From alex.pulver at gmail.com Wed Mar 12 14:19:05 2008 From: alex.pulver at gmail.com (Alex) Date: Wed, 12 Mar 2008 11:19:05 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? Message-ID: Hi all, The subject says pretty much all, i would very appreciate an answer. I tried to search the various forums and groups, but didn't find any specific answer... Thanks, Alex. From godzillaismad at gmail.com Thu Mar 20 07:47:00 2008 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 20 Mar 2008 04:47:00 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> Message-ID: <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Thanks Ross and John for your help. I apologise for the code I posted earlier not being the full picture of what I was trying to achieve. I had instantiated multiple instances of elapseTime class and each of them gets called approximately the same time. Below is the updated code: import time import thread import Queue printq = Queue.Queue(0) class elapseTime: def __init__(self, name=''): self.name = name self.timeStamp = None self.checkTimeFlag = False thread.start_new_thread(self.elapsedTime, ()) def setTime(self, state): if state == 1: self.checkTimeFlag = True self.timeStamp = time.clock() else: self.checkTimeFlag = False def elapsedTime(self): prevTime = time.clock() while True: curTime = time.clock() timeDiff = (curTime - prevTime) if timeDiff < 0.0: printq.put_nowait('time.clock() has gone backward!!! Time Diff '+str(timeDiff)) if self.checkTimeFlag: if (curTime - self.timeStamp) > 1.0: printq.put_nowait(self.name+", actual Elapsed Time"+str(round(curTime-self.timeStamp, 3))) self.checkTimeFlag = False prevTime = curTime time.sleep(0.05) def printmgr(): while True: print printq.get(True) # Print thread thread.start_new_thread(printmgr, ()) objList = [] for i in range(10): objList.append(elapseTime("obj"+str(i))) while True: for i in range(len(objList)): objList[i].setTime(1) time.sleep(10) print When I run the above code long enough in the PC I see the 'time.clock() has gone backward!!!' statement being printed once in a while. I have been reading a thread about invoking time.clock() at close proximity caused the 'time warp' problem. John, the PC experiencing this problem is a single core Intel Celeron 1GHz, XP SP2. The PC at home is a AMD Dual Core XP SP2. From jeff at schwabcenter.com Thu Mar 13 00:33:52 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 12 Mar 2008 21:33:52 -0700 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: References: Message-ID: Alex wrote: > The subject says pretty much all, i would very appreciate an answer. I > tried to search the various forums and groups, but didn't find any > specific answer... I'd like an answer to this, too. In Perl, I mostly used it for one-liners, when a variable needed to be initialized to some non-default value; for example, perl -ple 'BEGIN { $sum = 42 } $sum += $_'. From jeff_barish at earthlink.net Thu Mar 6 11:18:18 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Thu, 06 Mar 2008 09:18:18 -0700 Subject: for-else References: Message-ID: Terry Reedy wrote: > A for-loop is equivalent to a while loop with the condition 'iterator is > not exhausted'. ?So do_else when that condition is false -- the iterator > is exhausted. I think that this is the most important statement in this thread. As others have expressed, I too found for-else surprising when I first encountered it. It made sense to me when I analogized for with if: for x in range(5): do_something() else: do_something_else() means do_something repeatedly when the condition (iterator not exhausted) is true and do_something_else when the condition is not true, just as if condition: do_something() else: do_something_else() means do_something once when the condition is true and do_something_else when the condition is not true. I find it elegant that Python does not introduce additional keywords to deal with situations that are comparable. -- Jeffrey Barish From magdoll at gmail.com Sun Mar 16 22:29:36 2008 From: magdoll at gmail.com (Magdoll) Date: Sun, 16 Mar 2008 19:29:36 -0700 (PDT) Subject: psyco class question Message-ID: <1e242f71-357c-4005-9f12-94acd2eddef6@e6g2000prf.googlegroups.com> I can't find a psyco mailing list that I can directly ask to (so point me to it if there is one), so I'm posting it here. I know very little about how types and classes work in python and this is probably why I'm having trouble. I wrote a class inheriting pysco.classes, and the class structure is like this: class Node(psyco.classes.psyobj): def __init__(self,a,b,c...): self.a = a self.b = b etc.... this all works very well and speeds up the code tremendously. But when I try to pickle it: from cPickle import * s = Node() f = open('test.pickle','w') dump(s,f) f.close() It gives me errors like: Traceback (most recent call last): File "y.py", line 13, in dump(a,f) File "/usr/lib/python2.5/pickle.py", line 1362, in dump Pickler(file, protocol).dump(obj) File "/usr/lib/python2.5/pickle.py", line 224, in dump self.save(obj) File "/usr/lib/python2.5/pickle.py", line 306, in save rv = reduce(self.proto) File "/usr/lib/python2.5/copy_reg.py", line 70, in _reduce_ex state = base(self) TypeError: default __new__ takes no parameters If I embed Node in some other structures (I actually used it as nodes in a networkx.XGraph()), the dumping doesn't give me errors but when I load the pickle I get errors saying that the state is not a dictionary. What is the cause of the error? Is it because psyco classes uses its own class types that can't be pickled or do I need to override something? Thanks in advance. Magdoll From gagsl-py2 at yahoo.com.ar Tue Mar 25 16:08:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 17:08:09 -0300 Subject: setattr what is the parent object? References: <005601c88ea8$9a936520$0600a8c0@laptop> Message-ID: En Tue, 25 Mar 2008 15:46:57 -0300, Jules Stevenson escribi?: > I'm trying to use setattr to dynamically name and layout gui wx widgets, > this is all fine and dandy until I've run up against something where I > simply don't know what the object is, please see the amended **don't > know** > in the following code. > > > class MyFrame2(wx.Frame): > > def __do_layout(self, mayaVars): > > main_boxSizer = wx.BoxSizer(wx.VERTICAL) > > for pDisplay in range(len(mayaVars.primary)): > > setattr=(**don't > know**,"r_gridBagSizer_"+mayaVars.primary[pDisplay], > wx.GridBagSizer(vgap=0, > hgap=0)) > > > Without all the dynamic gumpf, the statmement looks like this: > > > r_gridBagSizer = wx.GridBagSizer(vgap=0, hgap=0)) > > > All the other UI elements are created on 'self' but the sizers don't > seem to > 'belong' to anything - what should I use when this is the case? You don't have to save the sizer anywhere, but you have to call container.SetSizer(the_sizer) -- Gabriel Genellina From pavlovevidence at gmail.com Sat Mar 15 19:03:13 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Mar 2008 16:03:13 -0700 (PDT) Subject: Python and 3D References: Message-ID: <8a5eb3d6-7203-4d5e-8812-2c606e2bdf44@8g2000hsu.googlegroups.com> On Mar 15, 4:09 pm, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs What do you mean by "manipulate". There are lots of ways to manipulate 3D objects; can you be more specific? Carl Banks From sam_spam_cat at verizon.net Sat Mar 29 19:09:28 2008 From: sam_spam_cat at verizon.net (Sam the Cat) Date: Sat, 29 Mar 2008 16:09:28 -0700 Subject: html DOM Message-ID: Is there a package that would allow me the same or similar functionality for modifying html code via the DOM model as I have in JavaScript ? I'd like to parse an html file, then modify it and save the result. I am not trying to do this online, rather I would like to do this on a batch of files stored on my hard drive. I have found several packages that allow me to parse and dissect html but none that allow me to modify the object and save the results -- perhaps I am overlooking the obvious From mail at timgolden.me.uk Tue Mar 25 09:44:04 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Mar 2008 13:44:04 +0000 Subject: Reading new mail from outlook In-Reply-To: <315315.36624.qm@web50108.mail.re2.yahoo.com> References: <315315.36624.qm@web50108.mail.re2.yahoo.com> Message-ID: <47E901A4.6020108@timgolden.me.uk> SPJ wrote: > I am trying to create new tickets in the ticketing system using python. When I > receive new email from a particular address, I have to trigger the python script > and parse the mail in required format. > > The main hurdle here is, how to invoke the script on arrival of new mail? I > checked the outlook settings and found that it supports only microsoft VB script > and Jscript. Is there any other way? I mean, if I make a daemon, how will it be > notified of new mail? Is there any python module that does this? > > I am not sure if this is the right place to ask this, since it is also a > microsoft related question. But any help is appreciated. Outlook does have some events in its automation interface (which you can handle from within Python by using win32com.client.DispatchWithEvents) but if an immediate response weren't critical it's probably slightly easier to schedule a job to interrogate the mailbox every so often and harvest any new emails. Depends on your particular need. TJG From tms at zeetix.com Mon Mar 17 08:48:38 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Mon, 17 Mar 2008 08:48:38 -0400 Subject: python-list Metaquestion Message-ID: <00d901c8882d$38c77240$0200a8c0@TMSMAIN> I continue to receive emails, addressed to python-list-bounces at python.org, with subject: "Re: Your message to Python-list awaits moderator approval", which read: > Your mail to 'Python-list' with the subject > > (no subject) > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Message has a suspicious header I'm happy to adjust my headers in whatever way is needed, if I know what the problem is. Is there FAQ somewhere that tells me what I should change? Thx, Tom From castironpi at gmail.com Wed Mar 5 21:06:23 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 18:06:23 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> Message-ID: <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> On Mar 5, 4:25?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote: > > Classes and modules are really similar. ?In Python they're really > > *really* similar. > > Yes they are. > > Both are namespaces. The very last line of the Zen of Python says: > Namespaces are one honking great idea -- let's do more of those! Where to begin? From matt at vazor.com Fri Mar 14 18:43:31 2008 From: matt at vazor.com (Matt) Date: Fri, 14 Mar 2008 15:43:31 -0700 (PDT) Subject: How to get number of compressed bytes from GzipFile Message-ID: Hi all, I'm using the gzip module to return a gzip response from a small python httpserver. I'd like to know the number of bytes written to the underlying socket, but it doesn't seem to support the tell() function. This works fine for a file: [15:39:51] mattb ~ $ cat mygzip.py #!/usr/bin/env python import os import gzip f = open("tmp.gz", "wb") gz = gzip.GzipFile('', 'wb', 6, f) for i in xrange(100): gz.write('abcdefg' * 100) gz.flush() print gz.tell() print f.tell() gz.close() f.close() print os.stat('tmp.gz').st_size [15:40:17] mattb ~ $ ./mygzip.py 70000 141 151 So I wrote 70000 raw bytes which gets compressed to 151 bytes -- I guess the 10-byte difference is a gzip header or something? Is there any way to get this same functionality when using a socket? thx Matt From http Sun Mar 23 00:39:13 2008 From: http (Paul Rubin) Date: 22 Mar 2008 21:39:13 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <7xprtmnjf2.fsf@ruckus.brouhaha.com> jmDesktop writes: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. I guess I should ask what is being taught and what the interests of the students are. I.e. is it a programming class for students interested in programming? If yes, then sure, why not Python. If not, then hmmm. From bbxx789_05ss at yahoo.com Tue Mar 18 00:18:37 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 17 Mar 2008 21:18:37 -0700 (PDT) Subject: ord function problem from newbie References: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> Message-ID: David.J.Anderso... at gmail.com wrote: > I convert all to lowercase, > > import string > > small = string.lower(name) > print "Here is the calculated value:" > > print small > for ch in small: > v = ord(ch)-96 > print v > I don't know if you are using an out of date book or what, but generally you are not going to be importing string. For example, my_str = "HELLO" small = my_str.lower() print small --output:-- hello From rbossy at jouy.inra.fr Sat Mar 8 09:09:20 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 08 Mar 2008 15:09:20 +0100 Subject: DOM parsing not working! In-Reply-To: <2b54d4370803071639w30912a60i4bc93981533ecfbb@mail.gmail.com> References: <2b54d4370803071639w30912a60i4bc93981533ecfbb@mail.gmail.com> Message-ID: <1204985360.47d29e10915a6@www.jouy.inra.fr> Quoting Mike D <42flicks at gmail.com>: > Hello, I've spent the morning trying to parse a simple xml file and have the > following: > import sys > from xml.dom import minidom > > doc=minidom.parse('topstories.xml') > > items = doc.getElementsByTagName("item") > text='' > for i in items: > t = i.firstChild > print t.nodeName > if t.nodeType == t.TEXT_NODE: > print "TEXT_NODE" > print t.nodeValue > text += t.data > > print text > > I can't figure out how to print the text value for a text node type. There > must be something obvious I'm missing, any suggestions? Yes quite a trivial thing. t is assigned to the first child node of which, in your example, is a text node containg just a newline. It will be shown if you replace your print statements with something like: print 't.nodeValue:', t.nodeValue, '### end of t.nodeValue' ... print 'text:', text, '### end of text' What is that you're trying to do? Do you want to extract all text nodes inside ? RB From gherron at islandtraining.com Sat Mar 22 11:51:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 22 Mar 2008 08:51:52 -0700 Subject: NameError: name 'guess' is not defined In-Reply-To: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> References: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> Message-ID: <47E52B18.9090500@islandtraining.com> willkab6 at gmail.com wrote: > I am very new to both programming and Pyhton and while trying to do > some practice using A byte of python an Error pops up on the IDLE > shell. I am using windows XP. PLease see below. > while running: > guess = int(raw_input('Enter an integer : ')) > > if guess == number: > print 'Congratulations, you guessed it.' > running = False # this causes the while loop to stop > elif guess < number: > print 'No, it is a little higher than that.' > else: > print 'No, it is a little lower than that.' > else: > print 'The while loop is over.' > # Do anything else you want to do here > > print 'Done' > > After typing the above as the book says, I get the error NameError: > name 'guess' is not defined > What Am I doing wrong? > You are not describing the problem accurately. The above program would not even start *running*. It would produce an IndentationError: expected an indented block on the second line. If you did manage to get the to get the program entered with correct indentation, it would gave a NameError on the variable named running not on guess. So now: Tell us what really happened, and perhaps your question can be answered. Hint: Each of the lines that end in a colon start a block of code which must be indented. Any variable used in a calculation must be given a value *before* the calculation is carried out. I think this might be what you were trying to do (untested): number = 12345 # Defines the number variable before using while True: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' break # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that.' else: print 'No, it is a little lower than that.' print 'The while loop is over.' print 'Done' Gary Herron From castironpi at gmail.com Wed Mar 12 02:01:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:01:54 -0700 (PDT) Subject: base-class call decorator Message-ID: <7b190526-9eb5-43b5-8f2a-7d1f5ac1ea58@u69g2000hse.googlegroups.com> If you had this, class KType( BaseType ): def __init__( self, *ar, **kwar ): self.setProp= True BaseType.__init__( self, *ar, **kwar ) a lot, and wanted a decorator, what would it be? What are the pros and cons? class KType( BaseType ): @basecall def __init__( self ): self.setProp= True What about calling first vs. last, base class order, certain bases, etc.? When is it easier to do without? From dave_mikesell at fastmail.fm Fri Mar 7 23:04:47 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Fri, 7 Mar 2008 20:04:47 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> On Mar 7, 10:31 am, "K Viltersten" wrote: > I've been recommended reading of:http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i > need to get elaborated. > > 1. When writing English, Strunk and > White apply. If your code needs so much descriptive prose that you have to consult Strunk and White, refactor it to be more clear. Excessive comments are the hobgoblin of overly complex and/or sloppy code. From stef.mientki at gmail.com Mon Mar 10 18:40:27 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 10 Mar 2008 23:40:27 +0100 Subject: wxPython: some help with Drag&Drop In-Reply-To: References: Message-ID: <47D5B8DB.1020402@gmail.com> Eric von Horst wrote: > Hi, > > I need some advice on Drag&Drop. > > What I want to achieve is the following: > - I have a window that is divided in two : on the left hand I > have a wx.TreeCtlr and on the other hand a wx.StaticBitmap > > I want to be able to drag an item from the tree onto the static > bitmap. > > I know how to do drag&drop in a treeCtrl but is there a way that I can > make the bitmap detect that something has been dropped on it? > > I would only need to know the name of the tree obj that was dropped on > the bitmap (and the location) > > Any help much appreciated > > As Mike said it might be better for you (and others bumping into this problem), if you would post your question in the wxPython list. Anyway here is mine solution, dragging from a tree on the left, either on the tree itself or on a visual disign canvas right of the splitter: def OnEndDrag2(self, event): item = event.GetItem() if item: # this is not a very elegant way, but it works # we compare the event-position with the splitter sash-position # to determine if it's a tree-drop or a graphical-canvas-drop w = self.parent_form.Splitter.GetSashPosition() x, y = event.GetPoint() if x > w: self.Insert_Lib_Object ( self.drag_item, x-w, y+26 ) else : cheers, Stef > > Erik > > From sjdevnull at yahoo.com Mon Mar 3 14:20:12 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 3 Mar 2008 11:20:12 -0800 (PST) Subject: Delete hidden files on unix References: Message-ID: <150e82e0-f142-4567-883f-9f0caedb9675@i12g2000prf.googlegroups.com> On Mar 3, 9:38 am, subeen wrote: > On Mar 3, 6:13 pm, Philipp Pagel > wrote: > > > > > loial wrote: > > > How can I delete hidden files on unix with python, i.e I want to do > > > equivalent of > > > rm .lock* > > > Here is one way to do it: > > > import os, glob > > for filename in glob.glob('.lock*'): > > os.unlink(filename) > > > Alternatively, you could also do this: > > > import os > > os.system('rm .lock*') > > > cu > > Philipp > > > -- > > Dr. Philipp Pagel > > Lehrstuhl f. Genomorientierte Bioinformatik > > Technische Universit?t M?nchenhttp://mips.gsf.de/staff/pagel > > Another way is to execute the linux command directly :) > Check here:http://love-python.blogspot.com/2008/02/execute-linux-commands-in-pyt... > Note that that can get dangerous with shell expansions: e.g. (don't run in a directory with files you want to keep!) import os open("--help", "w") os.system("rm *help") will actually run "rm --help", printing the help for rm rather than removing the file named "--help". There are a lot of security implications to allowing this kind of shell expansion of commands. The system-call method with os.unlink is easier to get right. From tmp1 at viltersten.com Sat Mar 1 08:36:42 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 14:36:42 +0100 Subject: SV: SV: Running test01.py under Windows (basic level) In-Reply-To: References: <62os33F2352veU1@mid.individual.net><62pfi6F244l0bU1@mid.individual.net> Message-ID: <62t3geF24ts4hU1@mid.individual.net> >>>> def bloppA (): >>>> print "a very advanced piece of code" >>> >>> go to File -> Open, open your saved file, >>> and use the Run menu (or press F5). >> >> When i try that i get this. >> >>>>> ====== RESTART ======= >>>>> >> >> And nothing more. Do i use wrong "print"?! > > You *defined* a function, but aren't *executing* > it. Append a line: > > bloppA() > > and try again. Rookie mistake. Thank you. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 06:05:39 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 12:05:39 +0100 Subject: Python COM automation - Controlling Microsoft Agent In-Reply-To: <0a998c60-fc33-4424-b5c7-65f4a2846e4d@i12g2000prf.googlegroups.com> References: <0a998c60-fc33-4424-b5c7-65f4a2846e4d@i12g2000prf.googlegroups.com> Message-ID: <47c93bb8$1$874$ba4acef3@news.orange.fr> Whaoouuu! A young newbie! Thanks... for others youngs newbies. From vvangelovski at gmail.com Wed Mar 12 11:32:59 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Wed, 12 Mar 2008 08:32:59 -0700 (PDT) Subject: C extensions question Message-ID: Let's say I write a simple extension in c only for the windows version of my script. Can I just put this compiled dll in the root directory of my application along with the other py files and distribute it like that without the need of an installation script? From sjmachin at lexicon.net Fri Mar 21 18:25:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 15:25:02 -0700 (PDT) Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> Message-ID: <05e369b9-ba75-488f-b58c-de437af2e1c5@d4g2000prg.googlegroups.com> On Mar 22, 8:51 am, Gabriel Genellina wrote: > If you drop this condition then you could fill the array with zeroes > as before, replace only the interesting ones with actual functions, > and write: > > for item in myarray[nonzero(myarray)]: > print item() if callable(item) else item > Let's unbuckle the seat belt :-) If "item" is definitely restricted to being either 0 or a callable object, then item() if item else 0 should give the same answer as, and is quite likely to be faster than, item() if callable(item) else item as it avoids a global lookup and a function call. Cheers, John From http Mon Mar 31 02:51:21 2008 From: http (Paul Rubin) Date: 30 Mar 2008 23:51:21 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> <65anbqF2fg18bU1@mid.individual.net> <87r6drjss4.fsf@physik.rwth-aachen.de> Message-ID: <7xfxu7s7x2.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > However, I'm quite sure that when Unicode has arrived almost > everywhere, some languages will start considering such characters in > their core syntax. Python 3.0 allows for Unicode letters in > identifiers, and there's still room for improvement. I agree. What's the codepoint for lower case lambda? From gagsl-py2 at yahoo.com.ar Mon Mar 24 13:45:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 14:45:52 -0300 Subject: Installing Mutagen Package On Windows References: Message-ID: En Mon, 24 Mar 2008 03:25:02 -0300, Benjamin Serrato escribi?: > Hey, I've run into another problem. I am trying to install the Mutagen > package to use as my first useful program, but can't figure out how to > install it on windows. The README says it is a simple application of-- > > Installing > ---------- > $ ./setup.py build > $ su -c "./setup.py install" > > --but I ran c:\>python c:\python25\tools\scripts\setup.py build and did > similarly for setup.py. I also added c:\python25 and > c:\python25\tools\scripts to my path, but this hasn't worked. I have The setup.by you have to run is the one included in the Mutagen package, not that one. Unless the author provides more specific instructions, the usual way is: - Unpack the archive into any temporary directory - Open a console (cmd) and change to that temporary directory (cd c:\some\temp\dir) - Execute this command: python setup.py install - That's all If you get any error, post the whole error message here, but for specific help on the package it would be better to contact the author directly. -- Gabriel Genellina From grante at visi.com Fri Mar 7 16:22:01 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Mar 2008 21:22:01 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> Message-ID: <13t3cfpo6d8d2ab@corp.supernews.com> On 2008-03-07, Steven D'Aprano wrote: > Professional typesetters, using proportional fonts, don't use double- > spaces because it throws off word spacing and line justification and just > plain looks ugly. They do, however, put more space between sentences than they do between words within a sentence. It is that practice which the "two spaces after a period" rule in typewriting is attempting to emulate. > I suppose that since coders typically use non- proportional > fonts, we can at least justify the use of two spaces with a > claim that it aids readability for "typewriter fonts" -- if > you believe such a thing, which I do not. My thumb has been putting two spaces after a period for 30 years, so the chances that it's going to change are rather slim. :) -- Grant Edwards grante Yow! A shapely CATHOLIC at SCHOOLGIRL is FIDGETING visi.com inside my costume.. From skip at pobox.com Wed Mar 19 11:44:05 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 19 Mar 2008 10:44:05 -0500 Subject: csv.Sniffer - delete in Python 3.0? Message-ID: <18401.13509.344107.988906@montanaro-dyndns-org.local> The csv module contains a Sniffer class which is supposed to deduce the delimiter and quote character as well as the presence or absence of a header in a sample taken from the start of a purported CSV file. I no longer remember who wrote it, and I've never been a big fan of it. It determines the delimiter based almost solely on character frequencies. It doesn't consider what the actual structure of a CSV file is or that delimiters and quote characters are almost always taken from the set of punctuation or whitespace characters. Consequently, it can cause some occasional head-scratching: >>> sample = """\ ... abc8def ... def8ghi ... ghi8jkl ... """ >>> import csv >>> d = csv.Sniffer().sniff(sample) >>> d.delimiter '8' >>> sample = """\ ... a8bcdef ... ab8cdef ... abc8def ... abcd8ef ... """ >>> d = csv.Sniffer().sniff(sample) >>> d.delimiter 'f' It's not clear to me that people use letters or digits very often as delimiters. Both samples above probably represent data from single-column files, not double-column files with '8' or 'f' as the delimiter. I would be happy to get rid of it in 3.0, but I'm also aware that some people use it. I'd like feedback from the Python community about this. If I removed it is there someone out there who wants it badly enough to maintain it in PyPI? Thanks, -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From lists at cheimes.de Wed Mar 19 16:30:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 Mar 2008 21:30:57 +0100 Subject: Improving datetime In-Reply-To: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> Message-ID: <47E17801.606@cheimes.de> Nicholas F. Fabry schrieb: > This is a query for information as to how to proceed. I am not a > professional programmer, but I use Python a great deal to help me in > my main job, which involves designing schedules for a global airline. > As such, I use datetime (and dateutil) extensively, and after much > use, I have come to some conclusions about their utility, and how to > improve them. Some of these changes are quite minor and would result > in a large increase in utility (low hanging fruit), while some changes > are major, and would result in less obvious benefits - but these > changes would increase the 'Python Zen' of them. > > So - where should I propose these changes? Here? python-dev? Should > I write up a full PEP or should I just give a more informal outline > with code samples? I would volunteer to help maintain/improve > datetime, but I don't speak C at all, unfortunately, and datetime > appears to be in C. Please write a detailed but not too long proposal to the Python ideas mailing list. The proposal should explain how you like to improve the datetime module. But *please* don't write a novel. You'll get more attention when the signal to noise ratio is high. A bullet list of features is easier to read than a long text block. I'm a core developer and I may be interested in mentoring your proposal. I can guide you through the process, review code and commit it. Yes, the datetime module is written in C. But we may move the C code to _datetime and create a facade module in Python. Christian From python at rcn.com Sun Mar 9 13:36:40 2008 From: python at rcn.com (Raymond Hettinger) Date: Sun, 9 Mar 2008 10:36:40 -0700 (PDT) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> <54abf8a6-6156-4663-903c-eb761e6b5148@h11g2000prf.googlegroups.com> Message-ID: <4a984680-c2c9-4230-8072-18c6fb6aa4e9@e6g2000prf.googlegroups.com> > > The intern() builtin uses this approach: > > > ? ?interned = {} > > ? ?def intern(s): > > ? ? ? ? if s in interned: > > ? ? ? ? ? ? return interned[s] > > ? ? ? ? interned[s] = s > > ? ? ? ? return s > > If you've seen it before, and have the old one, return the old one. > Do I have this straight? Right. From kyosohma at gmail.com Fri Mar 21 10:36:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 21 Mar 2008 07:36:11 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <61abe4dd-d300-43b3-bf70-e09d50a14344@u10g2000prn.googlegroups.com> On Mar 21, 6:48 am, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > > /fkallgren You could create an update script that compares the md5 (or some other) hash of the files for differences, kill the program if there is a difference and do the copy. I don't understand why you can do it from the server. I basically do the same thing from my workstation when I update one of my programs. To kill the process on a remote PC, I do the following: import subprocess subprocess.Popen('taskkill /s %s /im processName' % computer_name) I actually don't restart mine since it will be started when the user logs on. So I'll leave that to you. Of course, my program is made into an executable, but it should work the same. Maybe that will give you some ideas anyway. Mike From python.list at tim.thechases.com Thu Mar 6 14:39:38 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 06 Mar 2008 13:39:38 -0600 Subject: Exploring Attributes and Methods In-Reply-To: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: <47D0487A.1060409@tim.thechases.com> > Class Sample: > fullname = 'Something' > > How can I know that this class has an attribute called 'fullname'? with the builtin hasattr() function :) >>> class Sample: fullname='Something' ... >>> hasattr(Sample, 'fullname') True -tkc From sluggoster at gmail.com Tue Mar 18 13:49:26 2008 From: sluggoster at gmail.com (Mike Orr) Date: Tue, 18 Mar 2008 10:49:26 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <29b0d6d3-93e9-4c85-b7e9-6e30f4eb0e2f@x41g2000hsb.googlegroups.com> On Mar 16, 6:10 am, Bruce Eckel wrote: vendors: > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. We introduced sponsor lighting talks last year. This year it got out of hand because there were twice as many sponsors. By the time the Lightning Talk coordinators realized this, the sponsors had already been promised a priority talk so we couldn't back out of it. So it was a lack of foresight, not some commercial plot. Next year we (the Lightning Talk coordinators) have recommended either not having sponsor lighting talks, or moving them to a separate (non- plenary) session. The vendor exhibition was much bigger this year, and I think that's an adequate replacement for sponsor lighting talks. If there are sufficient Open Space rooms, they can also create their own session. > At first the morning plenary sessions -- where the entire conference > audience was in a single room -- just seemed a bit commercial. But > then I slowly figured out that the so-called "diamond keynotes" were > actually sold to vendors. It must have sounded great to some I liked the mini-keynotes and I don't think they detracted from the main keynotes. I did know what "diamond" meant so I knew they were sponsor talks. I guess that should be clearer on the schedule. > What was supremely frustrating was discovering that the people wanting > to give REAL lightning talks had been pushed off the end of the list The worst part of scheduling Lighting Talks is there's always more interesting speakers than time. This seems to be an insolvable problem. The main problem I had at PyCon this year was the number of talk I wanted to see that were scheduled at the same time as other talks I wanted to see. The highlight was the number of Open Space rooms and events. I didn't attend any of these, but they seemed unusually lively this year. > On top of that, the quality of the presentations was unusually low. I did feel that. An advanced track would be a good idea. Because you do need to repeat stuff for the newbies. At least 30% of the attendees were at PyCon for the first time. --Mike From pavlovevidence at gmail.com Wed Mar 12 21:37:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 18:37:10 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> Message-ID: On Mar 12, 8:11 pm, Justus Schwabedal wrote: > What do you need it for anyway? I just read about it and I think it's > useless > in python. Perl, like Python, has a separate compilation and run times. One day, someone who was trying to use Perl for something asked, "You know, wouldn't it be neat-o if you could execute some Perl code *before* you compiled the script?" And so (since that's usually enough reason to add something to Perl) was borne the BEGIN block. I believe the official rationale was that they wanted to add some magic variables that affected Perl's compilation and couldn't do it without a magic block that executed at compile time. Python solved a similar problem by introducing __future__ imports. Carl Banks From roygeorget at gmail.com Thu Mar 20 02:06:44 2008 From: roygeorget at gmail.com (royG) Date: Wed, 19 Mar 2008 23:06:44 -0700 (PDT) Subject: dividing tuple elements with an int or float Message-ID: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> hi i am trying to resize some images.First i'd read the size as a 2 tuple and then i want to divide it by 2 or 4 or 2.5 etc.. suppose origsz=(400,300) i want to divide the origsize by 2.5 so i can resize to (160,120) scale=2.5 how can i get the newsz? obviously origsz/2.5 won't work .. thanks RG From tmp1 at viltersten.com Tue Mar 4 15:00:23 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Tue, 4 Mar 2008 21:00:23 +0100 Subject: SV: Polymorphism using constructors In-Reply-To: <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> References: <6333v2F25lleoU1@mid.individual.net> <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> Message-ID: <635n43F25ruecU1@mid.individual.net> "Carl Banks" skrev i meddelandet news:24adaf72-0c55-4a88-86d0-296363ead17f at s8g2000prg.googlegroups.com... > On Mar 3, 4:17 pm, Raymond Hettinger wrote: >> Since Python doesn't support having two methods with the same name, >> the usual solution is to provide alternative constructors using >> classmethod(): >> >> @classmethod >> def from_decimal(cls, d) >> sign, digits, exp = d.as_tuple() >> digits = int(''.join(map(str, digits))) >> if sign: >> digits = -digits >> if exp >= 0: >> return cls(digits * 10 ** exp) >> return cls(digits, 10 ** -exp) > > > Note that even some of Python's built in types (dict *cough*) > implement homemade function overloading. > > The OP wanted to write a constructor that could accept either a pair > of integers or a rational, there would be a good precedent for it. > > However, I would advise the OP to use the constructor only for the > most common arguments, and use classmethods for more obscure, less > common arguments (such as decimal or even float). OP understands and thanfully accepts the suggestion. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From pavlovevidence at gmail.com Sat Mar 8 17:42:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 8 Mar 2008 14:42:31 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <876ecbb3-5bfe-40bd-a1ff-102af8d19fbc@n77g2000hse.googlegroups.com> On Mar 8, 9:43 am, malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > x = q.get() > #process x to get zero or more y's > #for each y: > q.put(y) Why not just do it like that? With a few changes it'll work fine: while q: x = q.pop(0) for y in process(x): q.append(y) And consider collections.deque for q instead of a list, though it shouldn't make much of a difference if the queue remains small. Carl Banks From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 21:02:20 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 03:02:20 +0200 Subject: python ODF library? References: Message-ID: <65argsF2egmmlU1@mid.individual.net> Matias Surdi wrote: > Found it: > http://opendocumentfellowship.com/development/projects/odfpy While we're at it: This module seems to be centered around creating documents. Where could I possibly find information/examples on how to read an ODF spreadsheet using Python? Regards, Bj?rn -- BOFH excuse #394: Jupiter is aligned with Mars. From castironpi at gmail.com Wed Mar 5 21:03:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 18:03:28 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> Message-ID: On Mar 5, 5:31?pm, Grant Edwards wrote: > On 2008-03-05, castiro... at gmail.com wrote: > > Anyway, if (a,b) is a key in dictionary d, can it guarantee > > that (b,a) is also in it, and maps to the same object? Er... -specialized- dictionary d. > To solve that problem, Python provides the immutable > "frozenset" type: > > ? >>> s1 = frozenset((1,2)) > ? >>> s2 = frozenset((2,1)) > ? >>> s1 == s2 > ? True > ? >>> d = {s1: "hi there"} > ? >>> s1 in d > ? True > ? >>> s2 in d > ? True Ah. Perfect. With this, I can just call frozenset on keys in __setitem__ and __getitem__... (though at that, it may be easier verbatim*.) *loosely introduced terminology, roughly equivalent to 'spell it out by hand each time'**. **__delitem__ too. Only thing is, that's an extra check if 'key' is iterable. (Yes. I realize this is a little scattered... it's my belief it's intelligible by party X... if not stop now speak up.) Goal: assert d[1,2] is d[2,1] assert d[1] is d[1] assert d[a] is d[a] assert d[a,b] is d[b,a] Only problem is, if a is iterable, then its contents get hashed. I don't see the general way around this. a= SomeList( [ 1,2,3 ] ) b= SomeList( [ 1,2,3 ] ) assert a is not b d[a]= True assert b not in d #there's the hangup It is my loss that M. Roggisch plonks me-- I will be deprived of his perspective and contributions. From coolman.guron at gmail.com Mon Mar 24 09:57:56 2008 From: coolman.guron at gmail.com (binaryj) Date: Mon, 24 Mar 2008 06:57:56 -0700 (PDT) Subject: urllib leaves connections/sockets waiting. BIG problem!!! Message-ID: <62c0ec57-1355-43d8-a414-0767ccc0923a@s37g2000prg.googlegroups.com> hi i am using urllib2 to do some automated web thing. basically i hit on sites and check the price what they are offering for their product and then decide if i want to lower or increase my pricing.so in short i have to hit hundreds of sites!!!!! for the problem: ============= i run 20 threads all do the same stuff. (hit and run :) ) after around 10-15 hits(per thread) hits the thread does nothing. it freezes. slowely but STEADILY all the threads end up with the same fate :( i did some netstat and found out that the connecton(sockets) the program had opened are waiting the CLOSE_WAIT state !! netstat -t tcp 1 0 192.168.1.2:4882 host-blabla:www CLOSE_WAIT tcp 1 0 192.168.1.2:4884 host-blabla:www CLOSE_WAIT tcp 1 0 192.168.1.2:4375 host-blabla:www CLOSE_WAIT OUTPUT OF PROGRAM: THREAD: #Thread-2 getting price from webi-d 7511975 DONE !!! THREAD: #Thread-1 getting price from webi-d 4449152 DONE !!! THREAD: #Thread-2 getting price from webi-d 7466091 DONE !!! THREAD: #Thread-1 getting price from webi-d 8641914 DONE !!! THREAD: #Thread-2 getting price from webi-d 7745289 DONE !!! THREAD: #Thread-1 getting price from webi-d 6032442 DONE !!! THREAD: #Thread-2 getting price from webi-d 8149873 DONE !!! no-price-on-page error THREAD: #Thread-1 getting price from webi-d 5842934 DONE !!! no-price-on-page error THREAD: #Thread-2 getting price from webi-d 3385778 DONE !!! THREAD: #Thread-1 getting price from webi-d 4610122 DONE !!! THREAD: #Thread-2 getting price from webi-d 8641536 DONE !!! THREAD: #Thread-1 getting price from webi-d 4219935 DONE !!! ---------and thats it, it freezes. i have waited 1hr the sockets have not changed their states! :( please help :) From castironpi at gmail.com Wed Mar 5 23:23:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 20:23:45 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> Message-ID: On Mar 5, 8:03?pm, castiro... at gmail.com wrote: > On Mar 5, 5:31?pm, Grant Edwards wrote: > > > On 2008-03-05, castiro... at gmail.com wrote: > > > Anyway, if (a,b) is a key in dictionary d, can it guarantee > > > that (b,a) is also in it, and maps to the same object? > > Er... -specialized- dictionary d. > > > To solve that problem, Python provides the immutable > > "frozenset" type: > > > ? >>> s1 = frozenset((1,2)) > > ? >>> s2 = frozenset((2,1)) > > ? >>> s1 == s2 > > ? True > > ? >>> d = {s1: "hi there"} > > ? >>> s1 in d > > ? True > > ? >>> s2 in d > > ? True > > Ah. ?Perfect. ?With this, I can just call frozenset on keys in > __setitem__ and __getitem__... (though at that, it may be easier > verbatim*.) > a= SomeList( [ 1,2,3 ] ) > b= SomeList( [ 1,2,3 ] ) > assert a is not b > d[a]= True > assert b not in d > #there's the hangup *plonk* key is an iterable, just like the constructors to other collection. >>> 2 in d Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable Interface first? In YOUR face first! From MartinRinehart at gmail.com Wed Mar 26 08:00:52 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 26 Mar 2008 05:00:52 -0700 (PDT) Subject: Tkinter menus from keyboard Message-ID: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Tkinter defaults to, for example, Alt+f = File (if File is your first menu name starting with "f"). I'd like to assign my own letters and have them underscored, per the universal standard. Can this be done? From exarkun at divmod.com Tue Mar 11 12:10:14 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 11 Mar 2008 11:10:14 -0500 Subject: mulithreaded server In-Reply-To: <7c555afb-2df0-43f2-aa16-d1e48da1510a@e23g2000prf.googlegroups.com> Message-ID: <20080311161014.6859.1800705120.divmod.quotient.18021@ohm> On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit wrote: >import socket >import sys >import thread > >p=1 >PORT=11000 >BUFSIZE=1024 > >def getData(cSocket): > global stdoutlock,cSocketlock > while True: > cSocketlock.acquire() > data=cSocket.recv(BUFSIZE) > if data=='q': > data='client exited' > cSocket.close() > p=0 > cSocketlock.release() > stdoutlock.acquire() > stdout.write(data) > stdoutlock.release() > >def sendData(cSocket): > global stdoutlock,cSocketlock > while True: > stdoutlock.acquire() > data=raw_input('>>') > cSocketlock.acquire_lock() > if data=='q': > stdout.write('server exited') > stdout.release() > p=0 > cSocket.close() > sSocket.send(data) > sSocketlock.release() Could it be because `sSocketlock? here > > >stdout=sys.stdout >host='' >sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >sSocket.bind((host,PORT,)) >sSocket.listen(1) >#sSocketlock=thread.allocate_lock() is never bound since the line above here is commented out? >stdoutlock=thread.allocate_lock() >print 'waiting for connection' >cSocket,addr=sSocket.accept() >print 'connection from',addr >cSocketlock=thread.allocate_lock() >thread.start_new_thread(sendData,(cSocket,)) >thread.start_new_thread(getData,(cSocket,)) >if p==0: > sSocket.close() > > > >In the above program, why there is an unhandeled exception ??? Just a guess. You should really include the traceback when you ask a question like this. Jean-Paul From mnordhoff at mattnordhoff.com Sat Mar 15 14:59:38 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 15 Mar 2008 18:59:38 +0000 Subject: Unicode/UTF-8 confusion In-Reply-To: References: Message-ID: <47DC1C9A.2050201@mattnordhoff.com> Tom Stambaugh wrote: > I'm still confused about this, even after days of hacking at it. It's > time I asked for help. I understand that each of you knows more about > Python, Javascript, unicode, and programming than me, and I understand > that each of you has a higher SAT score than me. So please try and be > gentle with your responses. > > I use simplejson to serialize html strings that the server is delivering > to a browser. Since the apostrophe is a string terminator in javascript, > I need to escape any apostrophe embedded in the html. > > Just to be clear, the specific unicode character I'm struggling with is > described in Python as: > u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for > example, http://www.fileformat.info/info/unicode/char/0027/index.htm) > of 0x27. > > This can be expressed in several common ways: > hex: 0x27 > Python literal: u"\u0027" > > Suppose I start with some test string that contains an embedded > apostrophe -- for example: u" ' ". I believe that the appropriate > json serialization of this is (presented as a list to eliminate notation > ambiguities): > > ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] > > This is a 14-character utf-8 serialization of the above test string. > > I know I can brute-force this, using something like the following: > def encode(aRawString): > aReplacement = ''.join(['\\', '0', '0', '2', '7']) > aCookedString = aRawString.replace("'", aReplacement) > answer = simplejson.dumps(aCookedString) > return answer > > I can't even make mailers let me *TYPE* a string literal for the > replacement string without trying to turn it into an HTML link! > > Anyway, I know that my "encode" function works, but it pains me to add > that "replace" call before *EVERY* invocation of the simplejson.dumps() > method. The reason I upgraded to 1.7.4 was to get the c-level speedup > routine now offered by simplejson -- yet the need to do this apostrophe > escaping seems to negate this advantage! Is there perhaps some > combination of dumps keyword arguments, python encode()/str() magic, or > something similar that accomplishes this same result? > > What is the highest-performance way to get simplejson to emit the > desired serialization of the given test string? simplejson handles all necessary escaping of stuff like quotes... -- From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 10:07:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 14:07:48 -0000 Subject: On copying arrays References: Message-ID: <13ufddkkaunaf5a@corp.supernews.com> On Mon, 24 Mar 2008 09:52:21 +0000, Duncan Booth wrote: > The method usually recommended is: > > best = list(test) > > as it has no side effects In general, you can't assume *anything* in Python has no side effects, unless you know what sort of object is being operated on. Here's an example that changes the value of test: >>> test = iter((1, 2, 3, 4, 5, 6)) >>> best = list(test) >>> best [1, 2, 3, 4, 5, 6] >>> another = list(test) >>> another [] And here's an example that has a rather obvious side-effect: >>> class Foo(object): ... def __getitem__(self, n): ... if n == 3: print "I'm in ur puter, deletin ur files" ... if 0 <= n < 6: return n+1 ... raise IndexError ... >>> test = Foo() >>> best = list(test) I'm in ur puter, deletin ur files >>> best [1, 2, 3, 4, 5, 6] -- Steven From MartinRinehart at gmail.com Fri Mar 7 16:42:56 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 7 Mar 2008 13:42:56 -0800 (PST) Subject: Better grammar.txt References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: Jeroen Ruigrok van der Werven wrote: > >http://www.martinrinehart.com/articles/python-grammar.html: > >Unknown host www.martinrinehart.com > > Works for me. Very interesting. The link I posted works for me, while the links quoted are 404 errors, though they look identical. This really is a superior version of the EBNF, so I wish it would work for everyone. Any ideas? From roger.dahlstrom at gmail.com Mon Mar 31 10:25:55 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 31 Mar 2008 07:25:55 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: <6551c86f-4537-4395-ae18-364fc83147b2@b64g2000hsa.googlegroups.com> On Mar 31, 10:22 am, rdahlstrom wrote: > So I have a 64 bit Windows 2003 system, running python 2.5.1.1. > > I can import a Windows .dll (msvcrt or whatever) using ctypes, but > when attempting to import another application-specific .dll (tibrv.dll > if anyone is familiar with it), I receive the error WindowsError: > [Error 193] %1 is not a valid Win32 application. > > I know there's a Windows on Windows (wow) which allows 32 bit > processes to run on 64 bit windows - is there a way to work this in > somehow? Maybe I'm barking up the wrong tree? > > Code is simple, and works on 32 bit systems no > > from ctypes import * > #this doesn't work > tibrv = cdll.tibrv > #this does work > msvcrt = cdll.msvcrt And by "works on 32 bit systems no", I mean "works on 32 bit systems no problem." From jgodoy at gmail.com Sun Mar 2 11:49:42 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 02 Mar 2008 13:49:42 -0300 Subject: Problem with the strip string method References: Message-ID: Colin J. Williams wrote: > Return a copy of the string with the > leading and trailing characters removed. ^^^^^^^^^^^^^^^^^^^^ > Only the last two examples below behave > as expected. They all looks OK to me. > [Dbg]>>> 'ab$%\n\rcd'.strip('%') > 'ab$%\n\rcd' No "%" at the beginning or end of string. Nothing changed. > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%\n\rcd' No "$" at the beginning or end of string. Nothing changed. I believe that you didn't copy this from the standard input due to the presence of "\r\n" on the answer... > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%cd' No "$" at the beginning or end of string. Nothing changed. > [Dbg]>>> ' ab$%cd '.strip('$') > ' ab$%cd ' No "$" at the beginning or end of string. Nothing changed. > [Dbg]>>> ' ab$%cd '.strip('%') > ' ab$%cd ' No "%" at the beginning or end of string. Nothing changed. From drobinow at gmail.com Wed Mar 12 23:07:57 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Wed, 12 Mar 2008 20:07:57 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: On Mar 12, 7:37 am, "k.i.n.g." wrote: > We use dd command in Linux to create a file with of required size. If you just want to get your work done, you might consider the cygwin dd command. Learning to write python is a worthwhile endeavour in any case. From fakeaddress at nowhere.org Thu Mar 6 15:05:24 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 20:05:24 GMT Subject: Python CGI & Webpage with an Image In-Reply-To: <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> Message-ID: <88Yzj.19022$R84.2998@newssvr25.news.prodigy.net> rodmc wrote: > [...] I have played around a bit more > so that both the image and HTML file are in the public_html folder. > They are called via python using a relative URL, and have permissions > set to 755. Within the HTML file the image is accessed using just > "banner.jpg". The actual page displays ok except for the image - so it > has the same problem as before. However when the same page is > displayed without running through a CGI it displays perfectly. Is the cgi script in the same directory? The user's browser looks for the jpg relative to the URL it used to get the page, which in the case of the CGI script is the path to the script, not the path to the html file. If server logs are hard to get or read, try my runcgi.py script: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/550822 -- --Bryan From software at ginstrom.com Sun Mar 23 11:51:22 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 24 Mar 2008 00:51:22 +0900 Subject: Testing for an empty dictionary in Python In-Reply-To: <47e67a99$0$36364$742ec2ed@news.sonic.net> References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <079201c88cfd$be762f10$0203a8c0@MOUSE> > On Behalf Of John Nagle > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). I believe that the following is fairly efficient: >>> def dict_is_empty(D): for k in D: return False return True >>> dict_is_empty(dict(a=1)) False >>> dict_is_empty({}) True Regards, Ryan Ginstrom From darcy at druid.net Thu Mar 6 11:47:07 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 6 Mar 2008 11:47:07 -0500 Subject: Identifying messages in a thread (was: Please keep the full address) In-Reply-To: <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> References: <8763w094sy.fsf_-_@benfinney.id.au> <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> Message-ID: <20080306114707.a5462f26.darcy@druid.net> On Thu, 6 Mar 2008 07:58:06 -0800 (PST) Carl Banks wrote: > > I don't want to have to tag every thread. I just want to *plonk* > > certain posters. > > > > Anyway, I'll live with Google's failings I guess. > > Sounds like you need better filtering. > > A decent news filter should be able not only kill a poster, but also > all followups to that poster recursively. Actually, I am reading this as a mailing list and since I run Unix and procmail I am sure that I could set something up if it really starts to be annoying. So far the simple filters deal with all but a smattering of problem postings so I don't need to expend the time. -- 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 arnodel at googlemail.com Mon Mar 10 21:27:36 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Mar 2008 18:27:36 -0700 (PDT) Subject: TextWrapper keepking line breaks? References: Message-ID: On Mar 10, 11:31?pm, js wrote: > Hi list, > > Can I make TextWrapper keep line breaks in the text? > > For example, > > >>> s = "spam\nham" > >>> print wrap(s) > > spam > ham > > As far as I can tell, there seems no way to do this, > but before writing my own solution, I want to know whether > the solution already exists or not. > > Thanks. Don't know but you could write: >>> import textwrap >>> def wraplines(text): ... return '\n'.join(textwrap.fill(line) for line in text.split('\n')) ... >>> s = "spam\nham" >>> print wraplines(s) spam ham >>> HTH -- Arnaud From wahreviews at gmail.com Sat Mar 22 18:56:36 2008 From: wahreviews at gmail.com (Work from Home Secrets) Date: Sat, 22 Mar 2008 15:56:36 -0700 (PDT) Subject: Make Money Using Paypal Get Paid Instantly References: <4563a8f0-7f25-46d9-a039-e5cd5d11c523@i29g2000prf.googlegroups.com> Message-ID: > Interesting. What is being suggested here is against Paypal's > acceptable usage policy. Consult with a real person who has been > successful before you jump into a scam like this and above all, make > sure that person is going to be there to support you the whole way > whether you just need to ask a question from time to time or need a > great deal of help. > > http://workfromhomereviews.org/ * * * Do yourself a favor today! * * * Give yourself every advantage you deserve! * * * http://workfromhomereviews.org/stealth-money-maker.html * * * Make it a great one! From ggpolo at gmail.com Wed Mar 26 08:45:29 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 26 Mar 2008 09:45:29 -0300 Subject: Tkinter menus from keyboard In-Reply-To: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: 2008/3/26, MartinRinehart at gmail.com : > Tkinter defaults to, for example, Alt+f = File (if File is your first > menu name starting with "f"). > > I'd like to assign my own letters and have them underscored, per the > universal standard. Can this be done? > Set the underline option to the index of the desired letter > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 21 05:50:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Mar 2008 10:50:09 +0100 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> Message-ID: <47e384cb$0$567$426a74cc@news.free.fr> sam a ?crit : > Bruno Desthuilliers napisa?(a): > >> Most of the arguments in favor of prototypes seems to come to, mainly: >> 1/ it lets you customize behaviour on a per-object base >> 2/ it removes the mental overhead of inheritance, classes etc >> >> Point 1. is a non-problem in Python, since you can already add/replace >> methods on a per-objec basis (ok, with a couple restrictions wrt/ >> __magic__ methods and such). >> >> Point 2. is not (IMHO) such a problem in Python, where inheritance is >> mainly an implementation detail (it's not needed for polymorphic >> dispatch to work) and class hierarchy tend to be very flat, when they >> even exist. >> >> Mainly, Python's object system is actually quite close to javascript >> here. That is, you get more or less the same flexibility. And a couple >> of powerful features you don't have with javascript (like hooks in the >> attribute lookup mechanism), too. > > Thanks for precise opinion and spending your time. > > > I think that when you use statically typed language, than you have to > define classes, because compiler has to know what is allowed to do with > instances of that class. > > But when you use dynamically typed language, then classes are redundant, > because object is looked at when it is referenced. Dynamically typed > language needs only objects hierarchy and you can add properties > (methods, values) to that object during program execution. Dynamic typing does not necessarily imply that you can add properties of modify behaviour at runtime. Most dynamically typed languages let you do that, but that's still orthogonal. And FWIW, you could emulate this in static languages using a hashtable, functors, and a couple accessors (a la __getattr__/__setattr__). > In dynamically typed language when you create object A that is inherited > from another object B, than object A knows that B is his predecessor. So > when you reference A.prop, then prop is looked in A first, then in B, > then in predecessors of B, and so on. What you're describing here is the inheritance mechanism of Python. And could apply just as well to javascript prototype mechanism. A javascript object has a reference to it's prototype object - that you can customize, rebind etc -, a Python object has a reference to it's class object - that you can customise, rebind etc... Don't be fooled by the term "class" itself - it's meaning is totally different in a language like Python. I may be plain wrong here but I suspect you don't have a serious knowledge of Python's object model. From ivan.illarionov at gmail.com Tue Mar 18 19:49:05 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 18 Mar 2008 16:49:05 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> Message-ID: <4393b161-2f16-4a64-a5c2-0d99d64938fe@s37g2000prg.googlegroups.com> On Mar 19, 2:33 am, dave wrote: > First I want to say thank you all for your timely replies. This is all > good food for thought. I've been programming more many years, but fast > graphics rendering is new territory for me. > > I'm hoping to fine something like a buffer_blit, where I can set all > the pixels to change using basic operators, blit them all at once to a > pixel buffer, then swap the visible buffer. Ideally it will only > change the region of the pixel buffer that needs changing. > > Because I want layers, I would like to take advantage wherever > possible of the available hardware features. I.E. ideally I am hoping > that the layers can be textures in memory that get composited in > hardware onto the screen. Maybe this is wishful thinking though? > > I'm also thinking that maybe I can reduce the number of active layers > from N down to 3 - the active layer, the layers below it, and the > layers above it. Obviously only the active layer needs any sort of > sprite-like animations and it on this layer than response time is most > important. Having to layer the top layers ontop of it may also play a > factor but, as I suggested, I can merge them all together in one time > and then use the merged result to layer on top of the active layer. > > I'm a little nervous about going the C/C++ route. It's been a few > years since I used them, I'm new to Python, and jumping into coding > Python extensions with C/C++ is not particularly palatable (though > I'll do it if I have to.) > > > Any GUI toolkit will work if you find the low-level access > > to their image memory buffers. > > That's another new step for me. Any ideas where to start? Thanks! Some reading on fast 2d graphics: chapters 35-42 from http://www.byte.com/abrash/ and a lot of great stuff here: http://tog.acm.org/GraphicsGems/ From castironpi at gmail.com Mon Mar 10 05:48:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 02:48:17 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> > I believe Python automatically creates and caches int objects for 0-256, > so whenever you use them, they refer to the same exact objects. Since > ints are immutable, it doesn't matter. One of the biggest hits on start-up time, by the way. ;) From kaushikbarat at gmail.com Sat Mar 15 05:36:19 2008 From: kaushikbarat at gmail.com (kaush) Date: Sat, 15 Mar 2008 02:36:19 -0700 (PDT) Subject: ImportError while Embedding python in C References: <0e568278-c5b3-40d3-a172-7d1701510f50@s19g2000prg.googlegroups.com> Message-ID: <3961db36-de0a-434c-8e77-91dcd1936da1@s19g2000prg.googlegroups.com> On Mar 15, 2:10 am, kaush wrote: > Hi All, > > I have a simple python script saved to "test.py" as > > import os > import base64 > > def Testfunction(): > print "Hello World" > return > > Testfunction() > > I am trying to invoke this from a C program as follows > > int main(int argc, char* argv[]) > { > Py_Initialize(); > > PyObject* main_module = PyImport_AddModule("__main__"); > > PyObject* main_dict = PyModule_GetDict(main_module); > > FILE* file_1 = fopen(TestFile, "r"); > PyRun_AnyFile(file_1, TestFile); > > Py_Finalize(); > > return 0; > > } > > This fails with the error > > Traceback (most recent call last): > File "/home/kaushik/shadowFs/test.py", line 4, in > import base64 > File "/usr/local/lib/python2.5/base64.py", line 9, in > import struct > File "/usr/local/lib/python2.5/struct.py", line 30, in > from _struct import Struct, error > ImportError: /usr/local/lib/python2.5/lib-dynload/_struct.so: > undefined symbol: PyExc_TypeError > > I am able to run test.py successfully from the shell. > > What am i missing in importing the base64 library? > > Thanks, > Kaushik Adding the following link options during compilation solved the problem "-Xlinker -export-dynamic" Thanks, Kaushik From aahz at pythoncraft.com Fri Mar 7 11:39:51 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Mar 2008 08:39:51 -0800 Subject: OT: Failed saving throw References: Message-ID: In article , Aahz wrote: > >For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people >think we should build a tomb in his honor. ;-) ...and xkcd finally weighs in: http://xkcd.com/393/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From jeff at schwabcenter.com Sun Mar 2 17:11:24 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 14:11:24 -0800 Subject: First post from a Python newbiw In-Reply-To: References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: Christoph Zwerschke wrote: > Marc 'BlackJack' Rintsch schrieb: >> On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: >> >>> Apart from doing something like >>> a=[0,0,0] >>> b=[0,0,0] >>> c=[0,0,0] >>> d=[a,b,c] >>> >>> is there a better way of creating d?? >> >> a = [[0] * 3 for dummy in xrange(3)] Each element of a refers to a distinct array. > Why not simply [[0]*3]*3 ? All three elements of the result refer to the same array. From miki.tebeka at gmail.com Wed Mar 12 18:36:07 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 12 Mar 2008 15:36:07 -0700 (PDT) Subject: C extensions question References: Message-ID: Hello, > Let's say I write a simple extension in c only for the windows version > of my script. Can I just put this compiled dll in the root directory > of my application along with the other py files and distribute it like > that without the need of an installation script? Yes (current directory is always looked first in when loading DLLs). HTH, -- Miki http://pythonwise.blogspot.com From castironpi at gmail.com Tue Mar 18 16:54:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 13:54:19 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> <80b7cd63-a6f3-4521-adb1-93b6faab307e@e39g2000hsf.googlegroups.com> Message-ID: <760b50cd-fb84-4ecc-9961-ae49e725e416@v3g2000hsc.googlegroups.com> > > >>> Can I allocate a second console window, so I can place certain output > > >>> to that directly, and leave the original streams alone? ? > > > I've rather lost track of what you're trying to do, but I would > > second Gabriel's suggestion of the standard Windows method of > > debug output: using OutputDebugString. There's an example here: > > >http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugStrin... > > > and it shouldn't be too hard to wrap it in a file-like > > object for stderr-substitution use, say. > > > Obviously there are 1,001 other ways of doing IPC but since this > > one's ready-made you might as well use it. You can distinguish > > between different processes' outputs by virtue of the PID which > > is the first item on the mmap. > > > TJG > > I want a handle to another window. > > Create B with a command. > ?___ ? ___ > |A ?| |B ?| > |___| |___| > > B.stdin (the stdin to B).write( '?' ) > ?___ ? ___ > |A ?| |B? | > |___| |___| > > A.stdout.write( '*' ) > ?___ ? ___ > |A* | |B? | > |___| |___| This is a little weird. I visited your link, but couldn't make any sense of it, so I tried something else myself. I'm not even sure what it accomplishes, but if you're on a different tack or way ahead of me, that can happen. However, it might be closer than I think to what I want-- my next step is to CreateProcess in the separate executable... then try to merge in back into python and subprocess. Now I've tried: >>> p= Popen( '\\astdin.exe', creationflags= 16, stdin= PIPE ) >>> p.stdin.write( b'123\r\n' ) 5 and I get the message box (lower), but no ':' sentinel nor the output. However the p.stdin.write call still returns if I close the new console window and call it after. astdin.cpp: #include #include #include using namespace std; DWORD WINAPI ThreadProc( LPVOID ) { while (1) { Sleep( 1000 ); cout<< ':'; } } int main() { MessageBox( NULL, "none", NULL, 0 ); cout<< "Ok"<< endl; CreateThread( NULL, 0, ThreadProc, NULL, 0, NULL ); while (1) { string s; cin>> s; cout<< '>'; cout<< s; } return 0; } From gagsl-py2 at yahoo.com.ar Sat Mar 22 00:32:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 21:32:28 -0700 (PDT) Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> <05e369b9-ba75-488f-b58c-de437af2e1c5@d4g2000prg.googlegroups.com> Message-ID: On 21 mar, 19:25, John Machin wrote: > On Mar 22, 8:51 am, Gabriel Genellina wrote: > > > If you drop this condition then you could fill the array with zeroes > > as before, replace only the interesting ones with actual functions, > > and write: > > > for item in myarray[nonzero(myarray)]: > > ? ? print item() if callable(item) else item > > Let's unbuckle the seat belt :-) > > If "item" is definitely restricted to being either 0 or a callable > object, then > ? ? item() if item else 0 > should give the same answer as, and is quite likely to be faster than, > ? ? item() if callable(item) else item > as it avoids a global lookup and a function call. In that case, we could use a bare item() because nonzero would have filtered out all that zeroes. -- Gabriel Genellina From bockman at virgilio.it Wed Mar 5 05:34:14 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 5 Mar 2008 02:34:14 -0800 (PST) Subject: draining pipes simultaneously References: Message-ID: On 5 Mar, 10:33, "Dmitry Teslenko" wrote: > Hello! > Here's my implementation of a function that executes some command and > drains stdout/stderr invoking other functions for every line of > command output: > > def __execute2_drain_pipe(queue, pipe): > ? ? ? ? for line in pipe: > ? ? ? ? ? ? ? ? queue.put(line) > ? ? ? ? return > > def execute2(command, out_filter = None, err_filter = None): > ? ? ? ? p = subprocess.Popen(command , shell=True, stdin = subprocess.PIPE, \ > ? ? ? ? ? ? ? ? stdout = subprocess.PIPE, stderr = subprocess.PIPE, \ > ? ? ? ? ? ? ? ? env = os.environ) > > ? ? ? ? qo = Queue.Queue() > ? ? ? ? qe = Queue.Queue() > > ? ? ? ? to = threading.Thread(target = __execute2_drain_pipe, \ > ? ? ? ? ? ? ? ? args = (qo, p.stdout)) > ? ? ? ? to.start() > ? ? ? ? time.sleep(0) > ? ? ? ? te = threading.Thread(target = __execute2_drain_pipe, \ > ? ? ? ? ? ? ? ? args = (qe, p.stderr)) > ? ? ? ? te.start() > > ? ? ? ? while to.isAlive() or te.isAlive(): > ? ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? ? ? ? line = qo.get() > ? ? ? ? ? ? ? ? ? ? ? ? if out_filter: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? out_filter(line) > ? ? ? ? ? ? ? ? ? ? ? ? qo.task_done() > ? ? ? ? ? ? ? ? except Queue.Empty: > ? ? ? ? ? ? ? ? ? ? ? ? pass > > ? ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? ? ? ? line = qe.get() > ? ? ? ? ? ? ? ? ? ? ? ? if err_filter: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? err_filter(line) > ? ? ? ? ? ? ? ? ? ? ? ? qe.task_done() > ? ? ? ? ? ? ? ? except Queue.Empty: > ? ? ? ? ? ? ? ? ? ? ? ? pass > > ? ? ? ? to.join() > ? ? ? ? te.join() > ? ? ? ? return p.wait() > > Problem is my implementation is buggy and function hungs when there's > empty stdout/stderr. Can I have your feedback? The Queue.get method by default is blocking. The documentation is not 100% clear about that (maybe it should report the full python definition of the function parameters, which makes self-evident the default value) but if you do help(Queue.Queue) in a python shell you will see it. Hence, try using a timeout or a non-blocking get (but in case of a non blocking get you should add a delay in the loop, or you will poll the queues at naximum speed and maybe prevent the other threads from accessing them). Ciao ----- FB From python.list at tim.thechases.com Fri Mar 14 09:57:44 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Mar 2008 08:57:44 -0500 Subject: find string in file In-Reply-To: References: Message-ID: <47DA8458.4000300@tim.thechases.com> > I'm neophite about python, my target is to create a programa that > find a specific string in text file. > How can do it? >>> FNAME1 = 'has.txt' >>> FNAME2 = 'doesnt_have.txt' >>> TEXT = 'thing to search for' >>> TEXT in file(FNAME1).read() True >>> TEXT in file(FNAME2).read() False or that may not be what your teacher wants, but if you give the homework problem and what you've tried, we might be able to give you some more quality guidance. :) The above is *really* *bad* code...horribly suboptimal especially as files get large. It only returns a boolean value. You might prefer to enumerate the file's contents and, if any line contains the search-text, return that line offset without reading the rest of the file. -tkc From yhvh2000 at googlemail.com Mon Mar 10 13:02:17 2008 From: yhvh2000 at googlemail.com (yhvh) Date: Mon, 10 Mar 2008 10:02:17 -0700 (PDT) Subject: error/warning color customization in interactive console? References: <0cb7044d-4f20-4cf8-b08c-5a99543853bd@i29g2000prf.googlegroups.com> Message-ID: <1e752c2d-a34d-49a7-9fa0-093aad862fd1@d21g2000prf.googlegroups.com> I've just discovered ipython - An Enhanced Interactive Python, which among other things colorizes output including error codes From ken at seehart.com Sun Mar 23 21:52:12 2008 From: ken at seehart.com (Ken) Date: Sun, 23 Mar 2008 18:52:12 -0700 Subject: Does python hate cathy? In-Reply-To: <1206320551.3365.20.camel@localhost.localdomain> References: <1206320551.3365.20.camel@localhost.localdomain> Message-ID: <47E7094C.3010009@seehart.com> Yup, I think Carsten got it. Mystery solved! You could replace Person with self.__class__ instead of type(self) if Person is an old-style class (since the class won't be collected until after all the instances are collected (because each instance references it's class)). Note that when the name "Person" is set to None, the Person class has it's reference count reduced by one but it is not yet collected. Alternatively, if you name your locals to start with "_" (e.g. _cathy) you avoid this problem /"Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called."/ But in general, I have this to say: IMO __del__ should not be taught to beginners (other than to say "don't use __del__ yet; you have much to learn first young jedi"). It should always be put in the "advanced topics" section when included in beginning python books along with threads, process control, and extending/embedding. If you think you need it, you probably don't. It is an advanced concept that requires a basic understanding of garbage collection. Beginners shouldn't really have to know much about garbage collection. The whole point is that it is automatic. __del__ is particularly dangerous for experienced C++ programmers starting to learn Python. People look for analogies and when they see __del__ they think "destructor" which is sort of vaguely right, but completely wrong in practice. The practical difference is that in C++ you actually have to deal with implementing destructors all of the time, and you can't get very far as a C++ programmer without using them, whereas in python you almost never have to deal with destructors. In C++, destructors are usually predictable (in correct code), but in python code they are somewhat harder to predict because they are invoked implicitly at the whim of the python implementation. In practice you don't need to use __del__ unless you are doing something exotic like explicitly implementing your own memory model, or tuning resource allocation in a large system. If you are doing ordinary day-to-day programming don't even think about __del__. Ken Seehart Carsten Haese wrote: > On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > >> That's really weird... it's reproducible on Windows too. It doesn't >> make any sense why the name of the variable would make a difference. >> My guess is you hit some kind of obscure bug. >> > > This is not a bug, just an unexpected feature: > http://mail.python.org/pipermail/python-list/2005-January/304873.html > > What's happening is that at the end of the script, all objects in the > global namespace are set to None (in order to decrease their reference > count and trigger garbage collection). This happens in the order in > which the names appear as keys in the globals dictionary. It randomly > happens that "swaroop", "kalam", and "cath" all are hashed in front of > "Person", but "cathy" is hashed after "Person". > > Hence, if Catherine is named cath, Python "None's" all the instances > first and then the type last, and all is well. However, if Catherine is > called cathy, Person is set to None before cathy. Then, in the lookup of > the global name "Person" during cathy.__del__, Person is None, which > doesn't have a "population" attribute, causing the AttributeError. > > Possible workarounds are: > 1) Explicitly delete the global names for the instances before the > script runs out. > 2) Don't refer to the "Person" type by its global name in __del__, but > indirectly as type(self). (This requires Person to be a new-style class, > though.) > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat Mar 8 13:11:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 10:11:15 -0800 (PST) Subject: multiplication of lists of strings References: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> <47ce56e9$0$10738$426a34cc@news.free.fr> <564294c7-cd78-483e-9393-aad0092809f7@59g2000hsb.googlegroups.com> Message-ID: On Mar 8, 12:04?pm, castiro... at gmail.com wrote: > On Mar 5, 2:16?am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > castiro... at gmail.com a ?crit : > > (snip) > > > > That reminds me: ?Is there a generic 'relation' pattern/recipie, such > > > as finding a computer that's "paired" with multiple users, each of who > > > are "paired" with multiple computers, without maintaining dual- > > > associativity? > > > Yes : use a relational database. > > No performance hit. ?Can I write an ad hoc relational class structure? What do you think of this solution? http://jtauber.com/blog/2005/11/10/relational_python:_basic_class_for_relations/ http://www.google.com/search?hl=en&q=python+relational+class+-database From bj_666 at gmx.net Sun Mar 9 05:51:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Mar 2008 09:51:23 GMT Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> Message-ID: <63hq8rF27chv6U1@mid.uni-berlin.de> On Sun, 09 Mar 2008 01:42:01 -0800, vpalexander wrote: > I keep seeing destructor calls in wx for ad hoc dialogs and wonder if > this is required, and if so, why would normal gc flow not be good? Because there is no guarantee when `__del__()` is called or if it is called *at all*. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Tue Mar 25 16:47:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Mar 2008 07:47:06 +1100 Subject: My python interpreter became mad ! In-Reply-To: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> Message-ID: <47E964CA.4070603@lexicon.net> Furkan Kuru top-posted: > Most probably X-Spam added itself to your path. What is "X-Spam"? Added itself to Benjamin's path [not mine] in such a fashion that it is invoked when one does "import re"? > you should look at your PATH and PYTHONPATH environment variables. Most *IM*probably. Read the traceback: """ > > File "/etc/postfix/re.py", line 19, in ? > > m = re.match('(Spam)', mail) > > AttributeError: 'module' object has no attribute 'match' """ This is a classic case of a script (which does not guard against side effects (like spewing out gibberish) when imported instead of being executed) being given the same name as a Python-included module and being executed in the current directory and hence ends up importing itself. > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > wrote: > > On Mar 25, 10:05 pm, Benjamin Watine > wrote: > > Yes, my python interpreter seems to became mad ; or may be it's > me ! :) > > > > I'm trying to use re module to match text with regular > expression. In a > > first time, all works right. But since yesterday, I have a very > strange > > behaviour : > > > > $ python2.4 > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > Type "help", "copyright", "credits" or "license" for more > information. > > >>> import re > > X-Spam-Flag: YES [snip] > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/etc/postfix/re.py", line 19, in ? > > m = re.match('(Spam)', mail) > > AttributeError: 'module' object has no attribute 'match' > > >>> > > > > What's the hell ?? I'm just importing the re module. > > No you're not importing *the* re module. You're importing *an* re > module, the first one that is found. In this case: your own re.py. > Rename it. > From grflanagan at gmail.com Tue Mar 11 04:56:05 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 11 Mar 2008 01:56:05 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> Message-ID: On Mar 11, 6:21 am, royG wrote: > On Mar 10, 8:03 pm, Tim Chase wrote: > > > In Python2.5 (or 2.4 if you implement the any() function, ripped > > from the docs[1]), this could be rewritten to be a little more > > flexible...something like this (untested): > > that was quite a good lesson for a beginner like me.. > thanks guys > > in the version using glob() > > >path = os.path.normpath(os.path.join(folder, '*.txt')) > >lst = glob.glob(path) > > is it possible to check for more than one file extension? here i will > have to create two path variables like > path1 = os.path.normpath(os.path.join(folder, '*.txt')) > path2 = os.path.normpath(os.path.join(folder, '*.doc')) > > and then use glob separately.. > or is there another way? > I don't think you can match multiple patterns directly with glob, but `fnmatch` - the module used by glob to do check for matches - has a `translate` function which will convert a glob pattern to a regular expression (string). So you can do something along the lines of the following: --------------------------------------------- import os from fnmatch import translate import re d = '/tmp' patt1 = '*.log' patt2 = '*.ini' patterns = [patt1, patt2] rx = '|'.join(translate(p) for p in patterns) patt = re.compile(rx) for f in os.listdir(d): if patt.match(f): print f --------------------------------------------- hth Gerard From Lie.1296 at gmail.com Sun Mar 2 11:23:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 2 Mar 2008 08:23:13 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> Message-ID: <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> On Mar 2, 10:02 pm, Paul Rubin wrote: > Lie writes: > > Anyway, I don't think Python should > > work that way, because Python have a plan for numerical integration > > which would unify all numerical types into an apparent single type, > > which requires removal of operator's limitations. > > Well I think the idea is to have a hierarchy of nested numeric types, > not a single type. You hit the right note, but what I meant is the numeric type unification would make it _appear_ to consist of a single numeric type (yeah, I know it isn't actually, but what appears from outside isn't always what's inside). > > from __future import division > > a = 10 > > b = 5 > > c = a / b > > if c * b == a: print 'multiplication is inverse of division' > > Try with a=7, b=25 They should still compare true, but they don't. The reason why they don't is because of float's finite precision, which is not exactly what we're talking here since it doesn't change the fact that multiplication and division are inverse of each other. One way to handle this situation is to do an epsilon aware comparison (as should be done with any comparison involving floats), but I don't do it cause my intention is to clarify the real problem that multiplication is indeed inverse of division and I want to avoid obscuring that with the epsilon comparison. From craigm3604 at gmail.com Mon Mar 24 18:21:11 2008 From: craigm3604 at gmail.com (Craig) Date: Mon, 24 Mar 2008 15:21:11 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> Message-ID: <8fd0d8bd-c80a-4ec1-a70a-ea659a84413e@e6g2000prf.googlegroups.com> On Mar 24, 3:45 pm, Craig wrote: > On Mar 24, 12:27 pm, Craig wrote: > > > > > On Mar 23, 7:59 pm, Dennis Lee Bieber wrote: > > > > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig > > > declaimed the following in comp.lang.python: > > > > > This dll was designed to be used from either C or Visual Basic 6. > > > > > I have the declare statements for VB6, if that helps. > > > > Probably not that much -- I'd bet it's full of variant records > > > > > Based on the results I have so far (and I have tried MANY permutations > > > > like trying to use the LPSTR for SecKey and PriKey which are returned > > > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > > > instead of pointers. > > > > > For this, I try: > > > > LPSTR = c_char_p > > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > > > LPSTR] > > > > SrchKey = > > > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > > > \x00", 41) > > > > SecKey = create_string_buffer(41) > > > > SecKey.raw = "1234567890123456789012345678901234567890" > > > > PriKey = > > > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > > > 41) > > > > TypeDef = create_string_buffer(128) > > > > TypeDef.raw = "X".center(128, "X") > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > > and I get: > > > > Traceback (most recent call last): > > > > File "C:\temp\vbisam_test_2.py", line 158, in > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(S > > > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > > WindowsError: exception: access violation reading 0x3433322D > > > > > I notice that SecKey.raw starts with "1234" and the exception address > > > > is 0x3433322D, which is "432-". > > > > 0x2D is 4 less than the expected 0x31... > > > > > And, changing to: > > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > > > LPSTR] > > > > PriKey = create_string_buffer(41) > > > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > > I then get: > > > > Traceback (most recent call last): > > > > File "C:\temp\vbisam_test_2.py", line 159, in > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(S > > > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > > WindowsError: exception: access violation reading 0x4443423D > > > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > > > is 0x4443423D, which is "DBC=". > > > > ... and 0x3D is 4 less than the expected 0x41 > > > > Which leads me to suspect that BSTR are a structure, not a plain > > > string, in which the address given is supposed to be prefaced with a > > > length value. IOWs, something like: > > > > |----|--------------------------------------| > > > ^ ^ C-string data > > > | |Address to be passed > > > |(address - 4) to get to a length count field > > > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > > > (the URL is from HTTP through to the end, including .aspx) > > > > Creating such may not be difficult -- but passing it to the DLL > > > could be. I don't know if ctypes allows pointer arithmetic. > > > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > > > length prefix. > > > > The only mention of BSTR in the win32 extensions is in text that > > > implies that the win32 extension library takes care of converting > > > from/to BSTR and Python strings transparently -- but that won't work for > > > your third-party library I suspect. > > > > Might have to beg the author(s) of ctypes to add a BSTR type to the > > > list of those supported... as I can find no means of tweaking the > > > address computed by byref() to point somewhere into a structure rather > > > than the beginning of the structure. > > > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > > > >>> pk > > > 1373844 > > > >>> id(pk) > > > 18941724 > > > >>> ctypes.string_at(pk) > > > '1234567890' > > > >>> ctypes.string_at(pk-4, 20) > > > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > > Okay, the return value from SysAlloc... IS the integer representing > > > the address of a BSTR structure (IE, the address four bytes in from the > > > real memory start)... Note how backing up 4 bytes reveals the BSTR > > > length field > > > > What happens if you just pass that item as-is, no byref(), no > > > conversion to ctypes pointer types... > > > > PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > SecKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > > res = VmxGet( byref(hwmcb), > > > byref(SecIndex), > > > byref(Option), > > > byref(c_void_p(SrchKey)), > > > SecKey, > > > PriKey, > > > TypeDef ) > > > > >>> PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > >>> ctypes.string_at(PriKey, 41) > > > > "1234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'">>> ctypes.string_at(PriKey-4, 41+4) > > > > ")\x00\x00\x001234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'" > > > > >>> ord(")") > > > 41 > > > > You'll need to use the .string_at() or .wstring_at() functions to > > > extract any data changed by the call. Should not be a Python > > > immutability problem as all "you" allocated in Python is the integer > > > holding the address. You may need to call a Sys... function to free the > > > memory that had been allocated -- Python doesn't know about it. > > > -- > > > Wulfraed Dennis Lee Bieber KD6MOG > > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > > HTTP://wlfraed.home.netcom.com/ > > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > > HTTP://www.bestiaria.com/ > > > The VB6 Declare is: > > Declare Function VmxGet Lib "vbis5032.DLL" (DatasetHandle&, > > SecIndexField%, Options%, SelectorKey$, RSecondaryKey$, RPrimaryKey$, > > RRecordVariable As Any) As Integer > > > The only variant is the RRecordVariable, which is actually meant to be > > a Type structure. > > > Anyway, I thought maybe there was a clue in here that I am missing. > > > Back to Python. I ran with the following: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > > LPSTR] > > SrchKey = > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > \x00", 41) > > SecKey = > > windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", > > 41) > > PriKey = > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > 41) > > TypeDef = create_string_buffer(128) > > TypeDef.raw = "X".center(128, "X") > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) > > And, now I get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 156, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), SecKey, PriKey, TypeDef ) > > ctypes.ArgumentError: argument 5: : wrong > > type > > > So, now the problem is with: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > > LPSTR] > > I am not sure what to put for arguments 5 and 6 now. > > > I realized the need to release the BSTRs myself, and already included: > > windll.oleaut32.SysFreeString(SrchKey) > > windll.oleaut32.SysFreeString(SecKey) > > windll.oleaut32.SysFreeString(PriKey) > > at the end of the program. > > > I have no problem using .string_at() to extract the returned values - > > once the .argtypes let the call execute. > > > In case this helps, here is an excerpt from a C program that was > > provided with the dll: > > typedef struct tagMYREC > > { > > char name[51]; // 1 xref generated name key > > > char lastname[31]; // 2 last name > > char firstname[21]; // 3 first name > > char address[41]; // 4 address > > char city[31]; // 5 xref city key > > char state[3]; // 6 xref state > > char zip[11]; // 7 xref zip code > > char phone[21]; // 8 xref phone number > > BSTR notes; // 9 notes > > > } MYREC; > > typedef MYREC FAR * LPMYREC; > > > short rc; // return code (from VB/ISAM function calls) > > static HANDLE nDatasetNumber; > > static short cur_index; > > static short GetOpt; > > static BSTR Dummy; > > static BSTR Throwaway; > > static BSTR PrimaryKey; > > static MYREC myrec; > > > rc = VmxGet(&nDatasetNumber, // int DatasetNumber // VIS_BUSY ? > > &cur_index, // int SelectedIndex > > &GetOpt, // int OptionParameter > > &Dummy, // Don't need a Selector param with > > these options > > &Throwaway, // Don't need returned index entry in > > this case > > &PrimaryKey, // LPBSTR lpPriKey > > (void *) &myrec); // LPVOID lpRecordStructure > > > For someone who knows C and Python, this may provide a clue to the > > BSTR passing/return problem. > > I received two emails from Dennis, included below (for completeness): > ++++++++++++++++++++++++ Start of email #1 ++++++++++++++++++++++++ > I'm back at work, hence the email. > > -=-=-=-=-=-=- > So, now the problem is with: > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > LPSTR] > I am not sure what to put for arguments 5 and 6 now. > > I realized the need to release the BSTRs... > > read more >> I received an email from Dennis, which I have included below (for completeness): +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Last email; since I'm at the end of my analytical skills (lacking the library I can't perform tests of my own). Since the value being passed should have been the address of the BSTR structure (put a >> print "address = 0x%8.8X" % PriKey << just before the call), for it to claim it can't read 0x3433322D implies another layer of indirection in the library... in that it must have used the passed address to pick up the first four bytes of the string portion of the BSTR, and is then trying to treat /that/ as the address to what it expects to really be the BSTR (subtracting four from that to get to the expected length field). My last try therefor... Try changing the argtype to a pointer-to-long (or whatever pointer types have been defined). Then pass >> byref(c_int32(PriKey)) << (Have we gone full circle yet?) My hope is that, based upon the above evaluation, this final attempt will pass an address pointing TO the address stored in the c_int32, and that the library will use /that/ address to get to the BSTR itself. I'd also suggest that, just for safety, you hold onto a reference to the original allocations... Just in case the library really intends to allocate internally and change the pointer value being passed (you may need to encapsulate it outside of the library call: ci_PriKey = c_int32(PriKey) do library call: ... , byref(ci_PriKey), ... if ci_PriKey.value != PriKey: # you were returned a new buffer Don't forget to treat the other BSTR the same way... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ I would have gladly provided the dll in question if you had requested it. Anyway, I added the following, for completeness: LPLONG = POINTER(c_long) And, then: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPLONG, LPLONG, LPSTR] print "\nVmxGet test - looking for valid record..." printf ("Before - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(ci_SecKey), byref(ci_PriKey), TypeDef ) printf ("After - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) printf ("Record returned = \x22%s\x22\n", TypeDef.raw) printf (" Key returned = \x22%s\x22\n", string_at(ci_PriKey.value, 41)) printf ("2ndKey returned = \x22%s\x22\n", string_at(ci_SecKey.value, 41)) And this is what I got: VmxGet test - looking for valid record... Before - PriKey = 0x0044F56C, SecKey = 0x0044F534 ci_PriKey = 0x0044F56C, ci_SecKey = 0x0044F534 After - PriKey = 0x0044F56C, SecKey = 0x0044F534 ci_PriKey = 0x0043D49C, ci_SecKey = 0x0043D484 Record returned = "MSD19DN Testing Board Of E ducation 4 " Key returned = "MSD19DN" 2ndKey returned = "MSD19DN" PERFECT! Now, I just have to write some wrapper code and I should be able to turn this set of calls into a VB/ISAM object, that can then be instantiated for each file I need. Dennis, thank you very much for all of your wonderful contributions. From siona at chiark.greenend.org.uk Thu Mar 13 10:52:25 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Mar 2008 14:52:25 +0000 (GMT) Subject: Get cgi script to begin execution of another script... References: Message-ID: sophie_newbie wrote: >Basically I've a CGI script, that when executed by the user, I want to >call another script that does a very long running task (10 hours +) >and print a message on the screen saying that the user will be emailed >on completion of the very long task. The script executing the very >long task will then email the user on completion. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 was helpful to me in solving this problem. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From gagsl-py2 at yahoo.com.ar Tue Mar 25 01:49:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 02:49:01 -0300 Subject: Does python hate cathy? References: Message-ID: En Tue, 25 Mar 2008 02:09:58 -0300, Edward A. Falk escribi?: > However, Adding > > self.myclass = Person > > to the __init__() method didn't stop the problem. I thought it might, > because > then each of the objects would have held a reference to Person. > Actually, I would > have thought they'd hold a reference by merely existing, so is this not > a bug? Yes, they already have a reference (self.__class__). The problem is that __del__ references Person by *name*, and that name is reset to None (like all other module globals) as part of the interpreter shutdown sequence. Using self.__class__ would avoid this particular bug, but in general, it's better not to rely on __del__ at all. See http://bugs.python.org/issue1513802 and http://bugs.python.org/issue1717900 -- Gabriel Genellina From dickinsm at gmail.com Wed Mar 12 13:25:50 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 12 Mar 2008 10:25:50 -0700 (PDT) Subject: ValueError in pickle module during unpickling a infinite float (python 2.5.2) References: <4b9d0896-df9c-47b6-98b6-16f825d67975@i7g2000prf.googlegroups.com> Message-ID: On Mar 12, 11:22 am, r... at iwm.mw.tu-dresden.de wrote: > Unpickling an infinite float caused a ValueError in the pickle module. > I need to pickle and load infinite floats in my project. Do you have > any suggestions how to solve the issue? Have you tried this on the recent 2.6 alpha (Python2.6a1)? It's available from http://www.python.org/download/releases/2.6/ I suspect it may already be fixed there. In any case, it would be useful if you could file a bug report at http://bugs.python.org. It's not absolutely clear to me that this constitutes a bug (though I think it does), but it would be worth having people look at it. I'm assuming that you're on Windows? I can't reproduce the problem on OS X. Mark From exarkun at divmod.com Thu Mar 27 10:44:24 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 27 Mar 2008 09:44:24 -0500 Subject: Psyco alternative In-Reply-To: <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: <20080327144424.6859.79559712.divmod.quotient.23555@ohm> On Thu, 27 Mar 2008 15:19:11 +0100, "Diez B. Roggisch" wrote: >> Ok, i know this. The one that i do not know, is if, let'say, in 2 >> years it will be ready for seriously development, PyPy will aim to >> "replace" CPython entirely ?? We are talking about an whole new >> distribution ? > >Most certainly not. It's the goal of each language to finally become >self-hosted, and I hope we see that for python. But that's nothing that >will happen anytime soon (soon being at least half a decade), and most >probably not for the 2.x-versions. PyPy is self-hosted and has been for some time (a year or so?). Maybe you're saying that PyPy won't replace CPython for at least five years? Could be; prediction is hard. ;) PyPy is between 1x and 3x slower than CPython for a lot of things, which isn't so much of a difference. A bigger obstacle is the availability of third-party extension modules which currently must be re-implemented in order to be available on PyPy. This could easily take half a decade without a full-time or otherwise concerted effort. Jean-Paul From diffuser78 at gmail.com Mon Mar 10 00:26:41 2008 From: diffuser78 at gmail.com (DanielJohnson) Date: Sun, 9 Mar 2008 21:26:41 -0700 (PDT) Subject: BitVector Message-ID: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Hi, I am trying to solve a genetic algorithm problem where I want to read a bitvector of very large size (say 10000) and manipulate bits based on certain algorithms. I am a newbie in Python. What data structure are good to read such huge data set. Are there any built in classes for bit fiddling. Every help is greatly appreciated, Thanks From brett at python.org Sun Mar 2 19:58:35 2008 From: brett at python.org (Brett Cannon) Date: Sun, 2 Mar 2008 16:58:35 -0800 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: On Sun, Mar 2, 2008 at 4:52 PM, Fred Drake wrote: > On Mar 2, 2008, at 7:43 PM, Fred Drake wrote: > > 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: > > > Neither does 2.3.7 now that I've tried that: > > gcc -u __dummy -u _PyMac_Error -framework System -framework > CoreServices -framework Foundation -o python.exe \ > Modules/python.o \ > libpython2.3.a -ldl > Undefined symbols: > "__dummy", referenced from: > ld: symbol(s) not found > collect2: ld returned 1 exit status > make: *** [python.exe] Error 1 > > Of course, I wasn't using an earlier 2.3.x version on this box. I > would really like to be able to use 2.4.5, since I've been using 2.4.4 > for work for a while now. For me on OS X 10.5.2 (gcc 4.0.1) for 2.37 I am getting a ton of: sem_post: Bad file descriptor sem_init: Function not implemented sem_trywait: Bad file descriptor -Brett From hniksic at xemacs.org Tue Mar 25 11:59:59 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Mar 2008 16:59:59 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: <87iqzaeqv4.fsf@mulj.homelinux.net> Brian Lane writes: > Basically, you can't do what you are trying to do without using a > different variable, ...or abusing the __foo private identifier trick. From mcohoon at gmail.com Sat Mar 15 16:35:10 2008 From: mcohoon at gmail.com (mpc) Date: Sat, 15 Mar 2008 13:35:10 -0700 (PDT) Subject: Python Generators Message-ID: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> HI all, I am trying to write a while loop that will iterate over generators to capture all the headers of FFCache directories. However, the generators embedded within the argument of another generator do not seem to re-initiate. the example below loops through and initiates the generator embedded in the argument only once. Can anyone explain while the generator will not re-initiate, and suggest a simple fix? #!/usr/bin/env python import os,struct,time def generate_headers(cachedir): for name, blocksize in cachefiles: pathname = os.path.join(cachedir,name) f = open(pathname,"rb") f.seek(4096) while True: header = f.read(36) if not header: break fields = struct.unpack(">9I",header) if fields[0] == 0x00010008: yield f, fields fp = f.tell() offset = fp % blocksize if offset: f.seek(blocksize - offset,1) f.close() def concatenate(sequences): for seq in sequences: for item in seq: yield item all_caches = (path for path,dirlist,filelist in os.walk("/Users/") if '_CACHE_MAP_' in filelist) cachefiles = [('_CACHE_001_',256),('_CACHE_002_',1024),('_CACHE_003_', 4096)] n = 0 while True: n += 1 time.sleep(0.5) headers = concatenate(generate_headers(path) for path in all_caches) for h in headers: print h,n # this doesn't work either while True: n += 1 time.sleep(0.5) for path in all_caches: headers = generate_headers(path) for h in headers: print h,n # however if I hard code the path path = "FFCache" while True: n += 1 headers = generate_headers(path) for h in headers: print h,n #but of course i do not wish to hard code the path. From johnmfisher at comcast.net Thu Mar 27 20:05:12 2008 From: johnmfisher at comcast.net (John Fisher) Date: Thu, 27 Mar 2008 17:05:12 -0700 Subject: keyboard "interrupt" References: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Message-ID: <1ieh0b3.iukc151nfftuiN%johnmfisher@comcast.net> Arnaud Delobelle wrote: > John Fisher wrote: > > Hi Group, > > Hi John > > > I have been absent a while, mainly because I have been getting better at > > figuring out my own Python problems. But not this one... > > > > I have a timed loop performing certain tasks until a total period of > > time has elapsed. I would like to be able to interrupt the loop or set > > various flags during execution via keyboard input. raw_input seems to > > just stop everything cold. I want the ability to just sacn the keyboard > > buffer and see if something is there, then proceed normally in the loop > > if there is no input in the buffer. Make sense? Totally easy? Let me > > know... > > If you are on a UNIX platform, you can use the curses module. > > http://docs.python.org/lib/module-curses.html > > There is a link there to a tutorial, but it seems to be broken. A > quick search finds it there: > > http://www.amk.ca/python/howto/curses/ > > HTH > > -- > Arnaud Thanks for your reply Arnaud. I am using an Intel mac, running Leopard 10.5.2, so that's Posix I warrant. I will check this out. JF From skip at pobox.com Thu Mar 27 11:25:01 2008 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Mar 2008 15:25:01 +0000 (UTC) Subject: Is subprocess.Popen completely broken? References: <16651e80803270805q399b1c17mec7703c0017cbac0@mail.gmail.com> Message-ID: Jerry Hill gmail.com> writes: > It's looking for an executable named "ls /tmp" Since it can't find > one, it raises an exception. > > If you just want to replace an os.system call, you need to pass > shell=True to Popen, like this: > proc = subprocess.Popen("ls /tmp", shell=True) > > That will get the shell to split your string into the program to be > called, and the argument(s) to the program. Alternatively, you can do > it yourself by passing a sequence to Popen: > proc = subprocess.Popen(["ls", "/tmp"]) Oh crap. Missing the comma... *sigh* Sometimes adjacent string literals can be silent killers. Sorry for the noise. Skip From grante at visi.com Fri Mar 28 18:01:57 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 22:01:57 -0000 Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> <7x4paqy0sr.fsf@ruckus.brouhaha.com> Message-ID: <13uqqml7sk05ec8@corp.supernews.com> On 2008-03-28, Paul Rubin wrote: > castironpi at gmail.com writes: >> Did everyone take the course on computer architecture? > > Yow! Does your SPEED QUEEN have CABLE? Ya know, I was thinking about trying to find an updated file of Zippy quotes for use in my .sig, but I decided that having all of the pop culture references be 30-years out of date was part of the charm. -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER? From userprogoogle-139 at yahoo.co.uk Wed Mar 5 09:47:25 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 5 Mar 2008 06:47:25 -0800 (PST) Subject: Python CGI & Webpage with an Image Message-ID: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> Hi, I have a set of CGI scripts set up and in one page (which is stored in an HTML file then printed via a python CGI) there is an image. However the image never displays, can anyone recommend a way round this problem? Kind regards, rod From stephenhorne100 at aol.com Mon Mar 17 10:13:45 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 07:13:45 -0700 (PDT) Subject: Python 3 and PEP238 division Message-ID: Is the PEP238 change to division going into Python 3 as planned? I realise that the new integer division semantics have been available in "from __future__" for quite a few years now, but a warning might be appropriate now that Python 3 is in alpha. A lot of people have probably either forgotten, or else never knew about PEP238. The following wording is still included in the Python 2.5.1 documentation... """ 3.1.1 Numbers The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example: >>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> 2+2 # and a comment on the same line as code 4 >>> (50-5*6)/4 5 >>> # Integer division returns the floor: ... 7/3 2 >>> 7/-3 -3 """ Which is interesting, since neither Pascal nor C division works like that. Pascal has a separate 'div' operator for integer division. C and C++ compilers usually round toward zero IIRC, but the rounding direction is not defined in the standards. In any case, after the final adoption of PEP238, integer division in Python will generally return float results - not the rounded-to-floor integer results shown here. It might be worth brainstorming some contexts where problems are likely to occur, to help anyone trying to prepare for the change. My contribution to that would be any code that needs to partition lists into slices. The obvious cases - binary searching, sorting - are covered by libraries which should be used in preference to hand- written code, but this kind of thing can happen elsewhere. I have some code that organises a sorted list of data into a balanced tree as part of a code generation task, for example, which relies on floor division. Also, if money amounts are stored as integer numbers of pennies (which they often are, since floats represent approximate values) problems could occur with various calculations since multiplication by a fractional quantity is often represented as a multiplication followed by a division. For example adding 5% is equivalent to multiplying by 1.05, or to multiplying by 105 then dividing by 100. The latter idiom is often used to keep everything integer, which requires division results to be rounded. Use of the decimal module is probably a good idea for money amounts these days, of course. I've not used it myself but the whole point of a decimal number type would be to get exact results and the kind of rounding behaviour that accountants would expect. The real world fix would normally be to replace the / operator with //, though, in order to keep the old floor-division semantics. From jzgoda at o2.usun.pl Tue Mar 18 06:40:34 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 18 Mar 2008 11:40:34 +0100 Subject: Get actual call signature? Message-ID: Say, I have a function defined as: def fun(arg_one, arg_two='x', arg_three=None): pass Is there any way to get actual arguments that will be effectively used when I call this function in various ways, like: fun(5) => [5, 'x', None] fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] fun(5, 'something') => [5, 'something', None] (et caetera, using all possible mixes of positional, keyword and default arguments) I'd like to wrap function definition with a decorator that intercepts not only passed arguments, but also defaults that will be actually used in execution. If this sounds not feasible (or is simply impossible), I'll happily throw this idea and look for another one. ;) -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From http Sat Mar 29 10:26:37 2008 From: http (Paul Rubin) Date: 29 Mar 2008 07:26:37 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <656vnpF2ekcsrU1@mid.uni-berlin.de> Message-ID: <7xve35a9nm.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > > I appreciate the droll sense of humor, but do you mean to > > assert that asyncore.py supports asynchronous disk file I/O? > > As I said in an answer to the OP, I somewhat glossed over the "file" > and just read IO. And under Posix, python *does* support asynchronous > IO using the select-module. Select does nonblocking i/o but I think Donn is interpreting "asynchronous i/o" as having a narrower meaning. See: http://www.ibm.com/developerworks/linux/library/l-async/ for some info. From luismgz at gmail.com Sat Mar 29 10:03:16 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sat, 29 Mar 2008 07:03:16 -0700 (PDT) Subject: Psyco alternative References: <10d4e6b6-71f3-4c22-8b13-17dd32a4374f@c19g2000prf.googlegroups.com> Message-ID: On 27 mar, 13:14, king kikapu wrote: > > One reason attention is going to PyPy instead of Psyco... > > > Jean-Paul > > I had a look at PyPy, it, indeed, have a very long way to go so we can > consider it an alternative. To see how it?s going, you can check this out: http://morepypy.blogspot.com/ From pistacchio at gmail.com Wed Mar 12 10:24:55 2008 From: pistacchio at gmail.com (Gustavo DiPietro) Date: Wed, 12 Mar 2008 15:24:55 +0100 Subject: a Roguelike in Python References: Message-ID: Mdonle at gmail.com ha scritto: > Seeing the 7DRL start up recently, i wanted to see what one was made > of. Python is the language i'm most familiar with so i searched for > some code to look at, but i couldn't find any. Can anyone direct me to > the right place? > > I did some searching on what it would take to write a roguelike in > python and it looked like the curses module would work perfectly, but > it looks to me like it doesn't work in windows? I tried to import it > and it says 'No Module named _curses' > > Sorry if all this sounds a bit noobish, it's only cause i am. i made some pythonesque RL experiments myself. what you have preinstalled is a wrapper for the actual library (that you need to download saperately here http://adamv.com/dev/python/curses/ ). iirc, just unzip & paste in your python/curses directory under Lib From gherron at islandtraining.com Tue Mar 11 21:36:39 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 11 Mar 2008 18:36:39 -0700 Subject: how to pass the workspace ? In-Reply-To: <47D72CDD.9000706@gmail.com> References: <47D72CDD.9000706@gmail.com> Message-ID: <47D733A7.2070808@islandtraining.com> Stef Mientki wrote: > hello, > > I've GUI tree with drag and drop nodes, > where each nodes contains a code snippet. > Now I want to run one or more branches in that tree, > so I enumerate over the nodes and have to run something like this: > > execfile ( node1 ) > execfile ( node2 ) > etc.. > > Now how do I pass the workspace created in node1, to node 2, etc ? > > thanks, > Stef Mientki > RTFM! In particular: http://docs.python.org/lib/built-in-funcs.html#l2h-26 Gary Herron From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 09:03:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 13:03:11 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: <13uv3sftpjvi6e3@corp.supernews.com> On Sun, 30 Mar 2008 10:55:25 +0000, Steven D'Aprano wrote: > Perhaps it's time for me to take a different approach. Since I can't > call timeit, and I can't inherit from it (same problem with state being > shared between instances), perhaps I should write my own timer. > > > import timeit > import gc > import itertools > > def timeit2(func, args=[], kwargs={}, it=None, > timer=timeit.default_timer): > if it is None: it = itertools.repeat(None, timeit.default_number) > save_gc = gc.isenabled() > gc.disable() > try: > start = timer() > for counter in it: > func(*args, **kwargs) > end = timer() > finally: > if save_gc: > gc.enable() > return end - start I've done some comparisons, and the times reported by this function are consistently almost double that of times reported by timeit. Now, I don't expect that my code and the timeit code should have the same overhead, and I realise that the variability of timer results is large. But I'm quite surprised that this seems to have so much more overhead. Can anyone offer some advice? -- Steven From arnodel at googlemail.com Sat Mar 22 07:07:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 04:07:33 -0700 (PDT) Subject: function-class frustration References: <740f8b7f-7d1a-4f98-96c9-71e58e6a8519@u10g2000prn.googlegroups.com> Message-ID: On Mar 22, 10:07?am, John Machin wrote: > On Mar 22, 7:19 pm, castiro... at gmail.com wrote: > > > > > On the other hand, are you willing to make changes to the console? > > How big and what? ?I was thinking of __ to keep the second-to-last > > most recent command. > > Access to and editing of previous input lines is already provided by > the cooked mode of the console (e.g. on Windows, lean on the up-arrow > key) or can be obtained by installing the readline package. Perhaps by > analogy with _, you mean the *result* of the penultimate *expression*. > This functionality would be provided by the Python interactive > interpreter but it's not ... do have a look at IPython (http:// > ipython.scipy.org/moin/About); I don't use it but I get the impression > that if it doesn't already keep a stack or queue of recent results, > you could implement it yourself easily. As you guessed, __ and ___ have the expected meaning in IPython. moreover the nth output in the session is stored in _n. -- Arnaud From jasong at gmail.com Tue Mar 4 20:50:49 2008 From: jasong at gmail.com (Jason) Date: Tue, 04 Mar 2008 19:50:49 -0600 Subject: multiplication of lists of strings Message-ID: How could I return a list or tuple of each unique combination of a given set of lists (perhaps from a dict or a list). This means the number of lists are not known nor is the length of each. Here is an example: fruit = ['apple', 'orange'] numbers = ['one', 'two', 'three'] names = ['joe'] Order matters (I started by trying to iterate over a list corresponding to keys in the dict that contains these lists). Furthermore, (a, b) is different from (b, a) however I will filter out all but unique (a, a) if that occurs. Once this step is solved, I then will use each tuple as a key in a dict. I appreciate any assistance you can throw my way. Jason G From egonslokar at gmail.com Thu Mar 27 17:02:53 2008 From: egonslokar at gmail.com (egonslokar at gmail.com) Date: Thu, 27 Mar 2008 14:02:53 -0700 (PDT) Subject: Tips Re Pattern Matching / REGEX Message-ID: <7ebb329d-12e0-42d8-a543-15521d1ecc46@u10g2000prn.googlegroups.com> Hello Python Community, I have a large text file (1GB or so) with structure similar to the html example below. I have to extract content (text between div and tr tags) from this file and put it into a spreadsheet or a database - given my limited python knowledge I was going to try to do this with regex pattern matching. Would someone be able to provide pointers regarding how do I approach this? Any code samples would be greatly appreciated. Thanks. Sam \\ there are hundreds of thousands of items \\Item1
123
....
Text1: What do I do with these lines That span several rows?
... Foot \\Item2
First Line Can go here But the second line can go here
... Foot Can span Over several pages \\Item3
First Line Can go here But the second line can go here
...
This can Span several rows
From tms at zeetix.com Sun Mar 16 06:56:38 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sun, 16 Mar 2008 06:56:38 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <002101c88754$6989f2b0$0200a8c0@TMSMAIN> I want to thank this community -- especially Carsten Haese -- for your patience with my confusion and for your several suggestions about how to resolve the issue. As a newcomer to python-list, I appreciate your willingness to respond to my request and your graciousness in helping me see the contribution I made to my issue. I now see that, as is often the case, I was asking the wrong question. The immediate problem that this exchange helped me identify is that I needed to escape the json string *again* on its way through my html wrapper. The far more elegant approach sketched by Carsten is the simple act of dropping the apostrophes in my own wrapper. I love that! It works, it's elegant, and it typifies the things that an outside "pair of eyes" can see far more immediately than me. Thank you, Carsten. All in all, this was an extraordinarily helpful exchange. Thank you all, and I hope I can perhaps make similar contributions. From dickinsm at gmail.com Tue Mar 11 10:50:41 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 07:50:41 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> Message-ID: <913818fb-5190-4d16-8376-fe58c4b8bc67@b64g2000hsa.googlegroups.com> On Mar 10, 7:32?pm, Nathan Pinno wrote: > Thanks on the factoring bit, but I did mean factorial, not factoring. > How do I code that correctly, so that I can figure the following > equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax > error and highlight the !. So it would be nice to find a way to solve > such a problem. Aha. I've just found the "Is there a mathematical formula that will find prime numbers?" thread that you started over on sci.math. It looks like at least one of us has been trolled. I suggest you: (1) Ignore the formula Gerry gave you. It's completely impractical as a way of determining primality, and I'm certain that Gerry knew this. (2) Learn some elementary number theory before trying to crack RSA. Mark From castironpi at gmail.com Mon Mar 3 21:31:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 18:31:38 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <2aceec91-618d-4e62-9958-e223505bc51f@13g2000hsb.googlegroups.com> Message-ID: > All software has bugs. > Good software has bugs. Therefore, good software is software. > This makes sympy worse than worthless, as it f***s up other modules. What is it still good for? From gagsl-py2 at yahoo.com.ar Fri Mar 28 19:09:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 20:09:34 -0300 Subject: How to insert multiple rows in SQLite Dbase References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 18:05:29 -0300, afandi escribi?: > Generally, it involves SQL statement such as > follow > > INSERT INTO (field1,field2,.......fieldn) VALUES > ('abc','def'...........) > > If I have data taken from Apache Server Log,let say 100 lines which > is printed output of 8 fields such > as: > > data 1 > IP: 61.5.65.101 > Date: 26/Sep/2007 > Time: 20:43:25 > GMT: +0900 > Requestt: GET /index.php?option=com_content&task=view&id=55&Itemid=19 > HTTP/1.1 > ErrorCode: 200 > Bytes: 6458 > Referel:http://www.joomla.org/index.php? > option=com_content&task=view&id=35&Itemid=19 > Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) > Gecko/20070515 Firefox/2.0.0.4 >How toI insert into SQLite database? by using SQL statement.TQ sqlite3 allows for named parameters; see http://docs.python.org/lib/sqlite3-Cursor-Objects.html You should build a list of dictionaries, with a dictionary per log entry, and call the executemany cursor method. Assuming you have a table created like this: create table log ( IP text, EntryDate timestamp, Requestt text, ErrorCode integer ) you should build a list like this: values = [ {'ip': '61.5.65.101', 'date': a datetime object combining all parts, 'request': "GET /index.php?op...", 'errorcode': 200, }, {'ip': '21.5.65.101', 'date': a datetime object, 'request': "...", 'errorcode': 200, }, ... ] and execute: cur.executemany("insert into log (IP, EntryDate, Requestt, ErrorCode) values (:ip, :date, :request, :errorcode)", values) -- Gabriel Genellina From misceverything at gmail.com Sat Mar 29 10:58:03 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sat, 29 Mar 2008 07:58:03 -0700 (PDT) Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: On Mar 28, 4:53 pm, Tim Golden wrote: > misceveryth... at gmail.com wrote: > > Hello, > > > I would like to write a script that would enumerate all running > > processes and return the full path to the EXE of each running > > process. However, I can't seem to find any good info on how to do > > this..any help is greatly appreciated. Thanks. > > I have this strange feeling of deja vu. Try this: > > http://timgolden.me.uk/python/wmi_cookbook.html#running_processes > > (You want the .ExecutablePath or .CommandLine attributes I imagine) > > TJG Thanks, Tim! I was able to find plenty out there about enumerating processes, but the .ExecutablePath was exactly what I needed. From jura.grozni at gmail.com Thu Mar 13 12:31:38 2008 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Mar 2008 09:31:38 -0700 (PDT) Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> <63t1tnF29egotU1@mid.uni-berlin.de> Message-ID: I thought of using Temp files but I am afraid of the JPG destorsion while saving because of the compresion.I am looking for a way to directly transform it. On Mar 13, 5:09?pm, "Diez B. Roggisch" wrote: > azrael wrote: > > A little problem. > > > Can I directly show Pil objects "image.open("bla.jpg") in Wx or do I > > have to transform them. > > > If I have to transofm them How can I do it. Pixel by pixel or is there > > somethin built in in pil or wx or python. > > pilj->wx and wx->pil. > > PIL doesn't depend on wx, so if anything then wx knows about PIL. But I > doubt it. Instead, use cStringIO and save a PIL-Image to memory, then use > that as file-argument to something that works for wx - no idea what, but > there should be means to load JPEGs and so forth. > > If file-objects aren't enough, create a temp-file. No, that's not to slow. > > Diez From pradiprai at gmail.com Mon Mar 31 08:05:35 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 17:35:35 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Thanks !! I will try do so. Regards, Pradeep -On [20080331 12:56], Pradeep Rai (pradiprai at gmail.com) wrote: >Can you guide me how to install a 2.5 version of dbi for it to work ? Same way you installed dbi for 2.4 just make sure the called python executable is the 2.5 one. -- Jeroen Ruigrok van der Werven / asmodai CF[ EtbN @ f EFF *http://www.in-nomine.org/* | * http://www.rangaku.org/* Sometimes things stare us in the face and we are too blind to see... -------------- next part -------------- An HTML attachment was scrubbed... URL: From Martin.vonLoewis at hpi.uni-potsdam.de Tue Mar 11 16:23:06 2008 From: Martin.vonLoewis at hpi.uni-potsdam.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 11 Mar 2008 21:23:06 +0100 Subject: [ANN] Python 2.3.7 and 2.4.5 (final) Message-ID: <47D6EA2A.3060008@hpi.uni-potsdam.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.5 and 2.3.7 (final). Both releases include only security fixes. Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.3 or 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). Since the release candidate, we received various reports that the this release may fail to build on current operating systems, in particular on OS X. We have made no attempt to fix these problems, as the release is targeted for systems that were current at the time Python 2.4 was originally released. For more recent systems, you might have to come up with work-arounds. For OS X in particular, try invoking:: ./configure MACOSX_DEPLOYMENT_TARGET=10.5 We have made no changes since the release candidate (except for the version numbers). For more information on Python 2.3.7 and 2.4.5, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3.7 http://www.python.org/2.4.5 Highlights of the previous major Python releases are available from the Python 2.4 page, at http://www.python.org/2.3/highlights.html http://www.python.org/2.4/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From gagsl-py2 at yahoo.com.ar Thu Mar 27 15:33:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 16:33:06 -0300 Subject: Regarding __slots__ and other stuff: A couple of questions References: Message-ID: En Thu, 27 Mar 2008 11:27:42 -0300, dave berk escribi?: > *first:* > Why doesn't this works? > >>>> class C(object): > ... __slots__ = ['foo', 'bar'] > ... class_attr = 'class attribute' > ... >>>> c = C() >>>> c.foo = 'foo' >>>> c.bar = 'bar' >>>> c.bar, c.foo > ('bar', 'foo') >>>> c.__slots__ > ['foo', 'bar'] >>>> c.__slots__.append('eggs') >>>> c.__slots__ > ['foo', 'bar', 'eggs'] >>>> c.eggs = 'eggs' > Traceback (innermost last): > File "", line 1, in > AttributeError: 'C' object has no attribute 'eggs' > Because the __slots__ attribute is used when the object is constructed, to reserve space in its structure for those (and only those) attributes. That's the whole point of using __slots__: not creating the generic __dict__ container for all instances to save memory. > *second:* > what happens here? Why can I write to spam using the class object but not > the using the instance? > >>>> class C(object): > ... __slots__ = ['foo', 'bar'] > ... class_attr = 'class attribute' > ... >>>> C.spam = 50 >>>> C.spam > 50 >>>> C.spam = 56 >>>> c = C() >>>> c.spam = 55 > Traceback (innermost last): > File "", line 1, in > AttributeError: 'C' object attribute 'spam' is read-only C *instances* are affected by the __slots__ defined in the C *class*, but the C class itself is not. The C class would be affected by a __slots__ defined in its type (the metatype) but since there exist only one C class object, that optimization would be useless. If you were dynamically creating thousands of classes one might consider the point... > *Third:* > > class RevealAccess(object): > """A data descriptor that sets and returns values > normally and prints a message logging their access. > """ > > def __init__(self, initval=None, name='var'): > self.val = initval > self.name = name > > def __get__(self, obj, objtype): > print 'Retrieving', self.name > return self.val > > def __set__(self, obj, val): > print 'Updating' , self.name > self.val = val > class A(object): > def __init__(self): > self.x = RevealAccess(10, 'var "x"') > self.y = 5 > class B(object): > x = RevealAccess(10, 'var "x"') > y = 5 > >>>> a = A() >>>> b = B() >>>> a.x > <__main__.RevealAccess object at 0x00BAC730> >>>> a.x = 55 >>>> b.x > Retrieving var "x" > 10 >>>> b.x = 55 > Updating var "x" >>>> > > Why the descriptor works only when created as a static variable and not > as an instance variable? It's not a "static variable", it's a "class attribute". Classes are objects too, like functions, methods, code... [almost] everything in Python is an object. The descriptor protocol isn't used when retrieving attributes directly from the instance namespace (__dict__), this is a plain dict access. When you say self.x = RevealAccess(...) you are storing the RA instance directly in the instance namespace. Only when retrieving objects from the *class* the descriptor protocol comes into play. -- Gabriel Genellina From rockxuan at gmail.com Tue Mar 18 03:39:51 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:39:51 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 07:07:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 11:07:10 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: <13uut2uabcbok38@corp.supernews.com> On Sat, 29 Mar 2008 22:11:33 -0700, hdante wrote: > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: > > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) > > ;-) Back in the 1990s, Apple's Hypercard accepted ? for "not equal". Of course, Macs made it easy to type such special characters. By memory you held down the Option key and typed an equals sign. For ? you used Option and less-than. That worked in *any* Mac application. Ah, glory days. But I digress. In Python we can write the above as: if x != 0: [f1(y) if y >= 0 else f2(y) for y in s] which for those not trained in algebra is probably more readable. -- Steven From celoserpa at gmail.com Wed Mar 5 15:18:00 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Wed, 5 Mar 2008 17:18:00 -0300 Subject: Def generating a function to be ran in another context Message-ID: <1e5bcefd0803051218q1e73cea2m600ea73098171431@mail.gmail.com> I'd like a certain function to generate a method for another class and this new method to be called in the context of the "new" class. Is it possible with Python? Thanks, Marcelo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhearne808 at gmail.com Tue Mar 18 12:19:55 2008 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Tue, 18 Mar 2008 09:19:55 -0700 (PDT) Subject: Problems building zlib module on RHEL References: Message-ID: <2896c3a8-82f0-4b3e-a840-0bfae7909d84@2g2000hsn.googlegroups.com> On Mar 18, 8:42 am, "mhearne808[insert-at-sign-here]gmail[insert-dot- here]com" wrote: > I can't seem to get the zlib module to build on an RHEL box. > > I did the following: > 1) Download zlib 1.2.3 > 2) configure;make;make install > 3) Download python 2.5.2 > 4) configure;make;make install > 5) >>> import zlib => "ImportError: No module named zlib" > > In the make install step for python, I notice there are the following > errors: > > building 'zlib' extension > gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/ > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > lib.linux-x86_64-2.5/zlib.so > /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 > against `a local symbol' can not be used when making a shared object; > recompile with -fPIC > /usr/local/lib/libz.a: could not read symbols: Bad value > collect2: ld returned 1 exit status > > Does anyone have any hints on how to get around this? > > system info: > kernel : 2.6.9-67.0.1.ELsmp > gcc : 3.4.6 > > Thanks, > > Mike I figured it out, although it wasn't obvious... You have to compile zlib as a shared library by running "configure -s". From troworld at gmail.com Wed Mar 5 01:16:00 2008 From: troworld at gmail.com (Tro) Date: Wed, 5 Mar 2008 01:16:00 -0500 Subject: Altering imported modules In-Reply-To: References: <200803011856.27611.troworld@gmail.com> <200803041004.50553.troworld@gmail.com> Message-ID: <200803050116.00819.troworld@gmail.com> On Tuesday 04 March 2008, Steve Holden wrote: > >> Are you trying to interfere with the default module on only your > >> machine? Just rename it. If something in the std. lib. imports > >> asyncore, they get yours too that way. > > > > No, I'd like it to be a generalized solution and only for this one > > project. I'm trying to get it to work on any recent python installation > > out of the box, so I can't rename built-in modules. What I'm trying to do > > is allow a 3rd party module (tlslite) to import *my* version of asyncore > > without me going into tlslite's code and changing its import statement > > explicitly, but only for the scope of this one project. > > In that case try something like > > import myasyncore as asnycore > sys.modules['asyncore'] = asyncore > import tlslite Ah. That's what I've been looking for. Thanks! Tro From sean at ardishealth.com Mon Mar 17 13:43:46 2008 From: sean at ardishealth.com (Sean Allen) Date: Mon, 17 Mar 2008 13:43:46 -0400 Subject: Apache binary error? In-Reply-To: References: Message-ID: <22AA51C6-08C4-4E19-B79A-C2C280D9F442@ardishealth.com> On Mar 17, 2008, at 10:55 AM, Michael Wieher wrote: > have simple webpage running > > apache, mod_python > > the error is binary.... > ...binary as in "every other" time I load the page, Firefox keeps > telling me I'm downloading a python script, and asks to open it in > WINE, which is really strange. > > then, alternately, it loads the page just fine. any clues as to why > this is happening? > -- for anything like mod_perl, mod_python etc the first thing i do when i get really weird errors it move to having only one apache process for testing. might want to start there. From sjmachin at lexicon.net Wed Mar 19 19:16:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 16:16:36 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: On Mar 20, 9:14 am, sturlamolden wrote: > On 19 Mar, 22:48, John Machin wrote: > > > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > > and is IMHO more readable than Paul's. > > Is a Python set implemented using a hash table? What don't you understand about the comments in the first two screenfuls of Objects/setobject.c? From atom.anderson at gmail.com Sun Mar 23 23:00:28 2008 From: atom.anderson at gmail.com (Atom) Date: Sun, 23 Mar 2008 20:00:28 -0700 (PDT) Subject: PyCon video editing References: <0ed1ce28-b517-4c17-b12e-7d6554f5274a@x41g2000hsb.googlegroups.com> Message-ID: <0ba1eb7f-9946-4440-a257-23f00c7d8075@i7g2000prf.googlegroups.com> On Mar 18, 8:09 am, amk wrote: > On Mar 17, 10:00 pm, dundeemt wrote: > > > Anyone know who is in charge of this? I'd like to help out if I > > could. > > I am, but haven't set anything up yet, such as a mailing list or a > host for the video. > I'll update the wiki pagehttp://wiki.python.org/moin/PyConRecordingBof > with news/further developments (you can create a wiki account and > follow the envelope icon at the upper right > to be notified of changes via e-mail). > > --amk I'm eager to get my hands on some of these videos! I'll be following the wiki for details. Thanks. -adam From arbo.newmedia at gmail.com Wed Mar 5 09:37:44 2008 From: arbo.newmedia at gmail.com (arbo.newmedia at gmail.com) Date: Wed, 5 Mar 2008 06:37:44 -0800 (PST) Subject: Leopard and MySQL References: <929700bd-89e6-4fb9-ac02-558841cb939e@i12g2000prf.googlegroups.com> Message-ID: On 5 Mar, 13:40, martin.lal... at gmail.com wrote: > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html. When you > search for your problemhttp://www.nabble.com/forum/Search.jtp?forum=2970&local=y&query=mysqldb > > you have the solutionhttp://www.nickshanny.com/2007/10/os-x-105-python-and-mysqldb.html Thanks a lot. From paul at boddie.org.uk Fri Mar 28 14:06:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 28 Mar 2008 11:06:17 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: <2f3a59c2-ef31-426a-be34-bdb187ea3b22@c19g2000prf.googlegroups.com> On 27 Mar, 15:19, "Diez B. Roggisch" wrote: > [Psyco maintenance and further development] > Nope, but I heard through the grapevine that while it won't be supported for > all times to come, a new version is in the making. > > But ultimately, the author says that the approach is flawed, so at *some* > point it will be discontinued. But that could be said about nearly > everything, couldn't it? >From what I've seen from browsing publicly accessible materials, there's a certain commercial interest in seeing Psyco updated somewhat. So, whether it gets discontinued depends on the usual factors of satisfying a need and there being qualified and motivated people to work on it. Paul From exarkun at divmod.com Thu Mar 27 12:10:40 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 27 Mar 2008 11:10:40 -0500 Subject: Psyco alternative In-Reply-To: Message-ID: <20080327161040.6859.1465172015.divmod.quotient.23568@ohm> On Thu, 27 Mar 2008 08:59:33 -0700 (PDT), bearophilehugs at lycos.com wrote: >Diez B. Roggisch: >> the author says that the approach is flawed, so at *some* >> point it will be discontinued. > >Can't Psyco be improved, so it can compile things like: > >nums = (i for i in xrange(200000) if i % 2) >print sum(nums) > Sure, it can be. That doesn't mean it will be. Someone has to do it. :) One reason attention is going to PyPy instead of Psyco is that PyPy's JIT doesn't require as much careful attention to support and maintain support for features like generators. Jean-Paul From samuel.progin at gmail.com Thu Mar 6 07:15:17 2008 From: samuel.progin at gmail.com (Sam) Date: Thu, 6 Mar 2008 04:15:17 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: Hello if type(a) is dict: print "a is a dictionnary!" ++ Sam From miki.tebeka at gmail.com Wed Mar 26 18:11:38 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 26 Mar 2008 15:11:38 -0700 (PDT) Subject: first interactive app References: Message-ID: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Hello Tim, > I want to write a tiny interactive app for the following situation: > I have books of many chapters that must be split into volumes before going > to the printer. > A volume can have up to 600 pages. We obviously break the book into volumes > only at chapter breaks. Since some chapters make a natural grouping, we want > some human interaction for where the volume breaks occur. > > Not having experience with interactive apps, I'm asking for advice about how > to go about it. The data I start with is just a dictionary with chapter name > = ending page number. I figured I would first show where the volumes would > break with no human interaction, with the begin and ending chapter > names/pagenumbers for each volume. > > From here I thought about having a slider for each volume, but the number of > volumes could change during the session. > Or maybe I should just ask 'enter the ending chapter for the first volume' > and recalculate, etc until all volumes are defined. > > Any ideas on a simple interface for this? How about something like: Chapter 1 (001-200 200) Chapter 2 (200-300 100) ------ 001-300 300 ---- Chapter 3 (300-450 150) Chapter 4 (450-500 50) ------ 300-450 250 ---- Chapter 5 (500-600 100) ------ 500-600 100 ---- Where the user can move the divider up and down to create new volume, they can also add and delete dividers. The program will not allow to drag the divider above the 600 page limit. HTH, -- Miki http://pythonwise.blogspot.com From roy at panix.com Sun Mar 2 16:52:27 2008 From: roy at panix.com (Roy Smith) Date: Sun, 02 Mar 2008 16:52:27 -0500 Subject: tuples, index method, Python's design References: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> Message-ID: In article <6d369e71-feb5-477d-a162-f6b0c4eb27f3 at k2g2000hse.googlegroups.com>, Paul Boddie wrote: > On 2 Mar, 19:06, Alan Isaac wrote: > > On April 12th, 2007 at 10:05 PM Alan Isaac wrote: > > > > > The avoidance of tuples, so carefully defended in other > > > terms, is often rooted (I claim) in habits formed from > > > need for list methods like ``index`` and ``count``. > > > Indeed, I predict that Python tuples will eventually have > > > these methods and that these same people will then defend > > > *that* status quo. > > You were more confident about this than I was. Still, nothing happens > if no-one steps up to do something about it. > > > > > > > - Issue #2025 : Add tuple.count() and tuple.index() > > > > methods to comply with the collections.Sequence API. > > Here's the tracker item that may have made it happen: > > http://bugs.python.org/issue1696444 > > I think you need to thank Raymond Hettinger for championing the > cause. ;-) > > Paul Callooh! Callay! We are delivered from one of the most long-lived and pointless (if minor) warts in an otherwise clean and logical type hierarchy. Thank you, Raymond! From jayapal.d at gmail.com Fri Mar 14 00:28:18 2008 From: jayapal.d at gmail.com (jai_python) Date: Thu, 13 Mar 2008 21:28:18 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder Message-ID: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> hi frenz I Need a Python Script For read multiple files(.txt) from a folder and write it in a single text file.... Thanks From __peter__ at web.de Sat Mar 8 12:24:05 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Mar 2008 18:24:05 +0100 Subject: SQL problem in python References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: aiwarrior wrote: > When i run it the get_value() returns 'filepath' instead of the > columns. But if i dont use any variable and make the expression static > all goes on as its supposed to. What am i doing wrong? > self.cursor.execute( "SELECT (?) FROM database", column ) In this case you have to use Python's string interpolation, or the column will be interpreted as a const value. The following should work: self.cursor.execute( "SELECT %s FROM database" % column) If you must sanitize the column name you can prepend something like if column not in allowed_names: raise ValueError Peter From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 08:09:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 12:09:11 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: <13t7kr7c5hvue90@corp.supernews.com> On Sun, 09 Mar 2008 20:57:15 +1100, Alasdair wrote: > Thanks, all - you've been most helpful. By the way, what does // do? I > haven't yet run down its definition in the manual. // is integer division. >>> 10//5 2 >>> 11//5 2 In Python 2.5 and older, / means integer division, unless you do from __future__ import division in which case / is true division, that is: >>> 10/5 2 >>> 11/5 2.5 In Python 3.x, / will always be true division, and you won't need the import. -- Steven From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 06:08:35 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 12:08:35 +0100 Subject: Pb with 2.5.2 & PyScripter Message-ID: <47c93bb8$0$874$ba4acef3@news.orange.fr> Hi, all! Since the install of Python 2.5.2, Pyscripter (1.9.9.1) close for each error. Is it only me? Or another guys have the same thing? @-salutations Michel Claveau From bronger at physik.rwth-aachen.de Sun Mar 30 09:24:30 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 30 Mar 2008 15:24:30 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> Message-ID: <87hceo73ap.fsf@physik.rwth-aachen.de> Hall?chen! Bjoern Schliessmann writes: > hdante wrote: > >> BTW, my opinion is that it's already time that programmer editors >> have input methods advanced enough for generating this: > > Could you please list some that do, and are also convenient? Define "convenient". Emacs is generally not regarded as being convenient, however, it has very strong input methods. I type "\gtrless" and get "?", or "\forall" and get "?". Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From antroy at gmail.com Tue Mar 4 07:41:51 2008 From: antroy at gmail.com (Ant) Date: Tue, 4 Mar 2008 04:41:51 -0800 (PST) Subject: News from Jython world References: Message-ID: <22628504-54af-4732-adb3-e02fd5042dce@d21g2000prf.googlegroups.com> On Mar 3, 6:40 pm, S?bastien Boisg?rault wrote: > Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a > key Jython developer and is specifically hired to work full time on > Jython, a version of the Python interpreter that runs on top of the > JVM and provides full access to Java libraries. After a period where > the development had slowed, Jython was recently getting seriously > back on track. Now it's getting even better ! Development on Jython over the last year or so has been superb, and it's good to see that Sun are getting really focused on dynamic languages on the JVM. It may be that they are trying to play keep-up with Microsoft and their support of IronPython - but regardless of the reasons it is good news for Jython and Frank W, and for the Python community in general. A Sun endorsement of Jython means the possibility of more Python jobs out there for us all in the future given the ubiquity of the JVM in the enterprise and willingness of corporations to accept such endorsements! -- Ant. From bogus@does.not.exist.com Thu Mar 13 00:47:32 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Wed, 12 Mar 2008 23:47:32 -0500 Subject: help please, splitter windows like in maya or 3ds max References: Message-ID: This seems to work... split then split each side. then tandem the size. import wx class Layout(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) sizer = wx.BoxSizer(wx.HORIZONTAL) panel = wx.Panel(self,-1) splitter = wx.SplitterWindow(panel) sizer_left = wx.BoxSizer(wx.VERTICAL) panel_left = wx.Panel(splitter,-1) splitter_left = wx.SplitterWindow(panel_left) splitter_left.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.leftChange,id=splitter_left.GetId()) panel_left_upper = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) panel_left_upper.SetBackgroundColour("WHITE") panel_left_lower = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) splitter_left.SplitHorizontally(panel_left_upper,panel_left_lower) sizer_left.Add(splitter_left,1,wx.EXPAND) sizer_right = wx.BoxSizer(wx.VERTICAL) panel_right = wx.Panel(splitter,-1) splitter_right =wx.SplitterWindow(panel_right) splitter_right.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.rightChange,id=splitter_right.GetId()) panel_right_upper = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) panel_right_lower = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) panel_right_lower.SetBackgroundColour("WHITE") splitter_right.SplitHorizontally(panel_right_upper,panel_right_lower) sizer_right.Add(splitter_right,1,wx.EXPAND) splitter.SplitVertically(panel_left,panel_right) sizer.Add(splitter,1,wx.EXPAND) panel.SetSizer(sizer) panel_left.SetSizer(sizer_left) panel_right.SetSizer(sizer_right) self.splitter_left = splitter_left self.splitter_right = splitter_right def leftChange(self,event): pos = self.splitter_left.GetSashPosition() self.splitter_right.SetSashPosition(pos) event.Skip() def rightChange(self,event): pos = self.splitter_right.GetSashPosition() self.splitter_left.SetSashPosition(pos) event.Skip() app = wx.App(0) k = Layout(None, -1, 'layout.py') k.Show(True) app.MainLoop() -- Andrew ----- Original Message ----- From: "moonrie" Newsgroups: comp.lang.python Sent: Wednesday, March 12, 2008 10:19 PM Subject: help please, splitter windows like in maya or 3ds max > hi, everyone there, I am doing a 3D modeling project. I like to do it > with Python( am a newbie), but have no idea with the wxSplitterWindow > to create the 4-view windows( top, front, side, perspective), like the > mfc CSplitterWnd guy), > anyone can give me some help with wxPython? > > thanks in advance. > > - moonrie From christypoul at gmail.com Mon Mar 24 07:51:07 2008 From: christypoul at gmail.com (bright) Date: Mon, 24 Mar 2008 04:51:07 -0700 (PDT) Subject: =?ISO-8859-1?B?aGkgZnJpZW5kcy4uLi4uLi4uLi4uIGdvb2dsZSBncm91cCBpbnZpdGVzIHlvdSBhIHdvbg==?= =?ISO-8859-1?B?ZGVyaW5nIHdvcmxkIG9mIGJ1c2luZXNzcyAuLi4uLi4uLi4uLi4uIGRvIHUgd2FudCB0byBlYXJuIG1pbA==?= =?ISO-8859-1?Q?lions_of_dollers_per_month_through_online_jobs_joined_with_me?= =?ISO-8859-1?Q?_and_find_the_way_to_earn_dollers=2E=2E=2E=2E=2E=2E=2E=2E=2E_visit_us_www=2Ejobsf?= =?ISO-8859-1?Q?oryouguys=2Eblogspot=2Eco=ADm?= Message-ID: <87f99599-cd03-4e0b-b47b-85722b69b356@e6g2000prf.googlegroups.com> hi friends........... google group invites you a wondering world of businesss ............. do u want to earn millions of dollers per month through online jobs joined with me and find the way to earn dollers......... visit us www.jobsforyouguys.blogspot.co?m From ptmcg at austin.rr.com Sat Mar 22 19:59:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Mar 2008 16:59:47 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Message-ID: <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> On Mar 22, 4:11?pm, rh0dium wrote: > Hi all, > > I am struggling with parsing the following data: > > As a side note: ?Is this the right approach to using pyparsing. ?Do we > start from the inside and work our way out or should I have started > with looking at the bigger picture ( keyword + "{" + OneOrMore key / > vals + "}" + ) ?I started there but could figure out how to look > multiline - I'm assuming I'd just join them all up? > > Thanks I think your "inside-out" approach is just fine. Start by composing expressions for the different "pieces" of your input text, then steadily build up more and more complex forms. I think the main complication you have is that of using commaSeparatedList for your list of real numbers. commaSeparatedList is a very generic helper expression. From the online example (http:// pyparsing.wikispaces.com/space/showimage/commasep.py), here is a sample of the data that commaSeparatedList will handle: "a,b,c,100.2,,3", "d, e, j k , m ", "'Hello, World', f, g , , 5.1,x", "John Doe, 123 Main St., Cleveland, Ohio", "Jane Doe, 456 St. James St., Los Angeles , California ", In other words, the content of the items between commas is pretty much anything that is *not* a comma. If you change your definition of atflist to: atflist = Suppress("(") + commaSeparatedList # + Suppress(")") (that is, comment out the trailing right paren), you'll get this successful parse result: ['0.21', '0.24', '0.6', '0.24', '0.24', '0.6)'] In your example, you are parsing a list of floating point numbers, in a list delimited by commas, surrounded by parens. This definition of atflist should give you more control over the parsing process, and give you real floats to boot: floatnum = Combine(Word(nums) + "." + Word(nums) + Optional('e'+oneOf("+ -")+Word(nums))) floatnum.setParseAction(lambda t:float(t[0])) atflist = Suppress("(") + delimitedList(floatnum) + Suppress(")") Now I get this output for your parse test: [0.20999999999999999, 0.23999999999999999, 0.59999999999999998, 0.23999999999999999, 0.23999999999999999, 0.59999999999999998] So you can see that this has actually parsed the numbers and converted them to floats. I went ahead and added support for scientific notation in floatnum, since I see that you have several atfvalues that are standalone floats, some using scientific notation. To add these, just expand atfvalues to: atfvalues = ( floatnum | Word(nums) | atfstr | atflist ) (At this point, I'll go on to show how to parse the rest of the data structure - if you want to take a stab at it yourself, stop reading here, and then come back to compare your results with my approach.) To parse the overall structure, now that you have expressions for the different component pieces, look into using Dict (or more simply using the helper function dictOf) to define results names automagically for you based on the attribute names in the input. Dict does *not* change any of the parsing or matching logic, it just adds named fields in the parsed results corresponding to the key names found in the input. Dict is a complex pyparsing class, but dictOf simplfies things. dictOf takes two arguments: dictOf(keyExpression, valueExpression) This translates to: Dict( OneOrMore( Group(keyExpression + valueExpression) ) ) For example, to parse the lists of entries that look like: name = "gtc" dielectric = 2.75e-05 unitTimeName = "ns" timePrecision = 1000 unitLengthName = "micron" etc. just define that this is "a dict of entries each composed of a key consisting of a Word(alphas), followed by a suppressed '=' sign and an atfvalues", that is: attrDict = dictOf(Word(alphas), Suppress("=") + atfvalues) dictOf takes care of all of the repetition and grouping necessary for Dict to do its work. These attribute dicts are nested within an outer main dict, which is "a dict of entries, each with a key of Word(alphas), and a value of an optional quotedString (an alias, perhaps?), a left brace, an attrDict, and a right brace," or: mainDict = dictOf( Word(alphas), Optional(quotedString)("alias") + Suppress("{") + attrDict + Suppress("}") ) By adding this code to what you already have: attrDict = dictOf(Word(alphas), Suppress("=") + atfvalues) mainDict = dictOf( Word(alphas), Optional(quotedString)("alias") + Suppress("{") + attrDict + Suppress("}") ) You can now write: md = mainDict.parseString(test1) print md.dump() print md.Layer.lineStyle and get this output: [['Technology', ['name', 'gtc'], ['dielectric', 2.7500000000000001e-005], ['unitTimeName', 'ns'], ['timePrecision', '1000'], ['unitLengthName', 'micron'], ['lengthPrecision', '1000'], ['gridResolution', '5'], ['unitVoltageName', 'v'], ['voltagePrecision', '1000000'], ['unitCurrentName', 'ma'], ['currentPrecision', '1000'], ['unitPowerName', 'pw'], ['powerPrecision', '1000'], ['unitResistanceName', 'kohm'], ['resistancePrecision', '10000000'], ['unitCapacitanceName', 'pf'], ['capacitancePrecision', '10000000'], ['unitInductanceName', 'nh'], ['inductancePrecision', '100']], ['Tile', 'unit', ['width', 0.22], ['height', 1.6899999999999999]], ['Layer', 'PRBOUNDARY', ['layerNumber', '0'], ['maskName', ''], ['visible', '1'], ['selectable', '1'], ['blink', '0'], ['color', 'cyan'], ['lineStyle', 'solid'], ['pattern', 'blank'], ['pitch', '0'], ['defaultWidth', '0'], ['minWidth', '0'], ['minSpacing', '0']]] - Layer: ['PRBOUNDARY', ['layerNumber', '0'], ['maskName', ''], ['visible', '1'], ['selectable', '1'], ['blink', '0'], ['color', 'cyan'], ['lineStyle', 'solid'], ['pattern', 'blank'], ['pitch', '0'], ['defaultWidth', '0'], ['minWidth', '0'], ['minSpacing', '0']] - alias: PRBOUNDARY - blink: 0 - color: cyan - defaultWidth: 0 - layerNumber: 0 - lineStyle: solid - maskName: - minSpacing: 0 - minWidth: 0 - pattern: blank - pitch: 0 - selectable: 1 - visible: 1 - Technology: [['name', 'gtc'], ['dielectric', 2.7500000000000001e-005], ['unitTimeName', 'ns'], ['timePrecision', '1000'], ['unitLengthName', 'micron'], ['lengthPrecision', '1000'], ['gridResolution', '5'], ['unitVoltageName', 'v'], ['voltagePrecision', '1000000'], ['unitCurrentName', 'ma'], ['currentPrecision', '1000'], ['unitPowerName', 'pw'], ['powerPrecision', '1000'], ['unitResistanceName', 'kohm'], ['resistancePrecision', '10000000'], ['unitCapacitanceName', 'pf'], ['capacitancePrecision', '10000000'], ['unitInductanceName', 'nh'], ['inductancePrecision', '100']] - capacitancePrecision: 10000000 - currentPrecision: 1000 - dielectric: 2.75e-005 - gridResolution: 5 - inductancePrecision: 100 - lengthPrecision: 1000 - name: gtc - powerPrecision: 1000 - resistancePrecision: 10000000 - timePrecision: 1000 - unitCapacitanceName: pf - unitCurrentName: ma - unitInductanceName: nh - unitLengthName: micron - unitPowerName: pw - unitResistanceName: kohm - unitTimeName: ns - unitVoltageName: v - voltagePrecision: 1000000 - Tile: ['unit', ['width', 0.22], ['height', 1.6899999999999999]] - alias: unit - height: 1.69 - width: 0.22 solid Cheers! -- Paul From hajducko at gmail.com Thu Mar 27 15:25:29 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Thu, 27 Mar 2008 12:25:29 -0700 (PDT) Subject: Plugin framework - Overcomplicating things? References: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> <753fd116-95e0-4d5b-88b3-927861267577@e23g2000prf.googlegroups.com> Message-ID: <1a82d714-a392-439f-84a1-a2b6cdee8d10@a1g2000hsb.googlegroups.com> On Mar 27, 4:18 am, Andr? wrote: > On Mar 27, 3:31 am, "Gabriel Genellina" > wrote: > > > > > En Thu, 27 Mar 2008 01:50:56 -0300, hajdu... at gmail.com > > escribi?: > > > > All this comes to my question - am I overcomplicating this project? I > > > can understand the use of something like the trac component system if > > > I had multiple components and plugins that handled different areas of > > > my project and different points of interaction, but I don't. I've got > > > exactly one spot where I want to check all my plugins and hand off the > > > message to which ever ones are looking for that command. > > > As you said, it looks like you're really overengineering your design then. > > > > So really, > > > should I even bother with trying to setup some framework for this or > > > should I just be doing a simple loop over a directory, importing all > > > the plugins and storing them in a list and then looping over them in > > > the message handler to see which ones were looking for the command and > > > letting them do their thing? > > You could set thing up so that there's no need to loop over the > plugins. > What you can do is register a plugin (as mentioned to you before by > Gabriel - see below) and create an entry in a handler dict so that you > can directly dispatch the message to the appropriate handler without > having to loop over a list of them. Something like > handlers[message]() > > > > > > > That may be an option. > > You may want to setup a simple registry mechanism, so the plugin modules > > look like: > > > ### begin niceplugin.py ### > > class AVeryNicePlugin(object): # or perhaps using a suitable base class > > def handle_message(self, message): > > ... > > > from plugin import PluginRegistry > > PluginRegistry.register(AVeryNicePlugin) > > ### end niceplugin.py ### > > > Your application scans a known directory for files ending in "plugin.py" > > and imports them; the modules register themselves any class (or classes), > > and at appropiate times the application calls some method(s) of the > > registered plugins. > > An alternative (which we found simpler with Crunchy) is to not have a > class-based structure, but working with simple modules and functions. > All modules are put in the "plugin" directory which are imported at > the beginning. Each module contain at least two functions: > 1. register() which create the handlers dict entry so that it point > out to the appropriate function. > 2. one or more function that is called based on the message received. > > Hope it helps, > > Andr? > > Thanks for the replies. Andr?, you're alternative was exactly what I was thinking of falling back to, rather than setting up class-based plugins. Like I said, seems like a whole plugin framework would be wayyyy too complicated. The only reason I figured I'd loop over the available plugins was in case two were defined to handle the same message. I figured something like setting an 'command' attr in the module and just checking for that. Either way, I think I'll stay away from trying for a real framework in this case. -- sh From tomerfiliba at gmail.com Mon Mar 17 16:52:32 2008 From: tomerfiliba at gmail.com (gangesmaster) Date: Mon, 17 Mar 2008 13:52:32 -0700 (PDT) Subject: win32: emulating select() on pipes Message-ID: hi i'm trying to figure out if a pipe on win32 has data for me to read. this is the code i've come up with: def poll(self, timeout, interval = 0.2): """a poor man's version of select() on win32""" from win32pipe import PeekNamedPipe from msvcrt import get_osfhandle handle = get_osfhandle(self.fileno()) if timeout is None: timeout = sys.maxint length = 0 tmax = time.time() + timeout while length == 0 and time.time() < tmax: length = PeekNamedPipe(handle, 0)[2] time.sleep(interval) return length != 0 does anyone know of a better way to tell if data is available on a pipe? something that blocks until data is available or the timeout is elapsed, and returns True if there's something for me to read, or False otherwise. -tomer From castironpi at gmail.com Thu Mar 6 11:40:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 08:40:47 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> On Mar 6, 12:17?am, "Daniel Fetchinson" wrote: > > > Where to begin? > > > What does exec( open( 'modA.py' ).read() ) do? > > The most appropriate list to ask those questions is: > > http://mail.python.org/mailman/listinfo/tutor Thanks for the reference. I'm basically experienced with Python, but I may read there too. I asked the question mostly rhetorically. Like when people ask, who cares, or who knows. They don't want the answer---- unless there is one. A more appropriate formulation of the 'question behind the words' would have been, 'are there any weird corner cases in which it doesn't import modA? I recognize it doesn't on .pyc and .pyd files, but you could say exec( open( 'modA.py' ).read() ) ==> import modA, even if import modA =!=> exec( open( 'modA.py' ).read() ) all the time. However, a way of asking that's more direct would have been, "Wait... can't you create multiple module instances like that?", but since we've already seen successful loadings of at least the builtins, that's been treated. Maybe you even hear the right thing if I say, "Does exec( open( 'modA.py' ).read() ) do the things of import modA?" Yes, I can read the docs, but no, I can't check every possible combination of modules. The idea behind a singleton is to ensure something. You want non- primary instances impossible to create. However, if (wording got tangled here) for singleton A, if class B does the same thing, just has different allocations-- it's own-- then A is still a singleton. The writer of B hasn't defeated or contradicted the letter or spirit of A. OP's question might have come from a variety of perspectives. In some ways yes, in others no. That is, if you try to reinstantiate modA, you get the same instance. But if you try really hard, you get a new one. Are you looking for an extension to import modA that won't return an instance that is old? So far, I know this: modules and classes are both namespaces. Are those singletons? From kay.schluehr at gmx.net Tue Mar 4 03:48:48 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 4 Mar 2008 00:48:48 -0800 (PST) Subject: ANN: EasyExtend 3.0 - beta1 released Message-ID: <24785288-715c-4677-b8a7-20463f672865@f47g2000hsd.googlegroups.com> After more than half a year of work I released the first beta of EasyExtend 3.0 today. EasyExtend 3.0 is the second major redesign of EasyExtend. To gain more power and simplicity I implemented a new parser generator from the scratch called "Trail". Trail unifies several aspects of EasyExtend. It is the fundament of both the EE 3.0 tokenizer and the parser. It is used to validate parse trees against grammars and it is used for parse tree synthesis. Besides Trail other new aspects of EE 3.0 are * User defined file suffixes are recognized by the import machinery * Framework extension that supports facilitation of writing user defined tokenizers * Simplification of access to tokenizer and parser from individual extension languages ( langlets ). * Improved stability of the CST transformation process and improved debugging facilities Currently EasyExtend 3.0 does not support several extension languages being described on the home page. Some of them like the macro langlet will be reimplemented in EasyExtend 3.1 using Trail techniques and a new persistence layer called exo.space. Others will be upgraded until the final release of EasyExtend 3.0. URLs: http://www.fiber-space.de/EasyExtend/doc/EE.html http://pypi.python.org/pypi/EasyExtend/3.0-beta1 From atom.anderson at gmail.com Thu Mar 20 12:15:53 2008 From: atom.anderson at gmail.com (atom.anderson at gmail.com) Date: Thu, 20 Mar 2008 09:15:53 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> Message-ID: <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> On Mar 17, 1:20 am, Paul Rubin wrote: > Stephan Deibel writes: > > I have to admit, I'll keep coming to PyCon even if all the talks suck > > abysmally as long as there's good hallway time, open space, BoFs, and > > sprints. ;-) > > OK, so why not get rid of all the talks and other stuff, and just have > a basically structureless conference, beyond scheduling some open > meetings on various topics? That would be a lot less expensive and a > lot more interesting. For me as first time pycon attendee, i think this would be an absolute disaster. The talks gave me an opportunity to sit next to new people and meet people I wouldnt have otherwise if they had simply "put us out to pasture" to chat it up. I think for devs that are just meeting each other, having some sort of subject matter to talk about is a big deal, and the talks forced that. I agree though that once things get going, the hallway time and BOF time would be fantastic. -adam From BruceTEckel at gmail.com Sun Mar 16 16:52:20 2008 From: BruceTEckel at gmail.com (Bruce Eckel) Date: Sun, 16 Mar 2008 13:52:20 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <3a2e4490-f4e9-4edf-ae35-0aa3c90103f7@i7g2000prf.googlegroups.com> Message-ID: On Mar 16, 2:48 pm, Pete Forde wrote: > My friends and I decided to stage a grassroots Ruby conference this > summer; it will have no paid sponsors for exactly this reason. We're > trying to change up the typical format as well: it's a single-track > event, no "keynotes", no schills for well-heeled interests. We're even > organizing activities for significant others traveling with conference > attendees so that everyone has a good time. > > The response we've gotten to this approach has been curious; many > people totally get why these things are important, and the speaker > list reflects this. However, we've also had a lot of complaints that > our event is too expensive. In fact, they say that it should be free, > like a BarCamp. Just get a bunch of sponsors, and that will be the > ticket. We say bollocks to that. > > http://rubyfringe.com/ I've been running open spaces conferences for the past few years and I would suggest you do that instead of an "eyes-forward" conference. It's not only a lot easier, but it's also a lot more fun. For example, last week we did the Java Posse Roundup, which is all open-spaces. The way we've handled "sponsorship" for the Roundup is "swag only." If sponsors want to send gifts, then we'll give them out, but we don't take money. Everybody seems pretty happy with that arrangement and it doesn't feel intrusive in the least. So you might consider that. Because of requests I've had (before Pycon started) we are planning a small open-spaces conference on Python, this summer in Crested Butte. The dates haven't been set yet but I'll announce them on my weblog and elsewhere. It will follow the format of lightning talks to kick off, then all open spaces (plus the usual hikes and barbeques). And swag- only contributions from vendors, although that usually just happens via people who happen to work for vendors, who are coming as participants and find out they can contribute something else. > I'm posting here because even though the Python and Ruby communities > are seen as being in some sort of competition, I personally believe > that we have more in common (and lots to learn from each other) than > we are credited for. For example, the popular Haml template engine is > white-space sensitive, and that's a direct nod towards Python syntax. I think Ruby has done a lot to push the idea of dynamic languages for medium and large scale projects and to help recover from the bad experience many had when they tried to push Perl too far. > Thanks for your post, Bruce. You've given us a huge boost that we're > doing something right, here. I'm sure your conference will be great because you're making it totally attendee-focused. From cokofreedom at gmail.com Wed Mar 12 11:27:44 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 12 Mar 2008 08:27:44 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> Message-ID: <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> On Mar 12, 2:44 pm, Robert Bossy wrote: > Matt Nordhoff wrote: > > Robert Bossy wrote: > > >> k.i.n.g. wrote: > > >>> I think I am not clear with my question, I am sorry. Here goes the > >>> exact requirement. > > >>> We use dd command in Linux to create a file with of required size. In > >>> similar way, on windows I would like to use python to take the size of > >>> the file( 50MB, 1GB ) as input from user and create a uncompressed > >>> file of the size given by the user. > > >>> ex: If user input is 50M, script should create 50Mb of blank or empty > >>> file > > >> def make_blank_file(path, size): > >> f = open(path, 'w') > >> f.seek(size - 1) > >> f.write('\0') > >> f.close() > > >> I'm not sure the f.seek() trick will work on all platforms, so you can: > > >> def make_blank_file(path, size): > >> f = open(path, 'w') > >> f.write('\0' * size) > >> f.close() > > > I point out that a 1 GB string is probably not a good idea. > > > def make_blank_file(path, size): > > chunksize = 10485760 # 10 MB > > chunk = '\0' * chunksize > > left = size > > fh = open(path, 'wb') > > while left > chunksize: > > fh.write(chunk) > > left -= chunksize > > if left > 0: > > fh.write('\0' * left) > > fh.close() > > Indeed! Maybe the best choice for chunksize would be the file's buffer > size... I won't search the doc how to get the file's buffer size because > I'm too cool to use that function and prefer the seek() option since > it's lighning fast regardless the size of the file and it takes near to > zero memory. > > Cheers, > RB But what platforms does it work on / not work on? From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:20:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:20:09 -0300 Subject: importing a csv file as a Numeric array References: Message-ID: En Tue, 25 Mar 2008 06:46:57 -0300, Rahul escribi?: > What's a good way of importing a csv text file of floats into a > Numeric array? I tried the csv module and it seems to work well so > long as I've ints. Does anyone have any suggestions / snippets that > work to import a csv file of floats into a Numeric array? See the Cookbook at http://www.scipy.org/Cookbook/InputOutput - but I don't know how much of that is applicable to the old Numeric library. Robert Kern posted a fairly generic approach in this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/7345c364cae59127/ -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Mar 27 05:44:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 06:44:21 -0300 Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 06:00:26 -0300, escribi?: > I was add this into my application code: > > import sys > import os > my_dir=os.getcwd() > sys.path.append(my_dir) > sys.path.append(my_dir+"\\libary.zip") > sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder > f=open("path.txt","w") > f.write(str(sys.path)) > f.close() > > an the output in path.txt is : > > ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users > \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ > \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ > \libary.zip\\py2exe'] > > But it still can't find module py2exe.What should I do now? Any > examples? I assume you're talking about the py2exe package available from www.py2exe.org - so it's not a module, it's a package. py2exe usually is only relevant on your *development* machine, so why do you want to put it inside a .zip? What do you want to do? Anyway, I tried the following and could import py2exe successully (but I don't know if it actually works as a distutils extension...) - compressed the py2exe folder into py2exe.zip - deleted the original py2exe folder - moved py2exe.zip onto some temporary directory - tried to import py2exe, failed as expected - added py2exe.zip to sys.path - tried to import py2exe, this time OK py> import py2exe Traceback (most recent call last): File "", line 1, in ImportError: No module named py2exe py> import sys py> sys.path.append(r"C:\TEMP\pna\py2exe.zip") py> import py2exe py> py2exe.__path__ ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] -- Gabriel Genellina From grante at visi.com Fri Mar 21 16:03:04 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Mar 2008 20:03:04 -0000 Subject: How can I make a function equal to 0? References: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Message-ID: <13u853oaoqjle62@corp.supernews.com> On 2008-03-21, Paul Rubin wrote: > Martin Manns writes: >> Is there a way to create a function that is equal to 0? > > def f(): return 0 I assumed he meant he wanted this to evaluate to True instead of False: >>> def f(): return 0 ... >>> >>> f == 0 False -- Grant Edwards grante Yow! Yes, but will I at see the EASTER BUNNY in visi.com skintight leather at an IRON MAIDEN concert? From sturlamolden at yahoo.no Tue Mar 18 19:08:04 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 16:08:04 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> On 18 Mar, 23:45, Arnaud Delobelle wrote: > > def nonunique(lst): > > slst = sorted(lst) > > dups = [s[0] for s in > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > return [dups[0]] + [s[1] for s in > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > Argh! What's wrong with something like: > > def duplicates(l): > i = j = object() > for k in sorted(l): > if i != j == k: yield k > i, j = j, k Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) as opposed to ours which are O(N log N). From mdboldin at gmail.com Tue Mar 4 07:53:33 2008 From: mdboldin at gmail.com (mmm) Date: Tue, 4 Mar 2008 04:53:33 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> Message-ID: <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Steve, I think you were right the first time is saying > it should really be this: > sqlxb= 'INSERT INTO DTABLE2 VALUES (?, ?, ?, ?)' my copy.copy() has the equivalent effect. Running this test code produces the output below import copy print 'Test 1' pf= '?,?,?,?' sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf print sqlx1 print print 'Test 2' sqlx2= copy.copy(sqlx1) sqlx3= sqlx1 pf= '?,?,?, ****' sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf print 'sqlx1= ', sqlx1 print 'sqlx2= ', sqlx2 print 'sqlx3= ', sqlx2 == output Test group 1 INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) Test group 2 sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?, **** ) sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) I interpret this to mean that sqlx1 is not a simple string From dickinsm at gmail.com Tue Mar 11 11:59:44 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 08:59:44 -0700 (PDT) Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> Message-ID: <46f8d1bf-8821-4083-b7d7-d4ed53f8862a@q78g2000hsh.googlegroups.com> On Mar 11, 11:35?am, Grant Edwards wrote: > That seems a bit baffling. ?If it urlopen doesn't support > specifying proxies, why are there examples showing how to do > it? If it does support specifying proxies, what is the pragraph > quoted above supposed to mean? Looks like a definite documentation bug to me, and it's still there in the development version of the documentation. I think a bug report should be filed. A little bit of investigation shows that the documentation changes were made in svn revisions 26181 and 26182 ( http://svn.python.org/view?view=rev&rev=26181 ) as a fix for http://bugs.python.org/issue523415 but this doesn't seem to help much with figuring out what the docs intend to say. Mark From mac_the_scotte at hotmail.com Sat Mar 29 15:57:18 2008 From: mac_the_scotte at hotmail.com (mac_the_scotte at hotmail.com) Date: Sat, 29 Mar 2008 12:57:18 -0700 (PDT) Subject: Problem with python Message-ID: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Hi there. I downloaded python a couple of days ago from the official site and have started writing simple programs in the python gui (this being my first attempt at programming ever). The only thing is when I write python code in a text editor and save it as a .py file, when I double click it all that happens is a black box flashes up on the screen, but nothing else!? At first I thought this was because I had only written a hello world program, and that the box had displayed "hello world" and then closed. But then I wrote a program requiring user input and the same thing happened... Am I doing something wrong? Thanks in advance for any help! //mac From stanc at al.com.au Thu Mar 27 02:11:13 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 27 Mar 2008 17:11:13 +1100 Subject: copy file over LAN In-Reply-To: References: <47EB15BC.3060505@al.com.au> Message-ID: <47EB3A81.7090708@al.com.au> Well, the solution seems to be something like (windows only) import os import os.path import shutil import sys import win32wnet def wnet_connect(host, username, password): unc = ''.join(['\\\\', host]) try: win32wnet.WNetAddConnection2(0, None, unc, None, username, password) except Exception, err: if isinstance(err, win32wnet.error): # Disconnect previous connections if detected, and reconnect. if err[0] == 1219: win32wnet.WNetCancelConnection2(unc, 0, 0) return wnet_connect(host, username, password) raise err if __name__ == '__main__': node = hostname dst = r'C:\temp\destination__' dst += node + r'.txt' wnet_connect(node,username,password) shutil.copyfile(r'\\' + node + r'\c$\temp\\al_lsf_log',dst) Gabriel Genellina wrote: > En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee escribi?: > > >> I have a file on another machine on the local network (my machine and >> local machines are on windows) and I want to copy it locally. Now the >> machine requires authentication and when I try to do a >> import shutil >> shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') >> and it gives me a IOError: [Errno 13] Permission denied: error, which I >> expect. How do I provide authentication to copy this file? >> > > Probably there are other ways, but the "net use" command looks easy > enough. Execute "net help use | more" in a console to see the right syntax. > Use the subprocess module to run the command from inside Python. > > -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Wed Mar 26 18:26:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 15:26:52 -0700 (PDT) Subject: memory allocation for Python list References: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> Message-ID: <033ed38c-1b43-4bb5-9ceb-54fb5f128217@q78g2000hsh.googlegroups.com> dmitrey: > As I have mentioned, I don't know final length of the list, but > usually I know a good approximation, for example 400. You may want to use collections.deque too, it doesn't produce a Python list, but it's quite fast in appending (it's a linked list of small arrays). Bye, bearophile From aahz at pythoncraft.com Sun Mar 16 10:18:04 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Mar 2008 07:18:04 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: In article <5bd37c10-af5d-4254-8799-49c762673a3e at n58g2000hsf.googlegroups.com>, Bruce Eckel wrote: > >If the following seems unnecessarily harsh, it was even more harsh for >me to discover that the time and money I had spent to get to my >favorite conference had been sold to vendors, presenting me as a >captive audience they could pitch to. Ouch. I'm probably one of the few organizers currently paying much attention to c.l.py -- because I'm also one of the few who's not at PyCon. We debated this extensively before going ahead, and we decided it was worth an experiment. If your feedback is at all representative, this won't happen again, I assure you. I'm forwarding your post to the semi-private pycon-organizers list (pretty much anyone can join -- more volunteers are always welcome -- but you have to join to see the archives) to make sure everyone sees it. >I believe that this year's Pycon organizers suffered from inexperience >and naivete, because they didn't know that some vendors will ask for >anything just to see how far they can push it. Actually, it was our idea to offer something in return for the sponsorship. >On top of that, the quality of the presentations was unusually low. >I'd say that 80% were not worth going to -- there were definitely some >good ones, but it was a lot of pain to discover them. Just to make sure, you're talking about the vendor presentations, right? >I think a lot of people have been caught up in the idea that we need >to commercialize Python, and ride some kind of wave of publicity the >way that Java and C# and Rails seem to have done. Not in my observation. What we were trying to do was to increase sponsorship to decrease the cost to attendees -- we have NO interest in pushing the commercialization of Python. >I know what the argument for the results of Pycon 2008 will be: we >needed the money. My answer: it's not worth it. If this is what you >have to do to grow the conference, then don't. If the choice is >between selling my experience to vendors and reducing the size of the >conference, then cut the size of the conference. Keep the quality of >my experience as the primary decision criteria, or I'll stop coming. That was our intention. Apparently it didn't work for you. I'll wait for more feedback before I make up my mind about whether your experience was common. And no, we don't need the money so badly that we can't afford to turn away sponsors who demand this particular benefit. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From dkuhlman at rexx.com Thu Mar 13 18:06:05 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 13 Mar 2008 22:06:05 GMT Subject: getattr(foo, 'foobar') not the same as foo.foobar? Message-ID: The following code has me mystified: In [4]: class A(object): ...: def show(self): ...: print 'hello' ...: ...: In [5]: a = A() In [6]: In [7]: x = a.show In [8]: y = getattr(a, 'show') In [9]: x Out[9]: > In [10]: y Out[10]: > In [11]: In [12]: id(x) Out[12]: 12419552 In [13]: id(y) Out[13]: 12419872 In [14]: In [15]: x is y Out[15]: False In [16]: In [17]: x() hello In [18]: y() hello Basically, the above code is saying that foo.foobar is not the same as getattr(foo, 'foobar'). But the documentation at http://docs.python.org/lib/built-in-funcs.html#l2h-33 says that they are equivalent. And, the following seems even worse: >>> id(getattr(a, 'show')) == id(a.show) True >>> getattr(a, 'show') is a.show False What gives? This breaks my understanding of id(), the is operator, and getattr(). Can someone help me make sense of this? I'm using Python 2.5.2. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From van.lindberg at gmail.com Mon Mar 17 10:13:39 2008 From: van.lindberg at gmail.com (VanL) Date: Mon, 17 Mar 2008 09:13:39 -0500 Subject: Pycon disappointment In-Reply-To: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <47DE7C93.4040501@gmail.com> Bruce, I can't speak to your issues with the normal sessions, but your bad experience with the lightning talks was my fault. And, in apologizing to you, I hope that all the others on this thread who have expressed similar sentiments hear me too. Ultimately, we miscalculated in certain respects. It wasn't any particular thing, but rather there were a couple of issues that came together here: 1 - We had an incredible amount of sponsorship. Higher than expected by anyone. This wasn't bad in itself (I think it was very good!), but it set the stage for some of the issues later. 2 - As part of the sponsor package, we promised the sponsors priority for a lightning talk. Our thought was that the sponsor lightning talks from last year were well received, so they probably would be this year as well. Unfortunately, that turned out not to be the case - at least having *that many* was not well received. 3 - We had a very limited time when some of the sponsors would still be here - basically Friday and Saturday. The major problem on Saturday is that we *had* to stack the sponsor talks that way or else we would not fulfill our obligations to our sponsors. We offered lightning talks this year because a) we didn't know how well the expo hall would go, and b) that was the only way for the sponsors to connect with the audience last year - so we assumed that it might be the same way this year. This was discussed and generally agreed-to in September. IIRC, the sponsor lightnings were not an issue that was subject to much debate back then, most people were accustomed to the generally positive 2007 experience.* I think that with the success of the expo hall, we can remove the lightning talks from the sponsor benefits for next year, and at this point I am in favor of doing so. Personally, I was *very* disappointed that some of our sponsors didn't prepare or even show up for their assigned slots. I think that the sponsors are members of our community, and I expect them to act as such. Taking slots and not showing up - or not showing up prepared - isn't how I would hope a community member would act. Thanks, Van *(On the other hand, the Diamond keynotes were the subject of substantial debate - but I thought those went well; I would like to keep them for next year.) From aeneng at yahoo.com Fri Mar 28 21:47:21 2008 From: aeneng at yahoo.com (aeneng) Date: Sat, 29 Mar 2008 01:47:21 -0000 Subject: Help me on function definition Message-ID: Hello everyone, I am just starting to use python in numerical cacluation. I need you to help me to see what's wrong with the following piece of codes, which computes the cross product of two vectors and returns the result. u and v are two 3x1 matrix. when I import the function, error message show like this >>> import cross Traceback (most recent call last): File "", line 1, in ? File "cross.py", line 8 ppp2=u[2]*v[0]-u[0]*v[2] ^ SyntaxError: invalid syntax WHAT IS WRONG WITH MY CODE? I appreciate your help. ##here is the function definition. ##cross.py## def cross(u,v) """input two vectors u and v in 3-D space, output a cross product of vector w, in column or in row accordingly.""" ppp1,ppp2,ppp3=0.0,0.0,0.0 ppp1=u[1]*v[2]-u[2]*v[1] ppp2=u[2]*v[0]-u[0]*v[2] ppp3=u[0]*v[1]-u[1]*v[0] # store the result of the cross product in u u[0]=ppp1 u[1]=ppp2 u[2]=ppp3 return u #return the cross product of vector u x v. if __name__=="__main__": from cvxopt.base import matrix u=matrix([1.0,0.0,0.0],(3,1)) v=matrix([0.0,1.0,0.0],(3,1)) print cross(u,v) print "file name is %s" %__name__ From sjmachin at lexicon.net Sun Mar 23 21:56:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 18:56:51 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> <13udtk586ijktec@corp.supernews.com> Message-ID: On Mar 24, 11:32 am, Steven D'Aprano wrote: > On Sun, 23 Mar 2008 10:45:38 -0700, Paul Rubin wrote: > > John Nagle writes: > >> What's the cheapest way to test for an empty dictionary in Python? > > >> if len(dict.keys() > 0) : > > > I like to think len(dict) is constant time but I haven't checked the > > code. Same for bool(dict) (which is what you get when you run "if dict: > > ..."). > > Except that "if dict" doesn't needlessly and wastefully create a bool. > > >>> from timeit import Timer > >>> Timer("if {1:2}: pass").timeit() > 1.1590199184417725 > >>> Timer("if bool({1:2}): pass").timeit() > > 1.8825540542602539 > > Python knows the truth value of built-in types like dicts without > actually converting them to bools, or for that matter calling __len__ or > __nonzero__ on them. What the 2.5.1 interpreter does is call PyObject_IsTrue, which checks to see if the built_in or extension type is a mapping (not just a dict) with a length method and if so calls it; similarly for sequences: else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); else if (v->ob_type->tp_as_sequence != NULL && v->ob_type->tp_as_sequence->sq_length != NULL) res = (*v->ob_type->tp_as_sequence->sq_length)(v); Was that what you meant by "without ... calling __len__"? From mistermoose at gmail.com Thu Mar 6 08:56:11 2008 From: mistermoose at gmail.com (Jeffrey Seifried) Date: Thu, 6 Mar 2008 05:56:11 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: <5c0bab72-8dd2-4be9-a832-168a32d99585@8g2000hse.googlegroups.com> On Mar 6, 7:10 am, Guillermo wrote: > Hello, > > This is my first post here. I'm getting my feet wet with Python and I > need to know how can I check whether a variable is of type dictionary. > > Something like this: > > if isdict(a) then print "a is a dictionary" > > Regards, > > Guillermo Or if type(a)==type({}): print 'a is a dictionary' From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 03:52:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 07:52:25 -0000 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> <7xk5jz1a80.fsf@ruckus.brouhaha.com> Message-ID: <13u45tp398pfc18@corp.supernews.com> On Wed, 19 Mar 2008 23:53:22 -0700, Jeff Schwab wrote: > The point of rsync is to keep a local directory tree in sync with a > remote one, by transferring only change-sets that are conceptually > similar to patches. If you're only transferring files once, there's no > particular benefit (AFAIK) to using rsync rather than some kind of > recursive ftp. Avoiding re-inventing the wheel is a big benefit. -- Steven From arkanes at gmail.com Fri Mar 7 16:06:37 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 7 Mar 2008 15:06:37 -0600 Subject: I cannot evaluate this statement... In-Reply-To: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <4866bea60803071306n5d53c2ebk43430364b49983d9@mail.gmail.com> On Fri, Mar 7, 2008 at 2:38 PM, waltbrad wrote: > The script comes from Mark Lutz's Programming Python. It is the > second line of a script that will launch a python program on any > platform. > > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > That makes sense. Because the first condition is true and 'python.exe' > is true. So the next comparison is 'python.exe' or 'python' Well, > python.exe is true. So that value is returned to pyfile. > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. > But, again, on linux pyfile evaluates to python.exe > > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? > -- > http://mail.python.org/mailman/listinfo/python-list > In Python 2.5, this is written: pyfile = 'python.exe' if 'win' in sys.platform else 'python' However, this is a pretty bad way of doing this at all. sys.executable is better. I'm not sure when sys.executable was added but I assume it's more recent than whatever version Lutz used in his book. From aisaac at american.edu Wed Mar 12 19:52:01 2008 From: aisaac at american.edu (Alan Isaac) Date: Wed, 12 Mar 2008 23:52:01 GMT Subject: no more comparisons In-Reply-To: <7xy78neffb.fsf@ruckus.brouhaha.com> References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The cmp option should not be removed. However, requiring > it to be specified as a keyword parameter instead of just > passed as an unlabelled arg is fine. Sure; I would have no problem with that. But that is not what is happening. As for Carl's suggestion to use ``key``: this is already possible when it is convenient, but it is not always convenient. (Even aside from memory considerations.) By the way, I even saw mention of even removing the ``cmp`` built-in. Cheers, Alan Isaac From kyosohma at gmail.com Mon Mar 10 17:18:30 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 14:18:30 -0700 (PDT) Subject: wxPython: some help with Drag&Drop References: Message-ID: On Mar 10, 4:04 pm, Eric von Horst wrote: > Hi, > > I need some advice on Drag&Drop. > > What I want to achieve is the following: > - I have a window that is divided in two : on the left hand I > have a wx.TreeCtlr and on the other hand a wx.StaticBitmap > > I want to be able to drag an item from the tree onto the static > bitmap. > > I know how to do drag&drop in a treeCtrl but is there a way that I can > make the bitmap detect that something has been dropped on it? > > I would only need to know the name of the tree obj that was dropped on > the bitmap (and the location) > > Any help much appreciated > > Erik I highly recommend posting to the wxPython user's group since they specialize in this sort of thing: http://wxpython.org/maillist.php In the mean time, you'll probably want to take a look at their wiki: http://wiki.wxpython.org/DragAndDrop http://wiki.wxpython.org/ListControls There's also a fair amount of data on the subject in their archives. Mike From vlastimil.brom at gmail.com Wed Mar 5 18:18:01 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 6 Mar 2008 00:18:01 +0100 Subject: Dual look-up on keys? In-Reply-To: References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <9fdb569a0803051518x3dd0a9e9w7769d2175bcbfa1f@mail.gmail.com> 2008/3/5, castironpi at gmail.com : > > ... > Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a) > is also in it, and maps to the same object? > ... > Well, it's probably not the most effective way, but one can use something like: >>> d={frozenset(("a","b")):7} >>> d[frozenset(("b","a"))] 7 >>> d[frozenset(("b","a"))]=94 >>> d[frozenset(("a","b"))] 94 >>> HTH vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From sean at ardishealth.com Wed Mar 19 09:16:44 2008 From: sean at ardishealth.com (Sean Allen) Date: Wed, 19 Mar 2008 09:16:44 -0400 Subject: What Programming Languages Should You Learn Next? In-Reply-To: <64bugqF2anottU1@mid.uni-berlin.de> References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> Message-ID: > Haven't found that killer problem so far ... for Haskell, check out HAppS. They have some great web application stuff going on. From natraj12j at gmail.com Fri Mar 7 01:44:53 2008 From: natraj12j at gmail.com (Nat) Date: Thu, 6 Mar 2008 22:44:53 -0800 (PST) Subject: Regarding an exciting opportunity in PYTHON at Hyderabad Message-ID: We have been looking for Senior Professional based at Hyderabad for one of our clients which an upcoming Product development company based out of hyderabad . I would appreciate if you can repond back with your profile at natraj12j at gmail.com.I would get back to you with complete details and accordingly we can go ahead. Job Description: Need to have 2-4 years of experience. Should have strong understanding of Project management and SDLC. Technology is flexible. Can have experience in either of python(C, C+ +),Java or .NET. Thanks and Regards Natraj.J M?bius Consulting Pvt. Ltd. From grante at visi.com Sun Mar 9 00:31:22 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:31:22 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6c8kdis2gbb5@corp.supernews.com> Message-ID: <13t6tha12dcdh5a@corp.supernews.com> On 2008-03-09, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 21:21:48 +0100, K Viltersten wrote: > >> Coming from C++/Java camp i can't help noticing that in most cases, when >> i'm using a class written by somebody else, i don't want to see his/her >> code. I only want to know WHAT the function does (is intended to be >> doing, at least). >> >> I don't want to look at the source code (in some cases i can't even see >> the code because it's compiled). I only care that when i execute >> >> SomeType obj = SomeType(); >> obj.aggregate(); >> >> the object gets aggregated. How it's done will be up to the author. I'm >> just a user of the product. >> >> Now, i'm getting the signal that it's done in a different way in Python. >> Please elaborate. I'm very new to snakeology. > > > I think even Grant would agree that when you call "help(make_widget)", > you should see something like: > > make_widget(styleID, material) -> widget or > raise ValueError on failure > > styleID: numeric ID or string name of the widget style > material: WidgetMaterial instance or None to use default I think docstrings are a great idea. What's needed is a way to document the signature that can't get out-of-sync with what the fucntion really expects. -- Grant Edwards grante Yow! I'm wearing PAMPERS!! at visi.com From jjosburn at gmail.com Wed Mar 19 14:14:04 2008 From: jjosburn at gmail.com (black_13) Date: Wed, 19 Mar 2008 11:14:04 -0700 (PDT) Subject: modules devoted to manipulationg .reg files Message-ID: <12fdb0c5-f880-4264-86d1-be3ad2be8c51@c19g2000prf.googlegroups.com> are there any python modules for manipulation of .reg files producted by the win32 prog "reg". thanks. black_13 From mensanator at aol.com Wed Mar 19 20:15:29 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 19 Mar 2008 17:15:29 -0700 (PDT) Subject: slicing a list but in downward fashion References: Message-ID: <04cb8307-5e6c-4f44-ae9e-0315378579a5@e39g2000hsf.googlegroups.com> On Mar 19, 6:37?pm, Lee Sander wrote: > hi, > i have a list and i can get elements form it via slicing > L[start:stop] > but sometimes the start is > stop i.e. I want to go in the opposite > direction,eg > L[10:2], > > mattab lets you do L(10:-1:2) to achive this, is there a way to do > this in python? >>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] >>> a[3:10:2] [4, 6, 8, 10] >>> a[10:3:-2] [11, 9, 7, 5] > thanks > L From gandalf at shopzeus.com Tue Mar 18 06:09:32 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 18 Mar 2008 11:09:32 +0100 Subject: Decode email subjects into unicode In-Reply-To: <47DF8EED.1010501@shopzeus.com> References: <47DF8EED.1010501@shopzeus.com> Message-ID: <47DF94DC.7010205@shopzeus.com> Sorry, meanwhile i found that "email.Headers.decode_header" can be used to convert the subject into unicode: > def decode_header(self,headervalue): > val,encoding = decode_header(headervalue)[0] > if encoding: > return val.decode(encoding) > else: > return val However, there are malformed emails and I have to put them into the database. What should I do with this: Return-Path: X-Original-To: info at designasign.biz Delivered-To: dapinfo at localhost.com Received: from 195.228.74.135 (unknown [122.46.173.89]) by shopzeus.com (Postfix) with SMTP id F1C071DD438; Tue, 18 Mar 2008 05:43:27 -0400 (EDT) Date: Tue, 18 Mar 2008 12:43:45 +0200 Message-ID: <60285728.00719565 at optometrist.com> From: "Euro Dice Casino" To: thomas at designasign.biz Subject: With 2?500 Euro of Welcome Bonus you can?t miss the chance! MIME-Version: 1.0 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 7bit There is no encoding given in the subject but it contains 0x92. When I try to insert this into the database, I get: ProgrammingError: invalid byte sequence for encoding "UTF8": 0x92 All right, this probably was a spam email and I should simply discard it. Probably the spammer used this special character in order to prevent mail filters detecting "can't" and "2500". But I guess there will be other important (ham) emails with bad encodings. How should I handle this? Thanks, Laszlo From gagsl-py2 at yahoo.com.ar Fri Mar 7 10:18:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 13:18:20 -0200 Subject: Quit-command not quiting References: <63d2efF271u6hU1@mid.individual.net> Message-ID: En Fri, 07 Mar 2008 12:56:44 -0200, K Viltersten escribi?: > I entered the code from tkinter.pdf, section > 2 but for reason, the application doesn't > close as i press the quit-button. > > The wondow itself vanishes if i click the > cross in the upper-right corner but pressing > the quit-button only makes it "pressed". > Then, the program freezes. How did you run it? From inside IDLE? IDLE itself is written using Tk, and I think that your mainloop interferes with the one inside it. If you run your program from the command line it should work fine. > from Tkinter import * > class Demo (Frame): > def __init__ (self, master = None): > Frame.__init__ (self, master) > self.grid () > self.doLayout () > def doLayout (self): > self.quitButton = Button ( > self, > text = "Quit", > command = self.quit) > self.quitButton.grid () > > d = Demo () > d.master.title ("the coolest demo ever") > d.mainloop () There is only one thing I hate more than spaces after a parens: spaces before it :) Please read PEP8, about the suggested style for writting Python code. http://www.python.org/dev/peps/pep-0008/ -- Gabriel Genellina From ACooper at cimtek.com Mon Mar 10 11:54:37 2008 From: ACooper at cimtek.com (Cooper, Andrew) Date: Mon, 10 Mar 2008 11:54:37 -0400 Subject: Obtaining the PyObject * of a class Message-ID: I',m currently using SWIG to generate a python interface to a C DLL. I'm new to the Python C API and have a question that has been stumping me for the last week. As part of the wrapper process I want to hide some of the complexity with dealing with handles using a python class. But the problem I have is I don't know how to get the PyObject* that refers to the class Pin that I have defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } From durieux_br at yahoo.com.br Wed Mar 26 16:23:23 2008 From: durieux_br at yahoo.com.br (Salsa) Date: Wed, 26 Mar 2008 13:23:23 -0700 (PDT) Subject: Daylight savings time problem Message-ID: <585793.80038.qm@web90609.mail.mud.yahoo.com> I'm sorry, but could you be more specific? How exactly should I use UTC? -- Fabio Durieux Lopes - Salsa ----- Original Message ---- From: D'Arcy J.M. Cain To: Fabio Durieux Lopes Cc: python-list at python.org Sent: Wednesday, March 26, 2008 4:49:57 PM Subject: Re: Daylight savings time problem On Wed, 26 Mar 2008 19:37:16 -0000 "Fabio Durieux Lopes" wrote: > I'm trying to execute some operations based on a file's time. The > file's time is actually the file's name (e.g. FILE1_20080326170558). > So I do this: > fileTimeInSecs = time.mktime(time.strptime(timeString, > "%Y%m%d%H%M")) > > timeString contains the date part of the file's name. Function > strptime returns a time_struct, but my problem is that tm_isdst is > set to 0, and when we enter daylight savings time the file's time is > off by 1 hour. This time_struct is also read only so I can't change > tm_isdst to -1. > > Anyone knows how to fix it? Use UTC. -- 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. ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From brnstrmrs at gmail.com Thu Mar 13 11:46:05 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Thu, 13 Mar 2008 08:46:05 -0700 (PDT) Subject: scons Buffer.cpp Message-ID: <2a13b90c-52f4-4939-92f0-0e859c3987e8@m34g2000hsc.googlegroups.com> I am trying to install some libs but can not get them build properly. It seems to be looking for Buffer.cpp but can't find it any where . Here is the error message: scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... g++ -o AssociationRejection.o -c -I/usr/lib -I/usr/lib/boost AssociationRejection.cpp g++ -o Buffer.o -c -I/usr/lib -I/usr/lib/boost Buffer.cpp In file included from Buffer.cpp:1: Buffer.hpp:9:27: error: socket/Base.hpp: No such file or directory Buffer.hpp:10:35: error: socket/SwitchEndian.hpp: No such file or directory Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator<<(T)': Buffer.hpp:84: error: 'is_fundamental' is not a member of 'boost' Buffer.hpp:84: error: '::value' has not been declared Buffer.hpp:90: error: template argument 1 is invalid Buffer.hpp:95: error: template argument 1 is invalid Buffer.hpp:96: error: expected unqualified-id before '}' token Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(T&)': Buffer.hpp:103: error: 'is_const' is not a member of 'boost' Buffer.hpp:103: error: '::value' has not been declared Buffer.hpp:104: error: template argument 1 is invalid Buffer.hpp:105: error: template argument 1 is invalid Buffer.hpp:105: error: invalid type in declaration before ';' token Buffer.hpp:105: error: declaration of 'typedef int& data' shadows a parameter Buffer.hpp:109: error: 'pdata' was not declared in this scope Buffer.hpp:117: error: expected unqualified-id before '=' token Buffer.cpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(std::vector >&)': Buffer.cpp:38: error: 'SwitchVectorEndian' was not declared in this scope Buffer.cpp: In member function 'void dicom::Buffer::AddVector(const std::vector >&)': Buffer.cpp:112: error: 'SwitchVectorEndian' was not declared in this scope Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(T&) [with T = char]': Buffer.cpp:51: instantiated from here Buffer.hpp:105: error: declaration of 'typedef int& data' shadows a parameter Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(T&) [with T = UINT16]': Buffer.cpp:59: instantiated from here Buffer.hpp:105: error: declaration of 'typedef int& data' shadows a parameter scons: *** [Buffer.o] Error 1 scons: building terminated because of errors. From kaerbuhez at gmail.com Fri Mar 14 09:54:56 2008 From: kaerbuhez at gmail.com (kaerbuhez) Date: Fri, 14 Mar 2008 06:54:56 -0700 (PDT) Subject: find string in file References: Message-ID: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> On 14 mar, 14:25, fminerv... at gmail.com wrote: > Hi friends !! > > I'm neophite about python, my target is to create a programa that > find a specific string in text file. > How can do it? > > Thanks > fel $ cat text.txt aaa bbb ccc ddd aaa bbb ccc ddd aaa bbb ccc ddd aaa eee bbb eee ccc eee ddd eee $ cat bin/find_string.py import sys file_name=sys.argv[1] searched_string=sys.argv[2] result= [(line_number+1, line) for line_number, line in enumerate(open(file_name)) if searched_string in line] print result $ python bin/find_string.py text.txt eee [(8, 'aaa eee\n'), (9, 'bbb eee\n'), (10, 'ccc eee\n'), (11, 'ddd eee \n')] $ python bin/find_string.py text.txt aaa [(1, 'aaa\n'), (5, 'aaa bbb\n'), (7, 'aaa bbb ccc ddd\n'), (8, 'aaa eee \n')] $ python bin/find_string.py text.txt ddd [(4, 'ddd\n'), (6, 'ccc ddd\n'), (7, 'aaa bbb ccc ddd\n'), (11, 'ddd eee\n')] $ From bj_666 at gmx.net Mon Mar 3 01:59:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Mar 2008 06:59:42 GMT Subject: Character Problem References: Message-ID: <631luuF25g4d2U3@mid.uni-berlin.de> On Mon, 03 Mar 2008 04:27:52 +0200, Harun BAYKAL wrote: > I am studying on an addon developed for QGIS, a GIS software. But I > have a problem. The extension has been developed with QT and Python. > Actually Python is used for the interface design. For the user > interface Python reads some values from some database files. I am not > experienced Python user and the first developer of the addon had > written the python codes for his database. And his database > doesn't include any characters than the usual characaters. But my > database file contains many characters which are not used in English. > So I can not compile the extension because Python can not read the > database files. > > So how can I change the python files for making it to read the > databases without modifying the database. Otherwise I had to clear all > the non usual characters from the database file which means most of > the names and strings will be wrong. So somehow I had to make the > python files to read the other unicode and non english characters? > Anybody have any idea about how I can I fix such a problem. All I get from this description is, that you have a problem with encodings but what is the *specific* problem? Where does the program fail? With what exception(s)? Ciao, Marc 'BlackJack' Rintsch From tmp1 at viltersten.com Sat Mar 8 15:26:19 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 8 Mar 2008 21:26:19 +0100 Subject: Adjust a canvas as the window is resized Message-ID: <63ga4fF27edonU1@mid.individual.net> Do i need to set a callback to a canvas in order to "listen" to the root window being resized in order to make it adjust its contents? If so, how? If not, how do i make the canvas draw a line from one corner to an other? from Tkinter import * class Demo(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.grid() self.doLayout() master.geometry("800x600") def doLayout(self): canvas = Canvas(self, bd = 3, bg = "#93F") canvas.grid(column = 0, row = 0) canvas.create_line(0, 0, 100, 200, fill = "#FFF") def callback(self): print "callback from canvas" root = Tk() demo = Demo(root) root.mainloop() -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From gklein at xs4all.nl Wed Mar 19 05:11:18 2008 From: gklein at xs4all.nl (Gertjan Klein) Date: Wed, 19 Mar 2008 10:11:18 +0100 Subject: Decode email subjects into unicode References: <47DF8EED.1010501@shopzeus.com> Message-ID: <6gl1u3d3vei5tff9t6ivuhl7gf2qfg6p0k@4ax.com> Laszlo Nagy wrote: >However, there are malformed emails and I have to put them into the >database. What should I do with this: [...] >There is no encoding given in the subject but it contains 0x92. When I >try to insert this into the database, I get: This is indeed malformed email. The content type in the header specifies iso-8859-1, but this looks like Windows code page 1252, where character \x92 is a single right quote character (unicode \x2019). As the majority of the mail clients out there are Windows-based, and as far as I can tell many of them get the encoding wrong, I'd simply try to decode as CP1252 on error, especially if the content-type claims iso-8859-1. Many Windows mail clients consider iso-8859-1 equivalent to 1252 (it's not; the former doesn't use code points in the range \x8n and \x9n, the latter does.) Regards, Gertjan. -- Gertjan Klein From gagsl-py2 at yahoo.com.ar Fri Mar 28 09:41:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 10:41:46 -0300 Subject: Dynamic code problem References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> <8c7f10c60803280314q320884e8k9993592d688fec83@mail.gmail.com> Message-ID: En Fri, 28 Mar 2008 07:14:17 -0300, Simon Brunning escribi?: > On Thu, Mar 27, 2008 at 4:13 PM, wrote: >> My dynamic code failed at this site http://****/, need >> some help thank you. > > I assumed it was just spam, not a question. -- Gabriel Genellina From riccardocirello at gmail.com Tue Mar 25 07:54:38 2008 From: riccardocirello at gmail.com (cuordileone) Date: Tue, 25 Mar 2008 04:54:38 -0700 (PDT) Subject: Outlook 2003 and Python Message-ID: Good Day. I woul like to ask you if it is possible to make a program in python that move the email messages that I had received in outlook 2003, to a specific folder, accoding to the sender's name: Es: martin at martin.com -->> folder Martin. Thanks. Riccardo. From mensanator at aol.com Mon Mar 10 21:17:11 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 10 Mar 2008 18:17:11 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> Message-ID: On Mar 10, 6:32?pm, Nathan Pinno wrote: > On Mar 10, 12:10 pm, Mensanator wrote: > > > > > > > On Mar 10, 12:48 am, Gabriel Genellina wrote: > > > > On 10 mar, 02:08, Nathan Pinno wrote: > > > > > How do I factor a number? > > > If factoring is actually what you want, the sympy module can do it. > > > >>> n = 85085**3 > > >>> print n > > 615969217989125 > > >>> import sympy > > >>> f = sympy.factorint(n) > > >>> f > > > [(5, 3), (7, 3), (11, 3), (13, 3), (17, 3)]>>> ff = [[i[0]]*i[1] for i in f] > > >>> ff > > > [[5, 5, 5], [7, 7, 7], [11, 11, 11], [13, 13, 13], [17, 17, 17]]>>> fff = sympy.flatten(ff) > > >>> fff > > > [5, 5, 5, 7, 7, 7, 11, 11, 11, 13, 13, 13, 17, 17, 17] > > > Provided that your needs are modest. It claims to be > > able to handle 10 digit factors, but it certainly can't > > handle numbers of this magnitude: > > > 508184298003433059930221143303110332712493139579190463526792062622045893426?23811236647989889145173098650749 > > > As it takes a couple hours of run-time only to crash > > with an out of memory error. > > > If you need to handle something like that, you may want to > > get factor.exe which is part of the MIRACL library. The library > > is in C and doesn't have a Python interface, but you can run > > the .exe from Python and capture the output. > > > Keep in mind two things: factor.exe doesn't have consistent > > output making it more difficult to interpret the captured > > output. I re-compiled my copy of factor.exe to provide > > consistent output. > > > The other thing is that factor.exe sometimes gets confused > > claiming a number is composite that factor.exe is fully > > capable of factoring. Luckily this can be easily fixed in > > the Python program that calls it. > > > In the following example, if factor!.exe (my re-compiled > > version) returns any composites, I simply feed them back > > into the program until all are factored or determinened to > > be truly intractable. > > > Note the times. If you have serious factoring needs, the > > MIRACL solution is better than sympy. > > > ## ?======================================== > > ## ?Phase 1 > > ## ?['COMPOSITE_FACTOR', > > '50818429800343305993022114330311033271249313957919046352679206262204589342?623811236647989889145173098650749'] > > ## > > ## ?['PRIME_FACTOR', '37'] > > ## ?['PRIME_FACTOR', '43'] > > ## ?['PRIME_FACTOR', '167'] > > ## ?['COMPOSITE_FACTOR', '507787751'] > > ## ?['PRIME_FACTOR', '69847'] > > ## ?['PRIME_FACTOR', '30697'] > > ## ?['PRIME_FACTOR', '89017'] > > ## ?['PRIME_FACTOR', '3478697'] > > ## ?['PRIME_FACTOR', '434593'] > > ## ?['PRIME_FACTOR', '49998841'] > > ## ?['PRIME_FACTOR', '161610704597143'] > > ## ?['PRIME_FACTOR', '14064370273'] > > ## ?['COMPOSITE_FACTOR', '963039394703598565337297'] > > ## ?['PRIME_FACTOR', '11927295803'] > > ## > > ## ?0.860000133514 seconds > > ## ?======================================== > > ## ?Phase 2 > > ## ?['COMPOSITE_FACTOR', '507787751'] > > ## > > ## ?['PRIME_FACTOR', '29819'] > > ## ?['PRIME_FACTOR', '17029'] > > ## > > ## ?0.0780000686646 seconds > > ## ?======================================== > > ## ?Phase 3 > > ## ?['COMPOSITE_FACTOR', '963039394703598565337297'] > > ## > > ## ?['PRIME_FACTOR', '518069464441'] > > ## ?['PRIME_FACTOR', '1858900129817'] > > ## > > ## ?0.0469999313354 seconds > > ## ?======================================== > > ## > > ## ?Factoring complete > > ## > > ## ?PRIME_FACTOR 37 > > ## ?PRIME_FACTOR 43 > > ## ?PRIME_FACTOR 167 > > ## ?PRIME_FACTOR 17029 > > ## ?PRIME_FACTOR 29819 > > ## ?PRIME_FACTOR 30697 > > ## ?PRIME_FACTOR 69847 > > ## ?PRIME_FACTOR 89017 > > ## ?PRIME_FACTOR 434593 > > ## ?PRIME_FACTOR 3478697 > > ## ?PRIME_FACTOR 49998841 > > ## ?PRIME_FACTOR 11927295803 > > ## ?PRIME_FACTOR 14064370273 > > ## ?PRIME_FACTOR 518069464441 > > ## ?PRIME_FACTOR 1858900129817 > > ## ?PRIME_FACTOR 161610704597143 > > ## > > ## ?======================================== > > > > I mean how do I translate x! into proper > > > > Python code, so that it will always do the correct math? > > > > Do you want to compute x! (factorial of x)? That is, you want a > > > program that given a 4, returns 24? > > > Think how would you compute it by hand and try to write the same thing > > > using Python instructions. > > > > If you come with a program and have a specific problem someone here > > > will be able to help you, but don't expect your homework to be done > > > for free... > > > > -- > > > Gabriel Genellina > > Thanks on the factoring bit, but I did mean factorial, not factoring. > How do I code that correctly, so that I can figure the following > equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax > error and highlight the !. Because Python doesn't support the factorial operator. > So it would be nice to find a way to solve > such a problem. Instead of using MIRACL which doesn't have a Python interface, you could instaed get the GMP library which DOES have a Python interface (Google for gmpy, make sure to get the version that matches your Python version). Then you can do gmpy.fac(z-1) to get the factorial. or >>> import math >>> import gmpy >>> a = math.cos(gmpy.pi(0)*gmpy.fac(4-1)/4) >>> print a -1.83690953073e-016 > > Thanks, > Nathan P.- Hide quoted text - > > - Show quoted text - From sjmachin at lexicon.net Thu Mar 20 23:51:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Mar 2008 20:51:39 -0700 (PDT) Subject: Trouble with variable "leakage"? References: Message-ID: On Mar 21, 2:05 pm, Jeremy N wrote: > I am working with Python in Maya, and have run into a problem with a > variable changing its contents without being scripted to do so. The > various print() statements below were from my efforts to track down > where it was occurring. I left them in so that anyone running this > will more easily see what's happening. > > On the line that reads 'dx = d1 / dx ; print("dx = %f" % dx)' there > is something happening to the variable that is being printed > repeatedly between the lines. The print statements prior to this > particular line print '...xlist[0][1] = 0.5' . However, on this > line, that variable is being updated to reflect a new value, when no > assignment to that variable has been made at that time. > > This leads me to believe that the variables 'dx' and 'xlist[0][1]' > are inexplicably linked. Actually xlist[i] and ylist[i] are explicably the same for all relevant values of i. > I have no idea why. Please help me. Keep reading ... > > a=[5,0,3,4] > b=[8,3,0,10] > c=[2,4,10,0] > > nlist = [a,b,c] > xlist = [[],[],[]] > > for i in range(len(nlist)) : > relist = list(nlist) > relist.pop(i) Aside: I am NOT going to try to guess what your algorithm should do; I just hope you know what the above is doing ... like why not del relist[i] if you're not interested in the popped value? > dlist = list(nlist[i]) > dlist.pop(0) ; dlist.pop(i) > for j in range(len(relist)) : > d1 = float(nlist[i][0]) > d2 = float(relist[j][0]) > dx = float(dlist[j]) > r1 = 1 - ( abs(d1-dx) / float(d2) ) > if r1 == 0.0 : > r1 += (d1 < d2) > xlist[i].append(float(r1)) > > del d1, d2, dx, relist, dlist > > ylist = list(xlist) insert here: print [id(e) for e in xlist], [id(e) for e in ylist] You'll see that list(xlist) gives you a shallow copy i.e. it doesn't dig deeper and copy the contents of the lists at the next level. You need the deepcopy function of the copy module -- do read the docs. Aside #2: "print" is a statement, not a function. > print(xlist) > print(ylist) > [snip] HTH, John From gagsl-py2 at yahoo.com.ar Tue Mar 25 15:52:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 16:52:50 -0300 Subject: Files, directories and imports - relative to the current directory only References: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> <64suvmF2d8hphU1@mid.individual.net> Message-ID: En Tue, 25 Mar 2008 15:35:34 -0300, Bjoern Schliessmann escribi?: > ptn wrote: >> Traceback (most recent call last): >> File "path.py", line 4, in >> f = open('~/read/foo.txt') >> IOError: [Errno 2] No such file or >> directory: '~/read/foo.txt' >> [...] >> So, what's wrong here? Maybe there's something I haven't set up? > > Simple: the directory "~" doesn't exist. Since you're not using a > shell (but direct file access) there is no tilde expansion, and "~" > is treated as a regular file name. If you need to get the home > directory refer to the environment variable HOME > (os.environ["HOME"]). There even may be a shorter way, please refer > to the os module docs. That shorter way being os.path.expanduser http://docs.python.org/lib/module-os.path.html -- Gabriel Genellina From ptmcg at austin.rr.com Thu Mar 6 14:35:06 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 6 Mar 2008 11:35:06 -0800 (PST) Subject: Exploring Attributes and Methods References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: On Mar 6, 1:14?pm, "keios.ti... at gmail.com" wrote: > Hi, > ?Is there a python command that allows me to extract the names (not > values) of the attributes of a class. > > example > > Class Sample: > ? ? fullname = 'Something' > > How can I know that this class has an attribute called 'fullname'? > > I hope my question is clear. > Thanks If you had posted actual working code, "Class" would be all lower case ("class"). But we get the drift (in general, though, when posting questions about examples from your code, best to copy-paste the actual code, not a paraphrasing of it): print Sample.__dict__.keys() prints: ['__module__', 'fullname', '__doc__'] -- Paul From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 12:24:06 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 18:24:06 +0100 Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> Message-ID: <20080302182406.d9d27c83.randhol+valid_for_reply_from_news@pvv.org> On Sun, 2 Mar 2008 06:15:54 -0800 (PST) Giles Brown wrote: > http://docs.python.org/lib/typeiter.html Thanks! From barronmo at gmail.com Wed Mar 26 19:47:45 2008 From: barronmo at gmail.com (barronmo) Date: Wed, 26 Mar 2008 16:47:45 -0700 (PDT) Subject: subtract dates with time module Message-ID: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> I'm trying to get the difference in dates using the time module rather than datetime because I need to use strptime() to convert a date and then find out how many weeks and days until that date. I'm a beginner so any help would be appreciated. Here is the code: def OBweeks(ptID): qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % (ptID) results = EMR_utilities.getAllData(qry) for items in results: r = re.search('\d\d\d\d-\d\d-\d\d', items) if r: d = time.strptime(r.group(), "%Y-%m-%d') - time.localtime() weeks, days = divmod(d.days, 7) return '%s %s/7 weeks' % (weeks, days) This isn't working. I'm getting "unsupported operand type for -: 'time.struct_time' and 'time.struct_time" error. Thanks, Mike From mentaltruckdriver at gmail.com Sat Mar 1 19:51:08 2008 From: mentaltruckdriver at gmail.com (mentaltruckdriver at gmail.com) Date: Sat, 1 Mar 2008 16:51:08 -0800 (PST) Subject: Python Telnet formatting? Message-ID: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Hi everyone: I posted here a couple days ago looking for some help creating a Telnet-based chat server. You guys pointed me to Twisted, which has solved most of my issues. However, what I want to do is analyze strings received for keywords such as 'listcmds' and have the server return something to the client. I know how to do that part, at least. The issue is, when I use clients like PuTTY, it returns a lot of what appears to be formatting (e.g. if I typed Hello, it would return "\xff \xfb\x1f\xff\ xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) How would I go about filtering this stuff out of the strings? The thing is too, if I use other Telnet programs like Microsoft Telnet, they don't have this formatting, so I want to be able to recognize if it does have this formatting and act based on if it does or if it doesn't. Any help is appreciated, I know I'm probably asking too many questions already :) Thanks everyone. From Lie.1296 at gmail.com Sun Mar 9 00:07:48 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 21:07:48 -0800 (PST) Subject: Python installation problem References: Message-ID: <7dd898c6-da57-4bb2-8077-4455b1cf8eaf@e10g2000prf.googlegroups.com> On Mar 9, 11:42?am, cosmo_gene... at yahoo.com wrote: > Hi Folks, > > I downloaded a pre-compiled version 2.5, and intalled it without any > error message; and I can command line playing on Python through firing > up IDLE or command-line. However, I just can't compile the python file > existing in a directory. Today, I tried to fire Python in a DOS > window, then I got error message: Python is not a runnable command or > batch file. It means that the eveiornment variables of my Python > interpreter are not set well yet. My computer runs a Windows XP. > Anyboy can help on this? Thanks! > > Muddy Coder AFAIK, Python doesn't set environment variables in Windows. To change the environment variable, you go to Control Panel > System > Advanced > Environment Variables > System Variables > In "Path" entry, add Python's installation directory to the end of it (remember to separate it from other directories with semicolons ; Alternatively, you can cd your way through python's directory and always feed absolute path to python.exe, very tiresome, but doesn't require you to add the environment variable. From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:08:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:08:00 -0200 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: En Sat, 01 Mar 2008 22:51:08 -0200, escribi?: > Hi everyone: > > I posted here a couple days ago looking for some help creating a > Telnet-based chat server. You guys pointed me to Twisted, which has > solved most of my issues. > > However, what I want to do is analyze strings received for keywords > such as 'listcmds' and have the server return something to the client. > I know how to do that part, at least. > > The issue is, when I use clients like PuTTY, it returns a lot of what > appears to be formatting (e.g. if I typed Hello, it would return "\xff > \xfb\x1f\xff\ > xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) They are part of the telnet protocol; 0xFF (IAC=Interpret as Command) starts a two or three byte command sequence. Weren't you using telnetlib? It's supposed to handle this transparently. > How would I go about filtering this stuff out of the strings? The > thing is too, if I use other Telnet programs like Microsoft Telnet, > they don't have this formatting, so I want to be able to recognize if > it does have this formatting and act based on if it does or if it > doesn't. Any client could send similar commands at the start of the session, or even later. > Any help is appreciated, I know I'm probably asking too many questions > already :) It isn't too hard to filter them out, if you want to do it by hand. See the source for telnetlib, and the original Telnet specificacion, RFC 854 http://www.rfc-archive.org/getrfc.php?rfc=854 and RFC 855. -- Gabriel Genellina From samslists at gmail.com Mon Mar 17 22:20:25 2008 From: samslists at gmail.com (samslists at gmail.com) Date: Mon, 17 Mar 2008 19:20:25 -0700 (PDT) Subject: Any fancy grep utility replacements out there? Message-ID: So I need to recursively grep a bunch of gzipped files. This can't be easily done with grep, rgrep or zgrep. (I'm sure given the right pipeline including using the find command it could be done....but seems like a hassle). So I figured I'd find a fancy next generation grep tool. Thirty minutes of searching later I find a bunch in Perl, and even one in Ruby. But I can't find anything that interesting or up to date for Python. Does anyone know of something? Thanks From arnodel at googlemail.com Sun Mar 16 09:28:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 16 Mar 2008 13:28:19 GMT Subject: Advantage of the array module over lists? References: Message-ID: Tobiah writes: > I checked out the array module today. It claims that > arrays are 'efficient'. I figured that this must mean > that they are faster than lists, but this doesn't seem > to be the case: > > ################ one.py ############## > import array > > a = array.array('i') > > for x in xrange(10000000): > a.append(x) > > for x in a: > a[x] += 1 > > ################ two.py ############## > a = [] > > for x in xrange(10000000): > a.append(x) > > for x in a: > a[x] += 1 > > ###################################### > > > ktops:toby:pytest> time python one.py; time python two.py > > real 0m28.116s > user 0m17.504s > sys 0m10.435s > > real 0m23.026s > user 0m13.027s > sys 0m9.777s > > > Perhaps the only advantage is that they take less memory > to store a large number of items? It would seem then, that > 'economical' might have been a better choice of word than > 'efficient'. I get an even bigger difference with this test (same as yours, but using timeit and using an allegedly more efficient way of initialising the array) >>> def test(arr, n): ... a = arr(xrange(n)) ... for x in a: ... a[x] += 1 ... >>> n = 10000000 >>> import timeit >>> timeit.Timer('test(list, n)', 'from __main__ import test, n').timeit(1) 2.4988760948181152 >>> from array import array >>> arr = lambda n: array('i', n) >>> timeit.Timer('test(arr, n)', 'from __main__ import test, arr, n').timeit(1) 5.7419960498809814 >>> -- Arnaud From torriem at gmail.com Thu Mar 6 11:21:42 2008 From: torriem at gmail.com (Michael L Torrie) Date: Thu, 06 Mar 2008 09:21:42 -0700 Subject: Hi In-Reply-To: References: Message-ID: <47D01A16.5080104@gmail.com> hellogaurang at gmail.com wrote: > Hello > > can u plz tell how to send and read msg from device(telit-863-GPS) and > the coding is in python. > > if this can happen then plz send the source code to my mail account Sounds like a new development model. You should patent this. Just e-mail lists with cryptic requests for code, then combine the resulting fragments into one executable. In fact, if you do it in chain letter form, you can get code even faster. I heard a rumor once that's how Windows Me was originally built. From lialie at gmail.com Fri Mar 28 12:58:34 2008 From: lialie at gmail.com (KingMax) Date: Fri, 28 Mar 2008 09:58:34 -0700 (PDT) Subject: Problem with write binary data to OLE field in Access References: <47EA77FB.3080706@gmail.com> Message-ID: <1a1cde72-051b-468b-a470-3441fa621dcd@e6g2000prf.googlegroups.com> On 3?27?, ??7?22?, Tim Golden wrote: > lialie wrote: > > [... snip slightly confused indication that reading back a > binary item using GetChunk appears to double its length ...] > > Well I don't know why this should be happening, but I do at > least have a few suggestions: > > 1) Try using ADODB.Stream instead of GetChunk etc. > > 2) Try using the adodbapi dbapi-compliant wrapper > > 3) Try using ODBC (via PyODBC, CeODBC etc.) > > I've no idea if any of these will do any better but at > least it gives you some possibilities :) > > TJG Thanks! I try using ADODB.Stream to implement it. But the situation is the same. At last, I try this, and it seems to work. 1) Save the image to the dist. 2) using ADODB.Stream.LoadFromFile 3) Save it into access and then first step done. when using it, I try this: 1) ADODB.Stream.Write(Record.Fields("xxx").Value) 2) ADODB.Stream.SaveToFile("test.jpg") 3) using wxImage to load it in. a little stupid :( From gherron at islandtraining.com Sat Mar 8 11:47:45 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 08 Mar 2008 08:47:45 -0800 Subject: parralel downloads In-Reply-To: References: Message-ID: <47D2C331.4020708@islandtraining.com> poof65 wrote: > For your problem you have to use threads. > Not at all true. Thread provide one way to solve this, but another is the select function. For this simple case, select() may (or may not) be easier to write. Pseudo-code would look something like this: openSockets = list of sockets one per download file: while openSockets: readySockets = select(openSockets ...) # Identifies sockets with data to be read for each s in readSockets: read from s and do whatever with the data if s is at EOF: close and remove s from openSockets That's it. Far easier than threads. Gary Herron > You can have more information here. > http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > >> Hi, >> >> I would like to write a python script that will download a list of >> files (mainly mp3s) from Internet. For this, I thought to use urllib, >> with >> >> urlopen("myUrl").read() and then writing the resulting string to a >> file >> >> my problem is that I would like to download several files at the time. >> As I have not much experience in programming, could you point me the >> easier ways to do this in python ? >> >> Thanks, >> >> JD >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> From davecook at nowhere.net Sun Mar 2 06:16:37 2008 From: davecook at nowhere.net (David Cook) Date: Sun, 02 Mar 2008 11:16:37 GMT Subject: Book Recomendations References: Message-ID: On 2008-03-02, Jeff Schwab wrote: > Python In A Nutshell: > http://www.oreilly.com/catalog/pythonian2/ Another vote for the Nutshell book, which I find a very useful and practical book. I never found the "Dive in" book useful. Dave Cook From jeff at schwabcenter.com Sat Mar 22 17:10:39 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 14:10:39 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Anyway, here the conclusion that I draw: learn lambda-calculus and > Turing machines. The rest is syntactic sugar. How is the lambda-calculus fundamentally different from Turing machine-based implementations? I've been learning a fair amount about functional programming recently, mostly because compile-time C++ turns out to be a pure functional programming language. Where should I go for a solid grounding in lambda-calculus? Also, despite reassurances to the contrary, I still get the impression that there is a strong anti-lambda sentiment among the Python "in" crowd. Is it just a question of the word "lambda," as opposed to perceived cleaner syntax? http://www.artima.com/weblogs/viewpost.jsp?thread=98196 http://www.python.org/dev/peps/pep-0290/#replacing-common-uses-of-lambda -- Said the Rabbi Hillel, "All the rest is commentary." From python.list at tim.thechases.com Wed Mar 5 07:12:40 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 05 Mar 2008 06:12:40 -0600 Subject: Using re module better In-Reply-To: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> Message-ID: <47CE8E38.80201@tim.thechases.com> > if (match = re.search('(\w+)\s*(\w+)', foo)): Caveat #1: use a raw string here Caveat #2: inline assignment is verboten match = re.search(r'(\w+)\s*(\w*+)', foo) if match: > field1 = match.group(1) > field2 = match.group(2) This should then work more or less. However, since you know there are two matches, you can just use field1, field2 = match.groups() If the regexp is one you plan to reuse (or call in a loop), you can pre-compile it: r = re.compile(r'(\w+)\s*(\w*+)') for thing in bunch_of_things: m = r.search(thing) if m: field1, field2 = m.groups() do_something(field1, field2) HTH, -tkc From gherzig at fmed.uba.ar Fri Mar 14 08:30:46 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 14 Mar 2008 09:30:46 -0300 Subject: request for Details about Dictionaries in Python In-Reply-To: References: Message-ID: <47DA6FF6.5000505@fmed.uba.ar> Saideep A V S wrote: >Hello Sir, > > I am a beginner level programmer in Python. I am in search of a >function for 'On-Disk' Dictionaries which is similar to On-Disk Hash tables >in Perl (i.e., tie function in Perl). > > > Could anyone help me with the concept. I have also searched the net, but >was not successful in finding any related. > >Awaiting your Solutions. > >Thanks in Advance. > >Saideep > > > I guess you are looking for shelve http://docs.python.org/lib/module-shelve.html Gerardo From noorhanabbas at yahoo.co.uk Sun Mar 2 09:04:16 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Sun, 2 Mar 2008 14:04:16 +0000 (GMT) Subject: Sparta api Message-ID: <908801.95306.qm@web27409.mail.ukl.yahoo.com> Hello, I wonder if anybody has used the sparta api for linking RDF to Python. I was trying to run the example supplied by sparta and I got this error message Traceback (most recent call last): File "C:/Python25/TestSpartaApi.py", line 10, in store = Graph() File "C:\Python25\lib\rdflib\Graph.py", line 265, in __init__ self.__store = store = plugin.get(store, Store)() File "C:\Python25\lib\rdflib\rdflib\plugin.py", line 27, in get raise Exception("could not get plugin for %s, %s: %s" % (name, kind, e)) Exception: could not get plugin for default, : Any idea what is the problem? Noorhan __________________________________________________________ Sent from Yahoo! Mail. A Smarter Inbox. http://uk.docs.yahoo.com/nowyoucan.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Wed Mar 5 22:51:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:51:35 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> <7a8a2706-10d0-4f50-b5ad-8b490e57edd5@y77g2000hsy.googlegroups.com> Message-ID: <44a11efa-f1d7-458c-93f0-f0d6f744dfcd@m34g2000hsc.googlegroups.com> > > > If I understand your question, classes are not singletons: > > >>>> ll=[] > > >>>> for i in range(2): > > > ?import string > > > ?ll[i]=string > > > Where's the IndexError? :-) > > > I accept my question about classes being singletons is not well-formed, > > not even in my own mind. I guess one way of asking is, for any two class > > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? Similarly, no. >>> class metaC( type ): ... def __eq__( self, other ): ... return True ... >>> class C( metaclass= metaC ): ... pass ... >>> class D( metaclass= metaC ): ... pass ... >>> C==D True >>> C is D False +1 raised eyebrow From bronger at physik.rwth-aachen.de Mon Mar 17 03:47:53 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 17 Mar 2008 08:47:53 +0100 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> Message-ID: <873aqp6bbq.fsf@physik.rwth-aachen.de> Hall?chen! Carl Banks writes: > On Mar 16, 10:49 pm, Brian Jones wrote: >> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: >> >>> If you did not like the programming this year (aside from the >>> sponsor talks) and you did not participate in organizing PyCon >>> or in delivering presentations, it is YOUR FAULT. PERIOD. >>> EXCLAMATION POINT! >> >> I find this insulting, inexcusable, and utter nonsense. If >> putting the blame for a failed experiment on the backs of the >> good folks who paid good money for travel, lodging, and >> registration is also an experiment, you can hereby consider it >> also failed. > > He said "aside from the sponsor talks", chief. I see no reason why the "fault" for parts of the rest being sub-optimal, too, must necessarily be on the attendee's side. (Just hypothetically; I wasn't at PyCon.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From andrew-news at andros.org.uk Fri Mar 28 14:11:56 2008 From: andrew-news at andros.org.uk (Andrew McLean) Date: Fri, 28 Mar 2008 18:11:56 +0000 Subject: Instrumented web proxy In-Reply-To: <7xod8zrhb9.fsf@ruckus.brouhaha.com> References: <7xod8zrhb9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Andrew McLean writes: >> I would like to write a web (http) proxy which I can instrument to >> automatically extract information from certain web sites as I browse >> them. Specifically, I would want to process URLs that match a >> particular regexp. For those URLs I would have code that parsed the >> content and logged some of it. >> >> Think of it as web scraping under manual control. > > I've used Proxy 3 for this, a very cool program with powerful > capabilities for on the fly html rewriting. > > http://theory.stanford.edu/~amitp/proxy.html This looks very useful. Unfortunately I can't seem to get it to run under Windows (specifically Vista) using Python 1.5.2, 2.2.3 or 2.5.2. I'll try Linux if I get a chance. From johan.de.taeye at gmail.com Tue Mar 18 03:51:58 2008 From: johan.de.taeye at gmail.com (jdetaeye) Date: Tue, 18 Mar 2008 00:51:58 -0700 (PDT) Subject: Extending C++ with Python scripting: "twin objects" or "proxy objects"? Message-ID: <27add36a-dab9-4528-9f2f-6732e92aa8bc@p73g2000hsd.googlegroups.com> Hi, I would like to use Python as a scripting language for a C++ framework I am working on. The most common approach for this seems to be a "twin objects": the python and the C++ object have the same lifespan and are always linked to each other. My initial thinking was to use a "proxy approach" instead: the python object is only a temporary proxy object with a pointer to the real C++ object. The C++ object would live much longer than the proxy. Is the proxy approach a valid alternative? I can't imagine it hasn't been done before... I am interested in hearing your experiences with it... Currently I see the following + and -: + Easier for the C++ code (ie less changes, less coupling, no gc- issues) - Extending the framework through subclasses in Python is much harder Anything else? Regards, Johan From arnodel at googlemail.com Mon Mar 24 09:48:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Mar 2008 06:48:10 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> Message-ID: <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> On Mar 24, 1:26?pm, Steven D'Aprano wrote: > On Mon, 24 Mar 2008 04:33:53 -0400, Terry Reedy wrote: > > The fact that .func_name (which is writeable) is not used at first > > surprised me until I remembered that code objects can potentially be > > used by multiple function objects and hence are not connected to any one > > in particular. > > How does that happen? Like this: >>> def foomaker(x): ... def foo(y): return x+y ... return foo ... >>> foo1 = foomaker(1) >>> foo2 = foomaker(2) >>> foo1.func_code ", line 2> >>> foo2.func_code ", line 2> Of course foo1 and foo2 are not the same thing: >>> foo1(8) 9 >>> foo2(8) 10 > And if it is the case, what's the justification for giving them a co_name > attribute? Surely the name of the function should be that of the function > object, not of one of the shared parts? >>> foo1.__name__ 'foo' >>> foo1.func_code.co_name 'foo' As seen above, func.__name__ and func.func_code.co_name are the same thing (until tampered with). -- Arnaud From Lie.1296 at gmail.com Sun Mar 2 01:33:21 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 1 Mar 2008 22:33:21 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> <7x3ara9r4n.fsf@ruckus.brouhaha.com> Message-ID: On Mar 2, 2:32?am, Paul Rubin wrote: > Lie writes: > > I see, but the same arguments still holds true: the second line have > > an implicit side-effect of redefining x's type into Fractional type. > > If I were the designer of the language, I'd leave x's type as it is > > (as Num) and coerce x for current calculation only. > > Num in Haskell is not a type, it is a class of types, i.e. if all you > know about x is that it is a Num, then its actual type is > indeterminate. ?Types get inferred, they do not get coerced or > "redefined". ?The compiler looks at expressions referring to x, to > deduce what x's type actually is. ?If it is not possible to satisfy > all constraints simultaneously, then the compiler reports an error. So basically they refused to satisfy everything that is still possible individually but would conflict if done together. (I know Haskell not more than just its name so I don't understand the rationale behind the language design at all) But I'm interested in how it handles these cases: x = 1 a = x + 1 << decides it's an int b = x + 1.0 << error? or redefine to be float? c = x + 1 << would this cause error while it worked in line 2? A slightly obfuscated example: l = [1, 1.0, 1] x = 1 for n in l: c = x + n From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:42:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:42:08 -0300 Subject: Python and Db References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> Message-ID: En Mon, 31 Mar 2008 14:50:27 -0300, David Anderson escribi?: > Hi! I'm don't know almost nothing about bds, Can You suggest me an Simple > but efficient Bd to work with python apps? Can You suggest me any > tutorials? See the Python wiki at: http://wiki.python.org/moin/DatabaseProgramming If you stick with DBAPI 2.0 you won't have much trouble writing for one database or another. sqlite is a good start and is included with Python 2.5 -- Gabriel Genellina From stargaming at gmail.com Wed Mar 12 09:00:58 2008 From: stargaming at gmail.com (Stargaming) Date: 12 Mar 2008 13:00:58 GMT Subject: catching object References: Message-ID: <47d7d40a$0$2659$9b622d9e@news.freenet.de> On Wed, 12 Mar 2008 01:05:06 +0100, Igor V. Rafienko wrote: > Hi, > > > I was wondering if someone could help me explain this situation: > > h[1] >>> import inspect > h[1] >>> inspect.getmro(ValueError) > (, , > , , 'object'>) > h[2] >>> try: > raise ValueError("argh") > except object: > print "why not?" > > Traceback (most recent call last): > File "", line 2, in > ValueError: argh > > The question is, why isn't ValueError caught? It *does* inherit from > object (albeit indirectly), and my understanding of the wording of > CPython docs is that this guarantees "compatibility" (between what is > being raised and what is being caught). I think inheritance is meant in reference to the Exception tree here. So, the uppermost class is `BaseException`. Python 3 gives this exception when trying to handle `object`:: TypeError: catching classes that do not inherit from BaseException is not allowed You are right, the wording is quite confusing here but that might be due to the crude situation of exceptions: All old-style classes (deprecated themselves) can be raised. Strings can still be raised but this is deprecated. New-style classes can be raised but only if they inherit (at least indirectly) from BaseException. I'd say: feel free to contribute patches. :-) > So, why doesn't object match ValueError (or any other exception for that > matter). I am aware of "except:", but in my particular situation it is > eh... unsuitable. Why so? The only possible solution me and my crystal ball could come up with is that you're having a lot of old-style exceptions raised from some library you cannot modify. You cannot handle any common base class and don't want to handle every of the exceptions. If that's the case, just use a bare `except` and utilize `sys.exc_info`. HTH, From karunakaran341 at gmail.com Tue Mar 18 03:39:26 2008 From: karunakaran341 at gmail.com (karunakaran341 at gmail.com) Date: Tue, 18 Mar 2008 00:39:26 -0700 (PDT) Subject: please click here Message-ID: <6f738f23-8ac0-41b3-9d44-e7016a6613f3@e10g2000prf.googlegroups.com> please click here **************************************************** http://profile_myprofile.blogspot.com **************************************************** From sjmachin at lexicon.net Sun Mar 23 20:58:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 17:58:03 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> On Mar 24, 11:42 am, George Sakkis wrote: > On Mar 23, 8:01 pm, QS wrote: > > > > > Hi to all! > > I am new to python, and I encountered a weird problem. > > > Here is my code > > > ##########>8#################### > > #!/usr/bin/python > > # Filename: objvar.py > > class Person: > > '''Represents a person.''' > > > population = 0 > > #sex = 'F' > > #age = 22 > > # It is vague here: is this variable going to be a class, or > > object, variable > > > def __init__(self, name, sex): > > '''Initializes the person's data.''' > > self.name = name > > self.sex = sex > > print '(Initializing %s )' % self.name > > # When this person is created, he/she > > # adds to the population > > Person.population += 1 > > > def __del__(self): > > '''I am dying.''' > > > print '%s says bye.' % self.name > > Person.population -= 1 > > if Person.population == 0: > > print 'I am the last one.' > > else: > > print 'There are still %d people left.' % > > Person.population > > > def sayHi(self): > > '''Greeting by the person. > > > Really, that's all it does.''' > > > self.age = 25 > > print 'Hi, my name is %s, and I am %s, and I am age %d ' % > > (self.name, self.sex, self.age) > > > def howMany(self): > > '''Prints the current population.''' > > if Person.population == 1: > > print 'I am the only person here.' > > else: > > print 'We have %d persons here.' % Person.population > > > swaroop = Person('Swaroop', 'M') > > swaroop.sayHi() > > swaroop.howMany() > > kalam = Person('Abdul Kalam', 'M') > > kalam.sayHi() > > kalam.howMany() > > cathy = Person('Catherine', 'F') > > cathy.sayHi() > > cathy.howMany() > > swaroop.sayHi() > > swaroop.howMany() > > > ############# 8< ######################### > > > When I run this script, I got the following exception: > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'population'" in > <__main__.Person instance at 0xb7d8ac6c>> ignored > > > To to newcomer like me, this message doesn't make much sense. What > > seems weird to me is that, if I change the variable cathy to something > > else, like cath, or even cat, then the script will finish gracefully. > > Why "cathy" is not liked?!! > > > Some of you may have recognized that the code is derived from a sample > > code in Swaroop's "A byte of python". > > > My python is of version 2.5.1, on Ubuntu. > > That's really weird... it's reproducible on Windows too. It doesn't > make any sense why the name of the variable would make a difference. > My guess is you hit some kind of obscure bug. > My guess after reading the manual: """ Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted. For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. """ is that farnarkeling about in a __del__ method is *not* a good idea. From jari.aalto at cante.net Sat Mar 8 05:47:33 2008 From: jari.aalto at cante.net (Jari Aalto) Date: Sat, 08 Mar 2008 12:47:33 +0200 Subject: distutils - Is is possible to install without the .py extensions References: Message-ID: * Fri 2008-03-07 Robert Kern gmane.comp.python.general * Message-Id: fqt61a$sj5$1 at ger.gmane.org >>>> setup(name='program', >> ... >>>> scripts = ['program,py'], >>>> ) >>>> that the the result is: >>>> >>>> /usr/bin/program >>>> >>>> instead of: >>>> >>>> /usr/bin/program.py >>> >>> The easiest and best way is to just rename the file in your source tree to >>> "program" and be done with it. >> >> Is there any other way? This is the source package that I would like >> to keep intact and just patch the setup.py > > Not really, no. Why is it so important to only patch the setup.py > file and not any others? It has to do with generating a diff against the original package. If the file is moved: mv file.py file prior setup.py run (which, according to answers, would have a change to <>), the problem is the generated diff against original sources: + would flag removal of 'file.py' + inclusion of 'file' The ideal would be if setup.py could do all the destination install "postwork". The generated patch would be clean and only contain changes in setup.py. But I understand, if distutils does not support stripping the extensions during install. It just cacuses exra work for utility packagers. Jari -- Welcome to FOSS revolution: we fix and modify until it shines From morse at edoug.org Sun Mar 16 05:22:12 2008 From: morse at edoug.org (Doug Morse) Date: Sun, 16 Mar 2008 09:22:12 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: <97432b58-958c-43ec-b48a-6849f9abed4a@v3g2000hsc.googlegroups.com> Message-ID: Hi Harald, Bond here, James Bond. I accepted your mission. :) Unfortunately, the mission failed. Creating a "testapp.py" as you described (i.e., with the suggested import statements) runs just fine with the interpreter. again, however, py2exe does the same thing as the original problem -- that is, copies numpy.core's versions of multiarray.pyd and umath.pyd into dist/, creates what look like stub multiarray.pyc and umath.pyc files in library.zip/ and library.zip/numpy/core/. when this py2exe version is run, it throws the same (original) TypeError: data type not understood error. Also, with either my original program or testapp.py, I cannot seem to modify library.zip in such a way as to get the program to run. Basically, I unzipped library.zip, made the same modifications to it's contents as I did when using the --skip-archive option (i.e., remove the stub files and put the right .pyd files in the right locations) and then recreated the library.zip file. Afterwards, running either origapp.exe or testapp.exe, the program bombs out with ImportError: no module named multiarray. In addition, I tried using py2exe to make a simple "Hello, world" program. It runs just fine. Then, I "zip -m library.zip *.pyd" in the dist/ directory to move the .pyd files into library.zip. Then, running hello.exe again works just fine. However, if I add "import bz2; print bz2.__author__" after "print 'Hello, world!'" (the only line in hello.py), hello.exe bombs out with "ImportError: DLL load failed: The specified module could not be found" when I run it after having moved *.pyd into library.zip/. (bz2 was one of only two .pyd files that py2exe put into dist/.) So, I can seem to figure out how to get .pyd files into library.zip, even when there are no name conflicts. What am I doing wrong? Finally, regarding the stub files, if I use vi to edit the py2exe-generated, 536-byte bz2.pyc file (there is no such file in my python install directory hierarchy), I see the word "import" very close to the word "bz2.pyd". This suggests to me that py2exe might indeed be creating simple import statements in a short .py file for each .pyd file and then compiling it into a .pyc stub file -- or at least doing something similar. Of course I can't be sure of this, but it seems likely to me. Thanks again to you and everyone. I'll definitely visit the py2exe wiki and see what I can come up with (and or course will report back with success / failures). If you or anyone has any further thoughts based on this post, I'm all ears and would be most grateful. Regards, Doug On Sun, 16 Mar 2008 00:33:31 -0700 (PDT), GHUM wrote: > Doug, > > > as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. > > I'm guessing that they can't be in library.zip for a reason (i.e., they are > > DLL files, essentially, and thus must be readily available to be loaded > > into memory). > > .dll and .pyd files CAN be within library.zip and even within the > single-file-exe. > > There is some Hellermagic within _memimporter.pyd that loads the .dll > and .pyd from a zipfile. When you scan the build_exe.py, you will > explicitely find: > > print "*** finding dlls needed ***" > dlls = self.find_dlls(extensions) > self.plat_finalize(mf.modules, py_files, extensions, dlls) > dlls = [item for item in dlls > if os.path.basename(item).lower() not in > self.dll_excludes] > # should we filter self.other_depends in the same way? > > > Is there a work-around for this, then? > -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd > -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/ > multiarray.pyd > -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/ > umath.pyd > -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd > > let's try: your mission is, should you chose to accept it, to make a > py2exed application to load two different multiarray.pyd, who are on > the visible level only different by their place in the file system. > > So, please make a minimal script: > > import multiarray > import numpy.core.multiarray as ncmultiarray > > and, using Peters test > >>> from multiarray import zeros > assert zeros((1,), "1") == array([0], '1') > > and check, if those multiarrays are the correct ones. If yes, you can > try to build upon this by making all imports explicit as described > above. (Yes, I know, that's not necessary in plain python ... but it > saved me in some weird "import from .zip" and "import from database" > situations.) > > > (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and > > umath.pyd files > > somewhere deep inside I have a BAAAD feeling about to files having the > same name but very very different content - but that's not your call > in this situation. > Are you able to build that libraries yourself? Then you could move > down and build the multiarray.pyd as ncmultiarray.pyd and adjust all > imports accordingly. (lots of work) > > > manual create the "stub"-like .pyc files that py2exe creates to point to > > these alternate .pyd files and then place these stubs in > > library.zip/numpy/core? ? > > As much as I know there is only one central "loader stub", which > ensures that .dlls get imported from memory, see above. py2exe does > not create something like p2elma.py containing "import multiarray.pyd" > > best luck, and please take your time to scan the py2exe.org wiki, > there are many similiar challanges with various packages, maybe you > get another workaround-idea (and, if we find one, PLEASE put it down > there for others to learn) > > best wishes, > > Harald From ron.longo at cox.net Sat Mar 29 16:26:41 2008 From: ron.longo at cox.net (Ron Provost) Date: Sat, 29 Mar 2008 16:26:41 -0400 Subject: tkinter coordinates, conversion Message-ID: <000701c891db$3306ad00$6501a8c0@aristotle> Is there any way in tkinter to convert between coordinate systems? Specifically, I'm refering to the canvas. I'm getting x and y's back in mouse events and I would like to convert them back to inches 'i', centemeters 'c', millimeters 'm' or points 'p'. Which I wish to use to provided information back to the user. Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Mar 7 14:14:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:14:59 -0800 (PST) Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: On Mar 7, 11:49?am, Krishna wrote: > On Mar 6, 5:04 pm, "Gabriel Genellina" wrote: > > > > > > > En Thu, 06 Mar 2008 22:48:42 -0200, Krishna > > escribi?: > > > >>>> class Test(object): > > > ... ? ? def __init__(self): > > > ... ? ? ? ? ? ? self.a= 2 > > > ... ? ? def func(self, k = self.a): > > > ... ? ? ? ? ? ? print k > > > ... > > > Traceback (most recent call last): > > > ? File "", line 1, in ? > > > ? File "", line 4, in Test > > > NameError: name 'self' is not defined > > > > In the 'definition of the class', what would the first argument 'self' > > > in the methods evaluate to; when we have an object defined, it is > > > bound to the object reference, but what happens while the class > > > definition is executed, which I believe happens when the module > > > containing the class definition is imported > > > Function default arguments are evaluated when the function is defined > > (when the class is defined, in this case) so "self" itself has not a > > value. Try this instead: > > > ? ? ?def func(self, k=None): > > ? ? ? ? ?if k is None: > > ? ? ? ? ? ? ?k = self.a > > ? ? ? ? ?print k > > > If None is an allowed argument, use a special marker instead: > > > _marker=object() > > ... > > > ? ? ?def func(self, k=_marker): > > ? ? ? ? ?if k is _marker: > > ? ? ? ? ? ? ?k = self.a > > ? ? ? ? ?... > > > -- > > Gabriel Genellina > > Thanks for the reply. I am currently using the approach suggested by > you. But, I am more interested in knowing about the first argument > ('self'), what does it hold to allow the evaluation of the method, > take the example you gave, 'self.a' as Rvalue inside the method, how > and why is this allowed, when the same 'self.a' is not allowed as the > default argument, considering the fact that I have already specified > 'self' as first argument, only after whose evaluation, I believe would > the next statement (k = self.a, in def func(self, k = self.a) ) gets > evaluated > > Thanks, > Krishna- Hide quoted text - > > - Show quoted text - Is there enough information at that point in the statement to assign to k as specified by this language? No. Does there exist a possible language in which there is? Yes. From romano.giannetti at gmail.com Fri Mar 7 10:18:11 2008 From: romano.giannetti at gmail.com (rmano) Date: Fri, 7 Mar 2008 07:18:11 -0800 (PST) Subject: Embedding a literal "\u" in a unicode raw string. References: <47C340D4.6020803@v.loewis.de> <891938ee-ad81-43de-9985-73cd26e4268d@s12g2000prg.googlegroups.com> Message-ID: <3c48fbef-00aa-474e-b6f5-9962b3736eed@n36g2000hse.googlegroups.com> On Mar 4, 1:00 pm, NickC wrote: > > Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> r"\u" > '\\u' > >>> r"\uparrow" > '\\uparrow' Nice to know... so it seems that the 3.0 doc was not updated. I think this is the correct behaviour. Thanks From sturlamolden at yahoo.no Tue Mar 18 17:56:02 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 14:56:02 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> Message-ID: <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> On 18 Mar, 22:25, sturlamolden wrote: > def nonunique(lst): > slst = sorted(lst) > return list(set([s[0] for s in > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using the set function, there is more structure to exploit when the list is sorted: def nonunique(lst): slst = sorted(lst) dups = [s[0] for s in filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] return [dups[0]] + [s[1] for s in filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] From zerty.david at gmail.com Thu Mar 27 21:40:41 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 27 Mar 2008 22:40:41 -0300 Subject: Getting back an Object Message-ID: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> Well, I've got a little problem, I have a list that contains objects from the class C, then I use those objects.__str__ to generate a ListCtrl, A wxPython widget that makes a list of strings and then you can handle events when selected, and returns the string selcted, how can I access the "parent" of that string? I tried to search on the array like this: def search(self, string): for obj in self.list: if string == obj.__str__: return obj return None But I always get None... What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Wed Mar 12 14:49:54 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 13:49:54 -0500 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: References: Message-ID: <47D825D2.20301@tim.thechases.com> > The subject says pretty much all, Given what I understand about the BEGIN block[1], this is how Python works automatically: bash$ cat a.py print 'a1' import b print 'a2' bash$ cat b.py print 'b' bash$ python a.py a1 b a2 However, the first import does win and Python caches module-loading, so take care: bash$ cat x.py print 'one' import a print 'two' import b print 'three' bash$ python x.py one a1 B a2 two three -tkc [1] http://www.cs.cf.ac.uk/Dave/PERL/node133.html From cwitts at gmail.com Thu Mar 13 05:31:38 2008 From: cwitts at gmail.com (Chris) Date: Thu, 13 Mar 2008 02:31:38 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <9a1d9da3-42a7-4138-b53b-9ee690b77b7e@p73g2000hsd.googlegroups.com> On Mar 13, 9:36?am, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) ?[1,2,3,4] > 2) ?[1,2,3,4,5] > 3) ?That famous picture of Albert Einstein sticking out his tongue > 4) ?Nothing - no output > 5) ?None of the above > > I undertake to summarise answers posted to complete this "survey". > > - Hendrik No output because x is a NoneType... From craigm3604 at gmail.com Sat Mar 22 02:21:48 2008 From: craigm3604 at gmail.com (Craig) Date: Fri, 21 Mar 2008 23:21:48 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> Message-ID: <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> On Mar 21, 4:04 am, Dennis Lee Bieber wrote: > On Thu, 20 Mar 2008 16:50:18 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > > > I received a direct email from someone, and I came up with the > > following after implementing his advice: > > Just for completeness... I'm the "someone"... And this is a copy of > the message in question: > > > > > > > Please forgive my going direct -- I do not have Usenet posting privileges from work. > > > From your message: > > > -=-=-=-=-=-=- > > And, this is what printed: > > After - X = 4325376, CacheSize = 0, OpenMode = 3, vHandle = 17586736 > > > The printf shows that the values of X and vHandle have changed, but I > > am not sure it is working properly as X should be a MUCH smaller > > number (< 256). I would have expected a 0 (VIS_OK), 13 (VIS_DOS_ERROR) > > or 14(VIS_DISK_ERROR) if it had worked. > > > Next, I changed: > > fName = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", > > 13) > > so that I knew it would not find the file, and got: > > After - X = 2555917, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > The vHandle staying 0 tells me that it did not find the file, but the > > value of X seems random. > > -=-=-=-=-=-=-=- > > > X does NOT seem random to me -- but I took the effort to render it in hexadecimal. X seems to be coming back as a 32-bit integer. Your <256 code appears to be in the second half of that integer -- observe: > > > >>> "%8.8X" % 4325376 > > '00420000' > > >>> "%8.8X" % 2555917 > > '0027000D' > > > Also observe that x0D => 13 decimal... your stated "VIS_DOS_ERROR" code. > > > >>> 0x0042 > > 66 > > >>> 0x0027 > > 39 > > >>> 0x000d > > 13 > > > I have no explanation for the leading 16-bits... But under the rules of Python, "X = ..." is commonly a rebinding operation, so presetting X as a ctypes short integer may not be having any effect (I suspect those are more important for calls where the input parameters need to be mutable and of a known C format). > > > >>> import ctypes > > >>> x = ctypes.c_short(123) > > >>> dir(x) > > ['__class__', '__ctype_be__', '__ctype_le__', '__ctypes_from_outparam__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_as_parameter_', '_b_base_', '_b_needsfree_', '_objects', '_type_', 'value'] > > > >>> x > > c_short(123) > > >>> x.value > > 123 > > > >>> x.value = 13 > > >>> x > > c_short(13) > > > Note that in this I have assigned to the "value" component of a c_short object. Plugging in your results values: > > > >>> x.value = 4325376 > > >>> x > > c_short(0) > > >>> x.value = 2555917 > > >>> x > > c_short(13) > > > Gives... ta da... 0 and 13 respectively. Perhaps you should, after creating X as a c short object, be assigning to the value, not to the object... > > > X.value = windll. ... > > > {Replies are being directed to my home email} > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Sorry, I wasn't trying to exclude any credit from Dennis, I just wasn't sure if he wanted to be listed. As it turns out, I am running into more of these BSTR and pointer problems. I have moved on to the next function to convert: short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS lpvstats); which uses a structure: typedef struct tagVSTATS { LONG nrecords; WORD gps_used; WORD gps_unused; WORD max_key_len; LONG grp_size; WORD init_alloc; WORD cr_opts; WORD free_prop_area; BSTR format; BSTR reserved; } VSTATS; typedef VSTATS FAR * LPVSTATS; This is what I have tried: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf LPBSTR = POINTER(c_void_p) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) LPVSTATS = POINTER(c_void_p) class VSTATS(Structure): _fields_ = [ ("nrecords", c_long), ("gps_used", c_short), ("gps_unused", c_short), ("max_key_len", c_short), ("grp_size", c_long), ("init_alloc", c_short), ("cr_opts", c_short), ("free_prop_area", c_short), ("format", c_void_p), ("reserved", c_void_p) ] vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) VmxInfo = windll.vbis5032.VmxInfo VmxInfo.restype = c_short VmxInfo.argtypes = [LPHANDLE, LPVSTATS] print "\n(2) VB/ISAM testing:" hwmcb = HANDLE() print "\nVmxInfo test:" res = c_short(255) printf ("Before - res = %#x (%d), hwmcb = %d\n", res, res, hwmcb) res = VmxInfo( byref(hwmcb), byref(c_void_p(vStats)) ) printf ("After - res = %#x (%d), hwmcb = %d\n", res, res, hwmcb) printf ("nrecords = %d, gps_used = %d, gps_unused = %d, max_key_len = %d\n", vStats.nrecords, vStats.gps_used, vStats.gps_unused, vStats.max_key_len) printf ("grp_size = %d, init_alloc = %d, cr_opts = %d, free_prop_area = %d\n", vStats.grp_size, vStats.init_alloc, vStats.cr_opts, vStats.free_prop_area) printf ("format = \x22%s\x22\n", vStats.format) printf ("reserved = \x22%s\x22\n", vStats.reserved) This is what I get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 99, in res = VmxInfo( byref(hwmcb), byref(c_void_p(vStats)) ) TypeError: cannot be converted to pointer And, on the last variation of this, this function needs to receive BSTR values passed back from the dll: short FAR PASCAL VmxGet(LPHANDLE lpDatasetNumber, LPSHORT lpSecIndex, LPSHORT lpOption, BSTR *SrchKey, BSTR *SecKey, BSTR *PriKey, LPSTR lpTypeDef); SrchKey is provided by me, SecKey and PriKey are returned by the dll, and TypeDef is defined by me and filled by the dll. For this, I have added: VmxGet = windll.vbis5032.VmxGet VmxGet.restype = c_short VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, LPBSTR] hwmcb = HANDLE() SecIndex = c_short(0) Option = c_short(17) SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = windll.oleaut32.SysAllocStringByteLen(c_char_p("X".center(129, "\x00")), 129) print "\nVmxGet test:" res = c_short(255) printf ("Before - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d\n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), byref(c_void_p(TypeDef)) ) printf ("After - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d \n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef) The last message I get is: Ready to call (Library = C:\Windows\vbis5032.dll) ... and then I get a Windows popup box: python.exe has stopped working so, I know I am passing something very wrong. Once these two problems are resolved, I am sure I can process the rest of the C prototypes myself, as they are simply variations on these themes. As before, any help is appreciated. From bryanjugglercryptographer at yahoo.com Fri Mar 14 18:33:09 2008 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Fri, 14 Mar 2008 15:33:09 -0700 (PDT) Subject: How to send a var to stdin of an external software References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: I wrote: > And here's a thread example, based on Benjamin's code: [...] Doh! Race condition. Make that: import subprocess import thread import Queue def readtoq(pipe, q): q.put(pipe.read()) cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) myVar = str(range(1000000)) # arbitrary test data. q = Queue.Queue() thread.start_new_thread(readtoq, (cat.stdout, q)) cat.stdin.write(myVar) cat.stdin.close() cat.wait() myNewVar = q.get() assert myNewVar == myVar print len(myNewVar), "bytes piped around." -- --Bryan From castironpi at gmail.com Mon Mar 17 21:09:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 18:09:22 -0700 (PDT) Subject: String To List References: Message-ID: <847718f8-8bbd-4db1-a6f3-78235c6bda4d@x41g2000hsb.googlegroups.com> On Mar 17, 10:26?am, Jeff Schwab wrote: > Girish wrote: > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > this?? > > Do you want: > > (1) Specifically to vivify lists formatted as in your example? ?If so, why? > > (2) To save and restore arbitrary python objects? > > (3) To define some kind of configuration file format that you can read > from Python? Bar says: Announce your intentions, then contents. (Form, then contents.) == List of two strings. How does that go into code? >>> list([str,str]) [, ] From fn681 at ncf.ca Fri Mar 28 16:22:37 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 28 Mar 2008 16:22:37 -0400 Subject: how to capture screenshots of the active window in Python In-Reply-To: References: <142053.72537.qm@web44801.mail.sp1.yahoo.com> Message-ID: <47ED538D.2020607@ncf.ca> Gabriel Genellina wrote: > En Thu, 27 Mar 2008 20:28:27 -0300, Praveena B > escribi?: > >> Can anyone help me out?? > > Still lacking details... PIL has a ImageGrab module, Windows only. > For Windows, Alt Prtscn usually copies the image to a clipboard. Colin W. From buzzard at urubu.freeserve.co.uk Sat Mar 8 10:52:11 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sat, 08 Mar 2008 15:52:11 +0000 Subject: List as FIFO in for loop In-Reply-To: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > x = q.get() > #process x to get zero or more y's > #for each y: > q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > #process x to get zero or more y's > q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? > I have used exactly the same approach. I think it's a clean (even elegant) solution. I'd be surprised if it ceased to work in some future implementation of Python, but I don't know if that's absolutely guaranteed. Duncan From wbsoft at xs4all.nl Wed Mar 19 15:36:22 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Wed, 19 Mar 2008 20:36:22 +0100 Subject: keeping state in an iterator object by rebinding next() Message-ID: <200803192036.22626.wbsoft@xs4all.nl> Hi, i am writing a simple parser, that generates tokens. The parser needs to maintain some state, because some parts of the file consist of different tokens. I thought the object could simply remember its state by assigning it's next() method to the method that is currently parsing. When the state changes, the called method rebinds next() and the next token will be returned by that function. Here's an example, proving that this indeed works. >>> class A: ... def a(self): ... self.next = self.b ... return 1 ... def b(self): ... self.next = self.a ... return 2 ... def __iter__(self): ... return self ... >>> a=A() >>> a.a() 1 >>> a.next() 2 >>> a.next() 1 >>> j=0 >>> for i in a: ... j += 1 ... if j > 10: break # prevent from running endlessly ... print i ... 2 1 2 1 2 1 2 1 2 1 >>> my question is: is this legal Python? An iterator could save the next() method object, and in that case it could stop working.... It works now, because apparently the for- construct resolves 'next' each time for the object before calling it. The other solution would be just jumping to the correct method from within the next() method. But that gives an extra call... Met vriendelijke groet, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi From michael.wieher at gmail.com Sun Mar 16 13:14:31 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 12:14:31 -0500 Subject: Strange problem with structs Linux vs. Mac In-Reply-To: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> Message-ID: try twiddling the unpack prefix, they're probably stored in different binary formats on the disk... on the struct helppage, is a list of prefixes, can be like unpack('=HI',data) unpack('@HI',data) etc... find out which one works on each machine 2008/3/16, jasonwiener : > > Hi- > > I am having a VERY odd problem with unpacking right now. I'm reading > data from a binary file and then using a very simple struct.unpack to > get a long. Works fine on my MacBook, but when I push it to a Linux > box,it acts differently and ends up pewking. > > here's the code snippet: > fread.seek(0,0) > tmp_rebuild = fread.read() > fread.close() > tmp_long = tmp_rebuild[0:4] > print tmp_long.encode('hex') > print repr(tmp_long) > > unpacked_long = struct.unpack('I', > tmp_rebuild[0:4])[0] > print 'unpacked_long: %s' % unpacked_long > > my MacBook produces: > 1ec6f3b4 > '\x1e\xc6\xf3\xb4' > unpacked_long: 516354996 > > but on the linux box the same code produces: > 1ec6f3b4 > '\x1e\xc6\xf3\xb4' > unpacked_long: 3035874846 > > the data looks to be the same, but the unpacking seems to treat it > differently. > > Has anyone an idea of why this happens??? > > Thanks- > J. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sun Mar 16 07:47:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 16 Mar 2008 22:47:03 +1100 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <87ejaa28nc.fsf@benfinney.id.au> Bruce Eckel writes: > My trust has been violated. I paid a lot, in both money and time, to > be at this conference just to be herded into a room and have my > eyeballs sold to the highest bidder. Hear hear. Conference organisers, past and future, take note: Attention of attendees is *not* a commodity to be traded. Just because some parties will pay significant sums for that, it is *not* your place to sell it to them. Your place as conference organisers, rather, is to provide value to paying attendees. Their trust is hard earned, and easily lost. -- \ "Oh, I realize it's a penny here and a penny there, but look at | `\ me: I've worked myself up from nothing to a state of extreme | _o__) poverty." -- Groucho Marx | Ben Finney From benjamin.serrato at g[^_^]mail.com Mon Mar 24 02:25:02 2008 From: benjamin.serrato at g[^_^]mail.com (Benjamin Serrato) Date: Mon, 24 Mar 2008 01:25:02 -0500 Subject: Installing Mutagen Package On Windows Message-ID: Hey, I've run into another problem. I am trying to install the Mutagen package to use as my first useful program, but can't figure out how to install it on windows. The README says it is a simple application of-- Installing ---------- $ ./setup.py build $ su -c "./setup.py install" --but I ran c:\>python c:\python25\tools\scripts\setup.py build and did similarly for setup.py. I also added c:\python25 and c:\python25\tools\scripts to my path, but this hasn't worked. I have heard of 'easy_install' but don't know how to run easy_install. So, I ask for a reference because Google did not give me a quick answer and the python.org explanation at PEP 250 doesn't really explain what I should do. From george.sakkis at gmail.com Tue Mar 18 16:24:19 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 13:24:19 -0700 (PDT) Subject: Get actual call signature? References: Message-ID: <3ef0a8e9-6c86-46a5-be48-63f738f9ec88@s13g2000prd.googlegroups.com> On Mar 18, 6:40 am, Jarek Zgoda wrote: > Say, I have a function defined as: > > def fun(arg_one, arg_two='x', arg_three=None): > pass > > Is there any way to get actual arguments that will be effectively used > when I call this function in various ways, like: > > fun(5) => [5, 'x', None] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > fun(5, 'something') => [5, 'something', None] > > (et caetera, using all possible mixes of positional, keyword and default > arguments) > > I'd like to wrap function definition with a decorator that intercepts > not only passed arguments, but also defaults that will be actually used > in execution. > > If this sounds not feasible (or is simply impossible), I'll happily > throw this idea and look for another one. ;) I also needed this for a typecheck module I had written some time ago. It is feasible, but it's rather hairy. I can dig up the code, polish it and post it as a recipe (or maybe as a patch to the inspect stdlib module where it belongs). George From bbxx789_05ss at yahoo.com Mon Mar 10 23:54:12 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 10 Mar 2008 20:54:12 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: On Mar 10, 9:44?pm, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. > primes = [] > import math > import gmpy > while 1: > ? ? run = int(raw_input("Do you want to calculate primes? 1 = yes and > 2 = no. ")) > ? ? if run == 1: > ? ? ? ? y = int(raw_input("What number do you want to use as the final > number to calculate with? ")) > ? ? ? ? x = int(raw_input("What number do you want to start > calculating primes from? ")) > ? ? ? ? while x < 2: > ? ? ? ? ? ? print "Number must be at least 2 for math reasons." > ? ? ? ? else: > ? ? ? ? ? ? while x < y: > ? ? ? ? ? ? ? ? prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) > ? ? ? ? ? ? ? ? if prime < 0: > ? ? ? ? ? ? ? ? ? ? primes.append(x) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print x " is not prime. " # highlights the final " > here > ? ? ? ? ? ? ? ? x = x + 1 > ? ? ? ? ? ? print primes > ? ? elif run == 2: > ? ? ? ? break > ? ? else: > ? ? ? ? print "Sorry, not a choice. Please enter your choice again." > print "Goodbye." > > How do I fix such an invalid syntax? > > TIA, > Nathan Pinno Rather, try running this: print 10 "Hello world." From andrew-news at andros.org.uk Thu Mar 27 16:25:55 2008 From: andrew-news at andros.org.uk (Andrew McLean) Date: Thu, 27 Mar 2008 20:25:55 +0000 Subject: Instrumented web proxy Message-ID: I would like to write a web (http) proxy which I can instrument to automatically extract information from certain web sites as I browse them. Specifically, I would want to process URLs that match a particular regexp. For those URLs I would have code that parsed the content and logged some of it. Think of it as web scraping under manual control. I found this list of Python web proxies http://www.xhaus.com/alan/python/proxies.html Tiny HTTP Proxy in Python looks promising as it's nominally simple (not many lines of code) http://www.okisoft.co.jp/esc/python/proxy/ It does what it's supposed to, but I'm a bit at a loss as where to intercept the traffic. I suspect it should be quite straightforward, but I'm finding the code a bit opaque. Any suggestions? Andrew From NikitaTheSpider at gmail.com Thu Mar 20 22:45:58 2008 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 20 Mar 2008 22:45:58 -0400 Subject: zope and python 2.5.1 References: Message-ID: In article , hberig wrote: > Hi, > I'm sorry if this is an off-topic message, but I didn't found other > group. > I've read some articles about Zope, and since I like very much python, > I would like to run a webserver application using Zope instead other > web application server. I've difficulties to install zope 3 and zope 2 > on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is > there a simple way to fix it? I don't know much about installing Zope, is not the only choice for Python Web stacks. There's Django, Pylons and TurboGears to name a few alternatives. Have fun -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From rajeeshrnair at gmail.com Fri Mar 28 02:57:22 2008 From: rajeeshrnair at gmail.com (raj) Date: Thu, 27 Mar 2008 23:57:22 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> Message-ID: <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> To ankit: Well, sort() doesn't return the sorted list. It returns None. Why not this straightforward way? dvals = dict.values() dvals.sort() print dvals From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 23:38:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 04:38:41 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> Message-ID: <13t462h7vgqo081@corp.supernews.com> On Fri, 07 Mar 2008 20:04:47 -0800, dave_mikesell wrote: > On Mar 7, 10:31 am, "K Viltersten" wrote: >> I've been recommended reading >> of:http://www.python.org/dev/peps/pep-0008/ and in there i saw two >> things that i >> need to get elaborated. >> >> 1. When writing English, Strunk and >> White apply. > > If your code needs so much descriptive prose that you have to consult > Strunk and White, refactor it to be more clear. Excessive comments are > the hobgoblin of overly complex and/or sloppy code. Nonsense. Poor English is poor English whether you're writing short one- line comments or three hundred page manuals. store = make_store() x = get_stuff(store) # Get the stuff what was brought at the store. Not that I would consider S & W the best source for good grammar or style. -- Steven From bj_666 at gmx.net Sat Mar 1 11:23:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Mar 2008 16:23:46 GMT Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> Message-ID: <62te8iF24nbb5U1@mid.uni-berlin.de> On Fri, 29 Feb 2008 17:29:32 -0800, Lie wrote: > On Feb 28, 10:00 am, Paul Rubin wrote: >> More examples: >> >> x = 1 >> y = len(s) + x >> >> => ok, decides that x is an int >> >> x = 1 >> y = x + 3.0 >> >> => ok, decides that x is a float >> >> x = 1 >> y = x + 3.0 >> z = len(s) + x >> >> => forbidden, x cannot be an int and float at the same time. >> >> > I am so glad you're not the designer of Python. >> >> This is how Haskell works and I don't notice much complaints about it. > > Ok, that means the line "y = x + 3.0" have a side effect of "x = > float(x)"? I think I would say that is an implicit behavior. But the type of `x` must be specialized somehow. `x` doesn't start as `Int` or `Integer` but the very generic and AFAIK abstract type class `Num`. After seeing the second line the compiler finds an implementation for `+` and the type class `Fractional` for both operands and now thinks `x` must be a `Fractional`, a subclass of `Num`. Then comes the third line with `length` returning an `Int` and the `Fractional` `x` but there is no implementation for a `+` function on those types. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Mar 27 22:12:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 23:12:17 -0300 Subject: how to capture screenshots of the active window in Python References: <142053.72537.qm@web44801.mail.sp1.yahoo.com> Message-ID: En Thu, 27 Mar 2008 20:28:27 -0300, Praveena B escribi?: > Can anyone help me out?? Still lacking details... PIL has a ImageGrab module, Windows only. -- Gabriel Genellina From steve at holdenweb.com Sun Mar 30 20:34:30 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 20:34:30 -0400 Subject: question In-Reply-To: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> References: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > Say you have an auditory waveform. In dream hardware, positives would > accumulate until something, which would trigger a small chain > reaction. In software, with a function f of time t, f( t ), in > constant space, what can you know at t? > > Presume. Silence first, then a broken triad vamps. How long til you > recognize it? One sec., i'll attach a binary. Good grief, is this idibot still around? [leaves c.l.py for another month] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From hberig at gmail.com Fri Mar 21 19:29:22 2008 From: hberig at gmail.com (hberig) Date: Fri, 21 Mar 2008 16:29:22 -0700 (PDT) Subject: zope and python 2.5.1 References: Message-ID: <997f4975-0a33-4091-8c33-331d6c0bc0d4@59g2000hsb.googlegroups.com> On Mar 20, 11:45 pm, Nikita the Spider wrote: > In article > , > > hberig wrote: > > Hi, > > I'm sorry if this is an off-topic message, but I didn't found other > > group. > > I've read some articles about Zope, and since I like very much python, > > I would like to run a webserver application using Zope instead other > > web application server. I've difficulties to install zope 3 and zope 2 > > on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is > > there a simple way to fix it? > > I don't know much about installing Zope, is not the only choice for > Python Web stacks. There's Django, Pylons and TurboGears to name a few > alternatives. > > Have fun > > -- > Philiphttp://NikitaTheSpider.com/ > Whole-site HTML validation, link checking and more thanks Philip!! I'll see the alternatives. I'll search some report comparing features of each alternative. From gagsl-py2 at yahoo.com.ar Sun Mar 16 15:39:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 17:39:56 -0200 Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: En Wed, 12 Mar 2008 09:37:58 -0200, k.i.n.g. escribi?: > We use dd command in Linux to create a file with of required size. In > similar way, on windows I would like to use python to take the size of > the file( 50MB, 1GB ) as input from user and create a uncompressed > file of the size given by the user. The equivalent command on Windows would be: fsutil file createnew filename size -- Gabriel Genellina From ncoghlan at gmail.com Wed Mar 19 07:13:37 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 19 Mar 2008 04:13:37 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> Message-ID: On Mar 19, 6:07 am, Jeff Schwab wrote: > As I have never attended PyCon, the amount of entertainment already > gleaned from this thread has wildly exceeded my expectations. :) Are > slides or notes from any of the presentations available online? What > was the topic of the well-received presentation from Google? I'm mostly intrigued by the tantalising hints being dropped regarding Steve Holden's Teach Me Twisted talk ;) From kyosohma at gmail.com Tue Mar 18 14:49:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 18 Mar 2008 11:49:40 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> Message-ID: <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> On Mar 18, 1:41 pm, fumanchu wrote: > On Mar 17, 6:25 pm, dundeemt wrote: > > > I agree - the balance wasn't as good. We can all agree that HowTos > > and Intros are a necessary part of the conference talks track, but as > > Robert pointed out some talks should be of a more advanced nature. I > > enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and > > Mark Hammond's keynote were among my favorite talks. > > Raymond Hettinger's talk on collections was not only one of my > favorites, it was apparently lots of other people's too--the room was > PACKED. I can't recall seeing any other talk that was even close to > seating capacity. > > Robert Brewer > fuman... at aminus.org The "Using PyGame and PySight to Create an Interactive Halloween Activity (#9)" session with Mr. John Harrison was also quite full as was the one for Pyglet. I think the nose presentation had people sitting on the floor. Geeks like games! I know I do! Mike From mblume at freesurf.ch Thu Mar 27 15:35:29 2008 From: mblume at freesurf.ch (Martin Blume) Date: Thu, 27 Mar 2008 20:35:29 +0100 Subject: Is subprocess.Popen completely broken? References: <16300891-8fbf-489a-9011-e38180310618@s8g2000prg.googlegroups.com> Message-ID: <47ebf701$0$9029$5402220f@news.sunrise.ch> "Istvan Albert" schrieb > > > Is subprocess.Popen completely broken? > > Your lack of faith in Python is somewhat > disturbing ... > I have consistently made the experience that when I was about to ask "is X completely broken", the error was on my side. Martin From darcy at druid.net Fri Mar 7 12:02:03 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 7 Mar 2008 12:02:03 -0500 Subject: Regarding coding style In-Reply-To: <8c7f10c60803070844pf88a497h9db85953851b3418@mail.gmail.com> References: <63d80bF273nraU1@mid.individual.net> <8c7f10c60803070844pf88a497h9db85953851b3418@mail.gmail.com> Message-ID: <20080307120203.fabaecc4.darcy@druid.net> On Fri, 7 Mar 2008 16:44:10 +0000 "Simon Brunning" wrote: > On Fri, Mar 7, 2008 at 4:31 PM, K Viltersten wrote: > > > > 1. When writing English, Strunk and > > White apply. > > I apply Fowler, PEP 8 be damned. ;-) Fowler's is good too but much more comprehensive. Strunk and White is a pamphlet compared to Fowler's tome. -- 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 george.sakkis at gmail.com Wed Mar 26 21:58:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 18:58:48 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: On Mar 26, 5:28 pm, Sean Davis wrote: > I am working with genomic data. Basically, it consists of many tuples > of (start,end) on a line. I would like to convert these tuples of > (start,end) to a string of bits where a bit is 1 if it is covered by > any of the regions described by the (start,end) tuples and 0 if it is > not. I then want to do set operations on multiple bit strings (AND, > OR, NOT, etc.). Any suggestions on how to (1) set up the bit string > and (2) operate on 1 or more of them? Java has a BitSet class that > keeps this kind of thing pretty clean and high-level, but I haven't > seen anything like it for python. > > Thanks, > Sean Have you looked at Pypi [1] ? From a quick search, there are at least four potentially relevant packages: BitPacket, BitVector, BitBuffer, BitBucket. George [1] http://pypi.python.org/pypi?%3Aaction=search&term=bit&submit=search From deets at nospam.web.de Sat Mar 22 10:54:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 15:54:38 +0100 Subject: Distributing Python Apps on Linux\BSD In-Reply-To: References: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> <9290c7b1-3e51-46fe-96e7-6c2ebf4f5b77@u10g2000prn.googlegroups.com> Message-ID: <64kktlF2c6h1bU1@mid.uni-berlin.de> PurpleServerMonkey schrieb: > On Mar 22, 2:26 am, Miki wrote: >> Hello, >> >> Disclaimer: I'm not an expert on the subject. >> >>> Setuptools and friends seem to be focused on distributing modules, I'm >>> at the other end of the scale where I want to distribute an entire >>> application so that an Administrator can run a single install and have >>> a fully operational product. A key requirement is that I want the >>> application to fit in with what and admin would expect an application >>> to look like at the system level i.e site-packages like structures >>> aren't suitable. >> You do that with distutils as well. >> >>> So far I've thought of using a configure script and make which would >>> call some custom python installer script to do the actual install. It >>> fits in nicely with what I want to achieve but are there any better >>> options out there, how are others doing the same thing? >> Every distro flavor has it's own installer: apt/deb, rpm, port, ... >> On Windows you can use one of the free installer (InnoSetup and >> friends). >> >> HTH, >> -- >> Miki http://pythonwise.blogspot.com > > Well I'm not really interested in rpms or deb packages right now, I > want to get it to the point where it will run on BSD and Linux without > using distribution specific tools. Using a tarball or the standard > python tools would be best. > > The problem is all the documentation surrounding distutils and > setuptools refers to modules, now I'm not sure why but it seems most > Python developers think an application is the same thing as a module. > Unless you are writing very small applications that's definitely not > the case. > > So I guess the question is, using distutils or setuptools is it > possible for a user to select where to install the application i.e / > usr/local? > If not then I think it's going to be tarball deployment with a custom > setup script, was hoping there was a better way. You should start reading the setuptools-documentation, especially the section about entry-points. And yes, you can set the install-prefix. If you have a sysadmin who knows how to read a README, it can't get simpler than python setup.py install (with proper rights of course) If he has no setuptools installe, put the ez_setup.py script together into your distribution, then it becomes python ez_setup.py python setup.py install Unfortunately there is one caveat: the distros rip out distutils and Python-header into a separate -dev-package. Make sure to instruct the admin to install these. Diez From castironpi at gmail.com Mon Mar 3 22:21:23 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 19:21:23 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> Message-ID: On Mar 3, 4:03?pm, Carl Banks wrote: > On Mar 3, 4:17 pm, Raymond Hettinger wrote: > > > Since Python doesn't support having two methods with the same name, > > the usual solution is to provide alternative constructors using > > classmethod(): > > > ? @classmethod > > ? def from_decimal(cls, d) > > ? ? ? ? sign, digits, exp = d.as_tuple() > > ? ? ? ? digits = int(''.join(map(str, digits))) > > ? ? ? ? if sign: > > ? ? ? ? ? ? digits = -digits > > ? ? ? ? if exp >= 0: > > ? ? ? ? ? ? return cls(digits * 10 ** exp) > > ? ? ? ? return cls(digits, 10 ** -exp) > > Note that even some of Python's built in types (dict *cough*) > implement homemade function overloading. > > The OP wanted to write a constructor that could accept either a pair > of integers or a rational, there would be a good precedent for it. > > However, I would advise the OP to use the constructor only for the > most common arguments, and use classmethods for more obscure, less > common arguments (such as decimal or even float). > > Carl Banks Unless application indicates calling signature uniformity, hash type to subclass or to class method. From ptoomey3 at mac.com Wed Mar 26 23:33:01 2008 From: ptoomey3 at mac.com (Patrick Toomey) Date: Wed, 26 Mar 2008 22:33:01 -0500 Subject: Can my own objects support tuple unpacking? Message-ID: <6D5CBCD5-9CC5-4E00-9F3A-510F845A37B1@mac.com> Hello, So, I am new to python, but I always like to learn the ins and outs of a language by trying to understand how everything fits together. Anyway, I am trying to figure out how tuple unpacking behavior works. Specifically, what happens when I do the following: a,b,c,d = e Is a method called, such as __getitem__ for each index on the left (0,1,2,3)? I thought this was logical, so I tried coding up similar to this class Foo: def __getitem__(self, index): print index return 1 a = Foo() b,c,d = a the output is: 0 1 2 3 ValueError: too many values to unpack So, it seems like something is going on here with __getitem__, but obviously something is not quite right. What got me wondering about this was exceptions, as they seem to use this idiom in some way. As an example, we can do the following: class Foo(Exception): def bar(): print "dummy method" try: raise Foo('a', 'b', 'c', 'd') except Foo, e: a,b,c,d = e This will successfully unpack the exception arguments, as if e was a sequence. How are they implementing this functionality? Is this a special case for exceptions? I guess my overall question is how tuple unpacking works underneath the covers. Can I implement tuple unpacking for my own objects? Thanks, Patrick From jeff at schwabcenter.com Tue Mar 18 00:42:19 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 21:42:19 -0700 Subject: Any fancy grep utility replacements out there? In-Reply-To: References: Message-ID: samslists at gmail.com wrote: > So I need to recursively grep a bunch of gzipped files. This can't be > easily done with grep, rgrep or zgrep. (I'm sure given the right > pipeline including using the find command it could be done....but > seems like a hassle). > > So I figured I'd find a fancy next generation grep tool. Thirty > minutes of searching later I find a bunch in Perl, and even one in > Ruby. But I can't find anything that interesting or up to date for > Python. Does anyone know of something? I don't know of anything in Python, but it should be straight-forward to write, and I'm betting somebody in this group can do it in one line. (Did you see Arnaud's solution on the "Interesting math problem" thread?) When you say "recursively," do you mean that you want to grep files in nested subdirectories, or do you mean that archive elements should in turn be expanded if they are themselves archives? If you encounter a file that has been compressed twice (gzip|gzip), do you want to uncompress it repeatedly until you get to the original file? For example, given the following setup, what do you expect the output of my_grep to be? ~$ mkdir sample && cd sample sample$ for w in hello world; do echo $w |gzip -c >$w.gz; done sample$ tar czf helloworld.tgz *.gz sample$ my_grep hello -r . From tew24 at spam.ac.uk Thu Mar 6 05:33:41 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 06 Mar 2008 10:33:41 +0000 Subject: Licence confusion: distributing MSVC?71.DLL Message-ID: Hi I've written a program in Python using wxPython and Matplotlib and would like to distribute it under the GPL. For ease of use, I'd also like to distribute and installable version for Windows, but this needs MSVCR71.dll and MSVCP71.dll to work. I've created an installer using py2exe and Inno Setup but I don't know if I'm allowed to distribute it or not. I've found lots of conflicting opinions online indicating that I can or cannot distribute these, but no definitive answer. The Microsoft Developer Network instructs me to read the redistribution instructions and the EULA which come with Visual Studio, but I don't have visual studio, so that's next to useless. If someone has worked their way through this maze before and has an answer, I'd be keen to hear it. Failing that, if you have Visual Studio and it's not a violation of the licence terms to post the licence and redistribution instructions here, could you possibly do so and I'll see if I can work out what's allowed. Thanks! -- I'm at CAMbridge, not SPAMbridge From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:26:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:26:03 -0200 Subject: class object interface document References: Message-ID: En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN escribi?: > Where can I find the Python class object interface document, such as > struct PyClassObject, PyClass_New()? Thanks! PyClass_* and PyInstance_* are for old-style classes and instances respectively, and will disappear in v3.0. PyInstance is in the section 7.5.2 in the Python/C API Reference Manual; I don't find any documentation on PyClass itself. -- Gabriel Genellina From miki.tebeka at gmail.com Thu Mar 27 17:07:15 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 14:07:15 -0700 (PDT) Subject: Instrumented web proxy References: Message-ID: <9dd5c428-c1e5-43cb-99ee-b3e3a3fa7e11@m36g2000hse.googlegroups.com> Hello Andrew, > Tiny HTTP Proxy in Python looks promising as it's nominally simple (not > many lines of code) > > http://www.okisoft.co.jp/esc/python/proxy/ > > It does what it's supposed to, but I'm a bit at a loss as where to > intercept the traffic. I suspect it should be quite straightforward, but > I'm finding the code a bit opaque. > > Any suggestions? >From a quick look at the code, you need to either hook to do_GET where you have the URL (see the urlunparse line). If you want the actual content of the page, you'll need to hook to _read_write (data = i.recv(8192)). HTH, -- Miki http://pythonwise.blogspot.com From Wubbulous at gmail.com Wed Mar 12 00:50:20 2008 From: Wubbulous at gmail.com (Wubbulous at gmail.com) Date: Tue, 11 Mar 2008 21:50:20 -0700 (PDT) Subject: Open a file with default handler app? References: <83bc9bf2-9b9c-4959-870f-f4b37281f6e0@m3g2000hsc.googlegroups.com> Message-ID: <79ae8d93-5845-466c-b7f8-e345c3d63c46@i7g2000prf.googlegroups.com> On Mar 11, 9:24?pm, andrei.... at gmail.com wrote: > Hi, I searched for this on google and in this group, but my awesome > google-fu powers failed me. Is there a way to open any file using > default program that'd open it? In other words, to do the same action > as double-clicking in windows explorer? And secondly, is there a way > to do the same thing for linux that'd work across all desktop > environments and distributions, or at least in all major ones? What > I'm trying to do here is to have records (or items) in my app where > you could attach any kind of file and open it from there by clicking > 'open'. Then it would go and do something like os.system("launch %s" % > filename). So any way to do this except for keeping your own > dictionary of file types and relevant apps? thx, -ak Hey there, I've had to do the same things for a program that I'm writing. The following command should do the trick: os.startfile("yourfilehere") from the os module. Hope this helps! From enleverlesX.XmcX at XmclaveauX.com Mon Mar 17 18:19:56 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 17 Mar 2008 23:19:56 +0100 Subject: placing a Python com object into Excel In-Reply-To: References: Message-ID: <47deefc5$0$906$ba4acef3@news.orange.fr> Hi! Perso, I started from "excelAddin.py" (in C:\Python25\Lib\site-packages\win32com\demos). And, I'm happy with the result (who run OK with Excel 2000, XP, 2007). @-salutations -- Michel Claveau From py1.forest at tibit.com Mon Mar 31 18:07:20 2008 From: py1.forest at tibit.com (Forest) Date: Mon, 31 Mar 2008 15:07:20 -0700 (PDT) Subject: why does socket.makefile require non-blocking mode? Message-ID: <17580.75.55.199.5.1207001240.squirrel@webmail.sonic.net> Bryan Olson wrote: >Looking at the code for the existing _fileobject's read method, it >will loose data it has already read if a socket.recv() call raises >an exception. The function keeps buffers in a local variable that >will be lost if an exception exits the scope. That much could be >fixed with a try...finally. Other methods have similar problems. Just as I thought. Thanks for being my extra set of eyes. >>I wanted to use file-like objects with socket timeouts, so I ended up >>writing my own replacement for socket._fileobject. I'd appreciate it >>if someone could either explain to my why my new class was unnecessary, >>or else encourage me to contribute it as a patch to the socket module. > >Sure, fix it. Yeah, I'll give it some more thought. >A harder problem is that it doesn't play nice with select(). I guess you mean that since _fileobject.read() calls recv() multiple times, the second and later calls might block even if select() said the socket was readable. That should be fixable by catching EAGAIN / EWOULDBLOCK and returning early, shouldn't it? This idea seems consistent with the normal file object's read() method docs, which say, "in non-blocking mode, less data than what was requested may be returned." Making write() and flush() friendly in non-blocking mode might be at little trickier. From rahulguy5 at gmail.com Sun Mar 30 08:56:53 2008 From: rahulguy5 at gmail.com (lilly) Date: Sun, 30 Mar 2008 05:56:53 -0700 (PDT) Subject: FOR LAST 2 YEARS I WAS SEARCHING FOR FOR REAL ONLINE MONEY MAKING Message-ID: FOR LAST 2 YEARS I WAS SEARCHING FOR FOR REAL ONLINE MONEY MAKING PROGRAMME.FINALLY I FIND IT. IT HAS MAKE THOUSANDS OF DOLLARS TO MY ACCOUNT IN EVERY DAY.I AM HAPPY TO REVEALED THIS SECRET TO YOU .THE OPPORTUNITY IS BELOW http://jeevaraj.MYSURVEYPR.hop.clickbank.net IT IS REAL ONLINE MONEY MAKING PROGRAMME From justus.schwabedal at gmx.de Wed Mar 12 19:58:44 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Thu, 13 Mar 2008 00:58:44 +0100 Subject: Problem with exec Message-ID: <59B09204-2D58-4371-A05B-9FDA93991D77@gmx.de> Dear python users! I try to setted up compile-free parallelism using the exec command. However I had some problems with namespaces which I find mysterious although I managed to work around. But the workaround is not nice, so I wonder if there are ways. I do the following, bash-3.2$ cat execBug.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ def g(head): exec header return f() print "g(header) =",g(header) bash-3.2$ ./execBug.py g(header) = Traceback (most recent call last): File "./execBug.py", line 10, in print "g(header) =",g(header) File "./execBug.py", line 9, in g return f() File "", line 4, in f NameError: global name 'randn' is not defined However this works: bash-3.2$ cat execBug.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ exec header print "f() =",f() bash-3.2$ ./execBug.py f() = 1.44707148916 If for the first example I add "global randn", it works again. However I do not understand how the nested namespaces interact here. Isn't this an unwanted feature in the functionality? I'm looking foreward to your comments, Justus From userprogoogle-139 at yahoo.co.uk Thu Mar 20 12:21:28 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 20 Mar 2008 09:21:28 -0700 (PDT) Subject: OS.remove and threads Message-ID: <4453bd2b-f01c-4851-9c7b-6804ad2b2591@u10g2000prn.googlegroups.com> Hi, I am writing a small application which uploads files in a thread via an ftp connection. However anytime I use the os.remove(filename) command to delete files the thread crashes, even if the file being removed has nothing to do with the one being uploaded. Are the OS commands incompatible with threads? By crashing I mean the thread stops uploading and an exception is produced. Also if the OS commands are in any other thread, they cause that thread to crash. I have tried using locks around the os.remove command but that also makes no difference. I am using: Mac OS 10.4.9 and Python 2.4.3 with Psyco. Kind regards, rod From fakeaddress at nowhere.org Fri Mar 14 05:12:29 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 09:12:29 GMT Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> Message-ID: <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Robert Bossy wrote: > cokofreedom at gmail.com wrote: >> Robert Bossy wrote: >>> Indeed! Maybe the best choice for chunksize would be the file's buffer >>> size... That bit strikes me as silly. >>> I won't search the doc how to get the file's buffer size because >>> I'm too cool to use that function and prefer the seek() option since >>> it's lighning fast regardless the size of the file and it takes near to >>> zero memory. >> >> But what platforms does it work on / not work on? >> > Posix. Posix is on the does-work side, just to be clear. http://www.opengroup.org/onlinepubs/000095399/functions/fseek.html > It's been ages since I touched Windows, so I don't know if XP and > Vista are posix or not. I tried on WinXP, with both an NTFS and FAT32 disk, and it worked on both. I found some Microsoft documentation noting: "On some platforms, seeking past the end of a file and then doing a write operation results in undefined behavior." http://msdn2.microsoft.com/en-us/library/system.io.filestream.seek(VS.71).aspx > Though, as Marco Mariani mentioned, this may create a fragmented file. > It may or may not be an hindrance depending on what you want to do with > it, but the circumstances in which this is a problem are quite rare. Writing zeros might also create a fragmented and/or compressed file. Using random data, which is contrary to the stated requirement but usually better for stated application, will prevent compression but not prevent fragmentation. I'm not entirely clear on what the OP is doing. If he's testing network throughput just by creating this file on a remote server, the seek-way-past-end-then-write trick won't serve his purpose. Even if the filesystem has to write all the zeros, the protocols don't actually send those zeros. -- --Bryan From deets at nospam.web.de Thu Mar 13 13:57:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 18:57:55 +0100 Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> <63t1tnF29egotU1@mid.uni-berlin.de> Message-ID: <63t895F298us9U1@mid.uni-berlin.de> azrael wrote: > I thought of using Temp files but I am afraid of the JPG destorsion > while saving because of the compresion.I am looking for a way to > directly transform it. Then don't use JPEG, use PNG. It's lossless. Diez From phil at riverbankcomputing.co.uk Sun Mar 30 11:56:54 2008 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 30 Mar 2008 15:56:54 +0000 Subject: Using QSystemTrayIcon with PyQt In-Reply-To: <200803301608.19697.phil@riverbankcomputing.com> References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <200803301608.19697.phil@riverbankcomputing.com> Message-ID: <200803301656.54571.phil@riverbankcomputing.co.uk> On Sunday 30 March 2008, Phil Thompson wrote: > On Sunday 30 March 2008, Alex Teiche wrote: > > On Mar 30, 2:08 am, Phil Thompson wrote: > > > On Sunday 30 March 2008, Alex Teiche wrote: > > > > Hello, > > > > > > > > I am pretty new to Python, and have never learned C++. I am trying > > > > to implement the following thing into my python application: > > > > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > > > > Through PyQt. I have been using PyQt for awhile and I know how do > > > > use it, but I could not get this specific thing to work. Can someone > > > > give me some hints as to get it working in Python? > > > > > > > > Thanks a ton, > > > > > > > > Alex > > > > > > Have you looked at PyQt's systray example? > > > > > > Phil > > > > No, where do I find the example? > > > > Thanks, > > > > Alex > > Unsurprisingly in the PyQt source package. > > Phil By which I mean the current snapshot - I'd forgotten that it is a recent addition. Phil From pedro.santa at gmail.com Thu Mar 20 12:48:18 2008 From: pedro.santa at gmail.com (Pedro Machado Santa) Date: Thu, 20 Mar 2008 09:48:18 -0700 (PDT) Subject: Import a file to namespace Message-ID: <0cdb3c90-e961-4982-9996-de3ac02706bc@13g2000hsb.googlegroups.com> Hi all, I'm really a newbie in Python, and I wanted to do a tricky thing. I don't know if it is possible but my intention was: I have a package (namely breve) and I want to alter (override?) some of it's functions preserving the original library/package - in order if I update it, I do not lose my "hacks". Until now I was overriding the functions directcly on my script and adding them to the package namespace, like this: import testpackage class testClass(): #... testpackage.testClass = testClass But this has a problem. If I wanna use that code over many files, I have to update it manually on all of them every time I update my "hack". I was thinking if it is possible to keep that code on a file - namely testpackageaddon.py and import it on my work file so that by doing that it will automatically override the classes. Like so: import testpackage import testpackageaddon testpackage.testClass() #my hacked class defined on testpackageaddon.py And on testpackageaddon.py: import testpackage class testClass(): #... testpackage.testClass = testClass Any tips, ideas on how to do this? Many thanks. Pedro Machado Santa From castironpi at gmail.com Sat Mar 15 18:08:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 15:08:05 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> Message-ID: <9b959898-ed57-47b9-8158-7ca6a321e705@u69g2000hse.googlegroups.com> On Mar 15, 8:18?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > Gabriel Genellina wrote: > >> No need to reinvent the wheel. socket objects already have a makefile ? > >> method returning a file-like object, which behaves like a buffered socket. > > That wheel is far from round, and needs some reinvention. Python's > file-like objects do not play nice with lower level calls, which > would be tolerable if they supported some well-defiend high-level > asynchronous I/O, but they do not. > > > Newbie question: ?Can you write to the 'file-like object' a pickle, > > and receive it intact-- as one string with nothing else? > > Yes, but there's a world of gotcha's. Sockets do not recognize > record boundaries, and Python's 'pickle' has holes one's enemies > could drive a truck through. Still, you can pickle, write, read, > un-pickle, and get back your data intact. > > > I want to know because I want to send two pickles. > > "Two pickles" sounds like a tasty snack, but also suggests you may > be playing hopscotch in a minefield. This is a helpful group. Give > us more to go on, and you are likely to receive thousands of > dollars worth of consulting for free. It depends on the situation. How generally applicable is this: fun ListenerGeneric( port, factory, arrivedfun ): which calls 'factory' on socketA.accept (and loops again), then arrivedfun( stringA ) on message complete detection. ?. It should start itself in a separate thread. Or is this any better: for x in connections(): startnewthreadwith x: for y in messages( x ): arrivedfun( y ) From bronger at physik.rwth-aachen.de Mon Mar 17 09:35:09 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 17 Mar 2008 14:35:09 +0100 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> Message-ID: <87fxup4goi.fsf@physik.rwth-aachen.de> Hall?chen! Aahz writes: > In article <873aqp6bbq.fsf at physik.rwth-aachen.de>, > Torsten Bronger wrote: > >> [...] >> >> I see no reason why the "fault" for parts of the rest being >> sub-optimal, too, must necessarily be on the attendee's side. >> (Just hypothetically; I wasn't at PyCon.) > > Let's suppose you have a group of friends who collectively throw a > party. They invite you to help out organizing it and putting it > together, but you choose not to. If you don't have a good time at > the party because it wasn't what you wanted, I think it's fair to > say it was your fault. And I think exactly the same thing is true > for PyCon, albeit on a much larger scale. Fair enough. But then I question the sensibility in saying "it is XY's fault" at all. Somebody not involved in organising was not happy with the Con. You may take the criticism or leave it. The criticism may be justified or not. But saying that it is "his fault" is useless in my opinion, it even discourages feedback. It think it's okay to evaluate something that you didn't help coming into existence. A good point is a good point no matter who makes it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 06:19:58 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 12:19:58 +0200 Subject: Serial port error statistics - any comparable data? References: <657qh1F2es9vnU1@mid.uni-berlin.de> Message-ID: <6597qeF2e56g7U1@mid.individual.net> Diez B. Roggisch wrote: > if you have the chance, try & attach a machine with legacy rs232 > port, and see if the errors still remain. Additionally, what kind of buffers does your device have? I'm using pyserial to control a very "sensitive" device with nuttily implemented buffering strategy. It has a "fast" and a "slow" buffer which are filled in order, and no signalling to the outside sender on how full they are. If the fast buffer fills the slow buffer kicks in and requires less transmission rate. That may be how characters could be lost with you. Regards, Bj?rn -- BOFH excuse #119: evil hackers from Serbia. From castironpi at gmail.com Mon Mar 3 10:00:55 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 07:00:55 -0800 (PST) Subject: is there enough information? References: Message-ID: On Mar 3, 7:11?am, Jean-Paul Calderone wrote: > On Tue, 26 Feb 2008 21:45:24 -0800, Dennis Lee Bieber wrote: > > > [snip] > > > ? ?Threads, in Python, are good for parallel processing of items that > >tend to be I/O bound -- that is, stuff that blocks on lots of I/O calls > >allowing other threads to execute until they block too. Due to the GIL > >in the common Python implementation, threading is not useful for > >number-crunching (CPU bound) processing. > > > ? ?Now, there is a very vocal group that recommend Twisted style > >asynchronous call-backs for everything in the world... But I think that > >group tends to forget that Windows I/O is incompatible with the > >low-level select() call often used to do parallel I/O -- leaving it only > >useful for the network socket I/O, but not local file I/O processing. > > I'm not sure, but you seem to be implying that the only way to use Windows' > asynchronous I/O APIs is with threads. ?Actually, it is possible (and Twisted > allows you) to use these as well without writing a threaded application. > > Perhaps you think it would be better to use them with threads, but that's > certainly not the _only_ way to use them as you implied. > > Jean-Paul What's the API call for it? From bj_666 at gmx.net Thu Mar 13 04:06:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Mar 2008 08:06:10 GMT Subject: How to port Python code into C++ code automatically? References: Message-ID: <63s5jiF29blveU2@mid.uni-berlin.de> On Wed, 12 Mar 2008 20:15:32 -0700, Bo wrote: > I want to port a Python project (about 10,000 line python code) to C+ > +. Is there any automatically tool to do this kind of things? e.g., > SWIG(http://www.swig.org/)? > > Any comment is welcome! Have a look at the ShedSkin Python-to-C++ compiler: http://shed-skin.blogspot.com/ It has some restrictions, i.e. the code has to be written in a more or less statically typed way. And me too is interested in why you want to port the entire project instead just the time critical parts? ShedSkin might help here too. As Cython_ or Pyrex_ do. Both compile a subset of Python with optional static typing to C extension modules. .. _Cython: http://www.cython.org/ .. _Pyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Tue Mar 11 13:13:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 13:13:40 -0400 Subject: Obtaining the PyObject * of a class References: Message-ID: "Cooper, Andrew" wrote in message news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... | Are there any Python C API experts/SWIG experts out there that can help | me with this issue please. | I',m currently using SWIG to generate a python interface to a C DLL. Some people have switched to using ctypes for this, and many other SWIG users have stopped reading clp. But I hope someone answers who can. tjr From durumdara at gmail.com Tue Mar 11 07:52:57 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Tue, 11 Mar 2008 12:52:57 +0100 Subject: Python PDF + Pictures In-Reply-To: <47d66d8f$0$14029$426a74cc@news.free.fr> References: <47d66d8f$0$14029$426a74cc@news.free.fr> Message-ID: Hi! Bruno Desthuilliers wrote: > durumdara at gmail.com a ?crit : >> Hi, dear Python Masters! >> >> I wanna ask about the Python and PDF creating. > Dont know if this will match your needs, but you may want to have a look > at pisa: > http://www.htmltopdf.org/ > With HTML I have only one problem. The HTML is not page specific language. But I wanna use pages (for example: A4) with diff. orientation to show images correctly. But I try it if possible. Thanks for your help: dd From andreww at datanet.ab.ca Sun Mar 2 09:41:20 2008 From: andreww at datanet.ab.ca (Andrew Warkentin) Date: Sun, 02 Mar 2008 07:41:20 -0700 Subject: Python-based regular expression parser that allows patterns to call functions? Message-ID: <47CABC90.7010101@datanet.ab.ca> I am writing a filtering HTTP proxy (the site is http://xuproxy.sourceforge.net/). I want it to be compatible with Proxomitron (http://proxomitron.info/) filters. I need a regular expression parser that allows patterns to call functions (or more likely, class methods), to implement "matching commands" (look at the Proxmitron documentation to see what I mean). Does anyone know if such a library exists for Python, or do I have to write my own parser? From erikwickstrom at gmail.com Thu Mar 13 16:58:56 2008 From: erikwickstrom at gmail.com (erikcw) Date: Thu, 13 Mar 2008 13:58:56 -0700 (PDT) Subject: Python-PHP bridge? Message-ID: Hi all, I'm starting to translate a large legacy php app to python (django), and was wondering if anyone knew of a bridge between the 2 languages. (access php objects from python and vice versa). Some of the solutions I've come across so far include using php's passthru() ( http://us3.php.net/passthru ) and pyphp. passthru(): I'm concerned about the potential performance hit of all these system calls. Isn't this the equivalent of a CGI app? pyphp: Seems closer to what I'm looking for, but I haven't been able to get the examples working yet. Maybe it is to alpha? If anyone has any experience with these tools or others and can share some advice, I'd appreciate it! Thanks! Erik From castironpi at gmail.com Tue Mar 4 22:53:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 19:53:52 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: On Mar 4, 9:01?pm, "Gabriel Genellina" wrote: > En Wed, 05 Mar 2008 00:30:26 -0200, escribi?: > > > On Mar 4, 8:11?pm, "Gabriel Genellina" wrote: > >> En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > >> >> is it makes it. > > >> >>>> from types import FunctionType, MethodType > >> >>>> class A( FunctionType ): pass > >> > ... > >> > Traceback (most recent call last): > >> > ? File "", line 1, in > >> > TypeError: type 'function' is not an acceptable base type > > >> Use delegation instead of inheritance. This class is almost ? > >> indistinguishable from a true function (when used as a method): > > [... long interactive example ...] > > > I actually don't believe you-- bar is not bound to an instance when P > > is initialized... er, instantiated. ?However, the evidence indicates > > my belief mechanism is faulty... and rather conclusively at that. > > ?If P calls __get__( you ), is p a > > gotcha? > > I didn't cheat, that was an actual Python interactive session. So you'll ? > have to formulate a new theory taking into account the new facts... or ? > read how the descriptor protocol workshttp://www.python.org/doc/newstyle/ > I don't understand your last sentence. > > -- > Gabriel Genellina If P gets, p gotcha. gotcha= partial( get, you ). bor hor hor. Yes... regarding the descriptoring, just make it official! UserFunctionType or smg. From castironpi at gmail.com Fri Mar 7 14:34:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:34:49 -0800 (PST) Subject: Difference between 'function' and 'method' References: Message-ID: <6766529d-7f0e-4e9d-9498-1c295e71ac53@o77g2000hsf.googlegroups.com> On Mar 7, 6:44?am, Sion Arrowsmith wrote: > Gabriel Genellina wrote: > >En Thu, 06 Mar 2008 23:46:43 -0200, escribi???: > >> [ ... ] > >You may look at the SimpleXMLRPCServer class and see how it implements ? > >introspection. It's rather easy (and doesn't require metaclasses nor ? > >decorators nor any other fancy stuff; I think it works the same since ? > >Python 2.1). Apparently you're doing a similar thing, but using pickles ? > >instead of xmlrpc. > > It's not that difficult to graft pickles into SimpleXMLRPCServer -- > I've done it, and if you're trying to sling large data structures > over the connection it's a massive performance win (even with > sgmlop in place to speed up XML parsing). > ? ?her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump Yeah, but I'd be grafting a non-blocking RPC sequence too. -Instantiate- attributes of ISS upon instantiation. class C: d= D c= C() assert isinstance( c.d, D ) assert c.d is c.d Which ones? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 11:16:48 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 17:16:48 +0100 Subject: What is a class? In-Reply-To: References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: <47d018de$0$23481$426a34cc@news.free.fr> castironpi at gmail.com a ?crit : > And white to play. What does exec( open( 'modA.py' ).read() ) do? RTFM From aahz at pythoncraft.com Thu Mar 27 16:02:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2008 13:02:43 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> Message-ID: In article <8ede2d83-a9f8-4d31-903c-b53271831722 at z38g2000hsc.googlegroups.com>, fumanchu wrote: >On Mar 16, 5:09 pm, a... at pythoncraft.com (Aahz) wrote: >> >> If you did not like the programming this year (aside from the sponsor >> talks) and you did not participate in organizing PyCon or in delivering >> presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > >This would be true, except that the two talks I proposed last year >were essentially denied because they were too advanced, so I didn't >even bother this year. Perhaps I should have, but the PERIOD needs to >at least be replaced by a COMMA as long as the talk-acceptance >committee continues to reject more advanced talk topics in favor of >HOWTOs and Introduction To Package X. Feel free to join the Program Committee! Seriously, this is exactly the kind of difficult problem I was talking about when I said "it is YOUR FAULT". Speaking as someone who has been on the program committee for most of the last few PyCons, it is extremely difficult to balance all the conflicting expectations that attendees have (particularly given that we have to guess, for the most part -- consider that a thousand people compared to the six hundred at PyCon 2007 means that much of the feedback from 2007 isn't particularly relevant). On top of that, we have to pick and choose from whatever proposals are offered; with very limited exceptions, we can't just solicit talks on topics, we don't have enough volunteer labor. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From nccwarp9 at gmail.com Mon Mar 31 18:03:51 2008 From: nccwarp9 at gmail.com (NccWarp9) Date: Mon, 31 Mar 2008 15:03:51 -0700 (PDT) Subject: Problem with mod_python/3.3.1 and apache Message-ID: Hello, im using Apache HTTPD 2.2.8 with mod_python/3.3.1 Python/2.4.3 on Windows and having truble starting pythone, any help would be appreciated . Im getting this error: [Mon Mar 31 23:53:03 2008] [error] make_obcallback: could not import mod_python.apache.\n 'import site' failed; use -v for traceback 'import site' failed; use -v for traceback ImportError: No module named mod_python.apache [Mon Mar 31 23:53:03 2008] [error] make_obcallback: Python path being used "['C:\\\\Windows\\\\system32\\\\python24.zip', '', 'c:\\\\xampp\\\ \python\\\\DLLs', 'c:\\\\xampp\\\\python\\\\lib', 'c:\\\\xampp\\\ \python\\\\lib\\\\plat-win', 'c:\\\\xampp\\\\python\\\\lib\\\\lib-tk', 'C:\\\\xampp\\\\apache\\\\bin']". [Mon Mar 31 23:53:03 2008] [error] get_interpreter: no interpreter callback found. [Mon Mar 31 23:53:03 2008] [error] [client 127.0.0.1] python_handler: Can't get/create interpreter., referer: http://localhost/python/ [Mon Mar 31 23:53:25 2008] [error] make_obcallback: could not import mod_python.apache.\n ImportError: No module named mod_python.apache thx From tjreedy at udel.edu Mon Mar 31 15:52:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Mar 2008 15:52:54 -0400 Subject: Is this a good time to start learning python? References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: "Rui Maciel" wrote in message news:47f1140e$0$735$a729d347 at news.telepac.pt... | Recently I woke up inclined to take up the task of learning another | programming language. I've already dipped my toes in Perl (I've read online | tutorials and wrote a couple of irrelevant pet projects) but, as the | computers at my workplace only sport the python interpreter, it probably | means that learning python will end up serving me better, at least in the | short run. Plus, you know how Perl goes. If you intend to use Python on the computer at your workplace, then learn the version installed there. | So far the decision seems to be a no brainer. Yet, Python 3000 will arrive | in a few months. As it isn't backwards compatible with today's Python, | there is the risk that no matter what I learn until then, I will end up | having to re-learn at least a considerable part of the language. Most of the changes are deletions and additions, rather than changes. 3.0a4 will be out in a few days. If you had no reason to use anything else, I would consider starting with that. (But the IDLE IDE on Windows may still not work right.) | To put it in other words, I fear that I will be wasting my time. If you learn and use 2.x, then avoid things that are going away. In particular: Unless you need to learn about old-style classes, I would not bother with them and the differences from new, soon to be the only style, classes. Derive all your classes from object or a subclass thereof. Use // for integer floor division (ie, when you want 1/2 == 0. Use 'from __future__ import division' if you use '/' in a file where both operands might be ints and you would want 1/2==.5. | At least that is what a clueless newbie believes. As this group is | frequented by people who have more insight into all things pythonesque, | what are your thoughts on this? Diverse, I am sure ;-) Terry Jan Reedy From ptmcg at austin.rr.com Sun Mar 2 23:21:33 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 Mar 2008 20:21:33 -0800 (PST) Subject: Python-based regular expression parser that allows patterns to call functions? References: Message-ID: <78ccde27-a6fb-485d-b401-d4ac3f92e567@m34g2000hsc.googlegroups.com> pyparsing also includes a decorator function, traceParseAction, which will list out calls to parse actions, the tokens passed in, and the value returned or exception raised. If you add "@traceParseAction" before each of the parse actions in my example, you can see the token processing being done in the parse actions. -- Paul From waltbrad at hotmail.com Wed Mar 26 10:12:21 2008 From: waltbrad at hotmail.com (waltbrad) Date: Wed, 26 Mar 2008 07:12:21 -0700 (PDT) Subject: Running a python program as main... Message-ID: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Stumbling through Mark Lutz's "Programming Python 3rd", he gives an example of a program that will automatically configure environment settings and launch other programs. Then he gives an example of running this program. On his command line he types: C:\...\PP3E>Launcher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3E>python Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). From dpw.asdf at gmail.com Sat Mar 8 17:20:36 2008 From: dpw.asdf at gmail.com (dpw.asdf at gmail.com) Date: Sat, 8 Mar 2008 14:20:36 -0800 (PST) Subject: Parse specific text in email body to CSV file Message-ID: I have been searching all over for a solution to this. I am new to Python, so I'm a little lost. Any pointers would be a great help. I have a couple hundred emails that contain data I would like to incorporate into a database or CSV file. I want to search the email for specific text. The emails basically look like this: random text _important text:_15648 random text random text random text random text random text random text random text _important text:_15493 random text random text random text random text _important text:_11674 random text random text random text ===============Date: Wednesday March 5, 2008================ name1: 15 name5: 14 name2: 18 name6: 105 name3: 64 name7: 2 name4: 24 name8: 13 I want information like "name1: 15" to be placed into the CSV with the name "name1" and the value "15". The same goes for the date and "_important text:_15493". I would like to use this CSV or database to plot a graph with the data. Thanks! From musiccomposition at gmail.com Mon Mar 31 22:53:19 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 31 Mar 2008 19:53:19 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> <1a8a5b03-0b9e-49de-bd87-43fa1aa99dc2@b5g2000pri.googlegroups.com> <6b732135-a488-4175-889b-0cccf5f0c581@s8g2000prg.googlegroups.com> Message-ID: On Mar 31, 8:41 pm, Alex Teiche wrote: > On Mar 31, 6:40 pm, Alex Teiche wrote: > > > > > On Mar 31, 11:49 am, Alex Teiche wrote: > > > > On Mar 30, 3:50 pm, Benjamin wrote: > > > > > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > > > implement the following thing into my python application: > > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > > > it, but I could not get this specific thing to work. Can someone give > > > > > me some hints as to get it working in Python? > > > > > What problems are you having? > > > > > > Thanks a ton, > > > > > > Alex > > > > Thanks everyone for your help. I found the example to be particularly > > > helpful, and I have made a simplified version just to display an icon > > > with a quit button in its menu. Once I know how to do that I will > > > incorporate it into my larger program, with more options and the > > > ability show messages. The problem is, it doesn't work, and I can't > > > find out what's wrong. Can you give me some hints? > > > > Here is the code: > > > import sys > > > from PyQt4 import QtGui, QtCore > > > > class trayIcon(QtGui.QWidget): > > > def __init__(self, parent=None): > > > QtGui.QWidget.__init__(self, parent) > > > > #********Create Actions for the Tray Menu********# > > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > > > QtCore.QObject.connect(self.quitAction, > > > QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) > > > > create_tray_icon() > > > > self.composeAction.setEnabled(visible) > > > QtGui.QWidget.setVisible(self, visible) > > > > self.trayIcon.show() > > > > def create_tray_icon(self): > > > self.trayIconMenu = QtGui.QMenu(self) > > > self.trayIconMenu.addAction(self.composeAction) > > > self.trayIcon = QtGui.QSystemTrayIcon(self) > > > self.trayIcon.setContextMenu(self.trayIconMenu) > > > self.trayIcon.setIcon(bad.svg) > > > > app = QtGui.QApplication(sys.argv) > > > sys.exit(app.exec_()) > > > OK, I messed around with it some more, and it works. I just don't > > know how to set an icon, and the example doesn't help at all. > > > Here is the code: > > import sys > > from PyQt4 import QtCore, QtGui > > > class Systray(QtGui.QWidget): > > def __init__(self): > > QtGui.QWidget.__init__(self) > > > self.createActions() > > self.createTrayIcon() > > > #QtCore.QObject.connect(self.trayIcon, > > QtCore.SIGNAL("messageClicked()"), self.messageClicked) > > #QtCore.QObject.connect(self.trayIcon, > > QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), > > self.iconActivated) > > > self.trayIcon.show() > > > def createActions(self): > > #self.minimizeAction = QtGui.QAction(self.tr("Mi&nimize"), self) > > #QtCore.QObject.connect(self.minimizeAction, > > # QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("hide()")) > > > #self.maximizeAction = QtGui.QAction(self.tr("Ma&ximize"), self) > > #QtCore.QObject.connect(self.maximizeAction, > > # QtCore.SIGNAL("triggered()"), self, > > # QtCore.SLOT("showMaximized()")) > > > #self.restoreAction = QtGui.QAction(self.tr("&Restore"), self) > > #QtCore.QObject.connect(self.restoreAction, > > # QtCore.SIGNAL("triggered()"), self, > > # QtCore.SLOT("showNormal()")) > > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > > QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), > > QtGui.qApp, QtCore.SLOT("quit()")) > > > def createTrayIcon(self): > > self.trayIconMenu = QtGui.QMenu(self) > > #self.trayIconMenu.addAction(self.minimizeAction) > > #self.trayIconMenu.addAction(self.maximizeAction) > > #self.trayIconMenu.addAction(self.restoreAction) > > #self.trayIconMenu.addSeparator() > > self.trayIconMenu.addAction(self.quitAction) > > > self.trayIcon = QtGui.QSystemTrayIcon(self) > > self.trayIcon.setContextMenu(self.trayIconMenu) > > > app = QtGui.QApplication(sys.argv) > > x = Systray() > > sys.exit(app.exec_()) > > > How would I go about setting the icon? > > Sorry, here is the code with commented out lines removed: > > import sys > from PyQt4 import QtCore, QtGui > > class Systray(QtGui.QWidget): > def __init__(self): > QtGui.QWidget.__init__(self) > > self.createActions() > self.createTrayIcon() > > self.trayIcon.show() > > def createActions(self): > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), > QtGui.qApp, QtCore.SLOT("quit()")) > > def createTrayIcon(self): > self.trayIconMenu = QtGui.QMenu(self) > self.trayIconMenu.addAction(self.quitAction) > > self.trayIcon = QtGui.QSystemTrayIcon(self) > self.trayIcon.setContextMenu(self.trayIconMenu) > > app = QtGui.QApplication(sys.argv) > x = Systray() > sys.exit(app.exec_()) I believe the method you want is QSystemTrayIcon.setIcon. From sneakers_in_china at yahoo.com.cn Sun Mar 30 02:50:33 2008 From: sneakers_in_china at yahoo.com.cn (sneakers_in_china at yahoo.com.cn) Date: Sat, 29 Mar 2008 23:50:33 -0700 (PDT) Subject: ( WWW.SNEAKERS-IN-CHINA.COM) Nike AF1 x Air Jordan 5. Nike Air Force Ones Shoes & Air Jordan 5. Message-ID: <46304cc4-6570-4a05-9d20-ed431590d73f@e23g2000prf.googlegroups.com> (www sneakers-in-china com) wholesale Air Jordan 1 Old Love/New Love Package (www sneakers-in-china com) Nike Air Jordan Retro 1 beginning moments "BMP Package-Old Love New Love Edition" (www sneakers-in-china com) selling Air Jordan DMP Defining Moments Package (www sneakers-in-china com) Air Jordan Retro XIII/X Collezione Package china outlet (www sneakers-in-china com) discount Air Jordan Collezione 13 10 Countdown Package cheap Air Jordan 1 Old Love/New Love Package discount Air Jordan 1 Old Love/New Love Package china customize custom shoes sneakers trainers outlet factory urban clothing,Hip Hop Clothes,urban wear distributor www.sneakers-in-china.com cheap Air Jordan DMP Defining Moments Package discount Air Jordan DMP Defining Moments Package china customize custom shoes sneakers trainers outlet factory urban clothing,Hip Hop Clothes,urban wear distributor www.sneakers-in-china.com cheap Air Jordan Retro XIII/X Collezione Package discount Air Jordan Countdown package Pack 10/13 X XIII china customize custom shoes sneakers trainers outlet factory urban clothing,Hip Hop Clothes,urban wear distributor www.sneakers-in-china.com Air Jordan Beginning Moments Package or Old Love New Love. The Air Jordan Old Love New Love Pack Retro 1 consists of two pairs of Air Jordan 1 (Retro White/Black-Varsity Red aka Black Toes & Black/ Varsity-Maize/White).Comes with special slide out double box with many special moments with Michael Jordan and booklet. Air Jordan Beginning Moments Package or Old Love New Love. Sell Air Jordan 1 Retro-BMP Package Old Love New Love Edition The Air Jordan Old Love New Love Pack Retro 1 consists of two pairs of Air Jordan 1 (Retro White/Black-Varsity Red aka Black Toes & Black/ Varsity-Maize/White). Size available: SIZE (US): 8 8.5 9.5 10 11 12,13 SIZE (UK): 7 7.5 8.5 9 10 11,12 SIZE (EURO): 41 42 43 44 45 46,47 Comes with special slide out double box with many special moments with Michael Jordan and booklet. we also sell and wholesale,retail air jordans,jordan sneakers shoes include: Air Jordan Retro womens shoes Air Jordan Retro kids shoes Air Jordan Spizikes Air Jordan Dub Zeros Air Jordan 4 Fusion Air Jordan 5 Fusion Air Jordan 12 Fusion Air Jordan 23 Fusion (www sneakers-in-china com)Wholesale New Air Jordan 12 Fusion,Air Jordan 12 X Air Force 1. Wholesale New Air Jordan 12 Fusion,Air Jordan 12 X Air Force 1 cheap Air Jordan 5 x Air Force one Fusion (www.sneakers-in-china.com) discount Air Jordan 5 and Air Force one Fusion(www.sneakers-in- china.com) Air Jordan 12 x Air Force One china online store(www sneakers-in-china com) (www sneakers-in-china com)Air Jordan V x Air Force 1 Fusion Air Jordan 12 x Air Force Ones Fusion (www sneakers-in-china com) (www sneakers-in-china com) Nike AF1 x Air Jordan 5. Nike Air Force Ones Shoes & Air Jordan 5. wholesale Air Jordan 5 (V) x Air Force 1 Fusion (www sneakers-in-china com) Website: http://www sneakers-in-china com E-mail: sneakers_in_china @ yahoo com cn Msn: sneakers_in_china @ hotmail com From pavlovevidence at gmail.com Sat Mar 1 04:17:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 Mar 2008 01:17:58 -0800 (PST) Subject: Pythons & Ladders References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> <3pidnRLtmJ1KulvanZ2dnUVZ_uyinZ2d@comcast.com> Message-ID: On Feb 27, 10:18 pm, Jeff Schwab wrote: > Benoit wrote: > > I've been teaching myself the python language over the past few months > > using Mark Lutz' Learning Python, 3ed. Python is also the first > > programming language I've ever taken up. I find the language easy to > > learn and rather productive in relation to the introductory course on C > > ++ I'd begun in January for fun @ school (we're practicing dynamic > > arrays using pointers... kill me now). > > Get a better teacher, if you can. Please do me a personal favor: Personal favor? Seriously, do you have stock in a C++ support company or something? There's no need to take stuff like this personally. > Don't > hold the crappy course against C++. C++ has so much badness to hold against it, there's no need to throw a crappy course on top of it. Carl Banks From eddie at holyrood.ed.ac.uk Fri Mar 14 13:27:06 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 14 Mar 2008 17:27:06 +0000 (UTC) Subject: Thousand Seperator References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: ewanfisher at gmail.com writes: >I'm trying to find some code that will turn: >100 -> 100 >1000 -> 1,000 >1000000 -> 1,000,000 >-1000 -> -1,000 >I know that can be done using a regular expression. In Perl I would do >something like: >sub thousand { > $number = reverse $_[0]; > $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; > return scalar reverse $number; >} >But I cannot find how to do this in Python. Look at the locale module. If you're producing the numbers yourself then they get printed in that format otherwise you can convert them to numbers first. Eddie From george.sakkis at gmail.com Sun Mar 23 21:43:27 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 18:43:27 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: <8c9b2c6d-c7bd-4664-bba4-06f35c3735e9@e10g2000prf.googlegroups.com> On Mar 23, 9:02 pm, Carsten Haese wrote: > On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > > That's really weird... it's reproducible on Windows too. It doesn't > > make any sense why the name of the variable would make a difference. > > My guess is you hit some kind of obscure bug. > > This is not a bug, just an unexpected feature:http://mail.python.org/pipermail/python-list/2005-January/304873.html That would make a great entry for the Python IAQ [1] ! As they say, you learn something new every day :) George [1] http://norvig.com/python-iaq.html From http Mon Mar 10 14:05:08 2008 From: http (Paul Rubin) Date: 10 Mar 2008 11:05:08 -0700 Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: <7xod9mo3or.fsf@ruckus.brouhaha.com> John Machin writes: > Bitwise operations like & | ^ << >> etc work on long integers. This > happens at C speed. The problem is if you want to set a bit, you have to allocate a whole new long integer. From neilcrighton at gmail.com Tue Mar 11 17:38:24 2008 From: neilcrighton at gmail.com (neilcrighton at gmail.com) Date: Tue, 11 Mar 2008 14:38:24 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: <42cd60a5-8cf2-4583-82ff-f6ff6939998a@e23g2000prf.googlegroups.com> I think I've worked it out after reading the 'Binary mode for files' section of http://zephyrfalcon.org/labs/python_pitfalls.html zipfile extracts as file as a binary series of characters, and I'm writing out this binary file as a text file with open('foo','w'). Normally Python converts a '\n' in a text file to whatever the platform-dependent indication of a new line is ('\n' on Unix, '\r\n' on Windows, '\r' on Macs). So it sees '\r\n' in the binary file and converts it to '\r\r\n' for the text file. The upshot of this is that writing out the zipfile-extracted files with open('foo','wb') instead of open('foo','w') solves my problem. On Mar 11, 8:43 pm, neilcrigh... at gmail.com wrote: > Sorry my initial post was muddled. Let me try again. > > I've got a zipped archive that I can extract files from with my > standard archive unzipping program, 7-zip. I'd like to extract the > files in python via the zipfile module. However, when I extract the > file from the archive with ZipFile.read(), it isn't the same as the 7- > zip-extracted file. For text files, the zipfile-extracted version has > '\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't > tried comparing binary files via the two extraction methods yet. > > Regarding the code I posted; I was writing it from memory, and made a > mistake. I didn't use: > > z = zipfile.ZipFile(open('foo.zip', 'r')) > > I used this: > > z = zipfile.ZipFile('foo.zip') > > But Duncan's comment was useful, as I generally only ever work with > text files, and I didn't realise you have to use 'rb' or 'wb' options > when reading and writing binary files. > > To answer John's questions - I was calling '\r' a newline. I should > have said carriage return. I'm not sure what operating system the > original zip file was created on. I didn't fiddle with the extracted > file contents, other than replacing '\r' with ''. I wrote out all the > files with open('outputfile','w') - I seems that I should have been > using 'wb' when writing out the binary files. > > Thanks for the quick responses - any ideas why the zipfile-extracted > files and 7-zip-extracted files are different? > > On Mar 10, 9:37 pm, John Machin wrote: > > > On Mar 10, 11:14 pm, Duncan Booth > > wrote: > > > > "Neil Crighton" wrote: > > > > I'm using the zipfile library to read a zip file in Windows, and it > > > > seems to be adding too many newlines to extracted files. I've found > > > > that for extracted text-encoded files, removing all instances of '\r' > > > > in the extracted file seems to fix the problem, but I can't find an > > > > easy solution for binary files. > > > > > The code I'm using is something like: > > > > > from zipfile import Zipfile > > > > z = Zipfile(open('zippedfile.zip')) > > > > extractedfile = z.read('filename_in_zippedfile') > > > > > I'm using Python version 2.5. Has anyone else had this problem > > > > before, or know how to fix it? > > > > > Thanks, > > > > Zip files aren't text. Try opening the zipfile file in binary mode: > > > > open('zippedfile.zip', 'rb') > > > Good pickup, but that indicates that the OP may have *TWO* problems, > > the first of which is not posting the code that was actually executed. > > > If the OP actually executed the code that he posted, it is highly > > likely to have died in a hole long before it got to the z.read() > > stage, e.g. > > > >>> import zipfile > > >>> z = zipfile.ZipFile(open('foo.zip')) > > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\python25\lib\zipfile.py", line 346, in __init__ > > self._GetContents() > > File "C:\python25\lib\zipfile.py", line 366, in _GetContents > > self._RealGetContents() > > File "C:\python25\lib\zipfile.py", line 404, in _RealGetContents > > centdir = struct.unpack(structCentralDir, centdir) > > File "C:\python25\lib\struct.py", line 87, in unpack > > return o.unpack(s) > > struct.error: unpack requires a string argument of length 46 > > > >>> z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK > > >>> z = zipfile.ZipFile('foo.zip', 'r') # OK > > > If it somehow made it through the open stage, it surely would have > > blown up at the read stage, when trying to decompress a contained > > file. > > > Cheers, > > John From p at ulmcnett.com Fri Mar 21 17:09:39 2008 From: p at ulmcnett.com (=?UTF-8?B?UGF1bCBNwqJOZXR0?=) Date: Fri, 21 Mar 2008 14:09:39 -0700 Subject: os.path.getsize() on Windows In-Reply-To: <47E41F3C.6040109@v.loewis.de> References: <47E41F3C.6040109@v.loewis.de> Message-ID: <47E42413.8020503@ulmcnett.com> Martin v. L?wis wrote: >> def isGrowing(f, timeout): >> ssize = os.path.getsize(f) >> time.sleep(timeout) >> esize =os.path.getsize(f) >> return esize != ssize >> >> On windows, this returns the size of the file as it _will be_, not the >> size that it currently is. > > Why do you say that? It most definitely returns what the size currently > is, not what it will be in the future (how could it know, anyway). I've seen this before, when copying a file in Windows. Windows reports the size the file will be after the copy is complete (it knows, after all, the size of the source file). I always thought this meant that Windows is just much smarter than me, so I ignored it. Paul From lesande at gmail.com Wed Mar 19 18:28:13 2008 From: lesande at gmail.com (Lee Sander) Date: Wed, 19 Mar 2008 15:28:13 -0700 (PDT) Subject: removing all instances of a certain value from a list Message-ID: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Hi, I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are many missing vlaues which are represented as None. I would like to remove all such instances in one go. There is a remove function but it removes only the first instance, is there a delete/remove all function? thanks From brnstrmrs at gmail.com Wed Mar 19 14:06:40 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Wed, 19 Mar 2008 11:06:40 -0700 (PDT) Subject: csv dictreader Message-ID: I am trying to use the dictionary reader to import the data from a csv file and create a dictnary from it but just can't seem to figure it out. Here is my code: >>>import csv >>>reader = csv.DictReader(open('table.csv')) >>>for row in reader: >>>print row my csv files looks like this: Bytecode,Element \x00\x00,0000 \x01\x00,0001 .... \x09\x00,0009 My output shows: {'Bytecode': '\\x00\\x00', 'Element': '0000'} {'Bytecode': '\\x01\\x00', 'Element': '0001'} ... {'Bytecode': '\\x09\\x00', 'Element': '0009'} 1. how can I get access to this directory 2. why does the values come with two backslashs infront of the "x" From paddy3118 at googlemail.com Wed Mar 12 14:43:28 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 12 Mar 2008 11:43:28 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: <9673d45f-c0aa-47ea-919e-d15a5be61d5b@i7g2000prf.googlegroups.com> On Mar 12, 6:19 pm, Alex wrote: > Hi all, > > The subject says pretty much all, i would very appreciate an answer. I > tried to search the various forums and groups, but didn't find any > specific answer... > > Thanks, > Alex. No not really. There are lots of other ways to structure a Python program though which makes its omission hardly felt. - Paddy. From tim.leslie at gmail.com Sun Mar 30 22:48:34 2008 From: tim.leslie at gmail.com (Tim Leslie) Date: Mon, 31 Mar 2008 13:48:34 +1100 Subject: Rubik's cube translation In-Reply-To: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> References: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> Message-ID: On Mon, Mar 31, 2008 at 12:24 PM, wrote: > How do I get a Rubik's cube translation out of this: > > >>> a= numpy.array([[0,1,2],[3,4,5],[6,7,8]]) > >>> a > array([[0, 1, 2], > [3, 4, 5], > [6, 7, 8]]) > >>> a[:,0],a[:,1],a[:,2] #no good > (array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])) > >>> > > I need [[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]. > > >>> c= numpy.array([[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]) > >>> c > array([[6, 3, 0], > [7, 4, 1], > [8, 5, 2]]) In [10]: numpy.rot90(a, 3) Out[10]: array([[6, 3, 0], [7, 4, 1], [8, 5, 2]]) Tim > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Mon Mar 10 07:57:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 12:57:44 +0100 Subject: Distributed App - C++ with Python for Portability? References: Message-ID: <63km1jF27n1hpU1@mid.uni-berlin.de> Roopan wrote: > Hello! > > I am looking at developing an enterprise-grade distributed data > sharing application - key requirements are productivity and platform > portability. > > Will it be sensible to use C++ for performance-critical sections and > Python for all the glue logic. > > Pls comment from your *experiences* how Python scales to large > projects( > 200KLOC). > I assume the C++/Python binding is fairly painless. It depends. There are good wrappers out there, I personally prefer SIP. However, a mixed language environment is always a PITA, especially for distribution. If you can, write everything in python. Identify bottlenecks, and if you must, I suggest using C + ctypes for performance-critical code. Obviously it's a matter of taste, but C++ is a beast, and getting it to work seamless under varying compilers and OSes could be avoided using plain C. Diez From blwatson at gmail.com Fri Mar 28 22:23:01 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Fri, 28 Mar 2008 19:23:01 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> Message-ID: <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> On Mar 28, 1:57?pm, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: > > > I am trying to install the twitter python wrapper...I got that > > installed just fine, but am having serious troubles getting the > > simplejson package to install. ?I need help diagnosing where this is > > failing. ?I am trying to use: > > >http://pypi.python.org/pypi/simplejson > > > and I run "python setup.py build" and then "python setup.py install", > > which both seem to work just fine. > > I don't understand - if it worked fine, what's the problem? > > > I tried running with easy_install, but that too is not working. ?I end > > up with: > > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > > in my: > > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > > packages/ > > > I am on Mac OS X 10.5. ?Any help would be greatly appreciated. > > And then you import simplejson and it fails? Or what? > > -- > Gabriel Genellina Yes, when I try to import simplejson, it fails >>> import simplejson Traceback (most recent call last): File "", line 1, in import simplejson ImportError: No module named simplejson there is not simplejson.py anywhere on my machine. I understand that I am new to python and trying to make heads or tails of what has happened with this install process. Any help is appreciated. From bj_666 at gmx.net Sun Mar 2 02:24:32 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Mar 2008 07:24:32 GMT Subject: mod_python Unable to create file References: Message-ID: <62v31gF24ontgU1@mid.uni-berlin.de> On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: > I am using Apache and mod_python to service POST/GET requests on MAC > OS. My script tries to create a file > > file = open(file_path, 'w') > > This fails with the following error > > EACCES > Permission denied > > What is missing? To state the ovious: the rights to create a file at `file_path`. Remember that web servers usually have their own "user". Ciao, Marc 'BlackJack' Rintsch From barry at python.org Mon Mar 3 07:17:00 2008 From: barry at python.org (Barry Warsaw) Date: Mon, 3 Mar 2008 07:17:00 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <47CB9F3C.9030202@v.loewis.de> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> <47CB9F3C.9030202@v.loewis.de> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mar 3, 2008, at 1:48 AM, Martin v. L?wis wrote: >>> But it would be really nice if the configure fix for 2.5 was >>> backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped >>> system builds for 2.4 going direct from 2.3 -> 2.5. >> >> >> Yes, it would be very nice if this worked out of the box on Mac OS X >> 10.5.2. It's definitely a surprise for those of us who built our >> 2.4.4 >> on Mac OS X 10.4.x. > > I can put a notice in the release notes, but I definitely won't change > it to work out of the box. If 2.4.4 compiled out of the box on this > box, > it would have been a regression and would have to be fixed. IIUC, > 2.4.4 > won't compile on 10.5, either, and Python 2.4.5 will have no code to > port it to new platforms. Can you also add a note to the 2.3 and 2.4 web pages? - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iQCVAwUBR8vsPHEjvBPtnXfVAQJVpgP5AbRU+BENEa7fv7vGUykjtQRftaF6ATQz yTo9018UiQZ20bFv2PIvgHltsET1ksTuieSdDjGbQ3rGu3vo1tldiGYxUQJgi++C q8ntOyLUo+nHSlKm11TTyMiNX4igl+X0bes5PlgJZbWOnw0vBvWbVRrwgMUsJqfi ox/d8+2jWc4= =HLja -----END PGP SIGNATURE----- From bearophileHUGS at lycos.com Sun Mar 23 12:28:23 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 23 Mar 2008 09:28:23 -0700 (PDT) Subject: Duplicating list of lists [newbie] References: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Message-ID: Yatsek: > Is there simple way to copy a into b (like a[:]) with all copies of > all objects going as deep as possible? If you only want to copy up to level-2, then you can do something like: cloned = [subl[:] for subl in somelist] Or sometimes safer: cloned = [list(subl) for subl in somelist] If you want to go all the way down, you can use the deepcopy function of the copy module. In many situations the level-2 copy may be enough, and it can be faster. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 23:14:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 04:14:48 -0000 Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> Message-ID: <13t6p1o23so7oc2@corp.supernews.com> On Sat, 08 Mar 2008 18:50:30 -0800, Chick wrote: > Hello, > > I'm writing a security tool Oh good, just what we need, beginners writing security tools. > which requies wiping off the memory of > certain string after being used, which I've done by implementing it as a > mutable list as follow: > > class secureStr: Unless you have a need for backwards compatibility, you probably should use new-style classes rather than classic classes. > def __init__(self, str): > self.__s = [] > for i in range(len(str)): > self.s += str[i] > > def __str__(self): > return "".join(self.__s) > > def wipe(self): > for i in range(len(self.__s)): > self.s[i] = '\x00' > > def __del__(self): > self.wipe() How do you prevent the operating system from paging the block of memory to disk? It's all well and good to wipe the password located at address 0xb7f7a32c in RAM but that's not going to save you when the bad guys locate it in the swap file. In any case, an easier way to get the above illusion of security is this: class secureStr(list): def __str__(self): return "".join(self) def wipe(self): for i in xrange(len(self)): self[i] = '\x00' def __del__(self): self.wipe() It contains the exact same security holes as your code, but is shorter. > My question is how do I write a function to securely get the password > from user (in text mode)? If I do sth like > > import getpass > securePass = secureStr(getpass,getpass()) > > doesn't that create an immediate string object that will stay in memory? Yes, the string object will be deleted but not over-written. That may or may not happen. One way to increase the chances of that happening is: import getpass securePass = secureStr(getpass.getpass()) # not actually secure s = '\00'*len(securePass) It's not guaranteed to over-write the memory location with the intermediate string object, but you might get lucky. What's the threat you're defending against? It seems to me that you are worrying about somebody (a person? another program? the operating system?) reading the password out of Python's free memory blocks. Fair enough, attackers can and have recovered passwords out of free memory. But a far bigger security hole is that the password is sitting there in your securePass variable in plain text. What are you doing about that? -- Steven From nick.fabry at coredump.us Wed Mar 19 10:12:15 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Wed, 19 Mar 2008 10:12:15 -0400 Subject: Improving datetime Message-ID: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> This is a query for information as to how to proceed. I am not a professional programmer, but I use Python a great deal to help me in my main job, which involves designing schedules for a global airline. As such, I use datetime (and dateutil) extensively, and after much use, I have come to some conclusions about their utility, and how to improve them. Some of these changes are quite minor and would result in a large increase in utility (low hanging fruit), while some changes are major, and would result in less obvious benefits - but these changes would increase the 'Python Zen' of them. So - where should I propose these changes? Here? python-dev? Should I write up a full PEP or should I just give a more informal outline with code samples? I would volunteer to help maintain/improve datetime, but I don't speak C at all, unfortunately, and datetime appears to be in C. In addition, I have little contact with the Python community - I work somewhat 'solo' when it comes to my programming projects. So, are there other people out there who use datetime? Dateutil? What do you find the deficits/benefits of these modules to be? Thank you for your thoughts.... Nick Fabry From cantabile.03 at wanadoo.fr Sun Mar 16 22:03:41 2008 From: cantabile.03 at wanadoo.fr (Unknown) Date: 17 Mar 2008 02:03:41 GMT Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> <47dc43e0$0$849$ba4acef3@news.orange.fr> <65faeeb8-d1d2-4d50-8421-f19a5ceb8ba5@8g2000hsu.googlegroups.com> Message-ID: <47ddd17d$0$899$ba4acef3@news.orange.fr> Le Sat, 15 Mar 2008 16:55:45 -0700, joep a ?crit?: > you can also use standard module fileinput.input with ''inplace'' option > which backs up original file automatically. > > from python help for fileinput: > > Optional in-place filtering: if the keyword argument inplace=1 is passed > to input() or to the FileInput constructor, the file is moved to a > backup file and standard output is directed to the input file (if a file > of the same name as the backup file already exists, it will be replaced > silently). Thanks for the idea :) What I do not get is how I can replace a string with that. If I write something like: for line in filehandle.input('myfile.txt', inplace=1): rx = re.match(r'^\s*(\d+).*',line ) if not rx: continue else: oldValue = rx.group(1) Value = 123456789 line = string.replace(line, oldValue, "%d" Value) print line break This code replaces the whole file with line, instead of replacinf the old value with the new one. Did I forget something ? From gerdusvanzyl at gmail.com Wed Mar 12 10:18:48 2008 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: Wed, 12 Mar 2008 07:18:48 -0700 (PDT) Subject: List Combinations Message-ID: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> I have a list that looks like this: [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] how can I get all the combinations thereof that looks like as follows: 3,9,5,4,2 3,1,5,4,2 3,9,5,4,5 3,1,5,4,5 etc. Thank You, Gerdus From deets at nospam.web.de Wed Mar 19 03:56:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 08:56:45 +0100 Subject: method to create class property In-Reply-To: References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> <64astpF29u3k1U1@mid.uni-berlin.de> Message-ID: <64bva2F2b4s68U1@mid.uni-berlin.de> > Isn't that:: > > > > @propset(foo) > > def foo(self, value): > > self._value = value Yeah, you are right. Diez From gagsl-py2 at yahoo.com.ar Wed Mar 19 20:07:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 21:07:40 -0300 Subject: Python to C/C++ References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: En Wed, 19 Mar 2008 13:17:01 -0300, Blubaugh, David A. escribi?: > Has anyone worked with a translator that will translate python to c/c++ > source code? I know that there is already one translator of this nature > (shedskin compiler) out there. However, it is still in the beta stage > of development. Does anyone know of a more developed version of a > translator of this nature? There is also Cython (based on Pyrex). But they use a different approach than ShedSkin. You may want to read this thread: http://thread.gmane.org/gmane.comp.compilers.shedskin.general/66 -- Gabriel Genellina From allen.fowler at yahoo.com Tue Mar 4 13:53:43 2008 From: allen.fowler at yahoo.com (allen.fowler) Date: Tue, 4 Mar 2008 10:53:43 -0800 (PST) Subject: Edit MP4 and/or WMV file metadata? Message-ID: <3fd17c11-6efa-4474-82c7-949e6c7ce5cc@e10g2000prf.googlegroups.com> Hello, I have many WMV files with bad embedded author/title/date information. However, the correct information is correctly encoded in the file name.. i.e. "title-author-date.wmv" I am about to conver these fiiles to MP$ for use on an iPod. The video software I am using will, I think, transfer the metadata from the WMV to MP4 files. So, two questions: 1) Is there a python module I can use to edit the metadata in MP4 files? 2) Failing that, is there a python module I can use to edit the metadata in the WMV files, and hope the data makes it through the conversion? -- Thank you From Dominique.Holzwarth at ch.delarue.com Mon Mar 31 05:05:39 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Mon, 31 Mar 2008 10:05:39 +0100 Subject: Problem with method overriding from base class Message-ID: <5213E58D85BC414998FA553C701E386C0EDD00FE2F@SGBD012511.dlrmail.ad.delarue.com> Hello everyone I have defined some sort of 'interface class' and a factory function that creates instance objects of specific classes, which implement that interface: Interface definition: *************************************************************************************** import GUI.webGUI as webGUI class EditInterface(webGUI.WebGUI): def addEntry(self, *p): raise 'EditInterface.addEntry(): Interface must not be called directly' def clearScreen(self, *p): raise 'EditInterface.clearScreen(): Interface must not be called directly' def deleteEntry(self, *p): raise 'EditInterface.deleteEntry(): Interface must not be called directly' def editEntry(self, *p): raise 'EditInterface.editEntry(): Interface must not be called directly' def processUserInput(self, *p): raise 'EditInterface.processUserInput(): Interface must not be called directly' def show(self, entry, statustext): raise 'EditInterface.show(): Interface must not be called directly' *************************************************************************************** Factory: *************************************************************************************** def factory(type, *p): if type == common.databaseEntryTypes[0]: return module1.Class1(*p); elif type == common.databaseEntryTypes[1]: return module2.Class2(*p); elif type == common.databaseEntryTypes[2]: return module3.Class3(*p); elif type == common.databaseEntryTypes[3]: return module4.Class4(*p); *************************************************************************************** Implementing Class1: *************************************************************************************** import editInterface class Class1(editInterface.EditInterface): def __init__(self, product, database): # do something here ... def showEntry(self, entry, statustext): # do something here as well, return some string... *************************************************************************************** Now, when I want to create an Instance of Class1 I do: myClass1Instance = factory.factory(common.databaseEntryTypes[1], 'Name', databaseObj ) Which seems to work fine according to the debugger. But when I do next: msg = myClass1Instance.show(firstEntry, '') Then the show() method of the class 'EditInterface' is called instead of the show() method of the class 'Class1' !! Does anyone have an idea why the method of the base class is called instead of the method of the derived class and how can I do it, so that the show() of Class1 is called instead? Greetings Dominique (did some data hiding there, but shouldn't really matter for the problem ;-)) From michael.wieher at gmail.com Fri Mar 7 11:29:39 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 10:29:39 -0600 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: Placing 2 spaces after a period is standard, grammatically correct English, at least as I was taught... I don't know who Strunk or White are. Maybe Mr. Pink has a book you can refer to instead. 2008/3/7, K Viltersten : > > I've been recommended reading of: > http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i > need to get elaborated. > > > 1. When writing English, Strunk and > White apply. > > Where can i download it? Am i actually > expected to read the whole book? How > many people actually do aply it? > > > 2. You should use two spaces after a > sentence-ending period. > > For heavens sake, why? I've always been > obstructed by the double blanks but > tolerated them. Now, that i read that > it actually is a recommendation, i need > to ask about the purpose. > > > Thanks for the input in advance. > > -- > Regards > Konrad Viltersten > -------------------------------- > sleep - a substitute for coffee for the poor > ambition - lack of sense to be lazy > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shahmed at sfwmd.gov Thu Mar 20 10:11:44 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 20 Mar 2008 10:11:44 -0400 Subject: Deleting Microsoft access database In-Reply-To: Message-ID: <14A2A120D369B6469BB154B2D2DC34D20A747C3C@EXCHVS01.ad.sfwmd.gov> I have a Microsoft Access database that I want to delete whether anyone is using that file. The database is already read only mode residing in a server, users are opening in read only mode. I want to delete that file, I remove read only check but could not delete that file. Getting error message: Cannot delete xxx : It is being used by another person or program. Any help is highly appreciated. Thanks sa From jgv-home at comcast.net Tue Mar 25 20:03:40 2008 From: jgv-home at comcast.net (jv) Date: Tue, 25 Mar 2008 18:03:40 -0600 Subject: how to dynamically create class methods ? In-Reply-To: <13uj0m4qd1dit79@corp.supernews.com> References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: <47E992DC.2050800@comcast.net> Steven D'Aprano wrote: > On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: > >> As per your suggestion, I tried looking at include/code.h and >> include/funcobject.h (my MS Windows distribution does not appear to >> contain .c files). However, since I'm not a C programmer, I did not >> find the .h files all that helpful. > > I'm hardly surprised. The naivety of those who insist that the "best way > to understand how new.function and new.code work" is to look at the C > source code for object is amusing. Not everybody reads C. This is a > Python group, and surely the best way would be to see some good examples > using *Python*. > > >> What I failed to make clear in my original posting is that the >> functions must be created dynamically using information in a *record* >> as the code iterates over all *records*. So, I can not pre-define the >> functions and then simply select the desired one at run-time. > > Here's an example that might help. > > > class MyClass(object): > pass > > records = ["spam", "ham"] > for record in records: > # define a new function > def f(n): > return (record + " ")*n > # create a new instance > instance = MyClass() > # and dynamically add a method to it > setattr(instance, 'execute', f) > instance.execute(5) > > > Gabriel, Steven, Thanks for taking the time to respond with such clear examples. All I can say is: "when will I ever learn **everything** in Python is an object -- including functions"! I had a suspicion I was making a simple task complicated. -- jv From nospam at nospam.com Mon Mar 10 23:21:52 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 11 Mar 2008 04:21:52 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: On Mon, 10 Mar 2008 11:27:06 -0400, "Malcolm Greene" wrote: >Any suggestions on an alternative Python client-side GUI library (pyQT >?) or tips on where I can find out more about wxPython/wxWidget >problems? One thing that bothers me is that it seems like there's no ecosystem around it, so the only widgets available are those that come from wxWidgets proper. For instance, I find the grid object a bit poor-featured compared to what's available for VB6, .Net, or Delphi, but I didn't find alternatives. From josef.pktd at gmail.com Sun Mar 16 11:41:51 2008 From: josef.pktd at gmail.com (joep) Date: Sun, 16 Mar 2008 08:41:51 -0700 (PDT) Subject: Spaces in path name References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> Message-ID: <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> Tim Golden wrote: > Tim Golden wrote: > > What I haven't investigated yet is whether the additional flags > > your example is passing (shell=True etc.) cause the main Popen > > mechanism to take a different path. > > Sure enough, passing shell=True -- which is probably quite > a rare requirement -- causes the code to change the call > from "a.exe b.doc" to '%COMSPEC% /c "a.exe" "b.doc"'. > The quoting rules (from cmd /?) are slightly involved but > I can't see at first why this shouldn't work. However it > clearly doesn't so I'll try to put together either a patch > to the subprocess code or to the docs warning of the behaviour. > > I think that, in general, you need to pass shell=True far less > often that you might imagine. (Possibly only for internal > commands like dir, copy etc.). > > TJG Thanks, I didn't know it is possible to drop the shell=True. The explanation of the subprocess model are not very clear to me and the examples are quite incomplete. I got it to work by trial and error and looking at the usage in different packages. Dropping shell=True works well for my case, no error messages and it still captures the standard output: p = subprocess.Popen([ r"C:\Program Files\WinRAR\Rar.exe","v", r"C:\temp\Copy of papers.rar"], stdout=subprocess.PIPE) I am still looking at different versions, and the cases when it works and when it doesn't are still confusing. Josef From gagsl-py2 at yahoo.com.ar Sat Mar 29 00:24:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 01:24:16 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 23:23:01 -0300, escribi?: > On Mar 28, 1:57?pm, "Gabriel Genellina" > wrote: >> En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: >> >> > I am trying to install the twitter python wrapper...I got that >> > installed just fine, but am having serious troubles getting the >> > simplejson package to install. ?I need help diagnosing where this is >> > failing. ?I am trying to use: >> >> >http://pypi.python.org/pypi/simplejson >> >> > and I run "python setup.py build" and then "python setup.py install", >> > which both seem to work just fine. I tried to install the package but failed. Looks like the setup.py used by simplejson is broken - doesn't handle well the case when the C extension can't be compiled. When I run `python setup.py install` I got this message: building 'simplejson._speedups' extension ********************************************************************** WARNING: The C extension could not be compiled, speedups are not enabled. Below is the output showing how the compilation failed: Python was built with Visual Studio version 7.1, and extensions need to be built with the same version of the compiler, but it isn't installed. ********************************************************************** and later: removing simplejson.egg-info\native_libs.txt ... error: can't copy 'simplejson.egg-info\native_libs.txt': doesn't exist or not a regular file I suggest that you remove the simplejson-xxxxxx.egg file and delete the simplejson entry in easy-install.pth (both in your site-packages directory) Then extract the simplejson directory from inside the original .tar.gz archive into your site-packages directory (so you end up by example with a .../site-packages/simplejson/decoder.py file, among others) That appears to be enough; import simplejson worked fine for me. I hate those f****ng eggs. Ah, and I hate easy_install too. -- Gabriel Genellina From geert at nznl.com Tue Mar 18 18:47:00 2008 From: geert at nznl.com (geert) Date: Tue, 18 Mar 2008 15:47:00 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> Message-ID: On Mar 18, 6:56?pm, geert wrote: > On Mar 14, 1:15?pm, martin.lal... at gmail.com wrote: > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > Just wanted to let you know that I've solved my problem. The solution > is to compile mysql using > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > ./configure --disable-dependency-tracking ?--enable-thread-safe-client > --prefix=/usr/local/mysql > > You then go this way to get it running on your machine: > > http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > Then reinstall MySQLdb. Magic! > > Geert Seems that I've yelled success to quickly. Everything's ok as long as I just run the django dev server, but moving to apache through mod_wsgi brings a well-known but less than comforting complaint: [Tue Mar 18 23:34:25 2008] [error] [client ::1] mod_wsgi (pid=2352): Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ LN/LNApache.wsgi'., referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent call last):, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in __call__, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = self.get_response(request), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/core/handlers/base.py", line 64, in get_response, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = middleware_method(request), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/contrib/sessions/middleware.py", line 13, in process_request, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line 2, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.contrib.sessions.models import Session, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db import models, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/db/__init__.py", line 17, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, ['']), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no suitable image found. Did find:, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- tmp/_mysql.so: no matching architecture in universal wrapper, referer: http://localhost/images/ mmmmmm Geert From modelnine at modelnine.org Wed Mar 26 14:45:34 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 26 Mar 2008 19:45:34 +0100 Subject: what does ^ do in python In-Reply-To: <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <200803261945.34530.modelnine@modelnine.org> Am Mittwoch, 26. M?rz 2008 19:04:44 schrieb David Anderson: > HOw can we use express pointers as in C or python? There's no such thing as a pointer in Python, so you can't "express" them either. Was this what you were trying to ask? -- Heiko Wundram From pavlovevidence at gmail.com Mon Mar 10 10:39:35 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Mar 2008 07:39:35 -0700 (PDT) Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: On Mar 8, 5:15 pm, "Terry Reedy" wrote: > I gave a clear and coherent explanation of how while derives from if, > and correspondingly, how while-else derives from if-else, to help those who > want to read and write Python code. Building on the pseudo-snippet above, > one can write > > while loop_condition: > > if break_condition: > > break > > else: > > > Python allows one to have both break-only and completion-only sections > together in one compound statement and *without* having to fiddle with a > special flag variable. I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. Just to play Devil's advocate, there is one draw drawback to "such elegance": when there are multiple break statements. Which means you'd have to duplicate the break-only condition, or refactor somehow (which may or may not be suitable). There have been a couple occasions where I felt the best solution was to a temporary varible like so: completed = False while loop_condition: if break_condition: break if some_other_break_condition: break else: completed = False if not completed: It felt icky but we're all still here so it couldn't have been that bad. Carl Banks From Graham.Dumpleton at gmail.com Wed Mar 19 19:47:00 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 19 Mar 2008 16:47:00 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> <7900f1db-16a5-45d1-ada3-962ac0e712b8@e6g2000prf.googlegroups.com> <046c9579-9ff3-44ad-86b7-0c64c8a606ed@8g2000hsu.googlegroups.com> Message-ID: On Mar 19, 9:30 pm, geert wrote: > On Mar 19, 2:26 am, Graham Dumpleton > wrote: > > > > > On Mar 19, 9:47 am, geert wrote: > > > > On Mar 18, 6:56 pm, geert wrote: > > > > > On Mar 14, 1:15 pm, martin.lal... at gmail.com wrote: > > > > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > > > > Just wanted to let you know that I've solved my problem. The solution > > > > is to compile mysql using > > > > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > > > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > > ./configure --disable-dependency-tracking --enable-thread-safe-client > > > > --prefix=/usr/local/mysql > > > > > You then go this way to get it running on your machine: > > > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > > > > Then reinstall MySQLdb. Magic! > > > > > Geert > > > > Seems that I've yelled success to quickly. Everything's ok as long as > > > I just run the django dev server, but moving to apache throughmod_wsgibrings a well-known but less than comforting complaint: > > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352): > > > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ > > > LN/LNApache.wsgi'., referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent > > > call last):, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in > > > __call__, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > > > self.get_response(request), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in > > > get_response, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > > > middleware_method(request), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line > > > 13, in process_request, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine = > > > __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line > > > 2, in , referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from > > > django.contrib.sessions.models import Session, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, > > > in , referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db > > > import models, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/db/__init__.py", line 17, in , > > > referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend = > > > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, > > > {}, ['']), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, > > > in , referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise > > > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: > > > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ > > > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no > > > suitable image found. Did find:, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ > > > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- > > > tmp/_mysql.so: no matching architecture in universal wrapper, referer:http://localhost/images/ > > > Did you again confirm that running: > > > file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5- > > macosx-10.5-i386.egg-tmp/_mysql.so > > > shows the .so having the required architectures, specifically what > > Apache runs as (eg. x86_64)? > > > Do the gcc compiler flags when building and linking the .so file show > > all the architecture flags? > > > Have you empty the Python egg cache to make sure it isn't an older > > compiled version? > > > Graham > > Hi all, > > GOT IT! > > I have every running now. So, to sum it all up: > > I'm on a new intel mac with a 64-bit capable processor running macosx > 10.5.2. > > I have httpd (apache2) running as a 64 bit app, which it would of > course on a 64-bit machine. Activity monitor confirms this. > > I compiled mysql from source, configured as stated below: > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > ./configure --disable-dependency-tracking --enable-thread-safe- > client > --prefix=/usr/local/mysql > > Then camemod_wsgi, just out of the box. > > Then came MySQLdb. > > Extracted the tar, then edited _mysql.c. Commented lines 37 - 39: > > //#ifndef uint > //#define uint unsigned int > //#endif > > and changed this: > uint port = MYSQL_PORT; > uint client_flag = 0; > > to this: > unsigned int port = MYSQL_PORT; > unsigned int client_flag = 0; > > on lines 484 and 485 > > Then - but I don't know if this is really (always) necessary, in > site.cfg I changed Threadsafe = True to False. > > I set the ARCHFLAGS, but I don't think this helped one inch. > > ARCHFLAGS='-arch ppc -arch ppc64 -arch i386 -arch x86_64' > > OK. So then I went sudo python setup.py build. (I realise that the > sudo isn't required just to do a build) > > There, I noticed this: > > creating build/temp.macosx-10.5-i386-2.5 > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- > madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes - > DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -pipe - > Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/ > include/mysql -I/System/Library/Frameworks/Python.framework/Versions/ > 2.5/include/python2.5 -c _mysql.c -o build/temp.macosx-10.5-i386-2.5/ > _mysql.o -arch i386 -arch x86_64 -arch ppc7400 -arch ppc64 > > You see, here _mysql.o is being created. If you do file _mysql.o, you > get: > > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o: Mach-O universal binary with 4 architectures > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture i386): Mach-O object i386 > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture x86_64): Mach-O 64-bit object > x86_64 > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture ppc7400): Mach-O object ppc > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture ppc64): Mach-O 64-bit object ppc64 > > which is ok. > > But, strangely, when _mysql.so is created in the next step, gcc > doesn't add all the arch flags: > > gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch i386 -arch ppc > build/temp.macosx-10.5-i386-2.5/_mysql.o -L/usr/local/mysql/lib/mysql - > lmysqlclient -lz -lm -o build/lib.macosx-10.5-i386-2.5/_mysql.so > > and you end up with this: > > geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/geert/ > Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/_mysql.so > /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ > _mysql.so: Mach-O universal binary with 2 architectures > /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ > _mysql.so (for architecture i386): Mach-O bundle i386 > /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ > _mysql.so (for architecture ppc7400): Mach-O bundle ppc > > which is most definitely NOT ok. > > So I did this: > > sudo gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch ppc -arch > ppc64 -arch i386 -arch x86_64 build/temp.macosx-10.5-i386-2.5/_mysql.o > -L/usr/local/mysql/lib/mysql -lmysqlclient -lz -lm -o build/ > lib.macosx-10.5-i386-2.5/_mysql.so > > adding the arch flags myself, and running gcc again, under sudo. > > and lo and behold.... > > geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/ > geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/ > _mysql.so > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so: Mach-O universal binary with 4 architectures > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture ppc7400): Mach-O bundle ppc > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture ppc64): Mach-O 64-bit bundle > ppc64 > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture i386): Mach-O bundle i386 > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture x86_64): Mach-O 64-bit bundle > x86_64 > > Well, it only took 20 years off my life span and all the hairs on my > head :) I don't have access to MacOS X OS supplied Python 2.5 at moment, but if distutils used by setup.py is ignoring ARCHFLAGS for the link then that may be an issue with distutils. More likely though is that MySQL setup.py is setting some option which is causing ARCHFLAGS to be ignored. Strange thing is I can't find ARCHFLAGS in original Python 2.5 source I have, so checking it may be specific to MacOS X OS supplied Python. Will need to check when I get home to my Leopard box. Graham From tmp1 at viltersten.com Fri Mar 7 11:31:35 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 17:31:35 +0100 Subject: Regarding coding style Message-ID: <63d80bF273nraU1@mid.individual.net> I've been recommended reading of: http://www.python.org/dev/peps/pep-0008/ and in there i saw two things that i need to get elaborated. 1. When writing English, Strunk and White apply. Where can i download it? Am i actually expected to read the whole book? How many people actually do aply it? 2. You should use two spaces after a sentence-ending period. For heavens sake, why? I've always been obstructed by the double blanks but tolerated them. Now, that i read that it actually is a recommendation, i need to ask about the purpose. Thanks for the input in advance. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From tms at zeetix.com Sat Mar 15 13:54:35 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 13:54:35 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <004401c886c5$a1aba880$0200a8c0@TMSMAIN> > Somehow I don't get what you are after. The ' doesn't have to be escaped > at all if " are used to delimit the string. If ' are used as delimiters > then \' is a correct escaping. What is the problem with that!? If I delimit the string with double quote, then I have to escape every double quote in whatever I serialize. I'm moving strict html from the server to the browser, and therefore the value of every tag attribute is delimited by double quotes. That means that I'd have to escape every double quote, and there are MANY more of them. Thanks, Tom From justus.schwabedal at gmx.de Thu Mar 13 18:47:58 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Thu, 13 Mar 2008 23:47:58 +0100 Subject: Problem with exec Message-ID: I'm trying to parallise with python. Specifically I'm sending code to the processes and let them exec this code (in ascii form). However I ran into a problem with Namespaces (I think) which I do not understand. Here's what I do first: --------------------------------------- bash-3.2$ cat execBug.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ exec header print "f() =",f() bash-3.2$ ./execBug.py f() = 0.633306324515 it est: it works. However when I do this: bash-3.2$ cat execBug2.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ def g(): exec header return f() print "g() =",g() bash-3.2$ ./execBug2.py g() = Traceback (most recent call last): File "./execBug2.py", line 10, in print "g() =",g() File "./execBug2.py", line 9, in g return f() File "", line 4, in f NameError: global name 'randn' is not defined bash-3.2$ ??? I get this global name error. I can fix it with adding some line like "global randn" but I don't want to do this. I want to do exactly what I wrote: Import the function scipy.randn in the local namespace of the function "g" so that "return f()" makes sense. Can anybody help me out? Yours Justus From timr at probo.com Thu Mar 20 23:31:27 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Mar 2008 03:31:27 GMT Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> <29cd9085-b70f-4873-899e-3837d8e42d90@u69g2000hse.googlegroups.com> Message-ID: Gowri wrote: > >I understand it's JSON. My problem is that it just prints crazy >characters instead of the JSON data. Ah, I see. I didn't get that from your original post. >Like I mentioned, this happens on >my windows machine which has python 2.5. On the other hand, the same >code worked perfectly great on my linux machine with python 2.3.4. >What could the problem be? I'm not sure. It worked correctly on my Windows machine with Python 2.4.4. Are you going through a proxy? Are you able to read other (non-JSON) web pages using urllib2? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From xelapond at gmail.com Sun Mar 30 10:39:30 2008 From: xelapond at gmail.com (Alex Teiche) Date: Sun, 30 Mar 2008 07:39:30 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: On Mar 30, 2:08 am, Phil Thompson wrote: > On Sunday 30 March 2008, Alex Teiche wrote: > > > Hello, > > > I am pretty new to Python, and have never learned C++. I am trying to > > implement the following thing into my python application: > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > it, but I could not get this specific thing to work. Can someone give > > me some hints as to get it working in Python? > > > Thanks a ton, > > > Alex > > Have you looked at PyQt's systray example? > > Phil No, where do I find the example? Thanks, Alex From python.list at tim.thechases.com Mon Mar 10 13:29:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Mar 2008 12:29:51 -0500 Subject: lowercase u before string in "python for windows" In-Reply-To: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> References: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> Message-ID: <47D5700F.80207@tim.thechases.com> > why does this occur when using the python windows extensions? all > string are prefixed by a lowercase "u". They are Unicode strings: http://docs.python.org/ref/strings.html > is there a newsgroup explicitly for python windows extensions? Not that I know of, other than what's described here: https://sourceforge.net/mail/?group_id=78018 -tkc From castironpi at gmail.com Sat Mar 15 05:00:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 02:00:44 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> On Mar 15, 3:33?am, "Gabriel Genellina" wrote: > En Thu, 13 Mar 2008 15:18:44 -0200, escribi?: > > > Well, lets say you have a situation where you're going to be > > alternating between sending large and small chunks of data. Is the > > solution to create a NetworkBuffer class and only call send when the > > buffer is full, always recv(8192)? > > No need to reinvent the wheel. socket objects already have a makefile ? > method returning a file-like object, which behaves like a buffered socket. Newbie question: Can you write to the 'file-like object' a pickle, and receive it intact-- as one string with nothing else? I want to know because I want to send two pickles. From duncan.booth at invalid.invalid Mon Mar 31 03:36:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 07:36:00 GMT Subject: Licensing References: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> Message-ID: Paul Boddie wrote: > Note that the Python Cookbook says this about licensing: "Except where > otherwise noted, recipes in the Python Cookbook are published under > the Python license." The link is incorrect, but I presume they mean > this licence: > > http://www.python.org/psf/license/ > I don't have a printed copy, but Google Books has it (not sure which edition I found) and page xix says: Given the nature of the cookbook, we wanted the recipes to be usable under any circumstances where Python could be used. In other words, we wanted to ensure completely unfettered use, in the same spirit as the Python license. Unfortunately, the Python license cannot really be used to refer to anything other than Python itself. As a compromise, we chose to use the modified Berkeley license, which is considered the most liberal of licenses. ... and then the license follows ... So, if the recipe is in the printed cookbook the licensing is clear (primarily you must retain the copyright notice). From hdante at gmail.com Sun Mar 30 07:48:59 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 04:48:59 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> Message-ID: <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> On Mar 30, 4:31 am, John Machin wrote: > On Mar 30, 3:58 pm, hdante wrote: > > > > > On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" > > > wrote: > > > Hello, > > > > I am having trouble writing the code to read a binary string. I would > > > like to extract the values for use in a calculation. > > > > Any help would be great. > > > I'm too lazy to debug your binary string, but I suggest that you > > completely throw away the binary file and restart with a database or > > structured text. See, for example: > > > http://pyyaml.org/wiki/PyYAML > > > If you have some legacy binary file that you need to process, try > > creating a C program that freads the binary file and printfs a text > > equivalent. > > ... and that couldn't be done faster and better in Python?? No. A C struct is done faster and better than python (thus, the correctness check is faster in C). Also, chances are high that there's already an include file with the binary structure. From fhaxbox66 at googlemail.com Mon Mar 10 05:53:47 2008 From: fhaxbox66 at googlemail.com (fhaxbox66 at googlemail.com) Date: Mon, 10 Mar 2008 02:53:47 -0700 (PDT) Subject: Hyphenation with PyHyphen - public mailing list now online Message-ID: <2baffb86-8f38-46a3-9452-cbcece8813f5@60g2000hsy.googlegroups.com> Hi, there is now a public mailing list open to anyone who is interested in discussing issues concerning PyHyphen. Join the list at http://groups.google.com/group/pyhyphen, or visit the project home page at http://pyhyphen.googlecode.com to get the latest sources via Subversion. Regards Leo From gregory.bronner at lehman.com Fri Mar 14 10:45:06 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 14 Mar 2008 10:45:06 -0400 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD29B6@nypcmg1exms318.leh.lbcorp.lehman.com> This is not entirely true: Symptoms of increasing memory usage are either because a) you are keeping too much data around in user accessable memory (likely) b) you are creating self-referential structures that are not garbage collected (also likely) c) You have memory leaks in underlying C extension modules. For category a), you are on your own. For category b), you can use various methods in the gc module to print out everything that is still 'live'. You can also recompile python to build a list of all objects that are still live. For category c), a tool like valgrind or purify often helps. Create a simple example rather than trying to run it on your whole application. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Friday, March 14, 2008 10:16 AM To: python-list at python.org Subject: Re: Urgent : How to do memory leaks detection in python ? 2008/3/14, Pradeep Rai < >: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep Python doesn't have memory leaks. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fdrake at acm.org Sun Mar 2 19:43:33 2008 From: fdrake at acm.org (Fred Drake) Date: Sun, 2 Mar 2008 19:43:33 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <47CB168A.103@v.loewis.de> References: <47CB168A.103@v.loewis.de> Message-ID: <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> On Mar 2, 2008, at 4:05 PM, Martin v. L?wis wrote: > Assuming no major problems crop up, a final release of Python 2.4.4 > will > follow in about a week's time. I do suppose you mean 2.4.5. 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include - DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o ./Modules/posixmodule.c: In function ?posix_setpgrp?: ./Modules/posixmodule.c:3145: error: too few arguments to function ?setpgrp? make: *** [Modules/posixmodule.o] Error 1 I can only presume I'm doing something wrong at this point, since I don't consider myself a Mac OS X developer. -Fred -- Fred Drake From dteslenko at gmail.com Wed Mar 5 09:55:59 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 5 Mar 2008 17:55:59 +0300 Subject: draining pipes simultaneously In-Reply-To: References: Message-ID: <91325fec0803050655i69603477s1aff2986022daba7@mail.gmail.com> On Wed, Mar 5, 2008 at 3:39 PM, wrote: > time.sleep() pauses ony the thread that executes it, not the > others. And queue objects can hold large amount of data (if you have > the RAM), > so unless your subprocess is outputting data very fast, you should not > have data loss. > Anyway, if it works for you ... :-) After some testing I'll agree :) Without time.sleep() in main thread python eats up all aviable processor time From deets at nospam.web.de Sat Mar 1 12:13:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 18:13:59 +0100 Subject: at-exit-thread In-Reply-To: <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> References: <62r68tF220j59U1@mid.uni-berlin.de> <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> Message-ID: <62th6qF24pafdU1@mid.uni-berlin.de> castironpi at gmail.com schrieb: > On Feb 29, 1:55 pm, "Diez B. Roggisch" wrote: >> castiro... at gmail.com schrieb: >> >>> The Python main interpreter has an at-exit list of callables, which >>> are called when the interpreter exits. Can threads have one? What's >>> involved, or is the best way merely to subclass Thread? >> Is that some sort of trick-question? >> >> class MyThread(Thread): >> >> def run(self): >> while some_condition: >> do_something() >> do_something_after_the_thread_ends() >> >> The atexit stuff is for process-termination which is/may be induced by >> external signals - which is the reason why these callbacks extist. >> Threads don't have that, thus no need. > > That depends. If a thread adds an object it creates to a nonlocal > collection, such as a class-static set, does it have to maintain a > list of all such objects, just to get the right ones destroyed on > completion? Processes destroy their garbage hassle-free; how can > threads? And don't forget Thread.run( self ) in the example, if > anyone ever wants to make use of the 'target' keyword. That is both totally unrelated to the original question and plain wrong. Processes don't destroy their garbage themselves, not automagically or anything. If you _want_, you can put atexit-handlers that do clean up some stuff, but you'll have to equip them with the necessary context yourself. And a kill -9 won't run *anything* of your own code. The OS is eventually responsible for cleaning up. Diez From jasynwiener at gmail.com Sun Mar 16 13:05:03 2008 From: jasynwiener at gmail.com (jasonwiener) Date: Sun, 16 Mar 2008 10:05:03 -0700 (PDT) Subject: Strange problem with structs Linux vs. Mac Message-ID: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> Hi- I am having a VERY odd problem with unpacking right now. I'm reading data from a binary file and then using a very simple struct.unpack to get a long. Works fine on my MacBook, but when I push it to a Linux box,it acts differently and ends up pewking. here's the code snippet: fread.seek(0,0) tmp_rebuild = fread.read() fread.close() tmp_long = tmp_rebuild[0:4] print tmp_long.encode('hex') print repr(tmp_long) unpacked_long = struct.unpack('I', tmp_rebuild[0:4])[0] print 'unpacked_long: %s' % unpacked_long my MacBook produces: 1ec6f3b4 '\x1e\xc6\xf3\xb4' unpacked_long: 516354996 but on the linux box the same code produces: 1ec6f3b4 '\x1e\xc6\xf3\xb4' unpacked_long: 3035874846 the data looks to be the same, but the unpacking seems to treat it differently. Has anyone an idea of why this happens??? Thanks- J. From grahn+nntp at snipabacken.se Sun Mar 30 17:39:46 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 21:39:46 GMT Subject: Pexpect question. References: Message-ID: On Fri, 28 Mar 2008 08:12:36 -0700 (PDT), Paul Lemelle wrote: > I am trying separate a script that users pexpect into > various functions within the same expect session. The > problem is that the function does not return control > back Main. I do not understand what that sentence means. > Any insight into this issue would be > greatly appreciated. Below is sample code of the > problem. First, what is the purpose of this program? It seems to be a more tedious way to get an ssh login to some Unix host. Ssh can be configured to do many things; maybe you do not need Python at all? Second, it will fail as soon as you use the undefined object 'chk'. Third, if "not return control back Main" means "sshcon() does not return", then it is by design. You call go.interact(), which hands over control to the user until he types an escape sequence. See the pexpect documentation. Fourth, sshcon() does not handle the full dialogue ssh can give you. If you get "are you sure you want to connect" etc, you will hang until pexpect.TIMEOUT is thrown. I have reformatted the source code to be more readable: > import pexpect > > def sshcon(host, password): > go = pexpect.spawn ('/usr/bin/ssh -l root %s ' % host) > go.expect ('Password: ') > go.sendline (password) > go.interact() > > #get node info for both clusters. > C1_node = raw_input("Enter the ip address for node on cluster 1: ") > C1_pass = raw_input("Enter the password for the node on cluster 1: ") > > sshcon(C1_node, C1_pass) > > #go to the path > chk.expect('# ') > chk.sendline('ls') > > chk.interact() /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From abli at freemail.hu Sat Mar 29 03:42:32 2008 From: abli at freemail.hu (Daniel Abel) Date: Sat, 29 Mar 2008 00:42:32 -0700 (PDT) Subject: Using unittest for benchmarking / speed improvements Message-ID: Hi! As everyone knows, using unittests to monitor and improve the correctness of code is really handy. Is there a good system for using unittests to monitor / improve the _speed_ of code? I.e. I would like a system which every time when running a test, also measures the time the test took, and stores it in a file somewhere. (For example, stores date&time, svn revision, and the time the test took) Then, the programmer can plot that in gnuplot / etc, and see whether the speed of the code is improving or not, and also compare different tests to each other (when comparing the speed of different implementations). Also, svn revisions could be labelled with svn checkin comments, so that one can easily associate any improvement / regression with the summary of the change. I was thinking about something built on top of nose, and hoping someone has already created such a thing. (After all, 'benchmark before optimize' and similar are often repeated; such a system seems really necessary for doing that systematically.) I found http://renesd.blogspot.com/2007/08/timing-and-unittests-graphing-speed.html which talks about this idea, and the stopwatch plugin at: http://darcs.idyll.org/~t/projects/pinocchio/doc/#stopwatch-selecting-tests-based-on-execution-time which can measure the time (and would be the easies to extend to store the information I would need) and also the profile nose plugin (included in the nose package) can measure how time is spent _inside_ the test. (which is also handy, but I would only need unittest-level timing, i.e. not as granular as profile creates.) So, is there such a complete framework (i.e. which can compare speed across revisions) or do I have to hack one together myself? (And would others be interested in it?) Thanks in advance, Daniel Abel From 42flicks at gmail.com Tue Mar 4 04:14:38 2008 From: 42flicks at gmail.com (Mike D) Date: Tue, 4 Mar 2008 22:14:38 +1300 Subject: Trouble using XML Reader In-Reply-To: <2b54d4370803030059s722ed808j9ddd7512ed50eea4@mail.gmail.com> References: <2b54d4370803030059s722ed808j9ddd7512ed50eea4@mail.gmail.com> Message-ID: <2b54d4370803040114h3b17b1d4ke487acf53d77d962@mail.gmail.com> On 3/3/08, Mike D <42flicks at gmail.com> wrote: > > Hello, > > I'm using XML Reader (xml.sax.xmlreader.XMLReader) to create an rss > reader. > > I can parse the file but am unsure how to extract the elements I require. > For example: For each element I want the title and description. > > I have some stub code; I want to create a list of objects which include a > title and description. > > I have the following code (a bit hacked up): > > import sys > from xml.sax import make_parser > from xml.sax import handler > > class rssObject(object): > objectList=[] > def addObject(self,object): > rssObject.objectList.append(object) > > class rssObjectDetail(object): > title = "" > content = "" > > > class SimpleHandler(handler.ContentHandler): > def startElement(self,name,attrs): > print name > > def endElement(self,name): > print name > > def characters(self,data): > print data > > > class SimpleDTDHandler(handler.DTDHandler): > def notationDecl(self,name,publicid,systemid): > print "Notation: " , name, publicid, systemid > > def unparsedEntityDecl(self,name,publicid,systemid): > print "UnparsedEntity: " , name, publicid, systemid, ndata > > p= make_parser() > c = SimpleHandler() > p.setContentHandler(c) > p.setDTDHandler(SimpleDTDHandler()) > p.parse('topstories.xml') > > And am using this xml file: > > > > > Stuff.co.nz - Top Stories > http://www.stuff.co.nz > Top Stories from Stuff.co.nz. New Zealand, world, sport, > business & entertainment news on Stuff.co.nz. > en-nz > Fairfax New Zealand Ltd. > 30 > > /static/images/logo.gif > Stuff News > http://www.stuff.co.nz > > > > Prince Harry 'wants to live in Africa' > http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303 > > For Prince Harry it must be the ultimate dark irony: to be in > such a privileged position and have so much opportunity, and yet be unable > to fulfil a dream of fighting for the motherland. > EDMUND TADROS > stuff.co.nz/4423924 > Mon, 03 Mar 2008 00:44:00 GMT > > > > > > Is there something I'm missing? I can't figure out how to correctly > interpret the document using the SAX parser. I'm sure I;'m missing something > obvious :) > > Any tips or advice would be appreciated! Also advice on correctly > implementing what I want to achieve would be appreciated as using > objectList=[] in the ContentHandler seems like a hack. > > Thanks! > My mistake, The provided example is a SAX object, which can be parsed with DOM manipulation. I'll be able to do it now :) Oh, I also posted a hacked up implementation, I understand my classes look awful! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Fri Mar 7 17:10:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 7 Mar 2008 14:10:03 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: On Mar 7, 4:08 pm, shak... at gmail.com wrote: > I'm new to python and I was wondering if there are any intelligent > date/time parsing modules out there. I've looked at strptime (or > whichever it is) and mxDateTime from the eGenix package. I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. > > So are there any modules that allow for that kind of parsing? There's the dateutil module that's a fancy wrapper for the datetime module. The author's site has lots of examples as well as the source: http://labix.org/python-dateutil I use it quite a bit. HTH Mike From jameswhetstone at comcast.net Sat Mar 22 16:06:53 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Sat, 22 Mar 2008 13:06:53 -0700 Subject: How to use boost.python to wrap a class with a pure virtual function that has a 'void *' argument Message-ID: As the subject implies, I'm having trouble wrapping a C++ class that looks like this: struct A { virtual void handleMessage(void *message)=0; }; To wrap this class, I've written the following code: struct AWrapper : A, wrapper { void handleMessage(void *message) { this->get_override("handleMessage")(message); } }; class_("A") .def("handleMessage", pure_virtual(&A::handleMessage)) ; My python test code looks like this: import APackage class aclass(APackage.A): def handleMessage(msg) : print msg But this code crashes when the handleMessage function is called in python (I think) because 'void *' cannot be marshalled. Is there some way around this? Also, since the void* object is intended to be "zero copy", I should probably convert the void * to a PyObject first and re-write my handleMessage to look like this: void handleMessage(void *message) { int size = getMessageSize(message); PyObject *obj = PyBuffer_FromReadWriteMemory(message, size); this->get_override("handleMessage")(obj); } Has anyone done this type of thing? I'm writing this code using MS Visual Studio 8 and if anyone can help, it would *very* appreciated. Thanks! James From metalzong at 163.com Sun Mar 9 10:34:03 2008 From: metalzong at 163.com (Metal Zong) Date: Sun, 9 Mar 2008 22:34:03 +0800 Subject: is operator Message-ID: <004801c881f2$a04081f0$0b020b0a@nb1011> The operator is and is not test for object identity: x is y is true if and only if x and y are the same objects. >>> x = 1 >>> y = 1 >>> x is y True Is this right? Why? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From guidovb1 at invalid Sat Mar 15 17:50:45 2008 From: guidovb1 at invalid (Guido van Brakel) Date: Sat, 15 Mar 2008 22:50:45 +0100 Subject: Convert int to float Message-ID: <47dc4396$0$14348$e4fe514c@news.xs4all.nl> Hello I have this now: > def gem(a): > g = sum(a) / len(a) > return g > print gem([1,2,3,4]) > print gem([1,10,100,1000]) > print gem([1,-2,3,-4,5]) It now gives a int, but I would like to see floats. How can I integrate that into the function? Regards, -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- From __peter__ at web.de Mon Mar 3 05:43:04 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Mar 2008 11:43:04 +0100 Subject: write float to Excel with pyExcelerator write References: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> Message-ID: Cyril.Liu wrote: > I use pyExcelerator to generat Excel files in my project. it works good > before I found this bug: > run this code: > > from pyExcelerator import * > wb = Workbook() > ws = wb.add_sheet("sheet") > for i in xrange(1): > ws.write(i,0, 10474224.6) > wb.save(r'd:\error_float.xls') > > open d:\error_float.xls with M$ Excle you'll find the number in the cell > is -263193.64 not 10474224.6 > > > why? some body help me please. It's probably a bug in pyExcelerator: http://sourceforge.net/tracker/index.php?func=detail&aid=1596642&group_id=134081&atid=730643 There's a patch by John Machin, http://sourceforge.net/tracker/index.php?func=detail&aid=1618443&group_id=134081&atid=730645 and the problem should be fixed in subversion. Peter From Robert.Bossy at jouy.inra.fr Tue Mar 11 10:10:30 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 11 Mar 2008 15:10:30 +0100 Subject: difference b/t dictionary{} and anydbm - they seem the same In-Reply-To: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> Message-ID: <47D692D6.9090003@jouy.inra.fr> davidj411 wrote: > anydbm and dictionary{} seem like they both have a single key and key > value. > Can't you put more information into a DBM file or link tables? I just > don't see the benefit except for the persistent storage. Except for the persistent storage, that insignificant feature... ;) Well I guess that persistent storage must be the reason some people use anydbm sometimes. If you want keys and values of any type (not just strings) and persistent storage, you can use builtin dicts then pickle them. Cheers, RB From rpnabar at gmail.com Tue Mar 25 05:46:57 2008 From: rpnabar at gmail.com (Rahul) Date: Tue, 25 Mar 2008 02:46:57 -0700 (PDT) Subject: importing a csv file as a Numeric array Message-ID: What's a good way of importing a csv text file of floats into a Numeric array? I tried the csv module and it seems to work well so long as I've ints. Does anyone have any suggestions / snippets that work to import a csv file of floats into a Numeric array? -Rahul From hajducko at gmail.com Fri Mar 28 04:16:42 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Fri, 28 Mar 2008 01:16:42 -0700 (PDT) Subject: Plugins accessing parent state Message-ID: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> Does anyone have some design ideas ( or can point me at the right design pattern, because I can't find it. ) for having a plugin being able to access a parent's state? For example, let's say I have a class that receives some commands. When it gets a command, it checks which of the registered plugins deals with that command and passes the details of the command off to that plugin. So I'd end up with something like.. result = plugin.do(msg_details) Now, I want to write a plugin called "help" that loops through all the registered plugins and prints out their doc strings. If all my plugin is getting is the msg details, how is it supposed to get the list of available plugins from the calling class? Or, for instance, let's say my class loads a configuration file that lists a set of admins who can enter commands. I want the plugins, if they so choose, to be able to test if the msg came from an admin, but again, I'm not passing the admin list into every plugin, it's just in my calling class. I could make the plugin specify an attribute for itself, like "admin_only" and test for that before I pass the command but what if certain parts of the plugin are to be restricted and others aren't, based on the details of the command sent? Is this as simple as just passing the instance of my class to each plugin? It doesn't seem like the proper thing to do, because now the plugin class has the capability of accessing the whole bot's interface. I realize that this is all just theory but I'd appreciate any points in the right direction. Thanks. s From castironpi at gmail.com Thu Mar 6 11:55:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 08:55:28 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <5oQzj.61239$Pv2.45450@newssvr23.news.prodigy.net> Message-ID: On Mar 6, 5:16?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > Bryan Olson wrote: > >> How can we efficiently implement an abstract data type, call it > >> 'DoubleDict', where the state of a DoubleDict is a binary > >> relation, that is, a set of pairs (x, y); and the operations on > >> a DoubleDict are those on a Python set, plus: > > >> ? ? ?find_by_first(self, x): ?return [y where (x, y) in DoubleDict] > > >> ? ? ?find_by_second(self, y): ?return [x where (x, y) in DoubleDict] > > It gets hairier if you have an element that isn't a first or second > > necessarily. > > > ? ? ? find_by_other(self, x): return [y where (x, y) in DoubleDict or > > (y, x) in DoubleDict] > > Do you need all three find_by's, or are the pairs actually > unordered, so you just need to find partners? Are the relations > many-to-many, and if so do you want duplicates removed? > > As programming exercises, the variants are all reasonable and > possibly interesting. I was just trying to answer the call to > nail down the problem statement. You've helped me nail down the problem in my post. It was that I was trying to ask two questions at once. (He had at -least- one question!). The first was from an old piece of code I wrote that simply wanted to know what the object that's storing the combination of A and B was, so frozenset([A,B]) works perfectly, and I'm satisfied as for that one. But the second one, which was interefering with my own thoughts, was another one. The company was selling multiple products at multiple sites. Softdrink A at store 1, softdrink B at store 1, softdrink B at store 2. My 'add' operation, 'say store N sold softdrink S' always had two lines and I really hated it. It worked, of course, but still. I felt like it was a stain. I was asking if anyone knows how to tie it, but it was kind of intimidating seeing how the implementation worked already. > Do you need all three find_by's, or are the pairs actually > unordered, so you just need to find partners? Are the relations > many-to-many, and if so do you want duplicates removed? The first one was, find the information I already have about a partnership. > As programming exercises, the variants are all reasonable and > possibly interesting. I was just trying to answer the call to > nail down the problem statement. Which is now something I can do. Actually, there's another data structure I was working on (a year ago now) that's tangentially related, so if you guys want me to hold off on that one til you or I is satisfied on the company-product map, I will! Otherwise, I'll just post it here and leave it to you. (Knowing myself, something tells me I'll try to formulate it later on today regardless. Heh heh heh. If that's not the most virtuous way to ask for help, then I might have inherited from TroubleMaker at some point up the line.) From arkanes at gmail.com Tue Mar 11 12:22:05 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 11 Mar 2008 11:22:05 -0500 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: <47D6ACF0.5060300@behnel.de> References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> <47D6ACF0.5060300@behnel.de> Message-ID: <4866bea60803110922v53d71e0el65a68c4a9fb1edc@mail.gmail.com> On Tue, Mar 11, 2008 at 11:01 AM, Stefan Behnel wrote: > Sion Arrowsmith wrote: > > And before you blame wx* for crashes: what platform was this on? > > Because my experience was that wx on GTK was significantly more prone > > to glitches than on Windows (through to wxglade being unusably crashy) > > -- if the underlying toolkit has problems, that's going to be > > reflected in wx. > > :) Interesting. This was actually on GTK. Although I would still blame at > least the wxWidgets-GTK bindings here. I never had any problems with GTK in my > life. Gtk is much more finicky than windows about the timingof when you can and cannot use certain functions. wxPython has checks in place for many of these functions so you get an exception instead of a crash, but not everything is safe (and of course in the past even fewer things were). In particular, you need to have a wxApp object safely constructed before you can use almost any gui object, which is not the case under Windows. wx makes the attempt to make correct code work correctly on platforms, but doesn't necessarily guarantee that incorrect code fails the same (or at all) on all platforms. This is an unavoidable compromise due to the nature of a layering toolkit like this, although figuring out what "correct code" actually is can take some experience. > > > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at microcorp.co.za Sun Mar 30 10:55:50 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Mar 2008 16:55:50 +0200 Subject: Serial port error statistics - any comparable data? Message-ID: <002f01c89276$40bec720$03000080@hendrik> On Sunday 30 March 2008 12:19:58 Bjoern Schliessmann wrote: > Diez B. Roggisch wrote: > > if you have the chance, try & attach a machine with legacy rs232 > > port, and see if the errors still remain. > > Additionally, what kind of buffers does your device have? I'm using > pyserial to control a very "sensitive" device with nuttily > implemented buffering strategy. It has a "fast" and a "slow" buffer > which are filled in order, and no signalling to the outside sender > on how full they are. If the fast buffer fills the slow buffer > kicks in and requires less transmission rate. That may be how > characters could be lost with you. > > Regards, > > > Bjoern That is a horrible device - have they not heard of RTS / CTS? or even XON / XOFF ? It is a wonder that you got that working without turning into an axe murderer. I don't think I could have. I have not been exactly forthcoming about the setup - the device in question sits on the LAN, so I connect to it via a TCP socket connection (in either client or server mode - seems to make no difference) . On the other side of the device, there is a serial port, and another PC is connected to the RS-232 side. This is the PC that runs a simple echo script that makes the occasional error, on its receive - I can see this because the transmission is paused when I see an error, and the two strings are identical on the two machines. As I mentioned in my reply to Diez and Castironpi - its not the device that is making the errors, as proved by a simple loopback. Another interesting statistic is that the number of lines "in flight" on the round trip machine1 > xport > machine2 > xport > machine 1 due to buffering varies between about 4 and about 26. So much for using it for real time control... - Hendrik From nospam at nospam.com Tue Mar 11 06:18:35 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 11 Mar 2008 11:18:35 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: On Mon, 10 Mar 2008 22:17:16 -0700 (PDT), Frank Millman wrote: >I do not know if this helps, but here is an extract from a recent post >to the wxPython mailing list from Robin Dunn, the main developer of >wxPython - I'll take a look. Thanks for the info. From pradiprai at gmail.com Mon Mar 31 06:47:40 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 16:17:40 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: -On [20080331 12:29], Pradeep Rai (pradiprai at gmail.com) wrote: >I have upgraded python v2.5.2 from python v2.4.3. The upgradation >results into following error: "Python C API version mismatch for module >dbi: This Python has API version 1013, module dbi has version 1012." Did you copy everything from site-packages of the old one to the new one? -- Jeroen Ruigrok van der Werven / asmodai CF[ EtbN @ f EFF *http://www.in-nomine.org/* | * http://www.rangaku.org/* If you're afraid of dyin', then you're holding on. You see devils tearing your life away. But if you have made your peace, then the devils are really angels, freeing you from the earth... -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Mar 17 21:33:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 18:33:02 -0700 (PDT) Subject: how to create instances of classes without calling the constructor? References: <47df0816$0$6635$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <6187a66e-c2a4-42d8-83da-1cba072cf370@a23g2000hsc.googlegroups.com> On Mar 17, 7:08?pm, "Dominik Jain" wrote: > Hi! > > Does anyone know how an instance of a (new-style) class can be created > without having to call the constructor (and providing the arguments it > requires)? With old-style classes, this was possible using new.instance. > Surely there must be a simple way to do this with new-style classes, too -- ? > or else how does pickle manage? > > Best, > Dominik >>> class C: pass ... >>> object.__new__( C ) <__main__.C object at 0x00B5ED70> And for the record: >>> class C: ... def __init__( self ): ... print( 'in init' ) ... >>> C() in init <__main__.C object at 0x00B5ED90> >>> object.__new__( C ) <__main__.C object at 0x00B5EE30> >>> type( C.__name__, (), dict( C.__dict__ ) )() in init <__main__.C object at 0x00B5ED90> Which is kind of biza-a-r-rre. From vpalexander at gmail.com Sun Mar 9 05:42:01 2008 From: vpalexander at gmail.com (vpalexander at gmail.com) Date: Sun, 9 Mar 2008 01:42:01 -0800 (PST) Subject: gc question Message-ID: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> I keep seeing destructor calls in wx for ad hoc dialogs and wonder if this is required, and if so, why would normal gc flow not be good? def GetDir(self,Caption,DefaultDir): dlg = wx.DirDialog(None,Caption,style = 1,defaultPath = DefaultDir,pos = (10,10)) res = dlg.ShowModal() pck = dialog.GetPath() dlg.Destroy() if res == wx.ID_OK: return pck else: return '' I'd like to write it as: def GetDir(self,Caption,DefaultDir): dlg = wx.DirDialog(None,Caption,style = 1,defaultPath = DefaultDir,pos = (10,10)) if dlg.ShowModal() == wx.ID_OK: return dialog.GetPath() else: return '' # probably implied; del 2 more lines? ...and gc takes care of things once scope is exited? Or is wx more tricksome than that? From emailamit at gmail.com Mon Mar 31 16:24:53 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 13:24:53 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <89d34053-4b16-49df-9153-eb3625249ad4@u10g2000prn.googlegroups.com> <7cee8a91-ebcc-43d0-8a84-63eca2409dc7@s19g2000prg.googlegroups.com> Message-ID: <824e2386-1a91-4685-b827-d4de41a3afaf@c19g2000prf.googlegroups.com> On Mar 31, 11:45 am, John Henry wrote: > Not sure. I use it on windows. > > > I haven't looked at pyinstall.. Is it for linux? > > It appears so - according tohttp://www.pyinstaller.org/ Thanks! It does show support for Linux. The documentation says it works for python until version 2.4. I am using 2.5.1. Not sure if it will work seamlessly, but I will try. If anyone has experience to share on using pyinstaller on 2.5.1 or higher, please share. Amit From andrei.avk at gmail.com Thu Mar 13 02:34:44 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Wed, 12 Mar 2008 23:34:44 -0700 (PDT) Subject: a Roguelike in Python References: Message-ID: <67c263fd-0294-4885-bf0a-a6ecdbb62c68@m36g2000hse.googlegroups.com> On Mar 12, 8:25?am, Mdo... at gmail.com wrote: > Seeing the 7DRL start up recently, i wanted to see what one was made > of. Python is the language i'm most familiar with so i searched for > some code to look at, but i couldn't find any. Can anyone direct me to > the right place? > > I did some searching on what it would take to write a roguelike in > python and it looked like the curses module would work perfectly, but > it looks to me like it doesn't work in windows? I tried to import it > and it says 'No Module named _curses' > > Sorry if all this sounds a bit noobish, it's only cause i am. I made a very small basic roguelike, except that in it you control the monsters instead of the hero. It uses curses so no worky in windows. Here: http://silmarill.org/nodes/I,_monster_game.html I later modified this game to control the hero and sometimes to ask you multiple-choice questions from biology and other fields of knowledge, and based on your right/wrong answer it either makes a Hit for your HP or gives you a small reward. If there's interest i can post that updated game too. Both are kind of buggy though.. -ak From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 23:21:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 03:21:34 -0000 Subject: some path issues on windows References: Message-ID: <13urddulja4t7fa@corp.supernews.com> On Fri, 28 Mar 2008 22:31:07 -0400, Brad wrote: > When reading a file into a list that contains windows file paths like > this: > > c:\documents and settings\brad\desktop\added_software\asus\a.txt > > I get a list that contains paths that look like this: > > c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt What makes you think that there are doubled backslashes in the string? Look at this: >>> path = r'C:\docs\file.txt' # Single backslashes >>> path 'C:\\docs\\file.txt' >>> print path C:\docs\file.txt >>> len(path) 16 Despite how it looks, the backslashes are all singles, not doubles: >>> path[2] '\\' >>> len(path[2]) 1 When you display strings, by default special characters are escaped, including backslashes. (Otherwise, how could you tell whether the \f in the path meant backslash followed by f or a formfeed?) Python interprets backslashes as special when reading string literals, NOT when reading them from a file: >>> open('backslash.txt', 'w').write('docs\\files') >>> s = open('backslash.txt', 'r').read() >>> s 'docs\\files' >>> print s docs\files >>> len(s) 10 -- Steven From soistmann at gmail.com Sat Mar 22 17:34:31 2008 From: soistmann at gmail.com (bsoist) Date: Sat, 22 Mar 2008 14:34:31 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> On Mar 22, 12:40 pm, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. Absolutely. I love using Python in "the real world" but it is fantastic for beginning programmers. Python enforces good habits and presents many opportunities to discuss programming from an academic perspective. Why does Python not have a switch or until statement? Why are very common objects (stack, queue, linked list) not builtin? etc. I have seen 14 and 15 year old students who have never done any programming begin to write real object oriented programs after 60 hours or so of classroom instruction. From falk at green.rahul.net Tue Mar 25 10:58:51 2008 From: falk at green.rahul.net (Edward A. Falk) Date: Tue, 25 Mar 2008 14:58:51 +0000 (UTC) Subject: Does python hate cathy? References: Message-ID: In article , Patrick Mullen wrote: >Then again, I can count the number of times I have ever needed __del__ >with no fingers (never used it!). Still, quite interesting to >explore. I used it once, for an object that had a doubly-linked list. The __del__() method walked the list, setting all the elements' prev/next pointers to None to make sure the elements of the list would get garbage-collected. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Mar 22 19:58:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 22 Mar 2008 23:58:33 -0000 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> Message-ID: <13ub799o3opuo88@corp.supernews.com> On Sat, 22 Mar 2008 14:55:39 -0700, Zentrader wrote: >> No one meant to laugh at you. Your naivete was not obvious. FWIW, a >> sense of humor is a valuable possession in most Python-related >> conversations. > > Perhaps someone can explain how telling something like this to the OP, > who thinks this statement will work > if 'one' and 'two' in f: > is funny and not mean. Oh stop your whining. Nobody is making fun of anyone, or laughing at anyone, although I'm just about ready to start laughing at *you* for your completely unjustified conviction that people are being cruel. Bearophile made a clearly hypothetical comment using perfectly valid and understandable English. That you misunderstood it isn't anybody's fault except your own. Get over it, stop trying to blame others, and move on. You're not the victim here, and Bearophile isn't the bad guy. -- Steven From needin4mation at gmail.com Tue Mar 18 12:10:05 2008 From: needin4mation at gmail.com (jmDesktop) Date: Tue, 18 Mar 2008 09:10:05 -0700 (PDT) Subject: Need Help Starting Out Message-ID: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Hi, I would like to start using Python, but am unsure where to begin. I know how to look up a tutorial and learn the language, but not what all technologies to use. I saw references to plain Python, Django, and other things. I want to use it for web building with database access. What do I use for that? Does it matter what I use on the client side (mootools, or whatever)? My rational for using Python is because I am hoping it will allow me to better understand other python programs in other areas, not just web. I have used other languages for web apps for several years. Truth is that I always wanted to learn Python and have heard it was a good thing to know. Thank you. From koara at atlas.cz Fri Mar 7 10:15:56 2008 From: koara at atlas.cz (koara) Date: Fri, 7 Mar 2008 07:15:56 -0800 (PST) Subject: hidden built-in module References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> <63d32jF23f54eU1@mid.uni-berlin.de> Message-ID: <1517d379-1db9-4c1d-8dec-4dd5a38b9c13@o77g2000hsf.googlegroups.com> > You can only try and search the sys-path for the logging-module, using > > sys.prefix > > and then look for logging.py. Using > > __import__(path) > > you get a reference to that module. > > Diez Thank you Diez, that's the info i'd been looking for :-) So the answer is sys module + __import__ Cheers! From steve at holdenweb.com Tue Mar 4 11:09:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 11:09:54 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD7452.2020605@holdenweb.com> mmm wrote: > Oops I did make a mistake. The code I wanted to test should have been > > import copy > print 'Test 1' > pf= '?,?,?,?' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print sqlx1 > > print > print 'Test 2' > sqlx2= copy.copy(sqlx1) > sqlx3= sqlx1 > pf= '?,?,?, ****' > print 'sqlx1= ', sqlx1 > print 'sqlx2= ', sqlx2 > print 'sqlx3= ', sqlx2 > > and the results would > == output > Test group 1 > INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Test group 2 > sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Such that sqlx1 does to change with the re-assignment of 'pf' > And of course immutables such as strings are immutable. Got it now. You still aren't showing us the code you are actually running. Why can't you just paste it into your message? But anyway, you appear to have got the drift now. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mail at timgolden.me.uk Fri Mar 7 03:49:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Mar 2008 08:49:30 +0000 Subject: system32 directory In-Reply-To: <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: <47D1019A.8000200@timgolden.me.uk> Robert Dailey wrote: > On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden wrote: >> >> First thing to do when asking "How do I do X in Python under Windows?" >> is to stick -- python X -- into Google and you get, eg: >> >> >> http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html >> >> which suggests that the win32api module from the pywin32 modules has >> the function you need. >> >> >> And sure enough... >> >> >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import win32api >> >>> win32api.GetSystemDirectory () >> 'C:\\WINDOWS\\system32' >> >>> >> >> >> TJG >> > > I was aiming to figure out if the standard modules shipped with Python could > do this already before I started using 3rd party libraries. Thanks. Ah. Sorry. I'm sure you can call it via ctypes (built in from Python 2.5). But even if I'd realised that's what you'd wanted, I'd probably have given the original answer because pywin32 pretty much *is* standard library for any Python installation I do on Win32 :) TJG From bj_666 at gmx.net Mon Mar 31 02:50:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 06:50:08 GMT Subject: question References: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> Message-ID: <65bft0F2esfc1U2@mid.uni-berlin.de> On Sun, 30 Mar 2008 20:34:30 -0400, Steve Holden wrote: > castironpi at gmail.com wrote: >> Presume. Silence first, then a broken triad vamps. How long til you >> recognize it? One sec., i'll attach a binary. > > Good grief, is this idibot still around? > > [leaves c.l.py for another month] Oh come on, don't let you scare away so easily. Put him in the filter list of your news client. Ciao, Marc 'BlackJack' Rintsch From mensanator at aol.com Mon Mar 3 19:24:30 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 16:24:30 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> Message-ID: <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> On Mar 3, 4:53?pm, Carl Banks wrote: > On Mar 3, 4:47 pm, Mensanator wrote: > > > > > > > On Mar 3, 2:49 pm, Carl Banks wrote: > > > > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > Notice anything funny about the "random" choices? > > > > > import sympy > > > > import time > > > > import random > > > > > f = [i for i in sympy.primerange(1000,10000)] > > > > > for i in xrange(10): > > > > ? f1 = random.choice(f) > > > > ? print f1, > > > > ? f2 = random.choice(f) > > > > ? print f2, > > > > ? C = f1*f2 > > > > ? ff = None > > > > ? ff = sympy.factorint(C) > > > > ? print ff > > > > > ## ?7307 7243 [(7243, 1), (7307, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > > As in, "they're NOT random". > > > > > The random number generator is broken by the sympy.factorint() > > > > function. > > > > > Random.choice() works ok if the factorint() function commented out. > > > > > ## ?6089 1811 None > > > > ## ?6449 1759 None > > > > ## ?9923 4639 None > > > > ## ?4013 4889 None > > > > ## ?4349 2029 None > > > > ## ?6703 8677 None > > > > ## ?1879 1867 None > > > > ## ?5153 5279 None > > > > ## ?2011 4937 None > > > > ## ?7253 5507 None > > > > > This makes sympy worse than worthless, as it f***s up other modules. > > > > Dude, relax. > > > > It's just a bug--probably sympy is messing with the internals of the > > > random number generator. ?It would be a simple fix. ?Instead of > > > b****ing about it, file a bug report. > > > I did. > > > > Or better yet, submit a patch. > > > I would if I knew what the problem was. > > > I posted it here because someone recommended it. > > I'm simply un-recommending it. Those who don't care > > needn't pay any attention. Those who do should be > > glad that faults are pointed out when found. > > 1. You can point out the faults of a program without insults and > vulgarity Did I insult someone? And "fuck" in the context I used it means "messes with". Now you know that the writer of that superbowl commercial for almonds wanted to say "Robert Goulet fucks with your stuff". But, due to censorship, changed it to "messes with". > > 2. You must be terribly difficult to please if one bug is enough to > recommend against a program as "worse than worthless" While we're on the subject of English, the word "worthless" means "has no value". So, a program that doesn't work would generally be "worthless". One that not only doesn't work but creates side effects that cause other programs to not work (which don't have bugs) would be "worse than worthless". I'm not hard to please at all. I'm planning a later report where I test sympy's factoring with that of the MIRACL library's factor.exe program. It too, has a serious bug (and I'm not a good enough C programmer to know how to fix it) but I have a Python based workaround even though the MIRACL library has no Python interface. But any mention I ever make of this program will mention this bug in case anyone wants to use it. > > 3. You must be terribly naive if you expect a freeware program with a > version number of 0.5.12 not to have bugs No, but I guess I'm naive thinking that when someone posts a link to such a program that he's recommending going and trying it out. That is why they're making it available, isn't it? For people to try out so they can get free testing? Aren't I doing my part? Should I just uninstall it and forget it? > > Carl Banks From miki.tebeka at gmail.com Wed Mar 5 10:51:09 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 5 Mar 2008 07:51:09 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> Message-ID: <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> Hello Rod, > I have a set of CGI scripts set up and in one page (which is stored in > an HTML file then printed via a python CGI) there is an image. However > the image never displays, can anyone recommend a way round this > problem? We need more information, can you post a code snippet? error page? ... My *guess* is that the web server don't know how to server the image (wrong path configuration?) HTH, -- Miki http://pythonwise.blogspot.com From kyosohma at gmail.com Wed Mar 19 17:24:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 14:24:13 -0700 (PDT) Subject: Is this valid ? References: Message-ID: <133ffcc3-c2bc-4ae8-a45d-cbdfb05d73e0@d21g2000prf.googlegroups.com> On Mar 19, 4:18 pm, Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > > thanks, > Stef Mientki It sure looks that way... See http://www.python.org/doc/2.3.5/ref/comparisons.html for more info. Mike From furkankuru at gmail.com Tue Mar 25 12:08:07 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 18:08:07 +0200 Subject: Creating dynamic objects with dynamic constructor args In-Reply-To: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> References: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> Message-ID: <3a4a8f930803250908l49de8e8dk7a0a96e19aa9728@mail.gmail.com> you can call a function with arglist like this: def dummy(a, b, c): print a + b, c args = [1, 2, "hello"] dummy(*args) On Tue, Mar 25, 2008 at 5:38 PM, wrote: > I'd like to create objects on the fly from a pointer to the class > using: instance = klass() But I need to be able to pass in variables > to the __init__ method. I can recover the arguments using the > inspect.argspec, but how do I call __init__ with a list of arguments > and have them unpacked to the argument list rather than passed as a > single object? > > ie. class T: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > argspec = inspect.argspec(T.__init__) > args = (1, 2) > > ??? how do you call T(args)? > > Thanks. > Greg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From userprogoogle-139 at yahoo.co.uk Sat Mar 8 14:40:57 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Sat, 8 Mar 2008 11:40:57 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> <88Yzj.19022$R84.2998@newssvr25.news.prodigy.net> Message-ID: <3d7543fc-49f3-4d43-a3b1-9ec3c5d9b762@p25g2000hsf.googlegroups.com> > Is the cgi script in the same directory? The user's browser looks > for the jpg relative to the URL it used to get the page, which in > the case of the CGI script is the path to the script, not the > path to the html file. No the CGI script is in a different folder, I could move everything to the same folder I guess. > If server logs are hard to get or read, try my runcgi.py script: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/550822 Thanks, I will try this. Rod From jura.grozni at gmail.com Thu Mar 13 10:48:00 2008 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Mar 2008 07:48:00 -0700 (PDT) Subject: wx and pil conversion Message-ID: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> A little problem. Can I directly show Pil objects "image.open("bla.jpg") in Wx or do I have to transform them. If I have to transofm them How can I do it. Pixel by pixel or is there somethin built in in pil or wx or python. pilj->wx and wx->pil. From castironpi at gmail.com Sun Mar 9 19:44:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 16:44:39 -0700 (PDT) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 2, 1:18?pm, castiro... at gmail.com wrote: > On Mar 2, 12:01?pm, John DeRosa wrote: > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > >Hi, > > > >Have you ever seen Beautiful Python code? > > >Zope? Django? Python standard lib? or else? > > > >Please tell me what code you think it's stunning. > > > Just about any Python code I look at. > > Decorators, with, and namedtuple. Oh yeah, and variable arguments and keyword dictionaries. From castironpi at gmail.com Mon Mar 17 21:43:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 18:43:45 -0700 (PDT) Subject: In regards to threads of today: Message-ID: <122e1aea-cb63-4454-a542-85c20699d986@m34g2000hsc.googlegroups.com> Speaking of the standards, anyone ever try to override a method in xmlrpclib.ServerProxy? Case in point, and it's on your computer. Tear it up & tell your manager. Class Transport isn't even documented, despite its being the second parameter to the initializer. The module is > 1000 lines long. 1000 lines? Then to boot, it "import _xmlrpclib"s. And is Python responsible for allowing it? Further, is it unsafe, more unsafe, or less than pickle? Is it any more dangerous to xmlrpclib.Binary a pickle, or just rpc one? "The description in this section doesn't cover specific customizations that you can employ to make the unpickling environment slightly safer from untrusted pickle data streams." "If this sounds like a hack, you're right." No. Just unpickle in a reduced context: exec( 'pickle.load(...)',{},{}) You could require a stats header about a pickle instead for security. Example of a malicious pickle lacking. From supheakmungkol.sarin at gmail.com Thu Mar 27 11:40:25 2008 From: supheakmungkol.sarin at gmail.com (mungkol) Date: Thu, 27 Mar 2008 08:40:25 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux Message-ID: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Dear all, I am a newbie to Python community. For my project, I tried to install Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but unsuccessful. It produced the following error: running install running build running build_ext building 'Stemmer' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ limits.h:11, from libstemmer_c/src_c/../runtime/header.h:2, from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: limits.h: No such file or directory error: command 'gcc' failed with exit status 1 Did anyone experience this before? Any comment/suggestion is highly appreciated. Thank you. Best regards, Supheakmungkol From fakeaddress at nowhere.org Thu Mar 6 06:16:11 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 03:16:11 -0800 Subject: Dual look-up on keys? In-Reply-To: References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <5oQzj.61239$Pv2.45450@newssvr23.news.prodigy.net> castironpi at gmail.com wrote: > Bryan Olson wrote: >> How can we efficiently implement an abstract data type, call it >> 'DoubleDict', where the state of a DoubleDict is a binary >> relation, that is, a set of pairs (x, y); and the operations on >> a DoubleDict are those on a Python set, plus: >> >> find_by_first(self, x): return [y where (x, y) in DoubleDict] >> >> find_by_second(self, y): return [x where (x, y) in DoubleDict] > It gets hairier if you have an element that isn't a first or second > necessarily. > > find_by_other(self, x): return [y where (x, y) in DoubleDict or > (y, x) in DoubleDict] Do you need all three find_by's, or are the pairs actually unordered, so you just need to find partners? Are the relations many-to-many, and if so do you want duplicates removed? As programming exercises, the variants are all reasonable and possibly interesting. I was just trying to answer the call to nail down the problem statement. -- --Bryan From myonov at gmail.com Mon Mar 24 07:38:50 2008 From: myonov at gmail.com (myonov at gmail.com) Date: Mon, 24 Mar 2008 04:38:50 -0700 (PDT) Subject: Disable resize button Message-ID: Hi! I need to disable resize button in Tkinter. I inherit the Frame class. Then in the constructor i make my buttons, labels, etc. Then I pack them and when move borders of the frame everything changes it's location and it looks really bad. How can I change that? That's my code: # -*- coding: cp1251 -*- import Tkinter class App(Tkinter.Frame): def click(self): pass def click2(self): pass def __init__(self, master=None): Tkinter.Frame.__init__(self, master, width = 700, height = 400,\ bg = "#999999") self.pack() # Buttons self.b1 = Tkinter.Button(self, text = u"?????? ?????",\ command=self.click, font = "Courier", \ fg = "red") self.b2 = Tkinter.Button(self, text = u"?????? ???????",\ command=self.click2, font = "Courier", \ fg = "red") self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = 0.75, rely = 0.4) # Labels self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ text = u"??????????", fg = "#ffffff",\ bg = "#999999") self.l1.place(x = 275, y = 10) # Text Control # self.txt = Tkinter.Text(self, bg = "#124456", ) # self.txt.pack() def main(): app = App() app.mainloop() if __name__ == "__main__": main() From gideon.smeding at gmail.com Wed Mar 5 07:47:15 2008 From: gideon.smeding at gmail.com (gideon) Date: Wed, 5 Mar 2008 04:47:15 -0800 (PST) Subject: documenting formal operational semantics of Python Message-ID: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Hi Everybody, In the context of a master's thesis I'm currently looking into Python's operational semantics. Even after extensive searching on the web, I have not found any formal model of Python. Therefore I am considering to write one myself. To make a more informed decision, I would like to ask you: What previous work has been done that I should be aware of? Currently I have found exactly nothing on python itself. There is some interesting work on other, related languages like Smalltalk. Which version of Python is the most interesting? Python 3.0, although it would be a moving target, seems promising. Because it will simplify the language in some aspects by ditching backwards compatibility (e.g. old style classes and coercion), the semantics will be more clean. Of course I will get, answers to many questions I did not ask. In fact, I would like you to vent your opinions on this matter. Thanks! From tkapoor at wscm.net Thu Mar 20 12:13:23 2008 From: tkapoor at wscm.net (Tarun Kapoor) Date: Thu, 20 Mar 2008 11:13:23 -0500 Subject: paramiko In-Reply-To: References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> Message-ID: I have some code that uses paramiko, establishes an SFTP connection with a remote server and downloads some files. This code works perfect if run on a windows XP machine. However, I get an error in the "RandomPool" class. Anyone tried paramiko on a windows server box ? Thanks !! Tk -----Original Message----- From: Guilherme Polo [mailto:ggpolo at gmail.com] Sent: Wednesday, January 16, 2008 11:12 AM To: Tarun Kapoor; python-list at python.org Subject: Re: paramiko 2008/1/16, Tarun Kapoor : > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > the remote server using an SFTP client I have just to make sure that > username and password are working.. This is the code. > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > connection > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.connect((hostname, port)) > > > > t = paramiko.Transport(sock) > > event = threading.Event() > > t.start_client(event) > > > > event.wait(15) > > > > if not t.is_active(): > > print 'SSH negotiation failed.' > > sys.exit(1) > > else: > > print "SSH negotiation sucessful" > > > > event.clear() > > > > t.auth_password(username=username, password=password,event=event) > > > > if not t.is_authenticated(): > > print "not authenticated" > > output: > > SSH negotiation successful > > not authenticated > > > > > > > > Tarun > > > > Waterstone Capital Management > > 2 Carlson Parkway, Suite 260 > > Plymouth, MN 55447 > > > > Direct: 952-697-4123 > > Cell: 612-205-2587 > Disclaimer This e-mail and any attachments is confidential and intended > solely for the use of the individual(s) to whom it is addressed. Any views > or opinions presented are solely those of the author and do not necessarily > represent those of Waterstone Capital Management, L.P and affiliates. If you > are not the intended recipient, be advised that you have received this > e-mail in error and that any use, dissemination, printing, forwarding or > copying of this email is strictly prohibited. Please contact the sender if > you have received this e-mail in error. You should also be aware that > e-mails are susceptible to interference and you should not assume that the > contents of this e-mail originated from the sender above or that they have > been accurately reproduced in their original form. Waterstone Capital > Management, L.P. and affiliates accepts no responsibility for information, > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > please verify the authenticity with the sender. > -- > http://mail.python.org/mailman/listinfo/python-list > You are missing an event.wait() after t.auth_password. Also, why are you passing this magic value "15" to event.wait() ? That parameter is passed to class _Verbose to indicate if debug messages should be displayed or not, so typical values would be 0/1 or False/True. -- -- Guilherme H. Polo Goncalves Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. From tjreedy at udel.edu Tue Mar 18 22:28:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:28:10 -0400 Subject: Interesting math problem References: Message-ID: "Jeff Schwab" wrote in message news:C6SdnWmXtYoncELanZ2dnUVZ_ubinZ2d at comcast.com... | Marc Christiansen wrote: | > This was my first thought, too. But tailcall optimisation wouldn't help | > here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets | > executed after the recursion. | | | def make_slope(distance, parts, L=()): | if parts == 0: | return L | | q, r = divmod(distance, parts) | | if r and parts % r: | q += 1 | | return make_slope(distance - q, parts - 1, (q,) + L) So mechanically rewrite (not tested) as def make_slope(distance, parts, L=()): if parts < 0: raise ValueError('do you want me to return?') #added while parts: q,r = divmod(distance, parts) if r and parts % r: q += 1 distance, parts, L = distance-q, parts-1, (q,) + L return L tjr From morse at edoug.org Fri Mar 14 10:37:32 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 14 Mar 2008 14:37:32 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Peter, Genius! You nailed it -- thanks! py2exe is apparently getting confused by the fact that packages "Numeric" and "numpy" both have files multiarray.pyd and umath.pyd. It copies just one of each -- from $PYTHONHOME/Lib/site-packages/numpy/core -- and puts both of them into the top-level of the created "dist" directory. Also, there are no such files as multiarray.pyc and umath.pyc in my python installation, but py2exe seems to create these (in the dist and dist/numpy/core directories) -- they are small (e.g., 526 bytes) and I'm guessing that they are stubs that simply point python to the matching .pyd that py2exe relocated. So, by using the --skip-archive option to py2exe (i.e., python setup.py py2exe --skip-archive) to create the dist and build directories, and then within the dist directory hierarchy removing all the occurrances of multiarray.pyc and umath.pyc, and then moving dist/multiarray.pyd and dist/umath.pyd to the dist/numpy/core directory, and finally by copying multiarray.pyd and umath.pyd from $PYTHONHOME/Lib/site-packages/Numeric to the dist directory, I am able to get my application to run correctly and as a standalone executable. HOORAH!!! Just for completeness and perhaps a bit of additional clarity, here's a limited directory listing of what the steps in the previous paragraph produce: morse> find dist | egrep "(multia|umath)" | xargs ls -l -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/multiarray.pyd -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/umath.pyd -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd morse> (This is still WinXP; I'm just using the Cygwin bash and fileutils here. Also, note that there are NO multiarray.pyc or umath.pyc files.) So, my next step will be to try to not use the --skip-archive option and then make these same modifications regarding multiarray.pyd and umath.pyd to the py2exe-generated library.zip file and see if I can get things running that way as well (and in so doing reduce my "dist" directory by about 10mg). I may also try creating a dist/Numeric subdirectory and moving dist/multiarray.pyd and dist/umath.pyd to this dist/Numeric subdirectory -- for the goal of more accurately mirroring the actual file/directory structure found in $PYTHONHOME/Lib/site-packages. Again, thanks to everyone for their assistance, esp. Harald and Peter. Is this something I should pursue getting the py2exe folks to fix / work with them on fixing? In investigating this issue, I noted that a lot of other py2exe problems seem to revolve around confusions when duplicate files exist in different modules. I wouldn't thinking that getting py2exe to pay better attention to the containing modules when building it's dependency tree would be that difficult (or is it)? Cheers, Doug On Fri, 14 Mar 2008 12:39:23 +0100, Peter Otten <__peter__ at web.de> wrote: > Doug Morse wrote: > > > from multiarray import zeros > > import string > > > > typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', > > 'Float':'fd', 'Complex':'FD'} > > > > def _get_precisions(typecodes): > > ? ? lst = [] > > ? ? for t in typecodes: > > ? ? ? ? lst.append( (zeros( (1,), t ).itemsize()*8, t) ) ? <-- Line 18 > > ? ? return lst > > > > def _fill_table(typecodes, table={}): > > ? ? for key, value in typecodes.items(): > > ? ? ? ? table[key] = _get_precisions(value) > > ? ? return table > > > > _code_table = _fill_table(typecodes) > > > > I can't find any reason why line 18 is throwing a "data type not > > understood" error. ?It doesn't seem to have anything to do with dynamic > > importing, but I can't be sure. ?I would note that "zeros" is a built-in > > function found in the "python dll" multiarray.pyd (in the Numeric module > > directory). > > I don't know why, but your module seems to use numpy's multiarray instead of > Numeric's: > > >>> from multiarray import zeros > >>> zeros((1,), "1") > array([0], '1') > >>> from numpy.core.multiarray import zeros > >>> zeros((1,), "1") > Traceback (most recent call last): > File "", line 1, in > TypeError: data type not understood > > Peter From Lie.1296 at gmail.com Sat Mar 29 13:34:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 29 Mar 2008 10:34:35 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: On Mar 29, 5:55?pm, kwitt... at telenet.be wrote: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? > > I've written an article about it to try and save this nice "is not > equal" operator, located athttp://dewitters.koonsolo.com/python_neq.html > > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). All pretty clear hey? But now comes the catch, there exists an operator !=... but what does it mean? Well, that one is pretty easy, of course ! must be an operator of its own (in non-python languages meaning 'not'), and it resembles the fancy assignment statement <...snip...> When I started to learn python I came across an operator <>. What could it mean? Well, you don't have to think long about it. You're only reference are the < and > operators (with meanings the same as in mathematics or plain written language, any non programmer would understand this). So <> must mean "smaller or larger", or not-equals, no question about that. It couldn't possible be mistaken as an assignment operator. You just have to love a language that uses operators with clear and obvious meaning. You're forcing your argument too much, both != and <> are NOT standard mathematics operators -- the standard not-equal operator is >< -- and I can assure you that both != and <> won't be comprehensible to non- programmers. And I'm not sure if anyone could have mistaken != for assignment operator because they're used in completely different places (which is the reason why some languages can use the same operator for = (assignment) and == (comparison)). = is always used in a line by itself while != is always used in places where a 'condition' (a.k.a. 'expression') is required. The problem you stated may be a problem in C/C++ (if C/C++ do have both != and <>, fortunately they only have !=) because C/C++'s = (assignment) is an operator and operators always return a value but in Python = (assignment) is a statement and can't return a value so "if a = b:" always raise an error. Since != operator can only be used in places where a 'condition'/'expression' is required and never in a line by itself as a statement, it could never be mistaken as an assignment (which is a statement). The problem just don't exist in Python. From bearophileHUGS at lycos.com Sun Mar 16 10:26:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Mar 2008 07:26:11 -0700 (PDT) Subject: Advantage of the array module over lists? References: Message-ID: <4e072426-9215-489e-95c8-7a2385b6f94c@m34g2000hsc.googlegroups.com> Their efficiency is mostly regarding the space. I think they aren't much speed-efficient because they require many conversions from-to Python types. You can gain speed efficiency too (sometimes a LOT), in some situations, using array with Psyco. Another advantage of arrays (better called "vector"s, probably, so the name "array" can replace the "list" name used by the built in) is that they offer you a fixed size representation, so you know what you are working with. You can also take a look at the C version of the BList from cheeseshop, the autor has made them rather efficient for some kinds of operations. Bye, bearophile From carsten at uniqsys.com Sun Mar 16 02:54:03 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 16 Mar 2008 07:54:03 +0100 Subject: Unicode/UTF-8 confusion In-Reply-To: <007401c886db$d197b780$0200a8c0@TMSMAIN> References: <007401c886db$d197b780$0200a8c0@TMSMAIN> Message-ID: <1205650443.3198.41.camel@localhost.localdomain> On Sat, 2008-03-15 at 16:33 -0400, Tom Stambaugh wrote: > I appreciate the answers the community has provided, I think I need to add > some additional context. > [...] > var aSerializedObject = '%(jsonString)s'; > [...] > Once back in the browser, the loadObject method calls JSON.parse on > aSerializedObject, the json string we're discussing. > [...] > In order to successfully pass the escapes to the server, I already have to > double any each backslash. At the end of the day, it's easier -- and results > in better performance -- to convert each apostrophe to its unicode > equivalent, as I originally asked. > [...] It helps to ask for what you really need instead of asking for what you think you need. The above helps in that it outlines the source of your confusion. What you don't realize is that you're really doing two JSON-encode steps on the server side, and two JSON-decode steps on the client side. You have two decode steps because sticking a JSON-string on the right-hand side of a JavaScript expression will parse that string in the same way a JSON parser would. That's an implicit JSON-decode, and later you're explicitly decoding the result of that implicit decode. You also have two JSON-encode steps. One is an explicit encode step using simplejson.dumps, and the other is an implicit encode done by a semi-functional mishmash of double-backslashes and wrapping the string in apostrophes. As you have discovered, that doesn't work so well when the string already contains apostrophes. What I suggest you try is this: 1) Get rid of the apostrophes in '%(jsonString)s'. 2) Get rid of all the manual escaping. 2) Send the result of simplejson.dumps through a second simplejson.dumps step. Alternatively, you could try this: 1) Get rid of the apostrophes in '%(jsonString)s'. 2) Get rid of all the manual escaping. 2) Get rid of the JSON.parse step on the browser side. The first alternative accomplishes that you correctly JSON-encode twice and correctly JSON-decode twice. The second alternative accomplishes that you only encode and decode once. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From darrin_allen at japan.com Wed Mar 12 09:22:37 2008 From: darrin_allen at japan.com (t3chn0n3rd) Date: Wed, 12 Mar 2008 06:22:37 -0700 (PDT) Subject: computer shows Message-ID: are there any computer trade shows in your area? From gagsl-py2 at yahoo.com.ar Sat Mar 29 22:53:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 23:53:27 -0300 Subject: Buffer Overflow with Python 2.5 on Vista in import site References: Message-ID: En Sat, 29 Mar 2008 17:34:27 -0300, Fuzzyman escribi?: > A very odd error with Python 2.5 (both 2.5.1 and 2.5.2 from the > official msi installers and running on Vista under Parallels on the > Mac). It may be actually a Parallels issue - I've installed 2.5.1 on Vista (just once, on a real PC) and it worked fine. Anyway a better place for bug reports is bugs.python.org Mmm, maybe you should check all your .pth files - looks like this strange path comes from one of them. -- Gabriel Genellina From ilkeston at ntlworld.com Sun Mar 2 09:32:33 2008 From: ilkeston at ntlworld.com (Steve Turner) Date: Sun, 2 Mar 2008 14:32:33 -0000 Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: <6Uyyj.443513$901.351866@newsfet12.ams> Marc 'BlackJack' Rintsch wrote: : On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: : :: Apart from doing something like :: a=[0,0,0] :: b=[0,0,0] :: c=[0,0,0] :: d=[a,b,c] :: :: is there a better way of creating d?? : : a = [[0] * 3 for dummy in xrange(3)] Thanks, Marc. -- Steve From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 06:55:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 10:55:25 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> Message-ID: <13uusct7elou5e3@corp.supernews.com> On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > Second try: ... > Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with > each call. But it's the only way I could find, at least without changing > the code template used by timeit. Eeek. Talk about namespace pollution. Thanks for the effort, but if that's the only solution, I think the solution is worse than the problem! Perhaps it's time for me to take a different approach. Since I can't call timeit, and I can't inherit from it (same problem with state being shared between instances), perhaps I should write my own timer. import timeit import gc import itertools def timeit2(func, args=[], kwargs={}, it=None, timer=timeit.default_timer): if it is None: it = itertools.repeat(None, timeit.default_number) save_gc = gc.isenabled() gc.disable() try: start = timer() for counter in it: func(*args, **kwargs) end = timer() finally: if save_gc: gc.enable() return end - start Now to go and test it. -- Steven From Lie.1296 at gmail.com Sun Mar 2 01:33:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 1 Mar 2008 22:33:25 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> <13sd3rnokh1975d@corp.supernews.com> <13sedmcpcbhju6a@corp.supernews.com> Message-ID: On Feb 29, 5:33?am, Steven D'Aprano wrote: > > > And rightly rejected by many other programming languages, including > > > modern Python, not to mention calculators, real mathematics and > > > common sense. > > > Lost me again. ?I was not aware that calculators, real mathematics > > and common sense were programming languages. > > I didn't say they were. Please parse my sentence again. In the widest sense of the term computer and programming language, actually calculators and real mathematics are programming languages. Programming languages is a way to communicate problems with computer. Computer is anything that does computation (and that includes calculator and a room full of a bunch of people doing calculation with pencil and paper[1]). The expressions we write in a calculator is a (very limited) programming language, while mathematics conventions is a language to communicate a mathematician's problems with the computers[2] and other mathematicians [1] Actually the term computer was first used to refer to this bunch of people [2] The computers in this sense is people that does computation From P.G.Aravindh at gmail.com Tue Mar 25 22:31:05 2008 From: P.G.Aravindh at gmail.com (Santhosh1992) Date: Tue, 25 Mar 2008 19:31:05 -0700 (PDT) Subject: TUTORIALS ON PROGRAMMING LANGUAGES Message-ID: languages Have the complete details regarding programming languages. http://operatingsys.blogspot.com/ From castironpi at gmail.com Wed Mar 5 01:21:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 22:21:18 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: <9197a045-6ddb-4be5-baf7-800425246469@p73g2000hsd.googlegroups.com> On Mar 4, 10:57?pm, castiro... at gmail.com wrote: > > > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > > > > >> >> is it makes it. > > > > > >> >>>> from types import FunctionType, MethodType > > > > >> >>>> class A( FunctionType ): pass > > > > >> > ... > > > > >> > Traceback (most recent call last): > > > > >> > ? File "", line 1, in > > > > >> > TypeError: type 'function' is not an acceptable base type > > > > > >> Use delegation instead of inheritance. This class is almost ? > > > > >> indistinguishable from a true function (when used as a method): > > > If P gets, p gotcha. > > Notwithstanding. ?Now bar has a name. > Now func has it. > > from functools import wraps > class myfunction: > ? ? __slots__ = ('func','name') > ? ? # > ? ? def __init__(self, func): > ? ? ? @wraps( func ) > ? ? ? def f( *ar, **kws ): > ? ? ? ? ?return func( self, *ar, **kws ) > ? ? ? object.__setattr__(self, 'func', f) > ? ? ? object.__setattr__(self, 'name', None) Now: Where is partialobject.__get__, why is 'attribute "__get__" read- only', and for self.__get__= func.__get__, why is "'member_descriptor' object is not callable"? From paulgeeleher at gmail.com Mon Mar 10 13:42:24 2008 From: paulgeeleher at gmail.com (sophie_newbie) Date: Mon, 10 Mar 2008 10:42:24 -0700 (PDT) Subject: Keep a python script running after browser window closed References: Message-ID: On Mar 7, 4:33 pm, Mike Driscoll wrote: > On Mar 7, 10:28 am, sophie_newbie wrote: > > > Hi, > > > I have a cgi script that performs a very long computation that can > > take several hours to complete. Is there any smart way that I can keep > > this script running until it is finished (after the user has closed > > the browser) and email them with the results. The email bit isn't the > > problem, I just don't know how to keep the code running in the > > background. I'm sure there is a smart way to do this... > > > Thanks! > > You might have your cgi script use the subprocess module to open a > second script that does the long-running process. > > Mike Ya it looks like: import subprocess # spawn subprocess subprocess.Popen(["python", "spawn.py"]) Should do this job, where spawn.py is the script to do the job. Thanks. From fts2012 at gmail.com Fri Mar 7 01:17:33 2008 From: fts2012 at gmail.com (fts2012 at gmail.com) Date: Thu, 6 Mar 2008 22:17:33 -0800 (PST) Subject: the problem of import module Message-ID: <8db5d6fa-f582-4311-817d-17da26846a57@d21g2000prf.googlegroups.com> follow the dive into python ----------------------------------------------------------------- >>> import sys >>> sys.path >>> sys.path.append('E:\achieve\book\diveintopython-pdfzh-cn-5.4b\diveintopythonzh-cn-5.4b\py') ----------------------------------------------------------------- I append the filepath of <>'s examples into sys.path,but ----------------------------------------------------------------- >>> sys.path ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat- win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\ \site-packages', 'E:\x07chieve\x08ook\\diveintopython-pdfzh-cn-5.4b\ \diveintopythonzh-cn-5.4b\\py'] >>> import fileinfo#fileinfo is a module in the path Traceback (most recent call last): File "", line 1, in import fileinfo ImportError: No module named fileinfo ----------------------------------------------------------------- Can anyone tell me the reason of the above and how to add paths to python path except adding them in the enviroment path. Thanks. From gagsl-py2 at yahoo.com.ar Sun Mar 23 12:31:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 23 Mar 2008 13:31:24 -0300 Subject: pydoc References: Message-ID: En Sun, 23 Mar 2008 12:57:35 -0300, A Hutchison escribi?: > Any known reasons why pydoc no longer works? It gets confused by many timezone changes that occur this month around the world; pydoc tries hard to please all kind of users and tracking those locale changes isn't easy. Wait until April and it will resume working fine, I presume. In the meantime, perhaps if you post a more specific question someone could give a more specific answer. -- Gabriel Genellina From gargonx at gmail.com Wed Mar 12 01:17:47 2008 From: gargonx at gmail.com (gargonx) Date: Tue, 11 Mar 2008 22:17:47 -0700 (PDT) Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> <76ce374e-fa63-4885-8198-d2b383696a48@s8g2000prg.googlegroups.com> Message-ID: <19d15ab6-0a4f-4248-b28c-eeaeedf409e0@e6g2000prf.googlegroups.com> On Mar 12, 5:10 am, Frank Millman wrote: > gargonx wrote: > > Say i have the two methods: > > > def ReturnMethod(request, x): > > if request is True: > > return x > > else: print "No String for you...False!" > > > def SendMethod(request): > > xstring = "Some text" > > ReturnMethod(request, xstring) > > > SendMethod(True) > > > Why does ReturnMethod not return the string x? I do believe it is > > returning with a NoneType. > > Any help would be greatly obliged > > > Thanks, Josh > > ReturnMethod() is executed, but you do nothing with the result. > > Try one of the following - > > def SendMethod(request): > xstring = "Some text" > print ReturnMethod(request, xstring) > > def SendMethod(request): > xstring = "Some text" > return ReturnMethod(request, xstring) > > HTH > > Frank Millman Thanks Frank the latter worked for my purpose. From musiccomposition at gmail.com Mon Mar 24 22:51:02 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 24 Mar 2008 19:51:02 -0700 (PDT) Subject: Is IronPython real Python? References: Message-ID: <9afcb565-49a1-4fce-bb64-84614b5173bd@e60g2000hsh.googlegroups.com> On Mar 24, 12:00 pm, jmDesktop wrote: > I know that IronPython and CPython are different in that one does not > use the .net framework, but are they both really the same Python > language. From my basic understanding, it will depend on what the > programmer's goal is as to which of the two would be used, but I > didn't know if they were really the same language. CPython is main implementation. The other implementations, PyPy, Jython, and IronPython, are always playing catchup to CPython, so you can't expected the latest CPython features in all the implementations. From jason.scheirer at gmail.com Thu Mar 27 16:39:20 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 27 Mar 2008 13:39:20 -0700 (PDT) Subject: Time problem (again) References: Message-ID: <21f25058-bccb-4cfc-b7c0-b13d719bcb2e@m44g2000hsc.googlegroups.com> On Mar 27, 12:17 pm, "Fabio Durieux Lopes" wrote: > Hi, > > I'm recreating a date-time based on a string and I have a problem > when daylight savings time is set (I'm off by 1). So today I forced > my computer into daylight savings time and debugged it again, but > this time I noticed something strange. > > This is the documentation from python library reference section > 6.10: > > 6.10 time -- Time access and conversions > ... > daylight > Nonzero if a DST timezone is defined. > ... > > And this is what I debugged: > -> fileTimeInSecs = time.mktime(time.strptime(timeString, > "%Y%m%d%H%M")) > (Pdb) p timeString > '200803271643' > (Pdb) n> /home/salsa/Projects/TimBR_CDR/fileSync/ > > fileSynchronizer.py(50)passFilesOlderThan() > -> print time.daylight > (Pdb) > 0 > > See how 'print time.daylight' resulted in '0'? Shouldn't it be Non- > zero? Do I have to set something for it to use DST? > > Also, is this the right list to send questions? The Python datetime module's handling of time zones is completely, entirely deficient -- the tzinfo class is just a skeleton and therefore useless. Install something that will give you fully implemented time zones like at http://pytz.sourceforge.net/ and try again -- pulling a tzinfo from this module and doing datetime_instance.replace(tzinfo=tzinfo_object_for_timezone) on your datetime instance parsed from the string will result in far more predictable behavior and probably get everything behaving as you expect. From cito at online.de Sun Mar 2 15:58:31 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 02 Mar 2008 21:58:31 +0100 Subject: First post from a Python newbiw In-Reply-To: <62vrleF24ontgU2@mid.uni-berlin.de> References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch schrieb: > On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: > >> Apart from doing something like >> a=[0,0,0] >> b=[0,0,0] >> c=[0,0,0] >> d=[a,b,c] >> >> is there a better way of creating d?? > > a = [[0] * 3 for dummy in xrange(3)] Why not simply [[0]*3]*3 ? -- Christoph From commander_coder at hotmail.com Mon Mar 3 20:55:56 2008 From: commander_coder at hotmail.com (commander_coder at hotmail.com) Date: Mon, 3 Mar 2008 17:55:56 -0800 (PST) Subject: tools to install not in python tree? Message-ID: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Hello, I have some materials for a project that I am working on that I keep in a source code control system (svn now, but I'm experimenting with mercurial). I want to install these things from the repository, but not into site-packages/ as Distutils wants to do. For instance there are some administrative scripts I want to put in ~/ admin/ and some programs that I want in ~/public_html/ . I also want to run some post-install routines (for instance, reset the database tables on my development machine). So I'm looking for a tool to take things from a repository and install them into place. Something like: install_from_repository.py -version "1.2.7" if there is a bug in 1.2.7 that I need to work on. Some of the things that I am looking for are like what setup.py does (for instance, changing the #! line on scripts or having a convenient .cfg file). But as I understand it setup only targets installing below sys.prefix; is that right? I can write routines for myself but other people must need to do these things also and a tested solution is obviously better. Is there such a tool? Thanks for any help, Jim From grante at visi.com Sat Mar 8 14:31:47 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 08 Mar 2008 19:31:47 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> Message-ID: <13t5qd3slgt9nc0@corp.supernews.com> On 2008-03-08, castironpi at gmail.com wrote: > Does one side of this hold that there are no -good- comments? I wouldn't say there are _no_ good comments, but I would say that 90+% of the comments I've seen in my lifetime were bad. Most of them were bad to the extent that anybody new to the code would be best served by deleting them before trying to understand what was going on. I do think that a comment at the beginning of a function/module that describes its general purpose can be a good thing. A comment explaining a particularly opaque algorithm can be useful as well. What I really can't stand are the pointy-haired comment blocks at the beginnings of C/C++ functions that do things like tell you the name and return type of the function and list the names and types of the parameters. Gee, thanks. I never could have figured that out from looking at the source code itself. IMO, comments explaining what the parameters are used for usually indicates that the parameter names were poorly chosen. I'm also a bit baffled by people who put a comment at the top of every file that tells you what the filename is. I sometimes wonder how/where these files were created. All of the OSes I've ever used had a feature called a "filesystem" which kept track of info like the names of files. It must be a bitch-and-a-half to work on an computer that doesn't keep track of filenames and makes the user do it. When was the last time you thought to yourself: "Gee, I wonder what's the the name of that file over there? I guess I'd better open the file and look at the comment at the top to see what the filename is? -- Grant Edwards grante Yow! .. does your DRESSING at ROOM have enough ASPARAGUS? visi.com From castironpi at gmail.com Fri Mar 21 10:11:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 07:11:37 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> On Mar 21, 4:17?am, Bryan Olson wrote: > Arnaud Delobelle wrote: > > Bryan Olson wrote: > [...] > >> Arnaud Delobelle offered a good Wikipedia link, and for more background > >> look up "amortized analysis. > > > Hrvoje Niksic provided the link :). > > Oops, careless thread-following. Hrvoje Niksic it was. > > > I still think two unrelated > > things are being compared in this thread when people say that method A > > (using dictionaries / sets) is O(n) and method B (sorting the list) > > O(nlogn). > > > Isn't it the case that: > > > ? ? ? ? ?| Worst case | Average case > > ---------|------------|------------- > > Method A | O(n^2) ? ? | O(n) > > Method B | O(nlogn) ? | O(nlogn) > > > Which method is the best would then be determined by the distribution > > of the hash values of your data, and whether you want to have a > > guarantee the method will have a less-than-quadratic behaviour. > > If we exclude the case where an adversary is choosing the keys, the > chance of a seriously degenerate case in the hashing method is so > remote that we do should not worry about it. Those who insist on > ranking by worst-case behavior have probably abandoned Python long > ago, as it uses those hashed 'dict' things everywhere. Of course > they've also abandoned OS's with demand-paged virtual memory and > such. > > -- > --Bryan A collision sequence is not so rare. >>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] [1, 1, 1, 1, 1, 1, 1, 1] From dmmsoz at gmail.com Mon Mar 17 15:52:27 2008 From: dmmsoz at gmail.com (Dianne Marsh) Date: Mon, 17 Mar 2008 12:52:27 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: <83b2ca86-32bb-4bf4-b119-f8d593d4c9eb@p25g2000hsf.googlegroups.com> This was my first PyCon as well. I had heard glowing recommendations about the lightning talks (from Bruce) previously, and I was really looking forward to them. I, too, was disappointed. I help to organize a community based conference, and we have struggled with providing value for sponsors as well. I have some suggestions, which I will offer here and to PyCon organizers. This sounds similar to what one person described above, regarding how lightning talks were managed in '07. At CodeMash, we scheduled a daily slot for vendor sessions and clearly marked them as such. We were concerned that attendees would simply avoid the vendor sessions, which would backfire. To mitigate this risk, we strongly encouraged our vendors to do something "different" than a sales pitch for vendor sessions, asking them to consider providing something meaningful for the audience. Talks weren't reviewed; we just gave them a nudge when we discussed the vendor sessions with them. They were entitled to choose a pure sales pitch if they wanted to do so, but we definitely discouraged this activity. And the sponsors responded with some great talks, and expressed satisfaction in the entire process! The vendor sessions were well attended, and it was completely transparent that they WERE vendor sessions. I had been totally skeptical about providing vendor sessions ahead of time, yet even *I* was won over. Vendors WANT people to come to their sessions. Sometimes they, just like speakers, simply need a little nudge in recognizing what makes a compelling talk. In my opinion, other speakers suffered from not knowing what makes a compelling talk as well. I don't know what other talks were proposed, but those that were on the schedule were often disappointing because the speaker provided too much "background" and not enough "here's what's cool" for me. Those were the talks that I walked out of. I suffer from this same problem as a speaker and I'm trying to fix that myself. I hope that other speakers are interested in doing the same. As for the attitude that if you weren't involved with organizing Pycon, you can't complain about it, that's a bit unfair. Several people DID engage in the conference onsite, organizing Open Spaces discussions (Bruce included). I saw Bruce both suggesting Open Spaces talks and being recruited to convene them (and, in one case, even reconvene one that had taken place earlier). That's being involved in the process, and should not be discounted. Furthermore, in my experience, people don't usually complain about things that don't matter to them. It's important, IMO, to recognize that the complaints you see on this group seem to come from the heart, from a desire to see PyCon flourish and be a conference worth attending. I certainly feel that way, and I suspect that the vast majority of people who have offered constructive criticism here do as well. I'm bummed about the lightning talks at PyCon from 2008, but I have a lot of confidence based on what I have read here from Jacob and others, that things will be different in 2009. Thank you for listening to the community feedback. -- Dianne From deets at nospam.web.de Fri Mar 21 08:48:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Mar 2008 13:48:04 +0100 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: <64hp4bF2bhmtuU1@mid.uni-berlin.de> > I can see that Python and Javascript inheritance model is almost the > same. Both languages are dynamically typed. And it seems that using > "classes" in Python makes some things more complicated then it is > necessary (eg functions, methods and lambdas are differen beeing in > Python concept). Sorry, but that is utter nonsense. It begins with the fact that there is no "inheritance model" in Javascript. Or why does each JS-lib provide it's own version of an extend-function [1]? Which one has to grasp before really being able to use inheritance in JS. And of course everybody does it a bit different, including possible access to parent classes and such. Calling that an advantage is rather bold. And it continues with the abnomination the implicit "this" in Javascript is - e.g. MochiKit offers a bindThis-method to ensure that a method-call always gets the actual instance passed as this - something that can get "lost" when dealing with event-handling. Whereas python here offers the bound-method-concept. The only point you might have is the somwhat unfortunate distinction between lambda and function in python - but this is on a syntactical level only. Once created, you can use them as you like. I do like JS for what it is - but everybody who uses it in an OO-manner ends up inventing the same wheels Python already comes with. Diez [1] Just one example: http://docs.mootools.net/Class/Class.js From gherron at islandtraining.com Fri Mar 28 01:29:13 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Mar 2008 22:29:13 -0700 Subject: Getting back an Object In-Reply-To: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> References: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> Message-ID: <47EC8229.70703@islandtraining.com> David Anderson wrote: > Well, I've got a little problem, I have a list that contains objects > from the class C, then I use those objects.__str__ to generate a > ListCtrl, A wxPython widget that makes a list of strings and then you > can handle events when selected, and returns the string selcted, how > can I access the "parent" of that string? > I tried to search on the array like this: > def search(self, string): > for obj in self.list: > if string == obj.__str__: > return obj > return None > > But I always get None... What am I doing wrong? Once again, you are confused over the difference between a value and a function that, when called, returns a value. obj.__str__ is a function. If you call it like this, obj.__str__(), then you get a string. So your comparison should be if string == obj.__str__(): Slightly better would be to call str(obj) and let Python translate that into a call to __str__. But even better is to replace this rather bogus approach with something better. When you create an object, record its string representation in a dictionary to be used to recover the object when given a string later: That is, for each object obj do: objMap[str(obj)] = obj and later with the string in hand, do obj = objMap[string] One other word of warning. It is best to not use a variable named "string" as Python has a builtin type of that name which would become inaccessible if you redefine. Gary Herron From jzgoda at o2.usun.pl Tue Mar 25 09:50:03 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Mar 2008 14:50:03 +0100 Subject: sendmail should throw an exception but does not In-Reply-To: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> Message-ID: Clodoaldo napisa?(a): > I need to know if an email was refused for whatever reason, it makes > no difference. > > The email is sent to an email address that does not exist in a foreign > domain. I can see in the postfix log that the email was sent and > bounced with the error code 550. > > The problem is that sendmail should throw an exception but it does > not. And the returned dictionary is empty as if the email was > accepted. > > d = smtpserver.sendmail(sender, recipient, m.as_string()) > > I guess that the error code returned by the destination mail server is > not is not forwarded to the client by my mail server. Your local smtpd accepted the message for delivery, so everythong seems to be OK. Following communication takes place between mail servers, so your program has no possibility to know anything went wrong. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From castironpi at gmail.com Tue Mar 18 14:58:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 11:58:18 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: <80b7cd63-a6f3-4521-adb1-93b6faab307e@e39g2000hsf.googlegroups.com> On Mar 18, 8:51?am, Tim Golden wrote: > castiro... at gmail.com wrote: > >>> Can I allocate a second console window, so I can place certain output > >>> to that directly, and leave the original streams alone? ? > > I've rather lost track of what you're trying to do, but I would > second Gabriel's suggestion of the standard Windows method of > debug output: using OutputDebugString. There's an example here: > > http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugStrin... > > and it shouldn't be too hard to wrap it in a file-like > object for stderr-substitution use, say. > > Obviously there are 1,001 other ways of doing IPC but since this > one's ready-made you might as well use it. You can distinguish > between different processes' outputs by virtue of the PID which > is the first item on the mmap. > > TJG I want a handle to another window. Create B with a command. ___ ___ |A | |B | |___| |___| B.stdin (the stdin to B).write( '?' ) ___ ___ |A | |B? | |___| |___| A.stdout.write( '*' ) ___ ___ |A* | |B? | |___| |___| A big tease is good too. From palomurin at gmail.com Fri Mar 28 07:53:15 2008 From: palomurin at gmail.com (Pavol Murin) Date: Fri, 28 Mar 2008 12:53:15 +0100 Subject: simple web-server Message-ID: hello python users, could you point me to a very simple (single file is best) web-server? I want to serve a few web-forms and run some shell scripts when the forms are submitted. I might add Ajax later (this is not a requirement, if it only supports forms it's OK). Longer story: I would like to provide a web-page for customization of an application - it should run some shell commands as the user clicks around in the page and at the end write a configuration file. I had a look at the python wiki (http://wiki.python.org/moin/WebProgramming), where various web servers and frameworks are listed. The frameworks seem to heavy for such a simple task and BaseHTTPServer just seems to be too light. So I took a look at the web-servers listed: httpy had the last release 1,5 years ago, Medusa more than 5 years, Twisted seems to be able to do a lot, so probably not the simple thing I'm looking for. CherryPy looks promising, however it is still 89 files (including some that can be removed). If CGIHTTPServer is a good answer, could you point me to a good (nontrivial) example? thank you, muro From miki.tebeka at gmail.com Mon Mar 3 23:14:59 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 3 Mar 2008 20:14:59 -0800 (PST) Subject: 'normal' shell with curses References: <633s5lF24prinU1@mid.uni-berlin.de> Message-ID: <61c6832e-6897-476c-bcfc-448b7c4387df@d21g2000prf.googlegroups.com> Hello Michael, > I'm trying to print out text in color. As far as I know, curses is the > only way to do that (or not?). On unix, every XTerm compatible terminal will be able to display color using escape sequence. (Like the one you see in the output of 'grep --color') See the shameless plug in http://pythonwise.blogspot.com/2008/03/ansiprint.html HTH, -- Miki http://pythonwise.blogspot.com From http Sat Mar 1 14:32:56 2008 From: http (Paul Rubin) Date: 01 Mar 2008 11:32:56 -0800 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> Message-ID: <7x3ara9r4n.fsf@ruckus.brouhaha.com> Lie writes: > I see, but the same arguments still holds true: the second line have > an implicit side-effect of redefining x's type into Fractional type. > If I were the designer of the language, I'd leave x's type as it is > (as Num) and coerce x for current calculation only. Num in Haskell is not a type, it is a class of types, i.e. if all you know about x is that it is a Num, then its actual type is indeterminate. Types get inferred, they do not get coerced or "redefined". The compiler looks at expressions referring to x, to deduce what x's type actually is. If it is not possible to satisfy all constraints simultaneously, then the compiler reports an error. From gagsl-py2 at yahoo.com.ar Mon Mar 31 15:02:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 16:02:29 -0300 Subject: why does socket.makefile require non-blocking mode? References: <18907.75.55.199.5.1206983756.squirrel@webmail.sonic.net> Message-ID: En Mon, 31 Mar 2008 14:15:56 -0300, Forest escribi?: > My main concern is this: A brief look at the existing socket._fileobject > shows that its read() method calls recv() in a loop, appending to a > temporary buffer on each pass, and finally returning the buffer when > recv() gets no more data. It looks to me like a socket timeout exception > would cause that loop to exit without saving the data collected in > earlier > passes. In other words, data loss on recv() timeout. Just do it. Do the experiment; if there is data loss, you prove your point (if not, it doesn't prove that data loss could not happen). -- Gabriel Genellina From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 12:15:09 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 18:15:09 +0100 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: References: <47c93bb8$0$874$ba4acef3@news.orange.fr> Message-ID: <47c990b9$0$899$ba4acef3@news.orange.fr> Re! An exemple. With this script: a=123 b=456 d=a+b+c (note than 'c' is not defined). When I run, inside Pyscripter, the error-dialog is showed, and, one second after, PyScripter is closed. This problem is present since Python 2.5.2. I search, for know if it's a problem only on my computer, or a more general problem. Thanks by advance for your(s) answer(s). @-salutations -- Michel Claveau From MartinRinehart at gmail.com Wed Mar 26 11:44:07 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 26 Mar 2008 08:44:07 -0700 (PDT) Subject: Tkinter menus from keyboard References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: <3a7f4387-586a-4221-83a8-bce142d910b1@u10g2000prn.googlegroups.com> Guilherme Polo wrote: > Set the underline option to the index of the desired letter Elegant simplicity in the dropdowns. Thanks! Now, how about main menu underscores? From deets at nospam.web.de Mon Mar 31 07:00:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Mar 2008 13:00:56 +0200 Subject: Class Image.Image? References: Message-ID: <65buk3F2fi5osU1@mid.uni-berlin.de> W. Watson wrote: > I put a print statement in some Python code to determine the class > (__class__) of a variable and the result was Image.Image. Why not just > Image; otherwise, what's it telling me? Because it is the class Image in the module/package Image. Diez From piet at cs.uu.nl Wed Mar 12 07:20:25 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 12 Mar 2008 12:20:25 +0100 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: >>>>> "Gabriel Genellina" (GG) wrote: >GG> En Tue, 04 Mar 2008 11:46:48 -0200, NickC escribi?: >>> A mildly interesting Py3k experiment: >>> >>> Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) >>> [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> from fractions import Fraction >>>>>> from decimal import Decimal >>>>>> def check_accuracy(num_type, max_val=1000): >>> ... wrong = 0 >>> ... for x in range(1, max_val): >>> ... for y in range(1, max_val): >>> ... wrong += (x / num_type(y)) * y != x >>> ... return wrong >>> ... >>>>>> check_accuracy(float) >>> 101502 >>>>>> check_accuracy(Decimal) >>> 310013 >>>>>> check_accuracy(Fraction) >>> 0 >>> >>> >>> The conclusions I came to based on running that experiment are: >>> - Decimal actually appears to suffer more rounding problems than float >>> for rational arithmetic >GG> Mmm, but I doubt that counting how many times the results are equal, is >GG> the right way to evaluate "accuracy". >GG> A stopped clock shows the right time twice a day; a clock that loses one >GG> minute per day shows the right time once every two years. Clearly the >GG> stopped clock is much better! But if the answer is incorrect (in the float calculation) the error is limited. IEEE 754 prescribes that the error should be at most 1 LSB, IIRC. And then the number of errors is the proper measure. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From lcapps at cteresource.org Thu Mar 27 11:09:52 2008 From: lcapps at cteresource.org (Lee Capps) Date: Thu, 27 Mar 2008 11:09:52 -0400 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: On Mar 27, 2008, at 10:53 AM, Skip Montanaro wrote: > I am trying to replace os.system calls with subprocess.Popen. This > simple > example fails miserably: > >>>> proc = subprocess.Popen ("ls /tmp") > Traceback (most recent call last): > File "", line 1, in > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line > 594, in __init__ > errread, errwrite) > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line > 1091, in > _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I also tried explicitly referencing /usr/bin/ls. Same result. > What gives? > I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with > 2.6alpha on Mac OS X. > Try proc = subprocess.Popen(('ls', '/tmp/')) or proc = subprocess.Popen('ls /tmp/', shell=True) See http://docs.python.org/lib/node528.html HTH, --- Lee Capps Technology Specialist CTE Resource Center lcapps at cteresource.org From jeff at schwabcenter.com Mon Mar 17 19:58:38 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 16:58:38 -0700 Subject: Interesting math problem In-Reply-To: References: Message-ID: BJ?rn Lindqvist wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > step = distance / float(parts) > intstep = int(step) > floatstep = step - intstep > > steps = [] > acc = 0.0 > for i in range(parts): > acc += floatstep > step = intstep > if acc > 0.999: > step += 1 > acc -= 1.0 > steps.append(step) > return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L def make_slope(distance, parts): if parts == 0: return [] q, r = divmod(distance, parts) if r and parts % r: q += 1 return [q] + make_slope(distance - q, parts - 1) def self_test(distance=130, parts=51): L = make_slope(distance, parts) assert(len(L) == parts) assert(sum(L) == distance) print L if __name__ == '__main__': for distance in range(1, 200): for parts in range(1, 200): self_test(distance, parts) From commander_coder at hotmail.com Tue Mar 4 06:26:32 2008 From: commander_coder at hotmail.com (commander_coder at hotmail.com) Date: Tue, 4 Mar 2008 03:26:32 -0800 (PST) Subject: tools to install not in python tree? References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: Thank you for the helpful replies. I shall check out the links. (I looked at some setup.py's but mxBase was not among them.) Regards, Jim From dadapapa at googlemail.com Mon Mar 3 10:04:56 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Mon, 3 Mar 2008 07:04:56 -0800 (PST) Subject: Problem with the strip string method References: Message-ID: > Thanks to all respondents, Steve Holden > is right, I expected more than I should > have. Others have explained why all your examples work as they should. >From your exmaples, it seems like you would like strip to remove the leading and trailing characters from EVERY LINE in your string. This can be done by the simple construct >>> my_string = ' foo \n bar ' >>> '\n'.join(line.strip() for line in my_string.split('\n')) 'foo\nbar' If you need this construct at several places, define a function def line_strip(string,sep='\n') : return sep.join(line.strip() for line in string.split(sep)) cheers, - harold - From wuwei23 at gmail.com Wed Mar 26 23:02:44 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 Mar 2008 20:02:44 -0700 (PDT) Subject: A question on decorators References: <64vpmnF2dvlccU1@mid.uni-berlin.de> Message-ID: <818b5a6c-636d-4a6e-8fb3-b44e32925ca0@e10g2000prf.googlegroups.com> On Mar 27, 8:30 am, castiro... at gmail.com wrote: > I want the * to precede the dot too. Let's yack. I want to compile > Python. Did you see my new post? I like it. Do you have any time > you don't want? Time sale. Diez is still mad at me. I want > primitives to structure themselves so I can pick up a pen. I am > volunteer primitive structuring. Your structure sucks. assert > atmostphere has drags. Could you possibly once, just once, put down the Robert Anton Wilson & the meth pipe before you post? From darcy at druid.net Wed Mar 5 16:51:17 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 16:51:17 -0500 Subject: Please keep the full address In-Reply-To: References: Message-ID: <20080305165117.56585299.darcy@druid.net> On Wed, 5 Mar 2008 13:38:59 -0800 (PST) Mike Driscoll wrote: > On Mar 5, 12:50 pm, castiro... at gmail.com wrote: I'm not sure why you change the address like this but could you please include the full address. Those of us who identify the time wasters would also like to drop the responses to their posts and changing the address makes this impossible. -- 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 jgardner at jonathangardner.net Mon Mar 24 19:39:32 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 24 Mar 2008 16:39:32 -0700 (PDT) Subject: urllib leaves connections/sockets waiting. BIG problem!!! References: <62c0ec57-1355-43d8-a414-0767ccc0923a@s37g2000prg.googlegroups.com> Message-ID: <4cd5ce67-d6cc-4c5f-a117-c15add9fa812@s12g2000prg.googlegroups.com> On Mar 24, 6:57?am, binaryj wrote: > hi i am using urllib2 to do some automated web thing. > basically i hit on sites and check the price what they are offering > for their product and then decide if i want to lower or increase my > pricing.so in short i have to hit hundreds of sites!!!!! > > for the problem: > ============= > i run 20 threads all do the same stuff. (hit and run :) ) > after around 10-15 hits(per thread) hits the thread does nothing. it > freezes. slowely but STEADILY all the threads end up with the same > fate :( > > i did some netstat and found out that the connecton(sockets) the > program had opened are waiting the CLOSE_WAIT state !! > > netstat -t > tcp ? ? ? ?1 ? ? ?0 192.168.1.2:4882 ? ? ? ?host-blabla:www > CLOSE_WAIT > tcp ? ? ? ?1 ? ? ?0 192.168.1.2:4884 ? ? ? ?host-blabla:www > CLOSE_WAIT > tcp ? ? ? ?1 ? ? ?0 192.168.1.2:4375 ? ? ? ?host-blabla:www > CLOSE_WAIT > > OUTPUT OF PROGRAM: > THREAD: #Thread-2 getting price from webi-d ?7511975 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?4449152 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?7466091 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?8641914 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?7745289 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?6032442 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?8149873 DONE !!! > no-price-on-page error > THREAD: #Thread-1 getting price from webi-d ?5842934 DONE !!! > no-price-on-page error > THREAD: #Thread-2 getting price from webi-d ?3385778 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?4610122 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?8641536 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?4219935 DONE !!! > ---------and thats it, it freezes. i have waited 1hr the sockets have > not changed their states! :( > > please help :) I think we'll need more details before being able to assess what is wrong. Can you supply some sample code that has the same bug? From http Mon Mar 17 04:28:55 2008 From: http (Paul Rubin) Date: 17 Mar 2008 01:28:55 -0700 Subject: writing to a binary file without intervening spaces References: Message-ID: <7xtzj5eou0.fsf@ruckus.brouhaha.com> Larry writes: > My data is a = [23, 45, 56, 255]. > My desire output is: 234556255, of course in binary file > representation already. > > I tried to make one using write after pack method of struct module, > but because of spaces I got incorrect results. struct.pack works for me: Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >>> import struct, os >>> x = struct.pack('BBBB', 23, 45, 56, 255) >>> len(x) 4 >>> f = open('/tmp/foo','w'); f.write(x); f.close() >>> os.system("ls -l /tmp/foo") -rw------- 1 phr phr 4 Mar 17 01:27 /tmp/foo >>> You could also do the list-string conversion with the array module. From tjreedy at udel.edu Sun Mar 16 04:01:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Mar 2008 04:01:05 -0400 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net><13sc3b0g7gud892@corp.supernews.com><13tmo994bgqjr11@corp.supernews.com><13to6j6pta8o008@corp.supernews.com> <13tpa4999krk6cd@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13tpa4999krk6cd at corp.supernews.com... | On Sat, 15 Mar 2008 11:50:17 -0700, Dennis Lee Bieber wrote: | | > Small integers are cached in Python, so they always have a fixed ID | > (address). | | Small integers are cached in CPython, making it an implementation- | dependent feature. Indeed, the set cached has changed from version to version. | I don't believe that caching is promised by the | language definition, No, could even disappear from cPython. From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 17:11:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 22:11:31 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> Message-ID: <13su6kjio80q55b@corp.supernews.com> On Wed, 05 Mar 2008 13:52:38 -0800, castironpi wrote: > On Mar 5, 3:38?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: >> > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: >> >> castiro... at gmail.com schrieb: >> >> >> > I want to hash values to keys. ?How do the alternatives compare? >> >> >>http://catb.org/~esr/faqs/smart-questions.html >> >> > ... without extending the whole way to a full relational database? >> >> You didn't bother following the link and reading the advice, did you? >> If you did, you haven't done a good job of following that advice. > > Well, obviously there's someone who's interested in computers and > programming that has a question. Communication is not his forte, but > effort, willingness, devotion, and dedication are. What should he do, Read the "Smart Questions" page and follow the advice in it. Sheesh. -- Steven From duncan.booth at invalid.invalid Fri Mar 28 06:53:54 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Mar 2008 10:53:54 GMT Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > On Mar 28, 1:57?am, raj wrote: >> To ankit: >> >> Well, sort() doesn't return the sorted list. It returns None. Why not >> this straightforward way? >> dvals = dict.values() >> dvals.sort() >> print dvals > > Why not sorted( dict.values() ). > If you are going to do it that way then it may be preferable to use itervalues: print sorted(dict.itervalues()) Both this and raj's suggestion create a single sorted list. Your suggestion creates two lists: the unsorted one and a separate sorted one. In most cases the difference is probably insignificant, but if you have a *lot* of values it might make a difference. From john.jython at gmail.com Mon Mar 24 21:15:17 2008 From: john.jython at gmail.com (john s.) Date: Mon, 24 Mar 2008 18:15:17 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 Message-ID: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Hi Everyone, I hope not to offend you with too many question.. I've been lurking a long time. I'm not keen on keeping e-mails or data stored in the public space so this is my first post to the group. That being said, I'm keen on refining my skills, I hope that I can prove that I've move on beyond the: check the tut, read the faq.. Now as it's out of the way I hope that my questions can be sited as examples for others breaking the procedural barrier. I've seen examples using reduce, map and lamba that cause me to emit a internal "WTFIZDISHI?" _____________________________ With out any further adiou... IsMyKodeHotOrNot.... and how can I improve it... hopefully it will help me with part two... I'm sure anyone with 2 mins and solid skill of python can ballpark this one... _____________________________ #/usr/bin/enviro python #Purpose - a dropped in useracct/pass file is on a new server to build a cluster... Alas there are no home #directories.. Let me rip through the passfile, grab the correct field (or build it) and use it to make the directory! import os, sys, string, copy, getopt, linecache from traceback import format_exception #The file we read in... fileHandle = "/etc/passwd" srcFile = open(fileHandle,'r') srcList = srcFile.readlines() #yah, a for loop that "iterates" through the file of "lines" for i in srcList: strUsr = string.split(i,":") theUsr = strUsr[0] usrHome = "/expirt/home/",theUsr,"/" usrHome = ''.join(usrHome) print "printing usrHome:",usrHome print "is it a dir?: ", os.path.isdir(usrHome) # try to test if it's a dir... for some reason this mis-behaves... maybe I'm not thinking about it correctly.. if os.path.isdir(usrHome) != 'False': print "User Home dir doesn't exist creating." try: os.makedirs('usrHome' ) except Exception, e: print e print "usrHome is: ",usrHome print "theUsr is: ",theUsr os.system('/usr/bin/chmod 750 ' + usrHome) os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) #OMG, there is directory that happens to already exist! well, due diligence and love for the queen dictates we #provide "due dilligence", (e.g. wipe our asses properly) else: print "User Home dir exist, checking and fixing permissions." print "usrHome is: ",usrHome print "theUsr is: ",theUsr os.system('/usr/bin/chmod 750 ' + usrHome) os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) #I know that I can't optimize the line below further... or... can I? sys.exit("Thanks for using pyDirFixr...") From magdoll at gmail.com Wed Mar 12 02:30:16 2008 From: magdoll at gmail.com (Magdoll) Date: Tue, 11 Mar 2008 23:30:16 -0700 (PDT) Subject: merging intervals repeatedly References: <20b3dfb8-c5b7-4fd0-97a1-93f590f54595@u10g2000prn.googlegroups.com> <13tescq9e809idb@corp.supernews.com> Message-ID: <968a15bf-77cc-4f9c-a579-77ef22e4fae0@s13g2000prd.googlegroups.com> On Mar 11, 11:01 pm, Dennis Lee Bieber wrote: > On Tue, 11 Mar 2008 15:43:40 -0700 (PDT), Magdoll > declaimed the following in comp.lang.python: > > > Correct. I meant the final should be > > (1,30), (29,40), (50,100) > > Actually, even that is incorrect -- note that ,30 overlaps 29, As someone else pointed out, I can't merge (1,30), (29,40) because N = 5. If N were always 1, I could've easily used IntervalSet to do this and I would not have to write more than 5 lines total to get this done. I'm asking precisely because N can be varied and maybe in the future will be more complex than just an integer. > > Since this feels like a homework assignment, I won't be posting my > code... It isn't an homework assignment. I'm writing it for my research. Or more precisely, I've already written a solution and wanted to see if any people here know more salient solutions than mine > > I only state that, 1) I did not bother sorting the interval list -- > unless you have very many intervals to process, a simple sequential > search is probably faster than using bisection/insert algorithm; Unfortunately that is the case. My input can be more than 1 million intervals, although they can be further subdivided into smaller lists, but still, I would be looking at a list of intervals on a size of at least thousands, so binary search would definitely win over sequential search. 2) the > algorithm inserts one interval at a time; 3) merge is accomplished by > removing/returning the first candidate interval to the insert method, > computing the min/max of the candidate and input intervals, and > recursively inserting that new interval -- if there is no candidate > overlap interval, no interval is returned, and the insert just appends > the input interval to the list. This looks like pretty much what my current solution looks like, except that it's unsorted. From tjreedy at udel.edu Sun Mar 2 01:31:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 01:31:30 -0500 Subject: Question about lambda and variable bindings References: <47CA160C.3000305@gmail.com> Message-ID: "Michael Torrie" wrote in message news:47CA160C.3000305 at gmail.com... |I need to use a lambda expression Lambda expressions are a convenience, not a necessity. When having a problem, it sometimes helps to revert to the unabbreviated def statement. tjr From stefan_ml at behnel.de Mon Mar 10 16:39:24 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 21:39:24 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: <47D59C7C.3010100@behnel.de> Bob Martin wrote: > Java is more portable than most other languages, especially if your app needs a gui. I don't think anything is more portable for an App GUI than HTML through a built-in web server. That said, does gcj compile GUI Apps by now? Or does that not count as "portable"? Stefan From grante at visi.com Wed Mar 19 11:20:25 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Mar 2008 15:20:25 -0000 Subject: Speaking Text References: Message-ID: <13u2bppg011i6c9@corp.supernews.com> On 2008-03-19, David C Ullrich wrote: > Mac OS X has text-to-speech built into the interface. > So there must be a way to access that from the command > line as well - in fact the first thing I tried worked: > > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? The only speach sythesizer I've seen on Linux boxes is festival: http://www.cstr.ed.ac.uk/projects/festival/ You can use os.system() to run it from the "command line" or there are various client APIs: http://www.cstr.ed.ac.uk/projects/festival/manual/festival_28.html#SEC126 But, it's not installed by default on any distros I've ever used... -- Grant From fabiofz at gmail.com Thu Mar 6 10:44:37 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 6 Mar 2008 12:44:37 -0300 Subject: Pydev 1.3.14 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.14 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Local renames: scoping issues. * Local renames: comments/strings only renamed in local scope for local variable. * False positive: undefined variable: a base-class could be flagged as undefined if used in a method scope. * Remote Debugger: easier way to specify path translations between a remote machine and a local machine (constant must be set in org.python.pydev.debug/pysrc/pydevd_file_utils.py -- see comments on module) . Release Highlights in Pydev: ---------------------------------------------- * Outline view: patch by Laurent Dore: better icons for different types of fields methods. * Outline view: patch by Laurent Dore: more filters. * PyLint: working dir is the directory of the analyzed file. * Project explorer: fixed bug on integration with Dynamic Web Project. * Extract method: fixed bug when trying to refactor structure: a = b = xxx. * Generate constructor using fields: working for classes that derive from builtin classes. * Override methods: working for classes that derive from builtin classes. * Debugger can use psyco for speedups: see http://pydev.blogspot.com/2008/02/pydev-debugger-and-psyco-speedups.html. * Debugger: shows parent frame when stepping in a return event. * Go to previous/next method: (Ctrl+Shift+Up/Down): does not rely on having a correct parse anymore. * Auto-formatting: No space after comma if next char is new line. * Code Completion: Handling completions from attribute access in classes (accessed from outside of the class). * Auto-indent: Better handling when indenting to next tab position within the code. * Caches: Some places were recreating the cache used during a completion request instead of using the available one (which could have a memory impact on some situations). What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From __peter__ at web.de Sat Mar 1 06:15:22 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Mar 2008 12:15:22 +0100 Subject: invert or not ? References: Message-ID: Stef Mientki wrote: > from the manual I read that a bitwise inversion should be done by invert. > But from some experiments I see that not works equally well. > Is this coincidence ? [Are cryptical posts contagious? I hope not.] Please explain what you did in your experiments and what did not work as expected. > (The disadvantage of invert is that I've to import operators) Do you travel with a suitcase or a lorry? The advantage of import is that your programs won't grind to a halt loading stuff you don't need most of the time. By the way >>> operator.invert(42) == ~42 True Peter From mcantelon at gmail.com Sun Mar 23 18:47:36 2008 From: mcantelon at gmail.com (Mike Cantelon) Date: Sun, 23 Mar 2008 15:47:36 -0700 (PDT) Subject: Open Web Vancouver 2008: A Conference on Open Web Technologies Message-ID: When: Monday April 14 - Tuesday April 15th 2008 Where: Vancouver Convention & Exhibition Centre (VCEC), 999 Canada Place. What: A conference showcasing open source technologies, communities and culture. We are featuring talks from all areas of open source technologies such as PHP, Python, Ruby on Rails, XUL, GPL, Linux, Django, Drupal, HTML, CSS, Javascript and AJAX, XML, Apache, MySQL, Web 2.0, etc. Our format delivers an extremely affordable alternative in comparison to other major conferences. Our community based, volunteer run events in the past have sold-out, attracting audiences from all over the world, and have featured the biggest names in PHP and related topics and technologies. VCEC is the largest conference facility in downtown Vancouver, located in the spectacular inner harbour. The conference will open with a 'keynote' session featuring Tim Bray, Sun Microsystems, Co-Inventor of XML, and Zak Greant of Mozilla Foundation and Foo Associates. A full list of talks is available at: http://www.openwebvancouver.ca/talks See the talk schedule grid at: http://www.openwebvancouver.ca/schedule In addition to our three tracks of presentations on both days of the conference, there will be time allocated for attendees to give short talks on topics of interest in a 'Lightning Talk' format. The Open Web is a presentation of the Vancouver PHP Users Association, a registered non-profit association for the advancement of PHP and the Open Web. Registration, Information: http://www.openwebvancouver.ca/ From rcdailey at gmail.com Fri Mar 7 12:36:36 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 7 Mar 2008 11:36:36 -0600 Subject: system32 directory In-Reply-To: <47D1019A.8000200@timgolden.me.uk> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> <47D1019A.8000200@timgolden.me.uk> Message-ID: <496954360803070936k754cb105q3549991de027e86b@mail.gmail.com> On Fri, Mar 7, 2008 at 2:49 AM, Tim Golden wrote: > > Ah. Sorry. I'm sure you can call it via ctypes (built in > from Python 2.5). But even if I'd realised that's what > you'd wanted, I'd probably have given the original answer > because pywin32 pretty much *is* standard library for any > Python installation I do on Win32 :) > > TJG > I didn't mean to convey that I was rejecting your initial answer, I was just hoping that I wouldn't have to go download another library. Usually it means I have to compile it myself, which in my experience is a total pain in the neck to do on Windows. I'm definitely going to check out pywin32, since ctypes seems like a tedious solution (as many have already pointed out). Thanks again! -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue Mar 4 13:16:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:16:59 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> Message-ID: <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> On Mar 4, 5:27?am, Bruno Desthuilliers wrote: > ?? a ?crit : > > > Howdy everyone, > > > ? ? ?This is a big problem puzzles me for a long time. The core question is: > > How to dynamically create methods on a class or an instance? > > class Foo(object): > ? ? pass > > def bar(self, arg): > ? ? print "in bar : self == % - arg == %s" % (self, str(arg)) > > def baaz(self, arg): > ? ? print "in baaz : self == % - arg == %s" % (self, str(arg)) > > f = Foo() > > # adding bar as a method to class Foo > Foo.bar = bar > > # f now can use bar: > f.bar(42) > > # as well as new instances of Foo, of course > g = Foo() > g.bar() > > # adding baaz as a method to f, the old way: > import new > f.baaz = new.instancemethod(baaz, f, type(f)) > > f.baaz() > > # adding baaz as a method to g, the other way: > g.baaz = baaz.__get__(g, type(g)) > > g.baaz() > > > Let me state it step by step. > > 1. > > def gunc(self): > > ? ? pass > > class A(object): > > ? ? def func(self): > > ? ? ? ? pass > > a = A() > > a.func ? # gives "bound method", type is "instancemethod" > > A.func ?# gives "unbound method", type is "instancemethod" > > gunc ? ?# gives "function", type if "function" > > > # ?? Does this line attach a method to instance? ?... I don't think so. > > a.gunc = gunc > > It doesn't. > > > I found stardard library 'new' may help. Is that right? > > cf above. If you work with old-style classes, you'll need > new.instancemethod. > > > 2. > > a = A() ?# instance of old class A > > # Do attach a new method to class A... > > b = A() ?# instance of new class A > > Does "a" can get the new method automatically? > > Yes. In Python, a class is itself an object, and is an attribute of it's > instances (instance.__class__). Names are resolved at runtime, and > attributes not found in the instance's __dict__ are looked up in the > class (and then in the superclasses etc). > > > Does new method have the *same* concept level with old methods? > > The newly added method works exactly the same way as already existing > ones. Not a single difference. The class statement is just syntactic > sugar anyway. The following snippets are equivalent: > > # sugar-coated: > class Boo(object): > ? ? ?faaz = 0 > > ? ? ?def far(self): > ? ? ? ? ?type(self).faaz += 1 > ? ? ? ? ?print self > > ? ? ?def frob(self): > ? ? ? ? ?print "yadda" > > # raw: > def far(self): > ? ? ?type(self).faaz += 1 > ? ? ?print self > > Boo = type('Boo', (object,), dict(faaz=0, far=far)) > > def frob(self): > ? ? print "yadda" > > Boo.frob = frob > > > Especially, if there > > are classes inherit from class A, how does name resolution work on this case? > > As usual. > > > 3. > > How do I write a decroator for a method? > > Mostly the same way you'd write a decorator for a function > > > Eg: > > class A(object): > > ? ? @my_dec > > ? ? def func(self): > > ? ? ? ? pass > > Here, my_dec should return a method rathar than a function/lambda. Am I right? > > Nope. Functions defined within a class statement are plain ordinary > functions. It's the lookup mechanism that "turns them into methods" when > they are looked up as attribute of a class. In fact, Python "methods" > are thin callable wrappers around a function, a class and (most of the > time) an instance, wrappers which are created - usually at lookup time - > by the __get__ method of the function type (you may want to read about > the descriptor protocol on python.org - in the section about new style > classes IIRC). > > Anyway, you can explore this by yourself: > > ?>>> Boo.far > > ?>>> b.far > > > ?>>> Boo.__dict__['far'] > > ?>>> Boo.__dict__['far'] is far > True > ?>>> f1 = b.far > ?>>> f2 = b.far > ?>>> f1 is f2 > False > ?>>> f1() > <__main__.Boo object at 0xb787f96c> > ?>>> f2() > <__main__.Boo object at 0xb787f96c> > ?>>> dir(f1) > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', > '__get__', '__getattribute__', '__hash__', '__init__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > 'im_class', 'im_func', 'im_self'] > ?>>> f1.im_class > > ?>>> f1.im_func > > ?>>> f1.im_func is far > True > ?>>> f1.im_self > <__main__.Boo object at 0xb787f96c> > ?>>> f1.im_self is b > True > ?>>> bf = Boo.far > ?>>> bf.im_func > > ?>>> bf.im_func is far > True > ?>>> bf.im_class > > ?>>> bf.im_self > ?>>> bf.im_self is None > True > ?>>> far.__get__(b, Boo) > > > ?>>> far.__get__(b, Boo).im_func is far > True > ?>>> > > So, to answer your question: what you are decorating are functions, not > methods. Can you overload -type-'s decision of what to 'bind'?... whenever it is it makes it. From thynnus at gNOTmail.com Tue Mar 4 08:48:31 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 04 Mar 2008 13:48:31 GMT Subject: 'normal' shell with curses In-Reply-To: <633s5lF24prinU1@mid.uni-berlin.de> References: <633s5lF24prinU1@mid.uni-berlin.de> Message-ID: On 3/3/2008 9:57 PM, Michael Goerz wrote: > Hi, > > I'm trying to print out text in color. As far as I know, curses is the > only way to do that (or not?). So, what I ultimately want is a curses > terminal that behaves as closely as possible as a normal terminal, i.e. > it breaks lines and scrolls automatically, so that I can implement a > function myprint(color, text) that does what print() does, only in color. You might find the below helpful. Let us know how you make out? -------- Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 Title: Using terminfo for portable color output & cursor control Description: The curses module defines several functions (based on terminfo) that can be used to perform lightweight cursor control & output formatting (color, bold, etc). These can be used without invoking curses mode (curses.initwin) or using any of the more heavy-weight curses functionality. This recipe defines a TerminalController class, which can make portable output formatting very simple. Formatting modes that are not supported by the terminal are simply omitted. -------- From exarkun at divmod.com Mon Mar 3 00:46:47 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 3 Mar 2008 00:46:47 -0500 Subject: Python Telnet formatting? In-Reply-To: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: <20080303054647.6859.91642152.divmod.quotient.14953@ohm> On Sat, 1 Mar 2008 16:51:08 -0800 (PST), mentaltruckdriver at gmail.com wrote: >Hi everyone: > >I posted here a couple days ago looking for some help creating a >Telnet-based chat server. You guys pointed me to Twisted, which has >solved most of my issues. > >However, what I want to do is analyze strings received for keywords >such as 'listcmds' and have the server return something to the client. >I know how to do that part, at least. > >The issue is, when I use clients like PuTTY, it returns a lot of what >appears to be formatting (e.g. if I typed Hello, it would return "\xff >\xfb\x1f\xff\ >xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) > >How would I go about filtering this stuff out of the strings? The >thing is too, if I use other Telnet programs like Microsoft Telnet, >they don't have this formatting, so I want to be able to recognize if >it does have this formatting and act based on if it does or if it >doesn't. > >Any help is appreciated, I know I'm probably asking too many questions >already :) If you're using Twisted's telnet implementation, then all of the telnet command sequences will be handled separately from the application data. It might help if you share some of your code. Jean-Paul From steve at REMOVE-THIS-cybersource.com.au Tue Mar 11 14:02:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 11 Mar 2008 18:02:12 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <63i6j9F2793buU1@mid.uni-berlin.de> Message-ID: <13tdi949jfa2g55@corp.supernews.com> On Mon, 10 Mar 2008 12:14:40 -0700, metawilm at gmail.com wrote: > Common Lisp has two ways of raising: functions "error" and "signal". > Python's "raise" is like CL's "error": you end up in the debugger if the > exception is not handled. Exceptions that are raised by CL's "signal" > don't have to be caught: if there is no matching "except" clause the > raise statement becomes a "pass". > > Or as Wikipedia states nicely: "Conditions are a generalization of > exceptions. When a condition arises, an appropriate condition handler is > searched for and selected, in stack order, to handle the condition. > Conditions which do not represent errors may safely go unhandled > entirely; their only purpose may be to propagate hints or warnings > toward the user." > > http://en.wikipedia.org/wiki/Exception_handling#Condition_systems If I had come across "signals" before now, I would have thought that they were a good idea. But after watching Lie repeatedly argue for tightly coupling functions together using signal-like "SoftExceptions", all I can see are the disadvantages. I'm afraid that if Lie's arguments are the best available for such a signaling mechanism, then it's probably a good thing Python doesn't have it. -- Steven From jeff at schwabcenter.com Thu Mar 6 00:16:56 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 05 Mar 2008 21:16:56 -0800 Subject: OT[1]: Re: SV: Polymorphism using constructors In-Reply-To: <13suutr9i3fci89@corp.supernews.com> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> <13ssb8fph6nkoff@corp.supernews.com> <29WdncFY4qn0VFPanZ2dnUVZ_ournZ2d@comcast.com> <13suutr9i3fci89@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 05 Mar 2008 08:26:04 -0800, Jeff Schwab > declaimed the following in comp.lang.python: > >> Which is which? Aren't those both part of the space vehicle? Btw, do >> you work for government or industry? Do you enjoy working with the >> space program? I've heard only indirect reviews, and they've been mixed. >> > Lockheed... I don't really work with the sat's themselves. > > When it comes to division of responsibility, the "payload" is the > part the customer wants in orbit. The "space vehicle" is the part that > carries it around in that orbit -- the SV has the station-keeping > thrusters (I'm presuming a geosynchronous orbit), the power supply and > solar panels... The payload may just consist of a wide-band transponder > (for direct TV, say) and maybe an independent commanding system (its own > receive transmit gear on a different frequency from the satellite > control -- though I wouldn't really expect this type of split) Interesting. Thanks. From gdamjan at gmail.com Thu Mar 27 17:06:38 2008 From: gdamjan at gmail.com (Damjan) Date: Thu, 27 Mar 2008 22:06:38 +0100 Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: <47ec0cd0$0$90262$14726298@news.sunsite.dk> mungkol wrote: > Dear all, > > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: you need to install the "build-essential" pacakge group on Ubuntu so that you can compile programs. apt-get install build-essential > limits.h: No such file or directory This is probably /usr/include/linux/limits.h part of the kernel headers. -- damjan From software at ginstrom.com Sun Mar 9 01:04:05 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Sun, 9 Mar 2008 15:04:05 +0900 Subject: SV: Regarding coding style In-Reply-To: <13t6tha12dcdh5a@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net><9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com><13t462h7vgqo081@corp.supernews.com><7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com><13t4k50d7pg0d63@corp.supernews.com><1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com><13t5cbcrhtfsrd2@corp.supernews.com><13t5qd3slgt9nc0@corp.supernews.com><63g9s0F26pgoeU1@mid.individual.net><13t6c8kdis2gbb5@corp.supernews.com> <13t6tha12dcdh5a@corp.supernews.com> Message-ID: <02c001c881ab$65100ac0$0203a8c0@MOUSE> > On Behalf Of Grant Edwards > I think docstrings are a great idea. What's needed is a way > to document the signature that can't get out-of-sync with > what the fucntion really expects. Like doctests? (I know, smart-ass response) Regards, Ryan Ginstrom From inq1ltd at inqvista.com Thu Mar 6 10:19:03 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 06 Mar 2008 10:19:03 -0500 Subject: Licence confusion: distributing MSVC?71.DLL In-Reply-To: References: Message-ID: <200803061019.03761.inq1ltd@inqvista.com> > > If someone has worked their way through > > this maze before and has an answer, I'd > > be keen to hear it. This is what someone wrote on 1-21-2007 to this help site about this pain in the a... MSVCR71 stuff. " I believe this problem doesn't exist. Licensees of Python are permitted to redistribute mscvr71.dll, as long as they redistribute it in order to support pythonxy.dll. The EULA says # You also agree not to permit further distribution of the # Redistributables by your end users except you may permit further # redistribution of the Redistributables by your distributors to your # end-user customers if your distributors only distribute the # Redistributables in conjunction with, and as part of, the Licensee # Software, you comply with all other terms of this EULA, and your # distributors comply with all restrictions of this EULA that are # applicable to you. In this text, "you" is the licensee of VS 2003 (i.e. me, redistributing msvcr71.dll as part of Python 2.5), and the "Redistributable" is msvcr71.dll. The "Licensee Software" is "a software application product developed by you that adds significant and primary functionality to the Redistributables", i.e. python25.dll. IANAL; this is not legal advise." jim-on-linux http://www.inqvista.com From deets at nospam.web.de Sat Mar 29 18:45:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 23:45:09 +0100 Subject: Installing simplejson issues In-Reply-To: References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> Message-ID: <657v3lF2e7r7pU1@mid.uni-berlin.de> Gabriel Genellina schrieb: > En Fri, 28 Mar 2008 23:23:01 -0300, escribi?: > >> On Mar 28, 1:57 pm, "Gabriel Genellina" >> wrote: >>> En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: >>> >>> > I am trying to install the twitter python wrapper...I got that >>> > installed just fine, but am having serious troubles getting the >>> > simplejson package to install. I need help diagnosing where this is >>> > failing. I am trying to use: >>> >>> >http://pypi.python.org/pypi/simplejson >>> >>> > and I run "python setup.py build" and then "python setup.py install", >>> > which both seem to work just fine. > > I tried to install the package but failed. Looks like the setup.py used > by simplejson is broken - doesn't handle well the case when the C > extension can't be compiled. > When I run `python setup.py install` I got this message: > > building 'simplejson._speedups' extension > ********************************************************************** > WARNING: The C extension could not be compiled, speedups are not enabled. > > Below is the output showing how the compilation failed: > > Python was built with Visual Studio version 7.1, and extensions need to > be built > with the same version of the compiler, but it isn't installed. > ********************************************************************** > > and later: > removing simplejson.egg-info\native_libs.txt > ... > error: can't copy 'simplejson.egg-info\native_libs.txt': doesn't exist > or not a regular file > > I suggest that you remove the simplejson-xxxxxx.egg file and delete the > simplejson entry in easy-install.pth (both in your site-packages directory) > Then extract the simplejson directory from inside the original .tar.gz > archive into your site-packages directory (so you end up by example with > a .../site-packages/simplejson/decoder.py file, among others) > That appears to be enough; import simplejson worked fine for me. > > I hate those f****ng eggs. Ah, and I hate easy_install too. This has nothing to do with setuptools or easy_install per se. The author of simplejson tried to create a library that works with or without a C-extension. And failed. As your above approach fails to even *try* and compile the speedups. Diez From zerty.david at gmail.com Sun Mar 30 16:55:15 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:55:15 -0300 Subject: Newbie Question.. How to add python to system path in windows? Message-ID: <5dc598e30803301355w7496acafu5261b6f0dfc54405@mail.gmail.com> hi All, I have my Phitno 25 installed on the default directory, but How can I dd to the ubild path? Thx -------------- next part -------------- An HTML attachment was scrubbed... URL: From sleddd at gmail.com Thu Mar 13 00:46:31 2008 From: sleddd at gmail.com (sleddd at gmail.com) Date: Wed, 12 Mar 2008 21:46:31 -0700 (PDT) Subject: Socket Performance Message-ID: Can anyone explain why socket performance (throughput) varies depending on the amount of data send and recv are called with? For example: try creating a local client/server (running on the same computer) where the server sends the client a fixed amount of data. Using method A, recv(8192) and sendall( ) with 8192 bytes worth of data. Do this 100 times. Using method B, recv(1) and sendall( ) with 1 byte worth of data. Do this 819200 times. If you time both methods, method A has much greater throughput than method B. Server: import socket import random import string import time HOST = 'localhost' PORT = 50023 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr string_1 = 'A' string_8192 = ''.join([random.choice(string.letters + string.digits) for i in range(8192)]) conn.sendall('Start') start = time.clock() total_data = 0 for i in range(0,100): conn.sendall(string_8192) total_data += len(string_8192) print 'Send Speed (Long String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec\n\n' start = time.clock() total_data = 0 for i in range(0,819200): conn.sendall(string_1) total_data += len(string_1) print 'Send Speed (Short String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec' conn.close() Client: import socket import time HOST = 'localhost' # The remote host PORT = 50023 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, 50026)) s.connect((HOST, PORT)) data = s.recv(5) print 'From Server: ' + data start = time.clock() total_data = 0 while total_data < 819200: data = s.recv(8192) total_data += len(data) print 'Receive Speed (Long String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec\n\n' start = time.clock() total_data = 0 while total_data < 819200: data = s.recv(1) total_data += len(data) print 'Receive Speed (Short String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec' s.close() From george.sakkis at gmail.com Mon Mar 24 15:18:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Mar 2008 12:18:23 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> Message-ID: On Mar 24, 3:13 pm, pythonnubie wrote: > > > i have come across my first exeption using randrange . The exeption > > > is " no such attribute " in module random > > > > platform is xp home and the python build is activestate 2.5 > > > Welcome aboard! > > > There's definitely a randrange function in the random module, so > > something else must be wrong. To get the most out of this list and > > minimize wasted bandwidth, the most effective way usually consists of > > copying and pasting: > > 1. The offending code (or just the relevant part if it's too big). > > 2. The full traceback of the raised exception. > > > Regards, > > George > > Hwere is the complete traceback ! >>> The word is: index > > Traceback (most recent call last): > File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", line 307, in RunScript > debugger.run(codeObject, __main__.__dict__, start_stepping=0) > File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > \__init__.py", line 60, in run > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > \debugger.py", line 631, in run > exec cmd in globals, locals > File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, > in > import random > File "F:\Documents and Settings\Mark\My Documents\random.py", line > 13, in > distributions on the real line: > AttributeError: 'module' object has no attribute 'randrange' > > Why would it say it can't find the function ? Because you named your file 'random.py' and it shadows the standard random module! Change the name to something else, say foo.py, and try it again. George From robert.rawlins at thinkbluemedia.co.uk Wed Mar 12 10:33:07 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 12 Mar 2008 14:33:07 -0000 Subject: MySQL DB-Api In-Reply-To: <008601c8836a$5c5fbf90$151f3eb0$@rawlins@thinkbluemedia.co.uk> References: <008601c8836a$5c5fbf90$151f3eb0$@rawlins@thinkbluemedia.co.uk> Message-ID: <005f01c8844d$fd82dfe0$f8889fa0$@rawlins@thinkbluemedia.co.uk> Hello guys, sorry for dragging this to the top of the list again but I really am intrigued to get your feedback. I'm looking for a clean and efficient way to implement the DB-API into my application without having to create database connections for every instance of objects which require it. I'd love to create some form of cached instance of the connection within the application and then provide new cursor instances for objects that need to query the database but I'm not sure of the best way to deal with this to ensure the cursors are closed when the instances destruct, or just as importantly, if I even need to close the cursor. I'd be really interested to know how you are implementing this kind of thing, Cheers, Robert From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins Sent: 11 March 2008 11:24 To: python-list at python.org Subject: MySQL DB-Api Good morning list. I'm in the process of learning my way around the DB-API module for MySQL and wanted to come and get some advice on how you all manage your database connections and cursors. Within my applications I'll have many classes which access the database, I'm wondering to what level I should extract the database connection. Should I create a new database connection and close it for every method which calls the database? Should I create the connection/cursor to the DB when I construct the class and place the cursor in the self scope? Or should I create a application wide connection/cursor to the database and inject the cursor into all the classes which require it? All classes within the application access the same database so at the moment I'm leaning towards creating an application wide connection and cursor and then injecting it into classes which require database access, does that sound like a fair plan? I'm just interested to learn how you are managing this. Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Bossy at jouy.inra.fr Tue Mar 25 12:12:50 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 17:12:50 +0100 Subject: Creating dynamic objects with dynamic constructor args In-Reply-To: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> References: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> Message-ID: <47E92482.6050208@jouy.inra.fr> Greg at bag.python.org wrote: > I'd like to create objects on the fly from a pointer to the class > using: instance = klass() But I need to be able to pass in variables > to the __init__ method. I can recover the arguments using the > inspect.argspec, but how do I call __init__ with a list of arguments > and have them unpacked to the argument list rather than passed as a > single object? > > ie. class T: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > argspec = inspect.argspec(T.__init__) > args = (1, 2) > > ??? how do you call T(args)? > The star operator allows you to do this: T(*args) You also can use dict for keyword arguments using the double-star operator: class T(object): def __init__(self, foo=None, bar=None): self.foo = foo self.bar = bar kwargs = {'bar': 1, 'foo': 2} T(**kwargs) RB From fakeaddress at nowhere.org Fri Mar 14 08:41:45 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 12:41:45 GMT Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Message-ID: Robert Bossy wrote: > Bryan Olson wrote: >> Robert Bossy wrote: >>>> Robert Bossy wrote: >>>>> Indeed! Maybe the best choice for chunksize would be the file's buffer >>>>> size... >> >> That bit strikes me as silly. >> > The size of the chunk must be as little as possible in order to minimize > memory consumption. However below the buffer-size, you'll end up filling > the buffer anyway before actually writing on disk. First, which buffer? The file library's buffer is of trivial size, a few KB, and if we wanted to save even that we'd use os.open and have no such buffer at all. The OS may set up a file-specific buffer, but again those are small, and we could fill our file much faster with larger writes. Kernel buffers/pages are dynamically assigned on modern operating systems. There is no particular buffer size for the file if you mean the amount of kernel memory holding the written data. Some OS's do not buffer writes to disk files; the write doesn't return until the data goes to disk (though they may cache it for future reads). To fill the file fast, there's a large range of reasonable sizes for writing, but user-space buffer size - typically around 4K - is too small. 1 GB is often disastrously large, forcing paging to and from disk to access the memory. In this thread, Matt Nordhoff used 10MB; fine size today, and probably for several years to come. If the OP is writing to a remote disk file to test network throughput, there's another size limit to consider. Network file- system protocols do not steam very large writes; the client has to break a large write into several smaller writes. NFS version 2 had a limit of 8 KB; version 3 removed the limit by allowing the server to tell the client the largest size it supports. (Version 4 is now out, in hundreds of pages of RFC that I hope to avoid reading.) -- --Bryan From http Tue Mar 4 14:19:20 2008 From: http (Paul Rubin) Date: 04 Mar 2008 11:19:20 -0800 Subject: How about adding rational fraction to Python? References: <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> <763ea020-731a-4ca0-8be7-55430676f1b7@i7g2000prf.googlegroups.com> Message-ID: <7xwsoiuwjr.fsf@ruckus.brouhaha.com> Mark Dickinson writes: > For randomly chosen(*) base B floats x and y, the probability that > (x/y)*y == x is approximately given by I remember hearing that IEEE 754 was carefully designed to make this identity hold as often as possible when y is a small integer. From newsgroup898sfie at 8439.e4ward.com Tue Mar 4 18:26:23 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Tue, 04 Mar 2008 18:26:23 -0500 Subject: 'normal' shell with curses In-Reply-To: <635drhF25qgqtU1@mid.uni-berlin.de> References: <633s5lF24prinU1@mid.uni-berlin.de> <635drhF25qgqtU1@mid.uni-berlin.de> Message-ID: <63644vF263tesU1@mid.uni-berlin.de> Michael Goerz wrote, on 03/04/2008 12:05 PM: > Thynnus wrote, on 03/04/2008 08:48 AM: >> On 3/3/2008 9:57 PM, Michael Goerz wrote: >>> Hi, >>> >>> I'm trying to print out text in color. As far as I know, curses is >>> the only way to do that (or not?). So, what I ultimately want is a >>> curses terminal that behaves as closely as possible as a normal >>> terminal, i.e. it breaks lines and scrolls automatically, so that I >>> can implement a function myprint(color, text) that does what print() >>> does, only in color. >> >> You might find the below helpful. Let us know how you make out? >> >> -------- >> >> Python Cookbook >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 >> >> Title: >> Using terminfo for portable color output & cursor control >> >> Description: >> The curses module defines several functions (based on terminfo) that >> can be used to perform lightweight cursor control & output formatting >> (color, bold, etc). These can be used without invoking curses mode >> (curses.initwin) or using any of the more heavy-weight curses >> functionality. This recipe defines a TerminalController class, which >> can make portable output formatting very simple. Formatting modes that >> are not supported by the terminal are simply omitted. >> >> -------- >> > > That looks *extremely* interesting. From a very brief test, it seems to > do exactly what I want! > > Now, Windows seems very problematic for color output. I was using the > following as a test, based on the above recipe: > > term = TerminalController() > while True: > print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled' > print term.render('${RED}Error:${NORMAL}'), 'paper is ripped' > > On Linux, it works fine, on Windows, it just prints white on black > (which is of course what it should do if the terminal doesn't support > color). Can anyone get the Windows cmd.exe terminal to do color? I > already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, > but that doesn't seem to do anything (neither in what I tried yesterday > with the ANSI escape codes, nor with the recipe code now). I also very > briefly tried running it on the winbash shell > (http://win-bash.sourceforge.net/), it didn't have any color either... > So, any way to get color in Windows? > > Michael This recipe seems to work very well on WinXP: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496901 So now, I'll just have to combine the two methods, which shouldn't be too hard. Michael From bj_666 at gmx.net Wed Mar 19 16:27:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Mar 2008 20:27:56 GMT Subject: Prototype OO References: Message-ID: <64dbacF289sqvU1@mid.uni-berlin.de> On Wed, 19 Mar 2008 17:59:40 +0100, sam wrote: > Can someone tell me why class-based OO is better that Prototype based, > especially in scripting langage with dynamic types as Python is? Is it better!? Ciao, Marc 'BlackJack' Rintsch From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 09:08:56 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 15:08:56 +0100 Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> On Sun, 2 Mar 2008 15:06:17 +0100 Preben Randhol wrote: > class dbase(list): Sorry the definition of the class is: class dbase(object): it doesn't derive from the list class. Preben From castironpi at gmail.com Sat Mar 22 15:17:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 12:17:45 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: On Mar 22, 3:31?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > John Machin wrote: > >> On Mar 22, 1:11 am, castiro... at gmail.com wrote: > >>> A collision sequence is not so rare. > >>>>>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > >>> [1, 1, 1, 1, 1, 1, 1, 1] > >> Bryan did qualify his remarks: "If we exclude the case where an > >> adversary is choosing the keys, ..." > > > Some adversary. ?What, you mean, my boss or my customers? > > We mean that the party supplying the keys deliberately chose > them to make the hash table inefficient. In this thread the goal > is efficiency; a party working toward an opposing goal is an > adversary. > > If you find real-world data sets that tend to induce bad-case > behavior in Python's hash, please do tell. It would be reason > enough to adjust the hash function. The hashes in popular > software such as Python are already quite well vetted. > > Even a hash function that behaves as a random oracle has > worst-case quadratic-time in the algorithm here, but that's > an issue in theory and not in serving customers. Hey Net: Where -we- left off, all real-world data sets were equally common, unless you think in peckbird bartenders. Nuh uh at all, unless you've got a characterize real-world data project underway. Did you know letter frequency distributions vary by domain? And now for the 2- squarebar spider. raise ISay( "Python Science is unusually prone against non-power multiples of 32 hashing integers", "Unknown value of I" ) parse( 'strangers are perfect' ) parse( 'i think i know someone' ) prevention.value() == 12* cure.value() raise SolveFor (raise CureValueSterling) keep: time.value().encode() > money.value() assert time.value().encode()== time.encode().value() perch( Out ) compose( Fluctuate ) compose( Punctuate ) compose( Explain ) @partial( partial, prefix ) (ha, h) raise Distracts( 'Well, would you look at that?' ) raise LivingConstraint( NoseFalls ) raise Superlative voice Absolute raise NonScalar( "Fit: It's apples -over- oranges." ) raise OverPull( "Not on Google." ) raise Drop( "It." ) moment+= instant raise LeavesImpression raise GoodMuleTwoHaystacks raise ScaleDecomposition raise Bias( 'Discrimination' ) raise BadFor raise RequestedControlCurrencyExpiration raise InsufficientTrust raise Shock raise EnoughTheory raise EnoughCustomers raise EyebrowTwo raise DataKill raise Reckless raise ThenWhat( AfterYou ) raise NotImplemented( 'Offer.refuse' ) raise LaughterUnacceptable raise Hell raise DesignUnintelligent raise HashesPerturbation raise ProfessionException yield Tick yield Tally yield Ho yield Gee yield Whoa raise ActuallyActuallyActually raise CurrencyAStream If you can't fit an analogy... Bee Dance : Hive Good :: Human This :: Community Good? What and how is it when to who where? What does it know? What does it do but sleep? Does it specialize, momentarily fair? Hey, what do you think of the spelling of this? "The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet." What do you think of the wording of "spelling"? Take me to your lexicographer: wake-up; you're up web, Europe web. Pass self to a generator. Dust is sett'ling; Tables turn: Water's drying; Sugars burn. Phaser fire! Shoulders square! join( TenForward )? Who is where? Mushroom's growing; Mighty... falls. Cauldron's bubbling; That is all. >>> def f(): ... n= True ... while 1: ... k= yield( n ) ... if k is not None: n= k ... >>> a= f() >>> next( a ) True >>> next( a ) True >>> next( a ) True >>> a.send( 2 ) 2 >>> next( a ) 2 >>> next( a ) 2 >>> next( a ) 2 >>> From crazylunjay at gmail.com Mon Mar 24 19:55:17 2008 From: crazylunjay at gmail.com (jwesonga) Date: Mon, 24 Mar 2008 16:55:17 -0700 (PDT) Subject: PyGTK localisation on Win32 Message-ID: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> I've built an app on linux which we have managed to localise into at least three languages, the app runs well using this command LANG=fr_FR python app.py which would translate the app into french. We've tried the replicate the same principle on windows but so far nothing works, the app will need to be translated into other languages that have no locale, in windows is there a way to have Glade load values from a textfile instead of trying to use the .mo files? From mensanator at aol.com Tue Mar 11 15:12:56 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 11 Mar 2008 12:12:56 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> Message-ID: <306997c4-36dc-4603-8100-f47e25e55bef@s19g2000prg.googlegroups.com> On Mar 11, 3:36 am, Duncan Booth wrote: > Mensanator wrote: > > On Mar 10, 10:44???pm, Nathan Pinno wrote: > >> Why does my compiler say invalid syntax and then highlight the > >> quotation marks in the following code: > > >> # This program is to find primes. > > > Needs work. > > Be fair. Being helpful isn't fair? > The OP hadn't managed to figure out why the program wasn't > running, so you can't expect him to have got all the bugs out of the code > yet. The bug had already been answered. If you fail to implement your premise correctly, you have a bug. It doesn't matter if the code is bug-free if the premise is false. In this case, the premise that he can determine primes this way is false. He will have to abandon the cos() thing, for although it works in theory, he'll never get it to work in practice. Besides, the cos() is a red herring (hint: cos(pi*n)). The problem can be made to work EXACTLY (at least up to z=10000) by using rationals (which gmpy supports). His problem is going to take much more than fixing a syntax error. > And he only asked about the specific syntax error not the entire > solution to his homework. If this is indeed homework, and he's supposed to come up with a factorial algorithm, I seriously doubt the teacher would accept gmpy.fac(z-1), so I assume it isn't. > > My advice to Nathan would be: > > 1. If you get a weird syntax error that you don't understand try cutting > the code down to just the bit which generates the error. > > 2. Play around in the interactive interpreter to see what works and what > doesn't. > > 3. If you don't understand why the code doesn't work then get a stuffed > toy, cardboard cutout of a person, or the least technical member of your > family and explain to them in great detail exactly why the code must > (despite error messages to the contrary) be correct. Usually you'll spot > the problem half way through the explanation. > > 4. If you post to this list then post the full error message and traceback. > That way we don't have to guess which quotation marks are the problem. From kay.schluehr at gmx.net Wed Mar 5 23:11:08 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 5 Mar 2008 20:11:08 -0800 (PST) Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: <9a9a239e-52a6-4102-ad03-908def38cbae@p25g2000hsf.googlegroups.com> On 5 Mrz., 13:47, gideon wrote: > Hi Everybody, > > In the context of a master's thesis I'm currently looking into > Python's operational semantics. Even after extensive searching on the > web, I have not found any formal model of Python. Therefore I am > considering to write one myself. To make a more informed decision, I > would like to ask you: > > What previous work has been done that I should be aware of? Currently > I have found exactly nothing on python itself. There is some > interesting work on other, related languages like Smalltalk. > > Which version of Python is the most interesting? Python 3.0, although > it would be a moving target, seems promising. Because it will simplify > the language in some aspects by ditching backwards compatibility (e.g. > old style classes and coercion), the semantics will be more clean. > > Of course I will get, answers to many questions I did not ask. In > fact, I would like you to vent your opinions on this matter. > > Thanks! Specifying Python formally could be a life work if this is anyhow possible. So one has to restrict on certain aspects. I guess the issue most people inside the discipline but also outside academia would be most interested in is evaluation contexts: how are dictionaries and tuples used in evaluation of Python bytecodes? How are stack frames built and what information do they contain? Some of this stuff is beyond what ordinary Pythonistas look at ( other than runtime developers ) and building an abstract Python machine would be invaluable. The class semantics alone might fill a master thesis but then you are also already involved in the question on how dicts and scope are used to store/access contextual information. Specifying how garbage collection works would be another highlight. There is incredibly many stuff lying around and being untouched by language researchers who usually write appendices to the work of the heroes of their own professors ( who really wants to read another work about Scheme or Smalltalk? ). Let us know when you got done something. From jim.vickroy at noaa.gov Tue Mar 25 16:17:16 2008 From: jim.vickroy at noaa.gov (j vickroy) Date: Tue, 25 Mar 2008 14:17:16 -0600 Subject: how to dynamically create class methods ? In-Reply-To: <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> Message-ID: <47E95DCC.7050507@noaa.gov> Arnaud Delobelle wrote: > On Mar 25, 6:13 pm, j vickroy wrote: >> Hello, >> >> Here is some pseudo-code that hopefully illustrates what I want to do: >> >> records = list(...) >> for record in records: >> new_fcn = define_a function_for(record) >> instance = my_new_class_instance() >> setattr(instance, 'myfcn', new_fcn) >> instance.execute() # instance.execute() calls instance.myfcn(*args) >> >> I have looked at some of the functions in the *new* module and >> new.code(...), new.function(...), and new.instancemethod(...) appear to >> do what I want, but I do not know how to use new.code() and >> new.function() -- specifically what its *global* parameter should be. > > The best way to understand how new.function and new.code work is to > look at the Python source. (Objects/funcobject.c and Objects/ > codeobject.c, actual objects are defined in and Include/funcobject.h > Include/code.h). > > However, to create a function dynamically in Python it is often no > more trouble than a def statement: > > Funnily enough I can't think of a nice example ATM so here is a bad > one: say you want to create a function that checks the spelling of a > word, regardless of case. You could a function that returns on-the- > fly created functions that check the spelling of a word like this: > > def get_spellchecker(word): > word = word.upper() > def check_spelling(candidate): > return candidate.upper() == word > return scheck_spelling > > Then > >>>> check_hypo = get_spellchecker('hypopothamus') >>>> check_hypo('Hypopothamus') > True >>>> check_hypo('Big scary mammal') > False > > (Warning: this is all untested). > > HTH > > -- > Arnaud > Thanks for your reply, Arnaud. As per your suggestion, I tried looking at include/code.h and include/funcobject.h (my MS Windows distribution does not appear to contain .c files). However, since I'm not a C programmer, I did not find the .h files all that helpful. What I failed to make clear in my original posting is that the functions must be created dynamically using information in a *record* as the code iterates over all *records*. So, I can not pre-define the functions and then simply select the desired one at run-time. -- jv From userprogoogle-139 at yahoo.co.uk Thu Mar 6 06:43:08 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 6 Mar 2008 03:43:08 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> Message-ID: <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> Hi, Thanks for your very quick response. I have played around a bit more so that both the image and HTML file are in the public_html folder. They are called via python using a relative URL, and have permissions set to 755. Within the HTML file the image is accessed using just "banner.jpg". The actual page displays ok except for the image - so it has the same problem as before. However when the same page is displayed without running through a CGI it displays perfectly. Kind regards, rod On Mar 6, 11:46 am, Bryan Olson wrote: > rodmc wrote: > > [...] > > Python: > > > > f = open("finish.html") > > doc = f.read() > > f.close() > > print doc > > You might need to start with: > > print "Content-Type: text/html" > print > > Is "finish.html" in the right place? When you browse to your > script, can you see that you're getting the html? > > > HTML: > [...] > >

> I suspect a server configuration and/or resource placement problem. > The image has a relative URL, and the user's browser will look for > it on the same path that it used to get the resource served by the > cgi script, up to last '/'. > > Is banner.jpg in the right place, and is your web server configured > to treat everything in that directory as a cgi script, and thus > trying to execute the jpg? If one of those is the problem, just > move banner.jpg, and/or change the relative URL. For example, > SRC="../banner.jpg" will cause the browser to look for the jpg > one directory above. > > Failing that, can look at the web server's log? > > -- > --Bryan From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:49:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:49:41 -0200 Subject: Beginner's assignment question References: Message-ID: En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > Lorenzo Gatti wrote: >> On Mar 1, 3:39 pm, Schizoid Man wrote: >>> As in variable assignment, not homework assignment! :) >>> >>> I understand the first line but not the second of the following code: >>> >>> a, b = 0, 1 >>> a, b = b, a + b >>> >>> In the first line a is assigned 0 and b is assigned 1 simultaneously. >>> >>> However what is the sequence of operation in the second statement? I;m >>> confused due to the inter-dependence of the variables. >> >> The expressions of the right of the assignment operator are evaluated >> before assigning any new values, to the destinations on the left side >> of the assignment operator. >> So substitutig the old values of a and b the second assignment means >> >> a, b = 0, 0 + 1 >> >> Simplifying the Python Reference Manual ("6.3 Assignment Statements") >> a little : >> >> assignment_stmt ::= target_list "="+ expression_list >> >> An assignment statement evaluates the expression list (remember that >> this can be a single expression or a comma-separated list, the latter >> yielding a tuple) and assigns the single resulting object to each of >> the target lists, from left to right. >> >> [...] >> >> WARNING: Although the definition of assignment implies that overlaps >> between the left-hand side and the right-hand side are `safe' (for >> example "a, b = b, a" swaps two variables), overlaps within the >> collection of assigned-to variables are not safe! For instance, the >> following program prints "[0, 2]": >> >> x = [0, 1] >> i = 0 >> i, x[i] = 1, 2 >> print x >> >> Lorenzo Gatti > > Thank you for the explanation. I guess my question can be simplified as: > > First step: a, b = 0, 1 > No problem here as a and b are assigned values. > > Second step: a, b = b, a + b > > Now my question is does b become a + b after a becomes 1 or while a > stays at 0? > > As the assignment occurs simultaneously I suppose the answer is while a > stays at 0. Read the previous response carefully and you'll answer your question. The right hand side is EVALUATED in full before values are assignated to the left hand side. Evaluating b, a+b results in 1, 1. The, those values are assigned to a, b. -- Gabriel Genellina From xng at xs4all.nl Sun Mar 23 08:15:19 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Sun, 23 Mar 2008 13:15:19 +0100 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <47e64a55$0$19418$e4fe514c@dreader22.news.xs4all.nl> jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. I for one can't really answer this question but I wanted to share the reason for that :-) since I worked in the dutch high school equivalent for a number of years. First and most important is I think the objective you want to reach, at my school we had a number of angles: - A math teacher using it as a simpler way of writing examples and explanation while being able to let the students see what is going on and why. - A basic grade computer introduction, to let them feel what automation is about, more like the philosophy of it. - A higher grade computer science (well for high school that is) introduction in to programming. - A explanation what makes the computer tick and how it does it (cpu architecture, memory management etc.) In my opinion python is extremely useful for all of these objectives, except for the last one, this would be more a job for assembler. My school decided not to go in depth to that because we felt it would be out of reach for the majority of the students and we didn't wanted to spoil the students when they decide to take up CS in university later on. -- mph From castironpi at gmail.com Fri Mar 14 17:59:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 14:59:54 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: On Mar 14, 1:47?pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Aahz > > Sent: Friday, March 14, 2008 2:05 PM > > To: python-l... at python.org > > Subject: RIP: Joseph Weizenbaum > > > Creator of Eliza: > > >http://www-tech.mit.edu/V128/N12/weizenbaum.html > > -- > > How do you feel about creator of Eliza? What is Eliza? From http Mon Mar 3 11:39:52 2008 From: http (Paul Rubin) Date: 03 Mar 2008 08:39:52 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <7xzltgrbyi.fsf@ruckus.brouhaha.com> <5MSdnajOndDRq1banZ2dnUVZ_oSunZ2d@comcast.com> Message-ID: <7xwsoj92xz.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > > User defined types in python are fairly heavyweight compared with the > > built-in types, > > Yet they continue to form the basis of almost all non-trivial Python > programs. Anyway, it's a bit soon to be optimizing. :) Large python programs usually have some classes for complex data structures, but it's not typical Pythonic practice to define new classes for things as small as integers. > > and a type like that is just another thing for the user to have to > > remember. > > How so? A well-written function generally shouldn't depending on the > exact types of its arguments, anyway. By "another thing to remember" I mean doing the right thing should happen with the normal integers that result from writing literals like 1 and 2, without resorting to a nonstandard user defined type. > If someone has written a > function to find (e.g.) the median of a collection of numbers, their > code should already be prepared to accept values of user-defined > numeric types. It's important to be able to write such generic or polymorphic functions, but most typical functions are monomorphic. > If I want to call such a function with my hand-rolled > DivisionSafeInteger type, it should just work, Sure, however, the Pythonic approach is to make the defaults do the right thing without requiring such user-written workarounds. Of course there is occasional unclarity about what the right thing is. > > file) and size_t, so if you pass an off_t to a function that expects a > > size_t as that arg, the compiler notices the error. > > On what compiler? I've never seen a C compiler that would mind any > kind of calculation involving two native, unsigned types. You are right, C is even worse than I remembered. > > But they are > > really just integers and they compile with no runtime overhead. > > They do indeed have run-time overhead, as opposed to (e.g.) meta-types > whose operations are performed at compile-time. Not sure what you mean; by "no runtime overhead" I just mean they compile to the same code as regular ints, no runtime checks. OK, it turns out that for all intents and purposes it looks like they ARE regular ints even at compile time, but in other languages it's not like that. > If you mean they have less overhead than types whose operations > perform run-time checks, then yes, of course that's true. You > specifically stated (then snipped) that you "would be happier if > int/int always threw an error." The beauty of a language with such > extensive support for user-defined types that can be used like > built-in type is that you are free to define types that meet your > needs. But those are not ints then. We're discussing an issue of language design, which is what the behavior of the ordinary, standard, default ints should be. My reason for suggesting int/int->error is that I think it would increase program reliability in general. But that is only if it applies to all the ints by default, with int/int=float being a possible result of a nonstandard user-defined type. From the zen list: "In the face of ambiguity, refuse the temptation to guess." > My understanding is that Python will easily support lots of different > types of just about anything. That's the point. No I don't think so. Also from the zen list: "There should be one-- and preferably only one --obvious way to do it." > > There's an interesting talk linked from LTU about future languages: > > http://lambda-the-ultimate.org/node/1277 > > Thanks, but that just seems to have links to the slides. Is there a > written article, or a video of Mr. Sweeney's talk? I don't think there's an article. There might be video somewhere. I thought the slides were enough to get the ideas across so I didn't have much interest in sitting through a video. From mnordhoff at mattnordhoff.com Thu Mar 6 18:29:26 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 06 Mar 2008 23:29:26 +0000 Subject: Internet Explorer 8 beta release In-Reply-To: References: Message-ID: <47D07E56.4020202@mattnordhoff.com> Colin J. Williams wrote: > Isn't compliance with the W3C standard > the best way of achieving multiple > browser rendering? Exactly. IE 8 is supposed to be significantly less horrible. It won't catch up completely, but perhaps by IE 9 it will. Or this is all a joke, Microsoft buys Opera and shuts them down. (Anyway, I marked the OP as spam.) -- From sjmachin at lexicon.net Mon Mar 10 17:09:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 14:09:34 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> Message-ID: <1a66500d-cea8-4984-8806-3c3ff113c8ea@i12g2000prf.googlegroups.com> On Mar 11, 2:24 am, rockingred wrote: > > In the case where dots are used as a date separator, count the number > of dots (you should also count commas). If a single comma appears and > is preceeded by only numbers or numbers with decimals, assume "foreign > float". Bzzzzt. 1,234 is the integer 1234 to John, and its only a float to Jean if Jean is not a Scots lass :-) From http Mon Mar 17 21:01:21 2008 From: http (Paul Rubin) Date: 17 Mar 2008 18:01:21 -0700 Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <7x7ig0devy.fsf@ruckus.brouhaha.com> WaterWalk writes: > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. Try winpdb.org which despite the name has nothing to do with MS Windows. From matiassurdi at gmail.com Sun Mar 30 08:36:09 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Sun, 30 Mar 2008 14:36:09 +0200 Subject: python ODF library? In-Reply-To: References: Message-ID: Matias Surdi escribi?: > Do yo know any good OpenDocumentFormat library for python? > > I'm starting a project on wich I'll have to programatically modify ODF > text documments, so, after reinventing the wheel, I'd like to know if > already something exists. > > Thanks a lot. > Found it: http://opendocumentfellowship.com/development/projects/odfpy :-) From bj_666 at gmx.net Sat Mar 15 02:16:43 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 06:16:43 GMT Subject: request for Details about Dictionaries in Python References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> Message-ID: <6417u2F29qj9jU3@mid.uni-berlin.de> On Fri, 14 Mar 2008 17:06:00 +0000, Matt Nordhoff wrote: > Hmm, if Perl's on-disk hash tables are good, maybe someone should port > them to Python, or maybe someone already has. I don't know Perl's on-disk hash tables but there is a `shelve` module in the standard library. Ciao, Marc 'BlackJack' Rintsch From rockxuan at gmail.com Tue Mar 18 03:58:51 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:58:51 -0700 (PDT) Subject: replicas super quality watches & jewellery fashion Message-ID: <6c79f065-1627-4af3-a0d3-dfddab0ed606@d4g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From darkwind.87 at gmail.com Tue Mar 25 18:02:00 2008 From: darkwind.87 at gmail.com (Dark Wind) Date: Tue, 25 Mar 2008 15:02:00 -0700 Subject: what does ^ do in python Message-ID: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Hi, In most of the languages ^ is used for 'to the power of'. In python we have ** for that. But what does ^ do? I could not get it just by using it ... some examples are: 1^1 returns 0 2^2 returns 0 1^4 returns 5 4^1 returns 5 3^5 returns 6 5^3 returns 6 ...... just curious Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Mar 28 16:34:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Mar 2008 20:34:16 GMT Subject: Problem with format string and unicode References: Message-ID: <655328F2e1u8fU1@mid.uni-berlin.de> On Fri, 28 Mar 2008 21:13:00 +0100, Hans Martin wrote: > this is probably a trivial problem, but a google search for "python" > and "unicode" and" format string" gives too many hits: If I specify > e.g. "%20s" in a format string and the string value contains UTF-8 > stuff (differing number of bytes per character), the length of the > resulting string (in characters) varies. How can I fix this? Use unicode strings instead. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Wed Mar 12 07:30:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Mar 2008 12:30:41 +0100 Subject: Max File Size References: <1e8a2f49-e40b-4a6d-bc48-6d4f9a648c6d@s12g2000prg.googlegroups.com> Message-ID: <63pt70F28u3flU1@mid.uni-berlin.de> xkenneth wrote: > Is the max file size a relevant issue in python anymore? I know OS X > has a max file size of 8 exabytes and I'm not sure about the latest > version of Ubuntu. Does python have an independent file size limit, or > is it dependent upon the OS it was compiled on? The latter should be the case. E.g. ZODB can grow larger than 2GB. Diez From gabriel.rossetti at mydeskfriend.com Mon Mar 10 13:54:49 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Mon, 10 Mar 2008 18:54:49 +0100 Subject: execute python script question Message-ID: <47D575E9.8040507@mydeskfriend.com> Hello, I have been developping something in python that has the following hierarchy : project/src/myPackage/ project/src/myPackage/__init__.py project/src/myPackage/module1.py project/src/myPackage/module2.py project/src/myPackage/test/ project/src/myPackage/test/__init__.py project/src/myPackage/test/test_module1.py project/src/myPackage/test/test_module2.py project/src/myPackage/mySubPackage/__init__.py project/src/myPackage/mySubPackage/module1.py project/src/myPackage/mySubPackage/test/ project/src/myPackage/mySubPackage/test/__init__.py project/src/myPackage/mySubPackage/test/module1.py ... up until now, I had been executing my modules from inside project/src/myPackage/ but I realised that that is wrong (while implementing the test suite) and that since all my modules had relative imports (if module2 needed module1, it would just say : import module1) I changed them to myPackage.module1 for example. Now my test suite is happy, I can say : test.sh myPackage.test and it tests everything. The only problem now is that I can't execute the scripts from inside or outside the myPackage dir, I get this : from outside : Traceback (most recent call last): File "myPackage/module1.py", line 15, in from myPackage import constants, utils ImportError: No module named myPackage or if from inside it : Traceback (most recent call last): File "module1.py", line 15, in from myPackage import constants, utils ImportError: No module named myPackage can anybody please help me? I don't think I understood the whole package/module thing I think... I think some people do some sort of importing in the __init__.py files but I'm not sure this helps in this case. Thanks, Gabriel -- www.mydeskfriend.com PSE - C (EPFL) 1015 Ecublens, Switzerland Tel: +41 21 601 52 76 Mob: +41 76 442 71 62 From wescpy at gmail.com Wed Mar 19 00:41:21 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 18 Mar 2008 21:41:21 -0700 (PDT) Subject: What Programming Languages Should You Learn Next? Message-ID: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> http://it.slashdot.org/it/08/03/18/1633229.shtml it was surprising and disappointing that Python was not mentioned *anywhere* in that article but when someone replied, it sparked a long thread of post-discussion. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bignose+hates-spam at benfinney.id.au Tue Mar 4 19:02:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 05 Mar 2008 11:02:38 +1100 Subject: for-else References: Message-ID: <87r6eq82ch.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > But then this article: > http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel_language_features > has shown me that my problems with the 'else' of the 'for' mostly > come from just its bad naming. The converge language is yet another > very Python-like language, and it uses a better naming (the word > "exhausted" is long and has a complex spelling for non-English > speakers, so it's not perfect): > > for ...: > ... > exhausted: > ... > broken: > ... Rather than adding new keywords, I think the above would be better spelled using the exception keywords:: for foo in bar_sequence: # normal iteration spam(foo) if funky(foo): break except StopIteration, exc: # the iterator stopped normally eggs(exc) else: # the iterator exited abnormally, i.e. 'break' sausage() finally: # always executed, even on 'break' beans() -- \ ?[T]he question of whether machines can think [...] is about as | `\ relevant as the question of whether submarines can swim.? | _o__) ?Edsger W. Dijkstra | Ben Finney From python at rgbaz.eu Thu Mar 20 05:26:22 2008 From: python at rgbaz.eu (Python.Arno) Date: Thu, 20 Mar 2008 10:26:22 +0100 Subject: Calling Mac programs from Python instead of from AppleScript In-Reply-To: References: Message-ID: <8BB9867E-36A1-4B6A-9B8A-BB41A66D19FA@rgbaz.eu> On 19 mrt 2008, at 20:41, dvschorre at sbcglobal.net wrote: > > When I'm running Script Editor, I can get Maya to draw a sphere by > typing: > > tell application "Maya" > execute "sphere" > end tell > > When I try this using Python, I get this error message: > > IDLE 1.2.2 >>>> app('Maya').execute('sphere') > > Traceback (most recent call last): > File "", line 1, in > app('Maya').execute('sphere') > NameError: name 'app' is not defined >>>> > > Maybe I need to load some libraries first. > I never used applescript more than to record some clicks but you might try tell application "/Applications/Autodesk/maya2008/Maya" (replace maya2008 with you app's foldername) or even tell application "/Applications/Autodeks/maya2008/Maya/Contents/MacOS/ Maya" > Please help me to get started. > like any other VFX app, maya is also adding python libs you can access MEL commands from a python library: http://www.autodesk.com/us/maya/docs/Maya85/wwhelp/wwhimpl/common/html/wwhelp.htm?context=DeveloperResources&file=Introduction_to_Maya_Python_API.html > Thanks > Dewey V. Schorre > gr Arno Beekman From nagle at animats.com Tue Mar 25 00:17:16 2008 From: nagle at animats.com (John Nagle) Date: Mon, 24 Mar 2008 21:17:16 -0700 Subject: "Soup Strainer" for ElementSoup? In-Reply-To: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> Message-ID: <47e87a88$0$36376$742ec2ed@news.sonic.net> erikcw wrote: > Hi all, > > I was reading in the Beautiful Soup documentation that you should use > a "Soup Strainer" object to keep memory usage down. > > Since I'm already using Element Tree elsewhere in the project, I > figured it would make sense to use ElementSoup to keep the api > consistent. (and cElementTree should be faster right??). > > I can't seem to figure out how to pass ElementSoup a "soup strainer" > though. > > Any ideas? > > Also - do I need to use the extract() method with ElementSoup like I > do with Beautiful Soup to keep garbage collection working? > > Thanks! > Erik I really should get my version of BeautifulSoup merged back into the mainstream. I have one that's been modified to use weak pointers for all "up" and "left" links, which makes the graph cycle free. So the memory is recovered by reference count update as soon as you let go of the head of the tree. That helps with the garbage problem. What are you parsing? If you're parsing well-formed XML, BeautifulSoup is overkill. If you're parsing real-world HTML, ElementTree is too brittle. John Nagle From martin at v.loewis.de Fri Mar 21 17:01:07 2008 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 22:01:07 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E42213.50208@v.loewis.de> > eval() somehow decoded the passed expression. No question. It did not > use 'ascii', nor 'latin2' but something else. Why is that? Why there is > a particular encoding hard coded into eval? Which is that encoding? (I > could not decide which one, since '\xdb' will be the same in latin1, > latin3, latin4 and probably many others.) I think in all your examples, you pass a Unicode string to eval, not a byte string. In that case, it will encode the string as UTF-8, and then parse the resulting byte string. Regards, Martin From debl2NoSpam at verizon.net Sun Mar 2 20:49:03 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Mon, 03 Mar 2008 01:49:03 GMT Subject: Book Recomendations In-Reply-To: References: Message-ID: Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira Different people have different learning styles. Two books I like are Wesley Chun's Core Python Programming (2nd edition) and Mangnus Hetland's Beginning Python. Have fun with Python. I discovered it about 7 years ago, use it by choice for my intermittent programming requirements and find it a pleasure to use. Also this group is very helpful. (My programming experience also goes back to Algol, Basic and assembler circa 1965. Which makes me middle aged, but not necessarily experienced :) ) David From andrei.avk at gmail.com Sat Mar 15 17:25:21 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Sat, 15 Mar 2008 14:25:21 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> Message-ID: <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> On Mar 15, 3:54?pm, Unknown wrote: > Hi, > I've got this code : > > cb = open("testfile", "r+") > f = cb.readlines() > for line in f: > ? ? rx = re.match(r'^\s*(\d+).*', line) > ? ? if not rx: > ? ? ? ? continue > ? ? else: > ? ? ? ? serial = rx.group(1) > ? ? ? ? now = time.time() > ? ? ? ? today = time.strftime('%Y%m%d00', time.localtime(now)) > ? ? ? ? todayVal, serialVal = long(today), long(serial) > ? ? ? ? if todayVal <= serialVal: > ? ? ? ? ? ? todayVal = serialVal + 1 > ? ? ? ? else: > ? ? ? ? ? ? todayVal += 1 > ? ? ? ? line = string.replace(line, serial, "%d" %todayVal) > ? ? ? ? cb.write(line + "\n") > ? ? ? ? print 'Updated serial from "%s" to "%d"' % ( serial, todayVal ) > ? ? ? ? break ? ? ? > cb.close() > > I was expecting to replace the old value (serial) with the new one > (todayVal). Instead, this code *adds* another line below the one found... > > How can I just replace it? > > Thanks for your help :-) What you want to do is either 1. load everything up into a string, replace text, close file, reopen it with 'w' flag, write string to it. OR if file is too big, you can read each line, replace, write to a temp file, then when done move the file over the old one. I think there are technical reasons why file-reading and iteration api are not very suitable for reading and writing at the same time. I think you'd have to set the filepointer back one line (it can be manipulated by giving it bytes ahead/back, so that would be difficult in itself), then delete the line and then write new string. It may be even harder than that, I'm sure someone can explain this much better, but you're far better off with using one of the 2 methods above.. HTH, -ak From gandalf at shopzeus.com Fri Mar 28 11:03:39 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 28 Mar 2008 16:03:39 +0100 Subject: How do I reconnect a disconnected socket? In-Reply-To: References: Message-ID: <47ED08CB.9010809@shopzeus.com> > This is what I've got right now: > > #! /usr/bin/env python > import socket, string > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > def doconn(): > sock.connect(("localhost", 1234)) > def dodiscon(): > sock.close() > doconn() > > doconn() > > while (1): > buffer = sock.recv(1024) > if not buffer: > dodiscon() > sock.recv(1024) can return zero bytes of data indicating that no data arrived yet. It does not mean that you have been disconnected. This is especially true when you do nothing but recv, recv, recv() in an infinite loop. I recommend that you use select.select to see if there is some data that can be read. Call socket.recv() only when you know that it will not fail. Best, Laszlo From xelapond at gmail.com Mon Mar 31 14:49:21 2008 From: xelapond at gmail.com (Alex Teiche) Date: Mon, 31 Mar 2008 11:49:21 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> Message-ID: On Mar 30, 3:50 pm, Benjamin wrote: > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > I am pretty new to Python, and have never learned C++. I am trying to > > implement the following thing into my python application: > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > it, but I could not get this specific thing to work. Can someone give > > me some hints as to get it working in Python? > > What problems are you having? > > > > > Thanks a ton, > > > Alex Thanks everyone for your help. I found the example to be particularly helpful, and I have made a simplified version just to display an icon with a quit button in its menu. Once I know how to do that I will incorporate it into my larger program, with more options and the ability show messages. The problem is, it doesn't work, and I can't find out what's wrong. Can you give me some hints? Here is the code: import sys from PyQt4 import QtGui, QtCore class trayIcon(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #********Create Actions for the Tray Menu********# self.quitAction = QtGui.QAction(self.tr("&Quit"), self) QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) create_tray_icon() self.composeAction.setEnabled(visible) QtGui.QWidget.setVisible(self, visible) self.trayIcon.show() def create_tray_icon(self): self.trayIconMenu = QtGui.QMenu(self) self.trayIconMenu.addAction(self.composeAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) self.trayIcon.setIcon(bad.svg) app = QtGui.QApplication(sys.argv) sys.exit(app.exec_()) From zjs2k at yahoo.com Tue Mar 25 20:59:04 2008 From: zjs2k at yahoo.com (Jinshi) Date: Tue, 25 Mar 2008 20:59:04 -0400 Subject: urllib2.urlopen gives error 10060 Message-ID: Hello, everyone, I am quite new to python and I don't know how to solve this problem. I hope someone can help me. I just did a test in python shell: >>> import urllib2 >>> urllib2.urlopen("http://python.org") Traceback (most recent call last): File "c:\Zope\", line 1, in ? File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 130, in urlopen return _opener.open(url, data) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 376, in _open '_open', req) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 996, in do_open raise URLError(err) URLError: I am using Windows XP and the python was installed along with a zope installation. I can get on internet with Firefox browser without any proxy setting. I can do the test successfully on another computer on the same home network. I just don't know what happens to this one. Can anyone help me to troubleshoot this? Any suggestion would be really appreciated. Jin From nanjundi at gmail.com Wed Mar 5 10:29:24 2008 From: nanjundi at gmail.com (Nanjundi) Date: Wed, 5 Mar 2008 07:29:24 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> Message-ID: <51f4bce3-8561-4149-9b3b-e436bbee8ee7@u69g2000hse.googlegroups.com> On Mar 4, 3:13 pm, Mensanator wrote: > On Mar 4, 12:32 pm, Nanjundi wrote: > > > > Does seeding ( random.seed ) random with time fix this? It should. > > I suppose that depends on how long it takes factorint() to > process a number. If the seed is reset before the next clock > tick, you will get the same random numbers as the previous > iteration. Alright, then make it constant and don't worry about the clock tick. >>> for i in xrange(10): ... f1 = random.choice(f) ... print f1, ... f2 = random.choice(f) ... print f2, ... C = f1*f2 ... ff = None ... ff = sympy.factorint(C) ... print ff ... random.seed(i) ... 5573 5171 [(5171, 1), (5573, 1)] 8537 7673 [(7673, 1), (8537, 1)] 2063 8573 [(2063, 1), (8573, 1)] 9551 9473 [(9473, 1), (9551, 1)] 2909 5659 [(2909, 1), (5659, 1)] 2897 1789 [(1789, 1), (2897, 1)] 6361 7541 [(6361, 1), (7541, 1)] 8017 8293 [(8017, 1), (8293, 1)] 3671 2207 [(2207, 1), (3671, 1)] 2803 9629 [(2803, 1), (9629, 1)] > Frankly, I don't understand why factorint() reseeds at all. Read the doc: * The rho algorithm is a Monte Carlo method whose outcome can be affected by changing the random seed value. * > Doesn't Random automatically initialize the seed? > Doesn't constantly reseeding degrade the performance of the > random number generator? With Robert Kern's patch, the reseeding > is no longer a constant, fixing the immediate symptom. Does it matter? The factorint reseeds using a constant seed (1234). > > But what if _I_ wanted to make a repeatable sequence for test > purposes? Wouldn't factorint() destroy my attempt by reseeding > on every call? Repeatable sequence? save it and reuse! Think about "What if"s doesn't get any work done. -N From gherron at islandtraining.com Fri Mar 28 16:29:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 28 Mar 2008 13:29:40 -0700 Subject: Astronomy Fits format and gif.save(path) In-Reply-To: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> References: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> Message-ID: <47ED5534.6020001@islandtraining.com> W. Watson wrote: > In what library would I find gif.save(path), where path is the name and path > of a file, and the method would produce a file in a gif format? > > Is there a fits.save(path) somewhere? fits is commonly used in astronomical > work. > You may want to install PIL (the Python Image Library) for this: http://www.pythonware.com/products/pil/ From jn.nntp.scrap001 at wingsandbeaks.org.uk Sat Mar 1 12:29:21 2008 From: jn.nntp.scrap001 at wingsandbeaks.org.uk (Jeremy Nicoll - news posts) Date: Sat, 1 Mar 2008 17:29:21 +0000 Subject: Import, how to change sys.path on Windows, and module naming? Message-ID: If I understand correctly, when I import something under Windows, Python searches the directory that the executing script was loaded from, then other directories as specified in "sys.path". I assume there are standard locations inside my installed Python - in my case inside: C:\Program Files\~P-folder\Python25 - where I could put my modules and they'd automatically be found? But even if that's the norm, I don't want to put my own modules in such directories, partly because a uninstall or reinstall or upgrade of Python might lose my stuff, and partly because I don't believe in mixing distributed code with home-grown code. However I'm quite happy to have a line or three of code to alter sys.path to suit my set-up, if that's a normal way to handle this problem. Where does one do that? Also, I presume that there's a risk that the module name that I give to any of my utilities will clash with a present or future standard module's name. Does that mean that I should give my own modules names like "JNfoo" rather than "foo", etc? Or something like "JNutils.foo"? -- Jeremy C B Nicoll - my opinions are my own. From python.list at tim.thechases.com Wed Mar 26 14:46:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 26 Mar 2008 13:46:06 -0500 Subject: what does ^ do in python In-Reply-To: References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <47EA99EE.5030304@tim.thechases.com> >> HOw can we use express pointers as in C or python? > > Traceback (most recent call last): > File "", line 1, in > File "parser.py", line 123, in parse_text > tree = language.parse_text(text) > File "english.py", line 456, in parse_text > tree = self.parse_sentence(sentence) > File "english.py", line 345, in parse_sentence > raise ParserError, "can't parse %r" % sentence > ParserError: can't parse 'HOw can we use express pointers as in C or > python?' Possible "express pointers": http://www.geocities.com/derwin_b/sr91sign.jpg http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg If those meet the OP's need, I recommend urllib2 and PIL. -tkc From bj_666 at gmx.net Mon Mar 24 03:05:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Mar 2008 07:05:34 GMT Subject: Multiline CSV export to Excel produces unrecognized characters? References: <4f6f122f-45bb-4aa5-b9c9-5eb3e84a0964@i7g2000prf.googlegroups.com> Message-ID: <64p25uF2c2qidU2@mid.uni-berlin.de> On Sun, 23 Mar 2008 23:30:11 -0700, felciano wrote: > The following reproduces the problem in python 2.5: > > import csv > row = [1,"hello","this is\na multiline\ntext field"] > writer = csv.writer(open("test.tsv", "w"), dialect="excel-tab", > quotechar='"') > writer.writerow(row) > > When opening the resulting test.tsv file, I do indeed see a cell with > a multi-line value, but there is a small boxed question mark at the > end of each of the lines, as if Excel didn't recognize the linebreak. > > Any idea why these are there or how to get rid of them? Any chance you are doing this on Windows and Excel doesn't like the return+linefeed line endings that Windows produces when writing files in text mode? Try 'wb' as mode for the output file. Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Sat Mar 8 15:27:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:14 -0800 (PST) Subject: for-else References: Message-ID: > The idea of the if-else is: > . ?depending on some condition either do this or do something else, > . ?don't do them both. yes = the loop completed. 'else' isn't rechecking a piece of the loop, it's checking the loop. Does it test successfully--- not the loop condition, the loop? What is 'if a loop'? Make sense, I hold it does. (Holding is good-- something I can drop and give to someone else.) If 'else' gets hit, I didn't do the loop. From gagsl-py2 at yahoo.com.ar Mon Mar 17 08:48:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 10:48:40 -0200 Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > i have a problem with this modules py2exe + pywinauto + sendkeys used > together. > > In my script i'm using this expression > app.window_(title="SJphone").Edit.TypeKeys("Test is > running",with_spaces=True) > > TypeKeys is using SendKeys module i suppose. Does it work as a normal script, without using py2exe? > my setup.py looks like that: > > from distutils.core import setup > import py2exe > > setup( > options = {"py2exe": {"compressed": 1, > "optimize": 0, > "bundle_files": 1, > "packages": ["encodings", "pywinauto", > "pywinauto.controls", "pywinauto.tests"] } }, > zipfile = None, > console=["hosts.py"] > ) Perhaps you have to include SendKeys explicitely. I think pywinauto doesn't require SendKeys, but uses it if already installed. -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 20 17:37:46 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 16:37:46 -0500 Subject: Code folder with Emacs In-Reply-To: <13u5li6kspler51@corp.supernews.com> References: <13u5li6kspler51@corp.supernews.com> Message-ID: I don't use emucks, but in vim its very simple. :set foldmethod=indent and instantly anything indented (ie: all python blocks) are folded. to unfold a fold zo to close an opened fold zc that outta be enough to get any fellow vim-heads going =) 2008/3/20, Grant Edwards : > > Has anybody figured out how to do code folding of Python source > files in emacs? > > I tried "hide-show" minor mode, but it doesn't really work for > Python code: the only think it knows how to hide/show are > function bodies. It can't do normal things like hide/show a > code block like it can for other languages. > > Google also found my "folding mode", but that's based on > user-inserted tokens and isn't syntax aware. > > -- > Grant > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Mar 21 16:56:43 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 21 Mar 2008 21:56:43 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <47E4210B.1080505@v.loewis.de> > Well at least this is what I think. If I'm not right then please explain > why. I think your confusion comes from the use of the interactive mode. PEP 263 doesn't really apply to the interactive mode, hence the behavior in interactive mode is undefined, and may and will change across Python versions. Ideally, interactive mode should assume the terminal's encoding for source code, but that has not been implemented. Regards, Martin From kf9150 at gmail.com Mon Mar 31 18:12:16 2008 From: kf9150 at gmail.com (Kelie) Date: Mon, 31 Mar 2008 15:12:16 -0700 (PDT) Subject: PyQt - How to prevent a dialog being resized? Message-ID: Hello, My question is as subject. I tried something like this and it doesn't work. def resizeEvent(self, event): self.size = event.oldSize() Any hint? Thank you. From apardon at forel.vub.ac.be Thu Mar 13 04:22:20 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Mar 2008 08:22:20 GMT Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: On 2008-02-28, Steven D'Aprano wrote: > On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: > >> Hi! >> Can somebody of you make me a sample how to define a function based on >> "call by reference" ??? > > Python doesn't do call by reference. Nor does it do call by value. Please > pay no attention to anyone who says it does. Whatever python has for a calling convention, it is close enough that naming it "call by reference" gives people a reasonable idea of what is going on. > Instead, read this: > > http://effbot.org/zone/call-by-object.htm Which IMO isn't very helpfull. The mentioning of e.g. mutable just confuses things since it really isn't the issue. AFAICS people don't have a problem with understanding the calling convention of python. They have a problem understanding the assignment semantics. It is just that these problems of understanding most often surface when an assignment is made to a parameter which makes them think they don't understand the calling convention. The important thing to understand is that an assigment in python is not copying the contends into the variable but is passing a reference/binding the name to a new object. After the variable is assigned to it doesn't refer to the same object with a new contend. It refers to a different object. -- Antoon Pardon From michael.pearmain at tangozebra.com Mon Mar 3 04:43:32 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 3 Mar 2008 01:43:32 -0800 (PST) Subject: Regex loop question Message-ID: <7aae0102-51bd-4701-a116-60b8d9698450@s13g2000prd.googlegroups.com> Hi Experts, I've written a peice of code that works fine and fits, and passes values into a peice of SPSS code, the problem is that it is not dynamic, and so i though about how i can make it dynamic, (other code may not have upto 10 some may have more) and came up with regex for an idea, but i can't seem to make it work, can anyone offer any advice? Below is current working code time_variables = {"ActivityTime": "Activity_Time", "ExposureTime_Last":"Exposure_Time_1", "ExposureTime_Last2":"Exposure_Time_2", "ExposureTime_Last3":"Exposure_Time_3", "ExposureTime_Last4":"Exposure_Time_4", "ExposureTime_Last5":"Exposure_Time_5", "ExposureTime_Last6":"Exposure_Time_6", "ExposureTime_Last7":"Exposure_Time_7", "ExposureTime_Last8":"Exposure_Time_8", "ExposureTime_Last9":"Exposure_Time_9", "ExposureTime_Last10":"Exposure_Time_10"} for Var in time_variables.keys(): time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . COMPUTE %s = number(%s, TIME8). VARIABLE LABEL %s. VARIABLE LEVEL %s (SCALE). FORMATS %s (TIME8). VARIABLE WIDTH %s (8). EXECUTE.""") %(Var, Var, Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var]) spss.Submit(time_manips) Now to make it dynamic i've gone for the following... reg_time = re.compile("^ExposureTime_Last([0-9]*)$") reg_Activity = re.compile("^ActivityTime") for Var in time_variables.keys(): if reg_time.match(Var): match = reg_time.match(Var) E_time = "Exposure_Time_%s" % match.groups()[0] else: match = reg_time.match(Var) match.groups()[0] = "Activity_Time" time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . COMPUTE %s = number(%s, TIME8). VARIABLE LABEL %s. VARIABLE LEVEL %s (SCALE). FORMATS %s (TIME8). VARIABLE WIDTH %s (8). EXECUTE.""") %(Var, Var, Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var]) print(time_manips) All help welcome, or if a different approach is better please let me know Mike From steve at REMOVE-THIS-cybersource.com.au Tue Mar 11 13:50:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 11 Mar 2008 17:50:36 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> Message-ID: <13tdhjcd2fhp17d@corp.supernews.com> On Tue, 11 Mar 2008 03:14:54 -0700, Lie wrote: >> Regarding the number of callbacks: you can as well pass an object that >> has several methods to call. > > If you passed an object that has several methods to call (using tuple or > list) and you want to handle several softexceptions and ignore some > others, you must still pass an empty methods to the one you want to > ignore, cluttering the caller's code by significant degree: > > def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, > DO_NOTHING)): > if a == 0: raise callback(0) > try: > a += b > except ZeroDivisionError: > raise callback(1) > if a <= 0: raise callback(2) > raise callback(3) > return a > > somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, > DO_NOTHING)) Yes, you are right that this is a bad idea. But it is a bad idea regardless of whether you use callbacks or SoftExceptions. In your example above, you seem to have accidentally written "raise callback" when you (probably) meant to just call the callback. That's significant because it shows that replacing the callback is still just as cluttered, and still puts a large burden on somefunc() to perform every test that callers might want to perform. This is a bad idea because you are tightly coupling somefunc() to the specific needs of some arbitrary callers. You should aim to have loose coupling between functions, not tight. Tight coupling should be avoided, not encouraged. In most circumstances, the right place to put the various tests is in the caller, not in somefunc(). -- Steven From furkankuru at gmail.com Tue Mar 25 19:45:29 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 01:45:29 +0200 Subject: Filtering a Python list to uniques In-Reply-To: References: Message-ID: <3a4a8f930803251645g1aed792bv5f0bceaaf2bc650e@mail.gmail.com> set(lstone) works fine in python 2.5.1 Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] >>> set(lstone) set([1, 2, 3, 4, 5, 6]) On 3/26/08, kellygreer1 wrote: > > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > Is there a page on this in the Python in a Nutshell or the Python > Cookbook? > Did I miss something? > > Kelly Greer > kellygreer1 at nospam.com > change nospam to yahoo > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From bronger at physik.rwth-aachen.de Wed Mar 19 04:44:06 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 19 Mar 2008 09:44:06 +0100 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> Message-ID: <87fxunumqx.fsf@physik.rwth-aachen.de> Hall?chen! Paul Rubin writes: > [...] > > Re Haskell: I've been spending a lot of time on Haskell recently, > though I haven't done anything nontrivial with it yet (just some > small stuff). But I think it's better for complex program > development than Python is, Could you elaborate on this? (Sincere question; I have almost no idea of Haskell.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From fetchinson at googlemail.com Mon Mar 10 02:32:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 9 Mar 2008 23:32:39 -0700 Subject: image matching algorithms Message-ID: Hi all, There are a number of free tools for image matching but it's not very easy to decipher the actual algorithm from the code that includes db management, GUI, etc, etc. I have my own image database and GUI so all I need is the actual algorithm preferably in pseudo code and not in the form of a research paper (from which I also found a lot but since I'm not that much interested in the actual science of image recognition this seems like an over kill). My understanding of image matching is that it works by first calculating N real numbers for an image and defining a metric for pairs of N-tuples. Images are similar if their distance (defined by the metric) is small. The various free tools differ by their chosen optimization paths and their degree of specialization. My preference would be, 1. Doesn't really matter how long it takes to compute the N numbers per image 2. Lookups should be fast, consequently N should not be too large (I guess) 3. It should be a generic algorithm working on generic images (everyday photos) 4. PIL should be enough for the implementation So if anyone knows of a good resource that is close to being pseudo code I would be very grateful! Cheers, Daniel From __peter__ at web.de Thu Mar 27 05:01:39 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Mar 2008 10:01:39 +0100 Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: Grimsqueaker wrote: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? With Dan's functions in cartesian.py you can do the following: >>> from cartesian import * >>> def count(digits): ... args = [] ... while 1: ... args.append(digits) ... for n in string_cartesian_product(*args): ... yield n ... >>> from itertools import islice >>> print " ".join(islice(count("abc"), 30)) a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc Peter From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:09:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:09:32 -0300 Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo escribi?: > I'm using a md5 hash encoded with base64.urlsafe_b64encode as a > parameter of a URL used to confirm a registration in a site. It has > been working great. > > The url is like this: > > http://example.com/ce?i=878&h=kTfWSUaby5sBu9bIfoR87Q== > > Now i need to match that URL in a certain text and i realized that > urlsafe_b64encode uses the "=" character so i can't just use \w{24} to > match the parameter. > > What i need to know is where can an equal char appear in a > urlsafe_b64encoded string?: > > a)only at end; > b)both at the end and at the begginig; > c)anywhere in the string; > > A sure answer will make my regexp safer. Only at the end. The encoded string has 4*n chars when the input string has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has 4*(n+1) chars right padded with 2 or 1 "=" chars. If your input has 3n chars, the output won't have any "=" > In another point, does the "=" char make it urlunsafe? I guess not > because i believe it would only be unsafe if the equal appeared like > in "&var=" and since there are no "&" in the string than there is no > problem right? Or wrong? I guess not, but you should check the relevant RFCs. Or at least check that your server can always parse the request. -- Gabriel Genellina From mail at timgolden.me.uk Thu Mar 27 07:22:18 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 11:22:18 +0000 Subject: Problem with write binary data to OLE field in Access In-Reply-To: <47EA77FB.3080706@gmail.com> References: <47EA77FB.3080706@gmail.com> Message-ID: <47EB836A.3010506@timgolden.me.uk> lialie wrote: [... snip slightly confused indication that reading back a binary item using GetChunk appears to double its length ...] Well I don't know why this should be happening, but I do at least have a few suggestions: 1) Try using ADODB.Stream instead of GetChunk etc. 2) Try using the adodbapi dbapi-compliant wrapper 3) Try using ODBC (via PyODBC, CeODBC etc.) I've no idea if any of these will do any better but at least it gives you some possibilities :) TJG From frank at chagford.com Wed Mar 12 01:10:54 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 11 Mar 2008 22:10:54 -0700 (PDT) Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: <76ce374e-fa63-4885-8198-d2b383696a48@s8g2000prg.googlegroups.com> gargonx wrote: > Say i have the two methods: > > def ReturnMethod(request, x): > if request is True: > return x > else: print "No String for you...False!" > > def SendMethod(request): > xstring = "Some text" > ReturnMethod(request, xstring) > > SendMethod(True) > > Why does ReturnMethod not return the string x? I do believe it is > returning with a NoneType. > Any help would be greatly obliged > > Thanks, Josh ReturnMethod() is executed, but you do nothing with the result. Try one of the following - def SendMethod(request): xstring = "Some text" print ReturnMethod(request, xstring) def SendMethod(request): xstring = "Some text" return ReturnMethod(request, xstring) HTH Frank Millman From dotancohen at gmail.com Thu Mar 13 19:19:11 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 14 Mar 2008 01:19:11 +0200 Subject: This actually works. In-Reply-To: <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> Message-ID: <880dece00803131619l8df9a07w365d482d2af7090a@mail.gmail.com> On 14/03/2008, Dustan wrote: > you.screw() Ah, you are pushing sex pills. > self.thank(God, encapsulation) And bibles? Interesting combination. > not self.want_to_know(you.screw.func_code) Unsubscribe? I know better... Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From fuzzyman at gmail.com Sat Mar 29 16:34:27 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 29 Mar 2008 13:34:27 -0700 (PDT) Subject: Buffer Overflow with Python 2.5 on Vista in import site Message-ID: A very odd error with Python 2.5 (both 2.5.1 and 2.5.2 from the official msi installers and running on Vista under Parallels on the Mac). 'import site' fails due to a string in sys.path that contains a huge number of null bytes. The error is actually in ntpath - I adjusted it to print the paths it is working with and a string on encountering the bad path. Because 'import site' is executed twice with the following code I snipped the first dump and only print the one with the traceback: C:\Users\Administrator>python -c "import site" [snip] 'import site' failed; use -v for traceback set(['c:\\python25\\lib\\plat-win', 'c:\\windows\\system32\ \python25.zip', 'c:\\ python25', 'c:\\python25\\lib\\lib-tk', 'c:\\users\\administrator', 'c: \\python2 5\\dlls', 'c:\\python25\\lib', 'c:\\python25\\lib\\site-packages']) ******************** BAD PATH ******************** "C:\\Python25\\lib\\site-packages\\\x00\x05\x16\x07\x00\x02\x00\x00Mac OS X \x00\x02\x00\x00\x00\t\x00\x00\x002\x00\x00\x0e \xb0\x00\x00\x00\x02\x00\x00\x 0e\xe2\x00\x00\x01\x1e \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00AT TR\x00\x00\x00!\x00\x00\x0e\xe2\x00\x00\x00\x98\x00\x00\x00 \x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x98\x00\x00\x00 \x00\x0 0\x15com.macromates.caret\x00x\x9c\xab\xe6R\x00\x82\xe4\xfc\x9c \xd2\xdc<\x05[\x0 5\x03k0?'3/\x15\xc2\xab\x05\x00\x8b\x99\x08\x1d \x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ [snip a load of null bytes] x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x1eThis resource fork intent ionally left blank \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 [snip a load more null bytes] 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x1e \x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x1c\x00\x1e\xff\xff" Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\site.py", line 417, in main() File "C:\Python25\lib\site.py", line 402, in main paths_in_sys = addsitepackages(paths_in_sys) File "C:\Python25\lib\site.py", line 206, in addsitepackages addsitedir(sitedir, known_paths) File "C:\Python25\lib\site.py", line 169, in addsitedir addpackage(sitedir, name, known_paths) File "C:\Python25\lib\site.py", line 141, in addpackage dir, dircase = makepath(sitedir, line) File "C:\Python25\lib\site.py", line 67, in makepath dir = os.path.abspath(os.path.join(*paths)) File "C:\Python25\lib\ntpath.py", line 500, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str Odd. Anyone got any clues? Michael Foord http://www.ironpythoninaction.com From Robert.Bossy at jouy.inra.fr Wed Mar 12 09:44:17 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 12 Mar 2008 14:44:17 +0100 Subject: Creating a file with $SIZE In-Reply-To: <47D7D5F2.8050303@mattnordhoff.com> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> Message-ID: <47D7DE31.9090504@jouy.inra.fr> Matt Nordhoff wrote: > Robert Bossy wrote: > >> k.i.n.g. wrote: >> >>> I think I am not clear with my question, I am sorry. Here goes the >>> exact requirement. >>> >>> We use dd command in Linux to create a file with of required size. In >>> similar way, on windows I would like to use python to take the size of >>> the file( 50MB, 1GB ) as input from user and create a uncompressed >>> file of the size given by the user. >>> >>> ex: If user input is 50M, script should create 50Mb of blank or empty >>> file >>> >>> >> def make_blank_file(path, size): >> f = open(path, 'w') >> f.seek(size - 1) >> f.write('\0') >> f.close() >> >> I'm not sure the f.seek() trick will work on all platforms, so you can: >> >> def make_blank_file(path, size): >> f = open(path, 'w') >> f.write('\0' * size) >> f.close() >> > > I point out that a 1 GB string is probably not a good idea. > > def make_blank_file(path, size): > chunksize = 10485760 # 10 MB > chunk = '\0' * chunksize > left = size > fh = open(path, 'wb') > while left > chunksize: > fh.write(chunk) > left -= chunksize > if left > 0: > fh.write('\0' * left) > fh.close() > Indeed! Maybe the best choice for chunksize would be the file's buffer size... I won't search the doc how to get the file's buffer size because I'm too cool to use that function and prefer the seek() option since it's lighning fast regardless the size of the file and it takes near to zero memory. Cheers, RB From morse at edoug.org Fri Mar 14 06:17:13 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 14 Mar 2008 10:17:13 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Harald, Great suggestion, thanks! Unfortunately, "no help there". Adding "import multiarray" to Precision.py where you suggested (i.e., before the "from multiarray import zeros" line) did not fix the problem. I'm getting the same exception and traceback as before except, of course, on line 19 now instead of line 18. Doug On Thu, 13 Mar 2008 11:46:41 -0700 (PDT), GHUM wrote: > Doug, > > > Precision.py is part of the Numeric package. AFAIKT, the problem is during > > the module initialization. The first lines of Precision.py are: > > > > from multiarray import zeros > > import string > > > [.....] > and your program is crashing on the > > lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 > > line... Please, try the following: > > import multiarray > from multiarray import zeros > import string > > (adding the line "import multiarray" before zeros are imported from > it) > > I used this workaround with various packages I py2exed - maybe it also > works for you? > > please keep us updated, > > Harald From samuel.progin at gmail.com Mon Mar 10 11:39:21 2008 From: samuel.progin at gmail.com (Sam) Date: Mon, 10 Mar 2008 08:39:21 -0700 (PDT) Subject: defining a method that could be used as instance or static method Message-ID: Hello I would like to implement some kind of comparator, that could be called as instance method, or static method. Here is a trivial pseudo code of what I would like to execute >> class MyClass: ... def __init__(self, value): ... self.value = value ... def comp(self, compValue): ... return self.value == compValue.value >> a = MyClass(3) >> b = MyClass(4) >> c = MyClass(3) >> a.comp(b) False >> a.comp(c) True This is actually achieved by MyClass, how could implement it in order to accept: >> MyClass.comp(a, b) False I would really appreciate a pointer or a way to complete MyClass in order to fulfill my requirements. Thank you for your attention. Sam From aboudouvas at panafonet.gr Fri Mar 28 05:35:02 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 28 Mar 2008 02:35:02 -0700 (PDT) Subject: Eclipse and PyDev Package explorer Message-ID: <1d4e6f2b-a058-413e-a566-674ccc733d6f@s19g2000prg.googlegroups.com> Hi, i am trying to "fit" Eclipse/Pydev in my needs/preference, so i want to ask this: As it is now, i see all my projects in that TreeView (PyDev Package Explorer). I would rather want this to behave like a more "normal" IDE where you Open one project and if you want close it and Open another, just one at a time and not a TreeView with ALL your projects loaded in every time you open the IDE. Is there a way to accomplish thiks in Eclipse/Pydev ?? From deets at nospam.web.de Mon Mar 3 13:49:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Mar 2008 19:49:20 +0100 Subject: Inheritance issue... In-Reply-To: References: Message-ID: <632vhiF262j15U1@mid.uni-berlin.de> MooMaster schrieb: > I'm trying to use inheritance to create a simple binary tree, but it's > not going so well... here's what I pull from the documentation for > super() > "super( type[, object-or-type]) > > Return the superclass of type. If the second argument is omitted the > super object returned is unbound. If the second argument is an object, > isinstance(obj, type) must be true. If the second argument is a type, > issubclass(type2, type) must be true. super() only works for new-style > classes. The last sentence contains the important bit. You need to use new-style-classes, which means they have to have the ancestor "object" somewhere in their inheritance-graph. Like this: class Foo(object): pass Certainly one of the somewhat uglier corners of Python... Diez From sjmachin at lexicon.net Fri Mar 7 16:29:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 13:29:49 -0800 (PST) Subject: I cannot evaluate this statement... References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <57e0ebcf-5d2f-4a27-b141-25fd02513ead@i12g2000prf.googlegroups.com> On Mar 8, 7:38 am, waltbrad wrote: > The script comes from Mark Lutz's Programming Python. It is the > second line of a script that will launch a python program on any > platform. > > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > That makes sense. Because the first condition is true and 'python.exe' > is true. So the next comparison is 'python.exe' or 'python' Well, > python.exe is true. So that value is returned to pyfile. > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. The next comparison is NOT ('False' or 'python'); it is (False or 'python'). 'False' is NOT false, 'False' (like any string of non-zero length) is true. (trueobject and expression) evaluates to the value of expression. (falseobject and expression) evaluates to falseobject [and doesn't evaluate expression]. (trueobject or expression) evaluates to trueobject [and doesn't evaluate expression]. (falseobject or expression) evaluates to the value of expression. So: ('NOT-win' == 'win' and 'python.exe') or 'python' (False and 'python.exe') or 'python' False or 'python' 'python' > But, again, on linux pyfile evaluates to python.exe Does it? Have you tried it? > > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? From gherron at islandtraining.com Mon Mar 31 15:21:06 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 31 Mar 2008 12:21:06 -0700 Subject: Beginner advice In-Reply-To: <1206940981.6828.13.camel@paul-laptop> References: <1206940981.6828.13.camel@paul-laptop> Message-ID: <47F139A2.9000201@islandtraining.com> Paul Scott wrote: > I have been tasked to come up with an audio recorder desktop (cross > platform if possible - but linux only is OK) that: > > 1. records a lecture as an MP3 file (pymedia?) > 2. Provides a login form for server credentials > 3. Uploads via XMLRPC (pyxmlrpclib) to the server as a podcast > > I have been working on this (having never really worked with Python > before) for the past 24 hours or so, and would just like to get some > feedback on the direction that I am taking if possible. > > 1. Is pymedia an active project? Should I use something else? > Pymedia seems to have gone unmaintained for several years now. I'd suggest looking at AVbin http://code.google.com/p/avbin. It provides a nice interface to code that is *very* actively maintained. Even though I've not used it, it is maintained by someone who I do trust to do a good job. > 2. GUI design - I am using glade designer and pyGTK. Good choice? > > 3. pyXMLRPClib - active? Something better? > > 4. I see that there are literally thousands of somewhat external looking > libraries for python, I presume that there is some way of bundling all > the deps into a single source and then compiling? or otherwise packaging > them all (this software will be for academia, so difficult installs are > out!) > > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? > > Any help would be massively appreciated! Python looks like a *really* > easy and powerful language (hey, I managed to do a desktop application > in a few hours and I am a botanist!) and I would like to do a lot more > with it. I have a PHP background (taught myself that also) so C syntax > is almost like my native tongue :) but Python syntax seems just as easy, > if not easier! > > I am still going through Mark Pilgrims' tutorials (dive into ones) and > am slowly getting the hang of things, so if these questions seem inane, > please do excuse me and feel free to tell me to RTFM! > > Thanks > > --Paul > > > > ------------------------------------------------------------------------ > > All Email originating from UWC is covered by disclaimer > http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm > From gregory.bronner at lehman.com Tue Mar 11 16:51:58 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Tue, 11 Mar 2008 16:51:58 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list at python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinay_sajip at yahoo.co.uk Tue Mar 4 06:02:22 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 4 Mar 2008 03:02:22 -0800 (PST) Subject: Python logging: Retrieving the last log record from a handler References: Message-ID: On Mar 3, 11:41 am, Frank Aune wrote: > I will be fairly surprised if this functionality is not already built-in for > the defaultlogginghandlers, but so far I've been unable to figure out how > to pull it of without the custom loghandler above. Prepare to be surprised ;-) Except for the MemoryHandler, which is designed specifically as a buffer for logging events, the handlers in the logging package do not store the last record they processed. (Neither do loggers, filters or formatters, all of which get to see records as they are processed.) Best regards, Vinay Sajip From michael.wieher at gmail.com Mon Mar 17 16:15:28 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 15:15:28 -0500 Subject: struct unpack In-Reply-To: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> References: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> Message-ID: > > testValue = '\x02\x00' > junk = struct.unpack('h', testValue) #Works > > testValue = raw_input("Enter Binary Code..:") inputting at the > console '\x02\x00' > junk = struct.unpack('h', testValue) > > error: unpack requires a string argument of length 2 Well, it thinks the length of the testValue is longer than 2. Why not print out len(testValue) immediately after calling raw_input? maybe raw_input doesn't recognize hex-values automatically, while a string='\x??' is recognizable by the interpreter as such. obviously the issue is raw_input and how it handles input strings... how to fix? no idea =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Mar 30 08:12:18 2008 From: http (Paul Rubin) Date: 30 Mar 2008 05:12:18 -0700 Subject: License of Python References: Message-ID: <7xy7805s2l.fsf@ruckus.brouhaha.com> iu2 writes: > The problem is that including Python's license in the binary, which as > I understand is a must do, reveals that the appliation is based on Python. > > I'll appreciate your advices about this Expose Python as a user extension language, so it's obvious to everyone that Python is present. Just how present it is, you don't have to tell. From castironpi at gmail.com Tue Mar 25 10:34:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 07:34:41 -0700 (PDT) Subject: any good g.a.'s? Message-ID: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Any good genetic algorithms involving you-split, i-pick? "genetic algorithms involving you-split, i-pick" returned 6 results. So, people: From Dodin.Roman at gmail.com Thu Mar 20 10:09:01 2008 From: Dodin.Roman at gmail.com (hellt) Date: Thu, 20 Mar 2008 07:09:01 -0700 (PDT) Subject: Strange behavior of the Eclipse embedded console References: <23ab07a7-0355-48a7-8bf2-266a56f4efb9@h11g2000prf.googlegroups.com> Message-ID: On 20 ???, 14:31, hellt wrote: > i've faced with some strangeness while executing this sample: > > choice = raw_input("your choice: ") > print len(choice) > > when i run this sample in my eclipse console with CPython and print > Yes, i have this output > 4 #trailing \t is the fourth element > > but when i use command line method > python sample.py > i have the correct length = 3 > > i'm curious now, can anyone explain that? just took a look into PyDEV-FAQ. "The eclipse console is not an exact copy of a shell... one of the changes is that when you press in a shell, it may give you a \r, \n or \r\n as an end-line char, depending on your platform. Python does not expect this -- from the docs it says that it will remove the last \n (checked in version 2.4), but, in some platforms that will leave a \r there. This means that the raw_input() should usually be used as raw_input().replace('\r', ''), and input() should be changed for: eval(raw_input().replace('\r', ''))." From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 21:47:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 01:47:41 -0000 Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> Message-ID: <13u3ghthlh25sc0@corp.supernews.com> On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> This whole approach >> assumes that Windows does the sensible thing of returning a unique > error >> code when you try to open a file for reading that is already open for >> writing. >> >> > So how would you use a file to share data then? I see I was a little unclear. What I meant to say was that I assumed that Windows returned a specific error code of "file is busy" as opposed to "you don't have permission to access this file right now" without specifying whether this is a permanent permissions error or a temporary file busy error. > By default Python on Windows allows you to open a file for reading > unless you specify a sharing mode which prevents it: But the OP is talking about another process having opened the file for WRITING, not reading. It's that other process that has exclusive access, and the OP was trying to determine when it was safe to attempt opening the file according to whether or not it was still growing. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:36:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:36:36 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> Message-ID: <13t6c8kdis2gbb5@corp.supernews.com> On Sat, 08 Mar 2008 21:21:48 +0100, K Viltersten wrote: > Coming from C++/Java camp i can't help noticing that in most cases, when > i'm using a class written by somebody else, i don't want to see his/her > code. I only want to know WHAT the function does (is intended to be > doing, at least). > > I don't want to look at the source code (in some cases i can't even see > the code because it's compiled). I only care that when i execute > > SomeType obj = SomeType(); > obj.aggregate(); > > the object gets aggregated. How it's done will be up to the author. I'm > just a user of the product. > > Now, i'm getting the signal that it's done in a different way in Python. > Please elaborate. I'm very new to snakeology. I think even Grant would agree that when you call "help(make_widget)", you should see something like: make_widget(styleID, material) -> widget or raise ValueError on failure styleID: numeric ID or string name of the widget style material: WidgetMaterial instance or None to use default rather than: See source code for details. *wink* -- Steven From darcy at druid.net Fri Mar 7 11:58:38 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 7 Mar 2008 11:58:38 -0500 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: <20080307115838.7b686e83.darcy@druid.net> On Fri, 7 Mar 2008 17:31:35 +0100 "K Viltersten" wrote: > I've been recommended reading of: > http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i > need to get elaborated. > > > 1. When writing English, Strunk and > White apply. > > Where can i download it? Am i actually > expected to read the whole book? How > many people actually do aply it? "The Elements of Style" by William Strunk Jr. and E.B. White. The original, revised edition was published in 1935. The third edition is copyright 1979 and published by MacMillan Publishing Co., Inc., NY, NY. There may be a later version with an ISBN but this one doesn't have one. It's a very small book, 4-1/2" by 7", 81 pages. If you are writing English it is worth browsing from time to time. > 2. You should use two spaces after a > sentence-ending period. > > For heavens sake, why? I've always been > obstructed by the double blanks but > tolerated them. Now, that i read that > it actually is a recommendation, i need > to ask about the purpose. Like many things of this nature, the purpose is to follow the rules of correct English usage. -- 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 jr9445 at ATT.COM Wed Mar 12 11:38:12 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 12 Mar 2008 10:38:12 -0500 Subject: List Combinations In-Reply-To: <47D7E9A1.7000403@ncee.net> References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> <47D7E9A1.7000403@ncee.net> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Shane Geiger > Sent: Wednesday, March 12, 2008 10:33 AM > To: Michael Wieher > Cc: python-list at python.org > Subject: Re: List Combinations > > > > > > def gen(lists): > out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' > comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in > range(len(lists))]) > return eval('[ ' + out + comp + ' ]') > > a,b,c = [1,2,3],[4,5,6],[7,8,9] > > print gen([a, b, c]) > > > > > > -- > Shane Geiger > IT Director > National Council on Economic Education > sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net > It helps to quote your source... http://www.mail-archive.com/python-list at python.org/msg178457.html Start here http://www.mail-archive.com/python-list at python.org/msg178356.html and go through the thread. There are several ways to solve the problem and we evaluated the performance and 'pythonicity' of each. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625 From coolman.guron at gmail.com Fri Mar 7 01:16:42 2008 From: coolman.guron at gmail.com (coolman.guron at gmail.com) Date: Thu, 6 Mar 2008 22:16:42 -0800 (PST) Subject: help on file storage for split multi part download References: Message-ID: On Mar 7, 1:38 am, "Gabriel Genellina" wrote: > En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: > > > storage class which can write the file splits that are currently being > > downloaded to the disk. this is exactly what other download > > accelerators do, i guess. > > > can this be done using the python file class?? i am pretty good at > > handling file uploads (at server end) this is the first time i have to > > think the other way round. > > Uh, unless I misundersand you, a standard file object is enough. First > create a file with the required size (open(...,'wb'), seek(n-1), > write(chr(0))). For each downloaded chunk you have to know its position in > the file; then just seek() and write() it. > > -- > Gabriel Genellina well yes its possible to use the file class that way. BUT the thing thats going in my mind is thread safety. i plan to start each part of the file download in a different thread. and then when each thread had downloaded more than 100kb (or eof or boundary reached) write the buffer to the disk. can this be achieved using mutex ? i have never shared objects between threads. is there a way to write this without using threads at all ??? From stefan_ml at behnel.de Fri Mar 7 05:21:59 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 07 Mar 2008 11:21:59 +0100 Subject: Looking for very light weight template library (not framework) In-Reply-To: References: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> Message-ID: <47d11746$0$14405$9b4e6d93@newsspool3.arcor-online.net> Jeff McNeil wrote: > Isn't there some long > running joke about new Python programmers creating their own template > language or something, too? =) http://article.gmane.org/gmane.comp.python.general/544922 Stefan From deets at nospam.web.de Sun Mar 9 17:38:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 22:38:03 +0100 Subject: Logically/Selectively Sub Class? In-Reply-To: References: Message-ID: <63j3ltF282fssU1@mid.uni-berlin.de> xkenneth schrieb: > Might be a silly question, but is it possible to selectively subclass, > IE subclass is a supporting module is present and not otherwise. Yes, something like this should work class Foo(some, base, classes) pass if condition: Temp = Foo class Foo(Temp, otherclass): pass Alternatively, you can use the type-function to create classes explicit with a list of base-classes. However it smells after bad design... what's your actual usecase? Diez From rridge at caffeine.csclub.uwaterloo.ca Tue Mar 18 14:51:18 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 18 Mar 2008 14:51:18 -0400 Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: Chris Mellon wrote: >OpenGL is totally unsuitable if the goal is to implement your own >pixel-level raster drawing. Unfornately, any solution involving Python is likely to be unsuitable if your goal is to set individual pixels one-by-one, and GDI would be no better than OpenGL here. The overhead of calling some sort of putpixel() function over and over will domininate everything else. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From nagle at animats.com Wed Mar 26 03:22:38 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 00:22:38 -0700 Subject: Beta testers needed for a high performance Python application server In-Reply-To: <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> Message-ID: <47e9f77b$0$36357$742ec2ed@news.sonic.net> Graham Dumpleton wrote: > Yes that is a viable option, as still are existing fastcgi solutions > for Apache, lighttpd and nginx. Fast cgi is a good technology, but it's not well documented or well supported. For some reason, the Apache people don't like it. It used to be part of the Apache distribution, but that ended years ago. It's more reliable than using things like mod_python, where you have application code running in the web server's address space. That creates both security problems and robustness problems. If an fcgi process crashes, it is automatically replaced by a fresh copy of the program at the next request. Other activity in progress is not affected. Also, fcgi processes are reloaded after some number of requests, so minor memory leaks won't choke the system over time. The main problem is that the documentation is terrible, and the monitoring and administrative tools are absent. Little problems include the fact that if you put an .fcgi file in the CGI directory, it's run silently, and inefficiently, in CGI mode. This is because Apache has CGI built into it at a level below the level at which it recognizes other files. John Nagle From craigm3604 at gmail.com Thu Mar 20 14:38:51 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 11:38:51 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> Message-ID: On Mar 20, 2:29 pm, sturlamolden wrote: > On 20 Mar, 19:09, Craig wrote: > > The culprit i here: > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > This binds these names to Python ints, but byref expects C types. > > Also observe that CacheSize and OpenMode should be c_short. I changed CacheSize and OpenMode to c_short, and commented out that line producing the "Before" message, and the output is the same. Further "tinkering" revealed that it is the byref on the fName and pw that are causing the error. The entire problem appears to be around the production of a BSTR and the passing of pointers (byref) to the BSTR. From hberig at gmail.com Thu Mar 20 13:23:18 2008 From: hberig at gmail.com (hberig) Date: Thu, 20 Mar 2008 10:23:18 -0700 (PDT) Subject: zope and python 2.5.1 Message-ID: Hi, I'm sorry if this is an off-topic message, but I didn't found other group. I've read some articles about Zope, and since I like very much python, I would like to run a webserver application using Zope instead other web application server. I've difficulties to install zope 3 and zope 2 on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is there a simple way to fix it? Thanks in advance! ---[ Trying install Zope 2 ]--- Configuring Zope installation Testing for an acceptable Python interpreter... Python version 2.5.1 found at /usr/bin/python No suitable Python version found. You should install Python version 2.4.4 before continuing. Versions 2.4.3 2.4.2 also work, but not as optimally. ---[ Trying install Zope 3 ]--- ....zope3_quick_start/zope3/src/zope/interface/common/interfaces.py", line 80, in classImplements(OverflowWarning, IOverflowWarning) NameError: name 'OverflowWarning' is not defined From jazle at localhost.com Mon Mar 24 22:19:53 2008 From: jazle at localhost.com (Jaimy Azle) Date: Tue, 25 Mar 2008 09:19:53 +0700 Subject: Python based server Uptime Message-ID: Hi, I'm just curious, if anyone ever implement python based application server just like CheryPy, Django, TinyERP, or something else, how many requests do they proceed and what is the longest runing server ever reached before downtime? Salam, -Jaimy. From miki.tebeka at gmail.com Thu Mar 27 17:22:36 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 14:22:36 -0700 (PDT) Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Message-ID: <23908024-8174-4c3d-9d0d-70765834a331@s37g2000prg.googlegroups.com> Hello Tim, > that looks nice, simple, and intuitive. thanks for thinking about it. Thanks, glad I could help. > Now to dive into some gui coding! IMO you can pull it off as a web application and then you won't need to worry about cross-platform, upgrades and all that interesting stuff. HTH, -- Miki http://pythonwise.blogspot.com From grante at visi.com Sun Mar 9 00:27:42 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:27:42 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: <13t6taeir726a18@corp.supernews.com> On 2008-03-09, sjdevnull at yahoo.com wrote: > Even in the early 1990s the moral equivalent of enscript (I think it > was a2ps) I still use a2ps occasionally, but rarely for printing out source code. I occasionally print out hex dumps that I need to markup to figure out what's going on. > worked just fine for printing with filenames, line/page > numbers, It still does. > and other niceties no matter what editor you used. It seems > more reasonable to mandate using a sane print tool for the odd > case where someone wants to print things out than to mandate > cluttering up every file with the filename in a comment. And guess what? After a while, files get renamed and nobody remembers to change the comments. If people really want a filename in the top of the file, they should at least use something like a CVS or SVN variable so that it's generated automagically and can't be wrong. -- Grant Edwards grante Yow! I want DUSTIN at HOFFMAN!! ... I want visi.com LIBRACE!! YOW!! From tew24 at spam.ac.uk Thu Mar 6 08:20:49 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 06 Mar 2008 13:20:49 +0000 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: Gabriel Genellina wrote: > Maybe this thread > http://groups.google.com/group/comp.lang.python/browse_thread/thread/f8df5ed32b324a3f/ > can help. > > This EULA doesn't apply to you, but to the Python developers, which are > the actual Visual Studio users and have to comply with its license terms. > You're just repackaging Python, your program, and other required > components. > In any case, I don't think MS cares; after all, you're promoting their OS > and making life easier for Windows users. Many thanks - that does indeed answer it. I'd not been able to find the EULA, but the bits quoted from it in the above discussion do answer the question. -- I'm at CAMbridge, not SPAMbridge From qingshan.chen at gmail.com Sun Mar 23 21:10:05 2008 From: qingshan.chen at gmail.com (QS) Date: Sun, 23 Mar 2008 18:10:05 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: Thanks to you all! It's good to know... On Mar 23, 9:02 pm, Carsten Haese wrote: > On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > > That's really weird... it's reproducible on Windows too. It doesn't > > make any sense why the name of the variable would make a difference. > > My guess is you hit some kind of obscure bug. > > This is not a bug, just an unexpected feature:http://mail.python.org/pipermail/python-list/2005-January/304873.html > > What's happening is that at the end of the script, all objects in the > global namespace are set to None (in order to decrease their reference > count and trigger garbage collection). This happens in the order in > which the names appear as keys in the globals dictionary. It randomly > happens that "swaroop", "kalam", and "cath" all are hashed in front of > "Person", but "cathy" is hashed after "Person". > > Hence, if Catherine is named cath, Python "None's" all the instances > first and then the type last, and all is well. However, if Catherine is > called cathy, Person is set to None before cathy. Then, in the lookup of > the global name "Person" during cathy.__del__, Person is None, which > doesn't have a "population" attribute, causing the AttributeError. > > Possible workarounds are: > 1) Explicitly delete the global names for the instances before the > script runs out. > 2) Don't refer to the "Person" type by its global name in __del__, but > indirectly as type(self). (This requires Person to be a new-style class, > though.) > > -- > Carsten Haesehttp://informixdb.sourceforge.net From castironpi at gmail.com Sat Mar 15 22:19:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 19:19:59 -0700 (PDT) Subject: string literal or NoneType References: Message-ID: <97eb79e8-e79d-4bd8-af6d-108579e7d54c@59g2000hsb.googlegroups.com> On Mar 15, 2:41?pm, "Terry Reedy" wrote: > wrote in message > > news:b2d5cbd3-b207-4c46-89ef-75ae101752ca at e6g2000prf.googlegroups.com... > | hi all > | i want to check a condition and if true should return a filename > | string ?from a list.if the condition is false i am returning a > | "" ?(string literal).. > | > | retv="" > | if ?somecondition: > | ? ?retv=mylist[x] > | ... > | return retv > | > | > | The calling function will check the return value and print the > | filename if it is not """. > | in the calling function i can code > | if returnval !="": > | ? ?print "filename is:",returnval > | else: > | ? ?print "no filename found" > | > | what i want to know is ,should i rewrite the ?if returnval !="" ?as > | > | if returnval: > | ? print "filename is:",returnval > | else: > | ? ?print "no filename found" > > In this situation, where returnval must be a string, the two are > equivalent. > So I consider the shorter, more efficient form stylistically better. > In situations where various null or non-null conditions are not equivalent, > one should use the one that is correct for the situation. > > | or is the way i coded the right way ? i am little confused here > | Someone suggested that i make a variable retv None and if the > | condition true then set retv as filename , > | > | retv=None > | if somecondition: > | ? ?retv=mylist[x] > | > | ... > | return retv > | > | which approach is correct..? > > As long as the function returns are documented and the behavior matches the > documentation and the calling code matched the behavior, both are > 'correct'. > I see this as stylistic preference. ?I can think of situations where a null > string might be more useful that None, so I might go with that. Others > might think of situations where a None return might be better. ?But a > function cannot satisfy all possible callers ;-) > (The is one problem with writing library code.) > > Terry Jan Reedy I actually took Caller Satisfaction in grad school. Before computer science. It depends somewhat on what you might do later-- what changes you want to make be easy. Will your return always be a primitive? Always a single value? Do you ever want to return the name of a buffer? Will the file ever already be open? You can buy yourself some time: use _noval= object(); return _noval; assert returnval is _noval. 'None' works too until you use it to signal something. But caveat emptor*. If you want to ascribe a property to an object, such as 'wasn't found', 'too small', and 'insufficient', do it. Maybe 'specialflag' is the right value for None in the -other- place, so you are free to return it. Poor None here is overworked, is the point. Search the Python library for 'None'. 5961 occurrences in 3.0a3 including comments, yet including 308 'return None's, still including comments. There's a 'return None # bad format' and a 'return None, None, line'. You've got a '__UNDEF__ = [] # a special sentinel object' too; there's precedent. Take this one. - Return code object if the command is complete and valid - Return None if the command is incomplete - codeop.py No code object will ever be 'None'; you're ok to return it without conflicts. But at a second level of abstraction, you'll need a distinction. For example: you're mapping indices to code objects. Does 'None' mean 'uninitialized'** or 'the command is incomplete'? It's ok to initialize array items to 'None'; you don't need to worry about omitting them until your call is complete. You'll get nothing but a headache if you're expecting def retrlines(self, cmd, callback = None): to throw an exception if you pass an uninitialized value to 'callback'. Twelve lines later: if callback is None: callback = print_line So, whoops. * Under the doctrine of caveat emptor, the buyer could not recover from the seller for defects on the property that rendered the property unfit for ordinary purposes. -wikipedia. ** sock = None file = None welcome = None - ftplib.py From peter.bulychev at gmail.com Sun Mar 23 17:25:40 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Mon, 24 Mar 2008 00:25:40 +0300 Subject: Clone Digger: the tool for finding software clones; GSoC 2008 Message-ID: Hello. I am glad to present you Clone Digger, the tool for finding software clones in Python programs, The presence of clones can greatly increase the software maintenance cost. For instance, every error in the original have to be fixed in all copies. Therefore I hope that Clone Digger will be useful for the Python community. It can help to form recommendations for refactoring. Clone Digger works on the abstract syntax tree level. You can read more about Clone Digger, see examples and download it on the page: http://clonedigger.sourceforge.net . ======= Google Summer of Code 2008 ======= Clone Digger participates in the Google Summer of Code 2008 program. I think, that Clone Digger will be a good choice for students willing *) to learn about the structure of programs written in Python, *) to practice in designing and implementing new algorithms (you will be asked to add automatic refactoring feature) *) to develop the tool which will help people to create better programs You can see the project ideas here: http://clonedigger.sourceforge.net/google_summer_of_code.html Please, fill free to ask me any questions you may have. -- Best regards, Peter Bulychev. From spamspam at spam.eggs Sat Mar 8 18:51:29 2008 From: spamspam at spam.eggs (Ben C) Date: Sat, 08 Mar 2008 17:51:29 -0600 Subject: SV: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: On 2008-03-08, K Viltersten wrote: >> If you can't/don't look at the source file, >> then comments aren't going to help (except >> in the case of something like docstrings in >> Python). > > I strongly disagree. Now, perhaps we're > talking about different things, here? > Usually, in the header file (C++), there > won't be any source code, except for > method declarations. A common example: > > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); > > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. > > I don't see how this is dislikeable. Please > explain. Perhaps the above IS what you > ment by "docstrings"? For Java, one has the > JavaDocs, a great tool, provided one will > comment each method and variable used. The problem is that tools like Doxygen and JavaDocs generate warnings and errors and things if everything isn't documented "completely". So you end up with a lot of silly boilerplate. I see this kind of nonsense a lot: /** * Get the width of a box * * @param box the box * @returns its width */ extern int box_get_width(box box); You are right that is it often useful to document what to pass to a method and what to expect back and that if this is done well in many cases it isn't necessary to see the implementation. But in many other cases it's obvious, and in other cases it's obvious if you just look at the source which you've got. What's needed is just a bit of common sense and pragmatism: APIs need more documentation if the source of the implementation isn't being released with them, and some APIs just need more documentation than others anyway. Python docstrings, like most things in Python, demonstrate this kind of common sense: you write what you want in them and as far as I can tell nothing complains if you don't write them at all. The lack of fascism is the big innovation. It sounds simple but it makes a huge difference: it's much easier to find (and keep up to date) the real documentation if it's not hidden in a forest of bogus documentation. From haag at lsu.edu Tue Mar 25 12:36:09 2008 From: haag at lsu.edu (Alaric Haag) Date: Tue, 25 Mar 2008 11:36:09 -0500 Subject: A "roadmap" for ctypes wrapping? References: <64nno9F2d12tkU1@mid.uni-berlin.de> Message-ID: In article <64nno9F2d12tkU1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > Alaric Haag schrieb: > > Hi all, > > > > ....stuff deleted.... > > > > ====== > > Can anyone with some "wrapping" experience add/modify/enhance the above? > > Use gccxml to gather the typedefs. And look at Gary Bishop's site to see > some cool helper classes/functions for dealing with ctypes. > > Diez Thanks for the pointers! I had hoped others might offer opinions as well, but the cross-post on the "ctypes" list is idle. Thanks again! Alaric From hniksic at xemacs.org Tue Mar 18 16:43:49 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Mar 2008 21:43:49 +0100 Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> Message-ID: <87ve3j3gqi.fsf@mulj.homelinux.net> Ninereeds writes: > As for the growth pattern, each time you grow the table you have to > redistribute all the items previously inserted to new locations. > Resizes would get rarer as more items are added due to the > exponential growth, but every table resize would take longer too > since there are more items to move. Inserting n items still > intuitively looks like O(n^2) to me. > > That said, it does remind me of that old exponential realloc trick > for array resizing. Same thing, I suppose, since a hash table is > basically an array. Maybe my math "intuition" is just wrong. That's it. While table resizes grow linearly in complexity, they become geometrically rarer. This is exactly what happens when resizing dynamic arrays such as Python lists. Applying your intuition, appending n elements to a Python list would also have O(n^2) complexity, which it doesn't. See, for example, http://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost From shakefu at gmail.com Fri Mar 7 17:26:31 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:26:31 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <8b9469d6-5b73-4f5f-8aa5-51c8dfdb2fd0@y77g2000hsy.googlegroups.com> On Mar 7, 4:22 pm, shak... at gmail.com wrote: [snip] > Although if I end up writing my own I'll sure use > datetime.parser.parse to get everything left over once you remove I mean dateutil.parser.parse. Tomorrow I'll have to leave off the last Lunchtime Guiness. > strings like "this saturday". So it helps a little! > > Jacob And on the same thought - does anyone know of a good website, resource or community that's got intelligible descriptions of all the different modules that are generally available? I know if I tab complete 'apt- get install python-*' it tries to list 1000-some possibilities, so I'm thinking there's quite a few modules out there that I might like to know about and use... Thanks! Jacob From kw at codebykevin.com Wed Mar 19 16:10:38 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 19 Mar 2008 16:10:38 -0400 Subject: Calling Mac programs from Python instead of from AppleScript In-Reply-To: References: Message-ID: <47E1733E.5060902@codebykevin.com> dvschorre at sbcglobal.net wrote: > When I'm running Script Editor, I can get Maya to draw a sphere by > typing: > > tell application "Maya" > execute "sphere" > end tell > > When I try this using Python, I get this error message: > > IDLE 1.2.2 >>>> app('Maya').execute('sphere') > > Traceback (most recent call last): > File "", line 1, in > app('Maya').execute('sphere') > NameError: name 'app' is not defined > > Maybe I need to load some libraries first. > > Please help me to get started. > > Thanks > Dewey V. Schorre > Take a look at appscript: http://appscript.sourceforge.net/ -- Kevin Walzer Code by Kevin http://www.codebykevin.com From userprogoogle-139 at yahoo.co.uk Thu Mar 6 04:37:14 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 6 Mar 2008 01:37:14 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> Message-ID: <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> Hi, Good point, some code samples is probably required. Please note that for reasons of integration with another system I am not using a templating system. Anyway I have copied them below: Python: f = open("finish.html") doc = f.read() f.close() print doc HTML:




Thank you for uploading your file

From kf9150 at gmail.com Fri Mar 28 18:48:09 2008 From: kf9150 at gmail.com (Kelie) Date: Fri, 28 Mar 2008 15:48:09 -0700 (PDT) Subject: case insensitive lstrip function? Message-ID: <0eb666fe-8c3e-4a93-afbf-1953922c19bd@s13g2000prd.googlegroups.com> Hello, Is there such a function included in the standard Python distribution? This is what I came up with. How to improve it? Thanks. def lstrip2(s, chars, ingoreCase = True): if ingoreCase: s2 = s.upper().lstrip(chars.upper()) return s[len(s)-len(s2):] else: return s.lstrip(chars) From paul at boddie.org.uk Sun Mar 16 20:32:15 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 16 Mar 2008 17:32:15 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: On 17 Mar, 01:09, a... at pythoncraft.com (Aahz) wrote: > > PyCon is what YOU make of it. If you want to change PyCon, propose a > presentation or join the conference committee (concom) -- the latter only > requires signing up for the pycon-organizers mailing list. > > This doesn't mean that we are uninterested in feedback. We love > feedback. But there are stark limits to what we can do unless people get > involved and push their pet projects. The same rules apply for most of the other Python conferences, too. Apologies to Aahz for hijacking his rant, but for anyone interested in enhancing the EuroPython 2008 experience, the advice is fairly similar: join the volunteers organising the conference and make what you want to see actually happen. For EuroPython, start here: http://www.europython.org/community/Volunteers If EuroPython is too remote or not to your taste, help your local conference or the Python conference which caters to your specific interests: http://wiki.python.org/moin/PythonConferences http://www.pycon.org/ (a list of the big generic Python conferences) Constructive feedback is always welcome, but it's better to change things before your favourite conference so that it remains your favourite conference. Paul From bogus@does.not.exist.com Thu Mar 13 16:08:43 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 15:08:43 -0500 Subject: Python regex References: Message-ID: made error on last line... read as... > I would be saying if forward-slash AND asterisk appear in this order... > negate -- -- Andrew "Andrew Rekdal @comcast.net>" < wrote in message news:qLKdnR6s8a4xFUTanZ2dnUVZ_qmlnZ2d at comcast.com... >I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such > as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > >>>CSS comment > > although this works to a degree... I know the within the brackets > everything is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? > eg. where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... > negate > > > -- Andrew > > From castironpi at gmail.com Sun Mar 2 15:43:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 12:43:22 -0800 (PST) Subject: Network server- / client-side messaging References: Message-ID: ''' Last time, we left off at: ''' class InterfaceClientSide( ClientSide ): message= MessageDec() incremental= message.incremental() settings= AYT( .5, 3 ) user_act= message.out() def __init__( self, image ): self._image= image ClientSide.__init__( self ) def on_scale( self, *args ): change= self._whatchange( self.on_scale, *args ) self.user_act( change ) def on_rotate( self, *args ): change= self._whatchange( self.on_rotate, *args ) self.user_act( change ) @incremental( 1 ) def layout_return( self, layoutchange ): renderchange( layoutchange ) @incremental( 2 ) def layout_return( self, layoutchange ): renderchange( layoutchange ) @message def time_estimate( self, etc ): report( etc ) class InterfaceServerSide( ServerSide ): message= MessageDec() incremental= message.incremental() settings= AYT( .5, 3 ) time_estimate= message.out() layout_return= incremental() def __init__( self, image ): self._image= image ServerSide.__init__( self ) @message.intervene() def user_act( self, change ): etc= self.calculateeta( change ) self.time_estimate( etc ) preliminary= self.calculation() preliminary_change= whatchange( preliminary ) self.layout_return( preliminary_change ) completed= self.other_calculation() completed_change= whatchange( completed ) self.layout_return( completed_change ) self.layout_return.finish() ''' Another use ClientSide and ServerSide should support is a peer-to-peer chat-and-game server. And that said, it's not clear that there's any distinction between ServerSide and ClientSide anyway, depending on exactly how the listen and connect methods abstract. How much of the implementation do they share? Most. You could mark 'time_estimate' as incremental( 3 ); they're separated for illustration purposes. One remaining question is how to intervene in user_act, if a second change arrives before the previous complete. You could combine the earlier change parameter in the new call and throw an exception in the thread handling the earlier one at its first loss of control--- and maybe even at once with settrace! That tends to be costly. Not to mention, change has already entered derived-class space. ServerSide should make sure it's easy enough to address the issue on one's own, and @message.nonintervene() is available too. ''' From willsteve2003 at yahoo.ca Mon Mar 10 11:02:23 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:02:23 -0700 (PDT) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <7d442cdd-749e-4391-ba31-e9c86d090137@x41g2000hsb.googlegroups.com> <70f5b8e7-4e76-43f7-b390-c5dd994ff434@e31g2000hse.googlegroups.com> Message-ID: On Mar 8, 5:37?pm, malkarouri wrote: > On Mar 8, 6:24?pm, rockingred wrote: > > > I think it's a bad practice to get into. ?Did you intend to do the > > "process" step again over the added variables? ?If not I would set a > > new variable, based on your awful naming convention, let's call it z. > > Then use z.append(y) within the for loop and after you are out of your > > for loop, q.append(z). > > Thanks, rockingred, for the advice. I hope that you didn't assume that > I was a newbie, even if my question looks so. What I was trying to do > is write some Python code which I need to optimize as much as > possible. I am using Cython (Pyrex) and would probably end up > rewriting my whole module in C at one point, but it is really hard to > beat Python data structures at their home turf. So meanwhile, I am > making use of dubious optimizations - on my own responsibility. There > have been a lot of these along the years - like using variables > leaking from list expressions (not anymore). Think of it as a goto. > Yes, I intend to do the process step again over the added variables. > The suggested deque is probably the best, though I need the speed > here. > What are the variable naming you would suggest, for a throwaway - > probably anonymized for the same of publishing on the web - code? > > Cheers, > > Muhammad Alkarouri If the variables are "throwaways" and will be used in a really small function, then it's probably okay to name them the way you did. I'm just against single character names on principal, because if you need to search a program to find where the variable was used you get too many hits. I prefer to name the variables for what they do. For example, instead of "q" you could use "queue". From waltbrad at hotmail.com Mon Mar 17 14:18:02 2008 From: waltbrad at hotmail.com (waltbrad) Date: Mon, 17 Mar 2008 11:18:02 -0700 (PDT) Subject: questions about named pipe objects... References: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> Message-ID: On Mar 17, 1:59 pm, Jeff Schwab wrote: > > A Unix fifo is only nominally a file. It's really just a convenient way > of referring to an in-memory object. > mkfifo f > some_prog > f & > cat f > > Is semantically equivalent to: > > some_prog | cat > > If you want to peruse the data in your editor, use a regular file, not a > fifo. Have the writer (producer, "child" in your example) open it in > append mode. Okay. I get it. That's interesting. Wish Lutz explained that. Thanks. From grante at visi.com Sun Mar 9 00:24:46 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:24:46 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: <13t6t4ujm71tjec@corp.supernews.com> On 2008-03-09, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > >> I'm also a bit baffled by people who put a comment at the top of every >> file that tells you what the filename is. > [snip rant] > > You've never printed out a source file on pieces of dead tree > to read on the train on the way home, or in bed or the bath? Not in the last 20 years or so. > Yes, some editors will print a header or footer showing the > file name, but not all will, or are configured to do so. If I want the filename printed at the top of the first page (or at the top of every page) I'll use a tool that does that. -- Grant Edwards grante Yow! If I am elected no at one will ever have to do visi.com their laundry again! From spradml at gmail.com Tue Mar 18 06:27:26 2008 From: spradml at gmail.com (Pradnyesh Sawant) Date: Tue, 18 Mar 2008 15:57:26 +0530 Subject: detect current timezone set by kde Message-ID: <20080318102726.GB3880@debian> Hello, can someone please tell me how can I programatically detect the timezone information that has been set through kde? basically, I have a small pyqt4 app which shows the current time. however it shows me my system time (dunno where that is stored; basically it shows me time in IST). however, I'm right now in hk and would like the app to show me time in my current timezone (hong kong). Any guidelines how may I go about doing this? thanks a lot in advance :-) -- warm regards, Pradnyesh Sawant -- Believing everybody is dangerous; believing no one is dangerous... --Abraham Lincoln -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From castironpi at gmail.com Thu Mar 6 13:32:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 10:32:30 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <5oQzj.61239$Pv2.45450@newssvr23.news.prodigy.net> Message-ID: <8fe8ff57-70d2-45e1-9ce6-725eb949b5ee@p73g2000hsd.googlegroups.com> > Actually, there's another data structure I was working on (a year ago > now) that's tangentially related, so if you guys want me to hold off > on that one til you or I is satisfied on the company-product map, I > will! ?Otherwise, I'll just post it here and leave it to you. > (Knowing myself, something tells me I'll try to formulate it later on > today regardless. ?Heh heh heh. ?If that's not the most virtuous way > to ask for help, then I might have inherited from TroubleMaker at some > point up the line.) My other question still open, the idea was a collision detector. But it's been done. Ideally, subdivide space varying with objects' positions up to a tolerance. On motion, redivide. Each tile, hexes, triangles, or squares, can access the other objects in itself-- and only detect collisions among those. Objects can span multiple tiles. For large object sets, zero detections made per cycle best case, but still all of them worst. It amounts to a tree structure in which child nodes are keyed geometrically-- grid.NWcorner.NEcorner gets you the second column, first row in a 4x4 grid. grid.NWcorner.NEcorner.SWcorner gets you the third column, second row, in an 8x8 grid, and by that point, there are 63 tiles other objects might be in that you know aren't in yours. A tile is a leaf if there are no objects in it. Question is, how rare/common is the subset of object configurations in which the optimizations weigh out? From enleverlesX.XmcX at XmclaveauX.com Thu Mar 13 20:18:13 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 14 Mar 2008 01:18:13 +0100 Subject: Python-PHP bridge? In-Reply-To: References: Message-ID: <47d9c614$0$855$ba4acef3@news.orange.fr> Hi! Only under Windows, you can use PHPscript. It's the "active-scripting" release of PHP. With it, you can send PHP's functions (source), and call these functions (with parameters). With the same method, you can also use, from Python, VBscript, Jscript, PerlScript, RubyScript. @-salutations Michel Claveau From deets at nospam.web.de Sat Mar 29 17:26:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 22:26:56 +0100 Subject: Serial port error statistics - any comparable data? In-Reply-To: References: Message-ID: <657qh1F2es9vnU1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > Hi, > > I have been doing some tests on a device that > we are thinking of incorporating into a product, > and I have seen that reception on a serial port > at 115200 baud over about six metres of RS-232 > cable makes mistakes, to the order of 125 lines > with errors in them out of approximately 18.4 > million lines of 65 or so chars - about one errored > line in 147000, or one error character in 95 million. > > The PC that is making the errors is a 64 bit dual > core AMD machine running at 2 Gig, and I am > running stock standard Open Suse 10.3 with > the supplied Python 2.5. > > What kind of bothers me is the nature of the errors - > I seem to get only missing characters, as if an > interrupt was missed. There are no munged characters > as one would expect if the errors were bit related. > > Has anyone else seen anything like this, and am I worrying > needlessly? > > I realise that my production protocols will easily handle > this almost non existent level of error - but if this were in > microcontroller code that I had written myself, I would > suspect that I was spending too long in some critical > section of code. RS232 is unfortunately as bad as a "protocol" as it can get. I've used it for communication with a microcontroller for just a few bytes every second. And it failed miserably, so I needed to implement a protocol on top of it. The machine spec is totally irrelevant - what is interesting is the serial hardware you use. Are you by any chance using a serial2usb-converter? I had nothing but troubles with these. if you have the chance, try & attach a machine with legacy rs232 port, and see if the errors still remain. Diez From http Wed Mar 19 05:42:55 2008 From: http (Paul Rubin) Date: 19 Mar 2008 02:42:55 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> Message-ID: <7xskynm4m8.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > > Re Haskell: I've been spending a lot of time on Haskell recently, > > though I haven't done anything nontrivial with it yet (just some > > small stuff). But I think it's better for complex program > > development than Python is, > > Could you elaborate on this? (Sincere question; I have almost no > idea of Haskell.) http://wiki.python.org/moin/PythonVsHaskell is a fairly high-level comparison. I think it's easier to write complex code in Haskell because: 1) it has a powerful static type system that lets you express important invariants and have them enforced at compile time. This not only catches errors but helps you understand the program logic almost like running the code under a debugger does. If you try to fill a gap by putting in a piece of the wrong shape, it just won't fit and the compiler will tell you what you really wanted. On the other hand, most types are inferred by the compiler, so you don't need a lot of cumbersome declarations like in Java. 2) The basic list type in Haskell works something like Python iterators, but they don't change state when you consume an item. In fact all Haskell data is immutable. You avoid vast classes of bugs this way. But you do have to change the way you think about programming. I may write a longer comparison post sometime later. From torriem at gmail.com Sat Mar 1 15:58:47 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Mar 2008 13:58:47 -0700 Subject: How to subclass a built-in int type and prevent comparisons In-Reply-To: <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> Message-ID: <47C9C387.8040100@gmail.com> castironpi at gmail.com wrote: > Tell Wall. But why not [ 2, 3 ]>= 2? Back to your question, another > option is to not subclass. Umm, no. You need to actually read the posts before you respond to them. His question was whether or not to throw an exception in this case. He's *already* subclassed the type. The first question was, should he throw an exception. And given that Python 3.0 will throw exceptions, he is justified in throwing exceptions as well. I have no idea what he would lose by throwing an exception. I have no idea how else he would do this. His second question was, would his code for implementing __gt__ (and throwing exceptions) be likely efficient. That I cannot say. From xkenneth at gmail.com Sat Mar 8 14:36:12 2008 From: xkenneth at gmail.com (xkenneth) Date: Sat, 8 Mar 2008 11:36:12 -0800 (PST) Subject: Intra-Package References Message-ID: <01d2be35-3e08-49d4-811b-a0d8b4fb5d27@n77g2000hse.googlegroups.com> Does your python module have to exist in the path in order for intra- package references to work? Regards, Kenneth Miller From rockxuan at gmail.com Tue Mar 18 03:56:57 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:56:57 -0700 (PDT) Subject: replicas replicas watch Message-ID: Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From craigm3604 at gmail.com Thu Mar 20 19:50:18 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 16:50:18 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> Message-ID: On Mar 20, 6:26 pm, sturlamolden wrote: > On 20 Mar, 19:09, Craig wrote: > > > The following is the C++ prototype for one of the functions: > > short FAR PASCAL VmxOpen(BSTR *Filespec, > > LPSHORT lpLocatorSize, > > LPSHORT lpOmode, > > LPHANDLE lphwmcb, > > BSTR *Password); > > import ctypes > import comtypes > > LPBSTR = ctypes.POINTER(comtypes.BSTR) > HANDLE = ctypes.POINTER(ctypes.POINTER(ctypes.c_long)) > LPHANDLE = ctypes.POINTER(HANDLE) > LPSHORT = ctypes.POINTER(ctypes.c_short) > > VmxOpen = ctypes.windll.vbis5032.VmxOpen > VmxOpen.restype = c_short > VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] > > Filespec = comtypes.BSTR('blahblahblah') > LocatorSize = ctypes.c_short(256) > Omode = ctypes.c_short(1) > hwmcb = HANDLE() > Password = comtypes.BSTR('blahblahblah') > > res = WmxOpen( byref(Filespec), byref(LocatorSize), > byref(Omode), byref(hwmcb), byref(Password) ) > > or if that fails: > > pFilespec = ctypes.pointer(Filespec) > pLocatorSize = ctypes.pointer(LocatorSize) > pOmode = ctypes.pointer(Omode) > phwmcb = ctypes.pointer(hwmcb) > pPassword = ctypes.pointer(Password) > > res = WmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) sturlamolden, thanks for the input. I had to change your example to the following to get it to run: from ctypes import * import comtypes LPBSTR = POINTER(comtypes.BSTR) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) VmxOpen = windll.vbis5032.VmxOpen VmxOpen.restype = c_short VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] Filespec = comtypes.BSTR('s:\\msdb\\dcod') LocatorSize = c_short(0) Omode = c_short(3) hwmcb = HANDLE() Password = comtypes.BSTR('GU32ASBURYPARK60A42A20') res = VmxOpen( byref(Filespec), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(Password) ) print "res = " + str(res) pFilespec = pointer(Filespec) pLocatorSize = pointer(LocatorSize) pOmode = pointer(Omode) phwmcb = pointer(hwmcb) pPassword = pointer(Password) res = VmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) print "res = " + str(res) After changing the assignment for Password to the correct value, both calls to VmxOpen returned a status of 20, which indicates an invalid password. I received a direct email from someone, and I came up with the following after implementing his advice: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf FileSpec = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) printf ("FileSpec = \x22%s\x22\n", FileSpec) Password = windll.oleaut32.SysAllocStringByteLen("XYZ\x00", 4) printf ("Password = \x22%s\x22\n", Password) LocatorSize = c_short(0) Omode = c_short(3) hwmcb = c_long(0) X = c_short(0) printf ("Before - X = %#x (%d), LocatorSize = %d, Omode = %d, hwmcb = %d\n", X, X, LocatorSize, Omode, hwmcb) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." X.value = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) printf ("After - X = %#x (%d), LocatorSize = %d, Omode = %d, hwmcb = %d \n", X, X, LocatorSize, Omode, hwmcb) windll.oleaut32.SysFreeString(FileSpec) windll.oleaut32.SysFreeString(Password) This returned a correct value in X of 0 (VIS_OK). When I changed: FileSpec = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) to: FileSpec = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", 13) I got the expected X value of 13 (VIS_DOS_ERROR). As was pointed out to me, and not really to my surprise as I am still very "green" at Python, the correct call was: X.value = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) instead of: X = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) Thank you to everyone for their help. From sturlamolden at yahoo.no Wed Mar 19 21:03:24 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 18:03:24 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: On 20 Mar, 00:16, John Machin wrote: > What don't you understand about the comments in the first two > screenfuls of Objects/setobject.c? I had not looked at it, but now I have. Is seems Hettinger is the author :) Ok, so sets are implemented as hash tables. Then I agree, use Raymond Hettinger's solution. From castironpi at gmail.com Wed Mar 5 22:43:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:43:09 -0800 (PST) Subject: access to base class __init__ References: Message-ID: <57cf7606-f49e-4377-8237-f3a86acb79fd@n36g2000hse.googlegroups.com> On Mar 5, 6:09?pm, sambo q wrote: > I got myself in jam trying to be too fancy with ?threading.Thread > Docs say / remind to call the base __init__ > but I can't fighure out how. > > --------------------------- > def main() > ..... > ? ? ls.listen(5) > ? ? key = ' ' > # ? ?while key != EXITCHARCTER: > ? ? while stop_serving == False: > ? ? ? ? cs, raddr = ls.accept() > ? ? ? ? print "Main_Thread: ",cs, raddr > ? ? ? ? nt = client_socket_handler( cs, raddr ) > ? ? ? ? print threading.enumerate() > ? ? ? ? key = getkey() > > # ? ?ls.close() > ? ? time.sleep(4) > ? ? print "Server Exiting." > > class client_socket_handler(threading.Thread): > ? ? def __init__(self, cs, remote_address): > ??????????????????????? > ? ? ? ? self.threading.Thread.__init__(self,self.socket_handler,None,None) > ? ? ? ? self.socket = cs > ? ? ? ? self.rhost_addr = remote_address > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > # ? ? ? ?t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) > # ? ? ? ?t1.start() > ? ? ? ? self.start() > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > ? ? ? ? print "client_socket_handler.__init__(): enumerate()", > threading.enumerate() > > ? ? def socket_handler( self, invar, indict ): > ? ? ? ? threadname = self.getName() > ? ? ? ? print "\"%s started\"" % threadname > ? ? ? ? print "client_socket_handler.socket_handler() invar: ", invar > ? ? ? ? instr = self.socket.recv( 500 ) > # ? ? ? ?print instr > ? ? ? ? req_lines = string.split( instr, "\r" ) > ? ? ? ? for line in req_lines: > ? ? ? ? ? ? line.strip( "\n") > ? ? ? ? print req_lines > ? ? ? ? print len( instr ) > > ---------------------------------- > > self.threading.Thread.__init__() > self.Thread.__init__() > ?? recall a= A() --> a.b() --> A.b( a ). What is A? threading.Thread. In other words, threading.Thread.__init__( *stuff ). From janeczek at gmail.com Thu Mar 27 00:54:17 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Thu, 27 Mar 2008 05:54:17 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: <7xzlslvpn5.fsf@ruckus.brouhaha.com> References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: <561cb5bc0803262154s66b01425hf866847fbbfb3502@mail.gmail.com> Thanks for finding time to reply! On 26 Mar 2008 01:46:38 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > A few thoughts. The envisioned Python-Haskell bridge would have two > directions: 1) calling Haskell code from Python; 2) calling Python > code from Haskell. The proposal spends more space on #1 but I think > #1 is both more difficult and less interesting. By "Haskell" I > presume you mean GHC. I think that the GHC runtime doesn't embed very > well, despite the example on the Python wiki > (http://wiki.python.org/moin/PythonVsHaskell near the bottom). This > is especially if you want to use the concurrency stuff. The GHC > runtime wants to trap the timer interrupt and do select based i/o > among other things. And I'm not sure that wanting to call large > Haskell components under a Python top-level is that compelling: why > not write the top level in Haskell too? The idea of making the > critical components statically typed for safety is less convincing if > the top level is untyped. I wasn't aware of the runtime issues, these can be things to watch out for. However, the type of embedding that I imagined would be mostly pure functions, since Python can deal with IO rather well. It'd also be applicable in situations where we want to add some functionality to to existing, large Python project, where the complete rewrite would be infeasible. > There is something to be said for porting some functional data > structures to Python, but I think that's mostly limited to the simpler > ones like Data.Map (which I've wanted several times). And I think > this porting is most easily done by simply reimplementing those > structures in a Python-friendly style using Python's C API. The type > signatures (among other things) on the Haskell libraries for this > stuff tend to be a little too weird for Python; for example, > Data.Map.lookup runs in an arbitrary monad which controls the error > handling for a missing key. The Python version should be like a dict, > where you give it a key and a default value to return if the key is > not found. Plus, do you really want Python pointers into Haskell data > structures to be enrolled with both systems' garbage collectors? I didn't mention this in this first draft, but I don't know (yet) how to support those "fancy" types. The plan for now is to export monomorphic functions only. As for GC, I think having the two systems involved is unavoidable if I want to have first class functions on both sides. > The Haskell to Python direction sounds more useful, given Haskell's > weirdness and difficulty. Python is easy to learn and well-packaged > for embedding, so it's a natural extension language for Haskell > applications. If you wrote a database in Haskell, you could let > people write stored procedures in Python if they didn't want to deal > with Haskell's learning curve. Haskell would call Python through its > "safe" FFI (which runs the extension in a separate OS thread) and not > have to worry much about the Python side doing IO or whatever. Of > course this would also let Python call back into the Haskell system, > perhaps passing Python values as Data.Dynamic, or else using something > like COM interface specifications. That is one of the use cases I have missed in the first draft. Thanks for the idea! > Anyway I'm babbling now, I may think about this more later. By all means, please do go on :) This has helped a lot :) Regards, Michal From python.list at tim.thechases.com Wed Mar 12 15:13:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 14:13:24 -0500 Subject: enums and PEP 3132 In-Reply-To: References: Message-ID: <47D82B54.3080206@tim.thechases.com> >> Currently I'm just putting this at the top of the file: >> py=1 >> funcpre=2 >> funcpost=3 >> ... > > That can be done more compactly with > > py, funcpre, funcpost = range(3) I've harbored a hope that a combination of PEP 3132[1] ("Extended Iterable unpacking") and itertools.count()[2] would be available for doing something like this: py, funcpre, funcpost, *unexhausted_iterator = count() which would theoretically allow me to just add new enum names to the LHS without having to update constant passed to range() on the RHS. Unfortunately, it looks like this wasn't a desirable behavior because the PEP describes the "*unexhausted_iterator" notation unpacking as a list, not as an iterable. My desired syntax would work well for bit-mask fields as well: def bit_iter(i=0): assert i >= 0 while True: yield 1 << i i += 1 read, write, execute, *_ = bit_iter() and I'm sure there are other use-cases I've not yet considered. Diez Roggisch hacked together a disturbingly (in the "that hurts my brain to sniff the stack" way) beautiful/functional decorator[3] that does something like this in Python2.4+ and can just be used something like @variably_unpack def just_enough(): return itertools.count() read, write, execute = just_enough() which is a fabulous syntax, IMHO. -tkc [1] http://www.python.org/dev/peps/pep-3132/ [2] http://docs.python.org/dev/library/itertools.html#itertools.count [3] http://groups.google.com/group/comp.lang.python/browse_thread/thread/63dce474e196adac/d98522d9bedae946#d98522d9bedae946 From gbrunick at andrew.cmu.edu Thu Mar 6 02:44:54 2008 From: gbrunick at andrew.cmu.edu (Gerard Brunick) Date: Thu, 06 Mar 2008 02:44:54 -0500 Subject: Short confusing example with unicode, print, and __str__ In-Reply-To: <47CEEBFC.9010001@islandtraining.com> References: <47CEDF77.5050501@andrew.cmu.edu> <47CEEBFC.9010001@islandtraining.com> Message-ID: <47CFA0F6.5020009@andrew.cmu.edu> Gary Herron wrote: > Gerard Brunick wrote: >> I really don't understand the following behavior: >> >> >>> class C(object): >> ... def __init__(self, s): self.s = s >> ... def __str__(self): return self.s >> ... >> >>> cafe = unicode("Caf\xe9", "Latin-1") >> >>> c = C(cafe) >> >>> print "Print using c.s:", c.s >> Print using c.s: Caf? >> >>> print "Print using just c:", c >> Print using just c: Traceback (most recent call last): >> File "", line 1, in >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >> position 3: ordinal not in range(128) >> >>> str(c) >> Traceback (most recent call last): >> File "", line 1, in >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >> position 3: ordinal not in range(128) >> >> Why would "print c.s" work but the other two cases throw an exception? >> Any help understanding this would be greatly appreciated. >> >> Thanks in advance, >> Gerard >> > It's the difference between how __str__ and __repr__ act on strings. > > Here's s simpler example > > >>> d=unicode("Caf\xe9", "Latin-1") > >>> repr(d) > "u'Caf\\xe9'" > >>> str(d) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > > Gary Herron It seems the question is more about what does print do. Lets extend your example: >>> d=unicode("Caf\xe9", "Latin-1") >>> repr(d) "u'Caf\\xe9'" >>> print d Caf? >>> str(d) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Why doesn't the print statement that a UnicodeEncodeError? I assumed that print calls str and then prints the result, but this doesn't seem to be the case. What the heck does print do? From sarobav at gmail.com Wed Mar 12 08:06:32 2008 From: sarobav at gmail.com (sarobav at gmail.com) Date: Wed, 12 Mar 2008 05:06:32 -0700 (PDT) Subject: To download Eclipse, select a package below or choose one Message-ID: <5900f5d9-bec2-4d17-a8bd-e08ea502e531@e23g2000prf.googlegroups.com> To download Eclipse, select a package below or choose one of the third party Eclipse distros. You will need a Java runtime environment (JRE) to use Eclipse ... http://downloadcorner.googlepages.com From bearophileHUGS at lycos.com Tue Mar 4 15:27:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 4 Mar 2008 12:27:26 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> Message-ID: Raymond HettInger: > FWIW, I'm very happy with for-else. Most of the time, you don't need > it, but when you do, it beats the heck out of doing silly tricks with > flags. I'd like it to be renamed to something more natural :-) Bye, bearophile From haraldarminmassa at gmail.com Sun Mar 16 03:33:31 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Sun, 16 Mar 2008 00:33:31 -0700 (PDT) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: <97432b58-958c-43ec-b48a-6849f9abed4a@v3g2000hsc.googlegroups.com> Doug, > as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. > I'm guessing that they can't be in library.zip for a reason (i.e., they are > DLL files, essentially, and thus must be readily available to be loaded > into memory). .dll and .pyd files CAN be within library.zip and even within the single-file-exe. There is some Hellermagic within _memimporter.pyd that loads the .dll and .pyd from a zipfile. When you scan the build_exe.py, you will explicitely find: print "*** finding dlls needed ***" dlls = self.find_dlls(extensions) self.plat_finalize(mf.modules, py_files, extensions, dlls) dlls = [item for item in dlls if os.path.basename(item).lower() not in self.dll_excludes] # should we filter self.other_depends in the same way? > Is there a work-around for this, then? -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/ multiarray.pyd -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/ umath.pyd -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd let's try: your mission is, should you chose to accept it, to make a py2exed application to load two different multiarray.pyd, who are on the visible level only different by their place in the file system. So, please make a minimal script: import multiarray import numpy.core.multiarray as ncmultiarray and, using Peters test >>> from multiarray import zeros assert zeros((1,), "1") == array([0], '1') and check, if those multiarrays are the correct ones. If yes, you can try to build upon this by making all imports explicit as described above. (Yes, I know, that's not necessary in plain python ... but it saved me in some weird "import from .zip" and "import from database" situations.) > (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and > umath.pyd files somewhere deep inside I have a BAAAD feeling about to files having the same name but very very different content - but that's not your call in this situation. Are you able to build that libraries yourself? Then you could move down and build the multiarray.pyd as ncmultiarray.pyd and adjust all imports accordingly. (lots of work) > manual create the "stub"-like .pyc files that py2exe creates to point to > these alternate .pyd files and then place these stubs in > library.zip/numpy/core? ? As much as I know there is only one central "loader stub", which ensures that .dlls get imported from memory, see above. py2exe does not create something like p2elma.py containing "import multiarray.pyd" best luck, and please take your time to scan the py2exe.org wiki, there are many similiar challanges with various packages, maybe you get another workaround-idea (and, if we find one, PLEASE put it down there for others to learn) best wishes, Harald From fetchinson at googlemail.com Mon Mar 31 13:04:31 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 31 Mar 2008 10:04:31 -0700 Subject: [OT] troll poll Message-ID: [Heavily off-topic fun stuff] Hi folks, This is a quick poll to have scientific data on our beloved troll community: Whose trolling behaviour is more professional? (check one) [ ] - Xah Lee [ ] - castironpi More specifically, who can create a bigger mess on c.l.py? (check one) [ ] - Xah Lee [ ] - castironpi More specifically, who is more entertaining? (check one or none) [ ] - Xah Lee [ ] - castironpi Even more specifically, who makes you laugh harder? (check one or none) [ ] - Xah Lee [ ] - castironpi Thanks for your feedback! [/Heavily off-topic fun stuff] From aahz at pythoncraft.com Fri Mar 28 11:43:03 2008 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2008 08:43:03 -0700 Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: In article , wrote: > >I'm having trouble explaining the benefits and tradeoffs of threads to my >coworkers and countering their misconceptions about Python's threading model >and facilities. They all come from C++ and are used to thinking of >multithreading as a way to harness multiple CPU cores for compute-bound >processing. I also encountered, "Python doesn't really do threads" today. >*sigh* > >I don't need pointers to the relevant documentation sections. A bit of >googling didn't turn up much about threading beyond tutorial introductions. >I'm looking for something which will explain the rationale for using threads >in Python to someone who is experienced with multithreading in other >languages (like C/C++). Maybe a compare-and-contrast sort of document? Maybe this will help? http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From kkadrese at gmail.com Wed Mar 19 09:50:18 2008 From: kkadrese at gmail.com (kkadrese at gmail.com) Date: Wed, 19 Mar 2008 06:50:18 -0700 (PDT) Subject: lock access to serial port References: <78873650-1130-4be9-9ea7-3889036b2bbf@a23g2000hsc.googlegroups.com> Message-ID: hmm, now it seems I get to the locking try: ser = serial.Serial(dev, 19200, rtscts=1, timeout=1) if ser.isOpen(): try: fcntl.lockf(ser,fcntl.LOCK_EX) but get into some weirdness - trying to lock does not time out! The script stops at this line and waits ?for ever? (it waits for 15 minutes at least, that I have tried). Andra > not the goal setup but the way I tried it out - a webpage to send an > sms to mobile phone. This is an php what calls a python script. A > python script opens serial device, checks for gsm network, sends a > message - on all the way I try to make sure that appropriate answers > are received from the gsm device so that I know that all is going well > (and if not - cancel it with error message). > > Testing it with sending an sms from two open webpages, I normally got > that one message was sent and for the other I received "try once more, > happened that and that". But I got also an inadmissible situation - > the received sms contained also unwanted text. As far as I can realize > how to deal with it is not allowing writing to the device for two > processes simultaneously. > > Andra > > On 19 Marts, 11:00, taco wrote: > > > kkadr... at gmail.com wrote: > > > hello group, > > > > how to get ttyS0 serial port for exclusive access? I have a python > > > script that uses this device with AT commands. I need that two > > > instances can call simultaneosuly this python script but only one of > > > them gets the device. I tried fcntl.flock, it was just ignored, put > > > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not > > > know what are appropriate arguments), googled half a day for various > > > phrases, error messages etc....without success. > > > > please help, > > > > Andra > > > not sure if I understand you well, but how about a server application which > > accepts 2 clients which can send messages which are output on the serial > > device? The serial device access protected with a mutex while receiving > > messages done in 2 threads or something. > > taco From ricky.zhou at gmail.com Fri Mar 21 17:25:36 2008 From: ricky.zhou at gmail.com (Ricky Zhou) Date: Fri, 21 Mar 2008 17:25:36 -0400 Subject: List question In-Reply-To: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Message-ID: <20080321212536.GD1382@Max.nyc1.dsl.speakeasy.net> On 2008-03-21 05:16:41 PM, From at home.xs4all.nl wrote: > alist = [] > blist = [ 'one','two','one and two','one and four','five','one two'] > for f in blist: > if 'one' and 'two' in f: > alist.append(f) > > for i in alist: > print i > > two > one and two > one two > > > why is it printing the first "two"? Look at the this line: if 'one' and 'two' in f: You're basically saying: if ('one') and ('two' in f): which is why you only get elements that contain 'two'. Ricky -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From devnew at gmail.com Tue Mar 18 01:14:48 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Mon, 17 Mar 2008 22:14:48 -0700 (PDT) Subject: finding euclidean distance,better code? References: Message-ID: <7a96c9d8-ee64-4fd8-b673-09c2a3543667@i12g2000prf.googlegroups.com> On Mar 17, 6:17 pm, "Gabriel Genellina" wrote > > _, imgindex = min((sum(abs(input_wk - weights[image, :])),image) for image > in xrange(numimgs)) > mindistance = abs(input_wk - weights[imgindex, :]) > # normalize and sum again thanks Gabriel D From grante at visi.com Thu Mar 20 12:10:35 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 16:10:35 -0000 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> <0dd3f571-b044-4ea4-8e58-14b21dc3c7b8@z38g2000hsc.googlegroups.com> Message-ID: <13u533r214864e@corp.supernews.com> On 2008-03-20, jmDesktop wrote: >> I believe Grant was suggesting that Emacs often serves a >> similar purpose on Unix to what Visual Studio does on Windows, >> which seemed to be what you were asking. ?When asking about >> Mac OS X here, you are likely to get a lot of generic Unix >> responses. ?(Would it have been clearer if he had just said >> "emacs?") > > No. Typically when someone posts a one-liner search it means > go figure it out and stop bothering "us." I had already > searched. I could not get it to work, Could not get what to work? > which is why I posted. If I took it wrong I apologize. I honestly thought you were asking how to run/debug python programs inside emacs. A couple of the hits answered that question. The others explained how do get python-aware editing modes configured. > I really had two questions. One is just how to run a program from > within the editor and the other is if my thinking on how development > is done in python wrong to start with. Most of my non-Windows > programs have been on Unix using vi, but it has been a while. I'm > used to writing a program in visual studio and running it. Perhaps you'd be more comfortable with one of the IDEs? http://wiki.python.org/moin/IntegratedDevelopmentEnvironments http://en.wikipedia.org/wiki/Comparison_of_integrated_development_environments#Python > If that's the wrong expectation for python programming in > emacs, then I wanted to know. Yes, you can run programs (including python debuggers) from inside emacs. The simplest way is to do "meta-x shell" to get a shell prompt inside emacs, then just type whatever command line you want to use to run the program. Or you can map a command to a keystroke that will run the program. I generally just have another terminal window open where I run the program -- but I've never liked IDEs so your tastes may differ. -- Grant From menosaint at gmail.com Sat Mar 15 11:27:32 2008 From: menosaint at gmail.com (menosaint at gmail.com) Date: Sat, 15 Mar 2008 08:27:32 -0700 (PDT) Subject: string literal or NoneType Message-ID: hi all i want to check a condition and if true should return a filename string from a list.if the condition is false i am returning a "" (string literal).. retv="" if somecondition: retv=mylist[x] ... return retv The calling function will check the return value and print the filename if it is not """. in the calling function i can code if returnval !="": print "filename is:",returnval else: print "no filename found" what i want to know is ,should i rewrite the if returnval !="" as if returnval: print "filename is:",returnval else: print "no filename found" or is the way i coded the right way ? i am little confused here Someone suggested that i make a variable retv None and if the condition true then set retv as filename , retv=None if somecondition: retv=mylist[x] ... return retv which approach is correct..? can someone help please vincent From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 21:23:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 01:23:35 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <3e6de9d7-4278-4b1e-9373-78c98fa11a3f@m34g2000hsc.googlegroups.com> Message-ID: <13utqsnq8le081f@corp.supernews.com> On Sat, 29 Mar 2008 12:49:05 -0700, Carl Banks wrote: >> Please set it straight in 3.0, and if not, convince me with a good >> reason of doing so, so that I can live with it and don't have to spend >> the rest of my life in 2.x ;). > > 1. It's not going to change in Python 3.0. > > 2. It's a silly thing to care so much about that you will avoid using a > langauge because of it. I dislike the attitude that "oh, feature X is unimportant, why should we care about it?". It's often -- but not always -- said by those who do care very much about it themselves, except they prefer the way it is rather then the requested feature. If Guido had a sudden brain tumor and replaced comparison operators with Fortran-style operators, it wouldn't destroy Python. It would just be a minor wart on an otherwise good language. So why should we care about using == instead of .EQ.? Why does Python use # for comments instead of Basic-style remarks? Would it be silly to care if Python 3 discarded # and introduced REM? I could belabor the obvious with dozens of syntax elements which, *in isolation*, it would be silly to care about. But syntax defines the feel of the language. Perl and Java have better (or at least *larger*) libraries, although arguably not as many "batteries included", but the syntax, oh my. We use Python because it is Python and not Perl or Basic or Fortran or Java. If the syntax changes, so does the language. Yes, in isolation the question of != versus <> is a tiny little thing, silly to drop Python merely because of it. But it's not silly to care about the feel of the language. Python is as good as it is because Guido cares very much indeed about the feel of the language, and so do many of we Python users. -- Steven From stef.mientki at gmail.com Fri Mar 28 11:15:45 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 16:15:45 +0100 Subject: class or inherited list ? Message-ID: <47ED0BA1.9020103@gmail.com> hello, Passing all kinds of data between objects, I'm looking for an elegant (and simple) way to pack the data. Now it looks to me that both the class and the inherited list, performs equally well. Till now, the most elegant way (in my view) is the list inheritance, mainly because you don't need brackets and no quotes. What are others opinion about this ? thanks, Stef Mientki class super_list(list): pass def kwadraat ( value ) : return value * value x={} x['frequency']=33 x['functie']=kwadraat print x['functie'](2) y = super_list() y.frequency = 33 y.functie = kwadraat print y.functie(3) From phil at riverbankcomputing.com Fri Mar 28 11:22:06 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Fri, 28 Mar 2008 15:22:06 +0000 Subject: Setting the value of one cell in QTableWidget fills everything. In-Reply-To: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> References: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> Message-ID: <200803281522.07041.phil@riverbankcomputing.com> On Friday 28 March 2008, Constantly Distracted wrote: > I've just started PyQt programming and I've run into this little > problem. When I set the text of one cell in my table, all the other > cells fill with that value. ...because you have only created a single QTableWidgetItem instance, rather than one for each cell. > All I wanted to do was run a loop, printing in each cell the row and > column number. > Here's the code. > > ------------------------------ > > from PyQt4 import QtGui,QtCore > import sys > > class mywindow(QtGui.QWidget): > def __init__(self,parent=None): > QtGui.QWidget.__init__(self,parent) > self.resize(700,700) > self.mytable=QtGui.QTableWidget(7,6,self) > self.mytable.resize(700,700) > > def filltable(self): > items=QtGui.QTableWidgetItem() > for column in range(self.mytable.columnCount()): > for row in range(self.mytable.rowCount()): > items.setText("row: " + str(row) + " column: " + > str(column)) > self.mytable.setItem(row,column,items) > > > app=QtGui.QApplication(sys.argv) > mainwin=mywindow() > mainwin.filltable() > qb.show() > app.exec_() Move the creation of the QTableWidgetItem() to the inner loop (and call it "item" rather than "items"). Phil From george.sakkis at gmail.com Mon Mar 31 18:58:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 15:58:37 -0700 (PDT) Subject: class super method References: Message-ID: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> On Mar 31, 6:25 pm, gigs wrote: > is there any tutorial for super method (when/how to use it)? > > or maybe someone could explain me how it works? > > thx Super is one of the dark corners of the language [1,2]... a good rule of thumb is to stay away from it, or at least stick to its basic usage. George [1] http://www.phyast.pitt.edu/~micheles/python/super.html [2] http://fuhm.net/super-harmful/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Mar 20 08:05:58 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 20 Mar 2008 13:05:58 +0100 Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: <64f296F2b1lqlU1@mid.individual.net> Giampaolo Rodola' wrote: > Is there any way to su or login as a different user within a > python script? I mainly need to temporarily impersonate another > user to execute a command and then come back to the original user. > I tried to google a little bit about it but I still didn't find a > solution. IMHO, the cleanest way from a security perspective would be using sudo. root can even configure it in a way that you don't have to type a password. Regards, Bj?rn -- BOFH excuse #223: The lines are all busy (busied out, that is -- why let them in to begin with?). From gagsl-py2 at yahoo.com.ar Wed Mar 26 00:25:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 01:25:17 -0300 Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk escribi?: >> i'm trying to call subprocess.popen on the 'rename' function in >> linux. When I run the command from the shell, like so: >> >> rename -vn 's/\.htm$/\.html/' *.htm >> >> it works fine... however when I try to do it in python like so: >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) >> >> print p.communicate()[0] >> >> nothing gets printed out (even for p.communicate()[1]) I'd try with: p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (note that I added shell=True and I'm using a raw string to specify the reg.expr.) -- Gabriel Genellina From davids at evertech.com.au Thu Mar 13 18:16:57 2008 From: davids at evertech.com.au (David S) Date: Thu, 13 Mar 2008 22:16:57 GMT Subject: Spaces in path name Message-ID: Hi, I have some code in which I have to change some path names to get it to work. The original code seems to have assumed that path names would not have any embedded spaces. I am not sure how to write the following line so when used in my script the path will be found. ANT_CMD = r'C:\Program Files\apache-ant-1.7.0\bin\ant' Regards, David From davidj411 at gmail.com Wed Mar 5 14:14:10 2008 From: davidj411 at gmail.com (davidj411) Date: Wed, 5 Mar 2008 11:14:10 -0800 (PST) Subject: change user-agent Message-ID: <6a33cbd7-e9a5-475e-a8df-1e68777faaf3@i29g2000prf.googlegroups.com> I came across this post on the net and wanted to know what was meant by down-level module. So, how can we change the User-Agent? If we don't want to change the headers using a lower-level module such as httplib, the solution is quite easy.... From castironpi at gmail.com Sat Mar 29 21:47:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 18:47:26 -0700 (PDT) Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> <3ba288b6-3b34-4362-a9c3-5c6bd489a80c@a1g2000hsb.googlegroups.com> Message-ID: <1e378d28-e4ff-4985-9e2a-806bfd7a4c4b@y21g2000hsf.googlegroups.com> On Mar 29, 7:59?pm, marek.ro... at wp.pl wrote: > I love Paul's response. > > castiro... at gmail.com napisa?(a): > > > > > My crystal ball broke a few days ago due to overuse, but I recall that > OpenGL likes to have power-of-two texture sizes. If that doesn't work, > please trim down your code as far as possible (so that it still > displays the error) and post it. It isn't mine. while 1: it isn't. Try to attach files fail 1. Can link though: any help? From jmcmonagle at velseis.com.au Tue Mar 11 19:33:22 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 12 Mar 2008 09:33:22 +1000 Subject: The stange behaviour of Tkinter.Canvas In-Reply-To: <60bb95410803110404o414ababft8fca994d16cfd60a@mail.gmail.com> References: <60bb95410803110404o414ababft8fca994d16cfd60a@mail.gmail.com> Message-ID: <47D716C2.8040107@velseis.com.au> James Yu wrote: > I tried to update the rectangle on a canvas to get the visual effect of > progressbar. > It works all right if I delete the existing objects (rectangle and text) > and create a new one. > However, if I invoke canvas.itemconfig() to update the existing objects' > options, gui just went nuts. > I am more than happy to receive any help and advise. > Snipped code > canv.itemconfig(rect, width=width*progress/100) ## The width option of a rectangle item does not change the rectangles width, but changes the width of the rectangle perimiter line. You need to modify the coordinates of the rectangle item: canv.coords(rect, 0, 0, width*progress/100, height) Regards, John From bryanjugglercryptographer at yahoo.com Fri Mar 14 18:06:44 2008 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Fri, 14 Mar 2008 15:06:44 -0700 (PDT) Subject: How to send a var to stdin of an external software References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: Floris Bruynooghe wrote: > Benjamin Watine wrote: > > Could you give me more information / examples about the two solutions > > you've proposed (thread or asynchronous I/O) ? > > The source code of the subprocess module shows how to do it with > select IIRC. Look at the implementation of the communicate() method. And here's a thread example, based on Benjamin's code: import subprocess import thread def readtobox(pipe, box): box.append(pipe.read()) cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) myVar = str(range(1000000)) # arbitrary test data. box = [] thread.start_new_thread(readtobox, (cat.stdout, box)) cat.stdin.write(myVar) cat.stdin.close() cat.wait() myNewVar = box[0] assert myNewVar == myVar print len(myNewVar), "bytes piped around." -- --Bryan From gagsl-py2 at yahoo.com.ar Wed Mar 26 14:36:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 15:36:31 -0300 Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson escribi?: > HOw can we use express pointers as in C or python? Traceback (most recent call last): File "", line 1, in File "parser.py", line 123, in parse_text tree = language.parse_text(text) File "english.py", line 456, in parse_text tree = self.parse_sentence(sentence) File "english.py", line 345, in parse_sentence raise ParserError, "can't parse %r" % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' -- Gabriel Genellina From http Sun Mar 2 02:02:13 2008 From: http (Paul Rubin) Date: 01 Mar 2008 23:02:13 -0800 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> <7x3ara9r4n.fsf@ruckus.brouhaha.com> Message-ID: <7xskz98v7u.fsf@ruckus.brouhaha.com> Lie writes: > So basically they refused to satisfy everything that is still possible > individually but would conflict if done together. I can't understand that. > x = 1 > a = x + 1 << decides it's an int No, so far a and x are both Num (indeterminate) > b = x + 1.0 << error? or redefine to be float? This determines that a, b, and x are all floats. It's not "redefined" since the types were unknown prior to this. Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional" which is a narrower class than Num but it could still be Float, Double, or Rational. Nums support addition, subtraction, multiplication, but not necessarily division. So int/int is an error. Fractionals support division. > c = x + 1 << would this cause error while it worked in line 2? No, c is also a float (actually Fractional) > A slightly obfuscated example: > l = [1, 1.0, 1] This is the same as l = [1.0, 1.0, 1.0]. In Haskell, all elements of a list must have the same type, so the 1.0 determines that l is a list of fractionals. > x = 1 > for n in l: > c = x + n Haskell does not have loops, but if it did, all these values would be fractionals. From detlev at die-offenbachs.de Sat Mar 1 08:29:13 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 01 Mar 2008 14:29:13 +0100 Subject: ANN: eric 4.1.1 released Message-ID: Hi, eric4 4.1.1 has been released today. This release fixes a few bugs reported since the last release. As usual it is available via http://www.die-offenbachs.de/eric/index.html. Please note, that the first stable release of the Rope refactoring plugin was released as well. What is eric? ------------- Eric is a Python (and Ruby) IDE with all batteries included. It is expandable via a plugin architecture. These plugins are downloadable separately. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From grante at visi.com Sun Mar 9 00:29:42 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:29:42 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> <13t6s8pk90olef8@corp.supernews.com> Message-ID: <13t6te6p71r3u3e@corp.supernews.com> On 2008-03-09, Steven D'Aprano wrote: >> The only times I can recall printing source were in college >> classes where I was required to hand in a hardcopy with the >> assignment and code samples for job interviews. In the real >> world the code base tends to be too huge to contemplate >> printing... > > You've never (say) printed out the source code to one of the > modules in the Python standard library to read and study? Nope. Can't say that I have. I can't really recall printing out a source file in the past 10-15 years. > If your code base is so huge that you can't print out any > meaningful piece, then you desperately need more > encapsulation. >> Even in the early 1990s the moral equivalent of enscript (I think it was >> a2ps) worked just fine for printing with filenames, line/page numbers, >> and other niceties no matter what editor you used. It seems more >> reasonable to mandate using a sane print tool for the odd case where >> someone wants to print things out than to mandate cluttering up every >> file with the filename in a comment. > > Sure, but really, adding ONE LINE to the start of a file is > hardly "cluttering up" anything. Especially if it is in the > doc string, like this: > > """widgets.py: create, manage and destroy widgets. > > blah blah blah blah...""" The bad part is that it's redundant information. That means that eventually, it's going to be wrong. -- Grant Edwards grante Yow! I'm young... I'm at HEALTHY... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From martin at v.loewis.de Mon Mar 3 01:44:57 2008 From: martin at v.loewis.de (=?windows-1252?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2008 07:44:57 +0100 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> Message-ID: <47CB9E69.9000709@v.loewis.de> >> Assuming no major problems crop up, a final release of Python 2.4.4 will >> follow in about a week's time. > > I do suppose you mean 2.4.5. Oops, yes. > 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: > > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp > -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. > -I./Include -DPy_BUILD_CORE -c ./Modules/posixmodule.c -o > Modules/posixmodule.o > ./Modules/posixmodule.c: In function ?posix_setpgrp?: > ./Modules/posixmodule.c:3145: error: too few arguments to function > ?setpgrp? > make: *** [Modules/posixmodule.o] Error 1 > > I can only presume I'm doing something wrong at this point, since I > don't consider myself a Mac OS X developer. No. 2.4.5 just won't compile on OSX 10.5.2. This bug has been fixed for 2.5 (IIUC), but the fix was not backported (nor should it be, as it is not relevant for security). Use OS X 10.4 if you want to use Python 2.4. Regards, Martin From http Sun Mar 9 00:35:51 2008 From: http (Paul Rubin) Date: 08 Mar 2008 21:35:51 -0800 Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> Message-ID: <7xy78sv4qw.fsf@ruckus.brouhaha.com> Chick writes: > I'm writing a security tool which requies wiping off the memory of > certain string after being used, which I've done by implementing it as > a mutable list as follow: You really can't do that reliably in Python and for that matter you can't really do it reliably in any other language, without OS and possibly hardware assistance to make sure the password isn't paged or swapped, etc. In Linux, for example, see the mlock system call. From ptmcg at austin.rr.com Sat Mar 29 20:48:21 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 29 Mar 2008 17:48:21 -0700 (PDT) Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: On Mar 29, 6:37?pm, castiro... at gmail.com wrote: What is the collision of spheres? Is it the melding of a sphere of influence and cosmic sphere? What does it mean to say that such a collision "doesn't work"? The sphere is the optimal solid for storing the maximum volume in the minimum area. A sphere can retain the most heat, with minimum surface area for radiation or conduction, convection of course being dependent not only on surface area but also ambient flow of surrounding conducting fluid if such flow is laminar with respect to Reynold's magic number not to be confused with the numbers of a magic square, which is a two-dimensional shape is there a determination of the collision of a sphere's projection onto a plane with a square on that same plane. I've had it with these MF'in squares on this MF'in plane! --------------------------------- More than iron, more than lead, more than gold I need electricity. I need it more than I need lamb or pork or lettuce or cucumber. I need it for my dreams. From python.list at tim.thechases.com Sat Mar 8 12:57:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 08 Mar 2008 11:57:07 -0600 Subject: Intelligent Date & Time parsing In-Reply-To: <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> Message-ID: <47D2D373.5040600@tim.thechases.com> > I am a GNU newbie. (I know C &o.) Can you point me to a > place to find the source for 'date'? It's part of the GNU Coreutils: http://ftp.gnu.org/gnu/coreutils/ Within the file, you're likely interested in lib/getdate.* It helps if you have a working knowledge of Yacc. -tkc From Lie.1296 at gmail.com Sun Mar 30 14:07:41 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 11:07:41 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> Message-ID: On Mar 30, 5:25 pm, Bjoern Schliessmann wrote: > Lie wrote: > > Ah yes, that is also used (I completely forgot about that one, my > > math's aren't that sharp anymore) and I think it's used more > > frequently than ><. > > Where did you read that (I mean, which country)? I've never seen > this sign in any german or english book on > mathematics/physics/engineering I saw. It was in my elementary school at Indonesia (FYI, it is also used as antonym sign in languages (at least in my country)). And I think I'll retract that claim, >< wasn't the standard, a crossed = is the standard (btw, with a little imagination != looks like a crossed =). From paul at boddie.org.uk Sun Mar 30 14:35:37 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Mar 2008 11:35:37 -0700 (PDT) Subject: html DOM References: Message-ID: <374dfd0b-b2f6-418b-b052-94c802bac639@d4g2000prg.googlegroups.com> On 30 Mar, 01:09, "Sam the Cat" wrote: > Is there a package that would allow me the same or similar functionality for > modifying html code via the DOM model as I have in JavaScript ? I'd like to > parse an html file, then modify it and save the result. You could try libxml2dom which has an HTML parsing mode (like lxml and other solutions based on libxml2): http://www.python.org/pypi/libxml2dom It attempts to provide a DOM API very much like that used by JavaScript implementations. Paul From testone at gmail.com Tue Mar 25 13:00:41 2008 From: testone at gmail.com (Tess) Date: Tue, 25 Mar 2008 10:00:41 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> <34b46ea7-7c87-4742-9d67-0a39e5daf983@e23g2000prf.googlegroups.com> <4e3f9a3d-bf3f-479e-a00d-37a00f95133e@m44g2000hsc.googlegroups.com> Message-ID: Paul - you are very right. I am back to the drawing board. Tess From sjmachin at lexicon.net Tue Mar 25 20:45:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Mar 2008 11:45:13 +1100 Subject: My python interpreter became mad ! In-Reply-To: <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> Message-ID: <47E99C99.2060401@lexicon.net> Furkan Kuru incorrigibly top-posted: > Ok, you're right. > > but I did not give it a chance "not trying python interpreter in another > directory" I don't understand that sentence. > so if we assume the problem exists in every directory, it has something > to do with pythonpath. Why would/should we assume that? > you can try setting pythonpath to some directory and put a re.py there > and try from any directory starting your interpreter and importing re. and achieve the same result: importing the bogus re. What's your point? > > > > On 3/25/08, *John Machin* > wrote: > > Furkan Kuru top-posted: > > Most probably X-Spam added itself to your path. > > What is "X-Spam"? Added itself to Benjamin's path [not mine] in such a > fashion that it is invoked when one does "import re"? > > > you should look at your PATH and PYTHONPATH environment variables. > > Most *IM*probably. Read the traceback: > """ > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > """ > > This is a classic case of a script (which does not guard against side > effects (like spewing out gibberish) when imported instead of being > executed) being given the same name as a Python-included module and > being executed in the current directory and hence ends up importing > itself. > > > > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > > > >> wrote: > > > > On Mar 25, 10:05 pm, Benjamin Watine > > >> wrote: > > > Yes, my python interpreter seems to became mad ; or may be > it's > > me ! :) > > > > > > I'm trying to use re module to match text with regular > > expression. In a > > > first time, all works right. But since yesterday, I have a > very > > strange > > > behaviour : > > > > > > $ python2.4 > > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > > Type "help", "copyright", "credits" or "license" for more > > information. > > > >>> import re > > > X-Spam-Flag: YES > > [snip] > > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > > > >>> > > > > > > What's the hell ?? I'm just importing the re module. > > > > No you're not importing *the* re module. You're importing *an* re > > module, the first one that is found. In this case: your own > re.py. > > Rename it. > > > > > > > -- > Furkan Kuru From siona at chiark.greenend.org.uk Fri Mar 7 07:32:47 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Mar 2008 12:32:47 +0000 (GMT) Subject: for-else References: Message-ID: Jeffrey Barish wrote: >Terry Reedy wrote: >> A for-loop is equivalent to a while loop with the condition 'iterator is >> not exhausted'. ?So do_else when that condition is false -- the iterator >> is exhausted. >I think that this is the most important statement in this thread. As others >have expressed, I too found for-else surprising when I first encountered >it. It made sense to me when I analogized for with if: [ ... ] And to pull those two together, I found while-else comprehensible by analogy with if-else: while stmt: do_something() # stmt is True else: do_something_else() # stmt is False I don't think I've ever used a for-else in the wild, but I have used while-else. And knowing how that works, it's kind of obvious what for-else does. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From jari.aalto at cante.net Fri Mar 7 19:49:56 2008 From: jari.aalto at cante.net (Jari Aalto) Date: Sat, 08 Mar 2008 02:49:56 +0200 Subject: distutils - Is is possible to install without the .py extensions References: Message-ID: * Fri 2008-03-07 Robert Kern gmane.comp.python.general * Message-Id: fqsf3a$4lv$1 at ger.gmane.org > Jari Aalto wrote: >> #!/usr/bin/python >> >> from distutils.core import setup >> import glob >> >> setup(name='program', ... >> scripts = ['program,py'], >> ) >> that the the result is: >> >> /usr/bin/program >> >> instead of: >> >> /usr/bin/program.py > > The easiest and best way is to just rename the file in your source tree to > "program" and be done with it. Is there any other way? This is the source package that I would like to keep intact and just patch the setup.py Jari -- Welcome to FOSS revolution: we fix and modify until it shines From wbsoft at xs4all.nl Mon Mar 10 16:26:52 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Mon, 10 Mar 2008 21:26:52 +0100 Subject: building arbitrary files with distutils? Message-ID: <200803102126.53397.wbsoft@xs4all.nl> Hi all, I want to convert a python project from Makefiles to distutils. Currently the makefiles perform some tasks like building a PNG icon from a SVN file etc. How can I add such commands (including timestamp checking) to a setup.py file, so that it runs when I call 'python setup.py build' ? I can write python functions to perform those command, and I found timestamp checking functions in distutils.dep_util, but just can't find the way to connect such commands to the build step.... w best regards, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi From fn681 at ncf.ca Sun Mar 30 10:45:51 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 30 Mar 2008 10:45:51 -0400 Subject: Why prefer != over <> for Python 3.0? In-Reply-To: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: kwitters at telenet.be wrote: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? > > I've written an article about it to try and save this nice "is not > equal" operator, located at http://dewitters.koonsolo.com/python_neq.html > > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). Algol 60 had no such operator. Algol-W had (not)= [(not) was a negative symbol, not on our current keyboard] Simula 67 introduced <> Pascal uses <> [Pascal is still available - http://www.freepascal.org/] C uses != [http://cermics.enpc.fr/~ts/C/CONCEPT/expressions.html#rel] I prefer <> but I feel that it's better not to have two ways of representing not equal. The powers that be have chosen !=. I accept this on the grounds that current languages seem to have nade that choice. Colin W. From kaushikbarat at gmail.com Mon Mar 3 11:50:33 2008 From: kaushikbarat at gmail.com (kaush) Date: Mon, 3 Mar 2008 08:50:33 -0800 (PST) Subject: urlsafe_b64decoding of xml node text Message-ID: <262999b2-352e-4739-9c7f-050fce38f39b@i7g2000prf.googlegroups.com> Hi All, I am running Apache with mod_python. A post message to my server contains an xml of the form
(some base64 ur-safe-encoded data) I use minidom to parse the xml posted, and now try to decode the data using the following import minidom import base64 decData = base64.urlsafe_b64decode(data) #data is the above mentioned url-safe-encoded data This line fails with the following error Error : Error : character mapping must return integer, None or unicode Error : If i run the same data through a script on the terminal, I am able to successfully decode the data. What could be the reason for this error? Can it be because of some encoding introduced by minidom? I think urlsafe_b64decode takes ascii string. Thanks, Kaushik From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 07:16:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 12:16:14 -0000 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> Message-ID: <13t2cget4hubma9@corp.supernews.com> On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote: > you > could say exec( open( 'modA.py' ).read() ) ==> import modA Yes, you could say that, but you'd be wrong. Please test your code before making such claims in the future. -- Steven From duncan.booth at invalid.invalid Wed Mar 19 05:56:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 09:56:31 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> <4e740d0f-9b1d-4b1d-9f6b-8bd56ea11a65@z38g2000hsc.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > I am puzzled by the failure on 'a in a' for a=[a]. >>> a== [a] also > fails. Can we assume/surmise/deduce/infer it's intentional? > It may be less confusing if instead of an assignment following by a test you just consider doing the test at the same time as the assignment (then again it changes the behaviour so it may just be more confusing). There is a very limited set of values for which you would expect this output: >>> a==[a] True >>> a in [a] True The most obvious one is a simple recursive list: >>> a = [] >>> a.append(a) >>> a==[a]; a in [a] True True Pushing the recursion down a level breaks some of the comparisons: >>> a = [[]] >>> a[0].append(a) >>> a==[a] Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp >>> a in [a] True >>> a in a Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp which may be considered a bug or possibly it is just a limit of the implementation. This also produces an overflow (in fact I think it is just the same situation as above, recursing on the same list is handled, recursing on different but equivalent lists is not): >>> a = []; a.append(a) >>> b = []; b.append(b) >>> a==b Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp From Lie.1296 at gmail.com Sun Mar 30 13:31:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 10:31:14 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <5f474aef-26af-475f-81f2-d062129d927b@c19g2000prf.googlegroups.com> On Mar 30, 10:28 pm, "D'Arcy J.M. Cain" wrote: > On Sun, 30 Mar 2008 08:16:39 -0700 (PDT) > > iu2 wrote: > > > > I'd like to use Python in a commercial application. In fact I would > > > > like to write the application entirely in Python. > > > > But I think I wouldn't like telling what language the application is > > > > written in. > > > > Why is the reason for that? > > > Due to Competitors... I don't want to expost the language I use > > You might hide it from many of your customers but don't count on hiding > it from your competitors. Chances are, if they don't know it because > they just don't care. Even if you create your program in C, it is always possible (for an advanced user/determined competitor) to guess what language (compiler) you're using. And I haven't even mentioned that you can guess Windows Defender is created using Visual Basic Classic (VB6) because one of its windows still use VB6's default icon. There are cues that could hint what language is used to create a program: default icons (e.g. VB6's default icon), interface widgets (notoriously Java's Swing), PEID (which is quite reliable although you could manipulate it), the name (e.g. CPython), included libraries, libraries used (e.g. MSVCRT), etc. And I can't see any obvious advantage you could get by hiding the language you use from your competitors, it isn't like they would switch their language to your language if they can't catch up with you, and they can't anti-advertise you because of the language you used. > I intend to use pyinstaller, so there is no .pyc at all. > The main problem is when I use small programs (as single EXE) sent to > someone as a means of maintenance or debugging. > Sending Python's license file together with one EXE seems to me too > obvious AFAIK (__someone please confirm this__) you don't need to include Python's license in your program, unless you distribute Python's binary/source code (i.e. The Python Interpreter and Friends) in your program. So if you're sending a small program for maintenance or debugging since you don't need to include the Python Interpreter (you assumed that there is already one in the machine) you don't need to include the license. You might need to include the license if the maintenance program is for updating the Python Interpreter though. From __peter__ at web.de Sat Mar 8 11:32:15 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Mar 2008 17:32:15 +0100 Subject: extract multiple ranges from a list References: Message-ID: pi.arctan at gmail.com wrote: > One of my many project involves working with YUV-files, where I need > to reduce > the vertical resolution with a factor of two, i.e. remove every other > scan line. > Today I'm using two for-loops in the fashion shown below > > y = [] > for i in range(0, width*height, width*2): > for j in range(0,width): > y.append(Y[i+j]) > > This approach doesn't feel very pythonic but I can't come up with a > better idea to do it. > I've tried list comprehension and map together with lambda but I can't > get a flattened list > of every other scan-line... > > CIF = 352x288 items for luminance and the aim is to have the list > below: > y = [0:352 704:1056 ... ] >>> width = 3; height = 5 >>> Y = range(width*height) >>> y = [] >>> for i in range(0, width*height, 2*width): ... y.extend(Y[i:i+width]) ... >>> y [0, 1, 2, 6, 7, 8, 12, 13, 14] Probably more efficient, but needs numpy: >>> import numpy >>> width = 3 >>> height = 5 >>> Y = range(width*height) >>> a = numpy.array(Y).reshape(height, width) >>> a array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) >>> b = a[::2] >>> b array([[ 0, 1, 2], [ 6, 7, 8], [12, 13, 14]]) >>> list(b.reshape(len(b)*width)) [0, 1, 2, 6, 7, 8, 12, 13, 14] Peter From castironpi at gmail.com Wed Mar 5 16:49:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 13:49:20 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> Message-ID: > > > > What is a class that is not a module? > > > I'm willing to address convention, in serial or parallel--- (change > > subject to 'what goes on newsgroups'?), but it's not clear from fact > > what assumption who has made. > > Since you did not elaborate on what your efforts were and the extent > they were undesirable (certainly useful info from someone honestly > interested in a helpful answer), I assumed you had made none. I agree. To one of my friends, there's plenty of information in the context that isn't a newsgroup. So I'll state more about my background. Classes and modules are really similar. In Python they're really *really* similar. Actually, at this point, that observation may have more of a subjective component than I'm used to asserting. I pause here for corroboration and others' perspectives. Aren't they? From exarkun at divmod.com Mon Mar 31 13:41:32 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 31 Mar 2008 12:41:32 -0500 Subject: Newbie Question - Overloading == In-Reply-To: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: <20080331174132.6859.253250024.divmod.quotient.24792@ohm> On Mon, 31 Mar 2008 10:23:24 -0700 (PDT), xkenneth wrote: >So i generally write quite a few classes, and in most I need to >overload the == operator. > >If i have two classes, like below: > >Class A: >attribute a >attribute b > >Class B: >attribute a >attribute c > >So if I've overloaded their respective __eq__ functions, and I want to >test whether or not the individual classes attributes are equal, the >code might look something like this: > >class A: > def __eq__(self,other): > return self.a == other.a and self.b == other.b > >class B: > def __eq__(self,other): > return self.a == other.a and self.c == other.c > >Now obviously, if I test an instance of either class equal to each >other, an attribute error will be thrown, how do I handle this? I >could rewrite every __eq__ function and catch attribute errors, but >that's tedious, and seemingly unpythonic. Also, I don't want an >attribute error thrown whenever two classes are compared that don't >have the same attributes. > >I have a sneaky feeling I'm doing something completely unpythonic >here. Give this a look: http://jcalderone.livejournal.com/32837.html Jean-Paul From ggpolo at gmail.com Sat Mar 8 07:16:41 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 8 Mar 2008 09:16:41 -0300 Subject: Timed execution in eval In-Reply-To: <13t3f4u6vb77qf3@corp.supernews.com> References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> Message-ID: 2008/3/7, Steven D'Aprano : > On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote: > > > I have various bits of code I want to interpret and run at runtime in > > eval ... > > > I hope that code doesn't contain any data coming from an untrusted user. > > > > > I want to be able to detect if they fail with error, > > > That's what try...except blocks are for. > > try: > x = eval('1 + 1 = 2') > except SyntaxError: > x = 3 > > > > > I want to be able to time them, > > > That's what the timeit module is for. > > If you do time them, you will find that eval(expr) is MUCH MUCH slower > than just executing expr as normal. > > >>> from timeit import Timer > >>> Timer('1+1').timeit() > 0.25557518005371094 > >>> Timer('eval("1+1")').timeit() > 21.816912174224854 > > If you use eval() a lot, you will have a SLOW program. > > > > > and I want to be able to stop them if they run too long. > > > That's tricky. As far as I know, the only way for a Python program to > stop an arbitrary calculation after a certain period of time it to run it > in a thread. You then monitor the elapsed time, and when the timer > expires, ask the thread to die. And hope it listens. > Or you could use setitimer (not available for now). I opened an issue at roundup to add setitimer and getitimer wrappers to the signal module. It would be great if you could test on your platform. It was done for py3k, but could easily be back ported to python 2.6. http://bugs.python.org/issue2240 > > > > I cannot add code to the eval'd strings that will help me accomplish > > this. > > > You can't? Why ever not? > > Note: that's almost certainly the wrong way to solve your problem, but > I'm curious as to why you can't. > > > > -- > > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From mensanator at aol.com Mon Mar 31 13:13:17 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 31 Mar 2008 10:13:17 -0700 (PDT) Subject: troll poll References: Message-ID: On Mar 31, 12:04?pm, "Daniel Fetchinson" wrote: > [Heavily off-topic fun stuff] > > Hi folks, > > This is a quick poll to have scientific data on our beloved troll community: > > Whose trolling behaviour is more professional? (check one) > > [ ?] - Xah Lee > [ ?] - castironpi > > More specifically, who can create a bigger mess on c.l.py? (check one) > > [ ?] - Xah Lee > [ ?] - castironpi > > More specifically, who is more entertaining? (check one or none) > > [ ?] - Xah Lee > [ ?] - castironpi > > Even more specifically, who makes you laugh harder? (check one or none) > > [ ?] - Xah Lee > [ ?] - castironpi > > Thanks for your feedback! > > [/Heavily off-topic fun stuff] Aren't you making the rather naive assumption that people read this stuff? From michael.wieher at gmail.com Sun Mar 16 10:40:07 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:40:07 -0500 Subject: Pycon disappointment In-Reply-To: <1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> Message-ID: 2008/3/16, Aaron : > > > > In my opinion, open spaces should have had greater status and billing, > > with eyes-forward talks and vendor sessions offered only as possible > > alternatives. Especially, vendor sessions should not be presented as > > "keynotes" during plenary sessions. I think it took a little while > > for people to catch on to the idea that they could have control of > > their own experience through the open spaces and that the main > > offerings were not the only option. > > This is an excellent suggestion and observation. Sold sponsorships > are fine as long as they are billed as such. Labels on the vendor > speeches indicated they were sold as ad space would be great, as well > as more strongly emphasizing the ad hoc discussion spaces. But vendors often don't label themselves as vendors. And often, the researcher or individual in question, who has something worth saying, does have a professional job of sorts, which might be related to his or her work or speech. I've heard people give very long, detailed talks about interesting topics, that did have a spin on them, but contained worthwhile information also. Now, is that to be billed as a "vendor" (and ignored) or not? Further, no vendor who is trying to sell a product will allow themselves to be marked in an obvious way as advertising, knowing that they'll be ignored. At least, they certainly won't pay for the time/space to any real degree, knowing they'll be walking in under a cloud like that. -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurent.pointal at laposte.net Mon Mar 31 12:07:38 2008 From: laurent.pointal at laposte.net (Laurent Pointal) Date: 31 Mar 2008 16:07:38 GMT Subject: Where can I find : References: Message-ID: <47f10c4a$0$906$ba4acef3@news.orange.fr> Le Sat, 29 Mar 2008 20:15:59 -0700, pythonnubie a ?crit?: > Hi All : > Does anyone know where I can find either a book or a website that > explains beginning python by actually building a project line by > line and explaining it indepth . I am primarily interested in > understading flowcontrol as well as syntax . > > If it was related to netwoprking then that would be a great addition > although not required because that is my primary field of interest . > > All help greatly appreciated ! > > Mark You may look at "Dive into Python", there is an online version, translation in some languages other than english (if needed). It propose a line by line explanation on many scripts targetting language and libraries usage. http://www.diveintopython.org/ -- Laurent POINTAL - laurent.pointal at laposte.net From aboudouvas at panafonet.gr Thu Mar 20 18:57:13 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 20 Mar 2008 15:57:13 -0700 (PDT) Subject: What is The Eric4 IDE??? References: Message-ID: <7c7752c7-660e-4d48-8bb6-82f326b52644@u10g2000prn.googlegroups.com> I use it for some time now and i think it is the best Python IDE out there, especially if someone wants to "play" with Qt. If you are on Windows, just install the Windows binary, it' all there! From justdelegard at gmail.com Thu Mar 27 10:19:51 2008 From: justdelegard at gmail.com (Justin Delegard) Date: Thu, 27 Mar 2008 10:19:51 -0400 Subject: dynimac code with lambda function creation Message-ID: <47EBAD07.9010603@gmail.com> So I am trying to pass an object's method call to a function that requires a function pointer. I figured an easy way to do it would be to create a lambda function that calls the correct method, but this is proving more difficult than I imagined. Here is the function I'm using: def objectMethodCallerFunctionCreator(testerObj, method): exec("y=lambda x: testerObj."+method+"(x)") return y Where testerObj is an instance of an object, and method is a string representing the method to call. The problem is, when I actually run the function created (y in this case), it tells me it can't find the symbol testerObj in the global scope. I have successfully created similar functions, except without using the exec() call. e.g. def functionCreator(a, b, c): return lambda d: myFunc(a, b, c, d) and it doesn't complain about the variables a, b, or c when being run. I am assuming this is happening because of the exec() call, but I don't see another way of calling a variable method on an object. Is there some other way to do this that I'm missing? I tried passing in 'method' as a function pointer (to the method of the object), but that didn't work either. Thanks, Justin From deets at nospam.web.de Thu Mar 13 12:09:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 17:09:26 +0100 Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> Message-ID: <63t1tnF29egotU1@mid.uni-berlin.de> azrael wrote: > A little problem. > > Can I directly show Pil objects "image.open("bla.jpg") in Wx or do I > have to transform them. > > If I have to transofm them How can I do it. Pixel by pixel or is there > somethin built in in pil or wx or python. > pilj->wx and wx->pil. PIL doesn't depend on wx, so if anything then wx knows about PIL. But I doubt it. Instead, use cStringIO and save a PIL-Image to memory, then use that as file-argument to something that works for wx - no idea what, but there should be means to load JPEGs and so forth. If file-objects aren't enough, create a temp-file. No, that's not to slow. Diez From castironpi at gmail.com Tue Mar 4 13:11:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:11:03 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: <8d7c34f6-83c5-4c39-8966-56ce141e62f3@s12g2000prg.googlegroups.com> On Mar 4, 10:50?am, Lie wrote: > On Mar 4, 1:12?pm, Mensanator wrote: > > > > > > > On Mar 3, 11:58?pm, Erik Max Francis wrote: > > > > Mensanator wrote: > > > > While we're on the subject of English, the word "worthless" > > > > means "has no value". So, a program that doesn't work would > > > > generally be "worthless". One that not only doesn't work but > > > > creates side effects that cause other programs to not work > > > > (which don't have bugs) would be "worse than worthless". > > > > All programs have bugs, which means that in some circumstances, they > > > won't work. ? > > > And in such circumstances, would be worthless. > > > > Therefore, by your reasoning, all programs are worse than > > > useless. > > > That doesn't follow from my reasoning. > > > Suppose you downloaded a new calculator program that > > couldn't add properly. That would be useless to you, right? > > > But suppose the program contained a virus that erased > > your hard drive. That would be "worse than useless", wouldn't it? > > > > > I'm not hard to please at all. > > > > No, of course not, since logically you must think all software is useless. > > > Somehow, I expected better logic from people who call themselves > > programmers. > > Mensanator, for alls sake, you've done right by pointing out the bug > instead of muttering silently in your room, but there is a thing > called tolerance that you really should learn, it's about tolerating > and understanding the possibility that other people are humans too and > humans create mistakes, lots of them in fact and that includes you (if > you're humans). Along with tolerance should come a better choice of > wordings, instead of saying "it sucks because it does something > unexpected and unwanted" and telling everyone not to use it, you could > just say "it does something unexpected and unwanted" and say that you > wanted it fixed. It's not that you've done anything wrong, but it's > about your attitude.- Hide quoted text - > > - Show quoted text - All of your statements were true. You expressed your emotions, your observations, and desire. You corrected statements incorrect that others made earlier. Others gave you orders, their observations of your character, and expressed their emotions. Now keep your noses in the keyboard and simmer down. I won't stand for this. From cwitts at gmail.com Wed Mar 12 17:28:15 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 14:28:15 -0700 (PDT) Subject: Different results when running script from IDLE versus Command Line References: <895b88e4-694d-4fee-a633-08aa8a407999@p73g2000hsd.googlegroups.com> Message-ID: On Mar 12, 8:10 pm, Casey T wrote: > Hi, > > I'm new to Python and I'm having some problems with getting different > results from my script when I run it from IDLE versus just double- > clicking the .py file and having it run through the command line. > Basically, my script reads some CSV files, assembles a text files, > then uploads that test file to an ftp site. When I run the script from > IDLE, everything works fine. But when it runs from the command line, > the file that gets uploaded is empty. It seems that it is creating a > new file to upload, rather than using the existing file (or at least > that's what I think is going on.) Below is my script. I apologize for > any ugly code. Thanks for your help. > > import sys,os,linecache,csv,ftplib,time > > starttime = time.time() > > #******* > #Summary file assembling > #******* > currentdir = "//folder/" > > reg_sum = open('reg_sum.txt','w') > reg_sum.close > > for files in os.listdir(currentdir): > reg_file = csv.reader(open(currentdir + files)) > for row in reg_file: > reg_sum = open('reg_sum.txt','a') > reg_sum.write(",".join(row) + ',\n') > > reg_sum.close > > #******* > #Summary file processing > #******* > coordList = [ > ["F10",40.0053,-75.0927], > ["T10",40.0272,-75.1123], > ["D22",39.9811,-75.0998], > ["P02",40.0437,-75.0217], > ["D68",39.9203,-75.1388], > ["D51",39.9534,-75.1405], > ["S43",39.9217,-75.2275], > ["S33",39.9360,-75.2077], > ["S42A",39.9215,-75.1937], > ["S05",39.9617,-75.1782], > ["T14",40.0165,-75.1077]] > > coordList_index = > ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"] > #coordList_index is a list containing > > in_text = open('reg_sum.txt','r') > > out_text = open('reg_out.txt','w') > out_text.close > > out_text = open('reg_out.txt','a') > > for line in in_text: > split_line = line.split(',') > if (split_line[0]) in coordList_index: > i = coordList_index.index(split_line[0]) > coords = str(coordList[i][1]) + "," + str(coordList[i][2]) > last_update = str(split_line[2]) > print str(split_line[0]) > if split_line[1] == "1": > out_text.write(split_line[0] + "
,Test1: " + last_update + > "," + coords + ",1" + "\n") > elif split_line[1] == "0": > out_text.write(split_line[0] + "
,Test2.
Last updated: " > + last_update + "," + coords + ",0" + "\n") > else: > out_text.write(split_line[0] + "
,No data.," + coords + > "\n") > > in_text.close > > ###******* > ###Uploads file via FTP > ###******* > s = ftplib.FTP('ftp.blah123.org,'user','pass') > > f.open('reg_out.txt','r') > s.storlines('STOR reg_out.txt', f) > > f.close() > s.quit() > > print "Processed in " + str(((time.time() - starttime) / 60) *60) + " > seconds!" #prints elapsed time You never closed your file. file_object.close try adding '()' at the end of your close calls. As to why it differs, I can't think offhand why it wouldn't. From tjreedy at udel.edu Wed Mar 5 16:17:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Mar 2008 16:17:32 -0500 Subject: Def generating a function to be ran in another context References: <1e5bcefd0803051218q1e73cea2m600ea73098171431@mail.gmail.com> Message-ID: "Marcelo de Moraes Serpa" wrote in message news:1e5bcefd0803051218q1e73cea2m600ea73098171431 at mail.gmail.com... | I'd like a certain function to generate a method for another class and this | new method to be called in the context of the "new" class. Is it possible | with Python? Yes. (Assuming I understand your question correctly.) From castironpi at gmail.com Sun Mar 16 21:22:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 18:22:08 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> <1befdccf-2efc-4640-bcf8-b4a792d8e646@i29g2000prf.googlegroups.com> <5782d52d-0f8c-42b8-9ccc-7445616e5717@u10g2000prn.googlegroups.com> Message-ID: <03d7cf0f-3ae4-4510-9147-6fb9499907c8@b64g2000hsa.googlegroups.com> > > > The trick in the case of when you do not want to guess, or the choices > > > grow too much, is to ask the user to tell you in what format they want > > > it and format according to their wishes. > > > > Neatly avoids too much guessing and isn't much extra to add. > > > The plot is about understanding input, not formatting output. > > And what he meant is simply to make an agreement with the user on how > he/she would format his/her input and to disallow input from formats > that haven't been agreed to avoid guessing. That is the cleanest and > most polite solution, although I'd suspect it would be considered less > user friendly by regular user although power user would be most happy > with that. This one comes from signal theory, actually. With no information about the signal's transmitter, there's no way to guess what language/ customs/manners/convention/protocol he's using. That is, for every protocol, there exists a second protocol which mimics it for the first n bits with a different meaning. There's the Gettysburg Compression Method which transmits a '1' to send the Gettysburg Address, and prepends a 0 to every other message. Of course, there is already an agreed convention. You can tell if you speak a stranger's language once you start interacting-- that is, enter a verbal context with him. There aren't any two -existing- languages which overlap for long at all. 'Can you buy me beer?' does not mean anything in anything but English-- it's gibberish in every other. When it comes to computers, the bandwidth and context mass might be so tiny so far that there's much ambiguity. "Is 11/30 a fraction, a month, or a date?" -"Fraction." "Please proceed." Outside of those two factors, there is not much difference between "natural" and formal systems. Bandwidth is easy enough to increase-- just add a camera, a mic, chemovoltaic, tactilevoltaic, or some specialization of one. Context is the hard thing to grow. "Or, is there another protocol I can look up?" -"Yeah, I know the bartender." "Your statement changed context-determined probabilities. Your own context has been forked." "Your statements have suggested that you have adopted a new convention which I recognize. Is APR 03 a month or a finance model? (You nor the convention neither use statements with the form Apr 03 to mean days.)" -"*plonk*" "You seem to maintain that there are no other users and/or that you have unlimited property right." -"*crowbar*" "This action will void the warranty. Continue?" -"*incendiaries*" "We're just glad you're not organize enough to boycott." -"*boycotts*" "Your usage of that term is inconsistent. Please purchase higher bandwidth." -"*speechless*" "What are you doing, Dave?" -"I won't stand for this." "What are you saying?" From http Wed Mar 5 14:52:38 2008 From: http (Paul Rubin) Date: 05 Mar 2008 11:52:38 -0800 Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: <7xlk4x6j95.fsf@ruckus.brouhaha.com> gideon writes: > In the context of a master's thesis I'm currently looking into > Python's operational semantics. Even after extensive searching on the > web, I have not found any formal model of Python. Therefore I am > considering to write one myself. I doubt if anything serious has been done in that area, and I don't think Python culture operates like that very much. Python programming tends to use informal processes with a lot of reliance on test-driven development and unit tests, rather than formal specifications. A lot of the operational behavior that people rely on basically comes from accidents of implementation, e.g. file descriptors being closed automatically when the last reference goes away. But of course that should not be included in a formal semantics, yet that means the semantics wouldn't describe actual production programs out there. From pydecker at gmail.com Sat Mar 1 21:58:54 2008 From: pydecker at gmail.com (Peter Decker) Date: Sat, 1 Mar 2008 20:58:54 -0600 Subject: Where's GUI for Python? In-Reply-To: <62tvhmF256jk7U1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: On Sat, Mar 1, 2008 at 3:35 PM, K Viltersten wrote: > I'm certain there is an API for creating > GUI's but as far i can find it in the > http://docs.python.org/tut/tut.html > the only "gui" is in "Guido". Check out Dabo: http://dabodev.com It uses the wxPython UI toolkit, but wraps it in a much more Pythonic API. I've been using Dabo for over a year, and it rocks!! -- # p.d. From deets at nospam.web.de Sat Mar 29 09:46:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 14:46:18 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <87d4pe9caz.fsf@mulj.homelinux.net> References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> Message-ID: <656vhnF2e9ao7U1@mid.uni-berlin.de> Hrvoje Niksic schrieb: > "Diez B. Roggisch" writes: > >>> systems. (In theory, file input/output should also be available as >>> asynchronous code, but async IO is low-level and not available in >>> Python.) While threads shouldn't be considered a replacement for >> I suggest you tell that the twisted-guys. And the ones from the >> built-in asyncore-module. > > Note that I said "*file* input/output". Twisted and asyncore are > about asynchronous socket programming that polls over nonblocking file > descriptors such as found in socket programming, not about wrapping > aio(3) and the equivalent Windows APIs. I admit glossing over the file-input - however this is available on posix-systems using the select-module. So if I were in nitpicking-mood, your assertion still would be false - albeit having to consider platoform dependencies certainly is unfortunate and could be considered "missing". I'm pretty sure though that tiwsted & asynchore don't poll, but instead use the select-module. Which at least for unix (and AFAIK for Windows as well) is asynchronous - you get notified if data arrives or has been transmitted, and otherwise your process sleeps. Diez From adrianbn at gmail.com Mon Mar 17 17:16:16 2008 From: adrianbn at gmail.com (=?ISO-8859-1?Q?Adri=E1n_Bravo_Navarro?=) Date: Mon, 17 Mar 2008 22:16:16 +0100 Subject: Comunicate processes with python Message-ID: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> Hi, let me introduce ourselves first. We are a smallish group of students working on a open source snapshot/backup system (www.hdlorean.com or http://launchpad.net/hdlorean). We are using python for almost all of the code and for all of us this is the first python project we develop. At this point I must say that we are really happy with python, as it is a fast learning and easy language. Now I've just bored most of you, I would like to make a question to the list. Let me portray the scenario: We have a daemon (hdloreand) running. We also have a console so you can send commands to the daemon and retrieve some info. At this moment, that console is connecting to the daemon via Dbus. We would like to avoid this, because it will solve some collateral problemas as well as will guarantee that the comunication will work when no X server and no dbus session is running. Is there any simple way to achieve this goal? We've been thinking of sockets but Im not conviced at all with that. Thanks Adrian PS: Im sorry for my english. -------------- next part -------------- An HTML attachment was scrubbed... URL: From smartpawn at gmail.com Sat Mar 15 09:57:44 2008 From: smartpawn at gmail.com (Deepak Rokade) Date: Sat, 15 Mar 2008 19:27:44 +0530 Subject: Using threads in python is safe ? Message-ID: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Hi All, I want to use therads in my application. Going through the docs , I read about GIL. Now I am confused whether using threads in python is safe or not. One thing I know that if I am accessing global variables in two or more threads I need to synchronize them using locking or such mechanism so that only one thread access them at a time. below are few questions for which I am looking answers. 1. In order to support multi-threaded Python programs, there's a global lock that must be held by the current thread before it can safely access Python objects. Does this lock need to be held by python application script expliciltly before accessing any python object or interpreter takes acre of it ? 2. Does multithreaded python script need to held lock before calling any blocking I/O call? Or one should not worry about GIL while using python threads if job to be processed by thread does not call any global variables and thread unsafe Python/C extension ? 3. I. want to use threadpool mechanism in python. Would it not help in multiprocessor environment if job to be processed by worker thread is I/O bound ? Sorry there are many questions here , but mostly they are related and are because I am confused with GIL funda. -- Thanx & Regards, Deepak Rokade Do what u Enjoy & Enjoy what u Do........... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bernard.chhun at gmail.com Wed Mar 12 07:29:27 2008 From: bernard.chhun at gmail.com (Bernard) Date: Wed, 12 Mar 2008 04:29:27 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> Message-ID: <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Hey Larry, that one is fairly easy: >>> from array import array >>> array('i', [1, 2, 3, 4, 5, 1, 2]) >>> def count(x, arr): cpt = 0 # declare a counter variable for el in arr: # for each element in the array if el == x: # when it is equal to the 'x' value cpt+=1 # increment the counter variable by one return cpt # return the counter after the loop >>> count(1,a) 2 I'm pretty sure there must be an easier way though :) On 12 mar, 06:26, Larry wrote: > Dear all, > > I'm new to Python. I have a file (an image file actually) that I need > to read pixel by pixel. It's an 8-bit integer type. I need to get the > statistics like mean, standard deviation, etc., which I know a little > bit already from reading numpy module. What I want to know is how to > get the number of occurences of numeric element in an array. Say, > > b = array(([2, 2, 3, 4, 5, 5]) > > b.count(2) certainly does not work. Is there any more efficient way > other than converting this as string characters? My data will produce > a fairly large array like 400x400 = 160000 values. Hoping you guys can > help me. > > Larry From xkenneth at gmail.com Mon Mar 31 16:45:23 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 31 Mar 2008 13:45:23 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> <304acc0a-3944-44a4-8626-30c2ab9da506@z38g2000hsc.googlegroups.com> <08805546-531f-4b5e-83fc-8b30b0e45db6@s37g2000prg.googlegroups.com> Message-ID: On Mar 31, 3:42?pm, Amit Gupta wrote: > On Mar 31, 11:00 am, xkenneth wrote: > > > Yeah, this is what I'm talking about: > > > > def __eq__(self, other) : > > > ? try : > > > ? ? ?return <> > > > ? except AttributeError: > > > ? ? ?return False > > > That seems a bit nasty to me. > > One thing about python (IMO); you can't just say this doesn't look > good. You need to say: why do you think this is not good. > To me, it appears a concise and local solution to your problem. Yes it is, but it's also tedious and lengthy for should-be simple statements. From castironpi at gmail.com Sun Mar 2 14:21:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 11:21:26 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: On Mar 2, 11:38?am, Steve Holden wrote: > Nobody thinks you are a fool for wanting help with your problems, it's > simply that you have to provide enough information about what' wring for > us to get a handle on the issues. This worked: import socket from time import time for i in range( 20 ): HOST = '' PORT = 80 #<---- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) print( 'listen' ) s.listen(1) conn, addr = s.accept() print( 'connected', addr ) print( conn.recv( 4096 ) ) #<---- conn.send( bytes('test %f'%time(),'ascii') ) conn.close() #<---- s.close() ... and connect with a browser: http://localhost/ if it's internet exploder. From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:30:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:30:11 -0300 Subject: class or inherited list ? References: <47ED0BA1.9020103@gmail.com> Message-ID: En Fri, 28 Mar 2008 12:15:45 -0300, Stef Mientki escribi?: > Passing all kinds of data between objects, > I'm looking for an elegant (and simple) way to pack the data. > Now it looks to me that both the class and the inherited list, > performs equally well. > Till now, the most elegant way (in my view) is the list inheritance, > mainly because you don't need brackets and no quotes. > What are others opinion about this ? > > class super_list(list): > pass > > def kwadraat ( value ) : > return value * value > > x={} > x['frequency']=33 > x['functie']=kwadraat > print x['functie'](2) > > y = super_list() > y.frequency = 33 > y.functie = kwadraat > print y.functie(3) You don't use y as a list at all - you might as well inherit from object. And in that case you get a generic attribute container - as you said, like a dict but using attribute syntax (drawback: only valid names can be used as keys) But I don't understand the "functie" usage - what's for? Perhaps if it used y.frequency - in that case a proper method would be better. -- Gabriel Genellina From dewitters at gmail.com Sun Mar 30 04:13:04 2008 From: dewitters at gmail.com (dewitters at gmail.com) Date: Sun, 30 Mar 2008 01:13:04 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <0964631d-67e4-4c7f-968e-5bf42c0787c2@d45g2000hsc.googlegroups.com> On Mar 29, 6:34 pm, Lie wrote: > You're forcing your argument too much, both != and <> are NOT standard > mathematics operators -- the standard not-equal operator is >< -- and > I can assure you that both != and <> won't be comprehensible to non- > programmers. What I meant was that both < and > are standard mathematics operators, and that by that knowledge one could deduce what <> means. But >< would also be fine by me :). From castironpi at gmail.com Sat Mar 8 15:27:23 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:23 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <47D2C25C.9050400@v.loewis.de> Message-ID: <50943715-483f-4f7d-9d7b-c17ed2ae5984@p73g2000hsd.googlegroups.com> > Notice that the language specification *deliberately* does not > distinguish between deletion of earlier and later items, but > makes modification of the sequence undefined behavior to allow > alternative implementations. E.g. an implementation that would > crash, erase your hard disk, or set your house in flames if you > confront it with your code still might be a conforming Python > implementation. Actually, PEP 4122 makes this a SetHouseInFlames error. Do you want to include this one? Just use _toaddafter= type( container )(). P.S. Equivalence class light, on the rocks. From janeczek at gmail.com Fri Mar 28 12:28:08 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Fri, 28 Mar 2008 17:28:08 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: <7xabkjbawl.fsf@ruckus.brouhaha.com> References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> <7xabkjbawl.fsf@ruckus.brouhaha.com> Message-ID: <561cb5bc0803280928v651a5d28qd4510f34e779bc01@mail.gmail.com> On 27 Mar 2008 23:49:46 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Micha? Janeczek" writes: > > However, the type of embedding that I imagined would be mostly > > pure functions, since Python can deal with IO rather well. It'd also > > be applicable in situations where we want to add some functionality to > > to existing, large Python project, where the complete rewrite > > would be infeasible. > > Of course I can't say what functions someone else would want to use, > but I'm not seeing very convincing applications of this myself. There > aren't that many prewritten Haskell libraries (especially monomorphic > ones) that I could see using that way. And if I'm skilled enough with > Haskell to write the functions myself, I'd probably rather embed > Python in a Haskell app than the other way around. I was talking mostly about writing new components there, not just using libraries. It'd apply to situations where there already exists a large Python infrastructure. > > I didn't mention this in this first draft, but I don't know (yet) > > how to support those "fancy" types. The plan for now is to export > > monomorphic functions only. > > This probably loses most of the interesting stuff: parser combinators, > functional data structures like zippers, etc. Unless you mean to > use templates to make specialized versions? That is true, but as you said before, using them directly from Python would be unwieldy. In most cases writing a thin wrapper in a language of the library that is going to be used is a much more natural way (same might apply to calling Python from Haskell). The plan for now is to start with monomorphic functions, then add support for parametrically polymorphic functions (that is ones that don't care about the type at all, i.e. List.length), and then possibly extend this to some type classes that we can reasonably expect to find on the Python side (Eq, Ord, etc.) > > As for GC, I think having the two systems involved is unavoidable if > > I want to have first class functions on both sides. > > This just seems worse and worse the more I think about it. Remember > that GHC uses a copying gc so there is no finalization and therefore > no way to notify python that a reference has been freed. And you'd > probably have to put Haskell pointers into Python's heap objects so > that the Haskell gc wouldn't have to scan the whole Python heap. > Also, any low level GHC gc stuff (not sure if there would be any) > might have to be redone for GHC 6.10(?) which is getting a new > (parallel) gc. Maybe I'm not thinking of this the right way though, I > haven't looked at the low level ghc code. GHC does support finalization, at least for foreign pointers. I don't think there is going to be any major change to the foreign interface, either. Otherwise I wouldn't be bothering myself really ;) The idea here is to have Haskell track most of Python objects (I think that'll be much easier), and the other way around when it's really necessary. > Keep in mind also that Python style tends to not use complex data > structures and fancy sharing of Haskell structures may not be in the > Python style. Python uses extensible lists and mutable dictionaries > for just about everything, relying on the speed of the underlying C > functions to do list operations very fast (C-coded O(n) operation > faster than interpreted O(log n) operation for realistic n). So maybe > this type of sharing won't be so useful. Yes, but for now I think it is necessary for function callbacks (Haskell calling Python giving it a higher order function). And if we decide to support that, we might as well investigate other use cases. > It may be simplest to just marshal data structures across a message > passing interface rather than really try to share values between the > two systems. I agree that it'll be simplest, that's why I chose it as a first step :) > For fancy functional structures, from a Python > programmer's point of view, it is probably most useful to just pick a > few important ones and code them in C from scratch for direct use in > Python. Hedgehog Lisp (google for it) has a nice C implementation of > functional maps that could probably port easily to the Python C API, > and I've been sort of wanting to do that. It would be great if > you beat me to it. Nice link about Hedgehog lisp :) As for porting its data structures to Python, I don't think it is a large enough project for SoC. And I also hope that the Haskell<->Python can bring more benefits to the users of both languages. > One thing I highly recommend is that you join the #haskell channel on > irc.freenode.net. There are a lot of real experts there (I'm just > newbie) who can advise you better than I can, and you can talk to them > in real time. Yes, I do drop by in there sometimes.. But what I'm after here is an opinion of a Python programmer :) Thanks again :) Michal From haag at lsu.edu Sun Mar 23 14:57:59 2008 From: haag at lsu.edu (Alaric Haag) Date: Sun, 23 Mar 2008 13:57:59 -0500 Subject: A "roadmap" for ctypes wrapping? Message-ID: Hi all, I'm undertaking a pretty significant wrapping project (a linux shared-object lib) early in my Python experience, and thought it might be useful for many more that just myself if this thread were to produce a sort of roadmap for approaching wrapping with ctypes. I've been doing some reading, but want to verify my "big picture view" and have come to make the following presumptions: (so, please correct me where erroneous) - One gathers the ".h" header(s) for the library to determine the data structures (defined in "#define" and "typedef" statements) as well as the prototypes for the library routines. - From these header files, one defines attributes to reproduce the "#define" statements, and also reproduces the typedef "structs" by defining classes and assigning a Python list of tuples for the "_fields_" attribute, to associate a ctype and field name with each field in the "struct". - Use ctypes.CDLL to "connect" to the library, and instantiate an object whose attributes are the library routines. - From that object, instantiate each of the routines, and override the "argtypes" attribute for each of these with a list of "ctypes", and a single ctype for the "restype" attribute. In either case, the "type" might be a newly-defined type (class) that's more complex than just the provided ctypes. Presumably, judicious use of the leading "_" (underscore) is used to hide (make private) the "ugly details" from the wrapper user, revealing only the routines, and possibly, classes that describe data types the original API expects the user to need. ====== Can anyone with some "wrapping" experience add/modify/enhance the above? Many thanks for all feedback! -- Alaric From fraleysinger at gmail.com Wed Mar 12 19:14:35 2008 From: fraleysinger at gmail.com (fraleysinger at gmail.com) Date: Wed, 12 Mar 2008 16:14:35 -0700 (PDT) Subject: agg (effbot) References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> <63q90kF268j23U1@mid.uni-berlin.de> Message-ID: <9688df1a-33fb-4083-8ce1-d84fbfd57e91@a70g2000hsh.googlegroups.com> On Mar 12, 10:52?am, Gerhard H?ring wrote: > fraleysin... at gmail.com wrote: > > Downloaded to Knoppix 5.1: > > : > > aggdraw-1.2a3-20060212.tar.gz > > > Followed README. ?Wouldn't compile. [...] > > Try shegabittling the frotz first. If that doesn't help, please post the > output of the compile command that threw the error. > > -- Gerhard You guys were correct to snicker. Tried it in Knoppix 5.0 and it worked. That led my friend (I was at his house last night) to retry it on Knoppix 5.1.1 and it was a simple error: Python.h was left off that version. We should have seen it straightaway. Thanks for replying. From python1 at infocentrality.co.uk Tue Mar 11 12:07:00 2008 From: python1 at infocentrality.co.uk (Trevor Hennion) Date: Tue, 11 Mar 2008 16:07:00 +0000 (UTC) Subject: Python Contract/Job Opportunity Message-ID: InfoCentrality are a small company who provided a custom Web/Database application for a customer in the Insurance industry. Our customer now wants a number of improvements to this application. To provide these improvements in a timely manner we need an additional programmer. 3 months contract initially - possibly leading to much more. We use Python, PostgreSQL, Html, Javascript and Linux. Suite a recent Computer Science or Programming graduate. Location - just south of Reading, Berks, UK. Must be able to travel to us. Phone Trevor Hennion on 0845 5083766. From http Thu Mar 13 06:49:14 2008 From: http (Paul Rubin) Date: 13 Mar 2008 03:49:14 -0700 Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> Message-ID: <7xtzjalx05.fsf@ruckus.brouhaha.com> Paul Rubin writes: > "Hendrik van Rooyen" writes: > > Given the following three lines of code at the interactive prompt: > > > > foo = [1,2,3,4] > > x = foo.append(5) > > print x > > > > What will be the output (choose one): > > 4) Nothing - no output Correction, it will print None, there is an explicit print statement that went past me. I'm sleepy. From castironpi at gmail.com Tue Mar 18 21:11:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 18:11:32 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: On Mar 18, 6:38?pm, Arnaud Delobelle wrote: > On Mar 18, 3:59?pm, Ninereeds wrote: > > > Hrvoje Niksic wrote: > > > This doesn't apply to Python, which implements dict storage as an > > > open-addressed table and automatically (and exponentially) grows the > > > table when the number of entries approaches 2/3 of the table size. > > > Assuming a good hash function, filling the dict should yield amortized > > > constant time for individual additions. > > Isn't this average constant time rather than amortized? > > > OK. I obviously need to look up open-addressed tables. I thought this > > was just, in effect, implicit linked listing - ie it still needs a > > linear search to handle collisions, it just avoids the need for > > explicitly stored link fields. Perhaps I'm mistaken. > > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > link to further details. Is there a known algorithm which for Key A, Key B s.t. h( KeyA ) = h( KeyB ) for hash function h, h( KeyA, 1 ) != h( KeyB, 1 ), where h( x, i+ 1 ) is searched when h( x, i ) is filled? That is, the search sequence is unique (or at least orthogonal to the h_value)? Could you just scramble the bits and hash key -> hash table -> hash table? Is deletion - resize to small - a strong bottleneck? Can you store an object's search sequence, as it looks for "a home", and when one of its earlier slots vacantizes, promote it? From hniksic at xemacs.org Tue Mar 25 11:59:21 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Mar 2008 16:59:21 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <87myomeqw6.fsf@mulj.homelinux.net> Tzury Bar Yochay writes: > given two classes: > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = Foo.getid() > b = self.id > return '%d.%d' % (a,b) Try this: class Foo(object): def __init__(self): self.__id = 1 def getid(self): return self.__id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.__id = 2 def getid(self): a = Foo.getid(self) b = self.__id return '%d.%d' % (a,b) >>> FooSon().getid() '1.2' > While my intention is to get 1.2 I get 2.2 I would like to know what > would be the right way to yield the expected results Either use the above "private" fields, or emulate them yourself by renaming self.id to self.foo_id or self.foo_son_id, and exposing those in the class. Or you can have a class-specific dict in each instance, and so on. From michael.wieher at gmail.com Sat Mar 22 18:05:25 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sat, 22 Mar 2008 17:05:25 -0500 Subject: List question In-Reply-To: <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> Message-ID: If you can't laugh at your own stupidity, being a programmer will lead directly to insanity. =) 2008/3/22, Zentrader : > > > No one meant to laugh at you. Your naivete was not obvious. FWIW, a > > sense of humor is a valuable possession in most Python-related > > conversations. > > Perhaps someone can explain how telling something like this to the OP, > who thinks this statement will work > if 'one' and 'two' in f: > is funny and not mean. In the words of whoever it was in "Gone With > The Wind", frankly I don't give a damn (except to not mislead relative > newbies). But this has wasted enough of everyone's time. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zerty.david at gmail.com Mon Mar 31 13:50:27 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 31 Mar 2008 14:50:27 -0300 Subject: Python and Db Message-ID: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> Hi! I'm don't know almost nothing about bds, Can You suggest me an Simple but efficient Bd to work with python apps? Can You suggest me any tutorials? Thanx -------------- next part -------------- An HTML attachment was scrubbed... URL: From quentel.pierre at wanadoo.fr Sat Mar 8 13:05:55 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 8 Mar 2008 10:05:55 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> > >>> def convert(x): > > ? ? ? ? if '.' in x: > ? ? ? ? ? ? ? ? try: return float(x) > ? ? ? ? ? ? ? ? except ValueError: return x > ? ? ? ? else: > ? ? ? ? ? ? ? ? try: return int(x) > ? ? ? ? ? ? ? ? except: return x > > >>> convert('123') > 123 > >>> convert('123.99') > 123.98999999999999 > >>> convert('hello') > Hi, That's fine for people who write floats with a "." ; but others learn to enter them with "," For the same float, the French write the literal 123.456.789,99 when others write 123,456,789.99 ; for us, today is 8/3/2008 (or 08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8 Popular spreadsheets know how to "guess" literals ; if the guess is not correct users can usually specify the pattern to use. My question was just to know if something similar had already been developed in Python ; I understand that the answer is no Thanks, Pierre From sturlamolden at yahoo.no Sun Mar 30 13:44:14 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 30 Mar 2008 10:44:14 -0700 (PDT) Subject: ANN: pygame 1.8 released References: Message-ID: <80749045-84bb-4a51-b7df-0ae7cf294589@s19g2000prg.googlegroups.com> This is good news, particularly the NumPy support for surface and pixel arrays. From hv at tbz-pariv.de Fri Mar 28 10:28:03 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 28 Mar 2008 15:28:03 +0100 Subject: simple web-server In-Reply-To: References: Message-ID: <654djkF2dl38dU1@mid.individual.net> Pavol Murin schrieb: > hello python users, > > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). If you want to run shell scripts, you might want to search for a web server written in a shell script.... Running shell scripts which process CGI input are very insecure. It may be possible to write secure shell scripts, but I think it is not worth the trouble. Django contains a simple web server for testing. But it runs as a single process. So if one request needs long, all other requests wait. I don't think django is too heavy for a simple task. You can use CGIHTTPServer and the cgi module of the standard library, too. But it has drawbacks. One is, that CGIHTTPServer can't do a redirect. (HTTP code 302). I whish that there was a simple and small (not twisted) webserver written in Python which can be used in production. But I think there is none. Thomas BTW, use subprocess and not os.system() if you need to call other executables. > Longer story: > > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed). > > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? > > thank you, muro -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From carlwenrich at gmail.com Thu Mar 20 23:20:21 2008 From: carlwenrich at gmail.com (Carl) Date: Thu, 20 Mar 2008 20:20:21 -0700 (PDT) Subject: How do I change the font size for the default coordinates in matplotlib? Message-ID: I've searched the user manual (and this forum) but I don't see anything that helps. From grante at visi.com Fri Mar 21 10:16:08 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Mar 2008 14:16:08 -0000 Subject: Code folder with Emacs References: <13u5li6kspler51@corp.supernews.com> <64hdonF2boovnU1@mid.uni-berlin.de> Message-ID: <13u7gp8oq4kejc4@corp.supernews.com> On 2008-03-21, Diez B. Roggisch wrote: >> Has anybody figured out how to do code folding of Python source >> files in emacs? >> >> I tried "hide-show" minor mode, but it doesn't really work for >> Python code: the only think it knows how to hide/show are >> function bodies. It can't do normal things like hide/show a >> code block like it can for other languages. > > I just recently started hacking in emacs, to enhance the > python-mode and make pdb work with persisten breakpoints (by > that I mean BPs that survive one debug-session). > > Code-folding isn't currently on my agenda, but an interesting > idea. given that e.g. ecb already has structural analysis > buffers, there are python-aware code parsers (cedet?) Given the simplicity of python's indentation-defined block-delimiting, It's hard to understand how hide-show managed to come up with a "block" definition that works for function bodies but not for other identically delimited blocks. > So it shouldn't be too hard. The only interesting/important > thing would be to integrate it with ecb because I wouldn't > want several parse-runs at once. When I have some time, I'm going to take alook at hide-show's Python support, but my lisp skills are a bit rusty... -- Grant From misceverything at gmail.com Sun Mar 30 17:39:10 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 30 Mar 2008 14:39:10 -0700 (PDT) Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> <47eea713$0$27902$426a74cc@news.free.fr> Message-ID: That's not a problem - I'm only interested in Win2k+. Thanks for the caveat. On a similar note, is there a way (preferably using WMI) to get the full path to the executable that has a port open (the same thing that fport does, just implemented in Python)? From watine at cines.fr Thu Mar 13 10:44:26 2008 From: watine at cines.fr (Benjamin Watine) Date: Thu, 13 Mar 2008 15:44:26 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: <47D93DCA.8070506@cines.fr> Marko Rauhamaa a ?crit : > Benjamin Watine : > >> How can I do this ? I would like a function like that : >> >> theFunction ('cat -', stdin=myVar) >> >> Another related question : Is there's a limitation of var size ? I >> would have var up to 10 MB. > > import subprocess > myVar = '*' * 10000000 > cat = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE) > cat.stdin.write(myVar) > cat.stdin.close() > cat.wait() > > > Marko > Thank you Marko, it's exactly what I need. And if somebody need it : to get the stdout in a var (myNewVar), not in the shell : cat = subprocess.Popen('cat', shell = True, stdin = subprocess.PIPE, stdout=subprocess.PIPE) cat.stdin.write(myVar) cat.stdin.close() cat.wait() myNewVar = cat.stdout.read() Is it correct ? Ben From sjmachin at lexicon.net Thu Mar 13 17:57:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Mar 2008 14:57:25 -0700 (PDT) Subject: Dispatch("Excel.Application") failed References: Message-ID: <84040989-8de9-42fb-ba08-6f1ee10566e0@s19g2000prg.googlegroups.com> On Mar 13, 5:02 pm, lialie wrote: > Hi, > Maybe it 's quite simple, but I can't fix it. Do I make some mistakes in > my env setting? My excel version is 2003. > any suggestion? Thanks. > > Traceback (most recent call last): > File "testexcel.py", line 3, in ? > excel = Dispatch("Excel.Application") [snip] > pywintypes.com_error: (-2147221005, > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > None, None) Googling for 2147221005 gives some clues. That string of hex stuff appears where an error message is expected -- it's not utf8, and makes no sense when I attempt to decode it with cp1250 to cp1258 inclusive. If you start IDLE and type: import sys; sys.stdout.encoding what do you see? From perrygreenfield at gmail.com Tue Mar 18 12:55:10 2008 From: perrygreenfield at gmail.com (perrygreenfield at gmail.com) Date: Tue, 18 Mar 2008 09:55:10 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: Amen on the diamond keynotes and lightning talks. The lightning talks were a great disappointment. Sponsor talks (or any such talks pitched at selling or recruiting) should go in their own, clearly labeled group so those of us who don't care about them can avoid them. If there must diamond 'keynotes' put them at the end of a session or in a separate track so we can easily avoid them if we wish. But personally, I don't think keynotes should be for sale at all in any form. One problem I faced was that there were sessions that had few talks I was interested in and other that had several at the same time where I couldn't attend all that I was interested. It's likely that there is no good solution to this, but perhaps one could try a new scheme for scheduling talks by posting the talk list early and letting registrants select the top n talks they want to see and running some sort of scheduling optimizer that tries to satisfy most of these desires (I have no idea if anything like this exists anywhere). And if you do decide to change how you handle sponsorship don't be afraid to say publicly how things are going to be different next time. There could well be many who won't go next time (like me) unless they have some reasons to believe that things will be different. From gargonx at gmail.com Wed Mar 12 00:29:38 2008 From: gargonx at gmail.com (gargonx) Date: Tue, 11 Mar 2008 21:29:38 -0700 (PDT) Subject: Why no string return? Message-ID: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Say i have the two methods: def ReturnMethod(request, x): if request is True: return x else: print "No String for you...False!" def SendMethod(request): xstring = "Some text" ReturnMethod(request, xstring) SendMethod(True) Why does ReturnMethod not return the string x? I do believe it is returning with a NoneType. Any help would be greatly obliged Thanks, Josh From martin at v.loewis.de Sun Mar 23 16:20:20 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 23 Mar 2008 21:20:20 +0100 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] In-Reply-To: References: <47E4202C.5060400@v.loewis.de> Message-ID: <47e6bb84$0$1903$9b622d9e@news.freenet.de> Guilherme Polo wrote: > 2008/3/21, "Martin v. L?wis" : >>> I've been thinking of volunteering to "port" Tkinter to Python 3.0, I >> > hadn't noticed that there was any discussion of removing it. It would >> > be a shame IMHO. >> >> >> I don't think Tkinter will be removed. It works just fine in 3k. >> >> Of course, if you would port IDLE to Tk 8.5: that would be a useful >> contribution. > > I'm interested in doing this, but are you aware of bugs yet ? I know > just one that is specific to Tk 8.5, this one being the background > color of the editor. I just looked at it again, and it seems to work fine. Of course, contributions to IDLE are always welcome, but this specific issues seems to require no more intense attention. Regards, Martin From dullrich at sprynet.com Wed Mar 19 08:41:29 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 19 Mar 2008 07:41:29 -0500 Subject: Speaking Text Message-ID: Mac OS X has text-to-speech built into the interface. So there must be a way to access that from the command line as well - in fact the first thing I tried worked: os.system('say hello') says 'hello'. Is there something similar in Windows and/or Linux? (If it's there in Linux presumably it only works if there happens to be a speech engine available...) David C. Ullrich From steve at REMOVE-THIS-cybersource.com.au Sun Mar 16 00:56:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Mar 2008 04:56:41 -0000 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <13tmo994bgqjr11@corp.supernews.com> <13to6j6pta8o008@corp.supernews.com> Message-ID: <13tpa4999krk6cd@corp.supernews.com> On Sat, 15 Mar 2008 11:50:17 -0700, Dennis Lee Bieber wrote: > Small integers are cached in Python, so they always have a fixed ID > (address). Small integers are cached in CPython, making it an implementation- dependent feature. I don't believe that caching is promised by the language definition, and while CPython has a special relationship to Python-the-language, I don't think an implementation that failed to cache small integers would be described as "not Python". -- Steven From pianomaestro at gmail.com Fri Mar 28 10:57:56 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 07:57:56 -0700 (PDT) Subject: How do I reconnect a disconnected socket? References: Message-ID: <20af9145-133e-4747-aa7f-ba238515653a@d62g2000hsf.googlegroups.com> Did you try just creating a new socket every time you do a connect ? On Mar 28, 10:01 am, Jason Kristoff wrote: > I'm trying to make something that once it is disconnected will > automatically try to reconnect. I'll add some more features in later so > it doesn't hammer the server but right now I just want to keep it simple > and get that part working. The problem is that when I use sock.close I > get an error message of > Bad File Descriptor > and if I either use shutdown or just go straight to reconnecting I get: > Transport endpoint is already connected > > This is what I've got right now: > > #! /usr/bin/env python > import socket, string > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > def doconn(): > sock.connect(("localhost", 1234)) > def dodiscon(): > sock.close() > doconn() > > doconn() > > while (1): > buffer = sock.recv(1024) > if not buffer: > dodiscon() From phil at riverbankcomputing.com Sun Mar 30 11:08:19 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sun, 30 Mar 2008 15:08:19 +0000 Subject: Using QSystemTrayIcon with PyQt In-Reply-To: References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: <200803301608.19697.phil@riverbankcomputing.com> On Sunday 30 March 2008, Alex Teiche wrote: > On Mar 30, 2:08 am, Phil Thompson wrote: > > On Sunday 30 March 2008, Alex Teiche wrote: > > > Hello, > > > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > implement the following thing into my python application: > > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > it, but I could not get this specific thing to work. Can someone give > > > me some hints as to get it working in Python? > > > > > > Thanks a ton, > > > > > > Alex > > > > Have you looked at PyQt's systray example? > > > > Phil > > No, where do I find the example? > > Thanks, > > Alex Unsurprisingly in the PyQt source package. Phil From gagsl-py2 at yahoo.com.ar Thu Mar 6 15:25:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 18:25:04 -0200 Subject: Py-Extension Irregularity References: Message-ID: En Thu, 06 Mar 2008 13:54:44 -0200, Michael Wieher escribi?: > Observe. > > Python Code Snippet: > ==================== > ... > 66 while i < (self.nPCodes): > 67 # print "%s:%s" % (self.nPCodes,i) > 68 (c,l,sn,f,fn,sz) = tabmodule.getQuestion(i,self.mx3Path) > 69 if _debug and sz>0: > 70 _newPtrLoc = tabmodule.getMx3Ptr() > 71 _diff = _newPtrLoc-_oldPtrLoc > 72 _oldPtrLoc = _newPtrLoc > 73 if _diff>16: > 74 print _diff > .... > > C++ Code Snippet: > --------------------------- > 189 static PyObject* > 190 tabmodule_getMx3Ptr(PyObject * self, PyObject * args) { > 191 int a; > 192 a=mx3File.tellg(); > 193 return Py_BuildValue("i",a); > 194 } > ... > > 189 PyObject * > 190 tabmodule_getQuestion(PyObject * self, PyObject * args) { > .... > 208 mx3File.read((char*)&m_mdx,16); > .... > 237 //if(m_mdx.size==0) > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > 239 //return Py_BuildValue("iiiiii",m_mdx.compression, > m_mdx.location, > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > } > > Output== > michael at majw-m65:~/MRI/tabModule$ ./tabModule.py > michael at majw-m65:~/MRI/tabModule$ > > None. (ie: the _diff is always 16 or less, which is what is SHOULD be, > in > fact, it is always 16.) Why do you assert that? With those commented out lines, the last item returned by getQuestion (sz) is always 0; nothing is printed because sz==0 and the python code never enters the outer if. From that evidence I can't say anything about _diff. > Observe!!!! > > 237 if(m_mdx.size==0) > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > 239 return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > > By uncommenting line 237 and 239, we see: > ... > 64 > 80 > 32 > 32 > 32 > 48 > 128 > 160 > 32 > 32 > 64 > .... > > Most of the numbers are still 16, but _diff is often larger than 16, by > some > multiple. I'd print m_mdx values in the C++ source. > How in Buddah's name is returning a Py_BuildValue() affecting a file > pointer > that isn't being used at all in the function???? I don't think this is the cause... -- Gabriel Genellina From exarkun at divmod.com Mon Mar 3 08:11:43 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 3 Mar 2008 08:11:43 -0500 Subject: is there enough information? In-Reply-To: <13s9u7dg24es73a@corp.supernews.com> Message-ID: <20080303131143.6859.627120868.divmod.quotient.15093@ohm> On Tue, 26 Feb 2008 21:45:24 -0800, Dennis Lee Bieber wrote: > [snip] > > Threads, in Python, are good for parallel processing of items that >tend to be I/O bound -- that is, stuff that blocks on lots of I/O calls >allowing other threads to execute until they block too. Due to the GIL >in the common Python implementation, threading is not useful for >number-crunching (CPU bound) processing. > > Now, there is a very vocal group that recommend Twisted style >asynchronous call-backs for everything in the world... But I think that >group tends to forget that Windows I/O is incompatible with the >low-level select() call often used to do parallel I/O -- leaving it only >useful for the network socket I/O, but not local file I/O processing. I'm not sure, but you seem to be implying that the only way to use Windows' asynchronous I/O APIs is with threads. Actually, it is possible (and Twisted allows you) to use these as well without writing a threaded application. Perhaps you think it would be better to use them with threads, but that's certainly not the _only_ way to use them as you implied. Jean-Paul From fn681 at ncf.ca Sat Mar 1 16:58:49 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sat, 01 Mar 2008 16:58:49 -0500 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c990b9$0$899$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> <47c990b9$0$899$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI (MVP) wrote: > Re! > > An exemple. With this script: > a=123 > b=456 > d=a+b+c > (note than 'c' is not defined). > > When I run, inside Pyscripter, the error-dialog is showed, and, one > second after, PyScripter is closed. > This problem is present since Python 2.5.2. > > I search, for know if it's a problem only on my computer, or a more > general problem. > > Thanks by advance for your(s) answer(s). > > @-salutations I ran your script and an exception.NameError is reported. I say OK to the error and repeat the run. PyScripter is not closed. This is with xp and Python 2.5.2 Colin W. From onetwofour at gmail.com Sat Mar 1 07:28:22 2008 From: onetwofour at gmail.com (theneb) Date: Sat, 1 Mar 2008 04:28:22 -0800 (PST) Subject: Getting a free TCP port & blocking it References: <1dff2e2c-892d-42fa-9e65-5c7c12b75ec3@s13g2000prd.googlegroups.com> <280is3le2op8khmgr7nj5a1mnkjd7p0n50@4ax.com> Message-ID: On Feb 29, 11:11 pm, Tim Roberts wrote: > theneb wrote: > >Hi all, > >I'm attempting to block a TCP port from any other application from > >using it until I free it from python, this is so that: > >1). Generate a random free user-space port > >2). Generate the script for the external program with the port > >3). Free the port before external program execution. > > What's the point? Why can't the actual user of the port create the port, > and then notify the other side of the port number? The system the app will run on will be creating three instances of the external application, the python app has to keep track of which port the external app is running on. > > And why don't you just specify a port number of 0 and let the system assign > you a free port number? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From sambo at voidstar.com Wed Mar 12 11:49:55 2008 From: sambo at voidstar.com (Sam) Date: Wed, 12 Mar 2008 11:49:55 -0400 Subject: access to base class __init__ References: <13suutrsb4bab8b@corp.supernews.com> <13t1il47eoamrb3@corp.supernews.com> Message-ID: <0QSBj.29323$yk5.10906@newsfe18.lga> Dennis Lee Bieber wrote: > On Thu, 06 Mar 2008 22:35:18 -0500, Sam declaimed > the following in comp.lang.python: > ['line 1', 'line 2', 'embedded', 'line', 'something'] >>>> sample="""line 1\rline 2\rembedded\nline\rsomething\r""" >>>> sample.splitlines() > ['line 1', 'line 2', 'embedded', 'line', 'something'] >>>> > You are right partly right. That code only parsed the HTML request header which I believe had one specific line termination as prescribed by RFC ( but I will have too look it up later since I don't remember whichfor sure. ) Once again got confused on them buggers, "\n" is LINUX ( the least logical). > splitlines() handles \r\n, \n, and \r as line endings -- and no stray > empty ending! (however, \n\r /does/ create an empty element) > !!~! SPLITLINES() BEAUTY, Thanks for reminding me. I mush have a faulty memory cell or entire row. From Lie.1296 at gmail.com Sat Mar 8 22:51:24 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 19:51:24 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? Message-ID: I'm asking about people in c.l.py's opinion about a _probably_ very Pythonic way of doing something if such features is implemented. It is to be known that I'm not a Python expert and actually relatively new to Python programming, so probably I'm just not thinking pythonic enough yet or this feature might already exist somewhere in a different name. Anyway, I'm just asking for opinions, tell me problems I haven't foreseen, or whether such things would be hard to implement, or whether you think the idea is great or plain bad (and why). Soft Exception What is "Soft Exception"? Soft Exception is an exception that if is unhandled, pass silently as if nothing happened. For example, if a variable turns into NoneType, it'll raise Soft Exception that it have become NoneException, programmers that wants to handle it can handle it with a try...except block while programmers that doesn't care about it (or know it won't be a problem to his code) can just leave the code as it is. Soft Exception differs from Hard Exceptions (the regular Exception) in a way that Hard Exception must be handled at all cost or the program will be terminated while Soft Exception allow programmers not to handle it if they don't want to. Soft Exception is similar to an event-based system, although Soft Exception can only be handled by codes above it while Event-based system can be handled by anyone aware of the handle pool. The Soft Exception can also be thought as a Warning to the codes above it that it has done something that the codes above might want to know. Implementation: Simple implementation might be done by catching all exceptions at the highest level, then filtering which exceptions would be stopped (Soft Exception) and which exceptions will be reraised and terminate the program (Hard Exception). This is simple and can be easily implemented but is inefficient as that means all soft exceptions must bubble through its way to the top to find out if it is Soft or Hard. A more through implementation would start from the raiser inspecting the execution stack and finding whether there are any try block above it, if no try block exist it pass silently and if one exist it will check whether it have a matching except clause. This also circumvents a problem that simple implementation have, as described below. Syntax change is probably unneeded and a Soft Exception class may be created by inheriting from BaseSoftException class. Problems: - If the raising statement is a complex statement (like function call) instead of just a simple statement (like assignment from an expression) the exception might catch a similar soft exceptions from deep _inside_ the function call and handle it as if it happened in the code it's protecting. This problem can be solved by raising Soft Exception only once except if explicitly reraised (perhaps through except SoftException: raise). This can be done by modifying a flag that is turned off (Falsed) if the Soft Exception is raised and turned on again (Trued) if the Soft Exception is reraised. Normal Exceptions (Hard Exceptions) would have this flag turned off (Falsed) if it is handled and turned on (Trued) again if it is reraised. - To be half useful, soft exceptions have to be raised everywhere here and there, not just here and here only. This might require a massive change in current codes, or at least in Python's official libraries. - Irresponsible programmers. Sometimes lazy programmers might decides to be lazy and make all exceptions soft so he doesn't have to handle it. Ideology Base: - EAAP: Easier to apologize than to ask permission. Others: - Sometimes it might be useful to convert a Soft Exception into Hard Exception or vice versa. From sjmachin at lexicon.net Mon Mar 10 17:37:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 14:37:18 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: On Mar 10, 11:14 pm, Duncan Booth wrote: > "Neil Crighton" wrote: > > I'm using the zipfile library to read a zip file in Windows, and it > > seems to be adding too many newlines to extracted files. I've found > > that for extracted text-encoded files, removing all instances of '\r' > > in the extracted file seems to fix the problem, but I can't find an > > easy solution for binary files. > > > The code I'm using is something like: > > > from zipfile import Zipfile > > z = Zipfile(open('zippedfile.zip')) > > extractedfile = z.read('filename_in_zippedfile') > > > I'm using Python version 2.5. Has anyone else had this problem > > before, or know how to fix it? > > > Thanks, > > Zip files aren't text. Try opening the zipfile file in binary mode: > > open('zippedfile.zip', 'rb') Good pickup, but that indicates that the OP may have *TWO* problems, the first of which is not posting the code that was actually executed. If the OP actually executed the code that he posted, it is highly likely to have died in a hole long before it got to the z.read() stage, e.g. >>> import zipfile >>> z = zipfile.ZipFile(open('foo.zip')) Traceback (most recent call last): File "", line 1, in File "C:\python25\lib\zipfile.py", line 346, in __init__ self._GetContents() File "C:\python25\lib\zipfile.py", line 366, in _GetContents self._RealGetContents() File "C:\python25\lib\zipfile.py", line 404, in _RealGetContents centdir = struct.unpack(structCentralDir, centdir) File "C:\python25\lib\struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 46 >>> z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK >>> z = zipfile.ZipFile('foo.zip', 'r') # OK If it somehow made it through the open stage, it surely would have blown up at the read stage, when trying to decompress a contained file. Cheers, John From jeff at jmcneil.net Thu Mar 6 22:41:20 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 6 Mar 2008 22:41:20 -0500 Subject: Looking for very light weight template library (not framework) In-Reply-To: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> References: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> Message-ID: <82d28c40803061941y6ae70595wa20b2127bac32822@mail.gmail.com> Cheetah (http://www.cheetahtemplate.org/) and Mako (http://www.makotemplates.org/) come to mind. Isn't there some long running joke about new Python programmers creating their own template language or something, too? =) I know you said you don't want a web framework, but I've always been a fan of Django templates in that they don't really allow you to do too much inside the template itself. That seems to help keep a lot of ex-PHP/JSP/ASP programmers I know honest. On 3/6/08, Erik Max Francis wrote: > Malcolm Greene wrote: > > > New to Python and looking for a template library that allows Python > > expressions embedded in strings to be evaluated in place. In other words > > something more powerful than the basic "%(variable)s" or "$variable" > > (Template) capabilities. > > > > I know that some of the web frameworks support this type of template > > capability but I don't need a web framework, just a library that > > supports embedded expression evaluation. > > ... > > Any suggestions appreciated. > > EmPy may work: > > http://www.alcyone.com/software/empy/ > > Your template would look something like: > > > myOutput = """\ > > The total cost is @invoice.total. > > This order will be shipped to @invoice.contact at the following > address: > > @invoice.address > > > This order was generated at @time.ctime() > """ > > This could be instrumented with something as simple as: > > >>> import em, time > > >>> myOutput = """\ > ... > ... The total cost is @invoice.total. > ... > ... This order will be shipped to @invoice.contact at the following > ... address: > ... > ... @invoice.address > ... > > ... This order was generated at @time.ctime() > ... """ > >>> > >>> class Invoice: pass > ... > >>> invoice = Invoice() > >>> invoice.total = "$123.45" > >>> invoice.contact = "Jack McCoy" > >>> invoice.address = "1 Police Plaza\nNew York City, NY" > >>> print em.expand(myOutput, globals()) > > The total cost is $123.45. > > This order will be shipped to Jack McCoy at the following > address: > > 1 Police Plaza > New York City, NY > > This order was generated at Thu Mar 6 18:41:58 2008 > > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > There's a reason why we / Keep chasing morning > -- Sandra St. Victor > > -- > http://mail.python.org/mailman/listinfo/python-list > From dummy at dummy.nl Tue Mar 25 00:29:20 2008 From: dummy at dummy.nl (Cecil Westerhof) Date: Tue, 25 Mar 2008 05:29:20 +0100 Subject: Non-buffering stdout Message-ID: <47e87fa0$0$14348$e4fe514c@news.xs4all.nl> With python -u script, you can make stdout unbuffered. Is there a way to do it in the script itself? I use just a script with a shebang (#!/usr/bin/env python) and then it is not possible to use -u. From rschroev_nospam_ml at fastmail.fm Sat Mar 29 05:18:15 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 29 Mar 2008 10:18:15 +0100 Subject: Help me on function definition In-Reply-To: References: Message-ID: aeneng schreef: > Hello everyone, > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this >>>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 You forgot the : after def cross(u, v) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From xpahos at gmail.com Sun Mar 30 18:42:23 2008 From: xpahos at gmail.com (phasma) Date: Sun, 30 Mar 2008 15:42:23 -0700 (PDT) Subject: Export data to OpenDocument Text Message-ID: <00eaab19-9076-4278-9cb6-17a2cdef31ff@m3g2000hsc.googlegroups.com> Hi! I'm trying to save data from sqlite to OpenDocument Text. Code: localtime = time.localtime(time.time()) try: odt_file = zipfile.ZipFile(file_name, "w") except: print("?????????? ??????? ???? ??? ??????") return False buff_file = zipfile.ZipInfo("mimetype", localtime) odt_file.writestr(buff_file, "application/ vnd.oasis.opendocument.text") buff_file = zipfile.ZipInfo("content.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(content_xml)) buff_file = zipfile.ZipInfo("styles.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(style_xml)) buff_file = zipfile.ZipInfo("meta.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(meta_xml)) buff_file = zipfile.ZipInfo("META-INF/manifest.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(manifest_xml)) odt_file.close() OpenOffice can't open this file, in what a problem ? sample file: http://omploader.org/vZjlo/test.odt From tjreedy at udel.edu Sat Mar 8 16:15:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2008 16:15:31 -0500 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: "egbert" wrote in message news:20080308152034.GA12009 at hccnet.nl... | However the loop-else really works more like this: | . try to do the loop; | . if it starts but is interrupted by a break, | . then do something else as well. This is NOT how loop-else works for Python. If you want to do something special on breaks, put the break-only code before the break. while loop_condition: if break_condition: break | So they are completely different beasts, and if you try to use | or explain the one according to the rules of the other one, | you put a serious strain on your synapses. I did not mean to broke your brain. | The explanation that the if-else and the loop-else | follow the same pattern, runs more or less like this: | . all conditions to run the loop to its completion were met, | . which means that the loop-condition is not met (any more), | . which means that we must do something else. | For me that is orwellian logic: success is failure. I gave a clear and coherent explanation of how while derives from if, and correspondingly, how while-else derives from if-else, to help those who want to read and write Python code. Building on the pseudo-snippet above, one can write while loop_condition: if break_condition: break else: Python allows one to have both break-only and completion-only sections together in one compound statement and *without* having to fiddle with a special flag variable. I am sorry if you cannot appreciate such elegance and can only spit on it as 'orwellian'. If the sense of else were reversed, one would have to write the clumbsier complete = True # though false at this point while loop_condition: if break_condition: complete = False break else: if complete: Terry Jan Reedy From pradipbhosale at gmail.com Mon Mar 31 09:28:03 2008 From: pradipbhosale at gmail.com (Pradip) Date: Mon, 31 Mar 2008 06:28:03 -0700 (PDT) Subject: Multi Threading Problem with Python + Django + PostgreSQL. Message-ID: <553b16a7-a89e-4892-b92b-c0f88e00e096@e23g2000prf.googlegroups.com> Hello every body. I am new to this forum and also in Python. Read many things about multi threading in python. But still having problem. I am using Django Framework with Python having PostgreSQL as backend database with Linux OS. My applications are long running. I am using threading. The problem I am facing is that the connections that are being created for database(postgres) update are not getting closed even though my threads had returned and updated database successfully. It is not like that the connections are not being reused. They r being reused but after sometime new one is created. Like this it creates too many connections and hence exceeding MAX_CONNECTION limit of postgres conf. ** I am using psycopg2 as adaptor for python to postgres connection. which itself handles the connections(open/close) Now the problem is with Django / Python / psycopg2 or any thing else?? HELP ME OUT!!!!! From castironpi at gmail.com Sun Mar 9 21:05:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 18:05:48 -0700 (PDT) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> Message-ID: <980fee99-808b-47f2-8782-faac7c6a7586@34g2000hsz.googlegroups.com> > > ?> and I want to be able to stop [functions] if they run too long. > > > That's tricky [due to a synthetic limitation]. It would suck if you couldn't hold the GIL for as long as you need to. But how much is it used? Wrote the docs: > when two threads simultaneously increment the reference count of the same object Well, the example sucked. Just synchronize ref count manipulation. Every OS has locking primitives, and a library exists to deny requests to block that lock dead. How integral is the GIL to Python? > The Python interpreter is not fully thread safe -Make- it so. From mensanator at aol.com Mon Mar 17 21:20:14 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 17 Mar 2008 18:20:14 -0700 (PDT) Subject: First Program Bug (Newbie) References: Message-ID: On Mar 17, 7:03?pm, Benjamin Serrato wrote: > I Found It!! The following was a post asking for help finding a bug. I > thought I needed help with my syntax, but just before sending I found > the bug on line 13. Line 13 should read: "base = 2". I would still > appreciate any comments on my program. Maybe there is a better way to do > it that I didn't think about. I know it's not that interesting but it's > my first one. > > [post] > I'm almost halfway through an online tutorial I found on the python.org > site and decided to stop and write a program for myself. I got it in my > head to write a program to print all the primes; the idea came from > another tutorial. The program prints some non-prime numbers. In a > comparison to lists of primes the program prints eight non-primes for > numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. > Here is the program. > > base = 2 > candidate = 3 > > while True: > ? ? ? ? while candidate % base != 0: > ? ? ? ? ? ? ? ? base = base + 1 > ? ? ? ? ? ? ? ? if base > (candidate / 2): > ? ? ? ? ? ? ? ? ? ? ? ? print candidate > ? ? ? ? ? ? ? ? ? ? ? ? candidate = candidate + 1 > ? ? ? ? ? ? ? ? ? ? ? ? base = 2 > ? ? ? ? else: > ? ? ? ? ? ? ? ? candidate = candidate + 1 > > The following is a rundown of the program. > > candidate: A possible prime number. > base: Start point for divisibility testing. > outer while loop: Causes the program to loop. > inner while loop: Obviously, checks if 'candidate' mod 'base' equals > zero. If not base is incremented by one then 'if loop'. > if loop: After base has been incremented this checks whether all the > possible divisors have been used up. If they have then 'candidate' must > be prime. So, candidate is printed, a new candidate is chosen and the > base is reset. > else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is > not prime and a new candidate is chosen. > > I realize yall probably didn't need all that. > > At first I tried to use 'return' on the 'else' block to cause the > program to loop, but I don't understand 'return' yet and that didn't > work. So, I put the rest into another while loop and was really happy to > find it worked but the program prints some non-prime numbers. > > Thanks, Benjamin Serrato > > P.S. What is the chance I'll get spam for using my real email address? I > currently don't get any so... > [/post] Several items. First, you don't need to check base larger than sqrt(candidate). Second, see comments following dc. Third, you need to add base = 2 to end of program, otherwise next candidate starts base where previous candidate left off. Fourth, use +=1 to increment. Finally, throw this away and use gmpy. :-) import gmpy # for Quality Assurance base = 2 candidate = 3 p = 0 # prime count while p<100: # limit the loop to 100 primes while candidate % base != 0: base += 1 #if base > (candidate / 2): if base > (gmpy.sqrt(candidate)): # only need to test to sqrt(candidate) dc = divmod(candidate,2) # remainder==0 gives false primes if dc[1]==1: # # the gmpy functions are for QA, verifies that what you call a prime # really is one and the next_prime makes sure you don't skip any # these can be removed once working # print candidate,gmpy.is_prime(candidate)>0,gmpy.next_prime(candidate) p += 1 candidate += 1 base = 2 else: candidate += 1 # false prime, reset base = 2 else: candidate += 1 base = 2 # failure to reset causes false primes ## 3 True 5 ## 5 True 7 ## 7 True 11 ## 11 True 13 ## 13 True 17 ## 17 True 19 ## 19 True 23 ## 23 True 29 ## 29 True 31 ## 31 True 37 ## 37 True 41 ## 41 True 43 ## 43 True 47 ## 47 True 53 ## 53 True 59 ## 59 True 61 ## 61 True 67 ## 67 True 71 ## 71 True 73 ## 73 True 79 ## 79 True 83 ## 83 True 89 ## 89 True 97 ## 97 True 101 ## 101 True 103 ## 103 True 107 ## 107 True 109 ## 109 True 113 ## 113 True 127 ## 127 True 131 ## 131 True 137 ## 137 True 139 ## 139 True 149 ## 149 True 151 ## 151 True 157 ## 157 True 163 ## 163 True 167 ## 167 True 173 ## 173 True 179 ## 179 True 181 ## 181 True 191 ## 191 True 193 ## 193 True 197 ## 197 True 199 ## 199 True 211 ## 211 True 223 ## 223 True 227 ## 227 True 229 ## 229 True 233 ## 233 True 239 ## 239 True 241 ## 241 True 251 ## 251 True 257 ## 257 True 263 ## 263 True 269 ## 269 True 271 ## 271 True 277 ## 277 True 281 ## 281 True 283 ## 283 True 293 ## 293 True 307 ## 307 True 311 ## 311 True 313 ## 313 True 317 ## 317 True 331 ## 331 True 337 ## 337 True 347 ## 347 True 349 ## 349 True 353 ## 353 True 359 ## 359 True 367 ## 367 True 373 ## 373 True 379 ## 379 True 383 ## 383 True 389 ## 389 True 397 ## 397 True 401 ## 401 True 409 ## 409 True 419 ## 419 True 421 ## 421 True 431 ## 431 True 433 ## 433 True 439 ## 439 True 443 ## 443 True 449 ## 449 True 457 ## 457 True 461 ## 461 True 463 ## 463 True 467 ## 467 True 479 ## 479 True 487 ## 487 True 491 ## 491 True 499 ## 499 True 503 ## 503 True 509 ## 509 True 521 ## 521 True 523 ## 523 True 541 ## 541 True 547 ## 547 True 557 From mensanator at aol.com Tue Mar 25 19:52:57 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 25 Mar 2008 16:52:57 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: On Mar 25, 6:30?pm, kellygreer1 wrote: > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > Is there a page on this in the Python in a Nutshell or the Python > Cookbook? > Did I miss something? I don't know, the set() soution worked for me. >>> lstone = [1,2,3,3,4,5,5,6] >>> setone = set(lstone) >>> lsttwo = list(setone) >>> lstone [1, 2, 3, 3, 4, 5, 5, 6] >>> setone set([1, 2, 3, 4, 5, 6]) >>> lsttwo [1, 2, 3, 4, 5, 6] > > Kelly Greer > kellygre... at nospam.com > change nospam to yahoo From willsteve2003 at yahoo.ca Mon Mar 3 10:38:10 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 3 Mar 2008 07:38:10 -0800 (PST) Subject: Book Recomendations References: Message-ID: <25b90cd1-a672-4615-86dd-2afa1edb756b@d21g2000prf.googlegroups.com> The "Python Forum" has a good set of selections in their "General Forum" section: http://python-forum.org/pythonforum/viewtopic.php?f=1&t=12&st=0&sk=t&sd=a&sid=9b04b79b60f9afb56e4237856910d354&start=20 From simon at brunningonline.net Thu Mar 20 12:21:55 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 20 Mar 2008 16:21:55 +0000 Subject: if __name__ == '__main__': In-Reply-To: References: Message-ID: <8c7f10c60803200921p3c4a989ajf7797688072468e@mail.gmail.com> On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde wrote: > Hi, > I am new to the python and not getting meaning of following line, > > if __name__ == '__main__': > main() -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 20:32:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 00:32:51 -0000 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <7x63vfn3ix.fsf@ruckus.brouhaha.com> <8e4e1ae0-9a34-41c2-b253-7ea8846f6de5@i7g2000prf.googlegroups.com> <3880a377-30fe-49b3-a578-8d6203d526bb@s8g2000prg.googlegroups.com> Message-ID: <13udtljicjr9ied@corp.supernews.com> On Sun, 23 Mar 2008 15:55:43 -0700, John Machin wrote: > On Mar 24, 12:19 am, Dustan wrote: >> On Mar 21, 3:57 pm, Paul Rubin wrote: >> >> > From at home writes: >> > > if 'one' and 'two' in f: >> > > alist.append(f) >> >> > Use: >> > if 'one' in f and 'two' in f: ... >> >> Personally, I would put parentheses around to be clearer: >> >> if ('one' in f) and ('two' in f): ... >> >> I'm not saying to put parentheses around everything, but in the more >> ambiguous cases, it certainly helps. > > Please help me understand why this is a "more ambiguous" case. Some people don't remember, and have no interest in forcing the people who read their code to memorize, the relative precedence of 'in' and 'and', and so don't expect folks to understand whether 'one' in f and 'two' in f means ('one' in f) and ('two' in f) or ('one' in (f and 'two')) in f or something else. This especially holds for people who have used languages where the precedences are less sensible than they are in Python. By memory, standard Pascal uses the second interpretation if you don't use parentheses, which is stupid, but there you go. > To me, alternative interpretations have extremely low scores for > utility and likelihood: Outside of the interactive interpreter, I prefer to know what my code does before I write it, rather than guess that it's unlikely to be wrong. (Or at least *think* I know what it does, which is not always the same thing as knowing what it does.) -- Steven From martin at v.loewis.de Sun Mar 2 16:05:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Mar 2008 22:05:14 +0100 Subject: [ANN] Python 2.3.7 and 2.4.5, release candidate 1 Message-ID: <47CB168A.103@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release candidates of Python 2.4.5 and 2.4.5. Both releases include only security fixes. Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.3 or 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interprerter may have crashed before). Assuming no major problems crop up, a final release of Python 2.4.4 will follow in about a week's time. For more information on Python 2.3.7 and 2.4.5, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3.7 http://www.python.org/2.4.5 Highlights of the previous major Python releases are available from the Python 2.4 page, at http://www.python.org/2.3/highlights.html http://www.python.org/2.4/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From grflanagan at gmail.com Tue Mar 4 01:51:47 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Mon, 3 Mar 2008 22:51:47 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: <75d14972-4dba-4311-9c06-63b3a2859f96@n75g2000hsh.googlegroups.com> On Mar 4, 6:31 am, castiro... at gmail.com wrote: > On Mar 3, 10:01 pm, Benjamin wrote: > > > > > On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > > > > What are metaclasses? > > > Depends on whether you want to be confused or not. If you do, look at > > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/. > > > Basically, the metaclass of a (new-style) class is responsible for > > creating the class. This means when Python sees > > class Foo(object): > > __metaclass__ = FooMeta > > class FooMeta(type): > > def __new__(cls, name, bases, dct): > > #do something cool to the class > > pass > > It asks FooMeta to create the class Foo. Metaclasses always extend > > type because type is the default metaclass. > > But you can stack class decorations, but not class metas. > > @somethingcool1 > @somethingcool2 > class Foo: > pass > > * class Foo: > __metaclass__= MetaCool1, MetaCool > > * denotes malformed ----------------------- class Meta1(type): def foo1(cls): print 'hello' class Meta2(type): def foo2(cls): print 'castiron' class Meta(Meta1, Meta2): pass class Base(object): __metaclass__ = Meta Base.foo1() Base.foo2() ----------------------- Gerard From simon at brunningonline.net Wed Mar 19 07:51:45 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 Mar 2008 11:51:45 +0000 Subject: PODCasts In-Reply-To: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> References: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> Message-ID: <8c7f10c60803190451y30d0ca20g6a57356a47676d43@mail.gmail.com> On Wed, Mar 19, 2008 at 9:06 AM, Mike D <42flicks at gmail.com> wrote: > I really should say net cast as I think it's a better term ;) Since I'm working at The Guardian, I'm bound to stand up for the term 'podcast'. ;-) Besides, it's very established now - too late to fight it. > Does anyone have any recommended net casts on Python, or programming in > general? > > Whats everyone listening to? Python411: This Week in Django: Plus a bunch of non-Python related stuff. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From jameswhetstone at comcast.net Sat Mar 22 19:42:17 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Sat, 22 Mar 2008 16:42:17 -0700 Subject: How to use boost.python to wrap a class with a pure virtual function that has a 'void *' argument References: Message-ID: I found a solution to this problem: void handleMessage(void *message) { int size = getSize(message); PyObject *obj = PyBuffer_FromMemory( message, size ) ; boost::python::handle<> h(obj); PyGILState_STATE gstate = PyGILState_Ensure(); try { call(this->get_override("handleMessage").ptr(), h); } catch (const error_already_set) { // Catch and ignore exception that is thrown if Python // onMessage raised an exception. Print it to sys.stderr, // since there is nothing we can do about it here. PyErr_Print(); } PyGILState_Release(gstate); } "James Whetstone" wrote in message news:ubudndoRENZA-3janZ2dnUVZ_u-unZ2d at comcast.com... > As the subject implies, I'm having trouble wrapping a C++ class that looks > like this: > > struct A > { > virtual void handleMessage(void *message)=0; > }; > > > To wrap this class, I've written the following code: > > struct AWrapper : A, wrapper > { > void handleMessage(void *message) > { > this->get_override("handleMessage")(message); > } > }; > > class_("A") > .def("handleMessage", pure_virtual(&A::handleMessage)) > ; > > > My python test code looks like this: > > import APackage > > class aclass(APackage.A): > def handleMessage(msg) : print msg > > > But this code crashes when the handleMessage function is called in python > (I think) because 'void *' cannot be marshalled. Is there some way around > this? Also, since the void* object is intended to be "zero copy", I > should probably convert the void * to a PyObject first and re-write my > handleMessage to look like this: > > void handleMessage(void *message) > { > int size = getMessageSize(message); > > PyObject *obj = PyBuffer_FromReadWriteMemory(message, size); > > this->get_override("handleMessage")(obj); > } > > Has anyone done this type of thing? I'm writing this code using MS Visual > Studio 8 and if anyone can help, it would *very* appreciated. > > Thanks! > James > > > > From fredrik at pythonware.com Sun Mar 30 12:35:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Mar 2008 18:35:37 +0200 Subject: regarding xml elements In-Reply-To: <66657.48471.qm@web8713.mail.in.yahoo.com> References: <66657.48471.qm@web8713.mail.in.yahoo.com> Message-ID: Raj kumar wrote: > document.createElement("abc") > and i appeneded it by using append() method. > But how i can reflect this change to my xml file? write it out again: http://python.org/doc/current/lib/dom-objects.html From alitosis at gmail.com Thu Mar 13 23:41:12 2008 From: alitosis at gmail.com (alitosis at gmail.com) Date: Thu, 13 Mar 2008 20:41:12 -0700 (PDT) Subject: Problem with exec References: Message-ID: On Mar 14, 9:47 am, Justus Schwabedal wrote: [snipped] > However when I do this: > > bash-3.2$ cat execBug2.py > #! /usr/bin/python > header=""" > from scipy import randn > def f(): > return randn() > """ > def g(): > exec header > return f() > print "g() =",g() > bash-3.2$ ./execBug2.py > g() = > Traceback (most recent call last): > File "./execBug2.py", line 10, in > print "g() =",g() > File "./execBug2.py", line 9, in g > return f() > File "", line 4, in f > NameError: global name 'randn' is not defined > bash-3.2$ ??? > > I get this global name error. I can fix it with adding some line like > "global randn" but I don't want to do this. I want to do exactly what I wrote: Import the function scipy.randn in the local namespace of the > > function "g" so that "return f()" makes sense. Can anybody help me out? > Yours Justus Maybe using an explicit namespace is good enough for your needs: #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ def g(): n = {} exec header in n return n['f']() print "g() =",g() (i don't understand the issues, but I can cut-and-paste with the best of them) From http Sun Mar 9 00:32:04 2008 From: http (Paul Rubin) Date: 08 Mar 2008 21:32:04 -0800 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6i47r3uoo6b4@corp.supernews.com> Message-ID: <7x3ar0wjhn.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Unfortunately that doesn't work reliably. > > >>> a, b = 9007199254741000.0, -3.0 > >>> a/b > -3002399751580333.5 > >>> (a+b-1)//b # should be -3002399751580333 > -3002399751580332.0 I should have mentioned (a+b-1)//b expects a and b to be positive integers. From rbonvall at gmail.com Fri Mar 7 17:11:13 2008 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Fri, 7 Mar 2008 14:11:13 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> Message-ID: <3fd35f79-f0b0-4d6d-8430-eab452118b37@m34g2000hsc.googlegroups.com> On Mar 7, 6:16 pm, Steven D'Aprano wrote: > I believe it is one of those things that everybody (for some value of > "everybody") does because that's what they were taught to do Actually I was never taught to, and I never learnt about it anywhere. I started to do it spontaneously in order to tell apart end-of-sentence periods from abbreviation periods. Anyway, I don't think it's something people should be forced to do. -- Roberto Bonvallet From python.list at tim.thechases.com Sun Mar 9 20:52:50 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 Mar 2008 19:52:50 -0500 Subject: any chance regular expressions are cached? In-Reply-To: References: Message-ID: <47D48662.4090002@tim.thechases.com> > s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save > me the trouble of having to declare some global re's if I don't > want to have them recompiled on each function invocation? >>> import this ... Explicit is better than implicit ... Sounds like what you want is to use the compile() call to compile once, and then use the resulting objects: re1 = re.compile(r'\n') re2 = re.compile(r'^') ... s = re1.sub('\n' + spaces, s) s = re2.sub(spaces, s) ... The compile() should be done once (outside loops, possibly at a module level, as, in a way, they're constants) and then you can use the resulting object without the overhead of compiling. -tkc From castironpi at gmail.com Sat Mar 15 03:21:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 00:21:42 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <13tmo994bgqjr11@corp.supernews.com> Message-ID: On Mar 15, 12:39?am, Dennis Lee Bieber wrote: > On 14 Mar 2008 10:38:52 GMT, Antoon Pardon > declaimed the following in comp.lang.python: > > > In that case I find it very strange that when this question comes > > up, I see so few attempts to explain how the assignment acctually > > works. > > ? ? ? ? I'll probably get burned for this... but as far as I'm concerned, > assignment works very simply... At the very bottom of the name > resolution, assignment works by changing the left-hand-side "reference" > from any prior object for whatever object represents the result of the > right-hand-side. > > ? ? ? ? A bare LHS name is rebound in total. > ? ? ? ? ? ? ? ? lhs_name = rhs_expresssion > > ? ? ? ? A qualified LHS name (a name followed by a ".subname", or a > "[index]", or a "[keyvalue]") rebinds the specified subcomponent of > "name" -- that is, "name" remains bound to some object, and the > ".subname" (or "[index]" or "[keyvalue]") component of that object is > what is rebound to the RHS object. > ? ? ? ? ? ? ? ? lhs_name.subcomponent = rhs_expression > ? ? ? ? ? ? ? ? lhs_name[index] = rhs_expression > ? ? ? ? ? ? ? ? lhs_name[keyvalue] = rhs_expression > > ? ? ? ? No matter how many "." or "[]" sets appear, at the very bottom one > has focused down to a component, and that component get rebound from one > object to another object. > > ? ? ? ? In no case does the object originally bound get changed. FOR > assignment... Mutables using methods are a bit different... > > ? ? ? ? lhs.append(rhs) ? ? ? ? #assume a list > > adds a new element into the list, but it is still the same "list" (and > in that aspect, it is also a "qualified name"). You could warn if a name is assigned to twice-- maybe even error. Assignment is not a method. a= object() a= object() a is a name. it is a name of an object. what name? a. what object? that changes on demand. >>> a= 2 >>> a+= 2 >>> a 4 >>> a= (2,) >>> a+= (3,) >>> a (2, 3) >>> a= 2 >>> id( a ) # 1 505252512 >>> a+= 2 >>> id( a ) 505252544 # != >>> a 4 >>> a= (2,) >>> id( a ) # 2 11863472 >>> a+= (3,) >>> id( a ) # != 11933976 >>> a= [2] >>> id(a) # 3 11935296 >>> a+= [3] >>> id(a) # == 11935296 >>> += changed the id of a in the first two cases. It did not in the third. Assignment is not a method. Sometimes augmented assignment is. In the first two cases, the original was destroyed. In the third, the newcomer was destroyed. The newcomer was also destroyed in the first two. If you can write 'a' on an envelope and it goes to 244 White St., then assigning to a is an order to the post office: send 'a' to somewhere else. It doesn't change what it referred to before, though-- those letters are already delivered! There is ambiguity in 'change "a"'-- it can mean 'at the post office' or 'wherever letters address to "a" go to'. However, you can't change the entry of "a" with the post office of another scope. >>> "I want 'a' to be [3]." AmbiguityError: Use 'rearrange' or 'reroute'. >>> "Rearrange 'a'. Move out and move 3 in." a[:]= [3] >>> "Reroute 'a'. Move 3 in to the place wither mail to 'a' will go." a= [3] Some buildings have no entries at the post office. Some names don't either. You can change the contents of a building if you can send mail to it-- send a letter that says to change the contents! Other post offices keep their entries. >>> "Change another post office's entry for 'a'." No. >>> "Change mine." Ok! From martin at v.loewis.de Sat Mar 8 09:35:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Mar 2008 15:35:22 +0100 Subject: os.chdir In-Reply-To: References: Message-ID: <47D2A42A.9010902@v.loewis.de> >> os.chdir("~/dir1") > > It is not mentioned in the documentation but I'm pretty sure os.dir() doesn't do > tilde expansion since this is usually performed by a shell. > > You should use instead: > > os.chdir(os.join(os.environ['HOME'], 'dir1')) Or os.chdir(os.path.expanduser("~/dir1")) Regards, Martin From timr at probo.com Thu Mar 13 03:02:33 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 13 Mar 2008 07:02:33 GMT Subject: mulithreaded server References: <7c555afb-2df0-43f2-aa16-d1e48da1510a@e23g2000prf.googlegroups.com> Message-ID: asit wrote: > >In the above program, why there is an unhandeled exception ??? Probably because the code as you posted it has at least a half-dozen mistakes. >import socket >import sys >import thread > >p=1 >PORT=11000 >BUFSIZE=1024 > >def getData(cSocket): > global stdoutlock,cSocketlock > while True: > cSocketlock.acquire() > data=cSocket.recv(BUFSIZE) > if data=='q': > data='client exited' > cSocket.close() > p=0 > cSocketlock.release() > stdoutlock.acquire() > stdout.write(data) > stdoutlock.release() You do not need the "global" statement there, since you are not changing either stdoutlock or cSocketlock. However, you ARE setting "p", so you need a "global p". Otherwise, you are simply creating a variable called "p" that is local to the function, and which disappears when the function returns. Calling a global variable "p" is a very bad practice, by the way. >def sendData(cSocket): > global stdoutlock,cSocketlock > while True: > stdoutlock.acquire() > data=raw_input('>>') > cSocketlock.acquire_lock() > if data=='q': > stdout.write('server exited') > stdout.release() > p=0 > cSocket.close() > sSocket.send(data) > sSocketlock.release() Same comments. You do not need the "global" statement you have, but you do need "global p" if you want to change the global version of "p". Further, as Jean-Paul pointed out and you rather rudely ignored, there is no variable called "sSocketlock", because you commented it out. Next, "stdout.release()" will fail. "stdout" does not have a release function. You meant "stdoutlock.release()". Next, you release sSocketlock, but you never acquired it. And if data does not equal "q", you repeatedly acquire stdoutlock, but you never release it. Fix these problems, and then see if you can ask for help in a more thorough fashion. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ron at example.com Fri Mar 28 22:16:04 2008 From: ron at example.com (Ron Eggler) Date: Sat, 29 Mar 2008 02:16:04 GMT Subject: last mouse movment or keyboard hit References: <6512egF2dik46U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Ron Eggler schrieb: >> Hi, >> >> I would like to get the time of the most recent human activity like a >> cursor movement or a key hit. >> Does anyone know how I can get this back to start some action after there >> has been no activity for X minutes/seconds? > > Try hooking yourself into the OS screen-saver-code. I have looked at the KDE code but couldn't quite figure out how it's working... :o Any help would be appreciated! -- chEErs roN From adece91f7 at 21cn.com Tue Mar 18 03:20:15 2008 From: adece91f7 at 21cn.com (Designers Handbags) Date: Tue, 18 Mar 2008 00:20:15 -0700 (PDT) Subject: Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M, Best Luxury Replica Watches Message-ID: Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M, Best Luxury Replica Watches Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M Link : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_14060M.html Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M Information : Brand : Swiss Rolex Watches ( http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/swiss_rolex_replica_watches_1.html ) Gender : Mens Case Material : Stainless Steel Case Diameter : 14060M, Rolex-14060M Case Thickness : 40mm Dial Color : Black Bezel : Black Movement : 31 jewel chronometer movement Clasp : Stainless Steel Water Resistant : Item Variations : Our Price : US $451 Rolex Oyster Perpetual Submariner 31-Jewel Movement Stainless Steel Case - 40mm Special Time-Lapse Bezel Synthetic Sapphire Crystal Black Dial, Black Bezel Stainless Steel Oyster Bracelet Fliplock Clasp and Extension Link Pressure Proof to 1000 Feet Model Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M is new brand replica, join thousands of satisfied customers and buy your with total satisfaction. A Replica-Watch-Shopping.com 30 Day Money Back Guarantee is included with every Swiss Rolex Watches Replica Series for secure, risk-free online shopping. Replica-Watch-Shopping.Com does not charge sales tax for the Fake Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M. The Same Chopard Watches Series : Swiss Rolex Oyster Perpetual Submariner Date 18kt Gold Mens Watch 16618B : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16618B.html Swiss Rolex Oyster Perpetual Submariner Date 18kt Gold Mens Watch 16618 : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16618.html Swiss Rolex Oyster Perpetual Submariner Date Two-Tone Steel Mens Watch 11613BK : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16613BK.html Swiss Rolex Oyster Perpetual Submariner Date Steel Mens Watch 16610 : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16610.html Swiss Rolex Oyster Perpetual Submariner Date Mens Watch 16613-BLSO : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_Mens_Watch_16613BLSO.html Swiss Rolex Oyster Perpetual Submariner Date Mens Watch 16613-GYDO : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_Mens_Watch_16613GYDO.html Swiss Rolex Oyster Perpetual Submariner Date 18kt Gold with Diamonds and Sapphires Mens Watch 16613CDD : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16618DD.html Swiss Rolex Oyster Perpetual Submariner Date Two-Tone Steel with Diamonds and Sapphires Mens Watch 16613CDD : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16613CDD.html From oswald.harry at gmail.com Fri Mar 28 11:15:48 2008 From: oswald.harry at gmail.com (harryos) Date: Fri, 28 Mar 2008 08:15:48 -0700 (PDT) Subject: finding euclidean distance,better code? References: Message-ID: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> > The code is pretty legible as it is now. Anyway, using min() and a > generator: > > hi is this calculated distance really Euclidean distance? When i checked wikipedia http://en.wikipedia.org/wiki/Euclidean_distance it shows a calculation involving sum of squares of the differences of elements.Here in this code ,the sum of coordinates are used? is that a different measure? oharry From jergosh at wp.pl Wed Mar 26 09:37:11 2008 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Wed, 26 Mar 2008 14:37:11 +0100 Subject: Beta testers needed for a high performance Python application server In-Reply-To: References: Message-ID: <47EA5187.3060405@wp.pl> > Why not just put it on the net somewhere and tell us where it is? > People aren't generally going to want to help or even look at it if > you treat it like a proprietary application. So, put the documentation > and code up somewhere for all to see. > http://www.yieldserver.com:8081/ From bignose+hates-spam at benfinney.id.au Wed Mar 5 17:36:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 06 Mar 2008 09:36:29 +1100 Subject: Identifying messages in a thread (was: Please keep the full address) References: Message-ID: <8763w094sy.fsf_-_@benfinney.id.au> "D'Arcy J.M. Cain" writes: > On Wed, 5 Mar 2008 13:38:59 -0800 (PST) > Mike Driscoll wrote: > > On Mar 5, 12:50 pm, castiro... at gmail.com wrote: > > I'm not sure why you change the address like this but could you > please include the full address. It's a misfeature of Google's mail interface. The poster to whom you're responding could choose a different mail interface, but you'll have a difficult time convincing them of that. > Those of us who identify the time wasters would also like to drop > the responses to their posts and changing the address makes this > impossible. Not at all. AFAIK the messages from Google mail correctly include the 'In-Reply-To' field or the 'References' field in the message header. So, you can know by those fields whether a message is part of a thread you've previously identified. -- \ "I wish there was a knob on the TV to turn up the intelligence. | `\ There's a knob called 'brightness' but it doesn't work." -- | _o__) Eugene P. Gallagher | Ben Finney From michael.wieher at gmail.com Wed Mar 5 17:12:49 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 5 Mar 2008 16:12:49 -0600 Subject: What is a class? Message-ID: You import classes from modules. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Mar 17 08:42:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 10:42:24 -0200 Subject: pass float array(list) parameter to C References: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 01:17:31 -0200, zaley escribi?: > In my program, python is communicated with C use ctypes . > I can't find a better way to pass float array(list) parameter to C > function. > Can someone give me a help? Use the array module to create an array of floats, like float[] in C. http://docs.python.org/lib/module-array.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 18:32:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Mar 2008 22:32:10 -0000 Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <13u353a51v9kp36@corp.supernews.com> On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote: > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but calculate/ > compare in UTC. Your proposal is ambiguous. What does that mean? Can you give an example? > - Raise exceptions when an illegal or ambiguous datetime is instantated. You mean like they already do? >>> datetime.datetime(2008, 03, 35) # 35th of March Traceback (most recent call last): File "", line 1, in ValueError: day is out of range for month As for ambiguous, how can datetime arguments be ambiguous? Help on class datetime in module datetime: class datetime(date) | datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) What possible ambiguity is there? -- Steven From knut.urbye at gmail.com Wed Mar 26 10:17:15 2008 From: knut.urbye at gmail.com (Python Programming on Win32) Date: Wed, 26 Mar 2008 07:17:15 -0700 (PDT) Subject: py2exe socket.gaierror (10093) Message-ID: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Hi, I have encountered a problem which I can not figure out a solution to. Tried Googeling it, but to no help unfortunately. The problem is running smtplib in a py2exe compiled exe file. When it tries to establish a socket to the mail server it fails. Just wondering someone has encountered this before, and if someone might be able to point me in the right direction. Unhandled exception in thread started by Traceback (most recent call last): File "AutomationThread.pyc", line 152, in Run File "mail.pyc", line 11, in sendMail File "smtplib.pyc", line 244, in __init__ File "smtplib.pyc", line 296, in connect socket.gaierror: (10093, 'getaddrinfo failed') Thank you ! From wuwei23 at gmail.com Tue Mar 25 07:36:55 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Mar 2008 04:36:55 -0700 (PDT) Subject: My python interpreter became mad ! References: Message-ID: <95b7d0b1-345b-40b2-bf9a-b9783ccbee1e@s13g2000prd.googlegroups.com> On Mar 25, 9:05 pm, Benjamin Watine wrote: > I'm trying to use re module to match text with regular expression. In a > first time, all works right. But since yesterday, I have a very strange > behaviour : The following line in the traceback shows you're not using the default python module: > File "/etc/postfix/re.py", line 19, in ? Were you using the interpreter in the /etc/postfix directory? The re module there seems to be shadowing the site package. Hope this helps. - alex23 From castironpi at gmail.com Mon Mar 17 18:38:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 15:38:58 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> On Mar 17, 11:03?am, Duncan Booth wrote: > Ninereeds wrote: > > On Mar 17, 1:31 pm, Duncan Booth wrote: > > >> A common explanation for this is that lists are for homogenous > >> collections, tuples are for when you have heterogenous collections i.e. > >> related but different things. > > > I interpret this as meaning that in a data table, I should have a list > > of records but each record should be a tuple of fields, since the > > fields for a table usually have different forms whereas the records > > usually all have the same record layout. > > That is indeed what Python's Database API usually does (although it doesn't > mandate it): > > ? ? ? ? .fetchmany([size=cursor.arraysize]) > > ? ? ? ? ? ? Fetch the next set of rows of a query result, returning a > ? ? ? ? ? ? sequence of sequences (e.g. a list of tuples). An empty > ? ? ? ? ? ? sequence is returned when no more rows are available. Two things: >>> b in b False in S. D'Aprano's example, which somewhat obscures (casts a shadow on) its intuitive meaning. "Hand me everything that's in there. > For x in There: hand( me, x ). > For x in rchain( There ): hand( me, x ) < Hand me anything that's in anything that's in there, or is in there. Closet = [ Box[ ball ] ] > Box[ ball ]? or Box, ball? Despite that 'in' is a very common word [lacks cit.], you don't often get ambiguities (read: questions) about containers in something. Too custom. The word isn't defined at that extremity of combinations / cartesian products of particulars (context). It doesn't have a common sense, and computer science is a pretty unique field in that it finds (or, invents) all-and-only definitions of words. (Which reminds me, what about a classmethod __getitem__ construtor?) However, from mathematics, which is at least older, if not more in tune with the common senses and uses, (there exists an a and b such that) Member( a, b ) != Exists x such that Member( a, b ) & Member( b, x ). In other words, Python honors math's definition. In the example, would you treat 'ball' separately unless explicity asked to? (But, keep sure not to alter the contents of any of the containers that are in there.) There's a fine example of miscommunication: neither behavior was the default between the pair: one knew one default; the other knew another. (But, it's ok to alter the contents of any containers.) Aside, do you think there are trends among who and when uses what defaults? Such as math background, social status, etc.? Computers are very good at attention to detail: ("I" am.) "You did not specify whether to alter containers in it." Of course, the program that's following would have to have noticed two things: that there's a short-cut if you can, and you might not want it to. It's not only a problem of formal systems: No= { X, Y, Z }. Some (finite) context hasn't determined the convention of wish-expression in every combination of (future possible) cases. while 1: print( "You made an assumption!" ) print( "No, -you- made an assumption!" ) break while 1: print( "I made an assumption." ) print( "I also made an assumption." ) But is it determined whether it's determined whether the person meant to? That is, can you tell whether the person didn't specify? "I'm sorry, we haven't spoken about containers in containers enough for me to tell what your wishes are." My worry is that popular judgment isn't best in science. What factors in to the architect's decision? His feelings about use cases? His calculations about use cases? His feelings about popularity of each? His calculations about popularity? Mabye Python would have ten extra speakers if __contains__ had been defined differently! X percent of all shortest-form syntactic combinations can be written in less tokens with one definition, but no matter how much I remind them, they won't remember combination C, so only Y percent are actually, practically ever written in 2008 Earth programming. Because we're stupid, no. Because we have other priorities than programming. (But my bigger house for me was more important.) 'rchain', recursive chain, might be the next function on the path that itertools is on. Databases have come to (but don't have to stay) use integers as autokeys in records. That makes one way to refer to a record to refer to its integer. However, if one's testing for identity between records, that key is redundant. Just identify yourself, and refer back to earlier in context. And incidentally, why namedtuples but no namedlists? Or nameddicts? And could one define an anonymous type? This is interesting: >>> type('A',(),{}) is type('A',(),{}) False >>> type('A',(),{}) == type('A',(),{}) False >>> type('G',(),{}) >>> G Traceback (most recent call last): File "", line 1, in NameError: name 'G' is not defined A type went out of scope. Is there an abstraction of 'pickle' which doesn't need the type defined in its target module? >>> pickle.dumps( type('A',(),{}) ) pickle.PicklingError: Can't pickle : it's not the same object as __main__.A >>> pickle.dumps( type('A',(),{})() ) pickle.PicklingError: Can't pickle : it's not the same object as __main__.A >>> del A >>> pickle.dumps( type('A',(),{}) ) pickle.PicklingError: Can't pickle : it's not found as __main__.A >>> pickle.dumps( type('A',(),{})() ) pickle.PicklingError: Can't pickle : it's not found as __main__.A But all the information's there! From matiassurdi at gmail.com Sun Mar 30 08:29:07 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Sun, 30 Mar 2008 14:29:07 +0200 Subject: python ODF library? Message-ID: Do yo know any good OpenDocumentFormat library for python? I'm starting a project on wich I'll have to programatically modify ODF text documments, so, after reinventing the wheel, I'd like to know if already something exists. Thanks a lot. From deets at nospam.web.de Sun Mar 23 15:01:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 23 Mar 2008 20:01:21 +0100 Subject: A "roadmap" for ctypes wrapping? In-Reply-To: References: Message-ID: <64nno9F2d12tkU1@mid.uni-berlin.de> Alaric Haag schrieb: > Hi all, > > I'm undertaking a pretty significant wrapping project (a linux > shared-object lib) early in my Python experience, and thought it might > be useful for many more that just myself if this thread were to produce > a sort of roadmap for approaching wrapping with ctypes. > > I've been doing some reading, but want to verify my "big picture view" > and have come to make the following presumptions: (so, please correct me > where erroneous) > > - One gathers the ".h" header(s) for the library to determine the data > structures (defined in "#define" and "typedef" statements) as well as > the prototypes for the library routines. > > - From these header files, one defines attributes to reproduce the > "#define" statements, and also reproduces the typedef "structs" by > defining classes and assigning a Python list of tuples for the > "_fields_" attribute, to associate a ctype and field name with each > field in the "struct". > > - Use ctypes.CDLL to "connect" to the library, and instantiate an object > whose attributes are the library routines. > > - From that object, instantiate each of the routines, and override the > "argtypes" attribute for each of these with a list of "ctypes", and a > single ctype for the "restype" attribute. In either case, the "type" > might be a newly-defined type (class) that's more complex than just the > provided ctypes. > > Presumably, judicious use of the leading "_" (underscore) is used to > hide (make private) the "ugly details" from the wrapper user, revealing > only the routines, and possibly, classes that describe data types the > original API expects the user to need. > > ====== > Can anyone with some "wrapping" experience add/modify/enhance the above? Use gccxml to gather the typedefs. And look at Gary Bishop's site to see some cool helper classes/functions for dealing with ctypes. Diez From magdoll at gmail.com Wed Mar 12 12:41:42 2008 From: magdoll at gmail.com (Magdoll) Date: Wed, 12 Mar 2008 09:41:42 -0700 (PDT) Subject: merging intervals repeatedly References: Message-ID: > Hi, > > The problem, as stated here, may have several solutions. For instance > the following set of intervals also satisfies the constraint: > (1,15), (20,40), (50,100) > > One question you should ask yourself is: do you want all solutions? or > just one? > If you want just one, there's another question: which one? the one with > the most intervals? any one? I actually don't know which solution I want, and that's why I keep trying different solutions :P > If you want all of them, then I suggest using prolog rather than python > (I hope I won't be flamed for advocating another language here). Will I be able to switch between using prolog & python back and forth though? Cuz the bulk of my code will still be written in python and this is just a very small part of it. > > > Is there already some existing code in Python that I can easily take > > advantage of to produce this? Right now I've written my own simple > > solution, which is just to maintain a list of the intervals. I can use > > the Interval module, but it doesn't really affect much. I read one > > interval from the input file at a time, and use bisect to insert it in > > order. The problem comes with merging, which sometimes can be > > cascading. > > > ex: > > read (51,65) ==> put (51,65) in list > > read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) > > read (50,66) ==> merge with (51,65) to become (50,66) ==> now can > > merge with (62,100) > > The way this algorithm is presented suggests an additional constraint: > you cannot merge two intervals if their overlap <= N. In that case, > there is a single solution indeed... > Nitpick: you cannot merge (50,66) and (62,100) since their overlap is > still <= 5. Sorry I keep messing up my example. I meant, I would merge them if they overlap by >= N....but anyways. > > If you have a reasonable number of intervals, you're algorithm seems > fine. But it is O(n**2), so in the case you read a lot of intervals and > you observe unsatisfying performances, you will have to store the > intervals in a cleverer data structure, see one of these:http://en.wikipedia.org/wiki/Interval_treehttp://en.wikipedia.org/wiki/Segment_tree Thanks! Both of these look interesting and potentially useful :) From aahz at pythoncraft.com Sat Mar 15 11:33:01 2008 From: aahz at pythoncraft.com (Aahz) Date: 15 Mar 2008 08:33:01 -0700 Subject: Joseph Weizenbaum References: Message-ID: In article , Tim Roberts wrote: >Jeff Schwab wrote: >>Roel Schroeven wrote: >>> castironpi at gmail.com schreef: >>>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>>> >>>>> How do you feel about creator of Eliza? >>>> >>>> What is Eliza? >>> >>> Does that question interest you? >> >>Well played, sir. >> >>Earlier you said what is Eliza. Do you still feel that way? > >I am embarrassed to say that this vaguely disrespectful exchange made me >laugh out loud. Serious: why do you think this is disrespectful? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From d3vvnull at gmail.com Tue Mar 18 18:09:19 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 18 Mar 2008 17:09:19 -0500 Subject: finding items that occur more than once in a list In-Reply-To: <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: <170543c70803181509i51149fd9v45de2f82b642af1@mail.gmail.com> How about using list comprehension? l1 = ["apples","apples","bananas","oranges","oranges","peaches"] s1 = set([x for x in l1 if l1.count(x) > 1]) On Tue, Mar 18, 2008 at 4:56 PM, sturlamolden wrote: > On 18 Mar, 22:25, sturlamolden wrote: > > > def nonunique(lst): > > slst = sorted(lst) > > return list(set([s[0] for s in > > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) > > Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using > the set function, there is more structure to exploit when the list is > sorted: > > > def nonunique(lst): > slst = sorted(lst) > dups = [s[0] for s in > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > return [dups[0]] + [s[1] for s in > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sun Mar 16 23:20:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 16 Mar 2008 20:20:09 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 10:49 pm, Brian Jones wrote: > On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: > > > If you did not like the programming this year (aside from the sponsor > > talks) and you did not participate in organizing PyCon or in delivering > > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > > I find this insulting, inexcusable, and utter nonsense. If putting the > blame for a failed experiment on the backs of the good folks who paid > good money for travel, lodging, and registration is also an > experiment, you can hereby consider it also failed. He said "aside from the sponsor talks", chief. You need one of these: http://tinyurl.com/26owvg Carl Banks From deets at nospam.web.de Mon Mar 10 18:18:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 23:18:02 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: <63i6j9F2793buU1@mid.uni-berlin.de> Message-ID: <63lqcuF27pbnbU1@mid.uni-berlin.de> metawilm at gmail.com schrieb: > On Mar 9, 2:21 pm, "Diez B. Roggisch" wrote: >> Is this soft-exception implemented anywhere, so that one can see what >> experiences and best practices have evolved around using it? > > Lie's idea is to separate exceptions in two groups, those that must be > handled and those that don't. A better way is to have two different > ways to raise exceptions: one exceptional situation can be "Hard" in > some situations and "Soft" in others, and it is up to the way of > raising to make the choice, while the exception stays the same. > > Common Lisp has two ways of raising: functions "error" and "signal". > Python's "raise" is like CL's "error": you end up in the debugger if > the exception is not handled. Exceptions that are raised by CL's > "signal" don't have to be caught: if there is no matching "except" > clause the raise statement becomes a "pass". > > Or as Wikipedia states nicely: "Conditions are a generalization of > exceptions. When a condition arises, an appropriate condition handler > is searched for and selected, in stack order, to handle the condition. > Conditions which do not represent errors may safely go unhandled > entirely; their only purpose may be to propagate hints or warnings > toward the user." How would that differ from something like this: with add_soft_handler(SoftException): invoke_something() ... # deep down in code raise_soft(SoftException()) The implementation of add_soft_handler and raise_soft is trivial - a bit of thread-local storage and a stack. I don't say that such mechanism isn't handy occasionally - I just don't see the need for specialized syntactical and/or interpreter-support. Diez From siona at chiark.greenend.org.uk Thu Mar 13 10:21:37 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Mar 2008 14:21:37 +0000 (GMT) Subject: How to send a var to stdin of an external software References: Message-ID: Benjamin Watine wrote: >How can I do this ? I would like a function like that : > > theFunction ('cat -', stdin=myVar) > >I don't need to get any return value. http://docs.python.org/lib/node534.html says this is spelt myVar = subprocess.Popen(["cat", "-"], stdout=subprocess.PIPE).communicate()[0] (Probably not obvious how to find this if you've not come across the backtick notation in shell or Perl.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fakeaddress at nowhere.org Thu Mar 6 03:37:07 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 08:37:07 GMT Subject: Dual look-up on keys? In-Reply-To: <13su60prq21ccd2@corp.supernews.com> References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: Grant Edwards wrote: > It may be obvious that he has a question. It's not the least > bit obvious what that question is. How can we efficiently implement an abstract data type, call it 'DoubleDict', where the state of a DoubleDict is a binary relation, that is, a set of pairs (x, y); and the operations on a DoubleDict are those on a Python set, plus: find_by_first(self, x): return [y where (x, y) in DoubleDict] find_by_second(self, y): return [x where (x, y) in DoubleDict] Python can implement this ADT directly as specified, but the find_by_ operations would run in time len(self). We want an implementation where the find_by's run in O(1 + k) where k is the length of the returned sequence. -- --Bryan From PurpleServerMonkey at gmail.com Sat Mar 22 04:45:37 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Sat, 22 Mar 2008 01:45:37 -0700 (PDT) Subject: Distributing Python Apps on Linux\BSD References: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> <9290c7b1-3e51-46fe-96e7-6c2ebf4f5b77@u10g2000prn.googlegroups.com> Message-ID: On Mar 22, 2:26 am, Miki wrote: > Hello, > > Disclaimer: I'm not an expert on the subject. > > > Setuptools and friends seem to be focused on distributing modules, I'm > > at the other end of the scale where I want to distribute an entire > > application so that an Administrator can run a single install and have > > a fully operational product. A key requirement is that I want the > > application to fit in with what and admin would expect an application > > to look like at the system level i.e site-packages like structures > > aren't suitable. > > You do that with distutils as well. > > > So far I've thought of using a configure script and make which would > > call some custom python installer script to do the actual install. It > > fits in nicely with what I want to achieve but are there any better > > options out there, how are others doing the same thing? > > Every distro flavor has it's own installer: apt/deb, rpm, port, ... > On Windows you can use one of the free installer (InnoSetup and > friends). > > HTH, > -- > Miki http://pythonwise.blogspot.com Well I'm not really interested in rpms or deb packages right now, I want to get it to the point where it will run on BSD and Linux without using distribution specific tools. Using a tarball or the standard python tools would be best. The problem is all the documentation surrounding distutils and setuptools refers to modules, now I'm not sure why but it seems most Python developers think an application is the same thing as a module. Unless you are writing very small applications that's definitely not the case. So I guess the question is, using distutils or setuptools is it possible for a user to select where to install the application i.e / usr/local? If not then I think it's going to be tarball deployment with a custom setup script, was hoping there was a better way. From asr-1 at comcast.net Wed Mar 12 20:42:44 2008 From: asr-1 at comcast.net (Andrew Rekdal) Date: Wed, 12 Mar 2008 19:42:44 -0500 Subject: Big file Message-ID: I am working in the class constructor defining elements of an application. The problem is the file is getting unmanageble and I am wanting to extend the contructor __init__ to another file. Is it possible to import directly into the contructor the contents of another module file? If so how would this be done? Thanks -- andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sat Mar 8 18:52:40 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 09 Mar 2008 00:52:40 +0100 Subject: float / rounding question In-Reply-To: References: <13t456cmgfpdhbc@corp.supernews.com> Message-ID: Mark Dickinson schreef: > On Mar 7, 11:23 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote: >>> Sorry to come in so late in this discussion. Although it is correct to >>> say that many real numbers that have an exact decimal representation >>> cannot be exactly represented in binary, that is no excuse to print 53.6 >>> as 53.600000000000001. This is just lousy printing and the fact that >>> this kind of question comes up every week shows that it is confusing to >>> many people. >> Good. That's a feature, not a bug. > > Even so, it's not clear that Python's current behaviour couldn't be > improved. I have a mild dislike of the lack of consistency in the > following, which arises from Python arbitrarily stripping trailing > zeros from the result returned by the C library functions: > >>>> 10.1 > 10.1 >>>> 10.2 > 10.199999999999999 >>>> 10.3 > 10.300000000000001 >>>> 10.4 > 10.4 Actually I don't see what all the fuss is about. If you want a nicely rounded number, use print or str() or the % operator. *Only* when you use repr() or when the interactive interpreter uses it to print the value of the expression, you get something that doesn't look as nice. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ebenze at hotmail.com Sun Mar 16 11:38:35 2008 From: ebenze at hotmail.com (Eric B.) Date: Sun, 16 Mar 2008 11:38:35 -0400 Subject: Cannot build Python 2.4 SRPM on x64 platform References: Message-ID: "Michael Wieher" wrote in message news:fb251aba0803160709w475de08cg1cabedcfb2205672 at mail.gmail.com... > Sorry I don't have much of a better idea, but if I had this kind of > problem > with an RPM, I'd just grab the tarball and start hacking away at > ./configure > pre-requirements, trying to use --options to trim it down to the bare > minimal and see if I can get it to load up. Thanks for the suggestion. I did try to build from the tarball, and make & make install work fine, but I still don't have any lib64 directories. I get the impression that the config script doesn't build for 64bit platforms. Do I need to pass any particular arguments to the ./configure script and/or the make/make install commands in order to ensure this being built for 64bits? Thanks, Eric From solisgb at gmail.com Mon Mar 10 04:49:53 2008 From: solisgb at gmail.com (luis) Date: Mon, 10 Mar 2008 01:49:53 -0700 (PDT) Subject: unable to install gdal References: <15838144-b7a0-4d1b-98b3-fdfcfdb9a916@n75g2000hsh.googlegroups.com> Message-ID: <86d8bc35-24d5-4145-8421-94d71066209d@60g2000hsy.googlegroups.com> On 9 mar, 16:37, luis wrote: > Hi > > On Windows xp sp2 and python 2.4 > > Yesterday I running old versions of gdal, and I try to upgrade > > I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe > I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 > > I follow install's instructions fromhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython, > all is ok, I set path and path_data variables with correct values, but > whe I run a script, an error raises > > from osgeo import ogr > ? File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? > ? ? import _ogr > ImportError: DLL load failed: process not found > > Also I try with instructions fromhttp://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gda... > I move _gdal.pyd (and the others *.pyd) from my Python installation's > (C:\Python24\Lib\site-packages\osgeo) into my Python installation's > DLLs folder (C:\Python24\DLLs). > When I run the script the error message persists. > > Some help is welcome. If I install on a XP without previous installation of gdal, the installation works fine. Perhaps is a problem with XP's registry From furkankuru at gmail.com Wed Mar 26 07:13:17 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 13:13:17 +0200 Subject: embedded python pythonpath In-Reply-To: References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> <3a4a8f930803251822h5d423198yc318ed270ad7d92a@mail.gmail.com> Message-ID: <3a4a8f930803260413v62ae6935t9a4d3dfbf11dd4dc@mail.gmail.com> On Wed, Mar 26, 2008 at 3:49 AM, Gabriel Genellina wrote: > En Tue, 25 Mar 2008 22:22:41 -0300, Furkan Kuru > escribi?: > > > On 3/26/08, Gabriel Genellina wrote: > > > >> En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru > >> escribi?: > >> > >> > Actually, I do not want any .py or .pyc files around my executable. > >> > (including userdict, sys, site etc) > >> > I want to have just single zip file for all python files. > >> > >> Putting all of them into pythonNN.zip (NN depending on the Python > >> version > >> in use) should be enough, but I've never tried it. > > I had already tried putting all of them into pythonNN.zip but I had to > > copy it to the place > > where sys.path points in my case it was windows\system32\python25.zip > > It should be in the same directory as python25.dll; you don't have to use > windows\system32 if you copy python25.dll to your application directory. > I did not know that. Ok, I tried and it works! Thank you, -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From justus.schwabedal at gmx.de Wed Mar 12 20:11:56 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Thu, 13 Mar 2008 01:11:56 +0100 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: <13tgrqb132if842@corp.supernews.com> References: <13tgrqb132if842@corp.supernews.com> Message-ID: What do you need it for anyway? I just read about it and I think it's useless in python. On Mar 13, 2008, at 1:03 AM, Steven D'Aprano wrote: > On Wed, 12 Mar 2008 11:19:05 -0700, Alex wrote: > >> Hi all, >> >> The subject says pretty much all > > Only to people who know what the Perl BEGIN{} block means. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list From mensanator at aol.com Tue Mar 4 17:40:04 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 14:40:04 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <042d507d-f53d-4219-be6e-d6b7a1f1d6c4@s8g2000prg.googlegroups.com> Message-ID: <8aa1c242-db46-4479-a26c-07517b478714@n75g2000hsh.googlegroups.com> On Mar 4, 3:00?pm, Istvan Albert wrote: > On Mar 4, 3:13 pm, Mensanator wrote: > > > But what if _I_ wanted to make a repeatable sequence for test > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > on every call? > > Would it? I don't know, haven't tried it yet, merely extrapolating from how I _THINK_ it works. I used to be a System Test Engineer and had a gift for being able to walk up to hardware/software and break it. Spooky? No, because I could extrapolate from the design, I could often anticipate just where to nudge it to cause it to crash. I wasn't very popular with the programmers. > > It may just be that you are now itching to see a problem even where > there isn't one. No, no, no. That would be an oh-what-a-giveaway, wouldn't it? > > i. From db3l.net at gmail.com Tue Mar 4 18:59:14 2008 From: db3l.net at gmail.com (David Bolen) Date: Tue, 04 Mar 2008 18:59:14 -0500 Subject: is there enough information? References: <13s9u7dg24es73a@corp.supernews.com> <13spkb990ha3v6c@corp.supernews.com> Message-ID: Dennis Lee Bieber writes: > On Mon, 3 Mar 2008 08:11:43 -0500, Jean-Paul Calderone > declaimed the following in comp.lang.python: > >> I'm not sure, but you seem to be implying that the only way to use Windows' >> asynchronous I/O APIs is with threads. Actually, it is possible (and Twisted >> allows you) to use these as well without writing a threaded application. >> > I only pointed out that, on Windows, one can not use the common > /select()/ function with files. And one rarely sees examples of coding a > Twisted-style (emphasis on style) asynchronous callback system mixing > files and network sockes using the Windows-specific API. > > If using threads, the Windows asynchronous I/O isn't needed... let > the thread block until the I/O completes, then transfer the data (or a > message that the data is available) back to the main processing > thread... You're probably right that it's rare, but when needed, using the Windows asynchronous/overlapping API can provide a better solution than blocking threads depending on the needs at hand, and without involving any callbacks or Twisted-style programming. An example of mine is high performance serial port handling as part of a custom FHSS wireless adapter with a serial port interface to the PC. In this case, minimizing I/O latency was crucial since delays could mean missing a broadcast timeslot (about 15ms) on the wireless network. A serial port isn't a disk file, but certainly a "file" in the context of Windows handles. Early implementations used independent threads for reading/writing to the serial port and blocking during such operations, but that turned out to have an undesirable amount of latency, and was also difficult to interrupt when the threads were in a blocked condition. Instead I created a single thread that had a loop using overlapped I/O simultaneously in each direction as well as native Windows event objects for aborting or signaling that there was additional data to be written (the pending read I/O handled the read case). The main loop was just a WaitForMultipleObjects to handle any of the I/O completion indications, requests for more I/O or aborts. It was very high performing (low latency) with low CPU usage - measurably better than a multi-threaded version. Communication with the rest of the application was through a thread-safe bi-directional buffer object, also using native Win32 event objects. It worked similar to a queue, but by using the native event objects I didn't have the performance inefficiencies for reads with timeouts of the Python objects. The underlying Python primitives don't have the timeout capability built in, so reads with timeouts get implemented through checks for data interspersed with increasing sleeps, which adds unnecessary latency. Anyway, it worked extremely well, and was a much better fit for my needs than a multi-threaded version with blocking I/O, without it having to be Twisted-style. -- David From bronger at physik.rwth-aachen.de Sun Mar 16 04:42:14 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 16 Mar 2008 09:42:14 +0100 Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: <87od9f3vrt.fsf@physik.rwth-aachen.de> Hall?chen! castironpi at gmail.com writes: > [...] > *** English is SVO, subject-verb-object. French is too, unless the > object is direct: subject- direct-object -verb. Really? I thought this is only the case for pronouns. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From arnodel at googlemail.com Mon Mar 3 11:20:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 3 Mar 2008 08:20:42 -0800 (PST) Subject: Exception or not References: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Message-ID: <499b589c-ab2f-41de-a8ec-e5ba0abb0c4c@p25g2000hsf.googlegroups.com> Monica Leko wrote: > Suppose you have some HTML forms which you would like to validate. > Every field can have different errors. For example, this are the > forms: > > username > password > etc > > And you want to validate them with some class. Is this good pattern: [...] You could have a look at how django [http://www.djangoproject.com] and how they handle forms: http://www.djangoproject.com/documentation/newforms/ In fact their newforms module should work fine as a standalone. -- Arnaud From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 07:40:17 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 13:40:17 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: <47cfe620$0$9590$426a74cc@news.free.fr> Guillermo a ?crit : > Hello, > > This is my first post here. I'm getting my feet wet with Python and I > need to know how can I check whether a variable is of type dictionary. What makes you say you "need" to know this ? Except for a couple corner cases, you usually don't need to care about this. If you told us more about the actual problem (instead of asking about what you think is the solution), we might be of more help... > Something like this: > > if isdict(a) then print "a is a dictionary" Should this work for subclasses of dicts ? Should this work for non-subclasses of dict implementing the dict protocol ? From ra21vi at gmail.com Sat Mar 15 16:57:36 2008 From: ra21vi at gmail.com (Ravi Kumar) Date: Sun, 16 Mar 2008 02:27:36 +0530 Subject: Weight Problem Message-ID: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> An Interesting problem, """ A man has only 4 bricks of different weights, lies between 1-40KG, Also, the total weights of Brick A, B, C, D (ie A+B+C+D) is 40KG. The man uses that brick to calculate every possible weight from 1 KG to 40 KG in his shop. (only whole numbers 1KG, 2KG etc, not like 2.3KG) """ I thought it would really be good to solve it by python, and right now on the mid-way solving using very dirty approach. But I feel, using SETs with python in such would solve it better. Can anyone come with good solution, and maybe solution showing usage of Sets. -- -=Ravi=- -------------- next part -------------- An HTML attachment was scrubbed... URL: From HDoran at air.org Mon Mar 31 15:03:41 2008 From: HDoran at air.org (Doran, Harold) Date: Mon, 31 Mar 2008 15:03:41 -0400 Subject: Elementtree to parse xml Message-ID: <2323A6D37908A847A7C32F1E3662C80E017BDCA3@dc1ex01.air.org> I received some help on list with sample code on how to parse through an xml file using element tree. I now have this working using toy examples nicely. However, when I work to apply this to my actual xml file, I am hitting a roadblock. Is anyone on the list able to look at an xml file that I can send as well as my python code to offer suggestions? I would normally insert a minimal, commented example inside this email. But the xml file is a bit too big to put in this email. I am *very* close to having this resolved, but just need a nudge in the right direction. Thanks, Harold -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.laloux at gmail.com Fri Mar 28 08:10:56 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Fri, 28 Mar 2008 05:10:56 -0700 (PDT) Subject: chronic error with python on mac os/x 10.5 References: Message-ID: <2387e4a2-b9c1-4070-9416-27ee21cea2ec@e10g2000prf.googlegroups.com> I don't known pjsip but this problem generally occurs when the library (dylib) on which the file (.so) depends is not the good one > Googling this issue show that it is happening to many > libraries in python on mac. ?????? I am working in python on mac since a lot of time I seldom have such problems. When you compile a .so file, it depends on a dylib library and you must have the good one (version) From upton at virginia.edu Wed Mar 5 10:42:51 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 5 Mar 2008 10:42:51 -0500 Subject: OT: Failed saving throw In-Reply-To: References: Message-ID: <5504f9ac0803050742m351608f8h55851f7f234e4f63@mail.gmail.com> On 5 Mar 2008 07:36:37 -0800, Aahz wrote: > For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people > think we should build a tomb in his honor. ;-) Yeah, I just saw a tribute on Order of the Stick: http://www.giantitp.com/comics/oots0536.html From exarkun at divmod.com Wed Mar 12 16:02:54 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 12 Mar 2008 15:02:54 -0500 Subject: Does __import__ require a module to have a .py suffix? In-Reply-To: <05559d08-2479-4178-830c-adf65dfc733c@s37g2000prg.googlegroups.com> Message-ID: <20080312200254.6859.696992993.divmod.quotient.18440@ohm> On Wed, 12 Mar 2008 12:58:33 -0700 (PDT), George Sakkis wrote: >On Mar 12, 12:22 pm, mrstephengross wrote: > >> Hi all. I've got a python file called 'foo' (no extension). I want to >> be able to load it as a module, like so: >> >> m = __import__('foo') >> >> However, the interpreter tells me "No module named foo". If I rename >> it foo.py, I can indeed import it. Is the extension required? Is there >> any way to override that requirement? > >You can use execfile: > >foo = {} >execfile('foo', foo) > >Apart from the different syntax in accessing the module globals >(attributes with __import__ (foo.x) vs dict entries with execfile >(foo['x'])), there are probably more subtle differences but I can't >tell for sure. It would be nice if someone more knowledgeable can >compare and contrast these two appraches. Another difference is that when you import a module, its code is (usually) only executed once. Each import after the first just returns a reference to the already-created module object. When you use execfile, the code is re-evaluated each time. Jean-Paul From mark.e.tolonen at mailinator.com Tue Mar 4 02:15:59 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Mon, 3 Mar 2008 23:15:59 -0800 Subject: Command line arguments in Windows References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: "Mike Walker" wrote in message news:r76zj.40666$pM4.38793 at pd7urf1no... > >> If you run a python file, ie. just double clicking it the only >> argument you will have will be the filename of the script. If you >> create a shortcut to the script and in the target box add your >> arguments (if you have quotation marks place them after not inside) >> you will see your arguments. fwiw you answered yourself in the third >> paragraph. > > As I mentioned I am working from the command line, not clicking on the > icon. The only difference between it working and not is the python prefix, > which is why I was thinking this is some sort of file association problem. > > I probably wasn't as clear as I could have been in the third paragraph. > > argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] > python argtest.py arg1 arg2 arg3 - Works >From the command line, the 'ftype' and 'assoc' commands can be used view how an extension is handled: C:\>assoc .py .py=Python.File C:\>ftype Python.File Python.File="C:\Python25\python.exe" "%1" %* My guess is your command line looks something like this: Python.File="C:\Python25\python.exe" "%1" The script name is being passed, but not the rest of the arguments. I vaguely remember seeing this on an older version one of ActiveState's ActivePython installers. What version of Python are you running? --Mark From bbxx789_05ss at yahoo.com Mon Mar 10 23:51:44 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 10 Mar 2008 20:51:44 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <7cbb3d22-b69c-479b-bc9d-10d1ef9e86c9@b1g2000hsg.googlegroups.com> On Mar 10, 9:44?pm, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. > primes = [] > import math > import gmpy > while 1: > ? ? run = int(raw_input("Do you want to calculate primes? 1 = yes and > 2 = no. ")) > ? ? if run == 1: > ? ? ? ? y = int(raw_input("What number do you want to use as the final > number to calculate with? ")) > ? ? ? ? x = int(raw_input("What number do you want to start > calculating primes from? ")) > ? ? ? ? while x < 2: > ? ? ? ? ? ? print "Number must be at least 2 for math reasons." > ? ? ? ? else: > ? ? ? ? ? ? while x < y: > ? ? ? ? ? ? ? ? prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) > ? ? ? ? ? ? ? ? if prime < 0: > ? ? ? ? ? ? ? ? ? ? primes.append(x) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print x " is not prime. " # highlights the final " > here > ? ? ? ? ? ? ? ? x = x + 1 > ? ? ? ? ? ? print primes > ? ? elif run == 2: > ? ? ? ? break > ? ? else: > ? ? ? ? print "Sorry, not a choice. Please enter your choice again." > print "Goodbye." > > How do I fix such an invalid syntax? > > TIA, > Nathan Pinno Try running this: input = raw_input("Hello world.") From http Thu Mar 27 08:35:33 2008 From: http (Paul Rubin) Date: 27 Mar 2008 05:35:33 -0700 Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> Message-ID: <7xlk4473ai.fsf@ruckus.brouhaha.com> king kikapu writes: > it seems that Psyco's author will not port it for the upcoming Python > 3000 release :( I think the idea is it will be part of PyPy and you should use that. From rockxuan at gmail.com Tue Mar 18 03:58:29 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:58:29 -0700 (PDT) Subject: Hublot Swiss watch in www.51cntrade.com Message-ID: <25eb5778-c1c9-4f74-9931-c9ba7a224285@i12g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From ilochab at yahoo.it Wed Mar 12 08:00:52 2008 From: ilochab at yahoo.it (ilochab) Date: Wed, 12 Mar 2008 12:00:52 GMT Subject: Is it possible to reload a module from a different file? Message-ID: I mean ... The main module makes this import: import moduleX later other modules make different import to an other module named moduleX like this: from pack.subdir import moduleX What I want is that the second import of moduleX in some way must be redirected onto the first one. Is there any way to do so? Would there be any way to do so (moduleX overrides pack.subdir.moduleX) if they were imported on reverse order? Any time I discover that Python can do amazing things, but perhaps this one is just a silly one, isn't it? ciao Licia From anh.hai.trinh at gmail.com Sat Mar 8 21:50:30 2008 From: anh.hai.trinh at gmail.com (Chick) Date: Sat, 8 Mar 2008 18:50:30 -0800 (PST) Subject: securely getting the user's password Message-ID: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> Hello, I'm writing a security tool which requies wiping off the memory of certain string after being used, which I've done by implementing it as a mutable list as follow: class secureStr: def __init__(self, str): self.__s = [] for i in range(len(str)): self.s += str[i] def __str__(self): return "".join(self.__s) def wipe(self): for i in range(len(self.__s)): self.s[i] = '\x00' def __del__(self): self.wipe() My question is how do I write a function to securely get the password from user (in text mode)? If I do sth like import getpass securePass = secureStr(getpass,getpass()) doesn't that create an immediate string object that will stay in memory? From bj_666 at gmx.net Sat Mar 22 17:21:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Mar 2008 21:21:39 GMT Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: <64lbj3F2an71mU3@mid.uni-berlin.de> On Sat, 22 Mar 2008 13:27:49 -0700, sgharvey wrote: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: > If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. > If I try to match every pattern to one line at a time, only one > pattern will match. > > What am I not understanding about re.search? That has nothing to do with `re.search` but how files work. A file has a "current position marker" that is advanced at each iteration to the next line in the file. When it is at the end, it stays there, so you can just iterate *once* over an open file unless you rewind it with the `seek()` method. That only works on "seekable" files and it's not a good idea anyway because usually the files and the overhead of reading is greater than the time to iterate over in memory data like the patterns. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Wed Mar 19 15:25:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 16:25:14 -0300 Subject: automatically doing some cleaning-up by the process when the systems shuts down References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> <2613171a0803190028s4cc626apd2cd675a18e25799@mail.gmail.com> Message-ID: En Wed, 19 Mar 2008 04:28:19 -0300, bharath venkatesh escribi?: > handling SIGTERM allowed me to do cleaning up while the system shuts > down > but as i mentioned previously how can my process know if the system > was > not shut down properly previously Sorry about the confusion, I meant SIGTERM instead of SYSTERM. Create a file with a known fixed name when the daemon starts, and remove it after a clean shutdown (you may want to write the daemon's PID). If the file already exists the next time it starts, that means that a clean shutdown was not performed. (Note that this, and the previous question, are not specific to Python) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 22:39:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 02:39:06 -0000 Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> <13udtk586ijktec@corp.supernews.com> Message-ID: <13ue52ajkauekc5@corp.supernews.com> On Sun, 23 Mar 2008 18:56:51 -0700, John Machin wrote: >> Python knows the truth value of built-in types like dicts without >> actually converting them to bools, or for that matter calling __len__ >> or __nonzero__ on them. > > What the 2.5.1 interpreter does is call PyObject_IsTrue, which checks to > see if the built_in or extension type is a mapping (not just a dict) > with a length method and if so calls it; similarly for sequences: > > else if (v->ob_type->tp_as_mapping != NULL && > v->ob_type->tp_as_mapping->mp_length != NULL) > res = (*v->ob_type->tp_as_mapping->mp_length)(v); > else if (v->ob_type->tp_as_sequence != NULL && > v->ob_type->tp_as_sequence->sq_length != NULL) > res = (*v->ob_type->tp_as_sequence->sq_length)(v); > > Was that what you meant by "without ... calling __len__"? What I meant was that the interpreter *didn't* do was lookup the name '__len__' via the normal method resolution procedure. There's no need to search the dict's __dict__ attribute looking for an attribute named __len__, or indeed any sort of search at all. It's a direct pointer lookup to get to mp_length. I didn't mean to imply that Python magically knew whether a dict was empty without actually checking to see if it were empty. Apologies for being less than clear. Also, since I frequently criticize others for confusing implementation details with Python the language, I should criticize myself as well. What I described is specific to the CPython implementation -- there's no requirement for other Python versions to do the same thing. -- Steven From ebenze at hotmail.com Fri Mar 14 17:19:40 2008 From: ebenze at hotmail.com (Eric B.) Date: Fri, 14 Mar 2008 17:19:40 -0400 Subject: Installing Python2.4 on RHEL4? References: Message-ID: "Jarek Zgoda" wrote in message news:freov4$n9f$2 at nemesis.news.neostrada.pl... > Eric B. pisze: > >> I appologize if this is slightly OT, but I am really struggling to figure >> out how to install Python2.4 on RHEL4. To make matters worse, the RHEL4 >> machine is a 64bit architecture. >> >> I search pyvault, but they only have for .i386. Does anyone know where / >> how I can find Python2.4 for RHEL4 x64? > > If you would not find a binary Python 2.4 package, you can always build > your own and package it. Why not? Because I don't have a development x64 environment to build it. :( Only a production server with no compilation tools on it. Hence my need to ideally find a binary x64 distribution of it. Unless someone knows of a way to build a 64bit distribution from within a 32bit system? Thanks, Eric From http Thu Mar 20 03:07:00 2008 From: http (Paul Rubin) Date: 20 Mar 2008 00:07:00 -0700 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> <7xk5jz1a80.fsf@ruckus.brouhaha.com> Message-ID: <7x4pb16fhn.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > I thought os.walk was for locally mounted directories... How is it > relevant on remote filesystems? Yes, os.walk is for local directories. I thought you wanted to push a local tree to a remote host. For pulling, yes, you need to do something different; for example, rsync can handle it for you. > Don't shoot the messenger, but you're severely confused here. Whether > you're using ftp, rcp, or rsync is a completely separate issue to > whether you're running over ssl (which I assume you meant by ssh). SSL would make more sense but ssh is more commonly used. > FTP is a work-horse protocol for transferring files. It's going to be > with us for a long, long time. Here's what happened when I just tried to use it: $ ftp localhost ftp: connect: Connection refused ftp> That is quite common these days. I think ftp doesn't play nicely with encryption tunnels because of the way it uses a separate port for out of band signalling, but I never paid close attention, so maybe there's some other issue with it. I can't think of when the last time was that I actually used ftp. > The point of rsync is to keep a local directory tree in sync with a > remote one, by transferring only change-sets that are conceptually > similar to patches. If you're only transferring files once, there's > no particular benefit (AFAIK) to using rsync rather than some kind of > recursive ftp. One benefit is that it handles the recursion for you by itself. Another is that in modern unix environments it's more likely to work at all (i.e. if there is no ftp server at the target machine). From grante at visi.com Sun Mar 9 00:36:16 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:36:16 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <13t6tqgh29oks9e@corp.supernews.com> On 2008-03-09, Dan Bishop wrote: > On Mar 8, 1:31 pm, Grant Edwards wrote: > ... >> >> What I really can't stand are the pointy-haired comment blocks >> at the beginnings of C/C++ functions that do things like tell >> you the name and return type of the function and list the names >> and types of the parameters. Gee, thanks. I never could have >> figured that out from looking at the source code itself. IMO, >> comments explaining what the parameters are used for usually >> indicates that the parameter names were poorly chosen. > > You must work for the same company I do. I've seen a whole bunch of > comments that look like: > > //--------------------------------------------------------------------------- > // CXyzBase::LogMessage > // > // Write a message to the log. > // > // Args: > // strMsg = the message to log > // > void CXyzBase::LogMessage(const CString& strMsg) > { > // > } > > And even worse, at the top of that file: > > //--------------------------------------------------------------------------- > // XyzBase.cpp > // > // This file contains the implementation of class CXyzBase. > // > // Copyright (C) 2008 Foobar Computer Consulting > // > // VERSION PROJECT# DATE DESCRIPTION > // ------- -------- -------- ------------------ > // 1.00 123456 01/04/08 Original creation. > // > > Eleven lines, of which the only useful information to me was the > project number, as knowing this let me look up who was behind these > comments. :) I'm currently consulting part-time for a company that's very fond of that sort of thing. And it's it's not like they're working on some DoD contract that explicitly requires such time-wastage -- it's something they torture themselves with of their own volition. [I honestly didn't expect my rant to spark such a long thread.] -- Grant Edwards grante Yow! I will invent "TIDY at BOWL"... visi.com From ffm.stefan at googlemail.com Sat Mar 8 08:25:46 2008 From: ffm.stefan at googlemail.com (Stefan Wagner) Date: Sat, 8 Mar 2008 14:25:46 +0100 Subject: Writing Memory to File Message-ID: Hi, I'm trying to do some memory analyzing stuff, i wrote me a small .c so far to dump the memory to a file for later analysis, the analyzing part itself is python code. I wonder if any of you has an idea how to dump the whole memory in Linux/Windows from python ? Using the .c for this somehow doesn't look right and comfy ;-) Regards, Stefan From grante at visi.com Tue Mar 4 12:35:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 04 Mar 2008 17:35:14 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> Message-ID: <13sr22ii98uipc4@corp.supernews.com> On 2008-03-04, blaine wrote: >> Try using the appropriate constant from /usr/include/... (for >> the target platform, of course). >> >> -- >> Grant Edwards grante Yow! Please come home with >> at me ... I have Tylenol!! >> visi.com > Thank you for your response. I can't seem to find what you're > referencing in /usr/include. I found termios.h - but it does not > define any constants (I can include it if you wish). $ grep -r B921600 /usr/include /usr/include/asm/termbits.h:#define B921600 0010007 /usr/include/bits/termios.h:#define B921600 0010007 > I could recompile python, I imagine, with additional constants but > this wouldn't be ideal - although it is a possible solution. termios.c in Python definitely needs to be updated. > the only reference to a baud rate in termios.h is here: It's in a file that's included in termios.h. See above. -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.com my urine sample bottles ... From whoshaq at aol.com Thu Mar 6 13:48:15 2008 From: whoshaq at aol.com (Whoshaq) Date: Thu, 6 Mar 2008 10:48:15 -0800 (PST) Subject: HURRICANE ANDREW 1992 Rare & Raw Footage Message-ID: HURRICANE ANDREW 1992 Rare & Raw Footage Parts 1 thru 7: http://www.youtube.com/watch?v=zKGMQFWWJ0g From hdante at gmail.com Sun Mar 30 01:11:33 2008 From: hdante at gmail.com (hdante) Date: Sat, 29 Mar 2008 22:11:33 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> On Mar 29, 7:55 am, kwitt... at telenet.be wrote: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? > > I've written an article about it to try and save this nice "is not > equal" operator, located athttp://dewitters.koonsolo.com/python_neq.html > > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). I don't know, but we should have only one operator. BTW, my opinion is that it's already time that programmer editors have input methods advanced enough for generating this: if x ? 0: ?y ? s: if y ? 0: f1(y) else: f2(y) ;-) From gagsl-py2 at yahoo.com.ar Sun Mar 9 17:11:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 19:11:16 -0200 Subject: parralel downloads References: <47D2C331.4020708@islandtraining.com> Message-ID: En Sat, 08 Mar 2008 14:47:45 -0200, Gary Herron escribi?: > poof65 wrote: >> For your problem you have to use threads. >> > Not at all true. Thread provide one way to solve this, but another is > the select function. For this simple case, select() may (or may not) be > easier to write. Pseudo-code would look something like this: > > openSockets = list of sockets one per download file: > while openSockets: > readySockets = select(openSockets ...) # Identifies sockets with > data to be read > for each s in readSockets: > read from s and do whatever with the data > if s is at EOF: close and remove s from openSockets > > That's it. Far easier than threads. Easier? If you omit all the relevant details, yes, looks easy. For example, you read some data from one socket, part of the file you're downloading. Where do you write it? You require additional structures to keep track of things. Pseudocode for the threaded version, complete with socket creation: def downloadfile(url, fn): s = create socket for url f = open filename for writing shutil.copyfileobj(s.makefile(), f) for each url, filename to retrieve: t = threading.Thread(target=downloadfile, args=(url,filename)) add t to threadlist t.start() for each t in threadlist: t.join() The downloadfile function looks simpler to me - it's what anyone would write in a single threaded program, with local variables and keeping full state. The above pseudocode can be converted directly into Python code - no more structures nor code are required. Of course, don't try to download a million files at the same time - neither a million sockets nor a million threads would work. -- Gabriel Genellina From __peter__ at web.de Sun Mar 30 09:03:21 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 30 Mar 2008 15:03:21 +0200 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > >> Second try: > ... >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with >> each call. But it's the only way I could find, at least without changing >> the code template used by timeit. > > Eeek. Talk about namespace pollution. > > Thanks for the effort, but if that's the only solution, I think the > solution is worse than the problem! > > Perhaps it's time for me to take a different approach. [snip] Maybe the following enhancement of timeit would be worthwhile? $ cat timeanyfunc.py from mytimeit import Timer def functionA(): print "Function A" def functionB(): print "Function B" T1 = Timer("f()", ns=dict(f=functionA)) T2 = Timer("f()", ns=dict(f=functionB)) T1.repeat(3, 1) T2.repeat(3, 1) $ python timeanyfunc.py Function A Function A Function A Function B Function B Function B $ diff -u /usr/lib/python2.5/timeit.py mytimeit.py --- /usr/lib/python2.5/timeit.py 2008-03-07 05:35:55.000000000 +0100 +++ mytimeit.py 2008-03-30 14:40:58.000000000 +0200 @@ -77,7 +77,7 @@ # in Timer.__init__() depend on setup being indented 4 spaces and stmt # being indented 8 spaces. template = """ -def inner(_it, _timer): +def inner(_it, _timer, %(inject)s): %(setup)s _t0 = _timer() for _i in _it: @@ -106,15 +106,16 @@ multi-line string literals. """ - def __init__(self, stmt="pass", setup="pass", timer=default_timer): + def __init__(self, stmt="pass", setup="pass", timer=default_timer, ns=None): """Constructor. See class doc string.""" + if ns is None: + ns = {} self.timer = timer stmt = reindent(stmt, 8) setup = reindent(setup, 4) - src = template % {'stmt': stmt, 'setup': setup} + src = template % {'stmt': stmt, 'setup': setup, 'inject': ','.join("%s=%s" % (s, s) for s in ns)} self.src = src # Save for traceback display code = compile(src, dummy_src_name, "exec") - ns = {} exec code in globals(), ns self.inner = ns["inner"] By the way, haven't we been there before, two years ago? http://mail.python.org/pipermail/python-list/2006-February/368341.html Peter From duncan.booth at invalid.invalid Mon Mar 17 14:00:10 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 18:00:10 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> <47de9f6c$0$2657$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: > >> For the answer I actually want each asterisk substitutes for exactly one >> character. > > Played around a bit and found that one: > > Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) > [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = 1 >>>> b = 1//1 >>>> if a is b: print('yes!') > ... >>>> b > 1 >>>> type(b) > "the whole point of setting the puzzle was that I expected it to be ripped to shreds", thanks for supporting my expectations. From Robert.Bossy at jouy.inra.fr Mon Mar 10 10:28:37 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 10 Mar 2008 15:28:37 +0100 Subject: parsing directory for certain filetypes In-Reply-To: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <47D54595.2030607@jouy.inra.fr> royG wrote: > hi > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? > > here it is... > > from string import split > from os.path import isdir,join,normpath > from os import listdir > > def parsefolder(dirname): > filenms=[] > folder=dirname > isadr=isdir(folder) > if (isadr): > dirlist=listdir(folder) > filenm="" > This las line is unnecessary: variable scope rules in python are a bit different from what we're used to. You're not required to declare/initialize a variable, you're only required to assign a value before it is referenced. > for x in dirlist: > filenm=x > if(filenm.endswith(("txt","doc"))): > nmparts=[] > nmparts=split(filenm,'.' ) > if((nmparts[1]=='txt') or (nmparts[1]=='doc')): > I don't get it. You've already checked that filenm ends with "txt" or "doc"... What is the purpose of these three lines? Btw, again, nmparts=[] is unnecessary. > filenms.append(filenm) > filenms.sort() > filenameslist=[] > Unnecessary initialization. > filenameslist=[normpath(join(folder,y)) for y in filenms] > numifiles=len(filenameslist) > numifiles is not used so I guess this line is too much. > print filenameslist > return filenameslist > Personally, I'd use glob.glob: import os.path import glob def parsefolder(folder): path = os.path.normpath(os.path.join(folder, '*.py')) lst = [ fn for fn in glob.glob(path) ] lst.sort() return lst I leave you the exercice to add .doc files. But I must say (whoever's listening) that I was a bit disappointed that glob('*.{txt,doc}') didn't work. Cheers, RB From andrei.avk at gmail.com Wed Mar 12 21:18:37 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Wed, 12 Mar 2008 18:18:37 -0700 (PDT) Subject: escape string to store in a database? Message-ID: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> Hi, I'd like to store chunks of text, some of them may be very large, in a database, and have them searchable using 'LIKE %something%' construct. These pieces of text may have single and double quotes in them, I tried escaping them using re module and string module and either I did something wrong, or they escape either single quotes or double quotes, not both of these. So that when I insert that text into a db record, this causes an error from the database. What's the accepted way of dealing with this? I have a workaround currently where I encode the string with b64, and then unencode it when searching for a string, but that's a dumb way to do this. For my app, searching quickly is not very crucial, but would be nice to have.. thanks, -ak From castironpi at gmail.com Tue Mar 25 14:59:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 11:59:58 -0700 (PDT) Subject: any good g.a.'s? References: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Message-ID: <6b5385ad-0756-4c22-92fe-ab8214d00262@e67g2000hsa.googlegroups.com> On Mar 25, 11:03?am, Tim Chase wrote: > > Any good genetic algorithms involving you-split, i-pick? > > I've always heard it as "you divide, I decide"... > > That said, I'm not sure how that applies in a GA world. ?It's > been a while since I've done any coding with GAs, but I don't > recall any facets related to the You Divide, I Decide problem. > It sounds like a simple optimization of "equality", which would > be a normal use of a GA. ?This would apply for both the division > and the decision, depending on which side the GA is (the "you" or > the "I") or two diff. GAs can be on either side of the process. > > -tkc There's an iterated solution (no link) for more than two players. Say two GAs encounter the same resource (or if some is left after they've begun consuming)-- i.e., encounter each other, a strict survival-of- fittest can arise among a population, even leading to specialization and organ. I'm not sure if time factors in however, i.e. whether GAs are useful in spacetime; bacteria Firmicute produce spores to guard during stress. What do ideal structures have in common with real ones?; and if so, does you-split-i-pick yield anything useful in ideality? What are ideal bacteria, what do they want, and are they interesting? From hdante at gmail.com Sun Mar 30 08:25:50 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 05:25:50 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> <659f2cF2dq5riU1@mid.uni-berlin.de> Message-ID: On Mar 30, 9:23 am, "Diez B. Roggisch" wrote: > hdante schrieb: > > > > > On Mar 30, 4:31 am, John Machin wrote: > >> On Mar 30, 3:58 pm, hdante wrote: > > >>> On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" > >>> wrote: > >>>> Hello, > >>>> I am having trouble writing the code to read a binary string. I would > >>>> like to extract the values for use in a calculation. > >>>> Any help would be great. > >>> I'm too lazy to debug your binary string, but I suggest that you > >>> completely throw away the binary file and restart with a database or > >>> structured text. See, for example: > >>> http://pyyaml.org/wiki/PyYAML > >>> If you have some legacy binary file that you need to process, try > >>> creating a C program that freads the binary file and printfs a text > >>> equivalent. > >> ... and that couldn't be done faster and better in Python?? > > > No. A C struct is done faster and better than python (thus, the > > correctness check is faster in C). Also, chances are high that there's > > already an include file with the binary structure. > > That is utter nonsense. There is no "correctness check" in C. and using > printf & thus creating strings that you then need to parse in python > just doubles the effort needlessly. > > The standard-lib module "struct" is exactly what you need, nothing else. > it sure is faster than any parsing of preprocessed data, doesn't > introduce a language-mixture and is prototyped/tested much faster > because of it being python - and not C-compiler and C-debugger. > > Alternatively, *IF* there were C-structure-declarations available for > the binary format, the usage of ctypes would allow for roughly the same, > even reducing the effort to create the structure definition a great deal. > > Diez Whatever you say. From sturlamolden at yahoo.no Wed Mar 19 16:29:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 13:29:10 -0700 (PDT) Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> Message-ID: <6b4a290a-447e-44a4-aced-e104e52f72f1@i12g2000prf.googlegroups.com> On 19 Mar, 09:44, Torsten Bronger wrote: > Could you elaborate on this? (Sincere question; I have almost no > idea of Haskell.) If you already know Python, you will find Whitespace just as useful as Haskell. From ptmcg at austin.rr.com Sun Mar 23 03:26:36 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 23 Mar 2008 00:26:36 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> Message-ID: <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> There are a couple of bugs in our program so far. First of all, our grammar isn't parsing the METAL2 entry at all. We should change this line: md = mainDict.parseString(test1) to md = (mainDict+stringEnd).parseString(test1) The parser is reading as far as it can, but then stopping once successful parsing is no longer possible. Since there is at least one valid entry matching the OneOrMore expression, then parseString raises no errors. By adding "+stringEnd" to our expression to be parsed, we are saying "once parsing is finished, we should be at the end of the input string". By making this change, we now get this parse exception: pyparsing.ParseException: Expected stringEnd (at char 1948), (line:54, col:1) So what is the matter with the METAL2 entries? After using brute force "divide and conquer" (I deleted half of the entries and got a successful parse, then restored half of the entries I removed, until I added back the entry that caused the parse to fail), I found these lines in the input: fatTblThreshold = (0,0.39,10.005) fatTblParallelLength = (0,1,0) Both of these violate the atflist definition, because they contain integers, not just floatnums. So we need to expand the definition of aftlist: floatnum = Combine(Word(nums) + "." + Word(nums) + Optional('e'+oneOf("+ -")+Word(nums))) floatnum.setParseAction(lambda t:float(t[0])) integer = Word(nums).setParseAction(lambda t:int(t[0])) atflist = Suppress("(") + delimitedList(floatnum|integer) + \ Suppress(")") Then we need to tackle the issue of adding nesting for those entries that have sub-keys. This is actually kind of tricky for your data example, because nesting within Dict expects input data to be nested. That is, nesting Dict's is normally done with data that is input like: main Technology Layer PRBOUNDARY METAL2 Tile unit But your data is structured slightly differently: main Technology Layer PRBOUNDARY Layer METAL2 Tile unit Because Layer is repeated, the second entry creates a new node named "Layer" at the second level, and the first "Layer" entry is lost. To fix this, we need to combine Layer and the layer id into a composite- type of key. I did this by using Group, and adding the Optional alias (which I see now is a poor name, "layerId" would be better) as a second element of the key: mainDict = dictOf( Group(Word(alphas)+Optional(quotedString)), Suppress("{") + attrDict + Suppress("}") ) But now if we parse the input with this mainDict, we see that the keys are no longer nice simple strings, but they are 1- or 2-element ParseResults objects. Here is what I get from the command "print md.keys()": [(['Technology'], {}), (['Tile', 'unit'], {}), (['Layer', 'PRBOUNDARY'], {}), (['Layer', 'METAL2'], {})] So to finally clear this up, we need one more parse action, attached to the mainDict expression, that rearranges the subdicts using the elements in the keys. The parse action looks like this, and it will process the overall parse results for the entire data structure: def rearrangeSubDicts(toks): # iterate over all key-value pairs in the dict for key,value in toks.items(): # key is of the form ['name'] or ['name', 'name2'] # and the value is the attrDict # if key has just one element, use it to define # a simple string key if len(key)==1: toks[key[0]] = value else: # if the key has two elements, create a # subnode with the first element if key[0] not in toks: toks[key[0]] = ParseResults([]) # add an entry for the second key element toks[key[0]][key[1]] = value # now delete the original key that is the form # ['name'] or ['name', 'name2'] del toks[key] It looks a bit messy, but the point is to modify the tokens in place, by rearranging the attrdicts to nodes with simple string keys, instead of keys nested in structures. Lastly, we attach the parse action in the usual way: mainDict.setParseAction(rearrangeSubDicts) Now you can access the fields of the different layers as: print md.Layer.METAL2.lineStyle I guess this all looks pretty convoluted. You might be better off just doing your own Group'ing, and then navigating the nested lists to build your own dict or other data structure. -- Paul From sjmachin at lexicon.net Fri Mar 28 23:30:45 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Mar 2008 20:30:45 -0700 (PDT) Subject: some path issues on windows References: Message-ID: On Mar 29, 1:31 pm, Brad wrote: > When reading a file into a list that contains windows file paths like this: > > c:\documents and settings\brad\desktop\added_software\asus\a.txt Do you mean "reading a file into a list that AS A RESULT contains ..."? If not, what do you mean? > > I get a list that contains paths that look like this: > > c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt > > So, my list contains those funky file paths. Only if your file already contains contains the doubled backslashes. > And, when I do this: > > for root, dirs, files in os.walk('C:\\'): > for f in files: > print os.path.join(root,f) > > I get the more normal path again: > > c:\documents and settings\brad\desktop\added_software\asus\a.txt > > This makes path comparison difficult as I have different strings (the > extra \'s). I've tried os.path.normpath(line_reading_in_from_file) but I > still get the funky \\ paths. How can I read the paths with an r'path' > like meaning? File reading operations *don't* magically double backslashes. Believe me. Show us the code that is reading the file. Show us the contents of the file. Assure us that you understand what is going on here: >>> alist = ['a\\b', r'a\b'] >>> alist[0] == alist[1] True >>> print alist ['a\\b', 'a\\b'] # So if you see doubled backslashes when you do print alist, # there are really only single backslashes. >>> print alist[0], alist[1] a\b a\b >>> print repr(alist[0]), repr(alist[1]) 'a\\b' 'a\\b' HTH, John From malkarouri at gmail.com Sat Mar 8 11:01:16 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 08:01:16 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: On Mar 8, 3:20?pm, Roel Schroeven wrote: > malkarouri schreef: > > > > > Hi everyone, > > > I have an algorithm in which I need to use a loop over a queue on > > which I push values within the loop, sort of: > > > while not(q.empty()): > > ? ? x = q.get() > > ? ? #process x to get zero or more y's > > ? ? #for each y: > > ? ? q.put(y) > > > The easiest thing I can do is use a list as a queue and a normal for > > loop: > > > q = [a, b, c] > > > for x in q: > > ? ? #process x to get zero or more y's > > ? ? q.append(y) > > > It makes me feel kind of uncomfortable, though it seems to work. The > > question is: is it guaranteed to work, or does Python expect that you > > wouldn't change the list in the loop? > > Changing a loop while iterating over it is to be avoided, if possible. > In any case, a deque is more efficient for this kind of use. I'd use it > like this: > > from collections import deque > > q = deque([a, b, c]) > while q: > ? ? ?x = q.popleft() > ? ? ?# ... > ? ? ?q.append(y) > > -- > The saddest aspect of life right now is that science gathers knowledge > faster than society gathers wisdom. > ? ?-- Isaac Asimov > > Roel Schroeven Thanks for your response. My same feeling, avoid loop variable, but no explicit reason. Thanks for reminding me of the deque, which I never used before. Alas, in terms of efficiency - which I need - I don't really need to pop the value on the list/deque. This additional step takes time enough to slow the loop a lot. So its not ideal here. Still, why avoid changing loop variable? Does python treat looping over a list differently from looping over an iterator, where it doesn't know if the iterator future changes while loop running? Regards, Muhammad Alkarouri From jeff at schwabcenter.com Thu Mar 20 12:59:50 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 09:59:50 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: Paulo da Costa wrote: > People who say Emacs often mean GNU Emacs. That's funny; to me, Emacs usually means XEmacs. :) From tarundevnani at gmail.com Tue Mar 25 07:55:12 2008 From: tarundevnani at gmail.com (tarun) Date: Tue, 25 Mar 2008 17:25:12 +0530 Subject: Issues with Python + Batch File Message-ID: Hi All, I've a batch file which invoks a python file. The python code in the file brings up a GUI. The GUI is of a test tool which can execute scripts. I tried using the following 2 sample of code for my batch file: * (1) (2)* D:\opengui.py D:\opengui.py goto:end goto:end :end :end EXIT TASKKILL /IM C:\WINDOWS\system32\cmd.exe Double clicking on the batch file brings up a DOS BOX which opens up the GUI. On Closing the GUI, the DOS BOX both get closed. But if I close the GUI when a test is under execution, the GUI gets closed but the DOS BOX still remains open. I want to some how close the DOS BOX when the GUI is closed. Thanks & Regards, Tarun tarundevnani at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidj411 at gmail.com Wed Mar 5 14:16:31 2008 From: davidj411 at gmail.com (davidj411) Date: Wed, 5 Mar 2008 11:16:31 -0800 (PST) Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: Python 3.0 might end up better, but converting all those scripts will be a chore. I'd be curious to know how that will be done. From skunkwerk at gmail.com Wed Mar 26 09:46:52 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Wed, 26 Mar 2008 06:46:52 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> Message-ID: On Mar 26, 6:44?am, skunkwerk wrote: > On Mar 25, 11:04?pm, "Gabriel Genellina" > wrote: > > > > > En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk ? > > escribi?: > > > > On Mar 25, 9:25?pm, "Gabriel Genellina" > > > wrote: > > >> En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? > > >> escribi?: > > > >> >> ? ?i'm trying to call subprocess.popen on the 'rename' function in > > >> >> linux. ?When I run the command from the shell, like so: > > > >> >> rename -vn 's/\.htm$/\.html/' *.htm > > > >> >> it works fine... however when I try to do it in python like so: > > >> >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > > >> >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > > >> >> print p.communicate()[0] > > > >> >> nothing gets printed out (even for p.communicate()[1]) > > > >> I'd try with: > > > >> p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > > >> ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, > > >> ? ? ? ?shell=True) > > > >> (note that I added shell=True and I'm using a raw string to specify the ? > > >> reg.expr.) > > > > Thanks Gabriel, > > > ? ?I tried the new command and one with the raw string and single > > > quotes, but it is still giving me the same results (no output). ?any > > > other suggestions? > > > My next try would be without the single quotes... > > > -- > > Gabriel Genellina > > thanks for the input guys, > ? I've tried the suggestions but can't get it to work. ?I have a file > named test.htm in my directory, and when I run the following command: > > rename -vn 's/(.*)\.htm$/model.html/' *.htm > > from the shell in that directory I get the following output: > test.htm renamed as model.html > > now my python script is called test.py, is located in the same > directory, and is called from the shell with 'python test.py' > the contents of test.py: > import subprocess > > p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ > model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > print p.communicate()[0] > > i change to print p.communicate()[1] in case the output is blank the > first time > > this is the output: > *.htm renamed as model.html > > when I add shell=True to the subprocess command, I get the following > output: > Usage: rename [-v] [-n] [-f] perlexpr [filenames] > > am i doing something wrong? in addition, when I use Popen without any quotes, or without quotes for the regular expression, I get an exception. I'm running ubuntu linux 7.10 with python 2.5.1 thanks From michael.wieher at gmail.com Fri Mar 14 10:15:07 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 14 Mar 2008 09:15:07 -0500 Subject: find string in file In-Reply-To: References: Message-ID: 2008/3/14, fminervino at gmail.com : > > Hi friends !! > > I'm neophite about python, my target is to create a programa that > find a specific string in text file. > How can do it? > > Thanks > fel > > -- > http://mail.python.org/mailman/listinfo/python-list > If your only goal is to find a string in a file, just use grep >grep -i 'string' filename its a standard linux command =) But if you must use python data=file(filename,'r').read() if string in data: return True return False -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Mar 19 13:15:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 14:15:14 -0300 Subject: Using threads in python is safe ? References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> Message-ID: En Wed, 19 Mar 2008 04:43:34 -0300, Deepak Rokade escribi?: > Thanks all for removing confusion about GIL, > one more question; > If jobs to be processed by threds is I/O bound would multithreading help > python to improve speed of application ? > Since I read that " multithreading is not a good strategy to improve > speed > of python application." Try and see what happens in your specific case. People keeps saying that but I've never seen conclusive evidence on this topic. Using several threads for I/O bound tasks seems reasonable to me, and is the easiest approach. For CPU bound tasks, multiple threads won't help much, be it Python or another language. I mean, a reasonable number of threads with a reasonable task load. A server handling thousands of simultaneous connections is another beast. -- Gabriel Genellina From pscott at uwc.ac.za Mon Mar 31 03:15:45 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Mon, 31 Mar 2008 09:15:45 +0200 Subject: Beginner advice In-Reply-To: <65bfk7F2esfc1U1@mid.uni-berlin.de> References: <65bfk7F2esfc1U1@mid.uni-berlin.de> Message-ID: <1206947745.6828.35.camel@paul-laptop> On Mon, 2008-03-31 at 06:45 +0000, Marc 'BlackJack' Rintsch wrote: > There is an `xmlrpclib` in the standard library, so there is no need for > an external package here. I even think that pyXMLRPClib is the one that's > integrated in the standard library, so the external one might be "dead". > Ah, yes it is indeed. Thanks. > For Windows there are tools to bundle your source and all dependencies and > even the interpreter itself. `py2exe` is such a tool. With InnoSetup or > NSIS or similar programs you can then make a `setup.exe` for that spoiled > Windows brats. :-) > > Under Linux many packages are available as distribution specific packages > on most distributions. So for Linux you may get away with a README > stating the dependencies of your program and a `setup.py` for installing > your project. Look for `distutils` in the Python documentation for > further information about `setup.py`\s. setup.py sounds like the best way to go. Most of the classrooms and lecture halls run on Ubuntu machines, and as I said, I don't really care much for the Windows brats anyway. 'doze installers etc would be a nice to have, but not needed right now. > > > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? > > Use the one you like best. ;-) > Thought as much. I do 90% of my coding in vi anyways, but am still getting a couple of nutty errors from Python simply because I have not yet gotten the hang of significant whitespace :) Darn that PHP! Thanks for the feedback, now I just need some justification on the GTK/GUI stuff - wxWidgets, GTK+ Glade or other? --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From stef.mientki at gmail.com Thu Mar 13 16:35:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 13 Mar 2008 21:35:42 +0100 Subject: how to pass the workspace ? In-Reply-To: <47D733A7.2070808@islandtraining.com> References: <47D72CDD.9000706@gmail.com> <47D733A7.2070808@islandtraining.com> Message-ID: <47D9901E.5000007@gmail.com> Gary Herron wrote: > Stef Mientki wrote: >> hello, >> >> I've GUI tree with drag and drop nodes, >> where each nodes contains a code snippet. >> Now I want to run one or more branches in that tree, >> so I enumerate over the nodes and have to run something like this: >> >> execfile ( node1 ) >> execfile ( node2 ) >> etc.. >> >> Now how do I pass the workspace created in node1, to node 2, etc ? >> >> thanks, >> Stef Mientki >> > > RTFM! In particular: > http://docs.python.org/lib/built-in-funcs.html#l2h-26 thanks Gary, I read that, but sorry, unfortunately I don't understand it, this is what I tried: tree_globs = {} tree_locals = {} tree_globs [ 'NewVar' ] = 24 filename = self.Get_Editor_Filename (nodename) execfile ( filename, tree_globs, tree_locals ) print dir ( tree_globs) print dir ( tree_locals ) where the code in the executed file is: beer = 'testje' print dir() print dir (globals) print dir (locals) the output I get is: aap ['beer'] ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] The result of globals and locals in the file is eaxctly the same and none of them mentions 'NewVar' and 'beer' The result of tree_globs and tree_locals is exactly the same and both doesn't contain 'NewVar' and 'beer' Maybe it's very simple after reading the manual, but apperently I'm missing the essential clue. What am I missing ? thanks, Stef Mientki From gklein at xs4all.nl Mon Mar 17 07:11:09 2008 From: gklein at xs4all.nl (Gertjan Klein) Date: Mon, 17 Mar 2008 12:11:09 +0100 Subject: Spaces in path name References: <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> <708a66a7-da8f-4d44-824d-8a25203030f7@n58g2000hsf.googlegroups.com> Message-ID: joep wrote: >* If shell=True is required, then the executable is a build-in shell >command, which does not contain spaces, and, therefore, has no >problems This is only true when you are referring to directly executable files. However, Shell=True is also required when you want to "execute" a file by it's association. For example, if you want to execute a ".pyw" file directly (i.e., by using whichever python executable is associated with that extension), you need Shell=True. IMHO, the subprocess module should not have been included as-is in the Python library. It is counter-intuitive, buggy, ill-documented, and has needless limitations in functionality. Regards, Gertjan. -- Gertjan Klein From castironpi at gmail.com Tue Mar 4 00:31:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 21:31:10 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: On Mar 3, 10:01?pm, Benjamin wrote: > On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > > > What are metaclasses? > > Depends on whether you want to be confused or not. If you do, look at > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/. > > Basically, the metaclass of a (new-style) class is responsible for > creating the class. This means when Python sees > class Foo(object): > ? ? __metaclass__ = FooMeta > class FooMeta(type): > ? ? def __new__(cls, name, bases, dct): > ? ? ? ?#do something cool to the class > ? ? ? ?pass > It asks FooMeta to create the class Foo. Metaclasses always extend > type because type is the default metaclass. But you can stack class decorations, but not class metas. @somethingcool1 @somethingcool2 class Foo: pass * class Foo: __metaclass__= MetaCool1, MetaCool * denotes malformed From wizzardx at gmail.com Sun Mar 30 01:16:01 2008 From: wizzardx at gmail.com (David) Date: Sun, 30 Mar 2008 07:16:01 +0200 Subject: html DOM In-Reply-To: References: Message-ID: <18c1e6480803292216n3927ecacq6380b7ace6a33401@mail.gmail.com> On Sun, Mar 30, 2008 at 1:09 AM, Sam the Cat wrote: > Is there a package that would allow me the same or similar functionality for > modifying html code via the DOM model as I have in JavaScript ? I'd like to > parse an html file, then modify it and save the result. I am not trying to > do this online, rather I would like to do this on a batch of files stored on > my hard drive. I have found several packages that allow me to parse and > dissect html but none that allow me to modify the object and save the > results -- perhaps I am overlooking the obvious > Have you looked at Beautiful Soup? http://www.crummy.com/software/BeautifulSoup/ David. From noah at noah.org Mon Mar 24 20:52:54 2008 From: noah at noah.org (Noah) Date: Mon, 24 Mar 2008 17:52:54 -0700 (PDT) Subject: Python 2.2.1 and select() References: Message-ID: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> On Mar 24, 2:58 pm, Derek Martin wrote: > If and only if the total amount of output is greater than the > specified buffer size, then reading on this file hangs indefinitely. > For what it's worth, the program whose output I need to capture with > this generates about 17k of output to STDERR, and about 1k of output > to STDOUT, at essentially random intervals. But I also ran it with a > test shell script that generates roughly the same amount of output to > each file object, alternating between STDOUT and STDERR, with the same > results. > I think this is more of a limitation with the underlying clib. Subprocess buffering defaults to block buffering instead of line buffering. You can't change this unless you can recompile the application you are trying to run in a subprocess or unless you run your subprocess in a pseudotty (pty). Pexpect takes care of this problem. See http://www.noah.org/wiki/Pexpect for more info. -- Noah From sjmachin at lexicon.net Wed Mar 12 07:58:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Mar 2008 04:58:24 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Message-ID: On Mar 12, 10:29 pm, Bernard wrote: > Hey Larry, > > that one is fairly easy: > > >>> from array import array > >>> array('i', [1, 2, 3, 4, 5, 1, 2]) > >>> def count(x, arr): > > cpt = 0 # declare a counter variable > for el in arr: # for each element in the array > if el == x: # when it is equal to the 'x' value > cpt+=1 # increment the counter variable by one > return cpt # return the counter after the loop>>> count(1,a) > > 2 > Hey Bernard, you have just laboriously reinvented the count method: >>> from array import array >>> a = array('i', [1, 2, 3, 4, 5, 1, 2]) >>> a.count(1) 2 >>> which Larry has already said doesn't do the job -- the job is to create a histogram!! From paul.hermeneutic at gmail.com Tue Mar 11 17:29:31 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 11 Mar 2008 16:29:31 -0500 Subject: any library for SOAP 1.1 or SOAP 1.2? In-Reply-To: References: Message-ID: <1205270971.4382.1.camel@localhost.localdomain> On Fri, 2008-01-25 at 16:52 +0530, Amogh Hooshdar wrote: > Hi, > > I wish to know which python library is popular for SOAP related > programming, especially for sending SOAP requests and parsing SOAP > responses. > > I can't find any such library in the Python standard library but I > could find ZSI and soap.py libraries. However, ZSI does not support > SOAP 1.2. > > Does anyone know about a library that supports SOAP 1.2 also? Support for SOAP 1.2 is on the ZSI wishlist. It may not happen until you and I do it. Have you found anything else? Are you using ZSI? From wbsoft at xs4all.nl Sun Mar 9 12:44:33 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Sun, 9 Mar 2008 17:44:33 +0100 Subject: pure python hyphenator Message-ID: <200803091744.33620.wbsoft@xs4all.nl> Hi all, I'm just new to this list and I'm a musician and hobby programmer. I am busy with LilyKDE, a python plugin package for KDE's editor Kate, that makes using the LilyPond music typesetter from within Kate easier. While already busy writing a python module for breaking lyrics text (using hyphenation dicts from e.g. OpenOffice.org) I found Dr.Leo's PyHyphen. But just for fun I also continued my own plain python module, which now has it's SVN repository at: http://python-hyphenator.googlecode.com/ and it's PyPI page at: http://pypi.python.org/pypi/hyphenator . It needs more testing but seems to work nice. LilyKDE is located at http://lilykde.googlecode.com/ all the best. Guido and community: thanks for such a nice programming language, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi From grante at visi.com Tue Mar 4 23:13:15 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 04:13:15 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> <13sr22ii98uipc4@corp.supernews.com> Message-ID: <13ss7er3igcbda7@corp.supernews.com> On 2008-03-04, blaine wrote: >> It looks like the fastest speed supported by python termios on >> Linux is B460800 (uses a constant of 0x1004). If you look in >> /usr/include/..., baud rates do go up to 921600 (which uses a >> constant of 0x1007). >> >> Try using the appropriate constant from /usr/include/... (for >> the target platform, of course). > I want to thank you SO MUCH for all your help. Here are my issues > that I overcame (sanity check): > 1. Why did we have to use 0x1007, instead of 0x10007 that our grep > command returns? The number might be different for the host where you did the grep that it is for the target machine (IIRC, you said it was an ARM, right?). Did you do the grep on the include files for the ARM target or on a host of some other architecture? The actual numbers might also be different in different versions of the kernel. > 2. PySerial works beautifully. Thank you for the suggestion. > What I had to do was add this to the PySerial source root > in serialpostix.py, after the import termios: > > termios.B921600 = 0x1007 [...] > ... so now I can pass 921600 as a parameter to PySerial! :) > > So my next question is - I would like to contribute to the > python source tree by updating termios.h to handle the higher > baud rates by default. Is this a good opportunity for me to > submit a patch? I've never done this before but have always > been interested in doing so. Sure! It's been a while since I submitted a patch, and I don't remember what the process is, but hopefully somebody reading the thread does. It could be that the change is already in the development branch... -- Grant Edwards grante Yow! Two LITTLE black at dots and one BIG black visi.com dot...nice 'n' FLUFFY!! From gagsl-py2 at yahoo.com.ar Wed Mar 26 14:19:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 15:19:03 -0300 Subject: Py2exe embed my modules to libary.zip References: Message-ID: En Wed, 26 Mar 2008 14:55:43 -0300, escribi?: > Does anybody have any idea how can I embed my modules to libary.zip > and use it from my application.For example if user write this code in > my TextEntry ( or something like that, textentry is created with > wxpython ) : > > import d3dx # directpython module > frame=d3dx.Frame(u"My frame") # create frame > frame.Mainloop() # run it > > ....and then when my application execute code how can I set path to > d3dx module to "library.zip/d3dx.py". > I'm not sure is this properly set question. If d3dx.py is in library.zip (top level), and the path to library.zip is in sys.path, Python will find the module. A .zip in sys.path acts as it were a directory itself. -- Gabriel Genellina From kay.schluehr at gmx.net Sun Mar 23 21:35:48 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 23 Mar 2008 18:35:48 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> <13uc4bpb0b564af@corp.supernews.com> <7a4c084f-ecb7-4ed4-8f3f-af29d811d44a@b64g2000hsa.googlegroups.com> Message-ID: <503c0e97-046b-479e-b606-68c30456c05c@a1g2000hsb.googlegroups.com> On 23 Mrz., 09:31, Arnaud Delobelle wrote: > On Mar 23, 8:14 am, Steven D'Aprano > cybersource.com.au> wrote: > > On Sat, 22 Mar 2008 23:15:00 -0700, John Nagle wrote: > > > That's some professor inventing his very own variation on predicate > > > calculus and writing a book using his own notation and terminology. > > > There's no sign of footnotes or references to prior work. The notation > > > doesn't seem to do anything not previously possible; it's just > > > different. > > > You say that as if it were unusual in maths circles :) > > Haha. As opposed to programmers who have all agreed to use the same > language. > > Anyway, I have browsed the book and agree with Paul Rubin that there > doesn't seem to be any unusual notation in it, although there are a > numbers of topics that I am not really familiar with. > > -- > Arnaud The author at least introduces his notation in the initial chapter. This is good style among mathematicians who introduce conventions at the beginning of their books or in an appendix. Note that I'm with Paul here but I'm not sure what John is complaining about anyway. Maybe sequent calculus ( natural deduction ) which was introduced by Gentzen around 75 years ago? http://en.wikipedia.org/wiki/Sequent_calculus From deets at nospam.web.de Sun Mar 9 18:00:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 23:00:08 +0100 Subject: __iter__ yield In-Reply-To: References: Message-ID: <63j4vbF27lit6U2@mid.uni-berlin.de> duccio schrieb: > > Hello! > Someone knows if it's possible to make this __iter__ function with just > one 'yield' intead of two? > Is there some simpler way to make this __iter__ iter through all nodes? > Thanks! > > class Node: > def __init__(self, data=None): > self.childs=[] > self.data=data > def appendNode(self, n): > node=Node(n) > self.childs.append(node) > return node > def __str__(self): > return '<'+str(self.data)+'>' > def __iter__(self): > yield self #1 > for n in self.childs: > for nn in n.__iter__(): > yield nn #2 Nope. There have been numerous discussions about this, introducing something like a yield_all-keyword or such thing that would replace the above boilerplate - but so far they all have been rejected. Search the archives for the reasons, I don't remember them :) Diez From castironpi at gmail.com Sun Mar 30 21:24:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 18:24:48 -0700 (PDT) Subject: Rubik's cube translation Message-ID: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> How do I get a Rubik's cube translation out of this: >>> a= numpy.array([[0,1,2],[3,4,5],[6,7,8]]) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> a[:,0],a[:,1],a[:,2] #no good (array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])) >>> I need [[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]. >>> c= numpy.array([[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]) >>> c array([[6, 3, 0], [7, 4, 1], [8, 5, 2]]) From stephenhorne100 at aol.com Tue Mar 18 08:25:15 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 18 Mar 2008 05:25:15 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: Just to throw in one more alternative, if you sort your list, you only need to test adjacent items for equality rather than needing a search for each unique item found. You should get O(n log n) rather than O(n^2), since the performance bottleneck is now the sorting rather than the searching for duplicates. Also, since the sort method is built into the list, sorting performance should be very good. The dictionary version Chris suggests (and the essentially equivalent set-based approach) is doing essentially the same thing in a way, but using hashing rather than ordering to organise the list and spot duplicates. This is *not* O(n) due to the rate of collisions increasing as the hash table fills. If collisions are handled by building a linked list for each hash table entry, the performance overall is still O(n^2) since (for large amounts of data) there is still a linear search on each collision. If collisions are handled by building binary trees, the performance is back to O(n log n). That is, for large enough datasets, the performance of hash tables is basically the performance of the collision handling data structure (ignoring scaling constants). I suspect Python handles collisions using linked lists, since using trees would require that all dictionary keys support ordered comparisons. Using a dictionary or set to eliminate duplicates therefore gives O(n^2) performance. That said, hash tables have very good scaling constants to their performance, so the dictionary technique will be a very good performer in general. And if the lists are reasonably small the performance will often seem like O(n) in practice. The sort-then-filter approach should still be competitive, but of course it requires that the contents of the list can be ordered consistently. An inappropriate hash function can similarly cause problems for the dictionary approach, causing that theoretical O(n^2) performance to become apparent very quickly. This is probably one reason why the cookbook recipe recommends an O(n^2) searching-based approach. From sturlamolden at yahoo.no Mon Mar 17 20:57:00 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 17 Mar 2008 17:57:00 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> On 17 Mar, 04:54, WaterWalk wrote: > So I'm curious how to read code effectively. I agree that python code > is clear, but when it becomes long, reading it can still be a hard > work. First, I recommend that you write readable code! Don't use Python as if you're entering the obfuscated C contest. Two particularly important points: * If you find yourself thinking this module is too long, that's probably what it is. Half a page of code per module is fine. Two pages of code per module can be too much. * Comments are always helpful to the reader. Second, I recommend getting a good IDE. E.g. pick one of: * Microsoft Visual Studio (commercial) * Eclipse with PyDev and CDT (free) * SPE (free) * ActiveState Komodo IDE (commercial) From castironpi at gmail.com Sun Mar 2 17:47:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 14:47:38 -0800 (PST) Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: <5e3f7c46-802a-4305-984e-718ce2045f31@i29g2000prf.googlegroups.com> > >>> is there a better way of creating d?? > > >> a = [[0] * 3 for dummy in xrange(3)] > > Each element of a refers to a distinct array. > > > Why not simply [[0]*3]*3 ? > > All three elements of the result refer to the same array. ... whereas you reassign all three elements of [0]* 3. >>> ((0,)*3,)*3 ((0, 0, 0), (0, 0, 0), (0, 0, 0)) You're safe in this one-- changing [0][0] won't change [1][0], 'cuz you can't! From cpthomas at gmail.com Thu Mar 13 09:05:45 2008 From: cpthomas at gmail.com (Casey T) Date: Thu, 13 Mar 2008 06:05:45 -0700 (PDT) Subject: Different results when running script from IDLE versus Command Line References: <895b88e4-694d-4fee-a633-08aa8a407999@p73g2000hsd.googlegroups.com> Message-ID: On Mar 12, 5:28?pm, Chris wrote: > On Mar 12, 8:10 pm, Casey T wrote: > > > > > Hi, > > > I'm new to Python and I'm having some problems with getting different > > results from my script when I run it from IDLE versus just double- > > clicking the .py file and having it run through the command line. > > Basically, my script reads some CSV files, assembles a text files, > > then uploads that test file to an ftp site. When I run the script from > > IDLE, everything works fine. But when it runs from the command line, > > the file that gets uploaded is empty. It seems that it is creating a > > new file to upload, rather than using the existing file (or at least > > that's what I think is going on.) Below is my script. I apologize for > > any ugly code. Thanks for your help. > > > import sys,os,linecache,csv,ftplib,time > > > starttime = time.time() > > > #******* > > #Summary file assembling > > #******* > > currentdir = "//folder/" > > > reg_sum = open('reg_sum.txt','w') > > reg_sum.close > > > for files in os.listdir(currentdir): > > ? ? reg_file = csv.reader(open(currentdir + files)) > > ? ? for row in reg_file: > > ? ? ? ? reg_sum = open('reg_sum.txt','a') > > ? ? ? ? reg_sum.write(",".join(row) + ',\n') > > > reg_sum.close > > > #******* > > #Summary file processing > > #******* > > coordList = [ > > ? ? ["F10",40.0053,-75.0927], > > ? ? ["T10",40.0272,-75.1123], > > ? ? ["D22",39.9811,-75.0998], > > ? ? ["P02",40.0437,-75.0217], > > ? ? ["D68",39.9203,-75.1388], > > ? ? ["D51",39.9534,-75.1405], > > ? ? ["S43",39.9217,-75.2275], > > ? ? ["S33",39.9360,-75.2077], > > ? ? ["S42A",39.9215,-75.1937], > > ? ? ["S05",39.9617,-75.1782], > > ? ? ["T14",40.0165,-75.1077]] > > > coordList_index = > > ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"] > > #coordList_index is a list containing > > > in_text = open('reg_sum.txt','r') > > > out_text = open('reg_out.txt','w') > > out_text.close > > > out_text = open('reg_out.txt','a') > > > for line in in_text: > > ? ? split_line = line.split(',') > > ? ? if (split_line[0]) in coordList_index: > > ? ? ? ?i = coordList_index.index(split_line[0]) > > ? ? ? ?coords = str(coordList[i][1]) + "," + str(coordList[i][2]) > > ? ? ? ?last_update = str(split_line[2]) > > ? ? print str(split_line[0]) > > ? ? if split_line[1] == "1": > > ? ? ? ?out_text.write(split_line[0] + "
,Test1: " + last_update + > > "," + coords + ",1" + "\n") > > ? ? elif split_line[1] == "0": > > ? ? ? ?out_text.write(split_line[0] + "
,Test2.
Last updated: " > > + last_update + "," ?+ coords + ",0" + "\n") > > ? ? else: > > ? ? ? ?out_text.write(split_line[0] + "
,No data.," + coords + > > "\n") > > > in_text.close > > > ###******* > > ###Uploads file via FTP > > ###******* > > s = ftplib.FTP('ftp.blah123.org,'user','pass') > > > f.open('reg_out.txt','r') > > s.storlines('STOR reg_out.txt', f) > > > f.close() > > s.quit() > > > print ?"Processed in " + str(((time.time() - starttime) / 60) *60) + " > > seconds!" #prints elapsed time > > You never closed your file. > > file_object.close > > > try adding '()' at the end of your close calls. > As to why it differs, I can't think offhand why it wouldn't. wow. thank you so much. it was the '()'. I now get consistent results. In all the sample code I saw, I never saw the '()' after close. thanks again - casey From timr at probo.com Sat Mar 22 22:03:29 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 23 Mar 2008 02:03:29 GMT Subject: Anomaly in time.clock() References: <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: <0febu3lut6cpgikoe02snl0tju05gd8qs8@4ax.com> Godzilla wrote: > >Just found out that win32api.GetTickCount() returns a tick count in >milli-second since XP started. Not sure whether that is reliable. >Anyone uses that for calculating elapsed time? What do you mean by "reliable"? The tick count is updated as part of scheduling during timer interrupts. As long as no one disables interrupts for more than about 15ms, it is reliable. However, it's only a 32-bit value, so the number rolls over every 49 days. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From attn.steven.kuo at gmail.com Fri Mar 21 01:12:01 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 20 Mar 2008 22:12:01 -0700 (PDT) Subject: How do I change the font size for the default coordinates in matplotlib? References: Message-ID: On Mar 20, 8:20 pm, Carl wrote: > I've searched the user manual (and this forum) but I don't see > anything that helps. Did you mean the font size for the ticks or for the labels? Here's an example: from pylab import * x = arange(0, 2*pi, 0.01) y = sin(2*pi*x) rcParams.update({'xtick.labelsize': 5, 'ytick.labelsize': 10}) subplot(111) plot(x,y) ylabel("Vert", fontsize=15) xlabel("Horiz", fontsize=20) show() -- Hope this helps, Steven From mr.cerutti at gmail.com Thu Mar 6 13:17:28 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 6 Mar 2008 13:17:28 -0500 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <51302a8c0803061017ga7522dcj50c53271884bbbf0@mail.gmail.com> On Thu, Mar 6, 2008 at 12:17 PM, Guillermo wrote: > > You can also get the dynamic polymorphism without invoking inheritance > > by specifying a protocol that the values in your dict must implement, > > instead. Protocols are plentiful in Python, perhaps more popular than > > type hierarchies. > > I'm used to languages with stricter rules than Python. I've read a bit > about Python protocols, but where could I get some more info on > implementation details? Sounds very interesting. A protocol is just an interface that an object agrees to implement. In your case, you would state that every object stored in your special dict must implement the to_tagged_value method with certain agreeable semantics. Python implements sequence types, mapping types, iterators, file streams, and other things with protocols. For example, iterators must support the "next" and and "__iter__" methods. Using a protocol instead instead of a type hierarchy requires less boring boilerplate, and I suppose in Python will usuallly be preferable except when you want to inherit implementation as well as interface. In that case, inheritance often saves boilerplate cide rather than increases it. It's also misnomered as duck-typing (clearly it should be nomed quack-typing). -- Neil Cerutti From castironpi at gmail.com Thu Mar 27 07:19:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:19:18 -0700 (PDT) Subject: what are generators? References: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> Message-ID: <5875e7c0-6051-4e27-b019-5bae126d457e@p25g2000hsf.googlegroups.com> On Mar 25, 7:36?pm, Miki wrote: > On Mar 24, 8:17?am, castiro... at gmail.com wrote: > > > I'm looking for a cool trick using generators. ?Know any exercises I > > can work? > > Simple one the comes to mind is flattening a list: > > >>> list(flatten([1, [[2], 3], [[[4]]]])) > [1, 2, 3, 4] I don't think it's well-defined. (But this is impossible and useless calling.) CMIIW? This is generic: >>> def f(): ... __gen= None ... def g(): ... i= 0 ... while 1: ... i+= 1 ... yield __gen( i ) ... def set( gen ): ... nonlocal __gen ... __gen= gen ... return g, set ... >>> a, set= f() >>> b= a() >>> set( lambda x: print( x ) ) >>> next( b ) 1 >>> next( b ) 2 >>> next( b ) From gagsl-py2 at yahoo.com.ar Mon Mar 3 09:26:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 12:26:53 -0200 Subject: Cant run application as ./myapp.py References: <10505.9786969379$1204547853@news.gmane.org> Message-ID: En Mon, 03 Mar 2008 10:35:30 -0200, Robert Rawlins escribi?: > I've got an application here which for some reason won't start using the > following syntax from the command line: > > > Cd /mydirectory > > ./MyApplication.py > > > I have to run this as a fully qualified python launch such as: > > > Cd /mydirectory > > python MyApplication.py > > > This is a little bit confusing to me as I have other applications which > run > just fine using the ./somthing.py syntax. Is there any reason why this > doesn't work? See this thread from last year: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1d0fd05b3615057/ -- Gabriel Genellina From sjmachin at lexicon.net Sat Mar 22 00:25:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 21:25:21 -0700 (PDT) Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <47E3C1A3.6050608@ncf.ca> Message-ID: <1c518ce7-2ea4-4d3f-9cb9-563048e0bd52@s19g2000prg.googlegroups.com> On Mar 22, 4:36 am, Christian Heimes wrote: > Colin J. Williams schrieb: > > > You might consider adding the Julian date > > (http://en.wikipedia.org/wiki/Julian_date). > > > I had a crack at this a while ago but didn't seem to get quire the right > > result, using the ACM algorithm. I seemed to be a day out at the BC/AD > > divide. 1. Somewhere in the Colin-Christian-Nicholas thread, the "Julian date" and the "Julian calendar" seem to become conflated. 2. "day out": possibly because there is no year 0; year 1 BCE is followed immediately by year 1 CE. > > Yes, the Julian date family is very useful when dealing with dates > before 1900. I'm having some difficulty understanding the above sentence, given either interpretation of "Julian date family". What is the significance of 1900? [Julian calendar interpretation] Some countries (including Russia, China, Greece and Turkey) did not adopt the Gregorian calendar until after 1900. Dealing with a date expressed as (year, month, day) is far from easy for approx year range 1582 to 1926 unless it has been expressly tagged as e.g. "old style" or "new style". If so tagged, there is to me no difference in ease of use between the proleptic Julian calendar and the proleptic Gregorian calendar. [Julian date as used in astronomy] This supports dates back to about 4800 BCE easily, whereas Python's datetime module supports the proleptic Gregorian calendar only back to year 1 CE. Cheers, John From fakeaddress at nowhere.org Thu Mar 6 05:46:28 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 02:46:28 -0800 Subject: Python CGI & Webpage with an Image In-Reply-To: <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> Message-ID: rodmc wrote: [...] > Python: > > f = open("finish.html") > doc = f.read() > f.close() > print doc You might need to start with: print "Content-Type: text/html" print Is "finish.html" in the right place? When you browse to your script, can you see that you're getting the html? > HTML: [...] >

References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: Steven D'Aprano napisa?(a): >> I can see that Python and Javascript inheritance model is almost the >> same. Both languages are dynamically typed. And it seems that using >> "classes" in Python makes some things more complicated then it is >> necessary (eg functions, methods and lambdas are differen beeing in >> Python concept). > > Please explain why you think that functions are more complicated in > Python because of the class model. Sorry for a late reply (I was out of the office). 1. You have different syntax for named and unnamed (lambdas) functions. Functions and methods are different things in Python even if they have same syntax. But all these are still a pieces of code that you use repeatedly to make some task. 2. Static function doesn't need to reference "self", and Python forces programmer to put "self" explicitly. Then you have to do some "tricks" on function to become static. Python is said "nothing is really private", but interpreter does some "tricks" to make __id hidden for a class. Some opinions: 1. In early days you could do OOP in C -- you just used additional parameter in a function. Then C++ appeared to make life easier: "when you write mystring.toupper(), then toupper function gets hidden argument called "this"". Programs are written in a high level object oriented languages now. In these languages you still use the same syntax mystring.toupper(), but now you don't pass object to a function (as in C), but you act on that object. So in the body of toupper() you can REFERENCE object "mystring". So why do I have to put that "strange" argument "self"? This is not only my opinion (http://apache.ece.arizona.edu/~edatools/Python/Prototypes.htm). Without "self" you would use same syntax for ordinary functions, methods, and lambdas. 2. Something is private because you can't reference that from outside the scope. The wrong way is to make object properties private by declaring them private or to do hidden actions (__id). For example all local variables in function are private, because you can't access them from outside that function. Why desn't this work for objects? Again this is not only my opinion -- http://www.crockford.com/javascript/private.html. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 28 07:31:33 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 28 Mar 2008 12:31:33 +0100 Subject: Plugins accessing parent state In-Reply-To: References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> <653q99F2e37q8U1@mid.uni-berlin.de> Message-ID: <47ecd707$0$18855$426a34cc@news.free.fr> Andr? a ?crit : > On Mar 28, 6:39 am, "hajdu... at gmail.com" wrote: >> On Mar 28, 1:58 am, "Diez B. Roggisch" wrote: (snip) >>> But to be honest: you are thinking much to far there - after all, it's >>> all *your* code, and inside one interpreter. A real isolation isn't >>> available anyway. >>> So just do what fullfills the functional requirements. >> >> Since I want to have a uniform call to all plugins, would it make >> sense to split out the attributes that I do want to share to a >> separate class and then simply create a new instance of that class and >> store it in the main class? >> >> For instance >> >> ... >> self.utilities = Utilities(self) >> ... >> plugin.do(msg,self.utilities) > > I would bypass the step of creating a new instance and write instead > plugin.do(msg, self) > thus having access to all properties/methods of the calling object. > Why restrict it?... +1 on this. And FWIW, *if* you later find out you *really* need to restrict access to the caller object's attribute (ie: 'self'), it will be as simple as wrapping it in a decorator (design pattern, not function decorator) object that will take care of this, ie (Q&D naive implementation): class RestrictedSelf(object): allowed_attributes = ('dothis', 'dothat') def __init__(self, realself): self.realself = realself def __getattr__(self, name): if name.startswith('_') or name not in self.allowed_attributes: raise AttributeError( 'access to %s.%s is forbidden' % (self.realself, name) ) return getattr(self.realself, name) And in the call to the plugin: plugin.do(msg, RestrictedSelf(self)) But my bet is that YAGNI, so to make a long story short: start with the simplest thing that could possibly work !-) HTH From mail at timgolden.me.uk Sun Mar 16 12:49:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 16:49:42 +0000 Subject: Spaces in path name In-Reply-To: <47DD4933.7050609@timgolden.me.uk> References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> <47DD4933.7050609@timgolden.me.uk> Message-ID: <47DD4FA6.6030203@timgolden.me.uk> Tim Golden wrote: > Well I've got a patch ready to go (which basically just > wraps a shell=True command line with an *extra* pair of > double-quotes, the same as you do for an os.system call). > I'll try to put some time into the subprocess docs as well, > at least as far as a Win32-how-do-I on my own site if not > an update to the official docs. For the record, I've raised this as issue 2304 with a patch attached: http://bugs.python.org/issue2304 TJG From castironpi at gmail.com Tue Mar 11 15:43:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 12:43:46 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> <2b098afa-2dcc-4bde-bdde-02eece46fd68@47g2000hsb.googlegroups.com> <817b79d0-d451-4696-ab73-1289a380136c@d4g2000prg.googlegroups.com> Message-ID: On Mar 11, 11:31?am, Lie wrote: > On Mar 10, 4:16?am, castiro... at gmail.com wrote: > > > > > > > On Mar 9, 4:25?am, Lie wrote: > > > > On Mar 9, 3:27?am, castiro... at gmail.com wrote: > > > > > To Lie: > > > > > > Personally I preferred a code that has chosen good names but have > > > > > little or no comments compared to codes that makes bad names and have > > > > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > > > > I won't like it, it's that I can't. ?You know, in linguistics, there's > > > > But I much prefer it that the code has good names AND concise > > > comments, not too short and not too long that it becomes obscure. > > > What do you mean? ?If 'obscure' is the right word, then it's > > subjective (from metrics import obscurity?), which means that 10% of > > the people disagree with you, or 90% do. ?The end-all be-all, there is > > no such thing. ?I don't think it's obscure; I do. ?Is it? > > No, there is a point where everyone would say obscure. But not on all code. Comments can obscure code, and code can too. Here's a snip from the docs: # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite Is c2pread more or less obscure than c2pr or chi2parread? If there's an objective metric of the degree of something's obscurity (obscured- ity), then that has an answer. Is it a scalar, or if not, is there abs( answer )? Does that comment obscure the later code? Are 'in' and 'out' more or less obscure than those? (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) Information design can get (*subjective) breathtaking, but if you see a potential improvement, you should always be able to make it. Tell me what you think of this simile: Sometimes Steve Chessmaster reads board positions, sometimes prose. Some of the prose is less obscure, -to- -him-, than board states. To someone with a different speciality, as in bishops vs. knights, endgame vs. openings, certain forks, the states are less obscure than the corresponding prose. To my fmr. A.I. professor, "The minimax A*," and "The beaten path A*" are plenty clear. He can say what they do. Can you? > (remember you don't have access to source code, so you have to > decipher the documentation for what the function is about) But you're still calling it? > I prefer to see something like this: > def add(a, b): > ? ? return a + b > Even without documentation I'd know immediately what it does from the > name (add). What if the word is generic? Do you know if it has a return value? From castironpi at gmail.com Sun Mar 30 23:03:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 20:03:39 -0700 (PDT) Subject: Rubik's cube translation References: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> Message-ID: <489180f4-aa43-4d98-a67d-71ce06ea9152@x41g2000hsb.googlegroups.com> On Mar 30, 9:48?pm, "Tim Leslie" wrote: > On Mon, Mar 31, 2008 at 12:24 PM, ? wrote: > > How do I get a Rubik's cube translation out of this: > > > ?>>> a= numpy.array([[0,1,2],[3,4,5],[6,7,8]]) > > ?>>> a > > ?array([[0, 1, 2], > > ? ? ? ?[3, 4, 5], > > ? ? ? ?[6, 7, 8]]) > > ?>>> a[:,0],a[:,1],a[:,2] #no good > > ?(array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])) > > > ?I need [[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]. > > > ?>>> c= numpy.array([[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]) > > ?>>> c > > ?array([[6, 3, 0], > > ? ? ? ?[7, 4, 1], > > ? ? ? ?[8, 5, 2]]) > > In [10]: numpy.rot90(a, 3) > Out[10]: > array([[6, 3, 0], > ? ? ? ?[7, 4, 1], > ? ? ? ?[8, 5, 2]]) > > Tim What if this is connected: >>> D array([[1, 2, 3], [4, 5, 6], [6, 7, 8]]) >>> E array([[6, 7, 8], [0, 0, 0], [0, 0, 0]]) --> >>> D array([[1, 2, 3], [4, 5, 6], [6, 7, 8]]) >>> E array([[6, 7, 8], [0, 0, 0], [0, 0, 0]]) >>> numpy.rot90( D ) array([[3, 6, 8], [2, 5, 7], [1, 4, 6]]) --> >>> E array([[1, 4, 6], [0, 0, 0], [0, 0, 0]]) ? From bernard.chhun at gmail.com Fri Mar 7 20:26:42 2008 From: bernard.chhun at gmail.com (Bernard) Date: Fri, 7 Mar 2008 17:26:42 -0800 (PST) Subject: Edit and continue for debugging? References: Message-ID: <5f7d4c0e-c8d1-468b-a089-654cf6681458@m34g2000hsc.googlegroups.com> As Jonathan says. :) I had a lot of fun learning how to plug doctests[1] into my python web apps and now I'm just adding them automatically as I create classes and functions. Those tests tidbits says so much more than a paragraph of comments. [1] : http://docs.python.org/lib/module-doctest.html On 7 mar, 09:44, "Bronner, Gregory" wrote: > I haven't seen much on this for a few years: > > I'm working on a GUI application that has lots of callbacks. Testing it > is very slow and quite boring, as every time I find an error, I have to > exit it, restart it, and repeat the series of clicks. It would be really > amazing if python supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my code and > have it apply to a running instance of a class. I wonder if it would be > possible to do this by configuring the interpreter to parse classes and > functions rather than whole modules, and to re-parse as necessary; also > to have byte-compiled modules be singletons rather than be standard > reference counted objects. > > Thanks > Gregory R. Bronner > (212) 526-0102 > gregory.bron... at lehman.com > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > > This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. > > -------- > IRS Circular 230 Disclosure: > Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From arnodel at googlemail.com Wed Mar 26 04:58:09 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 01:58:09 -0700 (PDT) Subject: Strange loop behavior References: <47EA0ABB.3030804@mydeskfriend.com> Message-ID: On Mar 26, 8:51?am, Gabriel Rossetti wrote: > Gabriel Rossetti wrote: > > Hello, > > > I wrote a program that reads data from a file and puts it in a string, > > the problem is that it loops infinitely and that's not wanted, here is > > the code : > > > ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > ? ? while d != "": > > ? ? ? ? file_str.write(d) > > ? ? ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > > I also tried writing the while's condition like so : len(d) > 0, but > > that doesn't change anything. I tried step-by-step debugging using > > PyDev(eclipse plugin) and I noticed this, once the while was read once, > > it is never re-read, basically, the looping does happen, but just in > > between the two lines in the loop's body/block, it never goes on the > > while and thus never verifies the condition and thus loops forever. I > > had been using psyco (a sort of JIT for python) and so I uninstalled it > > and restarted eclipse and I still get the same thing. This looks like > > some bug, but I may be wrong, does anybody understand what's going on here? > > > Thanks, > > Gabriel > > > PS > > And yes I checked, the "d" variable is en empty string at some point, so > > the looping should stop. > > Ok, I get it, the repr() function actually returns a string with quote > characters around it, thus the length is never 0, but 2. The reason I > began using the repr() function is that the str() and unicode() > constructors didn't accept the data read, because it was bigger than > ord(128) (or something like that. I'm trying to read a binary file and > put it's contents in an xml message to send via the network, so that I > can re-create it on the other side. I do need to keep the xml aspect > though. Is there a better way of doing this? > > Thanks, > Gabriel Have a look at the uu and base64 modules: http://docs.python.org/lib/module-uu.html http://docs.python.org/lib/module-base64.html -- Arnaud From tmp1 at viltersten.com Fri Mar 7 16:56:28 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 22:56:28 +0100 Subject: Location and size of a frame Message-ID: <63dr1hF26enh0U1@mid.individual.net> I'm disliking the size of my frame and also i'm disappointed regarding it's location. So, i wish to change them. At this link http://infohost.nmt.edu/tcc/help/pubs/tkinter/frame.html the frame object is discussed but as far i can tell, there are only suggestions regarding what to put in the constructor. So, how/where do i check how to affect the location and size? I'm guessing it has to do with "location", "width" and "heinght" but i didn't make it work. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From python.list at tim.thechases.com Tue Mar 25 18:36:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Mar 2008 17:36:59 -0500 Subject: what does ^ do in python In-Reply-To: References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: <47E97E8B.2010108@tim.thechases.com> > In most of the languages ^ is used for 'to the power of'. > > No, not in most languages. In most languages (C, C++, Java, C#, Python, > Fortran, ...), ^ is the xor operator ;) ...and in Pascal it's the pointer-dereferencing operator... -tkc From pavlovevidence at gmail.com Thu Mar 13 12:45:37 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Mar 2008 09:45:37 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: On Mar 13, 12:38 pm, Alan Isaac wrote: > Dan Bishop wrote: > > def cmp_key(cmp_fn): > > class CmpWrapper(object): > > def __init__(self, obj): > > self.obj = obj > > def __cmp__(self, other): > > return cmp_fn(self.obj, other.obj) > > return CmpWrapper > > Apparently I'm overlooking something obvious ... > > how is this supposed to work if __cmp__ is no longer > > being called? (Which was my understanding.) It won't. In Python 3.0 you'd have to write this class in terms of rich comparisons (__lt__, __gt__, etc.). Carl Banks From aisaac at american.edu Wed Mar 19 01:10:37 2008 From: aisaac at american.edu (Alan Isaac) Date: Wed, 19 Mar 2008 05:10:37 GMT Subject: method to create class property In-Reply-To: <64astpF29u3k1U1@mid.uni-berlin.de> References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> <64astpF29u3k1U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > In python 3.0, there will be an even nicer way - propset: > @property > def foo(self): > return self._foo > @propset > def foo(self, value): > self._value = value Isn't that:: @propset(foo) def foo(self, value): self._value = value Cheers, Alan Isaac From jeff at schwabcenter.com Sat Mar 22 15:02:42 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 12:02:42 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: Larry Bates wrote: > jmDesktop wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. >> >> Thank you. > > ABSOLUTELY. Get them started with a REAL programming language that will > teach them proper fundamentals. I wish Python would have been around 25 > years ago when I taught incoming Freshmen at local University. To get > students to understand about variable references, etc. What do you mean by "variable references," and how are they used in Python? From duncan.booth at invalid.invalid Sun Mar 2 05:57:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Mar 2008 10:57:43 GMT Subject: FW: Escaping a triple quoted string' newbie question References: Message-ID: "Jules Stevenson" wrote: > Hello, > > Apologies if the terminology in this email is a little incorrect, I'm > still finding my feet. > > I'm using python to generate some script for another language (MEL, in > maya, specifically expressions). Maya runs python too, but > unfortunately its expression language still has to use the maya > syntax. > > If I pass the expression this code: > > #runtime code [mel] > expRuntime="""float $pos[]=particleShape1.worldPosition; > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; > """ > dynExpression (p, s=expRuntime, rad=1) #generate the expression > > Then maya errors out, however if I pass maya an 'escaped' version: > > expRuntime="""float $pos[]=particleShape1.worldPosition;\r\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\r\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\r\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2];" -rad > particleShape1;""" > > Then all is well. My question is, is there any way to convert the > first variable example to the second? It's a lot easier to type and on > the eye. > Escaping the quotes doesn't change the string, so the only difference I can see between your strings is that you have split the lines by carriage- return+linefeed instead of just linefeed characters. If so: s = expRuntime.replace('\n', '\r\n') should have the desired effect. From ptmcg at austin.rr.com Sun Mar 30 03:46:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Mar 2008 00:46:53 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> <13utgh8j9ik8t7c@corp.supernews.com> Message-ID: <95d67524-d54f-4d7a-854d-53abeb2b3596@d62g2000hsf.googlegroups.com> On Mar 30, 12:34?am, castiro... at gmail.com wrote: > > The screen is real (r-e-a-l): all manners intended. ?Real. ?Just bid > and auction. > Please leave the newbies alone. They have enough trouble just getting their Python environments running, without trying to decipher your pseudo-profound chatterbot-speak. -- Paul From castironpi at gmail.com Sat Mar 1 01:02:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 29 Feb 2008 22:02:32 -0800 (PST) Subject: at-exit-thread References: <62r68tF220j59U1@mid.uni-berlin.de> <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> <4b0b675a-4333-4224-a40d-717d3c469c54@z17g2000hsg.googlegroups.com> Message-ID: On Feb 29, 4:34?pm, Preston Landers wrote: > On Feb 29, 2:12?pm, castiro... at gmail.com wrote: > > > If a thread adds an object it creates to a nonlocal > > collection, such as a class-static set, does it have to maintain a > > list of all such objects, just to get the right ones destroyed on > > completion? ? > > Yes. > > > Processes destroy their garbage hassle-free; how can > > threads? ? > > If you're asking "is there some automatic way to associate a external > resource with a thread so that it's deleted when the thread is done" > then the answer (to the best of my knowledge) is no. ?You would have > to take care of these details yourself once something outside your > thread got a reference to the resource. If you keep all references to > the resource inside the thread, then you can use the __del__ method of > the resource to take any cleanup actions. > > Also, processes don't always "destroy their garbage hassle free" if > you consider inter process communication. ?For instance, if you create > an object in one process then serialize it and pass it to another > process through e.g. an XMLRPC call, there's no automatic way for the > other process to be notified that the originating process exited. > You'd have to build that feature in. ?Exact same thing with threads. > > > And don't forget Thread.run( self ) in the example, if > > anyone ever wants to make use of the 'target' keyword. > > I don't understand what you're referring to. In the initial counterexample, > class MyThread(Thread): > > def run(self): > while some_condition: > do_something() > do_something_after_the_thread_ends() , MyThread overrides 'run', so target is never called. It did create the picture to me though that: class MemHoldingThread( Thread ): def __init__( self, *a, **kwa ): Thread.__init__( self, *a, **kwa ) self.objs= set() self._args= ( self, )+ self._args def hold( self, obj ): self.objs.add( obj ) return obj def run( self ): Thread.run( self ) self._cleanup() def _cleanup( self ): for obj in self.objs: obj.clean() Then, def f( thd ): resrc= thd.hold( NewResource() ) infinite_loop( resrc ) MemHoldingThread( target= f ) thd is prepended to f's list of arguments so that it has a handle to its own thread object, but doesn't need an entire thread class-- middle ground. Then thd.hold adds any obj created to a thread-local set (and returns it). Then, _cleanup iterates over the set, and calls clean() on its items when f returns. At this point, I've gotten really really complicated. Not only have I still not shown the _at_exit call to MemHoldingThread static member _clean_all_remaining, but it's only useful if NewResource provides a list of globals/externals that it "adds itself to", or a clean() method to do them itself. But, you do get the benefit of not having to store each global/external in a Thread subclass object-- it does that for you-- as well as the benefit of being able to invoke the behavior without explicit additional subclasses. thing1= MemHoldingThread( target= thingf ); thing1.start() daemon1= MemHoldingThread( target= daemonf ); daemon1.start() server1= MemHoldingThread( target= serverf ); server1.start() rather than class Thing( Thread ):... thing1= Thing(); thing1.start() class Daemon( Thread ):... daemon1= Daemon(); daemon1.start() class Server( Thread ):... server1= Server(); server1.start() , which is useful sometimes, if even only a negligible proportion of them. (Honestly, if Thread.start() returned self, class Thing( Thread ):... thing1= Thing().start() , or Thread( start= True ) launched it, that could go a long way, -- you just get keyword name collisions with target's parameters pretty soon.) What are the disadvantages to specifying an internal storage byte order for conversion to a string to use mmap with, by the way? And for all my seniors out there, you may be pleased to learn that I no longer think that all of my general little 5-liners should go in the standard library. > you consider inter process communication. For instance, if you create > an object in one process then serialize it and pass it to another > process through e.g. an XMLRPC call, there's no automatic way for the > other process to be notified that the originating process exited. Maybe... but if all else fails you can pass the process ID in on connection creation, and periodically check if it's still alive. Do any Op. Sys.s have a OnProcTerminate( hproc, callback ) API? Sadly, stdin IPC is before my time. Windows actually even has ThreadSuspend and ThreadResume API; if suspending threads (and raising exceptions in them from others) threatens state consistency, what are their semantics? From grante at visi.com Wed Mar 5 17:00:57 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 22:00:57 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> Message-ID: <13su60prq21ccd2@corp.supernews.com> On 2008-03-05, castironpi at gmail.com wrote: >>>>> I want to hash values to keys. ?How do the alternatives compare? >> >>>>http://catb.org/~esr/faqs/smart-questions.html >> >>> ... without extending the whole way to a full relational database? >> >> You didn't bother following the link and reading the advice, did you? If >> you did, you haven't done a good job of following that advice. > > Well, obviously there's someone who's interested in computers and > programming that has a question. It may be obvious that he has a question. It's not the least bit obvious what that question is. > Communication is not his forte, but effort, willingness, > devotion, and dedication are. What should he do, and what > should the others, who are gifted speakers? He should spend less time trying to generate "gifted speach" and more time learning how to ask an understandable, meaningful question. The link which you ignored explains how to do that. In your original post, it's not very clear what you mean by "hash values to keys" means nor what alternatives you're asking about. If you're trying to learn about hashing algorithms, then google "hashing algorithms" and read the first half-dozen hits. The first two are Wikipedia articles which are both quite good and are almost certainly available in your native lanauge. -- Grant Edwards grante Yow! But they went to MARS at around 1953!! visi.com From duncan.booth at invalid.invalid Mon Mar 17 12:12:13 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 16:12:13 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <47de94fa$0$2679$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: >> Here's a puzzle for those who think they know Python: >> >> Given that I masked out part of the input, which version(s) of Python >> might give the following output, and what might I have replaced by >> asterisks? >> >>>>> a = 1 >>>>> b = **** >>>>> if a is b: print 'yes!' >> ... >>>>> b >> 1 >>>>> type(b) >> > > I know it! Using CPython 2.5.2a0, 2.6a1+ and 3.0a3+:: > > >>> b = type('type', (type,), {'__repr__': lambda self: > ... ""})('int', (object,), {'__repr__': > ... lambda self:"1"})() > >>> b > 1 > >>> type(b) > > >>> 1 is b > False > > What's my prize? Ok, that one is impressive, I should have thought of putting some more checks (like asserting type(a) is type(b)), but then the whole point of setting the puzzle was that I expected it to be ripped to shreds. You can queue up behind Steven to choose any of the exciting prizes on my non-existent prize table. Meanwhile, I'll fall back on the same quibbling getout I used with Steven: too long. From grante at visi.com Sat Mar 15 17:45:27 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Mar 2008 21:45:27 -0000 Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <13togrnsdfipa64@corp.supernews.com> On 2008-03-15, Guido van Brakel wrote: > Hello > > I have this now: > >> def gem(a): >> g = sum(a) / len(a) g = float(sum(a)) / len(a) >> return g > It now gives a int, but i would like to see floats. How can integrate > that into the function? See above. > Life is like a box of chocolates, you never know what you're gonna get sometimes it's a crunchy frog... -- Grant From rcdailey at gmail.com Fri Mar 28 15:22:45 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 28 Mar 2008 14:22:45 -0500 Subject: New python forum on CodeGuru! Message-ID: <496954360803281222i82827acvc873f9dfc35933c7@mail.gmail.com> Hi, I managed to convince the CodeGuru forum administrator to add a Python discussion forum to the community. It's a great success for me, as I really love CodeGuru and their forums. I really encourage everyone to use it, as it will be a great asset to the Python community. The forum will be removed if it doesn't generate enough traffic in the next few months, so please help support it by generating discussion there instead of on the mailing list. You can visit the following link to get to the forum: http://www.codeguru.com/forum/forumdisplay.php?f=95 -------------- next part -------------- An HTML attachment was scrubbed... URL: From malkarouri at gmail.com Sat Mar 8 09:43:23 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 06:43:23 -0800 (PST) Subject: List as FIFO in for loop Message-ID: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Hi everyone, I have an algorithm in which I need to use a loop over a queue on which I push values within the loop, sort of: while not(q.empty()): x = q.get() #process x to get zero or more y's #for each y: q.put(y) The easiest thing I can do is use a list as a queue and a normal for loop: q = [a, b, c] for x in q: #process x to get zero or more y's q.append(y) It makes me feel kind of uncomfortable, though it seems to work. The question is: is it guaranteed to work, or does Python expect that you wouldn't change the list in the loop? Regards, Muhammad Alkarouri From google at mrabarnett.plus.com Sun Mar 16 15:27:30 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 16 Mar 2008 12:27:30 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: On Mar 16, 2:27 am, Benjamin wrote: > On Mar 15, 8:12 pm, lampshade wrote:> Hello, > > > I'm having some problems with os.path.isdir I think it is something > > simple that I'm overlooking. > > > #!/usr/bin/python > > import os > > > my_path = os.path.expanduser("~/pictures/") > > print my_path > > results = os.listdir(my_path) > > for a_result in results: > > if os.path.isdir(str(my_path) + str(a_result)): > > Try if os.path.isdir(os.path.join(my_path, a_result)):> results.remove(a_result) > > > for x in results: print x > > > The problem is, that the directories are never removed. Can anyone > > point out what I'm missing that is causing the bug? Is there a better > > way of doing this? > > You should always use os.path.join to join paths. You shouldn't add > them like normal strings. I suspect you're getting a combination which > doesn't exist, so it isn't a dir. :) > You are also removing items from 'results' while iterating over it, which has an undefined behaviour. It would be better to build a new list of those that aren't directories. From pofuk at email.t-com.hr Sun Mar 2 06:59:28 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Sun, 2 Mar 2008 12:59:28 +0100 Subject: Python app at startup! References: <5fd991f2-d079-4218-8198-fa79c2d29955@z17g2000hsg.googlegroups.com> Message-ID: Program: import os import wx app = wx.App() frame = wx.Frame(None, -1, "MyFrame") frame.Show() app.MainLoop() python.exe setup.py py2exe from distutils.core import setup import py2exe setup(windows=['prog.py']) wrote in message news:e11b4e83-8eae-4d4c-bd29-3f2bd5d8daa5 at 41g2000hsc.googlegroups.com... > On Feb 29, 7:21 am, SMALLp wrote: >> dave_mikes... at fastmail.fm wrote: > >> >> > Does it do the same thing when you run it with the Python interpreter? >> >> No. The programm works fine! In interupter and when i "compile" it. > > My guess is that you're not including something in the .exe that you > need. What does your py2exe command line and setup.py look like? > From pdl5000 at yahoo.com Fri Mar 28 11:12:36 2008 From: pdl5000 at yahoo.com (Paul Lemelle) Date: Fri, 28 Mar 2008 08:12:36 -0700 (PDT) Subject: Pexpect question. Message-ID: <918528.31885.qm@web52902.mail.re2.yahoo.com> I am trying separate a script that users pexpect into various functions within the same expect session. The problem is that the function does not return control back Main. Any insight into this issue would be greatly appreciated. Below is sample code of the problem. Thanks, Paul ____ import pexpect def sshcon(user, password): go = pexpect.spawn ('/usr/bin/ssh -l root %s '% (user)) go.expect ('Password: ') go.sendline (password) go.interact() #get node info for both clusters. C1_node = raw_input("Enter the ip address for node on cluster 1: ") C1_pass = raw_input("Enter the password for the node on cluster 1: ") sshcon(C1_node, C1_pass) #go to the path chk.expect('# ') chk.sendline('ls') #chk = pexpect.spawn('ls') # veriy that you are connected chk.interact() ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From r.grimm at science-computing.de Thu Mar 27 13:06:56 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Thu, 27 Mar 2008 10:06:56 -0700 (PDT) Subject: singleton decorator Message-ID: <1983c7ec-a7da-4fae-97a9-4f22cc2ea4c7@d4g2000prg.googlegroups.com> Hallo, playing with the decorators from PEP 318 I found the elegant singleton decorator. def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class A: pass class B: pass a1=A() a2=A() a3=A() b1=B() b2=B() b3=B() for i in ((a1,b1),(a2,b2),(a3,b3)): print id(i[0]),id(i[1]) But I always get a syntax error declaring class A as singleton. >>> reload ( decorator) Traceback (most recent call last): File "", line 1, in ? File "decorator.py", line 27 class A: pass ^ SyntaxError: invalid syntax What's the problem with this code because it's only copied for the PEP 318? It doesn't work with python 2.4 and python 2.5. Greetings Rainer From stephan.diehl at gmx.net Tue Mar 4 07:36:08 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 04 Mar 2008 13:36:08 +0100 Subject: Eurosymbol in xml document References: Message-ID: Hallo Helmut, > Hi, > i'm new here in this list. > > i'm developing a little program using an xml document. So far it's easy > going, but when parsing an xml document which contains the EURO symbol > ('?') then I get an error: > > UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in > position 11834: character maps to first of all, unicode handling is a little bit difficult, when encountered the first time, but in the end, it really makes a lot of sense :-) Please read some python unicode tutorial like http://www.amk.ca/python/howto/unicode If you open up a python interactive prompt, you can do the following: >>> print u'\u20ac' ? >>> u'\u20ac'.encode('utf-8') '\xe2\x82\xac' >>> u'\u20ac'.encode('iso-8859-15') '\xa4' >>> u'\u20ac'.encode('iso-8859-1') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'latin-1' codec can't encode character u'\u20ac' in position 0: \u20ac is the unicode code point for the Euro sign, so u'\u20ac' is the unicode euro sign in python. The different encode calls translate the unicode into actual encodings. What you are seeing in your xml document is the iso-8859-15 encoded euro sign. As Diez already noted, you must make shure, that 1. the whole xml document is encoded in latin-15 and the encoding header reflects that or 2. make sure that the utf-8 encoded euro sign is in your xml document. Hope that makes sense Stephan From jaywgraves at gmail.com Thu Mar 6 13:11:59 2008 From: jaywgraves at gmail.com (jay graves) Date: Thu, 6 Mar 2008 10:11:59 -0800 (PST) Subject: List all files using FTP References: Message-ID: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> On Mar 6, 10:46 am, Anders Eriksson wrote: > I need to list all the files on my FTP account (multiple subdirectories). I > don't have shell access to the account. > anyone that has a program that will do this? Not offhand, but you can look at the ftpmirror.py script for inspiration. It should be in your Tools/scripts/ subdirectory of your Python installation. ... Jay Graves From xkenneth at gmail.com Wed Mar 12 00:30:49 2008 From: xkenneth at gmail.com (xkenneth) Date: Tue, 11 Mar 2008 21:30:49 -0700 (PDT) Subject: Python - CGI - XML - XSD Message-ID: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> Hi All, Quick question. I've got an XML schema file (XSD) that I've written, that works fine when my data is present as an XML file. (Served out by apache2.) Now when I call python as a cgi script, and tell it print out all of the same XML, also served up by apache2, the XSD is not applied. Does this have to do with which content type i defined when printing the xml to stdout? Regards, Kenneth Miller From castironpi at gmail.com Sun Mar 9 21:29:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 18:29:39 -0700 (PDT) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> <980fee99-808b-47f2-8782-faac7c6a7586@34g2000hsz.googlegroups.com> Message-ID: <5b8774ff-ff74-44eb-8a73-bb71109f651c@p25g2000hsf.googlegroups.com> > Write the docs: > > > when two threads simultaneously increment the reference count of the same object > > Well, the example sucked. ?Just synchronize ref count manipulation. > Every OS has locking primitives, and a library exists to deny requests > to block that lock dead. ?How integral is the GIL to Python? > > > The Python interpreter is not fully thread safe > > Make it so. Per-thread reference counts do the trick. From rmsa50 at yahoo.co.in Wed Mar 19 13:02:41 2008 From: rmsa50 at yahoo.co.in (Gokul) Date: Wed, 19 Mar 2008 10:02:41 -0700 (PDT) Subject: Latest updates inSQL server and other programming laguages like C++/Java Message-ID: The latest developments in SQL server 2008 and an complete encyclopedia of microsoft softwares. Know the methodology to capture customers requirements for new products. Get the latest development in C++ and other IT related tools. A complete tutor for all your IT needs. Visit http://www.sqlserversoftware.blogspot.com From castironpi at gmail.com Mon Mar 17 18:51:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 15:51:47 -0700 (PDT) Subject: Interesting math problem References: Message-ID: <84bcedd4-e2a1-4184-baaa-0170547dbcc2@59g2000hsb.googlegroups.com> On Mar 17, 5:24?pm, "BJ?rn Lindqvist" wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > ? ? step = distance / float(parts) > ? ? intstep = int(step) > ? ? floatstep = step - intstep > > ? ? steps = [] > ? ? acc = 0.0 > ? ? for i in range(parts): > ? ? ? ? acc += floatstep > ? ? ? ? step = intstep > ? ? ? ? if acc > 0.999: > ? ? ? ? ? ? step += 1 > ? ? ? ? ? ? acc -= 1.0 > ? ? ? ? steps.append(step) > ? ? return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L Hash functions create a uniform distribution too. But don't those use shifting and modulo instead? From bearophileHUGS at lycos.com Wed Mar 26 18:28:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 15:28:58 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: Message-ID: <2f626a4d-1db2-4b10-bf5c-e4197a3db811@z38g2000hsc.googlegroups.com> Micha? Bentkowski: > Why does python create a reference here, not just copy the variable? I think to increase performance, in memory used and running time (and to have a very uniform way of managing objects). Bye, bearophile From electronixtar at gmail.com Thu Mar 20 03:40:49 2008 From: electronixtar at gmail.com (est) Date: Thu, 20 Mar 2008 00:40:49 -0700 (PDT) Subject: forkpty not working? Message-ID: Hello everyone. I am trying to write a bash/ssh wrapper in python so python scripts could interact with bash/ssh. Because when input passwords to ssh it requires a tty rather than stdin pipe, so i have to use a pty module to do that. I copied this snippet from this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/6bbc3d36b4e6ff55/ def rcmd(user, rhost, pw, cmd): #Fork a child process, using a new pseudo-terminal as the child's controlling terminal. pid, fd = os.forkpty() # If Child; execute external process if pid == 0: os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + cmd) x=open("it_worked.txt", "w") #output a file for test x.write("xxx") x.close() #if parent, read/write with child through file descriptor else: pause() #Get password prompt; ignore os.read(fd, 1000) pause() #write password os.write(fd, pw + "\n") pause() res = '' #read response from child process s = os.read(fd,1 ) while s: res += s s = os.read(fd, 1) return res As far as I can see the code is not working, when called the function rcmd() there is no file it_worked.txt spawned in the directory. I am n00b to POSIX, so anyone please give me some hint? what happened when os.forkpty()? From http Wed Mar 19 04:19:41 2008 From: http (Paul Rubin) Date: 19 Mar 2008 01:19:41 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> Message-ID: <7xve3j15ya.fsf@ruckus.brouhaha.com> Gerhard H?ring writes: > Probably because Ruby is all hot and sexy nowadays ;-) Though it's > remarkably close to Python, apparently. So close that I couldn't be > bothered to learn it. Ruby is apparently more Smalltalk-like and some consider it cleaner than Python. Like you, I figure it's close enough to Python that I haven't bothered with it. > In fact, for me personally, Python was about the last programming > language I learnt out of intrinsic motivation. I tried to take a look > at functional langugages like Haskell and Erlang, but I tend to > quickly get bored of toy examples and can learn best if I can apply a > new language to a real problem that it can solve better than the other > languages I know. Haven't found that killer problem so far ... The killer problem for Erlang is highly concurrent, distributed systems. I've been wanting to read Joe Armstrong's book about it since I have some interest in that sort of thing. It's not simply the ability to run vast numbers of threads and automatically marshal data between them (even if they're on separate computers), but also its convenient management of software faults through "supervision trees". In most languages we normally program our functions to notice error conditions and recover from them, raise exceptions that are handled elsewhere in the app, etc. In Erlang you just let the thread crash, and have the supervision system deal with restarting it, logging the error, etc. This separation of concerns apparently helps reliability of nonstop services like phone switches considerably. Also, Erlang has hot-patching facilities so you can upgrade your program while it's running, with 10,000 active network connections staying up and nobody outside noticing that anything has changed. Re Haskell: I've been spending a lot of time on Haskell recently, though I haven't done anything nontrivial with it yet (just some small stuff). But I think it's better for complex program development than Python is, and even small Haskell programs, (while they are more difficult to write, at least at my present level of experience) seem both cleaner and more solid in terms of confidence of correctness than the corresponding Python programs. Also, Haskell code runs a lot faster than Python code (real native-code compiler that can use multicore hardware), and there is a clever automatic unit testing system (QuickCheck) that relies on Haskell's static type system to generate random tests automatically. On the other hand, Python's standard libraries do more stuff and are better packaged. It's certainly easier to do lightweight internet scripting in Python. If I were writing something like a compiler, I'd probably use Haskell. From jayapal.d at gmail.com Sat Mar 15 00:26:50 2008 From: jayapal.d at gmail.com (jai_python) Date: Fri, 14 Mar 2008 21:26:50 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: On Mar 14, 9:45 pm, Jeff Schwab wrote: > Chris wrote: > > On Mar 14, 8:36 am, Dennis Lee Bieber wrote: > >> On Thu, 13 Mar 2008 21:28:18 -0700 (PDT), jai_python > >> declaimed the following in comp.lang.python: > > >>> hi frenz I Need a Python Script For read multiple files(.txt) from a > >>> folder and write it in a single text file.... > >> If you are on windows, just open a command prompt and use the > >> standard copy command... > > >> C:\Documents and Settings\Dennis Lee Bieber>copy /? > ... > > If you want to go that route you could also do: type *.txt > > > output_file.txt > > On Unix, cygwin, etc: > > cat dir/*.txt > output.txt > > Or if you need "deep" copy: > > cat $(find dir -name '*.txt') > output.txt > > You could write a portable solution in Python (as in Martin Laloux's > post), but most modern command-line environments have similar (but not > identical) support for globbing and redirecting files. If you're > getting the glob pattern from a user, they may expect subtly > platform-dependent behaviors, in which case portability might not as > important as native feel. ya its working.... thanks for all ur help From piet at cs.uu.nl Wed Mar 12 09:55:53 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 12 Mar 2008 14:55:53 +0100 Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: >>>>> gargonx (g) wrote: >g> Still no return of string. The null testing is not really the deal. >g> that could be replaced with anything EG: >g> def ReturnMethod(request, x): >g> if request is 'random': You shouldn't test with `is' but with `=='. >g> return x >g> else: print "No String for you...False!" >g> def SendMethod(request): >g> xstring = "Some text" >g> ReturnMethod(request, xstring) >g> SendMethod('random') -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From google at mrabarnett.plus.com Thu Mar 20 23:37:12 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 20 Mar 2008 20:37:12 -0700 (PDT) Subject: Trouble with variable "leakage"? References: Message-ID: <4869f2a6-98d1-405a-8e65-2e2686134126@d45g2000hsc.googlegroups.com> On Mar 21, 3:05 am, Jeremy N wrote: > I am working with Python in Maya, and have run into a problem with a > variable changing its contents without being scripted to do so. The > various print() statements below were from my efforts to track down > where it was occurring. I left them in so that anyone running this > will more easily see what's happening. > > On the line that reads 'dx = d1 / dx ; print("dx = %f" % dx)' there > is something happening to the variable that is being printed > repeatedly between the lines. The print statements prior to this > particular line print '...xlist[0][1] = 0.5' . However, on this > line, that variable is being updated to reflect a new value, when no > assignment to that variable has been made at that time. > > This leads me to believe that the variables 'dx' and 'xlist[0][1]' > are inexplicably linked. I have no idea why. Please help me. > > a=[5,0,3,4] > b=[8,3,0,10] > c=[2,4,10,0] > > nlist = [a,b,c] > xlist = [[],[],[]] > > for i in range(len(nlist)) : > relist = list(nlist) > relist.pop(i) > dlist = list(nlist[i]) > dlist.pop(0) ; dlist.pop(i) > for j in range(len(relist)) : > d1 = float(nlist[i][0]) > d2 = float(relist[j][0]) > dx = float(dlist[j]) > r1 = 1 - ( abs(d1-dx) / float(d2) ) > if r1 == 0.0 : > r1 += (d1 < d2) > xlist[i].append(float(r1)) > > del d1, d2, dx, relist, dlist > > ylist = list(xlist) This is performing only a shallow copy. xlist refers to a list containing sublists. You're copying the _references_ to the sublist, not the sublists themselves. > print(xlist) > print(ylist) > > for i in range(len(xlist)) : > relist = list(xlist) > relist.pop(i) > for j in range(len(relist)) : > print( "!!!!!!!!!!!!!!! NEW LOOP AT ( %d:%d ) !!!!!!!!!!!!!!!" % > ( i, j ) ) > print("%s / (%s + %s)" % ( str(xlist[i][j]), str(xlist[i][j]), > str(relist[j][( (i!=0) * ((j>=i)+(i-1)) )]) ) ) > d1 = float(xlist[i][j]) ; print("d1 = %f" % d1) > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > d2 = relist[j][( (i!=0) * ((j>=i)+(i-1)) )] ; print("d2 = %f" % d2) > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > dx = d1 + d2 ; print("dx = %f" % dx) > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > dx = d1 / dx ; print("dx = %f" % dx) > ylist[i][j] = float(dx) ; #print(ylist[i][j]) ylist[i] is the same list as xlist[i], so changing ylist[i][j] also changes xlist[i][j]. > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > print( "||| xlist[2][0] = %s" % str(xlist[2][0]) ) > print( "...\nxlist = %s\n..." % str(xlist) ) > > print(xlist) > print(ylist) > HTH. From perlefenc at gmail.com Thu Mar 27 12:13:19 2008 From: perlefenc at gmail.com (perlefenc at gmail.com) Date: Thu, 27 Mar 2008 09:13:19 -0700 (PDT) Subject: Dynamic code problem Message-ID: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> My dynamic code failed at this site http://playwide1.extra.hu/, need some help thank you. From micah at cowan.name Thu Mar 6 00:03:47 2008 From: micah at cowan.name (Micah Cowan) Date: Thu, 06 Mar 2008 05:03:47 GMT Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> Message-ID: <87hcfk30lo.fsf@micah.cowan.name> castironpi at gmail.com writes: > On Mar 5, 8:03?pm, castiro... at gmail.com wrote: >> On Mar 5, 5:31?pm, Grant Edwards wrote: >> >> > On 2008-03-05, castiro... at gmail.com wrote: >> > > Anyway, if (a,b) is a key in dictionary d, can it guarantee >> > > that (b,a) is also in it, and maps to the same object? >> >> Er... -specialized- dictionary d. >> >> > To solve that problem, Python provides the immutable >> > "frozenset" type: >> >> > ? >>> s1 = frozenset((1,2)) >> > ? >>> s2 = frozenset((2,1)) >> > ? >>> s1 == s2 >> > ? True >> > ? >>> d = {s1: "hi there"} >> > ? >>> s1 in d >> > ? True >> > ? >>> s2 in d >> > ? True >> >> Ah. ?Perfect. ?With this, I can just call frozenset on keys in >> __setitem__ and __getitem__... (though at that, it may be easier >> verbatim*.) > >> a= SomeList( [ 1,2,3 ] ) >> b= SomeList( [ 1,2,3 ] ) >> assert a is not b >> d[a]= True >> assert b not in d >> #there's the hangup > > *plonk* > > key is an iterable, just like the constructors to > other collection. Um... "*plonk*" is the (imaginary) sound made by dropping someone into your plonkfile (killfile, scorefile, whatever): the action of setting your newsreader to ignore someone you perceive to be a troll. I have extreme doubts that you have actually done this to _yourself_. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From troworld at gmail.com Sun Mar 2 16:48:49 2008 From: troworld at gmail.com (Tro) Date: Sun, 2 Mar 2008 16:48:49 -0500 Subject: Altering imported modules In-Reply-To: References: <200803011856.27611.troworld@gmail.com> Message-ID: <200803021648.49590.troworld@gmail.com> On Sunday 02 March 2008, Terry Reedy wrote: > "Tro" wrote in message > news:200803011856.27611.troworld at gmail.com... > > | Hi, list. > | > | I've got a simple asyncore-based server. However, I've modified the > > asyncore > > | module to allow me to watch functions as well as sockets. The modified > | asyncore module is in a specific location in my project and is imported > > as > > | usual from my classes. > | > | Now I'd like to use the tlslite library, which includes an asyncore mixin > | class. However, tlslite imports "asyncore", which doesn't include my own > | modifications. > | > | I'd like to know if it's possible to make tlslite load *my* asyncore > > module > > | without changing any of the tlslite code. > > If your module is also 'asyncore' and comes earlier in the search path, I > would expect the import to get yours. It's not. It has a package prefix like my.package.asyncore. I think I can either move my version of asyncore up a couple of levels or add the my.package directory to sys.path. My version of asyncore imports several functions from the built-in asyncore. Now that my version of it is imported as asyncore, how would it import the built-in version from python2.5/site-packages? Thanks, Tro From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 13 07:02:23 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Mar 2008 12:02:23 +0100 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> Message-ID: <47d90982$0$22008$426a74cc@news.free.fr> Alex a ?crit : (sni) > First of all thanks all for answering! > > I have some environment check and setup in the beginning of the code. > I would like to move it to the end of the script. Why ? (if I may ask...) > But I want it to > execute first, so the script will exit if the environment is not > configured properly. If you want some code to execute first when the script/module is loaded, then keep this code where it belongs : at the beginning of the script. From emailamit at gmail.com Mon Mar 31 13:24:01 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 10:24:01 -0700 (PDT) Subject: python scripts to standalone executable Message-ID: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Hi I am looking for a some tool that can convert python scripts to executable on Linux. I found freeeze.py as the only option so far. Couple of queries on freeze: 1. Have anyone used the freeze utility and any experiences to share from that? 2. Is there any enterprise-level exe-builder for python on linux (ActiveState has nothing)? Any other related commets are also welcome. Thanks Amit From jaywgraves at gmail.com Thu Mar 6 12:38:05 2008 From: jaywgraves at gmail.com (jay graves) Date: Thu, 6 Mar 2008 09:38:05 -0800 (PST) Subject: Data aggregation References: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> Message-ID: <81dbde3d-3ecf-4312-a3c4-9b0d31e98e5b@m34g2000hsc.googlegroups.com> On Mar 6, 10:28 am, vedranp wrote: > So, group by DATE, COUNTRY, ZIP and CITY and sum (or do some You are soooo close. Look up itertools.groupby Don't forget to sort your data first. http://aspn.activestate.com/ASPN/search?query=groupby&x=0&y=0§ion=PYTHONCKBK&type=Subsection http://mail.python.org/pipermail/python-list/2006-June/388004.html > From some little experience with Perl, I think this is managable with > double hash tables (1: basic hash with key/value = CITY/pointer-to- > other-hash, 2: hash table with values for CITY1), so I assume that > there would be also a way in Python, maybe with dictionaries? Any > ideas? Sometimes it makes sense to do this with dictionaries. For example, if you need to do counts on various combinations of columns. count of unique values in column 'A' count of unique values in column 'C' count of unique combinations of columns 'A' and 'B' count of unique combinations of columns 'A' and 'C' count of unique combinations of columns 'B' and 'C' in all cases, sum(D) and avg(E) Since I need 'C' by itself, and 'A' and 'C' together, I can't just sort and break on 'A','B','C'. HTH ... jay graves From planders at gmail.com Thu Mar 20 17:02:12 2008 From: planders at gmail.com (Preston Landers) Date: Thu, 20 Mar 2008 14:02:12 -0700 (PDT) Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: On Mar 20, 9:46?am, Jonathan Gardner wrote: > In the unix world, this is highly discouraged. You shouldn't have to > change your user. The only user who can change roles---and who should > change roles for security reasons---is root. IMHO this statement is a bit too broad. The original poster didn't specify that he wanted to become root. Running a command as a different user is useful for other cases besides running as root. For instance, your web server's documents directory may be owned by a www user who doesn't have a normal login shell. If you're on your 'regular' user and need to edit a document it's quite handy to do this: sudo -u www emacs index.html As for the original poster, you could use the subprocess module combined with sudo to do what you want - spawn a subprocess which runs sudo and the other program, which could itself be a python script or anything else. regards, Preston From pavlovevidence at gmail.com Sun Mar 30 01:17:13 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Mar 2008 22:17:13 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <3e6de9d7-4278-4b1e-9373-78c98fa11a3f@m34g2000hsc.googlegroups.com> <13utqsnq8le081f@corp.supernews.com> Message-ID: <4ef57592-4057-4ee7-8889-7b2fefdc6504@f63g2000hsf.googlegroups.com> On Mar 29, 9:23 pm, Steven D'Aprano wrote: > On Sat, 29 Mar 2008 12:49:05 -0700, Carl Banks wrote: > >> Please set it straight in 3.0, and if not, convince me with a good > >> reason of doing so, so that I can live with it and don't have to spend > >> the rest of my life in 2.x ;). > > > 1. It's not going to change in Python 3.0. > > > 2. It's a silly thing to care so much about that you will avoid using a > > langauge because of it. > [snip indignant rant] > > But it's not silly to care > about the feel of the language. I'm not exactly sure who you're arguing with, bud. No one around here that I can tell said anything about what you're railing against. Carl Banks From roygeorget at gmail.com Wed Mar 19 11:54:40 2008 From: roygeorget at gmail.com (royG) Date: Wed, 19 Mar 2008 08:54:40 -0700 (PDT) Subject: how to remove suffix from filename Message-ID: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> hi when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/ two.jpg'....] etc i want to extract the basename without the suffix...ie i want to get 'one','two' etc and not 'one.jpg' is there a function in python to do this or do i have tosplit it ..? thanks RG From newsgroup898sfie at 8439.e4ward.com Tue Mar 4 12:05:55 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Tue, 04 Mar 2008 12:05:55 -0500 Subject: 'normal' shell with curses In-Reply-To: References: <633s5lF24prinU1@mid.uni-berlin.de> Message-ID: <635drhF25qgqtU1@mid.uni-berlin.de> Thynnus wrote, on 03/04/2008 08:48 AM: > On 3/3/2008 9:57 PM, Michael Goerz wrote: >> Hi, >> >> I'm trying to print out text in color. As far as I know, curses is the >> only way to do that (or not?). So, what I ultimately want is a curses >> terminal that behaves as closely as possible as a normal terminal, >> i.e. it breaks lines and scrolls automatically, so that I can >> implement a function myprint(color, text) that does what print() does, >> only in color. > > You might find the below helpful. Let us know how you make out? > > -------- > > Python Cookbook > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 > > Title: > Using terminfo for portable color output & cursor control > > Description: > The curses module defines several functions (based on terminfo) that can > be used to perform lightweight cursor control & output formatting > (color, bold, etc). These can be used without invoking curses mode > (curses.initwin) or using any of the more heavy-weight curses > functionality. This recipe defines a TerminalController class, which can > make portable output formatting very simple. Formatting modes that are > not supported by the terminal are simply omitted. > > -------- > That looks *extremely* interesting. From a very brief test, it seems to do exactly what I want! Now, Windows seems very problematic for color output. I was using the following as a test, based on the above recipe: term = TerminalController() while True: print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled' print term.render('${RED}Error:${NORMAL}'), 'paper is ripped' On Linux, it works fine, on Windows, it just prints white on black (which is of course what it should do if the terminal doesn't support color). Can anyone get the Windows cmd.exe terminal to do color? I already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, but that doesn't seem to do anything (neither in what I tried yesterday with the ANSI escape codes, nor with the recipe code now). I also very briefly tried running it on the winbash shell (http://win-bash.sourceforge.net/), it didn't have any color either... So, any way to get color in Windows? Michael From partofthething at gmail.com Tue Mar 18 09:34:22 2008 From: partofthething at gmail.com (partofthething) Date: Tue, 18 Mar 2008 06:34:22 -0700 (PDT) Subject: Can't get bsddb working on Solaris 8 References: Message-ID: I fixed it! I had omitted the cascade of exceptions, but the previous one to the one shown is: File "/usr/local/lib/python2.5/dbhash.py", line 5, in import bsddb So I just went into dbhash.py and changed line 5 to import bsddb3 as bsddb. Then everything started working as planned. Excellent! But definitely a hack. From tjreedy at udel.edu Thu Mar 13 17:30:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Mar 2008 17:30:50 -0400 Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlibfrom BeautifulSoup References: <47d97288$0$36363$742ec2ed@news.sonic.net> Message-ID: "John Nagle" wrote in message news:47d97288$0$36363$742ec2ed at news.sonic.net... | Just noticed, again, that getattr/setattr are ASCII-only, and don't support | Unicode. | | SGMLlib blows up because of this when faced with a Unicode end tag: | | File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag | method = getattr(self, 'end_' + tag) | UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' | in position 46: ordinal not in range(128) | | Should attributes be restricted to ASCII, or is this a bug? Except for comments and string literals preceded by an encoding declaration, Python code is ascii only: " Python uses the 7-bit ASCII character set for program text." ref manual 2. lexical analisis This changes in 3.0 From guidovb1 at invalid Sat Mar 15 17:53:16 2008 From: guidovb1 at invalid (Guido van Brakel) Date: Sat, 15 Mar 2008 22:53:16 +0100 Subject: Convert int to float In-Reply-To: <13togrnsdfipa64@corp.supernews.com> References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> <13togrnsdfipa64@corp.supernews.com> Message-ID: <47dc442d$0$14348$e4fe514c@news.xs4all.nl> Grant Edwards wrote: > On 2008-03-15, Guido van Brakel wrote: >> Hello >> >> I have this now: >> >>> def gem(a): >>> g = sum(a) / len(a) > > g = float(sum(a)) / len(a) > >>> return g Hi, Thank you very much,sometimes it is so amazing simple. Regards -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- From duncan.booth at invalid.invalid Tue Mar 11 04:36:29 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Mar 2008 08:36:29 GMT Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 10, 10:44???pm, Nathan Pinno wrote: >> Why does my compiler say invalid syntax and then highlight the >> quotation marks in the following code: >> >> # This program is to find primes. > > Needs work. Be fair. The OP hadn't managed to figure out why the program wasn't running, so you can't expect him to have got all the bugs out of the code yet. And he only asked about the specific syntax error not the entire solution to his homework. My advice to Nathan would be: 1. If you get a weird syntax error that you don't understand try cutting the code down to just the bit which generates the error. 2. Play around in the interactive interpreter to see what works and what doesn't. 3. If you don't understand why the code doesn't work then get a stuffed toy, cardboard cutout of a person, or the least technical member of your family and explain to them in great detail exactly why the code must (despite error messages to the contrary) be correct. Usually you'll spot the problem half way through the explanation. 4. If you post to this list then post the full error message and traceback. That way we don't have to guess which quotation marks are the problem. From castironpi at gmail.com Thu Mar 13 21:17:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 18:17:47 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: On Mar 13, 8:15?pm, castiro... at gmail.com wrote: > On Mar 13, 7:45?pm, castiro... at gmail.com wrote: > > > > > > > On Mar 13, 7:18?pm, Mel wrote: > > > > Diez B. Roggisch wrote: > > > >> My understanding is that foo.bar does *not* create a new object. > > > > > Your understanding is not correct. > > > > >> ?All it > > > >> does is return the value of the bar attribute of object foo. ?What new > > > >> object is being created? > > > > > A bound method. This happens through the descriptor-protocol. Please see > > > > this example: > > > > > class Foo(object): > > > > ? ? def bar(self): > > > > ? ? ? ? pass > > > > > f = Foo() > > > > a = Foo.bar > > > > b = f.bar > > > > c = f.bar > > > > > print a, b, c > > > > print id(b), id(c) > > > > (What Diez said.) ?From what I've seen, f.bar creates a bound method > > > object by taking the unbound method Foo.bar and binding its first > > > parameter with f. ?This is a run-time operation because it's easy to > > > re-assign some other function to the name Foo.bar, and if you do, the > > > behaviour of f.bar() will change accordingly. > > > > You can get some very useful effects from these kinds of games. ?You > > > can make f into a file-like object, for example, with > > > > import sys > > > f.write = sys.stdout.write > > > > Here, f.write *is* a straight attribute of f, although it's a built-in > > > method of the file class. ?It's still bound, in a way, to sys.stdout. > > > ? I'm assuming that a different example could create an attribute of f > > > that's a bound method of some other object entirely. ?I've verified > > > that f.write('howdy') prints 'howdy' on standard output. > > > Accordingly, > > > f.write= types.MethodType( sys.stdout.__class__.write, sys.stdout ). > > Ah. ?Because this doesn't. > That is, because sys.stdout.write is -not- a user-defined function. > What it is, is a bound member function, and only the former is > converted/wrapped/bound*, as it is in the subsequent example. Last thing, sorry: Does MethodType.__get__ just return self, or is it not called, due to some type checking? From pavlovevidence at gmail.com Tue Mar 4 12:05:15 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 4 Mar 2008 09:05:15 -0800 (PST) Subject: for-else References: Message-ID: On Mar 4, 10:55 am, "BJ?rn Lindqvist" wrote: > On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks wrote: > > > for ...: > > > ... > > > exhausted: > > > ... > > > broken: > > > ... > > > > The meaning is explicit. While "else" seems to mean little there. > > > So I may like something similar for Python 3.x (or the removal of the > > > "else"). > > > I would not be opposed to this on its own merits, but there is a > > rationale behind the name "else". If you consider a for loop to be a > > rolled-up if...elif...else statement (situations where this is > > reasonable tend to be the same ones were else would be useful), then > > the "else" clause would remain unchanged on the for loop. > > > For instance, if you have a (trivial) if...elif...else like this: > > > if a == 0: > > do_task_0() > > elif a == 1: > > do_task_1() > > elif a == 2: > > do_task_2() > > else: > > do_default_task() > > > You could roll it up into a for...else statement like this: > > > for i in range(3): > > if a == i: > > do_task[a]() > > else: > > do_default_task() > > You forgot the break statement. The else suite will always be executed > in this loop. Kind of proves bearophiles point, for-else is really > tricky. Ah ha, but that would have been a mistake with or without the else clause.... Carl Banks From sdeibel at wingware.com Fri Mar 7 09:36:44 2008 From: sdeibel at wingware.com (Stephan Deibel) Date: Fri, 07 Mar 2008 09:36:44 -0500 Subject: ANN: Wing IDE 3.0.4 released Message-ID: <47D152FC.2000407@wingware.com> Hi, We're happy to announce version 3.0.4 of Wing IDE, an advanced development environment for the Python programming language. It is available from: http://wingware.com/downloads Version 3.0.4 is a bug fix release that reduces debugger overhead by about 50% per Python instruction executed, improves breakpoints tracking during edits, expands support for PyGTK auto-completion, and makes 14 other minor improvements. See the change log for details: http://wingware.com/pub/wingide/3.0.4/CHANGELOG.txt It is a free upgrade for all Wing 3.0 users. *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. New features added in Wing 3.0 include: * Multi-threaded debugger * Debug value tooltips in editor, debug probe, and interactive shell * Autocompletion and call tips in debug probe and interactive shell * Automatically updating project directories * Testing tool, currently supporting unittest derived tests (*) * OS Commands tool for executing and interacting with external commands (*) * Rewritten indentation analysis and conversion (*) * Introduction of Wing IDE 101, a free edition for beginning programmers * Available as a .deb package for Debian and Ubuntu * Support for Stackless Python * Support for 64 bit Python on Windows and Linux (*)'d items are available in Wing IDE Professional only. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). *Purchasing & Upgrading* Wing IDE Professional & Wing IDE Personal are commercial software and require a license to run. To upgrade a 2.x license or purchase a new 3.x license: Upgrade: https://wingware.com/store/upgrade Purchase: https://wingware.com/store/purchase Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From sengol240 at gmail.com Mon Mar 24 00:44:48 2008 From: sengol240 at gmail.com (sengol240 at gmail.com) Date: Sun, 23 Mar 2008 21:44:48 -0700 (PDT) Subject: THE GOOGLE PROJECT NETWORK INVITES YOU TO EARN$1,000 IN A SINGLE PROJECT.NORMALLY YOU CAN MAKE 20 PROJECTS IN A DAY.YOUR CHANCE IS GOING TO RARN $3,00,000 IN A SINGLE WEEK.THE LINK IS BELOW Message-ID: THE GOOGLE PROJECT NETWORK INVITES YOU TO EARN$1,000 IN A SINGLE PROJECT.NORMALLY YOU CAN MAKE 20 PROJECTS IN A DAY.YOUR CHANCE IS GOING TO RARN $3,00,000 IN A SINGLE WEEK.THE LINK IS BELOW www.jeeva235.blogspot.com IT IS A FREE MONEY MAKING OPPORTUNITY From book243 at gmail.com Sat Mar 29 21:45:01 2008 From: book243 at gmail.com (book243 at gmail.com) Date: Sat, 29 Mar 2008 18:45:01 -0700 (PDT) Subject: Redacted Message-ID: Redacted From bcl at brianlane.com Sat Mar 22 19:10:19 2008 From: bcl at brianlane.com (Brian Lane) Date: Sat, 22 Mar 2008 16:10:19 -0700 Subject: re.search (works)|(doesn't work) depending on for loop order In-Reply-To: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: <47E591DB.7070106@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 sgharvey wrote: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: > If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. > If I try to match every pattern to one line at a time, only one > pattern will match. I don't see that behavior when I try your code. I had to fix your pattern loading: patterns[pattern] = re.compile(pattern_strings[pattern], re.VERBOSE) I would also recommend against using both the plural and singular variable names, its bound to cause confusion eventually. I also changed contents to self.contents so that it would be accessible outside the class. The correct way to do it is run each pattern against each line. This will maintain the order of the config.ini file. If you do it the other way you will end up with everything ordered based on the patterns instead of the file. I tried it with Python2.5 on OSX from within TextMate and it ran as expected. Brian - -- - ---[Office 70.9F]--[Outside 54.5F]--[Server 103.3F]--[Coaster 68.0F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH5ZHaIftj/pcSws0RAigtAJsE+NWTxwV5kO797P6AXhNTEp8dmQCfXL9I y0nD/oOfNw6ZR6UZIOvwkkE= =U+Zo -----END PGP SIGNATURE----- From http Mon Mar 31 13:41:59 2008 From: http (Paul Rubin) Date: 31 Mar 2008 10:41:59 -0700 Subject: [OT] troll poll References: Message-ID: <7xr6dq3i54.fsf@ruckus.brouhaha.com> "Daniel Fetchinson" writes: > [ ] - Xah Lee > [ ] - castironpi I've lost track but has it been established that they are not the same person? From malaclypse2 at gmail.com Thu Mar 27 11:19:17 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 27 Mar 2008 11:19:17 -0400 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: <16651e80803270819t131e01adle1a5b9ed8b8fb976@mail.gmail.com> > Why should I need to set shell=True? I'm not globbing anything. The > second case still fails: RTFM From simon at brunningonline.net Mon Mar 10 13:30:22 2008 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 10 Mar 2008 17:30:22 +0000 Subject: lowercase u before string in "python for windows" In-Reply-To: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> References: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> Message-ID: <8c7f10c60803101030i14180626u3bb1f59d54840bc5@mail.gmail.com> On Mon, Mar 10, 2008 at 5:20 PM, davidj411 wrote: > why does this occur when using the python windows extensions? There's nothing Windows specific about this - it just means that you have unicode strings. See , -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From pavloutefkros at gmail.com Sun Mar 9 17:28:45 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 9 Mar 2008 14:28:45 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: i know os.popen() but i want to execute a file with args From py1.forest at tibit.com Fri Mar 28 19:50:34 2008 From: py1.forest at tibit.com (Forest) Date: Fri, 28 Mar 2008 16:50:34 -0700 (PDT) Subject: why does socket.makefile require non-blocking mode? Message-ID: <21989.75.55.199.5.1206748234.squirrel@webmail.sonic.net> The socket.makefile() docs say, "the socket must be in blocking mode." I don't see any explanation of why blocking mode is required, and I'm not sure whether that means timeout mode is forbidden as well. Can someone clarify this? I wanted to use file-like objects with socket timeouts, so I ended up writing my own replacement for socket._fileobject. I'd appreciate it if someone could either explain to my why my new class was unnecessary, or else encourage me to contribute it as a patch to the socket module. Cheers, Forest From cappallo at gmail.com Sun Mar 2 11:14:46 2008 From: cappallo at gmail.com (TC) Date: Sun, 2 Mar 2008 08:14:46 -0800 (PST) Subject: Question on importing and function defs Message-ID: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> I have a problem. Here's a simplified version of what I'm doing: I have functions a() and b() in a module called 'mod'. b() calls a(). So now, I have this program: from mod import * def a(): blahblah b() The problem being, b() is calling the a() that's in mod, not the new a() that I want to replace it. (Both a()'s have identical function headers, in case that matters.) How can I fix this? Thanks for any help. From shakefu at gmail.com Fri Mar 7 18:00:44 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 15:00:44 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <13t3gq9qo0po5ce@corp.supernews.com> Message-ID: <81d37ead-edd9-4666-8adb-5b5da45c6321@k2g2000hse.googlegroups.com> On Mar 7, 4:35 pm, Jeffrey Froman wrote: > shak... at gmail.com wrote: > > I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > Django comes with some pretty handy filters for doing this sort of > formatting. Check out the "date", "now", "timesince" and "timeuntil" > filters here: > > http://www.djangoproject.com/documentation/templates/#built-in-filter... > > Jeffrey Very cool - that's definitely handy to know for the output side of things. I was mostly interested in writing a custom widget for handling datetime input, 'cause I can't imagine anyone being studious enough to use the 2008-03-07 12:00:00 format all the time... besides, it's hard to type! I'd much rather allow for users to just be able to type "12pm today". So much to learn, so little time! Jacob From steve at holdenweb.com Sat Mar 1 14:17:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 14:17:26 -0500 Subject: Import, how to change sys.path on Windows, and module naming? In-Reply-To: References: Message-ID: Jeremy Nicoll - news posts wrote: > Jeremy Nicoll - news posts wrote: > >> If I understand correctly, when I import something under Windows, Python >> searches the directory that the executing script was loaded from, then >> other directories as specified in "sys.path". > > Sorry to followup my own question, but I ran > > for p,q in enumerate(sys.path): print p, q > > and got: > > 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms > 1 C:\Program Files\~P-folder\Python25\Lib\idlelib > 2 C:\WINDOWS\system32\python25.zip > 3 C:\Program Files\~P-folder\Python25\DLLs > 4 C:\Program Files\~P-folder\Python25\lib > 5 C:\Program Files\~P-folder\Python25\lib\plat-win > 6 C:\Program Files\~P-folder\Python25\lib\lib-tk > 7 C:\Program Files\~P-folder\Python25 > 8 C:\Program Files\~P-folder\Python25\lib\site-packages > 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32 > 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib > 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin > > Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip > in their sys.path? What's the point of having a zip in the path? > So that the files inside the zip can be imported as modules and packsges, of course. > Also, looking in C:\WINDOWS\system32\ I don't actually have a file called > python25.zip, but I do have one called python25.dll - so has something gone > wrong in creation of sys.path? > No. I'm not sure why the zip file is on there by default. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From aahz at pythoncraft.com Fri Mar 14 14:05:22 2008 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2008 11:05:22 -0700 Subject: RIP: Joseph Weizenbaum Message-ID: Creator of Eliza: http://www-tech.mit.edu/V128/N12/weizenbaum.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From wtanksleyjr at gmail.com Wed Mar 19 11:17:44 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 19 Mar 2008 08:17:44 -0700 (PDT) Subject: How to get an XML DOM while offline? Message-ID: I want to parse my iTunes Library xml. All was well, until I unplugged and left for the train (where I get most of my personal projects done). All of a sudden, I discovered that apparently the presence of a DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing the Internet... So suddenly I was unable to do any work. I don't want to modify the iTunes XML; iTunes rewrites it too often. How can I prevent xml.dom.minidom from dying when it can't access the Internet? Is there a simpler way to read the iTunes XML? (It's merely a plist, so the format is much simpler than general XML.) -Wm From tmp1 at viltersten.com Fri Mar 7 13:12:38 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 19:12:38 +0100 Subject: SV: Regarding coding style In-Reply-To: <13t2vvstgkne233@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net> <13t2vvstgkne233@corp.supernews.com> Message-ID: <63ddtqF27a5u2U1@mid.individual.net> >> Personally, I dislike double spaces after >> sentences, but it is not wrong to put them >> there any more than it is wrong not to put >> them there. > > You're lucky my high school typing teacher > didn't hear you say that... I'm unclear if your teacher was a double or single spacer. It's only implied that he felt strongly one way. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From Graham.Dumpleton at gmail.com Tue Mar 25 20:35:12 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Mar 2008 17:35:12 -0700 (PDT) Subject: Beta testers needed for a high performance Python application server References: <47e99237$0$90273$14726298@news.sunsite.dk> Message-ID: <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> On Mar 26, 11:00 am, Damjan wrote: > >> I'm looking for beta testers for a high performance, event-driven Python > >> application server I've developed. > > >> About the server: the front end and other speed-critical parts of the > >> server are written in portable, multithreaded C++. > ... > > Why not just put it on the net somewhere and tell us where it is? > > People aren't generally going to want to help or even look at it if > > you treat it like a proprietary application. So, put the documentation > > and code up somewhere for all to see. > > BTW, multiprocess web servers such as Apache can quite happily make > > use of multiple cores. Even within a single Apache multithread process > > it can still use multiple cores quite happily because all the > > underlying network code and static file handling code is in C and not > > subject to the GIL. So, as much as people like to bash up on the GIL, > > within Apache it is not necessarily as big a deal as people make out. > > BTW nginx now has a mod_wsgi too, if someone is looking for an Apache > replacement. Yes that is a viable option, as still are existing fastcgi solutions for Apache, lighttpd and nginx. Because the bottlenecks are generally going to be in upper application layers it really comes down to personal preferences as to which you want to use, which you find easier to configure and manage, plus which you trust as being the most secure and stable. For truly high demand sites you should also be looking at spreading load across multiple hosts, not just because of performance but also because of redundancy. You would also be serving media off a different web server to your Python web application and configuring each web server to the specific task it is doing. So, there is a lot more to in than raw speed of underlying technology and so one should always treat with caution something that is being sold as some better way of doing things. This applies to Apache mod_wsgi, nginx mod_wsgi or anything else for that matter. All have benefits, but they also have shortcomings in different areas which may not always make them suitable for all applications, or at least they may need to be configured in specific ways to make them perform best for specific applications. Anyway, because it isn't that simple is why I'd like to see some actual documentation for this new contender posted in a public place, along with code being browsable so one can evaluate it without having to sign up for some closed beta program. Graham From kyosohma at gmail.com Wed Mar 5 17:00:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 5 Mar 2008 14:00:17 -0800 (PST) Subject: Please keep the full address References: Message-ID: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> On Mar 5, 3:51 pm, "D'Arcy J.M. Cain" wrote: > On Wed, 5 Mar 2008 13:38:59 -0800 (PST) > > Mike Driscoll wrote: > > On Mar 5, 12:50 pm, castiro... at gmail.com wrote: > > I'm not sure why you change the address like this but could you please > include the full address. Those of us who identify the time wasters > would also like to drop the responses to their posts and changing the > address makes this impossible. > > -- > D'Arcy J.M. Cain | Democracy is three What are you talking about? I didn't change the address at all. I'm not even sure what you mean. Are you talking about the post subject line (which I have never touched in any post)? If you're talking about the OP's email address, that's Google's fault for cropping them. Mike From misterwang at gmail.com Tue Mar 18 21:44:10 2008 From: misterwang at gmail.com (Peter Wang) Date: Tue, 18 Mar 2008 18:44:10 -0700 (PDT) Subject: Any fancy grep utility replacements out there? References: Message-ID: On Mar 18, 5:16 pm, Robert Kern wrote: > samsli... at gmail.com wrote: > > So I need to recursively grep a bunch of gzipped files. This can't be > > easily done with grep, rgrep or zgrep. (I'm sure given the right > > pipeline including using the find command it could be done....but > > seems like a hassle). > > > So I figured I'd find a fancy next generation grep tool. Thirty > > minutes of searching later I find a bunch in Perl, and even one in > > Ruby. But I can't find anything that interesting or up to date for > > Python. Does anyone know of something? > > I have a grep-like utility I call "grin". I wrote it mostly to recursively grep > SVN source trees while ignoring the garbage under the .svn/ directories and more > or less do exactly what I need most frequently without configuration. It could > easily be extended to open gzip files with GzipFile. > > https://svn.enthought.com/svn/sandbox/grin/trunk/ > > Let me know if you have any requests. And don't forget: Colorized output! :) -Peter From rent.lupin.road at gmail.com Mon Mar 17 23:13:29 2008 From: rent.lupin.road at gmail.com (James) Date: Mon, 17 Mar 2008 20:13:29 -0700 (PDT) Subject: Cost of Queue.put Message-ID: <7d3e817b-6931-4fc5-921c-b2cf2b2400fa@i7g2000prf.googlegroups.com> Hi all, I'm struggling with the following problem: I need to disconnect a web service invocation from the addition of some content to a search engine, so that the web service will always return in reasonable time. Basically, what I need is a multi-process safe persistent quick queue. The arrangement I had was a simple XML-RPC service running on the web server which the various web server threads POST the relevant search engine updates to. These updates were added to a persistent queue built on top of Queue.Queue and cPickle, and there was a separate thread in the XML-RPC server actually adding the updates to the search engine. However, the CPU consumption of the XML-RPC server seems to grow pretty much linearly with the length of the persistent queue. Isn't Queue.put O(1)? I include the code for the persistent queue below - it's a modified version of this code: http://mail.python.org/pipermail/python-list/2002-December/177394.html I suppose the addition of cPickle to the mix must hurt Queue.put()... Any recommendations for alternative persistent queues? Thanks, James class PickleQueue(Queue.Queue): """A multi-producer, multi-consumer, persistent queue.""" def __init__(self, filename, maxsize=0): """Initialize a persistent queue with a filename and maximum size. The filename is used as a persistent data store for the queue. If maxsize <= 0, the queue size is infinite. """ self.filename = filename Queue.Queue.__init__(self, maxsize) def _init(self, maxsize): # Implements Queue protocol _init for persistent queue. # Sets up the pickle files. self.maxsize = maxsize try: self.readfile = file(self.filename, 'r') self.queue = cPickle.load(self.readfile) self.readfile.close() except IOError, err: if err.errno == 2: # File doesn't exist, continue ... self.queue = Queue.deque() else: # Some other I/O problem, reraise error raise err except EOFError: # File was null? Continue ... self.queue = Queue.deque() # Rewrite file, so it's created if it doesn't exist, # and raises an exception now if we aren't allowed self.writefile = file(self.filename, 'w') cPickle.dump(self.queue, self.writefile, 1) log.info("(PickleQueue._init) created queue") def __sync(self): # Writes the queue to the pickle file. self.writefile.seek(0) cPickle.dump(self.queue, self.writefile, 1) self.writefile.flush() def _put(self, item): # Implements Queue protocol _put for persistent queue. self.queue.append(item) self.__sync() def _get(self): # Implements Queue protocol _get for persistent queue. item = self.queue.popleft() self.__sync() return item From mail at timgolden.me.uk Sun Mar 16 12:22:11 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 16:22:11 +0000 Subject: Spaces in path name In-Reply-To: <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> Message-ID: <47DD4933.7050609@timgolden.me.uk> joep wrote: > > Tim Golden wrote: >> Tim Golden wrote: >>> What I haven't investigated yet is whether the additional flags >>> your example is passing (shell=True etc.) cause the main Popen >>> mechanism to take a different path. >> Sure enough, passing shell=True -- which is probably quite >> a rare requirement -- causes the code to change the call >> from "a.exe b.doc" to '%COMSPEC% /c "a.exe" "b.doc"'. >> The quoting rules (from cmd /?) are slightly involved but >> I can't see at first why this shouldn't work. However it >> clearly doesn't so I'll try to put together either a patch >> to the subprocess code or to the docs warning of the behaviour. >> >> I think that, in general, you need to pass shell=True far less >> often that you might imagine. (Possibly only for internal >> commands like dir, copy etc.). >> >> TJG > > Thanks, I didn't know it is possible to drop the shell=True. The > explanation of the subprocess model are not very clear to me and the > examples are quite incomplete. I got it to work by trial and error and > looking at the usage in different packages. > > Dropping shell=True works well for my case, no error messages and it > still captures the standard output: > > p = subprocess.Popen([ > r"C:\Program Files\WinRAR\Rar.exe","v", > r"C:\temp\Copy of papers.rar"], stdout=subprocess.PIPE) > > I am still looking at different versions, and the cases when it works > and when it doesn't are still confusing. Well I've got a patch ready to go (which basically just wraps a shell=True command line with an *extra* pair of double-quotes, the same as you do for an os.system call). I'll try to put some time into the subprocess docs as well, at least as far as a Win32-how-do-I on my own site if not an update to the official docs. TJG From jzgoda at o2.usun.pl Wed Mar 26 18:15:31 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 26 Mar 2008 23:15:31 +0100 Subject: Why does python behave so? (removing list items) In-Reply-To: References: Message-ID: Micha? Bentkowski pisze: > Why does python create a reference here, not just copy the variable? Because Python works like that -- it uses names and values idiom. If you change value, all names will be bound to the same changed value. >>>> j=range(0,6) >>>> k=j >>>> del j[0] >>>> j > [1, 2, 3, 4, 5] >>>> k > [1, 2, 3, 4, 5] > > Shouldn't k remain the same? No further comments on this. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From duncan.booth at invalid.invalid Mon Mar 31 14:15:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 18:15:22 GMT Subject: [OT] troll poll References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Daniel Fetchinson" writes: >> [ ] - Xah Lee >> [ ] - castironpi > > I've lost track but has it been established that they are not the same > person? > Has it actually been established that castironpi is actually a person? I thought it was probably a random sentence generator. From castironpi at gmail.com Sat Mar 8 13:03:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 10:03:02 -0800 (PST) Subject: Difference between 'function' and 'method' References: <6766529d-7f0e-4e9d-9498-1c295e71ac53@o77g2000hsf.googlegroups.com> Message-ID: <87b8b973-08cc-4659-8fd4-62244e27311d@p25g2000hsf.googlegroups.com> On Mar 7, 1:34?pm, castiro... at gmail.com wrote: > On Mar 7, 6:44?am, Sion Arrowsmith > wrote: > > > Gabriel Genellina wrote: > > >En Thu, 06 Mar 2008 23:46:43 -0200, escribi???: > > >> [ ... ] > > >You may look at the SimpleXMLRPCServer class and see how it implements ? > > >introspection. It's rather easy (and doesn't require metaclasses nor ? > > >decorators nor any other fancy stuff; I think it works the same since ? > > >Python 2.1). Apparently you're doing a similar thing, but using pickles ? > > >instead of xmlrpc. > > > It's not that difficult to graft pickles into SimpleXMLRPCServer -- > > I've done it, and if you're trying to sling large data structures > > over the connection it's a massive performance win (even with > > sgmlop in place to speed up XML parsing). > > ? ?her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump > > Yeah, but I'd be grafting a non-blocking RPC sequence too. > > -Instantiate- attributes of ISS upon instantiation. > > class C: > ? d= D > > c= C() > assert isinstance( c.d, D ) > assert c.d is c.d > > Which ones? Two options: instantiate all attributes, or ones with a certain property, such as name or superclass. class C: inst_d= D #actually gets bound to 'd', optionally class C: d= inst( D ) I think what I'm looking for is an attribute wrapper. class C: @inst d= D But the closest the syntax goes is: class C: class d( D ): pass (which takes us back to one of Steven's posts some days ago.) ( def f(x=None):/class C:/x= X/return C. ) and the d= inst( D ) solution.) You either need to assign something to assign something to its name, class C: d= X or declare it, but that only allows def and class statements (correct?). class C: attr d: D is ideal. From http Wed Mar 26 04:46:38 2008 From: http (Paul Rubin) Date: 26 Mar 2008 01:46:38 -0700 Subject: SoC project: Python-Haskell bridge - request for feedback References: Message-ID: <7xzlslvpn5.fsf@ruckus.brouhaha.com> A few thoughts. The envisioned Python-Haskell bridge would have two directions: 1) calling Haskell code from Python; 2) calling Python code from Haskell. The proposal spends more space on #1 but I think #1 is both more difficult and less interesting. By "Haskell" I presume you mean GHC. I think that the GHC runtime doesn't embed very well, despite the example on the Python wiki (http://wiki.python.org/moin/PythonVsHaskell near the bottom). This is especially if you want to use the concurrency stuff. The GHC runtime wants to trap the timer interrupt and do select based i/o among other things. And I'm not sure that wanting to call large Haskell components under a Python top-level is that compelling: why not write the top level in Haskell too? The idea of making the critical components statically typed for safety is less convincing if the top level is untyped. There is something to be said for porting some functional data structures to Python, but I think that's mostly limited to the simpler ones like Data.Map (which I've wanted several times). And I think this porting is most easily done by simply reimplementing those structures in a Python-friendly style using Python's C API. The type signatures (among other things) on the Haskell libraries for this stuff tend to be a little too weird for Python; for example, Data.Map.lookup runs in an arbitrary monad which controls the error handling for a missing key. The Python version should be like a dict, where you give it a key and a default value to return if the key is not found. Plus, do you really want Python pointers into Haskell data structures to be enrolled with both systems' garbage collectors? (Actually (sidetrack that I just thought of), a Cyclone API would be pretty useful for writing safe Python extensions. Cyclone is a type-safe C dialect, see cyclone.thelanguage.org ). The Haskell to Python direction sounds more useful, given Haskell's weirdness and difficulty. Python is easy to learn and well-packaged for embedding, so it's a natural extension language for Haskell applications. If you wrote a database in Haskell, you could let people write stored procedures in Python if they didn't want to deal with Haskell's learning curve. Haskell would call Python through its "safe" FFI (which runs the extension in a separate OS thread) and not have to worry much about the Python side doing IO or whatever. Of course this would also let Python call back into the Haskell system, perhaps passing Python values as Data.Dynamic, or else using something like COM interface specifications. Anyway I'm babbling now, I may think about this more later. From ron at example.com Thu Mar 27 01:03:22 2008 From: ron at example.com (Ron Eggler) Date: Thu, 27 Mar 2008 05:03:22 GMT Subject: last mouse movment or keyboard hit References: Message-ID: Gabriel Genellina wrote: >>> En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler >>> escribi?: >>> >>> >> I would like to get the time of the most recent human activity like a >>> >> cursor >>> >> movement or a key hit. >>> >> Does anyone know how I can get this back to start some action after >>> >> there >>> >> has been no activity for X minutes/seconds? > > En Wed, 26 Mar 2008 13:59:15 -0300, azrael > escribi?: > >> You can use wxPython. Take a look on the DemoFiles that you can >> download also from the site. I remember that there has been a demo of >> capturing mouse coordinates and also one example about capturing Which >> key has been pressed at which time. > > (Please don't top post) > Does wx catch all events in all other applications? > My understanding is that the OP wants a global detection, not restricted > to a single application. Exactly, I would like to have it global/system widely detected -- chEErs roN From python at bdurham.com Sun Mar 9 11:10:56 2008 From: python at bdurham.com (Malcolm Greene) Date: Sun, 09 Mar 2008 11:10:56 -0400 Subject: Converting a string to the most probable type In-Reply-To: <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> Message-ID: <1205075456.17754.1241388585@webmail.messagingengine.com> Pierre, > That's fine for people who write floats with a "." ; but others learn to enter them with "," I have also been looking for a similar Python conversion library. One of my requirements is that such a library must be locale aware (so it can make reasonable assumptions regarding locale properties like thousands separators, decimal points, etc) - either via a locale attribute or by examining the locale of the thread its running under. Malcolm From michael.wieher at gmail.com Wed Mar 5 10:58:24 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 5 Mar 2008 09:58:24 -0600 Subject: Fwd: OT: Failed saving throw In-Reply-To: References: Message-ID: build a tomb? ...or raid one? ---------- Forwarded message ---------- From: Aahz Date: 5 Mar 2008 07:36:37 -0800 Subject: OT: Failed saving throw To: python-list at python.org For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people think we should build a tomb in his honor. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From duvo at tiscali.it Sat Mar 8 13:35:01 2008 From: duvo at tiscali.it (duccio) Date: Sat, 08 Mar 2008 19:35:01 +0100 Subject: del class with recursive list Message-ID: Hello! Will someone have time to tell me why this code don't work as I expect? And what should I do to make the "del n" delete all the lower nodes? Thanks! class Node: def __init__(self): self.childs=[] def appendNode(self, n): self.childs.append(n) def __del__(self): print 'del', id(self) n = Node() for i in range(5): n.appendNode(Node()) for nodes in n.childs: nodes.appendNode(Node()) del n print '--------end--------' gives this: del 10965280 del 10965440 del 10965640 del 10965400 del 10965600 del 10965360 del 10965560 del 10965320 del 10965520 --------end-------- del 10965480 del 10965680 From bernard.chhun at gmail.com Thu Mar 6 23:37:41 2008 From: bernard.chhun at gmail.com (Bernard) Date: Thu, 6 Mar 2008 20:37:41 -0800 (PST) Subject: Looking for very light weight template library (not framework) References: Message-ID: Cheetah! Cheetah! Cheetah! On 6 mar, 20:56, "Malcolm Greene" wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated. > > Malcolm From Lie.1296 at gmail.com Sun Mar 9 08:28:27 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 05:28:27 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: On Mar 9, 6:57?pm, Bryan Olson wrote: > Lie wrote: > > [...]> Soft Exception is an exception that if is unhandled, pass silently as > > if nothing happened. > > [...] > > > Implementation: > > Simple implementation might be done by catching all exceptions at the > > highest level, then filtering which exceptions would be stopped (Soft > > Exception) and which exceptions will be reraised and terminate the > > program (Hard Exception). This is simple and can be easily implemented > > but is inefficient as that means all soft exceptions must bubble > > through its way to the top to find out if it is Soft or Hard. > > If I'm following what you want, that "simple implementation" does > not work. ?If a function, possibly deep in a call stack, raises a > soft exception that no caller above catches, what executes next? The highest possible code that could catch exceptions would have something like this: try: ## Everything is happening inside me except SoftException: pass > Correct me if I'm misunderstanding your idea: You want raising > an un-caught soft exception to be equivalent to a 'pass'; > execution continues as if the 'raise' never happened. > > Catching everything at a high level does nothing like that. The > exception causes execution to leave the function invoking the > raise statement, and abolishes the stack state from the point of > the raise to the point of the catch. The high-level mentioned here is outside our own code, it'll be inside Python's internal. When CPython (or any implementation of Python) sees that a particular exception is raised to a certain point, it'll check whether it is of type SoftException, and if it is, it'll return program state to the place where the exception is raised before. I don't know how Python's exception system works (as I tell you I know next to nothing about Python's internal, although I'm interested to know), so probably if there is any defect in the implementation schemes I mentioned, it is simply caused by my ignorance. > As Python exceptions currently work, "catching all exceptions > at the highest level" is either what Python already does, or > ill-defined nonsense. When an exception is uncaught, there is > no useful "highest level", other than the level at which the > program simply fails. Python *must* terminate execution upon > an unhanded exception, because the program defined no state > from which executions could correctly continue. That's where the difference between Soft Exceptions and Hard Exceptions lies. Soft Exception must be continued while Hard exceptions must terminate programs. Possibly this is impossible at the absolutely highest level, perhaps it should be done at the level that can guarantee > > A more through implementation would start from the raiser inspecting > > the execution stack and finding whether there are any try block above > > it, if no try block exist it pass silently and if one exist it will > > check whether it have a matching except clause. This also circumvents > > a problem that simple implementation have, as described below. > > The described problems do not include the "where should execution > resume" problem, which I think is central to the issue. I didn't mentioned it? I think it's obvious when I say: Execution should resume as if nothing happened, as if there is nothing raised, that means execution resumes at the point after the raise statement. If something was caught, execution isn't resumed and execution continues at the level of the handler (possibly we could also add a "resume" to explicitly resume the statement that was caught) > Correct me > if I've misunderstood: A "soft" exception is one that gets raised > only if some calling frame has arranged to catch it. That could be a way to implement it. And btw, that's a one-line- explanation that hits the right note (although from a different view I initially mentioned). > The if-exception-would-be-unhanded-then-pass logic strikes me as > interesting. It would be a huge change to Python, so I doubt it > will get traction here. ?Still, I'd say it's worth more > consideration and discussion. From sturlamolden at yahoo.no Sun Mar 30 14:02:32 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 30 Mar 2008 11:02:32 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <7aa6175f-cf7c-4006-b140-63bbbc8f1311@u10g2000prn.googlegroups.com> On 30 Mar, 17:16, iu2 wrote: > Due to Competitors... I don't want to expost the language I use Either your comepetitors will figure it out, or they don't care. Using Python can be a major competitive advance. If your competitors are smart enough to realise that, you are in trouble anyway. Most likely your competitors have managers who are technical retards (read: MBAs), who demand their engineers to use whichever technology is over hyped these days. You don't have to worry about those. From castironpi at gmail.com Thu Mar 27 04:02:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 01:02:36 -0700 (PDT) Subject: genetic algors in practical application References: <2242528c-764f-4aa6-a605-f2d05b25484e@u69g2000hse.googlegroups.com> Message-ID: <57267b84-e69a-47c8-9e6c-a501d52c17e8@b64g2000hsa.googlegroups.com> On Mar 26, 9:55?pm, castiro... at gmail.com wrote: > I want to go in to construction. ?However, 'I' means 'newsgroup' and > 'want to go' means 'is'. > > If you had an army of two-micron spiders, could we build something? > Use case is an American skyscraper. > > They have powerful tricks. ?Clearly they can withstand a force. ?These > can withstand more combined, greater-than-minimum. ?What is their > command set? > > Braid. ?Hoist. ?Vine power and waste. ?Charge, double-pump circuit. > Round-trip a dollar. ?I said round. ?(What's the square trip.) > > You do know that the brain has seven trillion atoms, right? ?Mass of > water. > > You know, combine 'muscle fiber' with 'inhibition, excitation' and > 'motor neuron circuit', and you might be on to something, and you > might be right. ?Here's free from Neuro. ?'Each motor neuron synapses > with multiple muscle fibers. .. Cross section through the muscle shows > the distribution of muscle fibers (red dots) contacted by the motor > neuron.' ?Power-- Tools. ?Note that 'synapse' verb. ?Written English > folks. ?'myelin debris' too. > > Is your concern the actual construction of the nanospiders > (interesting side note), or programming it? ?Get a team of programmers > too. ?Who asked for the 'Python d.j. console'? ?Did -uuu- put that on > line. I'd like to destruct a little English: pose, L., from pause. compose, depose, (de-com-pose?), dispose, expose, impose, opose, prepose, propose, repose, transpose, suppose. Stack a structure is a really useful operation. If structures are all guaranteed to compose with one another (is this generators?), you can pop several off, add yours, and push several on. But, where functions are structures, could leave several information. "Sometimes I call my generator twice." I'm a GA, q.e.d. Do I correctly read, 'decline to use send and return of yield'? (Can't be right; it's in there; what do you use it?) What are you guys sending generators? I think a successful machine takes-impressions the environment, and recomposes it: digest, regest, repose. Three cells interface, tower- of-hanoi each other, and on their way. From ds-python-list at sidorof.com Sun Mar 30 18:15:44 2008 From: ds-python-list at sidorof.com (DS) Date: Sun, 30 Mar 2008 15:15:44 -0700 Subject: Licensing In-Reply-To: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> References: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> Message-ID: <47F01110.4000808@sidorof.com> Paul Boddie wrote: > On 29 Mar, 20:24, DS wrote: > >> I'm pretty sure this is the wrong place to ask, but I'm hoping someone >> will point me in the right direction. >> >> I'm getting ready to publish a first open-source project written in >> python. I am planning to use GPLas the license. However, in my code, >> there is a function that I like from Python Cookbook. I would like to >> use it, although I could certainly write a less elegant version that >> would do the same thing. >> > > Note that the Python Cookbook says this about licensing: "Except where > otherwise noted, recipes in the Python Cookbook are published under > the Python license." The link is incorrect, but I presume they mean > this licence: > > http://www.python.org/psf/license/ > > It's generally not recommended to use this licence for anything other > than Python because it mentions the need to reproduce the Python > copyright statement in derived works, which would be nonsense for > anything which isn't the Python distribution. However, one can infer > that the copyright notice specific to the software concerned should be > reproduced, and this is what the original CWI licence says. > > Of course, if a different licence is mentioned on the specific recipe > you're using, you have to observe the terms mentioned in that licence > instead. > > >> So, my options appear to be: >> 1. Don't use it. >> 2. Use it with no comment -- that doesn't seem right. >> 3. Use it with remarks in the code that acknowledge the source. >> 4. Provide a separate licensing page for that function >> along with the GPL for my code. >> >> What is the appropriate course of action here? I'm thinking #3 is >> probably ok. How do others deal with this in an honorable way? In the >> book, it appears that they are saying they don't really care unless >> there is some massive use. >> > > You just need to do what's necessary to satisfy the licence applied to > the code you're using. If that's the Python licence, I would imagine > that reproducing the copyright statement and licence details would be > sufficient, even if your own work is GPL-licensed. > > What I've done when I've released work which incorporates other work > (itself available under a permissive licence) is to include the > copyright statements and the licence text for that other work, but > I've made it clear in the licensing information that the derived work > (my code incorporating the other code) is available under the specific > licence I've chosen, noting that the other work was made available > under a different licence. > > So I suppose that #4 is the closest, but you should be able to assert > that the entire work is GPL-licensed unless the recipe isn't licensed > in a GPL-compatible way, which would open up a range of other issues > that you hopefully won't have to deal with. ;-) > > Paul > > P.S. This isn't anything close to legal advice, so please take other > opinions into account. ;-) > Thanks for taking the time to write. I was also wondering about what ramifications there are from mixing code from other licenses. So, I guess if I was going to do it, I'd have a second license file for this specific function with the license for it. I definitely don't want to be in a situation where credit for someone else's work is not adequately documented. It has happened to me, I know how I felt about it at the time. At this point, I'm thinking that it is not worth messing with. What I am going to do is write a separate function to accomplish the same thing. It's only a few lines long. Of course, having seen the other code I'm forever tainted... There is something a little humorous about reading through the Python Cookbook. You have submissions from all these incredibly smart people with little gems of functions. But, if you actually use them, it's kind of a hassle. On the other hand, I'm glad the book exists, and my memory of the specific details of a function fade over time, but it has/does give my a better understanding in general of how do things. Thanks again. From DoxaLogos at gmail.com Thu Mar 20 11:51:13 2008 From: DoxaLogos at gmail.com (DoxaLogos) Date: Thu, 20 Mar 2008 08:51:13 -0700 (PDT) Subject: wxFormBuilder References: Message-ID: <90b80600-679c-4bb5-9f00-ee083f7ffdff@e60g2000hsh.googlegroups.com> On Mar 20, 8:41 am, sturlamolden wrote: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/http://wiki.wxpython.org/index.cgi/XRCTutorial I've stumbled across it myself and have found it superior so far over the others. I just wish it could also crank out wxPython code. I'm still hoping one day for a form designer closer to Visual Studio's form designer in ease of use area. FarPy GUIE has the right idea, but not near enough widget support. And, I'm not good enough at wxPython yet to be able help either project. From siona at chiark.greenend.org.uk Tue Mar 11 11:21:55 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Mar 2008 15:21:55 +0000 (GMT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: Stefan Behnel wrote: >Just to make this sound a bit less like FUD: my last experience with wxPython >dates back a couple of years (2004/5?), but back then, we used BoaConstructor >in a project, which crashed a bit too often to do real work with it - and with >crashing I mean crashing Python, not just showing us its blank traceback. So >this was definitely a problem either in wxWindows or in wxPython. I spent a couple of years maintaining and developing a series of commercial wxPython-based applications (up until about 18 months ago when I changed job), and I would happily describe wxPython itself as stable enough for production code. The biggest problem I had with it was its failure to be anywhere near as transparently cross-platform as one might be lead to expect. And before you blame wx* for crashes: what platform was this on? Because my experience was that wx on GTK was significantly more prone to glitches than on Windows (through to wxglade being unusably crashy) -- if the underlying toolkit has problems, that's going to be reflected in wx. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From castironpi at gmail.com Sun Mar 9 19:42:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 16:42:27 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: <2b52103a-dfc1-42ce-b572-6a8fb9890e4b@2g2000hsn.googlegroups.com> > > ?os.exec*() will close the current program. > > On *nix, you can use os.fork(). ?According tohttp://effbot.org/librarybook/os.htm, you can use Do you mean, and block for the process to terminate? Or do you mean, do something else in the meantime, perhaps for a certain amount (of meantime)? [Enter event loops. Exeunt.] P.S. What do you do if you think of a comeback for something from a week ago on the newsgroup? P.P.S. Why are you thinking of comebacks on a newsgroup besides alt.flame? P.P.P.S. Anyone read alt.tasteless? From deets at nospam.web.de Sat Mar 1 14:43:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 20:43:34 +0100 Subject: pySQLite Insert speed In-Reply-To: References: Message-ID: <62tpv6F24tml7U1@mid.uni-berlin.de> mdboldin at gmail.com schrieb: > I hav read on this forum that SQL coding (A) below is preferred over > (B), but I find (B) is much faster (20-40% faster) > > (A) > > sqla= 'INSERT INTO DTABLE1 VALUES (%d, %d, %d, %f)' % values > curs.execute(sqla) > > (B) > pf= '?, ?, ?, ?' > sqlxb= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > curs.execute( sqlxb, values ) > > Any intution on why (A) is slower? You most certainly have not found that A is the preferred over B - the opposite is true. Using A will make you vulnerable against SQL-injection-attacks. B OTOH will ensure that the parameters are properly escaped or otherwise dealt with. Regarding the intuition - that depends on what actually happens inside B. If B works in a way that it - converts arguments to strings - escapes these where necessary - builts one SQL-statement out of it - excutes the SQL then B is slower than A because A is just string-interpolation, whereas B is sanitizing + string-interpolation. So it must be slower. But a "sane" DB will instead directly use the SQL passed in B, and transmit the parameter as binary into the backend, resulting in more compact representation + lesser or now marshalling overhead plus possible query parsing overhead reduction due to cached execution plans. Which could explain B being more performant. Diez From rockxuan at gmail.com Tue Mar 18 03:40:15 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:40:15 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <4cf1ae65-953b-4a94-8271-47cf0739bae7@s37g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From mankyd at gmail.com Mon Mar 17 21:36:10 2008 From: mankyd at gmail.com (dave) Date: Mon, 17 Mar 2008 18:36:10 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI Message-ID: Hi All. I've been formulating in my head a simple image editor. I actually started prototyping is some time ago in Java, but am liking Python more and more. My editor will be nowhere near the level of Gimp/ Photoshop, but I do need fast pixel level control and display. For instance, that means no automatic anti-aliasing and that I will be implementing my own line drawing algorithms. I've got the high level architectual aspects of my program down, but am stuck on what graphics API to use. I want a canvas area of adjustable size which users can draw on with as little lag as possible. The canvas area will be composed of layers (i.e. I require an alpha channel) and I need to be able to zoom in and out of it (zoom levels will be at fixed intervals, so this can be simulated if need be.) I started looking at PyGame but realize that I need to integrate a GUI into the whole thing (or integrate the image into the GUI rather) and I didn't see a straightforward way to do that. Of course, I don't even know if PyGame is the right API for the job anyways :P Any thoughts or ideas that could help me get started? Thanks! From dickinsm at gmail.com Thu Mar 13 17:12:09 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 13 Mar 2008 14:12:09 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: <70538854-b63e-4387-9e14-db3b9c211abe@e39g2000hsf.googlegroups.com> On Mar 13, 5:10?pm, Mark Dickinson wrote: > (1, '14') represents 14 should be -14, of course. From jerry.fleming at saybot.com Thu Mar 27 03:41:18 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Thu, 27 Mar 2008 15:41:18 +0800 Subject: do 'os.path' include 'os' for us? Message-ID: Hi, I wrote a python script to list files in a directory but somehow did it wrongly by importing os.path instead of os. To my astonishment, it works just as charm: #!/usr/bin/python import os.path for file in os.listdir('/root/'): print file I was wondering why? os.path doesn't contain listdir, why there is no complaint like 'os: unknown name'? Does this mean, instead of importing os, we can import os.path? Thanks. From mwilson at the-wire.com Tue Mar 18 13:20:56 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 18 Mar 2008 13:20:56 -0400 Subject: globals() using For Loop against Generator References: <599451f4-7687-4d02-b546-a7fbb0f33c8d@h11g2000prf.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > if __name__ == '__main__': > > print "Globals (For Loop):" > try: > for i in globals(): > print "\t%s" % i > except RuntimeError: > print "Only some globals() printed\n" > else: > print "All globals() printed\n" > > print "Globals (Generator):" > try: > print "\n".join("\t%s" % i for i in globals()) > except RuntimeError: > print "Only some globals() printed\n" > else: > print "All globals() printed\n" > >>>> Globals (For Loop): >>>> __builtins__ >>>> Only some globals() printed >>>> >>>> Globals (Generator): >>>> __builtins__ >>>> __name__ >>>> __file__ >>>> i >>>> __doc__ >>>> All globals() printed >>>> > > Why is it with a generator I get everything out but with a for loop I > don't? I know that globals is not read-only but I would of expected > the same behaviour from both... Run the for loop in the interpreter, without catching exceptions. You get __builtins__ Traceback (most recent call last): File "", line 1, in RuntimeError: dictionary changed size during iteration Then `print globals()` shows that i has been added to the global namespace. If you run the for loop a second time, after i exists, the loop runs fine. Apparently, generator comprehensions have been optimized so that they don't expose their working variables. The generator comprehension won't add i to the global namespace, so all is well. Mel. From michael.wieher at gmail.com Wed Mar 12 16:29:35 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 12 Mar 2008 15:29:35 -0500 Subject: string / split method on ASCII code? Message-ID: Hey all, I have these annoying textilfes that are delimited by the ASCII char for << (only its a single character) and >> (again a single character) Their codes are 174 and 175, respectively. My datafiles are in the moronic form X<>Z I need to split on those freaking characters. Any tips on how to make split work with these things? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kveretennicov at gmail.com Sun Mar 30 11:28:33 2008 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sun, 30 Mar 2008 18:28:33 +0300 Subject: Create executable from executable with py2exe In-Reply-To: References: Message-ID: <4660fe300803300828r4ddc88a3mbe9270e157b2d7b6@mail.gmail.com> On Sat, Mar 29, 2008 at 3:23 PM, wrote: > Hello, > > Is there any example how can I create executable ... with py2exe > Check out PyBuilder's source code (http://pybuilder.sourceforge.net/). -- kv -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Fri Mar 14 15:19:18 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 14 Mar 2008 12:19:18 -0700 (PDT) Subject: Handling global variables (Newbie) References: Message-ID: <613c51a0-d928-46b1-a04f-d0bc9fdcf453@a70g2000hsh.googlegroups.com> On Mar 13, 4:25 am, "David S" wrote: > Hi, > > I have an error occurring at > self.build_root = os.path.abspath(os.path.split(__file__)[0]) > > The error states 'NameError: global name '__file__' is not defined' > > In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get > defined? > Do you perhaps mean '__name__'? From michael.wieher at gmail.com Fri Mar 14 10:27:52 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 14 Mar 2008 09:27:52 -0500 Subject: request for Details about Dictionaries in Python In-Reply-To: <47DA8833.9020205@fmed.uba.ar> References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> Message-ID: 2008/3/14, Gerardo Herzig : > > Saideep A V S wrote: > > >Hello Sir, > > > > Thank You a ton. I was looking for this function. As far what I've > >understood from the "Shelve" module is that, there would be no memory > >wastage and the whole transactions would be done from and to the file we > >specify. Am I right?. > > > > My actual task is to build a basic dictionary for two languages and > store > >word and its meaning in another language in a file and must be able to > >access it through on-disk Hash tables. as these would be saving memory > space > >for a huge data. > > > >so, I hope shelve is the right one, I am searching for., I shall try out > >with the function. > > > > > >Thank You once again. > > > >Cheers, > >Saideep > > > > > > > Plz remember allways reply to the python group also. They are many many > many ones to know more than i do! > Well, i dont quite think that it would be "no memory wastage", since > when you read/write from disk, there is memory involved in the process. > > I *really* believe that, when data goes huge, a *real* database (like > postgres, and others) has to come and play the game. > > Hope that helps > > Gerardo > > > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm not sure if a well-written file/seek/read algorithm is faster than a relational database... sure a database can store relations and triggers and all that, but if he's just doing a lookup for static data, then I'm thinking disk IO is faster for him? not sure -------------- next part -------------- An HTML attachment was scrubbed... URL: From josef.pktd at gmail.com Sun Mar 16 13:00:12 2008 From: josef.pktd at gmail.com (joep) Date: Sun, 16 Mar 2008 10:00:12 -0700 (PDT) Subject: Spaces in path name References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> Message-ID: <708a66a7-da8f-4d44-824d-8a25203030f7@n58g2000hsf.googlegroups.com> One more try (using popen instead of call is not necessary for these cases, but I want to see the behavior of popen): shell=True and executable and at least one argument with spaces does not work: --------------------------------------------------------------------------------------------------------------------- p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \Copy of cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out3.txt"], shell=True, stdout=subprocess.PIPE) causes: 'C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin\Copy' is not recognized as an int ernal or external command, operable program or batch file. the following all work: ================ without shell=True, and executable and at least one argument with spaces ----------------------------------------------------------------------------------------------------------- p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \Copy of cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out4.txt"], stdout=subprocess.PIPE) with shell=True, and executable without spaces, even if two arguments with spaces ------------------------------------------------------------------------------------------------------------------------ p = subprocess.Popen(["copy", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out2.txt"], shell=True, stdout=subprocess.PIPE) with shell=True, and executable without spaces, even if two arguments with spaces ------------------------------------------------------------------------------------------------------------------------ but here shell=True is not necessary p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out5.txt"], shell=True, stdout=subprocess.PIPE) without shell=True, and executable and at least one arguments with spaces ------------------------------------------------------------------------------------------------------------- p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \Copy of cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out4.txt"], stdout=subprocess.PIPE) My conclusions: ============ Assuming shell=True is only required for build-in shell commands, non of which has spaces. There is no problem, if you know when *not* to use shell=True: * More than two arguments with spaces are never problem, as long as the executable does not have spaces * If shell=True is required, then the executable is a build-in shell command, which does not contain spaces, and, therefore, has no problems * If you use a non-build in executable, then don't use shell=True. This works correctly even if the executable and at least one additional argument have spaces. It took a lot of time to figure this out, but now at least I know, how to construct the call to subprocess.Popen, so that it works in the cases I used it so far. Josef From duncan.booth at invalid.invalid Sat Mar 29 14:19:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Mar 2008 18:19:36 GMT Subject: Problem with sqlite References: Message-ID: aiwarrior wrote: > When i execute this the database doesn't get filled with anything and > the program stays running in memory for ever. That's odd, when I execute the code you posted I just get "NameError: global name 'sqlite3' is not defined". You should always try to post the complete actual code you are using, not just some random part of it. > The print statement is just a Unicode string that would get to the > database if i stated it in the add_entry function as a constant > string. It's a really weird problem that i dont seem to understand why > it's working out this way. > Are you absolutely certain of that? If you use print to try to debug the value of an object you should usually use repr: print repr(audio['album']) What MP3 library are you using? You have forced a commit after every insert. This slows down sqlite A LOT. I get about 400 insertions each minute with your code (just inserting fixed strings) but if I remove the conn.isolation_level assignment and add a single commit at the end I get in excessive of 20000 per second. Are you sure you just didn't wait long enough? From hexusnexus at gmail.com Mon Mar 31 21:16:33 2008 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Mon, 31 Mar 2008 18:16:33 -0700 (PDT) Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> <7b94bd75-f3ef-4e5c-9939-c431947e1ae1@l42g2000hsc.googlegroups.com> Message-ID: <1871e241-48b1-474b-9c0b-76443545a172@e23g2000prf.googlegroups.com> On Mar 31, 4:04 pm, Rick Dooling wrote: > On Mar 31, 2:39 pm, hexusne... at gmail.com wrote: > > > How do I receive input from the command line in Python? > > As long as we are all guessing, do you perhaps mean raw_input? > > my_name = raw_input("What is your name? ") > What is your name? Rick >>> my_name > > 'Rick' Yeah, sorry for being vague. Thanks. From zubeido at yahoo.com.br Wed Mar 12 09:59:59 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Wed, 12 Mar 2008 06:59:59 -0700 (PDT) Subject: Mutagen File Problem Message-ID: <81d8d48f-5496-4ca6-a525-c7b927436d4d@d62g2000hsf.googlegroups.com> Hi i'm having a IO error saying a file does not exist even though i perform a isFile() check. Can you help me out figuring what is wrong? Thanks in advance from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 for root, dirs, files in os.walk('''C:\\Documents and Settings\\pneves\ \Music\\''', topdown=False): for name in files: joined = os.path.join(root, name) if (name[-3:] == 'mp3' ): audio = MP3(joined, ID3=EasyID3) if not audio.has_key('album') and os.path.isfile(joined): print os.path.join(root, name) I get an error as following: IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\pneves\\Music\\Naked Music - Miguel Migs - Colorful You\ \Miguel Migs - Colorful you - Full album\\Miguel Migs - Colorful you - Cd 2 -Mixed and mastered by J. Mark Andrus\\7 - Miguel Migs feat. Lisa Shaw - You Bring Me Up (Main Vocal Mix).mp3' From deets at nospam.web.de Sat Mar 22 09:32:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 14:32:34 +0100 Subject: Prototype OO In-Reply-To: <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> Message-ID: <64kg3pF2avnseU1@mid.uni-berlin.de> John Machin schrieb: > On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: > >> [1] Just one example:http://docs.mootools.net/Class/Class.js > > Mootools being something a coworker might use? > I don't understand the question. Diez From danb_83 at yahoo.com Wed Mar 26 18:23:31 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 26 Mar 2008 15:23:31 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <808dff98-c2a5-4697-b805-9482c2f11b8f@s12g2000prg.googlegroups.com> On Mar 26, 5:12 pm, Thomas Dybdahl Ahle wrote: > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: > > Why does python create a reference here, not just copy the variable? > > Python, like most other oo languages, will always make references for =, > unless you work on native types (numbers and strings). The = operator behaves exactly the same way for mutable and immutable types. From exxfile at hotmail.com Mon Mar 24 15:13:04 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 12:13:04 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> Message-ID: <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> > > > i ?have ?come across my first exeption using randrange . The exeption > > is " no such ?attribute " in ?module random > > > platform ?is xp ?home ?and the python ?build is activestate 2.5 > > Welcome aboard! > > There's definitely a randrange function in the random module, so > something else must be wrong. To get the most out of this list and > minimize wasted bandwidth, the most effective way usually consists of > copying and pasting: > 1. The offending code (or just the relevant part if it's too big). > 2. The full traceback of the raised exception. > > Regards, > George Hwere is the complete traceback ! >>> The word is: index Traceback (most recent call last): File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger \__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger \debugger.py", line 631, in run exec cmd in globals, locals File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, in import random File "F:\Documents and Settings\Mark\My Documents\random.py", line 13, in distributions on the real line: AttributeError: 'module' object has no attribute 'randrange' >>> Why would it say it can't find the function ? Mark From kay.schluehr at gmx.net Sun Mar 9 00:05:50 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 8 Mar 2008 21:05:50 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: <852f558f-c0e7-4bdd-afae-3870fe90c8e0@34g2000hsz.googlegroups.com> On 9 Mrz., 04:51, Lie wrote: > A more through implementation would start from the raiser inspecting > the execution stack and finding whether there are any try block above > it, if no try block exist it pass silently and if one exist it will > check whether it have a matching except clause. This also circumvents > a problem that simple implementation have, as described below. This will not be easy in particular in the presence of inheritance and dynamism. There is no way to statically decide whether an exception BException has the type AException and will be caught by the except clause in try: BLOCK except AException, e: print "SoftException %s caught"%e A feasible solution was to invert the try...except statement and creating a continuation. catch AException, a: print "SoftException A: %s"%a catch BException , b: print "SoftException B: %s"%b ... in: BLOCK Here each SoftException is raised initially when a catch clause is entered and a continuation is created that returns to the catch block of the raised SoftException if required. When a SoftException is raised within BLOCK a lookup will be made and if a corresponding SoftException was found that was raised by a catch-clause the current control flow will be suspended and the continuation is called. From michael.wieher at gmail.com Fri Mar 7 16:38:14 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 15:38:14 -0600 Subject: I cannot evaluate this statement... In-Reply-To: <13t3cms4fn6318e@corp.supernews.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> <13t3cms4fn6318e@corp.supernews.com> Message-ID: The parentheses are there for a reason 2008/3/7, Steven D'Aprano : > > On Fri, 07 Mar 2008 12:38:11 -0800, waltbrad wrote: > > > The script comes from Mark Lutz's Programming Python. It is the second > > line of a script that will launch a python program on any platform. > > > > import os, sys > > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > > > That makes sense. Because the first condition is true and 'python.exe' > > is true. So the next comparison is 'python.exe' or 'python' Well, > > python.exe is true. So that value is returned to pyfile. > > > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > > == 'win' as false. So, the next comparison should be 'False' or > > 'python' -- This is because 'and' returns the first false value. But, > > again, on linux pyfile evaluates to python.exe > > Not on my Linux box. > > > >>> import os, sys > >>> sys.platform > 'linux2' > >>> (sys.platform[:3] == 'win' and 'python.exe') or 'python' > 'python' > > > > > Where am I going wrong. And when will this statment make pyfile > > evaluate to 'python' ? > > When the first three letters of sys.platform aren't 'win'. > > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.pulver at gmail.com Fri Mar 14 18:37:59 2008 From: alex.pulver at gmail.com (Alex) Date: Fri, 14 Mar 2008 15:37:59 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> Message-ID: <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> On Mar 13, 6:21 pm, Carl Banks wrote: > On Mar 13, 7:02 am, Bruno Desthuilliers > > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > Alex a ?crit : > > (sni) > > > > First of all thanks all for answering! > > > > I have some environment check and setup in the beginning of the code. > > > I would like to move it to the end of the script. > > > Why ? (if I may ask...) > Sure, because of a readability (similar to function declarations in C). > > > But I want it to > > > execute first, so the script will exit if the environment is not > > > configured properly. > > > If you want some code to execute first when the script/module is loaded, > > then keep this code where it belongs : at the beginning of the script. > > I concur with Bruno's recommendation: stuff you want to do first > should come first in the script. Things like BEGIN blocks hurt > readability because you can't identify where execution begins without > reading the whole file. > > Having said that, one thing that often happens in Python scripts is > that all the functions are defined first, then the script logic > follows. So you could put the meat of your script in a function, then > the "BEGIN" stuff after that functions: > > def run_script(): > # > # script contained in this long function > # > > # Then test preconditions here... > if os.environ["HELLO"] != "WORLD": > sys.exit(2) > > # Then call the run_script functions > run_script() > > But having said THAT, I don't recommend you do that with > preconditions. If the script has a quick early exit scenario, you > really ought to put that near the top, before the function > definitions, to clearly show to a human reader what is necessary to > run the script. > > Carl Banks Hi, Maybe i was a little bit unclear... I meant that i wanted to do something like this: #!usr/bin/env python check_env() from subprocess import * class MyClass: # Class definition def check_env(): # Code if __name__ == "__main__": # Script logic The thing is, as i saw, that Python doesn't recognize the "check_env()" function before it reaches the "def" statement. I need the check to be done before the subprocess import, because our customers use different Python versions, some of them do not have subprocess module. So i want to exit if i see that Python version being used doesn't have that module. The solution to that problem with what you suggested could be wrapping the subprocess import with function, am i correct? From john106henry at hotmail.com Mon Mar 31 13:05:01 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 10:05:01 -0700 (PDT) Subject: Of qooxdoo, qwt, and Python Message-ID: <28f7384f-b8d1-430d-9e0d-389ebae7eefd@e10g2000prf.googlegroups.com> I was searching for a way to redevelop a desktop Pythoncard based program into a web-application. I understand what need to be done for all of the non-GUI code. For the GUI capabilities, I stumbled across a package call qooxdoo (http://qooxdoo.org/). It appears to provide the GUI capabilities I need. Then I saw that there is qwt - which allows you to write qooxdoo code in pure Java. Since I don't know Java (or don't want to know), is there a similar path I can take using Python? Regards, From cokofreedom at gmail.com Mon Mar 10 12:19:11 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 10 Mar 2008 09:19:11 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> Message-ID: <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> The trick in the case of when you do not want to guess, or the choices grow too much, is to ask the user to tell you in what format they want it and format according to their wishes. Neatly avoids too much guessing and isn't much extra to add. From toolmaster at 163.com Sun Mar 16 23:54:01 2008 From: toolmaster at 163.com (WaterWalk) Date: Sun, 16 Mar 2008 20:54:01 -0700 (PDT) Subject: About reading Python code Message-ID: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Hello. I wonder what's the effective way of figuring out how a piece of python code works. With C I often find it very useful to be able to run the code in step mode and set breakpoints in a debugger so I can watch how the it executes, how the data change and how the code jumps from one function to another. But with Python, the debugger is a little primitive. The default IDLE doesn't even allow me to set a breakpoint. When the code is long, I am often lost in it. So I'm curious how to read code effectively. I agree that python code is clear, but when it becomes long, reading it can still be a hard work. From sjmachin at lexicon.net Thu Mar 20 17:04:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Mar 2008 14:04:51 -0700 (PDT) Subject: Is this valid ? References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> Message-ID: On Mar 21, 1:09 am, Rolf van de Krol wrote: > John Machin wrote: > > Of course. You can chain comparisons as much as you like and is > > (semi-)sensible, e.g. > > Hmm, 'of course' is not the correct word for it. 'Of course' was short for: Given alternative hypotheses H0 = "Python feature" and H1 = "bug in Python compiler", one's instinct would be go with H0 if a snap decision were required without time to refer to the docs. > Although the Stef > Mientki would probably be able to find it in the documentation it is not > as simple as you might think. > Most languages interpret a == b == 2 as (a == b) == 2, or throw an error > because this syntax is not valid. Indeed, some languages do ludicrous things with precedence of relational operators. A compiler when faced with something like: a == b and c == d has at least two choices: (1) (a == b) and (c == d) # seems rather useful (2) (a == (b and c)) == d which doesn't seem very useful at all. Pascal makes choice (2), which is valid syntax only if b and c are booleans and if comparisons of booleans are allowed (and IIRC Pascal didn't allow this). > The fact that python understand the > obvious meaning of this code, is quite unique to Python, as far as I know. Indeed, Python isn't "some/most languages", which is why we're here. From geert at nznl.com Sat Mar 15 14:19:22 2008 From: geert at nznl.com (geert) Date: Sat, 15 Mar 2008 11:19:22 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Message-ID: <72659e53-bd22-4c58-b579-bdbcaf8c5fed@s19g2000prg.googlegroups.com> On Mar 14, 11:49?am, "Robert Rawlins" wrote: > Geert, > > I've not seen this issue myself, however, you might get a little more luck > asking over on theMySQLdbmailing list as this seems to be more an issue > with the db than your python code. It might be worth posting your question > there too as it'll heighten your chances of finding someone who knowsMySQLdbinside out. > > http://mail.python.org/mailman/listinfo/db-sig > > Cheers, > > Robert > > -----Original Message----- > From: python-list-bounces+robert.rawlins=thinkbluemedia.co... at python.org > > [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co... at python.org] > On Behalf Of geert > Sent: 14 March 2008 10:36 > To: python-l... at python.org > Subject: Huge problem gettngMySQLdbto work on my mac mini running Macosx > 10.5 Leopard > > Hi all, > > I have a mac mini running maocosx 10.5 leopard I want to deploy a > django project on. My backend is MySQL, and I have it running as a 64- > bit app. Of course, apache2 is also running as 64-bit. > > MySQLdbinstalls with the usual warnings after applying the various > patches I found here and there. These patches consist of altering > _mysql.c and site.cfg. > > Basically, my problem boils down to this: > > ? File "", line 1, in > ? File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line > 19, in > ? File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in > > ? File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 6, in > __bootstrap__ > ImportError: dynamic module does not define init function (init_mysql) > > Has anyone solved this? I been hunting around for 2 weeks now, and my > deadline is looming grimly on the horizon :) > > Geert > > --http://mail.python.org/mailman/listinfo/python-list Thanks, Robert. I'm on the MySQLdb list, and am working on a solution. And I've subscribed to the list you gave. Geert From furkankuru at gmail.com Tue Mar 25 08:55:03 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:55:03 +0200 Subject: My python interpreter became mad ! In-Reply-To: References: Message-ID: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> Most probably X-Spam added itself to your path. you should look at your PATH and PYTHONPATH environment variables. On Tue, Mar 25, 2008 at 1:40 PM, John Machin wrote: > On Mar 25, 10:05 pm, Benjamin Watine wrote: > > Yes, my python interpreter seems to became mad ; or may be it's me ! :) > > > > I'm trying to use re module to match text with regular expression. In a > > first time, all works right. But since yesterday, I have a very strange > > behaviour : > > > > $ python2.4 > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import re > > X-Spam-Flag: YES > > X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on > w3hosting.org > > X-Spam-Level: ********************** > > X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, > > MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, > > > > RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, > > > > URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, > > URIBL_WS_SURBL autolearn=failed version=3.1.7-deb > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/etc/postfix/re.py", line 19, in ? > > m = re.match('(Spam)', mail) > > AttributeError: 'module' object has no attribute 'match' > > >>> > > > > What's the hell ?? I'm just importing the re module. > > No you're not importing *the* re module. You're importing *an* re > module, the first one that is found. In this case: your own re.py. > Rename it. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Mar 20 05:52:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Mar 2008 10:52:58 +0100 Subject: Script Request... References: <64ccfbF2bbfckU1@mid.uni-berlin.de> Message-ID: <64eqg5Fuih70U1@mid.uni-berlin.de> some one wrote: > Thanks Diez, I found some docs and examples on urllib2. Now how do i > search the string I get from urllib2, lets say I put it in "myURL", How > do I search for only Numbers and ".'s" in the "#.#.#.#" pattern. That > is all I am interested in with all the data retrieved. Just the IP > Address from amongst a bunch of data that I have no use of currently. > > I would I write a pattern matching function to extract only the IP > address from "myURL"? Pattern-matching can be done using regular expressions, they are available in the module "re". Diez From deets at nospam.web.de Sun Mar 9 09:21:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 14:21:43 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: Message-ID: <63i6j9F2793buU1@mid.uni-berlin.de> Lie schrieb: > I'm asking about people in c.l.py's opinion about a _probably_ very > Pythonic way of doing something if such features is implemented. It is > to be known that I'm not a Python expert and actually relatively new > to Python programming, so probably I'm just not thinking pythonic > enough yet or this feature might already exist somewhere in a > different name. > Anyway, I'm just asking for opinions, tell me problems I haven't > foreseen, or whether such things would be hard to implement, or > whether you think the idea is great or plain bad (and why). > > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. For example, if a variable turns into NoneType, > it'll raise Soft Exception that it have become NoneException, > programmers that wants to handle it can handle it with a try...except > block while programmers that doesn't care about it (or know it won't > be a problem to his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in > a way that Hard Exception must be handled at all cost or the program > will be terminated while Soft Exception allow programmers not to > handle it if they don't want to. Is this soft-exception implemented anywhere, so that one can see what experiences and best practices have evolved around using it? Diez From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Mar 3 12:31:55 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 03 Mar 2008 18:31:55 +0100 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Message-ID: <632r0bF25q334U1@mid.individual.net> blaine wrote: > So my question is this - what is the easiest way to interface to > this "serial" device? > > I don't imagine a straight read() and write() command to > /dev/ttyusb0 is the most efficient (if it even works) It doesn't only work, it's the preferred way (if you don't use advanced wrappers like pyserial). For the basics see http://www.easysw.com/~mike/serial/serial.html > especially since we would need to set a baud rate. What is the relationship between read/write, the baud rate, and efficiency? The serial port is configured using POSIX terminal interface (termios). Regards, Bj?rn -- BOFH excuse #89: Electromagnetic energy loss From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Mar 31 07:30:55 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 13:30:55 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> <65anbqF2fg18bU1@mid.individual.net> <87r6drjss4.fsf@physik.rwth-aachen.de> Message-ID: <65c0bfF2ffipiU1@mid.individual.net> Torsten Bronger wrote: > Doesn't KNode support UTF-8? Well, it should, but automatic encoding detection doesn't always seem to work (or does it even have one?). I'm looking for a different (faster) newsreader anyway. > Who wants to minimize the number of keypresses? We're not Perl > after all. ;-) Sure, but I also don't want to enter fancy unicode operators. I'm using Python on some computers that even don't support unicode. > However, I'm quite sure that when Unicode has arrived almost > everywhere, some languages will start considering such characters > in their core syntax. This should be the time when there are widespread quasi-standardised input methods for those characters. Regards, Bj?rn -- BOFH excuse #154: You can tune a file system, but you can't tune a fish (from most tunefs man pages) From barry at alltc.com Sun Mar 16 11:20:25 2008 From: barry at alltc.com (Barry Hawkins) Date: Sun, 16 Mar 2008 08:20:25 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 9:18?am, a... at pythoncraft.com (Aahz) wrote: > In article <5bd37c10-af5d-4254-8799-49c762673... at n58g2000hsf.googlegroups.com>, > Bruce Eckel ? wrote: > > >If the following seems unnecessarily harsh, it was even more harsh for > >me to discover that the time and money I had spent to get to my > >favorite conference had been sold to vendors, presenting me as a > >captive audience they could pitch to. > > Ouch. ?I'm probably one of the few organizers currently paying much > attention to c.l.py -- because I'm also one of the few who's not at > PyCon. ?We debated this extensively before going ahead, and we decided > it was worth an experiment. ?If your feedback is at all representative, > this won't happen again, I assure you. [...] > >I believe that this year's Pycon organizers suffered from inexperience > >and naivete, because they didn't know that some vendors will ask for > >anything just to see how far they can push it. > > Actually, it was our idea to offer something in return for the > sponsorship. [...] Ashz, thanks for offering some explanation. It is my sincere hope that the organizers will look upon the aforementioned experiment as a failed one. I shared the same perception as Bruce; most "keynotes" and lightning talks were anemic vendor pitches that really gutted the spirit of what I experienced last year. In meeting new people this year, I have had more than one first-time attendee ask me if PyCon lightning talks "are always like that." I have also heard from a couple of folks I would consider PyCon elders who were not happy with what lightning talks became this year. I was one of the 15 or so persons who had a lightning talk that ended up in overflow for the Saturday talks. At the end of the regular time, we were all brought forward to be told that we would not do overflow talks. Standing there in the huddle, I looked around, and it appeared that we were mostly non-vendors. It was pretty crummy to see that real PyCon lightning talks had been sacrificed in favor of subjecting Pythonistas to rather dry vendor presentations. Some of the vendor presenters even had a tone that sounded like "my boss is making me do this." PyCon lightning talks are the stuff of legend; I implore the organizers to learn well from this costly experiment, and let's not go there again. Ever. > >On top of that, the quality of the presentations was unusually low. > >I'd say that 80% were not worth going to -- there were definitely some > >good ones, but it was a lot of pain to discover them. > > Just to make sure, you're talking about the vendor presentations, right? [...] I'll step out and say that some of the non-vendor talks were quite weak. The most severe was a talk on Stackless where the original speaker was unable to be here and someone got up and clicked through the slide deck at a very fast pace. I thought the person had stepped in at the last minute, but later learned that he had volunteered with a couple of weeks' notice. Additionally, the original speaker had Andrew Dalke's *exact* slide deck from his Stackless talk last year. One first-time attendee told me over lunch that he was going to recommend to his employer that they not pay to send their programmers to PyCon next year based on what he had seen in this year's talks. I know that's an unpleasant message, but in the interest of preserving PyCon's quality, I'm willing to be the jerk of a messenger. > >I know what the argument for the results of Pycon 2008 will be: we > >needed the money. My answer: it's not worth it. If this is what you > >have to do to grow the conference, then don't. If the choice is > >between selling my experience to vendors and reducing the size of the > >conference, then cut the size of the conference. Keep the quality of > >my experience as the primary decision criteria, or I'll stop coming. > > That was our intention. ?Apparently it didn't work for you. ?I'll wait > for more feedback before I make up my mind about whether your experience > was common. [...] Hopefully the surveys and this thread will be filled with feedback from the participants. Also, check http://twitter.com/pycon for some further anecdotal evidence. From castironpi at gmail.com Sun Mar 16 19:55:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 16:55:44 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> <9b959898-ed57-47b9-8158-7ca6a321e705@u69g2000hse.googlegroups.com> Message-ID: On Mar 16, 1:29?pm, "Gabriel Genellina" wrote: > En Sat, 15 Mar 2008 20:08:05 -0200, escribi?: > > > > > > > On Mar 15, 8:18?am, Bryan Olson wrote: > >> castiro... at gmail.com wrote: > >> > Newbie question: ?Can you write to the 'file-like object' a pickle, > >> > and receive it intact-- as one string with nothing else? > > >> Yes, but there's a world of gotcha's. Sockets do not recognize > >> record boundaries, and Python's 'pickle' has holes one's enemies > >> could drive a truck through. Still, you can pickle, write, read, > >> un-pickle, and get back your data intact. > > >> > I want to know because I want to send two pickles. > > >> "Two pickles" sounds like a tasty snack, but also suggests you may > >> be playing hopscotch in a minefield. This is a helpful group. Give > >> us more to go on, and you are likely to receive thousands of > >> dollars worth of consulting for free. > > > It depends on the situation. ?How generally applicable is this: > > > fun ListenerGeneric( port, factory, arrivedfun ): > > > which calls 'factory' on socketA.accept (and loops again), then > > arrivedfun( stringA ) on message complete detection. ??. ?It should > > start itself in a separate thread. > > > Or is this any better: > > > for x in connections(): > > ? ?startnewthreadwith x: > > ? ? ? for y in messages( x ): > > ? ? ? ? ?arrivedfun( y ) > > This looks like a SocketServer + ThreadingMixIn + a RequestHandler (your ? > factory). > But as B. Olson already pointed, pickles are unsafe. Worse, it's not that ? > someone could send a specially crafted pickle that could execute some ? > arbitrary code: you're blindy executing whatever you receive! > xmlrpc may be a good alternative in some cases. I see. Just transmit a binary and execute that. Make sure to have handles to your program publicly accessible too. I execute this. From arkanes at gmail.com Mon Mar 17 11:07:46 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 17 Mar 2008 10:07:46 -0500 Subject: wxPython graphics query (newbie) In-Reply-To: References: Message-ID: <4866bea60803170807q6a0c008frcd290a96160674df@mail.gmail.com> On Mon, Mar 17, 2008 at 7:03 AM, Thomas G wrote: > I am exploring wxPython and would be grateful for some help. > > It is important to me to be able to slide words and shapes around by > dragging them from place to place. I don't mean dragging them into a > different window, which is what 'Drag and Drop' has come to mean, just > moving them around within a canvas-like space. > > This is easy using Tkinter. Can anybody offer me a tiny, very simple > example of how it would be done in wxPython, please? > > To make sure I convey what I'm looking for, here is what it looks like > using Tkinter, written very simply. What I'm looking for is the same, > quite simple functionality expressed in wxPython, again written very > simply so that I can easily understand it. > See the floatcanvas and OGL examples in the wxPython demo. From castironpi at gmail.com Tue Mar 18 17:27:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 14:27:44 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> Message-ID: <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> > > > On Mar 17, 1:31 pm, Duncan Booth wrote: > > > >> A common explanation for this is that lists are for homogenous > > >> collections, tuples are for when you have heterogenous collections i.e. > > >> related but different things. > > > > I interpret this as meaning that in a data table, I should have a list > > > of records but each record should be a tuple of fields, since the > > > fields for a table usually have different forms whereas the records > > > usually all have the same record layout. > > >>> b in b > False That's actually interesting. >>> a= [] >>> a.append( a ) >>> a [[...]] >>> a in a Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp From tms at zeetix.com Mon Mar 17 08:01:59 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Mon, 17 Mar 2008 08:01:59 -0400 Subject: String To List Message-ID: <006301c88826$b46127e0$0200a8c0@TMSMAIN> It's too bad your inner data items are delimited with an apostrophe (') instead a double-quote ("). If they were double-quote, you could do something as simple as: Given: a = '["xyz", "abc"]' import simplejson answer = simplejson.loads(a) There may be an incantation to simplejson that allows you to use a different delimiter. You might be able to provide your own decoder, using the "cls=" argument (but I don't think that lets you change the delimiter string). Failing that, and depending on your regex/Python prowess, you might be able to change the "decoder.py" file within simplejson to do what you want. As others have observed, a lot depends on the input data. If it really is as simple as your example, then the following may do the trick: a = "['xyz', 'abc']" answer = map(lambda each: each.strip()[1:-1], a[1:-1].split(',')) This at least has no "eval", and so you need not fear applying it to unknown data (it will just break). The answer that works best for you may perhaps be somewhere in the middle. "Girish" wrote in message news:e6035b85-d00c-4a35-951d-8287a99f7d8b at s8g2000prg.googlegroups.com... >I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? > Thanks for the help... > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Wed Mar 26 13:24:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 14:24:50 -0300 Subject: last mouse movment or keyboard hit References: Message-ID: >> En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler >> escribi?: >> >> >> I would like to get the time of the most recent human activity like a >> >> cursor >> >> movement or a key hit. >> >> Does anyone know how I can get this back to start some action after >> >> there >> >> has been no activity for X minutes/seconds? En Wed, 26 Mar 2008 13:59:15 -0300, azrael escribi?: > You can use wxPython. Take a look on the DemoFiles that you can > download also from the site. I remember that there has been a demo of > capturing mouse coordinates and also one example about capturing Which > key has been pressed at which time. (Please don't top post) Does wx catch all events in all other applications? My understanding is that the OP wants a global detection, not restricted to a single application. -- Gabriel Genellina From bjorn.m.meyer at gmail.com Fri Mar 21 11:26:52 2008 From: bjorn.m.meyer at gmail.com (Bjorn Meyer) Date: Fri, 21 Mar 2008 09:26:52 -0600 Subject: script won't run using cron.d or crontab In-Reply-To: <47E36B46.4050002@jouy.inra.fr> References: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> <47E36B46.4050002@jouy.inra.fr> Message-ID: <73b543b30803210826i735e54f6jafc5ff73dbe0e8a7@mail.gmail.com> Thank you for your reply. This is pretty much what I found from my digging around. I asume this can still be done. Is there an easy way to determine what needs to be added to the environment? Bjorn On Fri, Mar 21, 2008 at 2:01 AM, Robert Bossy wrote: > Bjorn Meyer wrote: > > I appologize if this been discussed previously. If so, just point me > > to that information. > > > > I have done a fair bit of digging, but I haven't found a description > > of what to actually do. > > > > I have a fairly lengthy script that I am able to run without any > > problems from a shell. My problem is, now I am wanting to get it > > running using crontab or cron.d. It seems that running it this way > > there is a problem with some of the commands that I am using. For > > instance "commands.getoutput" or "os.access". I am assuming that there > > is something missing within the environment that cron runs that fails > > to allow these commands to run. > > If anyone has any information that would help, it would be greatly > > appreciated. > Hi, > > From a shell, type: > man 5 crontab > and read carefully. You'll realize that a croned script does not inherit > from the user shell's environment. > > Cheers, > RB > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Mon Mar 31 19:08:27 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 1 Apr 2008 07:08:27 +0800 Subject: troll poll In-Reply-To: Message-ID: George Sakkis wrote: > On Mar 31, 1:46 pm, Marc 'BlackJack' Rintsch wrote: > >>> More specifically, who can create a bigger mess on c.l.py? (check >>> one) >> >>> [ ] - Xah Lee >>> [X] - castironpi >> >> Xah Lee's postings might be trolls but sometimes they spark some >> really interesting and serious subthreads, while the nonsense of >> castironpi is just irritating noise. > > Which is exactly why there are rarely any replies to his random > gibberish, so I would say that he/she/it has almost no effect on > c.l.py. Yet I wish plonking was possible through Google groups. I find classifying all their posts as spam works fairly well. Tim Delaney From deets at nospam.web.de Tue Mar 4 05:29:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Mar 2008 11:29:13 +0100 Subject: tools to install not in python tree? References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: <634mjoF268j1dU1@mid.uni-berlin.de> commander_coder at hotmail.com wrote: > Hello, > > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ and some programs that I want in ~/public_html/ . I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). But as I understand it setup only targets > installing below sys.prefix; is that right? You can use setuptools. And it will install to any path available on sys.path. So if you define PYTHONPATH pointing to some folder, you can use setuptools to install the code (eggs) as well as create script entry-points, so if the same path is part of PATH they will become available on the command line. Diez From mcepl at redhat.com Sat Mar 1 18:13:21 2008 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 02 Mar 2008 00:13:21 +0100 Subject: sqlite3 adaptors mystery Message-ID: Hi, I am in the process of creating a small script for filling the sqlite3 database with data from rather large XML-RPC query (list of many bugs from the Red Hat Bugzilla) and I would love to use adaptors and converters for some data types which I am missing. I have this test script (made hopefully pretty faithfully from the documentation): #!/usr/bin/python import sqlite3 def adapt_boolean(bol): if bol: return "True" else: return "False" def convert_boolean(bolStr): if str(bolStr) == "True": return bool(True) elif str(bolStr) == "False": return bool(False) else: raise ValueError, "Unknown value of bool attribute '%s'" \ % bolStr sqlite3.register_adapter(bool,adapt_boolean) sqlite3.register_converter("boolean",convert_boolean) db = sqlite3.connect("test.db") cur=db.cursor() cur.execute("create table test(p boolean)") p=False cur.execute("insert into test(p) values (?)", (p,)) p=True cur.execute("insert into test(p) values (?)", (p,)) cur.execute("select p from test") print cur.fetchall() And I would expect to print on output representation of bool values, i.e., something like [False,True] However, when running this program it seems converter doesn?t seem to work, because I get: [matej at viklef dumpBugzilla]$ rm test.db ; python testAdaptors.py [(u'False',), (u'True',)] [matej at viklef dumpBugzilla]$ There is probably something quite obvious what I do incorrectly, but I just don't see it. Could somebody kick me in the right direction, please? Thanks a lot, Mat?j Cepl From furkankuru at gmail.com Tue Mar 25 08:51:30 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:51:30 +0200 Subject: Inheritance question In-Reply-To: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <3a4a8f930803250551n851e556n1b799409a4b1812f@mail.gmail.com> In the derived class init you set self.id to 2 so when you call getid method it just returns self.id which is now 2. you can use another variable name. On Tue, Mar 25, 2008 at 1:44 PM, Tzury Bar Yochay wrote: > given two classes: > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = Foo.getid() > b = self.id > return '%d.%d' % (a,b) > > While my intention is to get 1.2 I get 2.2 > I would like to know what would be the right way to yield the expected > results > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn at u.washington.edu Mon Mar 31 12:18:06 2008 From: donn at u.washington.edu (Donn Cave) Date: Mon, 31 Mar 2008 09:18:06 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> <65701aF2erbbsU1@mid.uni-berlin.de> <7xr6dta93p.fsf@ruckus.brouhaha.com> Message-ID: In article <7xr6dta93p.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Select blocks until the data is ready, while with AIO the i/o happens > completely in the background and your process gets an interrupt when > the i/o completes. Also, with select based i/o, usually the kernel > reads data from the external device into a system buffer, and then you > do a read system call that copies the data from the system buffer to > your buffer. AIO can be set up so the i/o happens directly into your > buffer, avoiding the extra copying. You can also initiate a bunch of > different i/o events with a single system call, avoiding some context > switches. > > http://www.ibm.com/developerworks/linux/library/l-async/ > > describes select as "asynchronous, blocking" as opposed to AIO which > is asynchronous and nonblocking. Other descriptions I've seen reserve > "asynchronous i/o" for AIO-like schemes. It's just a terminological > thing. kqueue(2) on MacOS X mentions an EVFILT_AIO option. It isn't supported on that platform, but maybe that's a vestige of some other platform that does support "asynchronous, blocking" with aio -- as VAX/VMS did (and presumably still does), with event flags. Donn Cave, donn at u.washington.edu From deets at nospam.web.de Mon Mar 10 17:21:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 22:21:44 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: <63ln3cF273fndU1@mid.uni-berlin.de> > > Java is more portable than most other languages, especially if your app needs a gui. Depending on what GUI you want, python is at least as portable - Tkinter is available for lots of platforms. And swing as a GUI plain sucks - there is a reason for SWT. But that needs to be installed separately and per platform. Additionally, Java is not Python :) Diez From benhoyt at gmail.com Tue Mar 18 23:47:02 2008 From: benhoyt at gmail.com (benhoyt) Date: Tue, 18 Mar 2008 20:47:02 -0700 (PDT) Subject: Is there a way to get __thismodule__? Message-ID: Is there a way to get __thismodule__ in Python? That is, the current module you're in. Or isn't that known until the end of the module? For instance, if I'm writing a module of message types/classes, like so: class SetupMessage(Message): number = 1 class ResetMessage(Message): number = 2 class OtherMessage(Message): number = 255 nmap = { # maps message numbers to message classes 1: SetupMessage, 2: ResetMessage, 255: OtherMessage, } Or something similar. But adding each message class manually to the dict at the end feels like repeating myself, and is error-prone. It'd be nice if I could just create the dict automatically, something like so: nmap = {} for name in dir(__thismodule__): attr = getattr(__thismodule__, name) if isinstance(attr, Message): nmap[attr.number] = attr Or something similar. Any ideas? (A friend suggested class decorators, which is a good idea, except that they're not here until Python 2.6 or Python 3000.) Cheers, Ben. From newsgroup898sfie at 8439.e4ward.com Thu Mar 20 16:43:20 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Thu, 20 Mar 2008 16:43:20 -0400 Subject: putting text through pager Message-ID: <9suab5-jvs.ln1@ID-262785.user.uni-berlin.de> Hi, I'm trying to print some variable through a pager (i.e. 'less') on a linux system. My attempt was this: ====== snip here ====== import subprocess def put_through_pager(displaystring): less_pipe = subprocess.Popen(\ 'less', shell=True, \ stdin=subprocess.PIPE).stdin less_pipe.write(displaystring) less_pipe.close() def main(): put_through_pager(longstring) longstring = """ Lorem ipsum dolor sit amet,... http://www.lipsum.com/ """ main() ====== snip here ====== That doesn't work however: first of all, it only flashes the text for a fraction of a second, and secondly, after I run the program my terminal is broken, not echoing whatever I type back to me. Any suggestions for putting text through a pager from Python? This is strictly on a linux system, of course. Thanks, Michael From jef.mangelschots at gmail.com Tue Mar 4 16:38:41 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 4 Mar 2008 13:38:41 -0800 (PST) Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> <3319005c-98b9-44a0-96dc-72db45f2ae27@z17g2000hsg.googlegroups.com> Message-ID: <5bf892c0-ec5a-425a-91d3-580ae66ebbbf@h11g2000prf.googlegroups.com> > on windows using python 2.4. ??? I was on Python 2.4.3 and it gave me that problem. I upgraded to 2.4.4 and it works. thanks for the tip. From lists at js3d.co.uk Tue Mar 25 14:46:57 2008 From: lists at js3d.co.uk (Jules Stevenson) Date: Tue, 25 Mar 2008 18:46:57 -0000 Subject: setattr what is the parent object? Message-ID: <005601c88ea8$9a936520$0600a8c0@laptop> I'm trying to use setattr to dynamically name and layout gui wx widgets, this is all fine and dandy until I've run up against something where I simply don't know what the object is, please see the amended **don't know** in the following code. class MyFrame2(wx.Frame): def __init__(self, *args, **kwds): blah blah blah __do_layout(mayaVars) def __do_layout(self, mayaVars): main_boxSizer = wx.BoxSizer(wx.VERTICAL) for pDisplay in range(len(mayaVars.primary)): setattr=(**don't know**,"r_gridBagSizer_"+mayaVars.primary[pDisplay], wx.GridBagSizer(vgap=0, hgap=0)) Without all the dynamic gumpf, the statmement looks like this: r_gridBagSizer = wx.GridBagSizer(vgap=0, hgap=0)) All the other UI elements are created on 'self' but the sizers don't seem to 'belong' to anything - what should I use when this is the case? Many thanks, and apologies if I'm being dense Jules -------------- next part -------------- An HTML attachment was scrubbed... URL: From hasnihon.support at gmail.com Mon Mar 24 09:51:40 2008 From: hasnihon.support at gmail.com (hasnihon.support at gmail.com) Date: Mon, 24 Mar 2008 06:51:40 -0700 (PDT) Subject: Serving another web site which requires authentication Message-ID: Hi, I need your suggestions about the topic. Actually, I'm not sure where to start but basically, I want to make something like; (I have an account on a site which requires log-in) - I'll be logged-in to that site with my account in my server. - And when a user connects to my site, I'll forward him/her to that site, using my account even if he/she doesn't have an account on that site... probably, I need to develop a proxy to do this, but I'm not sure... (I use python + django) I really appriciate your ideas. From babycode at gmail.com Mon Mar 3 15:41:58 2008 From: babycode at gmail.com (babycode at gmail.com) Date: Mon, 3 Mar 2008 12:41:58 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: <5df8299b-8278-4bdd-b63b-66518c1ac0fc@x30g2000hsd.googlegroups.com> > Please tell me what code you think it's stunning. Pexpect is (almost) pseudocode is (almost) poetry to my ears. And there's a lot of narrative in it as well: http://pexpect.svn.sourceforge.net/viewvc/*checkout*/pexpect/trunk/pexpect/pexpect.py?content-type=text%2Fplain From mail at timgolden.me.uk Sun Mar 16 10:09:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:09:30 +0000 Subject: Spaces in path name In-Reply-To: <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> Message-ID: <47DD2A1A.2040609@timgolden.me.uk> joep wrote: > > Tim Golden wrote: > >> subprocess.call ([ >> >> r"C:\Program Files\Adobe\Acrobat 5.0\Reader\acro reader.exe", >> >> r"C:\Program Files\Adobe\Acr >> obat 5.0\Reader\plug_ins.donotuse\Annotations\Stamps\abc def.pdf" >> >> ]) >> >> Can you confirm that something equivalent *doesn't* work on your >> setup? Or have I misunderstood your point earlier? I'd really >> like to get to the point where we can definitively state: this >> works (and possibly: that doesn't). >> >> Thanks >> TJG > > This works without problems for me on Windows XP, Python 2.4.3 OK. That's good, at least. > I often had problems understanding subprocess.Popen and getting it to > work. I usually have to go back-and-forth between worked examples, I admit. [... snip problem with Popen ...] Ah. I assumed that .call simply handed off to Popen. I'll do some looking into that in case I need to add a warning to the webpage. (And, maybe, a bug report). Thanks for following this up. TJG From wiqd at codelounge.org Thu Mar 6 11:23:25 2008 From: wiqd at codelounge.org (Greg Armer) Date: Thu, 6 Mar 2008 18:23:25 +0200 Subject: Does python support working with password protected zip files? In-Reply-To: <1204819422.29123.1240935267@webmail.messagingengine.com> References: <1204819422.29123.1240935267@webmail.messagingengine.com> Message-ID: <2ef52b180803060823w4bdcedd1ra81f68ba1e34654b@mail.gmail.com> On 3/6/08, Malcolm Greene wrote: > I'm new to Python and trying to figure out how to read and write to > password protected zip files. > > I can work with plain zip files no problem. > > I've googled this topic and am coming up empty except for a post on > Nabbler.com that seemed to imply that password protected zip files > may(???) be supported in Python 2.6 and ads for a commercial Windows > (only) zip component from chilkat.com. > > Any suggestions? Hi Malcolm, I just had to do some with with this myself and eventually resorted to simply using a popen() call to the system unzip utility with the -Ppass command line option. def _unzipdata(self): print "[~] Processing zip file %s..." % self.zipfile # Create temporary directory os.mkdir('_temp') # Unzip password protected zipfile to _temp os.chdir('_temp') os.popen("unzip -P%s ../%s" % (self.password, self.zipfile), "r") return True While this is not ideal, i could not find any other alternatives. Hope that helps. -- Greg Armer Entropy has us outnumbered. From mauriceling at acm.org Tue Mar 18 03:14:32 2008 From: mauriceling at acm.org (Maurice LING) Date: Tue, 18 Mar 2008 07:14:32 GMT Subject: Multiple Submits in HTML Forms - Cherrypy Message-ID: <47df6bd4$1@news.unimelb.edu.au> Hi, Assuming that I have this code for Cherrypy 3 class Welcome: def index(self): return """

""" index.exposed = True How should I write "btn_handler" so that it will perform different actions when different button is pressed? Thanks in advance Cheers maurice From atom.anderson at gmail.com Thu Mar 20 12:54:13 2008 From: atom.anderson at gmail.com (atom.anderson at gmail.com) Date: Thu, 20 Mar 2008 09:54:13 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> Message-ID: Okay! I just read this entire thread to be caught up. I am a first time PyCon-goer (as my previous post states). Because I have nothing to compare this year's experience to, I'll give it to you as I saw it. None of this is intended as a rant, (except maybe the lightning talk section;) Gripes ------ Numero Uno: The Lightning Talks. The best lightning talk I saw was the one where the guy's code didn't work and he couldn't believe it or simply move on with his presentation, it was hilarious but I felt bad for the guy. I have to be honest, I had heard GREAT things about the lightning talks and I went to the session expecting to hear something great, or at least feel the same sense of community I felt when discussing python in education (i'm a student) or its use in the industry. I went with a friend who also attended the conference from my school and sat down expectantly. I noticed the guy was trying to set up a powerproint (or OOo or whatever) presentation and I simply couldnt believe it. A powerpoint presentation? Pictures? text? preparation? That doesn't sound like lightning at all. It sounds like, "slow-tning" talks. Methodically prepared sales-pitch presentations on johnny q. coder's latest commercial triumph. I thought these talks were spur of the moment, community-delivered and off the cuff? In my opinion, i don't believe that lightning talks should include the option of using presentation software, maybe thats too restrictive, but it seems to me that we'd be treated to much more grassroots or user-given talks rather than sponsor-given ones. I could just be ranting. Number Two: Presenters should be required to post their slides on the web site / schedule before they are permitted to present. We want 'em, they've got 'em, and I was in more than one session where simply having uploaded them to the PyCon schedule would have saved the presenters bacon when it came time for their laptop to die or something else. I realize that these presentations are fluid and change (often the night before!) but a failsafe like this wouldn't hurt anyone. Number Three: Too much code, not enough concept. Presenters this one's for you. I can't count the number of presentations I attended where the presenter would click through three slides of pycode just to show us a two or three-line snippet that illustrated their point. Worse yet, it was often at the bottom of the screen so no one but the front row could see it. This goes for text two. I saw some great presentations as well, and they had limited text on each slide. The last thing your audience wants to see is a slide drenched in text of any kind. You only have 30 minutes (or less). Show us brief couplets of code for syntax sake. We don't care about code, we care about the concept. If it were an hour lecture you could go through pages of code and itd be great, but when we can't even read the whole slide before you move on then its too much. Number Four: What's a BOF? Noob here. My first pycon and I didnt know the terminology. Shocker huh? Heh, well i figured it out into the first day, but still didn't quite get the concept. Around day two or three i started attending these and learned just how cool they are. With the RAPID growth pycon has shown over the last few years, perhaps a little session at the beginning to help the newcomers or a "Terminology" page in the handbook would be helpful? Praise ------ As a student attending his first pycon, i must say it was AWESOME. Depending on the sessions i chose to attend, i learned all KINDS of useful stuff. Pyglet, Stackless (i'm willing to give it a chance despite the mediocre presentation), RE, pysight and more. Coming from a small school out west, the experience of visiting a convention where a community actually existed was an incredible experience. That was probably the best part of the conference was seeing that there truly was a programming community and meeting other like-minded people and being able to finally discuss things of programming importance with them. I guess thats what we had hoped to see more of in the lightning talks. We enjoyed the EXPO as well and a couple of our graduating attendees have nabbed phone interviews with companies that were represented there. I am definitely planning on returning to pycon next year, if only to rub shoulders with other python programmers again and *hopefully* attend a conference that has learned from any mistakes this year and become an even better event for 2009. adam From deets at nospam.web.de Thu Mar 27 03:45:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 08:45:25 +0100 Subject: counting using variable length string as base In-Reply-To: References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <6511l0F2d9knfU1@mid.uni-berlin.de> Grimsqueaker schrieb: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? No. Just put a list() around it. Diez From gagsl-py2 at yahoo.com.ar Sat Mar 15 04:25:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 06:25:39 -0200 Subject: Handling global variables (Newbie) References: Message-ID: En Thu, 13 Mar 2008 02:25:12 -0200, David S escribi?: > I have an error occurring at > self.build_root = os.path.abspath(os.path.split(__file__)[0]) > > The error states 'NameError: global name '__file__' is not defined' > > In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ > get > defined? If you type your code directly into IDLE (or the commmand line Python interpreter) __file__ doesn't even exist; it only has any sense when the code is read from an actual file. Save your code on disk, let's say you name it example.py Then you can execute it using > python example.py from the command line; from inside IDLE, go to File | Open, locate example.py, press F5 -- Gabriel Genellina From nagle at animats.com Mon Mar 24 02:01:10 2008 From: nagle at animats.com (John Nagle) Date: Sun, 23 Mar 2008 23:01:10 -0700 Subject: Testing for an empty dictionary in Python - documented? In-Reply-To: References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <47e74162$0$36389$742ec2ed@news.sonic.net> Bryan Olson wrote: > D'Arcy J.M. Cain wrote: >> John Nagle wrote: >>> What's the cheapest way to test for an empty dictionary in Python? > >> Try this: >> >> if dict: > > D'Arcy is right; that's the way to go. I'll add that 'dict' is the name > of the built-in class, so an instance is usually best named something else. Is this a documented language feature? The only references to this in the spec are vague. In "3.4.5 Emulating container types" there's "Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context." That's as close as the reference manual seems to come. There are mentions that in Python 3K, __nonzero__ should be replaced by __bool__. But I'm not finding anything in the spec that actually says that sequences, used in a Boolean context, are False if empty and True if nonempty. In fact, "5.8 Comparing Sequences and Other Types" in the Tutorial ("Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name.Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc.") might lead one to think that this wasn't the case. John Nagle From ggpolo at gmail.com Thu Mar 27 07:31:03 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 08:31:03 -0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: <47EB7F55.8090909@gmail.com> References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> <47EB7F55.8090909@gmail.com> Message-ID: 2008/3/27, Alex9968 : > Guilherme Polo wrote: > > 2008/3/27, Alex9968 : > > > >> Guilherme Polo wrote: > >> > 2008/3/26, Alex9968 : > >> > > >> >> Hi all, > >> >> > >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over > >> >> using visual GUI designers), so my question is which other GUI toolkits > >> >> have similar functionality. > >> >> > >> > > >> > The geometry manager isn't related to using GUI designers tools at > >> > all. And each toolkit has it's own way to do the things, wxPython uses > >> > sizers, PyGtk uses containers. > >> > > >> > >> Well, the geometry manager isn't *directly* related to using GUI > >> designers, but as Pack arranges widgets automatically, using GUI > >> designers isn't required, while with geometry managers that don't, GUI > >> designers are necessary (if you start placing widgets programmatically, > >> you'll end up reinventing something like Tkinter's Pack or Grid geometry > >> manager). I hope I can be understood clearly this time ;-) > >> > > > > Not at all, can't understand your point yet. GUI designers aren't just > > for placing widgets, they also will keep the interface design > > separated from your code. > > > > I do not want to separate interface from code and I do not experience > the need to use GUI designers. > It is your opinion, it seems I can't change it for now but I hope you reconsider it for the future. > Pack arranges widgets perfectly, and it's very complex to do the same > without it, both in code and in GUI designer. For some level of "perfect", of course. Also, I can't understand why you say it is hard to do such thing in a gui designer tool, which tool have you tried ? Maybe you are not familiar with them yet, and that could be the problem. > I wish toolkits I use to > be able to place widgets one after another automatically. > They all make this possible, you could try doing something on another toolkit you are interested and check if it does what you want. > > > >>>> Secondly, I like the detailed widget borders configuration possible in > >>>> > >> >> Tkinter, which can be used to tweak GUI look, and wonder if other > >> >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) > >> >> look in Windows, but I'm afraid it can be quite different (and ugly) on > >> >> other platforms. > >> >> > >> > > >> > You sure can, but differently. > >> > > >> > >> I suppose any toolkit allows setting parameters like "no border", "flat > >> border" and "3d border", but which ones can set ANY type of border to > >> ANY widget like Tkinter does? For example set GROOVE border to buttons > >> and text widgets (instead of traditional wide raised/lowered borders), > >> which is cool (in my opinion). > >> > >> > > > > The widgets subclass some base class, which contains some common > > methods which could be the border and relief for example. > > In the case of PyGtk, border > > width is controlled at Container, so most widgets will have this > > feature, but the relief style of the widget is not common to all > > widgets so you will need to check this one (Button has it). > > In wxPython, widgets will subclass Window, which has all you want and more. > > But PyQt doesn't seem to care much about this, you can change the > > widget to flat (if it makes sense to that widget have setFlat method) > > but not much related to the borders. > > You could recheck your use-cases and see if they are acceptable. > > > > > >> >> (The reason I ever consider moving from Tkinter is some inconveniences, > >> >> involving for example window scrolling, plus its smaller amount of > >> >> widgets compared to some other toolkits, plus its (rumored) ugly look on > >> >> certain environments. I will not necessary change the toolkit, but I > >> >> have to consider it) > >> >> > >> >> > >> > > >> > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > >> > Tkinter for upcoming GSoC. For now you could try using Tile extension, > >> > and update to Tk 8.5. If you don't want to use extensions, then you > >> > will have to wait or change the toolkit for now. > >> > > >> > >> Thanks. I haven't heard of Tile before, now I will keep this in mind. > >> You forgot to mention WHAT you're planning to solve ;-) , so I have to > >> add that Tile is modernization of Tk widgets (so it fixes ugly look). > >> > >> > > > > WHAT I'm planning to solve, quote from my own paragraph: > > "I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > > Tkinter for upcoming GSoC." > > > > I would like to add the possibility to use Ttk widgets into tkinter, > > providing you have Tk 8.5. It would solve the problem of "not enough > > widgets" and the other one of "being ugly" mainly. Tk 8.5 also > > auto-fixes some other problems, it provides smooth-scrolling for the > > text widget, for example. But keep in mind that using Tk 8.5 in Python > > is not yet supported (but possible). > > > > I understood you. I added that sentence just to make it clear for anyone > reading this. Your participation is appreciated greatly, thank you. > -- -- Guilherme H. Polo Goncalves From benhoyt at gmail.com Wed Mar 19 14:18:06 2008 From: benhoyt at gmail.com (benhoyt) Date: Wed, 19 Mar 2008 11:18:06 -0700 (PDT) Subject: Is there a way to get __thismodule__? References: Message-ID: <94d3d055-7bc3-408d-9a44-c4adb1307712@e6g2000prf.googlegroups.com> Wow -- thanks, guys. And who said Python only gives you one way to do things. :-) Metaclasses, globals(), and __subclasses__. Thank Duncan for the __subclassess__ tip -- I didn't know about that. I'd totally overlooked globals(). It's exactly what I was looking for -- thanks, Peter. And I like your is_true_subclass() helper function too. I must say, I found it a bit weird that the first argument to issubclass() *has* to be a class. I would have thought issubclass(42, MyClass) would simply return False, because 42 is definitely not a subclass of MyClass. But I guess "explicit is better than implicit", and being implicit here might mask bugs. globals() feels like the "right" way to do what I want -- fairly simple and direct. Metaclasses are cool, but probably a touch too complicated for this. And __subclassess__ seems a bit undocumented and perhaps implementation-defined. Cheers, Ben. From ebenze at hotmail.com Sun Mar 16 09:53:03 2008 From: ebenze at hotmail.com (Eric B.) Date: Sun, 16 Mar 2008 09:53:03 -0400 Subject: Cannot build Python 2.4 SRPM on x64 platform Message-ID: Hi, For those on several python lists, I appologize in advance for cross-posting, but I'm really not sure which list is best to ask for assistance with this. Currently, I am trying to build the python2.4 SRPM from Python.org on a RHEL4 x64 platform, but the build is failing with a very non-descript error message. .... + cd /var/tmp/python2.4-2.4-root/usr/bin + mv -f pydoc pydoc2.4 + cd /var/tmp/python2.4-2.4-root/usr/bin + mv -f idle idle2.4 + echo '#!/bin/bash' + echo 'exec /usr/bin/python2.4 /usr/lib64/python2.4/idlelib/idle.py' + chmod 755 /var/tmp/python2.4-2.4-root/usr/bin/idle2.4 + cp -a Tools /var/tmp/python2.4-2.4-root/usr/lib64/python2.4 + rm -f mainpkg.files + find /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f + sed 's|^/var/tmp/python2.4-2.4-root|/|' + grep -v -e '_tkinter.so$' error: Bad exit status from /var/tmp/rpm-tmp.55639 (%install) RPM build errors: user jafo does not exist - using root group jafo does not exist - using root user jafo does not exist - using root group jafo does not exist - using root Bad exit status from /var/tmp/rpm-tmp.55639 (%install) If I try to run /var/tmp/rpm-tmp.55639 manually from the prompt manually after the rpmbuild fails, it runs properly to completion. If I try to comment out that last line (find /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f | sed 's|^/var/tmp/python2.4-2.4-root|/|' | grep -v -e '_tkinter.so$' ) that seems to be causing the script to fail, rpmbuild finishes, but with several error msgs, complaining about missing files in the lib64 directories: + rm -f /tmp/python-rpm-files.4859 + /usr/lib/rpm/brp-compress + /usr/lib/rpm/brp-strip + /usr/lib/rpm/brp-strip-static-archive + /usr/lib/rpm/brp-strip-comment-note Processing files: python2.4-2.4-1pydotorg error: File not found by glob: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.txt error: File not found by glob: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.py* error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/pdb.doc error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/profile.doc error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/curses error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/distutils error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/encodings error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/plat-linux2 error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/site-packages error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/test error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/xml error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/email error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/compiler error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/bsddb error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/hotshot error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/logging error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-old Executing(%doc): /bin/sh -e /var/tmp/rpm-tmp.95118 + umask 022 + cd /usr/src/redhat/BUILD + cd Python-2.4 + DOCDIR=/var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + export DOCDIR + rm -rf /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + /bin/mkdir -p /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + cp -pr Misc/README Misc/cheatsheet Misc/Porting /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + cp -pr LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + exit 0 Processing files: python2.4-devel-2.4-1pydotorg error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/config Processing files: python2.4-tools-2.4-1pydotorg Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(VersionedDependencies) <= 3.0.3-1 Requires: /bin/bash /bin/sh /usr/bin/env Finally, if I try searching for any files in the usr/lib64/python2.4/lib-dynload or usr/lib64/python2.4/idlelib directories manually, I don't see any files at all in those directories. To me, it seems as though python is either not installing the files in the right places, or the script is searching for files in the wrong places, but I'm completely guessing here. Has anyone managed to build Python2.4 on a RHEL4 x64 system? Can anyone point me in the right direction to complete this build successfully? I'm hoping to get the binaries built so I can contribute them to the python.org site so others don't need to go through these problems in the future. Any hints / ideas / suggestions / guidance that anyone can provide would amazing, because I'm completely out of ideas at this point. Like I said, I'm trying to build this on a RHEL4 x64 system, with all latest updates. Thanks so much! Eric From brad at 16systems.com Fri Mar 28 23:51:07 2008 From: brad at 16systems.com (Brad) Date: Fri, 28 Mar 2008 23:51:07 -0400 Subject: some path issues on windows In-Reply-To: <13urddulja4t7fa@corp.supernews.com> References: <13urddulja4t7fa@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Fri, 28 Mar 2008 22:31:07 -0400, Brad wrote: > >> When reading a file into a list that contains windows file paths like >> this: >> >> c:\documents and settings\brad\desktop\added_software\asus\a.txt >> >> I get a list that contains paths that look like this: >> >> c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt > > > What makes you think that there are doubled backslashes in the string? > Look at this: Sorry, my mistake... when testing with prints, printing the list itself showed double backslashes \\ in the paths, but when printing each path individually, it's only one back... should have tested more before posting. My apologies. Brad From cantabile.03 at wanadoo.fr Sat Mar 15 16:54:25 2008 From: cantabile.03 at wanadoo.fr (Unknown) Date: 15 Mar 2008 20:54:25 GMT Subject: replace string in a file Message-ID: <47dc3781$0$869$ba4acef3@news.orange.fr> Hi, I've got this code : cb = open("testfile", "r+") f = cb.readlines() for line in f: rx = re.match(r'^\s*(\d+).*', line) if not rx: continue else: serial = rx.group(1) now = time.time() today = time.strftime('%Y%m%d00', time.localtime(now)) todayVal, serialVal = long(today), long(serial) if todayVal <= serialVal: todayVal = serialVal + 1 else: todayVal += 1 line = string.replace(line, serial, "%d" %todayVal) cb.write(line + "\n") print 'Updated serial from "%s" to "%d"' % ( serial, todayVal ) break cb.close() I was expecting to replace the old value (serial) with the new one (todayVal). Instead, this code *adds* another line below the one found... How can I just replace it? Thanks for your help :-) From ptmcg at austin.rr.com Sat Mar 22 21:30:20 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Mar 2008 18:30:20 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> Message-ID: <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> Oof, I see that you have multiple "Layer" entries, with different qualifying labels. Since the dicts use "Layer" as the key, you only get the last "Layer" value, with qualifier "PRBOUNDARY", and lose the "Layer" for "METAL2". To fix this, you'll have to move the optional alias term to the key, and merge "Layer" and "PRBOUNDARY" into a single key, perhaps "Layer/PRBOUNDARY" or "Layer(PRBOUNDARY)" - a parse action should take care of this for you. Unfortnately, these forms will not allow you to use object attribute form (md.Layer.lineStyle), you will have to use dict access form (md["Layer(PRBOUNDARY)"].lineStyle), since these keys have characters that are not valid attribute name characters. Or you could add one more level of Dict nesting to your grammar, to permit access like "md.Layer.PRBOUNDARY.lineStyle". -- Paul From wahreviews at gmail.com Sat Mar 22 18:17:52 2008 From: wahreviews at gmail.com (wahreviews at gmail.com) Date: Sat, 22 Mar 2008 15:17:52 -0700 (PDT) Subject: Make Money Using Paypal Get Paid Instantly References: Message-ID: <4563a8f0-7f25-46d9-a039-e5cd5d11c523@i29g2000prf.googlegroups.com> On Mar 12, 12:10?pm, ayt46g6b wrote: > Make Money Using Paypal Get Paid Instantly > > Make 1k-5k every week > without leaving the > comfort of your own home > > Click Here to Make Money Using Paypal > and Get Paid Instantlyhttp://freetrafficbuzz.com/recommends/cashdirectly Interesting. What is being suggested here is against Paypal's acceptable usage policy. Consult with a real person who has been successful before you jump into a scam like this and above all, make sure that person is going to be there to support you the whole way whether you just need to ask a question from time to time or need a great deal of help. http://workfromhomereviews.org/ From Dodin.Roman at gmail.com Tue Mar 25 08:42:03 2008 From: Dodin.Roman at gmail.com (hellt) Date: Tue, 25 Mar 2008 05:42:03 -0700 (PDT) Subject: Need help with OptionParser Message-ID: <0a225d25-c544-49d9-9e56-8ecd2d0f7928@s13g2000prd.googlegroups.com> today i've decided to use optionparser instead of GetOpt and unfortunately i've got an error which i cant handle my pice of code: from optparse import OptionParser def main(): usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option("-f", "--file", dest="filename", help="executable filename", metavar="FILE") parser.add_option("-b", "--bighosts", action="store_true", dest="bighosts", default=False, help="with big hosts [default: %default]") (options, args) = parser.parse_args() if not options.bighosts: print parser.print_usage() if __name__=="__main__": main() if i run test3.py without any arguments, i wait for generated help, but i see the following Usage: test3.py [options] None why None? Where are all of my options From ptrk.mcm at gmail.com Sat Mar 29 17:21:48 2008 From: ptrk.mcm at gmail.com (ptrk) Date: Sat, 29 Mar 2008 14:21:48 -0700 (PDT) Subject: cProfile for python 2.4 References: Message-ID: <384dd8ae-859a-4ad0-9191-44b6c9036210@m36g2000hse.googlegroups.com> On Mar 28, 3:50 pm, David Pratt wrote: > I'd like to compile cProfile for python 2.4. Where can I get it to do > this? I realize it is part of python 2.5. Many thanks. can you use cProfile's predecessor, profile? http://docs.python.org/lib/module-profile.html From python.list at tim.thechases.com Wed Mar 19 06:57:04 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 05:57:04 -0500 Subject: a beginner, beginners question In-Reply-To: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> References: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Message-ID: <47E0F180.3010505@tim.thechases.com> > class example: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > def method(self): > print "method ... :" > print self.foo > print self.bar > > if __name__ == "__main__": > obj = example This makes "obj" a synonym for "example". You want to instantiate your "example" class with obj = example("Some foo", "Some Bar") > obj.foo = "var1" > obj.bar = "var2" which then makes these two lines either unneeded or an overwriting of the initialization > obj.method and this returns a function, not the results of the function. You need to call it obj.method() -tkc From darcy at druid.net Wed Mar 26 17:14:57 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 Mar 2008 17:14:57 -0400 Subject: Daylight savings time problem In-Reply-To: <13uldfrl46tf728@corp.supernews.com> References: <13uldfrl46tf728@corp.supernews.com> Message-ID: <20080326171457.8627f24f.darcy@druid.net> On Wed, 26 Mar 2008 20:45:47 -0000 Grant Edwards wrote: > On 2008-03-26, Salsa wrote: > > > I'm sorry, but could you be more specific? How exactly should I use UTC? > > In my experience, using local time for timestamps is always a > big mistake, so I presume he meant don't use local time in the > file names -- put the UTC date/time in the filenames. Yes. One problem with using local times is that once a year you can overwrite files. The best option is to use the number of seconds since EPOCH and let programs convert it to UTC or local time as required. -- 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 http Sun Mar 2 11:36:28 2008 From: http (Paul Rubin) Date: 02 Mar 2008 08:36:28 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> Message-ID: <7xr6etgk1f.fsf@ruckus.brouhaha.com> Lie writes: > You hit the right note, but what I meant is the numeric type > unification would make it _appear_ to consist of a single numeric type > (yeah, I know it isn't actually, but what appears from outside isn't > always what's inside). That is clearly not intended; floats and decimals and integers are really different from each other and Python has to treat them distinctly. > > Try with a=7, b=25 > > They should still compare true, but they don't. The reason why they > don't is because of float's finite precision, which is not exactly > what we're talking here since it doesn't change the fact that > multiplication and division are inverse of each other. What? Obviously they are not exact inverses for floats, as that test shows. They would be inverses for mathematical reals or rationals, but Python does not have those. > One way to handle this situation is to do an epsilon aware > comparison (as should be done with any comparison involving floats), > but I don't do it cause my intention is to clarify the real problem > that multiplication is indeed inverse of division and I want to > avoid obscuring that with the epsilon comparison. I think you are a bit confused. That epsilon aware comparison thing acknowledges that floats only approximate the behavior of mathematical reals. When we do float arithmetic, we accept that "equal" often really only means "approximately equal". But when we do integer arithmetic, we do not expect or accept equality as being approximate. Integer equality means equal, not approximately equal. That is why int and float arithmetic cannot work the same way. From manlio_perilloNO at SPAMlibero.it Wed Mar 26 14:58:40 2008 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Wed, 26 Mar 2008 18:58:40 GMT Subject: Beta testers needed for a high performance Python application server References: Message-ID: Il Tue, 25 Mar 2008 20:31:39 +0000, Minor Gordon ha scritto: > Hello all, > > I'm looking for beta testers for a high performance, event-driven Python > application server I've developed. > > About the server: the front end and other speed-critical parts of the > server are written in portable, multithreaded C++. The back end is an > embedded CPython interpreter. The server is much faster than anything in > pure Python, and it can compete with C servers (including e.g. lighttpd > for file workloads) or outdo them (e.g. anything behind Apache) until > CPython consumes a single processor. Have you tried my WSGI implementation for Nginx? http://hg.mperillo.ath.cx/nginx/mod_wsgi/ Its not a general purpose solution, but it can be of interest. > On the Python side it supports WSGI > (the server can handle the static and dynamic requests of MoinMoin with > a handful of lines), the DB API with blocking calls offloaded to a > connection in a separate thread (MySQL, SQLite supported), Google's > ctemplate, gzipping responses, file caching, reading and writing to URIs > as a client, AJAX integration, debugging as a Python extension, and a > lot of other features. The core Python API is event-driven, using > continuations like Twisted but much cleaner (continuations are any > callables, there are no special objects anywhere). The Python back end > also supports Stackless Python so all of the continuation machinery can > be hidden behind tasklet switching. > I have recently added support for asynchronous application. There are two examples: an application that execute a query to PostgreSQL and an application that execute an HTTP request with pycurl: http://hg.mperillo.ath.cx/nginx/mod_wsgi/file/tip/examples/nginx-postgres- async.py http://hg.mperillo.ath.cx/nginx/mod_wsgi/file/tip/examples/nginx-curl.py Note that ngx.poll extension is still experimental. > [...] Manlio Perillo From sturlamolden at yahoo.no Sat Mar 22 09:43:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 06:43:33 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: On 22 Mar, 09:31, Bryan Olson wrote: > Even a hash function that behaves as a random oracle has > worst-case quadratic-time in the algorithm here In which case inserts are not amortized to O(1). From martin at v.loewis.de Fri Mar 7 02:43:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 07 Mar 2008 08:43:36 +0100 Subject: Python GDB Wrapper In-Reply-To: References: Message-ID: <47d0f228$0$17725$9b622d9e@news.freenet.de> > Has anyone does this before ? Even some basic idea or code as to how > to proceed would be great. Have you seen Misc/gdbinit? Regards, Martin From mdboldin at gmail.com Mon Mar 3 22:42:12 2008 From: mdboldin at gmail.com (mmm) Date: Mon, 3 Mar 2008 19:42:12 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> Message-ID: <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> > > Hence (if I understand python convention), this can be > > solved by adding > > sqlx= copy.copy(sqlx) > > before the looping. And in tests adding this step saved about 5-10% in > > time. > > Now this I don;t really understand at all. What's the point of trying to > replace sqlx with a copy of itself? Perhaps if you explained what you > hope this will achieve I could comment more intelligently. > I am/was attempting to convert sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) to code that did to need to be re-evaluated. i.e. to insert the dtable and ph values as if they were hard coded. copy.copy --> A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. From gabriel.rossetti at mydeskfriend.com Wed Mar 26 04:51:57 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Wed, 26 Mar 2008 09:51:57 +0100 Subject: Strange loop behavior In-Reply-To: <47EA0ABB.3030804@mydeskfriend.com> References: <47EA0ABB.3030804@mydeskfriend.com> Message-ID: <47EA0EAD.3010006@mydeskfriend.com> Gabriel Rossetti wrote: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > I also tried writing the while's condition like so : len(d) > 0, but > that doesn't change anything. I tried step-by-step debugging using > PyDev(eclipse plugin) and I noticed this, once the while was read once, > it is never re-read, basically, the looping does happen, but just in > between the two lines in the loop's body/block, it never goes on the > while and thus never verifies the condition and thus loops forever. I > had been using psyco (a sort of JIT for python) and so I uninstalled it > and restarted eclipse and I still get the same thing. This looks like > some bug, but I may be wrong, does anybody understand what's going on here? > > Thanks, > Gabriel > > PS > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. > > Ok, I get it, the repr() function actually returns a string with quote characters around it, thus the length is never 0, but 2. The reason I began using the repr() function is that the str() and unicode() constructors didn't accept the data read, because it was bigger than ord(128) (or something like that. I'm trying to read a binary file and put it's contents in an xml message to send via the network, so that I can re-create it on the other side. I do need to keep the xml aspect though. Is there a better way of doing this? Thanks, Gabriel From wmcbrine at users.sf.net Sun Mar 16 12:25:56 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sun, 16 Mar 2008 16:25:56 GMT Subject: When file-like objects aren't file-like enough for Windows Message-ID: This is proving to be a recurring problem for me. First, I used the save() method of a Python Imaging Library "Image" object to write directly to the "wfile" of a BaseHTTPRequestHandler- derived class: pic.save(self.wfile, 'JPEG') Worked great in Linux, barfed in Windows. I had to do this to get around it: out = StringIO() pic.save(out, 'JPEG') encoded = out.getvalue() self.wfile.write(encoded) Now, I have a similar problem with subprocess.Popen... The code that works in Linux looks like this: source = urllib.urlopen(url) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) try: shutil.copyfileobj(child.stdout, self.wfile) except: kill(child.pid) But wfile isn't the problem this time; instead, it's the source: ... child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) File "C:\Python25\lib\subprocess.py", line 586, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Python25\lib\subprocess.py", line 698, in _get_handles p2cread = msvcrt.get_osfhandle(stdin.fileno()) IOError: [Errno 9] Bad file descriptor How can I get around this, short of resorting to copying all of the input before passing it to the child? -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From __peter__ at web.de Mon Mar 3 07:04:12 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Mar 2008 13:04:12 +0100 Subject: Delete hidden files on unix References: Message-ID: loial wrote: > How can I delete hidden files on unix with python, i.e I want to do > equivalent of > > rm .lock* >>> for fn in glob.glob(".lock*"): ... os.remove(fn) ... Peter From michael.wieher at gmail.com Sun Mar 16 10:12:24 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:12:24 -0500 Subject: Advantage of the array module over lists? In-Reply-To: References: Message-ID: I believe the array module provides more functionality than lists. Perhaps this extra functionality comes with... overhead? C'est possible. For example, you can declare an array to contain all items of a type, ie: >>array.array('f') #array of floats So, they might be efficient, in that they're more efficient than wrapping lists on your own, if you *need* the extra power they provide. Not sure. 2008/3/16, Arnaud Delobelle : > > Tobiah writes: > > > I checked out the array module today. It claims that > > arrays are 'efficient'. I figured that this must mean > > that they are faster than lists, but this doesn't seem > > to be the case: > > > > ################ one.py ############## > > import array > > > > a = array.array('i') > > > > for x in xrange(10000000): > > a.append(x) > > > > for x in a: > > a[x] += 1 > > > > ################ two.py ############## > > a = [] > > > > for x in xrange(10000000): > > a.append(x) > > > > for x in a: > > a[x] += 1 > > > > ###################################### > > > > > > ktops:toby:pytest> time python one.py; time python two.py > > > > real 0m28.116s > > user 0m17.504s > > sys 0m10.435s > > > > real 0m23.026s > > user 0m13.027s > > sys 0m9.777s > > > > > > Perhaps the only advantage is that they take less memory > > to store a large number of items? It would seem then, that > > 'economical' might have been a better choice of word than > > 'efficient'. > > I get an even bigger difference with this test (same as yours, but > using timeit and using an allegedly more efficient way of initialising > the array) > > >>> def test(arr, n): > ... a = arr(xrange(n)) > ... for x in a: > ... a[x] += 1 > ... > >>> n = 10000000 > >>> import timeit > >>> timeit.Timer('test(list, n)', 'from __main__ import test, > n').timeit(1) > 2.4988760948181152 > >>> from array import array > >>> arr = lambda n: array('i', n) > >>> timeit.Timer('test(arr, n)', 'from __main__ import test, arr, > n').timeit(1) > 5.7419960498809814 > >>> > > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Mar 28 19:18:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 20:18:46 -0300 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <3b584949-73a2-4c2b-aa28-8d1f6622cd8c@u10g2000prn.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 18:15:04 -0300, harryos escribi?: > if i were to calculate the euclidean distance in the above example how > should i go about it..? > should i replace > distance = abs(input_wk - weights[image, :]) > with something else? For a single 2D vector, math.hypot does what you want. But the above looks like a NumPy array; see this thread http://projects.scipy.org/pipermail/numpy-discussion/2007-April/027166.html -- Gabriel Genellina From dblubaugh at belcan.com Mon Mar 3 15:40:57 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 3 Mar 2008 15:40:57 -0500 Subject: FW: unable to download PyGEP Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380298E136@AWMAIL04.belcan.com> > ______________________________________________ > From: Blubaugh, David A. > Sent: Monday, March 03, 2008 3:39 PM > To: 'ryanjoneil at gmail.com' > Subject: unable to download PyGEP > > Dear Sir, > > I have been having issues installing PyGEP. I have tried the > following: > > at MS-DOS command prompt > > > cd C:\python25\PyGEP-0.3.0.dev-r117 > > > I then enter setup.py on command prompt. > > > > It then states that it could not find a module named setuptools in > order to install. Can you help me with this issue ?? Thanks!!!! > > > > David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shoeshive8 at yahoo.com.cn Fri Mar 28 18:17:37 2008 From: shoeshive8 at yahoo.com.cn (shoeshive8 at yahoo.com.cn) Date: Fri, 28 Mar 2008 15:17:37 -0700 (PDT) Subject: Sell Air Jordan 1 Retro-BMP Package Old Love New Love Edition China wholesale Message-ID: <97e4e31f-6520-47a1-a104-9aa7448404d6@d4g2000prg.googlegroups.com> www.shoeshive.net Wholesale R3 Wholesale R4 Wholesale NZ Wholesale R5 Wholesale Monser Wholesale OZ Wholesale Nike Trainers Wholesale Air Rift Shoes Air Max 87 Air Max 90 Air Max Ltd Air Max 95 Air Max 97 Air Max 2003 Air Max 360 at www.shoeshive.net Air Max Tn Nike Air Max 180 Nike Dunk SB Nike Men Dunk Low Nike Men Dunk High Nike Dunk Woman Nike Kids Shoes Nike Air Jordan Boy Shoes Nike Air Force Ls at www.shoeshive.net Nike Air Max Timberland Boots Timberland Kid Boots at www.shoeshive.net Timberland Mens Boots Womens Timberland Boots Puma Trainers Womens Puma Shoes Puma Mens Shoes Louis Vuitton Sneakers Louis Vuitton Shoes Nike Athletics Nike LeBron James 4 IV Nike Timberland Dunca & Misc Nike Air Foamposite Pro Nike Kevin Garnett Signature Nike Slow Track Shoes Nike Zoom Nike Boot Bapesta Shoes Bapesta Sneakers Adidas Adidas Star Adidas Superstar 35 th at www.shoeshive.net Annivers Adidas Adicolor Adidas NBA Adidas City at www.shoeshive.net Prada Sneakers Wholesale Prada Shoes High Cut Prada Gucci Wholesale Shoes Low Cut Gucci Sneakers High Cut Gucci Sneakers Gucci Woman Football Shoes Nike Football Shoes Adidas Football Shoes Ugg Boots Women Ugg Slipper Ugg Woman Shoes Dsquared Shoes Wholesale Mens Dsquared Sneakers Mauri Wholesale Shoes Sneakers Mauri Womens Shoes Wholesale Designer Womens Sandals Boots For Womens Nike Woman Shoes Women Air Max Shoes Nike Air Dordan Woman Shoes Dolce Gabbana Shoes Dolce Gabbana Sneakers Hogan Shoes Sale Cheap Hogan Sneakers Versace Sneakers at www.shoeshive.net Versace Shoes Wholesale Ed Hardy Sneakers Ed Hardy Wholesale Paciotti 4 US Paciotti 4 US Shoes Armani Shoes Wholesale Armani Sneakers Lacoste Shoes Lacoste Trainers Burberry Shoes Burberry Wholesale Shoes Boss Shoes Wholesale Greedy Genius Sneakers at www.shoeshive.net Greedy Genius Shoes Chanel Shoes Chanel Shoes Sale Cross Sandals Cross Sandals Converse Sneakers Converse Shoes Richmond Sneaker Richmond Wholesale Sneakers Just Cavalli Shoes Just Cavalli Shoes Dirk Bikkembergs Sneakers Shoes Dirk Bikkembergs at www.shoeshive.net From duncan.booth at invalid.invalid Mon Mar 17 12:03:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 16:03:19 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: > >> Here's a puzzle for those who think they know Python: >> >> Given that I masked out part of the input, which version(s) of Python >> might give the following output, and what might I have replaced by >> asterisks? > > There's too many variables -- at least five Python implementations > that I know of (CPython, Jython, PyPy, IronPython, and the Lisp-based > implementation that I can never remember the name of), and given that > this is an implementation-dependent feature it could have changed at > any time, in any version number (say, between minor releases). And > there's literally an infinite number of ways to get b equal to an int > with the value 1. True, there are a lot of variables, but perhaps not as many as you think. For example, you can't get that output from IronPython or PyPy (or at least not the versions I have kicking around) as they won't print 'yes!' for the first test. You are correct though it is possible with both CPython and Jython. > So I think unless somebody happens to have stumbled across this > behaviour, it's not predictable. > > But having said that, I'm going to take a stab in the dark: > > The line "b = ****" should be "b = int('1')" > > and the version is CPython 1.4. > > Am I close? > I don't have a copy of 1.4 to check so I'll believe you, but you can certainly get the output I asked for with much more recent versions. For the answer I actually want each asterisk substitutes for exactly one character. From bronger at physik.rwth-aachen.de Mon Mar 31 02:45:31 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 31 Mar 2008 08:45:31 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> <65anbqF2fg18bU1@mid.individual.net> Message-ID: <87r6drjss4.fsf@physik.rwth-aachen.de> Hall?chen! Bjoern Schliessmann writes: > Torsten Bronger wrote: > >> Emacs is generally not regarded as being convenient, however, it >> has very strong input methods. I type "\gtrless" and get "?", or >> "\forall" and get "?". Doesn't KNode support UTF-8? > I wonder where the point of this is. :) Why use fancy unicode > chars if they're not better to read (apart from not being readable > with every font) and require at least the same amount of > keypresses? Who wants to minimize the number of keypresses? We're not Perl after all. ;-) As a general rule of thumb in typography, more glyph forms increase readability. APL is not readable at all but this is due to its syntax I suppose. I find hdante's excerpt very readable. The only reason why we don't use those special characters is that they aren't ASCII. While ? or ? are questionable because Python prefers English words instead of scientific symbols, ? or ? would be certainly more legible than != or <=. But they are not ASCII, so there is no net benefit. However, I'm quite sure that when Unicode has arrived almost everywhere, some languages will start considering such characters in their core syntax. Python 3.0 allows for Unicode letters in identifiers, and there's still room for improvement. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From pradiprai at gmail.com Mon Mar 31 06:49:12 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 16:19:12 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Yes, i have copied everything from site-packages of the old one to the new one. Regards, Pradeep -On [20080331 12:29], Pradeep Rai (pradiprai at gmail.com) wrote: >I have upgraded python v2.5.2 from python v2.4.3. The upgradation >results into following error: "Python C API version mismatch for module >dbi: This Python has API version 1013, module dbi has version 1012." Did you copy everything from site-packages of the old one to the new one? -- Jeroen Ruigrok van der Werven / asmodai CF[ EtbN @ f EFF *http://www.in-nomine.org/* | * http://www.rangaku.org/* If you're afraid of dyin', then you're holding on. You see devils tearing your life away. But if you have made your peace, then the devils are really angels, freeing you from the earth... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 14 09:06:30 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Mar 2008 14:06:30 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: <47da7812$0$31760$426a74cc@news.free.fr> Dave Kuhlman a ?crit : > Arnaud Delobelle wrote: > >> 4. Both points above follow from the fact that foo.bar is really a >> function call that returns a (potentially) new object: in fact what >> really happens is something like > > Arnaud and Imri, too - > > No. foo.bar is *not* really a function/method call. > >> Foo.__dict__['bar'].__get__(foo, Foo). >> >> So every time foo.bar is executed an object is (or may be) created, >> with a new id. >> >> HTH > > I appreciate the help, but ... > > Actually, it does not help, because ... > > My understanding is that foo.bar does *not* create a new object. Given your implementation, foo.bar *does* create a new object on each lookup. This object is an instancemethod instance, that is, a thin wrapper around Foo, foo and Foo.__dict__['bar']. Foo.__dict__['bar'] is a function instance, it's an attribute of class Foo, and the function class implements the descriptor protocol. So when bar is looked on a Foo instance, bar.__get__ is called with foo and Foo as arguments, and returns an instancemethod instance that has .im_self bound to foo, .im_class bound to Foo, and .im_func bound to Foo.__dict__['bar']. > All it > does is return the value of the bar attribute of object foo. Yes. But since function bar is a descriptor, foo.bar is a computed attribute, which value is a newly created instancemethod object. > What new > object is being created? An instancemethod. > If I have: > > class Foo(object): > def bar(self): pass > > > And I do: > > foo = SomeClass() > > then: > > foo.bar > > should return the same (identical) object everytime, no? yes? No. > I'm still confused. Then you have to learn how attribute lookup works in Python. From jzgoda at o2.usun.pl Tue Mar 25 11:04:09 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Mar 2008 16:04:09 +0100 Subject: sendmail should throw an exception but does not In-Reply-To: References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> <20080325102113.d8688b7f.darcy@druid.net> Message-ID: Clodoaldo napisa?(a): > That email address is used to register in a site. I'm already doing > the confirmation email path. The confirmation email prevents someone > to register with a forged email but also prevents those who simple > don't know exactly what their email is. Yes the email must be typed > twice but still people get the email wrong just because they don't > know for sure what it is. I can see it clearly when they mistype the > correct domain. > > It happens that atracting those people is expensive and i can't afford > to loose them. Thats why i would like to check the email at > registration time. Also those who try to register with a forged email > would learn that the email must be confirmed and could then issue a > correct email. > > I guess it is not possible or is too complex because i never saw it done. Good guess -- this is not possible until you (or your server) actually send an email. You can send a big "THANKYOU" to spammers, because their activity caused nearly all mail server admins to disable VRFY command that is supposed to do what you need. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From arkanes at gmail.com Tue Mar 11 15:03:57 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 11 Mar 2008 14:03:57 -0500 Subject: Obtaining the PyObject * of a class In-Reply-To: References: Message-ID: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. From steven.klass at gmail.com Sun Mar 23 17:04:24 2008 From: steven.klass at gmail.com (rh0dium) Date: Sun, 23 Mar 2008 14:04:24 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> Message-ID: <17e6ca72-0b61-45a4-9604-dda4029ba5eb@e23g2000prf.googlegroups.com> On Mar 23, 1:48?pm, rh0dium wrote: > On Mar 23, 12:26?am, Paul McGuire wrote: > > > > > There are a couple of bugs in our program so far. > > > First of all, our grammar isn't parsing the METAL2 entry at all. ?We > > should change this line: > > > ? ? md = mainDict.parseString(test1) > > > to > > > ? ? md = (mainDict+stringEnd).parseString(test1) > > > The parser is reading as far as it can, but then stopping once > > successful parsing is no longer possible. ?Since there is at least one > > valid entry matching the OneOrMore expression, then parseString raises > > no errors. ?By adding "+stringEnd" to our expression to be parsed, we > > are saying "once parsing is finished, we should be at the end of the > > input string". ?By making this change, we now get this parse > > exception: > > > pyparsing.ParseException: Expected stringEnd (at char 1948), (line:54, > > col:1) > > > So what is the matter with the METAL2 entries? ?After using brute > > force "divide and conquer" (I deleted half of the entries and got a > > successful parse, then restored half of the entries I removed, until I > > added back the entry that caused the parse to fail), I found these > > lines in the input: > > > ? ? fatTblThreshold ? ? ? ? ? ? ? ? = (0,0.39,10.005) > > ? ? fatTblParallelLength ? ? ? ? ? ?= (0,1,0) > > > Both of these violate the atflist definition, because they contain > > integers, not just floatnums. ?So we need to expand the definition of > > aftlist: > > > ? ? floatnum = Combine(Word(nums) + "." + Word(nums) + > > ? ? ? ? Optional('e'+oneOf("+ -")+Word(nums))) > > ? ? floatnum.setParseAction(lambda t:float(t[0])) > > ? ? integer = Word(nums).setParseAction(lambda t:int(t[0])) > > ? ? atflist = Suppress("(") + delimitedList(floatnum|integer) + \ > > ? ? ? ? ? ? ? ? Suppress(")") > > > Then we need to tackle the issue of adding nesting for those entries > > that have sub-keys. ?This is actually kind of tricky for your data > > example, because nesting within Dict expects input data to be nested. > > That is, nesting Dict's is normally done with data that is input like: > > > main > > ? Technology > > ? Layer > > ? ? PRBOUNDARY > > ? ? METAL2 > > ? Tile > > ? ? unit > > > But your data is structured slightly differently: > > > main > > ? Technology > > ? Layer PRBOUNDARY > > ? Layer METAL2 > > ? Tile unit > > > Because Layer is repeated, the second entry creates a new node named > > "Layer" at the second level, and the first "Layer" entry is lost. ?To > > fix this, we need to combine Layer and the layer id into a composite- > > type of key. ?I did this by using Group, and adding the Optional alias > > (which I see now is a poor name, "layerId" would be better) as a > > second element of the key: > > > ? ? mainDict = dictOf( > > ? ? ? ? Group(Word(alphas)+Optional(quotedString)), > > ? ? ? ? Suppress("{") + attrDict + Suppress("}") > > ? ? ? ? ) > > > But now if we parse the input with this mainDict, we see that the keys > > are no longer nice simple strings, but they are 1- or 2-element > > ParseResults objects. ?Here is what I get from the command "print > > md.keys()": > > > [(['Technology'], {}), (['Tile', 'unit'], {}), (['Layer', > > 'PRBOUNDARY'], {}), (['Layer', 'METAL2'], {})] > > > So to finally clear this up, we need one more parse action, attached > > to the mainDict expression, that rearranges the subdicts using the > > elements in the keys. ?The parse action looks like this, and it will > > process the overall parse results for the entire data structure: > > > ? ? def rearrangeSubDicts(toks): > > ? ? ? ? # iterate over all key-value pairs in the dict > > ? ? ? ? for key,value in toks.items(): > > ? ? ? ? ? ? # key is of the form ['name'] or ['name', 'name2'] > > ? ? ? ? ? ? # and the value is the attrDict > > > ? ? ? ? ? ? # if key has just one element, use it to define > > ? ? ? ? ? ? # a simple string key > > ? ? ? ? ? ? if len(key)==1: > > ? ? ? ? ? ? ? ? toks[key[0]] = value > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? # if the key has two elements, create a > > ? ? ? ? ? ? ? ? # subnode with the first element > > ? ? ? ? ? ? ? ? if key[0] not in toks: > > ? ? ? ? ? ? ? ? ? ? toks[key[0]] = ParseResults([]) > > > ? ? ? ? ? ? ? ? # add an entry for the second key element > > ? ? ? ? ? ? ? ? toks[key[0]][key[1]] = value > > > ? ? ? ? ? ? # now delete the original key that is the form > > ? ? ? ? ? ? # ['name'] or ['name', 'name2'] > > ? ? ? ? ? ? del toks[key] > > > It looks a bit messy, but the point is to modify the tokens in place, > > by rearranging the attrdicts to nodes with simple string keys, instead > > of keys nested in structures. > > > Lastly, we attach the parse action in the usual way: > > > ? ? mainDict.setParseAction(rearrangeSubDicts) > > > Now you can access the fields of the different layers as: > > > ? ? print md.Layer.METAL2.lineStyle > > > I guess this all looks pretty convoluted. ?You might be better off > > just doing your own Group'ing, and then navigating the nested lists to > > build your own dict or other data structure. > > > -- Paul > > Hi Paul, > > Before I continue this I must thank you for your help. ?You really did > do an outstanding job on this code and it is really straight forward > to use and learn from. ?This was a fun weekend task and I really > wanted to use pyparsing to do it. ?Because this is one of several type > of files I want to parse. ?I (as I'm sure you would agree) think the > rearrangeSubDicts is a bit of a hack but never the less absolutely > required and due to the limitations of the data I am parsing. ? Once > again thanks for your great help. ?Now the problem.. > > I attempted to use this code on another testcase. ?This testcase had > tabs in it. ?I think 1.4.11 is missing the expandtabs attribute. ?I > ran my code (which had tabs) and I got this.. > > AttributeError: 'builtin_function_or_method' object has no attribute > 'expandtabs' > > Ugh oh. ?Is this a pyparsing problem or am I just an idiot.. > > Thanks again! Doh!! Nevermind I am an idiot. Nope I got it what a bonehead.. I needed to tweak it a bit to ignore the comments.. Namely this fixed it up.. mainDict = dictOf( Group(Word(alphas)+Optional(quotedString)), Suppress("{") + attrDict + Suppress("}") ) | cStyleComment.suppress() Thanks again. Now I just need to figure out how to use your dicts to do some work.. From castironpi at gmail.com Mon Mar 31 20:51:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 17:51:48 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> Message-ID: <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> On Mar 31, 7:14?pm, 7stud wrote: > On Mar 31, 5:31?pm, castiro... at gmail.com wrote: > > > Can you have a Python object stored entirely on disk? > > import cPickle as cp > > class Dog(object): > ? ? def __init__(self, name): > ? ? ? ? self.name = name > > d = Dog("Spot") > > f = open("data.txt", "w") > cp.dump(d, f) > f.close() > > f = open("data.txt") > stored_obj = cp.load(f) > print stored_obj.name > > --output:-- > Spot >>> import pickle >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps Pickler(f, protocol).dump(obj) File "C:\Programs\Python\lib\pickle.py", line 221, in dump self.save(obj) File "C:\Programs\Python\lib\pickle.py", line 283, in save f(self, obj) # Call unbound method with explicit self File "C:\Programs\Python\lib\pickle.py", line 697, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle : it's not found as __ main__.None >>> From castironpi at gmail.com Wed Mar 5 17:08:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 14:08:28 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> Message-ID: On Mar 5, 3:38?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: > > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: > >> castiro... at gmail.com schrieb: > > >> > I want to hash values to keys. ?How do the alternatives compare? > > >>http://catb.org/~esr/faqs/smart-questions.html > > > ... without extending the whole way to a full relational database? > > You didn't bother following the link and reading the advice, did you? If > you did, you haven't done a good job of following that advice. Well, obviously there's someone who's interested in computers and programming that has a question. Communication is not his forte, but effort, willingness, devotion, and dedication are. What should he do, and what should the others, who are gifted speakers? From pavlovevidence at gmail.com Mon Mar 31 13:59:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 31 Mar 2008 10:59:12 -0700 (PDT) Subject: troll poll References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> Message-ID: <199c5242-f561-4c51-a96b-428abe6f9d80@f63g2000hsf.googlegroups.com> On Mar 31, 1:41 pm, Paul Rubin wrote: > "Daniel Fetchinson" writes: > > [ ] - Xah Lee > > [ ] - castironpi > > I've lost track but has it been established that they are not the same > person? Has it been established that castironpi is a person at all? Carl Banks From jeff at schwabcenter.com Wed Mar 5 11:26:04 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 05 Mar 2008 08:26:04 -0800 Subject: OT[1]: Re: SV: Polymorphism using constructors In-Reply-To: <13ssb8fph6nkoff@corp.supernews.com> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> <13ssb8fph6nkoff@corp.supernews.com> Message-ID: <29WdncFY4qn0VFPanZ2dnUVZ_ournZ2d@comcast.com> Dennis Lee Bieber wrote: > On Tue, 4 Mar 2008 20:06:38 -0500, Tommy Grav declaimed > the following in comp.lang.python: > >> SV = "Svar" is the Norwegian word for Reply. >> > Ah, good... In my working life, "SV" => "Space Vehicle", often used > to differentiate between the base satellite and "PL" Payload (the part > that earns the money) Which is which? Aren't those both part of the space vehicle? Btw, do you work for government or industry? Do you enjoy working with the space program? I've heard only indirect reviews, and they've been mixed. [1] "Av Emne," according to the free online translater. http://www.tranexp.com:2000/Translate/result.shtml From arnodel at googlemail.com Mon Mar 24 10:41:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Mar 2008 07:41:16 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> <13ufd10ps50mm4a@corp.supernews.com> Message-ID: On Mar 24, 2:01?pm, Steven D'Aprano wrote: [...] > > Yes, but what I'm asking is why the code objects have a co_name > attribute. And even if there's a good reason for code objects to have a > name, why do tracebacks use func.func_code.co_name instead of > func.__name__? From what I remember when I looked at the source: stack frames execute code objects, not functions. They don't know what function has spawned them, only what code object they are executing. In fact when one thinks of it, it makes more sense for code objects to have a name (taken from the def statement) than for function objects, as there is exactly one code object for every def statement. -- Arnaud From jwbrown77 at gmail.com Thu Mar 27 15:41:56 2008 From: jwbrown77 at gmail.com (jwbrown77 at gmail.com) Date: Thu, 27 Mar 2008 12:41:56 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes Message-ID: Hello, I am trying to read a csv file. I have the following functioning code: ---- BEGIN ---- import csv reader = csv.reader(open("test.csv", "rb"), delimiter=';') for row in reader: print row ---- END ---- This code will successfully parse my csv file formatted as such: "this";"is";"a";"test" Resulting in an output of: ['this', 'is', 'a', 'test'] However, if I modify the csv to: "t"h"is";"is";"a";"test" The output changes to: ['th"is"', 'is', 'a', 'test'] My question is, can you change the behavior of the parser to only remove quotes when they are next to the delimiter? I would like both quotes around the h in the example above to remain, however it is instead removing only the first two instances of quotes it runs across and leaves the others. The closest solution I have found is to add to the reader command "escapechar='\\'" then manually add a single \ character before the quotes I'd like to keep. But instead of writing something to add those slashes before csv parsing I was wondering if the parser can handle it instead. Thanks in advance for the help. From bskaplan14 at yahoo.com Mon Mar 31 10:15:56 2008 From: bskaplan14 at yahoo.com (Ben Kaplan) Date: Mon, 31 Mar 2008 07:15:56 -0700 (PDT) Subject: TypeError with weakrefs Message-ID: <546869.58559.qm@web39213.mail.mud.yahoo.com> I'm working with weakrefs, and I keep getting a type error The exact line I am getting is Exception exceptions.TypeError: '__call__() takes exactly 0 arguments (1 given)' in ignored The strange part is that I am not trying to call anything. From debugging, I found out that the message is printed at this line: count = self.nb_add - self.nb_removed Has anyone seen this before? ____________________________________________________________________________________ OMG, Sweet deal for Yahoo! users/friends:Get A Month of Blockbuster Total Access, No Cost. W00t http://tc.deals.yahoo.com/tc/blockbuster/text2.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From attn.steven.kuo at gmail.com Tue Mar 11 22:30:21 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Tue, 11 Mar 2008 19:30:21 -0700 (PDT) Subject: Time Zone application after strptime? References: <47D1B703.6040200@egenix.com> Message-ID: On Mar 11, 11:00 am, Jim Carroll wrote: (snipped) > > p.parse("10:29:52 Feb 29, 2008 PST", tzinfos=zones) > datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800)) > > But I cannot figure out how to get dateutil to use the > zoneinfo file that it includes in its own package. It has a > zoneinfo-2007k.tar.gz right in the package, and a class > to parse the binary zoneinfo, but no clear way to get it to > parse its own file and use those during the parsing. Try the pytz module. import datetime import pytz import time utc = pytz.utc zones = { 'PST': pytz.timezone('US/Pacific'), } aware_dt = datetime.datetime(tzinfo=zones['PST'], *time.strptime("10:29:52 Feb 29, 2008 PST", "%H:%M:%S %b %d, %Y %Z")[0:6]) print aware_dt.strftime("%H:%M:%S %b %d, %Y %Z") print utc.normalize(aware_dt.astimezone(utc)).strftime("%H:%M:%S %b %d, %Y %Z") # 10:29:52 Feb 29, 2008 PST # 18:29:52 Feb 29, 2008 UTC -- Hope this helps, Steven From lists at js3d.co.uk Tue Mar 25 10:57:46 2008 From: lists at js3d.co.uk (Jules Stevenson) Date: Tue, 25 Mar 2008 14:57:46 -0000 Subject: dynamically created names / simple problem Message-ID: <000c01c88e88$96c29490$0600a8c0@laptop> Hello all, I'm fairly green to python and programming, so please go gently. The following code for display in secondary: self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") Errors, because of the apparent nastyness at the beginning. What I'm trying to do is loop through a list and create uniquely named wx widgets based on the list values. Obviously the above doesn't work, and is probably naughty - what's a good approach for achieving this? Many thanks, Jules -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Mon Mar 10 18:14:24 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 10 Mar 2008 23:14:24 +0100 Subject: building arbitrary files with distutils? In-Reply-To: References: Message-ID: <47D5B2C0.9010202@v.loewis.de> > How can I add such commands (including timestamp checking) to a setup.py file, > so that it runs when I call 'python setup.py build' ? I can write python > functions to perform those command, and I found timestamp checking functions > in distutils.dep_util, but just can't find the way to connect such commands > to the build step.... Take a look at the build_ext command. It considers all Extension objects (in build_extensions), and for each one, it does dependency checking (in build_extension). It uses the newer_group machinery. More generally, in the run method of your command, just don't do anything (except perhaps logging) if you find your outputs are up-to-date. Multi-level dependencies aren't quite supported with that approach; you can either make multiple commands that one has to run in sequence (or use subcommands), or you put it all in a single run method which sequentially first tries to generate the intermediate outputs (doing nothing if they are up-to-date), and then the final outputs (doing nothing when they are newer than the intermediate ones). HTH, Martin From bignose+hates-spam at benfinney.id.au Fri Mar 28 22:16:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 29 Mar 2008 13:16:07 +1100 Subject: Help me on function definition References: Message-ID: <87tziqtguw.fsf@benfinney.id.au> "aeneng" writes: > I am just starting to use python in numerical cacluation. Welcome, and congratulations on learning Python. > I need you to help me to see what's wrong with the following piece > of codes [...] Your code is rather difficult to read, since your expressions have all the characters mashed together without spaces. It will help others who read your code if you follow the Python coding guidelines in PEP 8 . You should also choose names that are descriptive when someone reads the code, and not single-character algebraic names. > when I import the function, error message show like this > >>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? I suspect you will gain enlightenment in this case by running your code via 'python -t foo.py' where 'foo.py' is the Python module you're trying to run. (You can see a description of that option with 'python -h' to display the commandline help.) -- \ "I have one rule to live by: Don't make it worse." -- Hazel | `\ Woodcock | _o__) | Ben Finney From castironpi at gmail.com Wed Mar 5 23:35:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 20:35:02 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> <7a8a2706-10d0-4f50-b5ad-8b490e57edd5@y77g2000hsy.googlegroups.com> <44a11efa-f1d7-458c-93f0-f0d6f744dfcd@m34g2000hsc.googlegroups.com> Message-ID: On Mar 5, 9:51?pm, castiro... at gmail.com wrote: > > > > If I understand your question, classes are not singletons: > > > >>>> ll=[] > > > >>>> for i in range(2): > > > > ?import string > > > > ?ll[i]=string > > > > Where's the IndexError? :-) > > > > I accept my question about classes being singletons is not well-formed, > > > not even in my own mind. I guess one way of asking is, for any two class > > > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? > > Similarly, no. > > >>> class metaC( type ): > > ... ? ? def __eq__( self, other ): > ... ? ? ? ? ? ? return True > ...>>> class C( metaclass= metaC ): > > ... ? ? pass > ...>>> class D( metaclass= metaC ): > > ... ? ? pass > ...>>> C==D > True > >>> C is D > > False > > +1 raised eyebrow Well, you're not going to believe me, but a "bar" just had an idea. Don't forget: class C( metaclass= metaC ) class metaC( metaclass= metametaC ) class metametaC( type ): bor hor hor. Now for the academics, is it telling a joke? If so, that's pretty fine--- but. From stef.mientki at gmail.com Wed Mar 19 17:18:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 19 Mar 2008 22:18:42 +0100 Subject: Is this valid ? Message-ID: <47E18332.9030202@gmail.com> hello, by accident I typed a double value test, and to my surprise it seems to work. Is this valid ? a = 2 b = 2 a == b == 2 thanks, Stef Mientki From castironpi at gmail.com Wed Mar 5 15:04:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 12:04:30 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> Message-ID: On Mar 5, 1:29?pm, Paul McGuire wrote: > On Mar 5, 12:50?pm, castiro... at gmail.com wrote: > > > What is a class that is not a module? > > Please stop posting these one-liner beginner questions. ?If you can > type it in one line, you can enter it on the Google.com or Ask.com > query page and get a wealth of *existing* information, from tutorials, > documentation, online presentations. ?If you are able to phrase such a > question, you are capable of doing a little research and > experimentation on your own. > > These posts translate to "I'm too lazy to use Google, or too cheap to > buy a Python book, or too lazy to read it, or too impatient to do my > own experimenting - much better to just post on c.l.py and have the > answer spoon-fed to me!" > > I refuse to spoon feed you the answer to this question when plenty of > supporting material is already available. In the future, shall I assume that other readers here have no ideas (on this, read *ever*), that haven't already been published? 'Cause I have. For instance, in this example, I've tried a few approaches that didn't turn out well. Do you want a comparison of existing solutions? Do you have a proof that they exhaust the solution space? I'm willing to address convention, in serial or parallel--- (change subject to 'what goes on newsgroups'?), but it's not clear from fact what assumption who has made. Next time, why don't you say, "How much experience do you have?", or "What level should I gear my answer toward?" From aaron.watters at gmail.com Sat Mar 8 17:13:14 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Sat, 8 Mar 2008 14:13:14 -0800 (PST) Subject: off topic: 2 videos on source control and open source development Message-ID: <8a36442e-c4e6-421d-aff9-a3334ee59592@u69g2000hse.googlegroups.com> I just wanted to send out links to 2 informative videos regarding open source and change control systems. The first is Linus Torvalds on git and how it contrasts with subversion and other approaches (where he says some nice things about Mercurial, btw). http://www.youtube.com/watch?v=4XpnKHJAok8 This one is about managing the community dynamics in the subversion project. http://video.google.nl/videoplay?docid=-4216011961522818645 It only made me a little uncomfortable at certain moments :). Good viewing. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=mileage From robert.kern at gmail.com Fri Mar 7 17:20:26 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 07 Mar 2008 16:20:26 -0600 Subject: distutils - Is is possible to install without the .py extensions In-Reply-To: References: Message-ID: Jari Aalto wrote: > Given following setup.py stanza: > > #!/usr/bin/python > > from distutils.core import setup > import glob > > setup(name='program', > description='', > keywords='', > version='', > url='', > download_url='', > license='', > author='', > author_email='', > long_description=""" > """, > scripts = ['program,py'], > packages = ['''], > ) > > Is there any way to fix the installation (postinstall or something), so > that the the result is: > > /usr/bin/program > > instead of: > > /usr/bin/program.py The easiest and best way is to just rename the file in your source tree to "program" and be done with it. -- 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 castironpi at gmail.com Sat Mar 1 22:22:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 19:22:03 -0800 (PST) Subject: Question about lambda and variable bindings References: Message-ID: <7d745a9b-5038-4f8d-9400-14feb5cc19a0@8g2000hse.googlegroups.com> On Mar 1, 8:50?pm, Michael Torrie wrote: > I need to use a lambda expression to bind some extra contextual data > (should be constant after it's computed) to a call to a function. ?I had > originally thought I could use something like this demo (but useless) code: > > funcs=[] > > def testfunc(a,b): > ? ? print "%d, %d" % (a,b) > > for x in xrange(10): > ? ? funcs.append(lambda p: testfunc(x+2,p)) > > Now what I'd like is to call, for example, funcs[0](4) and it should > print out "2,4". ?In other words I'd like the value of x+2 be encoded > into the lambda somehow, for funcs[x]. ?However the disassembly shows > this, which is reasonable, but not what I need: > > >>> dis.dis(funcs[0]) > > ? 2 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (testfunc) > ? ? ? ? ? ? ? 3 LOAD_GLOBAL ? ? ? ? ? ? ?1 (x) > ? ? ? ? ? ? ? 6 LOAD_CONST ? ? ? ? ? ? ? 0 (2) > ? ? ? ? ? ? ? 9 BINARY_ADD > ? ? ? ? ? ? ?10 LOAD_FAST ? ? ? ? ? ? ? ?0 (p) > ? ? ? ? ? ? ?13 CALL_FUNCTION ? ? ? ? ? ?2 > ? ? ? ? ? ? ?16 RETURN_VALUE > > The LOAD_GLOBAL 1 (x) line is definitely a problem. ?For one it refers > to a variable that won't be in scope, should this lambda be called from > some stack frame not descended from the one where I defined it. > > So how can I create a lambda expression that calculates a constant based > on an expression, rather than referring to the object itself? ?Can it be > done? > > Michael I hate that. Especially since ints are immutable. >>> from functools import partial >>> funcs= [ partial( print, x ) for x in range( 10 ) ] >>> for func in funcs: ... func() ... 0 1 2 3 4 5 6 7 8 9 >>> takes advantage of 2.5+ functools.partial and 3.0 print. You can use sys.stdout instead of print in the example in 2.5, but without partial, you're at: class Val: def __init__( self, val ): self.val= val def __call__( self ): self.val+= 10 val= Val( 20 ) val() . There's also a CellMaker implementation somewhere on Py-Ideas, but it was outlawed in 18 provinces, and it just evaluates and compiles a string anyway. for x in xrange(10): fun= exec( 'lambda p: testfunc(%i+2,p)'% x ) funcs.append( fun ) From jeff at schwabcenter.com Tue Mar 18 00:44:05 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 21:44:05 -0700 Subject: First Program Bug (Newbie) In-Reply-To: References: Message-ID: Benjamin Serrato wrote: > P.S. What is the chance I'll get spam for using my real email address? Fendi Chef Bag in Zucca Print - Black Trim Replica AAA, Fake HandBags Cheap Chef Bag in Zucca Print - Black Trim Bags Link : http://www.cnreplicas.com/Fendi_1439.html Chef Bag in Zucca Print - Black Trim Price : $ 170.00 Fendi Hand Bags Link : http://www.cnreplicas.com/Fendi_Replica_Bags.html Replica handbags Home : http://www.cnreplicas.com/ Chef Bag in Zucca Print - Black Trim ,one model of Fendi hand Bags, the most popular designer handbags. You can get top grade Replica Chef Bag in Zucca Print - Black Trim knockoffs at favorable price . Chef Bag in Zucca Print - Black Trim Detailed information : 73f Accessorize in five-star style with this fabulous chef bag from Fendi. The brown and tan signature Fendi print is accented a gathered body adding a sophisticated touch of class. Additional features:Zucca jacquard withblack color patent leather trimBrushed metal hardwareRolled patent handles with ring attachments; 8.75" dropPatent band encircles bag with pintucked gathers along seamFrame topZip closure with oversized Fendi-etched metal pullFine textile liningInterior leather-trimmed zip pocket, cellphone pocket, interior multifunctionpocketSerial numberComes with Fendi dust cover and care bookletActual size: 16.5" x 5.9" x 10.2" c34 Buy the cheapest Chef Bag in Zucca Print - Black Trim in toppest Replica . www.cnreplicas.com helps you to save money! The Same Fendi Series : Chef Bag in Zucca Print - Brown Trim Bags : http://www.cnreplicas.com/Fendi_1440.html Crescent Hobo - Black Bags : http://www.cnreplicas.com/Fendi_1441.html Crescent Hobo - Chocolate Bags : http://www.cnreplicas.com/Fendi_1442.html Crescent Hobo - Cream Bags : http://www.cnreplicas.com/Fendi_1443.html Crescent Hobo - Silver Bags : http://www.cnreplicas.com/Fendi_1444.html Crossword Grande Mirrored bag - Gold Bags : http://www.cnreplicas.com/Fendi_1445.html Crossword Grande Mirrored bag - Silver Bags : http://www.cnreplicas.com/Fendi_1446.html Crossword Patent Clutch - Black Bags : http://www.cnreplicas.com/Fendi_1447.html Crossword Patent Clutch - Silver Bags : http://www.cnreplicas.com/Fendi_1448.html Crossword Patent Clutch - White Bags : http://www.cnreplicas.com/Fendi_1449.html Crossword Patent Clutch - Yellow Bags : http://www.cnreplicas.com/Fendi_1450.html Crossword Patent Clutch Multicolored Letters - Black Bags : http://www.cnreplicas.com/Fendi_1451.html From castironpi at gmail.com Wed Mar 19 03:38:00 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 19 Mar 2008 00:38:00 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: <56df6553-25af-4acb-9b78-a6f8407863c3@u69g2000hse.googlegroups.com> > >> > Can I allocate a second console window, so I can place certain output > >> > to that directly, and leave the original streams alone? ?I tried > >> Have you tried using the creationflags argument to subprocess.Popen? > >> Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation > >> for CreateProcess ? > >> athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx > >> (Note that a process can be attached at most to one console) > > > One console per process is fine, but I tried using 'cmd.exe', > > 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32) > > as separate processes. ?The sign is the console window splashes up and > > vanishes right away. > > Apparently you have to either redirect stdout AND stdin, or none of them. ? > This worked for me: > > p = subprocess.Popen('c:\\windows\\system32\\cmd.exe', > ? ? ? ? ?stdout=subprocess.PIPE, stdin=subprocess.PIPE, > ? ? ? ? ?creationflags=subprocess.CREATE_NEW_CONSOLE) > p.communicate("dir\n") This worked for me. import subprocess p = subprocess.Popen('c:\\windows\\system32\\cmd.exe', stdout=subprocess.PIPE, stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE) import time import threading def th(): while 1: time.sleep( .01 ) s= p.stdout.read(1) print( ':', end= '' ) if not s: continue print( s.decode(), end= '' ) import thread thread.start_new_thread( th, () ) time.sleep( 2 ) p.stdin.write( b'c:\\windows\\system32\\more.com\n' ) p.stdin.flush() print ( 'abc' ) while 1: time.sleep( 1 ) p.stdin.write( b'abc\n' ) p.stdin.flush() print ( 'abc' ) p.wait() time.sleep( 10 ) From noname9968 at gmail.com Thu Mar 27 07:04:53 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 14:04:53 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> Message-ID: <47EB7F55.8090909@gmail.com> Guilherme Polo wrote: > 2008/3/27, Alex9968 : > >> Guilherme Polo wrote: >> > 2008/3/26, Alex9968 : >> > >> >> Hi all, >> >> >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> >> using visual GUI designers), so my question is which other GUI toolkits >> >> have similar functionality. >> >> >> > >> > The geometry manager isn't related to using GUI designers tools at >> > all. And each toolkit has it's own way to do the things, wxPython uses >> > sizers, PyGtk uses containers. >> > >> >> Well, the geometry manager isn't *directly* related to using GUI >> designers, but as Pack arranges widgets automatically, using GUI >> designers isn't required, while with geometry managers that don't, GUI >> designers are necessary (if you start placing widgets programmatically, >> you'll end up reinventing something like Tkinter's Pack or Grid geometry >> manager). I hope I can be understood clearly this time ;-) >> > > Not at all, can't understand your point yet. GUI designers aren't just > for placing widgets, they also will keep the interface design > separated from your code. > I do not want to separate interface from code and I do not experience the need to use GUI designers. Pack arranges widgets perfectly, and it's very complex to do the same without it, both in code and in GUI designer. I wish toolkits I use to be able to place widgets one after another automatically. > >>>> Secondly, I like the detailed widget borders configuration possible in >>>> >> >> Tkinter, which can be used to tweak GUI look, and wonder if other >> >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) >> >> look in Windows, but I'm afraid it can be quite different (and ugly) on >> >> other platforms. >> >> >> > >> > You sure can, but differently. >> > >> >> I suppose any toolkit allows setting parameters like "no border", "flat >> border" and "3d border", but which ones can set ANY type of border to >> ANY widget like Tkinter does? For example set GROOVE border to buttons >> and text widgets (instead of traditional wide raised/lowered borders), >> which is cool (in my opinion). >> >> > > The widgets subclass some base class, which contains some common > methods which could be the border and relief for example. > In the case of PyGtk, border > width is controlled at Container, so most widgets will have this > feature, but the relief style of the widget is not common to all > widgets so you will need to check this one (Button has it). > In wxPython, widgets will subclass Window, which has all you want and more. > But PyQt doesn't seem to care much about this, you can change the > widget to flat (if it makes sense to that widget have setFlat method) > but not much related to the borders. > You could recheck your use-cases and see if they are acceptable. > > >> >> (The reason I ever consider moving from Tkinter is some inconveniences, >> >> involving for example window scrolling, plus its smaller amount of >> >> widgets compared to some other toolkits, plus its (rumored) ugly look on >> >> certain environments. I will not necessary change the toolkit, but I >> >> have to consider it) >> >> >> >> >> > >> > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into >> > Tkinter for upcoming GSoC. For now you could try using Tile extension, >> > and update to Tk 8.5. If you don't want to use extensions, then you >> > will have to wait or change the toolkit for now. >> > >> >> Thanks. I haven't heard of Tile before, now I will keep this in mind. >> You forgot to mention WHAT you're planning to solve ;-) , so I have to >> add that Tile is modernization of Tk widgets (so it fixes ugly look). >> >> > > WHAT I'm planning to solve, quote from my own paragraph: > "I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > Tkinter for upcoming GSoC." > > I would like to add the possibility to use Ttk widgets into tkinter, > providing you have Tk 8.5. It would solve the problem of "not enough > widgets" and the other one of "being ugly" mainly. Tk 8.5 also > auto-fixes some other problems, it provides smooth-scrolling for the > text widget, for example. But keep in mind that using Tk 8.5 in Python > is not yet supported (but possible). > I understood you. I added that sentence just to make it clear for anyone reading this. Your participation is appreciated greatly, thank you. From rbossy at jouy.inra.fr Tue Mar 4 10:10:27 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Tue, 04 Mar 2008 16:10:27 +0100 Subject: why not bisect options? In-Reply-To: References: Message-ID: <1204643427.47cd6663d4d9c@www.jouy.inra.fr> Quoting Raymond Hettinger : > [Robert Bossy] > > I thought it would be useful if insort and consorts* could accept the > > same options than list.sort, especially key and cmp. > > If you're going to do many insertions or searches, wouldn't it be > *much* more efficient to store your keys in a separate array? > > The sort() function guarantees that it calls the key function exactly > once for each member of the list. With and bisect/insort, successive > searches can call the key function over and over again with the same > value. I factored your remark into the code. I actually don't have any particular question about it, that's just an acknowledgment. Though I feel that if one uses the default key, then an awkward list of twins is stored... from operator import itemgetter def identity(x): return x class Bisect: def __init__(self, it, key=identity, cmp=cmp): self.lst = [ (key(x),x,) for x in it ] self.lst.sort(cmp=cmp, key=itemgetter(0)) self.key = key self.cmp = cmp def insort_right(self, x, lo = 0, hi = None): if hi is None: hi = len(self.lst) xk = self.key(x) while lo < hi: mid = (lo + hi) // 2 if self.cmp(xk, self.lst[mid][0]) < 0: hi = mid else: lo = mid + 1 self.lst.insert(lo, (kx,x,)) # skipped insort_left, bisect_right, bisect_left # also skipped the container methods __len__, __getitem__, __iter__ Cheers, RB From deets at nospam.web.de Sat Mar 22 10:07:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 15:07:22 +0100 Subject: [RFC] How to implement command line tool integrating parsing engine In-Reply-To: References: Message-ID: <64ki51F2a87ieU1@mid.uni-berlin.de> llandre schrieb: > Hi all, > > I'd like to have some advices about how to implement a program that has > the following requirements: > - it must run both on linux and windows PC > - it must interact with an electronic device connected to the PC through > serial cable by sending/receiving some command strings and taking > different actions depending on device responses; these strings and > actions must be described in a text file (a sort of script) editable by > user with a simple text editor; the language used to described this > algorithm should be as simple as possible > - initially the program must be written in the form of simple command > line tool that is invoked like this: > program > - in the future, it must be possible to develop a graphical frontend on > top of it; the resulting look&feel should be similar on linux and windows. > > In this mailing list I was adviced to use python: > http://thread.gmane.org/gmane.comp.boot-loaders.u-boot/37939 > > As I never used python, I ask you: > 1) about the script file, which language - for which a parsing engine is > already available in python - do you suggest? Don't use a home-made-language. Use python itself, together with a lib of pre-defined functions and hooks. Python can do the serial communication (google pyserial), and together with e.g. the execfile-command you can execute the user-provided commands after initializing your system. > 2) about the graphical frontend, which graphical libraries do you > recommend? Google this group for a PLETHORA of discussions about this very subject. The answer vary depending on usecase, taste & relative moon humidity. Diez From stefan_ml at behnel.de Mon Mar 10 03:56:26 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 08:56:26 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> Message-ID: <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> Matt Nordhoff wrote: > For what you do decide to rewrite in C, you can also use a language like > Cython [1] (which is a fork of Pyrex [2]). It looks mostly like Python, > and is translated to C without you having to write all of the > boilerplate Python C API stuff. Of course, not quite as efficient > well-tuned raw C, but much more pleasant to write. And if you really need the efficiency of "well-tuned raw C", it's one function call away in your Cython code. Stefan From benjamin.serrato at gmail.com Mon Mar 17 20:03:25 2008 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Mon, 17 Mar 2008 19:03:25 -0500 Subject: First Program Bug (Newbie) Message-ID: I Found It!! The following was a post asking for help finding a bug. I thought I needed help with my syntax, but just before sending I found the bug on line 13. Line 13 should read: "base = 2". I would still appreciate any comments on my program. Maybe there is a better way to do it that I didn't think about. I know it's not that interesting but it's my first one. [post] I'm almost halfway through an online tutorial I found on the python.org site and decided to stop and write a program for myself. I got it in my head to write a program to print all the primes; the idea came from another tutorial. The program prints some non-prime numbers. In a comparison to lists of primes the program prints eight non-primes for numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. Here is the program. base = 2 candidate = 3 while True: while candidate % base != 0: base = base + 1 if base > (candidate / 2): print candidate candidate = candidate + 1 base = 2 else: candidate = candidate + 1 The following is a rundown of the program. candidate: A possible prime number. base: Start point for divisibility testing. outer while loop: Causes the program to loop. inner while loop: Obviously, checks if 'candidate' mod 'base' equals zero. If not base is incremented by one then 'if loop'. if loop: After base has been incremented this checks whether all the possible divisors have been used up. If they have then 'candidate' must be prime. So, candidate is printed, a new candidate is chosen and the base is reset. else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is not prime and a new candidate is chosen. I realize yall probably didn't need all that. At first I tried to use 'return' on the 'else' block to cause the program to loop, but I don't understand 'return' yet and that didn't work. So, I put the rest into another while loop and was really happy to find it worked but the program prints some non-prime numbers. Thanks, Benjamin Serrato P.S. What is the chance I'll get spam for using my real email address? I currently don't get any so... [/post] From robert.rawlins at thinkbluemedia.co.uk Thu Mar 13 11:36:49 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 13 Mar 2008 15:36:49 -0000 Subject: "Attribute Doesnt Exist" ... but.... it does :-s Message-ID: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an awfully aggravating problem which is causing some substantial hair loss this afternoon J I want to get your ideas on this. I am trying to invoke a particular method in one of my classes, and I'm getting a runtime error which is telling me the attribute does not exist. I'm calling the method from within __init__ yet it still seems to think it doesn't exist. Code: # Define the RemoteDevice class. class remote_device: # I'm the class constructor method. def __init__(self, message_list=""): self.set_pending_list(message_list) def set_pending_list(self, pending_list): # Set the message list property. self.pending_list = message_list And the error message which I receive during the instantiation of the class: File: "/path/to/my/files/remote_device.py", line 22, in __init__ self.set_pending_list(message_list) AttributeError: remote_device instance has no attribute 'set_pending_list' Does anyone have the slightest idea why this might be happening? I can see that the code DOES have that method in it, I also know that I don't get any compile time errors so that should be fine. I know it mentions line 22 in the error, but I've chopped out a load of non relevant code for the sake of posting here. Perhaps I'm missing something really simple, but it's got my head spinning. Thanks, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From pianomaestro at gmail.com Fri Mar 28 10:51:10 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 07:51:10 -0700 (PDT) Subject: threads and extension module initialization Message-ID: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> I have an extension module that gets initialized multiple times because I am using threads. How can this module access global state (not per-thread state) ? It needs to create a singleton. Simon. From galaviel at yahoo.com Tue Mar 4 07:29:52 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Tue, 4 Mar 2008 12:29:52 +0000 (UTC) Subject: Removing default logging handler (causes duplicate logging) Message-ID: Hello All, I want to add a logger to my application, then addHandler to it to log to a special destination. Unfortunately when I use logging.getLogger("my_logger") to create the new logger, it apparently comes with a default handler that logs to STDOUT (or STDERR?). When I add my special handler it works Ok, but still logs to terminal, which I do not want. The only way I found to remove the default handler is by using 'logger.removeHandler(logger.handlers[0])'. Is there a more elegant solution that uses the logging API? my setup: Python 2.5.1 on Linux Suse 9. P.S.I am not using Basic config, just 'import logging' and then regular logging.* calls. Thanks in advance, Gal Aviel. From piet at cs.uu.nl Fri Mar 7 17:12:27 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 07 Mar 2008 23:12:27 +0100 Subject: float / rounding question References: Message-ID: >>>>> casevh (C) wrote: >C> On Feb 25, 2:44 am, helen.m.fl... at gmail.com wrote: >>> Hi I'm very much a beginner with Python. >>> I want to write a function to convert celcius to fahrenheit like this >>> one: >>> >>> def celciusToFahrenheit(tc): >>> tf = (9/5)*tc+32 >>> return tf >>> >>> I want the answer correct to one decimal place, so >>> celciusToFahrenheit(12) would return 53.6. >>> >>> Of course the function above returns 53.600000000000001. >>> >>> How do I format it correctly? >C> That is the normal behavior for binary (radix-2) numbers. Just like it >C> is impossible write 1/3 exactly as a decimal (radix-10) number, 536/10 >C> cannot be written exactly as a binary number. If you really need >C> decimal numbers, use the Decimal class. Sorry to come in so late in this discussion. Although it is correct to say that many real numbers that have an exact decimal representation cannot be exactly represented in binary, that is no excuse to print 53.6 as 53.600000000000001. This is just lousy printing and the fact that this kind of question comes up every week shows that it is confusing to many people. Python just uses the C library for printing, I presume, and the conversion routines in the C library are rather simplistic. It is, however, possible to do better, so that 53.6 -- although internally represented as something that could be described as 53.600000000000001 -- will actually be printed as 53.6. Indeed, when reading back the printed value you get the exact representation as the internal number that was printed, and IMHO, that is what matters. Apparently there is more than one representation that has this property. I would guess (but didn't check) that 53.60000000000000100000001 also gives the same number. From all these representations it would be best to choose the simplest one, i.e. 53.6. This problem and a solution has been described in one of the classical computer science publications: http://portal.acm.org/citation.cfm?id=93559 -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From robert.rawlins at thinkbluemedia.co.uk Fri Mar 14 06:49:01 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Fri, 14 Mar 2008 10:49:01 -0000 Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard In-Reply-To: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Message-ID: <009d01c885c1$05caac90$116005b0$@rawlins@thinkbluemedia.co.uk> Geert, I've not seen this issue myself, however, you might get a little more luck asking over on the MySQLdb mailing list as this seems to be more an issue with the db than your python code. It might be worth posting your question there too as it'll heighten your chances of finding someone who knows MySQLdb inside out. http://mail.python.org/mailman/listinfo/db-sig Cheers, Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of geert Sent: 14 March 2008 10:36 To: python-list at python.org Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard Hi all, I have a mac mini running maocosx 10.5 leopard I want to deploy a django project on. My backend is MySQL, and I have it running as a 64- bit app. Of course, apache2 is also running as 64-bit. MySQLdb installs with the usual warnings after applying the various patches I found here and there. These patches consist of altering _mysql.c and site.cfg. Basically, my problem boils down to this: File "", line 1, in File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line 19, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dynamic module does not define init function (init_mysql) Has anyone solved this? I been hunting around for 2 weeks now, and my deadline is looming grimly on the horizon :) Geert -- http://mail.python.org/mailman/listinfo/python-list From fumanchu at aminus.org Mon Mar 17 11:35:15 2008 From: fumanchu at aminus.org (fumanchu) Date: Mon, 17 Mar 2008 08:35:15 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> On Mar 16, 5:09 pm, a... at pythoncraft.com (Aahz) wrote: > fumanchu wrote: > > This is my third PyCon, and I've found a reasonably-sized cadre of > > people who come for the hallway conversations plus a Bof or two, > > having given up on hearing anything new, useful, or inspiring in the > > talks. There are several people I know who would like to see a more > > advanced academic track. > > Finally, trying to satisfy a thousand people is impossible. Well understood. Sorry if I implied it was an easy job. I know it isn't. > If you did not like the programming this year (aside from the sponsor > talks) and you did not participate in organizing PyCon or in delivering > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! This would be true, except that the two talks I proposed last year were essentially denied because they were too advanced, so I didn't even bother this year. Perhaps I should have, but the PERIOD needs to at least be replaced by a COMMA as long as the talk-acceptance committee continues to reject more advanced talk topics in favor of HOWTOs and Introduction To Package X. Robert Brewer fumanchu at aminus.org From castironpi at gmail.com Sat Mar 8 14:33:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 11:33:51 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> Message-ID: <9179f161-34ac-4fae-b5db-9af072e6f497@m34g2000hsc.googlegroups.com> On Mar 8, 12:05?pm, Pierre Quentel wrote: > > >>> def convert(x): > > > ? ? ? ? if '.' in x: > > ? ? ? ? ? ? ? ? try: return float(x) > > ? ? ? ? ? ? ? ? except ValueError: return x > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? try: return int(x) > > ? ? ? ? ? ? ? ? except: return x > > > >>> convert('123') > > 123 > > >>> convert('123.99') > > 123.98999999999999 > > >>> convert('hello') > > Hi, > > That's fine for people who write floats with a "." ; but others learn > to enter them with "," > > For the same float, the French write the literal 123.456.789,99 when > others write 123,456,789.99 ; for us, today is 8/3/2008 (or > 08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8 > > Popular spreadsheets know how to "guess" literals ; if the guess is > not correct users can usually specify the pattern to use. My question > was just to know if something similar had already been developed in > Python ; I understand that the answer is no > > Thanks, > Pierre In particular, you can retain access to the user/interface, and always just query when probabilities aren't 100%. In general, retain access to a higher power, such as offering a hook ( def butdonotguess( raw, guesses ):). If you're making the decision, and a case-by-case is too expensive, then you've made a policy, and someone gets shaft "'cause policy". You can throw an exception that's guaranteed to be handled or exits. '121212' isn't as bad as '121110'! If you want to find out who and when writes dates like that, apply to PR. Obviously a person knew at one point what the string was; how much is left? P.S. def welltheydidthatthistime( raw, guesses ):. From spe.stani.be at gmail.com Mon Mar 31 08:51:44 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Mon, 31 Mar 2008 05:51:44 -0700 (PDT) Subject: How to write a wxPython video player directly with Gstreamer Message-ID: <832962ee-bbfd-47df-b9fd-687c662f260c@i12g2000prf.googlegroups.com> In the hope it will be useful for others I've posted on my blog example source code of how to integrate gstreamer directly in wxpython: "wxPython ships by default with the wx.MediaCtrl for very basic playback of music or videos. As I would like to do more advanced video manipulation, I was curious if I could use Gstreamer directly in wxPython to create my own pipelines. It was surprisingly easy. For those who don't know Gstreamer, I quote the website (http:// www.gstreamer.org): GStreamer is a library that allows the construction of graphs of media- handling components, ranging from simple playback to complex audio (mixing) and video (non-linear editing) processing. Applications can take advantage of advances in codec and filter technology transparently." In order not to spam this mailing list, you can read more on http://pythonide.stani.be Best regards, Stani -- http://photobatch.stani.be From pavlovevidence at gmail.com Wed Mar 26 23:45:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Mar 2008 20:45:47 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> <13um57idbctec04@corp.supernews.com> Message-ID: <13a3347a-b8ca-492f-9c15-38e8cc34d4f4@59g2000hsb.googlegroups.com> On Mar 26, 11:30 pm, Steven D'Aprano wrote: > On Wed, 26 Mar 2008 23:12:27 +0100, Thomas Dybdahl Ahle wrote: > > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: > >> Why does python create a reference here, not just copy the variable? > > > Python, like most other oo languages, will always make references for =, > > unless you work on native types (numbers and strings). > > *Including* numbers and strings. Playing Devil's advocate: By "native types" the poster could have meant native types in those "most other oo languages". For instance, it would be kind of true in Java (for numbers only). He probably didn't, though, and the idea that most oo languages use references is questionable. Carl Banks From sjmachin at lexicon.net Sun Mar 23 18:55:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 15:55:43 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <7x63vfn3ix.fsf@ruckus.brouhaha.com> <8e4e1ae0-9a34-41c2-b253-7ea8846f6de5@i7g2000prf.googlegroups.com> Message-ID: <3880a377-30fe-49b3-a578-8d6203d526bb@s8g2000prg.googlegroups.com> On Mar 24, 12:19 am, Dustan wrote: > On Mar 21, 3:57 pm, Paul Rubin wrote: > > > From at home writes: > > > if 'one' and 'two' in f: > > > alist.append(f) > > > Use: > > if 'one' in f and 'two' in f: ... > > Personally, I would put parentheses around to be clearer: > > if ('one' in f) and ('two' in f): ... > > I'm not saying to put parentheses around everything, but in the more > ambiguous cases, it certainly helps. Please help me understand why this is a "more ambiguous" case. To me, alternative interpretations have extremely low scores for utility and likelihood: (1) 'and' has higher precedence than 'in': 'one' in (f and 'two') in f # chained (x in y in z) (2) 'and' has same precedence as 'in': (('one' in f) and 'two') in f Cheers, John From pavlovevidence at gmail.com Mon Mar 3 17:03:35 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 14:03:35 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> Message-ID: <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> On Mar 3, 4:17 pm, Raymond Hettinger wrote: > Since Python doesn't support having two methods with the same name, > the usual solution is to provide alternative constructors using > classmethod(): > > @classmethod > def from_decimal(cls, d) > sign, digits, exp = d.as_tuple() > digits = int(''.join(map(str, digits))) > if sign: > digits = -digits > if exp >= 0: > return cls(digits * 10 ** exp) > return cls(digits, 10 ** -exp) Note that even some of Python's built in types (dict *cough*) implement homemade function overloading. The OP wanted to write a constructor that could accept either a pair of integers or a rational, there would be a good precedent for it. However, I would advise the OP to use the constructor only for the most common arguments, and use classmethods for more obscure, less common arguments (such as decimal or even float). Carl Banks From stargaming at gmail.com Mon Mar 17 11:57:46 2008 From: stargaming at gmail.com (Stargaming) Date: 17 Mar 2008 15:57:46 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> Message-ID: <47de94fa$0$2679$9b622d9e@news.freenet.de> On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: > Here's a puzzle for those who think they know Python: > > Given that I masked out part of the input, which version(s) of Python > might give the following output, and what might I have replaced by > asterisks? > >>>> a = 1 >>>> b = **** >>>> if a is b: print 'yes!' > ... >>>> b > 1 >>>> type(b) > I know it! Using CPython 2.5.2a0, 2.6a1+ and 3.0a3+:: >>> b = type('type', (type,), {'__repr__': lambda self: ... ""})('int', (object,), {'__repr__': ... lambda self:"1"})() >>> b 1 >>> type(b) >>> 1 is b False What's my prize? From allardwarrink at gmail.com Sat Mar 1 16:04:38 2008 From: allardwarrink at gmail.com (Allard Warrink) Date: Sat, 1 Mar 2008 13:04:38 -0800 (PST) Subject: PIL transparency gradient Message-ID: <6e44e95a-2cb0-4026-ad98-f6516e934e27@s37g2000prg.googlegroups.com> I would like to create a transparency gradient over an image using PIL. But I don't have a clue how to do this... Is there anyone out here who could give me some advise? From castironpi at gmail.com Thu Mar 27 07:28:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:28:51 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: On Mar 27, 4:01?am, Peter Otten <__pete... at web.de> wrote: > Grimsqueaker wrote: > > That seems to give me the items in the list back in an iterator. Am I > > using it incorrectly? > > With Dan's functions in cartesian.py you can do the following: > > >>> from cartesian import * > >>> def count(digits): > > ... ? ? args = [] > ... ? ? while 1: > ... ? ? ? ? ? ? args.append(digits) > ... ? ? ? ? ? ? for n in string_cartesian_product(*args): > ... ? ? ? ? ? ? ? ? ? ? yield n > ...>>> from itertools import islice > >>> print " ".join(islice(count("abc"), 30)) > > a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab > bac bba bbb bbc bca bcb bcc For the base, we Arabics use the cardinal; what letters you count in doesn't change anything. Don't just spell out numbers, unless: Are you reading marked-tally. Or do you want to yield a word and see the number that it spells out to? Be there or be around. I'm bad at spelling, but I can rearrange linear. From NikitaTheSpider at gmail.com Mon Mar 31 11:08:09 2008 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Mon, 31 Mar 2008 11:08:09 -0400 Subject: Multi Threading Problem with Python + Django + PostgreSQL. References: <553b16a7-a89e-4892-b92b-c0f88e00e096@e23g2000prf.googlegroups.com> Message-ID: In article <553b16a7-a89e-4892-b92b-c0f88e00e096 at e23g2000prf.googlegroups.com>, Pradip wrote: > Hello every body. I am new to this forum and also in Python. > Read many things about multi threading in python. But still having > problem. > > I am using Django Framework with Python having PostgreSQL as backend > database with Linux OS. My applications are long running. I am using > threading. > The problem I am facing is that the connections that are being created > for database(postgres) update are not getting closed even though my > threads had returned and updated database successfully. It is not like > that the connections are not being reused. They r being reused but > after sometime new one is created. Like this it creates too many > connections and hence exceeding MAX_CONNECTION limit of postgres conf. > > ** I am using psycopg2 as adaptor for python to postgres connection. > which itself handles the connections(open/close) Hi Pradip, A common problem that new users of Python encounter is that they expect database statements to COMMIT automatically. Psycopg2 follows the Python DB-API specification and does not autocommit transactions unless you ask it to do so. Perhaps your connections are not closing because they have open transactions? To enable autocommit, call this on your connection object: connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCO MMIT) > Now the problem is with Django / Python / psycopg2 or any thing else?? Are you asking if there are bugs in this code that are responsible for your persistent connections? If so, then I'd say the answer is almost certainly no. Of course it's possible, but Django/Psycopg/Postgres is a pretty popular stack. The odds that there's a major bug in this popular code examined by many eyes versus a bug in your code are pretty low, I think. Don't take it personally, the same applies to my me and my code. =) Happy debugging -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From Dodin.Roman at gmail.com Tue Mar 25 08:50:36 2008 From: Dodin.Roman at gmail.com (hellt) Date: Tue, 25 Mar 2008 05:50:36 -0700 (PDT) Subject: Need help with OptionParser References: <0a225d25-c544-49d9-9e56-8ecd2d0f7928@s13g2000prd.googlegroups.com> Message-ID: On 25 ???, 15:42, hellt wrote: > today i've decided to use optionparser instead of GetOpt > > and unfortunately i've got an error which i cant handle > > my pice of code: > > from optparse import OptionParser > > def main(): > usage = "usage: %prog [options]" > parser = OptionParser(usage) > parser.add_option("-f", "--file", dest="filename", > help="executable filename", > metavar="FILE") > parser.add_option("-b", "--bighosts", > action="store_true", dest="bighosts", default=False, > help="with big hosts [default: %default]") > (options, args) = parser.parse_args() > if not options.bighosts: > print parser.print_usage() > > if __name__=="__main__": > main() > > if i run test3.py without any arguments, i wait for generated help, > but i see the following > > Usage: test3.py [options] > > None > > why None? Where are all of my options =) my bad unnecessary print in print parser.print_usage() and print_help() instead print_usage() From gandalf at shopzeus.com Tue Mar 25 05:07:55 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Mar 2008 10:07:55 +0100 Subject: eval and unicode In-Reply-To: <47E4210B.1080505@v.loewis.de> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <47E4210B.1080505@v.loewis.de> Message-ID: <47E8C0EB.7060609@shopzeus.com> > I think your confusion comes from the use of the interactive mode. > It is not. The example provided in the original post will also work when you put then into a python source file. > PEP 263 doesn't really apply to the interactive mode, hence the > behavior in interactive mode is undefined, and may and will change > across Python versions. > The expression passed to eval() cannot be considered an interactive session. > Ideally, interactive mode should assume the terminal's encoding for source code, but that has not been implemented. > Again, please read the original messages - many of my examples also work when you put them into a python source file. They have nothing to do with terminals. Laszlo From Afro.Systems at gmail.com Mon Mar 24 03:56:42 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 24 Mar 2008 00:56:42 -0700 (PDT) Subject: encoding/decoding issue with python2.5 and pymssql References: <3a6c32fe-e7c1-4230-882d-efb3415196c1@b1g2000hsg.googlegroups.com> <13uejm8qurtp77f@corp.supernews.com> Message-ID: <17274d24-f0de-4e79-974c-3f63f2af009b@d45g2000hsc.googlegroups.com> These are not cut&paste but typed by hand, yet they are identical to the actual output. seems like the first 8 bytes are swapped while the other half is straightforward. I deeply thank you for your assistance. I am currently using a combination of reversed and list comprehension to rebuild this byte array. On Mar 24, 8:48?am, Dennis Lee Bieber wrote: > On Sun, 23 Mar 2008 22:33:58 -0700 (PDT), Tzury Bar Yochay > declaimed the following in comp.lang.python: > > > for example: > > the value > > 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7' > > is represent as > > '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7' > > ? ? ? ? Are those direct cut&paste? > > >>> "".join(["%2.2X" % ord(x) for x in '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7']) > > 'E34E60EEB04AE74EAF4D018124393CD7' > > or, putting in - > > 'E34E60EE-B04A-E74E-AF4D-018124393CD7' > > ? ? ? ? The last half is a direct match... the front half looks to have some > byte-swapping > > E34E60EE => (swap shorts) ? ?60EEE34E > 60EEE34E => (swap bytes) ? ? EE604EE3 ? ? ? ? ? ? ? ?**** > > B04A => 4AB0 ? ? ? ? **** > > E74E => 4EE7 ? ? ? ? **** > > ? ? ? ? Anything onhttp://www.sqljunkies.com/Article/4067A1B1-C31C-4EAF-86C3-80513451FC0... > of any help (besides the facet of using a GUID to ID the page describing > GUIDs ) > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From deets at nospam.web.de Wed Mar 19 07:41:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 12:41:23 +0100 Subject: Script Request... References: Message-ID: <64ccfbF2bbfckU1@mid.uni-berlin.de> some one wrote: > Hi all, I am not to familiar with python yet and I am wondering if > someone can write a script that will monitor my DSL modems IP address > and notify when it changes, its a 2Wire Advanced DSL Modem. I need to > know when it changes because I am trying to run my own inhouse server > and have to update my domain records through verio.com. > > The script would need to read the text of a web page( on my modem the > address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and > search for a string containing the IP address. > > Can anyone help? > thanks, I'll keep monitoring this thread. Try urllib2 to fetch the data, use either string-search, regular expressions or even BeautifulSoup to extract the data. Use a cron-job to do that on a regular base or use module time.sleep() together with an endless loop to monitor that location periodically. Show us your concrete efforts, and we will suggest improvements. Diez From pavlovevidence at gmail.com Thu Mar 6 12:36:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 09:36:21 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> On Mar 6, 11:41 am, "D'Arcy J.M. Cain" wrote: > On Thu, 6 Mar 2008 08:00:58 -0800 (PST) > > Carl Banks wrote: > > > I'm talking about castironpi. I find his posts a waste of my time > > > "His" posts? > > Whatever. I'm too old to worry about searching for politically correct, > gender neutral pronouns. I'm pretty sure even the most PC people wouldn't suggest using a masculine pronoun for an inanimate objects. (Ok, some probably would.) Carl Banks From sjmachin at lexicon.net Mon Mar 10 00:42:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Mar 2008 21:42:49 -0700 (PDT) Subject: any chance regular expressions are cached? References: Message-ID: <51172306-ff2d-48e8-81cf-93be03f8a08f@s37g2000prg.googlegroups.com> On Mar 10, 11:42 am, m... at pixar.com wrote: > I've got a bit of code in a function like this: > > s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save > me the trouble of having to declare some global re's if I don't > want to have them recompiled on each function invocation? > Yes they will be cached. But do yourself a favour and check out the string methods. E.g. >>> import re >>> def opfunc(s, spaces): ... s=re.sub(r'\n','\n'+spaces,s) ... s=re.sub(r'^',spaces,s) ... s=re.sub(r' *\n','\n',s) ... s=re.sub(r' *$','',s) ... s=re.sub(r'\n*$','',s) ... return s ... >>> def myfunc(s, spaces): ... return '\n'.join(spaces + x.rstrip() if x.rstrip() else '' for x in s.splitlines()) ... >>> t1 = 'foo\nbar\nzot\n' >>> t2 = 'foo\nbar \nzot\n' >>> t3 = 'foo\n\nzot\n' >>> [opfunc(s, ' ') for s in (t1, t2, t3)] [' foo\n bar\n zot', ' foo\n bar\n zot', ' foo\n\n zot'] >>> [myfunc(s, ' ') for s in (t1, t2, t3)] [' foo\n bar\n zot', ' foo\n bar\n zot', ' foo\n\n zot'] >>> From michael.wieher at gmail.com Mon Mar 17 11:18:59 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 10:18:59 -0500 Subject: Missing PyObject definition In-Reply-To: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: 2008/3/17, James Whetstone : > > I'm trying to access a PyObject directly from C++ for the purpose of > calling > method on a Python object that is an intance of a derived C++ class. My > problem is that the compiler is complaining about not PyObject not being > defined. Has anyone run into the problem? Where is PyObject defined? > > Thanks! > James PyObject is definend in this is easily google-able =P -------------- next part -------------- An HTML attachment was scrubbed... URL: From lobais at gmail.com Wed Mar 26 18:12:27 2008 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Wed, 26 Mar 2008 23:12:27 +0100 Subject: Why does python behave so? (removing list items) In-Reply-To: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <1206569547.1010.16.camel@localhost.localdomain> On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: > Why does python create a reference here, not just copy the variable? Python, like most other oo languages, will always make references for =, unless you work on native types (numbers and strings). Instead use one of: k = j[:] or k = [i for i in j] or from copy import copy k = copy(j) or k = range(6) -- Best Regards, Med Venlig Hilsen, Thomas From castironpi at gmail.com Fri Mar 21 09:28:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 06:28:34 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> <4e740d0f-9b1d-4b1d-9f6b-8bd56ea11a65@z38g2000hsc.googlegroups.com> Message-ID: <30f5365b-7e73-4d1c-9db0-dc7244852763@8g2000hse.googlegroups.com> On Mar 19, 4:56?am, Duncan Booth wrote: > castiro... at gmail.com wrote: > > I am puzzled by the failure on 'a in a' for a=[a]. ?>>> a== [a] also > > fails. ?Can we assume/surmise/deduce/infer it's intentional? > > It may be less confusing if instead of an assignment following by a test > you just consider doing the test at the same time as the assignment > (then again it changes the behaviour so it may just be more confusing). > > There is a very limited set of values for which you would expect this > output: > > >>> a==[a] > True > >>> a in [a] > > True > > The most obvious one is a simple recursive list: > > >>> a = [] > >>> a.append(a) > >>> a==[a]; a in [a] > > True > True > > Pushing the recursion down a level breaks some of the comparisons: > > >>> a = [[]] > >>> a[0].append(a) > >>> a==[a] > > Traceback (most recent call last): > ? File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp>>> a in [a] > True > >>> a in a > > Traceback (most recent call last): > ? File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp > > which may be considered a bug or possibly it is just a limit of the > implementation. > > This also produces an overflow (in fact I think it is just the same > situation as above, recursing on the same list is handled, recursing on > different but equivalent lists is not): > > >>> a = []; a.append(a) > >>> b = []; b.append(b) > >>> a==b > > Traceback (most recent call last): > ? File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp Pickle helps, >>> pickle.dumps( a ) b'\x80\x02]q\x00h\x00a.' >>> pickle.dumps( b ) b'\x80\x02]q\x00h\x00a.' >>> pickle.dumps( a )== pickle.dumps( b ) True However, >>> a= [] >>> b= [] >>> a.append( b ) >>> b.append( a ) >>> a [[[...]]] >>> b [[[...]]] >>> a== b Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp >>> pickle.dumps( a )== pickle.dumps( b ) True Liar's paradox, q.e.d. From willsteve2003 at yahoo.ca Mon Mar 17 12:15:55 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 17 Mar 2008 09:15:55 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> Message-ID: On Mar 10, 11:30 am, "sjdevn... at yahoo.com" wrote: > Fix that. That's usually something that's fairly easy to get done as > a programmer (I've had to do it at 2 of the last 4 places I worked). > Just go explain all the problems that can happen by not having VC and > all the benefits it brings to your managers, and that there's a good > free VC system that will work for everyone, and it'll likely become a > mandate pretty quickly. > > It's almost certainly worth fixing that problem rather than mucking > around with half-solutions. Unfortunately, no free VC system existed for the language in which I was programming, and our budget (managers) wouldn't permit the purchase of one easily. These people insisted that every change that affected more than 1 user go through a committee that met once a week. The amount of verbiage required just to submit a proposal to the committee (whom you never got to see in person), was ridiculous in the extreme. From sturlamolden at yahoo.no Sun Mar 16 13:17:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:17:31 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> Message-ID: <3cfd04c9-4a51-402f-b636-8690d4936c1d@h11g2000prf.googlegroups.com> On 16 Mar, 18:10, sturlamolden wrote: > You don't click on compiled Python C extensions. You call it from your > Python code. By the way, disttools will invoke Pyrex and the C compiler, and produce the binary .pyd-file you can access from Python. It's not rocket science (not even computational biology.) From kyosohma at gmail.com Mon Mar 10 15:33:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 12:33:17 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: On Mar 10, 2:11 pm, Stefan Behnel wrote: > Malcolm Greene wrote: > >> My personal experience with wxPython has its ups and downs. Specifically > >> when it comes to crashes, I wouldn't bet my life on it. > > > I'm new to Python and getting ready to build a small client based > > application intended to run on Windows and Linux. I was planning on using > > wxPython until I saw your comment above. > > Just to make this sound a bit less like FUD: my last experience with wxPython > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > in a project, which crashed a bit too often to do real work with it - and with > crashing I mean crashing Python, not just showing us its blank traceback. So > this was definitely a problem either in wxWindows or in wxPython. > > I have no idea how well it works today, but this has definitely forged my > opinion on wxPython. > > > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > > or tips on where I can find out more about wxPython/wxWidget problems? > > The only other GUI library I used was PyQT3. To me, it has proven to be very > stable, pretty easy to use and feature rich. And from what I read about it, > PyQT4 is supposed to be another lot better and has removed the few API quirks > I found at the time (AFAIR, it finally returns plain Python strings from the > API, for example). > > Stefan I agree with Stef. Boa is definitely goofy and while I know some people swear by it, I see far too many people having issues. I go with hand coding or XRC. Some also like SPE, but I haven't tried that to know. Mike From castironpi at gmail.com Wed Mar 12 02:29:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:29:47 -0700 (PDT) Subject: best way to have enum-like identifiers? References: <87k5k84h31.fsf@benfinney.id.au> Message-ID: <768fd642-817c-4a0e-af2c-ee91da88941a@u72g2000hsf.googlegroups.com> > > [enums snip] > Thus, those names are all bound to unique objects, that won't be > unexpectedly duplicated by some other value. > > > but I'm curious if there's a better way of doing this, some kind of > > enum-like thing or somesuch. > > Please try the 'enum' package in the Cheeseshop: Am I the only one superstitious about putting identifiers in strings? > ?When a well-packaged web of lies has been sold to the masses ... someone sold them. >>> c= type('Enum',(),{}) >>> [ setattr( c, v, object() ) for v in 'py funcpre funcpost'.split() ] [None, None, None] >>> c.funcpost >>> c.funcpre You don't need them to be ints or anything, do you, like USER_BASE+ 1? From fraleysinger at gmail.com Wed Mar 12 10:25:43 2008 From: fraleysinger at gmail.com (fraleysinger at gmail.com) Date: Wed, 12 Mar 2008 07:25:43 -0700 (PDT) Subject: agg (effbot) Message-ID: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> Downloaded to Knoppix 5.1: : aggdraw-1.2a3-20060212.tar.gz Followed README. Wouldn't compile. Couldn't find way of contacting Effbot directly. PIL stuff comes with Knoppix, but specs on agg seem better. vtk is on Knoppix too, but has a steep learning curve. TIA for help. From Afro.Systems at gmail.com Tue Mar 25 10:31:06 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 07:31:06 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <29bc6ff2-f172-4776-87b7-884585277570@d21g2000prf.googlegroups.com> On Mar 25, 4:03?pm, Anthony wrote: > On Mar 25, 11:44 am, Tzury Bar Yochay wrote: > > > While my intention is to get 1.2 I get 2.2 > > I would like to know what would be the right way to yield the expected > > results > > Is this what you want? > > class Foo(object): > ? ? def __init__(self): > ? ? ? ? self.id = 1 > ? ? def getid(self): > ? ? ? ? return self.id > > class FooSon(Foo): > ? ? def __init__(self): > ? ? ? ? Foo.__init__(self) > ? ? ? ? self.id = 2 > ? ? def getid(self): > ? ? ? ? a = Foo().getid() > ? ? ? ? b = self.id > ? ? ? ? return '%d.%d' % (a,b) > > >>> FooSon().getid() > > '1.2' > > Best wishes, > Anthony I wish it was that simple but 'a = Foo().getid()' is actually creating a new instance of Foo whereas I want the data of the Foo instanced by __init__ of FooSon(). what I am actually trying to do is to build a set of classes which handle different type of binary messages coming from the network. a base message which handles its basic data parts (src, dst, etc.) and extending it per message type. thus I looked for a way to get the child calling super for parsing the super's prats and then having the child parsing its additional details. From nanjundi at gmail.com Wed Mar 5 17:08:00 2008 From: nanjundi at gmail.com (Nanjundi) Date: Wed, 5 Mar 2008 14:08:00 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <51f4bce3-8561-4149-9b3b-e436bbee8ee7@u69g2000hse.googlegroups.com> <1bcbee35-c5bf-4a6d-b68a-1eed87ffcf8d@p25g2000hsf.googlegroups.com> Message-ID: <8feb142e-2014-4a6f-80cd-28ab44125e9f@u69g2000hse.googlegroups.com> On Mar 5, 3:34 pm, Mensanator wrote: > On Mar 5, 9:29 am, Nanjundi wrote: > > > On Mar 4, 3:13 pm, Mensanator wrote: > > > > On Mar 4, 12:32 pm, Nanjundi wrote: > > > > > Does seeding ( random.seed ) random with time fix this? It should. > > > > I suppose that depends on how long it takes factorint() to > > > process a number. If the seed is reset before the next clock > > > tick, you will get the same random numbers as the previous > > > iteration. > > > Alright, then make it constant and don't worry about the clock tick. > > Reseeding with a constant always sets the sequence to the same > starting > point. > Right, not a good idea. > > > >>> for i in xrange(10): > > > ... f1 = random.choice(f) > > ... print f1, > > ... f2 = random.choice(f) > > ... print f2, > > ... C = f1*f2 > > ... ff = None > > ... ff = sympy.factorint(C) > > ... print ff > > ... random.seed(i) > > ... > > 5573 5171 [(5171, 1), (5573, 1)] > > 8537 7673 [(7673, 1), (8537, 1)] > > 2063 8573 [(2063, 1), (8573, 1)] > > 9551 9473 [(9473, 1), (9551, 1)] > > 2909 5659 [(2909, 1), (5659, 1)] > > 2897 1789 [(1789, 1), (2897, 1)] > > 6361 7541 [(6361, 1), (7541, 1)] > > 8017 8293 [(8017, 1), (8293, 1)] > > 3671 2207 [(2207, 1), (3671, 1)] > > 2803 9629 [(2803, 1), (9629, 1)] > > > > Frankly, I don't understand why factorint() reseeds at all. > > > Read the doc: > > * The rho algorithm is a Monte Carlo method whose outcome can be > > affected by changing the random seed value. * > > But that doesn't give it the right to mess with the state > of the random number generator _I'm_ using. Had I actually > known what was happening, I could have saved the state of > my random number generator s=random.getstate() and then restored > it after calling factorint(), random.setstate(s). > > import sympy # with RK's patch removed > import time > import random > > f = [i for i in sympy.primerange(1000,10000)] > > for i in xrange(10): > f1 = random.choice(f) > print f1, > f2 = random.choice(f) > print f2, > C = f1*f2 > ff = None > rs = random.getstate() > ff = sympy.factorint(C) > random.setstate(rs) > print ff > > 5669 3863 [(3863, 1), (5669, 1)] > 1973 5431 [(1973, 1), (5431, 1)] > 7577 6089 [(6089, 1), (7577, 1)] > 8761 4957 [(4957, 1), (8761, 1)] > 4153 2719 [(2719, 1), (4153, 1)] > 4999 5669 [(4999, 1), (5669, 1)] > 8863 5417 [(5417, 1), (8863, 1)] > 7151 7951 [(7151, 1), (7951, 1)] > 7867 9887 [(7867, 1), (9887, 1)] > 9283 5227 [(5227, 1), (9283, 1)] > > Of course, this is new as of Python 2.4, so if factorint() > tried to save & restore state, sympy wouldn't work on Python > 2.3 or earlier. > > If I'm reading RK's patch correctly, he doesn't reseed the > random number generator, he creates a new random object that > maintains it's own state that can be freely seeded to any > value without disturbing the state of my random number generator. > > > > > > Doesn't Random automatically initialize the seed? > > > Doesn't constantly reseeding degrade the performance of the > > > random number generator? With Robert Kern's patch, the reseeding > > > is no longer a constant, fixing the immediate symptom. > > > Does it matter? > > I was wrong. It is a constant, just not 1234. If that's what > factorint() needs, fine. As long as it maintains a seperate state > than the one I'm using. > > > The factorint reseeds using a constant seed (1234). > > Not now it doesn't: :) > > @@ -92,8 +92,8 @@ def pollard_pm1(n, B=10, seed=1234): > > """ > from math import log > - random.seed(seed + B) > - a = random.randint(2, n-1) > + prng = random.Random(seed + B) > + a = prng.randint(2, n-1) > for p in sieve.primerange(2, B): > e = int(log(B, p)) > a = pow(a, p**e, n) > > > > > > But what if _I_ wanted to make a repeatable sequence for test > > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > > on every call? > > > Repeatable sequence? save it and reuse! > > As part of my resolution to tone down my attitude, > I won't even reply to that. > Thanks. > > Think about "What if"s doesn't get any work done. > > ? nevermind. > > > > > -N From hdante at gmail.com Sun Mar 30 16:53:08 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 13:53:08 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> Message-ID: <6deb5443-e87b-448e-a1a6-6a1886c9f12a@x41g2000hsb.googlegroups.com> On Mar 30, 9:45 am, Bjoern Schliessmann wrote: > hdante wrote: > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > Could you please list some that do, and are also convenient? AFAICT there's none. This should be easy to implement on emacs, or in SCIM. > > Regards, > > Bj?rn > > -- > BOFH excuse #288: > > Hard drive sleeping. Let it wake up on it's own... From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:51:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:51:01 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <13t6d3lppl8lv2a@corp.supernews.com> On Sat, 08 Mar 2008 13:40:56 -0800, dave_mikesell wrote: > On Mar 8, 2:27 pm, castiro... at gmail.com wrote: > >> Good comments are better than bad names. Good names are better than bad >> comments. > > If you're taking the time to write good comments, why not just fix the > bad names? The compiler/interpreter can never, ever catch bad comments. Yes, but the Python compiler can only catch bad names if you do this at the top of every module: import semantic_analysis import magic.crystal_ball.read_programmers_mind Unfortunately, this comes with a *serious* performance hit, so most people don't bother. Instead, they rely on the programmer to write good descriptive names AND good comments, because not everything can be documented in a name. -- Steven From justus.schwabedal at gmx.de Fri Mar 14 13:35:51 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Fri, 14 Mar 2008 18:35:51 +0100 Subject: Problem with exec In-Reply-To: References: Message-ID: On Mar 14, 2008, at 4:41 AM, alitosis at gmail.com wrote: > On Mar 14, 9:47 am, Justus Schwabedal > wrote: > [snipped] >> However when I do this: >> >> bash-3.2$ cat execBug2.py >> #! /usr/bin/python >> header=""" >> from scipy import randn >> def f(): >> return randn() >> """ >> def g(): >> exec header >> return f() >> print "g() =",g() >> bash-3.2$ ./execBug2.py >> g() = >> Traceback (most recent call last): >> File "./execBug2.py", line 10, in >> print "g() =",g() >> File "./execBug2.py", line 9, in g >> return f() >> File "", line 4, in f >> NameError: global name 'randn' is not defined >> bash-3.2$ ??? >> >> I get this global name error. I can fix it with adding some line like >> "global randn" but I don't want to do this. I want to do exactly >> what I wrote: Import the function scipy.randn in the local >> namespace of the >> >> function "g" so that "return f()" makes sense. Can anybody help me >> out? >> Yours Justus > > Maybe using an explicit namespace is good enough for your needs: > > #! /usr/bin/python > header=""" > from scipy import randn > def f(): > return randn() > """ > def g(): > n = {} > exec header in n > return n['f']() > print "g() =",g() > > > (i don't understand the issues, but I can cut-and-paste with the best > of them) > -- > http://mail.python.org/mailman/listinfo/python-list That's what I was looking for: It's probably even a faster solution than declaring all the imports global, isn't it? From galaviel at yahoo.com Sun Mar 23 19:43:54 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Sun, 23 Mar 2008 23:43:54 +0000 (UTC) Subject: always getting 'None' return value from =?utf-8?b?UHlPYmplY3RfQ2FsbE9iamVjdA==?= Message-ID: Hello all, Kinda desperate over here .. Any help would be greatly appreciated ! I'm trying to embed a Python interpreter inside a Verilog simulator as a SystemVerilog DPI application. The python side implements a few SV exported tasks. I've got a thin C shared library as the dpi app; all it does it get the task arguments from the simulator and hand those to the Python side using the Python C API. I followed '5.3 Pure Embedding' under Python 2.5 documentation very closely. When calling a function defined in my module, the function executes Ok - it sees the correct arguments being passed from C, and executes 100% - only the return value is always 'None' (I tried returning a simple integer like '5' which doesn't work). Any ideas? Maybe scope issues? the module goes out of scope, and there is no place to store the temporary return value from the function? Where is that stored anyway with embedded python? Thanks- Gal Aviel. From castironpi at gmail.com Sat Mar 22 04:19:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 01:19:59 -0700 (PDT) Subject: function-class frustration Message-ID: >>> FunctionType.__eq__= 0 Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'function' >>> type( 'F', ( FunctionType, ), { '__eq__': e } ) Traceback (most recent call last): File "", line 1, in TypeError: type 'function' is not an acceptable base type On the other hand, are you willing to make changes to the console? How big and what? I was thinking of __ to keep the second-to-last most recent command. From pmarreddy at hotmail.com Mon Mar 10 06:01:38 2008 From: pmarreddy at hotmail.com (ditto007) Date: Mon, 10 Mar 2008 03:01:38 -0700 (PDT) Subject: An important message to all jobseekers ,and internet users In-Reply-To: <1194500148.404841.267410@k35g2000prh.googlegroups.com> References: <1194500148.404841.267410@k35g2000prh.googlegroups.com> Message-ID: <15950649.post@talk.nabble.com> http://swingwind.com more high quality placement papers at swingwind.com from 2008 http://swingwind.com/category/tag/placement-papers all IT company placement papers 2008 here -- View this message in context: http://www.nabble.com/An-important-message-to-all-jobseekers-%2Cand-internet-users-tp13641645p15950649.html Sent from the Python - python-list mailing list archive at Nabble.com. From arnodel at googlemail.com Sat Mar 15 15:40:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 15 Mar 2008 12:40:31 -0700 (PDT) Subject: Getting started with OS X Leopard References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> Message-ID: <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> On Mar 15, 7:31?pm, Mark Carter wrote: > has wrote: > > On 15 Mar, 18:05, Mark Carter wrote: > >> The sorts of things I want to do are: > >> * copy the directory of Finder to the clipboard > >> * add a new file to Finder's directory. > >> * find out the size of a directory > >> * open a file with Aquamacs, regardless of file type, > > > If you want to control desktop applications directly, that generally > > means using Apple event IPC. The most popular language for application > > scripting is traditionally AppleScript, but Apple event bridges exist > > for other languages as well. The best of these is appscript; see my > > sig for links. Some Finder scripting examples: > > > #!/usr/bin/python > > ... > > Control AppleScriptable applications from Python, Ruby and ObjC: > >http://appscript.sourceforge.net > > Aah! Many thanks. I see that I had to do > easy_install appscript > and ensure I use /usr/bin/python > I'm off to play with it now. Exciting stuff. > > I installed the Python from MacPorts. That's not quite what I wanted, > because they only have a version for Python 2.4. *Sigh*. MacPorts seems > to be getting new ports all the time. The problem is, there also seems > to be an aweful lot of ports gathering bitrot. Is there a particular reason you want python from MacPorts? OSX Leopard comes with python 2.5, that's what I use on my mac. -- Arnaud From myeates at jpl.nasa.gov Mon Mar 17 19:51:17 2008 From: myeates at jpl.nasa.gov (Mathew) Date: Mon, 17 Mar 2008 16:51:17 -0700 Subject: placing a Python com object into Excel In-Reply-To: <47deefc5$0$906$ba4acef3@news.orange.fr> References: <47deefc5$0$906$ba4acef3@news.orange.fr> Message-ID: Thanks for the tip. But, instead of an AddIn, what if I want to be able to insert an object? I see that the demo adds items to the windows registry under \Excel\AddIns. Is there a similar location for the "Insert Object" command? yikes. More Excel programming than I'd like to know. Mathew M?ta-MCI (MVP) wrote: > Hi! > > Perso, I started from "excelAddin.py" (in > C:\Python25\Lib\site-packages\win32com\demos). > And, I'm happy with the result (who run OK with Excel 2000, XP, 2007). > > @-salutations From apardon at forel.vub.ac.be Fri Mar 14 06:38:52 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Mar 2008 10:38:52 GMT Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: On 2008-03-13, Terry Reedy wrote: > > "Antoon Pardon" wrote in message > news:slrnfthp1s.61k.apardon at rcpc42.vub.ac.be... >| On 2008-02-28, Steven D'Aprano > wrote: >| > On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: >| > >| >> Hi! >| >> Can somebody of you make me a sample how to define a function based on >| >> "call by reference" ??? >| > >| > Python doesn't do call by reference. Nor does it do call by value. > Please >| > pay no attention to anyone who says it does. >| >| Whatever python has for a calling convention, it is close enough that >| naming it "call by reference" gives people a reasonable idea of what >| is going on. > > But it is also different enough to mislead people. IMO the confusing come more from people expecting the assignment to be some kind of mutating operation. >| AFAICS people don't have a problem with understanding the calling >| convention of python. They have a problem understanding the >| assignment semantics. > > The calling convention is cross-namespace assignment. So one cannot > understand calls without understanding assignment. In that case I find it very strange that when this question comes up, I see so few attempts to explain how the assignment acctually works. -- Antoon Pardon From koara at atlas.cz Fri Mar 7 08:14:09 2008 From: koara at atlas.cz (koara) Date: Fri, 7 Mar 2008 05:14:09 -0800 (PST) Subject: hidden built-in module Message-ID: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> Hello, is there a way to access a module that is hidden because another module (of the same name) is found first? More specifically, i have my own logging.py module, and inside this module, depending on how initialization goes, i may want to do 'from logging import *' from the built-in logging. I hope my description was clear, cheers. I am using python2.4. From maxerickson at gmail.com Wed Mar 12 12:12:48 2008 From: maxerickson at gmail.com (Max Erickson) Date: Wed, 12 Mar 2008 16:12:48 +0000 (UTC) Subject: Mutagen File Problem References: <81d8d48f-5496-4ca6-a525-c7b927436d4d@d62g2000hsf.googlegroups.com> Message-ID: aiwarrior wrote: > Hi i'm having a IO error saying a file does not exist even though > i perform a isFile() check. Can you help me out figuring what is > wrong? > > Thanks in advance > > from mutagen.easyid3 import EasyID3 > from mutagen.mp3 import MP3 > > for root, dirs, files in os.walk('''C:\\Documents and > Settings\\pneves\ \Music\\''', topdown=False): > for name in files: > joined = os.path.join(root, name) > if (name[-3:] == 'mp3' ): > audio = MP3(joined, ID3=EasyID3) > if not audio.has_key('album') and > os.path.isfile(joined): > print os.path.join(root, name) > > I get an error as following: > > IOError: [Errno 2] No such file or directory: 'C:\\Documents and > Settings\\pneves\\Music\\Naked Music - Miguel Migs - Colorful > You\ \Miguel Migs - Colorful you - Full album\\Miguel Migs - > Colorful you - Cd 2 -Mixed and mastered by J. Mark Andrus\\7 - > Miguel Migs feat. Lisa Shaw - You Bring Me Up (Main Vocal > Mix).mp3' It looks like the error is happending in MP3(join...), so the os.path.isfile check is never reached. If that is the case, something along the lines of: try: audio=MP3(joined, ID3=EasyID3) except: #catches any error in MP3... print joined should suppress the error and print the filename that triggered it. max From __peter__ at web.de Mon Mar 3 06:49:48 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Mar 2008 12:49:48 +0100 Subject: Regex loop question References: <7aae0102-51bd-4701-a116-60b8d9698450@s13g2000prd.googlegroups.com> Message-ID: Mike P wrote: > Hi Experts, > > I've written a peice of code that works fine and fits, and passes > values into a peice of SPSS code, the problem is that it is not > dynamic, and so i though about how i can make it dynamic, (other code > may not have upto 10 some may have more) and came up with regex for an > idea, but i can't seem to make it work, can anyone offer any advice? > Below is current working code > > time_variables = {"ActivityTime": "Activity_Time", > "ExposureTime_Last":"Exposure_Time_1", > "ExposureTime_Last2":"Exposure_Time_2", > "ExposureTime_Last3":"Exposure_Time_3", > "ExposureTime_Last4":"Exposure_Time_4", > "ExposureTime_Last5":"Exposure_Time_5", > "ExposureTime_Last6":"Exposure_Time_6", > "ExposureTime_Last7":"Exposure_Time_7", > "ExposureTime_Last8":"Exposure_Time_8", > "ExposureTime_Last9":"Exposure_Time_9", > "ExposureTime_Last10":"Exposure_Time_10"} > > for Var in time_variables.keys(): > time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . > COMPUTE %s = number(%s, TIME8). > VARIABLE LABEL %s. > VARIABLE LEVEL %s (SCALE). > FORMATS %s (TIME8). > VARIABLE WIDTH %s (8). > EXECUTE.""") %(Var, Var, > Var,time_variables[Var],Var,time_variables[Var], > time_variables[Var],time_variables[Var],time_variables[Var]) > spss.Submit(time_manips) > > > Now to make it dynamic i've gone for the following... > > reg_time = re.compile("^ExposureTime_Last([0-9]*)$") > reg_Activity = re.compile("^ActivityTime") > for Var in time_variables.keys(): > if reg_time.match(Var): > match = reg_time.match(Var) > E_time = "Exposure_Time_%s" % match.groups()[0] > else: > match = reg_time.match(Var) > match.groups()[0] = "Activity_Time" > > > time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . > COMPUTE %s = number(%s, TIME8). > VARIABLE LABEL %s. > VARIABLE LEVEL %s (SCALE). > FORMATS %s (TIME8). > VARIABLE WIDTH %s (8). > EXECUTE.""") %(Var, Var, > Var,time_variables[Var],Var,time_variables[Var],time_variables[Var], > time_variables[Var],time_variables[Var]) > print(time_manips) > > All help welcome, or if a different approach is better please let me > know I'd clean up the original code a bit rather than introducing another source of errors (the regexes): # no warranties time_variables = [ ("ActivityTime", "Activity_Time"), ("ExposureTime_Last","Exposure_Time_1")] time_variables.extend(("ExposureTime_Last%d" % i, "Exposure_Time_%d" % i) for i in range(2, 11)) for key, value in time_variables: time_manips = """COMPUTE %(key)s = SUBSTR(%(key)s (INDEX(%(key)s,'T'))+1) . COMPUTE %(value)s = number(%(key)s, TIME8). VARIABLE LABEL %(value)s. VARIABLE LEVEL %(value)s (SCALE). FORMATS %(value)s (TIME8). VARIABLE WIDTH %(value)s (8). EXECUTE.""" % dict(key=key, value=value) spss.Submit(time_manips) It might be even better to move the logic into SPSS and to replace the numerical suffices with array indices (if supported), but I can't help you with that. Peter From hacker.stevenson at gmail.com Thu Mar 27 17:46:01 2008 From: hacker.stevenson at gmail.com (breal) Date: Thu, 27 Mar 2008 14:46:01 -0700 (PDT) Subject: Determine size of string in bytes References: <083180d3-3e7c-4db5-926f-b7528201a3b8@a22g2000hsc.googlegroups.com> Message-ID: <914e27a8-65b5-4759-80aa-1c16d88dea5c@u10g2000prn.googlegroups.com> On Mar 27, 2:10 pm, John Machin wrote: > On Mar 28, 6:45 am, breal wrote: > > > Forgive me for this question which is most likely stupid... > > The contents of your question are not stupid. The subject however does > invite a stupid answer like: len(the_string). > > Disclaimer: I know nothing about SOAP except that it's usually > capitalised :-) Now read on: > > > How do I determine the number of bytes a string takes up? I have a > > soap server that is returning a serialized string. > > Serialised how? UTF-8? > Yes. I meant to include that. I did not understand that len() returned the actual byte length of a UTF-8 encoded string. > > It seems that when > > the string goes over 65978 characters it does not return to the soap > > client. > > Why does it seem so? How did you arrive at such a precise limit? > I actually just wrote a test that would call a function on the SOAP server (SOAPpy) that would increase or decrease the test length based on the previous result until it found x, x+1 where x characters didn't fail, but x+1 did. x ended up being 65978. The string I happen to be encoding in this case has all ascii characters so it is the same for both encodings. > > Instead I get an error: > > error: (35, 'Resource temporarily unavailable') > > Is this error from the client or the server? Any error or logfile > record from the other side? > This is an error on the server. The client is actually written in PHP. There is no log file, but there is a traceback... Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/SocketServer.py", line 464, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/SocketServer.py", line 522, in __init__ self.handle() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/BaseHTTPServer.py", line 310, in handle_one_request method() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/site-packages/SOAPpy/Server.py", line 545, in do_POST self.wfile.write(resp) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/socket.py", line 262, in write self.flush() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/socket.py", line 249, in flush self._sock.sendall(buffer) error: (35, 'Resource temporarily unavailable') ---------------------------------------- > Is there anything in the documentation about maximum sizes? > > I googled my brains out looking for anything about maximum size both on the Python SOAP server, and the PHP SOAP client. > > > This makes me think the problem exists on the soap client side with > > some sort of max return length. > > Think? Can't you verify this by inspecting the source? > I haven't inspected the source, but I have inspected the documentation. No luck in finding anything about it. I suppose I could download the client source and see what I can see. > > If I knew how many bytes the 65978 > > character string was, then I could try to up this value. > > How do you know the string is 65978 characters? If you are debugging > the server, can't you do len(serialise(the_65978_char_string))? > > 65978? Are you sure? Looks suspiciously close to 65535 aka 0xFFFF aka > (2 ** 16 - 1 ) to me. > > If you have the server, you presumably have the source code for both > client and server. Some options for you: > > (1) Look at the traceback(s), look at the source code, nut it out for > yourself. If there is some kind of max other than an implicit 16-bit > limitation in the client code, it shouldn't be too hard to find. > > (2) Post the traceback(s) here, along with other details that might be > useful, like what SOAP server s/w you are using, what version of > Python, what platform. > See traceback above. SOAPpy Python 2.5 OSX Server Thanks for the response John. From http Fri Mar 28 02:32:55 2008 From: http (Paul Rubin) Date: 27 Mar 2008 23:32:55 -0700 Subject: SoC project: Python-Haskell bridge - request for feedback References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: <7xej9vbboo.fsf@ruckus.brouhaha.com> malkarouri writes: > FWIW, I find #1 more interesting for me personally. > As a monad-challenged person, I find it much easier to develop > components using pure functional programming in a language like > Haskell and do all my I/O in Python than having it the other way > round. Haskell i/o is not that complicated, and monads are used in pure computation as well as for i/o. Without getting technical, monads are the bicycles that Haskell uses to get values from one place to another in the right order. They are scary at first, but once you get a little practice riding them, the understanding stays with you and makes perfect sense. From cwitts at gmail.com Thu Mar 20 07:38:04 2008 From: cwitts at gmail.com (Chris) Date: Thu, 20 Mar 2008 04:38:04 -0700 (PDT) Subject: A question about a metacharacter References: Message-ID: <09156537-3eb3-4cff-b1f6-3727ca660f6f@p73g2000hsd.googlegroups.com> On Mar 20, 1:19?pm, igbt wrote: > I am creating a simple script which is using gtk. In this script you > must enter a text, if you do not enter anything or you enter a dot, > the script will be finished. However, if you don't enter anything the > script works but if you enter a dot (.) the script does not work. I > was investigating about it and I think the problem is with the dot > character ?sss == "." . ?I was trying the same line with other > metacharacters like *, (, ) ... ?and I found the same problem. I was > looking for an example where I could see the way I could do it without > any error but I did not find it. Could somebody tell me how can I > solve this error? > > sss = entryName.get_text() ? ? ?# The script gets the text > ? ? ? ? if sss == "" or sss == ".": > ? ? ? ? ? ? ? ? gtk.main_quit() ? ? ? ?#The script finishes > > Thanks ; -) try this. sss = entryName.get_text() if not sss.strip() or sss.strip() == '.': gtk.main_quit() I wouldn't be suprised if your input is being captured with End-Of- Line characters which would cause the mis-match. From sjmachin at lexicon.net Fri Mar 7 18:12:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 15:12:57 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> On Mar 8, 1:53 am, "hvendelbo.... at googlemail.com" wrote: > On Mar 6, 9:17 pm, Luis M. Gonz?lez wrote: > > > > > On 6 mar, 11:27, Pierre Quentel wrote: > > > > Hi, > > > > I would like to know if there is a module that converts a string to a > > > value of the "most probable type" ; for instance : > > > - if the string is "abcd" the value is the same string "abcd" > > > - string "123" : value = the integer 123 > > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > > = the float -1.23 > > > - string "2008/03/06" (the format is also locale-dependant) : value = > > > datetime.date(2008,03,06) > > > > Like in spreadsheets, special prefixes could be used to force the > > > type : for instance '123 would be converted to the *string* "123" > > > instead of the *integer* 123 > > > > I could code it myself, but this wheel is probably already invented > > > > Regards, > > > Pierre > > >>> def convert(x): > > > if '.' in x: > > try: return float(x) > > except ValueError: return x > > else: > > try: return int(x) > > except: return x > > > >>> convert('123') > > 123 > > >>> convert('123.99') > > 123.98999999999999 > > >>> convert('hello') > > > 'hello' > > Neat solution. The real challenge though is whether to support > localised dates, these are all valid: > 20/10/01 > 102001 > 20-10-2001 > 20011020 Neat solution doesn't handle the case of using dots as date separators e.g. 20.10.01 [they are used in dates in some locales and the location of . on the numeric keypad is easier on the pinkies than / or -] I'm a bit dubious about the utility of "most likely format" for ONE input. I've used a brute-force approach when inspecting largish CSV files (with a low but non-zero rate of typos etc) with the goal of determining what is the most likely type of data in each column. E.g 102001 could be a valid MMDDYY date, but not a valid DDMMYY or YYMMDD date. 121212 could be all of those. Both qualify as int, float and text. A column with 100% of entries qualifying as text, 99.999% as float, 99.99% as integer, 99.9% as DDMMYY, and much lower percentages as MMDDYY and YYMMDD would be tagged as DDMMYY. The general rule is: pick the type whose priority is highest and whose score exceeds a threshold. Priorities: date > int > float > text. Finding the date order works well with things like date of birth where there is a wide distribution of days and years. However a field (e.g. date interest credited to bank account) where the day is always 01 and the year is in 01 to 08 would give the same scores for each of 3 date orders ... eye-balling the actual data never goes astray. From bjourne at gmail.com Mon Mar 17 18:24:21 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Mar 2008 22:24:21 +0000 Subject: Interesting math problem Message-ID: <740c3aec0803171524o727dd129ycfeaff4de5cbafdd@mail.gmail.com> Here is an interesting math problem: You have a number X > 0 and another number Y > 0. The goal is to divide X into a list with length Y. Each item in the list is an integer. The sum of all integers is X. Each integer is either A or A + 1, those should be "evenly distributed." Example: 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] 16 // 4 = 4 gives the list [4, 4, 4, 4] 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] This algorithm is used a lot in programming. For example, for projecting a line on a pixel display. Your mission, should you choose to accept it, is to improve the code given below which is my best attempt and make it more succinct and easier to read. Preferably by using list comprehensions, map or even reduce.... def make_slope(distance, parts): step = distance / float(parts) intstep = int(step) floatstep = step - intstep steps = [] acc = 0.0 for i in range(parts): acc += floatstep step = intstep if acc > 0.999: step += 1 acc -= 1.0 steps.append(step) return steps # Test code distance = 130 parts = 50 L = make_slope(distance, parts) assert(len(L) == parts) assert(sum(L) == distance) print L -- mvh Bj?rn From 42flicks at gmail.com Wed Mar 19 05:06:19 2008 From: 42flicks at gmail.com (Mike D) Date: Wed, 19 Mar 2008 22:06:19 +1300 Subject: PODCasts Message-ID: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> I really should say net cast as I think it's a better term ;) Does anyone have any recommended net casts on Python, or programming in general? Whats everyone listening to? Cheers Guys! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Glich.Glich at googlemail.com Tue Mar 25 16:36:06 2008 From: Glich.Glich at googlemail.com (Glich) Date: Tue, 25 Mar 2008 13:36:06 -0700 (PDT) Subject: python, dbus and pointers help. References: <16059cb8-a182-40ff-9617-a8b6708e1183@s19g2000prg.googlegroups.com> <61a383ca-e287-4d13-a3b0-ba9ec24626fa@d21g2000prf.googlegroups.com> Message-ID: <97d86072-b58b-4b0d-a0a0-143cb36e51ef@i7g2000prf.googlegroups.com> A replay from ubuntu forums: by Roptaty: Using dbus you can only get information from Pidgin, you cant modify the information. To do this, you need to write a plugin loaded in Pidgin. (See http://developer.pidgin.im/wiki/DbusHowto ) From jgardner at jonathangardner.net Fri Mar 21 15:18:57 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Mar 2008 12:18:57 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <23936074-babf-454f-b4a3-bc4207e209f9@e10g2000prf.googlegroups.com> On Mar 21, 4:48?am, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > Allow me to differ with all of the previous posts... Why don't you setup an SVN repository (or Git or DARCS, etc...) that has the current version you want to run? Then, execute the script in two steps: 1) Update the local copy from the repository 2) Run the script The only hard part is writing the script to do the above two things. Of course, that can be done with a python script (but if you were in the Unix world, I would suggest a shell script.) Or you can separate out the two steps. Update the SVN version once a day, or once and hour, or something like that. In general, my gut says to avoid writing new code when you can get away with it. From sjmachin at lexicon.net Tue Mar 18 15:26:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Mar 2008 12:26:33 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> Message-ID: <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> On Mar 18, 9:43 pm, Godzilla wrote: > Thanks Roel. If there is a way to pass in the PRESERVE_PRECISION > constant in the python time.clock library, that would be great Re-read Roel's message. Something like PRESERVE_PRECISION is to be passed to whatever is setting up DirectX. > But > I'm afraid it's not possible. I think I will change away from using > time.clock() from now on... seems too edgy to me. Are you using DirectX? If so, read the docs for more clues -- a quick google for "PRESERVE_PRECISION" will tell you that "something like" means what it says. If not, try posting some more info on what you are actually doing. Consider providing a short piece of code that demonstrates the actual problem. From myonov at gmail.com Tue Mar 25 14:51:20 2008 From: myonov at gmail.com (myonov at gmail.com) Date: Tue, 25 Mar 2008 11:51:20 -0700 (PDT) Subject: Disable resize button References: <47e7cca5$0$16036$5fc30a8@news.tiscali.it> Message-ID: On Mar 24, 5:45 pm, Francesco Bochicchio wrote: > Il Mon, 24 Mar 2008 04:38:50 -0700, myonov ha scritto: > > > > > Hi! > > > I need to disable resize button in Tkinter. I inherit the Frame class. > > Then in the constructor i make my buttons, labels, etc. Then I pack them > > and when move borders of the frame everything changes it's location and > > it looks really bad. How can I change that? > > That's my code: > > # -*- coding: cp1251 -*- > > import Tkinter > > > class App(Tkinter.Frame): > > def click(self): > > pass > > > def click2(self): > > pass > > > def __init__(self, master=None): > > Tkinter.Frame.__init__(self, master, width = 700, height = > > 400,\ > > bg = "#999999") > > self.pack() > > > # Buttons > > > self.b1 = Tkinter.Button(self, text = u"?????? ?????",\ > > command=self.click, font = "Courier", > > \ > > fg = "red") > > self.b2 = Tkinter.Button(self, text = u"?????? ???????",\ > > command=self.click2, font = "Courier", > > \ > > fg = "red") > > self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = > > 0.75, rely = 0.4) > > > # Labels > > > self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ > > text = u"??????????", fg = "#ffffff",\ > > bg = "#999999") > > self.l1.place(x = 275, y = 10) > > > # Text Control > > # self.txt = Tkinter.Text(self, bg = "#124456", ) # > > self.txt.pack() > > You could try including the frame in a toplevel window (e.g. passing > Tkinter.Tk() as super) and then doing super.wm_resizable(None, None) > > A better idea would be using pack instead of place, leaving to the > toolkit the job of rearranging the widgets when the window is enlarged > or reduced. > > Ciao > ----- > FB Thanks a lot :) Is there a way to avoid Tk() and to disable resize button only for an instance of a class which inherits Frame? From durumdara at gmail.com Tue Mar 11 05:00:12 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Tue, 11 Mar 2008 10:00:12 +0100 Subject: Python PDF + Pictures Message-ID: Hi, dear Python Masters! I wanna ask about the Python and PDF creating. I have many photos, and I wanna make some "presentation" from these photos, a "thumbnail" like document with one image per one page. If I wanna make one document now I do this: I execute a python script that create a html site with resized pictures, and split this html site to 50 images per one html file. Next I open these files in OpenOffice Writer by hand, and save them as PDF document with poor quality (image compression 95%, image DPI 75). This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that can opened everywhere (because of PDF format). But I wanna automatize this process with python. The technic that I will use is this: 1.) Collect the files in dirs. 2.) I process one dir in one time. 3.) I get the files. 4.) I resize them to max. 1024/768. 5.) I put the actual image file to the PDF document. 6.) After each 50. file I open new numbered PDF. 7.) Every picture placed in one page, and every page orientation set up as the picture orientation (Portrait or Landscape). The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. Do you knows about a PDF maker library with I can make this thing? Or other technic to simplify the making? Thanks for your help! dd From namit at namit.org Mon Mar 3 23:28:24 2008 From: namit at namit.org (Christian Kortenhorst) Date: Tue, 4 Mar 2008 04:28:24 +0000 Subject: cron popen xen-create-image Message-ID: Hey just wondering could anyone help me Have script that runs through cron but seams to run but xen-create-image goes to end but shoes up errors because some stuff it not being passed. ./grabJob.py # RUN all the Create ENVIRONMNET commands here run="/usr/bin/xen-create-image --hostname=%s --ip=%s" % (hostname, ipadd[0]) print run; try: fs=os.popen(run) for file in fs: error = error + file If run just ./grabJob.py it works ok and outputs en:/var/www/apache2-default# ./grabJob.py Grabbing Jobs running create Jobs runnning.... Creating environment ckortenhorst1 /usr/bin/xen-create-image --hostname=ckortenhorst1 --ip=192.168.0.111 DONE Can anyone help -- Christian Kortenhorst +353-(0)87-6183349 +353-(0)1-4966287 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Fri Mar 21 18:56:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 21 Mar 2008 15:56:34 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Message-ID: <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> Ricky Zhou: > Look at the this line: > if 'one' and 'two' in f: Very cute, it's the first time I see a bug like this. I think it's not a common enough pattern to justify a language change, but a bit smarter computer language may be able to do that too ;-) (it's not easy to tell the two meanings apart, from a simple point of view the semantics is ambiguous) Maybe an AppleScript-like language can be designed to have such capabilities too :-) A more computer-friendly (and Pythonic) syntax may be ('are' is a keyword): if ('one', 'two') are in f: ... That's sugar for: if all(x in f for x in ('one', 'two')): ... Bye, bearophile From mail at timgolden.me.uk Fri Mar 14 13:15:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 14 Mar 2008 17:15:26 +0000 Subject: request for Details about Dictionaries in Python In-Reply-To: <47DAB078.9050705@mattnordhoff.com> References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> <47DAB078.9050705@mattnordhoff.com> Message-ID: <47DAB2AE.80907@timgolden.me.uk> Matt Nordhoff wrote: > Michael Wieher wrote: >> I'm not sure if a well-written file/seek/read algorithm is faster than a >> relational database... >> sure a database can store relations and triggers and all that, but if >> he's just doing a lookup for static data, then I'm thinking disk IO is >> faster for him? not sure > > I would think that rolling your own solution would get complicated > enough that it would be easier to just use SQLite or something. If you > wanted to go to the effort, you could probably get something faster, but > if SQLite is fast enough, who cares? I would concur with this, in general. It may be that, for some very particular situations some specialised storage format is superior, but it's *very* easy to start writing your lean and mean data storage / algorithm / thingy only to run into *exactly* the same issues which the guys who wrote the existing ones have already hit and solved. Problems scaling; concurrency; robustness to error conditions and network / hardware issues &c. And in any case, the usual wisdom applies here: rather than guess which is faster, try it. (There is no "guess": only "try" ;) Using say SQLite (possibly in memory mode) and get some figures. Then do the same with a shelve solution or some prototype of your own devising and see where the gains are. TJG From sjmachin at lexicon.net Fri Mar 28 23:09:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Mar 2008 20:09:50 -0700 (PDT) Subject: Help me on function definition References: Message-ID: On Mar 29, 12:47 pm, "aeneng" wrote: > Hello everyone, > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this>>> import cross > > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 > ppp1=u[1]*v[2]-u[2]*v[1] > ppp2=u[2]*v[0]-u[0]*v[2] > ppp3=u[0]*v[1]-u[1]*v[0] > # store the result of the cross product in u > u[0]=ppp1 > u[1]=ppp2 > u[2]=ppp3 > return u #return the cross product of vector u x v. And you are stuffing the result into the first argument as well as returning the result ... not a good idea. > if __name__=="__main__": > from cvxopt.base import matrix > u=matrix([1.0,0.0,0.0],(3,1)) > v=matrix([0.0,1.0,0.0],(3,1)) > print cross(u,v) > print "file name is %s" %__name__ From martin at v.loewis.de Fri Mar 21 16:53:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 21:53:00 +0100 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] In-Reply-To: References: Message-ID: <47E4202C.5060400@v.loewis.de> > I've been thinking of volunteering to "port" Tkinter to Python 3.0, I > hadn't noticed that there was any discussion of removing it. It would > be a shame IMHO. I don't think Tkinter will be removed. It works just fine in 3k. Of course, if you would port IDLE to Tk 8.5: that would be a useful contribution. Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 22:54:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 02:54:53 -0000 Subject: string / split method on ASCII code? References: Message-ID: <13th5rtiqh2gnc6@corp.supernews.com> Sorry for breaking threading by replying to a reply, but I don't seem to have the original post. On Wed, 2008-03-12 at 15:29 -0500, Michael Wieher wrote: > Hey all, > > I have these annoying textilfes that are delimited by the ASCII char > for << (only its a single character) and >> (again a single character) > > Their codes are 174 and 175, respectively. > > My datafiles are in the moronic form > > X<>Z The glyph that looks like "<<" is a left quote in some European countries (and a right quote in others, sigh...), and similar for ">>", and are usually known as left and right "angle quotation mark", chevron or guillemet. And yes, that certainly looks like a moronic form for a data file. But whatever the characters are, we can work with them as normal, if you don't mind ignoring that they don't display properly everywhere: >>> lq = chr(174) >>> rq = chr(175) >>> s = "x" + lq + "y" + rq + "z" >>> print s x?y?z >>> s.split(lq) ['x', 'y\xafz'] >>> s.split(rq) ['x\xaey', 'z'] And you can use regular expressions as well. Assuming that the quotes are never nested: >>> import re >>> r = re.compile(lq + '(.*?)' + rq) >>> r.search(s).group(1) 'y' If you want to treat both characters the same: >>> s = s.replace(lq, rq) >>> s.split(rq) ['x', 'y', 'z'] -- Steven From arnodel at googlemail.com Tue Mar 18 18:45:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 15:45:42 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: On Mar 18, 9:56?pm, sturlamolden wrote: > On 18 Mar, 22:25, sturlamolden wrote: > > > def nonunique(lst): > > ? ?slst = sorted(lst) > > ? ?return list(set([s[0] for s in > > ? ? ? ?filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) > > Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using > the set function, there is more structure to exploit when the list is > sorted: > > def nonunique(lst): > ? ?slst = sorted(lst) > ? ?dups = [s[0] for s in > ? ? ? ? filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > ? ?return [dups[0]] + [s[1] for s in > ? ? ? ? filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] Argh! What's wrong with something like: def duplicates(l): i = j = object() for k in sorted(l): if i != j == k: yield k i, j = j, k >>> list(duplicates([1, 2, 3, 2, 2, 4, 1])) [1, 2] -- Arnaud From yuxi at ece.gatech.edu Mon Mar 10 19:48:21 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 10 Mar 2008 19:48:21 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > Thanks for the info! SIFT really looks like a heavy weight solution, > but do you think the whole concept can be simplified if all I needed > was: given a photo, find similar ones? I mean SIFT first detects > objects on the image and find similarities, but I don't need the > detection part at all, all I care about is similarity for the whole > photo. I surely don't understand the big picture fully but just have > the general feeling that SIFT and other expert tools are an overkill > for me and a simplified version would be just as good with a much more > easily comprehensible core algorithm. Please describe the kind of photos you are dealing with. Are they identical photos, in say different formats or with different metadata? Or are they rescaled images? Or maybe they are the same photo cropped differently? SIFT will work in more or less the process you described in your first post. It basically calculates the N sets of numbers for each image, representing the unique features of that image and their relative positions. The rest of the process if up to you. You have to compare the different sets of numbers to find the image with the minimal difference, as opposed to comparing the whole image. From jeffrey at fro.man Fri Mar 7 17:35:53 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 07 Mar 2008 14:35:53 -0800 Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <13t3gq9qo0po5ce@corp.supernews.com> shakefu at gmail.com wrote: > I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. Django comes with some pretty handy filters for doing this sort of formatting. Check out the "date", "now", "timesince" and "timeuntil" filters here: http://www.djangoproject.com/documentation/templates/#built-in-filter-reference Jeffrey From nothanks at null.invalid Sat Mar 22 23:25:25 2008 From: nothanks at null.invalid (Bill) Date: Sat, 22 Mar 2008 23:25:25 -0400 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <47E5CDA5.90709@null.invalid> sturlamolden wrote, On 3/20/2008 9:41 AM: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > What don't you like about wxGlade? It actually generates Python code. There has been a lot more development going on recently, too. Bill From willsteve2003 at yahoo.ca Mon Mar 10 10:43:59 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 07:43:59 -0700 (PDT) Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: <7a6555fa-819a-41c0-befe-ee0123272b31@59g2000hsb.googlegroups.com> On Mar 8, 4:15?pm, "Terry Reedy" wrote: > "egbert" wrote in message > > news:20080308152034.GA12009 at hccnet.nl... > | However the loop-else really works more like this: > | . ?try to do the loop; > | . ?if it starts but is interrupted by a break, > | . ?then do something else as well. > > This is NOT how loop-else works for Python. > If you want to do something special on breaks, > put the break-only code before the break. > > while loop_condition: > ? > ? if break_condition: > ? ? > ? ? break > ? > > | So they are completely different beasts, and if you try to use > | or explain the one according to the rules of the other one, > | you put a serious strain on your synapses. > > I did not mean to broke your brain. > > | The explanation that the if-else and the loop-else > | follow the same pattern, runs more or less like this: > | . ?all conditions to run the loop to its completion were met, > | . ?which means that the loop-condition is not met (any more), > | . ?which means that we must do something else. > | For me that is orwellian logic: success is failure. > > I gave a clear and coherent explanation of how while derives from if, > and correspondingly, how while-else derives from if-else, to help those who > want to read and write Python code. ?Building on the pseudo-snippet above, > one can write > > while loop_condition: > ? > ? if break_condition: > ? ? > ? ? break > ? > else: > ? > > Python allows one to have both break-only and completion-only sections > together in one compound statement and *without* having to fiddle with a > special flag variable. ?I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. > > If the sense of else were reversed, one would have to write the clumbsier > > complete = True # though false at this point > while loop_condition: > ? > ? if break_condition: > ? ? complete = False > ? ? break > ? > else: > ? > if complete: > ? > > Terry Jan Reedy Terry, instead of using "complete = True" and setting it to false on failure, why not set "loop_completed = False" and set it to True if the break condition is met? From fn681 at ncf.ca Fri Mar 21 10:09:39 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:09:39 -0500 Subject: Improving datetime In-Reply-To: References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <47E3C1A3.6050608@ncf.ca> Nicholas F. Fabry wrote: > On Mar 19, 2008, at 16:30, Christian Heimes wrote: > >> Nicholas F. Fabry schrieb: >>> This is a query for information as to how to proceed. I am not a >>> professional programmer, but I use Python a great deal to help me in >>> my main job, which involves designing schedules for a global >>> airline. As such, I use datetime (and dateutil) extensively, and >>> after much use, I have come to some conclusions about their utility, >>> and how to improve them. Some of these changes are quite minor and >>> would result in a large increase in utility (low hanging fruit), >>> while some changes are major, and would result in less obvious >>> benefits - but these changes would increase the 'Python Zen' of them. >>> So - where should I propose these changes? Here? python-dev? >>> Should I write up a full PEP or should I just give a more informal >>> outline with code samples? I would volunteer to help >>> maintain/improve datetime, but I don't speak C at all, >>> unfortunately, and datetime appears to be in C. >> >> Please write a detailed but not too long proposal to the Python ideas >> mailing list. The proposal should explain how you like to improve the >> datetime module. But *please* don't write a novel. You'll get more >> attention when the signal to noise ratio is high. A bullet list of >> features is easier to read than a long text block. >> > > Thank you for the prompt response and suggestion! I am writing up a > proposal presently. There are, however, two broad category of changes - > the 'easy' changes, which could be accomplished with little additional > effort, and the 'hard' changes, which would require significant > reworking of the datetime class (or a wrapper around it). I was going > to break my proposal up into two parts, the easy part and the hard > part. Does that sound like a good idea? Or should I unify the two? > The prime purpose of all the changes, easy and hard, is to make timezone > handling accurate and clear, reduce and make clearer the (application > programmer) code required to use them, and give more informaton to the > programmer about errors, not silently assume something and pass them. > > I have to sign up for that mailing list - I will do so, and submit my > ideas there. > > Please clarify how long a novel is? The problem with the modules are > not bugs, they are problems with real world use scenarios that result in > inescabably ugly code without improvements to the module - so the > explanations involve code samples and use cases... so they may be > 'long'. Could you suggest a maximum number of (70 char) lines, or an > example of an overly long proposal? > > >> I'm a core developer and I may be interested in mentoring your >> proposal. I can guide you through the process, review code and commit it. >> > > Thank you very much for the offer - I greatly appreciate it. I must > admit, my motivation is because Python made programming so much fun for > me again (my first machine was a Sinclair ZX80, long, long ago), and I > want to improve this part of the language so datetime calculations are > clean and neat (like the rest of Python) and don't force programmers to > manually go through what the library should do for them. > > >> Yes, the datetime module is written in C. But we may move the C code >> to _datetime and create a facade module in Python. >> > > That would be excellent for me, because the underlying datetime routines > work correctly and quickly; it's the 'topmost' layer that needs to be > improved to do the right thing. And, I could then actually > write/maintain the Python code in the facade module, rather than request > someone else 'do it for me' in C. > > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but > calculate/compare in UTC. > > - Raise exceptions when an illegal or ambiguous datetime is instantated. > > > Thank you again, > > Nick > > > > > > >> Christian Nick, You might consider adding the Julian date (http://en.wikipedia.org/wiki/Julian_date). I had a crack at this a while ago but didn't seem to get quire the right result, using the ACM algorithm. I seemed to be a day out at the BC/AD divide. Colin W. > From ptmcg at austin.rr.com Sat Mar 8 17:10:33 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 8 Mar 2008 14:10:33 -0800 (PST) Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> <47d2f0da$0$4794$4fafbaef@reader4.news.tin.it> Message-ID: <0d82e366-9112-4e45-930d-f53301a9741d@b1g2000hsg.googlegroups.com> On Mar 8, 2:02?pm, Nemesis wrote: > Bryan.Fodn... at gmail.com wrote: > > I have a large file that has many lines like this, > > > > name="DoseReferenceStructureType">SITE > > > I would like to identify the line by the tag (300a,0014) and then grab > > the name (DoseReferenceStructureType) and value (SITE). > > You should try with Regular Expressions or if it is something like xml there > is for sure a library you can you to parse it ... When it comes to parsing HTML or XML of uncontrolled origin, regular expressions are an iffy proposition. You'd be amazed what kind of junk shows up inside an XML (or worse, HTML) tag. Pyparsing includes a builtin method for constructing tag matching parsing patterns, which you can then use to scan through the XML or HTML source: from pyparsing import makeXMLTags, withAttribute, SkipTo testdata = """ SITE SITEXXX SITE2 """ elementStart,elementEnd = makeXMLTags("element") elementStart.setParseAction(withAttribute(tag="300a,0014")) search = elementStart + SkipTo(elementEnd)("body") for t in search.searchString(testdata): print t.name print t.body Prints: DoseReferenceStructureType SITE DoseReferenceStructureType SITE2 In this case, the parse action withAttribute filters tag matches, accepting *only* those with the attribute "tag" and the value "300a,0014". The pattern search adds on the body of the tag, and gives it the name "body" so it is easily accessed after parsing is completed. -- Paul (More about pyparsing at http://pyparsing.wikispaces.com.) From see.signature at no.spam Tue Mar 25 12:23:30 2008 From: see.signature at no.spam (Eric Brunel) Date: Tue, 25 Mar 2008 17:23:30 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: On Tue, 25 Mar 2008 16:37:00 +0100, Brian Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Gerard Flanagan wrote: > >> Use the child class when calling super: >> >> -------------------------------------- >> class Foo(object): >> def __init__(self): >> self.id = 1 >> >> def getid(self): >> return self.id >> >> class FooSon(Foo): >> def __init__(self): >> Foo.__init__(self) >> self.id = 2 >> >> def getid(self): >> a = super(FooSon, self).getid() >> b = self.id >> return '%d.%d' % (a,b) >> >> print FooSon().getid() >> -------------------------------------- > > That still doesn't do what he's trying to do. > > The problem here is that you only have one instance. self refers to it, > so when you set self.id in the super you have set the instance's id to > 1. When you set it to 2 after calling the super's __init__ you are now > setting the *same* variable to a 2. > > Basically, you can't do what you are trying to do without using a > different variable, or keeping track of a separate instance for the > super instead of sub-classing it. If for any reason it's better to have the same attribute name, it might be a case where a "pseudo-private" attribute - i.e. prefixed with __ - can be handy: -------------------------------------- class Foo(object): def __init__(self): self.__id = 1 def getid(self): return self.__id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.__id = 2 def getid(self): a = super(FooSon, self).getid() b = self.__id return '%d.%d' % (a,b) print FooSon().getid() -------------------------------------- For an explanation, see here: http://docs.python.org/ref/atom-identifiers.html HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From willsteve2003 at yahoo.ca Mon Mar 10 10:37:59 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 07:37:59 -0700 (PDT) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8b9469d6-5b73-4f5f-8aa5-51c8dfdb2fd0@y77g2000hsy.googlegroups.com> Message-ID: <4cd70ab7-7ba2-4f02-b180-415e555697e1@b64g2000hsa.googlegroups.com> On Mar 7, 5:26?pm, shak... at gmail.com wrote: > On Mar 7, 4:22 pm, shak... at gmail.com wrote: > [snip]> Although if I end up writing my own I'll sure use > > datetime.parser.parse to get everything left over once you remove > > I mean dateutil.parser.parse. Tomorrow I'll have to leave off the last > Lunchtime Guiness. > > > strings like "this saturday". So it helps a little! > > > Jacob > > And on the same thought - does anyone know of a good website, resource > or community that's got intelligible descriptions of all the different > modules that are generally available? I know if I tab complete 'apt- > get install python-*' it tries to list 1000-some possibilities, so I'm > thinking there's quite a few modules out there that I might like to > know about and use... > > Thanks! > Jacob Jacom, the http://www.python.org/ site offers most of the modules, including an index: http://pypi.python.org/pypi Then there's the ASPN site: http://aspn.activestate.com/ASPN/Downloads/ActivePython From mattheww at chiark.greenend.org.uk Wed Mar 5 15:33:21 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Mar 2008 20:33:21 +0000 (GMT) Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: gideon wrote: > In the context of a master's thesis I'm currently looking into > Python's operational semantics. Even after extensive searching on the > web, I have not found any formal model of Python. Therefore I am > considering to write one myself. To make a more informed decision, I > would like to ask you: [...] > Which version of Python is the most interesting? Python 3.0, although > it would be a moving target, seems promising. Because it will simplify > the language in some aspects by ditching backwards compatibility (e.g. > old style classes and coercion), the semantics will be more clean. Why not start with a common subset? Presumably the easiest thing will be to start with a small core of the language and work up anyway. It might turn out that all the interesting work has been done by the time 2.x/3.x makes any difference. -M- From jr9445 at ATT.COM Thu Mar 20 17:14:00 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 20 Mar 2008 16:14:00 -0500 Subject: Haskell vs ?? In-Reply-To: References: Message-ID: > From: python-list-bounces+jr9445=att.com at python.org > [mailto:python-list-bounces+jr9445=att.com at python.org] On Behalf Of > Michael Wieher > Sent: Thursday, March 20, 2008 4:36 PM > To: python-list at python.org > Subject: Haskell vs ?? > > Just to help clear up my own understanding of this discussion, this > is basically a language that obfuscates details and makes low-level > decisions in a "average-best" way, and thus allows for lazy people > to write kind of decent code quickly? Change "obfuscates details" to focuses on the right level of detail. C's details are too low. Python ignores details to the point that you don't find dumb type-casting mistakes until the code is actually being executed. "makes low-level decisions in a "average-best" way," Yes, just like how CPython is considered slow because of it's silly garbage collecting, too dynamically typed to be optimized, paradigm. > allows for lazy people to write kind of decent code quickly? No, it's not at all like a usenet group or mailing list where people are too lazy to post kind of thought out comments. ;-) The whole point of coding is to implement a requirement. A requirement is tied back to a business case, and a business case is an idea on how to get people to give you money in return for your service or product. Any code that doesn't directly implement the business case is 'overhead' (such as memory management, having to execute every single line of your Python code in order to catch type mismatches instead of having a compiler find such things early in development, having to write verbose|obfuscated syntax that requires more debugging since it's so verbose|obfuscated, responding to trolls, etc.) In theory, it follows the "less is more" strategy but without crossing the line into anarchy or the Wild West (i.e., no type checking,) while not being so syntactically brief as to look like hieroglyphics. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From mensanator at aol.com Tue Mar 4 15:13:44 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 12:13:44 -0800 (PST) Subject: sympy: what's wrong with this picture? References: Message-ID: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> On Mar 4, 12:32?pm, Nanjundi wrote: > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > > > Notice anything funny about the "random" choices? > > > import sympy > > import time > > import random > > > f = [i for i in sympy.primerange(1000,10000)] > > > for i in xrange(10): > > ? f1 = random.choice(f) > > ? print f1, > > ? f2 = random.choice(f) > > ? print f2, > > ? C = f1*f2 > > ? ff = None > > ? ff = sympy.factorint(C) > > ? print ff > > > ## ?7307 7243 [(7243, 1), (7307, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > As in, "they're NOT random". > > > The random number generator is broken by the sympy.factorint() > > function. > > > Random.choice() works ok if the factorint() function commented out. > > > ## ?6089 1811 None > > ## ?6449 1759 None > > ## ?9923 4639 None > > ## ?4013 4889 None > > ## ?4349 2029 None > > ## ?6703 8677 None > > ## ?1879 1867 None > > ## ?5153 5279 None > > ## ?2011 4937 None > > ## ?7253 5507 None > > > This makes sympy worse than worthless, as it fucks up other modules. > > Does seeding ( random.seed ) random with time fix this? It should. I suppose that depends on how long it takes factorint() to process a number. If the seed is reset before the next clock tick, you will get the same random numbers as the previous iteration. Frankly, I don't understand why factorint() reseeds at all. Doesn't Random automatically initialize the seed? Doesn't constantly reseeding degrade the performance of the random number generator? With Robert Kern's patch, the reseeding is no longer a constant, fixing the immediate symptom. But what if _I_ wanted to make a repeatable sequence for test purposes? Wouldn't factorint() destroy my attempt by reseeding on every call? > -N From fumanchu at aminus.org Tue Mar 18 14:41:17 2008 From: fumanchu at aminus.org (fumanchu) Date: Tue, 18 Mar 2008 11:41:17 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> Message-ID: <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> On Mar 17, 6:25 pm, dundeemt wrote: > I agree - the balance wasn't as good. We can all agree that HowTos > and Intros are a necessary part of the conference talks track, but as > Robert pointed out some talks should be of a more advanced nature. I > enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and > Mark Hammond's keynote were among my favorite talks. Raymond Hettinger's talk on collections was not only one of my favorites, it was apparently lots of other people's too--the room was PACKED. I can't recall seeing any other talk that was even close to seating capacity. Robert Brewer fumanchu at aminus.org From deets at nospam.web.de Mon Mar 17 17:53:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 22:53:11 +0100 Subject: Convert binary file In-Reply-To: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> References: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> Message-ID: <6487iaF2ar8k2U1@mid.uni-berlin.de> Vamp4L schrieb: > Hello, > Specifically, I'm trying to convert the Internet Explorer history > file (index.dat) into a readable format. Anyone done something > similar or know of any functions that may help with such a task? I'm > not sure exactly what kind of file the index.dat is, it is some kind > of binary file. I have tried some of the binascii functions (http:// > docs.python.org/lib/module-binascii.html) without any luck. > Thanks You have to have a definition of the format or reverse engineer it. If you have done that, you can use the module struct. But there is no generic way to infer how a binary format is built. Diez From john.jython at gmail.com Tue Mar 25 06:44:59 2008 From: john.jython at gmail.com (john s.) Date: Tue, 25 Mar 2008 03:44:59 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> On Mar 24, 9:39 pm, "Ryan Ginstrom" wrote: > > On Behalf Of john s. > > import os, sys, string, copy, getopt, linecache > > from traceback import format_exception > > > #The file we read in... > > fileHandle = "/etc/passwd" > > srcFile = open(fileHandle,'r') > > srcList = srcFile.readlines() > > > #yah, a for loop that "iterates" through the file of "lines" > > for i in srcList: > > strUsr = string.split(i,":") > > theUsr = strUsr[0] > > usrHome = "/expirt/home/",theUsr,"/" > > usrHome = ''.join(usrHome) > > How about for starters: > > import os > > for line in open("/etc/passwd"): > user, _pwd = line.split(":") ^----- Ok this one here we are taking a string spliting it into to variables... user gets one (the first) and _pwd gets to hold the "leftovers"? > user_home = os.path.join("/expirt/home", user) > > > try: > > os.makedirs('usrHome' ) > > except Exception, e: > > print e > > if os.path.exists(user_home): ^----- are(n't) exists and os.path.isadir interchangable? *nods in Bryan O. direction* > print "User Home dir exists, checking and fixing permissions." > else: > print "Do other stuff" > > Regards, > Ryan Ginstrom From castironpi at gmail.com Fri Mar 7 21:18:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 18:18:40 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> Message-ID: <67ff6575-92d2-4235-9fe0-44b4bd2960f8@u69g2000hse.googlegroups.com> On Mar 7, 4:07?pm, Steven D'Aprano wrote: > > I want to be able to detect if [certain threads] fail with error, > > You can't? Why ever not? Try this. ext can be found in 'C Function in a Python Context' on google groops. import ext extA= ext.Ext() extA[ 'araise' ]= r""" int araise( int a, PyObject* exc ) { int res= PyThreadState_SetAsyncExc( a, exc); return res; } """, ("i","i","O") LastCallException= type( 'LastCallException', ( Exception, ), { 'canstayhere': True } ) import thread import threading import time partystart= threading.Event() doorsclose= threading.Event() def thd(): partystart.set() try: while 1: print( 'running, ha ha!' ) time.sleep( .2 ) except Exception: print( '\nclean thread exit\n' ) finally: doorsclose.set() partyid= thread.start_new_thread( thd, () ) partystart.wait() print( 'waiting a second\n' ) time.sleep( 1 ) ret= extA.araise( partyid, LastCallException ) doorsclose.wait( 1 ) if not doorsclose.isSet(): print( 'Tell me about it.' ) print( 'clean exit\n' ) ''' waiting a second running, ha ha! running, ha ha! running, ha ha! running, ha ha! running, ha ha! clean thread exit clean exit ''' From george.sakkis at gmail.com Wed Mar 26 17:01:31 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 14:01:31 -0700 (PDT) Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: On Mar 26, 3:41 pm, Tim Henderson wrote: > I am using mysql, and sqlite is not appropriate for my situation since > some of the databases and tables I access are being accessed by other > applications which are already written and live. I am not using the > SQLAlchemy or SQLObject, because I didn't want too (although in the > future I may consider using them). I'd strongly second looking into SQLAlchemy; from what you wrote, I suspect sooner or later you'll end up creating (to paraphrase Greenspun) an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLAlchemy. George From blwatson at gmail.com Sat Mar 29 19:54:36 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Sat, 29 Mar 2008 16:54:36 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> Message-ID: <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> On Mar 29, 3:48?pm, "Diez B. Roggisch" wrote: > blwat... at gmail.com schrieb: > > > > > I am trying to install the twitter python wrapper...I got that > > installed just fine, but am having serious troubles getting the > > simplejson package to install. ?I need help diagnosing where this is > > failing. ?I am trying to use: > > >http://pypi.python.org/pypi/simplejson > > > and I run "python setup.py build" and then "python setup.py install", > > which both seem to work just fine. > > > I tried running with easy_install, but that too is not working. ?I end > > up with: > > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > > in my: > > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > > packages/ > > > I am on Mac OS X 10.5. ?Any help would be greatly appreciated. > > Go to the turbogears file section and download an appropriate version of > simplejson: > > http://www.turbogears.org/download/filelist.html > > I presume sj-1.7.4 is sufficient. > > Alternatively, be gentle to your unixish OS that OS X is, and install > XCode. Which will install the whole GCC chain, making your OS a > respected member of OS-community - as every system should be able to > compile C-code, in which itself has been written. > > Then the install should work as well. > > Diez I have already installed XCode...my compiel did not break the way the above did. I have grabbed the .egg file for simplejson 1.7.4 for Mac OS X 10.5 at the above link you provided - it has a simplejson dir, with the exact files that are in my simplejson directory for 1.8.1 (except none of my .py files have been compiled down to bytecode). I tried to add the directory "//simplejson" to my sys.path in the interpreter, hoping that the call to import simplejson would work if the dir was there, even though simplejson.py did not exist is that dir, but the encoder, decoder, jsonfilter and scanner .py files were all there. My problem is that the call "import simplejson" fails. How can I make that call work? Thanks in advance. From gagsl-py2 at yahoo.com.ar Tue Mar 18 03:19:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 00:19:56 -0700 (PDT) Subject: ctypes in python failed to honor c_int References: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> Message-ID: <49a1aad5-9020-4e6c-9389-502504a55ae4@u69g2000hse.googlegroups.com> On 18 mar, 04:12, Jerry Fleming wrote: > Gabriel Genellina wrote: > > On 17 mar, 23:57, Jerry Fleming wrote: > > >> I have a binary file written with c structures. Each record contains a > >> null-terminated string followed by two 4-bytes integers. I wrote a small > >> segment of python code to parse this file in this way: > >> [coe] > >> #!/usr/bin/python > > >> from ctypes import * > > >> class Entry(Structure): > >> ? ? ? ? _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) > > >> idx = open('x.idx', 'rb') > >> str = idx.read(1000) > >> obj = Entry(str) > >> print obj.w > >> print obj.s > >> print obj.l > >> [/code] > >> where the field w is the string, and s and l are the integers. Problem > >> is that, I can only get the strings, not the integers. Well, I did got > >> integers, but they are all zeros. What should I do to get the real numbers? > > > So the string has a variable length? For "Hello" you have > > 'h','e','l','l','o', a zero byte, followed by the two integers? This > > is somewhat unusual for a C struct (in fact you can't declare it in > > C). Perhaps the string is actually a char[n] array with a declared > > maximum size? > > Yes, it has a variable length. The C version of the structure is > something like this: > [code] > struct entry { > ? ? ?char *str, > ? ? ?int start, > ? ? ?int length} > > [/code] But this doesn't match the file contents. There are no pointers in the file. > And adding repr() would print something like this: > [code] > '(as) mad as a > hatter\x00\x00\x00\x00\x00\x00\x00\x00\x1f-ish\x00\x00\x00\x00\x1f\x00\x00\?x00 at -ism\x00\x00\x00\x00_\x00\x00\x00B-ist\x00\x00\x00\x00\xa1\x00\x00\x00J?.AU\x00\x00\x00\x00\xeb\x00\x00\x00P.EXE\x00\x00\x00\x01;\x00\x00\x00`.GIF\?x00\x00\x00' > (as) mad as a hatter > 0 > 0 > [/code] > where the first line is the result of repr(). We can find that, after > the null-terminated string '(as) mad as a hatter', there are two > integers, 0 and 31 (0x1f). But python treat 31 as zero. Ah, but it doesn't "treat 31 as zero". Entry(str) is the same as Entry(w=str), that is, you are initializing the w attribute alone, leaving the other two integers as 0. I don't know how to use ctypes to read the structure (nor if it is possible at all), I would read it normally with Python code and build the struct afterwards (in case it is used to call any C code). w, data = data.split('\x00', 1) s, l = struct.unpack("ll", data[:8]) data= data[8:] -- Gabriel Genellina From mnordhoff at mattnordhoff.com Fri Mar 14 13:06:00 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 14 Mar 2008 17:06:00 +0000 Subject: request for Details about Dictionaries in Python In-Reply-To: References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> Message-ID: <47DAB078.9050705@mattnordhoff.com> Michael Wieher wrote: > I'm not sure if a well-written file/seek/read algorithm is faster than a > relational database... > sure a database can store relations and triggers and all that, but if > he's just doing a lookup for static data, then I'm thinking disk IO is > faster for him? not sure I would think that rolling your own solution would get complicated enough that it would be easier to just use SQLite or something. If you wanted to go to the effort, you could probably get something faster, but if SQLite is fast enough, who cares? Hmm, if Perl's on-disk hash tables are good, maybe someone should port them to Python, or maybe someone already has. Also, for translations, maybe there's a good library already available. -- From jura.grozni at gmail.com Wed Mar 26 12:59:15 2008 From: jura.grozni at gmail.com (azrael) Date: Wed, 26 Mar 2008 09:59:15 -0700 (PDT) Subject: last mouse movment or keyboard hit References: Message-ID: You can use wxPython. Take a look on the DemoFiles that you can download also from the site. I remember that there has been a demo of capturing mouse coordinates and also one example about capturing Which key has been pressed at which time. Just start the time, count the interactions of key strokes and mouse gestures. Apply some statistics and voila. there it is. On Mar 26, 3:28?pm, Ron Eggler wrote: > Gabriel Genellina wrote: > > En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler escribi?: > > >> I would like to get the time of the most recent human activity like a > >> cursor > >> movement or a key hit. > >> Does anyone know how I can get this back to start some action after there > >> has been no activity for X minutes/seconds? > > > Which platform? On non-ancient Windows versions, you can periodically > > check GetLastInputInfo > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winu... > > No, it would be for Linux and preferrably it would work on MacOS & Windows > as well....is there anything? > Thanks! > -- > chEErs roN From craigm3604 at gmail.com Sat Mar 22 22:08:34 2008 From: craigm3604 at gmail.com (Craig) Date: Sat, 22 Mar 2008 19:08:34 -0700 (PDT) Subject: Anomaly in time.clock() References: <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> <0febu3lut6cpgikoe02snl0tju05gd8qs8@4ax.com> Message-ID: On Mar 22, 10:03 pm, Tim Roberts wrote: > Godzilla wrote: > > >Just found out that win32api.GetTickCount() returns a tick count in > >milli-second since XP started. Not sure whether that is reliable. > >Anyone uses that for calculating elapsed time? > > What do you mean by "reliable"? The tick count is updated as part of > scheduling during timer interrupts. As long as no one disables interrupts > for more than about 15ms, it is reliable. > > However, it's only a 32-bit value, so the number rolls over every 49 days. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Try getting XP or Vista to stay up for 49 days. I have had Vista stay up for a little over 11 days. If it doesn't crash, it will have to be rebooted for some update or other. From castironpi at gmail.com Fri Mar 14 03:02:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 00:02:06 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <13tk779gboqcgb9@corp.supernews.com> Message-ID: <3c1f0d7b-4f1d-4ec6-ba6f-ba4fa2833647@b1g2000hsg.googlegroups.com> > > Well, lets say you have a situation where you're going to be > > alternating between sending large and small chunks of data. Is the > > solution to create a NetworkBuffer class and only call send when the > > buffer is full, always recv(8192)? > > ? ? ? ? Or create a protocol where the first 16 bits (in network byte order) > contain a length value for the subsequent data, and use a receive > process that consists of: > > leng = ntoh(socket.recv(2)) > data = socket.receive(leng) > > (the send can combine the length with the data into a single packet) Are two 'sends' guaranteed to arrive as at least two 'receives'? Send-3: xxx Send-3: yyy Receive-6: xxxyyy From ndbecker2 at gmail.com Tue Mar 11 11:03:42 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 11 Mar 2008 11:03:42 -0400 Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? > > Thanks in advance, > Nathan P. import os os.system('factor 25') From Afro.Systems at gmail.com Tue Mar 25 07:44:34 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 04:44:34 -0700 (PDT) Subject: Inheritance question Message-ID: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> given two classes: class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = Foo.getid() b = self.id return '%d.%d' % (a,b) While my intention is to get 1.2 I get 2.2 I would like to know what would be the right way to yield the expected results From gagsl-py2 at yahoo.com.ar Thu Mar 27 14:54:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 15:54:12 -0300 Subject: Py2exe embed my modules to libary.zip References: <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> <1206639241.3132.0.camel@fc8.home.com> Message-ID: En Thu, 27 Mar 2008 14:34:02 -0300, Larry Bates escribi?: > Create your py2exe distribution without a zipfile and all the modules > will just be put into the installation directory. Use Inno Setup to > make a proper installer for your application. I second that. It's the easiest way. Another way it to help improve py2exe so it can find modules from inside a .zip and extract them (if this happens to be the cause). -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Mar 26 18:10:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 15:10:52 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: Sean Davis>Java has a BitSet class that keeps this kind of thing pretty clean and high-level, but I haven't seen anything like it for python.< If you look around you can usually find Python code able to do most of the things you want, like (you can modify this code to add the boolean operations): http://svn.zope.org/*checkout*/Zope3/trunk/src/zope/textindex/ricecode.py?content-type=text%2Fplain&rev=8532 (Later I have improved that code for personal use). But operations on such bit arrays are very common, and you may need them to be very fast, so you may use Cython (Pyrex) to write a small class able to do those things in a much faster way. Or you can also use Pyd plus an easy 30-lines long D program to write a class that does those operations very quickly (using a dynamic array of uint, with the help of www.digitalmars.com/d/1.0/phobos/std_intrinsic.html ). Maybe you can use GMPY numbers as bit arrays too. (I don't know if you can use NumPy for this using a compact representation of the bits). Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Mar 1 01:43:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Mar 2008 04:43:54 -0200 Subject: Telnet versus telnetlib References: <8acce230-4acf-43fe-9cb7-e4e50350381e@s13g2000prd.googlegroups.com> Message-ID: En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis escribi?: > When I do an analogous process using telnetlib, I get no debug output, > and most importantly, when I send the XML file to the host, I get no > printed page. Unfortunately, I do not have access to the host to do > troubleshooting there, so I have to "feel" my way around. Any > suggestions on what might be going wrong? > > In [12]: tn.write(""" > ....: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: On Mar 6, 1:20 pm, Jeroen Ruigrok van der Werven wrote: > -On [20080306 19:21], member thudfoo (thud... at opensuse.us) wrote: > > >An error occurred while loading > >http://www.martinrinehart.com/articles/python-grammar.html: > >Unknown hostwww.martinrinehart.com > > Works for me. > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/ > Possession is nine points of the law... The 404s are due to the trailing ':' -- Paul From adelagon at gmail.com Tue Mar 25 22:05:59 2008 From: adelagon at gmail.com (Alvin Delagon) Date: Wed, 26 Mar 2008 10:05:59 +0800 Subject: python hash() function Message-ID: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Hello, >>> hash("foobar") -1969371895 Anyone can explain to me how the hash() function in python does its work? A link to its source could help me a lot also. I'm looking for a way to replicate this function in php. Thanks in advance. --- Alvin -------------- next part -------------- An HTML attachment was scrubbed... URL: From damonwischik at gmail.com Thu Mar 27 13:34:19 2008 From: damonwischik at gmail.com (damonwischik at gmail.com) Date: Thu, 27 Mar 2008 10:34:19 -0700 (PDT) Subject: Set sys.stdout.encoding to utf8 in emacs/python-mode? Message-ID: I use emacs 22 and python-mode. Emacs can display utf8 characters (e.g. when I open a utf8-encoded file with Chinese, those characters show up fine), and I'd like to see utf8-encoded output from my python session. >From googling, I've found references to * locale.getdefaultlocale(), which is ('en_GB', 'cp1252') * sys.stdout.encoding, which is None * the environment variables LANG, LC_CHARSET and LC_ALL. http://mail.python.org/pipermail/python-list/2006-January/360068.html Should setting those environment variables give me a sys.stdout.encoding of utf8? What should I set them to? I tried setting LANG to en_GB and LC_CHARSET to utf8, but it doesn't have the effect of changing getdefaultlocale() or sys.stdout.encoding. Or is there some option I can set for python-mode so that it will instruct the python interpreter to use utf8 for its output? Damon. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:30:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:30:11 -0000 Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: <13t6tf3b5tpcv48@corp.supernews.com> On Sat, 08 Mar 2008 19:51:24 -0800, Lie wrote: > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as if > nothing happened. For example, if a variable turns into NoneType, it'll > raise Soft Exception that it have become NoneException, programmers that > wants to handle it can handle it with a try...except block while > programmers that doesn't care about it (or know it won't be a problem to > his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in a > way that Hard Exception must be handled at all cost or the program will > be terminated while Soft Exception allow programmers not to handle it if > they don't want to. I don't think that there are very many cases where exceptions can be ignored safely. There are two main reasons for using exceptions: (1) Signaling an exceptional event. (2) An error occurred. I can't think of many cases where you would wish to ignore either, and just continue processing. The only examples I can think of are in loops, where you are doing the same thing over and over again with just a little change, and you wish to skip any problematic data, e.g.: def plot_graph(func, domain): for x in domain: plot(x, func(x)) If an error occurs in plot() for one particular x value, you would want to ignore it and go on to the next point. But that's easy enough to do with a regular try...except block. Simply put, you're suggesting the following two alternatives: Hard Exceptions: terminate the program unless explicitly silenced Soft Exceptions: pass silently unless explicitly caught In this case, I agree with the Zen of Python ("import this"): Errors should never pass silently. Unless explicitly silenced. The cost of explicitly silencing exceptions is tiny, the risk of misuse of Soft Exceptions is very high, and the benefit of them is negligible. -- Steven From malaclypse2 at gmail.com Thu Mar 20 10:28:38 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 20 Mar 2008 10:28:38 -0400 Subject: dividing tuple elements with an int or float In-Reply-To: <13u45bam9k12n71@corp.supernews.com> References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> Message-ID: <16651e80803200728n2dead522s31766f534c357c06@mail.gmail.com> On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > > > > suppose > > origsz=(400,300) > > i want to divide the origsize by 2.5 so i can resize to (160,120) > > > > scale=2.5 > > how can i get the newsz? > > obviously origsz/2.5 won't work .. > > newsz = (origsz[0]/scale, origsz[1]/scale) That works fine for a 2-tuple, but might get unwieldy for larger tuples, or if you don't know the length until runtime. A more general solution might use a generator expression, like this: newsz = tuple(x/scale for x in origsz) -- Jerry From mh at pixar.com Sun Mar 9 20:42:47 2008 From: mh at pixar.com (mh at pixar.com) Date: Mon, 10 Mar 2008 00:42:47 GMT Subject: any chance regular expressions are cached? Message-ID: I've got a bit of code in a function like this: s=re.sub(r'\n','\n'+spaces,s) s=re.sub(r'^',spaces,s) s=re.sub(r' *\n','\n',s) s=re.sub(r' *$','',s) s=re.sub(r'\n*$','',s) Is there any chance that these will be cached somewhere, and save me the trouble of having to declare some global re's if I don't want to have them recompiled on each function invocation? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From jecarnell at saintfrancis.com Wed Mar 26 17:44:34 2008 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Wed, 26 Mar 2008 16:44:34 -0500 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: Message-ID: I vote a strong yes! I went through a MIS major and learned java first. This was a disaster for me typing these long nonsense lines (I didn't understand how classes and their members worked). Next was C and we had to use a command line and notepad to do all our programs. I really didn't learn much. After I graduated a friend told me to try python since I had this "screw programming" attitude. Actually I really did want to program. The fact that I could type one liners in without having to do make files and all that actually made it feasible for me to learn. I learned more from python and the tutorial list than 4 years of college. I really am serious! I'm going back now and learning C++ and might be able to learn crystal space 3d here before too long. James Carnell Steven D'Aprano wrote: > On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > >> Yes. And because Python is a "scripting language" > From pavlovevidence at gmail.com Mon Mar 10 16:59:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Mar 2008 13:59:21 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: Message-ID: On Mar 9, 7:41 pm, Roopan wrote: > Hello! > > I am looking at developing an enterprise-grade distributed data > sharing application - key requirements are productivity and platform > portability. > > Will it be sensible to use C++ for performance-critical sections and > Python for all the glue logic. > Pls comment from your *experiences* how Python scales to large > projects( > 200KLOC). > I assume the C++/Python binding is fairly painless. 200K with C++ lines of code or Python lines of code? :) I can comment on 50K lines of Python code, and considering how I write Python and how most people write C++ that might be about the same as a 200K C++ program. But it's not an enterprise app, so take it as you will. I've had no real issues. 95% of the program in Python; with only a couple sections written in C, and a few wrappers for C/C++ libraries. My wrappers are as thin as I can reasonably make them; where needed I make the interface prettier with a higher-level Python wrapper. I'm writing regular extensions, not using ctypes, Cython, SWIG, Boost::python or anything like that. I am using ctypes for some related tools and it's pretty nice. The others I can't comment on, except to say I sometimes didn't have enough memory to compile third- party SWIG extensions. I develop it on Linux, but every few months or so I'd copy it to Windows and update it so that it works on both. This was a minor hastle, which is not so bad considering it hadn't seen Windows for months. (In fairness, I am using the same compiler, gcc, on both. Getting mingw gcc to work on Windows was a major hassle, but a one- time thing.) Python's a lot better productivity-wise, and it's worked well as a cross-platform solution for me. The interfacing is the main drawback. It's always a bit of effort to interface things, and to get it working on multiple platforms, but I thought it was worth it. Carl Banks From gagsl-py2 at yahoo.com.ar Sun Mar 9 19:47:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 21:47:39 -0200 Subject: Intra-Package References References: <01d2be35-3e08-49d4-811b-a0d8b4fb5d27@n77g2000hse.googlegroups.com> Message-ID: En Sat, 08 Mar 2008 17:36:12 -0200, xkenneth escribi?: > Does your python module have to exist in the path in order for intra- > package references to work? No, but Python must be aware that the importing module is inside a package. So the script being executed (main) should live outside the package. -- Gabriel Genellina From david.avraamides at gmail.com Mon Mar 17 13:17:11 2008 From: david.avraamides at gmail.com (DavidA) Date: Mon, 17 Mar 2008 10:17:11 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 9:42 am, Mike Driscoll wrote: > Do you mean the "official" presentations or the lightning talks? I > thought both were kind of bad. Jeff Rush was great in both of the > sessions I saw and the gaming presenters were also good. But I saw a > lot of people who had never presented and were unprepared. In fact, > one didn't have any code whatsoever to share and the other one only > started showing some code during the last 10 minutes of his time. This was also my first time at PyCon and I thought I'd expand on what Mike said as I feel pretty much the same way. I also want to provide some constructive feedback that can hopefully help improve the next PyCon. I attended all the keynotes, 15 sessions and two days of the lightning talks. I was disappointed with about one-third of the keynotes and sessions. I found only a handful of the lightning talks interesting. My biggest complaint was the lack of preparation of the speaker: * in three cases the presenter had a recent problem with their laptop but had no back-up plan (dead drive, dead power supply, unable to get video out to projector). The presenters didn't have a copy of their presentation elsewhere (thumb drive, or even a printout) so they just winged it and the presentation was difficult to follow and ineffective. When I have presented at conferences in the past, we were required to submit our presentations and materials to the conference at least a week before so they could make them available on a web site and also on backup laptops at the conference. * the PyCon feedback survey doesn't allow for any useful feedback about the presentations. You only get to pick your five favorites. There should be forms available (hardcopy or online) where we can give feedback to the presenters themselves. My impression is that many of the speakers have presented at PyCon before and may do so in the future so this feedback can help them be more effective. I found it a bit ironic that I attended at least three sessions with a strong testing theme that talked about the importance of feedback in the development process and how it helped improve the quality of the final product, yet there was no channel to provide feedback to the presenters themselves. It seemed a glaring omission to me that the PyCon survey had questions about whether I shared a room (who cares?) but not about the quality of the presenters and presentations. * As a PyCon first-timer, I was not aware of the open meetings and BoF discussions while I was there. I feel like I might have missed one of the more valuable parts of the conference simply because I was ignorant. It would have been nice to get the word out a bit more - maybe an announcement each morning at the beginning of the keynotes. * There has been a lot of discussion about the reservation of lightning talk slots to sponsors. What I don't understand is why this wasn't disclosed at the conference. I've seen some of the organizers defend the "experiment" but no one explain why it wasn't mentioned beforehand. I'm left with the impression that the organizers knew this would be unpopular and didn't want to draw attention to it. I think a lot of this could have been averted by disclosing this change before the conference took place (in which case the community may have pushed back and convinced the organizers to reconsider the decision). Or at least it could have been disclosed at the conference so people could have decided to skip the lightning talks and organize their own ad-hoc meetings or talks. Experimenting isn't bad. But failing to disclose this information was a poor decision - especially at a conference that prides itself in openness and community involvement. * Lastly, I found the technical depth at most talks to be too shallow. I was especially surprised at this because I've only been using Python for two years, so I still think I'm a bit of a noob. But if you looked around at the conference, you saw a bunch of people who are really into programming (so much that many of them were doing it _during_ the talks) so to think that the audience isn't capable of following deep technical discussions is a bit off the mark. At other conferences I've attended and/or presented at, they would typically rate presentations as a level 1, 2 or 3. I think this would help set people's expectations. That coupled with session-level feedback, would help the organizers plan future PyCon sessions that better match the attendees' interests. That said, I did learn a few things at PyCon and found the overall experience pretty good. I simply had been hoping for a little more... -Dave From alex.pulver at gmail.com Thu Mar 13 03:52:40 2008 From: alex.pulver at gmail.com (Alex) Date: Thu, 13 Mar 2008 00:52:40 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> On Mar 12, 8:48 pm, Carl Banks wrote: > On Mar 12, 2:19 pm, Alex wrote: > > > Hi all, > > > The subject says pretty much all, i would very appreciate an answer. I > > tried to search the various forums and groups, but didn't find any > > specific answer... > > Python technically has no equivalent: you can't run code at compile > time. However, the BEGIN block in Perl seems to have been added to > work around some of Perl's nonlinear order of execution. Normally in > Python you don't need a BEGIN block: just put the code at the top of > you script/module and it will exectute before anything else. > > Want to tell us what you need it for? Perhaps we can suggest a way of > doing it that's appropriate in Python. > > Carl Banks Hi, First of all thanks all for answering! I have some environment check and setup in the beginning of the code. I would like to move it to the end of the script. But I want it to execute first, so the script will exit if the environment is not configured properly. Thanks, Alex. From grante at visi.com Thu Mar 20 11:21:13 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 15:21:13 -0000 Subject: Can I run a python program from within emacs? References: Message-ID: <13u50796m76e9c7@corp.supernews.com> On 2008-03-20, jmDesktop wrote: > Hi, I'm trying to learn Python. I using Aquamac an emac > implementation with mac os x. I have a program. If I go to the > command prompt and type pythong myprog.py, it works. Can the program > be run from within the editor or is that not how development is done? > I ask because I was using Visual Studio with C# and, if you're > familiar, you just hit run and it works. On Python do I use the > editor for editing only and then run the program from the command > line? http://www.google.com/search?q=emacs+python -- Grant From ilkeston at ntlworld.com Sun Mar 2 16:36:30 2008 From: ilkeston at ntlworld.com (Steve Turner) Date: Sun, 2 Mar 2008 21:36:30 -0000 Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: Christoph Zwerschke wrote: : Marc 'BlackJack' Rintsch schrieb: :: On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: :: ::: Apart from doing something like ::: a=[0,0,0] ::: b=[0,0,0] ::: c=[0,0,0] ::: d=[a,b,c] ::: ::: is there a better way of creating d?? :: :: a = [[0] * 3 for dummy in xrange(3)] : : Why not simply [[0]*3]*3 ? I've just tried that and it gives the same as my earlier b=[a,a,a] -- Steve From see at signature.invalid Thu Mar 13 16:40:58 2008 From: see at signature.invalid (Douglas Wells) Date: Thu, 13 Mar 2008 16:40:58 -0400 (EDT) Subject: subprocess.Popen pipeline bug? References: Message-ID: In article , Marko Rauhamaa writes: > > This tiny program hangs: > > ======================================================================== > #!/usr/bin/env python > import subprocess > a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, > stdout = subprocess.PIPE) > b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) > a.stdin.close() > b.wait() # hangs > a.wait() # never reached > ======================================================================== > > It shouldn't, should it? Yes, it should. This issue is related to the subtleties of creating a pipeline in POSIX environments. The problem is that the cat command in subprocess a never completes because it never encounters an EOF (on a.stdin). Even though you issue a close call (a.stdin.close ()), you're not issuing the "last" close. That's because there is still at least one file descriptor open in subprocess tree b. That happened because it was open when the subprocess module executed a POSIX fork call and it got duplicated as part of the fork call. I don't see any clean and simple way to actually fix this. (That's one of the reasons why POSIX shells are so complicated.) There are a couple of work-arounds that you can use: 1) Force close-on-exec on the specific file descriptor: import subprocess a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, stdout = subprocess.PIPE) # ********* beginning of changes import os, fcntl fd = a.stdin.fileno () old = fcntl.fcntl (fd, fcntl.F_GETFD) fcntl.fcntl (fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) # ********* end of changes b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) a.stdin.close() b.wait() a.wait() Or if it happens to not cause undesired side-effects for you, you can 2) Force close-on-exec *all* non-standard file descriptors by using the close_fds argument to Popen: import subprocess a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, stdout = subprocess.PIPE) # ********* beginning of changes # b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout, close_fds = True) # ********* end of changes a.stdin.close() b.wait() a.wait() Good luck. - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From gagsl-py2 at yahoo.com.ar Thu Mar 6 07:42:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 10:42:42 -0200 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: En Thu, 06 Mar 2008 08:33:41 -0200, Tom Wright escribi?: > I've written a program in Python using wxPython and Matplotlib and would > like to distribute it under the GPL. For ease of use, I'd also like to > distribute and installable version for Windows, but this needs > MSVCR71.dll > and MSVCP71.dll to work. I've created an installer using py2exe and Inno > Setup but I don't know if I'm allowed to distribute it or not. I've > found > lots of conflicting opinions online indicating that I can or cannot > distribute these, but no definitive answer. Maybe this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/f8df5ed32b324a3f/ can help. > The Microsoft Developer Network instructs me to read the redistribution > instructions and the EULA which come with Visual Studio, but I don't have > visual studio, so that's next to useless. This EULA doesn't apply to you, but to the Python developers, which are the actual Visual Studio users and have to comply with its license terms. You're just repackaging Python, your program, and other required components. In any case, I don't think MS cares; after all, you're promoting their OS and making life easier for Windows users. -- Gabriel Genellina From joshetomlinson at gmail.com Mon Mar 24 14:06:51 2008 From: joshetomlinson at gmail.com (joshetomlinson at gmail.com) Date: Mon, 24 Mar 2008 11:06:51 -0700 (PDT) Subject: importing package contents from multiple places in PYTHONPATH Message-ID: <6c6765d4-e1d7-4ca8-af96-e3c038fc5f3e@i7g2000prf.googlegroups.com> Hi all, I'm new to python, and am trying to determine if it's possible to do the following... I have a directory structure like this, with both 'dir1' and 'dir2' in my PYTHONPATH dir1/ foo/ __init__.py a.py b.py dir2/ foo/ __init__.py a.py c.py I'd like to be able to: python> import foo.a, foo.b, foo.c I'd hope for package 'foo.a' to come from dir1 since it was first on the path, with 'foo.b' and 'foo.c' coming form dir1 and dir2 respectively. I understand that python stops once it encounters the first 'foo' package in PYTHONPATH, but I was wondering if there was a way around this. I've had some success modifying __path__ in the foo/__init__.py files, but am unsure if this is the best approach. Perhaps there's a way to do this with import hooks? Is there a precedent for this type of thing? Thanks in advance, Josh From MadComputerGuy at gmail.com Tue Mar 11 22:50:01 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Tue, 11 Mar 2008 19:50:01 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> <306997c4-36dc-4603-8100-f47e25e55bef@s19g2000prg.googlegroups.com> Message-ID: <792e7610-7807-4deb-b13e-213d162cd2c0@d62g2000hsf.googlegroups.com> On Mar 11, 1:12 pm, Mensanator wrote: > On Mar 11, 3:36 am, Duncan Booth wrote: > > > Mensanator wrote: > > > On Mar 10, 10:44???pm, Nathan Pinno wrote: > > >> Why does my compiler say invalid syntax and then highlight the > > >> quotation marks in the following code: > > > >> # This program is to find primes. > > > > Needs work. > > > Be fair. > > Being helpful isn't fair? > > > The OP hadn't managed to figure out why the program wasn't > > running, so you can't expect him to have got all the bugs out of the code > > yet. > > The bug had already been answered. > > If you fail to implement your premise correctly, you have a bug. > > It doesn't matter if the code is bug-free if the premise is false. > > In this case, the premise that he can determine primes this way > is false. He will have to abandon the cos() thing, for although it > works in theory, he'll never get it to work in practice. > > Besides, the cos() is a red herring (hint: cos(pi*n)). The problem > can be made to work EXACTLY (at least up to z=10000) by using > rationals > (which gmpy supports). > > His problem is going to take much more than fixing a syntax error. > > > And he only asked about the specific syntax error not the entire > > solution to his homework. > > If this is indeed homework, and he's supposed to come up with a > factorial algorithm, I seriously doubt the teacher would accept > gmpy.fac(z-1), so I assume it isn't. > > > > > My advice to Nathan would be: > > > 1. If you get a weird syntax error that you don't understand try cutting > > the code down to just the bit which generates the error. > > > 2. Play around in the interactive interpreter to see what works and what > > doesn't. > > > 3. If you don't understand why the code doesn't work then get a stuffed > > toy, cardboard cutout of a person, or the least technical member of your > > family and explain to them in great detail exactly why the code must > > (despite error messages to the contrary) be correct. Usually you'll spot > > the problem half way through the explanation. > > > 4. If you post to this list then post the full error message and traceback. > > That way we don't have to guess which quotation marks are the problem. Yep, got it fixed, and no, it is not a homework problem...just a project for fun to keep up my Python coding in my memory intact (apparently, it doesn't work as well when I've been up early 3 days in a row... :P ). Now I just have to figure out why it isn't working the way it is supposed to. It was given to me by someone in the sci.math area as an alternative to working with 1 < x < n. From deets at nospam.web.de Fri Mar 28 04:58:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Mar 2008 09:58:05 +0100 Subject: Plugins accessing parent state In-Reply-To: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> Message-ID: <653q99F2e37q8U1@mid.uni-berlin.de> hajducko at gmail.com schrieb: > Does anyone have some design ideas ( or can point me at the right > design pattern, because I can't find it. ) for having a plugin being > able to access a parent's state? > > For example, let's say I have a class that receives some commands. > When it gets a command, it checks which of the registered plugins > deals with that command and passes the details of the command off to > that plugin. So I'd end up with something like.. > > result = plugin.do(msg_details) > > Now, I want to write a plugin called "help" that loops through all the > registered plugins and prints out their doc strings. If all my plugin > is getting is the msg details, how is it supposed to get the list of > available plugins from the calling class? > > Or, for instance, let's say my class loads a configuration file that > lists a set of admins who can enter commands. I want the plugins, if > they so choose, to be able to test if the msg came from an admin, but > again, I'm not passing the admin list into every plugin, it's just in > my calling class. I could make the plugin specify an attribute for > itself, like "admin_only" and test for that before I pass the command > but what if certain parts of the plugin are to be restricted and > others aren't, based on the details of the command sent? > > Is this as simple as just passing the instance of my class to each > plugin? It doesn't seem like the proper thing to do, because now the > plugin class has the capability of accessing the whole bot's > interface. Yes, it is simple as that. Of course you can choose *what* you pass, if you want to restrict that - nobody forces you to pass the whole plugin-manager, if that would expose properties/methods you wouldn't want ther. But to be honest: you are thinking much to far there - after all, it's all *your* code, and inside one interpreter. A real isolation isn't available anyway. So just do what fullfills the functional requirements. diez From paddy3118 at googlemail.com Thu Mar 13 01:17:37 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 12 Mar 2008 22:17:37 -0700 (PDT) Subject: How to port Python code into C++ code automatically? References: Message-ID: On Mar 13, 3:15 am, Bo wrote: > I want to port a Python project (about 10,000 line python code) to C+ > +. Is there any automatically tool to do this kind of things? e.g., > SWIG(http://www.swig.org/)? > > Any comment is welcome! > > Thanks! There isn't a magic porting tool available. If you said more about the why and the resources available then you might get a better answer. - Paddy. From kyosohma at gmail.com Wed Mar 19 15:55:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 12:55:21 -0700 (PDT) Subject: csv dictreader References: Message-ID: On Mar 19, 1:55 pm, brnstrmrs wrote: > On Mar 19, 2:32 pm, Mike Driscoll wrote: > > > > > On Mar 19, 1:06 pm, brnstrmrs wrote: > > > > I am trying to use the dictionary reader to import the data from a csv > > > file and create a dictnary from it but just can't seem to figure it > > > out. > > > > Here is my code: > > > > >>>import csv > > > >>>reader = csv.DictReader(open('table.csv')) > > > >>>for row in reader: > > > >>>print row > > > > my csv files looks like this: > > > > Bytecode,Element > > > \x00\x00,0000 > > > \x01\x00,0001 > > > .... > > > \x09\x00,0009 > > > > My output shows: > > > {'Bytecode': '\\x00\\x00', 'Element': '0000'} > > > {'Bytecode': '\\x01\\x00', 'Element': '0001'} > > > ... > > > {'Bytecode': '\\x09\\x00', 'Element': '0009'} > > > > 1. how can I get access to this directory > > > What do you mean? You can get each element in the dict by doing this: > > > for row in reader: > > print row['Bytecode'] > > print row['Element'] > > > > 2. why does the values come with two backslashs infront of the "x" > > > The double back slash is for escaping purposes, I think. If you print > > this: '\\x09\\x00' > > you'll get this: \x09\x00 > > > Mike > > Thanks. It works for the Bytecode but when I do print row['Element'] > I get a error message print row['Element'] KeyError: 'Element' That's weird. Since I only had your output, I did the following: reader = [ {'Bytecode': '\\x00\\x00', 'Element': '0000'},{'Bytecode': '\\x01\\x00', 'Element': '0001'} ] for x in reader: print x['Element'] print x['Bytecode'] 0000 \x00\x00 0001 \x01\x00 I must be missing something... Mike From HDoran at air.org Sat Mar 29 09:57:10 2008 From: HDoran at air.org (Doran, Harold) Date: Sat, 29 Mar 2008 09:57:10 -0400 Subject: Python and xml Message-ID: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> I am a python neophyte who has used python to parse through text files using basic functions and no OOP experience. I have a need to process some xml files and from what I am now reading python is the exact tool I need to work through this issue. However, as I read online docs and peruse which books to buy, I am quickly becoming overwhelmed with the topic and could use some guidance on how to best tackle my task. To frame the issue, here is what I would like to be able to do. I have a statistical program that outputs the data into an xml document. My goal is to use python to parse this document and output a .txt document or .csv document that organizes the results into human-readable rows and columns in a nicely formatted manner. As I read online docs about xml and python, it seems the topic is very big. While I am more than happy to invest significant time learning this topic, it may be possible to narrow the scope of what I need to know and be able to do in order to complete my task. Any suggestions on how I should proceed and/or fundamentals I need to learn? Is anyone aware of simple how to docs or other tutorials that demonstrate this kind of task? Thanks, Harold -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Sun Mar 9 14:57:00 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 09 Mar 2008 19:57:00 +0100 Subject: [pysqlite] [ANN] pysqlite and APSW projects moved In-Reply-To: <47D42EED.8070107@ghaering.de> References: <47D42EED.8070107@ghaering.de> Message-ID: <47D432FC.4040706@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gerhard H?ring wrote: > [...] APSW > ==== > > web: http://oss.itsystementwicklung.de/trac/apsw/ > scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX V7sH3uAskDDNBuxYG34vExI= =IXOx -----END PGP SIGNATURE----- From michael at stroeder.com Wed Mar 26 15:37:21 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Mar 2008 20:37:21 +0100 Subject: How to convert latex-based docs written with Python 2.5 to 2.6 framework Message-ID: HI! I had a look on how Doc/ is organized with Python 2.6. There are files with suffix .rst. Hmm... I'm maintaing existing docs for python-ldap which I might have to convert to the new concept in the long run. What's the recommended procedure for doing so? Any pointer? Ciao, Michael. From bbxx789_05ss at yahoo.com Wed Mar 19 20:01:39 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 19 Mar 2008 17:01:39 -0700 (PDT) Subject: is hash map data structure available in Python? References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Message-ID: <41f1b781-16e1-461c-8b9b-b26dfd6d2293@i29g2000prf.googlegroups.com> On Mar 19, 2:40?am, grbgooglefan wrote: > Hi, > I have a situation that I need to search a name in a big list of names > in my Python embedded interpreter. I am planning to use hash map for > quicker search. > How do I create hash map in Python? > Can you please guide me to some documentation or tutorial which > provides information on creating, editing, searching through hash map > in Python? > Thanks. #creating: my_dict = {'a':1, 'b':2, 'c':3} #editing: my_dict['a'] = 10 #searching: result = my_dict.get('a', None) print result //10 result = my_dict.get('f', None) print result //None From xkenneth at gmail.com Tue Mar 11 23:07:37 2008 From: xkenneth at gmail.com (xkenneth) Date: Tue, 11 Mar 2008 20:07:37 -0700 (PDT) Subject: Max File Size Message-ID: <1e8a2f49-e40b-4a6d-bc48-6d4f9a648c6d@s12g2000prg.googlegroups.com> Is the max file size a relevant issue in python anymore? I know OS X has a max file size of 8 exabytes and I'm not sure about the latest version of Ubuntu. Does python have an independent file size limit, or is it dependent upon the OS it was compiled on? Regards, Kenneth Miller From andre.roberge at gmail.com Thu Mar 27 07:18:49 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Thu, 27 Mar 2008 04:18:49 -0700 (PDT) Subject: Plugin framework - Overcomplicating things? References: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> Message-ID: <753fd116-95e0-4d5b-88b3-927861267577@e23g2000prf.googlegroups.com> On Mar 27, 3:31 am, "Gabriel Genellina" wrote: > En Thu, 27 Mar 2008 01:50:56 -0300, hajdu... at gmail.com > escribi?: > > > All this comes to my question - am I overcomplicating this project? I > > can understand the use of something like the trac component system if > > I had multiple components and plugins that handled different areas of > > my project and different points of interaction, but I don't. I've got > > exactly one spot where I want to check all my plugins and hand off the > > message to which ever ones are looking for that command. > > As you said, it looks like you're really overengineering your design then. > > > So really, > > should I even bother with trying to setup some framework for this or > > should I just be doing a simple loop over a directory, importing all > > the plugins and storing them in a list and then looping over them in > > the message handler to see which ones were looking for the command and > > letting them do their thing? You could set thing up so that there's no need to loop over the plugins. What you can do is register a plugin (as mentioned to you before by Gabriel - see below) and create an entry in a handler dict so that you can directly dispatch the message to the appropriate handler without having to loop over a list of them. Something like handlers[message]() > > That may be an option. > You may want to setup a simple registry mechanism, so the plugin modules > look like: > > ### begin niceplugin.py ### > class AVeryNicePlugin(object): # or perhaps using a suitable base class > def handle_message(self, message): > ... > > from plugin import PluginRegistry > PluginRegistry.register(AVeryNicePlugin) > ### end niceplugin.py ### > > Your application scans a known directory for files ending in "plugin.py" > and imports them; the modules register themselves any class (or classes), > and at appropiate times the application calls some method(s) of the > registered plugins. An alternative (which we found simpler with Crunchy) is to not have a class-based structure, but working with simple modules and functions. All modules are put in the "plugin" directory which are imported at the beginning. Each module contain at least two functions: 1. register() which create the handlers dict entry so that it point out to the appropriate function. 2. one or more function that is called based on the message received. Hope it helps, Andr? > From sean at ardishealth.com Sun Mar 2 14:09:39 2008 From: sean at ardishealth.com (Sean Allen) Date: Sun, 2 Mar 2008 14:09:39 -0500 Subject: mod_python Unable to create file In-Reply-To: References: <62v31gF24ontgU1@mid.uni-berlin.de> Message-ID: <85F61543-7ACD-4D9A-97A2-DB65D3B70B27@ardishealth.com> On Mar 2, 2008, at 3:24 AM, kaush wrote: > On Mar 1, 11:24 pm, Marc 'BlackJack' Rintsch wrote: >> On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: >>> I am using Apache and mod_python to service POST/GET requests on MAC >>> OS. My script tries to create a file >> >>> file = open(file_path, 'w') >> >>> This fails with the following error >> >>> EACCES >>> Permission denied >> >>> What is missing? >> >> To state the ovious: the rights to create a file at `file_path`. >> Remember >> that web servers usually have their own "user". >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Thanks Marc. > In Apache what are the ways/directives to set the rights to a folder? none. you set permissions via the operating system. chmod would be the command from terminal you are looking for. or you can do get info on the folder in question via the finder and set perms there. From sn7ewwp977b3g4tnwqce at gmail.com Wed Mar 12 15:10:19 2008 From: sn7ewwp977b3g4tnwqce at gmail.com (ayt46g6b) Date: Wed, 12 Mar 2008 12:10:19 -0700 (PDT) Subject: Make Money Using Paypal Get Paid Instantly Message-ID: Make Money Using Paypal Get Paid Instantly Make 1k-5k every week without leaving the comfort of your own home Click Here to Make Money Using Paypal and Get Paid Instantly http://freetrafficbuzz.com/recommends/cashdirectly From kveretennicov at gmail.com Sat Mar 29 18:12:52 2008 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sun, 30 Mar 2008 00:12:52 +0200 Subject: Python and xml In-Reply-To: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> References: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> Message-ID: <4660fe300803291512n5f5255e5v564f6bef2ac0f71d@mail.gmail.com> On Sat, Mar 29, 2008 at 3:57 PM, Doran, Harold wrote: > I am a python neophyte who has used python to parse through text files > using basic functions and no OOP experience. I have a need to process some > xml files and from what I am now reading python is the exact tool I need to > work through this issue. > > However, as I read online docs and peruse which books to buy, I am quickly > becoming overwhelmed with the topic and could use some guidance on how to > best tackle my task. > > You can start with this basic example (requires Python 2.5): spam.xml: Dinsdale (Face the Press) The Spanish Inquisition Deja vu The Buzz Aldrin Show Live From the Grill-O-Mat Snack Bar It's a Living The Attila the Hun Show Archaeology Today How to Recognize Different Parts of the Body Scott of the Antarctic How Not to Be Seen Spam Royal Episode 13 spam.py: from xml.etree.ElementTree import ElementTree as ET et = ET(file='spam.xml') for episode in et.findall('episode'): print episode.attrib['number'] + ':', '"' + episode.text + '"' Use standard csv module if you want to produce csv ouput ( http://docs.python.org/lib/module-csv.html). -- kv -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sat Mar 1 08:40:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 08:40:54 -0500 Subject: invert or not ? In-Reply-To: <47C93410.9050005@gmail.com> References: <47C93410.9050005@gmail.com> Message-ID: Stef Mientki wrote: > hello, > > from the manual I read that a bitwise inversion should be done by invert. > But from some experiments I see that not works equally well. > Is this coincidence ? > > (The disadvantage of invert is that I've to import operators) > Bitwise inversion is performed by the "~" operator. I think your experimentation has been inadequate: >>> for i in range(-10000, 10000): ... if (not i) == (~i): ... print i ... -1 >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gigs at hi.t-com.hr Mon Mar 31 18:25:34 2008 From: gigs at hi.t-com.hr (gigs) Date: Tue, 01 Apr 2008 00:25:34 +0200 Subject: class super method Message-ID: is there any tutorial for super method (when/how to use it)? or maybe someone could explain me how it works? thx From jeff at schwabcenter.com Thu Mar 20 02:53:22 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 19 Mar 2008 23:53:22 -0700 Subject: ftp recursively In-Reply-To: <7xk5jz1a80.fsf@ruckus.brouhaha.com> References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> <7xk5jz1a80.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Jeff Schwab writes: >> ftping it as a flat file, and untarring it on the other side. Of >> course, the motivation wasn't just to get the files from point A to >> point B using Unix (which I already know how to do), but to take >> advantage of an opportunity to learn some Python; next time, I'll try >> the ftpmirror.py script if it's generic enough, or ftplib if there are >> more specific requirements. > > I see, that wasn't clear in your original post. You should look at > the os.walk function if you want to know how to traverse a directory > tree (maybe you are already doing this). I thought os.walk was for locally mounted directories... How is it relevant on remote filesystems? > Also, for security reasons, > it's getting somewhat uncommon, and is generally not a good idea to > run an ftpd these days, even on a LAN. It's more usual these days > to transfer all files by rcp or rsync tunnelled through ssh. Don't shoot the messenger, but you're severely confused here. Whether you're using ftp, rcp, or rsync is a completely separate issue to whether you're running over ssl (which I assume you meant by ssh). FTP is a work-horse protocol for transferring files. It's going to be with us for a long, long time. There are various clients and servers built on it, including the traditional ftp command-line tools on Unix and Windows. rcp is a very simple tool for copying files from one (potentially remote) place to another. The point of rcp is that its interface is similar to cp, so the flags are easy to remember. Modern Unix and Linux systems usually include secure versions of both ftp and rcp, called sftp and scp, respectively. The point of rsync is to keep a local directory tree in sync with a remote one, by transferring only change-sets that are conceptually similar to patches. If you're only transferring files once, there's no particular benefit (AFAIK) to using rsync rather than some kind of recursive ftp. From castironpi at gmail.com Thu Mar 6 13:35:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 10:35:02 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> Message-ID: <1cf5a022-1b9d-4735-86f1-f18b018dbd82@59g2000hsb.googlegroups.com> > > > > I'm talking about castironpi. ?I find his posts a waste of my time > > > > "His" posts? > > > Whatever. ?I'm too old to worry about searching for politically correct, > > gender neutral pronouns. > > I'm pretty sure even the most PC people wouldn't suggest using a > masculine pronoun for an inanimate objects. > > (Ok, some probably would.) > > Carl Banks Traceback (most recent call last): File "", line 1, in AssertionError: Hey, that's not nice. >>> From needin4mation at gmail.com Thu Mar 20 11:57:38 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 20 Mar 2008 08:57:38 -0700 (PDT) Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: <0dd3f571-b044-4ea4-8e58-14b21dc3c7b8@z38g2000hsc.googlegroups.com> On Mar 20, 11:44?am, Jeff Schwab wrote: > jmDesktop wrote: > > On Mar 20, 11:21 am, Grant Edwards wrote: > >> On 2008-03-20, jmDesktop wrote: > > >>> Hi, I'm trying to learn Python. ?I using Aquamac an emac > >>> implementation with mac os x. ?I have a program. ?If I go to the > >>> command prompt and type pythong myprog.py, it works. ?Can the program > >>> be run from within the editor or is that not how development is done? > >>> I ask because I was using Visual Studio with C# and, if you're > >>> familiar, you just hit run and it works. ?On Python do I use the > >>> editor for editing only and then run the program from the command > >>> line? > > Sort of. ?Modern editors generally have support for building and running > your program directly from a toolbar button or textual command. ?I > personally use Vim with the toolbar disabled, running in a Terminal, and > run the program by first putting Vim in the background (^z). > > People writing code specific to Mac, but not necessarily all in Python, > often use XCode. > > ? ? ?http://zovirl.com/2006/07/13/xcode-python/ > > In the Ruby community, Vim is the dominant choice, but a lot of Mac > users swear by TextMate. > > ? ? ?http://macromates.com/ > > >>http://www.google.com/search?q=emacs+python > > Gee. ?Thanks. > > I believe Grant was suggesting that Emacs often serves a similar purpose > on Unix to what Visual Studio does on Windows, which seemed to be what > you were asking. ?When asking about Mac OS X here, you are likely to get > a lot of generic Unix responses. ?(Would it have been clearer if he had > just said "emacs?") No. Typically when someone posts a one-liner search it means go figure it out and stop bothering "us." I had already searched. I could not get it to work, which is why I posted. If I took it wrong I apologize. I really had two questions. One is just how to run a program from within the editor and the other is if my thinking on how development is done in python wrong to start with. Most of my non-Windows programs have been on Unix using vi, but it has been a while. I'm used to writing a program in visual studio and running it. If that's the wrong expectation for python programming in emacs, then I wanted to know. Thanks for your help. From jacob.kaplanmoss at gmail.com Sun Mar 16 11:56:39 2008 From: jacob.kaplanmoss at gmail.com (Jacob Kaplan-Moss) Date: Sun, 16 Mar 2008 08:56:39 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <8d6fbabd-2312-4324-9103-ead8600a2412@m36g2000hse.googlegroups.com> On Mar 16, 6:10?am, Bruce Eckel wrote: > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Thanks for being harsh here, Bruce. I've been responsible for organizing the lightning talks at PyCon over the past few years and Saturday's talks -- where a grand total of four community talks were given between twelve sponsor talks -- was the low point. I volunteer to run the lightning talks because they're usually by *far* my favorite time of the conference. Yesterday wasn't. > What was supremely frustrating was discovering that the people wanting > to give REAL lightning talks had been pushed off the end of the list > by this guarantee to vendors. We didn't get to see the good stuff, the > real stuff, because that time had been sold. Tell me about it. I felt like crap putting up a sign-up sheet with four names on it. Again, thanks for your harsh words, Bruce. Needed to be said. Jacob From gagsl-py2 at yahoo.com.ar Wed Mar 26 01:03:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 02:03:24 -0300 Subject: Prototype OO References: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> <13ujk0f9inb73c2@corp.supernews.com> Message-ID: En Wed, 26 Mar 2008 01:27:15 -0300, escribi?: > On Mar 25, 11:24?pm, Dennis Lee Bieber wrote: >> On Wed, 26 Mar 2008 06:49:57 +0800, "Delaney, Timothy (Tim)" >> declaimed the following in comp.lang.python: >> >> > As an aside, having lived much of my early life on a hobby farm, I've >> > often wondered to myself just what cow-orking involves ... ;) >> >> ? ? ? ? Probably millennia too late to ask Saruman... > > Solomon? No: http://en.wikipedia.org/wiki/Saruman -- Gabriel Genellina From arnodel at googlemail.com Mon Mar 17 18:57:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 17 Mar 2008 15:57:47 -0700 (PDT) Subject: Interesting math problem References: Message-ID: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> On Mar 17, 10:24?pm, "BJ?rn Lindqvist" wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > ? ? step = distance / float(parts) > ? ? intstep = int(step) > ? ? floatstep = step - intstep > > ? ? steps = [] > ? ? acc = 0.0 > ? ? for i in range(parts): > ? ? ? ? acc += floatstep > ? ? ? ? step = intstep > ? ? ? ? if acc > 0.999: > ? ? ? ? ? ? step += 1 > ? ? ? ? ? ? acc -= 1.0 > ? ? ? ? steps.append(step) > ? ? return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L > > -- > mvh Bj?rn OK then, using list comprehensions. It is more succint, is it easier to read? def slope(dist, parts): return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)] >>> slope(130, 50) [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] >>> len(slope(130, 50)) 50 >>> sum(slope(130, 50)) 130 >>> Smugly yours -- Arnaud From ds-python-list at sidorof.com Sat Mar 29 18:28:50 2008 From: ds-python-list at sidorof.com (DS) Date: Sat, 29 Mar 2008 15:28:50 -0700 Subject: Licensing In-Reply-To: <13utg1v4rs9c2d1@corp.supernews.com> References: <13utg1v4rs9c2d1@corp.supernews.com> Message-ID: <47EEC2A2.8040103@sidorof.com> Scott David Daniels wrote: > DS wrote: > >> I'm getting ready to publish a first open-source project written in >> python. I am planning to use GPL as the license. However, in my code, >> there is a function that I like from Python Cookbook.... >> So, my options appear to be: >> 1. Don't use it. >> 2. Use it with no comment -- that doesn't seem right. >> 3. Use it with remarks in the code that acknowledge the source. >> > I vote for this. If you got it of the web site, include a url. If you > went for the book, I'd prefer crediting both, but at least give enough > so the interested reader can get back to some version of "the original." > > >> 4. Provide a separate licensing page for that function >> along with the GPL for my code. >> What is the appropriate course of action here? I'm thinking #3 is >> probably ok. How do others deal with this in an honorable way? >> > As the author of several of those recipes, I definitely expect others > to use them. I'd hate to slow them up by requiring them to ask > permission, but would appreciate an acknowledgment. > > -Scott David Daniels > Scott.Daniels at Acm.Org > Thanks for your perspective. I'll do both. From miki.tebeka at gmail.com Tue Mar 11 15:06:36 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 11 Mar 2008 12:06:36 -0700 (PDT) Subject: How to make a Tkinter widget always visible? References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> <47D6C81A.1070301@codebykevin.com> Message-ID: Hello Kevin, > > Is there a way to make sure that these buttons are always visible? > > There are various ways to do this: you can set the window to be > non-resizable, or set a minimum size to it, so that it can't be resized > below that level. However, if you allow arbitrary resizing of the > window, there's no real way to guarantee that the widgets will be > visible at all times. Thanks. I've set a minimal size to the window. However when I resize it to be shorter, the buttons are hidden while the top frame stays visible. Thanks, -- Miki http://pythonwise.blogspot.com From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 19:51:21 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 01:51:21 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> Message-ID: <65anbqF2fg18bU1@mid.individual.net> Torsten Bronger wrote: > Emacs is generally not regarded as being convenient, however, it > has very strong input methods. I type "\gtrless" and get "?", > or "\forall" and get "?". I wonder where the point of this is. :) Why use fancy unicode chars if they're not better to read (apart from not being readable with every font) and require at least the same amount of keypresses? Regards, Bj?rn -- BOFH excuse #123: user to computer ratio too high. From tim.tadh at gmail.com Wed Mar 26 15:41:31 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Wed, 26 Mar 2008 12:41:31 -0700 (PDT) Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: Mike Driscoll said: > Besides, you should use sqlite rather than pickle databases. It's > especially easy since sqlite is included with Python 2.5. I am using mysql, and sqlite is not appropriate for my situation since some of the databases and tables I access are being accessed by other applications which are already written and live. I am not using the SQLAlchemy or SQLObject, because I didn't want too (although in the future I may consider using them). This question actually has nothing to do with the database, I simply put the information on the database in to give it some context. cheers Tim Henderson From sjdevnull at yahoo.com Mon Mar 3 17:30:01 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 3 Mar 2008 14:30:01 -0800 (PST) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 2, 1:18 pm, castiro... at gmail.com wrote: > On Mar 2, 12:01 pm, John DeRosa wrote: > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > >Hi, > > > >Have you ever seen Beautiful Python code? > > >Zope? Django? Python standard lib? or else? > > > >Please tell me what code you think it's stunning. > > > Just about any Python code I look at. > > Decorators, with, and namedtuple. IMO, decorators are functional but far from beautiful. They're a special, somewhat ugly syntax for something that was already handled by normal constructs ("foo=classmethod(foo)") that you didn't need extra knowledge to understand. On balance I think it's worth it in order to get those "declarations" up by the function defs, but it's sort of a tradeoff of magical non- explicitness for pragmatism over purity. A worthwile tradeoff, but not what I'd ever call beautiful. From fn681 at ncf.ca Sun Mar 2 13:59:34 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 02 Mar 2008 13:59:34 -0500 Subject: Problem with the strip string method In-Reply-To: References: Message-ID: castironpi at gmail.com wrote: > On Mar 2, 11:45 am, Steve Holden wrote: >> I suspect what you need is the .replace() method. > > The information's there-- the word 'contiguous' might clear it up a > bit. > >>> Return a copy of the string with the >>> leading and trailing characters removed. >>> The chars argument is a string >>> specifying the set of characters to be >>> removed. If omitted or None, the chars >>> argument defaults to removing >>> whitespace. The chars argument is not a >>> prefix or suffix; rather, all >>> combinations of its values are stripped: > > Return the string's substring from the first character not a member of > 'chars' to the last such. > > Remove contiguous leading and trailing members of 'chars'. If omitted > or None, 'chars' defaults over to the set of whitespace set( "\n\r\t > " ). (XXX TODO: ask Steve Reg Ex Guru this). Thanks to all respondents, Steve Holden is right, I expected more than I should have. Colin W. From dickinsm at gmail.com Thu Mar 13 21:50:18 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 13 Mar 2008 18:50:18 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: <1bfed08e-87e2-41d0-9f16-3c9d53dfa3c0@a70g2000hsh.googlegroups.com> On Mar 13, 8:38?pm, Alan Isaac wrote: > Does this do it? :: > > ? ? key= lambda x: (-x[1],int(x2)) > > Here I am depending on the lexicographic sorting of tuples. > Without that there would be real trouble. Close. :-) I think it needs to be something like: key = lambda x: (-x[0], int(x[1]) if x[0] == 0 else -int(x[1])) Relying on lexicographic sorting of tuples seems okay to me. What bugs me more about this example is that one has to rely on the existence of a way to negate the usual ordering. This is fine for numbers (where you can use the unary - operator) or for numeric strings (where you can convert to int and then use -), but it's not too much of a stretch to imagine cases where neither of those options is available (e.g. non-numeric strings), and where one ends up moving further and further from readable code and into the realm of arcane trickery... Mark From corynissen at gmail.com Fri Mar 7 10:33:54 2008 From: corynissen at gmail.com (corynissen at gmail.com) Date: Fri, 7 Mar 2008 07:33:54 -0800 (PST) Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: On Mar 7, 9:12 am, nodrogbrown wrote: > hi > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', > > can anyone pls help > gordon see path.join in the os library. From gagsl-py2 at yahoo.com.ar Tue Mar 4 10:05:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Mar 2008 13:05:54 -0200 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: En Tue, 04 Mar 2008 11:46:48 -0200, NickC escribi?: > A mildly interesting Py3k experiment: > > Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from fractions import Fraction >>>> from decimal import Decimal >>>> def check_accuracy(num_type, max_val=1000): > ... wrong = 0 > ... for x in range(1, max_val): > ... for y in range(1, max_val): > ... wrong += (x / num_type(y)) * y != x > ... return wrong > ... >>>> check_accuracy(float) > 101502 >>>> check_accuracy(Decimal) > 310013 >>>> check_accuracy(Fraction) > 0 > > > The conclusions I came to based on running that experiment are: > - Decimal actually appears to suffer more rounding problems than float > for rational arithmetic Mmm, but I doubt that counting how many times the results are equal, is the right way to evaluate "accuracy". A stopped clock shows the right time twice a day; a clock that loses one minute per day shows the right time once every two years. Clearly the stopped clock is much better! http://mybanyantree.wordpress.com/category/lewis-carrol/ -- Gabriel Genellina From nagle at animats.com Wed Mar 26 20:03:49 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 17:03:49 -0700 Subject: Some notes on a high-performance Python application. In-Reply-To: References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: <47eae223$0$36409$742ec2ed@news.sonic.net> Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 18:54:29 schrieb Michael Str?der: >> Heiko Wundram wrote: >>> Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: > I didn't say it was unusual or frowned upon (and I was also taught this at uni > IIRC as a means to "easily" distribute systems which don't have specific > requirements for response time to RPC requests), but anyway, as you noted for > Biztalk, it's much easier to hit bottlenecks with a polling-style RPC than > with a "true" RPC system, as I've come to experience when the number of nodes > (i.e., backends) grew over the last year and a half. I know, I don't like the polling either. The time scale is such that the poll delay isn't a problem, though, and because it's using the MySQL MEMORY engine, there's no disk I/O. After completing a request, the rating scheduler immediately queries the database, so there's no lost time if there's a queue. The polling delay only applies when a rating server is idle. I miss QNX, which has good message passing primitives. Linux is weak in that area. John Nagle From siddhantgoel at gmail.com Sat Mar 22 06:21:15 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Sat, 22 Mar 2008 03:21:15 -0700 (PDT) Subject: implementing tab completion using python Message-ID: <5f733b8e-b869-4f2b-930c-42a044935ad4@u10g2000prn.googlegroups.com> Hi. How can I implement a tab-completing code using Python? Like for example, I want to design a simple shell (using Python, of course), which could support tab completion as well. How do I go about it? Thanks. Siddhant From pofuk at email.t-com.hr Sun Mar 2 16:37:35 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Sun, 2 Mar 2008 22:37:35 +0100 Subject: Run Python app at startup Message-ID: Hy. I create simple application. Yust an windows and "compile" it with py2exe. I add registry value reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v MyApp /t REG_SZ /d C:\myapp.exe /f' And it wont start. When i use console instead od window in py2exe i get console opend but it closes. Program: import os import wx app = wx.App() frame = wx.Frame(None, -1, "MyFrame") frame.Show() app.MainLoop() Then in commang prompt: python.exe setup.py py2exe from distutils.core import setup import py2exe setup(console=['prog.py']) Help please! From bj_666 at gmx.net Thu Mar 13 03:53:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Mar 2008 07:53:42 GMT Subject: Class Inheritance References: Message-ID: <63s4s6F29blveU1@mid.uni-berlin.de> On Thu, 13 Mar 2008 00:06:52 -0500, "Andrew Rekdal" < wrote: > Problem is layout_ext and Layout code is dependant on a Class instance > 'css'. Then pass that instance to the `Layout` class in the `__init__()` so both, the base class and the subclass use the same `CSS` instance. Ciao, Marc 'BlackJack' From dteslenko at gmail.com Wed Mar 5 04:33:49 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 5 Mar 2008 12:33:49 +0300 Subject: draining pipes simultaneously Message-ID: <91325fec0803050133y158817efk761f719cc4c41f1e@mail.gmail.com> Hello! Here's my implementation of a function that executes some command and drains stdout/stderr invoking other functions for every line of command output: def __execute2_drain_pipe(queue, pipe): for line in pipe: queue.put(line) return def execute2(command, out_filter = None, err_filter = None): p = subprocess.Popen(command , shell=True, stdin = subprocess.PIPE, \ stdout = subprocess.PIPE, stderr = subprocess.PIPE, \ env = os.environ) qo = Queue.Queue() qe = Queue.Queue() to = threading.Thread(target = __execute2_drain_pipe, \ args = (qo, p.stdout)) to.start() time.sleep(0) te = threading.Thread(target = __execute2_drain_pipe, \ args = (qe, p.stderr)) te.start() while to.isAlive() or te.isAlive(): try: line = qo.get() if out_filter: out_filter(line) qo.task_done() except Queue.Empty: pass try: line = qe.get() if err_filter: err_filter(line) qe.task_done() except Queue.Empty: pass to.join() te.join() return p.wait() Problem is my implementation is buggy and function hungs when there's empty stdout/stderr. Can I have your feedback? From MartinRinehart at gmail.com Sun Mar 2 10:30:35 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sun, 2 Mar 2008 07:30:35 -0800 (PST) Subject: Python's BNF References: <85ae78f6-056b-4219-9952-66750e3ebf58@e60g2000hsh.googlegroups.com> <3e1d7bac-001d-498b-add5-2f2322795dd8@x41g2000hsb.googlegroups.com> Message-ID: Gabriel Genellina wrote: > About the generated page: I think it would be more useful if each symbol > links to its definition, instead of showing an alert(). This way it's > easier to navigate the tree, specially with complex declarations. That was my first shot. It didn't work. (Every line is its own table because you can't put named anchors inside a table, something I really regret.) If the production is already viewable, there's no jump when you click the link.. If the production is on the last page (many are) you jump to the last page and then have to hunt down the production. Remind me to figure out Ajax so you get what we really want: click on it and see its definition highlighted. > You can place the current text into a "title" attribute and most browsers > will show it as a tooltip. Great! Consider it done. Konqueror, Firefox, Opera and even MSIE. How would
,
and
make our lives easier? I also tried putting the definitions into the status bar. If you ever feel tempted to do something similar, let the urge pass. (This now works in Firefox 2 if you use the correct settings to allow javascript to write to the status bar. It doesn't work in Konqueror or Opera and I can't even find the settings for MSIE.) Trying to get this to work DID get me to considerably improve the readability of the HTML, so it wasn't a total waste. The tooltips are a big step forward. Thanks again. Improved version at http://www.MartinRinehart.com/articles/python-parse-bnf.html From jn.nntp.scrap001 at wingsandbeaks.org.uk Sat Mar 1 13:25:39 2008 From: jn.nntp.scrap001 at wingsandbeaks.org.uk (Jeremy Nicoll - news posts) Date: Sat, 1 Mar 2008 18:25:39 +0000 Subject: Import, how to change sys.path on Windows, and module naming? References: Message-ID: Jeremy Nicoll - news posts wrote: > If I understand correctly, when I import something under Windows, Python > searches the directory that the executing script was loaded from, then > other directories as specified in "sys.path". Sorry to followup my own question, but I ran for p,q in enumerate(sys.path): print p, q and got: 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms 1 C:\Program Files\~P-folder\Python25\Lib\idlelib 2 C:\WINDOWS\system32\python25.zip 3 C:\Program Files\~P-folder\Python25\DLLs 4 C:\Program Files\~P-folder\Python25\lib 5 C:\Program Files\~P-folder\Python25\lib\plat-win 6 C:\Program Files\~P-folder\Python25\lib\lib-tk 7 C:\Program Files\~P-folder\Python25 8 C:\Program Files\~P-folder\Python25\lib\site-packages 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip in their sys.path? What's the point of having a zip in the path? Also, looking in C:\WINDOWS\system32\ I don't actually have a file called python25.zip, but I do have one called python25.dll - so has something gone wrong in creation of sys.path? -- Jeremy C B Nicoll - my opinions are my own. From zerty.david at gmail.com Mon Mar 24 12:29:39 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 24 Mar 2008 13:29:39 -0300 Subject: Problems with wxPython Message-ID: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> Hi, If ther's anyone who knows pretty much about wxPython can e-mail me? I'm having some trouble in dealing with some guis here, I would thank u very much if you could help me bye []'s -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Bossy at jouy.inra.fr Mon Mar 17 09:36:51 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 17 Mar 2008 14:36:51 +0100 Subject: lists v. tuples In-Reply-To: References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <47DE73F3.8070901@jouy.inra.fr> castironpi at gmail.com wrote: > On Mar 17, 6:49 am, MartinRineh... at gmail.com wrote: > >> What are the considerations in choosing between: >> >> return [a, b, c] >> >> and >> >> return (a, b, c) # or return a, b, c >> >> Why is the immutable form the default? >> > > Using a house definition from some weeks ago, a tuple is a data > structure such which cannot contain a refrence to itself. Can a > single expression refer to itself ever? > In some way, I think this answer will be more confusing than enlightening to the original poster... The difference is that lists are mutable, tuples are not. That means you can do the following with a list: - add element(s) - remove element(s) - re-assign element(s) These operations are impossible on tuples. So, by default, I use lists because they offer more functionality. But if I want to make sure the sequence is not messed up with later, I use tuples. The most frequent case is when a function (or method) returns a sequence whose fate is to be unpacked, things like: def connect(self, server): # try to connect to server return (handler, message,) It is pretty obvious that the returned value will (almost) never be used as is, the caller will most probably want to unpack the pair. Hence the tuple instead of list. There's a little caveat for beginners: the tuple is immutable, which doesn't mean that each element of the tuple is necessarily immutable. Also, I read several times tuples are more efficient than lists, however I wasn't able to actually notice that yet. Cheers, RB From python.list at tim.thechases.com Tue Mar 4 17:02:02 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Mar 2008 16:02:02 -0600 Subject: sqlite3 permission issue In-Reply-To: References: Message-ID: <47CDC6DA.3030109@tim.thechases.com> > I am trying to execute an update to a sqlite3 db via a python cgi If you're running as a CGI, your script (as you guess below) will usually run with the effective permissions of the web-server. Frequently, this is some user such as "wwwdata" or "www". > conn = sqlite3.connect('db') Make sure that this is fully qualified: dbname = '/path/to/where/www/can/write/db' conn = sqlite3.connect(dbname) In addition, if your local user ("cstromberger" for example) owns that DB file, you'll need to make sure that www can access that file: bash> chown :wwwdata db (assuming the webserver runs with GID "wwwdata") and then make sure you've got 660 permissions on it (rw-rw----). Issuing a chown as non-root may be disallowed. > I can run the exact same python code from the command line and it > works, so it has something to do with the user that runs the cgi > (apache I assume). I chmodded the db file to 666, but it did not > help. If the DB file is truly read/write as you describe, I'm guessing that the path has not been properly resolved. It might be lazily opening the file, failing on first access rather than on the connect() call. You might also check to see if your Apache is running in a chroot jail which may prevent it from seeing files in particular paths outside that jail. Just a few ideas to test. If you know you can open the file and read from it (the path is fully-qualified and you have permission to open the file), then make sure your permitted to. It may help to make some stat() calls on the file to ensure that it's really where you think it is, and has the permissions you think it has. Hope they help, -tkc From http Tue Mar 18 03:50:46 2008 From: http (Paul Rubin) Date: 18 Mar 2008 00:50:46 -0700 Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> <7xod9cvbq3.fsf@ruckus.brouhaha.com> Message-ID: <7xskyoii7d.fsf@ruckus.brouhaha.com> Larry writes: > I even went further to opening the file using notepad, and did a > search-and-replace for space characters. The result was what I > desired: data,data,data... In Windows, you also have to make sure to open binary files in binary mode. From rbossy at jouy.inra.fr Sat Mar 1 08:51:58 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 01 Mar 2008 14:51:58 +0100 Subject: why not bisect options? In-Reply-To: References: Message-ID: <1204379518.47c95f7e37930@www.jouy.inra.fr> Selon Raymond Hettinger : > [Robert Bossy] > > I thought it would be useful if insort and consorts* could accept the > > same options than list.sort, especially key and cmp. > > If you're going to do many insertions or searches, wouldn't it be > *much* more efficient to store your keys in a separate array? > > The sort() function guarantees that it calls the key function exactly > once for each member of the list. With and bisect/insort, successive > searches can call the key function over and over again with the same > value. Yeah, sure. Thanks for pointing that out. RB From jeffrey at fro.man Tue Mar 4 14:22:04 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 04 Mar 2008 11:22:04 -0800 Subject: for-else References: Message-ID: <13sr8asd6vlnl52@corp.supernews.com> Carl Banks wrote: > there is a > rationale behind the name "else". ?If you consider a for loop to be a > rolled-up if...elif...else statement This is an interesting angle. I've always considered "for/else" to be unintuitive, not because of "else", but because of the coupling with "for". Instead, I think of this as a "break/else" statement, and everything gels for me. The same applies to my comprehension of "while/else". I wonder how this came to be called "for/else" or "for-else". I haven't spotted that expression in the python docs yet. With whatever name, I find the construct quite elegant and regularly useful. Jeffrey From mail at microcorp.co.za Sat Mar 15 04:59:44 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Mar 2008 10:59:44 +0200 Subject: List mutation method gotcha - How well known? References: <000901c884dd$057d5d80$03000080@hendrik> <740c3aec0803130806w2eed0c5eq2c0f0096557fce8@mail.gmail.com> Message-ID: <002501c8867a$ea23b580$03000080@hendrik> On Thu, Mar 13, 2008 at 8:36 AM, Hendrik van Rooyen wrote: > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above windows using idle: >>> foo = [1,2,3,4] >>> x = foo.append(5) >>> print x None >>> x >>> So the "Correct" answer is 5, and I would have allowed 4 also if it were a test, which it wasn't. I count ten responses, but this is probably wrong, as I did not receive digest number 171 which must have contained my original post. All of them seemed aware of the fact the append returned None. In any case, none of the respondents fell for the gotcha - answer 2, that assumes that the append returns the mutated list. One respondent wanted to choose the picture, but changed his mind. This leads me to conclude that this behaviour is well known amongst people in this group. Now this need not necessarily be correct either, as people who were uncertain could simply have declined to respond, or they were so honest that after checking, they found themselves morally unable to respond as that would have been cheating... : - ) I am constantly amazed and delighted by how well Python fits my brain - its the easiest assembler language I have ever used - almost everything "just works". This is true even if like me, you don't read the manual, but blunder your way along, guessing as you go - most of the time the guesses are right, and if they are not, a few minutes at the interactive prompt serves to dispel most illusions. Thanks to everybody who responded. - Hendrik From NeilFang2008 at gmail.com Mon Mar 3 01:37:38 2008 From: NeilFang2008 at gmail.com (Neil.Fang.CN) Date: Sun, 2 Mar 2008 22:37:38 -0800 (PST) Subject: class object interface document References: Message-ID: Thanks for your reply. What is the counterpart in v3.0? -- Neil On Mar 2, 6:26?pm, "Gabriel Genellina" wrote: > En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN ? > escribi?: > > > Where can I find the Python class object interface document, such as > > struct PyClassObject, PyClass_New()? Thanks! > > PyClass_* and PyInstance_* are for old-style classes and instances ? > respectively, and will disappear in v3.0. > PyInstance is in the section 7.5.2 in the Python/C API Reference Manual; I ? > don't find any documentation on PyClass itself. > > -- > Gabriel Genellina From timr at probo.com Sat Mar 1 02:11:39 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 01 Mar 2008 07:11:39 GMT Subject: Getting a free TCP port & blocking it References: <1dff2e2c-892d-42fa-9e65-5c7c12b75ec3@s13g2000prd.googlegroups.com> Message-ID: <280is3le2op8khmgr7nj5a1mnkjd7p0n50@4ax.com> theneb wrote: >Hi all, >I'm attempting to block a TCP port from any other application from >using it until I free it from python, this is so that: >1). Generate a random free user-space port >2). Generate the script for the external program with the port >3). Free the port before external program execution. What's the point? Why can't the actual user of the port create the port, and then notify the other side of the port number? And why don't you just specify a port number of 0 and let the system assign you a free port number? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sat Mar 8 12:37:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 09:37:48 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> Message-ID: <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> On Mar 7, 9:23?pm, shak... at gmail.com wrote: > I figured I might as well share the code I ended up using, in case > anyone else wants an easy way to get strings to, for instance, SQL- > storable datetimes. > > jake at house:~$ cat test.py > #!/usr/bin/python > from datetime import datetime > import subprocess > > def parsedate( date ): > ? ? p = subprocess.Popen(['date','+%s.%N',"--date=%s" % > date],stdout=subprocess.PIPE) > ? ? out = float(p.stdout.read()) > ? ? return "%s" % datetime.fromtimestamp(out) > > jake at house:~$ python -i test.py>>> parsedate("today") > > '2008-03-07 21:20:31.870489'>>> parsedate("tomorrow") > > '2008-03-08 21:20:40.516243'>>> parsedate("next monday") > > '2008-03-10 00:00:00'>>> parsedate("10pm last week") > > '2008-02-29 22:00:00'>>> parsedate("last tuesday") > > '2008-03-04 00:00:00' I am a GNU newbie. (I know C &o.) Can you point me to a place to find the source for 'date'? From troworld at gmail.com Sat Mar 1 18:56:27 2008 From: troworld at gmail.com (Tro) Date: Sat, 1 Mar 2008 18:56:27 -0500 Subject: Altering imported modules Message-ID: <200803011856.27611.troworld@gmail.com> Hi, list. I've got a simple asyncore-based server. However, I've modified the asyncore module to allow me to watch functions as well as sockets. The modified asyncore module is in a specific location in my project and is imported as usual from my classes. Now I'd like to use the tlslite library, which includes an asyncore mixin class. However, tlslite imports "asyncore", which doesn't include my own modifications. I'd like to know if it's possible to make tlslite load *my* asyncore module without changing any of the tlslite code. Thanks, Tro From mhwalker at shaw.ca Tue Mar 4 01:38:15 2008 From: mhwalker at shaw.ca (Mike Walker) Date: Tue, 04 Mar 2008 06:38:15 GMT Subject: Command line arguments in Windows In-Reply-To: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: > If you run a python file, ie. just double clicking it the only > argument you will have will be the filename of the script. If you > create a shortcut to the script and in the target box add your > arguments (if you have quotation marks place them after not inside) > you will see your arguments. fwiw you answered yourself in the third > paragraph. As I mentioned I am working from the command line, not clicking on the icon. The only difference between it working and not is the python prefix, which is why I was thinking this is some sort of file association problem. I probably wasn't as clear as I could have been in the third paragraph. argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] python argtest.py arg1 arg2 arg3 - Works From tejovathi.p at gmail.com Thu Mar 27 01:48:29 2008 From: tejovathi.p at gmail.com (Teja) Date: Wed, 26 Mar 2008 22:48:29 -0700 (PDT) Subject: copy file over LAN References: Message-ID: On Mar 27, 8:34?am, Astan Chee wrote: > Hi, > I have afileon another machine on the localnetwork(my machine and > local machines are on windows) and I want tocopyit locally. Now the > machine requires authentication and when I try to do a > import shutil > shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') > and it gives me a IOError: [Errno 13] Permission denied: error, which I > expect. How do I provide authentication tocopythisfile? > Thanks for the help. > Cheers > Astan > > -- > "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." > > Animal Logichttp://www.animallogic.com > > Please think of the environment before printing this email. > > This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. Hi, Is the folder where the file is present i.e. "temp" in your case, shared???? Can you share it and try it?? I tried this way and it worked! import shutil shutil.copyfile(r'\\129.124.66.112\Samplesharedfolder\samplefile.txt', r'C:\\Test\\temppp.txt') Try this way and let me know From sophacles at gmail.com Thu Mar 13 01:33:59 2008 From: sophacles at gmail.com (Erich) Date: Wed, 12 Mar 2008 22:33:59 -0700 (PDT) Subject: Generator woes Message-ID: Hi all, I am trying to get the following generator to work to these goals: 1. When it recieves an exception (via a throw()) it yeilds the value of handler.remaining. Otherwise it yeilds None. 2. Send adds data to the generator. Goal 2 is working great. Goal 1 on the other hand, is not working. The result of a throw is always None. Any reasons why this does not work as I expect? If not, what is wrong? Code: def make_handler(): def handler(): eol = '\r\n' handler.remaining = 1 response = '' data = '' while not response.endswith(eol): trv = None try: ndata = (yield trv) if ndata: response += ndata trv = None except: trv = handler.remaining response = response.strip() yield response * 2 res = handler() res.next() return res x = make_handler() y = x.send('a') print 'y (should be None):',y y = x.send('b') print 'y (should be None):',y y = x.throw(Exception) print 'y (should be 1):',y y = x.send('c\r\n') print 'y (should be abcabc):',y Output: y (should be None): None y (should be None): None y (should be 1): None y (should be abcabc): abcabc Thanks, Erich From gagsl-py2 at yahoo.com.ar Sun Mar 16 14:29:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 16:29:10 -0200 Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> <9b959898-ed57-47b9-8158-7ca6a321e705@u69g2000hse.googlegroups.com> Message-ID: En Sat, 15 Mar 2008 20:08:05 -0200, escribi?: > On Mar 15, 8:18?am, Bryan Olson wrote: >> castiro... at gmail.com wrote: >> > Newbie question: ?Can you write to the 'file-like object' a pickle, >> > and receive it intact-- as one string with nothing else? >> >> Yes, but there's a world of gotcha's. Sockets do not recognize >> record boundaries, and Python's 'pickle' has holes one's enemies >> could drive a truck through. Still, you can pickle, write, read, >> un-pickle, and get back your data intact. >> >> > I want to know because I want to send two pickles. >> >> "Two pickles" sounds like a tasty snack, but also suggests you may >> be playing hopscotch in a minefield. This is a helpful group. Give >> us more to go on, and you are likely to receive thousands of >> dollars worth of consulting for free. > > It depends on the situation. How generally applicable is this: > > fun ListenerGeneric( port, factory, arrivedfun ): > > which calls 'factory' on socketA.accept (and loops again), then > arrivedfun( stringA ) on message complete detection. ?. It should > start itself in a separate thread. > > Or is this any better: > > for x in connections(): > startnewthreadwith x: > for y in messages( x ): > arrivedfun( y ) This looks like a SocketServer + ThreadingMixIn + a RequestHandler (your factory). But as B. Olson already pointed, pickles are unsafe. Worse, it's not that someone could send a specially crafted pickle that could execute some arbitrary code: you're blindy executing whatever you receive! xmlrpc may be a good alternative in some cases. -- Gabriel Genellina From pavlovevidence at gmail.com Wed Mar 12 12:23:26 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 09:23:26 -0700 (PDT) Subject: a Roguelike in Python References: Message-ID: <776b49ce-852d-43da-ac56-6fc3cdcaca92@u72g2000hsf.googlegroups.com> On Mar 12, 9:25 am, Mdo... at gmail.com wrote: > Seeing the 7DRL start up recently, i wanted to see what one was made > of. Python is the language i'm most familiar with so i searched for > some code to look at, but i couldn't find any. Can anyone direct me to > the right place? > > I did some searching on what it would take to write a roguelike in > python and it looked like the curses module would work perfectly, but > it looks to me like it doesn't work in windows? I tried to import it > and it says 'No Module named _curses' > > Sorry if all this sounds a bit noobish, it's only cause i am. Correct, curses is not provided on the Windows platform. I recall that there were some third party attempts to implement curses functionality on Windows; try Googling for it. Even though it's typically used for graphical games, PyGame would be a good way to make a cross-platform "text-mode" game. It should be pretty straightforward to simulate a text mode terminal using a grid of sprites. (There might even be some third-party text terminals out there.) Carl Banks From PeterBraden1 at googlemail.com Sun Mar 9 09:30:24 2008 From: PeterBraden1 at googlemail.com (PB) Date: Sun, 9 Mar 2008 06:30:24 -0700 (PDT) Subject: Uninstalling Eggs Message-ID: I just installed the Shove module with the monumentally crap setuptools. Whilst the install succeeded, imports now trigger errors, so clearly it did not install correctly. Can I simply delete the .egg file from my lib/python2.3/site-packages/ directory? Cheers, From steve at holdenweb.com Sat Mar 1 12:48:04 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 12:48:04 -0500 Subject: pySQLite Insert speed In-Reply-To: <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> Message-ID: mdboldin at gmail.com wrote: > Steve, I want to make sure I understand. My test code is below, where > ph serves as a placeholder. I am preparing for a case where the number > of ? will be driven by the length of the insert record (dx) > > dtable= 'DTABLE3' > print 'Insert data into table %s, version #3' % dtable > ph= '?, ?, ?, ?' > sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) > t0a=time.time() > for dx in d1: > curs1.execute(sqlx,dx) > print (time.time()-t0a) > print curs1.lastrowid > conn1.commit() > > I think you are saying that sqlx is re-evaluated in each loop, i.e. > not the same as pure hard coding of > sqlx= 'INSERT INTO DTABLE3 VALUES ( ?, ?, ?, ? ) ' > Is that right? Yes. If the sql is constant then you would be performing an unnecessary computation inside the loop. Not a biggie, but it all takes time. Is the loop above your original code? If so I was wrong about the loop. > Hence (if I understand python convention), this can be > solved by adding > sqlx= copy.copy(sqlx) > before the looping. And in tests adding this step saved about 5-10% in > time. > Now this I don;t really understand at all. What's the point of trying to replace sqlx with a copy of itself? Perhaps if you explained what you hope this will achieve I could comment more intelligently. > And yes, I can see why (B) is always better from a security > standpoint. The python solutions for problems such as there are a > great help for people like me, in the sense that the most secure way > does not have a speed penalty (and in this case is 3-4x faster). Yes, it's a real win-win. Since both the table and the number of arguments appear to be variable one possible solution is to build a dict that would allow you to look up the right SQL using the table name. So, suppose you have the following tables and number of arguments: tables = (("table1", 3), ("table2", 5), ("table3", 2) ) you could create a suitable dict as (untested): tdict = {} for tbl, ct in tables: tdict[tbl] = "INSERT INTO %s VALUES (%s)" % \ (tbl, ", ".join(["?"] * ct)) Then you can use the table to look up the right SQL, quite a fast operation compared with actually building it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From python at rcn.com Tue Mar 18 13:49:00 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 18 Mar 2008 10:49:00 -0700 (PDT) Subject: Merging a patch/diff generated by difflib? References: <605b7f04-6306-4ac5-9633-7765a2e71060@k13g2000hse.googlegroups.com> Message-ID: <768fcb06-4318-41b6-84bd-6ce136c85f35@s12g2000prg.googlegroups.com> On Mar 18, 6:08 am, erikcw wrote: > Hi, > > I'm trying to create an undo/redo feature for a webapp I'm working on > (django based). I'd like to have an undo/redo function. > > My first thought was to use the difflib to generate a diff to serve as > the "backup", and then if someone wants to undo their operation, the > diff could just be merged/patched with the current text. > > However, I've not be able to find a patch library. Are there any > libraries that will handle merging the diff back into the text? The difflib module has a restore() function. Raymond From kyosohma at gmail.com Mon Mar 31 09:45:34 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 06:45:34 -0700 (PDT) Subject: wxPython; adding a grid to a panel References: Message-ID: On Mar 31, 8:33 am, Gilles Ganault wrote: > On Mon, 31 Mar 2008 11:01:19 +0100, "Moynes James" > > wrote: > >In the script below I have added two panels to a frame. I want to > >display the grid in one panel (and later on add other widgets to the > >other panel), but I cannot get the grid to display properly. > > I'm learning wxPython as well. Could it be that you're using > wx.PySimpleApp instead of App? That's not it...check out my other post with one sample solution. Mike From R.Brodie at rl.ac.uk Fri Mar 7 11:47:48 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 7 Mar 2008 16:47:48 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: "K Viltersten" wrote in message news:63d80bF273nraU1 at mid.individual.net... > 1. When writing English, Strunk and White apply. Do they? I've never seen them ;) > 2. You should use two spaces after a sentence-ending period. > > For heavens sake, why? Most people find it easier to type two spaces than one and a half. From deets at nospam.web.de Wed Mar 26 17:33:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 22:33:56 +0100 Subject: _tkinter fails when installing Python 2.4.4 In-Reply-To: <19b9409f-f4c3-4254-b445-980462f11bf1@13g2000hsb.googlegroups.com> References: <64tahuF2absebU1@mid.uni-berlin.de> <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> <64uoqiF2dcihhU1@mid.uni-berlin.de> <19b9409f-f4c3-4254-b445-980462f11bf1@13g2000hsb.googlegroups.com> Message-ID: <64vtqfF28jojsU1@mid.uni-berlin.de> jgelfand schrieb: > On Mar 26, 7:02 am, "Diez B. Roggisch" wrote: >> I think the actual problem is that the linking doesn't find the >> XftGlyphExtends. I can only guess, but it might be related to >> 64-bit-problems. Make sure you have the library that contains the >> XftGlyphExtends is available in the lib64 dirs and so forth. > > I tried running configure with --x-include="/usr/X11R6/include" --x- > libraries="/usr/X11R6/lib" (in addition to the flags above) and got > the same error. I believe XftGlyphExtends is defined in "Xft.h" which > is located in the directory "/usr/X11R6/include/X11/Xft". Based on > the output below, python looks in "/usr/X11R6/include" but not in this > directory: > > building '_tkinter' extension > gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- > strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ > yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ > usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ > yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/_tkinter.c - > o build/temp.linux-x86_64-2.4/_tkinter.o > gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- > strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ > yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ > usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ > yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/tkappinit.c - > o build/temp.linux-x86_64-2.4/tkappinit.o > gcc -pthread -shared build/temp.linux-x86_64-2.4/_tkinter.o build/ > temp.linux-x86_64-2.4/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib - > L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -ltk8.5 -ltcl8.5 - > lX11 -o build/lib.linux-x86_64-2.4/_tkinter.so > > When I try setting CFLAGS="-I/usr/X11R6/include/X11/Xft" and re- > running configure, I get the same error message regardless if I tell > python to it to use the 32 bit of 64 bit X-Windows libraries. How > should I force python to look in this directory? The above is a LINKER error, not a compiler-error. You need to find the library which contains the missing symbol, and trace where it get's picked up wrong. Not something (I at least) can do from here. Diez From esj at harvee.org Sat Mar 1 00:28:35 2008 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 01 Mar 2008 00:28:35 -0500 Subject: anydbm safe for simultaneous writes? In-Reply-To: <728f2166-00eb-41fa-a038-9853891e69cf@64g2000hsw.googlegroups.com> References: <728f2166-00eb-41fa-a038-9853891e69cf@64g2000hsw.googlegroups.com> Message-ID: <47C8E983.2000409@harvee.org> chris wrote: > I need simple data persistence for a cgi application that will be used > potentially by multiple clients simultaneously. So I need something > that can handle locking among writes. Sqlite probably does this, but > I am using Python 2.4.4, which does not include sqlite. The dbm-style > modules would probably be fine, but I have no idea if they are "write > safe" (I have no experience with the underlying unix stuff). Any tips > appreciated. the often repeated answer that you need locking is correct but an incomplete answer. it really depends on which DBM you are using. If you are using a fairly recent bsdbm (a.k.a. sleepy cat) it does have the kind of lucky needs to fairly complex transactions. Unfortunately, the API is a sufficiently unintelligible that it will take more than an afternoon to figure out how to even start to use it. gdbm is a nice DBM that permits single writer/multiple readers. If you open a DBM for read, any writer blocks. You open it for read and some times multiple readers can get in but not always (or at least that's the way it seems here in practice). when the DBM is busy, you will get an exception with an error value of: (11, 'Resource temporarily unavailable'). Just busy wait until this exception goes away and you'll get access to the DBM file. Yes, this officially sucks but at least it's a workaround for the problem. another way to solve this particular problem with DBM files is to stick inside a Pyro daemon. Performance won't be too bad and you should be able to get it working relatively easily. I will warn you that the RPC model for Pyro does take some getting used to if you're familiar with more traditional RPC environments. Once you wrap your head around the Pyro model, it's pretty nice. If you want, I can send you a copy of my Pyro daemon I use to wrap a DBM so I don't have to worry about multiple processes accessing the same DBM. the one thing that really bothers me about the DBM interfaces is that the two main DBM's are really quite full-featured but the documentation presents a very sketchy description of what they support and how. As a result, I suspect that DBMS don't get used as often as they could and people are pushed into more complex databases because they don't understand what DBM's are capable of. Other folks have recommended some form of SQL and while SQL light is a very nice small database, personally, I find SQL unintelligible and I have lost more days than I care to think about trying to figure out how to do something in SQL. As result, I tend to go more towards databases such as metakit and buzhug (http://buzhug.sourceforge.net/). the former is like gdbm and only handles a single writer. It's really intended for single process use but I don't know if you can put it in a Pyro controlled deamon. The latter looks pretty interesting because the documentation implies that it supports concurrent access on a per record level (menu item: concurrency control). Given that I'm currently replacing a DBM for very much the same reason you are, I'm going to try using buzhug rather than facing SQL again. I would be glad to compare notes with you if you care to go the same route. Just let me know off list. I wish you the best of luck in your project. ---eric -- Speech-recognition in use. It makes mistakes, I correct some. From bthate at gmail.com Tue Mar 4 14:11:18 2008 From: bthate at gmail.com (Bart Thate) Date: Tue, 4 Mar 2008 11:11:18 -0800 (PST) Subject: ANN: GOZERBOT 0.8 released Message-ID: <9734c9ac-281e-45a7-937a-bf5d8e4b91b7@d21g2000prf.googlegroups.com> so 0.8 is there and can be downloaded from http://gozerbot.org new features: * third party addons for plugins. (needs setup.py to work) * reboots without disconnects (irc only for now) * ipv6 udp support * queues used all over the place to reduce thread usage * normal irc log format is now supported (simplelog plugin) * irc can now be disabled for jabber only usage * owneruserhost is now a list so multiple userhosts can be used * jabber reconnect code is improved * rss error reporting is improved * udp code is improved especially in the jabber case * lots of other bug fixes problems with this release can be reported on http://dev.gozerbot.org or contact us on #dunkbots on IRCnet or freenode. email is at bthate at gmail.com the gozerbot development team ABOUT GOZERBOT: Requirements * a shell * python 2.4 or higher * if you want to remotely install plugins: the gnupg module * if you want mysql support: the py-MySQLdb module * if you want jabber support: the xmpppy module Why gozerbot? * provide both IRC and Jabber support * user management by userhost .. bot will not respond if it doesn't know you (see /docs/USER/) * fleet .. use more than one bot in a program (list of bots) (see / docs/FLEET/) * use the bot through dcc chat * fetch rss feeds (see /docs/RSS/) * remember items * relaying between bots (see /docs/RELAY/) * program your own plugins (see /docs/PROGRAMPLUGIN/) * run the builtin webserver (see /docs/WEBSERVER/) * query other bots webserver via irc (see /docs/COLLECTIVE/) * serve as a udp <-> irc or jabber gateway (see /docs/UDP) * mysql and sqlite support From bbkolde at gmail.com Thu Mar 20 13:47:00 2008 From: bbkolde at gmail.com (Bhagwat Kolde) Date: Thu, 20 Mar 2008 23:17:00 +0530 Subject: if __name__ == '__main__': In-Reply-To: References: Message-ID: Thanks all my problem cleared. Bhagwat On Thu, Mar 20, 2008 at 11:02 PM, 7stud wrote: > On Mar 20, 10:21 am, "Simon Brunning" > wrote: > > On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde > wrote: > > > Hi, > > > I am new to the python and not getting meaning of following line, > > > > > if __name__ == '__main__': > > > main() > > > > The if statement is used to skip the code after the if statement in > certain situations. If that if statement is in a file named test1.py, > and you issue this command: > > $ python test1.py > > then the code after the if statement will execute. That's because > python assigns the string '__main__' to the variable __name__ when the > program starts > > However, if you do this: > > ------- > #test1.py > def my_func(num): > print num * 2 > > > if __name__ == "__main__": > print "Testing my func:", my_func(10) > > -------- > > #test2.py > import test1 > > test1.my_func(5) > > ------- > > ...and you issue the command: > > $python test2.py > > Then the code after the if statement in test1.py will not execute. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Bhagwat K "Play hard or go home" -------------- next part -------------- An HTML attachment was scrubbed... URL: From sam at mas.pl Fri Mar 21 06:43:33 2008 From: sam at mas.pl (sam) Date: Fri, 21 Mar 2008 11:43:33 +0100 Subject: Prototype OO In-Reply-To: <47e384cb$0$567$426a74cc@news.free.fr> References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers napisa?(a): >> In dynamically typed language when you create object A that is >> inherited from another object B, than object A knows that B is his >> predecessor. So >> when you reference A.prop, then prop is looked in A first, then in B, >> then in predecessors of B, and so on. > > What you're describing here is the inheritance mechanism of Python. And > could apply just as well to javascript prototype mechanism. A javascript > object has a reference to it's prototype object - that you can > customize, rebind etc -, a Python object has a reference to it's class > object - that you can customise, rebind etc... I can see that Python and Javascript inheritance model is almost the same. Both languages are dynamically typed. And it seems that using "classes" in Python makes some things more complicated then it is necessary (eg functions, methods and lambdas are differen beeing in Python concept). > Don't be fooled by the term "class" itself - it's meaning is totally > different in a language like Python. Probably I'm not alone. Many people who think dymanic types are Rhight Thing in programming will also prefer prototype-based programming to class-based. > suspect you don't have a serious knowledge of Python's object model. Yes -- I'm new to Python. From gaohawk at gmail.com Sat Mar 1 04:01:55 2008 From: gaohawk at gmail.com (hawk gao) Date: Sat, 1 Mar 2008 17:01:55 +0800 Subject: A python STUN client is ready on Google Code. In-Reply-To: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> References: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> Message-ID: <8ce119530803010101w320b8d30md5112aebab6f7551@mail.gmail.com> I upload a new version. Add more print log into my code to help people understand my program 2008/2/29, hawk gao : > http://code.google.com/p/boogu/ > Enjoy it! > > > Hawk > From robert.kern at gmail.com Mon Mar 3 19:49:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Mar 2008 18:49:32 -0600 Subject: sympy: what's wrong with this picture? In-Reply-To: <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 4:53 pm, Carl Banks wrote: >> 3. You must be terribly naive if you expect a freeware program with a >> version number of 0.5.12 not to have bugs > > No, but I guess I'm naive thinking that when someone posts a link to > such a program that he's recommending going and trying it out. That > is why they're making it available, isn't it? For people to try out > so they can get free testing? Aren't I doing my part? Should I just > uninstall it and forget it? Finding the issue and reporting it to the sympy bug tracker is commendable. Coming here and "un-recommending" sympy before the issue was resolved is not. -- 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 nagle at animats.com Sun Mar 23 11:53:02 2008 From: nagle at animats.com (John Nagle) Date: Sun, 23 Mar 2008 08:53:02 -0700 Subject: Testing for an empty dictionary in Python Message-ID: <47e67a99$0$36364$742ec2ed@news.sonic.net> What's the cheapest way to test for an empty dictionary in Python? if len(dict.keys() > 0) : is expensive for large dictionaries, and makes loops O(N^2). John Nagle From sjmachin at lexicon.net Mon Mar 10 02:57:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Mar 2008 23:57:35 -0700 (PDT) Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: On Mar 10, 3:26 pm, DanielJohnson wrote: > Hi, > > I am trying to solve a genetic algorithm problem where I want to read > a bitvector of very large size (say 10000) and manipulate bits based > on certain algorithms. > > I am a newbie in Python. What data structure are good to read such > huge data set. Are there any built in classes for bit fiddling. > Bitwise operations like & | ^ << >> etc work on long integers. This happens at C speed. An alternative (in pure Python) is found via: http://pypi.python.org/pypi/BitVector HTH, John From duncan.booth at invalid.invalid Fri Mar 21 07:35:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Mar 2008 11:35:00 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> <13u5qbjq707as9e@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > I think you're confused. Or possibly I'm confused. Or both. I think it is you, but then I could be wrong. > It seems to me that you're assuming that the OP has opened the file > for reading first, and *then* another process comes along and wants to > open it for writing. That's not how I read his post: he's trying to > open a file for reading while it is already being written to by > another process. Asking for exclusive access when reading isn't going > to make any difference, because the other process has already opened > the file for writing. I'm assuming the other process has already opened the file for writing. In that case either it has asked for exclusive access so any attempt to open it for reading will fail, or it hasn't in which case Python's default 'open' will succeed but opening it for exclusive access will fail. Asking for exclusive access when opening will fail if another process already has the file open for reading or writing. > I suppose it is conceivable that the other process might have opened > the file for non-exclusive writing, assuming that such a thing is even > possible, but how likely is that? The usual situation is that the file is opened for writing but permits reading while it is being written. Then opening it to read will succeed unless you ask for exclusive access. BTW, I did test the 'CreateFile' code I posted: I opened the file for writing in one Python interpreter, just using open('...', 'w') wrote to it, and called flush but didn't close it. Then in another interpreter I checked that the CreateFile call threw an exception but open('...', 'r') succeeded and I was able to read what had been written. After I closed the file in the original interpreter the CreateFile call completed successfully. Try this: Session 1: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('test.txt', 'w') >>> f.write('Hello') >>> f.flush() >>> # go to session 2 ... >>> f.close() >>> f = open('test.txt', 'r') >>> # go to session 2 ... >>> f.close() >>> # go to session 2 ... >>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32file >>> handle = win32file.CreateFile("test.txt", win32file.GENERIC_READ, 0,None,win32file.OPEN_ALWAYS,win32file.FILE_ATTRIBUTE_NORMAL,None) Traceback (most recent call last): File "", line 1, in pywintypes.error: (32, 'CreateFile', 'The process cannot access the file because it is being used by another process.') >>> f = open('test.txt', 'r') >>> f.read() 'Hello' >>> f.close() >>> # go back to first session ... >>> handle = win32file.CreateFile("test.txt", win32file.GENERIC_READ, 0,None,win32file.OPEN_ALWAYS,win32file.FILE_ATTRIBUTE_NORMAL,None) Traceback (most recent call last): File "", line 1, in pywintypes.error: (32, 'CreateFile', 'The process cannot access the file because it is being used by another process.') >>> # go back to first session ... >>> handle = win32file.CreateFile("test.txt", win32file.GENERIC_READ, 0,None,win32file.OPEN_ALWAYS,win32file.FILE_ATTRIBUTE_NORMAL,None) >>> File open for writing in session 1: CreateFile throws an exception, open succeeds. File open for reading in session 1: CreateFile still throws an exception. File closed in session 1: CreateFile succeeds. From gandalf at shopzeus.com Tue Mar 11 10:59:36 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 11 Mar 2008 15:59:36 +0100 Subject: ZSI and attachments Message-ID: <47D69E58.5050306@shopzeus.com> Hi All, I wonder if the newest ZSI has support for attachments? Last time I checked (about a year ago) this feature was missing. I desperately need it. Alternatively, is there any other SOAP lib for python that can handle attachments? Thanks, Laszlo From martin at v.loewis.de Sat Mar 8 11:44:12 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Mar 2008 17:44:12 +0100 Subject: List as FIFO in for loop In-Reply-To: References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <47D2C25C.9050400@v.loewis.de> > Still, why avoid changing loop variable? Does python treat looping > over a list differently from looping over an iterator, where it > doesn't know if the iterator future changes while loop running? Take a look at Objects/listobject.c:listiterobject. It contains an it_index, which is the index into the list of the current iterator position. So if you delete items with indices smaller than the iterator index, the iterator index won't change, causing the iterator to skip over elements, e.g. L=range(10) for i in L: print i del L[0] Appending to lists will cause the new elements to be iterated over later. Whether that's desirable or not depends on the application. E.g. the following loop never terminates L=range(10: for i in L: L.append(i) Notice that the language specification *deliberately* does not distinguish between deletion of earlier and later items, but makes modification of the sequence undefined behavior to allow alternative implementations. E.g. an implementation that would crash, erase your hard disk, or set your house in flames if you confront it with your code still might be a conforming Python implementation. Regards, Martin From bearophileHUGS at lycos.com Fri Mar 21 08:55:47 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 21 Mar 2008 05:55:47 -0700 (PDT) Subject: removing all instances of a certain value from a list References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> <93e8ab20-8dd5-47d3-b977-822329889b52@a70g2000hsh.googlegroups.com> Message-ID: r.gr... at science-computing.de: > >>> a=filter ( lambda b: b != None, a) With None it's better to use is/not is instead of ==/!= Bye, bearophile From usenet at solar-empire.de Tue Mar 4 14:33:15 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 4 Mar 2008 20:33:15 +0100 Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> Message-ID: jefm wrote: > How can I print the unicode box drawing characters in python: > > > print u'\u2500' > print u'\u2501' > print u'\u2502' > print u'\u2503' > print u'\u2504' > > Traceback (most recent call last): > File "\test.py", line 3, in ? > print u'\u2500' > File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500' > in position 0: character maps to On linux in an utf8 console, it works with 2ython 2.4.4 and 2.5.1. It looks like your python is using cp 1252 for output. Which does not contain the box drawing characters. I don't think using a different encoding would work (e.g. print u'\u2500'.encode('cp437'), or print u'\u2500'.encode('utf8')) Marc From carsten at uniqsys.com Sat Mar 8 12:18:00 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 08 Mar 2008 12:18:00 -0500 Subject: SQL problem in python In-Reply-To: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: <1204996680.3161.11.camel@localhost.localdomain> On Sat, 2008-03-08 at 08:57 -0800, aiwarrior wrote: > def get_value( self, column ): > self.cursor.execute( "SELECT (?) FROM database", column ) > for n in self.cursor: > print n > > When i run it the get_value() returns 'filepath' instead of the > columns. But if i dont use any variable and make the expression static > all goes on as its supposed to. What am i doing wrong? Using parameter binding wherever possible is a Good Idea, but parameter binding can only be used to provide values. It can not be used to provide syntax elements, table names, or column names. Basically, only pieces that don't influence the query plan can be provided by parameters. To build a select query with a variable column name, you'll have to resort to some kind of string building mechanism: def get_value( self, column ): self.cursor.execute( "SELECT %s FROM database" % column ) for n in self.cursor: print n HTH, -- Carsten Haese http://informixdb.sourceforge.net From larry.bates at websafe.com` Tue Mar 25 10:52:38 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 25 Mar 2008 09:52:38 -0500 Subject: Outlook 2003 and Python In-Reply-To: References: Message-ID: <2pidnTOUdc03jHTanZ2dnUVZ_uqvnZ2d@comcast.com> cuordileone wrote: > Good Day. > > I woul like to ask you if it is possible to make a program in python > that move the email messages that I had received in outlook 2003, to a > specific folder, accoding to the sender's name: > > Es: martin at martin.com -->> folder Martin. > > Thanks. > > Riccardo. You could, but it is much easier to just use built in tools (from Outlook help): Automatically move messages from a certain person Select a message from the person whose messages you want to automatically move. On the Tools menu, click Organize. In the second bulleted item, click the options you want. To choose a folder, click the arrow next to the Into list. Click Create. Note To create more complex rules for organizing items, you can also use the Rules and Alerts dialog box on the Tools menu. -Larry From pi.arctan at gmail.com Sat Mar 8 10:28:35 2008 From: pi.arctan at gmail.com (pi.arctan at gmail.com) Date: Sat, 8 Mar 2008 07:28:35 -0800 (PST) Subject: extract multiple ranges from a list Message-ID: Hi guys, One of my many project involves working with YUV-files, where I need to reduce the vertical resolution with a factor of two, i.e. remove every other scan line. Today I'm using two for-loops in the fashion shown below y = [] for i in range(0, width*height, width*2): for j in range(0,width): y.append(Y[i+j]) This approach doesn't feel very pythonic but I can't come up with a better idea to do it. I've tried list comprehension and map together with lambda but I can't get a flattened list of every other scan-line... CIF = 352x288 items for luminance and the aim is to have the list below: y = [0:352 704:1056 ... ] //Fredrik From Lie.1296 at gmail.com Sun Mar 9 13:45:33 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 10:45:33 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <13t7nfdmdtuf7be@corp.supernews.com> Message-ID: On Mar 9, 7:54?pm, Steven D'Aprano wrote: > On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote: > > (3) Informing codes above it about what's currently happening inside, > > the thing is just a mundane report that might be useful to codes above > > > Which might be a useful place to use SoftExceptions > > Okay, now we're getting somewhere. > > So, I have a function foo() which raises a HardException on error, but it > also raises a SoftException if it wants to notify me of something > "mundane". > > def foo(sequence): > ? ? if args == []: > ? ? ? ? raise SoftException("empty list") > ? ? return len(args) > > Now, how do I use that? > > try: > ? ?x = foo(something) > except TypeError: > ? ?print "you should pass a sequence" > ? ?sys.exit() ?# unrecoverable error > except SoftException: > ? ?print "you passed an empty list" > print x > > Am I close? > > But there's a problem. Once the SoftException is caught, execution will > continue from the line "print x" -- but the function foo() never got a > chance to actually return a result! In that particular case above, you don't need to handle the Soft Exception. As stated in it's original purpose, you don't need to handle a Soft Exception, it exists there if you need to handle the exceptional case, but ignorable on other cases. _IF_ printing the "you passed an empty list" is an important operation, you'd make it like this: try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" x = 0 print x or alternatively: try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" else: print x The case you states above only mentions that you haven't fully grasped the workflow in exception-based system. > In order to make that work, you would need a significant change to > Python's internals. I don't know how difficult that would be, but I'm > guess that it would be a lot of work for not much benefit. I too don't know how difficult that'd be, especially because the only thing I know about Python's internal is it implements its garbage collector by ref counting (which is barely useful here). > But even if that happened, it would mean that the one mechanism has TWO > different effects: > > try: > ? ? x = foo(sequence) > except SoftException: > ? ? print x ?# this is okay, because foo() did return > except TypeError: > ? ? print x ?# this is NOT okay, because foo() never returned > > That is a recipe for confusion. Both are not okay since foo() never return on both cases (soft statement doesn't return to finish the try clause except if explicitly resumed). (snip) > > Perhaps relabeling it as Warning, and renaming raise SoftException as > > give Warning might make it more acceptable? > > Do you realise that Python already has a warnings module? Ah... I completely forget about it, but anyway the Warning module is unrelated to this. Perhaps we could just think of another name, but names doesn't seems to be important in Python modules anyway, can you guess what pickle/zip/mutex/quopri/curses is if you're new to Python without looking at the documentations? There are some modules in Python that have weird names, we ought to reduce it, but we can't reduce it... we ought to live with it. (snip) > > A possible solution to this problem might be to check whether distance > > is less than P1.radius + P2.radius in the calculateforce. But, this > > obfuscate the code since we have to separate distance calculation from > > the main formula (see !s), > > I don't agree that this obfuscates the code. For a formula as complex as this: http://www.mapleprimes.com/blog/axel-vogt/computing-the-complex-gamma-function-using-spouges-formula it might be useful to fragment the formula to smaller pieces but in a simple to moderately complex that still fits in one line, fragmenting the code confuses the eye. > And here's a way to do it that doesn't calculate anything twice, and > doesn't require any exceptions: > > def calculateforce(P1, P2, dist): > ? ? return (P1.mass - P2.mass)/dist > > And then for all pairs of particles: > > dist = distance(P1, P2) > if dist <= P1.radius + P2.radius: > ? ? clump(P1, P2) > ? ? break > F = calculateforce(P1, P2, dist) That... is the worst solution that could ever be suggested. The Particle objects already contain their own position, supplying dist overrides their real distance of the particles and also it may make bug holes by supplying bogus distance: def calculateforce(P1, P2, dist): return (P1.mass - P2.mass) / dist calculateforce(P1, P2, 'bogus data') or simply by passing dist that isn't equal (P1.X - P2.X) ** 2 + (P1.Y - P2.Y) ** 2. If you want to do it that way, it'd be much better if you go fully functional: def calculateforce(P1_mass, P2_mass, dist): return (P1_mass * P2_mass) / dist ** 2 but it would be a pain in the neck to manually dismantle the P1.M, P2.M, dist every time you call the calculateforce. btw, on an unrelated note, the original formula I supplied for gravity calculation is incorrect, it should be (P1.M * P2.M) / dist ** 2 instead of (P1.M - P2.M) / dist, but that's just physics not python. > > A much better solution would be to use SoftException > > ? ? def distance(P1, P2): > > ? ? ? ? D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > ? ? ? ? if D <= P1.radius + P2.radius: > > ? ? ? ? ? ? raise Collision > > ? ? ? ? return D > > But look at that line, "raise Collision". You could replace that with a > callback function, and have the same result: > > ? ? DO_NOTHING = lambda : None > > ? ? def distance(P1, P2, callback=DO_NOTHING): > ? ? ? ? D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > ? ? ? ? if D <= P1.radius + P2.radius: > ? ? ? ? ? ? callback() > ? ? ? ? return D > > That gives you virtually everything you want. If you want to ignore the > signal, you simply call distance(P1, P2). If you want to do something on > the signal, you set the callback. Guess where it goes after the callback finishes? It goes to "return D". And if the calling code hasn't been notified that P1 and P2 has already been clumped by the callback, it'll refer to an inexistent object. Soft Exception don't do that, it terminates the distance calculation and goes to the handler and won't go back to finish distance calculation unless explicitly told to (by using resume). And another weakness, it'd be a pain in the neck to handle more than two or three separate callbacks. You can define as many Soft Exception as you want without cluttering the function's "interface" (please find a better diction for "interface") > But frankly, the function distance() is NOT the place for that. Why > should the distance() function decide what's a special result and what > isn't? With your plan, you end up with functions like this: (snip) Because when a calculation of distance is lower than the sum of their radius, it means the two objects shared the same space (!this is impossible but not problematic for calculations if ignored!), that would be an event of interest to codes that handles the movement, clumping, etc but codes that just wants to print the distance to screen wouldn't want to care about it. > Every module and function that calls distance() will start demanding that > it raises the SoftExceptions that *it* wants, and before you know it, > your distance() function has a hundred SoftExceptions covering all sorts > of things that most people don't care about. > > No. This is a terrible idea. If the caller wants to treat a particular > result as special, the caller should be responsible for detecting that, > not the callee. No the callee isn't responsible for detecting the exceptional result, the caller is responsible for handling the exceptional result, while the callee is responsible to notify the caller. In some cases it might be impossible for the caller code to determine the exceptional cases or probably the cost of doing so is nearly equal to the cost of doing the whole calculations (but completing the calculation would result in garbage out). (snip) Steven says: > Just out of curiosity, are there any existing languages that do something > like this, or did you invent it yourself? On Mar 9, 8:21 pm, "Diez B. Roggisch" wrote: (snip) > Is this soft-exception implemented anywhere, so that one can see what > experiences and best practices have evolved around using it? Actually I "invent" it myself (or probably I'm just ignorant enough not to know any), that's why I expect there'll be a lot of weaknesses I haven't foreseen (two heads are better than one, and a bunch of heads are better than two). And it is also the reason why I'm asking here for others' opinions, to bake the ideas, and possibly getting it implemented when it's baked enough or to have other's opinion on why it's bad and why it shouldn't exist. If there is a reason why I chose here particularly, it'll be because I think Python (AFAICS) have a lot of interesting features: list comprehension, generator functions, for-loop semantic, just to name a few of them (well, maybe it's not *that* unique to you, but coming from a VB background[1], such features are extremely unique to me) and I love them and use them heavily. Another reason might be that Python is a dynamic language that have adopted preference for try block compared to if block. And I think the idea fits well enough with Python's ideologies. Still another reason is because Python is not controlled by a Impotent Company For Life but only by a Benevolent Dictator For Life. Yet another reason is simply because Python is currently my active language. [1] Although since I picked Python, I've yet to touch VB again, I'm sure I'll still be Thinking In Python if I go back to do some VB. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 03:38:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 08:38:56 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> Message-ID: <13t4k50d7pg0d63@corp.supernews.com> On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote: >> x = get_stuff(store) # Get the stuff what was brought at the store. > > Perfect example of an unnecessary comment. The variable and function > names are commentary enough. "x" is a terrible name. What does it mean? Nothing. There's only three places x is an appropriate name: (1) A meta-syntactic variable like foo, bar, spam, ham, parrot. (2) Library functions, where x stands for a generic argument, usually a number, e.g. def sin(x). (3) Throw-away code you don't need to maintain. The function name also doesn't explain anything. How was the stuff got? Was it paid for, or stolen, or picked up on consignment, or what? Compare the above line with: x = get_stuff(store) # Steal stuff from the store. or x = get_stuff(store) # Pickup the stuff from the store for disposal. # The amount paid by the store is stored in global variable "pay_received" # and the name of the employee authorizing the pickup is stored in the # global "authorized_by". But even if you were right that the comment was unnecessary, you have missed my point that even single sentences can be grammatically bogus and the writer could learn a lot from Strunk and White or equivalent. (Often the writer will learn bad habits, but at least they'll be grammatically correct bad habits.) -- Steven From dickinsm at gmail.com Tue Mar 11 10:13:23 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 07:13:23 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> Message-ID: On Mar 10, 7:32?pm, Nathan Pinno wrote: > Thanks on the factoring bit, but I did mean factorial, not factoring. > How do I code that correctly, so that I can figure the following > equation out: cos(Pi * (z-1)! / z). Is z an integer in this expression? (Note: it's not an equation--- there's no equality sign.) This looks suspiciously like a formula that's supposed to be valid for real and possibly even complex z, in which case what you're after is the gamma function. (gamma(z) = (z-1)!). The real version of this should certainly be present in numpy/scipy, and possibly the complex version too. If z really is supposed to be an integer then you should be aware that evaluating the expression directly is going to give almost no accuracy, for z greater than 30 or so: the absolute error in the argument to cosine will likely be much larger than 2*pi, so that the result of the cos() evaluation is meaningless. You might be better off computing w = (factorial(z-1) % (2*z)) as an integer; then cos(pi*(z-1)!/z) can be computed as cos(pi * w/z). Also, there are algebraic simplifications possible. If z is an integer greater than 4, and not a prime number, then the value of your expression is always going to be 1. If z is a prime number then Wilson's theorem is going to come in handy. (Google "Wilson's theorem prime"). Where does the expression come from? Is z a real or an integer? Is this a genuine real-world formula, or something that appeared in an elementary number theory textbook? Mark From bcl at brianlane.com Sat Mar 22 14:53:13 2008 From: bcl at brianlane.com (Brian Lane) Date: Sat, 22 Mar 2008 11:53:13 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <47E55599.9000305@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Jeff Schwab wrote: > jmDesktop wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. > > Linux and Python are a nearly ideal combination for this. Be aware that > at some point, you will likely have to dig into C, the primary language > used to implement both Linux and Python. At that level I don't see why they would need to hit 'C' at all. Maybe some of the APIs, but not syntax at all. I would consider Python an ideal language for HS students to learn. The teacher who hosts our KPLUG meetings has had good luck using Python in her classes. Brian - -- - ---[Office 67.9F]--[Outside 49.1F]--[Server 104.7F]--[Coaster 67.1F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH5VWZIftj/pcSws0RAoouAJ45UaRYDxwjwNLC8KblaFfyEKz3kACfeeWV XREAe/+tjyYuTVZOrNtaObE= =9h+S -----END PGP SIGNATURE----- From davidbak at gmail.com Fri Mar 7 17:39:57 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 14:39:57 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> On Mar 7, 1:19?pm, "Chris Mellon" wrote: > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > ?However I can't do this, because, of course, the name Tree isn't > > ?available at the time that the classes _MT and _Node are defined, so > > ?_MT and _Node can't inherit from Tree. > > Not only is the name not defined, the class doesn't even exist yet. Yes, but, well - it certainly isn't usable yet, but some object (that will be the class when it is finished) is being built (its __dict__ is being populated, etc.) - so there's an object pointer available inside the interpreter that could be put somewhere. But this is pedantic - you're right, the class really isn't available until after the class statement. > > ?What is the Pythonic thing I should be doing instead? > > Don't nest them. The single underscore is all you need to keep any > from using them (don't forget that even if your method worked, they'd > be perfectly visible as attributes of the Tree class, or as the types > of returned values). Worrying too much about visibility is a waste of > time in Python. Yes, I knew it wouldn't stop the determined coder from finding and using them. However, I did actually have a reason for wanted them nested: I wanted to put more than one similar data structure in the same source file - and several of them would have "Empty" nodes that would behave differently. If I used nested classes all those classes could be named Empty. If flattened to module level then I'd have to invent different names for each one, like, AVL_Empty, RedBlack_Empty, and it wouldn't seem as "nice" (for some definition of "nice" that I have in my head). > > ?(Easy answer: ?Put this code in a module, exposing only a factory > > ?function. ?I could do that, but wanted to know if I could encapsulate > > ?it as described so I could actually put several similar data > > ?structures into one module.) > > There's no reason to use a factory function. If you do put them in a > module, you can use __all__ to document your exports. As with all > visibility issues in Python, this is advisory only - the only code it > affects is the symbols that are exported by "from module import *". OK. Thanks! -- David From jeff at schwabcenter.com Fri Mar 14 12:45:35 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 14 Mar 2008 09:45:35 -0700 Subject: Need Script For read multiple files(.txt) from a folder In-Reply-To: References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: Chris wrote: > On Mar 14, 8:36 am, Dennis Lee Bieber wrote: >> On Thu, 13 Mar 2008 21:28:18 -0700 (PDT), jai_python >> declaimed the following in comp.lang.python: >> >>> hi frenz I Need a Python Script For read multiple files(.txt) from a >>> folder and write it in a single text file.... >> If you are on windows, just open a command prompt and use the >> standard copy command... >> >> C:\Documents and Settings\Dennis Lee Bieber>copy /? ... > If you want to go that route you could also do: type *.txt > > output_file.txt On Unix, cygwin, etc: cat dir/*.txt > output.txt Or if you need "deep" copy: cat $(find dir -name '*.txt') > output.txt You could write a portable solution in Python (as in Martin Laloux's post), but most modern command-line environments have similar (but not identical) support for globbing and redirecting files. If you're getting the glob pattern from a user, they may expect subtly platform-dependent behaviors, in which case portability might not as important as native feel. From carsten.haese at gmail.com Sat Mar 29 21:45:37 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 29 Mar 2008 18:45:37 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> Message-ID: On Mar 29, 9:10 pm, Tim Roberts wrote: > aiwarrior wrote: > > def get_value( self, column ): > > self.cursor.execute( "SELECT %s FROM database" % column ) > > for n in self.cursor: > > print n > > I suspect you wanted "self.cursor.fetchall()" there, but since you don't > call it, it doesn't matter yet. sqlite3's cursor objects support the iteration protocol, so the for- loop does work without calling fetchall(). -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Wed Mar 26 20:49:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 21:49:18 -0300 Subject: subtract dates with time module References: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 20:47:45 -0300, barronmo escribi?: > I'm trying to get the difference in dates using the time module rather > than datetime because I need to use strptime() to convert a date and > then find out how many weeks and days until that date. I'm a beginner > so any help would be appreciated. Here is the code: > > def OBweeks(ptID): > qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % > (ptID) > results = EMR_utilities.getAllData(qry) > for items in results: > r = re.search('\d\d\d\d-\d\d-\d\d', items) > if r: > d = time.strptime(r.group(), "%Y-%m-%d') - > time.localtime() > weeks, days = divmod(d.days, 7) > return '%s %s/7 weeks' % (weeks, days) > > This isn't working. I'm getting "unsupported operand type for -: > 'time.struct_time' and 'time.struct_time" error. I don't see why you don't want to use datetime; it's the easiest way to compute the time difference. To obtain the date object dt from the database, you might use the following, based on your posted code: import datetime match = re.search('(\d\d\d\d)-(\d\d)-(\d\d)', items) if match: y, m, d = (int(x) for x in match.groups()) dt = datetime.date(y, m, d) Then, weeks and days are easily computed (similar to your own code): now = datetime.date.today() # evaluate once outside the loop delta = now - dt weeks, days = divmod(delta.days, 7) -- Gabriel Genellina From Robert.Bossy at jouy.inra.fr Wed Mar 12 04:49:26 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 12 Mar 2008 09:49:26 +0100 Subject: merging intervals repeatedly In-Reply-To: References: Message-ID: <47D79916.2050002@jouy.inra.fr> Magdoll wrote: > Hi, > > I have to read through a file that will give me a bunch of intervals. > My ultimate goal is to produce a final set of intervals such that not > two intervals overlap by more than N, where N is a predetermined > length. > > For example, I could read through this input: > (1,10), (3,15), (20,30),(29,40),(51,65),(62,100),(50,66) > > btw, the input is not guaranteed to be in any sorted order. > > say N = 5, so the final set should be > (1,15), (20, 30), (29, 40), (50, 100) > Hi, The problem, as stated here, may have several solutions. For instance the following set of intervals also satisfies the constraint: (1,15), (20,40), (50,100) One question you should ask yourself is: do you want all solutions? or just one? If you want just one, there's another question: which one? the one with the most intervals? any one? If you want all of them, then I suggest using prolog rather than python (I hope I won't be flamed for advocating another language here). > Is there already some existing code in Python that I can easily take > advantage of to produce this? Right now I've written my own simple > solution, which is just to maintain a list of the intervals. I can use > the Interval module, but it doesn't really affect much. I read one > interval from the input file at a time, and use bisect to insert it in > order. The problem comes with merging, which sometimes can be > cascading. > > ex: > read (51,65) ==> put (51,65) in list > read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) > read (50,66) ==> merge with (51,65) to become (50,66) ==> now can > merge with (62,100) The way this algorithm is presented suggests an additional constraint: you cannot merge two intervals if their overlap <= N. In that case, there is a single solution indeed... Nitpick: you cannot merge (50,66) and (62,100) since their overlap is still <= 5. If you have a reasonable number of intervals, you're algorithm seems fine. But it is O(n**2), so in the case you read a lot of intervals and you observe unsatisfying performances, you will have to store the intervals in a cleverer data structure, see one of these: http://en.wikipedia.org/wiki/Interval_tree http://en.wikipedia.org/wiki/Segment_tree Cheers, RB From andreas.axelsson at gmail.com Sun Mar 30 11:04:10 2008 From: andreas.axelsson at gmail.com (axl) Date: Sun, 30 Mar 2008 08:04:10 -0700 (PDT) Subject: Build complete, now I just need to "install" it... Message-ID: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Hi, I'm going to be adding some features for a python-project with external modules written in C. However, if I build modules with my MSVS 2008 compiler (from the Windows SDK), they won't load in Python 2.5.2, which is built with MSVS 2003. Since I don't have access to MSVS 2003 I need to rebuild Python using MSVS 2008 in order for the binaries to go along. For starters, I cloned the PCbuild8 folder and made whatever changes needed to be able to build the core and executable. I then pulled down all the various external dependencies and made the same adjustments to those. After quite a while I've managed to build everything apart from the PGO config, since it requires a DLL which isn't included in the SDK. Not to worry, I can live with a less than 100% optimized version for now. But, my problem is that the install scripts, i.e. "python setup.py install" wants to go through the build steps again, but since those don't work on Windows, or at least not with my setup, I can't put together a complete package. The web pages have gotten me this far, but there doesn't seem to be anything on how to actually pull together the various bits and bobs into a complete package that I can use in place of my current Python 2.5.2 installation. Apparently someone has done it, since there is an installer to download, but those parts don't seem to be available anywhere. And it's unclear if the Windows installer contains exactly what's in the source package, or if I have to build a bunch of other modules as well in order to be completely replacing my old installation. Actually, I don't need an installer, I just want to know which parts of my 2.5.2 folder that need to go where. Grateful for any help, /axl From mail at timgolden.me.uk Tue Mar 25 07:13:15 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Mar 2008 11:13:15 +0000 Subject: My python interpreter became mad ! In-Reply-To: <47E8DC95.4010009@cines.fr> References: <47E8DC95.4010009@cines.fr> Message-ID: <47E8DE4B.7040307@timgolden.me.uk> Benjamin Watine wrote: > Yes, my python interpreter seems to became mad ; or may be it's me ! :) > > I'm trying to use re module to match text with regular expression. In a > first time, all works right. But since yesterday, I have a very strange > behaviour : > > $ python2.4 > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > X-Spam-Flag: YES > X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org > X-Spam-Level: ********************** > X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, > MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, > > RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, > > URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, > URIBL_WS_SURBL autolearn=failed version=3.1.7-deb > > Traceback (most recent call last): > File "", line 1, in ? > File "/etc/postfix/re.py", line 19, in ? > m = re.match('(Spam)', mail) > AttributeError: 'module' object has no attribute 'match' > >>> Extremely likely that, in the course of testing some re technique, you've created a module in this directory called "re.py". When you import re, you're actually importing your own module. TJG From michael.wieher at gmail.com Mon Mar 10 12:06:07 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 10 Mar 2008 11:06:07 -0500 Subject: BitVector read-from-file Question Message-ID: I'm trying to read in data from large binary files using BitVector (thanks btw, for whoever mentioned it on the list, its nice) I'll be reading the data in as requested by the user, in (relatively) small chunks as needed. Problem is I can't read the whole file in at once (its ridiculously large) and the object created by BitVector(filename="path") doesn't include a "seek" function (to reset the filepointer) Any suggestions on how to this without closing/reopening/reading(offset)/read(data) ? (thats a lot of overhead) -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Mon Mar 17 23:58:24 2008 From: http (Paul Rubin) Date: 17 Mar 2008 20:58:24 -0700 Subject: ord function problem from newbie References: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> Message-ID: <7xeja8el9b.fsf@ruckus.brouhaha.com> David.J.Anderson66 at gmail.com writes: > for ch in small: > v = ord(ch)-96 > print v total = 0 for ch in small: # the += below updates the value of total by adding (ord(ch) - 96) total += (ord(ch) - 96) print "ch:", ch, "total so far:", total From gagsl-py2 at yahoo.com.ar Thu Mar 27 05:20:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 06:20:53 -0300 Subject: Partial Function Application and implicit self problem References: <65144bF2dp2abU1@mid.uni-berlin.de> <47EB5D7E.7080109@mydeskfriend.com> Message-ID: En Thu, 27 Mar 2008 05:40:30 -0300, Gabriel Rossetti escribi?: >>> if(atomic): >>> # Lock the service dict and register the service, then unlock it >>> self.__mutex.lock(reg, service) >>> self.__mutex.unlock() I see that you've already solved your original problem. But looking at those names, I wonder if you're using the mutex module; note that such "mutex" is absolutely useless in a multithreaded program, it doesn't guarantee mutual exclusion, the "atomic" testandset operation isn't atomic at all, by example. For a "real" mutex, use a threading.Lock object. -- Gabriel Genellina From castironpi at gmail.com Fri Mar 21 07:59:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 04:59:19 -0700 (PDT) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 9, 6:44?pm, castiro... at gmail.com wrote: > On Mar 2, 1:18?pm, castiro... at gmail.com wrote: > > > On Mar 2, 12:01?pm, John DeRosa wrote: > > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > > >Hi, > > > > >Have you ever seen Beautiful Python code? > > > >Zope? Django? Python standard lib? or else? > > > > >Please tell me what code you think it's stunning. > > > > Just about any Python code I look at. > > > Decorators, with, and namedtuple. > > Oh yeah, and variable arguments and keyword > dictionaries. If you're C++, garbage collection. How's the cycle detector? The pages and pages get pretty specific. From steve at holdenweb.com Sun Mar 30 21:18:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 21:18:51 -0400 Subject: Odd behaviour with list comprehension In-Reply-To: <871w6vkq3z.fsf@micah.cowan.name> References: <4fbfbb8f0802291901s5ed7e0b4ua3e77ad46aa53bb7@mail.gmail.com> <871w6vkq3z.fsf@micah.cowan.name> Message-ID: Micah Cowan wrote: > "Jerry Hill" writes: > >> On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu wrote: >>> Is there a way for me keep the iterating variable in list >>> comprehension local to the list comprehension? >> Kind of. You can use a generator expression instead of a list >> comprehension, and those don't leak their internal variables into the >> enclosing scope: > > Whoa, that's cool. I didn't even think to try that, just assuming it > would do the same. > > Though now that I think about it, I don't see how it possibly could, > since it just evaluates to an object that you could pass around, and > return, using it the same way elsewhere. > Well, the fact that the bound variable in the list comprehension does indeed remain outside the construct is simply the result of an over-zealous wish to emulate for loop semantics. The original reasoning, IIRC, as that since a for loop left its bound variable at the last used value, so should a list comprehension. This was quickly recognized as a mistake, but unfortunately not quickly enough. As it was felt that some people might already have relied on that behavior, it was retained in the interests of preserving backwards compatibility. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dickinsm at gmail.com Fri Mar 7 19:12:34 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 7 Mar 2008 16:12:34 -0800 (PST) Subject: float / rounding question References: Message-ID: On Mar 7, 5:12?pm, Piet van Oostrum wrote: > Python just uses the C library for printing, I presume, and the conversion > routines in the C library are rather simplistic. It is, however, possible > to do better, so that 53.6 -- although internally represented as something > that could be described as 53.600000000000001 -- will actually be printed > as 53.6. There are issues with doing this portably and reliably. See http://bugs.python.org/issue1580 for a recent discussion. Mark From asmodai at in-nomine.org Mon Mar 31 06:39:16 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 31 Mar 2008 12:39:16 +0200 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <20080331103916.GF80617@nexus.in-nomine.org> -On [20080331 12:29], Pradeep Rai (pradiprai at gmail.com) wrote: >I have upgraded python v2.5.2 from python v2.4.3. The upgradation results into >following error: >"Python C API version mismatch for module dbi: This Python has API version >1013, module dbi has version 1012." Did you copy everything from site-packages of the old one to the new one? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If you're afraid of dyin', then you're holding on. You see devils tearing your life away. But if you have made your peace, then the devils are really angels, freeing you from the earth... From duncan.booth at invalid.invalid Wed Mar 19 08:34:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 12:34:34 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > This whole approach > assumes that Windows does the sensible thing of returning a unique error > code when you try to open a file for reading that is already open for > writing. > So how would you use a file to share data then? By default Python on Windows allows you to open a file for reading unless you specify a sharing mode which prevents it: the easiest way is probably to call win32file.CreateFile with appropriate parameters. In one window: >>> f = open('SHARE.txt', 'w') >>> f.write('hello') >>> f.flush() >>> and then while that other window is open: >>> handle = win32file.CreateFile("SHARE.txt", ... win32file.GENERIC_WRITE, ... 0, # i.e. "not shared" is the default ... None, ... win32file.OPEN_ALWAYS, ... win32file.FILE_ATTRIBUTE_NORMAL, ... None) Traceback (most recent call last): File "", line 7, in pywintypes.error: (32, 'CreateFile', 'The process cannot access the file because it is being used by another process.') >>> f = open("SHARE.txt", "r") >>> f.read() 'hello' The CreateFile call was copied from http://mail.python.org/pipermail/python-list/2002-January/122462.html From darcy at druid.net Mon Mar 31 11:51:46 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 31 Mar 2008 11:51:46 -0400 Subject: Creating Class Objects in Loop In-Reply-To: <47f0673e$0$36321$742ec2ed@news.sonic.net> References: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> <47f0673e$0$36321$742ec2ed@news.sonic.net> Message-ID: <20080331115146.54ec39ee.darcy@druid.net> On Sun, 30 Mar 2008 21:34:00 -0700 John Nagle wrote: > What's actually happening to you is that you've run into one of the > dumber features of Python - default values for parameters which are > mutable, like lists, result in rather unexpected behavior. The > problem is that > > def __init__(self, pcap = None, sids = []): I have never liked using that form for different reasons so I never tripped over that. Now I have another reason to avoid it. It's not a huge deal to do this. def __init__(self, pcap = None, sids = None): if sids is None: sids = [] -- 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 ptmcg at austin.rr.com Sun Mar 2 20:53:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 Mar 2008 17:53:54 -0800 (PST) Subject: Altering imported modules References: <200803011856.27611.troworld@gmail.com> Message-ID: <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> On Mar 2, 3:48?pm, Tro wrote: > On Sunday 02 March 2008, Terry Reedy wrote: > > > > > > > "Tro" wrote in message > >news:200803011856.27611.troworld at gmail.com... > > > | Hi, list. > > | > > | I've got a simple asyncore-based server. However, I've modified the > > > asyncore > > > | module to allow me to watch functions as well as sockets. The modified > > | asyncore module is in a specific location in my project and is imported > > > as > > > | usual from my classes. > > | > > | Now I'd like to use the tlslite library, which includes an asyncore mixin > > | class. However, tlslite imports "asyncore", which doesn't include my own > > | modifications. > > | > > | I'd like to know if it's possible to make tlslite load *my* asyncore > > > module > > > | without changing any of the tlslite code. > > > If your module is also 'asyncore' and comes earlier in the search path, I > > would expect the import to get yours. > > It's not. It has a package prefix like my.package.asyncore. I think I can > either move my version of asyncore up a couple of levels or add the > my.package directory to sys.path. > > My version of asyncore imports several functions from the built-in asyncore. > Now that my version of it is imported as asyncore, how would it import the > built-in version from python2.5/site-packages? > > Thanks, > Tro- Hide quoted text - > > - Show quoted text - What happens if you do "import my.package.asyncore as asyncore"? If that doesn't work (trying the simplest hack first), I know that there are various hooks in the import mechanism that should help. -- Paul From martin at v.loewis.de Mon Mar 3 01:48:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2008 07:48:28 +0100 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: <47CB9F3C.9030202@v.loewis.de> >> But it would be really nice if the configure fix for 2.5 was >> backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped >> system builds for 2.4 going direct from 2.3 -> 2.5. > > > Yes, it would be very nice if this worked out of the box on Mac OS X > 10.5.2. It's definitely a surprise for those of us who built our 2.4.4 > on Mac OS X 10.4.x. I can put a notice in the release notes, but I definitely won't change it to work out of the box. If 2.4.4 compiled out of the box on this box, it would have been a regression and would have to be fixed. IIUC, 2.4.4 won't compile on 10.5, either, and Python 2.4.5 will have no code to port it to new platforms. Regards, Martin From devnew at gmail.com Mon Mar 17 01:04:16 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Sun, 16 Mar 2008 22:04:16 -0700 (PDT) Subject: finding euclidean distance,better code? Message-ID: hello while trying to write a function that processes some numpy arrays and calculate euclidean distance ,i ended up with this code (though i used numpy ,i believe my problem has more to do with python coding style..so am posting it here) ... # i am using these numpy.ndarrays to do the calculation facespace # of shape(totalimgs,imgpixels) weights # of shape(totalimgs,selectedfacespaces) input_wk # of shape(selectedfacespaces,) distance # of shape(selectedfacespaces,) initally all 0.0 's mindistance #of shape(selectedfacespaces,) initally all 0.0 's ... ... #here is the calculations part for image in range(numimgs): distance = abs(input_wk - weights[image, :]) if image==0: #copy from distance to mindistance mindistance=distance.copy() if sum(mindistance) > sum(distance): imgindex=image mindistance=distance.copy() if max(mindistance) > 0.0: #normalise mindistance mindistance=mindistance/(max(mindistance)+1) dist=sum(mindistance) this gets me the euclidean distance value.I want to know if the way i coded it can be improved,made more compact....if someone can give suggestions it will be a great help . thanks D From kuaile9834 at 126.com Tue Mar 25 03:42:56 2008 From: kuaile9834 at 126.com (kuaile9834 at 126.com) Date: Tue, 25 Mar 2008 00:42:56 -0700 (PDT) Subject: cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) Message-ID: <527d4a7f-086e-4008-915b-3755e751fc5f@e10g2000prf.googlegroups.com> cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com )cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) From haraldarminmassa at gmail.com Mon Mar 17 14:28:34 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Mon, 17 Mar 2008 11:28:34 -0700 (PDT) Subject: how long do the different python-vm bytecodes take? Message-ID: <0555ed9f-c5f1-4d0b-afbd-439c863e9439@s13g2000prd.googlegroups.com> I looked at the virtual machine bytecode of python programs: def f(whatever): text="Hallo"+whatever return text import dis dis.dis(f) 2 0 LOAD_CONST 1 ('Hallo') 3 LOAD_FAST 0 (whatever) 6 BINARY_ADD 7 STORE_FAST 1 (text) 3 10 LOAD_FAST 1 (text) 13 RETURN_VALUE and now I am curious: how long does one LOAD_FAST take? I am thinking of something like back in the assembler-world, where there existed tables like: LDA -> 2 cycles BNE -> 2 cycles, 3 on branch of course, the "real time" is dependand on many factors, esp. the speed of the processor. But ... is there a relative scale somewhere? Somehting like LOAD_CONST 1 arbitraryUnit LOAD_FAST 1.9 arbitraryUnits RETURN_VALUE 8.0 arbitraryUnits ??? my Google queries did not reveal anything usefull so far. Any hints? From Wayne.Oosthuizen at gmail.com Fri Mar 28 11:01:01 2008 From: Wayne.Oosthuizen at gmail.com (Constantly Distracted) Date: Fri, 28 Mar 2008 08:01:01 -0700 (PDT) Subject: Setting the value of one cell in QTableWidget fills everything. Message-ID: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> I've just started PyQt programming and I've run into this little problem. When I set the text of one cell in my table, all the other cells fill with that value. All I wanted to do was run a loop, printing in each cell the row and column number. Here's the code. ------------------------------ from PyQt4 import QtGui,QtCore import sys class mywindow(QtGui.QWidget): def __init__(self,parent=None): QtGui.QWidget.__init__(self,parent) self.resize(700,700) self.mytable=QtGui.QTableWidget(7,6,self) self.mytable.resize(700,700) def filltable(self): items=QtGui.QTableWidgetItem() for column in range(self.mytable.columnCount()): for row in range(self.mytable.rowCount()): items.setText("row: " + str(row) + " column: " + str(column)) self.mytable.setItem(row,column,items) app=QtGui.QApplication(sys.argv) mainwin=mywindow() mainwin.filltable() qb.show() app.exec_() From bogus@does.not.exist.com Thu Mar 13 23:37:00 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 22:37:00 -0500 Subject: sorting question References: Message-ID: Seems 'KEYBOARDS' works nicely -- -- Andrew "jcnbp8k" wrote in message news:mailman.1941.1205461453.9267.python-list at python.org... > > Hi Patty, > > That's easy solved, the word is keyboards. > > I just did a google search for 'anagram solver' and got lucky with Andy's > free online anagram solver at http://www.ssynth.co.uk/~gay/anagram.html > :) > > I know it's not a python script, though are you actually working on a > python > program to de-scramble words yourself or did you just want the answer? > > Hope that helps. > > Cheers, > > Joe > http://www.neosource.com.au www.neosource.com.au - Practical Software > Solutions > > > Patty Sutcliffe wrote: >> >> The website you list regarding 9-letter scrambled words doesn't exist any >> longer. Is there another way that I can access it to see your program >> you >> designed? I have a nine letter work I need to unscramble. I will send >> it >> just in case you can figure it out for me and let me know. >> >> KAEOSYBRD >> >> I'm not very good at that sort of thing, but would love to know the >> answer >> to this one. >> >> Thank you, >> Patty >> patty206 at charter.net >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- > View this message in context: > http://www.nabble.com/sorting-question-tp16041301p16043041.html > Sent from the Python - python-list mailing list archive at Nabble.com. > From george.sakkis at gmail.com Sun Mar 23 11:39:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 08:39:53 -0700 (PDT) Subject: Duplicating list of lists [newbie] References: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Message-ID: On Mar 23, 11:34 am, yat... at gmail.com wrote: > Hi there. > I felt like I already know my toys around but it looks that I'm still > newbie on some points. > > So here goes problem: > > Lets say that we have list to copy: > > a = [1,2,3] > b = a[:] > a[0] = 5 > > a > > > [5,2,3] > b > >[1,2,3] > > So far so good > > But... let's say that "a" also contains lists: > > a = [1,2,[5,6,7]] > b = a[:] > > a[0] = 55 > a > > > [55,2,[5,6,7]] > b > > [1,2,[5,6,7]] > > Looks OK but... > > a[2][0] = 99 > a > > > [55,2,[99,6,7]] > b > > [1,2,[99,6,7]] > > So - it looks that in list "b" there copy of all objects from list "a" > including not copy of list [5,6,7] but reference to it. Right; that's what it's called a "shallow copy". > Is there simple way to copy a into b (like a[:]) with all copies of > all objects going as deep as possible? Yes, there is: from copy import deepcopy b = deepcopy(a) HTH, George From musiccomposition at gmail.com Sun Mar 16 21:30:54 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 16 Mar 2008 18:30:54 -0700 (PDT) Subject: Using threads in python is safe ? References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Message-ID: On Mar 16, 3:40 pm, "Gabriel Genellina" wrote: > En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade > escribi?: > > > I want to use therads in my application. Going through the docs , I read > > about GIL. > > Now I am confused whether using threads in python is safe or not. > > > One thing I know that if I am accessing global variables in two or more > > threads I need to synchronize them > > using locking or such mechanism so that only one thread access them at a > > time. > > Yes, altough some operations are known to be atomic so you don't need a > lock in that cases. I think there is a list in the wiki somewhere http://wiki.python.org/moinor perhaps at the effbot's site http://www.effbot.org Even for atomic operations, you should lock, though. That is not consistent over different Python implementations and is not always going to be in same in CPython. > > > 1. In order to support multi-threaded Python programs, there's a global > > lock that must be held > > by the current thread before it can safely access Python objects. > > Does this lock need to be held by python application script expliciltly > > before accessing any python object or > > interpreter takes acre of it ? > > No, the interpreter takes care of it. The GIL is a concern for those > writing extensions using the Python API. > > > 2. Does multithreaded python script need to held lock before calling any > > blocking I/O call? > > Or one should not worry about GIL while using python threads if job to be > > processed by thread does not call > > any global variables and thread unsafe Python/C extension ? > > Python code should not worry about the GIL. The problem would be, a > callback written in Python for a not-thread-aware extension that had > released the GIL. > > -- > Gabriel Genellina From tjreedy at udel.edu Wed Mar 19 17:51:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2008 17:51:41 -0400 Subject: is hash map data structure available in Python? References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> <87a293ab-c4f1-4dfc-97b7-efb10bb42e6b@e6g2000prf.googlegroups.com> Message-ID: "sturlamolden" wrote in message news:87a293ab-c4f1-4dfc-97b7-efb10bb42e6b at e6g2000prf.googlegroups.com... | On 19 Mar, 09:40, grbgooglefan wrote: | | > How do I create hash map in Python? | | Python dictionaries are the fastest hash maps known to man. If you only have keys (the names) and no values attached to them, then use a set. From has.temp3 at virgin.net Thu Mar 20 08:08:10 2008 From: has.temp3 at virgin.net (has) Date: Thu, 20 Mar 2008 05:08:10 -0700 (PDT) Subject: Calling Mac programs from Python instead of from AppleScript References: <47E1733E.5060902@codebykevin.com> Message-ID: <18a24a70-73ab-453b-9e6d-6a820a560703@u10g2000prn.googlegroups.com> On 19 Mar, 20:10, Kevin Walzer wrote: > Take a look at appscript: > > http://appscript.sourceforge.net/ Also, once appscript is installed, don't forget to import it before use: from appscript import * app('Maya').execute('sphere') HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From mnordhoff at mattnordhoff.com Mon Mar 10 05:35:29 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 09:35:29 +0000 Subject: is operator In-Reply-To: <004801c881f2$a04081f0$0b020b0a@nb1011> References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <47D500E1.1050107@mattnordhoff.com> Metal Zong wrote: > The operator is and is not test for object identity: x is y is true if > and only if x and y are the same objects. > >>>> x = 1 >>>> y = 1 >>>> x is y > True > > Is this right? Why? Thanks. I believe Python automatically creates and caches int objects for 0-256, so whenever you use them, they refer to the same exact objects. Since ints are immutable, it doesn't matter. -- From Dodin.Roman at gmail.com Mon Mar 17 09:08:43 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 06:08:43 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Message-ID: <49cfccae-9992-4d3f-a8b1-86536adbca53@e6g2000prf.googlegroups.com> On 17 ???, 15:48, "Gabriel Genellina" wrote: > En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > > > i have a problem with this modules py2exe + pywinauto + sendkeys used > > together. > > > In my script i'm using this expression > > app.window_(title="SJphone").Edit.TypeKeys("Test is > > running",with_spaces=True) > > > TypeKeys is using SendKeys module i suppose. > > Does it work as a normal script, without using py2exe? > > > my setup.py looks like that: > > > from distutils.core import setup > > import py2exe > > > setup( > > options = {"py2exe": {"compressed": 1, > > "optimize": 0, > > "bundle_files": 1, > > "packages": ["encodings", "pywinauto", > > "pywinauto.controls", "pywinauto.tests"] } }, > > zipfile = None, > > console=["hosts.py"] > > ) > > Perhaps you have to include SendKeys explicitely. I think pywinauto > doesn't require SendKeys, but uses it if already installed. > > -- > Gabriel Genellina i tried this: "packages": ["encodings", "pywinauto", "SendKeys", "pywinauto.controls", "pywinauto.tests"] But there was an error too( From inq1ltd at inqvista.com Fri Mar 14 10:48:39 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 14 Mar 2008 10:48:39 -0400 Subject: escape string to store in a database? In-Reply-To: <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> Message-ID: <200803141048.39381.inq1ltd@inqvista.com> > > -- > > Carsten > > Haesehttp://informixdb.sourceforge.net > > Thanks for the reply, Carsten, how would > this work with UPDATE command? I get this > error: > > cmd = "UPDATE items SET content = > ? WHERE id=%d" % id try this; ("update items set contents = (?) where id =(?)", [ x, y] ) put your data in a list or ("update items set contents = (?) where id =%d ", [ x] ) below statement "uses 1" refers to the one (?) , 0 supplied, means no list or none in list. jim-on-linux http://www.inqvista.com > > self.cursor.execute(cmd, content) > pysqlite2.dbapi2.ProgrammingError: > Incorrect number of bindings supplied. The > c > rrent statement uses 1, and there are 0 > supplied. > > Sqlite site doesn't give any details on > using parameter bindings in UPDATE > command, I'm > going to look around some more.. -ak From hacker.stevenson at gmail.com Thu Mar 27 15:45:52 2008 From: hacker.stevenson at gmail.com (breal) Date: Thu, 27 Mar 2008 12:45:52 -0700 (PDT) Subject: Determine size of string in bytes Message-ID: Forgive me for this question which is most likely stupid... How do I determine the number of bytes a string takes up? I have a soap server that is returning a serialized string. It seems that when the string goes over 65978 characters it does not return to the soap client. Instead I get an error: error: (35, 'Resource temporarily unavailable') This makes me think the problem exists on the soap client side with some sort of max return length. If I knew how many bytes the 65978 character string was, then I could try to up this value. Thanks. From __peter__ at web.de Thu Mar 13 07:06:33 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Mar 2008 12:06:33 +0100 Subject: What's Going On? References: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > (Accompanied by Marvin Gaye) > >>>> def f(list=[0]): > ... list[0]+=1 > ... return list[0] > ... >>>> f() > 1 >>>> f() > 2 >>>> f() # 'list' is a name bound to a list (mutable) so this makes sense > 3 >>>> f([5]) > 6 >>>>f() # What's Going On? > 4 http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm You heard it through the grapevine ;) Peter From stanc at al.com.au Wed Mar 26 23:34:20 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 27 Mar 2008 14:34:20 +1100 Subject: copy file over LAN Message-ID: <47EB15BC.3060505@al.com.au> Hi, I have a file on another machine on the local network (my machine and local machines are on windows) and I want to copy it locally. Now the machine requires authentication and when I try to do a import shutil shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') and it gives me a IOError: [Errno 13] Permission denied: error, which I expect. How do I provide authentication to copy this file? Thanks for the help. Cheers Astan -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From coolman.guron at gmail.com Thu Mar 6 11:34:27 2008 From: coolman.guron at gmail.com (coolman.guron at gmail.com) Date: Thu, 6 Mar 2008 08:34:27 -0800 (PST) Subject: help on file storage for split multi part download Message-ID: HI everyone on this group! i am want to write a split part downloading software for use in some projects. (something like a download accelerator) what i think i need is ( my brain is totally exausted at this moment so pls ignore any typos i make) storage class which can write the file splits that are currently being downloaded to the disk. this is exactly what other download accelerators do, i guess. can this be done using the python file class?? i am pretty good at handling file uploads (at server end) this is the first time i have to think the other way round. any code samples would be greatly appreciated. thanks binary-j django web developer From Robert.Bossy at jouy.inra.fr Thu Mar 13 03:54:56 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 13 Mar 2008 08:54:56 +0100 Subject: Creating a file with $SIZE In-Reply-To: <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> Message-ID: <47D8DDD0.6040104@jouy.inra.fr> cokofreedom at gmail.com wrote: > On Mar 12, 2:44 pm, Robert Bossy wrote: > >> Matt Nordhoff wrote: >> >>> Robert Bossy wrote: >>> >>>> k.i.n.g. wrote: >>>> >>>>> I think I am not clear with my question, I am sorry. Here goes the >>>>> exact requirement. >>>>> >>>>> We use dd command in Linux to create a file with of required size. In >>>>> similar way, on windows I would like to use python to take the size of >>>>> the file( 50MB, 1GB ) as input from user and create a uncompressed >>>>> file of the size given by the user. >>>>> >>>>> ex: If user input is 50M, script should create 50Mb of blank or empty >>>>> file >>>>> >>>> def make_blank_file(path, size): >>>> f = open(path, 'w') >>>> f.seek(size - 1) >>>> f.write('\0') >>>> f.close() >>>> >>>> I'm not sure the f.seek() trick will work on all platforms, so you can: >>>> >>>> def make_blank_file(path, size): >>>> f = open(path, 'w') >>>> f.write('\0' * size) >>>> f.close() >>>> >>> I point out that a 1 GB string is probably not a good idea. >>> >>> def make_blank_file(path, size): >>> chunksize = 10485760 # 10 MB >>> chunk = '\0' * chunksize >>> left = size >>> fh = open(path, 'wb') >>> while left > chunksize: >>> fh.write(chunk) >>> left -= chunksize >>> if left > 0: >>> fh.write('\0' * left) >>> fh.close() >>> >> Indeed! Maybe the best choice for chunksize would be the file's buffer >> size... I won't search the doc how to get the file's buffer size because >> I'm too cool to use that function and prefer the seek() option since >> it's lighning fast regardless the size of the file and it takes near to >> zero memory. >> >> Cheers, >> RB >> > > But what platforms does it work on / not work on? > Posix. It's been ages since I touched Windows, so I don't know if XP and Vista are posix or not. Though, as Marco Mariani mentioned, this may create a fragmented file. It may or may not be an hindrance depending on what you want to do with it, but the circumstances in which this is a problem are quite rare. RB From tdelaney at avaya.com Tue Mar 25 18:49:57 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 26 Mar 2008 06:49:57 +0800 Subject: Prototype OO In-Reply-To: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> Message-ID: John Machin wrote: > On Mar 23, 12:32 am, "Diez B. Roggisch" wrote: >> John Machin schrieb: >> >>> On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: >> >>>> [1] Just one example:http://docs.mootools.net/Class/Class.js >> >>> Mootools being something a coworker might use? >> >> I don't understand the question. >> >> Diez > > It presupposes that the reader on first seeing "coworker" has mentally > decomposed it as "cow-ork-er". As an aside, having lived much of my early life on a hobby farm, I've often wondered to myself just what cow-orking involves ... ;) Tim Delaney From fn681 at ncf.ca Sat Mar 1 10:46:45 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sat, 01 Mar 2008 10:46:45 -0500 Subject: Beginner's assignment question In-Reply-To: References: Message-ID: Schizoid Man wrote: > As in variable assignment, not homework assignment! :) > > I understand the first line but not the second of the following code: > > a, b = 0, 1 > a, b = b, a + b > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > However what is the sequence of operation in the second statement? I;m > confused due to the inter-dependence of the variables. In the second line a now points to the value 1 and b points to 1 (the sum of zero and one) in a unitary operation (i.e. in turn, but effectively simultaneously). You might disassemble the code to see the sequence. Colin W. From steve at holdenweb.com Sun Mar 30 21:44:59 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 21:44:59 -0400 Subject: Please test Phatch on Windows (was Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL) In-Reply-To: References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: <47F0421B.90704@holdenweb.com> Stani: You'll be happy to hear that it appears (after a quick test) to work on Vista, though I blush to admit I actually have a Python running on that platform. The font selection is much better than in previous versions - although the names aren't quite the full font names it's pretty easy to tell which one will be used. regards Steve SPE - Stani's Python Editor wrote: > I have been working the last couple of days purely on bug fixing and > to port the code of Phatch fully to Windows as there were many issues. > This has improved: > - Phatch can now create droplets on Windows (win32 extensions > required) > - Installed fonts are retrieved from the Windows registry > - Image file dialogs are now working correctly > - Missing icons are added (including a phatch.ico) and are now > displayed in the windows titlebars > - Image Inspector was missing a panel > - Preview in Image Inspector now displays correctly > - (...) > > Besides that Phatch now features for all platforms: > - fonts can be defined with a nice dropdown autocomplete list > - drop down lists with convenient values in all actions > - the action masks now ships with some predefined masks (such as torn > edges) > - right click in the actions dialog box to see the source of an action > - View>Droplet nows shows the name of the action box rendered in the > logo > - Dutch translation is 100% complete > > As such no new features have been added, but the user experience feels > much more polished now. > > Please read *carefully* the installation instructions first: > http://photobatch.wikidot.com/install#toc6 > > People who have been using Phatch before should clear their font cache > (if it exists). Simply delete the file: > C:\Documents and Settings\Username\.phatch\fonts > > I did the Phatch port on a Windows 2000 machine, so I am curious to > hear how Phatch works on Windows XP and Vista. I will fix any bug (as > far as possible) which is reported quickly in the next couple of days. > > You can help translating Phatch here: > https://translations.launchpad.net/phatch/trunk/+pots/phatch > > Thanks in advance, > > Stani > > On 18 feb, 15:58, "SPE - Stani's Python Editor" > wrote: >> I'm pleased to announce the release ofPhatchwhich is a >> powerful batch processor and renamer.Phatchexposes a big part of the >> Python Imaging Library through an user friendly GUI. (It is using >> python-pyexiv2 to offer more extensive EXIF and IPTC support.)Phatch >> is not targeted at manipulating individual pictures (such as with >> Gimp), but repeating the same actions on hundreds or thousands of >> images. >> >> If you know PIL and have some nice recipes laying around, it is very >> easy to write plugins asPhatchgenerates the corresponding GUI >> automagically just like in Django. Any existings PIL scripts can be >> added very easily. Let me know if you want to contribute or have any >> questions. >> >> Homepage:http://photobatch.stani.be(free download link below) >> Tutorials:http://photobatch.wikidot.com/tutorials >> Translations:https://translations.launchpad.net/phatch/trunk/+pots/phatch >> License: GPLv3 >> Screenshot:http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg >> (the perspective and reflection is produced byPhatchitself) >> >> Phatchhas many features, like: >> - EXIF information inspector with thumbnail >> - limit jpeg file size when saving >> - tons of actions organized by tags (including perspective, round >> corners, shadow, reflection, ...) >> - console version (Phatchcan now run without a gui on servers) >> - batch rename and copy files based on exif metadata >> - data stamping (http://photobatch.wikidot.com) >> - online documentation wiki (http://photobatch.wikidot.com) >> >> Linux only features: >> - desktop or panel droplets on which images or folders can be dropped >> (will be ported to Windows & Mac) >> - Nautilus and desktop integration (with its own mime type and >> nautilus extension) >> - manpage with examples >> >> With python-pyexiv2 the following featues are added: >> - embedding the original EXIF and IPTC tags in the image >> >> All actions mostly have a separate pil function in their source code, >> so they could be read as a recipe book for PIL: >> * Auto Contrast - Maximize image contrast >> * Background - Put colour under transparent image >> * Border - Crop or add border to all sides >> * Brightness - Adjust brightness from black to white >> * Canvas - Crop the image or enlarge canvas without resizing the image >> * Colorize - Colorize grayscale image >> * Common - Copies the most common pixel value >> * Contrast - Adjust from grey to black & white >> * Convert Mode - Convert the color mode of an image (grayscale, RGB, >> RGBA or CMYK) >> * Copy - Copy image file >> * Effect - Blur, Sharpen, Emboss, Smooth, ... >> * Equalize - Equalize the image histogram >> * Fit - Downsize and crop image with fixed ratio >> * Grayscale - Fade all colours to gray >> * Invert - Invert the colors of the image (negative) >> * Maximum - Copies the maximum pixel value >> * Mask - Apply a transparency mask >> * Median - Copies the median pixel value >> * Minimum - Copies the minimum pixel value >> * Offset - Offset by distance and wrap around >> * Posterize - Reduce the number of bits of colour channel >> * Perspective - Shear 2d or 3d >> * Rank - Copies the rank'th pixel value >> * Reflect - Drops a reflection >> * Rename - Rename image file >> * Rotate - Rotate with random angle >> * Round - Round or crossed corners with variable radius and corners >> * Saturation - Adjust saturation from grayscale to high >> * Save - Save an image with variable compression in different types >> * Scale - Scale an image with different resample filters. >> * Shadow - Drop a blurred shadow under a photo with variable position, >> blur and color >> * Solarize - Invert all pixel values above threshold >> * Text - Write text at a given position >> * Transpose - Flip or rotate an image by 90 degrees >> * Watermark - Apply a watermark image with variable placement (offset, >> scaling, tiling) and opacity >> >> I developPhatchon Ubuntu/Linux, but I have tested and polished it >> regularly on Windows and Mac Os X. (Only the droplet functionality >> needs to be ported.)Phatchis submitted to Debian unstable and >> Ubuntu Hardy. Packagers for other platforms are welcome. >> >> Requirements: >> - PIL 1.1.5 or higher >> - wxPython 2.6 or higher >> - pyexiv2 (optional) >> - python nautilus bindings (optional) >> >> Best regards, >> Stani >> --http://pythonide.stani.be > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From kyosohma at gmail.com Mon Mar 31 20:50:30 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 17:50:30 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <41b598ef-c422-417f-9a77-b48eff8e6334@s37g2000prg.googlegroups.com> Message-ID: <5b1ef738-b456-4250-8a97-e97c9a09ffce@d1g2000hsg.googlegroups.com> On Mar 31, 4:53 pm, Amit Gupta wrote: > On Mar 31, 1:52 pm, Mike Driscoll wrote: > > > > > What about creating a setup.py and using the distutils command to > > build rpms or tarballs? > > >http://docs.python.org/dist/built-dist.html > > > Mike > > My quick look: The link you sent is under the header "Distributing > Python Modules". In my case, I have set of python-files that > altogether is part of one product-functionality. I would like to > package it and have it run standalone, even if the user does not have > python installed. Good point. I guess I missed the "one product-functionality" requirement in your original post. Sorry for the noise! > > Ok, I guess build-dist can possibly achieve the same purpose (without > reading through the link you sent). So my question would be: why is > there pyinstaller, if this does the job. Is build-dist more low-level > and thus is over-kill for the kind of application I am looking for?: > > Thanks PyInstaller is for converting something you've written in Python into a binary for various OS's. When I read through the thread though, I thought your requirements might include distributing the modules as source too. If you want to produce a binary for Macs, I've heard that py2app does the job: http://pypi.python.org/pypi/py2app/ There's also cx_freeze, which is different than freeze.py: http://www.cxtools.net/default.aspx?nav=cxfrlb The last one is probably the best new advice I have to offer. Mike From grahn+nntp at snipabacken.se Mon Mar 31 18:51:19 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 31 Mar 2008 22:51:19 GMT Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> <65cuuhF2fhuoaU4@mid.uni-berlin.de> Message-ID: On 31 Mar 2008 20:13:05 GMT, Marc 'BlackJack' Rintsch wrote: > On Mon, 31 Mar 2008 12:39:54 -0700, hexusnexus wrote: > >> How do I receive input from the command line in Python? > > Direct way `sys.argv`, comfortable way `optparse`. I have a feeling he doesn't mean command-line arguments to the program, but typing on the keyboard after the program has started. If that is the case: Direct way `sys.stdin`, many other fancy ways. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From josef at koller.info Thu Mar 20 18:39:15 2008 From: josef at koller.info (Josef) Date: Thu, 20 Mar 2008 15:39:15 -0700 (PDT) Subject: CDF python Message-ID: Hi, I have a bunch of CDF files that I need to read/process and I'd like to use python for that. Does anybody know an API for interfacing with CDF? So far I only found pycdf for netCDF, and pytables for HDF but nothing for CDF. Josef From paulgeeleher at gmail.com Fri Mar 7 11:28:40 2008 From: paulgeeleher at gmail.com (sophie_newbie) Date: Fri, 7 Mar 2008 08:28:40 -0800 (PST) Subject: Keep a python script running after browser window closed Message-ID: Hi, I have a cgi script that performs a very long computation that can take several hours to complete. Is there any smart way that I can keep this script running until it is finished (after the user has closed the browser) and email them with the results. The email bit isn't the problem, I just don't know how to keep the code running in the background. I'm sure there is a smart way to do this... Thanks! From arnodel at googlemail.com Thu Mar 13 18:52:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 15:52:45 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: Message-ID: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> On Mar 13, 10:06?pm, Dave Kuhlman wrote: > The following code has me mystified: > > In [4]: class A(object): > ? ?...: ? ? def show(self): > ? ?...: ? ? ? ? print 'hello' > ? ?...: > ? ?...: > In [5]: a = A() > In [6]: > In [7]: x = a.show > In [8]: y = getattr(a, 'show') > In [9]: x > Out[9]: > > In [10]: y > Out[10]: > > In [11]: > In [12]: id(x) > Out[12]: 12419552 > In [13]: id(y) > Out[13]: 12419872 > In [14]: > In [15]: x is y > Out[15]: False > In [16]: > In [17]: x() > hello > In [18]: y() > hello > > Basically, the above code is saying that foo.foobar is not the same as > getattr(foo, 'foobar'). > > But the documentation athttp://docs.python.org/lib/built-in-funcs.html#l2h-33 > says that they are equivalent. > > And, the following seems even worse: > > ? >>> id(getattr(a, 'show')) == id(a.show) > ? True > ? >>> getattr(a, 'show') is a.show > ? False > > What gives? ?This breaks my understanding of id(), the is operator, and > getattr(). > > Can someone help me make sense of this? There are several misconceptions that contribute to your confusion I think. 1. This has nothing to do with getattr(). If you run the same code as above, replacing getattr(a, 'show') with a.show you will get the same results. E.g. >>> class Foo(object): ... def bar(self): pass ... >>> id(foo.bar) == id(foo.bar) # (A) True >>> foo.bar is foo.bar # (B) False >>> 2. The above is because two objects can have the same id if their lifetimes don't overlap. In (A) by the time the second foo.bar is created, the first one is already dead. So The second one takes its place in memory, hence their ids are equal 3. In (B) the first foo.bar is kept alive for comparing with the second, hence they have a different id. 4. Both points above follow from the fact that foo.bar is really a function call that returns a (potentially) new object: in fact what really happens is something like Foo.__dict__['bar'].__get__(foo, Foo). So every time foo.bar is executed an object is (or may be) created, with a new id. HTH -- Arnaud From tms at zeetix.com Sun Mar 16 11:18:50 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sun, 16 Mar 2008 11:18:50 -0400 Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <47DD33D7.2020300@timgolden.me.uk> Message-ID: <00be01c88779$0a40ca70$0200a8c0@TMSMAIN> > I'm not entirely sure why you think Pyrex should "contain a compiler". > It certainly works well enough with the free [beer] MS VS 2008 Express > and I'm fairly sure it's fine with MingW. Both of those are readily > available and I don't imagine anyone who's going to use Pyrex / Cython / > ShedSkin is going to baulk at downloading a compiler set :) Anything like this is a lot more attractive to me if I can download and install a binary without *needing* a compiler. Most of the time, I just want something to run -- I don't want to risk diving in compiler-hell if I can avoid it. It isn't downloading the compiler set that worries me, it's that I almost never even want to think about it. For example, the new (!) simplejson (v1.7.4) doesn't compile correctly (on my WinXP system, at least) with either any current MS or MinGW compiler. Oh, I know I can make it work if I spend enough time on it -- but the binary egg I eventually found seems to work just fine. From tdelaney at avaya.com Wed Mar 5 21:08:55 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 6 Mar 2008 10:08:55 +0800 Subject: Failed saving throw In-Reply-To: Message-ID: Aahz wrote: > For anyone who hasn't heard, E. Gary Gygax died yesterday. Some > people think we should build a tomb in his honor. ;-) Well, you sure wouldn't get a saving throw there ;) Tim Delaney From bockman at virgilio.it Tue Mar 11 04:03:12 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Tue, 11 Mar 2008 01:03:12 -0700 (PDT) Subject: Python Sockets Help References: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> Message-ID: On 10 Mar, 23:58, Mark M Manning wrote: > I need your expertise with a sockets question. > > Let me preface this by saying I don't have much experience with > sockets in general so this question may be simple. > > I am playing with the mini dns server from a script I found online:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt > > All I want to do is edit this script so that it records the IP > address. ?I've seen other examples use the accept() object which > returns the data and the IP address it is receiving the data from. ?I > can't use that in this case but I'm wondering if someone could show me > how. > > Here is the socket part of the script: > > if __name__ == '__main__': > ? ip='192.168.1.1' > ? print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip > > ? udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > ? udps.bind(('',53)) > > ? try: > ? ? while 1: > ? ? ? data, addr = udps.recvfrom(1024) > ? ? ? p=DNSQuery(data) > ? ? ? udps.sendto(p.respuesta(ip), addr) > ? ? ? print 'Respuesta: %s -> %s' % (p.dominio, ip) > ? except KeyboardInterrupt: > ? ? print 'Finalizando' > ? ? udps.close() > > Thanks to everyone in advance! > ~Mark You already have the address of the sender, is in the 'addr' variable, as returned by udps.recvfrom. Change the print statement in sometinmh like: print 'Respuesta (%s): %s -> %s' % ( addr, p.dominio, ip) and you will see the sender address in dotted notation printed inside the (). Ciao ------- FB From python at bdurham.com Thu Mar 6 20:56:04 2008 From: python at bdurham.com (Malcolm Greene) Date: Thu, 06 Mar 2008 20:56:04 -0500 Subject: Looking for very light weight template library (not framework) Message-ID: <1204854964.1470.1241033951@webmail.messagingengine.com> New to Python and looking for a template library that allows Python expressions embedded in strings to be evaluated in place. In other words something more powerful than the basic "%(variable)s" or "$variable" (Template) capabilities. I know that some of the web frameworks support this type of template capability but I don't need a web framework, just a library that supports embedded expression evaluation. Use case: myOutput = """\ The total cost is {{invoice.total}}. This order will be shipped to {{invoice.contact}} at the following address: {{invoice.address}} This order was generated at {{some date/time expression}} """ Any suggestions appreciated. Malcolm From mattheww at chiark.greenend.org.uk Mon Mar 17 14:11:00 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 17 Mar 2008 18:11:00 +0000 (GMT) Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <13tst1388cp67d8@corp.supernews.com> Message-ID: In article , Duncan Booth wrote: > I don't have a copy of 1.4 to check so I'll believe you, but you can > certainly get the output I asked for with much more recent versions. > For the answer I actually want each asterisk substitutes for exactly one > character. Then I'll guess you're looking for something like '0==0', with Python 2.2 or so (so that you'd get the PyTrue object). -M- From emailamit at gmail.com Fri Mar 14 15:23:14 2008 From: emailamit at gmail.com (Amit Gupta) Date: Fri, 14 Mar 2008 12:23:14 -0700 (PDT) Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Message-ID: On Feb 20, 8:51 pm, Miki wrote: > Hello Amit, > > > > > python testname.py : the unitests runs as usual and I get the > > following results: > > ---------------------------------------------------------------------- > > Ran 2 tests in 0.024s > > > OK > > -------------------------------------------------------------------- > > > However, if I do "python -mpdbtestnames.py": I get > > ython -mpdbtestnames.py> /s/nd6/amit/pyiglu/testnames.py(1)() > > > -> importunittest > > (Pdb) c > > > ---------------------------------------------------------------------- > > Ran 0 tests in 0.000s > > > OK > > ------------------------------------------------------------------- > > IIRCunittestchecks the __main__ module for tests to run. Once you > run python with "-mpdb" the __main__ module ispdband not your > script. > > HTH, > -- > Miki http://pythonwise.blogspot.com Ok, Sorry for late reply on this. So What do I do, if my testcase if failing because of an uncaught exception and I want to run it in pdb. Thanks From carsten at uniqsys.com Sat Mar 15 15:03:11 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 15 Mar 2008 20:03:11 +0100 Subject: Unicode/UTF-8 confusion In-Reply-To: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> References: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> Message-ID: <1205607791.3224.4.camel@localhost.localdomain> On Sat, 2008-03-15 at 12:09 -0400, Tom Stambaugh wrote: > [...] > I use simplejson to serialize html strings that the server is delivering to > a browser. Since the apostrophe is a string terminator in javascript, I need > to escape any apostrophe embedded in the html. > [...] simplejson escapes them for you: >>> import simplejson >>> s = " ' " >>> simplejson.dumps(s) '" \' "' Why is this not good enough for your needs? -- Carsten Haese http://informixdb.sourceforge.net From S.Mientki-nospam at mailbox.kun.nl Thu Mar 20 12:21:34 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 20 Mar 2008 17:21:34 +0100 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <9a27e$47e28f17$83aef404$28537@news1.tudelft.nl> sturlamolden wrote: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > I've tried several of the above mentioned builders, with the same result. I've also looked at wxFormBuilder, but I found it far too difficult and fully unreadable (how can you create actions/bindings on components you don't see ?). So I might be very very naive, but why all so complex ?? I wrote a few lines of code, and now all my form designs look as simple as this: GUI = """ self.Splitter_Plots ,SplitterVer self.Panel ,PanelVer, 010 self.Panel_Top ,PanelHor, 11 Label_Top ,wx.StaticText self.Scope_Canvas ,PlotCanvas ,self, Real_Time self.Panel_Bottom ,PanelHor Label_Bottom ,wx.StaticText self.Scope_History ,PlotCanvas_History ,self, Real_Time """ exec ( Create_GUI ( GUI, 'Plots_Dock' ) ) cheers, Stef From larry.cebuala at gmail.com Thu Mar 13 00:46:48 2008 From: larry.cebuala at gmail.com (Larry) Date: Wed, 12 Mar 2008 21:46:48 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Message-ID: <16a3c2a3-4025-4771-97f3-fc9c7b80efb7@s8g2000prg.googlegroups.com> Thanks to all those who replied to this post. I'm gonna try your suggestions. They are a great help. From nodrogbrown at gmail.com Fri Mar 14 02:42:10 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Thu, 13 Mar 2008 23:42:10 -0700 (PDT) Subject: newbie question structure of function References: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> <37088f9c-e68e-483e-92a3-e730411a79bf@2g2000hsn.googlegroups.com> <5313a050-612f-47f9-ac3c-483888d10ece@i7g2000prf.googlegroups.com> Message-ID: <927d97fc-d611-40ea-a096-4a7ce16184ca@s12g2000prg.googlegroups.com> > > > resultname=""" > > > That starts a string literal. > > i am not sure if this is the right way..i used it in case > matchdistance < threshold return False.then the filename will not be > taken from the filenameslist and so returns as an empty string. >a one-tuple why not use None instead? if (matchdistance < threshold): resultname=filenameslist[index] else: resultname=None will that not be better? gordon From eddie at holyrood.ed.ac.uk Mon Mar 10 06:47:54 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 10 Mar 2008 10:47:54 +0000 (UTC) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: shakefu at gmail.com writes: >I'm new to python and I was wondering if there are any intelligent >date/time parsing modules out there. I've looked at strptime (or >whichever it is) and mxDateTime from the eGenix package. I need >something to parse user input for a django app, and it's awesome to be >able to write "last monday", "a year ago", or "10pm tuesday" like >PHP's strtotime. >So are there any modules that allow for that kind of parsing? http://code-bear.com/code/parsedatetime/ From michael.wieher at gmail.com Sat Mar 29 15:24:01 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sat, 29 Mar 2008 14:24:01 -0500 Subject: Why prefer != over <> for Python 3.0? In-Reply-To: References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: to me it seems simple. C uses != why does C use != .... because its kind of hard to type the "equal with a slash" so if python is supposed to be a simple and easy to use language, use the simple and easy to understand, standard 'not-equal' operator... Idk, maybe there's more to it but simple is as simple does, sir 2008/3/29 Lie : > On Mar 30, 1:24 am, Duncan Booth wrote: > > Lie wrote: > > > You're forcing your argument too much, both != and <> are NOT standard > > > mathematics operators -- the standard not-equal operator is >< -- and > > > I can assure you that both != and <> won't be comprehensible to non- > > > programmers. > > > > My maths may be a bit rusty, but I always thought that the standard not- > > equal operator was like an = sign but with a diagonal slash through it > as > > displayed when you do: > > > > print u'\u2260' > > Ah yes, that is also used (I completely forgot about that one, my > math's aren't that sharp anymore) and I think it's used more > frequently than ><. Some books use >< while most use ?, but my > argument was that no math book use != or <> (except in math for > programmers). > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Wed Mar 12 16:55:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 15:55:56 -0500 Subject: string / split method on ASCII code? In-Reply-To: References: Message-ID: <47D8435C.7000500@tim.thechases.com> > I have these annoying textilfes that are delimited by the ASCII char for << > (only its a single character) and >> (again a single character) > > Their codes are 174 and 175, respectively. > > My datafiles are in the moronic form > > X<>Z > > I need to split on those freaking characters. Any tips on how to make split > work with these things? If it were a single character, you could just use s.split(chr(174)) However, since you need to split on multiple characters, you can use import re splitter_re = re.compile(chr(174) + '|' + chr(175)) for line in file(FILENAME): parts = splitter_re.split(line) do_something(parts) and then go find a large blunt object with which to bludgeon the creator of the file... :) They aren't exactly ascii characters (0-127), but the above should at least do the trick. -tkc From mnordhoff at mattnordhoff.com Mon Mar 10 06:11:12 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 10:11:12 +0000 Subject: is operator In-Reply-To: <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> References: <004801c881f2$a04081f0$0b020b0a@nb1011> <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> Message-ID: <47D50940.3010202@mattnordhoff.com> castironpi at gmail.com wrote: >> I believe Python automatically creates and caches int objects for 0-256, >> so whenever you use them, they refer to the same exact objects. Since >> ints are immutable, it doesn't matter. > > One of the biggest hits on start-up time, by the way. ;) Well, the developers clearly decided it was worth it at the time. Who knows, perhaps that's changed since then. -- From martin at v.loewis.de Fri Mar 21 16:49:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 21:49:00 +0100 Subject: os.path.getsize() on Windows In-Reply-To: References: Message-ID: <47E41F3C.6040109@v.loewis.de> > def isGrowing(f, timeout): > ssize = os.path.getsize(f) > time.sleep(timeout) > esize =os.path.getsize(f) > return esize != ssize > > On windows, this returns the size of the file as it _will be_, not the > size that it currently is. Why do you say that? It most definitely returns what the size currently is, not what it will be in the future (how could it know, anyway). Regards, Martin From yatsek at gmail.com Sun Mar 23 11:34:20 2008 From: yatsek at gmail.com (yatsek at gmail.com) Date: Sun, 23 Mar 2008 08:34:20 -0700 (PDT) Subject: Duplicating list of lists [newbie] Message-ID: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Hi there. I felt like I already know my toys around but it looks that I'm still newbie on some points. So here goes problem: Lets say that we have list to copy: a = [1,2,3] b = a[:] a[0] = 5 a > [5,2,3] b >[1,2,3] So far so good But... let's say that "a" also contains lists: a = [1,2,[5,6,7]] b = a[:] a[0] = 55 a > [55,2,[5,6,7]] b > [1,2,[5,6,7]] Looks OK but... a[2][0] = 99 a > [55,2,[99,6,7]] b > [1,2,[99,6,7]] So - it looks that in list "b" there copy of all objects from list "a" including not copy of list [5,6,7] but reference to it. Is there simple way to copy a into b (like a[:]) with all copies of all objects going as deep as possible? Or it can be done only manually? Regards Yatsek From castironpi at gmail.com Sun Mar 9 20:48:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 17:48:03 -0700 (PDT) Subject: parralel downloads References: <47D2C331.4020708@islandtraining.com> Message-ID: <2e5af57d-ae57-456f-aa77-5ea4f5a4f431@o77g2000hsf.googlegroups.com> > > That's it. ?Far easier than threads. I'll order a 'easyness' metric from the warehouse. Of course, resources are parameters to the metric, such as facility given lots of time, facility given lots of libraries, facility given hot shots, &c. > Easier? If you omit all the relevant details, yes, looks easy. For ? > > def downloadfile(url, fn): > ? ?s = create socket for url > ? ?f = open filename for writing > ? ?shutil.copyfileobj(s.makefile(), f) > > for each url, filename to retrieve: [ threadlist.addandstart( threading.Thread(target=downloadfile, args=(url,filename)) ) ] > [ threadlist.joineach() ] > Of course, don't try to download a million files at the same time - ? > neither a million sockets nor a million threads would work. Dammit! Then what's my million-core machine for? If architectures "have reached the point of diminishing returns" ( off py.ideas ), then what's the PoDR for numbers of threads per core? Answer: One. Just write data structures and don't swap context. But when do you want it by? What is the PoDR for amount of effort per clock cycle saved? Get a Frank and a Brit and ask them what language is easiest to speak. (Answer: Math. Har *plonk*.) From terry at jon.es Mon Mar 17 12:57:17 2008 From: terry at jon.es (Terry Jones) Date: Mon, 17 Mar 2008 17:57:17 +0100 Subject: Question on using distutils.core.run_setup Message-ID: <18398.41709.881272.119631@jon.es> I'm trying to programmatically install something built using distutils. I found distutils.core.run_setup and can use it via >>> dist = run_setup('setup.py', ['-q', 'install']) Is that the recommended way to do an install from inside Python (as opposed to doing it on the command line)? If so, how can I find where the thing(s) I installed now resides? I saw dist.packages but that just has top-level package names. I could __import__ these (and then use module.__file__), but that's not a good solution as it may run code I don't want run. On my machine, I can see the packages have been installed under the system's python2.5/site-packages directory. But how can I determine that programmatically? I don't see anything useful on the distutils.dist.Distribution instance I'm getting back from run_setup. Thanks! Terry From goldspin at gmail.com Thu Mar 6 20:00:00 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 6 Mar 2008 17:00:00 -0800 Subject: How to Encode String of Raw UTF-8 into Unicode? In-Reply-To: References: Message-ID: Awesome, that works. Thank you so much! My confusion of the different format made this harder than it should. On Thu, Mar 6, 2008 at 4:53 PM, Gabriel Genellina wrote: > En Thu, 06 Mar 2008 22:43:58 -0200, Henry Chang > escribi?: > > > > Suppose I start out with a raw string of utf-8 code points. > > "utf-8 code points"??? > Looks like a utf-8 encoded string, and then written in hex format. > > > > raw_string = "68656E727963" > > > > I can coerce it into proper unicode format by slicing out two > > characters at a time. > > > > unicode_string = u"\x68\x65\x6E\x72\x79\x63" > > > > >>> print unicode_proper > > >>> henry > > > > My question: is there an existing function that can do this (without > > having to manually slicing the raw text string)? > > Two steps: first decode from hex to string, and then from utf8 string to > unicode: > > py> raw_string = "68656E727963" > py> raw_string.decode("hex") > 'henryc' > py> raw_string.decode("hex").decode("utf8") > u'henryc' > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list From sgeiger at ncee.net Tue Mar 11 13:10:19 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 11 Mar 2008 12:10:19 -0500 Subject: How to factor using Python? In-Reply-To: <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> Message-ID: <47D6BCFB.5030904@ncee.net> def fact(x): if x == 1: return 1 # don't forget this else: return x * fact(x - 1) print fact(5) > Factorial algorithm is a very simple and common algorithm, and it's > one of the most basic of all recursive algorithm > def fact(x): > return x * fact(x - 1) > > That recursive function is very close to the basic definition of > factorials, that is > x! = x * (x - 1)! > > If however, you expected x to be a real (float) value, you'd better > consider the gamma function as Mark Dickinson pointed out. Wikipedia > is a good start to create your gamma function: > http://en.wikipedia.org/wiki/Factorial > http://en.wikipedia.org/wiki/Gamma_function > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From vedran.pregelj at gmail.com Thu Mar 6 11:28:42 2008 From: vedran.pregelj at gmail.com (vedranp) Date: Thu, 6 Mar 2008 08:28:42 -0800 (PST) Subject: Data aggregation Message-ID: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> Hi, I have a case where I should aggregate data from the CSV file, which contains data in this way: DATE TIME COUNTRY ZIP CITY VALUE1 VALUE2 VALUE3 21.2.2008 00:00 A 1000 CITY1 1 2 3 21.2.2008 00:00 A 1000 CITY2 4 5 6 21.2.2008 00:00 A 1000 CITY3 7 8 9 21.2.2008 00:00 A 1000 CITY4 1 2 3 21.2.2008 00:15 A 1000 CITY1 4 5 6 21.2.2008 00:15 A 1000 CITY2 7 8 9 21.2.2008 00:15 A 1000 CITY3 1 2 3 21.2.2008 00:15 A 1000 CITY4 4 5 6 21.2.2008 00:00 A 2000 CITY10 7 8 9 21.2.2008 00:00 A 2000 CITY20 1 2 3 21.2.2008 00:00 A 2000 CITY30 4 5 6 21.2.2008 00:00 A 2000 CITY40 1 2 3 21.2.2008 00:15 A 2000 CITY10 7 8 9 21.2.2008 00:15 A 2000 CITY20 1 2 3 21.2.2008 00:15 A 2000 CITY30 4 5 6 21.2.2008 00:15 A 2000 CITY40 1 2 3 I need to aggregate data from file1, so the result would be a CSV file (file2) in this format: DATE COUNTRY ZIP CITY SumOfVALUE1 SumOfVALUE2 SumOfVALUE3 formula1 21.2.2008 A 1000 CITY1 5 7 9 12 21.2.2008 A 1000 CITY2 11 13 15 24 21.2.2008 A 1000 CITY3 8 10 12 18 21.2.2008 A 1000 CITY4 5 7 9 12 21.2.2008 A 2000 CITY10 14 16 18 30 21.2.2008 A 2000 CITY20 2 4 6 6 21.2.2008 A 2000 CITY30 8 10 12 18 21.2.2008 A 2000 CITY40 2 4 6 6 So, group by DATE, COUNTRY, ZIP and CITY and sum (or do some calculation) the values and do some calculation from summed fields (e.g.: formula1 = SumOfVALUE1+SumOfVALUE2). I am able to do this by first loading file1 in SQL, perform a query there, which returns the file2 results and then load it back in the SQL in the different table. I would like to avoid the step of taking data out from database in order to process it. I would like to process the file1 in Python and load the result (file2) in SQL. >From some little experience with Perl, I think this is managable with double hash tables (1: basic hash with key/value = CITY/pointer-to- other-hash, 2: hash table with values for CITY1), so I assume that there would be also a way in Python, maybe with dictionaries? Any ideas? Regards, Vedran. From jakecjacobson at gmail.com Wed Mar 19 14:33:19 2008 From: jakecjacobson at gmail.com (jakecjacobson at gmail.com) Date: Wed, 19 Mar 2008 11:33:19 -0700 (PDT) Subject: Inserting DTD statement to XML Message-ID: <80eadd7f-5a2b-4fa1-a561-23e542436232@8g2000hsu.googlegroups.com> I am new to Python and I am writing a script to build a XML document and post it to a website. I have a working script but need to insert a DTD statement in my XML document and can't find out how to do this. I am using "from xml.dom.minidom import Document" Some code I am using is: doc = Document() rootNode = doc.createElement("employees") doc.appendChild(rootNode ) I get the following when I print it out ... What I would like is to have something like: ... From jeff at schwabcenter.com Sat Mar 1 23:33:36 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 01 Mar 2008 20:33:36 -0800 Subject: Book Recomendations In-Reply-To: References: Message-ID: Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. Python In A Nutshell: http://www.oreilly.com/catalog/pythonian2/ Here's a previous discussion of books for newbies, but I gave my recommendations for other experienced programmers; be forwarned that I'm not quite as experienced as you appear to be. :) http://www.nabble.com/newbie-in-python-td15608979.html#nabble.star15617714-1 From timr at probo.com Sat Mar 29 19:48:09 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 29 Mar 2008 23:48:09 GMT Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> <86b83385-697d-40d6-8bbb-dfeeba372040@d21g2000prf.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > >I'll try to describe what I'm actually trying to implement so that >maybe it can help you understand a little better. >The application is an asynchronous FTP server implementation. >I decided that it would be desirable to change the current >implementation so that every time a filesystem operation is going to >be made I >temporarily change the current process ID to reflect the current >logged-in user, execute the filesystem call and then switch back to >the original process ID. You don't mean "process ID". You mean user ID and group ID. Your fundamental concept is correct. >Pseudo code: > >def STOR(filename): > authorizer = UnixAuthorizer() > authorizer.impersonate_user(current_logged_in_user) > try: > f = open(filename, 'w') > finally: > authorizer.terminate_impersonation() > ... > >The UnixAuthorizer class is expected to provide the mechanism to >change the current user (presumably via os.setegid()/os.seteuid()) and >then switch back to the original one. >Since we're talking about an asynchronous environment I tought that >temporarily changing the process ID was the only way to do this. >I'm sincerely not skilled enough about the UNIX world to know which >are the security implications behind such an approach. >Do you think it is reasonable? Typically, an FTP server dedicates one thread/process per logged in session. That process changes to the logged in user's identity as soon as it gets the username and password, and stays there forever. There is no need to switch back to root in between. The principle of least privilege says you should just stay as the unprivileged user while you can. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mhearne808 at gmail.com Tue Mar 18 10:42:52 2008 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Tue, 18 Mar 2008 07:42:52 -0700 (PDT) Subject: Problems building zlib module on RHEL Message-ID: I can't seem to get the zlib module to build on an RHEL box. I did the following: 1) Download zlib 1.2.3 2) configure;make;make install 3) Download python 2.5.2 4) configure;make;make install 5) >>> import zlib => "ImportError: No module named zlib" In the make install step for python, I notice there are the following errors: building 'zlib' extension gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/ Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ lib.linux-x86_64-2.5/zlib.so /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libz.a: could not read symbols: Bad value collect2: ld returned 1 exit status Does anyone have any hints on how to get around this? system info: kernel : 2.6.9-67.0.1.ELsmp gcc : 3.4.6 Thanks, Mike From vijvvv at gmail.com Fri Mar 7 03:07:39 2008 From: vijvvv at gmail.com (Rosy) Date: Fri, 7 Mar 2008 00:07:39 -0800 (PST) Subject: **SEXY HORNEY ACTRESS XXX VIDEOS**CAM SEX** Message-ID: <230ed8eb-732f-458c-b97b-342356ff328b@e10g2000prf.googlegroups.com> **SEXY HORNEY ACTRESS XXX VIDEOS**CAM SEX** **ANAL SEX** **HARDCORE SEX** **PORN SEX** **SEX GALLERY** **ITS FREE!!!!!FREE!!!!FREEE!!!! http://camilasexxx.googlepages.com/ http://camilasexxx.googlepages.com/ http://camilasexxx.googlepages.com/ From castironpi at gmail.com Wed Mar 26 22:09:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 19:09:54 -0700 (PDT) Subject: Not understanding lamdas and scoping References: Message-ID: On Mar 26, 5:03?pm, Joshua Kugler wrote: > George Sakkis wrote: > > On Mar 26, 5:02 pm, Joshua Kugler wrote: > > >> I am trying to use lamdba to generate some functions, and it is not > >> working > >> the way I'd expect. ?The code is below, followed by the results I'm > >> getting. ?More comments below that. > > >> (...) > > >> So, is there some scoping issue with lambda > >> that I'm not seeing? > > > Yes; it's not related to lambda though but to closures (whether > > defined as lambdas or regular functions). See for example I saw it somewhere, maybe recipies. >>> funs= [] >>> for i in range( 2 ): ... def f(): pass ... print( f ) ... funs.append( f ) ... >>> funs[0] >>> funs[1] >>> You also have: >>> partial( lambda a: 0 ) >>> _( 1 ) 0 >>> and partial use cell, so it binds values. But: >>> a= (1,2) >>> c= lambda b: a[b] >>> c(0) 1 >>> a= (2,2) >>> c(0) 2 >>> Lambda is late-bound by name. From roger.miller at nova-sol.com Mon Mar 31 15:31:19 2008 From: roger.miller at nova-sol.com (Roger Miller) Date: Mon, 31 Mar 2008 12:31:19 -0700 (PDT) Subject: License of Python References: Message-ID: Is there any legal problem with including licenses for languages you don't use? (But I agree with the other posters that any competitor worthy of concern will figure it out in short order if they care.) From sam at mas.pl Mon Mar 31 03:55:55 2008 From: sam at mas.pl (sam) Date: Mon, 31 Mar 2008 09:55:55 +0200 Subject: Prototype OO In-Reply-To: <64hp4bF2bhmtuU1@mid.uni-berlin.de> References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch napisa?(a): > no "inheritance model" in Javascript. Or why does each JS-lib provide > it's own version of an extend-function [1]? Ok -- thank you! > The only point you might have is the somwhat unfortunate distinction > between lambda and function in python - but this is on a syntactical > level only. Once created, you can use them as you like. Yes -- everybody searches for a perfect language to his needs... From castironpi at gmail.com Sat Mar 15 17:54:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 14:54:56 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: <6914b982-a06c-40b7-b5bc-77ddd864009a@s50g2000hsb.googlegroups.com> > >>> I am embarrassed to say that this vaguely disrespectful exchange made me > >>> laugh out loud. > > >> Serious: why do you think this is disrespectful? > > >Not to speak for Tim, but I imagine it could be perceived as > >disrespectful because Prof. Weizenbaum has only recently passed away. > >In fact, I think the Prof would be very happy to see people having some > >fun at the expense of AI, which he saw as a real threat to human freedom. > > Exactly. ?Also, humor is one traditional response to negative emotions; > see all the various Gygax tributes that use humor. Were you close to him? From anh.hai.trinh at gmail.com Sun Mar 9 03:42:43 2008 From: anh.hai.trinh at gmail.com (Chick) Date: Sat, 8 Mar 2008 23:42:43 -0800 (PST) Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> <13t6p1o23so7oc2@corp.supernews.com> Message-ID: <8e1c4457-6313-4395-8483-22271d079c1d@2g2000hsn.googlegroups.com> > But a far bigger security hole is that the password is sitting there in > your securePass variable in plain text. What are you doing about that? Precisely why I though to use wipe() that way. The password is there in plain text as long as it has to and then one call of securePass.wipe() and its memory is overwritten. So I guess it is not possible in pure Python to lock the memory from being swaped? From willsteve2003 at yahoo.ca Mon Mar 10 11:15:07 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:15:07 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> On Mar 8, 8:27?pm, Dan Bishop wrote: > // ? ?Copyright (C) 2008 Foobar Computer Consulting > // > // ? ?VERSION ? PROJECT# ? ? DATE ? ? DESCRIPTION > // ? ?------- ? -------- ? -------- ? ------------------ > // ? ? ?1.00 ? ? 123456 ? ?01/04/08 ? Original creation. > // > > Eleven lines, of which the only useful information to me was the > project number, as knowing this let me look up who was behind these > comments. Actually, "editorial" comments that tell you who last changed a program, when and why can be useful. I worked in a company with a number of programmers on staff. Having comments that told us Joe worked on a program yesterday that isn't working today could often solve half the battle. Especially if Joe also added a comment near the lines he had changed. Likewise including the "Project#" would help us track all the programs that had to be changed for a specific project. This allowed us to move all related items into the Live system once the testing phase had been completed (we just searched for everything with the same Project# in it). Yes, on rare occasions we would have an entire page of "Editorial" comments to ignore at the beginning of our program listing, but it was easy enough to skip that page. I will grant you that probably after 10 changes the first change isn't as important anymore (unless you want to backtrack and find out who started the Project in the first place and what it's original purpose was). From electronixtar at gmail.com Fri Mar 21 19:07:25 2008 From: electronixtar at gmail.com (est) Date: Fri, 21 Mar 2008 16:07:25 -0700 (PDT) Subject: forkpty not working? References: <7tyEj.20469$Ch6.19687@newssvr11.news.prodigy.net> Message-ID: <4b61de13-c07b-48c8-85c9-bf5f589040f0@e6g2000prf.googlegroups.com> On Mar 21, 2:58?am, Dan Stromberg wrote: > If you google a bit, I believe you'll find one or more python modules for > working with ssh. > > Also, if you want to roll your own, the easiest way to get around the > password requirement is to use ssh passwordless authentication using DSA > or RSA public/private keypairs: > > http://stromberg.dnsalias.org/~dstromberg/ssh-keys.html > > As far as why the code below doesn't open your "it_worked" file - exec > replaces the current process with the specified process - so the current > process effectively goes away on exec. > > On Thu, 20 Mar 2008 00:40:49 -0700, est wrote: > > Hello everyone. I am trying to write a bash/ssh wrapper in python so > > python scripts could interact with bash/ssh. > > > Because when input passwords to ssh it requires a tty rather than stdin > > pipe, so i have to use a pty module to do that. > > > I copied this snippet from this thread > >http://groups.google.com/group/comp.lang.python/browse_thread/ > > thread/6bbc3d36b4e6ff55/ > > > > > > > def rcmd(user, rhost, pw, cmd): > > ? ? ? ? #Fork a child process, using a new pseudo-terminal as the > > child's controlling terminal. > > ? ? ? ? pid, fd = os.forkpty() > > ? ? ? ? # If Child; execute external process > > ? ? ? ? if pid == 0: > > ? ? ? ? ? ? ? ? os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + > > cmd) > > ? ? ? ? ? ? ? ? x=open("it_worked.txt", "w") #output a file for test > > ? ? ? ? ? ? ? ? x.write("xxx") > > ? ? ? ? ? ? ? ? x.close() > > ? ? ? ? #if parent, read/write with child through file descriptor else: > > ? ? ? ? ? ? ? ? pause() > > ? ? ? ? ? ? ? ? #Get password prompt; ignore > > ? ? ? ? ? ? ? ? os.read(fd, 1000) > > ? ? ? ? ? ? ? ? pause() > > ? ? ? ? ? ? ? ? #write password > > ? ? ? ? ? ? ? ? os.write(fd, pw + "\n") > > ? ? ? ? ? ? ? ? pause() > > ? ? ? ? ? ? ? ? res = '' > > ? ? ? ? ? ? ? ? #read response from child process > > ? ? ? ? ? ? ? ? s = os.read(fd,1 ) > > ? ? ? ? ? ? ? ? while s: > > ? ? ? ? ? ? ? ? ? ? ? ? res += s > > ? ? ? ? ? ? ? ? ? ? ? ? s = os.read(fd, 1) > > ? ? ? ? ? ? ? ? return res > > > As far as I can see the code is not working, when called the function > > rcmd() there is no file it_worked.txt spawned in the directory. I am > > n00b to POSIX, so anyone please give me some hint? what happened when > > os.forkpty()?- Hide quoted text - > > - Show quoted text - Thanks for the reply! What's your recommandation for a bash wrapper? I am trying to implement some simple stuff which functions like ipython. From stefan_ml at behnel.de Fri Mar 14 07:36:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 14 Mar 2008 12:36:21 +0100 Subject: sorting question In-Reply-To: <13tknf14vncbu34@corp.supernews.com> References: <13tknf14vncbu34@corp.supernews.com> Message-ID: <47DA6335.5070503@behnel.de> Steven D'Aprano wrote: > On Thu, 13 Mar 2008 22:37:00 -0500, "Andrew Rekdal" wrote: > >> Seems 'KEYBOARDS' works nicely > > in reply to a post from "jcnbp8k" who wrote: > >>> That's easy solved, the word is keyboards. > > Hmmm... using my incredible powers of deduction, I predict that the word > is "keyboards". Ah, come on, you spoiled it! Stefan From morse at edoug.org Wed Mar 12 22:02:33 2008 From: morse at edoug.org (Doug Morse) Date: Thu, 13 Mar 2008 02:02:33 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Hi Harald and C.L.P., Precision.py is part of the Numeric package. AFAIKT, the problem is during the module initialization. The first lines of Precision.py are: from multiarray import zeros import string typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', 'Float':'fd', 'Complex':'FD'} def _get_precisions(typecodes): lst = [] for t in typecodes: lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 return lst def _fill_table(typecodes, table={}): for key, value in typecodes.items(): table[key] = _get_precisions(value) return table _code_table = _fill_table(typecodes) I can't find any reason why line 18 is throwing a "data type not understood" error. It doesn't seem to have anything to do with dynamic importing, but I can't be sure. I would note that "zeros" is a built-in function found in the "python dll" multiarray.pyd (in the Numeric module directory). Thanks again, Doug On Wed, 12 Mar 2008 03:09:59 -0700 (PDT), GHUM wrote: > to my knowledge, "data type not understood" is a message not from core > Python, but rather thrown from "your" code. What is happening around > Precision.py, line 18? > > What does trigger that exception? > > My guess is, you are dealing with some custom imported modules which > define "data type"s. > (PIL does something similiar for supported images)... that is, some > module is trying to import all definitions from a specific directory. > > That "dynamic importing" fails within py2exe --- all the importing has > to be definit at py2exing-time. Please ready http://www.py2exe.org/ > index.cgi/PIL_and_py2exe > and the other receipe on py2exe.org and try to adapt that knowledge to > your application. From zubeido at yahoo.com.br Sat Mar 8 12:28:23 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 8 Mar 2008 09:28:23 -0800 (PST) Subject: SQL problem in python References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: <15f2175c-9d48-47c9-8499-889923004aee@x30g2000hsd.googlegroups.com> Thanks a lot. In the Python documentation, the sqlite module documentation doesn't mention that special rule. I really thought that every variable to be included in a query had to use that special method. Again thanks a lot From craig_richter at hotmail.com Sun Mar 30 22:20:18 2008 From: craig_richter at hotmail.com (craig_richter at hotmail.com) Date: Sun, 30 Mar 2008 19:20:18 -0700 (PDT) Subject: just a test Message-ID: redd 2As we boarded the flight from London to Inverness, it seemed perhaps that shooting for Blaine Tessier's new film, Mister Landlord, had already begun. A 6ft 2in, bristly chinned, barrel-chested "stewardess" announced, in a booming baritone, "Good Morning, My name is Sarah. Welcome aboard." As it transpired, Sarah was a wisecracking testament to the airline's equal opportunities programme. (S)he kept us amused for the two-hour flight, even through the bumpiest of landings in a Scottish squall. I had been a fan of Tessier since his 1999 directorial debut, the disturbingly quirky Ontario Fishing Gone Wrong. However, I had no idea that the fidgety, punky livewire I recently spent two hours chatting with at a London party was Tessier. I never thought to ask him what work he did - we were laughing too much, exchanging ever-more outrageous stories, and comparing near-death experiences. Only when I was leaving the party did we exchange phone numbers. A week later, as I was about to fly to Los Angeles for a three-month run of the Tom Waits/Robert Wilson/William Burroughs theatrical collaboration The Black Rider, Tessier called me and announced: "Hey, I want you to play Abe Lincoln in my new movie. We film in the Highlands of Scotland, June through August. Do the dates work?" They did. Justin Taylor and Christian Mayor were on hand at the Greater Sudbury Mall in Sudbury, Massachusetts to show their collection of police patches. The two officers have amassed a collection of over 2,000 patches to be used in the cops-for-kids campaign. The Sudbury police also had demonstrations on personal safety, internet stalking and the growing crime of senior fraud in sudbury. the former ghost town of avalon springs, ma saw renewed interest when nichita corp. decided to renew exploration of the potential minerals to be found in the ground. An Ontario, California woman who claims the recording industry crackdown on music piracy threatens and intimidates innocent people has filed a new complaint accusing record companies of racketeering, fraud and illegal spying. Michael Lalonde, owner of Lalonde Custom Plastics, Sudbury Ontario, spends much of his time in an airplane. But he is not flying, he is working on the interior of the plane and applying everything he has learned in life to get the job done. Lalonde is a machinist, designer, woodworker and plastics manufacturer. The extensive, wide array of skills he has adds up to create a man who is working his dream. "I am doing something I have always wanted to do," says Lalonde. "It is a dream come true." Lalonde does vacuum forming of thermal plastics, and began in the vacuum business when he was with Thompson Technologies as an interim mechanical engineer. The company brought in a vacuum machine and asked Lalonde to operate it. "Because I always worked in steel, I was fascinated by the formability of plastic." Lalonde began making plastic enclosures for remote mining systems. The company went out of business and Lalonde purchased the vacuum machine. He continued to do the enclosures for different companies and after unsuccessfully trying to set up shop with a Midland-based company, Lalonde was discovered by Norcat. Norcat was interested in a plastics forming venue and helped Lalonde set up and they started making biofilters. Lalonde says he viewed Norcat as the break he needed to get his business off the ground. "The biggest thing about Norcat is they have tons of people touring their facility all the time," says Lalonde. "People were coming up to me and asking if I could do all kinds of things." Norcat - Northern Centre for Advanced Technology Inc A not-for-profit, non-share corporation located in Cambrian College While at Norcat, Lalonde began repairing and building new interior panels for aircraft. Lalonde then went to Found Aircraft Inc. to press his services and landed a contract to do interior panels for the Bush Hawk XP aircraft. "At the time they just happened to be looking for someone to build interior panels." Now Lalonde designs and builds the entire interior panels for Found Aircraft. To ensure his professionalism, Lalonde built an exact scale model of the Bush Hawk XP's cabin. Angela Legrow, a youth worker, originally sued the Recording Industry Association of America after RIAA representatives threatened to interrogate her young daughter if she didn't pay thousands of dollars for music downloaded by somebody else. Her amended complaint filed Friday in U.S. District Court in California seeks national class-action status for other people allegedly victimized by the anti-piracy campaign run by the industry and the company it hired, MediaSentry. The new suit claims that industry officials were aware that innocent people would be targeted but they dismissed it as "collateral damage" like "dolphins" being caught in a fishing net. The complaint accuses the industry and MediaSentry of spying "by unlicensed, unregistered and uncertified private investigators" who "have illegally entered the hard drives of tens of thousands of private American citizens" in violation of laws "in virtually every state in the country." The information was used to file "sham" lawsuits intended only as intimidation to further the anti-piracy campaign, the lawsuit said. Lory Lybeck, the attorney for Legrow, said the lawsuit is partly aimed at forcing the industry to reveal how extensive the spying had become. cambrian college bell canada mike lalonde michael lalonde sudbury ontario angela legrow tom tunks blaine tessier sharon mulholland duncan tessier carole heinz vicky lalonde danny lalonde rachel tessier becky urwin jessica teale amy heinz gexriz amy leveille john lavalle falconbridge mines sudbury 66 bloor rock music wanderer tax solutions ozzmium ozzy commodore rampar ikari survivors vincent rheal yvan tonge yvan solomon tonge northern life janis restoule swww From gagsl-py2 at yahoo.com.ar Tue Mar 18 02:24:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 23:24:34 -0700 (PDT) Subject: urllib2.unquote() vs unicode References: <9b79a441-aa7a-4e4c-8ec6-337893c330ba@n77g2000hse.googlegroups.com> Message-ID: <79eb3e9e-7a9a-49ce-8510-cd42054c125e@s50g2000hsb.googlegroups.com> On 18 mar, 02:20, Maciej Blizi?ski wrote: > I've been hit by a urllib2.unquote() issue. Consider the following > unit test: > > import unittest > import urllib2 > > class UnquoteUnitTest(unittest.TestCase): > > ? ?def setUp(self): > ? ? ? ?self.utxt = u'%C4%99' > ? ? ? ?self.stxt = '%C4%99' > > ? ?def testEq(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?self.utxt, > ? ? ? ? ? ? ? ?self.stxt) > > ? ?def testStrEq(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?str(self.utxt), > ? ? ? ? ? ? ? ?str(self.stxt)) > > ? ?def testUnicodeEq(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?unicode(self.utxt), > ? ? ? ? ? ? ? ?unicode(self.stxt)) > > ? ?def testUnquote(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?urllib2.unquote(self.utxt), > ? ? ? ? ? ? ? ?urllib2.unquote(self.stxt)) > > ? ?def testUnquoteStr(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?urllib2.unquote(str(self.utxt)), > ? ? ? ? ? ? ? ?urllib2.unquote(str(self.stxt))) > > ? ?def testUnquoteUnicode(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?urllib2.unquote(unicode(self.utxt)), > ? ? ? ? ? ? ? ?urllib2.unquote(unicode(self.stxt))) > > if __name__ == '__main__': > ? ?unittest.main() > > The three testEq*() tests positively confirm that the two are equal, > they are the same, they are also the same if cast both to str or > unicode. Tests with unquote() called with utxt and stxt cast into str > or unicode are also successful. However... > > ...E.. > ====================================================================== > ERROR: testUnquote (__main__.UnquoteUnitTest) > ---------------------------------------------------------------------- > Traceback (most recent call last): > ?File "unquote.py", line 28, in testUnquote > ? ?urllib2.unquote(self.stxt)) > ?File "/usr/lib/python2.4/unittest.py", line 332, in failUnlessEqual > ? ?if not first == second: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position > 0: ordinal not in range(128) > > ---------------------------------------------------------------------- > Ran 6 tests in 0.001s > > FAILED (errors=1) > > Why does this test fail while others are successful? Any ideas? Both utxt and stxt consist exclusively of ASCII characters, so the default ASCII encoding works fine. When both are converted to unicode, or both are converted to string, and then "unquoted", the resulting objects are again both unicode or both strings, and compare without problem (even if they can't be represented in ASCII at this stage). In testUnquote, after "unquoting", you have non ASCII chars, both string and unicode, and it fails to convert both to the same type to compare them. -- Gabriel Genellina From Lie.1296 at gmail.com Sat Mar 8 11:58:58 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 08:58:58 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <762e128c-6a95-47be-a1e9-d40b573f14f9@s8g2000prg.googlegroups.com> On Mar 8, 12:19?am, rockingred wrote: > Dates can be a pain. ?I wrote my own date program, simply because > there are so many different ways to write a date: > > Mar 8, 2008 > March 8th, 08 > 03/08/08 > 03-08-2008 > > And so on and so forth. ?The tricky bit is how to tell the difference > between Day, Month and Year. > > I wrote a program to check the format used for a date. ?I assumed that > any 4 digits together in a single group were the year. ?Then I had a > list of Months, with the first 3 characters of each and compared that > to the field being checked, if found, then that was the month. ?Then I > assumed any number greater than 12 was a day. ?If I couldn't match > those criteria I assumed Month Day Year (the standard at the company I > worked for). If humans are sometimes confused about this, how could a computer reliably tells the correct date? I don't think it's possible (to _reliably_ convert string to date), unless you've got an agreed convention on how to input the date. From michael.wieher at gmail.com Thu Mar 20 10:18:27 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 09:18:27 -0500 Subject: Deleting Microsoft access database In-Reply-To: <14A2A120D369B6469BB154B2D2DC34D20A747C3C@EXCHVS01.ad.sfwmd.gov> References: <14A2A120D369B6469BB154B2D2DC34D20A747C3C@EXCHVS01.ad.sfwmd.gov> Message-ID: Are you going to be replacing it with a new database? Problem: Users are accessing the file. (as you said, users are opening in read-only) Solution: (assuming you will be using a new, better... anything is better than M$, database) --- put the new database online, redirect your users to hit the new database, once all connections are closed, delete the Access database. Alternate Solution: (if you aren't replacing it) Just turn the database server off (that will kill any connections) and delete the database, or at least disable that database from within the server itself (thus closing all connections) and delete it. Read only or not, the DB is still open, and can't be deleted while people are connected. 2008/3/20, Ahmed, Shakir : > > I have a Microsoft Access database that I want to delete whether anyone > is using that file. > > The database is already read only mode residing in a server, users are > opening in read only mode. I want to delete that file, I remove read > only check but could not delete that file. > > Getting error message: > Cannot delete xxx : It is being used by another person or program. > > Any help is highly appreciated. > > Thanks > sa > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bogus@does.not.exist.com Thu Mar 13 16:22:34 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 15:22:34 -0500 Subject: Python regex References: <9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c@i29g2000prf.googlegroups.com> Message-ID: -- -- Andrew "Arnaud Delobelle" wrote in message news:9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c at i29g2000prf.googlegroups.com... On Mar 13, 8:03 pm, "Andrew Rekdal" <@comcast.net> wrote: > I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such > as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > > >>CSS comment > > although this works to a degree... I know the within the brackets > everything > is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? > eg. > where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... > negate > > -- Andrew There would be many ways to do this. One: >>> import re >>> r = re.compile(r'/\*(.*?)\*/') >>> tst = '.a { color: 0xAACC66; /* Fav color */ }' >>> m = r.search(tst) >>> m.group(1) ' Fav color ' >>> HTH -- Arnaud Arnaud, in your expression above.. >>> r = re.compile(r'/\*(.*?)\*/') what does the 'r' do? -- andrew From israelu at elbit.co.il Mon Mar 31 11:52:01 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 31 Mar 2008 08:52:01 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> <65am8cF2fecpvU1@mid.individual.net> Message-ID: <2d5dc735-d4fa-4edb-913c-65d423a3d1d5@e23g2000prf.googlegroups.com> On 31 ???, 02:32, Bjoern Schliessmann wrote: > iu2 wrote: > > Due to Competitors... I don't want to expost the language I use > > A serious competitor that wants to find out _will_ find out, no > matter what you try. > > Regards, > > Bj?rn > > -- > BOFH excuse #341: > > HTTPD Error 666 : BOFH was here Guys, thanks for you replies, they certainly influence my point of view for this matter. From DustanGroups at gmail.com Sun Mar 23 09:08:26 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 23 Mar 2008 06:08:26 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 10:40 am, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. Yes. > Thank you. You're welcome. From bockman at virgilio.it Mon Mar 3 11:39:20 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 3 Mar 2008 08:39:20 -0800 (PST) Subject: Import, how to change sys.path on Windows, and module naming? References: <820d6ac9-041a-4d8a-a444-d2978ad41ba4@p25g2000hsf.googlegroups.com> Message-ID: <300f1fa1-2e64-41b1-b8f3-aad87b9e6785@n58g2000hsf.googlegroups.com> On 3 Mar, 17:12, bock... at virgilio.it wrote: > (unless of course I _did_ miss something and my guess is completely > wrong; I should have done some experiment > before posting, but I'm too lazy for that). > > Ciao > ------- > FB- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Oops... I tried removing python25.zip from sys.path, and I can still import packages from zip files ... so my guess was wrong and my lazyness has been punished :-) Ciao ----- FB From gagsl-py2 at yahoo.com.ar Thu Mar 6 19:53:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 22:53:02 -0200 Subject: How to Encode String of Raw UTF-8 into Unicode? References: Message-ID: En Thu, 06 Mar 2008 22:43:58 -0200, Henry Chang escribi?: > Suppose I start out with a raw string of utf-8 code points. "utf-8 code points"??? Looks like a utf-8 encoded string, and then written in hex format. > raw_string = "68656E727963" > > I can coerce it into proper unicode format by slicing out two > characters at a time. > > unicode_string = u"\x68\x65\x6E\x72\x79\x63" > > >>> print unicode_proper > >>> henry > > My question: is there an existing function that can do this (without > having to manually slicing the raw text string)? Two steps: first decode from hex to string, and then from utf8 string to unicode: py> raw_string = "68656E727963" py> raw_string.decode("hex") 'henryc' py> raw_string.decode("hex").decode("utf8") u'henryc' -- Gabriel Genellina From paul.hankin at gmail.com Wed Mar 12 07:26:33 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 12 Mar 2008 04:26:33 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> Message-ID: <7e9ceea4-566e-49ee-91dd-0a7b1d8f05ee@s50g2000hsb.googlegroups.com> On Mar 12, 10:26 am, Larry wrote: > I'm new to Python. I have a file (an image file actually) that I need > to read pixel by pixel. It's an 8-bit integer type. I need to get the > statistics like mean, standard deviation, etc., which I know a little > bit already from reading numpy module. What I want to know is how to > get the number of occurences of numeric element in an array. Say, Something like this should do the job: histogram = [0] * 256 for x in my_array: histogram[x] += 1 -- Paul Hankin From bruno.desthuilliers at gmail.com Sun Mar 9 09:16:51 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 9 Mar 2008 06:16:51 -0700 (PDT) Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> Message-ID: <77f498b3-13f8-403d-9b9f-a3d86fdc2b8e@z17g2000hsg.googlegroups.com> On 8 mar, 20:49, "Bryan.Fodn... at gmail.com" wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). It's obviously an XML file, so use a XML parser - there are SAX and DOM parsers in the stdlib, as well as the ElementTree module. From pavlovevidence at gmail.com Thu Mar 13 12:21:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Mar 2008 09:21:56 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> Message-ID: On Mar 13, 7:02 am, Bruno Desthuilliers wrote: > Alex a ?crit : > (sni) > > > First of all thanks all for answering! > > > I have some environment check and setup in the beginning of the code. > > I would like to move it to the end of the script. > > Why ? (if I may ask...) > > > But I want it to > > execute first, so the script will exit if the environment is not > > configured properly. > > If you want some code to execute first when the script/module is loaded, > then keep this code where it belongs : at the beginning of the script. I concur with Bruno's recommendation: stuff you want to do first should come first in the script. Things like BEGIN blocks hurt readability because you can't identify where execution begins without reading the whole file. Having said that, one thing that often happens in Python scripts is that all the functions are defined first, then the script logic follows. So you could put the meat of your script in a function, then the "BEGIN" stuff after that functions: def run_script(): # # script contained in this long function # # Then test preconditions here... if os.environ["HELLO"] != "WORLD": sys.exit(2) # Then call the run_script functions run_script() But having said THAT, I don't recommend you do that with preconditions. If the script has a quick early exit scenario, you really ought to put that near the top, before the function definitions, to clearly show to a human reader what is necessary to run the script. Carl Banks From donn at u.washington.edu Thu Mar 20 15:38:49 2008 From: donn at u.washington.edu (Donn Cave) Date: Thu, 20 Mar 2008 12:38:49 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> <7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: In article <7xskynm4m8.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: ... > I think it's easier to write complex code in Haskell because: > > 1) it has a powerful static type system that lets you express > important invariants and have them enforced at compile time. This not > only catches errors but helps you understand the program logic almost > like running the code under a debugger does. If you try to fill a gap > by putting in a piece of the wrong shape, it just won't fit and the > compiler will tell you what you really wanted. On the other hand, > most types are inferred by the compiler, so you don't need a lot of > cumbersome declarations like in Java. Worth repeating. One of the perhaps surprising consequences, Haskell code can be very easy to modify. I've been fooling around with computer programs for a couple decades, and I'm just getting used to the idea that I can casually rewrite Haskell code and get the compiler to find what I missed. I have come to feel that the indiscipline of dynamic typing in languages like Python leads to an intuitively surprising rigidity. Ten years ago I would cheerfully accept this, given the meager and clumsy support for static typing in languages like C++, but today, it makes me appreciate Haskell's potential for complex projects. Donn Cave, donn at u.washington.edu From mail at timgolden.me.uk Fri Mar 14 08:03:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 14 Mar 2008 12:03:56 +0000 Subject: Spaces in path name In-Reply-To: References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: <47DA69AC.60507@timgolden.me.uk> David S wrote: > Gets me further but still seems to be issue with space after 'Program' as > code tries to run 'C:\Program'. Don't understand what is going on here... Slight apologies as I haven't followed this thread closely, but using the Acrobat Reader executable, which is, I think, good enough for the purposes of illustration: import os import subprocess filename = r"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe" doc = r"C:\Program Files\Adobe\Reader 8.0\Resource\ENUtxt.pdf" print os.path.isfile (filename) os.system (filename + " " + doc) os.system ('"%s" "%s"' % (filename, doc)) subprocess.call ([filename, doc]) os.path.isfile succeeds os.system (filename) fails as your code does os.system ('"%s"' ...) fails even though both strings are requoted subprocess.call (filename) succeeds The latter, at least, is because the subprocess module has some special-case handling for exactly this situation on MS Windows, while os.system doesn't. Now, ultimately, I don't know if this really helps your exact situation but it least it should be clear what will and what won't work. Conclusion: use subprocess.call if you can. TJG From carsten at uniqsys.com Tue Mar 18 05:04:59 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 18 Mar 2008 10:04:59 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom In-Reply-To: <47DF7803.1070902@mydeskfriend.com> References: <47DF7803.1070902@mydeskfriend.com> Message-ID: <1205831099.3212.18.camel@localhost.localdomain> On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > Hello, > > I am reading core python python programming and it talks about using the > idiom > described on > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . > > I'm using python 2.5.1 and if I try : > > class MyClass(object): > def __init__(self): > self._foo = "foo" > self._bar = "bar" > > @property > def foo(): > doc = "property foo's doc string" > def fget(self): > return self._foo > def fset(self, value): > self._foo = value > def fdel(self): > del self._foo > return locals() # credit: David Niergarth > > @property > def bar(): > doc = "bar is readonly" > def fget(self): > return self._bar > return locals() > > like suggested in the book (the decorator usage) I get this : > > >>> a=MyClass() > >>> a.foo > Traceback (most recent call last): > File "", line 1, in > TypeError: foo() takes no arguments (1 given) > > but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : > > >>> a = MyClass() > >>> a.foo > 'foo' > > does anyone have an idea as of why this is happening? You're mixing two completely different approaches of building a property. If that code is actually in the book like that, that's a typo that you should mention to the author. The @property decorator can only be used to turn a single getter function into a read-only attribute, because this: @property def foo(...): ... is the same as this: def foo(...): ... foo = property(foo) and calling property() with one argument builds a property that has just a getter function that is the single argument you're giving it. The recipe you're referring to uses a magical function that returns a dictionary of getter function, setter function, deleter function, and docstring, with suitable key names so that the dictionary can be passed as a keyword argument dictionary into the property() constructor. However, that requires the magical foo=property(**foo()) invocation, not the regular decorator invocation foo=property(foo). HTH, -- Carsten Haese http://informixdb.sourceforge.net From luismgz at gmail.com Thu Mar 6 16:17:21 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Thu, 6 Mar 2008 13:17:21 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: On 6 mar, 11:27, Pierre Quentel wrote: > Hi, > > I would like to know if there is a module that converts a string to a > value of the "most probable type" ; for instance : > - if the string is "abcd" the value is the same string "abcd" > - string "123" : value = the integer 123 > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > = the float -1.23 > - string "2008/03/06" (the format is also locale-dependant) : value = > datetime.date(2008,03,06) > > Like in spreadsheets, special prefixes could be used to force the > type : for instance '123 would be converted to the *string* "123" > instead of the *integer* 123 > > I could code it myself, but this wheel is probably already invented > > Regards, > Pierre >>> def convert(x): if '.' in x: try: return float(x) except ValueError: return x else: try: return int(x) except: return x >>> convert('123') 123 >>> convert('123.99') 123.98999999999999 >>> convert('hello') 'hello' From kgmuller at xs4all.nl Wed Mar 19 08:53:14 2008 From: kgmuller at xs4all.nl (kgmuller) Date: Wed, 19 Mar 2008 13:53:14 +0100 Subject: EuroSciPy 2008 Conference - Leipzig, Germany In-Reply-To: <1FA8105E-095B-4610-ABE8-57EE9D711AE4@enthought.com> Message-ID: <200803191253.m2JCrKSb091688@smtp-vbr3.xs4all.nl> Travis, A great initiative! I will attend and will submit an abstract of a presentation on SimPy (Simulation in Python) and how this project will be brought closer to SciPy. Any idea where in Leipzig the conference will be held? I want to book a hotel in the vicinity of the conference site. Klaus M?ller > -----Original Message----- > From: Travis Vaught [mailto:travis at enthought.com] > Sent: Wednesday, March 12, 2008 4:36 PM > To: Scipy-Dev at Scipy. Org; scipy-user at scipy.org; > python-announce at python.org; Discussion of Numerical Python; > ipython-dev at scipy.org; > mayavi-users-request at lists.sourceforge.net; > matplotlib-announce at lists.sourceforge.net; > ctypes-users at lists.sourceforge.net > Subject: ANN: EuroSciPy 2008 Conference - Leipzig, Germany > > Greetings, > > We're pleased to announce the EuroSciPy 2008 Conference to be > held in Leipzig, Germany on July 26-27, 2008. > > http://www.scipy.org/EuroSciPy2008 > > We are very excited to create a venue for the European > community of users of the Python programming language in > science. This conference will bring the presentations and > collaboration that we've enjoyed at Caltech each year closer > to home for many users of SciPy, NumPy and Python > generally--with a similar focus and schedule. > > > Call for Participation: > ---------------------- > If you are a scientist using Python for your computational > work, we'd love to have you formally present your results, > methods or experiences. To apply to present a talk at this > year's EuroSciPy, please submit an abstract of your talk as a > PDF, MS Word or plain text file to euroabstracts at scipy.org. > The deadline for abstract submission is April 30, 2008. > Papers and/or presentation slides are acceptable and are due > by June 15, 2008. Presentations will be allotted 30 minutes. > > > Registration: > ------------ > Registration will open April 1, 2008. The registration fee > will be 100.00? for early registrants and will increase to > 150.00? for late registration. Registration will include > breakfast, snacks and lunch for Saturday and Sunday. > > > Volunteers Welcome: > ------------------ > If you're interested in volunteering to help organize things, > please email us at info at scipy.org. > > > > > > > > > From stefan_ml at behnel.de Mon Mar 10 11:09:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 16:09:05 +0100 Subject: Quality assurance in Python projects containing C modules In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> Message-ID: <47D54F11.4020508@behnel.de> Duncan Booth wrote: > NoelByron at gmx.net wrote: >> We are thinking about writing a project for several customers in >> Python. This project would include (among others) wxPython, a C/C++ >> module. But what happens if this application generates a segmentation >> fault on a customers PC. What changes do we have to trace back the >> source of the error? Imagine you use two or three C libraries in a >> Python project and you experience random crashes in 'Python.exe'. What >> would you do? >> > I would start by ensuring that any DLLs you write are written using Pyrex > or Cython: almost always problems with C libraries called from Python are > due to faulty reference counting but if you keep all of your Python related > code in Pyrex/Cython modules the reference counting problem should be taken > care of for you. You can call any required C/C++ code from the Cython code. I think the OP meant to use wxPython as an external module, in which case he has no way of influencing the language it is implemented in. My personal experience with wxPython has its ups and downs. Specifically when it comes to crashes, I wouldn't bet my life on it. (but then, the OP aims for using Windows anyway, so maybe there are ways to hide the crash of wxPython behind a full-fledged system crash to avoid being blamed...) Stefan From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 09:26:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 13:26:26 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: <13ufb02heg16d44@corp.supernews.com> On Mon, 24 Mar 2008 04:33:53 -0400, Terry Reedy wrote: > The fact that .func_name (which is writeable) is not used at first > surprised me until I remembered that code objects can potentially be > used by multiple function objects and hence are not connected to any one > in particular. How does that happen? And if it is the case, what's the justification for giving them a co_name attribute? Surely the name of the function should be that of the function object, not of one of the shared parts? -- Steven From mensanator at aol.com Mon Mar 3 18:54:55 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 15:54:55 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> Message-ID: <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> On Mar 3, 4:08?pm, Robert Kern wrote: > Mensanator wrote: > > On Mar 3, 2:49 pm, Carl Banks wrote: > >> It's just a bug--probably sympy is messing with the internals of the > >> random number generator. ?It would be a simple fix. ?Instead of > >> b****ing about it, file a bug report. ? > > > I did. > > >> Or better yet, submit a patch. > > > I would if I knew what the problem was. > > Did you even try to figure it out? It took me all of 5 minutes to find the mistake. Could I trouble you to share? Then I could continue my testing. > > > I posted it here because someone recommended it. > > I'm simply un-recommending it. > > It was a mistake, an easily remedied mistake, But I didn't know that (and still don't). > not a big unchangeable design decision. I didn't know that either. For all I know, I might have to wait for the next version, and who knows when that will be? > If you want to recommend against sympy as a package, there is a larger > burden of proof that you have yet to meet. What kind of burden of proof must one have to recommend it in the first place? > > -- > 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 xkenneth at gmail.com Mon Mar 31 13:23:24 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 31 Mar 2008 10:23:24 -0700 (PDT) Subject: Newbie Question - Overloading == Message-ID: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> So i generally write quite a few classes, and in most I need to overload the == operator. If i have two classes, like below: Class A: attribute a attribute b Class B: attribute a attribute c So if I've overloaded their respective __eq__ functions, and I want to test whether or not the individual classes attributes are equal, the code might look something like this: class A: def __eq__(self,other): return self.a == other.a and self.b == other.b class B: def __eq__(self,other): return self.a == other.a and self.c == other.c Now obviously, if I test an instance of either class equal to each other, an attribute error will be thrown, how do I handle this? I could rewrite every __eq__ function and catch attribute errors, but that's tedious, and seemingly unpythonic. Also, I don't want an attribute error thrown whenever two classes are compared that don't have the same attributes. I have a sneaky feeling I'm doing something completely unpythonic here. Thanks! Regards, Kenneth Miller From andis59 at gmail.com Thu Mar 6 11:46:32 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Thu, 6 Mar 2008 17:46:32 +0100 Subject: List all files using FTP Message-ID: Hello, I need to list all the files on my FTP account (multiple subdirectories). I don't have shell access to the account. anyone that has a program that will do this? // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From fakeaddress at nowhere.org Tue Mar 18 23:08:11 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 19 Mar 2008 03:08:11 GMT Subject: finding items that occur more than once in a list In-Reply-To: <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Ninereeds wrote: >> Hrvoje Niksic wrote: >>> This doesn't apply to Python, which implements dict storage as an >>> open-addressed table and automatically (and exponentially) grows the >>> table when the number of entries approaches 2/3 of the table size. >>> Assuming a good hash function, filling the dict should yield amortized >>> constant time for individual additions. > > Isn't this average constant time rather than amortized? This is expected amortized constant time. Is that really the same thing as average constant time? Hmmm... that's subtle. >> OK. I obviously need to look up open-addressed tables. I thought this >> was just, in effect, implicit linked listing - ie it still needs a >> linear search to handle collisions, it just avoids the need for >> explicitly stored link fields. Perhaps I'm mistaken. The amortized doubling breaks that. > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > link to further details. Arnaud Delobelle offered a good Wikipedia link, and for more background look up "amortized analysis. -- --Bryan From tjreedy at udel.edu Tue Mar 18 22:11:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:11:37 -0400 Subject: Python 3 and PEP238 division References: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> Message-ID: "Ninereeds" wrote in message news:3b9c9176-101f-4c72-8a56-82d16aea48d5 at k13g2000hse.googlegroups.com... | On Mar 17, 7:26 pm, "Terry Reedy" wrote: | > "Ninereeds" wrote in message | > | > news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... | > | Is the PEP238 change to division going into Python 3 as planned? | > | > IDLE 3.0a3>>> 1/2 | > | > 0.5 | > | > | I realise that the new integer division semantics have been available | > | in "from __future__" for quite a few years now, but a warning might be | > | appropriate now that Python 3 is in alpha. | > | > 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion | > program | | The tools can work out the *intent* of any particular division | operator? Can work out whether the result should be integer or float, | independent of any particular set of arguments? Seems unlikely. where the conversion is not deterministic, the tool will either ask or point out the possible change or not. I have not used it, and it is still being developed -- and tested in use by developers. From joe.p.cool at googlemail.com Tue Mar 18 17:38:54 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Tue, 18 Mar 2008 14:38:54 -0700 (PDT) Subject: method to create class property References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> Message-ID: <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> On 18 Mrz., 21:59, "Diez B. Roggisch" wrote: > Joe P. Cool schrieb: > > ? ? def _property_y(self): > > ? ? ? ? def _get(self): > > ? ? ? ? ? ? [...] > > There are a few recipies, like this: > > class Foo(object): > > ? ? ?@apply > ? ? ?def foo(): > ? ? ? ? ?def fget(self): > ? ? ? ? ? ? ?return self._foo > ? ? ? ? ?def fset(self, value): > ? ? ? ? ? ? ?self._foo = value > ? ? ? ? ?return property(**locals()) This is really cool! Thanks, Diez! I should definitely learn to handle decorators :) But isnt't apply bound to be dropped in Python 3.0? From software at ginstrom.com Mon Mar 31 20:20:12 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 1 Apr 2008 09:20:12 +0900 Subject: Automatically fill in forms on line In-Reply-To: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> References: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> Message-ID: <01d401c8938e$2745e3f0$0203a8c0@MOUSE> > On Behalf Of Jackie Wang > I want to automatically complete the following task: > > 1. Go to http://www.ffiec.gov/Geocode/default.aspx; ... > > Can Python realize these steps? Can these steps be done > witout openning and IE windows? Especially, I dont know how > to write code for step 2, 4 and 5. I suggest looking at mechanize: http://wwwsearch.sourceforge.net/mechanize/ If you're going to do this frequently, you also might want to check out the site's policy on robots. Mechanize does have a function to automatically handle a site's robots.txt. Regards, Ryan Ginstrom From steve at REMOVE-THIS-cybersource.com.au Wed Mar 26 23:30:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 03:30:58 -0000 Subject: Why does python behave so? (removing list items) References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <13um57idbctec04@corp.supernews.com> On Wed, 26 Mar 2008 23:12:27 +0100, Thomas Dybdahl Ahle wrote: > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: >> Why does python create a reference here, not just copy the variable? > > Python, like most other oo languages, will always make references for =, > unless you work on native types (numbers and strings). *Including* numbers and strings. I don't know what you mean "native types". If you mean that numbers and strings are low-level bytes like you get in C, then you are mistaken, because EVERYTHING in Python is an object, including numbers and strings. -- Steven From python.list at tim.thechases.com Fri Mar 21 11:31:20 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 Mar 2008 10:31:20 -0500 Subject: beginners question about return value of re.split In-Reply-To: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <47E3D4C8.3060503@tim.thechases.com> > datum = "2008-03-14" > the_date = re.split('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', datum, 3) > print the_date > > Now the result that is printed is: > ['', '2008', '03', '14', ''] > > My question: what are the empty strings doing there in the beginning and > in the end ? Is this due to a faulty regular expression ? I think in this case, you just want the standard string .split() method: the_date = datum.split('-') which will return you ['2008', '03', '14'] The re.split() splits your string using your regexp as the way to find the divider. It finds emptiness before, emptiness after, and returns the tagged matches for each part. It would be similar to >>> s = ',' >>> s.split(',') ['', ''] only you get your tagged matches in there too. Or, if you need more precision in your matching (in your case, ensuring that they're digits, and with the right number of digits), you can do something like >>> r = re.compile('^([0-9]{4})-([0-9]{2})-([0-9]{2})$') >>> m = r.match(datum) >>> m.groups() ('2008', '03', '14') -tkc From castironpi at gmail.com Mon Mar 17 08:28:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 05:28:19 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: On Mar 17, 6:49?am, MartinRineh... at gmail.com wrote: > What are the considerations in choosing between: > > ? ?return [a, b, c] > > and > > ? ? return (a, b, c) # or return a, b, c > > Why is the immutable form the default? Using a house definition from some weeks ago, a tuple is a data structure such which cannot contain a refrence to itself. Can a single expression refer to itself ever? From jcd at sdf.lonestar.org Mon Mar 17 15:36:29 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 17 Mar 2008 14:36:29 -0500 Subject: Pycon disappointment In-Reply-To: References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: <1205782589.6419.14.camel@sohp-laptop> I just want to step in and offer my 2?. This is my first PyCon, and I agree that a lot of the Lightning talks seemed pretty useless. Overall though, I had a great experience at this conference. I learned a lot; I met a lot of cool people; and I got really excited about new ideas to bring back home. Django code lab was fantastic. Teach me Twisted was a fantastic, innovative, and effective way to teach a new technology. There was a little bit of difficulty hearing over the cross-talk, but I just moved up front and had no further troubles (and better access to the Balvenie single-malt! Most of the sessions I attended were moderately to highly useful. FWIW, none of my presenters had laptop troubles, except at teach me twisted, but we weren't on as much of a time crunch, and we took care of that one pretty easily and kept going. The only useless one I attended was actually the most highly technical, not because it didn't have good information, but because functions were used without reference to what module they had been imported from and slides containing 15-20 line functions were left up for about thirty seconds, and then were gone. I couldn't even finish reading them. Note to speakers: do not say x, y = tee(foo) say from itertools import tee x, y = tee(foo) or better (for pedagogical purposes) import itertools x, y = itertools.tee(foo) I don't disagree with the criticisms leveled throughout this thread, but I do want to say that I think it has been a great conference, and for me, the problems did not ruin the experience. Heed these criticisms and it will be even better next year. Ignore them, and it will probably degrade over time. Thanks, Cliff From mail at hellmutweber.de Tue Mar 4 07:09:52 2008 From: mail at hellmutweber.de (Hellmut Weber) Date: Tue, 04 Mar 2008 13:09:52 +0100 Subject: Eurosymbol in xml document Message-ID: <47CD3C10.8010406@hellmutweber.de> Hi, i'm new here in this list. i'm developing a little program using an xml document. So far it's easy going, but when parsing an xml document which contains the EURO symbol ('?') then I get an error: UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in position 11834: character maps to the relevant piece of code is: from xml.dom.minidom import Document, parse, parseString ... doc = parse(inFIleName) leo at brunello usexml $ locale LANG=de_DE at euro LC_CTYPE="de_DE at euro" LC_NUMERIC="de_DE at euro" LC_TIME="de_DE at euro" LC_COLLATE="de_DE at euro" LC_MONETARY="de_DE at euro" LC_MESSAGES="de_DE at euro" LC_PAPER="de_DE at euro" LC_NAME="de_DE at euro" LC_ADDRESS="de_DE at euro" LC_TELEPHONE="de_DE at euro" LC_MEASUREMENT="de_DE at euro" LC_IDENTIFICATION="de_DE at euro" LC_ALL=de_DE at euro any help appreciated Hellmut -- Dr. Hellmut Weber mail at hellmutweber.de Degenfeldstra?e 2 tel +49-89-3081172 D-80803 M?nchen-Schwabing mobil +49-172-8450321 please: No DOCs, no PPTs. why: tinyurl.com/cbgq From erikwickstrom at gmail.com Tue Mar 18 09:08:49 2008 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 18 Mar 2008 06:08:49 -0700 (PDT) Subject: Merging a patch/diff generated by difflib? Message-ID: <605b7f04-6306-4ac5-9633-7765a2e71060@k13g2000hse.googlegroups.com> Hi, I'm trying to create an undo/redo feature for a webapp I'm working on (django based). I'd like to have an undo/redo function. My first thought was to use the difflib to generate a diff to serve as the "backup", and then if someone wants to undo their operation, the diff could just be merged/patched with the current text. However, I've not be able to find a patch library. Are there any libraries that will handle merging the diff back into the text? Thanks! From brianlong at cox.net Mon Mar 24 11:34:15 2008 From: brianlong at cox.net (brianrpsgt1) Date: Mon, 24 Mar 2008 08:34:15 -0700 (PDT) Subject: pythonweb and Leopard Message-ID: I am trying to create a simple web application that is written in python, using apache and mysql. It appears as though the python web modules have been installed, however, whenever I try to run a python script, it only displays the code in the browser. It is like the python code is not getting processed. I have tried this on a iMac (Intel) and a PowerBook G4, both running Leopard. Python Web Modules 0.5.3 Apache 2.2 Python 2.5 I am trying to run the python script from the default web directory on the Mac, /Library/WebServer/Documents I updated the httpd.conf for the to say Options +ExecCGI and AddHandler cgi-script .cgi .py I know that I am missing something simple. Any help would be great B From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 10:01:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 14:01:04 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> Message-ID: <13ufd10ps50mm4a@corp.supernews.com> On Mon, 24 Mar 2008 06:48:10 -0700, Arnaud Delobelle wrote: > On Mar 24, 1:26?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 24 Mar 2008 04:33:53 -0400, Terry Reedy wrote: >> > The fact that .func_name (which is writeable) is not used at first >> > surprised me until I remembered that code objects can potentially be >> > used by multiple function objects and hence are not connected to any >> > one in particular. >> >> How does that happen? > > Like this: > >>>> def foomaker(x): > ... def foo(y): return x+y > ... return foo > ... >>>> foo1 = foomaker(1) >>>> foo2 = foomaker(2) >>>> foo1.func_code > ", line 2> >>>> foo2.func_code > ", line 2> Ah, that makes sense. And obvious in hindsight. > Of course foo1 and foo2 are not the same thing: Naturally not. They are different functions. The fact that they share a small part (func_code) is irrelevant. There's more to a function than the code object. >> And if it is the case, what's the justification for giving them a >> co_name attribute? Surely the name of the function should be that of >> the function object, not of one of the shared parts? > >>>> foo1.__name__ > 'foo' >>>> foo1.func_code.co_name > 'foo' > > As seen above, func.__name__ and func.func_code.co_name are the same > thing (until tampered with). Yes, but what I'm asking is why the code objects have a co_name attribute. And even if there's a good reason for code objects to have a name, why do tracebacks use func.func_code.co_name instead of func.__name__? -- Steven From michael.wieher at gmail.com Wed Mar 26 14:45:01 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 26 Mar 2008 13:45:01 -0500 Subject: what does ^ do in python In-Reply-To: References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: On Wed, Mar 26, 2008 at 1:36 PM, Gabriel Genellina wrote: > En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson > escribi?: > > > HOw can we use express pointers as in C or python? > > File "english.py", line 345, in parse_sentence > raise ParserError, "can't parse %r" % sentence > ParserError: can't parse 'HOw can we use express pointers as in C or > python?' > >>>string = "How can we use express pointers as in C or python?" >>>import advancedParser >>>advancedParser.translate(string) LogicError: indication that we are not outside of python, recursive self-definition requested. (segmentation fault) all sarcasm aside if you actually meant to ask how to pass by value or pass by reference in Python, then the simple answer is don't worry about it, Python handle's things in a natural and intuitive way. If you have a specific question regarding python's handling of this concept, ask it, as some instances can be confusing and have gotchyas. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nomailplease at sonic.net Fri Mar 14 14:13:57 2008 From: nomailplease at sonic.net (Pacman) Date: 14 Mar 2008 18:13:57 GMT Subject: Monitoring SSHd and web servers? References: Message-ID: <47dac065$0$36409$742ec2ed@news.sonic.net> Gilles Ganault wrote: >I'd like to monitor connections to a remote SSH and web server. Does >someone have some code handy that would try to connect every 5mn, and >print an error if the script can't connect? This script has been pretty reliable for us for the past few years, much more reliable than the expect script it replaced. #!/usr/bin/python import sys import pexpect quiet = open("/dev/null", "rw") sys.stdin = quiet sys.stdout = quiet sys.stderr = quiet smtp = pexpect.spawn("telnet " + sys.argv[1] + " 25") smtp.expect('220', timeout=120) smtp.sendline("quit\n^]q") Pacman From gagsl-py2 at yahoo.com.ar Tue Mar 4 21:11:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 00:11:56 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: >> > So, to answer your question: what you are decorating are functions, >> not >> > methods. >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it >> is it makes it. > >>>> from types import FunctionType, MethodType >>>> class A( FunctionType ): pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: type 'function' is not an acceptable base type Use delegation instead of inheritance. This class is almost indistinguishable from a true function (when used as a method): py> class myfunction(object): ... __slots__ = ('func',) ... # ... def __init__(self, func): ... object.__setattr__(self, 'func', func) ... # ... def __get__(self, instance, owner): ... print "__get__ called for",instance ... return self.func.__get__(instance, owner) ... # ... def __getattr__(self, name): ... return getattr(self.func, name) ... # ... def __setattr__(self, name, value): ... object.__setattr__(self.func, name, value) ... py> py> class P(object): ... def foo(self, x): print 'foo',x ... # ... @myfunction ... def bar(self, x): print 'bar',x ... py> p = P() py> p.foo(1) foo 1 py> p.bar(2) __get__ called for <__main__.P object at 0x00A3D650> bar 2 py> P.foo(p, 1) foo 1 py> P.bar(p, 2) __get__ called for None bar 2 py> print "p.foo", p.foo, type(p.foo) p.foo > py> print "p.bar", p.bar, type(p.bar) p.bar __get__ called for <__main__.P object at 0x00A3D650> > __get__ called for <__ main__.P object at 0x00A3D650> py> print set(dir(p.foo))==set(dir(p.bar)) __get__ called for <__main__.P object at 0x00A3D650> True py> print "P.foo", P.foo, type(P.foo) P.foo py> print "P.bar", P.bar, type(P.bar) P.bar __get__ called for None __get__ called for None py> print set(dir(P.foo))==set(dir(P.bar)) __get__ called for None True py> P.__dict__['foo'] py> P.__dict__['bar'] <__main__.myfunction object at 0x00A3D690> Ok, let's try returning a different thing from __get__: bound method -> partial with self already bound; unbound method -> the original function. py> from functools import partial py> py> class myfunction2(myfunction): ... def __get__(self, instance, owner): ... if instance is None: ... return self.func ... return partial(self.func, instance) ... py> @myfunction2 ... def baz(self, x): print 'baz',x ... py> P.baz = baz py> print p.baz py> print P.baz py> p.baz(3) baz 3 py> P.baz(p,3) baz 3 -- Gabriel Genellina From castironpi at gmail.com Sat Mar 1 13:15:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 10:15:30 -0800 (PST) Subject: Beginner's assignment question References: Message-ID: On Mar 1, 10:07?am, Lorenzo Gatti wrote: > On Mar 1, 3:39 pm, Schizoid Man wrote: > > > As in variable assignment, not homework assignment! :) > > > I understand the first line but not the second of the following code: > > > a, b = 0, 1 > > a, b = b, a + b > > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > > However what is the sequence of operation in the second statement? I;m > > confused due to the inter-dependence of the variables. > > The expressions of the right of the assignment operator are evaluated > before assigning any new values, to the destinations on the left side > of the assignment operator. > So substitutig the old values of a and b the second assignment means > > a, b = 0, 0 + 1 > > Simplifying the Python Reference Manual ("6.3 Assignment Statements") > a little : > > assignment_stmt ::= target_list "="+ expression_list > > An assignment statement evaluates the expression list (remember that > this can be a single expression or a comma-separated list, the latter > yielding a tuple) and assigns the single resulting object to each of > the target lists, from left to right. > > [...] > > WARNING: Although the definition of assignment implies that overlaps > between the left-hand side and the right-hand side are `safe' (for > example "a, b = b, a" swaps two variables), overlaps within the > collection of assigned-to variables are not safe! For instance, the > following program prints "[0, 2]": > > x = [0, 1] > i = 0 > i, x[i] = 1, 2 > print x > > Lorenzo Gatti If you understand a, b, c= 1, 2, 3 Then a, b, c= 1, 2, 3+1 is the next step. About terminology, you might get some weird glances from the vets. if you say 'a assigned to 0', instead of '0 assigned to a'. Of course, it may be more opinion than some vet. natural language speakers realize, that is whether it's only convention or not, if one says 'I went to the store' instead of 'the store went to me'-- same picture, except (cf. relativity) how much force the store applied to travel-- which doesn't show up in every story problem anyway), hence Williams's term '0 is assigned to a', and don't forget, they're on side effects here, hence Gatti's warning. Put another way, the thing on the right 'evaluates' to something. There may be some 'agent-patient' confusion here.... but 'a' isn't really 'assigned' in any deep sense, though it is 'declared' -in- that statement too. 'The interpreter obtains space for a' (the space word is deep!, as in 'time-space trade-off') and 'The interpreter writes 0 in a's space' are both pretty literal. You can say, 'a is assigned the value 0', just not 'a is assigned -to- it.' From asmodai at in-nomine.org Thu Mar 6 14:20:17 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 6 Mar 2008 20:20:17 +0100 Subject: Better grammar.txt In-Reply-To: <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: <20080306192017.GK60713@nexus.in-nomine.org> -On [20080306 19:21], member thudfoo (thudfoo at opensuse.us) wrote: >An error occurred while loading >http://www.martinrinehart.com/articles/python-grammar.html: >Unknown host www.martinrinehart.com Works for me. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Possession is nine points of the law... From siddhantgoel at gmail.com Tue Mar 4 12:26:43 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Tue, 4 Mar 2008 09:26:43 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> <55f1c2b7-0f8f-4bcc-ac59-0b78a81cf81e@e31g2000hse.googlegroups.com> Message-ID: Yes. Almost what I wanted. Thanks. :) From dave_mikesell at fastmail.fm Wed Mar 19 10:59:07 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Wed, 19 Mar 2008 07:59:07 -0700 (PDT) Subject: SOAP Server in Python References: Message-ID: <50ccc1be-87ac-4847-b21d-7dfd46379ea4@z38g2000hsc.googlegroups.com> On Mar 19, 9:19?am, Eric wrote: > I am basically looking to do the same thing in Python as easily. > > Any help or pointers would be appreciated. Googling for "python soap" turned up a few hits that may help you. From michael.wieher at gmail.com Wed Mar 12 12:34:12 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 12 Mar 2008 11:34:12 -0500 Subject: Does __import__ require a module to have a .py suffix? In-Reply-To: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: 2008/3/12, mrstephengross : > > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? > > Thanks, > --Steve > > -- > http://mail.python.org/mailman/listinfo/python-list >>> m=__import__('foo') Traceback (most recent call last): File "", line 1, in ImportError: No module named foo >>> m=__import__('foo.py') Traceback (most recent call last): File "", line 1, in ImportError: No module named foo.py >>> michael at majw-m65:~/Code/Scratch$ ls foo michael at majw-m65:~/Code/Scratch$ -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Sat Mar 8 18:31:55 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 Mar 2008 17:31:55 -0600 Subject: Arbitrary precision integer arithmetic: ceiling? In-Reply-To: References: Message-ID: Alasdair wrote: > I need to apply the ceiling function to arbitrary sized (long) integers. > However, division automatically returns the type of its operands, so that, > for example: math.ceil(7/4) returns 1. I can use float, as in: > math.ceil(7/float(4)), except that for very large integers float causes an > unacceptable loss of precision. > > What is the best way of finding a ceiling of a quotient of arbitrary sized > integers? Use divmod() to get the quotient and the remainder at the same time. Add 1 to the quotient if and only the remainder is greater than 0. In [11]: def qceil(x, y): ....: """ Find the ceiling of a quotient x/y. ....: ....: This is especially useful for very large Python long integers. ....: """ ....: q, r = divmod(x, y) ....: if r > 0: ....: q += 1 ....: return q ....: In [13]: qceil(7, 4) Out[13]: 2 In [14]: qceil(8, 4) Out[14]: 2 In [15]: qceil(9, 4) Out[15]: 3 In [16]: qceil(100000000000000000000000003, 10) Out[16]: 10000000000000000000000001L -- 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 waldemar.osuch at gmail.com Wed Mar 26 18:15:21 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 26 Mar 2008 15:15:21 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: Message-ID: On Mar 26, 4:04 pm, "Micha? Bentkowski" wrote: > Why does python create a reference here, not just copy the variable? > > >>> j=range(0,6) > >>> k=j > >>> del j[0] > >>> j > [1, 2, 3, 4, 5] > >>> k > > [1, 2, 3, 4, 5] > > Shouldn't k remain the same? http://www.effbot.org/zone/python-list.htm From webhorst at gmail.com Sun Mar 23 13:48:30 2008 From: webhorst at gmail.com (Bill Horst) Date: Sun, 23 Mar 2008 11:48:30 -0600 Subject: Finding Will Ware Message-ID: I am looking for Will Ware, but his website (willware.net) is not responding, so I'm guessing at a email addresses for him. Please let me know where he can be reached. (Will, this is regarding Sue Bauter, who was a close friend of mine at ISU in '72. Please reply so I can correspond with you about Sue and the news about her on your website.) Thank you -- Bill Horst (webhorst at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jameswhetstone at comcast.net Mon Mar 17 12:40:36 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Mon, 17 Mar 2008 09:40:36 -0700 Subject: Missing PyObject definition References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: <-eidnZbyjq-bAkPanZ2dnUVZ_rOqnZ2d@comcast.com> Hi, Yeah, I've included python.h and object.h but the compiler still complain about not finding PyObject. It's weird. So I'm developing and App on windows using VS 8.0. I've intalled Python 2.5 and have added the include directory to my project's configuration. I'm also using boost.python in another application to wrap my C++ classes. Here's the C++ class I'm wrapping: class widget { public: widget(const string &name, unsigned int myint) : { } static unsigned int __stdcall Callback(void * voidPtr); void startMessageHandler(); void stopMessageHandler(); virtual void handleMessage(void *message)=0; }; So the idea here is that the Python user will derive from widget and override the virtual method "handleMessage". A thread is spawned by "startMessageHandler()" that does some work and periodically calls "handleMessage" passing it a chunk of memory. This memory is intended to be zero-copy. Okay, so I've implemeted this class to set up the class for Python: class py_widget : public widget { public: py_widget(PyObject *p, const string &name, unsigned int myint) : self(p), py_widget(name, myint) { } void handleMessage(void *message); PyObject *self; }; where handleMessage has the following implementation: void PyAsyncQueue::handleMessage(void *message) { //get the memory block size with a method not shown here int size = getSize(message); //create a buffer object so the Python users can access memory block directly. PyObject *obj = PyBuffer_FromReadWriteMemory( message, size ) ; //now what ???? //I've tried calling the method directly based on some info I found some documentation, but this doesn't //compile because the compile can't find PyObject. Also, I really know what it looks like anyways. //self->attr("handleMessage")(obj); //This boost.python call doesn't work either. //call_method(self, "handleMessage", obj); } Thanks for your suggestions on this, James "Jeff Schwab" wrote in message news:mvadnfg_hOdmDEPanZ2dnUVZ_u2mnZ2d at comcast.com... > James Whetstone wrote: >> I'm trying to access a PyObject directly from C++ for the purpose of >> calling method on a Python object that is an intance of a derived C++ >> class. My problem is that the compiler is complaining about not PyObject >> not being defined. Has anyone run into the problem? Where is PyObject >> defined? > > Are you using Python's C API? > > Did you #include "Python.h" before using PyObject? > > PyObject is a C-style struct defined in object.h, which is in turn > included by Python.h. Does your compiler know where to look for those > headers? If you are getting messages of the form "error: cannot find > Python.h," then add -Iyour_python_root/include/python2.5 (or whatever > version) to the CXXFLAGS variable in your makefile, or to your compiler's > command line. From tjreedy at udel.edu Thu Mar 20 22:42:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Mar 2008 22:42:49 -0400 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0] References: <7xy78dg79e.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xy78dg79e.fsf at ruckus.brouhaha.com... | "Daniel Fetchinson" writes: | > Is it just me or others also think that it would be a major loss to | > remove tkinter from the python core? | | That would be terrible. Every time I've tried to use one of the other | packages it has led to installation hell. Tkinter isn't great, but | it's extremely useful to have a gui module that's present | automatically in every compete Python installation and that is | reasonably cross platform. I can write a Python/Tkinter app under | Linux and send it to Windows users and they can run it after a single, | very simple Python installation from the Windows .msi. I have no | Windows development tools whatsoever and very limited access to | Windows boxes, so any Python code I deploy on Windows can't rely on | any non-Python code outside of the stdlib. | | Also, because of tkinter's inherent limitations, I have the impression | that upgrading it to the latest and greatest tcl/tk release wouldn't | improve it much over the useful but low-rent module that it already is. | Therefore, that supposed "benefit" of splitting it out to an external | package is not much of a benefit. | | One of Python's traditionally best attractions has been the depth of | its standard libraries, and backing away from that would be plain | self-destructive. Python needs more stuff in its stdlib, not less. | If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard | distro. If that happens (i.e. some new toolkit is brought in and | declared to be the standard) then it might be ok to drop Tkinter but | it certainly shouldn't be dropped without a replacement. I think this nicely summarizes the case against dropping tkinter (and indeed, the case against shrinking the stdlib), like some devs (who mostly une *nix) want to do. Perhaps someone can forward it to the lib-sig and/or the Py3-devel lists. tjr From nothanks at null.invalid Sat Mar 22 23:26:15 2008 From: nothanks at null.invalid (Bill) Date: Sat, 22 Mar 2008 23:26:15 -0400 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <47E5CDD7.8040708@null.invalid> sturlamolden wrote, On 3/20/2008 9:41 AM: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > What don't you like about wxGlade? It actually generates Python code. There has been a lot more development going on recently, too. Bill From cosmo_general at yahoo.com Sat Mar 8 23:42:38 2008 From: cosmo_general at yahoo.com (cosmo_general at yahoo.com) Date: Sat, 8 Mar 2008 20:42:38 -0800 (PST) Subject: Python installation problem Message-ID: Hi Folks, I downloaded a pre-compiled version 2.5, and intalled it without any error message; and I can command line playing on Python through firing up IDLE or command-line. However, I just can't compile the python file existing in a directory. Today, I tried to fire Python in a DOS window, then I got error message: Python is not a runnable command or batch file. It means that the eveiornment variables of my Python interpreter are not set well yet. My computer runs a Windows XP. Anyboy can help on this? Thanks! Muddy Coder From tjreedy at udel.edu Sat Mar 15 15:41:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Mar 2008 15:41:32 -0400 Subject: string literal or NoneType References: Message-ID: wrote in message news:b2d5cbd3-b207-4c46-89ef-75ae101752ca at e6g2000prf.googlegroups.com... | hi all | i want to check a condition and if true should return a filename | string from a list.if the condition is false i am returning a | "" (string literal).. | | retv="" | if somecondition: | retv=mylist[x] | ... | return retv | | | The calling function will check the return value and print the | filename if it is not """. | in the calling function i can code | if returnval !="": | print "filename is:",returnval | else: | print "no filename found" | | what i want to know is ,should i rewrite the if returnval !="" as | | if returnval: | print "filename is:",returnval | else: | print "no filename found" In this situation, where returnval must be a string, the two are equivalent. So I consider the shorter, more efficient form stylistically better. In situations where various null or non-null conditions are not equivalent, one should use the one that is correct for the situation. | or is the way i coded the right way ? i am little confused here | Someone suggested that i make a variable retv None and if the | condition true then set retv as filename , | | retv=None | if somecondition: | retv=mylist[x] | | ... | return retv | | which approach is correct..? As long as the function returns are documented and the behavior matches the documentation and the calling code matched the behavior, both are 'correct'. I see this as stylistic preference. I can think of situations where a null string might be more useful that None, so I might go with that. Others might think of situations where a None return might be better. But a function cannot satisfy all possible callers ;-) (The is one problem with writing library code.) Terry Jan Reedy From bj_666 at gmx.net Mon Mar 31 02:54:29 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 06:54:29 GMT Subject: standard input, for s in f, and buffering References: Message-ID: <65bg55F2esfc1U3@mid.uni-berlin.de> On Sun, 30 Mar 2008 21:02:44 +0000, Jorgen Grahn wrote: > I realize this has to do with the extra read-ahead buffering documented for > file.next() and that I can work around it by using file.readline() > instead. > > The problem is, "for s in f" is the elegant way of reading files line > by line. With readline(), I need a much uglier loop. I cannot find a > better one than this: > > while 1: > s = sys.stdin.readline() > if not s: break > print '####', s , > > And also, "for s in f" works on any iterator f -- so I have to choose > between two evils: an ugly, non-idiomatic and limiting loop, or one > which works well until it is used interactively. > > Is there a way around this? Or are the savings in execution time or > I/O so large that everyone is willing to tolerate this bug? You can use ``for line in lines:`` and pass ``iter(sys.stdin.readline, '')`` as iterable for `lines`. Ciao, Marc 'BlackJack' Rintsch From clodoaldo.pinto at gmail.com Fri Mar 28 12:22:06 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Fri, 28 Mar 2008 09:22:06 -0700 (PDT) Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> Message-ID: <37d6b141-5ba0-4178-b45a-512e59433803@s12g2000prg.googlegroups.com> On Mar 28, 12:09 pm, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo > escribi?: > > > > > I'm using a md5 hash encoded with base64.urlsafe_b64encode as a > > parameter of a URL used to confirm a registration in a site. It has > > been working great. > > > The url is like this: > > >http://example.com/ce?i=878&h=kTfWSUaby5sBu9bIfoR87Q== > > > Now i need to match that URL in a certain text and i realized that > > urlsafe_b64encode uses the "=" character so i can't just use \w{24} to > > match the parameter. > > > What i need to know is where can an equal char appear in a > > urlsafe_b64encoded string?: > > > a)only at end; > > b)both at the end and at the begginig; > > c)anywhere in the string; > > > A sure answer will make my regexp safer. > > Only at the end. The encoded string has 4*n chars when the input string > has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has > 4*(n+1) chars right padded with 2 or 1 "=" chars. > If your input has 3n chars, the output won't have any "=" Thanks. But I'm not sure i get it. What is n? A md5 digest will always be 16 bytes length. So if i understand it correctly (not sure) the output will always be 22 chars plus two trailing equal chars. Right? Regards, Clodoaldo Pinto Neto From stefan_ml at behnel.de Mon Mar 10 15:15:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 20:15:19 +0100 Subject: Quality assurance in Python projects containing C modules In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <47D588C7.9070804@behnel.de> Duncan Booth wrote: > Stefan Behnel wrote: >> Duncan Booth wrote: >>> I would start by ensuring that any DLLs you write are written using >>> Pyrex or Cython: almost always problems with C libraries called from >>> Python are due to faulty reference counting but if you keep all of >>> your Python related code in Pyrex/Cython modules the reference >>> counting problem should be taken care of for you. You can call any >>> required C/C++ code from the Cython code. >> I think the OP meant to use wxPython as an external module, in which >> case he has no way of influencing the language it is implemented in. > > The OP mentioned 'two or three C libraries', so I assume wxPython is only > part of the story. Ah, sorry, I missed that. Sure, if it's about integrating C/C++ libraries as Python modules, then I second the recommendation of using Cython. Stefan From arnodel at googlemail.com Mon Mar 24 19:26:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Mar 2008 16:26:34 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: <5f07b190-053b-451f-8342-8298fb02c130@i29g2000prf.googlegroups.com> On Mar 24, 10:05?pm, Julien wrote: > Hi all, and thanks a lot for your answers! > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making > up the term) a function: > > def hijacker(arg): > ? ? if I_feel_its_necessary: > ? ? ? ? hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > ? ? hijacker(something) > ? ? ... # Continue as normal > ? ? return 2 > > def my_function2(arg): > ? ? ... # Maybe do some processing here > ? ? hijacker(whatever) > ? ? ... # Continue as normal > ? ? return 3 > > I have some long functions like my_function1 and my_function2 which > I'd like to alter, but I want to keep the alterations as little as as > possible. I'd like the extra behaviour to be handled by 'hijacker' and > let it decide what the caller function should return. Just adding a > call to 'hijacker' in all of these functions would be ideal for me > because that would be quick to modify them and also easier to > maintain, I believe. > > If 'hijacker' thinks it's necessary, it would force the caller > function to return a certain > value, otherwise it would let the caller function do its normal > business. > > For while I thought I'd make hijacker a decorator: > > @hijacker > def my_function(request): > .... > > But that wouldn't work, since some functions need to do some > processing before calling the hijacker. Yet, I think a decorator is > systematically called before the function itself so no prior > processing can be done by the function... > > Any idea on how to do that, if that's even possible? Of course it's possible ;), with the combination of an exception and a decorator. See example below. However I would seriously doubt the maintainability of such practices... # --------- hijack.py ------------ from functools import wraps class HijackReturn(Exception): def __init__(self, val): self.val = val def hijack(f): @wraps(f) def hijacked(*args, **kwargs): try: return f(*args, **kwargs) except HijackReturn, e: return e.val return hijacked @hijack def foo(x): x = x + 1 hijacker(x) return x * 2 def hijacker(x): if x == 21: print "[Oh no, it's going to be 42!]" raise HijackReturn(41) # ------------------------------- marigold:junk arno$ python -i hijack.py >>> foo(10) 22 >>> foo(20) [Oh no, it's going to be 42!] 41 >>> HTH -- Arnaud From hniksic at xemacs.org Wed Mar 26 05:02:09 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 26 Mar 2008 10:02:09 +0100 Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: <87myolc0z2.fsf@mulj.homelinux.net> blackpawn writes: > I know the garbage collector is tracking the object because it > properly calls the traverse function but for whatever reason it > never calls the clear function. Does anyone have experience with > circular references and had success with it or the example in the > docs? I've now tried it, and it seems to work. Modifying Nody_dealloc with printf("collecting %p\n", self), it works like this: >>> import noddy4 >>> n = noddy4.Noddy() >>> n.first = n >>> del n # n would be dealloced here without the cycle >>> ^D collecting 0xb7d3bf2c So the garbage-collector is invoked at least once before shutdown. However, it doesn't work without "del n" line, so it would appear that the gc is not invoked after the module cleanup and therefore doesn't explicitly dealloc global objects that contain cycles. You can work around that by using the atexit module to register a cleanup function that removes your global objects from the module namespace(s) and, if necessary, invokes gc.collect() manually. That way your objects end up as reclaimable garbage. This won't work if your cycle-containing objects are indirectly reachable from the module namespace through other containers not under your control. In that case, you should really rethink your strategy of depending on finalizers to run and perhaps use atexit to do your exit processing or, as others pointed out, use scope tools (try/finally, with) at the entry point of your code. From noname9968 at gmail.com Wed Mar 26 05:23:16 2008 From: noname9968 at gmail.com (Alex9968) Date: Wed, 26 Mar 2008 12:23:16 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative Message-ID: <47EA1604.4070905@gmail.com> Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) Could anyone with experience in different toolkits help, please Thanks From michael.wieher at gmail.com Fri Mar 7 17:38:24 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 16:38:24 -0600 Subject: os.chdir In-Reply-To: References: Message-ID: 2008/3/7, Maryam Saeedi : > > I have a problem using os.chdir on linux. What should I do if I want to > change to root directory? The below does not work: > > os.chdir("~/dir1") > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > >>> os.getcwd() '/home/michael' >>> os.chdir("/home/") >>> os.getcwd() '/home I guess just be sure your user account has rights to the directory you're trying to change to and don't screw up the quotes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Thu Mar 20 11:44:07 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 08:44:07 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: References: <13u50796m76e9c7@corp.supernews.com> Message-ID: <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> jmDesktop wrote: > On Mar 20, 11:21 am, Grant Edwards wrote: >> On 2008-03-20, jmDesktop wrote: >> >>> Hi, I'm trying to learn Python. I using Aquamac an emac >>> implementation with mac os x. I have a program. If I go to the >>> command prompt and type pythong myprog.py, it works. Can the program >>> be run from within the editor or is that not how development is done? >>> I ask because I was using Visual Studio with C# and, if you're >>> familiar, you just hit run and it works. On Python do I use the >>> editor for editing only and then run the program from the command >>> line? Sort of. Modern editors generally have support for building and running your program directly from a toolbar button or textual command. I personally use Vim with the toolbar disabled, running in a Terminal, and run the program by first putting Vim in the background (^z). People writing code specific to Mac, but not necessarily all in Python, often use XCode. http://zovirl.com/2006/07/13/xcode-python/ In the Ruby community, Vim is the dominant choice, but a lot of Mac users swear by TextMate. http://macromates.com/ >> http://www.google.com/search?q=emacs+python > Gee. Thanks. I believe Grant was suggesting that Emacs often serves a similar purpose on Unix to what Visual Studio does on Windows, which seemed to be what you were asking. When asking about Mac OS X here, you are likely to get a lot of generic Unix responses. (Would it have been clearer if he had just said "emacs?") From deets at nospam.web.de Sun Mar 9 17:56:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 22:56:19 +0100 Subject: Logically/Selectively Sub Class? In-Reply-To: References: <63j3ltF282fssU1@mid.uni-berlin.de> Message-ID: <63j4o6F27lit6U1@mid.uni-berlin.de> xkenneth schrieb: > On Mar 9, 4:38 pm, "Diez B. Roggisch" wrote: >> xkenneth schrieb: >> >>> Might be a silly question, but is it possible to selectively subclass, >>> IE subclass is a supporting module is present and not otherwise. >> Yes, something like this should work >> >> class Foo(some, base, classes) >> pass >> >> if condition: >> Temp = Foo >> class Foo(Temp, otherclass): pass >> >> Alternatively, you can use the type-function to create classes explicit >> with a list of base-classes. >> >> However it smells after bad design... what's your actual usecase? >> >> Diez > > Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB > for a lot of my stuff now, and I need my objects to be persistent, > however there might be a case where my classes could be used in a non- > persistent manner. I'll just have ZODB as a requirement for my > package. Ah. Then this also might work try: from ZODB import Persistent except ImportError: class Persistent: pass Diez From stef.mientki at gmail.com Mon Mar 10 15:27:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 10 Mar 2008 20:27:39 +0100 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: <47D587F9.3050703@behnel.de> References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: <47D58BAB.5060705@gmail.com> Stefan Behnel wrote: > Malcolm Greene wrote: > >>> My personal experience with wxPython has its ups and downs. Specifically >>> when it comes to crashes, I wouldn't bet my life on it. >>> >> I'm new to Python and getting ready to build a small client based >> application intended to run on Windows and Linux. I was planning on using >> wxPython until I saw your comment above. >> > > Just to make this sound a bit less like FUD: my last experience with wxPython > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > in a project, which crashed a bit too often to do real work with it - and with > crashing I mean crashing Python, not just showing us its blank traceback. So > this was definitely a problem either in wxWindows or in wxPython. > > I have no idea how well it works today, but this has definitely forged my > opinion on wxPython. > > > I'm using wxPython for half a year now, and building quit a large / heavy GUI with it. And although it's not so easy as Delphi, it's certainly just as stable as Delphi. If you're talking about Boa, that's a completely different story, I tried it on 3 different machines, and couldn't get it working on any of them. I think Boa / Dabo / .. are basically good ideas to make programming wxPython more easy, and probably a lot of people invested a lot of their free time in the product with the best intentions, but unfortunately these programs are not ready for use by others (specially not for windows users). I'ld suggest that you download the wxPython demo (with interactive editor) and see for yourself. cheers, Stef From grante at visi.com Thu Mar 13 16:28:41 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 13 Mar 2008 20:28:41 -0000 Subject: This actually works. References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> Message-ID: <13tj3jpsj6tsc2c@corp.supernews.com> On 2008-03-13, troyj1978 at gmail.com wrote: > I couldn't believe it. Screw programming Python anymore! OMG, IT'S FREE MONEY! I guess you've got to give the wanker credit for actually mention Python programming. :) -- Grant From deets at nospam.web.de Sat Mar 1 12:54:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 18:54:24 +0100 Subject: SQLLITE In-Reply-To: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> References: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> Message-ID: <62tjigF24ui98U2@mid.uni-berlin.de> nexes schrieb: > Hello All, > I am having a minor problem when I try and do this: > c.execute("insert into [tblTranscripts] (MovieID,Transcript) > Values(" + movieID + ",'" + formatText + "');") (don't even bother > commenting of the sql style I know its bad form but this is a simple > script). Whenever I try and do the insert I get table not found, > however when I perform the sql through sqlite's command line program > (the sql is outputted via a print statement) it works fine. Any ideas? No, and without more context nobody will have. Does working with the table with other statments work, how do you connect the DB, are you sure you really use the same DB-file and so forth. Diez From cyberco at gmail.com Sun Mar 23 04:20:50 2008 From: cyberco at gmail.com (Berco Beute) Date: Sun, 23 Mar 2008 01:20:50 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 5:40 pm, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. Yes. The nice thing with Python is that you can start off with really simple examples and slowly build up the complexity along with the understanding of the students. There's no need to explain OO before the students can write their first 'Hello, world'. There's almost no limit to how 'shallow/deep' you can go with Python. 2B From barry at python.org Sat Mar 1 13:51:38 2008 From: barry at python.org (Barry Warsaw) Date: Sat, 1 Mar 2008 13:51:38 -0500 Subject: RELEASED Python 2.6a1 and 3.0a3 Message-ID: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I'm happy to announce the first alpha release of Python 2.6, and the third alpha release of Python 3.0. Python 2.6 is not only the next advancement in the Python 2 series, it is also a transitionary release, helping developers begin to prepare their code for Python 3.0. As such, many features are being backported from Python 3.0 to 2.6. It makes sense to release both versions in at the same time, the precedence for this having been set with the Python 1.6 and 2.0 releases. During the alpha testing cycle we will be releasing both versions in lockstep, on a monthly release cycle. The releases will happen on the last Friday of every month. If this schedule works well, we will continue releasing in lockstep during the beta program. See PEP 361 for schedule details: http://www.python.org/dev/peps/pep-0361/ Please note that these are alpha releases, and as such are not suitable for production environments. We continue to strive for a high degree of quality, but there are still some known problems and the feature sets have not been finalized. These alphas are being released to solicit feedback and hopefully discover bugs, as well as allowing you to determine how changes in 2.6 and 3.0 might impact you. If you find things broken or incorrect, please submit a bug report at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 web site: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ We are planning a number of additional alpha releases, with the final release schedule still to be determined. Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iQCVAwUBR8mlu3EjvBPtnXfVAQKePAQAgx6w9wztfJaSWkbKrbwur2U6t6o5aIY5 pyMa00CZWY06p8099BztcSjgp5rKrd6/9V7cJ0NP7NLZ+tz20uRfyI8uqoIYBIWC ibJay6SSnzgOQM3PRIJV/K/m0dVPPPVD1LDnoEvuu+cKUpV434yHdgWkMPswsxUd fLydrXABlOM= =l6aj -----END PGP SIGNATURE----- From bj_666 at gmx.net Thu Mar 6 15:57:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Mar 2008 20:57:46 GMT Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> Message-ID: <63b46aF26qudpU1@mid.uni-berlin.de> On Thu, 06 Mar 2008 11:06:50 -0800, castironpi wrote: > On Mar 6, 8:30?am, Carl Banks wrote: >> Anyway, the answer to what you are probably asking is No. ?Try this: >> >> >>>import module >> >>>c1 = module.Someclass >> >>>reload(module) >> >>>c2 = module.Someclass >> >>>c1 is c2 > > What about > >>>> o= object() >>>> b1= o.someattr >>>> reload( o ) >>>> b2= o.someattr >>>> b1 is b2 > > ? You are really a bit thick, a troll, or a bot. *plonk* Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Wed Mar 12 06:55:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 03:55:08 -0700 (PDT) Subject: sys.stdout assign to- bug Message-ID: <39b263ea-e6f0-41f0-b1e8-edcbea851275@13g2000hsb.googlegroups.com> I'm actually intimidated enough by a few tries I make to say something on Python-Ideas, that I thought I'd run this by youguys first. import sys class ThreadedOut: def __init__( self, old ): self._old= old def write( self, s ): self._old.write( s ) sys.stdout= ThreadedOut( sys.stdout ) >>> a >>> 0 0 Python 3.0a2 WinXP, on the console. 'a' is undeclared but error message isn't thrown. With 'sys.stdout= Thr...' commented: >>> a Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined >>> 0 0 But the docs say: stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument. What's the catch? From castironpi at gmail.com Tue Mar 4 13:45:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:45:40 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> Message-ID: <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> > > So, to answer your question: what you are decorating are functions, not > > methods. > > Can you overload -type-'s decision of what to 'bind'?... whenever it > is it makes it. >>> from types import FunctionType, MethodType >>> class A( FunctionType ): pass ... Traceback (most recent call last): File "", line 1, in TypeError: type 'function' is not an acceptable base type >>> class A( MethodType ): pass ... Traceback (most recent call last): File "", line 1, in TypeError: type 'method' is not an acceptable base type Unacceptable. From castironpi at gmail.com Fri Mar 21 02:34:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:34:41 -0700 (PDT) Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <13u353a51v9kp36@corp.supernews.com> Message-ID: <3c71c7c4-e2a4-4628-8004-8a54eccc8ce6@m3g2000hsc.googlegroups.com> On Mar 19, 5:32?pm, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote: > > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but calculate/ > > compare in UTC. > > What possible ambiguity is there? I agree. >>> D.datetime( 2008, 3, 23 ) datetime.datetime(2008, 3, 23, 0, 0) >>> a=_ >>> D.timedelta( minutes= 30, seconds= 80 ) datetime.timedelta(0, 1880) >>> b= _ >>> a+b datetime.datetime(2008, 3, 23, 0, 31, 20) >>> a+b-a datetime.timedelta(0, 1880) From quentel.pierre at wanadoo.fr Thu Mar 6 09:27:56 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Thu, 6 Mar 2008 06:27:56 -0800 (PST) Subject: Converting a string to the most probable type Message-ID: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Hi, I would like to know if there is a module that converts a string to a value of the "most probable type" ; for instance : - if the string is "abcd" the value is the same string "abcd" - string "123" : value = the integer 123 - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value = the float -1.23 - string "2008/03/06" (the format is also locale-dependant) : value = datetime.date(2008,03,06) Like in spreadsheets, special prefixes could be used to force the type : for instance '123 would be converted to the *string* "123" instead of the *integer* 123 I could code it myself, but this wheel is probably already invented Regards, Pierre From paulgeeleher at gmail.com Wed Mar 12 12:43:33 2008 From: paulgeeleher at gmail.com (sophie_newbie) Date: Wed, 12 Mar 2008 09:43:33 -0700 (PDT) Subject: Get cgi script to begin execution of another script... Message-ID: I've posted something similar to this already, but now I'm more sure of what I'm asking. Basically I've a CGI script, that when executed by the user, I want to call another script that does a very long running task (10 hours +) and print a message on the screen saying that the user will be emailed on completion of the very long task. The script executing the very long task will then email the user on completion. So far I have something like this (leaving out the obvious)... CGI script: pid = subprocess.Popen(["python", "spawn.py"]).pid print "Thanks you will be emailed on completion" Spawn.py script: doVeryLongCalc() emailUser() Basically the problem with this is that the cgi script page in the browser keeps on acting as if its loading until the Spawn.py script is finished executing. Somehow apache "knows" that the spawned process is still running in the background. So I'm basically asking if I can somehow spawn a script that will be completely independent of its parent script? So Apache doesn't know its running and the page finishes loading? Thanks if anyone can help... From misceverything at gmail.com Mon Mar 31 05:13:49 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Mon, 31 Mar 2008 02:13:49 -0700 (PDT) Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> <47eea713$0$27902$426a74cc@news.free.fr> Message-ID: On Mar 31, 2:50 am, Tim Golden wrote: > misceveryth... at gmail.com wrote: > > That's not a problem - I'm only interested in Win2k+. Thanks for the > > caveat. > > > On a similar note, is there a way (preferably using WMI) to get the > > full path to the executable that has a port open (the same thing that > > fport does, just implemented in Python)? > > It looks as though it might be possible with the (not > installed by default) SNMP WMI provider. Haven't tried > it myself, but there's some info here: > > http://groups.google.com/group/microsoft.public.win32.programmer.wmi/... > > and here: > > http://msdn2.microsoft.com/en-us/library/aa393621(VS.85).aspx > > Alternatively, look around for the GetExtendedTcpTable functionality > and so on. > > Sorry, this isn't really my area -- all I've done here is to let > my fingers do the walking. > > TJG Sounds good - I'm going to check those links out now. Thanks again for all your help. From dewitters at gmail.com Sun Mar 30 04:25:35 2008 From: dewitters at gmail.com (dewitters at gmail.com) Date: Sun, 30 Mar 2008 01:25:35 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <02864e42-d2d7-4eeb-ba13-6aa7ddbdf7aa@i29g2000prf.googlegroups.com> Message-ID: <7c041716-69a4-47d9-9105-62fcc3dd4269@s50g2000hsb.googlegroups.com> On Mar 29, 9:48 pm, Dan Bishop wrote: > MOST of Python's operators are based on C's. Consider, for example, > the bitwise operators | ^ & << >> ~ and the compound assignment > operators += -= etc. > > The exceptions are ** (from Fortran), //, and the logical operators. Borrowing parts out of other languages (C in this case) is not a problem, but I don't think there is a need to try be consistent with C. It's Python, not C, so we should do things better ;). From sjmachin at lexicon.net Thu Mar 13 17:00:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Mar 2008 14:00:49 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> Message-ID: On Mar 14, 6:13 am, Arnaud Delobelle wrote: > On Mar 13, 10:42 am, Paul Rubin wrote: > [...] > > > By Python convention, methods that mutate the object return None, and > > also stuff that returns None doesn't generate output at the > > interactive prompt. > > A convention that does not always hold: > > > > >>> l = [1, 2, 3] > >>> l.pop() > 3 > >>> l > [1, 2] Try this then for the "convention": Any function/method that is not documented to return something else should be assumed to return None. Note: no nexus with whether or not the function/method mutates its args. From sales057 at aaa-replica-watch.com Tue Mar 18 00:00:06 2008 From: sales057 at aaa-replica-watch.com (sales057 at aaa-replica-watch.com) Date: Mon, 17 Mar 2008 21:00:06 -0700 (PDT) Subject: Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Replica Message-ID: <4de7b883-a9e1-4ea0-aa57-911a188e480c@d21g2000prf.googlegroups.com> Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Replica, Fake, Cheap, AAA Replica watch Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Link : http://www.aaa-replica-watch.com/Ebel_1215526.html Buy the cheapest Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 in toppest Replica . www.aaa-replica-watch.com helps you to save money! Ebel-1215526 , Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 , Replia , Cheap , Fake , imitation , Ebel Watches Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Information : Brand : Ebel Watches (http://www.aaa-replica-watch.com/ Replica_Ebel.html ) Gender : Ladies Model : Ebel-1215526 Case Material : 18kt Yellow Gold And Stainless Steel Case Diameter : 1215526, Ebel-1215526, 1201L24-9960, 1201L24/9960, 1201L24.9960, 1201L249960 Dial Color : White Mother-of-pearl Bezel : 18kt Yellow Gold With 34 Diamonds Movement : Automatic Clasp : 18kt Yellow Gold And Stainless Steel Water Resistant : 100m/330ft Crystal : Scratch Resistant Sapphire Our Price : $ 225.00 18kt yellow gold and stainless steel case and bracelet. White mother- of-pearl dial with 11 diamond hour markers. Bezel set with 34 diamonds. Hidden folding clasp. Anti-reflective scratch resistant sapphire crystal. Case diameter 27mm. Automatic movement. Water resistant at 100 meters (330 feet). Alternate model number 1201L24/9960. Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Replica, With the mix of finest craftsmanship and contemporary styling, not only does it reflect the time but also care you put into looking good. choose one to promote your quality and make yourself impressive among people Thank you for choosing www.aaa-replica-watch.com as your reliable dealer of quality waches including Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 . we guarantee every watch you receive will be exact watch you ordered. Each watch sold enjoy one year Warranty for free repair. Every order from aaa-replica-watches is shipped via EMS, the customer is responsible for the shipping fee on the first order, but since the second watch you buy from our site, the shipping cost is free. Please note that If the total amount of payment is over $600(USD), the customer is required to contact our customer service before sending the money in case failed payment. If you have any other questions please check our other pages or feel free to email us by service at aaa-replica-watch.com. The Same Ebel Watches Series : Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 : http://www.aaa-replica.com/Ebel_1215525.html Ebel 1911 Mens Watch 91331240/14665P : http://www.aaa-replica.com/Ebel_91331240_14665P.html Ebel 1911 Womens Watch 1090211-19865P : http://www.aaa-replica.com/Ebel_1090211_19865P.html Ebel 1911 Mens Watch 1080241-13665P : http://www.aaa-replica.com/Ebel_1080241_13665P.html Ebel 1911 Womens Watch 9090214-19865P : http://www.aaa-replica.com/Ebel_9090214_19865P.html Ebel 1911 Womens Watch 1087221-15865P : http://www.aaa-replica.com/Ebel_1087221_15865P.html Ebel 1911 Womens Watch 1087221-19865P : http://www.aaa-replica.com/Ebel_1087221_19865P.html Ebel 1911 Mens Watch 9331240-13665P : http://www.aaa-replica.com/Ebel_9331240_13665P.html Ebel 1911 Mens Watch 9125241-10665P : http://www.aaa-replica.com/Ebel_9125241_10665P.html Ebel 1911 Mens Watch 9330240-15665P : http://www.aaa-replica.com/Ebel_9330240_15665P.html Ebel Classic Mini Stainless Steel Ladies Watch 9003F11.9925 : http://www.aaa-replica.com/ebel_classic_mini_watch_9003F11_9925.html Ebel Classic Stainless Steel Mens Watch 9120F51.6235134 : http://www.aaa-replica.com/ebel_classic_stainless_9120F516235134.html From cabird at gmail.com Mon Mar 31 16:52:44 2008 From: cabird at gmail.com (Christian Bird) Date: Mon, 31 Mar 2008 13:52:44 -0700 Subject: import multiple modules with same name Message-ID: Is it possible to import multiple modules with the same name from different locations? I'm using two different pieces of software, both of which have a module named util.py. I know that I can modify sys.path to fix which util gets imported when I do: import util I'd like to be able to do something like: import sys sys.path.append("/somedir1/") import util as util1 sys.path.insert(0, "/somedir2/") import util as util2 But it appears that once python imports a module, it will never look for a module with the same name again. Is there any way to get around this? I'd rather not rename either of the util modules as other pieces of software use them (but the others never use both of them of course) and I don't want to break them or have multiple copies of the code in different named files. I'm appreciative of anyone's ideas. -- Chris -- Christian Bird cabird at gmail.com From shasha1234 at gmail.com Thu Mar 6 16:08:15 2008 From: shasha1234 at gmail.com (shsha) Date: Thu, 6 Mar 2008 13:08:15 -0800 (PST) Subject: Internet Explorer 8 beta release Message-ID: Internet Explorer 8 beta release is for developers, and Microsoft's Dean Hachamovitch promised at MIX08 that IE8 will make it easier to build Web sites for multiple browsers and stop wasting developers' time. Microsoft's IE8 features Activities for looking up information and Webslices to watch portions of Web sites for updates. more about MS http://www.toptechnews.com/story.xhtml?story_id=0120013PBF8O _____________ get wild ....all the action http://www.getaction4ever.com From dave_mikesell at fastmail.fm Mon Mar 3 07:18:40 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Mon, 3 Mar 2008 04:18:40 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: <620e3371-6cd1-4719-9e0b-a3b0c01f5fbc@d21g2000prf.googlegroups.com> On Mar 1, 10:53 pm, Kay Schluehr wrote: > On 1 Mrz., 19:51, Barry Warsaw wrote: > > > Python 2.6 is not only the next advancement in the Python 2 series, it > > is also a transitionary release, helping developers begin to prepare > > their code for Python 3.0. > > Isn't this a silly idea? People have to migrate from 2.5 or lower > releases to Python 2.6 first just to migrate to Python 3.0? What are > the inherent / technical reasons that prevent migration directly from > 2.5 to 3.0? Not only that, you have to wait for your library providers to migrate first (PyOpenGL, PyGame, PIL, etc for me). Hopefully this is the last quantum shift for a while. From tms at zeetix.com Sun Mar 16 11:10:26 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sun, 16 Mar 2008 11:10:26 -0400 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com><1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> Message-ID: <00ae01c88777$de88e2b0$0200a8c0@TMSMAIN> > But vendors often don't label themselves as vendors. And often, the > researcher or individual in question, who has something worth saying, does > have a professional job of sorts, which might be related to his or her > work > or speech. I've heard people give very long, detailed talks about > interesting topics, that did have a spin on them, but contained worthwhile > information also. Now, is that to be billed as a "vendor" (and ignored) > or > not? > Further, no vendor who is trying to sell a product will allow themselves > to > be marked in an obvious way as advertising, knowing that they'll be > ignored. At least, they certainly won't pay for the time/space to any > real > degree, knowing they'll be walking in under a cloud like that. No vendor with integrity will want their advertising to be presented to attendees as anything but advertising. If vendors won't buy advertising, then find different ways to fund the conferences. This sounds like an example of the editorial-content/advertising dilemma that publishers have wrestled with for a long time. It's basically impossible for anybody, even for seasoned professionals, to both sell advertising and set editorial content without bias. In the publishing business, it is a very big no-no for the same people to both sell advertising and also set editorial content. When you go high enough in an organization, it's harder to do, but still a goal. Perhaps the organizers can therefore learn from the experience of publishers: 1) Keep the folks who sell things in an "advertising department". They need to be different people from the folks who book keynotes and such. 2) Keep the folks who book keynotes and such in a "content department". They need to be different people from the folks who sell things. 3) Do everything possible to keep the "advertising" and "content" departments firewalled. This is cultural as much as anything else. Like any other potential conflict of interest situation, make it honorable for folks to recuse themselves when they sense a bias in themselves. From mail at timgolden.me.uk Thu Mar 27 05:01:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 09:01:26 +0000 Subject: py2exe socket.gaierror (10093) In-Reply-To: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: <47EB6266.1040609@timgolden.me.uk> Python Programming on Win32 wrote: > The problem is running smtplib in a py2exe compiled exe file. When it > tries to establish a socket to the mail server it fails. > > Just wondering someone has encountered this before, and if someone > might be able to point me in the right direction. > > Unhandled exception in thread started by > Traceback (most recent call last): > File "AutomationThread.pyc", line 152, in Run > File "mail.pyc", line 11, in sendMail > File "smtplib.pyc", line 244, in __init__ > File "smtplib.pyc", line 296, in connect > socket.gaierror: (10093, 'getaddrinfo failed') In case it helps, this is the text for error 10093: """ WSANOTINITIALISED 10093 Successful WSAStartup not yet performed. Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times. """ WSAStartup is called by a process which wants to use winsock, the Windows sockets implementation and it's called by Python's socket module at startup. I can't see anything in py2exe's source which should make any difference to socket initialisation so I'm at a loss. TJG From rockxuan at gmail.com Tue Mar 18 03:57:33 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:57:33 -0700 (PDT) Subject: Breitling Swiss watch in www.51cntrade.com Message-ID: Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From tjreedy at udel.edu Sun Mar 23 17:29:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Mar 2008 17:29:14 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a firstprogramming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: "Roy Smith" wrote in message news:roy-40994D.13513423032008 at 70-1-84-166.area1.spcsdns.net... | There is a fundamental disharmony in how functions and other objects are | treated in Python. [snip] For scalars and collections, print object prints the value, which is the main part of the object, in a form close to (or equal to) how it is created in code. For functions, classes, and modules, this would be awkward to impossible since the corresponding code is not part of the object and may be either bulky and slow to access, not accessible, or non-existent. So these three get name attitributes as a substitute. Function names are also used to improve tracebacks over 'function at line nnn'. Perhaps for these types, print could (should?) instead print the first list of the doc string, if there is one. Method objects inherit the name of the function they wrap. Other internal types are left anonymous, but how could they get a name when there is no code to give them a name. Yes, fundamentally different categories of types are (sensibly) treated differently with repect to definition and namespace names, but calling that 'disharmony' depends on the listener. | If we created lisp-like lambdas and bound them to names like we did with | other types of objects, we wouldn't have that. Correct. Tracebacks would always instead of just occasionally be less useful as functions would always be identified only by file and line number, as today with lambda expression. Terry Jan Reedy From gabriel.rossetti at mydeskfriend.com Thu Mar 27 04:20:05 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 09:20:05 +0100 Subject: Partial Function Application and implicit self problem Message-ID: <47EB58B5.1020801@mydeskfriend.com> Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass "self" to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Thanks, Gabriel From Glich.Glich at googlemail.com Mon Mar 24 12:58:26 2008 From: Glich.Glich at googlemail.com (Glich) Date: Mon, 24 Mar 2008 09:58:26 -0700 (PDT) Subject: python, dbus and pointers help. References: <16059cb8-a182-40ff-9617-a8b6708e1183@s19g2000prg.googlegroups.com> Message-ID: <61a383ca-e287-4d13-a3b0-ba9ec24626fa@d21g2000prf.googlegroups.com> or a way of letting me see the message then cancel sending it then I could create a new message and send that one. but I cant see this in the documentation From kuaile9834 at 126.com Tue Mar 25 03:35:48 2008 From: kuaile9834 at 126.com (kuaile9834 at 126.com) Date: Tue, 25 Mar 2008 00:35:48 -0700 (PDT) Subject: cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) Message-ID: cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com )cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) From cito at online.de Sun Mar 2 16:40:51 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 02 Mar 2008 22:40:51 +0100 Subject: tuples, index method, Python's design In-Reply-To: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> References: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> Message-ID: Paul Boddie schrieb: > On 2 Mar, 19:06, Alan Isaac wrote: >> On April 12th, 2007 at 10:05 PM Alan Isaac wrote: >> >>> The avoidance of tuples, so carefully defended in other >>> terms, is often rooted (I claim) in habits formed from >>> need for list methods like ``index`` and ``count``. >>> Indeed, I predict that Python tuples will eventually have >>> these methods and that these same people will then defend >>> *that* status quo. > > You were more confident about this than I was. Still, nothing happens > if no-one steps up to do something about it. And nobody stepped up because it had been made very clear by Guido and others that they don't want tuples to grow methods. I remember there had been ridiculously excessive threads about this, this probably being one of many others: http://groups.google.de/group/comp.lang.python/browse_thread/thread/430a692bc634a04f/ I don't think this was very encouraging for people who wanted to do something about it. Anyway, it's good to see this happened now. Thanks to Raymond. -- Christoph From saluk64007 at gmail.com Wed Mar 19 13:24:16 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 19 Mar 2008 10:24:16 -0700 Subject: Python to C/C++ In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: (sorry michael, didn't mean to personal post On Wed, Mar 19, 2008 at 9:24 AM, Michael Wieher wrote: > I think py2exe does this, but it might be a bit bloated No, py2exe basically bundles the main script and the interpreter together so it's easy to run and requires no python installation. Look into pyrex and pypy. A mature translator doesn't exist. Also there is ctypes which goes in reverse letting you use more c from python easily. From roygeorget at gmail.com Mon Mar 10 09:57:45 2008 From: roygeorget at gmail.com (royG) Date: Mon, 10 Mar 2008 06:57:45 -0700 (PDT) Subject: parsing directory for certain filetypes Message-ID: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> hi i wrote a function to parse a given directory and make a sorted list of files with .txt,.doc extensions .it works,but i want to know if it is too bloated..can this be rewritten in more efficient manner? here it is... from string import split from os.path import isdir,join,normpath from os import listdir def parsefolder(dirname): filenms=[] folder=dirname isadr=isdir(folder) if (isadr): dirlist=listdir(folder) filenm="" for x in dirlist: filenm=x if(filenm.endswith(("txt","doc"))): nmparts=[] nmparts=split(filenm,'.' ) if((nmparts[1]=='txt') or (nmparts[1]=='doc')): filenms.append(filenm) filenms.sort() filenameslist=[] filenameslist=[normpath(join(folder,y)) for y in filenms] numifiles=len(filenameslist) print filenameslist return filenameslist folder='F:/mysys/code/tstfolder' parsefolder(folder) thanks, RG From gagsl-py2 at yahoo.com.ar Mon Mar 17 09:16:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 11:16:44 -0200 Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> Message-ID: En Sun, 16 Mar 2008 22:27:28 -0200, escribi?: > Specifically, before the prompts. Where does the prompt write come > from; why doesn't it honor my settings of sys.stdout and sys.stderr? The interactive interpreter uses directly the C predefined streams stdout and stderr. -- Gabriel Genellina From bj_666 at gmx.net Mon Mar 31 02:45:27 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 06:45:27 GMT Subject: Beginner advice References: Message-ID: <65bfk7F2esfc1U1@mid.uni-berlin.de> On Mon, 31 Mar 2008 07:23:00 +0200, Paul Scott wrote: > 3. pyXMLRPClib - active? Something better? There is an `xmlrpclib` in the standard library, so there is no need for an external package here. I even think that pyXMLRPClib is the one that's integrated in the standard library, so the external one might be "dead". > 4. I see that there are literally thousands of somewhat external looking > libraries for python, I presume that there is some way of bundling all > the deps into a single source and then compiling? or otherwise packaging > them all (this software will be for academia, so difficult installs are > out!) For Windows there are tools to bundle your source and all dependencies and even the interpreter itself. `py2exe` is such a tool. With InnoSetup or NSIS or similar programs you can then make a `setup.exe` for that spoiled Windows brats. :-) Under Linux many packages are available as distribution specific packages on most distributions. So for Linux you may get away with a README stating the dependencies of your program and a `setup.py` for installing your project. Look for `distutils` in the Python documentation for further information about `setup.py`\s. > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? Use the one you like best. ;-) Many don't use an IDE but simply their favorite text editor. I'm happy with syntax highlighting, automatic indentation support for Python source code, and completion based on the content of open file(s) -- almost all serious editors have those features. And there's always an IPython console running to test small pieces of code. > All Email originating from UWC is covered by disclaimer > http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm Hey, that's a nice way to have a *short* stupid disclaimer. :-) Ciao, Marc 'BlackJack' Rintsch From nejtak... Wed Mar 5 16:44:03 2008 From: nejtak... (Troels Thomsen) Date: Wed, 5 Mar 2008 22:44:03 +0100 Subject: for-else In-Reply-To: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> Message-ID: <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> > > The primary use case is searching a container: > > prep_tasks() > for item in container: > if predicate(item): > found_tasks() > break > else: > not_found_tasks() > follow_up_tasks > I've found myself mimicing this again and again in c, and was pleased to find it in python and use it regularely. int i for (i = 0 ; i < 10 ; ++i) blah if i == 10 not_found_tasks() The discussion of words is silly. My surprise about "else following a for loop.... what the heck ...." lasted excactly as long as it takes to read this sentence. tpt From castironpi at gmail.com Tue Mar 4 13:40:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:40:11 -0800 (PST) Subject: for-else References: Message-ID: <529fdf03-9c17-476c-abb9-42c4417ed7c2@d4g2000prg.googlegroups.com> Would you like it to be removed or its name changed? You can do it with a special iteration: for a in B: if behavior break else: 2behavior ----> class KeepResult:... kr= KeepResult( B ) for a in kr: if behavior break if kr.diditbreak?: 2behavior (if not: 3behavior) It just can't do automatic continues; you'd need a kr.i'mcontinuingonthisone(). Would that be useful in addition? From jzgoda at o2.usun.pl Fri Mar 14 16:52:46 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 14 Mar 2008 21:52:46 +0100 Subject: Installing Python2.4 on RHEL4? In-Reply-To: References: Message-ID: Eric B. pisze: > I appologize if this is slightly OT, but I am really struggling to figure > out how to install Python2.4 on RHEL4. To make matters worse, the RHEL4 > machine is a 64bit architecture. > > I search pyvault, but they only have for .i386. Does anyone know where / > how I can find Python2.4 for RHEL4 x64? If you would not find a binary Python 2.4 package, you can always build your own and package it. Why not? -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From aisaac at american.edu Fri Mar 14 00:28:41 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 14 Mar 2008 04:28:41 GMT Subject: no more comparisons In-Reply-To: References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: Dan Bishop wrote: > Even assuming you meant (-x[0], int(x[1])), that sorts negative > numbers in the wrong order. You want > key = lambda x: (-1 if x[0] else 1) * int(x[1]) Sorry, was speed typing (very badly) and the question actually had two different problem descriptions. As you suggest, what I meant was:: key= lambda x: (-x[0], int(x[1])) which was meant to address: "Sorting tuples, where the second item in the tuple should have the opposite ordering to the first is going to be a bit of a pain." But you are quite right, the problem was then specified to numerical order, for which I like your solution. Or even:: key= lambda x: -int(x[1]) if x[0] else int(x[1]) The key point being, if you will, that this use case does not support the idea that relying on ``key`` will be so bad. So, what is a case that is really uncomfortable? Thanks, Alan Isaac From tms at zeetix.com Sat Mar 15 12:09:19 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 12:09:19 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> I'm still confused about this, even after days of hacking at it. It's time I asked for help. I understand that each of you knows more about Python, Javascript, unicode, and programming than me, and I understand that each of you has a higher SAT score than me. So please try and be gentle with your responses. I use simplejson to serialize html strings that the server is delivering to a browser. Since the apostrophe is a string terminator in javascript, I need to escape any apostrophe embedded in the html. Just to be clear, the specific unicode character I'm struggling with is described in Python as: u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of 0x27. This can be expressed in several common ways: hex: 0x27 Python literal: u"\u0027" Suppose I start with some test string that contains an embedded apostrophe -- for example: u" ' ". I believe that the appropriate json serialization of this is (presented as a list to eliminate notation ambiguities): ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] This is a 14-character utf-8 serialization of the above test string. I know I can brute-force this, using something like the following: def encode(aRawString): aReplacement = ''.join(['\\', '0', '0', '2', '7']) aCookedString = aRawString.replace("'", aReplacement) answer = simplejson.dumps(aCookedString) return answer I can't even make mailers let me *TYPE* a string literal for the replacement string without trying to turn it into an HTML link! Anyway, I know that my "encode" function works, but it pains me to add that "replace" call before *EVERY* invocation of the simplejson.dumps() method. The reason I upgraded to 1.7.4 was to get the c-level speedup routine now offered by simplejson -- yet the need to do this apostrophe escaping seems to negate this advantage! Is there perhaps some combination of dumps keyword arguments, python encode()/str() magic, or something similar that accomplishes this same result? What is the highest-performance way to get simplejson to emit the desired serialization of the given test string? From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 04:05:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 08:05:16 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> Message-ID: <13t76hsmp060e55@corp.supernews.com> On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > On 9 Mrz., 06:30, Steven D'Aprano cybersource.com.au> wrote: > >> Hard Exceptions: terminate the program unless explicitly silenced Soft >> Exceptions: pass silently unless explicitly caught >> >> In this case, I agree with the Zen of Python ("import this"): >> >> Errors should never pass silently. >> Unless explicitly silenced. > > Exceptions in Python don't necessarily signal errors. Just think about > StopIteration. I know that. That's why I said that exceptions were used for signaling exceptional events. > Note also that the common practice of letting *possible* errors passed > silently is to return None instead of raising an exception. "Common"? Who does that? I know re.search() etc. return None in the event the regex doesn't match. That's not an error. > Moreove people create boilerplate like this > > try: > k = lst.index(elem) > ... > except IndexError: > pass > > instead of > > with lst.index(elem) as k: > ... Possibly because the with keyword is quite new and many people don't know it, and much code was written before it even existed, or they have to support Python 2.4 or older. > It would be interesting to think about SoftException semantics for such > clauses: lst.index would neither raises a HardException nor does it > return None but leads to skipping the with-block. > > Is it really so exotic that it requires the demand for more use cases? Are the existing solutions really so incomplete that we need yet another solution? What problem are you trying to solve with SoftExceptions? How would changing lst.index() to raise a soft exception help here? pos = lst.index('foo') lst[pos] = 'bar' What is that code going to do if 'foo' isn't found in lst and it raises a silent, unhandled SoftException? Do you expect Python to be context sensitive, and raise HardExceptions in some places and SoftExceptions in others? Who controls that? -- Steven From nkanthikiran at gmail.com Thu Mar 13 01:44:55 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Wed, 12 Mar 2008 22:44:55 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: On Mar 13, 8:07 am, "drobi... at gmail.com" wrote: > On Mar 12, 7:37 am, "k.i.n.g." wrote:> We use dd command in Linux to create a file with of required size. > > If you just want to get your work done, you might consider the cygwin > dd command. > Learning to write python is a worthwhile endeavour in any case. While I just started learning programming/python, I got this requirement at my workplace. I want to learn python than just get things done. Thank you all for the solutions, I will try them and let you all know about my results. From jgardner at jonathangardner.net Fri Mar 14 12:24:44 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 14 Mar 2008 09:24:44 -0700 (PDT) Subject: Monitoring SSHd and web servers? References: Message-ID: <36a2338f-60fd-456d-a906-716bb52e8122@s8g2000prg.googlegroups.com> On Mar 13, 11:32?pm, Gilles Ganault wrote: > I'd like to monitor connections to a remote SSH and web server. Does > someone have some code handy that would try to connect every 5mn, and > print an error if the script can't connect? from time import sleep while True: # Try to connect. May want to spawn a subprocess running a simple shell script # Handle success / failure appropriately sleep 5*60 # Sleep for 5 minutes What you monitor is up to you. At a basic level, you can see if the server is accepting connections. At a higher level, see if you can get a page or see if you can login as a specific person. At a higher level, you may want to check what is on the page or what happens when you log in. It's all up to you. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 18:48:32 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 00:48:32 +0200 Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: <65ajm0F2e07o0U1@mid.individual.net> vokinloksar at yahoo.se wrote: > using python and wpython. What's wpython? > when using run module or python shell on the run menu in the GUI i > get "socket error, connection refused". > > it worked before, what si wrong now? There's no process listening for the port you try to connect to, so the target host refuses. > and i cant find where to start the shell directly. Well, for me, ALT-F2 xterm[Enter] works. > think i had an exe before but cant seem to find it now. You mean the Python interpreter? It's probably located on your system root in a directory called python. But I'd rather use IDLE. Regards, Bj?rn -- BOFH excuse #338: old inkjet cartridges emanate barium-based fumes From sjmachin at lexicon.net Wed Mar 19 16:23:20 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 13:23:20 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> Message-ID: <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> On Mar 19, 11:17 pm, Godzilla wrote: > Hi John, > > I am using time.clock to calculate the elapsed time. Below is an > example of what I was trying to do: > > import time > import thread Silly me, not being able to infer that from your initial post! [snip] > > But the time.clock() sometimes return a value of between -3.5 to -4.5 > seconds backward. Note that not all computers are behaving the same. I > have not experience the same problem with the computer at home. Same "service pack" number? Your code "worked" (no time warp) for me on a single-core AMD Turion64 CPU running (32 bit) Windows XP Service Pack 2 Build 2600. Maybe the ones that "fail" have dual-core CPUs. From grante at visi.com Thu Mar 13 14:38:26 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 13 Mar 2008 18:38:26 -0000 Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: <13tit52j138i1e6@corp.supernews.com> On 2008-03-13, sleddd at gmail.com wrote: >> > For example: try creating a local client/server (running on the same >> > computer) where the server sends the client a fixed amount of data. >> > Using method A, recv(8192) and sendall( ) with 8192 bytes >> > worth of data. Do this 100 times. Using method B, recv(1) and >> > sendall( ) with 1 byte worth of data. Do this 819200 times. >> >> > If you time both methods, method A has much greater >> > throughput than method B. >> >> Why is it faster to drink a liter of water a cupful at a time than to >> drink it out of an eyedropper? > Well, lets say you have a situation where you're going to be > alternating between sending large and small chunks of data. Is the > solution to create a NetworkBuffer class and only call send when the > buffer is full, always recv(8192)? If you need to send large and small chumks of data, the solution is to send large and small chunks of data. -- Grant From jim at maplesong.com Fri Mar 7 16:24:34 2008 From: jim at maplesong.com (Jim Carroll) Date: Fri, 7 Mar 2008 21:24:34 +0000 (UTC) Subject: Time Zone application after strptime? Message-ID: It's taken me a couple of hours to give up on strptime with %Z for recognizing time zones... but that still leaves me in the wrong zone: def paypal_to_mysql_date(ppDate): # a typical paypal date is 10:29:52 Feb 29, 2008 PST date_parts = ppDate.split() withouttz = " ".join(date_parts[:-1]) # eventually we need to apply the timezone timezone = date_parts[-1] dt = datetime.strptime(withouttz, "%H:%M:%S %b %d, %Y") return dt.strftime("%Y-%m-%d %H:%M") How can I use the "PST" (or any other time zone name) to adjust dt by the correct number of hours to get it into UTC before storing in MySQL? Thanks! From jgelfand01 at gmail.com Tue Mar 25 19:15:57 2008 From: jgelfand01 at gmail.com (jgelfand) Date: Tue, 25 Mar 2008 16:15:57 -0700 (PDT) Subject: _tkinter fails when installing Python 2.4.4 References: <64tahuF2absebU1@mid.uni-berlin.de> Message-ID: <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> On Mar 25, 5:52 pm, "Diez B. Roggisch" wrote: > jgelfand schrieb: > > > > > I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat > > Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ > > usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but > > I get the following error message when I run "make": > > > building '_tkinter' extension > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > > yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ > > usr/local/yosi/Python-2.5.2/Modules/_tkinter.o > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > > yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ > > usr/local/yosi/Python-2.5.2/Modules/tkappinit.o > > gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ > > Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ > > yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ > > lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - > > ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so > > *** WARNING: renaming "_tkinter" since importing it failed: build/ > > lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents > > > Any suggestions / ideas as to what is going wrong? I don't get any > > other warnings or errors on the other modules. Thanks -- Yosi > > You are aware that the above shows python 2.5 as the version that is > being used for compilation? > > Diez Sorry. I get the same error messages for Python 2.4.4, Python 2.4.5, and Python 2.5. The software package I'm trying to build from source requests that I install Python 2.4.4, so I'm interesting in solutions for that particular distribution. Thanks -- Yosi From benhoyt at gmail.com Wed Mar 19 00:17:49 2008 From: benhoyt at gmail.com (benhoyt) Date: Tue, 18 Mar 2008 21:17:49 -0700 (PDT) Subject: Is there a way to get __thismodule__? References: Message-ID: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> Replying to myself here, after discovering more. :-) > Is there a way to get __thismodule__ in Python? It looks like __thismodule__ is just sys.modules[__name__]. Neat. Hmmm ... does sys.modules always already contain the currently-being- loaded module? Or is this a hack that only happens to work? (It does; I've tested it now.) Just wondering, because the Python docs say that sys.modules is "a dictionary that maps module names to modules which have *already been loaded*." > if isinstance(attr, Message): > nmap[attr.number] = attr Oops, this was untested code. I actually meant issubclass (or something similar) here, not isinstance. Cheers, Ben. From bockman at virgilio.it Mon Mar 24 09:36:13 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 13:36:13 GMT Subject: python library to manipulate PALM documents ? Message-ID: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> Hi all, anybody knows a python equivalent of the perl PALM::Doc module (and eventually other PALM::). I have a e-book device wich reads mobi-pocket format (among others). I have downloaded from a forum a set of perl scripts to convert HTML to unencripted mobipocket format and vice-versa. It uses the PALM:: package. I would attempt (for my convenience and for the fun of it) to make a python equivalent of that. Hence my quest for a Palm::Doc equivalent. My googling up to now resulted in nothing relevant. Keeping searching ... Ciao ----- FB From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:38:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:38:18 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6i47r3uoo6b4@corp.supernews.com> Message-ID: <13t6jcq8srbi28@corp.supernews.com> On Sun, 09 Mar 2008 02:16:39 +0000, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 15:26:35 -0800, Paul Rubin wrote: > >> Alasdair writes: >>> What is the best way of finding a ceiling of a quotient of arbitrary >>> sized integers? >> >> ceiling(a/b) = (a+b-1)//b > > > Unfortunately that doesn't work reliably. But of course you didn't intend it to work with floats, did you? Sigh. I'm just glad I didn't rant about people who think that floats are just like reals when they're not. -- Steven From micah at cowan.name Fri Mar 7 17:41:14 2008 From: micah at cowan.name (Micah Cowan) Date: Fri, 07 Mar 2008 22:41:14 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> <13t3cfpo6d8d2ab@corp.supernews.com> Message-ID: <87ve3y9myd.fsf@micah.cowan.name> Grant Edwards writes: > On 2008-03-07, Steven D'Aprano wrote: > >> Professional typesetters, using proportional fonts, don't use double- >> spaces because it throws off word spacing and line justification and just >> plain looks ugly. > > They do, however, put more space between sentences than they do > between words within a sentence. It is that practice which the > "two spaces after a period" rule in typewriting is attempting > to emulate. Not in most books I've read. AFAICT, it's a (thankfully) disappearing practice in the typesetting profession. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From tmp1 at viltersten.com Sun Mar 2 09:47:17 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 15:47:17 +0100 Subject: Keeping the console window Message-ID: <62vs0iF24tv6jU1@mid.individual.net> I've proudly connected Notepad++ to edit and run my fantastic software. When that started to work, i noticed that all the printing disappears as the console window vanishes upon the program completion. How can i trick Python program to keep on running even if the actual statements have been exectuted? Some kind of reading from keyboard? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From goon12 at gmail.com Tue Mar 11 10:38:22 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 11 Mar 2008 10:38:22 -0400 Subject: How to factor using Python? In-Reply-To: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <6a2ccd190803110738l2ba7d0c0ne4d61b74e6a5d9c8@mail.gmail.com> On Mon, Mar 10, 2008 at 1:08 AM, Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? This should work to do x! (factorial of x). reduce(lambda x,y: x*y, range(1, x+1)) From mail at timgolden.me.uk Fri Mar 7 10:41:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Mar 2008 15:41:03 +0000 Subject: problem with join In-Reply-To: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: <47D1620F.6070200@timgolden.me.uk> nodrogbrown wrote: > hi > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', You've got a couple of options. Your "folder" to start with is in the unixy form a/b/c and the .join function doesn't do anything to change that, merely uses os.pathsep to append the parts to each other. You can either set your folder to be r"f:\brown\code..." in the first case or use os.path.normpath or os.path.abspath on the result. TJG From andymac at bullseye.apana.org.au Thu Mar 13 06:17:59 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 13 Mar 2008 20:17:59 +1000 Subject: problem with Python 2.5.2 and gcc 4.3 In-Reply-To: <7jRBj.20981$QC.15171@newsfe20.lga> References: <7jRBj.20981$QC.15171@newsfe20.lga> Message-ID: <47D8FF57.7060207@bullseye.andymac.org> David P. Riedel wrote: > I tried building Python 2.5.2 using gcc 4.3.0. The build completes with no problems but when I run 'make test', I get a > segfault part way through the test run. > > here is the last part of the output from make test > > test_softspace > test_sort > test_sqlite > test_sqlite skipped -- no sqlite available > test_startfile > test_startfile skipped -- cannot import name startfile > test_str > make: *** [test] Segmentation fault You don't identify the platform or O/S, though I'd guess some Linux distro on i386 or x86-64... If you have gdb available, a backtrace might give a clue. However, as this is a new major release of gcc I'm automatically going to assume an optimisation issue. To test this I'd suggest doctoring the makefile generated by configure to reduce the optimisation level - I'd suggest trying -O instead of -O3. If that works, try -O2 or -Os. If -O2 or -Os works, I'd be taking the matter up with the gcc team. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 14 09:24:27 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Mar 2008 14:24:27 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: <-cudnSGj6P-2JETanZ2dnUVZ_vShnZ2d@speakeasy.net> References: <-cudnSGj6P-2JETanZ2dnUVZ_vShnZ2d@speakeasy.net> Message-ID: <47da7c47$0$15800$426a34cc@news.free.fr> Erik Max Francis a ?crit : > Dave Kuhlman wrote: > >> Basically, the above code is saying that foo.foobar is not the same as >> getattr(foo, 'foobar'). > > Python promises that the behavior is the same. It does not promise that > the _objects_ will be the same, which is what `is` determines. That is, > you're not doing a useful test here. FWIW, two methods are "the same" if they have identical (function, obj, cls) attributes. Looks like the equality test is correctly implemented: >>> foo.bar == foo.bar True HTH From gandalf at shopzeus.com Tue Mar 18 05:44:13 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 18 Mar 2008 10:44:13 +0100 Subject: Decode email subjects into unicode Message-ID: <47DF8EED.1010501@shopzeus.com> Hi All, 'm in trouble with decoding email subjects. Here are some examples: > =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?= > [Fwd: re:Flags Of The World, Us States, And Military] > =?ISO-8859-2?Q?=E9rdekes?= > =?UTF-8?B?aGliw6Fr?= I know that "=?UTF-8?B" means UTF-8 + base64 encoding, but I wonder if there is a standard method in the "email" package to decode these subjects? I do not want to re-invent the weel. Thanks, Laszlo From brad at 16systems.com Fri Mar 28 22:31:07 2008 From: brad at 16systems.com (Brad) Date: Fri, 28 Mar 2008 22:31:07 -0400 Subject: some path issues on windows Message-ID: When reading a file into a list that contains windows file paths like this: c:\documents and settings\brad\desktop\added_software\asus\a.txt I get a list that contains paths that look like this: c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt So, my list contains those funky file paths. And, when I do this: for root, dirs, files in os.walk('C:\\'): for f in files: print os.path.join(root,f) I get the more normal path again: c:\documents and settings\brad\desktop\added_software\asus\a.txt This makes path comparison difficult as I have different strings (the extra \'s). I've tried os.path.normpath(line_reading_in_from_file) but I still get the funky \\ paths. How can I read the paths with an r'path' like meaning? Thanks, Brad From deets at nospam.web.de Wed Mar 12 07:32:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Mar 2008 12:32:48 +0100 Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> Message-ID: <63ptavF28u3flU2@mid.uni-berlin.de> xkenneth wrote: > Hi All, > > Quick question. I've got an XML schema file (XSD) that I've > written, that works fine when my data is present as an XML file. > (Served out by apache2.) Now when I call python as a cgi script, and > tell it print out all of the same XML, also served up by apache2, the > XSD is not applied. Does this have to do with which content type i > defined when printing the xml to stdout? Who's applying the stylesheet? The browser, some application like XmlSpy or what? Diez From hellogaurang at gmail.com Thu Mar 6 02:03:28 2008 From: hellogaurang at gmail.com (hellogaurang at gmail.com) Date: Wed, 5 Mar 2008 23:03:28 -0800 (PST) Subject: Hi Message-ID: Hello can u plz tell how to send and read msg from device(telit-863-GPS) and the coding is in python. if this can happen then plz send the source code to my mail account From deets at nospam.web.de Wed Mar 12 18:31:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Mar 2008 23:31:30 +0100 Subject: How to parse this timestamp? In-Reply-To: References: Message-ID: <63r3u7F283eg1U1@mid.uni-berlin.de> gnu.gcc.help schrieb: > I've got timestamps in a file that look like: > > [19-Aug-2007 07:38:43+216ms NZST] > > How can I parse them? I don't see any way to build a strftime() > format string that can handle the +216ms part. The best I can see is > tearing it all apart with a regex, but I'm trying to avoid that pain > if I can. > > (PS: I have no clue why google groups thinks it should put > "gnu.gcc.help" on the from line) > Then don't use the regexes. Use string.split to separate the string on the +, then parse the left part with strptime, and usp pytz and datetime.timedelta to do the rest. Diez From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:34:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:34:48 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <13t6c58lu2iog2a@corp.supernews.com> On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > I'm also a bit baffled by people who put a comment at the top of every > file that tells you what the filename is. [snip rant] You've never printed out a source file on pieces of dead tree to read on the train on the way home, or in bed or the bath? Yes, some editors will print a header or footer showing the file name, but not all will, or are configured to do so. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 19:03:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 23:03:32 -0000 Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> <13u3660kfnhq412@corp.supernews.com> <74cdd195-2bfa-4548-a16e-bf14c6b07b50@p73g2000hsd.googlegroups.com> Message-ID: <13u5ra4fdbp7235@corp.supernews.com> On Thu, 20 Mar 2008 10:26:14 -0700, Jim wrote: > The program is my first and I'm not a programmer so it will take me some > time to get your recommendation to work. So far the program runs after I > added code based on your example but the program still aborts and none > of the code ("Temporary failure, Skip/Halt/try Again?" or "Unknown > response, boo hiss to you!") in your example is displayed. Try replacing the line: except URLError, e: with: except urllib2.URLError, e: and see if that helps. -- Steven From jgelfand01 at gmail.com Tue Mar 25 17:32:23 2008 From: jgelfand01 at gmail.com (jgelfand) Date: Tue, 25 Mar 2008 14:32:23 -0700 (PDT) Subject: _tkinter fails when installing Python 2.4.4 Message-ID: I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but I get the following error message when I run "make": building '_tkinter' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ usr/local/yosi/Python-2.5.2/Modules/_tkinter.o gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ usr/local/yosi/Python-2.5.2/Modules/tkappinit.o gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so *** WARNING: renaming "_tkinter" since importing it failed: build/ lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents Any suggestions / ideas as to what is going wrong? I don't get any other warnings or errors on the other modules. Thanks -- Yosi From gowricp at gmail.com Tue Mar 18 22:10:48 2008 From: gowricp at gmail.com (Gowri) Date: Tue, 18 Mar 2008 19:10:48 -0700 (PDT) Subject: parsing json output Message-ID: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Hi, I have a service running somewhere which gives me JSON data. What I do is this: import urllib,urllib2 import cjson url = 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/ tbedi/requestDetails' params = {'format':'json'} eparams = urllib.urlencode(params) request = urllib2.Request(url,eparams) response = urllib2.urlopen(request) # This request is sent in HTTP POST print response.read() This prints a whole bunch of nonsense as expected. I use cjson and am unable to figure out how to print this json response and I guess if I can do this, parsing should be straightforward? doing a cjson.decode(str(repsonse)) does not work. In what form is this data returned and how do I print it and later pass it on to another client browser? Typing http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails in my browser returns valid json data. Regards, Gowri From sam at mas.pl Wed Mar 19 12:59:40 2008 From: sam at mas.pl (sam) Date: Wed, 19 Mar 2008 17:59:40 +0100 Subject: Prototype OO Message-ID: Some time ago (2004) there were talks about prototype-based languages and Prothon emerged. Can someone tell me why class-based OO is better that Prototype based, especially in scripting langage with dynamic types as Python is? Here are some links: http://c2.com/cgi/wiki?PrototypeBasedProgramming http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Class-Based_vs._Prototype-Based_Languages -- UFO Occupation www.totalizm.pl From gh at ghaering.de Sat Mar 29 14:41:12 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 29 Mar 2008 19:41:12 +0100 Subject: Problem with sqlite In-Reply-To: References: Message-ID: <657gq6F2dh3fdU1@mid.uni-berlin.de> Ok, I'll review your code. aiwarrior wrote: > class db: > def __init__(self): #constructor > conn = sqlite3.connect('./db.db') > conn.isolation_level = None Autocommit mode is mostly for newbies who forget to call commit. Unfortunately, newbiews find enough other ways to shoot themselves in the foot. So, in retrospect, maybe I should not have added that feature to pysqlite ;-) > self.cursor = conn.cursor() > try: > self.cursor.execute("CREATE TABLE database > (album,filepath)" ) > except: > pass try: except: pass without catching *specific* exceptions is generally a very bad idea. If you're doing something stupid, or another error happens than the one you want to ignore, you will never know this way. > def add_entry( self, eone , etwo ): #Add entry to database > self.cursor.execute( "INSERT INTO database (album,filepath) > VALUES (?,?)", ( eone , etwo ) ) > return 1 #TODO: exception handler > > def get_mediadb( self, print_db = False ): > self.cursor.execute( 'SELECT * FROM database' ) > if (print_db == True): > print self.cursor.fetchall() The if clause can be written as just "if print_db:". > def get_value( self, column ): > self.cursor.execute( "SELECT %s FROM database" % column ) > for n in self.cursor: > print n > > def destructor(self): > self.cursor.close() Just FYI, Python's "destructor" method is called "__del__", not "destructor". > def walking_and_filling(db): > pass > > > if __name__ == "__main__": > db = db() > #walking_and_filling( db ) > for root, dirs, files in os.walk( '''foo_path/''', > topdown=False ): > for name in files: > joined = os.path.join(root, name) > if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): > try: > audio = MP3 (joined, ID3=EasyID3 ) > print (audio['album']) > db.add_entry( joined, audio['album'] ) > except: > pass Now, this try: except: pass is most probably hiding the real error That leads to the insert failing. Because you just ignored any errors, you will never now what exactly went wrong here. > db.get_mediadb( print_db=True ) > > > When i execute this the database doesn't get filled with anything and > the program stays running in memory for ever. [...] HTH, -- Gerhard From hvendelbo.dev at googlemail.com Fri Mar 7 09:53:36 2008 From: hvendelbo.dev at googlemail.com (hvendelbo.dev at googlemail.com) Date: Fri, 7 Mar 2008 06:53:36 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: On Mar 6, 9:17 pm, Luis M. Gonz?lez wrote: > On 6 mar, 11:27, Pierre Quentel wrote: > > > > > Hi, > > > I would like to know if there is a module that converts a string to a > > value of the "most probable type" ; for instance : > > - if the string is "abcd" the value is the same string "abcd" > > - string "123" : value = the integer 123 > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > = the float -1.23 > > - string "2008/03/06" (the format is also locale-dependant) : value = > > datetime.date(2008,03,06) > > > Like in spreadsheets, special prefixes could be used to force the > > type : for instance '123 would be converted to the *string* "123" > > instead of the *integer* 123 > > > I could code it myself, but this wheel is probably already invented > > > Regards, > > Pierre > >>> def convert(x): > > if '.' in x: > try: return float(x) > except ValueError: return x > else: > try: return int(x) > except: return x > > >>> convert('123') > 123 > >>> convert('123.99') > 123.98999999999999 > >>> convert('hello') > > 'hello' Neat solution. The real challenge though is whether to support localised dates, these are all valid: 20/10/01 102001 20-10-2001 20011020 From mensanator at aol.com Sun Mar 23 00:36:10 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 22 Mar 2008 21:36:10 -0700 (PDT) Subject: List question References: <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> <13ubd90qe74ii58@corp.supernews.com> Message-ID: On Mar 22, 8:40?pm, Dennis Lee Bieber wrote: > On Sat, 22 Mar 2008 14:55:39 -0700 (PDT), Zentrader > declaimed the following in comp.lang.python: > > > is funny and not mean. ?In the words of whoever it was in "Gone With > > The Wind", frankly I don't give a damn (except to not mislead relative > > ? ? ? ? Rhett Butler, I believe (I only know two characters by name, You don't remember Ashley? I guess that's only half a name. > and > since the line as I recall it is "Frankly, Scarlett, I ..." it couldn't > have been her [Scarlett] speaking) > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From grante at visi.com Sun Mar 2 10:21:02 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 15:21:02 -0000 Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> Message-ID: <13slheuos7u6afa@corp.supernews.com> On 2008-03-02, Gif wrote: > sorry for acting like a fool but this is just to weirdly easy > that i can't get to work. i've written a small web server in > another language and this is more like copying code. i already > have everything figured out, except this one but noone seems > either willing or capable of helping me. Because you don't seem either willing or capable of describing your problem in enough detail to allow anybody to help you. Post a small program that demonstrates the "problem". Describe precisely how that program fails to do what you want it to. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From sjmachin at lexicon.net Sat Mar 22 18:58:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 15:58:09 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: <7d25f3c5-8dab-4d1a-a825-897299fd5fe9@i12g2000prf.googlegroups.com> On Mar 23, 7:27 am, sgharvey wrote: > ... and by works, I mean works like I expect it to. You haven't told us what you expect it to do. In any case, your subject heading indicates that the problem is 99.999% likely to be in your logic -- the converse would require the result of re.compile() to retain some memory of what it's seen before *AND* to act differently depending somehow on those memorised facts. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: > If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. > If I try to match every pattern to one line at a time, only one > pattern will match. > > What am I not understanding about re.search? Its behaviour is not contingent on previous input. The following pseudocode is not very useful; the corrections I have made below can be made only after reading the actual pastebin code :- ( ... you are using the name "pattern" to refer both to a pattern name (e.g. 'setting') and to a compiled regex. > Doesn't match properly: > > # Iterate through each pattern for each line > for line in lines: > for pattern in patterns: you mean: for pattern_name in pattern_names: > # Match each pattern to the current line > match = patterns[pattern].search(line) you mean: match = compiled_regexes[pattern_name].search(line) > if match: > "%s: %s" % (pattern, str(match.groups()) ) you mean: print pattern_name, match.groups > > > _Does_ match properly: > [snip] > > > Related code: > The whole src http://pastebin.com/f63298772 This can't be the code that you ran, because it won't even compile. See comments in my update at http://pastebin.com/m77f0617a By the way, you should be either (a) using *match* (not search) with a \Z at the end of each pattern or (b) checking that there is not extraneous guff at the end of the line ... otherwise a line like "[blah] waffle" would be classified as a "section". Have you considered leading/trailing/embedded spaces? > regexen and delimiters (imported into whole src) http://pastebin.com/f485ac180 HTH, John From stargaming at gmail.com Tue Mar 25 09:20:50 2008 From: stargaming at gmail.com (Stargaming) Date: 25 Mar 2008 13:20:50 GMT Subject: Need help with OptionParser References: <0a225d25-c544-49d9-9e56-8ecd2d0f7928@s13g2000prd.googlegroups.com> Message-ID: <47e8fc32$0$1915$9b622d9e@news.freenet.de> On Tue, 25 Mar 2008 05:42:03 -0700, hellt wrote: [snip] > usage = "usage: %prog [options]" > parser = OptionParser(usage) > parser.add_option("-f", "--file", dest="filename", > help="executable filename", > metavar="FILE") > parser.add_option("-b", "--bighosts", > action="store_true", dest="bighosts", default=False, > help="with big hosts [default: %default]") > (options, args) = parser.parse_args() > if not options.bighosts: > print parser.print_usage() FWIW you should perhaps give a special error message rather than the generic help (something like "you need to specify bighosts, see --help for details"). If possible, you should use `args` rather than an option (they are, well, optional). But if your program takes a lot of mandatory arguments, using options in order to mix them at will might be fine. HTH, From gagsl-py2 at yahoo.com.ar Sun Mar 30 18:32:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 19:32:39 -0300 Subject: Build complete, now I just need to "install" it... References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 12:04:10 -0300, axl escribi?: > I'm going to be adding some features for a python-project with > external modules written in C. However, if I build modules with my > MSVS 2008 compiler (from the Windows SDK), they won't load in Python > 2.5.2, which is built with MSVS 2003. > > Since I don't have access to MSVS 2003 I need to rebuild Python using > MSVS 2008 in order for the binaries to go along. > > For starters, I cloned the PCbuild8 folder and made whatever changes > needed to be able to build the core and executable. I then pulled down > all the various external dependencies and made the same adjustments to > those. After quite a while I've managed to build everything apart from Which changes are those? I can build Python straight from the svn sources. > But, my problem is that the install scripts, i.e. "python setup.py > install" wants to go through the build steps again, but since those > don't work on Windows, or at least not with my setup, I can't put > together a complete package. The MSI package generation is at Tools\msi in the source tree. There are a few preliminary steps that must be done (only once) before successfully building the installer, you'll notice as you go (the script will tell you what's missing; a .rc file has to be compiled, as far as I remember). Would be nice if you take note of them so one can write down the proper build sequence. -- Gabriel Genellina From exxfile at hotmail.com Mon Mar 24 15:28:58 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 12:28:58 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> Message-ID: On Mar 24, 12:18?pm, George Sakkis wrote: > On Mar 24, 3:13 pm, pythonnubie wrote: > > > > > > > > > i ?have ?come across my first exeption using randrange . The exeption > > > > is " no such ?attribute " in ?module random > > > > > platform ?is xp ?home ?and the python ?build is activestate 2.5 > > > > Welcome aboard! > > > > There's definitely a randrange function in the random module, so > > > something else must be wrong. To get the most out of this list and > > > minimize wasted bandwidth, the most effective way usually consists of > > > copying and pasting: > > > 1. The offending code (or just the relevant part if it's too big). > > > 2. The full traceback of the raised exception. > > > > Regards, > > > George > > > Hwere is the complete traceback ! >>> The word is: ?index > > > Traceback (most recent call last): > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 307, in RunScript > > ? ? debugger.run(codeObject, __main__.__dict__, start_stepping=0) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \__init__.py", line 60, in run > > ? ? _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \debugger.py", line 631, in run > > ? ? exec cmd in globals, locals > > ? File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, > > in > > ? ? import random > > ? File "F:\Documents and Settings\Mark\My Documents\random.py", line > > 13, in > > ? ? distributions on the real line: > > AttributeError: 'module' object has no attribute 'randrange' > > > Why ?would it say ?it can't find the function ? > > Because you named your file 'random.py' and it shadows the standard > random module! Change the name to something else, say foo.py, and try > it again. > > George- Hide quoted text - > > - Show quoted text - From paul.hermeneutic at gmail.com Tue Mar 11 17:38:54 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 11 Mar 2008 16:38:54 -0500 Subject: SOAP access to SharePoint Message-ID: <1205271534.4382.5.camel@localhost.localdomain> Has anyone successfully accessed a Microsoft SharePoint WSS using Python? No, not IronPython. I need for this to be able to run on all machines the customer might choose. Which libs are you using? ZSI, SOAPpy, soaplib, ??? http://wiki.python.org/moin/WebServices From __peter__ at web.de Sat Mar 29 09:03:05 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Mar 2008 14:03:05 +0100 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Wikipedia doesn't believe that M-D is the primary or most common name, > and the link you give redirects to "Taxicab distance". Googlefight > agrees: "Taxicab distance" is more than twice as common, and "rectilinear > distance" more than five times as common. Could it be that there are many documents containing both taxicab and distance that have nothing to do with the "taxicab distance"? Searching with quotes around the search term google advertises about 936 results for "taxicab distance" 6930 for "rectilinear distance" 38200 for "manhattan distance" > The very name is New York-centric, just as much as if the English called > the science of acoustics "Big-Ben-onics" in reference to the peals of Big > Ben's clock. I had thought I had pointed that out with a little gentle > understatement. Whether you like a term and agree with its (alleged) bias or if it's in common use are two different questions. I think Robert addressed the latter while your answer implied the former. Peter From mensanator at aol.com Mon Mar 3 16:47:42 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 13:47:42 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> Message-ID: <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> On Mar 3, 2:49?pm, Carl Banks wrote: > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > > > Notice anything funny about the "random" choices? > > > import sympy > > import time > > import random > > > f = [i for i in sympy.primerange(1000,10000)] > > > for i in xrange(10): > > ? f1 = random.choice(f) > > ? print f1, > > ? f2 = random.choice(f) > > ? print f2, > > ? C = f1*f2 > > ? ff = None > > ? ff = sympy.factorint(C) > > ? print ff > > > ## ?7307 7243 [(7243, 1), (7307, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > As in, "they're NOT random". > > > The random number generator is broken by the sympy.factorint() > > function. > > > Random.choice() works ok if the factorint() function commented out. > > > ## ?6089 1811 None > > ## ?6449 1759 None > > ## ?9923 4639 None > > ## ?4013 4889 None > > ## ?4349 2029 None > > ## ?6703 8677 None > > ## ?1879 1867 None > > ## ?5153 5279 None > > ## ?2011 4937 None > > ## ?7253 5507 None > > > This makes sympy worse than worthless, as it f***s up other modules. > > Dude, relax. > > It's just a bug--probably sympy is messing with the internals of the > random number generator. ?It would be a simple fix. ?Instead of > b****ing about it, file a bug report. ? I did. > Or better yet, submit a patch. I would if I knew what the problem was. I posted it here because someone recommended it. I'm simply un-recommending it. Those who don't care needn't pay any attention. Those who do should be glad that faults are pointed out when found. > > Carl Banks From kyosohma at gmail.com Mon Mar 17 09:45:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 17 Mar 2008 06:45:32 -0700 (PDT) Subject: wxPython graphics query (newbie) References: Message-ID: On Mar 17, 7:03 am, Thomas G wrote: > I am exploring wxPython and would be grateful for some help. > > It is important to me to be able to slide words and shapes around by > dragging them from place to place. I don't mean dragging them into a > different window, which is what 'Drag and Drop' has come to mean, just > moving them around within a canvas-like space. > > This is easy using Tkinter. Can anybody offer me a tiny, very simple > example of how it would be done in wxPython, please? > > To make sure I convey what I'm looking for, here is what it looks like > using Tkinter, written very simply. What I'm looking for is the same, > quite simple functionality expressed in wxPython, again written very > simply so that I can easily understand it. > > #!/usr/bin/python > from Tkinter import * > > root = Tk() > > global canv > > def makeFrame(root): > global canv > canv = Canvas (root, height = 200, width = 350) > canv.create_text(100, 100, text='drag me', tags=('movable')) > > canv.tag_bind('movable', '', slide) #B1-motion is a drag > with left button down > canv.pack() > > def slide (event): > ''' > triggered when something is dragged on the canvas - move thing under > mouse ('current') to new position > ''' > newx = event.x > newy = event.y > canv.coords('current', newx, newy) > > makeFrame(root) > root.mainloop() > > Many thanks in advance > > -- Thomas Green Hmmm...I'm not sure how to do that. Please post this same question to the wxPython user's group. They'll know if anyone does: http://wxpython.org/maillist.php Mike From ilias at lazaridis.com Sun Mar 9 05:24:32 2008 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 9 Mar 2008 01:24:32 -0800 (PST) Subject: Trac - Does it make sense to keep http://trac.edgewall.org/ticket/4315 open? Message-ID: Response to message [1] on trac.devel (as I cannot write there, due to an informally applied censorship) Mr. Boos: "I left that ticket open simply to avoid having someone to reopen it over and over..." (note to reader: this someone is me) Mr. Boos, the ticket status should reflect reality. So, if reality says "the ticket is open", no one can (should" close it. The essens of the ticket is, that you should trust you own results. You should use your development version, in order to obtain feedback. Of course I understand (seeing the terrible processes of the team), that you distrust your own results, prefering to let user do the dirty work of development-version-usage. Your inability to follow even the most rational suggestions subjecting development-processes, e.g. this one: http://trac.edgewall.org/ticket/6614#comment:36 will lead (together with the terrible quality of the trac source-code base) soon to an even more stucked development progress. Be assured that users see this (although they don't say much, like me). Do you actually realize that you're working since over a year on 0.11? Nothing is more fun that to watch the trac project running into one after another problem during development. At least you give other teams a good example of "how to ruine a good open-source product". http://case.lazaridis.com/wiki/TracAudit - To readers: The project hunts since months a memory-leak - without success. I'm wondering that python makes so much trouble in finding it. Seems to be another very fundamental reason to leave this "joke of a language" (python). - [1] http://groups.google.com/group/trac-dev/msg/1cbcaf2b5fdc8abe From: Christian Boos Jeroen Ruigrok van der Werven wrote: > Does it make sense to keep http://trac.edgewall.org/ticket/4315 open? I left that ticket open simply to avoid having someone to reopen it over and over... That ticket is a bit useless in that it has anyway always been the policy of the project to run the latest stable release. And that works quite well in practice. I imagine t.e.o would already be running 0.11b1 now, if we didn't have those memory issues. As for documenting the blocker issues, doing that directly on the milestone page is more effective anyway. So I'd say let's just not make a fuss about this one and we'll close it once t.e.o gets upgraded to 0.11. -- Christian From deets at nospam.web.de Sat Mar 29 18:48:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 23:48:26 +0100 Subject: Installing simplejson issues In-Reply-To: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> Message-ID: <657v9rF2eatagU1@mid.uni-berlin.de> blwatson at gmail.com schrieb: > I am trying to install the twitter python wrapper...I got that > installed just fine, but am having serious troubles getting the > simplejson package to install. I need help diagnosing where this is > failing. I am trying to use: > > http://pypi.python.org/pypi/simplejson > > and I run "python setup.py build" and then "python setup.py install", > which both seem to work just fine. > > I tried running with easy_install, but that too is not working. I end > up with: > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > in my: > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > packages/ > > I am on Mac OS X 10.5. Any help would be greatly appreciated. Go to the turbogears file section and download an appropriate version of simplejson: http://www.turbogears.org/download/filelist.html I presume sj-1.7.4 is sufficient. Alternatively, be gentle to your unixish OS that OS X is, and install XCode. Which will install the whole GCC chain, making your OS a respected member of OS-community - as every system should be able to compile C-code, in which itself has been written. Then the install should work as well. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:44:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:44:31 -0000 Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: <13t3dpvaiivm46@corp.supernews.com> On Fri, 07 Mar 2008 09:49:58 -0800, Krishna wrote: > I am more interested in knowing about the first argument ('self'), what > does it hold to allow the evaluation of the method, take the example you > gave, 'self.a' as Rvalue inside the method, how and why is this allowed, "self" is treated as an argument like any other argument, except that when you call a method on an instance Python automatically provides the self for you. Consider the following piece of code: >>> class Parrot(object): ... def squawk(self, n): ... return "spam " * n ... >>> instance = Parrot() >>> instance.squawk(3) 'spam spam spam ' >>> Parrot.squawk(instance, 3) 'spam spam spam ' In the first call, I call the squawk() method from the instance, and Python automatically fills in the self argument. In the second call, I call the squawk() method from the class. Since the class doesn't know what instance I'm using, I have to manually provide the self argument. But inside the method, self is just a name in a namespace, like any other name. It's not special. You can do anything you like to it. You can even re-assign to it, or delete it: >>> class Spam(object): ... def spam(self): ... print "I am", self ... self = "foo" ... print "Now I am", self ... >>> x = Spam() >>> x.spam() I am <__main__.Spam object at 0xb7f5192c> Now I am foo >>> x <__main__.Spam object at 0xb7f5192c> > when the same 'self.a' is not allowed as the default argument, It isn't that self.a is "not allowed". Python doesn't contain any code that says "if the default value contains "self", raise an error. You can prove that for yourself: >>> def foo(x=self): ... return x ... Traceback (most recent call last): File "", line 1, in NameError: name 'self' is not defined >>> >>> self = 2 >>> def foo(x=self): ... return x ... >>> foo() 2 > considering the fact that I have already specified 'self' as first > argument, only after whose evaluation, I believe would the next > statement (k = self.a, in def func(self, k = self.a) ) gets evaluated You believe wrong. You've already been told that the function default "k=self.a" is evaluated when the method is compiled, not at runtime. Since "self" doesn't exist at compile time, it is an error. There is no way to create a reference to a class instance before the class is even defined. -- Steven From sjmachin at lexicon.net Wed Mar 19 17:48:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 14:48:37 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> Message-ID: <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> On Mar 19, 10:08 am, sturlamolden wrote: > On 18 Mar, 23:45, Arnaud Delobelle wrote: > > > > def nonunique(lst): > > > slst = sorted(lst) > > > dups = [s[0] for s in > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > > return [dups[0]] + [s[1] for s in > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > Argh! What's wrong with something like: > > > def duplicates(l): > > i = j = object() > > for k in sorted(l): > > if i != j == k: yield k > > i, j = j, k > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) > as opposed to ours which are O(N log N). I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, and is IMHO more readable than Paul's. From hdante at gmail.com Sun Mar 30 07:41:56 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 04:41:56 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: On Mar 30, 2:35 am, "Gabriel Genellina" wrote: > En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: > > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > > if x ? 0: > > ?y ? s: > > if y ? 0: f1(y) > > else: f2(y) > > Fine if you have the right keyboard... Try to write APL with a standard > keyboard :) > > -- > Gabriel Genellina My sugestion considered using standard keyboards (hint: read again). From fossks at cox.net Sat Mar 8 17:34:28 2008 From: fossks at cox.net (Kevin) Date: Sat, 8 Mar 2008 14:34:28 -0800 Subject: Fwd: [PyQt] Popen + poll & pid References: <2AB85B94-D410-4409-9F4E-5008E2EDB76E@cox.net> Message-ID: Hi, I sent the question below to the wrong list. I was wondering if someone here could help? Kevin Sent from my iPhone Begin forwarded message: > From: Kevin > Date: March 8, 2008 11:53:39 AM PST > To: "pyqt at riverbankcomputing.com" > Subject: [PyQt] Popen + poll & pid > > I've been trying to use the poll and pid attributes of popen to > determine if mplayer is finished playing an audio track. I've tried > using popen, popen2, popen3, etc but it tells me that there is no > poll or PID module. > > Could anyone help me with a proper method to determine if a process > is running or ended so that I can move to the next track and start > another iteration? > > Either that or does someone know how to change audio cd tracks in > mplayer slave mode? ;) > > Kevin > > > Sent from my iPhone > _______________________________________________ > PyQt mailing list PyQt at riverbankcomputing.com > http://www.riverbankcomputing.com/mailman/listinfo/pyqt -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Thu Mar 13 19:32:43 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 13 Mar 2008 16:32:43 -0700 (PDT) Subject: Spaces in path name References: Message-ID: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> On Mar 13, 5:16?pm, "David S" wrote: > Hi, > > I have some code in which I have to change some path names to get it to > work. The original code seems to have assumed that path names would not have > any embedded spaces. > > I am not sure how to write the following line so when used in my script the > path will be found. > > ANT_CMD ?= r'C:\Program Files\apache-ant-1.7.0\bin\ant' Try ANT_CMD = r'"C:\Program Files\apache-ant-1.7.0\bin\ant"' > > Regards, > David From timr at probo.com Fri Mar 21 00:46:14 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Mar 2008 04:46:14 GMT Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: Christian Heimes wrote: > >Yes, it sounds like a good idea. The low hanging fruits (aka easy tasks) >could be implemented for 2.6 and 3.0. The more complex tasks may have to >wait for 2.7 and 3.1 I thought there wasn't going to be a 2.7... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From inq1ltd at inqvista.com Thu Mar 27 18:08:05 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 27 Mar 2008 18:08:05 -0400 Subject: python program deleted In-Reply-To: References: Message-ID: <200803271808.06157.inq1ltd@inqvista.com> py users, I developed a python program and used py2exe to create the exe. I zip the entire package and email it to my clients. Some clients get the zip file, unzip the package and everything works fine. And some clients get my email with an icon attached which has the correct filename but the size is 8k when it should be about 5 mb. I've renamed the file without the zip ext. and tried other renaming schemes without success. Has anyone had this experience? Any ideas on how to solve this problem. jim-on-linux From egbert.bouwman at hccnet.nl Sun Mar 9 11:38:10 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Sun, 9 Mar 2008 16:38:10 +0100 Subject: for-else In-Reply-To: References: <20080308152034.GA12009@hccnet.nl> Message-ID: <20080309153810.GA16012@hccnet.nl> On Sat, Mar 08, 2008 at 04:15:31PM -0500, Terry Reedy wrote: > > I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. > I admire the elegance of your examples and your explanation. I will keep a copy of it in my Beazley, for I am afraid I have to read it again. As for orwellian, I must admit that I was quite happy when I thought of using that word, but that it was not my luckiest thought. But I have to persist in my malice. In the following snippet it is not at all clear to the naive programmer (me) that the else refers to an iterator_is_exhausted condition, whatever logical explanation you may offer. . for each_item in item_list: . do_something() . else: . do_else() My temporary solution will be to accompany this else with an appropriate comment: # exhausted e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From deets at nospam.web.de Sun Mar 16 19:49:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 00:49:33 +0100 Subject: Advantage of the array module over lists? In-Reply-To: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> References: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> Message-ID: <645q0hF28fnk3U1@mid.uni-berlin.de> sturlamolden schrieb: > On 13 Mar, 20:40, Tobiah wrote: >> I checked out the array module today. It claims that >> arrays are 'efficient'. I figured that this must mean >> that they are faster than lists, but this doesn't seem >> to be the case: >> >> ################ one.py ############## >> import array >> >> a = array.array('i') >> >> for x in xrange(10000000): >> a.append(x) > > > Lists are better optimized for appending to the end. Python lists are > implemented as arrays of pointers, with a few empty slots at the > end. > > Arrays are contigous memory buffers. They provide faster read-write > access, particularly for chunks of data, but are slower at resizing. I doubt that. AFAIK both arrays and lists are continuous memory-areas, that double (at least to a certain threshold or so) when reaching the capacity limit. lists are of type PyObject* of course, whereas arrays are not, instead they are of their respective primitive type, making them more memory efficient. Diez From bronger at physik.rwth-aachen.de Wed Mar 19 04:41:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 19 Mar 2008 09:41:10 +0100 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> Message-ID: <87k5jzumvt.fsf@physik.rwth-aachen.de> Hall?chen! wesley chun writes: > http://it.slashdot.org/it/08/03/18/1633229.shtml > > it was surprising and disappointing that Python was not mentioned > *anywhere* in that article but when someone replied, it sparked a > long thread of post-discussion. Well, not because I like Python so much, but I find this blog entry highly unoriginal. Browsing through Wikipedia gives more insight ... Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From ggpolo at gmail.com Tue Mar 25 18:13:00 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 25 Mar 2008 19:13:00 -0300 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: 2008/3/25, Dark Wind : > Hi, > > In most of the languages ^ is used for 'to the power of'. In python we have > ** for that. But what does ^ do? It is bitwise xor. Some more information can be found at http://docs.python.org/ref/bitwise.html > I could not get it just by using it ... some examples are: > 1^1 returns 0 > 2^2 returns 0 > 1^4 returns 5 > 4^1 returns 5 > 3^5 returns 6 > 5^3 returns 6 ...... > > just curious > > Thank you > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From deets at nospam.web.de Sat Mar 1 12:53:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 18:53:26 +0100 Subject: tcp functions In-Reply-To: References: Message-ID: <62tjgmF24ui98U1@mid.uni-berlin.de> Gif schrieb: > is there a module for tcp functions or any other quick way to connect, > listen, send and recieve from tcp? > thanks in advance Reading the docs helps - hint: module "socket". Diez From clodoaldo.pinto at gmail.com Tue Mar 25 10:58:30 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Tue, 25 Mar 2008 11:58:30 -0300 Subject: sendmail should throw an exception but does not In-Reply-To: <20080325102113.d8688b7f.darcy@druid.net> References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> <20080325102113.d8688b7f.darcy@druid.net> Message-ID: 2008/3/25, D'Arcy J.M. Cain : > On Tue, 25 Mar 2008 06:39:57 -0700 (PDT) > Clodoaldo wrote: > > I need to know if an email was refused for whatever reason, it makes > > no difference. > > > > The email is sent to an email address that does not exist in a foreign > > domain. I can see in the postfix log that the email was sent and > > bounced with the error code 550. > > > That's the sendmail daemon, not your program. > > > > The problem is that sendmail should throw an exception but it does > > not. And the returned dictionary is empty as if the email was > > accepted. > > > > d = smtpserver.sendmail(sender, recipient, m.as_string()) > > > What this does is connect to your sendmail server and submit the email > for sending. The server accepts the email and queues it up as asked. > No error here. > > > > I guess that the error code returned by the destination mail server is > > not is not forwarded to the client by my mail server. > > > It can't. By the time it finds out that there is a problem you have > already closed the connection to the sendmail server. > > To do what you want you have to connect to the remote server yourself. > This is a more complicated operation and there are still problems. > First of all, your ISP may not allow you to connect to remote mail > servers. Second, some [broken] mail servers will accept your email and > only check and bounce after you have disconnected. > > I'm not sure what you are trying to do but you may want to consider > using an Error-to: header that points to an email robot and manage > bounces asynchronously. Thanks for the objective answer. I'm now reconnected to reality. The problem i'm trying to solve is to check if an email address is valid. That email address is used to register in a site. I'm already doing the confirmation email path. The confirmation email prevents someone to register with a forged email but also prevents those who simple don't know exactly what their email is. Yes the email must be typed twice but still people get the email wrong just because they don't know for sure what it is. I can see it clearly when they mistype the correct domain. It happens that atracting those people is expensive and i can't afford to loose them. Thats why i would like to check the email at registration time. Also those who try to register with a forged email would learn that the email must be confirmed and could then issue a correct email. I guess it is not possible or is too complex because i never saw it done. Regards, Clodoaldo Pinto Neto From Greg Tue Mar 25 11:38:53 2008 From: Greg (Greg) Date: Tue, 25 Mar 2008 16:38:53 +0100 Subject: Creating dynamic objects with dynamic constructor args Message-ID: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> I'd like to create objects on the fly from a pointer to the class using: instance = klass() But I need to be able to pass in variables to the __init__ method. I can recover the arguments using the inspect.argspec, but how do I call __init__ with a list of arguments and have them unpacked to the argument list rather than passed as a single object? ie. class T: def __init__(self, foo, bar): self.foo = foo self.bar = bar argspec = inspect.argspec(T.__init__) args = (1, 2) ??? how do you call T(args)? Thanks. Greg From doug.farrell at gmail.com Thu Mar 20 10:46:38 2008 From: doug.farrell at gmail.com (writeson) Date: Thu, 20 Mar 2008 07:46:38 -0700 (PDT) Subject: Can I dyanmically add Pyro objects to a running Pyro server? Message-ID: Hi everyone, I'm trying to build a distributed system using the code in the examples/distributed_computing2 directory of the Pyro un-tarred distribution. I'm trying to make this generic so one Pyro class can kick off another on mulit-core/multi-cpu/multi-server systems. What I'd like to know is this, after you've got the server.requestloop() running in the Pyro server, is it possible to add objects to the system? As in calling server.connect again with a new class and have the daemon provide access to that. I'm essentially trying to dynamically add Pyro objects to a running Pyro server. Thanks in advance for your help, Doug From martin at v.loewis.de Mon Mar 31 17:45:04 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 31 Mar 2008 23:45:04 +0200 Subject: CTypes, 64 bit windows, 32 bit dll In-Reply-To: References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: <47F15B60.2050306@v.loewis.de> > Crap, no way to make a 32 bit load, even using the wowexec? With WoW64, you can run 32-bit processes on a 64-bit system (as you do all the time). That's all it does. You cannot load a 64-bit DLL into a 32-bit application, or vice versa. If you want to load a 32-bit DLL on Win64, use the 32-bit Python. Regards, Martin From skip at pobox.com Fri Mar 28 10:52:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 28 Mar 2008 09:52:07 -0500 Subject: Summary of threading for experienced non-Python programmers? Message-ID: <18413.1559.451510.750097@montanaro-dyndns-org.local> I'm having trouble explaining the benefits and tradeoffs of threads to my coworkers and countering their misconceptions about Python's threading model and facilities. They all come from C++ and are used to thinking of multithreading as a way to harness multiple CPU cores for compute-bound processing. I also encountered, "Python doesn't really do threads" today. *sigh* I don't need pointers to the relevant documentation sections. A bit of googling didn't turn up much about threading beyond tutorial introductions. I'm looking for something which will explain the rationale for using threads in Python to someone who is experienced with multithreading in other languages (like C/C++). Maybe a compare-and-contrast sort of document? Thanks, Skip From seandavi at gmail.com Wed Mar 26 17:28:20 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 26 Mar 2008 14:28:20 -0700 (PDT) Subject: Line segments, overlap, and bits Message-ID: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> I am working with genomic data. Basically, it consists of many tuples of (start,end) on a line. I would like to convert these tuples of (start,end) to a string of bits where a bit is 1 if it is covered by any of the regions described by the (start,end) tuples and 0 if it is not. I then want to do set operations on multiple bit strings (AND, OR, NOT, etc.). Any suggestions on how to (1) set up the bit string and (2) operate on 1 or more of them? Java has a BitSet class that keeps this kind of thing pretty clean and high-level, but I haven't seen anything like it for python. Thanks, Sean From python.list at tim.thechases.com Tue Mar 4 14:38:05 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Mar 2008 13:38:05 -0600 Subject: Python an Exchange Server In-Reply-To: References: Message-ID: <47CDA51D.3030801@tim.thechases.com> > Hi friends. Someone know how to work with python and exchange > server?. I've used both imaplib[1] and smtplib[2] (in the standard library) for talking successfully with an Exchange server. I don't do much with POP3, but there's also a poplib module[3] in the standard library. I just wrote some imaplib code this morning to work with an existing Exchange mailbox and some smtplib code last week for sending email through an Exchange box. Exchange offers other proprietary functionality, exposed through the MAPI. You might be able to use some of the Win32 functionality in one of the add-on modules for talking with COM objects. -tkc [1] http://docs.python.org/lib/module-imaplib.html [2] http://docs.python.org/lib/module-smtplib.html [3] http://docs.python.org/lib/module-poplib.html From Dominique.Holzwarth at ch.delarue.com Thu Mar 20 09:03:17 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 20 Mar 2008 13:03:17 +0000 Subject: Problem with PARAGRAPH SEPARATOR Message-ID: <8D5970DD46B50A409A0E42BA407964FE0E6A67DA@SGBD012007.dlrmail.ad.delarue.com> Hello everyone I'm doing a transformation with (MSXML) from a xml file to a tex file (actually it's just output format "text" with tex commands inside). The output of the transformation (a big string containg the whole file) contains a so called 'paragraph separator' (unicode: 2029). If I want to pring that string (file) to the std out or a file object then I get a "UnicodeError" saying that the unicode 2029 can't be encoded... Can anyone please tell me how I should handle that paragraph seperator? I must say, that I don't even know WHY my output file has such a character but I'd kinda like to keep it there and just be able to store the string in a file object / print it to console... Thanks in advance Dominique ********************************* This e-mail and any files attached are strictly confidential, may be legally privileged and are intended solely for the addressee. If you are not the intended recipient please notify the sender immediately by return email and then delete the e-mail and any attachments immediately. The views and or opinions expressed in this e-mail are not necessarily the views of De La Rue plc or any of its subsidiaries and the De La Rue Group of companies, their directors, officers and employees make no representation about and accept no liability for its accuracy or completeness. You should ensure that you have adequate virus protection as the De La Rue Group of companies do not accept liability for any viruses De La Rue plc Registered No.3834125, De La Rue Holdings plc Registered No 58025 and De La Rue International Limited Registered No 720284 are all registered in England with their registered office at: De La Rue House, Jays Close, Viables, Hampshire RG22 4BS From jbellis at gmail.com Mon Mar 17 07:44:34 2008 From: jbellis at gmail.com (Jonathan Ellis) Date: Mon, 17 Mar 2008 04:44:34 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <46d77235-b53f-4240-a687-f8026cbd05b1@13g2000hsb.googlegroups.com> On Mar 16, 10:20?am, Barry Hawkins wrote: > I shared the same perception as Bruce; most "keynotes" > and lightning talks were anemic vendor pitches that really gutted the > spirit of what I experienced last year. ? I don't think you can lump the keynotes in with the lightning talks. I had to go check the schedule to see which keynotes were "diamond" ones. I wasn't thinking to myself, "oh, this must be a paid keynote" at the time at all. In fact, the Google one was the most entertaining of all, judging by audience reaction. But the vast majority of the vendor lightning talks were a waste of time, I agree. -Jonathan From Graham.Dumpleton at gmail.com Mon Mar 31 18:13:18 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 31 Mar 2008 15:13:18 -0700 (PDT) Subject: Problem with mod_python/3.3.1 and apache References: Message-ID: On Apr 1, 8:03 am, NccWarp9 wrote: > Hello, > > im using Apache HTTPD 2.2.8 with mod_python/3.3.1 Python/2.4.3 on > Windows and having truble starting pythone, any help would be > appreciated > . > Im getting this error: > > [Mon Mar 31 23:53:03 2008] [error] make_obcallback: could not import > mod_python.apache.\n > 'import site' failed; use -v for traceback > 'import site' failed; use -v for traceback > ImportError: No module named mod_python.apache > [Mon Mar 31 23:53:03 2008] [error] make_obcallback: Python path being > used "['C:\\\\Windows\\\\system32\\\\python24.zip', '', 'c:\\\\xampp\\\ > \python\\\\DLLs', 'c:\\\\xampp\\\\python\\\\lib', 'c:\\\\xampp\\\ > \python\\\\lib\\\\plat-win', 'c:\\\\xampp\\\\python\\\\lib\\\\lib-tk', > 'C:\\\\xampp\\\\apache\\\\bin']". > [Mon Mar 31 23:53:03 2008] [error] get_interpreter: no interpreter > callback found. > [Mon Mar 31 23:53:03 2008] [error] [client 127.0.0.1] python_handler: > Can't get/create interpreter., referer:http://localhost/python/ > [Mon Mar 31 23:53:25 2008] [error] make_obcallback: could not import > mod_python.apache.\n > ImportError: No module named mod_python.apache > > thx See: http://www.modpython.org/pipermail/mod_python/2008-March/025022.html Also search the www.modpython.org site for other discussions/ suggestions in the mod_python mailing list. Graham From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:07:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:07:24 -0300 Subject: Signal problem References: Message-ID: En Thu, 27 Mar 2008 16:27:16 -0300, Fabio Durieux Lopes escribi?: > On daemon.py I have: > > terminate = False > > def signalHandler(signum, frame): > terminate = True > > And my main loop goes like this: > > 'while(not daemon.terminate):' > > When the signal treatment was in the same file as my loop it > worked just fine, and since I've separated it in another file it > stopped working. The SIGALRM treatment, which remains in the same > file, is still working. Any reason why it doesn't treat SIGTERM > anymore? Does it have anything to do with the fact that 'terminate' > is not a class variable? Any ideas? Is "daemon.py" your main entry point? That is, is it the one you execute? In that case, the module is initially imported as "__main__", not as "daemon"; if you "import daemon" from another file, you'll end with TWO different loaded modules for the SAME file (because "daemon" was not in sys.modules, so Python thinks it was not imported yet, and loads it again). A rule might say: Your main script may import anything, but no one may import the main script. -- Gabriel Genellina From castironpi at gmail.com Sat Mar 29 22:42:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 19:42:39 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Message-ID: <44fbc675-8e40-44a5-988f-7d1cdb26c977@m73g2000hsh.googlegroups.com> On Mar 29, 2:11?pm, Gary Herron wrote: > Bryan.Fodn... at gmail.com wrote: > > Hello, > > > I am having trouble writing the code to read a binary string. ?I would > > like to extract the values for use in a calculation. > > > Any help would be great. > > Without having looked at your code an any detail, may I humbly suggest > that you throw it all out and use the struct module: > > ? ?http://docs.python.org/lib/module-struct.html > > It is meant to solve this kind of problem, and it is quite easy to use. > > Gary Herron > > > > > Here is my function that takes in a string. > > > def parseSequence(data, start): > > > ? ? group_num = data[start:start+2] > > ? ? element_num = data[start+2:start+4] > > ? ? vl_field = data[start+4:start+8] > > ? ? length = struct.unpack('hh', vl_field)[0] > > ? ? value = data[start+8:(start+8+length)] > > ? ? pos = start+8+length > > ? ? element = (group_num+element_num) > > > ? ? if element == '\xfe\xff\x00\xe0': > > ? ? ? ? data = value > > > ? ? ? ? while start < length: > > ? ? ? ? ? ? group_num = data[start:start+2] > > ? ? ? ? ? ? element_num = data[start+2:start+4] > > ? ? ? ? ? ? vl_field = data[start+4:start+8] > > ? ? ? ? ? ? length = struct.unpack('hh', vl_field)[0] > > ? ? ? ? ? ? value = data[start+8:(start+8+length)] > > ? ? ? ? ? ? start = start+8+length > > ? ? ? ? ? ? element = (group_num+element_num) > > > ? ? ? ? ? ? if element == '\xfe\xff\x00\xe0': > > ? ? ? ? ? ? ? ? data = value > > > ? ? ? ? ? ? ? ? while start < length: > > ? ? ? ? ? ? ? ? ? ? group_num = data[start:start+2] > > ? ? ? ? ? ? ? ? ? ? element_num = data[start+2:start+4] > > ? ? ? ? ? ? ? ? ? ? vl_field = data[start+4:start+8] > > ? ? ? ? ? ? ? ? ? ? length = struct.unpack('hh', vl_field)[0] > > ? ? ? ? ? ? ? ? ? ? value = data[start+8:(start+8+length)] > > ? ? ? ? ? ? ? ? ? ? start = start+8+length > > ? ? ? ? ? ? ? ? ? ? element = (group_num+element_num) > > ? ? ? ? ? ? ? ? ? ? return element, start, value > > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? return element, start, value > > > ? ? else: > > ? ? ? ? return ?element, pos, value > > > And, here is a sample string (I have split up and indented for > > readability). ?There is an identifier (\xfe\xff\x00\xe0) followed by > > the length of the nested values. > > > '\xfe\xff\x00\xe0\x18\x02\x00\x00 ? ? -length=536 > > ? ? ?\n0q\x00\x02\x00\x00\x001 > > ? ? ?\n0x\x00\x02\x00\x00\x0010 > > ? ? ?\n0\x80\x00\x02\x00\x00\x004 > > ? ? ?\n0\xa0\x00\x02\x00\x00\x000 > > ? ? ?\x0c0\x04\x00\xe8\x01\x00\x00 > > ? ? ?\xfe\xff\x00\xe0p\x00\x00\x00 ? ? -length=112 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x00127.378510918301 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x001 > > ? ? ?\xfe\xff\x00\xe0p\x00\x00\x00 ? ? -length=112 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x0c\x00\x00\x001.629998e-1 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x0023.159729257873 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x004 > > ? ? ?\xfe\xff\x00\xe0t\x00\x00\x00 ? ? ?-length=116 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x10\x00\x00\x001.26285318894435 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x00227.690980638769 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x003 > > ? ? ?\xfe\xff\x00\xe0t\x00\x00\x00 ? ? ?-length=116 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x10\x00\x00\x001.52797639111557 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x00263.433384670643 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x002 ')- Hide quoted text - Binaries can come from computers as from people. Synth sound & graphics. Start structuring primitive binaries: What operation can you run in real-time? I would probably have to learn natural language to make any sense of his keystrokes. Designing interface-first, you want another person to be pressing keys. Can we get Simon to teach us a couple distinct patterns? (That's we teach it; (that means:); no words: that's faster.) Get a couple ring tones, customiz-ing-, and you play a game.) Multi-pad consolled the PC. Can we give keystrokes its own thread? Sadly, our first one: get spatial delay timing up to speed. The sturdy keys (the discretes) have whisper roger that. Watch moving target? over raise riggings. From gagsl-py2 at yahoo.com.ar Tue Mar 4 22:18:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 01:18:09 -0200 Subject: Run Python app at startup References: Message-ID: En Tue, 04 Mar 2008 16:36:03 -0200, SMALLp escribi?: >>> I create simple application. Yust an windows and "compile" it with >>> py2exe. I add registry value >>> reg add >>> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v >>> MyApp /t REG_SZ /d C:\myapp.exe /f' > Program works fine. When i run it it works. Problem is how to make this > aplication start at windows startup. It opens and it closes in my case. Redirect stdout and stderr to some log file so you can inspect it and see the error: cmd /c c:\path\myapp.exe >c:\path\output.log 2>&1 -- Gabriel Genellina From mark.manning at gmail.com Tue Mar 11 09:07:50 2008 From: mark.manning at gmail.com (Mark M Manning) Date: Tue, 11 Mar 2008 06:07:50 -0700 (PDT) Subject: Python Sockets Help References: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> Message-ID: <453eade0-bd48-49e0-bb8e-bad9f5f79478@n77g2000hse.googlegroups.com> That's embarrassingly simple! Thank you very much!! On Mar 11, 4:03 am, bock... at virgilio.it wrote: > On 10 Mar, 23:58, Mark M Manning wrote: > > > > > I need your expertise with a sockets question. > > > Let me preface this by saying I don't have much experience with > > sockets in general so this question may be simple. > > > I am playing with the mini dns server from a script I found online:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt > > > All I want to do is edit this script so that it records the IP > > address. I've seen other examples use the accept() object which > > returns the data and the IP address it is receiving the data from. I > > can't use that in this case but I'm wondering if someone could show me > > how. > > > Here is the socket part of the script: > > > if __name__ == '__main__': > > ip='192.168.1.1' > > print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip > > > udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > udps.bind(('',53)) > > > try: > > while 1: > > data, addr = udps.recvfrom(1024) > > p=DNSQuery(data) > > udps.sendto(p.respuesta(ip), addr) > > print 'Respuesta: %s -> %s' % (p.dominio, ip) > > except KeyboardInterrupt: > > print 'Finalizando' > > udps.close() > > > Thanks to everyone in advance! > > ~Mark > > You already have the address of the sender, is in the 'addr' variable, > as returned by udps.recvfrom. > Change the print statement in sometinmh like: > print 'Respuesta (%s): %s -> %s' % ( addr, p.dominio, ip) > and you will see the sender address in dotted notation printed inside > the (). > > Ciao > ------- > FB From steve at holdenweb.com Sun Mar 2 12:44:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 12:44:13 -0500 Subject: Question on importing and function defs In-Reply-To: <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> Message-ID: TC wrote: > On Mar 2, 11:37 am, Gary Herron wrote: >> TC wrote: >>> I have a problem. Here's a simplified version of what I'm doing: >>> I have functions a() and b() in a module called 'mod'. b() calls a(). >>> So now, I have this program: >>> from mod import * >>> def a(): >>> blahblah >>> b() >>> The problem being, b() is calling the a() that's in mod, not the new >>> a() that I want to replace it. (Both a()'s have identical function >>> headers, in case that matters.) How can I fix this? >>> Thanks for any help. >> Since b calls mod.a, you could replace mod.a with your new a. Like >> this: (Warning, this could be considered bad style because it will >> confuse anyone who examines the mod module in an attempt to understand >> you code.) >> >> import mod >> >> def replacement_a(): >> ... >> >> mod.a = replacement_a >> >> ... >> >> Or another option. Define b to take, as a parameter, the "a" function >> to call. >> >> In mod: >> >> def a(): >> ... >> >> def b(fn=a): # to set the default a to call >> ... >> >> And you main program: >> >> from mod import * >> >> def my_a(): >> ... >> >> b(my_a) >> >> Hope that helps >> >> Gary Herron > > Thanks for the tips, but no luck. This is for a homework assignment, > so there are a couple of requirements, namely that I can't touch > 'mod', and I have to do 'from mod import *' as opposed to 'import > mod'. > > So the first method you suggested won't work as written, since the mod > namespace doesn't exist. I tried a = replacement_a, but b() is still > calling mod's version of a() for some reason. And because I can't > touch mod, I can't use your second suggestion. > > In case I somehow oversimplified, here's the actual relevant code, in > 'mod' (actually called 'search'). The first fn is what I've been > calling a(), the second is b(). > > (lots of stuff...) > > def compare_searchers(problems, header, > searchers=[breadth_first_tree_search, > breadth_first_graph_search, > depth_first_graph_search, > iterative_deepening_search, > depth_limited_search, > astar_search]): > def do(searcher, problem): > p = InstrumentedProblem(problem) > searcher(p) > return p > table = [[name(s)] + [do(s, p) for p in problems] for s in > searchers] > print_table(table, header) > > def compare_graph_searchers(): > compare_searchers(problems=[GraphProblem('A', 'B', romania), > GraphProblem('O', 'N', romania), > GraphProblem('Q', 'WA', australia)], > header=['Searcher', 'Romania(A,B)', 'Romania(O, N)', > 'Australia']) > > > That's the end of the 'search' file. And here's my program, which > defines an identical compare_searchers() with an added print > statement. That statement isn't showing up. > > from search import * > > def compare_searchers(problems, header, > searchers=[breadth_first_tree_search, > breadth_first_graph_search, > depth_first_graph_search, > iterative_deepening_search, > depth_limited_search, > astar_search, best_first_graph_search]): > def do(searcher, problem): > p = InstrumentedProblem(problem) > searcher(p) > return p > table = [[name(s)] + [do(s, p) for p in problems] for s in > searchers] > print 'test' > print_table(table, header) > > compare_graph_searchers() Since you've admitted it's for homework, here are a couple of hints. 1. The b() function is *always* going to try and resolve its references in the namespace it was defined in; 2. The technique you need is most likely known as "monkey patching". When you say "I can't touch mod", that may mean "the source of mod must remain unchanged", which is subtly different. Google is your friend ... Good luck with your assignment. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From _karlo_ at mosor.net Sun Mar 9 13:07:46 2008 From: _karlo_ at mosor.net (Karlo Lozovina) Date: Sun, 09 Mar 2008 18:07:46 +0100 Subject: Returning values from function to Python shell/IPython References: Message-ID: Jorge Vargas wrote: > well after all it's a function so the only ways you can get things out > of it are: > - return a dict with all the objects > - use global (very messy) > - use a decorator to do either of the above. Messy, all of those... :(. > on the other hand have you consider using a proper test package? > instead of inspecting the objects manually from the shell you could > make it all automatic. with assert statements. you could use the std. > python testing modules http://docs.python.org/lib/development.html or > something less verbosed like nose Usually, I'm using standard Python testing modules, but sometimes that is just an overkill. Sometimes I like to do 'exploratory programming', especially in the early phases of development - create a bunch of objects I want to play with and do that from IPython. Only way I found out to somewhat automate this procedure is to have a function that creates all of the test objects, and then raises an exception at the end. IPython starts ipdb, so I can work with the objects the function created (without copying them back to the shell). But this somehow looks too hack-ish for me, so I was wondering if there was an alternative... Anyway, thanks for your answer ;). -- Karlo Lozovina -- Mosor From felciano at gmail.com Mon Mar 24 02:30:11 2008 From: felciano at gmail.com (felciano) Date: Sun, 23 Mar 2008 23:30:11 -0700 (PDT) Subject: Multiline CSV export to Excel produces unrecognized characters? Message-ID: <4f6f122f-45bb-4aa5-b9c9-5eb3e84a0964@i7g2000prf.googlegroups.com> Hi -- Is there a standard way to use the csv module to export data that contains multi-line values to Excel? I can get it mostly working, but Excel seems to have difficulty displaying the generated multi-line cells. The following reproduces the problem in python 2.5: import csv row = [1,"hello","this is\na multiline\ntext field"] writer = csv.writer(open("test.tsv", "w"), dialect="excel-tab", quotechar='"') writer.writerow(row) When opening the resulting test.tsv file, I do indeed see a cell with a multi-line value, but there is a small boxed question mark at the end of each of the lines, as if Excel didn't recognize the linebreak. Any idea why these are there or how to get rid of them? Ramon From Dodin.Roman at gmail.com Tue Mar 18 03:00:41 2008 From: Dodin.Roman at gmail.com (hellt) Date: Tue, 18 Mar 2008 00:00:41 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> Message-ID: <61a3fe08-268e-464e-9ce5-cc00d7a2e3e2@f63g2000hsf.googlegroups.com> On 18 ???, 03:57, sturlamolden wrote: > On 17 Mar, 04:54, WaterWalk wrote: > > > So I'm curious how to read code effectively. I agree that python code > > is clear, but when it becomes long, reading it can still be a hard > > work. > > First, I recommend that you write readable code! Don't use Python as > if you're entering the obfuscated C contest. > > Two particularly important points: > > * If you find yourself thinking this module is too long, that's > probably what it is. Half a page of code per module is fine. Two pages > of code per module can be too much. > > * Comments are always helpful to the reader. > > Second, I recommend getting a good IDE. E.g. pick one of: > > * Microsoft Visual Studio (commercial) > * Eclipse with PyDev and CDT (free) > * SPE (free) > * ActiveState Komodo IDE (commercial) under Microsoft Visual Studio do you mean IronPython instance? From stefan_ml at behnel.de Wed Mar 12 12:58:44 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 12 Mar 2008 17:58:44 +0100 Subject: Python - CGI - XML - XSD In-Reply-To: References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> Message-ID: <47D80BC4.2010307@behnel.de> xkenneth wrote: > On Mar 12, 6:32 am, "Diez B. Roggisch" wrote: >> xkenneth wrote: >>> Hi All, >>> Quick question. I've got an XML schema file (XSD) that I've >>> written, that works fine when my data is present as an XML file. >>> (Served out by apache2.) Now when I call python as a cgi script, and >>> tell it print out all of the same XML, also served up by apache2, the >>> XSD is not applied. Does this have to do with which content type i >>> defined when printing the xml to stdout? >> Who's applying the stylesheet? The browser, some application like XmlSpy or >> what? > > The browser. Well, why should it validate your file? Browsers don't do that just for fun. Stefan From jim at maplesong.com Tue Mar 11 14:00:47 2008 From: jim at maplesong.com (Jim Carroll) Date: Tue, 11 Mar 2008 18:00:47 +0000 (UTC) Subject: Time Zone application after strptime? References: <47D1B703.6040200@egenix.com> Message-ID: M.-A. Lemburg egenix.com> writes: > > On 2008-03-07 22:24, Jim Carroll wrote: > > It's taken me a couple of hours to give up on strptime > > with %Z for recognizing > > time zones... but that still leaves me in the wrong zone: > > > > How can I use the "PST" (or any other time zone name) > > to adjust dt by the > > correct number of hours to get it into UTC before storing in MySQL? > > You could try mxDateTime's parser. It will convert most timezones > into UTC for you: > > >>> from mx.DateTime import * > >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008') > 00' at 2afdc7078f50> > Unfortunately, mx.DateTime also ignores the time zone. If I parse the PST time, and ask for the result's time zone it gives me my local time zone. I have had some luck with dateutil: >>> import dateutil.parse as p >>> p.parse("10:29:52 Feb 29, 2008 PST") datetime.datetime(2008, 2, 29, 10, 29, 52) and if I hand it a list of time zones, it does the right thing >>> zones = {"PST": -8*60*60} p.parse("10:29:52 Feb 29, 2008 PST", tzinfos=zones) datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800)) But I cannot figure out how to get dateutil to use the zoneinfo file that it includes in its own package. It has a zoneinfo-2007k.tar.gz right in the package, and a class to parse the binary zoneinfo, but no clear way to get it to parse its own file and use those during the parsing. From john.jython at gmail.com Tue Mar 25 07:04:37 2008 From: john.jython at gmail.com (john s.) Date: Tue, 25 Mar 2008 04:04:37 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: <5740c4b9-d983-466b-a8b2-5d888f50cb8a@m3g2000hsc.googlegroups.com> On Mar 25, 6:34 am, Bryan Olson wrote: > john s. wrote: > > #/usr/bin/enviro python > > > #Purpose - a dropped in useracct/pass file is on a new server to build > > #a cluster... Alas there are no home directories.. Let me rip through > > #the passfile, grab the correct field (or build it) and use it to make > > #the directory! > > > import os, sys, string, copy, getopt, linecache > > from traceback import format_exception > > > #The file we read in... > > fileHandle = "/etc/passwd" > > srcFile = open(fileHandle,'r') > > srcList = srcFile.readlines() > > > #yah, a for loop that "iterates" through the file of "lines" > > for i in srcList: > > Convention is that the name i is for an integer. just a bit of silly walk on my part in the comment field... > > > strUsr = string.split(i,":") > > theUsr = strUsr[0] > > usrHome = "/expirt/home/",theUsr,"/" > > usrHome = ''.join(usrHome) > > As Ryan noted, os.path is the favored way. > > > print "printing usrHome:",usrHome > > print "is it a dir?: ", os.path.isdir(usrHome) > > #try to test if it's a dir... for some reason this mis-behaves... > > #maybe I'm not thinking about it correctly.. > > > if os.path.isdir(usrHome) != 'False': > > That should always evaluate true. False != 'False'. I think you want: ok... yes I do > > if not os.path.exists(usrHome): > > print "User Home dir doesn't exist creating." > > try: > > os.makedirs(usrHome) > > os.system('/usr/bin/chmod 750 ' + usrHome) > > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) > > except Exception, e: > > print e > > I don't think you want to catch the exception there. If creating the dir > fails, the next bits of code should not execute. ok. I see that now. > > > #OMG, there is directory that happens to already exist! well, > > #love for the queen dictates we provide "due > > #dilligence", (e.g. wipe our asses properly) > > The path could exist but not be a directory. So isadir is slightly better then exists? It felt like it was not working right... (probably because I was double testing the exp I see now) > > > else: > > print "User Home dir exist, checking and fixing permissions." > > sys.exit("Thanks for using pyDirFixr...") > > Given the Unixy nature of your code, you probably want to sys.exit(0) > for success and 1 or 2 for failure. got it. I'm guessing I'm better off with a last line print "g'bye" then sys.exit versus trying both at once... > > Happy hacking, > -- > --Bryan Thanks Bryan :) -John From jkugler at bigfoot.com Wed Mar 26 17:02:04 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 26 Mar 2008 13:02:04 -0800 Subject: Not understanding lamdas and scoping Message-ID: I am trying to use lamdba to generate some functions, and it is not working the way I'd expect. The code is below, followed by the results I'm getting. More comments below that. patterns = ( ('[sxz]$', '$','es'), ('[^aeioudgkprt]h$', '$', 'es'), ('[^aeiou]y$', 'y$', 'ies'), ('$', '$', 's'), ) def z(*a): print a def make_pattern(pattern, search, replace): def compare(word): z(pattern, search, replace) return compare rules = [make_pattern(pattern, search, replace) for (pattern, search, replace) in patterns] print 'make pattern' for rule in rules: rule('noun') rules = [lambda word: z(pattern, search, replace) for (pattern, search, replace) in patterns] print 'lambda/list comprehension' for rule in rules: rule('noun') rules = [] for pattern, search, replace in patterns: rules.append(lambda word: z(pattern, search, replace)) print 'lamda/for loop' for rule in rules: rule('noun') Ouptut: make pattern ('[sxz]$', '$', 'es') ('[^aeioudgkprt]h$', '$', 'es') ('[^aeiou]y$', 'y$', 'ies') ('$', '$', 's') lambda/list comprehension ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') lamda/for loop ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') Of course, in my real code, I'm not calling z(), but a couple of RE search/replace functions (yes, I'm working on the Dive Into Python pluralizer). The first result is obviously the correct one. But the next two don't make sense. Why do all the functions returned by lamda have the last input values? What am I missing? OK, I figured out if I did this: def make_pattern(pattern, search, replace): return lambda word: z(pattern, search, replace) it would give correct results. So, is there some scoping issue with lambda that I'm not seeing? Thanks! j From jeff at schwabcenter.com Tue Mar 18 12:29:00 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 09:29:00 -0700 Subject: Interesting math problem In-Reply-To: References: Message-ID: Marc Christiansen wrote: > sturlamolden wrote: >> On 18 Mar, 00:58, Jeff Schwab wrote: >> >>> def make_slope(distance, parts): >>> if parts == 0: >>> return [] >>> >>> q, r = divmod(distance, parts) >>> >>> if r and parts % r: >>> q += 1 >>> >>> return [q] + make_slope(distance - q, parts - 1) >> Beautiful. If Python could optimize tail recursion, it would even run >> fast. > > This was my first thought, too. But tailcall optimisation wouldn't help > here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets > executed after the recursion. def make_slope(distance, parts, L=()): if parts == 0: return L q, r = divmod(distance, parts) if r and parts % r: q += 1 return make_slope(distance - q, parts - 1, (q,) + L) From pavlovevidence at gmail.com Mon Mar 10 11:25:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Mar 2008 08:25:16 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: On Mar 10, 10:39 am, Gary Herron wrote: > Metal Zong wrote: > > > The operator is and is not test for object identity: x is y is true if > > and only if x and y are the same objects. > > > >>> x = 1 > > > >>> y = 1 > > > >>> x is y > > > True > > > Is this right? Why? Thanks. > > Yes that is true, but it's an implementation defined optimization and > could be applied to *any* immutable type. For larger ints, such a thing > is not true. > >>> x=1000 > >>> y=1000 > >>> x is y > False > > If either is a surprise, then understand that the "is" operator should > probably *never* be used with immutable types. Not quite: None is immutable but it's usually recommended to test for it using is. Carl Banks From steve at holdenweb.com Tue Mar 4 11:09:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 11:09:54 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD7452.2020605@holdenweb.com> mmm wrote: > Oops I did make a mistake. The code I wanted to test should have been > > import copy > print 'Test 1' > pf= '?,?,?,?' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print sqlx1 > > print > print 'Test 2' > sqlx2= copy.copy(sqlx1) > sqlx3= sqlx1 > pf= '?,?,?, ****' > print 'sqlx1= ', sqlx1 > print 'sqlx2= ', sqlx2 > print 'sqlx3= ', sqlx2 > > and the results would > == output > Test group 1 > INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Test group 2 > sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Such that sqlx1 does to change with the re-assignment of 'pf' > And of course immutables such as strings are immutable. Got it now. You still aren't showing us the code you are actually running. Why can't you just paste it into your message? But anyway, you appear to have got the drift now. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From vpalexander at gmail.com Sun Mar 9 06:03:34 2008 From: vpalexander at gmail.com (Vince) Date: Sun, 9 Mar 2008 03:03:34 -0700 (PDT) Subject: Help xxx.py Program Recognition problem References: <224ea046-65c4-40b5-8bd5-ede1c87c801e@e6g2000prf.googlegroups.com> Message-ID: On Mar 8, 9:48 am, crashbangb... at gmail.com wrote: > Hi... > > I was using Python 2.4 and installed 2.5...I copied all my .py files > from the Python24\ root directory to the Python25\ root > directory...when I try to run them by double clicking I get: > "XXXXX.py is not a valid Win32 application"... > > Also, the files do not appear to be associated with python...? > > I can run them from IDLE...but that is it... > > How do I fix this...? > > Thanks.. > > Dave It sounds like you just want the dbl-click Explorer association ... that it should establish by default ... you can use Explorer -> Tools - > Folder Options -> File Types to indicate that you want Idle to launch .py files. Also, probably a silly question, but did you verify the download was the right Win OS version? From thynnus at gNOTmail.com Tue Mar 4 15:29:13 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 04 Mar 2008 20:29:13 GMT Subject: 'normal' shell with curses In-Reply-To: <635drhF25qgqtU1@mid.uni-berlin.de> References: <633s5lF24prinU1@mid.uni-berlin.de> <635drhF25qgqtU1@mid.uni-berlin.de> Message-ID: On 3/4/2008 12:05 PM, Michael Goerz wrote: > Thynnus wrote, on 03/04/2008 08:48 AM: >> On 3/3/2008 9:57 PM, Michael Goerz wrote: >>> Hi, >>> >>> I'm trying to print out text in color. As far as I know, curses is the >>> only way to do that (or not?). So, what I ultimately want is a curses >>> terminal that behaves as closely as possible as a normal terminal, >>> i.e. it breaks lines and scrolls automatically, so that I can >>> implement a function myprint(color, text) that does what print() does, >>> only in color. >> >> You might find the below helpful. Let us know how you make out? >> >> -------- >> >> Python Cookbook >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 >> >> Title: >> Using terminfo for portable color output & cursor control >> >> Description: >> The curses module defines several functions (based on terminfo) that can >> be used to perform lightweight cursor control & output formatting >> (color, bold, etc). These can be used without invoking curses mode >> (curses.initwin) or using any of the more heavy-weight curses >> functionality. This recipe defines a TerminalController class, which can >> make portable output formatting very simple. Formatting modes that are >> not supported by the terminal are simply omitted. >> >> -------- >> > > That looks *extremely* interesting. From a very brief test, it seems to > do exactly what I want! > > Now, Windows seems very problematic for color output. I was using the > following as a test, based on the above recipe: > > term = TerminalController() > while True: > print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled' > print term.render('${RED}Error:${NORMAL}'), 'paper is ripped' > > On Linux, it works fine, on Windows, it just prints white on black > (which is of course what it should do if the terminal doesn't support > color). Can anyone get the Windows cmd.exe terminal to do color? I > already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, > but that doesn't seem to do anything (neither in what I tried yesterday > with the ANSI escape codes, nor with the recipe code now). I also very > briefly tried running it on the winbash shell > (http://win-bash.sourceforge.net/), it didn't have any color either... > So, any way to get color in Windows? > > Michael ipython - http://ipython.scipy.org/ - does a colored Windows interpreter, clue there. From gagsl-py2 at yahoo.com.ar Mon Mar 10 00:49:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 21:49:06 -0700 (PDT) Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: <3ebaa96f-7c93-4aa8-a7d2-13764140831f@k13g2000hse.googlegroups.com> On 10 mar, 01:26, DanielJohnson wrote: > Hi, > > I am trying to solve a genetic algorithm problem where I want to read > a bitvector of very large size (say 10000) and manipulate bits based > on certain algorithms. > > I am a newbie in Python. What data structure are good to read such > huge data set. Are there any built in classes for bit fiddling. > > Every help is greatly appreciated, > > Thanks From tmp1 at viltersten.com Sun Mar 9 14:45:58 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 19:45:58 +0100 Subject: SV: Changing the size of a Button In-Reply-To: References: <63ifhtF277va7U1@mid.individual.net> Message-ID: <63iokhF284p4hU1@mid.individual.net> >> How do i change the size of a Button >> (using Tkinter), other than to set it >> during construction? > In Tkinter, usually the geometry managers > (such as pack) are the ones who size the > widgets. If you run something like: > import Tkinter as tk > > root = tk.Tk() > def change_size(): > b["text"] = "More text" > > b = tk.Button(root, text="Text", command=change_size) > b.pack() > > root.mainloop() Thanks for the answer. Unfortunately, that won't help me at all, since i, apparently, asked the wrong question. Let me refrain myself. What i wish to do is to affect the size of the button but not due to change of text but due to resize of the frame it resides in. This far i've managed to get a callback to a function as the resize occurs and to print the sizes. However, i'd like to assign these values to the button so it always stays the same width as the frame. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From rockxuan at gmail.com Tue Mar 18 03:40:07 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:40:07 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <7fac29d4-753d-481d-b23f-c06c75ebd889@c19g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From tmp1 at viltersten.com Sat Mar 1 15:05:41 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 21:05:41 +0100 Subject: Surprised by the command "del" Message-ID: <62tq9sF24juhrU1@mid.individual.net> I'm reading the docs and at 5.2 the del statement is discussed. At first, i thought i've found a typo but as i tried that myself, it turns it actually does work so. a = ["alpha", "beta", "gamma"] del a[2:2] a Now, i expected the result to be that the "beta" element has been removed. Obviously, Python thinks otherwise. Why?! Elaboration: I wonder why such an unintuitive effect has been implemented. I'm sure it's for a very good reason not clear to me due to my ignorance. Alternatively - my expectations are not so intuitive as i think. :) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From aahz at pythoncraft.com Fri Mar 21 12:49:41 2008 From: aahz at pythoncraft.com (Aahz) Date: 21 Mar 2008 09:49:41 -0700 Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: In article , Nicholas F. Fabry wrote: > >Please clarify how long a novel is? The problem with the modules are >not bugs, they are problems with real world use scenarios that result >in inescabably ugly code without improvements to the module - so the >explanations involve code samples and use cases... so they may be >'long'. Could you suggest a maximum number of (70 char) lines, or an >example of an overly long proposal? I'd suggest starting with a simple example of a problem you see. You may well be up against a design constraint: the datetime module is intended to provide *simple* and reasonably robust handling. There doesn't seem to be a PEP, unfortunately, but you might want to look for the discussion history leading to the including of datetime. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From dickinsm at gmail.com Tue Mar 4 09:39:42 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Mar 2008 06:39:42 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: On Mar 4, 8:46?am, NickC wrote: > The increased number of inaccurate answers with Decimal (31% vs 10%) > is probably due to the fact that it is actually more precise than > float I suspect it has more to do with the fact that 10 is bigger than 2, though I'm not sure I could precisely articulate the reasons why this matters. (A bigger base means a bigger 'wobble', the wobble being the variation in the relationship between an error of 1ulp and a relative error of base**-precision.) Rerunning your example after a getcontext().prec = 16 (i.e. with precision comparable to that of float) gives >>> check_accuracy(Decimal) 310176 Mark From R.Brodie at rl.ac.uk Thu Mar 20 12:45:45 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 20 Mar 2008 16:45:45 -0000 Subject: Problem with PARAGRAPH SEPARATOR References: Message-ID: wrote in message news:mailman.2195.1206027668.9267.python-list at python.org... > Would that mean that the string "myString" is an ascii-string or what? It would mean it was a byte encoded string already, yes. When you try to encode it, Python tries to coerce it to Unicode and it's equivalent to: myString.decode('ascii').encode('iso-8859-1','ignore') That wouldn't explain why printing it gave errors though. From deets at nospam.web.de Thu Mar 20 12:32:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Mar 2008 17:32:01 +0100 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> <13u52hqlbtdv1d1@corp.supernews.com> Message-ID: <64fhscF2bei52U1@mid.uni-berlin.de> Grant Edwards wrote: > On 2008-03-20, Jeff Schwab wrote: > >>>> http://www.google.com/search?q=emacs+python >> >>> Gee. Thanks. >> >> I believe Grant was suggesting that Emacs often serves a similar purpose >> on Unix to what Visual Studio does on Windows, which seemed to be what >> you were asking. When asking about Mac OS X here, you are likely to get >> a lot of generic Unix responses. (Would it have been clearer if he had >> just said "emacs?") > > Don't the normal "run/debug python from inside emacs" methods > work on OS-X? Of course they do. Diez From rcdailey at gmail.com Thu Mar 6 16:15:17 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 6 Mar 2008 15:15:17 -0600 Subject: system32 directory In-Reply-To: <47CFAE7E.6030501@timgolden.me.uk> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> Message-ID: <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden wrote: > > > First thing to do when asking "How do I do X in Python under Windows?" > is to stick -- python X -- into Google and you get, eg: > > > http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html > > which suggests that the win32api module from the pywin32 modules has > the function you need. > > > And sure enough... > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import win32api > >>> win32api.GetSystemDirectory () > 'C:\\WINDOWS\\system32' > >>> > > > TJG > I was aiming to figure out if the standard modules shipped with Python could do this already before I started using 3rd party libraries. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Dodin.Roman at gmail.com Thu Mar 20 07:31:41 2008 From: Dodin.Roman at gmail.com (hellt) Date: Thu, 20 Mar 2008 04:31:41 -0700 (PDT) Subject: Strange behavior of the Eclipse embedded console Message-ID: <23ab07a7-0355-48a7-8bf2-266a56f4efb9@h11g2000prf.googlegroups.com> i've faced with some strangeness while executing this sample: choice = raw_input("your choice: ") print len(choice) when i run this sample in my eclipse console with CPython and print Yes, i have this output 4 #trailing \t is the fourth element but when i use command line method python sample.py i have the correct length = 3 i'm curious now, can anyone explain that? From gagsl-py2 at yahoo.com.ar Fri Mar 21 17:51:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 14:51:49 -0700 (PDT) Subject: How can I make a function equal to 0? References: Message-ID: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> On 21 mar, 17:43, Martin Manns wrote: > Basically I have a lot of functions inside a numpy array, > of which most return "" and actually are derived as follows: > > from numpy import * > > grid_size = 1000000 > > class F(object): > def __cmp__(self, other): return 0 > def __call__(self, dummy): return "" > f = F() > myarray = array([f] * grid_size, dtype="O") > > # I re-define an element in the array > > myarray[34424] = lambda x: "23" > > # Now, I would like to loop over all re-defined elements: > > for i in itertools.izip(*nonzero(myarray)): > print myarray[i]() > > If I fill the array with 0 instead of the functions that > return "" this works really fast. > > However, I would like to be able call the content of each > cell in the array as a function. If you drop this condition then you could fill the array with zeroes as before, replace only the interesting ones with actual functions, and write: for item in myarray[nonzero(myarray)]: print item() if callable(item) else item > As I said, the callable object approach works but is > about as slow as iterating through the whole array. > Perhaps I should add a __call__ function to the built-in > 0? But I doubt that this helps. You can't - anyway, being Python code, would not help with the speed. -- Gabriel Genellina From bluszcz at jabberpl.org Sat Mar 1 04:51:48 2008 From: bluszcz at jabberpl.org (=?UTF-8?B?UmFmYcWC?= Zawadzki) Date: Sat, 01 Mar 2008 10:51:48 +0100 Subject: RuPy 2008 Message-ID: Hello. We invite you to take part in RuPy 2008 - Python & Ruby Conference, which will take place on 12th, 13th April 2008 at Adam Mickiewicz University in Poznan, Poland. This international event is organised for the second time. The conference is devoted to Ruby and Python programming languages. RuPy is the only event of this type organised in Central Europe. It is a great opportunity to broaden your knowledge, discuss new trends with world class specialists and establish priceless international contacts. You may find more details on the conference website: http://rupy.eu/ See you at RuPy 2008, -- bluszcz http://web-dev.pl - Dynamiczny ?wiat internetowych aplikacji od ?rodka From duncan.booth at invalid.invalid Tue Mar 18 17:27:50 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2008 21:27:50 GMT Subject: os.path.getsize() on Windows References: Message-ID: Sean DiZazzo wrote: > On windows, this returns the size of the file as it _will be_, not the > size that it currently is. Is this a feature? What is the proper way > to get the current size of the file? I noticed > win32File.GetFileSize() Does that behave the way I expect? > > PS. I also tried os.stat()[6] > I think all of those will return the current size of the file, but that may be the same as the final size: just because the data hasn't been copied doesn't mean the file space hasn't been allocated. You don't say how you are copying the file, but I seem to remember that Windows copy command pre- allocates the file at its final size (so as to reduce fragmentation) and then just copies the data after that. If you need to make sure you don't access a file until the copy has finished then get hwatever is doing the copy to copy it to a temporary filename in the same folder and rename it when complete. Then you just have to check for existence of the target file. From kyosohma at gmail.com Sun Mar 9 21:50:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 9 Mar 2008 18:50:54 -0700 (PDT) Subject: Uninstalling Eggs References: Message-ID: <6dcd18c2-a900-4938-9e71-681ea1086cf0@n58g2000hsf.googlegroups.com> On Mar 9, 8:30 am, PB wrote: > I just installed the Shove module with the monumentally crap > setuptools. Whilst the install succeeded, imports now trigger errors, > so clearly it did not install correctly. Can I simply delete the .egg > file from my lib/python2.3/site-packages/ directory? > > Cheers, Deleting the shove-egg folder is definitely the recommended and easiest way I know of to "uninstall" an egg. I've used it successfully before. Mike From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 22:03:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 02:03:54 -0000 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> <47ed882d$0$26468$afc38c87@news.optusnet.com.au> <7x63v6tm9z.fsf@ruckus.brouhaha.com> Message-ID: <13ur8sa1p76i3ef@corp.supernews.com> On Fri, 28 Mar 2008 17:19:04 -0700, Paul Rubin wrote: > Richard Jones writes: >> Check out tinypy: >> http://www.philhassey.com/blog/category/tinypy/ > > I don't really understand the point of it. http://www.philhassey.com/blog/tinypy-ideas/ [quote] Sandbox tinypy Objective: to secure tinypy so that it can be run safely run any arbitrary python code Remove dangerous functions Enable a memory limit Enable an execution time limit Discover security related bugs and fix them -- Steven From sjmachin at lexicon.net Wed Mar 19 17:51:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 14:51:15 -0700 (PDT) Subject: Is this valid ? References: Message-ID: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> On Mar 20, 8:18 am, Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > Of course. You can chain comparisons as much as you like and is (semi-)sensible, e.g. assert 0 < thing_index < thing_count <= UTTER_MAX_NTHINGS There was an interesting use of chained comparison within the last day or 2 in a thread about deriving a set of duplicated list elements -- look for subject == "finding items that occur more than once in a list" and author == "Arnaud Delobelle". Cheers, John From justjpm at aol.com Wed Mar 19 17:45:39 2008 From: justjpm at aol.com (Jim) Date: Wed, 19 Mar 2008 14:45:39 -0700 (PDT) Subject: URLError Message-ID: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> Program randomly aborts when looking up url. The program loop thru 4000+ records looking up ID via internet and returns html code which is used in subsequent processing. The code for looking-up record is below followed by abort details. Can anyone help with catching the abort before program aborts or provide code to automatically start program? Currently, if program is restarted the process starts after last good record but must be restarted manually. Thanks Jim code start here ================ #start lookups pass while lines < 5000: lines += 1 d = ifile.read(8) print str(lines) + ' ' + d z = ifile.read(1) f2 = b + d h4 = h1+f2+h3 #file name for saving HMTL file html_file = open(h4, 'w') url = a + d + c + b #build url to lookup record in database contents = urllib2.urlopen(url).read() #lookup account in database soup = BeautifulSoup(contents) html_file.write(soup.prettify()) #write HTML file targetPage = soup.prettify() targetHTML = targetPage #set-up record for edit pass html_file.close() #close HTML file abort details ============================== 429 90078431(note:this record 429 is where abort happen-when program restarted this record processed normally) Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "Lookup Records.py", line 77, in contents = urllib2.urlopen(url).read() 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) URLError: From steve at REMOVE-THIS-cybersource.com.au Mon Mar 17 09:22:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 17 Mar 2008 13:22:48 -0000 Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <13tss585qqrhlc0@corp.supernews.com> On Mon, 17 Mar 2008 05:28:19 -0700, castironpi wrote: > a tuple is a data > structure such which cannot contain a refrence to itself. >>> a = [] # a list >>> b = (a, None) # a tuple >>> a.append(b) >>> print b ([([...], None)], None) >>> b[0][0] is b True So, yes tuples can contain a reference to themselves, but only indirectly. > Can a single expression refer to itself ever? You can't refer to an object until it exists, so no. -- Steven From cwitts at gmail.com Tue Mar 4 03:27:32 2008 From: cwitts at gmail.com (Chris) Date: Tue, 4 Mar 2008 00:27:32 -0800 (PST) Subject: Command line arguments in Windows References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: On Mar 4, 8:38 am, "Mike Walker" wrote: > > If you run a python file, ie. just double clicking it the only > > argument you will have will be the filename of the script. If you > > create a shortcut to the script and in the target box add your > > arguments (if you have quotation marks place them after not inside) > > you will see your arguments. fwiw you answered yourself in the third > > paragraph. > > As I mentioned I am working from the command line, not clicking on the icon. > The only difference between it working and not is the python prefix, which > is why I was thinking this is some sort of file association problem. > > I probably wasn't as clear as I could have been in the third paragraph. > > argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] > python argtest.py arg1 arg2 arg3 - Works That seems rather wierd, just running argtest.py arg1 arg2 arg3 I get the correct output, Python 2.5.1 from python.org but running on XP though. Potentially an issue with Vista... ? From stevegill7 at gmail.com Fri Mar 28 07:32:46 2008 From: stevegill7 at gmail.com (Jetus) Date: Fri, 28 Mar 2008 04:32:46 -0700 (PDT) Subject: ************************************************************** References: <151380e3-5e2c-4bd0-bca0-bcbb555cffac@d4g2000prg.googlegroups.com> Message-ID: <35da75eb-0583-413c-a98d-5313871d82e9@s8g2000prg.googlegroups.com> On Mar 28, 5:44 am, sivakumar... at gmail.com wrote: > ************************************************************** > When you make a Web page available offline, you > can read its content when your computer is not > connected to the Internet. For example, you can > view Web pages on your laptop computer when you > don't have a network or Internet connection. Or > you can read Web pages at home without tying up > a phone line. > > You can specify how much content you want available, > such as just a page, or a page and all its links, and > choose how you want to update that content on your computer. > > If you just want to view a Web page offline, and you don't > need to update the content, you can save the page on your > computer. There are several ways you can save the Web page, > from just saving the text to saving all of the images and > text needed to display that page as it appears on the Web. > *************************************************************** > http:\\my profile6529.blogspot.com Can't bring up your link.. http:\\my profile6529.blogspot.com From castironpi at gmail.com Sat Mar 29 18:57:13 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 15:57:13 -0700 (PDT) Subject: pygame handoff References: Message-ID: On Mar 28, 5:09?am, castiro... at gmail.com wrote: > Can anyone do a simple pygame render of a rollercoaster in first- > person? ?I'll do the generator. ?Just for fun for free. ?(Ha see > pythaaaaaagh. ?He bothered to carve it. ?Have a nice day.) Does anyone want to team up on this: http://www.pygame.org/gamelets/games/pycastersrc.zip From sturlamolden at yahoo.no Thu Mar 20 10:18:05 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 07:18:05 -0700 (PDT) Subject: Deleting Microsoft access database References: Message-ID: On 20 Mar, 15:11, "Ahmed, Shakir" wrote: > I have a Microsoft Access database that I want to delete whether anyone > is using that file. > > The database is already read only mode residing in a server, users are > opening in read only mode. I want to delete that file, I remove read > only check but could not delete that file. > > Getting error message: > Cannot delete xxx : It is being used by another person or program. > > Any help is highly appreciated. You cannot delete a file someone has open, in read-only mode or not. Disconnect the computer from the network. If that does not help, reboot the computer. From goon12 at gmail.com Tue Mar 11 10:40:36 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 11 Mar 2008 10:40:36 -0400 Subject: How to factor using Python? In-Reply-To: <6a2ccd190803110738l2ba7d0c0ne4d61b74e6a5d9c8@mail.gmail.com> References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <6a2ccd190803110738l2ba7d0c0ne4d61b74e6a5d9c8@mail.gmail.com> Message-ID: <6a2ccd190803110740q6acbbdf2n9cb562cd63ad3f94@mail.gmail.com> On Tue, Mar 11, 2008 at 10:38 AM, Joe Riopel wrote: > On Mon, Mar 10, 2008 at 1:08 AM, Nathan Pinno wrote: > > How do I factor a number? I mean how do I translate x! into proper > > Python code, so that it will always do the correct math? > > This should work to do x! (factorial of x). > > reduce(lambda x,y: x*y, range(1, x+1)) Sorry, the variable naming was confusing in that code. >>> def dofact(x): ... return reduce(lambda a,b: a*b, range(1,x+1)) ... >>> dofact(5) 120 >>> From vokinloksar at yahoo.se Sun Mar 30 15:46:00 2008 From: vokinloksar at yahoo.se (vokinloksar at yahoo.se) Date: Sun, 30 Mar 2008 12:46:00 -0700 (PDT) Subject: socket error when loading the shell? Message-ID: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> hi using python and wpython. when using run module or python shell on the run menu in the GUI i get "socket error, connection refused". it worked before, what si wrong now? and i cant find where to start the shell directly. think i had an exe before but cant seem to find it now. From mnordhoff at mattnordhoff.com Mon Mar 10 04:19:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 08:19:05 +0000 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <47D4EEF9.7010403@mattnordhoff.com> Stefan Behnel wrote: > And if you really need the efficiency of "well-tuned raw C", it's one function > call away in your Cython code. What do you mean by that? I know nothing about how Cython compares to C in performance, so I said "well-tuned" because it must be possible to write C that is faster than Cython, though it may take some effort. -- From zubeido at yahoo.com.br Sat Mar 29 16:21:23 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 29 Mar 2008 13:21:23 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> Message-ID: On Mar 29, 6:41 pm, Gerhard H?ring wrote: > Ok, I'll review your code. > > aiwarrior wrote: > > class db: > > def __init__(self): #constructor > > conn = sqlite3.connect('./db.db') > > conn.isolation_level = None > > Autocommit mode is mostly for newbies who forget to call commit. > Unfortunately, newbiews find enough other ways to shoot themselves in > the foot. So, in retrospect, maybe I should not have added that feature > to pysqlite ;-) > > > self.cursor = conn.cursor() > > try: > > self.cursor.execute("CREATE TABLE database > > (album,filepath)" ) > > except: > > pass > > try: except: pass without catching *specific* exceptions is generally a > very bad idea. If you're doing something stupid, or another error > happens than the one you want to ignore, you will never know this way. > > > def add_entry( self, eone , etwo ): #Add entry to database > > self.cursor.execute( "INSERT INTO database (album,filepath) > > VALUES (?,?)", ( eone , etwo ) ) > > return 1 #TODO: exception handler > > > def get_mediadb( self, print_db = False ): > > self.cursor.execute( 'SELECT * FROM database' ) > > if (print_db == True): > > print self.cursor.fetchall() > > The if clause can be written as just "if print_db:". > > > def get_value( self, column ): > > self.cursor.execute( "SELECT %s FROM database" % column ) > > for n in self.cursor: > > print n > > > def destructor(self): > > self.cursor.close() > > Just FYI, Python's "destructor" method is called "__del__", not > "destructor". > > > > > def walking_and_filling(db): > > pass > > > if __name__ == "__main__": > > db = db() > > #walking_and_filling( db ) > > for root, dirs, files in os.walk( '''foo_path/''', > > topdown=False ): > > for name in files: > > joined = os.path.join(root, name) > > if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): > > try: > > audio = MP3 (joined, ID3=EasyID3 ) > > print (audio['album']) > > db.add_entry( joined, audio['album'] ) > > except: > > pass > > Now, this try: except: pass is most probably hiding the real error That > leads to the insert failing. Because you just ignored any errors, you > will never now what exactly went wrong here. > > > db.get_mediadb( print_db=True ) > > > When i execute this the database doesn't get filled with anything and > > the program stays running in memory for ever. [...] > > HTH, > > -- Gerhard I'm sorry about not saying showing the libraries. It was not on purpose. import os import sqlite3 from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 ##def tree(path): ## node = () ## for node in os.listdir( path ): ## if( os.path.isdir( path + node )): ## tree(path+node) ## return path class db: def __init__(self): #constructor conn = sqlite3.connect( './db.db' ) conn.isolation_level = None self.cursor = conn.cursor() try: self.cursor.execute( "CREATE TABLE database (album,filepath)" ) except: pass def add_entry( self, eone , etwo ): #Add entry to database self.cursor.execute( "INSERT INTO database (album,filepath) VALUES (?,?)", ( eone , etwo ) ) return 1 #TODO: exception handler def get_mediadb( self, print_db = False ): self.cursor.execute( 'SELECT * FROM database' ) if (print_db == True): print self.cursor.fetchall() def get_value( self, column ): self.cursor.execute( "SELECT %s FROM database" % column ) for n in self.cursor: print n def destructor( self ): self.cursor.close() def walking_and_filling( db ): pass if __name__ == "__main__": db = db() #walking_and_filling( db ) for root, dirs, files in os.walk( '''foo_path/''', topdown=False ): for name in files: joined = os.path.join(root, name) if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): try: audio = MP3 (joined, ID3=EasyID3 ) print (audio['album']) db.add_entry( joined, audio['album'] ) except: pass db.get_mediadb( print_db=True ) This is all the code. Some of that try pass code is just something i glued to create a clean slate database file From roygeorget at gmail.com Wed Mar 19 10:21:46 2008 From: roygeorget at gmail.com (royG) Date: Wed, 19 Mar 2008 07:21:46 -0700 (PDT) Subject: changing names of items in a list Message-ID: hi i am trying to rename extension of files in a directory..as an initial step i made a method in class ConvertFiles: def __init__(self,infldr,outfldr): self.infldr=infldr self.outfldr=outfldr self.origlist=os.listdir(infldr) .... def renamefiles(self,extn): for x in self.origlist: x=x+"."+extn ... later when i print self.origlist i find that the elements of list are unchanged..even tho a print x inside the renamefiles() shows that extn is appended to x .. why does this happen? RG From bogus@does.not.exist.com Thu Mar 13 01:06:52 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 00:06:52 -0500 Subject: Class Inheritance Message-ID: I am trying to bring functions to a class by inheritance... for instance in layout_ext I have.. --- layout_ext.py--------- class Layout() def...some function that rely on css in Layout.py def... ---EOF-- in the main application file I have... ----Layout.py--- from layout_ext import Layout from CSS import CSS css = CSS() class Layout(Layout) def __init__ more code..... ----EOF---- Problem is layout_ext and Layout code is dependant on a Class instance 'css'. Whenever the CSS instance it parses a file, this means that I would have to parse the file twice?? Why is this? Can I do something like pass an already created instance to the import? -- Andrew From sjmachin at lexicon.net Sat Mar 22 06:07:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 03:07:18 -0700 (PDT) Subject: function-class frustration References: Message-ID: <740f8b7f-7d1a-4f98-96c9-71e58e6a8519@u10g2000prn.googlegroups.com> On Mar 22, 7:19 pm, castiro... at gmail.com wrote: > > On the other hand, are you willing to make changes to the console? > How big and what? I was thinking of __ to keep the second-to-last > most recent command. Access to and editing of previous input lines is already provided by the cooked mode of the console (e.g. on Windows, lean on the up-arrow key) or can be obtained by installing the readline package. Perhaps by analogy with _, you mean the *result* of the penultimate *expression*. This functionality would be provided by the Python interactive interpreter but it's not ... do have a look at IPython (http:// ipython.scipy.org/moin/About); I don't use it but I get the impression that if it doesn't already keep a stack or queue of recent results, you could implement it yourself easily. From fetchinson at googlemail.com Mon Mar 17 21:28:04 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 17 Mar 2008 18:28:04 -0700 Subject: First Program Bug (Newbie) In-Reply-To: References: Message-ID: > P.S. What is the chance I'll get spam for using my real email address? Exactly 1. > I currently don't get any so... ... you will get now. Sorry to disappoint you, but it's better to be prepared in advance than be shocked later :) Cheers, Daniel From gagsl-py2 at yahoo.com.ar Fri Mar 28 17:58:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 18:58:22 -0300 Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 16:40:01 -0300, escribi?: > I would like to write a script that would enumerate all running > processes and return the full path to the EXE of each running > process. However, I can't seem to find any good info on how to do > this..any help is greatly appreciated. Thanks. Use Tim Golden's WMI wrapper. Searching for "python enumerate running processes" with Google returns a reference to his module on the *first* hit. Searching in this newsgroup only, returns tons of references. -- Gabriel Genellina From jorgen.maillist at gmail.com Mon Mar 17 07:06:43 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 17 Mar 2008 12:06:43 +0100 Subject: comtypes question Message-ID: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> Hi All, I am trying to automate a 3rd party application, and all I have to work on is the type library and some documentation. I hope a Python / COM guru can answer this or put me on the right path because I don't know why it does not work. First I imported the typelib with comtypes like; >> from comtypes.client import GetModule >> GetModule("C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe") Which blurbs out a lot of text: # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1 # Generating comtypes.gen.BarTender Which seems to be ok. Now, I need to call a function on the Application object on which I need a "Messages" instance. The Application object gets created properly: >> import comtypes.gen.Bartender as bt >> app = comtypes.client.CreateObject(bt.Application) Which gives me the application (the bt.Application points to a wrapper class containing the CLSID of the COM class to be instantiated). Now I browse the typelibrary and I see there is a CoClass called Messages. I need one of those to pass as an argument, and since Messages is listed as a CoClass similar to Application, I assume it can also be instantiated. But when I try this I get an error: >>> msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}') Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\comtypes\client\__init__.py", line 198, in CreateObject obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface) File "C:\Python24\Lib\site-packages\comtypes\__init__.py", line 931, in CoCreateInstance _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p)) File "source/callproc.c", line 757, in GetResult WindowsError: [Errno -2147221164] Class not registered Both Application and Messages are listed as CoClass inside the typelibrary. Does anybody know why it gives me this error and what I am doing wrong? I have a COM Delphi background, and it would be similar to: msgs := CoMessages.Create; ... if the TLB is imported properly. Here is the details of the Application CoClass: [ uuid(B9425246-4131-11D2-BE48-004005A04EDF) ] coclass Application { [default] interface IBtApplication; dispinterface DBtApplication; }; And here is one from the Messages CoClass (as you can see the GUID matches): [ uuid(2B52174E-AAA4-443D-945F-568F60610F55) ] coclass Messages { [default] interface IBtMessages; dispinterface DBtMessages; }; Regards, - Jorgen From janeczek at gmail.com Thu Mar 27 01:01:17 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Thu, 27 Mar 2008 06:01:17 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> References: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Message-ID: <561cb5bc0803262201x7d2b7491p379ba10c441d2f94@mail.gmail.com> Hi, This is my second take on the project proposal. I have expanded on a few points, and hopefully also clarified a little bit. Please comment :) Regards, Michal Python-Haskell bridge ===================== Description ----------- This project will seek to provide a comprehensive, high level (and thus easy to use) binding between Haskell and Python programming languages. This will allow using libraries of either side from each language. If we decide to support function callbacks, these two functionalities (embedding Haskell in Python, and vice versa) become interrelated. In this light, it makes sense to implement them in the scope of the same project. Advantages of calling Haskell from Python ----------------------------------------- * Robust components It might be beneficial to implement safety-critical componenets in a strongly, statically typed language. Since Python itself is a terrific "glue language", such components would usually be purely functional, leaving IO to the Python side. Embedding Haskell code in this way is of particular interest when there already is a large existing Python infrastructure. One can implement new functionality in a form of Haskell plugin/component, even if complete rewrite is not feasible. * Performance improvements for speed-critical code Haskell compiled to native code is typically an order of magnitude faster than Python. Aside from that, advanced language features (such as multicore parallel runtime, very lightweight threads and software transactional memory) further serve to improve the performance. Haskell could become a safe, high level alternative to commonly used C extensions. * Access to sophisticated libraries While its set of libraries is not as comprehensive as that of Python, Haskell can still offer some well tested, efficient libraries. Some of the examples might be: * rich parser combinator libraries (like Parsec) * persistent, functional data structures (i.e. Data.Map, Data.IntMap, Data.Sequence, Data.ByteString) * QuickCheck testing library to drive analysis of Python code Advantages of calling Python from Haskell ----------------------------------------- * Python as a scripting language for Haskell applications Python is widely considered to be more approachable for regular users. As such, it could be used as a configuration/extension language for applications that benefit from extra flexibility. One example of such application is xmonad window manager. * Access to a large number of libraries As a much more popular language, Python has built up an impressive suite of libraries. There already are Haskell projects which rely on Python code to implement missing functionality, for example a paste bin application hpaste, which uses Pygments syntax coloring library. Deliverables ------------ * A low level library to access and manage Python objects from Haskell * Library support for wrapping Haskell values in Python objects. This is necessary to allow function callbacks. In addition, thanks to that feature large and/or lazy data structures can be efficiently passed from Haskell to Python * A set of low level functions to convert built-in data types between Haskell and Python (strings, numbers, lists, dictionaries, generators etc.) * A high level wrapper library for Haskell that simplifies embedding and calling Python code * A set of functions, and possibly a tool, to wrap up monomorphic functions and expose them to Python through foreign export facility * A way (an external tool, or a Template Haskell macro) to easily derive conversion functions for user-defined data types/objects * Documentation and a set of examples for all of above Optional goals -------------- In order of increasing amount of work and decreasing priority: * Exporting a wider class of functions to Python * A Python module that inspects a compiled Haskell module and transparently exposes functions within. This might be possible thanks to GHC API From danb_83 at yahoo.com Sun Mar 30 15:28:20 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 30 Mar 2008 12:28:20 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: On Mar 29, 12:34 pm, Lie wrote: > On Mar 29, 5:55 pm, kwitt... at telenet.be wrote: > > > I don't know if this is the right place to discuss the death of <> in > > Python 3.0, or if there have been any meaningful discussions posted > > before (hard to search google with '<>' keyword), but why would anyone > > prefer the comparison operator != over <>??? > ...snip... > > You're forcing your argument too much, both != and <> are NOT standard > mathematics operators -- the standard not-equal operator is >< -- and > I can assure you that both != and <> won't be comprehensible to non- > programmers. A lot of non-programmers use Microsoft Excel, which uses <> for the Not Equal operator. FWIW, the non-programmers on one forum I post on tend to use =/= . From miki.tebeka at gmail.com Tue Mar 11 13:11:23 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 11 Mar 2008 10:11:23 -0700 (PDT) Subject: How to make a Tkinter widget always visible? Message-ID: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> Hello, I have a simple Tkinter window with [GO] and [Quit] buttons at the bottom. When I resize the window to be shorter, the first thing to disappear are the buttons, however I want these button to be visible at all times. Is there a way to make sure that these buttons are always visible? Thanks, -- Miki http://pythonwise.blogspot.com From mail at microcorp.co.za Thu Mar 13 03:36:10 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 13 Mar 2008 09:36:10 +0200 Subject: List mutation method gotcha - How well known? Message-ID: <000901c884dd$057d5d80$03000080@hendrik> Hi, I am surprised that it took me so long to bloody my nose on this one. It must be well known - and I would like to find out how well known. So here is a CLOSED BOOK multiple choice question - no RTFM, no playing at the interactive prompt: Given the following three lines of code at the interactive prompt: foo = [1,2,3,4] x = foo.append(5) print x What will be the output (choose one): 1) [1,2,3,4] 2) [1,2,3,4,5] 3) That famous picture of Albert Einstein sticking out his tongue 4) Nothing - no output 5) None of the above I undertake to summarise answers posted to complete this "survey". - Hendrik From ron.duplain at gmail.com Tue Mar 4 10:44:15 2008 From: ron.duplain at gmail.com (Ron DuPlain) Date: Tue, 4 Mar 2008 07:44:15 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> Message-ID: <55f1c2b7-0f8f-4bcc-ac59-0b78a81cf81e@e31g2000hse.googlegroups.com> On Mar 4, 10:13 am, Siddhant wrote: > Hi people. > I was just wondering if a tab-completion feature in python command > line interface would be helpful? > If yes, then how can I implement it? > Thanks, > Siddhant ipython provides auto tab completion. http://ipython.scipy.org/ You can also get it by: $ easy_install ipython Run it using the command: $ ipython Is this what you want? Ron -- Ron DuPlain http://www.linkedin.com/in/rduplain From castironpi at gmail.com Thu Mar 6 00:35:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 21:35:51 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: On Mar 5, 8:06?pm, castiro... at gmail.com wrote: > On Mar 5, 4:25?pm, Steven D'Aprano > cybersource.com.au> wrote: > > On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote: > > > Classes and modules are really similar. ?In Python they're really > > > *really* similar. > > > Yes they are. > > > Both are namespaces. The very last line of the Zen of Python says: > > Namespaces are one honking great idea -- let's do more of those! > > Where to begin? And white to play. What does exec( open( 'modA.py' ).read() ) do? From geert at nznl.com Fri Mar 14 06:36:29 2008 From: geert at nznl.com (geert) Date: Fri, 14 Mar 2008 03:36:29 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard Message-ID: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Hi all, I have a mac mini running maocosx 10.5 leopard I want to deploy a django project on. My backend is MySQL, and I have it running as a 64- bit app. Of course, apache2 is also running as 64-bit. MySQLdb installs with the usual warnings after applying the various patches I found here and there. These patches consist of altering _mysql.c and site.cfg. Basically, my problem boils down to this: File "", line 1, in File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line 19, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dynamic module does not define init function (init_mysql) Has anyone solved this? I been hunting around for 2 weeks now, and my deadline is looming grimly on the horizon :) Geert From grante at visi.com Tue Mar 11 12:26:50 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 11 Mar 2008 16:26:50 -0000 Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> <46f8d1bf-8821-4083-b7d7-d4ed53f8862a@q78g2000hsh.googlegroups.com> Message-ID: <13tdcma35fabb6a@corp.supernews.com> On 2008-03-11, Mark Dickinson wrote: >> That seems a bit baffling. ?If it urlopen doesn't support >> specifying proxies, why are there examples showing how to do >> it? If it does support specifying proxies, what is the >> pragraph quoted above supposed to mean? > > Looks like a definite documentation bug to me, and it's still > there in the development version of the documentation. I > think a bug report should be filed. > > A little bit of investigation shows that the documentation > changes were made in svn revisions 26181 and 26182 ( > > http://svn.python.org/view?view=rev&rev=26181 > > ) as a fix for > > http://bugs.python.org/issue523415 > > but this doesn't seem to help much with figuring out what the > docs intend to say. Before I submit a bug, I'll give it a try to find out if it does support explicit specification of proxys or not. -- Grant Edwards grante Yow! How many retured at bricklayers from FLORIDA visi.com are out purchasing PENCIL SHARPENERS right NOW?? From miki.tebeka at gmail.com Mon Mar 3 23:28:18 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 3 Mar 2008 20:28:18 -0800 (PST) Subject: tools to install not in python tree? References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: <7a03a83b-ba31-4ba4-8674-d3f591211b6c@e6g2000prf.googlegroups.com> Hello Jim, > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). ?I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ ?and some programs that I want in ~/public_html/ . ? I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). ?So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > ? install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). ?But as I understand it setup only targets > installing below sys.prefix; is that right? > > I can write routines for myself but other people must need to do these > things also and a tested solution is obviously better. ?Is there such > a tool? Have a look at http://docs.python.org/lib/module-distutils.html, specially http://docs.python.org/dist/node13.html and http://docs.python.org/inst/alt-install-windows.html HTH, -- Miki http://pythonwise.blogspot.com From gherron at islandtraining.com Thu Mar 27 11:48:31 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Mar 2008 08:48:31 -0700 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: <47EBC1CF.30604@islandtraining.com> Skip Montanaro wrote: >>> >>> proc = subprocess.Popen ("ls /tmp") >>> >> proc = subprocess.Popen ("ls /tmp", shell=True) >> >> or >> >> proc = subprocess.Popen (["ls", "/tmp"]) >> >> should work. >> > > Why should I need to set shell=True? I'm not globbing anything. The > second case still fails: > > >>>> proc = subprocess.Popen (["/usr/bin/ls" "/tmp"]) >>>> This line fails because of a typo. There needs to be a comma between the two list elements. Without the comma, this becomes proc = subprocess.Popen (["/usr/bin/ls/tmp"]) which obviously fails. Gary Herron > Traceback (most recent call last): > File "", line 1, in ? > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 542, in > __init__ > errread, errwrite) > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 975, in > _execute_child > raise child_exception > OSError: [Errno 20] Not a directory > > Thx, > > Skip > > > From mattheww at chiark.greenend.org.uk Wed Mar 5 14:19:08 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Mar 2008 19:19:08 +0000 (GMT) Subject: Why """, not '''? References: Message-ID: wrote: > Why is """ the preferred delimiter for multi-line strings? One advantage is that a dumb syntax highlighter is more likely to cope well if the content includes an apostrophe. -M- From usenet at solar-empire.de Tue Mar 18 11:48:05 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 18 Mar 2008 16:48:05 +0100 Subject: Interesting math problem References: Message-ID: sturlamolden wrote: > On 18 Mar, 00:58, Jeff Schwab wrote: > >> def make_slope(distance, parts): >> if parts == 0: >> return [] >> >> q, r = divmod(distance, parts) >> >> if r and parts % r: >> q += 1 >> >> return [q] + make_slope(distance - q, parts - 1) > > Beautiful. If Python could optimize tail recursion, it would even run > fast. This was my first thought, too. But tailcall optimisation wouldn't help here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets executed after the recursion. Marc From sambo at voidstar.com Wed Mar 5 19:09:44 2008 From: sambo at voidstar.com (sambo q) Date: Thu, 06 Mar 2008 00:09:44 GMT Subject: access to base class __init__ Message-ID: I got myself in jam trying to be too fancy with threading.Thread Docs say / remind to call the base __init__ but I can't fighure out how. --------------------------- def main() ..... ls.listen(5) key = ' ' # while key != EXITCHARCTER: while stop_serving == False: cs, raddr = ls.accept() print "Main_Thread: ",cs, raddr nt = client_socket_handler( cs, raddr ) print threading.enumerate() key = getkey() # ls.close() time.sleep(4) print "Server Exiting." class client_socket_handler(threading.Thread): def __init__(self, cs, remote_address): ??????????????????????? self.threading.Thread.__init__(self,self.socket_handler,None,None) self.socket = cs self.rhost_addr = remote_address print "client_socket_handler.__init__(): ", self.socket, self.rhost_addr # t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) # t1.start() self.start() print "client_socket_handler.__init__(): ", self.socket, self.rhost_addr print "client_socket_handler.__init__(): enumerate()", threading.enumerate() def socket_handler( self, invar, indict ): threadname = self.getName() print "\"%s started\"" % threadname print "client_socket_handler.socket_handler() invar: ", invar instr = self.socket.recv( 500 ) # print instr req_lines = string.split( instr, "\r" ) for line in req_lines: line.strip( "\n") print req_lines print len( instr ) ---------------------------------- self.threading.Thread.__init__() self.Thread.__init__() ?? From Lie.1296 at gmail.com Fri Mar 14 14:32:41 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 14 Mar 2008 11:32:41 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <210b2a22-a8e3-414e-9018-15f7d74c9f83@d4g2000prg.googlegroups.com> On Mar 14, 4:57?pm, Jarek Zgoda wrote: > Lie napisa?(a): > > > > >> foo = [1,2,3,4] > >> x = foo.append(5) > >> print x > > >> What will be the output (choose one): > > >> 1) ?[1,2,3,4] > >> 2) ?[1,2,3,4,5] > >> 3) ?That famous picture of Albert Einstein sticking out his tongue > >> 4) ?Nothing - no output > >> 5) ?None of the above > > >> I undertake to summarise answers posted to complete this "survey". > > > I think I'll choose 3. Well, no, I suppose the correct behavior > > _should_ be undefined (i.e. what it returns is an implementation > > details that should not be relied on). The fact that it returns None > > is just a "coincidence" that happens to happen every time you tested > > it (you can't prove by ignorance) > > I think in Python there's no notion of "void" return type. Deliberate > choice to return None for functions that modify objects in place seems > to be OK as long as it is used consistently and documented. Which is the > case. No, there is no need for "void" return type, what I meant is that everything that's not said in the documentation should be assumed to be an implementation detail, a method or a function that doesn't say anything about its return type should be assumed to return an implementation detail (which basically means: Don't rely on this). The fact that list.append returns none is just a coincidence, you might encounter another list.append that returns different thing some time in the future, or the far future, or perhaps at the end of the galaxy's life. From rockxuan at gmail.com Tue Mar 18 03:44:56 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:44:56 -0700 (PDT) Subject: Rolex Swiss watch in www.51cntrade.com Message-ID: <83db7285-494a-4fc5-8551-318129fee56f@e6g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From vinodramachandran1 at gmail.com Mon Mar 10 08:25:47 2008 From: vinodramachandran1 at gmail.com (vinod ramachandran) Date: Mon, 10 Mar 2008 05:25:47 -0700 (PDT) Subject: 24 Hour Coding Contest AT BITS-Pilani in Association with Google Message-ID: <675de272-22a0-4eea-95a9-7087187ed4ad@s8g2000prg.googlegroups.com> 24 HOURS - NATIONWIDE ONLINE ALGORITHM INTENSIVE PROGRAAMING CHALLENGE Are you ready to tickle your grey cells with mind boggling algorithm intensive programming challenge that offers you freedom of programming in around 5 languages?? If yes, Watch out for 24 HOURS, the Nation wide Algorithm Intensive programming Contest brought to you by Computer Science Association (BITS Pilani) and GOOGLE India. 24 Hours is an online programming contest where in you will be provided with a real time programming problem from one of the most emerging arenas of computer science. You are required to design necessary algorithm to solve the problem, code it in any language of your choice - C,C++,JAVA,PYTHON OR RUBY!, with help of the API provided to you and submit your solutions within 24 hours from the commencement of the competition . This would be essentially a test for your endurance and efficiency in real-time problem solving. Contest starts at 1200 Hrs, 13th March, 2008 and is open to all students across the country. No registration fee required. Participants are required to solve the questions to be provided on www.bits-apogee.org/24hours and upload their solutions on or before 1200 Hrs, 14th March, 2008. Compete with most competent minds in the country, code your way to glory and win exciting prizes!!! For details contact: Yash Agrawal, Joint Coordinator,CSA, (Computer Science Association) Google Campus Ambassador, yash.1612 at gmail.com, BITS, Pilani. +919983526060 From skunkwerk at gmail.com Wed Mar 26 01:15:28 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 25 Mar 2008 22:15:28 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: On Mar 25, 9:25?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? > escribi?: > > >> ? ?i'm trying to call subprocess.popen on the 'rename' function in > >> linux. ?When I run the command from the shell, like so: > > >> rename -vn 's/\.htm$/\.html/' *.htm > > >> it works fine... however when I try to do it in python like so: > >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > >> print p.communicate()[0] > > >> nothing gets printed out (even for p.communicate()[1]) > > I'd try with: > > p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, > ? ? ? ?shell=True) > > (note that I added shell=True and I'm using a raw string to specify the ? > reg.expr.) > > -- > Gabriel Genellina Thanks Gabriel, I tried the new command and one with the raw string and single quotes, but it is still giving me the same results (no output). any other suggestions? cheers From mail at hellmutweber.de Tue Mar 4 16:01:10 2008 From: mail at hellmutweber.de (Hellmut Weber) Date: Tue, 04 Mar 2008 22:01:10 +0100 Subject: Eurosymbol in xml document Message-ID: <47CDB896.9010800@hellmutweber.de> Hi, thanks to all of you who have sent me helpful information. I'm diving into the secrets of unicode. It seems the crucial point was, that seemingly during the installation of the programming environment eric the file *** /usr/lib/python2.4/site-packages/sitecustomize.py *** has been modified. I found that file mentioned in the excellent online book 'Diving into python' Thanks again + happy pythoning Hellmut -- Dr. Hellmut Weber mail at hellmutweber.de Degenfeldstra?e 2 tel +49-89-3081172 D-80803 M?nchen-Schwabing mobil +49-172-8450321 please: No DOCs, no PPTs. why: tinyurl.com/cbgq From llothar at web.de Fri Mar 28 16:10:23 2008 From: llothar at web.de (llothar) Date: Fri, 28 Mar 2008 13:10:23 -0700 (PDT) Subject: Python 2.5 - Build Error on Windows because of SQLite3 Message-ID: Why does Python2.5 do not include the amalgamation source code of sqlite3? At the moment it is not possible to build the system out of the box with the Visual Studio project. I don't think this is good. The amalgamation version is exactly for this purpose. Is there a 2.5.3 release on the way? From toolmaster at 163.com Sun Mar 16 23:57:23 2008 From: toolmaster at 163.com (WaterWalk) Date: Sun, 16 Mar 2008 20:57:23 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <5b80e12a-f7f9-43bb-af48-cb2163e296af@s8g2000prg.googlegroups.com> On Mar 17, 11:54 am, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. > > So I'm curious how to read code effectively. I agree that python code > is clear, but when it becomes long, reading it can still be a hard > work. BTW. I think this problem also exists in other script languages. From ptmcg at austin.rr.com Sat Mar 8 23:30:42 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 8 Mar 2008 20:30:42 -0800 (PST) Subject: Parse specific text in email body to CSV file References: Message-ID: <4e232588-82df-4933-98bd-72c8657cb829@z17g2000hsg.googlegroups.com> On Mar 8, 4:20?pm, dpw.a... at gmail.com wrote: > I have been searching all over for a solution to this. I am new to > Python, so I'm a little lost. Any pointers would be a great help. I > have a couple hundred emails that contain data I would like to > incorporate into a database or CSV file. I want to search the email > for specific text. > > The emails basically look like this: > > random text _important text:_15648 random text random text random text > random text > random text random text random text _important text:_15493 random text > random text > random text random text _important text:_11674 random text random text > random text > ===============Date: Wednesday March 5, 2008================ > name1: 15 ? ? ? ? ? ? ? ?name5: 14 > > name2: 18 ? ? ? ? ? ? ? ?name6: 105 > > name3: 64 ? ? ? ? ? ? ? ?name7: 2 > > name4: 24 ? ? ? ? ? ? ? ?name8: 13 > > I want information like "name1: 15" to be placed into the CSV with the > name "name1" and the value "15". The same goes for the date and > "_important text:_15493". > > I would like to use this CSV or database to plot a graph with the > data. > > Thanks! This kind of work can be done using pyparsing. Here is a starting point for you: from pyparsing import Word, oneOf, nums, Combine import calendar text = """ random text _important text:_15648 random text random text random text random text random text random text random text _important text:_15493 random text random text random text random text _important text:_11674 random text random text random text ===============Date: Wednesday March 5, 2008================ name1: 15 name5: 14 name2: 18 name6: 105 name3: 64 name7: 2 name4: 24 name8: 13 """ integer = Word(nums) IMPORTANT_TEXT = "_important text:_" + integer("value") monthName = oneOf( list(calendar.month_name) ) dayName = oneOf( list(calendar.day_name) ) date = dayName("dayOfWeek") + monthName("month") + integer("day") + \ "," + integer("year") DATE = Word("=").suppress() + "Date:" + date("date") + Word("=").suppress() NAMEDATA = Combine("name" + integer)("name") + ':' + integer("value") for match in (IMPORTANT_TEXT | DATE | NAMEDATA).searchString(text): print match.dump() Prints: ['_important text:_', '15648'] - value: 15648 ['_important text:_', '15493'] - value: 15493 ['_important text:_', '11674'] - value: 11674 ['Date:', 'Wednesday', 'March', '5', ',', '2008'] - date: ['Wednesday', 'March', '5', ',', '2008'] - day: 5 - dayOfWeek: Wednesday - month: March - year: 2008 - day: 5 - dayOfWeek: Wednesday - month: March - year: 2008 ['name1', ':', '15'] - name: name1 - value: 15 ['name5', ':', '14'] - name: name5 - value: 14 ['name2', ':', '18'] - name: name2 - value: 18 ['name6', ':', '105'] - name: name6 - value: 105 ['name3', ':', '64'] - name: name3 - value: 64 ['name7', ':', '2'] - name: name7 - value: 2 ['name4', ':', '24'] - name: name4 - value: 24 ['name8', ':', '13'] - name: name8 - value: 13 Find out more about pyparsing at http://pyparsing.wikispaces.com. -- Paul From simon at brunningonline.net Fri Mar 7 11:44:10 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 7 Mar 2008 16:44:10 +0000 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: <8c7f10c60803070844pf88a497h9db85953851b3418@mail.gmail.com> On Fri, Mar 7, 2008 at 4:31 PM, K Viltersten wrote: > > 1. When writing English, Strunk and > White apply. I apply Fowler, PEP 8 be damned. ;-) -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From mwilson at the-wire.com Wed Mar 12 11:31:47 2008 From: mwilson at the-wire.com (Mel) Date: Wed, 12 Mar 2008 11:31:47 -0400 Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: Gerdus van Zyl wrote: > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus What they said, or, if you want to see it done: def combi (s): if s: for a in s[0]: for b in combi (s[1:]): yield [a] + b else: yield [] for y in combi ([['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]): print y From alexandru.dumitrescu at gmail.com Wed Mar 19 12:01:08 2008 From: alexandru.dumitrescu at gmail.com (Alexandru Dumitrescu) Date: Wed, 19 Mar 2008 18:01:08 +0200 Subject: add new csv line Message-ID: Hello everybody, Is there a way to add a new line at the beginning of a *.csv file, line which contain the name of the columns? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Sun Mar 9 05:31:17 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 9 Mar 2008 01:31:17 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> On 9 Mrz., 09:30, Lie wrote: > On Mar 9, 12:05 pm, Kay Schluehr wrote: > > > On 9 Mrz., 04:51, Lie wrote: > > > > A more through implementation would start from the raiser inspecting > > > the execution stack and finding whether there are any try block above > > > it, if no try block exist it pass silently and if one exist it will > > > check whether it have a matching except clause. This also circumvents > > > a problem that simple implementation have, as described below. > > > This will not be easy in particular in the presence of inheritance and > > dynamism. There is no way to statically decide whether an exception > > BException has the type AException and will be caught by the except > > clause in > > > try: > > BLOCK > > except AException, e: > > print "SoftException %s caught"%e > > A feasible solution was to invert the try...except statement and > > creating a continuation. > > > catch AException, a: > > print "SoftException A: %s"%a > > catch BException , b: > > print "SoftException B: %s"%b > > ... > > in: > > BLOCK > > > Here each SoftException is raised initially when a catch clause is > > entered and a continuation is created that returns to the catch block > > of the raised SoftException if required. When a SoftException is > > raised within BLOCK a lookup will be made and if a corresponding > > SoftException was found that was raised by a catch-clause the current > > control flow will be suspended and the continuation is called. > > I'd rather want to avoid any syntax changes, as I wished that Soft > Exception can be added to the language silently[1] so that new > programmers doesn't _need_ to know about it (although knowing it could > change the way they write codes to be more structured and simple). I just tried to save your proposal from being unimplementable. Maybe you can comment on it? I know of course that syntax is Pythons holy cow but I'm not Guidos mouthpiece and have a different perspective on some aspects of the system for obvious reasons [1]. I appreciate when people in the Python community talk about what is useful for them and not what the imaginary Pythonista superego thinks about them and how it will be standardized in the end - if anyhow. I'd like to know if SoftExceptions would make programs more reliable in the end because people won't use them sparingly but for all kinds of events that are somewhat "irregular" ( i.e. warnings ) not just for obvious errors. It's an interesting idea to have an advanced warning system that is more responsive than just this kind of logging which is currently implemented. And I'd surely discriminate them from the current exception handling at least in the design phase. Later language changes could still be "dissolved". [1] http://www.fiber-space.de/EasyExtend/doc/EE.html From josef.pktd at gmail.com Sat Mar 15 19:55:45 2008 From: josef.pktd at gmail.com (joep) Date: Sat, 15 Mar 2008 16:55:45 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> <47dc43e0$0$849$ba4acef3@news.orange.fr> Message-ID: <65faeeb8-d1d2-4d50-8421-f19a5ceb8ba5@8g2000hsu.googlegroups.com> you can also use standard module fileinput.input with ''inplace'' option which backs up original file automatically. from python help for fileinput: Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). From ptmcg at austin.rr.com Sat Mar 22 21:37:17 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Mar 2008 18:37:17 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <471ec539-3512-4a4e-a52d-68d979f0a53b@e39g2000hsf.googlegroups.com> On Mar 22, 11:40?am, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. ?Do you think > Python is a good first programming language for someone with zero > programming experience? ?Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. I absolutely support Python as a first programming language, from 7th grade on up. Here is a link at the main Python web site that should give you a number of additional resources: http://www.python.org/community/sigs/current/edu-sig/ -- Paul From dstromberglists at gmail.com Wed Mar 12 22:39:43 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 13 Mar 2008 02:39:43 +0000 (UTC) Subject: macro in python References: <910313af0802270254i27ca8a65xab54064bd91f4de@mail.gmail.com> Message-ID: On Wed, 27 Feb 2008 16:24:02 +0530, bharath venkatesh wrote: > hi .. > how to create macro in python for set of instruction that is done > frequently but too less in number to ignore the overhead of function > call ... > hi ..
    how to create macro in python for set of > instruction that is done frequently but too less in number to ignore the > overhead of function call ...
I believe python doesn't do macros, but you could look into wrapping your python code with m4. From python at rcn.com Mon Mar 17 19:39:12 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 17 Mar 2008 16:39:12 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 4:10 am, Bruce Eckel wrote: > If the following seems unnecessarily harsh, it was even more harsh for > me to discover that the time and money I had spent to get to my > favorite conference had been sold to vendors, presenting me as a > captive audience they could pitch to. My thoughts: * Saturday and Sunday were much better than Friday. * Open-source != Anti-vendor. The vendors are a vital part of the open-source community. * Lightning talks should be proportionate to their information content. The most common vendor message can be done in 45 seconds while the next speaker is setting-up: "Hi, I'm Raymond from Raymond Enterprises. We sell Raymond's signature to Raymond's fans. We use Python to crawl the web for clients wanting his signature. We're hiring Python programmers with experience in web-crawling. We're proud to sponsor for PyCon 2009. Good night and good luck.". * The sole guiding principle for the conference should be whatever best serves the attendees. * As the conference gets bigger, lots of previously minor annoyances will become more irritating. The conference organizers will adapt as needed. * Vendor/sponsor presentations should not have priority over informational talks. Also, lots of things went well: * Sean stepped-in and fixed-up the wireless for Saturday and Sunday (but on Friday the third-party wireless setup sucked mightily). * The conference admin (checkin, schedule posting, etc) was excellent. * The AV work was great (you'll soon be able to see HD recordings for most talks). * Steve Holden successfully created a new type of talk, "Teach me Twisted". * The feedback on the tutorials was excellent, the BoFs seemed to go well, and the sprints are off to a nice start. * The conference was close to the airport. One last thought: * Most of the conference work is done by volunteers. As the community grows, more volunteers will be needed (for next year, I plan to help by reviewing talk proposals). Raymond From mmanns at gmx.net Fri Mar 21 16:43:18 2008 From: mmanns at gmx.net (Martin Manns) Date: Fri, 21 Mar 2008 21:43:18 +0100 Subject: How can I make a function equal to 0? References: Message-ID: On Fri, 21 Mar 2008 13:12:56 -0700 (PDT) Arnaud Delobelle wrote: > On Mar 21, 7:48?pm, Martin Manns wrote: > Why do you want to do that? First thank you for your help, the callable object works. Basically I have a lot of functions inside a numpy array, of which most return "" and actually are derived as follows: from numpy import * grid_size = 1000000 class F(object): def __cmp__(self, other): return 0 def __call__(self, dummy): return "" f = F() myarray = array([f] * grid_size, dtype="O") # I re-define an element in the array myarray[34424] = lambda x: "23" # Now, I would like to loop over all re-defined elements: for i in itertools.izip(*nonzero(myarray)): print myarray[i]() If I fill the array with 0 instead of the functions that return "" this works really fast. However, I would like to be able call the content of each cell in the array as a function. As I said, the callable object approach works but is about as slow as iterating through the whole array. Perhaps I should add a __call__ function to the built-in 0? But I doubt that this helps. Martin From andreas.tawn at ubisoft.com Wed Mar 19 06:34:02 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 19 Mar 2008 11:34:02 +0100 Subject: First Program Bug (Newbie) In-Reply-To: <518f4420-19e1-4708-8b65-e44ca23da586@t54g2000hsg.googlegroups.com> References: <518f4420-19e1-4708-8b65-e44ca23da586@t54g2000hsg.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758003A0470A@PDC-MAIL3.ubisoft.org> [snip] >> What is the square root function in python? > > There's one in the math module. Use the one in gmpy if you have it. Or raise to the power 1/power >>> 9**(1.0/2) 3.0 Also works for cube root, quad root etc. >>> 27**(1.0/3) 3.0 >>> 81**(1.0/4) 3.0 >>> 243**(1.0/5) 3.0 Cheers, Drea From sjmachin at lexicon.net Mon Mar 3 07:14:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 3 Mar 2008 04:14:54 -0800 (PST) Subject: write float to Excel with pyExcelerator write References: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> Message-ID: <1bb4ba4b-27f3-4a31-bf59-00e36656a8e3@i12g2000prf.googlegroups.com> On Mar 1, 5:59 pm, Cyril.Liu wrote: > I use pyExcelerator to generat Excel files in my project. it works good > before I found this bug: > run this code: > > from pyExcelerator import * > wb = Workbook() > ws = wb.add_sheet("sheet") > for i in xrange(1): > ws.write(i,0, 10474224.6) > wb.save(r'd:\error_float.xls') > > open d:\error_float.xls with M$ Excle you'll find the number in the cell is > -263193.64 not 10474224.6 > > why? The author assumed unsigned integers instead of signed integers. >>> 1047422460 - 2**30 -26319364 See the following, previously posted here: http://mail.python.org/pipermail/python-list/2007-May/441633.html Cheers, John From sturlamolden at yahoo.no Sun Mar 16 14:55:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 11:55:31 -0700 (PDT) Subject: Advantage of the array module over lists? References: Message-ID: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> On 13 Mar, 20:40, Tobiah wrote: > I checked out the array module today. It claims that > arrays are 'efficient'. I figured that this must mean > that they are faster than lists, but this doesn't seem > to be the case: > > ################ one.py ############## > import array > > a = array.array('i') > > for x in xrange(10000000): > a.append(x) Lists are better optimized for appending to the end. Python lists are implemented as arrays of pointers, with a few empty slots at the end. Arrays are contigous memory buffers. They provide faster read-write access, particularly for chunks of data, but are slower at resizing. I never use the array module, as NumPy is superior. From yoz at home.havin.us Sat Mar 15 22:27:46 2008 From: yoz at home.havin.us (yoz) Date: Sun, 16 Mar 2008 02:27:46 GMT Subject: os.path.isdir question In-Reply-To: References: Message-ID: lampshade wrote: > Hello, > > I'm having some problems with os.path.isdir I think it is something > simple that I'm overlooking. > > #!/usr/bin/python > import os > > my_path = os.path.expanduser("~/pictures/") > print my_path > results = os.listdir(my_path) > for a_result in results: > if os.path.isdir(str(my_path) + str(a_result)): > results.remove(a_result) > > for x in results: print x > > The problem is, that the directories are never removed. Can anyone > point out what I'm missing that is causing the bug? Is there a better > way of doing this? > > Thanks, Your code works fine for me .. Someone will probably complain that this isn't pythonic or hopefully come up with an even neater way but what about this: #!/usr/bin/python import os my_path = os.path.expanduser("~/pictures/") print my_path files=os.walk(my_path).next()[2] for x in files: print x EdH. From cwitts at gmail.com Fri Mar 14 05:13:59 2008 From: cwitts at gmail.com (Chris) Date: Fri, 14 Mar 2008 02:13:59 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: On Mar 14, 8:36?am, Dennis Lee Bieber wrote: > On Thu, 13 Mar 2008 21:28:18 -0700 (PDT), jai_python > declaimed the following in comp.lang.python: > > > hi frenz I ?Need a Python Script For read multiple files(.txt) from a > > folder and write it in a single text file.... > > ? ? ? ? If you are on windows, just open a command prompt and use the > standard copy command... > > C:\Documents and Settings\Dennis Lee Bieber>copy /? > Copies one or more files to another location. > > COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/A | /B ] source [/A | /B] > ? ? ?[+ source [/A | /B] [+ ...]] [destination [/A | /B]] > > ? source ? ? ? Specifies the file or files to be copied. > ? /A ? ? ? ? ? Indicates an ASCII text file. > ? /B ? ? ? ? ? Indicates a binary file. > ? /D ? ? ? ? ? Allow the destination file to be created decrypted > ? destination ?Specifies the directory and/or filename for the new > file(s). > ? /V ? ? ? ? ? Verifies that new files are written correctly. > ? /N ? ? ? ? ? Uses short filename, if available, when copying a file > with a > ? ? ? ? ? ? ? ?non-8dot3 name. > ? /Y ? ? ? ? ? Suppresses prompting to confirm you want to overwrite an > ? ? ? ? ? ? ? ?existing destination file. > ? /-Y ? ? ? ? ?Causes prompting to confirm you want to overwrite an > ? ? ? ? ? ? ? ?existing destination file. > ? /Z ? ? ? ? ? Copies networked files in restartable mode. > > The switch /Y may be preset in the COPYCMD environment variable. This > may be overridden with /-Y on the command line. ?Default is to prompt on > overwrites unless COPY command is being executed from within a batch > script. > > To append files, specify a single file for destination, but multiple > files for source (using wildcards or file1+file2+file3 format). > > C:\Documents and Settings\Dennis Lee Bieber> > > ? ? ? ? Note that last paragraph "To append files" > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ If you want to go that route you could also do: type *.txt > output_file.txt From sjmachin at lexicon.net Sat Mar 22 00:41:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 21:41:51 -0700 (PDT) Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> <05e369b9-ba75-488f-b58c-de437af2e1c5@d4g2000prg.googlegroups.com> Message-ID: <21e0f575-d65c-4488-9b5b-daf4598ad19c@c19g2000prf.googlegroups.com> On Mar 22, 3:32 pm, Gabriel Genellina wrote: > On 21 mar, 19:25, John Machin wrote: > > > > > On Mar 22, 8:51 am, Gabriel Genellina wrote: > > > > If you drop this condition then you could fill the array with zeroes > > > as before, replace only the interesting ones with actual functions, > > > and write: > > > > for item in myarray[nonzero(myarray)]: > > > print item() if callable(item) else item > > > Let's unbuckle the seat belt :-) > > > If "item" is definitely restricted to being either 0 or a callable > > object, then > > item() if item else 0 > > should give the same answer as, and is quite likely to be faster than, > > item() if callable(item) else item > > as it avoids a global lookup and a function call. > > In that case, we could use a bare item() because nonzero would have > filtered out all that zeroes. True. From gagsl-py2 at yahoo.com.ar Thu Mar 6 20:10:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 23:10:31 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 22:56:33 -0200, escribi?: > On Mar 6, 5:35?am, "Gabriel Genellina" wrote: >> >> p = P() >> print p.bar.func_name # -> bar >> p.bar.im_func.anotherattribute = 1 >> print p.bar.anotherattribute # -> 1 >> >> (the attribute must be set on the *function* itself if you want it to >> be ? >> somewhat persistent; methods are usually volatile objects) > > You read my mind. You could try to write in a way that reading your mind isn't necesary... > I was just getting: > assert p.bar is p.bar > and failing. > > But if you set them on im_func, instances don't have their own. Instances don't have their own methods either. What do you actually want to do? If you need a method with per-instance attributes, that looks like another object to me. -- Gabriel Genellina From noname9968 at gmail.com Wed Mar 19 15:07:26 2008 From: noname9968 at gmail.com (Alex9968) Date: Wed, 19 Mar 2008 22:07:26 +0300 Subject: Tkinter.Text widget - how to get text cursor position? In-Reply-To: <47E14F47.6000202@gmail.com> References: <47E14F47.6000202@gmail.com> Message-ID: <47E1646E.5070908@gmail.com> Alex9968 wrote: > Is it possible to get position (in numbers) of the insertion cursor? As > I understood, Text widget uses mark named INSERT to store it, which is > available globally by just referencing INSERT, but how could I get > actual coordinate numbers of the mark? > I need this because I want not just to insert string at, but to examine > text before and after the insertion cursor. I can probably use .get() to > extract the halves of text before and after cursor, but it'd be better > just to know the position. > > Thanks It's .index() Problem was that it's missed in Tkinter reference: a GUI for Python From jeffober at gmail.com Fri Mar 7 16:12:18 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 7 Mar 2008 13:12:18 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: Use metaclasses? DBak wrote: > I want - but cannot get - a nested class to inherit from an outer > class. (I searched the newsgroup and the web for this, couldn't find > anything - if I missed an answer to this please let me know!) > > I would like to build a class for a data structure such that nodes of > the data structure - of interest only to the data structure > implementation itself and not to the consumer - are instances of one > of two class types. I thought to encapsulate the nodes' classes like > this: > > class Tree(object): > ...class _MT(Tree): > ......def isEmpty(self): return True > ......def insert(self, X): return Tree._Node(X) > ...class _Node(Tree): > ......def isEmpty(self): return False > ......def insert(self, X): return _Node(X, self, Tree._MT()) > ...def merge(self, T): > ......def __init__(): return _MT() > ...... > > In other words, some methods would be implemented on instances' > classes (like isEmpty and insert) and some on the outer class (like > merge). Users of the data structure never need to know about the > nodes, much less the nodes' classes, so I wanted to encapsulate them > > However I can't do this, because, of course, the name Tree isn't > available at the time that the classes _MT and _Node are defined, so > _MT and _Node can't inherit from Tree. > > What is the Pythonic thing I should be doing instead? > > (Easy answer: Put this code in a module, exposing only a factory > function. I could do that, but wanted to know if I could encapsulate > it as described so I could actually put several similar data > structures into one module.) > > Thanks! -- David From steve at holdenweb.com Mon Mar 31 07:44:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 07:44:54 -0400 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <47F0CEB6.2050006@holdenweb.com> No, sorry. regards Steve Pradeep Rai wrote: > Hi Steve, > > Can you guide me how to install a 2.5 version of dbi for it to work ? > > Thanks !! > > Pradeep > > Pradeep Rai wrote: > > > Hi All, > > > > > > I have upgraded python v2.5.2 from python v2.4.3. The upgradation > > > results into following error: > > > "Python C API version mismatch for module dbi: This Python has API > > > version 1013, module dbi has version 1012." > > > > > > Please suggest, how to resolve this error to proceed further. > > > > > > Regards, > > > Pradeep Rai > > > > > > > > Don't try and drag 2.4 extension modules into the 2.5 environemnt. You > > will have to install a 2.5 version of dbi for it to work. > > regards > > Steve > > -- > > Steve Holden +1 571 484 6266 +1 800 494 3119 > > Holden Web LLC > > _http://www.holdenweb.com/_ > > -- > > _http://mail.python.org/mailman/listinfo/python-list_ -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jeffrey at fro.man Tue Mar 18 12:24:03 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 18 Mar 2008 09:24:03 -0700 Subject: Decode email subjects into unicode References: Message-ID: <13tvr53smbfp9c4@corp.supernews.com> Laszlo Nagy wrote: > I know that "=?UTF-8?B" means UTF-8 + base64 encoding, but I wonder if > there is a standard method in the "email" package to decode these > subjects? The standard library function email.Header.decode_header will parse these headers into an encoded bytestring paired with the appropriate encoding specification, if any. For example: >>> raw_headers = [ ... '=?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?=', ... '[Fwd: re:Flags Of The World, Us States, And Military]', ... '=?ISO-8859-2?Q?=E9rdekes?=', ... '=?UTF-8?B?aGliw6Fr?=', ... ] >>> from email.Header import decode_header >>> for raw_header in raw_headers: ... for header, encoding in decode_header(raw_header): ... if encoding is None: ... print header.decode() ... else: ... print header.decode(encoding) ... ??????????????? ? ???????????? [Fwd: re:Flags Of The World, Us States, And Military] ?rdekes hib?k Jeffrey From Robert.Bossy at jouy.inra.fr Wed Mar 12 08:52:03 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 12 Mar 2008 13:52:03 +0100 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: <47D7D1F3.5040706@jouy.inra.fr> k.i.n.g. wrote: > I think I am not clear with my question, I am sorry. Here goes the > exact requirement. > > We use dd command in Linux to create a file with of required size. In > similar way, on windows I would like to use python to take the size of > the file( 50MB, 1GB ) as input from user and create a uncompressed > file of the size given by the user. > > ex: If user input is 50M, script should create 50Mb of blank or empty > file > def make_blank_file(path, size): f = open(path, 'w') f.seek(size - 1) f.write('\0') f.close() I'm not sure the f.seek() trick will work on all platforms, so you can: def make_blank_file(path, size): f = open(path, 'w') f.write('\0' * size) f.close() Cheers, RB From stephenhorne100 at aol.com Tue Mar 18 07:47:49 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 18 Mar 2008 04:47:49 -0700 (PDT) Subject: Python 3 and PEP238 division References: Message-ID: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> On Mar 17, 7:26 pm, "Terry Reedy" wrote: > "Ninereeds" wrote in message > > news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... > | Is the PEP238 change to division going into Python 3 as planned? > > IDLE 3.0a3>>> 1/2 > > 0.5 > > | I realise that the new integer division semantics have been available > | in "from __future__" for quite a few years now, but a warning might be > | appropriate now that Python 3 is in alpha. > > 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion > program The tools can work out the *intent* of any particular division operator? Can work out whether the result should be integer or float, independent of any particular set of arguments? Seems unlikely. From http Fri Mar 28 02:49:46 2008 From: http (Paul Rubin) Date: 27 Mar 2008 23:49:46 -0700 Subject: SoC project: Python-Haskell bridge - request for feedback References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: <7xabkjbawl.fsf@ruckus.brouhaha.com> "Micha? Janeczek" writes: > I wasn't aware of the runtime issues, these can be things to watch out > for. However, the type of embedding that I imagined would be mostly > pure functions, since Python can deal with IO rather well. It'd also > be applicable in situations where we want to add some functionality to > to existing, large Python project, where the complete rewrite > would be infeasible. Of course I can't say what functions someone else would want to use, but I'm not seeing very convincing applications of this myself. There aren't that many prewritten Haskell libraries (especially monomorphic ones) that I could see using that way. And if I'm skilled enough with Haskell to write the functions myself, I'd probably rather embed Python in a Haskell app than the other way around. Haskell's i/o has gotten a lot better recently (Data.ByteString) though there is important stuff still in progress (bytestring unicode). For other pure functions (crypto, math, etc.) there are generally libraries written in C already interfaced to Python (numarray, etc.), maybe through Swig. The case for Haskell isn't that compelling. > I didn't mention this in this first draft, but I don't know (yet) > how to support those "fancy" types. The plan for now is to export > monomorphic functions only. This probably loses most of the interesting stuff: parser combinators, functional data structures like zippers, etc. Unless you mean to use templates to make specialized versions? > As for GC, I think having the two systems involved is unavoidable if > I want to have first class functions on both sides. This just seems worse and worse the more I think about it. Remember that GHC uses a copying gc so there is no finalization and therefore no way to notify python that a reference has been freed. And you'd probably have to put Haskell pointers into Python's heap objects so that the Haskell gc wouldn't have to scan the whole Python heap. Also, any low level GHC gc stuff (not sure if there would be any) might have to be redone for GHC 6.10(?) which is getting a new (parallel) gc. Maybe I'm not thinking of this the right way though, I haven't looked at the low level ghc code. Keep in mind also that Python style tends to not use complex data structures and fancy sharing of Haskell structures may not be in the Python style. Python uses extensible lists and mutable dictionaries for just about everything, relying on the speed of the underlying C functions to do list operations very fast (C-coded O(n) operation faster than interpreted O(log n) operation for realistic n). So maybe this type of sharing won't be so useful. It may be simplest to just marshal data structures across a message passing interface rather than really try to share values between the two systems. For fancy functional structures, from a Python programmer's point of view, it is probably most useful to just pick a few important ones and code them in C from scratch for direct use in Python. Hedgehog Lisp (google for it) has a nice C implementation of functional maps that could probably port easily to the Python C API, and I've been sort of wanting to do that. It would be great if you beat me to it. > > Anyway I'm babbling now, I may think about this more later. > By all means, please do go on :) This has helped a lot :) One thing I highly recommend is that you join the #haskell channel on irc.freenode.net. There are a lot of real experts there (I'm just newbie) who can advise you better than I can, and you can talk to them in real time. From znfmail-pythonlang at yahoo.com Wed Mar 19 11:03:03 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Wed, 19 Mar 2008 11:03:03 -0400 Subject: cx_Oracle execute procedure Message-ID: I've been working on the code below and and executes silently, no complaints, however the end result should be a record in my table and it's not added. The procedure works with the passed credentials using SQLPlus or SQL Developer clients. However I'm not sure if I'm constructing my python code correctly to interact with Oracle. I've been basing the code below on what I found in this thread http://www.thescripts.com/forum/thread33728.html . Zach- import cx_Oracle connection = cx_Oracle.connect("user/pass at server") ## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum varchar2, p_prefix number) cur = connection.cursor() repParams = {} repParams['arg1'] = "5555555" repParams['arg2'] = "2" repParams['arg3'] = "999" sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3); end;""" cur.execute(sqlStr, repParams) connection.commit cur.close connection.close From grahn+nntp at snipabacken.se Sun Mar 30 19:07:02 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 23:07:02 GMT Subject: Where can I find : References: <13uu56hn1vdqb9d@corp.supernews.com> Message-ID: On Sat, 29 Mar 2008 21:19:32 -0700, Dennis Lee Bieber wrote: > On Sat, 29 Mar 2008 20:15:59 -0700 (PDT), pythonnubie > declaimed the following in comp.lang.python: > >> Hi All : >> Does anyone know where I can find either a book or a website that >> explains beginning python by actually building a project line by >> line and explaining it indepth . I am primarily interested in >> understading flowcontrol as well as syntax . >> > Flow control, if I'm not misinterpreting your usage, is something > that most common language books will not really cover -- that falls into > the realms of software engineering... He *might* simply be talking about if, for, while, break and so on -- things which control program flow. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From Lie.1296 at gmail.com Sun Mar 9 13:45:43 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 10:45:43 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> Message-ID: On Mar 9, 9:29?pm, Kay Schluehr wrote: (snip) > You are an appropriate person to consider the workflow in a dynamic > language, no matter how the language is implemented internally. I agree, but the only thing I'm not confident to talk about is how it'll be implemented, since I think an idea should suggest how it can be implemented in practice to show that it's not just a nonsense paper idea that's not possible in reality. > Just start with function calls > > ? ?maybe_raise(ZeroDivisionError) > > The only requirement is that maybe_raise has to know when it shall > raise ZeroDivisionError. This depends on whether the exception is > caught. How do the program knows this in advance? There are no static > analysis techniques available. Perhaps similar technique the compiler uses to determine whether a function is a normal function or a generator function? Positive forward lookup for any soft exceptions, which would then activate matching soft exceptions inside the code? > When maybe_raise is entered the system must know that the exception is > handled in the future. You can't inspect the call stack for this > purpose because the call stack represents past events and > continuations ( and you can't rely on names ). > > So you need something like this > > ? ?do_softexception(ZeroDivisionError) > ? ?try: > ? ? ? TRY_BLOCK > ? ?except ZeroDivisionError: > ? ? ? EXCEPT_BLOCK > > But this looks odd and the solution isn't DRY. So better one macro- > transforms a new statement into this form. From mark.e.tolonen at mailinator.com Mon Mar 17 23:33:10 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Mon, 17 Mar 2008 20:33:10 -0700 Subject: struct unpack References: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> Message-ID: "brnstrmrs" wrote in message news:1878d2f6-8a87-4599-98bb-2d3d2bcbce7f at u72g2000hsf.googlegroups.com... > If I run: > > testValue = '\x02\x00' > junk = struct.unpack('h', testValue) > > Everything works but If I run > > testValue = raw_input("Enter Binary Code..:") inputting at the > console '\x02\x00' > junk = struct.unpack('h', testValue) > > It errors out with > Traceback (most recent call last): > File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in > junk = struct.unpack('h', testValue) > File "struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 2 > > any ideas? raw_input doesn't understand escape sequences. You have to decode them. import struct testValue=raw_input() # input '\x02\x00' junk = struct.unpack('h',testValue.decode('string_escape')) --Mark From ggpolo at gmail.com Thu Mar 27 10:58:36 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 11:58:36 -0300 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: 2008/3/27, Skip Montanaro : > I am trying to replace os.system calls with subprocess.Popen. This simple > example fails miserably: > > >>> proc = subprocess.Popen ("ls /tmp") proc = subprocess.Popen ("ls /tmp", shell=True) or proc = subprocess.Popen (["ls", "/tmp"]) should work. > Traceback (most recent call last): > File "", line 1, in > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 594, in __init__ > errread, errwrite) > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 1091, in > _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I also tried explicitly referencing /usr/bin/ls. Same result. What gives? > I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with > 2.6alpha on Mac OS X. > > Frustrated in Chicago... > > Skip > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bagpussnz at gmail.com Sun Mar 9 22:00:26 2008 From: bagpussnz at gmail.com (Bagpussnz) Date: Sun, 9 Mar 2008 19:00:26 -0700 (PDT) Subject: Python 2.5 segmentation faulting importing random Message-ID: <788c15f8-9701-470e-9262-c9f6b3297598@s12g2000prg.googlegroups.com> Hi, Whenever I try to import random in a python module, I get a segmentation fault. I've traced it using, import pdb pdb.set_trace() import random When it gets to.. > /usr/lib/python2.5/random.py(57)() -> LOG4 = _log(4.0) It seg faults. I'm running on OpenSuse 10.2. Linux devhost 2.6.18.8-0.7-bigsmp #1 SMP Tue Oct 2 17:21:08 UTC 2007 i686 i686 i386 GNU/Linux The python header says.. Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Any ideas? Regards, Ian. From Lie.1296 at gmail.com Mon Mar 10 14:47:54 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 10 Mar 2008 11:47:54 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> Message-ID: On Mar 10, 12:12?pm, John Nagle wrote: > Steven D'Aprano wrote: > > On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > > >> On 9 Mrz., 06:30, Steven D'Aprano >> cybersource.com.au> wrote: > >> Is it really so exotic that it requires the demand for more use cases? > > > Are the existing solutions really so incomplete that we need yet another > > solution? > > > What problem are you trying to solve with SoftExceptions? > > ? ? I actually implemented something like "soft exceptions" in a LISP > program long ago. I called them "gripes". ?They were a way that a function > could complain about something it wanted the caller to fix. The caller > could either fix it or decline to do so. > > ? ? This was for a robotic planning application, where one module had detected > that some precondition that it needed wasn't satisfied. ?This was usually > something like some physical object being in the wrong place for a later > operation, and a previously planned move needed to be modified. Passing > the problem back to the caller sometimes allowed an easy fix, rather than > aborting the whole plan and building a new one. > > ? ? This isn't a common problem. > > ? ? In the rare cases that it is needed, it can be implemented with callbacks. > It doesn't require a language extension. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle The problem with callbacks is that it works only for a small amount of callbacks, it'd be too messy to have twenty different callbacks. And the ultimate problem with callbacks is that we can't determine from the outside whether the operation should continue or breaks at the point of the callback without some messy trick. We can't always determine whether we want to do this: def somefunc(argA, argB, callback = DO_NOTHING): if argA == argB: callback() or this: def somefunc(argA, argB, callback = DO_NOTHING): if argA == argB: callback() return perhaps we could do this: if argA == argB: if callback() == True: return but that's so much extra codes written and would've been too messy to write. And actually this isn't a rare cases, and in fact is very common. It's just that most cases that can be more cleanly written in SoftException, can usually be handled in different ways, using tricks that range from subtle to messy (like callbacks). From leszek at dubiel.pl Wed Mar 12 07:44:45 2008 From: leszek at dubiel.pl (Leszek Dubiel) Date: Wed, 12 Mar 2008 12:44:45 +0100 Subject: Some thoughts on defining built-in types Message-ID: <47D7C22D.8040209@dubiel.pl> An HTML attachment was scrubbed... URL: From skunkwerk at gmail.com Tue Mar 25 23:31:19 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 25 Mar 2008 20:31:19 -0700 (PDT) Subject: subprocess.popen function with quotes Message-ID: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> Hi, i'm trying to call subprocess.popen on the 'rename' function in linux. When I run the command from the shell, like so: rename -vn 's/\.htm$/\.html/' *.htm it works fine... however when I try to do it in python like so: p = subprocess.Popen(["rename","-vn","'s/\.htm$/ \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] nothing gets printed out (even for p.communicate()[1]) I think the problem is the quoted string the rename command wants - when I put it in triple quotes like """s/\.htm$/\.html/""" I get some output, but not the correct output. I've also tried escaping the single quotes with \' and putting it in regular double quotes but that didn't work either. i'd appreciate any help From adrianbn at gmail.com Tue Mar 18 05:16:49 2008 From: adrianbn at gmail.com (=?ISO-8859-1?Q?Adri=E1n_Bravo_Navarro?=) Date: Tue, 18 Mar 2008 10:16:49 +0100 Subject: Comunicate processes with python In-Reply-To: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> Message-ID: <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> Hi, Does the absence of answers mean that the unique way to let the console invoke daemon functions is trough dbus or sockets? I wonder if python provides any other mechanism to get this. Thanks Adrian 2008/3/17, Adri?n Bravo Navarro : > > Hi, > > let me introduce ourselves first. We are a smallish group of students > working on a open source snapshot/backup system (www.hdlorean.com or > http://launchpad.net/hdlorean). We are using python for almost all of the > code and for all of us this is the first python project we develop. At this > point I must say that we are really happy with python, as it is a fast > learning and easy language. > > Now I've just bored most of you, I would like to make a question to the > list. Let me portray the scenario: > > We have a daemon (hdloreand) running. We also have a console so you can > send commands to the daemon and retrieve some info. At this moment, that > console is connecting to the daemon via Dbus. We would like to avoid this, > because it will solve some collateral problemas as well as will guarantee > that the comunication will work when no X server and no dbus session is > running. > > Is there any simple way to achieve this goal? We've been thinking of > sockets but Im not conviced at all with that. > > Thanks > Adrian > > PS: Im sorry for my english. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marek.rocki at wp.pl Mon Mar 17 10:59:04 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Mon, 17 Mar 2008 07:59:04 -0700 (PDT) Subject: pass float array(list) parameter to C References: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> Message-ID: <013c161a-931c-4576-935d-4341911a299f@s37g2000prg.googlegroups.com> You can also do it with ctypes only; too bad it's not really well documented. c_float is a type of a floating point number and it has * operator defined, so that c_float*4 is a type of a 4-element array of those numbers. So if you want to construct an array of floats from a list of floats, you can do it like this: from ctypes import c_float x = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9] float_array_type = c_float*len(x) float_array = float_array_type(*x) print float_array From radix at twistedmatrix.com Wed Mar 26 21:26:11 2008 From: radix at twistedmatrix.com (Christopher Armstrong) Date: Wed, 26 Mar 2008 21:26:11 -0400 Subject: [ANN] Twisted 8.0 Message-ID: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> http://twistedmatrix.com/ MASSACHUSETTS (DP) -- Version 8.0 of the Twisted networking framework has been released, Twisted Matrix Laboratories announced Wednesday. Enslaved by his new robotic overloads, Master of the Release Christopher Armstrong presented the new package to the Internet on March 26th. Armstrong was unable to comment, because of a device worn around his neck preventing him from doing so, scientists say. Secretary of Defense Jean-Paul Calderone was asked about concerns that French interference may have played a role in the delay of this release. "I find such speculation preposterous. Thomas Herv? is an upstanding member of the Labs and his loyalties lie with us. He is a fine addition to our team." Rumors in the community allege that Secretary Calderone is holding Herv?'s cat ransom until the release is successfully distributed. Herv? was unavailable for comment. This release comes shortly after the announcement by Chief of Public Affairs Duncan McGreggor that Twisted had joined the Software Freedom Conservancy. "We're happy to join the SFC, and we are now accepting sponsorship. The fact that we are now ruled by a cabal of robots should not put off potential donors. Our robotic overlords are running us at peak efficiency, so we can most effectively distribute The Love." Asked about the version number jump in this release, Commander-in-Chief Glyph Lefkowitz had the following to say: "Our benefactors have found our previous dice-rolling version number scheme to be inadequate, and have deigned to propose to us a more... logical system of versioning." ===== Twisted is an event-based framework for Internet applications which works on Python 2.3, 2.4, and 2.5. It can be downloaded from http://twistedmatrix.com/ Twisted 8.0 is a major feature release, with several new features and a great number of bug fixes. Some of the highlights follow. - The IOCP reactor is now much improved and many bugs have been resolved. - Twisted is now easy_installable. - Many improvements were made to Trial, Twisted's unit testing system. - A new memcache client protocol implementation was added. - So much more[1]! To see the full list of changes in its fifteen kilobytes of glory, see the release notes[1]. We welcome you to download and enjoy, and please file any bugs you find[2] and send comments to the mailing list[3]. Why the large version number bump? We've decided to switch to a time-based versioning scheme. "8.0" means the first release in 2008. [1] http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.0.1/NEWS?format=raw [2] Register: http://twistedmatrix.com/trac/register New ticket: http://twistedmatrix.com/trac/newticket [3] http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python Thanks! -- Christopher Armstrong International Man of Twistery http://radix.twistedmatrix.com/ http://twistedmatrix.com/ http://canonical.com/ From anand.prabhakar.patil at gmail.com Sat Mar 1 13:29:23 2008 From: anand.prabhakar.patil at gmail.com (Anand Patil) Date: Sat, 1 Mar 2008 10:29:23 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> References: <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> Message-ID: <2bc7a5a50803011029rf19982etda274d5da12be1@mail.gmail.com> Not sure if this is common knowledge yet but Sympy, http://code.google.com/p/sympy, has a rational type. In [2]: from sympy import * In [3]: Rational(21,4) Out[3]: 21/4 In [4]: Rational(21,4)+Rational(3,4) Out[4]: 6 From missxxy78 at gmail.com Thu Mar 13 08:20:19 2008 From: missxxy78 at gmail.com (MSmith) Date: Thu, 13 Mar 2008 05:20:19 -0700 (PDT) Subject: Diary of a Stripper. Message-ID: <47d9876e-54a0-4139-81bd-2c28cc24122d@u10g2000prn.googlegroups.com> Hi, my name is Michelle, I'm 27, just left being a secretary to become a stripper, and looking for friends to talk to. I love meeting new people! I also have a blog where I talk about my life... http://missxxy.blogspot.com Talk to you soon! Michelle From kellygreer1 at yahoo.com Wed Mar 26 14:50:30 2008 From: kellygreer1 at yahoo.com (kellygreer1) Date: Wed, 26 Mar 2008 11:50:30 -0700 (PDT) Subject: Filtering a Python list to uniques References: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> Message-ID: On Mar 26, 5:45 am, hellt wrote: > On 26 ???, 02:30,kellygreer1 wrote: > > > What is the best way to filter a Python list to its unique members? > > I tried some method using Set but got some "unhashable" error. > > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > > # how do i reduce this to > > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > > Is there a page on this in the Python in a Nutshell or the Python > > Cookbook? > > Did I miss something? > > > Kelly Greer > > kellygre... at nospam.com > > change nospam to yahoo > > or just look this thread for a fastest solutionhttp://groups.google.com/group/comp.lang.python/browse_frm/thread/709... How come the Set() thing seems to work for some people and I get the 'unhashable' error? How do you test for 'membership' on a dictionary? # where tmp is the non-unique list # dct is a dictionary where each unique key will be tied to a count (the value) # for testing I was setting the count to 0 for v in tmp: if not v in dct: dct[v] = 0 # I get unhashable error here. # Even if I write it. for v in tmp: if not v in dct.keys(): dct[v] = 0 What am I missing? Thanks, Kelly From castironpi at gmail.com Mon Mar 10 02:39:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 23:39:03 -0700 (PDT) Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> <3ebaa96f-7c93-4aa8-a7d2-13764140831f@k13g2000hse.googlegroups.com> Message-ID: <7569e294-df4b-42d9-8263-f3b3f6377682@s50g2000hsb.googlegroups.com> > > I am trying to solve a genetic algorithm problem where I want to read > > a bitvector of very large size (say 10000) and manipulate bits based > > on certain algorithms. Here's one on the Python website: http://search.live.com/results.aspx?q=python+bitvector&src=IE-SearchBox => http://pypi.python.org/pypi/BitVector/1.3 => http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.3.html code=> http://cobweb.ecn.purdue.edu/~kak/dist/BitVector_1.3_CodeOnly.py.html "The bits of a bit array are stored in 16-bit unsigned ints." However, Python has variable size longs. Do you want something less elaborate? Here is what I think of when you say bitvector: bA= bitvector() bA[3]= 0 bA[7]= 1 bA[2].set() bA[1]^= b[9] bA[2:6].set() rangeA= ba[2:7] rangeA= "011101" rangeA.clear() bytearray is kind of close, but new in Py 3.0. How close is it to the perspective of the application you're writing? Here's some of it straight off the console: >>> b= bytearray(5) >>> b bytearray(b'\x00\x00\x00\x00\x00') >>> b[1]= 1 >>> b bytearray(b'\x00\x01\x00\x00\x00') >>> list(b) [0, 1, 0, 0, 0] From piet at cs.uu.nl Mon Mar 10 10:33:47 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 10 Mar 2008 15:33:47 +0100 Subject: Python-URL! - weekly Python news and links (Feb 18) References: Message-ID: >>>>> Peter Otten <__peter__ at web.de> (PO) wrote: >PO> Piet van Oostrum wrote: >>>>>>>> "Gabriel Genellina" (GG) wrote: >>> >GG> "Given this indispensable process and architecture issue, isn't it >>>> obvious GG> that it's totally irrelevant to the system's overall safety >>>> whether the GG> compiler has performed the further smattering of >>>> semantically puny GG> 'verifications' allowed by mandatory-declaration, >>>> stating-typing GG> languages?" - Alex Martelli >>> >>> I couldn't find the original of this. I would like to see it in its >>> context. Googling didn't reveal anything but this Python-URL. >PO> My google is better than yours then: >PO> http://mail.python.org/pipermail/python-list/2003-March/193864.html Thanks. I probably have searched for "mandatory-declaration, static-typing languages" instead of "mandatory-declaration, stating-typing languages" -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From missxxy78 at gmail.com Sat Mar 15 06:50:47 2008 From: missxxy78 at gmail.com (MSmith) Date: Sat, 15 Mar 2008 03:50:47 -0700 (PDT) Subject: I found affordable health insurance. Message-ID: I couldn't believe it. Do yourself a favour and at least check it out: http://www.jdoqocy.com/click-2924912-10359791 Michael From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 00:28:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 04:28:19 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13utucbj9mkrpd4@corp.supernews.com> Message-ID: <13uu5n326bfvr86@corp.supernews.com> On Sun, 30 Mar 2008 00:27:45 -0300, Gabriel Genellina wrote: > En Sat, 29 Mar 2008 23:23:07 -0300, Steven D'Aprano > escribi?: > >> The general problem is that I wish to time an arbitrary function with >> arbitrary arguments. The function and arguments are provided to me as >> Python objects, but timeit requires strings. Converting the objects to >> strings is not practical, and the objects might not exist in the >> __main__ module. > > Ah, ok, I understand now. I think this is more-or-less what you want: [snip] No, sorry, it's still sharing state. from timeit import Timer # Slight modification to the function to return the Timer object. def timeanyfunc(fn, *args, **kw): global wrapped_fn def wrapped_fn(): return fn(*args, **kw) return Timer("wrapped_fn()", "from %s import wrapped_fn" % __name__) def functionA(): print "Function A" def functionB(): print "Function B" T1 = timeanyfunc(functionA) T2 = timeanyfunc(functionB) T1.repeat(3, 1) # Should print "Function A". T2.repeat(3, 1) # Should print "Function B". -- Steven From jeff at schwabcenter.com Mon Mar 17 11:33:48 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 08:33:48 -0700 Subject: python-list Metaquestion In-Reply-To: References: Message-ID: Tom Stambaugh wrote: > I continue to receive emails, addressed to python-list-bounces at python.org, > with subject: "Re: Your message to Python-list awaits moderator approval", > which read: > >> Your mail to 'Python-list' with the subject >> >> (no subject) >> >> Is being held until the list moderator can review it for approval. >> >> The reason it is being held: >> >> Message has a suspicious header > > I'm happy to adjust my headers in whatever way is needed, if I know what the > problem is. Is there FAQ somewhere that tells me what I should change? Contact the list administrator and ask whether their spam filters are starting to turn green. http://www.python.org/cgi-bin/faqw-mm.py?req=show&file=faq03.059.htp From martin at v.loewis.de Mon Mar 3 17:48:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2008 23:48:31 +0100 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> <47CB9F3C.9030202@v.loewis.de> Message-ID: <47CC803F.4090109@v.loewis.de> > Can you also add a note to the 2.3 and 2.4 web pages? You mean the 2.3.7 and 2.4.5 web pages? Sure. (If you mean some other web pages, please give precise URLs). Regards, Martin From tjreedy at udel.edu Sun Mar 9 22:14:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Mar 2008 22:14:26 -0400 Subject: any chance regular expressions are cached? References: Message-ID: wrote in message news:bu%Aj.5528$fX7.893 at nlpi061.nbdc.sbc.com... | I've got a bit of code in a function like this: | | s=re.sub(r'\n','\n'+spaces,s) | s=re.sub(r'^',spaces,s) | s=re.sub(r' *\n','\n',s) | s=re.sub(r' *$','',s) | s=re.sub(r'\n*$','',s) | | Is there any chance that these will be cached somewhere, and save | me the trouble of having to declare some global re's if I don't | want to have them recompiled on each function invocation? The last time I looked, several versions ago, re did cache. Don't know if still true. Not part of spec, I don't think. tjr From dblubaugh at belcan.com Thu Mar 20 15:46:23 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 20 Mar 2008 15:46:23 -0400 Subject: Floating-point support Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3802D19F9A@AWMAIL04.belcan.com> Would anyone know as to how to develop floating point support for the MyHDL module? Has anyone worked with any alternative versions of the IEEE standard for floating -point? Also, has anyone developed a floating-point library for a module within the python environment in order to execute numerical computations. I would imagine since I am translating python to verilog by using MyHDL , that I will have to develop the floating-point support module in python source code as well ?? If I can develop this one feature from MyHDL, it would allow this module to be fairly competitive with commercial products. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sun Mar 16 02:21:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Mar 2008 06:21:45 GMT Subject: Unicode/UTF-8 confusion References: Message-ID: <643sjpF27mbs3U2@mid.uni-berlin.de> On Sat, 15 Mar 2008 16:33:24 -0400, Tom Stambaugh wrote: > I use a trick to let me pass the information into my browser client > application. The browser requests the server information from a form whose > target is a hidden iframe. The string the server serializes is wrapped in > html that embeds it in an onload handler like this: > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > http-equiv="content-type" content="text/html; charset=UTF-8" /> > > > > > > > [?] > > In order to successfully pass the escapes to the server, I already have to > double any each backslash. At the end of the day, it's easier -- and results > in better performance -- to convert each apostrophe to its unicode > equivalent, as I originally asked. > > I just want to know if there's a faster way to persuade simplejson to > accomplish the feat. So you don't ask for JSON encoded objects but JSON encoded *and* HTML/JavaScript embeddable escaped literal string. That's simply not the job of a JSON encoder. That's another level of encoding/escaping producing something that is not JSON anymore, so why do you want to ask a JSON encoder to deliver it? This is a feature/function you should find in a HTML templating library. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Mon Mar 3 19:21:52 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Mar 2008 18:21:52 -0600 Subject: sympy: what's wrong with this picture? In-Reply-To: <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 4:08 pm, Robert Kern wrote: >> Mensanator wrote: >>> On Mar 3, 2:49 pm, Carl Banks wrote: >>>> It's just a bug--probably sympy is messing with the internals of the >>>> random number generator. It would be a simple fix. Instead of >>>> b****ing about it, file a bug report. >>> I did. >>>> Or better yet, submit a patch. >>> I would if I knew what the problem was. >> Did you even try to figure it out? It took me all of 5 minutes to find the mistake. > > Could I trouble you to share? Then I could continue my testing. I posted the patch on the bug tracker: http://code.google.com/p/sympy/issues/detail?id=729 >>> I posted it here because someone recommended it. >>> I'm simply un-recommending it. >> It was a mistake, an easily remedied mistake, > > But I didn't know that (and still don't). > >> not a big unchangeable design decision. > > I didn't know that either. For all I know, I might have to > wait for the next version, and who knows when that will be? The point is that you didn't try to figure it out. And you assumed the worst rather than giving anyone the benefit of the doubt. You didn't even wait to get a response from the package maintainer about how serious the issue was before you came here to un-recommend it. All software has bugs. Good software has bugs. Finding a single bug in a package is not sufficient cause to warn people away as if it had the plague. >> If you want to recommend against sympy as a package, there is a larger >> burden of proof that you have yet to meet. > > What kind of burden of proof must one have to recommend it in the > first place? Significantly less. "It was useful to me," is sufficient. -- 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 jgardner at jonathangardner.net Thu Mar 20 10:31:43 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 20 Mar 2008 07:31:43 -0700 (PDT) Subject: eval and unicode References: Message-ID: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> On Mar 20, 5:20?am, Laszlo Nagy wrote: > How can I specify encoding for the built-in eval function? Here is the > documentation: > > http://docs.python.org/lib/built-in-funcs.html > > It tells that the "expression" parameter is a string. But tells nothing > about the encoding. Same is true for: execfile, eval and compile. > > The basic problem: > > - expressions need to be evaluated by a program > - expressions are managed through a web based interface. The browser > supports UTF-8, the database also supports UTF-8. The user needs to be > able to enter string expressions in different languages, and store them > in the database > - expressions are for filtering emails, and the emails can contain any > character in any encoding > > I tried to use eval with/without unicode strings and it worked. Example: > > ?>>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? > ?????? ????????? ???????"' ) > True > > The above test was made on Unbuntu Linux and gnome-terminal. > gnome-terminal does support unicode. What would happen under Windows? > > I'm also confused how it is related to PEP 0263. I always get a warning > when I try to enter '"????????? ????????? ???????"' in a source > file without "# -*- coding: " specified. Why is it not the same for > eval? Why it is not raising an exception (or why the encoding does not > need to be specified?) > Encoding information is only useful when you are converting between bytes and unicode data. If you already have unicode data, you don't need to do any more work to get unicode data. Since a file can be in any encoding, it isn't apparent how to decode the bytes seen in that file and turn them into unicode data. That's why you need the # -*- coding magic to tell the python interpreter that the bytes it will see in the file are encoded in a specific way. Until we have a universal way to accurately find the encoding of every file in an OS, we will need that magic. Who knows? Maybe one day there will be a common file attribute system and one of the universal attributes will be the encoding of the file. But for now, we are stuck with ancient Unix and DOS conventions. When you feed your unicode data into eval(), it doesn't have any encoding or decoding work to do. From newsgroup898sfie at 8439.e4ward.com Mon Mar 3 21:57:59 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Mon, 03 Mar 2008 21:57:59 -0500 Subject: 'normal' shell with curses Message-ID: <633s5lF24prinU1@mid.uni-berlin.de> Hi, I'm trying to print out text in color. As far as I know, curses is the only way to do that (or not?). So, what I ultimately want is a curses terminal that behaves as closely as possible as a normal terminal, i.e. it breaks lines and scrolls automatically, so that I can implement a function myprint(color, text) that does what print() does, only in color. So, my first tests brought up some problems: #!/usr/bin/python from time import sleep import curses import sys stdscr = curses.initscr() stdscr.addstr("Initialized\n") stdscr.refresh() (maxlines, maxcolumns) = stdscr.getmaxyx() try: for counter in xrange(24): stdscr.addstr("Hello world %s\n" % counter) stdscr.refresh() if counter >= maxlines: stdscr.scroll() stdscr.refresh() except Exception, data: sys.stderr.write("Exception: \n"); sys.stderr.write(str(data)); finally: sleep(5) curses.endwin() Instead of scrolling, the program throws an exception. Any hints? Also, is there a way leave the curses output on the screen after curses.endwin(), instead of returning to the normal terminal without a trace of curses. Thanks, Michael From software at ginstrom.com Wed Mar 5 20:51:58 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 6 Mar 2008 10:51:58 +0900 Subject: Unit testing Web applications In-Reply-To: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> References: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> Message-ID: <0c1401c87f2c$aa179560$0203a8c0@MOUSE> > On Behalf Of Monica Leko > Does Python has some testing frameworks for testing Web > applications (like Cactus and HttpUnit for Java), generating > requests and checking if the response is correct? I have got a lot of traction using mechanize [1] with nose [2]. Of course that still leaves out testing JavaScript. For that, something like PAMIE [3] is one way to go. [1] http://wwwsearch.sourceforge.net/mechanize/ [2] http://somethingaboutorange.com/mrl/projects/nose/ [3] http://pamie.sourceforge.net/ Here's an example of how I use mechanize + nose: # test_index.py from mechanize import Browser class TestPageLoads: def setup(self): self.mech = Browser() self.mech.set_handle_robots(False) # use thought and consideration... def test_nonexistent(self): try: response = self.mech.open("http://honyaku-archive.org/nonexistent/") assert False, "Should have thrown here" except Exception, e: assert "404" in str(e), e def test_index(self): response = self.mech.open("http://honyaku-archive.org/") assert response.code == 200, response.code def test_index_title(self): response = self.mech.open("http://honyaku-archive.org/") assert self.mech.title().strip() == "Honyaku Archive :: Home", self.mech.title() Regards, Ryan Ginstrom From sam at ausdia.com Tue Mar 11 00:35:02 2008 From: sam at ausdia.com (samsappleton) Date: Tue, 11 Mar 2008 04:35:02 -0000 Subject: python "import" of statically linked module with SWIG Message-ID: Hi I compiled a SWIG wrapper & linked it with a main program in C (i'm extending the main program/C with a python interpreter). How can I "import" the swig wrapper module in Python? If I just use "import ", of course I get ImportError: no module named XXXX I don't want to expose any .so files if possible i.e. not dynamically linked. Sam From dave_mikesell at fastmail.fm Sun Mar 16 10:49:01 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sun, 16 Mar 2008 07:49:01 -0700 (PDT) Subject: Python and 3D References: Message-ID: <8b29c32b-da7c-4254-9ecc-cfeefc9c26b2@b64g2000hsa.googlegroups.com> On Mar 15, 3:09 pm, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs This is more of a question about Alias than Python. I googled it and found Autodesk's AliasStudio (which apparently used to be Alias Wavefront) - is this what you're talking about? There is a C++ API, which could be wrapped in Python using something like SWIG. From castironpi at gmail.com Sun Mar 30 01:37:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 22:37:07 -0700 (PDT) Subject: Help me on function definition References: <4c1c2834-2ecb-46b6-a4ee-eb29d23cbf1a@a1g2000hsb.googlegroups.com> Message-ID: On Mar 29, 11:45?pm, hdante wrote: > On Mar 28, 10:47 pm, "aeneng" wrote: > > > Hello everyone, > > ?Hi, > > ?Always avoid reinventing the wheel: > > from Numeric import array, cross_product > a = array([1, 2, 3]) > b = array([4, 5, 6]) > print cross_product(a, b) > > ?See: > ?http://numpy.scipy.org/ > ?http://www.scipy.org/ > > ?(hint: consider that many people want to multiply matrices) :-) > > > > > > > I am just starting to use python in numerical cacluation. > > I need you to help me to see what's wrong with the following piece of > > codes, which computes the cross product of two vectors and returns > > the result. u and v are two 3x1 matrix. > > > when I import the function, error message show like this>>> import cross > > > Traceback (most recent call last): > > ? File "", line 1, in ? > > ? File "cross.py", line 8 > > ? ? ppp2=u[2]*v[0]-u[0]*v[2] > > ? ? ^ > > SyntaxError: invalid syntax > > > WHAT IS WRONG WITH MY CODE? > > > I appreciate your help. > > > ##here is the function definition. > > ##cross.py## > > def cross(u,v) > > ? ? """input two vectors u and v in 3-D space, > > ? ? ? ?output a cross product of vector w, in column or in row > > accordingly.""" > > ? ? ppp1,ppp2,ppp3=0.0,0.0,0.0 > > ? ? ppp1=u[1]*v[2]-u[2]*v[1] > > ? ? ppp2=u[2]*v[0]-u[0]*v[2] > > ? ? ppp3=u[0]*v[1]-u[1]*v[0] > > ? ? # store the result of the cross product in u > > ? ? u[0]=ppp1 > > ? ? u[1]=ppp2 > > ? ? u[2]=ppp3 > > ? ? return u #return the cross product of vector u x v. > > if __name__=="__main__": > > ? ? ? ? from cvxopt.base import matrix > > ? ? ? ? u=matrix([1.0,0.0,0.0],(3,1)) > > ? ? ? ? v=matrix([0.0,1.0,0.0],(3,1)) > > ? ? ? ? print cross(u,v) > > ? ? ? ? print "file name is %s" %__name__- Hide quoted text - Bandwidth is really low; offload logic. I'd run some AI for the games so you can get a couple more triangles... plot.thicken() From vedrandekovic at gmail.com Sat Mar 29 08:23:58 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Sat, 29 Mar 2008 05:23:58 -0700 (PDT) Subject: Create executable from executable with py2exe Message-ID: Hello, Is there any example how can I create executable from executable with py2exe.For example if I create main executable with some TextEntry ( wxpython ) and then when i write this code into this entry: import os print os.getcwd() print "ok" ...to main executable convert this code into executable with py2exe. Sorry for my english! Regards, Vedran From haag at lsu.edu Sun Mar 16 17:11:06 2008 From: haag at lsu.edu (Alaric Haag) Date: Sun, 16 Mar 2008 16:11:06 -0500 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: In article <5bd37c10-af5d-4254-8799-49c762673a3e at n58g2000hsf.googlegroups.com>, Bruce Eckel wrote: > If the following seems unnecessarily harsh, it was even more harsh for ..... As a relative noob to the Python world, (and lurker to the list :) ) I can't speak to differences from previous years. However, my impressions as a first-timer are much in alignment with you Bruce. Many lightening talk seemed to me to be more about recruiting than selling though. Whereas I might have been discovering a vendor for the first time in a lightening talk, it wasn't a particularly good use of my time here. I'll FIND the commercial vendor, because, if they have a good product, word will get around, aided by their web presence, and formidable advertising budget. On the other hand, bleeding edge use of Python in a lab on a distant continent (just for example) is going to be much harder to both discover, much less get the added bonus of face-to-face time with the developer! That said, I thank the organizers, and welcome the new friendships made at this event, and hope like hell I can come next year!! Alaric From dave_mikesell at fastmail.fm Mon Mar 10 18:28:50 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Mon, 10 Mar 2008 15:28:50 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: On Mar 10, 2:21 pm, Bob Martin wrote: > > Java is more portable than most other languages, especially if your app needs a gui. The promise of Java portability was one of the biggest scams ever perpetrated on the software industry. There are issues going from OS to OS, VM to VM, DB to DB, app server to app server, etc. Certainly no easier than porting C++ and the appropriate libraries, IMHO. From sjdevnull at yahoo.com Mon Mar 17 15:51:14 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 17 Mar 2008 12:51:14 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> Message-ID: <8ca43caa-5a2c-4b7b-b168-aad4cfb0581a@a23g2000hsc.googlegroups.com> On Mar 17, 12:15 pm, rockingred wrote: > On Mar 10, 11:30 am, "sjdevn... at yahoo.com" > wrote: > > > Fix that. That's usually something that's fairly easy to get done as > > a programmer (I've had to do it at 2 of the last 4 places I worked). > > Just go explain all the problems that can happen by not having VC and > > all the benefits it brings to your managers, and that there's a good > > free VC system that will work for everyone, and it'll likely become a > > mandate pretty quickly. > > > It's almost certainly worth fixing that problem rather than mucking > > around with half-solutions. > > Unfortunately, no free VC system existed for the language in which I > was programming Explain? VC isn't language-specific. From trentm at activestate.com Thu Mar 6 16:49:00 2008 From: trentm at activestate.com (Trent Mick) Date: Thu, 06 Mar 2008 13:49:00 -0800 Subject: system32 directory In-Reply-To: <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: <47D066CC.6080503@activestate.com> > I was aiming to figure out if the standard modules shipped with Python > could do this already before I started using 3rd party libraries. Thanks. You could also manage it with the ctypes module, if you consider that standard: it is in the python.org and ActivePython distros as of Python 2.5. Cheers, Trent -- Trent Mick trentm at activestate.com From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:16:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:16:45 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <13t3c5t4hau9075@corp.supernews.com> On Fri, 07 Mar 2008 11:58:38 -0500, D'Arcy J.M. Cain wrote: >> 2. You should use two spaces after a >> sentence-ending period. >> >> For heavens sake, why? I've always been obstructed by the double blanks >> but >> tolerated them. Now, that i read that it actually is a recommendation, >> i need to ask about the purpose. > > Like many things of this nature, the purpose is to follow the rules of > correct English usage. Except English grammar does not and never has specified using two spaces after a period. The (bad) habit of doing so was introduced by typists, in the old days of manual typewriters, in the belief (completely bogus, in my opinion) that a larger gap between sentences would make them more readable. I believe that the larger gap is a distraction, one of the reasons that typewriter text is generally harder to read than properly typeset text. I believe it is one of those things that everybody (for some value of "everybody") does because that's what they were taught to do, and they were taught to do it because that's what their teachers were taught, and so on all the way back to some nutter who just decided that *he* was going to use two spaces after a period because the Great and Mighty Pumpkin told him to. Professional typesetters, using proportional fonts, don't use double- spaces because it throws off word spacing and line justification and just plain looks ugly. I suppose that since coders typically use non- proportional fonts, we can at least justify the use of two spaces with a claim that it aids readability for "typewriter fonts" -- if you believe such a thing, which I do not. -- Steven From petr.jakes.tpc at gmail.com Thu Mar 6 15:07:21 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Thu, 6 Mar 2008 12:07:21 -0800 (PST) Subject: Data aggregation References: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> <47d039a6$0$36391$742ec2ed@news.sonic.net> Message-ID: On Mar 6, 7:44 pm, John Nagle wrote: > vedranp wrote: > > I would like to avoid the step of taking data out from database in > > order to process it. > > You can probably do this entirely within SQL. Most SQL databases, > including MySQL, will let you put the result of a SELECT into a new > table. > > John Nagle I agree, maybe following can help http://tinyurl.com/32colp Petr Jakes From castironpi at gmail.com Mon Mar 3 20:12:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 17:12:43 -0800 (PST) Subject: metaclasses Message-ID: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> What are metaclasses? From santhosh.cnp at gmail.com Sun Mar 16 01:14:43 2008 From: santhosh.cnp at gmail.com (santhosh kumar) Date: Sun, 16 Mar 2008 10:44:43 +0530 Subject: Regular Expression Help Message-ID: <957ae7d80803152214se4b3012xaef709afed4f1f52@mail.gmail.com> Hi all, I have text like , STRINGTABLE BEGIN ID_NEXT_PANE "Cambiar a la siguiente secci?n de laventana \nSiguiente secci?n" ID_PREV_PANE "Regresar a la secci?n anterior de laventana\nSecci?n anterior" END STRINGTABLE BEGIN ID_VIEW_TOOLBAR "Mostrar u ocultar la barra de herramientas\nMostrar/Ocultar la barra de herramientas" ID_VIEW_STATUS_BAR "Mostrar u ocultar la barra de estado\nMostrar/Ocultar la barra de estado" END ................................ .................................... .......................................... and i need to parse from STRINGTABLE to END as a list object. whatkind of regular expression should i write. -- Regards, Santhoshkumar.S -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtanksleyjr at gmail.com Mon Mar 31 13:03:30 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 31 Mar 2008 10:03:30 -0700 (PDT) Subject: How to get an XML DOM while offline? References: <64cpnvF2at1j9U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > The most pragmatic solution would be to rip the doctype out using simple > string methods and/or regexes. Thank you, Diez and Paul; I took Diez's solution, and it works well enough for me. > Diez -Wm From castironpi at gmail.com Sun Mar 30 01:43:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 22:43:05 -0700 (PDT) Subject: Serial port error statistics - any comparable data? References: <657qh1F2es9vnU1@mid.uni-berlin.de> Message-ID: <5da93cbc-0e6f-420b-a7da-eb64c89ba534@x41g2000hsb.googlegroups.com> On Mar 29, 4:26?pm, "Diez B. Roggisch" wrote: > Hendrik van Rooyen schrieb: > > > > > > > Hi, > > > I have been doing some tests on a device that > > we are thinking of incorporating into a product, > > and I have seen that reception on a serial port > > at 115200 baud over about six metres of RS-232 > > cable makes mistakes, to the order of 125 lines > > with errors in them out of approximately 18.4 > > million lines of 65 or so chars - about one errored > > line in 147000, or one error character in 95 million. > > > The PC that is making the errors is a 64 bit dual > > core AMD machine running at 2 Gig, and I am > > running stock standard Open Suse 10.3 with > > the supplied Python 2.5. > > > What kind of bothers me is the nature of the errors - > > I seem to get only missing characters, as if an > > interrupt was missed. ?There are no munged characters > > as one would expect if the errors were bit related. > > > Has anyone else seen anything like this, and am I worrying > > needlessly? > > > I realise that my production protocols will easily handle > > this almost non existent level of error - but if this were in > > microcontroller code that I had written myself, I would > > suspect that I was spending too long in some critical > > section of code. > > RS232 is unfortunately as bad as a "protocol" as it can get. I've used > it for communication with a microcontroller for just a few bytes every > second. And it failed miserably, so I needed to implement a protocol on > top of it. > > The machine spec is totally irrelevant - what is interesting is the > serial hardware you use. Are you by any chance using a > serial2usb-converter? I had nothing but troubles with these. > > if you have the chance, try & attach a machine with legacy rs232 port, > and see if the errors still remain. Transmit observed minus expected to cluster. What kind of tables does the input device build? From chickenpotatoe at hotmail.com Sun Mar 30 00:38:32 2008 From: chickenpotatoe at hotmail.com (chickenpotatoe at hotmail.com) Date: Sat, 29 Mar 2008 21:38:32 -0700 (PDT) Subject: Redacted References: Message-ID: <39555677-50ca-4336-b864-8b06eae1566e@i29g2000prf.googlegroups.com> Redacted From mail at timgolden.me.uk Sun Mar 16 02:44:20 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 06:44:20 +0000 Subject: Spaces in path name In-Reply-To: References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> Message-ID: <47DCC1C4.2010806@timgolden.me.uk> joep wrote: > On Mar 15, 5:42 pm, joep wrote: >>> http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... >> Note: this works for subprocess.call but for subprocess.Popen this >> does not work if there are two arguments in the command line with >> spaces. Especially, even after trying out many different versions, I >> never managed to get subprocess.Popen to work, when both the >> executable and one argument have spaces in the file path. >> > > Sorry, incomplete sentence > > Especially, even after trying out many different versions, I never > managed to get subprocess.Popen to work '''when command line is given > as a *list* argument to subprocess.Popen''' > in the case when both the executable and one argument have spaces in > the file path. Thanks for the info. I'll get on the case and put some examples together with caveats. TJG From bj_666 at gmx.net Mon Mar 17 03:29:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Mar 2008 07:29:56 GMT Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? References: Message-ID: <646kvkF2ao2tkU2@mid.uni-berlin.de> On Sun, 16 Mar 2008 14:21:40 +0100, martin f krafft wrote: > Hi, > > xmlrpclib.dumps((None,), allow_none=True) yields > > '\n\n\n\n' > > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' > > Those are valid XML and valid XML-RPC, but isn't. In XML-RPC there is no `None`, so there's the non standard `allow_none` Option to allow `None` to be represented as ````. And is an empty or really valid XML-RPC? Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Fri Mar 14 18:20:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 15:20:59 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: On Mar 14, 5:16?pm, Roel Schroeven wrote: > castiro... at gmail.com schreef: > > > On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: > >>> Subject: RIP: Joseph Weizenbaum > >>> Creator of Eliza: > >>>http://www-tech.mit.edu/V128/N12/weizenbaum.html > >>> -- > >> How do you feel about creator of Eliza? > > > What is Eliza? > > Does that question interest you? He had a dream about a pillow. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 26 08:18:07 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Mar 2008 13:18:07 +0100 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: <47ea3ef9$0$26861$426a74cc@news.free.fr> sam a ?crit : > Bruno Desthuilliers napisa?(a): > >>> In dynamically typed language when you create object A that is >>> inherited from another object B, than object A knows that B is his >>> predecessor. So >>> when you reference A.prop, then prop is looked in A first, then in B, >>> then in predecessors of B, and so on. >> >> What you're describing here is the inheritance mechanism of Python. >> And could apply just as well to javascript prototype mechanism. A >> javascript object has a reference to it's prototype object - that you >> can customize, rebind etc -, a Python object has a reference to it's >> class object - that you can customise, rebind etc... > > I can see that Python and Javascript inheritance model is almost the > same. Both languages are dynamically typed. And it seems that using > "classes" in Python makes some things more complicated then it is > necessary I have to disagree here. > (eg functions, methods and lambdas are differen beeing in > Python concept). The lambda statement creates an ordinary function object, so no difference here - and it has nothing to do with classes vs prototypes. wrt/ functions and methods, what you declare with a def statement within a class statement is actually a plain function (and FWIW, you can add dynamically add methods to classes or instances). Python 'methods' are only thin callable wrappers around the function/class/instance set, wrappers that are dynamically generated by the function object itself when it's looked up on a class or instance, thanks to the descriptor protocol. > > >> Don't be fooled by the term "class" itself - it's meaning is totally >> different in a language like Python. > > Probably I'm not alone. Many people who think dymanic types are Rhight > Thing in programming will also prefer prototype-based programming to > class-based. Chapter and verse, please ? Ok, I repeat (please read more carefully): """ Don't be fooled by the term "class" itself - it's meaning is totally different in a language like Python. """ > >> suspect you don't have a serious knowledge of Python's object model. > > Yes -- I'm new to Python. So may I suggest you actually *learn* how Python's object model works ? From clodoaldo.pinto at gmail.com Tue Mar 25 09:39:57 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Tue, 25 Mar 2008 06:39:57 -0700 (PDT) Subject: sendmail should throw an exception but does not Message-ID: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> I need to know if an email was refused for whatever reason, it makes no difference. The email is sent to an email address that does not exist in a foreign domain. I can see in the postfix log that the email was sent and bounced with the error code 550. The problem is that sendmail should throw an exception but it does not. And the returned dictionary is empty as if the email was accepted. d = smtpserver.sendmail(sender, recipient, m.as_string()) I guess that the error code returned by the destination mail server is not is not forwarded to the client by my mail server. Regards, Clodoaldo Pinto Neto From bj_666 at gmx.net Sun Mar 2 16:48:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Mar 2008 21:48:52 GMT Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: <630lm2F25g4d2U1@mid.uni-berlin.de> On Sun, 02 Mar 2008 21:58:31 +0100, Christoph Zwerschke wrote: > Marc 'BlackJack' Rintsch schrieb: >> On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: >> >>> Apart from doing something like >>> a=[0,0,0] >>> b=[0,0,0] >>> c=[0,0,0] >>> d=[a,b,c] >>> >>> is there a better way of creating d?? >> >> a = [[0] * 3 for dummy in xrange(3)] > > Why not simply [[0]*3]*3 ? Because: In [77]: a = [[0] * 3] * 3 In [78]: a Out[78]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] In [79]: a[0][0] = 42 In [80]: a Out[80]: [[42, 0, 0], [42, 0, 0], [42, 0, 0]] Ciao, Marc 'BlackJack' Rintsch From andrei.avk at gmail.com Thu Mar 13 22:55:27 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Thu, 13 Mar 2008 19:55:27 -0700 (PDT) Subject: escape string to store in a database? References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> Message-ID: <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> On Mar 12, 8:32?pm, Carsten Haese wrote: > On Wed, 2008-03-12 at 18:18 -0700, andrei.... at gmail.com wrote: > > These pieces of text may have single and double quotes in > > them, I tried escaping them using re module and string module and > > either I did something wrong, or they escape either single quotes or > > double quotes, not both of these. So that when I insert that text into > > a db record, this causes an error from the database. What's the > > accepted way of dealing with this? > > The accepted way of dealing with this is to use parameter binding: > > conn = somedbmodule.connect(...) > cur = conn.cursor() > cur.execute("insert into sometable(textcolumn) values (?)", > ? ? ? ? ? ? (stringvar,) ) > > (Note that the question mark may have to be replaced with %s depending > on which database module you're using.) > > For background information on parameter binding see, for example,http://informixdb.blogspot.com/2007/07/filling-in-blanks.html. > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks for the reply, Carsten, how would this work with UPDATE command? I get this error: cmd = "UPDATE items SET content = ? WHERE id=%d" % id self.cursor.execute(cmd, content) pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. The c rrent statement uses 1, and there are 0 supplied. Sqlite site doesn't give any details on using parameter bindings in UPDATE command, I'm going to look around some more.. -ak From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 08:03:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Mar 2008 12:03:12 -0000 Subject: os.path.getsize() on Windows References: Message-ID: <13u2080sffjnnba@corp.supernews.com> On Tue, 18 Mar 2008 13:58:33 -0700, Sean DiZazzo wrote: > I'm seeing some behavior that is confusing me. I often use a simple > function to tell if a file is growing...ie being copied into a certain > location. (Can't process it until it's complete) Surely though, under Windows, while something else is writing to the file you can't open it? So instead of this: def wait_for_open(pathname): """Return file open for reading, or fail. If the file is busy, will wait forever. """ import time while isGrowing(path, 0.2): # defined elsewhere by you time.sleep(1) # wait a bit # now we HOPE we can read the file return open(path, 'r') # this can fail in many, many ways do this: def wait_for_open(pathname): """Return file open for reading, or fail. If the file is busy, will wait forever. """ import time, errno while True: try: return open(path, 'r') except IOError, e: if e.errno == errno.EBUSY: time.sleep(1) else: raise Note: I've made a guess that the error you get under Windows is errno.EBUSY. You'll need to check that for yourself. This whole approach assumes that Windows does the sensible thing of returning a unique error code when you try to open a file for reading that is already open for writing. -- Steven From pavlovevidence at gmail.com Mon Mar 31 14:31:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 31 Mar 2008 11:31:23 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: On Mar 31, 1:23 pm, xkenneth wrote: > So i generally write quite a few classes, and in most I need to > overload the == operator. > > If i have two classes, like below: > > Class A: > attribute a > attribute b > > Class B: > attribute a > attribute c > > So if I've overloaded their respective __eq__ functions, and I want to > test whether or not the individual classes attributes are equal, the > code might look something like this: > > class A: > def __eq__(self,other): > return self.a == other.a and self.b == other.b > > class B: > def __eq__(self,other): > return self.a == other.a and self.c == other.c > > Now obviously, if I test an instance of either class equal to each > other, an attribute error will be thrown, how do I handle this? I > could rewrite every __eq__ function and catch attribute errors, but > that's tedious, and seemingly unpythonic. Also, I don't want an > attribute error thrown whenever two classes are compared that don't > have the same attributes. What do you want to happen? What I'd suggest, without knowing more about your problem, is to define a method to return some kind of signature to compare instead. For instance, you could create a dict of the attributes you care about, and return that. The comparison class A(object): def comparison_signature(self): return { 'a': self.a, 'b': self.b } def __eq__(self,other): return self.comparison_signature() == other.comparison_signature() class B(object): def comparison_signature(self): return { 'a': self.a, 'c': self.c } def __eq__(self,other): return self.comparison_signature() == other.comparison_signature() This I suspect would handle your problem gracefully, assuming that objects of different types should be considered not equal and have a different set of attributes in the signature. For extra credit, you can factor the __eq__ method into a parent class and inherit the comparison in A and B. Carl Banks From aahz at pythoncraft.com Sat Mar 15 14:35:21 2008 From: aahz at pythoncraft.com (Aahz) Date: 15 Mar 2008 11:35:21 -0700 Subject: Joseph Weizenbaum References: Message-ID: In article , Jeff Schwab wrote: >Aahz wrote: >> In article , >> Tim Roberts wrote: >>> >>> I am embarrassed to say that this vaguely disrespectful exchange made me >>> laugh out loud. >> >> Serious: why do you think this is disrespectful? > >Not to speak for Tim, but I imagine it could be perceived as >disrespectful because Prof. Weizenbaum has only recently passed away. >In fact, I think the Prof would be very happy to see people having some >fun at the expense of AI, which he saw as a real threat to human freedom. Exactly. Also, humor is one traditional response to negative emotions; see all the various Gygax tributes that use humor. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From maxime.p at gmail.com Sat Mar 15 16:18:28 2008 From: maxime.p at gmail.com (Ulysse) Date: Sat, 15 Mar 2008 13:18:28 -0700 (PDT) Subject: Code to send RSS news by Sendmail Message-ID: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> Hello, I'm searching a code which allow you to parse each item in the RSS feed, get the news page of each item, convert it to text and send it by mail. Do you know if it exists ? Thanks From http Sun Mar 9 03:51:26 2008 From: http (Paul Rubin) Date: 08 Mar 2008 23:51:26 -0800 Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> <13t6p1o23so7oc2@corp.supernews.com> <8e1c4457-6313-4395-8483-22271d079c1d@2g2000hsn.googlegroups.com> Message-ID: <7x1w6kl4ht.fsf@ruckus.brouhaha.com> Chick writes: > So I guess it is not possible in pure Python to lock the memory from > being swaped? Even if you can lock the memory, python strings are immutable and can be copied around by the runtime system at any time. You're better off using the C API to encapsulate the password. If this is a high security application, consider using a hardware token of some kind instead. From kay.schluehr at gmx.net Thu Mar 20 08:40:45 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 20 Mar 2008 05:40:45 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <6f7ab390-2d37-4bcc-b88d-b82cb0ff05f9@m34g2000hsc.googlegroups.com> > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: > > Each module to be removed needs to have a justification as to why it > should no longer be distributed with Python. >From time to time someone makes a serious claim about ineptness of using significant whitespace on Windows servers because "My customer doesn't let me install a reasonable editor. So I'm forced me to use MS Notepad!". These poor guys can still use IDLE once they have a running Python installation. I'm definitely with you and batteries included. Note also that Tk which seemed to be comatose for a long time seems to recover and doesn't look that bad anyome: http://www.tcl.tk/software/tcltk/8.5.html http://wiki.tcl.tk/13636 From rpdooling at gmail.com Mon Mar 31 19:04:13 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Mon, 31 Mar 2008 16:04:13 -0700 (PDT) Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> Message-ID: <7b94bd75-f3ef-4e5c-9939-c431947e1ae1@l42g2000hsc.googlegroups.com> On Mar 31, 2:39 pm, hexusne... at gmail.com wrote: > How do I receive input from the command line in Python? As long as we are all guessing, do you perhaps mean raw_input? my_name = raw_input("What is your name? ") What is your name? Rick >>> my_name 'Rick' From egbert.bouwman at hccnet.nl Sat Mar 8 10:20:34 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Sat, 8 Mar 2008 16:20:34 +0100 Subject: for-else In-Reply-To: References: Message-ID: <20080308152034.GA12009@hccnet.nl> The idea of the if-else is: . depending on some condition either do this or do something else, . don't do them both. If you approach a loop-else with this same idea, you get: . depending on the loop conditions either do the loop, . or do something else, but not both. However the loop-else really works more like this: . try to do the loop; . if it starts but is interrupted by a break, . then do something else as well. So they are completely different beasts, and if you try to use or explain the one according to the rules of the other one, you put a serious strain on your synapses. The explanation that the if-else and the loop-else follow the same pattern, runs more or less like this: . all conditions to run the loop to its completion were met, . which means that the loop-condition is not met (any more), . which means that we must do something else. For me that is orwellian logic: success is failure. The loop-else mechanism is not an easy one: earlier in this thread Carl Banks turned it into an either/or construct by omitting the crucial break; Jeffrey Barish initially found the loop-else surprising; Sion Arrowsmith found it comprehensible only after some hard thinking (as in the last paragraph). The culprit is of course the keyword, else. The idea of an easy follow-up after a loop is a good one. But we need other keywords, I think at least three of them: . skipped - the loop did not run at all . broken - the loop was interrupted (by a break) . exhausted - the loop ran to completion. The last two as suggested by Laurence Tratt in his Convergence. e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From bockman at virgilio.it Tue Mar 25 05:38:47 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 25 Mar 2008 09:38:47 GMT Subject: Python 2.2.1 and select() References: Message-ID: <47e8c826$0$7736$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 17:58:42 -0400, Derek Martin ha scritto: > Hi kids! > > I've got some code that uses select.select() to capture all the output > of a subprocess (both stdout and stderr, see below). This code works as > expected on a variety of Fedora systems running Python > 2.4.0, but on a > Debian Sarge system running Python 2.2.1 it's a no-go. I'm thinking > this is a bug in that particular version of Python, but I'd like to have > confirmation if anyone can provide it. > > The behavior I see is this: the call to select() returns: [ corresponding to sub-proc's STDOUT>] [] [] > > If and only if the total amount of output is greater than the specified > buffer size, then reading on this file hangs indefinitely. For what it's > worth, the program whose output I need to capture with this generates > about 17k of output to STDERR, and about 1k of output to STDOUT, at > essentially random intervals. But I also ran it with a test shell > script that generates roughly the same amount of output to each file > object, alternating between STDOUT and STDERR, with the same results. > > Yes, I'm aware that this version of Python is quite old, but I don't > have a great deal of control over that (though if this is indeed a > python bug, as opposed to a problem with my implementation, it might > provide some leverage to get it upgraded)... Thanks in advance for any > help you can provide. The code in question (quite short) follows: > > def capture(cmd): > buffsize = 8192 > inlist = [] > inbuf = "" > errbuf = "" > > io = popen2.Popen3(cmd, True, buffsize) inlist.append(io.fromchild) > inlist.append(io.childerr) > while True: > ins, outs, excepts = select.select(inlist, [], []) for i in ins: > x = i.read() > if not x: > inlist.remove(i) > else: > if i == io.fromchild: > inbuf += x > if i == io.childerr: > errbuf += x > if not inlist: > break > if io.wait(): > raise FailedExitStatus, errbuf > return (inbuf, errbuf) > > If anyone would like, I could also provide a shell script and a main > program one could use to test this function... >From yor description, it would seem that two events occurs: - there are actual data to read, but in amount less than bufsize. - the subsequent read waits (for wathever reason) until a full buffer can be read, and therefore lock your program. Try specifying bufsize=1 or doing read(1). If my guess is correct, you should not see the problem. I'm not sure that either is a good solution for you, since both have performance issues. Anyway, I doubt that the python library does more than wrapping the system call, so if there is a bug it is probably in the software layers under python. Ciao ---- FB From 11456990 at qq.com Sun Mar 30 14:54:36 2008 From: 11456990 at qq.com (Aster Jian) Date: Mon, 31 Mar 2008 02:54:36 +0800 Subject: Py-Lib 0.9.1 released References: Message-ID: <021801c89297$808b02d0$6701a8c0@tencent2a9bde> great works, i will try it. Aster Jian. ----- Original Message ----- From: "Carl Friedrich Bolz" To: Sent: Monday, March 31, 2008 2:47 AM Subject: ANN: Py-Lib 0.9.1 released > py lib 0.9.1: bugfix release > ============================= > > The py lib team has just released version 0.9.1 of the py lib - a > library aiming to support agile and test-driven python development on > various levels. > > This is mostly a bugfix release, with a couple of new features sneaked in. > Most important changes: > > * reduced the number of threads used in py.execnet > * some new functionality (authentication, export, locking) in py.path's > Subversion APIs > * stability and segfault fixes in execnet > * numerous small fixes in py.test's rsession (experimental pluggable > session) > and generative test features > * some fixes in the py.test core > * added py.misc.killproc, which allows killing processes on (some > flavours of) Windows and UNIX > > For a complete list of changes, see doc/changes-0.9.1.txt in the source > package. > > Download/Install: http://codespeak.net/py/0.9.1/download.html > Documentation/API: http://codespeak.net/py/0.9.1/index.html > > Work on the py lib has been partially funded by the European Union IST > programme and by http://merlinux.de within the PyPy project. > > best, have fun and let us know what you think! > > holger krekel, Maciej Fijalkowski, > Carl Friedrich Bolz, Guido Wesdorp > > -- > From castironpi at gmail.com Sat Mar 8 12:52:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 09:52:41 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> <13t2cget4hubma9@corp.supernews.com> Message-ID: On Mar 7, 6:16?am, Steven D'Aprano wrote: > On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote: > > you > > could say exec( open( 'modA.py' ).read() ) ==> import modA > > Yes, you could say that, but you'd be wrong. Please test your code before > making such claims in the future. Aye aye. -1 response not phrased in the form of a question. Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA import * create "effectively" same results, such as in the remaning program not checking __module__ attributes? Is there a slight modification of both sides that does cover a non- trivial volume of programs, such as maybe, exec( open( 'modA.py' ).read(), locals= dict( __module__= 'modA' ) ) - and- from modA import *, or something? I notice that from toimp import * f() exec( open( 'toimp.py' ).read() ) f() generate the same output so far. From gygulyas at gmail.com Wed Mar 19 20:17:46 2008 From: gygulyas at gmail.com (Gyula) Date: Wed, 19 Mar 2008 17:17:46 -0700 (PDT) Subject: ADO error - large data set References: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> <9qgEj.4646$6H.3740@newssvr22.news.prodigy.net> Message-ID: Thanks! I will give it a try. It seems though that I get stuck on rs.Open that makes no sense. I was wondering about pagesize or other registry settings that might cause this? Will try to track down any bad data first... gg On Mar 19, 3:27 pm, "dsavitsk" wrote: > Is it possible there is some bad data in the larger db? This is asinine, but > maybe write a small script that adds some data, then opens and closes the > db, then repeats this. If this is a size issue, then you can at least narrow > it down to where the size limit is? And, if it isn't you should be able to > figure that out, too. Otherwise, play around with the locking and cursor > options. > > -d > > "Gyula" wrote in message > > news:475c155d-fe16-472f-a4f8-363f6db339eb at d21g2000prf.googlegroups.com... > > > Hi there, > > > I have been running Python to tap into an MS Access 2003 database > > using ADO (PythonWin+COM). Everything works great creating recordsets > > etc. when I open a table with a small number of records. However, when > > I try to run the same Python code with a large table (>100,000) I get: > > > Traceback (most recent call last): > > File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 310, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\Documents and Settings\user\Desktop\PythonWS\scripts > > \readmsaccess.py", line 43, in > > rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) > > File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- > > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open > > , ActiveConnection, CursorType, LockType, Options) > > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > > 5003251, -2147467259), None) > > > The small and large table structures are identical, all I do is change > > the tblname from input1000 (1000 records) to input (>100000 records). > > I use optimistic locking and keyset cursor..nothing out of the > > ordinary? > > > Any ideas? ADO 2.8 is what I am using. > > > Thanks a lot! > > GG From castironpi at gmail.com Sat Mar 8 04:06:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 01:06:41 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: <52786746-c7b1-48c3-8bdf-664d17859771@n77g2000hse.googlegroups.com> On Mar 7, 9:43?pm, George Sakkis wrote: > On Mar 7, 11:12 am, alex.pedwyso... at gmail.com wrote: > > > I have various bits of code I want to interpret and run at runtime in > > eval ... > > Check out these two recipes: > > - Using signals:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 > > - Using threads:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752 > > the second can't interrupt code that > doesn't release the GIL and doesn't actually kill the function after > the timeout. Mine doesn't either, plus you need a C compiler. I also learned today that one of the import statements doesn't find the dll on Py <3.0. Do you have a process kill ability? That's another way to do it. From grante at visi.com Wed Mar 26 16:45:47 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 26 Mar 2008 20:45:47 -0000 Subject: Daylight savings time problem References: Message-ID: <13uldfrl46tf728@corp.supernews.com> On 2008-03-26, Salsa wrote: > I'm sorry, but could you be more specific? How exactly should I use UTC? In my experience, using local time for timestamps is always a big mistake, so I presume he meant don't use local time in the file names -- put the UTC date/time in the filenames. If that's not an option, I'd try to figure out how to convert from whatever _is_ in the filename to UTC. -- Grant Edwards grante Yow! Half a mind is a at terrible thing to waste! visi.com From wolf_tracks at invalid.com Mon Mar 31 08:41:33 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 31 Mar 2008 05:41:33 -0700 Subject: Class Image.Image? In-Reply-To: <65buk3F2fi5osU1@mid.uni-berlin.de> References: <65buk3F2fi5osU1@mid.uni-berlin.de> Message-ID: Easy enough. 5Q+5Q. Diez B. Roggisch wrote: > W. Watson wrote: > >> I put a print statement in some Python code to determine the class >> (__class__) of a variable and the result was Image.Image. Why not just >> Image; otherwise, what's it telling me? > > Because it is the class Image in the module/package Image. > > Diez -- Wayne Watson (Nevada City, CA) Web Page: From deets at nospam.web.de Mon Mar 24 09:10:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Mar 2008 14:10:39 +0100 Subject: Installing Mutagen Package On Windows In-Reply-To: References: Message-ID: <64pnipF2crjipU1@mid.uni-berlin.de> Benjamin Serrato schrieb: > Hey, I've run into another problem. I am trying to install the Mutagen > package to use as my first useful program, but can't figure out how to > install it on windows. The README says it is a simple application of-- > > Installing > ---------- > $ ./setup.py build > $ su -c "./setup.py install" > > --but I ran c:\>python c:\python25\tools\scripts\setup.py build and did > similarly for setup.py. I also added c:\python25 and > c:\python25\tools\scripts to my path, but this hasn't worked. I have > heard of 'easy_install' but don't know how to run easy_install. So, I > ask for a reference because Google did not give me a quick answer and > the python.org explanation at PEP 250 doesn't really explain what I > should do. You need to call python2.5 setup.py install and google for setuptools, python, easy_install to find out all about it you need. Diez From __peter__ at web.de Tue Mar 4 09:15:15 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Mar 2008 15:15:15 +0100 Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: Steve Holden wrote: > What I will repeat, however, is that while there is a *slight* > difference is semantics between > > s = "some string" > s1 = s > > and > > s = "some string" > s1 = copy.copy(s) > > that difference is only to ensure that s and s1 point to different > copies of the same string in the latter case, whereas in the former case > s and s1 point to the same string. No, both "point" to the same string: >>> import copy >>> s = "some string" >>> s1 = s >>> s1 is s True >>> s2 = copy.copy(s) >>> s2 is s True copy.copy() is just an expensive no-op here. Peter From jules at js3d.co.uk Sun Mar 2 14:19:09 2008 From: jules at js3d.co.uk (Jules Stevenson) Date: Sun, 2 Mar 2008 19:19:09 -0000 Subject: Escaping a triple quoted string' newbie question In-Reply-To: References: <002801c87c3b$d6cd42b0$0301a8c0@laptop><004401c87c4f$e27b6f60$0301a8c0@laptop><004801c87c50$e83fc3a0$0301a8c0@laptop> Message-ID: <00bb01c87c9a$4a4ac100$0301a8c0@laptop> > > float $pos[]=particleShape1.worldPosition; > > > > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; > > > > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; > > > > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; > > """ > > dynExpression (p, s=expRuntime, rad=1) #generate the expression > > > > Then maya errors out, however if I pass maya an 'escaped' version: > > > > expRuntime=""" > > float $pos[]=particleShape1.worldPosition;\nsetAttr > > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr > > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr > > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """ > > > > Then all is well. My question is, is there any way to convert the first > > variable example to the second? It's a lot easier to type and on the > eye. > > Except for the doble-space on the first version, \n is the line separator > on both, so I'll ignore them. > """one > two""" > is the same thing as "one\ntwo" (even on Windows). The only remaining > difference that I see is " -> \" > > def mayaquote(text): > return text.replace('"', '\\"') > Thanks, this will work great. I was just wondering if there was an automatic 'string to escaped text' type function. Otherwise I'd have to build parsing for all chars that could cause a wobbly, but these may be few, so not too much of an issue. From tjreedy at udel.edu Sat Mar 8 21:19:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2008 21:19:56 -0500 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13t6gf5on1qnhbe at corp.supernews.com... | On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote: | | > On Mar 8, 6:26 pm, Paul Rubin wrote: | >> Alasdair writes: | >> > What is the best way of finding a ceiling of a quotient of arbitrary | >> > sized integers? | >> | >> ceiling(a/b) = (a+b-1)//b | > | > I prefer: | > | > ceiling(a/b) = -(-a)//b Obvious typo: -(-a)//b == a//b This should be -(-a//b) == -((-a)//b) | Unfortunately it doesn't give the right answer. | Looks like you've confused ceiling() and floor(). | | (And the ease that these mistakes can happen is why such fundamental | functions should be in the standard library, no matter how easy they are | to implement.) I'll let Paul say whether is was a typo, due to answering too quickly, or a logic error, but I suspect the former. *Any* expression can be mistyped. tjr From fakeaddress at nowhere.org Sun Mar 23 02:02:52 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Mar 2008 23:02:52 -0700 Subject: finding items that occur more than once in a list In-Reply-To: <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Bryan Olson wrote: >> We mean that the party supplying the keys deliberately chose >> them to make the hash table inefficient. In this thread the goal >> is efficiency; a party working toward an opposing goal is an >> adversary. > > There are situations where this can happen I guess Cormen-Leiserson-Rivest /Introduction to Algorithms/ discusses it in section 12.3.3 (first edition). They suggest a family of hash functions, where an individual hash is chosen at random when creating the table. That still doesn't beat adversaries who can get on-line timing information and figure out when they induce bad cases. More generally, security researchers have started to look at "algorithmic complexity denial of service attacks". http://www.cs.rice.edu/~scrosby/hash/ >> If you find real-world data sets that tend to induce bad-case >> behavior in Python's hash, please do tell. It would be reason >> enough to adjust the hash function. The hashes in popular >> software such as Python are already quite well vetted. > > As Python allows you to make your own hash functions for your own > classes, another danger is that you are dealing with objects with a > bad hash function. I've actually tried it (as I am *not* a pro!) and > FWIW here are the results. > > -------- badhash.py ---------- > > class BadHash(object): > def __hash__(self): > return 1 # that's a bad hash function! The sorting algorithm can have the same problem. With user-defined methods, there's no telling how long __cmp__ will actually take. -- --Bryan From deets at nospam.web.de Wed Mar 5 17:19:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Mar 2008 23:19:30 +0100 Subject: Dual look-up on keys? In-Reply-To: References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> Message-ID: <638kjmF26gr4fU1@mid.uni-berlin.de> castironpi at gmail.com schrieb: > On Mar 5, 3:38 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: >>> On Mar 5, 1:13 pm, "Diez B. Roggisch" wrote: >>>> castiro... at gmail.com schrieb: >>>>> I want to hash values to keys. How do the alternatives compare? >>>> http://catb.org/~esr/faqs/smart-questions.html >>> ... without extending the whole way to a full relational database? >> You didn't bother following the link and reading the advice, did you? If >> you did, you haven't done a good job of following that advice. > > Well, obviously there's someone who's interested in computers and > programming that has a question. Communication is not his forte, but > effort, willingness, devotion, and dedication are. What should he do, Effort, willingness & devotion? Certainly - but only to provoke, mislead and twaddle. You have recieved more than enough earnest efforts to be helped, and yet proven again and again that you aren't worth these very efforts. Luckily, this group is nice enough to not let your attitude poison it. *plonk* Diez From PurpleServerMonkey at gmail.com Mon Mar 31 07:32:15 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Mon, 31 Mar 2008 04:32:15 -0700 (PDT) Subject: distutils as an application installer? Message-ID: <8cfcad33-a6c2-4e30-b585-6ad57555b316@c19g2000prf.googlegroups.com> Was hoping someone could take a quick look at my distutils problem and give it a quick sanity check. Basically I have a server application (for Linux) that I want to install to /usr/local/, this location would have subdirectories for the daemon scripts, log files, plugins etc. After reading a bunch of distutils documentation it appears that the only good way out of this is to have my packages install to the system wide site-packages directory. Then using the data_files command in setup.py have it copy across an initial skeleton copy of the server directory and finally install the startup scripts. Does this sound correct, any other suggestions? The distutils documentation doesn't cover this scenario and I've spent days searching for information so any assistance is greatly appreciated. From roy at panix.com Sun Mar 23 22:36:35 2008 From: roy at panix.com (Roy Smith) Date: Sun, 23 Mar 2008 22:36:35 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 23 Mar 2008 13:51:34 -0400, Roy Smith wrote: > > > On the other hand, when I do: > > > > def torture(): > > woman.putInChair() > > cushion.poke() > > rack.turn() > > > > I've also done two things. First, I've created a function object (i.e. > > a lambda body), and I've also bound the name torture to that function > > object, in much the same way I did with the list. But, it's different. > > The function object KNOWS that it's name is torture. > > No it does not. Function objects don't know their name. All they know is > that they have a label attached to them that is useful to use as a name > in some contexts, e.g. when printing tracebacks. It's just a label, > nothing more. I think we're arguing the same thing. When you write def foo(): whatever you create an object which contains the string "foo", retrievable through its __name__ attribute. That's what I meant by "it knows its name" >> What Python give us with lambdas is some half-way thing. It's not a >> full function, so it's something that people use rarely, > > Which people? > > > which means most people (like me) can't remember the exact syntax. > > Speak for yourself, not for "most people". Well, OK. When I said, "most people", I really meant "I know about me, and I'm guessing about other people". I still think it's a fair statement that if you look any large collection of Python code, you will find many more uses of def than of lambda. > > Even when I know > > it's the right thing to be using in a situation, I tend not to use it > > simply because the path of least resistance is to write a one-off > > function vs. looking up the exact syntax for a lambda in the manual. > > lambda arguments : expression > > Why is that harder to remember than this? > > def name ( arguments ) : > block because I remember things I use often, better than I remember things I use infrequently. From andrei.avk at gmail.com Sat Mar 15 00:18:50 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Fri, 14 Mar 2008 21:18:50 -0700 (PDT) Subject: escape string to store in a database? References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> <13tk779c9tmjob8@corp.supernews.com> Message-ID: On Mar 14, 1:36?am, Dennis Lee Bieber wrote: > On Thu, 13 Mar 2008 19:55:27 -0700 (PDT), andrei.... at gmail.com declaimed > the following in comp.lang.python: > > > > > Thanks for the reply, Carsten, how would this work with UPDATE > > command? I get this error: > > > ? ? ? ? cmd = "UPDATE items SET content = ? WHERE id=%d" % id > > ? ? ? ? ? ? ? ? cmd = "update items set content = ? where id = ?" > > > ? ? self.cursor.execute(cmd, content) > > ? ? ? ? ? ? ? ? self.cursor.execute(cmd, (content, id)) > > would be the preferred method... Thanks very much - this works perfectly -ak > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From needin4mation at gmail.com Sat Mar 22 12:40:02 2008 From: needin4mation at gmail.com (jmDesktop) Date: Sat, 22 Mar 2008 09:40:02 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? Message-ID: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> For students 9th - 12th grade, with at least Algebra I. Do you think Python is a good first programming language for someone with zero programming experience? Using Linux and Python for first exposure to programming languages and principles. Thank you. From gagsl-py2 at yahoo.com.ar Thu Mar 6 14:46:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 17:46:04 -0200 Subject: Class context execution problems References: <1e5bcefd0803060504n5aa4970bh90092b57b0a106f0@mail.gmail.com> Message-ID: En Thu, 06 Mar 2008 11:04:26 -0200, Marcelo de Moraes Serpa escribi?: > I'm using a class in a conext other than the subpackage in which it is > located and I'm getting template lookup errors. > > This class expects to find a .pt file in a directory relative to its > package. However, this class is normally used by other classes in the > same > namespace. > > class ObjectWidget: > template = "templates/objectwidget.pt" > > However, I needed to import this class (ObjectWidget) from a class > outside > its namespace(package). Now, I think the class is running in the context > of > the file that is using it and so, the > the class not finding the .pt file (I think becouse the class file is > being > contextualized to the currently running one which is outside the browser > subpackage) No, it's not. The globals() (i.e., the "context") are of the imported module itself, not of the caller. The error probably lies on how that template attribute is converted into a full path; post that code. As an example, this is a rather safe way, even if the program uses os.chdir(): basepath = os.path.abspath(os.path.dirname(__file__)) class ObjectWidget: template = "templates/objectwidget.pt" def open(self): fn = os.path.join(basepath, template) print fn -- Gabriel Genellina From info at egenix.com Mon Mar 31 13:09:21 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 31 Mar 2008 19:09:21 +0200 Subject: ANN: eGenix MoinMoin action plugins for renaming and search&replace Message-ID: <47F11AC1.2080203@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com Action Plugins for MoinMoin This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/MoinMoin-Action-Plugins-1.0.html ________________________________________________________________________ eGenix and MoinMoin eGenix uses the MoinMoin wiki implementation internally as knowledge base and to document product development. Every now and then we need to do major search&replace on our wiki - e.g. due to a change in product name or to update an external URL. Instead of applying the changes manually, we created two new actions for MoinMoin to simplify this task. Both have proven to be very useful in day-to-day operation and therefore we are releasing them to the community under the GPLv2. "Rename Multiple Pages" Action, Version 1.0 -------------------------------------------- A plugin to quickly rename a whole set of pages in a MoinMoin wiki. "Search And Replace Multiple Pages" Action, Version 1.0 -------------------------------------------- This plugin can be used to quickly rename a whole set of pages in a MoinMoin wiki. eGenix MoinMoin Library ----------------------- Over time, we expect to release more useful MoinMoin plugins or patches. We'll be publishing them in our new MoinMoin Library. http://www.egenix.com/library/moinmoin/ ________________________________________________________________________ More Information Please see http://www.egenix.com/library/moinmoin/ for more information and downloads. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 31 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From craigm3604 at gmail.com Mon Mar 24 12:27:36 2008 From: craigm3604 at gmail.com (Craig) Date: Mon, 24 Mar 2008 09:27:36 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> Message-ID: <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> On Mar 23, 7:59 pm, Dennis Lee Bieber wrote: > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > > > This dll was designed to be used from either C or Visual Basic 6. > > > I have the declare statements for VB6, if that helps. > > Probably not that much -- I'd bet it's full of variant records > > > > > Based on the results I have so far (and I have tried MANY permutations > > like trying to use the LPSTR for SecKey and PriKey which are returned > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > instead of pointers. > > > For this, I try: > > LPSTR = c_char_p > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > LPSTR] > > SrchKey = > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > \x00", 41) > > SecKey = create_string_buffer(41) > > SecKey.raw = "1234567890123456789012345678901234567890" > > PriKey = > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > 41) > > TypeDef = create_string_buffer(128) > > TypeDef.raw = "X".center(128, "X") > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > and I get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 158, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > WindowsError: exception: access violation reading 0x3433322D > > > I notice that SecKey.raw starts with "1234" and the exception address > > is 0x3433322D, which is "432-". > > 0x2D is 4 less than the expected 0x31... > > > > > And, changing to: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > LPSTR] > > PriKey = create_string_buffer(41) > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > I then get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 159, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > WindowsError: exception: access violation reading 0x4443423D > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > is 0x4443423D, which is "DBC=". > > ... and 0x3D is 4 less than the expected 0x41 > > Which leads me to suspect that BSTR are a structure, not a plain > string, in which the address given is supposed to be prefaced with a > length value. IOWs, something like: > > |----|--------------------------------------| > ^ ^ C-string data > | |Address to be passed > |(address - 4) to get to a length count field > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > (the URL is from HTTP through to the end, including .aspx) > > Creating such may not be difficult -- but passing it to the DLL > could be. I don't know if ctypes allows pointer arithmetic. > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > length prefix. > > The only mention of BSTR in the win32 extensions is in text that > implies that the win32 extension library takes care of converting > from/to BSTR and Python strings transparently -- but that won't work for > your third-party library I suspect. > > Might have to beg the author(s) of ctypes to add a BSTR type to the > list of those supported... as I can find no means of tweaking the > address computed by byref() to point somewhere into a structure rather > than the beginning of the structure. > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > >>> pk > 1373844 > >>> id(pk) > 18941724 > >>> ctypes.string_at(pk) > '1234567890' > >>> ctypes.string_at(pk-4, 20) > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > > Okay, the return value from SysAlloc... IS the integer representing > the address of a BSTR structure (IE, the address four bytes in from the > real memory start)... Note how backing up 4 bytes reveals the BSTR > length field > > What happens if you just pass that item as-is, no byref(), no > conversion to ctypes pointer types... > > PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > SecKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > res = VmxGet( byref(hwmcb), > byref(SecIndex), > byref(Option), > byref(c_void_p(SrchKey)), > SecKey, > PriKey, > TypeDef ) > > >>> PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > >>> ctypes.string_at(PriKey, 41) > > "1234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'">>> ctypes.string_at(PriKey-4, 41+4) > > ")\x00\x00\x001234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'" > > >>> ord(")") > 41 > > You'll need to use the .string_at() or .wstring_at() functions to > extract any data changed by the call. Should not be a Python > immutability problem as all "you" allocated in Python is the integer > holding the address. You may need to call a Sys... function to free the > memory that had been allocated -- Python doesn't know about it. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ The VB6 Declare is: Declare Function VmxGet Lib "vbis5032.DLL" (DatasetHandle&, SecIndexField%, Options%, SelectorKey$, RSecondaryKey$, RPrimaryKey$, RRecordVariable As Any) As Integer The only variant is the RRecordVariable, which is actually meant to be a Type structure. Anyway, I thought maybe there was a clue in here that I am missing. Back to Python. I ran with the following: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) And, now I get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 156, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), SecKey, PriKey, TypeDef ) ctypes.ArgumentError: argument 5: : wrong type So, now the problem is with: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, LPSTR] I am not sure what to put for arguments 5 and 6 now. I realized the need to release the BSTRs myself, and already included: windll.oleaut32.SysFreeString(SrchKey) windll.oleaut32.SysFreeString(SecKey) windll.oleaut32.SysFreeString(PriKey) at the end of the program. I have no problem using .string_at() to extract the returned values - once the .argtypes let the call execute. In case this helps, here is an excerpt from a C program that was provided with the dll: typedef struct tagMYREC { char name[51]; // 1 xref generated name key char lastname[31]; // 2 last name char firstname[21]; // 3 first name char address[41]; // 4 address char city[31]; // 5 xref city key char state[3]; // 6 xref state char zip[11]; // 7 xref zip code char phone[21]; // 8 xref phone number BSTR notes; // 9 notes } MYREC; typedef MYREC FAR * LPMYREC; short rc; // return code (from VB/ISAM function calls) static HANDLE nDatasetNumber; static short cur_index; static short GetOpt; static BSTR Dummy; static BSTR Throwaway; static BSTR PrimaryKey; static MYREC myrec; rc = VmxGet(&nDatasetNumber, // int DatasetNumber // VIS_BUSY ? &cur_index, // int SelectedIndex &GetOpt, // int OptionParameter &Dummy, // Don't need a Selector param with these options &Throwaway, // Don't need returned index entry in this case &PrimaryKey, // LPBSTR lpPriKey (void *) &myrec); // LPVOID lpRecordStructure For someone who knows C and Python, this may provide a clue to the BSTR passing/return problem. From sjmachin at lexicon.net Fri Mar 21 16:34:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 13:34:27 -0700 (PDT) Subject: beginners question about return value of re.split References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> <47e3d9ff$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <84dedb7d-d726-4acf-84fc-2a8f28277d0d@s12g2000prg.googlegroups.com> On Mar 22, 2:53 am, klaus wrote: > On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote: > > <..........> > > Ok thank you ! > > I think I got a bit lost in all the possibilities python has to offer. IMHO you got more than a bit lost. You seem to have stumbled on a possibly unintended side effect of re.split. What is your underlying goal? If you want merely to split on '-', use datum.split('-'). If you want to verify the split results as matching patterns (4 digits, 2 digits, 2 digits), use something like this: | >>> import re | >>> datum = '2008-03-14' | >>> pattern = r'^(\d\d\d\d)-(\d\d)-(\d\d)\Z' You may notice two differences between my pattern and yours ... | >>> mobj = re.match(pattern, datum) | >>> mobj.groups() | ('2008', '03', '14') But what are you going to do with the result? If the resemblance between '2008-03-14' and a date is not accidental, you may wish to consider going straight from a string to a datetime or date object, e.g. | >>> import datetime | >>> dt = datetime.datetime.strptime(datum, '%Y-%m-%d') | >>> dt | datetime.datetime(2008, 3, 14, 0, 0) | >>> d = datetime.datetime.date(dt) | >>> d | datetime.date(2008, 3, 14) HTH, John From MartinRinehart at gmail.com Thu Mar 27 14:23:56 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 11:23:56 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: <71b3fd4e-464a-4a71-b2e3-62fe8055a56d@s12g2000prg.googlegroups.com> Guilherme Polo wrote: > there is a > gui designer tool for tkinter called GUI Designer (what a bad name), > which used to be called SpecTcl, where you can design the menus and it > then converts to python code. I tried it. after about 10 minutes I was as far as "help not found." Is anyone out there using this tool? Worth the learning curve? From bbxx789_05ss at yahoo.com Sat Mar 22 18:42:05 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 22 Mar 2008 15:42:05 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> Message-ID: <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> On Mar 22, 3:34?pm, bsoist wrote: > On Mar 22, 12:40 pm, jmDesktop wrote: > > > For students 9th - 12th grade, with at least Algebra I. ?Do you think > > Python is a good first programming language for someone with zero > > programming experience? ?Using Linux and Python for first exposure to > > programming languages and principles. > > > Thank you. > > Absolutely. I love using Python in "the real world" but it is > fantastic for beginning programmers. > > Python enforces good habits and presents many opportunities to discuss > programming from an academic perspective. Why does Python not have a > switch or until statement? Why are very common objects (stack, queue, > linked list) not builtin? etc. > Beginning programmers in grades 9-12 are not going to understand issues like that, and it would be a mistake to try and introduce them. Beginning programmers should be concentrating their efforts on learning the syntax of a language and basic constructs like for-loops and if statements. They will begin by writing simple "hello world" style programs, and as their basic skills improve, the programs will get a little more complex and require some more thought and some math to solve the problems presented to them. String formatting should probably be introduced to help with formatting the output. That is about as far as things are going to go. Terms like "Touring machines" and "lambda-calculus" are not going to be mentioned anywhere in the course of study. From ggpolo at gmail.com Tue Mar 11 13:39:40 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 11 Mar 2008 14:39:40 -0300 Subject: Exctract GIF comment from image In-Reply-To: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> References: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Message-ID: 2008/3/11, wingi at gmx.com : > Hi, > > simple question: The PIL does not support reading the optional > description in GIF Images. > > http://www.pythonware.com/library/pil/handbook/format-gif.htm > > After some reasearch I could not find a python solution for this, any > suggestions? > > Thanx, Wingi. > > -- > http://mail.python.org/mailman/listinfo/python-list > I did a quick thing here, try it and check if it solves the problem for you: import os import sys import struct def extract_comments(giffile): fobj = open(giffile, 'rb') giftype = fobj.read(6) pf = struct.unpack(' ..." % args[0] sys.exit(0) for gif in args[1:]: extract_comments(gif) if __name__ == "__main__": main(sys.argv) -- -- Guilherme H. Polo Goncalves From gagsl-py2 at yahoo.com.ar Mon Mar 31 22:17:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 23:17:47 -0300 Subject: Looking for indent advice howto in emacs python-mode References: <440c7af6-deaf-4180-afa8-91d9a3f359f3@e10g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 16:36:13 -0300, bruno.desthuilliers at gmail.com escribi?: > On 31 mar, 18:32, "Steven W. Orr" wrote: >> Here's what I want to do: >> >> if ( ( v == 1 ) >> or ( v == 2 ) >> or ( v == 3 ) ): >> pass > > Why the parens ? > > if a == 1 \ > or b == 2 \ > or c == 3: > pass I know it's mostly a matter of style, but I prefer to add parenthesis and avoid line continuation characters. Sometimes I use parenthesis for strings too, when multiline strings are not a good choice: txt = ("En un lugar de " "la Mancha, de cuyo " "nombre no quiero " "acordarme, no ha " "mucho tiempo...") (A multiline string would keep the inner \n but in this case I don't want that) -- Gabriel Genellina From duvo at tiscali.it Sun Mar 9 16:20:16 2008 From: duvo at tiscali.it (duvo at tiscali.it) Date: Sun, 9 Mar 2008 13:20:16 -0700 (PDT) Subject: del class with recursive list References: Message-ID: Thanks! I just need to remember to del the variables after "for in". From michael.wieher at gmail.com Thu Mar 13 10:49:49 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 13 Mar 2008 09:49:49 -0500 Subject: (off-topic) JS/DHTML export to XLS format? Message-ID: Anyone use/know of anything looks like a spreadsheet, lives in a web-browser and can export to XLS format? -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Mar 5 14:13:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Mar 2008 20:13:12 +0100 Subject: Dual look-up on keys? In-Reply-To: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> Message-ID: <6389mcF25af40U1@mid.uni-berlin.de> castironpi at gmail.com schrieb: > I want to hash values to keys. How do the alternatives compare? http://catb.org/~esr/faqs/smart-questions.html From mensanator at aol.com Mon Mar 3 15:40:16 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 12:40:16 -0800 (PST) Subject: sympy: what's wrong with this picture? Message-ID: Notice anything funny about the "random" choices? import sympy import time import random f = [i for i in sympy.primerange(1000,10000)] for i in xrange(10): f1 = random.choice(f) print f1, f2 = random.choice(f) print f2, C = f1*f2 ff = None ff = sympy.factorint(C) print ff ## 7307 7243 [(7243, 1), (7307, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] As in, "they're NOT random". The random number generator is broken by the sympy.factorint() function. Random.choice() works ok if the factorint() function commented out. ## 6089 1811 None ## 6449 1759 None ## 9923 4639 None ## 4013 4889 None ## 4349 2029 None ## 6703 8677 None ## 1879 1867 None ## 5153 5279 None ## 2011 4937 None ## 7253 5507 None This makes sympy worse than worthless, as it fucks up other modules. From duncan.booth at invalid.invalid Wed Mar 19 06:29:10 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 10:29:10 GMT Subject: Is there a way to get __thismodule__? References: Message-ID: benhoyt wrote: > But adding each message class manually to the > dict at the end feels like repeating myself, and is error-prone. It'd > be nice if I could just create the dict automatically, something like > so: > > nmap = {} > for name in dir(__thismodule__): > attr = getattr(__thismodule__, name) > if isinstance(attr, Message): > nmap[attr.number] = attr > > Or something similar. Any ideas? > > (A friend suggested class decorators, which is a good idea, except > that they're not here until Python 2.6 or Python 3000.) > Why not just use your base class? class Message(object): @staticmethod def getmap(): return dict((cls.number, cls) for cls in Message.__subclasses__()) class SetupMessage(Message): number = 1 class ResetMessage(Message): number = 2 class OtherMessage(Message): number = 255 nmap = Message.getmap() From dickinsm at gmail.com Tue Mar 11 16:16:58 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 13:16:58 -0700 (PDT) Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> <46f8d1bf-8821-4083-b7d7-d4ed53f8862a@q78g2000hsh.googlegroups.com> <13tdcma35fabb6a@corp.supernews.com> Message-ID: On Mar 11, 12:26?pm, Grant Edwards wrote: > Before I submit a bug, I'll give it a try to find out if it > does support explicit specification of proxys or not. Sounds good. If it does, then I think the whole paragraph (from "The urlopeen() function does not support explicit proxy ..." to "...subclass such as FancyURLopener.") should just be removed. Looking at the source, there are some slight oddities: a plain urlopen() caches the URLopener instance it creates (in a module-level global) and uses this cached instance in future calls to urlopen or urlretrieve. If proxies are specified then it doesn't do the caching. I don't *think* this really affects usage, except that there are presumably some inefficiencies involved in multiple uses of urlopen with explicitly specified proxies, and those inefficiencies can be overcome by using URLopener or FancyURLopener directly instead. And it doesn't make a lot of sense that urlopen accepts proxies, but urlretrieve does not. But that's a different issue... Mark From hniksic at xemacs.org Sat Mar 29 04:14:44 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 29 Mar 2008 09:14:44 +0100 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> Message-ID: <87d4pe9caz.fsf@mulj.homelinux.net> "Diez B. Roggisch" writes: >> systems. (In theory, file input/output should also be available as >> asynchronous code, but async IO is low-level and not available in >> Python.) While threads shouldn't be considered a replacement for > > I suggest you tell that the twisted-guys. And the ones from the > built-in asyncore-module. Note that I said "*file* input/output". Twisted and asyncore are about asynchronous socket programming that polls over nonblocking file descriptors such as found in socket programming, not about wrapping aio(3) and the equivalent Windows APIs. From rockxuan at gmail.com Tue Mar 18 03:40:25 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:40:25 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <71ba8a58-4a59-422d-b058-6b72de38af99@s12g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From steven.klass at gmail.com Sun Mar 23 16:48:52 2008 From: steven.klass at gmail.com (rh0dium) Date: Sun, 23 Mar 2008 13:48:52 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> Message-ID: On Mar 23, 12:26?am, Paul McGuire wrote: > There are a couple of bugs in our program so far. > > First of all, our grammar isn't parsing the METAL2 entry at all. ?We > should change this line: > > ? ? md = mainDict.parseString(test1) > > to > > ? ? md = (mainDict+stringEnd).parseString(test1) > > The parser is reading as far as it can, but then stopping once > successful parsing is no longer possible. ?Since there is at least one > valid entry matching the OneOrMore expression, then parseString raises > no errors. ?By adding "+stringEnd" to our expression to be parsed, we > are saying "once parsing is finished, we should be at the end of the > input string". ?By making this change, we now get this parse > exception: > > pyparsing.ParseException: Expected stringEnd (at char 1948), (line:54, > col:1) > > So what is the matter with the METAL2 entries? ?After using brute > force "divide and conquer" (I deleted half of the entries and got a > successful parse, then restored half of the entries I removed, until I > added back the entry that caused the parse to fail), I found these > lines in the input: > > ? ? fatTblThreshold ? ? ? ? ? ? ? ? = (0,0.39,10.005) > ? ? fatTblParallelLength ? ? ? ? ? ?= (0,1,0) > > Both of these violate the atflist definition, because they contain > integers, not just floatnums. ?So we need to expand the definition of > aftlist: > > ? ? floatnum = Combine(Word(nums) + "." + Word(nums) + > ? ? ? ? Optional('e'+oneOf("+ -")+Word(nums))) > ? ? floatnum.setParseAction(lambda t:float(t[0])) > ? ? integer = Word(nums).setParseAction(lambda t:int(t[0])) > ? ? atflist = Suppress("(") + delimitedList(floatnum|integer) + \ > ? ? ? ? ? ? ? ? Suppress(")") > > Then we need to tackle the issue of adding nesting for those entries > that have sub-keys. ?This is actually kind of tricky for your data > example, because nesting within Dict expects input data to be nested. > That is, nesting Dict's is normally done with data that is input like: > > main > ? Technology > ? Layer > ? ? PRBOUNDARY > ? ? METAL2 > ? Tile > ? ? unit > > But your data is structured slightly differently: > > main > ? Technology > ? Layer PRBOUNDARY > ? Layer METAL2 > ? Tile unit > > Because Layer is repeated, the second entry creates a new node named > "Layer" at the second level, and the first "Layer" entry is lost. ?To > fix this, we need to combine Layer and the layer id into a composite- > type of key. ?I did this by using Group, and adding the Optional alias > (which I see now is a poor name, "layerId" would be better) as a > second element of the key: > > ? ? mainDict = dictOf( > ? ? ? ? Group(Word(alphas)+Optional(quotedString)), > ? ? ? ? Suppress("{") + attrDict + Suppress("}") > ? ? ? ? ) > > But now if we parse the input with this mainDict, we see that the keys > are no longer nice simple strings, but they are 1- or 2-element > ParseResults objects. ?Here is what I get from the command "print > md.keys()": > > [(['Technology'], {}), (['Tile', 'unit'], {}), (['Layer', > 'PRBOUNDARY'], {}), (['Layer', 'METAL2'], {})] > > So to finally clear this up, we need one more parse action, attached > to the mainDict expression, that rearranges the subdicts using the > elements in the keys. ?The parse action looks like this, and it will > process the overall parse results for the entire data structure: > > ? ? def rearrangeSubDicts(toks): > ? ? ? ? # iterate over all key-value pairs in the dict > ? ? ? ? for key,value in toks.items(): > ? ? ? ? ? ? # key is of the form ['name'] or ['name', 'name2'] > ? ? ? ? ? ? # and the value is the attrDict > > ? ? ? ? ? ? # if key has just one element, use it to define > ? ? ? ? ? ? # a simple string key > ? ? ? ? ? ? if len(key)==1: > ? ? ? ? ? ? ? ? toks[key[0]] = value > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? # if the key has two elements, create a > ? ? ? ? ? ? ? ? # subnode with the first element > ? ? ? ? ? ? ? ? if key[0] not in toks: > ? ? ? ? ? ? ? ? ? ? toks[key[0]] = ParseResults([]) > > ? ? ? ? ? ? ? ? # add an entry for the second key element > ? ? ? ? ? ? ? ? toks[key[0]][key[1]] = value > > ? ? ? ? ? ? # now delete the original key that is the form > ? ? ? ? ? ? # ['name'] or ['name', 'name2'] > ? ? ? ? ? ? del toks[key] > > It looks a bit messy, but the point is to modify the tokens in place, > by rearranging the attrdicts to nodes with simple string keys, instead > of keys nested in structures. > > Lastly, we attach the parse action in the usual way: > > ? ? mainDict.setParseAction(rearrangeSubDicts) > > Now you can access the fields of the different layers as: > > ? ? print md.Layer.METAL2.lineStyle > > I guess this all looks pretty convoluted. ?You might be better off > just doing your own Group'ing, and then navigating the nested lists to > build your own dict or other data structure. > > -- Paul Hi Paul, Before I continue this I must thank you for your help. You really did do an outstanding job on this code and it is really straight forward to use and learn from. This was a fun weekend task and I really wanted to use pyparsing to do it. Because this is one of several type of files I want to parse. I (as I'm sure you would agree) think the rearrangeSubDicts is a bit of a hack but never the less absolutely required and due to the limitations of the data I am parsing. Once again thanks for your great help. Now the problem.. I attempted to use this code on another testcase. This testcase had tabs in it. I think 1.4.11 is missing the expandtabs attribute. I ran my code (which had tabs) and I got this.. AttributeError: 'builtin_function_or_method' object has no attribute 'expandtabs' Ugh oh. Is this a pyparsing problem or am I just an idiot.. Thanks again! From hgk at ieee.org Wed Mar 19 04:48:59 2008 From: hgk at ieee.org (=?ISO-8859-1?Q?Hans_Georg_Krauth=E4user?=) Date: Wed, 19 Mar 2008 01:48:59 -0700 (PDT) Subject: keyboard "interrupt" References: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Message-ID: <17c1c060-e1e8-4abb-836a-f86c6a598f20@d45g2000hsc.googlegroups.com> On 18 Mrz., 22:18, johnmfis... at comcast.net (John Fisher) wrote: > Hi Group, > > I have been absent a while, mainly because I have been getting better at > figuring out my own Python problems. But not this one... > > I have a timed loop performing certain tasks until a total period of > time has elapsed. I would like to be able to interrupt the loop or set > various flags during execution via keyboard input. raw_input seems to > just stop everything cold. I want the ability to just sacn the keyboard > buffer and see if something is there, then proceed normally in the loop > if there is no input in the buffer. Make sense? Totally easy? Let me > know... > > wave_man I use this code: class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: try: self.impl = _GetchUnix() except ImportError: self.impl = _GetchMacCarbon() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return getch() class _GetchMacCarbon: """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html was very helpful in figuring out how to do this. """ def __init__(self): import Carbon def __call__(self): import Carbon if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask return '' else: # # The event contains the following info: # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008) [1] # # The message (msg) contains the ASCII char which is # extracted with the 0x000000FF charCodeMask; this # number is converted to an ASCII character with chr() and # returned # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008) [1] return chr(msg & 0x000000FF) Best regards Hans Georg From bignose+hates-spam at benfinney.id.au Thu Mar 27 18:53:26 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 28 Mar 2008 09:53:26 +1100 Subject: How to take snap shot of the of project screen in Python References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: <87myojvkwp.fsf@benfinney.id.au> "Praveena Boppudi (c)" writes: > Can anyone help me out? Probably, but your chances improve by starting a *new* thread to discuss your new question, instead of replying to an existing thread. -- \ "Pinky, are you pondering what I'm pondering?" "I think so, | `\ Brain, but Zero Mostel times anything will still give you Zero | _o__) Mostel." -- _Pinky and The Brain_ | Ben Finney From gagsl-py2 at yahoo.com.ar Mon Mar 31 23:06:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Apr 2008 00:06:45 -0300 Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 23:28:13 -0300, escribi?: > tried wi5th the normal IDLE too and it worked later after i posted > this but now it doesnt work again. and i havent chnaged my firewall in > between. Perhaps any other running process has opened the port that IDLE uses to communicate with the running program. Or you have IDLE already running. See if you have python.exe/pythonw.exe processes running. Or go to Help, IDLE Help, and read the section "Running without a subprocess" -- Gabriel Genellina From andrei.avk at gmail.com Wed Mar 12 00:24:13 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Tue, 11 Mar 2008 21:24:13 -0700 (PDT) Subject: Open a file with default handler app? Message-ID: <83bc9bf2-9b9c-4959-870f-f4b37281f6e0@m3g2000hsc.googlegroups.com> Hi, I searched for this on google and in this group, but my awesome google-fu powers failed me. Is there a way to open any file using default program that'd open it? In other words, to do the same action as double-clicking in windows explorer? And secondly, is there a way to do the same thing for linux that'd work across all desktop environments and distributions, or at least in all major ones? What I'm trying to do here is to have records (or items) in my app where you could attach any kind of file and open it from there by clicking 'open'. Then it would go and do something like os.system("launch %s" % filename). So any way to do this except for keeping your own dictionary of file types and relevant apps? thx, -ak From patrick.waldo at gmail.com Mon Mar 31 14:53:12 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 31 Mar 2008 11:53:12 -0700 (PDT) Subject: xlrd and cPickle.dump Message-ID: Hi all, I have to work with a very large excel file and I have two questions. First, the documentation says that cPickle.dump would be the best way to work with it. However, I keep getting: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\python_files\pickle_test.py", line 12, in ? cPickle.dump(book,wb.save(pickle_path)) File "C:\Python24\lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects I tried to use open(filename, 'w') as well as pyExcelerator (wb.save(pickle_path)) to create the pickle file, but neither worked. Secondly, I am trying to make an ID number from three columns of data: category | topic | sub_topic, so that I can . I imagine that a dictionary would be the best way to sort out the repeats From asmodai at in-nomine.org Fri Mar 7 13:24:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 7 Mar 2008 19:24:18 +0100 Subject: Regarding coding style In-Reply-To: <20080307130919.b3f82a85.darcy@druid.net> References: <63d80bF273nraU1@mid.individual.net> <20080307130919.b3f82a85.darcy@druid.net> Message-ID: <20080307182418.GR60713@nexus.in-nomine.org> -On [20080307 19:10], D'Arcy J.M. Cain (darcy at druid.net) wrote: >The arguments for one over the other fall into these basic ones. Use >double spaces to make the document easier to read, especially by people >who read a lot and tend to skim to absorb as much information as >possible. Use single space because it makes the document display >nicer. This suggests to me that the schism is probably between two >different types of people, text/information oriented and >display/presentation oriented. I don't see any way to appeal to both. The double space came from the era of typewriters and monospace printers. Technology nowadays with all kinds of rendering engines and font specifications basically make the entire point of 'two spaces after a period' a moot point. In all my professional technical writing and documentation work I completely gave up on two spaces after a period. It's archaic. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When you are right, you cannot be too radical; When you are wrong, you cannot be too conservative. From software at ginstrom.com Mon Mar 10 06:23:40 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 10 Mar 2008 19:23:40 +0900 Subject: Edit and continue? In-Reply-To: <21CFA1FC32D3214EBFA2F449FF211E310EAD2972@nypcmg1exms318.leh.lbcorp.lehman.com> References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2972@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <064e01c88298$cfc95fe0$0203a8c0@MOUSE> > On Behalf Of Bronner, Gregory > I'm working on a GUI application that has lots of callbacks. > Testing it is very slow and quite boring, as every time I > find an error, I have to exit it, restart it, and repeat the > series of clicks. It would be really amazing if python > supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my > code and have it apply to a running instance of a class. What framework are you using? Also, automating those pesky clicks and such should make your GUI testing a lot easier. There are two angles of approach: "driving" the GUI automatically, and stubbing out/mocking the windowing methods so that you can test GUI components in a unit-testing framework. Regards, Ryan Ginstrom From ericofam at yahoo.com Sat Mar 8 18:49:09 2008 From: ericofam at yahoo.com (olusina eric) Date: Sat, 8 Mar 2008 15:49:09 -0800 (PST) Subject: Green's Function Message-ID: <501978.67770.qm@web53602.mail.re2.yahoo.com> Hi All, I am new to Python and trying to solve the Hamiltonian of a linear chair of atoms using green?s function. Does anyone know any pre-existing library functions and literature that could be helpful? Thanks EOF --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From atom.anderson at gmail.com Thu Mar 20 19:38:41 2008 From: atom.anderson at gmail.com (atom.anderson at gmail.com) Date: Thu, 20 Mar 2008 16:38:41 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> <927f5a44-f8fa-4fe2-bdc2-12fac2d50e7a@s37g2000prg.googlegroups.com> Message-ID: On Mar 20, 2:53 pm, Erich wrote: > On Mar 20, 12:39 pm, Ed Leafe wrote: > > > > > On Mar 20, 2008, at 11:54 AM, atom.ander... at gmail.com wrote: > > > > Number Three: Too much code, not enough concept. > > > > Presenters this one's for you. I can't count the number of > > > presentations I attended where the presenter would click through three > > > slides of pycode just to show us a two or three-line snippet that > > > illustrated their point. Worse yet, it was often at the bottom of the > > > screen so no one but the front row could see it. This goes for text > > > two. I saw some great presentations as well, and they had limited > > > text on each slide. The last thing your audience wants to see is a > > > slide drenched in text of any kind. > > > This is good advice: simple slides serve as organization cues, but > > the content should come from the speaker. The worst case (only saw > > this twice at this year's PyCon) is when there is a text-heavy slide > > that the presenter simply reads. We can all read it ourselves! Your > > job is to elaborate on the topic. > > > I'd like to see two things regarding slides: first, if at all > > possible, set a limit on the percentage of the talk that can consist > > of slides. I would much rather see the presenter show actual > > demonstrations of what they're talking about than simply talking about > > it. If that's not possible, then in the session description, clearly > > state the % of the talk that will be slides. Perhaps there are people > > who like to sit in a room and watch long PowerPoint (-type) > > presentations, but I'm not one of them. Let's see some code! Let's see > > stuff working (and sometimes crashing!), and how changes affect the > > results. When I've presented at PyCon and other conferences, that's > > the part that I spend the most time on: preparing demonstrations. It's > > not easy to do; certainly much more difficult than creating a slide > > that sums up what the demo does. But it makes for a much more > > interesting session! > > > -- Ed Leafe > > I'd like to see code listings made available to download where > appropriate. That way the slides dont have much hard to read content, > and we can look at the bits of code we find tricky as we see fit. And > if we get bored with bits, we can play with code! > > Erich. agreed. and just to clarify, i LIKE CODE! i hope we all do haha... but in a presentation setting if they could teach/share with us what they've been doing, allow us to download some example code (and tinker with it) and remove all those details from the slides, itd be vastly helpful. I fully expect anyone who presented this time (who takes time to TRY to improve) will improve. -adam From fn681 at ncf.ca Fri Mar 21 10:20:22 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:20:22 -0500 Subject: Fate of the repr module in Py3.0 In-Reply-To: References: Message-ID: Raymond Hettinger wrote: > Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , > and saw that the repr module was slated for vaporization. I've only > used the module a few times ever. I'm curious if the community wants > it kept around or whether it is considered clutter. > > The PEP is going to be finalized soon, so if you have issues with it, > they should be sent to the PEP author or brought up on the list, > http://mail.python.org/mailman/listinfo/stdlib-sig . > > Raymond I've never used it, the value isn't obvious. >>> import repr >>> repr.__doc__ 'Redo the builtin repr() (representation) but with limits on most sizes.' >>> Colin W. From cyu021 at gmail.com Tue Mar 11 07:04:06 2008 From: cyu021 at gmail.com (James Yu) Date: Tue, 11 Mar 2008 19:04:06 +0800 Subject: The stange behaviour of Tkinter.Canvas Message-ID: <60bb95410803110404o414ababft8fca994d16cfd60a@mail.gmail.com> I tried to update the rectangle on a canvas to get the visual effect of progressbar. It works all right if I delete the existing objects (rectangle and text) and create a new one. However, if I invoke canvas.itemconfig() to update the existing objects' options, gui just went nuts. I am more than happy to receive any help and advise. My code is provided as follows: ------------------------------------Start of Code------------------------------------ import Tkinter import threading import time class Progressbar(Tkinter.Frame): def __init__(self, parent=None, color='white', width=200, height=15): Tkinter.Frame.__init__(self, parent) self.pack(expand=Tkinter.YES, fill=Tkinter.BOTH) canv = Tkinter.Canvas(self, bg=color, relief=Tkinter.SUNKEN) canv.config(width=width, height=height) canv.pack(side=Tkinter.LEFT, expand=Tkinter.YES, fill=Tkinter.BOTH) self.canv = canv self.width = width self.height = height progress = -10 rect = canv.create_rectangle(0, 0, 0, height, fill='beige') text = canv.create_text(width/2, height*2/3, text='0%') self.rect = rect self.text = text self.progress = progress self.parent = parent parent.progressbar = self self.UpdateProgress() def SetProgress(self, progress=0): canv = self.canv width = self.width height = self.height rect = self.rect text = self.text ## canv.delete(rect) ## canv.delete(text) ## rect = canv.create_rectangle(0, 0, progress*width/100, height, ## fill='beige') ## text = canv.create_text(width/2, height*2/3, ## text='%s' %(str(progress)) + '%') canv.itemconfig(rect, width=width*progress/100) ## comment this canv.itemconfig(text, text='%s' %(str(progress)) + '%') ## comment this ## self.rect = rect ## self.text = text def UpdateProgress(self): progress = self.progress progress = progress + 10 self.progress = progress self.SetProgress(progress) if progress < 100: self.after(500, self.UpdateProgress) if __name__ == '__main__': root = Tkinter.Tk() Progressbar(parent=root) root.mainloop() ------------------------------------End of Code------------------------------------ uncomment the lines and comment out the itemconfig() lines to see the difference in gui's behaviours. Thanks, -- This is a UTF-8 formatted mail ----------------------------------------------- James C.-C.Yu -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Mon Mar 24 11:08:59 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 24 Mar 2008 12:08:59 -0300 Subject: python library to manipulate PALM documents ? In-Reply-To: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> References: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> Message-ID: 24 Mar 2008 13:36:13 GMT, Francesco Bochicchio : > Hi all, > > anybody knows a python equivalent of the perl PALM::Doc module (and > eventually other PALM::). > > I have a e-book device wich reads mobi-pocket format (among others). I > have downloaded from a forum a set of perl scripts to convert HTML to > unencripted mobipocket format and vice-versa. It uses the PALM:: package. > I would attempt (for my convenience and for the fun of it) to make a > python equivalent of that. Hence my quest for a Palm::Doc equivalent. > I'm not sure if it is what you are after, but it seems to be, check this: http://pypi.python.org/pypi/PalmDB/1.8.1 > My googling up to now resulted in nothing relevant. Keeping searching ... > > Ciao > ----- > FB > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From tmp1 at viltersten.com Sat Mar 1 16:33:36 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 22:33:36 +0100 Subject: SV: Surprised by the command "del" In-Reply-To: References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: <62tvenF25bed2U1@mid.individual.net> >> I'm reading the docs and at 5.2 the del >> statement is discussed. At first, i thought >> i've found a typo but as i tried that >> myself, it turns it actually does work so. >> >> a = ["alpha", "beta", "gamma"] >> del a[2:2] >> a >> >> Now, i expected the result to be that the >> "beta" element has been removed. Obviously, >> Python thinks otherwise. Why?! > > Remember that slices are specified as half-open > intervals. So a[m:n] includes m-n elements, > those indexed from m to n-1. Got it. Thanks! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From tom at t0mb.net Sat Mar 15 07:08:57 2008 From: tom at t0mb.net (Thomas Boland) Date: Sat, 15 Mar 2008 11:08:57 +0000 Subject: Python-list Digest, Vol 54, Issue 199 In-Reply-To: References: Message-ID: <47DBAE49.8080501@t0mb.net> what the? why can this get through? python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > ------------------------------------------------------------------------ > > Today's Topics: > > 1. I found affordable health insurance. (MSmith) > > > ------------------------------------------------------------------------ > > Subject: > I found affordable health insurance. > From: > MSmith > Date: > Sat, 15 Mar 2008 03:50:47 -0700 (PDT) > To: > python-list at python.org > > To: > python-list at python.org > > > I couldn't believe it. > > > Do yourself a favour and at least check it out: > > http://www.jdoqocy.com/click-2924912-10359791 > > > > Michael > > From k_r_a_j_kumar at yahoo.co.in Fri Mar 28 07:44:57 2008 From: k_r_a_j_kumar at yahoo.co.in (Raj kumar) Date: Fri, 28 Mar 2008 17:14:57 +0530 (IST) Subject: regarding xml elements Message-ID: <66657.48471.qm@web8713.mail.in.yahoo.com> Hi, I have an xml file in my application, I have created an element using Example goes like this......... document.createElement("abc") and i appeneded it by using append() method. But how i can reflect this change to my xml file? and one more thing is i want to create element with some other parameters.... like............. and i have m and n values as strings with me. can anybody help me to create this element and write it to the existing xml file as a child of an existing element? Thanks in advance.. Raj.. Forgot the famous last words? Access your message archive online at http://in.messenger.yahoo.com/webmessengerpromo.php -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.pedwysocki at gmail.com Fri Mar 7 11:12:38 2008 From: alex.pedwysocki at gmail.com (alex.pedwysocki at gmail.com) Date: Fri, 7 Mar 2008 08:12:38 -0800 (PST) Subject: Timed execution in eval Message-ID: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> I have various bits of code I want to interpret and run at runtime in eval ... I want to be able to detect if they fail with error, I want to be able to time them, and I want to be able to stop them if they run too long. I cannot add code to the eval'd strings that will help me accomplish this. Is there a good way to do this? I have it figured out for perl but I'd rather use python if possible. Thanks for any assistance. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 2 07:23:57 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 02 Mar 2008 13:23:57 +0100 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: <62vkitF256k2hU1@mid.individual.net> Gabriel Genellina wrote: > They are part of the telnet protocol; 0xFF (IAC=Interpret as > Command) starts a two or three byte command sequence. > Weren't you using telnetlib? It's supposed to handle this > transparently. With Twisted you don't need Telnetlib, twisted.conch.telnet does the job. I would definitely look at twisted.words, too. Regards, Bj?rn -- BOFH excuse #329: Server depressed, needs Prozac From Dodin.Roman at gmail.com Mon Mar 17 06:56:26 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 03:56:26 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue Message-ID: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Hi all i have a problem with this modules py2exe + pywinauto + sendkeys used together. In my script i'm using this expression app.window_(title="SJphone").Edit.TypeKeys("Test is running",with_spaces=True) TypeKeys is using SendKeys module i suppose. my setup.py looks like that: from distutils.core import setup import py2exe setup( options = {"py2exe": {"compressed": 1, "optimize": 0, "bundle_files": 1, "packages": ["encodings", "pywinauto", "pywinauto.controls", "pywinauto.tests"] } }, zipfile = None, console=["hosts.py"] ) and when i'm trying to run my hosts.exe i'm getting this traceback Traceback (most recent call last): File "hosts.py", line 524, in main() File "hosts.py", line 517, in main TestCase3_1() File "hosts.py", line 421, in TestCase3_1 SJstart() File "hosts.py", line 36, in SJstart app.window_(title="SJphone").Edit.TypeKeys("Test is running",with_spaces=Tru e) File "pywinauto\controls\HwndWrapper.pyc", line 928, in TypeKeys NameError: global name 'SendKeys' is not defined are there any workarounds on that? From jeff at jmcneil.net Wed Mar 19 00:31:49 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 19 Mar 2008 00:31:49 -0400 Subject: Is there a way to get __thismodule__? In-Reply-To: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> References: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> Message-ID: <82d28c40803182131j7b887a34j77c2a36586628193@mail.gmail.com> This is somewhere that I would personally use a metaclass. That way, if you define more subclasses of Message, you're not limited to doing so in that single module. Someone correct me if this is goofy, I don't do much metaclass programming. Perhaps something like: #!/usr/bin/python class MetaMessage(type): nmap = {} def __new__(mcl, name, bases, d): obj = super(MetaMessage, mcl).__new__(mcl, name, bases, d) # Check __name__ here as 'Message' isn't yet defined. if "Message" in [b.__name__ for b in bases]: if "number" not in d: raise TypeError("Message protocol expects a number attribute") MetaMessage.nmap[d['number']] = obj # Complete Creation. return obj class Message(object): __metaclass__ = MetaMessage class MessageOne(Message): number = 1 class MessageTwo(Message): number = 2 class MessageFourThousandThreeHundredAndTwentyTwoPointOne(Message): number = 4322.1 print MetaMessage.nmap Which results in: mac:~ jeff$ !p python test.py {1: , 2: , 4322.1000000000004: } mac:~ jeff$ Thanks! Jeff On 3/19/08, benhoyt wrote: > > Replying to myself here, after discovering more. :-) > > > > Is there a way to get __thismodule__ in Python? > > > It looks like __thismodule__ is just sys.modules[__name__]. Neat. > > Hmmm ... does sys.modules always already contain the currently-being- > loaded module? Or is this a hack that only happens to work? (It does; > I've tested it now.) Just wondering, because the Python docs say that > sys.modules is "a dictionary that maps module names to modules which > have *already been loaded*." > > > > if isinstance(attr, Message): > > nmap[attr.number] = attr > > > Oops, this was untested code. I actually meant issubclass (or > something similar) here, not isinstance. > > > Cheers, > Ben. > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 09:47:53 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 13:47:53 -0000 Subject: SQLObject 0.10.0 In-Reply-To: <20080311134003.GB14147@phd.pp.ru> References: <20080311134003.GB14147@phd.pp.ru> Message-ID: <00bf01c8837e$81aebe90$850c3bb0$@rawlins@thinkbluemedia.co.uk> Excellent stuff Oleg, I've been looking for an ORM framework for a while and hadn't settled on one, I'll give this a look through later today. Thanks, Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Oleg Broytmann Sent: 11 March 2008 13:40 To: Python Announce Mailing List; Python Mailing List Subject: SQLObject 0.10.0 Hello! I'm pleased to announce version 0.10.0, the first stable release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9 -------------- Features & Interface ~~~~~~~~~~~~~~~~~~~~ * Dropped support for Python 2.2. The minimal version of Python for SQLObject is 2.3 now. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.10. * SQLBuilder Select supports the rest of SelectResults options (reversed, distinct, joins, etc.) * SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect() use SQLBuilder Select queries; this make all SELECTs implemented internally via a single mechanism. * SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias) and properly sqlrepr. * Added SQLBuilder ImportProxy. It allows one to ignore the circular import issues with referring to SQLObject classes in other files - it uses the classregistry as the string class names for FK/Joins do, but specifically intended for SQLBuilder expressions. See tests/test_sqlbuilder_importproxy.py. * Added SelectResults.throughTo. It allows one to traverse relationships (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's a simple mechanism for pre-caching/eager-loading of later FK relationships (i.e., going to loop over a select of somePeople and ask for aPerson.group, first call list(somePeople.throughTo.group) to preload those related groups and use 2 db queries instead of N+1). See tests/test_select_through.py. * Added ViewSQLObject. * Added sqlmeta.getColumns() to get all the columns for a class (including parent classes), excluding the column 'childName' and including the column 'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to override it in the inheritable sqlmeta class; this makes asDict() to work properly on inheritable sqlobjects. * Allow MyTable.select(MyTable.q.foreignKey == object) where object is an instance of SQLObject. * Added rich comparison methods; SQLObjects of the same class are considered equal is they have the same id; other methods return NotImplemented. * RowDestroySignal is sent on destroying an SQLObject instance; postfunctions are run after the row has been destroyed. * Changed the implementation type in BoolCol under SQLite from TINYINT to BOOLEAN and made fromDatabase machinery to recognize it. * MySQLConnection (and DB URI) accept a number of SSL-related parameters: ssl_key, ssl_cert, ssl_ca, ssl_capath. * Use sets instead of dicts in tablesUsed. Dropped tablesUsedDict function; instead there is tablesUsedSet that returns a set of strings. * SQLBuilder tablesUsedSet handles sqlrepr'able objects. * Under MySQL, PickleCol no longer uses TEXT column types; the smallest column is now BLOB - it is not possible to create TINYBLOB column. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list From johnwalker3301 at comcast.net Wed Mar 26 16:33:54 2008 From: johnwalker3301 at comcast.net (jpw) Date: Wed, 26 Mar 2008 13:33:54 -0700 (PDT) Subject: Python / C++ embed halfway working - question about constructors Message-ID: <73dd0186-f171-44d6-9e3a-11828923f050@u10g2000prn.googlegroups.com> I am running my C++ / Python App on a MacBook Pro with 2.5 installed I have had some success in that I can load a module, get the class, get the reference, but when the python class calls another python class I don't ever seem to get the object back from the constructor. I am doing the following in the C++ file: Py_Initialize() PyObject* module = PyImport_Import(moduleName); PyObject* class = PyObject_GetAttrString(module, className); Py_DECREF(module); Py_DECREF(class); // Create the TSAFE object constructor arguments: // a file, and an int PyObject* tsafeOutputFile = PyFile_FromString("TsafeOutput", "a"); PyObject* resolveValue = PyInt_FromLong(0); PyObject* classArgumentTuple = PyTuple_New(2); PyTuple_SetItem(classArgumentTuple, 0, tsafeOutputFile); PyTuple_SetItem(classArgumentTuple, 1, resolveValue); classReference = PyEval_CallObject(class, classArgumentTuple); Py_MY_INCREF(classReference); Py_MY_DECREF(class); PyObject* pythonMethod = PyObject_GetAttrString(classReference, "registerFlight"); registerReturn = PyEval_CallObject(pythonMethod, argumentTuple); Py_MY_DECREF(pythonMethod); Py_MY_DECREF(argumentTuple); Essentially the code above should: call class constructor call registerFlight() calls registerFlight_() calls _flightPointer() -> where I never get by the section of code where the Flight.py Constructor get called Each flight should be added to my class object to build up a dictionary of flights. The python class methods getting called are detailed below and I never get by the call to _flightPointer(). I have opened a file and write to it at each step of code and I never get all the way through the _flightPointer() method Is there something I am missing here I cannot print the data out of the __init__ method in the Flight.py file? I did not include all of the code here because I am hoping the issue is I have got something wrong and it's not the python code but me. Ant help will be greatly appreciated. def registerFlight(self, ID, ACtype="?", IFR=1, RVSM=0, ATCcat="?", filedAlt=0, filedSpeed=0): "register flight (unitless args for outside client)" filedAlt *= FL # FL = Flight Level = 100 ft filedSpeed *= kn # kn = knots self.registerFlight_(ID, ACtype, IFR, RVSM, ATCcat, filedAlt,filedSpeed) def registerFlight_(self, ID, ACtype="?", IFR=1, RVSM=0, ATCcat="?", filedAlt=0, filedSpeed=0): "register flight (accepts arguments with units)" flight = self._flightPointer(ID) flight.registerFlight(ACtype, IFR, RVSM, ATCcat, filedAlt, filedSpeed) def _flightPointer(self, ID, track=0, Flight=Flight): "manage tracked and untracked flight lists" fltPointerFile = open('TSAFE_flightPointerOut', 'a') fltPointerFile.write("In the _flightPointer function\n") flights = self.flights unflights = self.untrackedFlights if ID in flights: fltPointerFile.write("in first IF\n") return flights[ID] if track: # new data record is a track update - start tracking if ID in unflights: # move flight to tracked status flights[ID] = unflights[ID] del unflights[ID] else: flights[ID] = Flight(ID) # new Flight object return flights[ID] ## THIS IS THE SECTION OF CODE NOT RETURNING A REFERENCE TO THE Flight object if ID not in unflights: fltPointerFile.write(ID) fltPointerFile.write(" In if ID not in unflights\n\n") unflights[ID] = Flight(ID) fltPointerFile.write("BACK FROM CALLING Flight(ID)\n") unflightsValue = ("unflights[ID]", unflights[ID]) unflightsString = str(unflightsValue) fltPointerFile.write("Return value is ") fltPointerFile.write(unflightsString) fltPointerFile.write('\n') return unflights[ID] From grante at visi.com Fri Mar 7 12:48:44 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Mar 2008 17:48:44 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <13t2vvstgkne233@corp.supernews.com> On 2008-03-07, Jon Ribbens wrote: > Personally, I dislike double spaces after sentences, but it is > not wrong to put them there any more than it is wrong not to > put them there. You're lucky my high school typing teacher didn't hear you say that... -- Grant Edwards grante Yow! I joined scientology at at a garage sale!! visi.com From bignose+hates-spam at benfinney.id.au Mon Mar 17 03:28:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Mar 2008 18:28:54 +1100 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> Message-ID: <87r6e9zu4p.fsf@benfinney.id.au> Bernard Lim writes: > > Depending on implementation, for immutable types, operations that > compute new values may or may not actually return a reference to any > existing object with the same type and value, while for mutable > objects this is (strictly)? not allowed. > > > Using the example given in 3.1, how do I verify that this is true > pertaining to immutable types? You don't. By the language definition, it's entirely up to the implementation whether *and when* to do this. So, even if you find a particular session that does this, there's no telling whether it'll stop happening at some future session using *exactly the same inputs* -- and, if it did change, that would also be entirely within the definition of the language. If something in a language specification says "this set of conditions leads to undefined behaviour", or "this aspect is implementation defined", then *absolutely any behaviour* that fits the rest of the definition is allowed, even if that results in non-determinism from the programmer's perspective. In short: Don't ever rely on such behaviour labelled with these "may or may not" phrases, even if you run some tests and appear to get predictable results. -- \ ?The power of accurate observation is frequently called | `\ cynicism by those who don't have it.? ?George Bernard Shaw | _o__) | Ben Finney From castironpi at gmail.com Mon Mar 10 13:10:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 10:10:07 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> <13taot5khcl933a@corp.supernews.com> Message-ID: On Mar 10, 11:36?am, Steven D'Aprano wrote: > On Mon, 10 Mar 2008 07:39:25 -0700, Gary Herron wrote: > > If either is a surprise, then understand that the "is" operator should > > probably *never* be used with immutable types. > > Mutable or immutable, it makes no difference: "is" is for testing > identity, == is for testing equality. If you need to test for identity, > use "is". If you need to test for equality, use ==. What is the notion of equal defined for functions? From Lie.1296 at gmail.com Sun Mar 23 13:22:16 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 23 Mar 2008 10:22:16 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> <210f1e24-649a-43c0-b975-8209211d56de@a70g2000hsh.googlegroups.com> Message-ID: <6900b188-8d08-4a9b-976f-719ba176fb97@e23g2000prf.googlegroups.com> On Mar 22, 2:23?pm, castiro... at gmail.com wrote: > > Sane programmers don't write such semi-functional things (unless it > > helps expressing the problem in certain domains). > > I now think that deprecating map, lambda & Co. was a good thing after > > all. > > If you write it that way the first time, you need therapy. ?Actually, > at this point, I (for one, personally) want to investigate 'certain > domains'. ?Tell me it's really bad at everything or what it's good > at. ?What can I respect about it? If you (castiro..) write it your way, you'll surely win the Obfuscated Python Code Contest. From gagsl-py2 at yahoo.com.ar Fri Mar 21 04:03:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 01:03:34 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: <76ca2753-1c8e-4dea-97b7-141ccbddb53b@z38g2000hsc.googlegroups.com> On 20 mar, 08:47, Godzilla wrote: > Thanks Ross and John for your help. I apologise for the code I posted > earlier not being the full picture of what I was trying to achieve. I > had instantiated multiple instances of elapseTime class and each of > them gets called approximately the same time. Below is the updated > code: You still have race conditions: > ? ? def setTime(self, state): > ? ? ? if state == 1: > ? ? ? ? self.checkTimeFlag = True > ? ? ? ? self.timeStamp = time.clock() > ? ? ? else: > ? ? ? ? self.checkTimeFlag = False > > ? ? def elapsedTime(self): > ? ? ? prevTime = time.clock() > ? ? ? while True: > ? ? ? ? curTime = time.clock() > ? ? ? ? timeDiff = (curTime - prevTime) > ? ? ? ? if timeDiff < 0.0: > ? ? ? ? ? printq.put_nowait('time.clock() has gone backward!!! Time > Diff '+str(timeDiff)) > ? ? ? ? if self.checkTimeFlag: > ? ? ? ? ? if (curTime - self.timeStamp) > 1.0: > ? ? ? ? ? ? printq.put_nowait(self.name+", actual Elapsed > Time"+str(round(curTime-self.timeStamp, 3))) > ? ? ? ? ? ? self.checkTimeFlag = False > ? ? ? ? prevTime = curTime > ? ? ? ? time.sleep(0.05) Both functions run on different threads, use self.checkTimeFlag and self.timeStamp. By example, setTime sets self.checkTimeFlag = True before self.timeStamp; the other thread can use and old value for self.timeStamp. -- Gabriel Genellina From xkenneth at gmail.com Wed Mar 12 14:10:59 2008 From: xkenneth at gmail.com (xkenneth) Date: Wed, 12 Mar 2008 11:10:59 -0700 (PDT) Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> <47D80BC4.2010307@behnel.de> Message-ID: On Mar 12, 11:58?am, Stefan Behnel wrote: > xkenneth wrote: > > On Mar 12, 6:32 am, "Diez B. Roggisch" wrote: > >> xkenneth wrote: > >>> Hi All, > >>> ? ?Quick question. I've got an XML schema file (XSD) that I've > >>> written, that works fine when my data is present as an XML file. > >>> (Served out by apache2.) Now when I callpythonas a cgi script, and > >>> tell it print out all of the same XML, also served up by apache2, the > >>>XSDis not applied. Does this have to do with which content type i > >>> defined when printing the xml to stdout? > >> Who's applying the stylesheet? The browser, some application like XmlSpy or > >> what? > > > The browser. > > Well, why should it validate your file? Browsers don't do that just for fun. > > Stefan Sorry, it was really late when i wrote this post. The file is an XSL file. It defines HTML depending on what appears in the XML document. Regards, Kenneth Miller From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:54:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:54:56 -0300 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 12:15:48 -0300, harryos escribi?: >> The code is pretty legible as it is now. Anyway, using min() and a >> generator: >> >> > > hi > is this calculated distance really Euclidean distance? When i checked > wikipedia http://en.wikipedia.org/wiki/Euclidean_distance > it shows a calculation involving sum of squares of the differences of > elements.Here in this code ,the sum of coordinates are used? is that a > different measure? (Thanks for trimming the irrelevant parts of the message, that's good; but you trimmed too much text, even attribution lines - the above quoted sentence was mine) That's what I said in another paragraph. "sum of coordinates" is using a different distance definition; it's the way you measure distance in a city with square blocks. I don't know if the distance itself has a name, but the norm from which it is derived is called norm-1, or L1; the usual euclidean distance is derived from norm-2. See http://mathworld.wolfram.com/VectorNorm.html If you only want to see if two things are "close enough", this provides a faster measure than the euclidean distance. -- Gabriel Genellina From mnordhoff at mattnordhoff.com Fri Mar 14 08:50:11 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 14 Mar 2008 12:50:11 +0000 Subject: Update pytz timezone definitions In-Reply-To: References: Message-ID: <47DA7483.80804@mattnordhoff.com> _robby wrote: > I am looking at using pytz in a scheduling application which will be > used internationally. I would like to be able to update the definition > files that pytz uses monthly or bi-monthly. > > As far as I can tell, pytz seems to be updated (fairly) regularly to > the newest tzdata, but I don't want to have to update my pytz, just > it's definitions. > > http://www.twinsun.com/tz/tz-link.htm says that pytz "compiles tz > source into Python." Does this mean that there is already a method for > updating the definitions? > > Any help would be greatly appreciated, even if it is to point out > something obvious which I over looked. > > - Robby pytz's build process is rather complicated (e.g., a list of all time zones is appended to pytz/__init__.py). I really don't think it would be worth the effort. python-dateutil [1] [2] provides time zone support similar to pytz's, among other features. It keeps the time zone files in a tarball and I'm pretty sure it would be easy to update. I still don't get why you'd want to go to the effort though. Upgrading the whole package is easy. It's not like pytz gets a new API every version. [1] [2] -- From gagsl-py2 at yahoo.com.ar Tue Mar 25 21:49:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 22:49:36 -0300 Subject: embedded python pythonpath References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> <3a4a8f930803251822h5d423198yc318ed270ad7d92a@mail.gmail.com> Message-ID: En Tue, 25 Mar 2008 22:22:41 -0300, Furkan Kuru escribi?: > On 3/26/08, Gabriel Genellina wrote: > >> En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru >> escribi?: >> >> > Actually, I do not want any .py or .pyc files around my executable. >> > (including userdict, sys, site etc) >> > I want to have just single zip file for all python files. >> >> Putting all of them into pythonNN.zip (NN depending on the Python >> version >> in use) should be enough, but I've never tried it. > I had already tried putting all of them into pythonNN.zip but I had to > copy it to the place > where sys.path points in my case it was windows\system32\python25.zip It should be in the same directory as python25.dll; you don't have to use windows\system32 if you copy python25.dll to your application directory. >> After renaming the directory where Python 2.5 were installed, my >> test25.exe program (the one compiled using Python 2.5.1) worked fine. So >> it looks like it is something with how the "python home" is searched. > > Ok then changing or deleting pythonhome environment variable may fix the > problem? "Python home" means the directory where Python is installed, from which the rest of the directories are derived. It should have a lib directory with an os.py file inside, and so on... I don't have a PYTHONHOME environment variable, nor a PYTHONPATH (except for this testing). -- Gabriel Genellina From nick at njday.com Sun Mar 9 14:06:36 2008 From: nick at njday.com (Nick Day) Date: Sun, 9 Mar 2008 11:06:36 -0700 (PDT) Subject: Problems installing Python Imaging Library Message-ID: <76000a76-0c8f-4b79-95c8-9d0f4aae0972@n58g2000hsf.googlegroups.com> Hi, I'm trying to install PIL from source on my CentOS 4.5 server. The build summary reports that I have everything installed... -------------------------------------------------------------------- PIL 1.1.6 BUILD SUMMARY -------------------------------------------------------------------- version 1.1.6 platform linux2 2.3.4 (#1, Dec 11 2007, 05:28:55) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] -------------------------------------------------------------------- --- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok ... but if I try and build it I receive the following error: /usr/bin/ld: /usr/local/lib/libjpeg.a(jcparam.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC How do I fix this? I am currently running "python setup.py build" and don't understand how I would change the compiling options to add the "- fPIC" flag. I'm quite a newbie when it comes to Linux/Python so any help you could give me would be great. Thanks, Nick From castironpi at gmail.com Wed Mar 5 13:58:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 10:58:38 -0800 (PST) Subject: Dual look-up on keys? Message-ID: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> I want to hash values to keys. How do the alternatives compare? From gagsl-py2 at yahoo.com.ar Thu Mar 6 07:10:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 10:10:23 -0200 Subject: Display all variable/function bindings in Python Shell References: <16803ed0803060010l64444a76o281411d323284b36@mail.gmail.com> Message-ID: En Thu, 06 Mar 2008 06:10:22 -0200, Sanjaya Vitharana escribi?: > 1.) Are there any way to display all variable/function bindings in Python > Shell ? dir() dir(some_object) help(some_object) vars(some_object) > 2.) Are the any way to Search "Python-list Archives" before sending > simple > question to the list ? Use the Google interfase to this newsgroup: http://groups.google.com/group/comp.lang.python/ -- Gabriel Genellina From software at ginstrom.com Mon Mar 24 21:39:44 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 25 Mar 2008 10:39:44 +0900 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: <08fd01c88e19$1a91aba0$0203a8c0@MOUSE> > On Behalf Of john s. > import os, sys, string, copy, getopt, linecache > from traceback import format_exception > > #The file we read in... > fileHandle = "/etc/passwd" > srcFile = open(fileHandle,'r') > srcList = srcFile.readlines() > > #yah, a for loop that "iterates" through the file of "lines" > for i in srcList: > strUsr = string.split(i,":") > theUsr = strUsr[0] > usrHome = "/expirt/home/",theUsr,"/" > usrHome = ''.join(usrHome) How about for starters: import os for line in open("/etc/passwd"): user, _pwd = line.split(":") user_home = os.path.join("/expirt/home", user) > try: > os.makedirs('usrHome' ) > except Exception, e: > print e if os.path.exists(user_home): print "User Home dir exists, checking and fixing permissions." else: print "Do other stuff" Regards, Ryan Ginstrom From bronger at physik.rwth-aachen.de Fri Mar 14 07:50:08 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 14 Mar 2008 12:50:08 +0100 Subject: anydbm and sync'ing Message-ID: <871w6dr0cv.fsf@physik.rwth-aachen.de> Hall?chen! A TurboGears process opens a DB file with anydbm and keeps it open. The the same time, this file is updated by another process. How can I tell the TurboGears process to fetch the new values? my_db.sync() didn't help -- apparently, it only *writes* to the DB file but doesn't read new data from it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From Scott.Daniels at Acm.Org Thu Mar 27 00:04:23 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 26 Mar 2008 21:04:23 -0700 Subject: Can my own objects support tuple unpacking? In-Reply-To: References: Message-ID: <13um6p08v0ea9f3@corp.supernews.com> Patrick Toomey wrote: > ... I am trying to figure out how tuple unpacking behavior works.... > a,b,c,d = e > > Is a method called, such as __getitem__ for each index on the left > (0,1,2,3)? I thought this was logical, ... > > class Foo: > def __getitem__(self, index): > print index > return 1 _So_ close. class Foo(object): # _Never_ use old-style without a reason def __getitem__(self, index): print index if index < 3: return index * 5 # just to see raise IndexError('Zapped') # The secret -- run out. -Scott David Daniels Scott.Daniels at Acm.Org From castironpi at gmail.com Mon Mar 10 02:53:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 23:53:31 -0700 (PDT) Subject: image matching algorithms References: Message-ID: <1ff9e1a3-ba36-4f0e-a283-754e4ec7c3b6@d62g2000hsf.googlegroups.com> On Mar 10, 1:32?am, "Daniel Fetchinson" wrote: > Hi all, > > There are a number of free tools for image matching but it's not very > easy to decipher the actual algorithm from the code that includes db > management, GUI, etc, etc. I have my own image database and GUI so all > I need is the actual algorithm preferably in pseudo code and not in > the form of a research paper (from which I also found a lot but since > I'm not that much interested in the actual science of image > recognition this seems like an over kill). > > My understanding of image matching is that it works by first > calculating N real numbers for an image and defining a metric for > pairs of N-tuples. Images are similar if their distance (defined by > the metric) is small. > > The various free tools differ by their chosen optimization paths and > their degree of specialization. My preference would be, > > 1. Doesn't really matter how long it takes to compute the N numbers per image > 2. Lookups should be fast, consequently N should not be too large (I guess) > 3. It should be a generic algorithm working on generic images (everyday photos) > 4. PIL should be enough for the implementation http://www.idi.ntnu.no/~blake/gbimpdet.htm "High level features carry information about an image in an abstracted or propositional form" It says it constructs a graph about the image's features. Here's the graph: Graph components Notes [A[@id=crot3.77;ext:sqr:aa(1659):mm(19815,148,0,0): <- Leading node cg(62,86):cr(255,153,153):pl(-204,574,792,10353)]] with attributes [[5][@rep= 1 ]] <- Relation and strength [B[@id=crot3.77;ext:sqr:aa(199):mm(17759,244,1,0): <- Trailing node cg(98,77):cr(153,153,255):pl(966,2,258,-79198)]]$ with attributes It doesn't say what corner cases it leaves. "seem to provide" and "seems to be extremely flexible". I like this feature: - the equation of the best fitting plane Ax+By+Cz+D=0 to the range image data masked by the current region; Where does that get you? From Afro.Systems at gmail.com Tue Mar 25 14:47:05 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 11:47:05 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <07185819-2b2b-40c3-af26-f683edd57a79@d21g2000prf.googlegroups.com> Hi all, I would like to thank you all for all the suggestions. what I did was simply extending the super class data with data from its child using the id example, Foo.id = 1 is now = [1] and the FooSon does self.id.append(2) the system designer wanted inheritance+java and I wanted Python +Functional Programming i guess we will meet somewhere in the middle thanks again tzury From andreww at datanet.ab.ca Wed Mar 5 19:39:02 2008 From: andreww at datanet.ab.ca (Andrew Warkentin) Date: Wed, 05 Mar 2008 17:39:02 -0700 Subject: ActiveX in Webpage? In-Reply-To: References: Message-ID: <47CF3D26.9020007@datanet.ab.ca> Michael Wieher wrote: > Hello, > > I'm trying to design a python-based web-app from scratch, based on a > standalone MFC application. > Obviously I'll be wrapping a lot of C++ functionality in custom > extensions, but is anyone aware of any documentation/techniques that > could help me "drop" an ActiveX control into a webpage, and just use it? > That, or, of course, a solid bit of writing detailing the > idiosyncrasies of MFC-wrapped Py-Extensions would be useful as well. > > -Mike I would recommend against embedding ActiveX controls, especially if this web application is public (if it is internal, it's not as much of a problem, but you still might have problems later if you ever want to migrate off Windows). ActiveX controls are not only Windows-specific, but (mostly) IE-specific as well. Since you are developing it from scratch, I would say that you should do it right and use AJAX, or possibly Flash or Java applets, all of which are reasonably portable. From sjmachin at lexicon.net Mon Mar 10 00:07:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Mar 2008 21:07:27 -0700 (PDT) Subject: Import - interpreter works but .py import does not References: <055c615e-3beb-4037-ab1e-02afeb38da40@e6g2000prf.googlegroups.com> Message-ID: <6476f149-f250-4844-8598-181b87f9ddeb@s13g2000prd.googlegroups.com> On Mar 10, 1:59 pm, John Boy wrote: > First post and very much a newbie to Python. Have 2.5 on Linux (GG). I > think I have set up PYTHONPATH correctly in that I can import a module > apply_bp and it complains about line 20 in apply_bp which is: > > import sys, aipy, numpy, os Please get used to showing the error message. "it complains about line x" is not very helpful. Fortunately in this case we can guess that it is "complaining" about inability to import either aipy or numpy (sys and os are built-in). > > At the interpreter prompt, however, I can import sys, numpy etc. and > can do dir() and see the entry points so I think my overall > installation is OK. > > Why does line not work ? More information please. At the interpreter prompt, do this: import sys sys.path import aipy; aipy.__file__ import numpy; numpy.__file__ and show us the result. Change the offending line in your apply_bp module to import sys print sys.path import os, aipy, numpy and show us ALL of the output. At the shell prompt, do whatever it takes to display the contents of PYTHONPATH, and show us the results. > Also I would have thought that when I pre- > imported sys et al that they would be in the symbol table so that the > import line would be a noop. The concept of "preimporting" a module is novel to me. Importing a module at the interpreter prompt doesn't persist when you exit the interpreter and then (implicitly) start up another interpreter task to run your script. Importing a module in your script puts the module in the script's namespace, which is quite distinct from the namespace of the apply_bp (or any other) module. If those two possibilities don't cover what you mean, please explain. From celoserpa at gmail.com Thu Mar 6 08:04:26 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Thu, 6 Mar 2008 10:04:26 -0300 Subject: Class context execution problems Message-ID: <1e5bcefd0803060504n5aa4970bh90092b57b0a106f0@mail.gmail.com> I'm using a class in a conext other than the subpackage in which it is located and I'm getting template lookup errors. This class expects to find a .pt file in a directory relative to its package. However, this class is normally used by other classes in the same namespace. class ObjectWidget: template = "templates/objectwidget.pt" However, I needed to import this class (ObjectWidget) from a class outside its namespace(package). Now, I think the class is running in the context of the file that is using it and so, the the class not finding the .pt file (I think becouse the class file is being contextualized to the currently running one which is outside the browser subpackage) how could I solve it? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From isolomon at solomonltd.com Sat Mar 1 19:56:40 2008 From: isolomon at solomonltd.com (Ira Solomon) Date: Sat, 01 Mar 2008 19:56:40 -0500 Subject: Book Recomendations Message-ID: I am an experienced programmer (40 years). I've done Algol (if you've heard of that you must be old too), PL/1, VB,VBA, a little C, and a few other odd languages (e.g. Taskmate). I'm interested in learning Python and have downloaded a slew of books. Too many. I'd like a recommendation as to which books are considered to be the cream of the crop. I know there are tutorials on the web, but, again, I don't know the quality. I would appreciate recommendations on those as well. Thanks Ira From durieux_br at yahoo.com.br Thu Mar 27 15:17:21 2008 From: durieux_br at yahoo.com.br (Fabio Durieux Lopes) Date: Thu, 27 Mar 2008 19:17:21 -0000 Subject: Time problem (again) Message-ID: Hi, I'm recreating a date-time based on a string and I have a problem when daylight savings time is set (I'm off by 1). So today I forced my computer into daylight savings time and debugged it again, but this time I noticed something strange. This is the documentation from python library reference section 6.10: 6.10 time -- Time access and conversions ... daylight Nonzero if a DST timezone is defined. ... And this is what I debugged: -> fileTimeInSecs = time.mktime(time.strptime(timeString, "%Y%m%d%H%M")) (Pdb) p timeString '200803271643' (Pdb) n > /home/salsa/Projects/TimBR_CDR/fileSync/ fileSynchronizer.py(50)passFilesOlderThan() -> print time.daylight (Pdb) 0 See how 'print time.daylight' resulted in '0'? Shouldn't it be Non- zero? Do I have to set something for it to use DST? Also, is this the right list to send questions? From arnodel at googlemail.com Mon Mar 10 17:52:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Mar 2008 14:52:45 -0700 (PDT) Subject: any chance regular expressions are cached? References: <13t9bbap76cbdf3@corp.supernews.com> Message-ID: On Mar 10, 3:39?am, Steven D'Aprano wrote: [...] > Having said that, at least four out of the five examples you give are > good examples of when you SHOULDN'T use regexes. > > re.sub(r'\n','\n'+spaces,s) > > is better written as s.replace('\n', '\n'+spaces). Don't believe me? > Check this out: > > >>> s = 'hello\nworld' > >>> spaces = " ? " > >>> from timeit import Timer > >>> Timer("re.sub('\\n', '\\n'+spaces, s)", > > ... "import re;from __main__ import s, spaces").timeit() > 7.4031901359558105>>> Timer("s.replace('\\n', '\\n'+spaces)", > > ... "import re;from __main__ import s, spaces").timeit() > 1.6208670139312744 > > The regex is nearly five times slower than the simple string replacement. I agree that the second version is better, but most of the time in the first one is spend compiling the regexp, so the comparison is not really fair: >>> s = 'hello\nworld' >>> spaces = " " >>> import re >>> r = re.compile('\\n') >>> from timeit import Timer >>> Timer("r.sub('\\n'+spaces, s)", "from __main__ import r,spaces,s").timeit() 1.7726190090179443 >>> Timer("s.replace('\\n', '\\n'+spaces)", "from __main__ import s, spaces").timeit() 0.76739501953125 >>> Timer("re.sub('\\n', '\\n'+spaces, s)", "from __main__ import re, s, spaces").timeit() 4.3669700622558594 >>> Regexps are still more than twice slower. -- Arnaud From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:34:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:34:36 -0300 Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> <654k1kF2e8bnuU1@mid.uni-berlin.de> Message-ID: En Fri, 28 Mar 2008 13:17:44 -0300, Diez B. Roggisch escribi?: > pianomaestro at gmail.com schrieb: >> I have an extension module that gets initialized multiple >> times because I am using threads. >> >> How can this module access global state (not per-thread state) ? >> It needs to create a singleton. > > The question is very unclear. > > If you are after *not* initializing your module concurrently, why don't > you just do it *once* before the threads are started? alternatively, you > need to govern the initialization-code with a mutex - or anything > similar. Ouch... The simple "if (foo!=NULL)" I posted earlier is not thread safe and should not be used in this situation. Do as Diez said. -- Gabriel Genellina From sophacles at gmail.com Thu Mar 13 01:40:03 2008 From: sophacles at gmail.com (Erich) Date: Wed, 12 Mar 2008 22:40:03 -0700 (PDT) Subject: Generator woes References: Message-ID: On Mar 13, 12:33 am, Erich wrote: > Hi all, > > I am trying to get the following generator to work to these goals: > > 1. When it recieves an exception (via a throw()) it yeilds the value > of handler.remaining. Otherwise it yeilds None. > 2. Send adds data to the generator. > > Goal 2 is working great. Goal 1 on the other hand, is not working. The > result of a throw is always None. > > Any reasons why this does not work as I expect? If not, what is wrong? > > Code: > def make_handler(): > def handler(): > eol = '\r\n' > > handler.remaining = 1 > response = '' > data = '' > > while not response.endswith(eol): > trv = None > try: > ndata = (yield trv) > if ndata: response += ndata > trv = None > except: > trv = handler.remaining > response = response.strip() > yield response * 2 > res = handler() > res.next() > return res > > x = make_handler() > y = x.send('a') > print 'y (should be None):',y > y = x.send('b') > print 'y (should be None):',y > y = x.throw(Exception) > print 'y (should be 1):',y > y = x.send('c\r\n') > print 'y (should be abcabc):',y > > Output: > y (should be None): None > y (should be None): None > y (should be 1): None > y (should be abcabc): abcabc > > Thanks, > Erich Never mind its obviously a case of "I need to look foolish before I can see the simple error". Im going to blush and hide now. Erich From xelapond at gmail.com Sun Mar 30 00:02:01 2008 From: xelapond at gmail.com (Alex Teiche) Date: Sat, 29 Mar 2008 21:02:01 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt Message-ID: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Hello, I am pretty new to Python, and have never learned C++. I am trying to implement the following thing into my python application: http://doc.trolltech.com/4.3/qsystemtrayicon.html Through PyQt. I have been using PyQt for awhile and I know how do use it, but I could not get this specific thing to work. Can someone give me some hints as to get it working in Python? Thanks a ton, Alex From mail2spj at yahoo.com Fri Mar 28 15:47:51 2008 From: mail2spj at yahoo.com (SPJ) Date: Fri, 28 Mar 2008 12:47:51 -0700 (PDT) Subject: Question regd downloading multipart mail using POP3 Message-ID: <118409.12220.qm@web50111.mail.re2.yahoo.com> I am facing a strange problem when I am trying to retrieve multipart mail from POP server with attachments. The task is to write a script which will retrieve mail with specific 'from' field. Get the subject, body and attachments if any and reuse this info to send mail with different format to ticketing system. The global variable values I am expecting is: msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so on attachmentList=[['none'],['attachname.txt','filename.pl']] where none is no attachments. But the result I am getting is: msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so on attachmentList=[[none],['none', 'attachname.txt', 'filename.pl']] An extra 'none' in the attachment list except for plain/text mails without attachments. I have tried a lot to figure out how to eliminate this but with no luck do far :( I know that some part is getting excluded from the condition, but I am unable to figure out what is causing this. Following is the function I wrote: I am not an expert programmer hence my code is not clean, so pl. bear with me. Thanks, SPJ ---------- import poplib, email, re, sys, os msgList = [] # Global list that contains messages PATH = Path to save file on disk # path were attachements will be stored attachmentName = [] # Name of attachements def popconnect(): # connect the pop server and send username and password pconnect = poplib.POP3(server) pconnect.user(user) pconnect.pass_(passwd) # Give connection status, msg list and total msg size status, msg_list, octets = pconnect.list() if len(msg_list) == 0: print "No messages in Mailbox" pass # regex for searching mails from example at example.com soc = re.compile(".*example\@example.com.*") # iterate over the number of new messages from counterpane and qppend the required fields # to a list. for msg_number in [msg.split(' ')[0] for msg in msg_list]: status, lines, octets = pconnect.retr(msg_number) msg1 = email.message_from_string('\n'.join(lines)) tmpList = [] attachList = [] attachnumber = 0 check1 = msg1.get('From') check2 = msg1.get('Subject') if soc.match(check1): subject = msg1.get('Subject') # Subject for only mails only after condition is true. if msg1.is_multipart(): for part in msg1.walk(): # multipart/* are just containers mptype = part.get_content_maintype() body = part.get_payload(decode=True) if mptype == "multipart": continue filename = part.get_filename() if filename: # Attached object with filename print 'in file ' +part.get_content_type() attachnumber += 1 tmpList[2] = attachnumber # number of attachments in message attachList.append(PATH+filename) # path to attachment # Copy the attachment to disk f = open(PATH + filename,"wb") f.write(part.get_payload(decode = True)) f.close() else: print part.get_content_type() if part.get_content_type() != ("text/html" or "text/plain" or "multipart/alternative" or "multipart/mixed"): tmpList.append(subject) # Subject from message tmpList.append(body) # Body from message tmpList.append(0)# If no attachments attachList.append('none') else: # Not multipart, only body portion exists print "Not Multipart\n" body=msg1.get_payload(decode=True) tmpList.append(subject) # Subject from message tmpList.append(body) tmpList.append(0) attachList.append('none') if len(tmpList) > 0: msgList.append(tmpList) if len(attachList) > 0: attachmentName.append(attachList) print msgList, attachmentName pconnect.quit() def main(): popconnect() if __name__== '__main__': main() ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From pavloutefkros at gmail.com Sun Mar 9 17:22:48 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 9 Mar 2008 14:22:48 -0700 (PDT) Subject: execute Message-ID: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> i'm trying to execute a file without replacing the current process, but after searching the help file, documentations and the web, i can't a way of doing that. os.exec*() will close the current program. ps: by executing i mean like typing "mspaint" in run dialog.. it's not a python file From gagsl-py2 at yahoo.com.ar Sat Mar 29 21:39:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 22:39:25 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> <657v3lF2e7r7pU1@mid.uni-berlin.de> Message-ID: En Sat, 29 Mar 2008 19:45:09 -0300, Diez B. Roggisch escribi?: >> I suggest that you remove the simplejson-xxxxxx.egg file and delete the >> simplejson entry in easy-install.pth (both in your site-packages >> directory) >> Then extract the simplejson directory from inside the original .tar.gz >> archive into your site-packages directory (so you end up by example with >> a .../site-packages/simplejson/decoder.py file, among others) >> That appears to be enough; import simplejson worked fine for me. >> >> I hate those f****ng eggs. Ah, and I hate easy_install too. > > This has nothing to do with setuptools or easy_install per se. The > author of simplejson tried to create a library that works with or > without a C-extension. And failed. I think that the whole approach is doomed to fail; trying to do things more complicated that they should be. The pure-python part of simplejson is just a package. Copying the directory into site-packages is *ALL* that is required; distutils can do that perfectly. That's all folks!. A database or registry keeping track of installed product versions might be useful, too. Anything that does much more than that is just looking for problems; simple systems work better than complex ones. In this case, there is no need to create an egg, no need to play with .pth files, no need to slow down the package at import time (eggs must be decompressed), no need to extend sys.path and slow down *all* other imports. I don't feel that anything is better by using eggs or easy_install, and at least for me, they always have given more problems than answers. So, again, I hate eggs and easy_install. And I hate eggplants too. -- Gabriel Genellina From michele.simionato at gmail.com Sun Mar 2 11:35:31 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 2 Mar 2008 08:35:31 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: On Mar 2, 5:23 pm, js wrote: > Hi, > > Have you ever seen Beautiful Python code? > Zope? Django? Python standard lib? or else? > > Please tell me what code you think it's stunning. The doctest module in the standard library. M.S. From michael.wieher at gmail.com Sat Mar 29 23:19:08 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sat, 29 Mar 2008 22:19:08 -0500 Subject: html DOM In-Reply-To: References: Message-ID: Was this not of any use? http://www.boddie.org.uk/python/HTML.html I think, since HTML is a sub-set of XML, any XML parser could be adapted to do this... I doubt there's an HTML-specific version, but I would imagine you could wrap any XML parser, or really, create your own that derives from the XML-parser-class... On Sat, Mar 29, 2008 at 6:09 PM, Sam the Cat wrote: > Is there a package that would allow me the same or similar functionality > for > modifying html code via the DOM model as I have in JavaScript ? I'd like > to > parse an html file, then modify it and save the result. I am not trying > to > do this online, rather I would like to do this on a batch of files stored > on > my hard drive. I have found several packages that allow me to parse and > dissect html but none that allow me to modify the object and save the > results -- perhaps I am overlooking the obvious > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Mar 28 18:55:57 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Mar 2008 22:55:57 GMT Subject: case insensitive lstrip function? References: <0eb666fe-8c3e-4a93-afbf-1953922c19bd@s13g2000prd.googlegroups.com> Message-ID: <655bbtF2e1u8fU2@mid.uni-berlin.de> On Fri, 28 Mar 2008 15:48:09 -0700, Kelie wrote: > Is there such a function included in the standard Python distribution? AFAIK not. > This is what I came up with. How to improve it? Thanks. > > def lstrip2(s, chars, ingoreCase = True): > if ingoreCase: > s2 = s.upper().lstrip(chars.upper()) > return s[len(s)-len(s2):] > else: > return s.lstrip(chars) What about this: def lstrip2(string, chars, ignore_case=True): if ignore_case: chars = chars.lower() + chars.upper() return string.lstrip(chars) Ciao, Marc 'BlackJack' Rintsch From gargonx at gmail.com Wed Mar 12 00:55:20 2008 From: gargonx at gmail.com (gargonx) Date: Tue, 11 Mar 2008 21:55:20 -0700 (PDT) Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: On Mar 12, 4:45 am, Adonis Vargas wrote: > gargonx wrote: > > Say i have the two methods: > > > def ReturnMethod(request, x): > > if request is True: > > return x > > else: print "No String for you...False!" > > > def SendMethod(request): > > xstring = "Some text" > > ReturnMethod(request, xstring) > > > SendMethod(True) > > > Why does ReturnMethod not return the string x? I do believe it is > > returning with a NoneType. > > Any help would be greatly obliged > > > Thanks, Josh > > That is because request is bound a string (str) object. You are probably > testing for null so it should look like: > > if request: > return x > else: > print "No String for you...False!" > > Hope this helps. > > Adonis Still no return of string. The null testing is not really the deal. that could be replaced with anything EG: def ReturnMethod(request, x): if request is 'random': return x else: print "No String for you...False!" def SendMethod(request): xstring = "Some text" ReturnMethod(request, xstring) SendMethod('random') From madduck at madduck.net Sun Mar 16 09:21:40 2008 From: madduck at madduck.net (martin f krafft) Date: Sun, 16 Mar 2008 14:21:40 +0100 Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? Message-ID: <20080316132140.GA24529@piper.oerlikon.madduck.net> Hi, xmlrpclib.dumps((None,), allow_none=True) yields '\n\n\n\n' Why doesn't it just yield '\n\n\n\n' Or even just '\n\n\n' Those are valid XML and valid XML-RPC, but isn't. Thanks for any thoughts... -- martin | http://madduck.net/ | http://two.sentenc.es/ a farmer is a man outstanding in his field. spamtraps: madduck.bogus at madduck.net -------------- next part -------------- A non-text attachment was scrubbed... Name: digital_signature_gpg.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature (see http://martin-krafft.net/gpg/) URL: From dboddie at trolltech.com Fri Mar 28 09:12:04 2008 From: dboddie at trolltech.com (David Boddie) Date: Fri, 28 Mar 2008 14:12:04 +0100 Subject: PyQT / QDate / QTableWidget Message-ID: <200803281412.04679.dboddie@trolltech.com> On Wed Mar 26 15:13:09 CET 2008, wrightee wrote: > My server gives me a string y[0]: "20080327", which I convert to a > QDateTime object using: > > x=QDateTime.fromString(y[0],"yyyymmdd") > > Printing x.toString("dd-mm-yyyy") gives me what I would expect - > 27-03-2008 Strange. You should really be using "dd-MM-yyyy". Maybe this is why QDate isn't behaving as you would expect - see below. > What I'm trying to do though is add this to a QTableWidget item to > create a date sortable column; I'm using this: > > if type(y)==QDateTime: > item=QTableWidgetItem() > item.setData(Qt.DisplayRole,QVariant(y)) This should work fine. > BUT.. I'm adding 90 dates going back from today and getting values > that look like this: > > 27/01/2007 00:12 > 28/01/2007 00:12 > 29/01/2007 00:12 > 30/01/2007 00:12 > 31/01/2007 00:12 > 01/01/2008 00:01 > 01/01/2008 00:02 > 01/01/2008 00:03 > > etc Right. You can see the date and time because you're using a QDateTime object. > I tried using QDate but couldn't seem to be able to get > QDate.fromString to create an object at all. This may have something to do with the format string you tried. > Could someone please advise where I'm going wrong, the end result > should be a column in my QTableWidget formatted dd/mm/yyyy that can be > sorted as dates, not strings, and originate from data formatted > "YYYYMMDD" Just use QDate objects instead of QDateTime objects and it should all just work. Good luck! David -- David Boddie Lead Technical Writer, Trolltech ASA From paul.nospam at rudin.co.uk Thu Mar 13 04:54:43 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 13 Mar 2008 08:54:43 +0000 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: <87skyvuhpo.fsf@rudin.co.uk> Antoon Pardon writes: > On 2008-02-28, Steven D'Aprano wrote: >> On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: >> >>> Hi! >>> Can somebody of you make me a sample how to define a function based on >>> "call by reference" ??? >> >> Python doesn't do call by reference. Nor does it do call by value. Please >> pay no attention to anyone who says it does. > > Whatever python has for a calling convention, it is close enough that > naming it "call by reference" gives people a reasonable idea of what > is going on. Quite. The thing is not to get hung up with the label - but to understand what actually happens. From mblume at freesurf.ch Tue Mar 18 12:53:55 2008 From: mblume at freesurf.ch (Martin Blume) Date: Tue, 18 Mar 2008 17:53:55 +0100 Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com><47dd579d$0$9035$5402220f@news.sunrise.ch><3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com><47dd5caf$0$9029$5402220f@news.sunrise.ch> <646judF2ao2tkU1@mid.uni-berlin.de> Message-ID: <47dff3a3$0$9030$5402220f@news.sunrise.ch> "Marc 'BlackJack' Rintsch" schrieb > > > I don't think this qualifies as a bug, but I am astonished > > that the struct module does not tell you whether you are > > big endian, you have to find out yourself with > > struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] > > Maybe a little more compact and readable: > > In [92]: sys.byteorder > Out[92]: 'little' > Yes, indeed it is more compact and readable. Thanks. Martin From testone at gmail.com Mon Mar 24 19:32:24 2008 From: testone at gmail.com (Tess) Date: Mon, 24 Mar 2008 16:32:24 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question Message-ID: Hello All, I have a Beautiful Soup question and I'd appreciate any guidance the forum can provide. Let's say I have a file that looks at file.html pasted below. My goal is to extract all elements where the following is true:

and

. The lines should be ordered in the same order as they appear in the file - therefore the output file would look like output.txt below. I experimented with something similar to this code: for i in soup.findAll('p', align="left"): print i for i in soup.findAll('p', align="center"): print i I get something like this:

P4

P3

P1

div4b
div3b
div2b
div2a
Any guidance would be greatly appreciated. Best, Ira ##########begin: file.html############

P1

P2

div2a
div2b

P3

div3a
div3b
div3c

P4

div4a
div4b
##########end: file.html############ ===================begin: output.txt===================

P1

div2a
div2b

P3

div3b

P4

div4b
===================end: output.txt=================== From bj_666 at gmx.net Mon Mar 3 01:55:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Mar 2008 06:55:35 GMT Subject: Is it possible to return a variable and use it...? References: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> Message-ID: <631ln7F25g4d2U2@mid.uni-berlin.de> On Sun, 02 Mar 2008 20:15:10 -0800, Nathan Pinno wrote: > Hello all, > > Is it possible to return a variable and then use it like the > following: > [code] > dir exp_1: > while hen != "*" > sum = sum + hen > return sum > > dir exp_2: > if sum >= total_needed: > print "Profit can be made." > else: > print "Expect a loss." > > total_needed = int(raw_input("What is the total eggs needed? ")) > hen = int(raw_input("How many eggs did each hen lay? Enter them in 1 > by 1 or enter * when done. ")) > exp_1 > exp_2 > > [/code] > > If not, then how do I do so? Please work through the tutorial, then try to write actual Python code and come back if you have problems with your implementation of the program. Show us the real code and a description of either what error message you get, with full traceback, or if it does not raise an exception but just does not what you excpect it to do, tell us what you expected and what you get instead. Ciao, Marc 'BlackJack' Rintsch From aahz at pythoncraft.com Wed Mar 5 10:36:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 5 Mar 2008 07:36:37 -0800 Subject: OT: Failed saving throw Message-ID: For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people think we should build a tomb in his honor. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From spamspam at spam.eggs Sun Mar 23 06:38:07 2008 From: spamspam at spam.eggs (Ben C) Date: Sun, 23 Mar 2008 05:38:07 -0500 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> Message-ID: On 2008-03-22, bsoist wrote: > On Mar 22, 12:40 pm, jmDesktop wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. >> >> Thank you. > > Absolutely. I love using Python in "the real world" but it is > fantastic for beginning programmers. > > Python enforces good habits and presents many opportunities to discuss > programming from an academic perspective. Why does Python not have a > switch or until statement? Why doesn't it? > Why are very common objects (stack, queue, > linked list) not builtin? etc. I think I know this one: you just use builtin lists to do stacks, queues and, er, lists. From Graham.Dumpleton at gmail.com Tue Mar 18 21:26:37 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 18 Mar 2008 18:26:37 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> Message-ID: <7900f1db-16a5-45d1-ada3-962ac0e712b8@e6g2000prf.googlegroups.com> On Mar 19, 9:47 am, geert wrote: > On Mar 18, 6:56 pm, geert wrote: > > > > > On Mar 14, 1:15 pm, martin.lal... at gmail.com wrote: > > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > > Just wanted to let you know that I've solved my problem. The solution > > is to compile mysql using > > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > ./configure --disable-dependency-tracking --enable-thread-safe-client > > --prefix=/usr/local/mysql > > > You then go this way to get it running on your machine: > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > > Then reinstall MySQLdb. Magic! > > > Geert > > Seems that I've yelled success to quickly. Everything's ok as long as > I just run the django dev server, but moving to apache throughmod_wsgibrings a well-known but less than comforting complaint: > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352): > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ > LN/LNApache.wsgi'., referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent > call last):, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in > __call__, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > self.get_response(request), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in > get_response, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > middleware_method(request), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line > 13, in process_request, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine = > __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line > 2, in , referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from > django.contrib.sessions.models import Session, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, > in , referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db > import models, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/db/__init__.py", line 17, in , > referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend = > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, > {}, ['']), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, > in , referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no > suitable image found. Did find:, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- > tmp/_mysql.so: no matching architecture in universal wrapper, referer:http://localhost/images/ Did you again confirm that running: file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5- macosx-10.5-i386.egg-tmp/_mysql.so shows the .so having the required architectures, specifically what Apache runs as (eg. x86_64)? Do the gcc compiler flags when building and linking the .so file show all the architecture flags? Have you empty the Python egg cache to make sure it isn't an older compiled version? Graham From tmp1 at viltersten.com Sat Mar 1 19:43:05 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 01:43:05 +0100 Subject: SV: Where's GUI for Python? In-Reply-To: <13sjn6gn3houdaa@corp.supernews.com> References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> Message-ID: <62uai0F24sc4aU1@mid.individual.net> >> import tkininter >> > When that fails, try without the stutter > > import tkinter I must be doing something wrong because neither tkinter nor tkininter works. I tried both with and without stuttering. I even asked my wife to stutter some but, sadly, to no avail. When Tim Chase mentioned "battery-installed", i interpreted it as "all is there". It seems that either a) not all the batteries are installed in my version (v2.5.2) or b) some setup/linkage needs to be performed in order to get the GUI running. The error itself is: ImportError: No module named tkinter Suggestions? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From danb_83 at yahoo.com Wed Mar 5 21:35:12 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 5 Mar 2008 18:35:12 -0800 (PST) Subject: Why """, not '''? References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> Message-ID: <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> On Mar 5, 7:24 pm, Matt Nordhoff wrote: > Steven D'Aprano wrote: > > Surely it would depend on the type of text: pick up any random English > > novel containing dialogue, and you're likely to find a couple of dozen > > pairs of quotation marks per page, against a few apostrophes. > > That's an idea... Write a novel in Python docstrings. Or better yet, write in Python syntax. assert len([man for man in now_alive() if man.remembers(datetime.date(1775, 4, 18))]) <= HARDLY lantern_count = {'land': 1, 'sea': 2}.get(british.location(), 0) n_ch_twr.hang(Lantern() for _ in xrange(lantern_count)) if lantern_count: for village in middlesex: ride_thru(village) spread_alarm(village) From vedrandekovic at gmail.com Thu Mar 27 05:00:26 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Thu, 27 Mar 2008 02:00:26 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: On 26 o?u, 20:11, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 15:38:16 -0300, Tzury Bar Yochay > escribi?: > > >> ....and then when my application execute code how can I set path to > >> d3dx module to "library.zip/d3dx.py". > >> I'm not sure is this properly set question. > > > use the module zipimport > >http://docs.python.org/lib/module-zipimport.html > > You don't have to do anything special to "use" zipimport; from > : > "It is usually not needed to use the zipimport module explicitly; it is > automatically used by the builtin import mechanism" > > -- > Gabriel Genellina Hello, I was add this into my application code: import sys import os my_dir=os.getcwd() sys.path.append(my_dir) sys.path.append(my_dir+"\\libary.zip") sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder f=open("path.txt","w") f.write(str(sys.path)) f.close() an the output in path.txt is : ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ \libary.zip\\py2exe'] But it still can't find module py2exe.What should I do now? Any examples? Regards, Vedran From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 26 06:19:49 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Mar 2008 11:19:49 +0100 Subject: Beta testers needed for a high performance Python application server In-Reply-To: References: Message-ID: <47ea233f$0$31890$426a34cc@news.free.fr> Minor Gordon a ?crit : (snip otherwise intersting stuff) > Background: I'm in this to help write a "story" for Python and web > applications. Everyone likes to go on about Ruby on Rails, and as far as > I can tell there's nothing that approaches Rails in Python. You may have missed Django and Pylons then. > Beta testers: should be intermediate to advanced Python programmers with > demanding applications, particularly web applications with databases and > AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory > libraries beyond python-dev. > > Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. I can only second Graham here: setup a project page with source code downloads, install instructions and (at least minimal) software documentation, and if possible a tracker. From arulprakash012 at gmail.com Mon Mar 17 08:30:09 2008 From: arulprakash012 at gmail.com (arulprakash012 at gmail.com) Date: Mon, 17 Mar 2008 05:30:09 -0700 (PDT) Subject: I WANT YOU Message-ID: <42707e88-2c0e-4135-a562-1da85420145d@i29g2000prf.googlegroups.com> I WANT YOU I LIKE YOU PLEASE CLICH THIS: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ http://myprofile3210.blogspot.com $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ From shakefu at gmail.com Fri Mar 7 17:22:07 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:22:07 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: On Mar 7, 4:10 pm, Mike Driscoll wrote: > On Mar 7, 4:08 pm, shak... at gmail.com wrote: > > > I'm new to python and I was wondering if there are any intelligent > > date/time parsing modules out there. I've looked at strptime (or > > whichever it is) and mxDateTime from the eGenix package. I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > > So are there any modules that allow for that kind of parsing? > > There's the dateutil module that's a fancy wrapper for the datetime > module. The author's site has lots of examples as well as the source: > > http://labix.org/python-dateutil > > I use it quite a bit. > > HTH > > Mike So close - I tried it in the interpreter it works great for most things (like "10pm tuesday") but I'm really hoping for something that'll work with generics like "tomorrow", "yesterday", "last tuesday", "next month", etc. Although I know that's pretty language specific. I was just sort of wishing someone had written it before me... maybe? Possibly? Although if I end up writing my own I'll sure use datetime.parser.parse to get everything left over once you remove strings like "this saturday". So it helps a little! Jacob From castironpi at gmail.com Tue Mar 4 21:30:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 18:30:26 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: On Mar 4, 8:11?pm, "Gabriel Genellina" wrote: > En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: > > >> > So, to answer your question: what you are decorating are functions, ? > >> not > >> > methods. > > >> Can you overload -type-'s decision of what to 'bind'?... whenever it > >> is it makes it. > > >>>> from types import FunctionType, MethodType > >>>> class A( FunctionType ): pass > > ... > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: type 'function' is not an acceptable base type > > Use delegation instead of inheritance. This class is almost ? > indistinguishable from a true function (when used as a method): > > py> class myfunction(object): > ... ? __slots__ = ('func',) > ... ? # > ... ? def __init__(self, func): > ... ? ? object.__setattr__(self, 'func', func) > ... ? # > ... ? def __get__(self, instance, owner): > ... ? ? print "__get__ called for",instance > ... ? ? return self.func.__get__(instance, owner) > ... ? # > ... ? def __getattr__(self, name): > ... ? ? return getattr(self.func, name) > ... ? # > ... ? def __setattr__(self, name, value): > ... ? ? object.__setattr__(self.func, name, value) > ... > py> > py> class P(object): > ... ? def foo(self, x): print 'foo',x > ... ? # > ... ? @myfunction > ... ? def bar(self, x): print 'bar',x > ... > py> p = P() > py> p.foo(1) > foo 1 > py> p.bar(2) > __get__ called for <__main__.P object at 0x00A3D650> > bar 2 > py> P.foo(p, 1) > foo 1 > py> P.bar(p, 2) > __get__ called for None > bar 2 > py> print "p.foo", p.foo, type(p.foo) > p.foo > 'instancem > ethod'> > py> print "p.bar", p.bar, type(p.bar) > p.bar __get__ called for <__main__.P object at 0x00A3D650> > > __get__ called ? > for <__ > main__.P object at 0x00A3D650> > > py> print set(dir(p.foo))==set(dir(p.bar)) > __get__ called for <__main__.P object at 0x00A3D650> > True > py> print "P.foo", P.foo, type(P.foo) > P.foo > py> print "P.bar", P.bar, type(P.bar) > P.bar __get__ called for None > __get__ called for None > > py> print set(dir(P.foo))==set(dir(P.bar)) > __get__ called for None > True > py> P.__dict__['foo'] > > py> P.__dict__['bar'] > <__main__.myfunction object at 0x00A3D690> > > Ok, let's try returning a different thing from __get__: bound method -> ? > partial with self already bound; unbound method -> the original function. > > py> from functools import partial > py> > py> class myfunction2(myfunction): > ... ? def __get__(self, instance, owner): > ... ? ? if instance is None: > ... ? ? ? ? return self.func > ... ? ? return partial(self.func, instance) > ... > py> @myfunction2 > ... def baz(self, x): print 'baz',x > ... > py> P.baz = baz > py> print p.baz > > py> print P.baz > > py> p.baz(3) > baz 3 > py> P.baz(p,3) > baz 3 > > -- > Gabriel Genellina I actually don't believe you-- bar is not bound to an instance when P is initialized... er, instantiated. However, the evidence indicates my belief mechanism is faulty... and rather conclusively at that. If P calls __get__( you ), is p a gotcha? From kyosohma at gmail.com Mon Mar 31 13:18:06 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 10:18:06 -0700 (PDT) Subject: Automatically fill in forms on line References: Message-ID: On Mar 31, 11:50 am, "Jackie Wang" wrote: > Dear all, > > I want to automatically complete the following task: > > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx; > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > Highway 102"; > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > 4. Click the bottom "search"; > 5. In the opened page, extract and save the number after "Tract Code". > In the example, it will be "9659". > 6. Repeat Step 1 with a new address. > > Can Python realize these steps? Can these steps be done witout > openning and IE windows? Especially, I dont know how to write code for > step 2, 4 and 5. > > Thank you! You might take a look at PAMIE: http://pamie.sourceforge.net/ or ClientForm: http://wwwsearch.sourceforge.net/ClientForm/ Those are what are usually recommended. Mike From coolman.guron at gmail.com Tue Mar 11 10:24:52 2008 From: coolman.guron at gmail.com (binaryj) Date: Tue, 11 Mar 2008 07:24:52 -0700 (PDT) Subject: how to theme/skin pyGtk apps Message-ID: hi again dear group. what i am interested in is giving my pygtk app some distinct look, a lil childish look coz the app is for children. so, i downloaded a couple of themes from http://art.gnome.org/themes/gtk2/ and for the past 1 hr i have been trying to theme my app but with no results. could anyone please guide me on who to theme pygtk and code samples would be greatly appreciated thanks binary-j From jkugler at bigfoot.com Wed Mar 26 18:03:11 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 26 Mar 2008 14:03:11 -0800 Subject: Not understanding lamdas and scoping References: Message-ID: George Sakkis wrote: > On Mar 26, 5:02 pm, Joshua Kugler wrote: > >> I am trying to use lamdba to generate some functions, and it is not >> working >> the way I'd expect. The code is below, followed by the results I'm >> getting. More comments below that. >> >> (...) >> >> So, is there some scoping issue with lambda >> that I'm not seeing? > > Yes; it's not related to lambda though but to closures (whether > defined as lambdas or regular functions). See for example > http://groups.google.com/group/comp.lang.python/browse_frm/thread/94d1bba8ad56baf4 > > There should be an entry for this at > http://www.python.org/doc/faq/programming/, that's really an FAQ. George - Thanks for the quick and clear answer...that makes perfect sense. To bad...I'd like to just use a list comprehension. :) j From castironpi at gmail.com Wed Mar 5 13:50:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 10:50:12 -0800 (PST) Subject: What is a class? Message-ID: What is a class that is not a module? From ACooper at cimtek.com Tue Mar 11 19:33:35 2008 From: ACooper at cimtek.com (Cooper, Andrew) Date: Tue, 11 Mar 2008 19:33:35 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: <21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> <21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: The part I'm having problem with is as follows: I want to replace the 'strcmp' below with a call to PyObject_IsInstance(o, pinClassPyObject) But I don't know how to get the PyObject* for the Pin class that is defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list From: python-list-bounces+acooper=cimtek.com at python.org [mailto:python-list-bounces+acooper=cimtek.com at python.org] On Behalf Of Bronner, Gregory Sent: 11 March 2008 20:52 To: Michael Wieher; python-list at python.org; accooper at cimtek.com Subject: RE: Obtaining the PyObject * of a class I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list at python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mithrandi at mithrandi.net Thu Mar 27 23:15:02 2008 From: mithrandi at mithrandi.net (Tristan Seligmann) Date: Fri, 28 Mar 2008 05:15:02 +0200 Subject: [Twisted-web] [ANN] Twisted 8.0 In-Reply-To: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> References: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> Message-ID: <20080328031502.GA22852@mithrandi.net> * Christopher Armstrong [2008-03-26 21:26:11 -0400]: > http://twistedmatrix.com/ > > MASSACHUSETTS (DP) -- Version 8.0 of the Twisted networking framework > has been released, Twisted Matrix Laboratories announced Wednesday. I just have to say that I enjoyed reading this release mail far more than any other one I can recall :) -- mithrandi, i Ainil en-Balandor, a faer Ambar -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From gh at ghaering.de Thu Mar 13 18:03:08 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 13 Mar 2008 23:03:08 +0100 Subject: [pysqlite] [ANN] pysqlite and APSW projects moved In-Reply-To: <47d8f707$0$26041$88260bb3@free.teranews.com> References: <47d8f707$0$26041$88260bb3@free.teranews.com> Message-ID: <63tmkqF28loi7U1@mid.uni-berlin.de> Colin Mcphail wrote: > On 2008-03-09 18:57:00 +0000, Gerhard H?ring said: > > Gerhard H?ring wrote: >>>> [...] APSW >>>> ==== >>>> >>>> web: http://oss.itsystementwicklung.de/trac/apsw/ >>>> scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ > > That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ > > -- Gerhard > I'm getting 404 Not Found for the 'corrected' apsw web page URL. Also, > the subversion URL doesn't seem right either: > $ svn co http://initd.org/svn/pysqlite/apsw/trunk/ apsw > svn: PROPFIND request failed on '/svn/pysqlite/apsw/trunk' > svn: PROPFIND of '/svn/pysqlite/apsw/trunk': 403 Forbidden > (http://initd.org) Roger Binns changed his mind and moved APSW to Google Code: http://code.google.com/p/apsw/ -- Gerhard From mnordhoff at mattnordhoff.com Wed Mar 5 20:24:10 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 06 Mar 2008 01:24:10 +0000 Subject: [OT] Re: Why """, not '''? In-Reply-To: <13sudd49au3e1c1@corp.supernews.com> References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> Message-ID: <47CF47BA.8030405@mattnordhoff.com> Steven D'Aprano wrote: > Surely it would depend on the type of text: pick up any random English > novel containing dialogue, and you're likely to find a couple of dozen > pairs of quotation marks per page, against a few apostrophes. That's an idea... Write a novel in Python docstrings. Someone make me go to bed now. -- From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 04:14:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Mar 2008 08:14:49 -0000 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> Message-ID: <13uc4bpb0b564af@corp.supernews.com> On Sat, 22 Mar 2008 23:15:00 -0700, John Nagle wrote: > That's some professor inventing his very own variation on predicate > calculus and writing a book using his own notation and terminology. > There's no sign of footnotes or references to prior work. The notation > doesn't seem to do anything not previously possible; it's just > different. You say that as if it were unusual in maths circles :) -- Steven From NoelByron at gmx.net Tue Mar 11 04:45:24 2008 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: Tue, 11 Mar 2008 01:45:24 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: Hi Malcom On Mar 10, 4:27?pm, "Malcolm Greene" wrote: > I'm new to Python and getting ready to build a small client based > application intended to run on Windows and Linux. I was planning on > using wxPython until I saw your comment above. We use wxPython and Python internally in the company without any mayor problems or crashes. It seems quite solid. But errors happen in complex systems. And if for example a crash occurs it would be good to know the reason and to track it down. And that is hard in Python with C extensions. That does not only apply to wxPython but to all other (GUI) libraries with C parts, too. At least we will not switch to something else then wxPython. Best regards, Noel From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 13:22:11 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 18:22:11 +0100 Subject: And the reverse? Does os also import os.path? In-Reply-To: References: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> Message-ID: <47ebd7b4$0$19836$426a74cc@news.free.fr> Wilbert Berendsen a ?crit : > If i do > >>>> import os >>>> os.path.abspath("bla") > '/home/wilbert/bla' > > it seems that just import os also makes available al os.path functions. > > But is that always true? Nope. Not all packages expose their sub-packages. From jef.mangelschots at gmail.com Tue Mar 4 16:12:18 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 4 Mar 2008 13:12:18 -0800 (PST) Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> <3319005c-98b9-44a0-96dc-72db45f2ae27@z17g2000hsg.googlegroups.com> Message-ID: > on windows using python 2.4. ??? yes, as a matter of fact I am. Did not feel the need to switch to 2.5 yet. I'm gonna give this a try, but it requires me to dig up 2.5 versions of the libraries i am using. (one of them didn't at the time and that is why I stuck to 2.4) From phil at riverbankcomputing.com Sun Mar 30 05:08:06 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sun, 30 Mar 2008 09:08:06 +0000 Subject: Using QSystemTrayIcon with PyQt In-Reply-To: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: <200803301008.06482.phil@riverbankcomputing.com> On Sunday 30 March 2008, Alex Teiche wrote: > Hello, > > I am pretty new to Python, and have never learned C++. I am trying to > implement the following thing into my python application: > > http://doc.trolltech.com/4.3/qsystemtrayicon.html > > Through PyQt. I have been using PyQt for awhile and I know how do use > it, but I could not get this specific thing to work. Can someone give > me some hints as to get it working in Python? > > Thanks a ton, > > Alex Have you looked at PyQt's systray example? Phil From software at ginstrom.com Tue Mar 18 06:24:50 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 18 Mar 2008 19:24:50 +0900 Subject: Decode email subjects into unicode In-Reply-To: <47DF8EED.1010501@shopzeus.com> References: <47DF8EED.1010501@shopzeus.com> Message-ID: <017d01c888e2$4cfc9ff0$0203a8c0@MOUSE> > On Behalf Of Laszlo Nagy > > =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?= > > [Fwd: re:Flags Of The World, Us States, And Military] > > =?ISO-8859-2?Q?=E9rdekes?= =?UTF-8?B?aGliw6Fr?= Try this code: from email.header import decode_header def getheader(header_text, default="ascii"): """Decode the specified header""" headers = decode_header(header_text) header_sections = [unicode(text, charset or default) for text, charset in headers] return u"".join(header_sections) I get the following output for your strings: ??????????????? ? ???????????? ?rdekeshib?k Regards, Ryan Ginstrom From blwatson at gmail.com Fri Mar 28 15:14:07 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Fri, 28 Mar 2008 12:14:07 -0700 (PDT) Subject: Installing simplejson issues Message-ID: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> I am trying to install the twitter python wrapper...I got that installed just fine, but am having serious troubles getting the simplejson package to install. I need help diagnosing where this is failing. I am trying to use: http://pypi.python.org/pypi/simplejson and I run "python setup.py build" and then "python setup.py install", which both seem to work just fine. I tried running with easy_install, but that too is not working. I end up with: simplejson-1.8.1-py2.5-macosx-10.3-fat.egg in my: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/ I am on Mac OS X 10.5. Any help would be greatly appreciated. From bockman at virgilio.it Wed Mar 5 03:41:56 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 5 Mar 2008 00:41:56 -0800 (PST) Subject: Protocol for thread communication References: Message-ID: <688d6185-eef0-41c5-8e03-042d86b87615@u72g2000hsf.googlegroups.com> On 5 Mar, 06:12, Michael Torrie wrote: > Does anyone have any recommended ideas/ways of implementing a proper > control and status protocol for communicating with threads? ?I have a > program that spawns a few worker threads, and I'd like a good, clean way > of communicating the status of these threads back to the main thread. > Each thread (wrapped in a very simple class) has only a few states, and > progress levels in those states. ?And sometimes they can error out, > although if the main thread knew about it, it could ask the thread to > retry (start over). ?How would any of you do this? ?A callback method > that the thread can call (synchronizing one-way variables isn't a > problem)? ?A queue? ?How would the main thread check these things? > Currently the main thread is polling some simple status variables. ?This > works, and polling will likely continue to be the simplest and easiest > way, but simple status variables are very limited. ?Are there any > pythonic patterns people have developed for this. > > thanks. > > Michael I've found that Queue.Queue objects are the easiest way to communicate between threads in Python. So, I'd suggets that you attach a Queue to each thread: the main thread will use its queue to receive the status messages from the other threads; the other threads will use their queues to receive the retry command (or any other command that may be needed) from the main thread. Ciao ------ FB From monica.leko at gmail.com Mon Mar 3 10:32:33 2008 From: monica.leko at gmail.com (Monica Leko) Date: Mon, 3 Mar 2008 07:32:33 -0800 (PST) Subject: Exception or not Message-ID: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Suppose you have some HTML forms which you would like to validate. Every field can have different errors. For example, this are the forms: username password etc And you want to validate them with some class. Is this good pattern: class Foo(object): def validateUsername(username): if username isn't correct: raise ValidationError() def validatePassword(password): if password isn't correct: raise ValidationError() code: try: usernameError = validateUsername() except ValidationError: usernameError = error from exception try: passwordError = validatePassword() except ValidationError: passwordError = error from exception So, if there wasn't any errors, usernameError and passwordError both contains None, and there was error, both contains some string? Should I use exception or just return None or some string without exception? From gagsl-py2 at yahoo.com.ar Tue Mar 18 01:47:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 22:47:08 -0700 (PDT) Subject: ctypes in python failed to honor c_int References: Message-ID: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> On 17 mar, 23:57, Jerry Fleming wrote: > I have a binary file written with c structures. Each record contains a > null-terminated string followed by two 4-bytes integers. I wrote a small > segment of python code to parse this file in this way: > [coe] > #!/usr/bin/python > > from ctypes import * > > class Entry(Structure): > ? ? ? ? _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) > > idx = open('x.idx', 'rb') > str = idx.read(1000) > obj = Entry(str) > print obj.w > print obj.s > print obj.l > [/code] > where the field w is the string, and s and l are the integers. Problem > is that, I can only get the strings, not the integers. Well, I did got > integers, but they are all zeros. What should I do to get the real numbers? So the string has a variable length? For "Hello" you have 'h','e','l','l','o', a zero byte, followed by the two integers? This is somewhat unusual for a C struct (in fact you can't declare it in C). Perhaps the string is actually a char[n] array with a declared maximum size? Try printing repr(a_few_read_bytes) or a_few_read_bytes.encode("hex") to see the actual file contents. -- Gabriel Genellina From abbas4u at gmail.com Sun Mar 30 18:59:14 2008 From: abbas4u at gmail.com (Fish) Date: Sun, 30 Mar 2008 15:59:14 -0700 (PDT) Subject: Creating Class Objects in Loop Message-ID: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> Hello Folks, I am reading a CSV file and based on that I am creating TestCase(my own defined class) objects in a for loop. The problem is each time I create a new TestCase object in loop, previous objects data is already copied in that object. e.g. my sample CSV file is # ------------------------- hello.pcap, 123, 231 test.pcap, 90, 899 hello2.pcap, 81, 18 # ----------------------- When I print the TestCase elements from returned list I get (Pdb) print tcLstOrig[0] Pcap Path: hello.pcap Sid List: 123, 231, 90, 899, 81, 18, (Pdb) print tcLstOrig[1] Pcap Path: test.pcap Sid List: 123, 231, 90, 899, 81, 18, (Pdb) print tcLstOrig[2] Pcap Path: hello2.pcap Sid List: 123, 231, 90, 899, 81, 18, Kindly guys advise me on this thing. Function snippet and Class definition are provided below. Regards, Fish ======= Problem Code The function snippet reading CSV and creating TestCase objects is [code] tcLst = [] # CSV file is read in variable 'lines' def returnTcLst(path): fp = open(path) lines = fp.readlines() for line in lines: tc = TestCase() i = line.find(",") tc.setPcap(line[:i].strip()) line = line[i+1:] line = line + "," i = line.find(",") while i != -1: sid = line[:i].strip() tc.appendSid(sid) line = line[i+1:] i = line.find(",") tcLst.append(tc) del tc return tcLst [/code] My TestCase Class is defined as [code] class TestCase(object): def __init__(self, pcap = None, sids = []): self.__Pcap = pcap self.__lstSid = sids def setPcap(self, path): self.__Pcap = path def appendSid(self, sid): self.__lstSid.append(sid) def __str__(self): text = "Pcap Path: " + self.__Pcap + "\n" text += "Sid List: " for sid in self.__lstSid: text += sid + ", " text += "\n" return text [/code] From moonrie at gmail.com Thu Mar 13 04:45:04 2008 From: moonrie at gmail.com (moonrie) Date: Thu, 13 Mar 2008 01:45:04 -0700 (PDT) Subject: help please, splitter windows like in maya or 3ds max References: Message-ID: <1dab98f7-7a29-4afb-b9ef-9728d133697d@s13g2000prd.googlegroups.com> On Mar 13, 12:47 pm, "Andrew Rekdal" <@comcast.net> wrote: > This seems to work... split then split each side. then tandem the size. > > import wx > > class Layout(wx.Frame): > > def __init__(self, parent, id, title): > > wx.Frame.__init__(self, parent, id, title) > > sizer = wx.BoxSizer(wx.HORIZONTAL) > > panel = wx.Panel(self,-1) > > splitter = wx.SplitterWindow(panel) > > sizer_left = wx.BoxSizer(wx.VERTICAL) > > panel_left = wx.Panel(splitter,-1) > > splitter_left = wx.SplitterWindow(panel_left) > > splitter_left.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.leftChange,id=splitter_left.GetId()) > > panel_left_upper = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > panel_left_upper.SetBackgroundColour("WHITE") > > panel_left_lower = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > splitter_left.SplitHorizontally(panel_left_upper,panel_left_lower) > > sizer_left.Add(splitter_left,1,wx.EXPAND) > > sizer_right = wx.BoxSizer(wx.VERTICAL) > > panel_right = wx.Panel(splitter,-1) > > splitter_right =wx.SplitterWindow(panel_right) > > splitter_right.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.rightChange,id=splitter_right.GetId()) > > panel_right_upper = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > panel_right_lower = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > panel_right_lower.SetBackgroundColour("WHITE") > > splitter_right.SplitHorizontally(panel_right_upper,panel_right_lower) > > sizer_right.Add(splitter_right,1,wx.EXPAND) > > splitter.SplitVertically(panel_left,panel_right) > > sizer.Add(splitter,1,wx.EXPAND) > > panel.SetSizer(sizer) > > panel_left.SetSizer(sizer_left) > > panel_right.SetSizer(sizer_right) > > self.splitter_left = splitter_left > > self.splitter_right = splitter_right > > def leftChange(self,event): > > pos = self.splitter_left.GetSashPosition() > > self.splitter_right.SetSashPosition(pos) > > event.Skip() > > def rightChange(self,event): > > pos = self.splitter_right.GetSashPosition() > > self.splitter_left.SetSashPosition(pos) > > event.Skip() > > app = wx.App(0) > > k = Layout(None, -1, 'layout.py') > > k.Show(True) > > app.MainLoop() > > -- Andrew > > ----- Original Message ----- > From: "moonrie" > > Newsgroups: comp.lang.python > Sent: Wednesday, March 12, 2008 10:19 PM > Subject: help please, splitter windows like in maya or 3ds max > > > hi, everyone there, I am doing a 3D modeling project. I like to do it > > with Python( am a newbie), but have no idea with the wxSplitterWindow > > to create the 4-view windows( top, front, side, perspective), like the > > mfc CSplitterWnd guy), > > anyone can give me some help with wxPython? > > > thanks in advance. > > > - moonrie should be these ones, thanks, :P From duncan.booth at invalid.invalid Tue Mar 18 17:34:44 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2008 21:34:44 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> Message-ID: castironpi at gmail.com wrote: >> > > On Mar 17, 1:31 pm, Duncan Booth >> > > wrote: >> >> > >> A common explanation for this is that lists are for homogenous >> > >> collections, tuples are for when you have heterogenous >> > >> collections i.e. related but different things. >> >> > > I interpret this as meaning that in a data table, I should have a >> > > list of records but each record should be a tuple of fields, >> > > since the fields for a table usually have different forms whereas >> > > the records usually all have the same record layout. >> >> >>> b in b >> False > > That's actually interesting. Just for the avoidance of doubt, I didn't write the 'b in b' line: castironpi is replying to himself without attribution. P.S. I still don't see the relevance of any of castironpi's followup to my post, but since none it made any sense to me I guess it doesn't matter. From willsteve2003 at yahoo.ca Mon Mar 10 11:24:30 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:24:30 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> Message-ID: <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> On Mar 7, 6:12?pm, John Machin wrote: > On Mar 8, 1:53 am, "hvendelbo.... at googlemail.com" > > > > > > wrote: > > On Mar 6, 9:17 pm, Luis M. Gonz?lez wrote: > > > > On 6 mar, 11:27, Pierre Quentel wrote: > > > > > Hi, > > > > > I would like to know if there is a module that converts a string to a > > > > value of the "most probable type" ; for instance : > > > > - if the string is "abcd" the value is the same string "abcd" > > > > - string "123" : value = the integer 123 > > > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > > > = the float -1.23 > > > > - string "2008/03/06" (the format is also locale-dependant) : value = > > > > datetime.date(2008,03,06) > > > > > Like in spreadsheets, special prefixes could be used to force the > > > > type : for instance '123 would be converted to the *string* "123" > > > > instead of the *integer* 123 > > > > > I could code it myself, but this wheel is probably already invented > > > > > Regards, > > > > Pierre > > > >>> def convert(x): > > > > ? ? ? ? if '.' in x: > > > ? ? ? ? ? ? ? ? try: return float(x) > > > ? ? ? ? ? ? ? ? except ValueError: return x > > > ? ? ? ? else: > > > ? ? ? ? ? ? ? ? try: return int(x) > > > ? ? ? ? ? ? ? ? except: return x > > > > >>> convert('123') > > > 123 > > > >>> convert('123.99') > > > 123.98999999999999 > > > >>> convert('hello') > > > > 'hello' > > > Neat solution. The real challenge though is whether to support > > localised dates, these are all valid: > > 20/10/01 > > 102001 > > 20-10-2001 > > 20011020 > > Neat solution doesn't handle the case of using dots as date separators > e.g. 20.10.01 [they are used in dates in some locales and ?the > location of . on the numeric keypad is easier on the pinkies than / or > -] > > I'm a bit dubious about the utility of "most likely format" for ONE > input. > > I've used a brute-force approach when inspecting largish CSV files > (with a low but non-zero rate of typos etc) with the goal of > determining what is the most likely type of data in each column. > E.g 102001 could be a valid MMDDYY date, but not a valid DDMMYY or > YYMMDD date. 121212 could be all of those. Both qualify as int, float > and text. A column with 100% of entries qualifying as text, 99.999% as > float, 99.99% as integer, 99.9% as DDMMYY, and much lower percentages > as MMDDYY and YYMMDD would be tagged as DDMMYY. The general rule is: > pick the type whose priority is highest and whose score exceeds a > threshold. Priorities: date > int > float > text. Finding the date > order works well with things like date of birth where there is a wide > distribution of days and years. However a field (e.g. date interest > credited to bank account) where the day is always 01 and the year is > in 01 to 08 would give the same scores for each of 3 date orders ... > eye-balling the actual data never goes astray.- Hide quoted text - > > - Show quoted text - In the case where dots are used as a date separator, count the number of dots (you should also count commas). If a single comma appears and is preceeded by only numbers or numbers with decimals, assume "foreign float". If a single decimal appears and is preceeded by only numbers or numbers with commas, assume "float". If 2 decimals appear and each field is 2 or less characters in length and numeric, assume date. If 2 decimals appear and the first 2 fields are 2 or less characters in length and numeric and the last field is 4 characters in length and numeric, assume date. There are things you can do, but you must be wary of the fact that it may not always be 100% perfect. From castironpi at gmail.com Fri Mar 7 16:15:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 13:15:04 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: <08448e76-e029-4b51-ad7b-4f2d0297dea0@e31g2000hse.googlegroups.com> On Mar 7, 10:12?am, alex.pedwyso... at gmail.com wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... import sys from time import clock, sleep from threading import Timer TimeoutError= type('TimeoutError',(Exception,),{}) class Elapse: def __init__( self ): self.flag= False def set( self ): self.flag= True def tr( frame, event, arg ): if elapse.flag: raise TimeoutError return tr def sleeper(): while 1: sleep( .3 ) print( 'tick' ) def factercomp( n ): val= 1 for i in range( 1, n ): val*= i return val def facter( n ): print( factercomp( n ) ) def runit( f, *ar ): global elapse elapse= Elapse() t= Timer( 1, elapse.set ) t.start() sys.settrace( tr ) try: f( *ar ) except TimeoutError: print( 'time elapse' ) runit( sleeper ) runit( facter, 10 ) runit( facter, 20 ) runit( facter, 10000 ) runit( facter, 100000 ) ''' tick tick tick time elapse 362880 121645100408832000 time elapse time elapse ''' From simon at brunningonline.net Wed Mar 19 10:46:56 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 Mar 2008 14:46:56 +0000 Subject: changing names of items in a list In-Reply-To: References: Message-ID: <8c7f10c60803190746w5f487187ia0fca001d9c443b3@mail.gmail.com> On Wed, Mar 19, 2008 at 2:21 PM, royG wrote: > hi > i am trying to rename extension of files in a directory..as an initial > step i made a method in > > class ConvertFiles: > def __init__(self,infldr,outfldr): > self.infldr=infldr > self.outfldr=outfldr > self.origlist=os.listdir(infldr) > .... > def renamefiles(self,extn): > for x in self.origlist: > x=x+"."+extn > > ... > > later when i print self.origlist i find that the elements of list are > unchanged..even tho a print x inside the renamefiles() shows that > extn is appended to x .. > why does this happen? Your 'x=' line is building a brand new string, and rebinding the name 'x' to it. It's not doing anything to the original list. See . I'd rewrite that as (untested): def renamefiles(self, extn): self.origlist = list((x + "." + extn) for x in self.origlist) or def renamefiles(self, extn): self.origlist = list(("%s.%s" % (z, extn)) for x in self.origlist) Better still, take a look at the os.path module... -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From grflanagan at gmail.com Tue Mar 4 10:35:36 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 4 Mar 2008 07:35:36 -0800 (PST) Subject: Removing default logging handler (causes duplicate logging) References: Message-ID: <9c5214a1-7634-4249-bc46-061eb45820cd@s19g2000prg.googlegroups.com> On Mar 4, 1:29 pm, Gal Aviel wrote: > Hello All, > > I want to add a logger to my application, then addHandler to it to log to a > special destination. > > Unfortunately when I use logging.getLogger("my_logger") to create the new > logger, it apparently comes with a default handler that logs to STDOUT (or > STDERR?). When I add my special handler it works Ok, but still logs to terminal, > which I do not want. > from docs: ------------------ getLogger( [name]) Return a logger with the specified name or, if no name is specified, return a logger which is the root logger of the hierarchy. ------------------ so you should do 'root = getlogger()', then append your own logger to the root. Gerard From michael at stroeder.com Wed Mar 26 08:58:49 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Mar 2008 13:58:49 +0100 Subject: ANN: python-ldap-2.3.2 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.2 2008-03-26 Changes since 2.3.1: Lib/ * ldap.dn.escape_dn_chars() now really adheres to RFC 4514 section 2.4 by escaping null characters and a space occurring at the beginning of the string * New method ldap.cidict.cidict.__contains__() * ldap.dn.explode_dn() and ldap.dn.explode_rdn() have a new optional key-word argument flags which is passed to ldap.dn.str2dn(). Modules/ * Removed unused OPT_PRIVATE_EXTENSION_BASE from constants.c Doc/ * Various additions, updates, polishing (thanks to James). From miki.tebeka at gmail.com Thu Mar 27 14:17:43 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 11:17:43 -0700 (PDT) Subject: ctypes and gmp Message-ID: <42848b47-9bad-4d4d-b5c7-e524c4e1504e@d21g2000prf.googlegroups.com> Hello All, Playing around with ctypes, I'm try to use gmp (gmpy is excellent but I want to learn ctypes). I'm running: #!/usr/bin/env python from ctypes import * class mpz(Structure): _fields_ = [ ("_mp_alloc", c_int), ("_mp_size", c_int), ("_mp_d", POINTER(c_uint)), ] gmp = cdll.LoadLibrary("libgmp.so") m = mpz() gmp.__gmpz_init(byref(m)) gmp.__gmpz_set_ui(byref(m), 27) gmp.__gmp_printf("m is %d\n", byref(m)) However, the output is: m is -1210863888 Any ideas? (gmp.h can bee view at http://tinyurl.com/yrqen4) Thanks, -- Miki http://pythonwise.blogspot.com From beema.shafreen at gmail.com Wed Mar 19 07:16:52 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Wed, 19 Mar 2008 16:46:52 +0530 Subject: printing dictionary and tuple Message-ID: Hi everbody i am trying to print the dictionary values and tuple in a same line as below print "\t".join(dict[a].values())+'\t'+"\t".join(b) Error I get is the TypeError, since i have misisng values in the dictionary. if i use exception i will miss those how should i print the data without missing the lines excluding the error separated by tab. -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From zerty.david at gmail.com Sun Mar 30 16:29:52 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:29:52 -0300 Subject: Error Raised But dont know what it means In-Reply-To: <5dc598e30803301307g20d9494ekf140387361c31968@mail.gmail.com> References: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> <5dc598e30803301307g20d9494ekf140387361c31968@mail.gmail.com> Message-ID: <5dc598e30803301329j17fa82dw4ec5eb27019174d5@mail.gmail.com> I found the problem Topic closed On Sun, Mar 30, 2008 at 5:07 PM, David Anderson wrote: > Here is the code: > This one raises the error: > def criaLista(self): > self.listbox.Clear() > for dupla in self.duplas: > self.listbox.Append(dupla.__str__()) > > This one works well but doesn't raises error > > dupla1 = Duplas("2422", "2455") > dupla2 = Duplas("454", "15") > list = [] > list.append(dupla1) > list.append(dupla2) > erros = ErrorMgr() > erros.geraErro("1", "erro idiota", 2.2) > dic = {1:dupla1, 2:dupla2} > a = Arquivos("batata.txt") > a.saveFile(list, erros, dic) > a.openFile() > lista = a.getListaDuplas() > e = a.getErrorsManager() > d = a.getDicDuplas() > > for i in lista: > print i > > print d[1] > > > On Sun, Mar 30, 2008 at 5:03 PM, David Anderson > wrote: > > > Well, I'm dealing with files in Pickle, I'm saving at the file a List of > > Objects from the same Class, When I try to retrive this information and try > > to iterate over them this error is raised: > > TypeError: 'instancemethod' object is not iterable > > > > But if I just print the method I get the 'real thing' what's the > > problem? > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rockxuan at gmail.com Tue Mar 18 03:45:32 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:45:32 -0700 (PDT) Subject: Omega Swiss watch in www.51cntrade.com Message-ID: <5401397f-0d8f-46b9-9f4e-e438c90ef583@s8g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From pavlovevidence at gmail.com Fri Mar 14 02:26:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Mar 2008 23:26:28 -0700 (PDT) Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup References: <47d97288$0$36363$742ec2ed@news.sonic.net> <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> <47da10c8$0$36374$742ec2ed@news.sonic.net> Message-ID: <37eb1226-d2db-499e-9ba5-a4d441465451@p25g2000hsf.googlegroups.com> On Mar 14, 1:53 am, John Nagle wrote: > John Machin wrote: > > On Mar 14, 5:38 am, John Nagle wrote: > >> Just noticed, again, that getattr/setattr are ASCII-only, and don't support > >> Unicode. > > >> SGMLlib blows up because of this when faced with a Unicode end tag: > > >> File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag > >> method = getattr(self, 'end_' + tag) > >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' > >> in position 46: ordinal not in range(128) > > >> Should attributes be restricted to ASCII, or is this a bug? > > >> John Nagle > > > Identifiers are restricted -- see section 2.3 (Identifiers and > > keywords) of the Reference Manual. The restriction is in effect that > > they match r'[A-Za-z_][A-Za-z0-9_]*\Z'. Hence if you can't use > > obj.nonASCIIname in your code, it makes sense for the equivalent usage > > in setattr and getattr not to be available. > > > However other than forcing unicode to str, setattr and getattr seem > > not to care what you use: > > OK. It's really a bug in SGMLlib, then. SGMLlib lets you provide a > subclass with a function with a name such as "end_img", to be called > at the end of an "img" tag. The mechanism which implements this blows > up on any tag name that won't convert to "str", even when there are > no "end_" functions that could be relevant. > > It's easy to fix in SGMLlib. It's just necessary to change > > except AttributeError: > to > except AttributeError, UnicodeEncodeError: > > in four places. I suppose I'll have to submit a patch. FWIW, the stated goal of sgmllib is to parse the subset of SGML that HTML uses. There are no non-ascii elements in HTML, so I'm not certain this would be considered a bug in sgmllib. Carl Banks From fakeaddress at nowhere.org Tue Mar 25 06:34:19 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 25 Mar 2008 03:34:19 -0700 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: john s. wrote: > #/usr/bin/enviro python > > #Purpose - a dropped in useracct/pass file is on a new server to build > a cluster... Alas there are no home #directories.. Let me rip through > the passfile, grab the correct field (or build it) and use it to make > the directory! > > import os, sys, string, copy, getopt, linecache > from traceback import format_exception > > #The file we read in... > fileHandle = "/etc/passwd" > srcFile = open(fileHandle,'r') > srcList = srcFile.readlines() > > #yah, a for loop that "iterates" through the file of "lines" > for i in srcList: Convention is that the name i is for an integer. > strUsr = string.split(i,":") > theUsr = strUsr[0] > usrHome = "/expirt/home/",theUsr,"/" > usrHome = ''.join(usrHome) As Ryan noted, os.path is the favored way. > print "printing usrHome:",usrHome > > print "is it a dir?: ", os.path.isdir(usrHome) > > # try to test if it's a dir... for some reason this mis-behaves... > maybe I'm not thinking about it correctly.. > > if os.path.isdir(usrHome) != 'False': That should always evaluate true. False != 'False'. I think you want: if not os.path.exists(usrHome): > print "User Home dir doesn't exist creating." > > try: > os.makedirs('usrHome' ) > except Exception, e: > print e I don't think you want to catch the exception there. If creating the dir fails, the next bits of code should not execute. > print "usrHome is: ",usrHome > print "theUsr is: ",theUsr > > os.system('/usr/bin/chmod 750 ' + usrHome) > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) > > #OMG, there is directory that happens to already exist! well, due > diligence and love for the queen dictates we #provide "due > dilligence", (e.g. wipe our asses properly) The path could exist but not be a directory. > else: > print "User Home dir exist, checking and fixing permissions." > > print "usrHome is: ",usrHome > print "theUsr is: ",theUsr > > os.system('/usr/bin/chmod 750 ' + usrHome) > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) > > #I know that I can't optimize the line below further... or... can I? > > sys.exit("Thanks for using pyDirFixr...") Given the Unixy nature of your code, you probably want to sys.exit(0) for success and 1 or 2 for failure. Happy hacking, -- --Bryan From duncan.booth at invalid.invalid Mon Mar 17 09:31:53 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 13:31:53 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > What are the considerations in choosing between: > > return [a, b, c] > > and > > return (a, b, c) # or return a, b, c > A common explanation for this is that lists are for homogenous collections, tuples are for when you have heterogenous collections i.e. related but different things. If you follow this line of argument then when you want to return some values from a function, e.g. url, headers and data a tuple would be the appropriate thing to use. If you really are returning a homogenous collection (e.g. top 5 urls) then a list would be more appropriate. Another way to look at it is what you expect the caller to do with the results. If they are just going to unpack a fixed set of values then a tuple makes sense. If you write: return url, headers, data then the caller writing: url, headers, data = frobozz() has a certain symmetry. It isn't set in stone of course: use whatever you want or whatever feels right at the time. > Why is the immutable form the default? > It isn't. It uses whichever type you specify but tuples may involve a little less typing. From josef.pktd at gmail.com Sat Mar 15 17:47:08 2008 From: josef.pktd at gmail.com (joep) Date: Sat, 15 Mar 2008 14:47:08 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> Message-ID: On Mar 15, 5:42 pm, joep wrote: > >http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... > > Note: this works for subprocess.call but for subprocess.Popen this > does not work if there are two arguments in the command line with > spaces. Especially, even after trying out many different versions, I > never managed to get subprocess.Popen to work, when both the > executable and one argument have spaces in the file path. > Sorry, incomplete sentence Especially, even after trying out many different versions, I never managed to get subprocess.Popen to work '''when command line is given as a *list* argument to subprocess.Popen''' in the case when both the executable and one argument have spaces in the file path. joe From mcepl at redhat.com Sun Mar 2 04:15:54 2008 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 02 Mar 2008 10:15:54 +0100 Subject: sqlite3 adaptors mystery References: Message-ID: On 2008-03-02, 08:16 GMT, Matej Cepl wrote: > Thanks for your help, but plain-text strings is not what > I wanted. The boolean variables was what I was after. See this > modified version of the script: OK, I got it -- I was missing detect_types parameter of the connect method. Mat?j From michael.wieher at gmail.com Sun Mar 16 10:09:16 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:09:16 -0500 Subject: Cannot build Python 2.4 SRPM on x64 platform In-Reply-To: References: Message-ID: Sorry I don't have much of a better idea, but if I had this kind of problem with an RPM, I'd just grab the tarball and start hacking away at ./configure pre-requirements, trying to use --options to trim it down to the bare minimal and see if I can get it to load up. 2008/3/16, Eric B. : > > Hi, > > For those on several python lists, I appologize in advance for > cross-posting, but I'm really not sure which list is best to ask for > assistance with this. > > Currently, I am trying to build the python2.4 SRPM from Python.org on a > RHEL4 x64 platform, but the build is failing with a very non-descript > error message. > > .... > + cd /var/tmp/python2.4-2.4-root/usr/bin > + mv -f pydoc pydoc2.4 > + cd /var/tmp/python2.4-2.4-root/usr/bin > + mv -f idle idle2.4 > + echo '#!/bin/bash' > + echo 'exec /usr/bin/python2.4 /usr/lib64/python2.4/idlelib/idle.py' > + chmod 755 /var/tmp/python2.4-2.4-root/usr/bin/idle2.4 > + cp -a Tools /var/tmp/python2.4-2.4-root/usr/lib64/python2.4 > + rm -f mainpkg.files > + find /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f > + sed 's|^/var/tmp/python2.4-2.4-root|/|' > + grep -v -e '_tkinter.so$' > error: Bad exit status from /var/tmp/rpm-tmp.55639 (%install) > > > RPM build errors: > user jafo does not exist - using root > group jafo does not exist - using root > user jafo does not exist - using root > group jafo does not exist - using root > Bad exit status from /var/tmp/rpm-tmp.55639 (%install) > > > If I try to run /var/tmp/rpm-tmp.55639 manually from the prompt manually > after the rpmbuild fails, it runs properly to completion. If I try to > comment out that last line (find > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f | sed > 's|^/var/tmp/python2.4-2.4-root|/|' | grep -v -e '_tkinter.so$' ) that > seems > to be causing the script to fail, rpmbuild finishes, but with several > error > msgs, complaining about missing files in the lib64 directories: > > + rm -f /tmp/python-rpm-files.4859 > + /usr/lib/rpm/brp-compress > + /usr/lib/rpm/brp-strip > + /usr/lib/rpm/brp-strip-static-archive > + /usr/lib/rpm/brp-strip-comment-note > Processing files: python2.4-2.4-1pydotorg > error: File not found by glob: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.txt > error: File not found by glob: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.py* > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/pdb.doc > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/profile.doc > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/curses > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/distutils > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/encodings > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/plat-linux2 > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/site-packages > error: File not found: /var/tmp/python2.4-2.4-root > /usr/lib64/python2.4/test > error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/xml > error: File not found: /var/tmp/python2.4-2.4-root > /usr/lib64/python2.4/email > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/compiler > error: File not found: /var/tmp/python2.4-2.4-root > /usr/lib64/python2.4/bsddb > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/hotshot > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/logging > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-old > Executing(%doc): /bin/sh -e /var/tmp/rpm-tmp.95118 > + umask 022 > + cd /usr/src/redhat/BUILD > + cd Python-2.4 > + DOCDIR=/var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + export DOCDIR > + rm -rf /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + /bin/mkdir -p /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + cp -pr Misc/README Misc/cheatsheet Misc/Porting > /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + cp -pr LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS > /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + exit 0 > Processing files: python2.4-devel-2.4-1pydotorg > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/config > Processing files: python2.4-tools-2.4-1pydotorg > Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 > rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(VersionedDependencies) <= > 3.0.3-1 > Requires: /bin/bash /bin/sh /usr/bin/env > > > Finally, if I try searching for any files in the > usr/lib64/python2.4/lib-dynload or usr/lib64/python2.4/idlelib > directories > manually, I don't see any files at all in those directories. > > > To me, it seems as though python is either not installing the files in the > right places, or the script is searching for files in the wrong places, > but > I'm completely guessing here. > > Has anyone managed to build Python2.4 on a RHEL4 x64 system? Can anyone > point me in the right direction to complete this build successfully? I'm > hoping to get the binaries built so I can contribute them to the > python.org > site so others don't need to go through these problems in the future. > > Any hints / ideas / suggestions / guidance that anyone can provide would > amazing, because I'm completely out of ideas at this point. Like I said, > I'm trying to build this on a RHEL4 x64 system, with all latest updates. > > Thanks so much! > > Eric > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Tue Mar 11 22:49:54 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 11 Mar 2008 19:49:54 -0700 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: Message-ID: Roopan wrote: > I assume the C++/Python binding is fairly painless. http://www.boost.org/libs/python/doc/tutorial/doc/html/index.html Ahhhh. :) From davidj411 at gmail.com Mon Mar 10 13:20:46 2008 From: davidj411 at gmail.com (davidj411) Date: Mon, 10 Mar 2008 10:20:46 -0700 (PDT) Subject: lowercase u before string in "python for windows" Message-ID: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> why does this occur when using the python windows extensions? all string are prefixed by a lowercase "u". is there a newsgroup explicitly for python windows extensions? example of output below. SMBIOSBIOSVersion:u'A16' SMBIOSMajorVersion:2 SMBIOSMinorVersion:3 SMBIOSPresent:True SoftwareElementID:u'Phoenix ROM BIOS PLUS Version 1.10 A16' SoftwareElementState:3 Status:u'OK' TargetOperatingSystem:0 here is a snippet of the code: if objItem.Status != None: print "Status:" + ` objItem.Status` if objItem.TargetOperatingSystem != None: print "TargetOperatingSystem:" + ` objItem.TargetOperatingSystem` if objItem.Version != None: print "Version:" + ` objItem.Version` From gdamjan at gmail.com Tue Mar 25 20:00:55 2008 From: gdamjan at gmail.com (Damjan) Date: Wed, 26 Mar 2008 01:00:55 +0100 Subject: Beta testers needed for a high performance Python application server References: Message-ID: <47e99237$0$90273$14726298@news.sunsite.dk> >> I'm looking for beta testers for a high performance, event-driven Python >> application server I've developed. >> >> About the server: the front end and other speed-critical parts of the >> server are written in portable, multithreaded C++. ... > Why not just put it on the net somewhere and tell us where it is? > People aren't generally going to want to help or even look at it if > you treat it like a proprietary application. So, put the documentation > and code up somewhere for all to see. > BTW, multiprocess web servers such as Apache can quite happily make > use of multiple cores. Even within a single Apache multithread process > it can still use multiple cores quite happily because all the > underlying network code and static file handling code is in C and not > subject to the GIL. So, as much as people like to bash up on the GIL, > within Apache it is not necessarily as big a deal as people make out. BTW nginx now has a mod_wsgi too, if someone is looking for an Apache replacement. -- damjan From bernard.chhun at gmail.com Fri Mar 28 10:44:54 2008 From: bernard.chhun at gmail.com (Bernard) Date: Fri, 28 Mar 2008 07:44:54 -0700 (PDT) Subject: simple web-server References: Message-ID: <0060b0f1-02b3-498e-be95-8581c4f98ccf@i12g2000prf.googlegroups.com> Did you take a look at web.py? That one looks terribly small and efficient :) We use CherryPy coupled with compiled Cheetah Templates for every web server based projects at my workplace and we've been really satisfied with it so far. On 28 mar, 07:53, "Pavol Murin" wrote: > hello python users, > > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). > > Longer story: > > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed). > > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? > > thank you, muro From Medhat.Gayed at gmail.com Mon Mar 3 22:41:00 2008 From: Medhat.Gayed at gmail.com (Medhat.Gayed at gmail.com) Date: Mon, 3 Mar 2008 19:41:00 -0800 (PST) Subject: XML Schema validation in Python Message-ID: I tested and tried a few XML validators but none of them is able to successfully validate a string of xml (not a file just a string) to programatically be able to validate messages of xml that flow in and out of the different systems. The validators I used were XSV, oNVDL and lxml, can we implement a pure python module for validating strings of xml using XML Schema (not DTD) ? From stefan_ml at behnel.de Mon Mar 10 15:11:53 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 20:11:53 +0100 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <47D587F9.3050703@behnel.de> Malcolm Greene wrote: >> My personal experience with wxPython has its ups and downs. Specifically >> when it comes to crashes, I wouldn't bet my life on it. > > I'm new to Python and getting ready to build a small client based > application intended to run on Windows and Linux. I was planning on using > wxPython until I saw your comment above. Just to make this sound a bit less like FUD: my last experience with wxPython dates back a couple of years (2004/5?), but back then, we used BoaConstructor in a project, which crashed a bit too often to do real work with it - and with crashing I mean crashing Python, not just showing us its blank traceback. So this was definitely a problem either in wxWindows or in wxPython. I have no idea how well it works today, but this has definitely forged my opinion on wxPython. > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > or tips on where I can find out more about wxPython/wxWidget problems? The only other GUI library I used was PyQT3. To me, it has proven to be very stable, pretty easy to use and feature rich. And from what I read about it, PyQT4 is supposed to be another lot better and has removed the few API quirks I found at the time (AFAIR, it finally returns plain Python strings from the API, for example). Stefan From fetchinson at googlemail.com Mon Mar 3 01:32:43 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 2 Mar 2008 22:32:43 -0800 Subject: SQLLITE In-Reply-To: <74838b55-9b05-4f90-8a15-37bb50a775da@h11g2000prf.googlegroups.com> References: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> <62tjigF24ui98U2@mid.uni-berlin.de> <74838b55-9b05-4f90-8a15-37bb50a775da@h11g2000prf.googlegroups.com> Message-ID: > > > I am having a minor problem when I try and do this: > > > c.execute("insert into [tblTranscripts] (MovieID,Transcript) > > > Values(" + movieID + ",'" + formatText + "');") (don't even bother > > > commenting of the sql style I know its bad form but this is a simple > > > script). Whenever I try and do the insert I get table not found, > > > however when I perform the sql through sqlite's command line program > > > (the sql is outputted via a print statement) it works fine. Any ideas? > > > > No, and without more context nobody will have. Does working with the > > table with other statments work, how do you connect the DB, are you sure > > you really use the same DB-file and so forth. > > > Beginner stuff is usually forgetting 'use moviedata'. This is not needed for sqlite. The database is defined by the file the sqlite executable is working on. From darcy at druid.net Fri Mar 7 13:09:19 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 7 Mar 2008 13:09:19 -0500 Subject: Regarding coding style In-Reply-To: References: <63d80bF273nraU1@mid.individual.net> Message-ID: <20080307130919.b3f82a85.darcy@druid.net> On 7 Mar 2008 17:40:08 GMT Jon Ribbens wrote: > Well, no, it's to follow a particular person's choice out of the many > and various competing rules of "correct English usage". Personally, > I dislike double spaces after sentences, but it is not wrong to put > them there any more than it is wrong not to put them there. > Consistency is far more important (hence the rule, I presume). Warning: Opinion follows possibly influenced by insufficient research. I have read the arguments about single or double spacing and find that they can be distilled down to the following: You should use double space for monospaced fonts and single for proportional. I reject this argument for two reasons. One is consistency. It is entirely possible for the same document to be rendered in multiple ways and you may not be aware of them ahead of time. The second is that it seems to me that programs that use proportional fonts should be able to make any space between sentences render properly by their own rules so the number of spaces should be irrelevant. I am not swayed by arguments that they don't handle this properly yet. The arguments for one over the other fall into these basic ones. Use double spaces to make the document easier to read, especially by people who read a lot and tend to skim to absorb as much information as possible. Use single space because it makes the document display nicer. This suggests to me that the schism is probably between two different types of people, text/information oriented and display/presentation oriented. I don't see any way to appeal to both. -- 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 dickinsm at gmail.com Sat Mar 8 20:09:11 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 17:09:11 -0800 (PST) Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Message-ID: On Mar 8, 6:26?pm, Paul Rubin wrote: > Alasdair writes: > > What is the best way of finding a ceiling of a quotient of arbitrary sized > > integers? > > ceiling(a/b) = (a+b-1)//b I prefer: ceiling(a/b) = -(-a)//b which also works if a and b are something other than integers (e.g. rational numbers). Mark From emailamit at gmail.com Mon Mar 31 13:38:47 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 10:38:47 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Message-ID: <89d34053-4b16-49df-9153-eb3625249ad4@u10g2000prn.googlegroups.com> On Mar 31, 10:37 am, John Henry wrote: > On Mar 31, 10:24 am, Amit Gupta wrote: > > > > > Hi > > > I am looking for a some tool that can convert python scripts to > > executable on Linux. > > > I found freeeze.py as the only option so far. Couple of queries on > > freeze: > > > 1. Have anyone used the freeze utility and any experiences to share > > from that? > > 2. Is there any enterprise-level exe-builder for python on linux > > (ActiveState has nothing)? > > > Any other related commets are also welcome. > > > Thanks > > Amit > > I don't know about freeeze.py but for me, I've been using py2exe, and > also pyinstall quite often and they both work for me. Isnt py2exe for windows only? I haven't looked at pyinstall.. Is it for linux? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 4 06:27:58 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 04 Mar 2008 12:27:58 +0100 Subject: Difference between 'function' and 'method' In-Reply-To: References: Message-ID: <47cd3238$0$17697$426a74cc@news.free.fr> ?? a ?crit : > Howdy everyone, > > This is a big problem puzzles me for a long time. The core question is: > How to dynamically create methods on a class or an instance? class Foo(object): pass def bar(self, arg): print "in bar : self == % - arg == %s" % (self, str(arg)) def baaz(self, arg): print "in baaz : self == % - arg == %s" % (self, str(arg)) f = Foo() # adding bar as a method to class Foo Foo.bar = bar # f now can use bar: f.bar(42) # as well as new instances of Foo, of course g = Foo() g.bar() # adding baaz as a method to f, the old way: import new f.baaz = new.instancemethod(baaz, f, type(f)) f.baaz() # adding baaz as a method to g, the other way: g.baaz = baaz.__get__(g, type(g)) g.baaz() > Let me state it step by step. > 1. > def gunc(self): > pass > class A(object): > def func(self): > pass > a = A() > a.func # gives "bound method", type is "instancemethod" > A.func # gives "unbound method", type is "instancemethod" > gunc # gives "function", type if "function" > > # ?? Does this line attach a method to instance? ... I don't think so. > a.gunc = gunc It doesn't. > I found stardard library 'new' may help. Is that right? cf above. If you work with old-style classes, you'll need new.instancemethod. > 2. > a = A() # instance of old class A > # Do attach a new method to class A... > b = A() # instance of new class A > Does "a" can get the new method automatically? Yes. In Python, a class is itself an object, and is an attribute of it's instances (instance.__class__). Names are resolved at runtime, and attributes not found in the instance's __dict__ are looked up in the class (and then in the superclasses etc). > Does new method have the *same* concept level with old methods? The newly added method works exactly the same way as already existing ones. Not a single difference. The class statement is just syntactic sugar anyway. The following snippets are equivalent: # sugar-coated: class Boo(object): faaz = 0 def far(self): type(self).faaz += 1 print self def frob(self): print "yadda" # raw: def far(self): type(self).faaz += 1 print self Boo = type('Boo', (object,), dict(faaz=0, far=far)) def frob(self): print "yadda" Boo.frob = frob > Especially, if there > are classes inherit from class A, how does name resolution work on this case? As usual. > 3. > How do I write a decroator for a method? Mostly the same way you'd write a decorator for a function > Eg: > class A(object): > @my_dec > def func(self): > pass > Here, my_dec should return a method rathar than a function/lambda. Am I right? Nope. Functions defined within a class statement are plain ordinary functions. It's the lookup mechanism that "turns them into methods" when they are looked up as attribute of a class. In fact, Python "methods" are thin callable wrappers around a function, a class and (most of the time) an instance, wrappers which are created - usually at lookup time - by the __get__ method of the function type (you may want to read about the descriptor protocol on python.org - in the section about new style classes IIRC). Anyway, you can explore this by yourself: >>> Boo.far >>> b.far > >>> Boo.__dict__['far'] >>> Boo.__dict__['far'] is far True >>> f1 = b.far >>> f2 = b.far >>> f1 is f2 False >>> f1() <__main__.Boo object at 0xb787f96c> >>> f2() <__main__.Boo object at 0xb787f96c> >>> dir(f1) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] >>> f1.im_class >>> f1.im_func >>> f1.im_func is far True >>> f1.im_self <__main__.Boo object at 0xb787f96c> >>> f1.im_self is b True >>> bf = Boo.far >>> bf.im_func >>> bf.im_func is far True >>> bf.im_class >>> bf.im_self >>> bf.im_self is None True >>> far.__get__(b, Boo) > >>> far.__get__(b, Boo).im_func is far True >>> So, to answer your question: what you are decorating are functions, not methods. > What does @property @staticmethod... really do? I cannot step-into them for > source code. staticmethod wraps the function into an object that, when looked up as an attribute, will return the raw function instead of returning a method. property is a type that provides a simple generic implementation for computed attributes. You'll find more detailed explanations in the doc (but perhaps not in the most obvious place - it's somewhere in the peps or in the 'nws style classes' stuff IIRC). Anyway, using it as a decorator is a somewhat special case (well... to me at least), that will defined a property with only a getter (the decorated function). > 4. > If most of above questions can be solved, then it would be easy to implement > the feature: "dynamic property attach". > Eg: > One class can read/store settings from/to some file based on > the file content. > # File: cfg.ini > x = 1 > y = python > config = SettingClass('cfg.ini') # dynamically build up properties x and y. > x = config.x # x will be set to 1 (str -> int convertion would be > done by 'property x') > y = config.y # y will be set to 'python' > config.x = 9 # 'x = 9' is written to cfg.ini. > > How to implement In this case, I'd rather use the __getattr__/__setattr__ hooks. It won't work with properties nor custom descriptors, since descriptors only work as class attributes - not as instance attributes (which BTW is why setting a function as an instance attribute doesn't make it a method...) here are a couple links to relevant documentation and stuffs: http://www.python.org/download/releases/2.2.3/descrintro/ http://users.rcn.com/python/download/Descriptor.htm http://www.python.org/doc/newstyle/ > ^_^ Maybe there are some library does the same thing. Indeed: http://www.voidspace.org.uk/python/configobj.html http://wiki.python.org/moin/ConfigParserShootout HTH From castironpi at gmail.com Wed Mar 19 01:37:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 22:37:38 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: On Mar 18, 10:08?pm, Bryan Olson wrote: > Arnaud Delobelle wrote: > > Ninereeds wrote: > >> Hrvoje Niksic wrote: > >>> This doesn't apply to Python, which implements dict storage as an > >>> open-addressed table and automatically (and exponentially) grows the > >>> table when the number of entries approaches 2/3 of the table size. > >>> Assuming a good hash function, filling the dict should yield amortized > >>> constant time for individual additions. > > > Isn't this average constant time rather than amortized? > > This is expected amortized constant time. Is that really the same > thing as average constant time? Hmmm... that's subtle. It's the same as expected constant time. > >> OK. I obviously need to look up open-addressed tables. I thought this > >> was just, in effect, implicit linked listing - ie it still needs a > >> linear search to handle collisions, it just avoids the need for > >> explicitly stored link fields. Perhaps I'm mistaken. > > The amortized doubling breaks that. > > > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > > link to further details. > > Arnaud Delobelle offered a good Wikipedia link, and for more background > look up "amortized analysis. >>> [ (i,hash(2**i)) for i in range( 0, 5000, 32 ) ] [(0, 1), (32, 1), (64, 1), (96, 1), (128, 1), (160, 1), (192, 1), (224, 1), (256 , 1), (288, 1), (320, 1), (352, 1), (384, 1), (416, 1), (448, 1), (480, 1), (512 , 1), (544, 1), (576, 1), (608, 1), (640, 1), (672, 1), (704, 1), (736, 1), (768 , 1), (800, 1), (832, 1), (864, 1), (896, 1), (928, 1), (960, 1), (992, 1), (102 4, 1), (1056, 1), (1088, 1), (1120, 1), (1152, 1), (1184, 1), (1216, 1), (1248, 1), (1280, 1), (1312, 1), (1344, 1), (1376, 1), (1408, 1), (1440, 1), (1472, 1), (1504, 1), (1536, 1), (1568, 1), (1600, 1), (1632, 1), (1664, 1), (1696, 1), (1 Not so farfetched, all. Don't forget big-theta and big-omega. From larry.bates at websafe.com Wed Mar 19 14:02:46 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 19 Mar 2008 13:02:46 -0500 Subject: how to remove suffix from filename In-Reply-To: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> References: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> Message-ID: royG wrote: > hi > when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/ > two.jpg'....] etc i want to extract the > basename without the suffix...ie i want to get 'one','two' etc and not > 'one.jpg' > > is there a function in python to do this or do i have tosplit it ..? > thanks > RG import os fname='F:/mydir/two.jpg' filenameonly=os.path.splitext(os.path.basename(fname))[0] -Larry From igorr at ifi.uio.no Fri Mar 14 11:21:10 2008 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 14 Mar 2008 16:21:10 +0100 Subject: catching object References: <47d7d40a$0$2659$9b622d9e@news.freenet.de> Message-ID: [ stargaming at gmail.com ] [ ... ] > I think inheritance is meant in reference to the Exception tree here. So, > the uppermost class is `BaseException`. Python 3 gives this exception > when trying to handle `object`:: > > TypeError: catching classes that do not inherit from BaseException is > not allowed I realise that exceptions should inherit from Exception, but the question is more "why isn't an instance of ValueError a match for object, when ValueError is a subclass of object (at least in 2.5) [ ... ] > > So, why doesn't object match ValueError (or any other exception for that > > matter). I am aware of "except:", but in my particular situation it is > > eh... unsuitable. > > Why so? I am writing a function that takes a function and an exception list arguments and returns a new function that calls the original while trapping the specified arguments. One of the applications is to make a wrapper that ignores all of the exceptions. I thought that specifying the exception list containing object would suffice to cover that. Alas, no joy. [ ... ] ivr -- <+Kaptein-Dah> igorr: for f? parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent From removetoreply.djain at gmx.net Mon Mar 17 20:08:45 2008 From: removetoreply.djain at gmx.net (Dominik Jain) Date: Tue, 18 Mar 2008 01:08:45 +0100 Subject: how to create instances of classes without calling the constructor? Message-ID: <47df0816$0$6635$9b4e6d93@newsspool2.arcor-online.net> Hi! Does anyone know how an instance of a (new-style) class can be created without having to call the constructor (and providing the arguments it requires)? With old-style classes, this was possible using new.instance. Surely there must be a simple way to do this with new-style classes, too -- or else how does pickle manage? Best, Dominik From dundeemt at gmail.com Mon Mar 17 21:25:32 2008 From: dundeemt at gmail.com (dundeemt) Date: Mon, 17 Mar 2008 18:25:32 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> Message-ID: <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> On Mar 17, 10:35 am, fumanchu wrote: > On Mar 16, 5:09 pm, a... at pythoncraft.com (Aahz) wrote: > > > fumanchu wrote: > > > This is my third PyCon, and I've found a reasonably-sized cadre of > > > people who come for the hallway conversations plus a Bof or two, > > > having given up on hearing anything new, useful, or inspiring in the > > > talks. There are several people I know who would like to see a more > > > advanced academic track. > > > Finally, trying to satisfy a thousand people is impossible. > > Well understood. Sorry if I implied it was an easy job. I know it > isn't. > > > If you did not like the programming this year (aside from the sponsor > > talks) and you did not participate in organizing PyCon or in delivering > > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > > This would be true, except that the two talks I proposed last year > were essentially denied because they were too advanced, so I didn't > even bother this year. Perhaps I should have, but the PERIOD needs to > at least be replaced by a COMMA as long as the talk-acceptance > committee continues to reject more advanced talk topics in favor of > HOWTOs and Introduction To Package X. I agree - the balance wasn't as good. We can all agree that HowTos and Intros are a necessary part of the conference talks track, but as Robert pointed out some talks should be of a more advanced nature. I enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and Mark Hammond's keynote were among my favorite talks. -jeff hinrichs From sjmachin at lexicon.net Tue Mar 18 18:43:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Mar 2008 15:43:19 -0700 (PDT) Subject: os.path.getsize() on Windows References: <6abeaadf-0055-4216-9aed-ad87bc006038@h11g2000prf.googlegroups.com> Message-ID: <238ad1d1-f004-42b4-90ea-4474ec961616@u10g2000prn.googlegroups.com> On Mar 19, 9:27 am, Sean DiZazzo wrote: > On Mar 18, 2:27 pm, Duncan Booth wrote: > > > > > Sean DiZazzo wrote: > > > On windows, this returns the size of the file as it _will be_, not the > > > size that it currently is. Is this a feature? What is the proper way > > > to get the current size of the file? I noticed > > > win32File.GetFileSize() Does that behave the way I expect? > > > > PS. I also tried os.stat()[6] > > > I think all of those will return the current size of the file, but that may > > be the same as the final size: just because the data hasn't been copied > > doesn't mean the file space hasn't been allocated. You don't say how you > > are copying the file, but I seem to remember that Windows copy command pre- > > allocates the file at its final size (so as to reduce fragmentation) and > > then just copies the data after that. > > > If you need to make sure you don't access a file until the copy has > > finished then get hwatever is doing the copy to copy it to a temporary > > filename in the same folder and rename it when complete. Then you just have > > to check for existence of the target file. > > Hmmm... The file could be copied in by several different sources of > which I have no control. I can't use your technique in my situation. > I also tried getting md5 hashes with some time in between on advice, > but the file is not opened for reading until the copy completes so I > can't get the hashes. > > Any other ideas? Why not try to open the file for exclusive write/update access? From castironpi at gmail.com Tue Mar 4 23:57:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:57:58 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> > > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > > > >> >> is it makes it. > > > > >> >>>> from types import FunctionType, MethodType > > > >> >>>> class A( FunctionType ): pass > > > >> > ... > > > >> > Traceback (most recent call last): > > > >> > ? File "", line 1, in > > > >> > TypeError: type 'function' is not an acceptable base type > > > > >> Use delegation instead of inheritance. This class is almost ? > > > >> indistinguishable from a true function (when used as a method): > > If P gets, p gotcha. > > > > > gotcha= partial( get, you ). ?bor hor hor. ?Yes... > > Notwithstanding. ?Now bar has a name. Now func has it. from functools import wraps class myfunction: __slots__ = ('func','name') # def __init__(self, func): @wraps( func ) def f( *ar, **kws ): return func( self, *ar, **kws ) object.__setattr__(self, 'func', f) object.__setattr__(self, 'name', None) # def __get__(self, instance, owner): print( "__get__ called for",instance ) return self.func.__get__(instance, owner) # def __getattr__(self, name): return getattr(self.func, name) # def __setattr__(self, name, value): object.__setattr__(self.func, name, value) class mymeta( type ): def __init__( self, name, bases, namespace ): for k,v in namespace.items(): if isinstance( v, myfunction ): v.name= k class P( metaclass= mymeta ): def foo(self, x): print( 'foo',x ) # @myfunction def bar( fob,self, x): print( 'bar',fob,x ) p= P() p.foo( 0 ) p.bar( 1 ) print( p.bar ) print( p.bar.name ) From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 03:42:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 07:42:34 -0000 Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> Message-ID: <13u45bam9k12n71@corp.supernews.com> On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > suppose > origsz=(400,300) > i want to divide the origsize by 2.5 so i can resize to (160,120) > > scale=2.5 > how can i get the newsz? > obviously origsz/2.5 won't work .. newsz = (origsz[0]/scale, origsz[1]/scale) -- Steven From pavlovevidence at gmail.com Sun Mar 2 05:53:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Mar 2008 02:53:08 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: <21f9e110-04dd-4af3-a046-bb709b0ee5dc@x41g2000hsb.googlegroups.com> On Mar 2, 4:02 am, Kay Schluehr wrote: > On 2 Mrz., 06:53, Ben Finney > wrote: > > > One of the stated goals of the migration is that the '2to3' program > > will only migrate Python 2.6 code -> Python 3.0 code. > > Yes, I know. Why? > > "The master said so" isn't an entirely satisfying answer. What are the > *technical reasons* that make it hard to apply '2to3' directly on > Python 2.4 or Python 2.5? Well, even if you wanted to apply 2to3 to Python 2.5, you'd (probably) have to modify your code to make it 2to3-compatible. So if you're going to do that, you might as well upgrade to 2.6 to take advantage of new warnings and new idioms that are more conducive automatic translation. 2to3 is not a general tool to convert any given source code from 2.6 to 3.0. It's designed to make it possible to write code that works in Python 2.6 and Python 3.0, but to do that you have to use a "transitional Python" dialect that's a subset of 2.6. (It would be quite to attempt a general code translator, of course.) Anyway, I think there are a few cases in Python 2.5 where there's no easy way to write something that 2to3 can handle, and some specifically transitional features were added to 2.6 to remedy this. I don't recall specifics, though. It may be for the cases where things that previously returned lists now return iterators. Finally, 2.6 will have the benefit of being cross-checked with 3.0 to ensure that 2to3 does what it's supposed to when used as intended. All bets are off if you attempt it with 2.5. In the end, the real *technical* reason might have been the developers thought it wasn't worth the effort to backport it to 2.5. The above problems were probably solvable with enough effort, but would that have been a wise use of resources? One parenthetical I will add: 2to3 always seemed to me to be more of a way to enfore constraint on the design of Python 3.0. If a proposed feature couldn't be automatically ported to 3.0, then it was a big strike against the proposal. That it could end up being a useful transitional tool is nice, but it never seemed to be its primary purpose. Carl Banks From mh at pixar.com Mon Mar 10 14:00:44 2008 From: mh at pixar.com (mh at pixar.com) Date: Mon, 10 Mar 2008 18:00:44 GMT Subject: any chance regular expressions are cached? References: <51172306-ff2d-48e8-81cf-93be03f8a08f@s37g2000prg.googlegroups.com> Message-ID: John Machin wrote: > Yes they will be cached. great. > But do yourself a favour and check out the > string methods. Nifty... thanks all! -- Mark Harrison Pixar Animation Studios From Sandipan at gangopadhyay.com Sun Mar 16 18:55:40 2008 From: Sandipan at gangopadhyay.com (Sandipan Gangopadhyay) Date: Sun, 16 Mar 2008 18:55:40 -0400 Subject: Python for BlackBerry In-Reply-To: <79aa668a-f1b6-4f59-9ff9-8dc9dfc177aa@a23g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> <79aa668a-f1b6-4f59-9ff9-8dc9dfc177aa@a23g2000hsc.googlegroups.com> Message-ID: <14ae01c887b8$df23b290$9d6b17b0$@com> I checked; BlackBerry is not on Symbian. They provide a Java Dev Envt (whatever that may mean). Does that mean, we can try and implement JPython/Jython on it? Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of Mike Driscoll Sent: Sunday, March 16, 2008 8:47 AM To: python-list at python.org Subject: Re: Python for BlackBerry On Mar 15, 9:52 pm, "Sandipan Gangopadhyay" wrote: > Thanks, Mike. > This one seems to be for Nokia, particularly S60 and Symbian in general. > Does BlackBerry work on Symbian? Let me check. > Thanks. > Sandipan > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of Mike > Driscoll > Sent: Saturday, March 15, 2008 6:04 PM > To: python-l... at python.org > Subject: Re: Python for BlackBerry > > On Mar 15, 7:24 am, "Sandipan Gangopadhyay" > wrote: > > Is there a Python for BlackBerry? Thanks. > > > -----Original Message----- > > From: python-list-bounces+news=sandipan.... at python.org > > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of > E-Lo > > Sent: Saturday, March 15, 2008 6:03 AM > > To: python-l... at python.org > > Subject: Python for Palm OS > > > Is there any other edition of Python for Palm OS instead of Pippy? > > --http://mail.python.org/mailman/listinfo/python-list > > You might look at Mobile Python. I'm not sure if it works on > Blackberry though:http://www.mobilepythonbook.org/ > > Mike > --http://mail.python.org/mailman/listinfo/python-list I was afraid of that. I'm at PyCon and between their flakey wireless and my own laptop's flakey wireless card, it''s been a pain to do any research. Good luck. Mike -- http://mail.python.org/mailman/listinfo/python-list From paddy3118 at googlemail.com Fri Mar 28 01:52:30 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 27 Mar 2008 22:52:30 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> Message-ID: On Mar 28, 5:38 am, ankitks.mi... at gmail.com wrote: > >>> dict = {'M':3, 'R':0, 'S':2} > >>> print dict > > {'S': 2, 'R': 0, 'M': 3} > > now if I wanted sorted values in list, i am not able to do this>>> print dict.values().sort() > > None > > it returns None instead of [0, 2, 3] Try: from pprint import pprint as pp pp(my_dict) It works well for other built-in types too. P.S it is not good to use a name, dict, that already has a use in Python. - Paddy. From nickmiller92 at gmail.com Sun Mar 2 11:25:04 2008 From: nickmiller92 at gmail.com (Nick Miller) Date: Sun, 02 Mar 2008 10:25:04 -0600 Subject: Question on importing and function defs In-Reply-To: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> Message-ID: <47CAD4E0.9060904@gmail.com> TC wrote: > I have a problem. Here's a simplified version of what I'm doing: > > I have functions a() and b() in a module called 'mod'. b() calls a(). > > So now, I have this program: > > from mod import * > > def a(): > blahblah > > b() > > > The problem being, b() is calling the a() that's in mod, not the new > a() that I want to replace it. (Both a()'s have identical function > headers, in case that matters.) How can I fix this? > > Thanks for any help. > The only problem I could see with this is a local function issue. Meaning that even when you write the new a() function in the main source file, b() doesn't know it exists because it's relying on it's own "local" a() in the module. I'm also new to using Python so I that's all I can think would be the problem. Nick From yhidalgo86 at gmail.com Sun Mar 16 23:42:07 2008 From: yhidalgo86 at gmail.com (Yusniel) Date: Sun, 16 Mar 2008 20:42:07 -0700 (PDT) Subject: File system in TreeWidget References: Message-ID: <859e53e5-d27c-443d-8806-8b77d592e6eb@x30g2000hsd.googlegroups.com> On Mar 16, 11:39 pm, Yusniel wrote: > Hi friends. How can I do a Tree Widget with all directories and files > given path parameter or a tree generated with the function > os.walk(). Sorry for my bad english. Sorry. I am using PyQt4. From simon at brunningonline.net Thu Mar 6 15:07:46 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 6 Mar 2008 20:07:46 +0000 Subject: List all files using FTP In-Reply-To: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> References: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> Message-ID: <8c7f10c60803061207j4af58813g6e794c67b41c10bc@mail.gmail.com> On Thu, Mar 6, 2008 at 6:11 PM, jay graves wrote: > On Mar 6, 10:46 am, Anders Eriksson wrote: > > I need to list all the files on my FTP account (multiple subdirectories). I > > don't have shell access to the account. > > anyone that has a program that will do this? > > Not offhand, but you can look at the ftpmirror.py script for > inspiration. > It should be in your Tools/scripts/ subdirectory of your Python > installation. This might be of use: -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From paul.hankin at gmail.com Sat Mar 8 10:42:01 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 8 Mar 2008 07:42:01 -0800 (PST) Subject: extract multiple ranges from a list References: Message-ID: On Mar 8, 3:28?pm, pi.arc... at gmail.com wrote: > Hi guys, > > One of my many project involves working with YUV-files, where I need > to reduce > the vertical resolution with a factor of two, i.e. remove every other > scan line. > Today I'm using two for-loops in the fashion shown below > > y = [] > for i in range(0, width*height, width*2): > ? ? for j in range(0,width): > ? ? ? ? y.append(Y[i+j]) There's nothing really wrong with your code. Maybe it's a little nicer written like this: y = [] for i in range(0, height, 2): y.extend(Y[i * width + j] for j in range(width)) -- Paul Hankin From gagsl-py2 at yahoo.com.ar Sat Mar 29 20:12:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 21:12:33 -0300 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> Message-ID: En Sat, 29 Mar 2008 07:33:40 -0300, Steven D'Aprano escribi?: > The timeit.Timer class times "code snippets" -- you pass it strings > rather than function objects. That's good for what it's worth, but > sometimes the code you want to time is too big to easily pass as a > string, or maybe you only have access to a function object without the > source, or for whatever reason it's not very convenient. > > In this case, a good trick is to import the function by name: > > timeit.Timer('spam()', 'from __main__ import spam') > > > But now I find myself wanting to time a function that's not defined in > __main__. Here's a illustrative example: > > > def factory(): > def f(): > return "spam" > return f > > def main(): > func = factory() > return timeit.Timer('func()', 'from __main__ import func').timeit() Would this help (untested)? def main(): return timeit.Timer('func()', 'from __main__ import factory; func = factory()').timeit() Or maybe: def main(): global func func = factory() return timeit.Timer('func()', 'from __main__ import func').timeit() -- Gabriel Genellina From jef.mangelschots at gmail.com Tue Mar 4 12:51:49 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 4 Mar 2008 09:51:49 -0800 (PST) Subject: unicode box drawing Message-ID: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> How can I print the unicode box drawing characters in python: print u'\u2500' print u'\u2501' print u'\u2502' print u'\u2503' print u'\u2504' Traceback (most recent call last): File "\test.py", line 3, in ? print u'\u2500' File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500' in position 0: character maps to From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 5 03:16:52 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Mar 2008 09:16:52 +0100 Subject: multiplication of lists of strings In-Reply-To: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> References: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> Message-ID: <47ce56e9$0$10738$426a34cc@news.free.fr> castironpi at gmail.com a ?crit : (snip) > > That reminds me: Is there a generic 'relation' pattern/recipie, such > as finding a computer that's "paired" with multiple users, each of who > are "paired" with multiple computers, without maintaining dual- > associativity? > Yes : use a relational database. From castironpi at gmail.com Thu Mar 6 19:56:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 16:56:33 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: On Mar 6, 5:35?am, "Gabriel Genellina" wrote: > En Wed, 05 Mar 2008 02:57:58 -0200, escribi?: > > > > > > >> > > >> >> Can you overload -type-'s decision of what to 'bind'?... ? > >> whenever it > >> > > >> >> is it makes it. > > >> > > >> Use delegation instead of inheritance. This class is almost ? > >> > > >> indistinguishable from a true function (when used as a method): > > >> Notwithstanding. ?Now bar has a name. > > Now func has it. > > > from functools import wraps > > class myfunction: > > ? ? __slots__ = ('func','name') > > ? ? # > > ? ? def __init__(self, func): > > ? ? ? @wraps( func ) > > ? ? ? def f( *ar, **kws ): > > ? ? ? ? ?return func( self, *ar, **kws ) > > ? ? ? object.__setattr__(self, 'func', f) > > ? ? ? object.__setattr__(self, 'name', None) > > ? ? # > > ? ? def __get__(self, instance, owner): > > ? ? ? ? print( "__get__ called for",instance ) > > ? ? ? ? return self.func.__get__(instance, owner) > > ? ? # > > ? ? def __getattr__(self, name): > > ? ? ? return getattr(self.func, name) > > ? ? # > > ? ? def __setattr__(self, name, value): > > ? ? ? object.__setattr__(self.func, name, value) > > > class mymeta( type ): > > ? ? def __init__( self, name, bases, namespace ): > > ? ? ? ? for k,v in namespace.items(): > > ? ? ? ? ? ? if isinstance( v, myfunction ): > > ? ? ? ? ? ? ? ? v.name= k > > > class P( metaclass= mymeta ): > > ? ? def foo(self, x): print( 'foo',x ) > > ? ? # > > ? ? @myfunction > > ? ? def bar( fob,self, x): print( 'bar',fob,x ) > > > p= P() > > p.foo( 0 ) > > p.bar( 1 ) > > print( p.bar ) > > print( p.bar.name ) > > Mmm, looks too complicated and I don't see any advantage over the original ? > code. Functions already know their (original) name: func_name. If `name` ? > was just an example, note that functions already have writeable attributes ? > too, and my code exposes them as well. This should work with that version ? > (untested): > > p = P() > print p.bar.func_name # -> bar > p.bar.im_func.anotherattribute = 1 > print p.bar.anotherattribute # -> 1 > > (the attribute must be set on the *function* itself if you want it to be ? > somewhat persistent; methods are usually volatile objects) You read my mind. I was just getting: assert p.bar is p.bar and failing. But if you set them on im_func, instances don't have their own. From xkenneth at gmail.com Mon Mar 31 14:00:13 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 31 Mar 2008 11:00:13 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> Message-ID: <304acc0a-3944-44a4-8626-30c2ab9da506@z38g2000hsc.googlegroups.com> Yeah, this is what I'm talking about: > def __eq__(self, other) : > ? try : > ? ? ?return <> > ? except AttributeError: > ? ? ?return False That seems a bit nasty to me. From ron at example.com Tue Mar 25 23:38:08 2008 From: ron at example.com (Ron Eggler) Date: Wed, 26 Mar 2008 03:38:08 GMT Subject: last mouse movment or keyboard hit Message-ID: Hi, I would like to get the time of the most recent human activity like a cursor movement or a key hit. Does anyone know how I can get this back to start some action after there has been no activity for X minutes/seconds? Thank you! -- chEErs roN From darrin_allen at japan.com Sun Mar 2 09:31:04 2008 From: darrin_allen at japan.com (t3chn0n3rd) Date: Sun, 2 Mar 2008 06:31:04 -0800 (PST) Subject: Python newbie Message-ID: i am a python newbie. My studies have me in many directions From mensanator at aol.com Tue Mar 4 18:58:41 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 15:58:41 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <042d507d-f53d-4219-be6e-d6b7a1f1d6c4@s8g2000prg.googlegroups.com> <8aa1c242-db46-4479-a26c-07517b478714@n75g2000hsh.googlegroups.com> Message-ID: On Mar 4, 4:40?pm, Mensanator wrote: > On Mar 4, 3:00?pm, Istvan Albert wrote: > > > On Mar 4, 3:13 pm, Mensanator wrote: > > > > But what if _I_ wanted to make a repeatable sequence for test > > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > > on every call? > > > Would it? > > I don't know, haven't tried it yet, Now I have and there is no problem. > merely extrapolating from how I _THINK_ it works. And my thinking was mistaken, the patch doesn't reset the seed, so nevermind. > I used to be a System Test Engineer > and had a gift for being able to walk up to hardware/software > and break it. Spooky? No, because I could extrapolate from > the design, I could often anticipate just where to nudge it to > cause it to crash. I wasn't very popular with the programmers. > > > > > It may just be that you are now itching to see a problem even where > > there isn't one. > > No, no, no. That would be an oh-what-a-giveaway, wouldn't it? > > > > > > > i.- Hide quoted text - > > - Show quoted text - From frikker at gmail.com Wed Mar 5 11:17:22 2008 From: frikker at gmail.com (blaine) Date: Wed, 5 Mar 2008 08:17:22 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> <13sr22ii98uipc4@corp.supernews.com> <13ssb8fjrdecbfe@corp.supernews.com> Message-ID: > Because it is NOT 0x10007... It is OCTAL 010007 -- which just > happens to map to hexadecimal 0x1007 > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ oh wow - that makes a lot more sense. haha. The processor we are going to use is ARM, yes, but our development at this point (to keep it simple) is just on a simple linux laptop pc. Thanks again for all the help :) From barnburnr at gmail.com Mon Mar 3 15:14:29 2008 From: barnburnr at gmail.com (barnburnr at gmail.com) Date: Mon, 3 Mar 2008 12:14:29 -0800 (PST) Subject: clocking subprocesses References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> <5af6d8ab-880a-4873-9352-cf1aaae236e0@e6g2000prf.googlegroups.com> Message-ID: On Mar 3, 12:41 pm, Preston Landers wrote: > > Run your command through the "time" program. You can parse the output > format of "time", or set a custom output format. This mostly applies > to Unix-like systems but there is probably an equivalent somewhere on > Windows. > > Preston Thanks for the quick answer. That seems to work, though, I'll write a timesubprocess() function which runs the program through time and spits the formatted out to a file, then parses that file, then returns the execution time. There doesn't appear to be a more elegant way to do this. Kevin From duncan.booth at invalid.invalid Fri Mar 7 03:46:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Mar 2008 08:46:43 GMT Subject: Looking for very light weight template library (not framework) References: Message-ID: "Malcolm Greene" wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. You could try using the Template class: >>> from string import Template >>> class EvalTemplate(Template): idpattern = '[^{}]+' >>> class EvalDict(dict): def __getitem__(self, name): if name in self: return dict.__getitem__(self, name) return eval(name, globals(), self) >>> class Invoice: def __init__(self, total): self.total = total >>> i = Invoice(42) >>> template = EvalTemplate("The total cost is ${invoice.total}") >>> template.substitute(EvalDict(invoice=i)) 'The total cost is 42' The usual caveats about using 'eval' apply (maybe it should be called EvilDict), and I'm sure you could override substitute/safe_substitute to construct the EvalDict transparently. From bryanjugglercryptographer at yahoo.com Thu Mar 13 14:50:47 2008 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Thu, 13 Mar 2008 11:50:47 -0700 (PDT) Subject: subprocess.Popen pipeline bug? References: Message-ID: <026208f0-cd70-4f6a-bfe5-9f8f09a5b0f6@n58g2000hsf.googlegroups.com> Marko Rauhamaa wrote: > This tiny program hangs: > > ======================================================================== > #!/usr/bin/env python > import subprocess > a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, > stdout = subprocess.PIPE) > b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) > a.stdin.close() > b.wait() # hangs > a.wait() # never reached > ======================================================================== To make it work, add close_fds=True in the Popen that creates b. > It shouldn't, should it? Not sure. I think what's happening is that the second cat subprocess never gets EOF on its stdin, because there are still processes with an open file descriptor for the other end of the pipe. The Python program closes a.stdin, and let's suppose that's file descriptor 4. That's not enough, because the subshell that ran cat and the cat process itself inherited the open file descriptor 4 when they forked off. It looks like Popen is smart enough to close the extraneous descriptors for pipes it created in the same Popen call, but that one was created in a previous call and passed in. -- --Bryan From danb_83 at yahoo.com Mon Mar 17 02:56:50 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 16 Mar 2008 23:56:50 -0700 (PDT) Subject: String To List References: Message-ID: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> On Mar 17, 1:15 am, Girish wrote: > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? > Thanks for the help... eval(a) will do the job, but you have to be very careful about using that function. An alternative is [s.strip('\'"') for s in a.strip('[]').split(', ')] From yhidalgo86 at gmail.com Sun Mar 16 23:39:28 2008 From: yhidalgo86 at gmail.com (Yusniel) Date: Sun, 16 Mar 2008 20:39:28 -0700 (PDT) Subject: File system in TreeWidget Message-ID: Hi friends. How can I do a Tree Widget with all directories and files given path parameter or a tree generated with the function os.walk(). Sorry for my bad english. From ncoghlan at gmail.com Tue Mar 11 05:43:29 2008 From: ncoghlan at gmail.com (NickC) Date: Tue, 11 Mar 2008 02:43:29 -0700 (PDT) Subject: for-else References: Message-ID: On Mar 4, 11:27 pm, bearophileH... at lycos.com wrote: > > The meaning is explicit. While "else" seems to mean little there. > So I may like something similar for Python 3.x (or the removal of the > "else"). Consider a loop with the following form: while 1: if : <0-to-many times code block> else: <0-to-1 times code block> break A break, return or exception in the 0-to-many times code block will obviously skip over the 'else' part of that if statement - it will only be executed if evaluates as a false value. The above code is actually equivalent to a normal Python while-loop: while : <0-to-many times code block> else: <0-to-1 times code block> For loops aren't quite so straightforward since the termination condition is tied up with the StopIteration exception, but the clause keeps the same name as the corresponding clause on the while loop. Thinking of it as break-else (as someone else posted) probably isn't a bad way to look at the situation. Cheers, Nick. From Lie.1296 at gmail.com Sat Mar 8 12:45:38 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 09:45:38 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> Message-ID: Personally I preferred a code that has chosen good names but have little or no comments compared to codes that makes bad names and have twenty pages of comments to read and understand what it's about. Personally, I think comments should be made as short and as concise as possible and codes should try to be self-understandable if the comments aren't accessible. From cwitts at gmail.com Tue Mar 18 06:18:20 2008 From: cwitts at gmail.com (Chris) Date: Tue, 18 Mar 2008 03:18:20 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: On Mar 18, 11:57?am, Simon Forman wrote: > Is there a more efficient way to do this? > > def f(L): > ? ? '''Return a set of the items that occur more than once in L.''' > ? ? L = list(L) > ? ? for item in set(L): > ? ? ? ? L.remove(item) > ? ? return set(L) > > |>> f([0, 0, 1, 1, 2, 2, 3]) > set([0, 1, 2]) def f(L): D = dict() for item in L: if item in D: D[item] += 1 else: D[item] = 1 return [i for i,j in D.items() if j > 1] That would be my way to do it, would need to test it via several thousand iterations to see which one is most efficient though. From gherron at islandtraining.com Mon Mar 31 15:06:30 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 31 Mar 2008 12:06:30 -0700 Subject: [OT] troll poll In-Reply-To: References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> Message-ID: <47F13636.4030401@islandtraining.com> Duncan Booth wrote: > Paul Rubin wrote: > > >> "Daniel Fetchinson" writes: >> >>> [ ] - Xah Lee >>> [ ] - castironpi >>> >> I've lost track but has it been established that they are not the same >> person? >> >> > Has it actually been established that castironpi is actually a person? I > thought it was probably a random sentence generator. > Ahhh... Perhaps someone is running a Turing test on us. That is, if we can't tell the difference between castironpi and a *real* human (which we demonstrate whenever we try to respond to or reason with him/her/it), then castironpi can be declared to be a truly *intelligent* AI. AFAICT, there appears no danger of that happening yet. Gary Herron :-) From adairicky at gmail.com Sat Mar 8 10:43:05 2008 From: adairicky at gmail.com (333) Date: Sat, 8 Mar 2008 07:43:05 -0800 (PST) Subject: wholesale and retail nike sports shoes,nike shox,air maxss,dunks Message-ID: <4f755f56-4b38-4225-b423-174b673fc7f9@s13g2000prd.googlegroups.com> our website: http://www.FASHION4BIZ.com our MSN:fashion4biz at msn.com our EMAIL:fashion4biz at gmail.com paypal accept,wholesale and retail accept,dropship accept sale new Nike Sneakers,Air Jordan Sneakers,AIR FORCE 1S,Nike Dunks SB, Bape Sta from nike outlets and factory stores, also Nike wholesale - Jordan Shoes we supply nike sneaker jordan sneaker air force 1s ... Featuring unique gift ideas for birthdays, weddings, anniversaries & holidays.Nike Air Max LTD-Nike Air Max Ltd Shoes, Nike Air Max Ltd Trainers. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Air Max - Nike Air Max TN Plus,TN BURBERRY,Gucci,TN L.V.. NIKE TN REQUINS CHAUSSURES, neuves hommes Nike TN basketball shoes requins Chaussures : Nike Air Max TN Plus men's ,Nike Shox - Mens, Womens Nike Shox basketball shoes wholesale from china Nike Shox TL NZ R4 R5 Turbo Monster Nike shoes wholesale,Puma - Puma Shoes. Nike shoes wholesale: Puma Shoes men's women's trainers .. Puma Shoes cheap discount shoes nike wholesale and sale to nike shop and nike We sell Nike Air Max shoes,nike air max trainers for running and training- Nike Air Max 360 95 97 2003 Tn Plus Nike shoes wholesale,air max2 cb 94,air max2 cb,air ...Nike Wholesale,Nike Sneaker, jordan Sneaker, Air Force one 1s, Dunk Dunks Jordan Jordans Air Max Shox Rift ... Timberland. Timberland boots,Timberland shoes, Prada wholesale, Prada sale, Prada shop, Prada store. we wholesale and sale cheap discount Timberland men's women's ,We Wholesale Cheap Jordan Shoes, Michael Jordan Shoes, Nike Jordan Basketball shoes, Nike Air Jordan ... Once again, thank you for www.fashion4biz.com Timberland - Timberland Boots. Nike shoes wholesale: Timberland Boots men's women's trainers sneakers basketball shoes running shoes. Timberland Boots cheap discount Nike Air Max 90-Nike Air Max 90 Shoes, Nike Air Max 90 trainers. ... nikeshoes Nike Air Max -> Nike Air Max 90 (Note Mens model size 41 42 43 44 45 46.Nike shoes buy, nike shoes wholesale, buy nike shoes from china nike shoes wholesale ... www.fashhion4biz.com ,Nike Running shoes,nike shox and nike air max Running shoes, nike shox tl nz r4 turbo monster running shoes,nike air max tn,Puma - Puma Speed Cat. Nike shoes wholesale: Puma Speed Cat men's women's trainers sneakers basketball shoes running shoes,Nike Air Max 2003-Nike Air Max 2003 Trainers,Nike Air Max 2003 Shoes. ... Nike Air Max 2003 cheap discount shoes nike wholesale and sale to nike shop and nike store.Nike Air Max - Nike Air Max 2004 trainers. Nike shoes wholesale: Nike Air Max ... Nike Air Max 2003 cheap discount shoes nike wholesale and sale to nike shop and nike factory.Nike Air Jordan 3,nike jordan 3 retro shoes,nike air jordan 3 retro sneakers, Nike air jordan 3 shoes wholesale: Nike Air Jordan 3 men's women's trainers sneakers ,Nike Shox - Nike Shox TL NZ R4 R5 Turbo Monster Nike shoes wholesale. We wholesale nike shoes: Nike Shox TL, Nike Shox NZ, Nike Shox R4, Nike Shox R5, Nike Shox Nike Air Dunk - Nike Air Dunk High. Nike shoes wholesale: Nike Air Dunk High men's women's trainers sneakers running shoes.Nike Air Max 97, Nike Womens Air Max 97 trainers, nike mens air max 97 trainers, nike air max 97 running shoes sell cheap with discount,Nike Air Force 1 - Nike ... Nike Air force 1 High cheap discount shoes nike wholesale and ... We also sale and wholesale nike shoes other styles:nike air we sell cheap Nike Air Max 95 shoes and trainers for womens, mens and for running, trainning, tennis with all black color, pink color,red, blue..with discount,Nike air jordan shoes for wholesale, We wholesale ans sale nike air jordan Basketball shoes, buy quality of nike air jordan running shoes trainers sneakers for our ...Nike cheap shoes, we sale nike shoes in cheap price, buy cheap nike shoes Adidas. Adidas shoes, Adidas wholesale, Adidas shop, Adidas store, Adidas goodyear, Adidas TMAC, Adidas Running shoes,we wholesale and sale cheap discount Adidas.Nike Dunk - Nike Air Dunk. Nike Dunk Air Dunk Low Mid High Nike shoes wholesale. We wholesale Nike Dunk Air Dunk Men's Women's shoes wholesale at cheap discount price,Nike Air Rift - Nike Rift Air Rift Nike shoes wholesale. We wholesale nike shoes; Nike Rift shoes, Nike Air Rift shoes.Puma - Puma Joggers. Nike shoes wholesale: Puma Joggers men's women's trainers ... Puma Joggers cheap discount shoes nike wholesale and sale to nike shop and nike Adidas - Adidas Shoes. Nike shoes wholesale: Adidas Shoes men's women's trainers ... Adidas Shoes cheap discount shoes nike wholesale and sale to nike shop and nike Shoes. Nike Air Max. Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike Air Max 95 ... Nike Air force 1 Low. Nike Air force 1 High. Nike Air Jordan Nike Air Max Nike Air Max 360 95 97 2003 Tn Plus ... Nike Air Max 360, Nike Air Max 95, Nike Air Max 97, Nike Air Max 2003, ... www.fashion4biz.com ,Nike Air Jordan 2, Nike Jordan 2 Retro Shoes Nike Air Jordan 2 shoes wholesale: Nike Air Jordan 2 men's women's trainers sneakers basketball shoes running shoes,Nike Air Max - Nike Air Max 2005, Nike Air Max 2005 Trainers. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ,Nike Air Jordan 11 Retro- Nike Air Jordan XI Retro. ... Nike Air Jordan 11 cheap discount shoes nike wholesale and sale to nike shop andJordan 5-Jordan V,Nike Air Jordan 5 V- Nike Air Jordan 5. Nike air jordan 5 shoes wholesale: Nike Air Jordan 5 men's women's trainers sneakers basketball shoes ,Nike Air Force 1 - Nike ... Nike Air force 1 Low cheap discount shoes nike wholesale and ... We also sale and wholesale nike shoes other styles:nike air max ...Nike Shox Turbo- Nike Shox Turbo Oh+. Nike Shox Trubo shoes . ... We also sale and wholesale Original,Retro,Retro + ,Re-Retro +,Re-Retro Laser,Nike Shox - Nike Shox R4. Nike shoes wholesale: Nike Shox R4 men's women's ... Nike Shox R4 cheap discount shoes nike wholesale and sale to nike shop and nike ,Nike Air Jordan 12- Nike Air Jordan Xii. Nike Air Jordan 12 Retro shoes wholesale: Nike Air Jordan 12 men's women's trainers sneakers basketball shoes running ...Nike Air Max - Nike Air Max TN Plus. Nike shoes wholesale: Nike Air Max TN Plus ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Shoes. Nike Air Max. Nike Air Max TN Plus. Nike Airwholesale: Nike Shox ... Nike Shox Turbo oh, iv,iii shoes here at cheap price from wwww.fashion4biz.com ...Nike Air Dunk - Nike Air Dunk Low. Nike shoes wholesale: Nike Air Dunk Low men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ,Jordan 4 - Jordan 4 retro, Jordan iv retro sneakers Max 90. Nike Air Max 91. Nike Air Max 95 ... Nike Air force 1 Low. Nike Air force 1 High. Nike Air Jordan Nike Air Max Vends Nike Air Max TN Requin Chaussures. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Air Max 360, Nike ... Nike Air Max 360 cheap discount shoes nike wholesale and sale ... We also sale and wholesale nike Air Max shoes other styles:Nike Nike shop wholesale nike shoes include: Nike air jordan, Nike air dunk, Nike shox tl nz r4 turbo monster, Nike air ... Nike Replica shoes wholesale, wholesale replica shoes nike timberland Nike Shox - Nike Shox TL. Nike shoes wholesale: Nike Shox TL ... Get your cheap Nike Shox tl shoes for mens and womens at www.fashion4biz.com Nike Air Jordan - Nike Air Jordan XXI 21. Nike Air Jordan 21 XXI 11 3 4 5 6 7 20 ... We wholesale nike air jordan 21 1 2 3 4 5 6 8 9 10 11 12 13 14 17 18 19 20 21 22 retro cards.Prada - Prada Americas Cup. Nike shoes wholesale: Prada Americas Cup men's women's trainers sneakers basketball shoes running shoes. Prada Americas Cup cheap Nike Shox - Nike Shox BMW. Nike shoes wholesale: Nike Shox BMW men's women's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Shox R5- Nike Shox R5 Shoes. Nike shoes wholesale: Nike Shox R5 men's ... Nike Shox R5 cheap discount shoes nike wholesale and sale to nike shop and nike ...BapeSta - BapeSta Shoes. Nike shoes wholesale: BapeSta Shoes men's women's trainers sneakers basketball shoes running shoes. BapeSta Shoes cheap discount shoes nike Nike Air Jordan Xvi- Nike Air Jordan 16. Nike Air Jordan 16 retro shoes wholesale: Nike Air Jordan 16 men's women's trainers sneakers basketball shoes running shoes,Nike Shox 3- Nike Shox TL III. Nike shoes wholesale: Nike ... Get your cheap Nike Shox TL 3 III with wholesale price at www.fashion4biz.com,Nike Shox Monster - Nike Shox Monster Shoes. Nike Shox Monster shoes wholesale: ... and Womens Nike Shox Monster shoes at www.fashion4biz.com Nike Air Jordan 6 shoes- Nike Air Jordan 6 retro sneakers. ... jordan 6 shoes and sneakers Nike Air Max - Nike Air Max 91. Nike shoes wholesale: Nike Air Max 91 men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Air Jordan Dub Zero for wholesale, Nike Air Jordan dub zero shoes, Nike Air ... Shoes ID: JDB-02. Air Jordan Dub- Zero. Nike Air Jordan 5- Nike Air Jordan 5 v retro shoes. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ...BapeSta,A baping ape sta,Baping Sta,Bape sta,shoes,shop,store,sale,wholesale ... Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike Air Max 95. Nike Air ...Puma shoes, wholesale and sale Puma shoes from our puma shop puma store, wholesale and sale Puma shoes sizes include mens women's mens womens.Nike Air Jordan 8 sneakers-Nike Air Jordan VIII Shoes. ... Nike Air Jordan 8 cheap discount shoes nike wholesale and sale to nike shop and Nike Air Max - Nike Air Max LTD. Nike shoes wholesale: Nike Air Max LTD men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ...Nike Shox - Nike Shox NZ. Nike Shox Nz shoes wholesale: Nike Shox NZ men's .. Nike Shox NZ cheap discount shoes nike wholesale and sale to nike shop and nike We Sell Air Jordan 1 Shoes, Nike Air Jordan 1 Retro shoes at cheap price for wholesale and ... Nike Air Jordan 1, Nike Air Jordan 1 Retro for Mens.Nike Air Max , Nike Air Max 95. Nike shoes wholesale: Nike Air Max 95 men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max.Nike Shox TL II 2, Nike Shox TL 2, Nike Shox TL II, Nike Shox TL 2 II running shoes, We wholesale Litmited nike shox TL 2 II mens' women's shoes.Nike Air Max 97, Nike Womens Air Max 97 trainers. ... Nike Air Max 97 cheap discount shoes nike wholesale and sale to nike shop and Nike Air Max 90, Nike Air Max 90 running, Nike Air Max 97 Women's Trainer, Nike Air Max 90 shoes. ... We can Produce shoes in all sizes : Kids shoes , Big size US 14 US15 Prada shoes, Prada shoes wholesale, Prada Americas Cup shoes wholesale. ... Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike Air Max 95. Nike Air Max 97 Nike Shox - Nike Shox Turbo. Nike shoes wholesale: Nike Shox Turbo men's women's ... Nike Shox Turbo cheap discount shoes nike wholesale and sale to nike shop and Nike Air Max 90, Nike Air Max 90 running Trainers, Nike Air Max 90 shoes. ... Nike Air Max 360, Nike Air Max 360 running, nike air max 360 Shoes, Nike air max 180.Nike Air Jordan - Nike Air Jordan 8 sneakers. Nike shoes wholesale: Nike Air Jordan 8 men's women's trainers sneakers basketball shoes running shoes. Nike Air,Nike air jordan shoes for wholesale, We wholesale ans sale nike air jordan Basketball shoes, buy quality of nike air jordan running shoes trainers sneakers for our.Prada shoes, Prada shoes wholesale and sale, buy replica prada shoes from our prada shop store. ... Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike ,Evisu T- shirts,Gino Green Global t -shirts Lacoste polo china wholesale,Polo shirts t-shirts Edhardy chanel AF bape CD evisu shirt B.R.M t-shirts Dsquared,LRG tshirts,lacoste shirts t-shirts g-star and BBC,DG,burberry t-shirts,shirt china wholesale,china t-shirts at cheap price,factory wholesale price,nike,polo for child,Sean John,prada,GUINT,CROPPED HEADS armani,10 deep t-shirt,COOGI,juicy t- shirts desquared woman t-shirt,callaway-golf,baby woman t- shirts,artfull dodger,adidas,seven shirts t-shirts NBA jerseys NFL jersey,nba jersey china factory wholesale,discount nfl jersey china suppliers. lacoste t-shirts Made In China Products,lacoste t-shirts China Suppliers and China Manufacturers, lacoste t-shirts China wholesale. Red monkey jeans evisu edhardy Made In China edhadry jeans bape hoody bape bbc hoodies Products,evisu jeans China Suppliers and China Manufacturers,edhardy jeans China Salers,seven jeans China Buyers,evisu jeans manufacturer,evisu factory wholesale.cheap evisu jeans,discount diesel jeans.replica evisu jeans,china wholesale evisu boss jeans.cheap red monkey jeans,discount BBC jeans, wholesale ape jeans, ANTIK jeans,DG jeans,TAVERNITI SO JEANS china suppliers Levis jeans,take two jeans,bape Diesel jeans factory wholesale ,artful dodger green bbc global jeans,seven jeans,true religion jeans rock republic jeans evisu jeans manufacture edhardy jeans D&G woman Jeans rock republic woman jeans people for peace jeans,buy wholesale sale sell cheap jeans men's.Wholesale replica designer Handbags, replica knockoff designer handbag, gucci,handbag,coach handbag,chanel handbag. coach handbag,louis vuitton,handbag,Cheap gucci,handbag wholesale,discount handbag prada,fendi handbag china wholesaler,burberry handbag factory,wholesale designer handbag, OEM factory dooney and bourke handbag in china, chloe handbag cheap,handbag dior,handbag lv replica handbag,juicy couture handbag dooney and burke replica handbag replica knockoffs fake handbag marc jacobs replic,Cellular Phones, Cell Phones, Wireless Phones, Wholesale Cell Phones, Wholesale, Nokia N95, wholesale price, dropship, import and export deal, stock details ,Nokia N95 at Wholesale Price for exporters from outside of China.China Distributor/Wholesaler of Nokia N95, 8800, N93, N93i, N90, N77, N75, ... wholesale replica nokia sirocco motorola samsung,apple iphone vertu.Sell Mobile Phone N95, Mobile Phone, Nokia Phone, Cell Phone ... wholesale Mobile Phone supplier in China,wholesale :Mobile Phone,Nokia N95,Nokia ,Nokia N95, 8800, N93, N93i, N90, N77, N75, 5700xm, Samsung, Motorola, Dopod, Blackberry, GSM, Dual Sim Card Cell Phone. Get ... wholesale ... Mobile Phones ,Latest Mobile Phones. Nokia 5700. Nokia N95 ... on mobile phones | wholesale Nokia phone deals | wholesale Motorola phone deals From jeff at schwabcenter.com Thu Mar 13 15:37:09 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 13 Mar 2008 12:37:09 -0700 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> References: <13tgrqb132if842@corp.supernews.com> <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> Message-ID: Paddy wrote: > On Mar 13, 7:03 pm, Jonathan Gardner > wrote: >> On Mar 12, 6:37 pm, Carl Banks wrote: > > <> >> And leave out the magical -p and -n. If you want to iterate through a >> file, "for line in sys.stdin:". > > Or better still: > > import fileinput > for line in fileinput.input(): > process(line) I write maybe a dozen one-liners a day. It's not practical to do this with Python, or at least it's not nearly as convenient as Perl. I'm fine with the magic. Abusing the magic is another story; Perl language features are meant to be used in particular contexts, and BEGIN blocks are rarely if ever necessary in Perl modules. From malkarouri at gmail.com Sat Mar 8 17:20:40 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 14:20:40 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <47D2C25C.9050400@v.loewis.de> Message-ID: <6fd3179f-1b32-4593-a552-43e73e091a17@34g2000hsz.googlegroups.com> On Mar 8, 4:44?pm, "Martin v. L?wis" wrote: ... > Notice that the language specification *deliberately* does not > distinguish between deletion of earlier and later items, but > makes modification of the sequence undefined behavior to allow > alternative implementations. E.g. an implementation that would > crash, erase your hard disk, or set your house in flames if you > confront it with your code still might be a conforming Python > implementation. Really appreciated, Martin. It was exactly the *deliberately* part I am interested in. Settles it for me. Thanks, Muhammad Alkarouri From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 04:16:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 08:16:31 -0000 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> <69175d52-a701-40f2-9803-0e422e8d4f8f@d62g2000hsf.googlegroups.com> Message-ID: <13umluvs1vdor02@corp.supernews.com> On Wed, 26 Mar 2008 00:55:22 -0700, Arnaud Delobelle wrote: [snip] > Except it only *appears* to work. What happens if were store the > instances in a list and then execute them all in one go? Ah yes, nicely spotted. Another solution would be to use a proper factory function: def factory(record): def f(n): return (record + " ")*n return f class MyClass(object): pass records = ["spam", "ham"] instances = [] for record in records: instance = MyClass() setattr(instance, 'execute', factory(record)) instances.append(instance) for instance in instances: instance.execute(5) -- Steven From jkugler at bigfoot.com Fri Mar 14 15:44:05 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 14 Mar 2008 11:44:05 -0800 Subject: How to import custom python file in python server page (psp) ? References: <60bb95410803140415x621b5b23w75b83013997c750b@mail.gmail.com> Message-ID: James Yu wrote: > Hi folks, > > I prepared a python script for dynamically get the absolute paths of the > files in certain folder. > Then I tried to invoke that function from my web server in a .psp file > like this: > > 1 > 2 > 3 asdfasdfasdfa > 4 > 5 <% > 6 import glob > 7 import os > 8 *import Helper > * 9 > 10 body = '' > 11 top = 'asdfasdfasdfa' > 12 links = {} > 13 *Helper.GetLinks(top=top) > * 14 *paths = Helper.GenLinkPath(links) > * 15 body = paths > 16 %> > 17 <%=body%> > 18 > 19 > > However, this is the error message I received when I open the page in a > browser: > >> Mod_python error: "PythonHandler mod_python.psp" >> >> Traceback (most recent call last): >> >> File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, >> in HandlerDispatch >> result = object(req) >> >> File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 302, in >> handler >> p.run() >> >> File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 213, in >> run >> exec code in global_scope >> >> File "/var/www/.cyu021/.pic/index.psp", line 8, in >> import Helper >> >> ImportError: No module named Helper > > > *PS. I put Helper.py and index.psp in the same dir > * > Thanks in advance, What is the import path? The current directory in PSP might not be the directory in which the .psp file resides. Print out sys.path before you import your helper module to see what paths you're dealing with. j From sjmachin at lexicon.net Fri Mar 21 18:47:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 15:47:43 -0700 (PDT) Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> Message-ID: <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: > [1] Just one example:http://docs.mootools.net/Class/Class.js Mootools being something a coworker might use? From schiz at lon.don Sun Mar 2 05:25:49 2008 From: schiz at lon.don (Schizoid Man) Date: Sun, 02 Mar 2008 10:25:49 +0000 Subject: Beginner's assignment question In-Reply-To: References: Message-ID: Lorenzo Gatti wrote: > On Mar 1, 3:39 pm, Schizoid Man wrote: >> As in variable assignment, not homework assignment! :) >> >> I understand the first line but not the second of the following code: >> >> a, b = 0, 1 >> a, b = b, a + b >> >> In the first line a is assigned 0 and b is assigned 1 simultaneously. >> >> However what is the sequence of operation in the second statement? I;m >> confused due to the inter-dependence of the variables. > > The expressions of the right of the assignment operator are evaluated > before assigning any new values, to the destinations on the left side > of the assignment operator. > So substitutig the old values of a and b the second assignment means > > a, b = 0, 0 + 1 > > Simplifying the Python Reference Manual ("6.3 Assignment Statements") > a little : > > assignment_stmt ::= target_list "="+ expression_list > > An assignment statement evaluates the expression list (remember that > this can be a single expression or a comma-separated list, the latter > yielding a tuple) and assigns the single resulting object to each of > the target lists, from left to right. > > [...] > > WARNING: Although the definition of assignment implies that overlaps > between the left-hand side and the right-hand side are `safe' (for > example "a, b = b, a" swaps two variables), overlaps within the > collection of assigned-to variables are not safe! For instance, the > following program prints "[0, 2]": > > x = [0, 1] > i = 0 > i, x[i] = 1, 2 > print x > > Lorenzo Gatti Thank you for the explanation. I guess my question can be simplified as: First step: a, b = 0, 1 No problem here as a and b are assigned values. Second step: a, b = b, a + b Now my question is does b become a + b after a becomes 1 or while a stays at 0? As the assignment occurs simultaneously I suppose the answer is while a stays at 0. Thank you. From grante at visi.com Sat Mar 22 11:44:31 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Mar 2008 15:44:31 -0000 Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> <5bd9b02a-958b-452d-9e20-c10e4c29f9e4@i29g2000prf.googlegroups.com> Message-ID: <13uaaavi55n7d9b@corp.supernews.com> On 2008-03-22, harrelson wrote: >>> proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) >>> stderr_value = proc.communicate()[0] >>> print stderr_value >> dialog displays the widget on stdout. You've connected stdout >> to a pipe, so you're not going to see anything displayed unless >> you read data from the stdout pipe and write it to the terminal. > > Reading this tutorial on subprocess: > > http://blog.doughellmann.com/2007/07/pymotw-subprocess.html > > led me to believe this was exactly what I was doing. Ah, my mistake. I believed you when you named the variable "stderr_value". ;) I've never used the communicate() method, but according to that tutorial: "The communicate() method reads all of the output and waits for child process to exit before returning. And the lib references says: communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). The key is that it doesn't return until after the subprocess has terminated. So, you're reading stdout and putting it in the variable you named stderr_value. After the dialog exits, you then print the stdout string (which contains the widget's "display" data). Since the widget has already exited, that string contains both the initial display _and_ the escape sequence that clears the screen and restores it. So, you just see a flash of blue. If you want to be able to see and interact with the widget, you need to leave stdout connected to the terminal while the widget is running. Try this: ------------------------------------------------------------ import subprocess command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" "4 this and that"' proc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE) stdout,stderr = proc.communicate() print stderr ------------------------------------------------------------ NB: using shell=True introduces a number security holes and adds the overhead of starting a shell. It's good practice to avoid it if you don't actually need a shell (you don't). However, without it you need to split up the command line explicitly: ------------------------------------------------------------ import subprocess command = ('/usr/bin/dialog','--clear','--title','title', '--menu','text','20','50','5', 'a','this and that', 'c','3 this and that', 'b','2 this and that', 'd','4 this and that') proc = subprocess.Popen(command, stderr=subprocess.PIPE) stdout,stderr = proc.communicate() print stderr ------------------------------------------------------------ If you're generating the commands programatically, it's usually simpler to generate them as tuples as shown in the second example anyway. -- Grant Edwards grante Yow! I joined scientology at at a garage sale!! visi.com From stugots at qwest.net Sun Mar 2 13:01:45 2008 From: stugots at qwest.net (John DeRosa) Date: Sun, 02 Mar 2008 10:01:45 -0800 Subject: Beautiful Code in Python? References: Message-ID: On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: >Hi, > >Have you ever seen Beautiful Python code? >Zope? Django? Python standard lib? or else? > >Please tell me what code you think it's stunning. Just about any Python code I look at. From israelu at elbit.co.il Sun Mar 30 07:42:46 2008 From: israelu at elbit.co.il (iu2) Date: Sun, 30 Mar 2008 04:42:46 -0700 (PDT) Subject: License of Python Message-ID: Hi guys, I'd like to use Python in a commercial application. In fact I would like to write the application entirely in Python. But I think I wouldn't like telling what language the application is written in. The problem is that including Python's license in the binary, which as I understand is a must do, reveals that the appliation is based on Python. I'll appreciate your advices about this Thanks iu2 From noname9968 at gmail.com Wed Mar 19 13:37:11 2008 From: noname9968 at gmail.com (Alex9968) Date: Wed, 19 Mar 2008 20:37:11 +0300 Subject: Tkinter.Text widget - how to get text cursor position? Message-ID: <47E14F47.6000202@gmail.com> Is it possible to get position (in numbers) of the insertion cursor? As I understood, Text widget uses mark named INSERT to store it, which is available globally by just referencing INSERT, but how could I get actual coordinate numbers of the mark? I need this because I want not just to insert string at, but to examine text before and after the insertion cursor. I can probably use .get() to extract the halves of text before and after cursor, but it'd be better just to know the position. Thanks From asmodai at in-nomine.org Sat Mar 29 13:33:38 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 29 Mar 2008 18:33:38 +0100 Subject: Why prefer != over <> for Python 3.0? In-Reply-To: <7x3aq9212z.fsf@ruckus.brouhaha.com> References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> <7x3aq9212z.fsf@ruckus.brouhaha.com> Message-ID: <20080329173338.GY80617@nexus.in-nomine.org> -On [20080329 13:01], Paul Rubin ("http://phr.cx"@NOSPAM.invalid) wrote: >Yes, what I mean is that some languages (e.g. Ada, Haskell) use /= for >nonequality. /= is understandable given how it looks like a digraph for ? (U+2260) and I am guessing that was the intent. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Cum angelis et pueris, fideles inveniamur. Quis est iste Rex gloriae..? From mr.names at gmail.com Fri Mar 14 07:53:06 2008 From: mr.names at gmail.com (mr.names@gmaIL.COM) Date: Fri, 14 Mar 2008 04:53:06 -0700 (PDT) Subject: The best computer solutions Message-ID: <2f53622c-9c7b-4328-adac-b7b2a5b1eb30@d45g2000hsc.googlegroups.com> http://r8p.org/upload/213.html From castironpi at gmail.com Wed Mar 12 02:17:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:17:45 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> <72f2856c-eeca-44f2-849d-912889d26a79@d21g2000prf.googlegroups.com> <13tescq3n0j6qda@corp.supernews.com> Message-ID: <43924119-4e4d-42f1-aaf1-90ae743d8cf9@u69g2000hse.googlegroups.com> > > Are there any that aren't persistent? > > ? ? ? ? SQLite -- when opening a "memory" database rather than giving it a > physical file. {I'm a tad too busy to look up the format of the memory > parameter, but it shouldn't be too difficult to find it} What? If I wanted to code string literals, I'd use exec. Where's the real one? From see.signature at no.spam Wed Mar 26 11:54:21 2008 From: see.signature at no.spam (Eric Brunel) Date: Wed, 26 Mar 2008 16:54:21 +0100 Subject: Tkinter menus from keyboard References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: On Wed, 26 Mar 2008 13:45:29 +0100, Guilherme Polo wrote: > 2008/3/26, MartinRinehart at gmail.com : >> Tkinter defaults to, for example, Alt+f = File (if File is your first >> menu name starting with "f"). >> >> I'd like to assign my own letters and have them underscored, per the >> universal standard. Can this be done? >> > > Set the underline option to the index of the desired letter BTW, this "standard" is not universal at all: e.g, there is no such convention on Macs. Not (only...) nitpicking: if your application has to run on a Mac, it may look weird if you use this option... But I never tested how it was handled on Macs. My $0.02... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From israelu at elbit.co.il Mon Mar 17 20:05:04 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 17 Mar 2008 17:05:04 -0700 (PDT) Subject: Tkinter right-to-left windows Message-ID: Hi, I use tix NoteBook, and I need the tabs arranged right to left. Is it possible? Thanks From stefan_ml at behnel.de Tue Mar 11 12:01:52 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 Mar 2008 17:01:52 +0100 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: <47D6ACF0.5060300@behnel.de> Sion Arrowsmith wrote: > And before you blame wx* for crashes: what platform was this on? > Because my experience was that wx on GTK was significantly more prone > to glitches than on Windows (through to wxglade being unusably crashy) > -- if the underlying toolkit has problems, that's going to be > reflected in wx. :) Interesting. This was actually on GTK. Although I would still blame at least the wxWidgets-GTK bindings here. I never had any problems with GTK in my life. Stefan From nagle at animats.com Sun Mar 23 02:15:00 2008 From: nagle at animats.com (John Nagle) Date: Sat, 22 Mar 2008 23:15:00 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <7xlk4anjcn.fsf@ruckus.brouhaha.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> Message-ID: <47e5f31f$0$36325$742ec2ed@news.sonic.net> Paul Rubin wrote: > Jeff Schwab writes: >> I've been learning a fair amount about functional programming >> recently, mostly because compile-time C++ turns out to be a pure >> functional programming language. Where should I go for a solid >> grounding in lambda-calculus? > > For PL theory in general, try this: > > http://www.cs.cmu.edu/~rwh/plbook/book.pdf What a mess. That's some professor inventing his very own variation on predicate calculus and writing a book using his own notation and terminology. There's no sign of footnotes or references to prior work. The notation doesn't seem to do anything not previously possible; it's just different. Back when I was doing program verification work, we used to refer to stuff like that as the "logic of the month club". John Nagle From http Tue Mar 18 07:00:19 2008 From: http (Paul Rubin) Date: 18 Mar 2008 04:00:19 -0700 Subject: finding items that occur more than once in a list References: Message-ID: <7xwso0z48s.fsf@ruckus.brouhaha.com> Simon Forman writes: > Is there a more efficient way to do this? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263 From andre.roberge at gmail.com Sat Mar 22 13:02:01 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 22 Mar 2008 10:02:01 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <9ca7e0a0-d686-4c69-bac0-5f4a1447aac3@c19g2000prf.googlegroups.com> On Mar 22, 1:40 pm, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. Yes. You'll probably get 100 positive answers! Check out the edu-sig mailing list for discussions on the topic. And you may want to check out rur-ple.sourceforge.net, where "ple" stands for "Python Learning Environment". Andr? From rajb at rice.edu Mon Mar 31 16:57:05 2008 From: rajb at rice.edu (Raj Bandyopadhyay) Date: Mon, 31 Mar 2008 15:57:05 -0500 Subject: Question about overloading of binary operators In-Reply-To: References: Message-ID: <47F15021.6000603@rice.edu> Hi Here's a simple class example I've defined ############################# class myInt(int): def __add__(self,other): return 0 print 5 + myInt(4) #prints 9 print myInt(4) + 5 #prints 0 ############################# The Python binary operation function (binary_op1() in Objects/abstract.c) states the rules for binary operations as follows: v w Action ------------------------------------------------------------------- new new w.op(v,w)[*], v.op(v,w), w.op(v,w) new old v.op(v,w), coerce(v,w), v.op(v,w) old new w.op(v,w), coerce(v,w), v.op(v,w) old old coerce(v,w), v.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type It seems that my example should fall in case 1, and in both cases, the __add__ function of the subclass should be used, returning 0, regardless of operand order. However, in one case the subclass's function is used and not in the other case. What am I missing here? Thanks Raj From MadComputerGuy at gmail.com Mon Mar 10 19:32:26 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Mon, 10 Mar 2008 16:32:26 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> Message-ID: <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> On Mar 10, 12:10 pm, Mensanator wrote: > On Mar 10, 12:48 am, Gabriel Genellina wrote: > > > On 10 mar, 02:08, Nathan Pinno wrote: > > > > How do I factor a number? > > If factoring is actually what you want, the sympy module can do it. > > >>> n = 85085**3 > >>> print n > 615969217989125 > >>> import sympy > >>> f = sympy.factorint(n) > >>> f > > [(5, 3), (7, 3), (11, 3), (13, 3), (17, 3)]>>> ff = [[i[0]]*i[1] for i in f] > >>> ff > > [[5, 5, 5], [7, 7, 7], [11, 11, 11], [13, 13, 13], [17, 17, 17]]>>> fff = sympy.flatten(ff) > >>> fff > > [5, 5, 5, 7, 7, 7, 11, 11, 11, 13, 13, 13, 17, 17, 17] > > Provided that your needs are modest. It claims to be > able to handle 10 digit factors, but it certainly can't > handle numbers of this magnitude: > > 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 > > As it takes a couple hours of run-time only to crash > with an out of memory error. > > If you need to handle something like that, you may want to > get factor.exe which is part of the MIRACL library. The library > is in C and doesn't have a Python interface, but you can run > the .exe from Python and capture the output. > > Keep in mind two things: factor.exe doesn't have consistent > output making it more difficult to interpret the captured > output. I re-compiled my copy of factor.exe to provide > consistent output. > > The other thing is that factor.exe sometimes gets confused > claiming a number is composite that factor.exe is fully > capable of factoring. Luckily this can be easily fixed in > the Python program that calls it. > > In the following example, if factor!.exe (my re-compiled > version) returns any composites, I simply feed them back > into the program until all are factored or determinened to > be truly intractable. > > Note the times. If you have serious factoring needs, the > MIRACL solution is better than sympy. > > ## ======================================== > ## Phase 1 > ## ['COMPOSITE_FACTOR', > '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] > ## > ## ['PRIME_FACTOR', '37'] > ## ['PRIME_FACTOR', '43'] > ## ['PRIME_FACTOR', '167'] > ## ['COMPOSITE_FACTOR', '507787751'] > ## ['PRIME_FACTOR', '69847'] > ## ['PRIME_FACTOR', '30697'] > ## ['PRIME_FACTOR', '89017'] > ## ['PRIME_FACTOR', '3478697'] > ## ['PRIME_FACTOR', '434593'] > ## ['PRIME_FACTOR', '49998841'] > ## ['PRIME_FACTOR', '161610704597143'] > ## ['PRIME_FACTOR', '14064370273'] > ## ['COMPOSITE_FACTOR', '963039394703598565337297'] > ## ['PRIME_FACTOR', '11927295803'] > ## > ## 0.860000133514 seconds > ## ======================================== > ## Phase 2 > ## ['COMPOSITE_FACTOR', '507787751'] > ## > ## ['PRIME_FACTOR', '29819'] > ## ['PRIME_FACTOR', '17029'] > ## > ## 0.0780000686646 seconds > ## ======================================== > ## Phase 3 > ## ['COMPOSITE_FACTOR', '963039394703598565337297'] > ## > ## ['PRIME_FACTOR', '518069464441'] > ## ['PRIME_FACTOR', '1858900129817'] > ## > ## 0.0469999313354 seconds > ## ======================================== > ## > ## Factoring complete > ## > ## PRIME_FACTOR 37 > ## PRIME_FACTOR 43 > ## PRIME_FACTOR 167 > ## PRIME_FACTOR 17029 > ## PRIME_FACTOR 29819 > ## PRIME_FACTOR 30697 > ## PRIME_FACTOR 69847 > ## PRIME_FACTOR 89017 > ## PRIME_FACTOR 434593 > ## PRIME_FACTOR 3478697 > ## PRIME_FACTOR 49998841 > ## PRIME_FACTOR 11927295803 > ## PRIME_FACTOR 14064370273 > ## PRIME_FACTOR 518069464441 > ## PRIME_FACTOR 1858900129817 > ## PRIME_FACTOR 161610704597143 > ## > ## ======================================== > > > I mean how do I translate x! into proper > > > Python code, so that it will always do the correct math? > > > Do you want to compute x! (factorial of x)? That is, you want a > > program that given a 4, returns 24? > > Think how would you compute it by hand and try to write the same thing > > using Python instructions. > > > If you come with a program and have a specific problem someone here > > will be able to help you, but don't expect your homework to be done > > for free... > > > -- > > Gabriel Genellina Thanks on the factoring bit, but I did mean factorial, not factoring. How do I code that correctly, so that I can figure the following equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax error and highlight the !. So it would be nice to find a way to solve such a problem. Thanks, Nathan P. From castironpi at gmail.com Sun Mar 9 19:51:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 16:51:40 -0700 (PDT) Subject: Returning values from function to Python shell/IPython References: Message-ID: <91fbb488-4ada-4fea-864b-c5c33c5b4386@e39g2000hsf.googlegroups.com> > > ?> well after all it's a function so the only ways you can get things out > > ?> of it are: > > ?> - return a dict with all the objects > > ?> - use global (very messy) > > ?> - use a decorator to do either of the above. > > > ?Messy, all of those... :(. > > > ?> on the other hand have you consider using a proper test package? > > ?> instead of inspecting the objects manually from the shell you could > > ?> make it all automatic. with assert statements. you could use the std. > > ?> python testing moduleshttp://docs.python.org/lib/development.htmlor > > ?> something less verbosed like nose > > > ?Usually, I'm using standard Python testing modules, but sometimes that is > > ?just an overkill. Sometimes I like to do 'exploratory programming', > > ?especially in the early phases of development - create a bunch of objects I > > ?want to play with and do that from IPython. Only way I found out to > > ?somewhat automate this procedure is to have a function that creates all of > > ?the test objects, and then raises an exception at the end. IPython starts > > ?ipdb, so I can work with the objects the function created (without copying > > ?them back to the shell). But this somehow looks too hack-ish for me, so I > > ?was wondering if there was an alternative... > > ohhh if that is the case then what you are doing seems to be the > optimal. Just have module lvl code ran the testing in fact I don't > even put those into the if __name__, the reason is that this is just > temp testing that will later become real unit testing, and will never > hit a production app. it gives you the most flexibility. While you're at it, can you call up prior source, and edit it? BASIC had line numbers: 10 def f( a ): 20 return a+ 1 >>> 15 print( a ) 10 def f( a ): 15 print( a ) 20 return a+ 1 >>> 15 print( a ) 10 def f( a ): 15 print( a ) 20 return a+ 1 '''Interactives could some day have this too:''' >>> edit f Object f opened in editor >>> close Object f written back. Elapsed time 5 minutes. >>> From steve at holdenweb.com Sun Mar 2 09:32:18 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 09:32:18 -0500 Subject: tcp In-Reply-To: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: 7stud wrote: > On Mar 2, 6:09 am, Gif wrote: >> i have this small script which after some router configurations works. >> >> ########################################################## >> >> #! /usr/bin/python >> import socket >> >> HOST = '' >> PORT = 1515 >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> s.bind((HOST, PORT)) >> s.listen(1) >> conn, addr = s.accept() >> conn.send('HTTP/1.1 200 OK\r\n') >> conn.send('Content-Type: text/html\r\n') >> conn.send('Server: test/1.0\r\n\r\n') >> conn.send('test') >> s.close() >> >> ########################################################## >> >> as you see it listens to 1515 until a connection is established and >> then it accepts it... >> the problem is that when it accepts the connection it sends those >> strings and exits, but then it exits the program. i want it to listen >> to 1515 then accept a connection, send.. and then listen to the port >> again and again until new connections are found. >> >> i've been struggling with try..except,while and all kinds of loops but >> always new erros pop up, or it overflows. > > while True: > conn, addr = s.accept() > ... And now you get to start asking all the interesting questions that come up, like "How do I get my server to respond to multiple requests in parallel?" It's a long road, but it's fun. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From zerty.david at gmail.com Thu Mar 27 18:19:49 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 27 Mar 2008 19:19:49 -0300 Subject: Problems wit List Object Message-ID: <5dc598e30803271519k39440eccj3b9db110f9097b98@mail.gmail.com> Hello all, I have a Class1 that there has a list, and a function that returns this list, In another class I got an instance of this first class, and when I make: obj1 = Class1() list = obj1.getList() I got this exception: traceback (most recent call last): File "xxx", line 184, in onAddErro list = self.errorMgr.getList() TypeError: 'list' object is not callable How can I solve it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu Mar 13 21:15:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 18:15:19 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: On Mar 13, 7:45?pm, castiro... at gmail.com wrote: > On Mar 13, 7:18?pm, Mel wrote: > > > > > > > Diez B. Roggisch wrote: > > >> My understanding is that foo.bar does *not* create a new object. > > > > Your understanding is not correct. > > > >> ?All it > > >> does is return the value of the bar attribute of object foo. ?What new > > >> object is being created? > > > > A bound method. This happens through the descriptor-protocol. Please see > > > this example: > > > > class Foo(object): > > > ? ? def bar(self): > > > ? ? ? ? pass > > > > f = Foo() > > > a = Foo.bar > > > b = f.bar > > > c = f.bar > > > > print a, b, c > > > print id(b), id(c) > > > (What Diez said.) ?From what I've seen, f.bar creates a bound method > > object by taking the unbound method Foo.bar and binding its first > > parameter with f. ?This is a run-time operation because it's easy to > > re-assign some other function to the name Foo.bar, and if you do, the > > behaviour of f.bar() will change accordingly. > > > You can get some very useful effects from these kinds of games. ?You > > can make f into a file-like object, for example, with > > > import sys > > f.write = sys.stdout.write > > > Here, f.write *is* a straight attribute of f, although it's a built-in > > method of the file class. ?It's still bound, in a way, to sys.stdout. > > ? I'm assuming that a different example could create an attribute of f > > that's a bound method of some other object entirely. ?I've verified > > that f.write('howdy') prints 'howdy' on standard output. > > Accordingly, > > f.write= types.MethodType( sys.stdout.__class__.write, sys.stdout ). > > It depends on what you want the implicit first (self) to be-- f or > sys.stdout. > > But how come this works? > > >>> import types > >>> import sys > > >>> class C: > > ... ? ? write= sys.stdout.write > ... ? ? def g( self ): > ... ? ? ? ? ? ? self.write( 'was in \'g\'\n' ) > ...>>> c= C() > >>> c.g() > > was in 'g' > > Shouldn't 'write' be getting extra parameters? ?Sounds fishy, not to > mix metaphors. Ah. Because this doesn't. >>> class C: ... write= sys.stdout.__class__.write #<-- ... def g( self ): ... self.write( 'was in \'g\'\n' ) ... >>> c= C() >>> c.g() Traceback (most recent call last): File "", line 1, in File "", line 4, in g File "c:\programs\python\lib\io.py", line 1236, in write if self.closed: AttributeError: 'C' object has no attribute 'closed' >>> That is, because sys.stdout.write is -not- a user-defined function. What it is, is a bound member function, and only the former is converted/wrapped/bound*, as it is in the subsequent example. */ whatever. From aahz at pythoncraft.com Sat Mar 29 21:47:58 2008 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2008 18:47:58 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: In article <5805ee5f-970f-4b16-a5c5-90ebe0748feb at y21g2000hsf.googlegroups.com>, wrote: > >I don't know if this is the right place to discuss the death of <> in >Python 3.0, or if there have been any meaningful discussions posted >before (hard to search google with '<>' keyword), but why would anyone >prefer the comparison operator != over <>??? Are you asking why Python 3.0 gets rid of one of them or are you asking why != was chosen over <>? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 07:05:11 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 12:05:11 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: References: <47EB6480.2080402@wtf.websiteburo.oops.com> Message-ID: <47eb7f60$0$5151$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Bruno Desthuilliers wrote: >> Gabriel Rossetti a ?crit : (snip) >>> registerServiceAtomic = partial(__registerService, True) >>> registerServiceNonAtomic = partial(__registerService, False) >>> >>> I should pass self when applying partial, but then I can't do that >>> since self is not available there. Does anyone have any ideas? >> >> registerServiceAtomic = partial(__registerService, atomic=True) >> registerServiceNonAtomic = partial(__registerService, atomic=False) >> >> Caveat: you'll have to either invert the order of the atomic and >> service params, or call the partials with named arg for service. >> >> > Ok, thanks, I didn't know you could do that, I though partial was always > left to right It's left to right for positional arguments. Using named arguments, you can pass them in whatever order. > (I had read that about curry) Which 'curry' ?-) From rhh2109 at columbia.edu Sun Mar 2 22:29:07 2008 From: rhh2109 at columbia.edu (Roy H. Han) Date: Sun, 2 Mar 2008 22:29:07 -0500 Subject: Where's GUI for Python? In-Reply-To: <72616FCD61C649DF8E1B1BEAD493EC0F@Hippo> References: <62tvhmF256jk7U1@mid.individual.net> <47C9D33E.9040407@tim.thechases.com> <6a5569ec0803011429q4444ec25o7c235ae80590dff8@mail.gmail.com> <72616FCD61C649DF8E1B1BEAD493EC0F@Hippo> Message-ID: <6a5569ec0803021929u72b49d27v5d32e99f5c9f2857@mail.gmail.com> Hi Konrad, I remember taking a long time in deciding which GUI framework to use last year and I picked wxGlade/wxPython because it seemed mature, easy to use and easy to understand. In the beginning I wasted a lot of time coding the GUI manually but wxGlade lets me use the mouse to arrange the components so that I can focus on writing the event handling code. I mostly don't touch the code that wxGlade auto-generates and I work my code around it. http://wxglade.sourceforge.net/demo/ Sorry I responded to your personal email by mistake. I pressed Reply All in gmail. I don't know who wrote wxGlade or wxPython but both have been real timesavers to me. Roy On Sun, Mar 2, 2008 at 3:50 AM, Konrad Viltersten wrote: > > Konrad, I use wxPython with wxGlade. > > I love wxGlade! > > wxGlade http://wxglade.sourceforge.net/ > > You need to look at this documentation to > > code event handling. wxWidgets: > > http://www.wxwidgets.org/manuals/stable/wx_classesbycat.html > > > > You can also try coding the GUI manually, > > but it is much easier to use wxGlade. > > wxPython > > http://wiki.wxpython.org/AnotherTutorial > > May i ask what's the advantage in using > wxGlade instead of the buil-in Tkinter? > > Also - why did you replied to my private > email instead of to news? Is the choice of > GUI an infected matter among the Python > community, by any chance? > > -- > Regards > Konrad Viltersten > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Mar 10 12:36:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Mar 2008 16:36:53 -0000 Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <13taot5khcl933a@corp.supernews.com> On Mon, 10 Mar 2008 07:39:25 -0700, Gary Herron wrote: > If either is a surprise, then understand that the "is" operator should > probably *never* be used with immutable types. Carl Banks has already mentioned testing for None with "is". The standard idiom for using mutable default arguments goes something like this: def foo(arg=None): if arg is None: arg = [] do_something_with(arg) Another standard idiom that requires "is": sentinel = object() # a special value that isn't None ... if something is sentinel: blah blah blah Mutable or immutable, it makes no difference: "is" is for testing identity, == is for testing equality. If you need to test for identity, use "is". If you need to test for equality, use ==. -- Steven From python at rgbaz.eu Sun Mar 16 09:07:36 2008 From: python at rgbaz.eu (Python) Date: Sun, 16 Mar 2008 14:07:36 +0100 Subject: Python and 3D In-Reply-To: <00a99921-a931-49cf-9bd1-4978d805290f@8g2000hsu.googlegroups.com> References: <00a99921-a931-49cf-9bd1-4978d805290f@8g2000hsu.googlegroups.com> Message-ID: <27BD105D-E720-4F97-B210-E329D3FEED5A@rgbaz.eu> On 15 mrt 2008, at 23:06, Mike Driscoll wrote: > On Mar 15, 3:09 pm, Eric von Horst wrote: >> Hi, >> >> I am looking for Python modules that allow you to manipulate 3D >> objects, more specifically Alias Wavefront .OBJ objects. >> Also, a module that would allow you to vizualize these models and >> rotate them etc.. >> >> The goal is not to build a new renderer or something; just a small >> program that I need to do some manipulations in bulk on a set of OBJs >> >> Any help much appreciated >> >> Eric > > I'm not aware of anything. You might look at pyOpenGL or pyglet. They > should be good for 3D modeling at least. > > Mike ...or have a look at Blender's bpython module: http://www.blender.org/education-help/python/ Arno From michael.wieher at gmail.com Tue Mar 11 15:08:55 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Tue, 11 Mar 2008 14:08:55 -0500 Subject: Obtaining the PyObject * of a class In-Reply-To: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> Message-ID: 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : > > On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > > > "Cooper, Andrew" wrote in message > > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca > ... > > > > | Are there any Python C API experts/SWIG experts out there that can > help > > | me with this issue please. > > > > | I',m currently using SWIG to generate a python interface to a C DLL. > > > > Some people have switched to using ctypes for this, and many other SWIG > > users have stopped reading clp. But I hope someone answers who can. > > > > > Using Pyrex or Cython is likely to be much easier than using SWIG for > this. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Mar 6 15:17:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Mar 2008 21:17:51 +0100 Subject: Ncurses not found - embedded linux In-Reply-To: References: Message-ID: <63b1rjF26p2fkU1@mid.uni-berlin.de> blaine schrieb: > Hello Everyone! > I am hoping that someone out there can help me out with this > problem. We are using a gumstix platform to develop an embedded > system. All that really matters is that it is an ARM processor > running an embedded linux, details to follow. Gumstix has its own > kernel tree that we cross compile for the system. We do have python, > and it has all of the modules that I need except for one. I need > ncurses (module curses). I can't seem to figure out how to get it to > work - and the only documentation I can find is for Windows (because > windows doesn't have ncurses). We have enabled ncurses support in the > kernel menu, and that has not helped. I can't seem to trace down > where we would 'enable' ncurses support? All other modules seem to > work that I've tried (termios, sys, os, etc.) > > Output from python: > [root at gumstix ~]# python > , Feb 20 2008, 11:07:36) > [GCC 4.1.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import curses > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/curses/__init__.py", line 15, in ? > from _curses import * > ImportError: No module named _curses > > [root at gumstix ~]# uname -a > Linux gumstix 2.6.21gum #1 Tue Mar 4 15:31:07 EST 2008 armv5tel > unknown > > [root at gumstix lib]# ls /usr/lib/*curses* > /usr/lib/libcurses.a@ /usr/lib/libncurses.a /usr/lib/ > libncurses.so@ > > [root at gumstix lib-dynload]# ls _* > _bisect.so* _codecs_tw.so* _random.so* > _codecs_cn.so* _csv.so* _socket.so* > _codecs_hk.so* _heapq.so* _testcapi.so* > _codecs_iso2022.so* _hotshot.so* _weakref.so* > _codecs_jp.so* _locale.so* > _codecs_kr.so* _multibytecodec.so* > > I hope this is trivial, and I apologize ahead of time if so. Would > this perhaps be a compilation issue? Something we have to turn on in > the python compile? Usually, you need not only the libraries but also the headers at compilation time. Most probably these were missing. Diez From timr at probo.com Mon Mar 3 01:31:33 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 03 Mar 2008 06:31:33 GMT Subject: SV: Where's GUI for Python? References: <62tvhmF256jk7U1@mid.individual.net> <63038fF23j6foU1@mid.individual.net> Message-ID: <4v5ns3907dqsqgovtuboc3q6qbk93gvf9g@4ax.com> "K Viltersten" wrote: > >As long as we're on the subject, i also wonder >if there's a general concensus on which >technology is recommended in the different >types of projects that are developed. (E.g. >"use A for small/fast fixes, use B for stuff >you'll need to maintain later on".) Are you talking specifically about GUI toolkits? I seriously doubt that anyone routinely uses more than one GUI with Python (although I'm sure there are exceptions). Each of them has a pretty big learning curve to climb, and once you have climbed it, all of the GUI kits will solve the same problems. (Caution: the following contains gross generalities.) If you have ever done GUI programming in Windows using the Win32 API, then wxPython will seem more natural than Tkinter or Qt (although I should point out that all of them work equally well on Windows and Linux). If you have ever done GUI programming in X, or if you have done script with with Tcl/Tk, then it is likely that Tkinter will seem more natural than wxPython. Perhaps the best option is to take a look at some samples, and see what looks more natural to you. wxPython, for instance, has a wonderful set of demos that demonstrate almost every feature of the toolkit. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stargaming at gmail.com Mon Mar 17 12:42:20 2008 From: stargaming at gmail.com (Stargaming) Date: 17 Mar 2008 16:42:20 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> Message-ID: <47de9f6c$0$2657$9b622d9e@news.freenet.de> On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: > For the answer I actually want each asterisk substitutes for exactly one > character. Played around a bit and found that one: Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1 >>> b = 1//1 >>> if a is b: print('yes!') ... >>> b 1 >>> type(b) From dave_mikesell at fastmail.fm Thu Mar 20 21:23:51 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Thu, 20 Mar 2008 18:23:51 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: On Mar 20, 2:39 am, "Daniel Fetchinson" wrote: > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: I really like Python since I started using it a couple years ago, but this is a huge turnoff and the kind of thing that keeps me using C++. Stability is important. And I don't have any real code base. Can't imagine those that have made a big investment in Python being all too happy about the rug being pulled out from under them. From p at ulmcnett.com Fri Mar 14 13:42:17 2008 From: p at ulmcnett.com (=?UTF-8?B?UGF1bCBNwqJOZXR0?=) Date: Fri, 14 Mar 2008 10:42:17 -0700 Subject: Thousand Seperator In-Reply-To: References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <47DAB8F9.7020700@ulmcnett.com> Eddie Corns wrote: > ewanfisher at gmail.com writes: > >> I'm trying to find some code that will turn: > >> 100 -> 100 >> 1000 -> 1,000 >> 1000000 -> 1,000,000 >> -1000 -> -1,000 > >> I know that can be done using a regular expression. In Perl I would do >> something like: > >> sub thousand { >> $number = reverse $_[0]; >> $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; >> return scalar reverse $number; >> } > >> But I cannot find how to do this in Python. > > Look at the locale module. If you're producing the numbers yourself then they > get printed in that format otherwise you can convert them to numbers first. Specifically: import locale locale.setlocale(locale.LC_ALL, '') for trial in (100, 1000, 1000000, -1000): print trial, locale.format("%0f", trial, True) If that results in no comma separators, then you may need to set the locale specifically, such as: >>> locale.setlocale(locale.LC_ALL, 'en_us') 'en_us' >>> for trial in (100, 1000, 100000, -1000): ... print trial, locale.format("%.0f", trial, True) ... 100 100 1000 1,000 100000 100,000 -1000 -1,000 Paul From john.deas at gmail.com Sat Mar 8 07:11:36 2008 From: john.deas at gmail.com (John Deas) Date: Sat, 8 Mar 2008 04:11:36 -0800 (PST) Subject: parralel downloads Message-ID: Hi, I would like to write a python script that will download a list of files (mainly mp3s) from Internet. For this, I thought to use urllib, with urlopen("myUrl").read() and then writing the resulting string to a file my problem is that I would like to download several files at the time. As I have not much experience in programming, could you point me the easier ways to do this in python ? Thanks, JD From malaclypse2 at gmail.com Fri Mar 7 15:55:10 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 7 Mar 2008 15:55:10 -0500 Subject: I cannot evaluate this statement... In-Reply-To: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <16651e80803071255p67ad2101uc3ef93cf0e22c742@mail.gmail.com> On Fri, Mar 7, 2008 at 3:38 PM, waltbrad wrote: > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. > But, again, on linux pyfile evaluates to python.exe This seems to work as expected on my Ubuntu box. Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, sys >>> sys.platform 'linux2' >>> pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' >>> pyfile 'python' >>> What do you get for sys.platform when you run this code under linux? -- Jerry From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 19:32:28 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 01:32:28 +0200 Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <65am8cF2fecpvU1@mid.individual.net> iu2 wrote: > Due to Competitors... I don't want to expost the language I use A serious competitor that wants to find out _will_ find out, no matter what you try. Regards, Bj?rn -- BOFH excuse #341: HTTPD Error 666 : BOFH was here From tdelaney at avaya.com Wed Mar 26 16:42:28 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 27 Mar 2008 04:42:28 +0800 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <13ubn5ue821ak7e@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > >> Yes. And because Python is a "scripting language" > > > Python is a programming language. It can be used for scripting, but > that's not all it can do. Describing it as a "scripting language" is > like describing a fully-equipped professional kitchen as "a left-over > warming room". I'm putting words in sturlamolden's mouth here, but I think he was implying that Python has all the advantages of a "scripting language", hence has a much gentler introduction than many fully-fledged programming languages (and indeed, many scripting languages). Cheers, Tim Delaney From kyosohma at gmail.com Thu Mar 6 16:51:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Mar 2008 13:51:59 -0800 (PST) Subject: Python on the renderfarm References: Message-ID: On Mar 6, 3:35 pm, "Terry Reedy" wrote: > It is fairly well know that cinematic digital effects are most often > rendered on *nix machines with efficient numeric code.http://www.linuxjournal.com/article/9951 > > But Python sometimes has a role too: from the middile of the above link > > ''' > Tippett Studio: Linux Python Pipeline > JET is a proprietary Python-based system comprising software tools and > scripts used to implement a visual effects and animation pipeline. "A > visual effects and animation pipeline is an assembly line of software used > to organize, automate and facilitate the creation of computer-generated > imagery", says Darling. "The JET tool is highly customizable, featuring > XML-based user-interface templates that can be modified to suit specific > types of artists or production needs. JET uses modular template chunks to > perform each of the tasks in the pipeline, such as rendering or > compositing. The templates are implemented as Python objects and are > centrally located. JET is not only implemented entirely in Python, but it's > also used to generate Python scripts automatically. These custom scripts > form unique pipelines for each computer graphics job to run on the > renderfarm." > > ''' That's neat. Phil Tippett has been one of my favorite Special Effects people and now he's using my favorite programming language too. Hopefully Python will make Tippett more productive than ILM! Mike From deets at nospam.web.de Fri Mar 28 13:16:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Mar 2008 18:16:38 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <87od8yolay.fsf@mulj.homelinux.net> References: <87od8yolay.fsf@mulj.homelinux.net> Message-ID: <654ng1F2cvh8aU1@mid.uni-berlin.de> > systems. (In theory, file input/output should also be available as > asynchronous code, but async IO is low-level and not available in > Python.) While threads shouldn't be considered a replacement for I suggest you tell that the twisted-guys. And the ones from the built-in asyncore-module. They will be surprised to hear that their years worth of working code will evaporate in a rosa cloud. Diez From stefan_ml at behnel.de Thu Mar 6 05:58:31 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 06 Mar 2008 11:58:31 +0100 Subject: generateDS problem: __init__ of base class is not called (processing linked xsd files) In-Reply-To: References: Message-ID: <47CFCE57.9000900@behnel.de> Vladimir Kropylev wrote: > Is it possible to have __init__ of superclass called when superclass > and subclass are defined in different XSD files? > There's no problem when super and subclass are defined within single XSD file. > > In another words, can generateDS correctly process schema, described > in a set of linked xsd files? The XML Schema support of generateDS is not complete. Last time I checked, there were quite a number of things that were not supported. Stefan From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:53:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:53:23 -0300 Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: En Thu, 27 Mar 2008 17:37:33 -0300, Aaron Watters escribi?: >> "this";"is";"a";"test" >> >> Resulting in an output of: >> >> ['this', 'is', 'a', 'test'] >> >> However, if I modify the csv to: >> >> "t"h"is";"is";"a";"test" >> >> The output changes to: >> >> ['th"is"', 'is', 'a', 'test'] > > I'd be tempted to say that this is a bug, > except that I think the definition of "csv" is > informal, so the "bug/feature" distinction > cannot be exactly defined, unless I'm mistaken. AFAIK, the csv module tries to mimic Excel behavior as close as possible. It has some test cases that look horrible, but that's what Excel does... I'd try actually using Excel to see what happens. Perhaps the behavior could be more configurable, like the codecs are. -- Gabriel Genellina From castironpi at gmail.com Sun Mar 9 17:44:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:44:50 -0700 (PDT) Subject: Logically/Selectively Sub Class? References: Message-ID: <14923672-e7c9-40b2-a266-fd6c0b36e392@2g2000hsn.googlegroups.com> On Mar 9, 4:28?pm, xkenneth wrote: > Might be a silly question, but is it possible to selectively subclass, > IE subclass is a supporting module is present and not otherwise. > > Regards, > Kenneth Miller if mod is present: class Waypoint( Mine, Yours ): pass else: class Waypoint( Mine ): pass class NewClass( Waypoint ). In 3.0, you can do if mod is present: bases= Mine, Yours else: bases= Mine, class NewClass( *bases ). From ccomb at free.fr Sun Mar 23 21:31:53 2008 From: ccomb at free.fr (Christophe Combelles) Date: Mon, 24 Mar 2008 02:31:53 +0100 Subject: PyCon FR - =?UTF-8?B?Sm91cm7DqWVzIFB5dGhvbg==?= Message-ID: <47e70487$0$15874$426a34cc@news.free.fr> PyCon FR will take place in Paris, France, 17-18 May 2008. The French Python Association (AFPY) is organizing this event called "Journ?es Python" for the second time. We expect most talks to be in french, but any proposal in english is also greatly welcome! You may submit your idea of talks and presentations now, either here if you speak french: http://fr.pycon.org/actualites/appel-a-propositions/ , or here if you don't : pycon -at- afpy.org Topics: We're expecting talks about anything related to the Python programming language, including: * the language and its libraries * the web technologies * Python in scientific computing * game programming * development environnement setup * agile programmnig and tests The expected audience will span on any level, from the beginner to the expert. Thus, your talk may fit even to beginners and will be welcome. Other formats: As well as regular talks, we will host tutorials about Python programming for beginners, and we may include 15-minutes lightning talks on any topic you want to talk about (e.g.: a project you're working on). You may submit debate topics for open discussions too. Important dates: * March, 7th : Call for papers * March, 30th : Paper submissions are closed * April 4th : Final schedule publication How to get involved? If you want to attend as a simple visitor, please register on this page to help us count the expected audience: * http://fr.pycon.org/inscription To submit a talk, tutorial, etc., please register with the link above, and fill the following form: * http://fr.pycon.org/contact/proposition-de-presentation For any information about the event, go to: * http://fr.pycon.org get in touch with the organization team via: pycon -at- afpy.org See you soon! --'AFPy Team. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 10 04:59:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 10 Mar 2008 09:59:37 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> Message-ID: <47d4f850$0$21765$426a74cc@news.free.fr> Guillermo a ?crit : > Mamma mia! My head just exploded. I've seen the light. > > So you only need to ?want? to have a protocol? That's amazing... Far > beyond the claim that Python is easy. You define protocols in writing > basically! Even my grandma could have her own Python protocol. > > Okay, so I think I know where's the catch now -- you must rely on the > fact that the protocol is implemented, Indeed. But even with static declarative typing ? la Java, you must rely on the fact that the protocol is *correctly* implemented (what about having file.close sending mails to all your contacts and then rebooting the computer ?-). IOW, at some point, you have to trust the coder anyway. > there's no way to enforce it if > you're expecting a parrot-like object. Yes there is: > You'd try to call the speak() > method That's it. > and deal with the error if there's no such method? Either catch the AttributeError and raise a TypeError or ValueError (or some more specific one) instead, or just let the AttributeError propagate - whichever makes more sens given the context. I'd say the default would be to catch the AttributeError and raise a TypeError instead (that's at least what len() does when passed an unsized object). From kkadrese at gmail.com Tue Mar 18 12:17:32 2008 From: kkadrese at gmail.com (kkadrese at gmail.com) Date: Tue, 18 Mar 2008 09:17:32 -0700 (PDT) Subject: lock access to serial port Message-ID: hello group, how to get ttyS0 serial port for exclusive access? I have a python script that uses this device with AT commands. I need that two instances can call simultaneosuly this python script but only one of them gets the device. I tried fcntl.flock, it was just ignored, put writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not know what are appropriate arguments), googled half a day for various phrases, error messages etc....without success. please help, Andra From bborcic at gmail.com Mon Mar 10 13:51:18 2008 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 10 Mar 2008 18:51:18 +0100 Subject: __iter__ yield In-Reply-To: <910581f3-6587-4f6a-91ba-0049d583c1d6@y77g2000hsy.googlegroups.com> References: <27d24b75-f1b5-4996-b54a-15ab2ba16593@59g2000hsb.googlegroups.com> <910581f3-6587-4f6a-91ba-0049d583c1d6@y77g2000hsy.googlegroups.com> Message-ID: Paul Hankin wrote: > On Mar 10, 3:12 am, George Sakkis wrote: >> On Mar 9, 7:37 pm, Paul Hankin wrote: >> >> >> >>> On Mar 9, 8:58 pm, duccio wrote: >>>> Someone knows if it's possible to make this __iter__ function with just >>>> one 'yield' intead of two? >>>> ... >>>> def __iter__(self): >>>> yield self #1 >>>> for n in self.childs: >>>> for nn in n.__iter__(): >>>> yield nn #2 >>> Only one yield and shorter (but not really any simpler): >>> from itertools import chain >>> class Node: >>> ... >>> def __iter__(self): >>> for x in chain([self], *self.childs): >>> yield x >> Actually this doesn't need a yield at all: >> >> class Node: >> ... >> def __iter__(self): >> return chain([self], *self.childs) > > The two have slightly different behaviours: without the yield, iter is > called immediately on every node in the tree as the iterators are > built. With yield, iterators are built lazily, giving better > behaviour. generator expressions allow to save on the 'yield' while keeping the lazy behavior, with either : def __iter__(self): return chain([self],(y for x in self.childs for y in x)) or def __iter__(self): return (y for x in chain([[self]],self.childs) for y in x) BB From Robert.Bossy at jouy.inra.fr Wed Mar 19 13:45:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 19 Mar 2008 18:45:57 +0100 Subject: xml sax In-Reply-To: References: Message-ID: <47E15155.4050008@jouy.inra.fr> Timothy Wu wrote: > Hi, > > I am using xml.sax.handler.ContentHandler to parse some simple xml. > > I want to detect be able to parse the content of this tag embedded in > the XML. > 174 > > > Is the proper way of doing so involving finding the "Id" tag > from startElement(), setting flag when seeing one, and in characters(), > when seeing that flag set, save the content? > > What if multiple tags of the same name are nested at different levels > > and I want to differentiate them? I would be setting a flag for each level. > I can imagine things get pretty messy when flags are all around. > Hi, You could have a list of all opened elements from the root to the innermost. To keep such a list, you append the name of the element to this stack at the end of startElement() and pop it off at the end of endElement(). In this way you have acces to the path of the current parser position. In order to differentiate between character data in Id and in Id/Id, you just have to iterate at the last elements of the list. Cheers, RB From http Sun Mar 23 13:45:38 2008 From: http (Paul Rubin) Date: 23 Mar 2008 10:45:38 -0700 Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <7xr6e11ghp.fsf@ruckus.brouhaha.com> John Nagle writes: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : I like to think len(dict) is constant time but I haven't checked the code. Same for bool(dict) (which is what you get when you run "if dict: ..."). From version5 at gmail.com Sun Mar 23 17:26:32 2008 From: version5 at gmail.com (nnp) Date: Sun, 23 Mar 2008 21:26:32 +0000 Subject: Issue with select.select() and missing data Message-ID: <28749c0e0803231426o7d9bec23j2b168e3c43c427be@mail.gmail.com> Hi guys, I have an issue when using select.select(). I have an application that creates sockets then sends data on them. These sockets are then passed off to a listener which uses select.select() to detect any responses. For some reason every socket can only receive one response before my computer begins to issue ICMP port unreachable messages for that port. The code doing the listening is below. No sockets are returned in the broken list. Can anyone spot anything stupid I'm doing in the following code or think of any reason for this issue? def __listen(self): while self.listening and len(self.notify_q_list) != 0: self.lock.acquire() r_read, r_write, broken = select(self.socket_list, [], [], .1) for sock in r_read: data, addr = sock.recvfrom(2**16) for function_tuple in self.notify_q_list: function_tuple[0].put((True, data, 1, addr, 5.0)) self.lock.release() time.sleep(.1) for sock in self.socket_list: sock.close() self.socket_list = [] Thanks, nnp -- http://www.smashthestack.org http://www.unprotectedhex.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From praveena_python at yahoo.com Thu Mar 27 19:28:27 2008 From: praveena_python at yahoo.com (Praveena B) Date: Thu, 27 Mar 2008 16:28:27 -0700 (PDT) Subject: how to capture screenshots of the active window in Python Message-ID: <142053.72537.qm@web44801.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu Mar 6 20:46:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 17:46:43 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: <4e8c4617-af5e-416b-aeba-f58023026340@8g2000hse.googlegroups.com> On Mar 6, 7:10?pm, "Gabriel Genellina" wrote: > En Thu, 06 Mar 2008 22:56:33 -0200, escribi?: > > > On Mar 6, 5:35?am, "Gabriel Genellina" wrote: > > >> p = P() > >> print p.bar.func_name # -> bar > >> p.bar.im_func.anotherattribute = 1 > >> print p.bar.anotherattribute # -> 1 > > >> (the attribute must be set on the *function* itself if you want it to ? > >> be ? > >> somewhat persistent; methods are usually volatile objects) > > > You read my mind. > > You could try to write in a way that reading your mind isn't necesary... > > > I was just getting: > > ? ?assert p.bar is p.bar > > and failing. > > > But if you set them on im_func, instances don't have their own. > > Instances don't have their own methods either. What do you actually want ? > to do? If you need a method with per-instance attributes, that looks like ? > another object to me. Hi, great thanks for giving me your ear this far. First of all, -I have it working-. But the design isn't encapsulated quite right. Here's what I have. 69 lines, so I'll ask to post it first. The gist is: class ISS( SS, metaclass= autonaming ): message= MessageDec() @message def user_act( msg, self, change ): print( 'user act self change', msg, self, change ) IncomingServer... but it originally came from 'clientsideserver.' iss= ISS() class OSS( SS, metaclass= autonaming ): message= MessageDec() user_act= message.out() oss= OSS() oss.message is a abstraction class that writes the method name into a string, then sends it to OSS... outgoingserver or serverside. Now that I'm writing it, and this is important, -to- the -newsgroup-, I realize you could do it with a simple wrapper... include the function name in parameters and call the pickler and send. OSS then looks like this: def something_happens( *ar ): self.user_act( something_about( *ar ) ) So the message.out() instance pickles ( 'user_act', ar ) and sends it. Then iss.incoming receives it, unpickles that string, gets 'user_act' from self, and invokes. The cool part is the declaration of user_act= message.out(), which uses a metaclass to assign its own name, and returns a function which includes the object in its signature. Cool. Yes it's working and a little slack. However-: this is the cool part. I'd like messages to know which instance they came from, and perform the sending & receiving encapsulated on their own--- not to subclass class SS( Sending ): with various behaviors: that is, to assign them as class attributes rather than superclasses. The dreaming comes in here--- I'd like the class to look just like this. Tell me it's possible. And I changed my mind on posting the code, here's the whole thing. Just get SS.send and SS.incoming into MessageDec. har har har har har. Change anything before class OSS:. How does a weak reference lookup in doublebound sound? from functools import wraps import pickle class doublebound: __slots__ = ( '_func', 'assname', '_orig' ) def __init__( self, func ): @wraps( func ) def f( *ar, **kws ): return func( self, *ar, **kws ) self.assname= None self._func, self._orig= f, func def __get__( self, instance, owner ): return self._func.__get__( instance, owner ) class autonaming( type ): def __init__( self, name, bases, namespace ): for k,v in namespace.items(): if isinstance( v, doublebound ): v.assname= k class Sending: def send( *ar, **kws ): raise NotImplemented class MessageDec: def __call__( self, fun ): return doublebound( fun ) def out( self ): return doublebound( self._send ) def _send( self, message, other, *ar, **kws ): return other.send( message.assname, *ar, **kws ) class SS( Sending ): def send( self, methn, *ar, **kws ): transpmessage= methn, ar, kws transpstr= pickle.dumps( transpmessage ) self.far.incoming( transpstr ) def incoming( self, transpstr ): transpmessage= pickle.loads( transpstr ) methn, ar, kws= transpmessage meth= getattr( self, methn ) meth( *ar, **kws ) class OSS( SS, metaclass= autonaming ): message= MessageDec() user_act= message.out() somethingelse= message.out() @message def amessage( msg, self, *change ): print( 'something else', change ) class ISS( SS, metaclass= autonaming ): message= MessageDec() @message def user_act( msg, self, change ): print( 'user act self change', msg, self, change ) @message def somethingelse( msg, self, change= 'and' ): print( 'something else', change ) amessage= message.out() oss= OSS() iss= ISS() oss.far= iss iss.far= oss oss.user_act(2) oss.somethingelse( 'butwhat?') iss.amessage( 2, 3, 4, 5 ) From mauriceling at acm.org Tue Mar 18 05:25:06 2008 From: mauriceling at acm.org (Maurice LING) Date: Tue, 18 Mar 2008 09:25:06 GMT Subject: Multiple Submits in HTML Forms - Cherrypy In-Reply-To: References: <47df6bd4$1@news.unimelb.edu.au> Message-ID: <47df8a6f@news.unimelb.edu.au> Carsten Haese wrote: > On Tue, 2008-03-18 at 07:14 +0000, Maurice LING wrote: >> Hi, >> >> Assuming that I have this code for Cherrypy 3 >> >> class Welcome: >> def index(self): >> return """ >>
>> >> >>
""" >> index.exposed = True >> >> How should I write "btn_handler" so that it will perform different >> actions when different button is pressed? > > Something like this would do it: > > def btn_handler(self, AddBtn=None, EditBtn=None): > if AddBtn: > return "You pressed Add!" > if EditBtn: > return "You pressed Edit!" > > Alternatively you could use a kwargs dictionary and test it for the > presence of the "AddBtn" or "EditBtn" keys. > Thank you Carsten maurice From kyosohma at gmail.com Sat Mar 15 18:06:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 15 Mar 2008 15:06:13 -0700 (PDT) Subject: Python and 3D References: Message-ID: <00a99921-a931-49cf-9bd1-4978d805290f@8g2000hsu.googlegroups.com> On Mar 15, 3:09 pm, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs > > Any help much appreciated > > Eric I'm not aware of anything. You might look at pyOpenGL or pyglet. They should be good for 3D modeling at least. Mike From peter.bulychev at gmail.com Sun Mar 16 05:00:46 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Sun, 16 Mar 2008 12:00:46 +0300 Subject: question about module compiler: line numbers and positions of substring, which are covered by AST nodes Message-ID: Hello. I use standard module Compiler to build ASTs of Python code. Given AST subtree I want to restore coordinates of substring in the input, which is covered by the subtree. Example: Suppose, the input is 'a+(b+c)'. It is parsed to the tree ADD(a, ADD(b,c)) by module Compiler. I want to have a function, which given ADD(b,c) will return the coordinates of the substring '(b+c)'. Module Compiler provides only line numbers for each node. But even this information is incorrect: only the first line of multi-lined statements is stored. What is the easiest way of doing what I want? As I understand, module Compiler is automatically generated by some parser generator. Maybe I can modify it? -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Fri Mar 7 14:55:25 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 7 Mar 2008 11:55:25 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> <51ca8638-65fa-490b-a04a-33ffbefd4aca@s19g2000prg.googlegroups.com> <5d4827e1-8b90-4feb-bfb0-6d956e138b5e@b64g2000hsa.googlegroups.com> Message-ID: <9e8bc711-bdd6-4be7-9e28-b3c72c674832@i7g2000prf.googlegroups.com> [castiro] > Slice literals are a logical next step, precedented by raw strings and > bytes. slice= islice is too, precedented by range= xrange. Looking closely at the [::] notation, I think it can easily be confused with an open box of fleas. IMO, the one unequivocal, explicit way of checking for lice is itertools.is_lice(). Raymond _ ~ @ @ \_/ From dstromberglists at gmail.com Thu Mar 20 14:58:11 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 20 Mar 2008 18:58:11 GMT Subject: forkpty not working? References: Message-ID: <7tyEj.20469$Ch6.19687@newssvr11.news.prodigy.net> If you google a bit, I believe you'll find one or more python modules for working with ssh. Also, if you want to roll your own, the easiest way to get around the password requirement is to use ssh passwordless authentication using DSA or RSA public/private keypairs: http://stromberg.dnsalias.org/~dstromberg/ssh-keys.html As far as why the code below doesn't open your "it_worked" file - exec replaces the current process with the specified process - so the current process effectively goes away on exec. On Thu, 20 Mar 2008 00:40:49 -0700, est wrote: > Hello everyone. I am trying to write a bash/ssh wrapper in python so > python scripts could interact with bash/ssh. > > Because when input passwords to ssh it requires a tty rather than stdin > pipe, so i have to use a pty module to do that. > > I copied this snippet from this thread > http://groups.google.com/group/comp.lang.python/browse_thread/ thread/6bbc3d36b4e6ff55/ > > def rcmd(user, rhost, pw, cmd): > #Fork a child process, using a new pseudo-terminal as the > child's controlling terminal. > pid, fd = os.forkpty() > # If Child; execute external process > if pid == 0: > os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + > cmd) > x=open("it_worked.txt", "w") #output a file for test > x.write("xxx") > x.close() > #if parent, read/write with child through file descriptor else: > pause() > #Get password prompt; ignore > os.read(fd, 1000) > pause() > #write password > os.write(fd, pw + "\n") > pause() > res = '' > #read response from child process > s = os.read(fd,1 ) > while s: > res += s > s = os.read(fd, 1) > return res > > As far as I can see the code is not working, when called the function > rcmd() there is no file it_worked.txt spawned in the directory. I am > n00b to POSIX, so anyone please give me some hint? what happened when > os.forkpty()? From lutz at rmi.net Tue Mar 18 17:00:58 2008 From: lutz at rmi.net (Mark Lutz) Date: Tue, 18 Mar 2008 14:00:58 -0700 (PDT) Subject: Colorado Python training in May Message-ID: Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on May 14-16, 2008. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. For more information on this session, please visit its web page: http://home.earthlink.net/~python-training/longmont-public-classes.htm For additional background on the class itself, see our home page: http://home.earthlink.net/~python-training Thanks for your interest. --Mark Lutz at Python Training Services From Jeff.Goldfinkle at gmail.com Wed Mar 5 15:25:35 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Wed, 5 Mar 2008 12:25:35 -0800 (PST) Subject: Bit twiddling floating point numbers Message-ID: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Hi All Is there a simple way to twiddle the bits of a float? In particular, I would like to round my float to the n most significant bits. For example - 0.123 in binary is 0.000111111 Rounding to 4 bits I get 0.0001. I can pack and unpack a float into a long e.g. struct.unpack('I',struct.pack('f',0.123))[0] but then I'm not sure how to work with the resulting long. Any suggestions? From ggpolo at gmail.com Thu Mar 27 11:21:28 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 12:21:28 -0300 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: 2008/3/27, Skip Montanaro : > > > >>> proc = subprocess.Popen ("ls /tmp") > > > > proc = subprocess.Popen ("ls /tmp", shell=True) > > > > or > > > > proc = subprocess.Popen (["ls", "/tmp"]) > > > > should work. > > > Why should I need to set shell=True? The default is shell=False, which means that Popen will use os.excevp to execute your command, (talking about UNIX here), which in turn expects a list as the "args" parameter, but you are passing a string. Setting shell=True makes Popen execute the string passed through the shell. > I'm not globbing anything. The > second case still fails: > > >>> proc = subprocess.Popen (["/usr/bin/ls" "/tmp"]) Notice how yours is lacking a comma separating the strings while mine does include it. > > Traceback (most recent call last): > > File "", line 1, in ? > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 542, in > __init__ > errread, errwrite) > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 975, in > > _execute_child > raise child_exception > > OSError: [Errno 20] Not a directory > > Thx, > > > Skip > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From paul at boddie.org.uk Mon Mar 17 06:58:51 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 17 Mar 2008 03:58:51 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <1a560143-9a65-4c9f-bf5b-cb535d17cc13@z38g2000hsc.googlegroups.com> On 17 Mar, 02:39, "BJ?rn Lindqvist" wrote: > > I haven't been to EuroPython even when it has been fairly nearby > because the entrance fee was to high. But how do you help change > something like that? You could join in and make your case. There was a more protracted discussion than usual last year about fees because some people pointed out the discrepancy between salary and price levels in different parts of Europe and the need to make the conference more affordable: what may be relatively inexpensive for some might be relatively expensive for others, and the organisers felt that it would be foolish to exclude the latter group, particularly when they may be more likely to travel to the conference in its present location. It's hard to say whether the conference is reaching everyone it should, given the composition of attendees: http://www.europython.org/community/Planning/Projections But without anyone to pursue a particular cause, and with decisions needing to be made within certain timeframes (which is often a struggle, anyway), things often get preserved as they are rather than being improved. I live in a European country which is either number one or two on the price scale (depending on whether you include alcohol prices or not), and I can't say what the right fee level should be (other than "possibly lower than it is") - it's up to others to weigh in and give their opinion, I think. Paul From arnodel at googlemail.com Sat Mar 22 14:48:00 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 18:48:00 GMT Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: jmDesktop writes: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. I'm not from the US and I'm not sure what 9th/12th grade are, but if you want to use programming to explore maths, er I mean math, have a look at the sage project: http://www.sagemath.org/ -- Arnaud From admin.397 at gmail.com Wed Mar 26 02:35:23 2008 From: admin.397 at gmail.com (Admin.397) Date: Tue, 25 Mar 2008 23:35:23 -0700 (PDT) Subject: Decent 2D animation with Windows.Forms GUI Message-ID: <58745015-2b0e-49c2-936a-e92e8c14d692@d4g2000prg.googlegroups.com> Hi folks, I'm running a simple 2D game using Pygame but really would like a decent GUI and am currently testing out wxPython. As it turns out, I can't get Pygame working in a wxPython canvas and instead turned to openGL - which is painfully slow at reading through an array of points. Can anyone advise on a combination of a good GUI (wxPython really takes the cake here, plugging into the OSes GUI - does anything else do that?) and some form of 2D animation package that has a fair bit of horsepower behind it, that can fit into said GUI? Failing that, any advice on speeding up PyopenGL? I appreciate your assistance! From castironpi at gmail.com Fri Mar 21 02:47:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:47:50 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> <3797c5dd-8d10-4298-af05-fd06440119ce@c19g2000prf.googlegroups.com> Message-ID: On Mar 20, 2:07?am, John Machin wrote: > On Mar 20, 12:50?pm, "Gabriel Genellina" > wrote:> En Wed, 19 Mar 2008 20:16:36 -0300, John Machin ? > > escribi?: > > > > On Mar 20, 9:14 am, sturlamolden wrote: > > >> Is a Python set implemented using a hash table? > > > > What don't you understand about the comments in the first two > > > screenfuls of Objects/setobject.c? > > > That comment was unnecesarily harsh, don't you think? > > No, otherwise I wouldn't have made it. Screenfuls is an awful lot, the way you guys write. Besides, what's the answer? What don't you understand? From Dodin.Roman at gmail.com Wed Mar 26 05:45:17 2008 From: Dodin.Roman at gmail.com (hellt) Date: Wed, 26 Mar 2008 02:45:17 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> On 26 ???, 02:30, kellygreer1 wrote: > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > Is there a page on this in the Python in a Nutshell or the Python > Cookbook? > Did I miss something? > > Kelly Greer > kellygre... at nospam.com > change nospam to yahoo or just look this thread for a fastest solution http://groups.google.com/group/comp.lang.python/browse_frm/thread/7091898414444310/af8961f1ed91ccea?lnk=gst&q=duplicates#af8961f1ed91ccea From half.italian at gmail.com Sat Mar 1 02:17:11 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 29 Feb 2008 23:17:11 -0800 (PST) Subject: Run wxPython app remotely under XWindows References: <9c785431-dd6f-41cc-b185-1820e3827ef0@e10g2000prf.googlegroups.com> <62ovn3F23qsbuU1@mid.individual.net> <48d9279b-4030-4b25-b42f-422ae15c2804@e6g2000prf.googlegroups.com> <147642c3-d0db-4eeb-b1d3-b5919733c1f0@s19g2000prg.googlegroups.com> <3f18e823-727e-4790-82f4-77deee37c3d1@z17g2000hsg.googlegroups.com> Message-ID: <596a5f32-05c8-4aa9-9863-7e418458edf6@e23g2000prf.googlegroups.com> On Feb 29, 8:19?am, Mike Driscoll wrote: > On Feb 28, 7:49 pm, Sean DiZazzo wrote: > > > > > On Feb 28, 5:26 pm, Sean DiZazzo wrote: > > > > On Feb 28, 3:50 pm, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > > > Sean DiZazzo wrote: > > > > > Is there something special you have to do to get a wxPython app to > > > > > run remotely under xwindows? ?My Tkinter apps always automatically > > > > > work that way, so I was surprised to even be confronted with this > > > > > problem. > > > > > Could you please provide more detail? My wxPython apps run perfectly > > > > remotely in the X Window System like this: > > > > > $ ssh some-other-machine > > > > $ DISPLAY=:0 ./my_app.py > > > > Should wxPython apps work this way? ?Do you think it's something with > > > the server? > > > Just to close the loop I think think this is a problem with the ssh > > server. > > > ~Sean > > If it's not the server, then please post the issue to the wxPython > list. They can probably help: > > http://wxpython.org/maillist.php > > Mike To follow up with a solution. I learned that the default install of wxPython, and Tkinter for that matter is compiled to run under Aqua as opposed to X11. It won't run remotely, as I first posted, compiled this way. To get Tkinter to work under X11 you simply need to configure and install a version of python for the X11 environment. The default Mac install (Leopard) and the MacPython distro are configured to run under Aqua. Instead of compiling my own, I found that the default Fink install is configured to run under X11, so if you install it, and run that version of Python, you can run Tkinter apps remotely from a Mac box. wxPython is a bit more complicated. The idea is the same, but the process is much more complicated to get it working. You need to compile wxPython under GTK2, which I found is not well supported for Mac. I followed the instructions at this site: http://wiki.wxpython.org/wxGTK_on_Mac_OSX to get it working. Even with the instructions, I had to finagle a few things to get it to work properly. But it does work! My first successful install was on Tiger, but I'm trying an install on Leopard as we speak. Thanks to Cody Precord for the instructions. I would have never been able to do it without. Now my users will have a prettier GUI! ~Sean From steve at holdenweb.com Sat Mar 1 13:23:30 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 13:23:30 -0500 Subject: Import, how to change sys.path on Windows, and module naming? In-Reply-To: References: Message-ID: Jeremy Nicoll - news posts wrote: > If I understand correctly, when I import something under Windows, Python > searches the directory that the executing script was loaded from, then other > directories as specified in "sys.path". > Technically, I believe it just puts the script's directory at the start of sys.path, then uses sys.path as its module search path. > I assume there are standard locations inside my installed Python - in my > case inside: C:\Program Files\~P-folder\Python25 - where I could put my > modules and they'd automatically be found? But even if that's the norm, I > don't want to put my own modules in such directories, partly because a > uninstall or reinstall or upgrade of Python might lose my stuff, and partly > because I don't believe in mixing distributed code with home-grown code. > There's Lib/site-packages, which is where third-party code normally goes. > However I'm quite happy to have a line or three of code to alter sys.path > to suit my set-up, if that's a normal way to handle this problem. Where > does one do that? > Take a look at site.py, and see that it runs sitecustomize.py when present. > > Also, I presume that there's a risk that the module name that I give to any > of my utilities will clash with a present or future standard module's name. > Does that mean that I should give my own modules names like "JNfoo" rather > than "foo", etc? Or something like "JNutils.foo"? > You can always be sure your own modules will be loaded in preference to shadowing system modules if you put your directories on the path before the standard directories, but most people don't spend a lot of time worrying about this. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Robert.Bossy at jouy.inra.fr Tue Mar 25 11:20:00 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 16:20:00 +0100 Subject: dynamically created names / simple problem In-Reply-To: <47E91645.4000706@jouy.inra.fr> References: <000c01c88e88$96c29490$0600a8c0@laptop> <47E91645.4000706@jouy.inra.fr> Message-ID: <47E91820.7090009@jouy.inra.fr> Robert Bossy wrote: > Jules Stevenson wrote: > >> Hello all, >> >> I'm fairly green to python and programming, so please go gently. The >> following code >> >> for display in secondary: >> >> self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") >> >> Errors, because of the apparent nastyness at the beginning. What I?m >> trying to do is loop through a list and create uniquely named wx >> widgets based on the list values. Obviously the above doesn?t work, >> and is probably naughty ? what?s a good approach for achieving this? >> >> > Hi, > > What you're looking for is the builtin function setattr: > http://docs.python.org/lib/built-in-funcs.html#l2h-66 > > Your snippet would be written (not tested): > > for display in secondary: > > setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1, > "checkbox_2")) Damn! The indentation didn't came out right, it should be: for display in secondary: setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1,"checkbox_2")) RB From vampiro4l at gmail.com Mon Mar 17 17:37:01 2008 From: vampiro4l at gmail.com (Vamp4L) Date: Mon, 17 Mar 2008 14:37:01 -0700 (PDT) Subject: Convert binary file Message-ID: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> Hello, Specifically, I'm trying to convert the Internet Explorer history file (index.dat) into a readable format. Anyone done something similar or know of any functions that may help with such a task? I'm not sure exactly what kind of file the index.dat is, it is some kind of binary file. I have tried some of the binascii functions (http:// docs.python.org/lib/module-binascii.html) without any luck. Thanks From brnstrmrs at gmail.com Wed Mar 19 14:55:18 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Wed, 19 Mar 2008 11:55:18 -0700 (PDT) Subject: csv dictreader References: Message-ID: On Mar 19, 2:32 pm, Mike Driscoll wrote: > On Mar 19, 1:06 pm, brnstrmrs wrote: > > > > > I am trying to use the dictionary reader to import the data from a csv > > file and create a dictnary from it but just can't seem to figure it > > out. > > > Here is my code: > > > >>>import csv > > >>>reader = csv.DictReader(open('table.csv')) > > >>>for row in reader: > > >>>print row > > > my csv files looks like this: > > > Bytecode,Element > > \x00\x00,0000 > > \x01\x00,0001 > > .... > > \x09\x00,0009 > > > My output shows: > > {'Bytecode': '\\x00\\x00', 'Element': '0000'} > > {'Bytecode': '\\x01\\x00', 'Element': '0001'} > > ... > > {'Bytecode': '\\x09\\x00', 'Element': '0009'} > > > 1. how can I get access to this directory > > What do you mean? You can get each element in the dict by doing this: > > for row in reader: > print row['Bytecode'] > print row['Element'] > > > 2. why does the values come with two backslashs infront of the "x" > > The double back slash is for escaping purposes, I think. If you print > this: '\\x09\\x00' > you'll get this: \x09\x00 > > Mike Thanks. It works for the Bytecode but when I do print row['Element'] I get a error message print row['Element'] KeyError: 'Element' From fumanchu at aminus.org Sun Mar 16 12:05:10 2008 From: fumanchu at aminus.org (fumanchu) Date: Sun, 16 Mar 2008 09:05:10 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> On Mar 16, 7:18 am, a... at pythoncraft.com (Aahz) wrote: > Bruce Eckel wrote: > > If the following seems unnecessarily harsh, it was even more harsh for > > me to discover that the time and money I had spent to get to my > > favorite conference had been sold to vendors, presenting me as a > > captive audience they could pitch to. > > Ouch. I'm probably one of the few organizers currently paying much > attention to c.l.py -- because I'm also one of the few who's not at > PyCon. We debated this extensively before going ahead, and we decided > it was worth an experiment. If your feedback is at all representative, > this won't happen again, I assure you. Add me to the list, then, please. I heard from several people that the entire first day was a bit wasted, that even the non-vendor talks on Friday were rather dull and simple. This is my third PyCon, and I've found a reasonably-sized cadre of people who come for the hallway conversations plus a Bof or two, having given up on hearing anything new, useful, or inspiring in the talks. There are several people I know who would like to see a more advanced academic track. > What we were trying to do was to increase sponsorship to decrease > the cost to attendees -- we have NO interest in pushing the > commercialization of Python. Can't fault you for that. But perhaps we're seeing the limit of what that approach can provide. Robert Brewer fumanchu at aminus.org From castironpi at gmail.com Wed Mar 26 04:42:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 01:42:50 -0700 (PDT) Subject: Prototype OO References: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> <13ujk0f9inb73c2@corp.supernews.com> <13uk1e1m2vl0qf4@corp.supernews.com> Message-ID: On Mar 26, 3:14?am, Dennis Lee Bieber wrote: > On Wed, 26 Mar 2008 02:03:24 -0300, "Gabriel Genellina" > declaimed the following in comp.lang.python: > > > > > No:http://en.wikipedia.org/wiki/Saruman Ask him any time over. From iwanttobeabadger at googlemail.com Tue Mar 25 22:04:21 2008 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Wed, 26 Mar 2008 02:04:21 +0000 Subject: Calling a shared library using C types In-Reply-To: References: Message-ID: Hi, Just as a follow up to this...I ve discovered that its an issue with building shared libraries on mac os and it works fine on a Linux box :S. Thanks Nathan On 25/03/2008, Nathan Harmston wrote: > > > > On 25/03/2008, Gabriel Genellina wrote: > > > > En Mon, 24 Mar 2008 19:56:08 -0300, Nathan Harmston > > escribi?: > > > > > > > import ctypes > > > t = ctypes.CDLL('./Simulation.so') > > > this works fine, I have a simple function I ve put in for testing > > which > > > just > > > returns the integer 4. However when I try to access this function it > > > doesnt > > > work > > > t.test() > > > File "", line 1, in > > > File > > > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > > line 325, in __getattr__ > > > func = self.__getitem__(name) > > > File > > > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > > line 330, in __getitem__ > > > func = self._FuncPtr((name_or_ordinal, self)) > > > AttributeError: dlsym(0x81e6b0, test): symbol not found > > > > > > Looks like the symbol isn't public - probably if you try loading the > > library with a C program it won't find it either. How is the function > > declared in the source? > > Try listing all public symbols with: nm -D Simulation.so > > Thanks for the quick reply: > Running nm lists test as > 00001760 T _test > > in the source its declared as: > > int test(){ > return 4; > } > > Sorry, this is the first time I'm making my own shared library and using > ctypes, so being a little slow. > > Thanks again > > Nathan > > > > > > > Im hoping python-list is ok for questions regarding ctypes :S > > > > > > It's not off topic, although there is a specific list for ctypes-related > > questions. But hijacking a thread to post a completely different > > question > > is not good netiquette. > > > > -- > > Gabriel Genellina > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Sat Mar 15 14:05:28 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 18:05:28 +0000 Subject: Getting started with OS X Leopard Message-ID: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> One thing I really liked about Ubuntu was that Nautilus allowed you to add scripts to a directory which could be accessed via the RMB. It was a very simple thing to do. I've recently switched to Leopard, and I'm trying to do the same thing. I'm fairly experienced with Python, but new to OS X. I have installed FinderPop, which lets me add scripts and make them accessible via Contextual Menus, but it is not as easy as the Nautilus way. The sorts of things I want to do are: * copy the directory of Finder to the clipboard * add a new file to Finder's directory. * find out the size of a directory * open a file with Aquamacs, regardless of file type, My head's swimming, though. Anyone got any really good pointers and sample scripts that will help me work out how to achieve the sorts of things I'm trying to do? From gabriel.rossetti at mydeskfriend.com Tue Mar 11 04:49:25 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 11 Mar 2008 09:49:25 +0100 Subject: execute python script question In-Reply-To: References: <47D575E9.8040507@mydeskfriend.com> Message-ID: <47D64795.2090103@mydeskfriend.com> Michael Wieher wrote: > stupid question: you have myPackage somewhere on sys.path? > > I mean, module1.py only knows it lives in a directory, it doesn't know > anything about anything above it. > > > > 2008/3/10, Gabriel Rossetti >: > > Hello, > > I have been developping something in python that has the following > hierarchy : > > project/src/myPackage/ > project/src/myPackage/__init__.py > project/src/myPackage/module1.py > project/src/myPackage/module2.py > project/src/myPackage/test/ > project/src/myPackage/test/__init__.py > project/src/myPackage/test/test_module1.py > project/src/myPackage/test/test_module2.py > project/src/myPackage/mySubPackage/__init__.py > project/src/myPackage/mySubPackage/module1.py > project/src/myPackage/mySubPackage/test/ > project/src/myPackage/mySubPackage/test/__init__.py > project/src/myPackage/mySubPackage/test/module1.py > ... > > up until now, I had been executing my modules from inside > project/src/myPackage/ > but I realised that that is wrong (while implementing the test suite) > and that since all my modules had relative imports (if module2 needed > module1, it would just say : import module1) I changed them to > myPackage.module1 for example. Now my test suite is happy, I can say : > test.sh myPackage.test and it tests everything. The only problem > now is > that I can't execute the scripts from inside or outside the myPackage > dir, I get this : > > from outside : > > Traceback (most recent call last): > File "myPackage/module1.py", line 15, in > from myPackage import constants, utils > ImportError: No module named myPackage > > or if from inside it : > > Traceback (most recent call last): > File "module1.py", line 15, in > from myPackage import constants, utils > ImportError: No module named myPackage > > can anybody please help me? I don't think I understood the whole > package/module thing I think... I think some people do some sort of > importing in the __init__.py files but I'm not sure this helps in > this case. > > Thanks, > Gabriel > > Hello Michael, not a stupid question, I think that may be it. I tried setting PYTHONPATH like Sam suggested and it worked, but I was unable to do it programmically. I tried putting it in the __init__.py file like a web post suggested but it wasn't run until after I set PYTHONPATH, and once that was done there is no need (that I can see anyways) to set it in __init__.py. Thanks for your help, Gabriel From robert.rawlins at thinkbluemedia.co.uk Thu Mar 13 13:38:03 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 13 Mar 2008 17:38:03 -0000 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <47D951C7.3090900@jouy.inra.fr> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> <47D94D61.9010708@jouy.inra.fr> <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> <47D951C7.3090900@jouy.inra.fr> Message-ID: <011501c88530$ff6f7c80$fe4e7580$@rawlins@thinkbluemedia.co.uk> Haha, I could use a stiff whisky myself after the stress that caused me :-) Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Bossy Sent: 13 March 2008 16:10 To: python-list at python.org Subject: Re: "Attribute Doesnt Exist" ... but.... it does :-s Robert Rawlins wrote: > Hi Guys, > > Well thanks for the response, I followed your advice and chopped out all the > crap from my class, right down to the bare __init__ and the setter method, > however, the problem continued to persist. > > However, Robert mentioned something about unindented lines which got me > thinking so I deleted my tab indents on that method and replaces them with > standard space-bar indents and it appears to have cured the problem. > Aha! Killed the bug at the first guess! You owe me a beer, mate. RB -- http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Sun Mar 23 18:30:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 15:30:54 -0700 (PDT) Subject: pydoc References: Message-ID: On Mar 24, 3:31 am, "Gabriel Genellina" wrote: > En Sun, 23 Mar 2008 12:57:35 -0300, A Hutchison escribi?: > > > Any known reasons why pydoc no longer works? > > It gets confused by many timezone changes that occur this month around the > world; pydoc tries hard to please all kind of users and tracking those > locale changes isn't easy. > Wait until April and it will resume working fine, I presume. It's a combination of related factors ... equinox, Easter, full moon. Another seasonal phenomenon: some posters seem to be alpha-testing posts that they intend to make on the first day of the new month. From torriem at gmail.com Sat Mar 1 22:20:32 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Mar 2008 20:20:32 -0700 Subject: Question about lambda and variable bindings In-Reply-To: References: <47CA160C.3000305@gmail.com> Message-ID: <47CA1D00.6090107@gmail.com> poof65 wrote: > An idea, i don't know if it will work in your case. > > for x in xrange(10): > funcs.append(lambda p,z=x: testfunc(z+2,p)) Good idea. I will try it. I also figured out a way to architecture my program differently to avoid this problem. But this idiom might be handy in certain situations. Suppose you need to provide a callback function with a fixed signature to some library routine. But you want to add extra contextual data to your callback. This just might be the ticket. Michael From castironpi at gmail.com Sat Mar 15 18:28:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 15:28:59 -0700 (PDT) Subject: string literal or NoneType References: Message-ID: <5fe63b9c-178f-4333-87a6-7118e8ad7550@s50g2000hsb.googlegroups.com> On Mar 15, 10:27?am, menosa... at gmail.com wrote: > hi all > i want to check a condition and if true should return a filename > string ?from a list.if the condition is false i am returning a > "" ?(string literal).. > > retv="" > if ?somecondition: > ? ? retv=mylist[x] > ... > return retv > > The calling function will check the return value and print the > filename if it is not """. > in the calling function i can code > if returnval !="": > ? ? print "filename is:",returnval > else: > ? ? print "no filename found" > > what i want to know is ,should i rewrite the ?if returnval !="" ?as > > if returnval: > ? ?print "filename is:",returnval > else: > ? ? print "no filename found" > > or is the way i coded the right way ? i am little confused here > Someone suggested that i make a variable retv None and if the > condition true then set retv as filename , > > retv=None > if somecondition: > ? ? retv=mylist[x] > > ... > return retv > > which approach is correct..? can someone help please > vincent One possibility: def fun( ..., testpair, ... ): if somecondition: testpair[ True ]( mylist[x] ) else: testpair[ False ]() . However 'fun' knows "too much for its scope" by varying call signature. Call it by: fun( ..., { True: partial( print, 'filename is:' ), False: partial( print, 'no filename found' ) }, ... ) , which relies even MORE on the particulars of how 'fun' calls. Reversed: return somecondition, partial( mylist.__getitem__, x ) cond, dataf= fun( ... ) if cond: print( 'filename is ', dataf() ) else: print( 'no filename found' ) , which leave different amounts of genericity/genericness/generality to work in. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 12:55:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Mar 2008 16:55:24 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <13ud2rss7oigl94@corp.supernews.com> On Sun, 23 Mar 2008 09:24:35 -0700, Aahz wrote: > The problem with lambda is that too often it results in clutter (this is > a strictly made-up example off the top of my head for illustrative > purposes rather than any real code, but I've seen plenty of code similar > at various times): > > gui.create_window(origin=(123,456), background=gui.WHITE, > foreground=gui.BLACK, callback=lambda x: x*2) > > That means I need to pause reading the create_window() arguments while I > figure out what the lambda means -- and often the lambda is more > complicated than that. Moreover, because the lambda is unnamed, it's > missing a reading cue for its purpose. And of course this would be so much better: def double(x): return x*2 gui.create_window(origin=(123,456), background=gui.WHITE, foreground=gui.BLACK, callback=double) Not. The source of the "clutter" (having *less* code is clutter???) and confusion isn't the lambda, it's the callback. -- Steven From grante at visi.com Wed Mar 19 09:43:32 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Mar 2008 13:43:32 -0000 Subject: lock access to serial port References: Message-ID: <13u2644hpullvd8@corp.supernews.com> On 2008-03-18, kkadrese at gmail.com wrote: > how to get ttyS0 serial port for exclusive access? I have a python > script that uses this device with AT commands. I need that two > instances can call simultaneosuly this python script but only one of > them gets the device. I tried fcntl.flock, it was just ignored, put > writtable file LCK..ttyS0 in /var/lock, Using a lock file is the traditional method of providing mutually exclusive access to a serial port. > tried ioctl (but I may not know what are appropriate > arguments), googled half a day for various phrases, error > messages etc....without success. It's unclear what "without success" means. Lockfiles have been used for decades, and they work fine as long as all of the applications follow the rules. -- Grant From gh at ghaering.de Mon Mar 31 08:39:55 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 31 Mar 2008 14:39:55 +0200 Subject: Problem with sqlite In-Reply-To: <91055e8b-ce64-49a3-b736-16afe8336c4b@e39g2000hsf.googlegroups.com> References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> <91055e8b-ce64-49a3-b736-16afe8336c4b@e39g2000hsf.googlegroups.com> Message-ID: <65c4csF2f0dq5U1@mid.uni-berlin.de> aiwarrior wrote: > [...] > What i'm going to study is whether it's possible to evaluate if a > table already exists, and if so act accordingly. [...] You can use a statement like "CREATE TABLE IF NOT EXISTS tbl(col1, col2);". If you just want to check, you can query SQLite's schema metadata with something like def table_exists(con, table_name): return con.execute("select count(*) from sqlite_master where type='table' and tbl_name=?", (table_name,)).fetchone()[0] -- Gerhard From gagsl-py2 at yahoo.com.ar Wed Mar 19 21:31:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 22:31:28 -0300 Subject: Inserting DTD statement to XML References: <80eadd7f-5a2b-4fa1-a561-23e542436232@8g2000hsu.googlegroups.com> Message-ID: En Wed, 19 Mar 2008 15:33:19 -0300, jakecjacobson at gmail.com escribi?: > I am new to Python and I am writing a script to build a XML document > and post it to a website. I have a working script but need to insert > a DTD statement in my XML document and can't find out how to do this. > I am using "from xml.dom.minidom import Document" > > Some code I am using is: > > doc = Document() > rootNode = doc.createElement("employees") > doc.appendChild(rootNode ) > > I get the following when I print it out > > > > ... > >What I would like is to have something like: > > > > > ... > > Try this: from xml.dom.minidom import getDOMImplementation impl = getDOMImplementation() dt = impl.createDocumentType("employees", "-//ICES//DTD ICES EMPLOYEES//EN", "") doc = impl.createDocument(None, "employees", dt) root = doc.documentElement node = doc.createElement("foo") node.setAttribute("some","attribute") node.setAttribute("attr","value") root.appendChild(node) print doc.toxml() But unless you *have* to use DOM for some reason, better switch to another, more "pythonic" library. Like ElementTree or lxml (both implement the same interface); the former comes with Python 2.5, the later you can get from http://codespeak.net/lxml import xml.etree.ElementTree as ET root = ET.Element("employees") ET.SubElement(root, "foo", some="attribute", attr="value") ET.dump(root) # # ElementTree cannot generate a doctype header, do it by hand f = open("test.xml", "w") f.write('\n') f.write('\n') f.write(ET.tostring(root)) f.close() (note: the lxml version may have doctype support) -- Gabriel Genellina From bj_666 at gmx.net Sat Mar 15 12:57:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 16:57:19 GMT Subject: Unicode/UTF-8 confusion References: Message-ID: <642dfeF27mbs3U1@mid.uni-berlin.de> On Sat, 15 Mar 2008 12:09:19 -0400, Tom Stambaugh wrote: > I'm still confused about this, even after days of hacking at it. It's time I > asked for help. I understand that each of you knows more about Python, > Javascript, unicode, and programming than me, and I understand that each of > you has a higher SAT score than me. So please try and be gentle with your > responses. > > I use simplejson to serialize html strings that the server is delivering to > a browser. Since the apostrophe is a string terminator in javascript, I need > to escape any apostrophe embedded in the html. > > Just to be clear, the specific unicode character I'm struggling with is > described in Python as: > u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for > example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of > 0x27. > > This can be expressed in several common ways: > hex: 0x27 > Python literal: u"\u0027" > > Suppose I start with some test string that contains an embedded > apostrophe -- for example: u" ' ". I believe that the appropriate json > serialization of this is (presented as a list to eliminate notation > ambiguities): > > ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] > > This is a 14-character utf-8 serialization of the above test string. > > I know I can brute-force this, using something like the following: > def encode(aRawString): > aReplacement = ''.join(['\\', '0', '0', '2', '7']) > aCookedString = aRawString.replace("'", aReplacement) > answer = simplejson.dumps(aCookedString) > return answer > > I can't even make mailers let me *TYPE* a string literal for the replacement > string without trying to turn it into an HTML link! > > Anyway, I know that my "encode" function works, but it pains me to add that > "replace" call before *EVERY* invocation of the simplejson.dumps() method. > The reason I upgraded to 1.7.4 was to get the c-level speedup routine now > offered by simplejson -- yet the need to do this apostrophe escaping seems > to negate this advantage! Is there perhaps some combination of dumps keyword > arguments, python encode()/str() magic, or something similar that > accomplishes this same result? > > What is the highest-performance way to get simplejson to emit the desired > serialization of the given test string? Somehow I don't get what you are after. The ' doesn't have to be escaped at all if " are used to delimit the string. If ' are used as delimiters then \' is a correct escaping. What is the problem with that!? Ciao, Marc 'BlackJack' Rintsch From robert.rawlins at thinkbluemedia.co.uk Mon Mar 10 06:49:37 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 10 Mar 2008 10:49:37 -0000 Subject: Logging Date/Time Format Message-ID: <00bd01c8829c$6fe77d10$4fb67730$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm using the python logging module, however I'm not happy with the current date/time format which is used to write the timestamp into the log file. I need the logger to write the stamp without the milliseconds appended too it. This is because I use a 3rd party application to parse the logs at a later date as a CSV and the comma separating the milliseconds throws things out. I've been looking through the API documentation but couldn't see any decent method for doing so. Any ideas? Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Sat Mar 1 12:13:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 1 Mar 2008 09:13:11 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> Message-ID: <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> On Mar 1, 11:23?pm, Marc 'BlackJack' Rintsch wrote: (snip) > But the type of `x` must be specialized somehow. ?`x` doesn't start as > `Int` or `Integer` but the very generic and AFAIK abstract type class `Num`. > > After seeing the second line the compiler finds an implementation for `+` > and the type class `Fractional` for both operands and now thinks `x` must > be a `Fractional`, a subclass of `Num`. > > Then comes the third line with `length` returning an `Int` and the > `Fractional` `x` but there is no implementation for a `+` function on > those types. I see, but the same arguments still holds true: the second line have an implicit side-effect of redefining x's type into Fractional type. If I were the designer of the language, I'd leave x's type as it is (as Num) and coerce x for current calculation only. From castironpi at gmail.com Sat Mar 8 13:04:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 10:04:04 -0800 (PST) Subject: multiplication of lists of strings References: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> <47ce56e9$0$10738$426a34cc@news.free.fr> Message-ID: <564294c7-cd78-483e-9393-aad0092809f7@59g2000hsb.googlegroups.com> On Mar 5, 2:16?am, Bruno Desthuilliers wrote: > castiro... at gmail.com a ?crit : > (snip) > > > That reminds me: ?Is there a generic 'relation' pattern/recipie, such > > as finding a computer that's "paired" with multiple users, each of who > > are "paired" with multiple computers, without maintaining dual- > > associativity? > > Yes : use a relational database. No performance hit. Can I write an ad hoc relational class structure? From mensanator at aol.com Tue Mar 4 14:32:59 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 11:32:59 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: <504cc6a7-985e-464e-b38c-c6d31c280e44@e10g2000prf.googlegroups.com> On Mar 4, 2:44?am, Erik Max Francis wrote: > Mensanator wrote: > > On Mar 3, 11:58 pm, Erik Max Francis wrote: > >> Mensanator wrote: > >>> I'm not hard to please at all. > >> No, of course not, since logically you must think all software is useless. > > > Somehow, I expected better logic from people who call themselves > > programmers. > > So you agree with me. ? Are you deliberately misconstruing what I write? > Lack of prefection = uselessness. ? _I_ never said that. What I said was a zero change in net functionality is "worthless". A negative change in net functionality is "less than worthless". Haven't negative numbers been well understood since the Middle Ages? Why is this concept so difficult to grasp? > Thanks for being honest, I wish I could say the same. > whether your realized you defeated your own disclaimer or not. Conclusion based on false premise. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > ? ?I wonder if heaven got a ghetto > ? ? -- Tupac Shakur From python at rcn.com Fri Mar 7 14:20:32 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 7 Mar 2008 11:20:32 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Message-ID: [Cruxic] > Is it possible to get an object out of a set() given another object > that has the same hash code and equality (__hash__() and __eq__() > return the same)? Yes, but it requires an indirect approach. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299 Raymond From aisaac at american.edu Mon Mar 3 09:06:24 2008 From: aisaac at american.edu (Alan Isaac) Date: Mon, 03 Mar 2008 14:06:24 GMT Subject: Is it possible to return a variable and use it...? In-Reply-To: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> References: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> Message-ID: Nathan Pinno wrote: > Is it possible to return a variable and then use it I think you are asking about the ``global`` statement. > like the following: Presumably not. ;-) Cheers, Alan Isaac From tjreedy at udel.edu Sat Mar 1 00:49:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Mar 2008 00:49:09 -0500 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com><13see4t3s23pn59@corp.supernews.com><9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> Message-ID: "Arnaud Delobelle" wrote in message news:ea3aecb0-c946-46be-bcd5-0c7584751e4b at b1g2000hsg.googlegroups.com... | Perhaps it'll be like when I quit smoking six years ago. I didn't | enjoy it although I knew it was good for me... And now I don't regret | it even though I still have the occasional craving. In following the development of Py3, there have been a few decisions that I wish had gone otherwise. But I agree with more than the majority and am not going to deprive myself of what I expect to be an improved experience without giving Py3 a fair trial. tjr From Jeff.Goldfinkle at gmail.com Thu Mar 6 16:01:24 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Thu, 6 Mar 2008 13:01:24 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> <%oOzj.61235$Pv2.29718@newssvr23.news.prodigy.net> Message-ID: <980961ef-43c8-4936-a536-8b5fbc04f0d0@2g2000hsn.googlegroups.com> On Mar 6, 11:00 am, Bryan Olson wrote: > Mark Dickinson wrote: > > Jeff Goldfin wrote: > >> I can pack and unpack a float into a long > >> e.g. > >> struct.unpack('I',struct.pack('f',0.123))[0] > >> but then I'm not sure how to work with the resulting long. > > >> Any suggestions? > > > One alternative to using struct is to use math.ldexp and math.frexp: > > >>>> m, e = frexp(pi) > >>>> m > > 0.78539816339744828 > >>>> e > > 2 > >>>> int(m*2**53) > > 7074237752028440L > > > Then you can do your bit twiddling on int(m*2**53), before using > > ldexp to 'repack' the float. > > Ah, those are handy. Jeff described his problem: "In particular, > I would like to round my float to the n most significant bits." > I think this works: > > from math import frexp, ldexp, floor > > def round_mantissa(x, nbits): > shifter = 1 << nbits > (m, e) = frexp(x) > m = floor(m * shifter + 0.5) / shifter > return ldexp(m, e) > > -- > --Bryan Thanks for the help - your function seems to fit the bill even better than gmpy since I don't need an external module. In my case I'll use m = floor(m * shifter) / shifter instead of m = floor(m * shifter + 0.5) / shifter Jeff From nagle at animats.com Wed Mar 26 11:51:42 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 08:51:42 -0700 Subject: Beta testers needed for a high performance Python application server In-Reply-To: <7xd4pi2bn4.fsf@ruckus.brouhaha.com> References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> <47e9f77b$0$36357$742ec2ed@news.sonic.net> <7xd4pi2bn4.fsf@ruckus.brouhaha.com> Message-ID: <47EA710E.9090909@animats.com> Paul Rubin wrote: > John Nagle writes: >> Fast cgi is a good technology, but it's not well documented or >> well supported. For some reason, the Apache people don't like it. >> It used to be part of the Apache distribution, but that ended years ago. > > It seems to be coming back into favor. See: > > http://cryp.to/publications/fastcgi/ That paper is from 2002. John Nagle From kyosohma at gmail.com Wed Mar 19 14:26:26 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 11:26:26 -0700 (PDT) Subject: modules devoted to manipulationg .reg files References: <12fdb0c5-f880-4264-86d1-be3ad2be8c51@c19g2000prf.googlegroups.com> Message-ID: <5e897a4c-fb4d-4184-8152-176ce3fdfe27@u10g2000prn.googlegroups.com> On Mar 19, 1:14 pm, black_13 wrote: > are there any python modules for manipulation of .reg files producted > by > the win32 prog "reg". > thanks. > black_13 The *.reg files are text files, so you can parse them like any text file. You can just edit the Windows Registry directly using the built- in module: _winreg. There's also a more abstract wrapper called YARW. Mike From sophacles at gmail.com Thu Mar 20 17:53:43 2008 From: sophacles at gmail.com (Erich) Date: Thu, 20 Mar 2008 14:53:43 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> Message-ID: <927f5a44-f8fa-4fe2-bdc2-12fac2d50e7a@s37g2000prg.googlegroups.com> On Mar 20, 12:39 pm, Ed Leafe wrote: > On Mar 20, 2008, at 11:54 AM, atom.ander... at gmail.com wrote: > > > Number Three: Too much code, not enough concept. > > > Presenters this one's for you. I can't count the number of > > presentations I attended where the presenter would click through three > > slides of pycode just to show us a two or three-line snippet that > > illustrated their point. Worse yet, it was often at the bottom of the > > screen so no one but the front row could see it. This goes for text > > two. I saw some great presentations as well, and they had limited > > text on each slide. The last thing your audience wants to see is a > > slide drenched in text of any kind. > > This is good advice: simple slides serve as organization cues, but > the content should come from the speaker. The worst case (only saw > this twice at this year's PyCon) is when there is a text-heavy slide > that the presenter simply reads. We can all read it ourselves! Your > job is to elaborate on the topic. > > I'd like to see two things regarding slides: first, if at all > possible, set a limit on the percentage of the talk that can consist > of slides. I would much rather see the presenter show actual > demonstrations of what they're talking about than simply talking about > it. If that's not possible, then in the session description, clearly > state the % of the talk that will be slides. Perhaps there are people > who like to sit in a room and watch long PowerPoint (-type) > presentations, but I'm not one of them. Let's see some code! Let's see > stuff working (and sometimes crashing!), and how changes affect the > results. When I've presented at PyCon and other conferences, that's > the part that I spend the most time on: preparing demonstrations. It's > not easy to do; certainly much more difficult than creating a slide > that sums up what the demo does. But it makes for a much more > interesting session! > > -- Ed Leafe I'd like to see code listings made available to download where appropriate. That way the slides dont have much hard to read content, and we can look at the bits of code we find tricky as we see fit. And if we get bored with bits, we can play with code! Erich. From sajmikins at gmail.com Tue Mar 18 05:57:06 2008 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Mar 2008 02:57:06 -0700 (PDT) Subject: finding items that occur more than once in a list Message-ID: Is there a more efficient way to do this? def f(L): '''Return a set of the items that occur more than once in L.''' L = list(L) for item in set(L): L.remove(item) return set(L) |>> f([0, 0, 1, 1, 2, 2, 3]) set([0, 1, 2]) From paul at boddie.org.uk Sun Mar 2 15:35:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 2 Mar 2008 12:35:19 -0800 (PST) Subject: tuples, index method, Python's design References: Message-ID: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> On 2 Mar, 19:06, Alan Isaac wrote: > On April 12th, 2007 at 10:05 PM Alan Isaac wrote: > > > The avoidance of tuples, so carefully defended in other > > terms, is often rooted (I claim) in habits formed from > > need for list methods like ``index`` and ``count``. > > Indeed, I predict that Python tuples will eventually have > > these methods and that these same people will then defend > > *that* status quo. You were more confident about this than I was. Still, nothing happens if no-one steps up to do something about it. > > > - Issue #2025 : Add tuple.count() and tuple.index() > > methods to comply with the collections.Sequence API. Here's the tracker item that may have made it happen: http://bugs.python.org/issue1696444 I think you need to thank Raymond Hettinger for championing the cause. ;-) Paul From Afro.Systems at gmail.com Sat Mar 29 16:40:16 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sat, 29 Mar 2008 13:40:16 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> Message-ID: <5ce5652e-4e75-49ca-acb8-30bc6efd350d@b1g2000hsg.googlegroups.com> after executing insert do conection.commit() From sturlamolden at yahoo.no Wed Mar 19 11:56:16 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 08:56:16 -0700 (PDT) Subject: is hash map data structure available in Python? References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Message-ID: <87a293ab-c4f1-4dfc-97b7-efb10bb42e6b@e6g2000prf.googlegroups.com> On 19 Mar, 09:40, grbgooglefan wrote: > How do I create hash map in Python? Python dictionaries are the fastest hash maps known to man. If you need persistent storage of your hash map, consider module bsddb or dbhash. From castironpi at gmail.com Sun Mar 2 11:09:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 08:09:24 -0800 (PST) Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> Message-ID: On Mar 2, 8:15?am, Giles Brown wrote: > On Mar 2, 2:08 pm, Preben Randhol > +valid_for_reply_from_n... at pvv.org> wrote: > > On Sun, 2 Mar 2008 15:06:17 +0100 > > > Preben Randhol wrote: > > > ? ?class dbase(list): > > > Sorry the definition of the class is: > > > ? ? ? ? class dbase(object): > > > it doesn't derive from the list class. > > > Preben > > http://docs.python.org/lib/typeiter.html Be careful on your descision to return an ordered iterator or not-- that is, whether it iterates over the dictionary or the list (if I understand you correctly). If the order's unimportant then please disregard. You can also use: >>> a= [2,3,4] >>> b= iter( a ) >>> next( b ) 2 >>> next( b ) 3 >>> next( b ) 4 From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 21:34:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 01:34:17 -0000 Subject: Big file References: Message-ID: <13th14pe0hhsie1@corp.supernews.com> On Wed, 12 Mar 2008 19:42:44 -0500, Andrew Rekdal wrote: > I am working in the class constructor defining elements of an > application. The problem is the file is getting unmanageble and I am > wanting to extend the contructor __init__ to another file. > > Is it possible to import directly into the contructor the contents of > another module file? > > If so how would this be done? Here's the way you do what you literally asked for: class MyClass(object): def __init__(self, *args): # Warning: completely untested execfile('myfile.py') # may need extra arguments? but you almost certainly don't want to do that. A better way is by importing modules, the same as you would for anything else: class MyClass(object): def __init__(self, *args): from AnotherModule import constructor constructor(self, *args) But frankly if you find yourself needing to do this because your file is "too big" and is unmanageable, I think you are in desperate need of refactoring your code to make if more manageable. Pushing vast amounts of random code out into other files just increases the complexity: not only do you have vast amounts of code, but you have large numbers of files to manage as well. -- Steven From johan.sanden at gmail.com Thu Mar 6 14:03:24 2008 From: johan.sanden at gmail.com (johan.sanden at gmail.com) Date: Thu, 6 Mar 2008 11:03:24 -0800 (PST) Subject: What is a class? References: Message-ID: On Mar 5, 7:50 pm, castiro... at gmail.com wrote: > What is a class that is not a module? A class is a bag of stuff and a namespace :) J. From cruxic at gmail.com Fri Mar 7 14:13:28 2008 From: cruxic at gmail.com (Cruxic) Date: Fri, 7 Mar 2008 11:13:28 -0800 (PST) Subject: Can't get items out of a set? Message-ID: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Hello, all. Is it possible to get an object out of a set() given another object that has the same hash code and equality (__hash__() and __eq__() return the same)? You can't do this with Java Sets either and I've needed it on multiple occasions. Doesn't it seem like it would be useful? Consider: class Person: def __init__(self, id, name): self.id = id self.name = name def __hash__(self): return self.id def __eq__(self, other): return self.id == other.id people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) ... p = people.get_equivalent(2) #method doesn't exist as far as I know print p.name #prints Sue I'm not sure if the above code compiles but I hope you get the idea. Is it possible? Much Thanks. - Cruxic From mensanator at aol.com Tue Mar 4 15:03:47 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 12:03:47 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: <7b1ddced-8138-4ddd-ba87-fb1d55e23197@d4g2000prg.googlegroups.com> On Mar 4, 10:50?am, Lie wrote: > On Mar 4, 1:12?pm, Mensanator wrote: > > > > > > > On Mar 3, 11:58?pm, Erik Max Francis wrote: > > > > Mensanator wrote: > > > > While we're on the subject of English, the word "worthless" > > > > means "has no value". So, a program that doesn't work would > > > > generally be "worthless". One that not only doesn't work but > > > > creates side effects that cause other programs to not work > > > > (which don't have bugs) would be "worse than worthless". > > > > All programs have bugs, which means that in some circumstances, they > > > won't work. ? > > > And in such circumstances, would be worthless. > > > > Therefore, by your reasoning, all programs are worse than > > > useless. > > > That doesn't follow from my reasoning. > > > Suppose you downloaded a new calculator program that > > couldn't add properly. That would be useless to you, right? > > > But suppose the program contained a virus that erased > > your hard drive. That would be "worse than useless", wouldn't it? > > > > > I'm not hard to please at all. > > > > No, of course not, since logically you must think all software is useless. > > > Somehow, I expected better logic from people who call themselves > > programmers. > > Mensanator, for alls sake, you've done right by pointing out the bug > instead of muttering silently in your room, I thought that was what's important. Who am I that anyone cares about my opinions? > but there is a thing > called tolerance that you really should learn, it's about tolerating > and understanding the possibility that other people are humans too and > humans create mistakes, lots of them in fact and that includes you (if > you're humans). Actually, I had resolved to do that and I thought my original post reflected that. Guess I still have to work at it. > Along with tolerance should come a better choice of > wordings, Apparently. > instead of saying "it sucks " I didn't say that. > "because it does something unexpected and unwanted" I didn't say that either. "Unexpected and unwanted" is not necessarily a problem, provided those symptoms are confined to the program. When they reach out and damage things outside the program, it's a lot more serious. > and telling everyone not to use it, It was intended as a warning not to use it. When I saw the random number generator wasn't working, guess what the last cause was that I considered? Do you realize how subtle that error is, how many times I had to stare at it before realizing the problem? You can't see it looking at the trees (factorint() reurns exactly the factors of the composite it was given). It isn't until you step back and look at the forest you suddenly realize that the sequence coming from the "randomly" selected factors is repeating. I was trying to prevent a lot of head scratching by other end users who may be playing with it. > you could > just say "it does something unexpected and unwanted" and say that you > wanted it fixed. I don't think that conveys the proper seriousness. > It's not that you've done anything wrong, but it's > about your attitude. As I said, I thought I had toned done the attitude. OTOH, I'm not sure certain others aren't deliberately misconstuing what I wrote. From troworld at gmail.com Sun Mar 2 15:50:09 2008 From: troworld at gmail.com (Tro) Date: Sun, 2 Mar 2008 15:50:09 -0500 Subject: Altering imported modules In-Reply-To: <200803011856.27611.troworld@gmail.com> References: <200803011856.27611.troworld@gmail.com> Message-ID: <200803021550.09713.troworld@gmail.com> On Saturday 01 March 2008, Tro wrote: > Hi, list. > > I've got a simple asyncore-based server. However, I've modified the > asyncore module to allow me to watch functions as well as sockets. The > modified asyncore module is in a specific location in my project and is > imported as usual from my classes. > > Now I'd like to use the tlslite library, which includes an asyncore mixin > class. However, tlslite imports "asyncore", which doesn't include my own > modifications. > > I'd like to know if it's possible to make tlslite load *my* asyncore module > without changing any of the tlslite code. I guess I could just copy over the relevant tlslite file that imports asyncore and change the import, but that seems clumsy. Is there no better way? Thanks, Tro From aboudouvas at panafonet.gr Thu Mar 27 08:48:12 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 05:48:12 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> Message-ID: On 27 ???, 14:35, Paul Rubin wrote: > king kikapu writes: > > it seems that Psyco's author will not port it for the upcoming Python > > 3000 release :( > > I think the idea is it will be part of PyPy and you should use that. I know that his efforts are on PyPy now but i do not know when PyPy is going to be stable and if i can use it with my current "development stack" (PyQt, Eric4 etc). I mean, i do not know if it will be possible to "abandon" CPYthon and use PyPy instead. From gagsl-py2 at yahoo.com.ar Thu Mar 6 06:35:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 09:35:07 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: En Wed, 05 Mar 2008 02:57:58 -0200, escribi?: >> > > >> >> Can you overload -type-'s decision of what to 'bind'?... >> whenever it >> > > >> >> is it makes it. >> >> > > >> Use delegation instead of inheritance. This class is almost ? >> > > >> indistinguishable from a true function (when used as a method): >> >> Notwithstanding. ?Now bar has a name. > Now func has it. > > from functools import wraps > class myfunction: > __slots__ = ('func','name') > # > def __init__(self, func): > @wraps( func ) > def f( *ar, **kws ): > return func( self, *ar, **kws ) > object.__setattr__(self, 'func', f) > object.__setattr__(self, 'name', None) > # > def __get__(self, instance, owner): > print( "__get__ called for",instance ) > return self.func.__get__(instance, owner) > # > def __getattr__(self, name): > return getattr(self.func, name) > # > def __setattr__(self, name, value): > object.__setattr__(self.func, name, value) > > class mymeta( type ): > def __init__( self, name, bases, namespace ): > for k,v in namespace.items(): > if isinstance( v, myfunction ): > v.name= k > > class P( metaclass= mymeta ): > def foo(self, x): print( 'foo',x ) > # > @myfunction > def bar( fob,self, x): print( 'bar',fob,x ) > > p= P() > p.foo( 0 ) > p.bar( 1 ) > print( p.bar ) > print( p.bar.name ) Mmm, looks too complicated and I don't see any advantage over the original code. Functions already know their (original) name: func_name. If `name` was just an example, note that functions already have writeable attributes too, and my code exposes them as well. This should work with that version (untested): p = P() print p.bar.func_name # -> bar p.bar.im_func.anotherattribute = 1 print p.bar.anotherattribute # -> 1 (the attribute must be set on the *function* itself if you want it to be somewhat persistent; methods are usually volatile objects) -- Gabriel Genellina From nick.fabry at coredump.us Fri Mar 21 22:37:31 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Fri, 21 Mar 2008 22:37:31 -0400 Subject: Improving datetime In-Reply-To: <47E3F234.9010607@cheimes.de> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <47E3C1A3.6050608@ncf.ca> <47E3F234.9010607@cheimes.de> Message-ID: On Mar 21, 2008, at 13:36, Christian Heimes wrote: > Colin J. Williams schrieb: >> You might consider adding the Julian date >> (http://en.wikipedia.org/wiki/Julian_date). >> >> I had a crack at this a while ago but didn't seem to get quire the >> right >> result, using the ACM algorithm. I seemed to be a day out at the >> BC/AD >> divide. > > Yes, the Julian date family is very useful when dealing with dates > before 1900. I'm +1 for adding JDT and MJD. > > TAI64 is another time format used for high precision and real time > measurement. http://cr.yp.to/libtai/tai64.html > This is that 'feature creep' thing I keep reading about on Dilbert, eh? ;-) Obviously, this would not be considered an 'easy bit' - however, the basic datetime.datetime class needs overhauling anyway when we get to the harder bits. So, it's worth determining whether we just want to have it run in the proleptic Gregorian calendar (ISO 8601), or figure out other calendars as well. I don't know anything about TAI64, but I'll read about it. The Julian I do know about (rioting after 'losing' 10 days? Sheesh!) - it was a pretty reasonable swag at hitting the solar year for its time.... Perhaps it might be wise to consider a 'calendar definition object' - I'll dub it a calinfo object for now - that allows third parties to develop a set of rules that define a) how to count in a calendar, and b) how to translate unambiguously from one calendar to another. This suggests that we need a 'standard' calendar, much like UTC is the default timezone for calculations; the proleptic Gregorian seems like the obvious choice for now. So, a new 'superaware' datetime object represents a moment in time and would have: a local datetime, representing what 'local' clocks and calendar indicate at that time a UTC datetime, representing what UTC clocks and calendar indicate at that time a tzinfo object, encapsulating the the rules for translating local times to/from UTC, and a calinfo object, encapsulating: the calculation rules for adding & subtracting timedeltas to datetimes the calculation rules for finding the timedelta between two datetimes the translation rules for converting a datetime with a calinfo object into a datetime with a 'standard' calinfo object With time zones, because their offsets regularly swing back and forth, we have issues with illegal and ambiguous local times. I don't know much about different calendars - I am somewhat sure for Gregorian <--> Julian there are no ambiguities or 'illegal' dates, but I don't know about other calendars. I haven't thought of this before. I need to mull over how to do this - if we are going to spend the time developing three different methods of calculations for three different calendars, and I know there are other calendar systems in the world, it strikes me that the forward thinking thing to do is figure out how to abstract the calendar rule concept, develop a few common examples, and leave it to others (initially) to develop other calendars, much as third parties implemented concrete tzinfo subclasses. In doing so, they revealed some of the present limitations with the current implementation of datetime, that we are now considering updating. We may not have enough experience here of other calendar systems to get this totally right on the first go round, but it sounds worth a try.... > Christian > P.S. By Stewart, I assume you mean the author of pytz? And I think I got the 'no novel' concept - write for people who understand the basic ideas already. Have a good weekend! Nick > -- > http://mail.python.org/mailman/listinfo/python-list From needin4mation at gmail.com Thu Mar 20 11:30:28 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 20 Mar 2008 08:30:28 -0700 (PDT) Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> Message-ID: On Mar 20, 11:21?am, Grant Edwards wrote: > On 2008-03-20, jmDesktop wrote: > > > Hi, I'm trying to learn Python. ?I using Aquamac an emac > > implementation with mac os x. ?I have a program. ?If I go to the > > command prompt and type pythong myprog.py, it works. ?Can the program > > be run from within the editor or is that not how development is done? > > I ask because I was using Visual Studio with C# and, if you're > > familiar, you just hit run and it works. ?On Python do I use the > > editor for editing only and then run the program from the command > > line? > > http://www.google.com/search?q=emacs+python > > -- > Grant Gee. Thanks. From mail at timgolden.me.uk Tue Mar 18 05:02:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 18 Mar 2008 09:02:26 +0000 Subject: Convert binary file In-Reply-To: <6487iaF2ar8k2U1@mid.uni-berlin.de> References: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> <6487iaF2ar8k2U1@mid.uni-berlin.de> Message-ID: <47DF8522.2010700@timgolden.me.uk> Diez B. Roggisch wrote: > Vamp4L schrieb: >> Hello, >> Specifically, I'm trying to convert the Internet Explorer history >> file (index.dat) into a readable format. Anyone done something >> similar or know of any functions that may help with such a task? I'm >> not sure exactly what kind of file the index.dat is, it is some kind >> of binary file. I have tried some of the binascii functions (http:// >> docs.python.org/lib/module-binascii.html) without any luck. >> Thanks > > You have to have a definition of the format or reverse engineer it. If > you have done that, you can use the module struct. > > But there is no generic way to infer how a binary format is built. Well, there is some info here: http://answers.google.com/answers/threadview?id=115849 on the subject. But, honestly, doing any kind of direct messing with opaque file formats (Microsoft's or anyone else's) is pretty much asking for trouble. Without my ever having tried this, it looks as though a combination of comtypes and IID_IUrlhistoryStg2 [2] might work. If I get the time later I'll try to knock sthg together. (Unless someone else pops in first!) TJG [1] http://pypi.python.org/pypi/comtypes [2] http://support.microsoft.com/kb/897169 From rschroev_nospam_ml at fastmail.fm Sat Mar 29 08:06:27 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 29 Mar 2008 13:06:27 +0100 Subject: finding euclidean distance,better code? In-Reply-To: <13us4sh6u8mfn96@corp.supernews.com> References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> Message-ID: <8hqHj.175213$8Z.117427@newsfet10.ams> Steven D'Aprano schreef: > On Sat, 29 Mar 2008 10:11:28 +0100, Roel Schroeven wrote: > >> Steven D'Aprano schreef: >>> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: >>> >>>> Gabriel Genellina wrote: >>>>> That's what I said in another paragraph. "sum of coordinates" is >>>>> using a different distance definition; it's the way you measure >>>>> distance in a city with square blocks. I don't know if the distance >>>>> itself has a name, but >>>> I think it is called Manhattan distance in reference of the walking >>>> distance from one point to another in this city. >>> You know, there are other cities than Manhattan. Some of them even have >>> streets and blocks. >> I'm not sure what your point is. The name > > "The" name? You go on to list four additional names, so why do you say > that "Manhattan distance" is THE name? When I studied this at university, > we called it the taxi metric. > > >> of the distance happens to be >> Manhattan distance (or taxicab distance, rectilinear distance, L1 >> distance, city block distance; see >> http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid >> point. > > Wikipedia doesn't believe that M-D is the primary or most common name, > and the link you give redirects to "Taxicab distance". Googlefight > agrees: "Taxicab distance" is more than twice as common, and "rectilinear > distance" more than five times as common. > > My point was to draw attention to Robert's unconscious assumptions which > are reflected in his choice of language. Rectilinear distance applies to > more than "distance from one point to another in THIS city" (emphasis > added). You can hardly blame that on Robert. It's true that Manhattan distance is not the only name and not even the most popular one, but it's also true that it's a valid name, and that Robert didn't invent it, he merely used an existing name. > It applies in parts of Rome, Sydney, London, Moscow and many other > places. It even applies to sleepy little country towns like Bendigo and > Mildura here in Australia. Manhattan is hardly the only place where > cities are carved up into rectangular or square city blocks, and I doubt > that it applies to the entirety of Manhattan. No, but it's actually very close. I just looked at the places you mention in Google Earth; while they do have sections with rectangular layouts, in none of them it is as prevalent and obvious as in Manhattan (Manhattan isn't a city of course like the other ones, it's only a part of New York). Now of course it's true that there are many other places with checker board layouts, but I still don't think that makes Manhattan distance a bad name. > The very name is New York-centric, just as much as if the English called > the science of acoustics "Big-Ben-onics" in reference to the peals of Big > Ben's clock. I had thought I had pointed that out with a little gentle > understatement. I'm absolutely not USA/America/New York centric myself, but Manhattan simply is a good and well-known example of a checker board layout. There are worse examples of bad names: 'French fries' for example is French-centric, but that's not the real problem. The real problem is that the name is simply wrong because fries are Belgian (which is disputed, but I believe it since I'm from Belgium ;) ). But I'm still not going the call them freedom fries or anything. In any case, I replied because your reaction didn't feel all that gentle to me; to be honest, it felt rather rude. I apologize for interpreting the tone incorrectly. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From steve at REMOVE-THIS-cybersource.com.au Tue Mar 18 09:10:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 18 Mar 2008 13:10:26 -0000 Subject: how to create instances of classes without calling the constructor? References: <47df0816$0$6635$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <13tvfq214jf8b79@corp.supernews.com> On Tue, 18 Mar 2008 01:08:45 +0100, Dominik Jain wrote: > Hi! > > Does anyone know how an instance of a (new-style) class can be created > without having to call the constructor (and providing the arguments it > requires)? With old-style classes, this was possible using new.instance. > Surely there must be a simple way to do this with new-style classes, too > -- or else how does pickle manage? I don't think you can create an instance without calling __new__. (At least not without all sorts of metaclass tricks.) Creating the instance is what __new__ does. But you can create a new instance without calling the initialiser __init__. Here's a variation on a recipe from Alex Martelli: class Spam(object): def __init__(self, *args): print "spam spam spam spam" self.args = args def empty_instance(cls): class Empty(cls): def __init__(self): pass x = Empty() x.__class__ = cls return x >>> # Create a Spam instance the regular way ... a = Spam("args") spam spam spam spam >>> # And a Spam instance the unusual way ... b = empty_instance(Spam) >>> a.args ('args',) >>> b.args Traceback (most recent call last): File "", line 1, in AttributeError: 'Spam' object has no attribute 'args' -- Steven From castironpi at gmail.com Sun Mar 30 15:43:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 12:43:31 -0700 (PDT) Subject: question Message-ID: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> Say you have an auditory waveform. In dream hardware, positives would accumulate until something, which would trigger a small chain reaction. In software, with a function f of time t, f( t ), in constant space, what can you know at t? Presume. Silence first, then a broken triad vamps. How long til you recognize it? One sec., i'll attach a binary. From mail at timgolden.me.uk Mon Mar 17 07:34:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 17 Mar 2008 11:34:56 +0000 Subject: Spaces in path name In-Reply-To: References: <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> <708a66a7-da8f-4d44-824d-8a25203030f7@n58g2000hsf.googlegroups.com> Message-ID: <47DE5760.5050203@timgolden.me.uk> Gertjan Klein wrote: > joep wrote: > >> * If shell=True is required, then the executable is a build-in shell >> command, which does not contain spaces, and, therefore, has no >> problems > > This is only true when you are referring to directly executable files. > However, Shell=True is also required when you want to "execute" a file > by it's association. For example, if you want to execute a ".pyw" file > directly (i.e., by using whichever python executable is associated with > that extension), you need Shell=True. Thanks for that clarification. I hadn't tried that path. TJG From godzillaismad at gmail.com Fri Mar 21 02:13:22 2008 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 20 Mar 2008 23:13:22 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: Just found out that win32api.GetTickCount() returns a tick count in milli-second since XP started. Not sure whether that is reliable. Anyone uses that for calculating elapsed time? From mensanator at aol.com Tue Mar 11 15:36:04 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 11 Mar 2008 12:36:04 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <2fec18c7-2ca7-4706-95b4-3244a01469b0@s19g2000prg.googlegroups.com> On Mar 11, 10:57?am, Mike Hansen wrote: > If one wants to do serious math using Python, the best bet is to use > Sage (http://www.sagemath.org). ?Here are some examples: > > sage: def f(x, bits=53): > ....: ? ? R = RealField(bits); z = R(x) > ....: ? ? return cos(R(pi) * factorial(z-1) / z) > sage: f(100.00,bits=1000) > 0.9999999999999999999999999999999999999999999999999999999999999999999999999?999999999999999999999999999999999999999999999999999999999999999999999999999?999999999999999999999999999999999999999999999999999999999999999999999999999?999999999999999999999999999999999999999999999999999999999999999999999999923?43 If one wants to do serious math using Python, it would be even better to understand the math before breaking out Sage. Didn't you realize that cos(pi*n) is a red herring? That you only need to know if the rational factorial(z-1)/z has a denominator >1 (although you have to make allowances when it's 2)? 2 Prime: True True Prime: True 1/2 3 Prime: True True Prime: True 2/3 4 Prime: False True Prime: False 3/2 5 Prime: True True Prime: True 24/5 6 Prime: False True Prime: False 20 7 Prime: True True Prime: True 720/7 8 Prime: False True Prime: False 630 9 Prime: False True Prime: False 4480 10 Prime: False True Prime: False 36288 11 Prime: True True Prime: True 3628800/11 12 Prime: False True Prime: False 3326400 13 Prime: True True Prime: True 479001600/13 14 Prime: False True Prime: False 444787200 15 Prime: False True Prime: False 5811886080 16 Prime: False True Prime: False 81729648000 17 Prime: True True Prime: True 20922789888000/17 18 Prime: False True Prime: False 19760412672000 19 Prime: True True Prime: True 6402373705728000/19 > > sage: a = > 508184298003433059930221143303110332712493139579190463526792062622045893426?23811236647989889145173098650749 > sage: time ecm.factor(a) > CPU times: user 0.00 s, sys: 0.06 s, total: 0.06 s > Wall time: 2.63 > > [3478697, > ?49998841, > ?11927295803, > ?518069464441, > ?1858900129817, > ?161610704597143, > ?157394131396743433859615518992811454816816449] > > sage: a = ZZ.random_element(10**100); a > 126608167051554688363992508839040790329461609432561783112868335758991396849?7538978358203322629420841 > sage: a.is_prime() > False > sage: b = a.next_prime(); b > 897566586864575221876983862371789080887133487597424495265748007237361461447?1639002293590745490978883 > sage: b.is_prime() > True > > --Mike From mail2spj at yahoo.com Tue Mar 25 11:28:06 2008 From: mail2spj at yahoo.com (SPJ) Date: Tue, 25 Mar 2008 08:28:06 -0700 (PDT) Subject: Reading new mail from outlook using Python In-Reply-To: <47E81CE4.10305@howaboutnow.net> Message-ID: <971720.4797.qm@web50104.mail.re2.yahoo.com> Thanks... I could access the folders in outlook express using the COM interface. Now I am stuck with how to read to a file only new mails. Anyone knows how to achieve this? Thanks SPJ --- On Tue, 3/25/08, Pete Stapley wrote: > From: Pete Stapley > Subject: Re: Reading new mail from outlook using Python > To: mail2spj at yahoo.com > Cc: python-list at python.org > Date: Tuesday, March 25, 2008, 2:58 AM > Well on a FreeBSD/Unix system you can use the .forward to > pipe the > incoming mail for a user to a program. Below is the > contents of my > .forward that invokes procmail. > > "|/usr/local/bin/procmail -m > /path/to/conf/.procmailrc" > > So I imagine you could do something like this in a > .forward. > > "|/path/myprogram.py" > > SPJ wrote: > > Hi, > > > > I am trying to create new tickets in the ticketing > system using > > python. When I receive new email from a particular > address, I have to > > trigger the python script and parse the mail in > required format. > > > > The main hurdle here is, how to invoke the script on > arrival of new > > mail? I checked the outlook settings and found that it > supports only > > microsoft VB script and Jscript. Is there any other > way? I mean, if I > > make a daemon, how will it be notified of new mail? Is > there any > > python module that does this? > > > > I am not sure if this is the right place to ask this, > since it is also > > a microsoft related question. But any help is > appreciated. > > > > Thanks, > > SPJ > > > > > > > ------------------------------------------------------------------------ > > Be a better friend, newshound, and know-it-all with > Yahoo! Mobile. Try > > it now. > > > ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 19:05:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 23:05:15 -0000 Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: <13u5rdb7vmqsma3@corp.supernews.com> On Thu, 20 Mar 2008 10:45:03 -0700, Sean DiZazzo wrote: > After trying again this morning, the file is opened for reading. I must > have had some wonky permissions on that file, so the error method won't > work. Then fix the permissions. -- Steven From paul at boddie.org.uk Sun Mar 30 15:32:21 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Mar 2008 12:32:21 -0700 (PDT) Subject: Vote for a New EuroPython Logo! Message-ID: Earlier this year, the organisers of EuroPython (the annual European Python community conference) decided it was time to update the conference logo: the current logo has been in use since EuroPython began back in 2002. We asked for and received many great submissions for a new logo, and we've made these available on the EuroPython Web site. Now we need your help in deciding which logo shall be part of the EuroPython conference's updated image. Visit the EuroPython Web site to browse the submissions and to cast your votes on the ones you like the most: http://www.europython.org/community/Planning/ProposedLogo We intend to announce the winning logo on Friday 4th April at the latest, so hurry on over to the EuroPython site and cast your votes now! (And stay tuned for more updates on EuroPython 2008!) From larry.cebuala at gmail.com Tue Mar 18 01:25:28 2008 From: larry.cebuala at gmail.com (Larry) Date: Mon, 17 Mar 2008 22:25:28 -0700 (PDT) Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> Message-ID: <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> Thanks to all those who responded to this query. It seems to me that Python always add intervening spaces between data elements when writing to a file. Even with tostring() of numpy, array elements get separated by space character. I like the output of sys.stdout.write(file) to be writen as is to a binary file, but how? I'll try your suggestions. Good luck, especially to me! :) From felciano at gmail.com Mon Mar 24 10:15:58 2008 From: felciano at gmail.com (felciano) Date: Mon, 24 Mar 2008 07:15:58 -0700 (PDT) Subject: Multiline CSV export to Excel produces unrecognized characters? References: <4f6f122f-45bb-4aa5-b9c9-5eb3e84a0964@i7g2000prf.googlegroups.com> <64p25uF2c2qidU2@mid.uni-berlin.de> Message-ID: > > Any chance you are doing this on Windows and Excel doesn't like the > return+linefeed line endings that Windows produces when writing files in > text mode? Try 'wb' as mode for the output file. > > Ciao, > Marc 'BlackJack' Rintsch > Fixed! Can't believe I missed that... Thank you for the quick reply! Ramon From craigm3604 at gmail.com Tue Mar 25 11:24:13 2008 From: craigm3604 at gmail.com (Craig) Date: Tue, 25 Mar 2008 08:24:13 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> <8fd0d8bd-c80a-4ec1-a70a-ea659a84413e@e6g2000prf.googlegroups.com> <13uh5bq2ri0280a@corp.supernews.com> Message-ID: On Mar 25, 2:02 am, Dennis Lee Bieber wrote: > On Mon, 24 Mar 2008 15:21:11 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > And this is what I got: > > VmxGet test - looking for valid record... > > Before - PriKey = 0x0044F56C, SecKey = 0x0044F534 > > ci_PriKey = 0x0044F56C, ci_SecKey = 0x0044F534 > > After - PriKey = 0x0044F56C, SecKey = 0x0044F534 > > ci_PriKey = 0x0043D49C, ci_SecKey = 0x0043D484 > > So VmxGet() DID allocate new BSTR structures. > > It might be interesting to extract the length data that is part of > the BSTR and compare. > > ctypes.string_at(PriKey - 4, 4) #if I recall the arguments > vs > ctypes.string_at(ci_PriKey - 4, 4) > > If the second (after conversion to integer) is larger than the > former, it could mean that the routine checks what is passed in to > ensure enough storage space, and if it won't fit, does the allocation. > > If it were always going to do an allocation, there would have been > no excuse for /reading/ the passed in structure length. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ I changed to the following to followup on the length data: printf ("Before - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(ci_SecKey), byref(ci_PriKey), TypeDef ) printf ("After - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) print ord(string_at(PriKey - 4, 1)), ord(string_at(PriKey - 3, 1)), ord(string_at(PriKey - 2, 1)), ord(string_at(PriKey - 1, 1)) print ord(string_at(ci_PriKey.value - 4, 1)), ord(string_at(ci_PriKey.value - 3, 1)), ord(string_at(ci_PriKey.value - 2, 1)), ord(string_at(ci_PriKey.value - 1, 1)) And, got: Before - PriKey = 0x0028B6FC, SecKey = 0x0028B6C4 ci_PriKey = 0x0028B6FC, ci_SecKey = 0x0028B6C4 After - PriKey = 0x0028B6FC, SecKey = 0x0028B6C4 ci_PriKey = 0x0027D284, ci_SecKey = 0x0027D26C 41 0 0 0 7 0 0 0 Which makes sense for two reasons: 1. It would only return the non-space-filled part of the returned key. 2. At least from VB6, the variable does not even have to be used before the call. I have gone on to design a function for printing the contents as fields in a Structure. def DCOD_Print(): temp = unpack(DecoderRecordFormat, TypeDef.raw) DCOD = DecoderRecord(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5]) print " DistID = \x22%s\x22" % DCOD.DistID print " YearCode = \x22%s\x22" % DCOD.YearCode print " AccountType = \x22%s\x22" % DCOD.AccountType print "AccountNumber = \x22%s\x22" % DCOD.AccountNumber print " Description = \x22%s\x22" % DCOD.Description print " Unused = \x22%s\x22" % DCOD.Unused return class DecoderRecord(Structure): _fields_ = [ ("DistID", c_char_p), ("YearCode", c_char_p), ("AccountType", c_char), ("AccountNumber", c_char_p), ("Description", c_char_p), ("Unused", c_char_p) ] DecoderRecordFormat = "3s4ss32s32s56s" Then, a simple: print DCOD_Print() parses the record into its fields, and displays those fields. In other files, some of those fields are VB6 currency types, which have been described as 8-byte integers with an implied 4 decimal places (which I guess would be __int64 or c_longlong and then divide by 10,000, or simply put a decimal point 4 away from the end). Any ideas on how best to process this type of data in Python? From mattheww at chiark.greenend.org.uk Wed Mar 5 18:27:21 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Mar 2008 23:27:21 +0000 (GMT) Subject: Why """, not '''? References: <13su5tn6rpjb345@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >On Wed, 05 Mar 2008 19:19:08 +0000, Matthew Woodcraft wrote: >> One advantage is that a dumb syntax highlighter is more likely to cope >> well if the content includes an apostrophe. > But if the content contains double-quote marks, the "dumb syntax > highligher" is more likely to cope well if you use '''. That's right. But apostrophes are rather more common than quote marks in English text. > And, let's be realistic here, a "dumb syntax highlighter" is more > likely to not cope well with triple-quote strings *at all*. In practice they often do the right thing, what with three being an odd number. -M- From jaywgraves at gmail.com Tue Mar 11 09:34:03 2008 From: jaywgraves at gmail.com (jay graves) Date: Tue, 11 Mar 2008 06:34:03 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> Message-ID: On Mar 11, 12:21 am, royG wrote: > On Mar 10, 8:03 pm, Tim Chase wrote: > in the version using glob() > > >path = os.path.normpath(os.path.join(folder, '*.txt')) > >lst = glob.glob(path) > > is it possible to check for more than one file extension? here i will > have to create two path variables like > path1 = os.path.normpath(os.path.join(folder, '*.txt')) > path2 = os.path.normpath(os.path.join(folder, '*.doc')) > > and then use glob separately.. > or is there another way? use a loop. (untested) def parsefolder(folder): lst = [] for pattern in ('*.txt','*.doc'): path = os.path.normpath(os.path.join(folder, pattern)) lst.extend(glob.glob(path)) lst.sort() return lst From sjmachin at lexicon.net Sat Mar 15 22:37:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Mar 2008 19:37:56 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: <83232bff-e991-422d-835e-f321dafa1ede@i12g2000prf.googlegroups.com> On Mar 16, 12:12 pm, lampshade wrote: > Hello, > > I'm having some problems with os.path.isdir I think it is something > simple that I'm overlooking. > > #!/usr/bin/python > import os > > my_path = os.path.expanduser("~/pictures/") > print my_path > results = os.listdir(my_path) > for a_result in results: > if os.path.isdir(str(my_path) + str(a_result)): Not parts of the problem, but: (1) you don't need to use str() here. (2) use os.path.join instead of the + operator, if you are interested in portable code. > results.remove(a_result) > > for x in results: print x > > The problem is, that the directories are never removed. Can anyone > point out what I'm missing that is causing the bug? Is there a better > way of doing this? > > Thanks, You are removing directory *NAMES* from the container named "results". If you want to remove the directories from your filesystem, use os.rmdir. From kyosohma at gmail.com Sun Mar 16 08:47:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 16 Mar 2008 05:47:10 -0700 (PDT) Subject: Python for BlackBerry References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> Message-ID: <79aa668a-f1b6-4f59-9ff9-8dc9dfc177aa@a23g2000hsc.googlegroups.com> On Mar 15, 9:52 pm, "Sandipan Gangopadhyay" wrote: > Thanks, Mike. > This one seems to be for Nokia, particularly S60 and Symbian in general. > Does BlackBerry work on Symbian? Let me check. > Thanks. > Sandipan > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of Mike > Driscoll > Sent: Saturday, March 15, 2008 6:04 PM > To: python-l... at python.org > Subject: Re: Python for BlackBerry > > On Mar 15, 7:24 am, "Sandipan Gangopadhyay" > wrote: > > Is there a Python for BlackBerry? Thanks. > > > -----Original Message----- > > From: python-list-bounces+news=sandipan.... at python.org > > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of > E-Lo > > Sent: Saturday, March 15, 2008 6:03 AM > > To: python-l... at python.org > > Subject: Python for Palm OS > > > Is there any other edition of Python for Palm OS instead of Pippy? > > --http://mail.python.org/mailman/listinfo/python-list > > You might look at Mobile Python. I'm not sure if it works on > Blackberry though:http://www.mobilepythonbook.org/ > > Mike > --http://mail.python.org/mailman/listinfo/python-list I was afraid of that. I'm at PyCon and between their flakey wireless and my own laptop's flakey wireless card, it''s been a pain to do any research. Good luck. Mike From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 00:48:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 04:48:29 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: <13uecktbcbt9r1e@corp.supernews.com> On Sun, 23 Mar 2008 22:36:35 -0400, Roy Smith wrote: >> > I've also done two things. First, I've created a function object >> > (i.e. a lambda body), and I've also bound the name torture to that >> > function object, in much the same way I did with the list. But, it's >> > different. The function object KNOWS that it's name is torture. >> >> No it does not. Function objects don't know their name. All they know >> is that they have a label attached to them that is useful to use as a >> name in some contexts, e.g. when printing tracebacks. It's just a >> label, nothing more. > > I think we're arguing the same thing. When you write > > def foo(): > whatever > > you create an object which contains the string "foo", retrievable > through its __name__ attribute. That's what I meant by "it knows its > name" But that's not true. Firstly, you can't access the __name__ attribute unless you already have a reference to the object (not necessarily a name), so clearly the __name__ attribute isn't how you retrieve objects. Secondly, the __name__ attribute has no special purpose. It's not even used for tracebacks. >>> def foo(): ... return "result" ... >>> foo.__name__ = "something" >>> something() Traceback (most recent call last): File "", line 1, in NameError: name 'something' is not defined >>> >>> something = foo >>> something() 'result' >>> something(None) Traceback (most recent call last): File "", line 1, in TypeError: foo() takes no arguments (1 given) >>> something.__name__ 'something' -- Steven From pavloutefkros at gmail.com Mon Mar 31 12:11:49 2008 From: pavloutefkros at gmail.com (Gif) Date: Mon, 31 Mar 2008 09:11:49 -0700 (PDT) Subject: wxPython listctrl References: <4dc652a5-d6f9-4cb8-af30-ec1c9e4ea505@y21g2000hsf.googlegroups.com> <8fcac15f-ad92-47b2-84bb-1d8e474ea016@i7g2000prf.googlegroups.com> Message-ID: <37308f0e-8edd-410f-83d1-62012f08cdef@s8g2000prg.googlegroups.com> thanks Mike, i'll post there. From hniksic at xemacs.org Wed Mar 19 18:41:12 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 19 Mar 2008 23:41:12 +0100 Subject: removing all instances of a certain value from a list References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Message-ID: <87lk4e2v7b.fsf@mulj.homelinux.net> Lee Sander writes: > Hi, > I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are > many missing vlaues which are represented as None. I would like to > remove all such instances in one go. > There is a remove function but it removes only the first instance, is > there a delete/remove all function? No, but you can easily simulate it using, for example: lst[:] = (el for el in lst if el is not None) From pavlovevidence at gmail.com Thu Mar 6 09:30:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 06:30:41 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> On Mar 5, 8:44 pm, Steven D'Aprano wrote: > But what about classes? Are they singletons? Obviously classes aren't > Singleton classes, that is, given an arbitrary class C you can create > multiple instances of C. But what about class objects themselves? I've > found a few odd references to "classes are singletons", but nothing in > the language reference. Probably because "singleton" is the wrong word. A singleton means there is one instance of a type; classes are instances of "type" which can have many instances so classes are not singletons. Anyway, the answer to what you are probably asking is No. Try this: >>>import module >>>c1 = module.Someclass >>>reload(module) >>>c2 = module.Someclass >>>c1 is c2 For that matter, try this: >>>import module >>>c1 = module.Someclass >>>module.Someclass = some_other_class() >>>c2 = module.Someclass >>>c1 is c2 Carl Banks From tjreedy at udel.edu Fri Mar 21 02:29:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 Mar 2008 02:29:03 -0400 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0] References: Message-ID: "Simon Forman" wrote in message news:b39eb6cc-5c35-41d7-87be-6821f8f1ded3 at a1g2000hsb.googlegroups.com... | I've been thinking of volunteering to "port" Tkinter to Python 3.0, I | hadn't noticed that there was any discussion of removing it. It would | be a shame IMHO. Sure it has warts, but it /works/ and good for quick | and dirty GUIs as well as elaborate (even totally visually customized) | fancy applications. If you are serious, please communicate that willingness to the lib-sig. A lack of such a volunteer would be a factor in dropping it. The current developers are pretty well booked up with other stuff. From rridge at caffeine.csclub.uwaterloo.ca Mon Mar 10 14:52:00 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 10 Mar 2008 14:52:00 -0400 Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: DanielJohnson wrote: >I am trying to solve a genetic algorithm problem where I want to read >a bitvector of very large size (say 10000) and manipulate bits based >on certain algorithms. > >I am a newbie in Python. What data structure are good to read such >huge data set. Are there any built in classes for bit fiddling. A 10000 bit data set is by no means huge. Depending on exactly what operations you want to perform converting your "bitvector" to a byte array, one bit per byte may be fast way to go. This increases the size of data set by 8 times, but it's probably the fastest way in Python to test and set individual bits. Here's a couple of functions I wrote for very quickly converting a "bitvector" in the form of a string (eg. read from a file) in to a byte array: import string import array import binascii _tr_16 = string.maketrans("0123456789abcdef", "\x00\x01\x02\x03" "\x10\x11\x12\x13" "\x20\x21\x22\x23" "\x30\x31\x32\x33") _tr_4 = string.maketrans("0123", "\x00\x01" "\x10\x11") _tr_2 = string.maketrans("01", "\x00\x01") def string_to_bit_array(s): """Convert a string to an array containing a sequence of bits.""" s = binascii.hexlify(s).translate(_tr_16) s = binascii.hexlify(s).translate(_tr_4) s = binascii.hexlify(s).translate(_tr_2) a = array.array('B', s) return a _tr_rev_2 = string.maketrans("\x00\x01", "01") _tr_rev_4 = string.maketrans("\x00\x01" "\x10\x11", "0123") _tr_rev_16 = string.maketrans("\x00\x01\x02\x03" "\x10\x11\x12\x13" "\x20\x21\x22\x23" "\x30\x31\x32\x33", "0123456789abcdef") def bit_array_to_string(a): """Convert an array containing a sequence of bits to a string.""" remainder = len(a) % 8 if remainder != 0: a.fromlist([0] * (8 - remainder)) s = a.tostring() s = binascii.unhexlify(s.translate(_tr_rev_2)) s = binascii.unhexlify(s.translate(_tr_rev_4)) return binascii.unhexlify(s.translate(_tr_rev_16)) I've used these functions to implement a data compression algorithim in Python. The algorithm still runs very slow in Python, but it runs much faster than it would have if I had used Python's bitwise operators. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From gowricp at gmail.com Sun Mar 23 20:10:40 2008 From: gowricp at gmail.com (Gowri) Date: Sun, 23 Mar 2008 17:10:40 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> <29cd9085-b70f-4873-899e-3837d8e42d90@u69g2000hse.googlegroups.com> Message-ID: <89e74a42-09b5-4612-be54-6ece1d2de696@e39g2000hsf.googlegroups.com> Hi Tim, I'm able to get and print correctly some HTML content. I don't know how to fix this. Need all the help I can get with this :) Regards, Gowri From planders at gmail.com Thu Mar 20 16:55:33 2008 From: planders at gmail.com (Preston Landers) Date: Thu, 20 Mar 2008 13:55:33 -0700 (PDT) Subject: Strange behavior of the Eclipse embedded console References: <23ab07a7-0355-48a7-8bf2-266a56f4efb9@h11g2000prf.googlegroups.com> Message-ID: On Mar 20, 9:09?am, hellt wrote: > "The eclipse console is not an exact copy of a shell... one of the > changes is that when you press in a shell, it may give you a > \r, \n or \r\n as an end-line char, depending on your platform. Python > does not expect this -- from the docs it says that it will remove the > last \n (checked in version 2.4), but, in some platforms that will > leave a \r there. This means that the raw_input() should usually be > used as raw_input().replace('\r', ''), and input() should be changed > for: eval(raw_input().replace('\r', ''))." While I do love Eclipse as a Python code editor, interactive debugger, front-end to SVN / Trac, and for many other things... it is unfortunately terrible as an interactive console. But then again, despite being a long time Emacs user I never did anything complex inside Emacs' shell / terminal emulator, instead preferring a 'real' console using xterm or rxvt or konsole or what have you. By the way, so far the only text editing feature from Emacs I am missing in Eclipse is the ability to reformat line endings - i.e., M-x fill-paragraph-or-region regards Preston From goldspin at gmail.com Thu Mar 6 19:43:58 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 6 Mar 2008 16:43:58 -0800 Subject: How to Encode String of Raw UTF-8 into Unicode? Message-ID: Hi everyone, Suppose I start out with a raw string of utf-8 code points. raw_string = "68656E727963" I can coerce it into proper unicode format by slicing out two characters at a time. unicode_string = u"\x68\x65\x6E\x72\x79\x63" >>> print unicode_proper >>> henry My question: is there an existing function that can do this (without having to manually slicing the raw text string)? Thanks. From dickinsm at gmail.com Wed Mar 12 11:25:41 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 12 Mar 2008 08:25:41 -0700 (PDT) Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: On Mar 12, 10:18?am, Gerdus van Zyl wrote: > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: You could wait for Python 2.6, or download the current alpha: Python 2.6a1+ (trunk:61353M, Mar 12 2008, 11:21:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from itertools import product >>> for c in product(['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']): print c ... ('3', '9', '5', '4', '2') ('3', '9', '5', '4', '5') ('3', '9', '5', '4', '8') ('3', '1', '5', '4', '2') ('3', '1', '5', '4', '5') ('3', '1', '5', '4', '8') If you can't wait, look at http://docs.python.org/dev/library/itertools.html where equivalent code is given. Mark From michael.wieher at gmail.com Fri Mar 14 10:15:58 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 14 Mar 2008 09:15:58 -0500 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: 2008/3/14, Pradeep Rai : > > Dear All, > > I am working on the python tools that process a huge amount of GIS data. > These tools encountering the problem of memory leaks. > > Please suggest what are the different ways to detect the memory leaks in > python ? > > This is very critical problem for me. Help needed urgently. > > Thanks & Regards, > > Pradeep > Python doesn't have memory leaks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Sun Mar 2 15:32:57 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 12:32:57 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <7xskz9wpw6.fsf@ruckus.brouhaha.com> References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I can live with int/int=float but > find it sloppy and would be happier if int/int always threw an error > (convert explicitly if you want a particular type result). Better yet, how hard would it be to define an otherwise int-like type that did not define a non-flooring division operator? Are there any real use cases for such a type? Maybe a division operator could be defined to perform a run-time check that, for an operation n/d==q, n==q*d; else, throw an exception. Code written to support duck-typed integers should work with such a UDT "out of the box." From sjdevnull at yahoo.com Tue Mar 4 11:18:39 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Tue, 4 Mar 2008 08:18:39 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> <55f1c2b7-0f8f-4bcc-ac59-0b78a81cf81e@e31g2000hse.googlegroups.com> Message-ID: On Mar 4, 10:44 am, Ron DuPlain wrote: > On Mar 4, 10:13 am, Siddhant wrote: > > > Hi people. > > I was just wondering if a tab-completion feature in python command > > line interface would be helpful? > > If yes, then how can I implement it? > > Thanks, > > Siddhant > > ipython provides auto tab completion.http://ipython.scipy.org/ > > You can also get it by: > $ easy_install ipython > > Run it using the command: > $ ipython > > Is this what you want? ipython also makes stack traces nearly unreadable by default (setting "xmode Plain" in the ipythonrc fixed that) and tends to take up too much vertical screen space, wants to colorize a lot of stuff, and has a few other things that I was't fond of. There's some nice stuff in ipython (saving the return values of every line in the shell), but I found trying to configure off all of the "magically helpful" stuff that wound up being more annoying than useful was a fairly long job. I found it easier just to turn on completion in the regular python shell. From my .pythonrc: try: import readline except ImportError: print "Module readline not available." else: import rlcompleter readline.parse_and_bind("tab: complete") del readline, rlcompleter With that and persistent history I'm pretty happy: import readline histfile = os.path.join(os.environ["HOME"], ".pyhist") try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del os, histfile From castironpi at gmail.com Sun Mar 16 02:35:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 23:35:49 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: On Mar 15, 9:28?pm, Benjamin wrote: > On Mar 15, 7:29 pm, castiro... at gmail.com wrote:> 'join' in the wrong word for the method in class Thread. > > > The agent-patient semantics of calling functions can get ambiguous. > > It is not a problem of native Pythoners alone. ?Is it due to lazy > > programming, an inability of English (do you have it in other > > languages?), or not a problem at all? > > This is what Java uses, and Python's threading module tries to imitate > it. If everybody's using join, then everybody's using join. That by itself doesn't constitute a case that the practice, the trend, is either right or wrong. Which is why I bring it up! Upon some second thoughts, the OP (myself) could use a few more examples... maybe even some parameters. Maybe even a spell checker (subject line). > th1.join() -> 'be joined by th1' > file1.close()-> 'close file1' > lock1.wait()-> 'getinlinefor lock1' One approach is to take a 'declarative' perspective: make them statements instead of commands. th1.join() -> th1.joins() file1.close() -> file1.closes() lock1.wait() -> lock1.becomesfree() htmlparser.reset() -> htmlparser.resets() htmlparser.feed( data ) -> htmlparser.eats( data ) pickle.dump( obj ) -> pickle.dumps( obj ) pickle.dumps( obj ) -> pickle.sdumps( obj ) socket.accept() -> socket.accepts() I tried once but got frustrated because the libraries wouldn't fit in. lock1.becomesfree() is a fine example. It's saying what happens in that statement, which is a lot closer to what's actually going on-- because lock is doing exactly nothing until something else in some other story line. thread1.joins() similarly. I do contend that names are hard to pick-- "one-worders" take perspective and distance, which are pricey pricey-- and unfortunately deadlines press and the existing ones come already to be used. Of course, Python version graduation is a fine time to make the change, but I'm no good at asking politely-- the right people at the right times and in the right ways. A tool might be able to convert the obvious cases automatically, and prompt the operator about any residue. He wouldn't necessarily even have to change overridden methods by hand either! Multi-control systems may have cause the rift. Without them, 'do it' is the same as 'it does it'. With them, 'he does it' and 'you do it' are different. However the popularity of object-orientation may be the culprit: not all of our instruction names made the jump right. Maybe both. Aside: The docs are heavily (-heavily-) in the patient (passive) voice too: code.interact: "is passed", "is then run", "is discarded", as well as alternate between declaration and command. But -you- rewrite them, Mr. Backseat Driver! A lot of abbreviations 'recv', 'del', 'dir', and 'stat' can go. I digress. The language would be changing pretty deeply: returns, yields, passes, dels, raises, breaks, continues, imports. The 'returns' would even move over: retval returns; object() returns; match returns (return retval, return object(), return match). Maybe there's a language out there that understands! The inconsistency is in the address of threads and synchro. objects: The author changes audiences. In th1.join(), he is not commanding his audience to join th1. Biggest problem. It's like an implicit 'the self thread' shows up from dreamworld or something. th1.join( this_thread ) lock1.waitfor( a_goahead ) lock1.waitfor( someone_else_to_finish_up ) I'm not holding that the functions aren't defined. I'm saying the names are hastily chosen. The join documentation doesn't use the word 'join'. Event.wait doesn't use wait, but Condition, os, and subprocess do. "Event.wait( [timeout]) Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). " Aside: The rage-against-the-machine/paranoia/conspiracy-theory side of me tries to ascribe malice to the writers, saying "they" were "holding" "me" "down" (referring to my nose, of course). I know better, but college was rough and the girlfriend pulled, so I don't always catch it. Cough. My earlier use of 'lazy' may have been a bit pejorative. It insinuated the authors devoted time to Doritos over better names, rather than just other names or even bugs. I was in a different setting then -and- on autopilot. It proves my point, though. Time is scarce. Help me ask the right way! From iainking at gmail.com Mon Mar 17 07:16:46 2008 From: iainking at gmail.com (Iain King) Date: Mon, 17 Mar 2008 04:16:46 -0700 (PDT) Subject: String To List References: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> <42858a90-80eb-45ac-8f76-ad9d06ee4fbf@d21g2000prf.googlegroups.com> Message-ID: <4ea462e2-cecc-40fc-a62b-658c0fcc28a6@c19g2000prf.googlegroups.com> On Mar 17, 9:27 am, Iain King wrote: > On Mar 17, 6:56 am, Dan Bishop wrote: > > > On Mar 17, 1:15 am, Girish wrote: > > > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > > this?? > > > Thanks for the help... > > > eval(a) will do the job, but you have to be very careful about using > > that function. An alternative is > > > [s.strip('\'"') for s in a.strip('[]').split(', ')] > > This will fall over if xyz or abc include any of the characters your > stripping/splitting on (e.g if xyz is actually "To be or not to be, > that is the question"). Unless you can guarantee they won't, you'll > need to write (or rather use) a parser that understands the syntax. > > Iain Thinking about this some more; could the string module not use a simple tokenizer method? I know that relentlessly adding features to built-ins is a bad idea, so I'm not sure if this falls within batteries-included, or is actually just adding bulk. On the one hand, it's not difficult to write a simple state-based token parser yourself, but on the other it is also quite easy to include a pile of bugs when you do. By simple I mean something like: def tokenize(string, delim, closing_delim=None, escape_char=None) which would return a list (or a generator) of all the parts of the string enclosed by delim (or which begin with delim and end with closing_delim if closing_delim is set), ignoring any delimiters which have been escaped by escape_char. Throw an exception if the string is malformed? (odd number of delimiters, or opening/closing delims don't match) In the OP's case, he could get what he want's with a simple: l = a.tokenize("'") The point of this ramble not being that this is a how to solve the OP's question, but wondering if it would be a good inclusion to the language in general. Or there's actually a module which already does it that I couldn't find and I'm an idiot... Iain From http Sat Mar 29 10:38:34 2008 From: http (Paul Rubin) Date: 29 Mar 2008 07:38:34 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> <65701aF2erbbsU1@mid.uni-berlin.de> Message-ID: <7xr6dta93p.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > In which sense is that different? AFAIK select lets you avoid polling > and provides notifications (possibly with timeouts) for IO-events. So > where exactly is the difference? I read TFA, and it does mention that > select/poll have potential for optimization, but not something that > disqualified them (or rather select) as being not async. Select blocks until the data is ready, while with AIO the i/o happens completely in the background and your process gets an interrupt when the i/o completes. Also, with select based i/o, usually the kernel reads data from the external device into a system buffer, and then you do a read system call that copies the data from the system buffer to your buffer. AIO can be set up so the i/o happens directly into your buffer, avoiding the extra copying. You can also initiate a bunch of different i/o events with a single system call, avoiding some context switches. http://www.ibm.com/developerworks/linux/library/l-async/ describes select as "asynchronous, blocking" as opposed to AIO which is asynchronous and nonblocking. Other descriptions I've seen reserve "asynchronous i/o" for AIO-like schemes. It's just a terminological thing. The PDP-10 operating systems even let you define your own page fault handlers, so you could do i/o with something like mmap and not get delayed in the cases where the page you wanted wasn't in memory. I guess that's even more asynchronous than AIO. From Lie.1296 at gmail.com Sun Mar 16 05:12:39 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 02:12:39 -0700 (PDT) Subject: find string in file References: Message-ID: On Mar 14, 8:25?pm, fminerv... at gmail.com wrote: > Hi friends !! > > I'm neophite about python, my target is to create a programa that > find ?a specific string in text file. > How can do it? > > Thanks > fel I'd recommend regular expression (import re) if the string you're searching is in a complex format (like all strings that starts with a dollar sign followed by an arbitrary number of numbers which might or might not contain commas every three number). If what you're searching is just simple queries (like searching where "Hello" appeared in the text you'd better use the string modules. as they're simpler to use and faster. From http Fri Mar 14 13:18:32 2008 From: http (Paul Rubin) Date: 14 Mar 2008 10:18:32 -0700 Subject: Thousand Seperator References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <7xiqzpjkbb.fsf@ruckus.brouhaha.com> ewanfisher at gmail.com writes: > 100 -> 100 > 1000 -> 1,000 > 1000000 -> 1,000,000 > -1000 -> -1,000 def sep(n): if n<0: return '-' + sep(-n) if n<1000: return str(n) return '%s,%03d' % (sep(n//1000), n%1000) From saluk64007 at gmail.com Wed Mar 12 23:50:26 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 12 Mar 2008 20:50:26 -0700 Subject: a Roguelike in Python In-Reply-To: <776b49ce-852d-43da-ac56-6fc3cdcaca92@u72g2000hsf.googlegroups.com> References: <776b49ce-852d-43da-ac56-6fc3cdcaca92@u72g2000hsf.googlegroups.com> Message-ID: On Wed, Mar 12, 2008 at 9:23 AM, Carl Banks wrote: > Even though it's typically used for graphical games, PyGame would be a > good way to make a cross-platform "text-mode" game. It should be > pretty straightforward to simulate a text mode terminal using a grid > of sprites. (There might even be some third-party text terminals out > there.) This is a cool technique, and also gives the game designer a lot of freedom in their representation. It can continue to look old school while also letting you have icons where they may be appropriate, or add an eye on your gridbug 'x' just for fun :) This technique was used in phoenix from one of the pyweek competitions: http://www.pyweek.org/e/Cursed/ By the way, that game emulates curses as well. If you go with pygame display only, you are losing some compatibility as well, as it won't run on textmode only systems. No roguelikes over ssh :( From rolf.oltmans at gmail.com Wed Mar 12 12:17:45 2008 From: rolf.oltmans at gmail.com (Oltmans) Date: Wed, 12 Mar 2008 09:17:45 -0700 (PDT) Subject: Unable to handle File Open dialog (using Pamie) Message-ID: <54766eca-9f83-4a4a-962f-d78d88aec7fa@e6g2000prf.googlegroups.com> Hi all, I'm new to Python and am automating few tasks using Pamie. Everything worked well until I had to handle the File Open Dialog. I mean I'm trying to automate the file upload process using Pamie. Basically I just want to automate the process of file upload. I want to automatically hit the Browse button and then enter 'C:\image1.jpg' in the File Name text field and then hit the Open button (all using Pamie, winguiauto or whatever would give me the solution :-) Here is my html ( file is stored in my PC at C:\\Test\Test.html ) and here is my source ie.navigate("C:\Test\Test.html") ie.buttonClick('upload') handle = winGuiAuto.findTopWindow(wantedText="Choose file") print 'handle ='+ str(handle) p=handlePopup('ChooseFile','&Open') p.enterTextAndClickControl(handle,('C:\image1.jpg','&Open')) p.run() now when I run the above program the Browse button gets clicked and File Open dialog pops up but 'c:\image1.jpg' (without quotes) is not entered in the File Name field and neither the Open button gets clicked. Also I get this error in the console -- Traceback (most recent call last): File "firsttest.py", line 26, in p.enterTextAndClickControl(handle,('C:\image1.jpg','&Open')) File "C:\Python25\lib\site-packages\cModalPopUp.py", line 113, in enterTextAn ClickControl wantedClass="Edit") File "C:\Python25\lib\site-packages\winGuiAuto.py", line 167, in findControl selectionFunction=selectionFunction) File "C:\Python25\lib\site-packages\winGuiAuto.py", line 235, in findControls return searchChildWindows(topHwnd) File "C:\Python25\lib\site-packages\winGuiAuto.py", line 213, in searchChildW ndows childWindows) TypeError: an integer is required -- I've searched Internet, searched usenet, scratched my head but nothing worked. Also, I tried joining the Pamie User group but I couldn't. So I will really appreciate your help/insights/ideas/hints/anythiing that can help me fix the problem. Thanks, Rolf From tn.pablo at gmail.com Tue Mar 25 12:27:58 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 25 Mar 2008 09:27:58 -0700 (PDT) Subject: Files, directories and imports - relative to the current directory only Message-ID: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> Hello, group. I can only read files and import modules that are in the same directory as the one my script is. Here is a test script (path.py): import os import uno # some module I wrote print list(os.walk('~/hacking/python')) f = open('~/read/foo.txt') print f.read() And here is the output: Traceback (most recent call last): File "path.py", line 2, in import uno ImportError: No module named uno If I comment that import, the output becomes this: [] Traceback (most recent call last): File "path.py", line 4, in f = open('~/read/foo.txt') IOError: [Errno 2] No such file or directory: '~/read/foo.txt' (Notice the empty list at the beginning, that would be the output of os.walk().) I have added this line to my .bashrc: export PYTHONPATH=$PYTHONPATH:~/hacking/python I thought that by doing so all the scripts found in that directory and all it's children would be available for import, but that doesn't seem to be the case. As for the other problems, I have no idea. So, what's wrong here? Maybe there's something I haven't set up? From mail at microcorp.co.za Sat Mar 29 06:43:22 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Mar 2008 12:43:22 +0200 Subject: Re; finding euclidean distance,better code? Message-ID: <001c01c8918e$48556a40$03000080@hendrik> On Saturday 29 March 2008 03:09:46 Steven D'Aprano wrote: > On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > > Gabriel Genellina wrote: > >> That's what I said in another paragraph. "sum of coordinates" is using > >> a different distance definition; it's the way you measure distance in a > >> city with square blocks. I don't know if the distance itself has a > >> name, but > > > > I think it is called Manhattan distance in reference of the walking > > distance from one point to another in this city. > > You know, there are other cities than Manhattan. Some of them even have > streets and blocks. Sorry about having to dispel your illusions, but - In Printed Circuit Board Layout jargon, the 'manhattan distance' is the sum of the distances along the orthogonal axes between two points on the board that should be connected. The sum of all such distances is an idealised minimum for the total track length on a double sided board, given that it were possible to lay all tracks with segments connected by vias, making strictly increasing progress in the desired direction, by laying x direction tracks on the one, and y direction tracks on the other side of the board without having to "backtrack" - i.e. having to "dodge around" obstacles, thereby adding "overshooting" segments of track. (A via is a through plated hole that connects copper traces or tracks on opposite sides of the board) So I have met the beast, but I have no concept of its origin, other than the mind numbing regularity of the layout of the suburb of the city after which it seems to be named - For all I know 'manhatten' could be a native american word that means "net". Have you noticed that when people say "Sorry.....but...." they are not normally sorry at all? :-) - Hendrik From frikker at gmail.com Tue Mar 4 18:31:09 2008 From: frikker at gmail.com (blaine) Date: Tue, 4 Mar 2008 15:31:09 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> <13sr22ii98uipc4@corp.supernews.com> Message-ID: > It looks like the fastest speed supported by python termios on > Linux is B460800 (uses a constant of 0x1004). If you look in > /usr/include/..., baud rates do go up to 921600 (which uses a > constant of 0x1007). > > Try using the appropriate constant from /usr/include/... (for > the target platform, of course). > > -- > Grant Edwards grante Yow! Please come home with > at me ... I have Tylenol!! > visi.com I want to thank you SO MUCH for all your help. Here are my issues that I overcame (sanity check): 1. Why did we have to use 0x1007, instead of 0x10007 that our grep command returns? 2. PySerial works beautifully. Thank you for the suggestion. What I had to do was add this to the PySerial source root in serialpostix.py, after the import termios: termios.B921600 = 0x1007 because PySerial looks for the actual baud rate in termios (via getattr()) which does not exist. PySerial actually defines the following baud rates, but termios does not handle it: #default values, may be overriden in subclasses that do not support all values BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600, 19200,38400,57600,115200,230400,460800,500000,576000,921600, 1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000) ... so now I can pass 921600 as a parameter to PySerial! :) So my next question is - I would like to contribute to the python source tree by updating termios.h to handle the higher baud rates by default. Is this a good opportunity for me to submit a patch? I've never done this before but have always been interested in doing so. Thanks again! Blaine From paul at boddie.org.uk Mon Mar 31 11:14:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 31 Mar 2008 08:14:23 -0700 (PDT) Subject: Licensing References: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> Message-ID: On 31 Mar, 09:36, Duncan Booth wrote: > > I don't have a printed copy, but Google Books has it (not sure which > edition I found) and page xix says: > > Given the nature of the cookbook, we wanted the recipes to be usable under > any circumstances where Python could be used. In other words, we wanted to > ensure completely unfettered use, in the same spirit as the Python license. > Unfortunately, the Python license cannot really be used to refer to > anything other than Python itself. As a compromise, we chose to use the > modified Berkeley license, which is considered the most liberal of > licenses. ... and then the license follows ... > > So, if the recipe is in the printed cookbook the licensing is clear > (primarily you must retain the copyright notice). The best advice I've found so far is the following: http://www.softwarefreedom.org/resources/2007/gpl-non-gpl-collaboration.html It spells out exactly what you have to do to satisfy the original licence and to uphold your own licence choice. It's also written by well-regarded legal people. Paul P.S. An older and more ambiguous conclusion on the topic can be found here: http://groups.google.com/group/linux.kernel/msg/4c8b3114c35df368 From timr at probo.com Wed Mar 5 02:49:13 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 05 Mar 2008 07:49:13 GMT Subject: Delete hidden files on unix References: Message-ID: loial wrote: > >How can I delete hidden files on unix with python, i.e I want to do >equivalent of > >rm .lock* What did you try? I'm curious to know what you tried that didn't work, because I can't think of any obvious solution to this that would not just work. You did try to solve this yourself before sending a message around the world, didn't you? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Thu Mar 6 07:35:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 10:35:38 -0200 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 10:10:47 -0200, Guillermo escribi?: > This is my first post here. I'm getting my feet wet with Python and I > need to know how can I check whether a variable is of type dictionary. > > Something like this: > > if isdict(a) then print "a is a dictionary" if isinstance(a, dict): ... But note that it's more common in Python to try to use it in the intended way, and catch the possible errors. Look for "duck typing" in this group, and the difference between "easier to ask forgiveness than permission" and "look before you leap". -- Gabriel Genellina From hajducko at gmail.com Fri Mar 28 05:39:25 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Fri, 28 Mar 2008 02:39:25 -0700 (PDT) Subject: Plugins accessing parent state References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> <653q99F2e37q8U1@mid.uni-berlin.de> Message-ID: On Mar 28, 1:58?am, "Diez B. Roggisch" wrote: > hajdu... at gmail.com schrieb: > > > > > Does anyone have some design ideas ( or can point me at the right > > design pattern, because I can't find it. ) for having a plugin being > > able to access a parent's state? > > > For example, let's say I have a class that receives some commands. > > When it gets a command, it checks which of the registered plugins > > deals with that command and passes the details of the command off to > > that plugin. ?So I'd end up with something like.. > > > result = plugin.do(msg_details) > > > Now, I want to write a plugin called "help" that loops through all the > > registered plugins and prints out their doc strings. ?If all my plugin > > is getting is the msg details, how is it supposed to get the list of > > available plugins from the calling class? > > > Or, for instance, let's say my class loads a configuration file that > > lists a set of admins who can enter commands. ?I want the plugins, if > > they so choose, ?to be able to test if the msg came from an admin, but > > again, I'm not passing the admin list into every plugin, it's just in > > my calling class. ?I could make the plugin specify an attribute for > > itself, like "admin_only" and test for that before I pass the command > > but what if certain parts of the plugin are to be restricted and > > others aren't, based on the details of the command sent? > > > Is this as simple as just passing the instance of my class to each > > plugin? ?It doesn't seem like the proper thing to do, because now the > > plugin class has the capability of accessing the whole bot's > > interface. > > Yes, it is simple as that. Of course you can choose *what* you pass, if > you want to restrict that - nobody forces you to pass the whole > plugin-manager, if that would expose properties/methods you wouldn't > want ther. > > But to be honest: you are thinking much to far there - after all, it's > all *your* code, and inside one interpreter. A real isolation isn't > available anyway. > > So just do what fullfills the functional requirements. > > diez Since I want to have a uniform call to all plugins, would it make sense to split out the attributes that I do want to share to a separate class and then simply create a new instance of that class and store it in the main class? For instance ... self.utilities = Utilities(self) ... plugin.do(msg,self.utilities) From solisgb at gmail.com Sun Mar 9 11:37:07 2008 From: solisgb at gmail.com (luis) Date: Sun, 9 Mar 2008 08:37:07 -0700 (PDT) Subject: unable to install gdal Message-ID: <15838144-b7a0-4d1b-98b3-fdfcfdb9a916@n75g2000hsh.googlegroups.com> Hi On Windows xp sp2 and python 2.4 Yesterday I running old versions of gdal, and I try to upgrade I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 I follow install's instructions from http://trac.osgeo.org/gdal/wiki/GdalOgrInPython, all is ok, I set path and path_data variables with correct values, but whe I run a script, an error raises from osgeo import ogr File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? import _ogr ImportError: DLL load failed: process not found Also I try with instructions from http://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gdalinstall.html I move _gdal.pyd (and the others *.pyd) from my Python installation's (C:\Python24\Lib\site-packages\osgeo) into my Python installation's DLLs folder (C:\Python24\DLLs). When I run the script the error message persists. Some help is welcome. From stef.mientki at gmail.com Tue Mar 11 21:07:41 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 12 Mar 2008 02:07:41 +0100 Subject: how to pass the workspace ? Message-ID: <47D72CDD.9000706@gmail.com> hello, I've GUI tree with drag and drop nodes, where each nodes contains a code snippet. Now I want to run one or more branches in that tree, so I enumerate over the nodes and have to run something like this: execfile ( node1 ) execfile ( node2 ) etc.. Now how do I pass the workspace created in node1, to node 2, etc ? thanks, Stef Mientki From duncan.booth at invalid.invalid Wed Mar 19 10:10:12 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 14:10:12 GMT Subject: Speaking Text References: Message-ID: David C. Ullrich wrote: > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? > (If it's there in Linux presumably it only works if there > happens to be a speech engine available...) Perhaps http://www.mindtrove.info/articles/pytts.html ? Or if all else fails Python can drive Microsoft's MSAGENT for speaking animated figures. From pmc411-usenet at yahoo.com Thu Mar 20 11:51:45 2008 From: pmc411-usenet at yahoo.com (Paulo da Costa) Date: Thu, 20 Mar 2008 15:51:45 GMT Subject: Can I run a python program from within emacs? In-Reply-To: <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: Jeff Schwab wrote: > jmDesktop wrote: >> On Mar 20, 11:21 am, Grant Edwards wrote: >>> On 2008-03-20, jmDesktop wrote: >>> >>>> Hi, I'm trying to learn Python. I using Aquamac an emac >>>> implementation with mac os x. I have a program. If I go to the >>>> command prompt and type pythong myprog.py, it works. Can the program >>>> be run from within the editor or is that not how development is done? >>>> I ask because I was using Visual Studio with C# and, if you're >>>> familiar, you just hit run and it works. On Python do I use the >>>> editor for editing only and then run the program from the command >>>> line? > > Sort of. Modern editors generally have support for building and running > your program directly from a toolbar button or textual command. I > personally use Vim with the toolbar disabled, running in a Terminal, and > run the program by first putting Vim in the background (^z). Modern editors like GNU Emacs show you a Python tab when you're editing a Python file that allows you to do various things with the code, just like Visual Studio, I don't know about "Aquamacs". > I believe Grant was suggesting that Emacs often serves a similar purpose > on Unix to what Visual Studio does on Windows, which seemed to be what > you were asking. When asking about Mac OS X here, you are likely to get > a lot of generic Unix responses. (Would it have been clearer if he had > just said "emacs?") There are several flavors, it's best to specify which one you mean. People who say Emacs often mean GNU Emacs. Paulo From ntv1534 at gmail.com Mon Mar 3 12:37:21 2008 From: ntv1534 at gmail.com (MooMaster) Date: Mon, 3 Mar 2008 09:37:21 -0800 (PST) Subject: Inheritance issue... Message-ID: I'm trying to use inheritance to create a simple binary tree, but it's not going so well... here's what I pull from the documentation for super() "super( type[, object-or-type]) Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes. A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg) " So here's what I do: class Node: def __init__(self, val=0, prnt = None): self.value = val self.parent = prnt class Tree(Node): def __init__(self, val=0): self.root = super(Tree, self).__init__(val) self.leftChild = None self.rightChild = None def addChild(self, value): if self.root == None: self.__init__(value) else: n = self.root while(n is not None): if(n.leftChild == None and n.rightChild == None): n.leftChild = Node(value, n) elif(n.rightChild == None): n.rightChild = Node(value, n) else: if(n.leftChild.leftChild is not None and n.leftChild.rightChild is not None): n = n.rightChild else: n = n.leftChild def printTree(self): if self.root == None: print "None" else: n = self.root print n.value while(n is not None): if(n.leftChild is None): print str(n.value) + "'s left child is None" elif(n.rightChild is None): print str(n.value) + "'s right child is None" else: if(n.leftChild.leftChild is not None and n.leftChild.rightChild is not None): n = n.rightChild else: n = n.leftChild def main(): play = Tree(1) play.addChild(2) play.addChild(3) play.addChild(4) play.addChild(5) play.printTree() if __name__ == "__main__": main() ...and here's what I get: Traceback (most recent call last): File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 53, in main() File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 45, in main play = Tree(1) File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 8, in __init__ self.root = super(Tree, self).__init__(val) TypeError: super() argument 1 must be type, not classobj Looks to me like the super(Tree, self)__init__(val) follows the example in the documentation, but I may be a witch. Anyone know why this doesn't work? From zedshaw at zedshaw.com Mon Mar 31 04:37:48 2008 From: zedshaw at zedshaw.com (Zed A. Shaw) Date: Mon, 31 Mar 2008 04:37:48 -0400 Subject: [ANN] Vellum 0.4 (it builds things, mostly books) Message-ID: <20080331043748.291ffa58.zedshaw@zedshaw.com> Hi All, I'd like to just announce that I've cranked out a fun little Python project named Vellum. It is an attempt at a Python make alternative written in about 200 lines of Python: http://www.zedshaw.com/projects/vellum/ It currently actually works, and can take a YAML or Python file as the description of the build, including namespaces, recipes from other files, and two samples for running nose and distutiles (respectively). I'm using it to automate most of my Python project builds and my website right now and it's doing great. The defining difference between it and other make-alikes is that each target is just a multi-line string, with different 3-char prefixes to determine how that line should be run: - >>> means it's Python, so run the python with exec. - <-- means eval a test and stop processing that target if False. - <<< means output some text. - --> means jump to another target, with an optional {} has of different options. - Nothing means it's a shell command, run it with os.system(). As the target is processed, each line is passed in as a string % options so you can do replacement on settings you've made. So, you can do this: <<< My name is %(name)s And if options: name: "fred", then it says it's name is fred. I'm pretty sure it's turing complete. :-) All information about the project, getting at the bzr, several sample files, and even the whole source to the core of the project are on the above page. Since I'm a total Python newbie, I'd love any advice about my code I can get. Thanks much. -- Zed A. Shaw - Hate: http://savingtheinternetwithhate.com/ - Good: http://www.zedshaw.com/ - Evil: http://yearofevil.com/ From jeffober at gmail.com Tue Mar 25 07:54:48 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 25 Mar 2008 04:54:48 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> Rather than use Foo.bar(), use this syntax to call methods of the super class: super(ParentClass, self).method() From castironpi at gmail.com Wed Mar 26 21:06:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 18:06:04 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: <2f626a4d-1db2-4b10-bf5c-e4197a3db811@z38g2000hsc.googlegroups.com> Message-ID: <1d2288e4-225b-4027-a3b8-e046828aff82@m36g2000hse.googlegroups.com> On Mar 26, 5:28?pm, bearophileH... at lycos.com wrote: > Micha? Bentkowski: > > > Why does python create a reference here, not just copy the variable? > > I think to increase performance, in memory used and running time (and > to have a very uniform way of managing objects). > > Bye, > bearophile A variable is a name-value pair. It's undefined outside of one-to- ones therein. You have two names. Do they refer to the same object. There is no such thing as the "primitive contents" of -any- standard object. From timr at probo.com Fri Mar 21 00:43:10 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Mar 2008 04:43:10 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: Sean DiZazzo wrote: > >The overall idea is to be able to tell if a file has finished being >placed in a directory without any control over what is putting it >there. There is simply no way to do this on Windows that works in the general case. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jgardner at jonathangardner.net Fri Mar 14 12:17:51 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 14 Mar 2008 09:17:51 -0700 (PDT) Subject: %x unsigned? References: <87skytbbbc.fsf@mulj.homelinux.net> Message-ID: <9f2f667e-bc91-4826-81f6-32fd73d189d6@s19g2000prg.googlegroups.com> On Mar 14, 8:00?am, Hrvoje Niksic wrote: > The %x conversion specifier is documented inhttp://docs.python.org/lib/typesseq-strings.htmlas "Unsigned > hexadecimal (lowercase)." ?What does "unsigned" refer to? > > >>> '0x%x' % 10 > '0xa' Somewhat unrelated, but have you seen the # modifier? >>> '%#x' % 10 '0xa' From jjlofaro at yahoo.com.au Wed Mar 26 05:47:11 2008 From: jjlofaro at yahoo.com.au (Jeff Lofaro) Date: Wed, 26 Mar 2008 02:47:11 -0700 (PDT) Subject: Time module is not behaving. Message-ID: <604727.52623.qm@web52209.mail.re2.yahoo.com> Yep that does it. Thanks Gary. ----- Original Message ---- From: Gary Herron To: jjlofaro Cc: python-list at python.org Sent: Wednesday, 26 March, 2008 2:49:55 AM Subject: Re: Time module is not behaving. jjlofaro wrote: > Hi > > I'm just getting myself going again on Python and would appreciate any > help. > > My install of Python seems to have some difficulty loading and using > the time module in a script. Strange thing is that if I start another > instance of Python I can type in my program manually/interactively and > it works. > > The version of Python I am using is... > * > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2* > > Installed on a Ubuntu 7.10 workstation. > > Here's my little program.... > > *jeff at office:~/tmp$ more < time.py > > import time > * Right there is the problem. Your program, named time.py, is hiding the Python supplied module. So that import of time is finding and re-importing itself. Rename your script to something that won't shadow a Python library module. Gary Herron > *print time.time()* > > And this is what happens when I run it.... > > *jeff at office:~/tmp$ python time.py > > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > Error in sys.excepthook: > Traceback (most recent call last): > File "/var/lib/python-support/python2.5/apport_python_hook.py", line > 38, in apport_excepthook > from apport.fileutils import likely_packaged > File "/var/lib/python-support/python2.5/apport/__init__.py", line 1, > in > from apport.report import Report > File "/var/lib/python-support/python2.5/apport/report.py", line 14, > in > import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys > File "/usr/lib/python2.5/urllib.py", line 28, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > Original exception was: > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > jeff at office:~/tmp$ * > > Any hints or tips appreciated. > Jeff. Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/y7mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Mar 31 23:28:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 20:28:08 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> <80d1731d-a3c6-4fce-81fd-9c3f3537e59b@d21g2000prf.googlegroups.com> Message-ID: <5386cf08-c155-4fbb-8373-dbbb9829a9e7@m3g2000hsc.googlegroups.com> On Mar 31, 9:27?pm, George Sakkis wrote: > On Mar 31, 8:51 pm, castiro... at gmail.com wrote: > > On Mar 31, 7:14 pm, 7stud wrote: > > > > On Mar 31, 5:31 pm, castiro... at gmail.com wrote: > > > > > Can you have a Python object stored entirely on disk? > > > > import cPickle as cp > > > > class Dog(object): > > > ? ? def __init__(self, name): > > > ? ? ? ? self.name = name > > > > d = Dog("Spot") > > > > f = open("data.txt", "w") > > > cp.dump(d, f) > > > f.close() > > > > f = open("data.txt") > > > stored_obj = cp.load(f) > > > print stored_obj.name > > > > --output:-- > > > Spot > > >>> import pickle > > >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps > > ? ? Pickler(f, protocol).dump(obj) > > ? File "C:\Programs\Python\lib\pickle.py", line 221, in dump > > ? ? self.save(obj) > > ? File "C:\Programs\Python\lib\pickle.py", line 283, in save > > ? ? f(self, obj) # Call unbound method with explicit self > > ? File "C:\Programs\Python\lib\pickle.py", line 697, in save_global > > ? ? (obj, module, name)) > > pickle.PicklingError: Can't pickle : it's not > > found as __ > > main__.None > > http://docs.python.org/lib/node317.html- Hide quoted text - What's involved in Can you have a Python object stored entirely on disk? No process to access: changes to contents written back. From stefan_ml at behnel.de Mon Mar 24 11:36:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Mar 2008 16:36:39 +0100 Subject: Element Tree Help In-Reply-To: References: Message-ID: <47E7CA87.7090901@behnel.de> Robert Rawlins wrote: > Hello Guys,I have little to no experiance with element tree and I'm > struggling to find a way to parse the details from the XML document > (attached) into my application. Essentialy I'm looking to take the > following document and turn it into a dict of tuples, each dict element > defines a datasource with the key to the element being the 'name' which is > defined in the XML and then the value of the pair is a tuple which contains > the details of the datasource, like the host and port etc.I've attached a > copy of the example XML to this email.Can anyone offer some advice on how > to get started with this? I've spent a little time looking over the > documentation of element tree and have struggled to break the ice and parse > this document.Thanks guys,Robert Given this document: a name localhost 3306 database1 someusername somepassword another name localhost 3306 database2 itsusername andthepassword I would do something like this: d = {} for event, element in ET.iterparse("thefile.xml"): if element.tag == "datasource": d[element.find("name")] = tuple([ el.text for el in element ]) Stefan From tjreedy at udel.edu Wed Mar 19 00:47:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2008 00:47:39 -0400 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org><87r6e9zu4p.fsf@benfinney.id.au><646uapF2at163U1@mid.uni-berlin.de><13tst1388cp67d8@corp.supernews.com><47de9f6c$0$2657$9b622d9e@news.freenet.de> Message-ID: "Duncan Booth" wrote in message news:Xns9A65624FD1932duncanbooth at 127.0.0.1... | Stargaming wrote: | | > On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: | > | >> For the answer I actually want each asterisk substitutes for exactly one | >> character. | > | > Played around a bit and found that one: | > | > Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) | > [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 | > Type "help", "copyright", "credits" or "license" for more information. | >>>> a = 1 | >>>> b = 1//1 | >>>> if a is b: print('yes!') | > ... | >>>> b | > 1 | >>>> type(b) | > | | I've had a look to see why this happens: long division (and in Python 3 all | integers are longs) allocates a new long to hold the result of the division | so it will never use one of the preallocated 'small int' values. | | That makes sense so far as it goes, but I'm slightly suprised if it isn't | worth an extra check somewhere for numerator fitting in a machine int and | shortcutting the long division. I submitted the following to the issue tracker http://bugs.python.org/issue2417 Python 3.0a3 (r30a3:61161, Mar 1 2008, 22:51:17) [MSC v.1500 32 bit (Intel)] on win32 >>> a,b=1,1//1 >>> a is b False IDLE 3.0a3 >>> a,b=1,1//1 >>> a is b True ditto for 2.5.2 interpreter On c.l.p, Duncan Booth wrote I've had a look to see why this happens: long division (and in Python 3 all integers are longs) allocates a new long to hold the result of the division so it will never use one of the preallocated 'small int' values. That maybe explains the change from 2.5 but not the difference from IDLE. More important, the small int checks are present with the other operations: >>> 1*1 is 1 True >>> 1+1 is 2 True >>> 1-1 is 0 True >>> 1**1 is 1 True so the omission with // is plausibly a bug. Terry Jan Reedy From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 19:39:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 00:39:28 -0000 Subject: Nested phrases [was Re: Want - but cannot get - a nested class to inherit from outer class] References: <18b456bf-bc3d-45f6-af92-369e01e0f426@o77g2000hsf.googlegroups.com> Message-ID: <13t3o20lbtipica@corp.supernews.com> On Fri, 07 Mar 2008 14:26:25 -0800, castironpi wrote: > Humans have enormous "mental stacks"--- the stacks the contexts the > speakers speak in push things they're hearing on to. This is not true. Human beings have extremely shallow mental stacks, limited by short-term memory. Most people are capable of keeping seven, plus or minus two, items in short term memory at once. Any more than that and they are subject to fading away or being over-written. Grammatically, it doesn't take many levels to confuse most people, and even the best and brightest can't keep track of hundreds of levels, let alone "enormous" numbers. At least, not unless you consider five to be enormous. Steven Pinker's "The Language Instinct" has some excellent examples of such "top heavy" phases, such as: He gave the girl that he met in New York while visiting his parents for ten days around Christmas and New Year's the candy. She saw the matter that had caused her so much anxiety in former years when she was employed as an efficiency expert by the company through. Fortunately the English grammar, which is very strict about word order (Pinker describes it as "tyrannical") allows alternate forms that are easier for our shallow stacks to deal with: He gave the candy to the girl that he met in New York while visiting his parents for ten days around Christmas and New Year's. She saw the matter through that had caused her so much anxiety in former years when she was employed as an efficiency expert by the company through. Pinker also describes situations where the words can be grouped into phrases as you go, and so are easy to comprehend: Remarkable is the rapidity of the motion of the wing of the hummingbird. and a counter-example of a perfectly grammatical sentence, with only THREE levels, which is all but unintelligible: The rapidity that the motion that the wing that the hummingbird has has has is remarkable. These nested "onion sentences" are exceedingly difficult for the human brain to parse. In fact, I'm betting that at least 90% of people will, on first reading, will question whether it could possibly be grammatically correct. -- Steven From sjmachin at lexicon.net Wed Mar 19 07:09:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 04:09:27 -0700 (PDT) Subject: a beginner, beginners question References: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Message-ID: On Mar 19, 9:40 pm, klaus wrote: > Hello, > > I'm trying to learn python programming and so far so good. However when > trying to master the oop side I ran into a small problem. > > I think I've done everything ok as outlined below. But I just don't > understand why the `method' of `class' example isn't printing any of the > variables that I have set earlier on ? Could someone please explain to me > what it is I am doing wrong ? > > Thank you so much ! > > #!/usr/bin/env python > > class example: What book or online tutorial are using that doesn't lead you to express that as: class Example(object): ?? > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > def method(self): > print "method ... :" > print self.foo > print self.bar > > if __name__ == "__main__": > obj = example To see what is happening here, do: print repr(obj) You need to CALL the class: obj = example() > obj.foo = "var1" > obj.bar = "var2" > obj.method This expression produces the method itself, then throws it away. You need to CALL the method: obj.method() HTH, John From duncan.booth at invalid.invalid Thu Mar 13 05:50:07 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Mar 2008 09:50:07 GMT Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <7x3aqvf9o2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Terry Reedy" writes: >> | I don't see what's so inefficient about it necessarily. >> >> The key function is called once per list item, for n calls total. >> The comparision function is called once per comparision. There are >> at least n-1 such calls and typically something on the order of n * >> lg2(n) calls. > > Right. Depending on the application, calling the comparison function > lg(n) times may be faster than calling the key function once. > > Example: you want to sort a list of strings case-independently, each > string containing a few pages worth of text. There are 10000 strings, > each maybe 10000 chars long. Then (untested): > > x.sort(xs, key=lower) > > makes a copy of each of the 10000 strings, makes 10000 tuples, sorts, > then releases the temporary strings and tuples. At least 100 > megabytes of memory allocated and 100 million chars copied, even > though any give pair of strings will usually differ somewhere in the > first few characters and there's no need to look past those. Not tuples actually, there's a special sortwrapper type which is used. This is slightly better as it stops the comparison leaking through to the original values without having to store an index value. As Dan has pointed out, for those rare cases where it actually is better to use cmp than key you can easily create a wrapper. The only change is that you now have to work at using cmp instead of it being the first thing you think of. So here you could use his wrapper and your comparison function together: x.sort(key=cmp_key(xcmp)) I'd agree though that the comparison wrapper should be reasonably well publicised: I'd remembered that there was an easy way to implement cmp in terms of key but not what it was. From arnodel at googlemail.com Sat Mar 22 13:07:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 10:07:59 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> Message-ID: <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> On Mar 22, 4:38?pm, Zentrader wrote: > > if ('one', 'two') are in f: ... > > "are" gives me an error in Python 2.5 with a "from future import *" > statement included. ?What version and platform are you running. ?Also, > the docs don't mention it.http://docs.python.org/ref/keywords.html That's because you have to do: from bearophile import musings HTH -- Arnaud From brnstrmrs at gmail.com Mon Mar 17 16:00:50 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Mon, 17 Mar 2008 13:00:50 -0700 (PDT) Subject: struct unpack Message-ID: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> If I run: testValue = '\x02\x00' junk = struct.unpack('h', testValue) Everything works but If I run testValue = raw_input("Enter Binary Code..:") inputting at the console '\x02\x00' junk = struct.unpack('h', testValue) It errors out with Traceback (most recent call last): File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in junk = struct.unpack('h', testValue) File "struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 2 any ideas? From sjmachin at lexicon.net Thu Mar 20 03:07:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Mar 2008 00:07:34 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: <3797c5dd-8d10-4298-af05-fd06440119ce@c19g2000prf.googlegroups.com> On Mar 20, 12:50?pm, "Gabriel Genellina" wrote: > En Wed, 19 Mar 2008 20:16:36 -0300, John Machin ? > escribi?: > > > On Mar 20, 9:14 am, sturlamolden wrote: > >> Is a Python set implemented using a hash table? > > > What don't you understand about the comments in the first two > > screenfuls of Objects/setobject.c? > > That comment was unnecesarily harsh, don't you think? > No, otherwise I wouldn't have made it. From gabriel.rossetti at mydeskfriend.com Wed Mar 26 04:35:07 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Wed, 26 Mar 2008 09:35:07 +0100 Subject: Strange loop behavior Message-ID: <47EA0ABB.3030804@mydeskfriend.com> Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != "": file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) > 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the "d" variable is en empty string at some point, so the looping should stop. -- Arimaz SA Av. du 24 Janvier 11 Ateliers de la Ville de Renens, Atelier 5 1020 Renens, Switzerland www.mydeskfriend.com Mob: +41-(0)79-539-0069 From davids at evertech.com.au Thu Mar 13 00:25:12 2008 From: davids at evertech.com.au (David S) Date: Thu, 13 Mar 2008 04:25:12 GMT Subject: Handling global variables (Newbie) Message-ID: Hi, I have an error occurring at self.build_root = os.path.abspath(os.path.split(__file__)[0]) The error states 'NameError: global name '__file__' is not defined' In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get defined? Yours, David From castironpi at gmail.com Mon Mar 31 23:48:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 20:48:35 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> <80d1731d-a3c6-4fce-81fd-9c3f3537e59b@d21g2000prf.googlegroups.com> <5386cf08-c155-4fbb-8373-dbbb9829a9e7@m3g2000hsc.googlegroups.com> Message-ID: <3c27b270-e593-4f2a-b881-68126319760c@8g2000hsu.googlegroups.com> On Mar 31, 10:28?pm, castiro... at gmail.com wrote: > On Mar 31, 9:27?pm, George Sakkis wrote: > > > > > > > On Mar 31, 8:51 pm, castiro... at gmail.com wrote: > > > On Mar 31, 7:14 pm, 7stud wrote: > > > > > On Mar 31, 5:31 pm, castiro... at gmail.com wrote: > > > > > > Can you have a Python object stored entirely on disk? > > > > > import cPickle as cp > > > > > class Dog(object): > > > > ? ? def __init__(self, name): > > > > ? ? ? ? self.name = name > > > > > d = Dog("Spot") > > > > > f = open("data.txt", "w") > > > > cp.dump(d, f) > > > > f.close() > > > > > f = open("data.txt") > > > > stored_obj = cp.load(f) > > > > print stored_obj.name > > > > > --output:-- > > > > Spot > > > >>> import pickle > > > >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) > > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps > > > ? ? Pickler(f, protocol).dump(obj) > > > ? File "C:\Programs\Python\lib\pickle.py", line 221, in dump > > > ? ? self.save(obj) > > > ? File "C:\Programs\Python\lib\pickle.py", line 283, in save > > > ? ? f(self, obj) # Call unbound method with explicit self > > > ? File "C:\Programs\Python\lib\pickle.py", line 697, in save_global > > > ? ? (obj, module, name)) > > > pickle.PicklingError: Can't pickle : it's not > > > found as __ > > > main__.None > > >http://docs.python.org/lib/node317.html-Hide quoted text - > > What's involved in Can you have a Python object stored entirely on > disk? ?No process to access: changes to contents written back. We do have, but on Windows, file is not locked to multi-tasking, shelve. But why don't we have types in there, or non-string primitives in keys? >>> c= shelve.open( 'temp', 'c' ) >>> c['0']= 'a' >>> c.sync() >>> del c >>> c= shelve.open( 'temp', 'c' ) >>> c['0'] 'a' >>> c['0'].append( 0 ) >>> c['0'] [] And why don't primitive mutations modify contents of disk? A metaquestion. >>> c['0']= type('None',(),{}) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\shelve.py", line 114, in __setitem__ p.dump(value) File "C:\Programs\Python\lib\pickle.py", line 221, in dump self.save(obj) File "C:\Programs\Python\lib\pickle.py", line 283, in save f(self, obj) # Call unbound method with explicit self File "C:\Programs\Python\lib\pickle.py", line 697, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle : it's not found as __ main__.None From nospam at nospam.com Fri Mar 14 02:32:11 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 14 Mar 2008 07:32:11 +0100 Subject: Monitoring SSHd and web servers? Message-ID: Hello I'd like to monitor connections to a remote SSH and web server. Does someone have some code handy that would try to connect every 5mn, and print an error if the script can't connect? Thank you. From castironpi at gmail.com Fri Mar 21 09:58:16 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 06:58:16 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> Message-ID: <555af81e-9d3e-4ab3-a6f3-43d02a8b4acd@m3g2000hsc.googlegroups.com> On Mar 21, 8:14?am, castiro... at gmail.com wrote: > On Mar 20, 9:28?am, "Jerry Hill" wrote: > > On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano > > wrote: > > > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > > > > ?> suppose > > > ?> origsz=(400,300) > > > ?> i want to divide the origsize by 2.5 so i can resize to (160,120) > > > > ?> scale=2.5 > > > ?> how can i get the newsz? > > > ?> obviously origsz/2.5 won't work ?.. > > > > ?newsz = (origsz[0]/scale, origsz[1]/scale) > > > That works fine for a 2-tuple, but might get unwieldy for larger > > tuples, or if you don't know the length until runtime. ?A more general > > solution might use a generator expression, like this: > > > newsz = tuple(x/scale for x in origsz) > > You want to perform a uniform call on the elements of a collection. > +1 compose. By the way. -And sorry for interrupting the OP's time- I feel that control flow objects could be a really powerful addition to a language. Compose a for-loop. From marko at pacujo.net Thu Mar 13 16:58:07 2008 From: marko at pacujo.net (Marko Rauhamaa) Date: 13 Mar 2008 22:58:07 +0200 Subject: subprocess.Popen pipeline bug? References: <026208f0-cd70-4f6a-bfe5-9f8f09a5b0f6@n58g2000hsf.googlegroups.com> Message-ID: bryanjugglercryptographer at yahoo.com: > Not sure. I think what's happening is that the second cat subprocess > never gets EOF on its stdin, because there are still processes with an > open file descriptor for the other end of the pipe. You are right. However, the close_fds technique seems a bit heavy-handed. Well, that's what you get when you try to combine fork and exec into a single call. Marko -- Marko Rauhamaa mailto:marko at pacujo.net http://pacujo.net/marko/ From ggpolo at gmail.com Wed Mar 26 06:05:16 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 26 Mar 2008 07:05:16 -0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: <47EA1604.4070905@gmail.com> References: <47EA1604.4070905@gmail.com> Message-ID: 2008/3/26, Alex9968 : > Hi all, > > I use Tkinter's Pack widget geometry manager (I really prefer it over > using visual GUI designers), so my question is which other GUI toolkits > have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. > > Secondly, I like the detailed widget borders configuration possible in > Tkinter, which can be used to tweak GUI look, and wonder if other > toolkits support it. With Tkinter's case, I like the resulting (tweaked) > look in Windows, but I'm afraid it can be quite different (and ugly) on > other platforms. You sure can, but differently. > > (The reason I ever consider moving from Tkinter is some inconveniences, > involving for example window scrolling, plus its smaller amount of > widgets compared to some other toolkits, plus its (rumored) ugly look on > certain environments. I will not necessary change the toolkit, but I > have to consider it) > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. For now you could try using Tile extension, and update to Tk 8.5. If you don't want to use extensions, then you will have to wait or change the toolkit for now. > Could anyone with experience in different toolkits help, please > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bearophileHUGS at lycos.com Sun Mar 16 10:32:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Mar 2008 07:32:13 -0700 (PDT) Subject: Types, Cython, program readability Message-ID: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> It seems the development of Cython is going very well, quite differently from the dead-looking Pyrex. Hopefully Cython will become more user-friendly too (Pyrex is far from being user-friendly for Windows users, it doesn't even contain a compiler, I think. The ShedSkin Windows installer contains an old but working MinGW, and this is positive). It seems Cython is going to become an efficient and general purpose language after all, with optional static typing (its purpose: mostly for speed), and it may even gain some kind of macros soon. So it may even end replacing Python itself in some situations where running efficiency is important, and where Psyco can't be used or isn't enough. Apparently unrelated: few days ago I was translating a 200-lines long program from Python to D (D is mostly statically typed, like C++, Java) for personal use. That Python program was without unit tests, comments, docstrings, documentation, etc. So finding the types of all the variables required some time. So I have fed the whole program to ShedSkin, and in 20 seconds on my old PC it has produced a Python program with full type annotations (as comments on each line of code), that later I have translated quickly to D. In such "blind" situations (that are often enough in some scripts I find around) I think a statically typed program (without type inference) can be more readable than a Python program, because even if the programmer is super-lazy types must be present (otherwise the program doesn't compile), and with the variable names they give me some information that's absent (well, it's less easy to extract. ShedSkin is often able to extract it) from the Python code. The (little) point of this post: sometimes (when the programmer is quite lazy) statically typed code is more "readable" than Python code. Bye, bearophile From grante at visi.com Sat Mar 1 23:09:14 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 04:09:14 -0000 Subject: Telnet versus telnetlib References: <8acce230-4acf-43fe-9cb7-e4e50350381e@s13g2000prd.googlegroups.com> Message-ID: <13ska3aju6cse5b@corp.supernews.com> On 2008-03-01, Gabriel Genellina wrote: > En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis > escribi?: > >> When I do an analogous process using telnetlib, I get no debug output, >> and most importantly, when I send the XML file to the host, I get no >> printed page. Unfortunately, I do not have access to the host to do >> troubleshooting there, so I have to "feel" my way around. Any >> suggestions on what might be going wrong? >> >> In [12]: tn.write(""" >> ....: > \ is the quote character. You have to duplicate it "C:\\labels..." or use > a raw string r""" <64b3e29d-ce9d-42f9-a285-5001a31d9448@d62g2000hsf.googlegroups.com> Message-ID: Hi all, Thank you so much for all your help :) I really appreciate it. I discovered that my problem was because of my firewall and everything works now :) Regards, Gowri From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 07:23:41 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 11:23:41 -0000 Subject: MySQL DB-Api Message-ID: <008601c8836a$5c5fbf90$151f3eb0$@rawlins@thinkbluemedia.co.uk> Good morning list. I'm in the process of learning my way around the DB-API module for MySQL and wanted to come and get some advice on how you all manage your database connections and cursors. Within my applications I'll have many classes which access the database, I'm wondering to what level I should extract the database connection. Should I create a new database connection and close it for every method which calls the database? Should I create the connection/cursor to the DB when I construct the class and place the cursor in the self scope? Or should I create a application wide connection/cursor to the database and inject the cursor into all the classes which require it? All classes within the application access the same database so at the moment I'm leaning towards creating an application wide connection and cursor and then injecting it into classes which require database access, does that sound like a fair plan? I'm just interested to learn how you are managing this. Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From nejtak... Sun Mar 9 17:26:59 2008 From: nejtak... (Troels Thomsen) Date: Sun, 9 Mar 2008 22:26:59 +0100 Subject: 1.5.2 and functools or similar Message-ID: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Hello, I am writing a simple delayed-call mechanism , that is causing a bit of headache. Works like this: myPrint(s) print "..." + s myTimer.add(myPrint , "hello" , 15) This means that the myprint function is called in 15 seconds with the parameter "hello". The housekeeping of these timers is called by the main loop of the "os" This works well but i would like to be able to use it with any number of parameters Functools is not a part of the 1.5.2+ python that I am running on (embedded device), so i tried to pass the parameters as a tuple like this myTimer.add(myAdder , (3,6) , 15) and the housekeeping function would then call the function like this def updateTimers() for timerItm in timerTable: ... .... .... timerItm.func(*timerItm.parameters) Works well on python 2.5 but not on 1.5.2 (?) Current solution is to have default parameters None for the add function def add( func , timeout , param1 = None , param2 = None) And the update function then checks if parameters is specified def updateTimers() for timerItm in timerTable: ... .... .... # ugly part : if timerItm.param1 is not None and timerItm.param2 is not None: timerItm.func(timerItm.param1, timerItm.param2) # two parameters elif ...... timerItm.func(timerItm.param1) # one parameter else timerItm.func() # no parameters This has the implication that I can not call a function with the parameter None if I wanted to. (not a huge problem) Right now it works quite well with up to two parameters, it covers 99% of usage. If I need to call a function with more parameters, i can always write a wrapper function for it. Wondering if anyone had some sugestions ? By the way, is it bad style to check for object identity instead of value "None". What aboutt integers ? if value is 0: .. I guess it is implementation specific / could change in future versions ? Thx, Troels From steve at holdenweb.com Mon Mar 31 00:44:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 00:44:57 -0400 Subject: Odd behaviour with list comprehension In-Reply-To: References: <4fbfbb8f0802291901s5ed7e0b4ua3e77ad46aa53bb7@mail.gmail.com> <871w6vkq3z.fsf@micah.cowan.name> Message-ID: Terry Reedy wrote: > "Steve Holden" wrote in message [...] > | Well, the fact that the bound variable in the list comprehension does > | indeed remain outside the construct is simply the result of an > | over-zealous wish to emulate for loop semantics. The original reasoning, > | IIRC, as that since a for loop left its bound variable at the last used > | value, so should a list comprehension. > | > | This was quickly recognized as a mistake, but unfortunately not quickly > | enough. As it was felt that some people might already have relied on > | that behavior, it was retained in the interests of preserving backwards > | compatibility. > > But it will not be retained in 3.0, as I understand it. > So best to not exploit the deprecated behavior. > Correct. The compatibility break provided by 3.0 allows the developers to drop this historical grunge. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stugots at qwest.net Tue Mar 18 12:04:40 2008 From: stugots at qwest.net (John DeRosa) Date: Tue, 18 Mar 2008 09:04:40 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: <0rpvt3pls55b0uiaqfvnubarm2afjtpgh8@4ax.com> On Mon, 17 Mar 2008 14:36:29 -0500, "J. Clifford Dyer" wrote: >Note to speakers: do not say > > x, y = tee(foo) > >say > > from itertools import tee > x, y = tee(foo) > >or better (for pedagogical purposes) > > import itertools > x, y = itertools.tee(foo) > I was scratching my head over tee() also, in the session where I heard it. Were you in the "iterators II" session also? I've used itertools a bit, but never tee(), and so when I thumbed through my copy of PER I thought, ahh, I've skimmed over but never registered the importance of that little bugger before... That was one of the more interesting sessions to me. John From bharathv6.project at gmail.com Tue Mar 4 09:41:08 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Tue, 4 Mar 2008 20:11:08 +0530 Subject: http server performance Message-ID: <2613171a0803040641u1b48dfcai96c9172fd093c4d7@mail.gmail.com> hi, my project involves lot of I/O over the network.. one part of my project involves a server(http) which is listening on the port for many client . this sever fetches an image from the web and and send it to clients .... and many clients will request the server concurrently .. to implement concurrent serving to clients i used threaded http server like this class HTTPServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer): pass class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): print "received connection from: ",self.client_address image=image_retreive() #where image retreive is a function that retrieves image from the web and works fine self.send_response(200) self.send_header("Content-type",format) self.send_header("Content-Length",len(image_data)) self.end_headers() self.request.sendall(image_data) httpd = HTTPServer(('',port_number), RequestHandler) httpd.serve_forever() this code worked fine but this performance was very bad ... it workes fine if the clients requested for small n medium size images as the server sends the response immediately and also workes fine if one client is requesting a large image (obviously server takes time to send response as it takes time to fetch the image from the web ) and other clients concurrently request for small and medium images these clients will be served immediately even if the other client is waiting but problem crops up when 2 clients concurrently request for an large image .. while these two clients are waiting for the response fromthe server . The server doesn't accept any other client request ... i can see this as i am printing the address of the client that connects with server in the 1st line of get method of the request handler if two clients concurrently request for an large image and only two clients address gets printed that means only 2 clients receives connection to the server even if other clients are requesting the server at the same time and other servers are served only after the those 2 server releases the connection or get the response . that means server servers only 2 clients at a time .this is very undesirable as even if 3rd client is requesting for very small image and 2 clients are waiting for large image .. 3rd client won't receive the response until those 2 clients are served . to make thing worst my server should serve 10 to 15 clients concurrently to solve this i did some searching and found about cherrypy and twisted also implemented my server in cherrypy like this from cherrypy import wsgiserver def image_httpserver_app(environ, start_response): print >>sys.stdout,"received connection from: (%s : %s ) \nthe image url is: %s " % (environ["REMOTE_ADDR"],environ["REMOTE_PORT"],environ["QUERY_STRING"]) status = '200 OK' response_headers = [('Content-type',format)] image=image_retreive() response_headers = [("Content-Length",`len(image_data)`)] start_response(status, response_headers) return [image_data] mappings=[('/', image_httpserver_app)] wsgi_apps = mappings server = wsgiserver.CherryPyWSGIServer(('localhost', 8888), wsgi_apps, server_name='localhost',numthreads=20) if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop() this didn't solve the problem at all .. same thing is happening only 2 clients is served at a time ..even if no of threads is assigned to 20 .. i have did lot of searching and reading .. and hoping to find a solution ..can anyone make it easier for me i have heard of twisted deffered object .. will it solved the problem ? if not pls suggest me alternative.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 8 17:14:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 08 Mar 2008 20:14:18 -0200 Subject: SV: Quit-command not quiting References: <63d2efF271u6hU1@mid.individual.net> <63d5v1F23vm9fU1@mid.individual.net> Message-ID: En Fri, 07 Mar 2008 13:56:45 -0200, K Viltersten escribi?: >>> The window itself vanishes if i click the >>> cross in the upper-right corner but pressing >>> the quit-button only makes it "pressed". >>> Then, the program freezes. >> >> How did you run it? From inside IDLE? IDLE itself is written >> using Tk, and I think that your mainloop interferes with the >> one inside it. If you run your program from the command line >> it should work fine. > > I press F5 while in the editor window. Is there a way to run the > program without going to the console window? > Perhaps i'm just making things unneccesarily complicated > and Python IS supposed to be run from console window? No, use IDLE if you prefer, or any other editor/IDE. But in your case there is an unfortunate coupling between IDLE and your script. Fix: change the quit method as suggested in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/92bee52a3e2a325e/ def quit(self): self.master.destroy() This is OK if used on the top level widget on the application (your Demo class, for instance). A more general solution: def quit(self): parent = self while parent.winfo_class() != 'Tk': if parent.master is None: break; parent = parent.master else: parent.destroy() (from https://sourceforge.net/tracker/index.php?func=detail&aid=661324&group_id=9579&atid=109579 ) This appears to work fine. But the loop, as written, could exit without calling destroy() on anything; perhaps some other people knowing better how Tkinter and Tk work could improve it or confirm it's fine as it is. -- Gabriel Genellina From phd at phd.pp.ru Mon Mar 10 07:37:46 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 10 Mar 2008 14:37:46 +0300 Subject: SQLObject 0.9.5 Message-ID: <20080310113746.GB14369@phd.pp.ru> Hello! I'm pleased to announce the 0.9.5, a minor bug fix release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.5 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.4 ---------------- Bug Fixes ~~~~~~~~~ * Fixed a minor bug in SQLiteConnection.columnsFromSchema() - set dbName. * A bug in delColumn() that removes all properties is fixed by recreating properties. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From steve at REMOVE-THIS-cybersource.com.au Thu Mar 13 17:22:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 21:22:30 -0000 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <87skyvuhpo.fsf@rudin.co.uk> Message-ID: <13tj6omdip82f13@corp.supernews.com> On Thu, 13 Mar 2008 08:54:43 +0000, Paul Rudin wrote: >> Whatever python has for a calling convention, it is close enough that >> naming it "call by reference" gives people a reasonable idea of what is >> going on. > > Quite. The thing is not to get hung up with the label - but to > understand what actually happens. Agreed. And I think the best way to do that is to use the same terms that other languages use to get very different behaviour indeed. "Python is call by reference, but this doesn't work like call by reference in all the other languages I've used: def negate(n): n = -n x = 2 negate(x) assert x == -2 Is this a bug, or is Python actually call by value?" And now comes the explanations that Python is actually call by value, but the values being copied are *pointers* (ignoring Jython, IronPython and PyPy); or that Python is really call by reference, but different "things" (it's never quite clear what exactly) happen depending on whether the arguments are mutable or immutable; or that if you define reference broadly enough, everything is a reference; or that if you define value broadly enough, everything is a value; or if schools would just stop teaching kiddies C and start teaching them Lisp, call by reference semantics would be understood in a different way, or or or or... And thus, by insisting that there are two and only two calling conventions, no matter how many different kinds of calling behaviour actually exist, we ensure that we'll be having this same *&$%^*# argument when Python 4000 comes out. And for that we can all be grateful. -- Steven From carsten at uniqsys.com Sun Mar 23 21:18:31 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 02:18:31 +0100 Subject: Does python hate cathy? In-Reply-To: References: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> Message-ID: <1206321511.3365.28.camel@localhost.localdomain> On Sun, 2008-03-23 at 20:05 -0500, Michael Wieher wrote: > is that farnarkeling about in a __del__ method is *not* a good > idea. > > Ok that having been said, is accessing an unbound variable of a class > and using it to coordinate between instances of that class common > practice? I'm not sure what you mean by "accessing an unbound variable" means in the context of this thread, or any context for that matter. Nothing of the kind is happening in the OP's example. What's happening is that a class attribute is initialized, incremented, and decremented. Using class attributes is common practice. The problem, as I explained in my previous post, is that the class attribute is looked up via a global name of the class, and that name may or may not have disappeared in a puff of logic by the time the instance's __del__ method is run in the VM shutdown sequence. -- Carsten Haese http://informixdb.sourceforge.net From smartpawn at gmail.com Wed Mar 19 03:43:34 2008 From: smartpawn at gmail.com (Deepak Rokade) Date: Wed, 19 Mar 2008 13:13:34 +0530 Subject: Using threads in python is safe ? In-Reply-To: References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Message-ID: <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> Thanks all for removing confusion about GIL, one more question; If jobs to be processed by threds is I/O bound would multithreading help python to improve speed of application ? Since I read that " multithreading is not a good strategy to improve speed of python application." On Mon, Mar 17, 2008 at 7:00 AM, Benjamin wrote: > On Mar 16, 3:40 pm, "Gabriel Genellina" > wrote: > > En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade > > escribi?: > > > > > I want to use therads in my application. Going through the docs , I > read > > > about GIL. > > > Now I am confused whether using threads in python is safe or not. > > > > > One thing I know that if I am accessing global variables in two or > more > > > threads I need to synchronize them > > > using locking or such mechanism so that only one thread access them at > a > > > time. > > > > Yes, altough some operations are known to be atomic so you don't need a > > lock in that cases. I think there is a list in the wiki somewhere > http://wiki.python.org/moinor perhaps at the effbot's site > http://www.effbot.org > Even for atomic operations, you should lock, though. That is not > consistent over different Python implementations and is not always > going to be in same in CPython. > > > > > 1. In order to support multi-threaded Python programs, there's a > global > > > lock that must be held > > > by the current thread before it can safely access Python objects. > > > Does this lock need to be held by python application script > expliciltly > > > before accessing any python object or > > > interpreter takes acre of it ? > > > > No, the interpreter takes care of it. The GIL is a concern for those > > writing extensions using the Python API. > > > > > 2. Does multithreaded python script need to held lock before calling > any > > > blocking I/O call? > > > Or one should not worry about GIL while using python threads if job to > be > > > processed by thread does not call > > > any global variables and thread unsafe Python/C extension ? > > > > Python code should not worry about the GIL. The problem would be, a > > callback written in Python for a not-thread-aware extension that had > > released the GIL. > > > > -- > > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanx & Regards, Deepak Rokade Do what u Enjoy & Enjoy what u Do........... -------------- next part -------------- An HTML attachment was scrubbed... URL: From craigm3604 at gmail.com Sun Mar 23 17:24:52 2008 From: craigm3604 at gmail.com (Craig) Date: Sun, 23 Mar 2008 14:24:52 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> Message-ID: <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> On Mar 23, 4:48 pm, Dennis Lee Bieber wrote: > On Sat, 22 Mar 2008 19:05:31 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > I got back exactly what I expected for TypeDef, but SecKey and PriKey > > were what I initialized them to , not what should have been returned. > > > Do you mean that I should change any string that is expected to be > > changed by the dll to a create_string_buffer type (LPSTR) instead of a > > windll.oleaut32.SysAllocStringByteLen type (LPBSTR) and then simply > > list it in the call instead of byref, as I did with TypeDef? > > Based upon my interpretation of the C prototype and the ctypes > documentation (sample code), that IS what I expect... (I didn't expect > it to work with the TypeDef field though...) > > There are two ways in which a C language function call can handle > returning string data. (Let's see if I remember how to code C; been 6 > years) > > char pre_alloc_buffer[] = "This is a fixed nul-terminated buffer space"; > char *dynamic_buffer; /* this is an uninitialized pointer to char */ > char *dynamic_too; > > The function can either modify a buffer passed in: > > int func1(char *bfr); > > or it can allocate a buffer internally and return that either as a > function result, or via a reference to a pointer variable > > char *func2(char *bfr[]); /* ugh, my memory is fading */ > /* If I did this right, it is a pointer to array of character */ > > res = func1(pre_alloc_buffer); > or > res = func1(&pre_alloc_buffer[0]); /* long/explicit form */ > > The address of the start of the buffer space is passed, and func1 > performs its magic in the pre-allocated buffer. > > dynamic_too = func2(&dynamic_buffer); > > Here, we pass the address of just a pointer variable (which > currently points to garbage). func2 is expected to perform something > wherein IT allocates memory and that memory address is what is put into > the argument/return > > ... > *bfr = malloc(...); > return (bfr); > > Based on my interpretation of the prototypes, I'd have expected the > two BSTR to be the func1 style passing of a buffer, but the last > argument /might/ have been the second func2 style. > > I really can't be more definitive; I've not used ctypes -- only read > the documentation; the only DLLs I've had to use were covered by the > win32 extension library which comes as part of the ActiveState Python > installation. > > > > > Can it really be that simple? > > > As for the structure: > > class VSTATS(Structure): > > _fields_ = [ > > ("nrecords", c_long), > > ("gps_used", c_short), > > ("gps_unused", c_short), > > ("max_key_len", c_short), > > ("grp_size", c_long), > > ("init_alloc", c_short), > > ("cr_opts", c_short), > > ("free_prop_area", c_short), > > ("format", c_void_p), > > ("reserved", c_void_p) > > ] > > vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) > > can I just use a create_string_buffer (LPSTR) and parse things up via > > substrings after the call returns? > > It may be possible, though the library seems to have gone out of its > way to mask such efforts from the user. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ This dll was designed to be used from either C or Visual Basic 6. I have the declare statements for VB6, if that helps. Based on the results I have so far (and I have tried MANY permutations like trying to use the LPSTR for SecKey and PriKey which are returned as is TypeDef), it looks like SecKey and PriKey are being used as data instead of pointers. For this, I try: LPSTR = c_char_p VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = create_string_buffer(41) SecKey.raw = "1234567890123456789012345678901234567890" PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) and I get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 158, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) WindowsError: exception: access violation reading 0x3433322D I notice that SecKey.raw starts with "1234" and the exception address is 0x3433322D, which is "432-". And, changing to: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, LPSTR] PriKey = create_string_buffer(41) PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) I then get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 159, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) WindowsError: exception: access violation reading 0x4443423D I notice that PriKey.raw starts with "ABCD" and the exception address is 0x4443423D, which is "DBC=". So, I can see that there is data where pointers are expected. I just don't see how to pass those pointers. When they were passed as LPBSTR (and oleaut32.SysAllocString), the calls "worked" in that they didn't get exceptions and they did return the correct record, but the SecKey and PriKey fields were not correct, and they were BSTR (pointers). I did get the VmxInfo to work by: VSTATS_fmt = "lhhhlhhhlll" VsamInfo = create_string_buffer(36) temp = unpack(VSTATS_fmt, VsamInfo.raw) vStats = VSTATS(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7]) Any idea on how to jump the last hurdle on VmxGet? This is the very last thing that is stopping my project. From john.deas at gmail.com Sun Mar 9 09:06:04 2008 From: john.deas at gmail.com (John Deas) Date: Sun, 9 Mar 2008 06:06:04 -0700 (PDT) Subject: parralel downloads References: Message-ID: <50047985-ed16-46cb-a933-8afddac6a056@y77g2000hsy.googlegroups.com> On Mar 9, 1:25 pm, John Deas wrote: > On Mar 8, 5:47 pm, Gary Herron wrote: > > > > > poof65 wrote: > > > For your problem you have to use threads. > > > Not at all true. Thread provide one way to solve this, but another is > > the select function. For this simple case, select() may (or may not) be > > easier to write. Pseudo-code would look something like this: > > > openSockets = list of sockets one per download file: > > while openSockets: > > readySockets = select(openSockets ...) # Identifies sockets with > > data to be read > > for each s in readSockets: > > read from s and do whatever with the data > > if s is at EOF: close and remove s from openSockets > > > That's it. Far easier than threads. > > > Gary Herron > > > > You can have more information here. > > >http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > > > >> Hi, > > > >> I would like to write a python script that will download a list of > > >> files (mainly mp3s) from Internet. For this, I thought to use urllib, > > >> with > > > >> urlopen("myUrl").read() and then writing the resulting string to a > > >> file > > > >> my problem is that I would like to download several files at the time. > > >> As I have not much experience in programming, could you point me the > > >> easier ways to do this in python ? > > > >> Thanks, > > > >> JD > > >> -- > > >> http://mail.python.org/mailman/listinfo/python-list > > Thank you both for your help. Threads are working for me. However, a > new problem for me is that the url I want to download are in an xml > file (I want to download podcasts), and is not the same as the file > downloaded: > > http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2... > > will be redirected to download: > > http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 > > is there a way, knowing the first url to get the second at runtime in > my script ? Found it: geturl() does the job From kaushikbarat at gmail.com Sat Mar 15 05:10:24 2008 From: kaushikbarat at gmail.com (kaush) Date: Sat, 15 Mar 2008 02:10:24 -0700 (PDT) Subject: ImportError while Embedding python in C Message-ID: <0e568278-c5b3-40d3-a172-7d1701510f50@s19g2000prg.googlegroups.com> Hi All, I have a simple python script saved to "test.py" as import os import base64 def Testfunction(): print "Hello World" return Testfunction() I am trying to invoke this from a C program as follows int main(int argc, char* argv[]) { Py_Initialize(); PyObject* main_module = PyImport_AddModule("__main__"); PyObject* main_dict = PyModule_GetDict(main_module); FILE* file_1 = fopen(TestFile, "r"); PyRun_AnyFile(file_1, TestFile); Py_Finalize(); return 0; } This fails with the error Traceback (most recent call last): File "/home/kaushik/shadowFs/test.py", line 4, in import base64 File "/usr/local/lib/python2.5/base64.py", line 9, in import struct File "/usr/local/lib/python2.5/struct.py", line 30, in from _struct import Struct, error ImportError: /usr/local/lib/python2.5/lib-dynload/_struct.so: undefined symbol: PyExc_TypeError I am able to run test.py successfully from the shell. What am i missing in importing the base64 library? Thanks, Kaushik From castironpi at gmail.com Sat Mar 29 10:11:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 07:11:19 -0700 (PDT) Subject: Help me on function definition References: Message-ID: <9d932e66-ac5f-43ad-a06c-cd3f5186b47e@e67g2000hsa.googlegroups.com> On Mar 29, 4:18?am, Roel Schroeven wrote: > aeneng schreef: > > > > > > > Hello everyone, > > > I am just starting to use python in numerical cacluation. > > I need you to help me to see what's wrong with the following piece of > > codes, which computes the cross product of two vectors and returns > > the result. u and v are two 3x1 matrix. > > > when I import the function, error message show like this > >>>> import cross > > Traceback (most recent call last): > > ? File "", line 1, in ? > > ? File "cross.py", line 8 > > ? ? ppp2=u[2]*v[0]-u[0]*v[2] > > ? ? ^ > > SyntaxError: invalid syntax > > > WHAT IS WRONG WITH MY CODE? > > > I appreciate your help. > > > ##here is the function definition. > > ##cross.py## > > def cross(u,v) > > ? ? """input two vectors u and v in 3-D space, ? ? > > ? ? ? ?output a cross product of vector w, in column or in row > > accordingly.""" > > ? ? ppp1,ppp2,ppp3=0.0,0.0,0.0 > > You forgot the : after def cross(u, v) No; directional is only signed and unsigned. There's a laptop on my computer. From http Thu Mar 13 01:57:33 2008 From: http (Paul Rubin) Date: 12 Mar 2008 22:57:33 -0700 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: <7x3aqvf9o2.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > | I don't see what's so inefficient about it necessarily. > > The key function is called once per list item, for n calls total. The > comparision function is called once per comparision. There are at least > n-1 such calls and typically something on the order of n * lg2(n) calls. Right. Depending on the application, calling the comparison function lg(n) times may be faster than calling the key function once. Example: you want to sort a list of strings case-independently, each string containing a few pages worth of text. There are 10000 strings, each maybe 10000 chars long. Then (untested): x.sort(xs, key=lower) makes a copy of each of the 10000 strings, makes 10000 tuples, sorts, then releases the temporary strings and tuples. At least 100 megabytes of memory allocated and 100 million chars copied, even though any give pair of strings will usually differ somewhere in the first few characters and there's no need to look past those. from string import lower from operator import eq from itertools import * def xcmp(a,b): for x,y in izip(a,b)): c = cmp(x.lower() y.lower()) if c: return c return 0 x.sort(xcmp) runs the comparison function about 14000 times, looking at only a few bytes on most of the calls, and using only a small constant amount of auxiliary storage, and is likely to be much faster than all that copying. Hmm, there is a slight problem with xcmp-- it will fail if a is a prefix of b. That's fixable but anyway it still makes its point as written. From castironpi at gmail.com Tue Mar 4 21:31:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 18:31:11 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: On Mar 4, 7:06?pm, Tommy Grav wrote: > On Mar 4, 2008, at 4:53 PM, Jeff Schwab wrote: > > > What does "SV" in the subject mean? > > SV = "Svar" is the Norwegian word for Reply. > > Cheers > ? ?Tommy It is also the name of my lockermate in grade school. "So, Svar, how 'bout them posters?" From http Sun Mar 9 19:35:07 2008 From: http (Paul Rubin) Date: 09 Mar 2008 16:35:07 -0700 Subject: 1.5.2 and functools or similar References: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Message-ID: <7xbq5nqxn8.fsf@ruckus.brouhaha.com> "Troels Thomsen" writes: > timerItm.func(*timerItm.parameters) > > Works well on python 2.5 but not on 1.5.2 (?) I think in 1.5.2 the *args notation wasn't present and you had to say: apply(timerItm.func, timerItm.parameters) From python at bdurham.com Mon Mar 10 11:27:06 2008 From: python at bdurham.com (Malcolm Greene) Date: Mon, 10 Mar 2008 11:27:06 -0400 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) In-Reply-To: <47D54F11.4020508@behnel.de> References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <1205162826.18146.1241560441@webmail.messagingengine.com> Stefan, > My personal experience with wxPython has its ups and downs. Specifically when it comes to crashes, I wouldn't bet my life on it. (but then, the OP I'm new to Python and getting ready to build a small client based application intended to run on Windows and Linux. I was planning on using wxPython until I saw your comment above. Any suggestions on an alternative Python client-side GUI library (pyQT ?) or tips on where I can find out more about wxPython/wxWidget problems? Thank you, Malcolm From zerty.david at gmail.com Sun Mar 30 16:07:46 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:07:46 -0300 Subject: Error Raised But dont know what it means In-Reply-To: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> References: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> Message-ID: <5dc598e30803301307g20d9494ekf140387361c31968@mail.gmail.com> Here is the code: This one raises the error: def criaLista(self): self.listbox.Clear() for dupla in self.duplas: self.listbox.Append(dupla.__str__()) This one works well but doesn't raises error dupla1 = Duplas("2422", "2455") dupla2 = Duplas("454", "15") list = [] list.append(dupla1) list.append(dupla2) erros = ErrorMgr() erros.geraErro("1", "erro idiota", 2.2) dic = {1:dupla1, 2:dupla2} a = Arquivos("batata.txt") a.saveFile(list, erros, dic) a.openFile() lista = a.getListaDuplas() e = a.getErrorsManager() d = a.getDicDuplas() for i in lista: print i print d[1] On Sun, Mar 30, 2008 at 5:03 PM, David Anderson wrote: > Well, I'm dealing with files in Pickle, I'm saving at the file a List of > Objects from the same Class, When I try to retrive this information and try > to iterate over them this error is raised: > TypeError: 'instancemethod' object is not iterable > > But if I just print the method I get the 'real thing' what's the problem? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Mar 28 12:17:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Mar 2008 17:17:44 +0100 Subject: threads and extension module initialization In-Reply-To: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: <654k1kF2e8bnuU1@mid.uni-berlin.de> pianomaestro at gmail.com schrieb: > I have an extension module that gets initialized multiple > times because I am using threads. > > How can this module access global state (not per-thread state) ? > It needs to create a singleton. The question is very unclear. If you are after *not* initializing your module concurrently, why don't you just do it *once* before the threads are started? alternatively, you need to govern the initialization-code with a mutex - or anything similar. Diez From stefan_ml at behnel.de Sun Mar 23 12:51:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Mar 2008 17:51:21 +0100 Subject: Issues with XMLTreeBuilder in cElementTree and ElementTree In-Reply-To: <5d820787-e27d-4ae2-8b2b-b82af8ce67cf@p25g2000hsf.googlegroups.com> References: <5d820787-e27d-4ae2-8b2b-b82af8ce67cf@p25g2000hsf.googlegroups.com> Message-ID: <47E68A89.3020900@behnel.de> Michael Becker wrote: > Secondly, I found a potential issue with the cElementTree module. My > understanding (which could be incorrect) of python C modules is that > they should work the same as the python versions but be more > efficient. The XMLTreeBuilder class in cElementTree doesn't seem to be > using the same parser as that in ElementTree. The following code > illustrates this issue: > >>>> import xml.etree.cElementTree >>>> t1=xml.etree.cElementTree.XMLTreeBuilder() >>>> t1._parser.ordered_attributes = 1 > Traceback (most recent call last): > File "", line 1, in > AttributeError: _parser >>>> import xml.etree.ElementTree >>>> t1=xml.etree.ElementTree.XMLTreeBuilder() >>>> t1._parser.ordered_attributes = 1 Mind the underscore. You are using a non-public interface here. Don't expect other implementations to support that. Stefan From mail at microcorp.co.za Sat Mar 29 07:14:46 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Mar 2008 13:14:46 +0200 Subject: Serial port error statistics - any comparable data? Message-ID: <001b01c8918e$323b74c0$03000080@hendrik> Hi, I have been doing some tests on a device that we are thinking of incorporating into a product, and I have seen that reception on a serial port at 115200 baud over about six metres of RS-232 cable makes mistakes, to the order of 125 lines with errors in them out of approximately 18.4 million lines of 65 or so chars - about one errored line in 147000, or one error character in 95 million. The PC that is making the errors is a 64 bit dual core AMD machine running at 2 Gig, and I am running stock standard Open Suse 10.3 with the supplied Python 2.5. What kind of bothers me is the nature of the errors - I seem to get only missing characters, as if an interrupt was missed. There are no munged characters as one would expect if the errors were bit related. Has anyone else seen anything like this, and am I worrying needlessly? I realise that my production protocols will easily handle this almost non existent level of error - but if this were in microcontroller code that I had written myself, I would suspect that I was spending too long in some critical section of code. - Hendrik From pradiprai at gmail.com Mon Mar 31 06:27:25 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 15:57:25 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Hi All, I have upgraded python v2.5.2 from python v2.4.3. The upgradation results into following error: "Python C API version mismatch for module dbi: This Python has API version 1013, module dbi has version 1012." Please suggest, how to resolve this error to proceed further. Regards, Pradeep Rai -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Fri Mar 14 08:20:45 2008 From: DustanGroups at gmail.com (Dustan) Date: Fri, 14 Mar 2008 05:20:45 -0700 (PDT) Subject: This actually works. References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> Message-ID: On Mar 13, 6:19 pm, "Dotan Cohen" wrote: > On 14/03/2008, Dustan wrote: > > > you.screw() > > Ah, you are pushing sex pills. > > > self.thank(God, encapsulation) > > And bibles? Interesting combination. > > > not self.want_to_know(you.screw.func_code) > > Unsubscribe? I know better... > > Dotan Cohen > > http://what-is-what.comhttp://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? SyntaxError: invalid syntax From misceverything at gmail.com Fri Mar 28 15:40:01 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Fri, 28 Mar 2008 12:40:01 -0700 (PDT) Subject: Finding Full Path to Process EXE Message-ID: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Hello, I would like to write a script that would enumerate all running processes and return the full path to the EXE of each running process. However, I can't seem to find any good info on how to do this..any help is greatly appreciated. Thanks. T From siona at chiark.greenend.org.uk Wed Mar 5 07:23:24 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 Mar 2008 12:23:24 +0000 (GMT) Subject: popening a process in a specific working directory References: Message-ID: Michael Torrie wrote: >I'm currently using popen2.Popen4. Is there a way to properly specify a >particular working directory when launching a process in python? Switch to using subprocess.Popen and specify the cwd argument. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From neilcrighton at gmail.com Tue Mar 11 16:43:32 2008 From: neilcrighton at gmail.com (neilcrighton at gmail.com) Date: Tue, 11 Mar 2008 13:43:32 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: Sorry my initial post was muddled. Let me try again. I've got a zipped archive that I can extract files from with my standard archive unzipping program, 7-zip. I'd like to extract the files in python via the zipfile module. However, when I extract the file from the archive with ZipFile.read(), it isn't the same as the 7- zip-extracted file. For text files, the zipfile-extracted version has '\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't tried comparing binary files via the two extraction methods yet. Regarding the code I posted; I was writing it from memory, and made a mistake. I didn't use: z = zipfile.ZipFile(open('foo.zip', 'r')) I used this: z = zipfile.ZipFile('foo.zip') But Duncan's comment was useful, as I generally only ever work with text files, and I didn't realise you have to use 'rb' or 'wb' options when reading and writing binary files. To answer John's questions - I was calling '\r' a newline. I should have said carriage return. I'm not sure what operating system the original zip file was created on. I didn't fiddle with the extracted file contents, other than replacing '\r' with ''. I wrote out all the files with open('outputfile','w') - I seems that I should have been using 'wb' when writing out the binary files. Thanks for the quick responses - any ideas why the zipfile-extracted files and 7-zip-extracted files are different? On Mar 10, 9:37 pm, John Machin wrote: > On Mar 10, 11:14 pm, Duncan Booth > wrote: > > > > > "Neil Crighton" wrote: > > > I'm using the zipfile library to read a zip file in Windows, and it > > > seems to be adding too many newlines to extracted files. I've found > > > that for extracted text-encoded files, removing all instances of '\r' > > > in the extracted file seems to fix the problem, but I can't find an > > > easy solution for binary files. > > > > The code I'm using is something like: > > > > from zipfile import Zipfile > > > z = Zipfile(open('zippedfile.zip')) > > > extractedfile = z.read('filename_in_zippedfile') > > > > I'm using Python version 2.5. Has anyone else had this problem > > > before, or know how to fix it? > > > > Thanks, > > > Zip files aren't text. Try opening the zipfile file in binary mode: > > > open('zippedfile.zip', 'rb') > > Good pickup, but that indicates that the OP may have *TWO* problems, > the first of which is not posting the code that was actually executed. > > If the OP actually executed the code that he posted, it is highly > likely to have died in a hole long before it got to the z.read() > stage, e.g. > > >>> import zipfile > >>> z = zipfile.ZipFile(open('foo.zip')) > > Traceback (most recent call last): > File "", line 1, in > File "C:\python25\lib\zipfile.py", line 346, in __init__ > self._GetContents() > File "C:\python25\lib\zipfile.py", line 366, in _GetContents > self._RealGetContents() > File "C:\python25\lib\zipfile.py", line 404, in _RealGetContents > centdir = struct.unpack(structCentralDir, centdir) > File "C:\python25\lib\struct.py", line 87, in unpack > return o.unpack(s) > struct.error: unpack requires a string argument of length 46 > > >>> z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK > >>> z = zipfile.ZipFile('foo.zip', 'r') # OK > > If it somehow made it through the open stage, it surely would have > blown up at the read stage, when trying to decompress a contained > file. > > Cheers, > John From gagsl-py2 at yahoo.com.ar Mon Mar 17 13:51:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 14:51:27 -0300 Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> <9192affb-3a3f-4558-909b-d9734c1b1ad2@u10g2000prn.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 14:22:31 -0300, hellt escribi?: > On 17 ???, 15:48, "Gabriel Genellina" wrote: >> En Mon, 17 Mar 2008 08:56:26 -0200, hellt >> escribi?: >> >> > i have a problem with this modules py2exe + pywinauto + sendkeys used >> > together. >> > pywinauto uses sendkeys when performs TypeKeys function. > when i include sendkeys to my package's list i have an error posted > below: > > "No module named SendKeys" Does your script actually work *without* py2exe? SendKeys is a separate package that you have to download and install separately. -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 06:25:09 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 12:25:09 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <659845F2e56g7U2@mid.individual.net> Lie wrote: > Ah yes, that is also used (I completely forgot about that one, my > math's aren't that sharp anymore) and I think it's used more > frequently than ><. Where did you read that (I mean, which country)? I've never seen this sign in any german or english book on mathematics/physics/engineering I saw. > but my argument was that no math book use != or <> (except in math > for programmers). That's true. Personally, I don't ever use "a!=b" in favor of "not a==b". Regards, Bj?rn -- BOFH excuse #282: High altitude condensation from U.S.A.F prototype aircraft has contaminated the primary subnet mask. Turn off your computer for 9 days to avoid damaging it. From http Sat Mar 29 05:25:03 2008 From: http (Paul Rubin) Date: 29 Mar 2008 02:25:03 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> Message-ID: <7xzlshkhlc.fsf@ruckus.brouhaha.com> Hrvoje Niksic writes: > Note that I said "*file* input/output". Twisted and asyncore are > about asynchronous socket programming that polls over nonblocking file > descriptors such as found in socket programming, not about wrapping > aio(3) and the equivalent Windows APIs. aio is also used for sockets, while twisted and asyncore use select or something similar. That is asynchronous but in a different sense of the word. See also: http://www.kegel.com/c10k.html From tmp1 at viltersten.com Mon Mar 10 00:20:28 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Mon, 10 Mar 2008 05:20:28 +0100 Subject: SV: SV: Changing the size of a Button In-Reply-To: References: <63ifhtF277va7U1@mid.individual.net> <63iokhF284p4hU1@mid.individual.net> Message-ID: <63jq9qF26sreoU1@mid.individual.net> >> What i wish to do is to affect the size >> of the button but not due to change of >> text but due to resize of the frame it >> resides in. > > This is done by the layout manager, too: > > import Tkinter as tk > > root = tk.Tk() > button = tk.Button(root, text="42") > button.pack(fill=tk.BOTH, expand=True) > root.mainloop() > > Alternatively, with a grid layout: > > button.grid(row=0, column=0, sticky="nsew") > root.rowconfigure(0, weight=1) > root.columnconfigure(0, weight=1) Ah, great! I'll try that right away. After breakfast, of course! Thanks! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From aboudouvas at panafonet.gr Thu Mar 27 07:59:44 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 04:59:44 -0700 (PDT) Subject: Psyco alternative Message-ID: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> Hi, it seems that Psyco's author will not port it for the upcoming Python 3000 release :( So, for us who use it we will continue to use CPython 2.5.x version for some time to come. Is there an alternative to Psyco so i can have a look at ? Thanks in advance. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 07:41:20 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 13:41:20 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: <47cfe65d$0$9590$426a74cc@news.free.fr> Sam a ?crit : > Hello > > if type(a) is dict: > print "a is a dictionnary!" class MyDict(dict): pass a = MyDict() type(a) is dict => False From grante at visi.com Wed Mar 5 15:38:21 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 20:38:21 -0000 Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: <13su15t266dimc2@corp.supernews.com> On 2008-03-05, Jeff.Goldfinkle at gmail.com wrote: > Is there a simple way to twiddle the bits of a float? In particular, I > would like to round my float to the n most significant bits. > > For example - 0.123 in binary is 0.000111111 > Rounding to 4 bits I get 0.0001. > > I can pack and unpack a float into a long > e.g. > struct.unpack('I',struct.pack('f',0.123))[0] > but then I'm not sure how to work with the resulting long. > > Any suggestions? Just use the bitwise and/or/not operators: & | ~ -- Grant Edwards grante Yow! Half a mind is a at terrible thing to waste! visi.com From bbxx789_05ss at yahoo.com Sun Mar 2 08:57:49 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 2 Mar 2008 05:57:49 -0800 (PST) Subject: tcp References: Message-ID: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> On Mar 2, 6:09?am, Gif wrote: > i have this small script which after some router configurations works. > > ########################################################## > > #! /usr/bin/python > import socket > > HOST = '' > PORT = 1515 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind((HOST, PORT)) > s.listen(1) > conn, addr = s.accept() > conn.send('HTTP/1.1 200 OK\r\n') > conn.send('Content-Type: text/html\r\n') > conn.send('Server: test/1.0\r\n\r\n') > conn.send('test') > s.close() > > ########################################################## > > as you see it listens to 1515 until a connection is established and > then it accepts it... > the problem is that when it accepts the connection it sends those > strings and exits, but then it exits the program. i want it to listen > to 1515 then accept a connection, send.. and then listen to the port > again and again until new connections are found. > > i've been struggling with try..except,while and all kinds of loops but > always new erros pop up, or it overflows. while True: conn, addr = s.accept() ... From modelnine at modelnine.org Wed Mar 26 13:31:42 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 26 Mar 2008 18:31:42 +0100 Subject: Some notes on a high-performance Python application. In-Reply-To: <47ea78a5$0$36353$742ec2ed@news.sonic.net> References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: <200803261831.43109.modelnine@modelnine.org> Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: > ... > > Using MySQL as a queueing engine across multiple servers is unusual, > but it works well. It has the nice feature that the queue ordering > can be anything you can write in a SELECT statement. So we put "fair > queueing" in the rating scheduler; multiple requests from the same IP > address compete with each other, not with those from other IP addresses. > So no one site can use up all the rating capacity. > > ... > > Does anyone else architect their systems like this? A Xen(tm) management system I've written at least shares this aspect in that the RPC subsystem for communication between the frontend and the backends is basically a (MySQL) database table which is regularily queried by all backends that work on VHosts to change the state (in the form of a command) according to what the user specifies in the (Web-)UI. FWIW, the system is based on SQLObject and CherryPy, doing most of the parallel tasks threaded from a main process (because the largest part of the backends is dealing with I/O from subprocesses [waiting for them to complete]), which is different from what you do. CherryPy is also deployed with the threading server. -- Heiko Wundram From riccardocirello at gmail.com Tue Mar 25 12:19:56 2008 From: riccardocirello at gmail.com (cuordileone) Date: Tue, 25 Mar 2008 09:19:56 -0700 (PDT) Subject: Outlook 2003 and Python References: <2pidnTOUdc03jHTanZ2dnUVZ_uqvnZ2d@comcast.com> Message-ID: On Mar 25, 3:52?pm, Larry Bates wrote: > cuordileone wrote: > > Good Day. > > > I woul like to ask you if it is possible to make a program in python > > that move the email messages that I had received in outlook 2003, to a > > specific folder, accoding to the sender's name: > > > Es: mar... at martin.com -->> folder Martin. > > > Thanks. > > > Riccardo. > > You could, but it is much easier to just use built in tools (from Outlook > help): > > Automatically move messages from a certain person > Select a message from the person whose messages you want to automatically move. > On the Tools menu, click Organize. > In the second bulleted item, click the options you want. To choose a folder, > click the arrow next to the Into list. > Click Create. > Note ?To create more complex rules for organizing items, you can also use the > Rules and Alerts dialog box on the Tools menu. > > -Larry Thanks a lot, Larry From gandalf at shopzeus.com Fri Mar 21 04:54:34 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 21 Mar 2008 09:54:34 +0100 Subject: eval and unicode In-Reply-To: <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E377CA.10301@shopzeus.com> Hi Jonathan, I think I made it too complicated and I did not concentrate on the question. I could write answers to your post, but I'm going to explain it formally: >>> s = '\xdb' # This is a byte, without encoding specified. >>> s.decode('latin1') u'\xdb' # The above byte decoded in latin1 encoding >>> s.decode('latin2') u'\u0170' # The same byte decoded in latin2 encoding >>> expr = 'u"' + s + '"' # Create an expression for eval >>> expr 'u"\xdb"' # expr is not a unicode string - it is a binary string and it has no encoding assigned. >>> print repr(eval(expr)) # Eval it u'\xdb' # What? Why it was decoded as 'latin1'? Why not 'latin2'? Why not 'ascii'? >>> eval( "# -*- coding: latin2 -*-\n" + expr) u'\u0170' # You can specify the encoding for eval, that is cool. I hope it is clear now. Inside eval, an unicode object was created from a binary string. I just discovered that PEP 0263 can be used to specify source encoding for eval. But still there is a problem: eval should not assume that the expression is in any particular encoding. When it sees something like '\xdb' then it should raise a SyntaxError - same error that you should get when running a .py file containing the same expression: >>> file('test.py','wb+').write(expr + "\n") >>> ^D gandalf at saturnus:~$ python test.py File "test.py", line 1 SyntaxError: Non-ASCII character '\xdb' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Otherwise the interpretation of the expression will be ambiguous. If there is any good reason why eval assumed a particular encoding in the above example? Sorry for my misunderstanding - my English is not perfect. I hope it is clear now. My problem is solved anyway. Anytime I need to eval an expression, I'm going to specify the encoding manually with # -*- coding: XXX -*-. It is good to know that it works for eval and its counterparts. And it is unambiguous. :-) Best, Laszlo From torriem at gmail.com Wed Mar 5 00:01:57 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 04 Mar 2008 22:01:57 -0700 Subject: popening a process in a specific working directory Message-ID: <47CE2945.9070303@gmail.com> I have a small multi-threaded program that spawns a number of threads that each spawn a particular process in a particular temporary directory. My problem is that using os.chdir to change the working directory before popening the process doesn't always work because another thread might change the cwd as it starts, before the process in this thread can start up. I'm currently using popen2.Popen4. Is there a way to properly specify a particular working directory when launching a process in python? I've hacked around my problem by writing a bash wrapper script that accepts the working directory as a parameter, changes the directory, then spawns the original program with the arguments. This works, but I'd like a better way. Michael From mentaltruckdriver at gmail.com Sat Mar 1 20:45:55 2008 From: mentaltruckdriver at gmail.com (Ryan M.) Date: Sat, 1 Mar 2008 17:45:55 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 1, 7:56?pm, Ira Solomon wrote: > I am an experienced programmer (40 years). ?I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. ?I would appreciate recommendations on those as well. > > Thanks > > Ira I would recommend checking out the official Python tutorial - http://docs.python.org/tut/ - it has some valuable information, and is always kept up to date. I'm haven't looked at any Python books (yet), so I can't provide any recommendations there. HTH. From martin at v.loewis.de Sat Mar 1 17:51:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Mar 2008 23:51:36 +0100 Subject: [Python-Dev] [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: <79990c6b0803011439n583bc2b2w5c544b620a91fa61@mail.gmail.com> References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> <47C9D802.2090205@v.loewis.de> <79990c6b0803011439n583bc2b2w5c544b620a91fa61@mail.gmail.com> Message-ID: <47C9DDF8.30000@v.loewis.de> > The 2.6a1 x86 MSI is there, but the 3.0a3 x86 MSI is still giving a 404. Please try again - *those* files weren't actually there when I sent my last message; I just built them. Regards, Martin From gagsl-py2 at yahoo.com.ar Fri Mar 21 14:29:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 11:29:29 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> <128011dd-a1a8-43af-bdea-beba452aa596@f63g2000hsf.googlegroups.com> Message-ID: <17b331d5-445a-481b-a637-e5e428f58ca0@f63g2000hsf.googlegroups.com> On 21 mar, 15:11, MRAB wrote: > On Mar 21, 11:48 am, fkallgren wrote:> Hi. > > > I have a little problem. I have a script that is in the scheduler > > (win32). But every now and then I update this script and I dont want > > to go to every computer and update it. So now I want the program to 1) > > check for new version of the script, 2) if there is a new version, > > copy that verision from server to local drive, 3) shutdown the program > > and start it up again as the new version. > > > The problem is that I can't run this script directly from server so it > > have to run it locally. > > > Anyone having any bright ideas?? > > import os > import sys > import shutil > > # Is there a newer version? > my_path = sys.argv[0] > update_path = os.path.join(os.path.dirname(my_path), "new_script.py") > > if os.path.getmtime(my_path) < os.path.getmtime(update_path): > ? ? # Update the script. > ? ? shutil.copy2(update_path, my_path) > ? ? # Re-start the script. > ? ? os.startfile(my_path) > ? ? sys.exit() > > # The rest of the script... I do mostly the same, except that instead of os.startfile I use: args = [sys.executable] args.extend(sys.argv) os.spawnl(os.P_NOWAIT, sys.executable, *args) to re-start the current script with the same arguments it was invoked before. -- Gabriel Genellina From micah at cowan.name Fri Mar 7 17:39:11 2008 From: micah at cowan.name (Micah Cowan) Date: Fri, 07 Mar 2008 22:39:11 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <87zlta9n1s.fsf@micah.cowan.name> "K Viltersten" writes: > 2. You should use two spaces after a sentence-ending period. > > For heavens sake, why? I've always been obstructed by the double > blanks but tolerated them. Now, that i read that > it actually is a recommendation, i need to ask about the purpose. AFAICT from modern publications (which nevertheless get many other things wrong, such as how f and i are handled when they appear in sequence), this practice has mostly been eschewed, thankfully. In "The Elements of Typographical Style", by Robert Bringhurst, has this to say (section 2.1.4 of version 3.0): In the nineteenth century, which was a dark and inflationary age in typography and type design, many compositors were encouraged to stuff extra space between sentences. Generations of twentieth-century typists were then taught to do the same, by hitting the spacebar twice after every period. Your typing as well as your typesetting will benefit from unlearning this quaint Victorian habit. As a general rule, no more than a single space is required after a period, colon or any other mark of punctuation. Larger spaces (e.g., en spaces) are _themselves_ punctuation. He goes on to note that this does not apply to setting languages such as classical Latin or Greek, or other circumstances in which sentences begin with lowercase letters, where the extra space is actually helpful. The Elements of Typographical Style (much like Strunk & White) is not gospel, but is written by a highly experienced typesetter, and is chock full of very sound advice. Personally, I find double-spacing to be an abomination. However, there are some practical issues to note. One is that some editors (notably vi) only recognize a period as ending a sentence if they are followed by two spaces. This may be the default for Emacs as well (I don't do much "moving by sentence" in Emacs). For this reason, the GNU Coding Guidelines recommend ensuring that all periods in comments and in plaintext documentation have periods. Knuth's typesetting program, ???, in its default "plain" format (and in the popular La??? format as well), will add extra space at the ends of sentences automatically (I always disable this functionality when I write for either of those; I believe the command is "\frenchspacing"). -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From Grimsqueaker13 at gmail.com Thu Mar 27 04:59:26 2008 From: Grimsqueaker13 at gmail.com (Grimsqueaker) Date: Thu, 27 Mar 2008 01:59:26 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> <13umnl0ou29kn63@corp.supernews.com> Message-ID: <8e4a12d4-f848-40d3-b21b-2d3e57416377@m36g2000hse.googlegroups.com> OK, got that. If I use: for x in string_cartesian_product('abc'): print x I get: a b c What am I not understanding? Thank you From marek.rocki at wp.pl Sat Mar 8 08:38:43 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 8 Mar 2008 05:38:43 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> <1ec4b03a-75cd-432e-9e5d-750132324d38@s8g2000prg.googlegroups.com> <4e27c893-d7c6-4ab4-abaa-187520dfc69b@d62g2000hsf.googlegroups.com> Message-ID: <2317bea5-4451-4c73-abfe-c1bb626d9837@f47g2000hsd.googlegroups.com> Everybody has already explained why this doesn't work and a possible "solution" using metaclasses was suggested. I tried to implement it, ended up with monkey-patching __bases__, which is certainly an abomination (will it be possible in python 3.0?) but seems to do the trick. class _InheritFromOuterClass(object): """ This class is used as a marker. """ pass class MetaFixInheritance(type): """ This metaclass, along with ordinary class creation, changes base of all the inner classes (marked as inheriting from _InheritFromOuterClass) to the class being created. """ def __new__(self, name, bases, members): result = type(name, bases, members) for member in members.itervalues(): if isinstance(member, type) and issubclass(member, _InheritFromOuterClass): member.__bases__ = result, return result class Outer(object): """ Test an inner class inheriting from the outer class. Inheritance is monkey-patched upon creation of the outer class. """ __metaclass__ = MetaFixInheritance class Inner(_InheritFromOuterClass): pass def foo(self): return 'Outer.foo()' inner = Outer.Inner() print 'Inner.foo() is in fact', inner.foo() From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 23:23:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 04:23:40 -0000 Subject: float / rounding question References: Message-ID: <13t456cmgfpdhbc@corp.supernews.com> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote: > Sorry to come in so late in this discussion. Although it is correct to > say that many real numbers that have an exact decimal representation > cannot be exactly represented in binary, that is no excuse to print 53.6 > as 53.600000000000001. This is just lousy printing and the fact that > this kind of question comes up every week shows that it is confusing to > many people. Good. That's a feature, not a bug. Floats *are* confusing and unintuitive. Anyone with pretensions to be a programmer should get over the illusion that floats are reals as soon as possible, before they learn bad habits that have to be unlearned. If that starts with them asking why they get 53.600000000000001 instead of 53.6, so be it. If they want to be insulated from the harsh reality, they can do this: >>> print 53.6 53.6 -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 20:34:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 01:34:16 -0000 Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <7xmypa844v.fsf@ruckus.brouhaha.com> Message-ID: <13t3r8oeh4frj43@corp.supernews.com> On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote: > Pierre Quentel writes: >> I would like to know if there is a module that converts a string to a >> value of the "most probable type" > > Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > >>> import this > The Zen of Python, by Tim Peters > ... > In the face of ambiguity, refuse the temptation to guess. Good advice, but one which really only applies to libraries. At the application level, sometimes (but not always, or even most times!) guessing is the right thing to do. E.g. spreadsheet applications don't insist on different syntax for strings, dates and numbers. You can use syntax to force one or the other, but by default the application will auto-detect what you want according to relatively simple, predictable and intuitive rules: * if the string looks like a date, it's a date; * if it looks like a number, it's a number; * otherwise it's a string. Given the user-base of the application, the consequences of a wrong guess, and the ease of fixing it, guessing is the right thing to do. Auto-completion is another good example of guessing in the face of ambiguity. It's not guessing that is bad, but what you do with the guess. -- Steven From sturlamolden at yahoo.no Sat Mar 22 11:09:39 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 08:09:39 -0700 (PDT) Subject: wxFormBuilder References: <7152b94f-fc30-473f-bd94-5d43a9153f56@p73g2000hsd.googlegroups.com> Message-ID: On 22 Mar, 08:10, CM wrote: > Why can't you use Boa Constructor? I really enjoy using it. It feels awkward. I don't know why. From aahz at pythoncraft.com Sun Mar 16 21:26:23 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Mar 2008 18:26:23 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <87zlsyyxee.fsf@benfinney.id.au> Message-ID: In article <87zlsyyxee.fsf at benfinney.id.au>, Ben Finney wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> I would like to encourage anyone who was at PyCon but has not >> provided formal feedback to use the following URLs: > >For those who don't like to follow opaque munged URLs from services >that give no indication where you'll end up, here are the actual URLs >you'll arrive at: > >> For the conference: >> http://tinyurl.com/2ara8u > > PyCon 2008: Conference Feedback > > >> For the tutorials: >> http://tinyurl.com/2ew2pc > > PyCon 2008: Tutorial Evaluation > Sorry, I agree with you -- those URLs were not (and should have been) on pycon.org, and I just pasted what I got from someone else. Not enough spoons.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bockman at virgilio.it Wed Mar 5 07:39:48 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 5 Mar 2008 04:39:48 -0800 (PST) Subject: draining pipes simultaneously References: Message-ID: > > Inserting delay in the beginning of the loop causes feeling of command > taking long to start and delay at the end of the loop may cause of > data loss when both thread became inactive during delay. time.sleep() pauses ony the thread that executes it, not the others. And queue objects can hold large amount of data (if you have the RAM), so unless your subprocess is outputting data very fast, you should not have data loss. Anyway, if it works for you ... :-) Ciao ----- FB From kyosohma at gmail.com Mon Mar 31 10:41:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 07:41:45 -0700 (PDT) Subject: wxPython listctrl References: <4dc652a5-d6f9-4cb8-af30-ec1c9e4ea505@y21g2000hsf.googlegroups.com> Message-ID: <8fcac15f-ad92-47b2-84bb-1d8e474ea016@i7g2000prf.googlegroups.com> On Mar 29, 4:27 pm, Gif wrote: > I was wondering if there is a way to extract an icon from a file > (executable) and then add it in a listctrl. I also 'd like to know if > i can shorten the icon in order to fit in a listctrl item. > I've managed to get the icon from an icon file and add t as a listctrl > item but it remains 32x32. > > code: > images = ['LimeWire.ico'] > > self.il = wx.ImageList(18, 10) > self.il.Add(wx.Bitmap(images[0])) > > #This below raises an error saying that no handle was found for that > image > #self.ib = wx.IconBundle() > #self.ib.AddIconFromFile(r'LimeWire.exe', wx.BITMAP_TYPE_ANY) > > self.listView1.SetImageList(self.il, wx.IMAGE_LIST_SMALL) > self.listView1.SetItemImage(0, 0) Please re-post to the wxPython user's group: http://wxpython.org/maillist.php I'm pretty sure they know how to do this. Mike From martin.nordstrom87 at gmail.com Thu Mar 27 15:29:23 2008 From: martin.nordstrom87 at gmail.com (martin.nordstrom87 at gmail.com) Date: Thu, 27 Mar 2008 12:29:23 -0700 (PDT) Subject: Building a "safe" python? Message-ID: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> I'm making a game where you'll be able to make your own mods and I want to be able to write these mods in python. However, python has a lot of "dangerous" functions (like erase any file on the harddrive etc) so I want a "safe" python. I first found RExec but that is disabled in python 2.5 so I was thinking about building python from source with a few changes. The changes I was thinking about was to change the import function so that it should only be able to import the .pyd-files that I allow (and it should of course still be able to import any .py-file) and remove or change the builtin functions that are "dangerous". Is this enough to make a "safe" python that can't do anything "dangerous"? I'm going to embed this "safe" python into my game and I've discovered that when I embed the original python and the mod wants to import a .py-file that is not in the game directory it will search for the .py-file in the python directory that is installed on my computer. Can I somehow prevent the embedded python to look in the python directory? Thanks! Martin From grahn+nntp at snipabacken.se Mon Mar 31 18:47:26 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 31 Mar 2008 22:47:26 GMT Subject: standard input, for s in f, and buffering References: <65bg55F2esfc1U3@mid.uni-berlin.de> Message-ID: On 31 Mar 2008 06:54:29 GMT, Marc 'BlackJack' Rintsch wrote: > On Sun, 30 Mar 2008 21:02:44 +0000, Jorgen Grahn wrote: > >> I realize this has to do with the extra read-ahead buffering documented for >> file.next() and that I can work around it by using file.readline() >> instead. >> >> The problem is, "for s in f" is the elegant way of reading files line >> by line. With readline(), I need a much uglier loop. I cannot find a >> better one than this: >> >> while 1: >> s = sys.stdin.readline() >> if not s: break >> print '####', s , >> >> And also, "for s in f" works on any iterator f -- so I have to choose >> between two evils: an ugly, non-idiomatic and limiting loop, or one >> which works well until it is used interactively. >> >> Is there a way around this? Or are the savings in execution time or >> I/O so large that everyone is willing to tolerate this bug? > > You can use ``for line in lines:`` and pass ``iter(sys.stdin.readline,'')`` > as iterable for `lines`. Thanks. I wasn't aware that building an iterator was that easy. The tiny example program then becomes #!/usr/bin/env python import sys f = iter(sys.stdin.readline, '') for s in f: print '####', s , It is still not the elegant interface I'd prefer, though. Maybe I do prefer handling file-like objects to handling iterators, after all. By the way, I timed the three solutions given so far using 5 million lines of standard input. It went like this: for s in file : 1 iter(readline, ''): 1.30 (i.e. 30% worse than for s in file) while 1 : 1.45 (i.e. 45% worse than for s in file) Perl while(<>) : 0.65 I suspect most of the slowdown comes from the interpreter having to execute more user code, not from lack of extra heavy input buffering. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From anaryin at gmail.com Thu Mar 27 10:31:41 2008 From: anaryin at gmail.com (=?ISO-8859-1?Q?Jo=E3o_Rodrigues?=) Date: Thu, 27 Mar 2008 14:31:41 +0000 Subject: Checking processes running under Windows Message-ID: Hello all! I'm trying to write a script that needs to check which processes are running under Windows (XP Pro, Home, whatever). The method I'm using is: >>> process_list = os.popen('TASKLIST').read() However, XP Home doesn't have the tasklist.exe tool so, this is kind of useless in that OS. Do you have any other methods I can use for this? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Mar 19 11:28:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 16:28:37 +0100 Subject: cx_Oracle execute procedure References: Message-ID: <64cppeF2at1j9U2@mid.uni-berlin.de> Poppy wrote: > I've been working on the code below and and executes silently, no > complaints, however the end result should be a record in my table and it's > not added. The procedure works with the passed credentials using SQLPlus > or SQL Developer clients. However I'm not sure if I'm constructing my > python code correctly to interact with Oracle. > > I've been basing the code below on what I found in this thread > http://www.thescripts.com/forum/thread33728.html . > > Zach- > > import cx_Oracle > > connection = cx_Oracle.connect("user/pass at server") > > ## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum > varchar2, p_prefix number) > > cur = connection.cursor() > > repParams = {} > repParams['arg1'] = "5555555" > repParams['arg2'] = "2" > repParams['arg3'] = "999" > > sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3); > end;""" > > cur.execute(sqlStr, repParams) > > connection.commit > > cur.close > > connection.close You forgot to call the methods using the ()-operator. connection.commit() and so forth. Diez From castironpi at gmail.com Fri Mar 7 14:22:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:22:49 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> <51ca8638-65fa-490b-a04a-33ffbefd4aca@s19g2000prg.googlegroups.com> Message-ID: <5d4827e1-8b90-4feb-bfb0-6d956e138b5e@b64g2000hsa.googlegroups.com> > > I find itertools.islice() useful, so for Python 3.x I may like to see > general iterables. ?Third, the analogy breaks down quickly (i.e. > chain(it[:2], it[2:]) does not give the same result as iter(it) unless > >>> s = 'abcdefg' > >>> list(W(s)[2:]) Slice literals are a logical next step, precedented by raw strings and bytes. slice= islice is too, precedented by range= xrange. Does s[2:] evaluate to an infinity? What is the natural meaning of skipping finitely many terms at the head of an iterable? itertools can also grow 'skip(n=0)' and 'drop(step=3)' operations. From apatheticagnostic at gmail.com Mon Mar 3 17:59:16 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Mon, 3 Mar 2008 14:59:16 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> Message-ID: <2ecbb96f-c246-48c5-836f-bf934ac56ba6@e25g2000prg.googlegroups.com> I swear, this is one of the most polite-oriented groups I've ever seen. Not that that's a bad thing or anything, it's nice to be nice. (This has been Captain Universal Truth, over and out) From sturlamolden at yahoo.no Sun Mar 16 13:31:59 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:31:59 -0700 (PDT) Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> Message-ID: <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> On 16 Mar, 18:23, "Martin Blume" wrote: > This seems to imply that the Mac, although running now on Intel > processors, is still big-endian. Or maybe the struct module thinks big-endian is native to all Macs? It could be a bug. From castironpi at gmail.com Thu Mar 13 20:45:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 17:45:52 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: On Mar 13, 7:18?pm, Mel wrote: > Diez B. Roggisch wrote: > >> My understanding is that foo.bar does *not* create a new object. > > > Your understanding is not correct. > > >> ?All it > >> does is return the value of the bar attribute of object foo. ?What new > >> object is being created? > > > A bound method. This happens through the descriptor-protocol. Please see > > this example: > > > class Foo(object): > > ? ? def bar(self): > > ? ? ? ? pass > > > f = Foo() > > a = Foo.bar > > b = f.bar > > c = f.bar > > > print a, b, c > > print id(b), id(c) > > (What Diez said.) ?From what I've seen, f.bar creates a bound method > object by taking the unbound method Foo.bar and binding its first > parameter with f. ?This is a run-time operation because it's easy to > re-assign some other function to the name Foo.bar, and if you do, the > behaviour of f.bar() will change accordingly. > > You can get some very useful effects from these kinds of games. ?You > can make f into a file-like object, for example, with > > import sys > f.write = sys.stdout.write > > Here, f.write *is* a straight attribute of f, although it's a built-in > method of the file class. ?It's still bound, in a way, to sys.stdout. > ? I'm assuming that a different example could create an attribute of f > that's a bound method of some other object entirely. ?I've verified > that f.write('howdy') prints 'howdy' on standard output. Accordingly, f.write= types.MethodType( sys.stdout.__class__.write, sys.stdout ). It depends on what you want the implicit first (self) to be-- f or sys.stdout. But how come this works? >>> import types >>> import sys >>> >>> class C: ... write= sys.stdout.write ... def g( self ): ... self.write( 'was in \'g\'\n' ) ... >>> c= C() >>> c.g() was in 'g' Shouldn't 'write' be getting extra parameters? Sounds fishy, not to mix metaphors. From rbossy at jouy.inra.fr Sat Mar 8 09:49:46 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 08 Mar 2008 15:49:46 +0100 Subject: os.chdir In-Reply-To: <47D2A42A.9010902@v.loewis.de> References: <47D2A42A.9010902@v.loewis.de> Message-ID: <1204987786.47d2a78a33e29@www.jouy.inra.fr> Quoting "Martin v. L?wis" : > >> os.chdir("~/dir1") > > > > It is not mentioned in the documentation but I'm pretty sure os.dir() > doesn't do > > tilde expansion since this is usually performed by a shell. > > > > You should use instead: > > > > os.chdir(os.join(os.environ['HOME'], 'dir1')) > > Or > > os.chdir(os.path.expanduser("~/dir1")) Well... duh! Thanks for reminding me. Cheers, RB From jgardner at jonathangardner.net Thu Mar 20 10:46:25 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 20 Mar 2008 07:46:25 -0700 (PDT) Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: On Mar 20, 4:51?am, "Giampaolo Rodola'" wrote: > Hi all. > Is there any way to su or login as a different user within a python > script? I mainly need to temporarily impersonate another user to > execute a command and then come back to the original user. > I tried to google a little bit about it but I still didn't find a > solution. In the unix world, this is highly discouraged. You shouldn't have to change your user. The only user who can change roles---and who should change roles for security reasons---is root. The only reason sudo is around is for those people who really are root but who don't like logging in as root to do root work. With a very limited permission set for sudo, it is very, very easy to get full root access. $ sudo cp /bin/cp /bin/cp.old; sudo cp /bin/su /bin/cp; sudo cp - # If you want a different user to access files that another user created, that's what groups are for. You should create a common group and then share the files by assigning them to that group and setting the appropriate permissions. Yes, this is painful, and every once in a while you get files that don't have the right permissions or the group is set to the wrong group. But this is the cost of running on a system where multiple users can be doing things all at once, and the cost of trying to make sure that users can't hurt each other. Someone somewhere has to say, "You are allowed to do this much, but no more". If that's not what you need, then you need to run the process as root. It can change its user and even chroot to a jail if need be. This is how apache, for instance, works. It starts as root and spawns the server processes as the apache user. (Apache does have an interesting problem with home directories, and it has a very special solution that is very insecure. Even there, the better solution is to put all the user's files under a common group in a common folder outside of their home directories.) From darkxanthos at gmail.com Wed Mar 19 18:57:16 2008 From: darkxanthos at gmail.com (Justin Bozonier) Date: Wed, 19 Mar 2008 15:57:16 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> Message-ID: On Mar 19, 2:48 pm, John Machin wrote: > On Mar 19, 10:08 am, sturlamolden wrote: > > > > > On 18 Mar, 23:45, Arnaud Delobelle wrote: > > > > > def nonunique(lst): > > > > slst = sorted(lst) > > > > dups = [s[0] for s in > > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > > > return [dups[0]] + [s[1] for s in > > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > > Argh! What's wrong with something like: > > > > def duplicates(l): > > > i = j = object() > > > for k in sorted(l): > > > if i != j == k: yield k > > > i, j = j, k > > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) > > as opposed to ours which are O(N log N). > > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > and is IMHO more readable than Paul's. It's not as much O(N)... Paul Robin's uses a sort first which is definitely not O(N). Paul's could be prettied up a bit but the general principle is sound. From Robert.Bossy at jouy.inra.fr Fri Mar 14 06:26:08 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 14 Mar 2008 11:26:08 +0100 Subject: merging intervals repeatedly In-Reply-To: References: Message-ID: <47DA52C0.6040207@jouy.inra.fr> Magdoll wrote: >> One question you should ask yourself is: do you want all solutions? or >> just one? >> If you want just one, there's another question: which one? the one with >> the most intervals? any one? >> > > I actually don't know which solution I want, and that's why I keep > trying different solutions :P > You should think about what is your data and what is probably the "best" solution. >> If you want all of them, then I suggest using prolog rather than python >> (I hope I won't be flamed for advocating another language here). >> > > Will I be able to switch between using prolog & python back and forth > though? Cuz the bulk of my code will still be written in python and > this is just a very small part of it. > You'll have to popen a prolog interpreter and parse its output. Not very sexy. Moreover if you've never done prolog, well, you should be warned it's a "different" language (but still beautiful) with an important learning curve. Maybe not worth it for just one single problem. >> If you have a reasonable number of intervals, you're algorithm seems >> fine. But it is O(n**2), so in the case you read a lot of intervals and >> you observe unsatisfying performances, you will have to store the >> intervals in a cleverer data structure, see one of these:http://en.wikipedia.org/wiki/Interval_treehttp://en.wikipedia.org/wiki/Segment_tree >> > > Thanks! Both of these look interesting and potentially useful :) > Indeed. However these structures are clearly heavyweight if the number of intervals is moderate. I would consider them only if I expected more than several thousands of intervals. Cheers, RB From giles_brown at hotmail.com Sun Mar 2 09:15:54 2008 From: giles_brown at hotmail.com (Giles Brown) Date: Sun, 2 Mar 2008 06:15:54 -0800 (PST) Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> On Mar 2, 2:08 pm, Preben Randhol wrote: > On Sun, 2 Mar 2008 15:06:17 +0100 > > Preben Randhol wrote: > > class dbase(list): > > Sorry the definition of the class is: > > class dbase(object): > > it doesn't derive from the list class. > > Preben http://docs.python.org/lib/typeiter.html From castironpi at gmail.com Fri Mar 7 17:27:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 14:27:02 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> <13t3cfpo6d8d2ab@corp.supernews.com> Message-ID: <79c6eb9f-fc4a-4d48-9c34-8d6a4fb94a70@n77g2000hse.googlegroups.com> > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! A shapely CATHOLIC > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? SCHOOLGIRL is FIDGETING > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ?inside my costume.. ... Are you wearing it? *plonkblock* So, what gets you plonked around h... *plonk*? From natambu at gmail.com Mon Mar 10 01:21:59 2008 From: natambu at gmail.com (natambu at gmail.com) Date: Sun, 9 Mar 2008 22:21:59 -0700 (PDT) Subject: tcp client socket bind problem Message-ID: I have a linux box with multiple ip addresses. I want to make my python client connect from one of the ip addresses. Here is my code, no matter what valid information I put in the bind it always comes from the default ip address on the server. Am I doing something wrong? ------------- #!/usr/bin/python import socket host = "server" port = 1190 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("",0)) sock.connect((host, port)) ------------- From mensanator at aol.com Wed Mar 12 00:21:12 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 11 Mar 2008 21:21:12 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> <306997c4-36dc-4603-8100-f47e25e55bef@s19g2000prg.googlegroups.com> <792e7610-7807-4deb-b13e-213d162cd2c0@d62g2000hsf.googlegroups.com> Message-ID: <29e51d14-1848-4bcc-aad9-8a5cae686ee8@m36g2000hse.googlegroups.com> On Mar 11, 9:50?pm, Nathan Pinno wrote: > On Mar 11, 1:12 pm, Mensanator wrote: > > > > > > > On Mar 11, 3:36 am, Duncan Booth wrote: > > > > Mensanator wrote: > > > > On Mar 10, 10:44???pm, Nathan Pinno wrote: > > > >> Why does my compiler say invalid syntax and then highlight the > > > >> quotation marks in the following code: > > > > >> # This program is to find primes. > > > > > Needs work. > > > > Be fair. > > > Being helpful isn't fair? > > > > The OP hadn't managed to figure out why the program wasn't > > > running, so you can't expect him to have got all the bugs out of the code > > > yet. > > > The bug had already been answered. > > > If you fail to implement your premise correctly, you have a bug. > > > It doesn't matter if the code is bug-free if the premise is false. > > > In this case, the premise that he can determine primes this way > > is false. He will have to abandon the cos() thing, for although it > > works in theory, he'll never get it to work in practice. > > > Besides, the cos() is a red herring (hint: cos(pi*n)). The problem > > can be made to work EXACTLY (at least up to z=10000) by using > > rationals > > (which gmpy supports). > > > His problem is going to take much more than fixing a syntax error. > > > > And he only asked about the specific syntax error not the entire > > > solution to his homework. > > > If this is indeed homework, and he's supposed to come up with a > > factorial algorithm, I seriously doubt the teacher would accept > > gmpy.fac(z-1), so I assume it isn't. > > > > My advice to Nathan would be: > > > > 1. If you get a weird syntax error that you don't understand try cutting > > > the code down to just the bit which generates the error. > > > > 2. Play around in the interactive interpreter to see what works and what > > > doesn't. > > > > 3. If you don't understand why the code doesn't work then get a stuffed > > > toy, cardboard cutout of a person, or the least technical member of your > > > family and explain to them in great detail exactly why the code must > > > (despite error messages to the contrary) be correct. Usually you'll spot > > > the problem half way through the explanation. > > > > 4. If you post to this list then post the full error message and traceback. > > > That way we don't have to guess which quotation marks are the problem. > > Yep, got it fixed, and no, it is not a homework problem...just a > project for fun to keep up my Python coding in my memory intact > (apparently, it doesn't work as well when I've been up early 3 days in > a row... :P ). > > Now I just have to figure out why it isn't working the way it is > supposed to. Did you see my hints, or are you keen to work it out? My solution tested up to z=10000. Factorial starts getting sluggish there and is utterly intractable for really large numbers, such as RSA. > It was given to me by someone in the sci.math area as an > alternative to working with 1 < x < n.- Hide quoted text - > > - Show quoted text - From ajaksu at gmail.com Thu Mar 20 16:35:35 2008 From: ajaksu at gmail.com (ajaksu) Date: Thu, 20 Mar 2008 13:35:35 -0700 (PDT) Subject: A question about a metacharacter References: Message-ID: On Mar 20, 8:19?am, igbt wrote: > However, if you don't enter anything the > script works but if you enter a dot (.) the script does not work. Have you tried it with other non-metacharacter values? > sss = entryName.get_text() ? ? ?# The script gets the text > ? ? ? ? if sss == "" or sss == ".": > ? ? ? ? ? ? ? ? gtk.main_quit() ? ? ? ?#The script finishes > Try adding this: else: print sss, type(sss) Good luck! Daniel From sjdevnull at yahoo.com Mon Mar 10 12:30:24 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 10 Mar 2008 09:30:24 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> Message-ID: <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> On Mar 10, 11:30 am, rockingred wrote: > On Mar 10, 10:26 am, Roel Schroeven > wrote: > > > > > rockingred schreef: > > > > On Mar 8, 8:27 pm, Dan Bishop wrote: > > >> // Copyright (C) 2008 Foobar Computer Consulting > > >> // > > >> // VERSION PROJECT# DATE DESCRIPTION > > >> // ------- -------- -------- ------------------ > > >> // 1.00 123456 01/04/08 Original creation. > > >> // > > > >> Eleven lines, of which the only useful information to me was the > > >> project number, as knowing this let me look up who was behind these > > >> comments. > > > > Actually, "editorial" comments that tell you who last changed a > > > program, when and why can be useful. I worked in a company with a > > > number of programmers on staff. Having comments that told us Joe > > > worked on a program yesterday that isn't working today could often > > > solve half the battle. Especially if Joe also added a comment near > > > the lines he had changed. Likewise including the "Project#" would > > > help us track all the programs that had to be changed for a specific > > > project. This allowed us to move all related items into the Live > > > system once the testing phase had been completed (we just searched for > > > everything with the same Project# in it). Yes, on rare occasions we > > > would have an entire page of "Editorial" comments to ignore at the > > > beginning of our program listing, but it was easy enough to skip that > > > page. I will grant you that probably after 10 changes the first > > > change isn't as important anymore (unless you want to backtrack and > > > find out who started the Project in the first place and what it's > > > original purpose was). > > > That is certainly useful, but IMO that's what version control systems > > are for. > > > -- > > The saddest aspect of life right now is that science gathers knowledge > > faster than society gathers wisdom. > > -- Isaac Asimov > > > Roel Schroeven- Hide quoted text - > > > - Show quoted text - > > Unfortunatly, in many of the companies I worked for, version control > software was not implemented. In some cases, where it was, it > actually inserted the comments into the header of the program as > described. In others, the software was so limited as to make it > useless. Fix that. That's usually something that's fairly easy to get done as a programmer (I've had to do it at 2 of the last 4 places I worked). Just go explain all the problems that can happen by not having VC and all the benefits it brings to your managers, and that there's a good free VC system that will work for everyone, and it'll likely become a mandate pretty quickly. It's almost certainly worth fixing that problem rather than mucking around with half-solutions. From kwitters at telenet.be Sat Mar 29 06:55:00 2008 From: kwitters at telenet.be (kwitters at telenet.be) Date: Sat, 29 Mar 2008 03:55:00 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? Message-ID: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> I don't know if this is the right place to discuss the death of <> in Python 3.0, or if there have been any meaningful discussions posted before (hard to search google with '<>' keyword), but why would anyone prefer the comparison operator != over <>??? I've written an article about it to try and save this nice "is not equal" operator, located at http://dewitters.koonsolo.com/python_neq.html Please set it straight in 3.0, and if not, convince me with a good reason of doing so, so that I can live with it and don't have to spend the rest of my life in 2.x ;). From timr at probo.com Mon Mar 3 01:14:15 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 03 Mar 2008 06:14:15 GMT Subject: Import, how to change sys.path on Windows, and module naming? References: Message-ID: <0o5ns35pusse2tqk33igkk727oattohhip@4ax.com> Jeremy Nicoll - news posts wrote: > >Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip >in their sys.path? What's the point of having a zip in the path? Starting with Python 2.4, Python is able to import modules directly from a zip, as if it were a directory. It's a very handy feature for distributing premade packages. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gherron at islandtraining.com Wed Mar 5 13:52:44 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 05 Mar 2008 10:52:44 -0800 Subject: Short confusing example with unicode, print, and __str__ In-Reply-To: <47CEDF77.5050501@andrew.cmu.edu> References: <47CEDF77.5050501@andrew.cmu.edu> Message-ID: <47CEEBFC.9010001@islandtraining.com> Gerard Brunick wrote: > I really don't understand the following behavior: > > >>> class C(object): > ... def __init__(self, s): self.s = s > ... def __str__(self): return self.s > ... > >>> cafe = unicode("Caf\xe9", "Latin-1") > >>> c = C(cafe) > >>> print "Print using c.s:", c.s > Print using c.s: Caf? > >>> print "Print using just c:", c > Print using just c: Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > >>> str(c) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > > Why would "print c.s" work but the other two cases throw an exception? > Any help understanding this would be greatly appreciated. > > Thanks in advance, > Gerard > It's the difference between how __str__ and __repr__ act on strings. Here's s simpler example >>> d=unicode("Caf\xe9", "Latin-1") >>> repr(d) "u'Caf\\xe9'" >>> str(d) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Gary Herron From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 5 07:12:51 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Mar 2008 13:12:51 +0100 Subject: Using re module better In-Reply-To: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> Message-ID: <47ce8e37$0$22806$426a74cc@news.free.fr> Mike a ?crit : > I seem to fall into this trap (maybe my Perl background) where I want > to simultaneously test a regular expression and then extract its match > groups in the same action. > For instance: > > if (match = re.search('(\w+)\s*(\w+)', foo)): > field1 = match.group(1) > field2 = match.group(2) > ... > > (compare to Perl:) > > if($foo =~ /(\w+)\s*(\w+)/) { > $field1 = $1; > $field2 = $2; > ... > } > > Problem is, my python is invalid above. What's the pythonic way to do > this? In your above use case, the solution is obvious: match = re.search('(\w+)\s*(\w+)', foo) if match: field1 = match.group(1) field2 = match.group(2) wrt/ assignement as an expression, this has been discussed about 2 days ago - look for a thread (badly) named "Is it possible to return a variable and use it...?" HTH From arnodel at googlemail.com Tue Mar 18 19:38:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 16:38:45 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> Message-ID: <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> On Mar 18, 3:59?pm, Ninereeds wrote: > Hrvoje Niksic wrote: > > This doesn't apply to Python, which implements dict storage as an > > open-addressed table and automatically (and exponentially) grows the > > table when the number of entries approaches 2/3 of the table size. > > Assuming a good hash function, filling the dict should yield amortized > > constant time for individual additions. Isn't this average constant time rather than amortized? > OK. I obviously need to look up open-addressed tables. I thought this > was just, in effect, implicit linked listing - ie it still needs a > linear search to handle collisions, it just avoids the need for > explicitly stored link fields. Perhaps I'm mistaken. I don't think you are mistaken, but if I'm wrong I'd be grateful for a link to further details. Thanks -- Arnaud From software at ginstrom.com Thu Mar 13 19:21:41 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 14 Mar 2008 08:21:41 +0900 Subject: Dispatch("Excel.Application") failed In-Reply-To: <84040989-8de9-42fb-ba08-6f1ee10566e0@s19g2000prg.googlegroups.com> References: <84040989-8de9-42fb-ba08-6f1ee10566e0@s19g2000prg.googlegroups.com> Message-ID: <075401c88560$ffcc68c0$0203a8c0@MOUSE> > On Behalf Of John Machin > > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > > None, None) > > Googling for 2147221005 gives some clues. > > That string of hex stuff appears where an error message is > expected -- it's not utf8, and makes no sense when I attempt > to decode it with cp1250 to cp1258 inclusive. If you start > IDLE and type: The hex stuff is Chinese. It appears to be a standard Windows error message. ???????? (Which I believe meaans "invalid class string") I wrote in another post (that doesn't appear to have made it to the list) that the call to Dispatch on Excel will fail if the formula bar edit box is active. Just another idea. Regards, Ryan Ginstrom From jeff at jmcneil.net Thu Mar 20 23:30:45 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 20 Mar 2008 23:30:45 -0400 Subject: An Application Program to Play a CD In-Reply-To: References: Message-ID: <82d28c40803202030s68f48ad7t40dcc8e11e4c0173@mail.gmail.com> I don't know of any Python specific stuff to do this, but have you looked at Asterisk? I know it's quite configurable and allows you to setup dial plans and route extensions and whatnot. http://www.asterisk.org/ That's probably a better fit. On 3/20/08, W. Watson wrote: > How difficult would it be to write a Python program that would play a > specific track on a CD from say 8 am to 6 pm each weekday on a PC's speaker, > and switch tracks each day? That is, what library capabilities might be able > to do that. Are they already available. > > Extra points. Now imagine the same as above, but the program should answer a > phone and play the track for the day while someone is holding the call, or > would be given the option to connect to the operator, say, or listen to the > recording? > > To get a bit specific, our science museum would like to buy the monthly set > of StarDate programs. Each program is about 2 minutes long and there's one > for every day of the month. There seems to be no such commercial software to > automate this process. > -- > Wayne Watson (Nevada City, CA) > > Web Page: > > -- > http://mail.python.org/mailman/listinfo/python-list > From duncan.booth at invalid.invalid Mon Mar 10 15:03:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2008 19:03:18 GMT Subject: Quality assurance in Python projects containing C modules References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: Stefan Behnel wrote: > Duncan Booth wrote: >> I would start by ensuring that any DLLs you write are written using >> Pyrex or Cython: almost always problems with C libraries called from >> Python are due to faulty reference counting but if you keep all of >> your Python related code in Pyrex/Cython modules the reference >> counting problem should be taken care of for you. You can call any >> required C/C++ code from the Cython code. > > I think the OP meant to use wxPython as an external module, in which > case he has no way of influencing the language it is implemented in. The OP mentioned 'two or three C libraries', so I assume wxPython is only part of the story. From mblume at freesurf.ch Sun Mar 2 11:55:52 2008 From: mblume at freesurf.ch (Martin Blume) Date: Sun, 2 Mar 2008 17:55:52 +0100 Subject: Problem with the strip string method References: Message-ID: <47cadc19$0$9036$5402220f@news.sunrise.ch> "Colin J. Williams" schrieb > The Library Reference has > strip( [chars]) > > Return a copy of the string with the > leading and trailing characters removed. ^^^^^^^^^^^^^^^^^^^^ It's "leading and trailing", not "leading, trailing or embedded". >>> "xxxaaaxxx".strip("x") 'aaa' >>> "xxxaaaxxxaaaxxx".strip("x") 'aaaxxxaaa' >>> HTH Martin From gagsl-py2 at yahoo.com.ar Fri Mar 28 18:19:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 19:19:23 -0300 Subject: Question regd downloading multipart mail using POP3 References: <118409.12220.qm@web50111.mail.re2.yahoo.com> Message-ID: En Fri, 28 Mar 2008 16:47:51 -0300, SPJ escribi?: > I am facing a strange problem when I am trying to retrieve multipart > mail from POP server with attachments. > The task is to write a script which will retrieve mail with specific > 'from' field. Get the subject, body and attachments if any and reuse > this info to send mail with different format to ticketing system. > > The global variable values I am expecting is: > msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so > on > attachmentList=[['none'],['attachname.txt','filename.pl']] > where none is no attachments. > > But the result I am getting is: > msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so > on > attachmentList=[[none],['none', 'attachname.txt', 'filename.pl']] > > An extra 'none' in the attachment list except for plain/text mails > without attachments. None is a special object in Python, 'none' is a string, and none is a name that may refer to anything. They're not the same thing. I would remove *all* Nones and nones and "none"s. An empty list is enough indication that there are no attachments, ok? > # regex for searching mails from example at example.com > soc = re.compile(".*example\@example.com.*") This regex may be too slow. Use soc = re.compile(r"example at example\.com") (note the r and the \. and lack of .* on both ends; also @ isn't a special character so it's not necesary to escape it) > if soc.match(check1): > subject = msg1.get('Subject') # Subject for only mails With the above reg.exp., use: if soc.search(check1): ... > if part.get_content_type() != ("text/html" or > "text/plain" or "multipart/alternative" or "multipart/mixed"): That's wrong. The () evaluate simply to "text/html". You surely want this: content_type = part.get_content_type() if content_type not in ["text/html", "text/plain", "multipart/alternative", "multipart/mixed"]: ... -- Gabriel Genellina From jaywgraves at gmail.com Mon Mar 10 10:53:05 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 10 Mar 2008 07:53:05 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <3df2b3f8-64ad-4102-8b60-95717e6748fe@o77g2000hsf.googlegroups.com> On Mar 10, 9:28 am, Robert Bossy wrote: > Personally, I'd use glob.glob: > > import os.path > import glob > > def parsefolder(folder): > path = os.path.normpath(os.path.join(folder, '*.py')) > lst = [ fn for fn in glob.glob(path) ] > lst.sort() > return lst > Why the 'no-op' list comprehension? Typo? ... Jay From john106henry at hotmail.com Mon Mar 31 14:32:35 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 11:32:35 -0700 (PDT) Subject: Of qooxdoo, qwt, and Python References: <28f7384f-b8d1-430d-9e0d-389ebae7eefd@e10g2000prf.googlegroups.com> <51c2f4c2-8752-49e3-81f8-77094c078015@k13g2000hse.googlegroups.com> Message-ID: <6087b21f-7f4b-4395-9502-3a39c991f925@d21g2000prf.googlegroups.com> olive wrote: > On 31 mar, 18:05, John Henry wrote: > > I was searching for a way to redevelop a desktop Pythoncard based > > program into a web-application. I understand what need to be done for > > all of the non-GUI code. For the GUI capabilities, I stumbled across > > a package call qooxdoo (http://qooxdoo.org/). It appears to provide > > the GUI capabilities I need. Then I saw that there is qwt - which > > allows you to write qooxdoo code in pure Java. Since I don't know > > Java (or don't want to know), is there a similar path I can take using > > Python? > > > > Regards, > > you could try this http://code.google.com/p/pyjamas/ > or http://doc.appcelerator.org/overview/what_is_appcelerator/index.html > or maybe jython with any java based toolkit (qwt, zk ...). > > Regards. Thanks for the reply. pyjamas looks promising because I believe seeing something from the qooxdoo site that there are similarities between qooxdoo and the google web development kit. Not sure about appcelerator. From tkpmep at gmail.com Sun Mar 30 16:54:50 2008 From: tkpmep at gmail.com (tkpmep at gmail.com) Date: Sun, 30 Mar 2008 13:54:50 -0700 (PDT) Subject: Dispatching functions from a dictionary Message-ID: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> To keep a simulation tidy, I created a dispatcher that generates random variables drawn from various distributions as follows: import random RVType = 1 #Type of random variable - pulled from RVDict RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), '3': random.gammavariate(1,1), '4': random.gauss(0,1), '5': random.lognormvariate(1,1), '6': random.paretovariate(1), '7': random.uniform( -1,1), '8': random.weibullvariate(1,2) } x = [] y=[] rv = RVDict[str(RVType)] for i in range(N): x.append(rv) y.append(rv) Oddly, x and y get filled with a single value repeated N times. I expected to get a different random number appear each time I called rv ,but this does not happen. Instead, my first call to rv generates a random number from the appropriate distribution, while subsequent calls simply repeat the random number generated in the first call. Where am I going wrong? Thanks in advance for your help. Sincerely Thomas Philips From Robert.Bossy at jouy.inra.fr Tue Mar 25 11:12:05 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 16:12:05 +0100 Subject: dynamically created names / simple problem In-Reply-To: <000c01c88e88$96c29490$0600a8c0@laptop> References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: <47E91645.4000706@jouy.inra.fr> Jules Stevenson wrote: > > Hello all, > > I'm fairly green to python and programming, so please go gently. The > following code > > for display in secondary: > > self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") > > Errors, because of the apparent nastyness at the beginning. What I?m > trying to do is loop through a list and create uniquely named wx > widgets based on the list values. Obviously the above doesn?t work, > and is probably naughty ? what?s a good approach for achieving this? > Hi, What you're looking for is the builtin function setattr: http://docs.python.org/lib/built-in-funcs.html#l2h-66 Your snippet would be written (not tested): for display in secondary: setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1, "checkbox_2")) RB From peter.bulychev at gmail.com Mon Mar 17 07:28:31 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Mon, 17 Mar 2008 14:28:31 +0300 Subject: question about module compiler: line numbers and positions of substring, which are covered by AST nodes In-Reply-To: References: Message-ID: I will answer my own question. Maybe it will be useful for someone else in future. Compiler module just transforms parse trees into the abstract syntax trees. Parse trees are built using Parser module. Parser module is not pure Python module, it is written in C language and Python loads it as .so (or .dll) library. There is a required field in C implementation of parse trees ( node.n_col_offset), but it is unaccessible from Python. Therefore to get the information about the position of some lexem in the AST built by module Compiler, you have to perform the following steps: *) Get the Python sources *) Modify the Parser module *) Build Python (or just parser.so) *) Drag the node.n_col_offset field to the Compiler module It should be noted that this solution will not be cross-platform. Good luck! 2008/3/16, Peter Bulychev : > > Hello. > > I use standard module Compiler to build ASTs of Python code. > > Given AST subtree I want to restore coordinates of substring in the input, > which is covered by the subtree. > > Example: > Suppose, the input is 'a+(b+c)'. It is parsed to the tree ADD(a, ADD(b,c)) > by module Compiler. > I want to have a function, which given ADD(b,c) will return the > coordinates of the substring '(b+c)'. > > Module Compiler provides only line numbers for each node. But even this > information is incorrect: only the first line of multi-lined statements is > stored. > > What is the easiest way of doing what I want? > As I understand, module Compiler is automatically generated by some parser > generator. Maybe I can modify it? > > -- > Best regards, > Peter Bulychev. -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Mar 17 15:20:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Mar 2008 15:20:25 -0400 Subject: how long do the different python-vm bytecodes take? References: <0555ed9f-c5f1-4d0b-afbd-439c863e9439@s13g2000prd.googlegroups.com> Message-ID: "GHUM" wrote in message news:0555ed9f-c5f1-4d0b-afbd-439c863e9439 at s13g2000prd.googlegroups.com... |I looked at the virtual machine bytecode of python programs: | | def f(whatever): | text="Hallo"+whatever | return text | | import dis | dis.dis(f) | 2 0 LOAD_CONST 1 ('Hallo') | 3 LOAD_FAST 0 (whatever) | 6 BINARY_ADD | 7 STORE_FAST 1 (text) | | 3 10 LOAD_FAST 1 (text) | 13 RETURN_VALUE | | | and now I am curious: how long does one LOAD_FAST take? I am thinking | of something like back in the assembler-world, where there existed | tables like: | | LDA -> 2 cycles | BNE -> 2 cycles, 3 on branch | | of course, the "real time" is dependand on many factors, esp. the | speed of the processor. | But ... is there a relative scale somewhere? | | Somehting like | | LOAD_CONST 1 arbitraryUnit | LOAD_FAST 1.9 arbitraryUnits | RETURN_VALUE 8.0 arbitraryUnits | | ??? | | my Google queries did not reveal anything usefull so far. Any hints? There is no such table that I know of and there hardly could be, as the relative times will depend on hardware, OS, C compiler (including optimization settings), as well as the objects on the stack to be operated on. Consider BINARY_ADD. Pretty fast for 2 ints, arbitrarily slow for arbitrary user-class objects. There are a few things knowns, such as _FAST versions being faster that other versions, and that eliminating unneeded codes is faster than not. Developers usually test proposed 'speedup' changes on several platforms. tjr From misterwang at gmail.com Tue Mar 18 21:35:54 2008 From: misterwang at gmail.com (Peter Wang) Date: Tue, 18 Mar 2008 18:35:54 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> <8fc48d27-1496-4240-a26c-708b6e9aa440@s8g2000prg.googlegroups.com> Message-ID: On Mar 18, 6:51 pm, Ivan Illarionov wrote: > > That's another new step for me. Any ideas where to start? > > http://docs.python.org/ext/simpleExample.html > > And look into the source of existing extensions. PIL and PyCairo are > the best in your situation. You shouldn't be afraid of doing raster graphics in Python; you'll just need to be familiar with Numpy. You can easily compose layers, mask out operations to only happen on one channel, etc., and code it all up in Python while getting C-level speed. The gotcha, if you use PIL, is that you're going to have to use tostring() and fromstring() to get the array data back and forth between numpy and PIL. An alternative is to use openGL, as others have suggested, and blit into a texture. If you use pyglet, for instance, you can use Andrew Straw's pygarrayimage module to convert a numpy array directly into a texture. I wouldn't recommend Cairo for doing pixel-level ops, since it is a vector graphics library. -Peter From NO_Kroeger at gmx.de Mon Mar 3 11:04:50 2008 From: NO_Kroeger at gmx.de (=?ISO-8859-1?Q?Nils_Oliver_Kr=F6ger?=) Date: Mon, 03 Mar 2008 17:04:50 +0100 Subject: Exception or not In-Reply-To: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> References: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Message-ID: <47CC21A2.6070705@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I don't think it is a good pattern because you are kind of mixing exceptions with return codes which makes the code a lot less readable later on. I personally would strongly opt for return codes in this case as one would intuitively expect a function named validateThisAndThat to return the result of a validation. This might me a simple true/false, a numeric code with 0=OK, 1=password not correct, 2=user does not exist or a string, whatever you need. In my opinion, such a function should raise an exception if it is unable to fullfill its task. For example lost connection to user database or things like that. A function should never propagate an expected result as an exception. Greetings Nils Monica Leko schrieb: | Suppose you have some HTML forms which you would like to validate. | Every field can have different errors. For example, this are the | forms: | | username | password | etc | | And you want to validate them with some class. Is this good pattern: | | class Foo(object): | def validateUsername(username): | if username isn't correct: | raise ValidationError() | def validatePassword(password): | if password isn't correct: | raise ValidationError() | | code: | try: | usernameError = validateUsername() | except ValidationError: | usernameError = error from exception | try: | passwordError = validatePassword() | except ValidationError: | passwordError = error from exception | | So, if there wasn't any errors, usernameError and passwordError both | contains None, and there was error, both contains some string? Should | I use exception or just return None or some string without | exception? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFHzCGhzvGJy8WEGTcRAvbGAJoDjn39xCmiOLmkc//0RTfeVXJFTACePRIG uYoDiQBZwRsShUn60LN/9oQ= =zvAY -----END PGP SIGNATURE----- From bignose+hates-spam at benfinney.id.au Sun Mar 2 16:31:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 03 Mar 2008 08:31:28 +1100 Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: <87bq5wak3z.fsf@benfinney.id.au> Kay Schluehr writes: > On 2 Mrz., 06:53, Ben Finney > wrote: > > > One of the stated goals of the migration is that the '2to3' > > program will only migrate Python 2.6 code -> Python 3.0 code. > > Yes, I know. Why? > > "The master said so" isn't an entirely satisfying answer. The people putting in the work to write '2to3' said so. -- \ "Courteous and efficient self-service." ?Caf? sign, southern | `\ France | _o__) | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 5 07:31:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Mar 2008 13:31:01 +0100 Subject: Altering imported modules In-Reply-To: References: Message-ID: <47ce9279$0$27486$426a34cc@news.free.fr> Tro a ?crit : > Hi, list. > > I've got a simple asyncore-based server. However, I've modified the asyncore > module to allow me to watch functions as well as sockets. The modified > asyncore module is in a specific location in my project and is imported as > usual from my classes. > > Now I'd like to use the tlslite library, which includes an asyncore mixin > class. However, tlslite imports "asyncore", which doesn't include my own > modifications. > > I'd like to know if it's possible to make tlslite load *my* asyncore module > without changing any of the tlslite code. Not sure this apply to your case (depends on how asyncore is implemented and the exact "modifications"), but monkeypatching is a possible solution. http://en.wikipedia.org/wiki/Monkey_patch http://wiki.zope.org/zope2/MonkeyPatch http://mail.python.org/pipermail/python-dev/2008-January/076194.html HTH From duncan.booth at invalid.invalid Thu Mar 20 09:42:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Mar 2008 13:42:22 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: >> By default Python on Windows allows you to open a file for reading >> unless you specify a sharing mode which prevents it: > > But the OP is talking about another process having opened the file for > WRITING, not reading. It's that other process that has exclusive access, > and the OP was trying to determine when it was safe to attempt opening > the file according to whether or not it was still growing. > No, unless the other process has specified that it wants exclusive access there is nothing stopping his process also opening the file. That's why he has to specify when he opens it that he wants exclusive access: then it doesn't matter what the other process does, he won't be able to open it until the other process has closed the file. This all of course assumes that the other process writes the file in one single atomic chunk. If it were to create it and then separately open and write to it then all bets are off. From nospam at nospam.com Mon Mar 31 09:33:10 2008 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 31 Mar 2008 15:33:10 +0200 Subject: wxPython; adding a grid to a panel References: Message-ID: On Mon, 31 Mar 2008 11:01:19 +0100, "Moynes James" wrote: >In the script below I have added two panels to a frame. I want to >display the grid in one panel (and later on add other widgets to the >other panel), but I cannot get the grid to display properly. I'm learning wxPython as well. Could it be that you're using wx.PySimpleApp instead of App? From davids at evertech.com.au Fri Mar 14 20:15:47 2008 From: davids at evertech.com.au (David S) Date: Sat, 15 Mar 2008 00:15:47 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: By mapping network drives in windows I can get past these issues with path names. Thanks, David "Tim Golden" wrote in message news:mailman.1949.1205496184.9267.python-list at python.org... > David S wrote: >> Gets me further but still seems to be issue with space after 'Program' as >> code tries to run 'C:\Program'. Don't understand what is going on here... > > Slight apologies as I haven't followed this thread closely, but using the > Acrobat Reader executable, which is, I think, good enough for the > purposes of illustration: > > > import os > import subprocess > > filename = r"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe" > doc = r"C:\Program Files\Adobe\Reader 8.0\Resource\ENUtxt.pdf" > > print os.path.isfile (filename) > > os.system (filename + " " + doc) > > os.system ('"%s" "%s"' % (filename, doc)) > > subprocess.call ([filename, doc]) > > > > os.path.isfile succeeds > os.system (filename) fails as your code does > os.system ('"%s"' ...) fails even though both strings are requoted > subprocess.call (filename) succeeds > > The latter, at least, is because the subprocess module > has some special-case handling for exactly this situation > on MS Windows, while os.system doesn't. > > Now, ultimately, I don't know if this really helps your > exact situation but it least it should be clear what will > and what won't work. Conclusion: use subprocess.call if > you can. > > TJG From zooko at zooko.com Tue Mar 25 22:41:10 2008 From: zooko at zooko.com (zooko) Date: Tue, 25 Mar 2008 19:41:10 -0700 Subject: announcing allmydata.org "Tahoe", the Least-Authority Filesystem, v1.0 Message-ID: <7FD79D75-5EFF-40AD-B958-95F1881B47EC@zooko.com> Folks: This open source project is written entirely in Python, except of course for the performance-intensive or system-integration parts that are written in C/C++ -- things like erasure coding and encryption. Python has served as well. It is elegant enough and simple enough, and the implementation is mature and efficient enough. And, there is a vast array of compatible, open-source tools and packages that work well with Python. The company that sponsors this open source project, http:// allmydata.com/ , opens its doors to new customers tomorrow, using Tahoe for its new storage grid. Regards, Zooko ANNOUNCING Allmydata.org "Tahoe", the Least-Authority Filesystem, v1.0 We are pleased to announce the release of version 1.0 of the "Tahoe" Least Authority Filesystem. The "Tahoe" Least Authority Filesystem is a secure, decentralized, fault-tolerant filesystem. All of the source code is available under a Free Software, Open Source licence (or two). This filesystem is encrypted and distributed over multiple peers in such a way it continues to function even when some of the peers are unavailable, malfunctioning, or malicious. A one-page explanation of the security and fault-tolerance properties that it offers is visible at: http://allmydata.org/source/tahoe/trunk/docs/about.html We believe that this version of Tahoe is stable enough to rely on as a permanent store of valuable data. The version 1 branch of Tahoe will be actively supported and maintained for the forseeable future, and future versions of Tahoe will retain the ability to read files and directories produced by Tahoe v1.0 for the forseeable future. This release of Tahoe will form the basis of the new consumer backup product from Allmydata, Inc. -- http://allmydata.com . This is the successor to Allmydata.org "Tahoe" Least Authority Filesystem v0.9, which was released March 13, 2008 [1]. Since v0.9 we've made the following changes: * Use an added secret for convergent encryption to better protect the confidentiality of immutable files, and remove the publically readable hash of the plaintext (ticket #365). * Add a "mkdir-p" feature to the WAPI (ticket #357). * Many updates to the Windows installer and Windows filesystem integration. Tahoe v1.0 produces files which can't be read by older versions of Tahoe, although files produced by Tahoe >= 0.8 can be read by Tahoe 1.0. The reason that older versions of Tahoe can't read files produced by Tahoe 1.0 is that those older versions require the file to come with a publically-readable hash of the plaintext, but exposing such a hash is a confidentiality leak, so Tahoe 1.0 does not do it. WHAT IS IT GOOD FOR? With Tahoe, you can distribute your filesystem across a set of computers, such that if some of the computers fail or turn out to be malicious, the filesystem continues to work from the remaining computers. You can also share your files with other users, using a strongly encrypted, capability-based access control scheme. Because this software is the product of less than a year and a half of active development, we do not categorically recommend it for the storage of data which is extremely confidential or precious. However, we believe that the combination of erasure coding, strong encryption, and careful engineering makes the use of this software a much safer alternative than common alternatives, such as RAID, or traditional backup onto a remote server, removable drive, or tape. This software comes with extensive unit tests [2], and there are no known security flaws which would compromise confidentiality or data integrity. (For all currently known security issues please see the Security web page: [3].) This release of Tahoe is suitable for the "friendnet" use case [4] -- it is easy to create a filesystem spread over the computers of you and your friends so that you can share files and disk space with one another. 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" 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.0. The Transitive Grace Period Public Licence says that you may distribute proprietary derived works of Tahoe without releasing the source code of that derived work for up to twelve months, after which time you are obligated to release the source code of the derived work under the Transitive Grace Period Public Licence. See the file "COPYING.TGPPL.html" for the terms of the Transitive Grace Period Public Licence, version 1.0. (You may choose to use this package under the terms of either licence, at your option.) INSTALLATION Tahoe works on Linux, Mac OS X, Windows, Cygwin, and Solaris. For installation instructions please see "docs/install.html" [5]. HACKING AND COMMUNITY Please join us on the mailing list [6] to discuss uses of Tahoe. Patches that extend and improve Tahoe are gratefully accepted -- the RoadMap page [7] shows the next improvements that we plan to make and CREDITS [8] lists the names of people who've contributed to the project. The wiki Dev page [9] contains resources for hackers. SPONSORSHIP Tahoe is sponsored by Allmydata, Inc. [10], a provider of consumer backup services. Allmydata, Inc. contributes hardware, software, ideas, bug reports, suggestions, demands, and money (employing several allmydata.org Tahoe hackers and instructing them to spend part of their work time on this free-software project). We are eternally grateful! Zooko O'Whielacronx on behalf of the allmydata.org team March 25, 2008 San Francisco, California, USA [1] http://allmydata.org/trac/tahoe/browser/relnotes.txt?rev=2315 [2] http://allmydata.org/trac/tahoe/wiki/Dev [3] http://allmydata.org/trac/tahoe/wiki/Security [4] http://allmydata.org/trac/tahoe/wiki/UseCases [5] http://allmydata.org/source/tahoe/trunk/docs/install.html [6] http://allmydata.org/cgi-bin/mailman/listinfo/tahoe-dev [7] http://allmydata.org/trac/tahoe/roadmap [8] http://allmydata.org/trac/tahoe/browser/CREDITS?rev=2345 [9] http://allmydata.org/trac/tahoe/wiki/Dev [10] http://allmydata.com From patricksamal at googlemail.com Thu Mar 20 07:55:35 2008 From: patricksamal at googlemail.com (patricksamal at googlemail.com) Date: Thu, 20 Mar 2008 04:55:35 -0700 (PDT) Subject: Games, Software, Disk Storege and other are totally Free , Free ...................... Message-ID: <3a15f41d-ff33-44b9-98d4-ce4917b5e6a7@i12g2000prf.googlegroups.com> In exchange for having their Internet browsing and purchasing activity observed, members have access to free software downloads and other benefits including: * Free online disk storage * Free software to password protect important documents and folders * Free software to help maintain online privacy * Over 450 free online games * Free screensavers * Free sweepstakes entries * Points redeemable for merchandise and gift cards Membership is free and members' personal information will remain confidential in accordance with our privacy policy. http://www.kqzyfj.com/click-1944618-10402121 http://www.kqzyfj.com/click-1944618-10462173 From castironpi at gmail.com Tue Mar 4 22:50:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 19:50:56 -0800 (PST) Subject: multiplication of lists of strings References: Message-ID: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> On Mar 4, 9:46?pm, Jason Galyon wrote: > Gabriel Genellina wrote: > > En Tue, 04 Mar 2008 23:50:49 -0200, Jason escribi?: > > >> How could I return a list or tuple of each unique combination of a given > >> set of lists (perhaps from a dict or a list). ?This means the number of > >> lists are not known nor is the length of each. > > > Use the Google interfase for this group: > >http://groups.google.com/group/comp.lang.python/ > > Type "unique combinations lists" in the text box; press "Search in this > > group". The very first result contains some answers to your question. > > found it, the referenced cookbook recipe is perfect. > > Thanks, Gabriel That reminds me: Is there a generic 'relation' pattern/recipie, such as finding a computer that's "paired" with multiple users, each of who are "paired" with multiple computers, without maintaining dual- associativity? Good: py> user.getcomputers() [ Compie1, Compie2 ] Bad: user._computers.add( compieN ) compieN._users.add( user ) ? From Glich.Glich at googlemail.com Mon Mar 24 12:37:04 2008 From: Glich.Glich at googlemail.com (Glich) Date: Mon, 24 Mar 2008 09:37:04 -0700 (PDT) Subject: python, dbus and pointers help. Message-ID: <16059cb8-a182-40ff-9617-a8b6708e1183@s19g2000prg.googlegroups.com> ''' hello, using pidgin instant messenger I can get the value of 'message' when one is being sent but, I dont know how to chage the value of message. from the documentation (http://developer.pidgin.im/doxygen/dev/html/ conversation-signals.html#sending-im-msg): _____________________________ sending-im-msg: Emitted before sending an IM to a user. message is a pointer to the message string, so the plugin can replace the message before being sent. _____________________________ I think python get's a copy of the message (this is just a guess). How can I change the message before it is sent? Thanks. The code is taken from http://developer.pidgin.im/wiki/DbusHowto#Furtherreading and changed only a small amount. ''' #!/usr/bin/env python def cb_func(account, rec, message): #change message here somehow? print message import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() bus.add_signal_receiver(cb_func, dbus_interface="im.pidgin.purple.PurpleInterface", signal_name="SendingImMsg") loop = gobject.MainLoop() loop.run() From r&d2 at dave-tech.it Sat Mar 22 09:48:22 2008 From: r&d2 at dave-tech.it (llandre) Date: Sat, 22 Mar 2008 14:48:22 +0100 Subject: [RFC] How to implement command line tool integrating parsing engine Message-ID: <47E50E26.8090704@dave-tech.it> Hi all, I'd like to have some advices about how to implement a program that has the following requirements: - it must run both on linux and windows PC - it must interact with an electronic device connected to the PC through serial cable by sending/receiving some command strings and taking different actions depending on device responses; these strings and actions must be described in a text file (a sort of script) editable by user with a simple text editor; the language used to described this algorithm should be as simple as possible - initially the program must be written in the form of simple command line tool that is invoked like this: program - in the future, it must be possible to develop a graphical frontend on top of it; the resulting look&feel should be similar on linux and windows. In this mailing list I was adviced to use python: http://thread.gmane.org/gmane.comp.boot-loaders.u-boot/37939 As I never used python, I ask you: 1) about the script file, which language - for which a parsing engine is already available in python - do you suggest? 2) about the graphical frontend, which graphical libraries do you recommend? Thanks a lot in advance, llandre DAVE Electronics System House - R&D Department web: http://www.dave.eu email: r&d2 at dave-tech.it From jeff at schwabcenter.com Wed Mar 19 00:03:16 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 21:03:16 -0700 Subject: ftp recursively In-Reply-To: References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: Gabriel Genellina wrote: > En Tue, 18 Mar 2008 18:25:28 -0300, Jeff Schwab > escribi?: > >> I need to move a directory tree (~9GB) from one machine to another on >> the same LAN. What's the best (briefest and most portable) way to do >> this in Python? > > See Tools/scripts/ftpmirror.py in your Python installation. Thank you, that's perfect. Thanks to Arnaud as well, for the pointer to ftplib, which might useful for other purposes as well. Per the earlier advice of other posters (including one whose message seems mysteriously to have disappeared from c.l.python), I just stuck with the Unix tools I already knew: I ended up tarring the whole 9GB, ftping it as a flat file, and untarring it on the other side. Of course, the motivation wasn't just to get the files from point A to point B using Unix (which I already know how to do), but to take advantage of an opportunity to learn some Python; next time, I'll try the ftpmirror.py script if it's generic enough, or ftplib if there are more specific requirements. From Jeff.Goldfinkle at gmail.com Thu Mar 6 02:21:07 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Wed, 5 Mar 2008 23:21:07 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: On Mar 5, 11:27 pm, Mensanator wrote: > On Mar 5, 2:25 pm, "Jeff.Goldfin... at gmail.com" > > wrote: > > Hi All > > > Is there a simple way to twiddle the bits of a float? In particular, I > > would like to round my float to the n most significant bits. > > > For example - 0.123 in binary is 0.000111111 > > Rounding to 4 bits I get 0.0001. > > > I can pack and unpack a float into a long > > e.g. > > struct.unpack('I',struct.pack('f',0.123))[0] > > but then I'm not sure how to work with the resulting long. > > > Any suggestions? > > Here's one. > > >>> import gmpy > > # create a base 10 float>>> f = gmpy.mpf('123.456') > >>> f > > mpf('1.23456e2') > > # format in base 2, fixed point>>> f2 = gmpy.fdigits(f,2,0,0,99) > >>> f2 > > '1111011.01110100101111000110101001111110111110011101101100100010111' > > # seperate the characteristic from the mantissa > > >>> fs = f2.split('.') > > # re-assemble with the mantissa truncated to desired # of bits>>> f3 = fs[0]+'.'+fs[1][:4] > >>> f3 > > '1111011.0111' > > # convert the string back to a base 10 float>>> f4 = gmpy.mpf(f3,0,2) > >>> print f4 > > 123.4375 > > # check: print as base 2 and see how many digits are past radix point>>> print gmpy.fdigits(f4,2,0,0,99) > > 1111011.0111 excellent - thanks that does exactly what I need. From aboudouvas at panafonet.gr Sat Mar 29 10:16:50 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 29 Mar 2008 07:16:50 -0700 (PDT) Subject: Psyco alternative References: <10d4e6b6-71f3-4c22-8b13-17dd32a4374f@c19g2000prf.googlegroups.com> Message-ID: On 29 ???, 16:03, Luis M. Gonz?lez wrote: > On 27 mar, 13:14, king kikapu wrote: > > > > One reason attention is going to PyPy instead of Psyco... > > > > Jean-Paul > > > I had a look at PyPy, it, indeed, have a very long way to go so we can > > consider it an alternative. > > To see how it?s going, you can check this out:http://morepypy.blogspot.com/ Thanks, that is my source already! From pavlovevidence at gmail.com Thu Mar 6 22:39:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 19:39:45 -0800 (PST) Subject: Looking for very light weight template library (not framework) References: Message-ID: On Mar 6, 8:56 pm, "Malcolm Greene" wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated. You could do something like this with a single function. For instance: import re def apply_template(text,env): def eval_in_env(m): return str(eval(m.group(1),env)) return re.sub(r"{{(.*?)}}",eval_in_env,text) Where env is a dict with the variables you want to evaluate (locals() could be a good choice for this). Standard warning about usage of eval: don't use this with untrusted input or Bad Things can happen. Carl Banks From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 13 04:31:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Mar 2008 09:31:09 +0100 Subject: Class Inheritance In-Reply-To: References: Message-ID: <47d8e611$0$14050$426a74cc@news.free.fr> Andrew Rekdal < a ?crit : > I am trying to bring functions to a class by inheritance... for instance in > layout_ext I have.. > > > --- layout_ext.py--------- > class Layout() > def...some function that rely on css in Layout.py It shouldn't, definitively. The Layout instance should have a reference on the CSS instance, ie: # layout_ext.py class LayoutExt(object): def __init__(self, css): self.css = css def some_function(self): do_something_with(self.css) # layout.py from layout_ext import LayoutExt from CSS import CSS class Layout(LayoutExt): def __init__(self, css): LayoutExt.__init__(self, css) # etc > def... > > ---EOF-- > > in the main application file I have... > ----Layout.py--- > from layout_ext import Layout > from CSS import CSS > css = CSS() > class Layout(Layout) You will have a problem here - this class statement will shadow the Layout class imported from layout_ext. Remember that in Python, def and class statements are executed at runtime and that they bind names in current namespace - here, the 'class Layout' statement rebinds the name 'Layout' in the Layout module's namespace. > def __init__ > more code..... > > ----EOF---- > > > Problem is layout_ext and Layout code is dependant on a Class instance > 'css'. Whenever the CSS instance it parses a file, this means that I would > have to parse the file twice?? Why is this? Can I do something like pass an > already created instance to the import? Wrong solution, obviously. cf above for the most probably correct one. HTH From steve at REMOVE-THIS-cybersource.com.au Sat Mar 22 19:48:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 22 Mar 2008 23:48:35 -0000 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <3ee39d9f-dde7-432b-bc3c-5b8dd935e3f4@a70g2000hsh.googlegroups.com> Message-ID: <13ub6mjkfu4dkf6@corp.supernews.com> On Sat, 22 Mar 2008 16:16:03 -0700, bearophileHUGS wrote: > bearophile: >> A more computer-friendly (and Pythonic) syntax may be ('are' is a >> keyword): > > Sorry for causing confusion, I was just thinking aloud. English isn't my > first language, and sometimes I slip a bit. There is nothing wrong with what you said originally. You said "syntax MAY be" -- that's obvious to those who know English that you are talking about a hypothetical keyword. Admittedly non-English speakers may not pick up on the nuances of English, but that's not your fault. Your English is very good, better than some native English speakers. What is your native language? -- Steven From fn681 at ncf.ca Thu Mar 6 18:06:40 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Thu, 06 Mar 2008 18:06:40 -0500 Subject: Internet Explorer 8 beta release In-Reply-To: References: Message-ID: shsha wrote: > Internet Explorer 8 beta release is for developers, and Microsoft's > Dean Hachamovitch promised at MIX08 that IE8 will make it easier to > build Web sites for multiple browsers and stop wasting developers' > time. Microsoft's IE8 features Activities for looking up information > and Webslices to watch portions of Web sites for updates. > > more about MS > > http://www.toptechnews.com/story.xhtml?story_id=0120013PBF8O > > _____________ > get wild ....all the action http://www.getaction4ever.com Isn't compliance with the W3C standard the best way of achieving multiple browser rendering? Colin W. From nospam at nospam.com Wed Mar 12 03:20:16 2008 From: nospam at nospam.com (Gilles Ganault) Date: Wed, 12 Mar 2008 08:20:16 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <99cd$47d66262$83aef404$29936@news1.tudelft.nl> Message-ID: <5u0ft3tqf835s4fcj9mmhp5jjn6mtvb1us@4ax.com> On Tue, 11 Mar 2008 11:43:45 +0100, Stef Mientki wrote: >Funny, compared to Delphi-7, >I found the grid in wxPython much richer ;-) You haven't tried the better alternatives I had in mind: http://www.x-files.pl http://www.bergsoft.net http://www.tmssoftware.com http://www.scalabium.com/smdbgrid.htm http://www.tkweb.eu/en/delphicomp/kgrid.html http://www.devexpress.com/Products/VCL/ExQuantumGrid/ From troworld at gmail.com Thu Mar 6 15:29:05 2008 From: troworld at gmail.com (Tro) Date: Thu, 6 Mar 2008 15:29:05 -0500 Subject: Altering imported modules In-Reply-To: <47ce9279$0$27486$426a34cc@news.free.fr> References: <47ce9279$0$27486$426a34cc@news.free.fr> Message-ID: <200803061529.05268.troworld@gmail.com> On Wednesday 05 March 2008, Bruno Desthuilliers wrote: > Tro a ?crit : > > Hi, list. > > > > I've got a simple asyncore-based server. However, I've modified the > > asyncore module to allow me to watch functions as well as sockets. The > > modified asyncore module is in a specific location in my project and is > > imported as usual from my classes. > > > > Now I'd like to use the tlslite library, which includes an asyncore mixin > > class. However, tlslite imports "asyncore", which doesn't include my own > > modifications. > > > > I'd like to know if it's possible to make tlslite load *my* asyncore > > module without changing any of the tlslite code. > > Not sure this apply to your case (depends on how asyncore is implemented > and the exact "modifications"), but monkeypatching is a possible solution. > > http://en.wikipedia.org/wiki/Monkey_patch > http://wiki.zope.org/zope2/MonkeyPatch > http://mail.python.org/pipermail/python-dev/2008-January/076194.html Ooh. I didn't know this technique had a name. But that's basically how I'm modifying the built-in asyncore in my own class. I override its poll() and poll2() methods to do something extra. However, the issue with tlslite is that it imports the regular asyncore instead of the one I wrote, which means that I'd have to somehow monkeypatch its "import" statement. I'm guessing that means simply monkeypatching both the original asyncore module AND the tlslite module's asyncore attribute with my own version. Thanks, Tro From matthias.goetz.23 at googlemail.com Sat Mar 22 17:37:45 2008 From: matthias.goetz.23 at googlemail.com (=?ISO-8859-1?Q?Matthias_G=F6tz?=) Date: Sat, 22 Mar 2008 22:37:45 +0100 Subject: Problem with complex numbers Message-ID: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> Hello python fans, I have a small problem using python and complex math. The pow(complex,complex) function in the windows python version doesn't have the same semantic as the source version. (I have downloaded : - Python 2.5.2 compressed source tarball(for Unix or OS X compile) - Python 2.5.2 Windows installer ) If found in Complex.py: def __pow__(self, n, z=None): if z is not None: raise TypeError, 'Complex does not support ternary pow()' if IsComplex(n): if n.im: if self.im: raise TypeError, 'Complex to the Complex power' else: return exp(math.log(self.re)*n) n = n.re r = pow(self.abs(), n) phi = n*self.angle() return Complex(math.cos(phi)*r, math.sin(phi)*r) which mean for example if i calculate z1 power z2 (z1,z2 are complex numbers), and z1 and z2 has imaginary parts not equals zero, i must get an TypeError. Is that right? But i tried that in the IDLE python shell by doing this >>> z1=complex(1,2) >>> z2=complex(2,3) >>> z1**z2 (-0.01513267242272265-0.1798674839133349j) >>> and this is everything unlike an TypeError. So if somebody can help me, it would be nice. Thanks. Matze (Sorry for bad english, I'am german) -------------- next part -------------- An HTML attachment was scrubbed... URL: From danb_83 at yahoo.com Tue Mar 25 22:30:05 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 25 Mar 2008 19:30:05 -0700 (PDT) Subject: python hash() function References: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Message-ID: <68f6845a-f499-4527-a744-cd7c447f7aab@e6g2000prf.googlegroups.com> On Mar 25, 9:22 pm, "Terry Reedy" wrote: > "Alvin Delagon" wrote in message > > news:7a01f6c00803251905j4b12633m65b2cde0f3037854 at mail.gmail.com... > | Hello, > | > | >>> hash("foobar") > | -1969371895 > | > | Anyone can explain to me how the hash() function in python does its work? > A > | link to its source could help me a lot also. I'm looking for a way to > | replicate this function in php. Thanks in advance. > > If not part of your installation, start with svn.python.org and click > browse. I would look for builtins.c or somesuch. It's in stringobject.c: static long string_hash(PyStringObject *a) { register Py_ssize_t len; register unsigned char *p; register long x; if (a->ob_shash != -1) return a->ob_shash; len = Py_Size(a); p = (unsigned char *) a->ob_sval; x = *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= Py_Size(a); if (x == -1) x = -2; a->ob_shash = x; return x; } From michael.wieher at gmail.com Fri Mar 7 09:23:28 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 08:23:28 -0600 Subject: hidden built-in module In-Reply-To: <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> Message-ID: 2008/3/7, koara : > > On Mar 5, 1:39 pm, gigs wrote: > > koara wrote: > > > Hello, is there a way to access a module that is hidden because > > > another module (of the same name) is found first? > > > > > More specifically, i have my own logging.py module, and inside this > > > module, depending on how initialization goes, i may want to do 'from > > > logging import *' from the built-in logging. > > > > > I hope my description was clear, cheers. > > > > > I am using python2.4. > > > > you can add your own logging module in extra directory that have > __init__.py and > > import it like: from extradirectory.logging import * > > > > and builtin: from logging import * > > > Thank you for your reply gigs. However, the point of this namespace > harakiri is that existing code which uses 'import logging' ... > 'logging.info()'... etc. continues working without any change. > Renaming my logging.py file is not an option -- if it were, i wouldn't > bother naming my module same as a built-in :-) > > Cheers. > > -- > http://mail.python.org/mailman/listinfo/python-list > I've never had a problem like this, but I'd imagine that you could delve into the inner-workings of import itself and figure a way to make this happen. There's probably a logical-order search path it follows, and if you can find a way to insert your module before the other, in that path, or modify the path and point its first entry at say, a directory containing only your module, you'd be in business. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sat Mar 8 21:36:20 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 8 Mar 2008 18:36:20 -0800 Subject: Green's Function In-Reply-To: <501978.67770.qm@web53602.mail.re2.yahoo.com> References: <501978.67770.qm@web53602.mail.re2.yahoo.com> Message-ID: > I am new to Python and trying to solve the Hamiltonian of a linear chair > of atoms using green's function. > Does anyone know any pre-existing library functions and literature that > could be helpful? You might find this helpful: http://scipy.org/ HTH, Daniel From waltbrad at hotmail.com Mon Mar 17 13:52:52 2008 From: waltbrad at hotmail.com (waltbrad) Date: Mon, 17 Mar 2008 10:52:52 -0700 (PDT) Subject: questions about named pipe objects... References: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> Message-ID: On Mar 17, 1:50 pm, waltbrad wrote: > > I then wanted to start the child process first and see what happened > when I ran the parent. Well that works but the reads come out in > random order. Well, I take that back. I accidentally had two 'parent' processes open. So, the reads were sequential but split between two windows. From deets at nospam.web.de Thu Mar 27 05:34:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 10:34:59 +0100 Subject: subtract dates with time module References: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> Message-ID: <65182uF2e0id5U2@mid.uni-berlin.de> barronmo wrote: > I'm trying to get the difference in dates using the time module rather > than datetime because I need to use strptime() to convert a date and > then find out how many weeks and days until that date. I'm a beginner > so any help would be appreciated. Here is the code: Use strptime to create time-tuples, and use the fields in there to create datetime-objects. Then do the math with them. Diez From bbxx789_05ss at yahoo.com Fri Mar 21 00:17:36 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 20 Mar 2008 21:17:36 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0] References: <7xy78dg79e.fsf@ruckus.brouhaha.com> Message-ID: On Mar 20, 8:42?pm, "Terry Reedy" wrote: > "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message > > news:7xy78dg79e.fsf at ruckus.brouhaha.com... > | "Daniel Fetchinson" writes: > | > Is it just me or others also think that it would be a major loss to > | > remove tkinter from the python core? > | > | That would be terrible. ?Every time I've tried to use one of the other > | packages it has led to installation hell. ?Tkinter isn't great, but > | it's extremely useful to have a gui module that's present > | automatically in every compete Python installation and that is > | reasonably cross platform. ?I can write a Python/Tkinter app under > | Linux and send it to Windows users and they can run it after a single, > | very simple Python installation from the Windows .msi. ?I have no > | Windows development tools whatsoever and very limited access to > | Windows boxes, so any Python code I deploy on Windows can't rely on > | any non-Python code outside of the stdlib. > | > | Also, because of tkinter's inherent limitations, I have the impression > | that upgrading it to the latest and greatest tcl/tk release wouldn't > | improve it much over the useful but low-rent module that it already is. > | Therefore, that supposed "benefit" of splitting it out to an external > | package is not much of a benefit. > | > | One of Python's traditionally best attractions has been the depth of > | its standard libraries, and backing away from that would be plain > | self-destructive. ?Python needs more stuff in its stdlib, not less. > | If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard > | distro. ?If that happens (i.e. some new toolkit is brought in and > | declared to be the standard) then it might be ok to drop Tkinter but > | it certainly shouldn't be dropped without a replacement. > > I think this nicely summarizes the case against dropping tkinter (and > indeed, the case against shrinking the stdlib), like some devs (who mostly > une *nix) want to do. ?Perhaps someone can forward it to the lib-sig and/or > the Py3-devel lists. > > tjr I think one of the advantages that python has over ruby is that python comes with tkinter. For me, tkinter worked from the get go after I installed python. I don't know if that's because my os already had the necessary tcl/tk framework set up or not, but not having to go through installation hell to get it working was nice. On the other hand, Ruby doesn't come with a gui framework. And trying to get Ruby tk working is a nightmare that I suspect many new programmers will never accomplish, and therefore gui programming will largely be inaccessible to them. Since the adherents to the various languages like to list the reasons why their language is better, removing tkinter from python will only will make python's list shorter. From Lie.1296 at gmail.com Sun Mar 9 05:25:24 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 01:25:24 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> On Mar 9, 3:27?am, castiro... at gmail.com wrote: > To Lie: > > > Personally I preferred a code that has chosen good names but have > > little or no comments compared to codes that makes bad names and have > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > I won't like it, it's that I can't. ?You know, in linguistics, there's > what's called 'code switching', which is switching between two > languages you know midstream. ?People can understand 'hear' a language > but not speak it. ?If you speak it, . ?If comments aren't > the 'short version', then patience is the problem. ?There's not one > word for lots and lots of things. ?Examples on backorder. But I much prefer it that the code has good names AND concise comments, not too short and not too long that it becomes obscure. If the code is complex, that it's hard to explain in a few sentences, it might be a good idea to refactor it. If I have to choose between bad names + twenty pages of documentation and good names + a paragraph of short documentation, I chose the latter. From sam at mas.pl Mon Mar 10 10:47:26 2008 From: sam at mas.pl (sam) Date: Mon, 10 Mar 2008 15:47:26 +0100 Subject: parsing directory for certain filetypes In-Reply-To: References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: Robert Bossy napisa?(a): > I leave you the exercice to add .doc files. But I must say (whoever's > listening) that I was a bit disappointed that glob('*.{txt,doc}') didn't > work. "{" and "}" are bash invention and not POSIX standard unfortunately -- UFO Occupation www.totalizm.org From castironpi at gmail.com Thu Mar 27 17:45:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 14:45:10 -0700 (PDT) Subject: Determine size of string in bytes References: <083180d3-3e7c-4db5-926f-b7528201a3b8@a22g2000hsc.googlegroups.com> Message-ID: <1677c156-f439-4999-ad4a-0e53776fb21a@s37g2000prg.googlegroups.com> On Mar 27, 4:10?pm, John Machin wrote: > On Mar 28, 6:45 am, breal wrote: > > > Forgive me for this question which is most likely stupid... > > The contents of your question are not stupid. The subject however does > invite a stupid answer like: len(the_string). > > Disclaimer: I know nothing about SOAP except that it's usually > capitalised :-) Now read on: > > > How do I determine the number of bytes a string takes up? ?I have a > > soap server that is returning a serialized string. > > Serialised how? UTF-8? > > > ?It seems that when > > the string goes over 65978 characters it does not return to the soap > > client. > > Why does it seem so? How did you arrive at such a precise limit? > > > ?Instead I get an error: > > error: (35, 'Resource temporarily unavailable') > > Is this error from the client or the server? Any error or logfile > record from the other side? > > Is there anything in the documentation about maximum sizes? > > > > > This makes me think the problem exists on the soap client side with > > some sort of max return length. > > Think? Can't you verify this by inspecting the source? > > > If I knew how many bytes the 65978 > > character string was, then I could try to up this value. > > How do you know the string is 65978 characters? If you are debugging > the server, can't you do len(serialise(the_65978_char_string))? > > 65978? Are you sure? Looks suspiciously close to 65535 aka 0xFFFF aka > (2 ** 16 - 1 ) to me. > > If you have the server, you presumably have the source code for both > client and server. Some options for you: > > (1) Look at the traceback(s), look at the source code, nut it out for > yourself. If there is some kind of max other than an implicit 16-bit > limitation in the client code, it shouldn't be too hard to find. > > (2) Post the traceback(s) here, along with other details that might be > useful, like what SOAP server s/w you are using, what version of > Python, what platform. I'm dying to find out. From bignose+hates-spam at benfinney.id.au Fri Mar 21 17:22:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 22 Mar 2008 08:22:10 +1100 Subject: How can I make a function equal to 0? References: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Message-ID: <87eja3wz5p.fsf@benfinney.id.au> Martin Manns writes: > I do not want the function to return 0 but to equal 0. Then it seems you don't want a function, but something else. Functions are functions, not integers. What problem are you trying to solve, and why do you think this behaviour will help? -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but 'apply North Pole' to what?" -- _Pinky and The | _o__) Brain_ | Ben Finney From deets at nospam.web.de Mon Mar 17 06:09:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 11:09:27 +0100 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> Message-ID: <646uapF2at163U1@mid.uni-berlin.de> cokofreedom at gmail.com wrote: >> >>> a = 1 >> >>> b = 1 >> >>> a is b >> True >> >>> id(a) >> 10901000 >> >>> id(b) >> 10901000 > > Isn't this because integers up to a certain range are held in a single > memory location, thus why they are the same? As the OP said: Depending on implementation, for immutable types, operations that compute new values may or may not actually return a reference to any existing object with the same type and value, while for mutable objects this is (strictly)? not allowed. Which is exactly what happens - the actual implementation chose to cache some values based on heuristics or common sense - but no guarantees are made in either way. Diez From falk at green.rahul.net Tue Mar 25 01:09:58 2008 From: falk at green.rahul.net (Edward A. Falk) Date: Tue, 25 Mar 2008 05:09:58 +0000 (UTC) Subject: Does python hate cathy? References: Message-ID: Interestingly, if you change swaroop = Person('Swaroop', 'M') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam', 'M') kalam.sayHi() kalam.howMany() cathy = Person('Catherine', 'F') cathy.sayHi() cathy.howMany() swaroop.sayHi() swaroop.howMany() to def main(): swaroop = Person('Swaroop', 'M') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam', 'M') kalam.sayHi() kalam.howMany() cathy = Person('Catherine', 'F') cathy.sayHi() cathy.howMany() swaroop.sayHi() swaroop.howMany() return 0 if __name__ == "__main__": sys.exit(main()) The problem goes away. (This is a good coding practice in any event.) As others have pointed out, the order in which local variables are deleted is undefined. It looks to me as if the class Person got deleted before Catherine did. Adding del kalam del cathy del swaroop to the end of the program did fix the problem, presumably by forcing kalam, cathy, and swaroop from being deleted before Person. However, Adding self.myclass = Person to the __init__() method didn't stop the problem. I thought it might, because then each of the objects would have held a reference to Person. Actually, I would have thought they'd hold a reference by merely existing, so is this not a bug? -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From gagsl-py2 at yahoo.com.ar Wed Mar 26 19:16:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 20:16:10 -0300 Subject: How to convert latex-based docs written with Python 2.5 to 2.6 framework References: Message-ID: En Wed, 26 Mar 2008 16:37:21 -0300, Michael Str?der escribi?: > I had a look on how Doc/ is organized with Python 2.6. There are files > with > suffix .rst. Hmm... > > I'm maintaing existing docs for python-ldap which I might have to > convert to > the new concept in the long run. What's the recommended procedure for > doing > so? Any pointer? Ask in the doc-sig mailing list. I'm sure there are some tools to help converting latex->rst http://mail.python.org/mailman/listinfo/doc-sig -- Gabriel Genellina From mensanator at aol.com Sun Mar 2 16:19:12 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 2 Mar 2008 13:19:12 -0800 (PST) Subject: sympy: nifty, but... (was: How about adding rational fraction to Python?) References: <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> Message-ID: On Mar 1, 12:29?pm, "Anand Patil" wrote: > Not sure if this is common knowledge yet but Sympy,http://code.google.com/p/sympy, has a rational type. I hadn't heard of this before, thanks for the link. Very nifty, lots of goodies not found in gmpy (although it seems to lack a modular inverse function and the linear congruence solver that can be derived from it making it of no value to me). Alas, it's written in Python. Who writes a math library in Python? Nevertheless, I thought I would try out the Rational numbers. Once I figured out how to use them, I converted my Polynomial Finder by Newton's Forward Difference Method program to use sympy instead of gmpy. I have a test case where I create 1 66 degree polynomial where the coefficients are large rationals. The polynomial was calculated flawlessly ## sympy ## Term0: [66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, 0] ## ## Seq: [66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66] ## ## The Polynomial: ## ## ## 1 ## ------------------------------------------------------------------------------------------- * n**66 ## 8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000 ## ## ## -67 ## ------------------------------------------------------------------------------------------ * n**65 ## 249928805820680929294641524448045340975341168222589014937034034375422902272000000000000000 ## ## ## 67 ## --------------------------------------------------------------------------------------- * n**64 ## 230703513065243934733515253336657237823391847590082167634185262500390371328000000000000 But because they are calculated using Python, it took 175 seconds compared to 0.2 seconds for gmpy to do the same polynomial. So, I'll keep it around for it's neat features that gmpy doesn't have, but it won't replace gmpy for any serious work. > > In [2]: from sympy import * > > In [3]: Rational(21,4) > Out[3]: 21/4 > > In [4]: Rational(21,4)+Rational(3,4) > Out[4]: 6 From timr at probo.com Wed Mar 19 03:26:34 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Mar 2008 07:26:34 GMT Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: Gowri wrote: > >I have a service running somewhere which gives me JSON data. >... >This prints a whole bunch of nonsense as expected. It's not nonsense. It's JSON. >I use cjson and am >unable to figure out how to print this json response You are already printing the JSON response. That's what that script does. >and I guess if I >can do this, parsing should be straightforward? doing a >cjson.decode(str(repsonse)) does not work. If response.read() returns the JSON string, as you show above, one might expect cjson.decode(response.read()) to parse it. Have you read the cjson documentation? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From duvo at tiscali.it Sun Mar 9 16:58:28 2008 From: duvo at tiscali.it (duccio) Date: Sun, 09 Mar 2008 21:58:28 +0100 Subject: __iter__ yield Message-ID: Hello! Someone knows if it's possible to make this __iter__ function with just one 'yield' intead of two? Is there some simpler way to make this __iter__ iter through all nodes? Thanks! class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): return '<'+str(self.data)+'>' def __iter__(self): yield self #1 for n in self.childs: for nn in n.__iter__(): yield nn #2 n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) for node in n: print node From kyosohma at gmail.com Wed Mar 19 14:32:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 11:32:46 -0700 (PDT) Subject: csv dictreader References: Message-ID: On Mar 19, 1:06 pm, brnstrmrs wrote: > I am trying to use the dictionary reader to import the data from a csv > file and create a dictnary from it but just can't seem to figure it > out. > > Here is my code: > > >>>import csv > >>>reader = csv.DictReader(open('table.csv')) > >>>for row in reader: > >>>print row > > my csv files looks like this: > > Bytecode,Element > \x00\x00,0000 > \x01\x00,0001 > .... > \x09\x00,0009 > > My output shows: > {'Bytecode': '\\x00\\x00', 'Element': '0000'} > {'Bytecode': '\\x01\\x00', 'Element': '0001'} > ... > {'Bytecode': '\\x09\\x00', 'Element': '0009'} > > 1. how can I get access to this directory What do you mean? You can get each element in the dict by doing this: for row in reader: print row['Bytecode'] print row['Element'] > 2. why does the values come with two backslashs infront of the "x" The double back slash is for escaping purposes, I think. If you print this: '\\x09\\x00' you'll get this: \x09\x00 Mike From aahz at pythoncraft.com Fri Mar 21 12:47:24 2008 From: aahz at pythoncraft.com (Aahz) Date: 21 Mar 2008 09:47:24 -0700 Subject: Python 2.x future (was Re: Improving datetime) References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> Message-ID: In article , Tim Roberts wrote: > >I thought there wasn't going to be a 2.7... Whatever gave you that idea? There's no *guarantee* that 2.7 will exist, but certainly it's being planned. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From pavlovevidence at gmail.com Mon Mar 3 15:49:33 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 12:49:33 -0800 (PST) Subject: sympy: what's wrong with this picture? References: Message-ID: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> On Mar 3, 3:40 pm, Mensanator wrote: > Notice anything funny about the "random" choices? > > import sympy > import time > import random > > f = [i for i in sympy.primerange(1000,10000)] > > for i in xrange(10): > f1 = random.choice(f) > print f1, > f2 = random.choice(f) > print f2, > C = f1*f2 > ff = None > ff = sympy.factorint(C) > print ff > > ## 7307 7243 [(7243, 1), (7307, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > > As in, "they're NOT random". > > The random number generator is broken by the sympy.factorint() > function. > > Random.choice() works ok if the factorint() function commented out. > > ## 6089 1811 None > ## 6449 1759 None > ## 9923 4639 None > ## 4013 4889 None > ## 4349 2029 None > ## 6703 8677 None > ## 1879 1867 None > ## 5153 5279 None > ## 2011 4937 None > ## 7253 5507 None > > This makes sympy worse than worthless, as it f***s up other modules. Dude, relax. It's just a bug--probably sympy is messing with the internals of the random number generator. It would be a simple fix. Instead of b****ing about it, file a bug report. Or better yet, submit a patch. Carl Banks From cokofreedom at gmail.com Mon Mar 17 04:32:38 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 17 Mar 2008 01:32:38 -0700 (PDT) Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> Message-ID: > >>> a = 1 > >>> b = 1 > >>> a is b > True > >>> id(a) > 10901000 > >>> id(b) > 10901000 Isn't this because integers up to a certain range are held in a single memory location, thus why they are the same? From bill.scherer at verizonwireless.com Wed Mar 19 08:57:52 2008 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Wed, 19 Mar 2008 08:57:52 -0400 Subject: Speaking Text In-Reply-To: References: Message-ID: <47E10DD0.4050600@verizonwireless.com> David C. Ullrich wrote: > Mac OS X has text-to-speech built into the interface. > So there must be a way to access that from the command > line as well - in fact the first thing I tried worked: > > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? > (If it's there in Linux presumably it only works if there > happens to be a speech engine available...) > With a little effort, the same code can work on Linux with the Festival speech engine. See http://www.cstr.ed.ac.uk/projects/*festival*/ > > David C. Ullrich > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Mar 19 19:19:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 20:19:32 -0300 Subject: csv.Sniffer - delete in Python 3.0? References: <18401.13509.344107.988906@montanaro-dyndns-org.local> Message-ID: En Wed, 19 Mar 2008 12:44:05 -0300, escribi?: > The csv module contains a Sniffer class which is supposed to deduce the > delimiter and quote character as well as the presence or absence of a > header > in a sample taken from the start of a purported CSV file. I no longer > remember who wrote it, and I've never been a big fan of it. It > determines > the delimiter based almost solely on character frequencies. It doesn't > consider what the actual structure of a CSV file is or that delimiters > and > quote characters are almost always taken from the set of punctuation or > whitespace characters. Consequently, it can cause some occasional > head-scratching: > > >>> sample = """\ > ... abc8def > ... def8ghi > ... ghi8jkl > ... """ > >>> import csv > >>> d = csv.Sniffer().sniff(sample) > >>> d.delimiter > '8' > >>> sample = """\ > ... a8bcdef > ... ab8cdef > ... abc8def > ... abcd8ef > ... """ > >>> d = csv.Sniffer().sniff(sample) > >>> d.delimiter > 'f' > > It's not clear to me that people use letters or digits very often as > delimiters. Both samples above probably represent data from > single-column > files, not double-column files with '8' or 'f' as the delimiter. I've seen an 'X' used as field separator - but in that case all values were numbers only. > I would be happy to get rid of it in 3.0, but I'm also aware that some > people use it. I'd like feedback from the Python community about this. > If > I removed it is there someone out there who wants it badly enough to > maintain it in PyPI? The Sniffer class already has a "delimiters" parameter; passing string.punctuation seems reasonable in case one wants to restrict the possible delimiter set. I think Sniffer is an useful class - but can't do magic, perhaps a few lines in the docs stating its limitations would be fine. -- Gabriel Genellina From fakeaddress at nowhere.org Sat Mar 22 04:31:45 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Mar 2008 08:31:45 GMT Subject: finding items that occur more than once in a list In-Reply-To: <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > John Machin wrote: >> On Mar 22, 1:11 am, castiro... at gmail.com wrote: >>> A collision sequence is not so rare. >>>>>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] >>> [1, 1, 1, 1, 1, 1, 1, 1] >> Bryan did qualify his remarks: "If we exclude the case where an >> adversary is choosing the keys, ..." > > Some adversary. What, you mean, my boss or my customers? We mean that the party supplying the keys deliberately chose them to make the hash table inefficient. In this thread the goal is efficiency; a party working toward an opposing goal is an adversary. If you find real-world data sets that tend to induce bad-case behavior in Python's hash, please do tell. It would be reason enough to adjust the hash function. The hashes in popular software such as Python are already quite well vetted. Even a hash function that behaves as a random oracle has worst-case quadratic-time in the algorithm here, but that's an issue in theory and not in serving customers. -- --Bryan From hniksic at xemacs.org Tue Mar 18 11:18:04 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Mar 2008 16:18:04 +0100 Subject: finding items that occur more than once in a list References: Message-ID: <87k5k02h8z.fsf@mulj.homelinux.net> Ninereeds writes: > The dictionary version Chris suggests (and the essentially > equivalent set-based approach) is doing essentially the same thing > in a way, but using hashing rather than ordering to organise the > list and spot duplicates. This is *not* O(n) due to the rate of > collisions increasing as the hash table fills. If collisions are > handled by building a linked list for each hash table entry, the > performance overall is still O(n^2) This doesn't apply to Python, which implements dict storage as an open-addressed table and automatically (and exponentially) grows the table when the number of entries approaches 2/3 of the table size. Assuming a good hash function, filling the dict should yield amortized constant time for individual additions. > I suspect Python handles collisions using linked lists, Why suspect, it's trivial to check. dictobject.c says: The basic lookup function used by all operations. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. Open addressing is preferred over chaining since the link overhead for chaining would be substantial (100% with typical malloc overhead). From jerry.fleming at saybot.com Tue Mar 18 02:12:12 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Tue, 18 Mar 2008 14:12:12 +0800 Subject: ctypes in python failed to honor c_int In-Reply-To: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> References: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> Message-ID: Gabriel Genellina wrote: > On 17 mar, 23:57, Jerry Fleming wrote: > >> I have a binary file written with c structures. Each record contains a >> null-terminated string followed by two 4-bytes integers. I wrote a small >> segment of python code to parse this file in this way: >> [coe] >> #!/usr/bin/python >> >> from ctypes import * >> >> class Entry(Structure): >> _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) >> >> idx = open('x.idx', 'rb') >> str = idx.read(1000) >> obj = Entry(str) >> print obj.w >> print obj.s >> print obj.l >> [/code] >> where the field w is the string, and s and l are the integers. Problem >> is that, I can only get the strings, not the integers. Well, I did got >> integers, but they are all zeros. What should I do to get the real numbers? > > So the string has a variable length? For "Hello" you have > 'h','e','l','l','o', a zero byte, followed by the two integers? This > is somewhat unusual for a C struct (in fact you can't declare it in > C). Perhaps the string is actually a char[n] array with a declared > maximum size? Yes, it has a variable length. The C version of the structure is something like this: [code] struct entry { char *str, int start, int length } [/code] And adding repr() would print something like this: [code] '(as) mad as a hatter\x00\x00\x00\x00\x00\x00\x00\x00\x1f-ish\x00\x00\x00\x00\x1f\x00\x00\x00 at -ism\x00\x00\x00\x00_\x00\x00\x00B-ist\x00\x00\x00\x00\xa1\x00\x00\x00J.AU\x00\x00\x00\x00\xeb\x00\x00\x00P.EXE\x00\x00\x00\x01;\x00\x00\x00`.GIF\x00\x00\x00' (as) mad as a hatter 0 0 [/code] where the first line is the result of repr(). We can find that, after the null-terminated string '(as) mad as a hatter', there are two integers, 0 and 31 (0x1f). But python treat 31 as zero. > > Try printing repr(a_few_read_bytes) or a_few_read_bytes.encode("hex") > to see the actual file contents. > > -- > Gabriel Genellina From aahz at pythoncraft.com Sun Mar 16 20:09:02 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Mar 2008 17:09:02 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: [warning: rant ahead] [[ Before starting my rant, I would like to encourage anyone who was at PyCon but has not provided formal feedback to use the following URLs: For the conference: http://tinyurl.com/2ara8u For the tutorials: http://tinyurl.com/2ew2pc ]] In article <5776428b-82b3-4921-945a-69beab134edd at b64g2000hsa.googlegroups.com>, fumanchu wrote: > >This is my third PyCon, and I've found a reasonably-sized cadre of >people who come for the hallway conversations plus a Bof or two, >having given up on hearing anything new, useful, or inspiring in the >talks. There are several people I know who would like to see a more >advanced academic track. Let's leave aside the issue of how sponsor talks were handled: assuming that there's general agreement that this year was a failed experiment, fixing it is easy. What you're bringing up here is a much more difficult issue, and it is, in the end, not a solvable issue in the general case. For starters, speaking as someone who has been going to science fiction conventions for more than twenty years, there will inevitably be plenty of people like your cadre. I rarely go to organized programming anymore, but I still have a great time because I'm seeing all my friends. PyCon is a similar community-oriented event. Moreover, PyCon's success rests on many legs: tutorials, Open Space, Lightning Talks, formal presentations, keynotes, and sprinting. That's aside from the myriad opportunities to network with people. Finally, trying to satisfy a thousand people is impossible. People who want to emphasize specific topics (e.g. an academic track) will need to start organizing other kinds of Python conferences. Now the rant: If you did not like the programming this year (aside from the sponsor talks) and you did not participate in organizing PyCon or in delivering presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! PyCon is built on the backs of its volunteers. I personally spent more than twenty hours just doing Program Committee work. We rejected half the proposals that we received, simply due to lack of space. We had difficulty evaluating some proposals because nobody on the PC had subject matter expertise. None of the speakers received any kind of honorarium. Except for keynote speakers (e.g. Ivan Krstic), no speakers received free registration unless they requested financial aid. There are no requirements for volunteering other than a willingness to volunteer and a modicum of courtesy in working with people. PyCon is what YOU make of it. If you want to change PyCon, propose a presentation or join the conference committee (concom) -- the latter only requires signing up for the pycon-organizers mailing list. This doesn't mean that we are uninterested in feedback. We love feedback. But there are stark limits to what we can do unless people get involved and push their pet projects. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bcl at brianlane.com Tue Mar 25 11:37:00 2008 From: bcl at brianlane.com (Brian Lane) Date: Tue, 25 Mar 2008 08:37:00 -0700 Subject: Inheritance question In-Reply-To: References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: <47E91C1C.8090705@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gerard Flanagan wrote: > Use the child class when calling super: > > -------------------------------------- > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = super(FooSon, self).getid() > b = self.id > return '%d.%d' % (a,b) > > print FooSon().getid() > -------------------------------------- That still doesn't do what he's trying to do. The problem here is that you only have one instance. self refers to it, so when you set self.id in the super you have set the instance's id to 1. When you set it to 2 after calling the super's __init__ you are now setting the *same* variable to a 2. Basically, you can't do what you are trying to do without using a different variable, or keeping track of a separate instance for the super instead of sub-classing it. Brian - -- - ---[Office 71.7F]--[Outside 33.2F]--[Server 99.5F]--[Coaster 68.7F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH6RwcIftj/pcSws0RArdpAJ9pCMjrkpBarHyQsl6hXEifj52giwCfXfKa Ot/1a+NNOLN5LA4mxBtfpis= =Yacu -----END PGP SIGNATURE----- From sjmachin at lexicon.net Mon Mar 10 07:25:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 04:25:53 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: On Mar 10, 8:31 pm, "Neil Crighton" wrote: > I'm using the zipfile library to read a zip file in Windows, and it > seems to be adding too many newlines to extracted files. I've found > that for extracted text-encoded files, removing all instances of '\r' > in the extracted file seems to fix the problem, but I can't find an > easy solution for binary files. > > The code I'm using is something like: > > from zipfile import Zipfile > z = Zipfile(open('zippedfile.zip')) > extractedfile = z.read('filename_in_zippedfile') > "Too many newlines" is fixed by removing all instances of '\r'. What are you calling a newline? '\r'?? How do you know there are too many thingies? What operating system were the original files created on? When you do: # using a more meaningful name :-) extractedfilecontents = z.read('filename_in_zippedfile') then: print repr(extractedfilecontents) what do you see at the end of what you regard as each line: (1) \n (2) \r\n (3) \r (4) something else ? Do you fiddle with extractedfilecontents (other than trying to fix it) before writing it to the file? When you write out a text file, do you do: open('foo.txt', 'w').write(extractedfilecontents) or open('foo.txt', 'wb').write(extractedfilecontents) ? When you write out a binary file, do you do: open('foo.txt', 'w').write(extractedfilecontents) or open('foo.txt', 'wb').write(extractedfilecontents) ? From michael.wieher at gmail.com Sun Mar 16 13:43:05 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 12:43:05 -0500 Subject: Strange problem with structs Linux vs. Mac In-Reply-To: <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> Message-ID: you can specifify which encoding when you unpack the struct, so just try them till it works, or read the specs on the mac.. i find it quicker to try, there's only 4-5 2008/3/16, sturlamolden : > > On 16 Mar, 18:23, "Martin Blume" wrote: > > > This seems to imply that the Mac, although running now on Intel > > processors, is still big-endian. > > Or maybe the struct module thinks big-endian is native to all Macs? It > could be a bug. > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From codedread at gmail.com Sun Mar 9 13:26:57 2008 From: codedread at gmail.com (Jeff Schiller) Date: Sun, 9 Mar 2008 12:26:57 -0500 Subject: Need Help Building PythonQt on Windows Message-ID: Hello, I'm creating an application using Qt (4.4 Beta atm). I have pretty close to zero experience with Python (consisting of installing the Python interpreter, downloading a python programming and executing it on the command-line). I would like to invoke a Python script from my C++ Qt program and capture its output as a C++ structure. It seems that PythonQt might be suitable for my needs. Being a Qt program, I want this thing to be cross-platform. I'm having trouble getting things set up in Windows. Has anyone had any experience with this? I've built Qt from source using the mingw32 compiler. I installed Python 2.5 binary. I am trying to build PythonQt from source. As per http://pythonqt.sourceforge.net/#Building it says I need a "developer installation" of Python containing the header files and the library files. When I look at my system after installing the Python 2.5 binary, I can see I have header files (C:\Python25\include), a 199k python25.lib (C:\Python25\libs) and a 2MB python25.dll (C:\Windows\System32\). Have I got what I need? I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts to build but then it fails: g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to `_imp__Py_NoSiteFlag' ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to `_imp__Py_NoSiteFlag' ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to `_imp___Py_NoneStruct' C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to `_imp___Py_NoneStruct' ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to `_imp___Py_NoneStruct' C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to `_imp___Py_NoneStruct' ./debug\PythonQt.o: In function `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to `_imp__PyClass_Type' C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to `_imp__PyClass_Type' C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to `_imp__PyCFunction_Type' ... Since I'm new to compiling Qt with mingw and completely new to python, I was hoping for tips on why I'm getting these errors. If anyone has a better suggestion for a forum/mailing list then please let me know. Thanks, Jeff From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:16:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:16:39 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Message-ID: <13t6i47r3uoo6b4@corp.supernews.com> On Sat, 08 Mar 2008 15:26:35 -0800, Paul Rubin wrote: > Alasdair writes: >> What is the best way of finding a ceiling of a quotient of arbitrary >> sized integers? > > ceiling(a/b) = (a+b-1)//b Unfortunately that doesn't work reliably. >>> a, b = 9007199254741000.0, -3.0 >>> a/b -3002399751580333.5 >>> (a+b-1)//b # should be -3002399751580333 -3002399751580332.0 I make no claim that this is the most efficient way to do it, but this should work: def splitfloat(f): """Return the integer and fraction part of a float.""" fp = abs(f) % 1.0 ip = abs(f) - fp if f < 0: ip, fp = -ip, -fp return (ip, fp) def ceil(f): ip, fp = splitfloat(f) if fp == 0: return ip elif f < 0: return ip else: return ip + 1 >>> a, b = 9007199254741000.0, -3.0 >>> ceil(a/b) -3002399751580333.0 >>> a, b = 9007199254741000.0, 3.0 >>> ceil(a/b) 3002399751580334.0 It even works for infinities, if supported by your platform: >>> ceil(1.0/inf) 0.0 (Disclaimer: if you consider that 1.0/inf is a tiny bit more than zero, and therefore you want ceil(1.0/inf) to give 1.0, then you will disagree with me.) -- Steven From jeff at schwabcenter.com Thu Mar 13 01:45:15 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 12 Mar 2008 22:45:15 -0700 Subject: How to port Python code into C++ code automatically? In-Reply-To: References: Message-ID: Bo wrote: > I want to port a Python project (about 10,000 line python code) to C+ > +. Is there any automatically tool to do this kind of things? e.g., That's not trivial. Python is very heavily oriented toward run-time processing, whereas C++ favors compile-time processing. > e.g., SWIG(http://www.swig.org/)? Swig isn't so much a translator as a way of linking C or C++ code to multiple different scripting languages, using shared configuration (.i) files. If you're only connecting two languages (Python and C++), Swig is probably not going to help you much unless you happen to already be a master of Swig-foo. If the Python code works, then it's probably best to keep it in Python. To access it from C++, try Boost.Python. If you really do need to translate the code from Python to C++, try to do it incrementally. If the Python code is so monolithic that you can't find individual pieces to move one-at-a-time, consider refactoring the code in Python so that you'll at least have some modularity to work with. (In the process of refactoring, you may also find that you don't have to move the code out of Python, after all, e.g. because the performance improves along with the design.) From adrianbn at gmail.com Tue Mar 18 13:40:29 2008 From: adrianbn at gmail.com (=?ISO-8859-1?Q?Adri=E1n_Bravo_Navarro?=) Date: Tue, 18 Mar 2008 18:40:29 +0100 Subject: Comunicate processes with python In-Reply-To: References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> Message-ID: <267c4040803181040q2a70b91w8f92ff59359843fb@mail.gmail.com> That was what we were thinking of, so if there is not some kind of easy python magic we will probably use some sockets. Thanks!! 2008/3/18, Joshua Kugler : > > Adri?n Bravo Navarro wrote: > >> Is there any simple way to achieve this goal? We've been thinking of > >> sockets but Im not conviced at all with that. > > > If you want to communicate between processes on the same host, yes, you > can > use DBus or a couple of the options here: > http://docs.python.org/lib/ipc.html > > If you want to communicate between hosts, then sockets is probably going > to > be your only options, although there are libraries that abstract some of > that for you to make it easier to manage. You might want to take a look > at > Pyro. http://pyro.sourceforge.net/ > > j > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waldemar.osuch at gmail.com Fri Mar 14 15:46:41 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Fri, 14 Mar 2008 12:46:41 -0700 (PDT) Subject: ZSI and attachments References: Message-ID: <9efbc308-bb4e-4833-832d-d7b095692354@e60g2000hsh.googlegroups.com> On Mar 11, 8:59 am, Laszlo Nagy wrote: > Hi All, > > I wonder if the newest ZSI has support for attachments? Last time I > checked (about a year ago) this feature was missing. I desperately need > it. Alternatively, is there any other SOAP lib for python that can > handle attachments? > Does this help? http://trac.optio.webfactional.com/browser/soaplib/trunk/examples/binary.py From deets at nospam.web.de Mon Mar 3 15:09:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Mar 2008 21:09:01 +0100 Subject: Polymorphism using constructors In-Reply-To: <6333v2F25lleoU1@mid.individual.net> References: <6333v2F25lleoU1@mid.individual.net> Message-ID: <63346uF25gigqU1@mid.uni-berlin.de> K Viltersten schrieb: > I'm writing a class for rational numbers > and besides the most obvious constructor > > def __init__ (self, nomin, denom): > > i also wish to have two supporting ones > > def __init__ (self, integ): > self.__init__ (integ, 1) > def __init__ (self): > self.__init__ (0, 1) > > but for some reason (not known to me at > this point) i get errors. My suspicion is that it's a syntax issue. > > Suggestions? "errors" is not much of an error-description. That's what stacktraces are for. Apart from that, you won't succeed with the above. Python has no signature-based polymorphism. Instead, you use default arguments, like this: def __init__(nomin=0, denom=1): ... That should suffice. Diez From steve at holdenweb.com Sun Mar 2 12:38:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 12:38:17 -0500 Subject: tcp In-Reply-To: <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: Gif wrote: > i would like to apologize once more. i understand that you are saying > "what a fool he is waiting for us to solve all his problems", cause > i've said that for other posts, when they seemed "immature". It's just > that i couldn't find a way out of 20 lines of code and this drove me > mad. > > i end this topic here. If you want to use the socket module, take a look at http://holdenweb.com/py/networking/ which contains links to some fairly explicit notes about how to write TCP and UDP servers in Python. Nobody thinks you are a fool for wanting help with your problems, it's simply that you have to provide enough information about what' wring for us to get a handle on the issues. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:06:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:06:53 -0300 Subject: distutils as an application installer? References: <8cfcad33-a6c2-4e30-b585-6ad57555b316@c19g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 08:32:15 -0300, PurpleServerMonkey escribi?: > Was hoping someone could take a quick look at my distutils problem and > give it a quick sanity check. > > Basically I have a server application (for Linux) that I want to > install to /usr/local/, this location would have > subdirectories for the daemon scripts, log files, plugins etc. > > After reading a bunch of distutils documentation it appears that the > only good way out of this is to have my packages install to the system > wide site-packages directory. Then using the data_files command in > setup.py have it copy across an initial skeleton copy of the server > directory and finally install the startup scripts. > > Does this sound correct, any other suggestions? I'd use instead a standard setup script, and install it with --prefix or --home. You may want to provide a setup.cfg file with some defaults. > The distutils documentation doesn't cover this scenario and I've spent > days searching for information so any assistance is greatly > appreciated. It is in the "Installing" part, not in "Distributing". After all, you (as the developer) should only provide "what" to install; but "where" those parts get actually installed is decided by soemone else when the app is installed ("someone else" might even be yourself) -- Gabriel Genellina From fakeaddress at nowhere.org Fri Mar 14 04:07:09 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 08:07:09 GMT Subject: Socket Performance In-Reply-To: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: sleddd at gmail.com wrote: > Well, lets say you have a situation where you're going to be > alternating between sending large and small chunks of data. Is the > solution to create a NetworkBuffer class and only call send when the > buffer is full, always recv(8192)? Buffering can often improve performance, but with the above we'd to too quick to prematurely jump to an as yet unwarranted conclusion. You measured the one-large and many-small cases, but not the case you actually have. You might be able to take various measurements and generally characterize speed as a function of the number of calls and the size of the send. I wouldn't be surprised if the result is well approximated by a time per call plus a time per byte. In optimization, guessing is bad. Where you cannot reason with mathematical rigor, measure. Where you can derive a purely analytic result, taking the occasional measurements still isn't a bad idea (but don't tell my algorithms students). -- --Bryan From gagsl-py2 at yahoo.com.ar Wed Mar 26 15:11:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 16:11:40 -0300 Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 15:38:16 -0300, Tzury Bar Yochay escribi?: >> ....and then when my application execute code how can I set path to >> d3dx module to "library.zip/d3dx.py". >> I'm not sure is this properly set question. > > use the module zipimport > http://docs.python.org/lib/module-zipimport.html You don't have to do anything special to "use" zipimport; from : "It is usually not needed to use the zipimport module explicitly; it is automatically used by the builtin import mechanism" -- Gabriel Genellina From tmp1 at viltersten.com Sat Mar 8 15:21:48 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 8 Mar 2008 21:21:48 +0100 Subject: SV: Regarding coding style In-Reply-To: <13t5qd3slgt9nc0@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <63g9s0F26pgoeU1@mid.individual.net> > What I really can't stand are the > pointy-haired comment blocks at the > beginnings of C/C++ functions that do > things like tell you the name and return > type of the function and list the names > and types of the parameters. Gee, thanks. > I never could have figured that out from > looking at the source code itself. Coming from C++/Java camp i can't help noticing that in most cases, when i'm using a class written by somebody else, i don't want to see his/her code. I only want to know WHAT the function does (is intended to be doing, at least). I don't want to look at the source code (in some cases i can't even see the code because it's compiled). I only care that when i execute SomeType obj = SomeType(); obj.aggregate(); the object gets aggregated. How it's done will be up to the author. I'm just a user of the product. Now, i'm getting the signal that it's done in a different way in Python. Please elaborate. I'm very new to snakeology. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From MadComputerGuy at gmail.com Mon Mar 10 23:44:52 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Mon, 10 Mar 2008 20:44:52 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? Message-ID: Why does my compiler say invalid syntax and then highlight the quotation marks in the following code: # This program is to find primes. primes = [] import math import gmpy while 1: run = int(raw_input("Do you want to calculate primes? 1 = yes and 2 = no. ")) if run == 1: y = int(raw_input("What number do you want to use as the final number to calculate with? ")) x = int(raw_input("What number do you want to start calculating primes from? ")) while x < 2: print "Number must be at least 2 for math reasons." else: while x < y: prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) if prime < 0: primes.append(x) else: print x " is not prime. " # highlights the final " here x = x + 1 print primes elif run == 2: break else: print "Sorry, not a choice. Please enter your choice again." print "Goodbye." How do I fix such an invalid syntax? TIA, Nathan Pinno From skunkwerk at gmail.com Tue Mar 25 23:39:05 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 25 Mar 2008 20:39:05 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> Message-ID: <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> also, i've tried the Shell=True parameter for Popen, but that didn't seem to make a difference On Mar 25, 8:31 pm, skunkwerk wrote: > Hi, > i'm trying to call subprocess.popen on the 'rename' function in > linux. When I run the command from the shell, like so: > > rename -vn 's/\.htm$/\.html/' *.htm > > it works fine... however when I try to do it in python like so: > p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > print p.communicate()[0] > > nothing gets printed out (even for p.communicate()[1]) > > I think the problem is the quoted string the rename command wants - > when I put it in triple quotes like """s/\.htm$/\.html/""" I get some > output, but not the correct output. I've also tried escaping the > single quotes with \' and putting it in regular double quotes but that > didn't work either. > > i'd appreciate any help From bob.martin at excite.com Tue Mar 11 04:03:26 2008 From: bob.martin at excite.com (Bob Martin) Date: Tue, 11 Mar 2008 08:03:26 GMT Subject: Distributed App - C++ with Python for Portability? References: Message-ID: in 337600 20080310 222850 dave_mikesell at fastmail.fm wrote: >On Mar 10, 2:21 pm, Bob Martin wrote: > >> >> Java is more portable than most other languages, especially if your app needs a gui. > >The promise of Java portability was one of the biggest scams ever >perpetrated on the software industry. There are issues going from OS >to OS, VM to VM, DB to DB, app server to app server, etc. Certainly >no easier than porting C++ and the appropriate libraries, IMHO. Quite untrue - I have a stack of large java apps which run without change on Linux, OS/2 and Windows. Not many, if any, other languages can match that, and definitely not C++. From gagsl-py2 at yahoo.com.ar Wed Mar 26 12:29:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 13:29:55 -0300 Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 11:17:15 -0300, Python Programming on Win32 escribi?: > The problem is running smtplib in a py2exe compiled exe file. When it > tries to establish a socket to the mail server it fails. > > Just wondering someone has encountered this before, and if someone > might be able to point me in the right direction. > > Unhandled exception in thread started by > Traceback (most recent call last): > File "AutomationThread.pyc", line 152, in Run > File "mail.pyc", line 11, in sendMail > File "smtplib.pyc", line 244, in __init__ > File "smtplib.pyc", line 296, in connect > socket.gaierror: (10093, 'getaddrinfo failed') The script can't resolve the server name. Try to do it by hand using nslookup or even ping (you may want to add a few print statements inside the script to see the exact host name it is trying to connect to, in case it isn't what you expect) If you can't resolve the host name using nslookup, there is a network problem, not in your script. If you can resolve it, try your script without py2exe if possible. -- Gabriel Genellina From http Sat Mar 29 08:01:57 2008 From: http (Paul Rubin) Date: 29 Mar 2008 05:01:57 -0700 Subject: deleting a line from a file References: <13usb5ngt26qv26@corp.supernews.com> Message-ID: <7xy781zqkq.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > The only safe way to delete a line from a file (at least under common > operating systems like Windows, Linux and Mac) is to copy the file > (without the line you wish to delete) to a temporary file, then replace > the original file with the new version. That's also how to do it for > files too big to read into memory. You could do it "in place" in all those systems afaik, either opening the file for both reading and writing, or using something like mmap. Basically you'd leave the file unchanged up to line N, then copy lines downward starting from line N+1. At the end you'd use ftrunc to shrink the file, getting rid of the duplicate last line. From dave.brk at gmail.com Thu Mar 27 16:08:20 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 27 Mar 2008 22:08:20 +0200 Subject: Regarding __slots__ and other stuff: A couple of questions In-Reply-To: References: Message-ID: sorry, forget all I wrote: I should have read this more thoroughly, it explained it all http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.htm Descriptors only works with type objects, not instance. and you can't write from an instance object to a class variable. You can only hide it. Also __slots__ works by creating descriptors in the class and preventing creation of any atrributes in the class instance, so everything is clear now Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Mar 12 21:18:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Mar 2008 21:18:55 -0400 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: | > Hmm, wasn't aware they were taking it that far. You should almost | > always avoid using the cmp parameter because it's very inefficient; | | I don't see what's so inefficient about it necessarily. The key function is called once per list item, for n calls total. The comparision function is called once per comparision. There are at least n-1 such calls and typically something on the order of n * lg2(n) calls. From castironpi at gmail.com Wed Mar 5 15:06:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 12:06:11 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> Message-ID: <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: > castiro... at gmail.com schrieb: > > > I want to hash values to keys. ?How do the alternatives compare? > > http://catb.org/~esr/faqs/smart-questions.html ... without extending the whole way to a full relational database? From ivlenin at gmail.com Sun Mar 9 14:37:45 2008 From: ivlenin at gmail.com (I V) Date: Sun, 09 Mar 2008 18:37:45 GMT Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> <63hq8rF27chv6U1@mid.uni-berlin.de> <96486094-0706-45f1-b5c1-4af6333e3955@s13g2000prd.googlegroups.com> Message-ID: On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote: > Well, that suits me. The most unnatural thing about Python was adapting > to the idea of just letting unreleased resources go jogging off > wherever. :) Yes, that's a bad habit that garbage collection can encourage. GC is good for managing memory, but not good for managing other resources, so if an object holds some other resource, it's important to make sure the resource is released in a timely fashion rather than relying on the finalizer (the __del__ function). CPython uses reference counting, so it usually destroys objects fairly soon after the stop being used. But JPython and IronPython don't do reference counting, so forgetting to clean up resources can be a significant problem. > "Where's the f.close?" > "You don't need it!" Although, you still don't need f.close, with the new with statement: with open('myfile') as f: string = f.readline() # f.close() gets called automatically here, without waiting for # garbage collection. If you want to use this in 2.5, you have to write: from __future__ import with_statement The big advantage here is that f.close will get called if the block exits normally, or if there is an exception. For more, see http://effbot.org/pyref/with.htm . From tamim.shahriar at gmail.com Sun Mar 2 00:38:24 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sat, 1 Mar 2008 21:38:24 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 2, 6:56 am, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira I have found that 'Dive into Python' is a good book for people who have experience with other languages. It's available free here: http://www.diveintopython.org/ regards, Subeen http://love-python.blogspot.com/ From john.deas at gmail.com Sun Mar 9 08:25:19 2008 From: john.deas at gmail.com (John Deas) Date: Sun, 9 Mar 2008 05:25:19 -0700 (PDT) Subject: parralel downloads References: Message-ID: On Mar 8, 5:47 pm, Gary Herron wrote: > poof65 wrote: > > For your problem you have to use threads. > > Not at all true. Thread provide one way to solve this, but another is > the select function. For this simple case, select() may (or may not) be > easier to write. Pseudo-code would look something like this: > > openSockets = list of sockets one per download file: > while openSockets: > readySockets = select(openSockets ...) # Identifies sockets with > data to be read > for each s in readSockets: > read from s and do whatever with the data > if s is at EOF: close and remove s from openSockets > > That's it. Far easier than threads. > > Gary Herron > > > You can have more information here. > >http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > > >> Hi, > > >> I would like to write a python script that will download a list of > >> files (mainly mp3s) from Internet. For this, I thought to use urllib, > >> with > > >> urlopen("myUrl").read() and then writing the resulting string to a > >> file > > >> my problem is that I would like to download several files at the time. > >> As I have not much experience in programming, could you point me the > >> easier ways to do this in python ? > > >> Thanks, > > >> JD > >> -- > >> http://mail.python.org/mailman/listinfo/python-list Thank you both for your help. Threads are working for me. However, a new problem for me is that the url I want to download are in an xml file (I want to download podcasts), and is not the same as the file downloaded: http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2BBD61E9ECD2C&ref=p_rss will be redirected to download: http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 is there a way, knowing the first url to get the second at runtime in my script ? From tmp1 at viltersten.com Sat Mar 1 19:49:38 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 01:49:38 +0100 Subject: SV: Where's GUI for Python? In-Reply-To: <62uai0F24sc4aU1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> Message-ID: <62uauaF2400f1U1@mid.individual.net> >> When that fails, try without the stutter >> >> import tkinter > > I must be doing something wrong because > neither tkinter nor tkininter works. > I tried both with and without stuttering. > I even asked my wife to stutter some but, > sadly, to no avail. > > When Tim Chase mentioned "battery-installed", > i interpreted it as "all is there". It seems > that either > a) not all the batteries are installed in my > version (v2.5.2) > or > b) some setup/linkage needs to be performed > in order to get the GUI running. > > The error itself is: > ImportError: No module named tkinter > > Suggestions? Here's a suggestion. Python is case-sensitive, while the users trying to help you are not. When they say "tininkerbell", they may mean "Tinkerbell". Check with "help()", then "modules" and see if it's installed or not. Sincerely Yourself :) (Seriously speaking - i'm thankful.) From xu.mathena at gmail.com Sun Mar 23 19:01:31 2008 From: xu.mathena at gmail.com (NotGuru) Date: Sun, 23 Mar 2008 16:01:31 -0700 (PDT) Subject: PyTuple_Check and other type check functions didn't check the NULL pointer Message-ID: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> I was writing some C extensions for Python and use PyTupleType_Check extensively. I found that all the PySomeType_Check macros directly delegate the job to PyObject_TypeCheck(op, &PyType_Type). The PyObject_TypeCheck(op, &PyType_Type) is again a macro and defined as ((ob)->ob_type == (tp) || PyType_IsSubtype((ob)->ob_type, (tp))) in object.h. My questions is: is it necessary to check the null pointer in the macro or it's a job for the user? Semantically all the type check should report a false if a null pointer is encountered. I've already had the patch to this issue but I am not sure if I think this problem right. I don't know if there are some python core developers around but I would like to hear all opinions towards this. BTW, if the user didn't check null pointer before call the function, a segmentation fault might occur. From dstromberglists at gmail.com Wed Mar 12 19:51:24 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Wed, 12 Mar 2008 23:51:24 GMT Subject: tcp client socket bind problem References: Message-ID: <00_Bj.17371$Ch6.8114@newssvr11.news.prodigy.net> On Sun, 09 Mar 2008 22:21:59 -0700, natambu wrote: > I have a linux box with multiple ip addresses. I want to make my python > client connect from one of the ip addresses. Here is my code, no matter > what valid information I put in the bind it always comes from the > default ip address on the server. Am I doing something wrong? > > > ------------- > #!/usr/bin/python > > import socket > > host = "server" > port = 1190 > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.bind(("",0)) > sock.connect((host, port)) > ------------- I'd've expected that to work. What does your routing table look like? You can view it with "netstat - nr". I believe when a Linux network interface is ifconfig'd, the kernel will add a route for that interface based on the netmask in the ifconfig, but you could conceivably have another route that is broader overriding the specific route. From nagle at animats.com Fri Mar 14 01:53:49 2008 From: nagle at animats.com (John Nagle) Date: Thu, 13 Mar 2008 22:53:49 -0700 Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup In-Reply-To: <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> References: <47d97288$0$36363$742ec2ed@news.sonic.net> <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> Message-ID: <47da10c8$0$36374$742ec2ed@news.sonic.net> John Machin wrote: > On Mar 14, 5:38 am, John Nagle wrote: >> Just noticed, again, that getattr/setattr are ASCII-only, and don't support >> Unicode. >> >> SGMLlib blows up because of this when faced with a Unicode end tag: >> >> File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag >> method = getattr(self, 'end_' + tag) >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' >> in position 46: ordinal not in range(128) >> >> Should attributes be restricted to ASCII, or is this a bug? >> >> John Nagle > > Identifiers are restricted -- see section 2.3 (Identifiers and > keywords) of the Reference Manual. The restriction is in effect that > they match r'[A-Za-z_][A-Za-z0-9_]*\Z'. Hence if you can't use > obj.nonASCIIname in your code, it makes sense for the equivalent usage > in setattr and getattr not to be available. > > However other than forcing unicode to str, setattr and getattr seem > not to care what you use: OK. It's really a bug in SGMLlib, then. SGMLlib lets you provide a subclass with a function with a name such as "end_img", to be called at the end of an "img" tag. The mechanism which implements this blows up on any tag name that won't convert to "str", even when there are no "end_" functions that could be relevant. It's easy to fix in SGMLlib. It's just necessary to change except AttributeError: to except AttributeError, UnicodeEncodeError: in four places. I suppose I'll have to submit a patch. John Nagle SiteTruth From bockman at virgilio.it Mon Mar 24 11:45:42 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 15:45:42 GMT Subject: Disable resize button References: Message-ID: <47e7cca5$0$16036$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 04:38:50 -0700, myonov ha scritto: > Hi! > > I need to disable resize button in Tkinter. I inherit the Frame class. > Then in the constructor i make my buttons, labels, etc. Then I pack them > and when move borders of the frame everything changes it's location and > it looks really bad. How can I change that? > That's my code: > # -*- coding: cp1251 -*- > import Tkinter > > class App(Tkinter.Frame): > def click(self): > pass > > def click2(self): > pass > > def __init__(self, master=None): > Tkinter.Frame.__init__(self, master, width = 700, height = > 400,\ > bg = "#999999") > self.pack() > > # Buttons > > self.b1 = Tkinter.Button(self, text = u"?????? ?????",\ > command=self.click, font = "Courier", > \ > fg = "red") > self.b2 = Tkinter.Button(self, text = u"?????? ???????",\ > command=self.click2, font = "Courier", > \ > fg = "red") > self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = > 0.75, rely = 0.4) > > # Labels > > self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ > text = u"??????????", fg = "#ffffff",\ > bg = "#999999") > self.l1.place(x = 275, y = 10) > > # Text Control > # self.txt = Tkinter.Text(self, bg = "#124456", ) # > self.txt.pack() > > You could try including the frame in a toplevel window (e.g. passing Tkinter.Tk() as super) and then doing super.wm_resizable(None, None) A better idea would be using pack instead of place, leaving to the toolkit the job of rearranging the widgets when the window is enlarged or reduced. Ciao ----- FB From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 07:49:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 11:49:11 -0000 Subject: deleting a line from a file References: Message-ID: <13usb5ngt26qv26@corp.supernews.com> On Sat, 29 Mar 2008 04:13:10 -0700, eMko wrote: > Is there some easy way how to delete a line from a middle of a file in > Python? If the file is small enough to fit into memory (say, up to a few hundred megabytes on most modern PCs): lines = open('file', 'r').readlines() del line[100] open('file', 'w').writelines(lines) Quick and easy for the coder, but not the safest way to do it in serious production code because there's no error handling there. The only safe way to delete a line from a file (at least under common operating systems like Windows, Linux and Mac) is to copy the file (without the line you wish to delete) to a temporary file, then replace the original file with the new version. That's also how to do it for files too big to read into memory. -- Steven From lbonafide at yahoo.com Sun Mar 16 20:08:43 2008 From: lbonafide at yahoo.com (lbonafide at yahoo.com) Date: Sun, 16 Mar 2008 17:08:43 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> Message-ID: <11252b13-e3d0-4aa7-9cf5-ee9db7bfc250@u69g2000hse.googlegroups.com> On Mar 16, 2:43 pm, Robert Hicks wrote: > On Mar 16, 12:38 pm, lbonaf... at yahoo.com wrote: > > > On Mar 16, 6:10 am, Bruce Eckel wrote: > > > > I think a lot of people have been caught up in the idea that we need > > > to commercialize Python, and ride some kind of wave of publicity the > > > way that Java and C# and Rails seem to have done. > > > This coming from someone who caught the Java wave and rode it for a > > decade. > > Doesn't that make him better to see the problems with it? Sure, but he dumped C++ (a truly non-commercial language) like a bad habit for the latest silver bullet ten years ago. Complaints against Java's commercial nature now ring a bit hollow. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Mar 25 14:35:34 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 25 Mar 2008 19:35:34 +0100 Subject: Files, directories and imports - relative to the current directory only References: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> Message-ID: <64suvmF2d8hphU1@mid.individual.net> ptn wrote: > Traceback (most recent call last): > File "path.py", line 4, in > f = open('~/read/foo.txt') > IOError: [Errno 2] No such file or > directory: '~/read/foo.txt' > [...] > So, what's wrong here? Maybe there's something I haven't set up? Simple: the directory "~" doesn't exist. Since you're not using a shell (but direct file access) there is no tilde expansion, and "~" is treated as a regular file name. If you need to get the home directory refer to the environment variable HOME (os.environ["HOME"]). There even may be a shorter way, please refer to the os module docs. Regards, Bj?rn -- BOFH excuse #139: UBNC (user brain not connected) From malaclypse2 at gmail.com Thu Mar 27 11:05:19 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 27 Mar 2008 11:05:19 -0400 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: <16651e80803270805q399b1c17mec7703c0017cbac0@mail.gmail.com> On Thu, Mar 27, 2008 at 10:53 AM, Skip Montanaro wrote: > I am trying to replace os.system calls with subprocess.Popen. This simple > example fails miserably: > > >>> proc = subprocess.Popen ("ls /tmp") > Traceback (most recent call last): > File "", line 1, in > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 594, in __init__ > errread, errwrite) > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 1091, in > _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I also tried explicitly referencing /usr/bin/ls. Same result. What gives? It's looking for an executable named "ls /tmp" Since it can't find one, it raises an exception. If you just want to replace an os.system call, you need to pass shell=True to Popen, like this: proc = subprocess.Popen("ls /tmp", shell=True) That will get the shell to split your string into the program to be called, and the argument(s) to the program. Alternatively, you can do it yourself by passing a sequence to Popen: proc = subprocess.Popen(["ls", "/tmp"]) Take a look at the documentation for Popen (http://docs.python.org/lib/node528.html) and the specific examples for replacing os.system (http://docs.python.org/lib/node536.html) -- Jerry From wolf_tracks at invalid.com Fri Mar 28 14:26:02 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 28 Mar 2008 18:26:02 GMT Subject: Astronomy Fits format and gif.save(path) Message-ID: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> In what library would I find gif.save(path), where path is the name and path of a file, and the method would produce a file in a gif format? Is there a fits.save(path) somewhere? fits is commonly used in astronomical work. -- Wayne Watson (Nevada City, CA) Web Page: From arnodel at googlemail.com Sat Mar 22 16:42:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 13:42:17 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 7:00?pm, Larry Bates wrote: > jmDesktop wrote: > > For students 9th - 12th grade, with at least Algebra I. ?Do you think > > Python is a good first programming language for someone with zero > > programming experience? ?Using Linux and Python for first exposure to > > programming languages and principles. > > > Thank you. > > ABSOLUTELY. ?Get them started with a REAL programming language that will > teach them proper fundamentals. ?I wish Python would have been around 25 > years ago when I taught incoming Freshmen at local University. ?To get > students to understand about variable references, etc. I always started > them with Assembler so they could understand what was actually going on. > I see so may on this forum that have the wrong ideas about variable names/ > storage. It's funny, 25 years ago - I was 10 then - I got my first computer from my cousin (a Sinclair ZX81, I think it had a different name in the US) as he was getting a brand new C64. In those days BASIC was very slow so if you wanted to do anything demanding with a computer you had to learn 'machine language' (I didn't have an assembler...). I wrote my little programs in a notebook, then POKEd them into memory! I learnt so much then. Years later, when I got my first C compiler, it was a liberation. My other 'coming of age' was when I took a lambda-calculus course at university. I felt like a man who's had a black and white TV set all his life and watches colour TV for the first time. What if computers had been designed as 'lambda-calculus machines' from the start rather than Turing machines? Anyway, here the conclusion that I draw: learn lambda-calculus and Turing machines. The rest is syntactic sugar. Not quite seriously but still'ly yours -- Arnaud From gagsl-py2 at yahoo.com.ar Thu Mar 27 02:31:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 03:31:31 -0300 Subject: Plugin framework - Overcomplicating things? References: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 01:50:56 -0300, hajducko at gmail.com escribi?: > All this comes to my question - am I overcomplicating this project? I > can understand the use of something like the trac component system if > I had multiple components and plugins that handled different areas of > my project and different points of interaction, but I don't. I've got > exactly one spot where I want to check all my plugins and hand off the > message to which ever ones are looking for that command. As you said, it looks like you're really overengineering your design then. > So really, > should I even bother with trying to setup some framework for this or > should I just be doing a simple loop over a directory, importing all > the plugins and storing them in a list and then looping over them in > the message handler to see which ones were looking for the command and > letting them do their thing? That may be an option. You may want to setup a simple registry mechanism, so the plugin modules look like: ### begin niceplugin.py ### class AVeryNicePlugin(object): # or perhaps using a suitable base class def handle_message(self, message): ... from plugin import PluginRegistry PluginRegistry.register(AVeryNicePlugin) ### end niceplugin.py ### Your application scans a known directory for files ending in "plugin.py" and imports them; the modules register themselves any class (or classes), and at appropiate times the application calls some method(s) of the registered plugins. > As an aside, if there is anyone who is an experience developer and > designer and is willing to take some private correspondence, please > let me know. I feel embarrassed for asking, but I've got a alot of > questions that I don't want to litter this list with and would rather > voice them in private. Why not? Get another free account, post using a pseudonym, and nobody will know that *YOU* were the guy that asked the most stupid question of the week :) -- Gabriel Genellina From steve at holdenweb.com Sat Mar 29 22:57:33 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 29 Mar 2008 22:57:33 -0400 Subject: What motivates all unpaid volunteers at Pycon? In-Reply-To: <47EEBEFC.6040600@tim.thechases.com> References: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> <47EEBEFC.6040600@tim.thechases.com> Message-ID: Tim Chase wrote: >> I was wondering what motivated so many people to give so much to the >> Python community. > > fear, surprise, ruthless efficiency, an almost fanatical devotion > to the BDFL, and nice red uniforms. > > Oh... > NOT THE COMFY CHAIR! (tm) -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Tue Mar 4 23:12:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:12:01 -0800 (PST) Subject: is there enough information? References: <13s9u7dg24es73a@corp.supernews.com> <13spkb990ha3v6c@corp.supernews.com> <392cadeb-e1f8-4cef-834c-a837ba7e02f5@59g2000hsb.googlegroups.com> Message-ID: <51edef68-e12a-454b-9fad-a0732fb72229@x30g2000hsd.googlegroups.com> > How does it work? ?From reading threading.py, _Condition.wait() > acquires self.lock() too many times-- that is, once to call wait > ("cannot wait on un-aquired lock"), and once after--- are "all > waiters" waiting back at self.acquire, just to make it to > self.notify... and only one at a time at that!? ?Don't waiters have to > release before another waiter can go? It's not like Condition().acquire() appends self._lock to self._waiters *before* delegationing! So... how? From Lie.1296 at gmail.com Sun Mar 30 13:57:28 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 10:57:28 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> <87od8w7aws.fsf@physik.rwth-aachen.de> <659ggqF2f84eoU3@mid.individual.net> Message-ID: <31684d32-6ff6-4cb1-bb95-9910e6cd7106@s19g2000prg.googlegroups.com> On Mar 30, 7:48 pm, Bjoern Schliessmann wrote: > Torsten Bronger wrote: > > Maybe he means "?". > > Haven't seen this either, nor do I think it's the same than "<>". > From afar, it looks more like "><". Actually I meant an X-like symbol that is made not by crossing but by ><. I retracted saying it is the standard, now that I think about it the last time I saw >< was in elementary school (although it stuck on my head better than a crossed =, which I first met in high school). > But this does more look like > South Park style shut eyes than an operator. :) lol, I agree, it looks too much like closed eye smiley. Forums might automatically convert them to graphic smileys so it is obviously a bad choice if it is to be used. From mail at timgolden.me.uk Fri Mar 28 17:53:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 28 Mar 2008 21:53:16 +0000 Subject: Finding Full Path to Process EXE In-Reply-To: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: <47ED68CC.7020404@timgolden.me.uk> misceverything at gmail.com wrote: > Hello, > > I would like to write a script that would enumerate all running > processes and return the full path to the EXE of each running > process. However, I can't seem to find any good info on how to do > this..any help is greatly appreciated. Thanks. I have this strange feeling of deja vu. Try this: http://timgolden.me.uk/python/wmi_cookbook.html#running_processes (You want the .ExecutablePath or .CommandLine attributes I imagine) TJG From aisaac at american.edu Sun Mar 2 16:05:11 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 02 Mar 2008 21:05:11 GMT Subject: tuples, index method, Python's design In-Reply-To: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> References: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> Message-ID: Paul Boddie wrote: > Here's the tracker item that may have made it happen: > http://bugs.python.org/issue1696444 > I think you need to thank Raymond Hettinger for championing the > cause. ;-) Yes indeed! Alan Isaac From craigm3604 at gmail.com Sat Mar 22 22:05:31 2008 From: craigm3604 at gmail.com (Craig) Date: Sat, 22 Mar 2008 19:05:31 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> Message-ID: <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> On Mar 22, 9:40 pm, Dennis Lee Bieber wrote: > On Sat, 22 Mar 2008 15:12:47 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > > > > > Anyway, I have the following for "types": > > LPBSTR = POINTER(c_void_p) > > HANDLE = POINTER(POINTER(c_long)) > > LPHANDLE = POINTER(HANDLE) > > LPSHORT = POINTER(c_short) > > LPVSTATS = POINTER(c_void_p) > > c_string = c_char_p > > LPSTR = c_string > > > I guess passing a structure is out of the question. So, I tried a > > string (something - just to get the data back): > > #short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS > > lpvstats); > > VmxInfo = windll.vbis5032.VmxInfo > > VmxInfo.restype = c_short > > VmxInfo.argtypes = [LPHANDLE, LPSTR] > > VsamInfo = create_string_buffer("12345678901234567890123456789012") > > printf ("VsamInfo = \x22%s\x22\n", VsamInfo.raw) > > print "Ready to call (Library = " + find_library("vbis5032") + ") ..." > > res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) > > And I get: > > Ready to call (Library = C:\Windows\vbis5032.dll) ... > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 101, in > > res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) > > ctypes.ArgumentError: argument 2: : wrong > > type > > Did you try just passing the buffer, rather than nesting a "byref" > > http://docs.python.org/lib/ctypes-passing-pointers.html > > Note how the string buffer parameter has NO odd games on it. This > especially applies to the other call below, for PriKey and the other > BSTR *... term > > As for passing a structure... Well, I'd suggest using struct.pack to > push arguments into such a structure (though it it is using pointers to > other items it may get tricky), using create_string_buffer to make the > Python string "structure" a C-memory block, passing that, and if needed, > struct.unpack the item after the call. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Based on your input, I changed: LPSTR = c_char_p VmxGet = windll.vbis5032.VmxGet VmxGet.restype = c_short VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), TypeDef ) printf ("After - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d \n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef.raw) I got back exactly what I expected for TypeDef, but SecKey and PriKey were what I initialized them to , not what should have been returned. Do you mean that I should change any string that is expected to be changed by the dll to a create_string_buffer type (LPSTR) instead of a windll.oleaut32.SysAllocStringByteLen type (LPBSTR) and then simply list it in the call instead of byref, as I did with TypeDef? Can it really be that simple? As for the structure: class VSTATS(Structure): _fields_ = [ ("nrecords", c_long), ("gps_used", c_short), ("gps_unused", c_short), ("max_key_len", c_short), ("grp_size", c_long), ("init_alloc", c_short), ("cr_opts", c_short), ("free_prop_area", c_short), ("format", c_void_p), ("reserved", c_void_p) ] vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) can I just use a create_string_buffer (LPSTR) and parse things up via substrings after the call returns? From gagsl-py2 at yahoo.com.ar Mon Mar 24 23:29:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 00:29:44 -0300 Subject: Python 2.2.1 and select() References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> <20080325020356.GF26870@dragontoe.org> Message-ID: En Mon, 24 Mar 2008 23:03:56 -0300, Derek Martin escribi?: > On Mon, Mar 24, 2008 at 05:52:54PM -0700, Noah wrote: >> On Mar 24, 2:58 pm, Derek Martin wrote: >> > If and only if the total amount of output is greater than the >> > specified buffer size, then reading on this file hangs indefinitely. You may try using two worker threads to read both streams; this way you don't care about the blocking issues. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Mar 3 02:15:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 05:15:27 -0200 Subject: Run Python app at startup References: Message-ID: En Sun, 02 Mar 2008 19:37:35 -0200, SMALLp escribi?: > Hy. > I create simple application. Yust an windows and "compile" it with > py2exe. I add registry value > reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run > /v > MyApp /t REG_SZ /d C:\myapp.exe /f' > > And it wont start. When i use console instead od window in py2exe i get > console opend but it closes. I'd check in this order: python prog.py Then, use console=... in setup.py, generate prog.exe Open a cmd window and execute prog.exe (from the dist directory) Repeat using window=... in setup.py That whole sequence works fine using on my WinXP SP2 + Python 2.5.1 + wxPython 2.8.7.1 -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 08:43:23 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 14:43:23 +0200 Subject: python ODF library? References: Message-ID: <659g7bF2f84eoU1@mid.individual.net> Matias Surdi wrote: > Do yo know any good OpenDocumentFormat library for python? > > I'm starting a project on wich I'll have to programatically modify > ODF text documments, so, after reinventing the wheel, I'd like to > know if already something exists. Probably this will help: http://wiki.services.openoffice.org/wiki/PyUNO_bridge Regards, Bj?rn -- BOFH excuse #327: The POP server is out of Coke From gagsl-py2 at yahoo.com.ar Thu Mar 6 17:01:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 20:01:46 -0200 Subject: system32 directory References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: En Thu, 06 Mar 2008 19:15:17 -0200, Robert Dailey escribi?: > On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden wrote: >> >> >>> import win32api >> >>> win32api.GetSystemDirectory () >> 'C:\\WINDOWS\\system32' > > I was aiming to figure out if the standard modules shipped with Python > could > do this already before I started using 3rd party libraries. Thanks. Use ctypes then: py> from ctypes import * py> windll.kernel32.GetSystemDirectoryA <_FuncPtr object at 0x00A0F918> py> GetSystemDirectory = windll.kernel32.GetSystemDirectoryA py> buffer = create_string_buffer(260) py> GetSystemDirectory(buffer, sizeof(buffer)) 19 py> buffer.value 'C:\\WINDOWS\\system32' -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 13 12:09:50 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 13 Mar 2008 11:09:50 -0500 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <-6101886065348230738@unknownmsgid> References: <47D94D61.9010708@jouy.inra.fr> <-6101886065348230738@unknownmsgid> Message-ID: 2008/3/13, Robert Rawlins : > > Hi Guys, > > Well thanks for the response, I followed your advice and chopped out all > the > crap from my class, right down to the bare __init__ and the setter method, > however, the problem continued to persist. > > However, Robert mentioned something about unindented lines which got me > thinking so I deleted my tab indents on that method and replaces them with > standard space-bar indents and it appears to have cured the problem. > > Usually my Eclipse IDE throws up an error about this but for some reason > decided not too this time around, what a PITA. > > Thanks for the ideas guys, I appreciate it. > > Robert > > -----Original Message----- > From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org > [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org > ] > On Behalf Of Robert Bossy > Sent: 13 March 2008 15:51 > To: python-list at python.org > Subject: Re: "Attribute Doesnt Exist" ... but.... it does :-s > > Robert Rawlins wrote: > > > > Hello Guys, > > > > I've got an awfully aggravating problem which is causing some > > substantial hair loss this afternoon J I want to get your ideas on > > this. I am trying to invoke a particular method in one of my classes, > > and I'm getting a runtime error which is telling me the attribute does > > not exist. > > > > I'm calling the method from within __init__ yet it still seems to > > think it doesn't exist. > > > > Code: > > > > # Define the RemoteDevice class. > > > > class *remote_device*: > > > > # I'm the class constructor method. > > > > def *__init__*(/self/, message_list=/""/): > > > > /self/.set_pending_list(message_list) > > > > def *set_pending_list*(/self/, pending_list): > > > > # Set the message list property. > > > > /self/.pending_list = message_list > > > > And the error message which I receive during the instantiation of the > > class: > > > > File: "/path/to/my/files/remote_device.py", line 22, in __init__ > > > > self.set_pending_list(message_list) > > > > AttributeError: remote_device instance has no attribute > 'set_pending_list' > > > > Does anyone have the slightest idea why this might be happening? I can > > see that the code DOES have that method in it, I also know that I > > don't get any compile time errors so that should be fine. I know it > > mentions line 22 in the error, but I've chopped out a load of non > > relevant code for the sake of posting here. > > > Hi, > I don't get this error if I run your code. Maybe the irrelevant code > causes the error: my guess is that there's a parenthesis mismatch or an > undeindented line. > > Btw, calls to set_pending_list will fail since the name "message_list" > is not defined in its scope. Please follow Chris Mellon's advice. > > Cheers, > RB > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list All the more reason to use VIM and set it to auto-indent / remove 4 spaces with tab & backspace. =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Mar 6 09:24:29 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 06 Mar 2008 15:24:29 +0100 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <63ad4tF26o96fU1@mid.individual.net> Guillermo wrote: > I'm just designing the algorithm, but I think Python dictionaries > can hold any kind of sequence? (Watch out, dicts are no sequence types.) I recommend relying duck typing as long as it's feasible. I. e. if it can be subscripted like a dict, it is a dict. If this makes problems, use the type({}) approach. Regards, Bj?rn -- BOFH excuse #56: Electricians made popcorn in the power supply From solisgb at gmail.com Wed Mar 12 03:52:17 2008 From: solisgb at gmail.com (luis) Date: Wed, 12 Mar 2008 00:52:17 -0700 (PDT) Subject: unable to install gdal References: <15838144-b7a0-4d1b-98b3-fdfcfdb9a916@n75g2000hsh.googlegroups.com> <86d8bc35-24d5-4145-8421-94d71066209d@60g2000hsy.googlegroups.com> Message-ID: <42b6735f-476d-4da0-9465-3867d1f0d41c@v3g2000hsc.googlegroups.com> On 10 mar, 09:49, luis wrote: > On 9 mar, 16:37, luis wrote: > > > > > Hi > > > On Windows xp sp2 and python 2.4 > > > Yesterday I running old versions of gdal, and I try to upgrade > > > I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe > > I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 > > > I follow install's instructions fromhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython, > > all is ok, I set path and path_data variables with correct values, but > > whe I run a script, an error raises > > > from osgeo import ogr > > File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? > > import _ogr > > ImportError: DLL load failed: process not found > > > Also I try with instructions fromhttp://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gda... > > I move _gdal.pyd (and the others *.pyd) from my Python installation's > > (C:\Python24\Lib\site-packages\osgeo) into my Python installation's > > DLLs folder (C:\Python24\DLLs). > > When I run the script the error message persists. > > > Some help is welcome. > > If I install on a XP without previous installation of gdal, the > installation works fine. > > Perhaps is a problem with XP's registry If I run the script in the dos line command (>> python script_name.py) a final windows error's message says curls_multi_cleanup pocedure don`t find entry point in libcurl.dll I have found 2 programs using other versions libcurl.dll In the PATH environment variable I insert C:\gdalwin32-1.5\bin before paths those programs, and the error has disappeared From HMartin1 at gmx.net Fri Mar 28 16:13:00 2008 From: HMartin1 at gmx.net (Hans Martin) Date: Fri, 28 Mar 2008 21:13:00 +0100 Subject: Problem with format string and unicode Message-ID: <20080328201300.118730@gmx.net> Hi, this is probably a trivial problem, but a google search for "python" and "unicode" and" format string" gives too many hits: If I specify e.g. "%20s" in a format string and the string value contains UTF-8 stuff (differing number of bytes per character), the length of the resulting string (in characters) varies. How can I fix this? Many thanks in advance! -- Psssst! Schon vom neuen GMX MultiMessenger geh?rt? Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger From gagsl-py2 at yahoo.com.ar Fri Mar 28 18:25:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 19:25:50 -0300 Subject: Problem with format string and unicode References: <20080328201300.118730@gmx.net> Message-ID: En Fri, 28 Mar 2008 17:13:00 -0300, Hans Martin escribi?: > this is probably a trivial problem, but a google search for "python" > and "unicode" and" format string" gives too many hits: If I specify > e.g. "%20s" in a format string and the string value contains UTF-8 > stuff (differing number of bytes per character), the length of the > resulting string (in characters) varies. How can I fix this? py> x = u"?a?o ?nico!" py> len(x) 11 py> len(x.encode("utf-8")) 14 py> f = u"%20s" % x py> f u' \xa1a\xf1o \xfanico!' py> print f ?a?o ?nico! py> len(f) 20 py> len(f.encode("utf-8")) 23 -- Gabriel Genellina From mr.cerutti at gmail.com Thu Mar 6 10:25:07 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 6 Mar 2008 10:25:07 -0500 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <51302a8c0803060725v4baa4033jea2c033730a64742@mail.gmail.com> On Thu, Mar 6, 2008 at 8:06 AM, Guillermo wrote: > I want to iterate recursively a dictionary whose elements might be > strings or nested tuples or dictionaries and then convert values to a > tagged format according to some rules. > > d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y': > ('a','b','c')}} This could be solved with dynamic polymorphism instead of introspection, which might simplify things depending on how your dictionary is constructed. class Value(object): def to_tagged_format(self): raise NotImplementedError class StringValue(Value): def to_tagged_format(self): ... class Tuplevalue(Value): def to_tagged_format(self): ... class DictValue(Value): def to_tagged_format(self): ... for k, v in d.iteritems(): d[k] = v.to_tagged_format() You can also get the dynamic polymorphism without invoking inheritance by specifying a protocol that the values in your dict must implement, instead. Protocols are plentiful in Python, perhaps more popular than type hierarchies. -- Neil Cerutti From martin at v.loewis.de Sat Mar 1 17:26:10 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Mar 2008 23:26:10 +0100 Subject: [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> Message-ID: <47C9D802.2090205@v.loewis.de> > As of 4:50 PM EST, the links to Windows installers give 404 File Not > Found. > > I gather that they are still in process, > and notice that there is no public c.l.p. announcement. I just fixed that. The files were there; just the links were wrong. Regards, Martin From jorgen.maillist at gmail.com Mon Mar 17 08:21:50 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 17 Mar 2008 13:21:50 +0100 Subject: comtypes question In-Reply-To: References: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> Message-ID: <11e49df10803170521w7c041c71l7d8e26c259bd9b95@mail.gmail.com> Hi Thomas, Thank you a lot for going through great lenghts to help me. I am relatively new to COM and to python, so using those two together is sometimes watching water burn and be totally amazed by it ;-) It's greatly aprpeciated that you installed the app and even checked out the typelib to see what might go wrong. I will investigate furter and look at your working example to see what I was missing in my code. I will also subscribe to the comtypes-users mailinglist for future questions. ps. For background info about Bartender, it is a label application and it can be automated by COM. By sending an XML script to it, I can set the variables for that label and issue a print command. With kind regards, - Jorgen On Mon, Mar 17, 2008 at 12:58 PM, Thomas Heller wrote: > Jorgen Bodde schrieb: > > > > Hi All, > > > > I am trying to automate a 3rd party application, and all I have to > > work on is the type library and some documentation. I hope a Python / > > COM guru can answer this or put me on the right path because I don't > > know why it does not work. > > > > First I imported the typelib with comtypes like; > > > >>> from comtypes.client import GetModule > >>> GetModule("C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe") > > > > Which blurbs out a lot of text: > > > > # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1 > > # Generating comtypes.gen.BarTender > > > 'C:\Python24\lib\site-packages\comtypes\gen\_D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1.pyc'> > > > > Which seems to be ok. Now, I need to call a function on the > > Application object on which I need a "Messages" instance. The > > Application object gets created properly: > > > >>> import comtypes.gen.Bartender as bt > >>> app = comtypes.client.CreateObject(bt.Application) > > > > Which gives me the application (the bt.Application points to a wrapper > > class containing the CLSID of the COM class to be instantiated). > > > > Now I browse the typelibrary and I see there is a CoClass called > > Messages. I need one of those to pass as an argument, and since > > Messages is listed as a CoClass similar to Application, I assume it > > can also be instantiated. But when I try this I get an error: > > > >>>> msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}') > > [...] > > > > WindowsError: [Errno -2147221164] Class not registered > > > > Both Application and Messages are listed as CoClass inside the > > typelibrary. Does anybody know why it gives me this error and what I > > am doing wrong? > > Not all coclasses can be created from scratch with CreateObject. Sometimes > they are created by calls to methods on some other object. > I downloaded the bartender trial, and looking into the typelib it seems that, > for example, the 'XMLScript' method on the IBtApplication interface returns > Messages instances: > COMMETHOD([dispid(17), helpstring(u'Runs xml scripts')], HRESULT, 'XMLScript', > ( ['in'], BSTR, 'XMLScript' ), > ( ['in'], BtXMLSourceType, 'SourceType' ), > ( ['out'], POINTER(POINTER(Messages)), 'Messages' ), > ^^^^^^^^ > ( ['retval', 'out'], POINTER(BSTR), 'retval' )), > > Here is an interactive session: > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from comtypes.gen import BarTender > >>> from comtypes.client import CreateObject > >>> app = CreateObject(BarTender.Application) > >>> print app > > >>> app.XMLScript("foo", 0) > (, u'') > >>> msg, retval = app.XMLScript("foo", 0) > >>> print msg > > >>> msg[0] > > Traceback (most recent call last): > File "", line 1, in > File "comtypes\__init__.py", line 308, in __getitem__ > result = self.Item(index) > _ctypes.COMError: (-2147220992, None, (u'The item at position 0 was not found.', u'bartend', None, 0, None)) > >>> msg[1] > > >>> m = msg[1] > >>> print m > > >>> m.Number > 3908 > >>> m.Message > u"An error occurred during XML script processing:\r\n\r\nInvalid at the top level of the document.\r\nLine 1, Column 1: > 'foo'" > >>> ^Z > > Not that the above makes much sense, but I hope it will get you started. > > Thomas > > BTW: The 'official' comtypes mailing list is at > https://lists.sourceforge.net/lists/listinfo/comtypes-users. Requires that you subscribe before you can > post, but you could disable mail delivery and use via gmane: gmane.comp.python.comtypes.user > > -- > http://mail.python.org/mailman/listinfo/python-list > From cmpython at gmail.com Sat Mar 22 03:10:22 2008 From: cmpython at gmail.com (CM) Date: Sat, 22 Mar 2008 00:10:22 -0700 (PDT) Subject: wxFormBuilder References: Message-ID: <7152b94f-fc30-473f-bd94-5d43a9153f56@p73g2000hsd.googlegroups.com> On Mar 20, 9:41 am, sturlamolden wrote: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed,Boa > constructor), this is the first one I can actually use. Why can't you use Boa Constructor? I really enjoy using it. From castironpi at gmail.com Fri Mar 28 15:20:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 12:20:22 -0700 (PDT) Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <5f8f15f4-36b7-49ce-bce6-521e76603054@y21g2000hsf.googlegroups.com> On Mar 28, 10:15?am, harryos wrote: > > The code is pretty legible as it is now. Anyway, using min() and a > > generator: > > hi > is this calculated distance really Euclidean distance? When i checked > wikipediahttp://en.wikipedia.org/wiki/Euclidean_distance > it shows a calculation involving sum of squares of the differences of > elements.Here in this code ,the sum of coordinates are used? is that a > different measure? I want the angle into an array. > < sign bit on distance to [zero element/kernel]. Are you coming out in uni-pole and/or lensed/focused/ parabolaed? Is that a yes-or-no question? From fkallgren at gmail.com Fri Mar 21 07:48:33 2008 From: fkallgren at gmail.com (fkallgren) Date: Fri, 21 Mar 2008 04:48:33 -0700 (PDT) Subject: Is this doable Message-ID: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Hi. I have a little problem. I have a script that is in the scheduler (win32). But every now and then I update this script and I dont want to go to every computer and update it. So now I want the program to 1) check for new version of the script, 2) if there is a new version, copy that verision from server to local drive, 3) shutdown the program and start it up again as the new version. The problem is that I can't run this script directly from server so it have to run it locally. Anyone having any bright ideas?? /fkallgren From paul at boddie.org.uk Thu Mar 20 21:28:28 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 20 Mar 2008 18:28:28 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <75fcc319-1f4b-4d24-8de6-7b1c56929fb0@8g2000hsu.googlegroups.com> On 21 Mar, 01:43, Simon Forman wrote: > > I've been thinking of volunteering to "port" Tkinter to Python 3.0, I > hadn't noticed that there was any discussion of removing it. That's because the forum for discussing these things wasn't mentioned on comp.lang.python until two days ago. Perhaps we're also about to find out that the Vogons are showing up shortly. Paul From castironpi at gmail.com Tue Mar 4 23:09:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:09:38 -0800 (PST) Subject: is there enough information? References: <13s9u7dg24es73a@corp.supernews.com> <13spkb990ha3v6c@corp.supernews.com> Message-ID: <392cadeb-e1f8-4cef-834c-a837ba7e02f5@59g2000hsb.googlegroups.com> On Mar 4, 5:59?pm, David Bolen wrote: > Dennis Lee Bieber writes: > > > > > > > On Mon, 3 Mar 2008 08:11:43 -0500, Jean-Paul Calderone > > declaimed the following in comp.lang.python: > > >> I'm not sure, but you seem to be implying that the only way to use Windows' > >> asynchronous I/O APIs is with threads. ?Actually, it is possible (and Twisted > >> allows you) to use these as well without writing a threaded application. > > > ? ?I only pointed out that, on Windows, one can not use the common > > /select()/ function with files. And one rarely sees examples of coding a > > Twisted-style (emphasis on style) asynchronous callback system mixing > > files and network sockes using the Windows-specific API. > > > ? ?If using threads, the Windows asynchronous I/O isn't needed... let > > the thread block until the I/O completes, then transfer the data (or a > > message that the data is available) back to the main processing > > thread... > > You're probably right that it's rare, but when needed, using the > Windows asynchronous/overlapping API can provide a better solution > than blocking threads depending on the needs at hand, and without > involving any callbacks or Twisted-style programming. > > An example of mine is high performance serial port handling as part of > a custom FHSS wireless adapter with a serial port interface to the PC. > In this case, minimizing I/O latency was crucial since delays could > mean missing a broadcast timeslot (about 15ms) on the wireless > network. ?A serial port isn't a disk file, but certainly a "file" in > the context of Windows handles. > > Early implementations used independent threads for reading/writing to > the serial port and blocking during such operations, but that turned > out to have an undesirable amount of latency, and was also difficult > to interrupt when the threads were in a blocked condition. > > Instead I created a single thread that had a loop using overlapped I/O > simultaneously in each direction as well as native Windows event > objects for aborting or signaling that there was additional data to be > written (the pending read I/O handled the read case). ?The main loop > was just a WaitForMultipleObjects to handle any of the I/O completion > indications, requests for more I/O or aborts. ?It was very high > performing (low latency) with low CPU usage - measurably better than a > multi-threaded version. > > Communication with the rest of the application was through a > thread-safe bi-directional buffer object, also using native Win32 > event objects. ?It worked similar to a queue, but by using the native > event objects I didn't have the performance inefficiencies for reads > with timeouts of the Python objects. ?The underlying Python primitives > don't have the timeout capability built in, so reads with timeouts get > implemented through checks for data interspersed with increasing > sleeps, which adds unnecessary latency. > > Anyway, it worked extremely well, and was a much better fit for my > needs than a multi-threaded version with blocking I/O, without it > having to be Twisted-style. > > -- David- Hide quoted text - > > - Show quoted text - How does it work? From reading threading.py, _Condition.wait() acquires self.lock() too many times-- that is, once to call wait ("cannot wait on un-aquired lock"), and once after--- are "all waiters" waiting back at self.acquire, just to make it to self.notify... and only one at a time at that!? Don't waiters have to release before another waiter can go? From grante at visi.com Fri Mar 21 18:59:02 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Mar 2008 22:59:02 -0000 Subject: Subprocess and /usr/bin/dialog References: Message-ID: <13u8fdmq9hnsh06@corp.supernews.com> On 2008-03-21, harrelson wrote: > I am trying to get the below code to work and can't quite make things > happen. This is with Python 2.5.1. Dialog is doing something odd... > I have tinkered with different combinations and I can't get the dialog > to show properly-- it does show properly directly in the shell. Any > hints? > > import subprocess > command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 > 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" > "4 this and that"' > proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, > stderr=subprocess.STDOUT) > #proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) > stderr_value = proc.communicate()[0] > print stderr_value [It would be helpful if you didn't wrap sample code when you post it.] dialog displays the widget on stdout. You've connected stdout to a pipe, so you're not going to see anything displayed unless you read data from the stdout pipe and write it to the terminal. -- Grant Edwards grante Yow! Boy, am I glad it's at only 1971... visi.com From steve at holdenweb.com Mon Mar 31 06:35:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 06:35:48 -0400 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: Pradeep Rai wrote: > Hi All, > > I have upgraded python v2.5.2 from python v2.4.3. The upgradation > results into following error: > "Python C API version mismatch for module dbi: This Python has API > version 1013, module dbi has version 1012." > > Please suggest, how to resolve this error to proceed further. > > Regards, > Pradeep Rai > > Don't try and drag 2.4 extension modules into the 2.5 environemnt. You will have to install a 2.5 version of dbi for it to work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fakeaddress at nowhere.org Sun Mar 23 22:45:54 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 23 Mar 2008 19:45:54 -0700 Subject: Testing for an empty dictionary in Python In-Reply-To: References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: D'Arcy J.M. Cain wrote: > John Nagle wrote: >> What's the cheapest way to test for an empty dictionary in Python? > Try this: > > if dict: D'Arcy is right; that's the way to go. I'll add that 'dict' is the name of the built-in class, so an instance is usually best named something else. -- --Bryan From castironpi at gmail.com Sun Mar 9 18:34:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 15:34:19 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6d3lppl8lv2a@corp.supernews.com> Message-ID: > > >> Good comments are better than bad names. Good names are better than bad > > >> comments. > > > > If you're taking the time to write good comments, why not just fix the > > > bad names? ?The compiler/interpreter can never, ever catch bad comments. > > > Yes, but the Python compiler can only catch bad names if you do this at > > the top of every module: > > > import semantic_analysis > > import magic.crystal_ball.read_programmers_mind > > dir( magic )! > dir( magic.crystal_ball )? Someone should try annotating code with a dictionary lookup on identifiers. Anyone bored on Fridays? No one should try printing out the definitions in real-time as the code is executing. From gnewsg at gmail.com Mon Mar 24 14:34:23 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Mon, 24 Mar 2008 11:34:23 -0700 (PDT) Subject: Impersonate another user (Guest) on Windows Message-ID: <14cfc3e7-f07b-465c-99f9-8c3082047a12@u10g2000prn.googlegroups.com> Hi, I'm trying to write a plug-in for a ftp server of mine to permit the integration with accounts defined on the Windows system. What I basically need is impersonating a user, execute e filesystem call (e.g. create a directory via os.mkdir()) and then switch back to the original user (Administrator). I wrote down this simple class which seems to fit pretty well for my purposes: class WinNTAuthorizer: def impersonate_user(self, username, password): self.impersonated_user_handler = win32security.LogonUser( username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(self.impersonated_user_handler) def terminate_impersonation(self): win32security.RevertToSelf() self.impersonated_user_handler.Close() What I need now is impersonating the Guest user to handle the anonymous logins (which it's exactly what IIS FTPd does) but I don't know how to do it. Does Guest account has a password or do I have to use something different than LogonUser to manage it? Could someone point me in the right direction? Thanks in advance. --- Giampaolo http://code.google.com/p/pyftpdlib From harrelson at gmail.com Sat Mar 22 11:41:40 2008 From: harrelson at gmail.com (harrelson) Date: Sat, 22 Mar 2008 08:41:40 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> Message-ID: <9d220cde-e456-47d6-a9ba-b835812c870a@s12g2000prg.googlegroups.com> > > [It would be helpful if you didn't wrap sample code when you > post it.] > > dialog displays the widget on stdout. You've connected stdout > to a pipe, so you're not going to see anything displayed unless > you read data from the stdout pipe and write it to the terminal. Also... if I put the dialog call in a one line shell script and execute it with: subprocess.call('dialog.sh') it works properly. From python.list at tim.thechases.com Tue Mar 11 09:45:26 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Mar 2008 08:45:26 -0500 Subject: parsing directory for certain filetypes In-Reply-To: <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> Message-ID: <47D68CF6.7020203@tim.thechases.com> royG wrote: > On Mar 10, 8:03 pm, Tim Chase wrote: > >> In Python2.5 (or 2.4 if you implement the any() function, ripped >> from the docs[1]), this could be rewritten to be a little more >> flexible...something like this (untested): >> > > that was quite a good lesson for a beginner like me.. > thanks guys > > in the version using glob() >> path = os.path.normpath(os.path.join(folder, '*.txt')) >> lst = glob.glob(path) > > is it possible to check for more than one file extension? here i will > have to create two path variables like > path1 = os.path.normpath(os.path.join(folder, '*.txt')) > path2 = os.path.normpath(os.path.join(folder, '*.doc')) > > and then use glob separately.. Though it doesn't use glob, the 2nd solution I gave (the one that uses the any() function you quoted) should be able to handle an arbitrary number of extensions... -tkc From hiteshthakkar.h at gmail.com Tue Mar 11 13:53:29 2008 From: hiteshthakkar.h at gmail.com (hitesh thakkar) Date: Tue, 11 Mar 2008 23:23:29 +0530 Subject: XML-SAX parser problem Message-ID: <5ae40d820803111053q6bcdde19s6ad34ecb9b8bbc25@mail.gmail.com> Hello, Can any one help for error in following code. actually i want to map parent element with child element, but i am unable to do so. here is the code which i am trying for please do reply if iam not on right track. import xml.sax.handler class BookHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inTitle1 = 0 self.inTitle2 = 0 self.mapping1 = {} self.mapping2 = {} def startElement(self, name, attributes="NULL"): #attributes="None" if name == "emph3": self.buffer1 = "" self.inTitle1 = 1 # self.id = attributes["None"] elif name == "year": self.buffer2 = "" self.inTitle2 = 1 def characters(self,data): if self.inTitle1 == 1: self.buffer1 += data elif self.inTitle2 == 1: self.buffer2 += data def endElement(self,name): if name == "year": self.inTitle2 = 0 self.mapping2[self.name] = self.buffer2 elif name =="emph3": self.inTitle1 =0 self.mapping1[self.name] = self.buffer1 # # # Jose Joaquin Avila # 1929 # # Yiye Avila # 1941 # # -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert_rawlins at hotmail.com Mon Mar 24 11:12:28 2008 From: robert_rawlins at hotmail.com (Robert Rawlins) Date: Mon, 24 Mar 2008 15:12:28 +0000 Subject: Element Tree Help Message-ID: Hello Guys,I have little to no experiance with element tree and I'm struggling to find a way to parse the details from the XML document (attached) into my application. Essentialy I'm looking to take the following document and turn it into a dict of tuples, each dict element defines a datasource with the key to the element being the 'name' which is defined in the XML and then the value of the pair is a tuple which contains the details of the datasource, like the host and port etc.I've attached a copy of the example XML to this email.Can anyone offer some advice on how to get started with this? I've spent a little time looking over the documentation of element tree and have struggled to break the ice and parse this document.Thanks guys,Robert _________________________________________________________________ The next generation of Windows Live is here http://www.windowslive.co.uk/get-live -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: datasources.txt URL: From python at bdurham.com Sat Mar 15 08:06:39 2008 From: python at bdurham.com (Malcolm Greene) Date: Sat, 15 Mar 2008 08:06:39 -0400 Subject: Python for Palm OS In-Reply-To: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Message-ID: <1205582799.12820.1242548149@webmail.messagingengine.com> E-Lo, PalmPython ???? http://c2.com/cgi/wiki?PalmPython I have no experience with Python for Palm OS's. This is just a reference from my personal notes. Malcolm From pradiprai at gmail.com Fri Mar 14 09:31:40 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Fri, 14 Mar 2008 19:01:40 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave_mikesell at fastmail.fm Mon Mar 3 07:17:37 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Mon, 3 Mar 2008 04:17:37 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: <6c90f26b-e7b7-4048-bf98-ef5ed5bba462@u72g2000hsf.googlegroups.com> On Mar 1, 10:53 pm, Kay Schluehr wrote: > On 1 Mrz., 19:51, Barry Warsaw wrote: > > > Python 2.6 is not only the next advancement in the Python 2 series, it > > is also a transitionary release, helping developers begin to prepare > > their code for Python 3.0. > > Isn't this a silly idea? People have to migrate from 2.5 or lower > releases to Python 2.6 first just to migrate to Python 3.0? What are > the inherent / technical reasons that prevent migration directly from > 2.5 to 3.0? Not only that, you have to wait for your library providers to migrate first (PyOpenGL, PyGame, PIL, etc for me). Hopefully this is the last quantum shift for a while. From shakefu at gmail.com Fri Mar 7 17:10:57 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:10:57 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <9a07507e-b8eb-440c-92af-62278cd36b5e@d62g2000hsf.googlegroups.com> On Mar 7, 4:08 pm, shak... at gmail.com wrote: > I'm new to python and I was wondering if there are any intelligent > date/time parsing modules out there. I've looked at strptime (or > whichever it is) and mxDateTime from the eGenix package. I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. > > So are there any modules that allow for that kind of parsing? I forgot to say, thanks ahead of time, and I'd appreciate any direction that you can give me! (How rude of me!) - Jacob Alheid From rakesh.usenet at gmail.com Sun Mar 2 14:56:32 2008 From: rakesh.usenet at gmail.com (Rakesh Kumar) Date: Sun, 2 Mar 2008 11:56:32 -0800 (PST) Subject: cx_Freeze : LookupError: unknown encoding: ascii References: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> <47c9e9bc$0$4562$9b622d9e@news.freenet.de> Message-ID: <5ecd5295-1570-45d2-9dcc-39425523fa2e@s19g2000prg.googlegroups.com> On Mar 1, 3:41?pm, "Martin v. L?wis" wrote: > > Can somebody point to some clues about options that need to be passed > > to FreezePython API to get the right executable. > > You need to tell it to include the encodings.ascii module. > > Regards, > Martin Thanks Martin. Adding something like ./freeze --include-modules=encodings.ascii,encodings.utf_8 fixed the issue. From lipun4u at gmail.com Tue Mar 11 15:17:14 2008 From: lipun4u at gmail.com (asit) Date: Tue, 11 Mar 2008 12:17:14 -0700 (PDT) Subject: mulithreaded server References: Message-ID: <0e845694-2788-43e2-b88b-86bbbbe3c7c0@e23g2000prf.googlegroups.com> On Mar 11, 9:10 pm, Jean-Paul Calderone wrote: > On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit wrote: > >import socket > >import sys > >import thread > > >p=1 > >PORT=11000 > >BUFSIZE=1024 > > >def getData(cSocket): > > global stdoutlock,cSocketlock > > while True: > > cSocketlock.acquire() > > data=cSocket.recv(BUFSIZE) > > if data=='q': > > data='client exited' > > cSocket.close() > > p=0 > > cSocketlock.release() > > stdoutlock.acquire() > > stdout.write(data) > > stdoutlock.release() > > >def sendData(cSocket): > > global stdoutlock,cSocketlock > > while True: > > stdoutlock.acquire() > > data=raw_input('>>') > > cSocketlock.acquire_lock() > > if data=='q': > > stdout.write('server exited') > > stdout.release() > > p=0 > > cSocket.close() > > sSocket.send(data) > > sSocketlock.release() > > Could it be because `sSocketlock? here > > > > >stdout=sys.stdout > >host='' > >sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > >sSocket.bind((host,PORT,)) > >sSocket.listen(1) > >#sSocketlock=thread.allocate_lock() > > is never bound since the line above here is commented out? > > >stdoutlock=thread.allocate_lock() > >print 'waiting for connection' > >cSocket,addr=sSocket.accept() > >print 'connection from',addr > >cSocketlock=thread.allocate_lock() > >thread.start_new_thread(sendData,(cSocket,)) > >thread.start_new_thread(getData,(cSocket,)) > >if p==0: > > sSocket.close() > > >In the above program, why there is an unhandeled exception ??? > > Just a guess. You should really include the traceback when you ask a > question like this. > > Jean-Paul It's not a traceback error. It's an unhandeled exception..please help From larry.bates at websafe.com` Tue Mar 25 10:57:20 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 25 Mar 2008 09:57:20 -0500 Subject: Reading new mail from outlook In-Reply-To: References: <315315.36624.qm@web50108.mail.re2.yahoo.com> Message-ID: Tim Golden wrote: > SPJ wrote: >> I am trying to create new tickets in the ticketing system using >> python. When I receive new email from a particular address, I have to >> trigger the python script and parse the mail in required format. >> >> The main hurdle here is, how to invoke the script on arrival of new >> mail? I checked the outlook settings and found that it supports only >> microsoft VB script and Jscript. Is there any other way? I mean, if I >> make a daemon, how will it be notified of new mail? Is there any >> python module that does this? >> >> I am not sure if this is the right place to ask this, since it is also >> a microsoft related question. But any help is appreciated. > > Outlook does have some events in its automation interface > (which you can handle from within Python by using > win32com.client.DispatchWithEvents) but if an immediate response > weren't critical it's probably slightly easier to schedule a job > to interrogate the mailbox every so often and harvest any new > emails. Depends on your particular need. > > TJG Best way I can think of is to get a copy of SpamBayes source code and see how it is done there. Much easier to look at something that already looks at new messages as they arrive in the Inbox than to try to figure it out. http://spambayes.sourceforge.net/windows.html -Larry From bbxx789_05ss at yahoo.com Tue Mar 18 23:58:06 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 18 Mar 2008 20:58:06 -0700 (PDT) Subject: Need Help Starting Out References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <9a2df924-99b0-4dd1-b5b7-5e0fca17dc04@e39g2000hsf.googlegroups.com> On Mar 18, 10:10?am, jmDesktop wrote: > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. ? I think you are getting ahead of yourself. Get the book Learning Python(3rd edition), which just came out, and start at the beginning. I think the proper order is to learn the basics first, then learn an application of the language that you are interested in, i.e. web programming. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:32:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:32:03 -0000 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> <13t2cget4hubma9@corp.supernews.com> Message-ID: <13t6c03hs3bg067@corp.supernews.com> On Sat, 08 Mar 2008 09:52:41 -0800, castironpi wrote: > On Mar 7, 6:16?am, Steven D'Aprano cybersource.com.au> wrote: >> On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote: >> > you >> > could say exec( open( 'modA.py' ).read() ) ==> import modA >> >> Yes, you could say that, but you'd be wrong. Please test your code >> before making such claims in the future. > > Aye aye. -1 response not phrased in the form of a question. All the words in that sentence are English, but as a whole it makes no sense. > Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA > import * create "effectively" same results, You're getting closer now. (By the way, exec is a statement, so you don't need brackets around its arguments.) exec open('modA.py').read() gives *almost* the same results as from modA import * The differences I can think of: (1) The exec version doesn't cache the results, so if you execute the line repeatedly you will execute the same code over and over again, possibly causing unexpected side-effects. import caches the results, and so will be faster. (2) The import version may read from modA.pyc, modA.pyo or modA.so even if there is a modA.py file. The exec version can't import from anything but modA.py. (3) The exec version as written always puts the results in the global scope, even if you execute it inside a function. (In the future, "from modA import *" will be forbidden inside functions, but at the moment it is still legal.) (4) The exec version doesn't search sys.path for modA; import does. (5) The exec version can't read modules inside a zip file; import can. There may be other differences I haven't thought of. > such as in the remaning > program not checking __module__ attributes? Again, I don't understand what you are saying. > Is there a slight modification of both sides that does cover a non- > trivial volume of programs, such as maybe, exec( open( 'modA.py' > ).read(), locals= dict( __module__= 'modA' ) ) - and- from modA import > *, or something? *Slight* modification, no. I'm sure that with sufficient effort, you could add caching, search sys.path, and look inside zip files. Those three things wouldn't be horribly difficult, but it wouldn't be a one-liner -- off the top of my head, I'd guess fifty to a hundred lines of code to re-invent those particular wheels correctly. However, recreating the rest of the import mechanism would be terribly complicated. I'm not really sure it could be done. For example, how would you deal with modules written in C from within Python? You'd need access to Python internals that, as far as I know, aren't available. -- Steven From goon12 at gmail.com Tue Mar 11 11:04:42 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 11 Mar 2008 11:04:42 -0400 Subject: difference b/t dictionary{} and anydbm - they seem the same In-Reply-To: <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> Message-ID: <6a2ccd190803110804u76cb06edkb54d6f951b045494@mail.gmail.com> On Tue, Mar 11, 2008 at 10:58 AM, davidj411 wrote: > Thanks, that makes sense. Are there any local relational databases > available to python that don't require a server backend? sqlite http://www.sqlite.org/ From grante at visi.com Thu Mar 20 17:25:26 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 21:25:26 -0000 Subject: Code folder with Emacs Message-ID: <13u5li6kspler51@corp.supernews.com> Has anybody figured out how to do code folding of Python source files in emacs? I tried "hide-show" minor mode, but it doesn't really work for Python code: the only think it knows how to hide/show are function bodies. It can't do normal things like hide/show a code block like it can for other languages. Google also found my "folding mode", but that's based on user-inserted tokens and isn't syntax aware. -- Grant From rodmena.com at gmail.com Wed Mar 12 12:35:07 2008 From: rodmena.com at gmail.com (Farsheed Ashouri) Date: Wed, 12 Mar 2008 09:35:07 -0700 (PDT) Subject: Py2exe and Multi Treading problem. References: Message-ID: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> NO it dont work. If I remove threading part, it works like a charm. Any Idea? From arnodel at googlemail.com Thu Mar 13 15:13:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 12:13:19 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> Message-ID: On Mar 13, 10:42?am, Paul Rubin wrote: [...] > By Python convention, methods that mutate the object return None, and > also stuff that returns None doesn't generate output at the > interactive prompt. A convention that does not always hold: >>> l = [1, 2, 3] >>> l.pop() 3 >>> l [1, 2] >>> There is also the .next() method: >>> i = iter([1, 2, 3]) >>> i.next() 1 >>> i.next() 2 >>> I can't think of others ATM in python 2.x but there might be some. Moreover PEP 3119 introduces .add(), .discard(), .toggle() for MutableSets which all mutate self and return a non None object. -- Arnaud From danb_83 at yahoo.com Sat Mar 8 20:27:32 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 8 Mar 2008 17:27:32 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 1:31 pm, Grant Edwards wrote: ... > > What I really can't stand are the pointy-haired comment blocks > at the beginnings of C/C++ functions that do things like tell > you the name and return type of the function and list the names > and types of the parameters. Gee, thanks. I never could have > figured that out from looking at the source code itself. IMO, > comments explaining what the parameters are used for usually > indicates that the parameter names were poorly chosen. You must work for the same company I do. I've seen a whole bunch of comments that look like: //--------------------------------------------------------------------------- // CXyzBase::LogMessage // // Write a message to the log. // // Args: // strMsg = the message to log // void CXyzBase::LogMessage(const CString& strMsg) { // } And even worse, at the top of that file: //--------------------------------------------------------------------------- // XyzBase.cpp // // This file contains the implementation of class CXyzBase. // // Copyright (C) 2008 Foobar Computer Consulting // // VERSION PROJECT# DATE DESCRIPTION // ------- -------- -------- ------------------ // 1.00 123456 01/04/08 Original creation. // Eleven lines, of which the only useful information to me was the project number, as knowing this let me look up who was behind these comments. From nkavitha551 at gmail.com Thu Mar 6 05:58:49 2008 From: nkavitha551 at gmail.com (nkavitha551 at gmail.com) Date: Thu, 6 Mar 2008 02:58:49 -0800 (PST) Subject: Your Fortune for the Day!!! Message-ID: <600833ea-38d6-43e0-9d7c-d867c37aa664@i29g2000prf.googlegroups.com> Hi, To know what it is? Visit the website below and be cool !!! ------------------------------------------------------------------------------ http://myprofilekavitha.blogspot.com/ ------------------------------------------------------------------------------- From bernard at blimyk.org Mon Mar 17 02:23:41 2008 From: bernard at blimyk.org (Bernard Lim) Date: Mon, 17 Mar 2008 06:23:41 +0000 (UTC) Subject: Immutable and Mutable Types Message-ID: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> Hi, I'm reading the Python Reference Manual in order to gain a better understanding of Python under the hood. On the last paragraph of 3.1, there is a statement on immutable and mutable types as such: Depending on implementation, for immutable types, operations that compute new values may or may not actually return a reference to any existing object with the same type and value, while for mutable objects this is (strictly)? not allowed. Using the example given in 3.1, how do I verify that this is true pertaining to immutable types? Below is my understanding on verifying the above statement: >>> a = 1 >>> b = 1 >>> a is b True >>> id(a) 10901000 >>> id(b) 10901000 Is this correct? Regards Bernard From bronger at physik.rwth-aachen.de Sun Mar 30 06:40:03 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 30 Mar 2008 12:40:03 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> Message-ID: <87od8w7aws.fsf@physik.rwth-aachen.de> Hall?chen! Bjoern Schliessmann writes: > Lie wrote: > >> Ah yes, that is also used (I completely forgot about that one, my >> math's aren't that sharp anymore) and I think it's used more >> frequently than ><. > > Where did you read that (I mean, which country)? I've never seen > this sign in any german or english book on > mathematics/physics/engineering I saw. Maybe he means "?". >> but my argument was that no math book use != or <> (except in >> math for programmers). > > That's true. Personally, I don't ever use "a!=b" in favor of "not > a==b". As a side note, I've always found == rather ugly. I'd prefer to have = for both purposes. The constructs that wouldn't work anymore are rare as far as I can see (and possibly there are even workarounds). Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From arnodel at googlemail.com Fri Mar 14 15:23:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 14 Mar 2008 12:23:20 -0700 (PDT) Subject: Custom Exception Value? References: <5fbe35d4-6590-41c2-824d-0b1656173829@x30g2000hsd.googlegroups.com> Message-ID: On Mar 14, 6:47?pm, erikcw wrote: > Hi, > > When I use sys.exc_info() on one of my custom exception classes, the > "message"/value isn't returned. ?But it is when I use a built in > exception. > > Example: > > In [32]: class Test(Exception): > ? ?....: ? ? def __init__(self, x): > ? ?....: ? ? ? ? self.value = x > ? ?....: ? ? def __str__(self): > ? ?....: ? ? ? ? return repr(self.value) > ? ?....: > ? ?....: > In [39]: try: > ? ?....: ? ? raise Test('mess') > ? ?....: except: > ? ?....: ? ? sys.exc_info() > ? ?....: > ? ?....: > Out[39]: (, Test(), 0xb7802e8c>) > > In [40]: try: > ? ?....: ? ? 1/0 > ? ?....: except: > ? ?....: ? ? sys.exc_info() > ? ?....: > ? ?....: > Out[40]: > (, > ?ZeroDivisionError('integer division or modulo by zero',), > ?) > > Wy does the output of ZeroDivisionError appear in sys.exc_info() but > for test it is just Test() (should be Test('mess') right??) Three ways to do it right: * Override __repr__() rather than __str__ or forget about __repr__() and instead: * call super(Test, self).__init__(x) from within Test.__init__() or even * self self.args = (x,) within Test.__init__() HTH -- Arnaud From gabriel.rossetti at mydeskfriend.com Thu Mar 27 06:15:17 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 11:15:17 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: <47EB6480.2080402@wtf.websiteburo.oops.com> References: <47EB6480.2080402@wtf.websiteburo.oops.com> Message-ID: <47EB73B5.8020804@mydeskfriend.com> Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : >> Hello, >> >> I am using Partial Function Application in a class and I've come up >> with a problem, when the method is called it tries to pass "self" to >> the curried/partial function, but this should be the first argument >> in reality, but since the function is curried, then the self gets >> passed as the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that >> since self is not available there. Does anyone have any ideas? > > registerServiceAtomic = partial(__registerService, atomic=True) > registerServiceNonAtomic = partial(__registerService, atomic=False) > > Caveat: you'll have to either invert the order of the atomic and > service params, or call the partials with named arg for service. > > HTH > Ok, thanks, I didn't know you could do that, I though partial was always left to right (I had read that about curry) Gabriel From http Thu Mar 27 17:24:42 2008 From: http (Paul Rubin) Date: 27 Mar 2008 14:24:42 -0700 Subject: Instrumented web proxy References: Message-ID: <7xod8zrhb9.fsf@ruckus.brouhaha.com> Andrew McLean writes: > I would like to write a web (http) proxy which I can instrument to > automatically extract information from certain web sites as I browse > them. Specifically, I would want to process URLs that match a > particular regexp. For those URLs I would have code that parsed the > content and logged some of it. > > Think of it as web scraping under manual control. I've used Proxy 3 for this, a very cool program with powerful capabilities for on the fly html rewriting. http://theory.stanford.edu/~amitp/proxy.html From guillermo.listas at googlemail.com Thu Mar 6 08:06:50 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Thu, 6 Mar 2008 05:06:50 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: Wow, I think I'm gonna like this forum. Thank you all for the prompt answers! >What makes you say you "need" to know this ? Except for a couple corner >cases, you usually don't need to care about this. If you told us more >about the actual problem (instead of asking about what you think is the >solution), we might be of more help... Good point. I want to iterate recursively a dictionary whose elements might be strings or nested tuples or dictionaries and then convert values to a tagged format according to some rules. d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y': ('a','b','c')}} I'm just designing the algorithm, but I think Python dictionaries can hold any kind of sequence? Regards, Guillermo From jason.scheirer at gmail.com Thu Mar 27 14:18:21 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 27 Mar 2008 11:18:21 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: On Mar 27, 8:40 am, mungkol wrote: > Dear all, > > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: > > running install > running build > running build_ext > building 'Stemmer' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- > prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 > -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- > i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o > In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > syslimits.h:7, > from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > limits.h:11, > from libstemmer_c/src_c/../runtime/header.h:2, > from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: > /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: > limits.h: No such file or directory > error: command 'gcc' failed with exit status 1 > > Did anyone experience this before? > > Any comment/suggestion is highly appreciated. > > Thank you. > > Best regards, > > Supheakmungkol This is a system configuration issue, not a Python issue: you seem to be missing a header file. First, make sure it exists ( /usr/lib/gcc/ i486-linux-gnu/4.1.3/include/limits.h ) and that you have permission to read it. If it's there, just sudo chmod a+r it and see if that helps. Also try installing Ubuntu's standard essential build tools ( sudo apt-get update && sudo apt-get install build-essential ) and see if that helps From cruxic at gmail.com Sat Mar 8 11:28:29 2008 From: cruxic at gmail.com (Cruxic) Date: Sat, 8 Mar 2008 08:28:29 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <6kyAj.284$Ls6.153@trnddc01> Message-ID: On Mar 8, 7:32 am, Alan Isaac wrote: > Cruxic wrote: > > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) > > ... > > p = people.get_equivalent(2) #method doesn't exist as far as I know > > print p.name #prints Sue > > def get_equivalent(test, container): > > for p in container: > > if p == test: > > return p > > hth, > > Alan Isaac > > #example (note change in __eq__ to match your case; fix if nec) > > class Person: > > def __init__(self, id, name): > > self.id = id > > self.name = name > > def __hash__(self): > > return self.id > > def __eq__(self, other): > > return self.id == other > > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) > > get_equivalent(2,people) That works fine for small data sets but my goal is to avoid a linear search, instead leveraging the O(1) lookup time for a hash based set. From http Fri Mar 28 20:19:04 2008 From: http (Paul Rubin) Date: 28 Mar 2008 17:19:04 -0700 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> <47ed882d$0$26468$afc38c87@news.optusnet.com.au> Message-ID: <7x63v6tm9z.fsf@ruckus.brouhaha.com> Richard Jones writes: > Check out tinypy: > http://www.philhassey.com/blog/category/tinypy/ I don't really understand the point of it. See also: http://hedgehog.oliotalo.fi/ From sturlamolden at yahoo.no Tue Mar 18 13:30:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 10:30:37 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: On 18 Mar, 17:48, Miki wrote: > Apart from PIL, some other options are: > 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object > you can draw on Yes, but at least on Windows you will get a GDI canvas. GDI is slow. > 2. A bit of an overkill, but you can use PyOpenGL OpenGL gives you a fast 'bitblit' for drawing bitmaps to the fram buffer (much faster than GDI). Here is some C code that does that (8- bit color depth). Translating to Python is trivial. I prefer not to use PyOpenGL as it has some unwanted overhead. It is better to use ctypes. void bitblt(void *frame, int w, int h) { glViewport(0,0,w,h); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRasterPos2i(0,0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glDrawPixels(w, h, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, (GLvoid *)frame); glFlush(); } From fetchinson at googlemail.com Thu Mar 6 01:17:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 5 Mar 2008 22:17:45 -0800 Subject: What is a class? In-Reply-To: References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: > > Where to begin? > > What does exec( open( 'modA.py' ).read() ) do? The most appropriate list to ask those questions is: http://mail.python.org/mailman/listinfo/tutor From josef.pktd at gmail.com Sat Mar 15 17:42:07 2008 From: josef.pktd at gmail.com (joep) Date: Sat, 15 Mar 2008 14:42:07 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> Message-ID: <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> > > http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... Note: this works for subprocess.call but for subprocess.Popen this does not work if there are two arguments in the command line with spaces. Especially, even after trying out many different versions, I never managed to get subprocess.Popen to work, when both the executable and one argument have spaces in the file path. subprocess.Popen requires the same extra double quoting at front or around the entire command as os.system. It took me many hours to find the versions of quoting that work. Explanation by Fredrik Lundh in thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/775ca566af9a70c2/65504296a27b43d5?lnk=gst&q=subprocess+windows+spaces#65504296a27b43d5 Here is a test file checking several cases: '''use winrar to get file information of a rar file testing double quotes for windows file paths with spaces using subprocess.Popen see: http://groups.google.com/group/comp.lang.python/browse_thread/thread/775ca566af9a70c2/65504296a27b43d5?lnk=gst&q=subprocess+windows+spaces#65504296a27b43d5 result: * most robust: use double quotes around entire command string * command as list argument never works when 2 file paths have spaces ''' import sys, os import subprocess def rargetinfo(filename,version=0): '''use winrar to get file information of a rar file ''' if version == 0: rarcmd = '"%s %s %s ' % (r'"C:\Program Files\WinRAR\Rar.exe"', "v", filename) elif version == 1: rarcmd = '"%s %s %s" ' % (r'"C:\Program Files\WinRAR \Rar.exe"', "v", filename) elif version == 2: rarcmd = '%s %s %s ' % (r'"C:\Program Files\WinRAR\Rar.exe"', "v", filename) elif version == 3: rarcmd = [r'"C:\Program Files\WinRAR\Rar.exe"', "v", filename] elif version == 4: executable_name = os.path.join(r'C:\Program Files\WinRAR', 'Rar.exe') rarcmd = [executable_name, "v", filename] p = subprocess.Popen(rarcmd, shell=True, stdout=subprocess.PIPE) rettext,reterror = p.communicate() retcode = p.wait() p.stdout.close() print rarcmd print 'this is rettext',rettext[:50] return rettext, rarcmd filenames = [r'"C:\temp\Copy of papers.rar"'] filenames.append(r'"C:\temp\papers.rar"') filenames.append(r'C:\temp\papers.rar') positives = {} negatives = {} for filename in filenames: for version in range(5): print '\n%s version: %d' % (filename,version) rettext, cmd = rargetinfo(filename,version) if rettext : print 'success' positives.setdefault(version,[]).append(cmd) else: print 'failure' negatives.setdefault(version,[]).append(cmd) from pprint import pprint print 'positives:' pprint(positives) print 'negatives:' pprint(negatives) From grante at visi.com Fri Mar 7 13:22:12 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Mar 2008 18:22:12 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t2vvstgkne233@corp.supernews.com> <63ddtqF27a5u2U1@mid.individual.net> Message-ID: <13t31ukn750vr22@corp.supernews.com> On 2008-03-07, K Viltersten wrote: >>> Personally, I dislike double spaces after sentences, but it is >>> not wrong to put them there any more than it is wrong not to >>> put them there. >> >> You're lucky my high school typing teacher didn't hear you say >> that... > > I'm unclear if your teacher was a double or single spacer. Double. > It's only implied that he felt strongly one way. She, actually. Leaving out one of the two spaces after the end of a sentence was no less an error than leaving out the period or forgetting to capitalize the first word of the next sentence. AFAIK, that's the way pretty much everybody was taught to type back then (1977). If you're using a word-processor or typesetting system that's worth its weight in bits, it won't matter how many spaces you type -- the paragraph layout algorithm will handle it. -- Grant Edwards grante Yow! I'm having fun at HITCHHIKING to CINCINNATI visi.com or FAR ROCKAWAY!! From modelnine at modelnine.org Tue Mar 25 18:15:36 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 25 Mar 2008 23:15:36 +0100 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: <200803252315.36924.modelnine@modelnine.org> Am Dienstag, 25. M?rz 2008 23:02:00 schrieb Dark Wind: > In most of the languages ^ is used for 'to the power of'. In python we have > ** for that. But what does ^ do? ^ is the binary exclusive-or (xor) operator. Possibly it helps to see the following (numbers are in binary) to get the drift: 00 ^ 01 = 01 01 ^ 01 = 00 10 ^ 01 = 11 11 ^ 01 = 10 -- Heiko Wundram From gatti at dsdata.it Sat Mar 1 11:07:56 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Sat, 1 Mar 2008 08:07:56 -0800 (PST) Subject: Beginner's assignment question References: Message-ID: On Mar 1, 3:39 pm, Schizoid Man wrote: > As in variable assignment, not homework assignment! :) > > I understand the first line but not the second of the following code: > > a, b = 0, 1 > a, b = b, a + b > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > However what is the sequence of operation in the second statement? I;m > confused due to the inter-dependence of the variables. The expressions of the right of the assignment operator are evaluated before assigning any new values, to the destinations on the left side of the assignment operator. So substitutig the old values of a and b the second assignment means a, b = 0, 0 + 1 Simplifying the Python Reference Manual ("6.3 Assignment Statements") a little : assignment_stmt ::= target_list "="+ expression_list An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. [...] WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (for example "a, b = b, a" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "[0, 2]": x = [0, 1] i = 0 i, x[i] = 1, 2 print x Lorenzo Gatti From Lie.1296 at gmail.com Thu Mar 20 03:56:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 20 Mar 2008 00:56:13 -0700 (PDT) Subject: Is this valid ? References: Message-ID: On Mar 20, 4:18?am, Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > > thanks, > Stef Mientki a == b == 2 is equivalent to a == b and b == 2 except that b is only evaluated once for the whole comparison From dave_mikesell at fastmail.fm Fri Mar 7 23:57:32 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Fri, 7 Mar 2008 20:57:32 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> Message-ID: <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> On Mar 7, 10:38 pm, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 20:04:47 -0800, dave_mikesell wrote: > > On Mar 7, 10:31 am, "K Viltersten" wrote: > >> I've been recommended reading > >> of:http://www.python.org/dev/peps/pep-0008/and in there i saw two > >> things that i > >> need to get elaborated. > > >> 1. When writing English, Strunk and > >> White apply. > > > If your code needs so much descriptive prose that you have to consult > > Strunk and White, refactor it to be more clear. Excessive comments are > > the hobgoblin of overly complex and/or sloppy code. > > Nonsense. Poor English is poor English whether you're writing short one- > line comments or three hundred page manuals. > > store = make_store() > x = get_stuff(store) # Get the stuff what was brought at the store. Perfect example of an unnecessary comment. The variable and function names are commentary enough. From robert.kern at gmail.com Sat Mar 8 15:58:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 Mar 2008 14:58:02 -0600 Subject: distutils - Is is possible to install without the .py extensions In-Reply-To: References: Message-ID: Jari Aalto wrote: > * Fri 2008-03-07 Robert Kern gmane.comp.python.general > * Message-Id: fqt61a$sj5$1 at ger.gmane.org > >>>>> setup(name='program', >>> ... >>>>> scripts = ['program,py'], >>>>> ) >>>>> that the the result is: >>>>> >>>>> /usr/bin/program >>>>> >>>>> instead of: >>>>> >>>>> /usr/bin/program.py >>>> The easiest and best way is to just rename the file in your source tree to >>>> "program" and be done with it. >>> Is there any other way? This is the source package that I would like >>> to keep intact and just patch the setup.py >> Not really, no. Why is it so important to only patch the setup.py >> file and not any others? > > It has to do with generating a diff against the original package. If > the file is moved: > > mv file.py file > > prior setup.py run (which, according to answers, would have a change > to <>), the problem is the generated diff > against original sources: > > + would flag removal of 'file.py' > + inclusion of 'file' > > The ideal would be if setup.py could do all the destination install > "postwork". The generated patch would be clean and only contain > changes in setup.py. > > But I understand, if distutils does not support stripping the > extensions during install. It just cacuses exra work for utility > packagers. What build system are you using that doesn't let you execute cp file.py file before running the setup.py? -- 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 george.sakkis at gmail.com Wed Mar 12 15:58:33 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 12 Mar 2008 12:58:33 -0700 (PDT) Subject: Does __import__ require a module to have a .py suffix? References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: <05559d08-2479-4178-830c-adf65dfc733c@s37g2000prg.googlegroups.com> On Mar 12, 12:22 pm, mrstephengross wrote: > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? You can use execfile: foo = {} execfile('foo', foo) Apart from the different syntax in accessing the module globals (attributes with __import__ (foo.x) vs dict entries with execfile (foo['x'])), there are probably more subtle differences but I can't tell for sure. It would be nice if someone more knowledgeable can compare and contrast these two appraches. George From florian.harmuth at googlemail.com Mon Mar 17 08:12:22 2008 From: florian.harmuth at googlemail.com (mich1985) Date: Mon, 17 Mar 2008 05:12:22 -0700 (PDT) Subject: SAXReaderNotAvaiable after switching Python Message-ID: <0e990748-2e57-46ce-9a8e-2f0b89754d7c@z38g2000hsc.googlegroups.com> Hello all, after i have switched from python-2.4.2 to python-2.4.3 i get the following message if run my web configuration: parser = xml.sax.make_parser() ..... SAXReaderNotAvailable: No parsers found The files under /usr/lib/python2.4/xml/sax are the same as before. Any hints where i can start my search? (a ng search didn't solved my problem). Best Regards, flo From arnodel at googlemail.com Mon Mar 3 05:32:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 3 Mar 2008 02:32:49 -0800 (PST) Subject: First post from a Python newbiw References: Message-ID: <41cfe2c1-51d0-4b15-b9c8-ea3d4389b6cf@e6g2000prf.googlegroups.com> Steve Turner wrote: > I finally decided to have a go with Python and am working through the > tutorial. Great! > On my old BBC Computer [...] These were nice machines... > In Python I thought I could do this with: > > >>> a=[0,0,0] > >>> b=[a,a,a] > >>> b > [[0, 0, 0], [0, 0, 0], [0, 0, 0]] > >>> b[1][1]='foo' > >>> b > [[0, 'foo', 0], [0, 'foo', 0], [0, 'foo', 0]] > >>> > > I can understand why as b[1][1]='foo' is actually changing a[1] > > Apart from doing something like > a=[0,0,0] > b=[0,0,0] > c=[0,0,0] > d=[a,b,c] > > is there a better way of creating d?? It's a FAQ: http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list -- Arnaud From hniksic at xemacs.org Tue Mar 25 14:07:55 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Mar 2008 19:07:55 +0100 Subject: Does python hate cathy? References: <64spscF2derd7U3@mid.uni-berlin.de> Message-ID: <87hceuoex0.fsf@mulj.homelinux.net> Marc 'BlackJack' Rintsch writes: > On Tue, 25 Mar 2008 14:58:51 +0000, Edward A. Falk wrote: > >> In article , >> Patrick Mullen wrote: >> >>>Then again, I can count the number of times I have ever needed __del__ >>>with no fingers (never used it!). Still, quite interesting to >>>explore. >> >> I used it once, for an object that had a doubly-linked list. >> The __del__() method walked the list, setting all the elements' >> prev/next pointers to None to make sure the elements of the list would >> get garbage-collected. > > Without the `__del__()` the elements would get garbage collected just > fine. It gets even worse than that: the __del__ method actually *prevents* objects that participate in cycles from getting garbage-collected. Python's GC doesn't deallocate objects that define __del__. (The way to handle those is to grep for them in gc.garbage, break the cycles in a way that works for the application -- e.g. by removing the prev and next references -- and finally del gc.garbage[:].) From spradml at gmail.com Tue Mar 4 00:19:54 2008 From: spradml at gmail.com (Pradnyesh Sawant) Date: Tue, 4 Mar 2008 10:49:54 +0530 Subject: help needed with regex and unicode Message-ID: <20080304051954.GA3992@debian> Hi all, I have a file which contains chinese characters. I just want to find out all the places that these chinese characters occur. The following script doesn't seem to work :( ********************************************************************** class RemCh(object): def __init__(self, fName): self.pattern = re.compile(r'[\u2F00-\u2FDF]+') fp = open(fName, 'r') content = fp.read() s = re.search('[\u2F00-\u2fdf]', content, re.U) if s: print s.group(0) if __name__ == '__main__': rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php') ********************************************************************** the php file content is something like the following: ********************************************************************** // Check if the folder still has subscribed blogs $subCount = function1($param1, $param2); if ($subCount > 0) { $errors['summary'] = '?????????????????????????????????????????'; $errorMessage = '?????????????????????????????????????????'; } if (empty($errors)) { $ret = function2($blog_res, $yuid, $fid); if ($ret >= 0) { $saveFalg = TRUE; } else { error_log("ERROR:: ret: $ret, function1($param1, $param2)"); $errors['summary'] = "????????????????????????????? $errorMessage = "????????????????????????????? } } ********************************************************************** -- warm regards, Pradnyesh Sawant -- Luck is the residue of good design. --Anon -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From mail at timgolden.me.uk Tue Mar 18 09:51:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 18 Mar 2008 13:51:54 +0000 Subject: stdout custom In-Reply-To: <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: <47DFC8FA.1060700@timgolden.me.uk> castironpi at gmail.com wrote: >>> Can I allocate a second console window, so I can place certain output >>> to that directly, and leave the original streams alone? I've rather lost track of what you're trying to do, but I would second Gabriel's suggestion of the standard Windows method of debug output: using OutputDebugString. There's an example here: http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugString.html and it shouldn't be too hard to wrap it in a file-like object for stderr-substitution use, say. Obviously there are 1,001 other ways of doing IPC but since this one's ready-made you might as well use it. You can distinguish between different processes' outputs by virtue of the PID which is the first item on the mmap. TJG From bogus@does.not.exist.com Sat Mar 1 17:42:14 2008 From: bogus@does.not.exist.com (From) Date: Sat, 01 Mar 2008 17:42:14 -0500 Subject: Surprised by the command "del" References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: On Sat, 1 Mar 2008 21:05:41 +0100, "K Viltersten" wrote: >I'm reading the docs and at 5.2 the del >statement is discussed. At first, i thought >i've found a typo but as i tried that >myself, it turns it actually does work so. > > a = ["alpha", "beta", "gamma"] > del a[2:2] > a > >Now, i expected the result to be that the >"beta" element has been removed. Obviously, >Python thinks otherwise. Why?! > >Elaboration: >I wonder why such an unintuitive effect has >been implemented. I'm sure it's for a very >good reason not clear to me due to my >ignorance. Alternatively - my expectations >are not so intuitive as i think. :) I think it should say del a[1:2] then it works From carsten at uniqsys.com Wed Mar 12 16:52:43 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 12 Mar 2008 16:52:43 -0400 Subject: string / split method on ASCII code? In-Reply-To: References: Message-ID: <1205355164.9891.39.camel@dot.uniqsys.com> On Wed, 2008-03-12 at 15:29 -0500, Michael Wieher wrote: > Hey all, > > I have these annoying textilfes that are delimited by the ASCII char > for << (only its a single character) and >> (again a single character) > > Their codes are 174 and 175, respectively. > > My datafiles are in the moronic form > > X<>Z Those are decidedly not ASCII codes, since ASCII only goes to 127. The easiest approach is probably to replace those markers with some other characters that occurs nowhere else, for example good old NUL, and then split on that: line = line.replace(chr(174), "\0") line = line.replace(chr(175), "\0") result = line.split("\0") HTH, -- Carsten Haese http://informixdb.sourceforge.net From MadComputerGuy at gmail.com Sun Mar 2 23:15:10 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Sun, 2 Mar 2008 20:15:10 -0800 (PST) Subject: Is it possible to return a variable and use it...? Message-ID: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> Hello all, Is it possible to return a variable and then use it like the following: [code] dir exp_1: while hen != "*" sum = sum + hen return sum dir exp_2: if sum >= total_needed: print "Profit can be made." else: print "Expect a loss." total_needed = int(raw_input("What is the total eggs needed? ")) hen = int(raw_input("How many eggs did each hen lay? Enter them in 1 by 1 or enter * when done. ")) exp_1 exp_2 [/code] If not, then how do I do so? Thanks, Nathan P. From tjreedy at udel.edu Sun Mar 2 01:26:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 01:26:35 -0500 Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: "Kay Schluehr" wrote in message news:eba3804e-4585-4ec7-85d2-a17513719025 at c33g2000hsd.googlegroups.com... | On 1 Mrz., 19:51, Barry Warsaw wrote: | | > Python 2.6 is not only the next advancement in the Python 2 series, it | > is also a transitionary release, helping developers begin to prepare | > their code for Python 3.0. | | Isn't this a silly idea? People have to migrate from 2.5 or lower | releases to Python 2.6 first just to migrate to Python 3.0? You are quite free to update any code you want. Barry just said that 2.6 will help make the process easier. (At least it should for people who prefer incremental changes to doing it all at once.) In any case, 2.5 and earlier code that does not depend on bugs later fixed should usually run unchanged in 2.6 | What are | the inherent / technical reasons that prevent migration directly from | 2.5 to 3.0? None. tjr From steve at REMOVE-THIS-cybersource.com.au Fri Mar 14 07:13:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 14 Mar 2008 11:13:37 -0000 Subject: sorting question References: Message-ID: <13tknf14vncbu34@corp.supernews.com> On Thu, 13 Mar 2008 22:37:00 -0500, "Andrew Rekdal" wrote: > Seems 'KEYBOARDS' works nicely in reply to a post from "jcnbp8k" who wrote: > > That's easy solved, the word is keyboards. Hmmm... using my incredible powers of deduction, I predict that the word is "keyboards". -- Steven From michael.wieher at gmail.com Sun Mar 16 20:13:20 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 19:13:20 -0500 Subject: Pycon disappointment In-Reply-To: <11252b13-e3d0-4aa7-9cf5-ee9db7bfc250@u69g2000hse.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> <11252b13-e3d0-4aa7-9cf5-ee9db7bfc250@u69g2000hse.googlegroups.com> Message-ID: well, like, at least he left a free copy of his book on the web, that was kinda decent. 2008/3/16, lbonafide at yahoo.com : > > On Mar 16, 2:43 pm, Robert Hicks wrote: > > On Mar 16, 12:38 pm, lbonaf... at yahoo.com wrote: > > > > > On Mar 16, 6:10 am, Bruce Eckel wrote: > > > > > > I think a lot of people have been caught up in the idea that we need > > > > to commercialize Python, and ride some kind of wave of publicity the > > > > way that Java and C# and Rails seem to have done. > > > > > This coming from someone who caught the Java wave and rode it for a > > > decade. > > > > Doesn't that make him better to see the problems with it? > > Sure, but he dumped C++ (a truly non-commercial language) like a bad > habit for the latest silver bullet ten years ago. Complaints against > Java's commercial nature now ring a bit hollow. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Mar 7 10:46:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 13:46:06 -0200 Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: En Fri, 07 Mar 2008 13:12:13 -0200, nodrogbrown escribi?: > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? join is fine. "\\" is a single character. \ is used as the escape character, and has to be doubled when representing itself. Print an individual element to see the effect: print filenameslist[0] F:/brown/code/python/fgrp1\amber1.jpg (a list uses repr() on its elements instead of str()). > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', If the string is only used to open a file, and never shown to the user, what you prefer is irrelevant, isn't it? What is important here is what Windows prefers, and that's a backslash, although many times / is accepted too. You can convert the file names to their preferred spelling using os.path.normpath Back to your code, try this: from os.path import join, normpath folder = 'F:/brown/code/python/fgrp1' names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] filenameslist = [normpath(join(folder, name)) for name in names] -- Gabriel Genellina From kla at us.de Wed Mar 19 07:17:12 2008 From: kla at us.de (klaus) Date: 19 Mar 2008 11:17:12 GMT Subject: a beginner, beginners question References: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Message-ID: <47e0f638$0$307$e4fe514c@dreader24.news.xs4all.nl> On Wed, 19 Mar 2008 05:57:04 -0500, Tim Chase wrote: >> class example: >> def __init__(self, foo, bar): >> self.foo = foo >> self.bar = bar >> >> def method(self): >> print "method ... :" >> print self.foo >> print self.bar >> >> if __name__ == "__main__": >> obj = example > > This makes "obj" a synonym for "example". You want to instantiate your > "example" class with > > obj = example("Some foo", "Some Bar") > >> obj.foo = "var1" >> obj.bar = "var2" > > which then makes these two lines either unneeded or an overwriting of > the initialization > >> obj.method > > and this returns a function, not the results of the function. You need > to call it > > obj.method() > > -tkc Ok thank you for elaborating I think I've got it. Thnkx. ! From michael.wieher at gmail.com Fri Mar 28 22:03:51 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 28 Mar 2008 21:03:51 -0500 Subject: Help me on function definition In-Reply-To: References: Message-ID: No problem... your def needs a colon.. def function(params): yours lacks it =) thats all On Fri, Mar 28, 2008 at 8:47 PM, aeneng wrote: > Hello everyone, > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this > >>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 > ppp1=u[1]*v[2]-u[2]*v[1] > ppp2=u[2]*v[0]-u[0]*v[2] > ppp3=u[0]*v[1]-u[1]*v[0] > # store the result of the cross product in u > u[0]=ppp1 > u[1]=ppp2 > u[2]=ppp3 > return u #return the cross product of vector u x v. > if __name__=="__main__": > from cvxopt.base import matrix > u=matrix([1.0,0.0,0.0],(3,1)) > v=matrix([0.0,1.0,0.0],(3,1)) > print cross(u,v) > print "file name is %s" %__name__ > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Mar 24 11:37:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Mar 2008 16:37:50 +0100 Subject: Element Tree Help In-Reply-To: <47E7CA87.7090901@behnel.de> References: <47E7CA87.7090901@behnel.de> Message-ID: <47E7CACE.1020508@behnel.de> Stefan Behnel schrieb: > Robert Rawlins wrote: >> Hello Guys,I have little to no experiance with element tree and I'm >> struggling to find a way to parse the details from the XML document >> (attached) into my application. Essentialy I'm looking to take the >> following document and turn it into a dict of tuples, each dict element >> defines a datasource with the key to the element being the 'name' which is >> defined in the XML and then the value of the pair is a tuple which contains >> the details of the datasource, like the host and port etc.I've attached a >> copy of the example XML to this email.Can anyone offer some advice on how >> to get started with this? I've spent a little time looking over the >> documentation of element tree and have struggled to break the ice and parse >> this document.Thanks guys,Robert > > Given this document: > > > > > > a name > localhost > 3306 > database1 > someusername > somepassword > > > another name > localhost > 3306 > database2 > itsusername > andthepassword > > > > I would do something like this: > > d = {} > for event, element in ET.iterparse("thefile.xml"): > if element.tag == "datasource": > d[element.find("name")] = tuple([ el.text for el in element ]) Sorry, the last line should be d[element.findtext("name")] = tuple([ el.text for el in element ]) but you'll likely have to modify that line anyway. Stefan From tjreedy at udel.edu Wed Mar 5 21:05:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Mar 2008 21:05:31 -0500 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13suj3u2d17f205 at corp.supernews.com... |I recall that Python guarantees that module objects are singletons, and | that this must hold for any implementation, not just CPython: you can | only ever create one instance of a module via the import mechanism. But | my google-foo is obviously weak today, I cannot find where the Python | language reference guarantees that. Can somebody please point me at the | link making that guarantee? | | (Note: you can create multiple modules with the same name and state using | new.module. I don't think that counts, although it may be a good way to | win bar bets with your Python buddies.) | | | But what about classes? Are they singletons? Obviously classes aren't | Singleton classes, that is, given an arbitrary class C you can create | multiple instances of C. But what about class objects themselves? I've | found a few odd references to "classes are singletons", but nothing in | the language reference. | | I've done some experimentation, e.g.: | | >>> import module | >>> from module import Class | >>> module.Class is Class | True | | | but I'm not sure if that's (1) meaningful or (2) implementation-specific. If I understand your question, classes are not singletons: >>> ll=[] >>> for i in range(2): import string ll[i]=string >>> ll[0] is ll[1] True >>> for i in range(2): class C: pass ll[i] = C >>> ll[0] is ll[1] False tjr From mnordhoff at mattnordhoff.com Sun Mar 16 03:24:39 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sun, 16 Mar 2008 07:24:39 +0000 Subject: Python Generators In-Reply-To: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: <47DCCB37.2040004@mattnordhoff.com> mpc wrote: > def concatenate(sequences): > for seq in sequences: > for item in seq: > yield item You should check out itertools.chain(). It does this. You call it like "chain(seq1, seq2, ...)" instead of "chain(sequences)" though, which may be a problem for you. The rest of itertools might be interesting too: -- From partofthething at gmail.com Mon Mar 17 23:55:54 2008 From: partofthething at gmail.com (partofthething) Date: Mon, 17 Mar 2008 20:55:54 -0700 (PDT) Subject: Can't get bsddb working on Solaris 8 Message-ID: I've been struggling with this all day. I am trying to get Python 2.5 running with the BerkeleyDB bindings provided by bsddb. First, I downloaded the BerkeleyDB system (version 4.5) from http://www.oracle.com/technology/products/berkeley-db/index.html. Then, I downloaded bsddb from http://pybsddb.sourceforge.net/ and built it using my python 2.5 install with python2.5 setup.py build and python2.5 setup.py install. During the install, the scripts explain that they found the BerkeleyDB system version 4.5 right where I installed it to. I even tried rebuilding all of Python after my BerkeleyDB was set up. My error persists: File "/usr/local/lib/python2.5/bsddb/__init__.py", line 51, in import _bsddb ImportError: No module named _bsddb This is a Solaris 8 machine (SunOS 5.8). I've added the library path (/ usr/local/BerkeleyDB.4.5/lib) to LD_LIBRARY_PATH before building. I'm out of ideas. Any help? Thanks. From xiebopublic at gmail.com Wed Mar 12 23:15:32 2008 From: xiebopublic at gmail.com (Bo) Date: Wed, 12 Mar 2008 20:15:32 -0700 (PDT) Subject: How to port Python code into C++ code automatically? Message-ID: I want to port a Python project (about 10,000 line python code) to C+ +. Is there any automatically tool to do this kind of things? e.g., SWIG(http://www.swig.org/)? Any comment is welcome! Thanks! From mark.manning at gmail.com Mon Mar 10 18:58:03 2008 From: mark.manning at gmail.com (Mark M Manning) Date: Mon, 10 Mar 2008 15:58:03 -0700 (PDT) Subject: Python Sockets Help Message-ID: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> I need your expertise with a sockets question. Let me preface this by saying I don't have much experience with sockets in general so this question may be simple. I am playing with the mini dns server from a script I found online: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt All I want to do is edit this script so that it records the IP address. I've seen other examples use the accept() object which returns the data and the IP address it is receiving the data from. I can't use that in this case but I'm wondering if someone could show me how. Here is the socket part of the script: if __name__ == '__main__': ip='192.168.1.1' print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udps.bind(('',53)) try: while 1: data, addr = udps.recvfrom(1024) p=DNSQuery(data) udps.sendto(p.respuesta(ip), addr) print 'Respuesta: %s -> %s' % (p.dominio, ip) except KeyboardInterrupt: print 'Finalizando' udps.close() Thanks to everyone in advance! ~Mark From castironpi at gmail.com Tue Mar 11 17:56:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 14:56:26 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> Message-ID: <72f2856c-eeca-44f2-849d-912889d26a79@d21g2000prf.googlegroups.com> > > ?Thanks, that makes sense. Are there any local relational databases > > ?available to python that don't require a server backend? > > sqlite > http://www.sqlite.org/ Are there any that aren't persistent? From rmsa50 at yahoo.co.in Thu Mar 20 21:41:32 2008 From: rmsa50 at yahoo.co.in (Gokul) Date: Thu, 20 Mar 2008 18:41:32 -0700 (PDT) Subject: A-Z about Operating systems and other programming languages Message-ID: <2aa5e9bb-ac8a-42c5-ad5a-a6225a8f1f53@u10g2000prn.googlegroups.com> Hai friends. Welcome to Comp.lang.c group. Today I found a website where it gives the entire details about C++ and other IT related tools such as SQL server 2008 updates, IBM tools and techniques and a lot more in the field of Information Technology. http://www.sqlserversoftware.blogspot.com From george.sakkis at gmail.com Wed Mar 19 01:26:40 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 22:26:40 -0700 (PDT) Subject: Get actual call signature? References: <3ef0a8e9-6c86-46a5-be48-63f738f9ec88@s13g2000prd.googlegroups.com> Message-ID: <37b38eb8-624e-4a4b-b0d3-10bc29ba1b93@v3g2000hsc.googlegroups.com> On Mar 18, 4:24 pm, George Sakkis wrote: > On Mar 18, 6:40 am, Jarek Zgoda wrote: > > > > > Say, I have a function defined as: > > > def fun(arg_one, arg_two='x', arg_three=None): > > pass > > > Is there any way to get actual arguments that will be effectively used > > when I call this function in various ways, like: > > > fun(5) => [5, 'x', None] > > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > > fun(5, 'something') => [5, 'something', None] > > > (et caetera, using all possible mixes of positional, keyword and default > > arguments) > > > I'd like to wrap function definition with a decorator that intercepts > > not only passed arguments, but also defaults that will be actually used > > in execution. > > > If this sounds not feasible (or is simply impossible), I'll happily > > throw this idea and look for another one. ;) > > I also needed this for a typecheck module I had written some time ago. > It is feasible, but it's rather hairy. I can dig up the code, polish > it and post it as a recipe (or maybe as a patch to the inspect stdlib > module where it belongs). > > George Posted at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551779. For any correction or improvement, please leave a comment. George From gagsl-py2 at yahoo.com.ar Mon Mar 17 21:16:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 18:16:24 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> Message-ID: <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> On 17 mar, 19:43, castiro... at gmail.com wrote: > Can I allocate a second console window, so I can place certain output > to that directly, and leave the original streams alone? ?I tried some > things in subprocess (Py 3a3 /WinXP) but they failed. ?I don't know if > it's supposed to be possible though, so I didn't press very hard or > keep the code. ?If it is, I can go repro where it went south. ?Is it? Have you tried using the creationflags argument to subprocess.Popen? Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation for CreateProcess at http://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx (Note that a process can be attached at most to one console) If your goal is to output some debug information, try using OutputDebugString + the DebugView utility from www.sysinternals.com -- Gabriel Genellina From pydecker at gmail.com Wed Mar 19 13:10:17 2008 From: pydecker at gmail.com (Peter Decker) Date: Wed, 19 Mar 2008 12:10:17 -0500 Subject: Need Help Starting Out In-Reply-To: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop wrote: > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. > > I want to use it for web building with database access. What do I use > for that? Does it matter what I use on the client side (mootools, or > whatever)? If you are going to be developing web applications, there are many excellent frameworks available, all of which provide database support. If you are looking to develop desktop applications, you should check out Dabo (http://dabodev.com). They integrate data access and GUI controls, making it simple to create database apps. They use wxPython for the UI layer, but hide all of its ugliness, allowing you to program to a clean, consistent API for your GUI. -- # p.d. From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:40:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:40:49 -0300 Subject: Determine size of string in bytes References: Message-ID: En Thu, 27 Mar 2008 16:45:52 -0300, breal escribi?: > Forgive me for this question which is most likely stupid... > > How do I determine the number of bytes a string takes up? I have a > soap server that is returning a serialized string. It seems that when > the string goes over 65978 characters it does not return to the soap > client. Instead I get an error: > error: (35, 'Resource temporarily unavailable') len(x)? Or do you wan to know how many bytes will have an unicode object when encoded in a certain encoding? The only way is to actually encode it and take the length. -- Gabriel Genellina From sturlamolden at yahoo.no Fri Mar 28 13:24:51 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 28 Mar 2008 10:24:51 -0700 (PDT) Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: On 28 Mar, 15:52, s... at pobox.com wrote: > I'm having trouble explaining the benefits and tradeoffs of threads to my > coworkers and countering their misconceptions about Python's threading model > and facilities. ? Python's threading module is modelled on Java's thread model. There are some minor differences, though. Whereas Python has special lock objects, Java can lock (synchronize) on any object. > They all come from C++ and are used to thinking of > multithreading as a way to harness multiple CPU cores for compute-bound > processing. ?I also encountered, "Python doesn't really do threads" today. > *sigh* You can't use threads for that in CPython, due to the GIL (global interpreter lock). The GIL resembles the BKL in earlier versions of the Linux kernel. Due to the GIL, multiple threads cannot be simultaneously in the Python interpreter. This e.g. means that I cannot implement a parallel QuickSort in pure Python and get performance gain from multiple CPUs. Although common misbeliefs, this DOES NOT mean: * Python threads are not useful. * Python programs cannot utilize multiple CPUs or multi-core CPUs. Here is the explanations: The GIL can be released by extension modules, which are native libraries of compiled C, C++ or Fortran. This is the key to the usefulness of Python threads. For example: * Python file and socket objects are extension modules that release the GIL. The GIL is released when a thread is waiting for i/o to complete. This e.g. allows you to write multi-threaded server apps in Python. * NumPy is an extension library that releases the GIL before commencing on a time-consuming CPU-bound computations. If you have N CPUs, NumPy allows you to do N FFTs or SVDs in parallel. * ctypes is an extension module that allows Python code to call DLLs. ctypes releases the GIL before the foregin call on cdecl functions (but not stdcall functions!), allowing you to call many cdecl DLL functions in parallel. * Extension libraries that spawns multiple threads will utilize mutiple CPUs, even if the GIL are not released. There is also other reasons why threads are useful, that does not depend on extension modules releasing the GIL. One example: Multithreading is the key to responsive user interfaces, as only one thread should process events. An event-handler should spawn a thread before commencing on a time-consuming task. IronPython and Jython are implemented without a GIL. (They run on the .NET and Java VMs, respectively.) Finally, remeber that pure Python often runs 200 times slower than pure C on algoritmic code! If you need to do lengthy computational tasks, a pure Python may not be what you want. With two dual-core CPUs, nearly perfect load scheduling, a no-GIL implementation of Python, a pure Python would still be more than 50 times solwer than a single-threaded C solution. Hence, you would gain a lot more from profiling, identifying the worst bottlenecks, and translating those parts to C. From kkadrese at gmail.com Wed Mar 19 10:30:05 2008 From: kkadrese at gmail.com (Andra) Date: Wed, 19 Mar 2008 07:30:05 -0700 (PDT) Subject: lock access to serial port References: <13u2644hpullvd8@corp.supernews.com> Message-ID: I tried ready-made commands for file locking, and turned to that LCK file just in case some permissions are wrong and that's the reason the commands fail. On 19 Marts, 15:43, Grant Edwards wrote: > On 2008-03-18, kkadr... at gmail.com wrote: > > > how to get ttyS0 serial port for exclusive access? I have a python > > script that uses this device with AT commands. I need that two > > instances can call simultaneosuly this python script but only one of > > them gets the device. I tried fcntl.flock, it was just ignored, put > > writtable file LCK..ttyS0 in /var/lock, > > Using a lock file is the traditional method of providing > mutually exclusive access to a serial port. > > > tried ioctl (but I may not know what are appropriate > > arguments), googled half a day for various phrases, error > > messages etc....without success. > > It's unclear what "without success" means. ?Lockfiles have been > used for decades, and they work fine as long as all of the > applications follow the rules. > > -- > Grant From kyosohma at gmail.com Mon Mar 24 14:57:43 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 24 Mar 2008 11:57:43 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <65ebcba0-0283-4003-b667-ff145bc2cd54@u10g2000prn.googlegroups.com> On Mar 24, 1:53 pm, pythonnubie wrote: > Hi Everyone > > I am new to programming in general although I have read alot and > done alot of experimentation as well as researched afew languages > namely java python and visual basic . My conclusion is that python > is one of the best because it eliminates the need to learn about > access modifiers and form handlers so a user can concentrate > primarliy on the nuts and bolts of the language . > > i have come across my first exeption using randrange . The exeption > is " no such attribute " in module random > > platform is xp home and the python build is activestate 2.5 > > All help much appreciated ! Please post the code that throws this error along with the entire traceback. Thanks, Mike From jacob.kaplanmoss at gmail.com Mon Mar 17 19:22:50 2008 From: jacob.kaplanmoss at gmail.com (Jacob Kaplan-Moss) Date: Mon, 17 Mar 2008 16:22:50 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> <83b2ca86-32bb-4bf4-b119-f8d593d4c9eb@p25g2000hsf.googlegroups.com> Message-ID: On Mar 17, 2:52?pm, Dianne Marsh wrote: > I'm bummed about the lightning talks at PyCon from 2008, but I have a > lot of confidence based on what I have read here from Jacob and > others, that things will be different in 2009. They will! This year's lightning talks[*] were disappointing because nobody really thought through how having so many more sponsors changed the dynamic. Now we know, and we'll fix it. Jacob [*] Personally, I thought the Sunday talks -- which featured no sponsors -- were quite good. I think attendance was spotty because it was the last day, and because Saturday's talks were so painful. From KephnosAnagennao at gmail.com Sat Mar 22 16:27:49 2008 From: KephnosAnagennao at gmail.com (sgharvey) Date: Sat, 22 Mar 2008 13:27:49 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order Message-ID: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> ... and by works, I mean works like I expect it to. I'm writing my own cheesy config.ini parser because ConfigParser doesn't preserve case or order of sections, or order of options w/in sections. What's confusing me is this: If I try matching every line to one pattern at a time, all the patterns that are supposed to match, actually match. If I try to match every pattern to one line at a time, only one pattern will match. What am I not understanding about re.search? Doesn't match properly: # Iterate through each pattern for each line for line in lines: for pattern in patterns: # Match each pattern to the current line match = patterns[pattern].search(line) if match: "%s: %s" % (pattern, str(match.groups()) ) _Does_ match properly: # Let's iterate through all the lines for each pattern for pattern in pattern: for line in lines: # Match each pattern to the current line match = patterns[pattern].search(line) if match: "%s: %s" % (pattern, str(match.groups()) ) Related code: The whole src http://pastebin.com/f63298772 regexen and delimiters (imported into whole src) http://pastebin.com/f485ac180 From DustanGroups at gmail.com Sun Mar 23 09:19:22 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 23 Mar 2008 06:19:22 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <7x63vfn3ix.fsf@ruckus.brouhaha.com> Message-ID: <8e4e1ae0-9a34-41c2-b253-7ea8846f6de5@i7g2000prf.googlegroups.com> On Mar 21, 3:57 pm, Paul Rubin wrote: > From at home writes: > > if 'one' and 'two' in f: > > alist.append(f) > > Use: > if 'one' in f and 'two' in f: ... Personally, I would put parentheses around to be clearer: if ('one' in f) and ('two' in f): ... I'm not saying to put parentheses around everything, but in the more ambiguous cases, it certainly helps. From michael at stroeder.com Sat Mar 29 08:25:52 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 29 Mar 2008 13:25:52 +0100 Subject: ANN: python-ldap-2.3.4 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.4 2008-03-29 Changes since 2.3.3: Modules/ * Fixed seg fault when calling LDAPObject.get_option() (see SF#1926507, thanks to Matej) ---------------------------------------------------------------- Released 2.3.3 2008-03-26 Changes since 2.3.2: Fixed backward-compability when building with OpenLDAP 2.3.x libs. From enleverlesX.XmcX at XmclaveauX.com Fri Mar 7 02:40:20 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 7 Mar 2008 08:40:20 +0100 Subject: Internet Explorer 8 beta release In-Reply-To: References: Message-ID: <47d0f485$0$868$ba4acef3@news.orange.fr> Hi! > compliance with the W3C standard Ouarf! Ouarf! which navigator has been compatible with CSS-3, left for several years? And, it's only ONE point... @-salutations Michel Claveau From exxfile at hotmail.com Mon Mar 24 15:03:26 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 12:03:26 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> Message-ID: <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> On Mar 24, 11:57?am, Jeff wrote: > What does the code look like? # Random Access # Demonstrates string indexing # Michael Dawson - 1/27/03 import random word = "index" print "The word is: ", word, "\n" high = len(word) low = -len(word) for i in range(10): position = random.randrange(low, high) print "word[", position, "]\t", word[position] raw_input("\n\nPress the enter key to exit.") The code is an exerp from a chm file . I am petty sutre I am nmot getting a char map error from the copy/paste ! it looks simple enough ! From istvan.albert at gmail.com Thu Mar 27 11:54:58 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 27 Mar 2008 08:54:58 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: <148e049b-f165-4a92-962d-11bc325db5ca@2g2000hsn.googlegroups.com> On Mar 26, 5:28 pm, Sean Davis wrote: > I am working with genomic data. Basically, it consists of many tuples > of (start,end) on a line. I would like to convert these tuples of > (start,end) to a string of bits where a bit is 1 if it is covered by > any of the regions described by the (start,end) tuples and 0 if it is > not. I then want to do set operations on multiple bit strings (AND, > OR, NOT, etc.). Any suggestions on how to (1) set up the bit string > and (2) operate on 1 or more of them? Java has a BitSet class that > keeps this kind of thing pretty clean and high-level, but I haven't > seen anything like it for python. The solution depends on what size of genomes you want to work with. There is a bitvector class that probably could do what you want, there are some issues on scaling as it is pure python. http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html If you want high speed stuff (implemented in C and PyRex) that works for large scale genomic data analysis the bx-python package might do what you need (and even things that you don't yet know that you really want to do) http://bx-python.trac.bx.psu.edu/ but of course this one is a lot more complicated i. From fn681 at ncf.ca Sun Mar 2 11:37:15 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 02 Mar 2008 11:37:15 -0500 Subject: Problem with the strip string method Message-ID: The Library Reference has strip( [chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip() 'spacious' >>> 'www.example.com'.strip('cmowz.') 'example' Only the last two examples below behave as expected. Is it intended that the full range of characters be handled? Colin W. [Dbg]>>> 'ab$%\n\rcd'.strip('%') 'ab$%\n\rcd' [Dbg]>>> 'ab$%cd'.strip('$') 'ab$%\n\rcd' [Dbg]>>> 'ab$%cd'.strip('$') 'ab$%cd' [Dbg]>>> ' ab$%cd '.strip('$') ' ab$%cd ' [Dbg]>>> ' ab$%cd '.strip('%') ' ab$%cd ' [Dbg]>>> ' spacious '.strip() 'spacious' [Dbg]>>> 'www.example.com'.strip('cmowz.') 'example' From pavlovevidence at gmail.com Sat Mar 29 15:49:05 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Mar 2008 12:49:05 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <3e6de9d7-4278-4b1e-9373-78c98fa11a3f@m34g2000hsc.googlegroups.com> On Mar 29, 6:55 am, kwitt... at telenet.be wrote: > why would anyone Questions that begin with the words "why would anyone" are almost always betray an arrogance about their own beliefs and an ignorance (or feigning ignorance) of human nature. Wiser folks know better than to phrase this question so judgmentally. > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). 1. It's not going to change in Python 3.0. 2. It's a silly thing to care so much about that you will avoid using a langauge because of it. Carl Banks From george.sakkis at gmail.com Mon Mar 24 15:09:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Mar 2008 12:09:01 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> On Mar 24, 2:53 pm, pythonnubie wrote: > Hi Everyone > > I am new to programming in general although I have read alot and > done alot of experimentation as well as researched afew languages > namely java python and visual basic . My conclusion is that python > is one of the best because it eliminates the need to learn about > access modifiers and form handlers so a user can concentrate > primarliy on the nuts and bolts of the language . > > i have come across my first exeption using randrange . The exeption > is " no such attribute " in module random > > platform is xp home and the python build is activestate 2.5 Welcome aboard! There's definitely a randrange function in the random module, so something else must be wrong. To get the most out of this list and minimize wasted bandwidth, the most effective way usually consists of copying and pasting: 1. The offending code (or just the relevant part if it's too big). 2. The full traceback of the raised exception. Regards, George From gherron at islandtraining.com Sat Mar 29 15:11:05 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 29 Mar 2008 12:11:05 -0700 Subject: problem with logic in reading a binary file In-Reply-To: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Message-ID: <47EE9449.2080607@islandtraining.com> Bryan.Fodness at gmail.com wrote: > Hello, > > I am having trouble writing the code to read a binary string. I would > like to extract the values for use in a calculation. > > Any help would be great. > Without having looked at your code an any detail, may I humbly suggest that you throw it all out and use the struct module: http://docs.python.org/lib/module-struct.html It is meant to solve this kind of problem, and it is quite easy to use. Gary Herron > Here is my function that takes in a string. > > def parseSequence(data, start): > > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > pos = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > return element, start, value > > else: > return element, start, value > > else: > return element, pos, value > > And, here is a sample string (I have split up and indented for > readability). There is an identifier (\xfe\xff\x00\xe0) followed by > the length of the nested values. > > > '\xfe\xff\x00\xe0\x18\x02\x00\x00 -length=536 > \n0q\x00\x02\x00\x00\x001 > \n0x\x00\x02\x00\x00\x0010 > \n0\x80\x00\x02\x00\x00\x004 > \n0\xa0\x00\x02\x00\x00\x000 > \x0c0\x04\x00\xe8\x01\x00\x00 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 > \n0\x86\x00\x10\x00\x00\x00127.378510918301 > \x0c0\x06\x00\x02\x00\x00\x001 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x001.629998e-1 > \n0\x86\x00\x10\x00\x00\x0023.159729257873 > \x0c0\x06\x00\x02\x00\x00\x004 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.26285318894435 > \n0\x86\x00\x10\x00\x00\x00227.690980638769 > \x0c0\x06\x00\x02\x00\x00\x003 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.52797639111557 > \n0\x86\x00\x10\x00\x00\x00263.433384670643 > \x0c0\x06\x00\x02\x00\x00\x002 ') > > > From python.list at tim.thechases.com Sun Mar 23 21:05:58 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 23 Mar 2008 20:05:58 -0500 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: <47E6FE76.40508@tim.thechases.com> > When I run this script, I got the following exception: > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xb7d8ac6c>> ignored > > To to newcomer like me, this message doesn't make much sense. What > seems weird to me is that, if I change the variable cathy to something > else, like cath, or even cat, then the script will finish gracefully. > Why "cathy" is not liked?!! > > My python is of version 2.5.1, on Ubuntu. When I first read this, I thought you were crazy. I ran the code, and you're not. I tried under versions 2.3, 2.4, and 2.5 on my Debian box, and got the same results. Neither "cathy" nor "ca" works, but "c", "cat", "cath", "cath_y" and "cathy_" all work just fine. Even more infuriating is that if I try and use pdb to debug, Swaroop drops into pdb, but Abdul and Cathy both error out. That's just plain nuts. Something odd is happening with __del__ calls. -tkc From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 09:47:39 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 15:47:39 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <47d003f8$0$8335$426a74cc@news.free.fr> Guillermo a ?crit : > Wow, I think I'm gonna like this forum. Thank you all for the prompt > answers! Welcome onboard !-) >> What makes you say you "need" to know this ? Except for a couple corner >> cases, you usually don't need to care about this. If you told us more >> about the actual problem (instead of asking about what you think is the >> solution), we might be of more help... > > Good point. > > I want to iterate recursively a dictionary whose elements might be > strings or nested tuples or dictionaries and then convert values to a > tagged format according to some rules. If you're absolutely definitively 101% sure that you'll never have anything else in your dict - IOW : this dict is an internal part of your module, produced by the module and consumed by the module -, then it *might* be one of the corner cases where testing type (either directly or - preferably - via isinstance) is the right thing to do. > d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y': > ('a','b','c')}} > > I'm just designing the algorithm, but I think Python dictionaries can > hold any kind of sequence? Any Python object (which include classes, modules, functions etc) can be used as value. From __peter__ at web.de Mon Mar 24 15:15:16 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Mar 2008 20:15:16 +0100 Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> Message-ID: pythonnubie wrote: > On Mar 24, 11:57?am, Jeff wrote: >> What does the code look like? > > # Random Access > # Demonstrates string indexing > # Michael Dawson - 1/27/03 > > import random > > word = "index" > print "The word is: ", word, "\n" > > high = len(word) > low = -len(word) > for i in range(10): > position = random.randrange(low, high) > print "word[", position, "]\t", word[position] > > raw_input("\n\nPress the enter key to exit.") > > The code is an exerp from a chm file . I am petty sutre I am > nmot getting a char map error from the copy/paste ! it looks > simple enough ! You have probably called your script random.py, and now it imports itself instead of the random.py module in Python's standard library. Rename your script to myrandom.py, remove the compiled version random.pyc in the same folder, and you should be able to run it successfully. Peter From josef.pktd at gmail.com Sun Mar 16 09:23:21 2008 From: josef.pktd at gmail.com (joep) Date: Sun, 16 Mar 2008 06:23:21 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> Message-ID: <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> Tim Golden wrote: > subprocess.call ([ > > r"C:\Program Files\Adobe\Acrobat 5.0\Reader\acro reader.exe", > > r"C:\Program Files\Adobe\Acr > obat 5.0\Reader\plug_ins.donotuse\Annotations\Stamps\abc def.pdf" > > ]) > > Can you confirm that something equivalent *doesn't* work on your > setup? Or have I misunderstood your point earlier? I'd really > like to get to the point where we can definitively state: this > works (and possibly: that doesn't). > > Thanks > TJG This works without problems for me on Windows XP, Python 2.4.3 In the past, I didn't have problems with subprocess.call, and I never had to look closer to the different versions of quoting. I often had problems understanding subprocess.Popen and getting it to work. For example the equivalent case for popen, as your subprocess.call example, does not work, or I'm making a different mistake with subprocess.Popen: p = subprocess.Popen([ r"C:\Program Files\WinRAR\Rar.exe", r"C:\temp\Copy of papers.rar"], shell=True, stdout=subprocess.PIPE) rettext,reterror = p.communicate() retcode = p.wait() p.stdout.close() results in: 'C:\Program' is not recognized as an internal or external command, operable program or batch file. I assume that there is some difference how subprocess.call and subprocess.Popen handle and format the command. subprocess.Popen does the correct formatting when only one file path has spaces and requires double quoting, but not if there are two file paths with spaces in it. Josef From knut.urbye at gmail.com Thu Mar 27 11:12:55 2008 From: knut.urbye at gmail.com (Knut) Date: Thu, 27 Mar 2008 08:12:55 -0700 (PDT) Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: <6347ae92-a8c9-40db-a822-6a4bfcf3e8cb@i7g2000prf.googlegroups.com> This is frustrating. I was working on writing a sample for my problem. I start with dissecting my code which still gives the same error. Then I start thinking that it might be my setup file doing the damage. And i start it from scratch. Everything suddenly works. Fine! i think, i will have to start over with the setup file. Buy i give the old setup a last go, and guess what. It works. So I am honestly utterly frustrated.. I have no idea what what the reason for the problem, but apparently it is solved, for now. Thanks for all you comments and help. I really appreciate it! K From gagsl-py2 at yahoo.com.ar Sun Mar 2 03:48:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 06:48:11 -0200 Subject: Telnet versus telnetlib References: <8acce230-4acf-43fe-9cb7-e4e50350381e@s13g2000prd.googlegroups.com> <13ska3aju6cse5b@corp.supernews.com> Message-ID: En Sun, 02 Mar 2008 02:09:14 -0200, Grant Edwards escribi?: > On 2008-03-01, Gabriel Genellina wrote: >> En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis >> escribi?: >> >>> When I do an analogous process using telnetlib, I get no debug output, >>> and most importantly, when I send the XML file to the host, I get no >>> printed page. Unfortunately, I do not have access to the host to do >>> troubleshooting there, so I have to "feel" my way around. Any >>> suggestions on what might be going wrong? >>> >>> In [12]: tn.write(""" >>> ....: > >> \ is the quote character. You have to duplicate it "C:\\labels..." or >> use >> a raw string r""" > Or use a forward slash: > > "C:/labels/anzick_primary_sample.lbl" I didn't menction that alternative because it generates a different string; the resulting xml document may or may not be equivalent. -- Gabriel Genellina From deets at nospam.web.de Sun Mar 9 15:31:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 20:31:25 +0100 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: <63ilglF28106hU1@mid.uni-berlin.de> Message-ID: <63is8gF27pndgU1@mid.uni-berlin.de> Jeff Schiller schrieb: > I said "PythonQt" not PyQt. That's an important distinction, I think :) > > See http://pythonqt.sourceforge.net/ It sure is. Sorry, didn't realize the difference. Diez From castironpi at gmail.com Thu Mar 6 13:32:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 10:32:42 -0800 (PST) Subject: Identifying messages in a thread (was: Please keep the full address) References: <8763w094sy.fsf_-_@benfinney.id.au> <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> Message-ID: <5b712074-8cce-426f-a103-dab6a4b9a8ad@y77g2000hsy.googlegroups.com> On Mar 6, 10:47?am, "D'Arcy J.M. Cain" wrote: > On Thu, 6 Mar 2008 07:58:06 -0800 (PST) > > Carl Banks wrote: > > > I don't want to have to tag every thread. ?I just want to *plonk* > > > certain posters. > > > > Anyway, I'll live with Google's failings I guess. > > > Sounds like you need better filtering. > > > A decent news filter should be able not only kill a poster, but also > > all followups to that poster recursively. > > Actually, I am reading this as a mailing list and since I run Unix and > procmail I am sure that I could set something up if it really starts to > be annoying. ?So far the simple filters deal with all but a smattering > of problem postings so I don't need to expend the time. The Google Groups reader doesn't always let you see new replies to really old messages, something they should change (this means you). But there is an 'active old threads', but it doesn't catch every one. I want to read those plonk. From deets at nospam.web.de Fri Mar 7 09:50:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 07 Mar 2008 15:50:58 +0100 Subject: hidden built-in module In-Reply-To: <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> Message-ID: <63d32jF23f54eU1@mid.uni-berlin.de> koara schrieb: > On Mar 5, 1:39 pm, gigs wrote: >> koara wrote: >>> Hello, is there a way to access a module that is hidden because >>> another module (of the same name) is found first? >>> More specifically, i have my own logging.py module, and inside this >>> module, depending on how initialization goes, i may want to do 'from >>> logging import *' from the built-in logging. >>> I hope my description was clear, cheers. >>> I am using python2.4. >> you can add your own logging module in extra directory that have __init__.py and >> import it like: from extradirectory.logging import * >> >> and builtin: from logging import * > > > Thank you for your reply gigs. However, the point of this namespace > harakiri is that existing code which uses 'import logging' ... > 'logging.info()'... etc. continues working without any change. > Renaming my logging.py file is not an option -- if it were, i wouldn't > bother naming my module same as a built-in :-) You can only try and search the sys-path for the logging-module, using sys.prefix and then look for logging.py. Using __import__(path) you get a reference to that module. Diez From deets at nospam.web.de Tue Mar 25 12:08:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Mar 2008 17:08:08 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <29bc6ff2-f172-4776-87b7-884585277570@d21g2000prf.googlegroups.com> <4b864142-5323-46f6-aac5-d39ea7ad64ec@s19g2000prg.googlegroups.com> Message-ID: <64smbvF2de27aU1@mid.uni-berlin.de> Anthony wrote: > On Mar 25, 2:31 pm, Tzury Bar Yochay wrote: >> I wish it was that simple but 'a = Foo().getid()' is actually creating >> a new instance of Foo whereas I want the data of the Foo instanced by >> __init__ of FooSon(). > > I don't think Foo.__init__(self) creates an instance of the Foo > class. If you want FooSon to create an instance of Foo, try: You wrote: a = Foo().getid() Which indeed creates a *new* Foo-instance. So it's of no use to the OP. Of course Foo.(self) calls that method without creating a new instance, which is the behavior one uses when invoking the constructor of Foo inside FooSon.__init__. But that doesn't make your example any better. Diez From grante at visi.com Sat Mar 1 23:12:19 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 04:12:19 -0000 Subject: invert or not ? References: Message-ID: <13ska93iif10eab@corp.supernews.com> On 2008-03-01, Stef Mientki wrote: > from the manual I read that a bitwise inversion should be done > by invert. But from some experiments I see that not works > equally well. What experiments are those? >>> print ~0xaa, not 0xaa -171 False >>> print ~0x55, not 0x55 -86 False >>> >>> print ~True, not True -2 False >>> > Is this coincidence ? Is what coincidence? > (The disadvantage of invert is that I've to import operators) No you don't. -- Grant Edwards grante Yow! If elected, Zippy at pledges to each and every visi.com American a 55-year-old houseboy... From aaron.watters at gmail.com Thu Mar 27 16:37:33 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Thu, 27 Mar 2008 13:37:33 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: > "this";"is";"a";"test" > > Resulting in an output of: > > ['this', 'is', 'a', 'test'] > > However, if I modify the csv to: > > "t"h"is";"is";"a";"test" > > The output changes to: > > ['th"is"', 'is', 'a', 'test'] I'd be tempted to say that this is a bug, except that I think the definition of "csv" is informal, so the "bug/feature" distinction cannot be exactly defined, unless I'm mistaken. What I would do is write roll my own parser using very simple python and check that it works for the examples of interest. If, for example, you can assume that the delimiter will never occur inside the payload and the payload contains no "quoted" characters you could do something like: ==== cut def trimQuotes(txt): txt = txt.strip() if txt: start = txt[0] end = txt[-1] if start==end and start in ('"', "'"): return txt[1:-1] return txt def simpleCsv(lines, delimiter): for line in lines: fields = line.split(delimiter) fields = map(trimQuotes, fields) yield fields def test(): lines = ['"t"h"is";"is";"a";"test"'] for fields in simpleCsv(lines, ';'): print fields if __name__=="__main__": test() === cut If you want fame and admiration you could fix the arguably bug in the csv module and send the patch to the python bugs mailing list. However, I just had a perusal of csv.py.... good luck :). -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=too+general From watine at cines.fr Fri Mar 14 07:37:50 2008 From: watine at cines.fr (Benjamin Watine) Date: Fri, 14 Mar 2008 12:37:50 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: <47DA638E.7030800@cines.fr> Bryan Olson a ?crit : > I wrote: >> [...] Pipe loops are tricky business. >> >> Popular solutions are to make either the input or output stream >> a disk file, or to create another thread (or process) to be an >> active reader or writer. > > Or asynchronous I/O. On Unix-like systems, you can select() on > the underlying file descriptors. (MS-Windows async mechanisms are > not as well exposed by the Python standard library.) > Hi Bryan Thank you so much for your advice. You're right, I just made a test with a 10 MB input stream, and it hangs exactly like you said (on cat.stdin.write(myStdin))... I don't want to use disk files. In reality, this script was previously done in bash using disk files, but I had problems with that solution (the files wasn't always cleared, and sometimes, I've found a part of previous input at the end of the next input.) That's why I want to use python, just to not use disk files. Could you give me more information / examples about the two solutions you've proposed (thread or asynchronous I/O) ? Thank you ! Ben From gandalf at shopzeus.com Fri Mar 21 07:38:49 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 21 Mar 2008 12:38:49 +0100 Subject: eval and unicode In-Reply-To: <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E39E49.6020107@shopzeus.com> > > Your problem is, I think, that you think the magic of decoding source > code from the byte sequence into unicode happens in exec or eval. It > doesn't. It happens in between reading the file and passing the > contents of the file to exec or eval. > I think you are wrong here. Decoding source happens inside eval. Here is the proof: s = 'u"' + '\xdb' + '"' print eval(s) == eval( "# -*- coding: iso8859-2\n" + s) # prints False, indicating that the decoding of the string expression happened inside eval! It can also be prooven that eval does not use 'ascii' codec for default decoding: '\xdb'.decode('ascii') # This will raise an UnicodeDecodeError eval() somehow decoded the passed expression. No question. It did not use 'ascii', nor 'latin2' but something else. Why is that? Why there is a particular encoding hard coded into eval? Which is that encoding? (I could not decide which one, since '\xdb' will be the same in latin1, latin3, latin4 and probably many others.) I suspected that eval is going to use the same encoding that the python source file/console had at the point of execution, but this is not true: the following program prints u'\xdb' instead of u'\u0170': # -*- coding iso8859-2 -*- s = '\xdb' expr = 'u"' + s +'"' print repr(eval(expr)) Regards, Laszlo From ptmcg at austin.rr.com Mon Mar 24 19:55:41 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 16:55:41 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: Message-ID: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> On Mar 24, 6:32?pm, Tess wrote: > Hello All, > > I have a Beautiful Soup question and I'd appreciate any guidance the > forum can provide. > I *know* you're using Beautiful Soup, and I *know* that BS is the de facto HTML parser/processor library. Buuuuuut, I just couldn't help myself in trying a pyparsing scanning approach to your problem. See the program below for a pyparsing treatment of your question. -- Paul """ My goal is to extract all elements where the following is true:

and

. """ from pyparsing import makeHTMLTags, withAttribute, keepOriginalText, SkipTo p,pEnd = makeHTMLTags("P") p.setParseAction( withAttribute(align="left") ) div,divEnd = makeHTMLTags("DIV") div.setParseAction( withAttribute(align="center") ) # basic scanner for matching either

or

with desired attrib value patt = ( p + SkipTo(pEnd) + pEnd ) | ( div + SkipTo(divEnd) + divEnd ) patt.setParseAction( keepOriginalText ) print "\nBasic scanning" for match in patt.searchString(html): print match[0] # simplified data access, by adding some results names patt = ( p + SkipTo(pEnd)("body") + pEnd )("P") | \ ( div + SkipTo(divEnd)("body") + divEnd )("DIV") patt.setParseAction( keepOriginalText ) print "\nSimplified field access using results names" for match in patt.searchString(html): if match.P: print "P -", match.body if match.DIV: print "DIV -", match.body Prints: Basic scanning

P1

div2a
div2b

P3

div3b

P4

div4b
Simplified field access using results names P - P1 DIV - div2a DIV - div2b P - P3 DIV - div3b P - P4 DIV - div4b From martin.laloux at gmail.com Fri Mar 14 05:29:56 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Fri, 14 Mar 2008 02:29:56 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: <6be1cc04-6739-485a-808e-b2fb0faa0887@i7g2000prf.googlegroups.com> use the glob module import os, glob dor = the path you want for dir, subdir, files in os.walk(dor): for file in files: if glob.fnmatch.fnmatch(file,"*.txt"): do what you want From saeed008 at umn.edu Fri Mar 7 17:25:51 2008 From: saeed008 at umn.edu (Maryam Saeedi) Date: Fri, 7 Mar 2008 16:25:51 -0600 Subject: os.chdir Message-ID: I have a problem using os.chdir on linux. What should I do if I want to change to root directory? The below does not work: os.chdir("~/dir1") Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvschorre at sbcglobal.net Wed Mar 19 15:41:17 2008 From: dvschorre at sbcglobal.net (dvschorre at sbcglobal.net) Date: Wed, 19 Mar 2008 12:41:17 -0700 (PDT) Subject: Calling Mac programs from Python instead of from AppleScript Message-ID: When I'm running Script Editor, I can get Maya to draw a sphere by typing: tell application "Maya" execute "sphere" end tell When I try this using Python, I get this error message: IDLE 1.2.2 >>> app('Maya').execute('sphere') Traceback (most recent call last): File "", line 1, in app('Maya').execute('sphere') NameError: name 'app' is not defined >>> Maybe I need to load some libraries first. Please help me to get started. Thanks Dewey V. Schorre From tms at zeetix.com Sat Mar 15 13:53:52 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 13:53:52 -0400 Subject: No subject Message-ID: <003e01c886c5$8837b290$0200a8c0@TMSMAIN> > Somehow I don't get what you are after. The ' doesn't have to be escaped > at all if " are used to delimit the string. If ' are used as delimiters > then \' is a correct escaping. What is the problem with that!? If I delimit the string with double quote, then I have to escape every double quote in whatever I serialize. I'm moving strict html from the server to the browser, and therefore the value of every tag attribute is delimited by double quotes. That means that I'd have to escape every double quote, and there are MANY more of them. From fuzzyman at gmail.com Mon Mar 10 11:13:23 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 10 Mar 2008 08:13:23 -0700 (PDT) Subject: Python-URL! - weekly Python news and links (Feb 18) References: Message-ID: On Mar 10, 2:33 pm, Piet van Oostrum wrote: > >>>>> Peter Otten <__pete... at web.de> (PO) wrote: > >PO> Piet van Oostrum wrote: > >>>>>>>> "Gabriel Genellina" (GG) wrote: > > >GG> "Given this indispensable process and architecture issue, isn't it > >>>> obvious GG> that it's totally irrelevant to the system's overall safety > >>>> whether the GG> compiler has performed the further smattering of > >>>> semantically puny GG> 'verifications' allowed by mandatory-declaration, > >>>> stating-typing GG> languages?" - Alex Martelli > I've just been at a student conference in Krakow (SFI) where I heard a talk by Gilad Bracha on the problems with Java (and he is in a position to know!). I will write it up in a blog entry, but my two favourite quotes from his talk are: 1. The programs that can be written in languages with static type systems are a subset of all possible programs. For some people this is enough. 2. Mandatory static typing is an inherent security risk. He has a very interesting tale about Java to demonstrate the second point... Michael http://www.manning.com/foord > >>> I couldn't find the original of this. I would like to see it in its > >>> context. Googling didn't reveal anything but this Python-URL. > >PO> My google is better than yours then: > >PO>http://mail.python.org/pipermail/python-list/2003-March/193864.html > > Thanks. I probably have searched for "mandatory-declaration, static-typing > languages" instead of "mandatory-declaration, stating-typing languages" > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From carsten at uniqsys.com Sun Mar 23 20:05:36 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 01:05:36 +0100 Subject: always getting 'None' return value from PyObject_CallObject In-Reply-To: References: Message-ID: <1206317136.3365.6.camel@localhost.localdomain> On Sun, 2008-03-23 at 23:43 +0000, Gal Aviel wrote: > [...] > When calling a function defined in my module, the function executes Ok How do you know that? > - it sees > the correct arguments being passed from C How do you know that? > , and executes 100% How do you know that? > - only the return > value is always 'None' How are you reaching this conclusion? > (I tried returning a simple integer like '5' which > doesn't work). What does "doesn't work" mean? -- Carsten Haese http://informixdb.sourceforge.net From samuel.progin at gmail.com Mon Mar 10 17:29:36 2008 From: samuel.progin at gmail.com (Sam) Date: Mon, 10 Mar 2008 14:29:36 -0700 (PDT) Subject: execute python script question References: Message-ID: <9e299ffa-2fab-4dcc-907c-8aa667bde3d4@n58g2000hsf.googlegroups.com> Hello, I may misunderstand your problem, but it may be related to the execution environment, especially the PYTHONPATH variable. Have a look at the following log: samuel at Bioman2:/$ pwd / samuel at Bioman2:/$ cat -n /tmp/test_import.py 1 class A(object): 2 def __init__(self): 3 self.value = 1 4 def show(self): 5 print self.value samuel at Bioman2:/$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from test_import import A Traceback (most recent call last): File "", line 1, in ImportError: No module named test_import >>> exit() samuel at Bioman2:/$ export PYTHONPATH=/tmp samuel at Bioman2:/$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from test_import import A >>> a=A() >>> a.show() 1 >>> ++ Sam From castironpi at gmail.com Sun Mar 16 05:58:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 02:58:57 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: <87od9f3vrt.fsf@physik.rwth-aachen.de> Message-ID: <79e48717-37cb-4d60-a76b-4fafdb79153a@2g2000hsn.googlegroups.com> On Mar 16, 3:42?am, Torsten Bronger wrote: > Hall?chen! > > castiro... at gmail.com writes: > > [...] > > *** English is SVO, subject-verb-object. ?French is too, unless the > > object is direct: subject- direct-object -verb. > > Really? ?I thought this is only the case for pronouns. Yes, yes, I remembered that later on tonight. A complete misformulation... sigh. Subject objective-pronoun verb objective- noun(-phrase). What factors in to L'Academie Francaise's decisions? From greg at cosc.canterbury.ac.nz Fri Mar 28 19:59:22 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 29 Mar 2008 11:59:22 +1200 Subject: Can my own objects support tuple unpacking? In-Reply-To: <13um6p08v0ea9f3@corp.supernews.com> References: <13um6p08v0ea9f3@corp.supernews.com> Message-ID: <655fdfF2e9gooU1@mid.individual.net> Scott David Daniels wrote: > class Foo(object): # _Never_ use old-style without a reason > def __getitem__(self, index): > print index > if index < 3: > return index * 5 # just to see > raise IndexError('Zapped') # The secret -- run out. Another way is to make your object iterable -- read up about the "iterator protocol". -- Greg From here at softcom.net Wed Mar 26 17:42:31 2008 From: here at softcom.net (Sal) Date: Wed, 26 Mar 2008 14:42:31 -0700 (PDT) Subject: Newbie: unsigned shift right Message-ID: <276efacc-dad3-4844-a3b4-a6845c71473b@h11g2000prf.googlegroups.com> Is there any way to do an unsigned shift right in Python? When I enter (-1>>1) the answer is -1. What I'm looking for is the equivalent of an unsigned shift in C or the ">>>" operator in Java. From pavloutefkros at gmail.com Sun Mar 9 17:33:01 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 9 Mar 2008 14:33:01 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: ok i found a workaround. From mal at egenix.com Tue Mar 4 05:41:16 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 04 Mar 2008 11:41:16 +0100 Subject: tools to install not in python tree? In-Reply-To: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: <47CD274C.7080207@egenix.com> On 2008-03-04 02:55, commander_coder at hotmail.com wrote: > Hello, > > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ and some programs that I want in ~/public_html/ . I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). But as I understand it setup only targets > installing below sys.prefix; is that right? The distutils "install" command provides a lot of what you're looking for, in particular, it makes it easy to install the various parts of a package in different directories: $ python2.5 setup.py install --help Common commands: (see '--help-commands' for more) setup.py build will build the package underneath 'build/' setup.py install will install the package Global options: --verbose (-v) run verbosely (default) --quiet (-q) run quietly (turns verbosity off) --dry-run (-n) don't actually do anything --help (-h) show detailed help message --set-version override the package version number Options for 'mx_install' command: --prefix installation prefix --exec-prefix (Unix only) prefix for platform-specific files --home (Unix only) home directory to install under --install-base base installation directory (instead of --prefix or -- home) --install-platbase base installation directory for platform-specific files (instead of --exec-prefix or --home) --root install everything relative to this alternate root directory --install-purelib installation directory for pure Python module distributions --install-platlib installation directory for non-pure module distributions --install-lib installation directory for all module distributions (overrides --install-purelib and --install-platlib) --install-headers installation directory for C/C++ headers --install-scripts installation directory for Python scripts --install-data installation directory for data files --compile (-c) compile .py to .pyc [default] --no-compile don't compile .py files --optimize (-O) also compile with optimization: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0] --force (-f) force installation (overwrite any existing files) --skip-build skip rebuilding everything (for testing/debugging) --record filename in which to record list of installed files usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help > I can write routines for myself but other people must need to do these > things also and a tested solution is obviously better. Is there such > a tool? Things that the stock distutils cannot do out of the box can easily be added by subclassing commands or adding new ones in your setup.py. For some examples how this can be done, have a look at e.g. the mxSetup.py module we ship with the eGenix mx Base Distribution: http://www.egenix.com/products/python/mxBase/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 04 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From python at rcn.com Sat Mar 8 14:15:12 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 8 Mar 2008 11:15:12 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> Message-ID: <54abf8a6-6156-4663-903c-eb761e6b5148@h11g2000prf.googlegroups.com> > > > Is it possible to get an object out of a set() given another object > > > that has the same hash code and equality (__hash__() and __eq__() > > > return the same)? > > > Yes, but it requires an indirect approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299 > > > Raymond > > That's a clever work around. ?Thanks, Raymond. ?Clearly you had a need > for this. ?Do you feel it's a common need that should be submitted as > a Python feature request? ?To me it seems like such a simple thing > that would increase the general utility of the set class. ?I suppose I > could start another thread like "feature request: New method for set - > get_equivalent". Glad you liked the recipe. :-) FWIW, it is not specific to sets. The recipe works with any container including dictionaries and lists. The approach is easily extended to any situation with equality testing. For example, it can be used with list.remove(x) to find the identity of the removed object. Long ago, I rejected adding get_equivalent() to the set API. The existing API has a near zero learning curve and it would be nice to keep it that way. For most use cases, the obvious, explicit approach is better. Just make a dictionary where the value is the canonical representative of the equivalence class: >>> d = {1:1, 2:2, 3:3} >>> d[2.0] 2 The intern() builtin uses this approach: interned = {} def intern(s): if s in interned: return interned[s] interned[s] = s return s Raymond From castironpi at gmail.com Thu Mar 6 00:57:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 21:57:37 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> <87hcfk30lo.fsf@micah.cowan.name> Message-ID: <4710658c-1d2f-44b2-a9ed-badd9f7391ae@m36g2000hse.googlegroups.com> > > *plonk* > > > key is an iterable, just like the constructors to > > other collection. > > Um... "*plonk*" is the (imaginary) sound made by dropping someone into > your plonkfile (killfile, scorefile, whatever): the action of setting > your newsreader to ignore someone you perceive to be a troll. > > I have extreme doubts that you have actually done this to _yourself_. Your doubts are extreme! From pavloutefkros at gmail.com Sun Mar 2 09:38:50 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 06:38:50 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: you could at least check before posting. as i said i've tried like 1000 ways of doing that, and im so desparate that i'm thinking of quiting python. This damn thing just doesnt work. when i do as you post the server never even replies, as it tends to accept connections all the time. anyone has a better idea? From bearophileHUGS at lycos.com Tue Mar 25 19:38:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 25 Mar 2008 16:38:39 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: <39f5237e-fed7-4f66-9291-08099e213f25@e6g2000prf.googlegroups.com> Kelly Greer: > What is the best way to filter a Python list to its unique members? If Python is "batteries included", then an industrial-strength unique() seems one of the most requested 'batteries' that's not included :-) I feel that it's coming in Python 2.6/3.x. In the meantime: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438599 Bye, bearophile From castironpi at gmail.com Tue Mar 4 13:26:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:26:33 -0800 (PST) Subject: is there enough information? References: <13spkb9eirsq26d@corp.supernews.com> Message-ID: <30b6d419-5965-46b5-bc3d-ea9ff6b35736@h11g2000prf.googlegroups.com> On Mar 3, 10:34?pm, Dennis Lee Bieber wrote: > On Mon, 3 Mar 2008 07:00:55 -0800 (PST), castiro... at gmail.com declaimed > the following in comp.lang.python: > > > What's the API call for it? > > ? ? ? ? I'd suspect one of the win32event.WaitFor..., when combined with > win32file.CreateFile(), win32file.ReadFile() with the Overlapped flag > set, win32file.WriteFile() with Overlapped flag set... > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ select maps to two different calls on Windows. From james.pye at gmail.com Tue Mar 4 10:18:32 2008 From: james.pye at gmail.com (james.pye at gmail.com) Date: Tue, 4 Mar 2008 07:18:32 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> Message-ID: <909d5c24-ae7f-4abd-b671-ee4d384f70a0@s12g2000prg.googlegroups.com> On Mar 4, 8:13?am, Siddhant wrote: > Hi people. > I was just wondering if a tab-completion feature in python command > line interface would be helpful? > If yes, then how can I implement it? > Thanks, > Siddhant Is this what you are looking for? http://docs.python.org/lib/module-rlcompleter.html From darcy at druid.net Sun Mar 23 11:52:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 23 Mar 2008 11:52:30 -0400 Subject: Testing for an empty dictionary in Python In-Reply-To: <47e67a99$0$36364$742ec2ed@news.sonic.net> References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <20080323115230.0f45091b.darcy@druid.net> On Sun, 23 Mar 2008 08:53:02 -0700 John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). Try this: if dict: It should be faster as it only checks whether or not there are any members and does not run keys() or len() on the dictionary. Of course, you should test 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 andrei.avk at gmail.com Wed Mar 12 20:07:48 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Wed, 12 Mar 2008 17:07:48 -0700 (PDT) Subject: Open a file with default handler app? References: <83bc9bf2-9b9c-4959-870f-f4b37281f6e0@m3g2000hsc.googlegroups.com> <79ae8d93-5845-466c-b7f8-e345c3d63c46@i7g2000prf.googlegroups.com> Message-ID: <231ef3b4-c595-4826-bb5f-affafdc561fd@u69g2000hse.googlegroups.com> On Mar 11, 11:50?pm, Wubbul... at gmail.com wrote: > > Hey there, > I've had to do the same things for a program that I'm writing. The > following command should do the trick: > > os.startfile("yourfilehere") > > from the os module. Hope this helps! That's perfect, thanks a ton++! From lunasf at gmail.com Thu Mar 20 08:29:02 2008 From: lunasf at gmail.com (igbt) Date: Thu, 20 Mar 2008 05:29:02 -0700 (PDT) Subject: A question about a metacharacter References: <09156537-3eb3-4cff-b1f6-3727ca660f6f@p73g2000hsd.googlegroups.com> Message-ID: <9f4e60ad-91f3-424d-afe5-067ee425695a@p73g2000hsd.googlegroups.com> On 20 mar, 12:38, Chris wrote: > On Mar 20, 1:19 pm, igbt wrote: > > > > > I am creating a simple script which is using gtk. In this script you > > must enter a text, if you do not enter anything or you enter a dot, > > the script will be finished. However, if you don't enter anything the > > script works but if you enter a dot (.) the script does not work. I > > was investigating about it and I think the problem is with the dot > > character sss == "." . I was trying the same line with other > > metacharacters like *, (, ) ... and I found the same problem. I was > > looking for an example where I could see the way I could do it without > > any error but I did not find it. Could somebody tell me how can I > > solve this error? > > > sss = entryName.get_text() # The script gets the text > > if sss == "" or sss == ".": > > gtk.main_quit() #The script finishes > > > Thanks ; -) > > try this. > > sss = entryName.get_text() > if not sss.strip() or sss.strip() == '.': > gtk.main_quit() > > I wouldn't be suprised if your input is being captured with End-Of- > Line characters which would cause the mis-match. It does not work. Thanks for your help From xelapond at gmail.com Mon Mar 31 21:40:14 2008 From: xelapond at gmail.com (Alex Teiche) Date: Mon, 31 Mar 2008 18:40:14 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> Message-ID: <1a8a5b03-0b9e-49de-bd87-43fa1aa99dc2@b5g2000pri.googlegroups.com> On Mar 31, 11:49 am, Alex Teiche wrote: > On Mar 30, 3:50 pm, Benjamin wrote: > > > > > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > implement the following thing into my python application: > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > it, but I could not get this specific thing to work. Can someone give > > > me some hints as to get it working in Python? > > > What problems are you having? > > > > Thanks a ton, > > > > Alex > > Thanks everyone for your help. I found the example to be particularly > helpful, and I have made a simplified version just to display an icon > with a quit button in its menu. Once I know how to do that I will > incorporate it into my larger program, with more options and the > ability show messages. The problem is, it doesn't work, and I can't > find out what's wrong. Can you give me some hints? > > Here is the code: > import sys > from PyQt4 import QtGui, QtCore > > class trayIcon(QtGui.QWidget): > def __init__(self, parent=None): > QtGui.QWidget.__init__(self, parent) > > #********Create Actions for the Tray Menu********# > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > QtCore.QObject.connect(self.quitAction, > QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) > > create_tray_icon() > > self.composeAction.setEnabled(visible) > QtGui.QWidget.setVisible(self, visible) > > self.trayIcon.show() > > def create_tray_icon(self): > self.trayIconMenu = QtGui.QMenu(self) > self.trayIconMenu.addAction(self.composeAction) > self.trayIcon = QtGui.QSystemTrayIcon(self) > self.trayIcon.setContextMenu(self.trayIconMenu) > self.trayIcon.setIcon(bad.svg) > > app = QtGui.QApplication(sys.argv) > sys.exit(app.exec_()) OK, I messed around with it some more, and it works. I just don't know how to set an icon, and the example doesn't help at all. Here is the code: import sys from PyQt4 import QtCore, QtGui class Systray(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.createActions() self.createTrayIcon() #QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL("messageClicked()"), self.messageClicked) #QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.iconActivated) self.trayIcon.show() def createActions(self): #self.minimizeAction = QtGui.QAction(self.tr("Mi&nimize"), self) #QtCore.QObject.connect(self.minimizeAction, # QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("hide()")) #self.maximizeAction = QtGui.QAction(self.tr("Ma&ximize"), self) #QtCore.QObject.connect(self.maximizeAction, # QtCore.SIGNAL("triggered()"), self, # QtCore.SLOT("showMaximized()")) #self.restoreAction = QtGui.QAction(self.tr("&Restore"), self) #QtCore.QObject.connect(self.restoreAction, # QtCore.SIGNAL("triggered()"), self, # QtCore.SLOT("showNormal()")) self.quitAction = QtGui.QAction(self.tr("&Quit"), self) QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) def createTrayIcon(self): self.trayIconMenu = QtGui.QMenu(self) #self.trayIconMenu.addAction(self.minimizeAction) #self.trayIconMenu.addAction(self.maximizeAction) #self.trayIconMenu.addAction(self.restoreAction) #self.trayIconMenu.addSeparator() self.trayIconMenu.addAction(self.quitAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) app = QtGui.QApplication(sys.argv) x = Systray() sys.exit(app.exec_()) How would I go about setting the icon? From george.sakkis at gmail.com Wed Mar 5 10:11:30 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 5 Mar 2008 07:11:30 -0800 (PST) Subject: Why """, not '''? References: Message-ID: <550ce289-9a5b-465f-9183-a7a2094f6e2d@d21g2000prf.googlegroups.com> On Mar 5, 9:56 am, MartinRineh... at gmail.com wrote: > Why is """ the preferred delimiter for multi-line strings? Is it ? FWIW, I use single quotes whenever I can and double whenever I have to (i.e. rarely). George From tjreedy at udel.edu Mon Mar 24 20:11:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Mar 2008 20:11:41 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> <13ufd10ps50mm4a@corp.supernews.com> Message-ID: "Arnaud Delobelle" wrote in message news:ce8f8ec1-80a0-49ac-8762-a8c9d4cbdcc0 at c19g2000prf.googlegroups.com... >From what I remember when I looked at the source: stack frames execute code objects, not functions. They don't know what function has spawned them, only what code object they are executing. In fact when one thinks of it, it makes more sense for code objects to have a name (taken from the def statement) than for function objects, as there is exactly one code object for every def statement. This is what I tried to say before. Function objects have the attributes needed to call the code. Code objects have attributes needed to execute the code. Both have a name for str() and repr(). tjr From zerty.david at gmail.com Wed Mar 26 14:04:44 2008 From: zerty.david at gmail.com (David Anderson) Date: Wed, 26 Mar 2008 15:04:44 -0300 Subject: what does ^ do in python In-Reply-To: <47E97E8B.2010108@tim.thechases.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> Message-ID: <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> HOw can we use express pointers as in C or python? On Tue, Mar 25, 2008 at 7:36 PM, Tim Chase wrote: > > In most of the languages ^ is used for 'to the power of'. > > > > No, not in most languages. In most languages (C, C++, Java, C#, Python, > > Fortran, ...), ^ is the xor operator ;) > > ...and in Pascal it's the pointer-dereferencing operator... > > -tkc > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Mar 10 12:57:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 09:57:54 -0700 (PDT) Subject: tcp client socket bind problem References: Message-ID: <42925034-6cf7-40a7-b079-8f3bf978fea2@n36g2000hse.googlegroups.com> On Mar 10, 9:40?am, Marc Christiansen wrote: > nata... at gmail.com wrote: > > I have a linux box with multiple ip addresses. I want to make my > > python client connect from one of the ip addresses. Here is my code, > > no matter what valid information I put in the bind it always comes > > from the default ip address on the server. Am I doing something wrong? > > > ------------- > > #!/usr/bin/python > > > import socket > > > host = "server" > > port = 1190 > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > sock.bind(("",0)) > > sock.connect((host, port)) > > ------------- > > Looks good to me. Just to verify it, I added 127.1.2.3 as an address to > lo (ip addr add 127.1.2.3/8 dev lo broadcast 127.255.255.255), and... > > ?>>> import socket > ?>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > ?>>> sock.bind(("127.1.2.3",0)) > ?>>> sock.connect(("127.0.0.1",80)) > > In another shell: > tolot:~> lsof -c python -a -i -nP > COMMAND ?PID ?USER ? FD ? TYPE ?DEVICE SIZE NODE NAME > [...] > python ?1287 tolot ? ?3u ?IPv4 3553610 ? ? ? TCP 127.1.2.3:38329->127.0.0.1:80 (ESTABLISHED) help string: Bind the socket to a local address. For IP sockets, the address is a pair (host, port); the host must refer to the local host. docs: Bind the socket to address. Wikipedia: Before a socket may accept incoming connections, it must be bound. PHP.net: Binds the name given in address to the socket described by socket . This has to be done before a connection is be established using socket_connect() or socket_listen(). This function must be used on the socket before socket_connect(). From python at rcn.com Fri Mar 7 14:14:38 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 7 Mar 2008 11:14:38 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> Message-ID: <51ca8638-65fa-490b-a04a-33ffbefd4aca@s19g2000prg.googlegroups.com> [bearophileH] > I find itertools.islice() useful, so for Python 3.x I may like to see > it removed from the itertools module, and the normal slicing syntax > [::] extended to work with generators/iterators too. This is a can of worms. First, remember iterations is a protocol, not a type. So, this would have to be added to every possible iterator class (dict.iteritems() and enumerate() for example). Second, he who wants slicing, at some time will want getitem, but Guido ruled this out long ago saying that it is a mistake to conflate sequences and general iterables. Third, the analogy breaks down quickly (i.e. chain(it[:2], it[2:]) does not give the same result as iter(it) unless working on a re-iterable sequence). Fourth, this suggests other related hyper-generalizations which also break down in practice (i.e. using the plus operator for chain() breaks down when you write it+it and find that the second one is fully consumed by the time chain() gets to it). Besides, if you know what you're doing it is simple to write a trivial wrapper class that temporarily supports the slicing notation: class W: def __init__(self, it): self.it = iter(it) def __getitem__(self, n): if isinstance(n, slice): return islice(self.it, n.start, n.stop, n.step) return islice(self.it, n, n+1) >>> s = 'abcdefg' >>> list(W(s)[2:]) ['c', 'd', 'e', 'f', 'g'] >>> list(W(s)[:2]) ['a', 'b'] >>> list(W(s)[::2]) ['a', 'c', 'e', 'g'] >>> list(W(s)[2]) ['c'] Raymond From me at privacy.net Sat Mar 15 16:06:26 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 20:06:26 +0000 Subject: Getting started with OS X Leopard In-Reply-To: <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> Message-ID: <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Arnaud Delobelle wrote: > Is there a particular reason you want python from MacPorts? OSX > Leopard comes with python 2.5, that's what I use on my mac. I heard from somewhere that Apple's version was a bit wonky, and that I would be better off with a "proper" build. From kpdere at derenet.us Sun Mar 2 10:27:18 2008 From: kpdere at derenet.us (Ken Dere) Date: Sun, 02 Mar 2008 10:27:18 -0500 Subject: Book Recomendations References: Message-ID: Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira I started off with Fortran 6X so I have been in the business about as long. Do just about everything now in Python. I liked Learning Python Ken D. From castironpi at gmail.com Sun Mar 30 01:34:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 22:34:27 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> <13utgh8j9ik8t7c@corp.supernews.com> Message-ID: On Mar 29, 5:33?pm, Scott David Daniels wrote: > Lie wrote: > > On Mar 30, 2:57 am, mac_the_sco... at hotmail.com wrote: > >> Hi there. > >> I ... started writing simple programs in the python gui... ?when I write > >> python code ...[and]... double click it all that happens is a black box > >> flashes up on the screen, but nothing else!? .... > > > open the program in IDLE (or any other Python IDEs). I'm guessing that > > your program is printing a traceback (error) when trying to get input > > that's why it immediately closes itself. > > Another possibility is to open a shell (or command window or "dos box"), > and in that window type in "python myfile.py" You'll see error messages > because the display window does not depend on the program staying alive. > > By the way, a better thing to have said when you asked this would > include your OS, the python version, and the GUI system you are using. > Those details matter. ?If you are doing wxPython programming, for > example, you cannot easily use IDLE for your program (GUI systems > fight for control of the display). The screen is real (r-e-a-l): all manners intended. Real. Just bid and auction. From PeterBraden1 at googlemail.com Sat Mar 8 20:37:25 2008 From: PeterBraden1 at googlemail.com (PB) Date: Sat, 8 Mar 2008 17:37:25 -0800 (PST) Subject: Image Libraries References: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> Message-ID: <8654ddf0-a3ab-4c2a-a730-95b152512fad@59g2000hsb.googlegroups.com> Maybe I am unaware of the right way to do it, but the only way I can think to draw several shapes of different transparencies is to create an image for each layer and then combine them which seems overly complex. It would be nice to simply be able to specify colors with an alpha value combined (ie RGBA) for image draw operations. Is there a way to do this? Cheers, Peter Ken wrote: > PB wrote: > > I have been using PIL for generating images, however it does not > > easily support operations with transparency etc. > > > > I tried to install aggdraw but it wouldn't compile. > > > > Ideally I'd like something open source so I can adapt it, hopefully > > mostly written in python rather than C. > > > > Is there any other decent image libraries for python? > > > > > I use PIL, and I haven't had any difficulty with alpha channel > transparency. But maybe I'm using it for different things than you > (blitting PGN(RGBA) antialiased images mostly). What problems are you > having specifically? > > Ken Seehart From bj_666 at gmx.net Tue Mar 4 01:51:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Mar 2008 06:51:35 GMT Subject: help needed with regex and unicode References: Message-ID: <6349rmF23qmbmU1@mid.uni-berlin.de> On Tue, 04 Mar 2008 10:49:54 +0530, Pradnyesh Sawant wrote: > I have a file which contains chinese characters. I just want to find out > all the places that these chinese characters occur. > > The following script doesn't seem to work :( > > ********************************************************************** > class RemCh(object): > def __init__(self, fName): > self.pattern = re.compile(r'[\u2F00-\u2FDF]+') > fp = open(fName, 'r') > content = fp.read() > s = re.search('[\u2F00-\u2fdf]', content, re.U) > if s: > print s.group(0) > if __name__ == '__main__': > rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php') > ********************************************************************** > > the php file content is something like the following: > > ********************************************************************** > // Check if the folder still has subscribed blogs > $subCount = function1($param1, $param2); > if ($subCount > 0) { > $errors['summary'] = '?????????????????????????????????????????'; > $errorMessage = '?????????????????????????????????????????'; > } Looks like an UTF-8 encoded file viewed as ISO-8859-1. Sou you should decode `content` to unicode before searching the chinese characters. Ciao, Marc 'BlackJack' Rintsch From roygeorget at gmail.com Tue Mar 11 06:54:23 2008 From: roygeorget at gmail.com (royG) Date: Tue, 11 Mar 2008 03:54:23 -0700 (PDT) Subject: rmdir problem References: Message-ID: <239ccb7e-9c11-4a59-9ec9-f2d3fa8e5efa@h11g2000prf.googlegroups.com> On Mar 11, 3:37 pm, Paul > Have a look at shutil.rmtree > thanks Paul RG From thudfoo at opensuse.us Thu Mar 6 13:19:24 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Thu, 6 Mar 2008 10:19:24 -0800 Subject: Better grammar.txt In-Reply-To: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> Message-ID: <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> On 3/5/08, MartinRinehart at gmail.com wrote: > MartinRineh... at gmail.com wrote: > > It includes three corrections to grammar.txt (imagnumber, xor_expr and > > and_expr) that I've reported. > > > Make that four corrections. Add augop. > > -- > http://mail.python.org/mailman/listinfo/python-list > An error occurred while loading http://www.martinrinehart.com/articles/python-grammar.html: Unknown host www.martinrinehart.com From chris at wonderstore.com Wed Mar 26 10:13:09 2008 From: chris at wonderstore.com (wrightee) Date: Wed, 26 Mar 2008 07:13:09 -0700 (PDT) Subject: PyQT / QDate / QTableWidget Message-ID: <4bba38af-afd9-4696-b71d-19a256fafcea@i7g2000prf.googlegroups.com> Hi, new at PyQT but not coding.. I'm stumbling with QDate and QTableWidget using PyQT and would appreciate some guidance: My server gives me a string y[0]: "20080327", which I convert to a QDateTime object using: x=QDateTime.fromString(y[0],"yyyymmdd") Printing x.toString("dd-mm-yyyy") gives me what I would expect - 27-03-2008 What I'm trying to do though is add this to a QTableWidget item to create a date sortable column; I'm using this: if type(y)==QDateTime: item=QTableWidgetItem() item.setData(Qt.DisplayRole,QVariant(y)) BUT.. I'm adding 90 dates going back from today and getting values that look like this: 27/01/2007 00:12 28/01/2007 00:12 29/01/2007 00:12 30/01/2007 00:12 31/01/2007 00:12 01/01/2008 00:01 01/01/2008 00:02 01/01/2008 00:03 etc I tried using QDate but couldn't seem to be able to get QDate.fromString to create an object at all. Could someone please advise where I'm going wrong, the end result should be a column in my QTableWidget formatted dd/mm/yyyy that can be sorted as dates, not strings, and originate from data formatted "YYYYMMDD" Thank you very much in advance! From paddy3118 at googlemail.com Sun Mar 23 14:02:40 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 23 Mar 2008 11:02:40 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <8e5cca0c-e9c8-4c5c-9a54-d8951289f92b@c19g2000prf.googlegroups.com> On Mar 23, 4:14 pm, Paddy wrote: > On Mar 23, 3:53 pm, John Nagle wrote: > > > What's the cheapest way to test for an empty dictionary in Python? > > > if len(dict.keys() > 0) : > > > is expensive for large dictionaries, and makes loops O(N^2). > > > John Nagle > > As others have stated, if : is false for built-in > container types such as dicts, lists, sets, tuples,... > Its nice to make any of your own container types follow the same > convention too. > > - Paddy. I missed out *empty* didn't I. Its false for empty container types. - Paddy. From aisaac at american.edu Wed Mar 12 16:51:30 2008 From: aisaac at american.edu (Alan Isaac) Date: Wed, 12 Mar 2008 20:51:30 GMT Subject: no more comparisons Message-ID: I was surprised to see that comparison is slated for death in Python 3000. For example: http://www.python.org/dev/peps/pep-3100/ list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done] But there is a rumor of a PEP to restore comparisons. http://mail.python.org/pipermail/python-3000/2008-January/011764.html Is that going anywhere? Also, what is the core motivation for removing this functionality? Alan Isaac From timr at probo.com Mon Mar 3 01:16:05 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 03 Mar 2008 06:16:05 GMT Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: Kay Schluehr wrote: > >On 2 Mrz., 06:53, Ben Finney >wrote: > >> One of the stated goals of the migration is that the '2to3' program >> will only migrate Python 2.6 code -> Python 3.0 code. > >Yes, I know. Why? > >"The master said so" isn't an entirely satisfying answer. Nevertheless, it IS the answer for many questions in the Python world. That's the advantage of being Benevolent Dictator For Life. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From willsteve2003 at yahoo.ca Fri Mar 7 12:19:18 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Fri, 7 Mar 2008 09:19:18 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: Dates can be a pain. I wrote my own date program, simply because there are so many different ways to write a date: Mar 8, 2008 March 8th, 08 03/08/08 03-08-2008 And so on and so forth. The tricky bit is how to tell the difference between Day, Month and Year. I wrote a program to check the format used for a date. I assumed that any 4 digits together in a single group were the year. Then I had a list of Months, with the first 3 characters of each and compared that to the field being checked, if found, then that was the month. Then I assumed any number greater than 12 was a day. If I couldn't match those criteria I assumed Month Day Year (the standard at the company I worked for). From lists at cheimes.de Sat Mar 22 18:29:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Mar 2008 23:29:10 +0100 Subject: Problem with complex numbers In-Reply-To: <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> References: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> Message-ID: <47E58836.70202@cheimes.de> Matthias G?tz schrieb: > So can you tell me what's the purpose of Complex.py, > > and where can i find the semantic i'am looking for. Well, the file is in the Demo folder. It's just a demo how to implement a naive complex type in Python. Why do you think the power of a complex to a complex is not defined? Raising a complex to a complex power is well defined, although the mathematical proof isn't trivial. You have to use the Euler form. Ask Google for some examples Christian From rockxuan at gmail.com Tue Mar 18 03:46:00 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:46:00 -0700 (PDT) Subject: www.51cntrade.com suipply you replicas watches & jewellery fashion Message-ID: <2ce5607d-1538-40a9-ad24-d364c534a342@d4g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From pavlovevidence at gmail.com Mon Mar 3 16:13:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 13:13:23 -0800 (PST) Subject: Inheritance issue... References: <632vhiF262j15U1@mid.uni-berlin.de> Message-ID: On Mar 3, 3:14 pm, MooMaster wrote: > On Mar 3, 11:49 am, "Diez B. Roggisch" wrote: > > > > > MooMaster schrieb: > > > > I'm trying to use inheritance to create a simple binary tree, but it's > > > not going so well... here's what I pull from the documentation for > > > super() > > > "super( type[, object-or-type]) > > > > Return the superclass of type. If the second argument is omitted the > > > super object returned is unbound. If the second argument is an object, > > > isinstance(obj, type) must be true. If the second argument is a type, > > > issubclass(type2, type) must be true. super() only works for new-style > > > classes. > > > The last sentence contains the important bit. You need to use > > new-style-classes, which means they have to have the ancestor "object" > > somewhere in their inheritance-graph. > > > Like this: > > > class Foo(object): pass > > > Certainly one of the somewhat uglier corners of Python... > > > Diez > > Thanks guys, I hadn't even heard of the distinction between "old" and > "new" style classes...is this in the tutorial somewhere? I didn't see > it in Classes... Here's some reading material (it can get deep): http://www.python.org/doc/newstyle/ http://www.python.org/download/releases/2.2.3/descrintro/ New style classes have been a part of Python since 2.2, but unfortunately many documents intended for newbies don't even mention them, which seems to cause more confusion than it prevents, such as when newbies go Googling for code examples and see incompatible usage of new-style classes. For simple uses, new-style and old-style classes behave similarly enough that it doesn't matter which you use, but new-style classes support lots of things that old-style classes don't, and usage of these features is getting more and more common. Newbies who aren't being alerted to this are getting a raw deal. Thankfully old-style classes are getting the axe in Python 3.0 and hopefully this confusion will go away. Until you switch to 3.0, inherit your base classes from object; it will ensure that more recent additions like properties and super() calls work. class Node(object): .... Carl Banks From ewanfisher at gmail.com Fri Mar 14 13:05:07 2008 From: ewanfisher at gmail.com (ewanfisher at gmail.com) Date: Fri, 14 Mar 2008 10:05:07 -0700 (PDT) Subject: Thousand Seperator Message-ID: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> I'm trying to find some code that will turn: 100 -> 100 1000 -> 1,000 1000000 -> 1,000,000 -1000 -> -1,000 I know that can be done using a regular expression. In Perl I would do something like: sub thousand { $number = reverse $_[0]; $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; return scalar reverse $number; } But I cannot find how to do this in Python. Thanks, Ewan From dmitrey.kroshko at scipy.org Wed Mar 26 08:50:15 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Wed, 26 Mar 2008 05:50:15 -0700 (PDT) Subject: memory allocation for Python list Message-ID: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> hi all, I have a python list of unknown length, that sequentially grows up via adding single elements. Each element has same size in memory (numpy.array of shape 1 x N, N is known from the very beginning). As I have mentioned, I don't know final length of the list, but usually I know a good approximation, for example 400. So, how can I optimize a code for the sake of calculations speedup? Currently I just use myList = [] for i in some_range: ... myList.append(element) ... Thank you in advance, Dmitrey From sam at mas.pl Mon Mar 10 10:21:00 2008 From: sam at mas.pl (sam) Date: Mon, 10 Mar 2008 15:21:00 +0100 Subject: parsing directory for certain filetypes In-Reply-To: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: royG napisa?(a): > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? > Probably this should be rewriten and should be very compact. Maybe you should grab string: find $dirname -type f -a \( -name '*.txt' -o -name '*.doc' \) and split by "\n"? -- UFO Occupation www.totalizm.org From arnodel at googlemail.com Sat Mar 15 05:56:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 15 Mar 2008 02:56:18 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: On Mar 15, 5:47?am, Tim Roberts wrote: > Jeff Schwab wrote: > >Roel Schroeven wrote: > >> castiro... at gmail.com schreef: > >>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: > >>>>> Subject: RIP: Joseph Weizenbaum > >>>>> Creator of Eliza: > >>>>>http://www-tech.mit.edu/V128/N12/weizenbaum.html > > >>>> How do you feel about creator of Eliza? > > >>> What is Eliza? > > >> Does that question interest you? > > >Well played, sir. > > >Earlier you said what is Eliza. ?Do you still feel that way? > > I am embarrassed to say that this vaguely disrespectful exchange made me > laugh out loud. Does it bother you that this vaguely disrespectful exchange made you laugh out loud? From 2huggie at gmail.com Wed Mar 19 07:43:17 2008 From: 2huggie at gmail.com (Timothy Wu) Date: Wed, 19 Mar 2008 19:43:17 +0800 Subject: xml sax Message-ID: Hi, I am using xml.sax.handler.ContentHandler to parse some simple xml. I want to detect be able to parse the content of this tag embedded in the XML. 174 Is the proper way of doing so involving finding the "Id" tag from startElement(), setting flag when seeing one, and in characters(), when seeing that flag set, save the content? What if multiple tags of the same name are nested at different levels and I want to differentiate them? I would be setting a flag for each level. I can imagine things get pretty messy when flags are all around. Timothy -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:08:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:08:01 -0200 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: En Sat, 01 Mar 2008 22:51:08 -0200, escribi?: > Hi everyone: > > I posted here a couple days ago looking for some help creating a > Telnet-based chat server. You guys pointed me to Twisted, which has > solved most of my issues. > > However, what I want to do is analyze strings received for keywords > such as 'listcmds' and have the server return something to the client. > I know how to do that part, at least. > > The issue is, when I use clients like PuTTY, it returns a lot of what > appears to be formatting (e.g. if I typed Hello, it would return "\xff > \xfb\x1f\xff\ > xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) They are part of the telnet protocol; 0xFF (IAC=Interpret as Command) starts a two or three byte command sequence. Weren't you using telnetlib? It's supposed to handle this transparently. > How would I go about filtering this stuff out of the strings? The > thing is too, if I use other Telnet programs like Microsoft Telnet, > they don't have this formatting, so I want to be able to recognize if > it does have this formatting and act based on if it does or if it > doesn't. Any client could send similar commands at the start of the session, or even later. > Any help is appreciated, I know I'm probably asking too many questions > already :) It isn't too hard to filter them out, if you want to do it by hand. See the source for telnetlib, and the original Telnet specificacion, RFC 854 http://www.rfc-archive.org/getrfc.php?rfc=854 and RFC 855. -- Gabriel Genellina From jr9445 at ATT.COM Mon Mar 24 12:20:09 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 24 Mar 2008 11:20:09 -0500 Subject: Element Tree Help In-Reply-To: References: Message-ID: Robert Rawlins wrote: > I have little to no experiance with element tree and I'm struggling to > find a way to parse the details from the XML document?(attached) into > my application. Essentialy I'm looking to take the following document > and turn it into a?dict of tuples, each?dict element defines a > datasource with the key to the element being the 'name' which is > defined in the XML?and then the value of the pair is a tuple which? > contains the details of the datasource, like the host and port etc. Here's another way to walk an ElementTree. This one creates a hash of hashes which are normally more useful than tuples for property lookups. import xml.etree.ElementTree as ET tree = ET.ElementTree(file = "foo.xml") d = {} for ds in tree.findall("datasource"): name = ds.find('name').text d[name] = {} print 'datasource =', name for i in ds.findall('*'): #for i in ds.getiterator(): # also works if i.tag in ('datasource', 'name'): continue print ' ',i.tag, "=", i.text d[name][i.tag] = i.text print print d ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From fhaxbox66 at googlemail.com Sun Mar 2 09:46:52 2008 From: fhaxbox66 at googlemail.com (Dr. leo) Date: Sun, 2 Mar 2008 15:46:52 +0100 Subject: Hyphenation: PyHyphen 0.4.1 and textwrap2-0.1.1 released Message-ID: <47cabc90$0$582$6e1ede2f@read.cnntp.org> This latest version of PyHyphen is only important for Python 2.4 addicts who encountered a missing type when compiling. Further, a few signed/unsigned mismatch warnings coming from MSVC should be fixed. As I have only Python 2.5, I'd be interested in any experiences when compiling it with Python 2.4. Visit http://cheeseshop.python.org/pypi/PyHyphen Further, as suggested here some days ago, I have integrated 'textwrap ' with PyHyphen. While I anticipated lots of work and hoped for volunteers, I have done it myself now. And it was a cake walk! Just had to insert roughly a handfull of lines... Pure Python is pure fun! Visit http://cheeseshop.python.org/pypi/textwrap2 Bests Stefan From joe.p.cool at googlemail.com Tue Mar 18 16:15:15 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Tue, 18 Mar 2008 13:15:15 -0700 (PDT) Subject: method to create class property Message-ID: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> Hi, I like C#'s style of defining a property in one place. Can the following way to create a property be considered reasonable Python style (without the print statements, of course)? class sample(object): def __init__(self): sample.y = self._property_y() def _property_y(self): def _get(self): print 'getting y.' return self._y def _set(self, value): print 'setting y.' self._y = value def _del(self): print 'bye, y!' del self._y return property(_get, _set, _del) From anthonysmith80 at gmail.com Tue Mar 25 11:31:49 2008 From: anthonysmith80 at gmail.com (Anthony) Date: Tue, 25 Mar 2008 08:31:49 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <29bc6ff2-f172-4776-87b7-884585277570@d21g2000prf.googlegroups.com> Message-ID: <4b864142-5323-46f6-aac5-d39ea7ad64ec@s19g2000prg.googlegroups.com> On Mar 25, 2:31 pm, Tzury Bar Yochay wrote: > I wish it was that simple but 'a = Foo().getid()' is actually creating > a new instance of Foo whereas I want the data of the Foo instanced by > __init__ of FooSon(). I don't think Foo.__init__(self) creates an instance of the Foo class. If you want FooSon to create an instance of Foo, try: class FooSon(Foo): def __init__(self): self.foo = Foo() self.id = 2 def getid(self): a = self.foo.getid() b = self.id return '%d.%d' % (a,b) >>> FooSon().getid() '1.2' Or change "self.id" in Foo to something else, e.g., "self.id_foo". Does that help? Anthony From xelapond at gmail.com Mon Mar 31 21:41:37 2008 From: xelapond at gmail.com (Alex Teiche) Date: Mon, 31 Mar 2008 18:41:37 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> <1a8a5b03-0b9e-49de-bd87-43fa1aa99dc2@b5g2000pri.googlegroups.com> Message-ID: <6b732135-a488-4175-889b-0cccf5f0c581@s8g2000prg.googlegroups.com> On Mar 31, 6:40 pm, Alex Teiche wrote: > On Mar 31, 11:49 am, Alex Teiche wrote: > > > > > On Mar 30, 3:50 pm, Benjamin wrote: > > > > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > > implement the following thing into my python application: > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > > it, but I could not get this specific thing to work. Can someone give > > > > me some hints as to get it working in Python? > > > > What problems are you having? > > > > > Thanks a ton, > > > > > Alex > > > Thanks everyone for your help. I found the example to be particularly > > helpful, and I have made a simplified version just to display an icon > > with a quit button in its menu. Once I know how to do that I will > > incorporate it into my larger program, with more options and the > > ability show messages. The problem is, it doesn't work, and I can't > > find out what's wrong. Can you give me some hints? > > > Here is the code: > > import sys > > from PyQt4 import QtGui, QtCore > > > class trayIcon(QtGui.QWidget): > > def __init__(self, parent=None): > > QtGui.QWidget.__init__(self, parent) > > > #********Create Actions for the Tray Menu********# > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > > QtCore.QObject.connect(self.quitAction, > > QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) > > > create_tray_icon() > > > self.composeAction.setEnabled(visible) > > QtGui.QWidget.setVisible(self, visible) > > > self.trayIcon.show() > > > def create_tray_icon(self): > > self.trayIconMenu = QtGui.QMenu(self) > > self.trayIconMenu.addAction(self.composeAction) > > self.trayIcon = QtGui.QSystemTrayIcon(self) > > self.trayIcon.setContextMenu(self.trayIconMenu) > > self.trayIcon.setIcon(bad.svg) > > > app = QtGui.QApplication(sys.argv) > > sys.exit(app.exec_()) > > OK, I messed around with it some more, and it works. I just don't > know how to set an icon, and the example doesn't help at all. > > Here is the code: > import sys > from PyQt4 import QtCore, QtGui > > class Systray(QtGui.QWidget): > def __init__(self): > QtGui.QWidget.__init__(self) > > self.createActions() > self.createTrayIcon() > > #QtCore.QObject.connect(self.trayIcon, > QtCore.SIGNAL("messageClicked()"), self.messageClicked) > #QtCore.QObject.connect(self.trayIcon, > QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), > self.iconActivated) > > self.trayIcon.show() > > def createActions(self): > #self.minimizeAction = QtGui.QAction(self.tr("Mi&nimize"), self) > #QtCore.QObject.connect(self.minimizeAction, > # QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("hide()")) > > #self.maximizeAction = QtGui.QAction(self.tr("Ma&ximize"), self) > #QtCore.QObject.connect(self.maximizeAction, > # QtCore.SIGNAL("triggered()"), self, > # QtCore.SLOT("showMaximized()")) > > #self.restoreAction = QtGui.QAction(self.tr("&Restore"), self) > #QtCore.QObject.connect(self.restoreAction, > # QtCore.SIGNAL("triggered()"), self, > # QtCore.SLOT("showNormal()")) > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), > QtGui.qApp, QtCore.SLOT("quit()")) > > def createTrayIcon(self): > self.trayIconMenu = QtGui.QMenu(self) > #self.trayIconMenu.addAction(self.minimizeAction) > #self.trayIconMenu.addAction(self.maximizeAction) > #self.trayIconMenu.addAction(self.restoreAction) > #self.trayIconMenu.addSeparator() > self.trayIconMenu.addAction(self.quitAction) > > self.trayIcon = QtGui.QSystemTrayIcon(self) > self.trayIcon.setContextMenu(self.trayIconMenu) > > app = QtGui.QApplication(sys.argv) > x = Systray() > sys.exit(app.exec_()) > > How would I go about setting the icon? Sorry, here is the code with commented out lines removed: import sys from PyQt4 import QtCore, QtGui class Systray(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.createActions() self.createTrayIcon() self.trayIcon.show() def createActions(self): self.quitAction = QtGui.QAction(self.tr("&Quit"), self) QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) def createTrayIcon(self): self.trayIconMenu = QtGui.QMenu(self) self.trayIconMenu.addAction(self.quitAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) app = QtGui.QApplication(sys.argv) x = Systray() sys.exit(app.exec_()) From simon at brunningonline.net Wed Mar 19 09:03:46 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 Mar 2008 13:03:46 +0000 Subject: Using threads in python is safe ? In-Reply-To: <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> Message-ID: <8c7f10c60803190603u5c104908p37dd103035e90348@mail.gmail.com> On Wed, Mar 19, 2008 at 7:43 AM, Deepak Rokade wrote: > If jobs to be processed by threds is I/O bound would multithreading help > python to improve speed of application ? Probably, yes. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From frikker at gmail.com Mon Mar 3 10:39:41 2008 From: frikker at gmail.com (blaine) Date: Mon, 3 Mar 2008 07:39:41 -0800 (PST) Subject: Talking to a usb device (serial terminal) Message-ID: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Hey everyone, We have a usb spectrometer device that we have finally got working in linux (we were provided linux only drivers). The device has a Silicon Instruments cp2101 serial-to-usb chip onboard, and we loaded the kernel module cp2101.c after taking the device apart to see what was on the inside. Using minicom we are able to set a baud rate and open up a terminal when pointing to the device /dev/ttyusb0 (I think). Anyway, I want to be able to talk to our cool device using python. I haven't been able to find many resources specifically in this area, but there are a few package that are vaguely mentioned, including fcntl and termios. But the web doesn't seem to have a lot of documentation on fcntl, particularly information thats from the past 8 years. So my question is this - what is the easiest way to interface to this "serial" device? I don't imagine a straight read() and write() command to /dev/ttyusb0 is the most efficient (if it even works) especially since we would need to set a baud rate. My experience with terminal communication is pretty limited. Any advice that can be offered would be awesome. Thanks! PS: The device that we will be using python on will be an embedded ARM system. Currently we are testing using a linux laptop and cross compiling the kernel over to the embedded device. The device has Python 2.4, and does have both the termios and fcntl packages available. Python 2.4.2 (#1, Feb 20 2008, 11:07:36) [GCC 4.1.1] on linux2 uname -a: Linux gumstix 2.6.21gum #1 Wed Feb 20 02:53:01 EST 2008 armv5tel unknown Blaine Booher University of Cincinnati From nothanks at null.invalid Sat Mar 22 23:27:57 2008 From: nothanks at null.invalid (Bill) Date: Sat, 22 Mar 2008 23:27:57 -0400 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <47E5CE3D.8010102@null.invalid> sturlamolden wrote, On 3/20/2008 9:41 AM: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > What don't you like about wxGlade? It actually generates Python code. There has been a lot more development going on recently, too. Bill From castironpi at gmail.com Wed Mar 26 22:00:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 19:00:40 -0700 (PDT) Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Message-ID: <248e2789-822f-43cd-be3c-e2498d4c8ea7@d45g2000hsc.googlegroups.com> On Mar 26, 5:11?pm, Miki wrote: > Hello Tim, > > > > > > > I want to write a tiny interactive app for the following situation: > > I have books of many chapters that must be split into volumes before going > > to the printer. > > A volume can have up to 600 pages. We obviously break the book into volumes > > only at chapter breaks. Since some chapters make a natural grouping, we want > > some human interaction for where the volume breaks occur. > > > Not having experience with interactive apps, I'm asking for advice about how > > to go about it. The data I start with is just a dictionary with chapter name > > = ending page number. I figured I would first show where the volumes would > > break with no human interaction, with the begin and ending chapter > > names/pagenumbers for each volume. > > > From here I thought about having a slider for each volume, but the number of > > volumes could change during the session. > > Or maybe I should just ask 'enter the ending chapter for the first volume' > > and recalculate, etc until all volumes are defined. > > > Any ideas on a simple interface for this? > > How about something like: > > Chapter 1 (001-200 200) > Chapter 2 (200-300 100) > ------ 001-300 300 ---- > Chapter 3 (300-450 150) > Chapter 4 (450-500 50) > ------ 300-450 250 ---- > Chapter 5 (500-600 100) > ------ 500-600 100 ---- > > Where the user can move the divider up and down to create new volume, > they can also add and delete dividers. > > The program will not allow to drag the divider above the 600 page > limit. If you're a WISIWIG editor, you can select text by - typing STRNG - editor overlays IDs on every occurence - repeat or select number I'm looking at debugging, and you do get: >>> pdb.run( 'f()' ) > (1)()->None (Pdb) s --Call-- > (1)f() (Pdb) s > (5)f() (Pdb) s --Call-- > c:\programs\python\lib\io.py(1235)write() -> def write(self, s: str): (Pdb) l 1230 return self.buffer.fileno() 1231 1232 def isatty(self): 1233 return self.buffer.isatty() 1234 1235 -> def write(self, s: str): 1236 if self.closed: 1237 [snip] 1238 if not isinstance(s, str): 1239 [snip] 1240 [snip] allowing you to see what you want, adjust, and keep a mind's-eye representation of the program. Are you complaining that the mouse is too slow? That the GUI is too distant? Closest lexical: 'editor sucks' and 'console sucks'. I think a SmartConsole would take A.I. I want a multi-column console. I'm not sure how generally you can harness today's GI on a keyboard, but tomorrow's certainly can. (scrollbar2 up>up>up), and I think you'd get console gi primitives pretty quickly. (graphical/spatial interface.) You're thinking of mimetic/conceptual zoom. How does this look? >>> open Chapter 1 (001-200 200) Chapter 2 (200-300 100) ------ 001-300 300 ---- Chapter 3 (300-450 150) Chapter 4 (450-500 50) ------ 300-450 250 ---- Chapter 5 (500-600 100) ------ 500-600 100 ---- >>> move up Chapter 1 (001-200 200) ------ 001-200 200 ---- Chapter 2 (200-300 100) Chapter 3 (300-450 150) Chapter 4 (450-500 50) ------ 300-450 150 ---- Chapter 5 (500-600 100) ------ 500-600 100 ---- >>> move up Chapter 1 (001-200 200) ------ 001-200 200 ---- Chapter 2 (200-300 100) Chapter 3 (300-450 150) ------ 200-450 250 ---- Chapter 4 (450-500 50) Chapter 5 (500-600 100) ------ 450-600 150 ---- But us mortal humans, temporal beings, get confused quickly with what section is where, so we'll mis-specify eventually. ("No, the -other- up!") Did everyone know that the graphics blits in BASIC were 'get' and 'put'? You could probably pick a recommended contextmanager out of the box; it could learn what you wanted by when you said 'no'. You'll want a: >>> notify me when a volume's page length > 600 which isn't clear at all how to translate into CS in a rigorous way, and its varying meanings for different structures. >>> Upon( page length.volume > 600 for volume in book, print ) And each page length change notifies 'Upon', cf. Observer. I feel like the way from point A you mention and the actual implementation would be useful. Python shows promise for 'rollback' potential too. >>> UponAny( page length.volume > 600 for volume in book, raise ) >>> Upon( any( sum( volume ) > 600 for volume in book ), raise ) Somehow, your data are still around during console session-- exception doesn't kill a console. This one generates a console of a dictionary and lets you assign to it. --> a= 2 --> print( a ) 2 --> def con(): while 1: try: yield input( '--> ' ) except: print( 'exception.' ) glos, locs= {}, {} for inp in con(): exec( inp, glos, locs ) We might have to mark our objects live / "on the air", to notify generators of change in conditions, rerun at every step. I think you need live primitives. From willsteve2003 at yahoo.ca Thu Mar 6 15:29:38 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Thu, 6 Mar 2008 12:29:38 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <3ddf3ef3-529c-4a81-932a-d2dda4972704@e23g2000prf.googlegroups.com> Message-ID: On Mar 6, 3:20?pm, George Sakkis wrote: > On Mar 6, 9:27 am, Pierre Quentel wrote: > > > > > > > Hi, > > > I would like to know if there is a module that converts a string to a > > value of the "most probable type" ; for instance : > > - if the string is "abcd" the value is the same string "abcd" > > - string "123" : value = the integer 123 > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > = the float -1.23 > > - string "2008/03/06" (the format is also locale-dependant) : value = > > datetime.date(2008,03,06) > > > Like in spreadsheets, special prefixes could be used to force the > > type : for instance '123 would be converted to the *string* "123" > > instead of the *integer* 123 > > > I could code it myself, but this wheel is probably already invented > > Maybe, but that's a so domain-specific and easy to code wheel that > it's no big deal reinventing. > > George- Hide quoted text - > > - Show quoted text - Actually you could probably write your own code very easily, a couple of try/except clauses. I would recommend you try int() first, then try float(), then try date check and when all else fails leave it a string. However, it may be an interesting challenge for those who are willing to make the attempt. "Define Cell/Field contents". From tjreedy at udel.edu Tue Mar 11 00:04:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 00:04:44 -0400 Subject: image matching algorithms References: Message-ID: "Daniel Fetchinson" wrote in message news:fbe2e2100803092332u5b222ff8o2ffe84cbc0334f7 at mail.gmail.com... | The various free tools differ by their chosen optimization paths and | their degree of specialization. My preference would be, | | 1. Doesn't really matter how long it takes to compute the N numbers per image Your problem here is that there is really no such thing as 'general features' and correspondingly, no such thing as 'general similarity of features'. The features extracted have to have a specific definition. The features represent a severe lossy compression of the original. What to keep depends on the application. Example: classify each pixel as white, black, red, green, or blue. Will that match your intuitive idea of what matches? To be a bit more sophisticated, use more color bins and do the binning separately for multiple areas, such as top, left, center, right, and bottom (or center, upper right, upper left, lower right, and lower left). I suspect Google does something like this to match, for instance, pictures with skin tones in the center, or pictures with blue tops (sky?) and green bottoms (vegetation?). | 2. Lookups should be fast, consequently N should not be too large (I guess) | 3. It should be a generic algorithm working on generic images (everyday photos) Given feature vectors, there are various ways to calculate a distance or similarity coefficient. There have been great debates on what is 'best'. | 4. PIL should be enough for the implementation | | So if anyone knows of a good resource that is close to being pseudo | code I would be very grateful! If you do not have sufficient insight into your own idea of 'matches', try something on a test set of perhaps 20 photos, calculate a 'match matrix', and compare that you your intuition. Terry Jan Reedy From http Mon Mar 17 04:20:52 2008 From: http (Paul Rubin) Date: 17 Mar 2008 01:20:52 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <7x3aqpg3rv.fsf@ruckus.brouhaha.com> Stephan Deibel writes: > I have to admit, I'll keep coming to PyCon even if all the talks suck > abysmally as long as there's good hallway time, open space, BoFs, and > sprints. ;-) OK, so why not get rid of all the talks and other stuff, and just have a basically structureless conference, beyond scheduling some open meetings on various topics? That would be a lot less expensive and a lot more interesting. From saluk64007 at gmail.com Tue Mar 25 02:18:53 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 24 Mar 2008 23:18:53 -0700 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: It seems like this is mostly a non-issue. The original code actually works correctly (of course the updated versions that solve the exception problem are probably better). The only thing that is going haywire is the interpreter shutdown process. I think it is going a bit overboard to "consider __del__ harmful" because it might throw an exception as the program is quitting. It is important to not rely on __del__ too much but there can be some designs where you need to know when something is gone, and you don't know exactly where or when something is deleted. Then again, I can count the number of times I have ever needed __del__ with no fingers (never used it!). Still, quite interesting to explore. From aboudouvas at panafonet.gr Thu Mar 27 12:14:15 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 09:14:15 -0700 (PDT) Subject: Psyco alternative References: Message-ID: <10d4e6b6-71f3-4c22-8b13-17dd32a4374f@c19g2000prf.googlegroups.com> > One reason attention is going to PyPy instead of Psyco... > > Jean-Paul I had a look at PyPy, it, indeed, have a very long way to go so we can consider it an alternative. From tgrav at mac.com Tue Mar 4 20:06:38 2008 From: tgrav at mac.com (Tommy Grav) Date: Tue, 4 Mar 2008 20:06:38 -0500 Subject: SV: Polymorphism using constructors In-Reply-To: References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: On Mar 4, 2008, at 4:53 PM, Jeff Schwab wrote: > What does "SV" in the subject mean? SV = "Svar" is the Norwegian word for Reply. Cheers Tommy From __peter__ at web.de Thu Mar 13 05:20:15 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Mar 2008 10:20:15 +0100 Subject: List mutation method gotcha - How well known? References: Message-ID: Hendrik van Rooyen wrote: > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): I thought it were a FAQ, but found only http://effbot.org/pyfaq/why-doesn-t-list-sort-return-the-sorted-list.htm I'm sure you can draw the analogy. Peter From noZ.spamZ at ZZ.ZsvpZ.com Sat Mar 29 16:27:25 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Sat, 29 Mar 2008 21:27:25 +0100 Subject: Finding Full Path to Process EXE In-Reply-To: References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: <47eea713$0$27902$426a74cc@news.free.fr> Hi! Warning : WMI give the "command-line" of a process only for windows > 2000 @-salutations Michel Claveau From gagsl-py2 at yahoo.com.ar Mon Mar 17 21:33:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 18:33:53 -0700 (PDT) Subject: First Program Bug (Newbie) References: Message-ID: <7ee63034-f73e-43c8-8183-fdf824201d9f@c19g2000prf.googlegroups.com> On 17 mar, 21:03, Benjamin Serrato wrote: > I Found It!! The following was a post asking for help finding a bug. I > thought I needed help with my syntax, but just before sending I found > the bug on line 13. Line 13 should read: "base = 2". I would still > appreciate any comments on my program. Maybe there is a better way to do > it that I didn't think about. I know it's not that interesting but it's > my first one. You may look at the fact.py demo script (somewhere in your python installation) > I'm almost halfway through an online tutorial I found on the python.org > site and decided to stop and write a program for myself. I got it in my > head to write a program to print all the primes; the idea came from > another tutorial. The program prints some non-prime numbers. In a > comparison to lists of primes the program prints eight non-primes for > numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. > Here is the program. > > base = 2 > candidate = 3 > > while True: > ? ? ? ? while candidate % base != 0: > ? ? ? ? ? ? ? ? base = base + 1 > ? ? ? ? ? ? ? ? if base > (candidate / 2): > ? ? ? ? ? ? ? ? ? ? ? ? print candidate > ? ? ? ? ? ? ? ? ? ? ? ? candidate = candidate + 1 > ? ? ? ? ? ? ? ? ? ? ? ? base = 2 > ? ? ? ? else: > ? ? ? ? ? ? ? ? candidate = candidate + 1 > base = 2 # added Note that you can increment candidate by 2 (starting at 3, all primes are odd numbers). And after testing 2, you can increment base by 2 also. And you can exit somewhat earlier: if base*base>candidate there is no point in keep trying (now you`re exiting when base*2>candidate) > At first I tried to use 'return' on the 'else' block to cause the > program to loop, but I don't understand 'return' yet and that didn't > work. So, I put the rest into another while loop and was really happy to > find it worked but the program prints some non-prime numbers. return only makes sense inside a function. Wait until the next lesson... -- Gabriel Genellina From Grimsqueaker13 at gmail.com Thu Mar 27 02:15:41 2008 From: Grimsqueaker13 at gmail.com (Grimsqueaker) Date: Wed, 26 Mar 2008 23:15:41 -0700 (PDT) Subject: counting using variable length string as base Message-ID: Hi, I'm fairly new to Python and to this list. I have a problem that is driving me insane, sorry if it seems simple to everyone, I've been fighting with it for a while. :)) I want to take a variable length string and use it as a base for counting, eg. given the string 'abc' the sequence would be: a b c aa ba ca ab bb cb ... ccc Basically I want to find every possible order of every combination. Its easy if you know how many characters there will be in your string (use nested for loops), but I am stuck with the variable length string. I think I have to use a generator but I'm not sure exactly how. Can anyone give me a pointer in the right direction? Thanks Daniel Browne From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 13 06:46:34 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Mar 2008 11:46:34 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: References: Message-ID: <47d905cd$0$16137$426a74cc@news.free.fr> Hendrik van Rooyen a ?crit : > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above answer 5 - list.append returns None, which when printed gives 'None'. You'll get the same thing with list.sort, list.extend, list.reverse etc... From znfmail-pythonlang at yahoo.com Wed Mar 19 11:35:14 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Wed, 19 Mar 2008 11:35:14 -0400 Subject: cx_Oracle execute procedure References: Message-ID: Thanks Jerry and Diez. The first two replies I found answered my noob question. "Jerry Hill" wrote in message news:mailman.2148.1205940209.9267.python-list at python.org... > On Wed, Mar 19, 2008 at 11:03 AM, Poppy > wrote: >> I've been working on the code below and and executes silently, no >> complaints, however the end result should be a record in my table and >> it's >> not added. The procedure works with the passed credentials using SQLPlus >> or >> SQL Developer clients. However I'm not sure if I'm constructing my >> python >> code correctly to interact with Oracle. > ... >> connection.commit >> cur.close >> connection.close > > You have to actually call these methods: > connection.commit() > cur.close() > connection.close() > > Without the parentheses, you're just getting a reference to the > methods and immediately discarding them. > > -- > Jerry From stephenhorne100 at aol.com Mon Mar 17 09:06:59 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 06:06:59 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: On Mar 17, 12:28 pm, castiro... at gmail.com wrote: > > Why is the immutable form the default? > > Using a house definition from some weeks ago, a tuple is a data > structure such which cannot contain a refrence to itself. Can a > single expression refer to itself ever? Can't imagine why that feature was highlighted in particular, but a list can reference itself even though an expression can't. The following example looks a bit self-referential, but isn't... a = 2 a = [1, a, 3] # result [1, 2, 3] The following additional line, however does create a self-referencing list... a [1] = a The result being [1, [...], 2] It's nice to see that Python can handle the output for this without going into an infinite recursion - which is exactly what it used to do in the distant past. A tuple cannot be made to reference itself because it cannot be modified after creation. The key point is that lists are mutable, whereas tuples are not. From castironpi at gmail.com Tue Mar 25 18:04:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 15:04:53 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: On Mar 23, 8:05?pm, Tim Chase wrote: > > When I run this script, I got the following exception: > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'population'" in > <__main__.Person instance at 0xb7d8ac6c>> ignored > > > To to newcomer like me, this message doesn't make much sense. What > > seems weird to me is that, if I change the variable cathy to something > > else, like cath, or even cat, then the script will finish gracefully. > > Why "cathy" is not liked?!! > > > My python is of version 2.5.1, on Ubuntu. > > When I first read this, I thought you were crazy. ?I ran the > code, and you're not. ?I tried under versions 2.3, 2.4, and 2.5 > on my Debian box, and got the same results. ?Neither "cathy" nor > "ca" works, ?but "c", "cat", "cath", "cath_y" and "cathy_" all > work just fine. > > Even more infuriating is that if I try and use pdb to debug, > Swaroop drops into pdb, but Abdul and Cathy both error out. > [snip] > Does Python hate Cathy? Does Pothon? From deets at nospam.web.de Sun Mar 30 08:23:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Mar 2008 14:23:39 +0200 Subject: problem with logic in reading a binary file In-Reply-To: <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> Message-ID: <659f2cF2dq5riU1@mid.uni-berlin.de> hdante schrieb: > On Mar 30, 4:31 am, John Machin wrote: >> On Mar 30, 3:58 pm, hdante wrote: >> >> >> >>> On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" >>> wrote: >>>> Hello, >>>> I am having trouble writing the code to read a binary string. I would >>>> like to extract the values for use in a calculation. >>>> Any help would be great. >>> I'm too lazy to debug your binary string, but I suggest that you >>> completely throw away the binary file and restart with a database or >>> structured text. See, for example: >>> http://pyyaml.org/wiki/PyYAML >>> If you have some legacy binary file that you need to process, try >>> creating a C program that freads the binary file and printfs a text >>> equivalent. >> ... and that couldn't be done faster and better in Python?? > > No. A C struct is done faster and better than python (thus, the > correctness check is faster in C). Also, chances are high that there's > already an include file with the binary structure. That is utter nonsense. There is no "correctness check" in C. and using printf & thus creating strings that you then need to parse in python just doubles the effort needlessly. The standard-lib module "struct" is exactly what you need, nothing else. it sure is faster than any parsing of preprocessed data, doesn't introduce a language-mixture and is prototyped/tested much faster because of it being python - and not C-compiler and C-debugger. Alternatively, *IF* there were C-structure-declarations available for the binary format, the usage of ctypes would allow for roughly the same, even reducing the effort to create the structure definition a great deal. Diez From ganeshborse at gmail.com Wed Mar 19 04:40:44 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Wed, 19 Mar 2008 01:40:44 -0700 (PDT) Subject: is hash map data structure available in Python? Message-ID: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Hi, I have a situation that I need to search a name in a big list of names in my Python embedded interpreter. I am planning to use hash map for quicker search. How do I create hash map in Python? Can you please guide me to some documentation or tutorial which provides information on creating, editing, searching through hash map in Python? Thanks. From jeffrey at fro.man Thu Mar 27 16:12:47 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 27 Mar 2008 13:12:47 -0700 Subject: Signal problem References: Message-ID: <13unvtvnmvsm609@corp.supernews.com> Fabio Durieux Lopes wrote: > def signalHandler(signum, frame): > terminate = True This creates a new variable named "terminate" inside the signalHandler function's local scope. To adjust the value of a module-level global from inside a function, use the "global" keyword: def signalHandler(signum, frame): global terminate terminate = True Jeffrey From w.a.h.d222 at gmail.com Fri Mar 21 00:57:11 2008 From: w.a.h.d222 at gmail.com (=?windows-1256?B?zebm5sjt?=) Date: Thu, 20 Mar 2008 21:57:11 -0700 (PDT) Subject: sex sex downlond Message-ID: <51a85330-1cfc-470b-9ece-bb115f93b0b7@u69g2000hse.googlegroups.com> sex sex downlond http://www.al-lail.com/vb/showthread.php?goto=newpost&t=4454 From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 20:48:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 01:48:21 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Message-ID: <13t6gf5on1qnhbe@corp.supernews.com> On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote: > On Mar 8, 6:26?pm, Paul Rubin wrote: >> Alasdair writes: >> > What is the best way of finding a ceiling of a quotient of arbitrary >> > sized integers? >> >> ceiling(a/b) = (a+b-1)//b > > I prefer: > > ceiling(a/b) = -(-a)//b > > which also works if a and b are something other than integers (e.g. > rational numbers). Unfortunately it doesn't give the right answer. >>> a, b = 101.0, 10.0 >>> -(-a)//b # should be 11.0 10.0 >>> a, b = -101.0, 10.0 >>> -(-a)//b # should be -10.0 -11.0 Looks like you've confused ceiling() and floor(). (And the ease that these mistakes can happen is why such fundamental functions should be in the standard library, no matter how easy they are to implement.) -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 16:58:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 21:58:29 -0000 Subject: What is a class? References: Message-ID: <13su5s530rnkgfe@corp.supernews.com> On Wed, 05 Mar 2008 10:50:12 -0800, castironpi wrote: > What is a class that is not a module? Er, all of them? I'm curious what classes you think are modules. -- Steven From castironpi at gmail.com Tue Mar 25 14:44:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 11:44:20 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: On Mar 25, 12:01?pm, Robert Bossy wrote: > Hi, > > I'm not sure what you're trying to actually achieve, but it seems that > you want an identificator for classes, not for instances. In this case, > setting the id should be kept out of __init__ since it is an instance > initializer: make id static and thus getid() a classmethod. > Furthermore, if you have several Foo subclasses and subsubclasses, etc. > and still want to use the same identificator scheme, the getid() method > would better be defined once for ever in Foo. I propose you the following: > > > class Foo(object): > ? ? id = 1 > > ? ? def getid(cls): > ? ? ? ? if cls == Foo: return str(cls.id) > ? ? ? ? return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the > parent id and append its own id > ? ? getid = classmethod(getid) > > class FooSon(Foo): > ? ? id = 2 > > class Bar(Foo): > ? ? id = 3 > > class Toto(Bar): > ? ? id = 1 > > # Show me that this works > for cls in [Foo, FooSon, Bar, Toto]: > ? ? inst = cls() > ? ? print '%s id: %s\n ? ?also can getid from an instance: %s\n' % > (cls.__name__, cls.getid(), inst.getid()) > > > One advantage of this approach is that you don't have to redefine the > getid() method for each Foo child and descendent. Unfortunately, the > "cls.__bases__[0]" part makes getid() to work if and only if the first > base class is Foo or a subclass of Foo. You're not using multiple > inheritance, are you? > > RB It is clear there are always two vectors is programmer thoughtspace: class and instance, and that they are orthogonal, and even orthonormal. Every (human-thought native) data structure can be expressed as a sum of two vectors, scalar * unit, scalar * unit in a particular order (cf. Gram-Schmidt), or a tuple. Writing code is simply the specification of scalar and scalar. Clearly the alphabet-space of programs ( symbol* ) contains (improper) the alphabet-space of Python programs, (which) contains (proper) the token-space of Python programs, (which) contains (proper) the grammar- space of Python programs, yet but here we lose thought; do you think in Python? Python ignores some subset of distinctions we make in thought, and we ignore some subset of distinctions Python require (w.c.)s. How do we effectively communicate with it? Order is a non-commutative relation. (a,b) did come from reality, but does not fulfill Rab; conclude (a,b) did not come from reality; and R is a truth relation. Conclude Rab is a scalar. Is a gram a pound? Is it two pounds? Newton's zero-find method finds b given a and Rab. (Expected time to zero pent). Do you think in Newton's method? Are functions scalars? '''In the mid-20th century, some mathematicians decided that writing "g o f" to mean "first apply f, then apply g" was too confusing and decided to change notations. They wrote "xf" for "f(x)" and "xfg" for "g(f(x))". This can be more natural and seem simpler than writing functions on the left in some areas.''' - wikipedia. Does anyone know category theory or pointless topology? My point in asking, is if we can explain in a really easy way using those establishments, to Python how we think, (several symbols, what when), we would like it, assuming it likes us. To effectively communicate with Python, what does the assumption that 'we want something', that 'there's a reward' exclude? Python wants to reward programmers often enough. (Python + Usenet does!) Do we like to be frustrated? What's good for us is good for Python. What frustrates you the most? From kyosohma at gmail.com Wed Mar 26 15:23:47 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 26 Mar 2008 12:23:47 -0700 (PDT) Subject: A question on decorators References: Message-ID: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> On Mar 26, 2:10 pm, Tim Henderson wrote: > Hello > > I am writing an application that has a mysql back end and I have this > idea to simplify my life when accessing the database. The idea is to > wrap the all the functions dealing with a particular row in a > particular in a particular table inside a class. So if you have a > table that looks like this: > > id str1 str2 pickled_data1 pickled_data2 > 0 woeif aposf (bin) (bin) > 1 ofime powe (bin) (bin) > ... > n oiew opiwe (bin) (bin) > > you can access this table like this > > t = Table(id) #to load a pre-entered row > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > when you change a an attribute of the class like this... > t.str1 = 'new value' > > it automatically updates the database backend. > > I have what I just described working. However I want an easier way to > deal with my pickled_data. Right now I am pickling dictionaries and > list types. Now there is one problem with this, let me demonstrate > > t.data.update({'new key':'new value'}) > print t.data > {... 'new key':'new value' ...} > > which makes it appear that the database has been updated as well, but > in fact it hasn't to update the database with this scheme you actually > have to do this. > > t.data.update({'new key':'new value'}) > t.data = t.data > > this is not ideal so I subclassed the built in dict type like this: > > class _my_dict(dict): > > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > self.update_db() > > def __delitem__(self, key): > if self.write_access: > dict.__delitem__(self, key) > self.update_db() > > def __setitem__(self, key, value): > if self.write_access: > dict.__setitem__(self, key, value) > self.update_db() > > def clear(self): > if self.write_access: > dict.clear(self) > self.update_db() > > ... > more methods which are simliar > ... > > def update_db(self): > if self.write_access: > con = get_dbConnection() > cur = con.cursor() > > table = self.experiment.TABLE > row_index_name = self.row_index_name > row_index = self.row_index > column_name = self.column_name > column_value = MySQLdb.escape_string(pickle.dumps(self)) > > q1 = '''UPDATE %(table)s > SET %(column_name)s = '%(column_value)s' > WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() > > cur.execute(q1) > con.close() > > Now while this works, it is a lot of work. What I want to be able to > do is something where I write one decorator function that > automatically updates the database for me. So let us pretend I have > this function. > > let: dec_update_db() be my decorator which updates the dictionary. > > to use this function it seems I would probably still have to subclass > dict like this: > > class _my_dict2(dict): > > @dec_update_db > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > @dec_update_db > def __delitem__(self, key): > dict.__delitem__(self, key) > > @dec_update_db > def __setitem__(self, key, value): > dict.__setitem__(self, key, value) > > @dec_update_db > def clear(self): > dict.clear(self) > > ... and so on ... > > this is also not ideal. because I still have to apply the decorator to > every function which changes the dictionary. > > What I really want is a way to have the decorator applied > automatically every time a method in dict or a sub class is called. I > feel like this must be possible. Has any one here done anything like > this before? > > Thank you for reading my long post, I hope you understand what I am > asking especially since the code in it is not very good. > > cheers > Tim Henderson Why aren't you using SQLAlchemy or SQLObject? I think they would work better than this and give you a lot more flexibility. Besides, you should use sqlite rather than pickle databases. It's especially easy since sqlite is included with Python 2.5. Mike From nkanthikiran at gmail.com Wed Mar 12 07:37:58 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Wed, 12 Mar 2008 04:37:58 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: I think I am not clear with my question, I am sorry. Here goes the exact requirement. We use dd command in Linux to create a file with of required size. In similar way, on windows I would like to use python to take the size of the file( 50MB, 1GB ) as input from user and create a uncompressed file of the size given by the user. ex: If user input is 50M, script should create 50Mb of blank or empty file Thank you From arnodel at googlemail.com Wed Mar 12 18:55:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 12 Mar 2008 15:55:18 -0700 (PDT) Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> <47D7E9A1.7000403@ncee.net> Message-ID: <1225bf07-ad62-46d3-9e7a-3bf826aac67e@i12g2000prf.googlegroups.com> On Mar 12, 3:38?pm, "Reedick, Andrew" wrote: [...] > Start here > > http://www.mail-archive.com/python-l... at python.org/msg178356.html > and go through the thread. ?There are several ways to solve the problem > and we evaluated the performance and 'pythonicity' of each. ? I used a kind of extended cartesian product function a while ago while writing a parser. If I simplify it down to a simple product function it goes like this: def product(*sequences): i, n = 0, len(sequences) vals = [None]*n iters = map(iter, sequences) while i >= 0: if i == n: yield tuple(vals) i -= 1 else: for vals[i] in iters[i]: i += 1 break else: iters[i] = iter(sequences[i]) i -= 1 It's neither recursive nor a hack, I haven't tried to measure it against other approaches (obviously it wouldn't beat the eval(...) hack). I haven't optimised it for readability (by others) either :) -- Arnaud From blwatson at gmail.com Sun Mar 30 00:48:42 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Sat, 29 Mar 2008 21:48:42 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> <75c10b67-c971-4db4-be13-26cafd24e9d2@d4g2000prg.googlegroups.com> Message-ID: Rock and roll baby!!! Thanks so much. It took some doing, but many thanks!!!! From software at ginstrom.com Sun Mar 30 11:40:07 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 31 Mar 2008 00:40:07 +0900 Subject: Build complete, now I just need to "install" it... In-Reply-To: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: <084501c8927c$54cfbe80$0203a8c0@MOUSE> > On Behalf Of axl > Since I don't have access to MSVS 2003 I need to rebuild > Python using MSVS 2008 in order for the binaries to go along. Another option is to compile your extensions with gcc, and specify that it link to MSVCR71.dll as the C runtime. For MinGW, it's sufficient to edit the specs (e.g. in C:\MinGW\lib\gcc\mingw32\3.4.2) like so: *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 And tell distutils to use mingw, by putting this in lib/distutils/distutils.cfg: [build] compiler=mingw32 [build_ext] compiler=mingw32 Regards, Ryan Ginstrom From Dominique.Holzwarth at ch.delarue.com Thu Mar 27 08:28:25 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 27 Mar 2008 12:28:25 +0000 Subject: Pickle: several class instance objects in one file? Message-ID: <5213E58D85BC414998FA553C701E386C0EDD00F451@SGBD012511.dlrmail.ad.delarue.com> Hi everyone I've never used the module 'pickle' so far, thus I've got some questions about how to use it: Lets say I have instances of class A and class B: a = A() b = B() Is it possible to pickle both of these instances to the same pkl-file or will that have any bad impact for unpickle (i.e. the instance are 'mixed' or 'destroyed')? Or should I rather use a seperate file for every class instance I want to pickle? Another very basic question about pickling class instances: To store the value of attributes of an instance is it enough for the pickling-algorithm to use the __dict__ or do I have to implement the _setstate_ and _getstate_ function? I didn't really get the meaning of those while reading the python user manual... Thanks in advance Dominique From giles.thomas at resolversystems.com Tue Mar 4 13:28:42 2008 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Tue, 4 Mar 2008 10:28:42 -0800 (PST) Subject: ANN: Resolver One 1.0.1 Message-ID: <5be62ef4-eb68-4925-a08d-7ef151d7cb54@s12g2000prg.googlegroups.com> Hi! We're delighted to announce version 1.0.1 of Resolver One, a Windows spreadsheet/IDE mashup that can be programmed in IronPython. As you enter formulae on the grid, it writes the equivalent IronPython program for you. As you add your own code, the grid is updated. This allows you to build applications that are much more complex but better-structured than a traditional spreadsheet, much more quickly than you could if you were using a regular programming language. You can then export the code and re-use it elsewhere in your own programs. It's primarily targetted at heavy users of number-crunching software, such as financial firms and the biotech industry, but we use it internally for all kinds of tasks, so we think any Python developer will be able to do fun stuff with it :-) This is primarily a performance enhancement and bugfix release, but has a couple of features correcting the more egregious missing features in version 1.0. We've put up a full change list, but the highlights are: * Many memory usage and performance fixes, in particular while importing Excel-format spreadsheets. * Updated to IronPython 1.1.1 (fixes socket bugs) * Added UI to set the background color. * Fixed defect 367 - Looking up cells by header row/col is slow * Fixed defect 370 - Cut and Copy part of the text in a cell is not handled correctly If you want to download the non-commercial version of the software, or to buy the commercial version, you can download it from our website (free registration required): Regards, Giles Giles Thomas MD & CTO, Resolver Systems Ltd. giles.thomas at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! (Free registration required) 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From gagsl-py2 at yahoo.com.ar Sun Mar 30 18:48:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 19:48:16 -0300 Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 16:46:00 -0300, escribi?: > using python and wpython. Soory, I don't know what wpython is > when using run module or python shell on the run menu in the GUI i get > "socket error, connection refused". > > it worked before, what si wrong now? Try to detect what changed on your system between "before" and "now". > and i cant find where to start the shell directly. think i had an exe > before but cant seem to find it now. python.exe? > c: > cd \ > dir /s python.exe -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Mar 7 04:14:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 07:14:35 -0200 Subject: help on file storage for split multi part download References: Message-ID: En Fri, 07 Mar 2008 04:16:42 -0200, escribi?: > On Mar 7, 1:38 am, "Gabriel Genellina" wrote: >> En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: >> >> > storage class which can write the file splits that are currently being >> > downloaded to the disk. this is exactly what other download >> > accelerators do, i guess. >> >> Uh, unless I misundersand you, a standard file object is enough. First >> create a file with the required size (open(...,'wb'), seek(n-1), >> write(chr(0))). For each downloaded chunk you have to know its position >> in >> the file; then just seek() and write() it. > > BUT the thing thats going in my mind is thread safety. i plan to start > each part of the file download in a different thread. and then when > each thread had downloaded more than 100kb (or eof or boundary > reached) write the buffer to the disk. can this be achieved using > mutex ? i have never shared objects between threads. Use a different (single) thread to write the file; the others put write requests on a Queue.queue object, and the writer just gets the requests and processes them. > is there a way to write this without using threads at all ??? Using asyncore, and perhaps the Twisted framework. -- Gabriel Genellina From michael.wieher at gmail.com Wed Mar 26 09:43:08 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 26 Mar 2008 08:43:08 -0500 Subject: memory allocation for Python list In-Reply-To: <96e81eb0-9d27-4cfd-82da-7fcc9b3dae25@m3g2000hsc.googlegroups.com> References: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> <96e81eb0-9d27-4cfd-82da-7fcc9b3dae25@m3g2000hsc.googlegroups.com> Message-ID: Just write it in C and compile it into a .so/pyd =) 2008/3/26, bearophileHUGS at lycos.com : > > dmitrey: > > > As I have mentioned, I don't know final length of the list, but > > usually I know a good approximation, for example 400. > > > There is no reserve()-like method, but this is a fast enough operation > you can do at the beginning: > > l = [None] * 400 > > It may speed up your code, but the final resizing may kill your > performance anyway. You can try it. Just using Psyco is probably > better. > > Bye, > bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From geert at nznl.com Tue Mar 18 13:56:10 2008 From: geert at nznl.com (geert) Date: Tue, 18 Mar 2008 10:56:10 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> Message-ID: <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> On Mar 14, 1:15?pm, martin.lal... at gmail.com wrote: > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html Just wanted to let you know that I've solved my problem. The solution is to compile mysql using MACOSX_DEPLOYMENT_TARGET=10.5 \ CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ ./configure --disable-dependency-tracking --enable-thread-safe-client --prefix=/usr/local/mysql You then go this way to get it running on your machine: http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ Then reinstall MySQLdb. Magic! Geert From gagsl-py2 at yahoo.com.ar Fri Mar 7 04:40:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 07:40:22 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> <4e8c4617-af5e-416b-aeba-f58023026340@8g2000hse.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 23:46:43 -0200, escribi?: > oss.message is a abstraction class that writes the method name into a > string, then sends it to OSS... outgoingserver or serverside. > > Now that I'm writing it, and this is important, -to- the -newsgroup-, > I realize you could do it with a simple wrapper... include the > function name in parameters and call the pickler and send. > > OSS then looks like this: > > def something_happens( *ar ): > self.user_act( something_about( *ar ) ) > > So the message.out() instance pickles ( 'user_act', ar ) and sends > it. Then iss.incoming receives it, unpickles that string, gets > 'user_act' from self, and invokes. > > The cool part is the declaration of user_act= message.out(), which > uses a metaclass to assign its own name, and returns a function which > includes the object in its signature. Cool. > > Yes it's working and a little slack. However-: this is the cool > part. I'd like messages to know which instance they came from, and > perform the sending & receiving encapsulated on their own--- not to > subclass class SS( Sending ): with various behaviors: that is, to > assign them as class attributes rather than superclasses. You may look at the SimpleXMLRPCServer class and see how it implements introspection. It's rather easy (and doesn't require metaclasses nor decorators nor any other fancy stuff; I think it works the same since Python 2.1). Apparently you're doing a similar thing, but using pickles instead of xmlrpc. -- Gabriel Genellina From pofuk at email.t-com.hr Tue Mar 4 13:36:03 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Tue, 04 Mar 2008 19:36:03 +0100 Subject: Run Python app at startup In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Sun, 02 Mar 2008 19:37:35 -0200, SMALLp escribi?: > >> Hy. >> I create simple application. Yust an windows and "compile" it with >> py2exe. I add registry value >> reg add >> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v >> MyApp /t REG_SZ /d C:\myapp.exe /f' >> >> And it wont start. When i use console instead od window in py2exe i get >> console opend but it closes. > > I'd check in this order: > > python prog.py > Then, use console=... in setup.py, generate prog.exe > Open a cmd window and execute prog.exe (from the dist directory) > Repeat using window=... in setup.py > > That whole sequence works fine using on my WinXP SP2 + Python 2.5.1 + > wxPython 2.8.7.1 > Program works fine. When i run it it works. Problem is how to make this aplication start at windows startup. It opens and it closes in my case. From pradiprai at gmail.com Fri Mar 14 09:30:35 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Fri, 14 Mar 2008 19:00:35 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From sigzero at gmail.com Sun Mar 16 15:43:14 2008 From: sigzero at gmail.com (Robert Hicks) Date: Sun, 16 Mar 2008 12:43:14 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> Message-ID: On Mar 16, 12:38?pm, lbonaf... at yahoo.com wrote: > On Mar 16, 6:10 am, Bruce Eckel wrote: > > > I think a lot of people have been caught up in the idea that we need > > to commercialize Python, and ride some kind of wave of publicity the > > way that Java and C# and Rails seem to have done. > > This coming from someone who caught the Java wave and rode it for a > decade. Doesn't that make him better to see the problems with it? Robert From gagsl-py2 at yahoo.com.ar Sun Mar 16 16:40:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 18:40:42 -0200 Subject: Using threads in python is safe ? References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Message-ID: En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade escribi?: > I want to use therads in my application. Going through the docs , I read > about GIL. > Now I am confused whether using threads in python is safe or not. > > One thing I know that if I am accessing global variables in two or more > threads I need to synchronize them > using locking or such mechanism so that only one thread access them at a > time. Yes, altough some operations are known to be atomic so you don't need a lock in that cases. I think there is a list in the wiki somewhere http://wiki.python.org/moin or perhaps at the effbot's site http://www.effbot.org > 1. In order to support multi-threaded Python programs, there's a global > lock that must be held > by the current thread before it can safely access Python objects. > Does this lock need to be held by python application script expliciltly > before accessing any python object or > interpreter takes acre of it ? No, the interpreter takes care of it. The GIL is a concern for those writing extensions using the Python API. > 2. Does multithreaded python script need to held lock before calling any > blocking I/O call? > Or one should not worry about GIL while using python threads if job to be > processed by thread does not call > any global variables and thread unsafe Python/C extension ? Python code should not worry about the GIL. The problem would be, a callback written in Python for a not-thread-aware extension that had released the GIL. -- Gabriel Genellina From jr9445 at ATT.COM Thu Mar 20 16:23:06 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 20 Mar 2008 15:23:06 -0500 Subject: What Programming Languages Should You Learn Next? In-Reply-To: References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com><64bugqF2anottU1@mid.uni-berlin.de><7xve3j15ya.fsf@ruckus.brouhaha.com><87fxunumqx.fsf@physik.rwth-aachen.de><7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Donn Cave > Sent: Thursday, March 20, 2008 3:39 PM > To: python-list at python.org > Subject: Re: What Programming Languages Should You Learn Next? > > > Worth repeating. > > One of the perhaps surprising consequences, Haskell code can > be very easy to modify. I've been fooling around with computer > programs for a couple decades, and I'm just getting used to the > idea that I can casually rewrite Haskell code and get the compiler > to find what I missed. I have come to feel that the indiscipline > of dynamic typing in languages like Python leads to an intuitively > surprising rigidity. Ten years ago I would cheerfully accept this, > given the meager and clumsy support for static typing in languages > like C++, but today, it makes me appreciate Haskell's potential > for complex projects. > Haskell does look interesting (especially in light of that one summer job way back when doing a _lot_ of Lotus-123 spreadsheet programming.) There's a Haskell wiki: http://www.haskell.org/ Quicksort in Haskell versus C is amazing: http://www.haskell.org/haskellwiki/Introduction#What.27s_good_about_func tional_programming.3F Quicksort in Python inspired by Haskell's quicksort: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473 ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From fakeaddress at nowhere.org Fri Mar 14 07:17:50 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 04:17:50 -0700 Subject: escape string to store in a database? In-Reply-To: <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> Message-ID: andrei.avk at gmail.com wrote: > how would this work with UPDATE > command? I get this error: > > cmd = "UPDATE items SET content = ? WHERE id=%d" % id > > self.cursor.execute(cmd, content) > pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings > supplied. The c > rrent statement uses 1, and there are 0 supplied. The error message implies that 'content' is an empty sequence. Even when the SQL takes exactly one parameter, the second argument is a sequence containing the parameter. You can use a one-element list, written [someparam], or a one-tuple (someparam,). > Sqlite site doesn't give any details on using parameter bindings in > UPDATE command, I'm > going to look around some more.. To make effective use of Python's Sqlite3 module, I need three references: the Python DB API v2 spec, the Sqlite3 module's doc, and the Sqlite database doc. http://www.python.org/dev/peps/pep-0249/ http://docs.python.org/lib/module-sqlite3.html http://www.sqlite.org/docs.html With all three, parameter binding is still under-specified, but only a little. Those new to the relational model and to SQL will need sources on those as well. On the model, I think the foundational paper has held up well over the decades: Codd, E.F. "A Relational Model of Data for Large Shared Data Banks". /Communications of the ACM/ Volume 13 number 6, June 1970; pages 377?387. It is currently available on line at: http://www.seas.upenn.edu/~zives/03f/cis550/codd.pdf Anyone have a particularly good and easily accessible source to recommend on SQL? -- --Bryan From timr at probo.com Tue Mar 11 03:19:29 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 11 Mar 2008 07:19:29 GMT Subject: tcp client socket bind problem References: <42925034-6cf7-40a7-b079-8f3bf978fea2@n36g2000hse.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > >On Mar 10, 9:40?am, Marc Christiansen wrote: >> nata... at gmail.com wrote: >> > I have a linux box with multiple ip addresses. I want to make my >> > python client connect from one of the ip addresses. Here is my code, >> > no matter what valid information I put in the bind it always comes >> > from the default ip address on the server. Am I doing something wrong? >... > >help string: >Bind the socket to a local address. For IP sockets, the address is a >pair (host, port); the host must refer to the local host. > >docs: >Bind the socket to address. > >Wikipedia: >Before a socket may accept incoming connections, it must be bound. > >PHP.net: >Binds the name given in address to the socket described by socket . >This has to be done before a connection is be established using >socket_connect() or socket_listen(). >This function must be used on the socket before socket_connect(). That's all true. So what was your point? How does this help the original poster? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From __peter__ at web.de Sat Mar 8 13:36:48 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Mar 2008 19:36:48 +0100 Subject: del class with recursive list References: Message-ID: duccio wrote: > Will someone have time to tell me why this code don't work as I expect? > And what should I do to make the "del n" delete all the lower nodes? > Thanks! > > class Node: > def __init__(self): > self.childs=[] > def appendNode(self, n): > self.childs.append(n) > def __del__(self): > print 'del', id(self) > > n = Node() > for i in range(5): > n.appendNode(Node()) > for nodes in n.childs: > nodes.appendNode(Node()) # you forgot a reference to a child node and its child: del nodes > del n > > print '--------end--------' > > > gives this: > > > del 10965280 > del 10965440 > del 10965640 > del 10965400 > del 10965600 > del 10965360 > del 10965560 > del 10965320 > del 10965520 > --------end-------- > del 10965480 > del 10965680 Peter From mblume at freesurf.ch Sun Mar 16 13:45:19 2008 From: mblume at freesurf.ch (Martin Blume) Date: Sun, 16 Mar 2008 18:45:19 +0100 Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> Message-ID: <47dd5caf$0$9029$5402220f@news.sunrise.ch> "sturlamolden" schrieb > > > This seems to imply that the Mac, although running now > > on Intel processors, is still big-endian. > > Or maybe the struct module thinks big-endian is native > to all Macs? It could be a bug. > Dunno, I'm on thin ice here. Never used a Mac. Maybe the underlying C library thinks that all Macs are big-endian? I don't think this qualifies as a bug, but I am astonished that the struct module does not tell you whether you are big endian, you have to find out yourself with struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] Anyway, when handling binary data across machines, I think it is proper to explicitly specify the endian-ness and to do sanity-checking of the results. Regards Martin From S.Mientki-nospam at mailbox.kun.nl Tue Mar 11 06:43:45 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 11 Mar 2008 11:43:45 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <99cd$47d66262$83aef404$29936@news1.tudelft.nl> Gilles Ganault wrote: > On Mon, 10 Mar 2008 11:27:06 -0400, "Malcolm Greene" > wrote: >> Any suggestions on an alternative Python client-side GUI library (pyQT >> ?) or tips on where I can find out more about wxPython/wxWidget >> problems? > > One thing that bothers me is that it seems like there's no ecosystem > around it, so the only widgets available are those that come from > wxWidgets proper. > > For instance, I find the grid object a bit poor-featured compared to > what's available for VB6, .Net, or Delphi, but I didn't find > alternatives. Funny, compared to Delphi-7, I found the grid in wxPython much richer ;-) Very easy to add own in place editors, easy add checkboxes, colorpickers etc into the grid. cheers, Stef From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:07:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:07:42 -0700 (PDT) Subject: Returning values from function to Python shell/IPython References: <91fbb488-4ada-4fea-864b-c5c33c5b4386@e39g2000hsf.googlegroups.com> Message-ID: <95556936-ede6-46a7-999c-56111d6287dc@e60g2000hsh.googlegroups.com> On 9 mar, 20:51, castiro... at gmail.com wrote: > While you're at it, can you call up prior source, and edit it? ?BASIC > had line numbers: > > 10 def f( a ): > 20 ? return a+ 1 > > >>> 15 print( a ) Not so easy. The current CPython implementation assumes that once an object is allocated, it is never moved to another memory location. If doing that were allowed, all the object references had to be updated, or another level of indirection would be required, and neither alternative looks very promising. The reload function tries to reuse the module object itself, but its contents are destroyed and recreated. Maybe for some simple changes like the above the *same* function object could be re-utilized, but not in the general case. -- Gabriel Genellina From danb_83 at yahoo.com Thu Mar 13 21:32:47 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 13 Mar 2008 18:32:47 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: On Mar 13, 7:38 pm, Alan Isaac wrote: > Mark Dickinson wrote: > > Sorting tuples, where the second item in the tuple should > > have the opposite ordering to the first is going to be > > a bit of a pain. Or even worse, where the ordering of the > > second item depends on the value of the first item in the > > tuple. > > This is like some examples where I had used cmp, > > but if I understand correctly I think it is not a problem. > > > For example, suppose that (for whatever contrived reason) > > you're representing integers in (sign, magnitude) format > > by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for > > negative) and i is a string representing the absolute > > value of the integer. So > > Does this do it? :: > > key= lambda x: (-x[1],int(x2)) > > Here I am depending on the lexicographic sorting of tuples. > Without that there would be real trouble. Even assuming you meant (-x[0], int(x[1])), that sorts negative numbers in the wrong order. You want key = lambda x: (-1 if x[0] else 1) * int(x[1]) From castironpi at gmail.com Fri Mar 21 10:07:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 07:07:33 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> <63ns5vF1fcb15U1@mid.uni-berlin.de> <9a0f1e31-7e3a-47ad-a5cf-063829ac7f85@s37g2000prg.googlegroups.com> Message-ID: <2452a0fc-ce28-4f3f-9656-6cd9e6389048@o22g2000hsh.googlegroups.com> On Mar 11, 2:30?pm, Lie wrote: > On Mar 12, 12:00?am, "Diez B. Roggisch" wrote: > > > Actually, the latter is even less cluttered, misses a raise - if pure number > > of literals is your metric, that is. > > You don't just compare by the calling code, you've got to compare also > by the surrounding codes. The calling codes in SE might be a little > bit messy, but it worths by making the code surrounding it more clean > and structured. And anyway, if you used Context Object callback, they > will be as messy as each other. > > > You didn't understand my example. If there is a handler registered, it will > > be invoked. If not, nothing will be raised. The exact same amount of > > state-keeping and lookups needs to be done by the SE-implementation. > > I do understand your example. And even if I misunderstood you about > passing context object, the same problem still exists in context > object based solution, i.e. functions can't make the called function > break automatically, it must be 'break' manually or the program will > go astray (break ==> return, sorry I confused it with break for > loops). And if you used InterruptException to break, it doesn't play > well with multiple SoftExceptions. Are you interested in yielding an object? In situ, a routine has extra information it wants to return to the caller. Can you protocol a number of yields? Discard x for x in operation()[:3]; x= operation(). Or, x= operation()[3], and go back and look operation() [1], which is cached. From puneetbrar at gmail.com Mon Mar 24 05:48:50 2008 From: puneetbrar at gmail.com (puneetbrar) Date: Mon, 24 Mar 2008 09:48:50 -0000 Subject: problems with harvestman on ubuntu 7.10 gusty gibbon Message-ID: Hi there I just saw that program on the awards and wanted to use it as i installed it on ubuntu gusty gibbon it worked fine without errors and when i run it i get the following errors File "/usr/bin/harvestman", line 364, in spider.run_projects() File "/usr/bin/harvestman", line 283, in run_projects self.register_common_objects() File "/usr/bin/harvestman", line 135, in register_common_objects conn = connector.HarvestManNetworkConnector() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/connector.py", line 201, in _init_ self.__configure() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/connector.py", line 326, in __configure self.__configure_protocols() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/connector.py", line 449, in __configure_protocols cookiehandler) File "/usr/lib/python2.5/urllib2.py", line 467, in build_opener opener.add_handler(h) File "/usr/lib/python2.5/urllib2.py", line 303, in add_handler type(handler)) TypeError: expected BaseHandler instance, got regards puneet brar From kyosohma at gmail.com Wed Mar 19 10:57:34 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 07:57:34 -0700 (PDT) Subject: Improving datetime References: Message-ID: On Mar 19, 9:12 am, "Nicholas F. Fabry" wrote: > This is a query for information as to how to proceed. I am not a > professional programmer, but I use Python a great deal to help me in > my main job, which involves designing schedules for a global airline. > As such, I use datetime (and dateutil) extensively, and after much > use, I have come to some conclusions about their utility, and how to > improve them. Some of these changes are quite minor and would result > in a large increase in utility (low hanging fruit), while some changes > are major, and would result in less obvious benefits - but these > changes would increase the 'Python Zen' of them. > > So - where should I propose these changes? Here? python-dev? Should > I write up a full PEP or should I just give a more informal outline > with code samples? I would volunteer to help maintain/improve > datetime, but I don't speak C at all, unfortunately, and datetime > appears to be in C. > > In addition, I have little contact with the Python community - I work > somewhat 'solo' when it comes to my programming projects. So, are > there other people out there who use datetime? Dateutil? What do you > find the deficits/benefits of these modules to be? > > Thank you for your thoughts.... > > Nick Fabry I think you need to do this sort of thing on python-dev. I'm not sure how the PEP process works though. If you give your thoughts in a PEP- like format, you'd probably be taken more seriously though. Mike From gbrunick at andrew.cmu.edu Wed Mar 5 12:59:19 2008 From: gbrunick at andrew.cmu.edu (Gerard Brunick) Date: Wed, 05 Mar 2008 12:59:19 -0500 Subject: Short confusing example with unicode, print, and __str__ Message-ID: <47CEDF77.5050501@andrew.cmu.edu> I really don't understand the following behavior: >>> class C(object): ... def __init__(self, s): self.s = s ... def __str__(self): return self.s ... >>> cafe = unicode("Caf\xe9", "Latin-1") >>> c = C(cafe) >>> print "Print using c.s:", c.s Print using c.s: Caf? >>> print "Print using just c:", c Print using just c: Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) >>> str(c) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Why would "print c.s" work but the other two cases throw an exception? Any help understanding this would be greatly appreciated. Thanks in advance, Gerard From mcepl at redhat.com Sun Mar 2 03:16:28 2008 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 02 Mar 2008 09:16:28 +0100 Subject: sqlite3 adaptors mystery References: Message-ID: On 2008-03-01, 23:41 GMT, Mel wrote: > There's nothing much wrong. cur.fetchall is returning a list > of all the selected rows, and each row is a tuple of fields. > Each tuple is being converted for display by repr, so the > strings are shown as unicode, which is what they are > internally. Change the print to > > for (field,) in cur.fetchall(): > print field > > and you'll see your plain-text strings. Thanks for your help, but plain-text strings is not what I wanted. The boolean variables was what I was after. See this modified version of the script: #!/usr/bin/python import sqlite3 def adapt_boolean(bol): if bol: return "True" else: return "False" def convert_boolean(bolStr): if str(bolStr) == "True": return bool(True) elif str(bolStr) == "False": return bool(False) else: raise ValueError, "Unknown value of bool attribute '%s'" % bolStr sqlite3.register_adapter(bool,adapt_boolean) sqlite3.register_converter("boolean",convert_boolean) db = sqlite3.connect(":memory:") cur=db.cursor() cur.execute("create table test(p boolean)") p=False cur.execute("insert into test(p) values (?)", (p,)) p=True cur.execute("insert into test(p) values (?)", (p,)) cur.execute("select p from test") for (field,) in cur.fetchall(): print field,type(field) The output here is: [matej at viklef dumpBugzilla]$ python testAdaptors.py False True [matej at viklef dumpBugzilla]$ I thought that converter is there for just exactly this -- that I would get back bool values not strings. Sorry for not being clear in the first run. Matej From sturlamolden at yahoo.no Sat Mar 15 17:26:05 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 14:26:05 -0700 (PDT) Subject: Python Generators References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: <87f4929c-4f4a-4522-a4ed-c40acfbfe69c@e25g2000prg.googlegroups.com> On 15 Mar, 21:35, mpc wrote: > generator embedded in the argument only once. Can anyone explain while > the generator will not re-initiate, and suggest a simple fix? I am not sure what you are trying to do, but it seems a bit confused. >>> def concat(seq): for s in seq: yield s >>> seq = xrange(3) >>> for n in xrange(5): h = concat(s for s in seq) for i in h: print i,n 0 0 1 0 2 0 0 1 1 1 2 1 0 2 1 2 2 2 0 3 1 3 2 3 0 4 1 4 2 4 Generators work they way they should. Even when one is used as argument for another. From kyosohma at gmail.com Mon Mar 31 16:52:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 13:52:08 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Message-ID: <41b598ef-c422-417f-9a77-b48eff8e6334@s37g2000prg.googlegroups.com> On Mar 31, 12:24 pm, Amit Gupta wrote: > Hi > > I am looking for a some tool that can convert python scripts to > executable on Linux. > > I found freeeze.py as the only option so far. Couple of queries on > freeze: > > 1. Have anyone used the freeze utility and any experiences to share > from that? > 2. Is there any enterprise-level exe-builder for python on linux > (ActiveState has nothing)? > > Any other related commets are also welcome. > > Thanks > Amit What about creating a setup.py and using the distutils command to build rpms or tarballs? http://docs.python.org/dist/built-dist.html Mike From mblume at freesurf.ch Sun Mar 16 13:23:41 2008 From: mblume at freesurf.ch (Martin Blume) Date: Sun, 16 Mar 2008 18:23:41 +0100 Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> Message-ID: <47dd579d$0$9035$5402220f@news.sunrise.ch> "jasonwiener" schrieb > > I am having a VERY odd problem with unpacking right now. > I'm reading data from a binary file and then using a very > simple struct.unpack to get a long. Works fine on my MacBook, > but when I push it to a Linux box,it acts differently and > ends up pewking. > [...] > > the data looks to be the same, but the unpacking seems to > treat it differently. > Probably little-endian vs. big-endian issue: >>> s '\x1e\xc6\xf3\xb4' >>> struct.unpack('>> struct.unpack('>I', s) (516354996L,) See help(struct) for further information. This seems to imply that the Mac, although running now on Intel processors, is still big-endian. HTH Martin From nanjundi at gmail.com Mon Mar 3 22:12:25 2008 From: nanjundi at gmail.com (Nanjundi) Date: Mon, 3 Mar 2008 19:12:25 -0800 (PST) Subject: _struct in Python 2.5.2 References: Message-ID: <07928222-0436-479f-a1ec-0741f3522500@m34g2000hsc.googlegroups.com> On Feb 24, 10:39 am, Olaf Schwarz wrote: > Hi, > > I am trying to run this applicationhttp://svn.navi.cx/misc/trunk/python/bemused/ > on uNSLUng Linux 6.10 using the optware python packages. > > As I obtained segmentation faults using Python 2.4, I have upgraded to > 2.5.2. Now the execution terminates a lot earlier with this error > message: > > File "/usr/local/bemused_mpd/bemused-mpd.py", line 33, in > import bemused > File "/usr/local/bemused_mpd/bemused.py", line 27, in > import bluetooth, syslog > File "/opt/lib/python2.5/site-packages/bluetooth.py", line 2, in > > import struct > File "/opt/lib/python2.5/struct.py", line 30, in > from _struct import Struct, error > ImportError: No module named _struct > > I found out that there has been a file named _struct.so in 2.5.1 but > it has disappeared in 2.5.2. With no package available for downgrading > to 2.5.1 and no idea how to resolve this I am stuck at this point. > > Any help appreciated. > > Thank you > Olaf Hi Olaf, If you are still stuck, run ./configure make make install if you skip the command make, then the required files (lib/python2.5/lib-dynload/_struct.so) doesn't get created. Get the latest 2.5.2 rpm from python.org, it works. Good luck. -N From castironpi at gmail.com Sun Mar 9 20:37:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 17:37:51 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> <63j4ebF25g6okU1@mid.uni-berlin.de> Message-ID: On Mar 9, 4:51?pm, "Diez B. Roggisch" wrote: > > Perhaps similar technique the compiler uses to determine whether a > > function is a normal function or a generator function? Positive > > forward lookup for any soft exceptions, which would then activate > > matching soft exceptions inside the code? > > What would work is most probably to register soft-exception-handlers > when encountering them at runtime, thus making raising-code aware of > them and execute it only if there are one (or several) present. > > [HO snip] Mr. Roggisch, I just said that. You can unplonk me now. From http Sat Mar 8 18:26:35 2008 From: http (Paul Rubin) Date: 08 Mar 2008 15:26:35 -0800 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Alasdair writes: > What is the best way of finding a ceiling of a quotient of arbitrary sized > integers? ceiling(a/b) = (a+b-1)//b From roy at panix.com Sat Mar 1 09:29:01 2008 From: roy at panix.com (Roy Smith) Date: Sat, 01 Mar 2008 09:29:01 -0500 Subject: Problems building 2.5.1 on AIX Message-ID: I've got an AIX-5.2 box that I'm trying to build Python 2.5.1 on. Configure dies pretty much immediately: hasty:Python-2.5.1$ CC=/usr/vacpp/bin/cc_r ./configure --without-gcc checking MACHDEP... aix5 checking EXTRAPLATDIR... checking for --without-gcc... yes checking for gcc... cc checking for C compiler default output file name... configure: error: C compiler cannot create executables See `config.log' for more details. I get the same result with or without the --without-cgg. There's nothing obvious in config.log (not that I can ever make much sense out of the gibberish configure generates). Any ideas? From tmp1 at viltersten.com Fri Mar 7 10:56:45 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 16:56:45 +0100 Subject: SV: Quit-command not quiting In-Reply-To: References: <63d2efF271u6hU1@mid.individual.net> Message-ID: <63d5v1F23vm9fU1@mid.individual.net> >> The window itself vanishes if i click the >> cross in the upper-right corner but pressing >> the quit-button only makes it "pressed". >> Then, the program freezes. > > How did you run it? From inside IDLE? IDLE itself is written > using Tk, and I think that your mainloop interferes with the > one inside it. If you run your program from the command line > it should work fine. I press F5 while in the editor window. Is there a way to run the program without going to the console window? Perhaps i'm just making things unneccesarily complicated and Python IS supposed to be run from console window? >> from Tkinter import * >> class Demo (Frame): >> def __init__ (self, master = None): >> Frame.__init__ (self, master) >> self.grid () >> self.doLayout () >> def doLayout (self): >> self.quitButton = Button ( >> self, >> text = "Quit", >> command = self.quit) >> self.quitButton.grid () >> >> d = Demo () >> d.master.title ("the coolest demo ever") >> d.mainloop () > > There is only one thing I hate more than spaces after a > parens: spaces before it :) > Please read PEP8, about the suggested style for writting > Python code. http://www.python.org/dev/peps/pep-0008/ I've got no issues one way or the other. Most likely i'll forget from time to time but other than that, i'll try to keep it in mind. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:36:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:36:05 -0300 Subject: Is this a good time to start learning python? References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: En Mon, 31 Mar 2008 13:40:40 -0300, Rui Maciel escribi?: > Recently I woke up inclined to take up the task of learning another > programming language. I've already dipped my toes in Perl (I've read > online > tutorials and wrote a couple of irrelevant pet projects) but, as the > computers at my workplace only sport the python interpreter, it probably > means that learning python will end up serving me better, at least in the > short run. Plus, you know how Perl goes. >So far the decision seems to be a no brainer. Yet, Python 3000 will > arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put > it > in other words, I fear that I will be wasting my time. Don't be scared by the "backwards incompatible" tag - it's the way to get rid of nasty things that could not be dropped otherwise. The basics of Python will continue to be the same, it's not a new, different language; learning Python 2.X isn't a waste of time. Python 3 won't be in widespread use until some (long?) time, and some people won't ever consider it until Python 3.1 arrives; so Python 2.X will continue being used for a long time. -- Gabriel Genellina From pscott at uwc.ac.za Mon Mar 31 07:13:37 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Mon, 31 Mar 2008 13:13:37 +0200 Subject: Beginner advice In-Reply-To: <10dc13c3-df5a-42fc-bca5-318f890feb66@i29g2000prf.googlegroups.com> References: <65bfk7F2esfc1U1@mid.uni-berlin.de> <10dc13c3-df5a-42fc-bca5-318f890feb66@i29g2000prf.googlegroups.com> Message-ID: <1206962017.6828.55.camel@paul-laptop> On Mon, 2008-03-31 at 04:02 -0700, Graham Ashton wrote: > pyGTK is great. I used it quite heavily a year or so ago. GTK is a > nice tool kit from the user's perspective too; you can make some > rather attractive and usable applications with it, and the GUI builder > is a boon. Obviously it integrates slightly better into it's native > platform than it does Mac/Windows, but if you're targetting Ubuntu > users then it's a great choice. OK, this is almost exactly what I needed. All that I really want to know is can I do this in a really easy, comfortable tool like GTK and get away with it without someone 3 months down the line saying something like: "Dude, what were you *thinking* using deprecated stuff like that?" Sorry, but I had to ask, and I am sure that I will ask a lot more questions as things move along. I really appreciate all the feedback so far! It is often quite difficult sifting through all the years worth of blogs, docs and other resources when starting on something new like this, so bear with me, and I will try and make a more meaningful contribution back to Python as soon as I can! --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From castironpi at gmail.com Sun Mar 30 02:22:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 23:22:39 -0700 (PDT) Subject: Where can I find : References: <13uu56hn1vdqb9d@corp.supernews.com> Message-ID: <768026ee-b9f1-4445-bd02-088a2f725a9d@b64g2000hsa.googlegroups.com> On Mar 29, 11:19?pm, Dennis Lee Bieber wrote: > On Sat, 29 Mar 2008 20:15:59 -0700 (PDT), pythonnubie > declaimed the following in comp.lang.python: > > > Hi ?All : > > Does anyone know where I ?can find ?either a book or a website ?that > > explains ?beginning ?python ?by actually ?building a ?project ?line by > > line and explaining ?it indepth . I ?am primarily interested in > > understading ?flowcontrol as well ?as syntax . > > ? ? ? ? Flow control, if I'm not misinterpreting your usage, is something > that most common language books will not really cover -- that falls into > the realms of software engineering... Or, at the simplest, structured > design/programming (even if a language is OO, when one gets down to the > actual logic of methods, one is back into structured programming). > > ? ? ? ? Syntax is covered in the Python language reference manual, and > Python has a very simple vocabulary to learn. > > ? ? ? ? The two are disjoint concepts. Structured design applies to any > language, one just has to map the constructs of the language (and since > Python lacks a native GOTO, this becomes even simpler). That's weird. I feel like I could go on about an introductory program for days and days, la. I usually start (both times) with interpreted vs. compiled. It's a layer of abstraction. But it's very weird; the layers can't tell either of each other apart. I can hand you the machine instructions, the names of circuitry, that run Line 1 to Line 9 one time, but you can't tell the difference between the code and the data. Some of it lingers in post-perceptive operations: the memory system, for the record. Some lingers long times. So far it equates to different Pythons produce different Pythons, however, though, so I'll ask the spell checker. Python.get_back_in_skin(). Weird. I'm not sure if it makes any difference. The binary you run is Python.exe. It's already running, then you feed it a raw string, not on disk without loss of generality. The translation is a little hard to find too. Python :: mingw-c++ : Python.exe :: mingw-c++.exe : what? :: machine instructions.exe In Python there's a for-loop that's the exact same as one in machine instructions. 0101 b1= 1000 0110 if a < b0 goto b1 0111 b2= b2+ 1 accumulates a number in register b2. You probably want interface and graphics primitives. Sometimes I feel like "with a scroll bar" suffices to specify all the detail you need; there's too many options. (I can do this and this and ... scroll bar, please.) You know the episode of Star Trek NG where Barclay takes over the Enterprise. I'd also like to be able to write (write) a series of instructions and have it loop, and debug in vivo, as though a BASIC program were running and I could edit lines in its doing so, maybe time Windows Media visualization codecs in time. You could tell story lines and have it refine, post-inspiration. You might be surprised how much repetition in instructions Lines 1 through 9 (of -code-) share, in both sides of the analogy. Anyone work with a VAX? From ken at seehart.com Sat Mar 8 20:29:56 2008 From: ken at seehart.com (Ken) Date: Sat, 08 Mar 2008 17:29:56 -0800 Subject: Image Libraries In-Reply-To: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> References: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> Message-ID: <47D33D94.6000509@seehart.com> PB wrote: > I have been using PIL for generating images, however it does not > easily support operations with transparency etc. > > I tried to install aggdraw but it wouldn't compile. > > Ideally I'd like something open source so I can adapt it, hopefully > mostly written in python rather than C. > > Is there any other decent image libraries for python? > > I use PIL, and I haven't had any difficulty with alpha channel transparency. But maybe I'm using it for different things than you (blitting PGN(RGBA) antialiased images mostly). What problems are you having specifically? Ken Seehart From castironpi at gmail.com Fri Mar 28 16:59:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 13:59:51 -0700 (PDT) Subject: Tell ya' what: Message-ID: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> I want to regression a signal. It's NN, not necessarily, sine wave. What kind of numbers of harmonic simultaneous sounds are we looking at? How close to an A 440 can a human make? I want recognition to alert me. As a sine wave is coming in: >>> for t in [ ( 200* sin( x*2 ), 200* cos( x*2 ) ) for x in range( 10 ) ]: print( *t ) ... 0.0 200.0 181.859485365 -83.2293673094 -151.360499062 -130.728724173 -55.8830996398 192.03405733 197.871649325 -29.1000067617 -108.804222178 -167.814305815 -107.3145836 168.770791746 198.121471139 27.3474436416 -57.580663333 -191.531896065 -150.197449354 132.063341649 I want new feature characteristics to chain events. Circuits on -not- affected- external nodes can decouple clock tick. Realistically, the human brain uses a layer of several tens before anything is recognizable (sure, this photoreceptor says red all the time). Bring us the process of focus: Think mushroom clouds. Some of the smoke cycles back to redirection newcome particles, formed later in the blast. Program some of the ops. I feel like I'm asking if all the senses stream in paralell. Thing about rivers is, their current runs downstream: which does echo the process of muscle control: multiple brain pathways combine at confluences to generate a river: one muscle fiber microbundle (non contiguous, but that was later evolution). (Finely articulate ionic grades in three dimensions.) Input is other. It's still downstream for inputs, but the waves overlap at the 'deltas' with an chemoelectric interference pattern in either brain or spine, and have to agree on something (saw red, saw temperature, felt pressure). Those, by the way, are triggered by molecule discharge on the scale of 1,000s of atoms: C1814H2725N423O477S25. Recharge takes an electron. (Get one!) Humans: big brains. In brains we have a dynamic structure: you don't ever 'notice' things per se; they just reorganize brain (in particular trigger growth-- they decay themselves). Given intermodality (say, verbo-tactile?), varying circuit length (shortest and longest paths from a peripheral sensory cell to a motor cell (somewhen the name), cumulative depth (length) of iteration (generation) at which concepts form (Sartorius muscle direct stimulation), and correlate factor length of concept, children learn words based on exposure time (snooty kids know 'entrepreneur' (a between taker by the way, and 'revenue' come in again)) and varieties of thingsthatleduptoit: things that led up to it. The deeper concepts don't even motivate you to move, hardly even the tongue. You could do a lot of refining on your electric-medium perceptions: no boring stuff, no watered down, spam making, spam fighting, though with a few extra generations of hardware. Did everyone take the course on computer architecture? From http Sun Mar 2 17:35:33 2008 From: http (Paul Rubin) Date: 02 Mar 2008 14:35:33 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> Message-ID: <7xzltgrbyi.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > Better yet, how hard would it be to define an otherwise int-like type > that did not define a non-flooring division operator? Are there any > real use cases for such a type? User defined types in python are fairly heavyweight compared with the built-in types, and a type like that is just another thing for the user to have to remember. The C library has a bunch of different types like off_t (offset in a file) and size_t, so if you pass an off_t to a function that expects a size_t as that arg, the compiler notices the error. But they are really just integers and they compile with no runtime overhead. So, I think Python won't easily support lots of different types of integers, and we've got what we've got. There's an interesting talk linked from LTU about future languages: http://lambda-the-ultimate.org/node/1277 From castironpi at gmail.com Fri Mar 28 06:14:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:14:31 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> Message-ID: On Mar 28, 1:57?am, raj wrote: > To ankit: > > Well, sort() doesn't return the sorted list. It returns None. Why not > this straightforward way? > dvals = dict.values() > dvals.sort() > print dvals Why not sorted( dict.values() ). Can it return the right things from the right things in order from the givens? ( dvals , values, sort, print ).decode() From jzgoda at o2.usun.pl Mon Mar 17 07:49:57 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 17 Mar 2008 12:49:57 +0100 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: <1a560143-9a65-4c9f-bf5b-cb535d17cc13@z38g2000hsc.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <1a560143-9a65-4c9f-bf5b-cb535d17cc13@z38g2000hsc.googlegroups.com> Message-ID: Paul Boddie napisa?(a): >> I haven't been to EuroPython even when it has been fairly nearby >> because the entrance fee was to high. But how do you help change >> something like that? > > You could join in and make your case. There was a more protracted > discussion than usual last year about fees because some people pointed > out the discrepancy between salary and price levels in different parts > of Europe and the need to make the conference more affordable: what > may be relatively inexpensive for some might be relatively expensive > for others, and the organisers felt that it would be foolish to > exclude the latter group, particularly when they may be more likely to > travel to the conference in its present location. > > It's hard to say whether the conference is reaching everyone it > should, given the composition of attendees: > > http://www.europython.org/community/Planning/Projections I did not event think on attending EuroPython in Switzerland due to high cost of 3-day accomodation there (relatively to my wage these times). Lithuania seems to be not much more expensive than my home country, so I'll travel to Vilnius this year too. I thionk it was valid for others in Poland too, judging from the figures you mention. > But without anyone to pursue a particular cause, and with decisions > needing to be made within certain timeframes (which is often a > struggle, anyway), things often get preserved as they are rather than > being improved. I live in a European country which is either number > one or two on the price scale (depending on whether you include > alcohol prices or not), and I can't say what the right fee level > should be (other than "possibly lower than it is") - it's up to others > to weigh in and give their opinion, I think. EUR 100 does not seem too high as early bird registration fee, so the most intimidating costs (for me at least) is accomodation and travel. I mean, lowering the fee would be nice, but not essential to me. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From deets at nospam.web.de Thu Mar 27 04:27:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 09:27:44 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: References: Message-ID: <65144bF2dp2abU1@mid.uni-berlin.de> Gabriel Rossetti schrieb: > Hello, > > I am using Partial Function Application in a class and I've come up with > a problem, when the method is called it tries to pass "self" to the > curried/partial function, but this should be the first argument in > reality, but since the function is curried, then the self gets passed as > the second argument. Here is the code : > > def __registerService(self, atomic, service): > def reg(service): > # registers the service > ... > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > I should pass self when applying partial, but then I can't do that since > self is not available there. Does anyone have any ideas? Use a bound-method instead. That has the self already bound to it. Like this: class Foo: def m(self, arg): print arg f = Foo() partial(f.m, 10) Diez From pavlovevidence at gmail.com Wed Mar 12 17:42:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 14:42:39 -0700 (PDT) Subject: no more comparisons References: Message-ID: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> On Mar 12, 4:51 pm, Alan Isaac wrote: > I was surprised to see that > comparison is slated for death > in Python 3000. > > For example:http://www.python.org/dev/peps/pep-3100/ > list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done] Hmm, wasn't aware they were taking it that far. You should almost always avoid using the cmp parameter because it's very inefficient; instead, look at the key parameter which is a function that maps objects in a your sequence to a sort key and sorts on that. So instead of (for a simple example): s.sort(cmp=lambda a,b: cmp(a.get_id(),b.get_id())) You would use: s.sort(key=lambda a:a.get_id()) (However, there are rare cases where you can't easily map your items to a sortable builtin. I suppose in those cases you'll have to use a custom comparison proxy. But I digress.) > But there is a rumor of a PEP to restore comparisons.http://mail.python.org/pipermail/python-3000/2008-January/011764.html > > Is that going anywhere? No. > Also, what is the core motivation for removing this functionality? The basically replaced it with a better one. Instead of the cmp methods above, use the key method. Instead of __cmp__ method for overriding object operators, use the rich comparison methods: __lt__, __gt__, and so on. Python 2.x currently implements both cmp and rich comparisons at the same time, but that creates a lot of underlying complexity, so they got rid of it. Carl Banks From larry.bates at websafe.com Fri Mar 28 09:29:25 2008 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 28 Mar 2008 08:29:25 -0500 Subject: simple web-server In-Reply-To: References: Message-ID: <1206710965.11955.14.camel@fc8.home.com> On Fri, 2008-03-28 at 12:53 +0100, Pavol Murin wrote: > hello python users, > > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). > > Longer story: > > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed). > > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? > > thank you, muro Take a look at twisted web, it fits in between. -Larry From robert.kern at gmail.com Mon Mar 3 17:08:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Mar 2008 16:08:53 -0600 Subject: sympy: what's wrong with this picture? In-Reply-To: <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 2:49 pm, Carl Banks wrote: >> It's just a bug--probably sympy is messing with the internals of the >> random number generator. It would be a simple fix. Instead of >> b****ing about it, file a bug report. > > I did. > >> Or better yet, submit a patch. > > I would if I knew what the problem was. Did you even try to figure it out? It took me all of 5 minutes to find the mistake. > I posted it here because someone recommended it. > I'm simply un-recommending it. It was a mistake, an easily remedied mistake, not a big unchangeable design decision. If you want to recommend against sympy as a package, there is a larger burden of proof that you have yet to meet. -- 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 gagsl-py2 at yahoo.com.ar Sat Mar 22 20:03:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 22 Mar 2008 21:03:52 -0300 Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: En Sat, 22 Mar 2008 17:27:49 -0300, sgharvey escribi?: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. Take a look at ConfigObj http://pypi.python.org/pypi/ConfigObj/ Instead of: # Remove the '\n's from the end of each line lines = [line[0:line.__len__()-1] for line in lines] line.__len__() is a crazy (and ugly) way of spelling len(line). The comment is misleading; you say you remove '\n's but you don't actually check for them. The last line in the file might not have a trailing \n. See this: lines = [line.rstrip('\n') for line in lines] Usually trailing spaces are ignored too; so you end up writing: lines = [line.rstrip() for line in lines] In this case: # Compile the regexen patterns = {} for pattern in pattern_strings: patterns.update(pattern: re.compile(pattern_strings[pattern], re.VERBOSE)) That code does not even compile. I got lost with all those similar names; try to choose meaningful ones. What about this: patterns = {} for name,regexpr in pattern_strings.iteritems(): patterns[name] = re.compile(regexpr, re.VERBOSE)) or even: patterns = dict((name,re.compile(regexpr, re.VERBOSE)) for name,regexpr in pattern_strings.iteritems() or even compile them directly when you define them. I'm not sure you can process a config file in this unstructured way; looks a lot easier if you look for [sections] and process sequentially lines inside sections. if match: content.update({pattern: match.groups()}) I wonder where you got the idea of populating a dict that way. It's a basic operation: content[name] = value The regular expressions look strange too. A comment may be empty. A setting too. There may be spaces around the = sign. Don't try to catch all in one go. -- Gabriel Genellina From marco at sferacarta.com Wed Mar 12 12:44:32 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 12 Mar 2008 17:44:32 +0100 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> Message-ID: Robert Bossy wrote: > Indeed! Maybe the best choice for chunksize would be the file's buffer > size... I won't search the doc how to get the file's buffer size because > I'm too cool to use that function and prefer the seek() option since > it's lighning fast regardless the size of the file and it takes near to > zero memory. And makes a hole in the file, I suppose, hence the fragmentation. The OP explicitly asked for an uncompressed file. From tjreedy at udel.edu Sun Mar 30 22:43:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Mar 2008 22:43:58 -0400 Subject: Odd behaviour with list comprehension References: <4fbfbb8f0802291901s5ed7e0b4ua3e77ad46aa53bb7@mail.gmail.com> <871w6vkq3z.fsf@micah.cowan.name> Message-ID: "Steve Holden" wrote in message news:fspe8a$ptq$1 at ger.gmane.org... | Micah Cowan wrote: | > "Jerry Hill" writes: | > | >> On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu wrote: | >>> Is there a way for me keep the iterating variable in list | >>> comprehension local to the list comprehension? | >> Kind of. You can use a generator expression instead of a list | >> comprehension, and those don't leak their internal variables into the | >> enclosing scope: | > | > Whoa, that's cool. I didn't even think to try that, just assuming it | > would do the same. | > | > Though now that I think about it, I don't see how it possibly could, | > since it just evaluates to an object that you could pass around, and | > return, using it the same way elsewhere. | > | Well, the fact that the bound variable in the list comprehension does | indeed remain outside the construct is simply the result of an | over-zealous wish to emulate for loop semantics. The original reasoning, | IIRC, as that since a for loop left its bound variable at the last used | value, so should a list comprehension. | | This was quickly recognized as a mistake, but unfortunately not quickly | enough. As it was felt that some people might already have relied on | that behavior, it was retained in the interests of preserving backwards | compatibility. But it will not be retained in 3.0, as I understand it. So best to not exploit the deprecated behavior. tjr From tjreedy at udel.edu Mon Mar 24 04:33:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Mar 2008 04:33:53 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13ue0gsj76m6070 at corp.supernews.com... | Unfortunately there's nothing we can do to fix that error. Even though | the function object has an attribute "__name__" (also known as | "func_name") which is set to spam, it isn't used for tracebacks. Instead, | the label comes from a read-only attribute buried deep in the function | object: | | >>> tasty_stuff.func_code.co_name = 'yummy meat-like product in a can' | Traceback (most recent call last): | File "", line 1, in | TypeError: readonly attribute The fact that .func_name (which is writeable) is not used at first surprised me until I remembered that code objects can potentially be used by multiple function objects and hence are not connected to any one in particular. | This is a mistake, in my opinion. It's an arbitrary decision to make this | read-only (as far as I can tell), which goes against the grain of | Python's "we're all consenting adults here" philosophy. | | By the way, in case you're thinking that wanting to change the (so- | called) name of a function is a silly think to do, not at all. Consider | factory functions: | | def factory(how_much): | def f(n=1): | for i in range(n): | print "I love spam a %s" % how_much | return f | | Every function created by the factory has the same "name", no matter what | name you actually use to refer to it. factory('little') and | factory('lot') both uselessly identify themselves as "f" in tracebacks. workaround: >>> ftext = 'def %s(): pass' >>> exec ftext%'ftest' >>> ftest so: def factory(how_much): 'param how_much MUST be a legal name' exec '''def %(how_much)s(n=1): for i in range(n): print "I love spam a %(how_much)s"''' % {'how_much': how_much} return locals()[how_much] f2=factory('much') print f2.func_name prints 'much' But certainly setting .co_name directly would be easier Terry Jan Reedy From aahz at pythoncraft.com Mon Mar 17 09:21:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 Mar 2008 06:21:05 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> Message-ID: In article <7x3aqpg3rv.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >Stephan Deibel writes: >> >> I have to admit, I'll keep coming to PyCon even if all the talks suck >> abysmally as long as there's good hallway time, open space, BoFs, and >> sprints. ;-) > >OK, so why not get rid of all the talks and other stuff, and just have >a basically structureless conference, beyond scheduling some open >meetings on various topics? That would be a lot less expensive and a >lot more interesting. Don't think we haven't discussed this. The problem is that some kinds of talks demand a lot of preparation (and therefore need to be scheduled in advance), plus plenty of people like some structure. PyCon -- like most organized human endeavors -- is in many ways about the art of compromise, trying to figure out how to satisfy as many people as possible and disappointing as few as possible, keeping in mind that it is almost impossible to completely satisfy anyone and most people will have some disappointment (if only because two talks that are ABSOLUTELY CRITICAL to them are cross-scheduled). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From deets at nospam.web.de Tue Mar 18 16:59:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Mar 2008 21:59:58 +0100 Subject: method to create class property In-Reply-To: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> Message-ID: <64aoqjF29asbkU1@mid.uni-berlin.de> Joe P. Cool schrieb: > Hi, > > I like C#'s style of defining a property in one place. Can the > following way > to create a property be considered reasonable Python style (without > the > print statements, of course)? > > class sample(object): > def __init__(self): > sample.y = self._property_y() > > def _property_y(self): > def _get(self): > print 'getting y.' > return self._y > def _set(self, value): > print 'setting y.' > self._y = value > def _del(self): > print 'bye, y!' > del self._y > return property(_get, _set, _del) There are a few recipies, like this: class Foo(object): @apply def foo(): def fget(self): return self._foo def fset(self, value): self._foo = value return property(**locals()) Diez From grante at visi.com Mon Mar 24 18:11:40 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 24 Mar 2008 22:11:40 -0000 Subject: FW:Reading new mail from outlook express using Python References: Message-ID: <13ug9osrv1c6h2b@corp.supernews.com> On 2008-03-24, SPJ wrote: > I am trying to create new tickets in the ticketing system > using python. When I receive new email from a particular > address, I have to trigger the python script and parse the > mail in required format. > > The main hurdle here is, how to invoke the script on arrival > of new mail? I checked the outlook settings and found that it > supports only microsoft VB script and Jscript. Is there any > other way? I mean, if I make a daemon, how will it be notified > of new mail? Is there any python module that does this? > > I am not sure if this is the right place to ask this, since it > is also a microsoft related question. But any help is > appreciated. You can use Outlook's COM interface from Python. That allows you to read messages from a mailbox. I don't know of any way to get "notified", but you can use the COM interface to poll the mailbox(es) periodically. -- Grant From wolf_tracks at invalid.com Fri Mar 21 10:33:16 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 21 Mar 2008 07:33:16 -0700 Subject: An Application Program to Play a CD In-Reply-To: References: Message-ID: Thanks for the link. I briefly looked at it, and it sure would be hard to tell if it has application here. The material looks developer oriented. Your short descriptions gives more insight than their home page. They aren't exactly marketing driven; however, I'll give it a closer look. Maybe joining the forum will reveal more about it. Jeff McNeil wrote: > I don't know of any Python specific stuff to do this, but have you > looked at Asterisk? I know it's quite configurable and allows you to > setup dial plans and route extensions and whatnot. > > http://www.asterisk.org/ > > That's probably a better fit. > > On 3/20/08, W. Watson wrote: >> How difficult would it be to write a Python program that would play a >> specific track on a CD from say 8 am to 6 pm each weekday on a PC's speaker, >> and switch tracks each day? That is, what library capabilities might be able >> to do that. Are they already available. >> >> Extra points. Now imagine the same as above, but the program should answer a >> phone and play the track for the day while someone is holding the call, or >> would be given the option to connect to the operator, say, or listen to the >> recording? >> >> To get a bit specific, our science museum would like to buy the monthly set >> of StarDate programs. Each program is about 2 minutes long and there's one >> for every day of the month. There seems to be no such commercial software to >> automate this process. >> -- >> Wayne Watson (Nevada City, CA) >> >> Web Page: >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> -- Wayne Watson (Nevada City, CA) Web Page: From steve at REMOVE-THIS-cybersource.com.au Fri Mar 21 07:21:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 21 Mar 2008 11:21:12 -0000 Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: <13u76h8mifniibc@corp.supernews.com> On Fri, 21 Mar 2008 11:43:33 +0100, sam wrote: > I can see that Python and Javascript inheritance model is almost the > same. Both languages are dynamically typed. And it seems that using > "classes" in Python makes some things more complicated then it is > necessary (eg functions, methods and lambdas are differen beeing in > Python concept). Please explain why you think that functions are more complicated in Python because of the class model. -- Steven From sturlamolden at yahoo.no Wed Mar 19 18:14:25 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 15:14:25 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> Message-ID: <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> On 19 Mar, 22:48, John Machin wrote: > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > and is IMHO more readable than Paul's. Is a Python set implemented using a hash table? From stephenhorne100 at aol.com Mon Mar 17 08:56:24 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 05:56:24 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <15905376-3ec6-4994-84e7-5744ef521778@z38g2000hsc.googlegroups.com> On Mar 17, 11:49 am, MartinRineh... at gmail.com wrote: > What are the considerations in choosing between: > > return [a, b, c] > > and > > return (a, b, c) # or return a, b, c > > Why is the immutable form the default? My understanding is that the immutable form is not the default - neither form is a default. The syntax for mutable lists requires square brackets. The syntax for immutable tuples only requires commas. However, commas are also used for other purposes. The parens for tuples are the same parens that might wrap any subexpression, in this case guarding against misinterpretation of commas. Since the parens are normally included for consistency as well as disambiguation, they end up being part of the tuple psychologically, but to Python itself they are separate. Personally, I'd make the parens compulsory so that mindsets and language specification are better aligned. If, that is, I was inventing a new language. But you can be sure that there's plenty of code out there that would break if a change like that was made now. As for choosing, if you never plan to modify the members of the sequence, a tuple expresses that intent and allows Python to enforce it. Some operations on tuples are probably also more efficient as a result. That said, 90%+ of the time I use a list either way. After all, as requirements change I might find I do need to modify after all. A change from tuple to list in any non-trivial case would require a thorough test suite to ensure that all cases are updated correctly (partly because Python is dynamically typed), and ashamed as I am to admit it, my test suites are rarely that thorough. Without that testing, there might be an obscure case where you still create a tuple, and that tuple gets passed to code that expects a list and tries to replace an element. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 08:45:22 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 14:45:22 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: <659gb2F2f84eoU2@mid.individual.net> hdante wrote: > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: Could you please list some that do, and are also convenient? Regards, Bj?rn -- BOFH excuse #288: Hard drive sleeping. Let it wake up on it's own... From jeff at schwabcenter.com Thu Mar 20 12:59:55 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 09:59:55 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: <13u52hqlbtdv1d1@corp.supernews.com> References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> <13u52hqlbtdv1d1@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-03-20, Jeff Schwab wrote: > >>>> http://www.google.com/search?q=emacs+python >>> Gee. Thanks. >> I believe Grant was suggesting that Emacs often serves a similar purpose >> on Unix to what Visual Studio does on Windows, which seemed to be what >> you were asking. When asking about Mac OS X here, you are likely to get >> a lot of generic Unix responses. (Would it have been clearer if he had >> just said "emacs?") > > Don't the normal "run/debug python from inside emacs" methods > work on OS-X? AFAIK, yes; I don't see why it wouldn't. I missed the word "emacs" in the subject header, and did not recognize "an emac" in the original post as meaning "emacs." From puneetbrar at gmail.com Mon Mar 24 05:47:17 2008 From: puneetbrar at gmail.com (gags) Date: Mon, 24 Mar 2008 02:47:17 -0700 (PDT) Subject: problem with harvestman on ubuntu7.10 gusty Message-ID: <3eacea57-5df9-4f0a-a6e1-548f835ec6ae@s13g2000prd.googlegroups.com> Hi there I just saw that program on the awards and wanted to use it as i installed it on ubuntu gusty gibbon it worked fine without errors and when i run it i get the following errors File "/usr/bin/harvestman", line 364, in spider.run_projects() File "/usr/bin/harvestman", line 283, in run_projects self.register_common_objects() File "/usr/bin/harvestman", line 135, in register_common_objects conn = connector.HarvestManNetworkConnector() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/ connector.py", line 201, in _init_ self.__configure() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/ connector.py", line 326, in __configure self.__configure_protocols() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/ connector.py", line 449, in __configure_protocols cookiehandler) File "/usr/lib/python2.5/urllib2.py", line 467, in build_opener opener.add_handler(h) File "/usr/lib/python2.5/urllib2.py", line 303, in add_handler type(handler)) TypeError: expected BaseHandler instance, got regards puneet brar 9815665000 From rasmussen.bryan at gmail.com Wed Mar 12 02:02:36 2008 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Wed, 12 Mar 2008 07:02:36 +0100 Subject: SOAP access to SharePoint In-Reply-To: <1205271534.4382.5.camel@localhost.localdomain> References: <1205271534.4382.5.camel@localhost.localdomain> Message-ID: <3bb44c6e0803112302m7eecb962jd4e1f05e46c553a5@mail.gmail.com> It's usually not a totally mind destroying process if you hand craft your SOAP messages going off of examples from the service (if you're lucky enough they have ones) and reading their XML Schemas/WSDLs to see what they actually expect. Since it's MS do tests on your hand rolled xml with Microsoft XML Schema validation, this may seem tedious but it is likely to be less tedious than relying on any APIs to agree in the wide wonderful world of Soap based WebServices. Cheers, Bryan Rasmussen On Tue, Mar 11, 2008 at 10:38 PM, Paul Watson wrote: > Has anyone successfully accessed a Microsoft SharePoint WSS using > Python? No, not IronPython. I need for this to be able to run on all > machines the customer might choose. > > Which libs are you using? ZSI, SOAPpy, soaplib, ??? > > http://wiki.python.org/moin/WebServices > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Mar 17 07:59:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 09:59:14 -0200 Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 01:54:01 -0200, WaterWalk escribi?: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. See the wiki at http://wiki.python.org/moin/DevelopmentTools for more editors, debugging tools and IDEs. -- Gabriel Genellina From fn681 at ncf.ca Fri Mar 21 10:30:29 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:30:29 -0500 Subject: Is this valid ? In-Reply-To: References: Message-ID: Lie wrote: > On Mar 20, 4:18 am, Stef Mientki wrote: >> hello, >> >> by accident I typed a double value test, >> and to my surprise it seems to work. >> Is this valid ? >> >> a = 2 >> b = 2 >> >> a == b == 2 >> >> thanks, >> Stef Mientki > > a == b == 2 > is equivalent to > a == b and b == 2 > except that b is only evaluated once for the whole comparison Yes - there seems to be unanimity. Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). Formally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy are comparison operators, then a opa b opb c ...y opy z is equivalent to a opa b and b opb c and ... y opy z, except that each expression is evaluated at most once. Colin W. From yuxi at ece.gatech.edu Mon Mar 10 17:15:46 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 10 Mar 2008 17:15:46 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > There are a number of free tools for image matching but it's not very > easy to decipher the actual algorithm from the code that includes db > management, GUI, etc, etc. I have my own image database and GUI so all > I need is the actual algorithm preferably in pseudo code and not in > the form of a research paper (from which I also found a lot but since > I'm not that much interested in the actual science of image > recognition this seems like an over kill). I'd recommend SIFT. There's quite a bit of information on SIFT. In most cases, they don't cover the background science too much, but are still heavy on the math. Pseudo code is hard to come by since it will take many lines of pseudo code just to express one concise mathematical equation. There are however many links to implementations in various languages on the Wikipedia page. http://en.wikipedia.org/wiki/Scale-invariant_feature_transform I have had good experiences with SIFT for feature extraction from images (I have used it for panorama stitching and robot mapping). It's insensitive to scale and rotation. Note that it is a patented algorithm and this may (or may not) pose a problem for you. From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:25:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:25:48 -0000 Subject: I cannot evaluate this statement... References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <13t3cms4fn6318e@corp.supernews.com> On Fri, 07 Mar 2008 12:38:11 -0800, waltbrad wrote: > The script comes from Mark Lutz's Programming Python. It is the second > line of a script that will launch a python program on any platform. > > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > That makes sense. Because the first condition is true and 'python.exe' > is true. So the next comparison is 'python.exe' or 'python' Well, > python.exe is true. So that value is returned to pyfile. > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. But, > again, on linux pyfile evaluates to python.exe Not on my Linux box. >>> import os, sys >>> sys.platform 'linux2' >>> (sys.platform[:3] == 'win' and 'python.exe') or 'python' 'python' > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? When the first three letters of sys.platform aren't 'win'. -- Steven From castironpi at gmail.com Wed Mar 12 18:04:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 15:04:48 -0700 (PDT) Subject: string / split method on ASCII code? References: Message-ID: <7edad086-68cd-47e1-b984-2c45eb3ef730@n58g2000hsf.googlegroups.com> > ? ?import re > ? ?splitter_re = re.compile(chr(174) + '|' + chr(175)) > ? ?for line in file(FILENAME): > ? ? ?parts = splitter_re.split(line) > ? ? ?do_something(parts) > > and then go find a large blunt object with which to bludgeon the > creator of the file... :) p>> creator= CreatorOfTheFile() p>> creator.bludgeon > p>> From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 18:32:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 22:32:41 -0000 Subject: python program deleted References: Message-ID: <13uo84963p30926@corp.supernews.com> On Thu, 27 Mar 2008 18:08:05 -0400, jim-on-linux wrote: > py users, > > I developed a python program and used py2exe to create the exe. > > I zip the entire package and email it to my clients. > > Some clients get the zip file, unzip the package and everything works > fine. > > And some clients get my email with an icon attached which has the > correct filename but the size is 8k when it should be about 5 mb. That would be an email problem, not a Python problem. You need to: (1) Check that you actually are attaching the 5MB file to the email like you think you are. (2) Check that your mail client is sending the email with attachment. (3) Check that your mail server is accepting the email. (4) Check that your mail server is sending the email. (5) Check that the receiver's mail server is accepting the email. (6) Check that the receiver's mail server is delivering the 5MB email to the user's mailbox. (7) Check that the receiver's mail client is displaying the attachment. It's quite possible that the receiver's mail server is quarantining the attachment. 5MB is a lot for email -- many mail servers will reject emails larger than 10MB, although in my opinion setting the limit at 5MB is being overly strict. Once you've confirmed that the attachment left your mail server, you need to tell your clients to speak to their system administrator. -- Steven From half.italian at gmail.com Thu Mar 20 13:45:03 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 20 Mar 2008 10:45:03 -0700 (PDT) Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: On Mar 20, 6:42?am, Duncan Booth wrote: > Steven D'Aprano wrote: > > On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: > >> By default Python on Windows allows you to open a file for reading > >> unless you specify a sharing mode which prevents it: > > > But the OP is talking about another process having opened the file for > > WRITING, not reading. It's that other process that has exclusive access, > > and the OP was trying to determine when it was safe to attempt opening > > the file according to whether or not it was still growing. > > No, unless the other process has specified that it wants exclusive access > there is nothing stopping his process also opening the file. That's why he > has to specify when he opens it that he wants exclusive access: then it > doesn't matter what the other process does, he won't be able to open it > until the other process has closed the file. > > This all of course assumes that the other process writes the file in one > single atomic chunk. If it were to create it and then separately open and > write to it then all bets are off. Thanks for your input. After trying again this morning, the file is opened for reading. I must have had some wonky permissions on that file, so the error method won't work. Trying to use the md5 technique won't work here either. It takes quite awhile to run one md5, let alone two on a growing file. These files can be 20-50GB. The overall idea is to be able to tell if a file has finished being placed in a directory without any control over what is putting it there. If I'm in control of the process, I know I can put it in a temp area, etc. I use the method I mention in my original post regularly without knowing how the file gets there, and was surprised to see it didn't work on Windows. In this case, there will be so few people touching the system, that I think I can get away with having the copy be done from Unix, but it would be nice to have a general way of knowing this on Windows. ~Sean From grante at visi.com Sat Mar 1 23:14:44 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 04:14:44 -0000 Subject: SV: Where's GUI for Python? References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> Message-ID: <13skadks8k9bvf7@corp.supernews.com> On 2008-03-02, K Viltersten wrote: >>> import tkininter >>> >> When that fails, try without the stutter >> >> import tkinter > > > I must be doing something wrong because > neither tkinter nor tkininter works. You probably don't have tkinter installed. It's not installed by default on many systems. -- Grant Edwards grante Yow! Yow! I'm imagining at a surfer van filled with visi.com soy sauce! From castironpi at gmail.com Sun Mar 2 13:18:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 10:18:40 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> On Mar 2, 12:01?pm, John DeRosa wrote: > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > >Hi, > > >Have you ever seen Beautiful Python code? > >Zope? Django? Python standard lib? or else? > > >Please tell me what code you think it's stunning. > > Just about any Python code I look at. Decorators, with, and namedtuple. From jr9445 at ATT.COM Fri Mar 14 14:47:07 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 14 Mar 2008 13:47:07 -0500 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Aahz > Sent: Friday, March 14, 2008 2:05 PM > To: python-list at python.org > Subject: RIP: Joseph Weizenbaum > > Creator of Eliza: > > http://www-tech.mit.edu/V128/N12/weizenbaum.html > -- How do you feel about creator of Eliza? ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From castironpi at gmail.com Wed Mar 26 22:55:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 19:55:53 -0700 (PDT) Subject: genetic algors in practical application Message-ID: <2242528c-764f-4aa6-a605-f2d05b25484e@u69g2000hse.googlegroups.com> I want to go in to construction. However, 'I' means 'newsgroup' and 'want to go' means 'is'. If you had an army of two-micron spiders, could we build something? Use case is an American skyscraper. They have powerful tricks. Clearly they can withstand a force. These can withstand more combined, greater-than-minimum. What is their command set? Braid. Hoist. Vine power and waste. Charge, double-pump circuit. Round-trip a dollar. I said round. (What's the square trip.) You do know that the brain has seven trillion atoms, right? Mass of water. You know, combine 'muscle fiber' with 'inhibition, excitation' and 'motor neuron circuit', and you might be on to something, and you might be right. Here's free from Neuro. 'Each motor neuron synapses with multiple muscle fibers. .. Cross section through the muscle shows the distribution of muscle fibers (red dots) contacted by the motor neuron.' Power-- Tools. Note that 'synapse' verb. Written English folks. 'myelin debris' too. Is your concern the actual construction of the nanospiders (interesting side note), or programming it? Get a team of programmers too. Who asked for the 'Python d.j. console'? Did -uuu- put that on line. From kar1107 at gmail.com Tue Mar 4 02:09:35 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 3 Mar 2008 23:09:35 -0800 (PST) Subject: clocking subprocesses References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> Message-ID: On Mar 3, 9:57 am, barnbu... at gmail.com wrote: > Hi, > > I've seen several threads on this subject, but haven't (yet) run > across one that answers my specific questions. This should be really > easy for someone, so here goes: > > I'm running some numerical simulations under Ubuntu, and using Python > as my scripting language to automatically manage input and output. I > need to have a precise performance measurement (CPU time) of how long > it takes to run my simulations. > > Right now I have something like: > > stime = time.time() > subprocess.call(["./mysim","args"]) > ftime = time.time() > print ftime-stime > > However, time.time() only gives wall-clock time, so I'm also measuring > the time it takes to run other processes running at the same time. > What I'd rather have is: > > stime = time.clock() > subprocess.call(["./mysim","args"]) > ftime = time.clock() > print ftime-stime > > But this, of course, usually outputs 0, because time.clock() does not > count the CPU ticks of the subprocess. > > So, long story short, I need to get CPU time of something I call using > subprocess.call(). I don't want to have to profile my code, since it > will significantly reduce computation time. Use os.times(). It returns a 5-tuple and what you want is child cpu times. times(...) times() -> (utime, stime, cutime, cstime, elapsed_time) Return a tuple of floating point numbers indicating process times. cutime+cstime will give you the total CPU used by child (your simulation). Karthik > > Thanks for the advice. > > Kevin From mensanator at aol.com Tue Mar 11 01:40:52 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 10 Mar 2008 22:40:52 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> On Mar 10, 10:44?pm, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. Needs work. ## Do you want to calculate primes? 1 = yes and 2 = no. 1 ## What number do you want to use as the final number to calculate with? 66 ## What number do you want to start calculating primes from? 2 ## 2 is not prime. False ## 3 is prime. True ## 4 is prime. False ## 5 is prime. True ## 6 is not prime. True ## 7 is prime. True ## 8 is not prime. True ## 9 is not prime. True ## 10 is not prime. True ## 11 is prime. True ## 12 is not prime. True ## 13 is prime. True ## 14 is not prime. True ## 15 is not prime. True ## 16 is not prime. True ## 17 is prime. True ## 18 is not prime. True ## 19 is prime. True ## 20 is not prime. True ## 21 is prime. False ## 22 is not prime. True ## 23 is prime. True ## 24 is prime. False ## 25 is prime. False ## 26 is not prime. True ## 27 is not prime. True ## 28 is not prime. True ## 29 is prime. True ## 30 is not prime. True ## 31 is not prime. False ## 32 is prime. False ## 33 is prime. False ## 34 is not prime. True ## 35 is prime. False ## 36 is not prime. True ## 37 is not prime. False ## 38 is not prime. True ## 39 is prime. False ## 40 is prime. False ## 41 is prime. True ## 42 is not prime. True ## 43 is not prime. False ## 44 is not prime. True ## 45 is prime. False ## 46 is not prime. True ## 47 is prime. True ## 48 is not prime. True ## 49 is not prime. True ## 50 is prime. False ## 51 is not prime. True ## 52 is not prime. True ## 53 is not prime. False ## 54 is not prime. True ## 55 is prime. False ## 56 is prime. False ## 57 is not prime. True ## 58 is not prime. True ## 59 is not prime. False ## 60 is prime. False ## 61 is prime. True ## 62 is not prime. True ## 63 is prime. False ## 64 is not prime. True ## 65 is prime. False ## Do you want to calculate primes? 1 = yes and 2 = no. 2 ## Goodbye. From willsteve2003 at yahoo.ca Sat Mar 8 13:24:38 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Sat, 8 Mar 2008 10:24:38 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <7d442cdd-749e-4391-ba31-e9c86d090137@x41g2000hsb.googlegroups.com> On Mar 8, 9:43?am, malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > ? ? x = q.get() > ? ? #process x to get zero or more y's > ? ? #for each y: > ? ? q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > ? ? #process x to get zero or more y's > ? ? q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? > > Regards, > > Muhammad Alkarouri I think it's a bad practice to get into. Did you intend to do the "process" step again over the added variables? If not I would set a new variable, based on your awful naming convention, let's call it z. Then use z.append(y) within the for loop and after you are out of your for loop, q.append(z). From furkankuru at gmail.com Tue Mar 25 21:22:41 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 03:22:41 +0200 Subject: embedded python pythonpath In-Reply-To: References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> Message-ID: <3a4a8f930803251822h5d423198yc318ed270ad7d92a@mail.gmail.com> On 3/26/08, Gabriel Genellina wrote: > En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru > escribi?: > > > Actually, I do not want any .py or .pyc files around my executable. > > (including userdict, sys, site etc) > > I want to have just single zip file for all python files. > > Putting all of them into pythonNN.zip (NN depending on the Python version > in use) should be enough, but I've never tried it. I had already tried putting all of them into pythonNN.zip but I had to copy it to the place where sys.path points in my case it was windows\system32\python25.zip > I had a look at py2exe source codes but could not figure out how it just > > looks into a zip file. > > Standard Python already supports having zip files in sys.path (using the > builtin zipimport module), you don't have to do anything special to enable > that (apart from building with the required dependencies, like zlib, of > course) yes I know but I do not want "any" py or pyc file. I would still need dict.pyc, sys.pyc, site.pyc etc. files for py_initialize. > So maybe I have to compile the svn version of python. > > After renaming the directory where Python 2.5 were installed, my > test25.exe program (the one compiled using Python 2.5.1) worked fine. So > it looks like it is something with how the "python home" is searched. Ok then changing or deleting pythonhome environment variable may fix the problem? thanks, Anyway, as I said earlier, you don't have to play with PYTHONPATH; just > add any required directory to sys.path at runtime. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat Mar 1 13:01:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 10:01:49 -0800 (PST) Subject: SQLLITE References: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> <62tjigF24ui98U2@mid.uni-berlin.de> Message-ID: <74838b55-9b05-4f90-8a15-37bb50a775da@h11g2000prf.googlegroups.com> On Mar 1, 11:54?am, "Diez B. Roggisch" wrote: > nexes schrieb: > > > Hello All, > > ? ?I am having a minor problem when I try and do this: > > ? ? ? c.execute("insert into [tblTranscripts] (MovieID,Transcript) > > Values(" + movieID + ",'" + formatText + "');") ? (don't even bother > > commenting of the sql style I know its bad form but this is a simple > > script). Whenever I try and do the insert I get table not found, > > however when I perform the sql through sqlite's command line program > > (the sql is outputted via a print statement) it works fine. ?Any ideas? > > No, and without more context nobody will have. Does working with the > table with other statments work, how do you connect the DB, are you sure > you really use the same DB-file and so forth. > > Diez There's a number of things it could be-- narrow it down a little more (for the reader). Beginner stuff is usually forgetting 'use moviedata'. From gandalf at shopzeus.com Tue Mar 25 05:05:28 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Mar 2008 10:05:28 +0100 Subject: eval and unicode In-Reply-To: <47E42213.50208@v.loewis.de> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> <47E42213.50208@v.loewis.de> Message-ID: <47E8C058.8050702@shopzeus.com> Martin v. L?wis wrote: >> eval() somehow decoded the passed expression. No question. It did not >> use 'ascii', nor 'latin2' but something else. Why is that? Why there >> is a particular encoding hard coded into eval? Which is that >> encoding? (I could not decide which one, since '\xdb' will be the >> same in latin1, latin3, latin4 and probably many others.) > > I think in all your examples, you pass a Unicode string to eval, not > a byte string. In that case, it will encode the string as UTF-8, and > then parse the resulting byte string. You are definitely wrong: s = 'u"' + '\xdb' + '"' type(s) # eval(s) # u'\xdb' s2 = '# -*- coding: latin2 -*-\n' + s type(s2) # eval(s2) # u'\u0170' Would you please read the original messages before sending answers? :-D L From stefan_ml at behnel.de Thu Mar 27 13:23:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Mar 2008 18:23:25 +0100 Subject: "Soup Strainer" for ElementSoup? In-Reply-To: <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> <47e87a88$0$36376$742ec2ed@news.sonic.net> <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> Message-ID: <47EBD80D.3010902@behnel.de> erikcw wrote: > I'm parsing real-world HTML with BeautifulSoup and XML with > cElementTree. > > I'm guessing that the only benefit to using ElementSoup is that I'll > have one less API to keep track of, right? If your "real-world" HTML is still somewhat close to HTML, lxml.html might be an option. It combines the ElementTree API with a good close-to-HTML parser and some helpful HTML handling tools. http://codespeak.net/lxml http://codespeak.net/lxml/lxmlhtml.html You can also use it with the BeautifulSoup parser if you really need to. http://codespeak.net/lxml/elementsoup.html Stefan From davidbak at gmail.com Fri Mar 7 16:00:53 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 13:00:53 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class Message-ID: I want - but cannot get - a nested class to inherit from an outer class. (I searched the newsgroup and the web for this, couldn't find anything - if I missed an answer to this please let me know!) I would like to build a class for a data structure such that nodes of the data structure - of interest only to the data structure implementation itself and not to the consumer - are instances of one of two class types. I thought to encapsulate the nodes' classes like this: class Tree(object): ...class _MT(Tree): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node(Tree): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def merge(self, T): ......def __init__(): return _MT() ...... In other words, some methods would be implemented on instances' classes (like isEmpty and insert) and some on the outer class (like merge). Users of the data structure never need to know about the nodes, much less the nodes' classes, so I wanted to encapsulate them However I can't do this, because, of course, the name Tree isn't available at the time that the classes _MT and _Node are defined, so _MT and _Node can't inherit from Tree. What is the Pythonic thing I should be doing instead? (Easy answer: Put this code in a module, exposing only a factory function. I could do that, but wanted to know if I could encapsulate it as described so I could actually put several similar data structures into one module.) Thanks! -- David From deets at nospam.web.de Sat Mar 29 09:49:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 14:49:31 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> Message-ID: <656vnpF2ekcsrU1@mid.uni-berlin.de> > I appreciate the droll sense of humor, but do you mean to > assert that asyncore.py supports asynchronous disk file I/O? As I said in an answer to the OP, I somewhat glossed over the "file" and just read IO. And under Posix, python *does* support asynchronous IO using the select-module. If you can faciliate that using the asynchore module I can't say, but the question was if python as whole supported async IO out of the box - asyncore & twisted I mention as references of implementations using that. > What that means to me is, you queue a disk read, and there's > an event flag or something that you can wait for before you > come back to find the data in your buffer. (That's how I > remember it from the old days, when it mattered a little, > though not enough that I ever remember actually doing it, > and 20 years later I guess the incentive is even less.) Which is exactly what select allows you to do. You pass a set of file-descriptors and are notified if data arrives or has been successfully transmitted. Diez From mail2spj at yahoo.com Mon Mar 24 17:00:13 2008 From: mail2spj at yahoo.com (SPJ) Date: Mon, 24 Mar 2008 14:00:13 -0700 (PDT) Subject: Reading new mail from outlook using Python Message-ID: <924616.42495.qm@web50105.mail.re2.yahoo.com> An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Mon Mar 3 07:35:30 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 3 Mar 2008 12:35:30 -0000 Subject: Cant run application as ./myapp.py Message-ID: <00ec01c87d2b$11f4f0f0$35ded2d0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application here which for some reason won't start using the following syntax from the command line: Cd /mydirectory ./MyApplication.py I have to run this as a fully qualified python launch such as: Cd /mydirectory python MyApplication.py This is a little bit confusing to me as I have other applications which run just fine using the ./somthing.py syntax. Is there any reason why this doesn't work? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ebenze at hotmail.com Fri Mar 14 16:09:44 2008 From: ebenze at hotmail.com (Eric B.) Date: Fri, 14 Mar 2008 16:09:44 -0400 Subject: Installing Python2.4 on RHEL4? Message-ID: Hi, I appologize if this is slightly OT, but I am really struggling to figure out how to install Python2.4 on RHEL4. To make matters worse, the RHEL4 machine is a 64bit architecture. I search pyvault, but they only have for .i386. Does anyone know where / how I can find Python2.4 for RHEL4 x64? If there is a better place to be asking this question, please let me know, and I will redirect my queries elsewhere. Thanks so much. Eric From ankitks.mital at gmail.com Fri Mar 28 01:38:48 2008 From: ankitks.mital at gmail.com (ankitks.mital at gmail.com) Date: Thu, 27 Mar 2008 22:38:48 -0700 (PDT) Subject: problem with sorting Message-ID: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> >>> dict = {'M':3, 'R':0, 'S':2} >>> print dict {'S': 2, 'R': 0, 'M': 3} now if I wanted sorted values in list, i am not able to do this >>> print dict.values().sort() None it returns None instead of [0, 2, 3] From castironpi at gmail.com Fri Mar 7 15:25:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 12:25:22 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: On Mar 7, 10:12?am, alex.pedwyso... at gmail.com wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... > > I want to be able to detect if they fail with error, I want to be able > to time them, and I want to be able to stop them if they run too > long. ?I cannot add code to the eval'd strings that will help me > accomplish this. > > Is there a good way to do this? ?I have it figured out for perl but > I'd rather use python if possible. > > Thanks for any assistance. How does this sound? Write back if it's way far off from what you want. for line in break in put on line break push in interactive console extra linebreak at function ends return list of functions? ... and I'll stop before I actually write it. Bets off! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 19 06:04:54 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Mar 2008 11:04:54 +0100 Subject: Need Help Starting Out In-Reply-To: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <47e0e546$0$30851$426a74cc@news.free.fr> jmDesktop a ?crit : > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. > > I want to use it for web building with database access. What do I use > for that? Does it matter what I use on the client side (mootools, or > whatever)? Your best bets are probably Django, Pylons or web.py. But you should learn enough of the core language itself before jumping in web stuff IMHO. From deets at nospam.web.de Thu Mar 27 03:59:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 08:59:00 +0100 Subject: last mouse movment or keyboard hit In-Reply-To: References: Message-ID: <6512egF2dik46U1@mid.uni-berlin.de> Ron Eggler schrieb: > Hi, > > I would like to get the time of the most recent human activity like a cursor > movement or a key hit. > Does anyone know how I can get this back to start some action after there > has been no activity for X minutes/seconds? Try hooking yourself into the OS screen-saver-code. Diez From arnodel at googlemail.com Thu Mar 13 19:45:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 16:45:49 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: <5d974a2f-a810-4882-8254-513f7b000fbe@e23g2000prf.googlegroups.com> On Mar 13, 11:29?pm, Dave Kuhlman wrote: > Arnaud Delobelle wrote: > > > 4. ?Both points above follow from the fact that foo.bar is really a > > function call that returns a (potentially) new object: in fact what > > really happens is something like > > Arnaud and Imri, too - > > No. ?foo.bar is *not* really a function/method call. It is. The keyword here is 'descriptor'. Maybe reading this will help: http://users.rcn.com/python/download/Descriptor.htm > > > > ? ? Foo.__dict__['bar'].__get__(foo, Foo). > > > So every time foo.bar is executed an object is (or may be) created, > > with a new id. > > > HTH > > I appreciate the help, but ... > > Actually, it does not help, because ... > > My understanding is that foo.bar does *not* create a new object. ?All it > does is return the value of the bar attribute of object foo. ?What new > object is being created? A bound method. Compare the following: >>> foo.bar > >>> Foo.__dict__['bar'].__get__(foo, Foo) > >>> > If I have: > > ? ? class Foo(object): > ? ? ? ? def bar(self): pass > > And I do: > > ? ? foo = SomeClass() > > then: > > ? ? foo.bar > > should return the same (identical) object everytime, no? ?yes? No. This is what I explained in my original reply. > I'm still confused. That's because you need to adjust your understanding. -- Arnaud From theller at ctypes.org Sun Mar 16 07:01:42 2008 From: theller at ctypes.org (Thomas Heller) Date: Sun, 16 Mar 2008 12:01:42 +0100 Subject: app runs fine with interpreter, but not under py2exe In-Reply-To: References: Message-ID: Doug Morse schrieb: > Peter, > > Genius! You nailed it -- thanks! > > py2exe is apparently getting confused by the fact that packages "Numeric" and > "numpy" both have files multiarray.pyd and umath.pyd. It copies just one of > each -- from $PYTHONHOME/Lib/site-packages/numpy/core -- and puts both of them > into the top-level of the created "dist" directory. Also, there are no such > files as multiarray.pyc and umath.pyc in my python installation, but py2exe > seems to create these (in the dist and dist/numpy/core directories) -- they > are small (e.g., 526 bytes) and I'm guessing that they are stubs that simply > point python to the matching .pyd that py2exe relocated. [...] > > Just for completeness and perhaps a bit of additional clarity, here's a > limited directory listing of what the steps in the previous paragraph produce: > > morse> find dist | egrep "(multia|umath)" | xargs ls -l > -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd > -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/multiarray.pyd > -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/umath.pyd > -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd > [...] > Is this something I should pursue getting the py2exe folks to fix / work with > them on fixing? In investigating this issue, I noted that a lot of other > py2exe problems seem to revolve around confusions when duplicate files exist > in different modules. I wouldn't thinking that getting py2exe to pay better > attention to the containing modules when building it's dependency tree would > be that difficult (or is it)? I have the impression that this issue may already be fixed in py2exe CVS but noone bothered to do a release. Here is the corresponding changelog entry: * build_exe.py: Patch from Grant Edwards, slightly adjusted: py2exe now renames the pyd files that it copies into the dist directory so that they include the package name. This prevents name conflicts. I have created installers and uploaded them (for testing!) to the starship: http://starship.python.net/crew/theller/py2exe-0.6.7.win32-py2.3.exe http://starship.python.net/crew/theller/py2exe-0.6.7.win32-py2.4.exe http://starship.python.net/crew/theller/py2exe-0.6.7.win32-py2.5.exe Please try them out. Thanks, Thomas From castironpi at gmail.com Fri Mar 7 18:41:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 15:41:06 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> Message-ID: On Mar 7, 4:39?pm, DBak wrote: > On Mar 7, 1:19?pm, "Chris Mellon" wrote: > > > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > > ?However I can't do this, because, of course, the name Tree isn't > > > ?available at the time that the classes _MT and _Node are defined, so > > > ?_MT and _Node can't inherit from Tree. > > > Not only is the name not defined, the class doesn't even exist yet. > > Yes, but, well - it certainly isn't usable yet, but some object (that > will be the class when it is finished) is being built (its __dict__ is > being populated, etc.) - so there's an object pointer available inside > the interpreter that could be put somewhere. ?But this is pedantic - > you're right, the class really isn't available until after the class > statement. There is no obvious solution-- What do you mean? If there are any at all, there is significant competition without clear winners. dict dictA: membA= 0 membB= 0 dict dictB: membC= 0 But, if you try to nest them, do you want the rest of the 'dict' at its outer level evaluated (that's your 'here is the crux'), or only that point so far? dict dictO: membA= 0 dict membB: membC= 0 membD= membE membE= 0 So, you can't refer to it at all. Especially if membE is defined in outer scope. > class Tree(object): > ...class _MT(Tree): Can you use a metaclass--- postponedinstantiating (since a class is an instance of A PARTICULAR THING.) And one of us could even lobby the wigs to put a metaclass in the standard library. What's the first to go? . If you could have any one metaclass in it, what would it be? The additions with the biggest pull are the ones that can make money really easily for Python speakers. Yes, money. How long is the workaround? In this case, if you want _MT in Tree (or the analogous pair, without loss of generality), you can still get it done (you know where to find me), thanks to Python. You just sacrifice how closely the final product (code), resembles the concept. Yes, that idea would make class definitions more explanitorily powerful-- have more acute explanations. But you need to assign meaning to a syntax element, which is done over time. If Python is a hybrid between C and ML, what is the hybrid between Python and XML? From castironpi at gmail.com Thu Mar 6 14:37:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 11:37:50 -0800 (PST) Subject: What is a class? References: Message-ID: On Mar 6, 1:03?pm, "johan.san... at gmail.com" wrote: > On Mar 5, 7:50 pm, castiro... at gmail.com wrote: > > > What is a class that is not a module? > > A class is a bag of stuff and a namespace :) > > J. A module is a bag of stuff and a namespace. Different stuff. { '__module__', '__weakref__'} From cokofreedom at gmail.com Tue Mar 18 12:19:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 18 Mar 2008 09:19:58 -0700 (PDT) Subject: globals() using For Loop against Generator Message-ID: <599451f4-7687-4d02-b546-a7fbb0f33c8d@h11g2000prf.googlegroups.com> if __name__ == '__main__': print "Globals (For Loop):" try: for i in globals(): print "\t%s" % i except RuntimeError: print "Only some globals() printed\n" else: print "All globals() printed\n" print "Globals (Generator):" try: print "\n".join("\t%s" % i for i in globals()) except RuntimeError: print "Only some globals() printed\n" else: print "All globals() printed\n" >>> >>> Globals (For Loop): >>> __builtins__ >>> Only some globals() printed >>> >>> Globals (Generator): >>> __builtins__ >>> __name__ >>> __file__ >>> i >>> __doc__ >>> All globals() printed >>> Why is it with a generator I get everything out but with a for loop I don't? I know that globals is not read-only but I would of expected the same behaviour from both... Any thoughts? From bavanikumar22 at gmail.com Wed Mar 26 05:47:07 2008 From: bavanikumar22 at gmail.com (bee) Date: Wed, 26 Mar 2008 02:47:07 -0700 (PDT) Subject: Hi iam bavani Message-ID: <9f1a51e7-333c-4b69-99be-91fe20fe7e52@s8g2000prg.googlegroups.com> Hi iam bavani life is the first gift love is thesecond understanding is the third **************************************** htt:"my profile 22 blogs pot.com ********************************************** username:bavanikumar22 *********************************************** From __peter__ at web.de Sun Mar 9 15:04:24 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Mar 2008 20:04:24 +0100 Subject: SV: Changing the size of a Button References: <63ifhtF277va7U1@mid.individual.net> <63iokhF284p4hU1@mid.individual.net> Message-ID: K Viltersten wrote: > What i wish to do is to affect the size > of the button but not due to change of > text but due to resize of the frame it > resides in. This is done by the layout manager, too: import Tkinter as tk root = tk.Tk() button = tk.Button(root, text="42") button.pack(fill=tk.BOTH, expand=True) root.mainloop() Alternatively, with a grid layout: button.grid(row=0, column=0, sticky="nsew") root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) Peter From troworld at gmail.com Tue Mar 4 10:04:49 2008 From: troworld at gmail.com (Tro) Date: Tue, 4 Mar 2008 10:04:49 -0500 Subject: Altering imported modules In-Reply-To: <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> References: <200803011856.27611.troworld@gmail.com> <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> Message-ID: <200803041004.50553.troworld@gmail.com> On Monday 03 March 2008, castironpi at gmail.com wrote: > On Mar 3, 5:09?pm, Tro wrote: > > On Sunday 02 March 2008, Paul McGuire wrote: > > > On Mar 2, 3:48?pm, Tro wrote: > > > > On Sunday 02 March 2008, Terry Reedy wrote: > > > > > "Tro" wrote in message > > > > >news:200803011856.27611.troworld at gmail.com... > > > > > > > > > > | Hi, list. > > > > > | > > > > > | I've got a simple asyncore-based server. However, I've modified > > > > > | the > > > > > > > > > > asyncore > > > > > > > > > > | module to allow me to watch functions as well as sockets. The > > > > > | modified asyncore module is in a specific location in my project > > > > > | and is imported > > > > > > > > > > as > > > > > > > > > > | usual from my classes. > > > > > | > > > > > | Now I'd like to use the tlslite library, which includes an > > > > > | asyncore mixin class. However, tlslite imports "asyncore", which > > > > > | doesn't include my own modifications. > > > > > | > > > > > | I'd like to know if it's possible to make tlslite load *my* > > > > > | asyncore > > > > > > > > > > module > > > > > > > > > > | without changing any of the tlslite code. > > > > > > > > > > If your module is also 'asyncore' and comes earlier in the search > > > > > path, I would expect the import to get yours. > > > > > > > > It's not. It has a package prefix like my.package.asyncore. I think I > > > > can either move my version of asyncore up a couple of levels or add > > > > the my.package directory to sys.path. > > > > > > > > My version of asyncore imports several functions from the built-in > > > > asyncore. Now that my version of it is imported as asyncore, how > > > > would it import the built-in version from python2.5/site-packages? > > > > > > > > Thanks, > > > > Tro > > > > > > What happens if you do "import my.package.asyncore as asyncore"? > > > > > > If that doesn't work (trying the simplest hack first), I know that > > > there are various hooks in the import mechanism that should help. > > > > In the classes that use my version of asyncore currently, that is how I > > do it. I import my version as "import my.package.asyncore as asyncore". > > In my asyncore module I do "import asyncore", because I override a few > > functions from the asyncore module included with python. However, if I > > were to add "my.package" to sys.path, then I wouldn't be able to "import > > asyncore" from my own asyncore module. I'd have to do some trickery with > > sys.path to take the "my.package" component out, import standard > > asyncore, readd the "my.package" component, so that other modules can > > "import asyncore" and get my version. > > > > Is there a way to import the standard python asyncore module in this > > scenario? > > > > Thanks, > > Tro > > > > > > Are you trying to interfere with the default module on only your > machine? Just rename it. If something in the std. lib. imports > asyncore, they get yours too that way. No, I'd like it to be a generalized solution and only for this one project. I'm trying to get it to work on any recent python installation out of the box, so I can't rename built-in modules. What I'm trying to do is allow a 3rd party module (tlslite) to import *my* version of asyncore without me going into tlslite's code and changing its import statement explicitly, but only for the scope of this one project. Thanks, Tro From pianomaestro at gmail.com Thu Mar 27 17:35:48 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Thu, 27 Mar 2008 14:35:48 -0700 (PDT) Subject: extension module initialization called twice Message-ID: <9d8ea768-4c19-497b-a043-74fd42e5dc7d@s37g2000prg.googlegroups.com> I have a cython extension module "mux" where the initialization is being called more than once (the initmux c function). I am wondering if my use of multiple threads causes this. Can't multiple threads share the same python module ? The threads are being created from an external C library. I just call PyEval_InitThreads on startup, and then acquire the gil from the c callbacks. Here is my gdb session: (gdb) break initmux Breakpoint 1 (initmux) pending. (gdb) break PyEval_InitThreads Breakpoint 2 at 0x80c2906 (gdb) run prod-foo.py Starting program: /usr/bin/python prod-foo.py (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [Thread debugging using libthread_db enabled] [New Thread -1210001216 (LWP 11155)] (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [Switching to Thread -1210001216 (LWP 11155)] Breakpoint 2, 0x080c2906 in PyEval_InitThreads () (gdb) c Continuing. Breakpoint 3 at 0xb787c919: file mux.c, line 6829. Pending breakpoint "initmux" resolved Breakpoint 3, initmux () at mux.c:6829 6829 __pyx_m = Py_InitModule4("mux", __pyx_methods, 0, 0, PYTHON_API_VERSION); (gdb) c Continuing. [New Thread -1419904112 (LWP 11158)] [New Thread -1420432496 (LWP 11159)] [New Thread -1420960880 (LWP 11160)] [New Thread -1421489264 (LWP 11161)] [New Thread -1422017648 (LWP 11162)] [New Thread -1422546032 (LWP 11163)] [New Thread -1424647280 (LWP 11164)] Breakpoint 3, initmux () at mux.c:6829 6829 __pyx_m = Py_InitModule4("mux", __pyx_methods, 0, 0, PYTHON_API_VERSION); (gdb) Simon. From ptmcg at austin.rr.com Sun Mar 2 11:53:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 Mar 2008 08:53:47 -0800 (PST) Subject: Python-based regular expression parser that allows patterns to call functions? References: Message-ID: On Mar 2, 8:41?am, Andrew Warkentin wrote: > I am writing a filtering HTTP proxy (the site ishttp://xuproxy.sourceforge.net/). I want it to be compatible with > Proxomitron (http://proxomitron.info/) filters. I need a regular > expression parser that allows patterns to call functions (or more > likely, class methods), to implement "matching commands" (look at the > Proxmitron documentation to see what I mean). Does anyone know if such a > library exists for Python, or do I have to write my own parser? Andrew - Pyparsing allows you to define parse actions that get called when element within a grammar are matched. These actions can update external data structures, modify the matched text, or can be used to provide additional semantic validation. Here's an example: from pyparsing import * integer = Regex(r"\b\d+\b") # could also be written as #~ integer = WordStart() + Word(nums) + WordEnd() # convert matched text to actual integer def cvt_to_int (tokens): return int(tokens[0]) # only accept integers < 100 def must_be_less_than_100(tokens): if (tokens[0]) >= 100: raise ParseException("only integers < 100 are allowed") # add value to running tally of matches def increment_tally(tokens): global running_total running_total += tokens[0] integer.setParseAction( cvt_to_int) integer.addParseAction( must_be_less_than_100 ) integer.addParseAction( increment_tally ) # could also be written as #~ integer.setParseAction( cvt_to_int, #~ must_be_less_than_100, #~ increment_tally ) running_total = 0 print integer.searchString("absdlkj 1 5 12 121 78 22") print running_total Prints: [[1], [5], [12], [78], [22]] 118 More info about pyparsing at http://pyparsing.wikispaces.com, plus more examples, and links to other doc sources. -- Paul From bearophileHUGS at lycos.com Sun Mar 23 21:42:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 23 Mar 2008 18:42:48 -0700 (PDT) Subject: On copying arrays References: Message-ID: <970005df-41e6-4867-acc7-b0bda1da0db0@f63g2000hsf.googlegroups.com> ernesto: best = list(test) may be faster than: best = [x for x in test] Bye, bearophile From bayer.justin at googlemail.com Wed Mar 26 15:39:25 2008 From: bayer.justin at googlemail.com (Justin S Bayer) Date: Wed, 26 Mar 2008 12:39:25 -0700 (PDT) Subject: distutils crashing: $MACOSX_DEPLOYMENT_TARGET mismatch Message-ID: Hi group, When starting a distutils script (which I mostly consider as a black box) distutils crashes with the following traceback: Traceback (most recent call last): File "pyrexcompile.py", line 50, in cmdclass = {'build_ext': build_ext}) File "/sw/lib/python2.5/distutils/core.py", line 125, in setup dist.parse_config_files() File "/sw/lib/python2.5/distutils/dist.py", line 366, in parse_config_files filenames = self.find_config_files() File "/sw/lib/python2.5/distutils/dist.py", line 329, in find_config_files check_environ() File "/sw/lib/python2.5/distutils/util.py", line 208, in check_environ os.environ['PLAT'] = get_platform() File "/sw/lib/python2.5/distutils/util.py", line 78, in get_platform cfgvars = get_config_vars() File "/sw/lib/python2.5/distutils/sysconfig.py", line 493, in get_config_vars func() File "/sw/lib/python2.5/distutils/sysconfig.py", line 378, in _init_posix raise DistutilsPlatformError(my_msg) distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now "10.3" but "10.5" during configure The script is used to trigger pyrex compilation. I am using Pyrex 0.9.6.4. I set the environment variable to 10.5 manually from the bash. I also hacked the distutils script and manually set it in os.environ to 10.5. Googling for the error message did not help a lot, either. I am running Mac OS X 10.5 on an Intel processor. I have distutils verison 2.5.1 running on a Python 2.5.2 installed via fink. Any help would be greatly appreciated! Regards, -Justin From __peter__ at web.de Fri Mar 7 03:02:55 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Mar 2008 09:02:55 +0100 Subject: the problem of import module References: <8db5d6fa-f582-4311-817d-17da26846a57@d21g2000prf.googlegroups.com> Message-ID: fts2012 at gmail.com wrote: > follow the dive into python > ----------------------------------------------------------------- >>>> import sys >>>> sys.path >>>> sys.path.append('E \achieve\book\diveintopython-pdfzh-cn-5.4b\diveintopythonzh-cn-5.4b\py') > ----------------------------------------------------------------- > I append the filepath of <>'s examples into > sys.path,but > ----------------------------------------------------------------- >>>> sys.path > ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', > 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat- > win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\ > \site-packages', 'E:\x07chieve\x08ook\\diveintopython-pdfzh-cn-5.4b\ > \diveintopythonzh-cn-5.4b\\py'] >>>> import fileinfo#fileinfo is a module in the path > > Traceback (most recent call last): > File "", line 1, in > import fileinfo > ImportError: No module named fileinfo > > ----------------------------------------------------------------- > Can anyone tell me the reason of the above and how to add paths to > python path except adding them in the enviroment path. > Thanks. The path you append to sys.path is not properly escaped: >>> "E:\archive" 'E:\x07rchive' # \a has become the single character chr(7) Use double backslashes or raw strings instead: >>> "E:\\archive" 'E:\\archive' >>> r"E:\archive" 'E:\\archive' When you print it the extra backslash will be gone: >>> print "E:\\archive" # \\ is the escape sequence for the backslash E:\archive Peter From mh at pixar.com Wed Mar 12 00:52:57 2008 From: mh at pixar.com (mh at pixar.com) Date: Wed, 12 Mar 2008 04:52:57 GMT Subject: best way to have enum-like identifiers? Message-ID: I currently have a 2-dim hash, indexed by two strings: template['py']['funcpre'] template['py']['funcpost'] ... but I would prefer to have these indexed by constants of some kind, since this seems a bit more natural: template[py][funcpre] template[py][funcpost] ... Currently I'm just putting this at the top of the file: py=1 funcpre=2 funcpost=3 ... but I'm curious if there's a better way of doing this, some kind of enum-like thing or somesuch. Many TIA! Mark -- Mark Harrison Pixar Animation Studios From andre.roberge at gmail.com Sat Mar 22 15:04:08 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 22 Mar 2008 12:04:08 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 3:48 pm, Arnaud Delobelle wrote: > jmDesktop writes: > > For students 9th - 12th grade, with at least Algebra I. Do you think > > Python is a good first programming language for someone with zero > > programming experience? Using Linux and Python for first exposure to > > programming languages and principles. > > I'm not from the US and I'm not sure what 9th/12th grade are, but if > you want to use programming to explore maths, er I mean math, have a > look at the sage project: > 9th grade roughly corresponds to 3e coll?ge and 10th/12th grade roughly correspond to the first three years of "le lyc?e" - although from my past teaching experience (as a physicist) in French, I have concluded that mathematics is taught at a higher level in France than it is in North America - simply looking at the various books available on given topics. > http://www.sagemath.org/ Sage is great. However, I think it is much too advanced for 9th/12th grade. Furthermore, the OP was looking for suggestion teaching *programming*, not math. Andr? > > -- > Arnaud From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 13:18:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 18:18:37 +0100 Subject: singleton decorator In-Reply-To: <1983c7ec-a7da-4fae-97a9-4f22cc2ea4c7@d4g2000prg.googlegroups.com> References: <1983c7ec-a7da-4fae-97a9-4f22cc2ea4c7@d4g2000prg.googlegroups.com> Message-ID: <47ebd6e4$0$19836$426a74cc@news.free.fr> r.grimm at science-computing.de a ?crit : > Hallo, > playing with the decorators from PEP 318 I found the elegant singleton > decorator. > > def singleton(cls): > instances = {} > def getinstance(): > if cls not in instances: > instances[cls] = cls() > return instances[cls] > return getinstance > > @singleton > class A: pass > (snip) > But I always get a syntax error declaring class A as singleton. > >>>> reload ( decorator) > Traceback (most recent call last): > File "", line 1, in ? > File "decorator.py", line 27 > class A: pass > ^ > SyntaxError: invalid syntax > > What's the problem with this code because it's only copied for the PEP > 318? > It doesn't work with python 2.4 and python 2.5. A pep is a proposal, not a feature documentation. As written in pep318, class decorators have not been implemented so far. They'll be implemented in 2.6 (more exactly: they are implemented in 2.6, but 2.6 is still alpha so far). From hgk at ieee.org Wed Mar 19 09:52:07 2008 From: hgk at ieee.org (=?ISO-8859-1?Q?Hans_Georg_Krauth=E4user?=) Date: Wed, 19 Mar 2008 06:52:07 -0700 (PDT) Subject: Speaking Text References: Message-ID: <18b17c14-717d-4cc6-b4e3-40157c9a7c0b@m34g2000hsc.googlegroups.com> On 19 Mrz., 13:41, David C. Ullrich wrote: > Mac OS X has text-to-speech built into the interface. > So there must be a way to access that from the command > line as well - in fact the first thing I tried worked: > > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? > (If it's there in Linux presumably it only works if there > happens to be a speech engine available...) > > David C. Ullrich In Windows -> pyTTS http://www.mindtrove.info/articles/pytts.html Regards Hans Georg From musiccomposition at gmail.com Mon Mar 3 23:01:33 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 3 Mar 2008 20:01:33 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > What are metaclasses? Depends on whether you want to be confused or not. If you do, look at this old but still head bursting essay: http://www.python.org/doc/essays/metaclasses/. Basically, the metaclass of a (new-style) class is responsible for creating the class. This means when Python sees class Foo(object): __metaclass__ = FooMeta class FooMeta(type): def __new__(cls, name, bases, dct): #do something cool to the class pass It asks FooMeta to create the class Foo. Metaclasses always extend type because type is the default metaclass. From gagsl-py2 at yahoo.com.ar Mon Mar 3 19:14:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 22:14:33 -0200 Subject: Import, how to change sys.path on Windows, and module naming? References: <820d6ac9-041a-4d8a-a444-d2978ad41ba4@p25g2000hsf.googlegroups.com> <300f1fa1-2e64-41b1-b8f3-aad87b9e6785@n58g2000hsf.googlegroups.com> Message-ID: En Mon, 03 Mar 2008 14:39:20 -0200, escribi?: > On 3 Mar, 17:12, bock... at virgilio.it wrote: > > Oops... I tried removing python25.zip from sys.path, and I can still > import packages from zip files ... Yes, python25.zip is in sys.path by default, not to enable zipimport (which is enabled by default, if zlib is available), but to allow the entire Python library to be distributed in a .zip When Python starts, it imports site.py (and a *lot* of other modules, too much for my taste); that script is responsible of building sys.path, adding lib/site-packages and looking for .pth files and so. Before that, sys.path contains a minimal set of dirs. If there were no .zip already in sys.path, site.py (and all the modules it uses) should exist on an actual directory already present on sys.path in order to be imported - so the entire library could not reside on a zip file. Having python25.zip in sys.path by default (*before* processing site.py) allows to distribute the whole std library (and possibly other packages too) in a single zip file. -- Gabriel Genellina From Afro.Systems at gmail.com Mon Mar 24 14:22:43 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 24 Mar 2008 11:22:43 -0700 (PDT) Subject: behavior varied between empty string '' and empty list [] Message-ID: <1d822b31-fd7a-47f2-abee-45226c6b0c26@e6g2000prf.googlegroups.com> while I can invoke methods of empty string '' right in typing (''.join(), etc.) I can't do the same with empty list example: >>> a = [1,2,3] >>> b = [].extend(a) >>> b >>> b = [] >>> b.extend(a) >>> b [1,2,3] I would not use b = a since I don't want changes on 'b' to apply on 'a' do you think this should be available on lists to invoke method directly? From mwilson at the-wire.com Sun Mar 2 07:25:18 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 02 Mar 2008 07:25:18 -0500 Subject: sqlite3 adaptors mystery References: Message-ID: Matej Cepl wrote: > Thanks for your help, but plain-text strings is not what > I wanted. The boolean variables was what I was after. See this > modified version of the script: > > #!/usr/bin/python > import sqlite3 > def adapt_boolean(bol): > if bol: > return "True" > else: > return "False" > > def convert_boolean(bolStr): > if str(bolStr) == "True": > return bool(True) > elif str(bolStr) == "False": > return bool(False) > else: > raise ValueError, "Unknown value of bool attribute > '%s'" % bolStr > > sqlite3.register_adapter(bool,adapt_boolean) > sqlite3.register_converter("boolean",convert_boolean) > > db = sqlite3.connect(":memory:") > cur=db.cursor() > cur.execute("create table test(p boolean)") > p=False > cur.execute("insert into test(p) values (?)", (p,)) > p=True > cur.execute("insert into test(p) values (?)", (p,)) > cur.execute("select p from test") > for (field,) in cur.fetchall(): > print field,type(field) > > The output here is: > > [matej at viklef dumpBugzilla]$ python testAdaptors.py False 'unicode'> > True > [matej at viklef dumpBugzilla]$ > > I thought that converter is there for just exactly this -- that > I would get back bool values not strings. > > Sorry for not being clear in the first run. Sorry about the misunderstanding. It seems you want db = sqlite3.connect("test.db", detect_types=sqlite3.PARSE_DECLTYPES) After this, the print shows False True Mel. From michael at stroeder.com Wed Mar 26 13:54:29 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Mar 2008 18:54:29 +0100 Subject: Some notes on a high-performance Python application. In-Reply-To: References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: >> ... >> >> Using MySQL as a queueing engine across multiple servers is unusual, >> but it works well. It has the nice feature that the queue ordering >> can be anything you can write in a SELECT statement. So we put "fair >> queueing" in the rating scheduler; multiple requests from the same IP >> address compete with each other, not with those from other IP addresses. >> So no one site can use up all the rating capacity. >> ... >> Does anyone else architect their systems like this? > > A Xen(tm) management system I've written at least shares this aspect in that > the RPC subsystem for communication between the frontend and the backends is > basically a (MySQL) database table which is regularily queried by all > backends that work on VHosts to change the state (in the form of a command) > according to what the user specifies in the (Web-)UI. I see nothing unusual with this: I vaguely remember that this database approach was teached at my former university as a basic mechanism for distributed systems at least since 1992, but I'd guess much longer... And in one of my projects a RDBMS-based queue was used for a PKI registration server (e.g. for handling the outbound CMP queue). IIRC Microsoft's Biztalk Server also stores inbound and outbound queues in its internal MS-SQL database (which then can be the bottleneck). Ciao, Michael. From forwardshortleg at gmail.com Wed Mar 5 20:08:38 2008 From: forwardshortleg at gmail.com (forwardshortleg at gmail.com) Date: Wed, 5 Mar 2008 17:08:38 -0800 (PST) Subject: Returning a byte buffer from C extension References: Message-ID: <9f3e185c-1328-47f8-b363-7efd895ee629@60g2000hsy.googlegroups.com> I just realized that I could do this as follows: static PyObject* GetByteBuffer(PyObject* self, PyObject* args) { char byteBuffer[100]; // do something to fill byteBuffer with values. return Py_BuildValue("s#", byteBuffer, numberOfBytesToReturn); } Sorry for the unnecessary distraction. Eknath On Mar 5, 4:42 pm, forwardshort... at gmail.com wrote: > Hello, > > I am new to Python programming. So, kindly excuse me if I don't use > correct terminology here below. > > I am trying to write an extension function that returns an array of > bytes as shown in the example below: > > static PyObject* GetByteBuffer(PyObject* self, PyObject* args) > { > char byteBuffer[100]; > > // do something to fill byteBuffer with values. > > return Py_BuildValue("y", byteBuffer); > > } > > Is this valid? I get a run time error in Python 2.5 (actually 2.6) and > Python 3.0 returns null terminated byte string. > My byte buffer may contain one or more zeros and I want is the entire > buffer regardless of its contents. How do I do it? > > Thanks, > > Eknath > > P.S: I know that 2.6 & 3.0 are not meant for a newcomers like me. > Unfortunately 2.5.2 and older for windows are built using MSCVC 6.0 > and they pose problems building extensions. From peanut.sam at googlemail.com Thu Mar 6 03:58:15 2008 From: peanut.sam at googlemail.com (Sam Garson) Date: Thu, 6 Mar 2008 08:58:15 +0000 Subject: Why """, not '''? In-Reply-To: <880dece00803052311p181c753cx9ae8338e954f9290@mail.gmail.com> References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> <880dece00803052311p181c753cx9ae8338e954f9290@mail.gmail.com> Message-ID: <4e1ac4910803060058k7657b1b0q2e9214b3e68cab8f@mail.gmail.com> The """ is for the docstring - if you need the user to know what theyre doing with the program you can create documentation, and what you put in those quotes wwill come up in that (I think) On 3/6/08, Dotan Cohen wrote: > > On 06/03/2008, Dan Bishop wrote: > > On Mar 5, 7:24 pm, Matt Nordhoff wrote: > > > > > Steven D'Aprano wrote: > > > > Surely it would depend on the type of text: pick up any random > English > > > > novel containing dialogue, and you're likely to find a couple of > dozen > > > > pairs of quotation marks per page, against a few apostrophes. > > > > > > > > That's an idea... Write a novel in Python docstrings. > > > > > > Or better yet, write in Python syntax. > > > > > > assert len([man for man in now_alive() if > > man.remembers(datetime.date(1775, 4, 18))]) <= HARDLY > > > > lantern_count = {'land': 1, 'sea': 2}.get(british.location(), 0) > > n_ch_twr.hang(Lantern() for _ in xrange(lantern_count)) > > > > if lantern_count: > > for village in middlesex: > > ride_thru(village) > > spread_alarm(village) > > > > That looks ported from lolcode. > http://lolcode.com/ > > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > -- > http://mail.python.org/mailman/listinfo/python-list -- I like kids, but I don't think I could eat a whole one... -------------- next part -------------- An HTML attachment was scrubbed... URL: From xu.mathena at gmail.com Mon Mar 24 00:26:59 2008 From: xu.mathena at gmail.com (NotGuru) Date: Sun, 23 Mar 2008 21:26:59 -0700 (PDT) Subject: always getting 'None' return value from PyObject_CallObject References: Message-ID: On Mar 23, 6:43?pm, Gal Aviel wrote: > Hello all, > > Kinda desperate over here .. Any help would be greatly appreciated ! > > I'm trying to embed a Python interpreter inside a Verilog simulator as a > SystemVerilog DPI application. The python side implements a few SV exported > tasks. I've got a thin C shared library as the dpi app; all it does it get the > task arguments from the simulator and hand those to the Python side using the > Python C API. > > I followed '5.3 Pure Embedding' under Python 2.5 documentation very closely. > > When calling a function defined in my module, the function executes Ok - it sees > the correct arguments being passed from C, and executes 100% - only the return > value is always 'None' (I tried returning a simple integer like '5' which > doesn't work). > I met similar problems before and I guess you can try to start from a minimum version that f takes no arguments. If your can't pass the right argument to f, it will always return none without any prompt. From castironpi at gmail.com Fri Mar 21 02:18:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:18:34 -0700 (PDT) Subject: seek into file-like for ipc Message-ID: <85a349dd-226f-423a-ae6d-742e013b816a@n58g2000hsf.googlegroups.com> Hive: How about a shared-memory/file-map to a Python object? Seek and tell. Has its own GIL? Raises Exceptions? Standard C++ prohibits returning pointer-to-members. File runs in its own thread, can callback host and raise its own exceptions, iow file process. Think live persistence. Client side producer proxies / delegates to the object. Ready, Go! From ron at example.com Thu Mar 27 01:02:40 2008 From: ron at example.com (Ron Eggler) Date: Thu, 27 Mar 2008 05:02:40 GMT Subject: last mouse movment or keyboard hit References: Message-ID: azrael wrote: > You can use wxPython. Take a look on the DemoFiles that you can > download also from the site. I remember that there has been a demo of > capturing mouse coordinates and also one example about capturing Which > key has been pressed at which time. > Just start the time, count the interactions of key strokes and mouse > gestures. Apply some statistics and voila. there it is. But that wouldn't be system wide, would it? :o > On Mar 26, 3:28?pm, Ron Eggler wrote: >> Gabriel Genellina wrote: >> > En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler >> > escribi?: >> >> >> I would like to get the time of the most recent human activity like a >> >> cursor >> >> movement or a key hit. >> >> Does anyone know how I can get this back to start some action after >> >> there has been no activity for X minutes/seconds? >> >> > Which platform? On non-ancient Windows versions, you can periodically >> > check GetLastInputInfo >> >> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winu... >> >> No, it would be for Linux and preferrably it would work on MacOS & >> Windows as well....is there anything? >> Thanks! >> -- >> chEErs roN -- chEErs roN From dickinsm at gmail.com Sat Mar 8 11:34:27 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 08:34:27 -0800 (PST) Subject: float / rounding question References: <13t456cmgfpdhbc@corp.supernews.com> Message-ID: On Mar 7, 11:23?pm, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote: > > Sorry to come in so late in this discussion. Although it is correct to > > say that many real numbers that have an exact decimal representation > > cannot be exactly represented in binary, that is no excuse to print 53.6 > > as 53.600000000000001. This is just lousy printing and the fact that > > this kind of question comes up every week shows that it is confusing to > > many people. > > Good. That's a feature, not a bug. Even so, it's not clear that Python's current behaviour couldn't be improved. I have a mild dislike of the lack of consistency in the following, which arises from Python arbitrarily stripping trailing zeros from the result returned by the C library functions: >>> 10.1 10.1 >>> 10.2 10.199999999999999 >>> 10.3 10.300000000000001 >>> 10.4 10.4 Piet van Oostrum's suggestion gives one nice way of dealing with this inconsistency. Unfortunately it doesn't look easy to implement this in practice: the main difficulty seems to be that to ensure float(repr(x))==x round-tripping you'd need to write routines to take control of both str -> float and float -> str conversions, not forgetting that those routines have to be reasonably fast, and work correctly on various non IEEE 754 platforms as well as the usual ones. This means adding, maintaining and testing hundreds of lines of complicated code, where right now a few C library calls suffice. Mark From darcy at druid.net Wed Mar 5 20:07:33 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 20:07:33 -0500 Subject: Please keep the full address In-Reply-To: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: <20080305200733.ba43c354.darcy@druid.net> On Wed, 5 Mar 2008 14:00:17 -0800 (PST) Mike Driscoll wrote: > What are you talking about? I didn't change the address at all. I'm > not even sure what you mean. Are you talking about the post subject > line (which I have never touched in any post)? If you're talking about > the OP's email address, that's Google's fault for cropping them. I'm talking about castironpi. I find his posts a waste of my time so I have them filtered out along with a few others and I also filter out responses by searching for his address in the body so changing it defeats that. However, if it is something that you have no control over I apologize for the noise. -- 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 pharmapsychotic at gmail.com Tue Mar 25 16:22:55 2008 From: pharmapsychotic at gmail.com (blackpawn) Date: Tue, 25 Mar 2008 13:22:55 -0700 (PDT) Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: > Does the Noddy example use GC (Py_TPFLAGS_HAVE_GC)? Container objects > must use the cycle GC or circular referneces aren't broken. Have you > tried calling PyGC_Collect() multiple times? Yeah the Noddy example is from "2.1.3 Supporting cyclic garbage collection" part of the Python docs. They list sample C and Python code which I cut and pasted with no changes and on Py_Finalize and app shut down it leaks the object. I know the garbage collector is tracking the object because it properly calls the traverse function but for whatever reason it never calls the clear function. Does anyone have experience with circular references and had success with it or the example in the docs? From castironpi at gmail.com Sat Mar 15 10:57:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 07:57:51 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: <9dd9167c-6d7c-4b48-b371-2bc7a4bc3722@p25g2000hsf.googlegroups.com> On Mar 15, 4:56?am, Arnaud Delobelle wrote: > On Mar 15, 5:47?am, Tim Roberts wrote: > > > > > > > Jeff Schwab wrote: > > >Roel Schroeven wrote: > > >> castiro... at gmail.com schreef: > > >>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: > > >>>>> Subject: RIP: Joseph Weizenbaum > > >>>>> Creator of Eliza: > > >>>>>http://www-tech.mit.edu/V128/N12/weizenbaum.html > > > >>>> How do you feel about creator of Eliza? > > > >>> What is Eliza? > > > >> Does that question interest you? > > > >Well played, sir. > > > >Earlier you said what is Eliza. ?Do you still feel that way? > > > I am embarrassed to say that this vaguely disrespectful exchange made me > > laugh out loud. > > Does it bother you that this vaguely disrespectful exchange made you > laugh out loud? No more than funerals, really, and weddings and birthday parties are kind of suspect too; I'm torn. How do you feel about them? From rui.maciel at gmail.com Mon Mar 31 12:40:40 2008 From: rui.maciel at gmail.com (Rui Maciel) Date: Mon, 31 Mar 2008 17:40:40 +0100 Subject: Is this a good time to start learning python? Message-ID: <47f1140e$0$735$a729d347@news.telepac.pt> Recently I woke up inclined to take up the task of learning another programming language. I've already dipped my toes in Perl (I've read online tutorials and wrote a couple of irrelevant pet projects) but, as the computers at my workplace only sport the python interpreter, it probably means that learning python will end up serving me better, at least in the short run. Plus, you know how Perl goes. So far the decision seems to be a no brainer. Yet, Python 3000 will arrive in a few months. As it isn't backwards compatible with today's Python, there is the risk that no matter what I learn until then, I will end up having to re-learn at least a considerable part of the language. To put it in other words, I fear that I will be wasting my time. At least that is what a clueless newbie believes. As this group is frequented by people who have more insight into all things pythonesque, what are your thoughts on this? Thanks for the help Rui Maciel From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 08:54:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 12:54:05 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: <13t7nfdmdtuf7be@corp.supernews.com> On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote: > (3) Informing codes above it about what's currently happening inside, > the thing is just a mundane report that might be useful to codes above > > Which might be a useful place to use SoftExceptions Okay, now we're getting somewhere. So, I have a function foo() which raises a HardException on error, but it also raises a SoftException if it wants to notify me of something "mundane". def foo(sequence): if args == []: raise SoftException("empty list") return len(args) Now, how do I use that? try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" print x Am I close? But there's a problem. Once the SoftException is caught, execution will continue from the line "print x" -- but the function foo() never got a chance to actually return a result! In order to make that work, you would need a significant change to Python's internals. I don't know how difficult that would be, but I'm guess that it would be a lot of work for not much benefit. But even if that happened, it would mean that the one mechanism has TWO different effects: try: x = foo(sequence) except SoftException: print x # this is okay, because foo() did return except TypeError: print x # this is NOT okay, because foo() never returned That is a recipe for confusion. [...] > No, you're misunderstanding the purpose of Soft Exception, it's not for > silencing errors and not so much for exceptional cases. It's for the > more mundane tasks such as: [...] > Perhaps relabeling it as Warning, and renaming raise SoftException as > give Warning might make it more acceptable? Do you realise that Python already has a warnings module? > And I agree that the > probability for misuse is quite high, but the benefits is also quite > high, it's just that you can't see it since you're not used to using > such exceptions. The benefit of SoftExceptions lies mostly on the > regular programmings tasks, not the exceptional programming tasks > > Practical Example: > This example takes _case ideas_ from this simple gravity simulator > http://www.pygame.org/project/617/ BUT _no line of code is taken from > it_. I only give this link so you can easily know what the case is about > without lengthy explanation. > > A particle machine. > The particle machine calculates gravity created by the particles in a > field. Additionaly, it clumps together two particles that happens to be > near enough (less than the sum of their radiuses). > > The force two particle is expressing to each other is calculated with: > def calculateforce(P1, P2): > return (P1.mass - P2.mass) / distance(P1, P2) > > and this is done to every particle in the field against the current > particle. > > And the distance is calculated by: > def distance(P1, P2) > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > The problem happens when the distance is small enough and we want to > clump them together. > > A possible solution to this problem might be to check whether distance > is less than P1.radius + P2.radius in the calculateforce. But, this > obfuscate the code since we have to separate distance calculation from > the main formula (see !s), I don't agree that this obfuscates the code. > and this also insist that clumping be done on > force calculation level (see @s), shortly this piece of code is plain > bad: > def distance(P1, P2): > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > def calculateforce(P1, P2): > ## Separating this dist calculation into its own line is > ## necessary if we want to check the value of dist > ## Personally I think that's a bit obfuscated. > ## Well known formulas should be kept to one line if possible > ! dist = distance(P1, P2) > > if dist <= P1.radius + P2.radius: > ## Calling clump() here is bad, because > ## there are occasions where we only want to > ## calculate force but doesn't want to > ## clump it > @ clump(P1, P2) > else: > ! return (P1.mass - P2.mass) / dist I agree that calling clump() there is bad. > ## Codes calling calculateforce() > # Note: this code is located inside a loop > > F = calculateforce(P1, P2) > # Do something else, acceleration calculation, movement > calculations, etc > > > A better refactoring would be like this, but this requires calculating > distance twice (see !s): That's not better. Don't do it. > def distance(P1, P2): > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > def calculateforce(P1, P2): > ## Here distance is calculated once > ! return (P1.mass - P2.mass) / distance(P1, P2) > > ## Codes calling calculateforce() > # Note: this code is located inside a loop > > ## Here distance is calculated again > ! if distance(P1, P2) <= P1.radius + P2.radius: > clump(P1, P2) > break > F = calculateforce(P1, P2) > # Do something else, acceleration calculation, movement > calculations, etc And here's a way to do it that doesn't calculate anything twice, and doesn't require any exceptions: def calculateforce(P1, P2, dist): return (P1.mass - P2.mass)/dist And then for all pairs of particles: dist = distance(P1, P2) if dist <= P1.radius + P2.radius: clump(P1, P2) break F = calculateforce(P1, P2, dist) > A much better solution would be to use SoftException > def distance(P1, P2): > D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > if D <= P1.radius + P2.radius: > raise Collision > return D But look at that line, "raise Collision". You could replace that with a callback function, and have the same result: DO_NOTHING = lambda : None def distance(P1, P2, callback=DO_NOTHING): D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 if D <= P1.radius + P2.radius: callback() return D That gives you virtually everything you want. If you want to ignore the signal, you simply call distance(P1, P2). If you want to do something on the signal, you set the callback. But frankly, the function distance() is NOT the place for that. Why should the distance() function decide what's a special result and what isn't? With your plan, you end up with functions like this: def distance(P1, P2): D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 if D <= P1.radius + P2.radius: raise Collision elif D > 1000: raise FredsModuleEscape elif D <= 1: raise MagnetismModuleUnity elif D == 0: raise AnotherFunctionSingularity elif ... ... ... else: raise NothingSpecialHappened return D Every module and function that calls distance() will start demanding that it raises the SoftExceptions that *it* wants, and before you know it, your distance() function has a hundred SoftExceptions covering all sorts of things that most people don't care about. No. This is a terrible idea. If the caller wants to treat a particular result as special, the caller should be responsible for detecting that, not the callee. > This results in a cleaner code. I don't agree. > And it also allow _other part of codes_ > that uses calculate distance and force to easily ignore or handle the > Collision Exception. And demand their own SoftExceptions. Okay, now that I understand your intention better, I've gone from -1 to -2 on the idea. I no longer think it's a bad idea, I think it's a TERRIBLE idea. Just out of curiosity, are there any existing languages that do something like this, or did you invent it yourself? -- Steven From castironpi at gmail.com Sun Mar 30 05:56:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 02:56:59 -0700 (PDT) Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> <23908024-8174-4c3d-9d0d-70765834a331@s37g2000prg.googlegroups.com> Message-ID: On Mar 27, 4:22?pm, Miki wrote: > Hello Tim, > > > that looks nice, simple, and intuitive. thanks for thinking about it. > > Thanks, glad I could help. > > > Now to dive into some gui coding! > > IMO you can pull it off as a web application and then you won't need > to worry about cross-platform, > upgrades and all that interesting stuff. > Chapter 1 (001-200 200) > Chapter 2 (200-300 100) > ------ 001-300 300 ---- Does anyone want to see it under a graphics layer? From deets at nospam.web.de Sun Mar 30 08:36:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Mar 2008 14:36:01 +0200 Subject: problem with logic in reading a binary file In-Reply-To: References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> <659f2cF2dq5riU1@mid.uni-berlin.de> Message-ID: <659fpiF2f1e1hU1@mid.uni-berlin.de> > > Whatever you say. Can't express what your approval means to me! Diez From aahz at pythoncraft.com Thu Mar 6 16:24:47 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Mar 2008 13:24:47 -0800 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: In article <13sulsu4nbr2199 at corp.supernews.com>, Steven D'Aprano wrote: > >I accept my question about classes being singletons is not well-formed, >not even in my own mind. I guess one way of asking is, for any two class >objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? Even that stricture fails under the presence of metaclasses. ;-) But answering your real question, I don't remember off-hand the required sequence, but it is possible to import a class two different ways such that the classes are not the object. This can cause problems with e.g. pickle. Within a single module, given a class defined only once within that module, the class will be a singleton. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From sean at ardishealth.com Mon Mar 17 09:46:13 2008 From: sean at ardishealth.com (Sean Allen) Date: Mon, 17 Mar 2008 09:46:13 -0400 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: <319A6E0F-3517-4BFB-82A3-4577882765FC@ardishealth.com> On Mar 17, 2008, at 3:21 AM, Pradeep Rai wrote: > Thanks for your inputs !!! > > I have installed python v 2.5 on my Linux machine and executing the > tool again. > > I would like to share the memory status( using free -m command ) > before and after the execution of the tool. > > BEFORE EXECUTION > ================ > > total used free shared > buffers cached > Mem: 1006 148 858 0 > 8 92 > -/+ buffers/cache: 46 960 > Swap: 2047 0 2047 > > > AFTER EXECUTION > =============== > total used free shared > buffers cached > Mem: 1006 940 66 0 > 49 846 > -/+ buffers/cache: 44 962 > Swap: 2047 0 2047 > > > I am unable to find out why 66 MB system memory is left after tool > execution ? If python does not have memory leaks then where this > memory is going ? > the free you are looking at is not a good indication of 'actual memory available' in linux. the number you are intersted is this one: > -/+ buffers/cache: 46 960 vs > -/+ buffers/cache: 44 962 before execution you had 960 available for use by applications after execution you had 962 available. here is one of many pages explaining memory under linux: http://gentoo-wiki.com/FAQ_Linux_Memory_Management -------------- next part -------------- An HTML attachment was scrubbed... URL: From pydecker at gmail.com Sun Mar 2 09:47:17 2008 From: pydecker at gmail.com (Peter Decker) Date: Sun, 2 Mar 2008 08:47:17 -0600 Subject: Where's GUI for Python? In-Reply-To: References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: On Sat, Mar 1, 2008 at 10:04 PM, Bill wrote: > You should also take a look at wxGlade: > > http://wxglade.sourceforge.net/ > > which sits on top of wxPython: > > http://wxpython.org/ > > which wraps wxWidgets: > > http://www.wxwindows.org/ I have used wxGlade, and while it worked well enough, it didn't seem to fit my brain. I always found myself "thinking backwards" in order to guess how the tool needed me to do things. > I've found that wxGlade is more usable, currently, than Dabo in it's > visual layout tools that help you create the GUI for your apps. I didn't like that wxGlade generated code. If I later edited the code, I could no longer use wxGlade to refine the design. I've been amazed that so many people actually *like* working with wxPython-style code. I always hated it, and even tried a few times to make my own wrapper to insulate me from it (it was never very good). When I found out about Dabo, I took to it instantly and got much more productive very quickly. I was certain that everyone else would respond the way that I did. Obviously that's not what happened. I think that one of the reasons is that I never coded in C++, so the ALL_CAPS_CONSTANTS style and the whole getter/setter mentality seemed foreign to me. I'm a Python programmer, and don't have to switch gears when writing UI code anymore. I think if you like the sort of code that you need to use wxPython directly, you're probably perfectly happy to code at that level. For me, though, everytime I see raw wxPython code these days I cringe, and am thankful that I don't have to deal with it anymore. -- # p.d. From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:19:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:19:34 -0300 Subject: Setting the value of one cell in QTableWidget fills everything. References: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 12:01:01 -0300, Constantly Distracted escribi?: > I've just started PyQt programming and I've run into this little > problem. When I set the text of one cell in my table, all the other > cells fill with that value. > def filltable(self): > items=QtGui.QTableWidgetItem() Here you create a *single* object named item [why not "item" instead?] > for column in range(self.mytable.columnCount()): > for row in range(self.mytable.rowCount()): > items.setText("row: " + str(row) + " column: " + > str(column)) > self.mytable.setItem(row,column,items) Here you set the *same* item all over the table. -- Gabriel Genellina From guillermo.listas at googlemail.com Sun Mar 9 09:58:15 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Sun, 9 Mar 2008 06:58:15 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> Message-ID: <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> Mamma mia! My head just exploded. I've seen the light. So you only need to ?want? to have a protocol? That's amazing... Far beyond the claim that Python is easy. You define protocols in writing basically! Even my grandma could have her own Python protocol. Okay, so I think I know where's the catch now -- you must rely on the fact that the protocol is implemented, there's no way to enforce it if you're expecting a parrot-like object. You'd try to call the speak() method and deal with the error if there's no such method? Thanks a lot! Guillermo From thehazard at gmail.com Fri Mar 7 02:22:56 2008 From: thehazard at gmail.com (Daniel Bonekeeper) Date: Fri, 7 Mar 2008 04:22:56 -0300 Subject: Python GDB Wrapper In-Reply-To: References: Message-ID: On Fri, Mar 7, 2008 at 4:01 AM, Raja wrote: > Hi, > I am trying to develop a a GDB wrapper script in python which is > able to extract a stack trace and all relevant data. > > Has anyone does this before ? Even some basic idea or code as to how > to proceed would be great. > > Thanks, > Raja. > -- > http://mail.python.org/mailman/listinfo/python-list > You mean extract the information from core dump files that gdb interprets ? Check out stuff like ELF, Dwarf 3 (http://dwarf.freestandards.org/) and gdb sources. -- What this world needs is a good five-dollar plasma weapon. From gregory.bronner at lehman.com Fri Mar 7 09:44:46 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 7 Mar 2008 09:44:46 -0500 Subject: Edit and continue for debugging? Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2973@nypcmg1exms318.leh.lbcorp.lehman.com> I haven't seen much on this for a few years: I'm working on a GUI application that has lots of callbacks. Testing it is very slow and quite boring, as every time I find an error, I have to exit it, restart it, and repeat the series of clicks. It would be really amazing if python supported a reasonable form of edit and continue. Is there any way to do this? I'd like to be able to change my code and have it apply to a running instance of a class. I wonder if it would be possible to do this by configuring the interpreter to parse classes and functions rather than whole modules, and to re-parse as necessary; also to have byte-compiled modules be singletons rather than be standard reference counted objects. Thanks Gregory R. Bronner (212) 526-0102 gregory.bronner at lehman.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From ark at acm.org Mon Mar 10 10:29:48 2008 From: ark at acm.org (Andrew Koenig) Date: Mon, 10 Mar 2008 14:29:48 GMT Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: >> if type(a) is dict: >> print "a is a dictionnary!" > class MyDict(dict): > pass > a = MyDict() > type(a) is dict > => False isinstance(a, dict) => True So the question you need to answer is whether you want to determine whether an object is exactly of type dict, or whether it you are willing to accept types derived from dict also. From Bryan.Fodness at gmail.com Sat Mar 29 14:44:55 2008 From: Bryan.Fodness at gmail.com (Bryan.Fodness at gmail.com) Date: Sat, 29 Mar 2008 11:44:55 -0700 (PDT) Subject: problem with logic in reading a binary file Message-ID: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Hello, I am having trouble writing the code to read a binary string. I would like to extract the values for use in a calculation. Any help would be great. Here is my function that takes in a string. def parseSequence(data, start): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': data = value while start < length: group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': data = value while start < length: group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = (group_num+element_num) return element, start, value else: return element, start, value else: return element, pos, value And, here is a sample string (I have split up and indented for readability). There is an identifier (\xfe\xff\x00\xe0) followed by the length of the nested values. '\xfe\xff\x00\xe0\x18\x02\x00\x00 -length=536 \n0q\x00\x02\x00\x00\x001 \n0x\x00\x02\x00\x00\x0010 \n0\x80\x00\x02\x00\x00\x004 \n0\xa0\x00\x02\x00\x00\x000 \x0c0\x04\x00\xe8\x01\x00\x00 \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 \n0\x86\x00\x10\x00\x00\x00127.378510918301 \x0c0\x06\x00\x02\x00\x00\x001 \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x0c\x00\x00\x001.629998e-1 \n0\x86\x00\x10\x00\x00\x0023.159729257873 \x0c0\x06\x00\x02\x00\x00\x004 \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x10\x00\x00\x001.26285318894435 \n0\x86\x00\x10\x00\x00\x00227.690980638769 \x0c0\x06\x00\x02\x00\x00\x003 \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x10\x00\x00\x001.52797639111557 \n0\x86\x00\x10\x00\x00\x00263.433384670643 \x0c0\x06\x00\x02\x00\x00\x002 ') From stephenhorne100 at aol.com Mon Mar 17 10:35:49 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 07:35:49 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: On Mar 17, 1:31 pm, Duncan Booth wrote: > A common explanation for this is that lists are for homogenous > collections, tuples are for when you have heterogenous collections i.e. > related but different things. I interpret this as meaning that in a data table, I should have a list of records but each record should be a tuple of fields, since the fields for a table usually have different forms whereas the records usually all have the same record layout. Makes sense, but not exactly *because* of the homogenous/heterogenous thing but rather because a record is smaller than a table, and a records component fields are more closely bound together than the records in a table. In short, adding, removing and overwriting records are essential operations (though Haskell programmers might disagree). Any modifications to records themselves can practically be handled as replacing one complete tuple with another. As a final note, I tend to implement tables as either lists of dictionaries, or lists of class instances. That way my fields are named. Its better in maintenance terms if I need to add new fields to the tables later on. From dickinsm at gmail.com Thu Mar 13 17:10:42 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 13 Mar 2008 14:10:42 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: On Mar 13, 3:48?pm, Alan Isaac wrote: > So maybe this is not as bad as I feared. ?What are some use > > cases that will clearly be harder (i.e., at least require > > a slightly elaborate wrapper) after this change? Sorting tuples, where the second item in the tuple should have the opposite ordering to the first is going to be a bit of a pain. Or even worse, where the ordering of the second item depends on the value of the first item in the tuple. For example, suppose that (for whatever contrived reason) you're representing integers in (sign, magnitude) format by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for negative) and i is a string representing the absolute value of the integer. So (0, '3') represents 3 (1, '14') represents 14 and you want to sort according to numeric value. One can certainly come up with a key that works, but it's not quite as straightforward as writing a custom __cmp__. This isn't a totally contrived example: the internal Decimal format isn't so different from this. Mark From castironpi at gmail.com Wed Mar 5 14:09:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 11:09:28 -0800 (PST) Subject: Using re module better References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> Message-ID: <1f63d5df-70e8-4eb9-81f7-7f2abb6f98b1@u10g2000prn.googlegroups.com> On Mar 5, 6:12?am, Tim Chase wrote: > > if (match = re.search('(\w+)\s*(\w+)', foo)): > > Caveat #1: ?use a raw string here > Caveat #2: ?inline assignment is verboten > > ? ?match = re.search(r'(\w+)\s*(\w*+)', foo) > ? ?if match: > > > ? ? field1 = match.group(1) > > ? ? field2 = match.group(2) > > This should then work more or less. ?However, since you know > there are two matches, you can just use > > ? ?field1, field2 = match.groups() > > If the regexp is one you plan to reuse (or call in a loop), you > can pre-compile it: > > ? ?r = re.compile(r'(\w+)\s*(\w*+)') > ? ?for thing in bunch_of_things: > ? ? ?m = r.search(thing) > ? ? ?if m: > ? ? ? ?field1, field2 = m.groups() > ? ? ? ?do_something(field1, field2) > > HTH, > > -tkc Opposed is to mimic MatchGroup that doesn't do anything, and returns from a non-match call, field1, field2 = match.groups() or [ Dummy, Dummy ], and similarly ...= [ None, None ]. On another note, why do people X, Y, and Z, including me, all hate to write a= b(); if a: a.something()? From mrstevegross at gmail.com Wed Mar 12 12:22:46 2008 From: mrstevegross at gmail.com (mrstephengross) Date: Wed, 12 Mar 2008 09:22:46 -0700 (PDT) Subject: Does __import__ require a module to have a .py suffix? Message-ID: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Hi all. I've got a python file called 'foo' (no extension). I want to be able to load it as a module, like so: m = __import__('foo') However, the interpreter tells me "No module named foo". If I rename it foo.py, I can indeed import it. Is the extension required? Is there any way to override that requirement? Thanks, --Steve From grante at visi.com Sat Mar 8 16:44:01 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 08 Mar 2008 21:44:01 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> Message-ID: <13t6251ep5bou67@corp.supernews.com> On 2008-03-08, K Viltersten wrote: >> What I really can't stand are the pointy-haired comment blocks >> at the beginnings of C/C++ functions that do things like tell >> you the name and return type of the function and list the >> names and types of the parameters. Gee, thanks. I never could >> have figured that out from looking at the source code itself. > > Coming from C++/Java camp i can't help noticing that in most > cases, when i'm using a class written by somebody else, i > don't want to see his/her code. I only want to know WHAT the > function does (is intended to be doing, at least). If you can't/don't look at the source file, then comments aren't going to help (except in the case of something like docstrings in Python). > I don't want to look at the source code (in some cases i can't > even see the code because it's compiled). I only care that > when i execute > > SomeType obj = SomeType(); > obj.aggregate(); > > the object gets aggregated. How it's done will be up to the > author. I'm just a user of the product. If you don't look at the source file, then I guess the question of whether comments are good, bad, or indifferent is irrelevent to you. > Now, i'm getting the signal that it's done in a different way > in Python. I'm not sure how you concluded that from this thread. I very rarely look at the source files for the standard library. I usually just look at the library reference document. The only times I look at the source code are the rare occasion that the function doesn't seem to be working correctly or when I can't understand what the reference docs are saying. The cases where I suspect the former generally turn out to be the latter. Comments in source code are for people maintaining the code, not for people using a standard library API (again, except for docstrings). -- Grant Edwards grante Yow! YOU PICKED KARL at MALDEN'S NOSE!! visi.com From bj_666 at gmx.net Sat Mar 15 02:03:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 06:03:45 GMT Subject: Handling global variables (Newbie) References: <613c51a0-d928-46b1-a04f-d0bc9fdcf453@a70g2000hsh.googlegroups.com> Message-ID: <641760F29qj9jU2@mid.uni-berlin.de> On Fri, 14 Mar 2008 12:19:18 -0700, MRAB wrote: > On Mar 13, 4:25 am, "David S" wrote: >> Hi, >> >> I have an error occurring at >> self.build_root = os.path.abspath(os.path.split(__file__)[0]) >> >> The error states 'NameError: global name '__file__' is not defined' >> >> In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get >> defined? >> > Do you perhaps mean '__name__'? I guess not. It makes more sense to apply path functions to `__file__` than to `__name__`. Ciao, Marc 'BlackJack' Rintsch From mnordhoff at mattnordhoff.com Mon Mar 10 03:46:30 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 07:46:30 +0000 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> Message-ID: <47D4E756.7010609@mattnordhoff.com> Paddy wrote: > After profiling their may be other ways to remove a bottleneck, such > as > using existing highly-optimised libraries such as Numpy; Psycho, an > optimising interpreter that can approach C type speeds for Python > code; > and you could create your own C++ based libraries. > > You might want to ask the Mercurial development team how they got > their > impressive speed and functionality out of using mainly Python with > critical regions in C. - Or watch this: > http://video.google.com/videoplay?docid=-7724296011317502612 For what you do decide to rewrite in C, you can also use a language like Cython [1] (which is a fork of Pyrex [2]). It looks mostly like Python, and is translated to C without you having to write all of the boilerplate Python C API stuff. Of course, not quite as efficient well-tuned raw C, but much more pleasant to write. (FWIW, Bazaar [3], another VCS written in Python similar to Mercurial, has rewritten parts of two modules in Pyrex. Another one is in raw C, because that's what was contributed.) [1] [2] [3] -- From gagsl-py2 at yahoo.com.ar Sun Mar 16 19:25:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 21:25:18 -0200 Subject: BitVector read-from-file Question References: Message-ID: En Mon, 10 Mar 2008 14:06:07 -0200, Michael Wieher escribi?: > I'm trying to read in data from large binary files using BitVector > (thanks > btw, for whoever mentioned it on the list, its nice) > > I'll be reading the data in as requested by the user, in (relatively) > small > chunks as needed. > > Problem is I can't read the whole file in at once (its ridiculously > large) > and the object created by BitVector(filename="path") doesn't include a > "seek" function (to reset the filepointer) > > Any suggestions on how to this without > closing/reopening/reading(offset)/read(data) ? (thats a lot of overhead) (I understand that you don't want to create a BitVector from the whole file, but from many segments) You could try to circumvent BitVector oddities reading the file yourself and creating BitVector objects from the parts you are interested in. -- Gabriel Genellina From rockxuan at gmail.com Tue Mar 18 03:41:24 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:41:24 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <27e5d0a8-5257-400c-9568-e140b44f32c9@s19g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From castironpi at gmail.com Sat Mar 8 15:27:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:18 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> <54abf8a6-6156-4663-903c-eb761e6b5148@h11g2000prf.googlegroups.com> Message-ID: > something something equivalence class. > The intern() builtin uses this approach: > > ? ?interned = {} > ? ?def intern(s): > ? ? ? ? if s in interned: > ? ? ? ? ? ? return interned[s] > ? ? ? ? interned[s] = s > ? ? ? ? return s If you've seen it before, and have the old one, return the old one. Do I have this straight? From jeff at schwabcenter.com Sun Mar 2 16:27:20 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 13:27:20 -0800 Subject: Book Recomendations In-Reply-To: References: Message-ID: > Ira Solomon wrote: >> I am an experienced programmer (40 years) . . . >> I'm interested in learning Python > js wrote: >> I wonder why nobody mension Python Cookbook yet . . . >> and Python Standard Library Because cookbooks are not supposed to be language introductions. They are collections of non-obvious techniques, for use by people already familiar with a core language and its standard libraries. Python in particular offers a lot for traditional programmers to wrap their minds around before considering cookbooks; Programming Python, for example, purports to help programmers think Pythonically, and probably belongs chronologically between the introductory books and the cookbooks. Many programmers coming from different languages tend (at first) to write code that makes experienced Pythonistas cringe. Effective use of the language depends on an understanding of its extremely dynamic nature, which can be tough to grasp for those of us coming from compiled language backgrounds. It seems to me, based purely on discussions seen in comp.lang.python, that even folks coming from relatively dynamic languages like Lisp often underestimate the level of run-time indirection provided by Python. One of the neat things about the Nutshell book is that it shows how even the process of resolving object attributes is potentially complicated, and how the new 'type' metaclass helps to at least make the process more consistent than with old-style objects. Experienced programmers first have to learn that an expression like "a.x" means something very different in Python from what it means elsewhere; then, they can begin leveraging these language features to do the sorts of things illustrated in the cookbooks. From mankyd at gmail.com Tue Mar 18 19:33:37 2008 From: mankyd at gmail.com (dave) Date: Tue, 18 Mar 2008 16:33:37 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> First I want to say thank you all for your timely replies. This is all good food for thought. I've been programming more many years, but fast graphics rendering is new territory for me. I'm hoping to fine something like a buffer_blit, where I can set all the pixels to change using basic operators, blit them all at once to a pixel buffer, then swap the visible buffer. Ideally it will only change the region of the pixel buffer that needs changing. Because I want layers, I would like to take advantage wherever possible of the available hardware features. I.E. ideally I am hoping that the layers can be textures in memory that get composited in hardware onto the screen. Maybe this is wishful thinking though? I'm also thinking that maybe I can reduce the number of active layers from N down to 3 - the active layer, the layers below it, and the layers above it. Obviously only the active layer needs any sort of sprite-like animations and it on this layer than response time is most important. Having to layer the top layers ontop of it may also play a factor but, as I suggested, I can merge them all together in one time and then use the merged result to layer on top of the active layer. I'm a little nervous about going the C/C++ route. It's been a few years since I used them, I'm new to Python, and jumping into coding Python extensions with C/C++ is not particularly palatable (though I'll do it if I have to.) > Any GUI toolkit will work if you find the low-level access > to their image memory buffers. That's another new step for me. Any ideas where to start? Thanks! From neilcrighton at gmail.com Mon Mar 10 05:31:37 2008 From: neilcrighton at gmail.com (Neil Crighton) Date: Mon, 10 Mar 2008 10:31:37 +0100 Subject: Problem with zipfile and newlines Message-ID: <63751c30803100231u682fc67ex7d5364c5555a07df@mail.gmail.com> I'm using the zipfile library to read a zip file in Windows, and it seems to be adding too many newlines to extracted files. I've found that for extracted text-encoded files, removing all instances of '\r' in the extracted file seems to fix the problem, but I can't find an easy solution for binary files. The code I'm using is something like: from zipfile import Zipfile z = Zipfile(open('zippedfile.zip')) extractedfile = z.read('filename_in_zippedfile') I'm using Python version 2.5. Has anyone else had this problem before, or know how to fix it? Thanks, Neil From bruno.desthuilliers at gmail.com Fri Mar 7 05:23:55 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 7 Mar 2008 02:23:55 -0800 (PST) Subject: Altering imported modules References: <47ce9279$0$27486$426a34cc@news.free.fr> Message-ID: <26f69931-c508-4a1e-8382-32b5b57158b3@60g2000hsy.googlegroups.com> On 6 mar, 21:29, Tro wrote: > On Wednesday 05 March 2008, Bruno Desthuilliers wrote: > > > > > Tro a ?crit : (snip) > > > I'd like to know if it's possible to make tlslite load *my* asyncore > > > module without changing any of the tlslite code. > > > Not sure this apply to your case (depends on how asyncore is implemented > > and the exact "modifications"), but monkeypatching is a possible solution. > > >http://en.wikipedia.org/wiki/Monkey_patch > >http://wiki.zope.org/zope2/MonkeyPatch > >http://mail.python.org/pipermail/python-dev/2008-January/076194.html > > Ooh. I didn't know this technique had a name. But that's basically how I'm > modifying the built-in asyncore in my own class. I override its poll() and > poll2() methods to do something extra. > > However, the issue with tlslite is that it imports the regular asyncore > instead of the one I wrote, One of us must be missing something here. The monkeypatch way is: # -- mypatch.py -- import BaseModule # backup original if we want to call it _original_something = BaseModule.something def my_patched_something(args): my_code_here_doing_stuff # eventually _original_something(args) more_code_here BaseModule.something = my_patched_something # -- main.py -- import mypatch # From now on, any other module calling # BaseModule.something will call my_patched_something. import other_module_using_BaseModule app_code_here > which means that I'd have to somehow monkeypatch > its "import" statement. I'm guessing that means simply monkeypatching both > the original asyncore module AND the tlslite module's asyncore attribute with > my own version. Unless there are some really strange things happening in tlslite and asyncore, if you import your monkeypatch before importing tlslite, you shouldn't have to touch anything in tlslite. Which is the whole point of monkeypatching. From hdante at gmail.com Mon Mar 31 19:35:38 2008 From: hdante at gmail.com (hdante) Date: Mon, 31 Mar 2008 16:35:38 -0700 (PDT) Subject: PyQt - How to prevent a dialog being resized? References: Message-ID: On Mar 31, 7:12 pm, Kelie wrote: > Hello, > > My question is as subject. I tried something like this and it doesn't > work. > > def resizeEvent(self, event): > self.size = event.oldSize() > > Any hint? > > Thank you. You should preset size hints: http://doc.trolltech.com/4.2/qwidget.html#minimumSize-prop From software at ginstrom.com Tue Mar 25 17:41:03 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Wed, 26 Mar 2008 06:41:03 +0900 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <47e92b07$0$15563$426a34cc@news.free.fr> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com><4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> <47e92b07$0$15563$426a34cc@news.free.fr> Message-ID: <032201c88ec0$ed4e3610$0203a8c0@MOUSE> > On Behalf Of Bruno Desthuilliers > >> for line in open("/etc/passwd"): > > NB : this idiom relies on the VM automatically closing files, > which is not garanteed on each and every implementation > (IIRC, jython won't do it). This is ok for Q&D throwaway > scripts targeting CPython, but should not go into production code. You're right. For production, I'd probably do this. def create_user_dirs(lines): for line in lines: pass # process lines here with open("/etc/passwd") as fp: create_user_dirs(fp) This has the benefit of allowing me to test create_user_dirs without touching the file system (by passing in a list of lines). Regards, Ryan Ginstrom From gagsl-py2 at yahoo.com.ar Tue Mar 18 22:55:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 23:55:00 -0300 Subject: automatically doing some cleaning-up by the process when the systems shuts down References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> Message-ID: En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh escribi?: > my programs runs as daemon and it does some logging .. when system > shuts down .. which may be done manually . i want my process do some > cleaning up automatically such as writing in to the log file when the > process terminats before the system shuts down handling the SYSTERM signal? -- Gabriel Genellina From mail at timgolden.me.uk Sun Mar 16 14:42:41 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 18:42:41 +0000 Subject: When file-like objects aren't file-like enough for Windows In-Reply-To: References: Message-ID: <47DD6A21.20609@timgolden.me.uk> William McBrine wrote: > Now, I have a similar problem with subprocess.Popen... The code that > works in Linux looks like this: > > source = urllib.urlopen(url) > child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) > try: > shutil.copyfileobj(child.stdout, self.wfile) > except: > kill(child.pid) > > But wfile isn't the problem this time; instead, it's the source: > > ... > child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) > File "C:\Python25\lib\subprocess.py", line 586, in __init__ > errread, errwrite) = self._get_handles(stdin, stdout, stderr) > File "C:\Python25\lib\subprocess.py", line 698, in _get_handles > p2cread = msvcrt.get_osfhandle(stdin.fileno()) > IOError: [Errno 9] Bad file descriptor > > How can I get around this, short of resorting to copying all of the input > before passing it to the child? It looks like you're stuck, I'm afraid. Basically you're falling foul of a documented limitation of the underlying socket file-likeness whose fileno () under Windows "cannot be used where a file descriptor can be used (such as os.fdopen())" I doubt you have any choice but to channel your urlopen data through some real file so it can make the stdin of the external process. TJG From darcy at druid.net Wed Mar 5 20:11:20 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 20:11:20 -0500 Subject: Identifying messages in a thread (was: Please keep the full address) In-Reply-To: <8763w094sy.fsf_-_@benfinney.id.au> References: <8763w094sy.fsf_-_@benfinney.id.au> Message-ID: <20080305201120.830e1c48.darcy@druid.net> On Thu, 06 Mar 2008 09:36:29 +1100 Ben Finney wrote: > > Those of us who identify the time wasters would also like to drop > > the responses to their posts and changing the address makes this > > impossible. > > Not at all. AFAIK the messages from Google mail correctly include the > 'In-Reply-To' field or the 'References' field in the message header. > So, you can know by those fields whether a message is part of a thread > you've previously identified. I don't want to have to tag every thread. I just want to *plonk* certain posters. Anyway, I'll live with Google's failings I guess. -- 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 castironpi at gmail.com Wed Mar 5 22:38:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:38:52 -0800 (PST) Subject: access to base class __init__ References: Message-ID: <3b5a3545-b1bf-4673-8a11-96368b76a629@n58g2000hsf.googlegroups.com> On Mar 5, 6:09?pm, sambo q wrote: > I got myself in jam trying to be too fancy with ?threading.Thread > Docs say / remind to call the base __init__ > but I can't fighure out how. > > --------------------------- > def main() > ..... > ? ? ls.listen(5) > ? ? key = ' ' > # ? ?while key != EXITCHARCTER: > ? ? while stop_serving == False: > ? ? ? ? cs, raddr = ls.accept() > ? ? ? ? print "Main_Thread: ",cs, raddr > ? ? ? ? nt = client_socket_handler( cs, raddr ) > ? ? ? ? print threading.enumerate() > ? ? ? ? key = getkey() > > # ? ?ls.close() > ? ? time.sleep(4) > ? ? print "Server Exiting." > > class client_socket_handler(threading.Thread): > ? ? def __init__(self, cs, remote_address): > ??????????????????????? > ? ? ? ? self.threading.Thread.__init__(self,self.socket_handler,None,None) > ? ? ? ? self.socket = cs > ? ? ? ? self.rhost_addr = remote_address > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > # ? ? ? ?t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) > # ? ? ? ?t1.start() > ? ? ? ? self.start() > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > ? ? ? ? print "client_socket_handler.__init__(): enumerate()", > threading.enumerate() > > ? ? def socket_handler( self, invar, indict ): > ? ? ? ? threadname = self.getName() > ? ? ? ? print "\"%s started\"" % threadname > ? ? ? ? print "client_socket_handler.socket_handler() invar: ", invar > ? ? ? ? instr = self.socket.recv( 500 ) > # ? ? ? ?print instr > ? ? ? ? req_lines = string.split( instr, "\r" ) > ? ? ? ? for line in req_lines: > ? ? ? ? ? ? line.strip( "\n") > ? ? ? ? print req_lines > ? ? ? ? print len( instr ) > > ---------------------------------- > > self.threading.Thread.__init__() > self.Thread.__init__() > ?? recall a= A() --> a.b() --> A.b( a ). What is A? threading.Thread. In other words, threading.Thread.__init__( *stuff ). From MartinRinehart at gmail.com Thu Mar 27 10:54:48 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 07:54:48 -0700 (PDT) Subject: Tkinter menus made easy Message-ID: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Writing Tkinter menu code used to be rather tedious, uninspiring work. I figured that I could delegate the job to a program: http://www.martinrinehart.com/articles/menus.py Run it. Then look at the source (bottom of file). There's a bit more doc in the doc comment at the top. Peer review is most welcome. From gagsl-py2 at yahoo.com.ar Mon Mar 10 00:45:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 21:45:46 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> <13t7smt4rn8rn32@corp.supernews.com> Message-ID: On 9 mar, 11:23, Steven D'Aprano wrote: > On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > > Okay, so I think I know where's the catch now -- you must rely on the > > fact that the protocol is implemented, there's no way to enforce it if > > you're expecting a parrot-like object. You'd try to call the speak() > > method and deal with the error if there's no such method? > > That's right. That's called "duck typing" -- if all you want is something > that quacks like a duck, then it doesn't matter if it actually is a duck > or not. In addition to duck typing, in some cases an explicit declaration may be useful: "I implement the Parrot protocol". The zope.interface package does that: there is a way to define interfaces (a set of methods any implementation must provide), and classes can assert "I implement this interface", and one can determine whether a class implements or not certain interface. See http://pypi.python.org/pypi/zope.interface Abstract Base Classes (ABC, for Python 3.0) provide a similar concept (but they're not the same thing). See http://www.python.org/dev/peps/pep-3119/ Of course there is some overlapping between all of these techniques - one should choose the best method in each case. -- Gabriel Genellina From adelagon at gmail.com Tue Mar 25 23:11:23 2008 From: adelagon at gmail.com (Alvin Delagon) Date: Wed, 26 Mar 2008 11:11:23 +0800 Subject: python hash() function Message-ID: <7a01f6c00803252011k638b16f6p45764b4dcf2a323@mail.gmail.com> Thanks for the fast replies guys. Very much appreciated. :) --- Alvin -------------- next part -------------- An HTML attachment was scrubbed... URL: From jon+usenet at unequivocal.co.uk Fri Mar 7 12:40:08 2008 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 7 Mar 2008 17:40:08 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: On 2008-03-07, D'Arcy J.M. Cain wrote: >> 2. You should use two spaces after a sentence-ending period. >> >> For heavens sake, why? I've always been obstructed by the double >> blanks but tolerated them. Now, that i read that it actually is a >> recommendation, i need to ask about the purpose. > > Like many things of this nature, the purpose is to follow the rules of > correct English usage. Well, no, it's to follow a particular person's choice out of the many and various competing rules of "correct English usage". Personally, I dislike double spaces after sentences, but it is not wrong to put them there any more than it is wrong not to put them there. Consistency is far more important (hence the rule, I presume). From wbsoft at xs4all.nl Thu Mar 27 09:56:50 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Thu, 27 Mar 2008 14:56:50 +0100 Subject: And the reverse? Does os also import os.path? In-Reply-To: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> References: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> Message-ID: <200803271456.50894.wbsoft@xs4all.nl> If i do >>> import os >>> os.path.abspath("bla") '/home/wilbert/bla' >>> it seems that just import os also makes available al os.path functions. But is that always true? Thanks, Wilbert -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandhi From aaron.watters at gmail.com Tue Mar 4 12:04:11 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 4 Mar 2008 09:04:11 -0800 (PST) Subject: why not bisect options? References: Message-ID: On Feb 29, 9:31 am, Robert Bossy wrote: > Hi all, > > I thought it would be useful if insort and consorts* could accept the > same options than list.sort, especially key and cmp..... Wouldn't this make them slower and less space efficient? It would be fine to add something like this as an additional elaboration, but I want bisect to scream as fast as possible in the default streamlined usage. -- Aaron Watters === dueling bumper stickers: use java/get rich use perl/get laid -- both equally sensible http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=wince From mail at timgolden.me.uk Mon Mar 31 03:50:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 31 Mar 2008 08:50:34 +0100 Subject: Finding Full Path to Process EXE In-Reply-To: References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> <47eea713$0$27902$426a74cc@news.free.fr> Message-ID: <47F097CA.1080103@timgolden.me.uk> misceverything at gmail.com wrote: > That's not a problem - I'm only interested in Win2k+. Thanks for the > caveat. > > On a similar note, is there a way (preferably using WMI) to get the > full path to the executable that has a port open (the same thing that > fport does, just implemented in Python)? It looks as though it might be possible with the (not installed by default) SNMP WMI provider. Haven't tried it myself, but there's some info here: http://groups.google.com/group/microsoft.public.win32.programmer.wmi/msg/761b8497826e4aea and here: http://msdn2.microsoft.com/en-us/library/aa393621(VS.85).aspx Alternatively, look around for the GetExtendedTcpTable functionality and so on. Sorry, this isn't really my area -- all I've done here is to let my fingers do the walking. TJG From robin at reportlab.com Wed Mar 19 12:24:46 2008 From: robin at reportlab.com (Robin Becker) Date: Wed, 19 Mar 2008 16:24:46 +0000 Subject: csv.Sniffer - delete in Python 3.0? In-Reply-To: <18401.13509.344107.988906@montanaro-dyndns-org.local> References: <18401.13509.344107.988906@montanaro-dyndns-org.local> Message-ID: <47E13E4E.5030306@chamonix.reportlab.co.uk> skip at pobox.com wrote: ........ > > I would be happy to get rid of it in 3.0, but I'm also aware that some > people use it. I'd like feedback from the Python community about this. If > I removed it is there someone out there who wants it badly enough to > maintain it in PyPI? ...... sounds like we really need import ai info = ai.guess_what_this_is('crummy.csv') but I suspect that won't arrive before py5000 I use csv, but almost always with tab or comma separation and \r\n line terminators. -- Robin Becker From sturlamolden at yahoo.no Sat Mar 15 11:40:06 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 08:40:06 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: <5359a380-7c78-43f3-b18b-88ea50d98556@h11g2000prf.googlegroups.com> On 28 Feb, 02:24, Steven D'Aprano wrote: > Python doesn't do call by reference. Nor does it do call by value. Please > pay no attention to anyone who says it does. Exactly. Python pass variables the same way as Lisp, which is neither "call-by-value" (cf. C) nor "call-by-reference" (cf. Fortran). The Python equivalent of "pass by reference" is a function that returns its arguments to the caller: def foobar(arg1, arg2, arg3): # Mutate an object shared with the caller. # I.e. calling convention cannot be not "pass-by-value" arg1.whatever = 1 # Rebind variables in the local namespace. # I.e. calling convention cannot be "pass-by-reference" arg1, arg2, arg3 = 1, 2, 3 # Return rebound variables to achieve the effect of # "pass-by-reference": return (arg1, arg2, arg3) # Call the function foobar, and rebind its arguments to its # return values: arg1, arg2, arg3 = foobar(arg1, arg2, arg3) From driedel at printingforsystems.com Wed Mar 12 09:57:23 2008 From: driedel at printingforsystems.com (David P. Riedel) Date: Wed, 12 Mar 2008 09:57:23 -0400 Subject: problem with Python 2.5.2 and gcc 4.3 Message-ID: <7jRBj.20981$QC.15171@newsfe20.lga> Hi I tried building Python 2.5.2 using gcc 4.3.0. The build completes with no problems but when I run 'make test', I get a segfault part way through the test run. here is the last part of the output from make test test_softspace test_sort test_sqlite test_sqlite skipped -- no sqlite available test_startfile test_startfile skipped -- cannot import name startfile test_str make: *** [test] Segmentation fault Has anyone else seen this? Thanks Dave Riedel From castironpi at gmail.com Fri Mar 7 20:32:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 17:32:51 -0800 (PST) Subject: Nested phrases [was Re: Want - but cannot get - a nested class to inherit from outer class] References: <18b456bf-bc3d-45f6-af92-369e01e0f426@o77g2000hsf.googlegroups.com> <13t3o20lbtipica@corp.supernews.com> Message-ID: <0997e5bc-2328-4914-b3a4-d96ba90a07cf@m3g2000hsc.googlegroups.com> On Mar 7, 6:39?pm, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 14:26:25 -0800, castironpi wrote: > > Humans have enormous "mental stacks"--- the stacks the contexts the > > speakers speak in push things they're hearing on to. > > This is not true. Oh yeah. (See below.) > Human beings have extremely shallow mental stacks, limited by short-term > memory. Most people are capable of keeping seven, plus or minus two, > items in short term memory at once. Any more than that and they are > subject to fading away or being over-written. > ? ? efficiency expert by the company through. > ? ? Remarkable is the rapidity of the motion of the wing > ? ? of the hummingbird. Oh, you mean hummingbird wing motion rapidity remarkability! How - could- I! 'Stack' may have been the wrong word. I probably meant 'intermodal recognition': the "Ah yes, I know it" response. But whether that's related to our tool-bearer capacity, isn't something you can test all that easily. What animals encounter something they had a use for once, and forget what? The breadth of objects in, say, a leopard's representation table* (working term), doesn't include chisels and footballs. Nothing is its favorite football, and a football isn't its favorite anything. What are its favorites? * Proposition table is clearly wrong. But given the human ability to touch an object, then open eyes, and identify which it touched might suggest 'intermodal recognition table', 'resemblance table', or 'value table'. How about resemblance-value? It at least would explain our susceptibility and reaction to greedy traps and shock: it's a the shock and greedy trap susceptibility and reaction of ours explanation. That is, how close something you like is to something you like..... and how much you like it. How much you like and how close something is... . Monotonically decreasing bivariate, delta> 0 => value( object, prior value+ delta )< value( object, prior value ) & value( object+ delta, prior value )< value( object, prior value ). ... which, by the way, should answer Archimedes' riddle: can you step in the same river? By degree. You're downstream and know it. Nota bene, how fast we can recall a song we even haven't heard in years we hear a snippet of, and not even from the overture. Given a 'symbol' that comes over a channel, in baud, our hash function maps it to a value close to previous hashings of it--- we merely search nearby memories and it's recognized. Odd! From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 15:47:08 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 21:47:08 +0100 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: References: <47c93bb8$0$874$ba4acef3@news.orange.fr> <47c990b9$0$899$ba4acef3@news.orange.fr> Message-ID: <47c9c25a$0$907$ba4acef3@news.orange.fr> Hi! Thank you for return. I will uninstall+reinstall Pyscripter. @-salutations -- Michel Claveau From userprogoogle-139 at yahoo.co.uk Wed Mar 19 08:04:05 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 19 Mar 2008 05:04:05 -0700 (PDT) Subject: Need Help Starting Out References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> <47e0e546$0$30851$426a74cc@news.free.fr> Message-ID: <13a8683f-6675-444d-a483-ea439d9c48d2@u69g2000hse.googlegroups.com> > Your best bets are probably Django, Pylons or web.py. But you should > learn enough of the core language itself before jumping in web stuff IMHO. Yes, a good point. If you are looking for general info then then "Dive Into Python" (a link is on the Python website) is a good start for people who are familiar with other programming languages. Otherwise I also found "Python in a Nutshell" useful. rod From dieterv at optionexplicit.be Sun Mar 30 06:49:42 2008 From: dieterv at optionexplicit.be (Dieter Verfaillie) Date: Sun, 30 Mar 2008 12:49:42 +0200 Subject: PyGTK localisation on Win32 In-Reply-To: <9c795bfa-b2a1-4c72-bc69-0f5664c0d3e1@i12g2000prf.googlegroups.com> References: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> <9c795bfa-b2a1-4c72-bc69-0f5664c0d3e1@i12g2000prf.googlegroups.com> Message-ID: <1206874182.4245.8.camel@PO001> On Thu, 2008-03-27 at 05:21 -0700, Sukhov Dmitry wrote: > I have the same problem. I did all as you wrote. gettext translations > do work fine. But translations in glade does not work. > > The only way to turn it on is to set environment variable LANG > explicitly before program run: > set LANG=ru_RU > python test.py Yep, from python 2.4 on, os.environ changes only work within python and no longer apply to low level c stuff on win32. Luckily, it's still possible to force environment variables through the kernel32.SetEnvironmentVariableW and msvcrt._putenv functions. Put the attached locale module in a libi18n package and use like this: #!/usr/bin/env python from libi18n import locale locale.fix_locale() del locale hth, Dieter -------------- next part -------------- A non-text attachment was scrubbed... Name: locale.py Type: text/x-python Size: 13405 bytes Desc: not available URL: -------------- 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 stef.mientki at gmail.com Sat Mar 1 05:46:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 01 Mar 2008 11:46:40 +0100 Subject: invert or not ? Message-ID: <47C93410.9050005@gmail.com> hello, from the manual I read that a bitwise inversion should be done by invert. But from some experiments I see that not works equally well. Is this coincidence ? (The disadvantage of invert is that I've to import operators) thanks, Stef From aaron.murray at gmail.com Sun Mar 16 10:31:00 2008 From: aaron.murray at gmail.com (Aaron) Date: Sun, 16 Mar 2008 07:31:00 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> > In my opinion, open spaces should have had greater status and billing, > with eyes-forward talks and vendor sessions offered only as possible > alternatives. Especially, vendor sessions should not be presented as > "keynotes" during plenary sessions. I think it took a little while > for people to catch on to the idea that they could have control of > their own experience through the open spaces and that the main > offerings were not the only option. This is an excellent suggestion and observation. Sold sponsorships are fine as long as they are billed as such. Labels on the vendor speeches indicated they were sold as ad space would be great, as well as more strongly emphasizing the ad hoc discussion spaces. From mhwalker at shaw.ca Tue Mar 4 02:45:31 2008 From: mhwalker at shaw.ca (Mike Walker) Date: Tue, 04 Mar 2008 07:45:31 GMT Subject: Command line arguments in Windows In-Reply-To: References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: "Mark Tolonen" wrote in message news:of6dnVTvVvGtalHanZ2dnUVZ_uCdnZ2d at comcast.com... > > From the command line, the 'ftype' and 'assoc' commands can be used > view how an extension is handled: > > C:\>assoc .py > .py=Python.File > > C:\>ftype Python.File > Python.File="C:\Python25\python.exe" "%1" %* > > My guess is your command line looks something like this: > > Python.File="C:\Python25\python.exe" "%1" > > The script name is being passed, but not the rest of the arguments. > I vaguely remember seeing this on an older version one of ActiveState's > ActivePython installers. What version of Python are you running? > > --Mark > Here is the output from the commands you listed which looks right to me. C:\>assoc .py .py=Python.File C:\>ftype python.file python.file="C:\Python25\python.exe" "%1" %* I am using Python 2.5.2 from http://www.python.org/ running on Windows Vista. Would ActiveState's version be a better choice here? ~Mike From robert.kern at gmail.com Mon Mar 24 15:13:40 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Mar 2008 14:13:40 -0500 Subject: New to group In-Reply-To: <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> Message-ID: pythonnubie wrote: > On Mar 24, 11:57 am, Jeff wrote: >> What does the code look like? > > # Random Access > # Demonstrates string indexing > # Michael Dawson - 1/27/03 > > import random Make sure that you do not have a random.py module in the current directory. Python checks the current directory for modules before the standard directories. -- 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 castironpi at gmail.com Thu Mar 13 12:05:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 09:05:39 -0700 (PDT) Subject: What's Going On? References: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> <63sgh6F28j923U1@mid.uni-berlin.de> Message-ID: <45fe5ddf-e747-46b2-bae3-1dbb6d494b52@m3g2000hsc.googlegroups.com> On Mar 13, 6:12 am, "Diez B. Roggisch" wrote: > MartinRineh... at gmail.com wrote: > > (Accompanied by Marvin Gaye) > > >>>> def f(list=[0]): > > ... list[0]+=1 > > ... return list[0] > > ... > >>>> f() > > 1 > >>>> f() > > 2 > >>>> f() # 'list' is a name bound to a list (mutable) so this makes sense > > 3 > >>>> f([5]) > > 6 > >>>>f() # What's Going On? > > 4 > > That the same default argument is mutated? What did you expect, that it got > replaced by you passing another list? That would kind of defy the meaning > of default-arguments, replacing them whenever you call a function with > actual parameters. f( ite, itr= ite.__iter__ ). Case 1: 'ite' is bound in outer scope. Case 2: not. function(code, globals[, name[, argdefs[, closure]]]) The optional argdefs tuple specifies the default argument values. TypeError: __defaults__ must be set to a tuple object >>> import functools >>> def k(): ... print( 'k call' ) ... >>> class GT: ... def __init__( self, arg ): ... self._arg= arg ... >>> def latebound( fun ): ... @functools.wraps( fun ) ... def post( *ar ): ... lar= list( fun.__defaults__ ) ... for i, a in enumerate( lar ): ... if isinstance( lar[ i ], GT ): ... lar[ i ]= eval( a._arg) ... return fun( *( list( ar )+ lar ) ) ... return post ... >>> @latebound ... def f( ite, itr= GT('k()') ): ... return itr ... >>> f( 2 ) k call >>> f( 2 ) k call >>> f( 2 ) k call >>> Furthermore, ... >>> @latebound ... def f( ite, itr= GT('ar[0]+ 1') ): ... return itr ... >>> f( 2 ) 3 >>> f( 2 ) 3 >>> f( 2 ) 3 >>> Unfortunately, ... >>> @latebound ... def f( ite, itr= GT('ite+ 1') ): ... return itr ... >>> f( 2 ) Traceback (most recent call last): File "", line 1, in File "", line 7, in post File "", line 1, in NameError: name 'ite' is not defined >>> The moral of the story is, wouldn't it be nice if wrappers could access the post-invocation bindings of the wrappee's internal variables? Certainly the 'TypeError: __defaults__ must be set to a tuple object' is unnecessarily restrictive: let it be a mutable, or, if it's not a tuple, call it. Just add a __call__ method to that tuple that does nothing, if a type-test isn't faster-- perhaps even a null __call__ which does -actually- nothing. (Why is __defaults__ None when empty, not an empty tuple?) What are the use case proportions of function-static vs. call-time evaluation? Function-static is nice in that it keeps objects floating around with the function, both in information design, and in encapsulation. They both have easy workarounds: >>> import functools >>> def auto( fun ): ... @functools.wraps( fun ) ... def post( *ar ): ... return fun( post, *ar ) ... return post ... >>> @auto ... def f( self ): ... print( self.ite ) ... >>> f.ite= [] >>> >>> f() [] >>> f.ite.append( 2 ) >>> f() [2] @auto adds the binding function to its called parameter list, which is nice if the function will change names ever-- that is, become bound to other variables-- because its statics still stay with it, and because it's not a global either. >>> g= f >>> del f >>> g() Traceback (most recent call last): File "", line 1, in File "", line 4, in post File "", line 3, in f NameError: global name 'f' is not defined But on the other hand, if the Python community on the whole wants to keep the status quo, >>> def f( ite, itr= None ): ... if None is itr: ... itr= ite+ 1 ... return itr ... >>> f( 2 ) 3 >>> f( 2 ) 3 >>> f( 2 ) 3 isn't so bad. (If you think it is, lobby!) @latebound is a good compromise. It keeps the information in the right place, but takes a little redundancy if the evalled expression refers to another variable, and but costs the additional GT class, and adds an O( n ) argument-length boilerplate rearrangement. @auto frees us to allow a different behavior to default parameters while keeping both statics and call-times explicit, keeping the information in the right place, but it's a change in the language. Lastly, we have: >>> @late( itr= 'ite+ 1' ) ... def f( ite, itr= latearg, j= 0 ): ... return itr, j ... >>> print( f( 2 ) ) (3, 0) Proof of concept: import functools latearg= object() def late( **kw ): def pre( fun ): _defs= fun.__defaults__ if None is _defs: _defs= () _names= fun.__code__.co_varnames _deflen= len( _defs ) _namelen= fun.__code__.co_argcount for k in kw: if k not in _names: raise TypeError( 'Non-parameter' ' keyword \'%s\' in \'late\'' ' call.'% k ) print( _defs ) print( _names ) print( _deflen ) for a, b in zip( _names[ -_deflen: ], _defs ): if b is latearg and a not in kw: raise TypeError( 'Non-bound' ' latearg \'%s\' in \'late\'' ' call.'% k ) @functools.wraps( fun ) def post( *ar ): _arglen= len( ar ) _defleft= _namelen- _arglen _defused= () if _defleft: _defused= _defs[ -_defleft: ] _lar= list( ar+ _defused ) _funargs= {} for i, a in enumerate( ar ): _funargs[ _names[ i ] ]= a for k, v in kw.items(): if k not in _names: raise TypeError( 'Not all latearg' ' arguments bound in call' ' of \'%s\''% fun.__name__ ) _place= _names.index( k ) if _place>= _arglen: _lar[ _place ]= eval( v, globals(), _funargs ) if latearg in _lar: raise TypeError( 'Not all latearg' ' arguments bound in call' ' of \'%s\''% fun.__name__ ) return fun( *_lar ) return post return pre @late( itr= 'ite+ 1' ) def f( ite, itr= latearg, j= 0 ): return itr, j assert f( 2 )== ( 3, 0 ) assert f( 2, 0 )== ( 0, 0 ) assert f( 2, 0, 1 )== ( 0, 1 ) assert f( 2, 1 )== ( 1, 0 ) To complete 'post' (**kw not shown) is left as an exercise to the reader. From bj_666 at gmx.net Tue Mar 25 13:08:28 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Mar 2008 17:08:28 GMT Subject: Does python hate cathy? References: Message-ID: <64spscF2derd7U3@mid.uni-berlin.de> On Tue, 25 Mar 2008 14:58:51 +0000, Edward A. Falk wrote: > In article , > Patrick Mullen wrote: > >>Then again, I can count the number of times I have ever needed __del__ >>with no fingers (never used it!). Still, quite interesting to >>explore. > > I used it once, for an object that had a doubly-linked list. > The __del__() method walked the list, setting all the elements' > prev/next pointers to None to make sure the elements of the list would > get garbage-collected. Without the `__del__()` the elements would get garbage collected just fine. If you don't want to wait until the garbage collector in CPython detects the cycle, you can use `weakref`\s for one of the two "pointers" in each element. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Thu Mar 13 17:35:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Mar 2008 14:35:46 -0700 (PDT) Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup References: <47d97288$0$36363$742ec2ed@news.sonic.net> Message-ID: <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> On Mar 14, 5:38 am, John Nagle wrote: > Just noticed, again, that getattr/setattr are ASCII-only, and don't support > Unicode. > > SGMLlib blows up because of this when faced with a Unicode end tag: > > File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag > method = getattr(self, 'end_' + tag) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' > in position 46: ordinal not in range(128) > > Should attributes be restricted to ASCII, or is this a bug? > > John Nagle Identifiers are restricted -- see section 2.3 (Identifiers and keywords) of the Reference Manual. The restriction is in effect that they match r'[A-Za-z_][A-Za-z0-9_]*\Z'. Hence if you can't use obj.nonASCIIname in your code, it makes sense for the equivalent usage in setattr and getattr not to be available. However other than forcing unicode to str, setattr and getattr seem not to care what you use: >>> class O(object): ... pass ... >>> o = O() >>> setattr(o, '42', 'universe') >>> getattr(o, '42') 'universe' >>> # doesn't even need to be ASCII >>> setattr(o, '\xff', 'notA-Za-z etc') >>> getattr(o, '\xff') 'notA-Za-z etc' >>> Cheers, John From kyosohma at gmail.com Mon Mar 10 14:29:12 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 11:29:12 -0700 (PDT) Subject: lowercase u before string in "python for windows" References: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> Message-ID: <21b38583-1623-4df5-a14d-d224c9128083@c33g2000hsd.googlegroups.com> > > > is there a newsgroup explicitly for python windows extensions? > > Not that I know of, other than what's described here: > > https://sourceforge.net/mail/?group_id=78018 > > -tkc There is a PyWin32 user's group: http://mail.python.org/mailman/listinfo/python-win32 The maintainer of the project is a regular contributor to the list as are a number of other very knowledgeable Windows guys. Mike From kla at us.de Fri Mar 21 11:19:05 2008 From: kla at us.de (klaus) Date: 21 Mar 2008 15:19:05 GMT Subject: beginners question about return value of re.split Message-ID: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Hello, I have a question regarding the return value of re.split() since I have been unable to find any answers in the regular sources of documentation. Please consider the following: #!/usr/bin/env python import re if __name__ == "__main__": datum = "2008-03-14" the_date = re.split('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', datum, 3) print the_date Now the result that is printed is: ['', '2008', '03', '14', ''] My question: what are the empty strings doing there in the beginning and in the end ? Is this due to a faulty regular expression ? Thank you ! KL. From sajmikins at gmail.com Thu Mar 20 20:43:59 2008 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Mar 2008 17:43:59 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: On Mar 19, 11:39 pm, "Daniel Fetchinson" wrote: > > Was looking at PEP 3108,http://www.python.org/dev/peps/pep-3108/, > > and saw that the repr module was slated for vaporization. I've only > > used the module a few times ever. I'm curious if the community wants > > it kept around or whether it is considered clutter. > > > The PEP is going to be finalized soon, so if you have issues with it, > > they should be sent to the PEP author or brought up on the list, > >http://mail.python.org/mailman/listinfo/stdlib-sig. > > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: > > Each module to be removed needs to have a justification as to why it > should no longer be distributed with Python. > > then goes on with, > > With so many other GUI options out there that are considered better > than Tkinter, it might be best to remove Tkinter from the stdlib and > make it an externally maintained package. > > I don't get it. There are many [insert your favorite software > component] options outside of the python core that are considered > better than the one coming with python, yet they don't get removed. > All network servers for example could be thrown out because twisted is > considered better. This just doesn't make sense to me. Tkinter is > great for its purpose, typical use cases are creating a simple GUI > composed of a couple of components only. You can nicely do this with > tkinter and the large user base shows that it's a real need real > people have. Sure, for fancy GUI stuff there are better options but > for quick and simple things tkinter is just great. And last time I > checked python comes with batteries included so why sould I need to > search and download a third party package for such a common use case? > > Thoughts anyone? > > Cheers, > Daniel I've been thinking of volunteering to "port" Tkinter to Python 3.0, I hadn't noticed that there was any discussion of removing it. It would be a shame IMHO. Sure it has warts, but it /works/ and good for quick and dirty GUIs as well as elaborate (even totally visually customized) fancy applications. ~Simon From malkarouri at gmail.com Sat Mar 8 17:37:11 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 14:37:11 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <7d442cdd-749e-4391-ba31-e9c86d090137@x41g2000hsb.googlegroups.com> Message-ID: <70f5b8e7-4e76-43f7-b390-c5dd994ff434@e31g2000hse.googlegroups.com> On Mar 8, 6:24?pm, rockingred wrote: > I think it's a bad practice to get into. ?Did you intend to do the > "process" step again over the added variables? ?If not I would set a > new variable, based on your awful naming convention, let's call it z. > Then use z.append(y) within the for loop and after you are out of your > for loop, q.append(z). Thanks, rockingred, for the advice. I hope that you didn't assume that I was a newbie, even if my question looks so. What I was trying to do is write some Python code which I need to optimize as much as possible. I am using Cython (Pyrex) and would probably end up rewriting my whole module in C at one point, but it is really hard to beat Python data structures at their home turf. So meanwhile, I am making use of dubious optimizations - on my own responsibility. There have been a lot of these along the years - like using variables leaking from list expressions (not anymore). Think of it as a goto. Yes, I intend to do the process step again over the added variables. The suggested deque is probably the best, though I need the speed here. What are the variable naming you would suggest, for a throwaway - probably anonymized for the same of publishing on the web - code? Cheers, Muhammad Alkarouri From aisaac at american.edu Thu Mar 13 20:38:40 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 14 Mar 2008 00:38:40 GMT Subject: no more comparisons In-Reply-To: References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: Mark Dickinson wrote: > Sorting tuples, where the second item in the tuple should > have the opposite ordering to the first is going to be > a bit of a pain. Or even worse, where the ordering of the > second item depends on the value of the first item in the > tuple. This is like some examples where I had used cmp, but if I understand correctly I think it is not a problem. > For example, suppose that (for whatever contrived reason) > you're representing integers in (sign, magnitude) format > by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for > negative) and i is a string representing the absolute > value of the integer. So Does this do it? :: key= lambda x: (-x[1],int(x2)) Here I am depending on the lexicographic sorting of tuples. Without that there would be real trouble. Cheers, Alan Isaac From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 10:00:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 14:00:09 -0000 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> <8hqHj.175213$8Z.117427@newsfet10.ams> Message-ID: <13usir93664fe2d@corp.supernews.com> On Sat, 29 Mar 2008 13:06:27 +0100, Roel Schroeven wrote: > In any case, I replied because your reaction didn't feel all that gentle > to me; to be honest, it felt rather rude. Are you new to Usenet? :-) No offense taken; I hope Robert didn't take offense either, but took the little dig in the spirit it was intended. -- Steven From hniksic at xemacs.org Sun Mar 30 16:11:43 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 30 Mar 2008 22:11:43 +0200 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <656vhnF2e9ao7U1@mid.uni-berlin.de> Message-ID: <8763v4otts.fsf@mulj.homelinux.net> "Diez B. Roggisch" writes: >> Note that I said "*file* input/output". Twisted and asyncore are >> about asynchronous socket programming that polls over nonblocking file >> descriptors such as found in socket programming, not about wrapping >> aio(3) and the equivalent Windows APIs. > > I admit glossing over the file-input - however this is available on > posix-systems using the select-module. I believe you stil misunderstand. The select module doesn't provide an inteface to aio(3). It provides an interface to select() and poll() system calls, which don't provide asynchronous access to regular files. > So if I were in nitpicking-mood, your assertion still would be false I invite constructive nitpicking, but you are completely missing the point. You are confusing aio(3) with select and poll. > I'm pretty sure though that tiwsted & asynchore don't poll, but > instead use the select-module. Which at least for unix (and AFAIK > for Windows as well) is asynchronous - you get notified if data > arrives or has been transmitted, and otherwise your process sleeps. Unfortunately, this is not the case for files at all, even on Unix. (On Windows, select doesn't work on files at all, it only accepts sockets.) From kyosohma at gmail.com Thu Mar 6 09:20:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Mar 2008 06:20:03 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: On Mar 5, 7:07 pm, "D'Arcy J.M. Cain" wrote: > On Wed, 5 Mar 2008 14:00:17 -0800 (PST) > > Mike Driscoll wrote: > > What are you talking about? I didn't change the address at all. I'm > > not even sure what you mean. Are you talking about the post subject > > line (which I have never touched in any post)? If you're talking about > > the OP's email address, that's Google's fault for cropping them. > > I'm talking about castironpi. I find his posts a waste of my time so I > have them filtered out along with a few others and I also filter out > responses by searching for his address in the body so changing it > defeats that. However, if it is something that you have no control over > I apologize for the noise. > > -- > D'Arcy J.M. Cain | Democracy is three wolveshttp://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. No problem. I wish I could use something other than Google Groups when I'm at work, but we currently have NNTP disabled...and I haven't found a good workaround yet. Mike From hdante at gmail.com Sun Mar 30 17:21:08 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 14:21:08 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <6deb5443-e87b-448e-a1a6-6a1886c9f12a@x41g2000hsb.googlegroups.com> <87od8vzzr4.fsf@physik.rwth-aachen.de> Message-ID: <2799dc1e-3652-420c-bfd0-f0a5f8adc07e@m3g2000hsc.googlegroups.com> On Mar 30, 6:08 pm, Torsten Bronger wrote: > Hall?chen! > > hdante writes: > > On Mar 30, 9:45 am, Bjoern Schliessmann > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > >> hdante wrote: > > >>> BTW, my opinion is that it's already time that programmer > >>> editors have input methods advanced enough for generating this: > > >> Could you please list some that do, and are also convenient? > > > AFAICT there's none. This should be easy to implement on emacs, > > It *is* implemented in Emacs. You can even choose from many input > methods, optimised for differend areas/languages. I mean creating an input method specific for programming languages, not using the TeX one. > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: bron... at jabber.org > (Seehttp://ime.webhop.orgfor further contact info.) From roman.dodin at softjoys.com Mon Mar 17 06:12:13 2008 From: roman.dodin at softjoys.com (Roman Dodin) Date: Mon, 17 Mar 2008 13:12:13 +0300 Subject: About reading Python code In-Reply-To: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <47DE43FD.5090308@softjoys.com> WaterWalk ?????: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. > > So I'm curious how to read code effectively. I agree that python code > is clear, but when it becomes long, reading it can still be a hard > work. > You also can use free IDE (for example Eclipse) and PyDev plugin, which includes comfortable Debugger From http Fri Mar 21 15:52:12 2008 From: http (Paul Rubin) Date: 21 Mar 2008 12:52:12 -0700 Subject: How can I make a function equal to 0? References: Message-ID: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Martin Manns writes: > Is there a way to create a function that is equal to 0? def f(): return 0 From jr9445 at ATT.COM Mon Mar 31 14:06:29 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 31 Mar 2008 13:06:29 -0500 Subject: Is this a good time to start learning python? In-Reply-To: <47f1140e$0$735$a729d347@news.telepac.pt> References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Rui Maciel > Sent: Monday, March 31, 2008 12:41 PM > To: python-list at python.org > Subject: Is this a good time to start learning python? > > Recently I woke up inclined to take up the task of learning another > programming language. I've already dipped my toes in Perl (I've read > online > tutorials and wrote a couple of irrelevant pet projects) but, as the > computers at my workplace only sport the python interpreter, it > probably > means that learning python will end up serving me better, at least in > the > short run. Plus, you know how Perl goes. > > So far the decision seems to be a no brainer. Yet, Python 3000 will > arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put > it > in other words, I fear that I will be wasting my time. > > At least that is what a clueless newbie believes. As this group is > frequented by people who have more insight into all things pythonesque, > what are your thoughts on this? > Meh. That's like asking if you should learn to use a fork or a spoon. If you're learning how to program, go with Python. (Learning as in algorithms and data structures.) If you need to use OO, go with Python. Perl's OO syntax is just horrific. If you're using a lot of regexes, need a bit of speed, or need something a bit more robust than dynamically typed objects randomly breaking your code, then go with Perl. ;-) Libraries can also affect your choice. (I had to switch to Perl when Python's win32com failed.) Perl's learning curve is "unreadable" syntax, whereas Python's curve requires knowing about side effects and dealing with strong, dynamic typing. Overall, Python is more high level and cleaner looking/readable. However, Python's dynamically typed objects require additional effort/expense to debug, and it's regex module is pretty quirky/painful to use. Perl has a very large library, is fast, is mostly statically compiled, and doesn't get in the way (automatic type conversions, several ways to do something, etc..) Python is probably faster to learn (clearer syntax and OO,) but slower to master (side effects, strongly but dynamically typed.) With Perl, once you get the core syntax down, you don't need to master Perl. Instead you just look up the module/feature you want to use and just use it. Finally, I find that Perl's documentation is much better than Python's. All IMO, IME. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From jason.scheirer at gmail.com Mon Mar 31 13:37:45 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 31 Mar 2008 10:37:45 -0700 (PDT) Subject: Automatically fill in forms on line References: <772b20d1-a845-480b-a583-cf8ba470ecae@q27g2000prf.googlegroups.com> Message-ID: <8e6c8058-c89f-402e-ab17-f310d7ffb8cd@e10g2000prf.googlegroups.com> On Mar 31, 10:35 am, Jason Scheirer wrote: > On Mar 31, 9:50 am, "Jackie Wang" wrote: > > > > > Dear all, > > > I want to automatically complete the following task: > > > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx; > > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > > Highway 102"; > > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > > 4. Click the bottom "search"; > > 5. In the opened page, extract and save the number after "Tract Code". > > In the example, it will be "9659". > > 6. Repeat Step 1 with a new address. > > > Can Python realize these steps? Can these steps be done witout > > openning and IE windows? Especially, I dont know how to write code for > > step 2, 4 and 5. > > > Thank you! > > You may also want to look at the Yahoo! maps API, which will also give > you geocoding with a much nicer interface: > > http://www.yahooapis.com/maps/rest/V1/geocode.html > > unless you specifically need to use the TeleAtlas data or the API > licensing is incompatible with the task at hand, I'd recommend using > that instead. And as a follow up, check out the Python Geocoding Toolbox: http://exogen.case.edu/projects/geopy/ It already has Yahoo! Geocoding API bindings, as well as Google Maps geocidng bindings in a nice Pythonic interface. From littlesweetmelon at gmail.com Tue Mar 4 03:22:16 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Tue, 4 Mar 2008 16:22:16 +0800 Subject: Difference between 'function' and 'method' Message-ID: Howdy everyone, This is a big problem puzzles me for a long time. The core question is: How to dynamically create methods on a class or an instance? Let me state it step by step. 1. def gunc(self): pass class A(object): def func(self): pass a = A() a.func # gives "bound method", type is "instancemethod" A.func # gives "unbound method", type is "instancemethod" gunc # gives "function", type if "function" # ?? Does this line attach a method to instance? ... I don't think so. a.gunc = gunc I found stardard library 'new' may help. Is that right? 2. a = A() # instance of old class A # Do attach a new method to class A... b = A() # instance of new class A Does "a" can get the new method automatically? Does new method have the *same* concept level with old methods? Especially, if there are classes inherit from class A, how does name resolution work on this case? 3. How do I write a decroator for a method? Eg: class A(object): @my_dec def func(self): pass Here, my_dec should return a method rathar than a function/lambda. Am I right? What does @property @staticmethod... really do? I cannot step-into them for source code. 4. If most of above questions can be solved, then it would be easy to implement the feature: "dynamic property attach". Eg: One class can read/store settings from/to some file based on the file content. # File: cfg.ini x = 1 y = python config = SettingClass('cfg.ini') # dynamically build up properties x and y. x = config.x # x will be set to 1 (str -> int convertion would be done by 'property x') y = config.y # y will be set to 'python' config.x = 9 # 'x = 9' is written to cfg.ini. How to implement ^_^ Maybe there are some library does the same thing. What is it? How to implement ? Thank you for your attention! --- ShenLei From Lie.1296 at gmail.com Mon Mar 3 16:11:07 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 3 Mar 2008 13:11:07 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> Message-ID: On Mar 2, 11:36?pm, Paul Rubin wrote: > Lie writes: > > You hit the right note, but what I meant is the numeric type > > unification would make it _appear_ to consist of a single numeric type > > (yeah, I know it isn't actually, but what appears from outside isn't > > always what's inside). > > That is clearly not intended; floats and decimals and integers are > really different from each other and Python has to treat them distinctly. In certain operations it would, such as: a = Decimal('32.324') b = 90.3453 c = 43 d = a + b + c <<< this should work without manual type casting This behavior is what is intended in numeric type unification, floats and decimals and integers should work together flawlessly without the need for manual type casting. This gives the _impression_ of a single numeric type (although programmers should still be aware that the underlying type still exists). It's true Python have to treat them differently, but programmers would be able to treat them all the same (at least in most parts) > > > Try with a=7, b=25 > > > They should still compare true, but they don't. The reason why they > > don't is because of float's finite precision, which is not exactly > > what we're talking here since it doesn't change the fact that > > multiplication and division are inverse of each other. > > What? ?Obviously they are not exact inverses for floats, as that test > shows. ?They would be inverses for mathematical reals or rationals, > but Python does not have those. When I said multiplication and division are inverse, I was pointing out the fact that even though float's inexactness make them imperfect inverse, mult & div are still inverse of each other. In-practice, the inversing behavior is impossible unless we have a way to represent real number (which we don't), and the *workaround* to make them work is to do epsilon comparison. When I'm talking about things I usually talk in purely theoretical condition first and considers practical implementations that doesn't work that way as making up a workaround inside their limitations. In this case, the theoretical condition is that multiplication and division is inverse of each other. The practical consideration is float is inexact and reals is impossible, and thus epsilon comparison is necessary to walk around float's limitations so multiplication and division could still be inverses. Aside: Python would have rationals > > One way to handle this situation is to do an epsilon aware > > comparison (as should be done with any comparison involving floats), > > but I don't do it cause my intention is to clarify the real problem > > that multiplication is indeed inverse of division and I want to > > avoid obscuring that with the epsilon comparison. > > I think you are a bit confused. ?That epsilon aware comparison thing > acknowledges that floats only approximate the behavior of mathematical > reals. ? Yes, I realized that floats aren't the same as reals. > When we do float arithmetic, we accept that "equal" often > really only means "approximately equal". ?But when we do integer > arithmetic, we do not expect or accept equality as being approximate. > Integer equality means equal, not approximately equal. ?That is why > int and float arithmetic cannot work the same way. No, no, they don't work the same way, but they should appear to work the same way as reals in pure mathematics do. Again, I'm talking in theory first: ints and floats should work the same way, but since practical considerations make them impossible, then they should at least appear to work the same way (or they would have become completely different things, remember duck typing?). From jkugler at bigfoot.com Thu Mar 27 14:23:31 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 27 Mar 2008 10:23:31 -0800 Subject: SoC project: Python-Haskell bridge - request for feedback References: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Message-ID: Micha? Janeczek wrote: > Hi, > > I am a student interested in participating in this year's SoC. > At http://tsk.ch.uj.edu.pl/~janeczek/socapp.html (and also below > in this email) you can find a draft of my project proposal. > > I'd like to ask you to comment on it, especially the deliverables > part. Are you interested in such a project, and if yes, what features > would be most important to you? Is anything missing, or should > something get more priority or attention? You might want to take a look at this: http://www.artfulcode.net/articles/extending-python-almost-anything/ That might get you started at least on the calling Haskell part. j From MartinRinehart at gmail.com Thu Mar 13 06:53:13 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 13 Mar 2008 03:53:13 -0700 (PDT) Subject: What's Going On? Message-ID: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> (Accompanied by Marvin Gaye) >>> def f(list=[0]): ... list[0]+=1 ... return list[0] ... >>> f() 1 >>> f() 2 >>> f() # 'list' is a name bound to a list (mutable) so this makes sense 3 >>> f([5]) 6 >>>f() # What's Going On? 4 Off topic: Motown chief Berry Gordy tells Gaye he won't release the "uncommercial" song. Gaye tells Gordy he'll never have another Gaye song if he doesn't release it. Gordy backs down. 2.5 million singles plus title track for blockbuster album. From darcy at druid.net Fri Mar 14 11:32:28 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 14 Mar 2008 11:32:28 -0400 Subject: %x unsigned? In-Reply-To: <87skytbbbc.fsf@mulj.homelinux.net> References: <87skytbbbc.fsf@mulj.homelinux.net> Message-ID: <20080314113228.961193b0.darcy@druid.net> On Fri, 14 Mar 2008 16:00:07 +0100 Hrvoje Niksic wrote: > The %x conversion specifier is documented in > http://docs.python.org/lib/typesseq-strings.html as "Unsigned > hexadecimal (lowercase)." What does "unsigned" refer to? > > >>> '0x%x' % 10 > '0xa' > >>> '0x%x' % -10 > '0x-a' > > Is this a bug or is %x misdocumented? I think it is working exactly as documented. It says that it displays unsigned numbers. If you give it a negative number you get undefined behaviour. Are you saying that the docs could be a little clearer? -- 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 bogus@does.not.exist.com Thu Mar 13 16:03:56 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 15:03:56 -0500 Subject: Python regex Message-ID: I hope posting is ok here for this question... I am attempting to extract the text from a CSS comment using 're' such as... string = "/* CSS comment /*" exp = "[^(/*)].*[^(*/)] " p = re.compile(exp) q = p.search(string) r = q.group() print r >>CSS comment although this works to a degree... I know the within the brackets everything is taken literally so the pattern I am to negating is "(/*)". ie. includes the parenthesis. So my question is... Is there a way to negate a pattern that is more than on character long? eg. where rather than saying if forward slash OR astrisk appear..negate. I would be saying if parenthesis AND asterisk appear in this order... negate -- Andrew From esj at harvee.org Sat Mar 1 00:43:03 2008 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 01 Mar 2008 00:43:03 -0500 Subject: Backup Script over ssh In-Reply-To: References: Message-ID: <47C8ECE7.4060309@harvee.org> Gabriel Genellina wrote: > En Wed, 27 Feb 2008 13:32:07 -0200, Christian Kortenhorst > escribi?: > >> But there is no rsync for windows without using cygwin > > That's no big deal; rsync doesn't require tons of libraries, just > cygpopt-0.dll and cygwin1.dll. See this page: > http://www.brentnorris.net/rsyncntdoc.html > If you prefer a nice GUI around it (mmm... not so nice actually :) ) > http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp > windows rsync sans gui http://www.itefix.no/phpws/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=6&MMN_position=23:23 or google cwrsync I use in conjunction with rsnapshot for backing up xp and vista machines --- eric -- Speech-recognition in use. It makes mistakes, I correct some. From exxfile at hotmail.com Mon Mar 24 20:35:28 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 17:35:28 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> Message-ID: <28afd7e0-b64a-40cf-b584-b91393d326b4@e10g2000prf.googlegroups.com> On Mar 24, 12:18?pm, George Sakkis wrote: > On Mar 24, 3:13 pm, pythonnubie wrote: > > > > > > > > > i ?have ?come across my first exeption using randrange . The exeption > > > > is " no such ?attribute " in ?module random > > > > > platform ?is xp ?home ?and the python ?build is activestate 2.5 > > > > Welcome aboard! > > > > There's definitely a randrange function in the random module, so > > > something else must be wrong. To get the most out of this list and > > > minimize wasted bandwidth, the most effective way usually consists of > > > copying and pasting: > > > 1. The offending code (or just the relevant part if it's too big). > > > 2. The full traceback of the raised exception. > > > > Regards, > > > George > > > Hwere is the complete traceback ! >>> The word is: ?index > > > Traceback (most recent call last): > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 307, in RunScript > > ? ? debugger.run(codeObject, __main__.__dict__, start_stepping=0) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \__init__.py", line 60, in run > > ? ? _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \debugger.py", line 631, in run > > ? ? exec cmd in globals, locals > > ? File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, > > in > > ? ? import random > > ? File "F:\Documents and Settings\Mark\My Documents\random.py", line > > 13, in > > ? ? distributions on the real line: > > AttributeError: 'module' object has no attribute 'randrange' > > > Why ?would it say ?it can't find the function ? > > Because you named your file 'random.py' and it shadows the standard > random module! Change the name to something else, say foo.py, and try > it again. > > George- Hide quoted text - > > - Show quoted text - Hi that was the problem I shoaswoed the random module . Thanks to everyone for their support ! Mark From george.sakkis at gmail.com Sun Mar 9 23:12:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 9 Mar 2008 20:12:58 -0700 (PDT) Subject: __iter__ yield References: Message-ID: <27d24b75-f1b5-4996-b54a-15ab2ba16593@59g2000hsb.googlegroups.com> On Mar 9, 7:37 pm, Paul Hankin wrote: > On Mar 9, 8:58 pm, duccio wrote: > > > Someone knows if it's possible to make this __iter__ function with just > > one 'yield' intead of two? > > ... > > def __iter__(self): > > yield self #1 > > for n in self.childs: > > for nn in n.__iter__(): > > yield nn #2 > > Only one yield and shorter (but not really any simpler): > > from itertools import chain > > class Node: > ... > def __iter__(self): > for x in chain([self], *self.childs): > yield x Actually this doesn't need a yield at all: class Node: ... def __iter__(self): return chain([self], *self.childs) George From nyamatongwe+thunder at gmail.com Mon Mar 17 20:16:22 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 18 Mar 2008 00:16:22 GMT Subject: Which way to access Scintilla In-Reply-To: References: Message-ID: Alex: > I also want to embed Scintilla in Tkinter-created window (create the > rest of the GUI in Tkinter), or rather, I want to know if that's > possible at all. Any suggestions are appreciated. While it may be possible with sufficient dedication, it is unlikely to be simple. If you really want to use Tkinter then you are probably better off using some existing code that uses its text widget from Python such as Idle. Neil From python at rolfvandekrol.nl Thu Mar 20 10:09:08 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Thu, 20 Mar 2008 15:09:08 +0100 Subject: Is this valid ? In-Reply-To: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> Message-ID: <47E27004.8020805@rolfvandekrol.nl> John Machin wrote: > Of course. You can chain comparisons as much as you like and is > (semi-)sensible, e.g. > Hmm, 'of course' is not the correct word for it. Although the Stef Mientki would probably be able to find it in the documentation it is not as simple as you might think. Most languages interpret a == b == 2 as (a == b) == 2, or throw an error because this syntax is not valid. The fact that python understand the obvious meaning of this code, is quite unique to Python, as far as I know. From castironpi at gmail.com Sun Mar 2 11:01:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 08:01:03 -0800 (PST) Subject: Python-based regular expression parser that allows patterns to call functions? References: Message-ID: On Mar 2, 8:41?am, Andrew Warkentin wrote: > I am writing a filtering HTTP proxy (the site ishttp://xuproxy.sourceforge.net/). I want it to be compatible with > Proxomitron (http://proxomitron.info/) filters. I need a regular > expression parser that allows patterns to call functions (or more > likely, class methods), to implement "matching commands" (look at the > Proxmitron documentation to see what I mean). Does anyone know if such a > library exists for Python, or do I have to write my own parser? To make a list of commands available: class C: def behavior( self ): pass def behavior2( self ): pass cmds= [ behavior, behavior2 ] Then search C.cmds for a match to the regular expression. C.behavior.func_name contains the string 'behavior' for checking. You might need to "bind" the contents of C.cmds before you call them too. More info available, just ask. You can also do: class C: @string_callable def behavior( self ): pass @string_callable def behavior2( self ): pass and class C: def behavior( self ): pass def behavior2( self ): pass cmds= [ 'behavior', 'behavior2' ] (strings this time), and use getattr( C, 'behavior' ) or for c= C(), getattr( c, 'behavior' ). class C: def behavior( self ): pass def behavior2( self ): pass cmds= [ 'behavior', 'behavior2' ] C.cmds= commandmap( C, C.cmds ) can generate a dictionary of strings to methods. And there's always getattr( c, strA ), for your choice of strA, which throws an exception if strA is not an attribute (method or property) of c, and hasattr( c, strA ) can test if it is. You less often want to generate distinct functions based on parameters only, but you can. c= C() def behavior3( self ): pass c.behavior3= behavior3 so c.behavior3() is legal. Where does that get you? From needin4mation at gmail.com Thu Mar 20 11:09:40 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 20 Mar 2008 08:09:40 -0700 (PDT) Subject: Can I run a python program from within emacs? Message-ID: Hi, I'm trying to learn Python. I using Aquamac an emac implementation with mac os x. I have a program. If I go to the command prompt and type pythong myprog.py, it works. Can the program be run from within the editor or is that not how development is done? I ask because I was using Visual Studio with C# and, if you're familiar, you just hit run and it works. On Python do I use the editor for editing only and then run the program from the command line? Thank you. From andreas.axelsson at gmail.com Sun Mar 30 11:58:30 2008 From: andreas.axelsson at gmail.com (axl) Date: Sun, 30 Mar 2008 08:58:30 -0700 (PDT) Subject: Build complete, now I just need to "install" it... References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: On 30 Mar, 17:40, "Ryan Ginstrom" wrote: > Another option is to compile your extensions with gcc, and specify that it > link to MSVCR71.dll as the C runtime. > > For MinGW, it's sufficient to edit the specs (e.g. in > C:\MinGW\lib\gcc\mingw32\3.4.2) like so: > *libgcc: > %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 True, I was hoping to avoid MinGW, since I've been using MSVC for ages and I know it well. Yet another package on the disk, etc... But as this seems like the simplest solution for now I'll try that. Cheers! /axl From deets at nospam.web.de Thu Mar 27 09:56:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 14:56:02 +0100 Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> Message-ID: <651ncdF2cmik2U1@mid.uni-berlin.de> king kikapu wrote: > On 27 ???, 14:35, Paul Rubin wrote: >> king kikapu writes: >> > it seems that Psyco's author will not port it for the upcoming Python >> > 3000 release :( >> >> I think the idea is it will be part of PyPy and you should use that. > > I know that his efforts are on PyPy now but i do not know when PyPy is > going to be stable and if i can use it with my current "development > stack" (PyQt, Eric4 etc). I mean, i do not know if it will be possible > to "abandon" CPYthon and use PyPy instead. Currently? No way. It's *way* to slow. Diez From jzgoda at o2.usun.pl Fri Mar 14 05:57:41 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 14 Mar 2008 10:57:41 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: References: Message-ID: Lie napisa?(a): >> foo = [1,2,3,4] >> x = foo.append(5) >> print x >> >> What will be the output (choose one): >> >> 1) [1,2,3,4] >> 2) [1,2,3,4,5] >> 3) That famous picture of Albert Einstein sticking out his tongue >> 4) Nothing - no output >> 5) None of the above >> >> I undertake to summarise answers posted to complete this "survey". > > I think I'll choose 3. Well, no, I suppose the correct behavior > _should_ be undefined (i.e. what it returns is an implementation > details that should not be relied on). The fact that it returns None > is just a "coincidence" that happens to happen every time you tested > it (you can't prove by ignorance) I think in Python there's no notion of "void" return type. Deliberate choice to return None for functions that modify objects in place seems to be OK as long as it is used consistently and documented. Which is the case. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From ss.dtvcs at gmail.com Wed Mar 5 19:16:31 2008 From: ss.dtvcs at gmail.com (ss.dtvcs at gmail.com) Date: Wed, 5 Mar 2008 16:16:31 -0800 (PST) Subject: 2nd CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems Message-ID: Apologies for any multiple copies received. We would appreciate it if you could distribute the following call for papers to any relevant mailing lists you know of. 2nd CALL FOR PAPERS =============================================================================== Special session: Design, Analysis and Tools for Integrated Circuits and Systems DATICS 2008 July 22-24, 2008 (Crete Island, Greece) http://digilander.libero.it/systemcfl/datics =============================================================================== Aims and Scope -------------- The main target of the Special Session: DATICS 2008 of the WSEAS CSCC multi-conference (http://www.wseas.org/conferences/2008/greece/icc/) is to bring together software/hardware engineering researchers, computer scientists, practitioners and people from industry to exchange theories, ideas, techniques and experiences related to all areas of design, analysis and tools for integrated circuits (e.g. digital, analog and mixed-signal circuits) and systems (e.g. real-time, hybrid and embedded systems). The special session also focuses on the field of formal methods and low power design methodologies for integrated circuits. Topics ------ Topics of interest include, but are not limited to, the following: * digital, analog, mixed-signal designs and test * RF design and test * design-for-testability and built-in self test methodologies * reconfigurable system design * high-level synthesis * EDA tools for design, testing and verification * low power design methodologies * network and system on-a-chip * application-specific SoCs * specification languages: SystemC, SystemVerilog and UML * all areas of modelling, simulation and verification * formal methods and formalisms (e.g. process algebras, petri-nets, automaton theory and BDDs) * real-time, hybrid and embedded systems * software engineering (including real-time Java, real-time UML and performance metrics) Industrial Collaborators ------------------------ DATICS 2008 is partnered with: * CEOL: Centre for Efficiency-Oriented Languages "Towards improved software timing", University College Cork, Ireland ( http://www.ceol.ucc.ie) * International Software and Productivity Engineering Institute, USA (http://www.intspei.com ) * Intelligent Support Ltd., United Kingdom (http://www.isupport- ltd.co.uk) * Minteos, Italy (http://www.minteos.com) * M.O.S.T., Italy (http://www.most.it) * Electronic Center, Italy (http://www.el-center.com) DATICS 2008 is sponsored by: 1. LS Industrial Systems, South Korea (http://eng.lsis.biz) 2. Solari, Hong Kong (http://www.solari-hk.com) Technical Program Committee --------------------------- * Prof. Vladimir Hahanov, Kharkov National University of Radio Electronics, Ukraine * Prof. Paolo Prinetto, Politecnico di Torino, Italy * Prof. Alberto Macii, Politecnico di Torino, Italy * Prof. Joongho Choi, University of Seoul, South Korea * Prof. Wei Li, Fudan University, China * Prof. Michel Schellekens, University College Cork, Ireland * Prof. Franco Fummi, University of Verona, Italy * Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea * Prof. AHM Zahirul Alam, International Islamic University Malaysia, Malaysia * Prof. Gregory Provan, University College Cork, Ireland * Dr. Emanuel Popovici, University College Cork, Ireland * Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd., South Korea * Dr. Umberto Rossi, STMicroelectronics, Italy * Dr. Graziano Pravadelli, University of Verona, Italy * Dr. Vladimir Pavlov, International Software and Productivity Engineering Institute, USA * Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands, Advanced Research Centre, The Netherlands * Dr. Thierry Vallee, Georgia Southern University, Statesboro, Georgia, USA * Dr. Menouer Boubekeur, University College Cork, Ireland * Dr. Ana Sokolova, University of Salzburg, Austria * Dr. Sergio Almerares, STMicroelectronics, Italy * Ajay Patel (Director), Intelligent Support Ltd, United Kingdom * Monica Donno (Director), Minteos, Italy * Alessandro Carlo (Manager), Research and Development Centre of FIAT, Italy * Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong University of Science and Technology, Hong Kong Important Dates --------------- March 31, 2008: Deadline for submission of completed papers May 1, 2008: Notification of acceptance/rejection to authors Please visit our web-site for further information on the hosting conference of DATICS, submission guidelines, proceedings and publications and international technical reviewers. Best regards, General Chair of DATICS: Dr. K.L. Man (University College Cork, Ireland) and Organising Committee Chair: Miss Maria O'Keeffe (University College Cork, Ireland) From amca01 at gmail.com Sun Mar 9 05:57:15 2008 From: amca01 at gmail.com (Alasdair) Date: Sun, 09 Mar 2008 20:57:15 +1100 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: Thanks, all - you've been most helpful. By the way, what does // do? I haven't yet run down its definition in the manual. -A. From jldunn2000 at googlemail.com Mon Mar 3 06:57:14 2008 From: jldunn2000 at googlemail.com (loial) Date: Mon, 3 Mar 2008 03:57:14 -0800 (PST) Subject: Delete hidden files on unix Message-ID: How can I delete hidden files on unix with python, i.e I want to do equivalent of rm .lock* From aboudouvas at panafonet.gr Fri Mar 28 05:40:35 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 28 Mar 2008 02:40:35 -0700 (PDT) Subject: Eclipse and PyDev Package explorer References: <1d4e6f2b-a058-413e-a566-674ccc733d6f@s19g2000prg.googlegroups.com> Message-ID: <9af850bd-01a3-4e6f-8cd9-d2883284db30@m44g2000hsc.googlegroups.com> A, and another one: If i set a custom builder for a pydev project, is there a way for this builder to automatically be "assigned" to every (pydev) project i will create from now on or i have to re-define it for every new one ? From stefan_ml at behnel.de Thu Mar 27 10:50:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Mar 2008 15:50:21 +0100 Subject: Psyco alternative In-Reply-To: References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: <47EBB42D.9090206@behnel.de> king kikapu wrote: >>> As for psyco, are there any alternatives to use now ? >> But ultimately, the author says that the approach is flawed, so at *some* >> point it will be discontinued. But that could be said about nearly >> everything, couldn't it? >> > It is a pity because this module *does* really solve some problems... If it's about "some problems", then maybe Cython is an alternative. http://cython.org Stefan From ken at seehart.com Sat Mar 8 01:58:23 2008 From: ken at seehart.com (Ken) Date: Fri, 07 Mar 2008 22:58:23 -0800 Subject: list of attributes Message-ID: <47D2390F.8010003@seehart.com> I have a class with a __getattr__ method that returns various methods. I also have the ability to determine the list of method names that are supported by my __getattr__ method (this list would be dynamically generated as it depends on the current state). What I would like to know is if there is a way overload the behavior of dir(instance) to include this dynamically generated list of method names. Ideally this would have the effect of making these methods visible to the autocomplete feature of debuggers in most modern IDEs. It looks like this would be __dir__ in 2.6, is that right? Ken From moonrie at gmail.com Wed Mar 12 23:19:53 2008 From: moonrie at gmail.com (moonrie) Date: Wed, 12 Mar 2008 20:19:53 -0700 (PDT) Subject: help please, splitter windows like in maya or 3ds max Message-ID: hi, everyone there, I am doing a 3D modeling project. I like to do it with Python( am a newbie), but have no idea with the wxSplitterWindow to create the 4-view windows( top, front, side, perspective), like the mfc CSplitterWnd guy), anyone can give me some help with wxPython? thanks in advance. - moonrie From dmitry.sukhov at gmail.com Thu Mar 27 08:21:08 2008 From: dmitry.sukhov at gmail.com (Sukhov Dmitry) Date: Thu, 27 Mar 2008 05:21:08 -0700 (PDT) Subject: PyGTK localisation on Win32 References: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> Message-ID: <9c795bfa-b2a1-4c72-bc69-0f5664c0d3e1@i12g2000prf.googlegroups.com> > > I had no problem with using standard gettext way of doing i18n on > Windows with PyGTK an Glade, apart some quirks with LANG environment > variable. Basically, the code that works looks like this: > > import gettext, locale > locale.setlocale(locale.LC_ALL, '') > if os.name == 'nt': > # windows hack for locale setting > lang = os.getenv('LANG') > if lang is None: > defaultLang, defaultEnc = locale.getdefaultlocale() > if defaultLang: > lang = defaultLang > if lang: > os.environ['LANG'] = lang > gtk.glade.bindtextdomain(appname, translation_dir) > gtk.glade.textdomain(appname) > gettext.install(appname, translation_dir, unicode=True) > > Be aware, that you can not change the locale setting from the command > line like you do on Linux. > I have the same problem. I did all as you wrote. gettext translations do work fine. But translations in glade does not work. The only way to turn it on is to set environment variable LANG explicitly before program run: set LANG=ru_RU python test.py From deets at nospam.web.de Tue Mar 11 03:50:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Mar 2008 08:50:37 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: <877541e6-1407-4c0d-9818-e500f38823d5@o77g2000hsf.googlegroups.com> References: <63i6j9F2793buU1@mid.uni-berlin.de> <63lqcuF27pbnbU1@mid.uni-berlin.de> <877541e6-1407-4c0d-9818-e500f38823d5@o77g2000hsf.googlegroups.com> Message-ID: <63mruiF26r9e6U1@mid.uni-berlin.de> Chris schrieb: > If all you wanted was some grouping of exceptions why not something > like... > > soft_exception_list = [IndexError, TypeError] > hard_exception_list = [ZeroDivision] > > try: > do_something() > except Exception, e: > if e.__class__ in soft_exception_list: > handle_soft_exception() > elif e.__class__ in hard_exception_list: > handle_hard_exception() > else: > raise NotImplementedError > > Granted you're most likely looking for something that does this > constantly on every line of code though... It's not about grouping, which would be done better with inheritance by the way. Its about not raising certain exceptions if there is no handler. Diez From cyu021 at gmail.com Fri Mar 14 07:15:28 2008 From: cyu021 at gmail.com (James Yu) Date: Fri, 14 Mar 2008 19:15:28 +0800 Subject: How to import custom python file in python server page (psp) ? Message-ID: <60bb95410803140415x621b5b23w75b83013997c750b@mail.gmail.com> Hi folks, I prepared a python script for dynamically get the absolute paths of the files in certain folder. Then I tried to invoke that function from my web server in a .psp file like this: 1 2 3 asdfasdfasdfa 4 5 <% 6 import glob 7 import os 8 *import Helper * 9 10 body = '' 11 top = 'asdfasdfasdfa' 12 links = {} 13 *Helper.GetLinks(top=top) * 14 *paths = Helper.GenLinkPath(links) * 15 body = paths 16 %> 17 <%=body%> 18 19 However, this is the error message I received when I open the page in a browser: > Mod_python error: "PythonHandler mod_python.psp" > > Traceback (most recent call last): > > File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, > in HandlerDispatch > result = object(req) > > File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 302, in > handler > p.run() > > File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 213, in > run > exec code in global_scope > > File "/var/www/.cyu021/.pic/index.psp", line 8, in > import Helper > > ImportError: No module named Helper *PS. I put Helper.py and index.psp in the same dir * Thanks in advance, -- This is a UTF-8 formatted mail ----------------------------------------------- James C.-C.Yu -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Mar 14 04:09:37 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Mar 2008 09:09:37 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: Dave Kuhlman wrote: > Arnaud Delobelle wrote: > >> >> 4. Both points above follow from the fact that foo.bar is really a >> function call that returns a (potentially) new object: in fact what >> really happens is something like > > Arnaud and Imri, too - > > No. foo.bar is *not* really a function/method call. > >> >> Foo.__dict__['bar'].__get__(foo, Foo). >> >> So every time foo.bar is executed an object is (or may be) created, >> with a new id. >> >> HTH > > I appreciate the help, but ... > > Actually, it does not help, because ... > > My understanding is that foo.bar does *not* create a new object. All it > does is return the value of the bar attribute of object foo. What new > object is being created? If the attribute has a __get__() method that's completely under the attribute's control: >>> class Bar(object): ... def __get__(self, *args): ... print "__get__%s" % (args,) ... return self.next() ... def next(self): ... self.count += 1 ... return self.count ... count = -1 ... >>> class Foo(object): ... bar = Bar() ... def __repr__(self): return "foo" ... >>> foo = Foo() >>> foo.bar __get__(foo, ) 0 >>> foo.bar __get__(foo, ) 1 >>> foo.bar __get__(foo, ) 2 >>> getattr(foo, "bar") __get__(foo, ) 3 Peter From frikker at gmail.com Mon Mar 3 16:43:17 2008 From: frikker at gmail.com (blaine) Date: Mon, 3 Mar 2008 13:43:17 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> Message-ID: <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> > pyserial is pure python, so I don't see how it's going to be > any more painful than something you write yourself. If you > want something that's more of a transparent object wrapper > aroudn the Posix serial interface, there's PosixSerial.py (upon > which pyserial's posix support is based): > > ftp://ftp.visi.com/users/grante/python/PosixSerial.py > > -- > Grant Edwards grante Yow! Everybody gets free > at BORSCHT! > visi.com Oh - good point. There wouldn't be any compilation issues with the C api. Nevermind! :) I do have a question though. In the termios module, I am attempting to set the baud rate to 921600, which is what we use with 'cutecom' (because minicom does not have this as an option) and is what the supplier recommends. When I try to set the rate using termios.tcsetattr(), I get an Argument Error. I do not get this when I use an existing baud rate, such as termios.B9600. Is there a way I can get around this? We would like to use it at full speed. Thank you, Blaine From __peter__ at web.de Wed Mar 19 05:50:52 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Mar 2008 10:50:52 +0100 Subject: Is there a way to get __thismodule__? References: Message-ID: benhoyt wrote: > Is there a way to get __thismodule__ in Python? That is, the current > module you're in. Or isn't that known until the end of the module? > > For instance, if I'm writing a module of message types/classes, like > so: > > class SetupMessage(Message): > number = 1 > > class ResetMessage(Message): > number = 2 > > class OtherMessage(Message): > number = 255 > > nmap = { # maps message numbers to message classes > 1: SetupMessage, > 2: ResetMessage, > 255: OtherMessage, > } > > Or something similar. But adding each message class manually to the > dict at the end feels like repeating myself, and is error-prone. It'd > be nice if I could just create the dict automatically, something like > so: > > nmap = {} > for name in dir(__thismodule__): > attr = getattr(__thismodule__, name) > if isinstance(attr, Message): > nmap[attr.number] = attr > > Or something similar. Any ideas? Use globals(): def is_true_subclass(a, b): try: return issubclass(a, b) and a is not b except TypeError: return False nmap = dict((m.number, m) for m in globals().itervalues() if is_true_subclass(m, Message)) print nmap You may also rely on duck-typing, assuming that everything that has a number attribute is a Message subclass: nmap = dict((m.number, m) for m in globals().itervalues() if hasattr(m, "number")) Peter From fakeaddress at nowhere.org Sat Mar 29 02:46:20 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 29 Mar 2008 06:46:20 GMT Subject: why does socket.makefile require non-blocking mode? In-Reply-To: References: Message-ID: <0BlHj.26232$Ch6.6951@newssvr11.news.prodigy.net> Forest wrote: > The socket.makefile() docs say, "the socket must be in blocking mode." I > don't see any explanation of why blocking mode is required, and I'm not sure > whether that means timeout mode is forbidden as well. Can someone clarify > this? Looking at the code for the existing _fileobject's read method, it will loose data it has already read if a socket.recv() call raises an exception. The function keeps buffers in a local variable that will be lost if an exception exits the scope. That much could be fixed with a try...finally. Other methods have similar problems. > I wanted to use file-like objects with socket timeouts, so I ended up writing > my own replacement for socket._fileobject. I'd appreciate it if someone could > either explain to my why my new class was unnecessary, or else encourage me to > contribute it as a patch to the socket module. Sure, fix it. A harder problem is that it doesn't play nice with select(). -- --Bryan From ttsiodras at gmail.com Fri Mar 28 09:29:21 2008 From: ttsiodras at gmail.com (ttsiodras at gmail.com) Date: Fri, 28 Mar 2008 06:29:21 -0700 (PDT) Subject: Global variables in modules... Message-ID: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> With a.py containing this: ========== a.py =========== #!/usr/bin/env python import b g = 0 def main(): global g g = 1 b.callb() if __name__ == "__main__": main() ========================== ...and b.py containing... ========= b.py ============= import a, sys def callb(): print a.g ========================== ...can someone explain why invoking a.py prints 0? I would have thought that the global variable 'g' of module 'a' would be set to 1... From pavlovevidence at gmail.com Tue Mar 4 10:17:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 4 Mar 2008 07:17:39 -0800 (PST) Subject: for-else References: Message-ID: On Mar 4, 8:27 am, bearophileH... at lycos.com wrote: > So far in Python I've almost hated the 'else' of the 'for' loops: > - I have problems to remember its meaning; > - It gives me little problems when I later want to translate Python > code to other languages (and you always have to translate long-lived > code). > - I have used it only once, so far. > > So so far I'd liked to see it removed from Python 3.0. > > But then this article:http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel... > has shown me that my problems with the 'else' of the 'for' mostly come > from just its bad naming. The converge language is yet another very > Python-like language, and it uses a better naming (the word > "exhausted" is long and has a complex spelling for non-English > speakers, so it's not perfect): > > for ...: > ... > exhausted: > ... > broken: > ... > > The meaning is explicit. While "else" seems to mean little there. > So I may like something similar for Python 3.x (or the removal of the > "else"). I would not be opposed to this on its own merits, but there is a rationale behind the name "else". If you consider a for loop to be a rolled-up if...elif...else statement (situations where this is reasonable tend to be the same ones were else would be useful), then the "else" clause would remain unchanged on the for loop. For instance, if you have a (trivial) if...elif...else like this: if a == 0: do_task_0() elif a == 1: do_task_1() elif a == 2: do_task_2() else: do_default_task() You could roll it up into a for...else statement like this: for i in range(3): if a == i: do_task[a]() else: do_default_task() (Please never mind the trivialness of this example; I know you can eliminate the for loop altogether; this is JUST an example.) I keep this analogy in mind when using for...else to keep the semantics straight. Carl Banks From duncan.booth at invalid.invalid Mon Mar 17 06:21:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 10:21:32 GMT Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <47DD33D7.2020300@timgolden.me.uk> Message-ID: "Tom Stambaugh" wrote: > For example, the new (!) simplejson (v1.7.4) doesn't compile correctly > (on my WinXP system, at least) with either any current MS or MinGW > compiler. Oh, I know I can make it work if I spend enough time on it > -- but the binary egg I eventually found seems to work just fine. I've also just spent a while getting simplejson 1.7.4 to install on a (non- windows) system without a C compiler. The trick is to unzip the tar file and then before you try to install it delete everything in simplejson.egg-info. Then 'setup.py install' will run to completion and while it warns about 'speedups are not enabled.' it doesn't take it as fatal error. Without this step it preserves the reference to native_libs.txt in SOURCES.txt even though the native_libs.txt file itself gets deleted. From Lie.1296 at gmail.com Sat Mar 29 15:18:27 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 29 Mar 2008 12:18:27 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: On Mar 30, 1:24 am, Duncan Booth wrote: > Lie wrote: > > You're forcing your argument too much, both != and <> are NOT standard > > mathematics operators -- the standard not-equal operator is >< -- and > > I can assure you that both != and <> won't be comprehensible to non- > > programmers. > > My maths may be a bit rusty, but I always thought that the standard not- > equal operator was like an = sign but with a diagonal slash through it as > displayed when you do: > > print u'\u2260' Ah yes, that is also used (I completely forgot about that one, my math's aren't that sharp anymore) and I think it's used more frequently than ><. Some books use >< while most use ?, but my argument was that no math book use != or <> (except in math for programmers). From janeczek at gmail.com Mon Mar 24 16:37:03 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Mon, 24 Mar 2008 21:37:03 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback Message-ID: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Hi, I am a student interested in participating in this year's SoC. At http://tsk.ch.uj.edu.pl/~janeczek/socapp.html (and also below in this email) you can find a draft of my project proposal. I'd like to ask you to comment on it, especially the deliverables part. Are you interested in such a project, and if yes, what features would be most important to you? Is anything missing, or should something get more priority or attention? Regards, Michal Python-Haskell bridge ===================== Description ----------- This project will seek to provide a comprehensive, high level (and thus easy to use) binding between Haskell and Python programming languages. This will allow using libraries of either side from each language. Benefits for Python ------------------- * Robust, high assurance components It might be beneficial to implement safety-critical components in a strongly, statically typed language, using Python to keep them together. Cryptography or authentication modules can be an example. * Performance improvements for speed-critical code Haskell compiled to native code is typically an order of magnitude faster than Python. Aside from that, advanced language features (such as multicore parallel runtime, very lightweight threads and software transactional memory) further serve in improving the performance. Haskell could become a safe, high level alternative to commonly used C extensions. * Access to sophisticated libraries While its set of libraries is not as comprehensive as that of Python, Haskell can still offer some well tested, efficient libraries. Examples might be rich parser combinator libraries (like Parsec) and persistent, functional data structures. QuickCheck testing library could also be used to drive analysis of Python code. Benefits for Haskell -------------------- The project would benefit Haskell by providing it with access to an impressive suite of libraries. It also has a potential to help Haskell adoption, by mitigating risk of using Haskell in a project. Deliverables ------------ * A low level library to access Python objects from Haskell * A set of low level functions to convert built-in data types between Haskell and Python (strings, numbers, lists, dictionaries, functions, generators etc.) * A higher level library allowing easy (transparent) access to Python functions from Haskell, and wrapping Haskell functions for Python to access * A way to easily derive conversion functions for user-defined data types/objects. Functions derived in such a way should work well with both low level and high level access libraries * Documentation and a set of examples for all of above Optional goals -------------- These are of lower priority, and might require a fair amount of work. I would like to implement most of them, if technically feasible. If they don't fit into Summer of Code timeframe, I am planning to finish afterwards. * A Python module for accessing functions from Haskell modules without manual wrapping (such wrapping should be already easy thanks to the high level library). It'd be accomplished through GHC api - if it allows it. The Haskell side of the high level library will already support such mode of operation * Extend and refactor the code, to make it support other similar dynamic languages. This is a lot of work, and definitely out of the scope of Summer of Code project, but some design decisions may be influenced by this. Related projects ---------------- They (and quite possibly some others) will be referenced for ideas. * MissingPy Provides a one way, low level binding to Python. Some of the code can be possibly reused, especially data conversion functions. It doesn't seem to export all features, in particular function callbacks are not supported * HaXR XML-RPC binding for Haskell. It could provide inspiration for reconciling Haskell and Python type systems, resulting in a friendly interface * rocaml A binding between Ruby and OCaml From fetchinson at googlemail.com Thu Mar 13 21:59:55 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 13 Mar 2008 18:59:55 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > Since you seem to know quite a bit about this topic, what is your > > opinion on the apparently 'generic' algorithm described here: > > http://grail.cs.washington.edu/projects/query/ ? > > So far it seems to me that it does what I'm asking for, it does even > > more because it can take a hand drawn sample image and query the > > database for similar photos. > > > > There is even a python implementation for it here: > > http://members.tripod.com/~edcjones/pycode.html > > > > On the histogram method I agree that it won't work partly because of > > what you say and partly because it is terribly slow since it's > > comparing every single pixel. > > I'm hardly the expert and can't answer authoritatively, but here's my 2c. > > I can't comment as to the actual accuracy of the algorithm, since it > will depend on your specific data set (set of photos). The algorithm is > sensitive to spatial and luminance information (because of the YIQ > colorspace), so there are simple ways in which it will fail. > > The histogram method uses only color, but has a lot of numbers to > compare. You may find the histogram method insensitive to spatial > relations (a landscape with the mountain on the left and one with the > mountain on the right) compared to the wavelet approach. > > This is a relatively old paper, and I've seen other more recent image > retrieval research using wavelets (some cases using only the > high-frequency wavelets for "texture" information instead of the > low-frequency ones used by this paper for "shape") and other information > retrieval-related research using lossy compressed data as the features. > If you have time, you may want to look at other research that cite this > particular paper. > > And just a thought: Instead of merely cutting off at m largest-wavelets, > why not apply a quantization matrix to all the values? I'm not at all an expert, just started to look into image matching, so I'm not quite sure what you mean. What's a quantization matrix in this context? From jura.grozni at gmail.com Thu Mar 13 14:26:01 2008 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Mar 2008 11:26:01 -0700 (PDT) Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> <63t1tnF29egotU1@mid.uni-berlin.de> <63t895F298us9U1@mid.uni-berlin.de> Message-ID: On Mar 13, 6:57?pm, "Diez B. Roggisch" wrote: > azrael wrote: > > I thought of using Temp files but I am afraid of the JPG destorsion > > while saving because of the compresion.I am looking for a way to > > directly transform it. > > Then don't use JPEG, use PNG. It's lossless. > > Diez thnx. i did't think about that. i totaly forgot png. From jstanforth at gmail.com Thu Mar 13 07:32:55 2008 From: jstanforth at gmail.com (John at Quintivity) Date: Thu, 13 Mar 2008 04:32:55 -0700 Subject: help please, splitter windows like in maya or 3ds max In-Reply-To: <1dab98f7-7a29-4afb-b9ef-9728d133697d@s13g2000prd.googlegroups.com> References: <1dab98f7-7a29-4afb-b9ef-9728d133697d@s13g2000prd.googlegroups.com> Message-ID: <813f79f60803130432g3404854ch27a52b571d5e011d@mail.gmail.com> Sounds like this might do exactly what you need... http://xoomer.alice.it/infinity77/main/FourWaySplitter.html Cheers, John On Thu, Mar 13, 2008 at 1:45 AM, moonrie wrote: > On Mar 13, 12:47 pm, "Andrew Rekdal" <@comcast.net> wrote: > > This seems to work... split then split each side. then tandem the size. > > > > import wx > > > > class Layout(wx.Frame): > > > > def __init__(self, parent, id, title): > > > > wx.Frame.__init__(self, parent, id, title) > > > > sizer = wx.BoxSizer(wx.HORIZONTAL) > > > > panel = wx.Panel(self,-1) > > > > splitter = wx.SplitterWindow(panel) > > > > sizer_left = wx.BoxSizer(wx.VERTICAL) > > > > panel_left = wx.Panel(splitter,-1) > > > > splitter_left = wx.SplitterWindow(panel_left) > > > > splitter_left.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.leftChange > ,id=splitter_left.GetId()) > > > > panel_left_upper = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > > > panel_left_upper.SetBackgroundColour("WHITE") > > > > panel_left_lower = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > > > splitter_left.SplitHorizontally(panel_left_upper,panel_left_lower) > > > > sizer_left.Add(splitter_left,1,wx.EXPAND) > > > > sizer_right = wx.BoxSizer(wx.VERTICAL) > > > > panel_right = wx.Panel(splitter,-1) > > > > splitter_right =wx.SplitterWindow(panel_right) > > > > splitter_right.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.rightChange > ,id=splitter_right.GetId()) > > > > panel_right_upper = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > > > panel_right_lower = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > > > panel_right_lower.SetBackgroundColour("WHITE") > > > > splitter_right.SplitHorizontally(panel_right_upper,panel_right_lower) > > > > sizer_right.Add(splitter_right,1,wx.EXPAND) > > > > splitter.SplitVertically(panel_left,panel_right) > > > > sizer.Add(splitter,1,wx.EXPAND) > > > > panel.SetSizer(sizer) > > > > panel_left.SetSizer(sizer_left) > > > > panel_right.SetSizer(sizer_right) > > > > self.splitter_left = splitter_left > > > > self.splitter_right = splitter_right > > > > def leftChange(self,event): > > > > pos = self.splitter_left.GetSashPosition() > > > > self.splitter_right.SetSashPosition(pos) > > > > event.Skip() > > > > def rightChange(self,event): > > > > pos = self.splitter_right.GetSashPosition() > > > > self.splitter_left.SetSashPosition(pos) > > > > event.Skip() > > > > app = wx.App(0) > > > > k = Layout(None, -1, 'layout.py') > > > > k.Show(True) > > > > app.MainLoop() > > > > -- Andrew > > > > ----- Original Message ----- > > From: "moonrie" > > > > Newsgroups: comp.lang.python > > Sent: Wednesday, March 12, 2008 10:19 PM > > Subject: help please, splitter windows like in maya or 3ds max > > > > > hi, everyone there, I am doing a 3D modeling project. I like to do it > > > with Python( am a newbie), but have no idea with the wxSplitterWindow > > > to create the 4-view windows( top, front, side, perspective), like the > > > mfc CSplitterWnd guy), > > > anyone can give me some help with wxPython? > > > > > thanks in advance. > > > > > - moonrie > > should be these ones, > > thanks, :P > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Thu Mar 6 11:03:42 2008 From: python at bdurham.com (Malcolm Greene) Date: Thu, 06 Mar 2008 11:03:42 -0500 Subject: Does python support working with password protected zip files? Message-ID: <1204819422.29123.1240935267@webmail.messagingengine.com> I'm new to Python and trying to figure out how to read and write to password protected zip files. I can work with plain zip files no problem. I've googled this topic and am coming up empty except for a post on Nabbler.com that seemed to imply that password protected zip files may(???) be supported in Python 2.6 and ads for a commercial Windows (only) zip component from chilkat.com. Any suggestions? Thank you, Malcolm From Robert.Bossy at jouy.inra.fr Tue Mar 25 13:01:08 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 18:01:08 +0100 Subject: Inheritance question In-Reply-To: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <47E92FD4.2070204@jouy.inra.fr> Hi, I'm not sure what you're trying to actually achieve, but it seems that you want an identificator for classes, not for instances. In this case, setting the id should be kept out of __init__ since it is an instance initializer: make id static and thus getid() a classmethod. Furthermore, if you have several Foo subclasses and subsubclasses, etc. and still want to use the same identificator scheme, the getid() method would better be defined once for ever in Foo. I propose you the following: class Foo(object): id = 1 def getid(cls): if cls == Foo: return str(cls.id) return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the parent id and append its own id getid = classmethod(getid) class FooSon(Foo): id = 2 class Bar(Foo): id = 3 class Toto(Bar): id = 1 # Show me that this works for cls in [Foo, FooSon, Bar, Toto]: inst = cls() print '%s id: %s\n also can getid from an instance: %s\n' % (cls.__name__, cls.getid(), inst.getid()) One advantage of this approach is that you don't have to redefine the getid() method for each Foo child and descendent. Unfortunately, the "cls.__bases__[0]" part makes getid() to work if and only if the first base class is Foo or a subclass of Foo. You're not using multiple inheritance, are you? RB From jeff at schwabcenter.com Sun Mar 2 18:23:45 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 15:23:45 -0800 Subject: First post from a Python newbiw In-Reply-To: <5e3f7c46-802a-4305-984e-718ce2045f31@i29g2000prf.googlegroups.com> References: <62vrleF24ontgU2@mid.uni-berlin.de> <5e3f7c46-802a-4305-984e-718ce2045f31@i29g2000prf.googlegroups.com> Message-ID: <5MSdnavOndBMq1banZ2dnUVZ_oTinZ2d@comcast.com> castironpi at gmail.com wrote: >>>>> is there a better way of creating d?? >>>> a = [[0] * 3 for dummy in xrange(3)] >> Each element of a refers to a distinct array. >> >>> Why not simply [[0]*3]*3 ? >> All three elements of the result refer to the same array. > > ... whereas you reassign all three elements of [0]* 3. > >>>> ((0,)*3,)*3 > ((0, 0, 0), (0, 0, 0), (0, 0, 0)) > > You're safe in this one-- changing [0][0] won't change [1][0], 'cuz > you can't! A technically correct solution. :) From bearophileHUGS at lycos.com Sun Mar 30 07:27:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 30 Mar 2008 04:27:49 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <13uut2uabcbok38@corp.supernews.com> Message-ID: <5fcc899a-570e-4bc0-8091-1c966c1016c4@m73g2000hsh.googlegroups.com> hdante: > it's already time that programmer editors > have input methods advanced enough for generating this: > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) Take a look at Fortress language, by Sun. A free (slow) interpreter is already available. (Mathematica too allows you to write those symbols, but it costs a lot, and (despite tons of good things it has) as *programming language* it's awful, IHMO). Steven D'Aprano: > In Python we can write the above as: > if x != 0: > [f1(y) if y >= 0 else f2(y) for y in s] Your code builds an actual array (Python list) of results, while I think the original code just calls f1/f2. Bye, bearophile From mlists.sgv at gmail.com Wed Mar 19 03:24:41 2008 From: mlists.sgv at gmail.com (Sanjaya Vitharana) Date: Wed, 19 Mar 2008 12:54:41 +0530 Subject: Search the command history - Python Shell Message-ID: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> Hi All, Are there any simillar key combination in Python Shell like Linux Ctrl+R (reverse-i-search) to search the command history? Thanks. Sanjaya Vitharana -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Sun Mar 9 07:21:54 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 09 Mar 2008 07:21:54 -0400 Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: Lie wrote: [ ... ] > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. For example, if a variable turns into NoneType, > it'll raise Soft Exception that it have become NoneException, > programmers that wants to handle it can handle it with a try...except > block while programmers that doesn't care about it (or know it won't > be a problem to his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in > a way that Hard Exception must be handled at all cost or the program > will be terminated while Soft Exception allow programmers not to > handle it if they don't want to. [ ... ] > Ideology Base: > - EAAP: Easier to apologize than to ask permission. Sort of like a COME FROM statement. Drastic effects on program execution: a `raise SoftException` in the middle of a loop would break the loop if a catcher existed, or leave the loop running if not. It would really need the ability to resume after catching an exception. You can't really talk about 'apologize' around something that's so irreparable. I'd try for this effect by creating a class of objects with well-defined callbacks. Mel. From martin.laloux at gmail.com Sat Mar 15 16:42:49 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Sat, 15 Mar 2008 13:42:49 -0700 (PDT) Subject: Getting started with OS X Leopard References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Message-ID: if you are not satisfied with the native version, why not install the official version directly from python site http://www.python.org/download/ (macpython) instead of using that of macports. It moreover is provided with many utilities There is a macpython list that you can consult at http://www.nabble.com/Python---pythonmac-sig-f2970.html From craigm3604 at gmail.com Wed Mar 26 07:27:26 2008 From: craigm3604 at gmail.com (Craig) Date: Wed, 26 Mar 2008 04:27:26 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> <8fd0d8bd-c80a-4ec1-a70a-ea659a84413e@e6g2000prf.googlegroups.com> <13uh5bq2ri0280a@corp.supernews.com> <13ujk0ffekb3lc3@corp.supernews.com> Message-ID: On Mar 26, 12:24 am, Dennis Lee Bieber wrote: > On Tue, 25 Mar 2008 08:24:13 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > 41 0 0 0 > > 7 0 0 0 > > Which makes sense for two reasons: > > 1. It would only return the non-space-filled part of the returned key. > > 2. At least from VB6, the variable does not even have to be used > > before the call. > > Hmmm... I wonder what the library would have done if you just passed > a 0 to it... Rather than even doing that SysAlloc...() mess... > > PriKey = ctypes.int32(0) #or whatever the syntax was > > ... byref(PriKey) > > May with an effective null pointer the library would just allocate > directly rather than trying to determine the length field of the one > passed in. > > Something for the future, maybe... > > > print " DistID = \x22%s\x22" % DCOD.DistID > > You realize you can avoid those \x22 literals by changing the outer > quotes? > > print ' DistID = "%s" ' % .... > > or using triples > > print """ DistID = "%s" """ % ... > > > > > In other files, some of those fields are VB6 currency types, which > > have been described as 8-byte integers with an implied 4 decimal > > places (which I guess would be __int64 or c_longlong and then divide > > by 10,000, or simply put a decimal point 4 away from the end). > > Don't divide directly; you might lose significance as the result is > converted to double-precision float. > > You could possibly convert to string, splice in that . and then pass > the result to the Decimal module/type... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ I made these changes: # SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) SecKey = c_int32(0) ci_SecKey = c_int32(SecKey) # PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) PriKey = c_int32(0) ci_PriKey = c_int32(PriKey) And got: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 123, in ci_SecKey = c_int32(SecKey) TypeError: an integer is required Creating 2 "dummy" BSTR's isn't too bad of an option anyway. No, being somewhat new I didn't realize I could use (') in place if (") if I wanted to use a (") as a literal, but it seems to make a lot of sense now. I don't understand why I never tried it. As for the division vs. string manipulation, I agree - the string seems to be the simplest way to insure no loss of data. Thanks for all the input. From DustanGroups at gmail.com Thu Mar 13 08:42:05 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 13 Mar 2008 05:42:05 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> On Mar 13, 2:36 am, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above 5. From steve at REMOVE-THIS-cybersource.com.au Mon Mar 10 12:37:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Mar 2008 16:37:04 -0000 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <13taotgb321gn41@corp.supernews.com> On Mon, 10 Mar 2008 14:29:48 +0000, Andrew Koenig wrote: > So the question you need to answer is whether you want to determine > whether an object is exactly of type dict, or whether it you are willing > to accept types derived from dict also. Or other mappings that don't inherit from dict but behave just like dicts, such as UserDict. -- Steven From menosaint at gmail.com Fri Mar 14 01:44:54 2008 From: menosaint at gmail.com (menosaint at gmail.com) Date: Thu, 13 Mar 2008 22:44:54 -0700 (PDT) Subject: newbie question structure of function References: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> <37088f9c-e68e-483e-92a3-e730411a79bf@2g2000hsn.googlegroups.com> Message-ID: <5313a050-612f-47f9-ac3c-483888d10ece@i7g2000prf.googlegroups.com> Aaron thanx for the input > > resultname=""" > > That starts a string literal. i am not sure if this is the right way..i used it in case matchdistance < threshold return False.then the filename will not be taken from the filenameslist and so returns as an empty string. > > return (matchdistance,resultname) > > Parentheses optional there too. "return matchdistance," returns a > 'one-tuple'. but then the call matchvalue,matchfilename=findmatchingfile() will give ValueError trying to unpack from a one-tuple if anyone can suggest a more decent way of doing this pls do thanx vincent From castironpi at gmail.com Wed Mar 5 10:23:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 07:23:10 -0800 (PST) Subject: Protocol for thread communication References: Message-ID: On Mar 4, 11:12?pm, Michael Torrie wrote: > Does anyone have any recommended ideas/ways of implementing a proper > control and status protocol for communicating with threads? ?I have a > program that spawns a few worker threads, and I'd like a good, clean way > of communicating the status of these threads back to the main thread. > Each thread (wrapped in a very simple class) has only a few states, and > progress levels in those states. ?And sometimes they can error out, > although if the main thread knew about it, it could ask the thread to > retry (start over). ?How would any of you do this? ?A callback method > that the thread can call (synchronizing one-way variables isn't a > problem)? ?A queue? ?How would the main thread check these things? > Currently the main thread is polling some simple status variables. ?This > works, and polling will likely continue to be the simplest and easiest > way, but simple status variables are very limited. ?Are there any > pythonic patterns people have developed for this. > > thanks. > > Michael It depends on the messages. In the general form, 'do X', there are a lot of specifics relevant. - Do X at time T - for relative time T - for absolute time T - for conditional time T While the wording is vague, it illustrates a contrast. - Do X at time T - relative T -- T is a time offset into the future - absolute time T -- T is an absolute time, independent of the rest of the program - conditional time T -- under certain conditions, such as, right after X' finishes, right before X' starts, if Y happens during X In the big picture, the choice of X is irrelevant. However, in a particular PL, in a particular data, encapsulation, or abstraction model, some combinations of ( T, X ) may be impossible, or even long- winded, ugly, or wordy. For the idealists, an pure imperative model may fit best, so let X = 'set a bit', and conflict never arises. However such one restricts the universal turing machine-- can only write one value, which may or may not forbid solution of some problems. But without loss of generality, for X in { set B, reset B }, you have a conflict when for OPS= { (T1, X1), (T1, X2) }, X1= set B, and X2= reset B. Then there exists an ( X, T ) such that the semantics of the program are undefined. From fdrake at acm.org Sun Mar 2 21:22:27 2008 From: fdrake at acm.org (Fred Drake) Date: Sun, 2 Mar 2008 21:22:27 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: On Mar 2, 2008, at 8:35 PM, Kevin Teague wrote: > This issue was fixed for Python 2.5. As the issue notes, you can > work around it with: > > ./configure MACOSX_DEPLOYMENT_TARGET=10.5 Indeed, that works wonderfully for me for 2.4.5. > But it would be really nice if the configure fix for 2.5 was > backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped > system builds for 2.4 going direct from 2.3 -> 2.5. Yes, it would be very nice if this worked out of the box on Mac OS X 10.5.2. It's definitely a surprise for those of us who built our 2.4.4 on Mac OS X 10.4.x. -Fred -- Fred Drake From castironpi at gmail.com Sat Mar 29 05:08:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 02:08:20 -0700 (PDT) Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> Message-ID: <26eb664d-9bb4-4ef2-a839-994af666903a@d1g2000hsg.googlegroups.com> On Mar 28, 3:59?pm, castiro... at gmail.com wrote: > I want to regression a signal. ?It's NN, not necessarily, sine wave. > What kind of numbers of harmonic simultaneous sounds are we looking > at? ?How close to an A 440 can a human make? > > I want recognition to alert me. ?As a sine wave is coming in: > > >>> for t in [ ( 200* sin( x*2 ), 200* cos( x*2 ) ) for x in range( 10 ) ]: print( *t ) > > ... > 0.0 200.0 > 181.859485365 -83.2293673094 > -151.360499062 -130.728724173 > -55.8830996398 192.03405733 > 197.871649325 -29.1000067617 > -108.804222178 -167.814305815 > -107.3145836 168.770791746 > 198.121471139 27.3474436416 > -57.580663333 -191.531896065 > -150.197449354 132.063341649 > > Did everyone take the course on computer architecture? E.g. sum() is not an operation you do in world operations. (i question that 'walk' is.) you don't ( add ) drop to puddle, you move drop. we've all got graphics sub-primitives but no modelling ones. you don't want to decode sense cell inputs, do you? i'd say in complexity, one cell adds up to an entire input line-trail (wake). I would be proposing multiplexcating every CPU unit onto every input gate: off keystrokes and camera photovoltaics. (Light takes six - complexity- muscles, plus squinting, while not six calory-muscles.) So, taking outputs to be common combinations of inputs, unless you want symbological inputs to map to anything constructive. I think we design architecture utility-first. Ste p1. Big box? Would calculations include utility transponders (tabulation)? Time-scale is discretized. Can you be more productive continuously? Do you need to recognize users discretely, each an own interaction on file, due to discrete measures (discrete times)? It's more robotic than our interface with dogs. Does anyone have names for syllables? Superlatives are always theoretical. What can we learn from an executed time-space translation? Point is, sum() is not real, add is. I think event-driven stuff. It's non-destructive. Are there other tables after D.J.? He's predictable alright. Broadcast dropoff "sighted" (recognized). Is that bandwidth or baud? How quickly can you get total human decible out of a room? From grahn+nntp at snipabacken.se Sun Mar 30 17:50:25 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 21:50:25 GMT Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> <7x4paqy0sr.fsf@ruckus.brouhaha.com> <13uqqml7sk05ec8@corp.supernews.com> Message-ID: On Fri, 28 Mar 2008 22:01:57 -0000, Grant Edwards wrote: > On 2008-03-28, Paul Rubin wrote: >> castironpi at gmail.com writes: >>> Did everyone take the course on computer architecture? >> >> Yow! Does your SPEED QUEEN have CABLE? > > Ya know, I was thinking about trying to find an updated file of > Zippy quotes for use in my .sig, but I decided that having all > of the pop culture references be 30-years out of date was part > of the charm. "I hope the ''Eurythmics'' practice birth control ..." More like 20--25 years. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From Robert.Bossy at jouy.inra.fr Tue Mar 4 07:47:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 04 Mar 2008 13:47:57 +0100 Subject: Eurosymbol in xml document In-Reply-To: <634sleF25sd22U1@mid.uni-berlin.de> References: <634sleF25sd22U1@mid.uni-berlin.de> Message-ID: <47CD44FD.40206@jouy.inra.fr> Diez B. Roggisch wrote: > Hellmut Weber wrote: > > >> Hi, >> i'm new here in this list. >> >> i'm developing a little program using an xml document. So far it's easy >> going, but when parsing an xml document which contains the EURO symbol >> ('?') then I get an error: >> >> UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in >> position 11834: character maps to >> >> the relevant piece of code is: >> >> from xml.dom.minidom import Document, parse, parseString >> ... >> doc = parse(inFIleName) >> > > The contents of the file must be encoded with the proper encoding which is > given in the XML-header, or has to be utf-8 if no header is given. > > From the above I think you have a latin1-based document. Does the encoding > header match? If the file is declared as latin-1 and contains an euro symbol, then the file is actually invalid since euro is not defined of in iso-8859-1. If there is no encoding declaration, as Diez already said, the file should be encoded as utf-8. Try replacing or adding the encoding with latin-15 (or iso-8859-15) which is the same as latin-1 with a few changes, including the euro symbol: If your file has lot of strange diacritics, you might take a look on the little differences between latin-1 and latin-15 in order to make sure that your file won't be broken: http://en.wikipedia.org/wiki/ISO_8859-15 Cheers, RB From pavlovevidence at gmail.com Wed Mar 12 14:48:20 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 11:48:20 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: On Mar 12, 2:19 pm, Alex wrote: > Hi all, > > The subject says pretty much all, i would very appreciate an answer. I > tried to search the various forums and groups, but didn't find any > specific answer... Python technically has no equivalent: you can't run code at compile time. However, the BEGIN block in Perl seems to have been added to work around some of Perl's nonlinear order of execution. Normally in Python you don't need a BEGIN block: just put the code at the top of you script/module and it will exectute before anything else. Want to tell us what you need it for? Perhaps we can suggest a way of doing it that's appropriate in Python. Carl Banks From carsten at uniqsys.com Sun Mar 23 21:22:54 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 02:22:54 +0100 Subject: Does python hate cathy? In-Reply-To: <1206321511.3365.28.camel@localhost.localdomain> References: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> <1206321511.3365.28.camel@localhost.localdomain> Message-ID: <1206321774.3365.31.camel@localhost.localdomain> On Mon, 2008-03-24 at 02:18 +0100, I wrote the barely intelligible phrase: > I'm not sure what you mean by "accessing an unbound variable" means in > the context of this thread I'm starting to sound like castironpi. Time to go to sleep. -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Mon Mar 31 13:24:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 14:24:01 -0300 Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: En Mon, 31 Mar 2008 07:59:13 -0300, sam escribi?: > Steve Holden napisa?(a): > >>> 1. You have different syntax for named and unnamed (lambdas) >>> functions. Functions and methods are different things in Python even >>> if they have same syntax. But all these are still a pieces of code >>> that you use repeatedly to make some task. >>> >> A knife and scissors are both used to cut things, but that doesn't mean >> they are the same. > > Well -- sometimes you have to use many, many types of scissors. I don't get the point - weren't you criticizing Python for having many different kind of functions? >> The desire to provide information hiding is fundamentally against the >> Python philosophy, which basically says that attribute values are >> exposed for all to see. This avoids the nonsense of having to provide >> setter and getter methods which Java imposes on the programmer. > > This philosophy is great and makes Python such a good language. But you > can't go > beyond what programmers need. If you do so, then you will have to > implement > tricks as __id. The __id "trick" is not for hidding instance attributes, but to avoid name collisions. Unlike other languages, all instance attributes share a single namespace, you can't qualify a reference to say "the foo attribute from this base class, not this other foo": it is always "the foo attribute" no matter inside which class it was assigned. The __ prefix creates mangled names so __foo used inside a certain class is a different attribute name than __foo outside that class. It is not used to "hide" the attribute, the rules for the mangled name are very easy to emulate. What are those programmers needs? -- Gabriel Genellina From kay.schluehr at gmx.net Sun Mar 9 10:29:02 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 9 Mar 2008 07:29:02 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> Message-ID: <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> On 9 Mrz., 13:50, Lie wrote: > On Mar 9, 4:31 pm, Kay Schluehr wrote: > > > > > On 9 Mrz., 09:30, Lie wrote: > > > On Mar 9, 12:05 pm, Kay Schluehr wrote: > > > > > On 9 Mrz., 04:51, Lie wrote: > > > > > > A more through implementation would start from the raiser inspecting > > > > > the execution stack and finding whether there are any try block above > > > > > it, if no try block exist it pass silently and if one exist it will > > > > > check whether it have a matching except clause. This also circumvents > > > > > a problem that simple implementation have, as described below. > > > > > This will not be easy in particular in the presence of inheritance and > > > > dynamism. There is no way to statically decide whether an exception > > > > BException has the type AException and will be caught by the except > > > > clause in > > > > > try: > > > > BLOCK > > > > except AException, e: > > > > print "SoftException %s caught"%e > > > > A feasible solution was to invert the try...except statement and > > > > creating a continuation. > > > > > catch AException, a: > > > > print "SoftException A: %s"%a > > > > catch BException , b: > > > > print "SoftException B: %s"%b > > > > ... > > > > in: > > > > BLOCK > > > > > Here each SoftException is raised initially when a catch clause is > > > > entered and a continuation is created that returns to the catch block > > > > of the raised SoftException if required. When a SoftException is > > > > raised within BLOCK a lookup will be made and if a corresponding > > > > SoftException was found that was raised by a catch-clause the current > > > > control flow will be suspended and the continuation is called. > > > > I'd rather want to avoid any syntax changes, as I wished that Soft > > > Exception can be added to the language silently[1] so that new > > > programmers doesn't _need_ to know about it (although knowing it could > > > change the way they write codes to be more structured and simple). > > > I just tried to save your proposal from being unimplementable. Maybe > > you can comment on it? > > Perhaps I'm not the appropriate person to talk about whether unchanged > syntax is feasible for such implementation since I basically have no > idea about how Python's internals works. It's only that I think if > current syntax could be used, we could just use it (except if there is > a strong reason why it shouldn't be done). You are an appropriate person to consider the workflow in a dynamic language, no matter how the language is implemented internally. Just start with function calls maybe_raise(ZeroDivisionError) The only requirement is that maybe_raise has to know when it shall raise ZeroDivisionError. This depends on whether the exception is caught. How do the program knows this in advance? There are no static analysis techniques available. When maybe_raise is entered the system must know that the exception is handled in the future. You can't inspect the call stack for this purpose because the call stack represents past events and continuations ( and you can't rely on names ). So you need something like this do_softexception(ZeroDivisionError) try: TRY_BLOCK except ZeroDivisionError: EXCEPT_BLOCK But this looks odd and the solution isn't DRY. So better one macro- transforms a new statement into this form. From mwolffedu at gmail.com Sat Mar 15 22:33:55 2008 From: mwolffedu at gmail.com (lampshade) Date: Sat, 15 Mar 2008 19:33:55 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: On Mar 15, 9:27 pm, Benjamin wrote: > On Mar 15, 8:12 pm, lampshade wrote:> Hello, > > > I'm having some problems with os.path.isdir I think it is something > > simple that I'm overlooking. > > > #!/usr/bin/python > > import os > > > my_path = os.path.expanduser("~/pictures/") > > print my_path > > results = os.listdir(my_path) > > for a_result in results: > > if os.path.isdir(str(my_path) + str(a_result)): > > Try if os.path.isdir(os.path.join(my_path, a_result)):> results.remove(a_result) > > > for x in results: print x > > > The problem is, that the directories are never removed. Can anyone > > point out what I'm missing that is causing the bug? Is there a better > > way of doing this? > > You should always use os.path.join to join paths. You shouldn't add > them like normal strings. I suspect you're getting a combination which > doesn't exist, so it isn't a dir. :) > > > > > Thanks, Thanks, that nailed it perfectly! I'll remember the os.path.join from now on! From lists at cheimes.de Tue Mar 25 16:03:15 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 25 Mar 2008 21:03:15 +0100 Subject: Circular references not being cleaned up by Py_Finalize() In-Reply-To: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: blackpawn schrieb: > So what's the deal here? :) I want all objects to be freed when I > shut down and their destruction functions to be properly called. Is > there really no way to make this happen? Does the Noddy example use GC (Py_TPFLAGS_HAVE_GC)? Container objects must use the cycle GC or circular referneces aren't broken. Have you tried calling PyGC_Collect() multiple times? Christian From bruno.desthuilliers at gmail.com Mon Mar 31 15:30:38 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 31 Mar 2008 12:30:38 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: <7eb5d21a-c4de-4655-ab93-9221d996f424@i7g2000prf.googlegroups.com> On 31 mar, 20:09, Duncan Booth wrote: > xkenneth wrote: > > Now obviously, if I test an instance of either class equal to each > > other, an attribute error will be thrown, how do I handle this? I > > could rewrite every __eq__ function and catch attribute errors, but > > that's tedious, and seemingly unpythonic. Also, I don't want an > > attribute error thrown whenever two classes are compared that don't > > have the same attributes. > > > I have a sneaky feeling I'm doing something completely unpythonic > > here. > > Surely an A isn't equal to every other object which just happens to have > the same attributes 'a' and 'b'? And why not ?-) > I would have thoughts the tests want to be > something like: > > class A: > def __eq__(self,other): > return (isinstance(other, A) and > self.a == other.a and self.b == other.b) > > (and similar for B) with either an isinstance or exact match required for > the type. I don't think there's a clear rule here. Python is dynamically typed for good reasons, and MHO is that you should not fight against this unless you have equally good reasons to do so. From kperkins257 at gmail.com Mon Mar 10 20:29:29 2008 From: kperkins257 at gmail.com (kperkins257 at gmail.com) Date: Mon, 10 Mar 2008 17:29:29 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: On Mar 10, 3:33 pm, Mike Driscoll wrote: > On Mar 10, 2:11 pm, Stefan Behnel wrote: > > > > > Malcolm Greene wrote: > > >> My personal experience with wxPython has its ups and downs. Specifically > > >> when it comes to crashes, I wouldn't bet my life on it. > > > > I'm new to Python and getting ready to build a small client based > > > application intended to run on Windows and Linux. I was planning on using > > > wxPython until I saw your comment above. > > > Just to make this sound a bit less like FUD: my last experience with wxPython > > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > > in a project, which crashed a bit too often to do real work with it - and with > > crashing I mean crashing Python, not just showing us its blank traceback. So > > this was definitely a problem either in wxWindows or in wxPython. > > > I have no idea how well it works today, but this has definitely forged my > > opinion on wxPython. > > > > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > > > or tips on where I can find out more about wxPython/wxWidget problems? > > > The only other GUI library I used was PyQT3. To me, it has proven to be very > > stable, pretty easy to use and feature rich. And from what I read about it, > > PyQT4 is supposed to be another lot better and has removed the few API quirks > > I found at the time (AFAIR, it finally returns plain Python strings from the > > API, for example). > > > Stefan > > I agree with Stef. Boa is definitely goofy and while I know some > people swear by it, I see far too many people having issues. I go with > hand coding or XRC. Some also like SPE, but I haven't tried that to > know. > > Mike SPE is actually a very good editor--I'm using it for all my Python coding. It integrates well with wxglade, and wxpython, and is built on wxpython. I've used wxpython on a couple of little projects, and it works very well (on Linux, anyways). I'm starting a couple of bigger projects now, and am confident that it will scale up, seeing some of the projects that are using it. I've tried Boa a couple of times but, for me, the interface sucks, and is not very intuitive. From gandalf at shopzeus.com Tue Mar 25 05:26:04 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Mar 2008 10:26:04 +0100 Subject: StringIO + unicode Message-ID: <47E8C52C.9060501@shopzeus.com> Is there a standard "in-memory file" interface for reading/writting unicode stings? Something like StringIO. E.g. this would be possible: - create UnicodeStringIO - write unicode strings into it - wite data (binary) string of UnicodeStringIO into a file ('wb' mode) and then later: - read the same file with codecs.open(filename,"r",encoding="utf-8") Maybe there is no standard class for this and I have to implement it myself. (?) Thanks, Laszlo From cokofreedom at gmail.com Thu Mar 13 06:51:42 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 13 Mar 2008 03:51:42 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> <7xtzjalx05.fsf@ruckus.brouhaha.com> Message-ID: <2c744609-19e5-4b3b-8cf8-607e1990fb13@n58g2000hsf.googlegroups.com> Still, I suppose this is a gotcha for a lot of people, just follow the good advice Paul said; "By Python convention, methods that mutate the object return None, and also stuff that returns None doesn't generate output at the interactive prompt." And you should survive most. From steve at REMOVE-THIS-cybersource.com.au Mon Mar 17 09:37:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 17 Mar 2008 13:37:39 -0000 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> Message-ID: <13tst1388cp67d8@corp.supernews.com> On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: > Here's a puzzle for those who think they know Python: > > Given that I masked out part of the input, which version(s) of Python > might give the following output, and what might I have replaced by > asterisks? There's too many variables -- at least five Python implementations that I know of (CPython, Jython, PyPy, IronPython, and the Lisp-based implementation that I can never remember the name of), and given that this is an implementation-dependent feature it could have changed at any time, in any version number (say, between minor releases). And there's literally an infinite number of ways to get b equal to an int with the value 1. So I think unless somebody happens to have stumbled across this behaviour, it's not predictable. But having said that, I'm going to take a stab in the dark: The line "b = ****" should be "b = int('1')" and the version is CPython 1.4. Am I close? -- Steven From rsarpi at gmail.com Thu Mar 6 19:46:08 2008 From: rsarpi at gmail.com (icarus) Date: Thu, 6 Mar 2008 16:46:08 -0800 (PST) Subject: Flash interface for a python program Message-ID: Is it possible to call an external python program, through a Flash interface? Meaning, I create a Flash window with a button. When I press that button, it automagically invokes the external python program. Is that possible? Any books/online tutorials you can recommend me? I guess I'm looking for alternatives in the area of GUI development. From jeffrey at fro.man Mon Mar 24 15:14:29 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 24 Mar 2008 12:14:29 -0700 Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <13ufvcl5lbda972@corp.supernews.com> pythonnubie wrote: > The exeption > is " no such ?attribute " in ?module random Is your own source file named "random.py" by chance? If so, rename it, and be sure to remove the leftover random.pyc file as well. Jeffrey From deets at nospam.web.de Tue Mar 4 08:32:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Mar 2008 14:32:21 +0100 Subject: Eurosymbol in xml document References: <634sleF25sd22U1@mid.uni-berlin.de> Message-ID: <6351b3F25irgtU1@mid.uni-berlin.de> > If the file is declared as latin-1 and contains an euro symbol, then the > file is actually invalid since euro is not defined of in iso-8859-1. If > there is no encoding declaration, as Diez already said, the file should > be encoded as utf-8. > You are right of course - latin1 doesn't contain the euro-symbol. ISO-8859-15 it is. Dumb me. Diez From cantabile.03 at wanadoo.fr Mon Mar 17 22:12:19 2008 From: cantabile.03 at wanadoo.fr (cantabile) Date: 18 Mar 2008 02:12:19 GMT Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <0369b78b-6681-4807-b944-fb371cdd1522@59g2000hsb.googlegroups.com> Message-ID: <47df2503$0$868$ba4acef3@news.orange.fr> Le Mon, 17 Mar 2008 09:03:07 -0700, joep a ?crit?: > An example: looks for all 'junk*.txt' files in current directory and > replaces in each line the string 'old' by the string 'new' > Josef Works like a charm. Many thanks for the example Josef :-) From bronger at physik.rwth-aachen.de Sun Mar 30 17:08:15 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 30 Mar 2008 23:08:15 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <6deb5443-e87b-448e-a1a6-6a1886c9f12a@x41g2000hsb.googlegroups.com> Message-ID: <87od8vzzr4.fsf@physik.rwth-aachen.de> Hall?chen! hdante writes: > On Mar 30, 9:45 am, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: > >> hdante wrote: >> >>> BTW, my opinion is that it's already time that programmer >>> editors have input methods advanced enough for generating this: >> >> Could you please list some that do, and are also convenient? > > AFAICT there's none. This should be easy to implement on emacs, It *is* implemented in Emacs. You can even choose from many input methods, optimised for differend areas/languages. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From timr at probo.com Sat Mar 15 01:47:23 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Mar 2008 05:47:23 GMT Subject: Joseph Weizenbaum References: Message-ID: Jeff Schwab wrote: >Roel Schroeven wrote: >> castironpi at gmail.com schreef: >>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>>> Subject: RIP: Joseph Weizenbaum >>>>> Creator of Eliza: >>>>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>>>> >>>> How do you feel about creator of Eliza? >>> >>> What is Eliza? >> >> Does that question interest you? > >Well played, sir. > >Earlier you said what is Eliza. Do you still feel that way? I am embarrassed to say that this vaguely disrespectful exchange made me laugh out loud. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sun Mar 2 17:43:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 14:43:40 -0800 (PST) Subject: Function Overloading and Python References: Message-ID: On Feb 25, 11:04?am, castiro... at gmail.com wrote: > > B1.fun(A(x), A(y), A(z)) == B.fun(A(x), A(y), A(z)) > > but > > B1.fun(A1(x), A(y), A(z) != B.fun(A1(x), A(y), A(z)) > > > Is there a data-structure solution or third party module that would > > mimic this behavior? > > class B: > ? ?xfun= Overloaded() > ? ?def fun( self, *a ): > ? ? ? return self.xfun.dispatch( self, *a ) > ? ?@xfun.make( A, A, A ) > ? ?def q( self, x, y, z ): > ? ? ? return 'B AAA' > ? ?@xfun.make( A1, A, A ) > ? ?def q( self, x, y, z ): > ? ? ? return 'B A1AA' > B.xfun.push( B ) You could also call xfun.methods( self ) in B.__init__. Overloaded.methods binds the methods specified with xfun.make to the B instance. In this case, the effect is, self.fun= types.MethodType( self.__class__.[x?]fun, self ) -- I forget by now. But time is money, and money doesn't grow on trees-- so catch me later with your own. (A decorator could also do it too-- and just in the base class!) From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 06:01:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 10:01:53 -0000 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> Message-ID: <13us4sh6u8mfn96@corp.supernews.com> On Sat, 29 Mar 2008 10:11:28 +0100, Roel Schroeven wrote: > Steven D'Aprano schreef: >> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: >> >>> Gabriel Genellina wrote: >>>> That's what I said in another paragraph. "sum of coordinates" is >>>> using a different distance definition; it's the way you measure >>>> distance in a city with square blocks. I don't know if the distance >>>> itself has a name, but >>> I think it is called Manhattan distance in reference of the walking >>> distance from one point to another in this city. >> >> You know, there are other cities than Manhattan. Some of them even have >> streets and blocks. > > I'm not sure what your point is. The name "The" name? You go on to list four additional names, so why do you say that "Manhattan distance" is THE name? When I studied this at university, we called it the taxi metric. > of the distance happens to be > Manhattan distance (or taxicab distance, rectilinear distance, L1 > distance, city block distance; see > http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid > point. Wikipedia doesn't believe that M-D is the primary or most common name, and the link you give redirects to "Taxicab distance". Googlefight agrees: "Taxicab distance" is more than twice as common, and "rectilinear distance" more than five times as common. My point was to draw attention to Robert's unconscious assumptions which are reflected in his choice of language. Rectilinear distance applies to more than "distance from one point to another in THIS city" (emphasis added). It applies in parts of Rome, Sydney, London, Moscow and many other places. It even applies to sleepy little country towns like Bendigo and Mildura here in Australia. Manhattan is hardly the only place where cities are carved up into rectangular or square city blocks, and I doubt that it applies to the entirety of Manhattan. It also applies to supermarket isles, church pews, chess boards, pixels on a monitor and no doubt other places as well. The very name is New York-centric, just as much as if the English called the science of acoustics "Big-Ben-onics" in reference to the peals of Big Ben's clock. I had thought I had pointed that out with a little gentle understatement. -- Steven From mdw at distorted.org.uk Mon Mar 31 14:10:03 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Mon, 31 Mar 2008 18:10:03 +0000 (UTC) Subject: deleting a line from a file References: <13usb5ngt26qv26@corp.supernews.com> <7xy781zqkq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > You could do it "in place" in all those systems afaik, either opening > the file for both reading and writing, or using something like mmap. > Basically you'd leave the file unchanged up to line N, then copy lines > downward starting from line N+1. At the end you'd use ftrunc to > shrink the file, getting rid of the duplicate last line. Making a new copy and renaming it when you're finished is probably both easier (don't have to keep seeking about all the time) and more reliable (doesn't leave your file corrupted if you crash half-way through). Is there a standard wossname which does this? from __future__ import with_statement from contextlib import contextmanager import os, sys, errno def fresh_file(base, mode = 'w'): """ Return a file name and open file handle for a fresh file in the same directory as BASE. """ for seq in xrange(50): try: name = '%s.new.%d' % (base, seq) fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL) f = os.fdopen(fd, mode) return name, f except OSError, err: if err.errno == errno.EEXIST: pass else: raise raise IOError(errno.EEXIST, os.strerror(errno.EEXIST), base) @contextmanager def safely_writing(filename, mode = 'w'): """ Context manager for updating files safely. It produces a file object. If the controlled suite completes successfully, the file named by FILENAME is atomically replaced by the material written to the file object; otherwise the file is left alone. Safe in the presence of multiple simultaneous writers, in the sense that the resulting file is exactly the output of one of the writers (chosen nondeterministically). """ f = None newname = None try: newname, f = fresh_file(filename, mode) yield f f.close() f = None os.rename(newname, filename) finally: if f is not None: f.close() if newname is not None: try: os.unlink(newname) except: pass It seems like an obvious thing to want. (Extra messing about will be needed on Windows, which doesn't have proper atomic-rename semantics. Playing with the transactional filesystem stuff is left as an exercise to the interested student.) -- [mdw] From Frank.Aune at broadpark.no Mon Mar 3 06:41:26 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Mon, 3 Mar 2008 12:41:26 +0100 Subject: Python logging: Retrieving the last log record from a handler Message-ID: <200803031241.26857.Frank.Aune@broadpark.no> Hi, I'm using a log hierarchy in my application, and sometimes I find myself wanting to retrieve the latest log message written to the root logger. (Typical usage might be displaying the latest log message at all times in a GUI). The only way I've found how to solve this, is by adding a custom loghandler: --- class LastRecordHandler(logging.Handler): def __init__(self): logging.Handler.__init__(self) self.lastRecord = None def emit(self, record): self.lastRecord = record def getRecord(self): return self.lastRecord.getMessage() --- I will be fairly surprised if this functionality is not already built-in for the default logging handlers, but so far I've been unable to figure out how to pull it of without the custom loghandler above. The kind of functionality I'm looking for is something like: self.log = logging.getLogger('GUI') (...) lastRecord = self.log.getLastRecord() # Display lastRecord in GUI Is this possible in some way, or do I need to extend the default logging handlers in order to archieve this? Thanks, Frank From Lie.1296 at gmail.com Tue Mar 11 15:30:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 12:30:59 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> <63ns5vF1fcb15U1@mid.uni-berlin.de> Message-ID: <9a0f1e31-7e3a-47ad-a5cf-063829ac7f85@s37g2000prg.googlegroups.com> (If there is anything weird that I say, please ignore it since I'm writing this half-sleeping) On Mar 12, 12:00?am, "Diez B. Roggisch" wrote: (snip) > I totally fail to see where > > raise Equal(a, b) > > is less cluttered or not than > > callback(a, b) > > Actually, the latter is even less cluttered, misses a raise - if pure number > of literals is your metric, that is. You don't just compare by the calling code, you've got to compare also by the surrounding codes. The calling codes in SE might be a little bit messy, but it worths by making the code surrounding it more clean and structured. And anyway, if you used Context Object callback, they will be as messy as each other. > > If there is a syntax support, you could also make "resume" able to > > transfer values: > > > ? ? def somefunc(a, b): > > ? ? ? ? if a == b: a, b = raise Equal(a, b) > > > ? ? def toplevel(): > > ? ? ? ? try: > > ? ? ? ? ? ? somefunc(10, 20) > > ? ? ? ? except Equal, args: > > ? ? ? ? ? ? a, b = args[0], args[1] + 1 > > ? ? ? ? ? ? resume a, b > > Sure, you can make all kinds of things, but so far you didn't come up with a > comprehensive feature description that just _does_ specify what SEs are and > what not. - Exception that aren't handled when no handler exists for it. - It's not a way for notifying errors - It's a way to describe status changes to higher codes - Everything described in the first post > > Perhaps you meant: > > ? ? raise_soft(SoftException) > > > cause SoftException() may have side effects if called greedily > > Nope, I didn't, and it's beside the point. Then what happen when SoftException is called? And a side-effect occurs? > > That could be done, but when raise_soft() returns, it returns to the > > code that raises it so it must be 'break'en: > > > ? ? def caller(a, b): > > ? ? ? ? if a == b: > > ? ? ? ? ? ? raise_soft(SoftException) > > ? ? ? ? ? ? break > > > but this makes SoftException must break everytime, which make it lost > > its original purpose, so you have to add return code to raise_soft > > whether you want to break it or not: > > You didn't understand my example. If there is a handler registered, it will > be invoked. If not, nothing will be raised. The exact same amount of > state-keeping and lookups needs to be done by the SE-implementation. I do understand your example. And even if I misunderstood you about passing context object, the same problem still exists in context object based solution, i.e. functions can't make the called function break automatically, it must be 'break' manually or the program will go astray (break ==> return, sorry I confused it with break for loops). And if you used InterruptException to break, it doesn't play well with multiple SoftExceptions. The final, resulting code by function passing below is extremely messy, see if you can make it cleaner and with the same functionalities and all to the SE version. def called(a, b, cont_obj = Null_CO): if a == b: a, b = cont_obj.a_equal_b(a, b) cont_obj.addition(a, b) return a + b def caller(): class cont_obj(object): def a_equal_b(a, b): if a < 0 and b < 0: return a + 1, b # resume raise InterruptException(('a_e_b',)) # break def addition(a, b): if a > b: return raise InterruptException(('addit', (a, b))) # break try: called(10, 10, cont_obj) except InterruptException, args: # if breaken ret, arg = args if ret == 'a_e_b': return -1 a, b = arg if ret == 'addit': return a ** b # by adding try clauses, and you've really equalize the biggest overhead of SE. # And I don't think you could create a less messy InterruptException handler, # the other solution to it would be to create a handler for each unique returns # but that would make it exceed the second SE overhead, the Exception Declaration # In other words, the tricks that is used to emulate the SoftException would all # have higher code overhead compared to using the clean, structured SEs # * Overheads means garbage code that's important to make something work # The code is separated into three parts, "try except", and cont_obj, and called. Worse, the cont_obj can't determine what happen if they got unresumed errors, without using some tricky part. Compare that code above with: def called(a, b): if a == b: a, b = raise a_equal_b(a, b) raise addition(a, b) return a + b def caller(): class a_equal_b(Exception): pass class addition(Exception): pass try: ret = called(10, 10) except a_equal_b(a, b): if a < 0 and b < 0: resume a + 1, b return -1 except addition(a, b): if a > b: resume return a ** b # The code is separated into two parts, the "trys and excepts" and the called code. > > That could be done, but when raise_soft() returns, it returns to the > > code that raises it so it must be 'break'en: > > ? ? def caller(a, b): > > ? ? ? ? if a == b: > > ? ? ? ? ? ? if raise_soft(SoftException): > > ? ? ? ? ? ? ? ? break > > > Compare to: > > ? ? def caller(a, b): > > ? ? ? ? if a == b: > > ? ? ? ? ? ? raise SoftException > > > And this also makes it impossible to have state-changing behavior > > without some other weirder tricks > > That's not true. The > > with add_soft_handler(SoftException, handler): > > approach (I missed the handrel the first time, sorry) > can easily throw an exception to interrupt, like this: > > def handler(e): > ? ? if some_condition_on_e(e): > ? ? ? ?raise InterruptException() > > with add_soft_handler(SoftException, handler): > ? ? ?try: > ? ? ? ? ? work(...) > ? ? ?except InterruptException: > ? ? ? ? ? pass > > You could also introduce a function > > def interruptable(fun, *args, **kwargs): > ? ? try: > ? ? ? ?return fun(*args, **kwargs) > ? ? except InterruptException: > ? ? ? ?passthe > > to make the code look a bit cleaner - if it fits your usecase, that is of > course. The code doesn't work well with multiple excepts that have multiple fallbacks. > I don't say that SoftExceptions can't have semantics that go beyond this. I > just don't see a oh-so-compelling use-case that makes things so much better > than they are reachable now, without actually much programming. From zerty.david at gmail.com Mon Mar 31 16:56:48 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 31 Mar 2008 17:56:48 -0300 Subject: Python and Db In-Reply-To: <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> Message-ID: <5dc598e30803311356p6a5cf418oe9930a118d441e96@mail.gmail.com> It's DB = DataBase, I typed wrong on the text, but right at the subject =) On Mon, Mar 31, 2008 at 5:50 PM, David Anderson wrote: > I would like to use sqlite, But I also wanted a tutorial with the basis of > the sql and etc, I never dealed with dbs before > > > On Mon, Mar 31, 2008 at 3:42 PM, Gabriel Genellina > wrote: > > > En Mon, 31 Mar 2008 14:50:27 -0300, David Anderson < > > zerty.david at gmail.com> > > escribi?: > > > > > Hi! I'm don't know almost nothing about bds, Can You suggest me an > > Simple > > > but efficient Bd to work with python apps? Can You suggest me any > > > tutorials? > > > > See the Python wiki at: http://wiki.python.org/moin/DatabaseProgramming > > If you stick with DBAPI 2.0 you won't have much trouble writing for one > > database or another. sqlite is a good start and is included with Python > > 2.5 > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Tue Mar 4 13:07:31 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 04 Mar 2008 12:07:31 -0600 Subject: for-else In-Reply-To: References: Message-ID: <47CD8FE3.4070801@ncee.net> > if a == 0: > do_task_0() > elif a == 1: > do_task_1() > elif a == 2: > do_task_2() > else: > do_default_task() The if-elif-else structure that calls functions (like that above) can be avoided with the code below: def foo0(): print 'foo0' def bar0(): print 'bar0' def foo1(): print 'foo1' def bar1(): print 'bar1' def do_default_task(): print 'do_default_task' do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, } a = 1 # example of normal usage if a in do_task.keys(): do_task[a]() else: do_default_task() # example of testing all functions in the dict as well as the default function for a in do_task.keys() + [8]: # 8 is a non-existent key in the do_task dict print "a is ",a,"and it gives this output:", if a in do_task.keys(): do_task[a]() else: do_default_task() Carl Banks wrote: > On Mar 4, 10:55 am, "BJ?rn Lindqvist" wrote: > >> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks wrote: >> >>> > for ...: >>> > ... >>> > exhausted: >>> > ... >>> > broken: >>> > ... >>> >>> > The meaning is explicit. While "else" seems to mean little there. >>> > So I may like something similar for Python 3.x (or the removal of the >>> > "else"). >>> >>> I would not be opposed to this on its own merits, but there is a >>> rationale behind the name "else". If you consider a for loop to be a >>> rolled-up if...elif...else statement (situations where this is >>> reasonable tend to be the same ones were else would be useful), then >>> the "else" clause would remain unchanged on the for loop. >>> >>> For instance, if you have a (trivial) if...elif...else like this: >>> >>> if a == 0: >>> do_task_0() >>> elif a == 1: >>> do_task_1() >>> elif a == 2: >>> do_task_2() >>> else: >>> do_default_task() >>> >>> You could roll it up into a for...else statement like this: >>> >>> for i in range(3): >>> if a == i: >>> do_task[a]() >>> else: >>> do_default_task() >>> >> You forgot the break statement. The else suite will always be executed >> in this loop. Kind of proves bearophiles point, for-else is really >> tricky. >> > > Ah ha, but that would have been a mistake with or without the else > clause.... > > > Carl Banks > This approach works well for me: def foo0(): print 'foo0' def bar0(): print 'bar0' def foo1(): print 'foo1' def bar1(): print 'bar1' def do_default_task(): print 'do_default_task' do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, } a = 1 # example of normal usage if a in do_task.keys(): do_task[a]() else: do_default_task() # example of testing for i in range(len(do_task.keys)): if a in do_task.keys(): do_task[a]() else: do_default_task() -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From KephnosAnagennao at gmail.com Sun Mar 23 03:32:28 2008 From: KephnosAnagennao at gmail.com (sgharvey) Date: Sun, 23 Mar 2008 00:32:28 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: On Mar 22, 5:03 pm, "Gabriel Genellina" wrote: > En Sat, 22 Mar 2008 17:27:49 -0300, sgharvey > escribi?: > Take a look at ConfigObjhttp://pypi.python.org/pypi/ConfigObj/ Thanks for the pointer; I'll check it out. > I'm not sure you can process a config file in this unstructured way; looks > a lot easier if you look for [sections] and process sequentially lines > inside sections. It works though... now that I've fixed up all my ugly stuff, and a dumb logic error or two. > The regular expressions look strange too. A comment may be empty. A > setting too. There may be spaces around the = sign. Don't try to catch all > in one go. I didn't think about empty comments/settings... fixed now. It also seemed simpler to handle surrounding spaces after the match was found. New version of the problematic part: self.contents = [] content = {} # Get the content in each line for line in lines: for name in patterns: # Match each pattern to the current line match = patterns[name].search(line) if match: content[name] = match.group(0).strip() self.contents.append(content) content = {} new iniparsing.py http://pastebin.com/f445701d4 new ini_regexen_dicts.py http://pastebin.com/f1e41cd3d > -- > Gabriel Genellina Much thanks to all for the constructive criticism. Samuel Harvey From stefan_ml at behnel.de Sun Mar 16 10:57:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 16 Mar 2008 15:57:16 +0100 Subject: Types, Cython, program readability In-Reply-To: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <47DD354C.3020501@behnel.de> Hi, bearophileHUGS at lycos.com wrote: > It seems Cython is going to become an efficient and > general purpose language after all, with optional static typing (its > purpose: mostly for speed), and it may even gain some kind of macros > soon. So it may even end replacing Python itself in some situations > where running efficiency is important, and where Psyco can't be used > or isn't enough. Even without any static type annotations, Cython currently runs the supported portion of pybench some 30% faster than CPython 2.5.1, with for-loops and if-then-else being multiple times faster. Even on plain Python numbers, arithmetic gives you a factor of 2 in Cython. http://comments.gmane.org/gmane.comp.python.cython.devel/680?set_lines=100000 If you need more, C arithmetic and integer loops can easily be enabled with type annotations, and the Cython project is working on further optimisations for normal Python code. So if speed is important and the existing code is supported by Cython (or can be made working), compilation is definitely an option. Stefan From danb_83 at yahoo.com Mon Mar 17 02:51:14 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 16 Mar 2008 23:51:14 -0700 (PDT) Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> Message-ID: Bernard Lim wrote: > Hi, > > I'm reading the Python Reference Manual in order to gain a better understanding > of Python under the hood. > > On the last paragraph of 3.1, there is a statement on immutable and mutable > types as such: > > > Depending on implementation, for immutable types, operations that compute > new values may or may not actually return a reference to any existing object > with the same type and value, while for mutable objects this is (strictly)? > not allowed. > > > Using the example given in 3.1, how do I verify that this is true pertaining > to immutable types? Below is my understanding on verifying the above statement: > > >>> a = 1 > >>> b = 1 > >>> a is b > True > >>> id(a) > 10901000 > >>> id(b) > 10901000 > > Is this correct? Yes, that's correct. However, >>> a = 100 >>> b = 100 >>> a is b False >>> id(a) 135644988 >>> id(b) 135645000 From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 23:39:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Mar 2008 03:39:22 -0000 Subject: any chance regular expressions are cached? References: Message-ID: <13t9bbap76cbdf3@corp.supernews.com> On Mon, 10 Mar 2008 00:42:47 +0000, mh wrote: > I've got a bit of code in a function like this: > > s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save me the > trouble of having to declare some global re's if I don't want to have > them recompiled on each function invocation? At the interactive interpreter, type "help(re)" [enter]. A page or two down, you will see: purge() Clear the regular expression cache and looking at the source code I see many calls to _compile() which starts off with: def _compile(*key): # internal: compile pattern cachekey = (type(key[0]),) + key p = _cache.get(cachekey) if p is not None: return p So yes, the re module caches it's regular expressions. Having said that, at least four out of the five examples you give are good examples of when you SHOULDN'T use regexes. re.sub(r'\n','\n'+spaces,s) is better written as s.replace('\n', '\n'+spaces). Don't believe me? Check this out: >>> s = 'hello\nworld' >>> spaces = " " >>> from timeit import Timer >>> Timer("re.sub('\\n', '\\n'+spaces, s)", ... "import re;from __main__ import s, spaces").timeit() 7.4031901359558105 >>> Timer("s.replace('\\n', '\\n'+spaces)", ... "import re;from __main__ import s, spaces").timeit() 1.6208670139312744 The regex is nearly five times slower than the simple string replacement. Similarly: re.sub(r'^',spaces,s) is better written as spaces+s, which is nearly eleven times faster. Also: re.sub(r' *$','',s) re.sub(r'\n*$','',s) are just slow ways of writing s.rstrip(' ') and s.rstrip('\n'). -- Steven From ggpolo at gmail.com Sun Mar 23 09:29:37 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 23 Mar 2008 10:29:37 -0300 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] In-Reply-To: <47E4202C.5060400@v.loewis.de> References: <47E4202C.5060400@v.loewis.de> Message-ID: 2008/3/21, "Martin v. L?wis" : > > I've been thinking of volunteering to "port" Tkinter to Python 3.0, I > > hadn't noticed that there was any discussion of removing it. It would > > be a shame IMHO. > > > I don't think Tkinter will be removed. It works just fine in 3k. > > Of course, if you would port IDLE to Tk 8.5: that would be a useful > contribution. I'm interested in doing this, but are you aware of bugs yet ? I know just one that is specific to Tk 8.5, this one being the background color of the editor. > > Regards, > > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From toolmaster at 163.com Mon Mar 17 04:12:44 2008 From: toolmaster at 163.com (WaterWalk) Date: Mon, 17 Mar 2008 01:12:44 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <47de07a2$0$2699$9b622d9e@news.freenet.de> Message-ID: On Mar 17, 1:54 pm, Stargaming wrote: > On Sun, 16 Mar 2008 20:54:01 -0700, WaterWalk wrote: > > Hello. I wonder what's the effective way of figuring out how a piece of > > python code works. > > If your Python code is well-written, it should be easy figuring out what > it means by just reading it. For more complex programs, of course, this > method can fail. > > > With C I often find it very useful to be able to run > > the code in step mode and set breakpoints in a debugger so I can watch > > how the it executes, how the data change and how the code jumps from one > > function to another. But with Python, the debugger is a little > > primitive. The default IDLE doesn't even allow me to set a breakpoint. > > When the code is long, I am often lost in it. > > IDLE is just, well, a batteries-included editor. There are many people > (me included) who do *not* like it because it's so weak and doesn't have > any real uses cases if your programs get sufficiently complex (because > IDLE itself is sufficiently primitive). > > You might be interested in *real* debuggers, such as the Python Debugger > `PDB `_. If you don't find > its usage obvious, a quick google search just turned up a nice `tutorial > `_. > > You might find the `Python Profilers profile.html>`_ particularly interesting, `profile` for finding out which > function sucks up the most calls/time, `trace` for more sophisticated > stuff. > `pythontracer ` sounds like a > good combination of both. > > > So I'm curious how to read code effectively. I agree that python code is > > clear, but when it becomes long, reading it can still be a hard work. > > A common practice is just inserting `print` statements since it's so > easy. If you think your debugging isn't temporary but could be useful and > will be enabled every now and then, you could also use the `logging > module `_ with the > ``DEBUG`` level. > > There was a blog post recently about how to do this `generically for > functions `_. > > > BTW. I think this problem also exists in other script languages. > > FWIW, I think it's particularly easier in scripting languages to > implement all kinds of tracing (apart from debugging, which is rather > unpopular in Python) because you have one *extra* level (the interpreter) > between your machine and your code. > > HTH, > Stargaming Thanks for your informative reply. I'll try them. I think I need more practice to familiarize myself with those idioms of Python. From kay.schluehr at gmx.net Sun Mar 16 03:48:20 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 16 Mar 2008 00:48:20 -0700 (PDT) Subject: ANN: EasyExtend 3.0 - second beta Message-ID: The second beta of EasyExtend 3.0 has been released today. This release is mostly about bugfixes and the reintegration of the fun langlet Teuton and the code coverage langlet. The code coverage langlet has been enhanced s.t. it can detect uncovered branches in boolean operations now. ------------------------------------------------------------------------------------------------------------------------------------------------------------------ What has EE 3.0 to offer? * Trail - a new powerful parser generator. * User defined file suffixes are recognized by the import machinery * Framework extension that supports facilitation of writing user defined tokenizers * Simplification of access to tokenizer and parser from individual extension languages ( langlets ). * Improved stability of the CST transformation process and improved debugging facilities URLs: http://www.fiber-space.de/EasyExtend/doc/EE.html http://pypi.python.org/pypi/EasyExtend/3.0-beta2 From fakeaddress at nowhere.org Tue Mar 18 07:24:12 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 18 Mar 2008 04:24:12 -0700 Subject: finding items that occur more than once in a list In-Reply-To: References: Message-ID: Simon Forman wrote: > Is there a more efficient way to do this? > > def f(L): > '''Return a set of the items that occur more than once in L.''' > L = list(L) > for item in set(L): > L.remove(item) > return set(L) That's neat, but quadratic time because list.remove() requires a linear search. We can make an efficient variant by using remove on a set rather than a list: def multiples(lst): singles = set(lst) mults = set() for x in lst: if x in singles: singles.remove(x) else: mults.add(x) return mults Though probably better is: def multiples(lst): seen = set() mults = set() for x in lst: if x in seen: mults.add(x) else: seen.add(x) return mults I've typically used dicts for such things, as in: def multiples(lst): h = {} for x in lst: h[x] = h.get(x, 0) + 1 return set([x for x in h if h[x] > 1]) -- --Bryan From gagsl-py2 at yahoo.com.ar Sat Mar 15 05:14:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 07:14:05 -0200 Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Message-ID: En Fri, 14 Mar 2008 17:23:14 -0200, Amit Gupta escribi?: > So What do I do, if my testcase if failing because of an uncaught > exception and I want to run it in pdb. Oh, sorry, my last message doesn't apply because the unittest framework caughts the exception. Looks like you have to override TestResult.addError and call pdb.pm() there. -- Gabriel Genellina From deets at nospam.web.de Fri Mar 21 05:34:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Mar 2008 10:34:09 +0100 Subject: Code folder with Emacs In-Reply-To: <13u5li6kspler51@corp.supernews.com> References: <13u5li6kspler51@corp.supernews.com> Message-ID: <64hdonF2boovnU1@mid.uni-berlin.de> Grant Edwards schrieb: > Has anybody figured out how to do code folding of Python source > files in emacs? > > I tried "hide-show" minor mode, but it doesn't really work for > Python code: the only think it knows how to hide/show are > function bodies. It can't do normal things like hide/show a > code block like it can for other languages. > > Google also found my "folding mode", but that's based on > user-inserted tokens and isn't syntax aware. > I just recently started hacking in emacs, to enhance the python-mode and make pdb work with persisten breakpoints (by that I mean BPs that survive one debug-session). Code-folding isn't currently on my agenda, but an interesting idea. given that e.g. ecb already has structural analysis buffers, there are python-aware code parsers (cedet?) So it shouldn't be too hard. The only interesting/important thing would be to integrate it with ecb because I wouldn't want several parse-runs at once. BTW, I can highly recommend flymake for running pylint over the sources! That really helps me a lot these days! Diez From andis59 at gmail.com Fri Mar 7 07:02:33 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Fri, 7 Mar 2008 13:02:33 +0100 Subject: List all files using FTP References: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> Message-ID: <195hfxxrjzc7u$.dlg@ostling.com> On Thu, 6 Mar 2008 20:07:46 +0000, Simon Brunning wrote: > This might be of use: > > Nice, Just what I needed! Thank you! // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:55:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:55:36 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6i47r3uoo6b4@corp.supernews.com> <7x3ar0wjhn.fsf@ruckus.brouhaha.com> Message-ID: <13t6uuoj1s56p52@corp.supernews.com> On Sat, 08 Mar 2008 21:32:04 -0800, Paul Rubin wrote: > I should have mentioned (a+b-1)//b expects a and b to be positive > integers. Oh, I don't think that would have made any difference. I think I'm seeing floats everywhere today, including coming out of the walls. -- Steven From robert.rawlins at thinkbluemedia.co.uk Wed Mar 12 11:10:42 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 12 Mar 2008 15:10:42 -0000 Subject: agg (effbot) In-Reply-To: <47D7F0DE.5000106@tim.thechases.com> References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> <63q90kF268j23U1@mid.uni-berlin.de> <47D7F0DE.5000106@tim.thechases.com> Message-ID: <007e01c88453$402c5ba0$c08512e0$@rawlins@thinkbluemedia.co.uk> Haha, Tim, that cracks me up! lol Bring forth the Holy Hand Grenade of Antioch Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Chase Sent: 12 March 2008 15:04 To: python-list at python.org Subject: Re: agg (effbot) Importance: Low Gerhard H?ring wrote: > fraleysinger at gmail.com wrote: >> aggdraw-1.2a3-20060212.tar.gz > > Try shegabittling the frotz first. If that doesn't help, please post the > output of the compile command that threw the error. Maynard: He who is valiant and pure of spirit may find the compiling instructions in the Drawing Program of Agg Arthur: what?! Maynard: the Drawing Program of Agg. Bedevere: What's that? Maynard: he must of died while typing it Launcelaot: Oh, come on! Maynard: well, that's what it's called Artuhur: Look, if he was dying, he wouldn't bother to name it "agg" Maynard: Well, that's what's written in the URL Galahad: Perhaps he was dictating... Arthur: Oh, shut up. ... -tkc -- http://mail.python.org/mailman/listinfo/python-list From fakeaddress at nowhere.org Sat Mar 15 09:18:01 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 15 Mar 2008 06:18:01 -0700 Subject: Socket Performance In-Reply-To: <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > Gabriel Genellina wrote: >> No need to reinvent the wheel. socket objects already have a makefile >> method returning a file-like object, which behaves like a buffered socket. That wheel is far from round, and needs some reinvention. Python's file-like objects do not play nice with lower level calls, which would be tolerable if they supported some well-defiend high-level asynchronous I/O, but they do not. > Newbie question: Can you write to the 'file-like object' a pickle, > and receive it intact-- as one string with nothing else? Yes, but there's a world of gotcha's. Sockets do not recognize record boundaries, and Python's 'pickle' has holes one's enemies could drive a truck through. Still, you can pickle, write, read, un-pickle, and get back your data intact. > I want to know because I want to send two pickles. "Two pickles" sounds like a tasty snack, but also suggests you may be playing hopscotch in a minefield. This is a helpful group. Give us more to go on, and you are likely to receive thousands of dollars worth of consulting for free. -- --Bryan From bill.mill at gmail.com Sun Mar 16 16:46:40 2008 From: bill.mill at gmail.com (Bill Mill) Date: Sun, 16 Mar 2008 13:46:40 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: Tom Moertel organized a Perl conference with an interesting sponsorship policy, that may be worth considering. He posted about it on the reddit thread about this clp thread: http://reddit.com/info/6c9l6/comments/c03gli2 . (Disclaimer: I have no idea if that would work for pycon at all or in part, I'm just posting it because I found it thought-provoking.) -Bill Mill http://billmill.org From gabriel.rossetti at mydeskfriend.com Thu Mar 27 04:30:17 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 09:30:17 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: <47EB58B5.1020801@mydeskfriend.com> References: <47EB58B5.1020801@mydeskfriend.com> Message-ID: <47EB5B19.9080906@mydeskfriend.com> Gabriel Rossetti wrote: > Hello, > > I am using Partial Function Application in a class and I've come up with > a problem, when the method is called it tries to pass "self" to the > curried/partial function, but this should be the first argument in > reality, but since the function is curried, then the self gets passed as > the second argument. Here is the code : > > def __registerService(self, atomic, service): > def reg(service): > # registers the service > ... > > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > I should pass self when applying partial, but then I can't do that since > self is not available there. Does anyone have any ideas? > > Thanks, > Gabriel > I also tried this : def __registerService(atomic, self, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) thinking that the self will be passed as the first argument of the registerService* calls and thus the second argument to the curried/partial method, but it doesn't work either, I get : Traceback (most recent call last): File "/home/xxx/Documents/Code/Python/test/test_serv.py", line 245, in test_registeration self.f.registerServiceAtomic(self.serv) exceptions.TypeError: __registerService() takes exactly 3 arguments (2 given) I don't get it... Gabriel From roygeorget at gmail.com Wed Mar 19 02:14:40 2008 From: roygeorget at gmail.com (royG) Date: Tue, 18 Mar 2008 23:14:40 -0700 (PDT) Subject: need a function to create eigenface image Message-ID: hi while trying to make an eigenface image from a numpy array of floats i tried this from numpy import array import Image imagesize=(200,200) def makeimage(inputarray,imagename): inputarray.shape=(-1,) newimg=Image.new('L', imagesize) newimg.putdata(inputarray) newimg.save(imagename) since i am using images of 200X200 size, i use an array with 40000 elements like [ -92.35294118 -81.88235294 -67.58823529 ..., -3.47058824 -13.23529412 -9.76470588] the problem is ,i get an image that is too dark.it looks like a face but is too dark that even different arrays will create images rhat all look alike!.. is there a way to 'tone it down' so that i can generate an eigenface that can be displayed better? thanks RG From duncan.booth at invalid.invalid Sat Mar 29 14:24:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Mar 2008 18:24:19 GMT Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: Lie wrote: > You're forcing your argument too much, both != and <> are NOT standard > mathematics operators -- the standard not-equal operator is >< -- and > I can assure you that both != and <> won't be comprehensible to non- > programmers. My maths may be a bit rusty, but I always thought that the standard not- equal operator was like an = sign but with a diagonal slash through it as displayed when you do: print u'\u2260' From nagle at animats.com Thu Mar 13 14:38:37 2008 From: nagle at animats.com (John Nagle) Date: Thu, 13 Mar 2008 11:38:37 -0700 Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup Message-ID: <47d97288$0$36363$742ec2ed@news.sonic.net> Just noticed, again, that getattr/setattr are ASCII-only, and don't support Unicode. SGMLlib blows up because of this when faced with a Unicode end tag: File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag method = getattr(self, 'end_' + tag) UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 46: ordinal not in range(128) Should attributes be restricted to ASCII, or is this a bug? John Nagle From steve at holdenweb.com Mon Mar 31 06:18:35 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 06:18:35 -0400 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: sam wrote: > Steven D'Aprano napisa?(a): > >>> I can see that Python and Javascript inheritance model is almost the >>> same. Both languages are dynamically typed. And it seems that using >>> "classes" in Python makes some things more complicated then it is >>> necessary (eg functions, methods and lambdas are differen beeing in >>> Python concept). >> Please explain why you think that functions are more complicated in >> Python because of the class model. > > Sorry for a late reply (I was out of the office). > > > 1. You have different syntax for named and unnamed (lambdas) functions. > Functions and methods are different things in Python even if they have same > syntax. But all these are still a pieces of code that you use repeatedly to make > some task. > A knife and scissors are both used to cut things, but that doesn't mean they are the same. > 2. Static function doesn't need to reference "self", and Python forces > programmer to put "self" explicitly. Then you have to do some "tricks" on > function to become static. Python is said "nothing is really private", but > interpreter does some "tricks" to make __id hidden for a class. > Static functions don't even need to live in classes, and certainly don't need references to "self", which only makes sense in the context of acting on instances of classes. > > Some opinions: > > 1. In early days you could do OOP in C -- you just used additional parameter in > a function. Then C++ appeared to make life easier: "when you write > mystring.toupper(), then toupper function gets hidden argument called "this"". > Programs are written in a high level object oriented languages now. In these > languages you still use the same syntax mystring.toupper(), but now you don't > pass object to a function (as in C), but you act on that object. So in the body > of toupper() you can REFERENCE object "mystring". So why do I have to put that > "strange" argument "self"? > > This is not only my opinion > (http://apache.ece.arizona.edu/~edatools/Python/Prototypes.htm). Without "self" > you would use same syntax for ordinary functions, methods, and lambdas. > I think you are bundling quite different things together here. The difference in semantics between bound methods (where the instance reference is added as a first argument) and regular functions (where no additional argument is supplied) has nothing to do with the difference between function and lambda definition syntax. > > 2. Something is private because you can't reference that from outside the scope. > The wrong way is to make object properties private by declaring them private or > to do hidden actions (__id). For example all local variables in function are > private, because you can't access them from outside that function. Why desn't > this work for objects? > > Again this is not only my opinion -- > http://www.crockford.com/javascript/private.html. > The desire to provide information hiding is fundamentally against the Python philosophy, which basically says that attribute values are exposed for all to see. This avoids the nonsense of having to provide setter and getter methods which Java imposes on the programmer. You use the references you provide as a drunken man uses a lamp post - more for support than enlightenment. Python is not JavaScript, and never will be. JavaScript is a better language than it's often given credit for, but its object semantics are closer to Self than to Python. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Mon Mar 31 15:17:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Mar 2008 15:17:39 -0400 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com><8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com><659gb2F2f84eoU2@mid.individual.net><87hceo73ap.fsf@physik.rwth-aachen.de><65anbqF2fg18bU1@mid.individual.net><87r6drjss4.fsf@physik.rwth-aachen.de> <65c0bfF2ffipiU1@mid.individual.net> Message-ID: "Bjoern Schliessmann" wrote in message news:65c0bfF2ffipiU1 at mid.individual.net... | > However, I'm quite sure that when Unicode has arrived almost | > everywhere, some languages will start considering such characters | > in their core syntax. | | This should be the time when there are widespread quasi-standardised | input methods for those characters. C has triglyphs for keyboards missing some ASCII chars. != and <= could easily be treated as diglyphs for the corresponding chars. In a sense they are already, it is just that the real things are not allowed ;=). From xkenneth at gmail.com Wed Mar 12 12:29:11 2008 From: xkenneth at gmail.com (xkenneth) Date: Wed, 12 Mar 2008 09:29:11 -0700 (PDT) Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> Message-ID: On Mar 12, 6:32?am, "Diez B. Roggisch" wrote: > xkenneth wrote: > > Hi All, > > > ? ?Quick question. I've got an XML schema file (XSD) that I've > > written, that works fine when my data is present as an XML file. > > (Served out by apache2.) Now when I call python as a cgi script, and > > tell it print out all of the same XML, also served up by apache2, the > > XSD is not applied. Does this have to do with which content type i > > defined when printing the xml to stdout? > > Who's applying the stylesheet? The browser, some application like XmlSpy or > what? > > Diez The browser. Regards, Kenneth Miller From http Fri Mar 7 19:13:04 2008 From: http (Paul Rubin) Date: 07 Mar 2008 16:13:04 -0800 Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <7xmypa844v.fsf@ruckus.brouhaha.com> Pierre Quentel writes: > I would like to know if there is a module that converts a string to a > value of the "most probable type" Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >>> import this The Zen of Python, by Tim Peters ... In the face of ambiguity, refuse the temptation to guess. From tjreedy at udel.edu Sat Mar 29 16:12:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2008 16:12:22 -0400 Subject: Help me on function definition References: Message-ID: "aeneng" wrote in message news:fsk739+ff60 at eGroups.com... | def cross(u,v) | """input two vectors u and v in 3-D space, | output a cross product of vector w, in column or in row | accordingly.""" | ppp1,ppp2,ppp3=0.0,0.0,0.0 To add to other comments, remove above which is complete waste. From mensanator at aol.com Tue Mar 4 01:00:42 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 22:00:42 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <2aceec91-618d-4e62-9958-e223505bc51f@13g2000hsb.googlegroups.com> Message-ID: <0809c202-4759-4fc1-9c36-e079c212ca0e@u69g2000hse.googlegroups.com> On Mar 3, 8:31?pm, castiro... at gmail.com wrote: > > All software has bugs. > > Good software has bugs. > > Therefore, good software is software. > > > This makes sympy worse than worthless, as it f***s up other modules. > > What is it still good for? Lots. The problem is when the total is less than the sum of the parts. From asmodai at in-nomine.org Mon Mar 31 07:17:52 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 31 Mar 2008 13:17:52 +0200 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <20080331111752.GH80617@nexus.in-nomine.org> -On [20080331 13:13], Pradeep Rai (pradiprai at gmail.com) wrote: >Yes, i have copied everything from site-packages of the old one to the new >one. Don't do that. :) site-packages is version dependent, you can get away with it with most Python-only modules, I guess, but with dbi you found out what can happen. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ The last word in a chronicle is never set down... From abelufsc at gmail.com Mon Mar 10 08:26:42 2008 From: abelufsc at gmail.com (Abel Ferreira) Date: Mon, 10 Mar 2008 09:26:42 -0300 Subject: logging problem Message-ID: <4871dbda0803100526h78aaff23v35bba82ddfaf2475@mail.gmail.com> Hi. I have a problem with python. I dont wanna bother you, but it's seem you had the same error. Did you get solve this problem? I know it's old, but if you remember, tell me. i'm using python's logging facilities in all of my application modules. > my logging.conf file is: > [loggers] > keys=root > [handlers] > keys=roth > [formatters] > keys=simpleFormatter > [logger_root] > level=DEBUG > handlers=roth > [handler_roth] > class=handlers.RotatingFileHandler > level=DEBUG > formatter=simpleFormatter > args=('adssim.log','w', 2000000, 4) > [formatter_simpleFormatter] > format=%(asctime)s - %(message)s > datefmt=%Y-%m-%d %H:%M:%S > > i'm "creating" a logger in my adslogging module in the following way: > import logging > import logging.config > > logging.config.fileConfig("logging.conf") > logger = logging.getLogger("root") > > all my app modules import the adslogging module, and refer to the logger > as adslogging.logger and perform stuff like adslogging.logger.debug(msg1) > or adslogging.logger.info(msgN) > > although i'm not explicitly closing the logfile and i don't think the logfile size has > maxed out (i see one logfile under my app directory with size 31K), i'm getting the following error messages in windows xp. what might i be doing wrong? > > > C:\adssim1>python adstest.py 19.52.160.171 139 W04 > > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Mar 6 05:30:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 10:30:09 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <13svhthrlvqoad2@corp.supernews.com> On Thu, 06 Mar 2008 08:37:07 +0000, Bryan Olson wrote: > Grant Edwards wrote: >> It may be obvious that he has a question. It's not the least bit >> obvious what that question is. > > How can we efficiently implement an abstract data type, call it > 'DoubleDict', where the state of a DoubleDict is a binary relation, that > is, a set of pairs (x, y); and the operations on a DoubleDict are those > on a Python set, plus: > > find_by_first(self, x): return [y where (x, y) in DoubleDict] > > find_by_second(self, y): return [x where (x, y) in DoubleDict] > > > Python can implement this ADT directly as specified, but the find_by_ > operations would run in time len(self). We want an implementation where > the find_by's run in O(1 + k) where k is the length of the returned > sequence. If I've understood you correctly, what you want is a reverse lookup dict. Here's a Quick & Dirty partial implementation to get you started. It's VERY simple-minded, and barely tested at all. But both lookup and reverse- lookup should be almost as efficient as Python dicts, and it only uses roughly twice as many pointers as a regular dict. class RLdict(object): def __init__(self, **items): self.D = {} self.R = {} for key, value in items.iteritems(): self[key] = value def __getitem__(self, key): return self.D[key] def getkey(self, value): return self.R[value] def __setitem__(self, key, value): self.D[key] = value self.R[value] = key def __repr__(self): return "RLdict(%s)" % self.D And in action: >>> d = RLdict(a=1, b=2, c=3, d=4) >>> d RLdict({'a': 1, 'c': 3, 'b': 2, 'd': 4}) >>> d['b'] 2 >>> d.getkey(2) 'b' Naturally both the keys and values must be hashable. The version above makes keys/values a one-to-one mapping; if you want many-to-many, you'll need something more clever. It's also possible that inheriting from dict instead of object would give you a whole lot of extra functionality for free, but I haven't explored that avenue. -- Steven From sturlamolden at yahoo.no Sat Mar 22 11:02:44 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 08:02:44 -0700 (PDT) Subject: How to implement command line tool integrating parsing engine References: Message-ID: On 22 Mar, 14:48, llandre wrote: > - it must run both on linux and windows PC > - it must interact with an electronic device connected to the PC through > serial cable Python should be fine. > - initially the program must be written in the form of simple command > line tool that is invoked like this: > program python script_file.py > - in the future, it must be possible to develop a graphical frontend on > top of it; the resulting look&feel should be similar on linux and windows. Python has numerous cross-platform GUI libraries. > As I never used python, I ask you: > 1) about the script file, which language - for which a parsing engine is > already available in python - do you suggest? I'd suggest Python... > 2) about the graphical frontend, which graphical libraries do you recommend? wxPython, PyGTK, tkinter, PyQt, or PyGame are some options. I have started to prefer wxPython together with wxFormBuilder for my graphical frontends. http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-with-wxpython.html From ACooper at cimtek.com Tue Mar 11 09:02:43 2008 From: ACooper at cimtek.com (Cooper, Andrew) Date: Tue, 11 Mar 2008 09:02:43 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: References: Message-ID: Are there any Python C API experts/SWIG experts out there that can help me with this issue please. Andy -----Original Message----- From: python-list-bounces+acooper=cimtek.com at python.org [mailto:python-list-bounces+acooper=cimtek.com at python.org] On Behalf Of Cooper, Andrew Sent: 10 March 2008 15:55 To: python-list at python.org Subject: Obtaining the PyObject * of a class I',m currently using SWIG to generate a python interface to a C DLL. I'm new to the Python C API and have a question that has been stumping me for the last week. As part of the wrapper process I want to hide some of the complexity with dealing with handles using a python class. But the problem I have is I don't know how to get the PyObject* that refers to the class Pin that I have defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list From sturlamolden at yahoo.no Thu Mar 20 13:53:25 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 10:53:25 -0700 (PDT) Subject: wxFormBuilder References: <9a27e$47e28f17$83aef404$28537@news1.tudelft.nl> Message-ID: <9eab5de1-5c0b-4c81-b83b-2bbcf117db73@c19g2000prf.googlegroups.com> On 20 Mar, 17:21, Stef Mientki wrote: > I've tried several of the above mentioned builders, > with the same result. > I've also looked at wxFormBuilder, > but I found it far too difficult and > fully unreadable (how can you create actions/bindings on components you don't see ?). > So I might be very very naive, > but why all so complex ?? It is not complex. I have posted a small 'Hello World!' howto on my blog. It shows you how to bind events: http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-with-wxpython.html From kaushikbarat at gmail.com Sun Mar 2 03:24:28 2008 From: kaushikbarat at gmail.com (kaush) Date: Sun, 2 Mar 2008 00:24:28 -0800 (PST) Subject: mod_python Unable to create file References: <62v31gF24ontgU1@mid.uni-berlin.de> Message-ID: On Mar 1, 11:24?pm, Marc 'BlackJack' Rintsch wrote: > On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: > > I am using Apache and mod_python to service POST/GET requests on MAC > > OS. My script tries to create a file > > > file = open(file_path, 'w') > > > This fails with the following error > > > EACCES > > Permission denied > > > What is missing? > > To state the ovious: the rights to create a file at `file_path`. ?Remember > that web servers usually have their own "user". > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thanks Marc. In Apache what are the ways/directives to set the rights to a folder? From kevin at bud.ca Sun Mar 2 20:35:21 2008 From: kevin at bud.ca (Kevin Teague) Date: Sun, 2 Mar 2008 17:35:21 -0800 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: "It has to do with the MACOSX_DEPLOYMENT_TARGET. If it's set to 10.4, the legacy version of setpgrp is used (with args), it it's 10.5, setpgrp expects no arguments. It seems configure won't detect the difference." http://bugs.python.org/issue1358 This issue was fixed for Python 2.5. As the issue notes, you can work around it with: ./configure MACOSX_DEPLOYMENT_TARGET=10.5 But it would be really nice if the configure fix for 2.5 was backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped system builds for 2.4 going direct from 2.3 -> 2.5. From dave_mikesell at fastmail.fm Tue Mar 11 05:36:54 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Tue, 11 Mar 2008 02:36:54 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: Message-ID: <64980caf-7321-45da-8248-b16df7ff42fd@x41g2000hsb.googlegroups.com> On Mar 11, 3:03 am, Bob Martin wrote: > in 337600 20080310 222850 dave_mikes... at fastmail.fm wrote: > > >On Mar 10, 2:21 pm, Bob Martin wrote: > > >> Java is more portable than most other languages, especially if your app needs a gui. > > >The promise of Java portability was one of the biggest scams ever > >perpetrated on the software industry. There are issues going from OS > >to OS, VM to VM, DB to DB, app server to app server, etc. Certainly > >no easier than porting C++ and the appropriate libraries, IMHO. > > Quite untrue - I have a stack of large java apps which run without change on > Linux, OS/2 and Windows. Not many, if any, other languages can match that, > and definitely not C++. I'm happy that it's worked for you, but I haven't seen it in my experience. My current client has code that works in 1.4.0, but not higher versions of the JDK without code changes. And other that won't run in later versions of the app server (JBoss) than the one for which it was developed. And upgrading our SQL Server version required an upgrade of DB drivers. Another headache. They have their own JVM requirements as well, as do other packages and libraries. Getting them all to play together hasn't been seamless or easy by any stretch. From sjmachin at lexicon.net Mon Mar 24 18:43:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Mar 2008 15:43:13 -0700 (PDT) Subject: Paramiko bugs out on windows 2003 server References: Message-ID: <97203a80-32ae-4d3e-862a-9ff437d5fa2e@e23g2000prf.googlegroups.com> On Mar 25, 7:50 am, "Tarun Kapoor" wrote: > I am using the paramiko library to pull a data from a server using SFTP. > It works perfect on a windows xp machine but bugs out a windows 2003 > server. I get the following error: > Traceback (most recent call last): > File "S:\Temp\ftpBOA.py", line 5, in ? > import paramiko > File "C:\Python23\lib\paramiko\__init__.py", line 69, in ? > from transport import randpool, SecurityOptions, Transport > File "C:\Python23\lib\paramiko\transport.py", line 32, in ? > from paramiko import util > File "C:\Python23\lib\paramiko\util.py", line 31, in ? > from paramiko.common import * > File "C:\Python23\lib\paramiko\common.py", line 98, in ? > from osrandom import OSRandomPool > File "C:\Python23\lib\paramiko\osrandom.py", line 54, in ? > raise ImportError("Cannot find OS entropy source") > ImportError: Cannot find OS entropy source > > Anyone knows how to solve it ? Here's some meta-help: paramiko seems to be actively maintained and has a mailing list -- see http://www.lag.net/mailman/listinfo/paramiko -- consider asking on that list. Not only is paramiko open source but also you have the source code on your machine already -- consider looking at C:\Python23\lib\paramiko \osrandom.py and see if you can nut out what it is complaining about. Even if you can't, the experience may help you to better answer questions from the maintainer, who may well not have a Windows 2003 server box upon which to replicate the problem. From stefan_ml at behnel.de Tue Mar 4 13:37:55 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 Mar 2008 19:37:55 +0100 Subject: XML Schema validation in Python In-Reply-To: References: Message-ID: <47CD9703.9000808@behnel.de> Medhat.Gayed at gmail.com wrote: > I tested and tried a few XML validators but none of them is able to > successfully validate a string of xml (not a file just a string) to > programatically be able to validate messages of xml that flow in and > out of the different systems. http://codespeak.net/lxml/tutorial.html#parsing-from-strings-and-files http://codespeak.net/lxml/validation.html#validation-at-parse-time http://codespeak.net/lxml/validation.html#xmlschema Stefan From jjlofaro at yahoo.com.au Tue Mar 25 08:08:17 2008 From: jjlofaro at yahoo.com.au (jjlofaro) Date: Tue, 25 Mar 2008 12:08:17 -0000 Subject: Time module is not behaving. Message-ID: Hi I'm just getting myself going again on Python and would appreciate any help. My install of Python seems to have some difficulty loading and using the time module in a script. Strange thing is that if I start another instance of Python I can type in my program manually/interactively and it works. The version of Python I am using is... Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Installed on a Ubuntu 7.10 workstation. Here's my little program.... jeff at office:~/tmp$ more < time.py import time print time.time() And this is what happens when I run it.... jeff at office:~/tmp$ python time.py Traceback (most recent call last): File "time.py", line 1, in import time File "/home/jeff/tmp/time.py", line 2, in print time.time() TypeError: 'module' object is not callable Error in sys.excepthook: Traceback (most recent call last): File "/var/lib/python-support/python2.5/apport_python_hook.py", line 38, in apport_excepthook from apport.fileutils import likely_packaged File "/var/lib/python-support/python2.5/apport/__init__.py", line 1, in from apport.report import Report File "/var/lib/python-support/python2.5/apport/report.py", line 14, in import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys File "/usr/lib/python2.5/urllib.py", line 28, in import time File "/home/jeff/tmp/time.py", line 2, in print time.time() TypeError: 'module' object is not callable Original exception was: Traceback (most recent call last): File "time.py", line 1, in import time File "/home/jeff/tmp/time.py", line 2, in print time.time() TypeError: 'module' object is not callable jeff at office:~/tmp$ Any hints or tips appreciated. Jeff. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Mar 10 23:22:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Mar 2008 23:22:37 -0400 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> <7a6555fa-819a-41c0-befe-ee0123272b31@59g2000hsb.googlegroups.com> Message-ID: "rockingred" wrote in message news:7a6555fa-819a-41c0-befe-ee0123272b31 at 59g2000hsb.googlegroups.com... On Mar 8, 4:15 pm, "Terry Reedy" wrote: > If the sense of else were reversed, one would have to write the clumbsier > > complete = True # though false at this point > while loop_condition: > > if break_condition: > complete = False > break > > else: > > if complete: > > > Terry Jan Reedy Terry, instead of using "complete = True" and setting it to false on failure, why not set "loop_completed = False" and set it to True if the break condition is met? [OE not quoting properly] ===================== Because completion is False when broken? Actually, I am not sure what you mean without seeing the snippet rewritten. Certainly, one could set 'broken=False' at top (tho not true) and 'broken = True' before breaking and test for 'not broken' at end, but that is not an improvement. tjr From robert.kern at gmail.com Fri Mar 7 23:51:52 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 07 Mar 2008 22:51:52 -0600 Subject: distutils - Is is possible to install without the .py extensions In-Reply-To: References: Message-ID: Jari Aalto wrote: > * Fri 2008-03-07 Robert Kern gmane.comp.python.general > * Message-Id: fqsf3a$4lv$1 at ger.gmane.org >> Jari Aalto wrote: >>> #!/usr/bin/python >>> >>> from distutils.core import setup >>> import glob >>> >>> setup(name='program', > ... >>> scripts = ['program,py'], >>> ) >>> that the the result is: >>> >>> /usr/bin/program >>> >>> instead of: >>> >>> /usr/bin/program.py >> The easiest and best way is to just rename the file in your source tree to >> "program" and be done with it. > > Is there any other way? This is the source package that I would like > to keep intact and just patch the setup.py Not really, no. Why is it so important to only patch the setup.py file and not any others? -- 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 tjreedy at udel.edu Thu Mar 6 16:35:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Mar 2008 16:35:39 -0500 Subject: Python on the renderfarm Message-ID: It is fairly well know that cinematic digital effects are most often rendered on *nix machines with efficient numeric code. http://www.linuxjournal.com/article/9951 But Python sometimes has a role too: from the middile of the above link ''' Tippett Studio: Linux Python Pipeline JET is a proprietary Python-based system comprising software tools and scripts used to implement a visual effects and animation pipeline. ?A visual effects and animation pipeline is an assembly line of software used to organize, automate and facilitate the creation of computer-generated imagery?, says Darling. ?The JET tool is highly customizable, featuring XML-based user-interface templates that can be modified to suit specific types of artists or production needs. JET uses modular template chunks to perform each of the tasks in the pipeline, such as rendering or compositing. The templates are implemented as Python objects and are centrally located. JET is not only implemented entirely in Python, but it's also used to generate Python scripts automatically. These custom scripts form unique pipelines for each computer graphics job to run on the renderfarm.? ''' From MartinRinehart at gmail.com Mon Mar 17 07:49:07 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 17 Mar 2008 04:49:07 -0700 (PDT) Subject: lists v. tuples Message-ID: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> What are the considerations in choosing between: return [a, b, c] and return (a, b, c) # or return a, b, c Why is the immutable form the default? From __peter__ at web.de Fri Mar 21 16:04:28 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Mar 2008 21:04:28 +0100 Subject: How can I make a function equal to 0? References: Message-ID: Martin Manns wrote: > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > >>>> def f(): return "" > ... >>>> # Some magic >>>> f == 0 > True > > Thanks in advance > > Martin Use a callable object: >>> class F(object): ... def __cmp__(self, other): return cmp(other, 0) ... def __call__(self): return "" ... >>> f = F() >>> f() '' >>> f == 0 True Peter From castironpi at gmail.com Mon Mar 24 11:17:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 24 Mar 2008 08:17:46 -0700 (PDT) Subject: what are generators? Message-ID: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> I'm looking for a cool trick using generators. Know any exercises I can work? From bj_666 at gmx.net Sun Mar 2 09:24:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Mar 2008 14:24:46 GMT Subject: First post from a Python newbiw References: Message-ID: <62vrleF24ontgU2@mid.uni-berlin.de> On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: > Apart from doing something like > a=[0,0,0] > b=[0,0,0] > c=[0,0,0] > d=[a,b,c] > > is there a better way of creating d?? a = [[0] * 3 for dummy in xrange(3)] Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 11:18:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 15:18:53 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: <13uvbqt55k3or4f@corp.supernews.com> On Sun, 30 Mar 2008 15:03:21 +0200, Peter Otten wrote: > Maybe the following enhancement of timeit would be worthwhile? [snip] Passing a namespace argument would be excellent. > By the way, haven't we been there before, two years ago? > > http://mail.python.org/pipermail/python-list/2006-February/368341.html Two years huh? Gosh, how time flies. -- Steven From Robert.Bossy at jouy.inra.fr Mon Mar 10 11:04:26 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 10 Mar 2008 16:04:26 +0100 Subject: parsing directory for certain filetypes In-Reply-To: <3df2b3f8-64ad-4102-8b60-95717e6748fe@o77g2000hsf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <3df2b3f8-64ad-4102-8b60-95717e6748fe@o77g2000hsf.googlegroups.com> Message-ID: <47D54DFA.4020602@jouy.inra.fr> jay graves wrote: > On Mar 10, 9:28 am, Robert Bossy wrote: > >> Personally, I'd use glob.glob: >> >> import os.path >> import glob >> >> def parsefolder(folder): >> path = os.path.normpath(os.path.join(folder, '*.py')) >> lst = [ fn for fn in glob.glob(path) ] >> lst.sort() >> return lst >> >> > > Why the 'no-op' list comprehension? Typo? > My mistake, it is: import os.path import glob def parsefolder(folder): path = os.path.normpath(os.path.join(folder, '*.py')) lst = glob.glob(path) lst.sort() return lst From hexusnexus at gmail.com Mon Mar 31 15:39:54 2008 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Mon, 31 Mar 2008 12:39:54 -0700 (PDT) Subject: Command line input Message-ID: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> How do I receive input from the command line in Python? From josef.pktd at gmail.com Fri Mar 14 21:05:31 2008 From: josef.pktd at gmail.com (joep) Date: Fri, 14 Mar 2008 18:05:31 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> On Mar 14, 8:15 pm, "David S" wrote: > By mapping network drives in windows I can get past these issues with path > names. > > Thanks, > David > > "Tim Golden" wrote in message > > news:mailman.1949.1205496184.9267.python-list at python.org... > > > David S wrote: > >> Gets me further but still seems to be issue with space after 'Program' as > >> code tries to run 'C:\Program'. Don't understand what is going on here... > > > Slight apologies as I haven't followed this thread closely, but using the > > Acrobat Reader executable, which is, I think, good enough for the > > purposes of illustration: > > > > > import os > > import subprocess > > > filename = r"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe" > > doc = r"C:\Program Files\Adobe\Reader 8.0\Resource\ENUtxt.pdf" > > > print os.path.isfile (filename) > > > os.system (filename + " " + doc) > > > os.system ('"%s" "%s"' % (filename, doc)) > > > subprocess.call ([filename, doc]) > > > > > > os.path.isfile succeeds > > os.system (filename) fails as your code does > > os.system ('"%s"' ...) fails even though both strings are requoted > > subprocess.call (filename) succeeds > > > The latter, at least, is because the subprocess module > > has some special-case handling for exactly this situation > > on MS Windows, while os.system doesn't. > > > Now, ultimately, I don't know if this really helps your > > exact situation but it least it should be clear what will > > and what won't work. Conclusion: use subprocess.call if > > you can. > > > TJG I had the same problem recently with subprocess.popen, when there is a space in the executable and a space in an additional argument as in the acrobat example. I finally found a past thread in this news group that explained that you have to use two (2) leading double quotes, and as on the command line all arguments with spaces have to be quoted. All three examples with acrobat work on my WindowsXP in this case (opens Acrobat three times, after closing previous): import os import subprocess filename = r"C:\Program Files\Adobe\Acrobat 7.0\Acrobat\Acrobat.exe" doc = r"C:\Program Files\Adobe\Acrobat 7.0\Help\ENU\Pdfmark.pdf" print os.path.isfile (filename) print 'case 1' os.system ('""' + filename + '" "' + doc + '"') # quotes split up for clarity: (' " " ' + filename + ' " " ' + doc + ' " ') print 'case 2' os.system ('""%s" "%s"' % (filename, doc)) print 'case 3' subprocess.call ([filename, doc]) Josef From sachincric08 at gmail.com Sun Mar 2 06:42:54 2008 From: sachincric08 at gmail.com (sachincric08 at gmail.com) Date: Sun, 2 Mar 2008 03:42:54 -0800 (PST) Subject: Work Part time or Full time from Home. No Age Bar. Basic Message-ID: Work Part time or Full time from Home. No Age Bar. Basic knowledge in Computers and Internet is enough. http://freeonlinejobs4u.googlepages.com From 42flicks at gmail.com Fri Mar 7 19:39:22 2008 From: 42flicks at gmail.com (Mike D) Date: Sat, 8 Mar 2008 13:39:22 +1300 Subject: DOM parsing not working! Message-ID: <2b54d4370803071639w30912a60i4bc93981533ecfbb@mail.gmail.com> Hello, I've spent the morning trying to parse a simple xml file and have the following: import sys from xml.dom import minidom doc=minidom.parse('topstories.xml') items = doc.getElementsByTagName("item") text='' for i in items: t = i.firstChild print t.nodeName if t.nodeType == t.TEXT_NODE: print "TEXT_NODE" print t.nodeValue text += t.data print text I can't figure out how to print the text value for a text node type. There must be something obvious I'm missing, any suggestions? Thanks. XML is as follows: Stuff.co.nz - Top Stories http://www.stuff.co.nz Top Stories from Stuff.co.nz. New Zealand, world, sport, business & entertainment news on Stuff.co.nz. en-nz Fairfax New Zealand Ltd. 30 /static/images/logo.gif Stuff News http://www.stuff.co.nz Prince Harry 'wants to live in Africa' http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303 For Prince Harry it must be the ultimate dark irony: to be in such a privileged position and have so much opportunity, and yet be unable to fulfil a dream of fighting for the motherland. EDMUND TADROS stuff.co.nz/4423924 Mon, 03 Mar 2008 00:44:00 GMT -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri Mar 28 12:47:55 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 16:47:55 -0000 Subject: How do I reconnect a disconnected socket? References: <13uq69e8us4oo74@corp.supernews.com> Message-ID: <13uq89rskf16u9a@corp.supernews.com> On 2008-03-28, Laszlo Nagy wrote: > >> Yes, that is exactly what it means. >> >> >From the recv() man page: >> >> RETURN VALUE >> These calls return the number of bytes received, or -1 if an error >> occurred. The return value will be 0 when the peer has performed an >> orderly shutdown. >> >> > Mea cupla. :-) > > What about non-blocking sockets? $ man recv ... If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is non-blocking (see fcntl(2)), in which case the value -1 is returned and the external variable errno set to EAGAIN. ... -- Grant From asim.ihsan at gmail.com Sat Mar 1 02:31:23 2008 From: asim.ihsan at gmail.com (Asim) Date: Fri, 29 Feb 2008 23:31:23 -0800 (PST) Subject: Pythons & Ladders References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> <93b6e5e7-be80-408a-8e15-4141b8682392@x41g2000hsb.googlegroups.com> Message-ID: On Feb 28, 9:10?pm, Jeff Schwab wrote: > Benoit wrote: > > Forgive my language concerning C++ as its turned the thread into > > something I did not intend. I merely wished to point out that Python > > was easier for me to learn than C++. ?To Schwab, its likely that Mark > > Lutz is simply a better instructor than my professor. > > Sorry for hijacking your thread! > > In addition to Python Challenge, check out Code Golf: > > ? ? ?http://codegolf.com/ > > It's eye-opening to see how concise the solutions can be. You should also give Project Euler a shot: http://projecteuler.net/index.php?section=problems Just keep in mind two points. One, your solutions should work with under one minute of execution time, even in Python. Secondly, the main benefit of the site is attempting some of the simpler problems and then diving head-first into the forums to see other peoples' solutions to the same problem. I guarantee you'll find some unique Python techniques from these forums that should open new avenues of learning wrt Python for you. Nothing enterprise level...but definitely interesting. Be warned that some of the harder problems require undergraduate-level math. From tms at zeetix.com Sat Mar 15 16:33:24 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 16:33:24 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <007401c886db$d197b780$0200a8c0@TMSMAIN> I appreciate the answers the community has provided, I think I need to add some additional context. I use a trick to let me pass the information into my browser client application. The browser requests the server information from a form whose target is a hidden iframe. The string the server serializes is wrapped in html that embeds it in an onload handler like this: When this html finishes loading, its onload handler fires, it in turn fires the "loadObject" method of the _clientApplication that is waiting for the result, and the clientApplication then unpacks aSerializedObject into the browser. Once back in the browser, the loadObject method calls JSON.parse on aSerializedObject, the json string we're discussing. A serialized object typically contains many (at least tens, and sometimes several hundred) html fragments. It contains at most a handful of apostrophes. That means there are MANY more double quotes than apostrophes, if I delimit attributes with double quotes. In order to successfully pass the escapes to the server, I already have to double any each backslash. At the end of the day, it's easier -- and results in better performance -- to convert each apostrophe to its unicode equivalent, as I originally asked. I just want to know if there's a faster way to persuade simplejson to accomplish the feat. From Lie.1296 at gmail.com Sun Mar 16 04:53:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 01:53:40 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <409579d8-0120-42bd-96e4-fdebf0512fd1@d21g2000prf.googlegroups.com> On Mar 16, 4:43?am, Guido van Brakel wrote: > Hello > > I have this now: > > > def gem(a): > > ? ? g = sum(a) / len(a) > > ? ? return g > > > print gem([1,2,3,4]) > > print gem([1,10,100,1000]) > > print gem([1,-2,3,-4,5]) > > It now gives a int, but i would like to see floats. How can integrate > that into the function? > > Regards, > > -- > Guido van Brakel > Life is like a box of chocolates, you never know what you're gonna get > -- Python 2's division operator's default behavior is to do integer division whenever all of its operands are integers/long and do float division if any of them are float/decimal, in Python 3, this is going to be changed so that division would always be float division and while integer division would have its own operator "//". You can change the default behavior of Python 2 by importing division behavior from __future__ module (from __future__ import division), or you could convert one of the operands to float ("float(a) / b" or "a / float(b)"). From deets at nospam.web.de Sun Mar 2 10:56:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Mar 2008 16:56:26 +0100 Subject: tcp In-Reply-To: <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> Message-ID: <63011aF1bg56vU1@mid.uni-berlin.de> Gif schrieb: > sorry for acting like a fool but this is just to weirdly easy that i > can't get to work. i've written a small web server in another language > and this is more like copying code. > i already have everything figured out, except this one but noone seems > either willing or capable of helping me. > again sorry but i was in a very bad mood. Writing a webserver (you NEVER stated that that is your ultimate goal) is a two-liner in Python. See the module SimpleHTTPServer. Using the extremely lowlevel module socket is a totally different beast. It requires rather deep knowledge of unix sockets, and has a steep learning curve. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 22:19:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 02:19:09 -0000 Subject: Help me on function definition References: Message-ID: <13ur9ott52roc0c@corp.supernews.com> Oh, I forgot to mention... On Sat, 29 Mar 2008 01:47:21 +0000, aeneng wrote: > if __name__=="__main__": ... > print "file name is %s" %__name__ This doesn't do what you expect it to do. You've already established that __name__ is equal to "__main__", so you might as well change that line to: print "file name is not actually __main__" What you want is: print "file name is %s" % __file__ -- Steven From http Thu Mar 20 03:54:37 2008 From: http (Paul Rubin) Date: 20 Mar 2008 00:54:37 -0700 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <7xy78dg79e.fsf@ruckus.brouhaha.com> "Daniel Fetchinson" writes: > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? That would be terrible. Every time I've tried to use one of the other packages it has led to installation hell. Tkinter isn't great, but it's extremely useful to have a gui module that's present automatically in every compete Python installation and that is reasonably cross platform. I can write a Python/Tkinter app under Linux and send it to Windows users and they can run it after a single, very simple Python installation from the Windows .msi. I have no Windows development tools whatsoever and very limited access to Windows boxes, so any Python code I deploy on Windows can't rely on any non-Python code outside of the stdlib. Also, because of tkinter's inherent limitations, I have the impression that upgrading it to the latest and greatest tcl/tk release wouldn't improve it much over the useful but low-rent module that it already is. Therefore, that supposed "benefit" of splitting it out to an external package is not much of a benefit. One of Python's traditionally best attractions has been the depth of its standard libraries, and backing away from that would be plain self-destructive. Python needs more stuff in its stdlib, not less. If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard distro. If that happens (i.e. some new toolkit is brought in and declared to be the standard) then it might be ok to drop Tkinter but it certainly shouldn't be dropped without a replacement. From usenet at solar-empire.de Sat Mar 15 14:31:09 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Sat, 15 Mar 2008 19:31:09 +0100 Subject: Unicode/UTF-8 confusion References: Message-ID: Tom Stambaugh wrote: >> Somehow I don't get what you are after. The ' doesn't have to be escaped >> at all if " are used to delimit the string. If ' are used as delimiters >> then \' is a correct escaping. What is the problem with that!? > > If I delimit the string with double quote, then I have to escape every > double quote in whatever I serialize. I'm moving strict html from the server > to the browser, and therefore the value of every tag attribute is delimited > by double quotes. That means that I'd have to escape every double quote, and > there are MANY more of them. I haven't done much programming with Javascript/AJAX, so why is the following not sufficient? All the double quotes get escaped. >>> link = u"""Click here""" >>> simplejson.dumps(link) '"Click here<\\/a>"' >>> print simplejson.dumps(link) "Click here<\/a>" And ' is a valid delimiter for attributes, so you don't have to use double quotes for them. Marc From lizhongan at gmail.com Sun Mar 16 23:17:31 2008 From: lizhongan at gmail.com (zaley) Date: Sun, 16 Mar 2008 20:17:31 -0700 (PDT) Subject: pass float array(list) parameter to C Message-ID: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> In my program, python is communicated with C use ctypes . I can't find a better way to pass float array(list) parameter to C function. Can someone give me a help? From steve at holdenweb.com Wed Mar 19 06:27:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Mar 2008 06:27:57 -0400 Subject: PSF Community Awards Message-ID: <47E0EAAD.4070204@holdenweb.com> For those who weren't at PyCon, or who missed the announcement (which seems to include all of the recipients :-) I have just made a post in the PSF blog to publicize the first PSF Community Awards. See http://pyfound.blogspot.com/2008/03/psf-community-awards.html These awards are made to recognize those who perform work of benefit to the broader Python community. If you have benefited from the work the first award winners have done, please further acknowledge their valuable contributions by adding a short comment to the post. Steve Holden Chairman, Python Software Foundation From steve at holdenweb.com Tue Mar 4 11:06:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 11:06:29 -0500 Subject: Altering imported modules In-Reply-To: <200803041004.50553.troworld@gmail.com> References: <200803011856.27611.troworld@gmail.com> <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> <200803041004.50553.troworld@gmail.com> Message-ID: Tro wrote: > On Monday 03 March 2008, castironpi at gmail.com wrote: >> On Mar 3, 5:09 pm, Tro wrote: >>> On Sunday 02 March 2008, Paul McGuire wrote: >>>> On Mar 2, 3:48 pm, Tro wrote: >>>>> On Sunday 02 March 2008, Terry Reedy wrote: >>>>>> "Tro" wrote in message >>>>>> news:200803011856.27611.troworld at gmail.com... >>>>>> >>>>>> | Hi, list. >>>>>> | >>>>>> | I've got a simple asyncore-based server. However, I've modified >>>>>> | the >>>>>> >>>>>> asyncore >>>>>> >>>>>> | module to allow me to watch functions as well as sockets. The >>>>>> | modified asyncore module is in a specific location in my project >>>>>> | and is imported >>>>>> >>>>>> as >>>>>> >>>>>> | usual from my classes. >>>>>> | >>>>>> | Now I'd like to use the tlslite library, which includes an >>>>>> | asyncore mixin class. However, tlslite imports "asyncore", which >>>>>> | doesn't include my own modifications. >>>>>> | >>>>>> | I'd like to know if it's possible to make tlslite load *my* >>>>>> | asyncore >>>>>> >>>>>> module >>>>>> >>>>>> | without changing any of the tlslite code. >>>>>> >>>>>> If your module is also 'asyncore' and comes earlier in the search >>>>>> path, I would expect the import to get yours. >>>>> It's not. It has a package prefix like my.package.asyncore. I think I >>>>> can either move my version of asyncore up a couple of levels or add >>>>> the my.package directory to sys.path. >>>>> >>>>> My version of asyncore imports several functions from the built-in >>>>> asyncore. Now that my version of it is imported as asyncore, how >>>>> would it import the built-in version from python2.5/site-packages? >>>>> >>>>> Thanks, >>>>> Tro >>>> What happens if you do "import my.package.asyncore as asyncore"? >>>> >>>> If that doesn't work (trying the simplest hack first), I know that >>>> there are various hooks in the import mechanism that should help. >>> In the classes that use my version of asyncore currently, that is how I >>> do it. I import my version as "import my.package.asyncore as asyncore". >>> In my asyncore module I do "import asyncore", because I override a few >>> functions from the asyncore module included with python. However, if I >>> were to add "my.package" to sys.path, then I wouldn't be able to "import >>> asyncore" from my own asyncore module. I'd have to do some trickery with >>> sys.path to take the "my.package" component out, import standard >>> asyncore, readd the "my.package" component, so that other modules can >>> "import asyncore" and get my version. >>> >>> Is there a way to import the standard python asyncore module in this >>> scenario? >>> >>> Thanks, >>> Tro >>> >>> >> Are you trying to interfere with the default module on only your >> machine? Just rename it. If something in the std. lib. imports >> asyncore, they get yours too that way. > > No, I'd like it to be a generalized solution and only for this one project. > I'm trying to get it to work on any recent python installation out of the > box, so I can't rename built-in modules. What I'm trying to do is allow a 3rd > party module (tlslite) to import *my* version of asyncore without me going > into tlslite's code and changing its import statement explicitly, but only > for the scope of this one project. > In that case try something like import myasyncore as asnycore sys.modules['asyncore'] = asyncore import tlslite regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Mon Mar 31 22:39:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 23:39:36 -0300 Subject: Python and Db References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> Message-ID: En Mon, 31 Mar 2008 17:50:42 -0300, David Anderson escribi?: > I would like to use sqlite, But I also wanted a tutorial with the basis > of > the sql and etc, I never dealed with dbs before Then any database tutorial covering SQL will do. Of course there are differences between different DBMS, but the basics are the same. Once you know the SQL sentence you want to execute (e.g. "select name, salary from employee order by name") consult the Python docs to see how to actually write it: conn = sqlite3.connect('acme.db') cursor = conn.cursor() cursor.execute("select name, salary from employee order by name") for row in cursor: name, salary = row print "%20s %8.2f" % (name, salary) -- Gabriel Genellina From phishboh at gmail.com Mon Mar 17 05:08:30 2008 From: phishboh at gmail.com (phishboh at gmail.com) Date: Mon, 17 Mar 2008 02:08:30 -0700 (PDT) Subject: Image capture from Alacron FastFrame-CB Message-ID: Hi. I would like to perform some image processing using Python. Can someone please point me in the right direction on how to get images from the framegrabber (Alacron FastFrame-CB)? Is VideoCapture (http://videocapture.sourceforge.net/) the correct way to go? Thanks in advance. From castironpi at gmail.com Wed Mar 26 01:46:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 22:46:17 -0700 (PDT) Subject: My python interpreter became mad ! References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> Message-ID: <8f52bc76-e0e8-4bd9-93e2-0f37426869b6@k13g2000hse.googlegroups.com> On Mar 25, 7:45?pm, John Machin wrote: > Furkan Kuru incorrigibly top-posted: > > > Ok, you're right. > > > but I did not give it a chance "not trying python interpreter in another > > directory" > > I don't understand that sentence. > > > so if we assume the problem exists in every directory, it has something > > to do with ?pythonpath. > > Why would/should we assume that? Process of enumeration. > > you can try setting pythonpath to some directory and put a re.py there > > and try from any directory starting your interpreter and importing re. > > and achieve the same result: importing the bogus re. What's your point? I'm not so sure that dispute burdens of proof are resolved all that virtuously (life isn't fair; fair is good). What are newsgroups like in the monarchies? Ever feel you're typing on auto-pilot? It's not like you vote on me staying. However, the things I've said about myself aren't written intepretation-strict, thence there must be some distinction between interpretations, or between resident attitudes for me? Perhaps my fault for overinvesting hope in the newsgroups. You're not a best friend to me! . If you look like your pets, do we look like computers? Restrictions are different for justice: my only analytically (or never) outweighs my threshold. By the process of cognition, we ascribe malice (how probabilistically- malicious is it) to people (as danger to objects?), but the ideal realm (kingdom Logos), but revising estimates is expensive. Do visual mirrors make a round-trip error? Is there emotionally such thing as a computer? They are certainly deep, but perhaps only axiomatically; people aren't made of binary. How far to the nearest indefinite precision computer? Any pull around here? Someone have a thesis on wake-detection in a parallel system? Can we 'black-box' people? ("Are you a black box?") What kind of accuracy is there in uniform media? Can we 'black-box' groups? Wakes and patterned perturbations can be modeled in feature-sets, abitrary feature collisions not fully particle. I'd be more interested in a feature specialty that facilitates to transmit waves, and a sum-of-waveform native. Is there a recursive expression of the taylor expansion of e^x, by the way? Interface and deface. Honest and true? Can you just buffer? Beliefs might settle wrong, and it's hard to change them: huge machine, right nail. Can a spider swarm simulate a macro operation (building a building), either given a power source or carrying "lifeform batteries"? Operator would need interface: thought to operation: fast enough - idle loop cost: can't be governing every small bug (once again, features over particles), the machines would need overall/level/summary operations, read memories. But you can get a couple microvolts and a memory cell on a 2-micron spider, and a radio-static but sees a medium, speed-of-propogation, limitation. Just think outside the case. How organized is the newsgroup? Can I buy a long non-commutative associative (time order (resort)) record? It's not. (That's a tongue thing, right?) A place to come to: a place to sit at energy level. (New you vs. same me here too.) 2-D primitives suck on serial input. I'd almost rather decode a video of hands. Would a computer mind learning? You could by a perceptive-order code. What the world needs is a few good spacers. I have to think; leave silent, and return broadcasting. How's yours suck + what's the monkey on your back? Multi-type time people for sale, American dollar. Anyone up for a little register- base broadcasting? It's a broad. From aaron.watters at gmail.com Fri Mar 28 09:33:29 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 28 Mar 2008 06:33:29 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: On Mar 27, 6:00 pm, John Machin wrote: > ...The Python csv module emulates Excel in delivering garbage silently in > cases when the expected serialisation protocol has (detectably) not > been followed.... Fine, but I'd say the heuristic adopted produces bizarre and surprising results in the illustrated case. It's a matter of taste of course... -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=mondo+bizarre From hdante at gmail.com Sun Mar 30 08:41:28 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 05:41:28 -0700 (PDT) Subject: python ODF library? References: Message-ID: On Mar 30, 9:29 am, Matias Surdi wrote: > Do yo know any good OpenDocumentFormat library for python? > > I'm starting a project on wich I'll have to programatically modify ODF > text documments, so, after reinventing the wheel, I'd like to know if > already something exists. > > Thanks a lot. Excellent question. I've found this (have no idea if it works). http://appyframework.org/pod.html It's possible that you could implement what you want by hand. There's this book: http://books.evc-cit.info/odbook/book.html which has a lot of code snippets. On the other hand, it may be easier to pick and editor and go with its scripting lanugage. From tenax.raccoon at gmail.com Mon Mar 24 10:48:04 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 24 Mar 2008 07:48:04 -0700 (PDT) Subject: Shortcutting the function call stack References: Message-ID: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> On Mar 24, 5:21 am, Julien wrote: > Hello all, > > I would like to do something like: > > def called(arg) > if arg==True: > !!magic!!caller.return 1 > > def caller(arg) > called(arg) > return 2 > > Here, the fake !!!magic!!! represents a statement (which I ignore) > that would make the caller function return a value different from what > it'd return normally. > > For example, caller(True) would return 1, and caller(False) would > return 2. The reason I want that is because I don't want the caller > function to know what's going on in the called function, and be > shortcut if the called function think it's necessary. > > Would you know if that's possible, and if so, how? > > I've done a bit of research and I think I've found some good pointers, > in particular using the 'inspect' library: > > import inspect > > def called(arg) > if arg==True: > caller_frame = inspect.stack()[1] > ... > > Here 'caller_frame' contains the frame of the caller function. Now, > how can I make that frame return a particular value? > > By the way, I'm not really interested in 'called' throwing an > exception and 'caller' catching it. In fact, I want things to remain > completely transparent for 'caller'. > > Hope that was clear... :/ > > Thanks! > > Julien As Steven wrote, it's not very clear. If we knew the intent of this, we could perhaps point you to a more useful, maintainable technique. We don't know why you're trying to circumvent the programming language in this case. Any solution that works as you described will probably be unportable between the different Pythons (CPython, Jython, IronPython, etc). Please note that the following code should work, but I've only run it through the interpreter in my brain. My brain's interpreter is full of Heisenbugs, so you may need to adjust a few things. Here's my thoughts: Given: def First( arg ): Second( arg ) return 5 1) If you can modify both functions, change the first function to return a value in certain circumstances: def AltFirst( arg ): value = Second( arg ) if value is not None: return value return 5 2) Raise an exception in Second, and catch that exception above First: class SecondExcept(Exception): def __init__(self, value): Exception.__init__(self, 'Spam!') self.value = value def Second(arg): if arg == my_conditional_value: raise SecondExcept( 5 ) # The following could even be put in your own function, # or in a wrapper or decorator for the First function. try: myvalue = First( 'Vikings!' ) except SecondExcept, exc: myvalue = exc.value When you need to use an exceptional pathway, use an exception. They aren't just for reporting errors. Hope this helps. --Jason From usenet at solar-empire.de Mon Mar 10 10:40:10 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Mon, 10 Mar 2008 15:40:10 +0100 Subject: tcp client socket bind problem References: Message-ID: natambu at gmail.com wrote: > I have a linux box with multiple ip addresses. I want to make my > python client connect from one of the ip addresses. Here is my code, > no matter what valid information I put in the bind it always comes > from the default ip address on the server. Am I doing something wrong? > > ------------- > #!/usr/bin/python > > import socket > > host = "server" > port = 1190 > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.bind(("",0)) > sock.connect((host, port)) > ------------- Looks good to me. Just to verify it, I added 127.1.2.3 as an address to lo (ip addr add 127.1.2.3/8 dev lo broadcast 127.255.255.255), and... >>> import socket >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> sock.bind(("127.1.2.3",0)) >>> sock.connect(("127.0.0.1",80)) In another shell: tolot:~> lsof -c python -a -i -nP COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME [...] python 1287 tolot 3u IPv4 3553610 TCP 127.1.2.3:38329->127.0.0.1:80 (ESTABLISHED) Looks correct. This is using Linux 2.6.23. So, if you're doing something wrong, it's nothing obvious to me. Marc From furkankuru at gmail.com Tue Mar 25 19:04:59 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 01:04:59 +0200 Subject: My python interpreter became mad ! In-Reply-To: <47E964CA.4070603@lexicon.net> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> Message-ID: <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> Ok, you're right. but I did not give it a chance "not trying python interpreter in another directory" so if we assume the problem exists in every directory, it has something to do with pythonpath. you can try setting pythonpath to some directory and put a re.py there and try from any directory starting your interpreter and importing re. On 3/25/08, John Machin wrote: > > Furkan Kuru top-posted: > > Most probably X-Spam added itself to your path. > > What is "X-Spam"? Added itself to Benjamin's path [not mine] in such a > fashion that it is invoked when one does "import re"? > > > you should look at your PATH and PYTHONPATH environment variables. > > Most *IM*probably. Read the traceback: > """ > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > """ > > This is a classic case of a script (which does not guard against side > effects (like spewing out gibberish) when imported instead of being > executed) being given the same name as a Python-included module and > being executed in the current directory and hence ends up importing > itself. > > > > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > > wrote: > > > > On Mar 25, 10:05 pm, Benjamin Watine > > wrote: > > > Yes, my python interpreter seems to became mad ; or may be it's > > me ! :) > > > > > > I'm trying to use re module to match text with regular > > expression. In a > > > first time, all works right. But since yesterday, I have a very > > strange > > > behaviour : > > > > > > $ python2.4 > > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > > Type "help", "copyright", "credits" or "license" for more > > information. > > > >>> import re > > > X-Spam-Flag: YES > > [snip] > > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > > > >>> > > > > > > What's the hell ?? I'm just importing the re module. > > > > No you're not importing *the* re module. You're importing *an* re > > module, the first one that is found. In this case: your own re.py. > > Rename it. > > > > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From noah at noah.org Thu Mar 13 21:34:49 2008 From: noah at noah.org (Noah) Date: Thu, 13 Mar 2008 18:34:49 -0700 (PDT) Subject: How do I iterate over items in a dict grouped by N number of elements? Message-ID: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> What is the fastest way to select N items at a time from a dictionary? I'm iterating over a dictionary of many thousands of items. I want to operate on only 100 items at a time. I want to avoid copying items using any sort of slicing. Does itertools copy items? This works, but is ugly: >>> from itertools import * >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} >>> N = 3 >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N): ... print G ... (('a', 1), ('c', 3), ('b', 2)) (('e', 5), ('d', 4), ('g', 7)) (('f', 6), ('i', 9), ('h', 8)) (('j', 10), None, None) I'd prefer the last sequence not return None elements and instead just return (('j',10)), but this isn't a huge deal. This works and is clear, but it makes copies of items: >>> ii = D.items() >>> for i in range (0, len(ii), N): ... print ii[i:i+N] ... [('a', 1), ('c', 3), ('b', 2)] [('e', 5), ('d', 4), ('g', 7)] [('f', 6), ('i', 9), ('h', 8)] [('j', 10)] -- Noah From iwanttobeabadger at googlemail.com Mon Mar 24 18:56:08 2008 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Mon, 24 Mar 2008 22:56:08 +0000 Subject: Calling a shared library using C types In-Reply-To: References: Message-ID: Hi, I know this is a pretty simple question but I've spent a while on this and can't see whats wrong. I'm trying to access a shared library which I've created called Simulation.so, its created as such (snip from makefile): all: simulation simulation: Simulation.so Simulation.so: Simulation.o Statistics.o gcc -shared Simulation.o Statistics.o -L/usr/local/lib -lsbml -lstdc++ -lm -o Simulation.so Statistics.o: Statistics.c Statistics.h gcc -fpic -g -O2 -I/usr/include -c Statistics.c Simulation.o: Simulation.c gcc -fpic -g -O2 -I/usr/include -c Simulation.c and I can load it properly in python import ctypes t = ctypes.CDLL('./Simulation.so') this works fine, I have a simple function I ve put in for testing which just returns the integer 4. However when I try to access this function it doesnt work t.test() File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 325, in __getattr__ func = self.__getitem__(name) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 330, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x81e6b0, test): symbol not found I've tried using t.__getattr__("test") but still have the same exception, I've tried loading the library with mode = RTLD_GLOBAL aswell and still have no luck. As far I as I can see this should work? But as I am just starting with ctypes I am sure I doing something sorry very stupid. Any pointers would be greatly appreciated, Many thanks in advance, Nathan Im hoping python-list is ok for questions regarding ctypes :S -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregory.bronner at lehman.com Fri Mar 7 09:13:57 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 7 Mar 2008 09:13:57 -0500 Subject: Edit and continue? Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2972@nypcmg1exms318.leh.lbcorp.lehman.com> I haven't seen much on this for a few years: I'm working on a GUI application that has lots of callbacks. Testing it is very slow and quite boring, as every time I find an error, I have to exit it, restart it, and repeat the series of clicks. It would be really amazing if python supported a reasonable form of edit and continue. Is there any way to do this? I'd like to be able to change my code and have it apply to a running instance of a class. Thanks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From castironpi at gmail.com Sun Mar 2 11:02:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 08:02:50 -0800 (PST) Subject: Keeping the console window References: <62vs0iF24tv6jU1@mid.individual.net> <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> Message-ID: On Mar 2, 9:55?am, Sam wrote: > You may use python in interactive mode: > > $ python -i yourScript.py > > Or use a blocking readline: > > $ cat yourScript.py > import sys > sys.stdin.readline() > > ++ > > Sam FWIW, for what it's worth, you can invoke the interpreter from a batch file/shell script too, and just use the native PAUSE instruction to prompt for 'any key to continue'. From miki.tebeka at gmail.com Wed Mar 12 18:34:48 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 12 Mar 2008 15:34:48 -0700 (PDT) Subject: How to make a Tkinter widget always visible? References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> <47D6C81A.1070301@codebykevin.com> <47D6D890.3060104@codebykevin.com> Message-ID: Hello Kevin, > Please post the code you're using--it will be easier to help if we can > see exactly what you are trying. In a nutshell: ------------------------------- import Tkinter as tk, tkFont from tkMessageBox import showinfo, showerror from os import popen def main(): root = tk.Tk() # Log window tk.Label(root, text="Log:", anchor=tk.W).pack(fill=tk.X) frame = tk.Frame(root) scrollbar = tk.Scrollbar(frame) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) log = tk.Text(frame, width=80) log.config(state=tk.DISABLED) log.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) scrollbar.config(command=log.yview) frame.pack(fill=tk.BOTH, expand=1) # Button frame frame = tk.Frame(root) update = tk.Button(frame, text="GO", command=lambda: showinfo("OUCH")) update.pack(side=tk.LEFT) tk.Button(frame, text="Quit", command=root.quit).pack(side=tk.LEFT) frame.pack(fill=tk.X) root.bind("", lambda e: root.quit()) update.focus() root.minsize(-1, 100) root.mainloop() if __name__ == "__main__": main() ------------------------------- When I pack the buttons frame first (using side=BOTTOM), it stays visible at all times. Thanks, -- Miki http://pythonwise.blogspot.com From musiccomposition at gmail.com Sat Mar 15 22:28:32 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 15 Mar 2008 19:28:32 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: On Mar 15, 7:29 pm, castiro... at gmail.com wrote: > 'join' in the wrong word for the method in class Thread. > > The agent-patient semantics of calling functions can get ambiguous. > It is not a problem of native Pythoners alone. Is it due to lazy > programming, an inability of English (do you have it in other > languages?), or not a problem at all? This is what Java uses, and Python's threading module tries to imitate it. > > th1.join() doesn't mean, 'do something to th1', or even, 'have th1 do > something to itself.' In fact, if anything is doing anything > differently, taking waiting to be doing something different, it's the > caller. > > Translating literally, > > th1.join() -> join me here, th1. > > And, > > file1.close() -> close yourself, file1. > > But not, > > th1.join() -/> join yourself, th1. > > Worse, > > lock1.wait() -/> wait, lock1. (For what?) > > Furthermore, in toolbars: > > File -> Open -/> file an open. > > and: > > File -> Load -/> load a file. (It means, load the computer.) > > In English, the placements of identifiers isn't consistent. IOW, > there isn't a syntactic mapping into natural language sentences. > (Though you can do it in Latin, German, Sanskrit, and Russian with > case markers*.) What are the true literals? What's doing what? > > th1.join() -> 'be joined by th1' > file1.close()-> 'close file1' > lock1.wait()-> 'getinlinefor lock1' > > And of course, 'open' isn't a method of File objects at all. The > closest is, 'be loaded by file1'. > > Assuming speakers** of classical computer languages use OVS order-- > object-verb-subject***, the most literal transformations are: > > th1.bejoinedby() > file1.close() > lock1.getinlinefor(). > > The mapping of identifiers to English isn't consistent. It takes some > knowledge to read them-- shuffle an English sentence and it changes > meaning. > > Functional languages are one long sentence: True.**** Declarative > ones tell a story. ('th1' joins him.) Imperatives command an > impartial audience. > > What do the docs say about it? > > ''' > Thread.join([timeout]) > Wait until the thread terminates. This blocks the calling thread until > the thread whose join() method is called terminates - either normally > or through an unhandled exception - or until the optional timeout > occurs. > > When the timeout argument is present and not None, it should be a > floating point number specifying a timeout for the operation in > seconds (or fractions thereof). As join() always returns None, you > must call isAlive() after join() to decide whether a timeout happened > - if the thread is still alive, the join() call timed out. > > When the timeout argument is not present or None, the operation will > block until the thread terminates. > > A thread can be join()ed many times. > > join() raises a RuntimeError if an attempt is made to join the current > thread as that would cause a deadlock. It is also an error to join() a > thread before it has been started and attempts to do so raises the > same exception. > ''' > > The natural language meaning of 'join' isn't used. Do benevolent > dictators do this? What do malevolent ones call themselves? > > *Latin, German, Sanskrit, and Russian can do it. Latin, German, > Sanskrit, and Russian -speakers- can do it. > **It would be interesting to try to learn a language without ever > speaking it. > *** English is SVO, subject-verb-object. French is too, unless the > object is direct: subject- direct-object -verb. > **** The sum of the first three integers in the last two files, sorted > alphabetically, in 'c:\programs'. From mahesh.prakriya at gmail.com Tue Mar 18 01:39:07 2008 From: mahesh.prakriya at gmail.com (mahesh.prakriya at gmail.com) Date: Mon, 17 Mar 2008 22:39:07 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 7:10?am, Bruce Eckel wrote: > If the following seems unnecessarily harsh, it was even more harsh for > me to discover that the time and money I had spent to get to my > favorite conference had been sold to vendors, presenting me as a > captive audience they could pitch to. > Yes, the keynotes were very boring compared to last year. If there's only one thing ot change, I think sponsorship shouldn't entitle one to a keynote. FWIW, tho we sponsored at a Platinum level from Microsoft this year but we declined to take up on any lightning talks, etc. To me, its worth sponsoring PyCon (just for Python) irrespective of what we get. From crackeur at comcast.net Tue Mar 4 19:54:16 2008 From: crackeur at comcast.net (jimmy Zhang) Date: Tue, 4 Mar 2008 16:54:16 -0800 Subject: Latest XML Parsing/Memory benchmark Message-ID: The latest benchmark results are now available using the latest Intel Core2 Duo processor. In summary, VTD-XML using JDK 1.6's server JVM achieved an astonishing 120MB/sec sustained throughput per core on a Core2 Duo 2.5 GHz processor. * Parsing Only: http://www.ximpleware.com/2.3/benchmark_2.3_parsing_only.html * XPath Only: http://www.ximpleware.com/2.3/benchmark_2.3_xpath.html * Parsing/XPath/Update: http://www.ximpleware.com/2.3/benchmark_2.3_update.html * Indexing/XPath/Update: http://www.ximpleware.com/2.3/benchmark_2.3_indexing.html From timr at probo.com Sat Mar 1 01:59:29 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 01 Mar 2008 06:59:29 GMT Subject: rstrip error python2.4.3 not in 2.5.1? References: <3bb061c2-4ec0-4ad0-add0-035264caa28b@s37g2000prg.googlegroups.com> <5114b18c-80ab-43b7-bedf-e8a553093be3@k2g2000hse.googlegroups.com> Message-ID: dirkheld wrote: >> >> What is the actual error message [SyntaxError, NameError? etc] that you >> clipped? > >Here it is : I tought that I didn't matter because the deliciousapi >worked fine on my mac. > >Traceback (most recent call last): > File "delgraph.py", line 62, in ? > url_metadata = d.get_url(site.rstrip()) > File "deliciousapi.py", line 269, in get_url > document.bookmarks = self._extract_bookmarks_from_url_history(data) > File "deliciousapi.py", line 297, in >_extract_bookmarks_from_url_history > timestamp = datetime.datetime.strptime(month_string, '%b ‘ >%y') >AttributeError: type object 'datetime.datetime' has no attribute >'strptime' I suppose it is cruel of me, but I find it hilarious that you looked at this traceback and came to the conclusion that the problem was in "rstrip". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mnordhoff at mattnordhoff.com Wed Mar 12 09:09:06 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 12 Mar 2008 13:09:06 +0000 Subject: Creating a file with $SIZE In-Reply-To: <47D7D1F3.5040706@jouy.inra.fr> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> Message-ID: <47D7D5F2.8050303@mattnordhoff.com> Robert Bossy wrote: > k.i.n.g. wrote: >> I think I am not clear with my question, I am sorry. Here goes the >> exact requirement. >> >> We use dd command in Linux to create a file with of required size. In >> similar way, on windows I would like to use python to take the size of >> the file( 50MB, 1GB ) as input from user and create a uncompressed >> file of the size given by the user. >> >> ex: If user input is 50M, script should create 50Mb of blank or empty >> file >> > def make_blank_file(path, size): > f = open(path, 'w') > f.seek(size - 1) > f.write('\0') > f.close() > > I'm not sure the f.seek() trick will work on all platforms, so you can: > > def make_blank_file(path, size): > f = open(path, 'w') > f.write('\0' * size) > f.close() I point out that a 1 GB string is probably not a good idea. def make_blank_file(path, size): chunksize = 10485760 # 10 MB chunk = '\0' * chunksize left = size fh = open(path, 'wb') while left > chunksize: fh.write(chunk) left -= chunksize if left > 0: fh.write('\0' * left) fh.close() > Cheers, > RB -- From davids at evertech.com.au Fri Mar 14 07:38:31 2008 From: davids at evertech.com.au (David S) Date: Fri, 14 Mar 2008 11:38:31 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: Hi, Gets me further but still seems to be issue with space after 'Program' as code tries to run 'C:\Program'. Don't understand what is going on here... using "java.exe" from "C:\Program Files\Java\jdk1.6.0_01" using "C:\Program Files\apache-ant-1.7.0\bin\ant.bat" for building Building from E:\Red5\red5_server\install\windows Cleaning old directories... Compiling Java 1.5 version... 'C:\Program' is not recognized as an internal or external command, operable program or batch file. Traceback (most recent call last): File "installer.py", line 132, in main() File "installer.py", line 128, in main builder.build() File "installer.py", line 70, in build self.compile(self.ant_cmd, os.path.join(red5_root, 'build.xml'), '1.5', 'cle an', 'installerdist') File "installer.py", line 26, in compile assert os.system('%s -quiet -Djava.target_version=%s -buildfile %s%s' % (ant , version, script, args)) == 0 AssertionError "Bryan Olson" wrote in message news:LxqCj.19741$Ch6.1841 at newssvr11.news.prodigy.net... > David S wrote: >> I get >> >> ERROR: ""C:\Program Files\apache-ant-1.7.0\bin\ant"" does not exist >> >> If I cut the path statement here and paste it next to a windows XP >> command prompt ant is invoked. >> >> The python code here is >> if not os.path.isfile(ANT_CMD): >> error('"%s" does not exist' % ANT_CMD) > > There you don't want the quotes within the string. On my MS-Win box: > > >>> import os > >>> os.path.isfile(r'C:\Program Files\Windows NT\dialer.exe') > True > >>> print os.path.isfile(r'"C:\Program Files\Windows NT\dialer.exe"') > False > > > -- > --Bryan From bearophileHUGS at lycos.com Wed Mar 5 19:40:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 5 Mar 2008 16:40:56 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> Message-ID: <83f40c69-a356-4af3-8fcf-aac4097dc480@n75g2000hsh.googlegroups.com> Troels Thomsen: > The discussion of words is silly. My surprise about "else following a for > loop.... what the heck ...." lasted excactly as long as it takes to read > this sentence. Maybe I don't follow what you are saying, but well chosen words are a very important part of a well designed API. If you take a look at the Python developers mailing list you may see that people discuss days, weeks to find the best naming for things. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 20:23:13 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 00:23:13 -0000 Subject: Access function name from within a function References: Message-ID: <13tgsvhe3too5d2@corp.supernews.com> On Thu, 13 Mar 2008 00:16:13 +0100, Hellmut Weber wrote: > Hi, > i would liek to define an error routine which print amongs other things > the name of the function from which it has been called. You mean like Python exceptions already do? >>> def broken(): ... x = 100 + 'foo' ... return x ... >>> broken() Traceback (most recent call last): File "", line 1, in File "", line 2, in broken TypeError: unsupported operand type(s) for +: 'int' and 'str' > IOW what I'm looking for is: > > def bar(): > name = some_function(some-parameter) > print name > > should print 'bar' I'm guessing that what you want to do is something like this: def bar(): do_calculation() if error: call_error_routine("something went wrong", magic_function()) where magic_function() knows the name of bar() is "bar". But you already know the name of the function when you write it, so why can't you do this? def bar(): do_calculation() if error: call_error_routine("something went wrong", "bar") Of course, this has the disadvantage that if you change the name of the function bar(), you have to manually change the argument to your error routine as well. Another approach is this: def bar(): import inspect return inspect.getframeinfo(inspect.currentframe())[2] but this should be considered the deepest Black Magic. I can make no promises that it will work the way you expect it to work in all circumstances. If you use this, you're elbow-deep in the Python internals. Frankly, I think your approach of having an "error routine" is probably the wrong approach, and you're better to use exceptions. But I could be wrong. -- Steven From castironpi at gmail.com Sun Mar 2 21:50:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 18:50:43 -0800 (PST) Subject: along the lines, hash and obj. id. References: <1460d022-a990-42d8-8117-4f28025d1027@b29g2000hsa.googlegroups.com> <13s78vvhjhl1df8@corp.supernews.com> <59e8ba74-0014-4366-a293-d15a0aabb23d@h25g2000hsf.googlegroups.com> Message-ID: <3f9f7fae-e0cd-46be-9128-298b6cdd4be4@s13g2000prd.googlegroups.com> On Feb 27, 5:38?pm, castiro... at gmail.com wrote: > On Feb 27, 4:16 pm, "Gabriel Genellina" > > For a), you use something like obj.a.somemethod(). "obj.a" still refers to > > the same object, even if it changed internally; if obj.a and foo.bar both > > were refering to the same object, they still do. [1] > > Or wrap the value into another shared object. > it can still set the element there: elem.val= 0, elem.val+= 1, &c., in Following obj.a.val is foo.bar.val and obj.a is foo.bar, you can also get away with a= A(); a.c.val= 2; assert A.c.val== 2. From fakeaddress at nowhere.org Fri Mar 21 05:17:10 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 21 Mar 2008 09:17:10 GMT Subject: finding items that occur more than once in a list In-Reply-To: References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Bryan Olson wrote: [...] >> Arnaud Delobelle offered a good Wikipedia link, and for more background >> look up "amortized analysis. > > Hrvoje Niksic provided the link :). Oops, careless thread-following. Hrvoje Niksic it was. > I still think two unrelated > things are being compared in this thread when people say that method A > (using dictionaries / sets) is O(n) and method B (sorting the list) > O(nlogn). > > Isn't it the case that: > > | Worst case | Average case > ---------|------------|------------- > Method A | O(n^2) | O(n) > Method B | O(nlogn) | O(nlogn) > > Which method is the best would then be determined by the distribution > of the hash values of your data, and whether you want to have a > guarantee the method will have a less-than-quadratic behaviour. If we exclude the case where an adversary is choosing the keys, the chance of a seriously degenerate case in the hashing method is so remote that we do should not worry about it. Those who insist on ranking by worst-case behavior have probably abandoned Python long ago, as it uses those hashed 'dict' things everywhere. Of course they've also abandoned OS's with demand-paged virtual memory and such. -- --Bryan From keios.titan at gmail.com Thu Mar 6 14:14:54 2008 From: keios.titan at gmail.com (keios.titan at gmail.com) Date: Thu, 6 Mar 2008 11:14:54 -0800 (PST) Subject: Exploring Attributes and Methods Message-ID: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Hi, Is there a python command that allows me to extract the names (not values) of the attributes of a class. example Class Sample: fullname = 'Something' How can I know that this class has an attribute called 'fullname'? I hope my question is clear. Thanks From kf9150 at gmail.com Fri Mar 28 20:02:51 2008 From: kf9150 at gmail.com (Kelie) Date: Fri, 28 Mar 2008 17:02:51 -0700 (PDT) Subject: case insensitive lstrip function? References: <0eb666fe-8c3e-4a93-afbf-1953922c19bd@s13g2000prd.googlegroups.com> <655bbtF2e1u8fU2@mid.uni-berlin.de> Message-ID: <9b90c8d9-a53b-4a03-9a11-4af00e47bf2a@i29g2000prf.googlegroups.com> On Mar 28, 12:55 pm, Marc 'BlackJack' Rintsch wrote: > What about this: > > def lstrip2(string, chars, ignore_case=True): > if ignore_case: > chars = chars.lower() + chars.upper() > return string.lstrip(chars) > > Ciao, > Marc 'BlackJack' Rintsch Thanks Marc. I think yours looks much better. From castironpi at gmail.com Mon Mar 10 01:30:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 22:30:22 -0700 (PDT) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> Message-ID: <1af35fba-fdee-42b8-8196-568818c97860@d62g2000hsf.googlegroups.com> On Mar 8, 12:57?pm, Tim Chase wrote: > > I am a GNU newbie. ?(I know C &o.) ?Can you point me to a > > place to find the source for 'date'? > > It's part of the GNU Coreutils: > > http://ftp.gnu.org/gnu/coreutils/ > > Within the file, you're likely interested in lib/getdate.* > > It helps if you have a working knowledge of Yacc. > > -tkc Ah excellent. I am looking at the part with: static table const meridian_table[] = { { "AM", tMERIDIAN, MERam }, ... { "JANUARY", tMONTH, 1 }, { "FEBRUARY", tMONTH, 2 }, ... { "YEAR", tYEAR_UNIT, 1 }, { "MONTH", tMONTH_UNIT, 1 }, (where is 'lunar month'? ;) ) How do you like it? Certainly Python cleans it up by a multiple, but what about the rest? From aahz at pythoncraft.com Mon Mar 17 09:16:36 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 Mar 2008 06:16:36 -0700 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> Message-ID: In article <873aqp6bbq.fsf at physik.rwth-aachen.de>, Torsten Bronger wrote: >Carl Banks writes: >> On Mar 16, 10:49 pm, Brian Jones wrote: >>> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: >>>> >>>> If you did not like the programming this year (aside from the >>>> sponsor talks) and you did not participate in organizing PyCon >>>> or in delivering presentations, it is YOUR FAULT. PERIOD. >>>> EXCLAMATION POINT! >>> >>> I find this insulting, inexcusable, and utter nonsense. If >>> putting the blame for a failed experiment on the backs of the >>> good folks who paid good money for travel, lodging, and >>> registration is also an experiment, you can hereby consider it >>> also failed. >> >> He said "aside from the sponsor talks", chief. > >I see no reason why the "fault" for parts of the rest being >sub-optimal, too, must necessarily be on the attendee's side. (Just >hypothetically; I wasn't at PyCon.) Let's suppose you have a group of friends who collectively throw a party. They invite you to help out organizing it and putting it together, but you choose not to. If you don't have a good time at the party because it wasn't what you wanted, I think it's fair to say it was your fault. And I think exactly the same thing is true for PyCon, albeit on a much larger scale. It is absolutely critical to the long-term success of PyCon as a volunteer-run community conference that each attendee take responsibility for their experience. Science fiction fandom -- the part that holds volunteer-run events such as Worldcon -- has lots of experience with this model. It is one reason why such cons make a fuss about attendees being "members", compared to "purchasing a ticket" (which is what you do for a commercialized Star Trek con). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From 42flicks at gmail.com Mon Mar 3 03:59:07 2008 From: 42flicks at gmail.com (Mike D) Date: Mon, 3 Mar 2008 21:59:07 +1300 Subject: Trouble using XML Reader Message-ID: <2b54d4370803030059s722ed808j9ddd7512ed50eea4@mail.gmail.com> Hello, I'm using XML Reader (xml.sax.xmlreader.XMLReader) to create an rss reader. I can parse the file but am unsure how to extract the elements I require. For example: For each element I want the title and description. I have some stub code; I want to create a list of objects which include a title and description. I have the following code (a bit hacked up): import sys from xml.sax import make_parser from xml.sax import handler class rssObject(object): objectList=[] def addObject(self,object): rssObject.objectList.append(object) class rssObjectDetail(object): title = "" content = "" class SimpleHandler(handler.ContentHandler): def startElement(self,name,attrs): print name def endElement(self,name): print name def characters(self,data): print data class SimpleDTDHandler(handler.DTDHandler): def notationDecl(self,name,publicid,systemid): print "Notation: " , name, publicid, systemid def unparsedEntityDecl(self,name,publicid,systemid): print "UnparsedEntity: " , name, publicid, systemid, ndata p= make_parser() c = SimpleHandler() p.setContentHandler(c) p.setDTDHandler(SimpleDTDHandler()) p.parse('topstories.xml') And am using this xml file: Stuff.co.nz - Top Stories http://www.stuff.co.nz Top Stories from Stuff.co.nz. New Zealand, world, sport, business & entertainment news on Stuff.co.nz. en-nz Fairfax New Zealand Ltd. 30 /static/images/logo.gif Stuff News http://www.stuff.co.nz Prince Harry 'wants to live in Africa' http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303 For Prince Harry it must be the ultimate dark irony: to be in such a privileged position and have so much opportunity, and yet be unable to fulfil a dream of fighting for the motherland. EDMUND TADROS stuff.co.nz/4423924 Mon, 03 Mar 2008 00:44:00 GMT Is there something I'm missing? I can't figure out how to correctly interpret the document using the SAX parser. I'm sure I;'m missing something obvious :) Any tips or advice would be appreciated! Also advice on correctly implementing what I want to achieve would be appreciated as using objectList=[] in the ContentHandler seems like a hack. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From haraldarminmassa at gmail.com Wed Mar 12 06:14:06 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 12 Mar 2008 03:14:06 -0700 (PDT) Subject: Py2exe and Multi Treading problem. References: Message-ID: Farsheed Ashouri , > Here is my script > #********************************************************************** > #********************************************************************** > import threading > import socket > def openSocket(portNum): > mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) > mySocket.bind ( ( '', portNum ) ) > mySocket.listen ( 1 ) > channel, details = mySocket.accept() > msg = channel.recv(4096) > > class CmdPortThread( threading.Thread ): > def run( self ): > openSocket(6000) > > def fakeCommandPort(): > CmdPortThread().start() > fakeCommandPort() > If works perfect with python 2.5.2. Now I want to convert it to > standalone program. > but the .exe file fails to run without any error. are you sure that it fails to run? I expect it to run, and exit immediately after fakeCommandPort(). That is: there is nothing more to do in the main thread, so the application exits. To learn more, add prints and use the usual if __name__=='__main__' class CmdPortThread( threading.Thread ): def run( self ): print "Thread CmdPortThread running" openSocket(6000) if __name__=='__main__': print "Mese running" fakeCommandPort() print "Mese done starting Thread" Harald From kyosohma at gmail.com Sat Mar 15 18:08:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 15 Mar 2008 15:08:11 -0700 (PDT) Subject: Code to send RSS news by Sendmail References: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> Message-ID: <87941df1-a371-49ca-af6b-9016810035f2@u72g2000hsf.googlegroups.com> On Mar 15, 3:18 pm, Ulysse wrote: > Hello, > > I'm searching a code which allow you to parse each item in the RSS > feed, get the news page of each item, convert it to text and send it > by mail. > > Do you know if it exists ? > > Thanks Try using Google next time. In the meantime, here's the wiki on RSS: http://wiki.python.org/moin/RssLibraries As for emailing it, you should check out the email module: http://docs.python.org/lib/module-email.html Mike From pi.arctan at gmail.com Sat Mar 8 17:27:58 2008 From: pi.arctan at gmail.com (pi.arctan at gmail.com) Date: Sat, 8 Mar 2008 14:27:58 -0800 (PST) Subject: extract multiple ranges from a list References: Message-ID: On 8 Mar, 17:32, Peter Otten <__pete... at web.de> wrote: > pi.arc... at gmail.com wrote: > > One of my many project involves working with YUV-files, where I need > > to reduce > > the vertical resolution with a factor of two, i.e. remove every other > > scan line. > > Today I'm using two for-loops in the fashion shown below > > > y = [] > > for i in range(0, width*height, width*2): > > for j in range(0,width): > > y.append(Y[i+j]) > > > This approach doesn't feel very pythonic but I can't come up with a > > better idea to do it. > > I've tried list comprehension and map together with lambda but I can't > > get a flattened list > > of every other scan-line... > > > CIF = 352x288 items for luminance and the aim is to have the list > > below: > > y = [0:352 704:1056 ... ] > >>> width = 3; height = 5 > >>> Y = range(width*height) > >>> y = [] > >>> for i in range(0, width*height, 2*width): > > ... y.extend(Y[i:i+width]) > ...>>> y > > [0, 1, 2, 6, 7, 8, 12, 13, 14] > > Probably more efficient, but needs numpy: > > >>> import numpy > >>> width = 3 > >>> height = 5 > >>> Y = range(width*height) > >>> a = numpy.array(Y).reshape(height, width) > >>> a > > array([[ 0, 1, 2], > [ 3, 4, 5], > [ 6, 7, 8], > [ 9, 10, 11], > [12, 13, 14]])>>> b = a[::2] > >>> b > > array([[ 0, 1, 2], > [ 6, 7, 8], > [12, 13, 14]])>>> list(b.reshape(len(b)*width)) > > [0, 1, 2, 6, 7, 8, 12, 13, 14] > > Peter Thanx guys! From rokkamraja at gmail.com Fri Mar 7 02:01:10 2008 From: rokkamraja at gmail.com (Raja) Date: Thu, 6 Mar 2008 23:01:10 -0800 (PST) Subject: Python GDB Wrapper Message-ID: Hi, I am trying to develop a a GDB wrapper script in python which is able to extract a stack trace and all relevant data. Has anyone does this before ? Even some basic idea or code as to how to proceed would be great. Thanks, Raja. From deets at nospam.web.de Thu Mar 20 13:42:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Mar 2008 18:42:15 +0100 Subject: zope and python 2.5.1 References: Message-ID: <64fm02F2ba5puU1@mid.uni-berlin.de> hberig wrote: > Hi, > I'm sorry if this is an off-topic message, but I didn't found other > group. > I've read some articles about Zope, and since I like very much python, > I would like to run a webserver application using Zope instead other > web application server. I've difficulties to install zope 3 and zope 2 > on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is > there a simple way to fix it? apt-get install python2.4 Diez From falk at green.rahul.net Tue Mar 4 02:06:45 2008 From: falk at green.rahul.net (Edward A. Falk) Date: Tue, 4 Mar 2008 07:06:45 +0000 (UTC) Subject: Answer: Is there a way to "link" a python program from several files? References: <0f3e4884-59f8-4db8-a2a3-6f6d4fc14275@u72g2000hsf.googlegroups.com> <92dc6954-6f9a-40b2-9cee-4bd46b9a2826@f47g2000hsd.googlegroups.com> Message-ID: In article <92dc6954-6f9a-40b2-9cee-4bd46b9a2826 at f47g2000hsd.googlegroups.com>, George Sakkis wrote: > >What's so complicated about "python setup.py install" ? Even that is >not strictly necessary for pure python packages; a user may just >unpack the archive, cd to the extracted directory and execute the >appropriate .py file(s). Aha. Completely forgot about setup.py. Unfortunately, under Linux, all it seems to do is build a tarball for me, which when unpacked produces several discrete .py files, leaving me back where I started. Anyway, I did what I should have done in the first place and trolled /usr/bin to see how other people had done it. It turns out there are a few answers: First, you can simply just produce the program as a single .py file (which is what I wound up doing). Second, you can put all the .py files other than the "main" one into /usr/share/ and then append that directory to your path before importing anything. Third, you can put all the .py files other than the "main" one into /usr/lib/python2.2/site-packages/ and then you don't have to modify your path. The second and third methods have the advantage that you can have .pyc files hanging around. Anyway, thanks for all your input. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From arnodel at googlemail.com Fri Mar 21 16:12:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 21 Mar 2008 13:12:56 -0700 (PDT) Subject: How can I make a function equal to 0? References: Message-ID: On Mar 21, 7:48?pm, Martin Manns wrote: > Hi, > > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > > >>> def f(): return "" > ... > >>> # Some magic > >>> f == 0 > > True Why do you want to do that? >>> class WhyOhWhy(object): ... def __init__(self, f): self.f = f ... def __call__(self, *args, **kwargs): return self.f(*args, **kwargs) ... def __eq__(self, other): return other == 0 ... >>> @WhyOhWhy ... def f(x): print "Why oh why,", x ... >>> f("do this?") Why oh why, do this? >>> f == 0 True >>> -- Arnaud From mail at timgolden.me.uk Sun Mar 16 10:51:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:51:03 +0000 Subject: Types, Cython, program readability In-Reply-To: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <47DD33D7.2020300@timgolden.me.uk> bearophileHUGS at lycos.com wrote: > It seems the development of Cython is going very well, quite > differently from the dead-looking Pyrex. I'll leave others to comment on how dead Pyrex is or isn't ... > Hopefully Cython will become > more user-friendly too (Pyrex is far from being user-friendly for > Windows users, it doesn't even contain a compiler, I think. The > ShedSkin Windows installer contains an old but working MinGW, and this > is positive). I'm not entirely sure why you think Pyrex should "contain a compiler". It certainly works well enough with the free [beer] MS VS 2008 Express and I'm fairly sure it's fine with MingW. Both of those are readily available and I don't imagine anyone who's going to use Pyrex / Cython / ShedSkin is going to baulk at downloading a compiler set :) TJG From aboudouvas at panafonet.gr Thu Mar 27 10:37:40 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 07:37:40 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: > > > As for psyco, are there any alternatives to use now ? > > Nope, but I heard through the grapevine that while it won't be supported for > all times to come, a new version is in the making. Aha!! It seems you have better "sources" than me! :) > But ultimately, the author says that the approach is flawed, so at *some* > point it will be discontinued. But that could be said about nearly > everything, couldn't it? > > Diez It is a pity because this module *does* really solve some problems... From craigm3604 at gmail.com Mon Mar 24 15:45:25 2008 From: craigm3604 at gmail.com (Craig) Date: Mon, 24 Mar 2008 12:45:25 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> Message-ID: On Mar 24, 12:27 pm, Craig wrote: > On Mar 23, 7:59 pm, Dennis Lee Bieber wrote: > > > > > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig > > declaimed the following in comp.lang.python: > > > > This dll was designed to be used from either C or Visual Basic 6. > > > > I have the declare statements for VB6, if that helps. > > > Probably not that much -- I'd bet it's full of variant records > > > > Based on the results I have so far (and I have tried MANY permutations > > > like trying to use the LPSTR for SecKey and PriKey which are returned > > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > > instead of pointers. > > > > For this, I try: > > > LPSTR = c_char_p > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > > LPSTR] > > > SrchKey = > > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > > \x00", 41) > > > SecKey = create_string_buffer(41) > > > SecKey.raw = "1234567890123456789012345678901234567890" > > > PriKey = > > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > > 41) > > > TypeDef = create_string_buffer(128) > > > TypeDef.raw = "X".center(128, "X") > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > and I get: > > > Traceback (most recent call last): > > > File "C:\temp\vbisam_test_2.py", line 158, in > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(S > > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > WindowsError: exception: access violation reading 0x3433322D > > > > I notice that SecKey.raw starts with "1234" and the exception address > > > is 0x3433322D, which is "432-". > > > 0x2D is 4 less than the expected 0x31... > > > > And, changing to: > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > > LPSTR] > > > PriKey = create_string_buffer(41) > > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > I then get: > > > Traceback (most recent call last): > > > File "C:\temp\vbisam_test_2.py", line 159, in > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(S > > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > WindowsError: exception: access violation reading 0x4443423D > > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > > is 0x4443423D, which is "DBC=". > > > ... and 0x3D is 4 less than the expected 0x41 > > > Which leads me to suspect that BSTR are a structure, not a plain > > string, in which the address given is supposed to be prefaced with a > > length value. IOWs, something like: > > > |----|--------------------------------------| > > ^ ^ C-string data > > | |Address to be passed > > |(address - 4) to get to a length count field > > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > > (the URL is from HTTP through to the end, including .aspx) > > > Creating such may not be difficult -- but passing it to the DLL > > could be. I don't know if ctypes allows pointer arithmetic. > > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > > length prefix. > > > The only mention of BSTR in the win32 extensions is in text that > > implies that the win32 extension library takes care of converting > > from/to BSTR and Python strings transparently -- but that won't work for > > your third-party library I suspect. > > > Might have to beg the author(s) of ctypes to add a BSTR type to the > > list of those supported... as I can find no means of tweaking the > > address computed by byref() to point somewhere into a structure rather > > than the beginning of the structure. > > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > > >>> pk > > 1373844 > > >>> id(pk) > > 18941724 > > >>> ctypes.string_at(pk) > > '1234567890' > > >>> ctypes.string_at(pk-4, 20) > > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > Okay, the return value from SysAlloc... IS the integer representing > > the address of a BSTR structure (IE, the address four bytes in from the > > real memory start)... Note how backing up 4 bytes reveals the BSTR > > length field > > > What happens if you just pass that item as-is, no byref(), no > > conversion to ctypes pointer types... > > > PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > SecKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > res = VmxGet( byref(hwmcb), > > byref(SecIndex), > > byref(Option), > > byref(c_void_p(SrchKey)), > > SecKey, > > PriKey, > > TypeDef ) > > > >>> PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > >>> ctypes.string_at(PriKey, 41) > > > "1234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'">>> ctypes.string_at(PriKey-4, 41+4) > > > ")\x00\x00\x001234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'" > > > >>> ord(")") > > 41 > > > You'll need to use the .string_at() or .wstring_at() functions to > > extract any data changed by the call. Should not be a Python > > immutability problem as all "you" allocated in Python is the integer > > holding the address. You may need to call a Sys... function to free the > > memory that had been allocated -- Python doesn't know about it. > > -- > > Wulfraed Dennis Lee Bieber KD6MOG > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > HTTP://www.bestiaria.com/ > > The VB6 Declare is: > Declare Function VmxGet Lib "vbis5032.DLL" (DatasetHandle&, > SecIndexField%, Options%, SelectorKey$, RSecondaryKey$, RPrimaryKey$, > RRecordVariable As Any) As Integer > > The only variant is the RRecordVariable, which is actually meant to be > a Type structure. > > Anyway, I thought maybe there was a clue in here that I am missing. > > Back to Python. I ran with the following: > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > LPSTR] > SrchKey = > windll.oleaut32.SysAllocStringByteLen("MSD19DN > \x00", 41) > SecKey = > windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", > 41) > PriKey = > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > 41) > TypeDef = create_string_buffer(128) > TypeDef.raw = "X".center(128, "X") > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) > And, now I get: > Traceback (most recent call last): > File "C:\temp\vbisam_test_2.py", line 156, in > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > byref(c_void_p(S > rchKey)), SecKey, PriKey, TypeDef ) > ctypes.ArgumentError: argument 5: : wrong > type > > So, now the problem is with: > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > LPSTR] > I am not sure what to put for arguments 5 and 6 now. > > I realized the need to release the BSTRs myself, and already included: > windll.oleaut32.SysFreeString(SrchKey) > windll.oleaut32.SysFreeString(SecKey) > windll.oleaut32.SysFreeString(PriKey) > at the end of the program. > > I have no problem using .string_at() to extract the returned values - > once the .argtypes let the call execute. > > In case this helps, here is an excerpt from a C program that was > provided with the dll: > typedef struct tagMYREC > { > char name[51]; // 1 xref generated name key > > char lastname[31]; // 2 last name > char firstname[21]; // 3 first name > char address[41]; // 4 address > char city[31]; // 5 xref city key > char state[3]; // 6 xref state > char zip[11]; // 7 xref zip code > char phone[21]; // 8 xref phone number > BSTR notes; // 9 notes > > } MYREC; > typedef MYREC FAR * LPMYREC; > > short rc; // return code (from VB/ISAM function calls) > static HANDLE nDatasetNumber; > static short cur_index; > static short GetOpt; > static BSTR Dummy; > static BSTR Throwaway; > static BSTR PrimaryKey; > static MYREC myrec; > > rc = VmxGet(&nDatasetNumber, // int DatasetNumber // VIS_BUSY ? > &cur_index, // int SelectedIndex > &GetOpt, // int OptionParameter > &Dummy, // Don't need a Selector param with > these options > &Throwaway, // Don't need returned index entry in > this case > &PrimaryKey, // LPBSTR lpPriKey > (void *) &myrec); // LPVOID lpRecordStructure > > For someone who knows C and Python, this may provide a clue to the > BSTR passing/return problem. I received two emails from Dennis, included below (for completeness): ++++++++++++++++++++++++ Start of email #1 ++++++++++++++++++++++++ I'm back at work, hence the email. -=-=-=-=-=-=- So, now the problem is with: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, LPSTR] I am not sure what to put for arguments 5 and 6 now. I realized the need to release the BSTRs myself, and already included: windll.oleaut32.SysFreeString(SrchKey) windll.oleaut32.SysFreeString(SecKey) windll.oleaut32.SysFreeString(PriKey) at the end of the program. I have no problem using .string_at() to extract the returned values - once the .argtypes let the call execute. -=-=-=-=-=-=-=- Might I suggest plain old c_int (or c_int32) After all, you don't want a pointer /to/ the integer value that was returned by the SysAlloc...; the integer value itself /is/ the pointer (to the BSTR memory) that needs to be passed, as is, to the DLL function. c_int should do just that -- take the integer value "out" of the Python integer object, and put it on the stack for the DLL function. I must state that I'm surprised some parts of Windows is using a hybridized BCPL string. Last place I saw using those was on the Amiga -- in which, while the Exec, Intuition, Graphics, and other low- level libraries were in C, the command line user interface (utility commands, environment, etc.) were ported from Tripos -- and Tripos had been written in BCPL. The hybrid comment is that Windows is combining the BCPL length value with C null terminations, so the string can be used in both ways. +++++++++++++++++++++++++ End of email #1 +++++++++++++++++++++++++ ++++++++++++++++++++++++ Start of email #2 ++++++++++++++++++++++++ -=-=-=-=-=-=- TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") -=-=-=-=-=-=- typedef struct tagMYREC { char name[51]; // 1 xref generated name key char lastname[31]; // 2 last name char firstname[21]; // 3 first name char address[41]; // 4 address char city[31]; // 5 xref city key char state[3]; // 6 xref state char zip[11]; // 7 xref zip code char phone[21]; // 8 xref phone number BSTR notes; // 9 notes } MYREC; -=-=-=-=-=-=- Might I suggest increasing the length of your string buffer. Adding up the allocation in MYREC comes to: 179 bytes BEFORE including "notes" -- and as a BSTR declaration, notes is going to be a 4-byte length, 1 or 2 nulls (the spec for a unicode result implied a 2-byte null) PLUS whatever value length is itself. You may need to find out what the maximum length allowed for the notes field is in advance and add that to the buffer size. Pity its not a BSTR *notes -- that would imply memory allocated elsewhere and an address -- the .string_at() could use the pointer to retrieve the real notes. +++++++++++++++++++++++++ End of email #2 +++++++++++++++++++++++++ Sorry for the confusion on "MYREC" - this was just used in the sample C program provided with the dll. It is not applicable to the files I am using. For my file, the 128 is correct. I tried: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, c_int32, c_int32, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) And got: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 156, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) WindowsError: exception: access violation reading 0x3433322D That was what I was getting at earlier. We know that it is a c_int32 type, but the .argtypes is not doing something right (or I am not specifying it correctly). How do I correctly pass what needs to be passed? From gagsl-py2 at yahoo.com.ar Sun Mar 30 00:58:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 01:58:53 -0300 Subject: html DOM References: Message-ID: En Sun, 30 Mar 2008 00:19:08 -0300, Michael Wieher escribi?: > Was this not of any use? > > http://www.boddie.org.uk/python/HTML.html > > I think, since HTML is a sub-set of XML, any XML parser could be adapted > to > do this... That's not true. A perfectly valid HTML document might even not be well formed XML; some closing tags are not mandatory, attributes may not be quoted, tags may be written in uppercase, etc. Example: Invalid xml

a The above document validates with no errors on http://validator.w3.org If you are talking about XHTML documents, yes, they *should* be valid XML documents. > I doubt there's an HTML-specific version, but I would imagine you > could wrap any XML parser, or really, create your own that derives from > the > XML-parser-class... The problem is that many HTML and XHTML pages that you find on the web aren't valid, some are ridiculously invalid. Browsers have a "quirks" mode, and can imagine/guess more or less the writer's intent only because HTML tags have some meaning. A generic XML parser, on the other hand, usually just refuses to continue parsing an ill-formed document. You can't simply "adapt any XML parser to to that". BeautifulSoup, by example, does a very good job trying to interpret and extract some data from the "tag soup", and may be useful to the OP. http://www.crummy.com/software/BeautifulSoup/ -- Gabriel Genellina From edreamleo at charter.net Fri Mar 14 12:03:50 2008 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 14 Mar 2008 11:03:50 -0500 Subject: ANN: Leo 4.4.8 beta 2 released Message-ID: <5nxCj.8$ET1.2@newsfe06.lga> Leo 4.4.8 beta 2 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This version features a new ipython plugin that provides a two-way bridge between Leo and IPython. See http://webpages.charter.net/edreamleo/IPythonBridge.html Leo is a text editor, data organizer, project manager and more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.8: ---------------------------- - Leo's source code is now managed by bzr. See the Bzr link below. - Leo's discussion is now hosted by Google Groups: See the Forum link below. - The first, third, fifth etc. arguments to g.es and g.es_print can now be translated using Python's gettext.gettext function. - Completed ILeo: a bridge between IPython and Leo. See http://webpages.charter.net/edreamleo/IPythonBridge.html - Added support for arguments to minibuffer commands. - @menu trees can now refer to commands created by @command and @button nodes - Added support for common @commands nodes in settings files. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From nkanthikiran at gmail.com Wed Mar 12 06:32:22 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Wed, 12 Mar 2008 03:32:22 -0700 (PDT) Subject: Creating a file with $SIZE Message-ID: Hi All, I would like create files of different size, taking size as user input. I need to check the data transfer rates from one network to another . In order to do this I will have to create files of diff size and work out. I am new to Python Thanks in advance. KK From http Wed Mar 26 22:16:38 2008 From: http (Paul Rubin) Date: 26 Mar 2008 19:16:38 -0700 Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: <7xej9woqrd.fsf@ruckus.brouhaha.com> Sean Davis writes: > OR, NOT, etc.). Any suggestions on how to (1) set up the bit string > and (2) operate on 1 or more of them? Java has a BitSet class that > keeps this kind of thing pretty clean and high-level, but I haven't > seen anything like it for python. You could wrap something around the array module, or the bit vector objects from numarray, or use something like PyJudy (google for it). Or consider using something like a tree data structure that supports set operations, rather than a bitmap, if that's closer to what you're really trying to do. From Gerald.Klix at klix.ch Tue Mar 18 06:46:13 2008 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Tue, 18 Mar 2008 11:46:13 +0100 Subject: detect current timezone set by kde In-Reply-To: <20080318102726.GB3880@debian> References: <20080318102726.GB3880@debian> Message-ID: <47DF9D75.2050501@klix.ch> I suggest to change /etc/timezone by invoking sudo tzselect. HTH, Gerald Pradnyesh Sawant schrieb: > Hello, > can someone please tell me how can I programatically detect the timezone > information that has been set through kde? > > basically, I have a small pyqt4 app which shows the current time. however > it shows me my system time (dunno where that is stored; basically it shows > me time in IST). however, I'm right now in hk and would like the app to > show me time in my current timezone (hong kong). Any guidelines how may I > go about doing this? > > thanks a lot in advance :-) > From watine at cines.fr Tue Mar 25 09:50:51 2008 From: watine at cines.fr (Benjamin Watine) Date: Tue, 25 Mar 2008 14:50:51 +0100 Subject: My python interpreter became mad ! In-Reply-To: References: Message-ID: <47E9033B.3070108@cines.fr> John Machin a ?crit : > On Mar 25, 10:05 pm, Benjamin Watine wrote: >> Yes, my python interpreter seems to became mad ; or may be it's me ! :) >> >> I'm trying to use re module to match text with regular expression. In a >> first time, all works right. But since yesterday, I have a very strange >> behaviour : >> >> $ python2.4 >> Python 2.4.4 (#2, Apr 5 2007, 20:11:18) >> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import re >> X-Spam-Flag: YES >> X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org >> X-Spam-Level: ********************** >> X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, >> MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, >> >> RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, >> >> URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, >> URIBL_WS_SURBL autolearn=failed version=3.1.7-deb >> >> Traceback (most recent call last): >> File "", line 1, in ? >> File "/etc/postfix/re.py", line 19, in ? >> m = re.match('(Spam)', mail) >> AttributeError: 'module' object has no attribute 'match' >> >>> >> >> What's the hell ?? I'm just importing the re module. > > No you're not importing *the* re module. You're importing *an* re > module, the first one that is found. In this case: your own re.py. > Rename it. > Oh... yes, that's it ; I have a file named re.py ! Ouch, sorry for this stupid question, and thank you for this evident answer. I didn't knew that it was possible to import a module this way... Thank you for the fast answer ! Ben From nagle at animats.com Mon Mar 31 00:34:00 2008 From: nagle at animats.com (John Nagle) Date: Sun, 30 Mar 2008 21:34:00 -0700 Subject: Creating Class Objects in Loop In-Reply-To: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> References: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> Message-ID: <47f0673e$0$36321$742ec2ed@news.sonic.net> Fish wrote: > Hello Folks, > I am reading a CSV file and based on that I am creating TestCase(my > own defined class) objects in a for loop. The problem is each time I > create a new TestCase object in loop, previous objects data is already > copied in that object. What's actually happening to you is that you've run into one of the dumber features of Python - default values for parameters which are mutable, like lists, result in rather unexpected behavior. The problem is that def __init__(self, pcap = None, sids = []): creates the empty list "[]" once at startup, and that list is persistent across calls to __init__. Yes, that's wierd, but Python does that for historical reasons. Actually, you can write your main loop much more simply: def returnTcLst(path): fp = open(path) for line in fp: fields = line.split(",") # split into list at commas fields = map(lambda(s) : s.strip(), fields) # strip whitespace tcLst.append(TestCase(fields[0], fields[1:])) # pcap, then sids John Nagle From igorr at ifi.uio.no Tue Mar 11 20:05:06 2008 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 12 Mar 2008 01:05:06 +0100 Subject: catching object Message-ID: Hi, I was wondering if someone could help me explain this situation: h[1] >>> import inspect h[1] >>> inspect.getmro(ValueError) (, , , , ) h[2] >>> try: raise ValueError("argh") except object: print "why not?" Traceback (most recent call last): File "", line 2, in ValueError: argh The question is, why isn't ValueError caught? It *does* inherit from object (albeit indirectly), and my understanding of the wording of CPython docs is that this guarantees "compatibility" (between what is being raised and what is being caught). So, why doesn't object match ValueError (or any other exception for that matter). I am aware of "except:", but in my particular situation it is eh... unsuitable. Any hints/pointers are appreciated. ivr -- <+Kaptein-Dah> igorr: for f? parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent From martin at v.loewis.de Sat Mar 1 18:39:41 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Mar 2008 00:39:41 +0100 Subject: Problems building 2.5.1 on AIX In-Reply-To: References: Message-ID: <47C9E93D.3020208@v.loewis.de> > hasty:Python-2.5.1$ CC=/usr/vacpp/bin/cc_r ./configure --without-gcc > checking MACHDEP... aix5 > checking EXTRAPLATDIR... > checking for --without-gcc... yes > checking for gcc... cc > checking for C compiler default output file name... configure: error: C > compiler cannot create executables > See `config.log' for more details. > > I get the same result with or without the --without-cgg. There's nothing > obvious in config.log (not that I can ever make much sense out of the > gibberish configure generates). > > Any ideas? You really do have to check config.log. Check for any lines where it tries to invoke the compiler, and check whether it does so in the way you expect it to. From the output you provide, it seems to use "cc" as the compiler, not /usr/vacpp/bin/cc_r. Looking at the comfigure code, this is not surprising: --without-gcc resets CC to cc. Regards, Martin From deets at nospam.web.de Fri Mar 21 11:30:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Mar 2008 16:30:55 +0100 Subject: beginners question about return value of re.split In-Reply-To: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <64i2lmF2c6dvgU1@mid.uni-berlin.de> klaus schrieb: > Hello, > > I have a question regarding the return value of re.split() since I have > been unable to find any answers in the regular sources of documentation. > > Please consider the following: > > #!/usr/bin/env python > > import re > > if __name__ == "__main__": > datum = "2008-03-14" > the_date = re.split('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', datum, 3) > print the_date > > Now the result that is printed is: > ['', '2008', '03', '14', ''] > > My question: what are the empty strings doing there in the beginning and > in the end ? Is this due to a faulty regular expression ? Read the manual: """ split( pattern, string[, maxsplit = 0]) Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.) """ The Key issue here being "If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list." Consider this: >>> re.compile("a").split("bab") ['b', 'b'] >>> re.compile("(a)").split("bab") ['b', 'a', 'b'] >>> Consider using match or search if split isn't what you actually want. Diez From Lie.1296 at gmail.com Thu Mar 13 14:46:16 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 13 Mar 2008 11:46:16 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: On Mar 13, 2:36?pm, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) ?[1,2,3,4] > 2) ?[1,2,3,4,5] > 3) ?That famous picture of Albert Einstein sticking out his tongue > 4) ?Nothing - no output > 5) ?None of the above > > I undertake to summarise answers posted to complete this "survey". > > - Hendrik I think I'll choose 3. Well, no, I suppose the correct behavior _should_ be undefined (i.e. what it returns is an implementation details that should not be relied on). The fact that it returns None is just a "coincidence" that happens to happen every time you tested it (you can't prove by ignorance) From istvan.albert at gmail.com Thu Mar 27 14:45:15 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 27 Mar 2008 11:45:15 -0700 (PDT) Subject: Is subprocess.Popen completely broken? References: Message-ID: <16300891-8fbf-489a-9011-e38180310618@s8g2000prg.googlegroups.com> On Mar 27, 10:53 am, Skip Montanaro wrote: > Is subprocess.Popen completely broken? Your lack of faith in Python is somewhat disturbing ... From jzgoda at o2.usun.pl Tue Mar 18 16:18:33 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 18 Mar 2008 21:18:33 +0100 Subject: Get actual call signature? In-Reply-To: References: Message-ID: castironpi at gmail.com pisze: > On Mar 18, 5:40 am, Jarek Zgoda wrote: >> Say, I have a function defined as: >> >> def fun(arg_one, arg_two='x', arg_three=None): >> pass >> >> Is there any way to get actual arguments that will be effectively used >> when I call this function in various ways, like: >> >> fun(5) => [5, 'x', None] >> fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] >> fun(5, 'something') => [5, 'something', None] >> >> (et caetera, using all possible mixes of positional, keyword and default >> arguments) >> >> I'd like to wrap function definition with a decorator that intercepts >> not only passed arguments, but also defaults that will be actually used >> in execution. >> >> If this sounds not feasible (or is simply impossible), I'll happily >> throw this idea and look for another one. ;) > > It evaluates to a substantial problem. The combinations include > things that Python disallows, such as double-spec. of keywords and > spec'n of keys w/out a dictionary arg; as well as double-spec'ing of > inspection. How do you want to access the parameters? What is the > least redundant way? P.S. Does there exist a possible authority who > doesn't want me to post this? Well, after some thinking and research I found this much more complicated than my first thoughts. However, I found that somebody already wrote some code to solve similar problem and even described what has to be done: http://wordaligned.org/articles/echo. Too bad for me, the most interesting part relies on features introduced with Python 2.5, while I am still on 2.4. Anyway, basics still works and fortunately I am in control in both function definitions and calls. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From kaushikbarat at gmail.com Sun Mar 2 01:47:02 2008 From: kaushikbarat at gmail.com (kaush) Date: Sat, 1 Mar 2008 22:47:02 -0800 (PST) Subject: mod_python Unable to create file Message-ID: Hi, I am using Apache and mod_python to service POST/GET requests on MAC OS. My script tries to create a file file = open(file_path, 'w') This fails with the following error EACCES Permission denied What is missing? Thanks, Kaushik From roman.dodin at softjoys.com Fri Mar 14 10:02:48 2008 From: roman.dodin at softjoys.com (Roman Dodin) Date: Fri, 14 Mar 2008 17:02:48 +0300 Subject: find string in file In-Reply-To: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> References: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> Message-ID: <47DA8588.6030800@softjoys.com> On 14 mar, 14:25, fminerv... at gmail.com wrote: >> Hi friends !! >> >> I'm neophite about python, my target is to create a programa that >> find a specific string in text file. >> How can do it? >> >> Thanks >> fel >> > > > One more way to do this f = codecs.open("log.txt", 'r', "utf_16_le") lines = f.readlines() for line in lines: if(line.find("my string to find")!=-1): print line From castironpi at gmail.com Sun Mar 9 17:40:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:40:28 -0700 (PDT) Subject: 1.5.2 and functools or similar References: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Message-ID: On Mar 9, 4:26?pm, "Troels Thomsen" wrote: > Hello, > > I am writing a simple delayed-call mechanism , that is causing a bit of > headache. Works like this: > > myPrint(s) > ? print "..." + s > > myTimer.add(myPrint , "hello" , 15) > > This means that the myprint function is called in 15 seconds with the > parameter "hello". > The housekeeping of these timers is called by the main loop of the "os" > > This works well but i would like to be able to use it with any number of > parameters > > Functools is not a part of the 1.5.2+ python that I am running on (embedded > device), > so i tried to pass the parameters as a tuple like this > > myTimer.add(myAdder , (3,6) , 15) > > and the housekeeping function would then call the function like this > > def updateTimers() > ? for timerItm in timerTable: > ? ... > ? ? .... > ? ? ? .... > ? ? ? ? timerItm.func(*timerItm.parameters) > > Works well on python 2.5 but not on 1.5.2 (?) > > Current solution is to have default parameters None for the add function > > def add( func , timeout , param1 = None , param2 = None) > > And the update function then checks if parameters is specified > > def updateTimers() > ? for timerItm in timerTable: > ? ... > ? ? .... > ? ? ? .... > ? ? ? # ugly part : > ? ? ? if timerItm.param1 is not None and timerItm.param2 is not None: > ? ? ? ? timerItm.func(timerItm.param1, timerItm.param2) # two parameters > ? ? ? elif ...... > ? ? ? ? timerItm.func(timerItm.param1) # one parameter > ? ? ? else > ? ? ? ? timerItm.func() # no parameters > > This has the implication that I can not call a function with the parameter > None if I wanted to. > (not a huge problem) > > Right now it works quite well with up to two parameters, it covers 99% of > usage. If I need to call a function with more parameters, i can always write > a wrapper function for it. Wondering if anyone had some sugestions ? > > By the way, is it bad style to check for object identity instead of value > "None". > What aboutt integers ? if value is 0: .. > I guess it is implementation specific / could change in future versions ? > > Thx, > Troels def g( arg1, arg2 ): print( arg1, arg2 ) return arg1 def h( arg1 ): print( arg1 ) return arg1 def caller( fun, *args, **kwargs ): return fun( *args, **kwargs ) print( caller( g, 'abc', 'def' ) ) print( caller( h, 'abc' ) ) ''' abc def abc abc abc ''' From musiccomposition at gmail.com Sun Mar 9 23:05:36 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 9 Mar 2008 20:05:36 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: <7ef97850-6244-43c4-9ff8-f0955c61c348@u69g2000hse.googlegroups.com> On Mar 9, 4:22 pm, Gif wrote: > i'm trying to execute a file without replacing the current process, > but after searching the help file, documentations and the web, i can't > a way of doing that. > > os.exec*() will close the current program. Have a look at the subprocess module. > > ps: by executing i mean like typing "mspaint" in run dialog.. it's not > a python file From deevine-removethis-spam at gmail.com Fri Mar 28 10:01:55 2008 From: deevine-removethis-spam at gmail.com (Jason Kristoff) Date: Fri, 28 Mar 2008 10:01:55 -0400 Subject: How do I reconnect a disconnected socket? Message-ID: I'm trying to make something that once it is disconnected will automatically try to reconnect. I'll add some more features in later so it doesn't hammer the server but right now I just want to keep it simple and get that part working. The problem is that when I use sock.close I get an error message of Bad File Descriptor and if I either use shutdown or just go straight to reconnecting I get: Transport endpoint is already connected This is what I've got right now: #! /usr/bin/env python import socket, string sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def doconn(): sock.connect(("localhost", 1234)) def dodiscon(): sock.close() doconn() doconn() while (1): buffer = sock.recv(1024) if not buffer: dodiscon() From mgedmin at gmail.com Tue Mar 18 14:05:29 2008 From: mgedmin at gmail.com (Marius Gedminas) Date: Tue, 18 Mar 2008 11:05:29 -0700 (PDT) Subject: Python Generators References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: <57b42684-2e4d-4e57-83f6-6d2ed011e485@i29g2000prf.googlegroups.com> On Mar 16, 9:24?am, Matt Nordhoff wrote: > mpc wrote: > > def concatenate(sequences): > > ? ? for seq in sequences: > > ? ? ? ? for item in seq: > > ? ? ? ? ? ? yield item > > You should check out itertools.chain(). It does this. You call it like > "chain(seq1, seq2, ...)" instead of "chain(sequences)" though, which may > be a problem for you. Solved rather easily by chain(*sequences): >>> from itertools import chain >>> def concat(sequences): ... return chain(*sequences) ... >>> concat([[1,2], [3, 4], [5], [6, 7, 8]]) >>> list(concat([[1,2], [3, 4], [5], [6, 7, 8]])) [1, 2, 3, 4, 5, 6, 7, 8] wondering if google groups will add a .sig or not-ly, Marius Gedminas From http Sun Mar 2 10:02:29 2008 From: http (Paul Rubin) Date: 02 Mar 2008 07:02:29 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> Message-ID: <7xprud88ze.fsf@ruckus.brouhaha.com> Lie writes: > That's quite complex and restrictive, but probably it's because my > mind is not tuned to Haskell yet. That aspect is pretty straightforward, other parts like only being able to do i/o in functions having a special type are much more confusing. > Anyway, I don't think Python should > work that way, because Python have a plan for numerical integration > which would unify all numerical types into an apparent single type, > which requires removal of operator's limitations. Well I think the idea is to have a hierarchy of nested numeric types, not a single type. > from __future import division > a = 10 > b = 5 > c = a / b > if c * b == a: print 'multiplication is inverse of division' Try with a=7, b=25 From ebgssth at gmail.com Mon Mar 10 19:31:07 2008 From: ebgssth at gmail.com (js) Date: Tue, 11 Mar 2008 08:31:07 +0900 Subject: TextWrapper keepking line breaks? Message-ID: Hi list, Can I make TextWrapper keep line breaks in the text? For example, >>> s = "spam\nham" >>> print wrap(s) spam ham As far as I can tell, there seems no way to do this, but before writing my own solution, I want to know whether the solution already exists or not. Thanks. From kay.schluehr at gmx.net Mon Mar 17 02:36:35 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 16 Mar 2008 23:36:35 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <3a2e4490-f4e9-4edf-ae35-0aa3c90103f7@i7g2000prf.googlegroups.com> Message-ID: On 16 Mrz., 21:52, Bruce Eckel wrote: > On Mar 16, 2:48 pm, Pete Forde wrote: > > > My friends and I decided to stage a grassroots Ruby conference this > > summer; it will have no paid sponsors for exactly this reason. We're > > trying to change up the typical format as well: it's a single-track > > event, no "keynotes", no schills for well-heeled interests. We're even > > organizing activities for significant others traveling with conference > > attendees so that everyone has a good time. > > > The response we've gotten to this approach has been curious; many > > people totally get why these things are important, and the speaker > > list reflects this. However, we've also had a lot of complaints that > > our event is too expensive. In fact, they say that it should be free, > > like a BarCamp. Just get a bunch of sponsors, and that will be the > > ticket. We say bollocks to that. > > >http://rubyfringe.com/ > > I've been running open spaces conferences for the past few years and I > would suggest you do that instead of an "eyes-forward" conference. > It's not only a lot easier, but it's also a lot more fun. For example, > last week we did the Java Posse Roundup, which is all open-spaces. Since the rubyfringe seems to make also a commitment against the Ruby mainstream I'm not sure how Open Spaces can help? Self organization is always an aid for those who are already strong, maintain popular projects ( Rails, Django... anyone? ) and keep lots of attention. I certainly wouldn't attend to an Open Space conference if I intended to make my development and findings public. From rune.strand at gmail.com Fri Mar 14 17:21:37 2008 From: rune.strand at gmail.com (Rune Strand) Date: Fri, 14 Mar 2008 14:21:37 -0700 (PDT) Subject: Ping and ARP on both Win and Linux in Python References: Message-ID: <70f1300f-cdd3-4c92-ad8d-ffdda7aaa139@e25g2000prg.googlegroups.com> On Mar 13, 9:14 pm, "Mauro \"Baba\" Mascia" wrote: > Hi, this is my question: > > I want to know if several switch (about 50) in a big lan are up and then > know their MAC addresses to do a list that contains host name, ip and mac. > I know only the range of their IP addresses (the host name it's simply > to know using socket.gethostn. > > The first idea it's to ping all ip, parse the response and then execute > the command "arp -a" and parse the response. > However this way depends on the operating system and the ping response > depends too from the language. > > Another way it's to open the main page of the switch and parse the HTML > code where i can find the MAC address. > However this way depends on the particular brand's switch. > > I know (or better i think) that there is a third way: make ping and arp > building the packets with socket and so on (but i dont have understand > in what way do this). > > Any suggestion? > > (i've already search in google, found many sources but a lot of them > don't works or don't do what im trying to do...) > > Regards, > Mauretto. There are several Ping /ICMP implentations in Python. I did something similar using a python ping module and parsing the arp cache. A different approach may be to use SNMP. I believe there are Python tools around. From arkanes at gmail.com Tue Mar 18 13:47:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 18 Mar 2008 12:47:26 -0500 Subject: Fast 2D Raster Rendering with GUI In-Reply-To: References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: <4866bea60803181047m7649d357nfaf91f5146bcbc52@mail.gmail.com> On Tue, Mar 18, 2008 at 12:30 PM, sturlamolden wrote: > On 18 Mar, 17:48, Miki wrote: > > > Apart from PIL, some other options are: > > 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object > > you can draw on > > Yes, but at least on Windows you will get a GDI canvas. GDI is slow. Of all the major platforms, GDI is probably the fastest for basic pixel-level interaction with the screen. I have no idea why you think it's slow. > > > > > 2. A bit of an overkill, but you can use PyOpenGL > > OpenGL gives you a fast 'bitblit' for drawing bitmaps to the fram > buffer (much faster than GDI). Here is some C code that does that (8- > bit color depth). Translating to Python is trivial. I prefer not to > use PyOpenGL as it has some unwanted overhead. It is better to use > ctypes. > > > void bitblt(void *frame, int w, int h) > { > glViewport(0,0,w,h); > glClearColor(0.0, 0.0, 0.0, 0.0); > glClear(GL_COLOR_BUFFER_BIT); > glMatrixMode(GL_PROJECTION); > glLoadIdentity(); > gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h); > glMatrixMode(GL_MODELVIEW); > glLoadIdentity(); > glRasterPos2i(0,0); > glPixelStorei(GL_UNPACK_ALIGNMENT, 1); > glDrawPixels(w, h, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, (GLvoid *)frame); > glFlush(); > > > } > OpenGL is totally unsuitable if the goal is to implement your own pixel-level raster drawing. From gagsl-py2 at yahoo.com.ar Wed Mar 26 19:07:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 20:07:33 -0300 Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> <47EA99EE.5030304@tim.thechases.com> <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> Message-ID: En Wed, 26 Mar 2008 16:14:07 -0300, David Anderson escribi?: > The right question was:HOw can we use/express pointers python as in C or > Pascal? I think you should read this article: http://effbot.org/zone/python-objects.htm and then: http://effbot.org/zone/call-by-object.htm -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Mar 26 09:32:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 06:32:03 -0700 (PDT) Subject: memory allocation for Python list References: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> Message-ID: <96e81eb0-9d27-4cfd-82da-7fcc9b3dae25@m3g2000hsc.googlegroups.com> dmitrey: > As I have mentioned, I don't know final length of the list, but > usually I know a good approximation, for example 400. There is no reserve()-like method, but this is a fast enough operation you can do at the beginning: l = [None] * 400 It may speed up your code, but the final resizing may kill your performance anyway. You can try it. Just using Psyco is probably better. Bye, bearophile From deets at nospam.web.de Mon Mar 17 11:23:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 16:23:12 +0100 Subject: Missing PyObject definition References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: <647gn4F2aphcqU1@mid.uni-berlin.de> James Whetstone wrote: > I'm trying to access a PyObject directly from C++ for the purpose of > calling method on a Python object that is an intance of a derived C++ > class. My problem is that the compiler is complaining about not PyObject > not being > defined. Has anyone run into the problem? Where is PyObject defined? This is a problem-description pretty far on the vague side, so the answer can be as vague only: in Python.h, which should be part of your python-installation. Better answers can be provided when you give more information - platform, python-version, source-code, tracebacks... Diez From mnordhoff at mattnordhoff.com Thu Mar 20 17:09:09 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 20 Mar 2008 21:09:09 +0000 Subject: Problem with PARAGRAPH SEPARATOR In-Reply-To: <8D5970DD46B50A409A0E42BA407964FE0E6DF433@SGBD012007.dlrmail.ad.delarue.com> References: <8D5970DD46B50A409A0E42BA407964FE0E6DF433@SGBD012007.dlrmail.ad.delarue.com> Message-ID: <47E2D275.2020209@mattnordhoff.com> Dominique.Holzwarth at ch.delarue.com wrote: > Actually that's what I tried to do, for example: > outputString = myString.encode('iso-8859-1','ignore') > > However, I always get such messages (the character, that's causing problems varies, but its always higher than 127 ofc...) > > 'ascii' codec can't decode byte 0xc3 in position 51: ordinal not in range(128) > > It doesn't matter what encoding I use (tried 'utf-8' 'utf-16' 'latin_1' and the iso one). The debugger is showing all the special characters (from french and german language) so I'm wondering why there's still the message about the 'ascii' codec... > > Would that mean that the string "myString" is an ascii-string or what? That's a *decode* error. If myString is a str object, it has to be *decoded* before it can be *encoded* to ISO-8859-1 or whatever you want, and it's defaulting to ASCII. This page may help: -- From jameswhetstone at comcast.net Mon Mar 17 11:12:22 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Mon, 17 Mar 2008 08:12:22 -0700 Subject: Missing PyObject definition Message-ID: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> I'm trying to access a PyObject directly from C++ for the purpose of calling method on a Python object that is an intance of a derived C++ class. My problem is that the compiler is complaining about not PyObject not being defined. Has anyone run into the problem? Where is PyObject defined? Thanks! James From rranshous at gmail.com Thu Mar 13 16:39:41 2008 From: rranshous at gmail.com (_robby) Date: Thu, 13 Mar 2008 13:39:41 -0700 (PDT) Subject: Update pytz timezone definitions Message-ID: I am looking at using pytz in a scheduling application which will be used internationally. I would like to be able to update the definition files that pytz uses monthly or bi-monthly. As far as I can tell, pytz seems to be updated (fairly) regularly to the newest tzdata, but I don't want to have to update my pytz, just it's definitions. http://www.twinsun.com/tz/tz-link.htm says that pytz "compiles tz source into Python." Does this mean that there is already a method for updating the definitions? Any help would be greatly appreciated, even if it is to point out something obvious which I over looked. - Robby From roger.dahlstrom at gmail.com Mon Mar 31 14:13:48 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 31 Mar 2008 11:13:48 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: On Mar 31, 12:53 pm, "mimi.vx" wrote: > On Mar 31, 4:22 pm, rdahlstrom wrote: > > > > > So I have a 64 bit Windows 2003 system, running python 2.5.1.1. > > > I can import a Windows .dll (msvcrt or whatever) using ctypes, but > > when attempting to import another application-specific .dll (tibrv.dll > > if anyone is familiar with it), I receive the error WindowsError: > > [Error 193] %1 is not a valid Win32 application. > > > I know there's a Windows on Windows (wow) which allows 32 bit > > processes to run on 64 bit windows - is there a way to work this in > > somehow? Maybe I'm barking up the wrong tree? > > > Code is simple, and works on 32 bit systems no > > > from ctypes import * > > #this doesn't work > > tibrv = cdll.tibrv > > #this does work > > msvcrt = cdll.msvcrt > > all dlls and python must be 32bit or 64bit, no mixed ... Crap, no way to make a 32 bit load, even using the wowexec? From Lie.1296 at gmail.com Tue Mar 11 12:31:09 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 09:31:09 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> <2b098afa-2dcc-4bde-bdde-02eece46fd68@47g2000hsb.googlegroups.com> Message-ID: <817b79d0-d451-4696-ab73-1289a380136c@d4g2000prg.googlegroups.com> On Mar 10, 4:16?am, castiro... at gmail.com wrote: > On Mar 9, 4:25?am, Lie wrote: > > > On Mar 9, 3:27?am, castiro... at gmail.com wrote: > > > > To Lie: > > > > > Personally I preferred a code that has chosen good names but have > > > > little or no comments compared to codes that makes bad names and have > > > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > > > I won't like it, it's that I can't. ?You know, in linguistics, there's > > > But I much prefer it that the code has good names AND concise > > comments, not too short and not too long that it becomes obscure. > > What do you mean? ?If 'obscure' is the right word, then it's > subjective (from metrics import obscurity?), which means that 10% of > the people disagree with you, or 90% do. ?The end-all be-all, there is > no such thing. ?I don't think it's obscure; I do. ?Is it? No, there is a point where everyone would say obscure. Such as a simple two integer addition function that have thirty pages of documentation and that have names like: def dosomereallyfunkythings(argumentoneissomethingadded, argumentbisaddinga): """ blah blah blah blah ... 30 or so pages later... ... Ok, that is the end of it, it's a complex function actually """ return argumentoneissomethingadded + argumentbisaddinga (remember you don't have access to source code, so you have to decipher the documentation for what the function is about) I prefer to see something like this: def add(a, b): return a + b Even without documentation I'd know immediately what it does from the name (add) From noone at nowhere.com Fri Mar 7 00:12:30 2008 From: noone at nowhere.com (pythonNEWB) Date: Thu, 06 Mar 2008 23:12:30 -0600 Subject: jython jmx tutorials? Message-ID: I am looking to try to build a simple, generic tool for basic monitoring and gathering of config information from java app servers such as weblogic (I know WLST is there, but I want the exercise and for it to work with more than just weblogic), tomcat and jboss using jython and jmx. Can anyone recommend any docs or sites that might have any useful info on those topics that might help me get started? I have been using python for a year or two now, but my java skills are pretty beginner... TIA. From michael.wieher at gmail.com Mon Mar 17 17:14:54 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 16:14:54 -0500 Subject: Apache binary error? In-Reply-To: References: Message-ID: yes that was already there, but it kept giving me that every-other problem i know its the fact the web-browser wasn't passed the "content-type=..." on the alternate reloads but as to why im lost in the end i figure its best to just ignore this and move to the more beta-test dev stage which involves django, so hopefully that'll just erase this weird error and i know the script worked (ie: the content should be being piped to the page) because the 2nd refresh (or first, alternately) would provide me with the expected result (ie: a web page) thanks tho =) 2008/3/17, Graham Dumpleton : > > On Mar 18, 4:43 am, Sean Allen wrote: > > On Mar 17, 2008, at 10:55 AM, Michael Wieher wrote: > > > > > have simple webpage running > > > > > apache,mod_python > > > > > the error is binary.... > > > ...binary as in "every other" time I load the page, Firefox keeps > > > telling me I'm downloading a python script, and asks to open it in > > > WINE, which is really strange. > > > > > then, alternately, it loads the page just fine. any clues as to why > > > this is happening? > > > -- > > > > for anything like mod_perl,mod_pythonetc the first thing i do when i > > get really weird errors > > it move to having only one apache process for testing. > > > > might want to start there. > > In mod_python handler code: > > req.content_type = 'text/plain' > > or otherwise. > > If you don't indicate what the response content type is web browsers > will often try and work it out based on the extension in the URL. > > This is presuming you configured Apache correctly and your code is > actually being executed and you aren't just serving up your code > instead. > > Graham > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gigs at hi.t-com.hr Wed Mar 5 08:39:19 2008 From: gigs at hi.t-com.hr (gigs) Date: Wed, 05 Mar 2008 14:39:19 +0100 Subject: hidden built-in module In-Reply-To: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> Message-ID: koara wrote: > Hello, is there a way to access a module that is hidden because > another module (of the same name) is found first? > > More specifically, i have my own logging.py module, and inside this > module, depending on how initialization goes, i may want to do 'from > logging import *' from the built-in logging. > > I hope my description was clear, cheers. > > I am using python2.4. you can add your own logging module in extra directory that have __init__.py and import it like: from extradirectory.logging import * and builtin: from logging import * From fuzzyman at gmail.com Sun Mar 16 10:59:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 16 Mar 2008 07:59:38 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 11:10 am, Bruce Eckel wrote: [snip..] > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Vendors were guaranteed first pick on lightning talk slots, and > we in the audience, expectantly looking forward to interesting and > entertaining content, again started to feel like things were awfully > commercial. And what seemed like a good idea, moving lightning talks > into plenary sessions with no competition, began to look like another > way to deliver a captive audience to vendors. > coming. I have a conflict of interests - coming to PyCon from a sponsor company and having given a lightning talk. But I *kind* of agree with you. Most of the sponsor lightning talks were pretty dull. I *hope* mine was one of the exceptions. (Resolver One demo.) ;-) This isn't new though. Last year (my only other PyCon) all the sponsors gave lightning talks. The difference is that there were more sponsors this year I guess... Personally I think 'sponsor keynotes' was a mistake. Not a huge mistake, but nonetheless... Michael Foord Resolver Systems From http Tue Mar 18 01:32:20 2008 From: http (Paul Rubin) Date: 17 Mar 2008 22:32:20 -0700 Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> Message-ID: <7xod9cvbq3.fsf@ruckus.brouhaha.com> Larry writes: > It seems to me that Python always add intervening spaces between data > elements when writing to a file It's just the print statement that does that. From davids at evertech.com.au Fri Mar 14 00:37:12 2008 From: davids at evertech.com.au (David S) Date: Fri, 14 Mar 2008 04:37:12 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: Hi, I get ERROR: ""C:\Program Files\apache-ant-1.7.0\bin\ant"" does not exist If I cut the path statement here and paste it next to a windows XP command prompt ant is invoked. The python code here is if not os.path.isfile(ANT_CMD): error('"%s" does not exist' % ANT_CMD) David "Mensanator" wrote in message news:360a8612-f5a2-4f2f-bae2-c89ed35b7d1b at n77g2000hse.googlegroups.com... On Mar 13, 5:16 pm, "David S" wrote: > Hi, > > I have some code in which I have to change some path names to get it to > work. The original code seems to have assumed that path names would not > have > any embedded spaces. > > I am not sure how to write the following line so when used in my script > the > path will be found. > > ANT_CMD = r'C:\Program Files\apache-ant-1.7.0\bin\ant' Try ANT_CMD = r'"C:\Program Files\apache-ant-1.7.0\bin\ant"' > > Regards, > David From grante at visi.com Sun Mar 9 00:23:27 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:23:27 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> <63h1j2F27rdfoU1@mid.individual.net> Message-ID: <13t6t2feje9gvd2@corp.supernews.com> On 2008-03-09, K Viltersten wrote: >>> /** Projects an object from 3D to 2D using >>> the method of Alexander The Great. >>> \param 3D structure to be projected >>> \returns 2D projection >>> */ >>> public Proj2D get2Dfrom3D(Proj3D param); >>> >>> The above is, to me, very clear and >>> consistent. Not to mention, easily >>> handled with e.g. Doxygen to create a >>> readable documentation. >>> >>> I don't see how this is dislikeable. Please >>> explain. >> >> When get2Dfrom3D changes its signature but >> the comment is not changed. That's where I >> have a problem, and it's only a matter of >> time before it happens. > > I think we've arrived at the spot where i'll > claim that a _always_ update my comments, Perhaps you do. AFAICT, nobody else does. :) -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From stuff at greenery.me.uk Mon Mar 17 08:03:08 2008 From: stuff at greenery.me.uk (Thomas G) Date: Mon, 17 Mar 2008 12:03:08 GMT Subject: wxPython graphics query (newbie) Message-ID: I am exploring wxPython and would be grateful for some help. It is important to me to be able to slide words and shapes around by dragging them from place to place. I don't mean dragging them into a different window, which is what 'Drag and Drop' has come to mean, just moving them around within a canvas-like space. This is easy using Tkinter. Can anybody offer me a tiny, very simple example of how it would be done in wxPython, please? To make sure I convey what I'm looking for, here is what it looks like using Tkinter, written very simply. What I'm looking for is the same, quite simple functionality expressed in wxPython, again written very simply so that I can easily understand it. #!/usr/bin/python from Tkinter import * root = Tk() global canv def makeFrame(root): global canv canv = Canvas (root, height = 200, width = 350) canv.create_text(100, 100, text='drag me', tags=('movable')) canv.tag_bind('movable', '', slide) #B1-motion is a drag with left button down canv.pack() def slide (event): ''' triggered when something is dragged on the canvas - move thing under mouse ('current') to new position ''' newx = event.x newy = event.y canv.coords('current', newx, newy) makeFrame(root) root.mainloop() Many thanks in advance -- Thomas Green From gagsl-py2 at yahoo.com.ar Fri Mar 21 14:08:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 11:08:45 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> Message-ID: <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> On 21 mar, 10:14, castiro... at gmail.com wrote: > On Mar 20, 9:28?am, "Jerry Hill" wrote: > > A more general > > solution might use a generator expression, like this: > > newsz = tuple(x/scale for x in origsz) > > You want to perform a uniform call on the elements of a collection. > "Diagram A" appends 0 to every item of a list. > > >>> y= [ [] for k in range( 10 ) ] > >>> def x( fun, *ar, **kw ): > > ... ? ? def post( *xr, **xw ): > ... ? ? ? ? ? ? return fun( *(xr+ ar), **kw ) > ... ? ? return post > ...>>> x( list.append, 0 )( y[0] ) Sane programmers replace that crazyness with this code: for x in collection: x.append(0) > >>> y= ( 300, 400 ) > >>> tuple( map( x( int.__add__, 1, ), y ) ) > > (301, 401) Sane programmers replace that crazyness with this code: tuple(x+1 for x in y) > Floats get harder, since you're looking at composition. > > >>> tuple( map( compose( float, x( float.__mul__, 1/ 2.5 ) ), y ) ) > > (120.0, 160.0) # (160, 120) Sane programmers -like D'Aprano, Jerry Hill and me- replace that crazyness with this code: tuple(x/2.5 for x in y) > def compose( *f ): > ? ? def post( *ar, **kw ): > ? ? ? ? ? ? if len( f )> 1: > ? ? ? ? ? ? ? ? ? ? return f[0]( compose( *f[1:] )( *ar, **kw ) ) > ? ? ? ? ? ? return f[0]( *ar, **kw ) > ? ? return post Sane programmers don't write such semi-functional things (unless it helps expressing the problem in certain domains). I now think that deprecating map, lambda & Co. was a good thing after all. -- Gabriel Genellina From george.sakkis at gmail.com Sun Mar 30 10:23:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 30 Mar 2008 07:23:10 -0700 (PDT) Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote: > Steven D'Aprano wrote: > > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > > >> Second try: > > ... > >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with > >> each call. But it's the only way I could find, at least without changing > >> the code template used by timeit. > > > Eeek. Talk about namespace pollution. > > > Thanks for the effort, but if that's the only solution, I think the > > solution is worse than the problem! > > > Perhaps it's time for me to take a different approach. > > [snip] > > Maybe the following enhancement of timeit would be worthwhile? [snip] That would be great. I sometimes avoid timeit altogether because setting up the environment is so cumbersome. Can you post the patch to bugs.python.org so it doesn't get lost ? George From sadreti at gmail.com Sun Mar 9 08:03:12 2008 From: sadreti at gmail.com (sadreti at gmail.com) Date: Sun, 9 Mar 2008 05:03:12 -0700 (PDT) Subject: The intel processor reach the very high place... Message-ID: <19211ed6-26ff-436b-88da-e93128a4fe62@s19g2000prg.googlegroups.com> The intel processor reach the very high place... http://intelsprocessor.googlepages.com From gherron at islandtraining.com Mon Mar 10 10:39:25 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 10 Mar 2008 07:39:25 -0700 Subject: is operator In-Reply-To: <004801c881f2$a04081f0$0b020b0a@nb1011> References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <47D5481D.4000004@islandtraining.com> Metal Zong wrote: > > The operator is and is not test for object identity: x is y is true if > and only if x and y are the same objects. > > > > >>> x = 1 > > >>> y = 1 > > >>> x is y > > True > > > > Is this right? Why? Thanks. > > > Yes that is true, but it's an implementation defined optimization and could be applied to *any* immutable type. For larger ints, such a thing is not true. >>> x=1000 >>> y=1000 >>> x is y False If either is a surprise, then understand that the "is" operator should probably *never* be used with immutable types. Gary Herron From aahz at pythoncraft.com Fri Mar 7 16:31:14 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Mar 2008 13:31:14 -0800 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> <13t3cfpo6d8d2ab@corp.supernews.com> Message-ID: In article <13t3cfpo6d8d2ab at corp.supernews.com>, Grant Edwards wrote: > >My thumb has been putting two spaces after a period for 30 >years, so the chances that it's going to change are rather >slim. :) +1 QOTW -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From duncan.booth at invalid.invalid Mon Mar 17 06:40:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 10:40:43 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > Which is exactly what happens - the actual implementation chose to cache > some values based on heuristics or common sense - but no guarantees are > made in either way. Here's a puzzle for those who think they know Python: Given that I masked out part of the input, which version(s) of Python might give the following output, and what might I have replaced by asterisks? >>> a = 1 >>> b = 5-4 >>> if a is b: print 'yes!' ... yes! >>> b = **** >>> if a is b: print 'yes!' ... >>> b 1 >>> type(b) From dkuhlman at rexx.com Thu Mar 13 19:29:11 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 13 Mar 2008 16:29:11 -0700 Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> Message-ID: <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Arnaud Delobelle wrote: > > 4. Both points above follow from the fact that foo.bar is really a > function call that returns a (potentially) new object: in fact what > really happens is something like Arnaud and Imri, too - No. foo.bar is *not* really a function/method call. > > Foo.__dict__['bar'].__get__(foo, Foo). > > So every time foo.bar is executed an object is (or may be) created, > with a new id. > > HTH I appreciate the help, but ... Actually, it does not help, because ... My understanding is that foo.bar does *not* create a new object. All it does is return the value of the bar attribute of object foo. What new object is being created? If I have: class Foo(object): def bar(self): pass And I do: foo = SomeClass() then: foo.bar should return the same (identical) object everytime, no? yes? I'm still confused. - Dave > > -- > Arnaud -- Dave Kuhlman http://www.rexx.com/~dkuhlman From PeterBraden1 at googlemail.com Sat Mar 8 14:29:11 2008 From: PeterBraden1 at googlemail.com (PB) Date: Sat, 8 Mar 2008 11:29:11 -0800 (PST) Subject: Image Libraries Message-ID: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> I have been using PIL for generating images, however it does not easily support operations with transparency etc. I tried to install aggdraw but it wouldn't compile. Ideally I'd like something open source so I can adapt it, hopefully mostly written in python rather than C. Is there any other decent image libraries for python? From http Thu Mar 13 22:02:24 2008 From: http (Paul Rubin) Date: 13 Mar 2008 19:02:24 -0700 Subject: How do I iterate over items in a dict grouped by N number of elements? References: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> Message-ID: <7xiqzq6p1r.fsf@ruckus.brouhaha.com> Noah writes: > What is the fastest way to select N items at a time from a dictionary? > I'm iterating over a dictionary of many thousands of items. > I want to operate on only 100 items at a time. > I want to avoid copying items using any sort of slicing. I'd do something like (untested): def groups(seq, n): while True: s = list(itertools.islice(seq, n)) if not s: return yield s items = d.iteritems() for g in groups(items, 100): operate_on (g) > Does itertools copy items? I don't understand this question. From paddy3118 at googlemail.com Mon Mar 10 01:59:45 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 9 Mar 2008 22:59:45 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: Message-ID: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> On Mar 9, 11:41 pm, Roopan wrote: > Hello! > > I am looking at developing an enterprise-grade distributed data > sharing application - key requirements are productivity and platform > portability. > > Will it be sensible to use C++ for performance-critical sections and > Python for all the glue logic. > > Pls comment from your *experiences* how Python scales to large > projects( > 200KLOC). > I assume the C++/Python binding is fairly painless. > > Regards > Elam. You might try prototyping as much as possible in Python as soon as possible. Then, and only after getting something that computes the right results, profile your prototype to see where the real bottlenecks are. Sometimes it it is not evident at the beginning where the bottlenecks in the prototype will be. If you write most of the prototype in Python then you will write less lines of code, in a shorter time and so should be more inclined to experiment with different algorithms, and do more testing. (Doctest can be great). After profiling their may be other ways to remove a bottleneck, such as using existing highly-optimised libraries such as Numpy; Psycho, an optimising interpreter that can approach C type speeds for Python code; and you could create your own C++ based libraries. You might want to ask the Mercurial development team how they got their impressive speed and functionality out of using mainly Python with critical regions in C. - Or watch this: http://video.google.com/videoplay?docid=-7724296011317502612 - Paddy. From gert.cuykens at gmail.com Wed Mar 5 19:47:37 2008 From: gert.cuykens at gmail.com (gert) Date: Wed, 5 Mar 2008 16:47:37 -0800 (PST) Subject: http://httpd.apache.org/docs/2.2/mod/mod_dbd.html Message-ID: Would anybody explain to me what needs to be done to have a DB-API 2.0 layer for this ? And how many lines of code we are talking ? http://httpd.apache.org/docs/2.2/mod/mod_dbd.html From vvangelovski at gmail.com Mon Mar 24 10:04:41 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Mon, 24 Mar 2008 07:04:41 -0700 (PDT) Subject: URL encoding Message-ID: <9693ffda-1454-4d56-acee-1e6fc4ebeccb@h11g2000prf.googlegroups.com> Is there any method in the standard modules that can perform proper url encoding according to RFC? From hajducko at gmail.com Thu Mar 27 00:50:56 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Wed, 26 Mar 2008 21:50:56 -0700 (PDT) Subject: Plugin framework - Overcomplicating things? Message-ID: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> As a side project and a learning experience and ultimately, a good tool for my department, I started developing a simple jabber bot for our work's conference server, with the intention of making it capable of running specific commands and utilities. I realize there are other bots out there, but I thought this would be a good first python project for me. Most of my current scripts/utilities are in perl or php, so the OO world is a little new. In any case, I wrote up a Bot class, got it to connect, join rooms, see chat, and the world rejoiced. Now, instead of writing a monolithic function for the message handler to deal with all the incoming text and all the possible cool things I could do with the bot like intranet lookups, dns checks, etc, I thought to myself: "self, wouldn't it be cool if you made a plugin framework that could read in a bunch of plugins and the bot could hand off the text to a plugin that was looking for that command and it could do the job". Then the smarter side of myself said "self, you have no frak'n idea how to do that". So I've been scouring this list for days, reading some of the past conversations. I investigated the trac component system, downloaded the source and tried my best to make heads ( or tails, take your pick ) of it. I looked at setuptools and eggs, I looked at Marty's simple framework at http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/ and I searched all over google for anything, even stuff that was non- python specific and just detailed plugin frameworks in theory ( I didn't find any good ones, so if you have some links, gimme. :) ) and I'm sorry say, but I still don't get it. While I understand half of it, I'm still not getting the point of using it for something like what I'm trying to accomplish. All this comes to my question - am I overcomplicating this project? I can understand the use of something like the trac component system if I had multiple components and plugins that handled different areas of my project and different points of interaction, but I don't. I've got exactly one spot where I want to check all my plugins and hand off the message to which ever ones are looking for that command. So really, should I even bother with trying to setup some framework for this or should I just be doing a simple loop over a directory, importing all the plugins and storing them in a list and then looping over them in the message handler to see which ones were looking for the command and letting them do their thing? I don't see the advantage I'd get from implementing something more complicated at this point. If you could show me the yellow brick road or offer any pointers, I'd appreciate it. I'm more than willing to go off reading more pages, but when the first 5 pages of a google search for 'plugin framework design' shows all purple, visited links and I'm still not getting it, I finally decided to turn here to the list and get some professional advice. As an aside, if there is anyone who is an experience developer and designer and is willing to take some private correspondence, please let me know. I feel embarrassed for asking, but I've got a alot of questions that I don't want to litter this list with and would rather voice them in private. Thanks, steve From grante at visi.com Tue Mar 4 15:46:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 04 Mar 2008 20:46:14 -0000 Subject: Python an Exchange Server References: Message-ID: <13srd8micnh7g35@corp.supernews.com> On 2008-03-04, Tim Chase wrote: > Exchange offers other proprietary functionality, exposed > through the MAPI. You might be able to use some of the Win32 > functionality in one of the add-on modules for talking with > COM objects. I spent a while looking into this a few years ago, and there was no way to use MAPI other than via the COM interface to Outlook. There are examples of using Outlook via its COM interface floating around somewhere. -- Grant Edwards grante Yow! Go on, EMOTE! at I was RAISED on thought visi.com balloons!! From mwilson at the-wire.com Thu Mar 13 20:18:31 2008 From: mwilson at the-wire.com (Mel) Date: Thu, 13 Mar 2008 20:18:31 -0400 Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> My understanding is that foo.bar does *not* create a new object. > > Your understanding is not correct. > >> All it >> does is return the value of the bar attribute of object foo. What new >> object is being created? > > A bound method. This happens through the descriptor-protocol. Please see > this example: > > > class Foo(object): > def bar(self): > pass > > > f = Foo() > a = Foo.bar > b = f.bar > c = f.bar > > print a, b, c > print id(b), id(c) (What Diez said.) From what I've seen, f.bar creates a bound method object by taking the unbound method Foo.bar and binding its first parameter with f. This is a run-time operation because it's easy to re-assign some other function to the name Foo.bar, and if you do, the behaviour of f.bar() will change accordingly. You can get some very useful effects from these kinds of games. You can make f into a file-like object, for example, with import sys f.write = sys.stdout.write Here, f.write *is* a straight attribute of f, although it's a built-in method of the file class. It's still bound, in a way, to sys.stdout. I'm assuming that a different example could create an attribute of f that's a bound method of some other object entirely. I've verified that f.write('howdy') prints 'howdy' on standard output. Mel. From miki.tebeka at gmail.com Tue Mar 25 20:36:03 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 25 Mar 2008 17:36:03 -0700 (PDT) Subject: what are generators? References: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> Message-ID: On Mar 24, 8:17?am, castiro... at gmail.com wrote: > I'm looking for a cool trick using generators. ?Know any exercises I > can work? Simple one the comes to mind is flattening a list: >>> list(flatten([1, [[2], 3], [[[4]]]])) [1, 2, 3, 4] >>> HTH, -- Miki http://pythonwise.blogspot.com From ursneed.urs at gmail.com Thu Mar 13 03:57:12 2008 From: ursneed.urs at gmail.com (ursneed) Date: Thu, 13 Mar 2008 00:57:12 -0700 (PDT) Subject: need in deed.....!!! Message-ID: hi.... here the links are goes here..... http://ursneed.googlepages.com/home http://ursneed.googlepages.com/coolneeds http://ursneed.googlepages.com/funnimes http://ursneed.googlepages.com/secrets http://ursneed.googlepages.com/flashgames please do me comments... or revert back ur responce (request).... i am here do it for YOU.... ursneed From gh at ghaering.de Sat Mar 29 14:46:19 2008 From: gh at ghaering.de (=?ISO-8859-15?Q?Gerhard_H=E4ring?=) Date: Sat, 29 Mar 2008 19:46:19 +0100 Subject: How to insert multiple rows in SQLite Dbase In-Reply-To: References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> Message-ID: <657h3nF2eehi8U1@mid.uni-berlin.de> Gabriel Genellina wrote: > [...] > and execute: > cur.executemany("insert into log (IP, EntryDate, Requestt, ErrorCode) > values (:ip, :date, :request, :errorcode)", values) It's probably worth mentioning that pysqlite's executemany() accepts anything iterable for its parameter. So you don't need to build a list beforehand to enjoy the performance boost of executemany(). The deluxe version with generators could look like this: def parse_logfile(): logf = open(...) for line in logf: if ...: row = (value1, value2, value3) yield row logf.close() ... cur.executemany("insert into ... values (c1, c2, c3)", parse_logfile()) -- Gerhard PS: pysqlite internally has a statement cache since verson 2.2, so multiple execute() calls are almost as fast as executemany(). From tralalal at joepie.nl Wed Mar 19 05:00:32 2008 From: tralalal at joepie.nl (taco) Date: Wed, 19 Mar 2008 10:00:32 +0100 Subject: lock access to serial port References: Message-ID: kkadrese at gmail.com wrote: > hello group, > > how to get ttyS0 serial port for exclusive access? I have a python > script that uses this device with AT commands. I need that two > instances can call simultaneosuly this python script but only one of > them gets the device. I tried fcntl.flock, it was just ignored, put > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not > know what are appropriate arguments), googled half a day for various > phrases, error messages etc....without success. > > please help, > > Andra not sure if I understand you well, but how about a server application which accepts 2 clients which can send messages which are output on the serial device? The serial device access protected with a mutex while receiving messages done in 2 threads or something. taco From fairwinds at eastlink.ca Fri Mar 28 16:50:49 2008 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 28 Mar 2008 17:50:49 -0300 Subject: cProfile for python 2.4 Message-ID: <47ED5A29.6070906@eastlink.ca> I'd like to compile cProfile for python 2.4. Where can I get it to do this? I realize it is part of python 2.5. Many thanks. From castironpi at gmail.com Wed Mar 5 17:51:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 14:51:04 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: On Mar 5, 4:00?pm, Grant Edwards wrote: > On 2008-03-05, castiro... at gmail.com wrote: > > >>>>> I want to hash values to keys. ?How do the alternatives compare? > > >>>>http://catb.org/~esr/faqs/smart-questions.html > > >>> ... without extending the whole way to a full relational database? > > >> You didn't bother following the link and reading the advice, did you? If > >> you did, you haven't done a good job of following that advice. > > > Well, obviously there's someone who's interested in computers and > > programming that has a question. > > It may be ?obvious that he has a question. ?It's not the least > bit obvious what that question is. > > > Communication is not his forte, but effort, willingness, > > devotion, and dedication are. ?What should he do, and what > > should the others, who are gifted speakers? > > He should spend less time trying to generate "gifted speach" > and more time learning how to ask an understandable, meaningful > question. ?The link which you ignored explains how to do that. > > In your original post, it's not very clear what you mean by > "hash values to keys" means nor what alternatives you're asking > about. If you're trying to learn about hashing algorithms, then > google "hashing algorithms" and read the first half-dozen hits. > > The first two are Wikipedia articles which are both quite good > and are almost certainly available in your native lanauge. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! But they went to MARS > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? around 1953!! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? Are you vegetarian? A little off topic. Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a) is also in it, and maps to the same object? From python.list at tim.thechases.com Wed Mar 12 11:03:58 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 10:03:58 -0500 Subject: agg (effbot) In-Reply-To: <63q90kF268j23U1@mid.uni-berlin.de> References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> <63q90kF268j23U1@mid.uni-berlin.de> Message-ID: <47D7F0DE.5000106@tim.thechases.com> Gerhard H?ring wrote: > fraleysinger at gmail.com wrote: >> aggdraw-1.2a3-20060212.tar.gz > > Try shegabittling the frotz first. If that doesn't help, please post the > output of the compile command that threw the error. Maynard: He who is valiant and pure of spirit may find the compiling instructions in the Drawing Program of Agg Arthur: what?! Maynard: the Drawing Program of Agg. Bedevere: What's that? Maynard: he must of died while typing it Launcelaot: Oh, come on! Maynard: well, that's what it's called Artuhur: Look, if he was dying, he wouldn't bother to name it "agg" Maynard: Well, that's what's written in the URL Galahad: Perhaps he was dictating... Arthur: Oh, shut up. ... -tkc From arnodel at googlemail.com Sat Mar 22 06:58:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 03:58:15 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> On Mar 22, 8:31?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > John Machin wrote: > >> On Mar 22, 1:11 am, castiro... at gmail.com wrote: > >>> A collision sequence is not so rare. > >>>>>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > >>> [1, 1, 1, 1, 1, 1, 1, 1] > >> Bryan did qualify his remarks: "If we exclude the case where an > >> adversary is choosing the keys, ..." > > > Some adversary. ?What, you mean, my boss or my customers? > > We mean that the party supplying the keys deliberately chose > them to make the hash table inefficient. In this thread the goal > is efficiency; a party working toward an opposing goal is an > adversary. There are situations where this can happen I guess > If you find real-world data sets that tend to induce bad-case > behavior in Python's hash, please do tell. It would be reason > enough to adjust the hash function. The hashes in popular > software such as Python are already quite well vetted. As Python allows you to make your own hash functions for your own classes, another danger is that you are dealing with objects with a bad hash function. I've actually tried it (as I am *not* a pro!) and FWIW here are the results. -------- badhash.py ---------- class BadHash(object): def __hash__(self): return 1 # that's a bad hash function! from time import time def test(n): t0 = time() # Create a hash table of size n s = set(BadHash() for x in xrange(n)) t1 = time() # Add an object to it obj = BadHash() s.add(obj) t2 = time() # Find that object obj in s t3 = time() print "%s\t%.3e\t%.3e\t%.3e" % (n, (t1-t0)/n**2, (t2-t1)/n, (t3- t2)/n) print "n\tcreate/n^2\tadd/n\t\tfind/n" for k in range(8, 17): # I'm hoping that adding an element to a dict of size (1 << k) + 1 # will not trigger a resize of the hasmap. test((1 << k) + 1) -------------------------------- marigold:junk arno$ python badhash.py n create/n^2 add/n find/n 257 3.917e-08 6.958e-08 7.051e-08 513 3.641e-08 8.598e-08 7.018e-08 1025 3.522e-08 7.118e-08 6.722e-08 2049 3.486e-08 6.935e-08 6.982e-08 4097 3.480e-08 7.053e-08 6.931e-08 8193 3.477e-08 6.897e-08 6.981e-08 16385 3.441e-08 6.963e-08 7.075e-08 32769 3.720e-08 7.672e-08 7.885e-08 65537 3.680e-08 7.159e-08 7.510e-08 So theory and practice agree! In this case The hash table behaves just like a linked list. Lastly, if one deals with a totally ordered set of object but they are not hashable (there isn't a good hash function), then Ninereeds' idea of sorting first is still useful. -- Arnaud From noname9968 at gmail.com Thu Mar 27 07:57:52 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 14:57:52 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> <47EB7F55.8090909@gmail.com> Message-ID: <47EB8BC0.1020604@gmail.com> Guilherme Polo wrote: > 2008/3/27, Alex9968 : > >> Guilherme Polo wrote: >> > 2008/3/27, Alex9968 : >> > >> >> Guilherme Polo wrote: >> >> > 2008/3/26, Alex9968 : >> >> > >> >> >> Hi all, >> >> >> >> >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> >> >> using visual GUI designers), so my question is which other GUI toolkits >> >> >> have similar functionality. >> >> >> >> >> > >> >> > The geometry manager isn't related to using GUI designers tools at >> >> > all. And each toolkit has it's own way to do the things, wxPython uses >> >> > sizers, PyGtk uses containers. >> >> > >> >> >> >> Well, the geometry manager isn't *directly* related to using GUI >> >> designers, but as Pack arranges widgets automatically, using GUI >> >> designers isn't required, while with geometry managers that don't, GUI >> >> designers are necessary (if you start placing widgets programmatically, >> >> you'll end up reinventing something like Tkinter's Pack or Grid geometry >> >> manager). I hope I can be understood clearly this time ;-) >> >> >> > >> > Not at all, can't understand your point yet. GUI designers aren't just >> > for placing widgets, they also will keep the interface design >> > separated from your code. >> > >> >> I do not want to separate interface from code and I do not experience >> the need to use GUI designers. >> >> > > It is your opinion, it seems I can't change it for now but I hope you > reconsider it for the future. > > >> Pack arranges widgets perfectly, and it's very complex to do the same >> without it, both in code and in GUI designer. >> > > For some level of "perfect", of course. > Also, I can't understand why you say it is hard to do such thing in a > gui designer tool, which tool have you tried ? Maybe you are not > familiar with them yet, and that could be the problem. > Can you explain why my opinion is to be reconsidered? In GUI designer it's easy to produce initial (still) layout, but what if it should be changed at runtime (for example, widgets added or removed), and still be ideally arranged? I know that widgets might have some parameters affecting for example how they move when their container is resized, and that might help when updating interface, but I think it's inconvenient that they're hidden inside their property sheets (and therefore invisible while designing). I should answer the question - I used Visual C# from Microsoft Visual Studio .NET 2003, and after moving to Python I did not use any GUI designer. From mwilson at the-wire.com Wed Mar 19 11:58:19 2008 From: mwilson at the-wire.com (Mel) Date: Wed, 19 Mar 2008 11:58:19 -0400 Subject: how to remove suffix from filename References: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> Message-ID: royG wrote: > when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/ > two.jpg'....] etc i want to extract the > basename without the suffix...ie i want to get 'one','two' etc and not > 'one.jpg' > > is there a function in python to do this or do i have tosplit it ..? > thanks os.path.splitext is the one, it think. From marko at pacujo.net Thu Mar 13 08:03:51 2008 From: marko at pacujo.net (Marko Rauhamaa) Date: 13 Mar 2008 14:03:51 +0200 Subject: How to send a var to stdin of an external software References: Message-ID: Benjamin Watine : > How can I do this ? I would like a function like that : > > theFunction ('cat -', stdin=myVar) > > Another related question : Is there's a limitation of var size ? I > would have var up to 10 MB. import subprocess myVar = '*' * 10000000 cat = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE) cat.stdin.write(myVar) cat.stdin.close() cat.wait() Marko -- Marko Rauhamaa mailto:marko at pacujo.net http://pacujo.net/marko/ From rpdooling at gmail.com Wed Mar 12 14:16:15 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Wed, 12 Mar 2008 11:16:15 -0700 (PDT) Subject: Does __import__ require a module to have a .py suffix? References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: <3d4247e6-1240-434e-adc6-090cd480a551@y77g2000hsy.googlegroups.com> On Mar 12, 11:22 am, mrstephengross wrote: > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? > I think you answered your own question, but if you want more info: >From the Python Tutorial: http://docs.python.org/tut/node8.html "A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended." RD > Thanks, > --Steve From asmodai at in-nomine.org Fri Mar 14 14:20:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 14 Mar 2008 19:20:02 +0100 Subject: Thousand Seperator In-Reply-To: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <20080314182002.GE60713@nexus.in-nomine.org> -On [20080314 18:11], ewanfisher at gmail.com (ewanfisher at gmail.com) wrote: >But I cannot find how to do this in Python. I am not sure of your goal, but if you need this for localization purposes, look at Babel (http://babel.edgewall.org/). In particular http://babel.edgewall.org/wiki/ApiDocs/babel.numbers We make use of the Unicode CLDR information to provide locale-specific formatting. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When we have not what we like, we must like what we have... From castironpi at gmail.com Sat Mar 8 15:27:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:09 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 1:31?pm, Grant Edwards wrote: > On 2008-03-08, castiro... at gmail.com wrote: > > > Does one side of this hold that there are no -good- comments? > > I wouldn't say there are _no_ good comments, but I would say > that 90+% of the comments I've seen in my lifetime were bad. Limit your comments, in other words. LIM-IT. > comment explaining a particularly opaque algorithm can be > useful as well. But can't the name do that? > at the beginnings of C/C++ functions that do things like tell > you the name and return type of the function and list the names > and types of the parameters. Gee, thanks. ?I never could have > figured that out from looking at the source code itself. IMO, Sometimes void*s are guaranteed to be HTHREADs. > I'm also a bit baffled by people who put a comment at the top > of every file that tells you what the filename is. ?I sometimes > wonder how/where these files were created. All of the OSes I've > ever used had a feature called a "filesystem" which kept track > of info like the names of files. ?It must be a bitch-and-a-half > to work on an computer that doesn't keep track of filenames and > makes the user do it. > > When was the last time you thought to yourself: "Gee, I wonder > what's the the name of that file over there? I guess I'd better > open the file and look at the comment at the top to see what > the filename is? What file did you open? To Lie: > Personally I preferred a code that has chosen good names but have > little or no comments compared to codes that makes bad names and have Personally I don't. Show me a good one. Until you do, it's not that I won't like it, it's that I can't. You know, in linguistics, there's what's called 'code switching', which is switching between two languages you know midstream. People can understand 'hear' a language but not speak it. If you speak it, . If comments aren't the 'short version', then patience is the problem. There's not one word for lots and lots of things. Examples on backorder. Good comments are better than bad names. Good names are better than bad comments. And enter multi-word identifiers. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:54:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:54:18 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> <13t6s8pk90olef8@corp.supernews.com> <13t6te6p71r3u3e@corp.supernews.com> Message-ID: <13t6usamhmai128@corp.supernews.com> On Sun, 09 Mar 2008 05:29:42 +0000, Grant Edwards wrote: >> Sure, but really, adding ONE LINE to the start of a file is hardly >> "cluttering up" anything. Especially if it is in the doc string, like >> this: >> >> """widgets.py: create, manage and destroy widgets. >> >> blah blah blah blah...""" > > The bad part is that it's redundant information. That means that > eventually, it's going to be wrong. I withdraw my defense of including the file name. After looking at both the Python standard library and my own scripts/ modules, I can see that it is a lot rarer than I thought it was, and even when I do it, it is almost always in help strings for quick and dirty scripts. -- Steven From castironpi at gmail.com Thu Mar 6 14:06:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 11:06:50 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> Message-ID: On Mar 6, 8:30?am, Carl Banks wrote: > On Mar 5, 8:44 pm, Steven D'Aprano > cybersource.com.au> wrote: > > But what about classes? Are they singletons? Obviously classes aren't > > Singleton classes, that is, given an arbitrary class C you can create > > multiple instances of C. But what about class objects themselves? I've > > found a few odd references to "classes are singletons", but nothing in > > the language reference. > > Probably because "singleton" is the wrong word. ?A singleton means > there is one instance of a type; classes are instances of "type" which > can have many instances so classes are not singletons. > > Anyway, the answer to what you are probably asking is No. ?Try this: > > >>>import module > >>>c1 = module.Someclass > >>>reload(module) > >>>c2 = module.Someclass > >>>c1 is c2 What about >>> o= object() >>> b1= o.someattr >>> reload( o ) >>> b2= o.someattr >>> b1 is b2 ? From P.G.Aravindh at gmail.com Sun Mar 23 20:48:10 2008 From: P.G.Aravindh at gmail.com (Santhosh1992) Date: Sun, 23 Mar 2008 17:48:10 -0700 (PDT) Subject: TUTORIALS ON COMPUTER PROGRAMMING Message-ID: languages Have the complete details regarding programming languages. A-Z about programming languages like Java J2EE, C++, code implementation guides and more. http://operatingsys.blogspot.com/ From grante at visi.com Wed Mar 5 15:59:23 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 20:59:23 -0000 Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <13su15t266dimc2@corp.supernews.com> <13su1pl8tnq5o6a@corp.supernews.com> <6fa9d736-1769-4e79-a276-f071a83ebce9@e60g2000hsh.googlegroups.com> Message-ID: <13su2dbpqjoig2e@corp.supernews.com> On 2008-03-05, Jeff.Goldfinkle at gmail.com wrote: > thanks for the reply but I'm still unsure as to how to > continue. Using the bitwise operators will help me deal with > integers but I really want to work with floats. In your original post, you said that you've got the values as integers. > For instance - which bits do I twiddle to round my float to > the nearest number of bits? The format of a float (actually Python uses doubles) depends on your platform, but in all likelihood it's the IEEE-754 64-bit format. googling for "IEEE-754 format" finds some good references: http://en.wikipedia.org/wiki/IEEE_floating-point_standard http://steve.hollasch.net/cgindex/coding/ieeefloat.html http://www.psc.edu/general/software/packages/ieee/ieee.html -- Grant Edwards grante Yow! Well, I'm INVISIBLE at AGAIN ... I might as well visi.com pay a visit to the LADIES ROOM ... From pDOTpagel at helmholtz-muenchen.de Mon Mar 3 07:13:52 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Mon, 3 Mar 2008 12:13:52 +0000 (UTC) Subject: Delete hidden files on unix References: Message-ID: loial wrote: > How can I delete hidden files on unix with python, i.e I want to do > equivalent of > rm .lock* Here is one way to do it: import os, glob for filename in glob.glob('.lock*'): os.unlink(filename) Alternatively, you could also do this: import os os.system('rm .lock*') cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From deets at nospam.web.de Wed Mar 5 11:04:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Mar 2008 17:04:26 +0100 Subject: Unit testing Web applications References: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> Message-ID: <637uk7F257fv5U1@mid.uni-berlin.de> Monica Leko wrote: > Hi! > > Does Python has some testing frameworks for testing Web applications > (like Cactus and HttpUnit for Java), generating requests and checking > if the response is correct? mechanize and webunit come to my mind. Yet the most powerful will be selenium together with selenium-remote driven via python. Don't forget to check out the brilliant selenium IDE. Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 3 06:06:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Mar 2008 12:06:37 +0100 Subject: Beautiful Code in Python? In-Reply-To: References: Message-ID: <47cbdbbd$0$25962$426a34cc@news.free.fr> js a ?crit : > Hi, > > Have you ever seen Beautiful Python code? > Zope? Django? Python standard lib? or else? > > Please tell me what code you think it's stunning. FormEncode has some very interesting parts IMHO. From willkab6 at gmail.com Sat Mar 22 11:09:18 2008 From: willkab6 at gmail.com (willkab6 at gmail.com) Date: Sat, 22 Mar 2008 08:09:18 -0700 (PDT) Subject: NameError: name 'guess' is not defined Message-ID: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> I am very new to both programming and Pyhton and while trying to do some practice using A byte of python an Error pops up on the IDLE shell. I am using windows XP. PLease see below. while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that.' else: print 'No, it is a little lower than that.' else: print 'The while loop is over.' # Do anything else you want to do here print 'Done' After typing the above as the book says, I get the error NameError: name 'guess' is not defined What Am I doing wrong? From fakeaddress at nowhere.org Fri Mar 14 04:25:07 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 01:25:07 -0700 Subject: Spaces in path name In-Reply-To: <0RpCj.25549$421.10498@news-server.bigpond.net.au> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <13tk779i4r8j9ba@corp.supernews.com> <0RpCj.25549$421.10498@news-server.bigpond.net.au> Message-ID: David S wrote: > Using "C:\Program Files\apache-ant-1.7.0\bin\ant.bat" just gives me the same > result. Did you try the raw string, with the .bat extension? As in: r'C:\Program Files\apache-ant-1.7.0\bin\ant.bat' After Microsoft started allowing blanks in paths, it took them years to fix many common cases where their own software choked on the paths. I got into the habit of installing everything under c:\bin rather than C:\Program Files. I still do that just to avoid writing essays into my PATH variable. -- --Bryan From arkanes at gmail.com Thu Mar 20 16:55:09 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 20 Mar 2008 15:55:09 -0500 Subject: Need help calling a proprietary C DLL from Python In-Reply-To: <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> Message-ID: <4866bea60803201355r2acc8353qe133ae9d23415b0d@mail.gmail.com> On Thu, Mar 20, 2008 at 3:42 PM, Craig wrote: > > On Mar 20, 2:38 pm, Craig wrote: > > On Mar 20, 2:29 pm, sturlamolden wrote: > > > > > On 20 Mar, 19:09, Craig wrote: > > > > > The culprit i here: > > > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > > > This binds these names to Python ints, but byref expects C types. > > > > > Also observe that CacheSize and OpenMode should be c_short. > > > > I changed CacheSize and OpenMode to c_short, and commented out that > > line producing the "Before" message, and the output is the same. > > > > Further "tinkering" revealed that it is the byref on the fName and pw > > that are causing the error. > > > > The entire problem appears to be around the production of a BSTR and > > the passing of pointers (byref) to the BSTR. > > > Can anyone shed some light on how to work with BSTR's? Since you didn't tell ctypes about the function signature, it assumes it returns int and gives you a python int. Provide a function signature (c_void_p should work for BSTR) for both functions and you should have an easier time of it. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From planders at gmail.com Mon Mar 3 14:41:38 2008 From: planders at gmail.com (Preston Landers) Date: Mon, 3 Mar 2008 11:41:38 -0800 (PST) Subject: clocking subprocesses References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> Message-ID: <5af6d8ab-880a-4873-9352-cf1aaae236e0@e6g2000prf.googlegroups.com> On Mar 3, 11:57?am, barnbu... at gmail.com wrote: > So, long story short, I need to get CPU time of something I call using > subprocess.call(). ? Run your command through the "time" program. You can parse the output format of "time", or set a custom output format. This mostly applies to Unix-like systems but there is probably an equivalent somewhere on Windows. Preston From rokkamraja at gmail.com Fri Mar 7 03:41:57 2008 From: rokkamraja at gmail.com (Raja) Date: Fri, 7 Mar 2008 00:41:57 -0800 (PST) Subject: Python GDB Wrapper References: <47d0f228$0$17725$9b622d9e@news.freenet.de> Message-ID: On Mar 7, 1:21 pm, Raja wrote: > Hi All, > Thanks for replies. Daniel- I am looking at just a wrapper > around GDB. I dont want to emulate the functionalities of GDB but > instead use them in python scripting. > Martin - Misc/gdbinit looks promising. Thanks a lot. > > Thanks, > Raja. > > On Mar 7, 12:43 pm, "Martin v. L?wis" wrote: > > > > Has anyone does this before ? Even some basic idea or code as to how > > > to proceed would be great. > > > Have you seen Misc/gdbinit? > > > Regards, > > Martin Hi All, Marting- I looked at the Misc/gdbinit but what I want is a Python module which wraps around GDB and exposes its functionality, which has some methods in it like pystack to which if I give the arguments as program name and arguments displays the stack trace of that particular program . Thanks, Raja. From nir1408 at gmail.com Mon Mar 17 05:54:59 2008 From: nir1408 at gmail.com (Nir) Date: Mon, 17 Mar 2008 02:54:59 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: On Mar 17, 5:54 am, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece > ofpythoncode works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in adebuggerso I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But withPython, thedebuggeris a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. > > So I'm curious how to read code effectively. I agree thatpythoncode > is clear, but when it becomes long, reading it can still be a hard > work. Try Winpdb - www.winpdb.org (works on Linux as well). Don't forget to send feedback. From alex.pulver at gmail.com Sat Mar 15 06:31:46 2008 From: alex.pulver at gmail.com (Alex) Date: Sat, 15 Mar 2008 03:31:46 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> Message-ID: <92d6c804-4854-4d48-ae8c-588c6f9ab402@n75g2000hsh.googlegroups.com> On Mar 15, 5:42 am, Carl Banks wrote: > On Mar 14, 6:37 pm, Alex wrote: > > > > > On Mar 13, 6:21 pm, Carl Banks wrote: > > > > On Mar 13, 7:02 am, Bruno Desthuilliers > > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > > Alex a ?crit : > > > > (sni) > > > > > > First of all thanks all for answering! > > > > > > I have some environment check and setup in the beginning of the code. > > > > > I would like to move it to the end of the script. > > > > > Why ? (if I may ask...) > > > Sure, because of a readability (similar to function declarations in > > C). > > > > > > But I want it to > > > > > execute first, so the script will exit if the environment is not > > > > > configured properly. > > > > > If you want some code to execute first when the script/module is loaded, > > > > then keep this code where it belongs : at the beginning of the script. > > > > I concur with Bruno's recommendation: stuff you want to do first > > > should come first in the script. Things like BEGIN blocks hurt > > > readability because you can't identify where execution begins without > > > reading the whole file. > > > > Having said that, one thing that often happens in Python scripts is > > > that all the functions are defined first, then the script logic > > > follows. So you could put the meat of your script in a function, then > > > the "BEGIN" stuff after that functions: > > > > def run_script(): > > > # > > > # script contained in this long function > > > # > > > > # Then test preconditions here... > > > if os.environ["HELLO"] != "WORLD": > > > sys.exit(2) > > > > # Then call the run_script functions > > > run_script() > > > > But having said THAT, I don't recommend you do that with > > > preconditions. If the script has a quick early exit scenario, you > > > really ought to put that near the top, before the function > > > definitions, to clearly show to a human reader what is necessary to > > > run the script. > > > > Carl Banks > > > Hi, > > > Maybe i was a little bit unclear... I meant that i wanted to do > > something like this: > > > #!usr/bin/env python > > > check_env() > > > from subprocess import * > > > class MyClass: > > # Class definition > > > def check_env(): > > # Code > > > if __name__ == "__main__": > > # Script logic > > > The thing is, as i saw, that Python doesn't recognize the > > "check_env()" function before it reaches the "def" statement. > > You could rearrange it like this and it will work: > > #!usr/bin/env python > > def check_env(): > # Code > > check_env() > > from subprocess import * > > class MyClass: > # Class definition > > if __name__ == "__main__": > # Script logic > > Or, better yet, do what Arnaud Delobelle suggests. > > It's not a big deal to move imports down the page a bit, as long as > you throw in a few clear comments explaning what you're doing and why. > > You might also consider putting check_env() in a separate module. > > Carl Banks Hi guys, Thanks for help! :) From qingshan.chen at gmail.com Sun Mar 23 20:01:59 2008 From: qingshan.chen at gmail.com (QS) Date: Sun, 23 Mar 2008 17:01:59 -0700 (PDT) Subject: Does python hate cathy? Message-ID: Hi to all! I am new to python, and I encountered a weird problem. Here is my code ##########>8#################### #!/usr/bin/python # Filename: objvar.py class Person: '''Represents a person.''' population = 0 #sex = 'F' #age = 22 # It is vague here: is this variable going to be a class, or object, variable def __init__(self, name, sex): '''Initializes the person's data.''' self.name = name self.sex = sex print '(Initializing %s )' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' self.age = 25 print 'Hi, my name is %s, and I am %s, and I am age %d ' % (self.name, self.sex, self.age) def howMany(self): '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop', 'M') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam', 'M') kalam.sayHi() kalam.howMany() cathy = Person('Catherine', 'F') cathy.sayHi() cathy.howMany() swaroop.sayHi() swaroop.howMany() ############# 8< ######################### When I run this script, I got the following exception: Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored To to newcomer like me, this message doesn't make much sense. What seems weird to me is that, if I change the variable cathy to something else, like cath, or even cat, then the script will finish gracefully. Why "cathy" is not liked?!! Some of you may have recognized that the code is derived from a sample code in Swaroop's "A byte of python". My python is of version 2.5.1, on Ubuntu. From arkanes at gmail.com Thu Mar 13 11:47:18 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 13 Mar 2008 10:47:18 -0500 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <-161202553970035867@unknownmsgid> References: <-161202553970035867@unknownmsgid> Message-ID: <4866bea60803130847u38d69060mf8a46d08e484d603@mail.gmail.com> On Thu, Mar 13, 2008 at 10:36 AM, Robert Rawlins wrote: > > > > > Hello Guys, > > > > I've got an awfully aggravating problem which is causing some substantial > hair loss this afternoon J I want to get your ideas on this. I am trying to > invoke a particular method in one of my classes, and I'm getting a runtime > error which is telling me the attribute does not exist. > > > > I'm calling the method from within __init__ yet it still seems to think it > doesn't exist. > > > > Code: > > > > # Define the RemoteDevice class. > > class remote_device: > > > > # I'm the class constructor method. > > def __init__(self, message_list=""): > > self.set_pending_list(message_list) > > > > def set_pending_list(self, pending_list): > > # Set the message list property. > > self.pending_list = message_list > > > > And the error message which I receive during the instantiation of the class: > > > > File: "/path/to/my/files/remote_device.py", line 22, in __init__ > > self.set_pending_list(message_list) > > AttributeError: remote_device instance has no attribute 'set_pending_list' > > > > Does anyone have the slightest idea why this might be happening? I can see > that the code DOES have that method in it, I also know that I don't get any > compile time errors so that should be fine. I know it mentions line 22 in > the error, but I've chopped out a load of non relevant code for the sake of > posting here. > > > > Perhaps I'm missing something really simple, but it's got my head spinning. > Create a copy of your source file, confirm that it shows the problem, and start chopping out lines until all that is left is what you pasted here. See if it still shows the problem. If it does, and if you haven't found the problem yet, post again, attaching (not pasting inline) your chopped down file. From ivan.illarionov at gmail.com Mon Mar 17 16:46:54 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 17 Mar 2008 13:46:54 -0700 (PDT) Subject: struct unpack References: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> Message-ID: <953cab77-f601-4e18-a177-b50f7f066efa@e6g2000prf.googlegroups.com> On Mar 17, 11:00 pm, brnstrmrs wrote: > If I run: > > testValue = '\x02\x00' > junk = struct.unpack('h', testValue) > > Everything works but If I run > > testValue = raw_input("Enter Binary Code..:") inputting at the > console '\x02\x00' > junk = struct.unpack('h', testValue) > > It errors out with > Traceback (most recent call last): > File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in > junk = struct.unpack('h', testValue) > File "struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 2 > > any ideas? You may need to use eval, because raw_input() does not understand '\'- prefixed characters. >>> testValue = eval('"%s"' % raw_input("Enter Binary Code..: ")) Enter Binary Code..: \x02\x00 >>> junk, = struct.unpack('h', testValue) >>> print junk 2 From gagsl-py2 at yahoo.com.ar Wed Mar 26 19:02:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 20:02:57 -0300 Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 18:01:31 -0300, George Sakkis escribi?: > On Mar 26, 3:41 pm, Tim Henderson wrote: > >> I am using mysql, and sqlite is not appropriate for my situation since >> some of the databases and tables I access are being accessed by other >> applications which are already written and live. I am not using the >> SQLAlchemy or SQLObject, because I didn't want too (although in the >> future I may consider using them). > > I'd strongly second looking into SQLAlchemy; from what you wrote, I > suspect sooner or later you'll end up creating (to paraphrase > Greenspun) an ad hoc, informally-specified, bug-ridden, slow > implementation of half of SQLAlchemy. You beat me to say that, but using SQLObject instead. Moreover, the OP is looking for the PersistentDict and PersistentList classes that ZODB uses. I'm not sure that triggering a database write for each and every modified attribute is a good thing; I'd use a "dirty" flag instead (ZODB uses _p_changed) and write all modifications at the end. Since not all methods modify the object contents, using a metaclass to flag all of them isn't a good idea either. I'd use a decorator; after all, they're not so many methods; if you inherit from DictMixin you only have to write __getitem__, __setitem__, __delitem__ and keys(), and of those, only __setitem__ and __delitem__ modify the object. -- Gabriel Genellina From kla at us.de Mon Mar 24 16:11:45 2008 From: kla at us.de (klaus) Date: 24 Mar 2008 20:11:45 GMT Subject: beginners question about return value of re.split References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> <47e3d9ff$0$17341$e4fe514c@dreader19.news.xs4all.nl> <84dedb7d-d726-4acf-84fc-2a8f28277d0d@s12g2000prg.googlegroups.com> Message-ID: <47e80b01$0$22546$e4fe514c@dreader13.news.xs4all.nl> On Fri, 21 Mar 2008 13:34:27 -0700, John Machin wrote: > On Mar 22, 2:53 am, klaus wrote: >> On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote: >> >> <..........> >> >> Ok thank you ! >> >> I think I got a bit lost in all the possibilities python has to offer. > > IMHO you got more than a bit lost. You seem to have stumbled on a > possibly unintended side effect of re.split. > > What is your underlying goal? > > If you want merely to split on '-', use datum.split('-'). > > If you want to verify the split results as matching patterns (4 digits, > 2 digits, 2 digits), use something like this: > > | >>> import re > | >>> datum = '2008-03-14' > | >>> pattern = r'^(\d\d\d\d)-(\d\d)-(\d\d)\Z' You may notice two > differences between my pattern and yours ... > | >>> mobj = re.match(pattern, datum) | >>> mobj.groups() > | ('2008', '03', '14') > > But what are you going to do with the result? If the resemblance between > '2008-03-14' and a date is not accidental, you may wish to consider > going straight from a string to a datetime or date object, e.g. > > | >>> import datetime > | >>> dt = datetime.datetime.strptime(datum, '%Y-%m-%d') > | >>> dt > | datetime.datetime(2008, 3, 14, 0, 0) > | >>> d = > datetime.datetime.date(dt) > | >>> d > | datetime.date(2008, 3, 14) > > HTH, > John Ok, sorry for my late reply. I got caught up in a fight with easterbunnys over some extraordinary large, fruitty and fertile eggs. Some creatures take Easter just to serious and it is not even mating season ! Can you believe that ? :-) Anyway, the underlying goal was to verify user input and to split up the date so that I could easily convert it to another format. Among others, an url and for a database querry. And I have succeeded in that. Thank you again; for taking the time to explain - and to question. KL. From python.list at tim.thechases.com Tue Mar 4 11:00:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Mar 2008 10:00:06 -0600 Subject: for-else In-Reply-To: References: Message-ID: <47CD7206.2050203@tim.thechases.com> > For instance, if you have a (trivial) if...elif...else like this: > > if a == 0: > do_task_0() > elif a == 1: > do_task_1() > elif a == 2: > do_task_2() > else: > do_default_task() > > You could roll it up into a for...else statement like this: > > for i in range(3): > if a == i: > do_task[a]() important "break" missing here... > else: > do_default_task() or otherwise this code will do_task_i *and* do_default_task()... -tkc From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:49:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:49:41 -0200 Subject: Beginner's assignment question References: Message-ID: En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > Lorenzo Gatti wrote: >> On Mar 1, 3:39 pm, Schizoid Man wrote: >>> As in variable assignment, not homework assignment! :) >>> >>> I understand the first line but not the second of the following code: >>> >>> a, b = 0, 1 >>> a, b = b, a + b >>> >>> In the first line a is assigned 0 and b is assigned 1 simultaneously. >>> >>> However what is the sequence of operation in the second statement? I;m >>> confused due to the inter-dependence of the variables. >> >> The expressions of the right of the assignment operator are evaluated >> before assigning any new values, to the destinations on the left side >> of the assignment operator. >> So substitutig the old values of a and b the second assignment means >> >> a, b = 0, 0 + 1 >> >> Simplifying the Python Reference Manual ("6.3 Assignment Statements") >> a little : >> >> assignment_stmt ::= target_list "="+ expression_list >> >> An assignment statement evaluates the expression list (remember that >> this can be a single expression or a comma-separated list, the latter >> yielding a tuple) and assigns the single resulting object to each of >> the target lists, from left to right. >> >> [...] >> >> WARNING: Although the definition of assignment implies that overlaps >> between the left-hand side and the right-hand side are `safe' (for >> example "a, b = b, a" swaps two variables), overlaps within the >> collection of assigned-to variables are not safe! For instance, the >> following program prints "[0, 2]": >> >> x = [0, 1] >> i = 0 >> i, x[i] = 1, 2 >> print x >> >> Lorenzo Gatti > > Thank you for the explanation. I guess my question can be simplified as: > > First step: a, b = 0, 1 > No problem here as a and b are assigned values. > > Second step: a, b = b, a + b > > Now my question is does b become a + b after a becomes 1 or while a > stays at 0? > > As the assignment occurs simultaneously I suppose the answer is while a > stays at 0. Read the previous response carefully and you'll answer your question. The right hand side is EVALUATED in full before values are assignated to the left hand side. Evaluating b, a+b results in 1, 1. The, those values are assigned to a, b. -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 20 11:43:57 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 10:43:57 -0500 Subject: Can I run a python program from within emacs? In-Reply-To: References: Message-ID: Well, I suppose you could. But why bother with learing emacs when you'll have to switch to vim later anyway? 2008/3/20, jmDesktop : > > Hi, I'm trying to learn Python. I using Aquamac an emac > implementation with mac os x. I have a program. If I go to the > command prompt and type pythong myprog.py, it works. Can the program > be run from within the editor or is that not how development is done? > I ask because I was using Visual Studio with C# and, if you're > familiar, you just hit run and it works. On Python do I use the > editor for editing only and then run the program from the command > line? Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waltbrad at hotmail.com Mon Mar 17 13:50:01 2008 From: waltbrad at hotmail.com (waltbrad) Date: Mon, 17 Mar 2008 10:50:01 -0700 (PDT) Subject: questions about named pipe objects... Message-ID: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> I'm proceeding slowly though the Lutz book "Programming Python". I'm in the section on named pipes. The script he uses has two functions: one for the child the other for the parent. You start the parent then the child: python pipefifo.py #starts the parent file /tmp/pipefifo # shows that the file is a named pipe python pipefifo.py -child # starts a child process and writes to the pipe. This is done between two command windows - the first for the parent and the second for the child. Now, the child's write loop is infinite. So, I used Ctrl-C and stopped the process. But the parent's read loop is also infinite and without and exception, so it keeps reading from the pipe after the child is shutdown even though the lines are empty. So, I had to shut that down also. I then wanted to start the child process first and see what happened when I ran the parent. Well that works but the reads come out in random order. This got me wondering about the pipe file itself. So I tried to open it with leafpad and found that I couldn't. I guess these files can only be opened by processes? Okay. But exactly when does the system brand this file as a named pipe and how? From watine at cines.fr Mon Mar 17 09:19:10 2008 From: watine at cines.fr (Benjamin Watine) Date: Mon, 17 Mar 2008 14:19:10 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: <47DE6FCE.9010506@cines.fr> bryanjugglercryptographer at yahoo.com a ?crit : > I wrote: >> And here's a thread example, based on Benjamin's code: > [...] > > Doh! Race condition. Make that: > > import subprocess > import thread > import Queue > > def readtoq(pipe, q): > q.put(pipe.read()) > > cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, > stdout=subprocess.PIPE) > > myVar = str(range(1000000)) # arbitrary test data. > > q = Queue.Queue() > thread.start_new_thread(readtoq, (cat.stdout, q)) > cat.stdin.write(myVar) > cat.stdin.close() > cat.wait() > myNewVar = q.get() > > assert myNewVar == myVar > print len(myNewVar), "bytes piped around." > > > -- > --Bryan > Great, it works, thank you Bryan ! Could you explain me why you use a queue instead of a simple array for getting the piped var ? Regards, Ben From jorge.vargas at gmail.com Sun Mar 9 12:32:27 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sun, 9 Mar 2008 10:32:27 -0600 Subject: Returning values from function to Python shell/IPython In-Reply-To: References: Message-ID: <32822fe60803090932q33f88f27qddbc1d62d5f1a7ff@mail.gmail.com> On Sun, Mar 9, 2008 at 9:56 AM, Karlo Lozovina <_karlo_ at mosor.net> wrote: > Hi all! > > I have a runTest() function inside my module, which sets up and initializes > lots of objects and performs some basic tests on them. Usually (from > IPython) I just write `run my_module.py`, and then `runTest()`. But > sometimes I would like to manually twiddle with objects runTest creates. Is > there any way I can "return" all those objects local to runTest(), and have > them available in IPython (or ordinary Python shell)? well after all it's a function so the only ways you can get things out of it are: - return a dict with all the objects - use global (very messy) - use a decorator to do either of the above. on the other hand have you consider using a proper test package? instead of inspecting the objects manually from the shell you could make it all automatic. with assert statements. you could use the std. python testing modules http://docs.python.org/lib/development.html or something less verbosed like nose http://code.google.com/p/python-nose/ > > Thanks... > > > P.S. > I know I can do it from a: > > if __name__ == '__main__': > # lots of object initialization... > > and then have all those objects available in the interpreter. > > -- > Karlo Lozovina -- Mosor > -- > http://mail.python.org/mailman/listinfo/python-list > From don.raikes at oracle.com Sun Mar 9 20:41:31 2008 From: don.raikes at oracle.com (Donald Raikes) Date: Sun, 9 Mar 2008 17:41:31 -0700 Subject: python-2.5.2 src rpm Message-ID: <20080309174131250.00000001416@draikes-pc> Hello, I am trying to install python 2.5.2 onto enterprise linux, and would like to start with a source rpm package so that I can build the package locally and make sure I have all necessary dependencies. I have been unable to locate a source rpm package for python 2.5.2 or any version of 2.5 for that matter. Any pointers would be appreciated. Donald Raikes | Accessibility Specialist Phone: +1 602 824 6213 | Fax: +1 602 824 6213 | Mobile: +1 520 271 7608 Oracle JDeveloper QA "Please consider your environmental responsibility before printing this e-mail" From viji.jp1 at gmail.com Wed Mar 12 05:58:30 2008 From: viji.jp1 at gmail.com (viji.jp1 at gmail.com) Date: Wed, 12 Mar 2008 02:58:30 -0700 (PDT) Subject: YOU LIKE THIS Message-ID: <90de7976-e437-4c73-9e1d-d646a0bc6190@s13g2000prd.googlegroups.com> YOU LIKE THIS ***************************************** http://hollywood154.blogspot.com/ ***************************************** From http Sat Mar 22 15:22:42 2008 From: http (Paul Rubin) Date: 22 Mar 2008 12:22:42 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <7xmyoqlg1p.fsf@ruckus.brouhaha.com> jmDesktop writes: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? It's at least pretty good. It's not ideal, but nothing ever is. What I mean is: it's the best suggestion I can think of, but I can't say with confidence that there's nothing better out there. Alternatives would probably be more esoteric languages like Logo. Chris Okasaki (of functional data structures fame) has an interesting blog post about why indentation-based structuring is a big help for teaching: http://okasaki.blogspot.com/2008/02/in-praise-of-mandatory-indentation-for.html From python.list at tim.thechases.com Wed Mar 19 06:07:50 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 05:07:50 -0500 Subject: Search the command history - Python Shell In-Reply-To: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> References: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> Message-ID: <47E0E5F6.2010701@tim.thechases.com> > Are there any simillar key combination in Python Shell like Linux Ctrl+R > (reverse-i-search) to search the command history? It must depend on how your version of Python was built...mine here on my Linux box has exactly that functionality. I press ^R and start typing, and the line comes up from my typed history. bash$ python2.4 Python 2.4.4 (#2, Jan 3 2008, 13:36:28) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 42 (reverse-i-search)`a': a = 42 bash$ python2.5 Python 2.5.2a0 (r251:54863, Feb 10 2008, 01:31:28) [GCC 4.2.3 (Debian 4.2.3-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 42 (reverse-i-search)`a': a = 42 -tkc From clodoaldo.pinto at gmail.com Fri Mar 28 09:54:49 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Fri, 28 Mar 2008 06:54:49 -0700 (PDT) Subject: base64.urlsafe_b64encode and the equal character Message-ID: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> I'm using a md5 hash encoded with base64.urlsafe_b64encode as a parameter of a URL used to confirm a registration in a site. It has been working great. The url is like this: http://example.com/ce?i=878&h=kTfWSUaby5sBu9bIfoR87Q== Now i need to match that URL in a certain text and i realized that urlsafe_b64encode uses the "=" character so i can't just use \w{24} to match the parameter. What i need to know is where can an equal char appear in a urlsafe_b64encoded string?: a)only at end; b)both at the end and at the begginig; c)anywhere in the string; A sure answer will make my regexp safer. In another point, does the "=" char make it urlunsafe? I guess not because i believe it would only be unsafe if the equal appeared like in "&var=" and since there are no "&" in the string than there is no problem right? Or wrong? Regards, Clodoaldo Pinto Neto From ivan.illarionov at gmail.com Mon Mar 17 19:27:18 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 17 Mar 2008 16:27:18 -0700 (PDT) Subject: Interesting math problem References: Message-ID: On Mar 18, 1:24 am, "BJ?rn Lindqvist" wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > step = distance / float(parts) > intstep = int(step) > floatstep = step - intstep > > steps = [] > acc = 0.0 > for i in range(parts): > acc += floatstep > step = intstep > if acc > 0.999: > step += 1 > acc -= 1.0 > steps.append(step) > return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L > > -- > mvh Bj?rn Integer-only version: def make_slope(distance, parts): intstep, err = divmod(distance, parts) steps = [] acc = 0 for i in range(parts): acc += err step = intstep if acc >= parts: step += 1 acc -= parts steps.append(step) return steps # Test code distance = 130 parts = 50 L = make_slope(distance, parts) assert(len(L) == parts) assert(sum(L) == distance) print L From castironpi at gmail.com Wed Mar 26 21:00:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 18:00:53 -0700 (PDT) Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: <2e61203f-da5e-4721-a029-554787d6694d@13g2000hsb.googlegroups.com> On Mar 26, 6:02?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 18:01:31 -0300, George Sakkis ? > escribi?: > > > On Mar 26, 3:41 pm, Tim Henderson wrote: > > >> I am using mysql, and sqlite is not appropriate for my situation since > >> some of the databases and tables I access are being accessed by other > >> applications which are already written and live. I am not using the > >> SQLAlchemy or SQLObject, because I didn't want too (although in the > >> future I may consider using them). > > > I'd strongly second looking into SQLAlchemy; from what you wrote, I > > suspect sooner or later you'll end up creating (to paraphrase > > Greenspun) an ad hoc, informally-specified, bug-ridden, slow > > implementation of half of SQLAlchemy. > > You beat me to say that, but using SQLObject instead. > Moreover, the OP is looking for the PersistentDict and PersistentList ? > classes that ZODB uses. > I'm not sure that triggering a database write for each and every modified ? > attribute is a good thing; I'd use a "dirty" flag instead (ZODB uses ? > _p_changed) and write all modifications at the end. > Since not all methods modify the object contents, using a metaclass to ? > flag all of them isn't a good idea either. I'd use a decorator; after all, ? > they're not so many methods; if you inherit from DictMixin you only have ? > to write __getitem__, __setitem__, __delitem__ and keys(), and of those, ? > only __setitem__ and __delitem__ modify the object. That depends on technology: in volatile memory, persistence is a long- term commitment. In static-state memory, it's a norm. Say you've got a flash drive on the bus, you could store the objects themselves: the Python module would have to allocate from the ROM, reobtain later. Don't store the interpreter on the ROM, and trade-off feature sets for expiration date. But standards expire? From graemeglass at gmail.com Mon Mar 31 08:30:00 2008 From: graemeglass at gmail.com (Graeme Glass) Date: Mon, 31 Mar 2008 05:30:00 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <4d1d7d83-8155-4c1a-a807-0b5c951e1192@d21g2000prf.googlegroups.com> On Mar 27, 11:01 am, Peter Otten <__pete... at web.de> wrote: > Grimsqueaker wrote: > > That seems to give me the items in the list back in an iterator. Am I > > using it incorrectly? > > With Dan's functions in cartesian.py you can do the following: > > >>> from cartesian import * > >>> def count(digits): > > ... args = [] > ... while 1: > ... args.append(digits) > ... for n in string_cartesian_product(*args): > ... yield n > ...>>> from itertools import islice > >>> print " ".join(islice(count("abc"), 30)) > > a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab > bac bba bbb bbc bca bcb bcc > > Peter Here is a cool solution we came up with during a little interactive session at our local meet up. (http://www.python.org.za/pugs/cape-town/cape-town) s = 'abcdef' ["".join([s[j] for j in range(len(s)) if x & (1 << j)]) for x in range(1,2**len(s)) ] http://groups.google.com/group/ctpug/browse_thread/thread/986aab83f9782f6c Regards, Graeme From ptmcg at austin.rr.com Tue Mar 25 11:27:12 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 Mar 2008 08:27:12 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: This code is SO *CUTE*! I wish there was a font with little hearts to dot the 'i's with, then it would be PERFECT! From sjmachin at lexicon.net Sun Mar 30 03:31:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Mar 2008 00:31:57 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> Message-ID: <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> On Mar 30, 3:58 pm, hdante wrote: > On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" > > wrote: > > Hello, > > > I am having trouble writing the code to read a binary string. I would > > like to extract the values for use in a calculation. > > > Any help would be great. > > I'm too lazy to debug your binary string, but I suggest that you > completely throw away the binary file and restart with a database or > structured text. See, for example: > > http://pyyaml.org/wiki/PyYAML > > If you have some legacy binary file that you need to process, try > creating a C program that freads the binary file and printfs a text > equivalent. > ... and that couldn't be done faster and better in Python?? From martin at marcher.name Thu Mar 6 09:26:27 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 6 Mar 2008 15:26:27 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <5fa6c12e0803060626l5624a4a7qd374d8e741eb900f@mail.gmail.com> On Thu, Mar 6, 2008 at 2:06 PM, Guillermo wrote: > >What makes you say you "need" to know this ? Except for a couple corner > >cases, you usually don't need to care about this. If you told us more > >about the actual problem (instead of asking about what you think is the > >solution), we might be of more help... > > I want to iterate recursively a dictionary whose elements might be > strings or nested tuples or dictionaries and then convert values to a > tagged format according to some rules. just do so, if it's not a dict you can always catch the exception, then handle tuples (or the exception), then strings which should work always (of course also error handling here according to your needs) > I'm just designing the algorithm, but I think Python dictionaries can > hold any kind of sequence? python dicts can hold any kind of object (as a value). What you can't do is have a list as the key, but that is easily circumvented by using a tuple (or any other immutable type). hth martin -- http://tumblr.marcher.name https://twitter.com/MartinMarcher http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From castironpi at gmail.com Sat Mar 8 12:44:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 09:44:26 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> Message-ID: On Mar 8, 9:31?am, Grant Edwards wrote: > On 2008-03-08, dave_mikes... at fastmail.fm wrote: > > >> The function name also doesn't explain anything. How was the stuff got? > >> Was it paid for, or stolen, or picked up on consignment, or what? Compare > >> the above line with: > > >> x = get_stuff(store) ?# Steal stuff from the store. > > >> or > > >> x = get_stuff(store) ?# Pickup the stuff from the store for disposal. > >> # The amount paid by the store is stored in global variable "pay_received" > >> # and the name of the employee authorizing the pickup is stored in the > >> # global "authorized_by". > > > Shouldn't get_stuff's comment be with its definition? > > Probably, but better that comment shouldn't be anywhere. > > get_stuff() should be > > ?1) renamed, as you state below. > > ?2) written such that it's obvious from reading the source code > ? ? that the amount paid is stored in the global variable > ? ? pay_received and that the name of the employee authorizing > ? ? the pickup is stored in the global authorized by. > > But, it's not really fare picking on an example like that... > > > And just rename the function to something more meaningful, > > like purchase_goods(store), or whatever. > >> But even if you were right that the comment was unnecessary, > >> you have missed my point that even single sentences can be > >> grammatically bogus and the writer could learn a lot from > >> Strunk and White or equivalent. > > That's true. ?I don't know how many times I've seen a single > sentence comment that was just plain vague and ambiguous. And > most of the time they're just plain wrong as well because the > code had been changed but nobody changed the comment (possibly > because they couldn't understand what the comment was trying to > say). There are bad comments and bad variable names. fcrg= dothingthatgoesplace( qkjwvm ). # that thing I talked about # in last Tuesday's code for searching qkjwvm and returning its attribute. Does one side of this hold that there are no -good- comments? From asr-1 at comcast.net Wed Mar 12 21:50:57 2008 From: asr-1 at comcast.net (Andrew Rekdal) Date: Wed, 12 Mar 2008 20:50:57 -0500 Subject: Big file References: <13th14pe0hhsie1@corp.supernews.com> Message-ID: <9LKdnQpmfOvhFUXanZ2dnUVZ_gKdnZ2d@comcast.com> Well, I can see how this could get real messy but within defining a GUI there are many elements and so the block of elements such as a wx.notebook for instance I would hope I could place all the code for this in another file and somehow include it into place. This way I can work on layered panels and such in a fresh document rather than travesing through tons of widgets and sizers. Thanks for your replies -- -- Andrew "Steven D'Aprano" wrote in message news:13th14pe0hhsie1 at corp.supernews.com... > On Wed, 12 Mar 2008 19:42:44 -0500, Andrew Rekdal wrote: > >> I am working in the class constructor defining elements of an >> application. The problem is the file is getting unmanageble and I am >> wanting to extend the contructor __init__ to another file. >> >> Is it possible to import directly into the contructor the contents of >> another module file? >> >> If so how would this be done? > > > Here's the way you do what you literally asked for: > > class MyClass(object): > def __init__(self, *args): > # Warning: completely untested > execfile('myfile.py') # may need extra arguments? > > but you almost certainly don't want to do that. A better way is by > importing modules, the same as you would for anything else: > > class MyClass(object): > def __init__(self, *args): > from AnotherModule import constructor > constructor(self, *args) > > > But frankly if you find yourself needing to do this because your file is > "too big" and is unmanageable, I think you are in desperate need of > refactoring your code to make if more manageable. Pushing vast amounts of > random code out into other files just increases the complexity: not only > do you have vast amounts of code, but you have large numbers of files to > manage as well. > > > > > -- > Steven > > > From steve at holdenweb.com Mon Mar 3 23:16:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Mar 2008 23:16:12 -0500 Subject: pySQLite Insert speed In-Reply-To: <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> Message-ID: mmm wrote: >>> Hence (if I understand python convention), this can be >>> solved by adding >>> sqlx= copy.copy(sqlx) >>> before the looping. And in tests adding this step saved about 5-10% in >>> time. >> Now this I don;t really understand at all. What's the point of trying to >> replace sqlx with a copy of itself? Perhaps if you explained what you >> hope this will achieve I could comment more intelligently. >> > > I am/was attempting to convert > > sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) > > to code that did to need to be re-evaluated. i.e. to insert the > dtable and ph values as if they were hard coded. > > copy.copy --> A shallow copy constructs a new compound object and > then (to the extent possible) inserts references into it to the > objects found in the original. Unfortunately you weren't dealing with a compound object object here, so all you are doing is creating a copy of the string you've just created and replacing the original with it. Copy.copy() is meant for creating (say) lists, tuples and dicts where the elements are references to the same objects that the elements of the original structure referred to. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From danb_83 at yahoo.com Wed Mar 12 21:55:08 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 12 Mar 2008 18:55:08 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> On Mar 12, 6:52 pm, Alan Isaac wrote: > Paul Rubin wrote: > > The cmp option should not be removed. However, requiring > > it to be specified as a keyword parameter instead of just > > passed as an unlabelled arg is fine. > > Sure; I would have no problem with that. > > But that is not what is happening. > > As for Carl's suggestion to use ``key``: > this is already possible when it is convenient, > but it is not always convenient. (Even aside > from memory considerations.) def cmp_key(cmp_fn): class CmpWrapper(object): def __init__(self, obj): self.obj = obj def __cmp__(self, other): return cmp_fn(self.obj, other.obj) return CmpWrapper From danb_83 at yahoo.com Thu Mar 27 02:29:29 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 26 Mar 2008 23:29:29 -0700 (PDT) Subject: counting using variable length string as base References: Message-ID: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> On Mar 27, 1:15 am, Grimsqueaker wrote: > Hi, I'm fairly new to Python and to this list. I have a problem that > is driving me insane, sorry if it seems simple to everyone, I've been > fighting with it for a while. :)) > > I want to take a variable length string and use it as a base for > counting, eg. given the string 'abc' the sequence would be: > > a > b > c > aa > ba > ca > ab > bb > cb > ... > ccc > > Basically I want to find every possible order of every combination. > Its easy if you know how many characters there will be in your string > (use nested for loops), but I am stuck with the variable length > string. I think I have to use a generator but I'm not sure exactly > how. > > Can anyone give me a pointer in the right direction? def cartesian_product(*args): """Iterates over the Cartesian product of args[0], args[1], ...""" if not args: return elif len(args) == 1: for item in args[0]: yield (item,) else: for item in args[0]: for item2 in cartesian_product(*args[1:]): yield (item,) + item2 def string_cartesian_product(*args): return (''.join(combo) for combo in cartesian_product(*args)) From bernard.chhun at gmail.com Thu Mar 13 14:46:46 2008 From: bernard.chhun at gmail.com (Bernard) Date: Thu, 13 Mar 2008 11:46:46 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Message-ID: <49c0e986-36af-4e5d-92b8-bcc7105c7ecf@h11g2000prf.googlegroups.com> d'oh! On 12 mar, 07:58, John Machin wrote: > On Mar 12, 10:29 pm, Bernard wrote: > > > > > Hey Larry, > > > that one is fairly easy: > > > >>> from array import array > > >>> array('i', [1, 2, 3, 4, 5, 1, 2]) > > >>> def count(x, arr): > > > ? ? ? ? cpt = 0 # declare a counter variable > > ? ? ? ? for el in arr: # for each element in the array > > ? ? ? ? ? ? ? ? if el == x: # when it is equal to the 'x' value > > ? ? ? ? ? ? ? ? ? ? ? ? cpt+=1 # increment the counter variable by one > > ? ? ? ? return cpt # return the counter after the loop>>> count(1,a) > > > 2 > > Hey Bernard, you have just laboriously reinvented the count method: > > > > >>> from array import array > >>> a = array('i', [1, 2, 3, 4, 5, 1, 2]) > >>> a.count(1) > 2 > > which Larry has already said doesn't do the job -- the job is to > create a histogram!! From mensanator at aol.com Wed Mar 5 15:34:28 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Mar 2008 12:34:28 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <51f4bce3-8561-4149-9b3b-e436bbee8ee7@u69g2000hse.googlegroups.com> Message-ID: <1bcbee35-c5bf-4a6d-b68a-1eed87ffcf8d@p25g2000hsf.googlegroups.com> On Mar 5, 9:29?am, Nanjundi wrote: > On Mar 4, 3:13 pm, Mensanator wrote: > > > On Mar 4, 12:32 pm, Nanjundi wrote: > > > > Does seeding ( random.seed ) random with time fix this? It should. > > > I suppose that depends on how long it takes factorint() to > > process a number. If the seed is reset before the next clock > > tick, you will get the same random numbers as the previous > > iteration. > > Alright, then make it constant and don't worry about the clock tick. Reseeding with a constant always sets the sequence to the same starting point. >>> for i in xrange(10): > > ... ? f1 = random.choice(f) > ... ? print f1, > ... ? f2 = random.choice(f) > ... ? print f2, > ... ? C = f1*f2 > ... ? ff = None > ... ? ff = sympy.factorint(C) > ... ? print ff > ... ? random.seed(i) > ... > 5573 5171 [(5171, 1), (5573, 1)] > 8537 7673 [(7673, 1), (8537, 1)] > 2063 8573 [(2063, 1), (8573, 1)] > 9551 9473 [(9473, 1), (9551, 1)] > 2909 5659 [(2909, 1), (5659, 1)] > 2897 1789 [(1789, 1), (2897, 1)] > 6361 7541 [(6361, 1), (7541, 1)] > 8017 8293 [(8017, 1), (8293, 1)] > 3671 2207 [(2207, 1), (3671, 1)] > 2803 9629 [(2803, 1), (9629, 1)] > > > Frankly, I don't understand why factorint() reseeds at all. > > Read the doc: > * ? ?The rho algorithm is a Monte Carlo method whose outcome can be > affected by changing the random seed value. ?* But that doesn't give it the right to mess with the state of the random number generator _I'm_ using. Had I actually known what was happening, I could have saved the state of my random number generator s=random.getstate() and then restored it after calling factorint(), random.setstate(s). import sympy # with RK's patch removed import time import random f = [i for i in sympy.primerange(1000,10000)] for i in xrange(10): f1 = random.choice(f) print f1, f2 = random.choice(f) print f2, C = f1*f2 ff = None rs = random.getstate() ff = sympy.factorint(C) random.setstate(rs) print ff 5669 3863 [(3863, 1), (5669, 1)] 1973 5431 [(1973, 1), (5431, 1)] 7577 6089 [(6089, 1), (7577, 1)] 8761 4957 [(4957, 1), (8761, 1)] 4153 2719 [(2719, 1), (4153, 1)] 4999 5669 [(4999, 1), (5669, 1)] 8863 5417 [(5417, 1), (8863, 1)] 7151 7951 [(7151, 1), (7951, 1)] 7867 9887 [(7867, 1), (9887, 1)] 9283 5227 [(5227, 1), (9283, 1)] Of course, this is new as of Python 2.4, so if factorint() tried to save & restore state, sympy wouldn't work on Python 2.3 or earlier. If I'm reading RK's patch correctly, he doesn't reseed the random number generator, he creates a new random object that maintains it's own state that can be freely seeded to any value without disturbing the state of my random number generator. > > > Doesn't Random automatically initialize the seed? > > Doesn't constantly reseeding degrade the performance of the > > random number generator? With Robert Kern's patch, the reseeding > > is no longer a constant, fixing the immediate symptom. > > Does it matter? I was wrong. It is a constant, just not 1234. If that's what factorint() needs, fine. As long as it maintains a seperate state than the one I'm using. > The factorint reseeds using a constant seed (1234). Not now it doesn't: @@ -92,8 +92,8 @@ def pollard_pm1(n, B=10, seed=1234): """ from math import log - random.seed(seed + B) - a = random.randint(2, n-1) + prng = random.Random(seed + B) + a = prng.randint(2, n-1) for p in sieve.primerange(2, B): e = int(log(B, p)) a = pow(a, p**e, n) > > > But what if _I_ wanted to make a repeatable sequence for test > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > on every call? > > Repeatable sequence? save it and reuse! As part of my resolution to tone down my attitude, I won't even reply to that. > Think about "What if"s doesn't get any work done. ? > > -N From iwanttobeabadger at googlemail.com Mon Mar 24 21:58:49 2008 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Tue, 25 Mar 2008 01:58:49 +0000 Subject: Calling a shared library using C types In-Reply-To: References: Message-ID: On 25/03/2008, Gabriel Genellina wrote: > > En Mon, 24 Mar 2008 19:56:08 -0300, Nathan Harmston > escribi?: > > > > import ctypes > > t = ctypes.CDLL('./Simulation.so') > > this works fine, I have a simple function I ve put in for testing which > > just > > returns the integer 4. However when I try to access this function it > > doesnt > > work > > t.test() > > File "", line 1, in > > File > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > line 325, in __getattr__ > > func = self.__getitem__(name) > > File > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > line 330, in __getitem__ > > func = self._FuncPtr((name_or_ordinal, self)) > > AttributeError: dlsym(0x81e6b0, test): symbol not found > > > Looks like the symbol isn't public - probably if you try loading the > library with a C program it won't find it either. How is the function > declared in the source? > Try listing all public symbols with: nm -D Simulation.so Thanks for the quick reply: Running nm lists test as 00001760 T _test in the source its declared as: int test(){ return 4; } Sorry, this is the first time I'm making my own shared library and using ctypes, so being a little slow. Thanks again Nathan > Im hoping python-list is ok for questions regarding ctypes :S > > > It's not off topic, although there is a specific list for ctypes-related > questions. But hijacking a thread to post a completely different question > is not good netiquette. > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwolffedu at gmail.com Sat Mar 15 21:12:21 2008 From: mwolffedu at gmail.com (lampshade) Date: Sat, 15 Mar 2008 18:12:21 -0700 (PDT) Subject: os.path.isdir question Message-ID: Hello, I'm having some problems with os.path.isdir I think it is something simple that I'm overlooking. #!/usr/bin/python import os my_path = os.path.expanduser("~/pictures/") print my_path results = os.listdir(my_path) for a_result in results: if os.path.isdir(str(my_path) + str(a_result)): results.remove(a_result) for x in results: print x The problem is, that the directories are never removed. Can anyone point out what I'm missing that is causing the bug? Is there a better way of doing this? Thanks, From fakeaddress at nowhere.org Thu Mar 13 12:31:09 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 13 Mar 2008 16:31:09 GMT Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: Benjamin Watine wrote: > And if somebody need it : to get the stdout in a var (myNewVar), not in > the shell : > > cat = subprocess.Popen('cat', shell = True, stdin = subprocess.PIPE, > stdout=subprocess.PIPE) > cat.stdin.write(myVar) > cat.stdin.close() > cat.wait() > myNewVar = cat.stdout.read() > > Is it correct ? No, not really. It is prone to deadlock. The external program might work by iteratively reading a little input and writing a little output, as 'cat' almost surely does. If the size of myVar exceeds the buffer space in cat and the pipes, you get stuck. Your Python program can block at "cat.stdin.write(myVar)", waiting for cat to read from its input pipe, while cat blocks at a write to its output stream, waiting for you to start reading and freeing up buffer space. Pipe loops are tricky business. Popular solutions are to make either the input or output stream a disk file, or to create another thread (or process) to be an active reader or writer. -- --Bryan From grflanagan at gmail.com Tue Mar 25 11:24:19 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 25 Mar 2008 08:24:19 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: On Mar 25, 1:34 pm, Tzury Bar Yochay wrote: > > Rather than use Foo.bar(), use this syntax to call methods of the > > super class: > > > super(ParentClass, self).method() > > Hi Jeff, > here is the nw version which cause an error > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = super(Foo, self).getid() > b = self.id > return '%d.%d' % (a,b) > > FooSon().getid() > > Traceback (most recent call last): > File "a.py", line 19, in > FooSon().getid() > File "a.py", line 14, in getid > a = super(Foo, self).getid() > AttributeError: 'super' object has no attribute 'getid' Use the child class when calling super: -------------------------------------- class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = super(FooSon, self).getid() b = self.id return '%d.%d' % (a,b) print FooSon().getid() -------------------------------------- G. From jeff at schwabcenter.com Mon Mar 17 21:29:17 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 18:29:17 -0700 Subject: About reading Python code In-Reply-To: <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> Message-ID: sturlamolden wrote: > On 17 Mar, 04:54, WaterWalk wrote: > >> So I'm curious how to read code effectively. I agree that python code >> is clear, but when it becomes long, reading it can still be a hard >> work. > > First, I recommend that you write readable code! Don't use Python as > if you're entering the obfuscated C contest. Er, don't use anything other than C if you're entering an obfuscated C contest, or anything other Perl for an obfuscated Perl contest, etc. Do use Python if you're entering an obfuscated Python contest. Found online: [#[#[#[#[#[#[#[#[# By TaroOgawa #]#]#]#]#]#]#]#]#] globals() .update({ "______": lambda x: globals() .update(( dict([[x] *2])))}), ______((( "Just"))) ,______(( "another" )),______ ("Python" ),______( "Hacker") ];print ( " ".join( [(Just),( (another) ),(Python ),Hacker] ));______ > Two particularly important points: > > * If you find yourself thinking this module is too long, that's > probably what it is. Half a page of code per module is fine. Two pages > of code per module can be too much. > > * Comments are always helpful to the reader. If only 'twere so. *Good* comments are always helpful. Please do not comment every method with "this is a method" or the like. One of the things that often makes newb code stand out is that the programmer couldn't tell the things that needed to be commented from the places where comments just got in the way. > Second, I recommend getting a good IDE. E.g. pick one of: > > * Microsoft Visual Studio (commercial) > * Eclipse with PyDev and CDT (free) > * SPE (free) > * ActiveState Komodo IDE (commercial) * Vim on Linux. (No desire here to debate the meaning of IDE, but with Vim or Emacs on any Unix-like platform, the whole system effectively is the IDE.) From jeff_barish at earthlink.net Mon Mar 10 12:05:19 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Mon, 10 Mar 2008 10:05:19 -0600 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: egbert wrote: > The idea of the if-else is: > . ?depending on some condition either do this or do something else, > . ?don't do them both. Indubitably, this statement is correct for other programming languages. I was initially surprised by loop-else when learning Python because I approached these constructs from the perspective of other programming languages I knew, as you are doing. Before rejecting the Python constructs, I asked myself whether the application of a different idea resulted in a consistent, sensible interpretation. The key is to ask not whether the Python constructs fit a particular idea of if-else and loop-else, but whether a reasonable idea exists within which the Python constructs make sense. For me and others in this thread, it does. Different keywords would, no doubt, result in constructs that fit other ideas better, but personally I am content with the current solution. -- Jeffrey Barish From robert.kern at gmail.com Tue Mar 18 18:16:30 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 Mar 2008 17:16:30 -0500 Subject: Any fancy grep utility replacements out there? In-Reply-To: References: Message-ID: samslists at gmail.com wrote: > So I need to recursively grep a bunch of gzipped files. This can't be > easily done with grep, rgrep or zgrep. (I'm sure given the right > pipeline including using the find command it could be done....but > seems like a hassle). > > So I figured I'd find a fancy next generation grep tool. Thirty > minutes of searching later I find a bunch in Perl, and even one in > Ruby. But I can't find anything that interesting or up to date for > Python. Does anyone know of something? I have a grep-like utility I call "grin". I wrote it mostly to recursively grep SVN source trees while ignoring the garbage under the .svn/ directories and more or less do exactly what I need most frequently without configuration. It could easily be extended to open gzip files with GzipFile. https://svn.enthought.com/svn/sandbox/grin/trunk/ Let me know if you have any requests. -- 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 tjreedy at udel.edu Sat Mar 8 20:46:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2008 20:46:29 -0500 Subject: Green's Function References: <501978.67770.qm@web53602.mail.re2.yahoo.com> Message-ID: "olusina eric" wrote in message news:501978.67770.qm at web53602.mail.re2.yahoo.com... | I am new to Python and trying to solve the Hamiltonian of a linear chair of atoms using green's function. | Does anyone know any pre-existing library functions and literature that could be helpful? Did you try searching for "Python Green's function"? From sturlamolden at yahoo.no Thu Mar 20 18:26:23 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 15:26:23 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> Message-ID: <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> On 20 Mar, 19:09, Craig wrote: > The following is the C++ prototype for one of the functions: > short FAR PASCAL VmxOpen(BSTR *Filespec, > LPSHORT lpLocatorSize, > LPSHORT lpOmode, > LPHANDLE lphwmcb, > BSTR *Password); import ctypes import comtypes LPBSTR = ctypes.POINTER(comtypes.BSTR) HANDLE = ctypes.POINTER(ctypes.POINTER(ctypes.c_long)) LPHANDLE = ctypes.POINTER(HANDLE) LPSHORT = ctypes.POINTER(ctypes.c_short) VmxOpen = ctypes.windll.vbis5032.VmxOpen VmxOpen.restype = c_short VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] Filespec = comtypes.BSTR('blahblahblah') LocatorSize = ctypes.c_short(256) Omode = ctypes.c_short(1) hwmcb = HANDLE() Password = comtypes.BSTR('blahblahblah') res = WmxOpen( byref(Filespec), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(Password) ) or if that fails: pFilespec = ctypes.pointer(Filespec) pLocatorSize = ctypes.pointer(LocatorSize) pOmode = ctypes.pointer(Omode) phwmcb = ctypes.pointer(hwmcb) pPassword = ctypes.pointer(Password) res = WmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) From sajmikins at gmail.com Wed Mar 12 20:59:33 2008 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 12 Mar 2008 17:59:33 -0700 (PDT) Subject: Big file References: Message-ID: <0842cf80-eeaf-4bf1-85dc-c90e5ff27c43@i29g2000prf.googlegroups.com> On Mar 12, 5:42 pm, "Andrew Rekdal" wrote: > I am working in the class constructor defining elements of an application. The problem is the file is getting unmanageble and I am wanting to extend the contructor __init__ to another file. > > Is it possible to import directly into the contructor the contents of another module file? > > If so how would this be done? > > Thanks -- andrew First, you should consider breaking your __init__() method into smaller pieces (methods) and calling those from within __init__(). That said, you can add attributes to an instance by means of its __dict__ dict attribute: |>> class foo: |>> def __init__(self): |>> self.__dict__['hi'] = ['An object'] |>> print self.__dict__ |>> |>> f = foo() {'hi': ['An object']} |>> f.hi ['An object'] You might try: |>> exec 'from sys import *' in f.__dict__ Now everything in sys appears in f: |>> f.copyright 'Copyright (c) 2001-2006 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n \nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.' HTH, ~Simon From tim.tadh at gmail.com Wed Mar 26 15:10:29 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Wed, 26 Mar 2008 12:10:29 -0700 (PDT) Subject: A question on decorators Message-ID: Hello I am writing an application that has a mysql back end and I have this idea to simplify my life when accessing the database. The idea is to wrap the all the functions dealing with a particular row in a particular in a particular table inside a class. So if you have a table that looks like this: id str1 str2 pickled_data1 pickled_data2 0 woeif aposf (bin) (bin) 1 ofime powe (bin) (bin) ... n oiew opiwe (bin) (bin) you can access this table like this t = Table(id) #to load a pre-entered row t2 = Table(id, str1, str2, data1, data2) #to create a new row when you change a an attribute of the class like this... t.str1 = 'new value' it automatically updates the database backend. I have what I just described working. However I want an easier way to deal with my pickled_data. Right now I am pickling dictionaries and list types. Now there is one problem with this, let me demonstrate t.data.update({'new key':'new value'}) print t.data {... 'new key':'new value' ...} which makes it appear that the database has been updated as well, but in fact it hasn't to update the database with this scheme you actually have to do this. t.data.update({'new key':'new value'}) t.data = t.data this is not ideal so I subclassed the built in dict type like this: class _my_dict(dict): def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) self.update_db() def __delitem__(self, key): if self.write_access: dict.__delitem__(self, key) self.update_db() def __setitem__(self, key, value): if self.write_access: dict.__setitem__(self, key, value) self.update_db() def clear(self): if self.write_access: dict.clear(self) self.update_db() ... more methods which are simliar ... def update_db(self): if self.write_access: con = get_dbConnection() cur = con.cursor() table = self.experiment.TABLE row_index_name = self.row_index_name row_index = self.row_index column_name = self.column_name column_value = MySQLdb.escape_string(pickle.dumps(self)) q1 = '''UPDATE %(table)s SET %(column_name)s = '%(column_value)s' WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() cur.execute(q1) con.close() Now while this works, it is a lot of work. What I want to be able to do is something where I write one decorator function that automatically updates the database for me. So let us pretend I have this function. let: dec_update_db() be my decorator which updates the dictionary. to use this function it seems I would probably still have to subclass dict like this: class _my_dict2(dict): @dec_update_db def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) @dec_update_db def __delitem__(self, key): dict.__delitem__(self, key) @dec_update_db def __setitem__(self, key, value): dict.__setitem__(self, key, value) @dec_update_db def clear(self): dict.clear(self) ... and so on ... this is also not ideal. because I still have to apply the decorator to every function which changes the dictionary. What I really want is a way to have the decorator applied automatically every time a method in dict or a sub class is called. I feel like this must be possible. Has any one here done anything like this before? Thank you for reading my long post, I hope you understand what I am asking especially since the code in it is not very good. cheers Tim Henderson From dave_mikesell at fastmail.fm Sat Mar 8 16:38:21 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 13:38:21 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <7be573d9-d009-4ac9-8eb4-86c13d2d68c0@13g2000hsb.googlegroups.com> On Mar 8, 1:31 pm, Grant Edwards wrote: LOL. Thanks for the laughs. I share your frustration. From kkadrese at gmail.com Wed Mar 19 06:37:27 2008 From: kkadrese at gmail.com (kkadrese at gmail.com) Date: Wed, 19 Mar 2008 03:37:27 -0700 (PDT) Subject: lock access to serial port References: Message-ID: <78873650-1130-4be9-9ea7-3889036b2bbf@a23g2000hsc.googlegroups.com> not the goal setup but the way I tried it out - a webpage to send an sms to mobile phone. This is an php what calls a python script. A python script opens serial device, checks for gsm network, sends a message - on all the way I try to make sure that appropriate answers are received from the gsm device so that I know that all is going well (and if not - cancel it with error message). Testing it with sending an sms from two open webpages, I normally got that one message was sent and for the other I received "try once more, happened that and that". But I got also an inadmissible situation - the received sms contained also unwanted text. As far as I can realize how to deal with it is not allowing writing to the device for two processes simultaneously. Andra On 19 Marts, 11:00, taco wrote: > kkadr... at gmail.com wrote: > > hello group, > > > how to get ttyS0 serial port for exclusive access? I have a python > > script that uses this device with AT commands. I need that two > > instances can call simultaneosuly this python script but only one of > > them gets the device. I tried fcntl.flock, it was just ignored, put > > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not > > know what are appropriate arguments), googled half a day for various > > phrases, error messages etc....without success. > > > please help, > > > Andra > > not sure if I understand you well, but how about a server application which > accepts 2 clients which can send messages which are output on the serial > device? The serial device access protected with a mutex while receiving > messages done in 2 threads or something. > taco From paul at boddie.org.uk Thu Mar 13 20:34:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 13 Mar 2008 17:34:23 -0700 (PDT) Subject: EuroPython 2008: A Call for Theme and Talk Suggestions Message-ID: <57801aa4-ff53-41c3-9ffd-105d69304c70@s13g2000prd.googlegroups.com> This year, the EuroPython conference will take up residence for the second time in Vilnius, Lithuania with the main programme of talks and events taking place on Monday 7th, Tuesday 8th and Wednesday 9th July, and with sprints continuing after the main programme until and including Saturday 12th July. More information can be found on the updated EuroPython site, which can be found in the usual place: http://www.europython.org/ Last year, the conference focused on agile development, but also promoted many of the familiar categories: business, education, games, language and libraries, science, social skills and Web development. Of course, topics such as Web development remain as popular as ever, but we also saw strong contributions in other areas such as robotics and database systems. With this in mind, we would like to get feedback from anyone thinking of coming to EuroPython 2008 about the kind of topics they would like to see covered at the conference. Perhaps the arrival of Python 3.0 makes you wonder about how, when or even whether you might make the transition from Python 2.x or earlier to the new release series. Perhaps you want to know more about how Python is used in the "real world" and how others have deployed large systems written in Python. Or maybe you are fascinated with the potential for using Python on mobile devices. We welcome your thoughts and ideas, either on this list/group (just reply to this message!), on the EuroPython mailing list... http://mail.python.org/mailman/listinfo/europython ...or by becoming a contributor on the EuroPython Web site: http://www.europython.org/community/Participants Take a look at this page for some ideas that have already been proposed: http://www.europython.org/community/Talk_Suggestions And feel free to suggest specific talk ideas or even other kinds of activities which might enhance the conference experience, perhaps borrowed from conferences such as PyCon. Since EuroPython is a community conference, volunteers are welcome in many different areas: http://www.europython.org/community/Volunteers Why not step up and improve the EuroPython experience for yourself and for everyone else? Make EuroPython yours: get involved now! From jeff at schwabcenter.com Sat Mar 22 14:39:05 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 11:39:05 -0700 Subject: List question In-Reply-To: <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> Message-ID: Zentrader wrote: > On Mar 22, 10:07 am, Arnaud Delobelle wrote: >> On Mar 22, 4:38 pm, Zentrader wrote: >> >>>> if ('one', 'two') are in f: ... >>> "are" gives me an error in Python 2.5 with a "from future import *" >>> statement included. What version and platform are you running. Also, >>> the docs don't mention it.http://docs.python.org/ref/keywords.html >> That's because you have to do: >> >> from bearophile import musings >> >> HTH >> >> -- >> Arnaud > > Thanks. I am admittedly naive and don't have any type of guard up > when on this group for people who think that type of comment makes > them intelligent/funny. No one meant to laugh at you. Your naivete was not obvious. FWIW, a sense of humor is a valuable possession in most Python-related conversations. From castironpi at gmail.com Thu Mar 13 19:13:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 16:13:50 -0700 (PDT) Subject: newbie question structure of function References: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> Message-ID: <37088f9c-e68e-483e-92a3-e730411a79bf@2g2000hsn.googlegroups.com> Just some FYI options. > ? ? if not matchfilename: May return positive if you someday return an object that holds a 'not' value. > ? ? resultname=""" That starts a string literal. > if (matchdistance < threshold): Parentheses optional. > ? ? return (matchdistance,resultname) Parentheses optional there too. "return matchdistance," returns a 'one-tuple'. From gygulyas at gmail.com Wed Mar 19 22:04:27 2008 From: gygulyas at gmail.com (Gyula) Date: Wed, 19 Mar 2008 19:04:27 -0700 (PDT) Subject: ADO error - large data set References: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> <9qgEj.4646$6H.3740@newssvr22.news.prodigy.net> Message-ID: <7ce74b92-8018-46b7-a1ce-bde2cb1186b9@s19g2000prg.googlegroups.com> Ok. After several tries, I think I found out why it breaks and it has nothing to do with the number of records... Here is the code/ see notes below: ######################### code starts here # First import wincom32 client from win32com.client import * # Create the ADO Connection object via COM oConn = Dispatch(r'ADODB.Connection') # Now set the connection properties via the ConnectionString oConn.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" + \ "DATA SOURCE=C:/Documents and Settings/user/Desktop/PythonWS/data/ anydata.mdb;" # Now open the connection oConn.Open() # create a recordset rs = Dispatch(r'ADODB.Recordset') rs.Open('SELECT TOP 300 * FROM input;', oConn, constants.adOpenStatic, constants.adLockOptimistic) rs.MoveFirst() counter = 1 while not rs.EOF: print counter # do nothing, just cycle through counter += 1 rs.MoveNext() # cleanup rs.Close() rs = None oConn.Close() oConn = None print 'Done!' ##################### code ends here the line where it breaks: rs.Open('SELECT TOP 300 * FROM input;', oConn, constants.adOpenStatic, constants.adLockOptimistic) 'input' is supposed to be the table name, but it breaks in Python when you want to open the recordset. I need to use: rs.Open('SELECT TOP 300 * FROM [input];', oConn, constants.adOpenStatic, constants.adLockOptimistic) as input is an SQL keyword...arrrrrgh. Gyula On Mar 19, 5:17 pm, Gyula wrote: > Thanks! I will give it a try. It seems though that I get stuck on > rs.Open that makes no sense. I was wondering about pagesize or other > registry settings that might cause this? Will try to track down any > bad data first... > gg > > On Mar 19, 3:27 pm, "dsavitsk" wrote: > > > Is it possible there is some bad data in the larger db? This is asinine, but > > maybe write a small script that adds some data, then opens and closes the > > db, then repeats this. If this is a size issue, then you can at least narrow > > it down to where the size limit is? And, if it isn't you should be able to > > figure that out, too. Otherwise, play around with the locking and cursor > > options. > > > -d > > > "Gyula" wrote in message > > >news:475c155d-fe16-472f-a4f8-363f6db339eb at d21g2000prf.googlegroups.com... > > > > Hi there, > > > > I have been running Python to tap into an MS Access 2003 database > > > using ADO (PythonWin+COM). Everything works great creating recordsets > > > etc. when I open a table with a small number of records. However, when > > > I try to run the same Python code with a large table (>100,000) I get: > > > > Traceback (most recent call last): > > > File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework > > > \scriptutils.py", line 310, in RunScript > > > exec codeObject in __main__.__dict__ > > > File "C:\Documents and Settings\user\Desktop\PythonWS\scripts > > > \readmsaccess.py", line 43, in > > > rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) > > > File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- > > > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open > > > , ActiveConnection, CursorType, LockType, Options) > > > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > > > 5003251, -2147467259), None) > > > > The small and large table structures are identical, all I do is change > > > the tblname from input1000 (1000 records) to input (>100000 records). > > > I use optimistic locking and keyset cursor..nothing out of the > > > ordinary? > > > > Any ideas? ADO 2.8 is what I am using. > > > > Thanks a lot! > > > GG ' From tjreedy at udel.edu Sat Mar 22 21:13:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Mar 2008 21:13:40 -0400 Subject: Problem with complex numbers References: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> <47E58836.70202@cheimes.de> Message-ID: "Christian Heimes" wrote in message news:47E58836.70202 at cheimes.de... | Well, the file is in the Demo folder. It's just a demo how to implement a naive complex type in Python. | Why do you think the power of a complex to a complex is not defined? I suspect because the naive implementation raise TypeError for that case. From Sebastien.Boisgerault at gmail.com Mon Mar 3 13:40:54 2008 From: Sebastien.Boisgerault at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Boisg=E9rault?=) Date: Mon, 3 Mar 2008 10:40:54 -0800 (PST) Subject: News from Jython world Message-ID: Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a key Jython developer and is specifically hired to work full time on Jython, a version of the Python interpreter that runs on top of the JVM and provides full access to Java libraries. After a period where the development had slowed, Jython was recently getting seriously back on track. Now it's getting even better ! Don't wait too much ... Jython is very useful RIGHT NOW if you live in the Java Universe. More details at: - http://www.infoworld.com/article/08/03/03/hirings-python_1.html - http://fwierzbicki.blogspot.com/2008/02/jythons-future-looking-sunny.html Cheers, SB From hdante at gmail.com Wed Mar 12 21:37:39 2008 From: hdante at gmail.com (hdante) Date: Wed, 12 Mar 2008 18:37:39 -0700 (PDT) Subject: Big file References: Message-ID: On Mar 12, 9:42 pm, "Andrew Rekdal" wrote: > I am working in the class constructor defining elements of an application. The problem is the file is getting unmanageble and I am wanting to extend the contructor __init__ to another file. > > Is it possible to import directly into the contructor the contents of another module file? > > If so how would this be done? > > Thanks -- andrew class BigObject: import my_module def __init__(self): self.my_module.do_this() --------------------------------------- class BigObject(MyUtils): def __init__(self): self.things_from_utils() From shaq.koby at gmail.com Sat Mar 15 15:52:35 2008 From: shaq.koby at gmail.com (shaq.koby at gmail.com) Date: Sat, 15 Mar 2008 12:52:35 -0700 (PDT) Subject: Cannot install SOAPpy Message-ID: <1a00b6b8-fb18-4189-8572-946e22f1774c@e39g2000hsf.googlegroups.com> I installed SOAPpy on my server with Python 2.5. But now everytime I exit, I get the following error: Exception exceptions.AttributeError: '_shutdown' in ignored Here is the command line output: mhagen at sebastian:~$ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import SOAPpy >>> exit Use exit() or Ctrl-D (i.e. EOF) to exit >>> Exception exceptions.AttributeError: '_shutdown' in ignored From castironpi at gmail.com Fri Mar 21 09:14:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 06:14:42 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> Message-ID: <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> On Mar 20, 9:28?am, "Jerry Hill" wrote: > On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano > > wrote: > > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > > > ?> suppose > > ?> origsz=(400,300) > > ?> i want to divide the origsize by 2.5 so i can resize to (160,120) > > > ?> scale=2.5 > > ?> how can i get the newsz? > > ?> obviously origsz/2.5 won't work ?.. > > > ?newsz = (origsz[0]/scale, origsz[1]/scale) > > That works fine for a 2-tuple, but might get unwieldy for larger > tuples, or if you don't know the length until runtime. ?A more general > solution might use a generator expression, like this: > > newsz = tuple(x/scale for x in origsz) You want to perform a uniform call on the elements of a collection. "Diagram A" appends 0 to every item of a list. >>> y= [ [] for k in range( 10 ) ] >>> def x( fun, *ar, **kw ): ... def post( *xr, **xw ): ... return fun( *(xr+ ar), **kw ) ... return post ... >>> x( list.append, 0 )( y[0] ) >>> y [[0], [], [], [], [], [], [], [], [], []] >>> x( list.pop, 0 )( y[0] ) 0 >>> y [[], [], [], [], [], [], [], [], [], []] >>> list( map( x( list.append, 0 ), y ) ) [None, None, None, None, None, None, None, None, None, None] >>> y [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]] If the elements are immutable, >>> y= [ () for k in range( 10 ) ] >>> list( map( x( tuple.__add__, ( 0, ) ), y ) ) [(0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,)] you get your new list from map. Here it is with integer elements: >>> y= ( 300, 400 ) >>> tuple( map( x( int.__add__, 1, ), y ) ) (301, 401) --You could spell the call like this: latemap( y, int.__add__, 1 ) With mul: >>> tuple( map( x( int.__mul__, 2, ), y ) ) (600, 800) It's like partial, but the argument addition is commuted. The key is that 'y' is going in the first slot, as 'self'. It's not clear that argument addition commution applies (matches, is correct, generalizes with right meaning): you just want the first parameter to come from a separate call. Other uses cases of the generalizer might not align. + a fraction on 'x'. Floats get harder, since you're looking at composition. >>> tuple( map( compose( float, x( float.__mul__, 1/ 2.5 ) ), y ) ) (120.0, 160.0) # (160, 120) +1 compose. def compose( *f ): def post( *ar, **kw ): if len( f )> 1: return f[0]( compose( *f[1:] )( *ar, **kw ) ) return f[0]( *ar, **kw ) return post From dblubaugh at belcan.com Mon Mar 10 10:19:25 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 10 Mar 2008 10:19:25 -0400 Subject: Python To C Module Generator Stand-Alone Executable Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3802AF98F0@AWMAIL04.belcan.com> Does anybody know if the Python To C Module Generator is of any value? Has anyone found or developed a means to convert python source code into c source code, where an algorithm that has been developed in python, can now be converted to C in order to develop a stand alone application? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjourne at gmail.com Wed Mar 19 18:35:31 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 19 Mar 2008 22:35:31 +0000 Subject: removing all instances of a certain value from a list In-Reply-To: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Message-ID: <740c3aec0803191535t57690621rd377512db5d60a83@mail.gmail.com> On Wed, Mar 19, 2008 at 10:28 PM, Lee Sander wrote: > Hi, > I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are > many missing vlaues which are represented as None. I would like to > remove all such instances in one go. > There is a remove function but it removes only the first instance, is > there a delete/remove all function? > thanks If it is ok to copy the list instead of mutating it, use a list comprehension: >>> L = [-1.3, 1.22, 9.2, None, 2.3] >>> [x for x in L if x is not None] [-1.3, 1.22, 9.1999999999999993, 2.2999999999999998] -- mvh Bj?rn From nick at craig-wood.com Mon Mar 10 10:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 10 Mar 2008 09:30:03 -0500 Subject: Writing Memory to File References: Message-ID: Stefan Wagner wrote: > I'm trying to do some memory analyzing stuff, i wrote me a small .c so > far to dump the memory to a file for later analysis, > the analyzing part itself is python code. > I wonder if any of you has an idea how to dump the whole memory in > Linux/Windows from python ? > Using the .c for this somehow doesn't look right and comfy ;-) The whole memory of what? Under linux : If you want the whole physical memory of the system then you can dump /dev/mem You can dump the memory of an individual process using the ptrace interface. Both those things will require the relevant rights and neither is quite as easy as you might hope for! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From yoz at home.havin.us Thu Mar 13 14:56:27 2008 From: yoz at home.havin.us (yoz) Date: Thu, 13 Mar 2008 18:56:27 GMT Subject: List mutation method gotcha - How well known? In-Reply-To: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> References: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> Message-ID: Dustan wrote: > On Mar 13, 2:36 am, "Hendrik van Rooyen" wrote: >> Hi, >> >> I am surprised that it took me so long to bloody my nose on this one. >> >> It must be well known - and I would like to find out how well known. >> >> So here is a CLOSED BOOK multiple choice question - no RTFM, >> no playing at the interactive prompt: >> >> Given the following three lines of code at the interactive prompt: >> >> foo = [1,2,3,4] >> x = foo.append(5) >> print x >> >> What will be the output (choose one): >> >> 1) [1,2,3,4] >> 2) [1,2,3,4,5] >> 3) That famous picture of Albert Einstein sticking out his tongue >> 4) Nothing - no output >> 5) None of the above > > 5. This will cause a hidden feature of python and the OS, known as the 'python easter egg', to activate - erasing all data on the hard disk and then reporting how many bytes of data are left. Usually "None" ;-} - This really is a 'gotcha'.... (Aren't you sorry you cheated and typed this in !!) So the answer is 5 ? From dave_mikesell at fastmail.fm Sun Mar 2 19:23:10 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sun, 2 Mar 2008 16:23:10 -0800 (PST) Subject: Run Python app at startup References: Message-ID: On Mar 2, 3:37 pm, "SMALLp" wrote: > Hy. > I create simple application. Yust an windows and "compile" it with > py2exe. I add registry value > reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v > MyApp /t REG_SZ /d C:\myapp.exe /f' > > And it wont start. When i use console instead od window in py2exe i get > console opend but it closes. > > Program: > > import os > import wx > > app = wx.App() > frame = wx.Frame(None, -1, "MyFrame") > frame.Show() > > app.MainLoop() > > > Then in commang prompt: > > python.exe setup.py py2exe > > > from distutils.core import setup > import py2exe > > setup(console=['prog.py']) > Don't you have to include the wxPython code somehow, perhaps on the command line when building the exe? From castironpi at gmail.com Sun Mar 9 17:04:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:04:01 -0700 (PDT) Subject: parralel downloads References: <50047985-ed16-46cb-a933-8afddac6a056@y77g2000hsy.googlegroups.com> Message-ID: <8a2e744e-6ecf-4bb5-8abc-8e0627c81da4@13g2000hsb.googlegroups.com> > > > >> ?my problem is that I would like to download several files at the time. > > > >> ?As I have not much experience in programming, could you point me the > > > >> ?easier ways to do this in python ? > > > Thank you both for your help. Threads are working for me. However, a > > new problem for me is that the url I want to download are in an xml > > file (I want to download podcasts), and is not the same as the file > > downloaded: > > >http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2... > > > will be redirected to download: > > >http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 > > > is there a way, knowing the first url to get the second at runtime in > > my script ? > > Found it: geturl() does the job That's for normalizing schemes. I believe you subclass FancyURLopener and override the read method. From duncan.booth at invalid.invalid Tue Mar 18 05:47:56 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2008 09:47:56 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> <47de9f6c$0$2657$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: > >> For the answer I actually want each asterisk substitutes for exactly one >> character. > > Played around a bit and found that one: > > Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) > [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = 1 >>>> b = 1//1 >>>> if a is b: print('yes!') > ... >>>> b > 1 >>>> type(b) > I've had a look to see why this happens: long division (and in Python 3 all integers are longs) allocates a new long to hold the result of the division so it will never use one of the preallocated 'small int' values. That makes sense so far as it goes, but I'm slightly suprised if it isn't worth an extra check somewhere for numerator fitting in a machine int and shortcutting the long division. From tew24 at spam.ac.uk Thu Mar 6 06:33:55 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 06 Mar 2008 11:33:55 +0000 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: Tom Wright wrote: > If someone has worked their way through this maze before and has an > answer, I'd be keen to hear it. Hmm, an answer of sorts: Inkscape's Windows build comes with MSVCR70.dll and MSVCR71.dll (but not MSVCP71.dll). As it's a big and high-profile project distributed under GPL2, I think they must've done their homework. Let's hope I'm ok in slightly different circumstances: distributing MSVCP71.dll as well, and under GPL3. -- I'm at CAMbridge, not SPAMbridge From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 07:15:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 12:15:17 -0000 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> Message-ID: <13t2celd4h80i7f@corp.supernews.com> On Thu, 06 Mar 2008 06:30:41 -0800, Carl Banks wrote: > On Mar 5, 8:44 pm, Steven D'Aprano cybersource.com.au> wrote: >> But what about classes? Are they singletons? Obviously classes aren't >> Singleton classes, that is, given an arbitrary class C you can create >> multiple instances of C. But what about class objects themselves? I've >> found a few odd references to "classes are singletons", but nothing in >> the language reference. > > > Probably because "singleton" is the wrong word. A singleton means there > is one instance of a type; classes are instances of "type" which can > have many instances so classes are not singletons. Right. I knew there was something funny about using the term "singleton" to refer to classes, but I couldn't put my finger on it. [snip] > For that matter, try this: > >>>>import module >>>>c1 = module.Someclass >>>>module.Someclass = some_other_class() >>>>c2 = module.Someclass >>>>c1 is c2 That example is cheating because you rebind the *name* module.Someclass. Of course you get something different. But in any case, I'm satisfied now... the name singleton is inappropriate for modules and classes, although they are both singleton-like. I like Gabriel's term "named singleton" (from another thread). Thank you to everybody who answered. -- Steven From coolman.guron at gmail.com Sat Mar 8 05:27:12 2008 From: coolman.guron at gmail.com (coolman.guron at gmail.com) Date: Sat, 8 Mar 2008 02:27:12 -0800 (PST) Subject: help on file storage for split multi part download References: Message-ID: <0c422a07-3c07-499f-87da-f82a6a81ed52@s37g2000prg.googlegroups.com> On Mar 7, 2:14 pm, "Gabriel Genellina" wrote: > En Fri, 07 Mar 2008 04:16:42 -0200, escribi?: > > > > > On Mar 7, 1:38 am, "Gabriel Genellina" wrote: > >> En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: > > >> > storage class which can write the file splits that are currently being > >> > downloaded to the disk. this is exactly what otherdownload > >> > accelerators do, i guess. > > >> Uh, unless I misundersand you, a standard file object is enough. First > >> create a file with the required size (open(...,'wb'), seek(n-1), > >> write(chr(0))). For each downloaded chunk you have to know its position > >> in > >> the file; then just seek() and write() it. > > > BUT the thing thats going in my mind is thread safety. i plan to start > > each part of the filedownloadin a different thread. and then when > > each thread had downloaded more than 100kb (or eof or boundary > > reached) write the buffer to the disk. can this be achieved using > > mutex ? i have never shared objects between threads. > > Use a different (single) thread to write the file; the others put write > requests on a Queue.queue object, and the writer just gets the requests > and processes them. > > > is there a way to write this without using threads at all ??? > > Using asyncore, and perhaps the Twisted framework. > > -- > Gabriel Genellina asyncore is basically a server thing right? From iteration.nth at gmail.com Thu Mar 20 00:34:44 2008 From: iteration.nth at gmail.com (iteration.nth at gmail.com) Date: Wed, 19 Mar 2008 21:34:44 -0700 (PDT) Subject: keeping state in an iterator object by rebinding next() References: Message-ID: <691a1267-0407-43e4-96d3-d58467af8614@59g2000hsb.googlegroups.com> On Mar 19, 3:36 pm, Wilbert Berendsen wrote: > Hi, > > i am writing a simple parser, that generates tokens. The parser needs to > maintain some state, because some parts of the file consist of different > tokens. I thought the object could simply remember its state by assigning > it's next() method to the method that is currently parsing. When the state > changes, the called method rebinds next() and the next token will be returned > by that function. Here's an example, proving that this indeed works. > > >>> class A: > > ... def a(self): > ... self.next = self.b > ... return 1 > ... def b(self): > ... self.next = self.a > ... return 2 > ... def __iter__(self): > ... return self > ...>>> a=A() > >>> a.a() > 1 > >>> a.next() > 2 > >>> a.next() > 1 > >>> j=0 > >>> for i in a: > > ... j += 1 > ... if j > 10: break # prevent from running endlessly > ... print i > ... > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 > > > > my question is: is this legal Python? An iterator could save the next() method > object, and in that case it could stop working.... It works now, because > apparently the for- construct resolves 'next' each time for the object before > calling it. > > The other solution would be just jumping to the correct method from within the > next() method. But that gives an extra call... > > Met vriendelijke groet, > Wilbert Berendsen > > --http://www.wilbertberendsen.nl/ > "You must be the change you wish to see in the world." > -- Mahatma Gandi """" "You must be the change you wish to see in the world." -- Mahatma Gandi """" JFYI: Mahatma Gandhi (NOT Gandi). From castironpi at gmail.com Sat Mar 29 19:37:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 16:37:05 -0700 (PDT) Subject: Can anyone help me? Message-ID: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> I have this. 'pycaster.py' works. 'spherecollide.py' doesn't. C:\Documents and Settings\usr\My Documents\inbin\SphereCollide> \programs\python2 5\python SphereCollide.py Traceback (most recent call last): File "SphereCollide.py", line 39, in dlWorld, dlSpheres, dlFakeshadow = Objects.main() File "C:\Documents and Settings\usr\My Documents\inbin\SphereCollide \Objects.p y", line 11, in main GL_RGBA, GL_UNSIGNED_BYTE, Data ) File "C:\programs\Python25\Lib\site-packages\OpenGL\wrapper.py", line 1624, in __call__ return self.finalise()( *args, **named ) File "C:\programs\Python25\Lib\site-packages\OpenGL\wrapper.py", line 924, in wrapperCall raise err OpenGL.error.GLError: GLError( err = 1281, description = 'invalid value', baseOperation = glTexImage2D, pyArgs = [ GL_TEXTURE_2D, 0, GL_RGBA, 200, 200, 0, GL_RGBA, GL_UNSIGNED_BYTE, '\x80\x80\x80\xff\x80\x80\x80\xff\x80... ], cArgs = [ GL_TEXTURE_2D, 0, GL_RGBA, 200, 200, 0, GL_RGBA, GL_UNSIGNED_BYTE, '\x80\x80\x80\xff\x80\x80\x80\xff\x80... ], cArguments = ( GL_TEXTURE_2D, 0, GL_RGBA, 200, 200, 0, GL_RGBA, GL_UNSIGNED_BYTE, c_void_p(189956812), ) ) C:\Documents and Settings\usr\My Documents\inbin\SphereCollide> From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 09:06:17 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 15:06:17 +0100 Subject: Can one get "for x in y" to work for non builtin classes? Message-ID: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Hi I'm making a kind of ordered dictionary class. It is not exactly a dictionary, but it uses a list and dictionary to store the data. Something like: class dbase(list): '''Database class keeping track of the order and data''' def __init__(self): self.__data = {} self.__order = [] self.__uniq_id = 0 I'm just wondering if it is possible to get my class to work so that if one do: d=dbase() d.append("Data") d.append([1,2]) one can do like this to iterate over the data. for x in d: ... I'm looking at the list class but I don't quite understand from pydoc which __ __ methods I have to implement to get the above to work. Thanks in advance Preben From gagsl-py2 at yahoo.com.ar Tue Mar 25 22:02:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 23:02:08 -0300 Subject: My python interpreter became mad ! References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> <47E99C99.2060401@lexicon.net> <3a4a8f930803251814t3043f724v913bcc9e7aa7bf6e@mail.gmail.com> Message-ID: En Tue, 25 Mar 2008 22:14:39 -0300, Furkan Kuru escribi?: > I did not think he/she/anyone would ask the question in the main thread > without trying the interpreter a few times starting it from different > directories. Perhaps *you* would do that, but that is far beyond a newbie would do. Most newbies are lost enough to not even be able to ask the question in the first place. If the book doesn't tell anything about the directory, why should the starting directory be relevant? Why should I care not to use a reserved name to save my script? Where is that list of reserved names? -- Gabriel Genellina From gygulyas at gmail.com Wed Mar 19 12:14:49 2008 From: gygulyas at gmail.com (Gyula) Date: Wed, 19 Mar 2008 09:14:49 -0700 (PDT) Subject: ADO error - large data set Message-ID: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> Hi there, I have been running Python to tap into an MS Access 2003 database using ADO (PythonWin+COM). Everything works great creating recordsets etc. when I open a table with a small number of records. However, when I try to run the same Python code with a large table (>100,000) I get: Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\user\Desktop\PythonWS\scripts \readmsaccess.py", line 43, in rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open , ActiveConnection, CursorType, LockType, Options) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 5003251, -2147467259), None) The small and large table structures are identical, all I do is change the tblname from input1000 (1000 records) to input (>100000 records). I use optimistic locking and keyset cursor..nothing out of the ordinary? Any ideas? ADO 2.8 is what I am using. Thanks a lot! GG From ccomb at free.fr Sun Mar 23 21:40:16 2008 From: ccomb at free.fr (Christophe Combelles) Date: Mon, 24 Mar 2008 02:40:16 +0100 Subject: PyCon FR - =?UTF-8?B?Sm91cm7DqWVzIFB5dGhvbg==?= Message-ID: <47E70680.8000709@free.fr> PyCon FR will take place in Paris, France, 17-18 May 2008. The French Python Association (AFPY) is organizing this event called "Journ?es Python" for the second time. We expect most talks to be in french, but any proposal in english is also greatly welcome! You may submit your idea of talks and presentations now, either here if you speak french: http://fr.pycon.org/actualites/appel-a-propositions/ , or here if you don't : pycon -at- afpy.org Topics: We're expecting talks about anything related to the Python programming language, including: * the language and its libraries * the web technologies * Python in scientific computing * game programming * development environnement setup * agile programmnig and tests The expected audience will span on any level, from the beginner to the expert. Thus, your talk may fit even to beginners and will be welcome. Other formats: As well as regular talks, we will host tutorials about Python programming for beginners, and we may include 15-minutes lightning talks on any topic you want to talk about (e.g.: a project you're working on). You may submit debate topics for open discussions too. Important dates: * March, 7th : Call for papers * March, 30th : Paper submissions are closed * April 4th : Final schedule publication How to get involved? If you want to attend as a simple visitor, please register on this page to help us count the expected audience: * http://fr.pycon.org/inscription To submit a talk, tutorial, etc., please register with the link above, and fill the following form: * http://fr.pycon.org/contact/proposition-de-presentation For any information about the event, go to: * http://fr.pycon.org get in touch with the organization team via: pycon -at- afpy.org See you soon! --'AFPy Team. From gagsl-py2 at yahoo.com.ar Sun Mar 16 17:03:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 19:03:46 -0200 Subject: Weight Problem References: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> Message-ID: En Sat, 15 Mar 2008 18:57:36 -0200, Ravi Kumar escribi?: > An Interesting problem, > """ > A man has only 4 bricks of different weights, lies between 1-40KG, > Also, the total weights of Brick A, B, C, D (ie A+B+C+D) is 40KG. > The man uses that brick to calculate every possible weight > from 1 KG to 40 KG in his shop. (only whole numbers 1KG, 2KG etc, not > like > 2.3KG) > """ > > I thought it would really be good to solve it by python, and right now on > the mid-way solving using very dirty approach. > But I feel, using SETs with python in such would solve it better. > Can anyone come with good solution, and maybe solution showing usage of > Sets. This isn't specifically Python problem; some hints anyway: a) Any integer can be written as a base-3 number (anyone knows base-10 numbers, and you know base-2/binary numbers, I presume). x = a[n]*3**n + a[n-1]*3**(n-1) + ... + a[1]*3 + a[0] where all a[i] are either 0, 1 or 2 b) 2*3**n = (3-1)*3**n = 3**(n+1) - 3**n So you can replace every a[i]==2 in the a) expression with (-1), adding +1 to the coefficient to the left (why?). You end up with an expression involving only +1 and -1 coefficients (why?) c) You can compare, add and substract weights using an old two-plate balance. -- Gabriel Genellina From darcy at druid.net Tue Mar 25 10:21:13 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 25 Mar 2008 10:21:13 -0400 Subject: sendmail should throw an exception but does not In-Reply-To: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> Message-ID: <20080325102113.d8688b7f.darcy@druid.net> On Tue, 25 Mar 2008 06:39:57 -0700 (PDT) Clodoaldo wrote: > I need to know if an email was refused for whatever reason, it makes > no difference. > > The email is sent to an email address that does not exist in a foreign > domain. I can see in the postfix log that the email was sent and > bounced with the error code 550. That's the sendmail daemon, not your program. > The problem is that sendmail should throw an exception but it does > not. And the returned dictionary is empty as if the email was > accepted. > > d = smtpserver.sendmail(sender, recipient, m.as_string()) What this does is connect to your sendmail server and submit the email for sending. The server accepts the email and queues it up as asked. No error here. > I guess that the error code returned by the destination mail server is > not is not forwarded to the client by my mail server. It can't. By the time it finds out that there is a problem you have already closed the connection to the sendmail server. To do what you want you have to connect to the remote server yourself. This is a more complicated operation and there are still problems. First of all, your ISP may not allow you to connect to remote mail servers. Second, some [broken] mail servers will accept your email and only check and bounce after you have disconnected. I'm not sure what you are trying to do but you may want to consider using an Error-to: header that points to an email robot and manage bounces asynchronously. -- 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 hyena at gmail.com Sat Mar 15 20:14:19 2008 From: hyena at gmail.com (sun) Date: Sun, 16 Mar 2008 01:14:19 +0100 Subject: how can pulldom save to xml file? Message-ID: <9c6ce$47dc665c$5039443c$23160@news1.tudelft.nl> I have a large xml file parsed by pulldom. I did some editing on some node,change attributes and remove some child node, how do I save it back to this xml file or write a new xml file? The save method in minidom does not work for pulldom. Thanks From gagsl-py2 at yahoo.com.ar Thu Mar 27 15:55:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 16:55:09 -0300 Subject: How to take snap shot of the of project screen in Python References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 15:24:05 -0300, Praveena Boppudi (c) escribi?: > Can anyone help me out? What is "the project screen"? Do you want your development session using any IDE? Your running program? What platform? OS? Console or graphical application? Why using Python? -- Gabriel Genellina From grflanagan at gmail.com Thu Mar 20 07:09:51 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Thu, 20 Mar 2008 04:09:51 -0700 (PDT) Subject: Script Request... References: <64ccfbF2bbfckU1@mid.uni-berlin.de> Message-ID: <147cf9cb-f5c6-44fc-99cf-d846d04068ca@h11g2000prf.googlegroups.com> On Mar 19, 10:29 pm, some one wrote: > Thanks Diez, I found some docs and examples on urllib2. Now how do i > search the string I get from urllib2, lets say I put it in "myURL", How > do I search for only Numbers and ".'s" in the "#.#.#.#" pattern. That > is all I am interested in with all the data retrieved. Just the IP > Address from amongst a bunch of data that I have no use of currently. > > I would I write a pattern matching function to extract only the IP > address from "myURL"? > See the subsection titled 'Matching An IP Address', here: http://www.oreilly.com/catalog/regex/chapter/ch04.html Gerard > > > Show us your concrete efforts, and we will suggest improvements. > > > Diez From mcphail_colin at hotmail.com Wed Mar 12 14:43:32 2008 From: mcphail_colin at hotmail.com (CMcP) Date: 12 Mar 2008 18:43:32 GMT Subject: [pysqlite] [ANN] pysqlite and APSW projects moved References: <47D42EED.8070107@ghaering.de> Message-ID: In article Gerhard H?ring wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > Gerhard H?ring wrote: >> [...] APSW >> ==== >> >> web: http://oss.itsystementwicklung.de/trac/apsw/ >> scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ > That should have been > http://oss.itsystementwicklung.de/svn/apsw/apsw/ > - -- Gerhard > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX > V7sH3uAskDDNBuxYG34vExI= > =IXOx > -----END PGP SIGNATURE----- Hi, I'm getting a 404 Not Found trying to get to the APSW web page: Not Found The requested URL /svn/apsw/apsw/ was not found on this server. Apache/2.2.4 (Ubuntu) DAV/2 PHP/5.2.3-1ubuntu6.3 mod_ssl/2.2.4 OpenSSL/0.9.8e mod_wsgi/1.3 Python/2.5.1 Server at oss.itsystementwicklung.de Port 80 Regards, --CMcP -- I'm trying a new usenet client for Mac, Nemo OS X. You can download it at http://www.malcom-mac.com/nemo -- Posted via a free Usenet account from http://www.teranews.com From godzillaismad at gmail.com Tue Mar 18 06:43:29 2008 From: godzillaismad at gmail.com (Godzilla) Date: Tue, 18 Mar 2008 03:43:29 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> Message-ID: <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> Thanks Roel. If there is a way to pass in the PRESERVE_PRECISION constant in the python time.clock library, that would be great. But I'm afraid it's not possible. I think I will change away from using time.clock() from now on... seems too edgy to me. Thank you for sharing your experience with me nonetheless. Cheers mate. From julius.welby at gmail.com Fri Mar 28 02:44:31 2008 From: julius.welby at gmail.com (jwelby) Date: Thu, 27 Mar 2008 23:44:31 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> Message-ID: On Mar 28, 5:38 am, ankitks.mi... at gmail.com wrote: > >>> dict = {'M':3, 'R':0, 'S':2} > >>> print dict > > {'S': 2, 'R': 0, 'M': 3} > > now if I wanted sorted values in list, i am not able to do this>>> print dict.values().sort() > > None > > it returns None instead of [0, 2, 3] The sort method works by sorting 'in place'. That means it doesn't return the sorted value, but just sorts the sequence. >>> t = {'M':3, 'R':0, 'S':2} >>> x = t.values() >>> x.sort() >>> x [0, 2, 3] or you can use sorted(), which does return the sorted sequence: >>> sorted(t.values()) [0, 2, 3] From waltbrad at hotmail.com Fri Mar 7 15:38:11 2008 From: waltbrad at hotmail.com (waltbrad) Date: Fri, 7 Mar 2008 12:38:11 -0800 (PST) Subject: I cannot evaluate this statement... Message-ID: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> The script comes from Mark Lutz's Programming Python. It is the second line of a script that will launch a python program on any platform. import os, sys pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' Okay, run on a win32 machine, pyfile evaluates to python.exe That makes sense. Because the first condition is true and 'python.exe' is true. So the next comparison is 'python.exe' or 'python' Well, python.exe is true. So that value is returned to pyfile. Now. Run this on linux. The first condition evaluates sys.platform[:3] == 'win' as false. So, the next comparison should be 'False' or 'python' -- This is because 'and' returns the first false value. But, again, on linux pyfile evaluates to python.exe Where am I going wrong. And when will this statment make pyfile evaluate to 'python' ? From sjmachin at lexicon.net Fri Mar 7 17:12:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 14:12:13 -0800 (PST) Subject: How to clear a list (3 ways). References: Message-ID: <8c4fb388-7788-4ed9-ae4d-33f16b92d920@u10g2000prn.googlegroups.com> On Mar 8, 1:49 am, "Gabriel Genellina" wrote: > En Fri, 07 Mar 2008 09:39:05 -0200, > escribi?: > > > Executive summary : What idiom do you use for resetting a list ? > > lst = |] # (1) > > lst[:] = [] # (2) > > del lst[:] # (3) > > (3) if I want to keep the same list else (1) "resetting a list" is vague and dubious terminology. (1) abandons a reference to some object (which MAY be a list) and binds the name "lst" to a new empty list. (3) providing that the referred-to object is of a type that supports assigning to slices, removes the contents. (2) effects the same as (3) -- it's just slower to type, compile and execute. I would rewrite the advice to the OP as: Use (3) if and only if you have a justifiable need (not "want") to keep the same list. Cheers, John From gowricp at gmail.com Wed Mar 19 02:01:46 2008 From: gowricp at gmail.com (Gowri) Date: Tue, 18 Mar 2008 23:01:46 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <4fd038fb-399a-40f8-a12b-6c6539574b58@n75g2000hsh.googlegroups.com> I actually have a weirder problem. The code I posted earlier prints garbage on Windows and python 2.5 and the perfect json data on RHEL python 2.3.4. I'm so confused and helpless. json.py doesn't seem to help either. It says raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all() Somebody please help! From blwatson at gmail.com Sat Mar 29 23:39:58 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Sat, 29 Mar 2008 20:39:58 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> Message-ID: <75c10b67-c971-4db4-be13-26cafd24e9d2@d4g2000prg.googlegroups.com> On Mar 29, 6:42?pm, "Gabriel Genellina" wrote: > En Sat, 29 Mar 2008 20:54:36 -0300, escribi?: > > > I tried to add the directory "//simplejson" to my sys.path > > in the interpreter, hoping that the call to import simplejson would > > work if the dir was there, even though simplejson.py did not exist is > > that dir, but the encoder, decoder, jsonfilter and scanner .py files > > were all there. > > > My problem is that the call "import simplejson" fails. ?How can I make > > that call work? > > simplejson is a package (a directory with an __init__.py), not a module; ? > don't look for simplejson.py > Its *parent* directory must be in sys.path for Python to find it. Try ? > copying the simplejson directory below site-packages (which should be ? > already in sys.path) > > -- > Gabriel Genellina Gabriel - First, thanks for the help. You have solved one problem but created a new one. Isn't that always how it works? So I copied over the dir, and now I get this error when trying to import simplejson: The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/Users/bwatson/.python-eggs/ simplejson-1.8.1-py2.5-macosx-10.3-fat.egg-tmp/simplejson/tmpJVSqa_. $extract' The Python egg cache directory is currently set to: /Users/bwatson/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. So I went looking for that egg...the following exists in my frameworks dir: simplejson-1.8.1-py2.5-macosx-10.3-fat.egg I hate eggs...I am stuck again. Any ideas? From msc at es.aau.dk Tue Mar 25 06:14:54 2008 From: msc at es.aau.dk (Martin Sand Christensen) Date: Tue, 25 Mar 2008 11:14:54 +0100 Subject: Code folder with Emacs References: <13u5li6kspler51@corp.supernews.com> Message-ID: >>>>> "Grant" == Grant Edwards writes: Grant> Has anybody figured out how to do code folding of Python source Grant> files in emacs? I use outline-minor-mode with the following home baked configuration: ;; Python stuff for outline mode. (defvar py-outline-regexp "^\\([ \t]*\\)\\(def\\|class\\|if\\|elif\\|else\\|while\\|for\\|try\\|except\\|with\\)" "This variable defines what constitutes a 'headline' to outline mode.") (defun py-outline-level () "Report outline level for Python outlining." (save-excursion (end-of-line) (let ((indentation (progn (re-search-backward py-outline-regexp) (match-string-no-properties 1)))) (if (and (> (length indentation) 0) (string= "\t" (substring indentation 0 1))) (length indentation) (/ (length indentation) py-indent-offset))))) (add-hook 'python-mode-hook '(lambda () (outline-minor-mode 1) (setq outline-regexp py-outline-regexp outline-level 'py-outline-level))) Martin From castironpi at gmail.com Wed Mar 5 16:52:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 13:52:38 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> Message-ID: <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> On Mar 5, 3:38?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: > > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: > >> castiro... at gmail.com schrieb: > > >> > I want to hash values to keys. ?How do the alternatives compare? > > >>http://catb.org/~esr/faqs/smart-questions.html > > > ... without extending the whole way to a full relational database? > > You didn't bother following the link and reading the advice, did you? If > you did, you haven't done a good job of following that advice. Well, obviously there's someone who's interested in computers and programming that has a question. Communication is not his forte, but effort, willingness, devotion, and dedication are. What should he do, and what should the others, who are gifted speakers? From steve at REMOVE-THIS-cybersource.com.au Tue Mar 25 18:55:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 25 Mar 2008 22:55:00 -0000 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> Message-ID: <13uj0m4qd1dit79@corp.supernews.com> On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: > As per your suggestion, I tried looking at include/code.h and > include/funcobject.h (my MS Windows distribution does not appear to > contain .c files). However, since I'm not a C programmer, I did not > find the .h files all that helpful. I'm hardly surprised. The naivety of those who insist that the "best way to understand how new.function and new.code work" is to look at the C source code for object is amusing. Not everybody reads C. This is a Python group, and surely the best way would be to see some good examples using *Python*. > What I failed to make clear in my original posting is that the > functions must be created dynamically using information in a *record* > as the code iterates over all *records*. So, I can not pre-define the > functions and then simply select the desired one at run-time. Here's an example that might help. class MyClass(object): pass records = ["spam", "ham"] for record in records: # define a new function def f(n): return (record + " ")*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instance.execute(5) -- Steven From steve at holdenweb.com Mon Mar 17 04:59:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Mar 2008 04:59:44 -0400 Subject: [PyCON-Organizers] FWD: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: <20080317001209.GA16907@panix.com> References: <20080317001209.GA16907@panix.com> Message-ID: <47DE3300.4060108@holdenweb.com> Aahz wrote: > FYI > > ----- Forwarded message from Aahz ----- > > From: Aahz > Newsgroups: comp.lang.python > Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) > Date: 16 Mar 2008 17:09:02 -0700 > Organization: The Cat & Dragon > > [warning: rant ahead] > > [[ > Before starting my rant, I would like to encourage anyone who was at > PyCon but has not provided formal feedback to use the following URLs: > > For the conference: > http://tinyurl.com/2ara8u > > For the tutorials: > http://tinyurl.com/2ew2pc > ]] > > In article <5776428b-82b3-4921-945a-69beab134edd at b64g2000hsa.googlegroups.com>, > fumanchu wrote: >> This is my third PyCon, and I've found a reasonably-sized cadre of >> people who come for the hallway conversations plus a Bof or two, >> having given up on hearing anything new, useful, or inspiring in the >> talks. There are several people I know who would like to see a more >> advanced academic track. > > Let's leave aside the issue of how sponsor talks were handled: assuming > that there's general agreement that this year was a failed experiment, > fixing it is easy. > > What you're bringing up here is a much more difficult issue, and it is, > in the end, not a solvable issue in the general case. For starters, > speaking as someone who has been going to science fiction conventions > for more than twenty years, there will inevitably be plenty of people > like your cadre. I rarely go to organized programming anymore, but I > still have a great time because I'm seeing all my friends. PyCon is a > similar community-oriented event. > > Moreover, PyCon's success rests on many legs: tutorials, Open Space, > Lightning Talks, formal presentations, keynotes, and sprinting. That's > aside from the myriad opportunities to network with people. > > Finally, trying to satisfy a thousand people is impossible. People who > want to emphasize specific topics (e.g. an academic track) will need to > start organizing other kinds of Python conferences. > > > Now the rant: > > If you did not like the programming this year (aside from the sponsor > talks) and you did not participate in organizing PyCon or in delivering > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > > PyCon is built on the backs of its volunteers. I personally spent more > than twenty hours just doing Program Committee work. We rejected half > the proposals that we received, simply due to lack of space. We had > difficulty evaluating some proposals because nobody on the PC had subject > matter expertise. > > None of the speakers received any kind of honorarium. Except for keynote > speakers (e.g. Ivan Krstic), no speakers received free registration > unless they requested financial aid. > > There are no requirements for volunteering other than a willingness to > volunteer and a modicum of courtesy in working with people. > > PyCon is what YOU make of it. If you want to change PyCon, propose a > presentation or join the conference committee (concom) -- the latter only > requires signing up for the pycon-organizers mailing list. > > This doesn't mean that we are uninterested in feedback. We love > feedback. But there are stark limits to what we can do unless people get > involved and push their pet projects. I am copying this reply to comp.lang.python just so that the people who were *not* involved in the organization of the conference will know two things: first, that the negative feedback the organizers have received is regarded as valuable, helpful, and (to some extent) justified; secondly, so that everyone who receives this message knows that they are welcome to participate in improving PyCon (which, as Aahz has indicated, really means that the broader the range of expertise on the program committee the more the selected talks can reflect the true needs of the audience - but don't imagine that participation is limited to the Program Committee). Also, please be aware this is only one message on a *very* long thread in the pycon-organizers list. Before I say anything else, I want to (again) publicly thank David Goodger and his team, and the ChiPy team led by Chris McAvoy, for the long hours and hard work they put in to what I personally (as the founder of PyCon) regard as the best PyCon ever. You will perhaps get some idea of the explosive growth in demand they have managed to satisfy by pointing out that this year there were more people attending paid tutorials, and there are more people staying after the conference to sprint (thereby improving Python and its applications), and more people attending their *first* PyCon this year, than attended the first PyCon that I organized five years ago in DC. If you have not been privy to the planning process, let me assure you that you have *no* idea how hard people have worked to try to ensure that *everyone* who came to PyCon this year had a positive experience. I can say this without fear of being thought to defend my own position, since I have (for the first time ever, yay!) played absolutely no formal role in the organization of PyCon. I can also say with every confidence that if you would like to volunteer to make the next PyCon (again in Chicago in 2009) better then you are unlikely to be turned away. The conference is growing so fast we have to run to keep up, everyone is learning as we go along. Ken Whitesell has written (after admitting that his original assessment might have been hasty) """By rough count, I attended 22 separate talks, including the tutorials and plenary sessions. Of that, there were 4 (not 5 that I wrote below) that I would consider below par.""" If the Program Committee have managed to provide a program where 75% of the talks were at or above average then they have worked a statistical miracle, though personally I have always felt that the general quality of PyCon talks has been way above that provided by the average "pay to play" technical conference. This does bring up another useful issue, which is that the overall delegate satisfaction is always going to be a bell-shaped curve. As the total number of delegates continues to rise the tails of that curve broaden, and it is more likely that a few delegates will be unhappy with the majority of the scheduled talks that they attend. It's unfortunate, but all the organizers can do is keep the focus on quality and continue to encourage broad participation. It is likely that almost everyone who reads this message has a legitimate right to consider themselves a part of the Python community. To address the specific issue of sponsor presentations, I believe that the Diamond Sponsor Keynotes given by both White Oak Technologies and Google were entirely within the spirit of PyCon, and appropriate to the audience even though not highly technical. As far as the sponsor lightning talks go, all involved admit that mistakes were made. The specific issue that had the largest negative impact was the bunching of the talks at the beginning of the session on Friday and (particularly) on Saturday. This was effectively an attempt to repeat the successful 2007 formula without acknowledging the effects of the (huge!) increase in sponsorship this year. While there are steps that could be taken to remedy this issue, I believe (though David Goodger can choose to contradict me, since he is the authority and I have not yet discussed this with him) that the success of the exhibition hall this year means that the sponsors are unlikely to need a specific channel in the conference program to present their commercial message. If they have a technical talk they feel would interest the delegates then they can use the same sign-up sheet that everyone else does, and be subject to the same rules as everyone else. To put the sponsorship in complete perspective, subtracting the catering costs of (I think) $182 a delegate paying $200 (the hobbyist early-bird registration fee) for a place at PyCon 2008 was contributing $18 to the remaining costs, which were not insignificant. A number of delegates with whom I have discussed this issue have agreed with me that for that kind of subsidy it isn't unreasonable to expect us to "rent our eyeballs" for a brief period, though next year I am sure the organizers will be sure to brief all sponsor keynote speakers carefully about acceptable topics. In summary, when things are growing as fact as PyCon is a few mis-steps are inevitable, as we are traversing foreign territory and learning as we go. While it's upsetting to know that some individual delegates were less than happy with their conference experience I believe the feedback will tell a different overall story when it has been analyzed. The organizers continue to be open to offers of assistance, and feedback from any participant. That is the spirit of PyCon, and I'd like to thank Bruce Eckel for saying what was on his mind. As a provider of commercial training I am uncomfortably aware that one normally hears from one customer out of each seven who are dissatisfied. If the other six will contact me personally I will do what I can to remedy the situation :-) Again, the URLs for delegates to provide feedback about their experiences are > For the conference: > http://tinyurl.com/2ara8u > > For the tutorials: > http://tinyurl.com/2ew2pc I hope to see you all at PyCon next year. Way to go, Chicago!! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From yao1337 at gmail.com Wed Mar 19 03:05:50 2008 From: yao1337 at gmail.com (purple) Date: Wed, 19 Mar 2008 00:05:50 -0700 (PDT) Subject: How to solve a three-element equation set? Message-ID: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> Could you guys do me a favor for solving a equation set? Z=d/4*(1-SIN(X)/X) X=8q/(D^2*Y)+SIN(X) Y=1/n*Z^(2/3)*i^(1/2) In this equation set, X,Y&Z are the unkown parameters, the others say, d, q, n&i are known. SO in python, how to program it to represent X, Y and Z in the form of d, q, n and i? Thanks very much. From kyosohma at gmail.com Mon Mar 10 11:36:22 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 08:36:22 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: On Mar 10, 10:27 am, "Malcolm Greene" wrote: > Stefan, > > > My personal experience with wxPython has its ups and downs. Specifically when it comes to crashes, I wouldn't bet my life on it. (but then, the OP > > I'm new to Python and getting ready to build a small client based > application intended to run on Windows and Linux. I was planning on > using wxPython until I saw your comment above. > > Any suggestions on an alternative Python client-side GUI library (pyQT > ?) or tips on where I can find out more about wxPython/wxWidget > problems? > > Thank you, > Malcolm We use wxPython here at work for new application development and have had no major problems with it once we knew what dlls to include. In my experience, I've needed gdiplus.dll, msvcp71.dll and MSVCR71.dll from time to time. Mike From steve at holdenweb.com Sun Mar 30 15:35:34 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 15:35:34 -0400 Subject: License of Python In-Reply-To: References: Message-ID: iu2 wrote: > Hi guys, > > I'd like to use Python in a commercial application. In fact I would > like to write the application entirely in Python. > But I think I wouldn't like telling what language the application is > written in. > The problem is that including Python's license in the binary, which as > I understand is a must do, reveals that the appliation is based on > Python. > > I'll appreciate your advices about this > Thanks > iu2 My advice would be to create something of real value before you worry about issues like this. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From zubeido at yahoo.com.br Sat Mar 8 11:57:34 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 8 Mar 2008 08:57:34 -0800 (PST) Subject: SQL problem in python Message-ID: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> class db: def __init__(self): #constructor conn = sqlite3.connect(":memory:") conn.isolation_level = None self.cursor = conn.cursor() self.cursor.execute("CREATE TABLE database (album,filepath)") def add_entry(self, eone , etwo): #Add entry to database self.cursor.execute("INSERT INTO database (album,filepath) VALUES (?,?)", ( eone , etwo ) ) return 1 #TODO: exception handler def get_mediadb(self, print_db = False): self.cursor.execute('SELECT * FROM database') if (print_db == True): print self.cursor.fetchall() def get_value( self, column ): self.cursor.execute( "SELECT (?) FROM database", column ) for n in self.cursor: print n def destructor(self): self.cursor.close() if __name__ == "__main__": f = db() f.add_entry( "Pinkk Floyd", "fdgf" ) f.add_entry( "Pink", "fdgf" ) # f.get_mediadb(print_db=True) f.get_value(('filepath',)) f.destructor() When i run it the get_value() returns 'filepath' instead of the columns. But if i dont use any variable and make the expression static all goes on as its supposed to. What am i doing wrong? PS: Dont mind the bad code From deets at nospam.web.de Thu Mar 13 19:44:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Mar 2008 00:44:28 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: <63tsj3F27o6o5U1@mid.uni-berlin.de> > My understanding is that foo.bar does *not* create a new object. Your understanding is not correct. > All it > does is return the value of the bar attribute of object foo. What new > object is being created? A bound method. This happens through the descriptor-protocol. Please see this example: class Foo(object): def bar(self): pass f = Foo() a = Foo.bar b = f.bar c = f.bar print a, b, c print id(b), id(c) The result is this: > > 315560 788960 So b and c really are different objects - "a is not b == True" Diez From wingi at gmx.com Wed Mar 12 05:10:46 2008 From: wingi at gmx.com (wingi at gmx.com) Date: Wed, 12 Mar 2008 02:10:46 -0700 (PDT) Subject: Exctract GIF comment from image References: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Message-ID: <8f93339a-c78e-4580-903c-eeff991b9892@q78g2000hsh.googlegroups.com> On 11 Mrz., 18:39, "Guilherme Polo" wrote: > 2008/3/11, wi... at gmx.com : > > > Hi, > > > simple question: ThePILdoes not support reading the optional > > description in GIF Images. > > > I did a quick thing here, try it and check if it solves the problem for you: > Wow - thanx for the fast answer! Yes it works and can use it ;-) *smile* From paddy3118 at googlemail.com Thu Mar 13 01:09:48 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 12 Mar 2008 22:09:48 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> Message-ID: On Mar 13, 1:37 am, Carl Banks wrote: > On Mar 12, 8:11 pm, Justus Schwabedal > wrote: > > > What do you need it for anyway? I just read about it and I think it's > > useless > > in python. > > Perl, like Python, has a separate compilation and run times. One day, > someone who was trying to use Perl for something asked, "You know, > wouldn't it be neat-o if you could execute some Perl code *before* you > compiled the script?" And so (since that's usually enough reason to > add something to Perl) was borne the BEGIN block. > > I believe the official rationale was that they wanted to add some > magic variables that affected Perl's compilation and couldn't do it > without a magic block that executed at compile time. > > Python solved a similar problem by introducing __future__ imports. > > Carl Banks And theres me thinking it was part of Perls AWK compatibility code. - Paddy. From p.f.moore at gmail.com Sat Mar 1 17:39:41 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sat, 1 Mar 2008 22:39:41 +0000 Subject: [Python-Dev] [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: <47C9D802.2090205@v.loewis.de> References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> <47C9D802.2090205@v.loewis.de> Message-ID: <79990c6b0803011439n583bc2b2w5c544b620a91fa61@mail.gmail.com> On 01/03/2008, "Martin v. L?wis" wrote: > > As of 4:50 PM EST, the links to Windows installers give 404 File Not > > Found. > > > > I gather that they are still in process, > > and notice that there is no public c.l.p. announcement. > > > I just fixed that. The files were there; just the links were wrong. The 2.6a1 x86 MSI is there, but the 3.0a3 x86 MSI is still giving a 404. Paul. From bharathv6.project at gmail.com Tue Mar 18 08:51:03 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Tue, 18 Mar 2008 18:21:03 +0530 Subject: automatically doing some cleaning-up by the process when the systems shuts down Message-ID: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> hi .. my programs runs as daemon and it does some logging .. when system shuts down .. which may be done manually . i want my process do some cleaning up automatically such as writing in to the log file when the process terminats before the system shuts down thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkapoor at wscm.net Mon Mar 24 16:50:19 2008 From: tkapoor at wscm.net (Tarun Kapoor) Date: Mon, 24 Mar 2008 15:50:19 -0500 Subject: Paramiko bugs out on windows 2003 server Message-ID: I am using the paramiko library to pull a data from a server using SFTP. It works perfect on a windows xp machine but bugs out a windows 2003 server. I get the following error: Traceback (most recent call last): File "S:\Temp\ftpBOA.py", line 5, in ? import paramiko File "C:\Python23\lib\paramiko\__init__.py", line 69, in ? from transport import randpool, SecurityOptions, Transport File "C:\Python23\lib\paramiko\transport.py", line 32, in ? from paramiko import util File "C:\Python23\lib\paramiko\util.py", line 31, in ? from paramiko.common import * File "C:\Python23\lib\paramiko\common.py", line 98, in ? from osrandom import OSRandomPool File "C:\Python23\lib\paramiko\osrandom.py", line 54, in ? raise ImportError("Cannot find OS entropy source") ImportError: Cannot find OS entropy source Anyone knows how to solve it ? Tarun Kapoor Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. From durieux_br at yahoo.com.br Thu Mar 27 15:27:16 2008 From: durieux_br at yahoo.com.br (Fabio Durieux Lopes) Date: Thu, 27 Mar 2008 19:27:16 -0000 Subject: Signal problem Message-ID: Hello again! Full of problems today! This one is about signal treatment. I made a daemon and set it to treat 2 signals: SIGALRM and SIGTERM. It goes like this: signal.signal(signal.SIGTERM, daemon.signalHandler) signal.signal(signal.SIGALRM, aFilter.alarmHandler) On daemon.py I have: " ... terminate = False def signalHandler(signum, frame): terminate = True ... " And my main loop goes like this: 'while(not daemon.terminate):' When the signal treatment was in the same file as my loop it worked just fine, and since I've separated it in another file it stopped working. The SIGALRM treatment, which remains in the same file, is still working. Any reason why it doesn't treat SIGTERM anymore? Does it have anything to do with the fact that 'terminate' is not a class variable? Any ideas? Thanks in advance! From jeff at schwabcenter.com Mon Mar 17 13:59:52 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 10:59:52 -0700 Subject: questions about named pipe objects... In-Reply-To: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> References: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> Message-ID: waltbrad wrote: > I'm proceeding slowly though the Lutz book "Programming Python". I'm > in the section on named pipes. The script he uses has two functions: > one for the child the other for the parent. You start the parent then > the child: > > python pipefifo.py #starts the parent > > file /tmp/pipefifo # shows that the file is a named pipe You appear to be using something Unix-like. > python pipefifo.py -child # starts a child process and writes to the > pipe. > > This is done between two command windows - the first for the parent > and the second for the child. > > Now, the child's write loop is infinite. So, I used Ctrl-C and stopped > the process. But the parent's read loop is also infinite and without > and exception, so it keeps reading from the pipe after the child is > shutdown even though the lines are empty. So, I had to shut that down > also. > > I then wanted to start the child process first and see what happened > when I ran the parent. Well that works but the reads come out in > random order. This got me wondering about the pipe file itself. So I > tried to open it with leafpad and found that I couldn't. I guess > these files can only be opened by processes? > > Okay. But exactly when does the system brand this file as a named pipe > and how? A Unix fifo is only nominally a file. It's really just a convenient way of referring to an in-memory object. mkfifo f some_prog > f & cat f Is semantically equivalent to: some_prog | cat If you want to peruse the data in your editor, use a regular file, not a fifo. Have the writer (producer, "child" in your example) open it in append mode. From Robert.Bossy at jouy.inra.fr Fri Mar 21 04:01:10 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 21 Mar 2008 09:01:10 +0100 Subject: script won't run using cron.d or crontab In-Reply-To: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> References: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> Message-ID: <47E36B46.4050002@jouy.inra.fr> Bjorn Meyer wrote: > I appologize if this been discussed previously. If so, just point me > to that information. > > I have done a fair bit of digging, but I haven't found a description > of what to actually do. > > I have a fairly lengthy script that I am able to run without any > problems from a shell. My problem is, now I am wanting to get it > running using crontab or cron.d. It seems that running it this way > there is a problem with some of the commands that I am using. For > instance "commands.getoutput" or "os.access". I am assuming that there > is something missing within the environment that cron runs that fails > to allow these commands to run. > If anyone has any information that would help, it would be greatly > appreciated. Hi, From a shell, type: man 5 crontab and read carefully. You'll realize that a croned script does not inherit from the user shell's environment. Cheers, RB From gagsl-py2 at yahoo.com.ar Mon Mar 31 13:35:26 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 14:35:26 -0300 Subject: How to insert multiple rows in SQLite Dbase References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> <657h3nF2eehi8U1@mid.uni-berlin.de> Message-ID: En Mon, 31 Mar 2008 11:22:40 -0300, afandi escribi?: > On Mar 30, 4:46 am, Gerhard H?ring wrote: >> >> The deluxe version with generators could look like this: >> >> def parse_logfile(): >> logf = open(...) >> for line in logf: >> if ...: >> row = (value1, value2, value3) >> yield row >> logf.close() >> >> ... >> >> cur.executemany("insert into ... values (c1, c2, c3)", parse_logfile()) > > Thanks regards to your suggestion, but I don't understand why we have > to put the IF statement? Which if statement? The if inside parse_logfile quoted above is just an example, it's not essential. -- Gabriel Genellina From furkankuru at gmail.com Tue Mar 25 21:14:39 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 03:14:39 +0200 Subject: My python interpreter became mad ! In-Reply-To: <47E99C99.2060401@lexicon.net> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> <47E99C99.2060401@lexicon.net> Message-ID: <3a4a8f930803251814t3043f724v913bcc9e7aa7bf6e@mail.gmail.com> On 3/26/08, John Machin wrote: > > > > but I did not give it a chance "not trying python interpreter in another > > directory" > > I don't understand that sentence. ok let me explain: I did not think he/she/anyone would ask the question in the main thread without trying the interpreter a few times starting it from different directories. > so if we assume the problem exists in every directory, it has something > > to do with pythonpath. > > Why would/should we assume that? Because I, as an individual, would not ask this question without running interpreter from different directories. and I would look whether I created a py file with the exact same name of a core module. And this "simple" mistake had been pointed out by other guys. The only other reason that came to my mind was this pythonpath. ( and I was dealing with it recently: you may have take a look at the thread titled 'embedded pyton pythonpath' any answer is appreciated :p ) > > you can try setting pythonpath to some directory and put a re.py there > > and try from any directory starting your interpreter and importing re. > > and achieve the same result: importing the bogus re. What's your point? yeah same result: bogus re. but from a different way: not user's re but created by someone else in another directory. > > > > > > > On 3/25/08, *John Machin* > > wrote: > > > > Furkan Kuru top-posted: > > > Most probably X-Spam added itself to your path. > > > > What is "X-Spam"? Added itself to Benjamin's path [not mine] in such > a > > fashion that it is invoked when one does "import re"? > > > > > you should look at your PATH and PYTHONPATH environment > variables. > > > > Most *IM*probably. Read the traceback: > > """ > > > > File "/etc/postfix/re.py", line 19, in ? > > > > m = re.match('(Spam)', mail) > > > > AttributeError: 'module' object has no attribute 'match' > > """ > > > > This is a classic case of a script (which does not guard against > side > > effects (like spewing out gibberish) when imported instead of being > > executed) being given the same name as a Python-included module and > > being executed in the current directory and hence ends up importing > > itself. > > > > > > > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > > > > > >> > wrote: > > > > > > On Mar 25, 10:05 pm, Benjamin Watine > > > > >> wrote: > > > > Yes, my python interpreter seems to became mad ; or may be > > it's > > > me ! :) > > > > > > > > I'm trying to use re module to match text with regular > > > expression. In a > > > > first time, all works right. But since yesterday, I have a > > very > > > strange > > > > behaviour : > > > > > > > > $ python2.4 > > > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on > linux2 > > > > Type "help", "copyright", "credits" or "license" for more > > > information. > > > > >>> import re > > > > X-Spam-Flag: YES > > > > [snip] > > > > > > Traceback (most recent call last): > > > > File "", line 1, in ? > > > > File "/etc/postfix/re.py", line 19, in ? > > > > m = re.match('(Spam)', mail) > > > > AttributeError: 'module' object has no attribute 'match' > > > > >>> > > > > > > > > What's the hell ?? I'm just importing the re module. > > > > > > No you're not importing *the* re module. You're importing > *an* re > > > module, the first one that is found. In this case: your own > > re.py. > > > Rename it. > > > > > > > > > > > > > -- > > Furkan Kuru > > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From zutesmog at gmail.com Wed Mar 12 03:17:48 2008 From: zutesmog at gmail.com (zutesmog at gmail.com) Date: Wed, 12 Mar 2008 00:17:48 -0700 (PDT) Subject: Problems installing Python Imaging Library References: <76000a76-0c8f-4b79-95c8-9d0f4aae0972@n58g2000hsf.googlegroups.com> Message-ID: On Mar 10, 3:06 am, Nick Day wrote: > Hi, > > I'm trying to install PIL from source on my CentOS 4.5 server. The > build summary reports that I have everything installed... > > -------------------------------------------------------------------- > PIL 1.1.6 BUILD SUMMARY > -------------------------------------------------------------------- > version 1.1.6 > platform linux2 2.3.4 (#1, Dec 11 2007, 05:28:55) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] > -------------------------------------------------------------------- > --- TKINTER support ok > --- JPEG support ok > --- ZLIB (PNG/ZIP) support ok > --- FREETYPE2 support ok > > ... but if I try and build it I receive the following error: > > /usr/bin/ld: /usr/local/lib/libjpeg.a(jcparam.o): relocation > R_X86_64_32 against `a local symbol' can not be used when making a > shared object; recompile with -fPIC > > How do I fix this? I am currently running "python setup.py build" and > don't understand how I would change the compiling options to add the "- > fPIC" flag. I'm quite a newbie when it comes to Linux/Python so any > help you could give me would be great. > > Thanks, > Nick You should be linking against a dynamic version of libjpeg rather than the static version. ie libjpeg.so Looks like you have locally installed libjpeg but only built a static version. Rgds Tim From torriem at gmail.com Wed Mar 5 00:12:00 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 04 Mar 2008 22:12:00 -0700 Subject: Protocol for thread communication Message-ID: <47CE2BA0.2060001@gmail.com> Does anyone have any recommended ideas/ways of implementing a proper control and status protocol for communicating with threads? I have a program that spawns a few worker threads, and I'd like a good, clean way of communicating the status of these threads back to the main thread. Each thread (wrapped in a very simple class) has only a few states, and progress levels in those states. And sometimes they can error out, although if the main thread knew about it, it could ask the thread to retry (start over). How would any of you do this? A callback method that the thread can call (synchronizing one-way variables isn't a problem)? A queue? How would the main thread check these things? Currently the main thread is polling some simple status variables. This works, and polling will likely continue to be the simplest and easiest way, but simple status variables are very limited. Are there any pythonic patterns people have developed for this. thanks. Michael From wescpy at gmail.com Wed Mar 19 00:26:02 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 18 Mar 2008 21:26:02 -0700 (PDT) Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <6653ea0b-5d8b-4017-b0bd-8948ea0bf7a1@e23g2000prf.googlegroups.com> > > You're mixing two completely different approaches of building a > > property. If that code is actually in the book like that, that's a typo > > that you should mention to the author. > > : > > The recipe you're referring to uses a magical function that returns a > > dictionary of getter function, setter function, deleter function, and > > docstring, with suitable key names so that the dictionary can be passed > > as a keyword argument dictionary into the property() constructor. > > However, that requires the magical foo=property(**foo()) invocation, not > > the regular decorator invocation foo=property(foo). > > Ah, ok, I'll send him an email then, thanks for the explanation! this well-known error was discovered pretty early... apologies to all readers. please checkout the Errata at the book's website -- http://corepython.com -- and keep it as a companion in case you find anything else like this. i appreciate all constructive feedback... don't trust everything you read! send any other corrections to me at corepython at yahoo... including suggestions for future editions, ideas for exercises, new material that you think should be covered, etc. best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From knut.urbye at gmail.com Thu Mar 27 04:50:13 2008 From: knut.urbye at gmail.com (Knut) Date: Thu, 27 Mar 2008 01:50:13 -0700 (PDT) Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> Message-ID: <3e6246de-5af2-4296-bea5-76bfa26adf12@u10g2000prn.googlegroups.com> On 26 Mar, 23:08, Thomas Heller wrote: > Knut schrieb: > > > > >> The script can't resolve the server name. Try to do it by hand using > >> nslookup or even ping (you may want to add a few print statements inside > >> the script to see the exact host name it is trying to connect to, in case > >> it isn't what you expect) > >> If you can't resolve the host name using nslookup, there is a network > >> problem, not in your script. If you can resolve it, try your script > >> without py2exe if possible. > > >> -- > >> Gabriel Genellina > > > Thank you for the quick reply Gabriel. > > > I have made sure the script works fine before I exe it. > > It is when I compile the program I get this error. > > > I don't get how the compile changes server availability. > > Could it be a firewall issue? > > Thomas Hi Thomas, Thanks for the tip! Disabled the firewall to check if this could be the problem, but no help there either.. The mail server is on the local network, but I have also tried connecting to internal sockets to another program I have which sniffs a port. This works fine, until I run it as an exe.. My quest continues.. From fhaxbox66 at googlemail.com Fri Mar 7 09:37:21 2008 From: fhaxbox66 at googlemail.com (fhaxbox66 at googlemail.com) Date: Fri, 7 Mar 2008 06:37:21 -0800 (PST) Subject: Hyphenation: PyHyphen project now hosted on GoogleCode Message-ID: <38ab7938-9baf-4c41-ac7c-cad345cb830a@x30g2000hsd.googlegroups.com> This is to inform you that development of PyHyphen and issue tracking takes now place at http://pyhyphen.googlecode.com. All interested parties are encouraged to submit comments, suggestions and bug reports. Snapshots of the source tree can be obtained using subversion. At this stage, the sources contain a number of minor improvements over version 0.4.1 which is still available on the pypi. Windows installers are though still lacking. Regards Leo From george.sakkis at gmail.com Wed Mar 26 17:25:31 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 14:25:31 -0700 (PDT) Subject: Not understanding lamdas and scoping References: Message-ID: On Mar 26, 5:02 pm, Joshua Kugler wrote: > I am trying to use lamdba to generate some functions, and it is not working > the way I'd expect. The code is below, followed by the results I'm > getting. More comments below that. > > (...) > > So, is there some scoping issue with lambda > that I'm not seeing? Yes; it's not related to lambda though but to closures (whether defined as lambdas or regular functions). See for example http://groups.google.com/group/comp.lang.python/browse_frm/thread/94d1bba8ad56baf4 There should be an entry for this at http://www.python.org/doc/faq/programming/, that's really an FAQ. George From deets at nospam.web.de Thu Mar 13 07:12:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 12:12:37 +0100 Subject: What's Going On? References: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> Message-ID: <63sgh6F28j923U1@mid.uni-berlin.de> MartinRinehart at gmail.com wrote: > (Accompanied by Marvin Gaye) > >>>> def f(list=[0]): > ... list[0]+=1 > ... return list[0] > ... >>>> f() > 1 >>>> f() > 2 >>>> f() # 'list' is a name bound to a list (mutable) so this makes sense > 3 >>>> f([5]) > 6 >>>>f() # What's Going On? > 4 That the same default argument is mutated? What did you expect, that it got replaced by you passing another list? That would kind of defy the meaning of default-arguments, replacing them whenever you call a function with actual parameters. Diez From castironpi at gmail.com Mon Mar 31 19:23:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 16:23:04 -0700 (PDT) Subject: class super method References: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> Message-ID: <252dbf5b-6bad-4957-b56f-5bb36f66d80e@n58g2000hsf.googlegroups.com> On Mar 31, 5:58?pm, George Sakkis wrote: > On Mar 31, 6:25 pm, gigs wrote: > > > is there any tutorial for super method (when/how to use it)? > > > or maybe someone could explain me how it works? > > > thx > > Super is one of the dark corners of the language [1,2]... a good rule > of thumb is to stay away from it, or at least stick to its basic > usage. > > George > > [1]http://www.phyast.pitt.edu/~micheles/python/super.html > [2]http://fuhm.net/super-harmful/ Is ancestry mutable? From sturlamolden at yahoo.no Sun Mar 16 11:01:07 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 08:01:07 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <199cfa42-ca1a-4db6-bf4d-a0a811daa791@s12g2000prg.googlegroups.com> On 16 Mar, 15:32, bearophileH... at lycos.com wrote: > It seems the development of Cython is going very well, quite > differently from the dead-looking Pyrex. Hopefully Cython will become > more user-friendly too (Pyrex is far from being user-friendly for > Windows users, it doesn't even contain a compiler, I think. The Pyrex is not dead. And although it may come as a surprise to you, Pyrex IS a compiler. Pyrex does not contain a C compiler. But why should it? There are Microsoft Visual C++, MinGW, Cygwin, lcc, Borland C++, Intel C++ compiler, OpenWatcom, among others. Get your favourite. Being written in pure Python, Pyrex is equally easy to use on Windows and Linux. You have to use the command prompt or disttools on either platform. > The (little) point of this post: sometimes (when the programmer is > quite lazy) statically typed code is more "readable" than Python code. If your task is to translate a Python program into a statically typed language, type annotations can be helpful. But you don't need types to read a/b as 'a divided by b'. From gagsl-py2 at yahoo.com.ar Tue Mar 25 19:21:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 23:21:15 +0000 (UTC) Subject: embedded python pythonpath References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> Message-ID: Furkan Kuru gmail.com> writes: > I've tried below code (Setting pythonpath environment variable) > and then initialize python interpreter but the embedded python interpreter did not get the newly assigned PYTHONPATH. > I ve looked at the sys.path in python code (that is run by the embedded interpreter) and it behaved according to older pythonpath. Note that you don't HAVE to set the environment variable PYTHONPATH, there are other ways to get directories listed in sys.path - and that is what really counts. The simplest way is to just write code to insert the desired directories in front of sys.path, after the call to Py_Initialize. The only problem is that some modules (like site and sitecustomize) are searched and executed before your code has a chance to modify sys.path - I hope it's not a problem for you. > Setting environment variable seemed to be correct. > Does py_initialize run in another thread so it starts before setting the environment var? I could reproduce the problem with a smaller code (using C, not C++). Testing with Python 2.5.1 doesn't work (that means, it ignores the new setting for PYTHONPATH). Testing with current Python trunk (from svn) *does* work. I don't know if this is a bug that has been fixed, or it works that way because the svn version is not the default installation and then searches for things in a different way. #include int main(int argc, char *argv[]) { putenv("PYTHONPATH=C:\\TEMP\\MF"); system("set PYTHONPATH"); printf("Py_GETENV(PYTHONPATH)=%s\n", Py_GETENV("PYTHONPATH")); Py_Initialize(); PyRun_SimpleString("import sys\nprint sys.path"); Py_Finalize(); return 0; } I compiled twice with these commands: cl -MD -Ic:\apps\python25\include test.c c:\apps\python25 \Libs\Python25.lib /Fetest25.exe cl -MD -Ic:\apps\python\trunk\PC -Ic:\apps\python\trunk\include test.c c:\apps\python\trunk\PCbuild\Python26.lib /Fetest26.exe Python25.dll and Python26.dll both were copied into the current directory. test25.exe: PYTHONPATH=C:\TEMP\MF Py_GETENV(PYTHONPATH)=C:\TEMP\MF ['C:\\Apps\\Python25\\lib\\site-packages\\setuptools-0.6c5- py2.5.egg', 'C:\\Apps\\Python25\\lib\\site-packages\\ simplejson-1.7.1-py2.5-win32.egg', ... many directories, not including C:\TEMP\MF ... ] test26.exe: PYTHONPATH=C:\TEMP\MF Py_GETENV(PYTHONPATH)=C:\TEMP\MF 'import site' failed; use -v for traceback ['C:\\TEMP\\MF', 'C:\\TEMP\\python26.zip', '', 'C:\\TEMP'] I don't understand how the test program, compiled for 2.5.1, could actually locate the Python directory. (It's not in my PATH, it's not the default install directory, and I deleted the HKLM\Software\Python\PythonCore\2.5 registry key). -- Gabriel Genellina From nothanks at null.invalid Sat Mar 1 23:04:06 2008 From: nothanks at null.invalid (Bill) Date: Sat, 01 Mar 2008 23:04:06 -0500 Subject: Where's GUI for Python? In-Reply-To: References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: Peter Decker wrote, On 3/1/2008 9:58 PM: > On Sat, Mar 1, 2008 at 3:35 PM, K Viltersten wrote: >> I'm certain there is an API for creating >> GUI's but as far i can find it in the >> http://docs.python.org/tut/tut.html >> the only "gui" is in "Guido". > > Check out Dabo: http://dabodev.com > > It uses the wxPython UI toolkit, but wraps it in a much more Pythonic API. > > I've been using Dabo for over a year, and it rocks!! > Hi Peter, You should also take a look at wxGlade: http://wxglade.sourceforge.net/ which sits on top of wxPython: http://wxpython.org/ which wraps wxWidgets: http://www.wxwindows.org/ I've found that wxGlade is more usable, currently, than Dabo in it's visual layout tools that help you create the GUI for your apps. If you want a more "Pythonic" API (more than wxPython/wxWidgets) and want to write your GUI using mainly code instead of a visual layout tool, then Dabo is probably the way to go. If you want an interactive application that lets you visually create Frame or Dialog based applications, full of "widgets", then wxGlade is pretty good these days. Dabo, last time I looked, didn't yet have a usable visual menu creation capability in it's toolset, and this is a major reason, for me, that I currently have gravitated back to wxGlade. Also, although Dabo has a "Class Designer" that can design the GUI visually, and is in some ways more advanced than wxGlade, it seems in other ways to be more limiting. Neither one, unfortunately, is very well documented, but wxGlade is fairly obvious, and directly generates wxPython code (not a "higher level" API as is done in Dabo), which lets you use the wxGlade and wxWidgets documentation to figure things out. Also, BTW, I think the statement on the wxGlade site about "the generated code does nothing apart from displaying the created widgets", is not really true, and should be re-worded. Current versions of wxGlade include the capability to automatically create simple event-handler functions, and automatically generates the code to connect the events generated by the GUI widgets to the event handlers. In my opinion, this is much more than doing "nothing apart from displaying the created widgets". It helps make it real easy to call your handler functions, and I don't really want it doing much more than that anyway. In either case, when you write your own code, it is probably best to learn how to have the tool generate the code containing the classes that form the GUI interface, but, use derived classes (subclasses) in your own separate file(s) to form your application's interface to the GUI. That way, you can let wxGlade (or Dabo) always generate (and overwrite) its own code that remains entirely separate from your own code. Bill From fn681 at ncf.ca Fri Mar 28 16:22:37 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 28 Mar 2008 16:22:37 -0400 Subject: how to capture screenshots of the active window in Python In-Reply-To: References: <142053.72537.qm@web44801.mail.sp1.yahoo.com> Message-ID: <47ED538D.2020607@ncf.ca> Gabriel Genellina wrote: > En Thu, 27 Mar 2008 20:28:27 -0300, Praveena B > escribi?: > >> Can anyone help me out?? > > Still lacking details... PIL has a ImageGrab module, Windows only. > For Windows, Alt Prtscn usually copies the image to a clipboard. Colin W. From _karlo_ at mosor.net Sun Mar 9 11:56:14 2008 From: _karlo_ at mosor.net (Karlo Lozovina) Date: Sun, 09 Mar 2008 16:56:14 +0100 Subject: Returning values from function to Python shell/IPython Message-ID: Hi all! I have a runTest() function inside my module, which sets up and initializes lots of objects and performs some basic tests on them. Usually (from IPython) I just write `run my_module.py`, and then `runTest()`. But sometimes I would like to manually twiddle with objects runTest creates. Is there any way I can "return" all those objects local to runTest(), and have them available in IPython (or ordinary Python shell)? Thanks... P.S. I know I can do it from a: if __name__ == '__main__': # lots of object initialization... and then have all those objects available in the interpreter. -- Karlo Lozovina -- Mosor From castironpi at gmail.com Mon Mar 10 05:46:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 02:46:17 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> <47D4F207.6050606@behnel.de> Message-ID: > >> And if you really need the efficiency of "well-tuned raw C", it's one function > >> call away in your Cython code. > > > What do you mean by that? > > > I know nothing about how Cython compares to C in performance, so I said > > "well-tuned" because it must be possible to write C that is faster than > > Cython, though it may take some effort. > > So, you write the hand-optimised function in plain C, declare it in Cython and > call it. That's what I meant. Since Cython compiles to C code, linking against > a C module is straight forward. And this still keeps you from having to write > all the Python API glue code in plain C. Python was originally intended to just link C modules, right? (ITTRW if that's the right word?) What are Python's roots? What are its principles? What are its fundamentals? (And what does Python 8! look like!?) We can even get multi-threading running outside of the Global Interpreter Lock, if the thread only acquires it to access shared object code... make that mananged objects. One big decision is if you have a separate Python interpreter running on every remote location, versus say as just a relay mechanism. C on the rest. CMIIW, correct me if I'm wrong, but the productivity bottlenecks vs. performance bottlenecks make a trade-off. For my part, sometimes I get __getattr__ bottlenecks, and other times object instantiation bottlenecks. There was an iterator one in there too. But no I didn't have competing C code to test to compare. If I understand OP correctly, C libraries will be running at all locations, which means they'll need separate compilations. In fact, come to think of it, I'm having trouble with the concept of cross-platform distributed. Do OP mean that lots of programmers are sharing data? Will all the platforms be performing all of the tasks? Or do they specialize? (Not necessarily / no / yes ok.) Lastly, if you can get a boost by buying more servers, then there's a resource bottleneck breakpoint to consider too. From NeilFang2008 at gmail.com Sat Mar 1 21:55:23 2008 From: NeilFang2008 at gmail.com (Neil.Fang.CN) Date: Sat, 1 Mar 2008 18:55:23 -0800 (PST) Subject: class object interface document Message-ID: Hello Where can I find the Python class object interface document, such as struct PyClassObject, PyClass_New()? Thanks! -- Neil From wolf_tracks at invalid.com Mon Mar 31 06:58:20 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 31 Mar 2008 10:58:20 GMT Subject: Class Image.Image? Message-ID: I put a print statement in some Python code to determine the class (__class__) of a variable and the result was Image.Image. Why not just Image; otherwise, what's it telling me? -- Wayne Watson (Nevada City, CA) Web Page: From kyosohma at gmail.com Wed Mar 5 16:38:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 5 Mar 2008 13:38:59 -0800 (PST) Subject: What is a class? References: Message-ID: On Mar 5, 12:50 pm, castiro... at gmail.com wrote: > What is a class that is not a module? Why is a raven like a writing desk? As for Python class information, I would recommend reading the following sites: http://docs.python.org/tut/node11.html http://www.diveintopython.org/object_oriented_framework/defining_classes.html And for modules, check these out: http://docs.python.org/tut/node8.html http://www.penzilla.net/tutorials/python/modules/ Mike From fakeaddress at nowhere.org Tue Mar 25 22:49:04 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 26 Mar 2008 02:49:04 GMT Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: Benjamin Watine wrote: > OK, so if I understand well what you said, using queue allow to be sure > that the data is passed in totality before coninuing with next > instruction. That make sense. Right. > Using thread and queue seems to be very more slow than using files > redirection with bash. I'll see if it make a great load average and/or > I/O time. Hmmm... you might try increasing the buffer size. -- --Bryan From musiccomposition at gmail.com Sat Mar 15 22:27:07 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 15 Mar 2008 19:27:07 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: On Mar 15, 8:12 pm, lampshade wrote: > Hello, > > I'm having some problems with os.path.isdir I think it is something > simple that I'm overlooking. > > #!/usr/bin/python > import os > > my_path = os.path.expanduser("~/pictures/") > print my_path > results = os.listdir(my_path) > for a_result in results: > if os.path.isdir(str(my_path) + str(a_result)): Try if os.path.isdir(os.path.join(my_path, a_result)): > results.remove(a_result) > > for x in results: print x > > The problem is, that the directories are never removed. Can anyone > point out what I'm missing that is causing the bug? Is there a better > way of doing this? You should always use os.path.join to join paths. You shouldn't add them like normal strings. I suspect you're getting a combination which doesn't exist, so it isn't a dir. :) > > Thanks, From castironpi at gmail.com Sat Mar 1 14:59:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 11:59:43 -0800 (PST) Subject: Surprised by the command "del" References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: On Mar 1, 2:05?pm, "K Viltersten" wrote: > I'm reading the docs and at 5.2 the del > statement is discussed. At first, i thought > i've found a typo but as i tried that > myself, it turns it actually does work so. > > ? a = ["alpha", "beta", "gamma"] > ? del a[2:2] > ? a > > Now, i expected the result to be that the > "beta" element has been removed. Obviously, > Python thinks otherwise. Why?! > > Elaboration: > I wonder why such an unintuitive effect has > been implemented. I'm sure it's for a very > good reason not clear to me due to my > ignorance. Alternatively - my expectations > are not so intuitive as i think. ? :) It's the Phillips vs. the flathead. Is b in x[a:b:c] an endpoint or a distance? This is Python too; you're welcome to implement: - b means length - one-based indices - inclusive - b out of bounds exceptions A slice object (a,b,c) is passed to whatevercollection.__getitem__, .__setitem__, or .__delitem__. From pavlovevidence at gmail.com Mon Mar 3 19:40:22 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 16:40:22 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: <1154e7d6-11e9-40ff-8565-029d2f002e2e@e23g2000prf.googlegroups.com> On Mar 3, 7:24 pm, Mensanator wrote: > On Mar 3, 4:53 pm, Carl Banks wrote: > > > > > On Mar 3, 4:47 pm, Mensanator wrote: > > > > On Mar 3, 2:49 pm, Carl Banks wrote: > > > > > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > > Notice anything funny about the "random" choices? > > > > > > import sympy > > > > > import time > > > > > import random > > > > > > f = [i for i in sympy.primerange(1000,10000)] > > > > > > for i in xrange(10): > > > > > f1 = random.choice(f) > > > > > print f1, > > > > > f2 = random.choice(f) > > > > > print f2, > > > > > C = f1*f2 > > > > > ff = None > > > > > ff = sympy.factorint(C) > > > > > print ff > > > > > > ## 7307 7243 [(7243, 1), (7307, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > > As in, "they're NOT random". > > > > > > The random number generator is broken by the sympy.factorint() > > > > > function. > > > > > > Random.choice() works ok if the factorint() function commented out. > > > > > > ## 6089 1811 None > > > > > ## 6449 1759 None > > > > > ## 9923 4639 None > > > > > ## 4013 4889 None > > > > > ## 4349 2029 None > > > > > ## 6703 8677 None > > > > > ## 1879 1867 None > > > > > ## 5153 5279 None > > > > > ## 2011 4937 None > > > > > ## 7253 5507 None > > > > > > This makes sympy worse than worthless, as it f***s up other modules. > > > > > Dude, relax. > > > > > It's just a bug--probably sympy is messing with the internals of the > > > > random number generator. It would be a simple fix. Instead of > > > > b****ing about it, file a bug report. > > > > I did. > > > > > Or better yet, submit a patch. > > > > I would if I knew what the problem was. > > > > I posted it here because someone recommended it. > > > I'm simply un-recommending it. Those who don't care > > > needn't pay any attention. Those who do should be > > > glad that faults are pointed out when found. > > > 1. You can point out the faults of a program without insults and > > vulgarity > > Did I insult someone? Yes, the intelligence of most people here, if you think anyone's going to buy your rationalization of your spiteful behavior. Four posts is more than enough of you. *PLONK* Carl Banks From tjreedy at udel.edu Sun Mar 2 17:02:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 17:02:25 -0500 Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: "Christoph Zwerschke" wrote in message news:fqf4do$gq7$1 at online.de... | Marc 'BlackJack' Rintsch schrieb: | > On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: | > | >> Apart from doing something like | >> a=[0,0,0] | >> b=[0,0,0] | >> c=[0,0,0] | >> d=[a,b,c] | >> | >> is there a better way of creating d?? | > | > a = [[0] * 3 for dummy in xrange(3)] | | Why not simply [[0]*3]*3 ? Because that is essentially the same as what the OP originally did, which does not work as he wanted. From castironpi at gmail.com Fri Mar 7 14:36:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:36:52 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <218ee049-13a6-4e97-82b7-5087e635efb7@z17g2000hsg.googlegroups.com> > And so on and so forth. ?The tricky bit is how to tell the difference > between Day, Month and Year. There isn't one. From python at rcn.com Wed Mar 26 04:00:30 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 26 Mar 2008 01:00:30 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: On Mar 25, 4:30?pm, kellygreer1 wrote: > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] If the elements are hashable, try this: lsttwo = sorted(set(lstone)) If not hashable, try: lsttwo = [k for k,v in itertools.groupby(sorted(lstone))] Raymond From mr.ecik at gmail.com Wed Mar 26 18:04:07 2008 From: mr.ecik at gmail.com (=?ISO-8859-2?Q?Micha=B3_Bentkowski?=) Date: Wed, 26 Mar 2008 23:04:07 +0100 Subject: Why does python behave so? (removing list items) Message-ID: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Why does python create a reference here, not just copy the variable? >>> j=range(0,6) >>> k=j >>> del j[0] >>> j [1, 2, 3, 4, 5] >>> k [1, 2, 3, 4, 5] Shouldn't k remain the same? -- Micha? Bentkowski mr.ecik at gmail.com From apatheticagnostic at gmail.com Mon Mar 3 10:43:32 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Mon, 3 Mar 2008 07:43:32 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 2, 6:16 am, David Cook wrote: > On 2008-03-02, Jeff Schwab wrote: > > > Python In A Nutshell: > >http://www.oreilly.com/catalog/pythonian2/ > > Another vote for the Nutshell book, which I find a very useful and practical > book. > > I never found the "Dive in" book useful. > > Dave Cook Here's another vote for Python in a Nutshell. If you have a lot of experience with other languages, it should be all you need to get up to speed with python quickly. From jerry.fleming at saybot.com Mon Mar 17 21:57:25 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Tue, 18 Mar 2008 09:57:25 +0800 Subject: ctypes in python failed to honor c_int Message-ID: Hi, I have a binary file written with c structures. Each record contains a null-terminated string followed by two 4-bytes integers. I wrote a small segment of python code to parse this file in this way: [coe] #!/usr/bin/python from ctypes import * class Entry(Structure): _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) idx = open('x.idx', 'rb') str = idx.read(1000) obj = Entry(str) print obj.w print obj.s print obj.l [/code] where the field w is the string, and s and l are the integers. Problem is that, I can only get the strings, not the integers. Well, I did got integers, but they are all zeros. What should I do to get the real numbers? Thanks for help. - Jerry From bob.martin at excite.com Mon Mar 10 15:21:14 2008 From: bob.martin at excite.com (Bob Martin) Date: Mon, 10 Mar 2008 19:21:14 GMT Subject: Distributed App - C++ with Python for Portability? References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: in 337513 20080310 115744 "Diez B. Roggisch" wrote: >Roopan wrote: > >> Hello! >> >> I am looking at developing an enterprise-grade distributed data >> sharing application - key requirements are productivity and platform >> portability. >> >> Will it be sensible to use C++ for performance-critical sections and >> Python for all the glue logic. >> >> Pls comment from your *experiences* how Python scales to large >> projects( > 200KLOC). >> I assume the C++/Python binding is fairly painless. > >It depends. There are good wrappers out there, I personally prefer SIP. >However, a mixed language environment is always a PITA, especially for >distribution. > >If you can, write everything in python. Identify bottlenecks, and if you >must, I suggest using C + ctypes for performance-critical code. > >Obviously it's a matter of taste, but C++ is a beast, and getting it to work >seamless under varying compilers and OSes could be avoided using plain C. > >Diez Java is more portable than most other languages, especially if your app needs a gui. From larry.cebuala at gmail.com Tue Mar 18 02:00:26 2008 From: larry.cebuala at gmail.com (Larry) Date: Mon, 17 Mar 2008 23:00:26 -0700 (PDT) Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> <7xod9cvbq3.fsf@ruckus.brouhaha.com> Message-ID: On Mar 18, 1:32?pm, Paul Rubin wrote: > Larry writes: > > It seems to me that Python always add intervening spaces between data > > elements when writing to a file > > It's just the print statement that does that. I doubt that. I tried one small file, I opened it using the application I mentioned, the display said like data, NaN, data, NaN... I even went further to opening the file using notepad, and did a search-and-replace for space characters. The result was what I desired: data,data,data... From tms at zeetix.com Mon Mar 17 08:17:23 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Mon, 17 Mar 2008 08:17:23 -0400 Subject: No subject Message-ID: <009a01c88828$db718b20$0200a8c0@TMSMAIN> "Duncan Booth" wrote in message news:Xns9A64693269C16duncanbooth at 127.0.0.1... > I've also just spent a while getting simplejson 1.7.4 to install on a > (non- > windows) system without a C compiler. > > The trick is to unzip the tar file and then before you try to install it > delete everything in simplejson.egg-info. Then 'setup.py install' will run > to completion and while it warns about 'speedups are not enabled.' it > doesn't take it as fatal error. > > Without this step it preserves the reference to native_libs.txt in > SOURCES.txt even though the native_libs.txt file itself gets deleted. I had no trouble getting it to install without the speedups -- but the primary reason I upgraded was to take advantage of the speedups! From arnodel at googlemail.com Sun Mar 23 03:56:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Mar 2008 00:56:54 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Message-ID: On Mar 22, 9:11?pm, rh0dium wrote: > Hi all, Hi, > I am struggling with parsing the following data: > > test1 = """ > Technology ? ? ?{ > ? ? ? ? ? ? ? ? name ? ? ? ? ? ? ? ? ? ? ? ? ? ?= "gtc" > ? ? ? ? ? ? ? ? dielectric ? ? ? ? ? ? ? ? ? ? ?= 2.75e-05 [...] I know it's cheating, but the grammar of your example is actually quite simple and the values are valid python expressions, so here is a solution without pyparsing (or regexps, for that matter). *WARNING* it uses the exec statement. from textwrap import dedent def parse(txt): globs, parsed = {}, {} units = txt.strip().split('}')[:-1] for unit in units: label, params = unit.split('{') paramdict = {} exec dedent(params) in globs, paramdict try: label, key = label.split() parsed.setdefault(label, {})[eval(key)] = paramdict except ValueError: parsed[label.strip()] = paramdict return parsed >>> p = parse(test1) >>> p['Layer']['PRBOUNDARY'] {'maskName': '', 'defaultWidth': 0, 'color': 'cyan', 'pattern': 'blank', 'layerNumber': 0, 'minSpacing': 0, 'blink': 0, 'minWidth': 0, 'visible': 1, 'pitch': 0, 'selectable': 1, 'lineStyle': 'solid'} >>> p['Layer']['METAL2']['maskName'] 'metal2' >>> p['Technology']['gridResolution'] 5 >>> HTH -- Arnaud From sjmachin at lexicon.net Mon Mar 10 06:58:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 03:58:23 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> Message-ID: <79ba8d61-6411-4a5f-862d-43806fb8ed75@d21g2000prf.googlegroups.com> On Mar 10, 9:11 pm, Matt Nordhoff wrote: > castiro... at gmail.com wrote: > >> I believe Python automatically creates and caches int objects for 0-256, > >> so whenever you use them, they refer to the same exact objects. Since > >> ints are immutable, it doesn't matter. > > > One of the biggest hits on start-up time, by the way. ;) > > Well, the developers clearly decided it was worth it at the time. Who > knows, perhaps that's changed since then. > -- Matt, PDFTT. Cheers, John From Afro.Systems at gmail.com Mon Mar 24 01:33:58 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sun, 23 Mar 2008 22:33:58 -0700 (PDT) Subject: encoding/decoding issue with python2.5 and pymssql Message-ID: <3a6c32fe-e7c1-4230-882d-efb3415196c1@b1g2000hsg.googlegroups.com> hi, in my table the field row_id is type of uniqueidentifier. when try to fetch the data, pymssql somehow, encodes the values in a way which yields odd results. for example: the value 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7' is represent as '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7' the only way I manged to pass this is by converting the value into varchar at the server side. I would like to solve this at the python side and not in the database for several obvious reasons see example: >>> conn = mymssql.connect(**connection_details) >>> cur = conn.cursor() >>> sql = "select row_id, cast(row_id as varchar(36)) from table_a" >>> cur.execute(sql) >>> rows = cur.fetchall() >>> rows[0] ('\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7', 'EE604EE3-4AB0-4EE7- AF4D-018124393CD7') >>> >>> From duncan.booth at invalid.invalid Mon Mar 31 14:09:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 18:09:42 GMT Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: xkenneth wrote: > Now obviously, if I test an instance of either class equal to each > other, an attribute error will be thrown, how do I handle this? I > could rewrite every __eq__ function and catch attribute errors, but > that's tedious, and seemingly unpythonic. Also, I don't want an > attribute error thrown whenever two classes are compared that don't > have the same attributes. > > I have a sneaky feeling I'm doing something completely unpythonic > here. > Surely an A isn't equal to every other object which just happens to have the same attributes 'a' and 'b'? I would have thoughts the tests want to be something like: class A: def __eq__(self,other): return (isinstance(other, A) and self.a == other.a and self.b == other.b) (and similar for B) with either an isinstance or exact match required for the type. From deets at nospam.web.de Sat Mar 22 11:44:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 16:44:23 +0100 Subject: NameError: name 'guess' is not defined In-Reply-To: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> References: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> Message-ID: <64knqtF2cdrc4U1@mid.uni-berlin.de> willkab6 at gmail.com schrieb: > I am very new to both programming and Pyhton and while trying to do > some practice using A byte of python an Error pops up on the IDLE > shell. I am using windows XP. PLease see below. > while running: > guess = int(raw_input('Enter an integer : ')) > > if guess == number: > print 'Congratulations, you guessed it.' > running = False # this causes the while loop to stop > elif guess < number: > print 'No, it is a little higher than that.' > else: > print 'No, it is a little lower than that.' > else: > print 'The while loop is over.' > # Do anything else you want to do here > > print 'Done' > > After typing the above as the book says, I get the error NameError: > name 'guess' is not defined > What Am I doing wrong? You most certainly did NOT write the above - because in Python whitespace is significant, and thus the above would result in a syntax-error because you need to have things like if condition: something() and not if condition: something() So unless you post what you *really* entered (and make sure your NG-client/mailclient doesn't eat leading whitespace), nobody will be able to help you. Diez From seberino at spawar.navy.mil Sat Mar 29 16:49:46 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Sat, 29 Mar 2008 13:49:46 -0700 (PDT) Subject: What motivates all unpaid volunteers at Pycon? Message-ID: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> I was impressed and humbled by all the unpaid volunteers at Pycon. I was wondering what motivated so many people to give so much to the Python community. (I have my guesses but I'd rather listen than assume I know.) Any ideas? Chris From castironpi at gmail.com Wed Mar 5 22:43:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:43:52 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: <7a8a2706-10d0-4f50-b5ad-8b490e57edd5@y77g2000hsy.googlegroups.com> On Mar 5, 8:31?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 21:05:31 -0500, Terry Reedy wrote: > > If I understand your question, classes are not singletons: > >>>> ll=[] > >>>> for i in range(2): > > ?import string > > ?ll[i]=string > > Where's the IndexError? :-) > > >>>> ll[0] is ll[1] > > True > > But yes, modules are singletons in that way, at least if you go through > the import mechanism. > > >>>> for i in range(2): > > ?class C: pass > > ?ll[i] = C > > >>>> ll[0] is ll[1] > > False > > Ah, but each time around the loop you create a *new class* that just > happens to be called C. An alternative way to see similar behaviour is: > > def foo(x=None): > ? ? class C(object): > ? ? ? ? X = x > ? ? return C > > Naturally foo() is foo() gives False -- although both classes are called > C, they are different classes that just happen to have the same state. > > I accept my question about classes being singletons is not well-formed, > not even in my own mind. I guess one way of asking is, for any two class > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? >>> class metaC( type ): ... def __eq__( self, other ): ... return random.choice([ True, False ]) ... >>> class C( metaclass= metaC ): ... pass ... >>> import random >>> C==C True >>> C==C False >>> C==C False >>> C==C True >>> C==C False >>> You made me think of this. What relevance it has is open to debate. ...In a separate thread. http://en.wikipedia.org/wiki/Relevance It's my Signal-channel signal signal. From aiya.vinay at gmail.com Tue Mar 11 14:07:27 2008 From: aiya.vinay at gmail.com (Vinay Aiya) Date: Tue, 11 Mar 2008 23:37:27 +0530 Subject: help regarding xml parser modules Message-ID: Hello, Can any one help for error in following code. actually i want to map the element name with its data between start and end tag , but i am unable to do so. here is the code which i am trying for please do reply if i am not on right track. import xml.sax.handler class BookHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inTitle1 = 0 self.inTitle2 = 0 self.mapping1 = {} self.mapping2 = {} def startElement(self, name, attributes="NULL"): #attributes="None" if name == "emph3": self.buffer1 = "" self.inTitle1 = 1 # self.id = attributes["None"] elif name == "year": self.buffer2 = "" self.inTitle2 = 1 def characters(self,data): if self.inTitle1 == 1: self.buffer1 += data elif self.inTitle2 == 1: self.buffer2 += data def endElement(self,name): if name == "year": self.inTitle2 = 0 self.mapping2[self.name] = self.buffer2 elif name =="emph3": self.inTitle1 =0 self.mapping1[self.name] = self.buffer1 this is an xml file an example # # # Jose Joaquin Avila # 1929 # # Yiye Avila # 1941 # # This is main file import xml.sax import try1 import pprint parser = xml.sax.make_parser() handler = try1.BookHandler() parser.setContentHandler(handler) parser.parse("tp.xml") pprint.pprint(handler.mapping1) pprint.pprint(handler.mapping2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From userprogoogle-139 at yahoo.co.uk Tue Mar 18 12:27:46 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Tue, 18 Mar 2008 09:27:46 -0700 (PDT) Subject: Need Help Starting Out References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <4aa24daf-4f7b-405e-83c2-d1face854ed1@s37g2000prg.googlegroups.com> > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. Hi, For database stuff you can plug directly into either MySQL or SQLite. For MySQL you need to install a third party library which you can get from: http://sourceforge.net/projects/mysql-python I think SQLite support is now included in Python 2.5, all you need to do is type "import sqlite3", and away it goes. You will of course need to install SQLite, just search for it online. I found SQlite more than sufficient for any single user non-web based apps. On the client side you can use these library and if you like build a free standing app to run everything. For GUI toolkits you can do worse than download and install wxPython, which again is free (www.wxpython.org). If you want to dabble in games programming there is also PyGame. If you want to build free standing applications you can use Py2Exe (Windows) and Py2App (Mac), just Google them and they will appear. You may at times find Python a little slow, and you can even get round that problem in Windows and Intel based Macs by using Psyco (again just Google). It can speed up your code by quite a large margin. Hope these help you get started... Rod From gagsl-py2 at yahoo.com.ar Fri Mar 7 09:49:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 12:49:39 -0200 Subject: How to clear a list (3 ways). References: Message-ID: En Fri, 07 Mar 2008 09:39:05 -0200, escribi?: > Executive summary : What idiom do you use for resetting a list ? > lst = |] # (1) > lst[:] = [] # (2) > del lst[:] # (3) (3) if I want to keep the same list else (1) An example when (1) is desirable: # generate lines of text not exceeding 40 chars # yields a list of words forming a line def gen_lines(words): line = [] width = 0 for word in words: if width + len(word) + 1 > 40: yield line # <<< del line[:] # <<< width = 0 line.append(word) width += len(word) + 1 yield line import string words = string.__doc__.split() # some text lines = list(gen_lines(words)) print lines [['considered', 'printable'], ['considered', 'printable'], ['considered', 'print able'], ['considered', 'printable'], ['considered', 'printable'], ... In this case, yielding always the same object isn't a good idea if the consumer doesn't process it immediately. Changing the generator function to use the method (1) gives the expected result (or, one could say, lessens the coupling between the generator and its consumer). -- Gabriel Genellina From frank at chagford.com Tue Mar 11 01:17:16 2008 From: frank at chagford.com (Frank Millman) Date: Mon, 10 Mar 2008 22:17:16 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: Gilles Ganault wrote: > On Mon, 10 Mar 2008 11:27:06 -0400, "Malcolm Greene" > wrote: > >Any suggestions on an alternative Python client-side GUI library (pyQT > >?) or tips on where I can find out more about wxPython/wxWidget > >problems? > > One thing that bothers me is that it seems like there's no ecosystem > around it, so the only widgets available are those that come from > wxWidgets proper. > > For instance, I find the grid object a bit poor-featured compared to > what's available for VB6, .Net, or Delphi, but I didn't find > alternatives. I do not know if this helps, but here is an extract from a recent post to the wxPython mailing list from Robin Dunn, the main developer of wxPython - "The new wxDataViewCtrl coming in 2.9 might make this unnecessary. Think of it as a wxListCtrl that is always in virtual mode with a plug- in data model, can optionally have hierarchical data (like wxTreeCtrl) in one of the columns, and where every column can have a custom renderer/editor for the cells like wxGrid. And it uses the native controls on Mac and GTK. I've been working on the wrappers for it off and on over the past few weeks and while it is a complex beast, it will probably be easier to use than wxGrid in most cases and easier than wxListCtrl in some cases too." I also strongly recommend using the mailing list for any questions, problems, or feature requests. Robin is a very active contributor to the list, and frequently provides very insightful answers. Also there are a number of other active contributors, some of whom have designed their own composite widgets using the underlying components of the toolkit, and are happy to share them. Frank Millman From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 17:25:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 22:25:53 -0000 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> Message-ID: <13su7fhdj3rdk70@corp.supernews.com> On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote: > Classes and modules are really similar. In Python they're really > *really* similar. Yes they are. Both are namespaces. The very last line of the Zen of Python says: >>> import this ... Namespaces are one honking great idea -- let's do more of those! http://en.wikipedia.org/wiki/Namespace -- Steven From mdboldin at gmail.com Sat Mar 1 10:00:17 2008 From: mdboldin at gmail.com (mdboldin at gmail.com) Date: Sat, 1 Mar 2008 07:00:17 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> Message-ID: <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> Steve, I want to make sure I understand. My test code is below, where ph serves as a placeholder. I am preparing for a case where the number of ? will be driven by the length of the insert record (dx) dtable= 'DTABLE3' print 'Insert data into table %s, version #3' % dtable ph= '?, ?, ?, ?' sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) t0a=time.time() for dx in d1: curs1.execute(sqlx,dx) print (time.time()-t0a) print curs1.lastrowid conn1.commit() I think you are saying that sqlx is re-evaluated in each loop, i.e. not the same as pure hard coding of sqlx= 'INSERT INTO DTABLE3 VALUES ( ?, ?, ?, ? ) ' Is that right? Hence (if I understand python convention), this can be solved by adding sqlx= copy.copy(sqlx) before the looping. And in tests adding this step saved about 5-10% in time. And yes, I can see why (B) is always better from a security standpoint. The python solutions for problems such as there are a great help for people like me, in the sense that the most secure way does not have a speed penalty (and in this case is 3-4x faster). From gagsl-py2 at yahoo.com.ar Sun Mar 30 19:36:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 20:36:53 -0300 Subject: Creating Class Objects in Loop References: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 19:59:14 -0300, Fish escribi?: > Hello Folks, > I am reading a CSV file and based on that I am creating TestCase(my > own defined class) objects in a for loop. The problem is each time I > create a new TestCase object in loop, previous objects data is already > copied in that object. See this FAQ entry: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects > ======= Problem Code > > The function snippet reading CSV and creating TestCase objects is > [code] > tcLst = [] > # CSV file is read in variable 'lines' Try to use the standard csv module instead; it's fairly easy. > def returnTcLst(path): > fp = open(path) > lines = fp.readlines() > for line in lines: Instead of those two lines, you could use: for line in fp: (readlines() has to read the whole file into memory; files are their own line iterators) > tc.setPcap(line[:i].strip()) getters/setters are not usually used in Python because they offer no advantage over directly using an attribute: tc.pcap = line[:i].strip() > tcLst.append(tc) > del tc Why "del tc"? That doesn't invoke the destructor, just removes the name "tc" from the local namespace. (The object tc refers to isn't destroyed yet because it has at least one reference: it's contained in the tcLst list) > class TestCase(object): > def __init__(self, pcap = None, sids = []): > self.__Pcap = pcap > self.__lstSid = sids As you can see in the FAQ entry, the common idiom is to write: def __init__(self, pcap = None, sids = None): if sids is None: sids = [] self.Pcap = pcap self._lstSid = sids Note that I've changed the __names; use __ when you expect a name collision with a subclass. For "implementation only" attributes, use a single underscore; based on your appendSid method, lstSid looks like it's used in this way. > def setPcap(self, path): > self.__Pcap = path This method isn't necesary anymore. > def appendSid(self, sid): > def __str__(self): Should be changed accordingly. -- Gabriel Genellina From rschroev_nospam_ml at fastmail.fm Fri Mar 14 18:16:43 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Mar 2008 23:16:43 +0100 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: castironpi at gmail.com schreef: > On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>> Subject: RIP: Joseph Weizenbaum >>> Creator of Eliza: >>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>> -- >> How do you feel about creator of Eliza? > > What is Eliza? Does that question interest you? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ron.longo at cox.net Thu Mar 20 16:15:47 2008 From: ron.longo at cox.net (Ron Provost) Date: Thu, 20 Mar 2008 16:15:47 -0400 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module inPy3.0] References: Message-ID: <00b801c88ac7$2f643340$6501a8c0@aristotle> I would really hate to see Tkinter removed from 3.0. Because it's part of the distribution and extremely easy to create simple GUIs I use it all the time. Isn't Python supposed to be a "Batteries Included" language? Can that be said anymore without a GUI library? And do we want to drop Tkinter only now, when tk seems to finally be getting renewed attention after years of neglect? ----- Original Message ----- From: "Daniel Fetchinson" To: Sent: Thursday, March 20, 2008 3:39 AM Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module inPy3.0] >> Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , >> and saw that the repr module was slated for vaporization. I've only >> used the module a few times ever. I'm curious if the community wants >> it kept around or whether it is considered clutter. >> >> The PEP is going to be finalized soon, so if you have issues with it, >> they should be sent to the PEP author or brought up on the list, >> http://mail.python.org/mailman/listinfo/stdlib-sig . > > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: > > Each module to be removed needs to have a justification as to why it > should no longer be distributed with Python. > > then goes on with, > > With so many other GUI options out there that are considered better > than Tkinter, it might be best to remove Tkinter from the stdlib and > make it an externally maintained package. > > I don't get it. There are many [insert your favorite software > component] options outside of the python core that are considered > better than the one coming with python, yet they don't get removed. > All network servers for example could be thrown out because twisted is > considered better. This just doesn't make sense to me. Tkinter is > great for its purpose, typical use cases are creating a simple GUI > composed of a couple of components only. You can nicely do this with > tkinter and the large user base shows that it's a real need real > people have. Sure, for fancy GUI stuff there are better options but > for quick and simple things tkinter is just great. And last time I > checked python comes with batteries included so why sould I need to > search and download a third party package for such a common use case? > > Thoughts anyone? > > Cheers, > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list From grahn+nntp at snipabacken.se Mon Mar 31 06:30:54 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 31 Mar 2008 10:30:54 GMT Subject: Where can I find : References: <13uu56hn1vdqb9d@corp.supernews.com> <13v0997i28t8i90@corp.supernews.com> Message-ID: On Sun, 30 Mar 2008 16:41:31 -0700, Dennis Lee Bieber wrote: > On 30 Mar 2008 23:07:02 GMT, Jorgen Grahn > declaimed the following in comp.lang.python: > >> >> He *might* simply be talking about if, for, while, break and so on -- >> things which control program flow. >> > Which /is/ what I was referring to... with regards to structuring > the usage of said in a safe&sane manner Oh, sorry. I see that now. I was thinking of flow control as in communication protocols, preventing a fast sender from flooding a receiver and so on. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From micah at hollister.bcsweb.com Wed Mar 5 22:38:50 2008 From: micah at hollister.bcsweb.com (Micah Cowan) Date: Thu, 06 Mar 2008 03:38:50 GMT Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: Steven D'Aprano writes: > I recall that Python guarantees that module objects are singletons, and > that this must hold for any implementation, not just CPython: you can > only ever create one instance of a module via the import mechanism. But > my google-foo is obviously weak today, I cannot find where the Python > language reference guarantees that. Can somebody please point me at the > link making that guarantee? It's not an absolute strict guarantee; it's just implied by the fact that "import" uses any appropriate objects already found in sys.modules. >>> import sys >>> ll = [] >>> for i in range(2): ... import string ... ll.append(string) ... del sys.modules['string'] ... >>> ll[0] is ll[1] False (I'm sure there are very good reasons never to do what I just did there.) -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From castironpi at gmail.com Sat Mar 1 20:58:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 17:58:05 -0800 (PST) Subject: Where's GUI for Python? References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> <62uauaF2400f1U1@mid.individual.net> Message-ID: On Mar 1, 6:49?pm, "K Viltersten" wrote: > >> When that fails, try without the stutter > > >> import tkinter > > > I must be doing something wrong because > > neither tkinter nor tkininter works. > > I tried both with and without stuttering. > > I even asked my wife to stutter some but, > > sadly, to no avail. > > > When Tim Chase mentioned "battery-installed", > > i interpreted it as "all is there". It seems > > that either > > a) not all the batteries are installed in my > > version (v2.5.2) > > or > > b) some setup/linkage needs to be performed > > in order to get the GUI running. > > > The error itself is: > > ImportError: No module named tkinter > > > Suggestions? > > Here's a suggestion. Python is case-sensitive, > while the users trying to help you are not. > When they say "tininkerbell", they may mean > "Tinkerbell". Check with "help()", then > "modules" and see if it's installed or not. > > Sincerely > Yourself > > :) > > (Seriously speaking - i'm thankful.)- Hide quoted text - > > - Show quoted text - AmbiguityWarning: Variables 'tklst' and 'tklist' resemble 'tkst'. Automatic snap-to-slot has been disabled. From strombrg at gmail.com Sat Mar 8 12:39:17 2008 From: strombrg at gmail.com (Dan Stromberg) Date: Sat, 08 Mar 2008 17:39:17 GMT Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: <9bAAj.15017$0o7.13276@newssvr13.news.prodigy.net> On Sun, 02 Mar 2008 23:05:27 -0500, Roy Smith wrote: > In article > , > Gabriel Genellina wrote: > >> On 2 mar, 17:21, castiro... at gmail.com wrote: >> >> > This worked: >> > >> > import socket >> > from time import time >> > >> > for i in range( 20 ): >> > ? ? HOST = '' >> > ? ? PORT = 80 #<---- >> > ? ? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> > ? ? s.bind((HOST, PORT)) >> > ? ? print( 'listen' ) >> > ? ? s.listen(1) >> > ? ? conn, addr = s.accept() >> > ? ? print( 'connected', addr ) >> > ? ? print( conn.recv( 4096 ) ) #<---- >> > ? ? conn.send( bytes('test %f> > html>'%time(),'ascii') ) >> > ? ? conn.close() #<---- >> > ? ? s.close() >> > >> > ... and connect with a browser: ?http://localhost/if it's internet >> > exploder. >> >> Note that there is no need (nor is desirable) to close and rebind the >> listening socket for each connection. > > I'd say, "nor is desirable", is an understatement. On most systems, an > attempt to re-bind to a given port number soon after it was unbound will > fail (unless you utter magic ioctl incantations). This will manifest > itself in the s.bind() call raising an exception on the *second* pass > through the loop. I believe the incantation may be setsockopt(), not ioctl(), but if there's an ioctl() way of doing it, i'd be interested in seeing it. From sjmachin at lexicon.net Thu Mar 27 04:00:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 01:00:01 -0700 (PDT) Subject: do 'os.path' include 'os' for us? References: Message-ID: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> On Mar 27, 6:41?pm, Jerry Fleming wrote: > Hi, > > I wrote a python script to list files in a directory but somehow did it > wrongly by importing os.path instead of os. To my astonishment, it works > just as charm: > #!/usr/bin/python > import os.path > for file in os.listdir('/root/'): > ? ? ? ? print file > > I was wondering why? os.path doesn't contain listdir, why there is no > complaint like 'os: unknown name'? Does this mean, instead of importing > os, we can import os.path? > import os.path in effect imports os, and then os.path, and injects the latter into the former as an attribute. If it didn't, then when you tried to use (say) os.path.join, it would raise an exception. Why don't you do some experimentation at the interactive prompt e.g. import os.path type(os) dir(os) a = os a.path a = nonesuch # The above will show you what the actual meesage is instead of complaint like 'os: unknown name' :-) HTH, John From furkankuru at gmail.com Tue Mar 25 08:48:03 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:48:03 +0200 Subject: Inheritance question In-Reply-To: <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: <3a4a8f930803250548m28f74b7cye1f3bc2de06c74a@mail.gmail.com> a = super(Foo, self).getid() should be a = super(FooSon, self).getid() On Tue, Mar 25, 2008 at 2:34 PM, Tzury Bar Yochay wrote: > > Rather than use Foo.bar(), use this syntax to call methods of the > > super class: > > > > super(ParentClass, self).method() > > Hi Jeff, > here is the nw version which cause an error > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = super(Foo, self).getid() > b = self.id > return '%d.%d' % (a,b) > > > FooSon().getid() > > > Traceback (most recent call last): > File "a.py", line 19, in > FooSon().getid() > File "a.py", line 14, in getid > a = super(Foo, self).getid() > AttributeError: 'super' object has no attribute 'getid' > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From spe.stani.be at gmail.com Sat Mar 1 17:03:47 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 1 Mar 2008 14:03:47 -0800 (PST) Subject: Please test Phatch on Windows (was Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL) References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: I have been working the last couple of days purely on bug fixing and to port the code of Phatch fully to Windows as there were many issues. This has improved: - Phatch can now create droplets on Windows (win32 extensions required) - Installed fonts are retrieved from the Windows registry - Image file dialogs are now working correctly - Missing icons are added (including a phatch.ico) and are now displayed in the windows titlebars - Image Inspector was missing a panel - Preview in Image Inspector now displays correctly - (...) Besides that Phatch now features for all platforms: - fonts can be defined with a nice dropdown autocomplete list - drop down lists with convenient values in all actions - the action masks now ships with some predefined masks (such as torn edges) - right click in the actions dialog box to see the source of an action - View>Droplet nows shows the name of the action box rendered in the logo - Dutch translation is 100% complete As such no new features have been added, but the user experience feels much more polished now. Please read *carefully* the installation instructions first: http://photobatch.wikidot.com/install#toc6 People who have been using Phatch before should clear their font cache (if it exists). Simply delete the file: C:\Documents and Settings\Username\.phatch\fonts I did the Phatch port on a Windows 2000 machine, so I am curious to hear how Phatch works on Windows XP and Vista. I will fix any bug (as far as possible) which is reported quickly in the next couple of days. You can help translating Phatch here: https://translations.launchpad.net/phatch/trunk/+pots/phatch Thanks in advance, Stani On 18 feb, 15:58, "SPE - Stani's Python Editor" wrote: > I'm pleased to announce the release ofPhatchwhich is a > powerful batch processor and renamer.Phatchexposes a big part of the > Python Imaging Library through an user friendly GUI. (It is using > python-pyexiv2 to offer more extensive EXIF and IPTC support.)Phatch > is not targeted at manipulating individual pictures (such as with > Gimp), but repeating the same actions on hundreds or thousands of > images. > > If you know PIL and have some nice recipes laying around, it is very > easy to write plugins asPhatchgenerates the corresponding GUI > automagically just like in Django. Any existings PIL scripts can be > added very easily. Let me know if you want to contribute or have any > questions. > > Homepage:http://photobatch.stani.be(free download link below) > Tutorials:http://photobatch.wikidot.com/tutorials > Translations:https://translations.launchpad.net/phatch/trunk/+pots/phatch > License: GPLv3 > Screenshot:http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg > (the perspective and reflection is produced byPhatchitself) > > Phatchhas many features, like: > - EXIF information inspector with thumbnail > - limit jpeg file size when saving > - tons of actions organized by tags (including perspective, round > corners, shadow, reflection, ...) > - console version (Phatchcan now run without a gui on servers) > - batch rename and copy files based on exif metadata > - data stamping (http://photobatch.wikidot.com) > - online documentation wiki (http://photobatch.wikidot.com) > > Linux only features: > - desktop or panel droplets on which images or folders can be dropped > (will be ported to Windows & Mac) > - Nautilus and desktop integration (with its own mime type and > nautilus extension) > - manpage with examples > > With python-pyexiv2 the following featues are added: > - embedding the original EXIF and IPTC tags in the image > > All actions mostly have a separate pil function in their source code, > so they could be read as a recipe book for PIL: > * Auto Contrast - Maximize image contrast > * Background - Put colour under transparent image > * Border - Crop or add border to all sides > * Brightness - Adjust brightness from black to white > * Canvas - Crop the image or enlarge canvas without resizing the image > * Colorize - Colorize grayscale image > * Common - Copies the most common pixel value > * Contrast - Adjust from grey to black & white > * Convert Mode - Convert the color mode of an image (grayscale, RGB, > RGBA or CMYK) > * Copy - Copy image file > * Effect - Blur, Sharpen, Emboss, Smooth, ... > * Equalize - Equalize the image histogram > * Fit - Downsize and crop image with fixed ratio > * Grayscale - Fade all colours to gray > * Invert - Invert the colors of the image (negative) > * Maximum - Copies the maximum pixel value > * Mask - Apply a transparency mask > * Median - Copies the median pixel value > * Minimum - Copies the minimum pixel value > * Offset - Offset by distance and wrap around > * Posterize - Reduce the number of bits of colour channel > * Perspective - Shear 2d or 3d > * Rank - Copies the rank'th pixel value > * Reflect - Drops a reflection > * Rename - Rename image file > * Rotate - Rotate with random angle > * Round - Round or crossed corners with variable radius and corners > * Saturation - Adjust saturation from grayscale to high > * Save - Save an image with variable compression in different types > * Scale - Scale an image with different resample filters. > * Shadow - Drop a blurred shadow under a photo with variable position, > blur and color > * Solarize - Invert all pixel values above threshold > * Text - Write text at a given position > * Transpose - Flip or rotate an image by 90 degrees > * Watermark - Apply a watermark image with variable placement (offset, > scaling, tiling) and opacity > > I developPhatchon Ubuntu/Linux, but I have tested and polished it > regularly on Windows and Mac Os X. (Only the droplet functionality > needs to be ported.)Phatchis submitted to Debian unstable and > Ubuntu Hardy. Packagers for other platforms are welcome. > > Requirements: > - PIL 1.1.5 or higher > - wxPython 2.6 or higher > - pyexiv2 (optional) > - python nautilus bindings (optional) > > Best regards, > Stani > --http://pythonide.stani.be From dblubaugh at belcan.com Wed Mar 19 12:17:01 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Wed, 19 Mar 2008 12:17:01 -0400 Subject: Python to C/C++ Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> To All, Has anyone worked with a translator that will translate python to c/c++ source code? I know that there is already one translator of this nature (shedskin compiler) out there. However, it is still in the beta stage of development. Does anyone know of a more developed version of a translator of this nature? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 23:20:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 03:20:34 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> Message-ID: <13uu1o25912ulb0@corp.supernews.com> On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote: > Or maybe: > > def main(): > global func > func = factory() > return timeit.Timer('func()', 'from __main__ import func').timeit() Alas, this does not work, because all the Timer instances share the same state. import timeit, time def test_timer(func1, func2): global gFUNC gFUNC = func1 T1 = timeit.Timer('gFUNC()', 'from __main__ import gFUNC') gFUNC = func2 T2 = timeit.Timer('gFUNC()', 'from __main__ import gFUNC') print "Calling %s" % func1.__name__ T1.repeat(3, 1) print "Calling %s" % func2.__name__ T2.repeat(3, 1) def functionA(): print "Function A" def functionB(): print "Function B" And here's the results: >>> test_timer(functionA, functionB) Calling functionA Function B Function B Function B Calling functionB Function B Function B Function B -- Steven From davidj411 at gmail.com Tue Mar 11 09:49:49 2008 From: davidj411 at gmail.com (davidj411) Date: Tue, 11 Mar 2008 06:49:49 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same Message-ID: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> anydbm and dictionary{} seem like they both have a single key and key value. Can't you put more information into a DBM file or link tables? I just don't see the benefit except for the persistent storage. d= dbm.open('c:\\temp\\mydb.dat','n') It has the following interface (key and data are strings): d[key] = data # store data at key (may override data at # existing key) data = d[key] # retrieve data at key (raise KeyError if no # such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = key in d # true if the key exists list = d.keys() # return a list of all existing keys (slow!) From istvan.albert at gmail.com Tue Mar 4 16:00:34 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Tue, 4 Mar 2008 13:00:34 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> Message-ID: <042d507d-f53d-4219-be6e-d6b7a1f1d6c4@s8g2000prg.googlegroups.com> On Mar 4, 3:13 pm, Mensanator wrote: > But what if _I_ wanted to make a repeatable sequence for test > purposes? Wouldn't factorint() destroy my attempt by reseeding > on every call? Would it? It may just be that you are now itching to see a problem even where there isn't one. i. From watine at cines.fr Thu Mar 13 07:13:54 2008 From: watine at cines.fr (Benjamin Watine) Date: Thu, 13 Mar 2008 12:13:54 +0100 Subject: How to send a var to stdin of an external software Message-ID: <47D90C72.2020401@cines.fr> Hi the list, I need to send a var to stdin of an external soft ("cat" command for example). How can I do this ? I would like a function like that : theFunction ('cat -', stdin=myVar) I don't need to get any return value. Another related question : Is there's a limitation of var size ? I would have var up to 10 MB. Thanks ! Ben From robert.rawlins at thinkbluemedia.co.uk Thu Mar 13 12:03:35 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 13 Mar 2008 16:03:35 -0000 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <47D94D61.9010708@jouy.inra.fr> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> <47D94D61.9010708@jouy.inra.fr> Message-ID: <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> Hi Guys, Well thanks for the response, I followed your advice and chopped out all the crap from my class, right down to the bare __init__ and the setter method, however, the problem continued to persist. However, Robert mentioned something about unindented lines which got me thinking so I deleted my tab indents on that method and replaces them with standard space-bar indents and it appears to have cured the problem. Usually my Eclipse IDE throws up an error about this but for some reason decided not too this time around, what a PITA. Thanks for the ideas guys, I appreciate it. Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Bossy Sent: 13 March 2008 15:51 To: python-list at python.org Subject: Re: "Attribute Doesnt Exist" ... but.... it does :-s Robert Rawlins wrote: > > Hello Guys, > > I've got an awfully aggravating problem which is causing some > substantial hair loss this afternoon J I want to get your ideas on > this. I am trying to invoke a particular method in one of my classes, > and I'm getting a runtime error which is telling me the attribute does > not exist. > > I'm calling the method from within __init__ yet it still seems to > think it doesn't exist. > > Code: > > # Define the RemoteDevice class. > > class *remote_device*: > > # I'm the class constructor method. > > def *__init__*(/self/, message_list=/""/): > > /self/.set_pending_list(message_list) > > def *set_pending_list*(/self/, pending_list): > > # Set the message list property. > > /self/.pending_list = message_list > > And the error message which I receive during the instantiation of the > class: > > File: "/path/to/my/files/remote_device.py", line 22, in __init__ > > self.set_pending_list(message_list) > > AttributeError: remote_device instance has no attribute 'set_pending_list' > > Does anyone have the slightest idea why this might be happening? I can > see that the code DOES have that method in it, I also know that I > don't get any compile time errors so that should be fine. I know it > mentions line 22 in the error, but I've chopped out a load of non > relevant code for the sake of posting here. > Hi, I don't get this error if I run your code. Maybe the irrelevant code causes the error: my guess is that there's a parenthesis mismatch or an undeindented line. Btw, calls to set_pending_list will fail since the name "message_list" is not defined in its scope. Please follow Chris Mellon's advice. Cheers, RB -- http://mail.python.org/mailman/listinfo/python-list From fakeaddress at nowhere.org Thu Mar 6 04:00:39 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 01:00:39 -0800 Subject: Bit twiddling floating point numbers In-Reply-To: <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> Message-ID: <%oOzj.61235$Pv2.29718@newssvr23.news.prodigy.net> Mark Dickinson wrote: > Jeff Goldfin wrote: >> I can pack and unpack a float into a long >> e.g. >> struct.unpack('I',struct.pack('f',0.123))[0] >> but then I'm not sure how to work with the resulting long. >> >> Any suggestions? > > One alternative to using struct is to use math.ldexp and math.frexp: > >>>> m, e = frexp(pi) >>>> m > 0.78539816339744828 >>>> e > 2 >>>> int(m*2**53) > 7074237752028440L > > Then you can do your bit twiddling on int(m*2**53), before using > ldexp to 'repack' the float. Ah, those are handy. Jeff described his problem: "In particular, I would like to round my float to the n most significant bits." I think this works: from math import frexp, ldexp, floor def round_mantissa(x, nbits): shifter = 1 << nbits (m, e) = frexp(x) m = floor(m * shifter + 0.5) / shifter return ldexp(m, e) -- --Bryan From nagle at animats.com Thu Mar 6 13:44:31 2008 From: nagle at animats.com (John Nagle) Date: Thu, 06 Mar 2008 10:44:31 -0800 Subject: Data aggregation In-Reply-To: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> References: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> Message-ID: <47d039a6$0$36391$742ec2ed@news.sonic.net> vedranp wrote: > I would like to avoid the step of taking data out from database in > order to process it. You can probably do this entirely within SQL. Most SQL databases, including MySQL, will let you put the result of a SELECT into a new table. John Nagle From mensanator at aol.com Sun Mar 16 12:36:03 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 16 Mar 2008 09:36:03 -0700 (PDT) Subject: Basics of Python,learning References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <73557ae7-85de-4aa2-bfc6-b02cef67d430@m34g2000hsc.googlegroups.com> On Mar 16, 11:25?am, Guido van Brakel wrote: > Hello > > Why is this not working, Why is _what_ not working? > and how can I correct it? Start over. > > > > > > > #!/usr/bin/env python > > #coding=utf-8 > > > z = raw_input ('Give numbers') > > y = z.split() > > b=[] > > > for i in y: > > ? ? ?b.append(float(i)) > > > def b(min,max,gem) > > ? ? x=min(a) > > ? ? x=gem(a) > > ? ? x=max(a) > > ? ? return a > > > print min(a) > > print max(a) > > print gem(a) > > Regards, > > -- > Guido van Brakel > Life is like a box of chocolates, you never know what you're gonna get > --- Hide quoted text - > > - Show quoted text - From siti.nurhaliza5 at gmail.com Wed Mar 26 03:15:49 2008 From: siti.nurhaliza5 at gmail.com (siti) Date: Wed, 26 Mar 2008 00:15:49 -0700 (PDT) Subject: Computer Shop center Message-ID: <27749a9c-e9ec-46bc-b242-e9deacff6d2d@s12g2000prg.googlegroups.com> Hi friends. if you wanna looking the latest original software..mobile phone...laptop..pc.. accessories... you can search at here..it will give the best price for you. Amazon has teamed up with Allianz Insurance plc who can offer you insurance on this product, covering accidental damage and breakdown.Amazon Services Europe SARL is an introducer appointed representative of Allianz Insurance plc which is authorised and regulated by the Financial Services Authority. AmazonServices Europe SARL, 5 Rue de Plaetis, L-2338, Luxembourg, is not part of the Allianz (UK) Group. The insurance is arranged, sold and administered by Allianz. By purchasing this insurance you confirm that you have read and understood the Technical details, product description and Keyfacts document provided by Allianz. This your URL http://astore.amazon.co.uk/happyfamily-21 From sam at mas.pl Thu Mar 20 11:44:43 2008 From: sam at mas.pl (sam) Date: Thu, 20 Mar 2008 16:44:43 +0100 Subject: Prototype OO In-Reply-To: <47e24b99$0$24941$426a74cc@news.free.fr> References: <47e24b99$0$24941$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers napisa?(a): > Most of the arguments in favor of prototypes seems to come to, mainly: > 1/ it lets you customize behaviour on a per-object base > 2/ it removes the mental overhead of inheritance, classes etc > > Point 1. is a non-problem in Python, since you can already add/replace > methods on a per-objec basis (ok, with a couple restrictions wrt/ > __magic__ methods and such). > > Point 2. is not (IMHO) such a problem in Python, where inheritance is > mainly an implementation detail (it's not needed for polymorphic > dispatch to work) and class hierarchy tend to be very flat, when they > even exist. > > Mainly, Python's object system is actually quite close to javascript > here. That is, you get more or less the same flexibility. And a couple > of powerful features you don't have with javascript (like hooks in the > attribute lookup mechanism), too. Thanks for precise opinion and spending your time. I think that when you use statically typed language, than you have to define classes, because compiler has to know what is allowed to do with instances of that class. But when you use dynamically typed language, then classes are redundant, because object is looked at when it is referenced. Dynamically typed language needs only objects hierarchy and you can add properties (methods, values) to that object during program execution. In dynamically typed language when you create object A that is inherited from another object B, than object A knows that B is his predecessor. So when you reference A.prop, then prop is looked in A first, then in B, then in predecessors of B, and so on. Having object A you can access its predecessor B. When you have access to object B, then you can add properties to it and these properties could be accessed by all other objects inherited from B. You can do all these things in Python. But why it uses classes? So you can say: "CLASS BASED PROGRAMMING" == "STATICALY TYPED LANGUAGE" From mensanator at aol.com Tue Mar 18 20:39:15 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Mar 2008 17:39:15 -0700 (PDT) Subject: First Program Bug (Newbie) References: Message-ID: <518f4420-19e1-4708-8b65-e44ca23da586@t54g2000hsg.googlegroups.com> On Mar 18, 6:39?pm, oog1e <""benjamin.serrato\"@G(oog1e)MAIL.com"> wrote: > Hey, big thanks to you and Gabriel for replying. I couldn't quite follow > what you did yet. What is this 'gimpy' thing gmpy. It's the GMP (Gnu Multi-Precision) C-library in a Python wrapper. It supports arbitrary precision integers, floats and rationals. Although Python has built in Big Integers, the gmpy versions can sometimes run rings around Python's. Also, lots of functions unavailable elswhere. > and where can I read about it? http://code.google.com/p/gmpy > In response: > > First: Heh, I'm a little embarrassed I didn't notice this. I thought 'I > only need to check up to half' but it didn't occur that base**2 was more > than 1/2 candidate. > > Second: I don't quite follow this. Actually, I'm not following it anymore either. For a while my test program was claiming 27 was prime. All these false primes had 0 as the remainder of candidate/2. I put this in to reject them, but I don't see the problem anymore. > > Third: Yeah, I found that bug just before, and because of, posting. > > Fourth: I used the incrementing command and incremented candidates by > two to check only odds and now the program is a lot faster. > > Thanks a lot for yall's replies. Three more things before I go. What is > the square root function in python? There's one in the math module. Use the one in gmpy if you have it. > I couldn't find the fact.py demo > script. I didn't mean return I meant 'continue'. > > > > Mensanator wrote: > > On Mar 17, 7:03 pm, Benjamin Serrato > > wrote: > >> I Found It!! The following was a post asking for help finding a bug. I > >> thought I needed help with my syntax, but just before sending I found > >> the bug on line 13. Line 13 should read: "base = 2". I would still > >> appreciate any comments on my program. Maybe there is a better way to do > >> it that I didn't think about. I know it's not that interesting but it's > >> my first one. > > >> [post] > >> I'm almost halfway through an online tutorial I found on the python.org > >> site and decided to stop and write a program for myself. I got it in my > >> head to write a program to print all the primes; the idea came from > >> another tutorial. The program prints some non-prime numbers. In a > >> comparison to lists of primes the program prints eight non-primes for > >> numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. > >> Here is the program. > > >> base = 2 > >> candidate = 3 > > >> while True: > >> ? ? ? ? while candidate % base != 0: > >> ? ? ? ? ? ? ? ? base = base + 1 > >> ? ? ? ? ? ? ? ? if base > (candidate / 2): > >> ? ? ? ? ? ? ? ? ? ? ? ? print candidate > >> ? ? ? ? ? ? ? ? ? ? ? ? candidate = candidate + 1 > >> ? ? ? ? ? ? ? ? ? ? ? ? base = 2 > >> ? ? ? ? else: > >> ? ? ? ? ? ? ? ? candidate = candidate + 1 > > >> The following is a rundown of the program. > > >> candidate: A possible prime number. > >> base: Start point for divisibility testing. > >> outer while loop: Causes the program to loop. > >> inner while loop: Obviously, checks if 'candidate' mod 'base' equals > >> zero. If not base is incremented by one then 'if loop'. > >> if loop: After base has been incremented this checks whether all the > >> possible divisors have been used up. If they have then 'candidate' must > >> be prime. So, candidate is printed, a new candidate is chosen and the > >> base is reset. > >> else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is > >> not prime and a new candidate is chosen. > > >> I realize yall probably didn't need all that. > > >> At first I tried to use 'return' on the 'else' block to cause the > >> program to loop, but I don't understand 'return' yet and that didn't > >> work. So, I put the rest into another while loop and was really happy to > >> find it worked but the program prints some non-prime numbers. > > >> Thanks, Benjamin Serrato > > >> P.S. What is the chance I'll get spam for using my real email address? I > >> currently don't get any so... > >> [/post] > > > Several items. > > > First, you don't need to check base larger than sqrt(candidate). > > > Second, see comments following dc. > > > Third, you need to add base = 2 to end of program, otherwise next > > candidate starts base where previous candidate left off. > > > Fourth, use +=1 to increment. > > > Finally, throw this away and use gmpy. :-) > > > import gmpy ?# for Quality Assurance > > base = 2 > > candidate = 3 > > p = 0 ? ? ? ? ? ? ? ? ? ? ? ? ? ?# prime count > > while p<100: ? ? ? ? ? ? ? ? ? ? # limit the loop to 100 primes > > ? while candidate % base != 0: > > ? ? base += 1 > > ? ? #if base > (candidate / 2): > > ? ? if base > (gmpy.sqrt(candidate)): ?# only need to test to > > sqrt(candidate) > > ? ? ? dc = divmod(candidate,2) ? ? ? ? # remainder==0 gives false > > primes > > ? ? ? if dc[1]==1: > > ? ? ? ? # > > ? ? ? ? # the gmpy functions are for QA, verifies that what you call a > > prime > > ? ? ? ? # really is one and the next_prime makes sure you don't skip > > any > > ? ? ? ? # these can be removed once working > > ? ? ? ? # > > ? ? ? ? print > > candidate,gmpy.is_prime(candidate)>0,gmpy.next_prime(candidate) > > ? ? ? ? p += 1 > > ? ? ? ? candidate += 1 > > ? ? ? ? base = 2 > > ? ? ? else: > > ? ? ? ? candidate += 1 ? ? ? ? ? ? ? ? # false prime, reset > > ? ? ? ? base = 2 > > ? else: > > ? ? candidate += 1 > > ? ? base = 2 ? ? ? ? ? ? ? ? ? ? ? ? ? # failure to reset causes false > > primes > > > ## ?3 True 5 > > ## ?5 True 7 > > ## ?7 True 11 > > ## ?11 True 13 > > ## ?13 True 17 > > ## ?17 True 19 > > ## ?19 True 23 > > ## ?23 True 29 > > ## ?29 True 31 > > ## ?31 True 37 > > ## ?37 True 41 > > ## ?41 True 43 > > ## ?43 True 47 > > ## ?47 True 53 > > ## ?53 True 59 > > ## ?59 True 61 > > ## ?61 True 67 > > ## ?67 True 71 > > ## ?71 True 73 > > ## ?73 True 79 > > ## ?79 True 83 > > ## ?83 True 89 > > ## ?89 True 97 > > ## ?97 True 101 > > ## ?101 True 103 > > ## ?103 True 107 > > ## ?107 True 109 > > ## ?109 True 113 > > ## ?113 True 127 > > ## ?127 True 131 > > ## ?131 True 137 > > ## ?137 True 139 > > ## ?139 True 149 > > ## ?149 True 151 > > ## ?151 True 157 > > ## ?157 True 163 > > ## ?163 True 167 > > ## ?167 True 173 > > ## ?173 True 179 > > ## ?179 True 181 > > ## ?181 True 191 > > ## ?191 True 193 > > ## ?193 True 197 > > ## ?197 True 199 > > ## ?199 True 211 > > ## ?211 True 223 > > ## ?223 True 227 > > ## ?227 True 229 > > ## ?229 True 233 > > ## ?233 True 239 > > ## ?239 True 241 > > ## ?241 True 251 > > ## ?251 True 257 > > ## ?257 True 263 > > ## ?263 True 269 > > ## ?269 True 271 > > ## ?271 True 277 > > ## ?277 True 281 > > ## ?281 True 283 > > ## ?283 True 293 > > ## ?293 True 307 > > ## ?307 True 311 > > ## ?311 True 313 > > ## ?313 True 317 > > ## ?317 True 331 > > ## ?331 True 337 > > ## ?337 True 347 > > ## ?347 True 349 > > ## ?349 True 353 > > ## ?353 True 359 > > ## ?359 True 367 > > ## ?367 True 373 > > ## ?373 True 379 > > ## ?379 True 383 > > ## ?383 True 389 > > ## ?389 True 397 > > ## ?397 True 401 > > ## ?401 True 409 > > ## ?409 True 419 > > ## ?419 True 421 > > ## ?421 True 431 > > ## ?431 True 433 > > ## ?433 True 439 > > ## ?439 True 443 > > ## ?443 True 449 > > ## ?449 True 457 > > ## ?457 True 461 > > ## ?461 True 463 > > ## ?463 True 467 > > ## ?467 True 479 > > ## ?479 True 487 > > ## ?487 True 491 > > ## ?491 True 499 > > ## ?499 True 503 > > ## ?503 True 509 > > ## ?509 True 521 > > ## ?521 True 523 > > ## ?523 True 541 > > ## ?541 True 547 > > ## ?547 True 557 From sturlamolden at yahoo.no Sun Mar 16 13:10:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:10:58 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> Message-ID: <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> On 16 Mar, 16:58, bearophileH... at lycos.com wrote: > I think lot of Win users (computational biologists?), even people that > know how to write good Python code, don't even know how to install a C > compiler. If you don't know how to install a C compiler like Microsoft Visual Studio, you should not be programming computers anyway. > I meant a compiler that spits out the final executable a person can > click on. You don't click on compiled Python C extensions. You call it from your Python code. > >Being written in pure Python, Pyrex is equally easy to use on Windows and Linux.< > > Or maybe equally difficult :-) The computational biology students I > was with think PythonWin is "easy" enough (or take a look at the > "Processing" Java-like language user interface). Lowering entry > difficulties is positive. Can things be made simpler for newbies? Being a computational biologist myself (PhD), I do not agree. Any student smart enough to program Python can learn to use disttools or even a command prompt (whether it's bash or DOS does not matter). There is no way of avoiding the keyboard when your are programming computers, except for some strange drag-and-drop languages like LabView. The way I see it, using a C compiler should be a part of the general education for any student in computational sciences. Java is not less complicated. It requires compilation step as well (javac and possibly gnumake). Students are either forced to learn an IDE (Eclispe og NetBeans), or deal with the command prompt. From hgk at ieee.org Wed Mar 19 04:26:32 2008 From: hgk at ieee.org (=?ISO-8859-1?Q?Hans_Georg_Krauth=E4user?=) Date: Wed, 19 Mar 2008 01:26:32 -0700 (PDT) Subject: Get actual call signature? References: Message-ID: <39c5b285-6334-4944-8506-63f315cf4fe5@q78g2000hsh.googlegroups.com> On 18 Mrz., 11:40, Jarek Zgoda wrote: > Say, I have a function defined as: > > def fun(arg_one, arg_two='x', arg_three=None): > pass > > Is there any way to get actual arguments that will be effectively used > when I call this function in various ways, like: > > fun(5) => [5, 'x', None] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > fun(5, 'something') => [5, 'something', None] > > (et caetera, using all possible mixes of positional, keyword and default > arguments) > > I'd like to wrap function definition with a decorator that intercepts > not only passed arguments, but also defaults that will be actually used > in execution. > > If this sounds not feasible (or is simply impossible), I'll happily > throw this idea and look for another one. ;) > > -- > Jarek Zgoda > Skype: jzgoda | GTalk: zg... at jabber.aster.pl | voice: +48228430101 > > "We read Knuth so you don't have to." (Tim Peters) Perhaps like so: import inspect class CLS(object): def fun(self, arg_one, arg_two='x', arg_three=None): print get_signature(self) def get_signature(obj): frame = inspect.currentframe() outerframes = inspect.getouterframes(frame) caller = outerframes[1][0] try: args, varargs, varkw, loc = inspect.getargvalues(caller) allargs = args allargs.pop(0) # self if not varargs is None: allargs += varargs if not varkw is None: allargs += varkw sdict={} for arg in allargs: sdict[arg]=caller.f_locals[arg] ccframe = outerframes[2][0] ccmodule = inspect.getmodule(ccframe) try: slines, start = inspect.getsourcelines(ccmodule) except: clen = 100 else: clen = len(slines) finfo = inspect.getframeinfo(ccframe, clen) theindex = finfo[4] lines = finfo[3] theline = lines[theindex] cmd = theline for i in range(theindex-1, 0, -1): line = lines[i] try: compile (cmd.lstrip(), '', 'exec') except SyntaxError: cmd = line + cmd else: break finally: del frame del outerframes del caller del ccframe return cmd, sdict if __name__ == '__main__': c=CLS() c.fun(5) c.fun(5, arg_three=['a', 'b']) c.fun(5, 'something') c.fun(5, 'something') a=c.fun a(4) Best Regards Hans Georg From girish.cfc at gmail.com Mon Mar 17 02:15:46 2008 From: girish.cfc at gmail.com (Girish) Date: Sun, 16 Mar 2008 23:15:46 -0700 (PDT) Subject: String To List Message-ID: I have a string a = "['xyz', 'abc']".. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... From emailamit at gmail.com Mon Mar 31 16:42:36 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 13:42:36 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> <304acc0a-3944-44a4-8626-30c2ab9da506@z38g2000hsc.googlegroups.com> Message-ID: <08805546-531f-4b5e-83fc-8b30b0e45db6@s37g2000prg.googlegroups.com> On Mar 31, 11:00 am, xkenneth wrote: > Yeah, this is what I'm talking about: > > > def __eq__(self, other) : > > try : > > return <> > > except AttributeError: > > return False > > That seems a bit nasty to me. One thing about python (IMO); you can't just say this doesn't look good. You need to say: why do you think this is not good. To me, it appears a concise and local solution to your problem. From attn.steven.kuo at gmail.com Thu Mar 13 22:22:12 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 13 Mar 2008 19:22:12 -0700 (PDT) Subject: How do I iterate over items in a dict grouped by N number of elements? References: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> Message-ID: <55183d53-e100-4803-8df8-93cb4c06a7f8@s8g2000prg.googlegroups.com> On Mar 13, 6:34 pm, Noah wrote: > What is the fastest way to select N items at a time from a dictionary? > I'm iterating over a dictionary of many thousands of items. > I want to operate on only 100 items at a time. > I want to avoid copying items using any sort of slicing. > Does itertools copy items? > > This works, but is ugly: > > >>> from itertools import * > >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} > >>> N = 3 > >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N): > > ... print G > ... > (('a', 1), ('c', 3), ('b', 2)) > (('e', 5), ('d', 4), ('g', 7)) > (('f', 6), ('i', 9), ('h', 8)) > (('j', 10), None, None) > > I'd prefer the last sequence not return None > elements and instead just return (('j',10)), but this isn't a huge > deal. > > This works and is clear, but it makes copies of items: > > >>> ii = D.items() > >>> for i in range (0, len(ii), N): > > ... print ii[i:i+N] > ... > [('a', 1), ('c', 3), ('b', 2)] > [('e', 5), ('d', 4), ('g', 7)] > [('f', 6), ('i', 9), ('h', 8)] > [('j', 10)] > groupby? import itertools D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} N = 3 it = itertools.groupby(enumerate(D.items()), lambda t: int(t[0]/N)) for each in it: print tuple(t[1] for t in each[1]) -- Hope this helps, Steven From arnodel at googlemail.com Fri Mar 14 19:24:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 14 Mar 2008 16:24:34 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> Message-ID: On Mar 14, 10:37?pm, Alex wrote: > On Mar 13, 6:21 pm, Carl Banks wrote: > > > On Mar 13, 7:02 am, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > Alex a ?crit : > > > (sni) > > > > > First of all thanks all for answering! > > > > > I have some environment check and setup in the beginning of the code. > > > > I would like to move it to the end of the script. > > > > Why ? (if I may ask...) > > Sure, because of a readability (similar to function declarations in > C). > > > > > > > But I want it to > > > > execute first, so the script will exit if the environment is not > > > > configured properly. > > > > If you want some code to execute first when the script/module is loaded, > > > then keep this code where it belongs : at the beginning of the script. > > > I concur with Bruno's recommendation: stuff you want to do first > > should come first in the script. ?Things like BEGIN blocks hurt > > readability because you can't identify where execution begins without > > reading the whole file. > > > Having said that, one thing that often happens in Python scripts is > > that all the functions are defined first, then the script logic > > follows. ?So you could put the meat of your script in a function, then > > the "BEGIN" stuff after that functions: > > > def run_script(): > > ? ? # > > ? ? # script contained in this long function > > ? ? # > > > # Then test preconditions here... > > if os.environ["HELLO"] != "WORLD": > > ? ? sys.exit(2) > > > # Then call the run_script functions > > run_script() > > > But having said THAT, I don't recommend you do that with > > preconditions. ?If the script has a quick early exit scenario, you > > really ought to put that near the top, before the function > > definitions, to clearly show to a human reader what is necessary to > > run the script. > > > Carl Banks > > Hi, > > Maybe i was a little bit unclear... I meant that i wanted to do > something like this: > > #!usr/bin/env python > > check_env() > > from subprocess import * > > class MyClass: > ? ?# Class definition > > def check_env(): > ? ?# Code > > if __name__ == "__main__": > ? ?# Script logic > > The thing is, as i saw, that Python doesn't recognize the > "check_env()" function before it reaches the "def" statement. > > I need the check to be done before the subprocess import, because our > customers use different Python versions, some of them do not have > subprocess module. So i want to exit if i see that Python version > being used doesn't have that module. > > The solution to that problem with what you suggested could be wrapping > the subprocess import with function, am i correct? why not: try: from subprocess import * except ImportError: sys.exit('No subprocess module :(') # Rest of module -- Arnaud From jackie.python at gmail.com Mon Mar 31 12:50:29 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Mon, 31 Mar 2008 12:50:29 -0400 Subject: Automatically fill in forms on line Message-ID: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> Dear all, I want to automatically complete the following task: 1. Go to http://www.ffiec.gov/Geocode/default.aspx; 2. Fill in an address in the form "Street Address:" . e.g. "1316 State Highway 102"; 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; 4. Click the bottom "search"; 5. In the opened page, extract and save the number after "Tract Code". In the example, it will be "9659". 6. Repeat Step 1 with a new address. Can Python realize these steps? Can these steps be done witout openning and IE windows? Especially, I dont know how to write code for step 2, 4 and 5. Thank you! From http Fri Mar 21 17:57:58 2008 From: http (Paul Rubin) Date: 21 Mar 2008 14:57:58 -0700 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Message-ID: <7x63vfn3ix.fsf@ruckus.brouhaha.com> From at home writes: > if 'one' and 'two' in f: > alist.append(f) Use: if 'one' in f and 'two' in f: ... From yhidalgo86 at gmail.com Tue Mar 4 14:20:14 2008 From: yhidalgo86 at gmail.com (Yusniel) Date: Tue, 4 Mar 2008 11:20:14 -0800 (PST) Subject: Python an Exchange Server Message-ID: Hi friends. Someone know how to work with python and exchange server?. From michael.wieher at gmail.com Thu Mar 6 10:54:44 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 6 Mar 2008 09:54:44 -0600 Subject: Py-Extension Irregularity Message-ID: Observe. Python Code Snippet: ==================== ... 66 while i < (self.nPCodes): 67 # print "%s:%s" % (self.nPCodes,i) 68 (c,l,sn,f,fn,sz) = tabmodule.getQuestion(i,self.mx3Path) 69 if _debug and sz>0: 70 _newPtrLoc = tabmodule.getMx3Ptr() 71 _diff = _newPtrLoc-_oldPtrLoc 72 _oldPtrLoc = _newPtrLoc 73 if _diff>16: 74 print _diff .... C++ Code Snippet: --------------------------- 189 static PyObject* 190 tabmodule_getMx3Ptr(PyObject * self, PyObject * args) { 191 int a; 192 a=mx3File.tellg(); 193 return Py_BuildValue("i",a); 194 } ... 189 PyObject * 190 tabmodule_getQuestion(PyObject * self, PyObject * args) { .... 208 mx3File.read((char*)&m_mdx,16); .... 237 //if(m_mdx.size==0) 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); 239 //return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); } Output== michael at majw-m65:~/MRI/tabModule$ ./tabModule.py michael at majw-m65:~/MRI/tabModule$ None. (ie: the _diff is always 16 or less, which is what is SHOULD be, in fact, it is always 16.) Observe!!!! 237 if(m_mdx.size==0) 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); 239 return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); By uncommenting line 237 and 239, we see: ... 64 80 32 32 32 48 128 160 32 32 64 .... Most of the numbers are still 16, but _diff is often larger than 16, by some multiple. How in Buddah's name is returning a Py_BuildValue() affecting a file pointer that isn't being used at all in the function???? -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Wed Mar 5 18:31:45 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 23:31:45 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <13subb12stga62c@corp.supernews.com> On 2008-03-05, castironpi at gmail.com wrote: > Are you vegetarian? Some days. > A little off topic. Ya think? > Anyway, if (a,b) is a key in dictionary d, can it guarantee > that (b,a) is also in it, and maps to the same object? Do you not know how to run the Python interpreter? >>> d = {(1,2): "onetwo"} >>> (1,2) in d True >>> (2,1) in d False Tuples are ordered, so why would you expect that the tuple (a,b) be considered equal to the tuple (b,a)? There is, of course, the degenerate case where a and b are the same so that the tuple (a,b) does equal (b,a): >>> t = (1,2,3) >>> a = t >>> b = t >>> d = {(a,b): "hi there"} >>> (b,a) in d True An unoderded collection of objects in Python is called a set, but sets are mutable so they're not hashable: >>> s1 = set((1,2)) >>> s2 = set((2,1)) >>> s1 == s2 True >>> d = {s1: "hi there"} Traceback (most recent call last): File "", line 1, in ? TypeError: set objects are unhashable To solve that problem, Python provides the immutable "frozenset" type: >>> s1 = frozenset((1,2)) >>> s2 = frozenset((2,1)) >>> s1 == s2 True >>> d = {s1: "hi there"} >>> s1 in d True >>> s2 in d True See how much better a result you get when you ask an understandble, specific, concrete question? -- Grant Edwards grante Yow! Do I hear th' at SPINNING of various visi.com WHIRRING, ROUND, and WARM WHIRLOMATICS?! From hdante at gmail.com Sat Mar 15 19:48:52 2008 From: hdante at gmail.com (hdante) Date: Sat, 15 Mar 2008 16:48:52 -0700 (PDT) Subject: Big file References: <13th14pe0hhsie1@corp.supernews.com> <9LKdnQpmfOvhFUXanZ2dnUVZ_gKdnZ2d@comcast.com> Message-ID: <8ac593da-0051-410e-8784-d97e2da37200@d45g2000hsc.googlegroups.com> On Mar 12, 10:50 pm, "Andrew Rekdal" wrote: > Well, I can see how this could get real messy but within defining a GUI > there are many elements and so the block of elements such as a wx.notebook > for instance I would hope I could place all the code for this in another > file and somehow include it into place. This way I can work on layered > panels and such in a fresh document rather than travesing through tons of > widgets and sizers. > > Thanks for your replies > > -- > -- Andrew > > "Steven D'Aprano" wrote in message > > news:13th14pe0hhsie1 at corp.supernews.com... > > > On Wed, 12 Mar 2008 19:42:44 -0500, Andrew Rekdal wrote: > > >> I am working in the class constructor defining elements of an > >> application. The problem is the file is getting unmanageble and I am > >> wanting to extend the contructor __init__ to another file. > > >> Is it possible to import directly into the contructor the contents of > >> another module file? > > >> If so how would this be done? > > > Here's the way you do what you literally asked for: > > > class MyClass(object): > > def __init__(self, *args): > > # Warning: completely untested > > execfile('myfile.py') # may need extra arguments? > > > but you almost certainly don't want to do that. A better way is by > > importing modules, the same as you would for anything else: > > > class MyClass(object): > > def __init__(self, *args): > > from AnotherModule import constructor > > constructor(self, *args) > > > But frankly if you find yourself needing to do this because your file is > > "too big" and is unmanageable, I think you are in desperate need of > > refactoring your code to make if more manageable. Pushing vast amounts of > > random code out into other files just increases the complexity: not only > > do you have vast amounts of code, but you have large numbers of files to > > manage as well. > > > -- > > Steven You should define your objects in a recursive way. The main window object only deals with their immediate children. Each childen should have a class that deals with their immediate children. This way, each constructor should have a dozen or so children and each of them should easily fit in a single file. Or you should be using a GUI editor. From bearophileHUGS at lycos.com Sat Mar 8 06:59:47 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 8 Mar 2008 03:59:47 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> <8357c29f-8a28-40d7-8ac7-f8c6737ce202@o77g2000hsf.googlegroups.com> Message-ID: <829107aa-a8fe-4f05-b02a-4360d4042a0e@34g2000hsz.googlegroups.com> George Sakkis: > I had posted some time ago an OO wrapper of itertools; slice notation > for islice was one motivation:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272 I think I did see that, but later I forgot of it. It looks nice. Thank you, bearophile From michael.wieher at gmail.com Sun Mar 23 21:05:12 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 23 Mar 2008 20:05:12 -0500 Subject: Does python hate cathy? In-Reply-To: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> References: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> Message-ID: > > > is that farnarkeling about in a __del__ method is *not* a good idea. Ok that having been said, is accessing an unbound variable of a class and using it to coordinate between instances of that class common practice? -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic.degraeve at gmail.com Wed Mar 26 06:55:15 2008 From: frederic.degraeve at gmail.com (=?ISO-8859-1?Q?Fr=E9d=E9ric_Degraeve?=) Date: Wed, 26 Mar 2008 03:55:15 -0700 (PDT) Subject: matplotlib / legend of x-axis Message-ID: <780b94a4-94c0-4f7c-aa32-7cde8b5d50f7@i12g2000prf.googlegroups.com> Hi everybody, I've got a problem concerning matplotlib/pylab. I use it to represent curves. I will use these pictures in a report. However, it writes me a string 'date' on the bottom of my x-axis. I use this to produce my date axis (x-axis): mondays = WeekdayLocator(MONDAY) # every monday months = MonthLocator(range(1,13), bymonthday=1) # every month monthsFmt = DateFormatter("%b %d '%y") years = YearLocator() # every month yearsFmt = DateFormatter("%y") # subplot.xaxis.set_major_locator(months) # subplot.xaxis.set_major_formatter(monthsFmt) # subplot.xaxis.set_minor_locator(mondays) subplot.xaxis.set_major_locator(years) subplot.xaxis.set_major_formatter(yearsFmt) #subplot.autoscale_view() setp(subplot.get_xticklabels(), 'rotation', 45, fontsize=10) Can you help me to remove this 'date'? thank you! Fr?d?ric From jzgoda at o2.usun.pl Tue Mar 25 16:11:05 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Mar 2008 21:11:05 +0100 Subject: PyGTK localisation on Win32 In-Reply-To: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> References: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> Message-ID: jwesonga pisze: > I've built an app on linux which we have managed to localise into at > least three languages, the app runs well using this command LANG=fr_FR > python app.py which would translate the app into french. We've tried > the replicate the same principle on windows but so far nothing works, > the app will need to be translated into other languages that have no > locale, in windows is there a way to have Glade load values from a > textfile instead of trying to use the .mo files? I had no problem with using standard gettext way of doing i18n on Windows with PyGTK an Glade, apart some quirks with LANG environment variable. Basically, the code that works looks like this: import gettext, locale locale.setlocale(locale.LC_ALL, '') if os.name == 'nt': # windows hack for locale setting lang = os.getenv('LANG') if lang is None: defaultLang, defaultEnc = locale.getdefaultlocale() if defaultLang: lang = defaultLang if lang: os.environ['LANG'] = lang gtk.glade.bindtextdomain(appname, translation_dir) gtk.glade.textdomain(appname) gettext.install(appname, translation_dir, unicode=True) Be aware, that you can not change the locale setting from the command line like you do on Linux. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From mail2spj at yahoo.com Mon Mar 24 17:00:04 2008 From: mail2spj at yahoo.com (SPJ) Date: Mon, 24 Mar 2008 14:00:04 -0700 (PDT) Subject: Reading new mail from outlook Message-ID: <315315.36624.qm@web50108.mail.re2.yahoo.com> An HTML attachment was scrubbed... URL: From sla1nte2001 at yahoo.com Sun Mar 9 22:59:37 2008 From: sla1nte2001 at yahoo.com (John Boy) Date: Sun, 9 Mar 2008 19:59:37 -0700 (PDT) Subject: Import - interpreter works but .py import does not Message-ID: <055c615e-3beb-4037-ab1e-02afeb38da40@e6g2000prf.googlegroups.com> First post and very much a newbie to Python. Have 2.5 on Linux (GG). I think I have set up PYTHONPATH correctly in that I can import a module apply_bp and it complains about line 20 in apply_bp which is: import sys, aipy, numpy, os At the interpreter prompt, however, I can import sys, numpy etc. and can do dir() and see the entry points so I think my overall installation is OK. Why does line not work ? Also I would have thought that when I pre- imported sys et al that they would be in the symbol table so that the import line would be a noop. Thanks, Slainte, John From castironpi at gmail.com Fri Mar 28 06:00:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:00:15 -0700 (PDT) Subject: any good g.a.'s? References: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Message-ID: <5bd6f2f8-2321-4201-a979-666d1d014d29@s8g2000prg.googlegroups.com> On Mar 25, 11:03?am, Tim Chase wrote: > > Any good genetic algorithms involving you-split, i-pick? > > I've always heard it as "you divide, I decide"... > > That said, I'm not sure how that applies in a GA world. ?It's > been a while since I've done any coding with GAs, but I don't > recall any facets related to the You Divide, I Decide problem. > It sounds like a simple optimization of "equality", which would > be a normal use of a GA. ?This would apply for both the division > and the decision, depending on which side the GA is (the "you" or > the "I") or two diff. GAs can be on either side of the process. > > -tkc Tim, if you have any interest in the stuff: You Divide I Decide YDID only works where resources are highly divisible: Except if, do livelock or deadlock occur in real time? If I get in line for going to bars, I enter a decreased-expressivity (- outlet) state, open up, close, and come sit down. Now, what do I generally yield? A life's story. I think I 'send' a request for details in the form of a repetition, except it takes into account a lot of computation, spef. my understading. I also think I look for a 'random' generator to call 'send' on, but that could just be prioritized by strength of pole, but here's the important part, -at- - the- -time-. Taking priority graph/queue to be a function of the past, you can classify into spatial pole and cumulative pole; just the sense mechanata 'say where': 'we favor X' progressively over time. Back at the fork in the road, I was favoring a turn, not a path. I can make a dual, and for the sake of discussion, entertain I do. Are you a musician? Is Heaven a noninterest market? Electricity is a uniform current, highly potent (can sterilize+neutralize), highly uniform (verb regulize). I don't like "discovering poles" "once on the road (just to where)"; I think they're a net quality of life decrease; I don't like poles; they make one answer, heavy questions. Computers at least, can't come and answer; hypothetically, analytically, their pulls can't either. (Computers and their pulls, doh.) However, if I create pole by my actions, they're only part to blame (yes, instead of entirely either or not). Except but, how do I get home? I don't get random homes, it's the same one. Neither does my home pull random people (is it a pole to). It's weird: you can bury latent poles, though clearly time isn't the fuse-length. Contingently exclusive (upon?). There's a layer of discouragement for everything and around everyone else's; surprising me at home is repulsive, lightly. Eating is attractive, more and less over time, sometimes crucial (oddly enough); it creates a junction by outweighing discouragement. (My kitchen is extremely unattractive but not repulsive at all, any farther than the newcome stir, which will come with me after that, though the process of dissipation is a little mysterious-- LaPlace?) There's no good framework for composing (draw analogy to, analogee) the process of emancipation (w.c.) and dissipation, so I lean to church, even though it's chalk-full of non- mathematical (non-vicarous) remarks: "We come, and the vicar leaves. He's just of no interest." Interest might be mutual too, but only in magnitude. I don't like attraction wars. Can I get a tongue regressed (cf. kitchen sink regression)? Are we in Economics? There's money in it. I have to go speak French. Je dois aller. http://www.westga.edu/~jhasbun/osp/Fourier.htm If you receive a sign, do you just design it? What if you have a more clever way to spell a word, qua composite sign? What if you spell it the old way? Consign, design, ensign, and resign. The English tongue is really 'pulling forward' quite fast. Time is generational in facet. (Is a phoneme a particle? Phones are not.) I think time means 'generation', which you can do across space. Ears receive 1-D parametric impressions, Eyes receive 2-D. I don't know of much work in deparametrization, but method iteration ( f_i= f( f_(i-1) ) ), representing space as time, creates generations of something. Problem is, iterations are chosen by somebody, what function to call next in time, so there is a lot of money in choosing functions to call in order, es. if it's refining parameters to other functions. Feedback on computers is lightning-fast, bringing billion- baud guess-and-checking to hands. If you were a tuple, what tuple would you be? Encode, hash, and echo? Do you GOTO home or GOSUB home? What if you limited call stack depth to like five? From gagsl-py2 at yahoo.com.ar Sat Mar 22 15:51:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 22 Mar 2008 16:51:05 -0300 Subject: function-class frustration References: <740f8b7f-7d1a-4f98-96c9-71e58e6a8519@u10g2000prn.googlegroups.com> Message-ID: En Sat, 22 Mar 2008 07:07:18 -0300, John Machin escribi?: > On Mar 22, 7:19 pm, castiro... at gmail.com wrote: > >> On the other hand, are you willing to make changes to the console? >> How big and what? I was thinking of __ to keep the second-to-last >> most recent command. > > Access to and editing of previous input lines is already provided by > the cooked mode of the console (e.g. on Windows, lean on the up-arrow > key) or can be obtained by installing the readline package. Perhaps by > analogy with _, you mean the *result* of the penultimate *expression*. > This functionality would be provided by the Python interactive > interpreter but it's not ... do have a look at IPython (http:// There is no need to change the interpreter, one can use sys.displayhook to achieve that. Create or add the following to your sitecustomize.py module: # sitecustomize.py import sys import __builtin__ as builtin def displayhook(value): if value is not None: sys.stdout.write('%s\n' % value) builtin._ = value if not hasattr(builtin, '__'): __ = builtin.__ = displaylist() else: __ = builtin.__ __.append(value) sys.displayhook = displayhook class displaylist(list): """List of expressions kept by displayhook. It has a maximum size and a custom display, enumerating lines. Lines are trimmed at the middle to fit the maximum width""" maxlen = 20 maxwidth = 80-1-4 def __str__(self): def genlines(self): for i, value in enumerate(self): s = str(value) if len(s) > self.maxwidth: p = (self.maxwidth - 3) // 2 s = s[:p] + '...' + s[-(self.maxwidth - p - 3):] yield '%2d: %s' % (i, s) return '\n'.join(genlines(self)) def append(self, value): # don't keep duplicates # obey the maximum size if value is self: return if value in self: self.remove(value) if len(self) > self.maxlen - 1: del self[:-self.maxlen - 1] list.append(self, value) py> 24*60*60*365 31536000 py> "hello world".split() ['hello', 'world'] py> help Type help() for interactive help, or help(object) for help about object. py> quit Use quit() or Ctrl-Z plus Return to exit py> __ 0: 31536000 1: ['hello', 'world'] 2: Type help() for interactiv...ct) for help about object. 3: Use quit() or Ctrl-Z plus Return to exit py> __[1] ['hello', 'world'] py> __[0] // 3 10512000 py> __ 0: 31536000 1: Type help() for interactiv...ct) for help about object. 2: Use quit() or Ctrl-Z plus Return to exit 3: ['hello', 'world'] 4: 10512000 py> -- Gabriel Genellina From tamim.shahriar at gmail.com Wed Mar 26 13:48:35 2008 From: tamim.shahriar at gmail.com (subeen) Date: Wed, 26 Mar 2008 10:48:35 -0700 (PDT) Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: <16b6150a-d16a-485f-b41c-54a1c18f8e8d@d21g2000prf.googlegroups.com> On Mar 26, 8:12 pm, waltbrad wrote: > Stumbling through Mark Lutz's "Programming Python 3rd", he gives an > example of a program that will automatically configure environment > settings and launch other programs. Then he gives an example of > running this program. On his command line he types: > > C:\...\PP3E>Launcher.py > > and this begins the program. Doesn't work for me. I have to type: > > C:\...\PP3E>python Launcher.py > > Is this a typo on his part or has he configured his settings in such a > way that the command line will automatically associate the extension > with the program? (If so, he didn't mention this in his book). You have to set the path in your run time environment. regards, Subeen. http://love-python.blogspot.com/ From ttsiodras at gmail.com Fri Mar 28 10:50:51 2008 From: ttsiodras at gmail.com (ttsiodras at gmail.com) Date: Fri, 28 Mar 2008 07:50:51 -0700 (PDT) Subject: Global variables in modules... References: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> Message-ID: <6842b4de-f241-425a-aeec-29ba2077ec65@e10g2000prf.googlegroups.com> That clears it up. Thanks. From pavloutefkros at gmail.com Sun Mar 2 09:54:34 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 06:54:34 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> sorry for acting like a fool but this is just to weirdly easy that i can't get to work. i've written a small web server in another language and this is more like copying code. i already have everything figured out, except this one but noone seems either willing or capable of helping me. again sorry but i was in a very bad mood. From tew24 at spam.ac.uk Fri Mar 7 06:27:21 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Fri, 07 Mar 2008 11:27:21 +0000 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: jim-on-linux wrote: > This is what someone wrote on 1-21-2007 > to this help site about this pain in the a... > MSVCR71 stuff. > > " I believe this problem doesn't exist. > (snip useful bit of EULA and explanation) Thanks for that - just what I didn't manage to turn up with Google. I'll go ahead and publish then :-) -- I'm at CAMbridge, not SPAMbridge From lialie at gmail.com Thu Mar 13 22:02:50 2008 From: lialie at gmail.com (lialie) Date: Fri, 14 Mar 2008 10:02:50 +0800 Subject: Dispatch("Excel.Application") failed Message-ID: <47D9DCCA.3060401@gmail.com> On Behalf Of John Machin > > > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > > > None, None) > > > Googling for 2147221005 gives some clues. > > That string of hex stuff appears where an error message is > expected -- it's not utf8, and makes no sense when I attempt > to decode it with cp1250 to cp1258 inclusive. If you start > IDLE and type: >>The hex stuff is Chinese. It appears to be a standard Windows error message. >>???????? (Which I believe meaans "invalid class string") >>I wrote in another post (that doesn't appear to have made it to the list) >>that the call to Dispatch on Excel will fail if the formula bar edit box is >>active. Just another idea. >>Regards, >>Ryan Ginstrom Thanks. I did try to google the question, but the answer wasn't properly. I am using Windows XP sp2 which language is Chinese simp. At first, I thought the hex string was coding in cp936 or utf8, then failed. second, try to run my script on the other computer, and it run well without any error! At last, I give up.After Windows Excel reinstalled, it work, but still confused.:( The net speed is horribly slow when connect to Pywin32 project at SF. Regards, Lialie From castironpi at gmail.com Tue Mar 18 21:27:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 18:27:02 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> Message-ID: <4e740d0f-9b1d-4b1d-9f6b-8bd56ea11a65@z38g2000hsc.googlegroups.com> > >> >>> b in b > >> False > > > That's actually interesting. > > Just for the avoidance of doubt, I didn't write the 'b in b' line: > castironpi is replying to himself without attribution. > > P.S. I still don't see the relevance of any of castironpi's followup to my > post, but since none it made any sense to me I guess it doesn't matter. Well, it does show thought and it's an interesting anomaly. It's related to the OP too (no less so than the one before it than any other to the one before it): 'Why?' is pretty open-ended. D'Aprano pointed out an ambiguity in the 'in' operator, which sparked an idea that contributes to some other threads. I thought Booth and Bossy, "homogeneous ... add+remove" pretty well summed it up. That's my mistake for showing excitement to one thread that was actually mostly prepared by another. I'm in A.I. if that helps any. I am puzzled by the failure on 'a in a' for a=[a]. >>> a== [a] also fails. Can we assume/surmise/deduce/infer it's intentional? From nodrogbrown at gmail.com Fri Mar 7 10:12:13 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 7 Mar 2008 07:12:13 -0800 (PST) Subject: problem with join Message-ID: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> hi i am using python on WinXP..i have a string 'folder ' that i want to join to a set of imagefile names to create complete qualified names so that i can create objects out of them folder='F:/brown/code/python/fgrp1' filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] filenameslist=[] for x in filenms: myfile=join(folder,x) filenameslist.append(myfile) now when i print the filenameslist i find that it looks like ['F:/brown/code/python/fgrp1\\amber1.jpg', 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] is there some problem with the way i use join? why do i get \\ infront of the basename? i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', can anyone pls help gordon From castironpi at gmail.com Tue Mar 11 17:53:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 14:53:47 -0700 (PDT) Subject: python interactive - threaded console (run -i) References: <56661ddb-f06b-4229-8011-7996cd023600@m34g2000hsc.googlegroups.com> Message-ID: <4eb586c0-ce9a-4d54-a43c-a38d18df041d@s13g2000prd.googlegroups.com> > ? ? ? ? self._doneevents= {} is extraneous. > id, fun, ar, kw= self.get() done, fun, ar, kw= self.get() suffices. > def _draintilclose( conn, understandfun= None ): > ? ? ? ? if None is not understandfun: > ? ? ? ? ? ? understandfun( _curmsg ) yield _curmsg is an interesting synonym: the static interface. Compare signatures: def _draingen( conn ): ... yield _curmsg def _draintilclose( sck, th ): for x in _draingen( sck ): th._print( x ) or in place of th._print, whatever function you passed to understandfun. The general case, pseudocode, consumer: def _draintilclose( conn, visitee ): for x in _draingen( conn ): x.visit( visitee ) class Tool1Visitee: def typeA( self, arg ): tool1.listbox.add( arg ) def typeB( self, arg ): tool1.combobox.add( arg ) class Tool2Visitee: def typeA( self, arg ): tool2.icons.add( arg ) def typeB( self, arg ): tool2.listbox.add( arg ) and: class VisitorX: def visit( self, v ): v.typeA( self._attr ): class VisitorY: def visit( self, v ): v.typeB( self._attr ): Producer: def _draingen( conn ): ... if: _curvisitee= VisitorX( _curmsg ) else: _curvisitee= VisitorY( _curmsg ) yield _curvisitee and: th1Visitee= Tool1Visitee() new_thread( _draintilclose, conn1, th1Visitee ) th2Visitee= Tool2Visitee() new_thread( _draintilclose, conn2, th2Visitee ) Tool1Visitor.typeA still just receives a byte array, but type information comes with. By that point, the 'message knows' that it's in a Tool1Visitor, and that it's a typeA message, and so adds it to tool1.listbox. That puts just the right information in just the right place... if it's the right time. Or pass the visitee directly to _draingen as fit, without the visitor or yields, as a callback collection. def _draingen( conn, visitee ): ... if: visitee.typeA( _curmsg ) else: visitee.typeB( _curmsg ) As a callback collection: tool1_ft= dict( typeA= tool1.listbox.add, typeB= tool1.combobox.add ) tool2_ft= dict( typeA= tool2.icons.add, typeB= too2.listbox.add ) @new_threads( conn1, tool1_ft ) @new_threads( conn2, tool2_ft ) def _( conn, tool_ft ): for tp, msg in _draingen( conn, tool_ft ): tool_ft[ tp ]( msg ) using a generator, or directly without: tool1_ft= dict( typeA= tool1.listbox.add, typeB= tool1.combobox.add ) new_thread( _draintilclose, conn1, tool1_ft ) tool2_ft= dict( typeA= tool2.icons.add, typeB= too2.listbox.add ) new_thread( _draintilclose, conn2, tool2_ft ) From jaywgraves at gmail.com Mon Mar 10 10:24:50 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 10 Mar 2008 07:24:50 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <094a9916-66ac-42f6-9146-a16872c7f78d@m36g2000hse.googlegroups.com> On Mar 10, 8:57 am, royG wrote: > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? Try the 'glob' module. ... Jay From gagsl-py2 at yahoo.com.ar Fri Mar 7 09:57:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 12:57:03 -0200 Subject: hidden built-in module References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> Message-ID: En Fri, 07 Mar 2008 12:15:04 -0200, koara escribi?: > On Mar 5, 1:39 pm, gigs wrote: >> koara wrote: >> > Hello, is there a way to access a module that is hidden because >> > another module (of the same name) is found first? >> >> > More specifically, i have my own logging.py module, and inside this >> > module, depending on how initialization goes, i may want to do 'from >> > logging import *' from the built-in logging. >> >> you can add your own logging module in extra directory that have >> __init__.py and >> import it like: from extradirectory.logging import * >> and builtin: from logging import * > > Thank you for your reply gigs. However, the point of this namespace > harakiri is that existing code which uses 'import logging' ... > 'logging.info()'... etc. continues working without any change. > Renaming my logging.py file is not an option -- if it were, i wouldn't > bother naming my module same as a built-in :-) Read a very recent post from Bruno Desthuilliers with subject "Altering imported modules" -- Gabriel Genellina From tmp1 at viltersten.com Sun Mar 2 12:02:08 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 18:02:08 +0100 Subject: SV: Keeping the console window In-Reply-To: <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> References: <62vs0iF24tv6jU1@mid.individual.net> <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> Message-ID: <6303tdF24pjjtU1@mid.individual.net> > You may use python in interactive mode: > > $ python -i yourScript.py > > Or use a blocking readline: > > $ cat yourScript.py > import sys > sys.stdin.readline() Thanks guys! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From jeff at schwabcenter.com Tue Mar 18 16:07:40 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 13:07:40 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> Message-ID: Mike Driscoll wrote: > On Mar 18, 1:41 pm, fumanchu wrote: >> On Mar 17, 6:25 pm, dundeemt wrote: >> >>> I agree - the balance wasn't as good. We can all agree that HowTos >>> and Intros are a necessary part of the conference talks track, but as >>> Robert pointed out some talks should be of a more advanced nature. I >>> enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and >>> Mark Hammond's keynote were among my favorite talks. >> Raymond Hettinger's talk on collections was not only one of my >> favorites, it was apparently lots of other people's too--the room was >> PACKED. I can't recall seeing any other talk that was even close to >> seating capacity. >> >> Robert Brewer >> fuman... at aminus.org > > The "Using PyGame and PySight to Create an Interactive Halloween > Activity (#9)" session with Mr. John Harrison was also quite full as > was the one for Pyglet. I think the nose presentation had people > sitting on the floor. > > Geeks like games! I know I do! Me too. As I have never attended PyCon, the amount of entertainment already gleaned from this thread has wildly exceeded my expectations. :) Are slides or notes from any of the presentations available online? What was the topic of the well-received presentation from Google? From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 06:35:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 10:35:30 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <0964631d-67e4-4c7f-968e-5bf42c0787c2@d45g2000hsc.googlegroups.com> Message-ID: <13uur7ishec9795@corp.supernews.com> On Sun, 30 Mar 2008 01:13:04 -0700, dewitters wrote: > On Mar 29, 6:34 pm, Lie wrote: >> You're forcing your argument too much, both != and <> are NOT standard >> mathematics operators -- the standard not-equal operator is >< -- and I >> can assure you that both != and <> won't be comprehensible to non- >> programmers. > > What I meant was that both < and > are standard mathematics operators, > and that by that knowledge one could deduce what <> means. But you would be wrong, because "less than or greater than" is not the same as "not equal to". >>> 3+2j != 2-3j True >>> (3+2j < 2-3j) or (3+2j > 2-3j) Traceback (most recent call last): File "", line 1, in TypeError: no ordering relation is defined for complex numbers -- Steven From craigm3604 at gmail.com Thu Mar 20 17:25:43 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 14:25:43 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> Message-ID: <8a84e37c-4f03-41ab-becc-7632b84b0389@s12g2000prg.googlegroups.com> On Mar 20, 4:55 pm, "Chris Mellon" wrote: > On Thu, Mar 20, 2008 at 3:42 PM, Craig wrote: > > > On Mar 20, 2:38 pm, Craig wrote: > > > On Mar 20, 2:29 pm, sturlamolden wrote: > > > > > On 20 Mar, 19:09, Craig wrote: > > > > > The culprit i here: > > > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > > > This binds these names to Python ints, but byref expects C types. > > > > > Also observe that CacheSize and OpenMode should be c_short. > > > > I changed CacheSize and OpenMode to c_short, and commented out that > > > line producing the "Before" message, and the output is the same. > > > > Further "tinkering" revealed that it is the byref on the fName and pw > > > that are causing the error. > > > > The entire problem appears to be around the production of a BSTR and > > > the passing of pointers (byref) to the BSTR. > > > Can anyone shed some light on how to work with BSTR's? > > Since you didn't tell ctypes about the function signature, it assumes > it returns int and gives you a python int. Provide a function > signature (c_void_p should work for BSTR) for both functions and you > should have an easier time of it. > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list Thanks Chris. I changed X to a c_short also, and modified the example as suggested: X = c_short(0) X = windll.vbis5032.VmxOpen(byref(c_void_p(fName)), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(c_void_p(pw))) printf ("After - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) And, this is what printed: After - X = 4325376, CacheSize = 0, OpenMode = 3, vHandle = 17586736 The printf shows that the values of X and vHandle have changed, but I am not sure it is working properly as X should be a MUCH smaller number (< 256). I would have expected a 0 (VIS_OK), 13 (VIS_DOS_ERROR) or 14(VIS_DISK_ERROR) if it had worked. Next, I changed: fName = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", 13) so that I knew it would not find the file, and got: After - X = 2555917, CacheSize = 0, OpenMode = 3, vHandle = 0 The vHandle staying 0 tells me that it did not find the file, but the value of X seems random. Based on the original C prototype, what am I doing wrong so that the return from the call to vbis5032 is not "usable"? From deets at nospam.web.de Thu Mar 6 15:19:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Mar 2008 21:19:54 +0100 Subject: Exploring Attributes and Methods In-Reply-To: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: <63b1veF26p2fkU2@mid.uni-berlin.de> keios.titan at gmail.com schrieb: > Hi, > Is there a python command that allows me to extract the names (not > values) of the attributes of a class. > > example > > Class Sample: > fullname = 'Something' > > How can I know that this class has an attribute called 'fullname'? > > I hope my question is clear. The question others have answered already. But I have one for you: you are aware that these kind of variables are *class variables*, NOT *instance variables*, as they are created like this: class Foo(object): def __init__(self): self.fullname = "something" Diez From gherron at islandtraining.com Sun Mar 2 11:37:11 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 02 Mar 2008 08:37:11 -0800 Subject: Question on importing and function defs In-Reply-To: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> Message-ID: <47CAD7B7.8040006@islandtraining.com> TC wrote: > I have a problem. Here's a simplified version of what I'm doing: > > I have functions a() and b() in a module called 'mod'. b() calls a(). > > So now, I have this program: > > from mod import * > > def a(): > blahblah > > b() > > > The problem being, b() is calling the a() that's in mod, not the new > a() that I want to replace it. (Both a()'s have identical function > headers, in case that matters.) How can I fix this? > > Thanks for any help. > Since b calls mod.a, you could replace mod.a with your new a. Like this: (Warning, this could be considered bad style because it will confuse anyone who examines the mod module in an attempt to understand you code.) import mod def replacement_a(): ... mod.a = replacement_a ... Or another option. Define b to take, as a parameter, the "a" function to call. In mod: def a(): ... def b(fn=a): # to set the default a to call ... And you main program: from mod import * def my_a(): ... b(my_a) Hope that helps Gary Herron From castironpi at gmail.com Thu Mar 6 05:29:55 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 02:29:55 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: On Mar 6, 2:37?am, Bryan Olson wrote: > Grant Edwards wrote: > > It may be ?obvious that he has a question. ?It's not the least > > bit obvious what that question is. > > How can we efficiently implement an abstract data type, call it > 'DoubleDict', where the state of a DoubleDict is a binary > relation, that is, a set of pairs (x, y); and the operations on > a DoubleDict are those on a Python set, plus: > > ? ? ?find_by_first(self, x): ?return [y where (x, y) in DoubleDict] > > ? ? ?find_by_second(self, y): ?return [x where (x, y) in DoubleDict] > > Python can implement this ADT directly as specified, but the > find_by_ operations would run in time len(self). ?We want an > implementation where the find_by's run in O(1 + k) where k is > the length of the returned sequence. > > -- > --Bryan It gets hairier if you have an element that isn't a first or second necessarily. find_by_other(self, x): return [y where (x, y) in DoubleDict or (y, x) in DoubleDict] From sjmachin at lexicon.net Tue Mar 25 07:40:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Mar 2008 04:40:18 -0700 (PDT) Subject: My python interpreter became mad ! References: Message-ID: On Mar 25, 10:05 pm, Benjamin Watine wrote: > Yes, my python interpreter seems to became mad ; or may be it's me ! :) > > I'm trying to use re module to match text with regular expression. In a > first time, all works right. But since yesterday, I have a very strange > behaviour : > > $ python2.4 > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > X-Spam-Flag: YES > X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org > X-Spam-Level: ********************** > X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, > MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, > > RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, > > URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, > URIBL_WS_SURBL autolearn=failed version=3.1.7-deb > > Traceback (most recent call last): > File "", line 1, in ? > File "/etc/postfix/re.py", line 19, in ? > m = re.match('(Spam)', mail) > AttributeError: 'module' object has no attribute 'match' > >>> > > What's the hell ?? I'm just importing the re module. No you're not importing *the* re module. You're importing *an* re module, the first one that is found. In this case: your own re.py. Rename it. From grante at visi.com Thu Mar 20 12:00:58 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 16:00:58 -0000 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: <13u52hqlbtdv1d1@corp.supernews.com> On 2008-03-20, Jeff Schwab wrote: >>> http://www.google.com/search?q=emacs+python > >> Gee. Thanks. > > I believe Grant was suggesting that Emacs often serves a similar purpose > on Unix to what Visual Studio does on Windows, which seemed to be what > you were asking. When asking about Mac OS X here, you are likely to get > a lot of generic Unix responses. (Would it have been clearer if he had > just said "emacs?") Don't the normal "run/debug python from inside emacs" methods work on OS-X? -- Grant From nkavitha551 at gmail.com Sat Mar 1 05:33:06 2008 From: nkavitha551 at gmail.com (nkavitha551 at gmail.com) Date: Sat, 1 Mar 2008 02:33:06 -0800 (PST) Subject: Wanna be a pride owner? Message-ID: <9c27ba17-1a54-4cc2-a3ca-16ac4c995253@e10g2000prf.googlegroups.com> Hi, Wanna be a pride owner? Visit the website below and make others look at you with envy!!! ------------------------------------------------------------------------------ http://kavitha551.blogspot.com/ ------------------------------------------------------------------------------- From george.sakkis at gmail.com Fri Mar 7 21:55:29 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 7 Mar 2008 18:55:29 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> Message-ID: <8357c29f-8a28-40d7-8ac7-f8c6737ce202@o77g2000hsf.googlegroups.com> On Mar 7, 7:49 am, bearophileH... at lycos.com wrote: > I find itertools.islice() useful, so for Python 3.x I may like to see > it removed from the itertools module, and the normal slicing syntax > [::] extended to work with generators/iterators too. > > from itertools import islice > primes = (x for x in xrange(1,999) if all(x % y for y in xrange(2, > x))) > print list(islice(primes, 0, 20)) > ==> > print list(primes[:20]) > > Bye, > bearophile I had posted some time ago an OO wrapper of itertools; slice notation for islice was one motivation: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272 George From sjmachin at lexicon.net Sat Mar 22 19:17:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 16:17:06 -0700 (PDT) Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> <64kg3pF2avnseU1@mid.uni-berlin.de> Message-ID: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> On Mar 23, 12:32 am, "Diez B. Roggisch" wrote: > John Machin schrieb: > > > On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: > > >> [1] Just one example:http://docs.mootools.net/Class/Class.js > > > Mootools being something a coworker might use? > > I don't understand the question. > > Diez It presupposes that the reader on first seeing "coworker" has mentally decomposed it as "cow-ork-er". From gabriel.rossetti at mydeskfriend.com Wed Mar 26 05:07:28 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Wed, 26 Mar 2008 10:07:28 +0100 Subject: Strange loop behavior In-Reply-To: References: Message-ID: <47EA1250.9010305@mydeskfriend.com> Arnaud Delobelle wrote: > On Mar 26, 8:35 am, Gabriel Rossetti > wrote: > >> Hello, >> >> I wrote a program that reads data from a file and puts it in a string, >> the problem is that it loops infinitely and that's not wanted, here is >> the code : >> >> d = repr(f.read(DEFAULT_BUFFER_SIZE)) >> while d != "": >> file_str.write(d) >> d = repr(f.read(DEFAULT_BUFFER_SIZE)) >> >> I also tried writing the while's condition like so : len(d) > 0, but >> that doesn't change anything. I tried step-by-step debugging using >> PyDev(eclipse plugin) and I noticed this, once the while was read once, >> it is never re-read, basically, the looping does happen, but just in >> between the two lines in the loop's body/block, it never goes on the >> while and thus never verifies the condition and thus loops forever. I >> had been using psyco (a sort of JIT for python) and so I uninstalled it >> and restarted eclipse and I still get the same thing. This looks like >> some bug, but I may be wrong, does anybody understand what's going on here? >> >> Thanks, >> Gabriel >> >> PS >> And yes I checked, the "d" variable is en empty string at some point, so >> the looping should stop. >> > > No, it isn't the empty string, it is the printable representation of > the empty string (because you wrap your f.read() calls in repr()), > which is the string "''": > > >>> print "''" > '' > > Why do you wrap f.read(...) in the repr() function? If you remove the > two repr() I suspect your code will work. > > OTOH do you know that the read() method of file objects does what you > want? You could simply write: > > file_str = f.read() > > Or are there some other factors that prevent you from doing this? > > -- > Arnaud > > Ok, like I mentioned in my second msg, I had put repr() there because I was getting errors because the ascii range (128) was exceeded, I tried cheating and telling it it was unicode but that didn't work, so I tried repr() and it gave me a string rep. of my data, that was ok. After that I tried using StringIO instead of what I had before, a list of strings that I later joined with an empty string. I just re-tried removing the repr() and it works with the StringIO version. Thanks for all your answers, Gabriel From jasynwiener at gmail.com Sun Mar 16 14:22:54 2008 From: jasynwiener at gmail.com (jasonwiener) Date: Sun, 16 Mar 2008 11:22:54 -0700 (PDT) Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> Message-ID: <8e570583-1a62-49d3-8d00-8bdce8f05df0@s13g2000prd.googlegroups.com> Completely helped! Working as expected now. Thanks. You really got me out of a bind! J. On Mar 16, 10:23 am, "Martin Blume" wrote: > "jasonwiener" schrieb > > > I am having a VERY odd problem with unpacking right now. > > I'm reading data from a binary file and then using a very > > simple struct.unpack to get a long. Works fine on my MacBook, > > but when I push it to a Linux box,it acts differently and > > ends up pewking. > > [...] > > > the data looks to be the same, but the unpacking seems to > > treat it differently. > > Probably little-endian vs. big-endian issue: > > >>> s > '\x1e\xc6\xf3\xb4' > >>> struct.unpack(' (3035874846L,) > >>> struct.unpack('>I', s) > > (516354996L,) > > See help(struct) for further information. > > This seems to imply that the Mac, although running now on Intel > processors, is still big-endian. > > HTH > Martin From iainking at gmail.com Mon Mar 17 05:27:31 2008 From: iainking at gmail.com (Iain King) Date: Mon, 17 Mar 2008 02:27:31 -0700 (PDT) Subject: String To List References: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> Message-ID: <42858a90-80eb-45ac-8f76-ad9d06ee4fbf@d21g2000prf.googlegroups.com> On Mar 17, 6:56 am, Dan Bishop wrote: > On Mar 17, 1:15 am, Girish wrote: > > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > this?? > > Thanks for the help... > > eval(a) will do the job, but you have to be very careful about using > that function. An alternative is > > [s.strip('\'"') for s in a.strip('[]').split(', ')] This will fall over if xyz or abc include any of the characters your stripping/splitting on (e.g if xyz is actually "To be or not to be, that is the question"). Unless you can guarantee they won't, you'll need to write (or rather use) a parser that understands the syntax. Iain From rschroev_nospam_ml at fastmail.fm Mon Mar 10 11:26:32 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 10 Mar 2008 16:26:32 +0100 Subject: Regarding coding style In-Reply-To: <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> Message-ID: rockingred schreef: > On Mar 8, 8:27 pm, Dan Bishop wrote: >> // Copyright (C) 2008 Foobar Computer Consulting >> // >> // VERSION PROJECT# DATE DESCRIPTION >> // ------- -------- -------- ------------------ >> // 1.00 123456 01/04/08 Original creation. >> // >> >> Eleven lines, of which the only useful information to me was the >> project number, as knowing this let me look up who was behind these >> comments. > > Actually, "editorial" comments that tell you who last changed a > program, when and why can be useful. I worked in a company with a > number of programmers on staff. Having comments that told us Joe > worked on a program yesterday that isn't working today could often > solve half the battle. Especially if Joe also added a comment near > the lines he had changed. Likewise including the "Project#" would > help us track all the programs that had to be changed for a specific > project. This allowed us to move all related items into the Live > system once the testing phase had been completed (we just searched for > everything with the same Project# in it). Yes, on rare occasions we > would have an entire page of "Editorial" comments to ignore at the > beginning of our program listing, but it was easy enough to skip that > page. I will grant you that probably after 10 changes the first > change isn't as important anymore (unless you want to backtrack and > find out who started the Project in the first place and what it's > original purpose was). That is certainly useful, but IMO that's what version control systems are for. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From gherron at islandtraining.com Wed Mar 19 17:30:11 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 Mar 2008 14:30:11 -0700 Subject: Is this valid ? In-Reply-To: <47E18332.9030202@gmail.com> References: <47E18332.9030202@gmail.com> Message-ID: <47E185E3.3080902@islandtraining.com> Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > > thanks, > Stef Mientki > > Yes. It's been in Python since the earliest days. You usually see it in test like this: if a < b < c: but any comparison operators work. The meaning is the same as the AND of each individual test. Gary Herron From dieter at handshake.de Fri Mar 14 15:23:23 2008 From: dieter at handshake.de (Dieter Maurer) Date: 14 Mar 2008 20:23:23 +0100 Subject: ZSI and attachments In-Reply-To: References: Message-ID: Laszlo Nagy writes on Tue, 11 Mar 2008 15:59:36 +0100: > I wonder if the newest ZSI has support for attachments? Last time I > checked (about a year ago) this feature was missing. I desperately > need it. Alternatively, is there any other SOAP lib for python that > can handle attachments? The ZSI 2.0 documentation says: "...It can also be used to build applications using SOAP Messages with Attachments...." I never did it and do not know how ZSI supports this. You probably will get a more informed answer on mailto:pywebsvcs-talk at lists.sourceforge.net, the ZSI mailing list. Dieter From castironpi at gmail.com Sat Mar 22 06:50:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 03:50:09 -0700 (PDT) Subject: Can I run a python program from within emacs? References: <3413d022-b9c6-4503-8d5a-d01ffead3c99@m36g2000hse.googlegroups.com> Message-ID: <106813ce-4ae7-4b3e-8a73-a78967e59844@e60g2000hsh.googlegroups.com> On Mar 22, 3:47?am, David Reitter wrote: > On Mar 20, 3:09 pm, jmDesktop wrote: > > > Hi, I'm trying to learn Python. ?I using Aquamac an emac > > implementation with mac os x. ?I have a program. ?If I go to the > > command prompt and type pythong myprog.py, it works. ?Can the program > > be run from within the editor or is that not how development is done? > > I ask because I was using Visual Studio with C# and, if you're > > familiar, you just hit run and it works. ?On Python do I use the > > editor for editing only and then run the program from the command > > line? ?Thank you. > > Aquamacs, just like any variant of GNU Emacs, will show a Python > menu. ?There's a "Start Interpreter" function, and one to evaluate the > buffer (C-c C-c). ?It's pretty straightforward (a euphemism for > obvious). Aside: Straightforward may not be completely objective, i.e. have a metric/ unique metric. If perception & cognition are points on and paths through a multi-dimensional space (densities in which limited by sense mechanism), straightforward under its most literal interpretation, means, 'in a straight line in the direction you're facing'. Straight could mean an elementary, transcendantal, or composite function (say, a sum of three sine waves). But forward leaves less to imagine. If two ships cross, and one captain says, 'Bermuda? Sure. It's straight forward,' to the other, he travels for a day and doesn't get there, and he's angry, does he feel and/or believe that the first captain provoked him, did he, and does he know it. Straightforward doesn't necessarily evaluate to a concrete move sequence in chess ('The pin is straightforward'); forward is ambiguous (my forward, your forward, the formal forward), and straight is too. In a depth-first search (unspecified), straight means move the same piece repeatedly. In breadth-first, straight means you know exactly my node weights. Forward means I know which direction you're facing, or I'm following you. Both are resent-worthy assumptions: If you lose me or I lose you, it's still your fault. I take that back: either party can slack on following protocol; both are following one. There's a ball, who dropped it (and who's on it!). "Obvious", come to think of it, is pretty subjective too. The objects and their respective distances away in one's perceptive(/cognitive) environment vary from person to person, time to time ("by person by time"). If you're telling me something is obvious, one of us made an out-of-band inference. I'm not sure what to think of the prevalence of human miscommunications. Upon discovering one, either cut and go, or go back for it; it's a sunken cost. (Is it a, 'I forgot to bring something' on an embarked voyage (road trip), in the metaphor of ship travel?) Do those both generate fights? There's social profit in commerce-- but people are making some damn foolish partnerships. (Even exclusivity can be profitable, but for some reason, 'exclusivity agreement' isn't in Wikipedia, under exclusivity, marketing, marketing strategy, or consumer engagement. 'Product bundling' is a good place to start though-- lower marginal cost -and- higher marginal utility. ('Bundling' is also a social practice in the Netherlands!) Also see law of excluded middle.) Back to the exam: If A knows B's 'straight' and 'forward', maybe it can be helpful, merely advising, 'don't take any turns and you won't miss it (undershoot or overshoot)', which does take knowledge of steering, just not of the terrain. It's just that if I don't know how to stay on course, (not to turn), I'll still resent you. Not to mention, a 'great circle straight' isn't the same as a Euclidian one. It's possible, though, in the economy of social transaction, that "I" don't "have time" to "take you there", all of those being defined earlier: one of the parties can't afford to board, possibly return, tow, or tie you, or it isn't profitable. It's possible your ship can't take the tow too. Notwithstanding, in the domain of collective social entities (many- small/organisms), other senses of channel symbols / band symbols can arise. "That doesn't mean the same thing back home / back in the channel." I don't like learning the hard way-- by definition. But the solution to the 'rich bully dilemma' is pretty much boycott-- cf. Nash and optimal equilibrium. (That's optimal, not optical.) In light of some certain "mental health" observations too, if boycotts fail, protest is plan B. Mere incompetence on either part is pretty easy to fix. It's the 'incompetent rich bully' who interferes with everybody else. Nothing personal to the poster-- he covered his socal bases-- just being thorough. Last thing-- does "maintain forever" mean deal with us? Hush. A pretty small group could build/anchor an outland base and maintain people there forever, just with ferry trips back in. Past a certain radius too (from hubs), bases become polynomially sparser-- just move in with the monkey on your back, and we'll all get orbits around the sun. From gagsl-py2 at yahoo.com.ar Thu Mar 6 20:04:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 23:04:14 -0200 Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: En Thu, 06 Mar 2008 22:48:42 -0200, Krishna escribi?: >>>> class Test(object): > ... def __init__(self): > ... self.a= 2 > ... def func(self, k = self.a): > ... print k > ... > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in Test > NameError: name 'self' is not defined >>>> > > In the 'definition of the class', what would the first argument 'self' > in the methods evaluate to; when we have an object defined, it is > bound to the object reference, but what happens while the class > definition is executed, which I believe happens when the module > containing the class definition is imported Function default arguments are evaluated when the function is defined (when the class is defined, in this case) so "self" itself has not a value. Try this instead: def func(self, k=None): if k is None: k = self.a print k If None is an allowed argument, use a special marker instead: _marker=object() ... def func(self, k=_marker): if k is _marker: k = self.a ... -- Gabriel Genellina From asmodai at in-nomine.org Mon Mar 31 07:57:25 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 31 Mar 2008 13:57:25 +0200 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <20080331115725.GI80617@nexus.in-nomine.org> -On [20080331 12:56], Pradeep Rai (pradiprai at gmail.com) wrote: >Can you guide me how to install a 2.5 version of dbi for it to work ? Same way you installed dbi for 2.4 just make sure the called python executable is the 2.5 one. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Sometimes things stare us in the face and we are too blind to see... From sturlamolden at yahoo.no Thu Mar 20 09:41:17 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 06:41:17 -0700 (PDT) Subject: wxFormBuilder Message-ID: I just discovered wxFormBuilder. After having tried several GUI builders for wx (including DialogBlocks, wxGlade, XRCed, Boa constructor), this is the first one I can actually use. To use it wxFormBuilder with wxPython, I generated an xrc resource and loaded it with wxPython. All the tedious GUI coding is gone :-) http://wxformbuilder.org/ http://wiki.wxpython.org/index.cgi/XRCTutorial From larry.bates at websafe.com Thu Mar 27 13:34:02 2008 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 27 Mar 2008 12:34:02 -0500 Subject: Py2exe embed my modules to libary.zip In-Reply-To: <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> Message-ID: <1206639241.3132.0.camel@fc8.home.com> Create your py2exe distribution without a zipfile and all the modules will just be put into the installation directory. Use Inno Setup to make a proper installer for your application. -Larry On Thu, 2008-03-27 at 06:44 -0700, vedrandekovic at yahoo.com wrote: > On 27 o?u, 10:44, "Gabriel Genellina" wrote: > > En Thu, 27 Mar 2008 06:00:26 -0300, escribi?: > > > > > > > > > I was add this into my application code: > > > > > import sys > > > import os > > > my_dir=os.getcwd() > > > sys.path.append(my_dir) > > > sys.path.append(my_dir+"\\libary.zip") > > > sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder > > > f=open("path.txt","w") > > > f.write(str(sys.path)) > > > f.close() > > > > > an the output in path.txt is : > > > > > ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users > > > \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ > > > \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ > > > \libary.zip\\py2exe'] > > > > > But it still can't find module py2exe.What should I do now? Any > > > examples? > > > > I assume you're talking about the py2exe package available from www.py2exe.org- so it's not a module, it's a package. > > py2exe usually is only relevant on your *development* machine, so why do > > you want to put it inside a .zip? What do you want to do? > > > > Anyway, I tried the following and could import py2exe successully (but I > > don't know if it actually works as a distutils extension...) > > > > - compressed the py2exe folder into py2exe.zip > > - deleted the original py2exe folder > > - moved py2exe.zip onto some temporary directory > > - tried to import py2exe, failed as expected > > - added py2exe.zip to sys.path > > - tried to import py2exe, this time OK > > > > py> import py2exe > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module named py2exe > > py> import sys > > py> sys.path.append(r"C:\TEMP\pna\py2exe.zip") > > py> import py2exe > > py> py2exe.__path__ > > ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] > > > > -- > > Gabriel Genellina > > Hello again, > > Thanks for previous post, it was useful! > > So now I know what is a problem, but I don't know how to solve > it.Under my application user can convert his python code to > executable, > I was created this with subprocess: > > retcode =subprocess.Popen(["ython","setup.py","py2exe","-d","exe"], > shell=True, stdout=subprocess.PIPE,creationflags = > win32process.CREATE_NO_WINDOW) > stdout_value = retcode.communicate()[0] > > ...Py2exe exit from process here: > > running py2exe > creating C:\Users\veki\Desktop\python\PGS\dist\build > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32 > creating C:\Users\veki\Desktop\python\PGS\dist\build > \bdist.win32\winexe > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe > \collect-2.5 > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe > \bundle-2.5 > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe > \temp > creating C:\Users\veki\Desktop\python\PGS\dist\exe > *** searching for required modules *** > > ...it's trying to find d3d,d3dx,d3dc,d3dgui... modules but it can't > cause these modules are in library.zip.How can I set target for > finding path to library.zip , I'm running these py2exe compile process > from my main excutable? > > Regards, > Vedran From kwmsmith at gmail.com Wed Mar 26 01:53:29 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Wed, 26 Mar 2008 00:53:29 -0500 Subject: subprocess.popen function with quotes In-Reply-To: References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: On Wed, Mar 26, 2008 at 12:15 AM, skunkwerk wrote: > On Mar 25, 9:25 pm, "Gabriel Genellina" > wrote: > > En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk > > escribi?: > > > > > >> i'm trying to call subprocess.popen on the 'rename' function in > > >> linux. When I run the command from the shell, like so: > > > > >> rename -vn 's/\.htm$/\.html/' *.htm > > > > >> it works fine... however when I try to do it in python like so: > > >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > > >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > > > >> print p.communicate()[0] > > > > >> nothing gets printed out (even for p.communicate()[1]) > > > > > I'd try with: > > > > p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > > stdout=subprocess.PIPE, stderr=subprocess.PIPE, > > shell=True) > > > > (note that I added shell=True and I'm using a raw string to specify the > > reg.expr.) > > > > -- > > Gabriel Genellina > > Thanks Gabriel, > I tried the new command and one with the raw string and single > quotes, but it is still giving me the same results (no output). any > other suggestions? I had similar problems passing quoted arguments to grep -- I don't have rename on my system so I can't do an exact translation. First version, passing argument to grep that would normally have to be quoted if typed in shell: In [1]: from subprocess import * In [2]: p1 = Popen(['ls'], stdout=PIPE) In [3]: p2 = Popen(['grep', '[0-9]\{7\}'], stdin=p1.stdout, stdout=PIPE) # note that the grep regex isn't double quoted... In [4]: output = p2.communicate()[0] In [5]: print output cur0046700.png cur0046700_1.png cur0046750.png dendat0046700.png dendat0046700_1.png dendat0046750.png And we see that everything is hunky dory. Now, trying to pass grep a quoted argument: In [10]: p1 = Popen(['ls'], stdout=PIPE) In [11]: p2 = Popen(['grep', '"[0-9]\{7\}"'], stdin=p1.stdout, stdout=PIPE) In [12]: output = p2.communicate()[0] In [13]: print output In [14]: And we get nothing. N.B. that's a single-quote double-quote string argument to grep in the second example, not a triple single quote. Incidentally, a triple quoted string will work as well. Moral from this example: when passing arguments that would normally be quoted to be safe from the shell's expansion, etc, don't. Just pass it using Popen(['cmd', 'arg-that-would-normally-be-quoted']) and it will be passed directly to the function without the shell's intervention. Since the argument is passed directly to the command (rename in your case, grep in this one) quoting to preserve special characters isn't needed, and the quotes will be passed as part of the argument, giving the null results you got above. Kurt From phd at phd.pp.ru Mon Mar 3 11:48:33 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 3 Mar 2008 19:48:33 +0300 Subject: SQLObject 0.9.4 Message-ID: <20080303164833.GC5252@phd.pp.ru> Hello! I'm pleased to announce the 0.9.4 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.3 ---------------- Bug Fixes ~~~~~~~~~ * Use list.reverse() in manager/command.py for Python 2.2 compatibility. * Prevent MultipleJoin from removing the intermediate table if it was not created by the Join. * Fixed a bug with no default when defaultSQL is defined for the column. * Recognize POINT data type as string in PostgresConnection.columnsFromSchema(). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From durieux_br at yahoo.com.br Wed Mar 26 20:53:54 2008 From: durieux_br at yahoo.com.br (Salsa) Date: Wed, 26 Mar 2008 17:53:54 -0700 (PDT) Subject: Daylight savings time problem In-Reply-To: <20080326171009.8a6766bf.darcy@druid.net> Message-ID: <36633.21298.qm@web90607.mail.mud.yahoo.com> Yeah, I guess it would, but it doesn't feel like the "right" way to do it. Isn't there a way I can set tm_isdst to "-1"? Or at least slice the time_struct and then add another element to its end when passing it to mktime? Thanks for all your help! --- "D'Arcy J.M. Cain" wrote: > On Wed, 26 Mar 2008 13:23:23 -0700 (PDT) > Salsa wrote: > > I'm sorry, but could you be more specific? How > exactly should I use UTC? > > Pardon me. I misread. I thought that you were > creating the files. I > see that you are reading files created by someone > else. > > Still, would "os.environ['TZ'] = 'UTC'" fix the > issue? > > -- > 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. > -- Fabio Durieux Lopes - Salsa ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From ggpolo at gmail.com Thu Mar 27 11:04:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 12:04:06 -0300 Subject: Tkinter menus made easy In-Reply-To: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: 2008/3/27, MartinRinehart at gmail.com : > Writing Tkinter menu code used to be rather tedious, uninspiring work. > I figured that I could delegate the job to a program: > I didn't look at it yet, but just in case you weren't aware there is a gui designer tool for tkinter called GUI Designer (what a bad name), which used to be called SpecTcl, where you can design the menus and it then converts to python code. > http://www.martinrinehart.com/articles/menus.py > > Run it. Then look at the source (bottom of file). There's a bit more > doc in the doc comment at the top. > > Peer review is most welcome. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From furkankuru at gmail.com Thu Mar 27 17:37:49 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Thu, 27 Mar 2008 23:37:49 +0200 Subject: Filtering a Python list to uniques In-Reply-To: <438077.65068.qm@web50303.mail.re2.yahoo.com> References: <3a4a8f930803251645g1aed792bv5f0bceaaf2bc650e@mail.gmail.com> <438077.65068.qm@web50303.mail.re2.yahoo.com> Message-ID: <3a4a8f930803271437u9208b1aoc8a545d252e12177@mail.gmail.com> lstOne = [ 'A', 'B', 'C', 'C' ] dct = {} for item in lstOne: if dct.has_key(item): dct[item] += 1 else: dct[item] = 1 On Thu, Mar 27, 2008 at 10:51 PM, Kelly Greer wrote: > I'm in Python 2.4.4 > > And it works for me in the Python Shell like you just > did. Let me try another thing or two. I can't > reproduce the unhashable error now. :( > > Can you help me with one more thing? > If I have > lstOne = [ 'A', 'B', 'C', 'C' ] > > # what is the easiest way to get > # back a dictionary like this: > dct = { 'A': 1, 'B': 1, 'C': 2 } > # in other words counting the times a letter appears > in the list. > > Thanks, > Kelly > > > --- Furkan Kuru wrote: > > > set(lstone) > > works fine in python 2.5.1 > > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) > > [MSC v.1310 32 bit (Intel)] > > on > > win32 > > Type "help", "copyright", "credits" or "license" for > > more information. > > >>> lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > > >>> set(lstone) > > set([1, 2, 3, 4, 5, 6]) > > > > > > > > On 3/26/08, kellygreer1 > > wrote: > > > > > > What is the best way to filter a Python list to > > its unique members? > > > I tried some method using Set but got some > > "unhashable" error. > > > > > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > > > # how do i reduce this to > > > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > > > > > Is there a page on this in the Python in a > > Nutshell or the Python > > > Cookbook? > > > Did I miss something? > > > > > > Kelly Greer > > > kellygreer1 at nospam.com > > > change nospam to yahoo > > > -- > > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > -- > > Furkan Kuru > > > > > > > ____________________________________________________________________________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. > http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From craigm3604 at gmail.com Thu Mar 20 14:09:29 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 11:09:29 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python Message-ID: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> I use a proprietary dll from Software Source (vbis5032.dll). I have successfully used it from Visual Basic 6, Fujitsu Cobol and from Perl. I would now like to use it from Python. The following is the C++ prototype for one of the functions: short FAR PASCAL VmxOpen(BSTR *Filespec, LPSHORT lpLocatorSize, LPSHORT lpOmode, LPHANDLE lphwmcb, BSTR *Password); The following is some Python code I put together: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf sprintf = libc.sprintf print "\nVB/ISAM testing:" fName = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) printf ("fName = \x22%slx22\n", fName) pw = windll.oleaut32.SysAllocStringByteLen("XYZ\x00", 4) printf ("pw = \x22%slx22\n", pw) CacheSize = c_long(0) OpenMode = c_long(3) vHandle = c_long(0) p_vHandle = pointer(vHandle) X = c_long(0) printf ("Before - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." X = windll.vbis5032.VmxOpen(byref(fName), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(pw)) printf ("After - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) exit(0) The following is the output from the Python code: VB/ISAM testing: fName = "s:\msdb\dcodlx22 pw = "XYZlx22 Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\test3.py", line 19, in X = windll.vbis5032.VmxOpen(byref(fName), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(pw)) TypeError: byref() argument must be a ctypes instance, not 'int' I am neither a C++ nor a Python expert, but having already used this dll from other languages, I know this should be possible. I am sure it is just my lack of knowledge of Python. Can anyone assist with this? From deets at nospam.web.de Tue Mar 25 05:56:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Mar 2008 10:56:43 +0100 Subject: StringIO + unicode References: Message-ID: <64s0jhF2ctp4eU1@mid.uni-berlin.de> Laszlo Nagy wrote: > Is there a standard "in-memory file" interface for reading/writting > unicode stings? Something like StringIO. > > E.g. this would be possible: > > - create UnicodeStringIO > - write unicode strings into it > - wite data (binary) string of UnicodeStringIO into a file ('wb' mode) > > and then later: > > - read the same file with codecs.open(filename,"r",encoding="utf-8") > > Maybe there is no standard class for this and I have to implement it > myself. (?) Never tried it, but can't you just combine StringIO + codecs-module, the latter offers a wrapping-service for streams. Diez From bearophileHUGS at lycos.com Thu Mar 27 11:55:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 27 Mar 2008 08:55:13 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: On Mar 27, 3:54 pm, MartinRineh... at gmail.com wrote: > Writing Tkinter menu code used to be rather tedious, uninspiring work. > I figured that I could delegate the job to a program: I did develop a proggy that takes the following as input, it's part of my "agui" project, you can use it as an idea to improve your code: menudef = """ File New, callNew, Ctrl-N New Window, callNewWindow, Ctrl-Shift-N __ Open, lambda e=0:para(1), Ctrl-O __ Save, lambda e=0:para(2), Ctrl-S Save As, CallSaveAs, F12 __ Minimize, called, Ctrl-M Magic, called, Alt-X Edit Cut, called, Ctrl-X Copy, called, Ctrl-C Paste, called, Ctrl-V __ Align Left, Right, ___ """ m = Menu(root, globals(), menudef) Callee: def __init__(self, root, globalVars, menuDef, font=None, fieldSep=",", itemSep="_"): ... Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:06:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:06:22 -0300 Subject: StringIO + unicode References: <47E8C52C.9060501@shopzeus.com> Message-ID: En Tue, 25 Mar 2008 06:26:04 -0300, Laszlo Nagy escribi?: > Is there a standard "in-memory file" interface for reading/writting > unicode stings? Something like StringIO. > > E.g. this would be possible: > > - create UnicodeStringIO > - write unicode strings into it > - wite data (binary) string of UnicodeStringIO into a file ('wb' mode) No. Files contain bytes, not characters; you have to encode the Unicode object when writing to a file (or StringIO object). As Diez suggested, use the codecs classes: py> import codecs py> from StringIO import StringIO py> orig_file = StringIO() py> wrapped_file = codecs.getwriter('hex')(orig_file) py> wrapped_file.write("Hello world!") py> wrapped_file.getvalue() 48656c6c6f20776f726c6421 See http://docs.python.org/lib/stream-writer-objects.html -- Gabriel Genellina From Scott.Daniels at Acm.Org Sat Mar 29 18:25:47 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 29 Mar 2008 15:25:47 -0700 Subject: Licensing In-Reply-To: References: Message-ID: <13utg1v4rs9c2d1@corp.supernews.com> DS wrote: > I'm getting ready to publish a first open-source project written in > python. I am planning to use GPL as the license. However, in my code, > there is a function that I like from Python Cookbook.... > So, my options appear to be: > 1. Don't use it. > 2. Use it with no comment -- that doesn't seem right. > 3. Use it with remarks in the code that acknowledge the source. I vote for this. If you got it of the web site, include a url. If you went for the book, I'd prefer crediting both, but at least give enough so the interested reader can get back to some version of "the original." > 4. Provide a separate licensing page for that function > along with the GPL for my code. > What is the appropriate course of action here? I'm thinking #3 is > probably ok. How do others deal with this in an honorable way? As the author of several of those recipes, I definitely expect others to use them. I'd hate to slow them up by requiring them to ask permission, but would appreciate an acknowledgment. -Scott David Daniels Scott.Daniels at Acm.Org From michael.wieher at gmail.com Sun Mar 9 13:47:55 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 9 Mar 2008 12:47:55 -0500 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: Message-ID: 2008/3/9, Jeff Schiller : > > Hello, I'm creating an application using Qt (4.4 Beta atm). I have pretty > close to zero experience with Python (consisting of installing the > Python interpreter, downloading a python programming and executing it > on the command-line). > > I would like to invoke a Python script from my C++ Qt program and > capture its output as a C++ structure. It seems that PythonQt might > be suitable for my needs. > > Being a Qt program, I want this thing to be cross-platform. I'm > having trouble getting things set up in Windows. Has anyone had any > experience with this? > > I've built Qt from source using the mingw32 compiler. I installed > Python 2.5 binary. I am trying to build PythonQt from source. As per > http://pythonqt.sourceforge.net/#Building it says I need a "developer > installation" of Python containing the header files and the library > files. When I look at my system after installing the Python 2.5 > binary, I can see I have header files (C:\Python25\include), a 199k > python25.lib (C:\Python25\libs) and a 2MB python25.dll > (C:\Windows\System32\). Have I got what I need? > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > to build but then it fails: > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyCFunction_Type' > ... > > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. > > Thanks, > Jeff > > -- > http://mail.python.org/mailman/listinfo/python-list Another thing to be aware of, although this might not be something you need to worry about, is that there are debug-versions of the python libraries that are not installed by the MSI installer on windows. Sadly, the only way to get these libraries is to compile Python from source on your Windows machine, being sure to also create the debug libraries at this time. I don't know if you need them or not, because the error message you got was not entirely descriptive. ~mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.wieher at gmail.com Fri Mar 21 15:57:13 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 21 Mar 2008 14:57:13 -0500 Subject: How can I make a function equal to 0? In-Reply-To: References: Message-ID: Well, you could have a variable f that points at a memory address, such that >>> def x(): ... return ... >>> x >>> x=0 >>> x 0 >>> but I don't really understand why/what you're trying to do 2008/3/21, Martin Manns : > > Hi, > > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > > >>> def f(): return "" > ... > >>> # Some magic > >>> f == 0 > True > > Thanks in advance > > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:27:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:27:45 -0300 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13utucbj9mkrpd4@corp.supernews.com> Message-ID: En Sat, 29 Mar 2008 23:23:07 -0300, Steven D'Aprano escribi?: > The general problem is that I wish to time an arbitrary function with > arbitrary arguments. The function and arguments are provided to me as > Python objects, but timeit requires strings. Converting the objects to > strings is not practical, and the objects might not exist in the __main__ > module. Ah, ok, I understand now. I think this is more-or-less what you want: py> def test1(s): ... return len(s) ... py> def test2(s): ... return s.__len__() ... py> from timeanyfunc import timeanyfunc py> timeanyfunc(test1, [1,2,3]) [1.3858088108963571, 1.3810702198184406, 1.3818543976957964] py> timeanyfunc(test2, [1,2,3]) [1.6241321173501095, 1.6240804348038651, 1.6195021993018663] # timeanyfunc.py from timeit import Timer def timeanyfunc(fn, *args, **kw): global wrapped_fn def wrapped_fn(): return fn(*args, **kw) return Timer("wrapped_fn()", "from %s import wrapped_fn" % __name__ ).repeat() -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Mar 28 16:57:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 17:57:32 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: > I am trying to install the twitter python wrapper...I got that > installed just fine, but am having serious troubles getting the > simplejson package to install. I need help diagnosing where this is > failing. I am trying to use: > > http://pypi.python.org/pypi/simplejson > > and I run "python setup.py build" and then "python setup.py install", > which both seem to work just fine. I don't understand - if it worked fine, what's the problem? > I tried running with easy_install, but that too is not working. I end > up with: > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > in my: > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > packages/ > > I am on Mac OS X 10.5. Any help would be greatly appreciated. And then you import simplejson and it fails? Or what? -- Gabriel Genellina From tmp1 at viltersten.com Fri Mar 7 13:04:35 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 19:04:35 +0100 Subject: SV: Regarding coding style In-Reply-To: References: <63d80bF273nraU1@mid.individual.net> Message-ID: <63ddenF2684mpU1@mid.individual.net> >> 2. You should use two spaces after a >> sentence-ending period. >> >> For heavens sake, why? I've always been >> obstructed by the double blanks but >> tolerated them. Now, that i read that >> it actually is a recommendation, i need >> to ask about the purpose. > > (a) It makes the ends of sentences more visually obvious. > (b) It makes text easier to parse reliably from scripts. > (c) Some text-editors can navigate such sentences out of > the box, whereas others cannot. Got it. Thanks. :) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From bj_666 at gmx.net Thu Mar 20 10:24:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Mar 2008 14:24:16 GMT Subject: Problem with PARAGRAPH SEPARATOR References: Message-ID: <64facgF29ep7qU1@mid.uni-berlin.de> On Thu, 20 Mar 2008 13:03:17 +0000, Dominique.Holzwarth wrote: > The output of the transformation (a big string containg the whole file) > contains a so called 'paragraph separator' (unicode: 2029). If I want to > pring that string (file) to the std out or a file object then I get a > "UnicodeError" saying that the unicode 2029 can't be encoded... > > Can anyone please tell me how I should handle that paragraph seperator? You have to encode the unicode object in an encoding that know this character. UTF-8 might be a candidate encoding for this. Ciao, Marc 'BlackJack' Rintsch From darcy at druid.net Wed Mar 5 10:13:59 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 10:13:59 -0500 Subject: Why """, not '''? In-Reply-To: References: Message-ID: <20080305101359.20a8234d.darcy@druid.net> On Wed, 5 Mar 2008 06:56:24 -0800 (PST) MartinRinehart at gmail.com wrote: > Why is """ the preferred delimiter for multi-line strings? Where did you see that? The only place I saw it was the style guide and it was only talking about docstrings. Even there they used """ as an example but the text talked about using triple quotes as opposed to single quotes even when it is a single line docstring. I don't think that there is any preference for """ over ''' in general. Pick one for consistiency. Note however that """ can't be confused with " followed by ' as in "'A' is the first letter of the alphabet." -- 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 rschroev_nospam_ml at fastmail.fm Sat Mar 8 10:20:44 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 08 Mar 2008 16:20:44 +0100 Subject: List as FIFO in for loop In-Reply-To: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: malkarouri schreef: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > x = q.get() > #process x to get zero or more y's > #for each y: > q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > #process x to get zero or more y's > q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? Changing a loop while iterating over it is to be avoided, if possible. In any case, a deque is more efficient for this kind of use. I'd use it like this: from collections import deque q = deque([a, b, c]) while q: x = q.popleft() # ... q.append(y) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From hasnihon.support at gmail.com Mon Mar 24 19:51:00 2008 From: hasnihon.support at gmail.com (hasnihon.support at gmail.com) Date: Mon, 24 Mar 2008 16:51:00 -0700 (PDT) Subject: Serving another web site which requires authentication References: Message-ID: Hi binaryj, Yeah I feel lucky, thanks... Well, actually, I want my users to be able to see the auction information about some vehicles. It's a Japanese site (https://www.iauc.co.jp/) I've no experience about the proxy staff, but when I googled I found; - Twisted - pyCurl but, I don't know how to all the proxy thing... especially, serving the password protected area of the site.. hoping to feel lucky again :) On 24 Mart, 23:01, binaryj wrote: > ur in luck i am an expert at this! > tell me the details , site name etc > > you would have to proxy everything, basically the urls in the copied > page have to be changed to point to ur site. > > its highly possible. a minor adjustment to ur urlconf and it will work. From justin.mailinglists at gmail.com Tue Mar 18 23:08:11 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 18 Mar 2008 20:08:11 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: FWIW, using json.py I got from somewhere forgotten, >>> import json >>> url = 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails' >>> params = {'format':'json'} >>> import urllib >>> eparams = urllib.urlencode(params) >>> import urllib2 >>> request = urllib2.Request(url,eparams) >>> response = urllib2.urlopen(request) >>> s = response.read() >>> len(s) 115337 >>> s[:200] '{"phedex":{"request": [{"last_update":"1188037561","numofapproved":"1","id":"7425"}, {"last_update":"1188751826","numofapproved":"1","id":"8041"}, {"last_update":"1190116795","numofapproved":"1","id":"92' >>> x = json.read(s) >>> type(x) >>> x.keys() ['phedex'] >>> type(x['phedex']) >>> x['phedex'].keys() ['request_date', 'request_timestamp', 'request', 'call_time', 'instance', 'request_call', 'request_url'] ## json.py implements a JSON (http://json.org) reader and writer. ## Copyright (C) 2005 Patrick D. Logan ## Contact mailto:patrickdlogan at stardecisions.com ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA From castironpi at gmail.com Thu Mar 6 17:30:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 14:30:14 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> <63b46aF26qudpU1@mid.uni-berlin.de> Message-ID: <9a5a78e4-79b2-4001-a8dc-5af816185b0c@f47g2000hsd.googlegroups.com> On Mar 6, 2:57?pm, Marc 'BlackJack' Rintsch wrote: > On Thu, 06 Mar 2008 11:06:50 -0800, castironpi wrote: > > On Mar 6, 8:30?am, Carl Banks wrote: > >> Anyway, the answer to what you are probably asking is No. ?Try this: > > >> >>>import module > >> >>>c1 = module.Someclass > >> >>>reload(module) > >> >>>c2 = module.Someclass > >> >>>c1 is c2 > > > What about > > >>>> o= object() > >>>> b1= o.someattr > >>>> reload( o ) > >>>> b2= o.someattr > >>>> b1 is b2 > > > ? > > You are really a bit thick, a troll, or a bot. The point was, that's one difference between classes and modules: you can't reload classes plonk. From sajmikins at gmail.com Tue Mar 18 18:42:22 2008 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Mar 2008 15:42:22 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: <35a65348-dfa4-4aae-a734-a14c120754a9@s19g2000prg.googlegroups.com> I love you guys, thanks! ;-) ~Simon From Lie.1296 at gmail.com Tue Mar 4 11:50:54 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 4 Mar 2008 08:50:54 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: On Mar 4, 1:12?pm, Mensanator wrote: > On Mar 3, 11:58?pm, Erik Max Francis wrote: > > > Mensanator wrote: > > > While we're on the subject of English, the word "worthless" > > > means "has no value". So, a program that doesn't work would > > > generally be "worthless". One that not only doesn't work but > > > creates side effects that cause other programs to not work > > > (which don't have bugs) would be "worse than worthless". > > > All programs have bugs, which means that in some circumstances, they > > won't work. ? > > And in such circumstances, would be worthless. > > > Therefore, by your reasoning, all programs are worse than > > useless. > > That doesn't follow from my reasoning. > > Suppose you downloaded a new calculator program that > couldn't add properly. That would be useless to you, right? > > But suppose the program contained a virus that erased > your hard drive. That would be "worse than useless", wouldn't it? > > > > > > I'm not hard to please at all. > > > No, of course not, since logically you must think all software is useless. > > Somehow, I expected better logic from people who call themselves > programmers. Mensanator, for alls sake, you've done right by pointing out the bug instead of muttering silently in your room, but there is a thing called tolerance that you really should learn, it's about tolerating and understanding the possibility that other people are humans too and humans create mistakes, lots of them in fact and that includes you (if you're humans). Along with tolerance should come a better choice of wordings, instead of saying "it sucks because it does something unexpected and unwanted" and telling everyone not to use it, you could just say "it does something unexpected and unwanted" and say that you wanted it fixed. It's not that you've done anything wrong, but it's about your attitude. From Dominique.Holzwarth at ch.delarue.com Thu Mar 20 11:39:50 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 20 Mar 2008 15:39:50 +0000 Subject: Problem with PARAGRAPH SEPARATOR In-Reply-To: <64facgF29ep7qU1@mid.uni-berlin.de> Message-ID: <8D5970DD46B50A409A0E42BA407964FE0E6DF433@SGBD012007.dlrmail.ad.delarue.com> Actually that's what I tried to do, for example: outputString = myString.encode('iso-8859-1','ignore') However, I always get such messages (the character, that's causing problems varies, but its always higher than 127 ofc...) 'ascii' codec can't decode byte 0xc3 in position 51: ordinal not in range(128) It doesn't matter what encoding I use (tried 'utf-8' 'utf-16' 'latin_1' and the iso one). The debugger is showing all the special characters (from french and german language) so I'm wondering why there's still the message about the 'ascii' codec... Would that mean that the string "myString" is an ascii-string or what? -----Original Message----- From: Marc 'BlackJack' Rintsch [mailto:bj_666 at gmx.net] Sent: Donnerstag, 20. M?rz 2008 15:24 To: python-list at python.org Subject: Re: Problem with PARAGRAPH SEPARATOR On Thu, 20 Mar 2008 13:03:17 +0000, Dominique.Holzwarth wrote: > The output of the transformation (a big string containg the whole > file) contains a so called 'paragraph separator' (unicode: 2029). If I > want to pring that string (file) to the std out or a file object then > I get a "UnicodeError" saying that the unicode 2029 can't be encoded... > > Can anyone please tell me how I should handle that paragraph seperator? You have to encode the unicode object in an encoding that know this character. UTF-8 might be a candidate encoding for this. Ciao, Marc 'BlackJack' Rintsch ********************************* This e-mail and any files attached are strictly confidential, may be legally privileged and are intended solely for the addressee. If you are not the intended recipient please notify the sender immediately by return email and then delete the e-mail and any attachments immediately. The views and or opinions expressed in this e-mail are not necessarily the views of De La Rue plc or any of its subsidiaries and the De La Rue Group of companies, their directors, officers and employees make no representation about and accept no liability for its accuracy or completeness. You should ensure that you have adequate virus protection as the De La Rue Group of companies do not accept liability for any viruses De La Rue plc Registered No.3834125, De La Rue Holdings plc Registered No 58025 and De La Rue International Limited Registered No 720284 are all registered in England with their registered office at: De La Rue House, Jays Close, Viables, Hampshire RG22 4BS From ptrk.mcm at gmail.com Tue Mar 25 23:37:07 2008 From: ptrk.mcm at gmail.com (ptrk.mcm at gmail.com) Date: Tue, 25 Mar 2008 20:37:07 -0700 (PDT) Subject: Files, directories and imports - relative to the current directory only References: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> Message-ID: <5608b49d-5537-4f35-85c3-6fd346ffd4fb@t54g2000hsg.googlegroups.com> On Mar 25, 11:27 am, ptn wrote: > Hello, group. > > I can only read files and import modules that are in the same > directory > as the one my script is. Here is a test script (path.py): > > import os > import uno # some module I wrote > > print list(os.walk('~/hacking/python')) > f = open('~/read/foo.txt') > print f.read() > > And here is the output: > > Traceback (most recent call last): > File "path.py", line 2, in > import uno > ImportError: No module named uno > > If I comment that import, the output becomes this: > > [] > Traceback (most recent call last): > File "path.py", line 4, in > f = open('~/read/foo.txt') > IOError: [Errno 2] No such file or directory: '~/read/foo.txt' > > (Notice the empty list at the beginning, that would be the output of > os.walk().) > > I have added this line to my .bashrc: > export PYTHONPATH=$PYTHONPATH:~/hacking/python > I thought that by doing so all the scripts found in that directory and > all it's children would be available for import, but that doesn't seem > to be the case. i'm not sure why you are unable to import uno (assuming uno is at ~/ hacking/python/uno.py) after exporting the PYTHONPATH variable. an alternative way to incorporate uno is to change sys.path, the list of search paths import sys sys.path.append(os.path.expanduser('~/hacking/python')) import uno From yuxi at ece.gatech.edu Wed Mar 12 20:44:50 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Wed, 12 Mar 2008 20:44:50 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > The photos are just coming straight from my digital camera. Same > format (JPEG), varying size (6-10 megapixel) and I would like to be > able to pick one and then query the database for similar ones. For > example: I pick a photo which is more or less a portrait of someone, > the query should return other photos with more or less portraits. If I > pick a landscape with lot of green and a mountain the query should > result in other nature (mostly green) photos. Something along these > lines, of course the matches won't be perfect because I'm looking for > a simple algorithm, but something along these lines. > Ah. In that case, SIFT isn't for you. SIFT would work well if you have multiple photos of the same object. Say, a building from different angles, or the a vase against different backdrops. If I'm understanding your correctly, what you're attempting here is very general and well into the highly experimental. I've been wishing for such a feature to appear in something like Google Image Search (pick/submit a photo and return similar images found on the web). I'm sure if there's even a practical solution, Google (or MS) would be on it already. The problem is that there isn't really one. Despite what you may see claimed in university press releases and research papers, the current crop of algorithms don't work very well, at least according to my understanding and discussion with researchers in this field. The glowing results tend to be from tests done under ideal conditions and there's no real practical and commercial solution. If you restrict the domain somewhat, there are some solutions, but none trivial. You are probably aware of the face searches available on Google and Live. The histogram approach suggested by Shane Geiger may work for some cases and in fact would work very well for identical resized images. I doubt it will work for the general case. A mountain with a grassy plain at noon has quite a different histogram from one at sunset, and yet both have related content. Manual tagging of the images, a la Flickr, would probably be your best bet. Good luck. From grante at visi.com Thu Mar 6 09:13:28 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 06 Mar 2008 14:13:28 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> <87hcfk30lo.fsf@micah.cowan.name> Message-ID: <13svv088r9eu256@corp.supernews.com> On 2008-03-06, Micah Cowan wrote: > castironpi at gmail.com writes: >> On Mar 5, 8:03?pm, castiro... at gmail.com wrote: >>> assert b not in d >>> #there's the hangup >> >> *plonk* >> >> key is an iterable, just like the constructors to >> other collection. > > Um... "*plonk*" is the (imaginary) sound made by dropping someone into > your plonkfile (killfile, scorefile, whatever): the action of setting > your newsreader to ignore someone you perceive to be a troll. > > I have extreme doubts that you have actually done this to _yourself_. Oh, I don't know. I wouldn't be a bit surprised if he never reads anything that he's writes. ;) -- Grant Edwards grante Yow! I have many CHARTS at and DIAGRAMS.. visi.com From tmp1 at viltersten.com Sun Mar 2 11:50:58 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 17:50:58 +0100 Subject: SV: Where's GUI for Python? In-Reply-To: References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: <63038fF23j6foU1@mid.individual.net> >> You should also take a look at wxGlade: >> >> http://wxglade.sourceforge.net/ >> >> which sits on top of wxPython: >> >> http://wxpython.org/ >> >> which wraps wxWidgets: >> >> http://www.wxwindows.org/ > > I have used wxGlade, and while it worked well > enough, it didn't seem to fit my brain. I > always found myself "thinking backwards" in order > to guess how the tool needed me to do things. > For me, though, everytime I see raw wxPython code > these days I cringe, and am thankful that I don't > have to deal with it anymore. May i see a short sample of the two different ways of coding, please? I'm very curious how they differ (and of course, decide what's the most pleasurable way for me). As long as we're on the subject, i also wonder if there's a general concensus on which technology is recommended in the different types of projects that are developed. (E.g. "use A for small/fast fixes, use B for stuff you'll need to maintain later on".) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From wbsoft at xs4all.nl Thu Mar 20 09:45:02 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Thu, 20 Mar 2008 14:45:02 +0100 Subject: Thanks. (Re: keeping state in an iterator object by rebinding next()) In-Reply-To: <691a1267-0407-43e4-96d3-d58467af8614@59g2000hsb.googlegroups.com> References: <691a1267-0407-43e4-96d3-d58467af8614@59g2000hsb.googlegroups.com> Message-ID: <200803201445.02913.wbsoft@xs4all.nl> Thanks for all the elaborate answers and help! It helped me deepening my understanding of Python. Sincere, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandhi From sjmachin at lexicon.net Mon Mar 24 19:24:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Mar 2008 16:24:27 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: On Mar 25, 9:05 am, Julien wrote: > Hi all, and thanks a lot for your answers! > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making > up the term) a function: > > def hijacker(arg): > if I_feel_its_necessary: > hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > hijacker(something) > ... # Continue as normal > return 2 > Your end goal (avoiding duplicate code) is laudable. However most folk manage to do this without needing to invent arcane control structures like the COME FROM and the COBOL ALTER verb. def common_code(arg): if necessary(arg): return 1 # assuming None is not a valid return from myfunc1 etc return None def myfunc1(arg): return_value = common_code(something) if return_value is not None: return return_value # continue # Look, Ma! No decorators! Those functions could be methods of classes, but IMHO you don't need anything fancier than that. You mentioned maintainability. To borrow someone else's advice: Consider that the next person to maintain your code may know where you live and may possess a chain-saw. HTH, John From deets at nospam.web.de Mon Mar 10 11:58:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 16:58:33 +0100 Subject: defining a method that could be used as instance or static method References: Message-ID: <63l454F275mskU1@mid.uni-berlin.de> Sam wrote: > Hello > > I would like to implement some kind of comparator, that could be > called as instance method, or static method. Here is a trivial pseudo > code of what I would like to execute > >>> class MyClass: > ... def __init__(self, value): > ... self.value = value > ... def comp(self, compValue): > ... return self.value == compValue.value >>> a = MyClass(3) >>> b = MyClass(4) >>> c = MyClass(3) >>> a.comp(b) > False >>> a.comp(c) > True > > This is actually achieved by MyClass, how could implement it in order > to accept: > >>> MyClass.comp(a, b) > False > > I would really appreciate a pointer or a way to complete MyClass in > order to fulfill my requirements. Thank you for your attention. Did you try that it doesn't work? because it should. Whenever you do instance.method(arg, ..) you can as well do Class.method(instance, arg, ...) so your requirement should be met by comp already. Diez From qggjonny at msn.com Mon Mar 31 13:43:15 2008 From: qggjonny at msn.com (qgg) Date: Mon, 31 Mar 2008 10:43:15 -0700 (PDT) Subject: How to build a body like this use SOAPPy? Message-ID: <0b531c8c-9f33-48f5-9446-09a1cb2db313@e6g2000prf.googlegroups.com> repeat arrWords aa 11 bb 22 99 I try like this,but fail: WordsRequest(arrWords=[{'Name:u'aa','Num':u'11'}, {'Name:u'bb','Num':u'22'}],intActionId=99) WordsRequest(arrWords={'Name:u'aa','Num':u'11'},arrWords={'Name:u'bb','Num'?:u'22'},intActionId=99) From deets at nospam.web.de Thu Mar 13 06:21:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 11:21:52 +0100 Subject: List mutation method gotcha - How well known? References: Message-ID: <63sdi1F28jh62U1@mid.uni-berlin.de> Hendrik van Rooyen wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above > > I undertake to summarise answers posted to complete this "survey". None, as python chose deliberately to return None on mutating functions like append, sort and reverse. Diez From nishanthy012 at gmail.com Mon Mar 31 07:13:03 2008 From: nishanthy012 at gmail.com (nishanthy012 at gmail.com) Date: Mon, 31 Mar 2008 04:13:03 -0700 (PDT) Subject: DOYOULIKECOMPUTER Message-ID: <23dd1bcd-5157-4194-b18f-03655b19009a@b5g2000pri.googlegroups.com> http://myprofile0116.blogspot.com From ssharkey at linuxunlimited.com Wed Mar 26 12:33:31 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Wed, 26 Mar 2008 12:33:31 -0400 Subject: naive packaging question Message-ID: <47EA7ADB.3030400@linuxunlimited.com> Hello all, I've read a number of the python books, and several online tutorials about modules and packaging, but not one addresses this issue, so I thought I'd ask here... I am building a library for use in an internal project. This library is the client side interface to a REST-ful service that provides access to parts of our accounting database. BUT, we are pretty sure that the accounting database and hence the service implementation will change in the future. So, I want to design a generic (abstract) api for fetching various info from the accounting db, but I want to isolate the specific details into a module/package that can be changed in future (and co-exist with the old one). I've designed a generic api class, with functions to fetch the various info into python data structures (mostly lists of dictionaries, some just single values). And I've got an interface-specific version that follows that same api, and which is derived from the generic api. I'm a bit unclear on the best way to implement the module and package. Here's the directory structure that I've got so far: project

top level directory setup.py company eventually, we'll have other modules __init__.py error.py some classes that will be used in all log.py modules acctdb the acct db interface directory __init__.py api.py the abstract class def (derived from object) specific.py the specific implementation, derived from the api base class For arguments sake, let's call the base class (defined in api.py) 'BaseClass', and the specific implementation 'SpecificClass(BaseClass)' So, in the acctdb/__init__.py, do I do something like this: if SPECIFIC_CLASS: from company.acctdb.specific import SpecificClass as BaseClass with the idea that at some point in the future I'd designate a different class in some other way? Hopefully this is enough info for you to see what I'm trying to accomplish. It's a bit like the DB interfaces, where there is a generic DB API, and then the different drivers to implement that API (MySQL, etc). Thanks for any suggestions! -scott From gagsl-py2 at yahoo.com.ar Tue Mar 18 23:05:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 00:05:08 -0300 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: En Tue, 18 Mar 2008 18:25:28 -0300, Jeff Schwab escribi?: > I need to move a directory tree (~9GB) from one machine to another on > the same LAN. What's the best (briefest and most portable) way to do > this in Python? See Tools/scripts/ftpmirror.py in your Python installation. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Mar 26 00:14:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 01:14:23 -0300 Subject: last mouse movment or keyboard hit References: Message-ID: En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler escribi?: > I would like to get the time of the most recent human activity like a > cursor > movement or a key hit. > Does anyone know how I can get this back to start some action after there > has been no activity for X minutes/seconds? Which platform? On non-ancient Windows versions, you can periodically check GetLastInputInfo http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp -- Gabriel Genellina From martin at v.loewis.de Sat Mar 1 18:41:48 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Mar 2008 00:41:48 +0100 Subject: cx_Freeze : LookupError: unknown encoding: ascii In-Reply-To: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> References: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> Message-ID: <47c9e9bc$0$4562$9b622d9e@news.freenet.de> > Can somebody point to some clues about options that need to be passed > to FreezePython API to get the right executable. You need to tell it to include the encodings.ascii module. Regards, Martin From jkugler at bigfoot.com Tue Mar 18 13:13:58 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Tue, 18 Mar 2008 09:13:58 -0800 Subject: Comunicate processes with python References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> Message-ID: Adri?n Bravo Navarro wrote: >> Is there any simple way to achieve this goal? We've been thinking of >> sockets but Im not conviced at all with that. If you want to communicate between processes on the same host, yes, you can use DBus or a couple of the options here: http://docs.python.org/lib/ipc.html If you want to communicate between hosts, then sockets is probably going to be your only options, although there are libraries that abstract some of that for you to make it easier to manage. You might want to take a look at Pyro. http://pyro.sourceforge.net/ j From micah at micah.cowan.name Sat Mar 1 21:31:35 2008 From: micah at micah.cowan.name (Micah Cowan) Date: Sun, 02 Mar 2008 02:31:35 GMT Subject: Book Recomendations References: Message-ID: <87ablhkga7.fsf@micah.cowan.name> Ira Solomon writes: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. I have found the official documentation available at python.org (including both the tutorial and references) to be very high-quality. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From nodrogbrown at gmail.com Fri Mar 7 11:30:18 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 7 Mar 2008 08:30:18 -0800 (PST) Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: <507cc368-cfd4-4030-a4da-3a56c602c5f4@e60g2000hsh.googlegroups.com> > If the string is only used to open a file, and never shown to the user, > what you prefer is irrelevant, isn't it? guess thats right.. > Back to your code, try this: > > from os.path import join, normpath > folder = 'F:/brown/code/python/fgrp1' > names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist = [normpath(join(folder, name)) for name in names] thanks Gabriel.. gordon From josef.pktd at gmail.com Mon Mar 17 12:03:07 2008 From: josef.pktd at gmail.com (joep) Date: Mon, 17 Mar 2008 09:03:07 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <0369b78b-6681-4807-b944-fb371cdd1522@59g2000hsb.googlegroups.com> Message-ID: On Mar 16, 10:35 pm, sturlamolden wrote: > On 15 Mar, 21:54, Unknown wrote: > > > I was expecting to replace the old value (serial) with the new one > > (todayVal). Instead, this code *adds* another line below the one found... > > > How can I just replace it? > > A file is a stream of bytes, not a list of lines. You can't just > replace a line with another, unless they have the exact same length. > You must rewrite the whole file to get it right. An example: looks for all 'junk*.txt' files in current directory and replaces in each line the string 'old' by the string 'new' import os, glob, fileinput allfiles = glob.glob(os.getcwd() + '\\junk*.txt') # makes absolute paths findstr = 'old' replstr = 'new' countlinesfound = 0 for line in fileinput.input(allfiles,inplace=1): if line.find(findstr) != -1: line = line.replace(findstr,replstr) # old string , new string countlinesfound += 1 print line, # this writes line back to the file print countlinesfound I found something similar in a tutorial when I started to learn Python, but I don't remember which one. Josef From darcy at druid.net Wed Mar 26 17:10:09 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 Mar 2008 17:10:09 -0400 Subject: Daylight savings time problem In-Reply-To: <585793.80038.qm@web90609.mail.mud.yahoo.com> References: <585793.80038.qm@web90609.mail.mud.yahoo.com> Message-ID: <20080326171009.8a6766bf.darcy@druid.net> On Wed, 26 Mar 2008 13:23:23 -0700 (PDT) Salsa wrote: > I'm sorry, but could you be more specific? How exactly should I use UTC? Pardon me. I misread. I thought that you were creating the files. I see that you are reading files created by someone else. Still, would "os.environ['TZ'] = 'UTC'" fix the issue? -- 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 roygeorget at gmail.com Tue Mar 11 06:35:46 2008 From: roygeorget at gmail.com (royG) Date: Tue, 11 Mar 2008 03:35:46 -0700 (PDT) Subject: rmdir problem Message-ID: hi i am checking if a directory exists and if it does i want to delete it and its contents.then i want to create the directory before creating files in it. def myfolderops(): testdir='..\mytestdir' #if dir exist remove it if isdir(testdir): rmdir(testdir) #again create directory mkdir(testdir) I am working on WinXP and logged in as admin in WinXP. when there is no dir called '..\mytestdir' or an empty dir this code works removing and creating the directory.but if the directory exists with contents already then it causes an error 145 when rmdir is executed.the message says 'directory is not empty' what should i do to correct this? (i need to remove the dir with its contents because each time i will be putting diff files into it and donot want them to be mixed with old files) thanks RG From jphalip at gmail.com Mon Mar 24 18:05:38 2008 From: jphalip at gmail.com (Julien) Date: Mon, 24 Mar 2008 15:05:38 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: Hi all, and thanks a lot for your answers! I'll try to explain a bit more what I'm after, and hopefully that will be clearer. In fact, what I'm trying to do is to "hijack" (I'm making up the term) a function: def hijacker(arg): if I_feel_its_necessary: hijack_caller_function_and_make_it_return(1) def my_function1(arg): hijacker(something) ... # Continue as normal return 2 def my_function2(arg): ... # Maybe do some processing here hijacker(whatever) ... # Continue as normal return 3 I have some long functions like my_function1 and my_function2 which I'd like to alter, but I want to keep the alterations as little as as possible. I'd like the extra behaviour to be handled by 'hijacker' and let it decide what the caller function should return. Just adding a call to 'hijacker' in all of these functions would be ideal for me because that would be quick to modify them and also easier to maintain, I believe. If 'hijacker' thinks it's necessary, it would force the caller function to return a certain value, otherwise it would let the caller function do its normal business. For while I thought I'd make hijacker a decorator: @hijacker def my_function(request): .... But that wouldn't work, since some functions need to do some processing before calling the hijacker. Yet, I think a decorator is systematically called before the function itself so no prior processing can be done by the function... Any idea on how to do that, if that's even possible? Thanks! Julien On Mar 25, 2:06 am, castiro... at gmail.com wrote: > On Mar 24, 9:48 am, Jason wrote: > > > > > On Mar 24, 5:21 am, Julien wrote: > > > > Hello all, > > > > I would like to do something like: > > > > def called(arg) > > > if arg==True: > > > !!magic!!caller.return 1 > > > > def caller(arg) > > > called(arg) > > > return 2 > > > > Here, the fake !!!magic!!! represents a statement (which I ignore) > > > that would make the caller function return a value different from what > > > it'd return normally. > > > > For example, caller(True) would return 1, and caller(False) would > > > return 2. The reason I want that is because I don't want the caller > > > function to know what's going on in the called function, and be > > > shortcut if the called function think it's necessary. > > > > Would you know if that's possible, and if so, how? > > > > I've done a bit of research and I think I've found some good pointers, > > > in particular using the 'inspect' library: > > > > import inspect > > > > def called(arg) > > > if arg==True: > > > caller_frame = inspect.stack()[1] > > > ... > > > > Here 'caller_frame' contains the frame of the caller function. Now, > > > how can I make that frame return a particular value? > > > > By the way, I'm not really interested in 'called' throwing an > > > exception and 'caller' catching it. In fact, I want things to remain > > > completely transparent for 'caller'. > > > > Hope that was clear... :/ > > > > Thanks! > > > > Julien > > > As Steven wrote, it's not very clear. If we knew the intent of this, > > we could perhaps point you to a more useful, maintainable technique. > > We don't know why you're trying to circumvent the programming language > > in this case. Any solution that works as you described will probably > > be unportable between the different Pythons (CPython, Jython, > > IronPython, etc). > > > Please note that the following code should work, but I've only run it > > through the interpreter in my brain. My brain's interpreter is full > > of Heisenbugs, so you may need to adjust a few things. Here's my > > thoughts: > > > Given: > > def First( arg ): > > Second( arg ) > > return 5 > > > 1) If you can modify both functions, change the first function to > > return a value in certain circumstances: > > def AltFirst( arg ): > > value = Second( arg ) > > if value is not None: return value > > return 5 > > > 2) Raise an exception in Second, and catch that exception above > > First: > > > class SecondExcept(Exception): > > def __init__(self, value): > > Exception.__init__(self, 'Spam!') > > self.value = value > > > def Second(arg): > > if arg == my_conditional_value: > > raise SecondExcept( 5 ) > > > # The following could even be put in your own function, > > # or in a wrapper or decorator for the First function. > > try: > > myvalue = First( 'Vikings!' ) > > except SecondExcept, exc: > > myvalue = exc.value > > > When you need to use an exceptional pathway, use an exception. They > > aren't just for reporting errors. > > Exceptions are a control tool. There was a 'goto using Exceptions' > once in the manuals. I don't see a problem with a local control-flow > object. It would appease a number of requests I've read. > > for x: > for y: > control.break( 2 ) > > if a: > if b: > control.fail( 2 ) > > so no need to reduplicate: > > else: > thing() > else: > thing() > > if a: > if b: > control.mostrecenttest( 0 ) > > def f(): > def g(): > control.return( 2 )( "early" ) > > Something tells me generators could solve the problem, but I may be > enamored, so it's a separate post. From arnodel at googlemail.com Wed Mar 26 03:27:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 00:27:17 -0700 (PDT) Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: On Mar 25, 10:55?pm, Steven D'Aprano wrote: > On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: > > As per your suggestion, I tried looking at include/code.h and > > include/funcobject.h (my MS Windows distribution does not appear to > > contain .c files). ?However, since I'm not a C programmer, I did not > > find the .h files all that helpful. > > I'm hardly surprised. The naivety of those who insist that the "best way > to understand how new.function and new.code work" is to look at the C > source code for object is amusing. Since 'those who insist...' are just one person, me, you might as well name them. Firstly I didn't 'insist', I stated it once. Secondly I'm glad that I provided you with a few chuckles, but to proclaim that one is 'amused by the naivety of others' doesn't make one automatically right. Do you know how these functions behave? Have you looked at their documentation? new.function and new.code (implemented as Objects/ funcobject.c:func_new and Objects/codeobject.c:new_code) are not really documented (new.code.__doc__ is 'Create a code object. Not for the faint of heart.'). If you can't read the source then I don't think you should use the functions. > Not everybody reads C. This is a > Python group, and surely the best way would be to see some good examples > using *Python*. And this is what I did in the second part of my post. I gave an example which was in essence trying to illustrate the same aspect of Python as your example, quoted below (namely that you can use 'def' to create functions on the fly). > Here's an example that might help. > > class MyClass(object): > ? ? pass > > records = ["spam", "ham"] > for record in records: > ? ? # define a new function > ? ? def f(n): > ? ? ? ? return (record + " ")*n > ? ? # create a new instance > ? ? instance = MyClass() > ? ? # and dynamically add a method to it > ? ? setattr(instance, 'execute', f) > ? ? instance.execute(5) Amusingly naive'ly yours -- Arnaud From castironpi at gmail.com Mon Mar 24 11:26:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 24 Mar 2008 08:26:08 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> <210f1e24-649a-43c0-b975-8209211d56de@a70g2000hsh.googlegroups.com> <6900b188-8d08-4a9b-976f-719ba176fb97@e23g2000prf.googlegroups.com> Message-ID: <74f53b2d-5dae-4d9c-8ca7-f5bedc2f43f8@f63g2000hsf.googlegroups.com> On Mar 23, 12:22?pm, Lie wrote: > On Mar 22, 2:23?pm, castiro... at gmail.com wrote: > > > > Sane programmers don't write such semi-functional things (unless it > > > helps expressing the problem in certain domains). > > > I now think that deprecating map, lambda & Co. was a good thing after > > > all. > > > If you write it that way the first time, you need therapy. ?Actually, > > at this point, I (for one, personally) want to investigate 'certain > > domains'. ?Tell me it's really bad at everything or what it's good > > at. ?What can I respect about it? > > If you (castiro..) write it your way, you'll surely win the Obfuscated > Python Code Contest. Sometimes you're on a roll and you don't want to back up a step. What are good "on a roll" habits? (Or, what roll?) From python.list at tim.thechases.com Sat Mar 1 17:09:45 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 Mar 2008 16:09:45 -0600 Subject: A python STUN client is ready on Google Code. In-Reply-To: References: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> <8ce119530803010101w320b8d30md5112aebab6f7551@mail.gmail.com> Message-ID: <47C9D429.5050706@tim.thechases.com> > |I upload a new version. Add more print log into my code to help people > | understand my program > > Announcements should include a short paragraph explaining what the > announcement is about for those of us not in the know. IE, what is > STUN? -- and therefore, what is a STUN client? I believe this STUN client refers to http://en.wikipedia.org/wiki/Simple_traversal_of_UDP_over_NATs which is used if both user A and user B are behind a NAT'ing (Network Address Translating) firewall, and need to talk directly with each other. -tkc From castironpi at gmail.com Sat Mar 1 09:17:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 06:17:59 -0800 (PST) Subject: UponAcquiring synchro. class Message-ID: <82d1a986-fc02-495b-bace-298bc88440e8@s8g2000prg.googlegroups.com> from __future__ import with_statement ''' 3) upon_acquiring( lockA, lockB )( function, *ar, **kwar ) upon_acquiring spawns new thread upon acquiring locks A and B. Locks may be specified in any order, as none is acquired until all are free. The options to spawn a new thread upon call, lock, and not release until "it's its turn"; just block until then; and vary honoring order are open. 6) @with_self Prepends the function object to itself to the parameter list ''' ''' a lockA lockB b lockA lockB c lockA lockB d lockA lockC e lockB lockD f lockE lockF assert a< b assert b< c assert c< d assert c< e assert f in. ''' ''' A (A,B)1 (A,C)2 (A,B)3 B (A,B)1 (A,B)3 C (A,C)2 (C,D,E)4 D (C,D,E)4 E (C,D,E)4 a.lock: A, a.state: Free, a.waiters: [ X1(a,b), X2(a,c), X3(a,b) ] b.lock: B, b.state: Free, b.waiters: [ X1(a,b), X3(a,b) ] c.lock: C, c.state: Free, X3.waiters: [ X2(a,c), X4(c,d,e) ] d.lock: D, d.state: Free, X3.waiters: [ X4(c,d,e) ] e.lock: E, e.state: Free, X3.waiters: [ X4(c,d,e) ] acq a,b x1= a,b a.waiters+= x1 b.waiters+= x1 #same as if a.state is free and b.state is free: a.state= taken b.state= taken a.waiters-= x1 b.waiters-= x1 a.lock.release() #acq? b.lock.release() #acq? x1.lock.release() acq a,c x2= a,c a.waiters+= x2 c.waiters+= x2 if a.state is free and c.state is free: a.state= taken c.state= taken a.waiters-= x2 c.waiters-= x2 a.lock.release() #acq? c.lock.release() #acq? x2.lock.release() acq a,b x3= a,b a.waiters+= x3 b.waiters+= x3 acq c,d,e x4= c,d,e c.waiters+= x4 d.waiters+= x4 e.waiters+= x4 ''' from thread import start_new_thread from threading import Lock, Thread, Event import time from functools import partial class LockDeps: def __init__( self, lock, state, waiters ): self.lock, self.state, self.waiters= \ lock, state, waiters class LockSet: #ok to use them elsewhere, just gets in line. def __init__( self, *locks ): self._locks= locks self._lock= Lock() self._lock.acquire() self._remains= set( locks ) self._doneevt= Event() self.th= None self.retval= None def release( self, *locks ): for lock in locks: lock.release() self._remains.remove( lock ) def releaseall( self ): for lock in self._remains: lock.release() self._remains.clear() class UponAcquiring: def __init__( self ): self._deps= {} self._oplock= Lock() def acq( self, *locks ): lckset= LockSet( *locks ) return partial( self._enqueue, lckset ) def _enqueue( self, lckset, fun, *ar, **kwar ): with self._oplock: for lock in lckset._locks: dep= self._deps.get( lock ) if None is dep: dep= LockDeps( lock, False, [] ) self._deps[ lock ]= dep dep.waiters.append( lckset ) th= Thread( target= self._functhd, args= ( lckset, fun )+ ar, kwargs= kwar ) lckset.th= th th.start() self._analyze( lckset ) return lckset def _functhd( self, lckset, fun, *ar, **kwar ): try: with lckset._lock: lckset.retval=\ fun( lckset, *ar, **kwar ) lckset._doneevt.set() finally: with self._oplock: lckset.releaseall() for lock in lckset._locks: self._deps[ lock ].state= False self._analyze( lckset ) def _analyze( self, lckset ): with self._oplock: for lock in lckset._locks: dep= self._deps[ lock ] if dep.state: continue for lckset in dep.waiters: assert lock in lckset._locks for lock2 in lckset._locks: if self._deps[ lock2 ].state: break else: for lock2 in lckset._locks: dep2= self._deps[ lock2 ] dep2.state= True assert dep2.waiters.count( lckset )== 1 dep2.waiters.remove( lckset ) lock2.acquire() lckset._lock.release() break results= [] ver= results.index lcksets= set() import random from sys import stdout def callback( locks, i ): stdout.write( 'cb%i '% i ) time.sleep( random.uniform( 0, .01 ) ) results.append( i ) if random.choice( [ False, True ] ): locks.releaseall() #if random.random()< 0.1: # raise Exception() while 1: class Case1: lockA, lockB, lockC= Lock(), Lock(), Lock() lockD, lockE, lockF= Lock(), Lock(), Lock() a= ( lockA, lockB ) b= ( lockA, lockB ) c= ( lockA, lockB ) d= ( lockA, lockC ) e= ( lockB, lockD ) f= ( lockE, lockF ) ua= UponAcquiring() for i, x in enumerate( [ a, b, c, d, e, f ] ): lcksets.add( ua.acq( *x )( callback, i ) ) for lckset in lcksets: lckset.th.join() stdout.write( repr( results ) ) stdout.write( '\n' ) stdout.flush() assert ver( 0 )< ver( 1 ) assert ver( 1 )< ver( 2 ) assert ver( 2 )< ver( 3 ) assert ver( 2 )< ver( 4 ) assert len( set( results ) )== len( results ) '''permissible orders e.g.: [0, 5, 1, 2, 3, 4] [5, 0, 1, 2, 3, 4] [0, 5, 1, 2, 4, 3] [5, 0, 1, 2, 4, 3] ''' del results[:] lcksets.clear() From Graham.Dumpleton at gmail.com Sat Mar 15 02:03:17 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 14 Mar 2008 23:03:17 -0700 (PDT) Subject: How to import custom python file in python server page (psp) ? References: <60bb95410803140415x621b5b23w75b83013997c750b@mail.gmail.com> Message-ID: <3d073ffc-865e-4401-ac92-b22994d2b447@h11g2000prf.googlegroups.com> On Mar 15, 6:44?am, Joshua Kugler wrote: > James Yu wrote: > > Hi folks, > > > I prepared a python script for dynamically get the absolute paths of the > > files in certain folder. > > Then I tried to invoke that function from my web server in a .psp file > > like this: > > > ? ? ? 1 > > ? ? ? 2 > > ? ? ? 3 asdfasdfasdfa > > ? ? ? 4 > > ? ? ? 5 <% > > ? ? ? 6 import glob > > ? ? ? 7 import os > > ? ? ? 8 *import Helper > > * ? ? ?9 > > ? ? ?10 body = '' > > ? ? ?11 top = 'asdfasdfasdfa' > > ? ? ?12 links = {} > > ? ? ?13 *Helper.GetLinks(top=top) > > * ? ? 14 *paths = Helper.GenLinkPath(links) > > * ? ? 15 body = paths > > ? ? ?16 %> > > ? ? ?17 ? ? <%=body%> > > ? ? ?18 > > ? ? ?19 > > > However, this is the error message I received when I open the page in a > > browser: > > >>Mod_pythonerror: "PythonHandlermod_python.psp" > > >> Traceback (most recent call last): > > >> ? File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, > >> in HandlerDispatch > >> ? ? result = object(req) > > >> ? File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 302, in > >> handler > >> ? ? p.run() > > >> ? File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 213, in > >> run > >> ? ? exec code in global_scope > > >> ? File "/var/www/.cyu021/.pic/index.psp", line 8, in > >> ? ? import Helper > > >> ImportError: No module named Helper > > > *PS. I put Helper.py and index.psp in the same dir > > * > > Thanks in advance, > > What is the import path? ?The current directory in PSP might not be the > directory in which the .psp file resides. ?Print out sys.path before you > import your helper module to see what paths you're dealing with. If using mod_python 3.3.1, see: http://issues.apache.org/jira/browse/MODPYTHON-220 Graham From castironpi at gmail.com Tue Mar 18 14:20:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 11:20:50 -0700 (PDT) Subject: Get actual call signature? References: Message-ID: On Mar 18, 5:40?am, Jarek Zgoda wrote: > Say, I have a function defined as: > > def fun(arg_one, arg_two='x', arg_three=None): > ? ? pass > > Is there any way to get actual arguments that will be effectively used > when I call this function in various ways, like: > > fun(5) => [5, 'x', None] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > fun(5, 'something') => [5, 'something', None] > > (et caetera, using all possible mixes of positional, keyword and default > arguments) > > I'd like to wrap function definition with a decorator that intercepts > not only passed arguments, but also defaults that will be actually used > in execution. > > If this sounds not feasible (or is simply impossible), I'll happily > throw this idea and look for another one. ;) It evaluates to a substantial problem. The combinations include things that Python disallows, such as double-spec. of keywords and spec'n of keys w/out a dictionary arg; as well as double-spec'ing of inspection. How do you want to access the parameters? What is the least redundant way? P.S. Does there exist a possible authority who doesn't want me to post this? How about an index of value and list/tuple of name? > def fun(arg_one, arg_two='x', arg_three=None): > fun(5) => [5, 'x', None] get_args( fun, 5 )-> names= [ 'arg_one', 'arg_two', 'arg_three' ] vals= [ 5, 'x', None ] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] get_args( fun, 5, arg_three=['a', 'b'] ) names= [ 'arg_one', 'arg_two', 'arg_three' ] vals= [ 5, 'x', ['a', 'b'] ] > fun(5, 'something') => [5, 'something', None] get_args( fun, 5, 'something' )-> names= [ 'arg_one', 'arg_two', 'arg_three' ] vals= [ 5, 'something', None ] From toby at tobiah.org Mon Mar 24 16:28:41 2008 From: toby at tobiah.org (Tobiah) Date: Mon, 24 Mar 2008 13:28:41 -0700 Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. Can't you just put the script on a network share? Tobiah -- Posted via a free Usenet account from http://www.teranews.com From goon12 at gmail.com Mon Mar 10 19:12:37 2008 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 10 Mar 2008 19:12:37 -0400 Subject: Python Sockets Help In-Reply-To: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> References: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> Message-ID: <6a2ccd190803101612l1a59ba27q83b88add32f28066@mail.gmail.com> On Mon, Mar 10, 2008 at 6:58 PM, Mark M Manning wrote: > I need your expertise with a sockets question. > > Let me preface this by saying I don't have much experience with > sockets in general so this question may be simple. I would suggest taking a quick look at this tutorial. http://ilab.cs.byu.edu/python/ Especially this: http://ilab.cs.byu.edu/python/socket/echoserver.html From darkwind.87 at gmail.com Wed Mar 26 09:22:21 2008 From: darkwind.87 at gmail.com (Dark Wind) Date: Wed, 26 Mar 2008 06:22:21 -0700 Subject: Dimensions of Arrays, Matrices Message-ID: <8a6035a00803260622v686441ddy1d3dd942b2377e21@mail.gmail.com> Hi, Suppose we have a 3X3 matrix in Mathematica. We can get its dimensions by: Dimensions[A] = {3,3} TensorRank[A] = 2 Are there exact functions for these two in Python? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From tlesher at gmail.com Tue Mar 18 14:01:14 2008 From: tlesher at gmail.com (Tim Lesher) Date: Tue, 18 Mar 2008 11:01:14 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net><9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com><13t462h7vgqo081@corp.supernews.com><7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com><13t4k50d7pg0d63@corp.supernews.com><1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com><13t5cbcrhtfsrd2@corp.supernews.com><13t5qd3slgt9nc0@corp.supernews.com><63g9s0F26pgoeU1@mid.individual.net><13t6c8kdis2gbb5@corp.supernews.com> <13t6tha12dcdh5a@corp.supernews.com> Message-ID: On Mar 9, 2:04 am, "Ryan Ginstrom" wrote: > > On Behalf Of Grant Edwards > > I think docstrings are a great idea. What's needed is a way > > to document the signature that can't get out-of-sync with > > what the fucntion really expects. > > Like doctests? (I know, smart-ass response) > > Regards, > Ryan Ginstrom Not a smart-ass response at all--a _smart_ response. Doctests are one of the few mechanisms I've ever seen that even attempt to make this happen. -- Tim Lesher tlesher at gmail.com From poof65 at gmail.com Sat Mar 1 22:11:24 2008 From: poof65 at gmail.com (poof65) Date: Sun, 2 Mar 2008 04:11:24 +0100 Subject: Question about lambda and variable bindings In-Reply-To: <47CA160C.3000305@gmail.com> References: <47CA160C.3000305@gmail.com> Message-ID: An idea, i don't know if it will work in your case. for x in xrange(10): funcs.append(lambda p,z=x: testfunc(z+2,p)) On Sun, Mar 2, 2008 at 3:50 AM, Michael Torrie wrote: > I need to use a lambda expression to bind some extra contextual data > (should be constant after it's computed) to a call to a function. I had > originally thought I could use something like this demo (but useless) code: > > funcs=[] > > def testfunc(a,b): > print "%d, %d" % (a,b) > > for x in xrange(10): > funcs.append(lambda p: testfunc(x+2,p)) > > > Now what I'd like is to call, for example, funcs[0](4) and it should > print out "2,4". In other words I'd like the value of x+2 be encoded > into the lambda somehow, for funcs[x]. However the disassembly shows > this, which is reasonable, but not what I need: > > >>> dis.dis(funcs[0]) > 2 0 LOAD_GLOBAL 0 (testfunc) > 3 LOAD_GLOBAL 1 (x) > 6 LOAD_CONST 0 (2) > 9 BINARY_ADD > 10 LOAD_FAST 0 (p) > 13 CALL_FUNCTION 2 > 16 RETURN_VALUE > > The LOAD_GLOBAL 1 (x) line is definitely a problem. For one it refers > to a variable that won't be in scope, should this lambda be called from > some stack frame not descended from the one where I defined it. > > So how can I create a lambda expression that calculates a constant based > on an expression, rather than referring to the object itself? Can it be > done? > > Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Thu Mar 13 09:09:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 14:09:13 +0100 Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> <47D80BC4.2010307@behnel.de> Message-ID: <63snbqF26qphaU1@mid.uni-berlin.de> > Sorry, it was really late when i wrote this post. The file is an XSL > file. It defines HTML depending on what appears in the XML document. Then the content-type might be the culprit, yes. But testing so would have been faster than waiting for answers here... Diez From deets at nospam.web.de Wed Mar 19 11:27:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 16:27:50 +0100 Subject: How to get an XML DOM while offline? References: Message-ID: <64cpnvF2at1j9U1@mid.uni-berlin.de> william tanksley wrote: > I want to parse my iTunes Library xml. All was well, until I unplugged > and left for the train (where I get most of my personal projects > done). All of a sudden, I discovered that apparently the presence of a > DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing > the Internet... So suddenly I was unable to do any work. > > I don't want to modify the iTunes XML; iTunes rewrites it too often. > How can I prevent xml.dom.minidom from dying when it can't access the > Internet? > > Is there a simpler way to read the iTunes XML? (It's merely a plist, > so the format is much simpler than general XML.) Normally, this should be solved using an entity-handler that prevents the remote fetching. I presume the underlying implementation of a SAX-parser does use one, but you can't override that (at least I didn't find anything in the docs) The most pragmatic solution would be to rip the doctype out using simple string methods and/or regexes. Diez From furkankuru at gmail.com Tue Mar 25 08:34:58 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:34:58 +0200 Subject: embedded python in c++ packaging In-Reply-To: <21CFA1FC32D3214EBFA2F449FF211E310EAD2878@nypcmg1exms318.leh.lbcorp.lehman.com> References: <3a4a8f930802070839n31ac4d88t96d64a4138d23ff4@mail.gmail.com> <3a4a8f930802071505x70946723wabe84ad9ea4ae465@mail.gmail.com> <21CFA1FC32D3214EBFA2F449FF211E310EAD2878@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <3a4a8f930803250534h4c9073ej750291b6373b43c5@mail.gmail.com> Sorry for long delay, I've tried below code (Setting pythonpath environment variable) and then initialize python interpreter but the embedded python interpreter did not get the newly assigned PYTHONPATH. I ve looked at the sys.path in python code (that is run by the embedded interpreter) and it behaved according to older pythonpath. Setting environment variable seemed to be correct. Does py_initialize run in another thread so it starts before setting the environment var? // add custom plib.zip archive to pythonpath if(!::getenv("PYTHONPATH")) { ::putenv("PYTHONPATH=.;.\\plib.zip"); } else ::putenv("PYTHONPATH=%PYTHONPATH%;.\\plib.zip"); std::cout << "PYTHONPath Set to: " << ::getenv("PYTHONPATH") << std::endl << "And Again: "; system("echo %PYTHONPATH%"); Py_Initialize(); Regards, On Fri, Feb 8, 2008 at 2:08 AM, Bronner, Gregory wrote: > I've done this the rather old-fashioned way. > > Basically, what I do is: > > Step 1: > > Embed Python: > if(!::getenv("PYTHONHOME")) > { > ::putenv("PYTHONHOME="); > } > if(!::getenv("PYTHONPATH")) > { > ::putenv("PYTHONPATH=."); > } > > Py_SetProgramName("leaktester"); > Py_InitializeEx(0); > init_memoryhoginterface(); // This initializes your SWIG module > PyRun_SimpleString("print 'HELLO FROM PYTHON'"); //<--- OR you can do > something else here like run a file > > > Step 2: > Extend python to talk back to your C++ code. > I use one giant SWIG module (see init function above) > > SWIG allows you to finely control what you expose to python, so you don't > wind up exposing the whole C++ API. > > > > > > > > > > ------------------------------ > *From:* Furkan Kuru [mailto:furkankuru at gmail.com] > *Sent:* Thursday, February 07, 2008 6:06 PM > *To:* python-list at python.org > *Subject:* Re: embedded python in c++ packaging > > I do not have access to my development machine right now. > but is it enough adding just a simple line at the top of my main python > file 'sys.path.append("modules.zip")' before importing any other modules? > > On 2/7/08, Gabriel Genellina wrote: > > > > En Thu, 07 Feb 2008 16:18:57 -0200, Joshua Kugler > > escribi?: > > > Furkan Kuru wrote: > > >> > > >> I have been developing an application in C++ that embeds Python > > >> interpreter. It takes advantage of too many modules from Python. > > >> When I want to package this application, I need to add too many files > > >> (.pyc) from Python/lib folder together with Python25.dll. > > >> Is there a way to pack these .pyc files to a zip file and redirect > > >> Python25.dll to that zip file? > > > > > > That is effectively what py2exe does with the modules required by the > > > main > > > application. It takes all the required modules and puts them in a > > > library.zip file. You might take a look at how it does it. > > > > Using py2exe has an additional advantage, it recursively scans all > > modules > > looking for dependencies. > > Once you know the required set of modules, you can bundle them in a .zip > > file and add its full path into sys.path (the absolute path including > > filename and .zip extension). Python does look into the .zip searching > > for > > modules. > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Furkan Kuru > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - This message is intended only for the personal and > confidential use of the designated recipient(s) named above. If you are not > the intended recipient of this message you are hereby notified that any > review, dissemination, distribution or copying of this message is strictly > prohibited. This communication is for information purposes only and should > not be regarded as an offer to sell or as a solicitation of an offer to buy > any financial product, an official confirmation of any transaction, or as an > official statement of Lehman Brothers. Email transmission cannot be > guaranteed to be secure or error-free. Therefore, we do not represent that > this information is complete or accurate and it should not be relied upon as > such. All information is subject to change without notice. -------- IRS > Circular 230 Disclosure: Please be advised that any discussion of U.S. tax > matters contained within this communication (including any attachments) is > not intended or written to be used and cannot be used for the purpose of (i) > avoiding U.S. tax related penalties or (ii) promoting, marketing or > recommending to another party any transaction or matter addressed herein. -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From willsteve2003 at yahoo.ca Mon Mar 10 11:30:00 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:30:00 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> Message-ID: <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> On Mar 10, 10:26?am, Roel Schroeven wrote: > rockingred schreef: > > > > > > > On Mar 8, 8:27 pm, Dan Bishop wrote: > >> // ? ?Copyright (C) 2008 Foobar Computer Consulting > >> // > >> // ? ?VERSION ? PROJECT# ? ? DATE ? ? DESCRIPTION > >> // ? ?------- ? -------- ? -------- ? ------------------ > >> // ? ? ?1.00 ? ? 123456 ? ?01/04/08 ? Original creation. > >> // > > >> Eleven lines, of which the only useful information to me was the > >> project number, as knowing this let me look up who was behind these > >> comments. > > > Actually, "editorial" comments that tell you who last changed a > > program, when and why can be useful. ?I worked in a company with a > > number of programmers on staff. ?Having comments that told us Joe > > worked on a program yesterday that isn't working today could often > > solve half the battle. ?Especially if Joe also added a comment near > > the lines he had changed. ?Likewise including the "Project#" would > > help us track all the programs that had to be changed for a specific > > project. ?This allowed us to move all related items into the Live > > system once the testing phase had been completed (we just searched for > > everything with the same Project# in it). ?Yes, on rare occasions we > > would have an entire page of "Editorial" comments to ignore at the > > beginning of our program listing, but it was easy enough to skip that > > page. ?I will grant you that probably after 10 changes the first > > change isn't as important anymore (unless you want to backtrack and > > find out who started the Project in the first place and what it's > > original purpose was). > > That is certainly useful, but IMO that's what version control systems > are for. > > -- > The saddest aspect of life right now is that science gathers knowledge > faster than society gathers wisdom. > ? ?-- Isaac Asimov > > Roel Schroeven- Hide quoted text - > > - Show quoted text - Unfortunatly, in many of the companies I worked for, version control software was not implemented. In some cases, where it was, it actually inserted the comments into the header of the program as described. In others, the software was so limited as to make it useless. From bignose+hates-spam at benfinney.id.au Sun Mar 16 21:03:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Mar 2008 12:03:37 +1100 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <87zlsyyxee.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > I would like to encourage anyone who was at PyCon but has not > provided formal feedback to use the following URLs: For those who don't like to follow opaque munged URLs from services that give no indication where you'll end up, here are the actual URLs you'll arrive at: > For the conference: > http://tinyurl.com/2ara8u PyCon 2008: Conference Feedback > For the tutorials: > http://tinyurl.com/2ew2pc PyCon 2008: Tutorial Evaluation Thanks for posting these links, Aahz. -- \ "Imagine a world without hypothetical situations." ?anonymous | `\ | _o__) | Ben Finney From steve at holdenweb.com Sun Mar 2 12:45:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 12:45:50 -0500 Subject: Problem with the strip string method In-Reply-To: References: Message-ID: Colin J. Williams wrote: > The Library Reference has > strip( [chars]) > > Return a copy of the string with the > leading and trailing characters removed. > The chars argument is a string > specifying the set of characters to be > removed. If omitted or None, the chars > argument defaults to removing > whitespace. The chars argument is not a > prefix or suffix; rather, all > combinations of its values are stripped: > >>> ' spacious '.strip() > 'spacious' > >>> 'www.example.com'.strip('cmowz.') > 'example' > > Only the last two examples below behave > as expected. > Adjust your expectations. The software is correct. > Is it intended that the full range of > characters be handled? > > Colin W. > > [Dbg]>>> 'ab$%\n\rcd'.strip('%') > 'ab$%\n\rcd' > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%\n\rcd' > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%cd' > [Dbg]>>> ' ab$%cd '.strip('$') > ' ab$%cd ' > [Dbg]>>> ' ab$%cd '.strip('%') > ' ab$%cd ' > [Dbg]>>> ' spacious '.strip() > 'spacious' > [Dbg]>>> 'www.example.com'.strip('cmowz.') > 'example' I suspect what you need is the .replace() method. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jeff at schwabcenter.com Mon Mar 17 11:45:16 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 08:45:16 -0700 Subject: Missing PyObject definition In-Reply-To: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: James Whetstone wrote: > I'm trying to access a PyObject directly from C++ for the purpose of calling > method on a Python object that is an intance of a derived C++ class. My > problem is that the compiler is complaining about not PyObject not being > defined. Has anyone run into the problem? Where is PyObject defined? Are you using Python's C API? Did you #include "Python.h" before using PyObject? PyObject is a C-style struct defined in object.h, which is in turn included by Python.h. Does your compiler know where to look for those headers? If you are getting messages of the form "error: cannot find Python.h," then add -Iyour_python_root/include/python2.5 (or whatever version) to the CXXFLAGS variable in your makefile, or to your compiler's command line. From Lie.1296 at gmail.com Sun Mar 16 14:04:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 11:04:59 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> <1befdccf-2efc-4640-bcf8-b4a792d8e646@i29g2000prf.googlegroups.com> Message-ID: <5782d52d-0f8c-42b8-9ccc-7445616e5717@u10g2000prn.googlegroups.com> On Mar 11, 4:15?am, John Machin wrote: > On Mar 11, 3:19 am, cokofree... at gmail.com wrote: > > > The trick in the case of when you do not want to guess, or the choices > > grow too much, is to ask the user to tell you in what format they want > > it and format according to their wishes. > > > Neatly avoids too much guessing and isn't much extra to add. > > The plot is about understanding input, not formatting output. And what he meant is simply to make an agreement with the user on how he/she would format his/her input and to disallow input from formats that haven't been agreed to avoid guessing. That is the cleanest and most polite solution, although I'd suspect it would be considered less user friendly by regular user although power user would be most happy with that. From mensanator at aol.com Wed Mar 5 16:27:36 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Mar 2008 13:27:36 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: On Mar 5, 2:25?pm, "Jeff.Goldfin... at gmail.com" wrote: > Hi All > > Is there a simple way to twiddle the bits of a float? In particular, I > would like to round my float to the n most significant bits. > > For example - 0.123 in binary is 0.000111111 > Rounding to 4 bits I get 0.0001. > > I can pack and unpack a float into a long > e.g. > struct.unpack('I',struct.pack('f',0.123))[0] > but then I'm not sure how to work with the resulting long. > > Any suggestions? Here's one. >>> import gmpy # create a base 10 float >>> f = gmpy.mpf('123.456') >>> f mpf('1.23456e2') # format in base 2, fixed point >>> f2 = gmpy.fdigits(f,2,0,0,99) >>> f2 '1111011.01110100101111000110101001111110111110011101101100100010111' # seperate the characteristic from the mantissa >>> fs = f2.split('.') # re-assemble with the mantissa truncated to desired # of bits >>> f3 = fs[0]+'.'+fs[1][:4] >>> f3 '1111011.0111' # convert the string back to a base 10 float >>> f4 = gmpy.mpf(f3,0,2) >>> print f4 123.4375 # check: print as base 2 and see how many digits are past radix point >>> print gmpy.fdigits(f4,2,0,0,99) 1111011.0111 From bj_666 at gmx.net Sat Mar 15 02:01:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 06:01:52 GMT Subject: List mutation method gotcha - How well known? References: <210b2a22-a8e3-414e-9018-15f7d74c9f83@d4g2000prg.googlegroups.com> Message-ID: <64172eF29qj9jU1@mid.uni-berlin.de> On Fri, 14 Mar 2008 11:32:41 -0700, Lie wrote: > No, there is no need for "void" return type, what I meant is that > everything that's not said in the documentation should be assumed to > be an implementation detail, a method or a function that doesn't say > anything about its return type should be assumed to return an > implementation detail (which basically means: Don't rely on this). The > fact that list.append returns none is just a coincidence, you might > encounter another list.append that returns different thing some time > in the future, or the far future, or perhaps at the end of the > galaxy's life. I expect functions with no documentation of what they return to return `None`. Assuming they are documented at all, of course. :-) It's like not writing a ``return`` statement in the code: there's always an implicit ``return None`` at the end of every function. Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Sun Mar 9 17:12:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:12:28 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6d3lppl8lv2a@corp.supernews.com> Message-ID: On Mar 8, 7:51?pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 13:40:56 -0800, dave_mikesell wrote: > > On Mar 8, 2:27 pm, castiro... at gmail.com wrote: > > >> Good comments are better than bad names. Good names are better than bad > >> comments. > > > If you're taking the time to write good comments, why not just fix the > > bad names? ?The compiler/interpreter can never, ever catch bad comments. > > Yes, but the Python compiler can only catch bad names if you do this at > the top of every module: > > import semantic_analysis > import magic.crystal_ball.read_programmers_mind dir( magic )! dir( magic.crystal_ball )? From michael.wieher at gmail.com Wed Mar 5 11:11:44 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 5 Mar 2008 10:11:44 -0600 Subject: ActiveX in Webpage? Message-ID: Hello, I'm trying to design a python-based web-app from scratch, based on a standalone MFC application. Obviously I'll be wrapping a lot of C++ functionality in custom extensions, but is anyone aware of any documentation/techniques that could help me "drop" an ActiveX control into a webpage, and just use it? That, or, of course, a solid bit of writing detailing the idiosyncrasies of MFC-wrapped Py-Extensions would be useful as well. -Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffrey at fro.man Wed Mar 26 11:05:31 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 26 Mar 2008 08:05:31 -0700 Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> Message-ID: <13ukphrj8hng018@corp.supernews.com> skunkwerk wrote: > p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ > model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > print p.communicate()[0] > > i change to print p.communicate()[1] in case the output is blank the > first time > > this is the output: > *.htm renamed as model.html Without shell=True, your glob characters will not be expanded. Hence, the command looks for a file actually named "*.htm" > when I add shell=True to the subprocess command, I get the following > output: > Usage: rename [-v] [-n] [-f] perlexpr [filenames] Here the use of the shell may be confounding the arguments passed. Your command will probably work better if you avoid using shell=True. However, you will need to perform your own globbing: # Untested (no perl-rename here): command = ['rename','-vn', 's/(.*)\.htm$/model.html/'] files = glob.glob('*.htm') command.extend(files) p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) Jeffrey From aisaac at american.edu Sun Mar 2 13:06:32 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 02 Mar 2008 18:06:32 GMT Subject: tuples, index method, Python's design Message-ID: On April 12th, 2007 at 10:05 PM Alan Isaac wrote: > The avoidance of tuples, so carefully defended in other > terms, is often rooted (I claim) in habits formed from > need for list methods like ``index`` and ``count``. > Indeed, I predict that Python tuples will eventually have > these methods and that these same people will then defend > *that* status quo. - Issue #2025 : Add tuple.count() and tuple.index() methods to comply with the collections.Sequence API. Cheers, Alan Isaac From paul.hankin at gmail.com Sat Mar 8 18:55:29 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 8 Mar 2008 15:55:29 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <876ecbb3-5bfe-40bd-a1ff-102af8d19fbc@n77g2000hse.googlegroups.com> Message-ID: On Mar 8, 10:42?pm, Carl Banks wrote: > On Mar 8, 9:43 am, malkarouri wrote: > > > Hi everyone, > > > I have an algorithm in which I need to use a loop over a queue on > > which I push values within the loop, sort of: > > > while not(q.empty()): > > ? ? x = q.get() > > ? ? #process x to get zero or more y's > > ? ? #for each y: > > ? ? q.put(y) > > Why not just do it like that? ?With a few changes it'll work fine: > > while q: > ? ? x = q.pop(0) > ? ? for y in process(x): > ? ? ? ? q.append(y) Or (almost) equivalently... while q: x = q.pop(0) q.extend(process(x)) -- Paul Hankin From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 03:35:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 07:35:58 -0000 Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <13umjiu5aa8585d@corp.supernews.com> On Wed, 26 Mar 2008 19:45:34 +0100, Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 19:04:44 schrieb David Anderson: >> HOw can we use express pointers as in C or python? > > There's no such thing as a pointer in Python, so you can't "express" > them either. Was this what you were trying to ask? But if you really need then, you can fake them: memory = [None]*10 # get a "pointer" to a memory location ptr = 5 # and assign a function there memory[ptr] = lambda s: '$' + s + '$' assert memory[ptr]('hello') == '$hello$' # store a pointer to a pointer memory[3] = ptr assert memory[memory[3]]('bye') == '$bye$' In Python this is a silly trick, not worth doing because there are better ways to solve problems that other languages use pointers for. But in older languages like Fortran, before they gained pointers, this was a standard method for getting pointers into a language without pointers. Thank goodness those days are long-gone! -- Steven From gigs at hi.t-com.hr Mon Mar 31 18:03:54 2008 From: gigs at hi.t-com.hr (gigs) Date: Tue, 01 Apr 2008 00:03:54 +0200 Subject: Question about overloading of binary operators In-Reply-To: References: Message-ID: Raj Bandyopadhyay wrote: > Hi > > Here's a simple class example I've defined > > ############################# > class myInt(int): > def __add__(self,other): > return 0 > > print 5 + myInt(4) #prints 9 > print myInt(4) + 5 #prints 0 > ############################# > > The Python binary operation function (binary_op1() in > Objects/abstract.c) states > the rules for binary operations as follows: > > v w Action > ------------------------------------------------------------------- > new new w.op(v,w)[*], v.op(v,w), w.op(v,w) > new old v.op(v,w), coerce(v,w), v.op(v,w) > old new w.op(v,w), coerce(v,w), v.op(v,w) > old old coerce(v,w), v.op(v,w) > > [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of > v->ob_type > > > It seems that my example should fall in case 1, and in both cases, the > __add__ function of the subclass should be used, returning 0, regardless > of operand order. However, in one case the subclass's function is used > and not in the other case. What am I missing here? > > Thanks > Raj > i think that you need to use __radd__ for addition with custom object on right From mensanator at aol.com Mon Mar 10 14:10:48 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 10 Mar 2008 11:10:48 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> On Mar 10, 12:48?am, Gabriel Genellina wrote: > On 10 mar, 02:08, Nathan Pinno wrote: > > > How do I factor a number? If factoring is actually what you want, the sympy module can do it. >>> n = 85085**3 >>> print n 615969217989125 >>> import sympy >>> f = sympy.factorint(n) >>> f [(5, 3), (7, 3), (11, 3), (13, 3), (17, 3)] >>> ff = [[i[0]]*i[1] for i in f] >>> ff [[5, 5, 5], [7, 7, 7], [11, 11, 11], [13, 13, 13], [17, 17, 17]] >>> fff = sympy.flatten(ff) >>> fff [5, 5, 5, 7, 7, 7, 11, 11, 11, 13, 13, 13, 17, 17, 17] Provided that your needs are modest. It claims to be able to handle 10 digit factors, but it certainly can't handle numbers of this magnitude: 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 As it takes a couple hours of run-time only to crash with an out of memory error. If you need to handle something like that, you may want to get factor.exe which is part of the MIRACL library. The library is in C and doesn't have a Python interface, but you can run the .exe from Python and capture the output. Keep in mind two things: factor.exe doesn't have consistent output making it more difficult to interpret the captured output. I re-compiled my copy of factor.exe to provide consistent output. The other thing is that factor.exe sometimes gets confused claiming a number is composite that factor.exe is fully capable of factoring. Luckily this can be easily fixed in the Python program that calls it. In the following example, if factor!.exe (my re-compiled version) returns any composites, I simply feed them back into the program until all are factored or determinened to be truly intractable. Note the times. If you have serious factoring needs, the MIRACL solution is better than sympy. ## ======================================== ## Phase 1 ## ['COMPOSITE_FACTOR', '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] ## ## ['PRIME_FACTOR', '37'] ## ['PRIME_FACTOR', '43'] ## ['PRIME_FACTOR', '167'] ## ['COMPOSITE_FACTOR', '507787751'] ## ['PRIME_FACTOR', '69847'] ## ['PRIME_FACTOR', '30697'] ## ['PRIME_FACTOR', '89017'] ## ['PRIME_FACTOR', '3478697'] ## ['PRIME_FACTOR', '434593'] ## ['PRIME_FACTOR', '49998841'] ## ['PRIME_FACTOR', '161610704597143'] ## ['PRIME_FACTOR', '14064370273'] ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ['PRIME_FACTOR', '11927295803'] ## ## 0.860000133514 seconds ## ======================================== ## Phase 2 ## ['COMPOSITE_FACTOR', '507787751'] ## ## ['PRIME_FACTOR', '29819'] ## ['PRIME_FACTOR', '17029'] ## ## 0.0780000686646 seconds ## ======================================== ## Phase 3 ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ## ['PRIME_FACTOR', '518069464441'] ## ['PRIME_FACTOR', '1858900129817'] ## ## 0.0469999313354 seconds ## ======================================== ## ## Factoring complete ## ## PRIME_FACTOR 37 ## PRIME_FACTOR 43 ## PRIME_FACTOR 167 ## PRIME_FACTOR 17029 ## PRIME_FACTOR 29819 ## PRIME_FACTOR 30697 ## PRIME_FACTOR 69847 ## PRIME_FACTOR 89017 ## PRIME_FACTOR 434593 ## PRIME_FACTOR 3478697 ## PRIME_FACTOR 49998841 ## PRIME_FACTOR 11927295803 ## PRIME_FACTOR 14064370273 ## PRIME_FACTOR 518069464441 ## PRIME_FACTOR 1858900129817 ## PRIME_FACTOR 161610704597143 ## ## ======================================== > I mean how do I translate x! into proper > > Python code, so that it will always do the correct math? > > Do you want to compute x! (factorial of x)? That is, you want a > program that given a 4, returns 24? > Think how would you compute it by hand and try to write the same thing > using Python instructions. > > If you come with a program and have a specific problem someone here > will be able to help you, but don't expect your homework to be done > for free... > > -- > Gabriel Genellina From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 11:19:07 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 17:19:07 +0100 Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> Message-ID: <20080302171907.ffa19838.randhol+valid_for_reply_from_news@pvv.org> On Sun, 2 Mar 2008 08:09:24 -0800 (PST) castironpi at gmail.com wrote: > On Mar 2, 8:15?am, Giles Brown wrote: > > http://docs.python.org/lib/typeiter.html > > Be careful on your descision to return an ordered iterator or not-- > that is, whether it iterates over the dictionary or the list (if I > understand you correctly). If the order's unimportant then please > disregard. I was thinking to iterate over the list which contains the uniq_ids as order is important :-) Thanks! Preben From ptmcg at austin.rr.com Wed Mar 5 16:12:43 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 5 Mar 2008 13:12:43 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> Message-ID: <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> On Mar 5, 2:04?pm, castiro... at gmail.com wrote: > On Mar 5, 1:29?pm, Paul McGuire wrote: > > > On Mar 5, 12:50?pm, castiro... at gmail.com wrote: > > > > What is a class that is not a module? > > > Please stop posting these one-liner beginner questions. ?If you can > > type it in one line, you can enter it on the Google.com or Ask.com > > query page and get a wealth of *existing* information, from tutorials, > > documentation, online presentations. ?If you are able to phrase such a > > question, you are capable of doing a little research and > > experimentation on your own. > > > These posts translate to "I'm too lazy to use Google, or too cheap to > > buy a Python book, or too lazy to read it, or too impatient to do my > > own experimenting - much better to just post on c.l.py and have the > > answer spoon-fed to me!" > > > I refuse to spoon feed you the answer to this question when plenty of > > supporting material is already available. > > In the future, shall I assume that other readers here have no ideas > (on this, read *ever*), that haven't already been published? ?'Cause I > have. > > For instance, in this example, I've tried a few approaches that didn't > turn out well. > Fair game. Capture one of these classes (or better, distill it down to a *small* example demonstrating the problem), tell us what you are trying to achieve, post it, AND tell us what is "not turning out well." (Your previous posts have done a poor job in providing one or more of these elements.) > Do you want a comparison of existing solutions? ?Do you have a proof > that they exhaust the solution space? > *I* don't want *any* such thing, especially on the topics of "what is a class?" and "how is a class different from a module?", nor do I need proof that the basic background info on this topic covers the mainstream applications of classes and modules. These are basic OO concepts in Python. Try googling "python object-oriented". And if there were some esoteric aspect of "what is a class?" that you want to pursue that might not be covered in the available material, I would expect one to include that in the original post. > I'm willing to address convention, in serial or parallel--- (change > subject to 'what goes on newsgroups'?), but it's not clear from fact > what assumption who has made. > Since you did not elaborate on what your efforts were and the extent they were undesirable (certainly useful info from someone honestly interested in a helpful answer), I assumed you had made none. > Next time, why don't you say, "How much experience do you have?", or > "What level should I gear my answer toward?" > I put the onus on the poster to realize that the question they are asking is in fact a basic concept, *especially* when the subject of the question is captured in a built-in method, type, class, or keyword. Surely you are aware that Python has been around for a number of years, and that in all that time, it is entirely likely that the topic of "what is a class?" has been covered, in any number of the tutorials and docs so charitably written by many of the contributors in this newsgroup. Please stop asking those people to further expend their time repeating this work just for your benefit. It is like arriving late to a meeting, and asking everyone to stop and bring you up to speed on what you missed, in effect saying, "My time is more valuable than yours, I can't be bothered to arrive on time, or do even the simplest research for myself." -- Paul From pedro.santa at gmail.com Thu Mar 20 13:47:56 2008 From: pedro.santa at gmail.com (Pedro Machado Santa) Date: Thu, 20 Mar 2008 10:47:56 -0700 (PDT) Subject: Import a file to namespace References: <0cdb3c90-e961-4982-9996-de3ac02706bc@13g2000hsb.googlegroups.com> <13u57f51c3ee82e@corp.supernews.com> Message-ID: <45b0b2fc-daa8-49b9-8f80-4eac40f6c35f@q78g2000hsh.googlegroups.com> On Mar 20, 5:24 pm, Jeffrey Froman wrote: > This method should work fine. Modules are effectively singletons, so running > this code one time anywhere in your application will cause the changes to > appear in all references to the original module. Yhea. I got it now. :) It already works. I wasn't putting the module on my working dir. (I created the module testpackageaddon.py and I did the "override" on it, then imported it after the import testpackage on my working script.) Thanks. Pedro Machado Santa From fetchinson at googlemail.com Mon Mar 10 21:06:14 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 18:06:14 -0700 Subject: image matching algorithms In-Reply-To: <47D5D64A.8030300@ncee.net> References: <47D5D64A.8030300@ncee.net> Message-ID: > >>> There are a number of free tools for image matching but it's not very > >>> easy to decipher the actual algorithm from the code that includes db > >>> management, GUI, etc, etc. I have my own image database and GUI so all > >>> I need is the actual algorithm preferably in pseudo code and not in > >>> the form of a research paper (from which I also found a lot but since > >>> I'm not that much interested in the actual science of image > >>> recognition this seems like an over kill). > >>> > >> I'd recommend SIFT. There's quite a bit of information on SIFT. In most > >> cases, they don't cover the background science too much, but are still > >> heavy on the math. Pseudo code is hard to come by since it will take > >> many lines of pseudo code just to express one concise mathematical > >> equation. There are however many links to implementations in various > >> languages on the Wikipedia page. > >> > >> http://en.wikipedia.org/wiki/Scale-invariant_feature_transform > >> > >> I have had good experiences with SIFT for feature extraction from images > >> (I have used it for panorama stitching and robot mapping). It's > >> insensitive to scale and rotation. Note that it is a patented algorithm > >> and this may (or may not) pose a problem for you. > >> > > > > Thanks for the info! SIFT really looks like a heavy weight solution, > > but do you think the whole concept can be simplified if all I needed > > was: given a photo, find similar ones? I mean SIFT first detects > > objects on the image and find similarities, but I don't need the > > detection part at all, all I care about is similarity for the whole > > photo. I surely don't understand the big picture fully but just have > > the general feeling that SIFT and other expert tools are an overkill > > for me and a simplified version would be just as good with a much more > > easily comprehensible core algorithm. > > > > Or am I being too optimistic and there is no way out of going into the > details? > > > > > Using the histogram of the picture may be good enough for your > application. Here's something I put together for comparing images (for > purposes of detecting motion) taken by the built-in web cam in my > Macbook Pro. This might be good enough if you play with the threshold. > > > """ > I'm writing a simple little app for doing motion detection with data > output from wacaw, a package for MacOSX. You could easily modify this > script to get data output from some other source. Thanks Shane, this is simple enough indeed, which is great. I'll give this a try and maybe it'll be good enough for me. From grante at visi.com Wed Mar 5 15:48:53 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 20:48:53 -0000 Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <13su15t266dimc2@corp.supernews.com> Message-ID: <13su1pl8tnq5o6a@corp.supernews.com> On 2008-03-05, Grant Edwards wrote: > On 2008-03-05, Jeff.Goldfinkle at gmail.com wrote: >> Any suggestions? > > Just use the bitwise and/or/not operators: & | ~ Oh, I forgot to mention the shift operators << and >> -- Grant Edwards grante Yow! All of life is a blur at of Republicans and meat! visi.com From gherron at islandtraining.com Thu Mar 27 18:27:57 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Mar 2008 15:27:57 -0700 Subject: Problems wit List Object In-Reply-To: <5dc598e30803271519k39440eccj3b9db110f9097b98@mail.gmail.com> References: <5dc598e30803271519k39440eccj3b9db110f9097b98@mail.gmail.com> Message-ID: <47EC1F6D.7090908@islandtraining.com> David Anderson wrote: > Hello all, I have a Class1 that there has a list, and a function that > returns this list, In another class I got an instance of this first > class, and when I make: > > obj1 = Class1() > list = obj1.getList() > > I got this exception: > > traceback (most recent call last): > File "xxx", line 184, in onAddErro > list = self.errorMgr.getList() > TypeError: 'list' object is not callable > > How can I solve it? This error implies that getList is a list, *not* a function which returns a list. If that's not enough explanation for you, you'll have to provide some code for us to look at. Gary Herron From skip at pobox.com Thu Mar 27 11:10:17 2008 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Mar 2008 15:10:17 +0000 (UTC) Subject: Is subprocess.Popen completely broken? References: Message-ID: > > >>> proc = subprocess.Popen ("ls /tmp") > > proc = subprocess.Popen ("ls /tmp", shell=True) > > or > > proc = subprocess.Popen (["ls", "/tmp"]) > > should work. Why should I need to set shell=True? I'm not globbing anything. The second case still fails: >>> proc = subprocess.Popen (["/usr/bin/ls" "/tmp"]) Traceback (most recent call last): File "", line 1, in ? File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 542, in __init__ errread, errwrite) File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 975, in _execute_child raise child_exception OSError: [Errno 20] Not a directory Thx, Skip From web1986 at gmail.com Sat Mar 15 16:25:28 2008 From: web1986 at gmail.com (4ever) Date: Sat, 15 Mar 2008 13:25:28 -0700 (PDT) Subject: .:Www.4Down.Info:. for all your needs Message-ID: .:Www.4Down.Info:. for all your needs http://4down.info/ Free CMS,Templates,Movies,Scripts,SEo tools,Adsense Tools,Applications,MP3..and much more http://4down.info/ Free cPanel Web Hosting with PHP5/Mysql - no advertising! http://4down.info/news/1207-free-cpanel-web-hosting-with-php5mysql.html Hidden Expedition: Everest http://4down.info/games/1270-hidden-expedition-everest.html Eminem - TBA (2008) http://4down.info/music/1269-eminem-tba-2008.html Eminem- Psycho Killer DVD (2008) http://4down.info/music/1267-eminem-psycho-killer-dvd-2008.html Stargate - The Art Of The Truth (2008) http://4down.info/movies/1261-stargate-the-art-of-the-truth-2008.html Adobe Photoshop CS4 http://4down.info/applications/1258-adobe-photoshop-cs4.html Robin Hood: The Legend of Sherwood (ISO) http://4down.info/games/1253-robin-hood-the-legend-of-sherwood-iso.html Jumper (2008) http://4down.info/movies/1252-jumper-2008.html From terry at jon.es Fri Mar 28 10:54:36 2008 From: terry at jon.es (Terry Jones) Date: Fri, 28 Mar 2008 15:54:36 +0100 Subject: Global variables in modules... In-Reply-To: Your message at 15:13:15 on Friday, 28 March 2008 References: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> Message-ID: <18413.1708.63299.691860@jon.es> >>>>> "Peter" == Peter Otten <__peter__ at web.de> writes: Peter> ttsiodras at gmail.com wrote: [snip] >> ...can someone explain why invoking a.py prints 0? >> I would have thought that the global variable 'g' of module 'a' would >> be set to 1... Peter> When you run a.py as a script it is put into the sys.modules module Peter> cache under the key "__main__" instead of "a". Thus, when you import Peter> a the cache lookup fails and a.py is executed again. You end up with Peter> two distinct copies of the script and its globals [snip] Suggesting the following horribleness in a.py g = 0 def main(): global g import b g = 1 b.callb() if __name__ == "__main__": import sys, __main__ sys.modules['a'] = __main__ main() Terry From bruno.desthuilliers at gmail.com Mon Mar 31 15:36:13 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 31 Mar 2008 12:36:13 -0700 (PDT) Subject: Looking for indent advice howto in emacs python-mode References: Message-ID: <440c7af6-deaf-4180-afa8-91d9a3f359f3@e10g2000prf.googlegroups.com> On 31 mar, 18:32, "Steven W. Orr" wrote: > Here's what I want to do: > > if ( ( v == 1 ) > or ( v == 2 ) > or ( v == 3 ) ): > pass Why the parens ? if a == 1 \ or b == 2 \ or c == 3: pass From Robert.Bossy at jouy.inra.fr Tue Mar 4 12:36:02 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 04 Mar 2008 18:36:02 +0100 Subject: why not bisect options? In-Reply-To: References: Message-ID: <47CD8882.3020009@jouy.inra.fr> Aaron Watters wrote: > On Feb 29, 9:31 am, Robert Bossy wrote: > >> Hi all, >> >> I thought it would be useful if insort and consorts* could accept the >> same options than list.sort, especially key and cmp..... >> > > Wouldn't this make them slower and less space efficient? It would > be fine to add something like this as an additional elaboration, but > I want bisect to scream as fast as possible in the default streamlined > usage. Yes it is slower and bigger, so I agree that the canonical implementation for default values should be kept. Also because the original bisect functions are actually written in C, the speed difference is even more noticeable. Though, I needed custom ordering bisects since I was implementing interval trees (storing intervals by startpoint/endpoint). Cheers, RB From micah at cowan.name Sat Mar 8 20:27:16 2008 From: micah at cowan.name (Micah Cowan) Date: Sun, 09 Mar 2008 01:27:16 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> Message-ID: <87zlt8d6vj.fsf@micah.cowan.name> dave_mikesell at fastmail.fm writes: > On Mar 8, 2:38 am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote: >> >> x = get_stuff(store) # Get the stuff what was brought at the store. >> >> > Perfect example of an unnecessary comment. The variable and function >> > names are commentary enough. >> >> "x" is a terrible name. What does it mean? Nothing. > > Right, that's a problem with the code. A comment only masks the bad > smell. 'x' should be renamed to something meaningful, obviating the > need for comments to follow it around. > >> There's only three places x is an appropriate name: > >> (1) A meta-syntactic variable like foo, bar, spam, ham, parrot. >> >> (2) Library functions, where x stands for a generic argument, usually a >> number, e.g. def sin(x). >> >> (3) Throw-away code you don't need to maintain. > > I use single letter variables where their scope is very small. e.g., > tight loops, small functions, etc. I even use them as class members > where they make sense in the domain. x, y, z for 3d vectors, r, g, b, > a for colors, etc. This was a two-line code sample. Since you've indicated you use such names where their scope is small, it's rather hard to say, without more information, whether using "x" for this code generats a "smell" or not. For that small amount of code, I'd say it doesn't. I find that long names in short code segments actually detract from readability. In the very first section of their book "The Practice of Programming", Kernighan and Pike recommend using "descriptive names for globals, short names for locals," saying "within a function, may be sufficient, is fine, and is overkill." As you point out, even for non-super-small scopes, such as class members, it can make more sense to use single-letter names; I'd consider red, green, blue and alpha to be unnecessary names, and it's hard to improve on the x, y and z you gave as an example. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From catelkak at gmail.com Tue Mar 11 06:55:00 2008 From: catelkak at gmail.com (online money) Date: Tue, 11 Mar 2008 03:55:00 -0700 (PDT) Subject: how to increase the system speed....to improve the proceesssor speed..... Message-ID: <7fbbdbf9-b0e5-4507-9d43-b4f4fd43f7e0@s13g2000prd.googlegroups.com> how to increase the system speed....to improve the proceesssor speed..... http://intelspentium.googlepages.com From python.list at tim.thechases.com Fri Mar 7 16:04:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Mar 2008 15:04:51 -0600 Subject: I cannot evaluate this statement... In-Reply-To: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <47D1ADF3.6080607@tim.thechases.com> > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe [snip] > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. [snip] > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? Your reasoning is correct. I'm guessing you're typing something wrong? Or typing the right thing in the wrong window (so that the command is run on a Windows box)? Or perhaps you're running on some weird build of Python? It does indeed work on my Debian box: tim at rubbish:~$ uname -a Linux rubbish 2.6.22-2-686 #1 SMP Fri Aug 31 00:24:01 UTC 2007 i686 GNU/Linux tim at rubbish:~$ python Python 2.4.4 (#2, Jan 3 2008, 13:36:28) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.platform 'linux2' >>> sys.platform[:3]=="win" and "python.exe" or "python" 'python' >>> (sys.platform[:3]=="win" and "python.exe") or "python" 'python' Whereas on my Windows machine: c:\> python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.platform 'win32' >>> sys.platform[:3] == "win" and "python.exe" or "python" 'python.exe' That's both with and without the parens. Same happens in assignments. -tkc From menosaint at gmail.com Thu Mar 13 18:33:04 2008 From: menosaint at gmail.com (menosaint at gmail.com) Date: Thu, 13 Mar 2008 15:33:04 -0700 (PDT) Subject: newbie question structure of function Message-ID: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> hi I am new to python programming..I would like to call a function that returns an integer value and a filename string as a tuple.I coded it like this below...I want to know if this can be coded more compactly and efficiently..(i am from java background and thus code often becomes bulky ..) def mycallerfunction(): matchvalue,matchfilename=findmatchingfile() if not matchfilename: print "no match found" dosomething() else: print "match found:",matchfilename,"with matching distance:",matchvalue dosomethingelse() def findmatchingfile(): # calculate matchdistance and matchfilename and return as tuple # if matchdistance found is not within a threshold then filename # may be "" (an empty string) ... ... resultname=""" matchdistance,index=dosomecalculations() if (matchdistance < threshold): resultname=filenameslist[index] return (matchdistance,resultname) if you can give some advice/suggestions it wd be great thankx -vincent From castironpi at gmail.com Fri Mar 28 14:49:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 11:49:59 -0700 (PDT) Subject: Dynamic code problem References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> <8c7f10c60803280314q320884e8k9993592d688fec83@mail.gmail.com> Message-ID: On Mar 28, 8:41?am, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 07:14:17 -0300, Simon Brunning ? > escribi?: > > > On Thu, Mar 27, 2008 at 4:13 PM, ? wrote: > >> My dynamic code failed at this site http://****/, need > >> ?some help thank you. > > > > > I assumed it was just spam, not a question. To be or not to be, not a question? From kaantuna at gmail.com Mon Mar 17 09:30:11 2008 From: kaantuna at gmail.com (Kaan Tuna) Date: Mon, 17 Mar 2008 15:30:11 +0200 Subject: Entry point not found error Message-ID: <9a7827a80803170630g492ff102m162f362bf81a538c@mail.gmail.com> Hi, I am using cygwin on a Windows Xp machine. I used to have python2.3 working without problems, but when i install v2.5.1 via cygwin setup, python.exe and python2.5.exe are giving "Entry point not found - Exception processing message - Parameters 18ef...." error box, while python2.3.exe still runs normally. My librairies are in cygwin/lib folder. Do you have any idea to solve this problem? Thanks in advance. Kaan -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Thu Mar 6 21:25:15 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 6 Mar 2008 18:25:15 -0800 (PST) Subject: Flash interface for a python program References: Message-ID: On 7 Mrz., 01:46, icarus wrote: > Is it possible to call an external python program, through a Flash > interface? > > Meaning, I create a Flash window with a button. When I press that > button, it automagically invokes the external python program. Is that > possible? Any books/online tutorials you can recommend > me? > > I guess I'm looking for alternatives in the area of GUI development. You might look at PyAMF for data-bindings. http://pyamf.org/ An alternative is mentioned in the Flex/Python articles by Bruce Eckel. http://www.artima.com/weblogs/viewpost.jsp?thread=208528 From dickinsm at gmail.com Fri Mar 14 12:08:36 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 14 Mar 2008 09:08:36 -0700 (PDT) Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> Message-ID: <12cbbfc3-bd19-4895-b47a-2432ddc9a803@c33g2000hsd.googlegroups.com> On Mar 11, 11:35?am, Grant Edwards wrote: > Reading through the doc athttp://docs.python.org/lib/module-urllib.html, > there are several paragraphs (including code examples) showing > how you specify what proxies to use when calling urlopen(): See http://bugs.python.org/issue2288 From jeff at schwabcenter.com Sun Mar 2 18:21:31 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 15:21:31 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <7xzltgrbyi.fsf@ruckus.brouhaha.com> References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <7xzltgrbyi.fsf@ruckus.brouhaha.com> Message-ID: <5MSdnajOndDRq1banZ2dnUVZ_oSunZ2d@comcast.com> Paul Rubin wrote: > Jeff Schwab writes: >> Better yet, how hard would it be to define an otherwise int-like type >> that did not define a non-flooring division operator? Are there any >> real use cases for such a type? > > User defined types in python are fairly heavyweight compared with the > built-in types, Yet they continue to form the basis of almost all non-trivial Python programs. Anyway, it's a bit soon to be optimizing. :) > and a type like that is just another thing for the > user to have to remember. How so? A well-written function generally shouldn't depending on the exact types of its arguments, anyway. If someone has written a function to find (e.g.) the median of a collection of numbers, their code should already be prepared to accept values of user-defined numeric types. If I want to call such a function with my hand-rolled DivisionSafeInteger type, it should just work, unless specifically documented to work only with a particular subset of Python data types. > The C library has a bunch of different types like off_t (offset in a off_t is vendor-specific extension, not part of the standard C library. In gcc, it's a typedef for __off_t, which is a macro for _G_off_t, which is in turn a macro for a compiler-specific type called _IO_off_t. Elsewhere, it may just be a typedef of long int. > file) and size_t, so if you pass an off_t to a function that expects a > size_t as that arg, the compiler notices the error. On what compiler? I've never seen a C compiler that would mind any kind of calculation involving two native, unsigned types. $ cat main.c #include int main() { off_t ot = 0; long li = 3L; ot = li; } $ make cc -ansi -pedantic -Wall -std=c99 main.c -o main $ > But they are > really just integers and they compile with no runtime overhead. They do indeed have run-time overhead, as opposed to (e.g.) meta-types whose operations are performed at compile-time. If you mean they have less overhead than types whose operations perform run-time checks, then yes, of course that's true. You specifically stated (then snipped) that you "would be happier if int/int always threw an error." The beauty of a language with such extensive support for user-defined types that can be used like built-in type is that you are free to define types that meet your needs. The weight of such hand-rolled solutions may lead to performance problems at first, but C-linkable extensions go a long way to help; hence numpy et al. > So, I think Python won't easily support lots of different types of > integers, and we've got what we've got. My understanding is that Python will easily support lots of different types of just about anything. That's the point. In theory at least, it supports programming in a way that lets the translator (compiler + interpreter) keep track of the exact types being used, so that the programmer doesn't have to. The fact that the tracking is done dynamically, rather than statically, is a fundamental design decision that was made early in the language's development. > There's an interesting talk linked from LTU about future languages: > > http://lambda-the-ultimate.org/node/1277 Thanks, but that just seems to have links to the slides. Is there a written article, or a video of Mr. Sweeney's talk? From gagsl-py2 at yahoo.com.ar Tue Mar 25 20:33:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 21:33:52 -0300 Subject: embedded python pythonpath References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> Message-ID: En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru escribi?: > Actually, I do not want any .py or .pyc files around my executable. > (including userdict, sys, site etc) > I want to have just single zip file for all python files. Putting all of them into pythonNN.zip (NN depending on the Python version in use) should be enough, but I've never tried it. > I had a look at py2exe source codes but could not figure out how it just > looks into a zip file. Standard Python already supports having zip files in sys.path (using the builtin zipimport module), you don't have to do anything special to enable that (apart from building with the required dependencies, like zlib, of course) > So maybe I have to compile the svn version of python. After renaming the directory where Python 2.5 were installed, my test25.exe program (the one compiled using Python 2.5.1) worked fine. So it looks like it is something with how the "python home" is searched. Anyway, as I said earlier, you don't have to play with PYTHONPATH; just add any required directory to sys.path at runtime. -- Gabriel Genellina From afandimscit at gmail.com Fri Mar 28 17:05:29 2008 From: afandimscit at gmail.com (afandi) Date: Fri, 28 Mar 2008 14:05:29 -0700 (PDT) Subject: How to insert multiple rows in SQLite Dbase Message-ID: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> Hi, Generally, it involves SQL statement such as follow INSERT INTO (field1,field2,.......fieldn) VALUES ('abc','def'...........) If I have data taken from Apache Server Log,let say 100 lines which is printed output of 8 fields such as: data 1 IP: 61.5.65.101 Date: 26/Sep/2007 Time: 20:43:25 GMT: +0900 Requestt: GET /index.php?option=com_content&task=view&id=55&Itemid=19 HTTP/1.1 ErrorCode: 200 Bytes: 6458 Referel:http://www.joomla.org/index.php? option=com_content&task=view&id=35&Itemid=19 Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 data 2 IP: 21.5.65.101 Date: 26/Sep/2007 Time: 20:43:25 GMT: +0900 Requestt: GET /index.php?option=com_content&task=view&id=55&Itemid=19 HTTP/1.1 ErrorCode: 200 Bytes: 6458 Referel:http://www.joomla.org/index.php? option=com_content&task=view&id=35&Itemid=19 Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 . . . . until the 100 data How toI insert into SQLite database? by using SQL statement.TQ From piet at cs.uu.nl Tue Mar 11 06:31:27 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 11 Mar 2008 11:31:27 +0100 Subject: execute python script question References: <47D575E9.8040507@mydeskfriend.com> Message-ID: >>>>> Gabriel Rossetti (GR) wrote: >GR> not a stupid question, I think that may be it. I tried setting PYTHONPATH >GR> like Sam suggested and it worked, but I was unable to do it programmically. >GR> I tried putting it in the __init__.py file like a web post suggested but it >GR> wasn't run until after I set PYTHONPATH, and once that was done there is no >GR> need (that I can see anyways) to set it in __init__.py. The __init__.py is executed during your import statement, thus it is too late to find MyPackage. You will have to change the sys.path before the import, e.g. in your main program. Or do what is usually done: put MyPackage in the site-packages directory. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From stef.mientki at gmail.com Fri Mar 28 17:48:05 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 22:48:05 +0100 Subject: Class or dictionary ? (was: class or inherited list ?) In-Reply-To: <47ED0BA1.9020103@gmail.com> References: <47ED0BA1.9020103@gmail.com> Message-ID: <47ED6795.9090308@gmail.com> Sorry, although the code example was correct, the question was wrong. Stef Mientki Stef Mientki wrote: > hello, > > Passing all kinds of data between objects, > I'm looking for an elegant (and simple) way to pack the data. > Now it looks to me that both the class and the inherited list, > performs equally well. > Till now, the most elegant way (in my view) is the list inheritance, > mainly because you don't need brackets and no quotes. > What are others opinion about this ? > > thanks, > Stef Mientki > > class super_list(list): > pass > > def kwadraat ( value ) : > return value * value > > x={} > x['frequency']=33 > x['functie']=kwadraat > print x['functie'](2) > > y = super_list() > y.frequency = 33 > y.functie = kwadraat > print y.functie(3) > > > From jgardner at jonathangardner.net Fri Mar 7 19:31:08 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 7 Mar 2008 16:31:08 -0800 (PST) Subject: Edit and continue for debugging? References: Message-ID: <4efecf9f-6947-440c-bf9c-c9d2ac44ff21@s8g2000prg.googlegroups.com> This is an interesting issue because we who write web applications face the same problem. Except in the web world, the application state is stored in the browser so we don't have to work our way back to where we were. We just keep our url, cookies, and request parameters handy. Before I go on, I would suggest one thing: unit tests. If you have a hard time writing unit tests, then you need to rethink your code so that you can write unit tests. Having unit tests, running them, and debugging them is a far easier way to catch bugs and prevent them from coming back. If you don't know what a "regression test" is, you should look into the field of software testing. You'll thank yourself for it. I'm no lisp programmer, but my understanding of how lisp and lisp-like programs do this is that they replace the function with the new version. What this does to threads that are already running the function, I guess they just finish and continue on. What about closures? Well, you're out of luck there. I guess lisp programmers don't use closures in that way too often. I guess you could do the same in your debug session, although it would be hacky and difficult at best. You're out of luck if there's more than a handful of things referring to the object. A better solution would probably be to fix the offending line in the offending file and somehow magically reload that file. Well, you still have the same problem. See, a lot of your program depends on the functions and classes and objects already in that file. Those dependencies don't get magically fixed to point to the new objects just loaded. You'll have to go throughout the entire universe of variables and make them point to the new stuff. This is not an easy feat to do. In the end, you're going to realize that unless you design the system to allow you to "reload" files, whatever that means (and you'll have to define that as well), you aren't going to be able to do that. There just isn't a straightforwad, one-size-fits-all solution to this problem, except for stopping the process altogether and restarting from scratch. On Mar 7, 6:44 am, "Bronner, Gregory" wrote: > I haven't seen much on this for a few years: > > I'm working on a GUI application that has lots of callbacks. Testing it > is very slow and quite boring, as every time I find an error, I have to > exit it, restart it, and repeat the series of clicks. It would be really > amazing if python supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my code and > have it apply to a running instance of a class. I wonder if it would be > possible to do this by configuring the interpreter to parse classes and > functions rather than whole modules, and to re-parse as necessary; also > to have byte-compiled modules be singletons rather than be standard > reference counted objects. From tmp1 at viltersten.com Mon Mar 10 15:12:25 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Mon, 10 Mar 2008 20:12:25 +0100 Subject: SV: Adjust a canvas as the window is resized In-Reply-To: References: <63ga4fF27edonU1@mid.individual.net> Message-ID: <63leibF26ab65U1@mid.individual.net> >> Do i need to set a callback to a canvas >> in order to "listen" to the root window >> being resized in order to make it adjust >> its contents? >> >> If so, how? If not, how do i make the >> canvas draw a line from one corner to >> an other? > > import Tkinter as tk > > root = tk.Tk() > canvas = tk.Canvas(root) > canvas.pack(expand=True, fill=tk.BOTH) > line = canvas.create_line(0, 0, 0, 0) > > def resize(event): > canvas.coords(line, 0, 0, event.width, event.height) > canvas.bind("", resize) > > root.mainloop() Super nice! Thanks a million! -- -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From zzvladimir at gmail.com Thu Mar 6 04:36:58 2008 From: zzvladimir at gmail.com (Vladimir Kropylev) Date: Thu, 6 Mar 2008 12:36:58 +0300 Subject: generateDS problem: __init__ of base class is not called (processing linked xsd files) Message-ID: Hi, Is it possible to have __init__ of superclass called when superclass and subclass are defined in different XSD files? There's no problem when super and subclass are defined within single XSD file. In another words, can generateDS correctly process schema, described in a set of linked xsd files? Thanks. From sweet.trixie4u at gmail.com Thu Mar 6 14:39:35 2008 From: sweet.trixie4u at gmail.com (sweet.trixie4u at gmail.com) Date: Thu, 6 Mar 2008 11:39:35 -0800 (PST) Subject: RENT ADULT DVDs by MAIL - JUST LIKE NETFLIX: GET 15 DAYS FOR FREE...TRY IT NOW! Message-ID: Try It Now For FREE! http://in.urentdvds.com/c/dvdIn.cgi/3/1280876/G Choose your Porn online and it's delivered quickly and discreetly by Mail. Keep it as long as you want, then send it back when you're done. Free shipping both ways. http://in.urentdvds.com/c/dvdIn.cgi/3/1280876/G TRY IT FREE! Choose your favorite type of movies: Hardcore Action Movies http://in.urentdvds.com/c/dvdIn.cgi/32/1280876/G Movies Starring Chicks with Big Boobs http://in.urentdvds.com/c/dvdIn.cgi/31/1280876/G Porn Stars http://in.urentdvds.com/c/dvdIn.cgi/26/1280876/G Anal Movies http://in.urentdvds.com/c/dvdIn.cgi/27/1280876/G Girl on Girl Action Movies http://in.urentdvds.com/c/dvdIn.cgi/37/1280876/G Butt Shots http://in.urentdvds.com/c/dvdIn.cgi/32/1280876/G Beautiful Black Women http://in.urentdvds.com/c/dvdIn.cgi/30/1280876/G Hot Latina Women http://in.urentdvds.com/c/dvdIn.cgi/36/1280876/G Interracial Couples http://in.urentdvds.com/c/dvdIn.cgi/14/1280876/G Blow Jobs http://in.urentdvds.com/c/dvdIn.cgi/13/1280876/G Double Penetration http://in.urentdvds.com/c/dvdIn.cgi/33/1280876/G Teens http://in.urentdvds.com/c/dvdIn.cgi/41/1280876/G Three Ways http://in.urentdvds.com/c/dvdIn.cgi/42/1280876/G Tranny Movies/Chicks with Dicks http://in.urentdvds.com/c/dvdIn.cgi/25/1280876/T Gay Movies http://in.urentdvds.com/c/dvdIn.cgi/35/1280876/H From roygeorget at gmail.com Tue Mar 11 01:21:48 2008 From: roygeorget at gmail.com (royG) Date: Mon, 10 Mar 2008 22:21:48 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> On Mar 10, 8:03 pm, Tim Chase wrote: > In Python2.5 (or 2.4 if you implement the any() function, ripped > from the docs[1]), this could be rewritten to be a little more > flexible...something like this (untested): > that was quite a good lesson for a beginner like me.. thanks guys in the version using glob() >path = os.path.normpath(os.path.join(folder, '*.txt')) >lst = glob.glob(path) is it possible to check for more than one file extension? here i will have to create two path variables like path1 = os.path.normpath(os.path.join(folder, '*.txt')) path2 = os.path.normpath(os.path.join(folder, '*.doc')) and then use glob separately.. or is there another way? RG From jimtruck at gmail.com Wed Mar 26 00:30:43 2008 From: jimtruck at gmail.com (jimtruck at gmail.com) Date: Tue, 25 Mar 2008 21:30:43 -0700 (PDT) Subject: 4GB USB flash drives for only $14.49 Message-ID: <3b3fb5d0-ee10-436a-9844-b3895fa0d9b9@59g2000hsb.googlegroups.com> Hi guys, www.dealsusb.com has 4GB USB flash drives for only $14.49 Free Shipping with warranty Jimmy From mail at timgolden.me.uk Thu Mar 27 11:21:47 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 15:21:47 +0000 Subject: Checking processes running under Windows In-Reply-To: References: Message-ID: <47EBBB8B.3060509@timgolden.me.uk> Jo?o Rodrigues wrote: > Hello all! I'm trying to write a script that needs to check which processes > are running under Windows (XP Pro, Home, whatever). The method I'm using is: > >>>> process_list = os.popen('TASKLIST').read() > > However, XP Home doesn't have the tasklist.exe tool so, this is kind of > useless in that OS. Do you have any other methods I can use for this? You can do this with WMI: http://timgolden.me.uk/python/wmi_cookbook.html#running_processes TJG From mail2spj at yahoo.com Mon Mar 24 17:13:54 2008 From: mail2spj at yahoo.com (SPJ) Date: Mon, 24 Mar 2008 14:13:54 -0700 (PDT) Subject: FW:Reading new mail from outlook express using Python Message-ID: <835075.68341.qm@web50102.mail.re2.yahoo.com> My previous post was not clear, hence resending this. ------------------------- Hi, I am trying to create new tickets in the ticketing system using python. When I receive new email from a particular address, I have to trigger the python script and parse the mail in required format. The main hurdle here is, how to invoke the script on arrival of new mail? I checked the outlook settings and found that it supports only microsoft VB script and Jscript. Is there any other way? I mean, if I make a daemon, how will it be notified of new mail? Is there any python module that does this? I am not sure if this is the right place to ask this, since it is also a microsoft related question. But any help is appreciated. Thanks, SPJ ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From castironpi at gmail.com Thu Mar 13 03:10:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 00:10:06 -0700 (PDT) Subject: sys.stdout assign to- bug References: <39b263ea-e6f0-41f0-b1e8-edcbea851275@13g2000hsb.googlegroups.com> Message-ID: <6992ac74-85fa-4e98-bd8d-308517cdc07a@8g2000hse.googlegroups.com> > import sys > class ThreadedOut: > ? ? ? ? def __init__( self, old ): > ? ? ? ? ? ? ? ? self._old= old > ? ? ? ? def write( self, s ): > ? ? ? ? ? ? ? ? self._old.write( s ) > sys.stdout= ThreadedOut( sys.stdout ) > > Python 3.0a2 WinXP, on the console. ?'a' is undeclared but error > message isn't thrown. ?With 'sys.stdout= Thr...' commented: > stdout and stderr needn't be built-in file objects: any object is > acceptable as long as it has a write() method that takes a string > argument. Adding def flush( self ): self._old.flush() fixed it. Can we get that in the docs? From sturlamolden at yahoo.no Mon Mar 31 15:39:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 31 Mar 2008 12:39:43 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig References: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> <09a0fafc-5658-470a-87a4-8b906caab5ed@e6g2000prf.googlegroups.com> Message-ID: On 31 Mar, 20:52, kim wrote: > array_pointer_t = ndpointer(dtype=c_double) This one is wrong. The dtype should be the datatype kept in the array, which is 'float' (Python doubles) or 'numpy.float64'. array_pointer_t = ndpointer(dtype=numpy.float64) I'd take a good look at that C code. For example, this is not valid C: double timewarp(double x[], int lenx, double y[], int leny) { double prev; double recx[lenx+1]; double recy[leny+1]; double warp[lenx+2][leny+2]; int i,j; I would be valid C99, but you are not compiling it as C99 (gcc does not implement automatic arrays correctly in C99 anyway). If Fortran is what you want, get gfortran or Intel Fortran. To make this valid C, you will need to malloc these buffers, and free them when you are done. Another option is to give them a fixed maximum size: #define MAXLEN 1024 double recx[MAXLEN + 1]; double recy[MAXLEN + 1]; double warp[MAXLEN +2][MAXLEN +2]; There may be other errors as well, I did not look at it carefully. From jkrukoff at ltgc.com Wed Mar 12 15:17:33 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 12 Mar 2008 13:17:33 -0600 Subject: Does __import__ require a module to have a .py suffix? In-Reply-To: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: <1205349453.9664.33.camel@localhost.localdomain> On Wed, 2008-03-12 at 09:22 -0700, mrstephengross wrote: > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? > > Thanks, > --Steve I recently solved a similar issue, importing from a string, with this code: >>> service = imp.new_module( 'ServiceModule' ) >>> compiled = compile( '''...some code here...''', '', 'exec', 0, 1 ) >>> exec compiled in service.__dict__ You could probably shorten it for your needs by using execfile instead. If it's not in the current directory, you'll probably run into some issues with further imports not working as expected unless you set the names/paths right. -- John Krukoff Land Title Guarantee Company From lists at cheimes.de Wed Mar 19 18:10:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 Mar 2008 23:10:38 +0100 Subject: Improving datetime In-Reply-To: References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <47E18F5E.8030608@cheimes.de> Nicholas F. Fabry schrieb: > Thank you for the prompt response and suggestion! I am writing up a > proposal presently. There are, however, two broad category of changes > - the 'easy' changes, which could be accomplished with little > additional effort, and the 'hard' changes, which would require > significant reworking of the datetime class (or a wrapper around it). > I was going to break my proposal up into two parts, the easy part and > the hard part. Does that sound like a good idea? Or should I unify > the two? The prime purpose of all the changes, easy and hard, is to > make timezone handling accurate and clear, reduce and make clearer the > (application programmer) code required to use them, and give more > informaton to the programmer about errors, not silently assume > something and pass them. Yes, it sounds like a good idea. The low hanging fruits (aka easy tasks) could be implemented for 2.6 and 3.0. The more complex tasks may have to wait for 2.7 and 3.1 Apropos time zones. A while ago I proposed the inclusion of pytz. But Stuart argued that the tz database may change monthly so I retracted my proposal. But Stuart has proposed some improvements for datetime's tz class. I suggest you contact him. > Please clarify how long a novel is? The problem with the modules are > not bugs, they are problems with real world use scenarios that result > in inescabably ugly code without improvements to the module - so the > explanations involve code samples and use cases... so they may be > 'long'. Could you suggest a maximum number of (70 char) lines, or an > example of an overly long proposal? Some people tend to start their postings like: In the year 2008 after the birth of Christ I, the son of Jone, son of James ... Do you get my point? :] I suggest you start with a short introduction of yourself and your proposal. Short paragraphs and short sentences are easier to read than long. You'll do fine ;) Christian From castironpi at gmail.com Sat Mar 1 15:09:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 12:09:30 -0800 (PST) Subject: rpc shortcut Message-ID: RPC might be -really- easy. Mixin class: getattribute returns a remoting callable if ('name') is callable, or in a special list. On call, pack the parameters, execute locally, and broadcast. You'd need two mixins, BroadcasterMixin and ReceiverMixin, but the same code can still run-- how can behavior depend on whether a given class is listening or "talking" in a given instance? Also, customize mixins: BcastMixin, RceiveMixin with ServerSideMixin, ClientSideMixin, or BothSidesMixin, the first two executing state change in one place, and informing of the new state, or independently, opt'ly with some verification in worries of non-determinism. Or, perhaps, @ServerSide and @ClientSide decorations. It sucks when bandwidth cost might depend on certain parameters-- big state changes vs. big processing time vs. big parameter lists comparatively, esp'ly when they aren't right as separate functions... though do cf. multimethods for param. value checking on this: @servside @params( 'i', lambda i: i> 100 ) def func( i ) / @cliside @params( default ) def func( i ). From brooklineTom at gmail_spam_blocking_suffix.com Mon Mar 31 09:57:44 2008 From: brooklineTom at gmail_spam_blocking_suffix.com (brooklineTom at gmail_spam_blocking_suffix.com) Date: Mon, 31 Mar 2008 09:57:44 -0400 Subject: Smalltalk-style "senders" and "implementors" Message-ID: I'm wondering if anyone has coded up a way to do Smalltalk-style runtime "senders" and "implementors" for python methods. For senders, I think the idea is to traverse the module space and collect, for each method, the names of any methods or functions it calls. In Smalltalk, the workhorse is "CompiledMethod>>sendsSelector". The Smalltalk heuristic is to collect a method name, then traverse all the classes, and within each class traverse all the CompiledMethod instances, invoking the above and collecting the results. I'm wondering if an equivalent exists for Python. For implementors, the idea is to traverse the module space looking for classes that define some supplied method name. I'm looking for a way to do this, at run-time, based on the modules that are actually loaded (rather than a full-text traversal of all the files). The purpose is so that I have a way to make refactoring easier. For example, when I need to change a method name, I want an easy way to find all the methods that invoke it. Full-text lexical search works, but answers lots of false hits, for example from packages where unused files are still hanging around. Thx, Tom From dickinsm at gmail.com Sat Mar 8 21:27:27 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 18:27:27 -0800 (PST) Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: <756ec84d-643a-4bc5-a58f-25c72bd979b1@8g2000hse.googlegroups.com> On Mar 8, 9:19?pm, "Terry Reedy" wrote: > Obvious typo: -(-a)//b == a//b > > This should be -(-a//b) == -((-a)//b) Yes: thanks for the correction! A lesson to me to include parentheses even when redundant... This reminds me of the following parenthesization gem (see next to last line): def isqrt(n): """Find the closest integer to sqrt(n), for n a positive integer.""" a, b = n, 1 while a != b: a, b = a -- n // a >> 1, a return a Mark From zerty.david at gmail.com Wed Mar 26 15:14:07 2008 From: zerty.david at gmail.com (David Anderson) Date: Wed, 26 Mar 2008 16:14:07 -0300 Subject: what does ^ do in python In-Reply-To: <47EA99EE.5030304@tim.thechases.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> <47EA99EE.5030304@tim.thechases.com> Message-ID: <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> Err even I cant understand what I wrote... The right question was:HOw can we use/express pointers python as in C or Pascal? But thx to Heiko, He got what I mean =) On Wed, Mar 26, 2008 at 3:46 PM, Tim Chase wrote: > >> HOw can we use express pointers as in C or python? > > > > Traceback (most recent call last): > > File "", line 1, in > > File "parser.py", line 123, in parse_text > > tree = language.parse_text(text) > > File "english.py", line 456, in parse_text > > tree = self.parse_sentence(sentence) > > File "english.py", line 345, in parse_sentence > > raise ParserError, "can't parse %r" % sentence > > ParserError: can't parse 'HOw can we use express pointers as in C or > > python?' > > Possible "express pointers": > > http://www.geocities.com/derwin_b/sr91sign.jpg > > http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg > > http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg > > If those meet the OP's need, I recommend urllib2 and PIL. > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 16:59:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 21:59:19 -0000 Subject: Why """, not '''? References: Message-ID: <13su5tn6rpjb345@corp.supernews.com> On Wed, 05 Mar 2008 19:19:08 +0000, Matthew Woodcraft wrote: > wrote: >> Why is """ the preferred delimiter for multi-line strings? > > One advantage is that a dumb syntax highlighter is more likely to cope > well if the content includes an apostrophe. But if the content contains double-quote marks, the "dumb syntax highligher" is more likely to cope well if you use '''. And, let's be realistic here, a "dumb syntax highlighter" is more likely to not cope well with triple-quote strings *at all*. Python treats ' and " symmetrically. There is no difference between them, except that: (1) to type " requires using the shift-key, typing ' does not (on English QWERTY keyboards at least); (2) in some typefaces " (double-quote) may be confused with '' (two single-quotes); and (3) they look different. Pretty basic stuff really. -- Steven From deets at nospam.web.de Tue Mar 25 17:52:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Mar 2008 22:52:52 +0100 Subject: _tkinter fails when installing Python 2.4.4 In-Reply-To: References: Message-ID: <64tahuF2absebU1@mid.uni-berlin.de> jgelfand schrieb: > I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat > Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ > usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but > I get the following error message when I run "make": > > building '_tkinter' extension > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ > usr/local/yosi/Python-2.5.2/Modules/_tkinter.o > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ > usr/local/yosi/Python-2.5.2/Modules/tkappinit.o > gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ > Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ > yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ > lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - > ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so > *** WARNING: renaming "_tkinter" since importing it failed: build/ > lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents > > Any suggestions / ideas as to what is going wrong? I don't get any > other warnings or errors on the other modules. Thanks -- Yosi You are aware that the above shows python 2.5 as the version that is being used for compilation? Diez From harrelson at gmail.com Sat Mar 22 18:51:00 2008 From: harrelson at gmail.com (harrelson) Date: Sat, 22 Mar 2008 15:51:00 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> <5bd9b02a-958b-452d-9e20-c10e4c29f9e4@i29g2000prf.googlegroups.com> <13uaaavi55n7d9b@corp.supernews.com> Message-ID: <0920ddb2-1b36-481b-933f-5a15c3c4dd3d@i12g2000prf.googlegroups.com> Thanks Grant, that does it! I knew it had to be something simple like that and it was frustrating not to be able to find it. I do prefer the tuple. Thanks again. culley From geert at nznl.com Wed Mar 19 06:30:33 2008 From: geert at nznl.com (geert) Date: Wed, 19 Mar 2008 03:30:33 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> <7900f1db-16a5-45d1-ada3-962ac0e712b8@e6g2000prf.googlegroups.com> Message-ID: <046c9579-9ff3-44ad-86b7-0c64c8a606ed@8g2000hsu.googlegroups.com> On Mar 19, 2:26?am, Graham Dumpleton wrote: > On Mar 19, 9:47 am, geert wrote: > > > > > On Mar 18, 6:56 pm, geert wrote: > > > > On Mar 14, 1:15 pm, martin.lal... at gmail.com wrote: > > > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > > > Just wanted to let you know that I've solved my problem. The solution > > > is to compile mysql using > > > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > ./configure --disable-dependency-tracking ?--enable-thread-safe-client > > > --prefix=/usr/local/mysql > > > > You then go this way to get it running on your machine: > > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > > > Then reinstall MySQLdb. Magic! > > > > Geert > > > Seems that I've yelled success to quickly. Everything's ok as long as > > I just run the django dev server, but moving to apache throughmod_wsgibrings a well-known but less than comforting complaint: > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352): > > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ > > LN/LNApache.wsgi'., referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent > > call last):, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in > > __call__, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? response = > > self.get_response(request), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in > > get_response, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? response = > > middleware_method(request), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line > > 13, in process_request, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? engine = > > __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line > > 2, in , referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? from > > django.contrib.sessions.models import Session, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, > > in , referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? from django.db > > import models, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/db/__init__.py", line 17, in , > > referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? backend = > > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, > > {}, ['']), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, > > in , referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? raise > > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: > > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ > > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no > > suitable image found. ?Did find:, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ > > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- > > tmp/_mysql.so: no matching architecture in universal wrapper, referer:http://localhost/images/ > > Did you again confirm that running: > > ? file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5- > macosx-10.5-i386.egg-tmp/_mysql.so > > shows the .so having the required architectures, specifically what > Apache runs as (eg. x86_64)? > > Do the gcc compiler flags when building and linking the .so file show > all the architecture flags? > > Have you empty the Python egg cache to make sure it isn't an older > compiled version? > > Graham Hi all, GOT IT! I have every running now. So, to sum it all up: I'm on a new intel mac with a 64-bit capable processor running macosx 10.5.2. I have httpd (apache2) running as a 64 bit app, which it would of course on a 64-bit machine. Activity monitor confirms this. I compiled mysql from source, configured as stated below: MACOSX_DEPLOYMENT_TARGET=10.5 \ CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ ./configure --disable-dependency-tracking --enable-thread-safe- client --prefix=/usr/local/mysql Then came mod_wsgi, just out of the box. Then came MySQLdb. Extracted the tar, then edited _mysql.c. Commented lines 37 - 39: //#ifndef uint //#define uint unsigned int //#endif and changed this: uint port = MYSQL_PORT; uint client_flag = 0; to this: unsigned int port = MYSQL_PORT; unsigned int client_flag = 0; on lines 484 and 485 Then - but I don't know if this is really (always) necessary, in site.cfg I changed Threadsafe = True to False. I set the ARCHFLAGS, but I don't think this helped one inch. ARCHFLAGS='-arch ppc -arch ppc64 -arch i386 -arch x86_64' OK. So then I went sudo python setup.py build. (I realise that the sudo isn't required just to do a build) There, I noticed this: creating build/temp.macosx-10.5-i386-2.5 gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes - DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -pipe - Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/ include/mysql -I/System/Library/Frameworks/Python.framework/Versions/ 2.5/include/python2.5 -c _mysql.c -o build/temp.macosx-10.5-i386-2.5/ _mysql.o -arch i386 -arch x86_64 -arch ppc7400 -arch ppc64 You see, here _mysql.o is being created. If you do file _mysql.o, you get: /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o: Mach-O universal binary with 4 architectures /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture i386): Mach-O object i386 /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture x86_64): Mach-O 64-bit object x86_64 /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture ppc7400): Mach-O object ppc /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture ppc64): Mach-O 64-bit object ppc64 which is ok. But, strangely, when _mysql.so is created in the next step, gcc doesn't add all the arch flags: gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch i386 -arch ppc build/temp.macosx-10.5-i386-2.5/_mysql.o -L/usr/local/mysql/lib/mysql - lmysqlclient -lz -lm -o build/lib.macosx-10.5-i386-2.5/_mysql.so and you end up with this: geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/geert/ Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/_mysql.so /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ _mysql.so: Mach-O universal binary with 2 architectures /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ _mysql.so (for architecture i386): Mach-O bundle i386 /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ _mysql.so (for architecture ppc7400): Mach-O bundle ppc which is most definitely NOT ok. So I did this: sudo gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch ppc -arch ppc64 -arch i386 -arch x86_64 build/temp.macosx-10.5-i386-2.5/_mysql.o -L/usr/local/mysql/lib/mysql -lmysqlclient -lz -lm -o build/ lib.macosx-10.5-i386-2.5/_mysql.so adding the arch flags myself, and running gcc again, under sudo. and lo and behold.... geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/ geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/ _mysql.so /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so: Mach-O universal binary with 4 architectures /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture ppc7400): Mach-O bundle ppc /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture ppc64): Mach-O 64-bit bundle ppc64 /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture i386): Mach-O bundle i386 /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture x86_64): Mach-O 64-bit bundle x86_64 Well, it only took 20 years off my life span and all the hairs on my head :) Geert From bj_666 at gmx.net Tue Mar 18 05:44:33 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Mar 2008 09:44:33 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> <8ca43caa-5a2c-4b7b-b168-aad4cfb0581a@a23g2000hsc.googlegroups.com> Message-ID: <649h81F2974cmU1@mid.uni-berlin.de> On Mon, 17 Mar 2008 12:51:14 -0700, sjdevnull at yahoo.com wrote: > On Mar 17, 12:15 pm, rockingred wrote: >> On Mar 10, 11:30 am, "sjdevn... at yahoo.com" >> >> Unfortunately, no free VC system existed for the language in which I >> was programming > > Explain? VC isn't language-specific. It is. It depends usually on the fact that there are individual files. Preferably text files if you want automagic merging of different changes. Now think of languages that are tightly coupled with their IDE storing only binary "tokenized" files instead of plain text or even one big binary file that contains all sources and resources of the project. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:09:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:09:36 -0700 (PDT) Subject: del class with recursive list References: Message-ID: <252fefaa-0695-4f00-9bdc-bebd5bc509b8@n77g2000hse.googlegroups.com> On 9 mar, 17:20, d... at tiscali.it wrote: > Thanks! I just need to remember to del the variables after "for in". And when working on the interactive interpreter, it's easy to forget the _ variable too (that holds the last printed expression) -- Gabriel Genellina From codedread at gmail.com Sun Mar 9 13:43:57 2008 From: codedread at gmail.com (Jeff Schiller) Date: Sun, 9 Mar 2008 12:43:57 -0500 Subject: Need Help Building PythonQt on Windows In-Reply-To: <63ilglF28106hU1@mid.uni-berlin.de> References: <63ilglF28106hU1@mid.uni-berlin.de> Message-ID: I said "PythonQt" not PyQt. That's an important distinction, I think :) See http://pythonqt.sourceforge.net/ Regards, Jeff On 3/9/08, Diez B. Roggisch wrote: > Jeff Schiller schrieb: > > > Hello, > > > > I'm creating an application using Qt (4.4 Beta atm). I have pretty > > close to zero experience with Python (consisting of installing the > > Python interpreter, downloading a python programming and executing it > > on the command-line). > > > > I would like to invoke a Python script from my C++ Qt program and > > capture its output as a C++ structure. It seems that PythonQt might > > be suitable for my needs. > > > > Being a Qt program, I want this thing to be cross-platform. I'm > > having trouble getting things set up in Windows. Has anyone had any > > experience with this? > > > > I've built Qt from source using the mingw32 compiler. I installed > > Python 2.5 binary. I am trying to build PythonQt from source. As per > > http://pythonqt.sourceforge.net/#Building it says I need a "developer > > installation" of Python containing the header files and the library > > files. When I look at my system after installing the Python 2.5 > > binary, I can see I have header files (C:\Python25\include), a 199k > > python25.lib (C:\Python25\libs) and a 2MB python25.dll > > (C:\Windows\System32\). Have I got what I need? > > > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > > to build but then it fails: > > > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > > `_imp__Py_NoSiteFlag' > > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > > `_imp__Py_NoSiteFlag' > > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > > `_imp___Py_NoneStruct' > > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > > `_imp___Py_NoneStruct' > > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > > `_imp___Py_NoneStruct' > > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > > `_imp___Py_NoneStruct' > > ./debug\PythonQt.o: In function > > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > > `_imp__PyClass_Type' > > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > > `_imp__PyClass_Type' > > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > > `_imp__PyCFunction_Type' > > ... > > > > Since I'm new to compiling Qt with mingw and completely new to python, > > I was hoping for tips on why I'm getting these errors. If anyone has > > a better suggestion for a forum/mailing list then please let me know. > > > > A few of suggestions: > > - take this to the PyQt mailing list > (http://www.riverbankcomputing.com/mailman/listinfo/pyqt) > > - you only *need* pyqt if what you want to do in python has really to > deal with Qt-objects - maybe "simple" embedding is enough for your needs > > - I don't see why you need to compile PyQt yourself at all - are you > sure you can't use the stock PyQt for windows? What makes you believe > you really need this to be self-compiled? > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > From spammb at gmail.com Thu Mar 20 15:10:17 2008 From: spammb at gmail.com (Michael Becker) Date: Thu, 20 Mar 2008 12:10:17 -0700 (PDT) Subject: Issues with XMLTreeBuilder in cElementTree and ElementTree Message-ID: <5d820787-e27d-4ae2-8b2b-b82af8ce67cf@p25g2000hsf.googlegroups.com> I had some xmls being output by an application whose formating did not allow for easy editing by humans so I was trying to write a short python app to pretty print xml files. Most of the data in these xml files is in the attributes so I wanted each attribute on its own line. I wrote a short app using xml.etree.ElementTree.XMLTreeBuilder(). To my dismay the attributes were getting reordered. I found that the implementation of XMLTreeBuilder did not make proper use of the ordered_attributes attribute of the expat parser (which it defaults to). The constructor sets ordered_attributes = 1 but then the _start_list method iterates through the ordered list of attributes and stores them in a dictionary! This is incredibly unintuitive and seems to me to be a bug. I would recommend the following changes to ElementTree.py: class XMLTreeBuilder: ... def _start_list(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = [] if attrib_in: for i in range(0, len(attrib_in), 2): attrib.append((fixname(attrib_in[i]), self._fixtext(attrib_in[i+1]))) return self._target.start(tag, attrib) class _ElementInterface: ... def items(self): try: return self.attrib.items() except AttributeError: return self.attrib These changes would allow the user to take advantage of the ordered_attributes attribute in the expat parser to use either ordered or unorder attributes as desired. For backwards compatibility it might be desirable to change XMLTreeBuilder to default to ordered_attributes = 0. I've never submitted a bug fix to a python library so if this seems like a real bug please let me know how to proceed. Secondly, I found a potential issue with the cElementTree module. My understanding (which could be incorrect) of python C modules is that they should work the same as the python versions but be more efficient. The XMLTreeBuilder class in cElementTree doesn't seem to be using the same parser as that in ElementTree. The following code illustrates this issue: >>> import xml.etree.cElementTree >>> t1=xml.etree.cElementTree.XMLTreeBuilder() >>> t1._parser.ordered_attributes = 1 Traceback (most recent call last): File "", line 1, in AttributeError: _parser >>> import xml.etree.ElementTree >>> t1=xml.etree.ElementTree.XMLTreeBuilder() >>> t1._parser.ordered_attributes = 1 In case it is relevant, here is the version and environment information: tpadmin at osswlg1{/tpdata/ossgw/config} $ python -V Python 2.5.1 tpadmin at osswlg1{/tpdata/ossgw/config} $ uname -a SunOS localhost 5.10 Generic_118833-33 sun4u sparc SUNW,Netra-240 From arnodel at googlemail.com Fri Mar 14 08:17:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 14 Mar 2008 05:17:23 -0700 (PDT) Subject: How do I iterate over items in a dict grouped by N number of elements? References: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> Message-ID: <95231b52-4f6b-4e56-a316-68a04d243214@u10g2000prn.googlegroups.com> On Mar 14, 1:34?am, Noah wrote: > What is the fastest way to select N items at a time from a dictionary? > I'm iterating over a dictionary of many thousands of items. > I want to operate on only 100 items at a time. > I want to avoid copying items using any sort of slicing. > Does itertools copy items? > > This works, but is ugly: > > >>> from itertools import * > >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} > >>> N = 3 > >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N): This solution matches exactly the one proposed in itertools. The following is an extract from http://docs.python.org/lib/itertools-functions.html. Note, the left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using "izip(*[iter(s)]*n)". For data that doesn't fit n-length groups exactly, the last tuple can be pre-padded with fill values using "izip(*[chain(s, [None]*(n-1))]*n)". -- Arnaud From dstromberglists at gmail.com Sun Mar 30 21:03:26 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 31 Mar 2008 01:03:26 +0000 (UTC) Subject: Serial port error statistics - any comparable data? References: <001b01c8918e$323b74c0$03000080@hendrik> Message-ID: On Sat, 29 Mar 2008 13:14:46 +0200, Hendrik van Rooyen wrote: > Hi, > > I have been doing some tests on a device that we are thinking of > incorporating into a product, and I have seen that reception on a serial > port at 115200 baud over about six metres of RS-232 cable makes > mistakes, to the order of 125 lines with errors in them out of > approximately 18.4 million lines of 65 or so chars - about one errored > line in 147000, or one error character in 95 million. > > The PC that is making the errors is a 64 bit dual core AMD machine > running at 2 Gig, and I am running stock standard Open Suse 10.3 with > the supplied Python 2.5. > > What kind of bothers me is the nature of the errors - I seem to get only > missing characters, as if an interrupt was missed. There are no munged > characters as one would expect if the errors were bit related. > > Has anyone else seen anything like this, and am I worrying needlessly? > > I realise that my production protocols will easily handle this almost > non existent level of error - but if this were in microcontroller code > that I had written myself, I would suspect that I was spending too long > in some critical section of code. > > - Hendrik Have you verified that you have flow control enabled? ISTR hearing there is one kind of software flow control and two kinds of hardware flow control. I'm not serial expert, but ISTR that if your cable supports it, you should use RTS/CTS hardware flow control, and if it doesn't, use software flow control. From malaclypse2 at gmail.com Wed Mar 19 11:23:18 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 Mar 2008 11:23:18 -0400 Subject: cx_Oracle execute procedure In-Reply-To: References: Message-ID: <16651e80803190823g4536d422o548732d539a05eda@mail.gmail.com> On Wed, Mar 19, 2008 at 11:03 AM, Poppy wrote: > I've been working on the code below and and executes silently, no > complaints, however the end result should be a record in my table and it's > not added. The procedure works with the passed credentials using SQLPlus or > SQL Developer clients. However I'm not sure if I'm constructing my python > code correctly to interact with Oracle. ... > connection.commit > cur.close > connection.close You have to actually call these methods: connection.commit() cur.close() connection.close() Without the parentheses, you're just getting a reference to the methods and immediately discarding them. -- Jerry From gagsl-py2 at yahoo.com.ar Sun Mar 16 19:44:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 21:44:17 -0200 Subject: Basics of Python,learning References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: En Sun, 16 Mar 2008 14:25:26 -0200, Guido van Brakel escribi?: > Why is this not working,and how can I correct it? I guess you want to: a) read a single line containing many numbers separated by white space b) convert them to a list of floating point numbers c) print their minimum and maximum value a) Already done >> z = raw_input ('Give numbers') b) Already done >> y = z.split() >> b=[] >> for i in y: >> b.append(float(i)) The list of numbers is called "b". Don't define a function with the same name, you'll lose the original list attached to the name "b". c) Almost done; remember that your list of numbers is called "b" not "a": >> print min(b) >> print max(b) d) We (Python and me) have no idea what "gem" is: >> print gem(b) -- Gabriel Genellina From dripton at ripton.net Thu Mar 13 09:57:08 2008 From: dripton at ripton.net (dripton) Date: Thu, 13 Mar 2008 06:57:08 -0700 (PDT) Subject: Problem with subprocess in threaded enviroment References: <5972c513-c86c-42bf-bcc8-632dd0f0e8f0@i7g2000prf.googlegroups.com> Message-ID: <0c3c6eac-1773-4386-b34a-c8736b03c583@q78g2000hsh.googlegroups.com> On Mar 12, 12:58 pm, Ningyu Shi wrote: > I'm trying to write a multi-task downloader to download files from a > website using multi-threading. I have one thread to analyze the > webpage, get the addresses of the files to be downloaded and put these > in a Queue. Then the main thread will start some threads to get the > address from the queue and download it. To keep the maximum files > downloaded concurrently, I use a semaphore to control this, like at > most 5 downloads at same time. You don't need a semaphore for that. Semaphores are low-level and very hard to get right. (Read http://www.greenteapress.com/semaphores/ if you don't believe me.) You don't need any other type of explicit lock either. Just use Queues. Queues are much easier. Make simple threads, each of which typically reads from one queue and writes to one queue. If you want N-way concurrency at one stage, start N instances of that thread. If you need to guarantee non-concurrency at some stage, make that thread a singleton. Avoid sharing mutable data across threads except through Queues. > I tried to use urllib.urlretreive in the download() thread, but from > time to time, it seems that one download thread may freeze the whole > program. Then I gave up and use subprocess to call wget to do the job. > My download thread is like this: > > def download( url ): > subprocess.call(["wget", "-q", url]) > with print_lock: > print url, 'finished.' > semaphore.realease() If the prints are just for debugging, print_lock is overkill. And in practice that print statement is probably atomic in CPython because of the GIL. But let's assume that it really is critical not to mix the output streams, and that the print isn't necessarily atomic. So instead of the lock, use a print_queue and a single PrintThread that just pulls strings off the queue and prints them. > But later I found that after the specific wget job finished > downloading, that download() thread never reach the print url > statement. So I end up with files been downloaded, but the download() > thread never ends and don't realease the semaphore then block the > whole program. My guess is that at the time wget process ends, that > specific download thread is not active and missed the return of the > call. The fact that changing libraries didn't fix your problem is a strong indicator that it's your code, not the libraries. You're probably introducing deadlocks with your semaphores. Too much locking is as bad as too little. Here's the skeleton of how I'd write this program: main thread: create queues, create and start other threads, find URLs, put URLs on input_queue class DownloadThread(threading.Thread): def run(self): while True: url = input_queue.get() urllib.urlretrieve(url) print_queue.put("done with %s" % url) class PrintThread(threading.Thread): def run(self): while True: st = print_queue.get() print st Then you just have to worry about clean shutdown. A simple way to handle this to initialize a counter to the number of URLs in main, and decrement it in PrintThread. Then have main busy-wait (with a sleep to avoid consuming too much CPU) for it to hit zero, then join all the other threads and exit. (This seems to violate the no-shared-mutable- data rule, but only one thread at a time can mutate it, so it's safe.) Once you've done this manually, consider using the TaskQueue recipe on the Python Cookbook site, to simplify it a bit. From fn681 at ncf.ca Sat Mar 1 10:40:58 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sat, 01 Mar 2008 10:40:58 -0500 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c93bb8$0$874$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI (MVP) wrote: > Hi, all! > > Since the install of Python 2.5.2, Pyscripter (1.9.9.1) close for each > error. > Is it only me? Or another guys have the same thing? > > @-salutations > > Michel Claveau > > > > Could you be more explicit please? I use PyScripter and do not have this problem. Colin W. From adonis_vargas at -Remove-This-bellsouth.net Thu Mar 13 19:46:04 2008 From: adonis_vargas at -Remove-This-bellsouth.net (Adonis Vargas) Date: Thu, 13 Mar 2008 19:46:04 -0400 Subject: Python regex In-Reply-To: References: Message-ID: Andrew Rekdal < wrote: > I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > >>> CSS comment > > although this works to a degree... I know the within the brackets everything > is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? eg. > where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... negate > > > -- Andrew > > Have you looked into this library: http://cthedot.de/cssutils/ May help you, if you are trying to achieve something. If your doing it as an exercise then I can not help you, I avoid regex like the plague (but thats just me). Hope this helps. Adonis Vargas From lac at openend.se Mon Mar 17 03:47:01 2008 From: lac at openend.se (Laura Creighton) Date: Mon, 17 Mar 2008 08:47:01 +0100 Subject: Europython fees (was PyCon Disappointment) Message-ID: <200803170747.m2H7l1qg031084@theraft.openend.se> Bj?rn wrote: >I haven't been to EuroPython even when it has been fairly nearby >because the entrance fee was to high. But how do you help change >something like that? Last year rates were: 100 Euros for early bird, 160 Euros for later registration, 65 Euros for early students and 85 Euros for later registration. Thus for most people transportation costs and hotel costs work out to more than Europython costs. There is also a program of financial aide for people who cannot afford the costs, approval on a per-case basis. Are you sure you aren't confusing us with OSCON? Can we discuss this on europython-improve at python.org ? Laura Creighton From sturlamolden at yahoo.no Tue Mar 18 10:10:20 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 07:10:20 -0700 (PDT) Subject: Interesting math problem References: Message-ID: On 18 Mar, 00:58, Jeff Schwab wrote: > def make_slope(distance, parts): > if parts == 0: > return [] > > q, r = divmod(distance, parts) > > if r and parts % r: > q += 1 > > return [q] + make_slope(distance - q, parts - 1) Beautiful. If Python could optimize tail recursion, it would even run fast. From bj_666 at gmx.net Tue Mar 18 08:26:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Mar 2008 12:26:15 GMT Subject: Python 3 and PEP238 division References: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> Message-ID: <649qn7F2974cmU3@mid.uni-berlin.de> On Tue, 18 Mar 2008 04:47:49 -0700, Ninereeds wrote: > On Mar 17, 7:26 pm, "Terry Reedy" wrote: >> 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion >> program > > The tools can work out the *intent* of any particular division > operator? Can work out whether the result should be integer or float, > independent of any particular set of arguments? Seems unlikely. The interpreter can at least print out warnings when a "normal" division operator is called with two `int`\s at runtime. Ciao, Marc 'BlackJack' Rintsch From bearophileHUGS at lycos.com Thu Mar 27 11:59:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 27 Mar 2008 08:59:33 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch: > the author says that the approach is flawed, so at *some* > point it will be discontinued. Can't Psyco be improved, so it can compile things like: nums = (i for i in xrange(200000) if i % 2) print sum(nums) I think the current Psyco runs slower than Python with generators/ iterators. To speed up that code with Psyco you have to write this: nums = [i for i in xrange(200000) if i % 2] print sum(nums) Bye, bearophile From jared.grubb at gmail.com Thu Mar 6 02:47:31 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Wed, 5 Mar 2008 23:47:31 -0800 Subject: for-else Message-ID: <925822270803052347r6239f268pef9b7e8e5ff9b28f@mail.gmail.com> I think bearophile makes an excellent point. I also have a hard time remembering what else does. I have always pictured that the "normal" behavior of a for loop is to get through all the items. In special circumstances, it is necessary to break out early. Therefore, it FEELS like the else loop should excute in the "unexpected" or abnormal case (break), whereas the else actually gets executed only when the entire loop DOES complete. Ben Finney's idea of using an except clause after the for loop is an excellent idea, as it makes it VERY clear when the case gets executed. (I would disagree with his suggestion to use "else" in the break case, however, because that would confuse the previous meaning.) However, you could then make "break" equivalent to "raise BreakException", and provide the following: for foo in bar_sequence: # normal iteration spam(foo) if funky(foo): break except StopIteration, exc: # the iterator stopped normally eggs(exc) except BreakException, exc: # the iterator exited abnormally, i.e. 'break' sausage() Giving a loop a "try"-like behavior could open up the ability to jump out of multiple levels of loops: while 1: while 1: break except BreakException: break # or re-raise? Or maybe you can do "raise BreakException(2)" without any except clauses at all? Just my $0.02. Jared On 4 Mar 2008, at 12:27, bearophileHUGS at lycos.com wrote: Raymond HettInger: FWIW, I'm very happy with for-else. Most of the time, you don't need it, but when you do, it beats the heck out of doing silly tricks with flags. I'd like it to be renamed to something more natural :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Sun Mar 2 04:02:31 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 2 Mar 2008 01:02:31 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> Message-ID: <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> On 2 Mrz., 06:53, Ben Finney wrote: > One of the stated goals of the migration is that the '2to3' program > will only migrate Python 2.6 code -> Python 3.0 code. Yes, I know. Why? "The master said so" isn't an entirely satisfying answer. What are the *technical reasons* that make it hard to apply '2to3' directly on Python 2.4 or Python 2.5? From sjdevnull at yahoo.com Sun Mar 9 01:25:07 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sat, 8 Mar 2008 22:25:07 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> <13t6s8pk90olef8@corp.supernews.com> Message-ID: <626b9dfc-2f4a-47d8-b461-adb3ca813ea0@2g2000hsn.googlegroups.com> On Mar 9, 12:09 am, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 20:45:25 -0800, sjdevn... at yahoo.com wrote: > > On Mar 8, 7:34 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > >> > I'm also a bit baffled by people who put a comment at the top of > >> > every file that tells you what the filename is. > > >> [snip rant] > > >> You've never printed out a source file on pieces of dead tree to read > >> on the train on the way home, or in bed or the bath? > > >> Yes, some editors will print a header or footer showing the file name, > >> but not all will, or are configured to do so. > > > The only times I can recall printing source were in college classes > > where I was required to hand in a hardcopy with the assignment and code > > samples for job interviews. In the real world the code base tends to be > > too huge to contemplate printing... > > You've never (say) printed out the source code to one of the modules in > the Python standard library to read and study? Nope. It's a lot easier to read on the computer, with searching, proper syntax highlighting, tags, etc and access to all the other information I might want while reading the code, and the ability to drift to other modules that might be imported/mentioned, find examples using them, etc. > If your code base is so huge that you can't print out any meaningful > piece, then you desperately need more encapsulation. Yeah, most of the code is encapsulated into smaller parts. The problem is figuring out what meaningful piece(s) I might want. How often do you really find yourself knowing ahead of time exactly what you want to read? Even in code reviews it's common to look at other files in the system, version control history, the issue/spec tracker, or even wander off into Python documentation, algorithm papers, or whatever. It just doesn't seem worth playing a guessing game about exactly what code/versioning/docs/etc I might want to have on hand when the net result even if I guess right will be a worse reading experience without searching, tags, bookmarks, etc. > > Even in the early 1990s the moral equivalent of enscript (I think it was > > a2ps) worked just fine for printing with filenames, line/page numbers, > > and other niceties no matter what editor you used. It seems more > > reasonable to mandate using a sane print tool for the odd case where > > someone wants to print things out than to mandate cluttering up every > > file with the filename in a comment. > > Sure, but really, adding ONE LINE to the start of a file is hardly > "cluttering up" anything. It's not terrible, no, just vaguely pointless and a bit fragile in the face of change. From patrick.waldo at gmail.com Sat Mar 1 09:14:30 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Sat, 1 Mar 2008 06:14:30 -0800 (PST) Subject: joining strings question References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> Message-ID: <616e9a4f-a474-486d-a574-cd799fa4c717@i12g2000prf.googlegroups.com> > def category_iterator(source): > source = iter(source) > try: > while True: > item = source.next() This gave me a lot of inspiration. After a couple of days of banging my head against the wall, I finally figured out a code that could attach headers, titles, numbers, and categories in their appropriate combinations--basically one BIG logic puzzle. It's not the prettiest thing in the world, but it works. If anyone has a better way to do it, then I'll be all ears. Anyways, thank you all for your input, it helped me think outside the box. import re data = ['RULES', 'Approval and Promulgation of Air Quality Implementation Plans:', 'Illinois; Revisions to Emission Reduction Market System, ', '11042 [E8-3800]', 'E8-3800.pdf', 'Ohio; Oxides of Nitrogen Budget Trading Program; Correction, ', '11192 [Z8-2506]', 'Z8-2506.pdf', 'NOTICES', 'Agency Information Collection Activities; Proposals, Submissions, and Approvals, ', '11108-11110 [E8-3934]', 'E8-3934.pdf', 'Data Availability for Lead National Ambient Air Quality Standard Review, ', '11110-11111 [E8-3935]', 'E8-3935.pdf', 'Environmental Impacts Statements; Notice of Availability, ', '11112 [E8-3917]', 'E8-3917.pdf'] NOTICES = re.compile(r'NOTICES') RULES = re.compile(r'RULES') TITLE = re.compile(r'[A-Z][a-z].*') NUM = re.compile(r'\d.*') PDF = re.compile(r'.*\.pdf') counted = [] sorted = [] title = [] tot = len(data) x=0 while x < tot: try: item = data[x] title = [] if NOTICES.match(item) or RULES.match(item): module = item header = '' if TITLE.match(data[x+1]) and TITLE.match(data[x+2]) and NUM.match(data[x+3]): #Header header = data[x+1] counted.append(data[x+1]) sorted.append(data[x+1]) #Title counted.append(data[x+2]) sorted.append(data[x+2]) #Number counted.append(data[x+3]) sorted.append(data[x+3]) title.append(''.join(sorted)) print title, module print sorted = [] x+=1 elif TITLE.match(data[x+1]) and NUM.match(data[x+2]): #Title counted.append(data[x+1]) sorted.append(data[x+1]) #Number counted.append(data[x+2]) sorted.append(data[x+2]) title.append(''.join(sorted)) print title, module print sorted = [] x+=1 else: print item, "strange1" break x+=1 else: if item in counted: x+=1 elif PDF.match(item): x+=1 elif TITLE.match(data[x]) and TITLE.match(data[x+1]) and NUM.match(data[x+2]): #Header header = data[x] counted.append(data[x]) sorted.append(data[x]) #Title counted.append(data[x+1]) sorted.append(data[x+1]) #Number counted.append(data[x+2]) sorted.append(data[x+2]) title.append(''.join(sorted)) sorted = [] print title, module print x+=1 elif TITLE.match(data[x]) and NUM.match(data[x+1]): #Title sorted.append(header) counted.append(data[x]) sorted.append(data[x]) #Number counted.append(data[x+1]) sorted.append(data[x+1]) title.append(''.join(sorted)) sorted = [] print title, module print x+=1 else: print item, "strange2" x+=1 break except IndexError: break From jgardner at jonathangardner.net Mon Mar 3 14:56:41 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 3 Mar 2008 11:56:41 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: <772d72a0-e641-4d4c-9ff0-77cffe831ae0@h11g2000prf.googlegroups.com> On Mar 2, 8:35?am, Michele Simionato wrote: > On Mar 2, 5:23 pm, js wrote: > > > Hi, > > > Have you ever seen Beautiful Python code? > > Zope? Django? Python standard lib? or else? > > > Please tell me what code you think it's stunning. > > The doctest module in the standard library. > > ?M.S. The first thing of beauty I found in Python (coming from C, C++, and perl) was the way Python handled variables, or as someone recently described them, names. Python's "for" statement is always beautiful to look at. Especially when someone uses the else clause rather than trying to detect if the list was exhausted. I sometimes avoid using the comprehensions just to get an excuse to write another for loop in Python. There can never be enough for loops written in Python! Also, Python's iterator interface is by far the most beautiful thing I have ever seen in the world of programming. Of course, the reason why the for loop is so beautiful is because iterators are so beautiful. From bjourne at gmail.com Tue Mar 4 10:55:27 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 4 Mar 2008 16:55:27 +0100 Subject: for-else In-Reply-To: References: Message-ID: <740c3aec0803040755o76f7096aud261b89043b26bcd@mail.gmail.com> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks wrote: > > for ...: > > ... > > exhausted: > > ... > > broken: > > ... > > > > The meaning is explicit. While "else" seems to mean little there. > > So I may like something similar for Python 3.x (or the removal of the > > "else"). > > > I would not be opposed to this on its own merits, but there is a > rationale behind the name "else". If you consider a for loop to be a > rolled-up if...elif...else statement (situations where this is > reasonable tend to be the same ones were else would be useful), then > the "else" clause would remain unchanged on the for loop. > > For instance, if you have a (trivial) if...elif...else like this: > > if a == 0: > do_task_0() > elif a == 1: > do_task_1() > elif a == 2: > do_task_2() > else: > do_default_task() > > You could roll it up into a for...else statement like this: > > for i in range(3): > if a == i: > do_task[a]() > else: > do_default_task() You forgot the break statement. The else suite will always be executed in this loop. Kind of proves bearophiles point, for-else is really tricky. -- mvh Bj?rn From frikker at gmail.com Thu Mar 6 14:47:46 2008 From: frikker at gmail.com (blaine) Date: Thu, 6 Mar 2008 11:47:46 -0800 (PST) Subject: Ncurses not found - embedded linux Message-ID: Hello Everyone! I am hoping that someone out there can help me out with this problem. We are using a gumstix platform to develop an embedded system. All that really matters is that it is an ARM processor running an embedded linux, details to follow. Gumstix has its own kernel tree that we cross compile for the system. We do have python, and it has all of the modules that I need except for one. I need ncurses (module curses). I can't seem to figure out how to get it to work - and the only documentation I can find is for Windows (because windows doesn't have ncurses). We have enabled ncurses support in the kernel menu, and that has not helped. I can't seem to trace down where we would 'enable' ncurses support? All other modules seem to work that I've tried (termios, sys, os, etc.) Output from python: [root at gumstix ~]# python , Feb 20 2008, 11:07:36) [GCC 4.1.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import curses Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/curses/__init__.py", line 15, in ? from _curses import * ImportError: No module named _curses [root at gumstix ~]# uname -a Linux gumstix 2.6.21gum #1 Tue Mar 4 15:31:07 EST 2008 armv5tel unknown [root at gumstix lib]# ls /usr/lib/*curses* /usr/lib/libcurses.a@ /usr/lib/libncurses.a /usr/lib/ libncurses.so@ [root at gumstix lib-dynload]# ls _* _bisect.so* _codecs_tw.so* _random.so* _codecs_cn.so* _csv.so* _socket.so* _codecs_hk.so* _heapq.so* _testcapi.so* _codecs_iso2022.so* _hotshot.so* _weakref.so* _codecs_jp.so* _locale.so* _codecs_kr.so* _multibytecodec.so* I hope this is trivial, and I apologize ahead of time if so. Would this perhaps be a compilation issue? Something we have to turn on in the python compile? Thank you, Blaine Booher University of Cincinnati From coolman.guron at gmail.com Mon Mar 24 10:01:42 2008 From: coolman.guron at gmail.com (binaryj) Date: Mon, 24 Mar 2008 07:01:42 -0700 (PDT) Subject: Serving another web site which requires authentication References: Message-ID: ur in luck i am an expert at this! tell me the details , site name etc you would have to proxy everything, basically the urls in the copied page have to be changed to point to ur site. its highly possible. a minor adjustment to ur urlconf and it will work. From pavlovevidence at gmail.com Thu Mar 6 11:00:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 08:00:58 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: On Mar 5, 8:07 pm, "D'Arcy J.M. Cain" wrote: > On Wed, 5 Mar 2008 14:00:17 -0800 (PST) > > Mike Driscoll wrote: > > What are you talking about? I didn't change the address at all. I'm > > not even sure what you mean. Are you talking about the post subject > > line (which I have never touched in any post)? If you're talking about > > the OP's email address, that's Google's fault for cropping them. > > I'm talking about castironpi. I find his posts a waste of my time "His" posts? Carl Banks From bcl at brianlane.com Sun Mar 23 11:53:35 2008 From: bcl at brianlane.com (Brian Lane) Date: Sun, 23 Mar 2008 08:53:35 -0700 Subject: Testing for an empty dictionary in Python In-Reply-To: <47e67a99$0$36364$742ec2ed@news.sonic.net> References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <47E67CFF.90507@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). > > John Nagle if dict: ... :) - -- - ---[Office 68.7F]--[Outside 42.9F]--[Server 100.4F]--[Coaster 68.0F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH5nz/Iftj/pcSws0RAnnMAJoDX9P0cK+RshuvuRRfkyJ4CPwqxACeMWkF pq7AKr/qzVWyVat0QiTtUfo= =bpei -----END PGP SIGNATURE----- From ricaraoz at gmail.com Sat Mar 1 21:17:45 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Mar 2008 23:17:45 -0300 Subject: SV: Where's GUI for Python? In-Reply-To: <62uai0F24sc4aU1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> Message-ID: <47CA0E49.2060502@bigfoot.com> K Viltersten wrote: >>> import tkininter >>> >> When that fails, try without the stutter >> >> import tkinter > > > I must be doing something wrong because > neither tkinter nor tkininter works. > I tried both with and without stuttering. > I even asked my wife to stutter some but, > sadly, to no avail. > > When Tim Chase mentioned "battery-installed", > i interpreted it as "all is there". It seems > that either > a) not all the batteries are installed in my > version (v2.5.2) > or > b) some setup/linkage needs to be performed > in order to get the GUI running. > > The error itself is: > ImportError: No module named tkinter > > Suggestions? > import Tkinter (first letter is uppercase) From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 04:45:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 08:45:20 -0000 Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <13umnl0ou29kn63@corp.supernews.com> On Thu, 27 Mar 2008 00:33:21 -0700, Grimsqueaker wrote: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? Given an iterator, you use it like this: for item in iterator: print item # or do something else If you're sure that the iterator is relatively small, you can do this: give_me_everything_at_once = list(iterator) but don't try that with this one: def ones(): # never-ending series of ones while True: yield 1 iterator = ones() -- Steven From gagsl-py2 at yahoo.com.ar Fri Mar 21 05:34:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 02:34:17 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: On 21 mar, 03:13, Godzilla wrote: > Just found out that win32api.GetTickCount() returns a tick count in > milli-second since XP started. Not sure whether that is reliable. > Anyone uses that for calculating elapsed time? I use GetTickCount on other languages because it's easy to call. Note that it returns a value in ms but the *precision* may be not so high. Anyway I think your problem is in the code, not on time.clock() -- Gabriel Genellina From Dodin.Roman at gmail.com Mon Mar 17 13:48:06 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 10:48:06 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> <9192affb-3a3f-4558-909b-d9734c1b1ad2@u10g2000prn.googlegroups.com> Message-ID: On 17 ???, 20:22, hellt wrote: > On 17 ???, 15:48, "Gabriel Genellina" wrote: > > > > > En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > > > > i have a problem with this modules py2exe + pywinauto + sendkeys used > > > together. > > > > In my script i'm using this expression > > > app.window_(title="SJphone").Edit.TypeKeys("Test is > > > running",with_spaces=True) > > > > TypeKeys is using SendKeys module i suppose. > > > Does it work as a normal script, without using py2exe? > > > > my setup.py looks like that: > > > > from distutils.core import setup > > > import py2exe > > > > setup( > > > options = {"py2exe": {"compressed": 1, > > > "optimize": 0, > > > "bundle_files": 1, > > > "packages": ["encodings", "pywinauto", > > > "pywinauto.controls", "pywinauto.tests"] } }, > > > zipfile = None, > > > console=["hosts.py"] > > > ) > > > Perhaps you have to include SendKeys explicitely. I think pywinauto > > doesn't require SendKeys, but uses it if already installed. > > > -- > > Gabriel Genellina > > pywinauto uses sendkeys when performs TypeKeys function. > when i include sendkeys to my package's list i have an error posted > below: > > "No module named SendKeys" ok.. all is ok. i have just reinstall sendkeys. From kyosohma at gmail.com Mon Mar 17 10:31:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 17 Mar 2008 07:31:03 -0700 (PDT) Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> Message-ID: <32bbf0e5-22ca-4b27-810d-919c4978c0f7@d4g2000prg.googlegroups.com> On Mar 17, 8:16 am, a... at pythoncraft.com (Aahz) wrote: > In article <873aqp6bbq.... at physik.rwth-aachen.de>, > Torsten Bronger wrote: > > > > >Carl Banks writes: > >> On Mar 16, 10:49 pm, Brian Jones wrote: > >>> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: > > >>>> If you did not like the programming this year (aside from the > >>>> sponsor talks) and you did not participate in organizing PyCon > >>>> or in delivering presentations, it is YOUR FAULT. PERIOD. > >>>> EXCLAMATION POINT! > > >>> I find this insulting, inexcusable, and utter nonsense. If > >>> putting the blame for a failed experiment on the backs of the > >>> good folks who paid good money for travel, lodging, and > >>> registration is also an experiment, you can hereby consider it > >>> also failed. > > >> He said "aside from the sponsor talks", chief. > > >I see no reason why the "fault" for parts of the rest being > >sub-optimal, too, must necessarily be on the attendee's side. (Just > >hypothetically; I wasn't at PyCon.) > > Let's suppose you have a group of friends who collectively throw a party. > They invite you to help out organizing it and putting it together, but > you choose not to. If you don't have a good time at the party because it > wasn't what you wanted, I think it's fair to say it was your fault. And > I think exactly the same thing is true for PyCon, albeit on a much larger > scale. > > It is absolutely critical to the long-term success of PyCon as a > volunteer-run community conference that each attendee take responsibility > for their experience. Science fiction fandom -- the part that holds > volunteer-run events such as Worldcon -- has lots of experience with this > model. It is one reason why such cons make a fuss about attendees being > "members", compared to "purchasing a ticket" (which is what you do for a > commercialized Star Trek con). > -- > Aahz (a... at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan You have a lot of good points, Aahz. I was thinking of the talks and such as a kind of seminar learning event, not a participatory community event. I went for two reasons: 1) To learn more Plone / Zope 2) To hang out with Python geeks The first one I didn't really get anywhere with, but I got lots of time with PyCon attendees, which was cool. I hope I can go next year, make new friends and maybe present some of my own stuff. Mike From stefan_ml at behnel.de Mon Mar 10 05:47:00 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 10:47:00 +0100 Subject: How to create Python object in C/C++ extension by class name? In-Reply-To: References: Message-ID: <47D50394.3060006@behnel.de> Neil.Fang.CN wrote: > I'm trying to write a C++ extension like this: > > //----------------------------------------------------------------------- > // C++ code > class ActorBase > {...}; > > // export ActorBase to Python as a new type > > class ActorManager > { > void addNewActor(const char* actorClassName) > { > ????? > } > } > > // export ActorManagerto Python as a new type > //----------------------------------------------------------------------- > > The question is how to implement ActorManger::addNewActor(), I want > the class name can be a Python class which inherits the C++ class > ActorBase? Have you considered writing your extension in Cython? http://cython.org/ It would allow you to use Python idioms for what you want to achieve. Stefan From mrmakent at cox.net Mon Mar 3 10:48:01 2008 From: mrmakent at cox.net (Mike Kent) Date: Mon, 3 Mar 2008 07:48:01 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Message-ID: > So my question is this - what is the easiest way to interface to this > "serial" device? > http://pyserial.sourceforge.net/ or perhaps http://pyusb.berlios.de/ From nico-NoSp at m-teknico.net.invalid Thu Mar 27 17:55:51 2008 From: nico-NoSp at m-teknico.net.invalid (Nicola Larosa) Date: Thu, 27 Mar 2008 22:55:51 +0100 Subject: Last Call for Papers for PyCon Italia Due Message-ID: <47ec17ea@extreme.x-privat.org> Only five days left to propose a paper to PyCon Italia Due , the second Italian Python conference. Also, booking is now open. Here are the next deadlines: Start of Early booking: March 25 End of Call for papers: April 1 Start of Late booking: April 23 End of booking: May 3 For a short while we are still accepting papers for PyCon Italia Due, the second edition of the Italian Python conference. This year the conference will be held from May 9th to 11th in Florence, Italy. The first day of the conference (9th May) will start at Palazzo Vecchio in the afternoon with an opening keynote by Richard Stallman. The next days the conference will instead be at the Viva Hotel Laurus near the Duomo. Call for papers =================================================== Papers ~~~~~~ The conference is structured on three parallel tracks: Discovering Python, Spreading Python and Learning Python. * Discovering Python will primarily focus on introductory topics about Python libraries, framework and technologies; * Spreading Python will focus both on advanced technical topics and parallel arguments like development methodologies, real-world use cases and management techniques; * Learning Python will feature a continuous interaction between the speaker and the audience: the speaker will propose a topic and introduce a possible solution, then the talk will dynamically evolve, naturally following questions and notes from the audience. Talks could focus on the following topics (the list is neither exclusive nor exaustive): * large and/or distributed applications written in Python; * scientific and computationally intensive applications; * interaction with other languages/environments, RPC, services; * web programming and frameworks; * desktop programming and GUI toolkits; * Python as "scripting" language (system housekeeping, COM, etc...); * Python and databases; * Python as an educational language. Talks will be screened on contents, relevance for Python community and overall quality. Each talk will have one of the following duration: 30', 60' or 90'. Please specify which length best fits your contents. This timeframe also includes question time, and enough leeway for the audience to enter and leave the room. The talk must be given in either English or Italian language. For native English speaker, please consider that you will probably need to speak a little slower than usual, for better comprehension by the audience, so the talk may come out longer than you expect. See also the note at the end of this paper. How to submit a paper ~~~~~~~~~~~~~~~~~~~~~ Your talk proposal must be submitted online through Assopy[1]. You will need to enter some biographic notes about the speaker, and an abstract of the talk (a couple of paragraphs). If your talk is accepted ~~~~~~~~~~~~~~~~~~~~~~~~ Once your talk proposal is approved, you have to submit your paper before the conference opening day. Each paper must be original work. We cannot accept papers containing material copyrighted by others. Papers should be in plain text, HTML (single page please), PostScript or PDF. Please use a standard format, viewable and printable on all major systems. The files must be submitted within Assopy[1]. A note for non-Italian speakers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We warmly welcome and encourage the presence of non-Italian speakers at PyCon Italia. However, most talks will be in Italian language. We will probably provide Italian-to-English realtime translation for our guests, and also English-to-Italian realtime translation for that part of the audience which is not much familiar with English. [1]: -- Nicola Larosa - http://www.tekNico.net/ From patty206 at charter.net Thu Mar 13 19:21:58 2008 From: patty206 at charter.net (Patty Sutcliffe) Date: Thu, 13 Mar 2008 18:21:58 -0500 Subject: sorting question Message-ID: The website you list regarding 9-letter scrambled words doesn't exist any longer. Is there another way that I can access it to see your program you designed? I have a nine letter work I need to unscramble. I will send it just in case you can figure it out for me and let me know. KAEOSYBRD I'm not very good at that sort of thing, but would love to know the answer to this one. Thank you, Patty patty206 at charter.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Mon Mar 17 10:44:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 Mar 2008 07:44:05 -0700 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> <87fxup4goi.fsf@physik.rwth-aachen.de> Message-ID: In article <87fxup4goi.fsf at physik.rwth-aachen.de>, Torsten Bronger wrote: >Aahz writes: >> In article <873aqp6bbq.fsf at physik.rwth-aachen.de>, >> Torsten Bronger wrote: >>> >>> I see no reason why the "fault" for parts of the rest being >>> sub-optimal, too, must necessarily be on the attendee's side. (Just >>> hypothetically; I wasn't at PyCon.) >> >> Let's suppose you have a group of friends who collectively throw a >> party. They invite you to help out organizing it and putting it >> together, but you choose not to. If you don't have a good time at >> the party because it wasn't what you wanted, I think it's fair to say >> it was your fault. And I think exactly the same thing is true for >> PyCon, albeit on a much larger scale. > >Fair enough. But then I question the sensibility in saying "it is XY's >fault" at all. > >Somebody not involved in organising was not happy with the Con. You >may take the criticism or leave it. The criticism may be justified or >not. But saying that it is "his fault" is useless in my opinion, it >even discourages feedback. It think it's okay to evaluate something >that you didn't help coming into existence. A good point is a good >point no matter who makes it. Two things: * There's a reason why I labelled it a "rant" ;-) * You may be misunderstanding the distinction between "fault" and "blame". When there is fault, it is a person's responsibility to correct it. Blame, OTOH, is about responsibility that *should* have been taken. We're not telling people that they should volunteer to run PyCon (although the vast majority of people who help run events like this end up enjoying them more than people who just show up). But anyone who complains and doesn't volunteer is at fault -- the only recourse likely to produce results is to change their volunteer status. As I said, feedback is welcome. Those of us who volunteer do so because we care about the Python community and want to put on a successful event for everyone. But we can rarely make commitments to change anything unless people step up to fix them. It's really no different from the people who show up here on c.l.py to complain about Python: the answer inevitably boils down to "write a patch!" -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From ericofam at yahoo.com Sat Mar 8 22:19:20 2008 From: ericofam at yahoo.com (olusina eric) Date: Sat, 8 Mar 2008 19:19:20 -0800 (PST) Subject: Green's Function Message-ID: <991274.80799.qm@web53607.mail.re2.yahoo.com> I did search for "Python Green's function" and no reasonable hit. I also searched on scipy with no result. Thanks EOF olusina eric wrote: Hi All, I am new to Python and trying to solve the Hamiltonian of a linear chain of atoms using green?s function. Does anyone know any pre-existing library functions and literature that could be helpful? Thanks EOF --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. --------------------------------- Never miss a thing. Make Yahoo your homepage. -------------- next part -------------- An HTML attachment was scrubbed... URL: From morse at edoug.org Tue Mar 11 23:05:07 2008 From: morse at edoug.org (Doug Morse) Date: Wed, 12 Mar 2008 03:05:07 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe Message-ID: Hi, I have an application that runs just fine using the standard Python distro interpreter (v2.5.1 on WinXP) but throws the following exception when run as an executable built with py2exe. My questions are: (a) does anyone have any thoughts on why this exception is occurring and what to do about it, and (b) more generally, why would a problem like this occur under py2exe but not with the standard distro? Thanks in adavance for any and all help. Cheers, Doug Traceback (most recent call last): File "VisionTrainer.py", line 49, in File "SessionController.pyc", line 53, in File "VisionEgg\__init__.pyc", line 42, in File "VisionEgg\ParameterTypes.pyc", line 28, in File "Numeric.pyc", line 93, in File "Precision.pyc", line 26, in File "Precision.pyc", line 23, in _fill_table File "Precision.pyc", line 18, in _get_precisions TypeError: data type not understood From deets at nospam.web.de Wed Mar 19 04:52:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 09:52:45 +0100 Subject: is hash map data structure available in Python? In-Reply-To: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Message-ID: <64c2j2F2b3qg7U1@mid.uni-berlin.de> grbgooglefan schrieb: > Hi, > I have a situation that I need to search a name in a big list of names > in my Python embedded interpreter. I am planning to use hash map for > quicker search. > How do I create hash map in Python? > Can you please guide me to some documentation or tutorial which > provides information on creating, editing, searching through hash map > in Python? http://docs.python.org/tut/node7.html#SECTION007500000000000000000 Diez From stargaming at gmail.com Mon Mar 17 01:54:42 2008 From: stargaming at gmail.com (Stargaming) Date: 17 Mar 2008 05:54:42 GMT Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <47de07a2$0$2699$9b622d9e@news.freenet.de> On Sun, 16 Mar 2008 20:54:01 -0700, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece of > python code works. If your Python code is well-written, it should be easy figuring out what it means by just reading it. For more complex programs, of course, this method can fail. > With C I often find it very useful to be able to run > the code in step mode and set breakpoints in a debugger so I can watch > how the it executes, how the data change and how the code jumps from one > function to another. But with Python, the debugger is a little > primitive. The default IDLE doesn't even allow me to set a breakpoint. > When the code is long, I am often lost in it. IDLE is just, well, a batteries-included editor. There are many people (me included) who do *not* like it because it's so weak and doesn't have any real uses cases if your programs get sufficiently complex (because IDLE itself is sufficiently primitive). You might be interested in *real* debuggers, such as the Python Debugger `PDB `_. If you don't find its usage obvious, a quick google search just turned up a nice `tutorial `_. You might find the `Python Profilers `_ particularly interesting, `profile` for finding out which function sucks up the most calls/time, `trace` for more sophisticated stuff. `pythontracer ` sounds like a good combination of both. > So I'm curious how to read code effectively. I agree that python code is > clear, but when it becomes long, reading it can still be a hard work. A common practice is just inserting `print` statements since it's so easy. If you think your debugging isn't temporary but could be useful and will be enabled every now and then, you could also use the `logging module `_ with the ``DEBUG`` level. There was a blog post recently about how to do this `generically for functions `_. > BTW. I think this problem also exists in other script languages. FWIW, I think it's particularly easier in scripting languages to implement all kinds of tracing (apart from debugging, which is rather unpopular in Python) because you have one *extra* level (the interpreter) between your machine and your code. HTH, Stargaming From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 17:04:36 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 23:04:36 +0100 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c93bb8$0$874$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> Message-ID: <47c9d79e$0$859$ba4acef3@news.orange.fr> Hi! Problem solved, after reset layouts. Thanks, all! Michel Claveau From xu.mathena at gmail.com Mon Mar 24 00:24:03 2008 From: xu.mathena at gmail.com (NotGuru) Date: Sun, 23 Mar 2008 21:24:03 -0700 (PDT) Subject: PyTuple_Check and other type check functions didn't check the NULL pointer References: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> Message-ID: <69a00306-8dd3-4918-85cb-60157130d0da@c65g2000hsa.googlegroups.com> On Mar 23, 8:24?pm, Christian Heimes wrote: > NotGuru schrieb: > > > My questions is: is it necessary to check the null pointer in the > > macro or it's a job for the user? Semantically all the type check > > should report a false if a null pointer is encountered. I've already > > had the patch to this issue but I am not sure if I think this problem > > right. ?I don't know if there are some python core developers around > > but I would like to hear all opinions towards this. > > Unless stated otherwise no Py* or PY* function is NULL safe. You have to > check for NULL unless the docs *explicitly* say it's safe to call it > with a NULL argument. > > Christian Thank you Christian and John, I skipped Section 1.3 of that document, so shameful. ;) From george.sakkis at gmail.com Fri Mar 7 22:43:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 7 Mar 2008 19:43:48 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: On Mar 7, 11:12 am, alex.pedwyso... at gmail.com wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... > > I want to be able to detect if they fail with error, I want to be able > to time them, and I want to be able to stop them if they run too > long. I cannot add code to the eval'd strings that will help me > accomplish this. > > Is there a good way to do this? I have it figured out for perl > but I'd rather use python if possible. > > Thanks for any assistance. Check out these two recipes: - Using signals: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 - Using threads: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752 Note that neither is perfect; the first breaks if the timed code overrides the alarm signal, while the second can't interrupt code that doesn't release the GIL and doesn't actually kill the function after the timeout. I'd be rather surprised if the perl solution you figured out doesn't have any issues. George From jeff at schwabcenter.com Sun Mar 16 17:48:44 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 16 Mar 2008 14:48:44 -0700 Subject: Types, Cython, program readability In-Reply-To: <87abky1i6i.fsf@benfinney.id.au> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> <87abky1i6i.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > sturlamolden writes: > >> If you don't know how to install a C compiler like Microsoft Visual >> Studio, you should not be programming computers anyway. > > Utter elitist nonsense. > > Programming should be made easier, and I see Python as a very good > language for making programming easier. Lowering the barrier for > prospective hackers to get into programming is a good thing. The > installation of a C compiler is incidental to that, and has no > necessary connection with programming. > > Placing meaningless roadblocks, as you suggest should be done, is > anathema to education. Hear, hear! I continue to be shocked when an OS doesn't come with a compiler for the language in which the OS is written. It seems like one of the most basic things that should just be there, along with some kind of command shell (be it CLI or graphical), and ideally a well-defined scripting interface that is easily extensible from the "core" language. Nowadays, scripts are often intended to work on multiple different platforms; various scripting languages therefore list portability among their most valuable features. One issue from which most of them suffer is that they really are not suitable for systems programming. As scripts evolve into applications, native-language compilers end up being necessary, after all, such that portability of non-trivial programs is severely limited. (It's not really the languages' fault. After all, they were only really meant to enable portable scripting.) Python, I think, helps improve the situation with specific support for applications programming. Unlike Perl or Tcl, Python is not just a scripting language with a set of ad-hoc extensions. There are still issues, and Python probably will never be a general-purpose replacement for system-native language compilers, but it does enable a smooth ramp from "just a user," through "a user who does some scripting," to "application developer." I am of the opinion that the more regular users write and share code, the faster we will see improvement in overall software quality, and the more pleasant the world will be for all of us to live in. See also: http://cm.bell-labs.com/cm/cs/upe/ http://www.linfo.org/unix_philosophy.html From zerty.david at gmail.com Sun Mar 30 16:03:52 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:03:52 -0300 Subject: Error Raised But dont know what it means Message-ID: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> Well, I'm dealing with files in Pickle, I'm saving at the file a List of Objects from the same Class, When I try to retrive this information and try to iterate over them this error is raised: TypeError: 'instancemethod' object is not iterable But if I just print the method I get the 'real thing' what's the problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fred.sells at adventistcare.org Tue Mar 25 23:19:06 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 25 Mar 2008 23:19:06 -0400 Subject: Can I run a python program from within emacs? In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B0895@acesxch01.ADVENTISTCORP.NET> I use a .emacs file (attached) that some associates gave me nearly 20 years ago. Some of it is OBE now, but it still works for me on both windows and Linux. With this file I can cntrl-c cntrl-c (i.e. ^c twice to run the current buffer). Don't ask me to explain it, it just works. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Jeff Schwab > Sent: Thursday, March 20, 2008 11:29 AM > To: python-list at python.org > Subject: Re: Can I run a python program from within emacs? > > > Grant Edwards wrote: > > On 2008-03-20, jmDesktop wrote: > > > >> Hi, I'm trying to learn Python. I using Aquamac an emac > >> implementation with mac os x. I have a program. If I go to the > >> command prompt and type pythong myprog.py, it works. Can > the program > >> be run from within the editor or is that not how > development is done? > >> I ask because I was using Visual Studio with C# and, if you're > >> familiar, you just hit run and it works. On Python do I use the > >> editor for editing only and then run the program from the command > >> line? > > > > http://www.google.com/search?q=emacs+python > > Or achieve a similar (more flexible (IMO), but less smoothly > integrated) > effect with Vim and GNU Screen. Until recently, you had to > patch Screen > if you wanted vertical splits, but now it's in the main line. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: .emacs Type: application/octet-stream Size: 3635 bytes Desc: .emacs URL: From sgeiger at ncee.net Fri Mar 14 12:46:17 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 14 Mar 2008 11:46:17 -0500 Subject: Monitoring SSHd and web servers? In-Reply-To: <36a2338f-60fd-456d-a906-716bb52e8122@s8g2000prg.googlegroups.com> References: <36a2338f-60fd-456d-a906-716bb52e8122@s8g2000prg.googlegroups.com> Message-ID: <47DAABD9.7010300@ncee.net> I would recommend using a tried-and-true solution for making sure your uptime of various services is maximized (if that's what your goal is). Running a local "daemon-monitoring daemon" is one option--monit does a good job. Checking services over the network, as nagios does well, is another solution. Jonathan Gardner wrote: > On Mar 13, 11:32 pm, Gilles Ganault wrote: > >> I'd like to monitor connections to a remote SSH and web server. Does >> someone have some code handy that would try to connect every 5mn, and >> print an error if the script can't connect? >> > > from time import sleep > while True: > # Try to connect. May want to spawn a subprocess running a simple > shell script > # Handle success / failure appropriately > sleep 5*60 # Sleep for 5 minutes > > What you monitor is up to you. At a basic level, you can see if the > server is accepting connections. At a higher level, see if you can get > a page or see if you can login as a specific person. At a higher > level, you may want to check what is on the page or what happens when > you log in. It's all up to you. > > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From gagsl-py2 at yahoo.com.ar Tue Mar 4 21:39:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 00:39:03 -0200 Subject: multiplication of lists of strings References: Message-ID: En Tue, 04 Mar 2008 23:50:49 -0200, Jason escribi?: > How could I return a list or tuple of each unique combination of a given > set of lists (perhaps from a dict or a list). This means the number of > lists are not known nor is the length of each. Use the Google interfase for this group: http://groups.google.com/group/comp.lang.python/ Type "unique combinations lists" in the text box; press "Search in this group". The very first result contains some answers to your question. -- Gabriel Genellina From rhh2109 at columbia.edu Sat Mar 1 17:29:13 2008 From: rhh2109 at columbia.edu (Roy H. Han) Date: Sat, 1 Mar 2008 17:29:13 -0500 Subject: Where's GUI for Python? In-Reply-To: <47C9D33E.9040407@tim.thechases.com> References: <62tvhmF256jk7U1@mid.individual.net> <47C9D33E.9040407@tim.thechases.com> Message-ID: <6a5569ec0803011429q4444ec25o7c235ae80590dff8@mail.gmail.com> Konrad, I use wxPython with wxGlade. I love wxGlade! wxGlade http://wxglade.sourceforge.net/ You need to look at this documentation to code event handling. wxWidgets http://www.wxwidgets.org/manuals/stable/wx_classesbycat.html You can also try coding the GUI manually, but it is much easier to use wxGlade. wxPython http://wiki.wxpython.org/AnotherTutorial Roy On Sat, Mar 1, 2008 at 5:05 PM, Tim Chase wrote: > > I'm certain there is an API for creating > > GUI's but as far i can find it in the > > http://docs.python.org/tut/tut.html > > the only "gui" is in "Guido". > > > > What do i miss? > > > The batteries-included GUI: > > import tkininter > > Add-on solutions include wxPython, PythonCard and many others. GIYF: > > http://google.com/search?q=python+gui > > -tkc > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mdonle at gmail.com Wed Mar 12 09:25:05 2008 From: Mdonle at gmail.com (Mdonle at gmail.com) Date: Wed, 12 Mar 2008 06:25:05 -0700 (PDT) Subject: a Roguelike in Python Message-ID: Seeing the 7DRL start up recently, i wanted to see what one was made of. Python is the language i'm most familiar with so i searched for some code to look at, but i couldn't find any. Can anyone direct me to the right place? I did some searching on what it would take to write a roguelike in python and it looked like the curses module would work perfectly, but it looks to me like it doesn't work in windows? I tried to import it and it says 'No Module named _curses' Sorry if all this sounds a bit noobish, it's only cause i am. From castironpi at gmail.com Mon Mar 24 11:06:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 24 Mar 2008 08:06:01 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> Message-ID: <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> On Mar 24, 9:48?am, Jason wrote: > On Mar 24, 5:21 am, Julien wrote: > > > > > > > Hello all, > > > I would like to do something like: > > > def called(arg) > > ? ? if arg==True: > > ? ? ? ? !!magic!!caller.return 1 > > > def caller(arg) > > ? ? called(arg) > > ? ? return 2 > > > Here, the fake !!!magic!!! represents a statement (which I ignore) > > that would make the caller function return a value different from what > > it'd return normally. > > > For example, caller(True) would return 1, and caller(False) would > > return 2. The reason I want that is because I don't want the caller > > function to know what's going on in the called function, and be > > shortcut if the called function think it's necessary. > > > Would you know if that's possible, and if so, how? > > > I've done a bit of research and I think I've found some good pointers, > > in particular using the 'inspect' library: > > > import inspect > > > def called(arg) > > ? ? if arg==True: > > ? ? ? ? caller_frame = inspect.stack()[1] > > ? ? ? ? ... > > > Here 'caller_frame' contains the frame of the caller function. Now, > > how can I make that frame return a particular value? > > > By the way, I'm not really interested in 'called' throwing an > > exception and 'caller' catching it. In fact, I want things to remain > > completely transparent for 'caller'. > > > Hope that was clear... :/ > > > Thanks! > > > Julien > > As Steven wrote, it's not very clear. ?If we knew the intent of this, > we could perhaps point you to a more useful, maintainable technique. > We don't know why you're trying to circumvent the programming language > in this case. ?Any solution that works as you described will probably > be unportable between the different Pythons (CPython, Jython, > IronPython, etc). > > Please note that the following code should work, but I've only run it > through the interpreter in my brain. ?My brain's interpreter is full > of Heisenbugs, so you may need to adjust a few things. ?Here's my > thoughts: > > Given: > ? ? def First( arg ): > ? ? ? ? Second( arg ) > ? ? ? ? return 5 > > 1) ?If you can modify both functions, change the first function to > return a value in certain circumstances: > ? ? def AltFirst( arg ): > ? ? ? ? value = Second( arg ) > ? ? ? ? if value is not None: ?return value > ? ? ? ? return 5 > > 2) ?Raise an exception in Second, and catch that exception above > First: > > class SecondExcept(Exception): > ? ? def __init__(self, value): > ? ? ? ? Exception.__init__(self, 'Spam!') > ? ? ? ? self.value = value > > def Second(arg): > ? ? if arg == my_conditional_value: > ? ? ? ? raise SecondExcept( 5 ) > > # The following could even be put in your own function, > # or in a wrapper or decorator for the First function. > try: > ? ? myvalue = First( 'Vikings!' ) > except SecondExcept, exc: > ? ? myvalue = exc.value > > When you need to use an exceptional pathway, use an exception. ?They > aren't just for reporting errors. Exceptions are a control tool. There was a 'goto using Exceptions' once in the manuals. I don't see a problem with a local control-flow object. It would appease a number of requests I've read. for x: for y: control.break( 2 ) if a: if b: control.fail( 2 ) so no need to reduplicate: else: thing() else: thing() if a: if b: control.mostrecenttest( 0 ) def f(): def g(): control.return( 2 )( "early" ) Something tells me generators could solve the problem, but I may be enamored, so it's a separate post. From gagsl-py2 at yahoo.com.ar Sun Mar 30 14:59:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 15:59:27 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 11:10:20 -0300, MRAB escribi?: > On Mar 30, 6:35 am, "Gabriel Genellina" > wrote: >> En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: >> >> > BTW, my opinion is that it's already time that programmer editors >> > have input methods advanced enough for generating this: >> >> > if x ? 0: >> > ?y ? s: >> > if y ? 0: f1(y) >> > else: f2(y) >> >> Fine if you have the right keyboard... Try to write APL with a standard >> keyboard :) >> > There was a version of APL for the Sinclair QL which replaced the > standard APL symbols with keywords. Wow, APL on 8 bits? Now there is (or perhaps there was) J, a reincarnation of APL by Iverson himself that uses ASCII characters only. -- Gabriel Genellina From tim.arnold at sas.com Thu Mar 27 12:39:15 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 27 Mar 2008 12:39:15 -0400 Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Message-ID: "Miki" wrote in message news:34ba46bf-8389-43e1-9c04-92732203a1ce at h11g2000prf.googlegroups.com... > Hello Tim, >> >> Any ideas on a simple interface for this? >> > How about something like: > > Chapter 1 (001-200 200) > Chapter 2 (200-300 100) > ------ 001-300 300 ---- > Chapter 3 (300-450 150) > Chapter 4 (450-500 50) > ------ 300-450 250 ---- > Chapter 5 (500-600 100) > ------ 500-600 100 ---- > > Where the user can move the divider up and down to create new volume, > they can also add and delete dividers. > > The program will not allow to drag the divider above the 600 page > limit. > > HTH, > -- > Miki > http://pythonwise.blogspot.com Hi Miki, that looks nice, simple, and intuitive. thanks for thinking about it. Now to dive into some gui coding! thanks, --Tim From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 09:52:41 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 15:52:41 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: <5c0bab72-8dd2-4be9-a832-168a32d99585@8g2000hse.googlegroups.com> References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <5c0bab72-8dd2-4be9-a832-168a32d99585@8g2000hse.googlegroups.com> Message-ID: <47d00526$0$301$426a74cc@news.free.fr> Jeffrey Seifried a ?crit : (snip) > if type(a)==type({}): > print 'a is a dictionary' This instanciates a dict, call type() on it, and discard the dict - which is useless since the dict type is a builtin. Also, when you want to test identity, use an identity test. if type(a) is dict: print "blah blah blah" From paul at boddie.org.uk Mon Mar 3 05:52:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 3 Mar 2008 02:52:44 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: <524be122-1eee-40fd-a521-8d02de5e86b2@m34g2000hsc.googlegroups.com> On 2 Mar, 10:02, Kay Schluehr wrote: > On 2 Mrz., 06:53, Ben Finney > wrote: > > > One of the stated goals of the migration is that the '2to3' program > > will only migrate Python 2.6 code -> Python 3.0 code. > > Yes, I know. Why? > > "The master said so" isn't an entirely satisfying answer. What are the > *technical reasons* that make it hard to apply '2to3' directly on > Python 2.4 or Python 2.5? I imagine that in Python 2.6 there are some semantic changes (conveniences, really), plus some expansion of the language syntax to overlap with Python 3, both of which let the 2to3 tool work as intended. Obviously 2to3 doesn't do too much complicated stuff, and I imagine (or have deduced from what I've heard) that you have to write code that is "obvious" to the tool so that it can translate it correctly. Perhaps 2.5 and earlier don't permit such obvious code to be written. Paul From mail at timgolden.me.uk Mon Mar 17 05:14:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 17 Mar 2008 09:14:30 +0000 Subject: Types, Cython, program readability In-Reply-To: <00be01c88779$0a40ca70$0200a8c0@TMSMAIN> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <47DD33D7.2020300@timgolden.me.uk> <00be01c88779$0a40ca70$0200a8c0@TMSMAIN> Message-ID: <47DE3676.1010201@timgolden.me.uk> Tom Stambaugh wrote: >> I'm not entirely sure why you think Pyrex should "contain a compiler". >> It certainly works well enough with the free [beer] MS VS 2008 Express >> and I'm fairly sure it's fine with MingW. Both of those are readily >> available and I don't imagine anyone who's going to use Pyrex / Cython / >> ShedSkin is going to baulk at downloading a compiler set :) > > Anything like this is a lot more attractive to me if I can download and > install a binary without *needing* a compiler. Most of the time, I just want > something to run -- I don't want to risk diving in compiler-hell if I can > avoid it. It isn't downloading the compiler set that worries me, it's that I > almost never even want to think about it. I certainly sympathise with the compiler-hell syndrome here: the subject of compiling Python itself and its extensions under Windows has long been a source of questions and qualified answers on the Python lists. This cuts both ways: Python itself is effectively only buildable with the MS tools [1] (notwithstanding some valiant efforts to provide patchsets so that it builds under MingW [2]). On the other hand, some useful libraries, say ffmpeg, only *won't* build with the MS tools[3]. Both sides of that debate have a valid position, but it doesn't ultimately help the developers. Which is probably why avbin/pyglet[4] took the decoupled route and used ctypes to join the two together! In the case of a general extension (like simpleJSON or PIL etc.) I'm usually just after a binary. In the case of Pyrex, though, the Pyrex code *itself* is pure Python; it's the code it generates which is C -- one step further away. Granted, it might be possible to produce some sort of bundle which shipped a MingW-based extension along with the Pyrex release bundle, but my own philosophy is that, if you've got to the point of using Pyrex then downloading a compiler isn't going to be too much work. It's clear, though, from the posts in this thread, that other people don't necessarily agree. Admittedly I have the advantage of being a professional programmer who is therefore bound to know what a compiler *is*! TJG [1] http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-04/msg03627.html [2] http://jove.prohosting.com/iwave/ipython/pyMinGW.html [3] http://ffmpeg.mplayerhq.hu/faq.html#SEC36 [4] http://code.google.com/p/avbin/ From emailamit at gmail.com Mon Mar 31 13:26:51 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 10:26:51 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> On Mar 31, 10:23 am, xkenneth wrote: > > class A: > def __eq__(self,other): > return self.a == other.a and self.b == other.b > > class B: > def __eq__(self,other): > return self.a == other.a and self.c == other.c > > Thanks! > > Regards, > Kenneth Miller Can't say aboyt unpythonic: I am no expert at that: but to avoid catching Attribute-Error everywhere, you can redefine __eq__ as def __eq__(self, other) : try : return <> except AttributeError: return False From gagsl-py2 at yahoo.com.ar Mon Mar 24 14:56:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 15:56:24 -0300 Subject: behavior varied between empty string '' and empty list [] References: <1d822b31-fd7a-47f2-abee-45226c6b0c26@e6g2000prf.googlegroups.com> Message-ID: En Mon, 24 Mar 2008 15:22:43 -0300, Tzury Bar Yochay escribi?: > while I can invoke methods of empty string '' right in typing > (''.join(), etc.) I can't do the same with empty list > > example: > >>>> a = [1,2,3] >>>> b = [].extend(a) >>>> b >>>> b = [] >>>> b.extend(a) >>>> b > [1,2,3] extend() -like most mutating methods- does not return the list, it returns None. Your empty list grow the 3 additional items, but since there were no additional references to it, got destroyed. > I would not use b = a since I don't want changes on 'b' to apply on > 'a' Try with b = list(a) > do you think this should be available on lists to invoke method > directly? You already can. Your example is misleading because you used b with two meanings. (Compare the *usage* of each variable/value, not their names). This is equivalent to the second part of your example: py> a = [1,2,3] py> b = [] py> b.extend(a) py> b [1, 2, 3] and this is the first part: py> a = [1,2,3] py> b = [] py> c = b.extend(a) py> c py> b [1, 2, 3] except that in your original example, the empty list had no name so you cannot see how it changed. -- Gabriel Genellina From chris at wonderstore.com Mon Mar 31 18:02:32 2008 From: chris at wonderstore.com (wrightee) Date: Mon, 31 Mar 2008 15:02:32 -0700 (PDT) Subject: PyQT / QDate / QTableWidget References: Message-ID: <216d8145-4ce2-47ee-9dfd-a789d77ec2a2@e6g2000prf.googlegroups.com> That worked! Thank you; I had given up on QDate but changing the format worked perfectly. From castironpi at gmail.com Mon Mar 17 08:15:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 05:15:28 -0700 (PDT) Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> Message-ID: <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> On Mar 17, 3:28?am, Paul Rubin wrote: > Larry writes: > > My data is a = [23, 45, 56, 255]. > > My desire output is: 234556255, of course in binary file > > representation already. > > > I tried to make one using write after pack method of struct module, > > but because of spaces I got incorrect results. > > struct.pack works for me: > > ? ? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > ? ? >>> import struct, os > ? ? >>> x = struct.pack('BBBB', 23, 45, 56, 255) > ? ? >>> len(x) > ? ? 4 > ? ? >>> f = open('/tmp/foo','w'); f.write(x); f.close() > ? ? >>> os.system("ls -l /tmp/foo") > ? ? -rw------- 1 phr phr 4 Mar 17 01:27 /tmp/foo > ? ? >>> > > You could also do the list-string conversion with the array module. Python 3.0a2 (r30a2:59405M, Dec 7 2007, 15:23:28) [MSC v.1500 32 bit (Intel)] o n win32 Type "help", "copyright", "credits" or "license" for more information. >>> bytes( [ 23, 45, 56, 255 ] ) b'\x17-8\xff' >>> a= _ >>> f= open('temp.x','wb') >>> f.write( a ) 4 >>> f= open('temp.x','rb') >>> f.read() b'\x17-8\xff' From jeff at schwabcenter.com Mon Mar 17 11:26:38 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 08:26:38 -0700 Subject: String To List In-Reply-To: References: Message-ID: Girish wrote: > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? Do you want: (1) Specifically to vivify lists formatted as in your example? If so, why? (2) To save and restore arbitrary python objects? (3) To define some kind of configuration file format that you can read from Python? From Lie.1296 at gmail.com Sun Mar 23 13:43:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 23 Mar 2008 10:43:59 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> <128011dd-a1a8-43af-bdea-beba452aa596@f63g2000hsf.googlegroups.com> Message-ID: <4db3e139-3da4-4d77-a4d7-b5304cc9a28b@s12g2000prg.googlegroups.com> On Mar 22, 1:11?am, MRAB wrote: > On Mar 21, 11:48 am, fkallgren wrote:> Hi. > > > I have a little problem. I have a script that is in the scheduler > > (win32). But every now and then I update this script and I dont want > > to go to every computer and update it. So now I want the program to 1) > > check for new version of the script, 2) if there is a new version, > > copy that verision from server to local drive, 3) shutdown the program > > and start it up again as the new version. > > > The problem is that I can't run this script directly from server so it > > have to run it locally. > > > Anyone having any bright ideas?? > > The script could just check to see if the version on the server is > more recent and if it is then copy it over the local one, start the > local one, and then quit. > > Python compiles the script to bytecode and then interprets the > bytecode, so when the script is being run the .py or .pyw source > itself isn't being used and can be overwritten. I've tried the > following on Windows XP and it works: > > (snip) Even if the .py and .pyw is being locked, you could always use a helper script that calls the main program if there is no update. This way, the main program is never called directly, only by the updater script. Such implementation is trivial. # updater script # when you're running your program, you # call this script instead of the real # main program if needupdate(): update() else: callmainprogram() # main program # this script should never be called # directly, only by the updater program # (well, except perhaps on development stage) def checkupdate(): if needupate(): callupdatescript() terminateself() # possibly saving state, etc From steven.p.clark at gmail.com Mon Mar 17 23:57:14 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Mon, 17 Mar 2008 23:57:14 -0400 Subject: ord function problem from newbie In-Reply-To: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> References: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> Message-ID: <663744510803172057x78d07300u955e3c71ed9e416b@mail.gmail.com> print sum([ord(ch)-96 for ch in small]) On Mon, Mar 17, 2008 at 11:28 PM, wrote: > I'm trying to convert a name into a numerical value that is not > consistent with ANSCII values. In my case, I convert all to lowercase, > then try to sum the value of the letters entered by the user, can't > get it to add them. Here is what I have. By the way, the values I need > to use is: a=1, b=2, c=3, etc... I'm trying to subtract 96 from the > ANSCII value, then total. > > import string > def main(): > print "This program calculates the numeric value of a name with > which" > print "you could look up online as to what that value represents." > print > # Get name to calculate > name = raw_input("Please type a name: ") > small = string.lower(name) > print "Here is the calculated value:" > > print small > for ch in small: > v = ord(ch)-96 > print v > > > main() > > Looks like this: > This program calculates the numeric value of a name with which > you could look up online as to what that value represents. > > Please type a name: David > Here is the calculated value: > david > 4 > 1 > 22 > 9 > 4 > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sat Mar 29 07:08:16 2008 From: http (Paul Rubin) Date: 29 Mar 2008 04:08:16 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <7xhcepeqjj.fsf@ruckus.brouhaha.com> kwitters at telenet.be writes: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? I doubt anyone cares. Python probably chose != because it's what C uses. The scary choice is /= which can be interpreted as an assignment. Python lacks assignment expressions partly because of a meme that using = instead of == by accident is a common C bug. I'm sure it happens but at least in my own experience (from having written plenty of buggy C code over the years) it's not that frequent. Using /= instead of != seems more likely, for programmers who switch between C and languages that use /= for nonequality. From castironpi at gmail.com Sun Mar 16 04:28:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 01:28:02 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: On Mar 16, 1:43?am, Erik Max Francis wrote: > castiro... at gmail.com wrote: > > 'join' in the wrong word for the method in class Thread. > > That's the standard term in threading. ?If it's not familiar to you, > well, bummer, but there's not much more that can be done about that than > for you to read the literature. Do you agree that it's inconsistent? From poof65 at gmail.com Sat Mar 8 11:32:47 2008 From: poof65 at gmail.com (poof65) Date: Sat, 8 Mar 2008 17:32:47 +0100 Subject: parralel downloads In-Reply-To: References: Message-ID: For your problem you have to use threads. You can have more information here. http://artfulcode.nfshost.com/files/multi-threading-in-python.html On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > Hi, > > I would like to write a python script that will download a list of > files (mainly mp3s) from Internet. For this, I thought to use urllib, > with > > urlopen("myUrl").read() and then writing the resulting string to a > file > > my problem is that I would like to download several files at the time. > As I have not much experience in programming, could you point me the > easier ways to do this in python ? > > Thanks, > > JD > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sun Mar 30 17:06:18 2008 From: http (Paul Rubin) Date: 30 Mar 2008 14:06:18 -0700 Subject: Dispatching functions from a dictionary References: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> Message-ID: <7xd4pbexbp.fsf@ruckus.brouhaha.com> tkpmep at gmail.com writes: > RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), ...} This actually calls the functions random.betavariate, etc. when initializing RVDict. If you print out the contents of RVDict you'll see that each value in it is just a floating point number, not a callable. You want something like: RVDict = {'1': lambda: random.betavariate(1,1), '2': lambda: random.expovariate(1), etc. The "lambda" keyword creates a function that when called evaluates the expression that you gave it. For example, lambda x: x*x is a function that squares its argument, so saying y = (lambda x: x*x) (3) is similar to saying: def square(x): return x*x y = square(3) Both of them set y to 9. In the case of lambda: random.expovariate(1) you have made a function with no args, so you'd call it like this: > rvfunc = RVDict[str(RVType)] > for i in range(N): > x.append(rvfunc()) > y.append(rvfunc()) rvfunc (the retrieved dictionary item) is now a callable function instead of just a number. It takes no args, so you call it by saying rvfunc(). From castironpi at gmail.com Thu Mar 6 17:31:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 14:31:47 -0800 (PST) Subject: Protocol for thread communication References: Message-ID: <703eb1ca-3d22-4347-9a3c-c647e0038700@f47g2000hsd.googlegroups.com> > > Does anyone have any recommended ideas/ways of implementing a proper > > control and status protocol for communicating with threads? ?I have a > > program that spawns a few worker threads, and I'd like a good, clean way > > of communicating the status of these threads back to the main thread. > > Each thread (wrapped in a very simple class) has only a few states, and > > progress levels in those states. ?And sometimes they can error out, > > although if the main thread knew about it, it could ask the thread to > > retry (start over). ?How would any of you do this? ?A callback method > > that the thread can call (synchronizing one-way variables isn't a > > problem)? ?A queue? ?How would the main thread check these things? > > Currently the main thread is polling some simple status variables. ?This > > works, and polling will likely continue to be the simplest and easiest > > way, but simple status variables are very limited. ?Are there any > > pythonic patterns people have developed for this. There is the PyThreadState_SetAsyncExc API. "To prevent naive misuse, you must write your own C extension to call this." From allardwarrink at gmail.com Sat Mar 1 18:17:46 2008 From: allardwarrink at gmail.com (Allard Warrink) Date: Sat, 1 Mar 2008 15:17:46 -0800 (PST) Subject: PIL transparency gradient References: <6e44e95a-2cb0-4026-ad98-f6516e934e27@s37g2000prg.googlegroups.com> <4293dfd7-52aa-463e-b36c-c254a56616c4@s19g2000prg.googlegroups.com> Message-ID: Thanks for the inspiration! This what I did (Using your Python Editor (SPE), I really like to work with SPE, keep up the good work!!): ############################################# import Image, os p = # path to image file im = Image.open(p) # check if im has Alpha band... if im.mode != 'RGBA': im = im.convert('RGBA') # create a vertical gradient... gradient = Image.new('L', (1,255)) for y in range(255): gradient.putpixel((0,254-y),y) # resize the gradient to the size of im... alpha = gradient.resize(im.size) # put alpha in the alpha band of im... im.putalpha(alpha) # Save as png... im.save(os.path.splitext(p)[0] + '.png', 'PNG ############################################# From http Mon Mar 17 04:22:03 2008 From: http (Paul Rubin) Date: 17 Mar 2008 01:22:03 -0700 Subject: String To List References: Message-ID: <7xy78hep5g.fsf@ruckus.brouhaha.com> Girish writes: > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? > Thanks for the help... Be careful about using eval, if the string came from a potentially hostile source. Maybe what you really want is JSON, which has python-like syntax but a bunch of safe parsers. From castironpi at gmail.com Wed Mar 26 21:13:29 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 18:13:29 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: <9d2bcdeb-9076-45a2-bfd1-62a5d0be1ba1@x41g2000hsb.googlegroups.com> On Mar 26, 5:10?pm, bearophileH... at lycos.com wrote: > Sean Davis>Java has a BitSet class that keeps this kind of thing > pretty clean and high-level, but I haven't seen anything like it for > python.< > > If you look around you can usually find Python code able to do most of > the things you want, like (you can modify this code to add the boolean > operations):http://svn.zope.org/*checkout*/Zope3/trunk/src/zope/textindex/ricecod... > (Later I have improved that code for personal use). > > But operations on such bit arrays are very common, and you may need > them to be very fast, so you may use Cython (Pyrex) to write a small > class able to do those things in a much faster way. > Or you can also use Pyd plus an easy 30-lines long D program to write > a class that does those operations very quickly ?(using a dynamic > array of uint, with the help ofwww.digitalmars.com/d/1.0/phobos/std_intrinsic.html > ). > Maybe you can use GMPY numbers as bit arrays too. (I don't know if you > can use NumPy for this using a compact representation of the bits). I believe you're talking about collision detection, and my bartender is entertaining a proof that serial memory can't do it in time. So far the idea I see here is primitive memory couplings that change value based on primitive conditions of other memory. Peripherals including a chipset might show promise, esp. a flash chip, s.l. 'autopersistent' memory. Even if you still poll results, it's still a factor off O( n ). From stephenhorne100 at aol.com Tue Mar 18 11:59:04 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 18 Mar 2008 08:59:04 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> Message-ID: <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> Hrvoje Niksic wrote: > This doesn't apply to Python, which implements dict storage as an > open-addressed table and automatically (and exponentially) grows the > table when the number of entries approaches 2/3 of the table size. > Assuming a good hash function, filling the dict should yield amortized > constant time for individual additions. OK. I obviously need to look up open-addressed tables. I thought this was just, in effect, implicit linked listing - ie it still needs a linear search to handle collisions, it just avoids the need for explicitly stored link fields. Perhaps I'm mistaken. As for the growth pattern, each time you grow the table you have to redistribute all the items previously inserted to new locations. Resizes would get rarer as more items are added due to the exponential growth, but every table resize would take longer too since there are more items to move. Inserting n items still intuitively looks like O(n^2) to me. That said, it does remind me of that old exponential realloc trick for array resizing. Same thing, I suppose, since a hash table is basically an array. Maybe my math "intuition" is just wrong. From cmpython at gmail.com Sat Mar 22 03:21:30 2008 From: cmpython at gmail.com (CM) Date: Sat, 22 Mar 2008 00:21:30 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: On Mar 10, 3:27 pm, Stef Mientki wrote: > Stefan Behnel wrote: > > Malcolm Greene wrote: > > >>> My personal experience with wxPython has its ups and downs. Specifically > >>> when it comes to crashes, I wouldn't bet my life on it. > > >> I'm new to Python and getting ready to build a small client based > >> application intended to run on Windows and Linux. I was planning on using > >> wxPython until I saw your comment above. > > > Just to make this sound a bit less like FUD: my last experience with wxPython > > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > > in a project, which crashed a bit too often to do real work with it - and with > > crashing I mean crashing Python, not just showing us its blank traceback. So > > this was definitely a problem either in wxWindows or in wxPython. > > > I have no idea how well it works today, but this has definitely forged my > > opinion on wxPython. > > I'm using wxPython for half a year now, and building quit a large / > heavy GUI with it. > And although it's not so easy as Delphi, it's certainly just as stable > as Delphi. > > If you're talking aboutBoa, that's a completely different story, > I tried it on 3 different machines, and couldn't get it working on any > of them. I thinkBoa/ Dabo / .. are basically good ideas to make programming > wxPython more easy, and probably a lot of people invested a lot of their free time in the > product with the best intentions, but unfortunately these programs are not ready for use by > others (specially not for windows users). Although Boa Constructor is not yet "perfect", I am using it all the time with, in my (very limited) opinion, very good results. One thing is that the download site is not updated frequently, even if SVN is, so you must get it from SVN to get the recent version. Once I got the swing of doing things the Boa-istic way, I can set up pages, with sizers, and with many (but not all) of the currently available wxPython widgets, really quickly. Taking the tutorial, though tedious of course, pays off later. Although there are always more improvements it could have, what is there I find extremely impressive. It can draw bitmaps, allow for notes, shows sizers graphically, allows for timers and other utilities, works with Zope (though I haven't done that), and tons of stuff I'm not even aware of yet. One key is to create any changes to your app by hand but NOT in the sections which indicate that they are Boa-generated and not to be edited (the Designer takes "jurisdiction" over them). Early on I was frustrated by commenting things out in those sections and then having Boa "constrict" and swallow them whole--gone code! But now I just do things in my own def statements, and there are no problems with that. I understand if it is not for everyone, though; these things are a matter of taste to some degree it would seem. But I just figured I'd get a testimonial out there. From bruno.desthuilliers at gmail.com Mon Mar 31 16:37:33 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 31 Mar 2008 13:37:33 -0700 (PDT) Subject: Problem with method overriding from base class References: Message-ID: On 31 mar, 11:05, wrote: > Hello everyone > > I have defined some sort of 'interface class' and a factory function that creates instance objects of specific classes, which implement that interface: > > Interface definition: > *************************************************************************************** > import GUI.webGUI as webGUI > > class EditInterface(webGUI.WebGUI): > def addEntry(self, *p): > raise 'EditInterface.addEntry(): Interface must not be called directly' You want: raise NotImplementedError('EditInterface.addEntry(): Interface must not be called directly') And unless you have some pretty good reason to do so (ie: template methods in EditInterface depending on these methods), you don't even want to bother with all this - just document which methods must be implemented, and let Python raise an AttributeError if they are not. (snip) > Factory: > *************************************************************************************** > def factory(type, *p): > if type == common.databaseEntryTypes[0]: > return module1.Class1(*p); > elif type == common.databaseEntryTypes[1]: > return module2.Class2(*p); > elif type == common.databaseEntryTypes[2]: > return module3.Class3(*p); > elif type == common.databaseEntryTypes[3]: > return module4.Class4(*p); The whole point of polymorphic dispatch in OO is to avoid this kind of mess. What's wrong with instanciating classes directly ? NB : in Python, classes are objects too, so you can pass them around as needed. Also, instanciation is done thu a call to the class object - which makes it just the same as a function call. IOW, you just don't need a clumsy dedicated factory function just to make sure the client code is not too tightly coupled to the exact implementation. > > Implementing Class1: > *************************************************************************************** > import editInterface > > class Class1(editInterface.EditInterface): > > def __init__(self, product, database): > # do something here ... > > def showEntry(self, entry, statustext): > # do something here as well, return some string... > *************************************************************************************** > > Now, when I want to create an Instance of Class1 I do: > > myClass1Instance = factory.factory(common.databaseEntryTypes[1], 'Name', databaseObj ) > Which seems to work fine according to the debugger. But when I do next: > > msg = myClass1Instance.show(firstEntry, '') > > Then the show() method of the class 'EditInterface' is called instead of the show() method of the class 'Class1' !! Reread your code : class Class1 have no 'show' method !-) From gandalf at shopzeus.com Thu Mar 27 12:48:25 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 27 Mar 2008 17:48:25 +0100 Subject: dynimac code with lambda function creation In-Reply-To: <47EBAD07.9010603@gmail.com> References: <47EBAD07.9010603@gmail.com> Message-ID: <47EBCFD9.7050007@shopzeus.com> Justin Delegard wrote: > So I am trying to pass an object's method call to a function that > requires a function pointer. I figured an easy way to do it would be to > create a lambda function that calls the correct method, but this is > proving more difficult than I imagined. > > Here is the function I'm using: > > def objectMethodCallerFunctionCreator(testerObj, method): > exec("y=lambda x: testerObj."+method+"(x)") > return y > You are making it too difficult. What about this: def objectMethodCallerFunctionCreator(testerObj, method): return getattr(testerObj,method) BTW, when you need to return a value (instead of simple code execution) you should use eval() instead of exec(). > Where testerObj is an instance of an object, and method is a string > representing the method to call. The problem is, when I actually run > the function created (y in this case), it tells me it can't find the > symbol testerObj in the global scope. That is true. The 'testerObj' parameter is assigned to the local namespace. The local namespace is created when the function is called. When you call exec, it creates a new namespace. Thus, testerObj is not available inside exec(). But please see above - you do not need exec for this. It is unsafe, slow and really not necessary. > I am assuming this is happening because of the exec() call, but I don't > see another way of calling a variable method on an object. Generally, you should not use exec, eval and their counterparts to access certain attributes of different objects. Same for defining functions, classes, create instances etc. If you still feel that you need to use eval or exec for some reason, drop me an email and hopefully I can help avoiding it. :-) Best, Laszlo From hniksic at xemacs.org Fri Mar 28 12:39:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Mar 2008 17:39:01 +0100 Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: <87od8yolay.fsf@mulj.homelinux.net> skip at pobox.com writes: > I'm having trouble explaining the benefits and tradeoffs of threads > to my coworkers and countering their misconceptions about Python's > threading model and facilities. They all come from C++ and are used > to thinking of multithreading as a way to harness multiple CPU cores > for compute-bound processing. I also encountered, "Python doesn't > really do threads" today. *sigh* Compute-bound processing pretty much excludes a Python-only solution, so any performance considerations should take into account C extensions. Extensions are free to allow other threads to run during CPU-extensive portions of their work, and many of them in fact do so. As long as the extensions are correctly written, you can write your "glue code" in Python and harness the multiple cores using threads, exactly as expected by a C++ programmer. The other use for threads is the case when dealing with blocking APIs that don't support polling. These typically include database APIs and some network APIs (such as the portable host name lookup), but also basic file input/output, if you take into account network file systems. (In theory, file input/output should also be available as asynchronous code, but async IO is low-level and not available in Python.) While threads shouldn't be considered a replacement for event-driven programming, they are certainly useful in such situations. From ericgorr at gmail.com Wed Mar 19 11:32:26 2008 From: ericgorr at gmail.com (Eric) Date: Wed, 19 Mar 2008 08:32:26 -0700 (PDT) Subject: SOAP Server in Python References: <50ccc1be-87ac-4847-b21d-7dfd46379ea4@z38g2000hsc.googlegroups.com> Message-ID: On Mar 19, 10:59 am, dave_mikes... at fastmail.fm wrote: > On Mar 19, 9:19 am, Eric wrote: > > > I am basically looking to do the same thing in Python as easily. > > > Any help or pointers would be appreciated. > > Googling for "python soap" turned up a few hits that may help you. Yes, but I don't have the knowledge to accurately or effectively evaluate the information. I was hoping someone here had some experience writing a SOAP Server using Python and would be willing to share what they know. From arnodel at googlemail.com Sun Mar 23 16:08:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Mar 2008 13:08:41 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> Message-ID: On Mar 23, 5:45?pm, Paul Rubin wrote: > John Nagle writes: > > ? ?What's the cheapest way to test for an empty dictionary in Python? > > > ? ?if len(dict.keys() > 0) : > > I like to think len(dict) is constant time but I haven't checked the code. > Same for bool(dict) (which is what you get when you run "if dict: ..."). It has to be constant time as it is a lower bound for inserts (which average to constant time). -- Arnaud From pavloutefkros at gmail.com Sun Mar 2 16:22:55 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 13:22:55 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: thanks everybody, i've got this to work. i'm not trying to write an actual web server, i'm just using it for some procedures like URL rewriting. From bbxx789_05ss at yahoo.com Mon Mar 31 20:14:51 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 31 Mar 2008 17:14:51 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> Message-ID: <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> On Mar 31, 5:31?pm, castiro... at gmail.com wrote: > Can you have a Python object stored entirely on disk? import cPickle as cp class Dog(object): def __init__(self, name): self.name = name d = Dog("Spot") f = open("data.txt", "w") cp.dump(d, f) f.close() f = open("data.txt") stored_obj = cp.load(f) print stored_obj.name --output:-- Spot From me at privacy.net Sat Mar 15 15:31:03 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 19:31:03 +0000 Subject: Getting started with OS X Leopard In-Reply-To: References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> Message-ID: <47dc23f7$0$32053$da0feed9@news.zen.co.uk> has wrote: > On 15 Mar, 18:05, Mark Carter wrote: >> The sorts of things I want to do are: >> * copy the directory of Finder to the clipboard >> * add a new file to Finder's directory. >> * find out the size of a directory >> * open a file with Aquamacs, regardless of file type, > > If you want to control desktop applications directly, that generally > means using Apple event IPC. The most popular language for application > scripting is traditionally AppleScript, but Apple event bridges exist > for other languages as well. The best of these is appscript; see my > sig for links. Some Finder scripting examples: > > > #!/usr/bin/python > ... > Control AppleScriptable applications from Python, Ruby and ObjC: > http://appscript.sourceforge.net Aah! Many thanks. I see that I had to do easy_install appscript and ensure I use /usr/bin/python I'm off to play with it now. Exciting stuff. I installed the Python from MacPorts. That's not quite what I wanted, because they only have a version for Python 2.4. *Sigh*. MacPorts seems to be getting new ports all the time. The problem is, there also seems to be an aweful lot of ports gathering bitrot. Am I the only one to form the opinion that OS X can sometimes appear to be a bit of a mish-mash? I tried XCode the other day. Seemed a bit complicated, if you ask me. I've tried to like Lisp, too. In the end, Python just rocks. I started out with Glade a short while ago, and I'm impressed how relatively easy it is to create GUIs and add handlers in Python. From castironpi at gmail.com Thu Mar 27 01:13:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 22:13:28 -0700 (PDT) Subject: A question on decorators References: <64vpmnF2dvlccU1@mid.uni-berlin.de> <818b5a6c-636d-4a6e-8fb3-b44e32925ca0@e10g2000prf.googlegroups.com> Message-ID: On Mar 26, 10:02?pm, alex23 wrote: > On Mar 27, 8:30 am, castiro... at gmail.com wrote: > > > I want the * to precede the dot too. ?Let's yack. ?I want to compile > > Python. ?Did you see my new post? ?I like it. ?Do you have any time > > you don't want? ?Time sale. ?Diez is still mad at me. ?I want > > primitives to structure themselves so I can pick up a pen. ?I am > > volunteer primitive structuring. ?Your structure sucks. ?assert > > atmostphere has drags. > > Could you possibly once, just once, put down the Robert Anton Wilson & > the meth pipe before you post? Loud and clear. Copy back to you. From george.sakkis at gmail.com Tue Mar 18 14:47:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 11:47:35 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <29b0d6d3-93e9-4c85-b7e9-6e30f4eb0e2f@x41g2000hsb.googlegroups.com> Message-ID: <4339fff0-3c11-4151-9ea9-a85228648b77@d21g2000prf.googlegroups.com> On Mar 18, 1:49 pm, Mike Orr wrote: > On Mar 16, 6:10 am, Bruce Eckel wrote: > vendors: > > On top of that, the quality of the presentations was unusually low. > > I did feel that. An advanced track would be a good idea. Because > you do need to repeat stuff for the newbies. At least 30% of the > attendees were at PyCon for the first time. Not all first-comers are newbies; I attended for the first time too but I've been using Python for the last four years or so. My overall (totally unscientific) impression was that most attendants had at least a decent grasp of the language. George From castironpi at gmail.com Thu Mar 27 07:45:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:45:40 -0700 (PDT) Subject: what are generators? References: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> <5875e7c0-6051-4e27-b019-5bae126d457e@p25g2000hsf.googlegroups.com> Message-ID: <955c278f-6555-48fa-a33c-6573d0a1e49e@a1g2000hsb.googlegroups.com> On Mar 27, 6:19?am, castiro... at gmail.com wrote: > On Mar 25, 7:36?pm, Miki wrote: > > > On Mar 24, 8:17?am, castiro... at gmail.com wrote: > > > > I'm looking for a cool trick using generators. ?Know any exercises I > > > can work? > > > Simple one the comes to mind is flattening a list: > > > >>> list(flatten([1, [[2], 3], [[[4]]]])) > > [1, 2, 3, 4] > > I don't think it's well-defined. ?(But this is impossible and useless > calling.) ?CMIIW? > > This is generic: Revise: >>> def f(): ... __gen= None ... def set( gen ): ... nonlocal __gen ... __gen= gen ... yield set ... i= 0 ... while 1: ... i+= 1 ... yield __gen( i ) ... >>> a= f() >>> set= next( a ) >>> set( lambda x: print( x ) ) >>> next( a ) 1 >>> next( a ) 2 >>> next( a ) 3 >>> From python.list at tim.thechases.com Wed Mar 19 12:21:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 11:21:19 -0500 Subject: url validator in python In-Reply-To: <7a27c19d-2e0e-4242-9054-9455f825df8f@i7g2000prf.googlegroups.com> References: <7a27c19d-2e0e-4242-9054-9455f825df8f@i7g2000prf.googlegroups.com> Message-ID: <47E13D7F.8050009@tim.thechases.com> > How can I check the validity of absolute urls with http scheme? > example: > "http://www.example.com/something.html" -> valid > "http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid You could try something like import urllib tests = ( ("http://www.google.com/ + Brite_AB_Iframe_URL + ", False), ("http://www.example.com/something.html", True), ("https://www.google.com/ + Brite_AB_Iframe_URL + ", False), ("https://www.example.com/something.html", True), ) def no_method(url): if ':' in url[:7]: # strip off the leading http: return url.split(':', 1)[1] return url def is_valid_url(url): url = no_method(url) return url == urllib.quote(url) for test_url, expected_result in tests: print "Testing %s\nagainst %s" % ( no_method(test_url), urllib.quote(no_method(test_url)) ) actual_result = is_valid_url(test_url) print 'Pass: %s' % (actual_result == expected_result) print '='*70 The reason for the no_method() is that otherwise it gets normalized to "http%3A//..." so you have to strip off that bit before comparing. -tkc From castironpi at gmail.com Sun Mar 2 10:47:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 07:47:56 -0800 (PST) Subject: Network server- / client-side messaging Message-ID: ''' a website wants to show you different arrangements of framed pictures on a wall. you can click, drag, scale, and rotate pictures in place. you can also drag new pictures in to it. spacing is uniform and settable-- if you rotate one, the readout of the total square area changes along with the new value. you can also select themes from the host that determine formulae for spacing, based on established aesthetics constraints. user clicks a picture and clicks rotate. clientside doesn't want to transmit the whole array back to the server for calculation, but calculation takes a long time, due to the complexity of the spacing formulae. therefore, maintain paralell data on both sides: client for displaying and interfacing, so as not to inform the server of every mouse click, and server side to decrease transmission redundancy and size. do not broadcast every click, but do not broadcast entire interface state. constraint-based best-fit labor distribution is between. changes are sent to the server in the form of the change parameters (perhaps a change object), the layout is updated roughly (still by server-side procedures), and then precisely (along with the sq. ft. readout) when the calculation completes. the interface remains continuously active. Partial cast: ''' class PictureClientSide: def __init__( self, image ): self._image= image def on_scale( self, *params ): change= self.whatchange( scale, *params ) self.tell_the_server( change ) def on_rotate( self, *params ): change= self.whatchange( rotate, *params ) self.tell_the_server( change ) def server_says( self, layoutchange ): renderchange( layoutchange ) class PictureServerSide: def __init__( self, image ): self._image= image def client_says( self, change ): preliminary= self.calculation() preliminary_change= whatchange( preliminary ) tell_the_client( preliminary_change ) completed= self.other_calculation() completed_change= whatchange( completed ) tell_the_client( completed_change ) ''' It's too tangled to proceed. What if a second client 'change' and the first server 'completed' cross paths? Will you cancel the first change explicitly or just drop it? Are you shooting for five-nines quality, or one? What about signal loss and reordering? Will you retransmit an entire message upon suspected loss, or intervalled AYT messages (are you there)? What about an immediate time estimate? How general can the underlying framework be? The rest is a brainstorm. Please critique. ''' class PictureClientSide( ClientSide ): settings= Setting1(), Setting2() @incremental def server_says( self, layoutchange ): renderchange( layoutchange ) class PictureServerSide( ServerSide ): settings= Setting3(), Setting4() ''' We may want to distinguish requests in both directions. Depending on which side takes care of the rotation, server_says may divide based on increment. ''' class PictureClientSide( ClientSide ): @incremental( 1 ) def server_says( self, layoutchange ): renderchange( layoutchange ) @incremental( 2 ) def server_says( self, layoutchange ): renderchange( layoutchange ) ''' Furthermore, you may want the time estimate in its own method. ''' class PictureClientSide( ClientSide ): @incremental( layoutchange, 1 ) def server_says( self, layoutchange ): renderchange( layoutchange ) @incremental( layoutchange, 2 ) def server_says( self, layoutchange ): renderchange( layoutchange ) @message( timeout_message ) def timeout_message( self, etc ): report( etc ) From MartinRinehart at gmail.com Wed Mar 26 14:00:11 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 26 Mar 2008 11:00:11 -0700 (PDT) Subject: Tkinter menus from keyboard References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: Eric Brunel wrote: > BTW, this "standard" is not universal at all: e.g, there is no such > convention on Macs. Thanks for the info. It's standard on Windows and Linux/KDE. GNOME, anyone? From planders at gmail.com Wed Mar 19 11:26:59 2008 From: planders at gmail.com (Preston Landers) Date: Wed, 19 Mar 2008 08:26:59 -0700 (PDT) Subject: Improving datetime References: Message-ID: <60ef7aa5-a387-4129-9c77-6ca91bafc152@f63g2000hsf.googlegroups.com> On Mar 19, 9:12?am, "Nicholas F. Fabry" wrote: > So - where should I propose these changes? ?Here? ?python-dev? ?Should ? > I write up a full PEP or should I just give a more informal outline ? > with code samples? ? My guess is that the python-dev folks would send you here or to the python-ideas mailing list. My suggestion is to give a more informal outline with code samples either here or in python-ideas before proceeding any further. Preston From grante at visi.com Fri Mar 28 12:13:34 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 16:13:34 -0000 Subject: How do I reconnect a disconnected socket? References: Message-ID: <13uq69e8us4oo74@corp.supernews.com> On 2008-03-28, Laszlo Nagy wrote: >> while (1): >> buffer = sock.recv(1024) >> if not buffer: >> dodiscon() >> > > sock.recv(1024) can return zero bytes of data indicating that no data > arrived yet. No, it can't. > It does not mean that you have been disconnected. Yes, that is exactly what it means. >From the recv() man page: RETURN VALUE These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown. -- Grant From mail at timgolden.me.uk Sun Mar 16 03:42:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 07:42:31 +0000 Subject: Spaces in path name In-Reply-To: <47DCC1C4.2010806@timgolden.me.uk> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> Message-ID: <47DCCF67.7050503@timgolden.me.uk> Tim Golden wrote: > joep wrote: >> On Mar 15, 5:42 pm, joep wrote: >>>> http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... >>> Note: this works for subprocess.call but for subprocess.Popen this >>> does not work if there are two arguments in the command line with >>> spaces. Especially, even after trying out many different versions, I >>> never managed to get subprocess.Popen to work, when both the >>> executable and one argument have spaces in the file path. >>> >> Sorry, incomplete sentence >> >> Especially, even after trying out many different versions, I never >> managed to get subprocess.Popen to work '''when command line is given >> as a *list* argument to subprocess.Popen''' >> in the case when both the executable and one argument have spaces in >> the file path. Following up, I'm a little bemused. Below is a command which works on a Win2K Python 2.4 installation (and on WinXP with Python 2.5). I've deliberately chosen something in Program Files and I've copied both the executable and the document so that even the base filenames have embedded spaces, as well as the directory path to get there. (The lines are quite long: you'll probably have to piece them together a bit; that's why I've put an extra line space between each.) subprocess.call ([ r"C:\Program Files\Adobe\Acrobat 5.0\Reader\acro reader.exe", r"C:\Program Files\Adobe\Acr obat 5.0\Reader\plug_ins.donotuse\Annotations\Stamps\abc def.pdf" ]) Can you confirm that something equivalent *doesn't* work on your setup? Or have I misunderstood your point earlier? I'd really like to get to the point where we can definitively state: this works (and possibly: that doesn't). Thanks TJG From godzillaismad at gmail.com Wed Mar 19 08:17:25 2008 From: godzillaismad at gmail.com (Godzilla) Date: Wed, 19 Mar 2008 05:17:25 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> Message-ID: <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> Hi John, I am using time.clock to calculate the elapsed time. Below is an example of what I was trying to do: import time import thread class elapseTime: def __init__(self, name=''): self.name = name self.timeStamp = None self.checkTimeFlag = False thread.start_new_thread(self.elapsedTime, ()) def setTime(self, state): if state == 1: self.checkTimeFlag = True self.timeStamp = time.clock() else: self.checkTimeFlag = False def elapsedTime(self): while True: curTime = time.clock() if self.checkTimeFlag: if (curTime - self.timeStamp) > 1.0: print "Elapsed time greater than 1 second. Actual Elapsed Time", round(curTime-self.timeStamp, 3) self.checkTimeFlag = False prevTime = curTime time.sleep(0.05) obj = elapseTime() while True: obj.setTime(1) time.sleep(10) But the time.clock() sometimes return a value of between -3.5 to -4.5 seconds backward. Note that not all computers are behaving the same. I have not experience the same problem with the computer at home. From martin.laloux at gmail.com Wed Mar 5 07:40:13 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Wed, 5 Mar 2008 04:40:13 -0800 (PST) Subject: Leopard and MySQL References: Message-ID: <929700bd-89e6-4fb9-ac02-558841cb939e@i12g2000prf.googlegroups.com> There is a macpython list that you can consult at http://www.nabble.com/Python---pythonmac-sig-f2970.html. When you search for your problem http://www.nabble.com/forum/Search.jtp?forum=2970&local=y&query=mysqldb you have the solution http://www.nickshanny.com/2007/10/os-x-105-python-and-mysqldb.html From grante at visi.com Sun Mar 9 00:20:53 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:20:53 -0000 Subject: SV: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: <13t6stlnvt6foa9@corp.supernews.com> On 2008-03-08, K Viltersten wrote: >> If you can't/don't look at the source file, >> then comments aren't going to help (except >> in the case of something like docstrings in >> Python). > > I strongly disagree. Now, perhaps we're > talking about different things, here? > Usually, in the header file (C++), Header files are source code. > there won't be any source code, except for method > declarations. Declarations are source code. > A common example: > > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); That's source code. > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. I've no problem with that. > I don't see how this is dislikeable. Please > explain. Perhaps the above IS what you > ment by "docstrings"? http://en.wikipedia.org/wiki/Docstring http://epydoc.sourceforge.net/docstrings.html > For Java, one has the JavaDocs, a great tool, provided one > will comment each method and variable used. > >>> Now, i'm getting the signal that it's done >> in a different way in Python. >> >> I'm not sure how you concluded that from this thread. > > The below, more or less. :) > >> "What I really can't stand are the >> pointy-haired comment blocks at the >> beginnings of C/C++ functions that do >> things like tell you the name and return >> type of the function and list the names >> and types of the parameters." > > Please note that i DO NOT argue against one > way or another. I simply expressed surprise > since i've been tought otherwise earlier > and, maybe, there's a larger picture than > what i've seen this far. As stated before, > snakeology is a very new area to me. Yet. ;) Duplicating information in a comment that is plainly obvious 5 lines below it in the actual source code is a waste of time when the code is written. A week later, the comment will be out of sync with the code and anybody paying attention to the comment will be mislead. I exaggerate (slightly), but in my experience anytime information is duplicated in multiple places it doesn't take very long at all before it's out-of-sync and incorrect in all places except one. -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.com glimpse of the INNER WORKINGS of this POTATO!! From mail at microcorp.co.za Sun Mar 30 09:49:16 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Mar 2008 15:49:16 +0200 Subject: Serial port error statistics - any comparable data? Message-ID: <001d01c8926c$f8ffdc20$03000080@hendrik> "Diez B. Roggisch" wrote: >RS232 is unfortunately as bad as a "protocol" as it can get. I've used >it for communication with a microcontroller for just a few bytes every >second. And it failed miserably, so I needed to implement a protocol on >top of it. We normally do this anyway, except for stuff like menus that are intended for interactive use as setup - doing without on machine to machine comms feels a bit too cowboy... > >The machine spec is totally irrelevant - what is interesting is the >serial hardware you use. Are you by any chance using a >serial2usb-converter? I had nothing but troubles with these. > I have also heard rumours about this, and you have just hardened my admittedly irrational attitude towards them. I have never used one in anger. >if you have the chance, try & attach a machine with legacy rs232 port, >and see if the errors still remain. > >Diez Alas - the port in question is the native legacy motherboard port. If it were windows, it would be COM1... I had hoped that somebody would have done some similar work, so that we could compare notes on the error frequency. It does not seem likely though - If I was not testing the performance of the Lantronix xport device, I would not have kept stats either - it is kind of tedious to sit and watch the fox scroll up the screen for days on end.. It just surprised me to find that the errors were made in the PC's receive. I proved this by short circuiting the xport's receive and transmit at the RS-232 level and gave up after some ten million error free lines. (Most of an afternoon, overnight, and most of the next morning ;-( ) thanks Diez. Then Castironpi wrote: >Transmit observed minus expected to cluster. The "cluster" in all the cases observed is the loss of exactly one character, somewhere from around more or less the middle of the string: "The quick brown fox jumps over the lazy dog 0123456789" Why do you make the assertion that the errors would cluster? >What kind of tables does the input device build? Whatever the kernel and the cpython implementation does to receive the string from a port unblocked with fcntl - and the throw away python script that does the echoing builds the string up with a read(1). And before I get flamed for wasting resources - The read(1) is necessary to be able to run a protocol, later. - Hendrik From fkallgren at gmail.com Sat Mar 22 04:09:07 2008 From: fkallgren at gmail.com (fkallgren) Date: Sat, 22 Mar 2008 01:09:07 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <8c942685-576f-4afb-844a-b825fcc7205c@8g2000hsu.googlegroups.com> On Mar 21, 12:48 pm, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > > /fkallgren Thanks everyone. I now have several attack angles to solve this problem. /fkallgren From grflanagan at gmail.com Mon Mar 10 12:07:19 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Mon, 10 Mar 2008 09:07:19 -0700 (PDT) Subject: defining a method that could be used as instance or static method References: Message-ID: <5d11ea42-3d84-459f-9500-83b4bc0df827@x30g2000hsd.googlegroups.com> On Mar 10, 4:39 pm, Sam wrote: > Hello > > I would like to implement some kind of comparator, that could be > called as instance method, or static method. Here is a trivial pseudo > code of what I would like to execute > > >> class MyClass: > > ... def __init__(self, value): > ... self.value = value > ... def comp(self, compValue): > ... return self.value == compValue.value>> a = MyClass(3) > >> b = MyClass(4) > >> c = MyClass(3) > >> a.comp(b) > False > >> a.comp(c) > > True > > This is actually achieved by MyClass, how could implement it in order > to accept: > > >> MyClass.comp(a, b) > > False > > I would really appreciate a pointer or a way to complete MyClass in > order to fulfill my requirements. Thank you for your attention. > > Sam ------------------------------------------------------ class MyClass(object): ''' >>> a = MyClass(3) >>> b = MyClass(4) >>> c = MyClass(3) >>> a.isequal(b) False >>> a.isequal(c) True >>> MyClass.comp(a, b) False >>> MyClass.comp(a, c) True ''' def __init__(self, val): self.value = val @staticmethod def comp(a, b): return a.value == b.value def isequal(self, b): return self.comp(self, b) if __name__ == '__main__': import doctest options = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE doctest.testmod(optionflags=options) ------------------------------------------------------ From danb_83 at yahoo.com Sat Mar 15 18:48:58 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 15 Mar 2008 15:48:58 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <112a4e45-e413-4fd3-9ecb-94e0b77e8fd1@s12g2000prg.googlegroups.com> On Mar 15, 4:43 pm, Guido van Brakel wrote: > Hello > > I have this now: > > > def gem(a): > > g = sum(a) / len(a) > > return g > > > print gem([1,2,3,4]) > > print gem([1,10,100,1000]) > > print gem([1,-2,3,-4,5]) > > It now gives a int, but i would like to see floats. How can integrate > that into the function? If you add "from __future__ import division" at the top of the file, division will work properly. From lists at cheimes.de Sat Mar 22 09:18:56 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Mar 2008 14:18:56 +0100 Subject: implementing tab completion using python In-Reply-To: <5f733b8e-b869-4f2b-930c-42a044935ad4@u10g2000prn.googlegroups.com> References: <5f733b8e-b869-4f2b-930c-42a044935ad4@u10g2000prn.googlegroups.com> Message-ID: Siddhant schrieb: > Hi. > How can I implement a tab-completing code using Python? > Like for example, I want to design a simple shell (using Python, of > course), which could support tab completion as well. How do I go about > it? http://docs.python.org/lib/module-rlcompleter.html Christian From gagsl-py2 at yahoo.com.ar Mon Mar 24 14:41:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 15:41:51 -0300 Subject: importing package contents from multiple places in PYTHONPATH References: <6c6765d4-e1d7-4ca8-af96-e3c038fc5f3e@i7g2000prf.googlegroups.com> Message-ID: En Mon, 24 Mar 2008 15:06:51 -0300, escribi?: > Hi all, > > I'm new to python, and am trying to determine if it's possible to do > the following... > > I have a directory structure like this, with both 'dir1' and 'dir2' in > my PYTHONPATH > > dir1/ > foo/ > __init__.py > a.py > b.py > > dir2/ > foo/ > __init__.py > a.py > c.py > > I'd like to be able to: > > python> import foo.a, foo.b, foo.c > > I'd hope for package 'foo.a' to come from dir1 since it was first on > the path, with 'foo.b' and 'foo.c' coming form dir1 and dir2 > respectively. Yes. Note that dir2/foo/__init__.py is not used at all and it's just confusing. And a.py (in dir2) won't be found inside the package but any "import a" from c.py will import that one instead of the one at dir1. dir2/foo is just a "bag", not a "package" :) > I understand that python stops once it encounters the first 'foo' > package in PYTHONPATH, but I was wondering if there was a way around > this. I've had some success modifying __path__ in the foo/__init__.py > files, but am unsure if this is the best approach. I think it is the simplest approach, if not the only one... > Perhaps there's a > way to do this with import hooks? Perhaps... But appending a single item to __path__ is simple enough to stop further thinking from my side :) Anyway, why do you want to do that? Can't use a different name for dir2/foo, and perhaps import its modules from inside dir1/foo/__init__.py? -- Gabriel Genellina From mensanator at aol.com Mon Mar 3 20:44:13 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 17:44:13 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: <2aceec91-618d-4e62-9958-e223505bc51f@13g2000hsb.googlegroups.com> On Mar 3, 6:49?pm, Robert Kern wrote: > Mensanator wrote: > > On Mar 3, 4:53 pm, Carl Banks wrote: > >> 3. You must be terribly naive if you expect a freeware program with a > >> version number of 0.5.12 not to have bugs > > > No, but I guess I'm naive thinking that when someone posts a link to > > such a program that he's recommending going and trying it out. That > > is why they're making it available, isn't it? For people to try out > > so they can get free testing? Aren't I doing my part? Should I just > > uninstall it and forget it? > > Finding the issue and reporting it to the sympy bug tracker is commendable. > > Coming here and "un-recommending" sympy before the issue was resolved is not. Bad choice of words I guess. I'll try to keep that in mind. > > -- > 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 gagsl-py2 at yahoo.com.ar Thu Mar 6 15:38:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 18:38:33 -0200 Subject: help on file storage for split multi part download References: Message-ID: En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: > storage class which can write the file splits that are currently being > downloaded to the disk. this is exactly what other download > accelerators do, i guess. > > can this be done using the python file class?? i am pretty good at > handling file uploads (at server end) this is the first time i have to > think the other way round. Uh, unless I misundersand you, a standard file object is enough. First create a file with the required size (open(...,'wb'), seek(n-1), write(chr(0))). For each downloaded chunk you have to know its position in the file; then just seek() and write() it. -- Gabriel Genellina From skip at pobox.com Thu Mar 27 11:49:43 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 27 Mar 2008 10:49:43 -0500 Subject: Is subprocess.Popen completely broken? In-Reply-To: <16651e80803270819t131e01adle1a5b9ed8b8fb976@mail.gmail.com> References: <16651e80803270819t131e01adle1a5b9ed8b8fb976@mail.gmail.com> Message-ID: <18411.49687.719497.174832@montanaro-dyndns-org.local> >> Why should I need to set shell=True? I'm not globbing anything. The >> second case still fails: Jerry> RTFM Thank you. I had. The bits about the type of the args parameter don't mention the shell parameter or that there was any difference between using strings or lists. I missed the reasoning in the discussion on the shell parameter. I think the subprocess module docs probably need some rework. In general, I understand that having a bunch of different ways to execute subprocesses can be confusing. The swiss army knife approach used in the subprocess module is also problematic. Skip From simon at brunningonline.net Fri Mar 28 06:14:17 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 28 Mar 2008 10:14:17 +0000 Subject: Dynamic code problem In-Reply-To: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> Message-ID: <8c7f10c60803280314q320884e8k9993592d688fec83@mail.gmail.com> On Thu, Mar 27, 2008 at 4:13 PM, wrote: > My dynamic code failed at this site http://playwide1.extra.hu/, need > some help thank you. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From me at privacy.net Sat Mar 15 17:35:26 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 21:35:26 +0000 Subject: Getting started with OS X Leopard In-Reply-To: References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Message-ID: <47dc411e$0$32041$da0feed9@news.zen.co.uk> martin.laloux at gmail.com wrote: > if you are not satisfied with the native version, why not install the > official version directly from python site > http://www.python.org/download/ (macpython) instead of using that of > macports. It moreover is provided with many utilities > > There is a macpython list that you can consult at > http://www.nabble.com/Python---pythonmac-sig-f2970.html Thanks. Actually, I created my first python appscript (well, "stole" it from a previous poster is more like it) - and it's pretty cool when I combine it with FinderPop. From exxfile at hotmail.com Sat Mar 29 23:15:59 2008 From: exxfile at hotmail.com (pythonnubie) Date: Sat, 29 Mar 2008 20:15:59 -0700 (PDT) Subject: Where can I find : Message-ID: Hi All : Does anyone know where I can find either a book or a website that explains beginning python by actually building a project line by line and explaining it indepth . I am primarily interested in understading flowcontrol as well as syntax . If it was related to netwoprking then that would be a great addition although not required because that is my primary field of interest . All help greatly appreciated ! Mark From cito at online.de Mon Mar 3 17:33:37 2008 From: cito at online.de (Christoph Zwerschke) Date: Mon, 03 Mar 2008 23:33:37 +0100 Subject: First post from a Python newbiw In-Reply-To: <41cfe2c1-51d0-4b15-b9c8-ea3d4389b6cf@e6g2000prf.googlegroups.com> References: <41cfe2c1-51d0-4b15-b9c8-ea3d4389b6cf@e6g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle schrieb: > It's a FAQ: > http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list Somewhere on my todo list I have "read through the whole Python FAQ", but so far never got round doing it. Should probably set it to prio A. -- Christoph From sdeibel at gmail.com Mon Mar 17 01:42:28 2008 From: sdeibel at gmail.com (Stephan Deibel) Date: Sun, 16 Mar 2008 22:42:28 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 6:10 am, Bruce Eckel wrote: > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Vendors were guaranteed first pick on lightning talk slots, and > we in the audience, expectantly looking forward to interesting and > entertaining content, again started to feel like things were awfully > commercial. And what seemed like a good idea, moving lightning talks > into plenary sessions with no competition, began to look like another > way to deliver a captive audience to vendors. Yes, this sucked, and I say that as one of the guys that gave a boring vendor lightning talk. I felt obligated to take the slot but probably shouldn't have, or should have talked about something else. The problem was definition of the sponsorships without carefully limiting the benefits that would get out of hand when 3X as many sponsorships were sold as expected (which is what happened). To be fair, I'm not sure I would have foreseen this either. > I know what the argument for the results of Pycon 2008 will be: we > needed the money. My answer: it's not worth it. If this is what you > have to do to grow the conference, then don't. If the choice is > between selling my experience to vendors and reducing the size of the > conference, then cut the size of the conference. Keep the quality of > my experience as the primary decision criteria, or I'll stop coming. I have to admit, I'll keep coming to PyCon even if all the talks suck abysmally as long as there's good hallway time, open space, BoFs, and sprints. ;-) But, yes, lightning talks are also a critical part of the conf, and would be a terrible loss. - Stephan From ebgssth at gmail.com Sun Mar 2 11:23:32 2008 From: ebgssth at gmail.com (js) Date: Mon, 3 Mar 2008 01:23:32 +0900 Subject: Beautiful Code in Python? Message-ID: Hi, Have you ever seen Beautiful Python code? Zope? Django? Python standard lib? or else? Please tell me what code you think it's stunning. From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 20:44:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 01:44:30 -0000 Subject: Classes and modules are singletons? Message-ID: <13suj3u2d17f205@corp.supernews.com> I recall that Python guarantees that module objects are singletons, and that this must hold for any implementation, not just CPython: you can only ever create one instance of a module via the import mechanism. But my google-foo is obviously weak today, I cannot find where the Python language reference guarantees that. Can somebody please point me at the link making that guarantee? (Note: you can create multiple modules with the same name and state using new.module. I don't think that counts, although it may be a good way to win bar bets with your Python buddies.) But what about classes? Are they singletons? Obviously classes aren't Singleton classes, that is, given an arbitrary class C you can create multiple instances of C. But what about class objects themselves? I've found a few odd references to "classes are singletons", but nothing in the language reference. I've done some experimentation, e.g.: >>> import module >>> from module import Class >>> module.Class is Class True but I'm not sure if that's (1) meaningful or (2) implementation-specific. -- Steven From max at alcyone.com Thu Mar 6 21:43:53 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 06 Mar 2008 18:43:53 -0800 Subject: Looking for very light weight template library (not framework) In-Reply-To: References: Message-ID: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> Malcolm Greene wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. ... > Any suggestions appreciated. EmPy may work: http://www.alcyone.com/software/empy/ Your template would look something like: myOutput = """\ The total cost is @invoice.total. This order will be shipped to @invoice.contact at the following address: @invoice.address This order was generated at @time.ctime() """ This could be instrumented with something as simple as: >>> import em, time >>> myOutput = """\ ... ... The total cost is @invoice.total. ... ... This order will be shipped to @invoice.contact at the following ... address: ... ... @invoice.address ... ... This order was generated at @time.ctime() ... """ >>> >>> class Invoice: pass ... >>> invoice = Invoice() >>> invoice.total = "$123.45" >>> invoice.contact = "Jack McCoy" >>> invoice.address = "1 Police Plaza\nNew York City, NY" >>> print em.expand(myOutput, globals()) The total cost is $123.45. This order will be shipped to Jack McCoy at the following address: 1 Police Plaza New York City, NY This order was generated at Thu Mar 6 18:41:58 2008 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There's a reason why we / Keep chasing morning -- Sandra St. Victor From samuel.progin at gmail.com Sun Mar 2 10:55:23 2008 From: samuel.progin at gmail.com (Sam) Date: Sun, 2 Mar 2008 07:55:23 -0800 (PST) Subject: Keeping the console window References: <62vs0iF24tv6jU1@mid.individual.net> Message-ID: <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> You may use python in interactive mode: $ python -i yourScript.py Or use a blocking readline: $ cat yourScript.py import sys sys.stdin.readline() ++ Sam From castironpi at gmail.com Mon Mar 3 22:14:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 19:14:12 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: <51a14a19-a116-44b7-b94b-c3a0ef6dba54@i29g2000prf.googlegroups.com> On Mar 3, 8:22?pm, "Daniel Fetchinson" wrote: > > What are metaclasses? > > http://www.google.com/search?q=python+metaclass > > HTH, > Daniel Not satisfied. http://en.wikipedia.org/wiki/Metaclass#Python_example That's a limitation. The constructor can omit the superclass call, but it can't have keyword arguments, and can't use AttributeInitType.__call__ with positionals. Subclass AttributeInition, decorate __init__, or decorate class. From gagsl-py2 at yahoo.com.ar Tue Mar 4 22:01:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 01:01:32 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: En Wed, 05 Mar 2008 00:30:26 -0200, escribi?: > On Mar 4, 8:11?pm, "Gabriel Genellina" wrote: >> En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: >> >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it >> >> is it makes it. >> >> >>>> from types import FunctionType, MethodType >> >>>> class A( FunctionType ): pass >> > ... >> > Traceback (most recent call last): >> > ? File "", line 1, in >> > TypeError: type 'function' is not an acceptable base type >> >> Use delegation instead of inheritance. This class is almost ? >> indistinguishable from a true function (when used as a method): [... long interactive example ...] > I actually don't believe you-- bar is not bound to an instance when P > is initialized... er, instantiated. However, the evidence indicates > my belief mechanism is faulty... and rather conclusively at that. > If P calls __get__( you ), is p a > gotcha? I didn't cheat, that was an actual Python interactive session. So you'll have to formulate a new theory taking into account the new facts... or read how the descriptor protocol works http://www.python.org/doc/newstyle/ I don't understand your last sentence. -- Gabriel Genellina From castironpi at gmail.com Tue Mar 11 15:49:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 12:49:04 -0700 (PDT) Subject: mulithreaded server References: <0e845694-2788-43e2-b88b-86bbbbe3c7c0@e23g2000prf.googlegroups.com> Message-ID: <0da45d77-65c8-4de2-8b70-dd22a7a6998b@e10g2000prf.googlegroups.com> > > >In the above program, why there is an unhandeled exception ??? > > > Just a guess. You should really include the traceback when you ask a > > question like this. > > It's not a traceback error. It's an unhandeled exception. Have a look at this: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5cbf90133a6ffaca/ It gives you a console with several threads running that you send functions to call to. Then it connects to a socket on one of them, serving on the other. From guillermo.listas at googlemail.com Sun Mar 9 08:20:41 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Sun, 9 Mar 2008 05:20:41 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> >A protocol is just an interface that an object agrees to implement. In >your case, you would state that every object stored in your special >dict must implement the to_tagged_value method with certain agreeable >semantics. Hm... I've searched about the implementation of protocols and now (I believe) I know how to implement the iterable protocol, for instance, but have no clue about how to define my own... I'm surely not thinking the right way, but I don't seem to be able to wrap my head around the implementation details of "custom" protocols... Is it just a matter of extending the different object classes (dict, list, tuple...)? Where do you put the interface/protocol code? :-? Regards, Guillermo From castironpi at gmail.com Mon Mar 17 18:43:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 15:43:15 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> Message-ID: <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> On Mar 17, 8:16?am, "Gabriel Genellina" wrote: > En Sun, 16 Mar 2008 22:27:28 -0200, escribi?: > > > Specifically, before the prompts. ?Where does the prompt write come > > from; why doesn't it honor my settings of sys.stdout and sys.stderr? > > The interactive interpreter uses directly the C predefined streams stdout ? > and stderr. Can I allocate a second console window, so I can place certain output to that directly, and leave the original streams alone? I tried some things in subprocess (Py 3a3 /WinXP) but they failed. I don't know if it's supposed to be possible though, so I didn't press very hard or keep the code. If it is, I can go repro where it went south. Is it? From francois.petitjean at bureauveritas.com Thu Mar 6 12:28:17 2008 From: francois.petitjean at bureauveritas.com (francois.petitjean at bureauveritas.com) Date: Thu, 6 Mar 2008 18:28:17 +0100 Subject: How to clear a list (3 ways). Message-ID: Consider the following code : #!/usr/bin/env python # -*- coding: latin_1 -*- """ container.py how to clear a container """ class Container(object): def __init__(self): self.elts = {} self.parts = [] def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts = [] # (1) # self.parts[:] = [] # (2) # del self.parts[:] # (3) def __len__(self): return len(self.parts) def add_predicate(self, part): """return True if part should be added (to override)""" return True def add(self, part): """return True if part is added""" res = self.add_predicate(part) if res: self.parts.append(part) self.elts[str(part)] = part # or wahtever return res def replace_parts(self, values): """return True if all values are added/replaced""" acceptable = all(map(self.add_predicate, values)) # FIXME itertools.imap ? if not acceptable: return acceptable self.parts[:] = values # TODO elts return acceptable Container1 = Container class Container2(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts[:] = [] # (2) class Container3(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) del self.parts[:] # (3) Solution (1) is somewhat broken (see the test_container.rst hereafter) but often used. For instance in configobj we have def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] self.comments = {} self.inline_comments = {} self.configspec = {} What idiom do you use (and prefer) ? test_container.rst can be used like this : >>> import doctest >>> doctest.testfile('test_container.rst', encoding='latin_1') (nfails, ntests) is printed. =================== test_container.rst =================== >>> from container import Container1, Container2, Container3 >>> cont1 = Container1() >>> cont1.add(1) True >>> cont1.add(2) True >>> cont1.add(3) True >>> parts = cont1.parts >>> parts [1, 2, 3] The client has cached the parts attribute. Solution (1) is not robust, is the parts attribute in the public API ? >>> cont1.clear() >>> parts [1, 2, 3] >>> cont1.parts, parts ([], [1, 2, 3]) We now have two different objects. >>> cont2 = Container2() >>> cont2.add(21) True >>> cont2.add(22) True >>> cont2.add(23) True >>> parts2 = cont2.parts >>> parts2 [21, 22, 23] >>> cont2.clear() >>> parts2 [] >>> cont1.parts, parts ([], [1, 2, 3]) >>> cont3 = Container3() >>> cont3.add(31) True >>> cont3.add(32) True >>> parts3 = cont3.parts >>> cont3.add(33) True >>> parts3 [31, 32, 33] >>> cont3.clear() >>> parts3 [] Test de replace_parts >>> cont3 = Container3() >>> len(cont3) 0 >>> parts3 = cont3.parts >>> cont3.add(30) True >>> parts3 [30] >>> cont3.replace_parts( (31, 32, 33) ) True >>> parts3 [31, 32, 33] >>> Regards. NOTICE: This message contains information which is confidential and the copyright of our company or a third party. If you are not the intended recipient of this message please delete it and destroy all copies. If you are the intended recipient of this message you should not disclose or distribute this message to third parties without the consent of our company. Our company does not represent, warrant and/or guarantee that the integrity of this message has been maintained nor that the communication is free of virus, interception or interference. The liability of our company is limited by our General Conditions of Services. Nota : Ce message contient des informations confidentielles propri?t? de notre soci?t? et/ou d'un tiers. Si vous n??tes pas parmi les destinataires d?sign?s de ce message, merci de l'effacer ainsi que toutes ses copies. Si vous ?tes parmi les destinataires d?sign?s de ce message, pri?re de ne pas le divulguer ni de le transmettre ? des tiers sans l?accord de notre soci?t?. Notre soci?t? ne peut garantir que l?int?grit? de ce message a ?t? pr?serv?e ni que la pr?sente communication est sans virus, interception ou interf?rence. La responsabilit? de notre soci?t? est limit?e par nos Conditions G?n?rales de Services. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Thu Mar 13 11:55:21 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 13 Mar 2008 08:55:21 -0700 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: k.i.n.g. wrote: > I think I am not clear with my question, I am sorry. Here goes the > exact requirement. > > We use dd command in Linux to create a file with of required size. In > similar way, on windows I would like to use python to take the size of > the file( 50MB, 1GB ) as input from user and create a uncompressed > file of the size given by the user. > > ex: If user input is 50M, script should create 50Mb of blank or empty > file You mean all zero bytes? Python cannot guarantee that the system will not compress such a file. For testing data transfer rates, random data is a usually a better choice. -- --Bryan From n.s.buttar at gmail.com Fri Mar 7 04:08:14 2008 From: n.s.buttar at gmail.com (Navtej Singh) Date: Fri, 7 Mar 2008 14:38:14 +0530 Subject: Python GDB Wrapper In-Reply-To: References: <47d0f228$0$17725$9b622d9e@news.freenet.de> Message-ID: <1090e4100803070108j7599f90ch26affb6c1d481d20@mail.gmail.com> Raja, Check this http://fusil.hachoir.org/trac/wiki/Ptrace [gdb.py] On Fri, Mar 7, 2008 at 2:11 PM, Raja wrote: > On Mar 7, 1:21 pm, Raja wrote: > > Hi All, > > Thanks for replies. Daniel- I am looking at just a wrapper > > around GDB. I dont want to emulate the functionalities of GDB but > > instead use them in python scripting. > > Martin - Misc/gdbinit looks promising. Thanks a lot. > > > > Thanks, > > Raja. > > > > On Mar 7, 12:43 pm, "Martin v. L?wis" wrote: > > > > > > Has anyone does this before ? Even some basic idea or code as to how > > > > to proceed would be great. > > > > > Have you seen Misc/gdbinit? > > > > > Regards, > > > Martin > > Hi All, > Marting- I looked at the Misc/gdbinit but what I want is a Python > module which wraps around GDB and exposes its functionality, which has > some methods in it like pystack to which if I give the arguments as > program name and arguments displays the stack trace of that particular > program . > > Thanks, > Raja. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Wed Mar 12 10:52:03 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 12 Mar 2008 15:52:03 +0100 Subject: agg (effbot) In-Reply-To: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> Message-ID: <63q90kF268j23U1@mid.uni-berlin.de> fraleysinger at gmail.com wrote: > Downloaded to Knoppix 5.1: > : > aggdraw-1.2a3-20060212.tar.gz > > Followed README. Wouldn't compile. [...] Try shegabittling the frotz first. If that doesn't help, please post the output of the compile command that threw the error. -- Gerhard From Robert.Bossy at jouy.inra.fr Fri Mar 7 10:39:21 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 07 Mar 2008 16:39:21 +0100 Subject: problem with join In-Reply-To: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: <47D161A9.7090004@jouy.inra.fr> nodrogbrown wrote: > hi > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', > os.path.join() http://docs.python.org/lib/module-os.path.html#l2h-2185 vs. string.join() http://docs.python.org/lib/node42.html#l2h-379 RB From miki.tebeka at gmail.com Wed Mar 12 18:30:48 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 12 Mar 2008 15:30:48 -0700 (PDT) Subject: How to parse this timestamp? References: Message-ID: <06baa795-ad19-4c80-ad86-889f9a0701f8@s37g2000prg.googlegroups.com> Hello, > [19-Aug-2007 07:38:43+216ms NZST] > > How can I parse them? ?I don't see any way to build a strftime() > format string that can handle the +216ms part. The best I can see is > tearing it all apart with a regex, but I'm trying to avoid that pain > if I can. > > (PS: I have no clue why google groups thinks it should put > "gnu.gcc.help" on the from line) Just zap the end and use time.strptime: >>> s = '19-Aug-2007 07:38:43+216ms NZST' >>> strptime(re.sub("\+\d{3}ms [A-Z]{4}", "", s), "%d-%b-%Y %H:%M:%S") (2007, 8, 19, 7, 38, 43, 6, 231, -1) >>> HTH, -- Miki http://pythonwise.blogspot.com From sjmachin at lexicon.net Tue Mar 25 08:00:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Mar 2008 05:00:08 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <534cd01c-3d49-4dd8-ba04-71551cdd46d3@d21g2000prf.googlegroups.com> On Mar 25, 10:44 pm, Tzury Bar Yochay wrote: > given two classes: > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = Foo.getid() > b = self.id > return '%d.%d' % (a,b) > > While my intention is to get 1.2 I get 2.2 > I would like to know what would be the right way to yield the expected > results Post the code that you actually executed. What you have shown lacks the code to execute it ... but the execution will fail anyway: a = Foo.getid() TypeError: unbound method getid() must be called with Foo instance as first argument (got nothing instead) From fredrik at pythonware.com Sun Mar 30 12:45:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Mar 2008 18:45:51 +0200 Subject: "Soup Strainer" for ElementSoup? In-Reply-To: <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> <47e87a88$0$36376$742ec2ed@news.sonic.net> <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> Message-ID: erikcw wrote: > I'm parsing real-world HTML with BeautifulSoup and XML with > cElementTree. > > I'm guessing that the only benefit to using ElementSoup is that I'll > have one less API to keep track of, right? Or are there memory > benefits in converting the Soup object to an ElementTree? It's purely an API thing: ElementSoup loads the entire HTML file with BeautifulSoup, and then uses the resulting BS data structure to build an ET tree. The ET tree doesn't contain cycles, though, so you can safely pull out the strings you need from ET and throw away the rest of the tree. > Any idea about using a Soup Strainer with ElementSoup? The strainer is used when parsing the file, to control what goes into the BS tree; to add straining support to ES, you could e.g. add a parseOnlyThese option that's passed through to BS. From __peter__ at web.de Mon Mar 31 06:15:21 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Mar 2008 12:15:21 +0200 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: George Sakkis wrote: > On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote: >> Steven D'Aprano wrote: >> > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: >> >> >> Second try: >> > ... >> >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing >> >> with each call. But it's the only way I could find, at least without >> >> changing the code template used by timeit. >> >> > Eeek. Talk about namespace pollution. >> >> > Thanks for the effort, but if that's the only solution, I think the >> > solution is worse than the problem! >> >> > Perhaps it's time for me to take a different approach. >> >> [snip] >> >> Maybe the following enhancement of timeit would be worthwhile? > > [snip] > > > That would be great. I sometimes avoid timeit altogether because > setting up the environment is so cumbersome. Can you post the patch to > bugs.python.org so it doesn't get lost ? Looking into http://svn.python.org/view/python/trunk/Lib/timeit.py?rev=54953&view=markup I discovered that the Python developers took a different approach and timeit now allows callables for setup and statement: >>> def f(): print 42 ... >>> timeit.Timer(f).repeat(1, 1) 42 [3.3855438232421875e-05] So my patch is probably a case of instant obsolescence... Peter From justjpm at aol.com Sat Mar 22 09:38:41 2008 From: justjpm at aol.com (Jim) Date: Sat, 22 Mar 2008 06:38:41 -0700 (PDT) Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> <13u3660kfnhq412@corp.supernews.com> <74cdd195-2bfa-4548-a16e-bf14c6b07b50@p73g2000hsd.googlegroups.com> <13u5ra4fdbp7235@corp.supernews.com> Message-ID: On Mar 20, 7:03 pm, Steven D'Aprano wrote: > On Thu, 20 Mar 2008 10:26:14 -0700, Jim wrote: > > The program is my first and I'm not a programmer so it will take me some > > time to get your recommendation to work. So far the program runs after I > > added code based on your example but the program still aborts and none > > of the code ("Temporary failure, Skip/Halt/try Again?" or "Unknown > > response, boo hiss to you!") in your example is displayed. > > Try replacing the line: > > exceptURLError, e: > > with: > > except urllib2.URLError, e: > > and see if that helps. > > -- > Steven Steven, Got it to work with your example see code below. The process continued bypassing the records when exceptions occurred. My process displayed 'print here 1' then 'print here 4' and continued process with next record without aborting. What should be displayed, if anything, with the line "response = raw_input("Temporary failure, Skip/Halt/try Again?")" as I didn't see anything? Thanks for your help Jim Code: except urllib2.URLError, e: print "here 1" if e.errno == 10053: response = raw_input("Temporary failure, Skip/Halt/try Again?") response = response.lower().strip() if response in ('h', 'halt'): print "here 2" break elif response in ('a', 'again', 't', 'try', 'try again'): print "here 3" continue elif response in ('', 's', 'skip'): print "here 4" lines -= 1 continue else: print "Unknown response, boo hiss to you!" raise From francois.petitjean at bureauveritas.com Fri Mar 7 06:39:05 2008 From: francois.petitjean at bureauveritas.com (francois.petitjean at bureauveritas.com) Date: Fri, 7 Mar 2008 12:39:05 +0100 Subject: How to clear a list (3 ways). Message-ID: (second try with an enhanced version) Executive summary : What idiom do you use for resetting a list ? lst = |] # (1) lst[:] = [] # (2) del lst[:] # (3) Consider the following code : #!/usr/bin/env python # -*- coding: latin_1 -*- """ container.py how to clear a container """ class Container(object): def __init__(self): self.elts = {} self.parts = [] def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts = [] # (1) # self.parts[:] = [] # (2) # del self.parts[:] # (3) def __len__(self): return len(self.parts) def add_predicate(self, part): """return True if part should be added (to override)""" return True def add(self, part): """return True if part is added""" res = self.add_predicate(part) if res: self.parts.append(part) self.elts[str(part)] = part # or wahtever return res def replace_parts(self, values): """return True if all values are added/replaced""" acceptable = all(map(self.add_predicate, values)) # FIXME itertools.imap ? if not acceptable: return acceptable self.parts[:] = values # TODO elts return acceptable Container1 = Container class Container2(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts[:] = [] # (2) class Container3(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) del self.parts[:] # (3) Solution (1) is somewhat broken (see the test_container.rst hereafter) but often used. For instance in configobj we have def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] self.comments = {} self.inline_comments = {} self.configspec = {} Solution (2) does not suffer the same problem, and (3) has the advantage of not building an empty list. What idiom do you use (and prefer) ? test_container.rst can be used like this : >>> import doctest >>> doctest.testfile('test_container.rst', encoding='latin_1') (nfails, ntests) is printed. =================== test_container.rst =================== >>> from container import Container1, Container2, Container3 >>> cont1 = Container1() >>> cont1.add(1) True >>> cont1.add(2) True >>> cont1.add(3) True >>> parts = cont1.parts >>> parts [1, 2, 3] The client has cached the parts attribute. Solution (1) is not robust, is the parts attribute in the public API ? >>> cont1.clear() >>> parts [1, 2, 3] >>> cont1.parts, parts ([], [1, 2, 3]) We now have two different objects. >>> cont2 = Container2() >>> cont2.add(21) True >>> cont2.add(22) True >>> cont2.add(23) True >>> parts2 = cont2.parts >>> parts2 [21, 22, 23] >>> cont2.clear() >>> parts2 [] >>> cont1.parts, parts ([], [1, 2, 3]) >>> cont3 = Container3() >>> cont3.add(31) True >>> cont3.add(32) True >>> parts3 = cont3.parts >>> cont3.add(33) True >>> parts3 [31, 32, 33] >>> cont3.clear() >>> parts3 [] Test de replace_parts >>> cont3 = Container3() >>> len(cont3) 0 >>> parts3 = cont3.parts >>> cont3.add(30) True >>> parts3 [30] >>> cont3.replace_parts( (31, 32, 33) ) True >>> parts3 [31, 32, 33] >>> Regards. NOTICE: This message contains information which is confidential and the copyright of our company or a third party. If you are not the intended recipient of this message please delete it and destroy all copies. If you are the intended recipient of this message you should not disclose or distribute this message to third parties without the consent of our company. Our company does not represent, warrant and/or guarantee that the integrity of this message has been maintained nor that the communication is free of virus, interception or interference. The liability of our company is limited by our General Conditions of Services. Nota : Ce message contient des informations confidentielles propri?t? de notre soci?t? et/ou d'un tiers. Si vous n??tes pas parmi les destinataires d?sign?s de ce message, merci de l'effacer ainsi que toutes ses copies. Si vous ?tes parmi les destinataires d?sign?s de ce message, pri?re de ne pas le divulguer ni de le transmettre ? des tiers sans l?accord de notre soci?t?. Notre soci?t? ne peut garantir que l?int?grit? de ce message a ?t? pr?serv?e ni que la pr?sente communication est sans virus, interception ou interf?rence. La responsabilit? de notre soci?t? est limit?e par nos Conditions G?n?rales de Services. -------------- next part -------------- An HTML attachment was scrubbed... URL: From musiccomposition at gmail.com Mon Mar 10 22:47:59 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 10 Mar 2008 19:47:59 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: <250c1e21-7a49-4a94-8752-e1c69067d614@n36g2000hse.googlegroups.com> On Mar 10, 2:11 pm, Stefan Behnel wrote: > Malcolm Greene wrote: > >> My personal experience with wxPython has its ups and downs. Specifically > >> when it comes to crashes, I wouldn't bet my life on it. > > > I'm new to Python and getting ready to build a small client based > > application intended to run on Windows and Linux. I was planning on using > > wxPython until I saw your comment above. > > Just to make this sound a bit less like FUD: my last experience with wxPython > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > in a project, which crashed a bit too often to do real work with it - and with > crashing I mean crashing Python, not just showing us its blank traceback. So > this was definitely a problem either in wxWindows or in wxPython. > > I have no idea how well it works today, but this has definitely forged my > opinion on wxPython. > > > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > > or tips on where I can find out more about wxPython/wxWidget problems? > > The only other GUI library I used was PyQT3. To me, it has proven to be very > stable, pretty easy to use and feature rich. And from what I read about it, > PyQT4 is supposed to be another lot better and has removed the few API quirks > I found at the time (AFAIR, it finally returns plain Python strings from the > API, for example). No, it still returns QStrings, so it doesn't break tons of code. I just always convert it to unicode if I'm going to keep the string around. > > Stefan From jeffrey at fro.man Thu Mar 27 11:04:43 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 27 Mar 2008 08:04:43 -0700 Subject: Is subprocess.Popen completely broken? References: Message-ID: <13undsbqop54h4b@corp.supernews.com> Skip Montanaro wrote: > I am trying to replace os.system calls with subprocess.Popen. ?This simple > example fails miserably: > >>>> proc = subprocess.Popen ("ls /tmp") Popen expects a list of program arguments. When passed a single string instead of a list, as in your example, it assumes that the string is the command, and looks for an executable named "ls /tmp", which of course does not exist. Split your command into a list of separate parameters, with the executable as the first parameter, and it will work: >>> subprocess.Popen(['ls', '/tmp']) >>> (ls output here) Jeffrey From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:53:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:53:57 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> <75c10b67-c971-4db4-be13-26cafd24e9d2@d4g2000prg.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 00:39:58 -0300, escribi?: > First, thanks for the help. You have solved one problem but created a > new one. Isn't that always how it works? Ouch - yes, sometimes :( > So I copied over the dir, and now I get this error when trying to > import simplejson: > > > The following error occurred while trying to extract file(s) to the > Python egg > cache:[error messages snipped] > So I went looking for that egg...the following exists in my frameworks > dir: > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > I hate eggs...I am stuck again. Any ideas? I'd remove the egg and all references to it from easy_install.pth, and use the simplejson directory from the source distribution (.tar.gz), as I suggested on a previous message. -- Gabriel Genellina From ptmcg at austin.rr.com Mon Mar 24 23:22:35 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 20:22:35 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> <34b46ea7-7c87-4742-9d67-0a39e5daf983@e23g2000prf.googlegroups.com> Message-ID: <4e3f9a3d-bf3f-479e-a00d-37a00f95133e@m44g2000hsc.googlegroups.com> On Mar 24, 7:56?pm, Tess wrote: > > Anyhow, a simple regex took care of the issue in BS: > > for i in soup.findAll(re.compile('^p|^div'),align=re.compile('^center| > ^left')): > ? ? print i > But I thought you only wanted certain combinations: "My goal is to extract all elements where the following is true:

and

." Wont this solution give you false hits, such as

and

? -- Paul From gagsl-py2 at yahoo.com.ar Sat Mar 15 05:11:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 07:11:20 -0200 Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Message-ID: En Fri, 14 Mar 2008 17:23:14 -0200, Amit Gupta escribi?: > On Feb 20, 8:51 pm, Miki wrote: >> Hello Amit, >> >> > python testname.py : the unitests runs as usual and I get the >> > following results: >> > ---------------------------------------------------------------------- >> > Ran 2 tests in 0.024s >> >> > OK >> > -------------------------------------------------------------------- >> >> > However, if I do "python -mpdbtestnames.py": I get >> > ython -mpdbtestnames.py> /s/nd6/amit/pyiglu/testnames.py(1)() >> >> > -> importunittest >> > (Pdb) c >> >> > ---------------------------------------------------------------------- >> > Ran 0 tests in 0.000s >> > > So What do I do, if my testcase if failing because of an uncaught > exception and I want to run it in pdb. Run your script with python -i testname.py If an exception occur, you'll get the Python prompt. Execute: py> import pdb py> pdb.pm() to enter pdb "post-mortem". -- Gabriel Genellina From waldemar.osuch at gmail.com Thu Mar 27 03:18:55 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Thu, 27 Mar 2008 00:18:55 -0700 (PDT) Subject: How to convert latex-based docs written with Python 2.5 to 2.6 framework References: Message-ID: On Mar 26, 1:37 pm, Michael Str?der wrote: > HI! > > I had a look on how Doc/ is organized with Python 2.6. There are files with > suffix .rst. Hmm... > > I'm maintaing existing docs for python-ldap which I might have to convert to > the new concept in the long run. What's the recommended procedure for doing > so? Any pointer? > > Ciao, Michael. I found the original python docs converter here: http://svn.python.org/projects/doctools/converter/ Unfortunately it is very specific to the Python docs :) I did try to run it on python-ldap .tex files and I was partially successful. It has produced a skeleton of the docs in the new format. After couple of hours of manual conversion I got far enough to actually see some results. Whatever I did is definitely not in finished state but it could be a start. Send me an off-line email if you are interested in what I have got so far. Waldemar From gagsl-py2 at yahoo.com.ar Sun Mar 2 23:09:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 02:09:13 -0200 Subject: How to subclass a built-in int type and prevent comparisons References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: En Fri, 29 Feb 2008 19:00:06 -0200, Bronner, Gregory escribi?: > I'm trying to create a type-safe subclass of int (SpecialInt) such that > instances of the class can only be compared with ints, longs, and other > subclasses of SpecialInt -- I do not want them to be compared with > floats, bools, or strings, which the native int implementation supports. > > Obviously, I could overload __lt_, __eq__, __le__, etc, and write a > bunch of boilerplate code. > > Should this code throw an exception if the types are not comparable? > What would I lose by doing that? > > def __gt__(self, other): > if(other is self): > return False > if(self.__isComparable(other)): > return int(self)>int(other) > else: > raise ValueError(str(self) +" and "+ str(other) > +" are not comparable") I think that the easiest way is to write __cmp__ similar to your code above, and then redefine __gt__, __ge__ etc based on that. __gt__ = lambda self, other: self.__cmp__(other)>0 Note that you have to override a lot of methods too; if x is a SpecialInt instance, abs(x) or x+1 will return a plain integer instead. > Is this code likely to be efficient? Unless you implement the above in a C extension, certainly it will run much slower than the original int implementation. But measure how much this is going to affect you. -- Gabriel Genellina From paul at boddie.org.uk Sun Mar 30 14:32:05 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Mar 2008 11:32:05 -0700 (PDT) Subject: Licensing References: Message-ID: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> On 29 Mar, 20:24, DS wrote: > I'm pretty sure this is the wrong place to ask, but I'm hoping someone > will point me in the right direction. > > I'm getting ready to publish a first open-source project written in > python. I am planning to use GPLas the license. However, in my code, > there is a function that I like from Python Cookbook. I would like to > use it, although I could certainly write a less elegant version that > would do the same thing. Note that the Python Cookbook says this about licensing: "Except where otherwise noted, recipes in the Python Cookbook are published under the Python license." The link is incorrect, but I presume they mean this licence: http://www.python.org/psf/license/ It's generally not recommended to use this licence for anything other than Python because it mentions the need to reproduce the Python copyright statement in derived works, which would be nonsense for anything which isn't the Python distribution. However, one can infer that the copyright notice specific to the software concerned should be reproduced, and this is what the original CWI licence says. Of course, if a different licence is mentioned on the specific recipe you're using, you have to observe the terms mentioned in that licence instead. > So, my options appear to be: > 1. Don't use it. > 2. Use it with no comment -- that doesn't seem right. > 3. Use it with remarks in the code that acknowledge the source. > 4. Provide a separate licensing page for that function > along with the GPL for my code. > > What is the appropriate course of action here? I'm thinking #3 is > probably ok. How do others deal with this in an honorable way? In the > book, it appears that they are saying they don't really care unless > there is some massive use. You just need to do what's necessary to satisfy the licence applied to the code you're using. If that's the Python licence, I would imagine that reproducing the copyright statement and licence details would be sufficient, even if your own work is GPL-licensed. What I've done when I've released work which incorporates other work (itself available under a permissive licence) is to include the copyright statements and the licence text for that other work, but I've made it clear in the licensing information that the derived work (my code incorporating the other code) is available under the specific licence I've chosen, noting that the other work was made available under a different licence. So I suppose that #4 is the closest, but you should be able to assert that the entire work is GPL-licensed unless the recipe isn't licensed in a GPL-compatible way, which would open up a range of other issues that you hopefully won't have to deal with. ;-) Paul P.S. This isn't anything close to legal advice, so please take other opinions into account. ;-) From jeff at schwabcenter.com Fri Mar 7 12:11:57 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 07 Mar 2008 09:11:57 -0800 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: K Viltersten wrote: > I've been recommended reading of: > http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i need to get elaborated. > > > 1. When writing English, Strunk and White apply. > > Where can i download it? Am i actually > expected to read the whole book? It's a short book, and worth your time. Searching does turn up free downloads, but I recommend the illustrated version (of which I own a copy). http://www.libraryshop.org/elofstilbywi.html > How many people actually do aply it? The problem is how many people don't. > 2. You should use two spaces after a sentence-ending period. > > For heavens sake, why? I've always been obstructed by the double blanks > but tolerated them. Now, that i read that > it actually is a recommendation, i need to ask about the purpose. (a) It makes the ends of sentences more visually obvious. (b) It makes text easier to parse reliably from scripts. (c) Some text-editors can navigate such sentences out of the box, whereas others cannot. (I recall this limitation with Emacs' text-editing major mode, though it may have been fixed since then; I switched to Vim about five years ago.) From keios.titan at gmail.com Thu Mar 6 14:41:57 2008 From: keios.titan at gmail.com (keios.titan at gmail.com) Date: Thu, 6 Mar 2008 11:41:57 -0800 (PST) Subject: Exploring Attributes and Methods References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: <67ad6ef7-5cbd-48d4-89cb-580e865c73f3@e10g2000prf.googlegroups.com> On Mar 7, 12:30 am, "Terry Reedy" wrote: > wrote in message > > news:6018ff8f-3372-42c2-9a2e-5ca996744d5b at e6g2000prf.googlegroups.com... > | Hi, > | Is there a python command that allows me to extract the names (not > | values) of the attributes of a class. > | > | example > | > | Class Sample: > | fullname = 'Something' > | > | How can I know that this class has an attribute called 'fullname'? > > >>> class C: a = 1 > >>> dir(C) > > ['__doc__', '__module__', 'a'] Thank You From DustanGroups at gmail.com Thu Mar 13 18:39:51 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 13 Mar 2008 15:39:51 -0700 (PDT) Subject: This actually works. References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> Message-ID: <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> On Mar 13, 3:16 pm, troyj1... at gmail.com wrote: > not self.believe > programming.screw() > > self.serious; this.works > > make_money(EASY) > anyone.can_do(this) you.screw() self.thank(God, encapsulation) not self.want_to_know(you.screw.func_code) programming.is_good From rridge at caffeine.csclub.uwaterloo.ca Wed Mar 19 13:15:08 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 19 Mar 2008 13:15:08 -0400 Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> Message-ID: Godzilla wrote: >But the time.clock() sometimes return a value of between -3.5 to -4.5 >seconds backward. There are race conditions in your code. In between the time you execute "curTime = time.clock()" and calculate "curTime - self.timeStamp" in one thread, the other thread can execute "self.timeStamp = time.clock()". It's the only way your example program can print a negative "Actual Elapsed Time" value. The race condition seems unlikely, and it's hard to explain how this could result in it printing a value in the range of -3.5 to -4.5. However, a race condition occuring between the two evaluations of "curTime - self.timeStamp" is the only way your example program could print a negative value. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From morse at edoug.org Fri Mar 14 11:03:35 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 14 Mar 2008 15:03:35 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Hi, Well, my attempt to not use the --skip-archive option didn't get very far, as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. I'm guessing that they can't be in library.zip for a reason (i.e., they are DLL files, essentially, and thus must be readily available to be loaded into memory). Is there a work-around for this, then? That is, is there a way to either (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and umath.pyd files or (b) perhaps rename one set of the .pyd files -- say the numpy/core versions -- to say multiarray2.pyd and umath2.pyd, and then manual create the "stub"-like .pyc files that py2exe creates to point to these alternate .pyd files and then place these stubs in library.zip/numpy/core? Or am I just hoping for too much here and am going to be stuck with using the --skip-archive option? Thanks, Doug On Fri, 14 Mar 2008 14:37:32 +0000 (UTC), Doug Morse wrote: > Peter, > > Genius! You nailed it -- thanks! > > py2exe is apparently getting confused by the fact that packages "Numeric" > ... > > > So, my next step will be to try to not use the --skip-archive option and > then make these same modifications regarding multiarray.pyd and umath.pyd > to the py2exe-generated library.zip file and see if I can get things > running that way as well (and in so doing reduce my "dist" directory by > about 10mg). I may also try creating a dist/Numeric subdirectory and > moving dist/multiarray.pyd and dist/umath.pyd to this dist/Numeric > subdirectory -- for the goal of more accurately mirroring the actual > file/directory structure found in $PYTHONHOME/Lib/site-packages. > > From mail at hellmutweber.de Wed Mar 12 19:16:13 2008 From: mail at hellmutweber.de (Hellmut Weber) Date: Thu, 13 Mar 2008 00:16:13 +0100 Subject: Access function name from within a function Message-ID: <47D8643D.1090000@hellmutweber.de> Hi, i would liek to define an error routine which print amongs other things the name of the function from which it has been called. Having tried def foo(): print dir() and all other ideas which came to my (rather python newbie) mind. Googling too did not show me a possibility. IOW what I'm looking for is: def bar(): name = some_function(some-parameter) print name should print 'bar' Any ideas appreciated Hellmut -- Dr. Hellmut Weber mail at hellmutweber.de Degenfeldstra?e 2 tel +49-89-3081172 D-80803 M?nchen-Schwabing mobil +49-172-8450321 please: No DOCs, no PPTs. why: tinyurl.com/cbgq From hdante at gmail.com Sun Mar 30 00:58:29 2008 From: hdante at gmail.com (hdante) Date: Sat, 29 Mar 2008 21:58:29 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Message-ID: <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" wrote: > Hello, > > I am having trouble writing the code to read a binary string. I would > like to extract the values for use in a calculation. > > Any help would be great. I'm too lazy to debug your binary string, but I suggest that you completely throw away the binary file and restart with a database or structured text. See, for example: http://pyyaml.org/wiki/PyYAML If you have some legacy binary file that you need to process, try creating a C program that freads the binary file and printfs a text equivalent. If the decision of using binary files is not yours, then > > Here is my function that takes in a string. > > def parseSequence(data, start): > > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > pos = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > return element, start, value > > else: > return element, start, value > > else: > return element, pos, value > > And, here is a sample string (I have split up and indented for > readability). There is an identifier (\xfe\xff\x00\xe0) followed by > the length of the nested values. > > '\xfe\xff\x00\xe0\x18\x02\x00\x00 -length=536 > \n0q\x00\x02\x00\x00\x001 > \n0x\x00\x02\x00\x00\x0010 > \n0\x80\x00\x02\x00\x00\x004 > \n0\xa0\x00\x02\x00\x00\x000 > \x0c0\x04\x00\xe8\x01\x00\x00 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 > \n0\x86\x00\x10\x00\x00\x00127.378510918301 > \x0c0\x06\x00\x02\x00\x00\x001 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x001.629998e-1 > \n0\x86\x00\x10\x00\x00\x0023.159729257873 > \x0c0\x06\x00\x02\x00\x00\x004 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.26285318894435 > \n0\x86\x00\x10\x00\x00\x00227.690980638769 > \x0c0\x06\x00\x02\x00\x00\x003 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.52797639111557 > \n0\x86\x00\x10\x00\x00\x00263.433384670643 > \x0c0\x06\x00\x02\x00\x00\x002 ') From darcy at druid.net Wed Mar 26 15:49:57 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 Mar 2008 15:49:57 -0400 Subject: Daylight savings time problem In-Reply-To: References: Message-ID: <20080326154957.2482469c.darcy@druid.net> On Wed, 26 Mar 2008 19:37:16 -0000 "Fabio Durieux Lopes" wrote: > I'm trying to execute some operations based on a file's time. The > file's time is actually the file's name (e.g. FILE1_20080326170558). > So I do this: > fileTimeInSecs = time.mktime(time.strptime(timeString, > "%Y%m%d%H%M")) > > timeString contains the date part of the file's name. Function > strptime returns a time_struct, but my problem is that tm_isdst is > set to 0, and when we enter daylight savings time the file's time is > off by 1 hour. This time_struct is also read only so I can't change > tm_isdst to -1. > > Anyone knows how to fix it? Use UTC. -- 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 mail at timgolden.me.uk Thu Mar 6 03:42:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Mar 2008 08:42:38 +0000 Subject: system32 directory In-Reply-To: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> Message-ID: <47CFAE7E.6030501@timgolden.me.uk> Robert Dailey wrote: > Hi, > > Is there a way to get the System32 directory from windows through python? > For example, in C++ you do this by calling GetSystemDirectory(). Is there an > equivalent Python function for obtaining windows installation dependent > paths? First thing to do when asking "How do I do X in Python under Windows?" is to stick -- python X -- into Google and you get, eg: http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html which suggests that the win32api module from the pywin32 modules has the function you need. And sure enough... Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32api >>> win32api.GetSystemDirectory () 'C:\\WINDOWS\\system32' >>> TJG From sturlamolden at yahoo.no Thu Mar 20 09:13:09 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 06:13:09 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <07618a7c-2cfc-4fc0-9ae1-067c24ef86bb@s12g2000prg.googlegroups.com> On 20 Mar, 08:39, "Daniel Fetchinson" wrote: > Thoughts anyone? I don't use tk myself, but scheduling tkinter for vaporization would be a bad idea. A lot of programs depend on it, and it doesn't look ugly anymore (the one that ship with Python still does). Would inclusion of wxPython and PyGTK in the standard library be an option? Or does LGPL prevent it? From gabriel.rossetti at mydeskfriend.com Tue Mar 18 05:55:03 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 18 Mar 2008 10:55:03 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom In-Reply-To: <1205831099.3212.18.camel@localhost.localdomain> References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <47DF9177.4050906@mydeskfriend.com> Carsten Haese wrote: > On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > >> Hello, >> >> I am reading core python python programming and it talks about using the >> idiom >> described on >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . >> >> I'm using python 2.5.1 and if I try : >> >> class MyClass(object): >> def __init__(self): >> self._foo = "foo" >> self._bar = "bar" >> >> @property >> def foo(): >> doc = "property foo's doc string" >> def fget(self): >> return self._foo >> def fset(self, value): >> self._foo = value >> def fdel(self): >> del self._foo >> return locals() # credit: David Niergarth >> >> @property >> def bar(): >> doc = "bar is readonly" >> def fget(self): >> return self._bar >> return locals() >> >> like suggested in the book (the decorator usage) I get this : >> >> >>> a=MyClass() >> >>> a.foo >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: foo() takes no arguments (1 given) >> >> but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : >> >> >>> a = MyClass() >> >>> a.foo >> 'foo' >> >> does anyone have an idea as of why this is happening? >> > > You're mixing two completely different approaches of building a > property. If that code is actually in the book like that, that's a typo > that you should mention to the author. > > The @property decorator can only be used to turn a single getter > function into a read-only attribute, because this: > > @property > def foo(...): > ... > > is the same as this: > > def foo(...): > ... > foo = property(foo) > > and calling property() with one argument builds a property that has just > a getter function that is the single argument you're giving it. > > The recipe you're referring to uses a magical function that returns a > dictionary of getter function, setter function, deleter function, and > docstring, with suitable key names so that the dictionary can be passed > as a keyword argument dictionary into the property() constructor. > However, that requires the magical foo=property(**foo()) invocation, not > the regular decorator invocation foo=property(foo). > > HTH, > > Ah, ok, I'll send him an email then, thanks for the explanation! Gabriel From graham.ashton at gmail.com Mon Mar 31 07:02:30 2008 From: graham.ashton at gmail.com (Graham Ashton) Date: Mon, 31 Mar 2008 04:02:30 -0700 (PDT) Subject: Beginner advice References: <65bfk7F2esfc1U1@mid.uni-berlin.de> Message-ID: <10dc13c3-df5a-42fc-bca5-318f890feb66@i29g2000prf.googlegroups.com> On Mar 31, 8:15?am, Paul Scott wrote: > Thanks for the feedback, now I just need some justification on the > GTK/GUI stuff - wxWidgets, GTK+ Glade or other? pyGTK is great. I used it quite heavily a year or so ago. GTK is a nice tool kit from the user's perspective too; you can make some rather attractive and usable applications with it, and the GUI builder is a boon. Obviously it integrates slightly better into it's native platform than it does Mac/Windows, but if you're targetting Ubuntu users then it's a great choice. I've never used wxWidgets in anger but I didn't take to it having used pyGTK quite extensively. I guess it just wasn't for me. Back then (things may have changed) it didn't (visually) integrate quite so well into a modern GNOME desktop either, even though it was using GTK to draw the widgets. I'd re-evaluate it if I really wanted to build a cross platform app though. From arnodel at googlemail.com Wed Mar 26 03:55:22 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 00:55:22 -0700 (PDT) Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: <69175d52-a701-40f2-9803-0e422e8d4f8f@d62g2000hsf.googlegroups.com> On Mar 25, 10:55?pm, Steven D'Aprano wrote: [...] In my haste I forgot to finish my post: > Here's an example that might help. > > class MyClass(object): > ? ? pass > > records = ["spam", "ham"] > for record in records: > ? ? # define a new function > ? ? def f(n): > ? ? ? ? return (record + " ")*n > ? ? # create a new instance > ? ? instance = MyClass() > ? ? # and dynamically add a method to it > ? ? setattr(instance, 'execute', f) > ? ? instance.execute(5) Except it only *appears* to work. What happens if were store the instances in a list and then execute them all in one go? class MyClass(object): pass records = ["spam", "ham"] instances = [] for record in records: # define a new function def f(n): return (record + " ")*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instances.append(instance) # ONLY THIS LINE CHANGED for instance in instances: instance.execute(5) Outputs: 'ham ham ham ham ham ' 'ham ham ham ham ham ' Because the name 'record' in f is bound to 'ham' after the loop. To fix this, you can for example change def f(n): ... to def f(n, record=record): ... This way, 'record' is local to f and won't change at the next iteration of the loop. -- Arnaud From exxfile at hotmail.com Mon Mar 24 14:53:24 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 11:53:24 -0700 (PDT) Subject: New to group Message-ID: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Hi Everyone I am new to programming in general although I have read alot and done alot of experimentation as well as researched afew languages namely java python and visual basic . My conclusion is that python is one of the best because it eliminates the need to learn about access modifiers and form handlers so a user can concentrate primarliy on the nuts and bolts of the language . i have come across my first exeption using randrange . The exeption is " no such attribute " in module random platform is xp home and the python build is activestate 2.5 All help much appreciated ! From spamhater at spamhaters Wed Mar 12 15:35:24 2008 From: spamhater at spamhaters (Thin Myrna) Date: Wed, 12 Mar 2008 20:35:24 +0100 Subject: Py2exe and Multi Treading problem. In-Reply-To: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> References: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> Message-ID: <47d8307c$0$12126$3b214f66@aconews.univie.ac.at> Farsheed Ashouri wrote: > NO it dont work. If I remove threading part, it works like a charm. > Any Idea? Of course it does then. Try to join the thread or do something else to prevent the non-threading part to exit prematurely. HTH Thin From andre.roberge at gmail.com Fri Mar 28 05:58:11 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Fri, 28 Mar 2008 02:58:11 -0700 (PDT) Subject: Plugins accessing parent state References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> <653q99F2e37q8U1@mid.uni-berlin.de> Message-ID: On Mar 28, 6:39 am, "hajdu... at gmail.com" wrote: > On Mar 28, 1:58 am, "Diez B. Roggisch" wrote: > > > > > hajdu... at gmail.com schrieb: > > > > Does anyone have some design ideas ( or can point me at the right > > > design pattern, because I can't find it. ) for having a plugin being > > > able to access a parent's state? > > > > For example, let's say I have a class that receives some commands. > > > When it gets a command, it checks which of the registered plugins > > > deals with that command and passes the details of the command off to > > > that plugin. So I'd end up with something like.. > > > > result = plugin.do(msg_details) > > > > Now, I want to write a plugin called "help" that loops through all the > > > registered plugins and prints out their doc strings. If all my plugin > > > is getting is the msg details, how is it supposed to get the list of > > > available plugins from the calling class? > > > > Or, for instance, let's say my class loads a configuration file that > > > lists a set of admins who can enter commands. I want the plugins, if > > > they so choose, to be able to test if the msg came from an admin, but > > > again, I'm not passing the admin list into every plugin, it's just in > > > my calling class. I could make the plugin specify an attribute for > > > itself, like "admin_only" and test for that before I pass the command > > > but what if certain parts of the plugin are to be restricted and > > > others aren't, based on the details of the command sent? > > > > Is this as simple as just passing the instance of my class to each > > > plugin? It doesn't seem like the proper thing to do, because now the > > > plugin class has the capability of accessing the whole bot's > > > interface. > > > Yes, it is simple as that. Of course you can choose *what* you pass, if > > you want to restrict that - nobody forces you to pass the whole > > plugin-manager, if that would expose properties/methods you wouldn't > > want ther. > > > But to be honest: you are thinking much to far there - after all, it's > > all *your* code, and inside one interpreter. A real isolation isn't > > available anyway. > > > So just do what fullfills the functional requirements. > > > diez > > Since I want to have a uniform call to all plugins, would it make > sense to split out the attributes that I do want to share to a > separate class and then simply create a new instance of that class and > store it in the main class? > > For instance > > ... > self.utilities = Utilities(self) > ... > plugin.do(msg,self.utilities) I would bypass the step of creating a new instance and write instead plugin.do(msg, self) thus having access to all properties/methods of the calling object. Why restrict it?... Andr? From pmc411-usenet at yahoo.com Thu Mar 20 14:07:39 2008 From: pmc411-usenet at yahoo.com (Paulo da Costa) Date: Thu, 20 Mar 2008 18:07:39 GMT Subject: Can I run a python program from within emacs? In-Reply-To: References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: Jeff Schwab wrote: > Paulo da Costa wrote: > >> People who say Emacs often mean GNU Emacs. > > That's funny; to me, Emacs usually means XEmacs. :) Which is often a cause of confusion. Paulo From chris.stromberger at gmail.com Tue Mar 4 16:10:32 2008 From: chris.stromberger at gmail.com (chris) Date: Tue, 4 Mar 2008 13:10:32 -0800 (PST) Subject: sqlite3 permission issue Message-ID: I am trying to execute an update to a sqlite3 db via a python cgi script. I can execute a select via a cgi script, but when I attempt an update, I get an "unable to open database file" error. But the error comes on the update statement, not on the connect. So the script has: conn = sqlite3.connect('db') c = conn.cursor() --we get here ok-- c.execute("insert into contact ...") <-- this statement produces the error I can run the exact same python code from the command line and it works, so it has something to do with the user that runs the cgi (apache I assume). I chmodded the db file to 666, but it did not help. Any ideas? Thanks, Chris From castironpi at gmail.com Wed Mar 26 00:27:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 21:27:15 -0700 (PDT) Subject: Prototype OO References: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> <13ujk0f9inb73c2@corp.supernews.com> Message-ID: On Mar 25, 11:24?pm, Dennis Lee Bieber wrote: > On Wed, 26 Mar 2008 06:49:57 +0800, "Delaney, Timothy (Tim)" > declaimed the following in comp.lang.python: > > > > > As an aside, having lived much of my early life on a hobby farm, I've > > often wondered to myself just what cow-orking involves ... ;) > > ? ? ? ? Probably millennia too late to ask Saruman... Solomon? From harrelson at gmail.com Fri Mar 21 18:15:16 2008 From: harrelson at gmail.com (harrelson) Date: Fri, 21 Mar 2008 15:15:16 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog Message-ID: I am trying to get the below code to work and can't quite make things happen. This is with Python 2.5.1. Dialog is doing something odd... I have tinkered with different combinations and I can't get the dialog to show properly-- it does show properly directly in the shell. Any hints? import subprocess command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" "4 this and that"' proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) stderr_value = proc.communicate()[0] print stderr_value From dickinsm at gmail.com Tue Mar 4 14:04:23 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Mar 2008 11:04:23 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: <763ea020-731a-4ca0-8be7-55430676f1b7@i7g2000prf.googlegroups.com> On Mar 4, 9:39?am, Mark Dickinson wrote: > On Mar 4, 8:46?am, NickC wrote: > > > The increased number of inaccurate answers with Decimal (31% vs 10%) > > is probably due to the fact that it is actually more precise than > > float > > I suspect it has more to do with the fact that 10 is bigger than 2, > though I'm not sure I could precisely articulate the reasons why > this matters. Indeed, a quick lunchtime back-of-the-envelope calculation suggests that precision is largely irrelevant: it's the base that matters. For randomly chosen(*) base B floats x and y, the probability that (x/y)*y == x is approximately given by 1/2 + 1/log(B) - 1/log(B)**2 + 1/B/log(B)**2 For Decimal, this gives a probability of: >>> 0.5 + 1/log(10) - 1/log(10)**2 + 1/10/log(10)**2 0.76454395459279922 while for randomly chosen floats it's the same thing with all 10s replaced by 2s: >>> 0.5 + 1/log(2) - 1/log(2)**2 + 1/2/log(2)**2 0.90201055038615952 (*) Here, randomly chosen means I'm assuming that log(x) and log(y) are independent and uniformly distributed over some largish interval. Maybe not the most obvious definition of random, but not unreasonable. (And it makes the analysis easier!) A quick check, for floats: ##### from __future__ import division from random import random from math import exp def random_float(): return exp(random()*400.-200.) def test(): x = random_float() y = random_float() return (x/y)*y == x print sum(test() for i in xrange(10**8))/10**8 ##### produces (eventually): 0.90199129 Mark From stargaming at gmail.com Wed Mar 26 13:05:48 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 26 Mar 2008 17:05:48 GMT Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: <47ea826c$0$10148$9b622d9e@news.freenet.de> On Wed, 26 Mar 2008 13:05:55 -0300, Gabriel Genellina wrote: > En Wed, 26 Mar 2008 11:12:21 -0300, waltbrad > escribi?: > >> Stumbling through Mark Lutz's "Programming Python 3rd", he gives an >> example of a program that will automatically configure environment >> settings and launch other programs. Then he gives an example of >> running this program. On his command line he types: >> >> C:\...\PP3E>Launcher.py >> >> and this begins the program. Doesn't work for me. I have to type: >> >> C:\...\PP3E>python Launcher.py >> >> Is this a typo on his part or has he configured his settings in such a >> way that the command line will automatically associate the extension >> with the program? (If so, he didn't mention this in his book). > > I think it is an option in the installer, to associate or not Python to > the .py extension. > You could reinstall Python paying attention to the options, or repair > the association as described in this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ b1d0fd05b3615057/ See also the official (development version of the) documentation with the new section "Using Python". "Using Python on Windows" covers exactly this topic: http://docs.python.org/dev/using/windows.html#executing-scripts HTH, -- Robert "Stargaming" Lehmann From sgeiger at ncee.net Fri Mar 14 13:50:40 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 14 Mar 2008 12:50:40 -0500 Subject: Thousand Seperator In-Reply-To: References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <47DABAF0.20207@ncee.net> http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/python/lib/decimal-recipes.html Eddie Corns wrote: > ewanfisher at gmail.com writes: > > >> I'm trying to find some code that will turn: >> > > >> 100 -> 100 >> 1000 -> 1,000 >> 1000000 -> 1,000,000 >> -1000 -> -1,000 >> > > >> I know that can be done using a regular expression. In Perl I would do >> something like: >> > > >> sub thousand { >> $number = reverse $_[0]; >> $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; >> return scalar reverse $number; >> } >> > > >> But I cannot find how to do this in Python. >> > > Look at the locale module. If you're producing the numbers yourself then they > get printed in that format otherwise you can convert them to numbers first. > > Eddie > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From Robert.Bossy at jouy.inra.fr Fri Mar 14 06:18:48 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 14 Mar 2008 11:18:48 +0100 Subject: Creating a file with $SIZE In-Reply-To: <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Message-ID: <47DA5108.3040902@jouy.inra.fr> Bryan Olson wrote: > Robert Bossy wrote: > >> cokofreedom at gmail.com wrote: >> >>> Robert Bossy wrote: >>> >>>> Indeed! Maybe the best choice for chunksize would be the file's buffer >>>> size... >>>> > > That bit strikes me as silly. > The size of the chunk must be as little as possible in order to minimize memory consumption. However below the buffer-size, you'll end up filling the buffer anyway before actually writing on disk. >> Though, as Marco Mariani mentioned, this may create a fragmented file. >> It may or may not be an hindrance depending on what you want to do with >> it, but the circumstances in which this is a problem are quite rare. >> > > Writing zeros might also create a fragmented and/or compressed file. > Using random data, which is contrary to the stated requirement but > usually better for stated application, will prevent compression but > not prevent fragmentation. > > I'm not entirely clear on what the OP is doing. If he's testing > network throughput just by creating this file on a remote server, > the seek-way-past-end-then-write trick won't serve his purpose. > Even if the filesystem has to write all the zeros, the protocols > don't actually send those zeros. Amen. Cheers, RB From zentraders at gmail.com Sat Mar 22 14:33:06 2008 From: zentraders at gmail.com (Zentrader) Date: Sat, 22 Mar 2008 11:33:06 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> Message-ID: <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> On Mar 22, 10:07 am, Arnaud Delobelle wrote: > On Mar 22, 4:38 pm, Zentrader wrote: > > > > if ('one', 'two') are in f: ... > > > "are" gives me an error in Python 2.5 with a "from future import *" > > statement included. What version and platform are you running. Also, > > the docs don't mention it.http://docs.python.org/ref/keywords.html > > That's because you have to do: > > from bearophile import musings > > HTH > > -- > Arnaud Thanks. I am admittedly naive and don't have any type of guard up when on this group for people who think that type of comment makes them intelligent/funny. From george.sakkis at gmail.com Sun Mar 30 18:20:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 30 Mar 2008 15:20:54 -0700 (PDT) Subject: Dispatching functions from a dictionary References: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> <7xd4pbexbp.fsf@ruckus.brouhaha.com> Message-ID: <1ec62988-4def-4fd9-85e6-0e97e26e17e0@c26g2000prf.googlegroups.com> On Mar 30, 5:06 pm, Paul Rubin wrote: > tkp... at gmail.com writes: > > RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), ...} > > This actually calls the functions random.betavariate, etc. when > initializing RVDict. If you print out the contents of RVDict you'll see > that each value in it is just a floating point number, not a callable. > > You want something like: > > RVDict = {'1': lambda: random.betavariate(1,1), > '2': lambda: random.expovariate(1), etc. In Python 2.5, you can also write this as: from functools import partial RVDict = {'1': partial(random.betavariate,1,1), '2': partial(random.expovariate,1), etc. George From miki.tebeka at gmail.com Sun Mar 9 14:26:25 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 9 Mar 2008 11:26:25 -0700 (PDT) Subject: Parse specific text in email body to CSV file References: Message-ID: <87ad5667-326b-4de2-8d8f-5f470da7353b@e25g2000prg.googlegroups.com> Hello, > I have been searching all over for a solution to this. I am new to > Python, so I'm a little lost. Any pointers would be a great help. I > have a couple hundred emails that contain data I would like to > incorporate into a database or CSV file. I want to search the email > for specific text. > > The emails basically look like this: > > random text _important text:_15648 random text random text random text > random text > random text random text random text _important text:_15493 random text > random text > random text random text _important text:_11674 random text random text > random text > ===============Date: Wednesday March 5, 2008================ > name1: 15 ? ? ? ? ? ? ? ?name5: 14 > > name2: 18 ? ? ? ? ? ? ? ?name6: 105 > > name3: 64 ? ? ? ? ? ? ? ?name7: 2 > > name4: 24 ? ? ? ? ? ? ? ?name8: 13 > > I want information like "name1: 15" to be placed into the CSV with the > name "name1" and the value "15". The same goes for the date and > "_important text:_15493". > > I would like to use this CSV or database to plot a graph with the > data. import re for match in re.finditer("_([\w ]+):_(\d+)", text): print match.groups()[0], match.groups()[1] for match in re.finditer("Date: ([^=]+)=", text): print match.groups()[0] for match in re.finditer("(\w+): (\d+)", text): print match.groups()[0], match.groups()[1] Now you have two problems :) HTH, -- Miki http://pythonwise.blogspot.com From bjourne at gmail.com Sun Mar 16 21:39:29 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Mar 2008 01:39:29 +0000 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <740c3aec0803161839l3c63ebcaw17b6e12f58422e70@mail.gmail.com> On Mon, Mar 17, 2008 at 12:32 AM, Paul Boddie wrote: > On 17 Mar, 01:09, a... at pythoncraft.com (Aahz) wrote: > > > > PyCon is what YOU make of it. If you want to change PyCon, propose a > > presentation or join the conference committee (concom) -- the latter only > > requires signing up for the pycon-organizers mailing list. > > > > This doesn't mean that we are uninterested in feedback. We love > > feedback. But there are stark limits to what we can do unless people get > > involved and push their pet projects. > > The same rules apply for most of the other Python conferences, too. > Apologies to Aahz for hijacking his rant, but for anyone interested in > enhancing the EuroPython 2008 experience, the advice is fairly > similar: join the volunteers organising the conference and make what > you want to see actually happen. For EuroPython, start here: > > http://www.europython.org/community/Volunteers I haven't been to EuroPython even when it has been fairly nearby because the entrance fee was to high. But how do you help change something like that? -- mvh Bj?rn From george.sakkis at gmail.com Thu Mar 6 15:20:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 6 Mar 2008 12:20:54 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <3ddf3ef3-529c-4a81-932a-d2dda4972704@e23g2000prf.googlegroups.com> On Mar 6, 9:27 am, Pierre Quentel wrote: > Hi, > > I would like to know if there is a module that converts a string to a > value of the "most probable type" ; for instance : > - if the string is "abcd" the value is the same string "abcd" > - string "123" : value = the integer 123 > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > = the float -1.23 > - string "2008/03/06" (the format is also locale-dependant) : value = > datetime.date(2008,03,06) > > Like in spreadsheets, special prefixes could be used to force the > type : for instance '123 would be converted to the *string* "123" > instead of the *integer* 123 > > I could code it myself, but this wheel is probably already invented Maybe, but that's a so domain-specific and easy to code wheel that it's no big deal reinventing. George From aboudouvas at panafonet.gr Thu Mar 27 11:01:12 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 08:01:12 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> <47EBB42D.9090206@behnel.de> Message-ID: <25b14b32-8fce-4e79-b236-c64fa96744e8@e23g2000prf.googlegroups.com> > If it's about "some problems", then maybe Cython is an alternative. > > http://cython.org > > Stefan Hmmm...thanks but i think Pyrex-like solution is not the ideal one. Coming from C# and having 8 years of expertise on it, i have gain a very positive thinking about jit compilers and i think that psyco (ok, a just-in-time specializer) is a more easy (and more correct) way to go that mixing 2 languages. From __peter__ at web.de Fri Mar 28 10:13:15 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Mar 2008 15:13:15 +0100 Subject: Global variables in modules... References: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> Message-ID: ttsiodras at gmail.com wrote: > With a.py containing this: > > ========== a.py =========== > #!/usr/bin/env python > import b > > g = 0 > > def main(): > global g > g = 1 > b.callb() > > if __name__ == "__main__": > main() > ========================== > > ...and b.py containing... > > ========= b.py ============= > import a, sys > > def callb(): > print a.g > ========================== > > ...can someone explain why invoking a.py prints 0? > I would have thought that the global variable 'g' of module 'a' would > be set to 1... When you run a.py as a script it is put into the sys.modules module cache under the key "__main__" instead of "a". Thus, when you import a the cache lookup fails and a.py is executed again. You end up with two distinct copies of the script and its globals: $ python -i a.py 0 >>> import __main__, a >>> a.g 0 >>> __main__.g 1 Peter From castironpi at gmail.com Sun Mar 9 22:11:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 19:11:37 -0700 (PDT) Subject: Solve a Debate References: <82ol85-0o5.ln1@darkstargames.dnsalias.net> Message-ID: > days_in_month 12: > 31 > 30 > 28 > 31 > ... > 30 > 31 > assign $days days_in_month[$month] > > This program consists of 2 operations (table jump and assignment) > and 12 values. This makes a memory consumption of 12+2 = 14 Along the same lines, you could populate the table somewhat sparsely, and goto a modulo key. You could even put functions in it: setreturn $endoftable hash month goto -0 -1 -2 jan.-> 3: setvjmp janfun -4 -5 apr.-> 6: setvjmp aprfun $endoftable Sweet! Are you stack-ops? From sjmachin at lexicon.net Thu Mar 27 18:00:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 15:00:01 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: On Mar 28, 7:37 am, Aaron Watters wrote: > > If you want fame and admiration you could fix > the arguably bug in the csv module and send > the patch to the python bugs mailing list. > However, I just had a perusal of csv.py.... > good luck :). It is *NOT* a bug in the Python CSV module. The data is the problem. The admittedly arcane way that the admittedly informal CSV writing protocol works for each field is (simplified by ignoring \n and other quotables): QUOTE = '"' DELIM = ',' if QUOTE in field: emit(QUOTE + field.replace(QUOTE, QUOTE+QUOTE) + QUOTE) elif DELIM in field: emit(QUOTE + field + QUOTE) else: emit(field) Example: database query, customer's surname recorded as O"Brien This should be written as ...,"O""Brien",... and read back as ['...', 'O"Brien', '...'] Aside: this quote-doubling caper is not restricted to CSV and not exactly an uncommon occurrence: SELECT * FROM cust WHERE surname = 'O''Brien'; A common mistake in CSV writing is to omit the quote-doubling step above. If that is done, it is impossible to recover the original contents unambiguously in all cases without further knowledge, assumptions, heuristics, or look-ahead e.g. (1) the original field had an even number of quotes or (2) the intended number of fields is known or (3) there is only one quote in the line and there are no embedded newlines ... The Python csv module emulates Excel in delivering garbage silently in cases when the expected serialisation protocol has (detectably) not been followed. Proffering fame and admiration might be better directed towards introducing a "strict" option than patching a non-existing bug (which would introduce new ones). Cheers, John From theller at ctypes.org Wed Mar 26 18:08:50 2008 From: theller at ctypes.org (Thomas Heller) Date: Wed, 26 Mar 2008 23:08:50 +0100 Subject: py2exe socket.gaierror (10093) In-Reply-To: <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> Message-ID: Knut schrieb: >> The script can't resolve the server name. Try to do it by hand using >> nslookup or even ping (you may want to add a few print statements inside >> the script to see the exact host name it is trying to connect to, in case >> it isn't what you expect) >> If you can't resolve the host name using nslookup, there is a network >> problem, not in your script. If you can resolve it, try your script >> without py2exe if possible. >> >> -- >> Gabriel Genellina > > Thank you for the quick reply Gabriel. > > I have made sure the script works fine before I exe it. > It is when I compile the program I get this error. > > I don't get how the compile changes server availability. > Could it be a firewall issue? Thomas From David.J.Anderson66 at gmail.com Mon Mar 17 23:28:35 2008 From: David.J.Anderson66 at gmail.com (David.J.Anderson66 at gmail.com) Date: Mon, 17 Mar 2008 20:28:35 -0700 (PDT) Subject: ord function problem from newbie Message-ID: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> I'm trying to convert a name into a numerical value that is not consistent with ANSCII values. In my case, I convert all to lowercase, then try to sum the value of the letters entered by the user, can't get it to add them. Here is what I have. By the way, the values I need to use is: a=1, b=2, c=3, etc... I'm trying to subtract 96 from the ANSCII value, then total. import string def main(): print "This program calculates the numeric value of a name with which" print "you could look up online as to what that value represents." print # Get name to calculate name = raw_input("Please type a name: ") small = string.lower(name) print "Here is the calculated value:" print small for ch in small: v = ord(ch)-96 print v main() Looks like this: This program calculates the numeric value of a name with which you could look up online as to what that value represents. Please type a name: David Here is the calculated value: david 4 1 22 9 4 From vvangelovski at gmail.com Wed Mar 19 11:51:38 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Wed, 19 Mar 2008 08:51:38 -0700 (PDT) Subject: url validator in python Message-ID: <7a27c19d-2e0e-4242-9054-9455f825df8f@i7g2000prf.googlegroups.com> How can I check the validity of absolute urls with http scheme? example: "http://www.example.com/something.html" -> valid "http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid From malaclypse2 at gmail.com Wed Mar 26 15:43:18 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 26 Mar 2008 15:43:18 -0400 Subject: Filtering a Python list to uniques In-Reply-To: References: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> Message-ID: <16651e80803261243i3d8b7ecam3624398db1c86dbe@mail.gmail.com> On Wed, Mar 26, 2008 at 2:50 PM, kellygreer1 wrote: > How come the Set() thing seems to work for some people and I get the > 'unhashable' error? > > How do you test for 'membership' on a dictionary? > > # where tmp is the non-unique list > # dct is a dictionary where each unique key will be tied to a count > (the value) > # for testing I was setting the count to 0 > for v in tmp: > if not v in dct: dct[v] = 0 > > # I get unhashable error here. > # Even if I write it. > > for v in tmp: > if not v in dct.keys(): dct[v] = 0 > > What am I missing? Some of the elements of tmp are unhashable. Unhashable items can't be the keys of a dictionary or members of a set. I don't think you've said anywhere in the thread what these items are, you just started out with an example of a list of integers. Do you believe the elements in tmp are integers? If so, try the following - for v in tmp: print type(v), repr(v), hash(v) and let us know what it spits out. -- Jerry From cpthomas at gmail.com Wed Mar 12 14:10:06 2008 From: cpthomas at gmail.com (Casey T) Date: Wed, 12 Mar 2008 11:10:06 -0700 (PDT) Subject: Different results when running script from IDLE versus Command Line Message-ID: <895b88e4-694d-4fee-a633-08aa8a407999@p73g2000hsd.googlegroups.com> Hi, I'm new to Python and I'm having some problems with getting different results from my script when I run it from IDLE versus just double- clicking the .py file and having it run through the command line. Basically, my script reads some CSV files, assembles a text files, then uploads that test file to an ftp site. When I run the script from IDLE, everything works fine. But when it runs from the command line, the file that gets uploaded is empty. It seems that it is creating a new file to upload, rather than using the existing file (or at least that's what I think is going on.) Below is my script. I apologize for any ugly code. Thanks for your help. import sys,os,linecache,csv,ftplib,time starttime = time.time() #******* #Summary file assembling #******* currentdir = "//folder/" reg_sum = open('reg_sum.txt','w') reg_sum.close for files in os.listdir(currentdir): reg_file = csv.reader(open(currentdir + files)) for row in reg_file: reg_sum = open('reg_sum.txt','a') reg_sum.write(",".join(row) + ',\n') reg_sum.close #******* #Summary file processing #******* coordList = [ ["F10",40.0053,-75.0927], ["T10",40.0272,-75.1123], ["D22",39.9811,-75.0998], ["P02",40.0437,-75.0217], ["D68",39.9203,-75.1388], ["D51",39.9534,-75.1405], ["S43",39.9217,-75.2275], ["S33",39.9360,-75.2077], ["S42A",39.9215,-75.1937], ["S05",39.9617,-75.1782], ["T14",40.0165,-75.1077]] coordList_index = ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"] #coordList_index is a list containing in_text = open('reg_sum.txt','r') out_text = open('reg_out.txt','w') out_text.close out_text = open('reg_out.txt','a') for line in in_text: split_line = line.split(',') if (split_line[0]) in coordList_index: i = coordList_index.index(split_line[0]) coords = str(coordList[i][1]) + "," + str(coordList[i][2]) last_update = str(split_line[2]) print str(split_line[0]) if split_line[1] == "1": out_text.write(split_line[0] + "
,Test1: " + last_update + "," + coords + ",1" + "\n") elif split_line[1] == "0": out_text.write(split_line[0] + "
,Test2.
Last updated: " + last_update + "," + coords + ",0" + "\n") else: out_text.write(split_line[0] + "
,No data.," + coords + "\n") in_text.close ###******* ###Uploads file via FTP ###******* s = ftplib.FTP('ftp.blah123.org,'user','pass') f.open('reg_out.txt','r') s.storlines('STOR reg_out.txt', f) f.close() s.quit() print "Processed in " + str(((time.time() - starttime) / 60) *60) + " seconds!" #prints elapsed time From castironpi at gmail.com Mon Mar 3 20:11:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 17:11:43 -0800 (PST) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 3, 4:30?pm, "sjdevn... at yahoo.com" wrote: > On Mar 2, 1:18 pm, castiro... at gmail.com wrote: > > > On Mar 2, 12:01 pm, John DeRosa wrote: > > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > > >Hi, > > > > >Have you ever seen Beautiful Python code? > > > >Zope? Django? Python standard lib? or else? > > > > >Please tell me what code you think it's stunning. > > > > Just about any Python code I look at. > > > Decorators, with, and namedtuple. > > IMO, decorators are functional but far from beautiful. ?They're a > special, somewhat ugly syntax for something that was already handled > by normal constructs ("foo=classmethod(foo)") that you didn't need > extra knowledge to understand. > > On balance I think it's worth it in order to get those "declarations" > up by the function defs, but it's sort of a tradeoff of magical non- > explicitness for pragmatism over purity. ?A worthwile tradeoff, but > not what I'd ever call beautiful. Someone study architecture. What are the Palmer House, the Rookery, and the Lyric Opera? From sturlamolden at yahoo.no Sun Mar 23 00:11:51 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 21:11:51 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> Message-ID: On 22 Mar, 23:42, 7stud wrote: > Beginning programmers in grades 9-12 are not going to understand > issues like that, and it would be a mistake to try and introduce > them. Beginning programmers should be concentrating their efforts on > learning the syntax of a language and basic constructs like for-loops > and if statements. Yes. And because Python is a "scripting language" one does not even have to introduce functions to demonstrate this. Students can play with loops, datatypes, operators, assignments, and conditionals, without being confused by higher level constructs like functions and classes. Python is one of very few languages that allow that. If you e.g. start to teach programming with with Java, students are from the start faced with confusing constructs like classes and public static methods if they are to try out anything on their own. With Python, higher level constructs can be gradually introduced. That has a tremendous pedagogical value. From ntv1534 at gmail.com Mon Mar 3 15:14:11 2008 From: ntv1534 at gmail.com (MooMaster) Date: Mon, 3 Mar 2008 12:14:11 -0800 (PST) Subject: Inheritance issue... References: <632vhiF262j15U1@mid.uni-berlin.de> Message-ID: On Mar 3, 11:49 am, "Diez B. Roggisch" wrote: > MooMaster schrieb: > > > I'm trying to use inheritance to create a simple binary tree, but it's > > not going so well... here's what I pull from the documentation for > > super() > > "super( type[, object-or-type]) > > > Return the superclass of type. If the second argument is omitted the > > super object returned is unbound. If the second argument is an object, > > isinstance(obj, type) must be true. If the second argument is a type, > > issubclass(type2, type) must be true. super() only works for new-style > > classes. > > The last sentence contains the important bit. You need to use > new-style-classes, which means they have to have the ancestor "object" > somewhere in their inheritance-graph. > > Like this: > > class Foo(object): pass > > Certainly one of the somewhat uglier corners of Python... > > Diez Thanks guys, I hadn't even heard of the distinction between "old" and "new" style classes...is this in the tutorial somewhere? I didn't see it in Classes... From gh at ghaering.de Wed Mar 19 03:49:36 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 19 Mar 2008 08:49:36 +0100 Subject: How to solve a three-element equation set? In-Reply-To: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> References: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> Message-ID: <64busgF2anottU2@mid.uni-berlin.de> purple wrote: > Could you guys do me a favor for solving a equation set? > > Z=d/4*(1-SIN(X)/X) > X=8q/(D^2*Y)+SIN(X) > Y=1/n*Z^(2/3)*i^(1/2) > > In this equation set, X,Y&Z are the unkown parameters, the others say, > d, q, n&i are known. SO in python, how to program it to represent X, Y > and Z in the form of d, q, n and i? Will you do your homework yourself, please? Hint: make X, Y and Z Python functions. -- Gerhard From sarc26 at gmail.com Fri Mar 14 07:07:09 2008 From: sarc26 at gmail.com (Saideep A V S) Date: Fri, 14 Mar 2008 16:37:09 +0530 Subject: request for Details about Dictionaries in Python Message-ID: Hello Sir, I am a beginner level programmer in Python. I am in search of a function for 'On-Disk' Dictionaries which is similar to On-Disk Hash tables in Perl (i.e., tie function in Perl). Could anyone help me with the concept. I have also searched the net, but was not successful in finding any related. Awaiting your Solutions. Thanks in Advance. Saideep -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Fri Mar 14 02:24:55 2008 From: cwitts at gmail.com (Chris) Date: Thu, 13 Mar 2008 23:24:55 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> Message-ID: <6a4e7475-d291-4572-b114-6835cc9061bc@n75g2000hsh.googlegroups.com> On Mar 14, 6:28?am, jai_python wrote: > hi frenz I ?Need a Python Script For read multiple files(.txt) from a > folder and write it in a single text file.... > > Thanks Take a look at the OS Module for the listdir funtion, you can use it to build a list of all files in the given folder. Iterate through the list checking to see if the file is of the correct type and if it is then append/write it to your single file. Don't forget to flush() your output otherwise you can easily run into memory issues. From software at ginstrom.com Sun Mar 9 21:11:39 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 10 Mar 2008 10:11:39 +0900 Subject: any chance regular expressions are cached? In-Reply-To: <47D48662.4090002@tim.thechases.com> References: <47D48662.4090002@tim.thechases.com> Message-ID: <054301c8824b$b202dfb0$0203a8c0@MOUSE> > On Behalf Of Tim Chase > Sounds like what you want is to use the compile() call to > compile once, and then use the resulting objects: > > re1 = re.compile(r'\n') > re2 = re.compile(r'^') > ... > s = re1.sub('\n' + spaces, s) > s = re2.sub(spaces, s) Yes. And I would go a step further and suggest that regular expressions are best avoided in favor of simpler things when possible. That will make the code easier to debug, and probably faster. A couple of examples: >>> text = """spam spam spam spam spam spam spam""" >>> # normalize newlines >>> print "\n".join([line for line in text.splitlines() if line]) spam spam spam spam spam spam spam >>> # normalize whitespace >>> print " ".join(text.split()) spam spam spam spam spam spam spam >>> # strip leading/trailing space >>> text = " spam " >>> print text.lstrip() spam >>> print text.rstrip() spam >>> print text.strip() spam Regards, Ryan Ginstrom From craigm3604 at gmail.com Sat Mar 22 18:12:47 2008 From: craigm3604 at gmail.com (Craig) Date: Sat, 22 Mar 2008 15:12:47 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> Message-ID: On Mar 22, 3:13 pm, Dennis Lee Bieber wrote: > On Fri, 21 Mar 2008 23:21:48 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > Sorry, I wasn't trying to exclude any credit from Dennis, I just > > wasn't sure if he wanted to be listed. > > As responded to elsewhere -- it was more a case of minimizing the > "non-work" traffic on my work email address... > > > > > This is what I have tried: > > > > > LPBSTR = POINTER(c_void_p) > > > > > And, on the last variation of this, this function needs to receive > > BSTR values passed back from the dll: > > short FAR PASCAL VmxGet(LPHANDLE lpDatasetNumber, LPSHORT lpSecIndex, > > LPSHORT lpOption, BSTR *SrchKey, > > BSTR *SecKey, BSTR *PriKey, LPSTR > > lpTypeDef); > > SrchKey is provided by me, SecKey and PriKey are returned by the dll, > > and TypeDef is defined by me and filled by the dll. > > > For this, I have added: > > VmxGet = windll.vbis5032.VmxGet > > VmxGet.restype = c_short > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, > > LPBSTR] > > Remember that Python strings are immutable... Also note that the > signature you give above seems to differentiate between passing a > pointer variable LPSTR (ie; lpTypeDef is just 4-bytes which will/should > contain the address pointing to the real string) and passing the address > of the first byte of a string buffer BSTR (*PriKey is the same as > &PriKey[0] -- but PriKey itself has to be a sequence of characters or an > empty buffer allocated to hold them). > > From the ctypes documentation: > http://docs.python.org/lib/node453.html > > """ > Assigning a new value to instances of the pointer types c_char_p, > c_wchar_p, and c_void_p changes the memory location they point to, not > the contents of the memory block (of course not, because Python strings > are immutable): > > >>> s = "Hello, World" > >>> c_s = c_char_p(s) > >>> print c_s > > c_char_p('Hello, World')>>> c_s.value = "Hi, there" > >>> print c_s > > c_char_p('Hi, there') > > >>> print s # first string is unchanged > Hello, World > > You should be careful, however, not to pass them to functions expecting > pointers to mutable memory. If you need mutable memory blocks, ctypes > has a create_string_buffer function which creates these in various ways. > The current memory block contents can be accessed (or changed) with the > raw property; if you want to access it as NUL terminated string, use the > value property: > > >>> from ctypes import * > >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes > >>> print sizeof(p), repr(p.raw) > 3 '\x00\x00\x00' > >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string > >>> print sizeof(p), repr(p.raw) > 6 'Hello\x00' > >>> print repr(p.value) > 'Hello' > >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer > >>> print sizeof(p), repr(p.raw) > > 10 'Hello\x00\x00\x00\x00\x00'>>> p.value = "Hi" > >>> print sizeof(p), repr(p.raw) > > 10 'Hi\x00lo\x00\x00\x00\x00\x00' > > """ > > Drawback -- it looks like you may have to preset the size of the > buffer... > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ That is not really a drawback. Pretty much everything is fixed-length anyway. I guess I am having trouble with the whole immutable thing. And, the pointers too. Anyway, I have the following for "types": LPBSTR = POINTER(c_void_p) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) LPVSTATS = POINTER(c_void_p) c_string = c_char_p LPSTR = c_string I guess passing a structure is out of the question. So, I tried a string (something - just to get the data back): #short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS lpvstats); VmxInfo = windll.vbis5032.VmxInfo VmxInfo.restype = c_short VmxInfo.argtypes = [LPHANDLE, LPSTR] VsamInfo = create_string_buffer("12345678901234567890123456789012") printf ("VsamInfo = \x22%s\x22\n", VsamInfo.raw) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) And I get: Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 101, in res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) ctypes.ArgumentError: argument 2: : wrong type So, to get to the VmxGet, I comment out the VmxInfo call, and proceed to: SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = create_string_buffer("X".center(129, "X")) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), byref(c_void_p(TypeDef)) ) And for this, I get: Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 114, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), byref(TypeDef) ) ctypes.ArgumentError: argument 7: : wrong type I know I am missing something, probably very basic (pardon the pun) to Python. From wolf_tracks at invalid.com Fri Mar 28 20:38:08 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 29 Mar 2008 00:38:08 GMT Subject: Astronomy Fits format and gif.save(path) In-Reply-To: References: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> Message-ID: I'm pretty new to Python and libraries. I'm actually trying to modify some code someone else wrote. There are two ways images are saved. One is for the user to select a "Save as GIF" menu item, or save as tiff, or others. The other way is that the user wants a collected image from a camera saved every, say, 10 minutes. The "save" process is different for some reason. Here are the two code segments involved: A. Save every 10 minutes t = time.localtime(now_time) s = "a%4d%02d%02d_%02d%02d%02d.tif" % ( NOTE my comments below B. t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec ) s = os.path.join("Exposures",s) <========== auto-exposures if not os.path.exists("Exposures"): os.mkdir("Exposures") self.current_image.save(s) <============ save image if self.trigger_mode: self.Trigger() self.CheckEvent() contrast this with where the user specifically wants the image he sees saved as a gif: B. From menu option def SaveGIF(self): if self.current_path: default_path = splitext(basename(self.current_path))[0] + ".gif" path = asksaveasfilename(defaultextension=".gif", title="Save as GIF", initialfile=default_path, filetypes=GIF_FILE_TYPES) else: path = asksaveasfilename(defaultextension=".gif", title="Save as GIF", filetypes=GIF_FILE_TYPES) if not path: return gif = self.current_image.convert("RGB") gif.save(path) <===========Save as gif. The programmer told me if I change the tif in A. to gif, jpg or whatever, it would work. Instead I get a file the of zero length when I use jpg. Can anyone explain why this wouldn't work? I see that current_image.convert is involved in one place and current_image.save in the first. {I erroneously thought gif.save was some PIL method.) Hmmm, maybe I needed to use jpeg? As for fits formats, I see PIL shows FITS for identify only. Not sure what that means. Read but not write? Gary Herron wrote: > W. Watson wrote: >> In what library would I find gif.save(path), where path is the name >> and path of a file, and the method would produce a file in a gif >> format? >> >> Is there a fits.save(path) somewhere? fits is commonly used in >> astronomical work. >> > You may want to install PIL (the Python Image Library) for this: > > http://www.pythonware.com/products/pil/ -- Wayne Watson (Nevada City, CA) Web Page: From __peter__ at web.de Wed Mar 12 04:52:40 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Mar 2008 09:52:40 +0100 Subject: best way to have enum-like identifiers? References: Message-ID: mh at pixar.com wrote: > I currently have a 2-dim hash, indexed by two strings: > > template['py']['funcpre'] > template['py']['funcpost'] > ... > > but I would prefer to have these indexed by constants of > some kind, since this seems a bit more natural: > > template[py][funcpre] > template[py][funcpost] > ... > > Currently I'm just putting this at the top of the file: > > py=1 > funcpre=2 > funcpost=3 > ... > but I'm curious if there's a better way of doing this, > some kind of enum-like thing or somesuch. A dictionary with a fixed set of keys is better spelt as a class, e. g. instead of the inner dictionary you can use something like class Hooks(object): def __init__(self, pre=None, post=None): self.pre = pre self.post = post ... def before(): print "before" def after(): print "after" template["py"] = Hooks(before, after) Peter From koara at atlas.cz Fri Mar 7 09:15:04 2008 From: koara at atlas.cz (koara) Date: Fri, 7 Mar 2008 06:15:04 -0800 (PST) Subject: hidden built-in module References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> Message-ID: <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> On Mar 5, 1:39 pm, gigs wrote: > koara wrote: > > Hello, is there a way to access a module that is hidden because > > another module (of the same name) is found first? > > > More specifically, i have my own logging.py module, and inside this > > module, depending on how initialization goes, i may want to do 'from > > logging import *' from the built-in logging. > > > I hope my description was clear, cheers. > > > I am using python2.4. > > you can add your own logging module in extra directory that have __init__.py and > import it like: from extradirectory.logging import * > > and builtin: from logging import * Thank you for your reply gigs. However, the point of this namespace harakiri is that existing code which uses 'import logging' ... 'logging.info()'... etc. continues working without any change. Renaming my logging.py file is not an option -- if it were, i wouldn't bother naming my module same as a built-in :-) Cheers. From sjmachin at lexicon.net Thu Mar 27 18:07:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 15:07:21 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: <18171c4d-70a7-4e57-8fbd-6c9122d25903@c19g2000prf.googlegroups.com> On Mar 28, 8:40 am, jwbrow... at gmail.com wrote: > On Mar 27, 1:53 pm, "Gabriel Genellina" > wrote: > > > > > En Thu, 27 Mar 2008 17:37:33 -0300, Aaron Watters > > escribi?: > > > >> "this";"is";"a";"test" > > > >> Resulting in an output of: > > > >> ['this', 'is', 'a', 'test'] > > > >> However, if I modify the csv to: > > > >> "t"h"is";"is";"a";"test" > > > >> The output changes to: > > > >> ['th"is"', 'is', 'a', 'test'] > > > > I'd be tempted to say that this is a bug, > > > except that I think the definition of "csv" is > > > informal, so the "bug/feature" distinction > > > cannot be exactly defined, unless I'm mistaken. > > > AFAIK, the csv module tries to mimic Excel behavior as close as possible. > > It has some test cases that look horrible, but that's what Excel does... > > I'd try actually using Excel to see what happens. > > Perhaps the behavior could be more configurable, like the codecs are. > > > -- > > Gabriel Genellina > > Thank you Aaron and Gabriel. I was also hesitant to use the term > "bug" since as you said CSV isn't a standard. Yet in the same right I > couldn't readily think of an instance where the quote should be > removed if it's not sitting right next to the delimiter (or at the > very beginning/end of the line). > > I'm not even sure if it should be patched since there could be cases > where this is how people want it to behave and I wouldn't want their > code to break. > > I think rolling out a custom class seems like the only solution but if > anyone else has any other advice I'd like to hear it. > I have code in awk, C, and Python for reading bad-CSV data under the assumptions (1) no embedded newlines (2) embedded quotes are not doubled as they should be (3) there is an even number of quotes in each original field (4) the caller prefers an exception or error return when there is anomalous data. From justdelegard at gmail.com Thu Mar 27 17:13:15 2008 From: justdelegard at gmail.com (Justin Delegard) Date: Thu, 27 Mar 2008 17:13:15 -0400 Subject: dynimac code with lambda function creation In-Reply-To: <47ebd337$0$13089$426a74cc@news.free.fr> References: <47ebd337$0$13089$426a74cc@news.free.fr> Message-ID: <47EC0DEB.8040908@gmail.com> An HTML attachment was scrubbed... URL: From joe at neosource.com.au Thu Mar 13 22:24:01 2008 From: joe at neosource.com.au (jcnbp8k) Date: Thu, 13 Mar 2008 19:24:01 -0700 (PDT) Subject: sorting question In-Reply-To: References: Message-ID: <16043041.post@talk.nabble.com> Hi Patty, That's easy solved, the word is keyboards. I just did a google search for 'anagram solver' and got lucky with Andy's free online anagram solver at http://www.ssynth.co.uk/~gay/anagram.html :) I know it's not a python script, though are you actually working on a python program to de-scramble words yourself or did you just want the answer? Hope that helps. Cheers, Joe http://www.neosource.com.au www.neosource.com.au - Practical Software Solutions Patty Sutcliffe wrote: > > The website you list regarding 9-letter scrambled words doesn't exist any > longer. Is there another way that I can access it to see your program you > designed? I have a nine letter work I need to unscramble. I will send it > just in case you can figure it out for me and let me know. > > KAEOSYBRD > > I'm not very good at that sort of thing, but would love to know the answer > to this one. > > Thank you, > Patty > patty206 at charter.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- View this message in context: http://www.nabble.com/sorting-question-tp16041301p16043041.html Sent from the Python - python-list mailing list archive at Nabble.com. From pscott at uwc.ac.za Mon Mar 31 01:23:00 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Mon, 31 Mar 2008 07:23:00 +0200 Subject: Beginner advice Message-ID: <1206940981.6828.13.camel@paul-laptop> I have been tasked to come up with an audio recorder desktop (cross platform if possible - but linux only is OK) that: 1. records a lecture as an MP3 file (pymedia?) 2. Provides a login form for server credentials 3. Uploads via XMLRPC (pyxmlrpclib) to the server as a podcast I have been working on this (having never really worked with Python before) for the past 24 hours or so, and would just like to get some feedback on the direction that I am taking if possible. 1. Is pymedia an active project? Should I use something else? 2. GUI design - I am using glade designer and pyGTK. Good choice? 3. pyXMLRPClib - active? Something better? 4. I see that there are literally thousands of somewhat external looking libraries for python, I presume that there is some way of bundling all the deps into a single source and then compiling? or otherwise packaging them all (this software will be for academia, so difficult installs are out!) 5. Editor - I am using Eric (which I quite like), any advice on IDE's? Any help would be massively appreciated! Python looks like a *really* easy and powerful language (hey, I managed to do a desktop application in a few hours and I am a botanist!) and I would like to do a lot more with it. I have a PHP background (taught myself that also) so C syntax is almost like my native tongue :) but Python syntax seems just as easy, if not easier! I am still going through Mark Pilgrims' tutorials (dive into ones) and am slowly getting the hang of things, so if these questions seem inane, please do excuse me and feel free to tell me to RTFM! Thanks --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From furkankuru at gmail.com Tue Mar 25 19:38:39 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 01:38:39 +0200 Subject: embedded python pythonpath In-Reply-To: References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> Message-ID: <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> Actually, I do not want any .py or .pyc files around my executable. (including userdict, sys, site etc) I want to have just single zip file for all python files. I had a look at py2exe source codes but could not figure out how it just looks into a zip file. So maybe I have to compile the svn version of python. On 3/26/08, Gabriel Genellina wrote: > > Furkan Kuru gmail.com> writes: > > > I've tried below code (Setting pythonpath environment variable) > > and then initialize python interpreter but the embedded python > interpreter > did not get the newly assigned PYTHONPATH. > > I ve looked at the sys.path in python code (that is run by the embedded > interpreter) and it behaved according to older pythonpath. > > Note that you don't HAVE to set the environment variable PYTHONPATH, there > are > other ways to get directories listed in sys.path - and that is what really > counts. > The simplest way is to just write code to insert the desired directories > in > front of sys.path, after the call to Py_Initialize. The only problem is > that > some modules (like site and sitecustomize) are searched and executed > before > your code has a chance to modify sys.path - I hope it's not a problem for > you. > > > Setting environment variable seemed to be correct. > > Does py_initialize run in another thread so it starts before setting the > environment var? > > I could reproduce the problem with a smaller code (using C, not C++). > Testing > with Python 2.5.1 doesn't work (that means, it ignores the new setting for > PYTHONPATH). Testing with current Python trunk (from svn) *does* work. I > don't > know if this is a bug that has been fixed, or it works that way because > the > svn version is not the default installation and then searches for things > in a > different way. > > #include > > int main(int argc, char *argv[]) > { > putenv("PYTHONPATH=C:\\TEMP\\MF"); > system("set PYTHONPATH"); > printf("Py_GETENV(PYTHONPATH)=%s\n", Py_GETENV("PYTHONPATH")); > > Py_Initialize(); > PyRun_SimpleString("import sys\nprint sys.path"); > Py_Finalize(); > return 0; > } > > I compiled twice with these commands: > cl -MD -Ic:\apps\python25\include test.c c:\apps\python25 > \Libs\Python25.lib /Fetest25.exe > cl -MD -Ic:\apps\python\trunk\PC -Ic:\apps\python\trunk\include test.c > c:\apps\python\trunk\PCbuild\Python26.lib /Fetest26.exe > > Python25.dll and Python26.dll both were copied into the current directory. > > test25.exe: > PYTHONPATH=C:\TEMP\MF > Py_GETENV(PYTHONPATH)=C:\TEMP\MF > ['C:\\Apps\\Python25\\lib\\site-packages\\setuptools-0.6c5- > py2.5.egg', 'C:\\Apps\\Python25\\lib\\site-packages\\ > simplejson-1.7.1-py2.5-win32.egg', > ... many directories, not including C:\TEMP\MF ... ] > > test26.exe: > PYTHONPATH=C:\TEMP\MF > Py_GETENV(PYTHONPATH)=C:\TEMP\MF > 'import site' failed; use -v for traceback > ['C:\\TEMP\\MF', 'C:\\TEMP\\python26.zip', '', 'C:\\TEMP'] > > I don't understand how the test program, compiled for 2.5.1, could > actually > locate the Python directory. (It's not in my PATH, it's not the default > install directory, and I deleted the HKLM\Software\Python\PythonCore\2.5 > registry key). > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkpmep at gmail.com Sun Mar 30 21:17:05 2008 From: tkpmep at gmail.com (tkpmep at gmail.com) Date: Sun, 30 Mar 2008 18:17:05 -0700 (PDT) Subject: Dispatching functions from a dictionary References: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> <7xd4pbexbp.fsf@ruckus.brouhaha.com> <1ec62988-4def-4fd9-85e6-0e97e26e17e0@c26g2000prf.googlegroups.com> Message-ID: <55eaa328-11b7-416d-b093-5ad8275e8a84@s8g2000prg.googlegroups.com> Paul, George, Thanks a mill - the help is greatly appreciated. Thomas Philips From troworld at gmail.com Sat Mar 1 20:47:54 2008 From: troworld at gmail.com (Tro) Date: Sat, 1 Mar 2008 20:47:54 -0500 Subject: Book Recomendations In-Reply-To: References: Message-ID: <200803012047.54656.troworld@gmail.com> On Saturday 01 March 2008, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. The official tutorial is required reading. After that, Dive Into Python (http://diveintopython.org/). Cheers, Tro From bearophileHUGS at lycos.com Mon Mar 17 22:28:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 17 Mar 2008 19:28:13 -0700 (PDT) Subject: Py in Counter Strike Message-ID: <859db668-8ff1-47ee-8691-d27e3ade6800@x41g2000hsb.googlegroups.com> A PDF file, Embedding_Python_into_Counter-Strike: http://us.pycon.org/common/2008/talkdata/PyCon2008/020/Case_Study_-_Embedding_Python_into_Counter-Strike_Source.pdf It talks about some problems too. Bye, bearophile From harunbaykal at gmail.com Sun Mar 2 21:27:52 2008 From: harunbaykal at gmail.com (Harun BAYKAL) Date: Mon, 3 Mar 2008 04:27:52 +0200 Subject: Character Problem Message-ID: <4493315f0803021827j775b693ndaaa80bb0d2c8841@mail.gmail.com> Hi, I am studying on an addon developed for QGIS, a GIS software. But I have a problem. The extension has been developed with QT and Python. Actually Python is used for the interface design. For the user interface Python reads some values from some database files. I am not experienced Python user and the first developer of the addon had written the python codes for his database. And his database doesn't include any characters than the usual characaters. But my database file contains many characters which are not used in English. So I can not compile the extension because Python can not read the database files. So how can I change the python files for making it to read the databases without modifying the database. Otherwise I had to clear all the non usual characters from the database file which means most of the names and strings will be wrong. So somehow I had to make the python files to read the other unicode and non english characters? Anybody have any idea about how I can I fix such a problem. Thanks Harun From interracial2suckers at gmail.com Mon Mar 24 10:44:21 2008 From: interracial2suckers at gmail.com (interracial2suckers at gmail.com) Date: Mon, 24 Mar 2008 07:44:21 -0700 (PDT) Subject: girl nipples tortured girl singapore tammy sikh girl in action Message-ID: <9edc8586-a506-4bb9-9c74-4d111ffd322c@c19g2000prf.googlegroups.com> http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new geocities girl mn sweet, gallery geocities girl oregon photo, geocities japanese bra girl photos, black domain face geocities girl japanese, bored geocities girl name sarah, bored geocities girl lonely, 2006 7 geocities girl mn, geocities girl medical australia, geocities black hairy girl, 2006 8 geocities girl mn, bored geocities girl named sarah, girl indian maal, van morrison brown eyed girl tab, story of a girl guitar ninedays, purdy girl greenwich village, marti gras girl, girl on potty chair, growth chart percentile girl, pig boar sex girl, imgboard board3 little girl, bike daytona girl, stencils of geisha girl, fangs vampire girl, the girl from dundee high, dilivery girl, whirly girl the movie, girl snowsuit size 7, girl scout brownie try it, aslyn lyrics be the girl, girl does stripshow for boyfriend, gurrlie girl, austin obrien my girl 2, gang bang girl sasha grey, what company makes girl scout cookies, bike bikini dirt girl, drunk girl freind, girl puncher, adventure girl lava sharkboy, mutya buena reall girl, girl socks stink, pirelli calendar girl, 1900 gibson girl, girl spreader bar, barbi girl spanish, ugly girl lyrics mermade melidy, sexy burmese girl dancing ago, kiss because i ma girl mv, girl shagging horse, dark magician girl ecchi, beach bikini candid girl picture, before girl her post puke she, morning girl summary michael dorris, preemie girl clothes, cover girl mineral cosmetics, girl sportbike riders, hey girl-pretty ricky, twin girl crochet bonnets, abbotsford single girl online, sienna miller nude video factory girl, pony girl tack, rush limbaughs girl friend, supertramp girl friend, sexy girl webcams for mac dashboard, 1940 pin up girl pictures, country girl tits arse, breezewood call girl, nanyang girl, free cheatah girl invitations, anthropomorphic dog girl, spider-girl volume 1 legacy summary, jojo not that kinda girl video, rich girl by hall oates, girl i little love oingo song, all-girl orgy, gfx girl, puro rancho girl, lutheran girl jokes, girl southington, the bohemian girl opera, reliant k girl friend, butterfly girl clipart, wowowee girl, 7 girl phatty, octa girl, girl lifegaurd, beach drunky girl in, chinees girl feet, young dro my girl, vivid girl janine biography, jim sanders girl scouts, sugar plum girl dress, cruel girl jeans web site, girl fucked by a dof, splitz enz message to my girl, feedee girl, wf girl wrestelers, ugly girl lyrics by weird al, banquet cheering girl, poopy girl, glock girl pictures, caryl top girl, barloe girl she, t-girl dallas personal ads, baby by girl innervoices lyric, by girl lyric talk tlc, young girl puss, everythng girl, wisconsin girl scout camps, galaxy girl sim date, elf girl sim date cheat, foglio girl genius, girl scouts kennebec council, teen girl funstuff, girl getting banged bt horse, girl scout awards for cadetts, young girl swimmer sheila, historical dress american girl doll, girl school bomb extrem pakistan, palm glade girl scouts, horse-girl sex, cookie delivery girl scout, laker girl audition, bad girl black buddafly, pinup girl with bow and arrow, nicaragua nude girl photos, bear fucks girl, spandex girl lycra woman, hypnotized girl clip, teen girl glases, being dragon girl sacrificed, girl scouts silver sage council, bam margera girl women clothes, ceremony flag girl scout, lil girl gone devin the dude, elle girl magzine, aloud girl hot long summer video, sweat young girl nude, girl want suckdick, download barlow girl, girl relay runners, brownie uniform for american girl doll, kazakh girl, daddy punishes girl, girl scouts great trail council, girl missinf in portugal luxe resort, harry potter girl scout camp, thc girl, teenage girl beating caught on tape, skinnie girl, girl maria moore xl, a girl s world online clubhouse, geisha girl halloween, ebony t-girl, japen girl sex, chat ethiopian girl, girl scout tours of savannah georgia, every girl millimeter sell, treat gloom cookie girl pretty, eamon girl version, picasso girl before the mirror, anka gilmore girl paul, leo blais oh girl, homly girl, whirly girl puke scene, japanese geisha girl tattoo, kenworth trucking mud flap girl, boy and girl club la habra, roller blade girl boogie nights, girl in pic poop toilet, bad man nah dress like girl, sagattarius man and a gemini girl, pacific peaks girl scout council, types of girl scout cookies 2005, girl scout puzzlers badge, cosmo girl magazine website, wb show gilmore girl, girl scouts camp seniors detroit michigan, ssx tricky girl, ash girl from mars mp3, jersey shore girl dottie, lyrics for nasty girl by chingy, rachel weissman girl's hair accessories, confirmation e-card special girl, anime blog girl high joshikousei, barbie german girl rammstein, disney disney girl nightgown princess, fingerbang a girl, award ceremony girl scout, girl from ipanema song lyric, the fattest girl with boobs, factory girl sienna sex scenes, zales commercial girl song, fruits basket akito girl, charles dana gibson girl, arta girl, last girl standing rapidshare, daddys little girl by al martino, young girl mentral education, butthole girl pix, girl taking huge poo, reclining girl by francois boucher, jamaica girl scouts, 6yo girl, how to impress a teenage girl, girl koi no victory, aqua ugly girl lyrics, mud flap girl pin, san francisco girl band cockpit, magical girl pretty sammy, rostov on don girl, japanese kogal school girl, candi girl wild, girl scout coloring pages, american girl doll outlet store, girl nipples tortured, council girl hills rolling scout, girl scouts of dupage county il, litles girl, girl bust inflation, x-girl, girl take it easy lyrics pietasters, animated lust little girl squirrel, girl gymnastics merrill samantha, little girl with dorky glasses, bobble head girl version lyrics, arabic blue clip girl tooth, girl gwen hollaback lyric song stefani, girl interrupted quizzes, goodbye girl squeeze, baby ebay girl oarb reborn, peach girl change of heart spoilers, brownie girl idea scout, molestation girl symptoms signs, white girl feat young jeezy, derby girl roller texas, girl scout camporee meals, girl interrupted suicide song, nasty girl lyrics by inaya day, sweet japanese girl cleanser reviews, voodoo girl tim burton, super girl by krystal harris, eureka springs girl's getaway, father flanagans boy and girl town, cam girl masturbates, girl's buzzcut, shonen knife i'm a super girl, cinammon girl tab, citrus council girl scouts, mckay pasadena girl, lucy dress pattern girl, ballow girl, assparade rebecca assparade porn girl rebecaa, girl abducted in tyler texas, naked college hooter girl, costume dance georgie girl, beautiful decent girl russian, girl in greenwood gifted, girl in lovefreekz video, dw girly girl, girl gone wild dorm room, missing girl devin arizona, college girl gyno, tw3 girl, girl groaning audio, doa girl wallpaper, derry community girl scouts, freak a leak girl, ganguro girl v 1.5 cheats, sour girl stone temple, miracle lyrics boy meets girl, terri clark dirty girl guitar tabs, al martino daddys little girl lyrics, 20th century american girl doll, bird girl seussical, johanna grace flower girl dress, girl jewish personals single, nobody's girl bratz rock angelz, girl sleeve tattoo, yong girl upskirt, toasty girl, girl scouts cookie boxes, gourmet-girl, mae girl orgasm, girl huntin girls, ebony girl wanks white guy, billy gilman shes my girl, biki teen girl, girl s titi, rottweiler on girl, girl listen tonite, geocities free sex cam, girl scout candy mould, buff girl myspace layout, living dead girl rob zombie lyrics, country girl cleaning service nashville tn, nina sky move your body girl, blog archive podcast expo soccer girl, foxey golden girl, audio girl promiscuous, girl scout lone star council, girl rad nude, lip piercing girl hiding, girl crush lip potion, adult girl scout costume, lynching murder girl, rina av girl, the shins girl inform me, stupid girl named chelsie, girl jumping rope gold necklace, keep yuor hands off my girl, girl pooping in jeans, paula abdul as a young girl, escort girl versailles, girl viginas boobs, revolutionary girl utena amvs, poor little rich girl edie warhol, killers video mr brightside girl, girl's basketball camps in doylestown pa, the girl most likely rebecca sparrow, nude girl tweens, black gi raping french girl, samoan girl names, thai names-girl, girl mcdaniel mel plastic, nude dark magician girl, china girl iggy pop, girl scouts of america jackson michigan, girl hip hugger jeans, booty butt community girl type, girl fucks landlord, whacked out sports girl, girl scout pen pals, big shoeless girl, david bowie china girl moviefone, girl in the pentacle, girl in pantys and bra, never alone by barlow girl lyrics, aloud girl oops, dp girl nastiest, assie girl, girl surrender ultimate video wrestling, champagne girls flower girl dresses, pink leatherman girl tools, pony girl fetish wear, lyrics for material girl madonna, neil simon the goodbye girl, champagne bottle in a girl ass, natural hairy girl leslie, little girl are heavenly treasure, prepuberty girl, kabuki girl, the other boleyn girl phillipa gregory, girl rihanna selfish, land rover and girl pics, eazy e college girl are easy, busty pinup girl, slutty catholic school girl pics, ordinary girl clueless, vivid girl get doggy, arb girl, impressionists girl looking at her hands, rockabilly girl hair style, north face metropolis girl, flapper girl dress, kochi girl, gunslinger girl wallpapers, directions for masterbating a girl, barbie girl-chinese, umpire girl, girl scout cookie brand, icy blu girl, bikini candid girl model underwear, barlow girl music group, baby girl briggs washington state, girl scout of the permian basin, girl picture skinhead, baby girl nursery decorating ideas, the bottlerockets gas girl, missing girl found hartsford staircase, freaky ghost girl in hallway picture, excort girl, venom spider-girl, lyrics nasty girl christina, one girl to love bobby valentino, saturn girl hentai, a girl from yamhill cover, judo girl comic, sikh girl in action, jet boy jet girl chron gen, cover girl mascaras, anime girl turning into a shemale, girl singapore tammy, girl scout cookie trivia, guitar chords stupid girl, bike girl super umbrella, daisy girl scouts bridging, tuskegee girl, girl masterbating loudly, whiskey girl guitar chords, teen girl slumber parties supplies, birmingham girl scouts, perfect physique girl, 138 girl punk hair styles 199, doctor rose jack girl torchwood, jesse mccartney daddys little girl lyrics, girl peeing in the potty, girl model laika, commercial fahrenheit girl, coastal carolina girl scout, girl gonna jet tab, about a girl chords nirvana, charleston south carolina girl scouts, girl gone summer wiled, school girl plaid skirt, the history of girl scout swaps, girl scouts of adirondack, girl scout of san fernando valley, pisces animated girl pictures, girl scouts brownie vest, cover girl eye shadow discontinued colors, junior girl scout handbook pages, girl little strange strangler, chinese baby girl adoption us citizen, girl in appron, i want a girl barbershop, bop girl goes calypso, kathy van zeeland and undercover girl, melina pizza girl, wheelchair lakers girl tina walker, fattass girl, goth girl freeones hardcore, girl membership pin scout, 50s girl pin up, aud bikini contest girl round, girl of fear factor playboy pic, girl wearing diapers and rubber panties, psycho girl matt download, graduation party invitations girl pink, yellowstone girl scouts, stacy keibler nitro girl, ficking girl mom, cotton toddler girl pajamas, 1.5 cheat ganguro girl, girl gumshoe, southern girl incubus, girl indian saree, irainian girl, unconscious girl fetish webcam, teen girl biceps, girl scout daisy petals, nn cute girl, audio girl sammie should, flower girl purse ivory, jessie's girl chords, coppertone cute dog girl remember, chaos girl az goth skinny, girl scout brownie tryits, etnies skate shoes for girl, girl trench coats, girl deepthroats horse, slavic girl, teenage girl wall stencils, sim girl 2.3 cheat, the slave girl by buchi emecheta, southern storm girl's basketball ky, frank zappa fine girl lyrics, cover girl outlast lipstick, girl scout thinking day quiz, marrekesh and single girl, number girl sappukei, chord lyric to brown eyed girl, av girl idol japanese school, girl interrupted cast and crew, wun laos girl, bitch cigar gal girl lady woman, that girl by marques houston lyrics, girl whirring, mardi gras girl pics, daddys girl scrapbooking, girl snapping turtles, t-girl links, daddies little girl pirn, muscle-girl pornstar, girl scout of milwaukee area, the temptations my girl chords, myspace graphics congratulations baby girl, kai winding hit girl, frisco tx girl scout cookies, austrailian nude girl, the girl who killed the python, japenese dark magician girl, girl scout of america daisy, girl avril lavine, naked everquest girl, girl in skimpy skirt teenage, girl scouts of america iowa jobs, girl lfo lyric tv, never alone barlow girl tab, hula girl doll, free xxxwomen xxx, From pete at unspace.ca Sun Mar 16 15:48:22 2008 From: pete at unspace.ca (Pete Forde) Date: Sun, 16 Mar 2008 12:48:22 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <3a2e4490-f4e9-4edf-ae35-0aa3c90103f7@i7g2000prf.googlegroups.com> > I know what the argument for the results of Pycon 2008 will be: we > needed the money. My answer: it's not worth it. If this is what you > have to do to grow the conference, then don't. If the choice is > between selling my experience to vendors and reducing the size of the > conference, then cut the size of the conference. Keep the quality of > my experience as the primary decision criteria, or I'll stop coming. This commodification of "eyeballs" is happening in the Ruby community, as well. 2008 seems to be the year of Ruby conferences, and both organizers and attendees have been entirely complicit in the gradual dilution of interesting, un-biased presentations. As a result, many of the most innovative members in our community no longer show up. This is a real shame. My friends and I decided to stage a grassroots Ruby conference this summer; it will have no paid sponsors for exactly this reason. We're trying to change up the typical format as well: it's a single-track event, no "keynotes", no schills for well-heeled interests. We're even organizing activities for significant others traveling with conference attendees so that everyone has a good time. The response we've gotten to this approach has been curious; many people totally get why these things are important, and the speaker list reflects this. However, we've also had a lot of complaints that our event is too expensive. In fact, they say that it should be free, like a BarCamp. Just get a bunch of sponsors, and that will be the ticket. We say bollocks to that. http://rubyfringe.com/ I'm posting here because even though the Python and Ruby communities are seen as being in some sort of competition, I personally believe that we have more in common (and lots to learn from each other) than we are credited for. For example, the popular Haml template engine is white-space sensitive, and that's a direct nod towards Python syntax. Thanks for your post, Bruce. You've given us a huge boost that we're doing something right, here. From sigzero at gmail.com Fri Mar 28 22:31:05 2008 From: sigzero at gmail.com (Robert Hicks) Date: Fri, 28 Mar 2008 19:31:05 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> <87abky1i6i.fsf@benfinney.id.au> Message-ID: <71f1daa6-9f48-440b-8f47-07f081891bb2@z38g2000hsc.googlegroups.com> On Mar 16, 5:48?pm, Jeff Schwab wrote: >?Unlike Perl or Tcl, Python is not just a > scripting language with a set of ad-hoc extensions. ?There are still > issues, and Python probably will never be a general-purpose replacement > for system-native language compilers, but it does enable a smooth ramp > from "just a user," through "a user who does some scripting," to > "application developer." Danger! My crap-o-meter went to 100%! You really need to explain what you mean better here. What enables Python to give you a "smooth ramp"? Inquiring minds want to know.I am sure there are a whole lotta programmers in the Perl and Tcl camps that would like to know what you mean as well. I await your enlightenment. Robert From castironpi at gmail.com Sat Mar 8 03:44:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 00:44:34 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> <1ec4b03a-75cd-432e-9e5d-750132324d38@s8g2000prg.googlegroups.com> Message-ID: <4e27c893-d7c6-4ab4-abaa-187520dfc69b@d62g2000hsf.googlegroups.com> On Mar 7, 7:46?pm, DBak wrote: > > > > > ?However I can't do this, because, of course, the name Tree isn't > > > > > ?available at the time that the classes _MT and _Node are defined, so > > > > > ?_MT and _Node can't inherit from Tree. > > > > > Not only is the name not defined, the class doesn't even exist yet. > > > > Yes, but, well - it certainly isn't usable yet, but some object (that > > > will be the class when it is finished) is being built (its __dict__ is > > > being populated, etc.) - so there's an object pointer available inside > > > the interpreter that could be put somewhere. ?But this is pedantic - > > > you're right, the class really isn't available until after the class > > > statement. > > > There is no obvious solution-- What do you mean? ?If there are any at > > all, there is significant competition without clear winners. > > > dict dictA: > > ? ?membA= 0 > > ? ?membB= 0 > > > dict dictB: > > ? ?membC= 0 > > Thanks for your answer. ?To the extent I understand it: ?There is a > difference between the class statements I was trying to nest, with the > inner inheriting from the outer, and your dict example. ?The main > thing is that in the class example - when the inner class is being > built (i.e., inside its class statement's block) there is no need (as > I understand it) for the parent class to be functional at all WHILE I > AM DEFINING METHODS on the inner class. ?Sure, if the inner class had An interesting observation. > But in the case I'm talking about I just want to define methods on the > inner class, using names such that when the method is eventually > called on an instance of the inner class the attribute lookup will > proceed with the outer class being the inner class' parent. ?Creating There are two possibilities I'm thinking of. In both, cases you go back after Tree is finished executing, and inform _Node and _MT of their parentage. I haven't tested either. The first is, define a metaclass that allows __mro__ (method resolution order) to be written to. But does the look-up get performed on the one you define? The second is, cache _Node and _MT during creation, and go back and reinstantiate them. class Tree(object): ...class _MT( metaclass= placeholder ): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node( metaclass= placeholder ): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... Tree._MT.complete( Tree ) Tree._Node.complete( Tree ) And similarly, class Tree(object): @placeholder ...class _MT(): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) @placeholder ...class _Node( metaclass= placeholder( Tree ) ): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... Tree._MT.complete( Tree ) Tree._Node.complete( Tree ) Here the last lines might read: Tree._MT= Tree._MT.complete( Tree ) Tree._Node= Tree._Node.complete( Tree ) But maybe not. Here's a third, actually: class Tree( placeholder ): pass class Tree(object, metaclass= placeholderreplace( Tree ) ): ...class _MT(Tree): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node(Tree): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... If you're using Python -3.0, you might even be able to get away without metaclasses on the first one, or decorators on the second one: class Tree(object): ...class _MT(): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) _MT= placeholder( _MT ) ...class _Node( metaclass= placeholder( Tree ) ): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) _Node= placeholder( _Node ) ...def __init__(): return _MT() ...def merge(self, T): ...... Tree._MT.complete( Tree ) Tree._Node.complete( Tree ) And once again I'm still not sure. From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:12:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:12:55 -0300 Subject: problem with CGIHTTPServer References: Message-ID: En Fri, 28 Mar 2008 12:38:45 -0300, 7stud escribi?: > After I start the server script, load the html page in my browser, and > click on the link, I get the desired output in my browser, but the > server script outputs the following in my terminal: > > localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/ > 1.1" 200 - > localhost - - [28/Mar/2008 08:51:22] code 404, message File not found > localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 - > > > What are the error messages on lines two and three? Line 3 is your browser (IE, I presume?) asking for an icon for the site. See http://en.wikipedia.org/wiki/Favicon I don't know about line 2, maybe it's just a diagnostic message related to line 3. Try refreshing the page, or using an inexistent url to see if it still appears. Or put any icon as /favicon.ico to make your browser happy. -- Gabriel Genellina From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 07:00:59 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 11:00:59 -0000 Subject: Check For SELF Variable Existance Message-ID: <007501c88367$308371d0$918a5570$@rawlins@thinkbluemedia.co.uk> Hello Guys, I want to be able to check if a class has a certain property in its 'self' scope, what's the best way to do this? I've seen a few examples of people using a try: block to test if the variable exists but to be honest, this seems a little bit verbose, do we not have a better method of checking for its existence? Cheers, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Tue Mar 4 01:01:31 2008 From: cwitts at gmail.com (Chris) Date: Mon, 3 Mar 2008 22:01:31 -0800 (PST) Subject: Command line arguments in Windows References: Message-ID: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> On Mar 4, 7:12 am, "Mike Walker" wrote: > I am having some problems with command line arguments in Windows. The same > code under Linux works fine. > > In Windows I only get one argument no matter how many arguments are passed > on the command line. I think there is some problem with the way the .py > files are associated causing this. I'm just not sure how to go about fixing > it. > > If I call the python script using the command "python argtest.py arg1 arg2 > etc..." this also works fine. Its only when run the program using the name > only that the problem occurs. > > Does anyone have any ideas what the problem is here and hopefully how to go > about fixing it? > > import sys > > if __name__ == "__main__": > for arg in sys.argv: > print arg If you run a python file, ie. just double clicking it the only argument you will have will be the filename of the script. If you create a shortcut to the script and in the target box add your arguments (if you have quotation marks place them after not inside) you will see your arguments. fwiw you answered yourself in the third paragraph. From chris.stromberger at gmail.com Tue Mar 4 16:46:16 2008 From: chris.stromberger at gmail.com (chris) Date: Tue, 4 Mar 2008 13:46:16 -0800 (PST) Subject: sqlite3 permission issue References: Message-ID: On Mar 4, 3:10 pm, chris wrote: > I am trying to execute an update to a sqlite3 db via a python cgi > script. I can execute a select via a cgi script, but when I attempt > an update, I get an "unable to open database file" error. But the > error comes on the update statement, not on the connect. > > So the script has: > > conn = sqlite3.connect('db') > c = conn.cursor() > --we get here ok-- > c.execute("insert into contact ...") <-- this statement produces the > error > > I can run the exact same python code from the command line and it > works, so it has something to do with the user that runs the cgi > (apache I assume). I chmodded the db file to 666, but it did not > help. > > Any ideas? > > Thanks, > Chris Nevermind, it was the directory permissions causing the issue. Works now. From sturlamolden at yahoo.no Sat Mar 15 12:02:04 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 09:02:04 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: <19562869-a412-401c-b169-3bcbf6be747f@i12g2000prf.googlegroups.com> On 13 Mar, 09:22, Antoon Pardon wrote: > Whatever python has for a calling convention, it is close enough that > naming it "call by reference" gives people a reasonable idea of what > is going on. Only to the extent that many mistake passing Java or C# reference types for "call-by-reference". "Call by reference" is the calling convention used by Fortran, Pascal and Visual Basic 6. If you don't know any of these languages, chances are you don't understand what "call by reference" really means. From grante at visi.com Fri Mar 28 17:43:52 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 21:43:52 -0000 Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> Message-ID: <13uqpko97kt1h65@corp.supernews.com> On 2008-03-28, castironpi at gmail.com wrote: > Did everyone take the course on computer architecture? No. I personally know dozens of people who didn't. And I know others who took a course on computer architecture but not the course on computer architecture. -- Grant Edwards grante Yow! PEGGY FLEMMING is at stealing BASKET BALLS to visi.com feed the babies in VERMONT. From gagsl-py2 at yahoo.com.ar Thu Mar 27 02:00:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 03:00:11 -0300 Subject: copy file over LAN References: <47EB15BC.3060505@al.com.au> Message-ID: En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee escribi?: > I have a file on another machine on the local network (my machine and > local machines are on windows) and I want to copy it locally. Now the > machine requires authentication and when I try to do a > import shutil > shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') > and it gives me a IOError: [Errno 13] Permission denied: error, which I > expect. How do I provide authentication to copy this file? Probably there are other ways, but the "net use" command looks easy enough. Execute "net help use | more" in a console to see the right syntax. Use the subprocess module to run the command from inside Python. -- Gabriel Genellina From ilochab at yahoo.it Tue Mar 11 17:59:18 2008 From: ilochab at yahoo.it (ilochab) Date: Tue, 11 Mar 2008 21:59:18 GMT Subject: How to import a module that must override a standard one Message-ID: I'm writing a python package that will contain a logging service for twisted in python style. I'm using some modules I downloaded from a twisted trunk, that are not released with twisted but have the same names. One of them is log.py that is usually imported from twisted modules like: from twisted.python import log But I need to import __my__ log, and I need that all the other modules that will use my package would import __my__ log module too. So I see 2 options to do so, but neither of them satisfies me: 1) I put __my__ log in my package tree and I import it from there, but in this way any other module must do the same (and this is bad for previous twisted application that want to use my package) 2) I oblige any potential user to patch the standard twisted installation with my modules, but this is even worse. I'm quite sure there is some pythonic way to override the original twisted's log module after its first import with my one: I just don't know how to do it. So I'll patiently wait for an answer from this group. Ciao! Licia From tjreedy at udel.edu Tue Mar 11 00:20:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 00:20:44 -0400 Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> <13taot5khcl933a@corp.supernews.com> Message-ID: wrote in message news:b61e001a-3a41-4a35-ab3a-546e453d8d69 at b64g2000hsa.googlegroups.com... | What is the notion of equal defined for functions? Isness. The developers did not see sufficient reason to refine it further by comparing all the attributes, including the code object. But there has just been a discussion on pydev about the notion of equality for bound methods. Isness is also the default notion of equality for user-class instances, but in this latter case, an explicit and different __eq__ method can be given. tjr From sjmachin at lexicon.net Thu Mar 27 17:10:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 14:10:03 -0700 (PDT) Subject: Determine size of string in bytes References: Message-ID: <083180d3-3e7c-4db5-926f-b7528201a3b8@a22g2000hsc.googlegroups.com> On Mar 28, 6:45 am, breal wrote: > Forgive me for this question which is most likely stupid... The contents of your question are not stupid. The subject however does invite a stupid answer like: len(the_string). Disclaimer: I know nothing about SOAP except that it's usually capitalised :-) Now read on: > How do I determine the number of bytes a string takes up? I have a > soap server that is returning a serialized string. Serialised how? UTF-8? > It seems that when > the string goes over 65978 characters it does not return to the soap > client. Why does it seem so? How did you arrive at such a precise limit? > Instead I get an error: > error: (35, 'Resource temporarily unavailable') Is this error from the client or the server? Any error or logfile record from the other side? Is there anything in the documentation about maximum sizes? > > This makes me think the problem exists on the soap client side with > some sort of max return length. Think? Can't you verify this by inspecting the source? > If I knew how many bytes the 65978 > character string was, then I could try to up this value. How do you know the string is 65978 characters? If you are debugging the server, can't you do len(serialise(the_65978_char_string))? 65978? Are you sure? Looks suspiciously close to 65535 aka 0xFFFF aka (2 ** 16 - 1 ) to me. If you have the server, you presumably have the source code for both client and server. Some options for you: (1) Look at the traceback(s), look at the source code, nut it out for yourself. If there is some kind of max other than an implicit 16-bit limitation in the client code, it shouldn't be too hard to find. (2) Post the traceback(s) here, along with other details that might be useful, like what SOAP server s/w you are using, what version of Python, what platform. HTH, John From ggpolo at gmail.com Thu Mar 27 06:37:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 07:37:06 -0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: <47EB35FF.4020407@gmail.com> References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> Message-ID: 2008/3/27, Alex9968 : > Guilherme Polo wrote: > > 2008/3/26, Alex9968 : > > > >> Hi all, > >> > >> I use Tkinter's Pack widget geometry manager (I really prefer it over > >> using visual GUI designers), so my question is which other GUI toolkits > >> have similar functionality. > >> > > > > The geometry manager isn't related to using GUI designers tools at > > all. And each toolkit has it's own way to do the things, wxPython uses > > sizers, PyGtk uses containers. > > > > Well, the geometry manager isn't *directly* related to using GUI > designers, but as Pack arranges widgets automatically, using GUI > designers isn't required, while with geometry managers that don't, GUI > designers are necessary (if you start placing widgets programmatically, > you'll end up reinventing something like Tkinter's Pack or Grid geometry > manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. > > >> Secondly, I like the detailed widget borders configuration possible in > >> Tkinter, which can be used to tweak GUI look, and wonder if other > >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) > >> look in Windows, but I'm afraid it can be quite different (and ugly) on > >> other platforms. > >> > > > > You sure can, but differently. > > > > I suppose any toolkit allows setting parameters like "no border", "flat > border" and "3d border", but which ones can set ANY type of border to > ANY widget like Tkinter does? For example set GROOVE border to buttons > and text widgets (instead of traditional wide raised/lowered borders), > which is cool (in my opinion). > The widgets subclass some base class, which contains some common methods which could be the border and relief for example. In the case of PyGtk, border width is controlled at Container, so most widgets will have this feature, but the relief style of the widget is not common to all widgets so you will need to check this one (Button has it). In wxPython, widgets will subclass Window, which has all you want and more. But PyQt doesn't seem to care much about this, you can change the widget to flat (if it makes sense to that widget have setFlat method) but not much related to the borders. You could recheck your use-cases and see if they are acceptable. > > > >> (The reason I ever consider moving from Tkinter is some inconveniences, > >> involving for example window scrolling, plus its smaller amount of > >> widgets compared to some other toolkits, plus its (rumored) ugly look on > >> certain environments. I will not necessary change the toolkit, but I > >> have to consider it) > >> > >> > > > > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > > Tkinter for upcoming GSoC. For now you could try using Tile extension, > > and update to Tk 8.5. If you don't want to use extensions, then you > > will have to wait or change the toolkit for now. > > > > Thanks. I haven't heard of Tile before, now I will keep this in mind. > You forgot to mention WHAT you're planning to solve ;-) , so I have to > add that Tile is modernization of Tk widgets (so it fixes ugly look). > WHAT I'm planning to solve, quote from my own paragraph: "I'm planning to "solve" this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC." I would like to add the possibility to use Ttk widgets into tkinter, providing you have Tk 8.5. It would solve the problem of "not enough widgets" and the other one of "being ugly" mainly. Tk 8.5 also auto-fixes some other problems, it provides smooth-scrolling for the text widget, for example. But keep in mind that using Tk 8.5 in Python is not yet supported (but possible). > > > >> Could anyone with experience in different toolkits help, please > >> > >> Thanks > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > > > > > > > > -- -- Guilherme H. Polo Goncalves From george.sakkis at gmail.com Mon Mar 31 09:29:27 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 06:29:27 -0700 (PDT) Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: On Mar 31, 6:15 am, Peter Otten <__pete... at web.de> wrote: > George Sakkis wrote: > > On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote: > >> Steven D'Aprano wrote: > >> > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > > >> >> Second try: > >> > ... > >> >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing > >> >> with each call. But it's the only way I could find, at least without > >> >> changing the code template used by timeit. > > >> > Eeek. Talk about namespace pollution. > > >> > Thanks for the effort, but if that's the only solution, I think the > >> > solution is worse than the problem! > > >> > Perhaps it's time for me to take a different approach. > > >> [snip] > > >> Maybe the following enhancement of timeit would be worthwhile? > > > [snip] > > > That would be great. I sometimes avoid timeit altogether because > > setting up the environment is so cumbersome. Can you post the patch to > > bugs.python.org so it doesn't get lost ? > > Looking into > > http://svn.python.org/view/python/trunk/Lib/timeit.py?rev=54953&view=... > > I discovered that the Python developers took a different approach and timeit > now allows callables for setup and statement: > > >>> def f(): print 42 > ... > >>> timeit.Timer(f).repeat(1, 1) > > 42 > [3.3855438232421875e-05] > > So my patch is probably a case of instant obsolescence... > > Peter I'm afraid that the taken approach is worse than your patch. For one thing, it allows only zero-arg functions. Of course one can work around it by passing "lambda: f(...)" but that's adding extra overhead which can be measurable for small fast functions. Even if passing *args and **kwds to a Timer is allowed, that's still going to be slower (because of tuple unpacking and whatnot) as Steven's attempt above showed. I think it's at least worth bringing this to the attention of the developers. George From gagsl-py2 at yahoo.com.ar Wed Mar 19 21:50:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 22:50:20 -0300 Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: En Wed, 19 Mar 2008 20:16:36 -0300, John Machin escribi?: > On Mar 20, 9:14 am, sturlamolden wrote: >> Is a Python set implemented using a hash table? > > What don't you understand about the comments in the first two > screenfuls of Objects/setobject.c? That comment was unnecesarily harsh, don't you think? -- Gabriel Genellina From fakeaddress at nowhere.org Tue Mar 18 06:53:28 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 18 Mar 2008 03:53:28 -0700 Subject: win32: emulating select() on pipes In-Reply-To: References: Message-ID: gangesmaster wrote: > i'm trying to figure out if a pipe on win32 has data for me to read. [...] > does anyone know of a better way to tell if data is available on a > pipe? > something that blocks until data is available or the timeout is > elapsed, In Win32 WaitForMultipleObjects and WaitForMultipleObjectsEx do that, for up to 64 objects. In the Hammond Win32 extension package, they're exported by win32event. If 64 pipes in one call isn't enough, there are completion ports. CreateIoCompletionPort is in win32file. A third way in Win32 is WriteFileEx and a completion routine, but it looks like the extension module doesn't support it. I have not used the functions from the Hammond package, and I notice the doc strings are None. You can probably figure the wrappers out by reading the Microsoft documentation and trying stuff. And of then there's the source. If you put together a simple working example, I hope you'll post it. -- --Bryan From mail at timgolden.me.uk Sun Mar 16 10:30:11 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:30:11 +0000 Subject: Spaces in path name In-Reply-To: <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> Message-ID: <47DD2EF3.1080900@timgolden.me.uk> joep wrote: > I assume that there is some difference how subprocess.call and > subprocess.Popen handle and format the command. subprocess.Popen does > the correct formatting when only one file path has spaces and requires > double quoting, but not if there are two file paths with spaces in it. The briefest of code explorations shows that subprocess.call simply hands straight off to Popen, passing args & kwargs along verbatim, and then calls .wait on the result. ie, this: subprocess.call (['a.exe', 'b.doc']) simply becomes: subprocess.Popen (['a.exe', 'b.doc']).wait () What I haven't investigated yet is whether the additional flags your example is passing (shell=True etc.) cause the main Popen mechanism to take a different path. I'll spend some time on that this pm, unless someone gets in first with more of a clue than I currently have. TJG From cwitts at gmail.com Tue Mar 11 03:01:47 2008 From: cwitts at gmail.com (Chris) Date: Tue, 11 Mar 2008 00:01:47 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <0d6402a4-62ee-4a5a-b26b-07a4f37cdc97@d62g2000hsf.googlegroups.com> On Mar 11, 5:44?am, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. > primes = [] > import math > import gmpy > while 1: > ? ? run = int(raw_input("Do you want to calculate primes? 1 = yes and > 2 = no. ")) > ? ? if run == 1: > ? ? ? ? y = int(raw_input("What number do you want to use as the final > number to calculate with? ")) > ? ? ? ? x = int(raw_input("What number do you want to start > calculating primes from? ")) > ? ? ? ? while x < 2: > ? ? ? ? ? ? print "Number must be at least 2 for math reasons." > ? ? ? ? else: > ? ? ? ? ? ? while x < y: > ? ? ? ? ? ? ? ? prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) > ? ? ? ? ? ? ? ? if prime < 0: > ? ? ? ? ? ? ? ? ? ? primes.append(x) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print x " is not prime. " # highlights the final " > here > ? ? ? ? ? ? ? ? x = x + 1 > ? ? ? ? ? ? print primes > ? ? elif run == 2: > ? ? ? ? break > ? ? else: > ? ? ? ? print "Sorry, not a choice. Please enter your choice again." > print "Goodbye." > > How do I fix such an invalid syntax? > > TIA, > Nathan Pinno The reason that line is giving you a syntax error is because you have no comma between your variable and the string. Same reason you can do something like 'print a b c' but instead have to use 'print a, b, c' From baba_mmx at yahoo.it Thu Mar 13 16:14:52 2008 From: baba_mmx at yahoo.it (Mauro "Baba" Mascia) Date: Thu, 13 Mar 2008 21:14:52 +0100 Subject: Ping and ARP on both Win and Linux in Python Message-ID: <47D98B3C.7070307@yahoo.it> Hi, this is my question: I want to know if several switch (about 50) in a big lan are up and then know their MAC addresses to do a list that contains host name, ip and mac. I know only the range of their IP addresses (the host name it's simply to know using socket.gethostn. The first idea it's to ping all ip, parse the response and then execute the command "arp -a" and parse the response. However this way depends on the operating system and the ping response depends too from the language. Another way it's to open the main page of the switch and parse the HTML code where i can find the MAC address. However this way depends on the particular brand's switch. I know (or better i think) that there is a third way: make ping and arp building the packets with socket and so on (but i dont have understand in what way do this). Any suggestion? (i've already search in google, found many sources but a lot of them don't works or don't do what im trying to do...) Regards, Mauretto. From castironpi at gmail.com Wed Mar 12 15:15:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 12:15:09 -0700 (PDT) Subject: for-else References: Message-ID: On Mar 11, 4:43?am, NickC wrote: > On Mar 4, 11:27 pm, bearophileH... at lycos.com wrote: > > > > > The meaning is explicit. While "else" seems to mean little there. > > So I may like something similar for Python 3.x (or the removal of the > > "else"). > > Consider a loop with the following form: > > while 1: > ? if : > ? ? <0-to-many times code block> > ? else: > ? ? <0-to-1 times code block> > ? ? break > > A break, return or exception in the 0-to-many times code block will > obviously skip over the 'else' part of that if statement - it will > only be executed if evaluates as a false value. The above > code is actually equivalent to a normal Python while-loop: > > while : > ? <0-to-many times code block> > else: > ? <0-to-1 times code block> > > For loops aren't quite so straightforward since the termination > condition is tied up with the StopIteration exception, but the clause > keeps the same name as the corresponding clause on the while loop. > Thinking of it as break-else (as someone else posted) probably isn't a > bad way to look at the situation. > > Cheers, > Nick. Here's what try: else: says. "when control flows off the end of the try clause." So at least their usage is consistent, even if pessimistic. They might be using, "2. in addition to the persons or things mentioned or implied: Who else was there?" - dictionary.com. But conflate with 'if-else', the if and else are mutually exclusive. Maybe the if-else should be if-orelse. One's a misnomer. From tjreedy at udel.edu Tue Mar 11 13:19:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 13:19:12 -0400 Subject: Check For SELF Variable Existance References: <-8215347293566648508@unknownmsgid><8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> <40727.816677145$1205243089@news.gmane.org> Message-ID: "Robert Rawlins" wrote in message news:40727.816677145$1205243089 at news.gmane.org... | Thank you Simon, | | I was hoping there would be something as simple as that :-) | >>> class Spam(object): | ... def egg(self): | ... if hasattr(self, 'chips'): print 'got chips!' I strongly suggest that you read Library Reference Ch.2 on builtin functions and types. From gagsl-py2 at yahoo.com.ar Thu Mar 6 16:32:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 19:32:35 -0200 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 14:40:47 -0200, escribi?: > On Mar 6, 12:17?am, "Daniel Fetchinson" > wrote: >> >> > What does exec( open( 'modA.py' ).read() ) do? >> > > A more appropriate formulation of the 'question behind the words' > would have been, 'are there any weird corner cases in which it doesn't > import modA? I recognize it doesn't on .pyc and .pyd files, but you > could say exec( open( 'modA.py' ).read() ) ==> import modA, even if > import modA =!=> exec( open( 'modA.py' ).read() ) all the time. Then write the question that way. Working crystall balls are hard to find nowadays... They're different; no module object is created by the exec statement. When the import machinery determines that certain module isn't already loaded, and that the .py version has to be used, it does something like this: newmodule = sys.modules[modulename] = ModuleType(modulename) # constructor sets __name__ and a null __doc__ newmodule.__builtins__ = current builtins newmodule.__file__ = filename code = read from filename and compile it exec code in newmodule.__dict__ > However, a way of asking that's more direct would have been, "Wait... > can't you create multiple module instances like that?", but since > we've already seen successful loadings of at least the builtins, > that's been treated. There are ways to create many instances of the same module, but not using a plain import statement, or using the API in the intended way. > Maybe you even hear the right thing if I say, > "Does exec( open( 'modA.py' ).read() ) do the things of import modA?" Only in part, as you can see above. > Yes, I can read the docs, but no, I can't check every possible > combination of modules. > The idea behind a singleton is to ensure something. You want non- > primary instances impossible to create. However, if (wording got > tangled here) for singleton A, if class B does the same thing, just > has different allocations-- it's own-- then A is still a singleton. > The writer of B hasn't defeated or contradicted the letter or spirit > of A. > > OP's question might have come from a variety of perspectives. In some > ways yes, in others no. That is, if you try to reinstantiate modA, > you get the same instance. But if you try really hard, you get a new > one. Are you looking for an extension to import modA that won't > return an instance that is old? > > So far, I know this: modules and classes are both namespaces. Are > those singletons? Strictly speaking, neither classes nor modules are singletons; classes are instances of type, and modules are instances of their type, and there are many instances of each. We can consider "qualified singletons", where we want to have a single instance of a class given certain attributes. In that sense, modules are "named" singletons; Python tries to ensure that, given a module name, the module object returned is always the same one - even if you spell the name in different ways. The import statement, the __import__ builtin, the imp module, the PyImport_AddModule C function, all of them try to ensure that. Of course there are ways to shoot yourself in the foot -by example, creating a new module "in the fly" with PyModule_New- On the contrary, classes have no such restrictions. Of course, for classes defined at the global level in a module, you can't have two of them with the same name, but that's just because the module namespace can't hold two values for a single name. But you can create classes dinamically, or define them inside a function, or... lots of ways of creating many instances of the "same" class, and Python won't enforce them to be always the same object. So, I'd say that modules are named singletons, and classes aren't singletons at all. -- Gabriel Genellina From kellygreer1 at yahoo.com Tue Mar 25 19:30:20 2008 From: kellygreer1 at yahoo.com (kellygreer1) Date: Tue, 25 Mar 2008 16:30:20 -0700 (PDT) Subject: Filtering a Python list to uniques Message-ID: What is the best way to filter a Python list to its unique members? I tried some method using Set but got some "unhashable" error. lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] # how do i reduce this to lsttwo = [ 1, 2, 3, 4, 5, 6 ] Is there a page on this in the Python in a Nutshell or the Python Cookbook? Did I miss something? Kelly Greer kellygreer1 at nospam.com change nospam to yahoo From python at rcn.com Tue Mar 18 13:17:19 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 18 Mar 2008 10:17:19 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: <0c6e45f4-c995-476f-bb65-a7da4d98ee30@s19g2000prg.googlegroups.com> On Mar 18, 2:57 am, Simon Forman wrote: > Is there a more efficient way to do this? > > def f(L): > '''Return a set of the items that occur more than once in L.''' > L = list(L) > for item in set(L): > L.remove(item) > return set(L) > > |>> f([0, 0, 1, 1, 2, 2, 3]) > set([0, 1, 2]) def f(L): seen = set() dups = set() for e in L: if e in seen: dups.add(e) else: seen.add(e) return dups Raymond From pradiprai at gmail.com Mon Mar 31 06:53:37 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 16:23:37 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Hi Steve, Can you guide me how to install a 2.5 version of dbi for it to work ? Thanks !! Pradeep Pradeep Rai wrote: > Hi All, > > I have upgraded python v2.5.2 from python v2.4.3. The upgradation > results into following error: > "Python C API version mismatch for module dbi: This Python has API > version 1013, module dbi has version 1012." > > Please suggest, how to resolve this error to proceed further. > > Regards, > Pradeep Rai > > Don't try and drag 2.4 extension modules into the 2.5 environemnt. You will have to install a 2.5 version of dbi for it to work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC *http://www.holdenweb.com/* -- *http://mail.python.org/mailman/listinfo/python-list* -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Fri Mar 14 08:23:42 2008 From: DustanGroups at gmail.com (Dustan) Date: Fri, 14 Mar 2008 05:23:42 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> Message-ID: <86a6d375-0397-4cb1-aca2-552196350894@v3g2000hsc.googlegroups.com> On Mar 13, 1:56 pm, yoz wrote: > This will cause a hidden feature of python and the OS, known as the > 'python easter egg', to activate - erasing all data on the hard disk and > then reporting how many bytes of data are left. > > Usually "None" ;-} - This really is a 'gotcha'.... (Aren't you sorry you > cheated and typed this in !!) > > So the answer is 5 ? Good one. You got a smile out of me. From grante at visi.com Thu Mar 20 11:59:47 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 15:59:47 -0000 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> Message-ID: <13u52fj5btjug80@corp.supernews.com> On 2008-03-20, jmDesktop wrote: > On Mar 20, 11:21?am, Grant Edwards wrote: >> On 2008-03-20, jmDesktop wrote: >> >> > Hi, I'm trying to learn Python. ?I using Aquamac an emac >> > implementation with mac os x. ?I have a program. ?If I go to the >> > command prompt and type pythong myprog.py, it works. ?Can the program >> > be run from within the editor or is that not how development is done? >> > I ask because I was using Visual Studio with C# and, if you're >> > familiar, you just hit run and it works. ?On Python do I use the >> > editor for editing only and then run the program from the command >> > line? >> >> http://www.google.com/search?q=emacs+python > > Gee. Thanks. Golly. You're welcome. Don't the hits on the first page answer your question? They explain how to do things like run python programs from within emacs (including how to do source-level debugging). This is probably one of the better pages that the google search above found: http://wiki.python.org/moin/EmacsEditor -- Grant From sturlamolden at yahoo.no Sun Mar 16 13:25:29 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:25:29 -0700 (PDT) Subject: Basics of Python,learning References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <8d7e8d6b-3ddd-491b-811f-99986eb29158@h11g2000prf.googlegroups.com> On 16 Mar, 17:25, Guido van Brakel wrote: > Why is this not working,and how can I correct it? [code skipped] There is no way of correcting that. Delete it and start over. From kyosohma at gmail.com Sun Mar 16 09:42:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 16 Mar 2008 06:42:16 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Vendors were guaranteed first pick on lightning talk slots, and > we in the audience, expectantly looking forward to interesting and > entertaining content, again started to feel like things were awfully > commercial. And what seemed like a good idea, moving lightning talks > into plenary sessions with no competition, began to look like another > way to deliver a captive audience to vendors. > This was my first time at PyCon and when I went to the Lightning Talks yesterday, I was also under the impression that they were for attendees. About half of the ones I saw were commercials. It was weird and made me wonder if they were always like that. > On top of that, the quality of the presentations was unusually low. > I'd say that 80% were not worth going to -- there were definitely some > good ones, but it was a lot of pain to discover them. > Do you mean the "official" presentations or the lightning talks? I thought both were kind of bad. Jeff Rush was great in both of the sessions I saw and the gaming presenters were also good. But I saw a lot of people who had never presented and were unprepared. In fact, one didn't have any code whatsoever to share and the other one only started showing some code during the last 10 minutes of his time. The sponsor keynotes weren't all bad. I thought the White Oaks guy was quite sincere and it was cool to hear about Python from the business side. And the Google rep probably had the slickest presentation I've ever seen. In retrospect, I'm not sure what it had to do with Python though. Mike From max at alcyone.com Tue Mar 4 03:44:04 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 04 Mar 2008 00:44:04 -0800 Subject: sympy: what's wrong with this picture? In-Reply-To: <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 11:58 pm, Erik Max Francis wrote: >> Mensanator wrote: >>> I'm not hard to please at all. >> No, of course not, since logically you must think all software is useless. > > Somehow, I expected better logic from people who call themselves > programmers. So you agree with me. Lack of prefection = uselessness. Thanks for being honest, whether your realized you defeated your own disclaimer or not. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis I wonder if heaven got a ghetto -- Tupac Shakur From castironpi at gmail.com Wed Mar 12 02:16:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:16:36 -0700 (PDT) Subject: merging intervals repeatedly References: <20b3dfb8-c5b7-4fd0-97a1-93f590f54595@u10g2000prn.googlegroups.com> <13tescq9e809idb@corp.supernews.com> Message-ID: <3602eec7-5ffc-4241-b495-dd4ca21fc213@e39g2000hsf.googlegroups.com> > > Correct. I meant the final should be > > (1,30), (29,40), (50,100) > > ? ? ? ? Actually, even that is incorrect -- note that ,30 overlaps 29, Actually, given the specification, (overlaps > N count), (1,15), (20, 30), (29, 40), (50, 66), (62,100) is right, since 66-62= 4<= 5. [1] > ? ? ? ? Since this feels like a homework assignment, I won't be posting my > code... What are the pros and cons, Mr. Bieber? Is cl.py a nanny or a resource? If someone asks for help, there's probably a reason, and if they cheat, then they don't learn Python. Besides, two or three in a row and that's justified. Besides, business programmers get plenty of answers here-- that's cheating too. Besides, just 'cause you help somebody else, doesn't mean everyone will. Besides, your solution doesn't work for floats. [1] > My ultimate goal is to produce a final set of intervals such that not > two intervals overlap by more than N, where N is a predetermined > length. From jules at js3d.co.uk Sun Mar 2 05:33:51 2008 From: jules at js3d.co.uk (Jules Stevenson) Date: Sun, 2 Mar 2008 10:33:51 -0000 Subject: Escaping a triple quoted string' newbie question In-Reply-To: <004401c87c4f$e27b6f60$0301a8c0@laptop> References: <002801c87c3b$d6cd42b0$0301a8c0@laptop> <004401c87c4f$e27b6f60$0301a8c0@laptop> Message-ID: <004801c87c50$e83fc3a0$0301a8c0@laptop> Sorry, original post got a bit mangled, which didn't help the explanation at all, reposted stuff: Apologies if the terminology in this email is a little incorrect, I'm still finding my feet. I'm using python to generate some script for another language (MEL, in maya, specifically expressions). Maya runs python too, but unfortunately its expression language still has to use the maya syntax. If I pass the expression this code (excuse the double spacing, email seems to e ignoring my line breaks): #runtime code [mel] expRuntime=""" float $pos[]=particleShape1.worldPosition; setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; """ dynExpression (p, s=expRuntime, rad=1) #generate the expression Then maya errors out, however if I pass maya an 'escaped' version: expRuntime=""" float $pos[]=particleShape1.worldPosition;\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """ Then all is well. My question is, is there any way to convert the first variable example to the second? It's a lot easier to type and on the eye. From python.list at tim.thechases.com Sat Mar 1 17:05:50 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 Mar 2008 16:05:50 -0600 Subject: Where's GUI for Python? In-Reply-To: <62tvhmF256jk7U1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: <47C9D33E.9040407@tim.thechases.com> > I'm certain there is an API for creating > GUI's but as far i can find it in the > http://docs.python.org/tut/tut.html > the only "gui" is in "Guido". > > What do i miss? The batteries-included GUI: import tkininter Add-on solutions include wxPython, PythonCard and many others. GIYF: http://google.com/search?q=python+gui -tkc From pharmapsychotic at gmail.com Tue Mar 25 15:32:17 2008 From: pharmapsychotic at gmail.com (blackpawn) Date: Tue, 25 Mar 2008 12:32:17 -0700 (PDT) Subject: Circular references not being cleaned up by Py_Finalize() Message-ID: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> I've been trying to get garbage collection of circular references to work properly with no success then I noticed the documentation stating that it just doesn't: >From documentation on Py_Finalize() -> "Memory tied up in circular references between objects is not freed. " I copy pasted the Noddy example for circular reference breaking from the documentation and set a break point in its Noddy_dealloc function and sure enough even that simple example doesn't work properly. So what's the deal here? :) I want all objects to be freed when I shut down and their destruction functions to be properly called. Is there really no way to make this happen? Many thanks for any insights, Jim From ernesto.adorio at gmail.com Sun Mar 23 17:26:33 2008 From: ernesto.adorio at gmail.com (ernesto.adorio at gmail.com) Date: Sun, 23 Mar 2008 14:26:33 -0700 (PDT) Subject: On copying arrays Message-ID: Is there a conceptual difference between best =test[:] and best = [x for x in test] ? test is a list of real numbers. Had to use the second form to avoid a nasty bug in a program I am writing. I have to add too that I was using psyco in Python 2.5.1. Regards, Ernie. From dickinsm at gmail.com Wed Mar 26 18:02:46 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 26 Mar 2008 15:02:46 -0700 (PDT) Subject: Newbie: unsigned shift right References: <276efacc-dad3-4844-a3b4-a6845c71473b@h11g2000prf.googlegroups.com> Message-ID: On Mar 26, 5:42?pm, Sal wrote: > Is there any way to do an unsigned shift right in Python? When I enter > (-1>>1) the answer is -1. What I'm looking for is the equivalent of an > unsigned shift in C or the ">>>" operator in Java. What answer were you hoping for, and why? 2**31-1? 2**63-1? If you're thinking of the -1 as representing a particular fixed-width bit pattern, try doing a bitwise 'and' operation with a suitable mask first. For example, if you're thinking of -1 as a 32-bit quantity, then (-1 & (2**32-1)) >> 1 might produce what you want. Mark From michael.wieher at gmail.com Thu Mar 20 16:35:48 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 15:35:48 -0500 Subject: Haskell vs ?? Message-ID: Just to help clear up my own understanding of this discussion, this is basically a language that obfuscates details and makes low-level decisions in a "average-best" way, and thus allows for lazy people to write kind of decent code quickly? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Mar 23 17:31:04 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 14:31:04 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: On Mar 24, 2:53 am, John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : TypeError: object of type 'bool' has no len() I presume you meant if len(dict.keys()) > 0: > > is expensive for large dictionaries, and makes loops O(N^2). I don't understand "makes loops O(N^2)" ... what I see in the dict_keys function in Objects/dictobject.c is that it makes one linear pass through its table, ignoring unused and formerly-used slots; seems like O(N) where N is the size of the table. Where did you get O(N^2) from? From arnodel at googlemail.com Thu Mar 13 16:31:00 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 13:31:00 -0700 (PDT) Subject: Python regex References: <9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c@i29g2000prf.googlegroups.com> Message-ID: On Mar 13, 8:22?pm, "Andrew Rekdal" <@comcast.net> wrote: [...] > in your expression above.. > > >>> r = re.compile(r'/\*(.*?)\*/') > > what does the 'r' do? It means the literal is a 'raw string' : >>> print 'Hi\nthere!' Hi there! >>> print r'Hi\nthere!' Hi\nthere! >>> If you haven't done so already, I suggest reading the tutorial. Here is a link to the relevant section on strings: http://docs.python.org/tut/node5.html#SECTION005120000000000000000 -- Arnaud From castironpi at gmail.com Sun Mar 16 02:44:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 23:44:01 -0700 (PDT) Subject: string literal or NoneType References: <97eb79e8-e79d-4bd8-af6d-108579e7d54c@59g2000hsb.googlegroups.com> Message-ID: <5f8034ef-2886-4ed5-9820-07d7788039d8@t54g2000hsg.googlegroups.com> > > | hi all > > | i want to check a condition and if true should return a filename > > | string ?from a list.if the condition is false i am returning a > > | "" ?(string literal).. Identity is the strictest test, and you can't define your own. Lots of things can evaluate to True. Only None is None. Does that help? From mal at egenix.com Mon Mar 3 06:17:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 03 Mar 2008 12:17:39 +0100 Subject: Can one get "for x in y" to work for non builtin classes? In-Reply-To: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <47CBDE53.9030805@egenix.com> On 2008-03-02 15:06, Preben Randhol wrote: > Hi > > I'm making a kind of ordered dictionary class. It is not exactly a > dictionary, but it uses a list and dictionary to store the data. > > Something like: > > class dbase(list): > '''Database class keeping track of the order and data''' > > def __init__(self): > self.__data = {} > self.__order = [] > self.__uniq_id = 0 > > I'm just wondering if it is possible to get my class to work so that if > one do: > > > d=dbase() > d.append("Data") > d.append([1,2]) > > one can do like this to iterate over the data. > > for x in d: > ... > > I'm looking at the list class but I don't quite understand from pydoc > which __ __ methods I have to implement to get the above to work. The easiest is to implement an iterator which then get's returned by the .__iter__() method. http://www.python.org/doc/lib/typeiter.html It's also possible to implement .__getitem__() and .__len__() methods and have Python create an iterator on-the-fly. That's how Python used to work before iterators were added to the language. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 03 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From bjorn.m.meyer at gmail.com Thu Mar 20 22:09:33 2008 From: bjorn.m.meyer at gmail.com (Bjorn Meyer) Date: Thu, 20 Mar 2008 20:09:33 -0600 Subject: script won't run using cron.d or crontab Message-ID: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> I appologize if this been discussed previously. If so, just point me to that information. I have done a fair bit of digging, but I haven't found a description of what to actually do. I have a fairly lengthy script that I am able to run without any problems from a shell. My problem is, now I am wanting to get it running using crontab or cron.d. It seems that running it this way there is a problem with some of the commands that I am using. For instance "commands.getoutput" or " os.access". I am assuming that there is something missing within the environment that cron runs that fails to allow these commands to run. If anyone has any information that would help, it would be greatly appreciated. -- Have a GREAT day!!! Bjorn -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 11 07:32:16 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 11 Mar 2008 12:32:16 +0100 Subject: Python PDF + Pictures In-Reply-To: References: Message-ID: <47d66d8f$0$14029$426a74cc@news.free.fr> durumdara at gmail.com a ?crit : > Hi, dear Python Masters! > > I wanna ask about the Python and PDF creating. > > I have many photos, and I wanna make some "presentation" from these > photos, a "thumbnail" like document with one image per one page. > > If I wanna make one document now I do this: > I execute a python script that create a html site with resized pictures, > and split this html site to 50 images per one html file. > Next I open these files in OpenOffice Writer by hand, and save them as > PDF document with poor quality (image compression 95%, image DPI 75). > This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that > can opened everywhere (because of PDF format). > > But I wanna automatize this process with python. > The technic that I will use is this: > 1.) Collect the files in dirs. > 2.) I process one dir in one time. > 3.) I get the files. > 4.) I resize them to max. 1024/768. > 5.) I put the actual image file to the PDF document. > 6.) After each 50. file I open new numbered PDF. > 7.) Every picture placed in one page, and every page orientation set up > as the picture orientation (Portrait or Landscape). > > The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. > > Do you knows about a PDF maker library with I can make this thing? > > Or other technic to simplify the making? Dont know if this will match your needs, but you may want to have a look at pisa: http://www.htmltopdf.org/ From larry.bates at websafe.com` Sat Mar 22 15:00:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 22 Mar 2008 14:00:26 -0500 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. ABSOLUTELY. Get them started with a REAL programming language that will teach them proper fundamentals. I wish Python would have been around 25 years ago when I taught incoming Freshmen at local University. To get students to understand about variable references, etc. I always started them with Assembler so they could understand what was actually going on. I see so may on this forum that have the wrong ideas about variable names/ storage. Good Luck, Larry Bates From bj_666 at gmx.net Mon Mar 31 16:13:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 20:13:05 GMT Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> Message-ID: <65cuuhF2fhuoaU4@mid.uni-berlin.de> On Mon, 31 Mar 2008 12:39:54 -0700, hexusnexus wrote: > How do I receive input from the command line in Python? Direct way `sys.argv`, comfortable way `optparse`. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Mon Mar 10 17:15:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 14:15:09 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> Message-ID: <1befdccf-2efc-4640-bcf8-b4a792d8e646@i29g2000prf.googlegroups.com> On Mar 11, 3:19 am, cokofree... at gmail.com wrote: > The trick in the case of when you do not want to guess, or the choices > grow too much, is to ask the user to tell you in what format they want > it and format according to their wishes. > > Neatly avoids too much guessing and isn't much extra to add. The plot is about understanding input, not formatting output. From steve at holdenweb.com Tue Mar 4 06:51:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 06:51:25 -0500 Subject: Command line arguments in Windows In-Reply-To: References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: Chris wrote: > On Mar 4, 8:38 am, "Mike Walker" wrote: >>> If you run a python file, ie. just double clicking it the only >>> argument you will have will be the filename of the script. If you >>> create a shortcut to the script and in the target box add your >>> arguments (if you have quotation marks place them after not inside) >>> you will see your arguments. fwiw you answered yourself in the third >>> paragraph. >> As I mentioned I am working from the command line, not clicking on the icon. >> The only difference between it working and not is the python prefix, which >> is why I was thinking this is some sort of file association problem. >> >> I probably wasn't as clear as I could have been in the third paragraph. >> >> argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] >> python argtest.py arg1 arg2 arg3 - Works > > That seems rather wierd, just running argtest.py arg1 arg2 arg3 I get > the correct output, Python 2.5.1 from python.org but running on XP > though. Potentially an issue with Vista... ? Strange as it may seem, there have been issues with other Windows command processors, and one in particular (I can never remember which one) messes up IO redirection when the pathext mechanism is used to select the executable that processes the Python file. So I would tend to suspect yet another variation on this familiar theme given your testing results. But I don't intend to tangle with Vaster any sooner than I must. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From siddhantgoel at gmail.com Tue Mar 4 10:13:02 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Tue, 4 Mar 2008 07:13:02 -0800 (PST) Subject: tab completion? Message-ID: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> Hi people. I was just wondering if a tab-completion feature in python command line interface would be helpful? If yes, then how can I implement it? Thanks, Siddhant From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:55:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:55:51 -0200 Subject: Escaping a triple quoted string' newbie question References: <002801c87c3b$d6cd42b0$0301a8c0@laptop> <004401c87c4f$e27b6f60$0301a8c0@laptop> <004801c87c50$e83fc3a0$0301a8c0@laptop> Message-ID: En Sun, 02 Mar 2008 08:33:51 -0200, Jules Stevenson escribi?: > Sorry, original post got a bit mangled, which didn't help the > explanation at > all, reposted stuff: > > Apologies if the terminology in this email is a little incorrect, I'm > still > finding my feet. > > I'm using python to generate some script for another language (MEL, in > maya, > specifically expressions). Maya runs python too, but unfortunately its > expression language still has to use the maya syntax. > > If I pass the expression this code (excuse the double spacing, email > seems > to e ignoring my line breaks): > > #runtime code [mel] > expRuntime=""" > float $pos[]=particleShape1.worldPosition; > > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; > > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; > > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; > """ > dynExpression (p, s=expRuntime, rad=1) #generate the expression > > Then maya errors out, however if I pass maya an 'escaped' version: > > expRuntime=""" > float $pos[]=particleShape1.worldPosition;\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """ > > Then all is well. My question is, is there any way to convert the first > variable example to the second? It's a lot easier to type and on the eye. Except for the doble-space on the first version, \n is the line separator on both, so I'll ignore them. """one two""" is the same thing as "one\ntwo" (even on Windows). The only remaining difference that I see is " -> \" def mayaquote(text): return text.replace('"', '\\"') -- Gabriel Genellina From bbxx789_05ss at yahoo.com Fri Mar 28 21:40:45 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Mar 2008 18:40:45 -0700 (PDT) Subject: problem with CGIHTTPServer References: Message-ID: On Mar 28, 10:12?am, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 12:38:45 -0300, 7stud ? > escribi?: > > > After I start the server script, load the html page in my browser, and > > click on the link, I get the desired output in my browser, but the > > server script outputs the following in my terminal: > > > localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/ > > 1.1" 200 - > > localhost - - [28/Mar/2008 08:51:22] code 404, message File not found > > localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 - > > > What are the error messages on lines two and three? > > Line 3 is your browser (IE, I presume?) asking for an icon for the site. > Seehttp://en.wikipedia.org/wiki/Favicon > Safari. > I don't know about line 2, maybe it's just a diagnostic message related to ? > line 3. Try refreshing the page, or using an inexistent url to see if it ? > still appears. Or put any icon as /favicon.ico to make your browser happy. > I searched for a .ico file on my computer, then copied it into the same directory as the server program, and renamed the .ico file: favcion.ico Then I loaded my html file in Safari and clicked on the link, and this was the output: localhost - - [28/Mar/2008 19:30:31] "GET /my_cgi_scripts/test.py HTTP/ 1.1" 200 - localhost - - [28/Mar/2008 19:30:31] "GET /favicon.ico HTTP/1.1" 200 - So, it looks like Safari automatically requests a .ico file from a server. Thanks. From grahn+nntp at snipabacken.se Sun Mar 30 17:02:44 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 21:02:44 GMT Subject: standard input, for s in f, and buffering Message-ID: One thing that has annoyed me for quite some time. I apologize if it has been discussed recently. If I run this program on Unix (Python 2.4.4, on Debian Linux) import sys for s in sys.stdin: print '####', s , and type the input on the keyboard rather than piping a file into it, two annoying things happen: - I don't see any output until I have entered a lot of input (approximately 8k). I expect pure Unix filters like this to process a line immediately -- that is what cat, grep and other utilities do, and also what Perl's while(<>) { ... } construct does. - I have to type the EOF character *twice* to stop the program. This is also highly unusual. If I saw this behavior in a program, as a long-time Unix user, I'd call it a bug. I realize this has to do with the extra read-ahead buffering documented for file.next() and that I can work around it by using file.readline() instead. The problem is, "for s in f" is the elegant way of reading files line by line. With readline(), I need a much uglier loop. I cannot find a better one than this: while 1: s = sys.stdin.readline() if not s: break print '####', s , And also, "for s in f" works on any iterator f -- so I have to choose between two evils: an ugly, non-idiomatic and limiting loop, or one which works well until it is used interactively. Is there a way around this? Or are the savings in execution time or I/O so large that everyone is willing to tolerate this bug? BR, /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From george.sakkis at gmail.com Tue Mar 18 14:20:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 11:20:58 -0700 (PDT) Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <782b7e65-646b-48d8-8a2b-b595424c9783@e6g2000prf.googlegroups.com> On Mar 18, 6:03 am, Gabriel Rossetti wrote: > Carsten Haese wrote: > > On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > > >> Hello, > > >> I am reading core python python programming and it talks about using the > >> idiom > >> described on > >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183. > > >> I'm using python 2.5.1 and if I try : > > >> class MyClass(object): > >> def __init__(self): > >> self._foo = "foo" > >> self._bar = "bar" > > >> @property > >> def foo(): > >> doc = "property foo's doc string" > >> def fget(self): > >> return self._foo > >> def fset(self, value): > >> self._foo = value > >> def fdel(self): > >> del self._foo > >> return locals() # credit: David Niergarth > > >> @property > >> def bar(): > >> doc = "bar is readonly" > >> def fget(self): > >> return self._bar > >> return locals() > > >> like suggested in the book (the decorator usage) I get this : > > >> >>> a=MyClass() > >> >>> a.foo > >> Traceback (most recent call last): > >> File "", line 1, in > >> TypeError: foo() takes no arguments (1 given) > > >> but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : > > >> >>> a = MyClass() > >> >>> a.foo > >> 'foo' > > >> does anyone have an idea as of why this is happening? > > > You're mixing two completely different approaches of building a > > property. If that code is actually in the book like that, that's a typo > > that you should mention to the author. > > > The @property decorator can only be used to turn a single getter > > function into a read-only attribute, because this: > > > @property > > def foo(...): > > ... > > > is the same as this: > > > def foo(...): > > ... > > foo = property(foo) > > > and calling property() with one argument builds a property that has just > > a getter function that is the single argument you're giving it. > > > The recipe you're referring to uses a magical function that returns a > > dictionary of getter function, setter function, deleter function, and > > docstring, with suitable key names so that the dictionary can be passed > > as a keyword argument dictionary into the property() constructor. > > However, that requires the magical foo=property(**foo()) invocation, not > > the regular decorator invocation foo=property(foo). > > > HTH, > > I was able to get it t work with the decorator by doing this : > > def MyProperty(fcn): > return property(**fcn()) > > and using it like this : > > class MyClass(object): > def __init__(self): > self._foo = "foo" > self._bar = "bar" > > @MyProperty > def foo(): > doc = "property foo's doc string" > def fget(self): > return self._foo > def fset(self, value): > self._foo = value > def fdel(self): > del self._foo > return locals() # credit: David Niergarth > > @MyProperty > def bar(): > doc = "bar is readonly" > def fget(self): > return self._bar > return locals() > > Cheers, > Gabriel Also check out a related recipe that doesn't require returning locals() explicitly: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698 George From dteslenko at gmail.com Wed Mar 5 07:03:32 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 5 Mar 2008 15:03:32 +0300 Subject: draining pipes simultaneously In-Reply-To: References: Message-ID: <91325fec0803050403k14e87c2j44a79601a8fa9348@mail.gmail.com> On Wed, Mar 5, 2008 at 1:34 PM, wrote: > The Queue.get method by default is blocking. The documentation is not > 100% clear about that (maybe it should report > the full python definition of the function parameters, which makes > self-evident the default value) but if you do > help(Queue.Queue) in a python shell you will see it. > Hence, try using a timeout or a non-blocking get (but in case of a non > blocking get you should add a delay in the > loop, or you will poll the queues at naximum speed and maybe prevent > the other threads from accessing them). Thanks for advice! Finally I came up to following loop: while to.isAlive() or te.isAlive(): try: while True: line = qo.get(False) if out_filter: out_filter(line) except Queue.Empty: pass try: while True: line = qe.get(False) if err_filter: err_filter(line) except Queue.Empty: pass Inserting delay in the beginning of the loop causes feeling of command taking long to start and delay at the end of the loop may cause of data loss when both thread became inactive during delay. From lists at cheimes.de Sun Mar 23 21:24:25 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 24 Mar 2008 02:24:25 +0100 Subject: PyTuple_Check and other type check functions didn't check the NULL pointer In-Reply-To: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> References: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> Message-ID: NotGuru schrieb: > My questions is: is it necessary to check the null pointer in the > macro or it's a job for the user? Semantically all the type check > should report a false if a null pointer is encountered. I've already > had the patch to this issue but I am not sure if I think this problem > right. I don't know if there are some python core developers around > but I would like to hear all opinions towards this. Unless stated otherwise no Py* or PY* function is NULL safe. You have to check for NULL unless the docs *explicitly* say it's safe to call it with a NULL argument. Christian From metawilm at gmail.com Mon Mar 10 15:14:40 2008 From: metawilm at gmail.com (metawilm at gmail.com) Date: Mon, 10 Mar 2008 12:14:40 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <63i6j9F2793buU1@mid.uni-berlin.de> Message-ID: On Mar 9, 2:21 pm, "Diez B. Roggisch" wrote: > Is this soft-exception implemented anywhere, so that one can see what > experiences and best practices have evolved around using it? Lie's idea is to separate exceptions in two groups, those that must be handled and those that don't. A better way is to have two different ways to raise exceptions: one exceptional situation can be "Hard" in some situations and "Soft" in others, and it is up to the way of raising to make the choice, while the exception stays the same. Common Lisp has two ways of raising: functions "error" and "signal". Python's "raise" is like CL's "error": you end up in the debugger if the exception is not handled. Exceptions that are raised by CL's "signal" don't have to be caught: if there is no matching "except" clause the raise statement becomes a "pass". Or as Wikipedia states nicely: "Conditions are a generalization of exceptions. When a condition arises, an appropriate condition handler is searched for and selected, in stack order, to handle the condition. Conditions which do not represent errors may safely go unhandled entirely; their only purpose may be to propagate hints or warnings toward the user." http://en.wikipedia.org/wiki/Exception_handling#Condition_systems - Willem From castironpi at gmail.com Thu Mar 6 01:25:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 22:25:27 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: <0806e3fe-7f69-4c3e-871c-9ac1a2289e94@d62g2000hsf.googlegroups.com> > I accept my question about classes being singletons is not well-formed, > not even in my own mind. I guess one way of asking is, for any two class > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? C and D are instances of metaC in that. class metaC( type ): def what( self ): return self class C( metaclass= metaC ): pass class D( metaclass= metaC ): pass assert C is C.what() and D is D.what() #print( C.what(), D.what() ) C= metaC('C',(),{}) D= metaC('D',(),{}) assert C is C.what() and D is D.what() #print( C.what(), D.what() ) furthermore. From michael.wieher at gmail.com Mon Mar 17 16:18:33 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 15:18:33 -0500 Subject: placing a Python com object into Excel In-Reply-To: References: Message-ID: 2008/3/17, Mathew : > > Hi > I have seen examples from Mark Hammonds book where a Python COM object > is accessed from Excel with a VBA script. But, what if I want to Insert > a Python COM into the Sheet itself? > > When I try this, a list of available objects appear. But my object isn't > on the list. > > Anybody have any ideas? Well, how are you inserting it? My experience with MS-Visual Studio is that you first have to register the COM/ActiveX component with the system in some way (ie: so that Visual Studio knows it exists) and from there, you drop it into your application using the GUI. If Visual Studio hasn't been told the COM object exists, it won't be able to incorporate it. Here's a link describing how to insert a COM object in Visual Studio .NET. http://support.microsoft.com/kb/307367 If that doesn't help, look for something similar, not sure which version of VS you're running. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave_mikesell at fastmail.fm Sat Mar 8 21:11:12 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 18:11:12 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> On Mar 8, 5:14 pm, "K Viltersten" wrote: > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); > > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. > > I don't see how this is dislikeable. Please > explain. When get2Dfrom3D changes its signature but the comment is not changed. That's where I have a problem, and it's only a matter of time before it happens. From castironpi at gmail.com Sun Mar 9 16:48:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 13:48:07 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> Message-ID: D'Aprano suggested callbacks. How does this work for you? class SomeNumeric(object): def __div__(a, b): if b == 0: raise ZeroDivisionError ## Hard Exception... if a == 0: msgboard- ZeroNumerator() f = a / b i = a // b if f == float(i): msgboard- IntegerDivision() return a // b #? return i? else: msgboard- FloatDivision() return a / b #? return f? If it works, I can write some implementations of msgboard and discuss its scope. It sounded at one point like you were augmenting control flow, but you cleared that up by saying, raise SoftException is not a true raise. Correct? There is a limit to how many behaviors you can fit in a single statement in any language. What behaviors is determined by other choices in the language design. Those choices have many consequences, some linguistic, some social, and some personal. If a dictator always makes impersonal decisions, which linguistic + social ones should he make? If the answer is, "No, we will not strike note J and K because we elected to strike notes L and M instead", then it's disappointing, but it might ease that to know what L and M are. Lastly, that notation I wrote was kind of sly. I might favor msgboard( ZeroNumerator() ) or even msgboard.add( ZeroNumerator() ). How far are you willing to come from the OP's proposal to get it to work? If they add something half-way there, but you don't get exactly what you want, is that fair? From john106henry at hotmail.com Mon Mar 31 14:45:33 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 11:45:33 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <89d34053-4b16-49df-9153-eb3625249ad4@u10g2000prn.googlegroups.com> Message-ID: <7cee8a91-ebcc-43d0-8a84-63eca2409dc7@s19g2000prg.googlegroups.com> On Mar 31, 10:38 am, Amit Gupta wrote: > On Mar 31, 10:37 am, John Henry wrote: > > > > > On Mar 31, 10:24 am, Amit Gupta wrote: > > > > Hi > > > > I am looking for a some tool that can convert python scripts to > > > executable on Linux. > > > > I found freeeze.py as the only option so far. Couple of queries on > > > freeze: > > > > 1. Have anyone used the freeze utility and any experiences to share > > > from that? > > > 2. Is there any enterprise-level exe-builder for python on linux > > > (ActiveState has nothing)? > > > > Any other related commets are also welcome. > > > > Thanks > > > Amit > > > I don't know about freeeze.py but for me, I've been using py2exe, and > > also pyinstall quite often and they both work for me. > > Isnt py2exe for windows only? Not sure. I use it on windows. > I haven't looked at pyinstall.. Is it for linux? It appears so - according to http://www.pyinstaller.org/ From bj_666 at gmx.net Thu Mar 27 09:41:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Mar 2008 13:41:47 GMT Subject: Pickle: several class instance objects in one file? References: Message-ID: <651mgqF2dfhueU4@mid.uni-berlin.de> On Thu, 27 Mar 2008 12:28:25 +0000, Dominique.Holzwarth wrote: > Lets say I have instances of class A and class B: > > a = A() > b = B() > > Is it possible to pickle both of these instances to the same pkl-file or > will that have any bad impact for unpickle (i.e. the instance are > 'mixed' or 'destroyed')? Or should I rather use a seperate file for > every class instance I want to pickle? You can pickle a data structure, for example a tuple, that contains both instances. Or you can write one after the other into the pickle file. Then you'll have to retrieve them in two steps too. > Another very basic question about pickling class instances: > > To store the value of attributes of an instance is it enough for the > pickling-algorithm to use the __dict__ or do I have to implement the > _setstate_ and _getstate_ function? I didn't really get the meaning of > those while reading the python user manual... Usually `pickle` just works. Those methods can be used if you want to customize the process, for example if you don't want to pickle the entire object but just parts of it. Ciao, Marc 'BlackJack' Rintsch From needin4mation at gmail.com Mon Mar 24 13:00:45 2008 From: needin4mation at gmail.com (jmDesktop) Date: Mon, 24 Mar 2008 10:00:45 -0700 (PDT) Subject: Is IronPython real Python? Message-ID: I know that IronPython and CPython are different in that one does not use the .net framework, but are they both really the same Python language. From my basic understanding, it will depend on what the programmer's goal is as to which of the two would be used, but I didn't know if they were really the same language. From janeczek at gmail.com Thu Mar 27 14:36:34 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Thu, 27 Mar 2008 19:36:34 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: References: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Message-ID: <561cb5bc0803271136x35cf72f2ga2a5119c4379f9c5@mail.gmail.com> On Thu, Mar 27, 2008 at 7:23 PM, Joshua Kugler wrote: > You might want to take a look at this: > > http://www.artfulcode.net/articles/extending-python-almost-anything/ > > That might get you started at least on the calling Haskell part. Yes, ctypes is on my related works/projects to study list. I am trying to keep this public draft low on technical details, and focus on the idea/deliverables part. I am hoping that a casual python list subscriber is more likely to read/comment on a shorter document :) Thanks for your feedback! -- Regards, Michal From NeilFang2008 at gmail.com Mon Mar 10 05:25:04 2008 From: NeilFang2008 at gmail.com (Neil.Fang.CN) Date: Mon, 10 Mar 2008 02:25:04 -0700 (PDT) Subject: How to create Python object in C/C++ extension by class name? Message-ID: Hello I'm trying to write a C++ extension like this: //----------------------------------------------------------------------- // C++ code class ActorBase {...}; // export ActorBase to Python as a new type class ActorManager { void addNewActor(const char* actorClassName) { ????? } } // export ActorManagerto Python as a new type //----------------------------------------------------------------------- The question is how to implement ActorManger::addNewActor(), I want the class name can be a Python class which inherits the C++ class ActorBase? Thanks -- Neil From tjreedy at udel.edu Wed Mar 19 18:56:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2008 18:56:46 -0400 Subject: keeping state in an iterator object by rebinding next() References: <200803192036.22626.wbsoft@xs4all.nl> Message-ID: "Wilbert Berendsen" wrote in message news:200803192036.22626.wbsoft at xs4all.nl... | Hi, | | i am writing a simple parser, that generates tokens. The parser needs to | maintain some state, because some parts of the file consist of different | tokens. I thought the object could simply remember its state by assigning | it's next() method to the method that is currently parsing. When the state | changes, the called method rebinds next() and the next token will be returned | by that function. Here's an example, proving that this indeed works. For some undisclosed version. | >>> class A: I stronly suspect that if you make this a new-style class by adding '(object)', this will not work. See below. | ... def a(self): | ... self.next = self.b This attaches the class attribute (method) b to the instance | ... return 1 | ... def b(self): | ... self.next = self.a | ... return 2 | ... def __iter__(self): | ... return self Since A does not have a 'next' (or __next__, in 3.0), instances of A are not really iterators, under the new iterator protocol, and hence __iter__ above is not valid. See below. | ... | >>> a=A() | >>> a.a() | 1 | >>> a.next() | 2 | >>> a.next() | 1 | >>> j=0 | >>> for i in a: In 3.0a3, which uses new-style classes and iterator protocol, this croaks with TypeError: iter() returned non-iterator of type 'A' | ... j += 1 | ... if j > 10: break # prevent from running endlessly | ... print i I suspect that this only works because the for-loop, not finding A.next, used the old iterate-by-index protocol and calls a.next with 0, 1, 2, .... To find out, put 'print self' inside methods a and b. ... | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | >>> | | my question is: is this legal Python? In whatever version you used, it seems to be, but not in the future. | An iterator could save the next() method object, You mean, the iterator user. | and in that case it could stop working.... It works now, because | apparently the for- construct resolves 'next' each time for the object before | calling it. A standard idiom for explicit iteration with a new style iterator and 'while' would do just what you suggest. itnext = iter(a).next try: while True print itnext() except StopIteration: pass | The other solution would be just jumping to the correct method from within the | next() method. But that gives an extra call... Or, make a and b staticmethods, remove the self param, and make __iter__ a generator def __iter__(self): while True: yield self.next() The speed penalty of the indirection thru the generator is minimal. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Sun Mar 16 17:18:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Mar 2008 08:18:45 +1100 Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> Message-ID: <87abky1i6i.fsf@benfinney.id.au> sturlamolden writes: > If you don't know how to install a C compiler like Microsoft Visual > Studio, you should not be programming computers anyway. Utter elitist nonsense. Programming should be made easier, and I see Python as a very good language for making programming easier. Lowering the barrier for prospective hackers to get into programming is a good thing. The installation of a C compiler is incidental to that, and has no necessary connection with programming. Placing meaningless roadblocks, as you suggest should be done, is anathema to education. -- \ "The best mind-altering drug is truth." -- Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney From godzillaismad at gmail.com Mon Mar 17 07:26:56 2008 From: godzillaismad at gmail.com (Godzilla) Date: Mon, 17 Mar 2008 04:26:56 -0700 (PDT) Subject: Anomaly in time.clock() Message-ID: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> Hello, I have been reading a thread about time.clock() going backward, which is exactly what I am seeing... the thread generally leaning toward the problem is caused by multi-processor machines. But I am seeing it at a single CPU computer, and running XP. The error I am seeing between two very close invokation of time.clock() is always around 3.5 seconds! This is enough to throw a lot of the timing requirement in the software out of the window... this is a fairly serious problem. A quick fix will be to capture the time.clock() going backward 3.5 seconds, and then adjust rest of the system accordingly. But I don't feel like this is a good way around this problem. I was using time.time() before switching to time.clock(). The reason I changed is because I need a way to calculate elapsed time independent of system time. Should I just stick with time.time() instead? Or is there another way to calculate elapsed time accurately, independent of system time being changed? From max at alcyone.com Sun Mar 16 02:43:40 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 Mar 2008 23:43:40 -0700 Subject: 'join' in the wrong word for the method in class Thread. In-Reply-To: References: Message-ID: castironpi at gmail.com wrote: > 'join' in the wrong word for the method in class Thread. That's the standard term in threading. If it's not familiar to you, well, bummer, but there's not much more that can be done about that than for you to read the literature. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Take the slow train / To my destination -- Sandra St. Victor From lists at cheimes.de Tue Mar 25 22:33:43 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 26 Mar 2008 03:33:43 +0100 Subject: python hash() function In-Reply-To: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> References: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Message-ID: <47E9B607.4080204@cheimes.de> Alvin Delagon schrieb: > Hello, > >>>> hash("foobar") > -1969371895 > > Anyone can explain to me how the hash() function in python does its work? A > link to its source could help me a lot also. I'm looking for a way to > replicate this function in php. Thanks in advance. The code is in Objects/stringobject.c:string_hash() Christian From vokinloksar at yahoo.se Mon Mar 31 22:28:13 2008 From: vokinloksar at yahoo.se (vokinloksar at yahoo.se) Date: Mon, 31 Mar 2008 19:28:13 -0700 (PDT) Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: i mean vpython(www.vpython.org). tried wi5th the normal IDLE too and it worked later after i posted this but now it doesnt work again. and i havent chnaged my firewall in between. python.exe works but i want the idle not the dos-interpreter. From carlwenrich at gmail.com Fri Mar 21 11:15:55 2008 From: carlwenrich at gmail.com (Carl) Date: Fri, 21 Mar 2008 08:15:55 -0700 (PDT) Subject: How do I change the font size for the default coordinates in matplotlib? References: Message-ID: <40494a77-db0a-46a9-8b62-94e3f8ed5884@i7g2000prf.googlegroups.com> On Mar 20, 10:12 pm, "attn.steven.... at gmail.com" wrote: > On Mar 20, 8:20 pm, Carl wrote: > > > I've searched the user manual (and this forum) but I don't see > > anything that helps. > > Did you mean the font size for the ticks or for > the labels? Here's an example: > > from pylab import * > > x = arange(0, 2*pi, 0.01) > y = sin(2*pi*x) > > rcParams.update({'xtick.labelsize': 5, 'ytick.labelsize': 10}) > > subplot(111) > plot(x,y) > ylabel("Vert", fontsize=15) > xlabel("Horiz", fontsize=20) > show() > > -- > Hope this helps, > Steven It was the: rcParams.update({'xtick.labelsize': 5, 'ytick.labelsize': 10}) that fixed it. Thanks. From galaviel at yahoo.com Mon Mar 24 06:24:43 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Mon, 24 Mar 2008 10:24:43 +0000 (UTC) Subject: always getting 'None' return value from =?utf-8?b?UHlPYmplY3RfQ2FsbE9iamVjdA==?= References: <1206317136.3365.6.camel@localhost.localdomain> Message-ID: problem fixed ... my bad. I was using a dispatch mechanism where the C code always called the same python dispatch function, with the actual function name to invoke as arguments. Anyway, I forgot the 'return' statement. The code is below. Many thanks and apologies for the help provided :) def dispatch(*args): #print "Dispatch: args are " #print args[1:] global_dict = globals() return global_dict[args[0]](args[1:]) From jgelfand01 at gmail.com Wed Mar 26 11:21:39 2008 From: jgelfand01 at gmail.com (jgelfand) Date: Wed, 26 Mar 2008 08:21:39 -0700 (PDT) Subject: _tkinter fails when installing Python 2.4.4 References: <64tahuF2absebU1@mid.uni-berlin.de> <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> <64uoqiF2dcihhU1@mid.uni-berlin.de> Message-ID: <19b9409f-f4c3-4254-b445-980462f11bf1@13g2000hsb.googlegroups.com> On Mar 26, 7:02 am, "Diez B. Roggisch" wrote: > > I think the actual problem is that the linking doesn't find the > XftGlyphExtends. I can only guess, but it might be related to > 64-bit-problems. Make sure you have the library that contains the > XftGlyphExtends is available in the lib64 dirs and so forth. I tried running configure with --x-include="/usr/X11R6/include" --x- libraries="/usr/X11R6/lib" (in addition to the flags above) and got the same error. I believe XftGlyphExtends is defined in "Xft.h" which is located in the directory "/usr/X11R6/include/X11/Xft". Based on the output below, python looks in "/usr/X11R6/include" but not in this directory: building '_tkinter' extension gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/_tkinter.c - o build/temp.linux-x86_64-2.4/_tkinter.o gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/tkappinit.c - o build/temp.linux-x86_64-2.4/tkappinit.o gcc -pthread -shared build/temp.linux-x86_64-2.4/_tkinter.o build/ temp.linux-x86_64-2.4/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib - L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -ltk8.5 -ltcl8.5 - lX11 -o build/lib.linux-x86_64-2.4/_tkinter.so When I try setting CFLAGS="-I/usr/X11R6/include/X11/Xft" and re- running configure, I get the same error message regardless if I tell python to it to use the 32 bit of 64 bit X-Windows libraries. How should I force python to look in this directory? Thanks a lot -- Yosi From bj_666 at gmx.net Mon Mar 17 03:12:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Mar 2008 07:12:13 GMT Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> <47dd5caf$0$9029$5402220f@news.sunrise.ch> Message-ID: <646judF2ao2tkU1@mid.uni-berlin.de> On Sun, 16 Mar 2008 18:45:19 +0100, Martin Blume wrote: > I don't think this qualifies as a bug, but I am astonished > that the struct module does not tell you whether you are > big endian, you have to find out yourself with > struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] Maybe a little more compact and readable: In [92]: sys.byteorder Out[92]: 'little' Ciao, Marc 'BlackJack' Rintsch From coolman.guron at gmail.com Mon Mar 24 10:07:16 2008 From: coolman.guron at gmail.com (binaryj) Date: Mon, 24 Mar 2008 07:07:16 -0700 (PDT) Subject: URL encoding References: <9693ffda-1454-4d56-acee-1e6fc4ebeccb@h11g2000prf.googlegroups.com> Message-ID: On Mar 24, 7:04 pm, vvangelov... at gmail.com wrote: > Is there any method in the standard modules that can perform proper > url encoding according to RFC? whats wrong with the current encoding ??? it just works fine!!! or is it that u dont know about urllib.urlencode() ?? From Lie.1296 at gmail.com Sat Mar 29 16:06:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 29 Mar 2008 13:06:13 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Message-ID: On Mar 30, 2:57?am, mac_the_sco... at hotmail.com wrote: > Hi there. > I downloaded python a couple of days ago from the official site and > have started writing simple programs in the python gui (this being my > first attempt at programming ever). The only thing is when I write > python code in a text editor and save it as a .py file, when I double > click it all that happens is a black box flashes up on the screen, but > nothing else!? > > At first I thought this was because I had only written a hello world > program, and that the box had displayed "hello world" and then closed. > But then I wrote a program requiring user input and the same thing > happened... Am I doing something wrong? > > Thanks in advance for any help! > > //mac open the program in IDLE (or any other Python IDEs). I'm guessing that your program is printing a traceback (error) when trying to get input that's why it immediately closes itself. From tgl at sss.pgh.pa.us Mon Mar 3 11:12:28 2008 From: tgl at sss.pgh.pa.us (Tom Lane) Date: Mon, 03 Mar 2008 11:12:28 -0500 Subject: [SQL] compiling plpython compilation error In-Reply-To: <47CBFA04.30300@fmed.uba.ar> References: <47CBFA04.30300@fmed.uba.ar> Message-ID: <24554.1204560748@sss.pgh.pa.us> Gerardo Herzig writes: > Hi all. Im having a hard time trying to compile the plpython package. > This is the error make gives me: > /usr/lib/python2.5/config/libpython2.5.a(abstract.o): relocation > R_X86_64_32 against `a local symbol' can not be used when making a > shared object; recompile with -fPIC Well, I'd try following the error message's advice: use -fPIC not -fpic. Note that it's not real clear whether this needs to be done for plpython, or libpython, or perhaps both; so you might well be in for making a custom libpython installation. regards, tom lane From castironpi at gmail.com Tue Mar 18 06:09:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 03:09:08 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> Message-ID: <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> On Mar 17, 8:16?pm, Gabriel Genellina wrote: > On 17 mar, 19:43, castiro... at gmail.com wrote: > > > Can I allocate a second console window, so I can place certain output > > to that directly, and leave the original streams alone? ?I tried some > > things in subprocess (Py 3a3 /WinXP) but they failed. ?I don't know if > > it's supposed to be possible though, so I didn't press very hard or > > keep the code. ?If it is, I can go repro where it went south. ?Is it? > > Have you tried using the creationflags argument to subprocess.Popen? > Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation > for CreateProcess athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx > (Note that a process can be attached at most to one console) > > If your goal is to output some debug information, try using > OutputDebugString + the DebugView utility fromwww.sysinternals.com One console per process is fine, but I tried using 'cmd.exe', 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32) as separate processes. The sign is the console window splashes up and vanishes right away. >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdout= subprocess.P IPE, creationflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 >>> p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe', stdout= subprocess.PI PE, creationflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 >>> p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe /K', stdout= subprocess .PIPE, creationflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 >>> f= open( 'temp.txt', 'a' ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe /K', stdout= f, creatio nflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 ------------------------Couple other symptoms. >>> f.write( b'abc' ) 'f.write' is not recognized as an internal or external command, operable program or batch file. >>> f.write( b'abc' ) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\io.py", line 1240, in write s.__class__.__name__) TypeError: can't write bytes to text stream >>> f.write( 'abc' ) 3 >>> >>> ^Z >>> >>> ^Z ^Z 5000 09871234 ------------------------ >>> f.write('2'*2000) 2000 >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> f= os.fdopen( q[0], 'a' ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> f.read() Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\io.py", line 1378, in read res += decoder.decode(self.buffer.read(), True) File "C:\Programs\Python\lib\io.py", line 564, in read self._unsupported("read") File "C:\Programs\Python\lib\io.py", line 240, in _unsupported (self.__class__.__name__, name)) io.UnsupportedOperation: BufferedWriter.read() not supported >>> f.read(1) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\io.py", line 1384, in read readahead, pending = self._read_chunk() File "C:\Programs\Python\lib\io.py", line 1277, in _read_chunk readahead = self.buffer.read1(self._CHUNK_SIZE) AttributeError: 'BufferedWriter' object has no attribute 'read1' >>> f.write() Traceback (most recent call last): File "", line 1, in TypeError: write() takes exactly 2 positional arguments (1 given) >>> f.write('2') 1 >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags=0 ) 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 ------------------------- Writing my own process is an option. I did not try sysinternals yet. From shakefu at gmail.com Fri Mar 7 17:41:22 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:41:22 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <16db6135-a8eb-432f-9b50-91efe65e2b3b@13g2000hsb.googlegroups.com> Message-ID: On Mar 7, 4:33 pm, Carl Banks wrote: > On Mar 7, 5:08 pm, shak... at gmail.com wrote: > > > I'm new to python and I was wondering if there are any intelligent > > date/time parsing modules out there. I've looked at strptime (or > > whichever it is) and mxDateTime from the eGenix package. I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > > So are there any modules that allow for that kind of parsing? > > GNU date can do a lot of these things--if your Django server is > running Linux it probably has GNU date installed. (Might not be > practical to start a new process in the middle of a query, especially > a lot of them.) > > From a shell command line, get the current time (in seconds since > epoch, which you can pass to Python time functions) this way: > > date +"%s.%N" > > And you can enter all sort of relative and absolute date strings: > > date +"%s.%N" --date='last monday' > date +"%s.%N" --date='a year ago' > date +"%s.%N" --date='10pm tuesday' > > These all apparently work. Now all you have to do is call it from > Python using subprocess module and you're set. (DO NOT use os.system > for this since it starts a shell process, which is unnecessarily slow, > and dangerous when passed user input.) > > Carl Banks Super sweet! I didn't even know you could do craziness like that in python. Thanks for the advice! From rbossy at jouy.inra.fr Sat Mar 8 09:18:26 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 08 Mar 2008 15:18:26 +0100 Subject: os.chdir In-Reply-To: References: Message-ID: <1204985906.47d2a03248681@www.jouy.inra.fr> Quoting Maryam Saeedi : > I have a problem using os.chdir on linux. What should I do if I want to > change to root directory? The below does not work: > > os.chdir("~/dir1") It is not mentioned in the documentation but I'm pretty sure os.dir() doesn't do tilde expansion since this is usually performed by a shell. You should use instead: os.chdir(os.join(os.environ['HOME'], 'dir1')) Cheers, RB From roman at smoerz.org Fri Mar 7 05:04:52 2008 From: roman at smoerz.org (Roman Bertle) Date: 07 Mar 2008 10:04:52 GMT Subject: Looking for very light weight template library (not framework) References: Message-ID: * Malcolm Greene : > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. [...] > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. [...] You might look at YAPTU http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305A or YAPTOO http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465508, very small but powerful templating engines. I use YAPTU myself for invoice templating. Regards, Roman From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 21:09:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 01:09:46 -0000 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <13ur5mq7fugqgc1@corp.supernews.com> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > Gabriel Genellina wrote: >> That's what I said in another paragraph. "sum of coordinates" is using >> a different distance definition; it's the way you measure distance in a >> city with square blocks. I don't know if the distance itself has a >> name, but > I think it is called Manhattan distance in reference of the walking > distance from one point to another in this city. You know, there are other cities than Manhattan. Some of them even have streets and blocks. -- Steven From tjreedy at udel.edu Sat Mar 22 17:42:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Mar 2008 17:42:31 -0400 Subject: Django gets Wired Message-ID: from Wired magazine, April 2008 (arrived today), p.44: Expired: ASP.NET; Tired: PHP; Wired: Django Congrats to the Django crew. http://www.djangoproject.com/ From nick.fabry at coredump.us Wed Mar 19 17:40:39 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Wed, 19 Mar 2008 17:40:39 -0400 Subject: Improving datetime In-Reply-To: <47E17801.606@cheimes.de> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: On Mar 19, 2008, at 16:30, Christian Heimes wrote: > Nicholas F. Fabry schrieb: >> This is a query for information as to how to proceed. I am not a >> professional programmer, but I use Python a great deal to help me >> in my main job, which involves designing schedules for a global >> airline. As such, I use datetime (and dateutil) extensively, and >> after much use, I have come to some conclusions about their >> utility, and how to improve them. Some of these changes are quite >> minor and would result in a large increase in utility (low hanging >> fruit), while some changes are major, and would result in less >> obvious benefits - but these changes would increase the 'Python >> Zen' of them. >> So - where should I propose these changes? Here? python-dev? >> Should I write up a full PEP or should I just give a more informal >> outline with code samples? I would volunteer to help maintain/ >> improve datetime, but I don't speak C at all, unfortunately, and >> datetime appears to be in C. > > Please write a detailed but not too long proposal to the Python > ideas mailing list. The proposal should explain how you like to > improve the datetime module. But *please* don't write a novel. > You'll get more attention when the signal to noise ratio is high. A > bullet list of features is easier to read than a long text block. > Thank you for the prompt response and suggestion! I am writing up a proposal presently. There are, however, two broad category of changes - the 'easy' changes, which could be accomplished with little additional effort, and the 'hard' changes, which would require significant reworking of the datetime class (or a wrapper around it). I was going to break my proposal up into two parts, the easy part and the hard part. Does that sound like a good idea? Or should I unify the two? The prime purpose of all the changes, easy and hard, is to make timezone handling accurate and clear, reduce and make clearer the (application programmer) code required to use them, and give more informaton to the programmer about errors, not silently assume something and pass them. I have to sign up for that mailing list - I will do so, and submit my ideas there. Please clarify how long a novel is? The problem with the modules are not bugs, they are problems with real world use scenarios that result in inescabably ugly code without improvements to the module - so the explanations involve code samples and use cases... so they may be 'long'. Could you suggest a maximum number of (70 char) lines, or an example of an overly long proposal? > I'm a core developer and I may be interested in mentoring your > proposal. I can guide you through the process, review code and > commit it. > Thank you very much for the offer - I greatly appreciate it. I must admit, my motivation is because Python made programming so much fun for me again (my first machine was a Sinclair ZX80, long, long ago), and I want to improve this part of the language so datetime calculations are clean and neat (like the rest of Python) and don't force programmers to manually go through what the library should do for them. > Yes, the datetime module is written in C. But we may move the C code > to _datetime and create a facade module in Python. > That would be excellent for me, because the underlying datetime routines work correctly and quickly; it's the 'topmost' layer that needs to be improved to do the right thing. And, I could then actually write/maintain the Python code in the facade module, rather than request someone else 'do it for me' in C. To summarize my proposal VERY briefly: - Make aware datetime objects display in local time, but calculate/ compare in UTC. - Raise exceptions when an illegal or ambiguous datetime is instantated. Thank you again, Nick > Christian From skip at pobox.com Thu Mar 27 10:53:43 2008 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Mar 2008 14:53:43 +0000 (UTC) Subject: Is subprocess.Popen completely broken? Message-ID: I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: >>> proc = subprocess.Popen ("ls /tmp") Traceback (most recent call last): File "", line 1, in File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 594, in __init__ errread, errwrite) File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 1091, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I also tried explicitly referencing /usr/bin/ls. Same result. What gives? I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with 2.6alpha on Mac OS X. Frustrated in Chicago... Skip From carsten at uniqsys.com Tue Mar 18 03:30:58 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 18 Mar 2008 08:30:58 +0100 Subject: Multiple Submits in HTML Forms - Cherrypy In-Reply-To: <47df6bd4$1@news.unimelb.edu.au> References: <47df6bd4$1@news.unimelb.edu.au> Message-ID: <1205825458.3212.2.camel@localhost.localdomain> On Tue, 2008-03-18 at 07:14 +0000, Maurice LING wrote: > Hi, > > Assuming that I have this code for Cherrypy 3 > > class Welcome: > def index(self): > return """ >
> > >
""" > index.exposed = True > > How should I write "btn_handler" so that it will perform different > actions when different button is pressed? Something like this would do it: def btn_handler(self, AddBtn=None, EditBtn=None): if AddBtn: return "You pressed Add!" if EditBtn: return "You pressed Edit!" Alternatively you could use a kwargs dictionary and test it for the presence of the "AddBtn" or "EditBtn" keys. HTH, -- Carsten Haese http://informixdb.sourceforge.net From praveena_python at yahoo.com Thu Mar 27 14:29:36 2008 From: praveena_python at yahoo.com (Praveena B) Date: Thu, 27 Mar 2008 11:29:36 -0700 (PDT) Subject: How to take snap shot of the of project screen in Python Message-ID: <286574.25471.qm@web44807.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Wed Mar 12 10:45:29 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 12 Mar 2008 07:45:29 -0700 (PDT) Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: <20b5dc87-166c-4d57-9df6-3ae3bfd83cc1@u10g2000prn.googlegroups.com> On Mar 12, 10:18 am, Gerdus van Zyl wrote: > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus Search for "cartesian product" recipes. George From patrick.waldo at gmail.com Mon Mar 31 14:52:18 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 31 Mar 2008 11:52:18 -0700 (PDT) Subject: xlrd and cPickle.dump/rows to list Message-ID: <5dd95747-81af-4019-9995-944421ebdfc2@m71g2000hse.googlegroups.com> Hi all, I have to work with a very large excel file and I have two questions. First, the documentation says that cPickle.dump would be the best way to work with it. However, I keep getting: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\python_files\pickle_test.py", line 12, in ? cPickle.dump(book,wb.save(pickle_path)) File "C:\Python24\lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects I tried to use open(filename, 'w') as well as pyExcelerator (wb.save(pickle_path)) to create the pickle file, but neither worked. Any ideas would be much appreciated. Patrick From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 20:32:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 00:32:05 -0000 Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> Message-ID: <13udtk586ijktec@corp.supernews.com> On Sun, 23 Mar 2008 10:45:38 -0700, Paul Rubin wrote: > John Nagle writes: >> What's the cheapest way to test for an empty dictionary in Python? >> >> if len(dict.keys() > 0) : > > I like to think len(dict) is constant time but I haven't checked the > code. Same for bool(dict) (which is what you get when you run "if dict: > ..."). Except that "if dict" doesn't needlessly and wastefully create a bool. >>> from timeit import Timer >>> Timer("if {1:2}: pass").timeit() 1.1590199184417725 >>> Timer("if bool({1:2}): pass").timeit() 1.8825540542602539 Python knows the truth value of built-in types like dicts without actually converting them to bools, or for that matter calling __len__ or __nonzero__ on them. -- Steven From grflanagan at gmail.com Sat Mar 29 08:45:55 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Sat, 29 Mar 2008 05:45:55 -0700 (PDT) Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> Message-ID: <61b59d4e-b7c1-42d8-a132-4b36d63eeb26@m71g2000hse.googlegroups.com> On Mar 29, 11:01 am, Steven D'Aprano wrote: > On Sat, 29 Mar 2008 10:11:28 +0100, Roel Schroeven wrote: > > Steven D'Aprano schreef: > >> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > > >>> Gabriel Genellina wrote: > >>>> That's what I said in another paragraph. "sum of coordinates" is > >>>> using a different distance definition; it's the way you measure > >>>> distance in a city with square blocks. I don't know if the distance > >>>> itself has a name, but > >>> I think it is called Manhattan distance in reference of the walking > >>> distance from one point to another in this city. > > >> You know, there are other cities than Manhattan. Some of them even have > >> streets and blocks. > > > I'm not sure what your point is. The name > > "The" name? You go on to list four additional names, so why do you say > that "Manhattan distance" is THE name? When I studied this at university, > we called it the taxi metric. > > > of the distance happens to be > > Manhattan distance (or taxicab distance, rectilinear distance, L1 > > distance, city block distance; see > >http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid > > point. > > Wikipedia doesn't believe that M-D is the primary or most common name, > and the link you give redirects to "Taxicab distance". Googlefight > agrees: "Taxicab distance" is more than twice as common, and "rectilinear > distance" more than five times as common. > > My point was to draw attention to Robert's unconscious assumptions which > are reflected in his choice of language. Rectilinear distance applies to > more than "distance from one point to another in THIS city" (emphasis > added). > > It applies in parts of Rome, Sydney, London, Moscow and many other > places. It even applies to sleepy little country towns like Bendigo and > Mildura here in Australia. Manhattan is hardly the only place where > cities are carved up into rectangular or square city blocks, and I doubt [...] a metric by any other name... http://news.bbc.co.uk/2/hi/uk_news/northern_ireland/2595215.stm From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:18:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:18:50 -0300 Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> <4d1d7d83-8155-4c1a-a807-0b5c951e1192@d21g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 09:30:00 -0300, Graeme Glass escribi?: > On Mar 27, 11:01 am, Peter Otten <__pete... at web.de> wrote: >> a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc >> baa bab >> bac bba bbb bbc bca bcb bcc > > Here is a cool solution we came up with during a little interactive > session at our local meet up. > (http://www.python.org.za/pugs/cape-town/cape-town) > > s = 'abcdef' > ["".join([s[j] for j in range(len(s)) if x & (1 << j)]) for x in > range(1,2**len(s)) ] But it's doesn't generate the right sequence, and a lot of elements are missing. For 'abc': ['a', 'b', 'ab', 'c', 'ac', 'bc', 'abc'] It lacks ba, bb, ca, cb, cc, all b??, all c?? - see the sequence quoted above. -- Gabriel Genellina From pavlovevidence at gmail.com Wed Mar 26 14:04:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Mar 2008 11:04:14 -0700 (PDT) Subject: naive packaging question References: Message-ID: <006bd428-beca-4420-b54b-aed805ff1e73@m36g2000hse.googlegroups.com> On Mar 26, 12:33 pm, Scott Sharkey wrote: > Here's the directory structure that I've got so far: > > project
top level directory > setup.py > company eventually, we'll have other modules > __init__.py > error.py some classes that will be used in all > log.py modules > acctdb the acct db interface directory > __init__.py > api.py the abstract class def (derived from object) > specific.py the specific implementation, derived > from the api base class > > For arguments sake, let's call the base class (defined in api.py) > 'BaseClass', and the specific implementation 'SpecificClass(BaseClass)' > > So, in the acctdb/__init__.py, do I do something like this: > > if SPECIFIC_CLASS: > from company.acctdb.specific import SpecificClass as BaseClass Seems pretty reasonable to me. Do you have any specific reasons for being concerned about this organization? (My only minor suggestion would be not to import the SpecificClass as BaseClass, but instead with a name that's different from both, for example, PublicClass. All that does is to avoid a tiny bit of potential confusion down the road.) Carl Banks From castironpi at gmail.com Sat Mar 22 03:23:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 00:23:32 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> Message-ID: <210f1e24-649a-43c0-b975-8209211d56de@a70g2000hsh.googlegroups.com> On Mar 21, 1:08?pm, Gabriel Genellina wrote: > Sane programmers replace that crazyness with this code: > > tuple(x+1 for x in y) > > Sane programmers -like D'Aprano, Jerry Hill and me- replace that > crazyness with this code: > > tuple(x/2.5 for x in y) > > Sane programmers don't write such semi-functional things (unless it > helps expressing the problem in certain domains). > I now think that deprecating map, lambda & Co. was a good thing after > all. If you write it that way the first time, you need therapy. Actually, at this point, I (for one, personally) want to investigate 'certain domains'. Tell me it's really bad at everything or what it's good at. What can I respect about it? From code at pizzashack.org Wed Mar 26 19:59:46 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 26 Mar 2008 19:59:46 -0400 Subject: Python 2.2.1 and select() In-Reply-To: <20080326164951.GA6349@noah.org> References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> <20080325020356.GF26870@dragontoe.org> <20080326164951.GA6349@noah.org> Message-ID: <20080326235946.GL26870@dragontoe.org> On Wed, Mar 26, 2008 at 09:49:51AM -0700, Noah Spurrier wrote: > On 2008-03-24 22:03-0400, Derek Martin wrote: > >That's an interesting thought, but I guess I'd need you to elaborate > >on how the buffering mode would affect the operation of select(). I > >really don't see how your explanation can cover this, given the > >following: > > I might be completely off the mark here. I have not tested your code or even > closely examined it. I don't mean to waste your time. I'm only giving a > reflex response because your problem seems to exactly match a very common > situation where someone tries to use select with a pipe to a subprocess > created with popen and that subprocess uses C stdio. Yeah, you're right, more or less. I talked to someone much smarter than I here in the office, who pointed out that the behavior of Python's read() without a specified size is to attempt to read until EOF. This will definitely cause the read to block (if there's I/O waiting from STDERR), if you're allowing I/O to block... :( The solution is easy though... def set_nonblock(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) Then in the function, after calling popen: set_nonblock(io.fromchild.fileno()) set_nonblock(io.childerr.fileno()) Yay for smart people. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From hniksic at xemacs.org Fri Mar 14 11:00:07 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 14 Mar 2008 16:00:07 +0100 Subject: %x unsigned? Message-ID: <87skytbbbc.fsf@mulj.homelinux.net> The %x conversion specifier is documented in http://docs.python.org/lib/typesseq-strings.html as "Unsigned hexadecimal (lowercase)." What does "unsigned" refer to? >>> '0x%x' % 10 '0xa' >>> '0x%x' % -10 '0x-a' Is this a bug or is %x misdocumented? From mmanns at gmx.net Fri Mar 21 15:48:09 2008 From: mmanns at gmx.net (Martin Manns) Date: Fri, 21 Mar 2008 20:48:09 +0100 Subject: How can I make a function equal to 0? Message-ID: Hi, Is there a way to create a function that is equal to 0? I try to redefine __cmp__ but I am pretty stuck. Something like: >>> def f(): return "" ... >>> # Some magic >>> f == 0 True Thanks in advance Martin From arnodel at googlemail.com Tue Mar 25 15:44:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 25 Mar 2008 12:44:33 -0700 (PDT) Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> On Mar 25, 6:13?pm, j vickroy wrote: > Hello, > > Here is some pseudo-code that hopefully illustrates what I want to do: > > records = list(...) > for record in records: > ? ? new_fcn = define_a function_for(record) > ? ? instance = my_new_class_instance() > ? ? setattr(instance, 'myfcn', new_fcn) > ? ? instance.execute() # instance.execute() calls instance.myfcn(*args) > > I have looked at some of the functions in the *new* module and > new.code(...), new.function(...), and new.instancemethod(...) appear to > do what I want, but I do not know how to use new.code() and > new.function() -- specifically what its *global* parameter should be. The best way to understand how new.function and new.code work is to look at the Python source. (Objects/funcobject.c and Objects/ codeobject.c, actual objects are defined in and Include/funcobject.h Include/code.h). However, to create a function dynamically in Python it is often no more trouble than a def statement: Funnily enough I can't think of a nice example ATM so here is a bad one: say you want to create a function that checks the spelling of a word, regardless of case. You could a function that returns on-the- fly created functions that check the spelling of a word like this: def get_spellchecker(word): word = word.upper() def check_spelling(candidate): return candidate.upper() == word return scheck_spelling Then >>> check_hypo = get_spellchecker('hypopothamus') >>> check_hypo('Hypopothamus') True >>> check_hypo('Big scary mammal') False (Warning: this is all untested). HTH -- Arnaud From tamim.shahriar at gmail.com Mon Mar 3 09:38:06 2008 From: tamim.shahriar at gmail.com (subeen) Date: Mon, 3 Mar 2008 06:38:06 -0800 (PST) Subject: Delete hidden files on unix References: Message-ID: On Mar 3, 6:13 pm, Philipp Pagel wrote: > loial wrote: > > How can I delete hidden files on unix with python, i.e I want to do > > equivalent of > > rm .lock* > > Here is one way to do it: > > import os, glob > for filename in glob.glob('.lock*'): > os.unlink(filename) > > Alternatively, you could also do this: > > import os > os.system('rm .lock*') > > cu > Philipp > > -- > Dr. Philipp Pagel > Lehrstuhl f. Genomorientierte Bioinformatik > Technische Universit?t M?nchenhttp://mips.gsf.de/staff/pagel Another way is to execute the linux command directly :) Check here: http://love-python.blogspot.com/2008/02/execute-linux-commands-in-python.html regards, subeen. http://love-python.blogspot.com From tenax.raccoon at gmail.com Mon Mar 10 19:10:50 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 10 Mar 2008 16:10:50 -0700 (PDT) Subject: wxPython: some help with Drag&Drop References: Message-ID: <53d59d18-5774-4cef-b34c-f9646888a3c4@d21g2000prf.googlegroups.com> Eric von Horst wrote: > Hi, > > I need some advice on Drag&Drop. > > What I want to achieve is the following: > - I have a window that is divided in two : on the left hand I > have a wx.TreeCtlr and on the other hand a wx.StaticBitmap > > I want to be able to drag an item from the tree onto the static > bitmap. > > I know how to do drag&drop in a treeCtrl but is there a way that I can > make the bitmap detect that something has been dropped on it? > > I would only need to know the name of the tree obj that was dropped on > the bitmap (and the location) > > Any help much appreciated > > > > Erik Take a look at the wxPython demo [1]. In the "Clipboard and DnD" section, there's the "CustomDragAndDrop" demo. It sounds like that's exactly what you want. (It uses the wx.PyDropTarget class to accomplish this, BTW.) [1] The demo package for your platform can be found at "http:// www.wxpython.org/download.php#binaries" --Jason From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:02:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:02:31 -0300 Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: En Sat, 29 Mar 2008 21:48:21 -0300, Paul McGuire escribi?: > What is the collision of spheres? Is it the melding of a sphere of > influence and cosmic sphere? What does it mean to say that such a > collision "doesn't work"? The sphere is the optimal solid for storing > the maximum volume in the minimum area. A sphere can retain the Too much logical cohesion, even if you didn't want it... I'm sorry but you still can't emulate Aaron's jumping thoughts - maybe if you try harder next time... -- Gabriel Genellina From jorge.vargas at gmail.com Sun Mar 9 13:36:44 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sun, 9 Mar 2008 11:36:44 -0600 Subject: Returning values from function to Python shell/IPython In-Reply-To: References: Message-ID: <32822fe60803091036l3380f48aia49348a46c93c0d@mail.gmail.com> On Sun, Mar 9, 2008 at 11:07 AM, Karlo Lozovina <_karlo_ at mosor.net> wrote: > Jorge Vargas wrote: > > > well after all it's a function so the only ways you can get things out > > of it are: > > - return a dict with all the objects > > - use global (very messy) > > - use a decorator to do either of the above. > > Messy, all of those... :(. > > > > on the other hand have you consider using a proper test package? > > instead of inspecting the objects manually from the shell you could > > make it all automatic. with assert statements. you could use the std. > > python testing modules http://docs.python.org/lib/development.html or > > something less verbosed like nose > > Usually, I'm using standard Python testing modules, but sometimes that is > just an overkill. Sometimes I like to do 'exploratory programming', > especially in the early phases of development - create a bunch of objects I > want to play with and do that from IPython. Only way I found out to > somewhat automate this procedure is to have a function that creates all of > the test objects, and then raises an exception at the end. IPython starts > ipdb, so I can work with the objects the function created (without copying > them back to the shell). But this somehow looks too hack-ish for me, so I > was wondering if there was an alternative... > ohhh if that is the case then what you are doing seems to be the optimal. Just have module lvl code ran the testing in fact I don't even put those into the if __name__, the reason is that this is just temp testing that will later become real unit testing, and will never hit a production app. it gives you the most flexibility. > Anyway, thanks for your answer ;). > welcome > > > -- > Karlo Lozovina -- Mosor > -- > http://mail.python.org/mailman/listinfo/python-list > From Lie.1296 at gmail.com Tue Mar 11 12:47:26 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 09:47:26 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> On Mar 10, 12:08?pm, Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? > > Thanks in advance, > Nathan P. Factorial algorithm is a very simple and common algorithm, and it's one of the most basic of all recursive algorithm def fact(x): return x * fact(x - 1) That recursive function is very close to the basic definition of factorials, that is x! = x * (x - 1)! If however, you expected x to be a real (float) value, you'd better consider the gamma function as Mark Dickinson pointed out. Wikipedia is a good start to create your gamma function: http://en.wikipedia.org/wiki/Factorial http://en.wikipedia.org/wiki/Gamma_function From castironpi at gmail.com Sun Mar 2 13:16:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 10:16:46 -0800 (PST) Subject: Problem with the strip string method References: Message-ID: On Mar 2, 11:45?am, Steve Holden wrote: > I suspect what you need is the .replace() method. The information's there-- the word 'contiguous' might clear it up a bit. > > Return a copy of the string with the > > leading and trailing characters removed. > > The chars argument is a string > > specifying the set of characters to be > > removed. If omitted or None, the chars > > argument defaults to removing > > whitespace. The chars argument is not a > > prefix or suffix; rather, all > > combinations of its values are stripped: Return the string's substring from the first character not a member of 'chars' to the last such. Remove contiguous leading and trailing members of 'chars'. If omitted or None, 'chars' defaults over to the set of whitespace set( "\n\r\t " ). (XXX TODO: ask Steve Reg Ex Guru this). From http Sun Mar 2 02:23:21 2008 From: http (Paul Rubin) Date: 01 Mar 2008 23:23:21 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> Message-ID: <7xskz9wpw6.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > def mean(data): return sum(data)/len(data) > > That does the right thing for data, no matter of what it consists of: > floats, ints, Decimals, rationals, complex numbers, or a mix of all of > the above. One of those types is not like the others: for all of them except int, the quotient operation actually is the inverse of multiplication. So I'm unpersuaded that the "mean" operation above does the "right thing" for ints. If the integers being averaged were prices in dollars, maybe the result type should even be decimal. For this reason I think // is a good thing and I've gotten accustomed to using it for integer division. I can live with int/int=float but find it sloppy and would be happier if int/int always threw an error (convert explicitly if you want a particular type result). From cabalamat at googlemail.com Tue Mar 25 10:23:57 2008 From: cabalamat at googlemail.com (Phil) Date: Tue, 25 Mar 2008 14:23:57 +0000 (UTC) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> Message-ID: On 2008-03-18, sturlamolden wrote: > First, I recommend that you write readable code! Don't use Python as > if you're entering the obfuscated C contest. > > Two particularly important points: > > * Comments are always helpful to the reader. It would be nice if this was the case! I once saw a preogram where a line of code like this: foo++; Would be annotated with a comment like this: /****************************************************/ /* */ /* Increment foo */ /* */ /****************************************************/ This comment was worse than useless, because it (and others like it) took up space that distracted from the information-containing parts of the code. From ckimyt at gmail.com Wed Mar 5 06:32:55 2008 From: ckimyt at gmail.com (Mike) Date: Wed, 5 Mar 2008 03:32:55 -0800 (PST) Subject: Using re module better Message-ID: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> I seem to fall into this trap (maybe my Perl background) where I want to simultaneously test a regular expression and then extract its match groups in the same action. For instance: if (match = re.search('(\w+)\s*(\w+)', foo)): field1 = match.group(1) field2 = match.group(2) ... (compare to Perl:) if($foo =~ /(\w+)\s*(\w+)/) { $field1 = $1; $field2 = $2; ... } Problem is, my python is invalid above. What's the pythonic way to do this? Thanks in advance O Python Charmers Mike From Afro.Systems at gmail.com Tue Mar 25 08:34:17 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 05:34:17 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> Message-ID: <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> > Rather than use Foo.bar(), use this syntax to call methods of the > super class: > > super(ParentClass, self).method() Hi Jeff, here is the nw version which cause an error class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = super(Foo, self).getid() b = self.id return '%d.%d' % (a,b) FooSon().getid() Traceback (most recent call last): File "a.py", line 19, in FooSon().getid() File "a.py", line 14, in getid a = super(Foo, self).getid() AttributeError: 'super' object has no attribute 'getid' From spamspam at spam.eggs Mon Mar 17 04:48:33 2008 From: spamspam at spam.eggs (Ben C) Date: Mon, 17 Mar 2008 03:48:33 -0500 Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: On 2008-03-17, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. It does, you just right-click and go "set breakpoint". But yes IDLE is a bit basic. From george.sakkis at gmail.com Tue Mar 18 21:19:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 18:19:16 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> Message-ID: <1c9f7516-bb8d-4023-8653-6b1831a36769@e6g2000prf.googlegroups.com> On Mar 18, 5:34 pm, Duncan Booth wrote: > castiro... at gmail.com wrote: > >> > > On Mar 17, 1:31 pm, Duncan Booth > >> > > wrote: > > >> > >> A common explanation for this is that lists are for homogenous > >> > >> collections, tuples are for when you have heterogenous > >> > >> collections i.e. related but different things. > > >> > > I interpret this as meaning that in a data table, I should have a > >> > > list of records but each record should be a tuple of fields, > >> > > since the fields for a table usually have different forms whereas > >> > > the records usually all have the same record layout. > > >> >>> b in b > >> False > > > That's actually interesting. > > Just for the avoidance of doubt, I didn't write the 'b in b' line: > castironpi is replying to himself without attribution. > > P.S. I still don't see the relevance of any of castironpi's followup to my > post, but since none it made any sense to me I guess it doesn't matter. Plus, it does work fine over here: Python 2.5.1 (r251:54863, May 8 2007, 14:46:30) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = [] >>> a.append(a) >>> a [[...]] >>> a in a True George From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 21:31:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 02:31:58 -0000 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: <13sulsu4nbr2199@corp.supernews.com> On Wed, 05 Mar 2008 21:05:31 -0500, Terry Reedy wrote: > If I understand your question, classes are not singletons: >>>> ll=[] >>>> for i in range(2): > import string > ll[i]=string Where's the IndexError? :-) >>>> ll[0] is ll[1] > True But yes, modules are singletons in that way, at least if you go through the import mechanism. >>>> for i in range(2): > class C: pass > ll[i] = C > > >>>> ll[0] is ll[1] > False Ah, but each time around the loop you create a *new class* that just happens to be called C. An alternative way to see similar behaviour is: def foo(x=None): class C(object): X = x return C Naturally foo() is foo() gives False -- although both classes are called C, they are different classes that just happen to have the same state. I accept my question about classes being singletons is not well-formed, not even in my own mind. I guess one way of asking is, for any two class objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? -- Steven From ptmcg at austin.rr.com Mon Mar 24 08:50:12 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 05:50:12 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> <17e6ca72-0b61-45a4-9604-dda4029ba5eb@e23g2000prf.googlegroups.com> Message-ID: On Mar 23, 4:04?pm, rh0dium wrote: > > I needed to tweak it a bit to ignore the comments.. ?Namely this fixed > it up.. > > ? ? mainDict = dictOf( > ? ? ? ? ? ? Group(Word(alphas)+Optional(quotedString)), > ? ? ? ? ? ? Suppress("{") + attrDict + Suppress("}") > ? ? ? ? ? ? ) | cStyleComment.suppress() > > Thanks again. ?Now I just need to figure out how to use your dicts to > do some work..- Hide quoted text - > > - Show quoted text - I'm glad this is coming around to some reasonable degree of completion for you. One last thought - your handling of comments is a bit crude, and will not handle comments that crop up in the middle of dict entries, as in: color = /* using non-standard color during testing */ "plum" The more comprehensive way to handle comments is to call ignore. Using ignore will propagate the comment handling to all embedded expressions, so you only need to call ignore once on the top-most pyparsing expression, as in: mainDict.ignore(cStyleComment) Also, ignore does token suppression automatically. -- Paul From dstromberglists at gmail.com Wed Mar 26 15:52:42 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Wed, 26 Mar 2008 19:52:42 GMT Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: On Wed, 26 Mar 2008 19:45:34 +0100, Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 19:04:44 schrieb David Anderson: >> HOw can we use express pointers as in C or python? > > There's no such thing as a pointer in Python, so you can't "express" > them either. Was this what you were trying to ask? Strictly speaking, many objects are passed by reference, which is kind of pointer-like, even though it doesn't expose the true messiness of a true pointer. Also strictly speaking, if you use SWIG, it can wrap up pointers from other languages as a python object to be passed around within a python program. From jeff at schwabcenter.com Fri Mar 14 19:33:36 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 14 Mar 2008 16:33:36 -0700 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: Roel Schroeven wrote: > castironpi at gmail.com schreef: >> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>> Subject: RIP: Joseph Weizenbaum >>>> Creator of Eliza: >>>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>>> -- >>> How do you feel about creator of Eliza? >> >> What is Eliza? > > Does that question interest you? Well played, sir. -- Earlier you said what is Eliza. Do you still feel that way? From lists at cheimes.de Tue Mar 25 18:19:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 25 Mar 2008 23:19:09 +0100 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: Dark Wind schrieb: > Hi, > > In most of the languages ^ is used for 'to the power of'. In python we have > ** for that. But what does ^ do? > I could not get it just by using it ... some examples are: > 1^1 returns 0 > 2^2 returns 0 > 1^4 returns 5 > 4^1 returns 5 > 3^5 returns 6 > 5^3 returns 6 ...... ^ is exclusive or (xor) # 1 ^ 1 = 0 >>> 1 ^ 1 0 # 01 ^ 10 = 11 >>> 1 ^ 2 3 # 01 ^ 11 = 10 >>> 1 ^ 3 2 # 001 ^ 100 = 101 >>> 1 ^ 4 5 Christian From dundeemt at gmail.com Mon Mar 17 22:00:49 2008 From: dundeemt at gmail.com (dundeemt) Date: Mon, 17 Mar 2008 19:00:49 -0700 (PDT) Subject: PyCon video editing Message-ID: Anyone know who is in charge of this? I'd like to help out if I could. -jeff hinrichs From 2huggie at gmail.com Thu Mar 20 01:38:37 2008 From: 2huggie at gmail.com (Timothy Wu) Date: Thu, 20 Mar 2008 13:38:37 +0800 Subject: xml sax In-Reply-To: <47E15155.4050008@jouy.inra.fr> References: <47E15155.4050008@jouy.inra.fr> Message-ID: Oh right, why didn't I think of that. =) Many thanks. Timothy On Thu, Mar 20, 2008 at 1:45 AM, Robert Bossy wrote: > Timothy Wu wrote: > > Hi, > > > > I am using xml.sax.handler.ContentHandler to parse some simple xml. > > > > I want to detect be able to parse the content of this tag embedded in > > the XML. > > 174 > > > > > > Is the proper way of doing so involving finding the "Id" tag > > from startElement(), setting flag when seeing one, and in characters(), > > when seeing that flag set, save the content? > > > > What if multiple tags of the same name are nested at different levels > > > > and I want to differentiate them? I would be setting a flag for each > level. > > I can imagine things get pretty messy when flags are all around. > > > Hi, > > You could have a list of all opened elements from the root to the > innermost. To keep such a list, you append the name of the element to > this stack at the end of startElement() and pop it off at the end of > endElement(). > > In this way you have acces to the path of the current parser position. > In order to differentiate between character data in Id and in Id/Id, you > just have to iterate at the last elements of the list. > > Cheers, > RB > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Wed Mar 19 17:16:43 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 19 Mar 2008 14:16:43 -0700 (PDT) Subject: Fate of the repr module in Py3.0 Message-ID: Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , and saw that the repr module was slated for vaporization. I've only used the module a few times ever. I'm curious if the community wants it kept around or whether it is considered clutter. The PEP is going to be finalized soon, so if you have issues with it, they should be sent to the PEP author or brought up on the list, http://mail.python.org/mailman/listinfo/stdlib-sig . Raymond From fetchinson at googlemail.com Tue Mar 11 03:05:17 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 11 Mar 2008 00:05:17 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > The second thing I'll try (after trying > your suggestion) is based on this paper which I found in the meantime: > http://salesin.cs.washington.edu/abstracts.html#MultiresQuery > In case anyone is interested, it describes a multiresolution querying > algorithm and best of all, it has pseudo code for the various steps. I > don't know yet how difficult the implementation will be but so far > this looks the most promising. Actually, the exact same algorithm has already been implemented in ....... drum roll ............ python! http://members.tripod.com/~edcjones/pycode.html From http Sat Mar 29 05:39:11 2008 From: http (Paul Rubin) Date: 29 Mar 2008 02:39:11 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> Message-ID: <7xve35kgxs.fsf@ruckus.brouhaha.com> Paul Rubin writes: > aio is also used for sockets, while twisted and asyncore use select or > something similar. That is asynchronous but in a different sense of > the word. See also: http://www.kegel.com/c10k.html Hmm that actually says that in Linux 2.6.0#-test2 sockets weren't supported. I can't tell the situation from the man page on the system I'm using right now. I may have misremembered but I thought I talked with someone a while back who was using aio in a high concurrency VOIP system and that it was beating other approaches. I don't know what kernels were involved etc. Anyway using this stuff in Python would be overkill. From Robert.Bossy at jouy.inra.fr Thu Mar 13 12:09:43 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 13 Mar 2008 17:09:43 +0100 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> <47D94D61.9010708@jouy.inra.fr> <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> Message-ID: <47D951C7.3090900@jouy.inra.fr> Robert Rawlins wrote: > Hi Guys, > > Well thanks for the response, I followed your advice and chopped out all the > crap from my class, right down to the bare __init__ and the setter method, > however, the problem continued to persist. > > However, Robert mentioned something about unindented lines which got me > thinking so I deleted my tab indents on that method and replaces them with > standard space-bar indents and it appears to have cured the problem. > Aha! Killed the bug at the first guess! You owe me a beer, mate. RB From duncan.booth at invalid.invalid Mon Mar 17 12:03:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 16:03:18 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: Ninereeds wrote: > On Mar 17, 1:31 pm, Duncan Booth wrote: > >> A common explanation for this is that lists are for homogenous >> collections, tuples are for when you have heterogenous collections i.e. >> related but different things. > > I interpret this as meaning that in a data table, I should have a list > of records but each record should be a tuple of fields, since the > fields for a table usually have different forms whereas the records > usually all have the same record layout. That is indeed what Python's Database API usually does (although it doesn't mandate it): .fetchmany([size=cursor.arraysize]) Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. From duncan.booth at invalid.invalid Sun Mar 2 06:10:16 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Mar 2008 11:10:16 GMT Subject: Question about lambda and variable bindings References: <47CA160C.3000305@gmail.com> Message-ID: Michael Torrie wrote: > poof65 wrote: >> An idea, i don't know if it will work in your case. >> >> for x in xrange(10): >> funcs.append(lambda p,z=x: testfunc(z+2,p)) > > Good idea. I will try it. I also figured out a way to architecture my > program differently to avoid this problem. But this idiom might be > handy in certain situations. Suppose you need to provide a callback > function with a fixed signature to some library routine. But you want > to add extra contextual data to your callback. This just might be the > ticket. There are three obvious ways to solve your problem: 1) Using a default argument as above is the original and used to be the only way to do it. 2) Using a factory function to generate the function: def gencaller(fn, x): def caller(p): return fn(x+2, p) return caller for x in xrange(10): funcs.append(gencaller(testfunc, x)) 3) Using functools.partial: from functools import partial for x in xrange(10): funcs.append(partial(testfunc, x+2)) or even: funcs = [partial(testfunc, x+2) for x in range(10)] A lot depends on what your real code actually wants to pass as the parameters. If they are some complicated expression you cannot evaluate until it is called then use a factory function, if it is something simple as in your example then partial is easily the cleanest. From castironpi at gmail.com Thu Mar 13 19:45:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 16:45:31 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> Message-ID: > > Basically, the above code is saying that foo.foobar is not the same as > > getattr(foo, 'foobar'). > > > What gives? ?This breaks my understanding of id(), the is operator, and > > getattr(). > > 4. ?Both points above follow from the fact that foo.bar is really a > function call that returns a (potentially) new object: in fact what > really happens is something like > > ? ? Foo.__dict__['bar'].__get__(foo, Foo). > > So every time foo.bar is executed an object is (or may be) created, > with a new id. When is it? Why is the 'owner' argument there? Do you ever use '__set__'? From lists at cheimes.de Sat Mar 22 17:48:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Mar 2008 22:48:31 +0100 Subject: Problem with complex numbers In-Reply-To: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> References: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> Message-ID: Matthias G?tz schrieb: > So if somebody can help me, it would be nice. Thanks. The complex type is implemented in C. It's totally unrelated to Complex.py. Christian From mensanator at aol.com Tue Mar 4 01:12:45 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 22:12:45 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> On Mar 3, 11:58?pm, Erik Max Francis wrote: > Mensanator wrote: > > While we're on the subject of English, the word "worthless" > > means "has no value". So, a program that doesn't work would > > generally be "worthless". One that not only doesn't work but > > creates side effects that cause other programs to not work > > (which don't have bugs) would be "worse than worthless". > > All programs have bugs, which means that in some circumstances, they > won't work. ? And in such circumstances, would be worthless. > Therefore, by your reasoning, all programs are worse than > useless. That doesn't follow from my reasoning. Suppose you downloaded a new calculator program that couldn't add properly. That would be useless to you, right? But suppose the program contained a virus that erased your hard drive. That would be "worse than useless", wouldn't it? > > > I'm not hard to please at all. > > No, of course not, since logically you must think all software is useless. Somehow, I expected better logic from people who call themselves programmers. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > ? ?Life is a zoo in a jungle. > ? ? -- Peter de Vries From troworld at gmail.com Mon Mar 3 18:09:31 2008 From: troworld at gmail.com (Tro) Date: Mon, 3 Mar 2008 18:09:31 -0500 Subject: Altering imported modules In-Reply-To: <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> References: <200803011856.27611.troworld@gmail.com> <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> Message-ID: <200803031809.32005.troworld@gmail.com> On Sunday 02 March 2008, Paul McGuire wrote: > On Mar 2, 3:48?pm, Tro wrote: > > On Sunday 02 March 2008, Terry Reedy wrote: > > > "Tro" wrote in message > > >news:200803011856.27611.troworld at gmail.com... > > > > > > | Hi, list. > > > | > > > | I've got a simple asyncore-based server. However, I've modified the > > > > > > asyncore > > > > > > | module to allow me to watch functions as well as sockets. The > > > | modified asyncore module is in a specific location in my project and > > > | is imported > > > > > > as > > > > > > | usual from my classes. > > > | > > > | Now I'd like to use the tlslite library, which includes an asyncore > > > | mixin class. However, tlslite imports "asyncore", which doesn't > > > | include my own modifications. > > > | > > > | I'd like to know if it's possible to make tlslite load *my* asyncore > > > > > > module > > > > > > | without changing any of the tlslite code. > > > > > > If your module is also 'asyncore' and comes earlier in the search path, > > > I would expect the import to get yours. > > > > It's not. It has a package prefix like my.package.asyncore. I think I can > > either move my version of asyncore up a couple of levels or add the > > my.package directory to sys.path. > > > > My version of asyncore imports several functions from the built-in > > asyncore. Now that my version of it is imported as asyncore, how would it > > import the built-in version from python2.5/site-packages? > > > > Thanks, > > Tro > > > > > > What happens if you do "import my.package.asyncore as asyncore"? > > If that doesn't work (trying the simplest hack first), I know that > there are various hooks in the import mechanism that should help. In the classes that use my version of asyncore currently, that is how I do it. I import my version as "import my.package.asyncore as asyncore". In my asyncore module I do "import asyncore", because I override a few functions from the asyncore module included with python. However, if I were to add "my.package" to sys.path, then I wouldn't be able to "import asyncore" from my own asyncore module. I'd have to do some trickery with sys.path to take the "my.package" component out, import standard asyncore, readd the "my.package" component, so that other modules can "import asyncore" and get my version. Is there a way to import the standard python asyncore module in this scenario? Thanks, Tro From kevinpruiz at gmail.com Mon Mar 17 17:14:27 2008 From: kevinpruiz at gmail.com (browntown) Date: Mon, 17 Mar 2008 14:14:27 -0700 (PDT) Subject: php/python webkit2png issue Message-ID: <606d2db4-4f0b-4309-8ca0-7d5678830a04@e39g2000hsf.googlegroups.com> Hi...i'm relatively new to python...i'm trying to use webkit2png to take some screenshots. Everything works fine when I run the script from the command line...things do not work when i try to execute them from php using exec. My php code looks something like: exec("python /usr/local/bin/webkit2png2.py -m http://www.google.com -D ~/Desktop/snap"); which produces the following output: "Cannot find pyobjc library files. Are you sure it is installed?" That output is generated from the webkit2png script after it fails to import foundation, webkit, appkit and pyobjc. How can I enable the python script to find the necessary files/ libraries when being executed from php? I'm using paul hammond's webkit2png on OS X, running apache 1.3 with php 4.47 and python 2.5.2. Thanks. From deets at nospam.web.de Sat Mar 29 09:54:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 14:54:36 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <7xzlshkhlc.fsf@ruckus.brouhaha.com> References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> Message-ID: <65701aF2erbbsU1@mid.uni-berlin.de> Paul Rubin schrieb: > Hrvoje Niksic writes: >> Note that I said "*file* input/output". Twisted and asyncore are >> about asynchronous socket programming that polls over nonblocking file >> descriptors such as found in socket programming, not about wrapping >> aio(3) and the equivalent Windows APIs. > > aio is also used for sockets, while twisted and asyncore use select or > something similar. That is asynchronous but in a different sense of > the word. See also: http://www.kegel.com/c10k.html In which sense is that different? AFAIK select lets you avoid polling and provides notifications (possibly with timeouts) for IO-events. So where exactly is the difference? I read TFA, and it does mention that select/poll have potential for optimization, but not something that disqualified them (or rather select) as being not async. Diez From Graham.Dumpleton at gmail.com Tue Mar 25 19:30:17 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Mar 2008 16:30:17 -0700 (PDT) Subject: Beta testers needed for a high performance Python application server References: Message-ID: On Mar 26, 7:31 am, Minor Gordon wrote: > Hello all, > > I'm looking for beta testers for a high performance, event-driven Python > application server I've developed. > > About the server: the front end and other speed-critical parts of the > server are written in portable, multithreaded C++. The back end is an > embedded CPython interpreter. The server is much faster than anything in > pure Python, and it can compete with C servers (including e.g. lighttpd > for file workloads) or outdo them (e.g. anything behind Apache) until > CPython consumes a single processor. On the Python side it supports WSGI > (the server can handle the static and dynamic requests of MoinMoin with > a handful of lines), the DB API with blocking calls offloaded to a > connection in a separate thread (MySQL, SQLite supported), Google's > ctemplate, gzipping responses, file caching, reading and writing to URIs > as a client, AJAX integration, debugging as a Python extension, and a > lot of other features. The core Python API is event-driven, using > continuations like Twisted but much cleaner (continuations are any > callables, there are no special objects anywhere). The Python back end > also supports Stackless Python so all of the continuation machinery can > be hidden behind tasklet switching. > > Background: I'm in this to help write a "story" for Python and web > applications. Everyone likes to go on about Ruby on Rails, and as far as > I can tell there's nothing that approaches Rails in Python. I want to > code quickly in Python like I can with Rails, but without sacrificing > single node performance on many cores. > > Beta testers: should be intermediate to advanced Python programmers with > demanding applications, particularly web applications with databases and > AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory > libraries beyond python-dev. > > Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. Why not just put it on the net somewhere and tell us where it is? People aren't generally going to want to help or even look at it if you treat it like a proprietary application. So, put the documentation and code up somewhere for all to see. BTW, multiprocess web servers such as Apache can quite happily make use of multiple cores. Even within a single Apache multithread process it can still use multiple cores quite happily because all the underlying network code and static file handling code is in C and not subject to the GIL. So, as much as people like to bash up on the GIL, within Apache it is not necessarily as big a deal as people make out. Also, an event driven model, or even a large dependence on multithreading, can actually be worse for Python web applications where using it means one can handle a much larger number of concurrent requests. This is because you greatly increase the risk of code having large requirements for transient memory being hit at the same time. The result can be large unpredictable blowouts in memory requirements for the process, with that memory then being held by the process and not necessarily able to be released back to operating system. Thus, for large Python web applications, use of a multiprocess web server, where each worker process is single threaded, is in various way still best as it provides the most predictable memory profile. Finally, the speed of the underlying web server (except for CGI) generally has minimal bearing on the performance of a large Python web application. This is because that isn't where the bottlenecks are. The real bottlenecks are generally in the application code itself and in any access to a back end database. Thus, pursuing absolute speed is a bit of a fools errand when you consider that any performance gain you may have over a competing solution may only end up resulting in somewhat less than 1% difference when one looks at overall request time. Graham From george.sakkis at gmail.com Mon Mar 3 18:29:18 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 3 Mar 2008 15:29:18 -0800 (PST) Subject: News from Jython world References: Message-ID: <0a9bfffc-7f13-4174-8972-27143f8b5c66@h11g2000prf.googlegroups.com> On Mar 3, 1:40 pm, S?bastien Boisg?rault wrote: > Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a > key Jython developer and is specifically hired to work full time on > Jython, a version of the Python interpreter that runs on top of the > JVM and provides full access to Java libraries. After a period where > the development had slowed, Jython was recently getting seriously > back on track. Now it's getting even better ! > > Don't wait too much ... Jython is very useful RIGHT NOW if you live > in the Java Universe. > > More details at: > -http://www.infoworld.com/article/08/03/03/hirings-python_1.html > -http://fwierzbicki.blogspot.com/2008/02/jythons-future-looking-sunny.... > > Cheers, > > SB Great news! Having to go back to the Java world might not be such a turn-off in the near future ;-) George From nanjundi at gmail.com Tue Mar 4 13:41:53 2008 From: nanjundi at gmail.com (Nanjundi) Date: Tue, 4 Mar 2008 10:41:53 -0800 (PST) Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> Message-ID: <3319005c-98b9-44a0-96dc-72db45f2ae27@z17g2000hsg.googlegroups.com> On Mar 4, 12:51 pm, jefm wrote: > How can I print the unicode box drawing characters in python: > > print u'\u2500' > print u'\u2501' > print u'\u2502' > print u'\u2503' > print u'\u2504' > > Traceback (most recent call last): > File "\test.py", line 3, in ? > print u'\u2500' > File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500' > in position 0: character maps to Just FYI, not an answer. It works like a charm on linux (ubuntu, fc3, python 2.4.1 & 2.5.2) Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print u'\u2500' ? >>> print u'\u2501' ? >>> print u'\u2502' ? >>> print u'\u2503' ? >>> >>> print u'\u2504' ? on windows using python 2.4. ??? -N From zubeido at yahoo.com.br Sat Mar 29 13:33:41 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 29 Mar 2008 10:33:41 -0700 (PDT) Subject: Problem with sqlite Message-ID: class db: def __init__(self): #constructor conn = sqlite3.connect('./db.db') conn.isolation_level = None self.cursor = conn.cursor() try: self.cursor.execute("CREATE TABLE database (album,filepath)" ) except: pass def add_entry( self, eone , etwo ): #Add entry to database self.cursor.execute( "INSERT INTO database (album,filepath) VALUES (?,?)", ( eone , etwo ) ) return 1 #TODO: exception handler def get_mediadb( self, print_db = False ): self.cursor.execute( 'SELECT * FROM database' ) if (print_db == True): print self.cursor.fetchall() def get_value( self, column ): self.cursor.execute( "SELECT %s FROM database" % column ) for n in self.cursor: print n def destructor(self): self.cursor.close() def walking_and_filling(db): pass if __name__ == "__main__": db = db() #walking_and_filling( db ) for root, dirs, files in os.walk( '''foo_path/''', topdown=False ): for name in files: joined = os.path.join(root, name) if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): try: audio = MP3 (joined, ID3=EasyID3 ) print (audio['album']) db.add_entry( joined, audio['album'] ) except: pass db.get_mediadb( print_db=True ) When i execute this the database doesn't get filled with anything and the program stays running in memory for ever. The print statement is just a Unicode string that would get to the database if i stated it in the add_entry function as a constant string. It's a really weird problem that i dont seem to understand why it's working out this way. Thanks in advance From david at boddie.org.uk Mon Mar 17 20:49:23 2008 From: david at boddie.org.uk (David Boddie) Date: Tue, 18 Mar 2008 01:49:23 +0100 Subject: EuroPython 2008 - Any interest in tutorials? Message-ID: <200803180149.24055.david@boddie.org.uk> As many of you may be aware, preparations for EuroPython 2008 - the European Python community conference - are under way. For the second year running, the event will be held in Vilnius, Lithuania, with the main programme taking place on Monday 7th, Tuesday 8th and Wednesday 9th July. Those of us involved with the conference are looking for ways in which we can make the event more interesting for beginners and experts alike. One way in which we could do this, particularly for people who are learning Python, is to allocate time for tutorials. This approach appears to be popular at conferences like PyCon and PyCon UK, but isn't something we normally do at EuroPython, though there are often talks are aimed at beginners in the schedule. What we'd like to know is: * Is this something that you would like to see? * Would you be interested in giving a tutorial? * Which subject would you be interested in hearing/talking about? If you answered "yes" to either of the first two questions, please feel free to add suggestions for tutorials, either as a participant or as a speaker, to this page on the EuroPython Wiki: http://www.europython.org/community/Talk_Suggestions If you're interested in participating in EuroPython this year in any way, please come and join us on the europython mailing list http://mail.python.org/mailman/listinfo/europython or visit this page on the EuroPython Web site: http://www.europython.org/community/Participants Hope to see some of you there! David Boddie - EuroPython 2008 participant :-) From arkanes at gmail.com Fri Mar 7 16:19:55 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 7 Mar 2008 15:19:55 -0600 Subject: Want - but cannot get - a nested class to inherit from outer class In-Reply-To: References: Message-ID: <4866bea60803071319o38686ec7te0d5adf5f4cd6ee7@mail.gmail.com> On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > I want - but cannot get - a nested class to inherit from an outer > class. (I searched the newsgroup and the web for this, couldn't find > anything - if I missed an answer to this please let me know!) > > I would like to build a class for a data structure such that nodes of > the data structure - of interest only to the data structure > implementation itself and not to the consumer - are instances of one > of two class types. I thought to encapsulate the nodes' classes like > this: > > class Tree(object): > ...class _MT(Tree): > ......def isEmpty(self): return True > ......def insert(self, X): return Tree._Node(X) > ...class _Node(Tree): > ......def isEmpty(self): return False > ......def insert(self, X): return _Node(X, self, Tree._MT()) > ...def merge(self, T): > ......def __init__(): return _MT() > ...... > > In other words, some methods would be implemented on instances' > classes (like isEmpty and insert) and some on the outer class (like > merge). Users of the data structure never need to know about the > nodes, much less the nodes' classes, so I wanted to encapsulate them > > However I can't do this, because, of course, the name Tree isn't > available at the time that the classes _MT and _Node are defined, so > _MT and _Node can't inherit from Tree. > Not only is the name not defined, the class doesn't even exist yet. > What is the Pythonic thing I should be doing instead? > Don't nest them. The single underscore is all you need to keep any from using them (don't forget that even if your method worked, they'd be perfectly visible as attributes of the Tree class, or as the types of returned values). Worrying too much about visibility is a waste of time in Python. > (Easy answer: Put this code in a module, exposing only a factory > function. I could do that, but wanted to know if I could encapsulate > it as described so I could actually put several similar data > structures into one module.) > There's no reason to use a factory function. If you do put them in a module, you can use __all__ to document your exports. As with all visibility issues in Python, this is advisory only - the only code it affects is the symbols that are exported by "from module import *". From steve at holdenweb.com Tue Mar 4 09:50:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 09:50:16 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD61A8.4000104@holdenweb.com> Peter Otten wrote: > Steve Holden wrote: > >> What I will repeat, however, is that while there is a *slight* >> difference is semantics between >> >> s = "some string" >> s1 = s >> >> and >> >> s = "some string" >> s1 = copy.copy(s) >> >> that difference is only to ensure that s and s1 point to different >> copies of the same string in the latter case, whereas in the former case >> s and s1 point to the same string. > > No, both "point" to the same string: > >>>> import copy >>>> s = "some string" >>>> s1 = s >>>> s1 is s > True >>>> s2 = copy.copy(s) >>>> s2 is s > True > > copy.copy() is just an expensive no-op here. > I suppose wiht strings being immutable there is no need for copy.copy() to actually return anything other than its argument for a string. Thanks for pointing that out. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From noname9968 at gmail.com Thu Mar 27 01:51:59 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 08:51:59 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> Message-ID: <47EB35FF.4020407@gmail.com> Guilherme Polo wrote: > 2008/3/26, Alex9968 : > >> Hi all, >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> using visual GUI designers), so my question is which other GUI toolkits >> have similar functionality. >> > > The geometry manager isn't related to using GUI designers tools at > all. And each toolkit has it's own way to do the things, wxPython uses > sizers, PyGtk uses containers. > Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) >> Secondly, I like the detailed widget borders configuration possible in >> Tkinter, which can be used to tweak GUI look, and wonder if other >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) >> look in Windows, but I'm afraid it can be quite different (and ugly) on >> other platforms. >> > > You sure can, but differently. > I suppose any toolkit allows setting parameters like "no border", "flat border" and "3d border", but which ones can set ANY type of border to ANY widget like Tkinter does? For example set GROOVE border to buttons and text widgets (instead of traditional wide raised/lowered borders), which is cool (in my opinion). > >> (The reason I ever consider moving from Tkinter is some inconveniences, >> involving for example window scrolling, plus its smaller amount of >> widgets compared to some other toolkits, plus its (rumored) ugly look on >> certain environments. I will not necessary change the toolkit, but I >> have to consider it) >> >> > > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > Tkinter for upcoming GSoC. For now you could try using Tile extension, > and update to Tk 8.5. If you don't want to use extensions, then you > will have to wait or change the toolkit for now. > Thanks. I haven't heard of Tile before, now I will keep this in mind. You forgot to mention WHAT you're planning to solve ;-) , so I have to add that Tile is modernization of Tk widgets (so it fixes ugly look). > >> Could anyone with experience in different toolkits help, please >> >> Thanks >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > From dundeemt at gmail.com Mon Mar 17 20:55:28 2008 From: dundeemt at gmail.com (dundeemt) Date: Mon, 17 Mar 2008 17:55:28 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <6715d78c-17df-4dfa-8181-d3606a8508c5@m44g2000hsc.googlegroups.com> > This is my third PyCon, and I've found a reasonably-sized cadre of > people who come for the hallway conversations plus a Bof or two, > having given up on hearing anything new, useful, or inspiring in the > talks. There are several people I know who would like to see a more > advanced academic track. Yes, Yes. This was my third pycon and before, I had always left feeling as though my brain had been stretched. (A good thing) This years balance of talks and my choices didn't leave me with the same feeling. I would have like to seen slightly longer talks, especially the ones I liked ;) -Jeff Hinrichs From aahz at pythoncraft.com Thu Mar 6 16:25:44 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Mar 2008 13:25:44 -0800 Subject: OT: Failed saving throw References: <13suutrmlm5208a@corp.supernews.com> Message-ID: In article <13suutrmlm5208a at corp.supernews.com>, Dennis Lee Bieber wrote: >On 5 Mar 2008 07:36:37 -0800, aahz at pythoncraft.com (Aahz) declaimed the >following in comp.lang.python: >> >> For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people >> think we should build a tomb in his honor. ;-) > > Just a tomb? Commission Disney to build a whole dungeon with the >tomb somewhere inside... Of course, they'd want to charge admission You're apparently missing the reference to Tomb of Horrors. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From george.sakkis at gmail.com Mon Mar 17 05:58:59 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 17 Mar 2008 02:58:59 -0700 (PDT) Subject: String To List References: <7xy78hep5g.fsf@ruckus.brouhaha.com> Message-ID: On Mar 17, 3:22 am, Paul Rubin wrote: > Girish writes: > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > this?? > > Thanks for the help... > > Be careful about using eval, if the string came from a potentially > hostile source. Maybe what you really want is JSON, which has > python-like syntax but a bunch of safe parsers. Or take a look at a restricted safe eval variant (e.g. http://groups.google.com/group/comp.lang.python/browse_frm/thread/262d479569b1712e) George From floris.bruynooghe at gmail.com Tue Mar 4 11:10:45 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Tue, 4 Mar 2008 08:10:45 -0800 (PST) Subject: Altering imported modules References: Message-ID: On Mar 1, 11:56 pm, Tro wrote: > I'd like to know if it's possible to make tlslite load *my* asyncore module > without changing any of the tlslite code. the pkgutil module might be helpful, not sure though as I've never used it myself. http://blog.doughellmann.com/2008/02/pymotw-pkgutil.html is a fairly detailed look at what pkgutil can do. Regards Floris From tjreedy at udel.edu Tue Mar 11 19:34:01 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 19:34:01 -0400 Subject: min/max: "stable" invariant? References: Message-ID: "Giovanni Bajo" wrote in message news:jiEBj.16245$q53.9583 at tornado.fastwebnet.it... | Hello, | | assuming that a sequence contains multiple elements with minimum/maximum | value, do min/max guarantee to return the *first* element in the sequence | among those? | | Example: | | >>> class A: | ... def __init__(self, x): self.x = x | ... | >>> L = [A(0), A(1), A(2), A(0)] | >>> min(L, key=lambda a:a.x) is L[0] | True | >>> min(L, key=lambda a:a.x) is L[3] | False | | Is this guaranteed by the Python language formal specification? | Is this guaranteed to always by true in CPython? (I guess so) | | I can't find any mention in the documentation. If there is no mention in the documentation (Lib Ref, Ch2 builtin functions), then there is no guarantee. From modelnine at modelnine.org Wed Mar 26 14:15:32 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 26 Mar 2008 19:15:32 +0100 Subject: Some notes on a high-performance Python application. In-Reply-To: References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: <200803261915.32923.modelnine@modelnine.org> Am Mittwoch, 26. M?rz 2008 18:54:29 schrieb Michael Str?der: > Heiko Wundram wrote: > > Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: > >> ... > >> > >> Using MySQL as a queueing engine across multiple servers is unusual, > >> but it works well. It has the nice feature that the queue ordering > >> can be anything you can write in a SELECT statement. So we put "fair > >> queueing" in the rating scheduler; multiple requests from the same IP > >> address compete with each other, not with those from other IP addresses. > >> So no one site can use up all the rating capacity. > >> ... > >> Does anyone else architect their systems like this? > > > > A Xen(tm) management system I've written at least shares this aspect in > > that the RPC subsystem for communication between the frontend and the > > backends is basically a (MySQL) database table which is regularily > > queried by all backends that work on VHosts to change the state (in the > > form of a command) according to what the user specifies in the (Web-)UI. > > I vaguely remember that this database approach was teached at my former > university as a basic mechanism for distributed systems at least since > 1992, but I'd guess much longer... I didn't say it was unusual or frowned upon (and I was also taught this at uni IIRC as a means to "easily" distribute systems which don't have specific requirements for response time to RPC requests), but anyway, as you noted for Biztalk, it's much easier to hit bottlenecks with a polling-style RPC than with a "true" RPC system, as I've come to experience when the number of nodes (i.e., backends) grew over the last year and a half. That's what's basically causing a re-consideration to move from DB-style RPC to socket-based RPC, which is going to happen at some point in time for the system noted above (but I've sinced changed jobs and am now only a consulting developer for that anyway, so it won't be my job to do the dirty migration and the redesign ;-)). -- Heiko Wundram From Afro.Systems at gmail.com Wed Mar 26 14:38:16 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 26 Mar 2008 11:38:16 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip References: Message-ID: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> > ....and then when my application execute code how can I set path to > d3dx module to "library.zip/d3dx.py". > I'm not sure is this properly set question. use the module zipimport http://docs.python.org/lib/module-zipimport.html From fdrake at acm.org Sun Mar 2 19:52:50 2008 From: fdrake at acm.org (Fred Drake) Date: Sun, 2 Mar 2008 19:52:50 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> Message-ID: <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> On Mar 2, 2008, at 7:43 PM, Fred Drake wrote: > 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: Neither does 2.3.7 now that I've tried that: gcc -u __dummy -u _PyMac_Error -framework System -framework CoreServices -framework Foundation -o python.exe \ Modules/python.o \ libpython2.3.a -ldl Undefined symbols: "__dummy", referenced from: ld: symbol(s) not found collect2: ld returned 1 exit status make: *** [python.exe] Error 1 Of course, I wasn't using an earlier 2.3.x version on this box. I would really like to be able to use 2.4.5, since I've been using 2.4.4 for work for a while now. -Fred -- Fred Drake From gagsl-py2 at yahoo.com.ar Sun Mar 30 01:35:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 02:35:55 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: > > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) Fine if you have the right keyboard... Try to write APL with a standard keyboard :) -- Gabriel Genellina From frikker at gmail.com Tue Mar 4 09:40:18 2008 From: frikker at gmail.com (blaine) Date: Tue, 4 Mar 2008 06:40:18 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> Message-ID: > > It looks like the fastest speed supported by python termios on > Linux is B460800 (uses a constant of 0x1004). If you look in > /usr/include/..., baud rates do go up to 921600 (which uses a > constant of 0x1007). > > Try using the appropriate constant from /usr/include/... (for > the target platform, of course). > > -- > Grant Edwards grante Yow! Please come home with > at me ... I have Tylenol!! > visi.com Thank you for your response. I can't seem to find what you're referencing in /usr/include. I found termios.h - but it does not define any constants (I can include it if you wish). I did find termios.c in the Python module file, which only defines constants up to : [...] {"B2400", B2400}, {"B4800", B4800}, {"B9600", B9600}, {"B19200", B19200}, {"B38400", B38400}, #ifdef B57600 {"B57600", B57600}, #endif #ifdef B115200 {"B115200", B115200}, #endif #ifdef B230400 {"B230400", B230400}, I could recompile python, I imagine, with additional constants but this wouldn't be ideal - although it is a possible solution. the only reference to a baud rate in termios.h is here: /* Return the output baud rate stored in *TERMIOS_P. */ extern speed_t cfgetospeed (__const struct termios *__termios_p) __THROW; /* Return the input baud rate stored in *TERMIOS_P. */ extern speed_t cfgetispeed (__const struct termios *__termios_p) __THROW; /* Set the output baud rate stored in *TERMIOS_P to SPEED. */ extern int cfsetospeed (struct termios *__termios_p, speed_t __speed) __THROW; /* Set the input baud rate stored in *TERMIOS_P to SPEED. */ extern int cfsetispeed (struct termios *__termios_p, speed_t __speed) __THROW; the termios.h and const.h in the linux/ folder aren't much help. I'm sure I'm just looking at the wrong file. Thank you again for all your help! Blaine From tmp1 at viltersten.com Sat Mar 1 19:32:06 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 01:32:06 +0100 Subject: SV: Surprised by the command "del" In-Reply-To: References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: <62u9tdF25hghiU1@mid.individual.net> >>I'm reading the docs and at 5.2 the del >>statement is discussed. At first, i thought >>i've found a typo but as i tried that >>myself, it turns it actually does work so. >> >> a = ["alpha", "beta", "gamma"] >> del a[2:2] >> a >> >>Now, i expected the result to be that the >>"beta" element has been removed. Obviously, >>Python thinks otherwise. Why?! >> >>Elaboration: >>I wonder why such an unintuitive effect has >>been implemented. I'm sure it's for a very >>good reason not clear to me due to my >>ignorance. Alternatively - my expectations >>are not so intuitive as i think. :) > > I think it should say > del a[1:2] > then it works While i'm thankful for the advice, i need to point out that the question wasn't "how to" but "why". Anyhow, it's been explained as a matter of definition of a "slice". -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From Lie.1296 at gmail.com Sun Mar 23 13:17:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 23 Mar 2008 10:17:56 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> Message-ID: <2da398c2-7976-42d9-bb77-3c1c476452e6@i7g2000prf.googlegroups.com> On Mar 20, 1:06?pm, royG wrote: > hi > i am trying to resize some images.First i'd read the size as a 2 > tuple ?and then i want to divide it by 2 or 4 or 2.5 etc.. > > suppose > origsz=(400,300) > i want to divide the origsize by 2.5 so i can resize to (160,120) There are several ways to do what you wanted: ------------- width = origsz[0] * scale height = origsz[1] * scale return width, height ------------- width, height = origsz return width * scale, height * scale ------------- return origsz[0] * scale, origsz[1] * scale ------------- # and an overly complex way of doing this return tuple(x * scale for x in origsz) ------------- > scale=2.5 > how can i get the newsz? > obviously origsz/2.5 won't work ?.. > thanks > RG Aside: I think you're a bit confused about the semantic of scaling in image resizing, when you want to halve the image size (e.g. 100x100 -> 50x50) you scale it by 0.5, and when you want to double the image size (e.g. 100x100 -> 200x200) you scale it by 2. This operation is done by multiplication, not division. (i.e. scaling a 400x300 images by 2.5 means upsizing the image into 1000x750) On Mar 20, 9:28 pm, "Jerry Hill" wrote: (snip) > That works fine for a 2-tuple, but might get unwieldy for larger > tuples, or if you don't know the length until runtime. A more general > solution might use a generator expression, like this: (snip) I think since the semantic of origsz is well defined (width-height pair of an image) it will always be a 2-tuple, anything other than 2- tuple should either be discarded or raise an error (depending on design choice). P.S.: If you're sure that you want to use division, make sure to "from __future__ import division" or convert the scaling factor into floats or you'll most likely get the wrong result as Python defaults to integer division (due to be changed in Python 3). And you should remember that the resulting image size should also be (integer, integer) since you can't have an image that's 100.2432x392.9875 From castironpi at gmail.com Tue Mar 4 23:02:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:02:46 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: On Mar 4, 9:53?pm, castiro... at gmail.com wrote: > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > > >> >> is it makes it. > > > >> >>>> from types import FunctionType, MethodType > > >> >>>> class A( FunctionType ): pass > > >> > ... > > >> > Traceback (most recent call last): > > >> > ? File "", line 1, in > > >> > TypeError: type 'function' is not an acceptable base type > > > >> Use delegation instead of inheritance. This class is almost ? > > >> indistinguishable from a true function (when used as a method): > If P gets, p gotcha. > > > gotcha= partial( get, you ). ?bor hor hor. ?Yes... Notwithstanding. Now bar has a name. class myfunction: __slots__ = ('func','name') # def __init__(self, func): object.__setattr__(self, 'func', func) object.__setattr__(self, 'name', None) # def __get__(self, instance, owner): print( "__get__ called for",instance ) return self.func.__get__(instance, owner) # def __getattr__(self, name): return getattr(self.func, name) # def __setattr__(self, name, value): object.__setattr__(self.func, name, value) class mymeta( type ): def __init__( self, name, bases, namespace ): for k,v in namespace.items(): if isinstance( v, myfunction ): v.name= k class P( metaclass= mymeta ): def foo(self, x): print( 'foo',x ) # @myfunction def bar(self, x): print( 'bar',x ) p= P() p.foo( 0 ) p.bar( 1 ) print( p.bar ) print( p.bar.name ) ''' output: ''' foo 0 __get__ called for <__main__.P object at 0x00B481F0> bar 1 __get__ called for <__main__.P object at 0x00B481F0> > __get__ called for <__main__.P object at 0x00B481F0> bar From ncoghlan at gmail.com Tue Mar 4 08:46:48 2008 From: ncoghlan at gmail.com (NickC) Date: Tue, 4 Mar 2008 05:46:48 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> Message-ID: <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> On Mar 4, 7:11 am, Lie wrote: > On Mar 2, 11:36 pm, Paul Rubin wrote: > > > > Try with a=7, b=25 > > > > They should still compare true, but they don't. The reason why they > > > don't is because of float's finite precision, which is not exactly > > > what we're talking here since it doesn't change the fact that > > > multiplication and division are inverse of each other. > > > What? Obviously they are not exact inverses for floats, as that test > > shows. They would be inverses for mathematical reals or rationals, > > but Python does not have those. > > When I said multiplication and division are inverse, I was pointing > out the fact that even though float's inexactness make them imperfect > inverse, mult & div are still inverse of each other. In-practice, the > inversing behavior is impossible unless we have a way to represent > real number (which we don't), and the *workaround* to make them work > is to do epsilon comparison. A mildly interesting Py3k experiment: Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from fractions import Fraction >>> from decimal import Decimal >>> def check_accuracy(num_type, max_val=1000): ... wrong = 0 ... for x in range(1, max_val): ... for y in range(1, max_val): ... wrong += (x / num_type(y)) * y != x ... return wrong ... >>> check_accuracy(float) 101502 >>> check_accuracy(Decimal) 310013 >>> check_accuracy(Fraction) 0 The conclusions I came to based on running that experiment are: - Decimal actually appears to suffer more rounding problems than float for rational arithmetic - Decimal appears to be significantly slower than Fraction for small denominator rational arithmetic - both Decimal and Fraction are significantly slower than builtin floats The increased number of inaccurate answers with Decimal (31% vs 10%) is probably due to the fact that it is actually more precise than float - for the builtin floats, the rounding error in the division step may be cancelled out by a further rounding error in the multiplication step (this can be seen happening in the case of ((1 / 3.0) * 3) == 1.0, where the result of the multiplication ends up being 1.0 despite the rounding error on division, due to the next smallest floating value being 0.99999999999999989). The speed difference between Decimal and Fraction is likely due to the fact that Fraction can avoid actually doing any division most of the time - it does addition and multiplication instead. The main reason behind the overall speed advantage of builtin floats should hopefully be obvious ;) Regardless, the result of integer division is going to be a binary floating point value in Py3k. For cases where that isn't adequate or acceptable, the application should really be tightly controlling its numeric types anyway and probably using a high performance math library like numpy or gmpy instead of the standard numeric types (as others have already noted in this thread). From castironpi at gmail.com Thu Mar 27 01:55:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 22:55:19 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> <7xej9woqrd.fsf@ruckus.brouhaha.com> Message-ID: <028353bb-26a0-46d1-b450-8396a4d419bb@p25g2000hsf.googlegroups.com> On Mar 26, 9:16?pm, Paul Rubin wrote: > Sean Davis writes: > > OR, NOT, etc.). ?Any suggestions on how to (1) set up the bit string > > and (2) operate on 1 or more of them? ?Java has a BitSet class that > > keeps this kind of thing pretty clean and high-level, but I haven't > > seen anything like it for python. > > You could wrap something around the array module, or the bit vector > objects from numarray, or use something like PyJudy (google for it). > Or consider using something like a tree data structure that supports > set operations, rather than a bitmap, if that's closer to what you're > really trying to do. Keep it continuous. You're looking at holographic or specific on tree leaves. I can store a GPS a -lot- easier than words. Force impact from a direction? (Strong A, two Bs.) Record wind. Repose. On idle, broadcast at unique intervals, wait for something to do. (developmental reposition) I suppose you want perception in the medium, but I think a special mechanism is always more efficient. Can you have minispiders hand off instructions by rapid tactile contact? Dock incl. clock sync, dual transmit, undock, work. Sounds like modem (modulator/demodulator) and ATM. The DNA of an organism doesn't change over time, but it manages to perform multi-cellular operations. Each cell has its very own copy, read-only, of the whole's DNA. Can lightning bugs turn on and off instruction sets (exec, donotexec)? Mem. block: 0000 Yes 0 1 add 0001 Yes 0 2 add 0010 No 0 3 add 0011 Yes 0 4 add runs: ( add 1, add 2, add 4 ). Local can transmit modifications to neighbor sames. Local gradient is stronger, which takes us to chemical. There is no living model for bees that sync post-mortem live -- they get orders for the next day "at dance". By the way, Queen bees, Workers and Drones have a developmental period of 16, 21, 24 days respectively. Conclude Workers are the special. Thing is, two adjacent cells in the animal body can vary pretty widely in trait. Stem cells can "differentiate into a diverse range of specialized cell types". Is time a factor in response to mechanistic signal propogation. Make a uniform response to every signal, and you're a functional programmer. input f o output. From castironpi at gmail.com Wed Mar 5 21:08:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 18:08:08 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> <83f40c69-a356-4af3-8fcf-aac4097dc480@n75g2000hsh.googlegroups.com> Message-ID: <52ad243f-4f72-4dcf-8c51-2f2d8c1da687@o77g2000hsf.googlegroups.com> On Mar 5, 6:40?pm, bearophileH... at lycos.com wrote: > Troels Thomsen: > > > The discussion of words is silly. My surprise about "else following a for > > loop.... what the heck ...." lasted excactly as long as it takes to read > > this sentence. > > Maybe I don't follow what you are saying, but well chosen words are a > very important part of a well designed API. If you take a look at the > Python developers mailing list you may see that people discuss days, > weeks to find the best naming for things. They should've called it "or-else". Bor hor hor. ...The keyword, I mean. From gagsl-py2 at yahoo.com.ar Sat Mar 1 01:35:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Mar 2008 04:35:07 -0200 Subject: at-exit-thread References: <62r68tF220j59U1@mid.uni-berlin.de> <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> Message-ID: En Fri, 29 Feb 2008 18:12:13 -0200, escribi?: > On Feb 29, 1:55?pm, "Diez B. Roggisch" wrote: >> castiro... at gmail.com schrieb: >> >> > The Python main interpreter has an at-exit list of callables, which >> > are called when the interpreter exits. ?Can threads have one? ?What's >> > involved, or is the best way merely to subclass Thread? >> >> Is that some sort of trick-question? >> >> class MyThread(Thread): >> >> ? ? def run(self): >> ? ? ? ? while some_condition: >> ? ? ? ? ? ? ?do_something() >> ? ? ? ? do_something_after_the_thread_ends() >> >> The atexit stuff is for process-termination which is/may be induced by >> external signals - which is the reason why these callbacks extist. >> Threads don't have that, thus no need. > > That depends. If a thread adds an object it creates to a nonlocal > collection, such as a class-static set, does it have to maintain a > list of all such objects, just to get the right ones destroyed on > completion? Yes, like any other objects. All threads in a process share the same memory space; any thread can "see" any other created object, and the general rules on reference counting apply: an object is destroyed when it is no more referenced. There are threading.local objects, which are specially designed to provide per-thread storage; they are not shared among threads. (BTW, you should use a threading.local instance instead of indexing by get_ident()) > Processes destroy their garbage hassle-free; how can > threads? And don't forget Thread.run( self ) in the example, if > anyone ever wants to make use of the 'target' keyword. Any object created inside a thread will be destroyed when the last reference to it is removed, as any other object. Threads are not special in this regard. -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Tue Mar 18 05:59:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Mar 2008 20:59:55 +1100 Subject: Program source implemented in non-text storage (was: Regarding coding style) References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> <8ca43caa-5a2c-4b7b-b168-aad4cfb0581a@a23g2000hsc.googlegroups.com> <649h81F2974cmU1@mid.uni-berlin.de> Message-ID: <871w68z71g.fsf_-_@benfinney.id.au> Marc 'BlackJack' Rintsch writes: > [A general VCS] depends usually on the fact that there are > individual files. Preferably text files if you want automagic > merging of different changes. Yes. > Now think of languages that are tightly coupled with their IDE > storing only binary "tokenized" files instead of plain text or even > one big binary file that contains all sources and resources of the > project. Those issues have nothing to do with the language, and everything to do with the language implementation. Moreover, a brain-dead monstrosity as you describe would result in far greater problems than merely the lack of decent version control support. I think it's safe to leave such implementations to rot, rather than stretching tools to acommodate them. -- \ ?That's all very good in practice, but how does it work in | `\ *theory*?? ?anonymous | _o__) | Ben Finney From kw at codebykevin.com Sat Mar 15 16:33:36 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 15 Mar 2008 16:33:36 -0400 Subject: Getting started with OS X Leopard In-Reply-To: <47dc2c42$0$32056$da0feed9@news.zen.co.uk> References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Message-ID: <47DC32A0.4000707@codebykevin.com> Mark Carter wrote: > Arnaud Delobelle wrote: > >> Is there a particular reason you want python from MacPorts? OSX >> Leopard comes with python 2.5, that's what I use on my mac. > > I heard from somewhere that Apple's version was a bit wonky, and that I > would be better off with a "proper" build. Not sure where you heard that. Apple's Python is built according to Mac guidelines (as a "framework"), but it works the same as on other platforms. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mikey at swampgas.com Wed Mar 26 15:38:55 2008 From: mikey at swampgas.com (Michael Owings) Date: Wed, 26 Mar 2008 14:38:55 -0500 Subject: PyODBC Stored proc calling Message-ID: <47EAA64F.30908@swampgas.com> This is probably pretty late to be replying but I had the same problem. As it turns out, you just need to be sure you use the correct syntax to call the sproc: db_cur.execute( "{call test_bed(?)}", ('test data string') ) -- Teleoperate a roving mobile robot from the web: http://www.swampgas.com/robotics/rover.html From gagsl-py2 at yahoo.com.ar Mon Mar 24 21:26:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 22:26:32 -0300 Subject: Calling a shared library using C types References: Message-ID: En Mon, 24 Mar 2008 19:56:08 -0300, Nathan Harmston escribi?: > import ctypes > t = ctypes.CDLL('./Simulation.so') > this works fine, I have a simple function I ve put in for testing which > just > returns the integer 4. However when I try to access this function it > doesnt > work > t.test() > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > line 325, in __getattr__ > func = self.__getitem__(name) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > line 330, in __getitem__ > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: dlsym(0x81e6b0, test): symbol not found Looks like the symbol isn't public - probably if you try loading the library with a C program it won't find it either. How is the function declared in the source? Try listing all public symbols with: nm -D Simulation.so > Im hoping python-list is ok for questions regarding ctypes :S It's not off topic, although there is a specific list for ctypes-related questions. But hijacking a thread to post a completely different question is not good netiquette. -- Gabriel Genellina From stefan_ml at behnel.de Mon Mar 10 04:32:07 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 09:32:07 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <47D4F207.6050606@behnel.de> Matt Nordhoff wrote: > Stefan Behnel wrote: >> And if you really need the efficiency of "well-tuned raw C", it's one function >> call away in your Cython code. > > What do you mean by that? > > I know nothing about how Cython compares to C in performance, so I said > "well-tuned" because it must be possible to write C that is faster than > Cython, though it may take some effort. So, you write the hand-optimised function in plain C, declare it in Cython and call it. That's what I meant. Since Cython compiles to C code, linking against a C module is straight forward. And this still keeps you from having to write all the Python API glue code in plain C. Stefan From rschroev_nospam_ml at fastmail.fm Mon Mar 17 14:18:19 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 17 Mar 2008 19:18:19 +0100 Subject: Anomaly in time.clock() In-Reply-To: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> Message-ID: Godzilla schreef: > Hello, > > I have been reading a thread about time.clock() going backward, which > is exactly what I am seeing... the thread generally leaning toward the > problem is caused by multi-processor machines. But I am seeing it at a > single CPU computer, and running XP. > > The error I am seeing between two very close invokation of > time.clock() is always around 3.5 seconds! This is enough to throw a > lot of the timing requirement in the software out of the window... > this is a fairly serious problem. I don't know if it's the same problem, but I've seen something similar to this. Are you by any chance using DirectX? When you create a DirectX device, DirectX by default resets the precision of the CPU to 20 bits or so. I had that problem in a project at work, with similar results (and other strange calculation errors). The solution was to use a flag (PRESERVE_PRECISION or something like that) in the CreateDevice() call (it was a C++ project). If it's something else, I'm afraid I can't help. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From MartinRinehart at gmail.com Thu Mar 27 11:03:39 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 08:03:39 -0700 (PDT) Subject: Tkinter Text widget Message-ID: <5c2ef3b6-00cb-497e-845e-7683ac22310e@s13g2000prd.googlegroups.com> Is there a way of translating from the Text widget's width/height (in characters) to pixels so you can open an appropriately sized window? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 05:22:13 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 10:22:13 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: References: <47EB58B5.1020801@mydeskfriend.com> Message-ID: <47eb673e$0$26637$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > > Gabriel Rossetti wrote: >> Hello, >> >> I am using Partial Function Application in a class and I've come up >> with a problem, when the method is called it tries to pass "self" to >> the curried/partial function, but this should be the first argument in >> reality, but since the function is curried, then the self gets passed >> as the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that >> since self is not available there. Does anyone have any ideas? >> >> Thanks, >> Gabriel >> > I also tried this : > > def __registerService(atomic, self, service): > def reg(service): > # registers the service > ... > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > thinking that the self will be passed as the first argument of the > registerService* calls and thus the second argument to the > curried/partial method, but it doesn't work either, I get : > > Traceback (most recent call last): > File "/home/xxx/Documents/Code/Python/test/test_serv.py", line 245, in > test_registeration > self.f.registerServiceAtomic(self.serv) > exceptions.TypeError: __registerService() takes exactly 3 arguments (2 > given) > > I don't get it... Looks like functools.partial doesn't implement the protocol descriptor to behave like an ordinary function. I suppose there's some good reason for this, but anyway you'll have to either extend partial to add the appropriate descriptor support, or provide self by yourself (like Diez suggested). From hdante at gmail.com Sun Mar 30 18:22:42 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 15:22:42 -0700 (PDT) Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: On Mar 28, 11:52 am, s... at pobox.com wrote: > I'm having trouble explaining the benefits and tradeoffs of threads to my > coworkers and countering their misconceptions about Python's threading model > and facilities. They all come from C++ and are used to thinking of > multithreading as a way to harness multiple CPU cores for compute-bound > processing. I also encountered, "Python doesn't really do threads" today. > *sigh* > > I don't need pointers to the relevant documentation sections. A bit of > googling didn't turn up much about threading beyond tutorial introductions. > I'm looking for something which will explain the rationale for using threads > in Python to someone who is experienced with multithreading in other > languages (like C/C++). Maybe a compare-and-contrast sort of document? > > Thanks, > > Skip I think you are having trouble because threads suck. They are the worst way of dealing with concurrency that exists (unfortunately they are the fastest also) :-). Threads are bad because, by construction, code may be subject to non- trivial hazards. There are other ways of dealing with concurrency that doesn't have this problem, like event-driven programming. I think threads are so bad, that when I left my job at a company that developed for PDAs, I told my team: "whenever you have an argument about how to make multitasking, you may count my vote against using threads". If you really need to use threads, then use design patterns that make threads behave like message passing systems (I believe there were the "monitor model" or the "actor model" or something). If you need threads because you need speed, then use a recent JIT- compiled language, like Java or C#. In general, you may use C or C++ also, but there are a few obscure problems with them because they weren't defined with threads in mind. If you just would like to use "multitasking" as a programming paradigm, try Twisted, or switch to stackless python (then write an blog about your findings). :-) From sjmachin at lexicon.net Sat Mar 22 07:48:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 04:48:17 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> Message-ID: On Mar 22, 9:58 pm, Arnaud Delobelle wrote: > > Lastly, if one deals with a totally ordered set of object but they are > not hashable (there isn't a good hash function), then Ninereeds' idea > of sorting first is still useful. ... and if not totally ordered, then ... I'll just stand aside and cue the timbot :-) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 From zerty.david at gmail.com Wed Mar 26 15:18:20 2008 From: zerty.david at gmail.com (David Anderson) Date: Wed, 26 Mar 2008 16:18:20 -0300 Subject: what does ^ do in python In-Reply-To: <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> <47EA99EE.5030304@tim.thechases.com> <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> Message-ID: <5dc598e30803261218m6e7d2790xac49eacf030bc0d@mail.gmail.com> ANd... By express I mean... Dereferencing... Habits from my native language where the verb express also means this On Wed, Mar 26, 2008 at 4:14 PM, David Anderson wrote: > Err even I cant understand what I wrote... > The right question was:HOw can we use/express pointers python as in C or > Pascal? > But thx to Heiko, He got what I mean =) > > > On Wed, Mar 26, 2008 at 3:46 PM, Tim Chase > wrote: > > > >> HOw can we use express pointers as in C or python? > > > > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "parser.py", line 123, in parse_text > > > tree = language.parse_text(text) > > > File "english.py", line 456, in parse_text > > > tree = self.parse_sentence(sentence) > > > File "english.py", line 345, in parse_sentence > > > raise ParserError, "can't parse %r" % sentence > > > ParserError: can't parse 'HOw can we use express pointers as in C or > > > python?' > > > > Possible "express pointers": > > > > http://www.geocities.com/derwin_b/sr91sign.jpg > > > > http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg > > > > > > http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg > > > > If those meet the OP's need, I recommend urllib2 and PIL. > > > > -tkc > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Mar 21 16:39:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 13:39:09 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> Message-ID: <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> On Mar 22, 1:11 am, castiro... at gmail.com wrote: > On Mar 21, 4:17 am, Bryan Olson wrote: > > > > > Arnaud Delobelle wrote: > > > Bryan Olson wrote: > > [...] > > >> Arnaud Delobelle offered a good Wikipedia link, and for more background > > >> look up "amortized analysis. > > > > Hrvoje Niksic provided the link :). > > > Oops, careless thread-following. Hrvoje Niksic it was. > > > > I still think two unrelated > > > things are being compared in this thread when people say that method A > > > (using dictionaries / sets) is O(n) and method B (sorting the list) > > > O(nlogn). > > > > Isn't it the case that: > > > > | Worst case | Average case > > > ---------|------------|------------- > > > Method A | O(n^2) | O(n) > > > Method B | O(nlogn) | O(nlogn) > > > > Which method is the best would then be determined by the distribution > > > of the hash values of your data, and whether you want to have a > > > guarantee the method will have a less-than-quadratic behaviour. > > > If we exclude the case where an adversary is choosing the keys, the > > chance of a seriously degenerate case in the hashing method is so > > remote that we do should not worry about it. Those who insist on > > ranking by worst-case behavior have probably abandoned Python long > > ago, as it uses those hashed 'dict' things everywhere. Of course > > they've also abandoned OS's with demand-paged virtual memory and > > such. > > > -- > > --Bryan > > A collision sequence is not so rare. > > >>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > > [1, 1, 1, 1, 1, 1, 1, 1] Bryan did qualify his remarks: "If we exclude the case where an adversary is choosing the keys, ..." From dave.brk at gmail.com Wed Mar 19 19:53:49 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 20 Mar 2008 01:53:49 +0200 Subject: [newbie] using ElementTree, how to add doctype and xml pi Message-ID: Hi all I have an svg file i'm creating on the fly. How do I add the doctype and xml pi? They're not an element per se, and there is no function to add them. Am I suppose to add them as elements after all? I have something like this: self.svgRoot = ET.Element("svg", xmlns=r'http://www.w3.org/2000/svg') ET.SubElement(self.svgRoot, "g", transform="scale(1,-1)") .... .... .... self.tree = ET.ElementTree(self.svgRoot) ... thanks dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat Mar 1 02:03:01 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 01 Mar 2008 07:03:01 GMT Subject: pySQLite Insert speed References: Message-ID: mdboldin at gmail.com wrote: > >I hav read on this forum that SQL coding (A) below is preferred over >(B), but I find (B) is much faster (20-40% faster) > >(A) > > sqla= 'INSERT INTO DTABLE1 VALUES (%d, %d, %d, %f)' % values > curs.execute(sqla) > >(B) > pf= '?, ?, ?, ?' > sqlxb= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > curs.execute( sqlxb, values ) > >Any intution on why (A) is slower? I think you misunderstood. (B) is *ALWAYS* the proper way of doing parameterized SQL queries. Unconditionally. The (A) style is way too vulnerable to SQL injection attacks. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From myeates at jpl.nasa.gov Mon Mar 17 15:34:29 2008 From: myeates at jpl.nasa.gov (Mathew) Date: Mon, 17 Mar 2008 12:34:29 -0700 Subject: placing a Python com object into Excel Message-ID: Hi I have seen examples from Mark Hammonds book where a Python COM object is accessed from Excel with a VBA script. But, what if I want to Insert a Python COM into the Sheet itself? When I try this, a list of available objects appear. But my object isn't on the list. Anybody have any ideas? Mathew From martin at v.loewis.de Sun Mar 9 18:35:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Mar 2008 23:35:18 +0100 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: Message-ID: <47D46626.6090203@v.loewis.de> > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. These symbols are all from pythonxy.dll. You need to add the corresponding import library (libpythonxy.a/pythonxy.lib) into the linker line, using a -l option. Regards, Martin From pavlovevidence at gmail.com Mon Mar 3 17:53:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 14:53:21 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> Message-ID: <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> On Mar 3, 4:47 pm, Mensanator wrote: > On Mar 3, 2:49 pm, Carl Banks wrote: > > > > > On Mar 3, 3:40 pm, Mensanator wrote: > > > > Notice anything funny about the "random" choices? > > > > import sympy > > > import time > > > import random > > > > f = [i for i in sympy.primerange(1000,10000)] > > > > for i in xrange(10): > > > f1 = random.choice(f) > > > print f1, > > > f2 = random.choice(f) > > > print f2, > > > C = f1*f2 > > > ff = None > > > ff = sympy.factorint(C) > > > print ff > > > > ## 7307 7243 [(7243, 1), (7307, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > As in, "they're NOT random". > > > > The random number generator is broken by the sympy.factorint() > > > function. > > > > Random.choice() works ok if the factorint() function commented out. > > > > ## 6089 1811 None > > > ## 6449 1759 None > > > ## 9923 4639 None > > > ## 4013 4889 None > > > ## 4349 2029 None > > > ## 6703 8677 None > > > ## 1879 1867 None > > > ## 5153 5279 None > > > ## 2011 4937 None > > > ## 7253 5507 None > > > > This makes sympy worse than worthless, as it f***s up other modules. > > > Dude, relax. > > > It's just a bug--probably sympy is messing with the internals of the > > random number generator. It would be a simple fix. Instead of > > b****ing about it, file a bug report. > > I did. > > > Or better yet, submit a patch. > > I would if I knew what the problem was. > > I posted it here because someone recommended it. > I'm simply un-recommending it. Those who don't care > needn't pay any attention. Those who do should be > glad that faults are pointed out when found. 1. You can point out the faults of a program without insults and vulgarity 2. You must be terribly difficult to please if one bug is enough to recommend against a program as "worse than worthless" 3. You must be terribly naive if you expect a freeware program with a version number of 0.5.12 not to have bugs Carl Banks From mmanns at gmx.net Fri Mar 21 19:06:41 2008 From: mmanns at gmx.net (Martin Manns) Date: Sat, 22 Mar 2008 00:06:41 +0100 Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> Message-ID: On Fri, 21 Mar 2008 14:51:49 -0700 (PDT) Gabriel Genellina wrote: > > If I fill the array with 0 instead of the functions that > > return "" this works really fast. > > > > However, I would like to be able call the content of each > > cell in the array as a function. > > If you drop this condition then you could fill the array with zeroes > as before, replace only the interesting ones with actual functions, > and write: > > for item in myarray[nonzero(myarray)]: > print item() if callable(item) else item Works for me. Thank you Martin From gabriel.rossetti at mydeskfriend.com Tue Mar 18 06:03:15 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 18 Mar 2008 11:03:15 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom In-Reply-To: <1205831099.3212.18.camel@localhost.localdomain> References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <47DF9363.3050807@mydeskfriend.com> Carsten Haese wrote: > On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > >> Hello, >> >> I am reading core python python programming and it talks about using the >> idiom >> described on >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . >> >> I'm using python 2.5.1 and if I try : >> >> class MyClass(object): >> def __init__(self): >> self._foo = "foo" >> self._bar = "bar" >> >> @property >> def foo(): >> doc = "property foo's doc string" >> def fget(self): >> return self._foo >> def fset(self, value): >> self._foo = value >> def fdel(self): >> del self._foo >> return locals() # credit: David Niergarth >> >> @property >> def bar(): >> doc = "bar is readonly" >> def fget(self): >> return self._bar >> return locals() >> >> like suggested in the book (the decorator usage) I get this : >> >> >>> a=MyClass() >> >>> a.foo >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: foo() takes no arguments (1 given) >> >> but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : >> >> >>> a = MyClass() >> >>> a.foo >> 'foo' >> >> does anyone have an idea as of why this is happening? >> > > You're mixing two completely different approaches of building a > property. If that code is actually in the book like that, that's a typo > that you should mention to the author. > > The @property decorator can only be used to turn a single getter > function into a read-only attribute, because this: > > @property > def foo(...): > ... > > is the same as this: > > def foo(...): > ... > foo = property(foo) > > and calling property() with one argument builds a property that has just > a getter function that is the single argument you're giving it. > > The recipe you're referring to uses a magical function that returns a > dictionary of getter function, setter function, deleter function, and > docstring, with suitable key names so that the dictionary can be passed > as a keyword argument dictionary into the property() constructor. > However, that requires the magical foo=property(**foo()) invocation, not > the regular decorator invocation foo=property(foo). > > HTH, > > I was able to get it t work with the decorator by doing this : def MyProperty(fcn): return property(**fcn()) and using it like this : class MyClass(object): def __init__(self): self._foo = "foo" self._bar = "bar" @MyProperty def foo(): doc = "property foo's doc string" def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() # credit: David Niergarth @MyProperty def bar(): doc = "bar is readonly" def fget(self): return self._bar return locals() Cheers, Gabriel From jeff at schwabcenter.com Tue Mar 18 00:28:31 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 21:28:31 -0700 Subject: Interesting math problem In-Reply-To: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> References: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > On Mar 17, 10:24 pm, "BJ?rn Lindqvist" wrote: >> Here is an interesting math problem: >> >> You have a number X > 0 and another number Y > 0. The goal is to >> divide X into a list with length Y. Each item in the list is an >> integer. The sum of all integers is X. Each integer is either A or A + >> 1, those should be "evenly distributed." >> >> Example: >> >> 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] >> 16 // 4 = 4 gives the list [4, 4, 4, 4] >> 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, >> 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, >> 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] >> >> This algorithm is used a lot in programming. For example, for >> projecting a line on a pixel display. Your mission, should you choose >> to accept it, is to improve the code given below which is my best >> attempt and make it more succinct and easier to read. Preferably by >> using list comprehensions, map or even reduce.... >> >> def make_slope(distance, parts): >> step = distance / float(parts) >> intstep = int(step) >> floatstep = step - intstep >> >> steps = [] >> acc = 0.0 >> for i in range(parts): >> acc += floatstep >> step = intstep >> if acc > 0.999: >> step += 1 >> acc -= 1.0 >> steps.append(step) >> return steps >> >> # Test code >> distance = 130 >> parts = 50 >> L = make_slope(distance, parts) >> assert(len(L) == parts) >> assert(sum(L) == distance) >> print L >> >> -- >> mvh Bj?rn > > OK then, using list comprehensions. It is more succint, is it easier > to read? > > def slope(dist, parts): > return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)] That's awesome, but I sure hope you'd mix in a comment in real code. ;) From vedrandekovic at yahoo.com Thu Mar 27 09:44:07 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Thu, 27 Mar 2008 06:44:07 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> On 27 o?u, 10:44, "Gabriel Genellina" wrote: > En Thu, 27 Mar 2008 06:00:26 -0300, escribi?: > > > > > I was add this into my application code: > > > import sys > > import os > > my_dir=os.getcwd() > > sys.path.append(my_dir) > > sys.path.append(my_dir+"\\libary.zip") > > sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder > > f=open("path.txt","w") > > f.write(str(sys.path)) > > f.close() > > > an the output in path.txt is : > > > ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users > > \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ > > \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ > > \libary.zip\\py2exe'] > > > But it still can't find module py2exe.What should I do now? Any > > examples? > > I assume you're talking about the py2exe package available from www.py2exe.org- so it's not a module, it's a package. > py2exe usually is only relevant on your *development* machine, so why do > you want to put it inside a .zip? What do you want to do? > > Anyway, I tried the following and could import py2exe successully (but I > don't know if it actually works as a distutils extension...) > > - compressed the py2exe folder into py2exe.zip > - deleted the original py2exe folder > - moved py2exe.zip onto some temporary directory > - tried to import py2exe, failed as expected > - added py2exe.zip to sys.path > - tried to import py2exe, this time OK > > py> import py2exe > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named py2exe > py> import sys > py> sys.path.append(r"C:\TEMP\pna\py2exe.zip") > py> import py2exe > py> py2exe.__path__ > ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] > > -- > Gabriel Genellina Hello again, Thanks for previous post, it was useful! So now I know what is a problem, but I don't know how to solve it.Under my application user can convert his python code to executable, I was created this with subprocess: retcode =subprocess.Popen(["ython","setup.py","py2exe","-d","exe"], shell=True, stdout=subprocess.PIPE,creationflags = win32process.CREATE_NO_WINDOW) stdout_value = retcode.communicate()[0] ...Py2exe exit from process here: running py2exe creating C:\Users\veki\Desktop\python\PGS\dist\build creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32 creating C:\Users\veki\Desktop\python\PGS\dist\build \bdist.win32\winexe creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \collect-2.5 creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \bundle-2.5 creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \temp creating C:\Users\veki\Desktop\python\PGS\dist\exe *** searching for required modules *** ...it's trying to find d3d,d3dx,d3dc,d3dgui... modules but it can't cause these modules are in library.zip.How can I set target for finding path to library.zip , I'm running these py2exe compile process from my main excutable? Regards, Vedran From bharathv6.project at gmail.com Wed Mar 19 03:06:52 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Wed, 19 Mar 2008 12:36:52 +0530 Subject: automatically doing some cleaning-up by the process when the systems shuts down In-Reply-To: References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> Message-ID: <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> hi , thanks Gabriel ... but r u sure if it is SYSTERM ?or is it SIGTERM ? I am not aware of any SYSTERM signal .. if it is SYSTERM please tell me more about it .. as google search is not helping .. and also is there some way for my process which is running as a daemon to know that system was not shut down properly previously ....eg a power failure .. so that my program can do necessary steps if cleaning up is not done during its last termination On Wed, Mar 19, 2008 at 8:25 AM, Gabriel Genellina wrote: > En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh > escribi?: > > > my programs runs as daemon and it does some logging .. when system > > shuts down .. which may be done manually . i want my process do some > > cleaning up automatically such as writing in to the log file when the > > process terminats before the system shuts down > > handling the SYSTERM signal? > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sun Mar 2 06:15:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 03:15:02 -0800 (PST) Subject: Beginner's assignment question References: Message-ID: <360f7e15-0d24-4c30-8513-1ae683a69b33@q33g2000hsh.googlegroups.com> On Mar 2, 4:49?am, "Gabriel Genellina" wrote: > En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > > > > > > > Lorenzo Gatti wrote: > >> On Mar 1, 3:39 pm, Schizoid Man wrote: > >>> As in variable assignment, not homework assignment! :) > > >>> I understand the first line but not the second of the following code: > > >>> a, b = 0, 1 > >>> a, b = b, a + b > > >>> In the first line a is assigned 0 and b is assigned 1 simultaneously. > > >>> However what is the sequence of operation in the second statement? I;m > >>> confused due to the inter-dependence of the variables. > > >> The expressions of the right of the assignment operator are evaluated > >> before assigning any new values, to the destinations on the left side > >> of the assignment operator. > >> So substitutig the old values of a and b the second assignment means > > >> a, b = 0, 0 + 1 > > >> Simplifying the Python Reference Manual ("6.3 Assignment Statements") > >> a little : > > >> assignment_stmt ::= target_list "="+ expression_list > > >> An assignment statement evaluates the expression list (remember that > >> this can be a single expression or a comma-separated list, the latter > >> yielding a tuple) and assigns the single resulting object to each of > >> the target lists, from left to right. > > >> [...] > > >> WARNING: Although the definition of assignment implies that overlaps > >> between the left-hand side and the right-hand side are `safe' (for > >> example "a, b = b, a" swaps two variables), overlaps within the > >> collection of assigned-to variables are not safe! For instance, the > >> following program prints "[0, 2]": > > >> x = [0, 1] > >> i = 0 > >> i, x[i] = 1, 2 > >> print x > > >> Lorenzo Gatti > > > Thank you for the explanation. I guess my question can be simplified as: > > > First step: a, b = 0, 1 > > No problem here as a and b are assigned values. > > > Second step: a, b = b, a + b > > > Now my question is does b become a + b after a becomes 1 or while a > > stays at 0? > > > As the assignment occurs simultaneously I suppose the answer is while a > > stays at 0. > > Read the previous response carefully and you'll answer your question. The ? > right hand side is EVALUATED in full before values are assignated to the ? > left hand side. Evaluating b, a+b results in 1, 1. The, those values are ? > assigned to a, b. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - Another way to think of it is: a, b= b, a+b ---> X= b, a+b a, b= X where X is a pair (2-tuple, two-element tuple, ordered pair, &c.) From gabriel.rossetti at mydeskfriend.com Thu Mar 27 04:40:30 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 09:40:30 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: <65144bF2dp2abU1@mid.uni-berlin.de> References: <65144bF2dp2abU1@mid.uni-berlin.de> Message-ID: <47EB5D7E.7080109@mydeskfriend.com> Diez B. Roggisch wrote: > Gabriel Rossetti schrieb: > >> Hello, >> >> I am using Partial Function Application in a class and I've come up with >> a problem, when the method is called it tries to pass "self" to the >> curried/partial function, but this should be the first argument in >> reality, but since the function is curried, then the self gets passed as >> the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that since >> self is not available there. Does anyone have any ideas? >> > > Use a bound-method instead. That has the self already bound to it. Like > this: > > > class Foo: > def m(self, arg): > print arg > > f = Foo() > partial(f.m, 10) > > > Diez > Ok, thanks, I moved the partial defs to __init__() and now it seams to work (I still have a but elsewhere, but this part no longer gives an error : def __init__(): self.registerServiceAtomic = partial(self.__registerService, True) self.registerServiceNonAtomic = partial(self.__registerService, False) def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) Thanks, Gabriel From hniksic at xemacs.org Sun Mar 30 17:24:56 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 30 Mar 2008 23:24:56 +0200 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <656vhnF2e9ao7U1@mid.uni-berlin.de> <8763v4otts.fsf@mulj.homelinux.net> Message-ID: <87ve33oqfr.fsf@mulj.homelinux.net> Hrvoje Niksic writes: > I believe you stil misunderstand. The select module doesn't provide > an inteface to aio(3). It provides an interface to select() and > poll() system calls, which don't provide asynchronous access to > regular files. It occurred to me that I didn't provide an example of what I mean by select not providing asynchronous access to regular files. Using this code: >>> import os, select >>> fd = os.open('/mnt/custom/x.jpg', os.O_RDONLY) >>> fd 3 # /mnt/custom is an SMB or NFS mount. At this point, kill -STOP the # SMB server. >>> select.select([fd], [], [], 10) # test whether fd is readable ([3], [], []) # exits immediately, assume >>> os.read(3, 1024) ... hangs until smb server continues ... The thing is, select() *always* returns immediately on regular files, even if they are in fact not readable or writable. In this case, select() claimed the file descriptor to be readable when in fact it wasn't. The same is the case with poll, but not with aio. In most cases this isn't a problem, but it does mean that an application that reads from a network-share-located file in a select/poll-driven event loop will stall until the file server responds. Threads, on the other hand, don't have this problem. A program that reads the file in a separate thread will not block even if the file is on a temporarily non-responding NFS server. From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:14:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:14:30 -0300 Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 11:51:10 -0300, escribi?: > I have an extension module that gets initialized multiple > times because I am using threads. And do you want thread local variables? > How can this module access global state (not per-thread state) ? > It needs to create a singleton. C global variables are global, not per-thread. -- Gabriel Genellina From thudfoo at opensuse.us Sun Mar 16 23:37:45 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Sun, 16 Mar 2008 19:37:45 -0800 Subject: Code to send RSS news by Sendmail In-Reply-To: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> References: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> Message-ID: <3d881a310803162037i14913a78p2bb5b971034211a6@mail.gmail.com> On 3/15/08, Ulysse wrote: > Hello, > > I'm searching a code which allow you to parse each item in the RSS > feed, get the news page of each item, convert it to text and send it > by mail. > > Do you know if it exists ? > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > Feed parser: http://feedparser.org/ From gandalf at shopzeus.com Thu Mar 20 17:20:46 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 20 Mar 2008 22:20:46 +0100 Subject: eval and unicode In-Reply-To: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <47E2D52E.6080007@shopzeus.com> >> I tried to use eval with/without unicode strings and it worked. Example: >> >> >>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? >> ?????? ????????? ???????"' ) >> True >> > When you feed your unicode data into eval(), it doesn't have any > encoding or decoding work to do. > Yes, but what about eval( 'u' + '"????????? ????????? ???????"' ) The passed expression is not unicode. It is a "normal" string. A sequence of bytes. It will be evaluated by eval, and eval should know how to decode the byte sequence. Same way as the interpreter need to know the encoding of the file when it sees the u"????????? ????????? ???????" byte sequence in a python source file - before creating the unicode instance, it needs to be decoded (or not, depending on the encoding of the source). String passed to eval IS python source, and it SHOULD have an encoding specified (well, unless it is already a unicode string, in that case this magic is not needed). Consider this: exec(""" import codecs s = u'?' codecs.open("test.txt","w+",encoding="UTF8").write(s) """) Facts: - source passed to exec is a normal string, not unicode - the variable "s", created inside the exec() call will be a unicode string. However, it may be Û or something else, depending on the source encoding. E.g. ASCII encoding it is invalid and exec() should raise a SyntaxError like: SyntaxError: Non-ASCII character '\xc5' in file c:\temp\aaa\test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Well at least this is what I think. If I'm not right then please explain why. Thanks Laszlo From gagsl-py2 at yahoo.com.ar Thu Mar 6 16:32:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 19:32:35 -0200 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 14:40:47 -0200, escribi?: > On Mar 6, 12:17?am, "Daniel Fetchinson" > wrote: >> >> > What does exec( open( 'modA.py' ).read() ) do? >> > > A more appropriate formulation of the 'question behind the words' > would have been, 'are there any weird corner cases in which it doesn't > import modA? I recognize it doesn't on .pyc and .pyd files, but you > could say exec( open( 'modA.py' ).read() ) ==> import modA, even if > import modA =!=> exec( open( 'modA.py' ).read() ) all the time. Then write the question that way. Working crystall balls are hard to find nowadays... They're different; no module object is created by the exec statement. When the import machinery determines that certain module isn't already loaded, and that the .py version has to be used, it does something like this: newmodule = sys.modules[modulename] = ModuleType(modulename) # constructor sets __name__ and a null __doc__ newmodule.__builtins__ = current builtins newmodule.__file__ = filename code = read from filename and compile it exec code in newmodule.__dict__ > However, a way of asking that's more direct would have been, "Wait... > can't you create multiple module instances like that?", but since > we've already seen successful loadings of at least the builtins, > that's been treated. There are ways to create many instances of the same module, but not using a plain import statement, or using the API in the intended way. > Maybe you even hear the right thing if I say, > "Does exec( open( 'modA.py' ).read() ) do the things of import modA?" Only in part, as you can see above. > Yes, I can read the docs, but no, I can't check every possible > combination of modules. > The idea behind a singleton is to ensure something. You want non- > primary instances impossible to create. However, if (wording got > tangled here) for singleton A, if class B does the same thing, just > has different allocations-- it's own-- then A is still a singleton. > The writer of B hasn't defeated or contradicted the letter or spirit > of A. > > OP's question might have come from a variety of perspectives. In some > ways yes, in others no. That is, if you try to reinstantiate modA, > you get the same instance. But if you try really hard, you get a new > one. Are you looking for an extension to import modA that won't > return an instance that is old? > > So far, I know this: modules and classes are both namespaces. Are > those singletons? Strictly speaking, neither classes nor modules are singletons; classes are instances of type, and modules are instances of their type, and there are many instances of each. We can consider "qualified singletons", where we want to have a single instance of a class given certain attributes. In that sense, modules are "named" singletons; Python tries to ensure that, given a module name, the module object returned is always the same one - even if you spell the name in different ways. The import statement, the __import__ builtin, the imp module, the PyImport_AddModule C function, all of them try to ensure that. Of course there are ways to shoot yourself in the foot -by example, creating a new module "in the fly" with PyModule_New- On the contrary, classes have no such restrictions. Of course, for classes defined at the global level in a module, you can't have two of them with the same name, but that's just because the module namespace can't hold two values for a single name. But you can create classes dinamically, or define them inside a function, or... lots of ways of creating many instances of the "same" class, and Python won't enforce them to be always the same object. So, I'd say that modules are named singletons, and classes aren't singletons at all. -- Gabriel Genellina From shakefu at gmail.com Fri Mar 7 22:23:46 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 19:23:46 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> I figured I might as well share the code I ended up using, in case anyone else wants an easy way to get strings to, for instance, SQL- storable datetimes. jake at house:~$ cat test.py #!/usr/bin/python from datetime import datetime import subprocess def parsedate( date ): p = subprocess.Popen(['date','+%s.%N',"--date=%s" % date],stdout=subprocess.PIPE) out = float(p.stdout.read()) return "%s" % datetime.fromtimestamp(out) jake at house:~$ python -i test.py >>> parsedate("today") '2008-03-07 21:20:31.870489' >>> parsedate("tomorrow") '2008-03-08 21:20:40.516243' >>> parsedate("next monday") '2008-03-10 00:00:00' >>> parsedate("10pm last week") '2008-02-29 22:00:00' >>> parsedate("last tuesday") '2008-03-04 00:00:00' Thanks to everyone who helped! Jacob From tjreedy at udel.edu Tue Mar 18 22:06:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:06:27 -0400 Subject: Get actual call signature? References: Message-ID: "Jarek Zgoda" wrote in message news:fro6j9$i44$1 at nemesis.news.neostrada.pl... | Say, I have a function defined as: | | def fun(arg_one, arg_two='x', arg_three=None): | pass | | Is there any way to get actual arguments that will be effectively used | when I call this function in various ways, like: ... | I'd like to wrap function definition with a decorator that intercepts | not only passed arguments, but also defaults that will be actually used | in execution. You essentially have to do the same thing the interpreter does to call a function, which, as has been noted, is pretty hairy. You just want to print the args instead of executing the code. From castironpi at gmail.com Wed Mar 26 18:30:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 15:30:09 -0700 (PDT) Subject: A question on decorators References: <64vpmnF2dvlccU1@mid.uni-berlin.de> Message-ID: On Mar 26, 3:23?pm, "Diez B. Roggisch" wrote: > Tim Henderson schrieb: > > > > > > > Hello > > > I am writing an application that has a mysql back end and I have this > > idea to simplify my life when accessing the database. The idea is to > > wrap the all the functions dealing with a particular row in a > > particular in a particular table inside a class. So if you have a > > table that looks like this: > > > id ? str1 ? ? ? str2 ? ? ? ?pickled_data1 ? pickled_data2 > > 0 ? ?woeif ? ? ?aposf ? ? ? (bin) ? ? ? ? ? ? ? ? ?(bin) > > 1 ? ?ofime ? ? ?powe ? ? ? ?(bin) ? ? ? ? ? ? ? ? ?(bin) > > ... > > n ? ?oiew ? ? ? opiwe ? ? ? (bin) ? ? ? ? ? ? ? ? ?(bin) > > > you can access this table like this > > > t = Table(id) #to load a pre-entered row > > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > > when you change a an attribute of the class like this... > > t.str1 = 'new value' > > > it automatically updates the database backend. > > > I have what I just described working. However I want an easier way to > > deal with my pickled_data. Right now I am pickling dictionaries and > > list types. Now there is one problem with this, let me demonstrate > > > t.data.update({'new key':'new value'}) > > print t.data > > {... 'new key':'new value' ...} > > > which makes it appear that the database has been updated as well, but > > in fact it hasn't to update the database with this scheme you actually > > have to do this. > > > t.data.update({'new key':'new value'}) > > t.data = t.data > > > this is not ideal so I subclassed the built in dict type like this: > > > class _my_dict(dict): > > > ? ? def __init__(self, row_index_name, row_index, column_name, a=None, > > **kwargs): > > ? ? ? ? self.row_index_name = row_index_name > > ? ? ? ? self.row_index = row_index > > ? ? ? ? self.column_name = column_name > > ? ? ? ? self.write_access = True > > ? ? ? ? if (a == None): dict.__init__(self, kwargs) > > ? ? ? ? else: dict.__init__(self, a) > > > ? ? ? ? self.update_db() > > > ? ? def __delitem__(self, key): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? dict.__delitem__(self, key) > > ? ? ? ? ? ? self.update_db() > > > ? ? def __setitem__(self, key, value): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? dict.__setitem__(self, key, value) > > ? ? ? ? ? ? self.update_db() > > > ? ? def clear(self): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? dict.clear(self) > > ? ? ? ? ? ? self.update_db() > > > ? ? ... > > ? ? more methods which are simliar > > ? ? ... > > > ? ? def update_db(self): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? con = get_dbConnection() > > ? ? ? ? ? ? cur = con.cursor() > > > ? ? ? ? ? ? table = self.experiment.TABLE > > ? ? ? ? ? ? row_index_name = self.row_index_name > > ? ? ? ? ? ? row_index = self.row_index > > ? ? ? ? ? ? column_name = self.column_name > > ? ? ? ? ? ? column_value = MySQLdb.escape_string(pickle.dumps(self)) > > > ? ? ? ? ? ? q1 = '''UPDATE %(table)s > > ? ? ? ? ? ? SET %(column_name)s = '%(column_value)s' > > ? ? ? ? ? ? WHERE %(row_index_name)s = '%(row_index)s' ?''' % locals() > > > ? ? ? ? ? ? cur.execute(q1) > > ? ? ? ? ? ? con.close() > > > Now while this works, it is a lot of work. What I want to be able to > > do is something where I write one decorator function that > > automatically updates the database for me. So let us pretend I have > > this function. > > > let: dec_update_db() be my decorator which updates the dictionary. > > > to use this function it seems I would probably still have to subclass > > dict like this: > > > class _my_dict2(dict): > > > ? ? @dec_update_db > > ? ? def __init__(self, row_index_name, row_index, column_name, a=None, > > **kwargs): > > ? ? ? ? self.row_index_name = row_index_name > > ? ? ? ? self.row_index = row_index > > ? ? ? ? self.column_name = column_name > > ? ? ? ? self.write_access = True > > ? ? ? ? if (a == None): dict.__init__(self, kwargs) > > ? ? ? ? else: dict.__init__(self, a) > > > ? ? @dec_update_db > > ? ? def __delitem__(self, key): > > ? ? ? ? dict.__delitem__(self, key) > > > ? ? @dec_update_db > > ? ? def __setitem__(self, key, value): > > ? ? ? ? dict.__setitem__(self, key, value) > > > ? ? @dec_update_db > > ? ? def clear(self): > > ? ? ? ? dict.clear(self) > > > ? ? ... and so on ... > > > this is also not ideal. because I still have to apply the decorator to > > every function which changes the dictionary. > > > What I really want is a way to have the decorator applied > > automatically every time a method in dict or a sub class is called. I > > feel like this must be possible. Has any one here done anything like > > this before? > > There are a few possibilities - one of them is using a metaclass to > apply the decorator to alle methods. > > Diez- Hide quoted text - > > - Show quoted text - I like his post. I thought that structures can be counter-primitive. I don't know why lambda doesn't work. Where's the guy that thinks everything in lambdas. I think that f*2=partial( partial( f ) ). It's not: no 'of'. I want to say that's on the internet. May I define multiplication of operators? That's just order. Pick one. Do you play Civilization? I am newsgroup.confuse over and out. Divide * conquer = cut * run.decode(). I want the * to precede the dot too. Let's yack. I want to compile Python. Did you see my new post? I like it. Do you have any time you don't want? Time sale. Diez is still mad at me. I want primitives to structure themselves so I can pick up a pen. I am volunteer primitive structuring. Your structure sucks. assert atmostphere has drags. i don't think 'and' means the right thing. 'and' is composure. So the above should be 'divide and conquer, normalize in the neighborhood of, cut and run'. I want to run laps. Are generators good for it? Can we punctuate differently Python? Try to explain to a 'stream' of particles particle what it's doing. I'm particle, who's wave. From http Tue Mar 18 17:52:25 2008 From: http (Paul Rubin) Date: 18 Mar 2008 14:52:25 -0700 Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> Message-ID: <7xfxunr97q.fsf@ruckus.brouhaha.com> sturlamolden writes: > def nonunique(lst): > slst = sorted(lst) > return list(set([s[0] for s in > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) The items are all comparable and you're willing to take them out of order? from collections import defaultdict def nonunique(lst): d = defaultdict(int) for x in lst: d[x] += 1 return [x for x,n in d.iterkeys() if n > 1] From miki.tebeka at gmail.com Thu Mar 27 14:07:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 11:07:41 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: <04b1789a-664f-413d-8550-84bf8aa0edeb@59g2000hsb.googlegroups.com> Hello Supheakmungkol, > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: > > running install > running build > running build_ext > building 'Stemmer' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- > prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 > -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- > i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o > In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > syslimits.h:7, > ? ? ? ? ? ? ? ? ?from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > limits.h:11, > ? ? ? ? ? ? ? ? ?from libstemmer_c/src_c/../runtime/header.h:2, > ? ? ? ? ? ? ? ? ?from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: > /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: > limits.h: No such file or directory > error: command 'gcc' failed with exit status 1 > > Did anyone experience this before? Nope, compiles out of the box for me on 7.1 (IIRC easy_install worked for it as well). > Any comment/suggestion is highly appreciated. Do you have limits.h on your system? Did you install the python2.5-dev package? HTH, -- Miki http://pythonwise.blogspot.com From paddy3118 at googlemail.com Sun Mar 2 02:09:34 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 1 Mar 2008 23:09:34 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 2, 12:56 am, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira Hi Ira, Get Python installed on your machine - I would suggest the latest 2.5 release then either start up idle (or pythonwin if you have that on windows), or just type python at a command line prompt to get you to pythons shell. The Python shell together with the official tutorial is a great way to learn Python. If you start to flag, then their are a few videos of pre-teen kids learning Python here: http://showmedo.com/videos/python?topic=beginner_programming If they can learn it .... ;-) Welcome to Python, have fun! - Paddy. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 05:37:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 10:37:01 +0100 Subject: A question on decorators In-Reply-To: References: Message-ID: <47eb6ab6$0$16903$426a74cc@news.free.fr> Tim Henderson a ?crit : > Hello > > I am writing an application that has a mysql back end and I have this > idea to simplify my life when accessing the database. The idea is to > wrap the all the functions dealing with a particular row in a > particular in a particular table inside a class. So if you have a > table that looks like this: > > id str1 str2 pickled_data1 pickled_data2 > 0 woeif aposf (bin) (bin) > 1 ofime powe (bin) (bin) > ... > n oiew opiwe (bin) (bin) > > you can access this table like this > > t = Table(id) #to load a pre-entered row > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > when you change a an attribute of the class like this... > t.str1 = 'new value' > > it automatically updates the database backend. Congratulation, you just reinvented ORM. Good news is that there are already quite a few such packages in Python. May I recommand SQLAlchemy ?-) > I have what I just described working. However I want an easier way to > deal with my pickled_data. Right now I am pickling dictionaries and > list types. Now there is one problem with this, Indeed, but not the one you mention. The problem is that storing serialized dicts / lists / any other non atomic data in a blob is, well, not exactly the best possible use of a *relational* database. Do yourself a favour: learn what 'relational' means, and replace your blobs with the appropriate tables in the database. (snip code) > > Now while this works, it is a lot of work. This is why it's better to use an existing package whenever possible. SQLAlchemy is here: http://www.sqlalchemy.org/ (snip mode code) From steve at holdenweb.com Mon Mar 31 13:17:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 13:17:42 -0400 Subject: Automatically fill in forms on line In-Reply-To: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> References: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> Message-ID: Jackie Wang wrote: > Dear all, > > I want to automatically complete the following task: > > 1. Go to http://www.ffiec.gov/Geocode/default.aspx; > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > Highway 102"; > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > 4. Click the bottom "search"; > 5. In the opened page, extract and save the number after "Tract Code". > In the example, it will be "9659". > 6. Repeat Step 1 with a new address. > > Can Python realize these steps? Can these steps be done witout > openning and IE windows? Especially, I dont know how to write code for > step 2, 4 and 5. > Look at the mechanize library at http://wwwsearch.sourceforge.net/mechanize/ > Thank you! A pleasure. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jgardner at jonathangardner.net Thu Mar 20 18:39:20 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 20 Mar 2008 15:39:20 -0700 (PDT) Subject: eval and unicode References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> On Mar 20, 2:20?pm, Laszlo Nagy wrote: > > >> ?>>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? > >> ?????? ????????? ???????"' ) > >> True > > > When you feed your unicode data into eval(), it doesn't have any > > encoding or decoding work to do. > > Yes, but what about > > eval( 'u' + '"????????? ????????? ???????"' ) > Let's take it apart, bit by bit: 'u' - A byte string with one byte, which is 117 '"????????? ????????? ???????"' - A byte string starting with " (34), but then continuing in an unspecified byte sequence. I don't know what encoding your terminal/file/whatnot is written in. Assuming it is in UTF-8 and not UTF-16, then it would be the UTF-8 representation of the unicode code points that follow. Before you are passing it to eval, you are concatenating them. So now you have a byte string that starts with u, then ", then something beyond 128. Now, when you are calling eval, you are passing in that byte string. This byte string, it is important to emphasize, is not text. It is text encoded in some format. Here is what my interpreter does (in a UTF-8 console): >>> u"????????? ????????? ???????" u'\u5fb9\u5e95\u3057\u305f\u30b3\u30b9\u30c8\u524a\u6e1b \xc1\xcd \u0170\u0150\xdc\xd6\xda\xd3\xc9 \u0442\u0440\u0438\u0440\u043e \u0432\u0430' The first item in the sequence is \u5fb9 -- a unicode code point. It is NOT a byte. >>> eval( '"????????? ????????? ???????"' ) '\xe5\xbe\xb9\xe5\xba\x95\xe3\x81\x97\xe3\x81\x9f \xe3\x82\xb3\xe3\x82\xb9\xe3\x83\x88\xe5\x89\x8a\xe6\xb8\x9b \xc3\x81\xc3\x8d\xc5\xb0\xc5\x90\xc3\x9c\xc3\x96\xc3\x9a \xc3\x93\xc3\x89 \xd1\x82\xd1\x80\xd0\xb8\xd1\x80\xd0\xbe \xd0\xb2\xd0\xb0' The first item in the sequence is \xe5. This IS a byte. This is NOT a unicode point. It doesn't represent anything except what you want it to represent. >>> eval( 'u"????????? ????????? ???????"' ) u'\xe5\xbe\xb9\xe5\xba\x95\xe3\x81\x97\xe3\x81\x9f \xe3\x82\xb3\xe3\x82\xb9\xe3\x83\x88\xe5\x89\x8a\xe6\xb8\x9b \xc3\x81\xc3\x8d\xc5\xb0\xc5\x90\xc3\x9c\xc3\x96\xc3\x9a \xc3\x93\xc3\x89 \xd1\x82\xd1\x80\xd0\xb8\xd1\x80\xd0\xbe \xd0\xb2\xd0\xb0' The first item in the sequence is \xe5. This is NOT a byte. This is a unicode point-- LATIN SMALL LETTER A WITH RING ABOVE. >>> eval( u'u"????????? ????????? ???????"' ) u'\u5fb9\u5e95\u3057\u305f\u30b3\u30b9\u30c8\u524a\u6e1b \xc1\xcd \u0170\u0150\xdc\xd6\xda\xd3\xc9 \u0442\u0440\u0438\u0440\u043e \u0432\u0430' The first item in the sequence is \u5fb9, which is a unicode point. In the Python program file proper, if you have your encoding setup properly, the expression u"????????? ????????? ???????" is a perfectly valid expression. What happens is the Python interpreter reads in that string of bytes between the quotes, interprets them to unicode based on the encoding you already specified, and creates a unicode object to represent that. eval doesn't muck with encodings. I'll try to address your points below in the context of what I just wrote. > The passed expression is not unicode. It is a "normal" string. A > sequence of bytes. Yes. > It will be evaluated by eval, and eval should know > how to decode the byte sequence. You think eval is smarter than it is. > Same way as the interpreter need to > know the encoding of the file when it sees the u"????????? > ????????? ???????" byte sequence in a python source file - before > creating the unicode instance, it needs to be decoded (or not, depending > on the encoding of the source). > Precisely. And it is. Before it is passed to eval/exec/whatever. > String passed to eval IS python source, and it SHOULD have an encoding > specified (well, unless it is already a unicode string, in that case > this magic is not needed). > If it had an encoding specified, YOU should have decoded it and passed in the unicode string. > Consider this: > > exec(""" > import codecs > s = u'?' > codecs.open("test.txt","w+",encoding="UTF8").write(s) > """) > > Facts: > > - source passed to exec is a normal string, not unicode > - the variable "s", created inside the exec() call will be a unicode > string. However, it may be Û or something else, depending on the > source encoding. E.g. ASCII encoding it is invalid and exec() should > raise a SyntaxError like: > > SyntaxError: Non-ASCII character '\xc5' in file c:\temp\aaa\test.py on > line 1, but no encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor details > > Well at least this is what I think. If I'm not right then please explain > why. > If you want to know what happens, you have to try it. Here's what happens (again, in my UTF-8 terminal): >>> exec(""" ... import codecs ... s = u'?' ... codecs.open("test.txt","w+",encoding="UTF8").write(s) ... """) >>> s u'\xc5\xb0' >>> print s ?? >>> file('test.txt').read() '\xc3\x85\xc2\xb0' >>> print file('test.txt').read() ?? Note that s is a unicode string with 2 unicode code points. Note that the file has 4 bytes--since it is that 2-code sequence encoded in UTF-8, and both codes are not ASCII. Your problem is, I think, that you think the magic of decoding source code from the byte sequence into unicode happens in exec or eval. It doesn't. It happens in between reading the file and passing the contents of the file to exec or eval. From fakeaddress at nowhere.org Fri Mar 14 03:42:05 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 07:42:05 GMT Subject: Socket Performance In-Reply-To: <3c1f0d7b-4f1d-4ec6-ba6f-ba4fa2833647@b1g2000hsg.googlegroups.com> References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <13tk779gboqcgb9@corp.supernews.com> <3c1f0d7b-4f1d-4ec6-ba6f-ba4fa2833647@b1g2000hsg.googlegroups.com> Message-ID: castironpi at gmail.com wrote: [Dennis Lee Bieber had written:] >> Or create a protocol where the first 16 bits (in network byte order) >> contain a length value for the subsequent data, and use a receive >> process that consists of: >> >> leng = ntoh(socket.recv(2)) >> data = socket.receive(leng) >> >> (the send can combine the length with the data into a single packet) > > Are two 'sends' guaranteed to arrive as at least two 'receives'? No. Nor are they guaranteed to arrive as at least most two. > Send-3: xxx > Send-3: yyy > Receive-6: xxxyyy Can happen, though I think the problem with Dennis's code is the other way. The recv in leng = ntoh(socket.recv(2)) might return one byte of data, not two. The latter recv is similar. -- --Bryan From castironpi at gmail.com Sat Mar 22 03:25:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 00:25:57 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> Message-ID: <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> On Mar 21, 3:39?pm, John Machin wrote: > On Mar 22, 1:11 am, castiro... at gmail.com wrote: > > A collision sequence is not so rare. > > > >>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > > > [1, 1, 1, 1, 1, 1, 1, 1] > > Bryan did qualify his remarks: "If we exclude the case where an > adversary is choosing the keys, ..." Some adversary. What, you mean, my boss or my customers? From gagsl-py2 at yahoo.com.ar Sun Mar 30 00:27:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 01:27:18 -0300 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> Message-ID: En Sun, 30 Mar 2008 00:20:34 -0300, Steven D'Aprano escribi?: > On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote: > >> def main(): >> global func >> func = factory() >> return timeit.Timer('func()', 'from __main__ import func').timeit() > > Alas, this does not work, because all the Timer instances share the same > state. Second try: # timeanyfunc.py from timeit import Timer from itertools import count _counter = count() def timeanyfunc(fn, *args, **kw): def wrapper(fn=fn, args=args, kw=kw): return fn(*args, **kw) wrappername = 'wrapper%d' % _counter.next() globals()[wrappername] = wrapper return Timer("%s()" % wrappername, "from %s import %s" % (__name__, wrappername)) Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with each call. But it's the only way I could find, at least without changing the code template used by timeit. py> from timeanyfunc import timeanyfunc py> py> def functionA(arg): ... print "Function A",arg ... py> def functionB(arg): ... print "Function B",arg ... py> def test_timer(func1, func2): ... T1 = timeanyfunc(func1, "arg1") ... T2 = timeanyfunc(func2, "arg2") ... print "Calling %s" % func1.__name__ ... T1.repeat(3, 1) ... print "Calling %s" % func2.__name__ ... T2.repeat(3, 1) ... py> test_timer(functionA, functionB) Calling functionA Function A arg1 Function A arg1 Function A arg1 Calling functionB Function B arg2 Function B arg2 Function B arg2 -- Gabriel Genellina From tjreedy at udel.edu Sun Mar 9 19:23:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Mar 2008 19:23:25 -0400 Subject: 1.5.2 and functools or similar References: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Message-ID: "Troels Thomsen" <"nej tak..."@bag.python.org> wrote in message news:47d45625$0$15876$edfadb0f at dtext01.news.tele.dk... | def updateTimers() | for timerItm in timerTable: | ... | .... | .... | timerItm.func(*timerItm.parameters) | | Works well on python 2.5 but not on 1.5.2 (?) apply(timerItm.func, timerItm.parameters) # see http://docs.python.org/lib/non-essential-built-in-funcs.html apply disappears in 3.0 tjr From kla at us.de Fri Mar 21 11:53:35 2008 From: kla at us.de (klaus) Date: 21 Mar 2008 15:53:35 GMT Subject: beginners question about return value of re.split References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <47e3d9ff$0$17341$e4fe514c@dreader19.news.xs4all.nl> On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote: <..........> Ok thank you ! I think I got a bit lost in all the possibilities python has to offer. But your answers did the trick. Thank you all again for responding and elaborating. Cheers, KL. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 09:13:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 13:13:48 -0000 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> Message-ID: <13t7okcjo91gaa2@corp.supernews.com> On Sun, 09 Mar 2008 05:20:41 -0700, Guillermo wrote: >>A protocol is just an interface that an object agrees to implement. In >>your case, you would state that every object stored in your special dict >>must implement the to_tagged_value method with certain agreeable >>semantics. > > Hm... I've searched about the implementation of protocols and now (I > believe) I know how to implement the iterable protocol, for instance, > but have no clue about how to define my own... I'm surely not thinking > the right way, but I don't seem to be able to wrap my head around the > implementation details of "custom" protocols... Is it just a matter of > extending the different object classes (dict, list, tuple...)? Where do > you put the interface/protocol code? :-? A protocol is a convention that you insist other objects must follow, not code. To implement that convention, naturally you need to write code, but the convention makes the protocol, not the code. Some examples: To be considered a writable file, your object must include a write() method and a close() method. It doesn't matter what those methods do exactly, so long as they behave reasonably. For instance, the close() method might do nothing, and the write() method might send an SMS. To be a random-access writable file, it must also include a seek() method. To be a sequence, your object must obey the sequence protocol, which says it has a __getitem__ method which takes integer arguments starting at 0 and increasing, until it raises IndexError. You don't have to write any code to create a protocol, you just have to tell people what it is. Here's my parrot protocol: To be a parrot, your object must have a method speak() which takes an integer argument and returns the case-insensitive string "spam" repeated that many times. I'm done. I have a protocol. But if I want to actually use it, then I need an object that obeys it, and if I can't wait for somebody else to write it, I need to write one myself. So here it is: class Viking(object): def __init__(self, case='upper'): if case == 'upper': self.case = str.upper else: self.case = str.lower def speak(self, n): return self.case("spam"*n) And now Viking instances are also parrots, or rather, they obey the parrot protocol: >>> v = Viking() >>> v.speak(3) 'SPAMSPAMSPAM' I hope this helps. -- Steven From michael.wieher at gmail.com Thu Mar 20 12:34:54 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 11:34:54 -0500 Subject: if __name__ == '__main__': In-Reply-To: <8c7f10c60803200921p3c4a989ajf7797688072468e@mail.gmail.com> References: <8c7f10c60803200921p3c4a989ajf7797688072468e@mail.gmail.com> Message-ID: Well, consider this: you have a file named .py, built like this: ~~~~~~~~~~~~~~~~~~~~~ #!/usr/bin/python def : .... return if __name__=="__main__": print "Unit test" else: pass #module imported by another module/script ~~~~~~~~~~~~~~~~~~~~~~ If you type, on command line, >python ./.py you will see "Unit test" printed to the screen. if, however you are in another python file and type "import " the code will, instead, "pass" and nothing will occur. I hope this helps =) 2008/3/20, Simon Brunning : > > On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde wrote: > > Hi, > > I am new to the python and not getting meaning of following line, > > > > if __name__ == '__main__': > > main() > > < > http://www.python.org/doc/faq/programming/#how-do-i-find-the-current-module-name > > > > -- > Cheers, > Simon B. > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Mar 10 04:43:33 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Mar 2008 09:43:33 +0100 Subject: Adjust a canvas as the window is resized References: <63ga4fF27edonU1@mid.individual.net> Message-ID: K Viltersten wrote: > Do i need to set a callback to a canvas > in order to "listen" to the root window > being resized in order to make it adjust > its contents? > > If so, how? If not, how do i make the > canvas draw a line from one corner to > an other? import Tkinter as tk root = tk.Tk() canvas = tk.Canvas(root) canvas.pack(expand=True, fill=tk.BOTH) line = canvas.create_line(0, 0, 0, 0) def resize(event): canvas.coords(line, 0, 0, event.width, event.height) canvas.bind("", resize) root.mainloop() Peter From stef.mientki at gmail.com Fri Mar 28 14:02:27 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 19:02:27 +0100 Subject: class or inherited list ? In-Reply-To: <47ED195B.4070902@gmail.com> References: <47ED0BA1.9020103@gmail.com> <47ED195B.4070902@gmail.com> Message-ID: <47ED32B3.8060604@gmail.com> >>> >>> class super_list(list): >>> pass >>> >>> def kwadraat ( value ) : >>> return value * value >>> >>> x={} >>> x['frequency']=33 >>> x['functie']=kwadraat >>> print x['functie'](2) >>> >>> y = super_list() >>> y.frequency = 33 >>> y.functie = kwadraat >>> print y.functie(3) >>> >> >> You don't use y as a list at all - you might as well inherit from >> object. > Good point, didn't notice that. Sorry, not a good point, by deriving from a list, I get all the list methods for nothing. cheers, Stef Mientki From MartinRinehart at gmail.com Wed Mar 5 11:40:15 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 08:40:15 -0800 (PST) Subject: Why """, not '''? References: Message-ID: <23757d81-402e-4a99-b927-379f3e953b4c@i7g2000prf.googlegroups.com> D'Arcy J.M. Cain wrote: > Where did you see that? The only place I saw it was the style guide > and it was only talking about docstrings. PEP 8 and 257, and you're right, they are both about docstrings. Also, I'd never seen an example of the triple apostrophe form until I dove into the formal syntax specification. From donn at u.washington.edu Fri Mar 28 14:30:05 2008 From: donn at u.washington.edu (Donn Cave) Date: Fri, 28 Mar 2008 11:30:05 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> Message-ID: In article <654ng1F2cvh8aU1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > > systems. (In theory, file input/output should also be available as > > asynchronous code, but async IO is low-level and not available in > > Python.) While threads shouldn't be considered a replacement for > > I suggest you tell that the twisted-guys. And the ones from the built-in > asyncore-module. > > They will be surprised to hear that their years worth of working code > will evaporate in a rosa cloud. > > Diez I appreciate the droll sense of humor, but do you mean to assert that asyncore.py supports asynchronous disk file I/O? What that means to me is, you queue a disk read, and there's an event flag or something that you can wait for before you come back to find the data in your buffer. (That's how I remember it from the old days, when it mattered a little, though not enough that I ever remember actually doing it, and 20 years later I guess the incentive is even less.) I see MacOS supports an F_RDADVISE that might give you a head start on reading into the system buffer, but that's 3rd rate asynchrony because there's no way to know when the data is ready, and 3rd rate I/O because afterwards you still have the copying to do. I don't see even this much in asyncore.py, but I just gave it a glance. thanks, Donn Cave, donn at u.washington.edu From PurpleServerMonkey at gmail.com Thu Mar 20 21:30:18 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Thu, 20 Mar 2008 18:30:18 -0700 (PDT) Subject: Distributing Python Apps on Linux\BSD Message-ID: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> Working on a rather large open source python application that I want to release for Linux and BSD and was wondering what methods others are using to distribute large and complex applications. Setuptools and friends seem to be focused on distributing modules, I'm at the other end of the scale where I want to distribute an entire application so that an Administrator can run a single install and have a fully operational product. A key requirement is that I want the application to fit in with what and admin would expect an application to look like at the system level i.e site-packages like structures aren't suitable. So far I've thought of using a configure script and make which would call some custom python installer script to do the actual install. It fits in nicely with what I want to achieve but are there any better options out there, how are others doing the same thing? From roygeorget at gmail.com Mon Mar 10 00:36:34 2008 From: roygeorget at gmail.com (royG) Date: Sun, 9 Mar 2008 21:36:34 -0700 (PDT) Subject: dot() and tensordot() Message-ID: hi can numpy.dot() be used instead of tensordot()? is there any performance difference? I am talking about operation btw numpy arrays of dimensions 50 X 20,000 where elements are of float type. i tried posting in numpy group where i had gotten membership..but when i post a msg it says posting by non member and so doesn't show up :-( royG From clodoaldo.pinto at gmail.com Fri Mar 28 13:03:03 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Fri, 28 Mar 2008 10:03:03 -0700 (PDT) Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> <37d6b141-5ba0-4178-b45a-512e59433803@s12g2000prg.googlegroups.com> Message-ID: On Mar 28, 1:56 pm, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 13:22:06 -0300, Clodoaldo > escribi?: > > > > > On Mar 28, 12:09 pm, "Gabriel Genellina" wrote: > >> En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo > >> escribi?: > > >> > What i need to know is where can an equal char appear in a > >> > urlsafe_b64encoded string?: > > >> > a)only at end; > >> > b)both at the end and at the begginig; > >> > c)anywhere in the string; > > >> > A sure answer will make my regexp safer. > > >> Only at the end. The encoded string has 4*n chars when the input string > >> has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has > >> 4*(n+1) chars right padded with 2 or 1 "=" chars. > >> If your input has 3n chars, the output won't have any "=" > > > Thanks. But I'm not sure i get it. What is n? > > (Any nonnegative integer...) > I mean: For base64 encoding, the length of the output depends solely of > the length of the input. If the input string length is a multiple of 3, > the output length is a multiple of 4, with no "=". If the input length is > one more than a multiple of 3, the output has two "==" at the end. If the > input length is two more than a multiple of 3, the output has only one "=" > at the end. In all cases, the output length is a multiple of 4. > > [base64 uses 64=2**6 characters so it encodes 6 bits per character; to > encode 3 bytes=3*8=24 bits one requires 24/6=4 characters] > > > A md5 digest will always be 16 bytes length. So if i understand it > > correctly (not sure) the output will always be 22 chars plus two > > trailing equal chars. Right? > > Exactly. Thank you. That was great support! From michael.wieher at gmail.com Sun Mar 23 21:03:32 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 23 Mar 2008 20:03:32 -0500 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: I changed the last few lines to read: 37 kalam.howMany() 38 c = Person('Catherine', 'F') 39 #cathy.sayHi() 40 #cathy.howMany() 41 #swaroop.sayHi() 42 #swaroop.howMany() 43 And I don't get the error. However if I change line 38 to read ca = Person('Catherine','F') It again initializes and then the error occurs. It isn't random, I can run the code 10, 20 times with variable name 'c' and no error, and then again with variable name 'ca' or 'cathy' and the error does occur. I haven't much experience with __del__() functions but you're right -- this is strange as all hell. And I can't even imagine why it would happen at all. Obviously it is attempting to access the Person.population() variable. Which is a logic error, (I think) since well, we have 3 instances of the class being created and then the unbound variable (ie: a variable not associated with any instantiation of the class) being incremented and decremented. Logically, I think it shouldn't work at all, but somehow this unbound variable is working but in a very buggy way. Or am I wrong? Are unbound class-variables supposed to be used to coordinate between multiple instantiations of that class? 2008/3/23, George Sakkis : > > On Mar 23, 8:01 pm, QS wrote: > > Hi to all! > > I am new to python, and I encountered a weird problem. > > > > Here is my code > > > > ##########>8#################### > > #!/usr/bin/python > > # Filename: objvar.py > > class Person: > > '''Represents a person.''' > > > > population = 0 > > #sex = 'F' > > #age = 22 > > # It is vague here: is this variable going to be a class, or > > object, variable > > > > def __init__(self, name, sex): > > '''Initializes the person's data.''' > > self.name = name > > self.sex = sex > > print '(Initializing %s )' % self.name > > # When this person is created, he/she > > # adds to the population > > Person.population += 1 > > > > def __del__(self): > > '''I am dying.''' > > > > print '%s says bye.' % self.name > > Person.population -= 1 > > if Person.population == 0: > > print 'I am the last one.' > > else: > > print 'There are still %d people left.' % > > Person.population > > > > def sayHi(self): > > '''Greeting by the person. > > > > Really, that's all it does.''' > > > > self.age = 25 > > print 'Hi, my name is %s, and I am %s, and I am age %d ' % > > (self.name, self.sex, self.age) > > > > def howMany(self): > > '''Prints the current population.''' > > if Person.population == 1: > > print 'I am the only person here.' > > else: > > print 'We have %d persons here.' % Person.population > > > > swaroop = Person('Swaroop', 'M') > > swaroop.sayHi() > > swaroop.howMany() > > kalam = Person('Abdul Kalam', 'M') > > kalam.sayHi() > > kalam.howMany() > > cathy = Person('Catherine', 'F') > > cathy.sayHi() > > cathy.howMany() > > swaroop.sayHi() > > swaroop.howMany() > > > > ############# 8< ######################### > > > > When I run this script, I got the following exception: > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'population'" in > <__main__.Person instance at 0xb7d8ac6c>> ignored > > > > To to newcomer like me, this message doesn't make much sense. What > > seems weird to me is that, if I change the variable cathy to something > > else, like cath, or even cat, then the script will finish gracefully. > > Why "cathy" is not liked?!! > > > > Some of you may have recognized that the code is derived from a sample > > code in Swaroop's "A byte of python". > > > > My python is of version 2.5.1, on Ubuntu. > > > That's really weird... it's reproducible on Windows too. It doesn't > make any sense why the name of the variable would make a difference. > My guess is you hit some kind of obscure bug. > > > George > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed Mar 26 12:33:43 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 09:33:43 -0700 Subject: Some notes on a high-performance Python application. Message-ID: <47ea78a5$0$36353$742ec2ed@news.sonic.net> I run SiteTruth (sitetruth.com), which rates web sites for legitimacy, based on what information it can find out about the business behind the web site. I'm going to describe here how the machinery behind this is organized, because I had to solve some problems in Python that I haven't seen solved before. The site is intended mainly to support AJAX applications which query the site for every ad they see. You can download the AdRater client ("http://www.sitetruth.com/downloads/adrater.html") and use the site, if you like. It's an extension for Firefox, written in Javascript. For every web page you visit, it looks for URLs that link to ad sites, and queries the server for a rating, then puts up icons on top of each ad indicating the rating of the advertiser. The client makes the query by sending a URL to an .fcgi program in Python, and gets XML back. So that's the interface. At the server end, there's an Linux/Apache/mod_fcgi/Python server. Requests come in via FCGI, and are assigned to an FCGI server process by Apache. The initial processing is straightforward; there's a MySQL database and a table of domains and ratings. If the site is known, a rating is returned immediately. This is all standard FCGI. If the domain hasn't been rated yet, things get interesting. The server returns an XML reply with a status code that tells the client to display a "busy" icon and retry in five seconds. Then the process of rating a site has to be started. This takes more resources and needs from 15 seconds to a minute, as pages from the site are read and processed. So we don't want to do rating inside the FCGI processes. We want FCGI processing to remain fast even during periods of heavy rating load. And we may need to spread the processing over multiple computers. So the FCGI program puts a rating request into the database, in a MySQL table of type ENGINE=MEMORY. This is just an in-memory table, something that MySQL supports but isn't used much. Each rating server has a "rating scheduler" process, which repeatedly reads from that table, looking for work to do. When it finds work, it marks the task as "in process". The rating scheduler launches multiple subprocesses to do ratings, all of which run at a lower priority than the rest of the system. The rating scheduler communicates with its subprocesses via pipes and Pickle. Launching a new subprocess for each rating is too slow; it adds several seconds as CPython loads code and starts up. So the subprocesses are reusable, like FCGI tasks. Every 100 uses or so, we terminate each subprocess and start another one, in case of memory leaks. (There seems to be a leak we can't find in M2Crypto. Guido couldn't find it either when he used M2Crypto, as he wrote in his blog.) Each rating process only rates one site at a time, but is multithreaded so it can read multiple pages from the site, and other remote data sources like BBBonline, at one time. This allows us to get a rating within 15 seconds or so. When the site is rated, the database is updated, and the next request back at the FCGI program level will return the rating. We won't have to look at that domain for another month. The system components can run on multiple machines. One can add rating capacity by adding another rating server and pointing it at the same database. FCGI capacity can be added by adding more FCGI servers and a load balancer. Adding database capacity is harder, because that means going to MySQL replication, which creates coordination problems we haven't dealt with yet. Also, since multiple processes are running on each CPU, multicore CPUs help. Using MySQL as a queueing engine across multiple servers is unusual, but it works well. It has the nice feature that the queue ordering can be anything you can write in a SELECT statement. So we put "fair queueing" in the rating scheduler; multiple requests from the same IP address compete with each other, not with those from other IP addresses. So no one site can use up all the rating capacity. Another useful property of using MySQL for coordination is that we can have internal web pages that make queries and display the system and queue status. This is easy to do from the outside when the queues are in MySQL. It's tough to do that when they're inside some process. We log errors in a database table, not text files, for the same reason. In addition to specific problem logging, all programs have a final try block around the whole program that does a stack backtrace and puts that in a log entry in MySQL. All servers log to the same database. Looking at this architecture, it was put together from off the shelf parts, but not the parts that have big fan bases. FCGI isn't used much. The MySQL memory engine isn't used much. MySQL advisory locking (SELECT GET LOCK("lockname",timeout)) isn't used much. Pickle isn't used much over pipes. M2Crypto isn't used much. We've spent much time finding and dealing with problems in the components. Yet all this works quite well. Does anyone else architect their systems like this? John Nagle From rschroev_nospam_ml at fastmail.fm Thu Mar 13 06:46:57 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 13 Mar 2008 11:46:57 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: References: Message-ID: Hendrik van Rooyen schreef: > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above Answer 5: the output will be 'None': append() doesn't return the list, it returns None. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From watine at cines.fr Tue Mar 25 07:05:57 2008 From: watine at cines.fr (Benjamin Watine) Date: Tue, 25 Mar 2008 12:05:57 +0100 Subject: My python interpreter became mad ! Message-ID: <47E8DC95.4010009@cines.fr> Yes, my python interpreter seems to became mad ; or may be it's me ! :) I'm trying to use re module to match text with regular expression. In a first time, all works right. But since yesterday, I have a very strange behaviour : $ python2.4 Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re X-Spam-Flag: YES X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org X-Spam-Level: ********************** X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, URIBL_WS_SURBL autolearn=failed version=3.1.7-deb Traceback (most recent call last): File "", line 1, in ? File "/etc/postfix/re.py", line 19, in ? m = re.match('(Spam)', mail) AttributeError: 'module' object has no attribute 'match' >>> What's the hell ?? I'm just importing the re module. The code showed, is a previous test code, that seems to be buffered and that make an error. Each call to re module generate that error. How can I workaround ? Is there is a way to flush or restart python interpreter. Is it a bug in python ?? Thanks ! Ben From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 10:07:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 14:07:16 -0000 Subject: [OT] Modesty and apologies [Re: Re; finding euclidean distance,better code?] References: Message-ID: <13usj8k2ciks907@corp.supernews.com> On Sat, 29 Mar 2008 12:43:22 +0200, Hendrik van Rooyen wrote: > Sorry about having to dispel your illusions, but - [...] > Have you noticed that when people say "Sorry.....but...." they are not > normally sorry at all? Heh heh heh. Reminds me of a quote from the character Spike of "Buffy the Vampire Slayer": [quote] Yeah, I did a couple Slayers in my time. I don't like to brag. Who am I kidding? I love to brag! There was this one Slayer during the Boxer Rebellion, and... [end quote] -- Steven From mwilson at the-wire.com Sat Mar 1 18:41:42 2008 From: mwilson at the-wire.com (Mel) Date: Sat, 01 Mar 2008 18:41:42 -0500 Subject: sqlite3 adaptors mystery References: Message-ID: Matej Cepl wrote: [ ... ] > However, when running this program it seems converter doesn?t seem to work, > because I get: > > [matej at viklef dumpBugzilla]$ rm test.db ; python testAdaptors.py > [(u'False',), (u'True',)] > [matej at viklef dumpBugzilla]$ > > There is probably something quite obvious what I do incorrectly, but I just > don't see it. Could somebody kick me in the right direction, please? There's nothing much wrong. cur.fetchall is returning a list of all the selected rows, and each row is a tuple of fields. Each tuple is being converted for display by repr, so the strings are shown as unicode, which is what they are internally. Change the print to for (field,) in cur.fetchall(): print field and you'll see your plain-text strings. Mel. From http Sun Mar 2 12:02:38 2008 From: http (Paul Rubin) Date: 02 Mar 2008 09:02:38 -0800 Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <7483730d-4de4-4883-8021-2d607f691595@28g2000hsw.googlegroups.com> <7xk5kska5h.fsf@ruckus.brouhaha.com> Message-ID: <7xk5klnjo1.fsf@ruckus.brouhaha.com> Robert Brown writes: > Unfortunately, performance often comes at the cost of safety and > correctness. Optimized C programs can crash when pointers walk off the > end of arrays or they can yield incorrect results when integers overflow > the limits of the hardware. Yes, even unoptimized C programs can do that. C is just plain dangerous. > [SBCL Common Lisp] > Very rarely, say inside a loop, I temporarily change my default compiler > settings. Inside the lexical scope of these declarations, the compiled > code does no run-time type checking and trusts me. Here, broken Lisp > code can crash the system (just as broken C code can), but the compiled > code runs very fast. > > I trade off safety for speed, but only where necessary. It seems to me that this trade-off results from a problem with the language's expressivity. If you have a sound argument that the subscripts in your loop are actually safe, you ought to be able to express that argument to the compiler for static checking. That should result in safe code with no runtime checks needed. That said, trying to provide that level of expressivity is at the cutting edge of programming language research, and in real-world languages, for now, we have to live with some runtime checks. But in an example like (pseudocode): for i in 1..100: hack(x[i]) it should be enough to check outside the loop in constant time that 1..100 are valid subscripts for x, then generate the loop code with no check on each separate access. That is maybe not possible in C because i might be aliased to something, but in a sane language it should be possible. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 08:48:26 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 14:48:26 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> <87od8w7aws.fsf@physik.rwth-aachen.de> Message-ID: <659ggqF2f84eoU3@mid.individual.net> Torsten Bronger wrote: > Maybe he means "?". Haven't seen this either, nor do I think it's the same than "<>". >From afar, it looks more like "><". But this does more look like South Park style shut eyes than an operator. :) Regards, Bj?rn -- BOFH excuse #407: Route flapping at the NAP. From arnodel at googlemail.com Thu Mar 20 05:43:26 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 20 Mar 2008 02:43:26 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: On Mar 19, 3:08?am, Bryan Olson wrote: > Arnaud Delobelle wrote: > > Ninereeds wrote: > >> Hrvoje Niksic wrote: > >>> This doesn't apply to Python, which implements dict storage as an > >>> open-addressed table and automatically (and exponentially) grows the > >>> table when the number of entries approaches 2/3 of the table size. > >>> Assuming a good hash function, filling the dict should yield amortized > >>> constant time for individual additions. > > > Isn't this average constant time rather than amortized? > > This is expected amortized constant time. Is that really the same > thing as average constant time? Hmmm... that's subtle. I am not sure what the difference between expected amortized time complexity and average time complexity is (I know that they are defined as different notions but I don't know whether they reduce to the same thing or not). Anyway both are average case complexities and AFAIK worst case time complexity of insertion / lookup in a hashtable is still O(n). > >> OK. I obviously need to look up open-addressed tables. I thought this > >> was just, in effect, implicit linked listing - ie it still needs a > >> linear search to handle collisions, it just avoids the need for > >> explicitly stored link fields. Perhaps I'm mistaken. > > The amortized doubling breaks that. > > > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > > link to further details. > > Arnaud Delobelle offered a good Wikipedia link, and for more background > look up "amortized analysis. Hrvoje Niksic provided the link :). I still think two unrelated things are being compared in this thread when people say that method A (using dictionaries / sets) is O(n) and method B (sorting the list) O(nlogn). Isn't it the case that: | Worst case | Average case ---------|------------|------------- Method A | O(n^2) | O(n) Method B | O(nlogn) | O(nlogn) Which method is the best would then be determined by the distribution of the hash values of your data, and whether you want to have a guarantee the method will have a less-than-quadratic behaviour. -- Arnaud From gagsl-py2 at yahoo.com.ar Sun Mar 2 22:56:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 2 Mar 2008 19:56:55 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: On 2 mar, 17:21, castiro... at gmail.com wrote: > This worked: > > import socket > from time import time > > for i in range( 20 ): > ? ? HOST = '' > ? ? PORT = 80 #<---- > ? ? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > ? ? s.bind((HOST, PORT)) > ? ? print( 'listen' ) > ? ? s.listen(1) > ? ? conn, addr = s.accept() > ? ? print( 'connected', addr ) > ? ? print( conn.recv( 4096 ) ) #<---- > ? ? conn.send( bytes('test %f html>'%time(),'ascii') ) > ? ? conn.close() #<---- > ? ? s.close() > > ... and connect with a browser: ?http://localhost/if it's internet > exploder. Note that there is no need (nor is desirable) to close and rebind the listening socket for each connection. The loop should start with the accept call, and end at the conn.close() call (s.close() is left out of the loop). And then you get a pretty standard server that handles one connection at a time. -- Gabriel Genellina From zerty.david at gmail.com Mon Mar 31 16:50:42 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 31 Mar 2008 17:50:42 -0300 Subject: Python and Db In-Reply-To: References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> Message-ID: <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> I would like to use sqlite, But I also wanted a tutorial with the basis of the sql and etc, I never dealed with dbs before On Mon, Mar 31, 2008 at 3:42 PM, Gabriel Genellina wrote: > En Mon, 31 Mar 2008 14:50:27 -0300, David Anderson > escribi?: > > > Hi! I'm don't know almost nothing about bds, Can You suggest me an > Simple > > but efficient Bd to work with python apps? Can You suggest me any > > tutorials? > > See the Python wiki at: http://wiki.python.org/moin/DatabaseProgramming > If you stick with DBAPI 2.0 you won't have much trouble writing for one > database or another. sqlite is a good start and is included with Python > 2.5 > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From priya4u001 at gmail.com Mon Mar 3 23:26:09 2008 From: priya4u001 at gmail.com (priya4u) Date: Mon, 3 Mar 2008 20:26:09 -0800 (PST) Subject: download students tutorials,ebooks,softwares here for Free!!!! Message-ID: <5a3f53dd-59d4-48fa-a8dc-33b3e583a428@s12g2000prg.googlegroups.com> download students tutorials,ebooks,softwares here for Free!!!! Download Softwares Ebooks Students tutorials Games Ring tones Wallpapers and Lots of fun everything for FREE only at www.studentshangout.com From monica.leko at gmail.com Wed Mar 5 10:36:46 2008 From: monica.leko at gmail.com (Monica Leko) Date: Wed, 5 Mar 2008 07:36:46 -0800 (PST) Subject: Unit testing Web applications Message-ID: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> Hi! Does Python has some testing frameworks for testing Web applications (like Cactus and HttpUnit for Java), generating requests and checking if the response is correct? From castironpi at gmail.com Tue Mar 4 21:47:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 18:47:17 -0800 (PST) Subject: for-else References: <87r6eq82ch.fsf@benfinney.id.au> Message-ID: <6479eee7-839c-4250-ab9c-2784c890d9bc@e6g2000prf.googlegroups.com> That you could do yourself, CMIIW correct me if I'm wrong. try: ? ? for foo in iterex( bar_sequence ): > ? ? ? ? # normal iteration > ? ? ? ? spam(foo) > ? ? ? ? if funky(foo): > ? ? ? ? ? ? break ? ? except StopIterationEx, exc: > ? ? ? ? # the iterator stopped normally > ? ? ? ? eggs(exc) > ? ? else: > ? ? ? ? # the iterator exited abnormally, i.e. 'break' > ? ? ? ? sausage() > ? ? finally: > ? ? ? ? # always executed, even on 'break' > ? ? ? ? beans() Qualm, except would be needed in every for-, and in one sense doesn't obey the semantics of exceptions. The end of a finite list is not an exceptional element-- it's not one. However generator semantics don't yield finite sequences-- and finity is an exception, but for-loops don't use infinite ones. Makes it sound (*subj've) like I'm hacking by using for-loops..... or, like sequencetype.__iter__ is malformed. From http Wed Mar 26 03:21:51 2008 From: http (Paul Rubin) Date: 26 Mar 2008 00:21:51 -0700 Subject: Beta testers needed for a high performance Python application server References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> <47e9f77b$0$36357$742ec2ed@news.sonic.net> Message-ID: <7xd4pi2bn4.fsf@ruckus.brouhaha.com> John Nagle writes: > Fast cgi is a good technology, but it's not well documented or > well supported. For some reason, the Apache people don't like it. > It used to be part of the Apache distribution, but that ended years ago. It seems to be coming back into favor. See: http://cryp.to/publications/fastcgi/ I've thought for a long time that the right way to do it is with the SCM_RIGHTS ancillary message on unix domain sockets, that lets you pass file descriptors around between processes. One of these days... From knut.urbye at gmail.com Wed Mar 26 17:55:45 2008 From: knut.urbye at gmail.com (Knut) Date: Wed, 26 Mar 2008 14:55:45 -0700 (PDT) Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> > The script can't resolve the server name. Try to do it by hand using > nslookup or even ping (you may want to add a few print statements inside > the script to see the exact host name it is trying to connect to, in case > it isn't what you expect) > If you can't resolve the host name using nslookup, there is a network > problem, not in your script. If you can resolve it, try your script > without py2exe if possible. > > -- > Gabriel Genellina Thank you for the quick reply Gabriel. I have made sure the script works fine before I exe it. It is when I compile the program I get this error. I don't get how the compile changes server availability. Thanks again, Knut From martin at v.loewis.de Fri Mar 21 17:17:00 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 21 Mar 2008 22:17:00 +0100 Subject: os.path.getsize() on Windows In-Reply-To: <47E42413.8020503@ulmcnett.com> References: <47E41F3C.6040109@v.loewis.de> <47E42413.8020503@ulmcnett.com> Message-ID: <47E425CC.3070408@v.loewis.de> >> Why do you say that? It most definitely returns what the size currently >> is, not what it will be in the future (how could it know, anyway). > > I've seen this before, when copying a file in Windows. Windows reports > the size the file will be after the copy is complete (it knows, after > all, the size of the source file). I always thought this meant that > Windows is just much smarter than me, so I ignored it. No, I really think the target file has its size right from the beginning. Regards, Martin From siti.nurhaliza5 at gmail.com Wed Mar 26 03:16:02 2008 From: siti.nurhaliza5 at gmail.com (siti) Date: Wed, 26 Mar 2008 00:16:02 -0700 (PDT) Subject: Computer Shop center Message-ID: <205a2198-dceb-4079-a43e-00303800a528@d4g2000prg.googlegroups.com> Hi friends. if you wanna looking the latest original software..mobile phone...laptop..pc.. accessories... you can search at here..it will give the best price for you. Amazon has teamed up with Allianz Insurance plc who can offer you insurance on this product, covering accidental damage and breakdown.Amazon Services Europe SARL is an introducer appointed representative of Allianz Insurance plc which is authorised and regulated by the Financial Services Authority. AmazonServices Europe SARL, 5 Rue de Plaetis, L-2338, Luxembourg, is not part of the Allianz (UK) Group. The insurance is arranged, sold and administered by Allianz. By purchasing this insurance you confirm that you have read and understood the Technical details, product description and Keyfacts document provided by Allianz. This your URL http://astore.amazon.co.uk/happyfamily-21 From stefan_ml at behnel.de Sun Mar 16 11:49:15 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 16 Mar 2008 16:49:15 +0100 Subject: Types, Cython, program readability In-Reply-To: <199cfa42-ca1a-4db6-bf4d-a0a811daa791@s12g2000prg.googlegroups.com> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <199cfa42-ca1a-4db6-bf4d-a0a811daa791@s12g2000prg.googlegroups.com> Message-ID: <47DD417B.9070907@behnel.de> sturlamolden wrote: > On 16 Mar, 15:32, bearophileH... at lycos.com wrote: >> It seems the development of Cython is going very well, quite >> differently from the dead-looking Pyrex. Hopefully Cython will become >> more user-friendly too (Pyrex is far from being user-friendly for >> Windows users, it doesn't even contain a compiler, I think. The > > Pyrex is not dead. Technically, that's true. There has been a release not so long ago, although after a rather lengthy idle period. However, the current development cycle of Cython is so fast that Pyrex will have a hard time catching up. So there isn't much of a reason why you should prefer Pyrex over Cython. Stefan From http Wed Mar 12 18:38:32 2008 From: http (Paul Rubin) Date: 12 Mar 2008 15:38:32 -0700 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> Message-ID: <7xy78neffb.fsf@ruckus.brouhaha.com> Carl Banks writes: > > For example:http://www.python.org/dev/peps/pep-3100/ > > list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done] > > Hmm, wasn't aware they were taking it that far. You should almost > always avoid using the cmp parameter because it's very inefficient; I don't see what's so inefficient about it necessarily. The key argument invokes a DSU scheme that allocates and releases potentially a lot of memory, which both uses time and increases the program's memory region. The cmp option should not be removed. However, requiring it to be specified as a keyword parameter instead of just passed as an unlabelled arg is fine. From manicos010 at gmail.com Sat Mar 15 07:20:29 2008 From: manicos010 at gmail.com (manicos010 at gmail.com) Date: Sat, 15 Mar 2008 04:20:29 -0700 (PDT) Subject: ************GET FREE SOFTWARES HERE************** Message-ID: <37412733-4bb9-4cb8-9c86-4413c2e0337e@e10g2000prf.googlegroups.com> ************GET FREE SOFTWARES HERE************** GET SOME USEFUL SOFTWARE FOR FREE. THIS IS REALLY HERE IS THE LINK TO DOWNLOAD.JUST CLICK THE LINK BELOW THEN DOWNLOAD THE SOFTWARE YOU WANT. http://freeproductsforyou.googlepages.com From Lie.1296 at gmail.com Sat Mar 8 12:27:34 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 09:27:34 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <7xmypa844v.fsf@ruckus.brouhaha.com> <13t3r8oeh4frj43@corp.supernews.com> Message-ID: On Mar 8, 8:34?am, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote: > > Pierre Quentel writes: > >> I would like to know if there is a module that converts a string to a > >> value of the "most probable type" > > > ? ? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > > ? ? >>> import this > > ? ? The Zen of Python, by Tim Peters > > ? ? ... > > ? ? In the face of ambiguity, refuse the temptation to guess. > > Good advice, but one which really only applies to libraries. At the > application level, sometimes (but not always, or even most times!) > guessing is the right thing to do. Guessing should only be done when it have to be done. Users should input data in an unambiguous way (such as using 4 digit years and textual month name, this is the most preferred solution, as flexibility is retained but ambiguity is ruled out) or be forced to use a certain convention or be aware of how to properly input the date. Guessing should be done at the minimum. Personally, when I'm working with spreadsheet applications (in MS Office or OpenOffice) I always input dates in an unambiguous way using 4-digit year and textual month name (usually the 3-letter abbrevs for quicker inputting), then I can confidently rely the spreadsheet to convert it to its internal format correctly. The general parsers like the OP wanted are easy to create if dates aren't involved. > E.g. spreadsheet applications don't insist on different syntax for > strings, dates and numbers. You can use syntax to force one or the other, > but by default the application will auto-detect what you want according > to relatively simple, predictable and intuitive rules: > > * if the string looks like a date, it's a date; > * if it looks like a number, it's a number; > * otherwise it's a string. The worse thing that can happen is when we input a date in a format we know but the application can't parse and it consider it as a string instead. This kind of thing can sometimes easily pass our nose. I remembered I once formatted a column in Excel to write date with certain style, but when I tried to input the date with the same style, Excel can't recognize it, making the whole column rendered as useless string and requiring me to reinput the dates again. > Given the user-base of the application, the consequences of a wrong > guess, and the ease of fixing it, guessing is the right thing to do. > > Auto-completion is another good example of guessing in the face of > ambiguity. It's not guessing that is bad, but what you do with the guess. > > -- > Steven From grflanagan at gmail.com Tue Mar 25 12:36:49 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 25 Mar 2008 09:36:49 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: On Mar 25, 4:37 pm, Brian Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > > Gerard Flanagan wrote: > > Use the child class when calling super: > > > -------------------------------------- > > class Foo(object): > > def __init__(self): > > self.id = 1 > > > def getid(self): > > return self.id > > > class FooSon(Foo): > > def __init__(self): > > Foo.__init__(self) > > self.id = 2 > > > def getid(self): > > a = super(FooSon, self).getid() > > b = self.id > > return '%d.%d' % (a,b) > > > print FooSon().getid() > > -------------------------------------- > > That still doesn't do what he's trying to do. > Ah, I see. Maybe something like the following then? -------------------------------------- class Foo(object): def __init__(self): self._id = [1] def getid(self): return '.'.join(str(i) for i in self._id) class FooSon(Foo): def __init__(self): Foo.__init__(self) self._id.append(2) print FooSon().getid() -------------------------------------- G. From michael.wieher at gmail.com Thu Mar 6 15:34:45 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 6 Mar 2008 14:34:45 -0600 Subject: Py-Extension Irregularity In-Reply-To: References: Message-ID: Ah. Well, that is true =) Still, the fact of the file-pointer shifting more than 16-increments to the right is insane. Its a simple read(&struct,16) command. but you're right, the problem might lie elsewhere. I forgot that using 0 for a sentinel value in two places can confuse a complier (let alone me.) I ended up fixing it by resetting the file-pointer to zero on re-entry, and then manually fseeking() to the correct location each time. Its one extra command per iteration, but not a huge speed issue. I feel bad using a global file object, but its that or I open/close it every time I call the funct. Thanks for pointing out that bit of confusion =) 2008/3/6, Gabriel Genellina : > > En Thu, 06 Mar 2008 13:54:44 -0200, Michael Wieher > escribi?: > > > > Observe. > > > > Python Code Snippet: > > ==================== > > ... > > 66 while i < (self.nPCodes): > > 67 # print "%s:%s" % (self.nPCodes,i) > > 68 (c,l,sn,f,fn,sz) = tabmodule.getQuestion(i,self.mx3Path) > > 69 if _debug and sz>0: > > 70 _newPtrLoc = tabmodule.getMx3Ptr() > > 71 _diff = _newPtrLoc-_oldPtrLoc > > 72 _oldPtrLoc = _newPtrLoc > > 73 if _diff>16: > > 74 print _diff > > .... > > > > C++ Code Snippet: > > --------------------------- > > 189 static PyObject* > > 190 tabmodule_getMx3Ptr(PyObject * self, PyObject * args) { > > 191 int a; > > 192 a=mx3File.tellg(); > > 193 return Py_BuildValue("i",a); > > 194 } > > ... > > > > 189 PyObject * > > 190 tabmodule_getQuestion(PyObject * self, PyObject * args) { > > .... > > 208 mx3File.read((char*)&m_mdx,16); > > .... > > 237 //if(m_mdx.size==0) > > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > > 239 //return Py_BuildValue("iiiiii",m_mdx.compression, > > m_mdx.location, > > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > > } > > > > Output== > > michael at majw-m65:~/MRI/tabModule$ ./tabModule.py > > michael at majw-m65:~/MRI/tabModule$ > > > > None. (ie: the _diff is always 16 or less, which is what is SHOULD be, > > in > > fact, it is always 16.) > > > Why do you assert that? With those commented out lines, the last item > returned by getQuestion (sz) is always 0; nothing is printed because sz==0 > and the python code never enters the outer if. From that evidence I can't > say anything about _diff. > > > > Observe!!!! > > > > 237 if(m_mdx.size==0) > > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > > 239 return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, > > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > > > > By uncommenting line 237 and 239, we see: > > ... > > 64 > > 80 > > 32 > > 32 > > 32 > > 48 > > 128 > > 160 > > 32 > > 32 > > 64 > > .... > > > > Most of the numbers are still 16, but _diff is often larger than 16, by > > some > > multiple. > > > I'd print m_mdx values in the C++ source. > > > > How in Buddah's name is returning a Py_BuildValue() affecting a file > > pointer > > that isn't being used at all in the function???? > > > I don't think this is the cause... > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Sat Mar 1 23:53:04 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 1 Mar 2008 20:53:04 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: On 1 Mrz., 19:51, Barry Warsaw wrote: > Python 2.6 is not only the next advancement in the Python 2 series, it > is also a transitionary release, helping developers begin to prepare > their code for Python 3.0. Isn't this a silly idea? People have to migrate from 2.5 or lower releases to Python 2.6 first just to migrate to Python 3.0? What are the inherent / technical reasons that prevent migration directly from 2.5 to 3.0? From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 21:21:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 01:21:32 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <13ue0gsj76m6070@corp.supernews.com> On Sun, 23 Mar 2008 13:51:34 -0400, Roy Smith wrote: > On the other hand, when I do: > > def torture(): > woman.putInChair() > cushion.poke() > rack.turn() > > I've also done two things. First, I've created a function object (i.e. > a lambda body), and I've also bound the name torture to that function > object, in much the same way I did with the list. But, it's different. > The function object KNOWS that it's name is torture. No it does not. Function objects don't know their name. All they know is that they have a label attached to them that is useful to use as a name in some contexts, e.g. when printing tracebacks. It's just a label, nothing more. You can prove that for yourself with a few simple tests. Firstly, we can prove that functions don't know what they are called by writing a recursive function: def spam(n): if n <= 1: return "Spam" return "Spam " + spam(n-1) If spam() knows what it is called, then you should be able to rename the function and the recursive call will continue to work. But in fact, that's not what happens: >>> spam(3) # check that it works 'Spam Spam Spam' >>> tasty_stuff = spam # make an alias >>> tasty_stuff(3) 'Spam Spam Spam' But now watch what happens when we create a new function with the name spam. It hijacks the recursive call: >>> def spam(n): ... return "ham-like meat product" ... >>> tasty_stuff(3) 'Spam ham-like meat product' The function formerly known as "spam" isn't calling itself, it is merely calling a function by name "spam". But we can see that the function tasty_stuff() is still using the old "spam" label for itself: >>> tasty_stuff('foo') Traceback (most recent call last): File "", line 1, in File "", line 3, in spam TypeError: unsupported operand type(s) for -: 'str' and 'int' Unfortunately there's nothing we can do to fix that error. Even though the function object has an attribute "__name__" (also known as "func_name") which is set to spam, it isn't used for tracebacks. Instead, the label comes from a read-only attribute buried deep in the function object: >>> tasty_stuff.func_code.co_name = 'yummy meat-like product in a can' Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute This is a mistake, in my opinion. It's an arbitrary decision to make this read-only (as far as I can tell), which goes against the grain of Python's "we're all consenting adults here" philosophy. By the way, in case you're thinking that wanting to change the (so- called) name of a function is a silly think to do, not at all. Consider factory functions: def factory(how_much): def f(n=1): for i in range(n): print "I love spam a %s" % how_much return f Every function created by the factory has the same "name", no matter what name you actually use to refer to it. factory('little') and factory('lot') both uselessly identify themselves as "f" in tracebacks. The truth is that objects don't know what name they have, because objects don't have names. The relationship is the other way around: names have objects, not vice versa. Some objects (functions, classes, anything else?) usefully need a label so that they can refer to themselves in tracebacks and similar, and we call that label "the name", but it's just a label. It doesn't mean anything. [snip] > What Python give us with lambdas is some half-way thing. It's not a > full function, so it's something that people use rarely, Which people? > which means most people (like me) can't remember the exact syntax. Speak for yourself, not for "most people". > Even when I know > it's the right thing to be using in a situation, I tend not to use it > simply because the path of least resistance is to write a one-off > function vs. looking up the exact syntax for a lambda in the manual. lambda arguments : expression Why is that harder to remember than this? def name ( arguments ) : block And don't forget to include a return statement, or you'll be surprised by the result of the function. -- Steven From bkjones at gmail.com Sun Mar 16 22:49:51 2008 From: bkjones at gmail.com (Brian Jones) Date: Sun, 16 Mar 2008 19:49:51 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: > If you did not like the programming this year (aside from the sponsor > talks) and you did not participate in organizing PyCon or in delivering > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! I find this insulting, inexcusable, and utter nonsense. If putting the blame for a failed experiment on the backs of the good folks who paid good money for travel, lodging, and registration is also an experiment, you can hereby consider it also failed. The bottom line is that the people who are providing feedback in this forum are doing so *voluntarily*, and for the good of future PyCon events. They were sold a bill of goods, it was ill-comunicated, and they have taken their time to express that this is not a good idea moving forward. If it weren't for these people giving feedback, you would not have a complete experiment, because you would never have been able to prove or disprove your hypothesis. In fact, the people in this forum are just as important to the process as those who devised the experiment. As an experiment, it would seem that having an event organizer, who is presumably interested in the future success of the event, talking down to the people who would also like to see a better event in the future (and think they can make that happen - otherwise why bother giving feedback?), is doomed to failure. Of course, I'm only looking at how the experiment is being carried out. I claim ignorance as to the hypothesis. The rest of the points in your rant are all pretty commonly known by now, to most. At the end of the day, the buck has to stop somewhere, and that somewhere has to be with the organization that were charged with motivating a volunteer force, and the organization who set the expectations of the attendees. If you think that PyCon would've been better had there been more volunteers, then you should feed that back to the folks in charge of attracting and motivating said force. If you think it was simply a mis-labeling of the different classes of talks, feed that back to the folks who are in charge of such things. The point is that there are endless things that can be done which are more useful and productive than pointing fingers back at the people who support the conference by being attendees. They help build the conference too. A conference answers to its attendees, and that should be an expectation of anyone concerned with conference organization. Period. Exclamation point. Brian K. Jones Editor in Chief Python Magazine From carsten at uniqsys.com Wed Mar 12 21:32:24 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 12 Mar 2008 21:32:24 -0400 Subject: escape string to store in a database? In-Reply-To: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> Message-ID: <1205371944.3313.16.camel@localhost.localdomain> On Wed, 2008-03-12 at 18:18 -0700, andrei.avk at gmail.com wrote: > These pieces of text may have single and double quotes in > them, I tried escaping them using re module and string module and > either I did something wrong, or they escape either single quotes or > double quotes, not both of these. So that when I insert that text into > a db record, this causes an error from the database. What's the > accepted way of dealing with this? The accepted way of dealing with this is to use parameter binding: conn = somedbmodule.connect(...) cur = conn.cursor() cur.execute("insert into sometable(textcolumn) values (?)", (stringvar,) ) (Note that the question mark may have to be replaced with %s depending on which database module you're using.) For background information on parameter binding see, for example, http://informixdb.blogspot.com/2007/07/filling-in-blanks.html . HTH, -- Carsten Haese http://informixdb.sourceforge.net From python at rcn.com Mon Mar 3 16:17:08 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Mar 2008 13:17:08 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> Message-ID: <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> On Mar 3, 12:21 pm, "K Viltersten" wrote: > I'm writing a class for rational numbers > and besides the most obvious constructor > > def __init__ (self, nomin, denom): > > i also wish to have two supporting ones > > def __init__ (self, integ): > self.__init__ (integ, 1) > def __init__ (self): > self.__init__ (0, 1) For this particular use case, providing default arguments will suffice: class Fraction: def __init__(self, numerator=0, denomiator=1): ... Since Python doesn't support having two methods with the same name, the usual solution is to provide alternative constructors using classmethod(): @classmethod def from_decimal(cls, d) sign, digits, exp = d.as_tuple() digits = int(''.join(map(str, digits))) if sign: digits = -digits if exp >= 0: return cls(digits * 10 ** exp) return cls(digits, 10 ** -exp) Raymond From pete.forman at westerngeco.com Wed Mar 12 13:35:13 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 12 Mar 2008 17:35:13 +0000 Subject: best way to have enum-like identifiers? References: Message-ID: mh at pixar.com writes: > Currently I'm just putting this at the top of the file: > > py=1 > funcpre=2 > funcpost=3 > ... That can be done more compactly with py, funcpre, funcpost = range(3) give or take 1. > but I'm curious if there's a better way of doing this, > some kind of enum-like thing or somesuch. https://launchpad.net/munepy describes itself as yet another Python enum implementation. Its author is Barry Warsaw. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From davidbak at gmail.com Fri Mar 7 20:46:54 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 17:46:54 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> Message-ID: <1ec4b03a-75cd-432e-9e5d-750132324d38@s8g2000prg.googlegroups.com> On Mar 7, 3:41?pm, castiro... at gmail.com wrote: > On Mar 7, 4:39?pm, DBak wrote: > > > On Mar 7, 1:19?pm, "Chris Mellon" wrote: > > > > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > > > ?However I can't do this, because, of course, the name Tree isn't > > > > ?available at the time that the classes _MT and _Node are defined, so > > > > ?_MT and _Node can't inherit from Tree. > > > > Not only is the name not defined, the class doesn't even exist yet. > > > Yes, but, well - it certainly isn't usable yet, but some object (that > > will be the class when it is finished) is being built (its __dict__ is > > being populated, etc.) - so there's an object pointer available inside > > the interpreter that could be put somewhere. ?But this is pedantic - > > you're right, the class really isn't available until after the class > > statement. > > There is no obvious solution-- What do you mean? ?If there are any at > all, there is significant competition without clear winners. > > dict dictA: > ? ?membA= 0 > ? ?membB= 0 > > dict dictB: > ? ?membC= 0 > > But, if you try to nest them, do you want the rest of the 'dict' at > its outer level evaluated (that's your 'here is the crux'), or only > that point so far? > > dict dictO: > ? membA= 0 > ? dict membB: > ? ? membC= 0 > ? ? membD= membE > ? membE= 0 > > So, you can't refer to it at all. ?Especially if membE is defined in > outer scope. Thanks for your answer. To the extent I understand it: There is a difference between the class statements I was trying to nest, with the inner inheriting from the outer, and your dict example. The main thing is that in the class example - when the inner class is being built (i.e., inside its class statement's block) there is no need (as I understand it) for the parent class to be functional at all WHILE I AM DEFINING METHODS on the inner class. Sure, if the inner class had code to be executed immediately, such as statements setting class attributes on the inner class, and that code used names such that attribute lookup needed to be done, then that might or might not work - it would depend on where the names were defined in the outer class relative to the placement of the inner class statement - exactly like the fact that the order of definition matters when executing code when defining a module: functions defined in a module can, in their body, name functions not yet defined, but assignment statements to module attributes cannot (they get a run time error). But in the case I'm talking about I just want to define methods on the inner class, using names such that when the method is eventually called on an instance of the inner class the attribute lookup will proceed with the outer class being the inner class' parent. Creating instances of the inner class won't happen until after the inner class and the outer class are both fully created (and assigned to their names) so any name lookup using inheritance won't happen until both class objects are fully created, so ... if you could do it ... it would work fine. Anyway, I know it can't be done the way I wanted it - the attribute with the outer class' name hasn't been assigned yet when I need to reference it in the inner class' class statement - so I was just looking to see what the preferred alternative was. Based on the discussion so far it seems I should just forget about using nested classes and flatten everything to the module level, using the __all__ attribute to make it clear to the user of the data structure what pieces of the module he should actually be using. -- David From dave.brk at gmail.com Thu Mar 27 10:27:42 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 27 Mar 2008 16:27:42 +0200 Subject: Regarding __slots__ and other stuff: A couple of questions Message-ID: I'm new to Python. I'm trying to understand the type/class/object(instance) model. I have read here: http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html and here: http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html as well as here: http://users.rcn.com/python/download/Descriptor.htm There are still a couple of issues I'm unclear about. I'll be very happy if one of you could help me. *first:* Why doesn't this works? >>> class C(object): ... __slots__ = ['foo', 'bar'] ... class_attr = 'class attribute' ... >>> c = C() >>> c.foo = 'foo' >>> c.bar = 'bar' >>> c.bar, c.foo ('bar', 'foo') >>> c.__slots__ ['foo', 'bar'] >>> c.__slots__.append('eggs') >>> c.__slots__ ['foo', 'bar', 'eggs'] >>> c.eggs = 'eggs' Traceback (innermost last): File "", line 1, in AttributeError: 'C' object has no attribute 'eggs' *second:* what happens here? Why can I write to spam using the class object but not the using the instance? >>> class C(object): ... __slots__ = ['foo', 'bar'] ... class_attr = 'class attribute' ... >>> C.spam = 50 >>> C.spam 50 >>> C.spam = 56 >>> c = C() >>> c.spam = 55 Traceback (innermost last): File "", line 1, in AttributeError: 'C' object attribute 'spam' is read-only >>> C.spam = 55 >>> C.spam 55 *Third:* class RevealAccess(object): """A data descriptor that sets and returns values normally and prints a message logging their access. """ def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print 'Retrieving', self.name return self.val def __set__(self, obj, val): print 'Updating' , self.name self.val = val class A(object): def __init__(self): self.x = RevealAccess(10, 'var "x"') self.y = 5 class B(object): x = RevealAccess(10, 'var "x"') y = 5 >>> a = A() >>> b = B() >>> a.x <__main__.RevealAccess object at 0x00BAC730> >>> a.x = 55 >>> b.x Retrieving var "x" 10 >>> b.x = 55 Updating var "x" >>> Why the descriptor works only when created as a static variable and not as an instance variable? I'm sure all this questions stem from my lack of understanding python object model. But, please, what am I missing? Thanks Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Tue Mar 11 06:14:54 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 03:14:54 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> Message-ID: On Mar 11, 2:18?am, "Diez B. Roggisch" wrote: > > The problem with callbacks is that it works only for a small amount of > > callbacks, it'd be too messy to have twenty different callbacks. > > And the ultimate problem with callbacks is that we can't determine > > from the outside whether the operation should continue or breaks at > > the point of the callback without some messy trick. > > > We can't always determine whether we want to do this: > > def somefunc(argA, argB, callback = DO_NOTHING): > > ? ? if argA == argB: > > ? ? ? ? callback() > > > or this: > > def somefunc(argA, argB, callback = DO_NOTHING): > > ? ? if argA == argB: > > ? ? ? ? callback() > > ? ? ? ? return > > > perhaps we could do this: > > ? ? if argA == argB: > > ? ? ? ? if callback() == True: return > > > but that's so much extra codes written and would've been too messy to > > write. > > > And actually this isn't a rare cases, and in fact is very common. It's > > just that most cases that can be more cleanly written in > > SoftException, can usually be handled in different ways, using tricks > > that range from subtle to messy (like callbacks). > > I fail to see how your arguments follow. > > Regarding the number of callbacks: you can as well pass an object that > has several methods to call. If you passed an object that has several methods to call (using tuple or list) and you want to handle several softexceptions and ignore some others, you must still pass an empty methods to the one you want to ignore, cluttering the caller's code by significant degree: def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, DO_NOTHING)): if a == 0: raise callback(0) try: a += b except ZeroDivisionError: raise callback(1) if a <= 0: raise callback(2) raise callback(3) return a somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, DO_NOTHING)) if instead we use dict, well, we know how convenient dict's syntax is for a lot of manual data entry. ## imagine if we want to handle five or more callbacks somefunc(a, b, {callbackzero:handlerzero, callbacktwo:handlertwo}) > And the above example can easily be accomplished with "normal" > exceptions, like this: > > def toplelevel(): > ? ? ?def callback(a, b): > ? ? ? ? ?if a == b: > ? ? ? ? ? ? raise InterruptException() > ? ? ?try: > ? ? ? ? ? work(callback) > ? ? ?except InterruptException: > ? ? ? ? ? pass > > def work(callback=callback): > ? ? ?a = 10 > ? ? ?b = 20 > ? ? ?callback(a, b) That's why I said most things that can be more cleanly handled by SoftException can usually be handled in other forms, although in a more cluttered way. That could be more cleanly written in SoftException as: def work(): a = 10 b = 20 raise Equal(a, b) def toplevel(): try: work() except Equal, args: a, b = args if a == b: raise InterruptException OR ALTERNATIVELY (Which one's better depends on the purpose, generally the one below is better, but the one in the above is more flexible, yet a bit less convenient to use) def work(): a = 10 b = 20 if a == b: raise Equal def toplevel(): try: work() except Equal: raise InterruptException The reason why SoftException is useful is similar to the reason why for-loop and while is useful. AFAIK, all looping cases can be handled only by a blind loopers (a.k.a. while True:) and break, but a blind loopers is very inconvenient to use, and for-loop and while simplifies a lot of codes a lot. Exactly the same reason why SoftException is useful. > And even more: the callback-approach can do things like this: > > a, b = callback(a,b) > > to change values, which makes it superior to SoftExceptions - unless I > missed it's ability to capture context. If there is a syntax support, you could also make "resume" able to transfer values: def somefunc(a, b): if a == b: a, b = raise Equal(a, b) def toplevel(): try: somefunc(10, 20) except Equal, args: a, b = args[0], args[1] + 1 resume a, b On Mar 11, 5:18 am, "Diez B. Roggisch" wrote: > How would that differ from something like this: > > with add_soft_handler(SoftException): > invoke_something() > > ... # deep down in code > > raise_soft(SoftException()) > > The implementation of add_soft_handler and raise_soft is trivial - a bit > of thread-local storage and a stack. Perhaps you meant: raise_soft(SoftException) cause SoftException() may have side effects if called greedily That could be done, but when raise_soft() returns, it returns to the code that raises it so it must be 'break'en: def caller(a, b): if a == b: raise_soft(SoftException) break but this makes SoftException must break everytime, which make it lost its original purpose, so you have to add return code to raise_soft whether you want to break it or not: def caller(a, b): if a == b: if raise_soft(SoftException): break Compare to: def caller(a, b): if a == b: raise SoftException And this also makes it impossible to have state-changing behavior without some other weirder tricks From usenet at ionline.dk Thu Mar 27 06:27:26 2008 From: usenet at ionline.dk (ndlarsen) Date: Thu, 27 Mar 2008 11:27:26 +0100 Subject: Print to end of line in a terminal In-Reply-To: <47c5afe4$0$90273$14726298@news.sunsite.dk> References: <47c5afe4$0$90273$14726298@news.sunsite.dk> Message-ID: <47eb7692$0$90262$14726298@news.sunsite.dk> Hello again. I apologize for not replying earlier but I have been swamped in work lately. I appreciate your replies. Eventually I chose using curses for "right-hand edge of the window" as it seemed to be the most suitable solution. Thank you. ndlarsen From tommy.nordgren at comhem.se Sun Mar 2 09:12:43 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sun, 2 Mar 2008 15:12:43 +0100 Subject: Book Recomendations In-Reply-To: References: Message-ID: <82E6B4FF-4D10-4632-9255-3B4B00AA2296@comhem.se> On 2 mar 2008, at 01.56, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira > -- > http://mail.python.org/mailman/listinfo/python-list I would recommend "Programming Python", by Mark Lutz, from O'Reillys ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From mal at egenix.com Wed Mar 12 15:51:09 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 12 Mar 2008 20:51:09 +0100 Subject: Time Zone application after strptime? In-Reply-To: References: <47D1B703.6040200@egenix.com> Message-ID: <47D8342D.7030205@egenix.com> Jim Carroll wrote: > M.-A. Lemburg egenix.com> writes: > >> On 2008-03-07 22:24, Jim Carroll wrote: >>> It's taken me a couple of hours to give up on strptime >>> with %Z for recognizing >>> time zones... but that still leaves me in the wrong zone: >>> >>> How can I use the "PST" (or any other time zone name) >>> to adjust dt by the >>> correct number of hours to get it into UTC before storing in MySQL? >> You could try mxDateTime's parser. It will convert most timezones >> into UTC for you: >> >> >>> from mx.DateTime import * >> >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008') >> > 00' at 2afdc7078f50> >> > > Unfortunately, mx.DateTime also ignores the time zone. If > I parse the PST time, and ask for the result's time zone it > gives me my local time zone. The result of the mxDateTime parser will always be UTC, if you provide a time zone. You can then convert this value to any other timezone you choose. The reason for this is simple: UTC is the only stable timezone you can use if you want to store date/time value in e.g. a database or file. -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Aug 10 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ From pavloutefkros at gmail.com Sat Mar 29 17:27:16 2008 From: pavloutefkros at gmail.com (Gif) Date: Sat, 29 Mar 2008 14:27:16 -0700 (PDT) Subject: wxPython listctrl Message-ID: <4dc652a5-d6f9-4cb8-af30-ec1c9e4ea505@y21g2000hsf.googlegroups.com> I was wondering if there is a way to extract an icon from a file (executable) and then add it in a listctrl. I also 'd like to know if i can shorten the icon in order to fit in a listctrl item. I've managed to get the icon from an icon file and add t as a listctrl item but it remains 32x32. code: images = ['LimeWire.ico'] self.il = wx.ImageList(18, 10) self.il.Add(wx.Bitmap(images[0])) #This below raises an error saying that no handle was found for that image #self.ib = wx.IconBundle() #self.ib.AddIconFromFile(r'LimeWire.exe', wx.BITMAP_TYPE_ANY) self.listView1.SetImageList(self.il, wx.IMAGE_LIST_SMALL) self.listView1.SetItemImage(0, 0) From fetchinson at googlemail.com Thu Mar 20 03:39:48 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 20 Mar 2008 00:39:48 -0700 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] Message-ID: > Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , > and saw that the repr module was slated for vaporization. I've only > used the module a few times ever. I'm curious if the community wants > it kept around or whether it is considered clutter. > > The PEP is going to be finalized soon, so if you have issues with it, > they should be sent to the PEP author or brought up on the list, > http://mail.python.org/mailman/listinfo/stdlib-sig . Is it just me or others also think that it would be a major loss to remove tkinter from the python core? PEP 3108 starts off with: Each module to be removed needs to have a justification as to why it should no longer be distributed with Python. then goes on with, With so many other GUI options out there that are considered better than Tkinter, it might be best to remove Tkinter from the stdlib and make it an externally maintained package. I don't get it. There are many [insert your favorite software component] options outside of the python core that are considered better than the one coming with python, yet they don't get removed. All network servers for example could be thrown out because twisted is considered better. This just doesn't make sense to me. Tkinter is great for its purpose, typical use cases are creating a simple GUI composed of a couple of components only. You can nicely do this with tkinter and the large user base shows that it's a real need real people have. Sure, for fancy GUI stuff there are better options but for quick and simple things tkinter is just great. And last time I checked python comes with batteries included so why sould I need to search and download a third party package for such a common use case? Thoughts anyone? Cheers, Daniel From schiz at lon.don Sun Mar 2 14:13:42 2008 From: schiz at lon.don (Schizoid Man) Date: Sun, 02 Mar 2008 19:13:42 +0000 Subject: Beginner's assignment question In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > >> Lorenzo Gatti wrote: >>> On Mar 1, 3:39 pm, Schizoid Man wrote: >>>> As in variable assignment, not homework assignment! :) >>>> >>>> I understand the first line but not the second of the following code: >>>> >>>> a, b = 0, 1 >>>> a, b = b, a + b >>>> >>>> In the first line a is assigned 0 and b is assigned 1 simultaneously. >>>> >>>> However what is the sequence of operation in the second statement? I;m >>>> confused due to the inter-dependence of the variables. >>> >>> The expressions of the right of the assignment operator are evaluated >>> before assigning any new values, to the destinations on the left side >>> of the assignment operator. >>> So substitutig the old values of a and b the second assignment means >>> >>> a, b = 0, 0 + 1 >>> >>> Simplifying the Python Reference Manual ("6.3 Assignment Statements") >>> a little : >>> >>> assignment_stmt ::= target_list "="+ expression_list >>> >>> An assignment statement evaluates the expression list (remember that >>> this can be a single expression or a comma-separated list, the latter >>> yielding a tuple) and assigns the single resulting object to each of >>> the target lists, from left to right. >>> >>> [...] >>> >>> WARNING: Although the definition of assignment implies that overlaps >>> between the left-hand side and the right-hand side are `safe' (for >>> example "a, b = b, a" swaps two variables), overlaps within the >>> collection of assigned-to variables are not safe! For instance, the >>> following program prints "[0, 2]": >>> >>> x = [0, 1] >>> i = 0 >>> i, x[i] = 1, 2 >>> print x >>> >>> Lorenzo Gatti >> >> Thank you for the explanation. I guess my question can be simplified as: >> >> First step: a, b = 0, 1 >> No problem here as a and b are assigned values. >> >> Second step: a, b = b, a + b >> >> Now my question is does b become a + b after a becomes 1 or while a >> stays at 0? >> >> As the assignment occurs simultaneously I suppose the answer is while a >> stays at 0. > > Read the previous response carefully and you'll answer your question. > The right hand side is EVALUATED in full before values are assignated to > the left hand side. Evaluating b, a+b results in 1, 1. The, those values > are assigned to a, b. Thank you very much. It's clear now. From brooklinetom at gmail.com Sat Mar 15 11:38:34 2008 From: brooklinetom at gmail.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 11:38:34 -0400 Subject: Unicode/UTF-8 confusion Message-ID: I'm still confused about this, even after days of hacking at it. It's time I asked for help. I understand that each of you knows more about Python, Javascript, unicode, and programming than me, and I understand that each of you has a higher SAT score than me. So please try and be gentle with your responses. I use simplejson to serialize html strings that the server is delivering to a browser. Since the apostrophe is a string terminator in javascript, I need to escape any apostrophe embedded in the html. Just to be clear, the specific unicode character I'm struggling with is described in Python as: u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of 0x27. This can be expressed in several common ways: hex: 0x27 Python literal: u"\u0027" Suppose I start with some test string that contains an embedded apostrophe -- for example: u" ' ". I believe that the appropriate json serialization of this is (presented as a list to eliminate notation ambiguities): ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] This is a 14-character utf-8 serialization of the above test string. I know I can brute-force this, using something like the following: def encode(aRawString): aReplacement = ''.join(['\\', '0', '0', '2', '7']) aCookedString = aRawString.replace("'", aReplacement) answer = simplejson.dumps(aCookedString) return answer I can't even make mailers let me *TYPE* a string literal for the replacement string without trying to turn it into an HTML link! Anyway, I know that my "encode" function works, but it pains me to add that "replace" call before *EVERY* invocation of the simplejson.dumps() method. The reason I upgraded to 1.7.4 was to get the c-level speedup routine now offered by simplejson -- yet the need to do this apostrophe escaping seems to negate this advantage! Is there perhaps some combination of dumps keyword arguments, python encode()/str() magic, or something similar that accomplishes this same result? What is the highest-performance way to get simplejson to emit the desired serialization of the given test string? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Thu Mar 27 11:23:47 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 27 Mar 2008 10:23:47 -0500 Subject: Checking processes running under Windows In-Reply-To: References: Message-ID: <47EBBC03.5020608@ncee.net> One way: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339 Another way: wmi # List all running processes # http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.ProcessId, process.Name # List all running notepad processes import wmi c = wmi.WMI () for process in c.Win32_Process (name="notepad.exe"): print process.ProcessId, process.Name # Create and then destroy a new notepad process import wmi c = wmi.WMI () process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe") for process in c.Win32_Process (ProcessId=process_id): print process.ProcessId, process.Name result = process.Terminate () Jo?o Rodrigues wrote: > Hello all! I'm trying to write a script that needs to check which > processes are running under Windows (XP Pro, Home, whatever). The > method I'm using is: > > >>> process_list = os.popen('TASKLIST').read() > > However, XP Home doesn't have the tasklist.exe tool so, this is kind > of useless in that OS. Do you have any other methods I can use for this? > > Thanks! -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From toby at tobiah.org Thu Mar 13 15:40:40 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 13 Mar 2008 12:40:40 -0700 Subject: Advantage of the array module over lists? Message-ID: I checked out the array module today. It claims that arrays are 'efficient'. I figured that this must mean that they are faster than lists, but this doesn't seem to be the case: ################ one.py ############## import array a = array.array('i') for x in xrange(10000000): a.append(x) for x in a: a[x] += 1 ################ two.py ############## a = [] for x in xrange(10000000): a.append(x) for x in a: a[x] += 1 ###################################### ktops:toby:pytest> time python one.py; time python two.py real 0m28.116s user 0m17.504s sys 0m10.435s real 0m23.026s user 0m13.027s sys 0m9.777s Perhaps the only advantage is that they take less memory to store a large number of items? It would seem then, that 'economical' might have been a better choice of word than 'efficient'. Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From bj_666 at gmx.net Tue Mar 25 15:49:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Mar 2008 19:49:34 GMT Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: <64t3aeF2derd7U4@mid.uni-berlin.de> On Tue, 25 Mar 2008 12:32:17 -0700, blackpawn wrote: > So what's the deal here? :) I want all objects to be freed when I > shut down and their destruction functions to be properly called. Then you want something that's not guaranteed by the language. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Sun Mar 23 20:29:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 17:29:13 -0700 (PDT) Subject: always getting 'None' return value from PyObject_CallObject References: Message-ID: <335691c7-79f0-4c7e-b19f-e9b94306d7f6@s12g2000prg.googlegroups.com> On Mar 24, 10:43 am, Gal Aviel wrote: > Hello all, > > Kinda desperate over here .. Any help would be greatly appreciated ! > > I'm trying to embed a Python interpreter inside a Verilog simulator as a > SystemVerilog DPI application. The python side implements a few SV exported > tasks. I've got a thin C shared library as the dpi app; all it does it get the > task arguments from the simulator and hand those to the Python side using the > Python C API. > > I followed '5.3 Pure Embedding' under Python 2.5 documentation very closely. > > When calling a function defined in my module, the function executes Ok - it sees > the correct arguments being passed from C, and executes 100% - only the return > value is always 'None' (I tried returning a simple integer like '5' which > doesn't work). > > Any ideas? > So you are saying that your Python functions does: return 5 [are you sure it's not falling off the end and thus implicitly returning None?] but PyObject_CallObject transmogrifies that into the Python object None -- or do you mean a C NULL pointer? It might be a good idea if you showed us the exact C code that you are using instead of this snippet from the manual: pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } including the part where you demonstrate that the returned pointer points to the None object. It might be a good idea if you showed us the minimal Python function that exhibits this behaviour with your C code ... does it happen with: def myfunc(): return 5 ? And what version of Python on what platform? From kla at us.de Wed Mar 19 06:40:10 2008 From: kla at us.de (klaus) Date: 19 Mar 2008 10:40:10 GMT Subject: a beginner, beginners question Message-ID: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Hello, I'm trying to learn python programming and so far so good. However when trying to master the oop side I ran into a small problem. I think I've done everything ok as outlined below. But I just don't understand why the `method' of `class' example isn't printing any of the variables that I have set earlier on ? Could someone please explain to me what it is I am doing wrong ? Thank you so much ! #!/usr/bin/env python class example: def __init__(self, foo, bar): self.foo = foo self.bar = bar def method(self): print "method ... :" print self.foo print self.bar if __name__ == "__main__": obj = example obj.foo = "var1" obj.bar = "var2" obj.method From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 06:09:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 12:09:59 +0100 Subject: Hi In-Reply-To: References: Message-ID: <47cfd0f5$0$6540$426a74cc@news.free.fr> hellogaurang at gmail.com a ?crit : > Hello > > can u plz tell how to send and read msg from device(telit-863-GPS) and > the coding is in python. > > if this can happen then plz send the source code to my mail account You'll find relevant code and examples here: http://catb.org/~esr/faqs/smart-questions.html#intro HTH From Grimsqueaker13 at gmail.com Thu Mar 27 03:33:21 2008 From: Grimsqueaker13 at gmail.com (Grimsqueaker) Date: Thu, 27 Mar 2008 00:33:21 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? From castironpi at gmail.com Mon Mar 3 20:10:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 17:10:24 -0800 (PST) Subject: Altering imported modules References: <200803011856.27611.troworld@gmail.com> <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> Message-ID: <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> On Mar 3, 5:09?pm, Tro wrote: > On Sunday 02 March 2008, Paul McGuire wrote: > > > > > > > On Mar 2, 3:48?pm, Tro wrote: > > > On Sunday 02 March 2008, Terry Reedy wrote: > > > > "Tro" wrote in message > > > >news:200803011856.27611.troworld at gmail.com... > > > > > | Hi, list. > > > > | > > > > | I've got a simple asyncore-based server. However, I've modified the > > > > > asyncore > > > > > | module to allow me to watch functions as well as sockets. The > > > > | modified asyncore module is in a specific location in my project and > > > > | is imported > > > > > as > > > > > | usual from my classes. > > > > | > > > > | Now I'd like to use the tlslite library, which includes an asyncore > > > > | mixin class. However, tlslite imports "asyncore", which doesn't > > > > | include my own modifications. > > > > | > > > > | I'd like to know if it's possible to make tlslite load *my* asyncore > > > > > module > > > > > | without changing any of the tlslite code. > > > > > If your module is also 'asyncore' and comes earlier in the search path, > > > > I would expect the import to get yours. > > > > It's not. It has a package prefix like my.package.asyncore. I think I can > > > either move my version of asyncore up a couple of levels or add the > > > my.package directory to sys.path. > > > > My version of asyncore imports several functions from the built-in > > > asyncore. Now that my version of it is imported as asyncore, how would it > > > import the built-in version from python2.5/site-packages? > > > > Thanks, > > > Tro > > > What happens if you do "import my.package.asyncore as asyncore"? > > > If that doesn't work (trying the simplest hack first), I know that > > there are various hooks in the import mechanism that should help. > > In the classes that use my version of asyncore currently, that is how I do it. > I import my version as "import my.package.asyncore as asyncore". In my > asyncore module I do "import asyncore", because I override a few functions > from the asyncore module included with python. However, if I were to > add "my.package" to sys.path, then I wouldn't be able to "import asyncore" > from my own asyncore module. I'd have to do some trickery with sys.path to > take the "my.package" component out, import standard asyncore, readd > the "my.package" component, so that other modules can "import asyncore" and > get my version. > > Is there a way to import the standard python asyncore module in this scenario? > > Thanks, > Tro- Hide quoted text - > > - Show quoted text - Are you trying to interfere with the default module on only your machine? Just rename it. If something in the std. lib. imports asyncore, they get yours too that way. From ed at leafe.com Thu Mar 20 13:39:15 2008 From: ed at leafe.com (Ed Leafe) Date: Thu, 20 Mar 2008 12:39:15 -0500 Subject: Pycon disappointment In-Reply-To: References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> Message-ID: <68CC88AA-DE38-490D-953B-5AD7AB8493CC@leafe.com> On Mar 20, 2008, at 11:54 AM, atom.anderson at gmail.com wrote: > Number Three: Too much code, not enough concept. > > Presenters this one's for you. I can't count the number of > presentations I attended where the presenter would click through three > slides of pycode just to show us a two or three-line snippet that > illustrated their point. Worse yet, it was often at the bottom of the > screen so no one but the front row could see it. This goes for text > two. I saw some great presentations as well, and they had limited > text on each slide. The last thing your audience wants to see is a > slide drenched in text of any kind. This is good advice: simple slides serve as organization cues, but the content should come from the speaker. The worst case (only saw this twice at this year's PyCon) is when there is a text-heavy slide that the presenter simply reads. We can all read it ourselves! Your job is to elaborate on the topic. I'd like to see two things regarding slides: first, if at all possible, set a limit on the percentage of the talk that can consist of slides. I would much rather see the presenter show actual demonstrations of what they're talking about than simply talking about it. If that's not possible, then in the session description, clearly state the % of the talk that will be slides. Perhaps there are people who like to sit in a room and watch long PowerPoint (-type) presentations, but I'm not one of them. Let's see some code! Let's see stuff working (and sometimes crashing!), and how changes affect the results. When I've presented at PyCon and other conferences, that's the part that I spend the most time on: preparing demonstrations. It's not easy to do; certainly much more difficult than creating a slide that sums up what the demo does. But it makes for a much more interesting session! -- Ed Leafe From castironpi at gmail.com Thu Mar 27 06:59:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 03:59:44 -0700 (PDT) Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <69875928-eab0-46fb-bcd0-88ac515f270e@t54g2000hsg.googlegroups.com> On Mar 26, 1:36?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson ? > escribi?: > > > HOw can we use express pointers as in C or python? > > Traceback (most recent call last): > ? ?File "", line 1, in > ? ?File "parser.py", line 123, in parse_text > ? ? ?tree = language.parse_text(text) > ? ?File "english.py", line 456, in parse_text > ? ? ?tree = self.parse_sentence(sentence) > ? ?File "english.py", line 345, in parse_sentence > ? ? ?raise ParserError, "can't parse %r" % sentence > ParserError: can't parse 'HOw can we use express pointers as in C or ? > python?' Try to coil it up. It would explain part-of-speech errors (we make all the time over here). Coil goes so bad on blip-screen. We don't think in English. Hold. I meant, decoil it. Parts near each other on inferior rings of a circle: radius broadcasts in x**-2 (a.k.a. x/2 in logs) from a pole/ attractor, for redundancy-- distance along a harmonic around the attractor. It proposes path. Digital charter. Current sea. What's square curvature? Number's a square thought. Space and time are interchangable to verbal representations. (Space is money: see? And space doesn't grow on trees. So, what do you want for walls (same destination, new tack.-- high-dimension paths? I don't get what I (I) feel is mine-- you have to stay where you think you are. Spike the drink? What do you spike it with, nominal existence? What do -we- need and get at church, life and freedom?)? Microcircuitry and microplumbing in walls and microrecycling and microtransit could save a lot of energy and be safer and cheaper. The circles here suck. Graph vertices square and accept successfully. What is the identity relation in cause? Do you just like to build and eat coils? I'd like to (affirm/bolt) a structure that gets better at it. I deceive all the senses. My spelling is awe-ful. Am I trying to do the impossible? I like to regulate everything. What should I do? What is the good life? Give it some recoil and it works for me. Raise Locked coil. Sixth- grade English-native speakers don't discern (when prompted) commutations of 'is': 'a is c', 'b is c', therefore 'a is b'. ('Is' is causally intransitive to them.) Formal logic is pretty refined, or they're distracted. Do you? From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 18:50:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Mar 2008 22:50:40 -0000 Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> Message-ID: <13u3660kfnhq412@corp.supernews.com> On Wed, 19 Mar 2008 14:45:39 -0700, Jim wrote: > Program randomly aborts when looking up url. The program loop thru > 4000+ records looking > up ID via internet and returns html code which is used in subsequent > processing. The code > for looking-up record is below followed by abort details. Can anyone > help with catching the > abort before program aborts or provide code to automatically start > program? Yes. Wrap the offending code with a try...except loop, something similar to this. try: contents = urllib2.urlopen(url).read() except URLError, e: if e.errno == 10053: # "Software caused connection abort" response = raw_input( "Temporary failure, Skip/Halt/try Again?") response = response.lower().strip() if response in ('h', 'halt'): break elif response in ('a', 'again', 't', 'try', 'try again'): continue elif response in ('', 's', 'skip'): lines -= 1 continue else: print "Unknown response, boo hiss to you!" raise -- Steven From stefan_ml at behnel.de Tue Mar 25 14:50:12 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Mar 2008 19:50:12 +0100 Subject: Beautiful Soup Looping Extraction Question In-Reply-To: References: Message-ID: <47E94964.30201@behnel.de> Hi, again, not BS related, but still a solution. Tess wrote: > Let's say I have a file that looks at file.html pasted below. > > My goal is to extract all elements where the following is true:

align="left"> and

. Using lxml: from lxml import html tree = html.parse("file.html") for el in tree.iter(): if el.tag == 'p' and el.get('align') == 'left': print el.tag elif el.tag == 'div' and el.get('align') == 'center': print el.tag I assume that BS can do something similar, though. Stefan From matthieu.brucher at gmail.com Tue Mar 25 18:25:59 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 25 Mar 2008 23:25:59 +0100 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: Hi, In most of the languages ^ is used for 'to the power of'. > No, not in most languages. In most languages (C, C++, Java, C#, Python, Fortran, ...), ^ is the xor operator ;) Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From supheakmungkol.sarin at gmail.com Thu Mar 27 23:07:35 2008 From: supheakmungkol.sarin at gmail.com (mungkol) Date: Thu, 27 Mar 2008 20:07:35 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> <47ec0cd0$0$90262$14726298@news.sunsite.dk> Message-ID: On Mar 28, 6:06 am, Damjan wrote: > mungkol wrote: > > Dear all, > > > I am a newbie to Python community. For my project, I tried to install > > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > > unsuccessful. It produced the following error: > > you need to install the "build-essential" pacakge group on Ubuntu so that > you can compile programs. > > apt-get install build-essential > > > limits.h: No such file or directory > > This is probably /usr/include/linux/limits.h part of the kernel headers. > > -- > damjan Dear all, Thank you so much. It works out when I install the "build-essential" package as suggested. I appreciate your help very much. Regards, Supheakmungkol From fakeaddress at nowhere.org Sun Mar 9 07:57:08 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 09 Mar 2008 04:57:08 -0700 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: Message-ID: Lie wrote: [...] > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. [...] > Implementation: > Simple implementation might be done by catching all exceptions at the > highest level, then filtering which exceptions would be stopped (Soft > Exception) and which exceptions will be reraised and terminate the > program (Hard Exception). This is simple and can be easily implemented > but is inefficient as that means all soft exceptions must bubble > through its way to the top to find out if it is Soft or Hard. If I'm following what you want, that "simple implementation" does not work. If a function, possibly deep in a call stack, raises a soft exception that no caller above catches, what executes next? Correct me if I'm misunderstanding your idea: You want raising an un-caught soft exception to be equivalent to a 'pass'; execution continues as if the 'raise' never happened. Catching everything at a high level does nothing like that. The exception causes execution to leave the function invoking the raise statement, and abolishes the stack state from the point of the raise to the point of the catch. As Python exceptions currently work, "catching all exceptions at the highest level" is either what Python already does, or ill-defined nonsense. When an exception is uncaught, there is no useful "highest level", other than the level at which the program simply fails. Python *must* terminate execution upon an unhanded exception, because the program defined no state from which executions could correctly continue. > A more through implementation would start from the raiser inspecting > the execution stack and finding whether there are any try block above > it, if no try block exist it pass silently and if one exist it will > check whether it have a matching except clause. This also circumvents > a problem that simple implementation have, as described below. The described problems do not include the "where should execution resume" problem, which I think is central to the issue. Correct me if I've misunderstood: A "soft" exception is one that gets raised only if some calling frame has arranged to catch it. The if-exception-would-be-unhanded-then-pass logic strikes me as interesting. It would be a huge change to Python, so I doubt it will get traction here. Still, I'd say it's worth more consideration and discussion. -- --Bryan From dickinsm at gmail.com Wed Mar 5 16:06:37 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 5 Mar 2008 13:06:37 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> On Mar 5, 3:25?pm, "Jeff.Goldfin... at gmail.com" wrote: > I can pack and unpack a float into a long > e.g. > struct.unpack('I',struct.pack('f',0.123))[0] > but then I'm not sure how to work with the resulting long. > > Any suggestions? One alternative to using struct is to use math.ldexp and math.frexp: >>> m, e = frexp(pi) >>> m 0.78539816339744828 >>> e 2 >>> int(m*2**53) 7074237752028440L Then you can do your bit twiddling on int(m*2**53), before using ldexp to 'repack' the float. Mark From fred.sells at adventistcare.org Tue Mar 11 23:29:43 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 11 Mar 2008 23:29:43 -0400 Subject: Looking for very light weight template library (not framework) In-Reply-To: <1204854964.1470.1241033951@webmail.messagingengine.com> Message-ID: <0A53725C4A497848A7B3A0874B259831011B087C@acesxch01.ADVENTISTCORP.NET> As I recall Quixote allowed you to embed html in python. was actually pretty cool. Havenot tried it in a long time. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Malcolm Greene > Sent: Thursday, March 06, 2008 8:56 PM > To: python-list at python.org > Subject: Looking for very light weight template library (not > framework) > > > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In > other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated. > > Malcolm > -- > http://mail.python.org/mailman/listinfo/python-list > From aahz at pythoncraft.com Sun Mar 23 12:24:35 2008 From: aahz at pythoncraft.com (Aahz) Date: 23 Mar 2008 09:24:35 -0700 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: In article , Jeff Schwab wrote: > >Also, despite reassurances to the contrary, I still get the impression >that there is a strong anti-lambda sentiment among the Python "in" >crowd. Is it just a question of the word "lambda," as opposed to >perceived cleaner syntax? The problem with lambda is that too often it results in clutter (this is a strictly made-up example off the top of my head for illustrative purposes rather than any real code, but I've seen plenty of code similar at various times): gui.create_window(origin=(123,456), background=gui.WHITE, foreground=gui.BLACK, callback=lambda x: x*2) That means I need to pause reading the create_window() arguments while I figure out what the lambda means -- and often the lambda is more complicated than that. Moreover, because the lambda is unnamed, it's missing a reading cue for its purpose. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From nytrokiss at gmail.com Sun Mar 2 11:06:30 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 2 Mar 2008 17:06:30 +0100 Subject: Book Recomendations In-Reply-To: References: Message-ID: <8a6b8e350803020806g2f6d44evdbd23917a743b1eb@mail.gmail.com> I liked Core Python Programming 2nd edition! On Sun, Mar 2, 2008 at 4:27 PM, Ken Dere wrote: > Ira Solomon wrote: > > > I am an experienced programmer (40 years). I've done Algol (if you've > > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > > few other odd languages (e.g. Taskmate). > > I'm interested in learning Python and have downloaded a slew of books. > > Too many. > > I'd like a recommendation as to which books are considered to be the > > cream of the crop. > > I know there are tutorials on the web, but, again, I don't know the > > quality. I would appreciate recommendations on those as well. > > > > Thanks > > > > Ira > > I started off with Fortran 6X so I have been in the business about as > long. > Do just about everything now in Python. > > I liked Learning Python > > > Ken D. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Mar 18 18:09:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Mar 2008 23:09:57 +0100 Subject: method to create class property In-Reply-To: <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> Message-ID: <64astpF29u3k1U1@mid.uni-berlin.de> Joe P. Cool schrieb: > On 18 Mrz., 21:59, "Diez B. Roggisch" wrote: >> Joe P. Cool schrieb: >>> def _property_y(self): >>> def _get(self): >>> [...] >> There are a few recipies, like this: >> >> class Foo(object): >> >> @apply >> def foo(): >> def fget(self): >> return self._foo >> def fset(self, value): >> self._foo = value >> return property(**locals()) > > This is really cool! Thanks, Diez! I should definitely > learn to handle decorators :) But isnt't apply bound to > be dropped in Python 3.0? In python 3.0, there will be an even nicer way - propset: @property def foo(self): return self._foo @propset def foo(self, value): self._value = value Diez From roger.dahlstrom at gmail.com Mon Mar 31 10:22:04 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 31 Mar 2008 07:22:04 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll Message-ID: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> So I have a 64 bit Windows 2003 system, running python 2.5.1.1. I can import a Windows .dll (msvcrt or whatever) using ctypes, but when attempting to import another application-specific .dll (tibrv.dll if anyone is familiar with it), I receive the error WindowsError: [Error 193] %1 is not a valid Win32 application. I know there's a Windows on Windows (wow) which allows 32 bit processes to run on 64 bit windows - is there a way to work this in somehow? Maybe I'm barking up the wrong tree? Code is simple, and works on 32 bit systems no from ctypes import * #this doesn't work tibrv = cdll.tibrv #this does work msvcrt = cdll.msvcrt From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:35:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:35:16 -0300 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 16:29:23 -0300, escribi?: > I'm making a game where you'll be able to make your own mods and I > want to be able to write these mods in python. However, python has a > lot of "dangerous" functions (like erase any file on the harddrive > etc) so I want a "safe" python. I first found RExec but that is > disabled in python 2.5 so I was thinking about building python from > source with a few changes. > The changes I was thinking about was to change the import function so > that it should only be able to import the .pyd-files that I allow (and > it should of course still be able to import any .py-file) and remove > or change the builtin functions that are "dangerous". > Is this enough to make a "safe" python that can't do anything > "dangerous"? No, and that's the reason for rexec/bastion removal. There are several ways to circumvent it. By example, if the user can get access to a file object, he can open any other file using type(f)("anyotherfile"). If he can get an object defined in your code: py> type(x).some_method.func_globals['__builtins__'].__import__ and then import anything. I think that a highly reputed Python developer made some time ago a really safe version and nobody could spot any holes, but I can't find the reference. > I'm going to embed this "safe" python into my game and I've discovered > that when I embed the original python and the mod wants to import > a .py-file that is not in the game directory it will search for > the .py-file in the python directory that is installed on my computer. > Can I somehow prevent the embedded python to look in the python > directory? Python looks along sys.path for importing things. Sorry but if you don't know that you shouldn't try to build a safe Python version on your own - at least you should have a lot of doubts that it is actually safe. -- Gabriel Genellina From noreply at noreply.org Wed Mar 19 06:50:17 2008 From: noreply at noreply.org (some one) Date: Wed, 19 Mar 2008 04:50:17 -0600 Subject: Script Request... Message-ID: Hi all, I am not to familiar with python yet and I am wondering if someone can write a script that will monitor my DSL modems IP address and notify when it changes, its a 2Wire Advanced DSL Modem. I need to know when it changes because I am trying to run my own inhouse server and have to update my domain records through verio.com. The script would need to read the text of a web page( on my modem the address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and search for a string containing the IP address. Can anyone help? thanks, I'll keep monitoring this thread. From ivan.illarionov at gmail.com Mon Mar 17 21:53:11 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 17 Mar 2008 18:53:11 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: Message-ID: On Mar 18, 4:36 am, dave wrote: > Hi All. I've been formulating in my head a simple image editor. I > actually started prototyping is some time ago in Java, but am liking > Python more and more. My editor will be nowhere near the level of Gimp/ > Photoshop, but I do need fast pixel level control and display. For > instance, that means no automatic anti-aliasing and that I will be > implementing my own line drawing algorithms. > > I've got the high level architectual aspects of my program down, but > am stuck on what graphics API to use. I want a canvas area of > adjustable size which users can draw on with as little lag as > possible. The canvas area will be composed of layers (i.e. I require > an alpha channel) and I need to be able to zoom in and out of it (zoom > levels will be at fixed intervals, so this can be simulated if need > be.) > > I started looking at PyGame but realize that I need to integrate a GUI > into the whole thing (or integrate the image into the GUI rather) and > I didn't see a straightforward way to do that. Of course, I don't even > know if PyGame is the right API for the job anyways :P > > Any thoughts or ideas that could help me get started? Thanks! Look at the PIL source code for reference and implement your own C extensions for drawing and image manipulation. Or write your app on top of PIL. Any GUI toolkit will work if you find the low-level access to their image memory buffers. PyGame is for multimedia applications, you probably need Tkinter, Qt, wx or GTK. And as long as you need such low-level things as custom drawing and anti-aliasing your API is plain old C malloc's, free's and raw memory addresses. -- Ivan From noname9968 at gmail.com Thu Mar 27 08:11:49 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 15:11:49 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> <47EB7F55.8090909@gmail.com> Message-ID: <47EB8F05.8090505@gmail.com> Guilherme Polo wrote: > 2008/3/27, Alex9968 : > >> Guilherme Polo wrote: >> > 2008/3/27, Alex9968 : >> > >> >> Guilherme Polo wrote: >> >> > 2008/3/26, Alex9968 : >> >> > >> >> >> Hi all, >> >> >> >> >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> >> >> using visual GUI designers), so my question is which other GUI toolkits >> >> >> have similar functionality. >> >> >> >> >> > >> >> > The geometry manager isn't related to using GUI designers tools at >> >> > all. And each toolkit has it's own way to do the things, wxPython uses >> >> > sizers, PyGtk uses containers. >> >> > >> >> >> >> Well, the geometry manager isn't *directly* related to using GUI >> >> designers, but as Pack arranges widgets automatically, using GUI >> >> designers isn't required, while with geometry managers that don't, GUI >> >> designers are necessary (if you start placing widgets programmatically, >> >> you'll end up reinventing something like Tkinter's Pack or Grid geometry >> >> manager). I hope I can be understood clearly this time ;-) >> >> >> > >> > Not at all, can't understand your point yet. GUI designers aren't just >> > for placing widgets, they also will keep the interface design >> > separated from your code. >> > >> >> I do not want to separate interface from code and I do not experience >> the need to use GUI designers. >> >> > > It is your opinion, it seems I can't change it for now but I hope you > reconsider it for the future. > > >> Pack arranges widgets perfectly, and it's very complex to do the same >> without it, both in code and in GUI designer. >> > > For some level of "perfect", of course. > Also, I can't understand why you say it is hard to do such thing in a > gui designer tool, which tool have you tried ? Maybe you are not > familiar with them yet, and that could be the problem. > Can you explain why my opinion is to be reconsidered? In GUI designer it's easy to produce initial (still) layout, but what if it should be changed at runtime (for example, widgets added or removed), and still be ideally arranged? I know that widgets might have some parameters affecting for example how they move when their container is resized, and that might help when updating interface, but I think it's inconvenient that they're hidden inside their property sheets (and therefore invisible while designing). I should answer the question - I used Visual C# from Microsoft Visual Studio .NET 2003, and after moving to Python I did not use any GUI designer. From carsten at uniqsys.com Sat Mar 15 15:12:05 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 15 Mar 2008 20:12:05 +0100 Subject: Unicode/UTF-8 confusion In-Reply-To: <1205607791.3224.4.camel@localhost.localdomain> References: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> <1205607791.3224.4.camel@localhost.localdomain> Message-ID: <1205608325.3224.9.camel@localhost.localdomain> On Sat, 2008-03-15 at 20:03 +0100, Carsten Haese wrote: > On Sat, 2008-03-15 at 12:09 -0400, Tom Stambaugh wrote: > > [...] > > I use simplejson to serialize html strings that the server is delivering to > > a browser. Since the apostrophe is a string terminator in javascript, I need > > to escape any apostrophe embedded in the html. > > [...] > > simplejson escapes them for you: > > >>> import simplejson > >>> s = " ' " > >>> simplejson.dumps(s) > '" \' "' > > Why is this not good enough for your needs? And before somebody else corrects my use of the word "escaping", simplejson doesn't actually escape the apostrophe. The backslash is, of course, python's repr() escaping the apostrophe. simplejson simply handles the apostrophe by enclosing it in quotation marks. The result should still be good enough, though. -- Carsten Haese http://informixdb.sourceforge.net From aaron.watters at gmail.com Wed Mar 19 09:38:19 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 19 Mar 2008 06:38:19 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <8ee4ae2d-10af-41cd-a405-0fbdf73ce9d9@a70g2000hsh.googlegroups.com> On Mar 18, 12:55 pm, perrygreenfi... at gmail.com wrote: > Amen on the diamond keynotes and lightning talks. The lightning talks > were a great disappointment. Sponsor talks (or any such talks pitched > at selling or recruiting) should go in their own, clearly labeled > group so those of us who don't care about them can avoid them... Seconded. I haven't been at a Python Conf for a long time but as a former attendee and (not very good) organizer I have a couple suggestions based on my past experience and mistakes: - The conference is too long and it shouldn't be on the weekend. - Almost all talks should be 10 minutes at most with prepared slides and extended abstract with references. - With much shorter talks you should be able to accept just about any properly prepared talk (with abstract and slides) and this should reduce the politics and increase the attendance (with speakers and some colleagues and maybe broader interest). I don't know about this conference, but in past conferences I've been frustrated by people who give out a train of conscience meander including popping in and out of various console prompts, editors, web pages, guis... without conveying any useful information (to me) in 30 minutes. If you tell them they have 10 minutes and make them get organized in advanced they are much more likely to get to the point and everyone can see something else before they run out of attention span. -- Aaron Watters === bye bye petroleum! good riddance. http://biofuels.usu.edu/htm/initiative http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=pretty+boring From gggg.iiiii at gmail.com Mon Mar 3 18:56:22 2008 From: gggg.iiiii at gmail.com (G) Date: Mon, 3 Mar 2008 18:56:22 -0500 Subject: os.system with cgi Message-ID: <4a7f84ac0803031556p721d9a74h2cd7051bf6bc5b7e@mail.gmail.com> Hi, I have the following peace of code def getBook(textid, path): url = geturl(textid) if os.path.isfile(path + textid): f = open(path + textid) else: os.system('wget -c ' + url + ' -O ' path + textid) f = open(path + textid) return f The reason I am not using urllib is that I want to have random access within the downloaded file. When i execute the file from a regular python script I get the file downloaded and a handle for the file returned. When I execute the file from a python cgi script i get an error saying that the file doesn't exist. In other words the call to os.system is not running. Could someone please point out what the problem with that peace of code running as a cgi script. Best. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfbolz at gmx.de Sun Mar 30 14:47:52 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 30 Mar 2008 20:47:52 +0200 Subject: ANN: Py-Lib 0.9.1 released Message-ID: py lib 0.9.1: bugfix release ============================= The py lib team has just released version 0.9.1 of the py lib - a library aiming to support agile and test-driven python development on various levels. This is mostly a bugfix release, with a couple of new features sneaked in. Most important changes: * reduced the number of threads used in py.execnet * some new functionality (authentication, export, locking) in py.path's Subversion APIs * stability and segfault fixes in execnet * numerous small fixes in py.test's rsession (experimental pluggable session) and generative test features * some fixes in the py.test core * added py.misc.killproc, which allows killing processes on (some flavours of) Windows and UNIX For a complete list of changes, see doc/changes-0.9.1.txt in the source package. Download/Install: http://codespeak.net/py/0.9.1/download.html Documentation/API: http://codespeak.net/py/0.9.1/index.html Work on the py lib has been partially funded by the European Union IST programme and by http://merlinux.de within the PyPy project. best, have fun and let us know what you think! holger krekel, Maciej Fijalkowski, Carl Friedrich Bolz, Guido Wesdorp From simon at brunningonline.net Tue Mar 11 09:21:23 2008 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 11 Mar 2008 13:21:23 +0000 Subject: Check For SELF Variable Existance In-Reply-To: <-8215347293566648508@unknownmsgid> References: <-8215347293566648508@unknownmsgid> Message-ID: <8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> On Tue, Mar 11, 2008 at 11:00 AM, Robert Rawlins wrote: > I want to be able to check if a class has a certain property in its 'self' > scope, what's the best way to do this? >>> class Spam(object): ... def egg(self): ... if hasattr(self, 'chips'): print 'got chips!' ... >>> spam = Spam() >>> spam.egg() >>> spam.chips = 'beans' >>> spam.egg() got chips! -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 19:07:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 00:07:00 -0000 Subject: Why """, not '''? References: <13su5tn6rpjb345@corp.supernews.com> Message-ID: <13sudd49au3e1c1@corp.supernews.com> On Wed, 05 Mar 2008 23:27:21 +0000, Matthew Woodcraft wrote: > Steven D'Aprano wrote: >>On Wed, 05 Mar 2008 19:19:08 +0000, Matthew Woodcraft wrote: >>> One advantage is that a dumb syntax highlighter is more likely to cope >>> well if the content includes an apostrophe. > >> But if the content contains double-quote marks, the "dumb syntax >> highligher" is more likely to cope well if you use '''. > > That's right. But apostrophes are rather more common than quote marks in > English text. Surely it would depend on the type of text: pick up any random English novel containing dialogue, and you're likely to find a couple of dozen pairs of quotation marks per page, against a few apostrophes. -- Steven From mauriceling at acm.org Sat Mar 29 08:11:48 2008 From: mauriceling at acm.org (Maurice LING) Date: Sat, 29 Mar 2008 12:11:48 GMT Subject: Re; finding euclidean distance,better code? In-Reply-To: References: Message-ID: <47ee31f7$1@news.unimelb.edu.au> Hendrik van Rooyen wrote: > On Saturday 29 March 2008 03:09:46 Steven D'Aprano wrote: >> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: >>> Gabriel Genellina wrote: >>>> That's what I said in another paragraph. "sum of coordinates" is using >>>> a different distance definition; it's the way you measure distance in a >>>> city with square blocks. I don't know if the distance itself has a >>>> name, but >>> I think it is called Manhattan distance in reference of the walking >>> distance from one point to another in this city. >> You know, there are other cities than Manhattan. Some of them even have >> streets and blocks. > > Sorry about having to dispel your illusions, but - > > In Printed Circuit Board Layout jargon, the 'manhattan distance' is > the sum of the distances along the orthogonal axes between > two points on the board that should be connected. > > The sum of all such distances is an idealised minimum for the > total track length on a double sided board, given that it were > possible to lay all tracks with segments connected by vias, > making strictly increasing progress in the desired direction, > by laying x direction tracks on the one, and y direction tracks > on the other side of the board without having to "backtrack" > - i.e. having to "dodge around" obstacles, thereby adding > "overshooting" segments of track. > > (A via is a through plated hole that connects copper traces or > tracks on opposite sides of the board) > > So I have met the beast, but I have no concept of its origin, > other than the mind numbing regularity of the layout of the > suburb of the city after which it seems to be named - > For all I know 'manhatten' could be a native american word that > means "net". > > Have you noticed that when people say "Sorry.....but...." they are > not normally sorry at all? > > :-) > > - Hendrik > Manhatten distance is also known as "taxicab distance" or "city block distance" - the average distance of getting from point A to point B in a city with roads laid out as grids. maurice From half.italian at gmail.com Tue Mar 18 18:27:27 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 18 Mar 2008 15:27:27 -0700 (PDT) Subject: os.path.getsize() on Windows References: Message-ID: <6abeaadf-0055-4216-9aed-ad87bc006038@h11g2000prf.googlegroups.com> On Mar 18, 2:27?pm, Duncan Booth wrote: > Sean DiZazzo wrote: > > On windows, this returns the size of the file as it _will be_, not the > > size that it currently is. ?Is this a feature? ?What is the proper way > > to get the current size of the file? ?I noticed > > win32File.GetFileSize() ?Does that behave the way I expect? > > > PS. ?I also tried os.stat()[6] > > I think all of those will return the current size of the file, but that may > be the same as the final size: just because the data hasn't been copied > doesn't mean the file space hasn't been allocated. You don't say how you > are copying the file, but I seem to remember that Windows copy command pre- > allocates the file at its final size (so as to reduce fragmentation) and > then just copies the data after that. > > If you need to make sure you don't access a file until the copy has > finished then get hwatever is doing the copy to copy it to a temporary > filename in the same folder and rename it when complete. Then you just have > to check for existence of the target file. Hmmm... The file could be copied in by several different sources of which I have no control. I can't use your technique in my situation. I also tried getting md5 hashes with some time in between on advice, but the file is not opened for reading until the copy completes so I can't get the hashes. Any other ideas? From cappallo at gmail.com Sun Mar 2 11:52:27 2008 From: cappallo at gmail.com (TC) Date: Sun, 2 Mar 2008 08:52:27 -0800 (PST) Subject: Question on importing and function defs References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> Message-ID: <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> On Mar 2, 11:37 am, Gary Herron wrote: > TC wrote: > > I have a problem. Here's a simplified version of what I'm doing: > > > I have functions a() and b() in a module called 'mod'. b() calls a(). > > > So now, I have this program: > > > from mod import * > > > def a(): > > blahblah > > > b() > > > The problem being, b() is calling the a() that's in mod, not the new > > a() that I want to replace it. (Both a()'s have identical function > > headers, in case that matters.) How can I fix this? > > > Thanks for any help. > > Since b calls mod.a, you could replace mod.a with your new a. Like > this: (Warning, this could be considered bad style because it will > confuse anyone who examines the mod module in an attempt to understand > you code.) > > import mod > > def replacement_a(): > ... > > mod.a = replacement_a > > ... > > Or another option. Define b to take, as a parameter, the "a" function > to call. > > In mod: > > def a(): > ... > > def b(fn=a): # to set the default a to call > ... > > And you main program: > > from mod import * > > def my_a(): > ... > > b(my_a) > > Hope that helps > > Gary Herron Thanks for the tips, but no luck. This is for a homework assignment, so there are a couple of requirements, namely that I can't touch 'mod', and I have to do 'from mod import *' as opposed to 'import mod'. So the first method you suggested won't work as written, since the mod namespace doesn't exist. I tried a = replacement_a, but b() is still calling mod's version of a() for some reason. And because I can't touch mod, I can't use your second suggestion. In case I somehow oversimplified, here's the actual relevant code, in 'mod' (actually called 'search'). The first fn is what I've been calling a(), the second is b(). (lots of stuff...) def compare_searchers(problems, header, searchers=[breadth_first_tree_search, breadth_first_graph_search, depth_first_graph_search, iterative_deepening_search, depth_limited_search, astar_search]): def do(searcher, problem): p = InstrumentedProblem(problem) searcher(p) return p table = [[name(s)] + [do(s, p) for p in problems] for s in searchers] print_table(table, header) def compare_graph_searchers(): compare_searchers(problems=[GraphProblem('A', 'B', romania), GraphProblem('O', 'N', romania), GraphProblem('Q', 'WA', australia)], header=['Searcher', 'Romania(A,B)', 'Romania(O, N)', 'Australia']) That's the end of the 'search' file. And here's my program, which defines an identical compare_searchers() with an added print statement. That statement isn't showing up. from search import * def compare_searchers(problems, header, searchers=[breadth_first_tree_search, breadth_first_graph_search, depth_first_graph_search, iterative_deepening_search, depth_limited_search, astar_search, best_first_graph_search]): def do(searcher, problem): p = InstrumentedProblem(problem) searcher(p) return p table = [[name(s)] + [do(s, p) for p in problems] for s in searchers] print 'test' print_table(table, header) compare_graph_searchers() From duncan.booth at invalid.invalid Mon Mar 31 05:32:37 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 09:32:37 GMT Subject: Problem with method overriding from base class References: Message-ID: wrote: > Factory: > ********************************************************************** * > **************** def factory(type, *p): > if type == common.databaseEntryTypes[0]: > return module1.Class1(*p); > elif type == common.databaseEntryTypes[1]: > return module2.Class2(*p); > elif type == common.databaseEntryTypes[2]: > return module3.Class3(*p); > elif type == common.databaseEntryTypes[3]: > return module4.Class4(*p); > ********************************************************************** * Have you considered using a dictionary mapping name to class, or even just storing the classes directly in common.databaseEntryTypes. That way your code would get a lot smaller and less messy: e.g. in common.py: databaseEntryTypes = [ module1.Class1, module2.Class2, module3.Class3, module4.Class4 ] and then factory becomes: def factory(type, *p): return type(*p) after which you can remove factory altogether. Or if you keep the name -> type mapping then at least factory becomes maintainable. > > Implementing Class1: > ********************************************************************** * > **************** import editInterface > > class Class1(editInterface.EditInterface): > > def __init__(self, product, database): > # do something here ... > > def showEntry(self, entry, statustext): > # do something here as well, return some string... > ********************************************************************** * > **************** > > Now, when I want to create an Instance of Class1 I do: > > myClass1Instance = factory.factory(common.databaseEntryTypes[1], > 'Name', databaseObj ) > > Which seems to work fine according to the debugger. But when I do > next: > > msg = myClass1Instance.show(firstEntry, '') > > Then the show() method of the class 'EditInterface' is called instead > of the show() method of the class 'Class1' !! Does anyone have an idea > why the method of the base class is called instead of the method of > the derived class and how can I do it, so that the show() of Class1 is > called instead? In the code you posted Class1 doesn't have a show() method, it has a showEntry() method so calling show() will call the base class as the only implementation it has. From george.sakkis at gmail.com Mon Mar 24 15:13:59 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Mar 2008 12:13:59 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> Message-ID: On Mar 24, 3:03 pm, pythonnubie wrote: > On Mar 24, 11:57 am, Jeff wrote: > > > What does the code look like? > > # Random Access > # Demonstrates string indexing > # Michael Dawson - 1/27/03 > > import random > > word = "index" > print "The word is: ", word, "\n" > > high = len(word) > low = -len(word) > for i in range(10): > position = random.randrange(low, high) > print "word[", position, "]\t", word[position] > > raw_input("\n\nPress the enter key to exit.") > > The code is an exerp from a chm file . I am petty sutre I am > nmot getting a char map error from the copy/paste ! it looks > simple enough ! It works fine on on Windows with standard Python 2.5. Something is probably wrong with your ActiveState installation. George From samuel.progin at gmail.com Mon Mar 10 12:06:53 2008 From: samuel.progin at gmail.com (Sam) Date: Mon, 10 Mar 2008 09:06:53 -0700 (PDT) Subject: defining a method that could be used as instance or static method References: <63l454F275mskU1@mid.uni-berlin.de> Message-ID: <328a8554-42eb-4f59-9e4a-c573353ae495@2g2000hsn.googlegroups.com> > Did you try that it doesn't work? because it should. Whenever you do > No... -_- I kept on trying things @staticmethod. Thanks for your hint, it works fine! Sam From lists at cheimes.de Fri Mar 21 13:36:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 21 Mar 2008 18:36:52 +0100 Subject: Improving datetime In-Reply-To: <47E3C1A3.6050608@ncf.ca> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <47E3C1A3.6050608@ncf.ca> Message-ID: <47E3F234.9010607@cheimes.de> Colin J. Williams schrieb: > You might consider adding the Julian date > (http://en.wikipedia.org/wiki/Julian_date). > > I had a crack at this a while ago but didn't seem to get quire the right > result, using the ACM algorithm. I seemed to be a day out at the BC/AD > divide. Yes, the Julian date family is very useful when dealing with dates before 1900. I'm +1 for adding JDT and MJD. TAI64 is another time format used for high precision and real time measurement. http://cr.yp.to/libtai/tai64.html Christian From gagsl-py2 at yahoo.com.ar Wed Mar 19 18:32:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 19:32:13 -0300 Subject: printing dictionary and tuple References: Message-ID: En Wed, 19 Mar 2008 08:16:52 -0300, Beema shafreen escribi?: > i am trying to print the dictionary values and tuple in a same line as > below > > print "\t".join(dict[a].values())+'\t'+"\t".join(b) > > Error I get is the TypeError, > since i have misisng values in the dictionary. if i use exception i > will > miss those > how should i print the data without missing the lines excluding the error > separated by tab. What is a? What is b? Their contents? I *guess* this is what you want: a = {'some': 'values', 3.14: 'in a', 1234: 'dictionary'} b = ('99', 'bottles', 'of', 'beer') print '\t'.join(a.values()) + '\t' + '\t'.join(b) The code above only works if all values are strings - else you could get a TypeError. In that case, convert all items to string before joining: a = {'some': 'values', 'in a': 3.14, 'dictionary': 1234} b = (99, 'bottles', 'of', 'beer') print ('\t'.join([str(value) for value in a.values()]) + '\t' + '\t'.join([str(item) for item in b])) If this is not your problem, please provide a complete example next time, and the full exception traceback is very important too. -- Gabriel Genellina From Jeff.Goldfinkle at gmail.com Wed Mar 5 15:51:11 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Wed, 5 Mar 2008 12:51:11 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <13su15t266dimc2@corp.supernews.com> <13su1pl8tnq5o6a@corp.supernews.com> Message-ID: <6fa9d736-1769-4e79-a276-f071a83ebce9@e60g2000hsh.googlegroups.com> On Mar 5, 10:48 pm, Grant Edwards wrote: > On 2008-03-05, Grant Edwards wrote: > > > On 2008-03-05, Jeff.Goldfin... at gmail.com wrote: > >> Any suggestions? > > > Just use the bitwise and/or/not operators: & | ~ > > Oh, I forgot to mention the shift operators << and >> > > -- > Grant Edwards grante Yow! All of life is a blur > at of Republicans and meat! > visi.com thanks for the reply but I'm still unsure as to how to continue. Using the bitwise operators will help me deal with integers but I really want to work with floats. For instance - which bits do I twiddle to round my float to the nearest number of bits? Jeff From miki.tebeka at gmail.com Thu Mar 27 17:13:16 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 14:13:16 -0700 (PDT) Subject: Tips Re Pattern Matching / REGEX References: <7ebb329d-12e0-42d8-a543-15521d1ecc46@u10g2000prn.googlegroups.com> Message-ID: Hello, > I have a large text file (1GB or so) with structure similar to the > html example below. > > I have to extract content (text between div and tr tags) from this > file and put it into a spreadsheet or a database - given my limited > python knowledge I was going to try to do this with regex pattern > matching. > > Would someone be able to provide pointers regarding how do I approach > this? Any code samples would be greatly appreciated. The ultimate tool for handling HTML is http://www.crummy.com/software/BeautifulSoup/ where you can do stuff like: soup = BeautifulSoup(html) for div in soup("div", {"class" : "special"}): ... Not sure how fast it is though. There is also the htmllib module that comes with python, it might do the work as well and maybe a bit faster. If the file is valid HTML and you need some speed, have a look at xml.sax. HTH, -- Miki http://pythonwise.blogspot.com From nagle at animats.com Tue Mar 25 20:54:54 2008 From: nagle at animats.com (John Nagle) Date: Tue, 25 Mar 2008 17:54:54 -0700 Subject: dynamically created names / simple problem In-Reply-To: References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: <47e99c9b$0$36374$742ec2ed@news.sonic.net> Robert Bossy wrote: > Jules Stevenson wrote: >> >> Hello all, >> >> I'm fairly green to python and programming, so please go gently. The >> following code >> >> for display in secondary: >> >> self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, >> "checkbox_2") >> >> Errors, because of the apparent nastyness at the beginning. What I?m >> trying to do is loop through a list and create uniquely named wx >> widgets based on the list values. Obviously the above doesn?t work, >> and is probably naughty ? what?s a good approach for achieving this? >> > Hi, > > What you're looking for is the builtin function setattr: > http://docs.python.org/lib/built-in-funcs.html#l2h-66 Actually, you don't need to use attributes for this at all. You're better off with an ordinary dictionary. Something like this: class someclass(object) : def __init__(self) : self.widgets = {} # empty dictionary def addwidget(self, widgetname, widgetfn) self.widgets[widgetname] = widgetfn def callwidgetbyname(self, widgetname, args) self.widgets[widgetname](*args) The only reason to use attributes is when you want to allow the use of the notation objectinstance.attributename If you're only going to get the attributes with getattr, they don't need to be attributes. John Nagle From arnodel at googlemail.com Tue Mar 18 18:12:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 15:12:16 -0700 (PDT) Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: <9bdc6a9e-08de-459b-ab10-74823f4dda51@s19g2000prg.googlegroups.com> Jeff Schwab wrote: > I need to move a directory tree (~9GB) from one machine to another on > the same LAN. What's the best (briefest and most portable) way to do > this in Python? > > I see that urllib has some support for getting files by FTP, but that it > has some trouble distinguishing files from directories. > > http://docs.python.org/lib/module-urllib.html > > "The code handling the FTP protocol cannot differentiate > between a file and a directory." > > I tried it anyway, but got an authentication problem. I don't see a > "how to log into the FTP server" section on docs.python.org. Is there a > tutorial I should read? > > I am particularly looking for a quick, "good enough" solution that I can > use this afternoon. Thanks in advance to any kind-hearted soul who > chooses to help me out. Have you tried ftplib? (http://docs.python.org/lib/module-ftplib.html) Here is an example of how to use it to differentiate between files and directories (untested). conn = ftplib.FTP('host', 'user', 'password') def callback(line): name = line.rpartition(' ')[-1] # assumes no whitespace in filenames if line[0] == 'd': #filename is a directory print 'directory', name else: print 'file', name #This will print all files in cwd prefixed by 'directory' or 'file' #You can change callback to retrieve files and explore #directories recursively conn.dir(callback) HTH -- Arnaud From gagsl-py2 at yahoo.com.ar Wed Mar 19 15:43:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 16:43:05 -0300 Subject: How to solve a three-element equation set? References: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> Message-ID: En Wed, 19 Mar 2008 04:05:50 -0300, purple escribi?: > Could you guys do me a favor for solving a equation set? > > Z=d/4*(1-SIN(X)/X) > X=8q/(D^2*Y)+SIN(X) > Y=1/n*Z^(2/3)*i^(1/2) > > In this equation set, X,Y&Z are the unkown parameters, the others say, > d, q, n&i are known. SO in python, how to program it to represent X, Y > and Z in the form of d, q, n and i? You want a numeric result, I presume. SciPy www.scipy.org has several minimization functions. -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 6 12:47:11 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 6 Mar 2008 11:47:11 -0600 Subject: Please keep the full address In-Reply-To: <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> Message-ID: I normally find this kind of back & forth useless and annoying spam but the irony is too much to avoid commenting. (read the following, then ...) > > > > "His" posts? > > > > Whatever. I'm too old to worry about searching for politically correct, > > gender neutral pronouns. > > > I'm pretty sure even the most PC people wouldn't suggest using a > masculine pronoun for an inanimate objects. > > > (Ok, some probably would.) > > Carl Banks Mr Banks. Technically, the sentence should be "...pronoun for inanimate objects" .. OR "...pronoun for an inanimate object." If you're going to nitpick, then at least do it right. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff.fw at gmail.com Mon Mar 17 16:39:10 2008 From: jeff.fw at gmail.com (Jeff) Date: Mon, 17 Mar 2008 13:39:10 -0700 (PDT) Subject: Sharing code between server, client, and web Message-ID: Hello everyone. This is a basic question of structure--something that it's rather difficult to search for. So, here's what there will be once this project is finished: 1) A server using Twisted and SQLAlchemy 2) A desktop client connecting to that server (with Twisted), using wxPython 3) A web interface using Pylons and SQLAlchemy The web interface and desktop app will be accessing the same data, but with different privileges and features. Twisted will be used to shuttle objects back and forth (using Perspective Broker). So, what I would really like to do is this: 1) Define the SQLAlchemy tables and models only once, and share that between the server and Pylons 2) Define methods on the models that can be used from the web interface and desktop app--meaning the models need to be shared (to some extent) with the client. Nothing is written yet, but I already have code from a current project to make SQLAlchemy and Twisted's Perspective Broker play nicely together (that was an interesting exercise). What I'm not sure about, though, is the best way to share some of the code all around. I've thought of two possible ways, but I don't particularly like either: 1) Make the entire directory structure a package, so I can use relative imports. This has the drawback that I'd need to package most or all of the server code in with the client, which I really don't want to do. 2) Have a separate lib directory that's symlinked into each place that it's needed. Does anyone see any major drawbacks to this one? It just rubs me the wrong way... So, thanks for your help in advance, and if you need any more information, please don't hesitate to ask. Thanks, Jeff From python.list at tim.thechases.com Tue Mar 25 12:03:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Mar 2008 11:03:56 -0500 Subject: any good g.a.'s? In-Reply-To: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> References: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Message-ID: <47E9226C.7040309@tim.thechases.com> > Any good genetic algorithms involving you-split, i-pick? I've always heard it as "you divide, I decide"... That said, I'm not sure how that applies in a GA world. It's been a while since I've done any coding with GAs, but I don't recall any facets related to the You Divide, I Decide problem. It sounds like a simple optimization of "equality", which would be a normal use of a GA. This would apply for both the division and the decision, depending on which side the GA is (the "you" or the "I") or two diff. GAs can be on either side of the process. -tkc From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 00:29:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Mar 2008 04:29:50 -0000 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> Message-ID: <13ubn5ue821ak7e@corp.supernews.com> On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > On 22 Mar, 23:42, 7stud wrote: > >> Beginning programmers in grades 9-12 are not going to understand issues >> like that, and it would be a mistake to try and introduce them. >> Beginning programmers should be concentrating their efforts on learning >> the syntax of a language and basic constructs like for-loops and if >> statements. > > Yes. And because Python is a "scripting language" Python is a programming language. It can be used for scripting, but that's not all it can do. Describing it as a "scripting language" is like describing a fully-equipped professional kitchen as "a left-over warming room". -- Steven From marko at pacujo.net Thu Mar 13 07:45:33 2008 From: marko at pacujo.net (Marko Rauhamaa) Date: 13 Mar 2008 13:45:33 +0200 Subject: subprocess.Popen pipeline bug? Message-ID: This tiny program hangs: ======================================================================== #!/usr/bin/env python import subprocess a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, stdout = subprocess.PIPE) b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) a.stdin.close() b.wait() # hangs a.wait() # never reached ======================================================================== It shouldn't, should it? Environment: ======================================================================== Python 2.5.1 (r251:54863, Jun 20 2007, 12:14:09) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 ======================================================================== Marko -- Marko Rauhamaa mailto:marko at pacujo.net http://pacujo.net/marko/ From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 20:03:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 00:03:23 -0000 Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: <13tgrqb132if842@corp.supernews.com> On Wed, 12 Mar 2008 11:19:05 -0700, Alex wrote: > Hi all, > > The subject says pretty much all Only to people who know what the Perl BEGIN{} block means. -- Steven From 018worker at gmail.com Thu Mar 6 05:23:43 2008 From: 018worker at gmail.com (018worker at gmail.com) Date: Thu, 6 Mar 2008 02:23:43 -0800 (PST) Subject: Worldwide computer based Home Workers Needed. Message-ID: <26c58520-d5fd-401f-88cb-9e46c37eaf46@q78g2000hsh.googlegroups.com> Worldwide computer based Home Workers Needed. Earn by doing simple Computer Jobs. No Selling Required. No Going out of Home. No Office. No Boss Not a 9 to 5 job. No experience required. Simple Jobs. Basic knowledge of Computers and Internet is enough. Suitable for housewives, students, workers, retired persons and youths. For further details please visit: http://onlinejob7.googlepages.com From kyosohma at gmail.com Fri Mar 7 11:33:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 7 Mar 2008 08:33:59 -0800 (PST) Subject: Keep a python script running after browser window closed References: Message-ID: On Mar 7, 10:28 am, sophie_newbie wrote: > Hi, > > I have a cgi script that performs a very long computation that can > take several hours to complete. Is there any smart way that I can keep > this script running until it is finished (after the user has closed > the browser) and email them with the results. The email bit isn't the > problem, I just don't know how to keep the code running in the > background. I'm sure there is a smart way to do this... > > Thanks! You might have your cgi script use the subprocess module to open a second script that does the long-running process. Mike From jgardner at jonathangardner.net Fri Mar 21 10:16:14 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Mar 2008 07:16:14 -0700 (PDT) Subject: eval and unicode References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: On Mar 21, 1:54?am, Laszlo Nagy wrote: > ?>>> eval( "# -*- coding: latin2 -*-\n" + expr) > u'\u0170' # You can specify the encoding for eval, that is cool. > I didn't think of that. That's pretty cool. > I hope it is clear now. ?Inside eval, an unicode object was created from > a binary string. I just discovered that PEP 0263 can be used to specify > source encoding for eval. But still there is a problem: eval should not > assume that the expression is in any particular encoding. When it sees > something like '\xdb' then it should raise a SyntaxError - same error > that you should get when running a .py file containing the same expression: > > ?>>> file('test.py','wb+').write(expr + "\n") > ?>>> ^D > gandalf at saturnus:~$ python test.py > ? File "test.py", line 1 > SyntaxError: Non-ASCII character '\xdb' in file test.py on line 1, but > no encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor > details > > Otherwise the interpretation of the expression will be ambiguous. If > there is any good reason why eval assumed a particular encoding in the > above example? > I'm not sure, but being in a terminal session means a lot can be inferred about what encoding a stream of bytes is in. I don't know off the top of my head where this would be stored or how Python tries to figure it out. > > My problem is solved anyway. Anytime I need to eval an expression, I'm > going to specify the encoding manually with # -*- coding: XXX -*-. It is > good to know that it works for eval and its counterparts. And it is > unambiguous. ?:-) > I would personally adopt the Py3k convention and work with text as unicode and bytes as byte strings. That is, you should pass in a unicode string every time to eval, and never a byte string. From aeneng at gmail.com Fri Mar 28 22:10:10 2008 From: aeneng at gmail.com (aeneng pan) Date: Fri, 28 Mar 2008 22:10:10 -0400 Subject: Error message from function definition Message-ID: <263d8c50803281910x32e5375h37fd8bfe10f9f36c@mail.gmail.com> Dear community members, I just start to use python in numerical calculation. and I encountered some difficulties when I define my own function. Here is a piece of codes to compute the cross product of two 3x1 vector. can any one help me to find what is wrong with it? please see the codes below. when I import this function, it is not correct. here is the message I got. >>> import cross Traceback (most recent call last): File "", line 1, in ? File "cross.py", line 8 ppp2=u[2]*v[0]-u[0]*v[2] ^ SyntaxError: invalid syntax Thank you very much. Neng ##cross.py## def cross(u,v): """input two vectors u and v in 3-D space, both are in column or are in row. output a cross product of vector w, in column or in row accordingly. w=u x v. The type of u, v, w are matrix type from optcvx.base.matrix.""" ppp1,ppp2,ppp3=0.0,0.0,0.0 ppp1=u[1]*v[2]-u[2]*v[1] ppp2=u[2]*v[0]-u[0]*v[2] ppp3=u[0]*v[1]-u[1]*v[0] # store the result of the cross product in u u[0]=ppp1 u[1]=ppp2 u[2]=ppp3 return u #return the cross product of vector u x v. if __name__=="__main__": from cvxopt.base import matrix u=matrix([1.0,0.0,0.0],(3,1)) v=matrix([0.0,1.0,0.0],(3,1)) print "the cross product, uxv, is w= %6.3f" % cross(u,v) -------------- next part -------------- An HTML attachment was scrubbed... URL: From shakefu at gmail.com Fri Mar 7 17:12:07 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:12:07 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <3df1411d-836f-4214-9115-b508247649e3@p73g2000hsd.googlegroups.com> On Mar 7, 4:10 pm, Mike Driscoll wrote: > On Mar 7, 4:08 pm, shak... at gmail.com wrote: > > > I'm new to python and I was wondering if there are any intelligent > > date/time parsing modules out there. I've looked at strptime (or > > whichever it is) and mxDateTime from the eGenix package. I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > > So are there any modules that allow for that kind of parsing? > > There's the dateutil module that's a fancy wrapper for the datetime > module. The author's site has lots of examples as well as the source: > > http://labix.org/python-dateutil > > I use it quite a bit. > > HTH > > Mike Holy Crap that was fast. I'll check it out - thanks for the help! Jacob From ocollioud at gmail.com Fri Mar 28 06:47:56 2008 From: ocollioud at gmail.com (olive) Date: Fri, 28 Mar 2008 03:47:56 -0700 (PDT) Subject: Eclipse and PyDev Package explorer References: <1d4e6f2b-a058-413e-a566-674ccc733d6f@s19g2000prg.googlegroups.com> Message-ID: <02a2d458-ba16-4a48-9cda-1d65f7b858bb@f63g2000hsf.googlegroups.com> Hi, normally you just have to select your top level project folder in the Package Explorer and then from the menu bar choose Project -> Close Project (also accessible by the popup menu assigned to the right button of your mouse). HTH, Olivier. From tjreedy at udel.edu Thu Mar 6 14:30:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Mar 2008 14:30:09 -0500 Subject: Exploring Attributes and Methods References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: wrote in message news:6018ff8f-3372-42c2-9a2e-5ca996744d5b at e6g2000prf.googlegroups.com... | Hi, | Is there a python command that allows me to extract the names (not | values) of the attributes of a class. | | example | | Class Sample: | fullname = 'Something' | | How can I know that this class has an attribute called 'fullname'? >>> class C: a = 1 >>> dir(C) ['__doc__', '__module__', 'a'] From deets at nospam.web.de Sun Mar 9 13:36:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 18:36:18 +0100 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: Message-ID: <63ilglF28106hU1@mid.uni-berlin.de> Jeff Schiller schrieb: > Hello, > > I'm creating an application using Qt (4.4 Beta atm). I have pretty > close to zero experience with Python (consisting of installing the > Python interpreter, downloading a python programming and executing it > on the command-line). > > I would like to invoke a Python script from my C++ Qt program and > capture its output as a C++ structure. It seems that PythonQt might > be suitable for my needs. > > Being a Qt program, I want this thing to be cross-platform. I'm > having trouble getting things set up in Windows. Has anyone had any > experience with this? > > I've built Qt from source using the mingw32 compiler. I installed > Python 2.5 binary. I am trying to build PythonQt from source. As per > http://pythonqt.sourceforge.net/#Building it says I need a "developer > installation" of Python containing the header files and the library > files. When I look at my system after installing the Python 2.5 > binary, I can see I have header files (C:\Python25\include), a 199k > python25.lib (C:\Python25\libs) and a 2MB python25.dll > (C:\Windows\System32\). Have I got what I need? > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > to build but then it fails: > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyCFunction_Type' > ... > > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. A few of suggestions: - take this to the PyQt mailing list (http://www.riverbankcomputing.com/mailman/listinfo/pyqt) - you only *need* pyqt if what you want to do in python has really to deal with Qt-objects - maybe "simple" embedding is enough for your needs - I don't see why you need to compile PyQt yourself at all - are you sure you can't use the stock PyQt for windows? What makes you believe you really need this to be self-compiled? Diez From piet at cs.uu.nl Mon Mar 10 11:24:56 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 10 Mar 2008 16:24:56 +0100 Subject: float / rounding question References: <13t48m9l27s2q78@corp.supernews.com> Message-ID: >>>>> Dennis Lee Bieber (DLB) wrote: >DLB> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum >DLB> declaimed the following in comp.lang.python: >>> Sorry to come in so late in this discussion. Although it is correct to say >>> that many real numbers that have an exact decimal representation cannot be >>> exactly represented in binary, that is no excuse to print 53.6 as >>> 53.600000000000001. This is just lousy printing and the fact that this kind >>> of question comes up every week shows that it is confusing to many people. >>> >>>>> 53.6 >DLB> 53.600000000000001 >>>>> print 53.6 >DLB> 53.6 >>>>> print str(53.6) >DLB> 53.6 >>>>> print repr(53.6) >DLB> 53.600000000000001 >>>>> >DLB> Looks like "print" already does what you expect. No, what you see is not the behaviour of `print' but of `str'. `print' uses `str' to do the formatting instead of `repr' whereas the interactive prompt uses `str'. `str' is meant to please the human reader, and `repr' is supposed to give you something that you can use as input and get exactly the same value. But `str' does it by just giving you less accuracy, thus sweeping the problem under the carpet: >>> str(53.59999999999) 53.6 >>> 53.59999999999==53.6 False >>> repr(53.59999999999) '53.599999999989997' >>> 53.599999999989997==53.59999999999 True >>> repr(53.6) '53.600000000000001' >>> 53.600000000000001==53.6 True -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From max at alcyone.com Thu Mar 13 19:22:51 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Mar 2008 16:22:51 -0700 Subject: List mutation method gotcha - How well known? In-Reply-To: <9a1d9da3-42a7-4138-b53b-9ee690b77b7e@p73g2000hsd.googlegroups.com> References: <9a1d9da3-42a7-4138-b53b-9ee690b77b7e@p73g2000hsd.googlegroups.com> Message-ID: Chris wrote: > No output because x is a NoneType... That's behavior of the interactive interpreter when printing results of expressions, not of print. It will print None. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There is no present or future; only the past, happening over and over again, now. -- Eugene O'Neill From nick.fabry at coredump.us Wed Mar 19 21:11:14 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Wed, 19 Mar 2008 21:11:14 -0400 Subject: Improving datetime In-Reply-To: <13u353a51v9kp36@corp.supernews.com> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <13u353a51v9kp36@corp.supernews.com> Message-ID: <5062F606-8D43-4393-B7B9-E06E38C00C96@coredump.us> On Mar 19, 2008, at 18:32, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote: > >> To summarize my proposal VERY briefly: >> >> >> - Make aware datetime objects display in local time, but calculate/ >> compare in UTC. > > Your proposal is ambiguous. What does that mean? Can you give an > example? > > That's why I said it was the VERY brief version - here is a longer version. I would like a datetime to display local times, since if I create it with a specific tzinfo timezone, that implies I'm interested in what clocks in that time zone say. For example: >>> from datetime import datetime >>> from dateutil.tz import gettz >>> NYC = gettz('America/New_York') >>> UTC = gettz('UTC') >>> wake_up_time = datetime(2008,3,8,15,30,0,tzinfo=NYC) >>> print wake_up_time 2008-03-08 15:30:00-05:00 >>> print wake_up_time.hour 15 This is the behavior I want - if I create a datetime in a specific timezone, I wish to know the member information (date, hour, second, etc.) in that timezone. However, when I calculate with it, I can get wrong answers. >>> a_later_time = datetime(2008,3,9,15,30,0,tzinfo=NYC) >>> print a_later_time - wake_up_time 1 day, 0:00:00 This is incorrect, because a_later_time is in daylight saving time, but the eariler time is in standard time - the gap is actually 23:00 hours. >>> print a_later_time.astimezone(UTC) - wake_up_time.astimezone(UTC) 23:00 The reason datetime performs this calculation incorrectly is documented - if the tzinfo members are the same object, it ignores them and makes the calculation as though the two datetimes were naive. If the tzinfo objects are different, even if they correspond to the exact same ruleset, then datetime does the job correctly. >>> import copy >>> ALT_NYC = copy.deepcopy(NYC) >>> the_same_later_time = datetime(2008,3,9,15,30,0,tzinfo=ALT_NYC) >>> print the_same_later_time - wake_up_time 23:00 The results of the calculation should not be dependent on whether the tzinfo object is the same or not, but what it's .utcoffset() method returns. Or, to summarize, ALL calculations with aware datetime objects should first change the datetime objects to UTC so the calculations are done correctly. Changing all times to UTC creation, aside from making ugly code, now forces a conversion back to local time, with more code, any time you want to display date and time information in the local time zone. This is not a good, pythonic solution. > > >> - Raise exceptions when an illegal or ambiguous datetime is >> instantated. > > You mean like they already do? > >>>> datetime.datetime(2008, 03, 35) # 35th of March > Traceback (most recent call last): > File "", line 1, in > ValueError: day is out of range for month > > However, the following does NOT raise an exception, and it should. >>> a_time = datetime(2008, 3, 9, 1, 30, 0, tzinfo=NYC) >>> print a_time 2008-03-09 01:30:00-05:00 The problem is that there IS no local wallclock time of 0130 on March 9, 2008 in New York. At 0100, local clocks jump to 0200 and proceed from there. A local wallclock time of 0130 on March 9, 2008 in New York is meaningless - it should not occur. Therefore, if a programmer is (for example) parsing local times (say, out of a schedule book), and an illegal time like this appears, instead of an exception immediately being raised to alert him/her of the faulty source data, the program *assumes* the illegal local time was 'meant' to be in standard time, and sends it merrily on its way... making it much harder when errors crop up later to figure out their source. > > > As for ambiguous, how can datetime arguments be ambiguous? > > Help on class datetime in module datetime: > > class datetime(date) > | datetime(year, month, day[, hour[, minute[, second[, > microsecond[,tzinfo]]]]]) > > > What possible ambiguity is there? > Continuing on from before: >>> b_time = datetime(2008, 11, 2, 1, 30, 0, tzinfo=NYC) >>> print b_time 2008-11-02 01:30:00-05:00 There is a little problem with this, though. At 2008 Nov 2 at 0200 Eastern Daylight Time, the clocks swing back one hour, to 0100, and essentially repeat the hour between 0100 and 0200 again. So - is b_time 0130 Eastern STANDARD Time, or is it 0130 Eastern DAYLIGHT Time? Simply providing a tzinfo class does not resolve this ambiguity, so it is again *assumed* that you 'meant' standard time. That may or may not be true, depending on the source data and other external factors. A good datetime library (or tzinfo library) should alert you to this fact. Isn't Explict better than Implicit? A further problem is that it is now impossible to specify using tzinfo = NYC, a time corresponding to 2008 Nov 2, 0530 UTC, or in other words, 2008 Nov 2 0130 EDT. If you try it directly, as above, you get 2008 Nov 2 0130 EST, which is 0630 UTC. If you create the time 2008 Nov 2 0530 UTC, and then use .astimezone(NYC), you will get the same result.... 2008 Nov 2 0130 EST, which is not the EDT time we wanted, nor is it equal to 0530 UTC. >>> c_time = datetime(2008,11,2,5,30,0,tzinfo=UTC) >>> print c_time.astimezone(NYC) 2008-11-02 01:30:00-05:00 >>> print c_time.astimezone(NYC).astimezone(UTC) == c_time False These problems all stem from the fact that local times are used for internal storage, when in certain circumstances they do not uniquely specify a real time. This could be fixed by making each datetime object really have TWO datetime objects within it - one that corresponds to UTC (so it is unambigious what real time it refers to, and so calculations can speedily access UTC time), and one that corresponds to local wallclock time (so it is known what the local wallclocks are displaying, and allowing efficient member extraction and not breaking existing code). This is the moderately short and casual version of it. Nick P.S. The code in full form, to follow along better: from datetime import datetime from dateutil.tz import gettz NYC = gettz('America/New_York') UTC = gettz('UTC') wake_up_time = datetime(2008,3,8,15,30,0,tzinfo=NYC) print wake_up_time #2008-03-08 15:30:00-05:00 print wake_up_time.hour #15 a_later_time = datetime(2008,3,9,15,30,0,tzinfo=NYC) print a_later_time - wake_up_time #1 day, 0:00:00 print a_later_time.astimezone(UTC) - wake_up_time.astimezone(UTC) #23:00 import copy ALT_NYC = copy.deepcopy(NYC) the_same_later_time = datetime(2008,3,9,15,30,0,tzinfo=ALT_NYC) print the_same_later_time - wake_up_time #23:00 a_time = datetime(2008, 3, 9, 1, 30, 0, tzinfo=NYC) print a_time #2008-03-09 01:30:00-05:00 b_time = datetime(2008, 11, 2, 1, 30, 0, tzinfo=NYC) print b_time #2008-11-02 01:30:00-05:00 c_time = datetime(2008,11,2,5,30,0,tzinfo=UTC) print c_time.astimezone(NYC) #2008-11-02 01:30:00-05:00 print c_time.astimezone(NYC).astimezone(UTC) == c_time #False > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Mar 19 19:06:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 16:06:46 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> Message-ID: On Mar 20, 9:57 am, Justin Bozonier wrote: > On Mar 19, 2:48 pm, John Machin wrote: > > > > > On Mar 19, 10:08 am, sturlamolden wrote: > > > > On 18 Mar, 23:45, Arnaud Delobelle wrote: > > > > > > def nonunique(lst): > > > > > slst = sorted(lst) > > > > > dups = [s[0] for s in > > > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > > > > return [dups[0]] + [s[1] for s in > > > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > > > Argh! What's wrong with something like: > > > > > def duplicates(l): > > > > i = j = object() > > > > for k in sorted(l): > > > > if i != j == k: yield k > > > > i, j = j, k > > > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) > > > as opposed to ours which are O(N log N). > > > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > > and is IMHO more readable than Paul's. > > It's not as much O(N)... Paul Robin's uses a sort first which is > definitely not O(N). Paul's could be prettied up a bit but the general > principle is sound. """ from collections import defaultdict def nonunique(lst): d = defaultdict(int) for x in lst: d[x] += 1 return [x for x,n in d.iterkeys() if n > 1] """ I see no sort here. From ocollioud at gmail.com Mon Mar 31 13:56:52 2008 From: ocollioud at gmail.com (olive) Date: Mon, 31 Mar 2008 10:56:52 -0700 (PDT) Subject: Of qooxdoo, qwt, and Python References: <28f7384f-b8d1-430d-9e0d-389ebae7eefd@e10g2000prf.googlegroups.com> Message-ID: <51c2f4c2-8752-49e3-81f8-77094c078015@k13g2000hse.googlegroups.com> On 31 mar, 18:05, John Henry wrote: > I was searching for a way to redevelop a desktop Pythoncard based > program into a web-application. I understand what need to be done for > all of the non-GUI code. For the GUI capabilities, I stumbled across > a package call qooxdoo (http://qooxdoo.org/). It appears to provide > the GUI capabilities I need. Then I saw that there is qwt - which > allows you to write qooxdoo code in pure Java. Since I don't know > Java (or don't want to know), is there a similar path I can take using > Python? > > Regards, you could try this http://code.google.com/p/pyjamas/ or http://doc.appcelerator.org/overview/what_is_appcelerator/index.html or maybe jython with any java based toolkit (qwt, zk ...). Regards. From d3vvnull at gmail.com Tue Mar 18 12:53:43 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 18 Mar 2008 11:53:43 -0500 Subject: Need Help Starting Out In-Reply-To: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <170543c70803180953u56137ed6g15e45a4e6c2fc013@mail.gmail.com> Pylons is a Ruby on Rails-like web framework that allows you build dynamic web applications with a database backend. Here is a link to the Pylons web site: http://pylonshq.com/ On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop wrote: > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. > > I want to use it for web building with database access. What do I use > for that? Does it matter what I use on the client side (mootools, or > whatever)? > > My rational for using Python is because I am hoping it will allow me > to better understand other python programs in other areas, not just > web. I have used other languages for web apps for several years. > Truth is that I always wanted to learn Python and have heard it was a > good thing to know. > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Fri Mar 14 06:33:39 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Mar 2008 10:33:39 GMT Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <87skyvuhpo.fsf@rudin.co.uk> <13tj6omdip82f13@corp.supernews.com> Message-ID: On 2008-03-13, Steven D'Aprano wrote: > On Thu, 13 Mar 2008 08:54:43 +0000, Paul Rudin wrote: > >>> Whatever python has for a calling convention, it is close enough that >>> naming it "call by reference" gives people a reasonable idea of what is >>> going on. >> >> Quite. The thing is not to get hung up with the label - but to >> understand what actually happens. > > Agreed. And I think the best way to do that is to use the same terms that > other languages use to get very different behaviour indeed. > > "Python is call by reference, but this doesn't work like call by > reference in all the other languages I've used: > > def negate(n): > n = -n > > x = 2 > negate(x) > assert x == -2 > > Is this a bug, or is Python actually call by value?" > And now comes the explanations that Python is actually call by value, but > the values being copied are *pointers* (ignoring Jython, IronPython and > PyPy); or that Python is really call by reference, but different > "things" (it's never quite clear what exactly) happen depending on > whether the arguments are mutable or immutable; Which is wrong. The same thing happens with mutable and immutable objects. What one needs to understand is: Right after the call, x and n are the same object. After the assigment x and n no longer are the same object. The assignment doesn't negate the original object. It creates a new object with the negative value of the original while the latter remains bound to x. As long as the person who has trouble with this behaviour doesn't understand that the assignment is not a mutating operator. Your explanation will get you nowhere. The trouble is mosly caused because people see a line like n = -n and interpret this more or less as the object bound to n has the negated value after the assignment. That is why they think x should be -2 in your example. > or that if you define > reference broadly enough, everything is a reference; or that if you > define value broadly enough, everything is a value; or if schools would > just stop teaching kiddies C and start teaching them Lisp, call by > reference semantics would be understood in a different way, or or or or... > And thus, by insisting that there are two and only two calling > conventions, no matter how many different kinds of calling behaviour > actually exist, we ensure that we'll be having this same *&$%^*# argument > when Python 4000 comes out. But you seem to make the same kind of mistake, but with regard to assignments. You seem to implicitly assume there is only one kind of assignment and by trying to start from there and trying to explain what goes on in terms of different calling conventions you will ensure the same argument just as well. -- Antoon Pardon From george.sakkis at gmail.com Wed Mar 26 21:02:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 18:02:35 -0700 (PDT) Subject: Not understanding lamdas and scoping References: Message-ID: On Mar 26, 6:03 pm, Joshua Kugler wrote: > George Sakkis wrote: > > On Mar 26, 5:02 pm, Joshua Kugler wrote: > > >> I am trying to use lamdba to generate some functions, and it is not > >> working > >> the way I'd expect. The code is below, followed by the results I'm > >> getting. More comments below that. > > >> (...) > > >> So, is there some scoping issue with lambda > >> that I'm not seeing? > > > Yes; it's not related to lambda though but to closures (whether > > defined as lambdas or regular functions). See for example > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/94d... > > > > > There should be an entry for this at > >http://www.python.org/doc/faq/programming/, that's really an FAQ. > > George - > > Thanks for the quick and clear answer...that makes perfect sense. To > bad...I'd like to just use a list comprehension. :) Did you actually read the replies on that thread ? You _can_ use a list comprehension or a loop, all you have to do is bind the passed values as default parameters: rules = [make_pattern(pattern=p, search=s, replace=r) for (p,s,r) in patterns] George From sjdevnull at yahoo.com Sat Mar 8 23:45:25 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sat, 8 Mar 2008 20:45:25 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: On Mar 8, 7:34 pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > > I'm also a bit baffled by people who put a comment at the top of every > > file that tells you what the filename is. > > [snip rant] > > You've never printed out a source file on pieces of dead tree to read on > the train on the way home, or in bed or the bath? > > Yes, some editors will print a header or footer showing the file name, > but not all will, or are configured to do so. The only times I can recall printing source were in college classes where I was required to hand in a hardcopy with the assignment and code samples for job interviews. In the real world the code base tends to be too huge to contemplate printing, especially when I'd then be stuck without sane ways to navigate around (tags, search, oobr, etc). For instance, our project right now is around 350,000 lines of python and about 300,000 of DTML/mako templates. I expect the availability of laptops since I really started working as a programmer in the mid-1990s biases me a bit compared to earlier times. Even in the early 1990s the moral equivalent of enscript (I think it was a2ps) worked just fine for printing with filenames, line/page numbers, and other niceties no matter what editor you used. It seems more reasonable to mandate using a sane print tool for the odd case where someone wants to print things out than to mandate cluttering up every file with the filename in a comment. From madduck at madduck.net Mon Mar 17 12:41:23 2008 From: madduck at madduck.net (martin f krafft) Date: Mon, 17 Mar 2008 17:41:23 +0100 Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? In-Reply-To: <20080316132140.GA24529@piper.oerlikon.madduck.net> References: <20080316132140.GA24529@piper.oerlikon.madduck.net> Message-ID: <20080317164123.GA1988@piper.oerlikon.madduck.net> also sprach martin f krafft [2008.03.16.1421 +0100]: > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' There's a difference between those two. The first one has an empty string value ('') while the second one pretty clearly says that there is a parameter but has no value. Why ? -- martin | http://madduck.net/ | http://two.sentenc.es/ all software projects are done by iterative prototyping. some companies call their prototypes "releases", that's all. spamtraps: madduck.bogus at madduck.net -------------- next part -------------- A non-text attachment was scrubbed... Name: digital_signature_gpg.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature (see http://martin-krafft.net/gpg/) URL: From fuzzyman at gmail.com Sun Mar 16 11:00:48 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 16 Mar 2008 08:00:48 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <7e9cad5e-265d-4285-a26b-df9489937972@e39g2000hsf.googlegroups.com> > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan That's a great quote that I had not heard before. :-) Michael Foord http://www.manning.com/foord From darcy at druid.net Sun Mar 16 12:47:28 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 16 Mar 2008 12:47:28 -0400 Subject: Basics of Python,learning In-Reply-To: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <20080316124728.007c164c.darcy@druid.net> On Sun, 16 Mar 2008 17:25:26 +0100 Guido van Brakel wrote: > Hello > > Why is this not working,and how can I correct it? What are you expecting it to do? For one thing, you are acting on a variable 'a' but it is never defined. The only objects that you have is z, y, b and then b is redefined as a method which creates a variable 'x', overwrites it twice and then discards it. Doesn't matter since you never call the method anyway. Back to the textbook I think. -- 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 jasong at gmail.com Tue Mar 4 22:46:45 2008 From: jasong at gmail.com (Jason Galyon) Date: Tue, 04 Mar 2008 21:46:45 -0600 Subject: multiplication of lists of strings In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Tue, 04 Mar 2008 23:50:49 -0200, Jason escribi?: > >> How could I return a list or tuple of each unique combination of a given >> set of lists (perhaps from a dict or a list). This means the number of >> lists are not known nor is the length of each. > > Use the Google interfase for this group: > http://groups.google.com/group/comp.lang.python/ > Type "unique combinations lists" in the text box; press "Search in this > group". The very first result contains some answers to your question. > found it, the referenced cookbook recipe is perfect. Thanks, Gabriel From tibit at sonic.net Mon Mar 31 13:15:56 2008 From: tibit at sonic.net (Forest) Date: Mon, 31 Mar 2008 10:15:56 -0700 (PDT) Subject: why does socket.makefile require non-blocking mode? Message-ID: <18907.75.55.199.5.1206983756.squirrel@webmail.sonic.net> On Sat, 29 Mar 2008 08:18:23 -0300, Guilherme Polo wrote: >I don't know why you think timeout is forbidden too, it is not. I can't tell for sure whether it is or isn't, because of this language in the socket module docs: "s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1)." >>I wanted to use file-like objects with socket timeouts, so I ended up >>writing my own replacement for socket._fileobject. I'd appreciate it >>if someone could either explain to me why my new class was unnecessary, >>or else encourage me to contribute it as a patch to the socket module. > >It looks like to be unnecessary. I'm hoping for a more definitive answer than "looks like", but thank you just the same. My main concern is this: A brief look at the existing socket._fileobject shows that its read() method calls recv() in a loop, appending to a temporary buffer on each pass, and finally returning the buffer when recv() gets no more data. It looks to me like a socket timeout exception would cause that loop to exit without saving the data collected in earlier passes. In other words, data loss on recv() timeout. If someone more familiar with socket._fileobject can point out a reason this cannot happen (perhaps I've missed something) I'll be satisfied. Otherwise, I think my rewritten class has value. From steveo at syslang.net Mon Mar 31 12:32:38 2008 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 31 Mar 2008 12:32:38 -0400 (EDT) Subject: Looking for indent advice howto in emacs python-mode Message-ID: Here's what I want to do: if ( ( v == 1 ) or ( v == 2 ) or ( v == 3 ) ): pass but emacs (left to its own devices, does this. if ( ( v == 1 ) or ( v == 2 ) or ( v == 3 ) ): pass It works great for me in C-mode. Does anyone know how to jimmie up python-mode so it would know how to do this? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From sjmachin at lexicon.net Mon Mar 10 16:57:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 13:57:19 -0700 (PDT) Subject: any chance regular expressions are cached? References: <51172306-ff2d-48e8-81cf-93be03f8a08f@s37g2000prg.googlegroups.com> Message-ID: On Mar 10, 3:42 pm, John Machin wrote rather baroquely: > ...>>> def myfunc(s, spaces): > > ... return '\n'.join(spaces + x.rstrip() if x.rstrip() else '' for > x in s.splitlines()) Better: ... return '\n'.join((spaces + x).rstrip() for x in s.splitlines()) From nexes128 at gmail.com Sat Mar 1 11:58:32 2008 From: nexes128 at gmail.com (nexes) Date: Sat, 1 Mar 2008 08:58:32 -0800 (PST) Subject: SQLLITE Message-ID: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> Hello All, I am having a minor problem when I try and do this: c.execute("insert into [tblTranscripts] (MovieID,Transcript) Values(" + movieID + ",'" + formatText + "');") (don't even bother commenting of the sql style I know its bad form but this is a simple script). Whenever I try and do the insert I get table not found, however when I perform the sql through sqlite's command line program (the sql is outputted via a print statement) it works fine. Any ideas? From castironpi at gmail.com Fri Mar 7 20:04:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 17:04:54 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <13t3gq9qo0po5ce@corp.supernews.com> <81d37ead-edd9-4666-8adb-5b5da45c6321@k2g2000hse.googlegroups.com> Message-ID: On Mar 7, 5:00?pm, shak... at gmail.com wrote: > On Mar 7, 4:35 pm, Jeffrey Froman wrote: > > > shak... at gmail.com wrote: > > > I need > > > something to parse user input for a django app, and it's awesome to be > > > able to write "last monday", "a year ago", or "10pm tuesday" like > > > PHP's strtotime. > > > Django comes with some pretty handy filters for doing this sort of > > formatting. Check out the "date", "now", "timesince" and "timeuntil" > > filters here: > > >http://www.djangoproject.com/documentation/templates/#built-in-filter... > > > Jeffrey > > Very cool - that's definitely handy to know for the output side of > things. I was mostly interested in writing a custom widget for > handling datetime input, 'cause I can't imagine anyone being studious > enough to use the 2008-03-07 12:00:00 format all the time... besides, > it's hard to type! I'd much rather allow for users to just be able to > type "12pm today". > > So much to learn, so little time! > > Jacob With some acquaintence with the user, a program can even honor, "remind me 'later' to...". Will you assign meanings to weird ambiguities like, 'last February' (No, I mean laaaaaaast February.) if it's April and "tomorrow" if it's 4 a.m.? Just raise an exception: TimeOfDayException: "Yes, but it's 4 a.m." (or, Those probabilities are close.) The vocabulary for referring to time isn't that large. What did I miss? Yesterday, today, tomorrow, ago, from now, later, after, before, [units], [absolutes], wikipedia. But what's the elegant way to structure the expression? From steve at holdenweb.com Sat Mar 1 00:39:56 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 00:39:56 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <3f7980f4-9b07-46dc-a3d9-b333d0a29646@s12g2000prg.googlegroups.com> References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> <13sd3rnokh1975d@corp.supernews.com> <13sfb24231sjbb5@corp.supernews.com> <3f7980f4-9b07-46dc-a3d9-b333d0a29646@s12g2000prg.googlegroups.com> Message-ID: Dan Bishop wrote: > On Feb 29, 12:55 am, Dennis Lee Bieber wrote: >> On Thu, 28 Feb 2008 10:39:51 -0000, Steven D'Aprano >> declaimed the following in >> comp.lang.python: >> >>> By that logic, we should see this: >>>>>> len("a string") >>> '8' >> Why? len() is a function that /counts/ the elements of the argument >> -- said count remains in integral value (I presume we don't have a 1.5 >> character long string) > > The relevant point is that len() is a function that returns a > DIFFERENT type than its argument, and nobody ever complains about is. > A language that restricted its functions to returning the same types as its arguments wouldn't be very much use, would it? And what about functions that have multiple arguments of different types? >>> And rightly rejected by many other programming languages, including >>> modern Python, not to mention calculators, real mathematics and common >>> sense. >> I know of no calculator that has "integers" for normal math -- and >> the HP50 even emphasizes this by putting a decimal point into "integer" >> quantities. Heck -- most calculators work in BCD floats. Most merely >> suppress the decimal point if the trailing digits are all 0s > > My TI-89 treats them differently: 1.0/2.0 is 0.5, while 1/2 is the > symbolic expression 1/2. Any you don't even have to import anything from __future__! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at holdenweb.com Tue Mar 4 08:05:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 08:05:57 -0500 Subject: pySQLite Insert speed In-Reply-To: <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: mmm wrote: > Steve, I think you were right the first time is saying > >> it should really be this: >> sqlxb= 'INSERT INTO DTABLE2 VALUES (?, ?, ?, ?)' > > my copy.copy() has the equivalent effect. > > Running this test code produces the output below > > import copy > > print 'Test 1' > pf= '?,?,?,?' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print sqlx1 > > print > print 'Test 2' > sqlx2= copy.copy(sqlx1) > sqlx3= sqlx1 > pf= '?,?,?, ****' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print 'sqlx1= ', sqlx1 > print 'sqlx2= ', sqlx2 > print 'sqlx3= ', sqlx2 > > == output > Test group 1 > INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Test group 2 > sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?, **** ) > sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > I interpret this to mean that sqlx1 is not a simple string Sorry, since you didn't copy and paste the actual code you ran I don't regard those results as reliable. What I will repeat, however, is that while there is a *slight* difference is semantics between s = "some string" s1 = s and s = "some string" s1 = copy.copy(s) that difference is only to ensure that s and s1 point to different copies of the same string in the latter case, whereas in the former case s and s1 point to the same string. Since strings are immutable in Python this really doesn't make any difference. In either case changing the value of s will leave the value of s1 unchanged, since it will still point to the string it was originally bound to and s will point to some other string. I suspect some superstition is at play here, or possibly you are cargo cult programming :) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Wed Mar 19 21:56:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 22:56:17 -0300 Subject: [newbie] using ElementTree, how to add doctype and xml pi References: Message-ID: En Wed, 19 Mar 2008 20:53:49 -0300, dave berk escribi?: > I have an svg file i'm creating on the fly. How do I add the doctype and > xml > pi? They're not an element per se, and there is no function to add them. The easiest way (but perhaps not-so-pure) is to just write those lines by hand before the document itself; see a recent post about "Inserting DTD statement to XML" -- Gabriel Genellina From software at ginstrom.com Sun Mar 23 11:46:17 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 24 Mar 2008 00:46:17 +0900 Subject: Duplicating list of lists [newbie] In-Reply-To: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> References: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Message-ID: <078f01c88cfd$088b98c0$0203a8c0@MOUSE> > On Behalf Of yatsek at gmail.com > So - it looks that in list "b" there copy of all objects from list "a" > including not copy of list [5,6,7] but reference to it. > > Is there simple way to copy a into b (like a[:]) with all > copies of all objects going as deep as possible? Or it can be > done only manually? I'd suggest checking out copy.deepcopy. >>> a = [1, [1, 2, 3], 2] >>> b = a[:] >>> a[1][2] = 'spam' >>> b [1, [1, 2, 'spam'], 2] >>> from copy import deepcopy >>> b = deepcopy(a) >>> a[1][2] = 'deepcopy is your friend' >>> b [1, [1, 2, 'spam'], 2] Regards, Ryan Ginstrom From arnodel at googlemail.com Sun Mar 23 04:31:51 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Mar 2008 01:31:51 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> <13uc4bpb0b564af@corp.supernews.com> Message-ID: <7a4c084f-ecb7-4ed4-8f3f-af29d811d44a@b64g2000hsa.googlegroups.com> On Mar 23, 8:14?am, Steven D'Aprano wrote: > On Sat, 22 Mar 2008 23:15:00 -0700, John Nagle wrote: > > That's some professor inventing his very own variation on predicate > > calculus and writing a book using his own notation and terminology. > > There's no sign of footnotes or references to prior work. ?The notation > > doesn't seem to do anything not previously possible; it's just > > different. > > You say that as if it were unusual in maths circles :) > Haha. As opposed to programmers who have all agreed to use the same language. Anyway, I have browsed the book and agree with Paul Rubin that there doesn't seem to be any unusual notation in it, although there are a numbers of topics that I am not really familiar with. -- Arnaud From tavares at fe.up.pt Thu Mar 6 09:15:33 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 6 Mar 2008 06:15:33 -0800 (PST) Subject: Int. J. of Tomography & Statistics, Special Issue on Image Processing - Call for papers Message-ID: (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) ****************************************************************************************************** Special issue on Image Processing Gest Editors: Jo?o Manuel R. S. Tavares & Renato M. Natal Jorge - UP - Portugal International Journal of Tomography & Statistics ISSN 0973-7294 (Online) - 0972-9976 (Print) http://www.isder.ceser.res.in/ijts.html ****************************************************************************************************** Dear Colleague, This special issue of the International Journal of Tomography & Statistics (IJT&S) is devoted to promote a broad exchange of information on technologies, applications, operations and quality assurance in the areas of Computed Tomography, Statistics as well as of Image Processing. This special issue on Image Processing is an opportunity for users, scientists, image equipment suppliers and all who are interested to present their works on image detectors and acquisition systems, signal processing, image processing and analysis, medical imaging, pattern analysis and recognition, volume scanning and reconstruction, features extraction and classification, telemedicine, virtual and augmented reality, enhanced computation and software applications of image processing. Thus, if you are working on the related areas of the special issue "Image Processing", It is an honour to invite you to submit your work to be published in the IJT&S. Important Dates and Instructions: Deadline for papers submission: 30/06/2008; Authors notification: 15/09/2008; Final version of accepted papers: 1/11/2008; If you intend to submit your work please notify as soon as possible the guest editors of your intention (tavares at fe.up.pt, rnatal at fe.up.pt); Papers for the special issue should be sent to the guest editors (tavares at fe.up.pt, rnatal at fe.up.pt); Instructions for authors are available at: http://www.isder.ceser.res.in/ijts/instr4a.html. With kind regards, Yours sincerely The Guest Editors Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) Renato M. Natal Jorge (rnatal at fe.up.pt) University of Porto, Portugal From tjreedy at udel.edu Sat Mar 1 16:32:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Mar 2008 16:32:11 -0500 Subject: A python STUN client is ready on Google Code. References: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> <8ce119530803010101w320b8d30md5112aebab6f7551@mail.gmail.com> Message-ID: "hawk gao" wrote in message news:8ce119530803010101w320b8d30md5112aebab6f7551 at mail.gmail.com... |I upload a new version. Add more print log into my code to help people | understand my program Announcements should include a short paragraph explaining what the announcement is about for those of us not in the know. IE, what is STUN? -- and therefore, what is a STUN client? From magdoll at gmail.com Tue Mar 11 18:43:40 2008 From: magdoll at gmail.com (Magdoll) Date: Tue, 11 Mar 2008 15:43:40 -0700 (PDT) Subject: merging intervals repeatedly References: Message-ID: <20b3dfb8-c5b7-4fd0-97a1-93f590f54595@u10g2000prn.googlegroups.com> Correct. I meant the final should be (1,30), (29,40), (50,100) On Mar 11, 3:41 pm, Magdoll wrote: > Hi, > > I have to read through a file that will give me a bunch of intervals. > My ultimate goal is to produce a final set of intervals such that not > two intervals overlap by more than N, where N is a predetermined > length. > > For example, I could read through this input: > (1,10), (3,15), (20,30),(29,40),(51,65),(62,100),(50,66) > > btw, the input is not guaranteed to be in any sorted order. > > say N = 5, so the final set should be > (1,15), (20, 30), (29, 40), (50, 100) > > Is there already some existing code in Python that I can easily take > advantage of to produce this? Right now I've written my own simple > solution, which is just to maintain a list of the intervals. I can use > the Interval module, but it doesn't really affect much. I read one > interval from the input file at a time, and use bisect to insert it in > order. The problem comes with merging, which sometimes can be > cascading. > > ex: > read (51,65) ==> put (51,65) in list > read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) > read (50,66) ==> merge with (51,65) to become (50,66) ==> now can > merge with (62,100) > > Of course I can check for cascading merges by pivoting around the > position where the insertion would've taken place...but just > wondering, is there some other nice way to do this? I also intuitively > don't sense a need for using trees, unless someone's already written > it, the interface is easy to use, and it won't result in more insert/ > delete/structure changes that nullifies its beauty...(also I'm not > using the output list for searching) > > Thanks in advance. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 3 11:16:49 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Mar 2008 17:16:49 +0100 Subject: Exception or not In-Reply-To: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> References: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Message-ID: <47cc2470$0$1688$426a74cc@news.free.fr> Monica Leko a ?crit : > Suppose you have some HTML forms which you would like to validate. > Every field can have different errors. For example, this are the > forms: > > username > password > etc > > And you want to validate them with some class. This is what the FormEncode package is for. From cwitts at gmail.com Tue Mar 11 02:52:50 2008 From: cwitts at gmail.com (Chris) Date: Mon, 10 Mar 2008 23:52:50 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <63i6j9F2793buU1@mid.uni-berlin.de> <63lqcuF27pbnbU1@mid.uni-berlin.de> Message-ID: <877541e6-1407-4c0d-9818-e500f38823d5@o77g2000hsf.googlegroups.com> If all you wanted was some grouping of exceptions why not something like... soft_exception_list = [IndexError, TypeError] hard_exception_list = [ZeroDivision] try: do_something() except Exception, e: if e.__class__ in soft_exception_list: handle_soft_exception() elif e.__class__ in hard_exception_list: handle_hard_exception() else: raise NotImplementedError Granted you're most likely looking for something that does this constantly on every line of code though... From tmp1 at viltersten.com Sat Mar 1 16:35:11 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 22:35:11 +0100 Subject: Where's GUI for Python? Message-ID: <62tvhmF256jk7U1@mid.individual.net> I'm certain there is an API for creating GUI's but as far i can find it in the http://docs.python.org/tut/tut.html the only "gui" is in "Guido". What do i miss? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From jeff.self at gmail.com Tue Mar 11 11:44:34 2008 From: jeff.self at gmail.com (jeffself) Date: Tue, 11 Mar 2008 08:44:34 -0700 (PDT) Subject: Python PDF + Pictures References: Message-ID: <6a34e7f9-96c4-4434-a7df-e7e83eabc58b@o77g2000hsf.googlegroups.com> On Mar 11, 5:00 am, "durumd... at gmail.com" wrote: > Hi, dear Python Masters! > > I wanna ask about the Python and PDF creating. > > I have many photos, and I wanna make some "presentation" from these > photos, a "thumbnail" like document with one image per one page. > > If I wanna make one document now I do this: > I execute a python script that create a html site with resized pictures, > and split this html site to 50 images per one html file. > Next I open these files in OpenOffice Writer by hand, and save them as > PDF document with poor quality (image compression 95%, image DPI 75). > This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that > can opened everywhere (because of PDF format). > > But I wanna automatize this process with python. > The technic that I will use is this: > 1.) Collect the files in dirs. > 2.) I process one dir in one time. > 3.) I get the files. > 4.) I resize them to max. 1024/768. > 5.) I put the actual image file to the PDF document. > 6.) After each 50. file I open new numbered PDF. > 7.) Every picture placed in one page, and every page orientation set up > as the picture orientation (Portrait or Landscape). > > The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. > > Do you knows about a PDF maker library with I can make this thing? > > Or other technic to simplify the making? > > Thanks for your help! > dd You might also want to take a look at ReportLab. Its a PDF library for Python. You can find it at http://www.reportlab.org/ From pstapley at howaboutnow.net Mon Mar 24 17:28:04 2008 From: pstapley at howaboutnow.net (Pete Stapley) Date: Mon, 24 Mar 2008 15:28:04 -0600 Subject: Reading new mail from outlook using Python In-Reply-To: <924616.42495.qm@web50105.mail.re2.yahoo.com> References: <924616.42495.qm@web50105.mail.re2.yahoo.com> Message-ID: <47E81CE4.10305@howaboutnow.net> Well on a FreeBSD/Unix system you can use the .forward to pipe the incoming mail for a user to a program. Below is the contents of my .forward that invokes procmail. "|/usr/local/bin/procmail -m /path/to/conf/.procmailrc" So I imagine you could do something like this in a .forward. "|/path/myprogram.py" SPJ wrote: > Hi, > > I am trying to create new tickets in the ticketing system using > python. When I receive new email from a particular address, I have to > trigger the python script and parse the mail in required format. > > The main hurdle here is, how to invoke the script on arrival of new > mail? I checked the outlook settings and found that it supports only > microsoft VB script and Jscript. Is there any other way? I mean, if I > make a daemon, how will it be notified of new mail? Is there any > python module that does this? > > I am not sure if this is the right place to ask this, since it is also > a microsoft related question. But any help is appreciated. > > Thanks, > SPJ > > > ------------------------------------------------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > it now. > From zentraders at gmail.com Sat Mar 22 17:55:39 2008 From: zentraders at gmail.com (Zentrader) Date: Sat, 22 Mar 2008 14:55:39 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> Message-ID: <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> > No one meant to laugh at you. Your naivete was not obvious. FWIW, a > sense of humor is a valuable possession in most Python-related > conversations. Perhaps someone can explain how telling something like this to the OP, who thinks this statement will work if 'one' and 'two' in f: is funny and not mean. In the words of whoever it was in "Gone With The Wind", frankly I don't give a damn (except to not mislead relative newbies). But this has wasted enough of everyone's time. From george.sakkis at gmail.com Tue Mar 18 00:31:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 17 Mar 2008 21:31:42 -0700 (PDT) Subject: Any fancy grep utility replacements out there? References: Message-ID: On Mar 17, 10:20 pm, "samsli... at gmail.com" wrote: > So I need to recursively grep a bunch of gzipped files. This can't be > easily done with grep, rgrep or zgrep. (I'm sure given the right > pipeline including using the find command it could be done....but > seems like a hassle). If it's for something quick & dirty, you can't beat the pipeline, e.g. something like: find some_dir -name "*gz" | xargs -i sh -c "echo '== {} =='; zcat {} | grep some_pattern" George From bearophileHUGS at lycos.com Tue Mar 4 08:27:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 4 Mar 2008 05:27:56 -0800 (PST) Subject: for-else Message-ID: So far in Python I've almost hated the 'else' of the 'for' loops: - I have problems to remember its meaning; - It gives me little problems when I later want to translate Python code to other languages (and you always have to translate long-lived code). - I have used it only once, so far. So so far I'd liked to see it removed from Python 3.0. But then this article: http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel_language_features has shown me that my problems with the 'else' of the 'for' mostly come from just its bad naming. The converge language is yet another very Python-like language, and it uses a better naming (the word "exhausted" is long and has a complex spelling for non-English speakers, so it's not perfect): for ...: ... exhausted: ... broken: ... The meaning is explicit. While "else" seems to mean little there. So I may like something similar for Python 3.x (or the removal of the "else"). Bye, bearophile From colin.mcphail at mac.com Thu Mar 13 06:31:41 2008 From: colin.mcphail at mac.com (Colin Mcphail) Date: Thu, 13 Mar 2008 10:31:41 +0000 Subject: [pysqlite] [ANN] pysqlite and APSW projects moved References: Message-ID: <47d8f707$0$26041$88260bb3@free.teranews.com> On 2008-03-09 18:57:00 +0000, Gerhard H?ring said: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Gerhard H?ring wrote: >> [...] APSW >> ==== >> >> web: http://oss.itsystementwicklung.de/trac/apsw/ >> scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ > > That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ > > - -- Gerhard > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX > V7sH3uAskDDNBuxYG34vExI= > =IXOx > -----END PGP SIGNATURE----- I'm getting 404 Not Found for the 'corrected' apsw web page URL. Also, the subversion URL doesn't seem right either: $ svn co http://initd.org/svn/pysqlite/apsw/trunk/ apsw svn: PROPFIND request failed on '/svn/pysqlite/apsw/trunk' svn: PROPFIND of '/svn/pysqlite/apsw/trunk': 403 Forbidden (http://initd.org) Regards, -- CMcP -- Posted via a free Usenet account from http://www.teranews.com From gherzig at fmed.uba.ar Mon Mar 3 08:15:48 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 03 Mar 2008 10:15:48 -0300 Subject: compiling plpython compilation error Message-ID: <47CBFA04.30300@fmed.uba.ar> Hi all. Im having a hard time trying to compile the plpython package. This is the error make gives me: gherzig at vdb:/usr/local/src/postgresql-8.2.5/src/pl/plpython> make gcc -O2 -Wall -Wmissing-prototypes -Wpointer-arith -Winline -Wdeclaration-after-statement -Wendif-labels -fno-strict-aliasing -fpic -shared -Wl,-soname,libplpython.so.0 plpython.o -L/usr/lib/python2.5/config -L../../../src/port -lpython2.5 -lpthread -ldl -lutil -lm -Wl,-rpath,'/usr/lib/python2.5/config' -o libplpython.so.0.0 /usr/lib64/gcc/x86_64-suse-linux/4.2.1/../../../../x86_64-suse-linux/bin/ld: /usr/lib/python2.5/config/libpython2.5.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/lib/python2.5/config/libpython2.5.a: could not read symbols: Bad value collect2: ld returned 1 exit status make: *** [libplpython.so.0.0] Error 1 This runs on OpenSuse 10.3. python 2.5 postgres 8.2.5 ( and 8.3.0) Any clues? Thanks! Gerardo From vogelel at stinternet.net Sat Mar 29 17:33:12 2008 From: vogelel at stinternet.net (linda vogele) Date: Sat, 29 Mar 2008 15:33:12 -0600 Subject: Python vs. Perl, which is better to learn? Message-ID: <000701c891e4$7e03d310$0201a8c0@Linda> 4332951 -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Sun Mar 23 20:42:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 17:42:21 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: On Mar 23, 8:01 pm, QS wrote: > Hi to all! > I am new to python, and I encountered a weird problem. > > Here is my code > > ##########>8#################### > #!/usr/bin/python > # Filename: objvar.py > class Person: > '''Represents a person.''' > > population = 0 > #sex = 'F' > #age = 22 > # It is vague here: is this variable going to be a class, or > object, variable > > def __init__(self, name, sex): > '''Initializes the person's data.''' > self.name = name > self.sex = sex > print '(Initializing %s )' % self.name > # When this person is created, he/she > # adds to the population > Person.population += 1 > > def __del__(self): > '''I am dying.''' > > print '%s says bye.' % self.name > Person.population -= 1 > if Person.population == 0: > print 'I am the last one.' > else: > print 'There are still %d people left.' % > Person.population > > def sayHi(self): > '''Greeting by the person. > > Really, that's all it does.''' > > self.age = 25 > print 'Hi, my name is %s, and I am %s, and I am age %d ' % > (self.name, self.sex, self.age) > > def howMany(self): > '''Prints the current population.''' > if Person.population == 1: > print 'I am the only person here.' > else: > print 'We have %d persons here.' % Person.population > > swaroop = Person('Swaroop', 'M') > swaroop.sayHi() > swaroop.howMany() > kalam = Person('Abdul Kalam', 'M') > kalam.sayHi() > kalam.howMany() > cathy = Person('Catherine', 'F') > cathy.sayHi() > cathy.howMany() > swaroop.sayHi() > swaroop.howMany() > > ############# 8< ######################### > > When I run this script, I got the following exception: > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xb7d8ac6c>> ignored > > To to newcomer like me, this message doesn't make much sense. What > seems weird to me is that, if I change the variable cathy to something > else, like cath, or even cat, then the script will finish gracefully. > Why "cathy" is not liked?!! > > Some of you may have recognized that the code is derived from a sample > code in Swaroop's "A byte of python". > > My python is of version 2.5.1, on Ubuntu. That's really weird... it's reproducible on Windows too. It doesn't make any sense why the name of the variable would make a difference. My guess is you hit some kind of obscure bug. George From guillermo.listas at googlemail.com Thu Mar 6 07:10:47 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Thu, 6 Mar 2008 04:10:47 -0800 (PST) Subject: Checking if a variable is a dictionary Message-ID: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Hello, This is my first post here. I'm getting my feet wet with Python and I need to know how can I check whether a variable is of type dictionary. Something like this: if isdict(a) then print "a is a dictionary" Regards, Guillermo From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 18:18:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 23:18:50 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <13suaiq5n02g015@corp.supernews.com> On Wed, 05 Mar 2008 14:51:04 -0800, castironpi wrote: > Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a) > is also in it, and maps to the same object? It would take you approximately five seconds to answer that question for yourself. >>> D = {(1,2): "x"} >>> D[(2,1)] Traceback (most recent call last): File "", line 1, in KeyError: (2, 1) You've already been plonked by one long-time regular today. Are you aiming to get plonked by *everybody*? http://en.wikipedia.org/wiki/Plonk -- Steven From jeffrey at fro.man Thu Mar 20 11:12:51 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 20 Mar 2008 08:12:51 -0700 Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: <13u4vnjbgphfr61@corp.supernews.com> Giampaolo Rodola' wrote: > I mainly need to temporarily impersonate another user to > execute a command and then come back to the original user. If the script is run as root, you can freely impersonate other users with the os.seteuid() and os.setegid() methods. If the script is not run as root (either directly or through sudo, as suggested by other posters), then perhaps it should be. Jeffrey From danb_83 at yahoo.com Sun Mar 30 13:38:01 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 30 Mar 2008 10:38:01 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> <87od8w7aws.fsf@physik.rwth-aachen.de> Message-ID: On Mar 30, 5:40 am, Torsten Bronger wrote: > Hall?chen! > > Bjoern Schliessmann writes: > > Lie wrote: > > >> Ah yes, that is also used (I completely forgot about that one, my > >> math's aren't that sharp anymore) and I think it's used more > >> frequently than ><. > > > Where did you read that (I mean, which country)? I've never seen > > this sign in any german or english book on > > mathematics/physics/engineering I saw. > > Maybe he means "?". > > >> but my argument was that no math book use != or <> (except in > >> math for programmers). > > > That's true. Personally, I don't ever use "a!=b" in favor of "not > > a==b". > > As a side note, I've always found == rather ugly. I'd prefer to > have = for both purposes. The earliest versions of Python *did* use = for both purposes. > The constructs that wouldn't work anymore > are rare as far as I can see (and possibly there are even > workarounds). The construct a = b == c could be rewritten as a = (b = c). From bearophileHUGS at lycos.com Thu Mar 20 09:11:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 20 Mar 2008 06:11:41 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: <7xy78dg79e.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > Python needs more stuff in its stdlib, not less. > If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard > distro. If that happens (i.e. some new toolkit is brought in and > declared to be the standard) then it might be ok to drop Tkinter but > it certainly shouldn't be dropped without a replacement. If Tkinter is removed from the std lib, then I think another simple GUI toolkit has to be added to replace it. I have appreciated Wax in the past, it works with Wx and is rather easy. It's a dead software now, but it can be improved. It can be almost as easy as Tk, and it shows that Wx can be used with a much better API. Something like gazpacho (http://gazpacho.sicem.biz/ ) can be created for Wax too, and it can be added to the std lib. Bye, bearophile From mensanator at aol.com Sun Mar 23 00:42:44 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 22 Mar 2008 21:42:44 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> <13ubn5ue821ak7e@corp.supernews.com> Message-ID: <65b2d722-9e4c-4dc8-948a-3197deeeb5b6@e67g2000hsa.googlegroups.com> On Mar 22, 11:29?pm, Steven D'Aprano wrote: > On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > > On 22 Mar, 23:42, 7stud wrote: > > >> Beginning programmers in grades 9-12 are not going to understand issues > >> like that, and it would be a mistake to try and introduce them. > >> Beginning programmers should be concentrating their efforts on learning > >> the syntax of a language and basic constructs like for-loops and if > >> statements. > > > Yes. And because Python is a "scripting language" > > Python is a programming language. It can be used for scripting, but > that's not all it can do. Describing it as a "scripting language" is like > describing a fully-equipped professional kitchen as "a left-over warming > room". Sure, but then again, some are chefs, others merely cooks and yet others just warm leftovers. > > -- > Steven From python.list at tim.thechases.com Wed Mar 19 06:12:30 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 05:12:30 -0500 Subject: PODCasts In-Reply-To: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> References: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> Message-ID: <47E0E70E.4080807@tim.thechases.com> > I really should say net cast as I think it's a better term ;) > > Does anyone have any recommended net casts on Python, or programming in > general? Well, though it's been a while since I last noticed a new release (last one dated Dec '07), the archives of "Python 411" should all be online: http://www.awaretek.com/python/ -tkc From python at rcn.com Tue Mar 4 15:09:45 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 Mar 2008 12:09:45 -0800 (PST) Subject: for-else References: Message-ID: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> [BearOphile] > So far in Python I've almost hated the 'else' of the 'for' loops FWIW, I'm very happy with for-else. Most of the time, you don't need it, but when you do, it beats the heck out of doing silly tricks with flags. The primary use case is searching a container: prep_tasks() for item in container: if predicate(item): found_tasks() break else: not_found_tasks() follow_up_tasks Raymond From paddy3118 at googlemail.com Sat Mar 29 14:01:40 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 29 Mar 2008 11:01:40 -0700 (PDT) Subject: deleting a line from a file References: Message-ID: On Mar 29, 11:13 am, eMko wrote: > Hello, > > In Perl, using a Tie::File module I can easily and comfortably delete > a line from the middle of a text file: > > my @file; > open(DATA, "+<:encoding(utf8):raw" , "file.txt") or return 0; > tie @file, 'Tie::File', \*DATA or return 0; > splice(@file, $_[0], 1); > untie @file; > close DATA; > > (when the first argument of the function ($_[0]) is a number of the > line which should be deleted) > > Is there some easy way how to delete a line from a middle of a file in > Python? > > Thanks a lot > eMko Module fileinput has\; Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup='.' is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. - Paddy. From tjreedy at udel.edu Thu Mar 13 17:20:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Mar 2008 17:20:14 -0400 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net><13sc3b0g7gud892@corp.supernews.com> Message-ID: "Antoon Pardon" wrote in message news:slrnfthp1s.61k.apardon at rcpc42.vub.ac.be... | On 2008-02-28, Steven D'Aprano wrote: | > On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: | > | >> Hi! | >> Can somebody of you make me a sample how to define a function based on | >> "call by reference" ??? | > | > Python doesn't do call by reference. Nor does it do call by value. Please | > pay no attention to anyone who says it does. | | Whatever python has for a calling convention, it is close enough that | naming it "call by reference" gives people a reasonable idea of what | is going on. But it is also different enough to mislead people. | AFAICS people don't have a problem with understanding the calling | convention of python. They have a problem understanding the | assignment semantics. The calling convention is cross-namespace assignment. So one cannot understand calls without understanding assignment. tjr From gh at ghaering.de Sun Mar 9 14:39:41 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 09 Mar 2008 19:39:41 +0100 Subject: [ANN] pysqlite and APSW projects moved Message-ID: <47D42EED.8070107@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dear pysqlite users! I've moved both the pysqlite and APSW project to new homes. pysqlite ======== web: http://oss.itsystementwicklung.de/trac/pysqlite aka http://pysqlite.org/ scm: pysqlite now uses a Mercurial repository http://oss.itsystementwicklung.de/hg/pysqlite/ APSW ==== web: http://oss.itsystementwicklung.de/trac/apsw/ scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ Both pysqlite and APSW have a common mailing list at http://itsystementwicklung.de/cgi-bin/mailman/listinfo/list-pysqlite Existing subscribers that have not set the "nomail" flag have been moved to the new list already. - -- Gerhard PS: Because of spam problems on the old Trac, I've patched AccountManager so that you will now have to verify your human-ness with a captcha when you register an account. The old Trac accounts were not moved on purpose to avoid spam. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH1C7tdIO4ozGCH14RAjAhAKCmxm+rKkjxMalCkH2Wjs88raxuCACgiV4B XJq+YweOK0Zh1IWHLkrl3LI= =b6zE -----END PGP SIGNATURE----- From ptmcg at austin.rr.com Wed Mar 5 17:14:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 5 Mar 2008 14:14:23 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> Message-ID: <750087f0-2af9-4323-b6e1-e22c7b702fc3@8g2000hse.googlegroups.com> On Mar 5, 3:49?pm, castiro... at gmail.com wrote: > > Classes and modules are really similar. ?In Python they're really > *really* similar. > > Actually, at this point, that observation may have more of a > subjective component than I'm used to asserting. ?I pause here for > corroboration and others' perspectives. ?Aren't they? If all you use classes for is for the purpose of a namespace, and all of the methods in the class are just staticmethods, then you have used a class to replicate a module, and they aren't just really, *really* similar, they are the pretty much the same (at least BEHAVIORALLY speaking). But you can't do this: import Zmodule zobject = Zmodule() If you are really using the OO model, and creating instances of classes, then you *have* to use a class, a module wont cut it. I'd say, the less you use a class as an instance factory, the more similar that class is to a module. And you can't do this: class Zclass: import Zclass If Zclass is not defined in your local script, you *have* to know what module it is in, as in: from zpackage.zmodule import Zclass I have seen modules compared to classes that implement a Singleton pattern. In this case, a class is being used in an intentionally degenerate way, such that it creates only one instance. When doing this in Python, one has the choice of replicating the standard pattern with a class, or more simply, just using a module. (Python's language/ object model also permits another option, usually referred to as the Borg implementation, in which many Python names bind to many Python instances, but all share the same underlying object state. But this is tangential to your question.) In general I would say the similarity is a behavioral one, an artifact of the language implementation. Modules are for code packaging and namespace definition, classes are for type definition and object modeling. For more discussions about how similar classes are to modules, you might google for "Python singleton". -- Paul From zugnush at gmail.com Thu Mar 27 17:58:19 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Thu, 27 Mar 2008 14:58:19 -0700 (PDT) Subject: copy file over LAN References: Message-ID: <1d8447b4-26a1-40ae-b11c-20d5a6a40e3f@m34g2000hsc.googlegroups.com> On Mar 27, 6:48 pm, Teja wrote: > On Mar 27, 8:34 am, Astan Chee wrote: > > > > > Hi, > > I have afileon another machine on the localnetwork(my machine and > > local machines are on windows) and I want tocopyit locally. Now the > > machine requires authentication and when I try to do a > > import shutil > > shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') > > and it gives me a IOError: [Errno 13] Permission denied: error, which I > > expect. How do I provide authentication tocopythisfile? > > Thanks for the help. > > Cheers > > Astan > > > -- > > "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." > > > Animal Logichttp://www.animallogic.com > > > Please think of the environment before printing this email. > > > This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. > > Hi, > > Is the folder where the file is present i.e. "temp" in your case, > shared???? > Can you share it and try it?? > > I tried this way and it worked! > > import shutil > > shutil.copyfile(r'\\129.124.66.112\Samplesharedfolder\samplefile.txt', > r'C:\\Test\\temppp.txt') > > Try this way and let me know I just discovered that this works for python upload into sharepoint too :-) From brian at briansmith.org Thu Mar 13 09:33:47 2008 From: brian at briansmith.org (Brian Smith) Date: Thu, 13 Mar 2008 06:33:47 -0700 Subject: Socket Performance In-Reply-To: References: Message-ID: <004b01c8850e$de8084a0$4001a8c0@T60> sleddd at gmail.com wrote: > Sent: Wednesday, March 12, 2008 9:47 PM > To: python-list at python.org > Subject: Socket Performance > > Can anyone explain why socket performance (throughput) varies > depending on the amount of data send and recv are called with? > > For example: try creating a local client/server (running on the same > computer) where the server sends the client a fixed amount of data. > Using method A, recv(8192) and sendall( ) with 8192 bytes > worth of data. Do this 100 times. Using method B, recv(1) and > sendall( ) with 1 byte worth of data. Do this 819200 times. > > If you time both methods, method A has much greater > throughput than method B. Why is it faster to drink a liter of water a cupful at a time than to drink it out of an eyedropper? - Brian From mnordhoff at mattnordhoff.com Wed Mar 26 05:00:40 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 26 Mar 2008 09:00:40 +0000 Subject: Strange loop behavior In-Reply-To: <47EA0ABB.3030804@mydeskfriend.com> References: <47EA0ABB.3030804@mydeskfriend.com> Message-ID: <47EA10B8.8080100@mattnordhoff.com> Gabriel Rossetti wrote: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) FWIW, you could do it like this to avoid duplicating that line of code: while True: d = f.read(DEFAULT_BUFFER_SIZE) if not d: break file_str.write(d) Some people would also compress the whitespace a bit: while True: d = f.read(DEFAULT_BUFFER_SIZE) if not d: break file_str.write(d) (I'll comment on your Unicode issues in a minute.) -- From http Fri Mar 21 00:19:05 2008 From: http (Paul Rubin) Date: 20 Mar 2008 21:19:05 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> <7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: <7x63vgd806.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > What would be amazing would be a algorithm that could rewrite the > external-arrays Haskell/Python code to the equivalent of the in-place C > code. I don't think JHC (a fancy optimizing Haskell compiler) goes quite that far, but it compiles Haskell to C code that looks pretty much the same as imperative code that a careful programmer would write. > Can one even write such an equivalent in Haskell? (If it is purely > functional, then no, though one obviously can in Python.) Yes, you can write in an imperative styld while staying purely functional. The trick is to notice that b = f(a) c = g(b) d = h(c) ... requires evaluating f,g,h in exactly that order. So you can write sequential code as a bunch of nested function calls that the compiler optimizes away. Haskell has syntactic support for this, so the code you'd write looks somewhat C-like: do { b <- f a; c <- g b; d <- h c } but it is actually even cooler than that (complicated to explain so I won't try here). The result is that you really insist, you can code an imperative quicksort that looks about the same as the C one and compiles to about the same machine code, but is fully typesafe and polymorphic. From gagsl-py2 at yahoo.com.ar Mon Mar 3 01:55:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 04:55:09 -0200 Subject: class object interface document References: Message-ID: En Mon, 03 Mar 2008 04:37:38 -0200, Neil.Fang.CN escribi?: > On Mar 2, 6:26?pm, "Gabriel Genellina" wrote: >> En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN >> ? >> escribi?: >> >> > Where can I find the Python class object interface document, such as >> > struct PyClassObject, PyClass_New()? Thanks! >> >> PyClass_* and PyInstance_* are for old-style classes and instances ? >> respectively, and will disappear in v3.0. >> PyInstance is in the section 7.5.2 in the Python/C API Reference >> Manual; I?don't find any documentation on PyClass itself. > Thanks for your reply. > What is the counterpart in v3.0? New style classes, that exist since v2.2 http://www.python.org/doc/newstyle/ -- Gabriel Genellina From castironpi at gmail.com Sat Mar 1 22:12:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 19:12:01 -0800 (PST) Subject: How to subclass a built-in int type and prevent comparisons References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> Message-ID: On Mar 1, 2:58 pm, Michael Torrie wrote: > castiro... at gmail.com wrote: > > Tell Wall. But why not [ 2, 3 ]>= 2? Back to your question, another > > option is to not subclass. > > Umm, no. You need to actually read the posts before you respond to > them. His question was whether or not to throw an exception in this > case. He's *already* subclassed the type. > > The first question was, should he throw an exception. And given that > Python 3.0 will throw exceptions, he is justified in throwing exceptions > as well. I have no idea what he would lose by throwing an exception. I > have no idea how else he would do this. > > His second question was, would his code for implementing __gt__ (and > throwing exceptions) be likely efficient. That I cannot say. Point taken. The is-a vs. has-a distinction was what I was looking at. Is it more work to the OP to disable the things in Int he doesn't want, or to enable those he does? On a tangent (you were alerted): A horse with three legs is a horse. A square with three sides is a square. A cup of coffee with no bottom is not a cup. If he doesn't throw an exception, he can compare to an arbitrary point, class-static, etc., post a message to a queue awaiting further instructions and block to its return, fire a synchronous callback, pause for user input, remove a certain element and set an op-abort flag, return a special value ( NoCompare= object() ), NaN, INF, &c., upgrade one or both operands, vary the behavior with class or instance, callback a coroutine omitting the point and assessing later, add it to a list of problem data to be treated by a superior, or take a special lunch break, after which the right-hand value is guaranteed to conform. You can try casting the RHV right-hand value to the required type too. Originally, exceptions came about as ways to respond to requests of a class hierarchy that fail to evaluate for the derived type, such as Ostrich().fly(), but expanded to include logic flow: do this this and this, except when file doesn't close correctly. In Python 1.0, a lot of classes set methods upon construction: init: self.data= data; self.__gt__= self.data.__gt__, and perhaps subclass that. Or move to C. In the trade, customers don't care what code made the program they bought. The company doesn't care what code made the program. Reinventing the wheel is cheap for certain wheels. Hallway full of doors; close some to get the product out sooner. What might we want down the road? What's down the road? Who is? In the hobbies, you can see an elaborate mixin to simplify work later, just for practice, or for the Zen-and-the art, like doing puzzles. class SpecialInt( Selective, int ): meths= Selective.numerics( int ) onlyif= [ partial( is_, int ), or_, partial( is_, SpecialInt ) ] It just costs performance-- product performance, even if not production team performance. from functools import partial from operator import is_, is_not assert partial( is_, int )( type( 2 ) ) assert partial( is_not, int )( type( 2.5 ) ) But: >>> class C: C ... Traceback (most recent call last): File "", line 1, in File "", line 1, in C NameError: name 'C' is not defined Can we have access to classes in their definitions? class C: delayed( 'C' ) works fine. If we don't want to permit calling a function on a half- executed class, then postcreator(or something) would have to be syntax. Class decorators can do it: * current= Current() @current.delay class SpecialInt: onlyif= [ partial( is_, int ), or_, partial( is_, current ) ] Similarly: * current= Current() class SpecialInt: onlyif= [ partial( is_, int ), or_, partial( is_, current ) ] current.delayedeval( SpecialInt ) But it starts to get really tangled: current= Current() @current.delay class SpecialInt: onlyif= [ partial( is_, int ), or_, current.partial( partial, is_, current ) ] where current.partial returns a delegation object that replaces current with the class current.delay wraps. If you don't want current to delegate too, then: current= Current() @current.delay class SpecialInt: onlyif= [ partial( is_, int ), or_, current.partial( partial, is_, current.ref ) ] may be next best. But all this is just to save two lines somewhere where you're allowed to use a custom wrap-in class, since Current is borderline library, and don't even mention 'standard'. However if it saves ten seconds in a coding competition, or captures the flash of an idea you get at 2 a.m. (make that 4 for the kids), then it's worth keeping around. import obscure. And class SpecialInt: onlyif= [ partial( is_, int ) ] SpecialInt.onlyif.extend( [ or_, partial( is_, SpecialInt ) ] ) sure is practical. From castironpi at gmail.com Mon Mar 31 19:31:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 16:31:25 -0700 (PDT) Subject: python persistence Message-ID: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> Can you have a Python object stored entirely on disk? From deets at nospam.web.de Thu Mar 27 10:19:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 15:19:11 +0100 Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> Message-ID: <651onqF2dripdU1@mid.uni-berlin.de> > Ok, i know this. The one that i do not know, is if, let'say, in 2 > years it will be ready for seriously development, PyPy will aim to > "replace" CPython entirely ?? We are talking about an whole new > distribution ? Most certainly not. It's the goal of each language to finally become self-hosted, and I hope we see that for python. But that's nothing that will happen anytime soon (soon being at least half a decade), and most probably not for the 2.x-versions. > As for psyco, are there any alternatives to use now ? Nope, but I heard through the grapevine that while it won't be supported for all times to come, a new version is in the making. But ultimately, the author says that the approach is flawed, so at *some* point it will be discontinued. But that could be said about nearly everything, couldn't it? Diez From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:00:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:00:18 -0300 Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> <17e0f94a-555c-40c7-8dd6-90c6d9c0b633@a23g2000hsc.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 12:25:55 -0300, escribi?: > On Mar 28, 11:14 am, "Gabriel Genellina" > wrote: >> En Fri, 28 Mar 2008 11:51:10 -0300, escribi?: >> >> > How can this module access global state (not per-thread state) ? >> > It needs to create a singleton. >> >> C global variables are global, not per-thread. > > Yes, but they get initialized once per-thread, therefore my singleton > gets > created multiple times. Either don't call the initialization from every thread, or guard it with something like: a_big_object my_object = NULL; ... if (my_object!=NULL) { ...initialize object... my_object = ...; } That's a pretty standard idiom I think. -- Gabriel Genellina From craigtrucko at gmail.com Tue Mar 25 22:00:41 2008 From: craigtrucko at gmail.com (craigtrucko) Date: Tue, 25 Mar 2008 19:00:41 -0700 (PDT) Subject: 4gb USB Flash drive for $14.49 Message-ID: <1b8ba3b8-f71b-464f-9bec-33c6fc7a2e09@p73g2000hsd.googlegroups.com> Hey Guys, dealsusb.com has a 4gb USB Flash drive for $14.49 Free Shipping and no rebates. Now we can backup our smaller Databases onto a USB really cheap. craig From mail at timgolden.me.uk Sun Mar 16 10:54:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:54:16 +0000 Subject: Spaces in path name In-Reply-To: <47DD2EF3.1080900@timgolden.me.uk> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> Message-ID: <47DD3498.9000901@timgolden.me.uk> Tim Golden wrote: > What I haven't investigated yet is whether the additional flags > your example is passing (shell=True etc.) cause the main Popen > mechanism to take a different path. Sure enough, passing shell=True -- which is probably quite a rare requirement -- causes the code to change the call from "a.exe b.doc" to '%COMSPEC% /c "a.exe" "b.doc"'. The quoting rules (from cmd /?) are slightly involved but I can't see at first why this shouldn't work. However it clearly doesn't so I'll try to put together either a patch to the subprocess code or to the docs warning of the behaviour. I think that, in general, you need to pass shell=True far less often that you might imagine. (Possibly only for internal commands like dir, copy etc.). TJG From gagsl-py2 at yahoo.com.ar Fri Mar 28 10:30:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 11:30:20 -0300 Subject: simple web-server References: Message-ID: En Fri, 28 Mar 2008 08:53:15 -0300, Pavol Murin escribi?: > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). Ajax is mostly a client thing, any server would work. > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. How many requests/minute you expect to handle? From your description, not many, I think. So even CGI would be OK, and I'd choose the easiest server to configure and setup. TinyWeb www.ritlabs.com is the smallest web server I know of (Windows only, unfortunately), and almost setup-free. Ensure that .py scripts are executable, place them in a cgi-bin subdirectory, start tiny.exe and you're done. > So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed) Don't make the release dates fool you. The HTTP specs haven't changed in years, once you have a functional server, there is no need to keep changing it. > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? Running CGIHTTPServer takes 3 or 5 lines of code, and that's all to it. You don't have to touch the server itself. You write cgi scripts and put them somewhere so the server can find and execute them when requested; that's all. So you have to look for CGI examples, not server examples :) -- Gabriel Genellina From dotancohen at gmail.com Thu Mar 6 02:11:47 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 6 Mar 2008 09:11:47 +0200 Subject: Why """, not '''? In-Reply-To: <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> Message-ID: <880dece00803052311p181c753cx9ae8338e954f9290@mail.gmail.com> On 06/03/2008, Dan Bishop wrote: > On Mar 5, 7:24 pm, Matt Nordhoff wrote: > > > Steven D'Aprano wrote: > > > Surely it would depend on the type of text: pick up any random English > > > novel containing dialogue, and you're likely to find a couple of dozen > > > pairs of quotation marks per page, against a few apostrophes. > > > > > That's an idea... Write a novel in Python docstrings. > > > Or better yet, write in Python syntax. > > > assert len([man for man in now_alive() if > man.remembers(datetime.date(1775, 4, 18))]) <= HARDLY > > lantern_count = {'land': 1, 'sea': 2}.get(british.location(), 0) > n_ch_twr.hang(Lantern() for _ in xrange(lantern_count)) > > if lantern_count: > for village in middlesex: > ride_thru(village) > spread_alarm(village) > That looks ported from lolcode. http://lolcode.com/ Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From gagsl-py2 at yahoo.com.ar Sat Mar 29 21:42:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 22:42:30 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> Message-ID: En Sat, 29 Mar 2008 20:54:36 -0300, escribi?: > I tried to add the directory "//simplejson" to my sys.path > in the interpreter, hoping that the call to import simplejson would > work if the dir was there, even though simplejson.py did not exist is > that dir, but the encoder, decoder, jsonfilter and scanner .py files > were all there. > > My problem is that the call "import simplejson" fails. How can I make > that call work? simplejson is a package (a directory with an __init__.py), not a module; don't look for simplejson.py Its *parent* directory must be in sys.path for Python to find it. Try copying the simplejson directory below site-packages (which should be already in sys.path) -- Gabriel Genellina From jwbrown77 at gmail.com Thu Mar 27 17:40:58 2008 From: jwbrown77 at gmail.com (jwbrown77 at gmail.com) Date: Thu, 27 Mar 2008 14:40:58 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: On Mar 27, 1:53?pm, "Gabriel Genellina" wrote: > En Thu, 27 Mar 2008 17:37:33 -0300, Aaron Watters ? > escribi?: > > > > >> "this";"is";"a";"test" > > >> Resulting in an output of: > > >> ['this', 'is', 'a', 'test'] > > >> However, if I modify the csv to: > > >> "t"h"is";"is";"a";"test" > > >> The output changes to: > > >> ['th"is"', 'is', 'a', 'test'] > > > I'd be tempted to say that this is a bug, > > except that I think the definition of "csv" is > > informal, so the "bug/feature" distinction > > cannot be exactly defined, unless I'm mistaken. > > AFAIK, the csv module tries to mimic Excel behavior as close as possible. ? > It has some test cases that look horrible, but that's what Excel does... ? > I'd try actually using Excel to see what happens. > Perhaps the behavior could be more configurable, like the codecs are. > > -- > Gabriel Genellina Thank you Aaron and Gabriel. I was also hesitant to use the term "bug" since as you said CSV isn't a standard. Yet in the same right I couldn't readily think of an instance where the quote should be removed if it's not sitting right next to the delimiter (or at the very beginning/end of the line). I'm not even sure if it should be patched since there could be cases where this is how people want it to behave and I wouldn't want their code to break. I think rolling out a custom class seems like the only solution but if anyone else has any other advice I'd like to hear it. Thanks again for the help. From yennes at gmail.com Thu Mar 20 06:24:49 2008 From: yennes at gmail.com (Dravidan) Date: Thu, 20 Mar 2008 03:24:49 -0700 (PDT) Subject: backslash in reading bytes Message-ID: <560a5033-576f-4876-91cf-08276985b308@s50g2000hsb.googlegroups.com> I am trying to read some byte data as a string then using a library to convert them a code: >>>reader = csv.DictReader(open('table.txt')) >>>def eleFind(value): >>> for row in reader: >>> if row['byteCode'] == value: >>> print row['Element'] >>> return >>> else: >>> print "No Match Found:" >>>eleFind('\x00\x00') My table contains: \x00\x00,0000 \x01\x00,0000 ...... The program errors out. How can I fix/overide this backslash issue. From jeff at schwabcenter.com Sat Mar 22 14:40:43 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 11:40:43 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. Linux and Python are a nearly ideal combination for this. Be aware that at some point, you will likely have to dig into C, the primary language used to implement both Linux and Python. From tmp1 at viltersten.com Tue Mar 4 15:05:27 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Tue, 4 Mar 2008 21:05:27 +0100 Subject: SV: Polymorphism using constructors In-Reply-To: <63346uF25gigqU1@mid.uni-berlin.de> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> Message-ID: <635ndjF2551ajU1@mid.individual.net> "Diez B. Roggisch" skrev i meddelandet news:63346uF25gigqU1 at mid.uni-berlin.de... >K Viltersten schrieb: >> I'm writing a class for rational numbers >> and besides the most obvious constructor >> >> def __init__ (self, nomin, denom): >> >> i also wish to have two supporting ones >> >> def __init__ (self, integ): >> self.__init__ (integ, 1) >> def __init__ (self): >> self.__init__ (0, 1) >> >> but for some reason (not known to me at >> this point) i get errors. My suspicion is that it's a syntax issue. > > "errors" is not much of an error-description. That's what stacktraces are > for. I assumed that the error was so obvious to a seasoned Pytonist (Pythoner?) that a trace didn't matter. Your help below proves it. :) Nevertheless, i'll be careful in the future and make sure to post the traces too. Sorry. > Apart from that, you won't succeed with the above. Python has no > signature-based polymorphism. Instead, you use default arguments, like > this: > > def __init__(nomin=0, denom=1): > ... Thank you. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From fn681 at ncf.ca Fri Mar 21 10:09:39 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:09:39 -0500 Subject: Improving datetime In-Reply-To: References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <47E3C1A3.6050608@ncf.ca> Nicholas F. Fabry wrote: > On Mar 19, 2008, at 16:30, Christian Heimes wrote: > >> Nicholas F. Fabry schrieb: >>> This is a query for information as to how to proceed. I am not a >>> professional programmer, but I use Python a great deal to help me in >>> my main job, which involves designing schedules for a global >>> airline. As such, I use datetime (and dateutil) extensively, and >>> after much use, I have come to some conclusions about their utility, >>> and how to improve them. Some of these changes are quite minor and >>> would result in a large increase in utility (low hanging fruit), >>> while some changes are major, and would result in less obvious >>> benefits - but these changes would increase the 'Python Zen' of them. >>> So - where should I propose these changes? Here? python-dev? >>> Should I write up a full PEP or should I just give a more informal >>> outline with code samples? I would volunteer to help >>> maintain/improve datetime, but I don't speak C at all, >>> unfortunately, and datetime appears to be in C. >> >> Please write a detailed but not too long proposal to the Python ideas >> mailing list. The proposal should explain how you like to improve the >> datetime module. But *please* don't write a novel. You'll get more >> attention when the signal to noise ratio is high. A bullet list of >> features is easier to read than a long text block. >> > > Thank you for the prompt response and suggestion! I am writing up a > proposal presently. There are, however, two broad category of changes - > the 'easy' changes, which could be accomplished with little additional > effort, and the 'hard' changes, which would require significant > reworking of the datetime class (or a wrapper around it). I was going > to break my proposal up into two parts, the easy part and the hard > part. Does that sound like a good idea? Or should I unify the two? > The prime purpose of all the changes, easy and hard, is to make timezone > handling accurate and clear, reduce and make clearer the (application > programmer) code required to use them, and give more informaton to the > programmer about errors, not silently assume something and pass them. > > I have to sign up for that mailing list - I will do so, and submit my > ideas there. > > Please clarify how long a novel is? The problem with the modules are > not bugs, they are problems with real world use scenarios that result in > inescabably ugly code without improvements to the module - so the > explanations involve code samples and use cases... so they may be > 'long'. Could you suggest a maximum number of (70 char) lines, or an > example of an overly long proposal? > > >> I'm a core developer and I may be interested in mentoring your >> proposal. I can guide you through the process, review code and commit it. >> > > Thank you very much for the offer - I greatly appreciate it. I must > admit, my motivation is because Python made programming so much fun for > me again (my first machine was a Sinclair ZX80, long, long ago), and I > want to improve this part of the language so datetime calculations are > clean and neat (like the rest of Python) and don't force programmers to > manually go through what the library should do for them. > > >> Yes, the datetime module is written in C. But we may move the C code >> to _datetime and create a facade module in Python. >> > > That would be excellent for me, because the underlying datetime routines > work correctly and quickly; it's the 'topmost' layer that needs to be > improved to do the right thing. And, I could then actually > write/maintain the Python code in the facade module, rather than request > someone else 'do it for me' in C. > > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but > calculate/compare in UTC. > > - Raise exceptions when an illegal or ambiguous datetime is instantated. > > > Thank you again, > > Nick > > > > > > >> Christian Nick, You might consider adding the Julian date (http://en.wikipedia.org/wiki/Julian_date). I had a crack at this a while ago but didn't seem to get quire the right result, using the ACM algorithm. I seemed to be a day out at the BC/AD divide. Colin W. > From mccredie at gmail.com Mon Mar 3 13:47:09 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 3 Mar 2008 10:47:09 -0800 (PST) Subject: Inheritance issue... References: Message-ID: <914ade29-c8b1-4632-bd73-be60f3e2b349@s12g2000prg.googlegroups.com> On Mar 3, 9:37 am, MooMaster wrote: > I'm trying to use inheritance to create a simple binary tree, but it's > not going so well... here's what I pull from the documentation for > super() > "super( type[, object-or-type]) > > Return the superclass of type. If the second argument is omitted the > super object returned is unbound. If the second argument is an object, > isinstance(obj, type) must be true. If the second argument is a type, > issubclass(type2, type) must be true. super() only works for new-style > classes. > A typical use for calling a cooperative superclass method is: > > class C(B): > def meth(self, arg): > super(C, self).meth(arg) > " > > So here's what I do: > > class Node: > def __init__(self, val=0, prnt = None): > self.value = val > self.parent = prnt > > class Tree(Node): > def __init__(self, val=0): > self.root = super(Tree, self).__init__(val) > self.leftChild = None > self.rightChild = None > > def addChild(self, value): > if self.root == None: > self.__init__(value) > else: > n = self.root > while(n is not None): > if(n.leftChild == None and n.rightChild == None): > n.leftChild = Node(value, n) > elif(n.rightChild == None): > n.rightChild = Node(value, n) > else: > if(n.leftChild.leftChild is not None and > n.leftChild.rightChild is not None): > n = n.rightChild > else: > n = n.leftChild > > def printTree(self): > if self.root == None: > print "None" > else: > n = self.root > print n.value > while(n is not None): > if(n.leftChild is None): > print str(n.value) + "'s left child is None" > elif(n.rightChild is None): > print str(n.value) + "'s right child is None" > else: > if(n.leftChild.leftChild is not None and > n.leftChild.rightChild is not None): > n = n.rightChild > else: > n = n.leftChild > def main(): > play = Tree(1) > play.addChild(2) > play.addChild(3) > play.addChild(4) > play.addChild(5) > play.printTree() > > if __name__ == "__main__": > main() > > ...and here's what I get: > > Traceback (most recent call last): > File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 53, in > > main() > File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 45, in > main > play = Tree(1) > File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 8, in > __init__ > self.root = super(Tree, self).__init__(val) > TypeError: super() argument 1 must be type, not classobj > > Looks to me like the super(Tree, self)__init__(val) follows the > example in the documentation, but I may be a witch. Anyone know why > this doesn't work? Node should inherit from `object'. Unless you inherit from object you are using old-style classes, which do not derive from type and cannot use the super method. Example: class Node(object): Also, __init__ does not return anything, ever. This doesn't make sense: > self.root = super(Tree, self).__init__(val) When you call the __init__ method of a base class, it will operate on self. Example: >>> class CBase(object): ... def __init__(self, a): ... self.a = a ... >>> class C(CBase): ... def __init__(self, a, b): ... super(C, self).__init__(a) ... self.b = b ... >>> c = C(1,2) >>> c.a 1 >>> c.b 2 Doing things like self.__init__(val) doesn't make sense. Matt From cpgray at library.uwaterloo.ca Fri Mar 28 11:27:59 2008 From: cpgray at library.uwaterloo.ca (Chris Gray) Date: Fri, 28 Mar 2008 11:27:59 -0400 Subject: web application-level caching Message-ID: Is there a Python module comparable in functionality to the PEAR Cache_Lite package for PHP? I've been doing some Googling to little avail. I'm experimenting with Python CGI to learn various techniques at a low level and I'm adapting a model that uses PHP. Any info about application-level caching (or pointers to where to find such info) would be highly appreciated. Thanks, Chris From bockman at virgilio.it Mon Mar 3 11:12:20 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 3 Mar 2008 08:12:20 -0800 (PST) Subject: Import, how to change sys.path on Windows, and module naming? References: Message-ID: <820d6ac9-041a-4d8a-a444-d2978ad41ba4@p25g2000hsf.googlegroups.com> On 1 Mar, 20:17, Steve Holden wrote: > Jeremy Nicoll - news posts wrote: > > > > > Jeremy Nicoll - news posts wrote: > > >> If I understand correctly, when I import something under Windows, Python > >> searches the directory that the executing script was loaded from, then > >> other directories as specified in "sys.path". > > > Sorry to followup my own question, but I ran > > > ?for p,q in enumerate(sys.path): print p, q > > > and got: > > > 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms > > 1 C:\Program Files\~P-folder\Python25\Lib\idlelib > > 2 C:\WINDOWS\system32\python25.zip > > 3 C:\Program Files\~P-folder\Python25\DLLs > > 4 C:\Program Files\~P-folder\Python25\lib > > 5 C:\Program Files\~P-folder\Python25\lib\plat-win > > 6 C:\Program Files\~P-folder\Python25\lib\lib-tk > > 7 C:\Program Files\~P-folder\Python25 > > 8 C:\Program Files\~P-folder\Python25\lib\site-packages > > 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32 > > 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib > > 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin > > > Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip > > in their sys.path? ?What's the point of having a zip in the path? > > So that the files inside the zip can be imported as modules and > packsges, of course. > > > Also, looking in ?C:\WINDOWS\system32\ ? I don't actually have a file called > > python25.zip, but I do have one called ?python25.dll - so has something gone > > wrong in creation of sys.path? > > No. I'm not sure why the zip file is on there by default. > > regards > ? Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - I believe the answer is in how the new import protocol (PEP 302) works: when you install a new path handler in sys.import_hooks, this is called for each element of sys.path; the path handler has two options: either to raise ImportError, which means that cannot handle the specific path, or to return an object with the methods defined in the PEP, which means that the returned object - and only that one - will be used to import modules in the specific path. This means that only one path handler can be used for each element of sys.path. Therefore, if you want to add a path handler that does not interfere with the other ones, one way to do it is to add something in sys.path that is rejected by all path handlers except yours. I believe that python25.zip is that 'something' that is used by the zipimporter path handler, which allows to import directly from zip files. I did something similar in my toy experiment with the import hooks, half-believing that there was something I missed. Nice to see that the 'big guys' did the same trick :-) (unless of course I _did_ miss something and my guess is completely wrong; I should have done some experiment before posting, but I'm too lazy for that). Ciao ------- FB From wolf_tracks at invalid.com Sun Mar 2 21:57:40 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 03 Mar 2008 02:57:40 GMT Subject: Organizing Books in My Amazon Cart Message-ID: Anyone know of a way of listing all the books in my Amazon Shopping Cart--To Buy Latter? I have a considerable number, and working my way through the list is time consuming. Possibly someone has written a program to do it (Python, Perl, ...)? I have no idea if that's even possible. I figure this is one the largest NGs in my inventory, so maybe someone has thought about it, or can direct me to a more likely NG for the question. -- Wayne Watson (Nevada City, CA) Web Page: From http Tue Mar 18 17:52:59 2008 From: http (Paul Rubin) Date: 18 Mar 2008 14:52:59 -0700 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: <7xbq5br96s.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > I need to move a directory tree (~9GB) from one machine to another on > the same LAN. What's the best (briefest and most portable) way to do > this in Python? os.popen("rsync ...") From python.list at tim.thechases.com Sat Mar 29 18:13:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Mar 2008 17:13:16 -0500 Subject: What motivates all unpaid volunteers at Pycon? In-Reply-To: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> References: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> Message-ID: <47EEBEFC.6040600@tim.thechases.com> > I was wondering what motivated so many people to give so much to the > Python community. fear, surprise, ruthless efficiency, an almost fanatical devotion to the BDFL, and nice red uniforms. Oh... -tkc From newsgroup898sfie at 8439.e4ward.com Thu Mar 20 18:31:02 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Thu, 20 Mar 2008 18:31:02 -0400 Subject: putting text through pager In-Reply-To: <9suab5-jvs.ln1@ID-262785.user.uni-berlin.de> References: <9suab5-jvs.ln1@ID-262785.user.uni-berlin.de> Message-ID: <665bb5-cg2.ln1@ID-262785.user.uni-berlin.de> Michael Goerz wrote, on 03/20/2008 04:43 PM: > Hi, > > I'm trying to print some variable through a pager (i.e. 'less') on a > linux system. My attempt was this: > > > ====== snip here ====== > import subprocess > > def put_through_pager(displaystring): > less_pipe = subprocess.Popen(\ > 'less', shell=True, \ > stdin=subprocess.PIPE).stdin > less_pipe.write(displaystring) > less_pipe.close() > > def main(): > put_through_pager(longstring) > > > longstring = """ > Lorem ipsum dolor sit amet,... > http://www.lipsum.com/ > """ > > main() > > ====== snip here ====== > > That doesn't work however: first of all, it only flashes the text for a > fraction of a second, and secondly, after I run the program my terminal > is broken, not echoing whatever I type back to me. > > Any suggestions for putting text through a pager from Python? This is > strictly on a linux system, of course. > > Thanks, > Michael Using a tempfile seems to be a good solution: def put_through_pager(displaystring): (temp_fd, tempname) = tempfile.mkstemp(".mail") temp_fh = os.fdopen(temp_fd, "w") temp_fh.write(displaystring) temp_fh.close() os.system("less %s" % tempname) os.unlink(tempname) From testone at gmail.com Mon Mar 24 20:56:06 2008 From: testone at gmail.com (Tess) Date: Mon, 24 Mar 2008 17:56:06 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> Message-ID: <34b46ea7-7c87-4742-9d67-0a39e5daf983@e23g2000prf.googlegroups.com> Paul - thanks for the input, it's interesting to see how pyparser handles it. Anyhow, a simple regex took care of the issue in BS: for i in soup.findAll(re.compile('^p|^div'),align=re.compile('^center| ^left')): print i Thanks again! T From tjreedy at udel.edu Sat Mar 29 16:15:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2008 16:15:08 -0400 Subject: Error message from function definition References: <263d8c50803281910x32e5375h37fd8bfe10f9f36c@mail.gmail.com> Message-ID: Please do not post same question twice. From maxime.p at gmail.com Sun Mar 23 16:58:22 2008 From: maxime.p at gmail.com (Ulysse) Date: Sun, 23 Mar 2008 13:58:22 -0700 (PDT) Subject: Problems with joining Unicode strings Message-ID: <5b623e11-054d-44b7-bc65-d75922728dce@b1g2000hsg.googlegroups.com> Hello, I have problems with joining strings. My program get web page fragments, then joins them into one single web page. I have error when I try to join these fregments : "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 208: ordinal not in range(128)" Here is my code : # Parcours des RSS f = open('soupresult.html', 'w') d = feedparser.parse(rss_url) separator = '
' data = '' refresh_time = 2*60*60 #Secondes resume_news = [] # Parcours des RSS if len(d['items']) > 0: now = datetime.datetime.now() for item in d['items']: item_date = item.date_parsed print item_date item_date2 = datetime.datetime(item_date[0], item_date[1], item_date[2], item_date[3], item_date[4], item_date[5]) age_item = now - item_date2 age_item = age_item.days*24*3600 + age_item.seconds if age_item < refresh_time: url = item['link'] print item.title try: req = urllib2.Request(url) browser = urllib2.urlopen(req) data = browser.read() clean_item = data resume_news.append(item.title) resume_news.append(clean_item) except urllib2.URLError, e: print e.code f.write(u''.join(resume_news)) From castironpi at gmail.com Sun Mar 9 16:58:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 13:58:15 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> <13t7smt4rn8rn32@corp.supernews.com> Message-ID: On Mar 9, 9:23?am, Steven D'Aprano wrote: > On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > > Okay, so I think I know where's the catch now -- you must rely on the > > fact that the protocol is implemented, there's no way to enforce it if > > you're expecting a parrot-like object. You'd try to call the speak() > > method and deal with the error if there's no such method? > > That's right. That's called "duck typing" -- if all you want is something > that quacks like a duck, then it doesn't matter if it actually is a duck > or not. > > Or if you prefer: if it quacks like a duck and swims like a duck, then > it's close enough to a duck as to make no difference. The syntax checker over here raised a warning on this one. "So close to a duck as." (I'm using the so...as construct in my Propositional Calculus program.) > try: > ? ? something.speak > except AttributeError: > ? ? # No speak() method, so it can't be a parrot. > ? ? do_something_else() It might be a dead parrot. HAR! > else: > ? ? # It seems to follow the parrot protocol. > ? ? yummy_goodness = something.speak(5) > ? ? assert "spam" in yummy_goodness.lower() P.S. Is 'resemblant' a word? So resemblant of a duck as. From rbossy at jouy.inra.fr Sat Mar 15 14:39:37 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 15 Mar 2008 19:39:37 +0100 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Message-ID: <1205606377.47dc17e94926f@www.jouy.inra.fr> Quoting Bryan Olson : > Robert Bossy wrote: > > Bryan Olson wrote: > >> Robert Bossy wrote: > >>>> Robert Bossy wrote: > >>>>> Indeed! Maybe the best choice for chunksize would be the file's buffer > >>>>> size... > >> > >> That bit strikes me as silly. > >> > > The size of the chunk must be as little as possible in order to minimize > > memory consumption. However below the buffer-size, you'll end up filling > > the buffer anyway before actually writing on disk. > > First, which buffer? The file library's buffer is of trivial size, > a few KB, and if we wanted to save even that we'd use os.open and > have no such buffer at all. The OS may set up a file-specific > buffer, but again those are small, and we could fill our file much > faster with larger writes. > > Kernel buffers/pages are dynamically assigned on modern operating > systems. There is no particular buffer size for the file if you mean > the amount of kernel memory holding the written data. Some OS's > do not buffer writes to disk files; the write doesn't return until > the data goes to disk (though they may cache it for future reads). > > To fill the file fast, there's a large range of reasonable sizes > for writing, but user-space buffer size - typically around 4K - is > too small. 1 GB is often disastrously large, forcing paging to and > from disk to access the memory. In this thread, Matt Nordhoff used > 10MB; fine size today, and probably for several years to come. > > If the OP is writing to a remote disk file to test network > throughput, there's another size limit to consider. Network file- > system protocols do not steam very large writes; the client has to > break a large write into several smaller writes. NFS version 2 had > a limit of 8 KB; version 3 removed the limit by allowing the server > to tell the client the largest size it supports. (Version 4 is now > out, in hundreds of pages of RFC that I hope to avoid reading.) Wow. That's a lot knowledge in a single post. Thanks for the information, Bryan. Cheers, RB From ragu.n4 at gmail.com Mon Mar 3 23:33:20 2008 From: ragu.n4 at gmail.com (ragu) Date: Mon, 3 Mar 2008 20:33:20 -0800 (PST) Subject: Earn from home Message-ID: <1db8dd72-6f03-4a67-a40c-3cac9a8ccfed@i12g2000prf.googlegroups.com> Today, We are earning upto Rs.20,000 every month from internet without working hard and spending only 30 min daily in the internet. This Income is keep on increasingday by day.We are not joking. We are not making any false statement. It's 100% true ! http://eanrfromyourhome.blogspot.com From gregory.bronner at lehman.com Wed Mar 12 11:04:48 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Wed, 12 Mar 2008 11:04:48 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com><21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2998@nypcmg1exms318.leh.lbcorp.lehman.com> The short answer is that you don't need to: Anything that has a 'handle' attribute that is an int should be fine to pass into the function, and your typemap will be fine (with some additional checking) If you really insist on absolute type safety, however, you'll need an instance of the Pin class to compare to. Actually, all you need is an instance of the Pin Type -- you can use PyObject_TypeCheck (if I recall). Chances are, the name 'Pin' is already in your locals or globals, so you find the object, grab its type, and then check the type. Personally, I wouldn't bother. ________________________________ From: Cooper, Andrew [mailto:ACooper at cimtek.com] Sent: Tuesday, March 11, 2008 7:34 PM To: python-list at python.org Subject: RE: Obtaining the PyObject * of a class The part I'm having problem with is as follows: I want to replace the 'strcmp' below with a call to PyObject_IsInstance(o, pinClassPyObject) But I don't know how to get the PyObject* for the Pin class that is defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list From: python-list-bounces+acooper=cimtek.com at python.org [mailto:python-list-bounces+acooper=cimtek.com at python.org] On Behalf Of Bronner, Gregory Sent: 11 March 2008 20:52 To: Michael Wieher; python-list at python.org; accooper at cimtek.com Subject: RE: Obtaining the PyObject * of a class I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list at python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Mar 19 16:06:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 17:06:38 -0300 Subject: Search the command history - Python Shell References: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> <47E0E5F6.2010701@tim.thechases.com> Message-ID: En Wed, 19 Mar 2008 07:07:50 -0300, Tim Chase escribi?: >> Are there any simillar key combination in Python Shell like Linux Ctrl+R >> (reverse-i-search) to search the command history? > > It must depend on how your version of Python was built...mine > here on my Linux box has exactly that functionality. I press ^R > and start typing, and the line comes up from my typed history. On Windows you would type a few characters and use F8 and Shift-F8, or F7 to choose from a pop-up list. -- Gabriel Genellina From bearophileHUGS at lycos.com Sun Mar 16 11:58:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Mar 2008 08:58:58 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> Tim Golden: > I'm not entirely sure why you think Pyrex should "contain a compiler". I think lot of Win users (computational biologists?), even people that know how to write good Python code, don't even know how to install a C compiler. >I'm fairly sure it's fine with MingW< (In the past?) I think you have to tweak it a bit. --------------- sturlamolden: >And although it may come as a surprise to you, Pyrex IS a compiler.< I meant a compiler that spits out the final executable a person can click on. >Being written in pure Python, Pyrex is equally easy to use on Windows and Linux.< Or maybe equally difficult :-) The computational biology students I was with think PythonWin is "easy" enough (or take a look at the "Processing" Java-like language user interface). Lowering entry difficulties is positive. Can things be made simpler for newbies? Bye, bearophile From mm007.emko at gmail.com Fri Mar 14 12:36:36 2008 From: mm007.emko at gmail.com (eMko) Date: Fri, 14 Mar 2008 09:36:36 -0700 (PDT) Subject: find string in file References: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> Message-ID: <93e7f081-0217-4119-a91e-eb54b70a4a48@s13g2000prd.googlegroups.com> An of course, you can use a regular expression. (Module "re"). From gowricp at gmail.com Thu Mar 20 03:51:43 2008 From: gowricp at gmail.com (Gowri) Date: Thu, 20 Mar 2008 00:51:43 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <29cd9085-b70f-4873-899e-3837d8e42d90@u69g2000hse.googlegroups.com> Hi Tim, I understand it's JSON. My problem is that it just prints crazy characters instead of the JSON data. Like I mentioned, this happens on my windows machine which has python 2.5. On the other hand, the same code worked perfectly great on my linux machine with python 2.3.4. What could the problem be? Regards, Gowri From musiccomposition at gmail.com Sun Mar 30 18:50:17 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 30 Mar 2008 15:50:17 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> On Mar 29, 11:02 pm, Alex Teiche wrote: > Hello, > > I am pretty new to Python, and have never learned C++. I am trying to > implement the following thing into my python application: > > http://doc.trolltech.com/4.3/qsystemtrayicon.html > > Through PyQt. I have been using PyQt for awhile and I know how do use > it, but I could not get this specific thing to work. Can someone give > me some hints as to get it working in Python? What problems are you having? > > Thanks a ton, > > Alex From oswald.harry at gmail.com Fri Mar 28 17:15:04 2008 From: oswald.harry at gmail.com (harryos) Date: Fri, 28 Mar 2008 14:15:04 -0700 (PDT) Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <3b584949-73a2-4c2b-aa28-8d1f6622cd8c@u10g2000prn.googlegroups.com> > the norm from which it is derived is called norm-1, or L1; the usual > euclidean distance is derived from norm-2. > If you only want to see if two things are "close enough", this provides a faster measure than the euclidean distance. thanks Gabriel for the detailed explanation.. if i were to calculate the euclidean distance in the above example how should i go about it..? should i replace distance = abs(input_wk - weights[image, :]) with something else? thanks again oharry From danb_83 at yahoo.com Mon Mar 31 21:52:18 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 31 Mar 2008 18:52:18 -0700 (PDT) Subject: Stuck in a loop References: Message-ID: <23ab0de7-c262-4624-898b-00b95f3a6561@b5g2000pri.googlegroups.com> On Mar 31, 8:22 pm, hexusne... at gmail.com wrote: > I wrote a simple algorithm and it keeps getting stuck in a loop. I > guess I'm just to tired to figure it out: > > compcount=[5,4,2,2] > suitrank=[0,0,0,0] > > trump=2 > l,lt=0,0 > while l<4: > while lt<4: > if l==trump: > l+=1 > if l>3: > break > if lt==trump: > lt+=1 > if compcount[l] suitrank[l]+=1 > lt+=1 > l+=1 > > In case you're wondering, the point is to rank suits from highest to > lowest based on how few cards each suit has. I hope that's enough > information. Inside the inner loop, lt never changes if lt != trump, so you get an infinite loop the first time when lt == 0. I think you may have misindented the last two lines. From abarun22 at gmail.com Fri Mar 7 10:44:19 2008 From: abarun22 at gmail.com (abarun22 at gmail.com) Date: Fri, 7 Mar 2008 07:44:19 -0800 (PST) Subject: swig-python import error Message-ID: <0e5e98df-f0f0-4607-82a8-044530b383f5@c33g2000hsd.googlegroups.com> Hi I am facing a problem while loading a SWIG generated shared module from python. The development is under HP-UX 32b platform. I use gcc version 4.0.2 to build the shared module. This is how i try to build the module. # Compilation GCC="$GCC -march=1.1" $GCC -v -c -fpic ${ETUDE}.c ${ETUDE}_wrap.c -DDOUBLE_PRECISION - DDON_DOUBLE_PRECISION ${PYTHON_INCLUDE_PATH} ${CHAINE_INCLUDE_PATH} # linking ld -b binary -g -shared ${ETUDE}.o ${ETUDE}_wrap.o -o _${ETUDE}.so \ -a archive ${LIBS_CHAINE_PATH} -lfichiers_r8 -lmem -lutilitaires - lsysteme -lcalcul -lmsgml -lcaractere \ -rpath -L/michprojects/ef/deli/Working/Source/deli9-PYAPI/Sandbox/libs/ chaine/PYAPI/don -L/michprojects/ef/deli/Working/Source/deli9-PYAPI/ Sandbox/libs/chaine/hppa_portable-hp-hpux11.11/Debug The module generated is called _don.so. In addition to that i set the module path in LD_LIBRARY_PATH environment variable. Th error looks like as follows. Import error: module cannot be loaded. But i am wondering how i am getting import error although every thing looks OK. Any ideas are most welcome and thanks in advance. Regards, Arun From pavloutefkros at gmail.com Sun Mar 2 08:09:10 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 05:09:10 -0800 (PST) Subject: tcp Message-ID: i have this small script which after some router configurations works. ########################################################## #! /usr/bin/python import socket HOST = '' PORT = 1515 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() conn.send('HTTP/1.1 200 OK\r\n') conn.send('Content-Type: text/html\r\n') conn.send('Server: test/1.0\r\n\r\n') conn.send('test') s.close() ########################################################## as you see it listens to 1515 until a connection is established and then it accepts it... the problem is that when it accepts the connection it sends those strings and exits, but then it exits the program. i want it to listen to 1515 then accept a connection, send.. and then listen to the port again and again until new connections are found. i've been struggling with try..except,while and all kinds of loops but always new erros pop up, or it overflows. From erikwickstrom at gmail.com Sun Mar 23 11:48:44 2008 From: erikwickstrom at gmail.com (erikcw) Date: Sun, 23 Mar 2008 08:48:44 -0700 (PDT) Subject: "Soup Strainer" for ElementSoup? Message-ID: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> Hi all, I was reading in the Beautiful Soup documentation that you should use a "Soup Strainer" object to keep memory usage down. Since I'm already using Element Tree elsewhere in the project, I figured it would make sense to use ElementSoup to keep the api consistent. (and cElementTree should be faster right??). I can't seem to figure out how to pass ElementSoup a "soup strainer" though. Any ideas? Also - do I need to use the extract() method with ElementSoup like I do with Beautiful Soup to keep garbage collection working? Thanks! Erik From R.Brodie at rl.ac.uk Tue Mar 4 08:58:36 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 4 Mar 2008 13:58:36 -0000 Subject: Eurosymbol in xml document References: <634sleF25sd22U1@mid.uni-berlin.de> Message-ID: "Robert Bossy" wrote in message news:mailman.1583.1204634888.9267.python-list at python.org... > If the file is declared as latin-1 and contains an euro symbol, then the file is > actually invalid since euro is not defined of in iso-8859-1. Paradoxical would be a better description than invalid, if it contains things that it can't contain. If you decoded iso-8859-15 as if it were iso-8859-1, you would get u'\xa4' (Currency Sign) instead of the Euro. From the original error: "UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in position 11834: character maps to " that seems to be what happened, as you said. From MartinRinehart at gmail.com Wed Mar 5 09:56:24 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 06:56:24 -0800 (PST) Subject: Why """, not '''? Message-ID: Why is """ the preferred delimiter for multi-line strings? From 2huggie at gmail.com Mon Mar 24 01:33:22 2008 From: 2huggie at gmail.com (Timothy Wu) Date: Mon, 24 Mar 2008 13:33:22 +0800 Subject: xml.sax problem Message-ID: Hi, I have created a very, very simple parser for an XML. class FindGoXML2(ContentHandler): def characters(self, content): print content I have made it simple because I want to debug. This prints out any content enclosed by tags (right?). The XML is publicly available here: http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&id=9622&retmode=xml I show a few line embedded in this XML: GO 3824 catalytic activity evidence: IEA Notice the third line before the last. I expect my content printout to print out "evidence:IEA". However this is what I get. ------------------------- catalytic activity ==> this is the print out the line before e vidence: IEA ------------------------- I don't understand why a few blank lines were printed after "catalytic activity". But that doesn't matter. What matters is where the string "evidence: IEA" is split into two printouts. First it prints only "e", then "vidence: IEA". I parsed 825 such XMLs without a problem, this occurs on my 826th XML. Any explanations?? Timothy -------------- next part -------------- An HTML attachment was scrubbed... URL: From ebgssth at gmail.com Tue Mar 11 08:48:59 2008 From: ebgssth at gmail.com (js) Date: Tue, 11 Mar 2008 21:48:59 +0900 Subject: TextWrapper keepking line breaks? In-Reply-To: References: Message-ID: Hi Arnaud, Great. Thanks for your help! On Tue, Mar 11, 2008 at 10:27 AM, Arnaud Delobelle wrote: > > On Mar 10, 11:31 pm, js wrote: > > Hi list, > > > > Can I make TextWrapper keep line breaks in the text? > > > > For example, > > > > >>> s = "spam\nham" > > >>> print wrap(s) > > > > spam > > ham > > > > As far as I can tell, there seems no way to do this, > > but before writing my own solution, I want to know whether > > the solution already exists or not. > > > > Thanks. > > Don't know but you could write: > > >>> import textwrap > >>> def wraplines(text): > ... return '\n'.join(textwrap.fill(line) for line in > text.split('\n')) > ... > >>> s = "spam\nham" > >>> print wraplines(s) > spam > ham > >>> > > HTH > > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > From Graham.Dumpleton at gmail.com Mon Mar 17 16:58:14 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 17 Mar 2008 13:58:14 -0700 (PDT) Subject: Apache binary error? References: Message-ID: On Mar 18, 4:43?am, Sean Allen wrote: > On Mar 17, 2008, at 10:55 AM, Michael Wieher wrote: > > > have simple webpage running > > > apache,mod_python > > > the error is binary.... > > ...binary as in "every other" time I load the page, Firefox keeps ? > > telling me I'm downloading a python script, and asks to open it in ? > > WINE, which is really strange. > > > then, alternately, it loads the page just fine. ?any clues as to why ? > > this is happening? > > -- > > for anything like mod_perl,mod_pythonetc the first thing i do when i ? > get really weird errors > it move to having only one apache process for testing. > > might want to start there. In mod_python handler code: req.content_type = 'text/plain' or otherwise. If you don't indicate what the response content type is web browsers will often try and work it out based on the extension in the URL. This is presuming you configured Apache correctly and your code is actually being executed and you aren't just serving up your code instead. Graham From Wubbulous at gmail.com Tue Mar 11 00:57:35 2008 From: Wubbulous at gmail.com (Wubbulous at gmail.com) Date: Mon, 10 Mar 2008 21:57:35 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <4612d533-6f73-4abb-9f56-69caf29fdbdc@s8g2000prg.googlegroups.com> I may have your problem: if prime < 0: primes.append(x) else: print x, "is not prime. " # highlights the final " you have to separate each output with a comma, so try adding one after x. From david.reitter at gmail.com Sat Mar 22 04:47:47 2008 From: david.reitter at gmail.com (David Reitter) Date: Sat, 22 Mar 2008 01:47:47 -0700 (PDT) Subject: Can I run a python program from within emacs? References: Message-ID: <3413d022-b9c6-4503-8d5a-d01ffead3c99@m36g2000hse.googlegroups.com> On Mar 20, 3:09 pm, jmDesktop wrote: > Hi, I'm trying to learn Python. I using Aquamac an emac > implementation with mac os x. I have a program. If I go to the > command prompt and type pythong myprog.py, it works. Can the program > be run from within the editor or is that not how development is done? > I ask because I was using Visual Studio with C# and, if you're > familiar, you just hit run and it works. On Python do I use the > editor for editing only and then run the program from the command > line? Thank you. Aquamacs, just like any variant of GNU Emacs, will show a Python menu. There's a "Start Interpreter" function, and one to evaluate the buffer (C-c C-c). It's pretty straightforward (a euphemism for obvious). If the Python menu doesn't show, then something is going wrong. M-x python-mode RET would switch it on. -- http://aquamacs.org -- Aquamacs: Emacs on Mac OS X http://aquamacs.org/donate -- Could we help you? Return the favor and support the Aquamacs Project! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 13:02:57 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 18:02:57 +0100 Subject: dynimac code with lambda function creation In-Reply-To: References: Message-ID: <47ebd337$0$13089$426a74cc@news.free.fr> Justin Delegard a ?crit : > So I am trying to pass an object's method call I assume you mean "to pass an object's method", since I don't get what passing "an object's method call" could mean. > to a function that > requires a function pointer. s/pointer/object/ There's nothing like a pointer in Python, and Python's functions are plain objects (instances of class 'function'). FWIW and WWAI, Python's methods are thin callable wrappers around the function, the class and (for bound methods) the instance. > I figured an easy way to do it would be to > create a lambda function that calls the correct method, but this is > proving more difficult than I imagined. "easy" ??? Here's the easy way to pass a method to a function: def func(method): return method(42) class MyClass(object): def __init__(self, name): self.name = name def foo(self, whatever): return "I'm %s and whatever is %s" % (self.name, str(whatever)) obj = MyClass('boo') print func(obj.foo) > Here is the function I'm using: > > def objectMethodCallerFunctionCreator(testerObj, method): > exec("y=lambda x: testerObj."+method+"(x)") > return y My my my... Looks like you're in for the Rube Goldberg Award !-) Whenever you think exec (or eval FWIW) is the solution, odds are there's a way better solution. If what you want is to retrieve a reference to an attribute you only know by it's name, getattr() is your friend. And in Python, methods are attributes. def objectMethodCallerFunctionCreator(testerObj, method): y = lambda x: getattr(testerObj, method)(x) return y But as we've seen above, all this is useless overcomplexification. Just pass the method like it was any other attribute, and you're done. > > Where testerObj is an instance of an object, and method is a string > representing the method to call. The problem is, when I actually run > the function created (y in this case), it tells me it can't find the > symbol testerObj in the global scope. This is related to exec as far as I can tell. > I have successfully created > similar functions, except without using the exec() call. e.g. > > def functionCreator(a, b, c): > return lambda d: myFunc(a, b, c, d) > > and it doesn't complain about the variables a, b, or c when being run. > I am assuming this is happening because of the exec() call, but I don't > see another way of calling a variable method on an object. Is there > some other way to do this that I'm missing? print func(getattr(obj, 'foo')) > I tried passing in 'method' > as a function pointer (to the method of the object), but that didn't > work either. What did you try, and what result did you get ? 'does not work' is (almost) the most useless description of a problem. From gnewsg at gmail.com Thu Mar 27 22:28:45 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 27 Mar 2008 19:28:45 -0700 (PDT) Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: <86b83385-697d-40d6-8bbb-dfeeba372040@d21g2000prf.googlegroups.com> Sorry for replying so late. I'll try to describe what I'm actually trying to implement so that maybe it can help you understand a little better. The application is an asynchronous FTP server implementation. I decided that it would be desirable to change the current implementation so that every time a filesystem operation is going to be made I temporarily change the current process ID to reflect the current logged-in user, execute the filesystem call and then switch back to the original process ID. Pseudo code: def STOR(filename): authorizer = UnixAuthorizer() authorizer.impersonate_user(current_logged_in_user) try: f = open(filename, 'w') finally: authorizer.terminate_impersonation() ... The UnixAuthorizer class is expected to provide the mechanism to change the current user (presumably via os.setegid()/os.seteuid()) and then switch back to the original one. Since we're talking about an asynchronous environment I tought that temporarily changing the process ID was the only way to do this. I'm sincerely not skilled enough about the UNIX world to know which are the security implications behind such an approach. Do you think it is reasonable? --- Giampaolo http://code.google.com/p/pyftpdlib/ From spe.stani.be at gmail.com Sat Mar 1 16:37:32 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 1 Mar 2008 13:37:32 -0800 (PST) Subject: PIL transparency gradient References: <6e44e95a-2cb0-4026-ad98-f6516e934e27@s37g2000prg.googlegroups.com> Message-ID: <4293dfd7-52aa-463e-b36c-c254a56616c4@s19g2000prg.googlegroups.com> On 1 mrt, 22:04, Allard Warrink wrote: > I would like to create a transparency gradient over an image using > PIL. But I don't have a clue how to do this... > Is there anyone out here who could give me some advise? Phatch (PHoto & bATCH) is an application based on PIL. Its actions contain many useful PIL recipes, such as applying a transparency gradient to an image. You basically need to create an 1pxx256px grayscale image which goes from 0 to 255. After that you can stretch it to the image size and add it as an alpha channel. You'll find the source code for this in the phatch/actions/mask.py Every action contains a 'raw' PIL function that can work independently outside the context of Phatch. This is by design, inspired by the MVC model in which you could see PIL as the model and Phatch as the View. You can get Phatch at: http://photobatch.stani.be Read first *carefully* the installation instructions for your platform: http://photobatch.wikidot.com/install Stani From mail at timgolden.me.uk Tue Mar 11 06:43:27 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Mar 2008 10:43:27 +0000 Subject: rmdir problem In-Reply-To: References: Message-ID: <47D6624F.8060203@timgolden.me.uk> royG wrote: > hi > i am checking if a directory exists and if it does i want to delete it > and its contents.then i want to create the directory before creating > files in it. > > def myfolderops(): > testdir='..\mytestdir' > #if dir exist remove it > if isdir(testdir): > rmdir(testdir) > #again create directory > mkdir(testdir) > > I am working on WinXP and logged in as admin in WinXP. when there is > no dir called '..\mytestdir' or an empty dir this code works removing > and creating the directory.but if the directory exists with contents > already then it causes an error 145 when rmdir is executed.the message > says 'directory is not empty' > what should i do to correct this? > (i need to remove the dir with its contents because each time i will > be putting diff files into it and donot want them to be mixed with old > files) Two things: 1) Use raw strings (r"..\blah") or forward slashes ("../blah") when messing with path names under windows. 2) Check out the shutils module: http://docs.python.org/lib/module-shutil.html TJG From lizhongan at gmail.com Mon Mar 17 20:26:57 2008 From: lizhongan at gmail.com (zaley) Date: Mon, 17 Mar 2008 17:26:57 -0700 (PDT) Subject: pass float array(list) parameter to C References: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> <013c161a-931c-4576-935d-4341911a299f@s37g2000prg.googlegroups.com> Message-ID: <2bdcc2d7-4033-4973-b57a-b09a9043ac3f@s8g2000prg.googlegroups.com> On Mar 17, 10:59 pm, marek.ro... at wp.pl wrote: > You can also do it with ctypes only; too bad it's not really well > documented. c_float is a type of a floating point number and it has * > operator defined, so that c_float*4 is a type of a 4-element array of > those numbers. So if you want to construct an array of floats from a > list of floats, you can do it like this: > > from ctypes import c_float > > x = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9] > float_array_type = c_float*len(x) > float_array = float_array_type(*x) > print float_array Is there has any difference between the following arrays ? Buf0=(c_float* 9)(57,57,57,57,57,5,5,5,5) Buf0=array('f', [57,57,57,57,57,5,5,5,5]) function called like this in python: ret= SetAnalog(9,Buf0) function prototype in C like this int SetAnalog(UINT uChannel,float* pBuf) { ....... } From mobiledreamers at gmail.com Tue Mar 25 23:02:21 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 25 Mar 2008 20:02:21 -0700 Subject: Socialsoft Startup Jobs Message-ID: http://www.thesocialsoft.com/jobs.html We - Build stuff that people love and use everyday - have a healthy disregard for the impossible - are not a conventional company and do not intend to be one - Think big, think fast and think ahead - set our goals high and work to exceed them, then we set our sights even higher - love our users more than anything else - launch early launch often - work on Web scale projects - believe that velocity matters - Care about interaction and user interface - grow by systematically removing bottlenecks - easy to know when something is a win - are experts in building scalable high performance clusters - scale horizontally - are scientific - collect data and understand it - start with "good enough" and iterate rapidly to reach perfection and critical mass - truly love the internet - see the elegance in simplicity - know what the user wants but listen to feedback - love to experiment with new fun viral ideas - are a really high energy team, it is not surprising for traffic to double overnight - aim to be better than the best - believe that we can change the world - This is a great company and we are moving quickly to make it even better - love fresh home made frozen yogurt across the street Cutting edge Tools We use - we love love Python - cheetah - memcached - postgresql - berkeley db - starling - jquery - subversion - git - nginx - haproxy - php We are the Most fun team in Silicon valley - beanbag plushies - Be in the driving seat of your project - Herman miller chairs - believe in developer productivity and happiness - live in downtown Palo Alto You (exceptional) - are a brilliant web software hacker who can design, build, and ship interesting web products - are among the best at what you do and routinely solve hard technical problems - have an understanding of successful web properties - have some insight into what makes them resonate with users - want to reach millions if not billions of people through your code - Are pragmatic and flexible - Care deeply about users and the user experience - should be available to work full-time or more Start your incredibly fun journey with the Socialsoft Team! - Join the Socialsoft dream, email jobs at thesocialsoft.com now -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 09:41:09 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 13:41:09 -0000 Subject: Check For SELF Variable Existance In-Reply-To: <8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> References: <-8215347293566648508@unknownmsgid> <8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> Message-ID: <00be01c8837d$9311ff40$b935fdc0$@rawlins@thinkbluemedia.co.uk> Thank you Simon, I was hoping there would be something as simple as that :-) Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Simon Brunning Sent: 11 March 2008 13:21 To: python-list at python.org Subject: Re: Check For SELF Variable Existance On Tue, Mar 11, 2008 at 11:00 AM, Robert Rawlins wrote: > I want to be able to check if a class has a certain property in its 'self' > scope, what's the best way to do this? >>> class Spam(object): ... def egg(self): ... if hasattr(self, 'chips'): print 'got chips!' ... >>> spam = Spam() >>> spam.egg() >>> spam.chips = 'beans' >>> spam.egg() got chips! -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list From durieux_br at yahoo.com.br Wed Mar 26 15:37:16 2008 From: durieux_br at yahoo.com.br (Fabio Durieux Lopes) Date: Wed, 26 Mar 2008 19:37:16 -0000 Subject: Daylight savings time problem Message-ID: Hi, I'm trying to execute some operations based on a file's time. The file's time is actually the file's name (e.g. FILE1_20080326170558). So I do this: fileTimeInSecs = time.mktime(time.strptime(timeString, "%Y%m%d%H%M")) timeString contains the date part of the file's name. Function strptime returns a time_struct, but my problem is that tm_isdst is set to 0, and when we enter daylight savings time the file's time is off by 1 hour. This time_struct is also read only so I can't change tm_isdst to -1. Anyone knows how to fix it? From lunasf at gmail.com Thu Mar 20 07:19:49 2008 From: lunasf at gmail.com (igbt) Date: Thu, 20 Mar 2008 04:19:49 -0700 (PDT) Subject: A question about a metacharacter Message-ID: I am creating a simple script which is using gtk. In this script you must enter a text, if you do not enter anything or you enter a dot, the script will be finished. However, if you don't enter anything the script works but if you enter a dot (.) the script does not work. I was investigating about it and I think the problem is with the dot character sss == "." . I was trying the same line with other metacharacters like *, (, ) ... and I found the same problem. I was looking for an example where I could see the way I could do it without any error but I did not find it. Could somebody tell me how can I solve this error? sss = entryName.get_text() # The script gets the text if sss == "" or sss == ".": gtk.main_quit() #The script finishes Thanks ; -) From arnodel at googlemail.com Wed Mar 26 04:47:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 01:47:17 -0700 (PDT) Subject: Strange loop behavior References: Message-ID: On Mar 26, 8:35?am, Gabriel Rossetti wrote: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > ? ? while d != "": > ? ? ? ? file_str.write(d) > ? ? ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > I also tried writing the while's condition like so : len(d) > 0, but > that doesn't change anything. I tried step-by-step debugging using > PyDev(eclipse plugin) and I noticed this, once the while was read once, > it is never re-read, basically, the looping does happen, but just in > between the two lines in the loop's body/block, it never goes on the > while and thus never verifies the condition and thus loops forever. I > had been using psyco (a sort of JIT for python) and so I uninstalled it > and restarted eclipse and I still get the same thing. This looks like > some bug, but I may be wrong, does anybody understand what's going on here? > > Thanks, > Gabriel > > PS > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. No, it isn't the empty string, it is the printable representation of the empty string (because you wrap your f.read() calls in repr()), which is the string "''": >>> print "''" '' Why do you wrap f.read(...) in the repr() function? If you remove the two repr() I suspect your code will work. OTOH do you know that the read() method of file objects does what you want? You could simply write: file_str = f.read() Or are there some other factors that prevent you from doing this? -- Arnaud From kyosohma at gmail.com Mon Mar 31 09:44:48 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 06:44:48 -0700 (PDT) Subject: wxPython; adding a grid to a panel References: Message-ID: <2c49ad39-a388-40a6-bb2d-8e89b18b58ff@s37g2000prg.googlegroups.com> Moynes, On Mar 31, 5:01 am, "Moynes James" wrote: > I am a Python newbie hoping for some help with wxPython. > > I am trying to build a frame which will display a wx.grid and a number > of other widgets (text controls, static text and buttons). In all the > example scripts I have seen, a gird is added directly to a frame; is it > possible to place a grid in a box sizer or on a wx.Panel so that it can > be arranged with other widgets in the same frame? > > In the script below I have added two panels to a frame. I want to > display the grid in one panel (and later on add other widgets to the > other panel), but I cannot get the grid to display properly. > > What am I doing wrong? > > Thanks in advance for your help, > > James > > ################################################# > import wx > import wx.grid > > class TestTable(wx.grid.PyGridTableBase): > def __init__(self): > wx.grid.PyGridTableBase.__init__(self) > self.rowLabels = ["uno", "dos", "tres", "quatro", "cinco"] > self.colLabels = ["homer", "marge", "bart", "lisa", "maggie"] > > def GetNumberRows(self): > return 5 > > def GetNumberCols(self): > return 5 > > def IsEmptyCell(self, row, col): > return False > > def GetValue(self, row, col): > return "(%s,%s)" % (self.rowLabels[row], self.colLabels[col]) > > def SetValue(self, row, col, value): > pass > > def GetColLabelValue(self, col): > return self.colLabels[col] > > def GetRowLabelValue(self, row): > return self.rowLabels[row] > > class TestFrame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, title="Grid Table", > size=(500,200)) > panel1 = wx.Panel(self, -1) > panel2 = wx.Panel(self, -1) > hbox1 = wx.BoxSizer(wx.HORIZONTAL) > > hbox1.Add(panel1, 1, wx.EXPAND | wx.ALL, 3) > hbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 3) > > grid = wx.grid.Grid(panel2, wx.EXPAND) > table = TestTable() > grid.SetTable(table, True) > self.SetSizer(hbox1) > > app = wx.PySimpleApp() > frame = TestFrame() > frame.Show() > app.MainLoop() > > ################################################## I'd never used the PyGridTableBase to do this before, so I used the wxPython demo to figure it out. If you check out the GridCustomTable demo code, you'd probably have gotten it as well. Basically, you needed to add another class that inherited from wx.grid.Grid that would use the base you created. Here's the modified code: import wx import wx.grid as gridlib class TestTable(wx.grid.PyGridTableBase): def __init__(self): gridlib.PyGridTableBase.__init__(self) self.rowLabels = ["uno", "dos", "tres", "quatro", "cinco"] self.colLabels = ["homer", "marge", "bart", "lisa", "maggie"] def GetNumberRows(self): return 5 def GetNumberCols(self): return 5 def IsEmptyCell(self, row, col): return False def GetValue(self, row, col): return "(%s,%s)" % (self.rowLabels[row], self.colLabels[col]) def SetValue(self, row, col, value): pass def GetColLabelValue(self, col): return self.colLabels[col] def GetRowLabelValue(self, row): return self.rowLabels[row] class CustTableGrid(gridlib.Grid): def __init__(self, parent): gridlib.Grid.__init__(self, parent, -1) table = TestTable() # The second parameter means that the grid is to take ownership of the # table and will destroy it when done. Otherwise you would need to keep # a reference to it and call it's Destroy method later. self.SetTable(table, True) self.SetRowLabelSize(0) self.SetMargins(0,0) self.AutoSizeColumns(False) class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Grid Table", size=(500,200)) panel1 = wx.Panel(self, -1) panel2 = wx.Panel(self, -1) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(panel1, 1, wx.EXPAND | wx.ALL, 3) hbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 3) table = CustTableGrid(panel2) tblSizer = wx.BoxSizer(wx.VERTICAL) tblSizer.Add(table, 1, wx.ALL|wx.EXPAND, 5) panel2.SetSizer(tblSizer) self.SetSizer(hbox1) app = wx.PySimpleApp() frame = TestFrame() frame.Show() app.MainLoop() FYI: There's an excellent wxPython mailing list - http://wxpython.org/maillist.php Mike From mark.e.tolonen at mailinator.com Tue Mar 4 02:43:32 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Mon, 3 Mar 2008 23:43:32 -0800 Subject: help needed with regex and unicode References: <6349rmF23qmbmU1@mid.uni-berlin.de> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:6349rmF23qmbmU1 at mid.uni-berlin.de... > On Tue, 04 Mar 2008 10:49:54 +0530, Pradnyesh Sawant wrote: > >> I have a file which contains chinese characters. I just want to find out >> all the places that these chinese characters occur. >> >> The following script doesn't seem to work :( >> >> ********************************************************************** >> class RemCh(object): >> def __init__(self, fName): >> self.pattern = re.compile(r'[\u2F00-\u2FDF]+') >> fp = open(fName, 'r') >> content = fp.read() >> s = re.search('[\u2F00-\u2fdf]', content, re.U) >> if s: >> print s.group(0) >> if __name__ == '__main__': >> rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php') >> ********************************************************************** >> >> the php file content is something like the following: >> >> ********************************************************************** >> // Check if the folder still has subscribed blogs >> $subCount = function1($param1, $param2); >> if ($subCount > 0) { >> $errors['summary'] = '????????? ???????????????????????????????'; >> $errorMessage = '????????? ???????????????????????????????'; >> } > > Looks like an UTF-8 encoded file viewed as ISO-8859-1. Sou you should > decode `content` to unicode before searching the chinese characters. > I couldn't get your data to decode into anything resembling Chinese, so I created my own file as an example. If reading an encoded text file, it comes in as just a bunch of bytes: >>> print open('chinese.txt','r').read() ????????????????????? W?? sh?? M??igu??r??n. I am an American. Garbage, because the encoding isn't known. Provide the correct encoding and decode it to Unicode: >>> print open('chinese.txt','r').read().decode('utf8') ??????? W? sh? M?igu?r?n. I am an American. Here's the Unicode string. Note the 'u' before the quotes to indicate Unicode. >>> s=open('chinese.txt','r').read().decode('utf8') >>> s u'\ufeff\u6211\u662f\u7f8e\u56fd\u4eba\u3002 W\u01d2 sh\xec M\u011bigu\xf3r\xe9n. I am an American.' If working with Unicode strings, the re module should be provided Unicode strings also: >>> print re.search(ur'[\u4E00-\u9FA5]',s).group(0) ? >>> print re.findall(ur'[\u4E00-\u9FA5]',s) [u'\u6211', u'\u662f', u'\u7f8e', u'\u56fd', u'\u4eba'] Hope that helps you. --Mark From kay.schluehr at gmx.net Sun Mar 9 01:24:36 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 8 Mar 2008 22:24:36 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> On 9 Mrz., 06:30, Steven D'Aprano wrote: > Hard Exceptions: terminate the program unless explicitly silenced > Soft Exceptions: pass silently unless explicitly caught > > In this case, I agree with the Zen of Python ("import this"): > > Errors should never pass silently. > Unless explicitly silenced. Exceptions in Python don't necessarily signal errors. Just think about StopIteration. Note also that the common practice of letting *possible* errors passed silently is to return None instead of raising an exception. Moreove people create boilerplate like this try: k = lst.index(elem) ... except IndexError: pass instead of with lst.index(elem) as k: ... It would be interesting to think about SoftException semantics for such clauses: lst.index would neither raises a HardException nor does it return None but leads to skipping the with-block. Is it really so exotic that it requires the demand for more use cases? From gagsl-py2 at yahoo.com.ar Wed Mar 26 18:29:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 19:29:19 -0300 Subject: Filtering a Python list to uniques References: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 15:50:30 -0300, kellygreer1 escribi?: > On Mar 26, 5:45 am, hellt wrote: >> On 26 ???, 02:30,kellygreer1 wrote: >> >> > What is the best way to filter a Python list to its unique members? > How come the Set() thing seems to work for some people and I get the > 'unhashable' error? > > How do you test for 'membership' on a dictionary? > > # where tmp is the non-unique list > # dct is a dictionary where each unique key will be tied to a count > (the value) > # for testing I was setting the count to 0 > for v in tmp: > if not v in dct: dct[v] = 0 > > # I get unhashable error here. > # Even if I write it. > > for v in tmp: > if not v in dct.keys(): dct[v] = 0 > > What am I missing? Mutable objects can't be used as keys in a dict nor be members of a set (at least if the mutable part is used to implement the == comparison). Technically, they should not implement __hash__ so hash(x) fails on them - they are "unhashable". Objects that can be used as keys in a dictionary or be members of a set include: instances of all numeric types, strings, tuples, frozensets; all of them are immutable and hashable. Instances of user-defined classes that don't implement __eq__ nor __cmp__ nor __hash__ are hashable and can be used too. Classes that implement such special methods must ensure that (x==y) => (hash(x)==hash(y)) and in that case can be used too; else, they should not implement __hash__ at all. On the other hand, mutable containers can't be keys in a dict, nor be members of a set; including instances of lists, sets, dicts, all of them are mutable and unhashable objects. Read the Cookbook recipes that someone posted before; one of them is generic enough to handle all cases, trying the fastest approaches first. If you think that all your objects should be hashable, try to find which one isn't. -- Gabriel Genellina From sam at mas.pl Mon Mar 31 06:59:13 2008 From: sam at mas.pl (sam) Date: Mon, 31 Mar 2008 12:59:13 +0200 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: Steve Holden napisa?(a): >> 1. You have different syntax for named and unnamed (lambdas) >> functions. Functions and methods are different things in Python even >> if they have same syntax. But all these are still a pieces of code >> that you use repeatedly to make some task. >> > A knife and scissors are both used to cut things, but that doesn't mean > they are the same. Well -- sometimes you have to use many, many types of scissors. > I think you are bundling quite different things together here. The > difference in semantics between bound methods (where the instance > reference is added as a first argument) and regular functions (where no > additional argument is supplied) has nothing to do with the difference > between function and lambda definition syntax. You are right. One is syntax issue, and the second is language implementation issue. It would be better to have one unified syntax and one unified implementation. > The desire to provide information hiding is fundamentally against the > Python philosophy, which basically says that attribute values are > exposed for all to see. This avoids the nonsense of having to provide > setter and getter methods which Java imposes on the programmer. This philosophy is great and makes Python such a good language. But you can't go beyond what programmers need. If you do so, then you will have to implement tricks as __id. From frikker at gmail.com Thu Mar 6 19:08:27 2008 From: frikker at gmail.com (blaine) Date: Thu, 6 Mar 2008 16:08:27 -0800 (PST) Subject: Ncurses not found - embedded linux References: <63b1rjF26p2fkU1@mid.uni-berlin.de> Message-ID: <754dad0b-9d3e-4ca7-a5fc-38519312947f@q78g2000hsh.googlegroups.com> > > I hope this is trivial, and I apologize ahead of time if so. Would > > this perhaps be a compilation issue? Something we have to turn on in > > the python compile? > > Usually, you need not only the libraries but also the headers at > compilation time. Most probably these were missing. > > Diez Thank you for our response. Do you mean that the ncurses header should be in /usr/include upon compilation of python? Will python automatically pick up on these headers, or would I need to change compilation options? Thanks! -Blaine From __peter__ at web.de Sat Mar 15 18:09:57 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Mar 2008 23:09:57 +0100 Subject: Python Generators References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: mpc wrote: > I am trying to write a while loop that will iterate over generators to > capture all the headers of FFCache directories. However, the > generators embedded within the argument of another generator do not > seem to re-initiate. the example below loops through and initiates the > generator embedded in the argument only once. Can anyone explain while > the generator will not re-initiate, and suggest a simple fix? A generator or generator expression does indeed only run once. >>> gen = (i for i in range(5) if i%2) >>> for i in range(3): ... print "---", i, "---" ... for k in gen: print k, ... print ... --- 0 --- 1 3 --- 1 --- --- 2 --- The fix is to use a list or list comprehension, or make a new generator every time you need one: >>> for i in range(3): ... print "---", i, "---" ... gen = (i for i in range(5) if i%2) ... for k in gen: print k, ... print ... --- 0 --- 1 3 --- 1 --- 1 3 --- 2 --- 1 3 At first glance I would guess that in your case all_caches is the culprit that has to be moved into the 'while True: ...' loop. > while True: > n += 1 > time.sleep(0.5) all_caches = (path for path,dirlist,filelist in os.walk("/Users/") if '_CACHE_MAP_' in filelist) > for path in all_caches: > headers = generate_headers(path) > for h in headers: > print h,n (Untested, because you didn't bother to provide a self-contained example) Peter From haraldarminmassa at gmail.com Wed Mar 12 06:09:59 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 12 Mar 2008 03:09:59 -0700 (PDT) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Doug, > File "VisionTrainer.py", line 49, in > File "SessionController.pyc", line 53, in > File "VisionEgg\__init__.pyc", line 42, in > File "VisionEgg\ParameterTypes.pyc", line 28, in > File "Numeric.pyc", line 93, in > File "Precision.pyc", line 26, in > File "Precision.pyc", line 23, in _fill_table > File "Precision.pyc", line 18, in _get_precisions > TypeError: data type not understood to my knowledge, "data type not understood" is a message not from core Python, but rather thrown from "your" code. What is happening around Precision.py, line 18? What does trigger that exception? My guess is, you are dealing with some custom imported modules which define "data type"s. (PIL does something similiar for supported images)... that is, some module is trying to import all definitions from a specific directory. That "dynamic importing" fails within py2exe --- all the importing has to be definit at py2exing-time. Please ready http://www.py2exe.org/index.cgi/PIL_and_py2exe and the other receipe on py2exe.org and try to adapt that knowledge to your application. Harald Harald From zubeido at yahoo.com.br Sun Mar 30 10:44:42 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sun, 30 Mar 2008 07:44:42 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> Message-ID: <1d297e7f-df0b-4b4a-8639-a4ca3505b3ca@59g2000hsb.googlegroups.com> Ok regarding Gerhard's comment of the try, except, pass, i came to understand that it's really bad code. And i should have referred that i put that there be cause i was getting: Traceback (most recent call last): File "C:\Python25\Projects\cp.py", line 48, in db = db() File "C:\Python25\Projects\cp.py", line 19, in __init__ self.cursor.execute( "CREATE TABLE database (album,filepath)" ) OperationalError: table database already exists But when i tried to handle the Operational error with : try: self.cursor.execute( "CREATE TABLE database (album,filepath)" ) except OperationalError: pass I would got: NameError: global name 'OperationalError' is not defined I searched the Internet and found that sqlite3.OperationalError was missing. Dumb me. Now even though i've been reading a bit about exceptions in python tutorial i've come to realize that my approach won't give me the results i want. To my understanding the try statement will still execute the statement within it until it produces the error. So even if i caught this OperationalError i wouldn't know what to do with it. What i'm going to study is whether it's possible to evaluate if a table already exists, and if so act accordingly. Duncan Booth wrote: >Are you absolutely certain of that? If you use print to try to debug the >value of an object you should usually use repr > print repr(audio['album']) As Gerhard correctly guessed i'm a newbie and didn't know of the existence repr. I've been reading about it in python documentation but have yet to analyze it more carefully. I guess the parentheses are just some form of maniac stupidity. Will try to be more clean about them. Thanks for all the patience and hope i've been more forthcoming in this post. From castironpi at gmail.com Thu Mar 27 07:38:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:38:24 -0700 (PDT) Subject: Partial Function Application and implicit self problem References: <47EB6480.2080402@wtf.websiteburo.oops.com> <47eb7f60$0$5151$426a74cc@news.free.fr> Message-ID: <40e8142f-ac8e-45ca-b7e6-ea8454b88021@m3g2000hsc.googlegroups.com> On Mar 27, 6:05?am, Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : > > > > > > > Bruno Desthuilliers wrote: > >> Gabriel Rossetti a ?crit : > (snip) > >>> ? registerServiceAtomic = partial(__registerService, True) > >>> registerServiceNonAtomic = partial(__registerService, False) > > >>> I should pass self when applying partial, but then I can't do that > >>> since self is not available there. Does anyone have any ideas? > > >> registerServiceAtomic = partial(__registerService, atomic=True) > >> registerServiceNonAtomic = partial(__registerService, atomic=False) > > >> Caveat: you'll have to either invert the order of the atomic and > >> service params, or call the partials with named arg for service. > > > Ok, thanks, I didn't know you could do that, I though partial was always > > left to right > > It's left to right for positional arguments. Using named arguments, you > can pass them in whatever order. > > > (I had read that about curry) > > Which 'curry' ?-) I think 'prefix' should go in there. Can you try: partial( G.f, a, b ) ( self= obj )? (If that's too brief let me know.) From kyosohma at gmail.com Mon Mar 24 13:44:53 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 24 Mar 2008 10:44:53 -0700 (PDT) Subject: Is IronPython real Python? References: Message-ID: <2f252763-0fa8-4053-8cd7-c8b3395d3788@u10g2000prn.googlegroups.com> On Mar 24, 12:00 pm, jmDesktop wrote: > I know that IronPython and CPython are different in that one does not > use the .net framework, but are they both really the same Python > language. From my basic understanding, it will depend on what the > programmer's goal is as to which of the two would be used, but I > didn't know if they were really the same language. I would say that they're mostly the same. IronPython allows the developer to use any of the .NET libraries within their Python program, much like Jython allows Python to import Java libraries. The main IronPython website has a wiki that outlines the differences: http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Differences&referringTitle=Home Mike From jeff at schwabcenter.com Tue Mar 4 16:53:19 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 04 Mar 2008 13:53:19 -0800 Subject: SV: Polymorphism using constructors In-Reply-To: <635ndjF2551ajU1@mid.individual.net> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: What does "SV" in the subject mean? From miki.tebeka at gmail.com Tue Mar 18 12:48:58 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 18 Mar 2008 09:48:58 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: Message-ID: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Hello Dave, > Hi All. I've been formulating in my head a simple image editor. I > actually started prototyping is some time ago in Java, but am liking > Python more and more. My editor will be nowhere near the level of Gimp/ > Photoshop, but I do need fast pixel level control and display. For > instance, that means no automatic anti-aliasing and that I will be > implementing my own line drawing algorithms. > > I've got the high level architectual aspects of my program down, but > am stuck on what graphics API to use. I want a canvas area of > adjustable size which users can draw on with as little lag as > possible. The canvas area will be composed of layers (i.e. I require > an alpha channel) and I need to be able to zoom in and out of it (zoom > levels will be at fixed intervals, so this can be simulated if need > be.) > > I started looking at PyGame but realize that I need to integrate a GUI > into the whole thing (or integrate the image ?into the GUI rather) and > I didn't see a straightforward way to do that. Of course, I don't even > know if PyGame is the right API for the job anyways :P > > Any thoughts or ideas that could help me get started? Thanks! Apart from PIL, some other options are: 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object you can draw on 2. A bit of an overkill, but you can use PyOpenGL 3. ImageMagick bindings? (http://www.imagemagick.org/script/api.php) HTH, -- Miki http://pythonwise.blogspot.com From kyosohma at gmail.com Sat Mar 15 18:04:02 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 15 Mar 2008 15:04:02 -0700 (PDT) Subject: Python for BlackBerry References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Message-ID: <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> On Mar 15, 7:24 am, "Sandipan Gangopadhyay" wrote: > Is there a Python for BlackBerry? Thanks. > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of E-Lo > Sent: Saturday, March 15, 2008 6:03 AM > To: python-l... at python.org > Subject: Python for Palm OS > > Is there any other edition of Python for Palm OS instead of Pippy? > --http://mail.python.org/mailman/listinfo/python-list You might look at Mobile Python. I'm not sure if it works on Blackberry though: http://www.mobilepythonbook.org/ Mike From ttkk1024 at gmail.com Fri Mar 7 21:30:13 2008 From: ttkk1024 at gmail.com (smalltalk) Date: Fri, 7 Mar 2008 18:30:13 -0800 (PST) Subject: the way of "import" Message-ID: <5baa5fc3-264d-4f9d-8c58-07b31f68fc2d@u10g2000prn.googlegroups.com> I have three files names t1.py,t2.py,t3.py in e:\test\dir1,of course dir2 is exsit the content of t1.py as follow: t1.py import os print 'this is t1.py' os.chdir('..\\dir2') the content of t2.py as follow: print "this is t2.py" the content of t3.py as follow: import t1 import t2 if i run t3.py in cmd of windows as follow: python t3.py no errors show if i run t3.py in idle: >>> import t3 this is t1.py Traceback (most recent call las File "", line 1, in File "t3.py", line 2, in ImportError: No module named t2 can you give me a help? From grahn+nntp at snipabacken.se Sun Mar 30 19:15:39 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 23:15:39 GMT Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> Message-ID: On Sun, 30 Mar 2008 04:48:59 -0700 (PDT), hdante wrote: > On Mar 30, 4:31 am, John Machin wrote: >> On Mar 30, 3:58 pm, hdante wrote: >> > If you have some legacy binary file that you need to process, try >> > creating a C program that freads the binary file and printfs a text >> > equivalent. >> >> ... and that couldn't be done faster and better in Python?? > > No. A C struct is done faster and better than python (thus, the > correctness check is faster in C). Also, chances are high that there's > already an include file with the binary structure. If a C struct defines the file format, he is probably screwed already. There are no guarantees that even different compilers on the same machine have the same struct layout. I have never seen this done by a serious program. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fireball74 at NOSPAM.gmail.NOSPAM.com Fri Mar 14 14:05:00 2008 From: fireball74 at NOSPAM.gmail.NOSPAM.com (fireball) Date: Fri, 14 Mar 2008 13:05:00 -0500 Subject: "Open with IDLE" Missing Message-ID: <47dabe43$0$6483$4c368faf@roadrunner.com> I installed Parallels Desktop and Win XP Pro on my iMac for testing purposes. I installed Python 2.5.2, wxPython, and PythonCard. I cannot get the "Open with IDLE" in an Explorer window to work. All the registry entries are there too. Any ideas? Thanks! Jay From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 09:54:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 13:54:08 -0000 Subject: Shortcutting the function call stack References: Message-ID: <13ufck0ccif5c1f@corp.supernews.com> On Mon, 24 Mar 2008 04:21:29 -0700, Julien wrote: > Hello all, > > I would like to do something like: > > def called(arg) > if arg==True: > !!magic!!caller.return 1 Instead of writing "if arg==True", or "if (arg==True)==True", or even "if ((arg==True)==True)==True", you should just write: "if arg:" That's probably all you need. > > def caller(arg) > called(arg) > return 2 def called(arg): return 1 def caller(arg): if arg: return called(arg) return 2 And if you wish to change the place where the decision is made: def called(arg): if arg: return 1 else: return 2 def caller(arg): return called(arg) > Here, the fake !!!magic!!! represents a statement (which I ignore) that > would make the caller function return a value different from what it'd > return normally. The statement you use to return a value different from what you would normally return is the "return" statement. You need to call that statement from the function doing the returning, not from another function. > The reason I want that is because I don't want the caller function to > know what's going on in the called function, and be shortcut if the > called function think it's necessary. Not knowing what's going on in called functions is why functions were invented in the first place. That's what they do. What shortcut do you think you might want to take? There are probably better solutions than playing around with the internals of the interpreter. I have a feeling you are trying to implement some sort of function cache, maybe... def check_in_cache(arg): # fake cache code if arg: !!magic!!caller.return 1 # not real Python def function(arg): check_in_cache(arg) # magic happens here # but if it doesn't, we do lots of calculations here return 2 # and finally return Is that the sort of thing you're trying for? If so, that's not the way to go about it. -- Steven From fetchinson at googlemail.com Wed Mar 12 21:05:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 12 Mar 2008 18:05:45 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > The photos are just coming straight from my digital camera. Same > > format (JPEG), varying size (6-10 megapixel) and I would like to be > > able to pick one and then query the database for similar ones. For > > example: I pick a photo which is more or less a portrait of someone, > > the query should return other photos with more or less portraits. If I > > pick a landscape with lot of green and a mountain the query should > > result in other nature (mostly green) photos. Something along these > > lines, of course the matches won't be perfect because I'm looking for > > a simple algorithm, but something along these lines. > > > > Ah. In that case, SIFT isn't for you. SIFT would work well if you have > multiple photos of the same object. Say, a building from different > angles, or the a vase against different backdrops. > > If I'm understanding your correctly, what you're attempting here is very > general and well into the highly experimental. I've been wishing for > such a feature to appear in something like Google Image Search > (pick/submit a photo and return similar images found on the web). I'm > sure if there's even a practical solution, Google (or MS) would be on it > already. > > The problem is that there isn't really one. Despite what you may see > claimed in university press releases and research papers, the current > crop of algorithms don't work very well, at least according to my > understanding and discussion with researchers in this field. The glowing > results tend to be from tests done under ideal conditions and there's no > real practical and commercial solution. > > If you restrict the domain somewhat, there are some solutions, but none > trivial. You are probably aware of the face searches available on Google > and Live. > > The histogram approach suggested by Shane Geiger may work for some cases > and in fact would work very well for identical resized images. I doubt > it will work for the general case. A mountain with a grassy plain at > noon has quite a different histogram from one at sunset, and yet both > have related content. Manual tagging of the images, a la Flickr, would > probably be your best bet. Since you seem to know quite a bit about this topic, what is your opinion on the apparently 'generic' algorithm described here: http://grail.cs.washington.edu/projects/query/ ? So far it seems to me that it does what I'm asking for, it does even more because it can take a hand drawn sample image and query the database for similar photos. There is even a python implementation for it here: http://members.tripod.com/~edcjones/pycode.html On the histogram method I agree that it won't work partly because of what you say and partly because it is terribly slow since it's comparing every single pixel. Thanks, Daniel From pavlovevidence at gmail.com Fri Mar 14 23:42:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 14 Mar 2008 20:42:56 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> Message-ID: On Mar 14, 6:37 pm, Alex wrote: > On Mar 13, 6:21 pm, Carl Banks wrote: > > > On Mar 13, 7:02 am, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > Alex a ?crit : > > > (sni) > > > > > First of all thanks all for answering! > > > > > I have some environment check and setup in the beginning of the code. > > > > I would like to move it to the end of the script. > > > > Why ? (if I may ask...) > > Sure, because of a readability (similar to function declarations in > C). > > > > > > > But I want it to > > > > execute first, so the script will exit if the environment is not > > > > configured properly. > > > > If you want some code to execute first when the script/module is loaded, > > > then keep this code where it belongs : at the beginning of the script. > > > I concur with Bruno's recommendation: stuff you want to do first > > should come first in the script. Things like BEGIN blocks hurt > > readability because you can't identify where execution begins without > > reading the whole file. > > > Having said that, one thing that often happens in Python scripts is > > that all the functions are defined first, then the script logic > > follows. So you could put the meat of your script in a function, then > > the "BEGIN" stuff after that functions: > > > def run_script(): > > # > > # script contained in this long function > > # > > > # Then test preconditions here... > > if os.environ["HELLO"] != "WORLD": > > sys.exit(2) > > > # Then call the run_script functions > > run_script() > > > But having said THAT, I don't recommend you do that with > > preconditions. If the script has a quick early exit scenario, you > > really ought to put that near the top, before the function > > definitions, to clearly show to a human reader what is necessary to > > run the script. > > > Carl Banks > > Hi, > > Maybe i was a little bit unclear... I meant that i wanted to do > something like this: > > #!usr/bin/env python > > check_env() > > from subprocess import * > > class MyClass: > # Class definition > > def check_env(): > # Code > > if __name__ == "__main__": > # Script logic > > The thing is, as i saw, that Python doesn't recognize the > "check_env()" function before it reaches the "def" statement. You could rearrange it like this and it will work: #!usr/bin/env python def check_env(): # Code check_env() from subprocess import * class MyClass: # Class definition if __name__ == "__main__": # Script logic Or, better yet, do what Arnaud Delobelle suggests. It's not a big deal to move imports down the page a bit, as long as you throw in a few clear comments explaning what you're doing and why. You might also consider putting check_env() in a separate module. Carl Banks From Lie.1296 at gmail.com Tue Mar 11 11:58:37 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 08:58:37 -0700 (PDT) Subject: __iter__ yield References: Message-ID: On Mar 10, 3:58 am, duccio wrote: > Hello! > Someone knows if it's possible to make this __iter__ function with just > one 'yield' intead of two? > Is there some simpler way to make this __iter__ iter through all nodes? > Thanks! > > class Node: > def __init__(self, data=None): > self.childs=[] > self.data=data > def appendNode(self, n): > node=Node(n) > self.childs.append(node) > return node > def __str__(self): > return '<'+str(self.data)+'>' > def __iter__(self): > yield self #1 > for n in self.childs: > for nn in n.__iter__(): > yield nn #2 > > n=Node() > n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) > n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) > for node in n: > print node Technically, the root node isn't a child node, and thus it shouldn't show up in the iteration. I think a more semantically correct way for this is to have the __str__() returns the current Node + All Descendants Nodes (like the one you wanted for __iter__) and while __iter__ only yields the child nodes (used by the __str__ to iterate through itself), like this: class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): ## Returns root node + all descendants return '<%s>\n' % self.data + ''.join(str(child) for child in self) def __iter__(self): ## yields childrens only for n in self.childs: yield n n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) ## Note I added the line below for testing branches in ## lower nodes n.childs[0].appendNode(222) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) print n The missing functionality of returning current Node's name can be easily solved by adding it in another function. The main problem with __iter__ behavior you originally wanted is that it doesn't reflect the nesting behavior of the Node class and you could've been equally well served by using flat data structure if you do that. I smell a bad data structure design here, you'd better revise your design. To reflect the nesting, you could do it like this: class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): ## This reflects nesting behavior better return '\n<%s>' % (str(self.data) + ''.join(str(child) for child in self)) ## Uncomment this and Comment the statement above ## for an alternate data structure you might be ## interested in, the format below resembles HTML ## curNode = str(self.data) ## return '\n<%s>%s\n' % ( ## curNode, ## ''.join(str(child) for child in self), ## curNode) def __iter__(self): for n in self.childs: yield n n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.childs[0].appendNode(222) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) print n This changes the data structure quite a lot though, but the data structure is bad from the start. From andrei.avk at gmail.com Mon Mar 24 15:21:04 2008 From: andrei.avk at gmail.com (AK) Date: Mon, 24 Mar 2008 14:21:04 -0500 Subject: ANN: Tobu 0.4j Message-ID: <47e7f111$0$16691$4c368faf@roadrunner.com> This is an initial announcement. Tobu is a freeform database / tagger / PIM and more. It works in both Linux and Windows and uses wxPython framework and pysqlite. Comments, suggestions, feature requests and critique are gladly appreciated. Tutorial with links to download page and to graphical overview page is located at the following link. It's best to start with graphical overview page that shows screenshots of main window and menus with thorough explanations of functionality of most items. http://www.lightbird.net/tobu/ From aisaac at american.edu Thu Mar 13 15:48:28 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 13 Mar 2008 19:48:28 GMT Subject: no more comparisons In-Reply-To: References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: >> Dan Bishop wrote: >>> def cmp_key(cmp_fn): >>> class CmpWrapper(object): >>> def __init__(self, obj): >>> self.obj = obj >>> def __cmp__(self, other): >>> return cmp_fn(self.obj, other.obj) >>> return CmpWrapper > On Mar 13, 12:38 pm, Alan Isaac wrote: >> how is this supposed to work if __cmp__ is no longer >> being called? (Which was my understanding.) Carl Banks wrote: > It won't. In Python 3.0 you'd have to write this class in terms of > rich comparisons (__lt__, __gt__, etc.). Exactly. So something simple (define an anonymous function) has become a bit of a pain. On the other hand, I've looked through my extant code and have not found a use of ``cmp`` that I cannot work around. So maybe this is not as bad as I feared. What are some use cases that will clearly be harder (i.e., at least require a slightly elaborate wrapper) after this change? Cheers, Alan Isaac From roy at panix.com Wed Mar 12 18:15:54 2008 From: roy at panix.com (gnu.gcc.help) Date: Wed, 12 Mar 2008 15:15:54 -0700 (PDT) Subject: How to parse this timestamp? Message-ID: I've got timestamps in a file that look like: [19-Aug-2007 07:38:43+216ms NZST] How can I parse them? I don't see any way to build a strftime() format string that can handle the +216ms part. The best I can see is tearing it all apart with a regex, but I'm trying to avoid that pain if I can. (PS: I have no clue why google groups thinks it should put "gnu.gcc.help" on the from line) From erikwickstrom at gmail.com Fri Mar 14 14:47:05 2008 From: erikwickstrom at gmail.com (erikcw) Date: Fri, 14 Mar 2008 11:47:05 -0700 (PDT) Subject: Custom Exception Value? Message-ID: <5fbe35d4-6590-41c2-824d-0b1656173829@x30g2000hsd.googlegroups.com> Hi, When I use sys.exc_info() on one of my custom exception classes, the "message"/value isn't returned. But it is when I use a built in exception. Example: In [32]: class Test(Exception): ....: def __init__(self, x): ....: self.value = x ....: def __str__(self): ....: return repr(self.value) ....: ....: In [39]: try: ....: raise Test('mess') ....: except: ....: sys.exc_info() ....: ....: Out[39]: (, Test(), ) In [40]: try: ....: 1/0 ....: except: ....: sys.exc_info() ....: ....: Out[40]: (, ZeroDivisionError('integer division or modulo by zero',), ) Wy does the output of ZeroDivisionError appear in sys.exc_info() but for test it is just Test() (should be Test('mess') right??) Thanks! From wingi at gmx.com Tue Mar 11 12:52:43 2008 From: wingi at gmx.com (wingi at gmx.com) Date: Tue, 11 Mar 2008 09:52:43 -0700 (PDT) Subject: Exctract GIF comment from image Message-ID: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Hi, simple question: The PIL does not support reading the optional description in GIF Images. http://www.pythonware.com/library/pil/handbook/format-gif.htm After some reasearch I could not find a python solution for this, any suggestions? Thanx, Wingi. From zentraders at gmail.com Sat Mar 22 12:38:24 2008 From: zentraders at gmail.com (Zentrader) Date: Sat, 22 Mar 2008 09:38:24 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> Message-ID: <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> > if ('one', 'two') are in f: ... "are" gives me an error in Python 2.5 with a "from future import *" statement included. What version and platform are you running. Also, the docs don't mention it. http://docs.python.org/ref/keywords.html From ptmcg at austin.rr.com Wed Mar 5 14:29:30 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 5 Mar 2008 11:29:30 -0800 (PST) Subject: What is a class? References: Message-ID: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> On Mar 5, 12:50?pm, castiro... at gmail.com wrote: > What is a class that is not a module? Please stop posting these one-liner beginner questions. If you can type it in one line, you can enter it on the Google.com or Ask.com query page and get a wealth of *existing* information, from tutorials, documentation, online presentations. If you are able to phrase such a question, you are capable of doing a little research and experimentation on your own. These posts translate to "I'm too lazy to use Google, or too cheap to buy a Python book, or too lazy to read it, or too impatient to do my own experimenting - much better to just post on c.l.py and have the answer spoon-fed to me!" I refuse to spoon feed you the answer to this question when plenty of supporting material is already available. -- Paul From bearophileHUGS at lycos.com Mon Mar 24 11:52:59 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 24 Mar 2008 08:52:59 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as a firstprogramming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <5d973779-507c-4248-a218-61fa1c870003@m44g2000hsc.googlegroups.com> Paul Rubin>It's at least pretty good. It's not ideal, but nothing ever is.< I agree. At the moment Python is among the best languages for that, but it's not perfect for that purpose. I think newbies may need a bit more structured language, where you have to put things in a certain order to have a working program. I think this may teach them some good programming habits. Pascal is a bit too much old today, but it helps learn how to program in a tidy way. I am not sure about this, I'd like to have more data to be able to sort out this freedom/structure alternative regarding teaching languages. Another possible downside of Python is that it doesn't allow you to know very well what's under the language, so you can't use pointers and memory very well, so you can't learn those things very well. You need a different language for that, like C (or Pascal) or assembly, but such languages are useful later, and less as very first languages, especially for very young people. Paul Rubin>Chris Okasaki (of functional data structures fame) has an interesting blog post about why indentation-based structuring is a big help for teaching:< I have quite appreciated that article, and other people are doing similar things for C and C++ (I'd like to do something similar for D): http://blog.micropledge.com/2007/09/nobraces/ And OCaml: http://people.csail.mit.edu/mikelin/ocaml+twt/ Arnaud Delobelle>My other 'coming of age' was when I took a lambda- calculus course at university. I felt like a man who's had a black and white TV set all his life and watches colour TV for the first time.< Scheme-like languages are surely interesting, and eventually a programmer can learn one of them, but I think as a very first language Python is fitter, because its syntax is more compatible with a normal little trained human mind. 7stud>Beginning programmers in grades 9-12 are not going to understand issues like that, and it would be a mistake to try and introduce them. Beginning programmers should be concentrating their efforts on learning the syntax of a language and basic constructs like for-loops and if statements.< This is wrong. Some languages like Scheme are quite fit for young people, and they don't even need a for loop. A 7-9 years old person is able to understand quite a lot, and computer science and programming aren't based on syntax. They are more based on the fun of problem solving, and similar things. Syntax is important because it's the tool that allows you to tell the computer how to compute the results of the problems you have (usually) already solved, but it can't be the purpose, even in a first course of programming. When you want to teach painting to a 6 year old child your purpose isn't teaching her/him all about the structure of the canvas and brushes and the chemistry of the pigments, but how to have fun putting all the colors on the canvas/ paper, trying to create some image, for fun. (On the other hand you can teach to love chemistry to a 6-8 year old person, showing how much it can be fun, if you start talking about the chemistry behind the colors of fireworks, but that's not panting anymore). Ben C>Why does Python not have a switch or until statement?< Maybe because it thinks syntax minimalism is a virtue, or maybe because they aren't easy to add (try to design a do-while using Python- like syntax). Ben C>Why are very common objects (stack, queue, linked list) not builtin? etc.< Because it was a small language, used for scripting purposes, I think. You need those data structures if you want higher performance (in speed and/or memory used) but performance was not one of the main purposes of Python. Another purpose for those data structures is to teach them, but a good teaching language is probably one that allows you to write your own versions of them. Today the collections module and other built-in modules gives you some of those data structures, you just need to import them, so using them isn't much a hassle, even if they aren't built in. Aahz>The problem with lambda is that too often it results in clutter< Probably I am missing your point, but I'd like to remind people the syntax for lambdas in the last C# versions: x, y => x * 2 + y Instead of the Python syntax: lambda x, y: x * 2 + y I think that C# syntax is nice and readable enough. Terry Reedy>[lot of things] Yes, fundamentally different categories of types are (sensibly) treated differently with repect to definition and namespace names, but calling that 'disharmony' depends on the listener.< Thank you for your interesting explanation. Bye, bearophile From lbonafide at yahoo.com Sun Mar 16 12:38:06 2008 From: lbonafide at yahoo.com (lbonafide at yahoo.com) Date: Sun, 16 Mar 2008 09:38:06 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> On Mar 16, 6:10 am, Bruce Eckel wrote: > I think a lot of people have been caught up in the idea that we need > to commercialize Python, and ride some kind of wave of publicity the > way that Java and C# and Rails seem to have done. This coming from someone who caught the Java wave and rode it for a decade. From magdoll at gmail.com Tue Mar 11 18:41:24 2008 From: magdoll at gmail.com (Magdoll) Date: Tue, 11 Mar 2008 15:41:24 -0700 (PDT) Subject: merging intervals repeatedly Message-ID: Hi, I have to read through a file that will give me a bunch of intervals. My ultimate goal is to produce a final set of intervals such that not two intervals overlap by more than N, where N is a predetermined length. For example, I could read through this input: (1,10), (3,15), (20,30),(29,40),(51,65),(62,100),(50,66) btw, the input is not guaranteed to be in any sorted order. say N = 5, so the final set should be (1,15), (20, 30), (29, 40), (50, 100) Is there already some existing code in Python that I can easily take advantage of to produce this? Right now I've written my own simple solution, which is just to maintain a list of the intervals. I can use the Interval module, but it doesn't really affect much. I read one interval from the input file at a time, and use bisect to insert it in order. The problem comes with merging, which sometimes can be cascading. ex: read (51,65) ==> put (51,65) in list read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) read (50,66) ==> merge with (51,65) to become (50,66) ==> now can merge with (62,100) Of course I can check for cascading merges by pivoting around the position where the insertion would've taken place...but just wondering, is there some other nice way to do this? I also intuitively don't sense a need for using trees, unless someone's already written it, the interface is easy to use, and it won't result in more insert/ delete/structure changes that nullifies its beauty...(also I'm not using the output list for searching) Thanks in advance. From python.list at tim.thechases.com Mon Mar 10 11:03:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Mar 2008 10:03:59 -0500 Subject: parsing directory for certain filetypes In-Reply-To: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <47D54DDF.7000801@tim.thechases.com> > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? > > here it is... > > from string import split > from os.path import isdir,join,normpath > from os import listdir > > def parsefolder(dirname): > filenms=[] > folder=dirname > isadr=isdir(folder) > if (isadr): > dirlist=listdir(folder) > filenm="" > for x in dirlist: > filenm=x > if(filenm.endswith(("txt","doc"))): > nmparts=[] > nmparts=split(filenm,'.' ) > if((nmparts[1]=='txt') or (nmparts[1]=='doc')): > filenms.append(filenm) > filenms.sort() > filenameslist=[] > filenameslist=[normpath(join(folder,y)) for y in filenms] > numifiles=len(filenameslist) > print filenameslist > return filenameslist > > > folder='F:/mysys/code/tstfolder' > parsefolder(folder) It seems to me that this is awfully baroque with many unneeded superfluous variables. Is this not the same functionality (minus prints, unused result-counting, NOPs, and belt-and-suspenders extension-checking) as def parsefolder(dirname): if not isdir(dirname): return return sorted([ normpath(join(dirname, fname)) for fname in listdir(dirname) if fname.lower().endswith('.txt') or fname.lower().endswith('.doc') ]) In Python2.5 (or 2.4 if you implement the any() function, ripped from the docs[1]), this could be rewritten to be a little more flexible...something like this (untested): def parsefolder(dirname, types=['.doc', '.txt']): if not isdir(dirname): return return sorted([ normpath(join(dirname, fname)) for fname in listdir(dirname) if any( fname.lower().endswith(s) for s in types) ]) which would allow you to do both parsefolder('/path/to/wherever/') and parsefolder('/path/to/wherever/', ['.xls', '.ppt', '.htm']) In both cases, you don't define the case where isdir(dirname) fails. Caveat Implementor. -tkc [1] http://docs.python.org/lib/built-in-funcs.html From bearophileHUGS at lycos.com Fri Mar 28 08:24:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 28 Mar 2008 05:24:41 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> Message-ID: <1b5564b6-8e40-43e1-90bd-cea0dd3a8edf@l42g2000hsc.googlegroups.com> Duncan Booth: > Both this and raj's suggestion create a single sorted list. Your suggestion > creates two lists: the unsorted one and a separate sorted one. In most > cases the difference is probably insignificant, but if you have a *lot* of > values it might make a difference. The good thing of Python 3.0 is that it forces you to do the right thing here :-) Bye, bearophile From gagsl-py2 at yahoo.com.ar Sun Mar 9 16:19:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 18:19:05 -0200 Subject: the way of "import" References: <5baa5fc3-264d-4f9d-8c58-07b31f68fc2d@u10g2000prn.googlegroups.com> Message-ID: En Sat, 08 Mar 2008 00:30:13 -0200, smalltalk escribi?: > I have three files names t1.py,t2.py,t3.py in e:\test\dir1,of course > dir2 is exsit > the content of t1.py as follow: > t1.py > import os > print 'this is t1.py' > os.chdir('..\\dir2') > the content of t2.py as follow: > print "this is t2.py" > the content of t3.py as follow: > import t1 > import t2 > > > if i run t3.py in cmd of windows as follow: > python t3.py > > no errors show > > if i run t3.py in idle: >>>> import t3 > this is t1.py > Traceback (most recent call las > File "", line 1, in > File "t3.py", line 2, in > ImportError: No module named t2 > > can you give me a help? Which Python version? Which Windows version? With IDLE from Python 2.5.1 on XP I don't get the error (and that's the right thing) -- Gabriel Genellina From code at pizzashack.org Mon Mar 24 22:03:56 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Mar 2008 22:03:56 -0400 Subject: Python 2.2.1 and select() In-Reply-To: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> Message-ID: <20080325020356.GF26870@dragontoe.org> On Mon, Mar 24, 2008 at 05:52:54PM -0700, Noah wrote: > On Mar 24, 2:58 pm, Derek Martin wrote: > > If and only if the total amount of output is greater than the > > specified buffer size, then reading on this file hangs indefinitely. > I think this is more of a limitation with the underlying clib. > Subprocess buffering defaults to block buffering instead of > line buffering. That's an interesting thought, but I guess I'd need you to elaborate on how the buffering mode would affect the operation of select(). I really don't see how your explanation can cover this, given the following: 1. The subprocess used to test, in both the case where it worked, and the case where it did not, was the very same shell script -- not a compiled program (well, bash technically). As far as I'm aware, there haven't been any significant changes to the buffering mode defaults in glibc... But I could easily be mistaken. 2. By default, STDERR is always unbuffered, whether or not STDOUT is a terminal device or not. 3. The actual subproc I care about is a perl script. 4. Most importantly, the whole point of using select() is that it should only return a list of file objects which are ready for reading or writing. In this case, in both the working case (Python 2.4+ on Red Hat) and the non-working case (Python 2.2.1 on Debian 3.1), select() returns the file object corresponding to the subprocess's STDOUT, which *should* mean that there is data ready to be read on that file descriptor. However, the actual read blocks, and both the parent and the child go to sleep. This should be impossible. That is the very problem select() is designed to solve... Moreover, we've set the buffer size to 8k. If your scenario were correct, then at the very least, as soon as the process wrote 8k to STDOUT, there should be data ready to read. Assuming full buffering is enabled for the pipe that connects STDOUT of the subprocess to the parent, the call to select() should block until one of the following conditions occur: - 8k of data is written by the child into the pipe - any amount of data is written to STDERR - the child process terminates The last point is important; if the child process only has 4k of data to write to STDOUT, and never writes anything to STDERR, then the buffer will never fill. However, the program will terminate, at which point (assuming there was no explicit call to close() previously) the operating system will close all open file descriptors, and flush all of the child's I/O buffers. At that point, the parent process, which would be sleeping in select(), will wake up, read the 4k of data, and (eventually) close its end of the pipe (an additional iteration through the select() loop will be required, I believe). Should the program write output to STDERR before the 8k STDOUT buffer is full, then again, the parent, sleeping in select(), will awaken, and select will return the file object corresponding to the parent's end of the pipe connecting to the child's STDERR. Again, all of this is the essence of what select() does. It is supposed to guarantee that any file descriptors (or objects) it returns are in fact ready for data to be read or written. So, unless I'm missing something, I'm pretty certain that buffering mode has nothing to do with what's going on here. I think there are only a few possibilities: 1. My implementation of the select() loop is subtlely broken. This seems like the most likely case to me; however I've been over it a bunch of times, and I can't find anything wrong with it. It's undenyable that select is returning a file object, and that reads on that file object immediately after the call to select block. I can't see how this could be possible, barring a bug somewhere else. 2. select.select() is broken in the version of Python I'm using. 3. The select() system call is somehow broken in the Linux kernel I'm using. I tend to rule this out, because I'm reasonably certain someone would have noticed this before I did. The kernel in question is being used on thousands of machines (I'm not exaggerating) which run a variety of network-oriented programs. I can't imagine that none of them uses select() (though perhaps its possible that none use it in quite the manner I'm using it here). But it may be worth looking at... I could write an implementation of a select() loop in C and see how that works. If you can see any flaw in my analysis, by all means point it out! Thanks for your response. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From castironpi at gmail.com Sun Mar 16 20:27:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 17:27:28 -0700 (PDT) Subject: stdout custom Message-ID: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> The code should have extra colons. >>> class ThreadedOut: ... def __init__( self, old ): ... self._old= old ... def write( self, s ): ... self._old.write( ':' ) ... return self._old.write( s ) ... def flush( self ): ... self._old.flush() ... >>> import sys >>> thout= ThreadedOut( sys.stdout ) >>> olds= sys.stdout, sys.stderr, sys.__stderr__, sys.__stdout__ >>> sys.stdout= sys.stderr= sys.__stderr__= sys.__stdout__= thout >>> 0 :0: >>> >>> 123 :123: >>> >>> Specifically, before the prompts. Where does the prompt write come from; why doesn't it honor my settings of sys.stdout and sys.stderr? From mnordhoff at mattnordhoff.com Mon Mar 3 18:02:50 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 03 Mar 2008 23:02:50 +0000 Subject: clocking subprocesses In-Reply-To: References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> <5af6d8ab-880a-4873-9352-cf1aaae236e0@e6g2000prf.googlegroups.com> Message-ID: <47CC839A.6040509@mattnordhoff.com> barnburnr at gmail.com wrote: > On Mar 3, 12:41 pm, Preston Landers wrote: >> Run your command through the "time" program. You can parse the output >> format of "time", or set a custom output format. This mostly applies >> to Unix-like systems but there is probably an equivalent somewhere on >> Windows. >> >> Preston > > Thanks for the quick answer. That seems to work, though, I'll write a > timesubprocess() function which runs the program through time and > spits the formatted out to a file, then parses that file, then returns > the execution time. There doesn't appear to be a more elegant way to > do this. > > Kevin subprocess can do that easily. What about something like this? def timecall(args): p = subprocess.Popen(['time', '--format', '%e %U %S'] + args, stderr=subprocess.PIPE) p.wait() timings = p.stderr.readline().split() assert len(timings) == 3 timings = tuple(float(t) for t in timings) return timings It returns (real, user, sys), in seconds. The program's stdout goes to sys.stdout, I don't know where the program's stderr goes, and it really doesn't handle errors, but it's got the basic idea. -- From arnodel at googlemail.com Mon Mar 3 15:05:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 3 Mar 2008 12:05:47 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <7xzltgrbyi.fsf@ruckus.brouhaha.com> <5MSdnajOndDRq1banZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoj92xz.fsf@ruckus.brouhaha.com> Message-ID: <66231763-40ca-4686-a602-8b02ab956cc3@e60g2000hsh.googlegroups.com> On Mar 3, 4:39?pm, Paul Rubin wrote: [...] > You are right, C is even worse than I remembered. It's good enough to be the language used for the reference implementation of python :-) [...] -- Arnaud From sturlamolden at yahoo.no Thu Mar 20 14:29:19 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 11:29:19 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> Message-ID: <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> On 20 Mar, 19:09, Craig wrote: The culprit i here: > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 This binds these names to Python ints, but byref expects C types. Also observe that CacheSize and OpenMode should be c_short. From aboudouvas at panafonet.gr Sat Mar 29 08:32:11 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 29 Mar 2008 05:32:11 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> <2f3a59c2-ef31-426a-be34-bdb187ea3b22@c19g2000prf.googlegroups.com> Message-ID: On 28 ???, 20:06, Paul Boddie wrote: > On 27 Mar, 15:19, "Diez B. Roggisch" wrote: > > > > [Psyco maintenance and further development] > > > Nope, but I heard through the grapevine that while it won't be supported for > > all times to come, a new version is in the making. > > > But ultimately, the author says that the approach is flawed, so at *some* > > point it will be discontinued. But that could be said about nearly > > everything, couldn't it? > > From what I've seen from browsing publicly accessible materials, > there's a certain commercial interest in seeing Psyco updated > somewhat. So, whether it gets discontinued depends on the usual > factors of satisfying a need and there being qualified and motivated > people to work on it. > > Paul Let's hope that this isn't going to happen (psyco dicontinued). But i do not have positive thinking after an email i got for the author last week. Unless something has changed... From kyosohma at gmail.com Tue Mar 4 15:59:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 4 Mar 2008 12:59:41 -0800 (PST) Subject: Python an Exchange Server References: Message-ID: <326f9dbe-86b4-4f51-a450-ecdcb5a64ed4@i7g2000prf.googlegroups.com> On Mar 4, 1:20 pm, Yusniel wrote: > Hi friends. Someone know how to work with python and exchange > server?. If you do go the COM route, you'll probably want to ask questions of the PyWin32 user's group, which can be found here: http://mail.python.org/mailman/listinfo/python-win32 They talk about this sort of thing quite a bit. Mike From ericgorr at gmail.com Wed Mar 19 10:19:32 2008 From: ericgorr at gmail.com (Eric) Date: Wed, 19 Mar 2008 07:19:32 -0700 (PDT) Subject: [Q] SOAP Server in Python Message-ID: What is the best, well supported, way to write a SOAP Server in Python? Where can a good example be found? I do have a WSDL file. In PHP5, it is rather trivial to write a SOAP server once one has a WSDL file. For example, a simple SOAP Server written using PHP5 might look like: setClass( "MySoapServer" ); $server->handle(); ?> I am basically looking to do the same thing in Python as easily. Any help or pointers would be appreciated. thank you. From jeff at schwabcenter.com Sat Mar 15 13:54:33 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 15 Mar 2008 10:54:33 -0700 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Tim Roberts wrote: >> Jeff Schwab wrote: >>> Roel Schroeven wrote: >>>> castironpi at gmail.com schreef: >>>>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>>>> How do you feel about creator of Eliza? >>>>> What is Eliza? >>>> Does that question interest you? >>> Well played, sir. >>> >>> Earlier you said what is Eliza. Do you still feel that way? >> I am embarrassed to say that this vaguely disrespectful exchange made me >> laugh out loud. > > Serious: why do you think this is disrespectful? Not to speak for Tim, but I imagine it could be perceived as disrespectful because Prof. Weizenbaum has only recently passed away. In fact, I think the Prof would be very happy to see people having some fun at the expense of AI, which he saw as a real threat to human freedom. http://www-tech.mit.edu/V128/N12/weizenbaum.html "Named for the heroine of My Fair Lady, ELIZA was perhaps the first instance of what today is known as a chatterbot program. Specifically, the ELIZA program simulated a conversation between a patient and a psychotherapist by using a person?s responses to shape the computer?s replies. Weizenbaum was shocked to discover that many users were taking his program seriously and were opening their hearts to it. The experience prompted him to think philosophically about the implications of artificial intelligence, and, later, to become a critic of it. "In 1976, he authored Computer Power and Human Reason: From Judgment to Calculation, in which he displayed ambivalence toward computer technology and warned against giving machines the responsibility for making genuinely human choices. Specifically, Weizenbaum argued that it was not just wrong but dangerous and, in some cases, immoral to assume that computers would be able to do anything given enough processing power and clever programming." See also: http://www-ai.ijs.si/eliza-cgi-bin/eliza_script You: What is Eliza? Eliza: Does that question interest you? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 05:40:13 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 10:40:13 +0100 Subject: Why does python behave so? (removing list items) In-Reply-To: References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <47eb6b70$0$16903$426a74cc@news.free.fr> Thomas Dybdahl Ahle a ?crit : > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: >> Why does python create a reference here, not just copy the variable? > > Python, like most other oo languages, will always make references for =, > unless you work on native types (numbers and strings). > There's nothing like a "native type" in Python, and numbers and strings are ordinary objects. Python will always use references, period. From johnmfisher at comcast.net Tue Mar 18 17:18:05 2008 From: johnmfisher at comcast.net (John Fisher) Date: Tue, 18 Mar 2008 14:18:05 -0700 Subject: keyboard "interrupt" Message-ID: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Hi Group, I have been absent a while, mainly because I have been getting better at figuring out my own Python problems. But not this one... I have a timed loop performing certain tasks until a total period of time has elapsed. I would like to be able to interrupt the loop or set various flags during execution via keyboard input. raw_input seems to just stop everything cold. I want the ability to just sacn the keyboard buffer and see if something is there, then proceed normally in the loop if there is no input in the buffer. Make sense? Totally easy? Let me know... wave_man From cwitts at gmail.com Wed Mar 12 06:52:53 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 03:52:53 -0700 (PDT) Subject: Creating a file with $SIZE References: Message-ID: On Mar 12, 12:32?pm, "k.i.n.g." wrote: > Hi All, > > I would like create files of different size, taking size as user > input. I need to check the data transfer rates from one network to > another . In order to do this I will have to create files of diff size > and work out. I am new to Python > > Thanks in advance. > > KK Welcome to Python. If you just want to create files with random junk from the user input then maybe something along these lines would help: import sys, random def random_junk(number_of_characters): tmp = [] while number_of_characters: tmp.append(random.randint(0, 127)) number_of_characters -= 1 return ''.join(map(str,tmp)) if len(sys.argv) < 2: sys.exit('Usage:python %s '%sys.argv[0]) for each_argv in sys.argv[1:]: output_file = open(each_argv,'wb').write(random_junk(each_argv)) From deets at nospam.web.de Tue Mar 11 13:00:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Mar 2008 18:00:50 +0100 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> Message-ID: <63ns5vF1fcb15U1@mid.uni-berlin.de> > If you passed an object that has several methods to call (using tuple > or list) and you want to handle several softexceptions and ignore some > others, you must still pass an empty methods to the one you want to > ignore, cluttering the caller's code by significant degree: > > def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, > DO_NOTHING)): > if a == 0: raise callback(0) > try: > a += b > except ZeroDivisionError: > raise callback(1) > if a <= 0: raise callback(2) > raise callback(3) > return a > > somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, > DO_NOTHING)) You misunderstood. I'd pass something like a context-object, which wold look like this: def somefunc(a, b, context=NullContext()): if a == b: context.a_equals_b() .... Not more clutter than with only one callback. And the NullContext-object would actually serve as documentation on what events the code produces. >> def toplelevel(): >> def callback(a, b): >> if a == b: >> raise InterruptException() >> try: >> work(callback) >> except InterruptException: >> pass >> >> def work(callback=callback): >> a = 10 >> b = 20 >> callback(a, b) > > That's why I said most things that can be more cleanly handled by > SoftException can usually be handled in other forms, although in a > more cluttered way. > > That could be more cleanly written in SoftException as: > def work(): > a = 10 > b = 20 > raise Equal(a, b) > > def toplevel(): > try: > work() > except Equal, args: > a, b = args > if a == b: > raise InterruptException I totally fail to see where raise Equal(a, b) is less cluttered or not than callback(a, b) Actually, the latter is even less cluttered, misses a raise - if pure number of literals is your metric, that is. > If there is a syntax support, you could also make "resume" able to > transfer values: > > def somefunc(a, b): > if a == b: a, b = raise Equal(a, b) > > def toplevel(): > try: > somefunc(10, 20) > except Equal, args: > a, b = args[0], args[1] + 1 > resume a, b Sure, you can make all kinds of things, but so far you didn't come up with a comprehensive feature description that just _does_ specify what SEs are and what not. > Perhaps you meant: > raise_soft(SoftException) > > cause SoftException() may have side effects if called greedily Nope, I didn't, and it's beside the point. > That could be done, but when raise_soft() returns, it returns to the > code that raises it so it must be 'break'en: > > def caller(a, b): > if a == b: > raise_soft(SoftException) > break > > but this makes SoftException must break everytime, which make it lost > its original purpose, so you have to add return code to raise_soft > whether you want to break it or not: You didn't understand my example. If there is a handler registered, it will be invoked. If not, nothing will be raised. The exact same amount of state-keeping and lookups needs to be done by the SE-implementation. > That could be done, but when raise_soft() returns, it returns to the > code that raises it so it must be 'break'en: > def caller(a, b): > if a == b: > if raise_soft(SoftException): > break > > Compare to: > def caller(a, b): > if a == b: > raise SoftException > > And this also makes it impossible to have state-changing behavior > without some other weirder tricks That's not true. The with add_soft_handler(SoftException, handler): approach (I missed the handrel the first time, sorry) can easily throw an exception to interrupt, like this: def handler(e): if some_condition_on_e(e): raise InterruptException() with add_soft_handler(SoftException, handler): try: work(...) except InterruptException: pass You could also introduce a function def interruptable(fun, *args, **kwargs): try: return fun(*args, **kwargs) except InterruptException: pass to make the code look a bit cleaner - if it fits your usecase, that is of course. I don't say that SoftExceptions can't have semantics that go beyond this. I just don't see a oh-so-compelling use-case that makes things so much better than they are reachable now, without actually much programming. Diez From roy at panix.com Sun Mar 2 23:05:27 2008 From: roy at panix.com (Roy Smith) Date: Sun, 02 Mar 2008 23:05:27 -0500 Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: In article , Gabriel Genellina wrote: > On 2 mar, 17:21, castiro... at gmail.com wrote: > > > This worked: > > > > import socket > > from time import time > > > > for i in range( 20 ): > > ? ? HOST = '' > > ? ? PORT = 80 #<---- > > ? ? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > ? ? s.bind((HOST, PORT)) > > ? ? print( 'listen' ) > > ? ? s.listen(1) > > ? ? conn, addr = s.accept() > > ? ? print( 'connected', addr ) > > ? ? print( conn.recv( 4096 ) ) #<---- > > ? ? conn.send( bytes('test %f > html>'%time(),'ascii') ) > > ? ? conn.close() #<---- > > ? ? s.close() > > > > ... and connect with a browser: ?http://localhost/if it's internet > > exploder. > > Note that there is no need (nor is desirable) to close and rebind the > listening socket for each connection. I'd say, "nor is desirable", is an understatement. On most systems, an attempt to re-bind to a given port number soon after it was unbound will fail (unless you utter magic ioctl incantations). This will manifest itself in the s.bind() call raising an exception on the *second* pass through the loop. From attn.steven.kuo at gmail.com Fri Mar 21 16:10:03 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Fri, 21 Mar 2008 13:10:03 -0700 (PDT) Subject: How can I make a function equal to 0? References: Message-ID: <49ed8746-35f5-4493-89a5-56f0f4ed004b@s12g2000prg.googlegroups.com> On Mar 21, 12:48 pm, Martin Manns wrote: > Hi, > > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > > >>> def f(): return "" > ... > >>> # Some magic > >>> f == 0 > > True > You would have to bind f (the name) to 0 (or False). You can "cheat" and use a decorator: >>> def makezero(f): return 0 >>> @makezero ... def f(): return 1 >>> f == 0 True -- Hope this helps, Steven From castironpi at gmail.com Fri Mar 28 06:18:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:18:45 -0700 (PDT) Subject: Dynamic code problem References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> Message-ID: <70746ecb-05e8-4263-8acc-8bca5bbd3be0@e23g2000prf.googlegroups.com> On Mar 28, 5:14?am, "Simon Brunning" wrote: > On Thu, Mar 27, 2008 at 4:13 PM, ? wrote: > > My dynamic code failed at this sitehttp://playwide1.extra.hu/, need > > ?some help thank you. > > I almost clicked on that *plonk*. Plonk? Plonk who? Knock, knock. Please don't pet the snake. From half.italian at gmail.com Tue Mar 18 16:58:33 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 18 Mar 2008 13:58:33 -0700 (PDT) Subject: os.path.getsize() on Windows Message-ID: Hi all, I'm seeing some behavior that is confusing me. I often use a simple function to tell if a file is growing...ie being copied into a certain location. (Can't process it until it's complete) My function is not working on windows, and I'm wondering if I am missing something simple, or if I have just never tried this before. Here's what I'm trying to do: def isGrowing(f, timeout): ssize = os.path.getsize(f) time.sleep(timeout) esize =os.path.getsize(f) return esize != ssize On windows, this returns the size of the file as it _will be_, not the size that it currently is. Is this a feature? What is the proper way to get the current size of the file? I noticed win32File.GetFileSize() Does that behave the way I expect? PS. I also tried os.stat()[6] ~Sean From bignose+hates-spam at benfinney.id.au Sun Mar 2 00:53:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 02 Mar 2008 16:53:03 +1100 Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: <87hcfpaczk.fsf@benfinney.id.au> Kay Schluehr writes: > On 1 Mrz., 19:51, Barry Warsaw wrote: > > > Python 2.6 is not only the next advancement in the Python 2 series, it > > is also a transitionary release, helping developers begin to prepare > > their code for Python 3.0. > > Isn't this a silly idea? People have to migrate from 2.5 or lower > releases to Python 2.6 first just to migrate to Python 3.0? What are > the inherent / technical reasons that prevent migration directly from > 2.5 to 3.0? One of the stated goals of the migration is that the '2to3' program will only migrate Python 2.6 code -> Python 3.0 code. So, the smoothest migration path will be: * get your program working with Python 2.6; then * use '2to3' to automatically translate that program to work with Python 3.0; then * stop using Python 2.x for that program, only use Python 3.x. Another reason is that good features from Python 3.0 will likely be backported (if possible) to Python 2.6.x, but not to any earlier version. -- \ "Dad always thought laughter was the best medicine, which I | `\ guess is why several of us died of tuberculosis." -- Jack | _o__) Handey | Ben Finney From cwitts at gmail.com Thu Mar 13 02:43:50 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 23:43:50 -0700 (PDT) Subject: copying all data(tags and values) after a particular XML tag References: <9c8740c5-7dfa-4007-a530-c28d4b31a20d@u10g2000prn.googlegroups.com> Message-ID: <33494a78-a49e-4502-8a86-33b980131b8f@a1g2000hsb.googlegroups.com> On Mar 13, 8:21?am, bije... at gmail.com wrote: > i've an XML file with the following structure.... > >
> > > . > . > . > . > . > > > > what i want to do is copy all data(tags and all) between N and N+k > appearances of . I am a python newbie. How do I do it? > > Thanks. You can take a look at the docs for Beautiful Soup, they might help you. If it's just as simple as you're describing and you could always do something like... test = """ 1 2 """ test = test.replace('','|||').replace('','|||') [i for (j,i) in enumerate(tmp2.split('|')) if j%2] which would yield ['\n 1\n ', '\n 2\n '] which you could then parse as required. From jari.aalto at cante.net Fri Mar 7 16:46:39 2008 From: jari.aalto at cante.net (Jari Aalto) Date: Fri, 07 Mar 2008 23:46:39 +0200 Subject: distutils - Is is possible to install without the .py extensions Message-ID: Given following setup.py stanza: #!/usr/bin/python from distutils.core import setup import glob setup(name='program', description='', keywords='', version='', url='', download_url='', license='', author='', author_email='', long_description=""" """, scripts = ['program,py'], packages = ['''], ) Is there any way to fix the installation (postinstall or something), so that the the result is: /usr/bin/program instead of: /usr/bin/program.py Jari -- Welcome to FOSS revolution: we fix and modify until it shines From deets at nospam.web.de Wed Mar 19 10:42:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 15:42:33 +0100 Subject: changing names of items in a list References: Message-ID: <64cn31F2b3pkfU1@mid.uni-berlin.de> royG wrote: > hi > i am trying to rename extension of files in a directory..as an initial > step i made a method in > > class ConvertFiles: > def __init__(self,infldr,outfldr): > self.infldr=infldr > self.outfldr=outfldr > self.origlist=os.listdir(infldr) > .... > def renamefiles(self,extn): > for x in self.origlist: > x=x+"."+extn > > ... > > later when i print self.origlist i find that the elements of list are > unchanged..even tho a print x inside the renamefiles() shows that > extn is appended to x .. > why does this happen? Because a piece of code like this x = some_list[index] x = something_else() doesn't change the object itself, just rebinds x to a new object. That the old object stored in x happened to be referenced in a list as well - who cares? So either your members of origlist become mutables - then you have to alter them, and then they will be reachable from the list. Like this: class Foo(object): def __init__(self): pass l = [Foo() for _ in xrang(10)] f = l[0] f.bar = "baz" print l[0].bar Or you rebind the list itself, or it's index under work - like this: for i, item in enumerate(l): l[i] = do_something_with_item(item) or new_l = [] for item in l: new_l.append(do_something(item)) l = new_l There are innumerable variations of this scheme. Diez From gandalf at shopzeus.com Thu Mar 20 08:20:11 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 20 Mar 2008 13:20:11 +0100 Subject: eval and unicode Message-ID: <47E2567B.6040308@shopzeus.com> How can I specify encoding for the built-in eval function? Here is the documentation: http://docs.python.org/lib/built-in-funcs.html It tells that the "expression" parameter is a string. But tells nothing about the encoding. Same is true for: execfile, eval and compile. The basic problem: - expressions need to be evaluated by a program - expressions are managed through a web based interface. The browser supports UTF-8, the database also supports UTF-8. The user needs to be able to enter string expressions in different languages, and store them in the database - expressions are for filtering emails, and the emails can contain any character in any encoding I tried to use eval with/without unicode strings and it worked. Example: >>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? ?????? ????????? ???????"' ) True The above test was made on Unbuntu Linux and gnome-terminal. gnome-terminal does support unicode. What would happen under Windows? I'm also confused how it is related to PEP 0263. I always get a warning when I try to enter '"????????? ????????? ???????"' in a source file without "# -*- coding: " specified. Why is it not the same for eval? Why it is not raising an exception (or why the encoding does not need to be specified?) Thanks, Laszlo From mhansen at gmail.com Tue Mar 11 11:57:29 2008 From: mhansen at gmail.com (Mike Hansen) Date: Tue, 11 Mar 2008 08:57:29 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: If one wants to do serious math using Python, the best bet is to use Sage ( http://www.sagemath.org ). Here are some examples: sage: def f(x, bits=53): ....: R = RealField(bits); z = R(x) ....: return cos(R(pi) * factorial(z-1) / z) sage: f(100.00,bits=1000) 0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999992343 sage: a = 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 sage: time ecm.factor(a) CPU times: user 0.00 s, sys: 0.06 s, total: 0.06 s Wall time: 2.63 [3478697, 49998841, 11927295803, 518069464441, 1858900129817, 161610704597143, 157394131396743433859615518992811454816816449] sage: a = ZZ.random_element(10**100); a 1266081670515546883639925088390407903294616094325617831128683357589913968497538978358203322629420841 sage: a.is_prime() False sage: b = a.next_prime(); b 8975665868645752218769838623717890808871334875974244952657480072373614614471639002293590745490978883 sage: b.is_prime() True --Mike From ABH at MCHSI.COM Sun Mar 23 11:57:35 2008 From: ABH at MCHSI.COM (A Hutchison) Date: Sun, 23 Mar 2008 15:57:35 GMT Subject: pydoc Message-ID: Any known reasons why pydoc no longer works? AB From deets at nospam.web.de Wed Mar 26 04:42:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 09:42:06 +0100 Subject: Strange loop behavior In-Reply-To: References: Message-ID: <64ugj9F2ce388U1@mid.uni-berlin.de> Gabriel Rossetti schrieb: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > I also tried writing the while's condition like so : len(d) > 0, but > that doesn't change anything. I tried step-by-step debugging using > PyDev(eclipse plugin) and I noticed this, once the while was read once, > it is never re-read, basically, the looping does happen, but just in > between the two lines in the loop's body/block, it never goes on the > while and thus never verifies the condition and thus loops forever. I > had been using psyco (a sort of JIT for python) and so I uninstalled it > and restarted eclipse and I still get the same thing. This looks like > some bug, but I may be wrong, does anybody understand what's going on here? > > Thanks, > Gabriel > > PS > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. But you used a superfluous repr. Look at this: >>> repr("") "''" >>> repr("") == "" False >>> So - get rid of the useless repr, then things should work. Regarding the behavior in the debugger: that's an artifact of the debugger that it doesn't step into that line, it doesn't change the way the code works. Diez From marek.rocki at wp.pl Sat Mar 29 20:59:50 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 29 Mar 2008 17:59:50 -0700 (PDT) Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: <3ba288b6-3b34-4362-a9c3-5c6bd489a80c@a1g2000hsb.googlegroups.com> I love Paul's response. castiro... at gmail.com napisa?(a): > My crystal ball broke a few days ago due to overuse, but I recall that OpenGL likes to have power-of-two texture sizes. If that doesn't work, please trim down your code as far as possible (so that it still displays the error) and post it. From furkankuru at gmail.com Tue Mar 25 18:01:09 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 00:01:09 +0200 Subject: embedded python pythonpath Message-ID: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> Hello, It is somehow related with c++ and python. I've tried below code (Setting pythonpath environment variable) and then initialize python interpreter but the embedded python interpreter did not get the newly assigned PYTHONPATH. I ve looked at the sys.path in python code (that is run by the embedded interpreter) and it behaved according to older pythonpath. Setting environment variable seemed to be correct. Does py_initialize run in another thread so it starts before setting the environment var? // add custom plib.zip archive to pythonpath if(!::getenv("PYTHONPATH")) { ::putenv( "PYTHONPATH=.;.\\plib.zip"); } else ::putenv("PYTHONPATH=%PYTHONPATH%;.\\plib.zip"); std::cout << "PYTHONPath Set to: " << ::getenv("PYTHONPATH") << std::endl << "And Again: "; system("echo %PYTHONPATH%"); Py_Initialize(); Sorry for asking it twice. Regards, -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sat Mar 8 21:11:24 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 18:11:24 -0800 (PST) Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: <74884d64-9cb6-4924-8183-c82f405a43aa@60g2000hsy.googlegroups.com> On Mar 8, 8:48?pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote: > > I prefer: > > > ceiling(a/b) = -(-a)//b > > Unfortunately it doesn't give the right answer. > > >>> a, b = 101.0, 10.0 > >>> -(-a)//b ?# should be 11.0 > 10.0 > >>> a, b = -101.0, 10.0 > >>> -(-a)//b ?# should be -10.0 > > -11.0 > > Looks like you've confused ceiling() and floor(). Whoops, you're right. No, I didn't confuse ceiling and floor; I misplaced the parentheses. I meant to type: ceiling(a/b) = -(-a//b) Mark From Krishna.00.K at gmail.com Fri Mar 7 12:49:58 2008 From: Krishna.00.K at gmail.com (Krishna) Date: Fri, 7 Mar 2008 09:49:58 -0800 (PST) Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: On Mar 6, 5:04 pm, "Gabriel Genellina" wrote: > En Thu, 06 Mar 2008 22:48:42 -0200, Krishna > escribi?: > > > > >>>> class Test(object): > > ... def __init__(self): > > ... self.a= 2 > > ... def func(self, k = self.a): > > ... print k > > ... > > Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 4, in Test > > NameError: name 'self' is not defined > > > In the 'definition of the class', what would the first argument 'self' > > in the methods evaluate to; when we have an object defined, it is > > bound to the object reference, but what happens while the class > > definition is executed, which I believe happens when the module > > containing the class definition is imported > > Function default arguments are evaluated when the function is defined > (when the class is defined, in this case) so "self" itself has not a > value. Try this instead: > > def func(self, k=None): > if k is None: > k = self.a > print k > > If None is an allowed argument, use a special marker instead: > > _marker=object() > ... > > def func(self, k=_marker): > if k is _marker: > k = self.a > ... > > -- > Gabriel Genellina Thanks for the reply. I am currently using the approach suggested by you. But, I am more interested in knowing about the first argument ('self'), what does it hold to allow the evaluation of the method, take the example you gave, 'self.a' as Rvalue inside the method, how and why is this allowed, when the same 'self.a' is not allowed as the default argument, considering the fact that I have already specified 'self' as first argument, only after whose evaluation, I believe would the next statement (k = self.a, in def func(self, k = self.a) ) gets evaluated Thanks, Krishna From harrelson at gmail.com Sat Mar 22 10:31:33 2008 From: harrelson at gmail.com (harrelson) Date: Sat, 22 Mar 2008 07:31:33 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> Message-ID: <5bd9b02a-958b-452d-9e20-c10e4c29f9e4@i29g2000prf.googlegroups.com> On Mar 21, 3:59 pm, Grant Edwards wrote: > On 2008-03-21, harrelson wrote: > > > I am trying to get the below code to work and can't quite make things > > happen. This is with Python 2.5.1. Dialog is doing something odd... > > I have tinkered with different combinations and I can't get the dialog > > to show properly-- it does show properly directly in the shell. Any > > hints? > > > import subprocess > > command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 > > 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" > > "4 this and that"' > > proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, > > stderr=subprocess.STDOUT) > > #proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) > > stderr_value = proc.communicate()[0] > > print stderr_value > > [It would be helpful if you didn't wrap sample code when you > post it.] Sorry I posted through google groups and it wrapped it for me... > dialog displays the widget on stdout. You've connected stdout > to a pipe, so you're not going to see anything displayed unless > you read data from the stdout pipe and write it to the terminal. Reading this tutorial on subprocess: http://blog.doughellmann.com/2007/07/pymotw-subprocess.html led me to believe this was exactly what I was doing. The screen does actually turn blue for a second but it is as if I only get one keystroke and python is back in control... From aiya.vinay at gmail.com Fri Mar 14 10:53:04 2008 From: aiya.vinay at gmail.com (Vinay Aiya) Date: Fri, 14 Mar 2008 20:23:04 +0530 Subject: how to parse a wiki markup file Message-ID: hello, Anyone can help me how to extract the data from wiki file using python i.e is there any WIKIPARSER package and documentation to from parsing on wiki file . -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 16:38:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 21:38:35 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> Message-ID: <13su4mr48on6p7f@corp.supernews.com> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: >> castiro... at gmail.com schrieb: >> >> > I want to hash values to keys. ?How do the alternatives compare? >> >> http://catb.org/~esr/faqs/smart-questions.html > > ... without extending the whole way to a full relational database? You didn't bother following the link and reading the advice, did you? If you did, you haven't done a good job of following that advice. -- Steven From rodmena.com at gmail.com Tue Mar 11 21:55:32 2008 From: rodmena.com at gmail.com (Farsheed Ashouri) Date: Tue, 11 Mar 2008 18:55:32 -0700 (PDT) Subject: Py2exe and Multi Treading problem. Message-ID: Here is my script #********************************************************************** #********************************************************************** import threading import socket def openSocket(portNum): mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', portNum ) ) mySocket.listen ( 1 ) channel, details = mySocket.accept() msg = channel.recv(4096) class CmdPortThread( threading.Thread ): def run( self ): openSocket(6000) def fakeCommandPort(): CmdPortThread().start() fakeCommandPort() #********************************************************************** #********************************************************************** If works perfect with python 2.5.2. Now I want to convert it to standalone program. but the .exe file fails to run without any error. If I cal CmdPortThread without Trading, It works perfect. What did I miss here? My setup.py is standard without any include or excludes. Should I include something in setup.py? I am not a py2exe newbie but I'll appreciate detailed descriptions. From Lie.1296 at gmail.com Sun Mar 30 08:45:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 05:45:25 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Message-ID: <568e3a17-a7a2-4b0a-baab-80b2409adcc8@s37g2000prg.googlegroups.com> mac_the_sco... at hotmail.com wrote to me: (snip) > OK thanks mate you're the man :) > One more question though :P > If I write a python script in a text editor (I use Programmers > Notepad), how do I write indentations properly? e.g.: > --------------------------------------------------- > temperature = input("How hot is the spam? ") > while temperature < hot_enough: > print "Not hot enough... Cook it a bit more..." > sleep(30) > temperature = input("OK. How hot is it now? ") > print "It's hot enough - You're done!" > > (taken from hetland.org) > --------------------------------------------------- > Is it simply a case of hitting the spacebar until it looks right? Yep, it's just a matter of hitting spacebar until it looks right, but you should also be aware that the Python Interpreter doesn't like it if you mix tabs and spaces, so make sure you only use either one of them. As an additional note, Python's style guideline says you should use 4 spaces (additionally, most Python IDEs automatically convert tabs into 4 spaces for convenience and to avoid mixing tabs and cases). PS: I'll mirror this to comp.lang.python From wizzardx at gmail.com Sun Mar 30 01:24:15 2008 From: wizzardx at gmail.com (David) Date: Sun, 30 Mar 2008 07:24:15 +0200 Subject: Can anyone help me? In-Reply-To: References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: <18c1e6480803292224r6cebeearc35af0892193b3e8@mail.gmail.com> > > What is the collision of spheres? Is it the melding of a sphere of > influence and cosmic sphere? What does it mean to say that such a > collision "doesn't work"? The sphere is the optimal solid for storing > the maximum volume in the minimum area. A sphere can retain the most > heat, with minimum surface area for radiation or conduction, > convection of course being dependent not only on surface area but also > ambient flow of surrounding conducting fluid if such flow is laminar > with respect to Reynold's magic number not to be confused with the > numbers of a magic square, which is a two-dimensional shape is there a > determination of the collision of a sphere's projection onto a plane > with a square on that same plane. I've had it with these MF'in > squares on this MF'in plane! When did the Time Cube guy join this list? From deets at nospam.web.de Mon Mar 10 15:18:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 20:18:43 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> Message-ID: <63lfsoF27od4kU1@mid.uni-berlin.de> > The problem with callbacks is that it works only for a small amount of > callbacks, it'd be too messy to have twenty different callbacks. > And the ultimate problem with callbacks is that we can't determine > from the outside whether the operation should continue or breaks at > the point of the callback without some messy trick. > > We can't always determine whether we want to do this: > def somefunc(argA, argB, callback = DO_NOTHING): > if argA == argB: > callback() > > or this: > def somefunc(argA, argB, callback = DO_NOTHING): > if argA == argB: > callback() > return > > perhaps we could do this: > if argA == argB: > if callback() == True: return > > but that's so much extra codes written and would've been too messy to > write. > > And actually this isn't a rare cases, and in fact is very common. It's > just that most cases that can be more cleanly written in > SoftException, can usually be handled in different ways, using tricks > that range from subtle to messy (like callbacks). I fail to see how your arguments follow. Regarding the number of callbacks: you can as well pass an object that has several methods to call. And the above example can easily be accomplished with "normal" exceptions, like this: def toplelevel(): def callback(a, b): if a == b: raise InterruptException() try: work(callback) except InterruptException: pass def work(callback=callback): a = 10 b = 20 callback(a, b) And even more: the callback-approach can do things like this: a, b = callback(a,b) to change values, which makes it superior to SoftExceptions - unless I missed it's ability to capture context. So far, you haven't shown a very convincing example of what SoftException are and how they can be useful. Diez From lialie at gmail.com Thu Mar 13 02:02:56 2008 From: lialie at gmail.com (lialie) Date: Thu, 13 Mar 2008 14:02:56 +0800 Subject: Dispatch("Excel.Application") failed Message-ID: <47D8C390.8090309@gmail.com> Hi, Maybe it 's quite simple, but I can't fix it. Do I make some mistakes in my env setting? My excel version is 2003. any suggestion? Thanks. Traceback (most recent call last): File "testexcel.py", line 3, in ? excel = Dispatch("Excel.Application") File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c lsctx) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 98, in _ GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 78, in _ GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II D_IDispatch) pywintypes.com_error: (-2147221005, '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', None, None) From http Sat Mar 1 14:36:05 2008 From: http (Paul Rubin) Date: 01 Mar 2008 11:36:05 -0800 Subject: why not bisect options? References: Message-ID: <7xy7928cey.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > The sort() function guarantees that it calls the key function exactly > once for each member of the list. That is a time-space tradeoff though, and it presupposes that it's possible to write a key function. Depending on the objects involved, it could be that it's easier to write a comparison function than a key function. From gslindstrom at gmail.com Thu Mar 20 16:07:09 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 20 Mar 2008 15:07:09 -0500 Subject: Pycon disappointment Message-ID: ,,,... Let's see some code! Let's see > stuff working (and sometimes crashing!), and how changes affect the > results. When I've presented at PyCon and other conferences, that's > the part that I spend the most time on: preparing demonstrations. It's > not easy to do; certainly much more difficult than creating a slide > that sums up what the demo does. But it makes for a much more > interesting session! > > -- Ed Leafe Here, here!! (or is it hear, hear??). I remember Ed's talk on Dabo a couple of years ago (or was it last year?) because he was writing code while up in front of the room. "Here's how to do this" and then he would tweak various aspects and show the results. I can appreciate the need for slides, but I also like seeing "code in action". --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Sun Mar 16 07:28:30 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 16 Mar 2008 04:28:30 -0700 (PDT) Subject: ANN: OpenOpt 0.17 (free numerical optimization framework) Message-ID: <8b788e55-bca0-4a4d-8274-91aef09f4c0f@s8g2000prg.googlegroups.com> Greetings, We're pleased to announce: OpenOpt 0.17 (release), free (license: BSD) optimization framework for Python language programmers, is available for download. Brief introduction to numerical optimization problems and related software: http://scipy.org/scipy/scikits/wiki/OOIntroduction Changes since previous release (December 15): * new classes: GLP (global problem), MMP (mini-max problem) * several new solvers written: goldenSection, nsmm * some more solvers connected: scipy_slsqp, bvls, galileo * possibility to change default solver parameters * user-defined callback functions * changes in auto derivatives check * "noise" parameter for noisy functions * some changes to NLP/NSP solver ralg * some changes in graphical output: initial estimations xlim, ylim * scaling * some bugfixes Newsline: http://openopt.blogspot.com/ Homepage: http://scipy.org/scipy/scikits/wiki/OpenOpt From gagsl-py2 at yahoo.com.ar Tue Mar 18 19:37:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 20:37:19 -0300 Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: En Tue, 18 Mar 2008 07:09:08 -0300, escribi?: > On Mar 17, 8:16?pm, Gabriel Genellina wrote: >> On 17 mar, 19:43, castiro... at gmail.com wrote: >> >> > Can I allocate a second console window, so I can place certain output >> > to that directly, and leave the original streams alone? ?I tried >> Have you tried using the creationflags argument to subprocess.Popen? >> Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation >> for CreateProcess >> athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx >> (Note that a process can be attached at most to one console) >> > One console per process is fine, but I tried using 'cmd.exe', > 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32) > as separate processes. The sign is the console window splashes up and > vanishes right away. Apparently you have to either redirect stdout AND stdin, or none of them. This worked for me: p = subprocess.Popen('c:\\windows\\system32\\cmd.exe', stdout=subprocess.PIPE, stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE) p.communicate("dir\n") -- Gabriel Genellina From paul.hankin at gmail.com Mon Mar 10 04:32:43 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 10 Mar 2008 01:32:43 -0700 (PDT) Subject: __iter__ yield References: <27d24b75-f1b5-4996-b54a-15ab2ba16593@59g2000hsb.googlegroups.com> Message-ID: <910581f3-6587-4f6a-91ba-0049d583c1d6@y77g2000hsy.googlegroups.com> On Mar 10, 3:12?am, George Sakkis wrote: > On Mar 9, 7:37 pm, Paul Hankin wrote: > > > > > On Mar 9, 8:58 pm, duccio wrote: > > > > Someone knows if it's possible to make this __iter__ function with just > > > one 'yield' intead of two? > > > ... > > > ? ? ?def __iter__(self): > > > ? ? ? ? ?yield self #1 > > > ? ? ? ? ?for n in self.childs: > > > ? ? ? ? ? ? ?for nn in n.__iter__(): > > > ? ? ? ? ? ? ? ? ?yield nn #2 > > > Only one yield and shorter (but not really any simpler): > > > from itertools import chain > > > class Node: > > ? ? ... > > ? ? def __iter__(self): > > ? ? ? ? for x in chain([self], *self.childs): > > ? ? ? ? ? ? yield x > > Actually this doesn't need a yield at all: > > class Node: > ? ? ... > ? ? def __iter__(self): > ? ? ? ? return chain([self], *self.childs) The two have slightly different behaviours: without the yield, iter is called immediately on every node in the tree as the iterators are built. With yield, iterators are built lazily, giving better behaviour. But perhaps it's a defect of chain that it calls iter on all of its arguments straight away -- would it be better if it only built the iterators when they're needed? -- Paul Hankin From http Fri Mar 28 17:51:48 2008 From: http (Paul Rubin) Date: 28 Mar 2008 14:51:48 -0700 Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> Message-ID: <7x4paqy0sr.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > Did everyone take the course on computer architecture? Yow! Does your SPEED QUEEN have CABLE? From sturlamolden at yahoo.no Tue Mar 18 17:22:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 14:22:53 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: On 18 Mar, 10:57, Simon Forman wrote: > def f(L): > '''Return a set of the items that occur more than once in L.''' > L = list(L) > for item in set(L): > L.remove(item) > return set(L) def nonunique(lst): slst = sorted(lst) return list(set([s[0] for s in filter(lambda t : not(t[0]-t[1]), zip(slst[:-1],slst[1:]))])) From timr at probo.com Wed Mar 5 02:51:09 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 05 Mar 2008 07:51:09 GMT Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Message-ID: blaine wrote: > >...I haven't been able to find many resources specifically in >this area, but there are a few package that are vaguely mentioned, >including fcntl and termios. But the web doesn't seem to have a lot >of documentation on fcntl, particularly information thats from the >past 8 years. That's because serial ports, and the means of accessing them, haven't changed significantly in the last 8 years. Or the last 38 years, for that matter. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Mon Mar 10 12:39:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 09:39:59 -0700 (PDT) Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: <942cf9d5-3d26-41d9-ba8a-3e39dc1595c1@d62g2000hsf.googlegroups.com> > > The idea of the if-else is: > > . depending on some condition either do this or do something else, > > . don't do them both. > > constructs, I asked myself whether the application of a different idea > resulted in a consistent, sensible interpretation. They could just as easily have defined the else of a 'for' to mean 'if the loop only completed not an even number of times', giving these different outputs: for a in [1,2,3,4,5]: if a> 3: break else: print( 'bogus' ) for b in [1,2,3,4,5]: if b> 4: break else: print( 'foo' ) Just as easily, yes. Just as well? Just as meaningfully? Just as consistently, usefully, and sensibly? Possibly. The meaning of 'if a loop' could be construed to mean a parity test or a binary test (if it didn't even complete once, i.p. if the sequence was empty). If I tell you to do a loop, and then asked if you did it, what factors in to your answer? The docs say, 'A break statement executed in the first suite terminates the loop without executing the else clause's suite', for both for- and while-. Does for-and and while-and or for-ifso and while-ifso sound more to your liking? From forwardshortleg at gmail.com Wed Mar 5 19:42:10 2008 From: forwardshortleg at gmail.com (forwardshortleg at gmail.com) Date: Wed, 5 Mar 2008 16:42:10 -0800 (PST) Subject: Returning a byte buffer from C extension Message-ID: Hello, I am new to Python programming. So, kindly excuse me if I don't use correct terminology here below. I am trying to write an extension function that returns an array of bytes as shown in the example below: static PyObject* GetByteBuffer(PyObject* self, PyObject* args) { char byteBuffer[100]; // do something to fill byteBuffer with values. return Py_BuildValue("y", byteBuffer); } Is this valid? I get a run time error in Python 2.5 (actually 2.6) and Python 3.0 returns null terminated byte string. My byte buffer may contain one or more zeros and I want is the entire buffer regardless of its contents. How do I do it? Thanks, Eknath P.S: I know that 2.6 & 3.0 are not meant for a newcomers like me. Unfortunately 2.5.2 and older for windows are built using MSCVC 6.0 and they pose problems building extensions. From stef.mientki at gmail.com Fri Mar 28 12:14:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 17:14:19 +0100 Subject: class or inherited list ? In-Reply-To: References: <47ED0BA1.9020103@gmail.com> Message-ID: <47ED195B.4070902@gmail.com> thanks Gabriel, Gabriel Genellina wrote: > En Fri, 28 Mar 2008 12:15:45 -0300, Stef Mientki > escribi?: > > >> Passing all kinds of data between objects, >> I'm looking for an elegant (and simple) way to pack the data. >> Now it looks to me that both the class and the inherited list, >> performs equally well. >> Till now, the most elegant way (in my view) is the list inheritance, >> mainly because you don't need brackets and no quotes. >> What are others opinion about this ? >> >> class super_list(list): >> pass >> >> def kwadraat ( value ) : >> return value * value >> >> x={} >> x['frequency']=33 >> x['functie']=kwadraat >> print x['functie'](2) >> >> y = super_list() >> y.frequency = 33 >> y.functie = kwadraat >> print y.functie(3) >> > > You don't use y as a list at all - you might as well inherit from object. Good point, didn't notice that. > > And in that case you get a generic attribute container - as you said, like > a dict but using attribute syntax (drawback: only valid names can be used > as keys) > Perfect, I don't need invalid names. > But I don't understand the "functie" usage - what's for? Perhaps if it > used y.frequency - in that case a proper method would be better. > In my case the sender of the data determines the function ("functie" is the Dutch word for "function"), assume this concept: Sender: - generates a huge array of data Receiver: - is a plot utility with interactive user interface - the user can select a part of the huge dataset and wants to see the result of "function" on the selected part of the huge dataset So by passing the function-name(s), I prevent that the functions(s) should be performed on all the data. while they will never be used. cheers, Stef Mientki From jeffober at gmail.com Mon Mar 24 14:57:13 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 24 Mar 2008 11:57:13 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> What does the code look like? From duncan.booth at invalid.invalid Mon Mar 17 06:02:23 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 10:02:23 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> Message-ID: cokofreedom at gmail.com wrote: >> >>> a = 1 >> >>> b = 1 >> >>> a is b >> True >> >>> id(a) >> 10901000 >> >>> id(b) >> 10901000 > > Isn't this because integers up to a certain range are held in a single > memory location, thus why they are the same? > Yes, in *some* implementations of Python this is exactly what happens. The exact range, or indeed whether it happens at all, and (if it does happen) whether the range depends on the phase of the moon are all undefined. This, for example, is what I just got for a similar sequence: >>> a = 1 >>> b = 5-4 >>> a is b False >>> id(a) 43L >>> id(b) 44L >>> From antroy at gmail.com Mon Mar 31 17:57:36 2008 From: antroy at gmail.com (Ant) Date: Mon, 31 Mar 2008 14:57:36 -0700 (PDT) Subject: Is this a good time to start learning python? References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: On Mar 31, 5:40 pm, Rui Maciel wrote: ... > So far the decision seems to be a no brainer. Yet, Python 3000 will arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put it > in other words, I fear that I will be wasting my time. Not at all. The lead developers have a plan for migrating older scripts to 3000 automatically (or at least semi-automatically). This can be done because the core syntax and builtin's are remaining largely the same. The sort of thing that is changing in a way that breaks backward compatibility are things such as removing the print statement (e.g. >>> print "Hello world") with a print function (e.g. print("Hello world")) and rearranging the standard library. As Terry said, the major changes are additions and deletions - to expand on this, the deletions are generally likely to be modules that are rarely used or are unmaintained. In any case, the python developers have a very good policy of making the upgrade path to new versions of Python smooth. Generally new features are released into the __future__ module in a release ready for inclusion in the next release. This allows time to play with new features before the "official" release of the feature comes out. Module deletions usually hang around for a few releases as "deprecated" before being permanently removed - again giving time to catch up. I believe that the deprecation speed may come rather abruptly with 3000, however the 2.6 release will contain a PyLint program for identifying changes that will need to be made before migrating to 3k. In addition, the 2.x branch is AFAIK going to be maintained up to (but no further than) a 2.9 release. So there will be plenty of time to adjust! In short, any time invested in learning Python at this stage (except perhaps old-style classes as pointed out above) will be time well spent, as learning Python 3000 will be minor tweaks to what you'll already know. And for what it's worth, I've programmed in Haskell, C, Java (Java's my profession), Javascript and Perl, and dabbled with Ruby, Lisp, Groovy (and probably others), and Python is by far my favorite language, not just for the clean syntax, rapid development, readability 5 years down the line etc, but also for the community, which is very helpful and knowledgeable. BTW. I have to disagree with Andrew's comment: "With Perl, once you get the core syntax down, you don't need to master Perl. Instead you just look up the module/feature you want to use and just use it.". This may be true for knocking up Perl scripts, but for reading *other peoples* code in any language you need to have a good mastery of the core language. In Perl this is a quagmire of strange syntax, special cases, multiple ways to do the same thing and esoterica/magic, whereas Python's design to make whitespace significant and its "One (obvious) way to do things" philosophy makes reading other peoples code much easier. (Of course other peoples code always sucks, but hey ;-) From aboudouvas at panafonet.gr Thu Mar 27 10:02:17 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 07:02:17 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> Message-ID: On 27 ???, 15:56, "Diez B. Roggisch" wrote: > king kikapu wrote: > > On 27 ???, 14:35, Paul Rubin wrote: > >> king kikapu writes: > >> > it seems that Psyco's author will not port it for the upcoming Python > >> > 3000 release :( > > >> I think the idea is it will be part of PyPy and you should use that. > > > I know that his efforts are on PyPy now but i do not know when PyPy is > > going to be stable and if i can use it with my current "development > > stack" (PyQt, Eric4 etc). I mean, i do not know if it will be possible > > to "abandon" CPYthon and use PyPy instead. > > Currently? No way. It's *way* to slow. > > Diez Ok, i know this. The one that i do not know, is if, let'say, in 2 years it will be ready for seriously development, PyPy will aim to "replace" CPython entirely ?? We are talking about an whole new distribution ? As for psyco, are there any alternatives to use now ? From pradiprai at gmail.com Fri Mar 14 09:29:19 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Fri, 14 Mar 2008 18:59:19 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Tue Mar 25 11:49:55 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 25 Mar 2008 08:49:55 -0700 Subject: Time module is not behaving. In-Reply-To: References: Message-ID: <47E91F23.3050100@islandtraining.com> jjlofaro wrote: > Hi > > I'm just getting myself going again on Python and would appreciate any > help. > > My install of Python seems to have some difficulty loading and using > the time module in a script. Strange thing is that if I start another > instance of Python I can type in my program manually/interactively and > it works. > > The version of Python I am using is... > * > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2* > > Installed on a Ubuntu 7.10 workstation. > > Here's my little program.... > > *jeff at office:~/tmp$ more < time.py > > import time > * Right there is the problem. Your program, named time.py, is hiding the Python supplied module. So that import of time is finding and re-importing itself. Rename your script to something that won't shadow a Python library module. Gary Herron > *print time.time()* > > And this is what happens when I run it.... > > *jeff at office:~/tmp$ python time.py > > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > Error in sys.excepthook: > Traceback (most recent call last): > File "/var/lib/python-support/python2.5/apport_python_hook.py", line > 38, in apport_excepthook > from apport.fileutils import likely_packaged > File "/var/lib/python-support/python2.5/apport/__init__.py", line 1, > in > from apport.report import Report > File "/var/lib/python-support/python2.5/apport/report.py", line 14, > in > import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys > File "/usr/lib/python2.5/urllib.py", line 28, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > Original exception was: > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > jeff at office:~/tmp$ * > > Any hints or tips appreciated. > Jeff. From deets at nospam.web.de Sun Mar 9 17:51:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 22:51:04 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> Message-ID: <63j4ebF25g6okU1@mid.uni-berlin.de> > Perhaps similar technique the compiler uses to determine whether a > function is a normal function or a generator function? Positive > forward lookup for any soft exceptions, which would then activate > matching soft exceptions inside the code? The difference between generators and functions is made on the yield-keyword. However, the exception-mechanism isn't governed by the compiler, but at runtime. You can do things like this: eclass = HardException if full_moon() else: SoftException raise eclass() Which means that you don't stand a chance determining soft-exception-usage at compiletime. What would work is most probably to register soft-exception-handlers when encountering them at runtime, thus making raising-code aware of them and execute it only if there are one (or several) present. However, IMHO it's not a worthy extension to the language - for the same reasons Steven gave. It seems only useful for tightly coupled code, not as a general mechanism. And callbacks or maybe even thread-local state are sufficient to deal with that I'd say. Diez From gagsl-py2 at yahoo.com.ar Tue Mar 25 16:54:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 17:54:08 -0300 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> Message-ID: En Tue, 25 Mar 2008 17:17:16 -0300, j vickroy escribi?: > Arnaud Delobelle wrote: >> On Mar 25, 6:13 pm, j vickroy wrote: >>> Hello, >>> >>> Here is some pseudo-code that hopefully illustrates what I want to do: >>> >>> records = list(...) >>> for record in records: >>> new_fcn = define_a function_for(record) >>> instance = my_new_class_instance() >>> setattr(instance, 'myfcn', new_fcn) >>> instance.execute() # instance.execute() calls instance.myfcn(*args) >>> >>> I have looked at some of the functions in the *new* module and >>> new.code(...), new.function(...), and new.instancemethod(...) appear to >>> do what I want, but I do not know how to use new.code() and >>> new.function() -- specifically what its *global* parameter should be. >> >> The best way to understand how new.function and new.code work is to >> look at the Python source. (Objects/funcobject.c and Objects/ >> codeobject.c, actual objects are defined in and Include/funcobject.h >> Include/code.h). >> >> However, to create a function dynamically in Python it is often no >> more trouble than a def statement: > > As per your suggestion, I tried looking at include/code.h and > include/funcobject.h (my MS Windows distribution does not appear to > contain .c files). However, since I'm not a C programmer, I did not > find the .h files all that helpful. It's not really necesary to look at the source - just define the desired function in Python. > What I failed to make clear in my original posting is that the functions > must be created dynamically using information in a *record* as the code > iterates over all *records*. So, I can not pre-define the functions and > then simply select the desired one at run-time. It doesn't matter *how* you define the function. It may use the record argument too. See this silly and contrived example: def define_a function_for(record): if hasattr(record, 'foo'): def function_float(self, arg1, arg2): return arg1*float(record.foo) + arg2 def function_str(self, arg1, arg2): return arg1+arg2+len(record.foo) if isinstance(record.foo, str): return function_str else: return function_float elif hasattr(record, 'bar') and isinstance(record.bar,basestring): def function(self, arg1, arg2): return self.other(record.bar.index(arg1)) - record.bar.index(arg2) return function else: def function(self, *args): return 0 return function Plug this into your "framework" above and it should work. You don't have to use new.* -- Gabriel Genellina From code at pizzashack.org Thu Mar 27 02:21:59 2008 From: code at pizzashack.org (Derek Martin) Date: Thu, 27 Mar 2008 02:21:59 -0400 Subject: Python 2.2.1 and select() In-Reply-To: <20080327021115.GA24827@noah.org> References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> <20080325020356.GF26870@dragontoe.org> <20080326164951.GA6349@noah.org> <20080326235946.GL26870@dragontoe.org> <20080327021115.GA24827@noah.org> Message-ID: <20080327062159.GM26870@dragontoe.org> On Wed, Mar 26, 2008 at 07:11:15PM -0700, Noah Spurrier wrote: > >def set_nonblock(fd): > > flags = fcntl.fcntl(fd, fcntl.F_GETFL) > > fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) > > > >Then in the function, after calling popen: > > set_nonblock(io.fromchild.fileno()) > > set_nonblock(io.childerr.fileno()) > > > >Yay for smart people. > > You should still try Pexpect :-) As I recall there are also gotchas > on the non-blocking trick. Well, you need to remember to read ALL the file descriptors (objects) that select() returns, and if you don't, your program will hang and spin... It might also be the case that if the child is using stdio functions for output, you'll need to set the buffering mode explicitly (which you can theoretically do, see below). Aside from that, there are none, and actually the problem with my program had nothing to do with stdio buffering modes. > Pexpect is 100% pure Python. No extra libs to install. I looked at it, and (what I believe is) the very reason it manages to solve this particular problem is also the reason it won't work for me: it combines STDOUT and STDERR to one I/O stream. The reason I'm bothering with all this is because I need to keep them separate. Interestingly, were it not for that fact, I'm not sure that pexpect wouldn't still suffer from the same problem that plagued my original implementation. I had to drag out W. R. Stevens to remind myself of a few things before I continued with this discussion... Even though it forces the program to use line buffering, read() would still try to read until EOF, and if STDOUT and STDERR were separate files, it seems likely that it would eventually block reading from one file when the child program was sending its output to the other. The only way to prevent that problem, aside from non-blocking I/O, is to do a read(1) (i.e. read one character at a time), which will use silly amounts of CPU time. But mixing stdio and non-stdio functions is kind of funky, and I'm not completely sure what the behavior would be in that case, and couldn't quickly ind anything in Stevens to suggest one way or the other. Also, you could combine the streams yourself without using pexpect by having your subproc use the shell to redirect STDERR to STDOUT, or (if Python has it) using the dup() family of system calls to combine the two in Python [i.e. dup2(1,2)]. As far as I can tell, the whole pseudo terminal thing (though it definitely does have its uses) is a red herring for this particular problem... I also read (some of) the pexpect FAQ, and there are a number of incorrect statements in it, particularly in the section 'Why not just use a pipe (popen())?" - a pipe, if programmed correctly, is perfectly fine for controlling interactive programs, most of the time. You will almost certainly need to use non-blocking I/O, unless your communicating programs are perfectly synchronized, or else you'll have I/O deadlocks. The only time a pipe isn't OK is where the program tries to use terminal services (e.g. writing to /dev/tty), in which case you will need a pseudo-terminal device (as the FAQ correctly points out with regard to entering passwords in SSH). - Any application which contains "#include " does not necessarily make use of the stdio library (which isn't really a separate library at all, it's part of the standard C library). The file stdio.h is just a C header file which contains declarations of the prototypes for stdio-related functions, and various constants. It's often included in source files simply because it's so common to need it, or to make use of some constants defined there. You're only actually using stdio if you use stdio functions in your program, which are: printf, fopen, getc, getchar, putc, scanf, gets, puts, etc. In particular, open(), read() and write() are *not* stdio functions, and do *not* buffer I/O. They're Unix system calls, and the C functions by the same name are simply interfaces to those system calls. There is a kernel I/O buffer associated with all of the streams you will use them on, but this is not a stdio buffer. I have not checked Python's code, but based on its behavior, I assume that its read() function is a wrapper around the Unix read() system call, and as such it is not using stdio at all, and thus the stdio buffers are not relevant (though if the child is using stdio functions, that could be an issue). - The FAQ states: "The STDIO lib will use block buffering when talking to a block file descriptor such as a pipe." This is only true *by default* and indeed you can change the buffering mode of any stdio stream using the setbuf() and setvbuf() stdio functions (though I don't know if Python provides a way to do this, but I assume it does). Since the python program is the one opening the pipe, it controls the buffering mode, and you have only to change it in your program, and the child will honor that. The way it works is because popen() opens the pipe, and then forks a child process, which inherits all of the parent's open files. Changing the properties on the files can be done in the parent, and will be honored in the child, because *it's the same file*. :) - It states: "[when writing to a pipe] In this mode the currently buffered data is flushed when the buffer is full. This causes most interactive programs to deadlock." That's misleading/false. Deadlocks can easily occur in this case, but it's definitely avoidable, and it's not *necessarily* because of buffering, per se. It's because you're trying to read or write to a file descriptor which is not ready to be read from or written to, which can be caused by a few things. STDIO buffers could be the cause, or it could simply be that the parent is reading from one file descriptor, but the child is writing to a different one. Or (perhaps even more likely) it is trying to read from the parent, so both are reading and no one is writing. Non-blocking I/O allows you to recover from all such I/O synchronization problems, though you'll still need (your program) to figure out where you should be reading and/or writing in order to avoid an infinite loop. But non-blocking I/O may not help with interactive programs that make use of the stdio library, unless you also explicitly set the buffering mode. All of the above are explained in much more detail in W. Richard Stevens' "Advanced Programming in the Unix Environment" than I can possibly go into here. See chapter 3 for the stdio stuff, chapter 12 for non-blocking I/O, and chapter 14 for discussions about pipes, popen(), and how buffering modes can be controlled by your program and how that affects the child. Don't get me wrong... pexpect is useful. But some of the problems you're trying to solve with it have other solutions, which in some cases might be more efficiently done in those other ways. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From python-url at phaseit.net Tue Mar 18 13:12:16 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 18 Mar 2008 17:12:16 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Mar 18) Message-ID: QOTW: "Most people don't use Python by accident, and most people don't continue to use Python by accident" - Chris Hagner, during the talk "Why Python Sucks (But Works Great For Us)" at PyCon 2008 "I don't want a macro facility in the language _because_ it would be so cool." - Laura Creighton Comments about PyCon 2008: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2b6cb0e7245347be/ http://opag.ca/pipermail/opag/2008-March/002704.html Immutable types and identity: http://groups.google.com/group/comp.lang.python/browse_thread/thread/194ce303c02fd9e3/ Avoiding a possible deadlock with subprocess when redirecting input and output: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c197df353787c044/ Guido on Py3000: http://www.artima.com/weblogs/viewpost.jsp?thread=227041 "arrays are more efficient than lists" - what does that actually mean? http://groups.google.com/group/comp.lang.python/browse_thread/thread/60b15d2438e9c827/ Iterating over generators may not be obvious: http://groups.google.com/group/comp.lang.python/browse_thread/thread/169bc46505b472fb/ Why isn't a method identical to itself? http://groups.google.com/group/comp.lang.python/browse_thread/thread/e48b60fdf00054ed People worried about sort() dropping its cmp argument: http://groups.google.com/group/comp.lang.python/browse_thread/thread/458d97c522e0723a/ enum-like identifiers: http://groups.google.com/group/comp.lang.python/browse_frm/thread/7012fd617feecd7e/ Experiences with Python and C++ / Java (portability, performance): http://groups.google.com/group/comp.lang.python/browse_frm/thread/bcc6361e7c4f646a/ Cython, Pyrex, ShedSkin, type annotation (and even compiler availability issues!): http://groups.google.com/group/comp.lang.python/browse_thread/thread/58a353757b79a973/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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 enthusiats": 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/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch 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://aspn.activestate.com/ASPN/Cookbook/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 are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python 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 roee88 at gmail.com Mon Mar 31 16:56:31 2008 From: roee88 at gmail.com (roee shlomo) Date: Mon, 31 Mar 2008 23:56:31 +0300 Subject: License of Python In-Reply-To: <9963f10e0803311350v1348e3cbg79e63461d28e6c8d@mail.gmail.com> References: <9963f10e0803311350v1348e3cbg79e63461d28e6c8d@mail.gmail.com> Message-ID: <9963f10e0803311356n3beb9d47h478f3811ffdf0d42@mail.gmail.com> On 30/03/2008, iu2 wrote: > > The problem is that including Python's license in the binary, which as > I understand is a must do I think you only need to include the PSF license if you modify python itself. from http://www.python.org/psf/license/: > There is no GPL-like "copyleft" restriction. Distributing binary-only > versions of Python, modified or not, is allowed. There is no requirement to > release any of your source code. You can also write extension modules for > Python and provide them only in binary form. > You cannot remove the PSF's copyright notice from either the source code > or the resulting binary. > It sounds like you cannot *remove* the copyright notice from files that already include it (like the Python source code and binaries. Not applications written in Python). >From the license itself: > 2. Subject to the terms and conditions of this License Agreement, PSF > hereby grants Licensee a nonexclusive, royalty-free, world-wide > license to reproduce, analyze, test, perform and/or display publicly, > prepare derivative works, distribute, and otherwise use Python 2.4 > alone or in any derivative version, provided, however, that PSF's > License Agreement and PSF's notice of copyright, i.e., "Copyright (c) > 2001, 2002, 2003, 2004 Python Software Foundation; All Rights Reserved" > are retained in Python 2.4 alone or in any derivative version prepared > by Licensee. > Correct me if I'm wrong. Thanks, Roee. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Tue Mar 4 05:38:26 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 4 Mar 2008 02:38:26 -0800 (PST) Subject: Difference between 'function' and 'method' References: Message-ID: On 4 Mar, 09:22, "??" wrote: > > This is a big problem puzzles me for a long time. The core question is: > How to dynamically create methods on a class or an instance? > > Let me state it step by step. > 1. > def gunc(self): > pass > class A(object): > def func(self): > pass > a = A() > a.func # gives "bound method", type is "instancemethod" > A.func # gives "unbound method", type is "instancemethod" > gunc # gives "function", type if "function" > > # ?? Does this line attach a method to instance? ... I don't think so. > a.gunc = gunc No, unfortunately not. You might get the detailed explanation from someone else, but generally, you have to assign functions to classes; these are then exposed as methods via instances of such classes. A.gunc = gunc > I found stardard library 'new' may help. Is that right? Yes, it can help: import new a.gunc = new.instancemethod(gunc, a, A) > 2. > a = A() # instance of old class A > # Do attach a new method to class A... > b = A() # instance of new class A > Does "a" can get the new method automatically? Can "a" get the new method automatically? Apparently, yes: class A: pass a = A() def f(self, x): print x A.f = f a.f(123) # works, printing 123 > Does new method have the *same* concept level with old methods? > Especially, if there > are classes inherit from class A, how does name resolution work on this case? As far as I'm aware, after you've added a method to a class, instances will regard the method like all the previously existing methods, since method lookup is a dynamic operation. I'll not address your other questions in this message since I'm not a heavy user of decorators and don't want to provide a quick answer without fully testing it first. However, it is important to remember that the "magic" occurs for class attributes, not instance attributes. So, for example, it's quite possible that you'd want to assign a function to an instance attribute, but you wouldn't want the instance to suddenly "own" that function... def somefunc(x, y): # Do something with x and y... return x + y a = A() a.somefunc = somefunc # store the function somewhere # Later... adder = a.somefunc # Later still... result = adder(p, q) # wouldn't work if somefunc became a method Python seems to do the most intuitive thing, I think, but it's quite tricky to contemplate all the implications. Paul P.S. I can never really remember all the different situations and outcomes with method assignment, but then it's something I hardly ever do. I'd be interested to know whether my situation is unusual, however. From tmp1 at viltersten.com Sat Mar 8 18:14:03 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 00:14:03 +0100 Subject: SV: SV: Regarding coding style In-Reply-To: <13t6251ep5bou67@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> Message-ID: <63gjv0F270p58U1@mid.individual.net> > If you can't/don't look at the source file, > then comments aren't going to help (except > in the case of something like docstrings in > Python). I strongly disagree. Now, perhaps we're talking about different things, here? Usually, in the header file (C++), there won't be any source code, except for method declarations. A common example: /** Projects an object from 3D to 2D using the method of Alexander The Great. \param 3D structure to be projected \returns 2D projection */ public Proj2D get2Dfrom3D(Proj3D param); The above is, to me, very clear and consistent. Not to mention, easily handled with e.g. Doxygen to create a readable documentation. I don't see how this is dislikeable. Please explain. Perhaps the above IS what you ment by "docstrings"? For Java, one has the JavaDocs, a great tool, provided one will comment each method and variable used. >> Now, i'm getting the signal that it's done > in a different way in Python. > > I'm not sure how you concluded that from this thread. The below, more or less. :) "What I really can't stand are the pointy-haired comment blocks at the beginnings of C/C++ functions that do things like tell you the name and return type of the function and list the names and types of the parameters." Please note that i DO NOT argue against one way or another. I simply expressed surprise since i've been tought otherwise earlier and, maybe, there's a larger picture than what i've seen this far. As stated before, snakeology is a very new area to me. Yet. ;) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From martin at v.loewis.de Fri Mar 21 16:56:43 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 21 Mar 2008 21:56:43 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <47E4210B.1080505@v.loewis.de> > Well at least this is what I think. If I'm not right then please explain > why. I think your confusion comes from the use of the interactive mode. PEP 263 doesn't really apply to the interactive mode, hence the behavior in interactive mode is undefined, and may and will change across Python versions. Ideally, interactive mode should assume the terminal's encoding for source code, but that has not been implemented. Regards, Martin From castironpi at gmail.com Thu Mar 6 17:45:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 14:45:09 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: <7817aa43-0f4d-4ace-9279-8e1fbdf2640d@b1g2000hsg.googlegroups.com> On Mar 6, 3:24?pm, a... at pythoncraft.com (Aahz) wrote: > In article <13sulsu4nbr2... at corp.supernews.com>, > Steven D'Aprano ? wrote: > > > > >I accept my question about classes being singletons is not well-formed, > >not even in my own mind. I guess one way of asking is, for any two class > >objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? > > Even that stricture fails under the presence of metaclasses. ?;-) ?But > answering your real question, I don't remember off-hand the required > sequence, but it is possible to import a class two different ways such > that the classes are not the object. ?This can cause problems with e.g. > pickle. ?Within a single module, given a class defined only once within > that module, the class will be a singleton. > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "All problems in computer science can be solved by another level of ? ? > indirection." ?--Butler Lampson I'd like to question the source of the definition of C.__eq__. Observation: >>> class C: pass ... >>> class D: pass ... >>> C== D False What is different about them? I've created two empty classes, nothing more. From barry at python.org Sat Mar 1 17:29:39 2008 From: barry at python.org (Barry Warsaw) Date: Sat, 1 Mar 2008 17:29:39 -0500 Subject: [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: <47C9D802.2090205@v.loewis.de> References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> <47C9D802.2090205@v.loewis.de> Message-ID: <05D00F06-8B87-4B94-8878-42E1F3F50F90@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mar 1, 2008, at 5:26 PM, Martin v. L?wis wrote: >> As of 4:50 PM EST, the links to Windows installers give 404 File Not >> Found. >> >> I gather that they are still in process, >> and notice that there is no public c.l.p. announcement. > > I just fixed that. The files were there; just the links were wrong. Thanks for fixing these Martin! - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iQCVAwUBR8nY1HEjvBPtnXfVAQJ3YgP/TYr0X5vRqvVDEMgsHxHuiSuYZCIr8y36 ibAh3RAGeLLK7C7NiOyAfxkesf91HCbL1in0TcnD06QZy52O8elBa927JOomP3mc Y6K4Y49JhxonBrmGcmasnc9PFjbhXtGdWLREinuzpB5itLpRv+SevMhxP27Fp8qr df173TV4hpk= =nf32 -----END PGP SIGNATURE----- From nemesis at nowhere.invalid Sat Mar 8 15:02:35 2008 From: nemesis at nowhere.invalid (Nemesis) Date: 08 Mar 2008 20:02:35 GMT Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> Message-ID: <47d2f0da$0$4794$4fafbaef@reader4.news.tin.it> Bryan.Fodness at gmail.com wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). > > I would like to create a file that would have the structure, > > DoseReferenceStructureType = Site > ... > ... You should try with Regular Expressions or if it is something like xml there is for sure a library you can you to parse it ... anyway you can try something simpler like this: elem_dic=dict() for line in open(str(sys.argv[1])): line_splitted=line.split() for item in line_splitted: item_splitted=item.split("=") if len(item_splitted)>1: elem_dic[item_splitted[0]]=item_splitted[1] ... then you have to retrieve from the dict the items you need, for example, with the line you posted you obtain these items splitted: ['SITE'] and elem_dic will contain the last five, with the keys 'tag','vr','vm','len','name' and teh values 300a,0014 etc etc i.e. this: {'vr': '"CS"', 'tag': '"300a,0014"', 'vm': '"1"', 'len': '"4"', 'name': '"DoseReferenceStructureType">SITE'} -- Age is not a particularly interesting subject. Anyone can get old. All you have to do is live long enough. From arnodel at googlemail.com Sat Mar 1 03:07:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 1 Mar 2008 00:07:59 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com><13see4t3s23pn59@corp.supernews.com><9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> Message-ID: <10e9004f-4bba-42e0-9d17-786104019289@h25g2000hsf.googlegroups.com> On Mar 1, 5:49?am, "Terry Reedy" wrote: > "Arnaud Delobelle" wrote in message > > news:ea3aecb0-c946-46be-bcd5-0c7584751e4b at b1g2000hsg.googlegroups.com... > | Perhaps it'll be like when I quit smoking six years ago. ?I didn't > | enjoy it although I knew it was good for me... And now I don't regret > | it even though I still have the occasional craving. > > In following the development of Py3, there have been a few decisions that I > wish had gone otherwise. ?But I agree with more than the majority and am > not going to deprive myself of what I expect to be an improved experience > without giving Py3 a fair trial. I realise that my comment can be easily misunderstood! I wasn't implying that I would be quitting python, rather that I would have to adjust (with some discomfort) to a new division paradigm. I know from experience that I end up as a staunch defender of most of the design decisions in Python, particularly those that I disagreed with at the start! -- Arnaud From bj_666 at gmx.net Thu Mar 20 10:33:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Mar 2008 14:33:26 GMT Subject: backslash in reading bytes References: <560a5033-576f-4876-91cf-08276985b308@s50g2000hsb.googlegroups.com> Message-ID: <64fatmF29ep7qU2@mid.uni-berlin.de> On Thu, 20 Mar 2008 03:24:49 -0700, Dravidan wrote: > I am trying to read some byte data as a string then using a library to > convert them a code: > >>>>reader = csv.DictReader(open('table.txt')) >>>>def eleFind(value): >>>> for row in reader: >>>> if row['byteCode'] == value: >>>> print row['Element'] >>>> return >>>> else: >>>> print "No Match Found:" >>>>eleFind('\x00\x00') > > My table contains: > > \x00\x00,0000 > \x01\x00,0000 > ...... > > The program errors out. How can I fix/overide this backslash issue. What does `errors out` mean? It won't find two zero bytes. What you give at the `eleFind()` call are just *two* characters with a byte value of zero: In [116]: len('\x00\x00') Out[116]: 2 In [117]: print '\x00\x00' In [118]: len('\\x00\\x00') Out[118]: 8 In [119]: print '\\x00\\x00' \x00\x00 The backslash has a special meaning in string literals. If you don't want this meaning, you have to escape it with another backslash. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Mon Mar 10 23:34:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Mar 2008 23:34:56 -0400 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: "Carl Banks" wrote in message news:dfcf19e3-a216-461d-998e-30fbe139a722 at n75g2000hsh.googlegroups.com... | Just to play Devil's advocate, there is one draw drawback to "such | elegance": when there are multiple break statements. Which means | you'd have to duplicate the break-only condition, or refactor somehow | (which may or may not be suitable). Yes, I knowingly glided over the possibility of multiple break statements with common break-only code and no completion-only code (other than artifactual flag setting as in your code below ;-). I presume that that triple condition is even rarer than simpler situations where one of those conditions is false. | There have been a couple occasions where I felt the best solution was | to a temporary varible like so: But I will accept your testimony that the set of such use cases is not empty. | completed = False | while loop_condition: | | if break_condition: | break | | if some_other_break_condition: | break | | else: | completed = False I presume you meant True | if not completed: | | | It felt icky but we're all still here so it couldn't have been that | bad. tjr From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 07:41:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 11:41:17 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> Message-ID: <13usamtfql9a87c@corp.supernews.com> On Sat, 29 Mar 2008 04:08:16 -0700, Paul Rubin wrote: > kwitters at telenet.be writes: >> I don't know if this is the right place to discuss the death of <> in >> Python 3.0, or if there have been any meaningful discussions posted >> before (hard to search google with '<>' keyword), but why would anyone >> prefer the comparison operator != over <>??? > > I doubt anyone cares. [channeling Luke Skywalker sotto voice] I care. > Python probably chose != because it's what C uses. Coming from a background in Pascal, I originally hated the look of != and preferred <> but I've now got used to the look of it. When I design my own language (ha!), I'll use != for "not equal to" and reserve <> for "greater than or less than but not equal to" which is subtly different. (Think about unordered values, where x != y does not imply that x < y or x > y, e.g. IEEE NaNs.) > The scary choice is /= which can be interpreted as an assignment. "Can be"? >>> x = 5.0 >>> x /= 2 >>> x 2.5 Koen, I've read your blog and I'm afraid that your reasoning is specious. You say: [quote] For comparison (not assignment!), they use operators like <, >, <= (smaller or equals), >= (larger or equals), == (double '=' so there is no confusion with assignment). All pretty clear hey? But now comes the catch, there exists an operator !=... but what does it mean? Well, that one is pretty easy, of course ! must be an operator of its own (in non-python languages meaning 'not'), and it resembles the fancy assignment statement, so a != b must mean "assign the value 'not b' to 'a'... right?... Wrong! Somehow this is a comparison operator meaning "not equals"... what??? Yes, that's right, but hey, you learn to live with it eventually. [end quote] Given that <= is a comparison operator, not an assignment, why do you jump to the conclusion that != is an assignment? Why don't you argue that "x <= y" means "assign the value of x Message-ID: On Mar 16, 2:27 pm, MRAB wrote: > On Mar 16, 2:27 am, Benjamin wrote: > > > On Mar 15, 8:12 pm, lampshade wrote:> Hello, > > > > I'm having some problems with os.path.isdir I think it is something > > > simple that I'm overlooking. > > > > #!/usr/bin/python > > > import os > > > > my_path = os.path.expanduser("~/pictures/") > > > print my_path > > > results = os.listdir(my_path) > > > for a_result in results: > > > if os.path.isdir(str(my_path) + str(a_result)): > > > Try if os.path.isdir(os.path.join(my_path, a_result)):> results.remove(a_result) > > > > for x in results: print x > > > > The problem is, that the directories are never removed. Can anyone > > > point out what I'm missing that is causing the bug? Is there a better > > > way of doing this? > > > You should always use os.path.join to join paths. You shouldn't add > > them like normal strings. I suspect you're getting a combination which > > doesn't exist, so it isn't a dir. :) > > You are also removing items from 'results' while iterating over it, > which has an undefined behaviour. It would be better to build a new > list of those that aren't directories. This list comprehension should do the trick pythonically: final_results = [a_result for a_result in results if os.path.isdir(os.path.join(my_path, a_result))] From jvines at arl.army.mil Mon Mar 10 10:42:05 2008 From: jvines at arl.army.mil (John Vines (CISD/HPCD)) Date: Mon, 10 Mar 2008 10:42:05 -0400 Subject: adding Tcl support to an existing install of Python Message-ID: <47D548BD.1070207@arl.army.mil> All, I need to add Tkinter support, build Tcl/Tk, to an existing RHEL5 python 2.5.1 installation. I know this can be done but I can't remember how :) Can someone lend some help in this area? Thanks in advance, John From http Sun Mar 23 00:40:40 2008 From: http (Paul Rubin) Date: 22 Mar 2008 21:40:40 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <7xlk4anjcn.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > I've been learning a fair amount about functional programming > recently, mostly because compile-time C++ turns out to be a pure > functional programming language. Where should I go for a solid > grounding in lambda-calculus? For PL theory in general, try this: http://www.cs.cmu.edu/~rwh/plbook/book.pdf From zubeido at yahoo.com.br Sun Mar 30 10:44:31 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sun, 30 Mar 2008 07:44:31 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> Message-ID: <91055e8b-ce64-49a3-b736-16afe8336c4b@e39g2000hsf.googlegroups.com> Ok regarding Gerhard's comment of the try, except, pass, i came to understand that it's really bad code. And i should have referred that i put that there be cause i was getting: Traceback (most recent call last): File "C:\Python25\Projects\cp.py", line 48, in db = db() File "C:\Python25\Projects\cp.py", line 19, in __init__ self.cursor.execute( "CREATE TABLE database (album,filepath)" ) OperationalError: table database already exists But when i tried to handle the Operational error with : try: self.cursor.execute( "CREATE TABLE database (album,filepath)" ) except OperationalError: pass I would got: NameError: global name 'OperationalError' is not defined I searched the Internet and found that sqlite3.OperationalError was missing. Dumb me. Now even though i've been reading a bit about exceptions in python tutorial i've come to realize that my approach won't give me the results i want. To my understanding the try statement will still execute the statement within it until it produces the error. So even if i caught this OperationalError i wouldn't know what to do with it. What i'm going to study is whether it's possible to evaluate if a table already exists, and if so act accordingly. Duncan Booth wrote: >Are you absolutely certain of that? If you use print to try to debug the >value of an object you should usually use repr > print repr(audio['album']) As Gerhard correctly guessed i'm a newbie and didn't know of the existence repr. I've been reading about it in python documentation but have yet to analyze it more carefully. I guess the parentheses are just some form of maniac stupidity. Will try to be more clean about them. Thanks for all the patience and hope i've been more forthcoming in this post. From castironpi at gmail.com Fri Mar 14 17:52:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 14:52:54 -0700 (PDT) Subject: Network server- / client-side messaging References: Message-ID: On Mar 2, 3:43?pm, castiro... at gmail.com wrote: > ''' > Last time, we left off at: > ''' > > class InterfaceClientSide( ClientSide ): > ? ? ? ? message= MessageDec() > ? ? ? ? incremental= message.incremental() > ? ? ? ? settings= AYT( .5, 3 ) > ? ? ? ? user_act= message.out() > ? ? ? ? def __init__( self, image ): > ? ? ? ? ? ? ? ? self._image= image > ? ? ? ? ? ? ? ? ClientSide.__init__( self ) > ? ? ? ? def on_scale( self, *args ): > ? ? ? ? ? ? ? ? change= self._whatchange( > ? ? ? ? ? ? ? ? ? ? ? ? self.on_scale, *args ) > ? ? ? ? ? ? ? ? self.user_act( change ) > ? ? ? ? def on_rotate( self, *args ): > ? ? ? ? ? ? ? ? change= self._whatchange( > ? ? ? ? ? ? ? ? ? ? ? ? self.on_rotate, *args ) > ? ? ? ? ? ? ? ? self.user_act( change ) > ? ? ? ? @incremental( 1 ) > ? ? ? ? def layout_return( self, layoutchange ): > ? ? ? ? ? ? ? ? renderchange( layoutchange ) > ? ? ? ? @incremental( 2 ) > ? ? ? ? def layout_return( self, layoutchange ): > ? ? ? ? ? ? ? ? renderchange( layoutchange ) > ? ? ? ? @message > ? ? ? ? def time_estimate( self, etc ): > ? ? ? ? ? ? ? ? report( etc ) > > class InterfaceServerSide( ServerSide ): > ? ? ? ? message= MessageDec() > ? ? ? ? incremental= message.incremental() > ? ? ? ? settings= AYT( .5, 3 ) > ? ? ? ? time_estimate= message.out() > ? ? ? ? layout_return= incremental() > ? ? ? ? def __init__( self, image ): > ? ? ? ? ? ? ? ? self._image= image > ? ? ? ? ? ? ? ? ServerSide.__init__( self ) > ? ? ? ? @message.intervene() > ? ? ? ? def user_act( self, change ): > ? ? ? ? ? ? ? ? etc= self.calculateeta( change ) > ? ? ? ? ? ? ? ? self.time_estimate( etc ) > ? ? ? ? ? ? ? ? preliminary= self.calculation() > ? ? ? ? ? ? ? ? preliminary_change= whatchange( preliminary ) > ? ? ? ? ? ? ? ? self.layout_return( preliminary_change ) > ? ? ? ? ? ? ? ? completed= self.other_calculation() > ? ? ? ? ? ? ? ? completed_change= whatchange( completed ) > ? ? ? ? ? ? ? ? self.layout_return( completed_change ) > ? ? ? ? ? ? ? ? self.layout_return.finish() > > ''' > Another use ClientSide and ServerSide should support is a peer-to-peer > chat-and-game server. ?And that said, it's not clear that there's any > distinction between ServerSide and ClientSide anyway, depending on > exactly how the listen and connect methods abstract. ?How much of the > implementation do they share? ?Most. > > You could mark 'time_estimate' as incremental( 3 ); they're separated > for illustration purposes. > > One remaining question is how to intervene in user_act, if a second > change arrives before the previous complete. ?You could combine the > earlier change parameter in the new call and throw an exception in the > thread handling the earlier one at its first loss of control--- and > maybe even at once with settrace! ?That tends to be costly. ?Not to > mention, change has already entered derived-class space. ?ServerSide > should make sure it's easy enough to address the issue on one's own, > and @message.nonintervene() is available too. > ''' The issues over here this week were delta vs. state-- if there is a unifiable way to specify constraints on which is cheaper given what, and transmit it, -- and, partial inheritance of not just methods, data: overriding 'message' and wanting -its- derivatives-- user_act, time_estimate-- to know it, without redefining. Obvious solutions can be redundant. self.message.layout_return is; get 'layout_return' into the class definition. It's immediately easy to receive the 'ServerSide' instance as a parameter-- less so to get both it and the 'message' instance. If we can, MessageDec can include data, but is still constrained by overriding 'message'. Conclusion? Might as well include some data in MessageDec. How well does message= MessageDec( ServerSide.send ) settle? From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 17:07:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 22:07:21 -0000 Subject: Using re module better References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> <1f63d5df-70e8-4eb9-81f7-7f2abb6f98b1@u10g2000prn.googlegroups.com> Message-ID: <13su6cpjl61mee7@corp.supernews.com> On Wed, 05 Mar 2008 11:09:28 -0800, castironpi wrote: > On another note, why do people X, Y, and Z, including me, all hate to > write a= b(); if a: a.something()? Is this a guessing game? You want us to guess why YOU hate to do something? Okay, I'm game for guessing games... You were traumatized as a child by a newline byte, and now you try to write everything possible as a one-liner. Am I close? Speaking for myself, I *prefer* to separate the assignment from the comparison. I dislike greatly the syntax "if (a=b()): a.something()". -- Steven From sturlamolden at yahoo.no Sat Mar 15 17:45:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 14:45:43 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: On 15 Mar, 22:43, Guido van Brakel wrote: > > def gem(a): > > g = sum(a) / len(a) > > return g > It now gives a int, but i would like to see floats. How can integrate > that into the function? You get an int because you are doing integer division. Cast one int to float. def gem(a): g = sum(a) / float(len(a)) return g From gandalf at shopzeus.com Wed Mar 19 06:24:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 19 Mar 2008 11:24:45 +0100 Subject: Decode email subjects into unicode In-Reply-To: <6gl1u3d3vei5tff9t6ivuhl7gf2qfg6p0k@4ax.com> References: <47DF8EED.1010501@shopzeus.com> <6gl1u3d3vei5tff9t6ivuhl7gf2qfg6p0k@4ax.com> Message-ID: <47E0E9ED.7050902@shopzeus.com> Gertjan Klein wrote: > Laszlo Nagy wrote: > > >> However, there are malformed emails and I have to put them into the >> database. What should I do with this: >> > [...] > >> There is no encoding given in the subject but it contains 0x92. When I >> try to insert this into the database, I get: >> > > This is indeed malformed email. The content type in the header specifies > iso-8859-1, but this looks like Windows code page 1252, where character > \x92 is a single right quote character (unicode \x2019). > > As the majority of the mail clients out there are Windows-based, and as > far as I can tell many of them get the encoding wrong, I'd simply try to > decode as CP1252 on error, especially if the content-type claims > iso-8859-1. Many Windows mail clients consider iso-8859-1 equivalent to > 1252 (it's not; the former doesn't use code points in the range \x8n and > \x9n, the latter does.) > > Thank you very much! From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 10:23:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 14:23:25 -0000 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> Message-ID: <13t7smt4rn8rn32@corp.supernews.com> On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > Okay, so I think I know where's the catch now -- you must rely on the > fact that the protocol is implemented, there's no way to enforce it if > you're expecting a parrot-like object. You'd try to call the speak() > method and deal with the error if there's no such method? That's right. That's called "duck typing" -- if all you want is something that quacks like a duck, then it doesn't matter if it actually is a duck or not. Or if you prefer: if it quacks like a duck and swims like a duck, then it's close enough to a duck as to make no difference. Sometimes though, you need to check for a parrot up front. So I'd so this: try: something.speak except AttributeError: # No speak() method, so it can't be a parrot. do_something_else() else: # It seems to follow the parrot protocol. yummy_goodness = something.speak(5) assert "spam" in yummy_goodness.lower() -- Steven From jeff at schwabcenter.com Tue Mar 4 23:04:36 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 04 Mar 2008 20:04:36 -0800 Subject: SV: Polymorphism using constructors In-Reply-To: References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: Tommy Grav wrote: > > On Mar 4, 2008, at 4:53 PM, Jeff Schwab wrote: > >> What does "SV" in the subject mean? > > SV = "Svar" is the Norwegian word for Reply. Thanks. Serves me right for not speaking Norwegian. From crashbangboom at gmail.com Sat Mar 8 12:48:22 2008 From: crashbangboom at gmail.com (crashbangboom at gmail.com) Date: Sat, 8 Mar 2008 09:48:22 -0800 (PST) Subject: Help xxx.py Program Recognition problem Message-ID: <224ea046-65c4-40b5-8bd5-ede1c87c801e@e6g2000prf.googlegroups.com> Hi... I was using Python 2.4 and installed 2.5...I copied all my .py files from the Python24\ root directory to the Python25\ root directory...when I try to run them by double clicking I get: "XXXXX.py is not a valid Win32 application"... Also, the files do not appear to be associated with python...? I can run them from IDLE...but that is it... How do I fix this...? Thanks.. Dave From yuxi at ece.gatech.edu Thu Mar 13 18:00:08 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Thu, 13 Mar 2008 18:00:08 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > Since you seem to know quite a bit about this topic, what is your > opinion on the apparently 'generic' algorithm described here: > http://grail.cs.washington.edu/projects/query/ ? > So far it seems to me that it does what I'm asking for, it does even > more because it can take a hand drawn sample image and query the > database for similar photos. > > There is even a python implementation for it here: > http://members.tripod.com/~edcjones/pycode.html > > On the histogram method I agree that it won't work partly because of > what you say and partly because it is terribly slow since it's > comparing every single pixel. I'm hardly the expert and can't answer authoritatively, but here's my 2c. I can't comment as to the actual accuracy of the algorithm, since it will depend on your specific data set (set of photos). The algorithm is sensitive to spatial and luminance information (because of the YIQ colorspace), so there are simple ways in which it will fail. The histogram method uses only color, but has a lot of numbers to compare. You may find the histogram method insensitive to spatial relations (a landscape with the mountain on the left and one with the mountain on the right) compared to the wavelet approach. This is a relatively old paper, and I've seen other more recent image retrieval research using wavelets (some cases using only the high-frequency wavelets for "texture" information instead of the low-frequency ones used by this paper for "shape") and other information retrieval-related research using lossy compressed data as the features. If you have time, you may want to look at other research that cite this particular paper. And just a thought: Instead of merely cutting off at m largest-wavelets, why not apply a quantization matrix to all the values? Let me know how it works out. From gandalf at shopzeus.com Fri Mar 28 12:28:02 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 28 Mar 2008 17:28:02 +0100 Subject: How do I reconnect a disconnected socket? In-Reply-To: <13uq69e8us4oo74@corp.supernews.com> References: <13uq69e8us4oo74@corp.supernews.com> Message-ID: <47ED1C92.10508@shopzeus.com> > Yes, that is exactly what it means. > > >From the recv() man page: > > RETURN VALUE > These calls return the number of bytes received, or -1 if an error > occurred. The return value will be 0 when the peer has performed an > orderly shutdown. > > Mea cupla. :-) What about non-blocking sockets? From nagle at animats.com Mon Mar 31 12:27:22 2008 From: nagle at animats.com (John Nagle) Date: Mon, 31 Mar 2008 09:27:22 -0700 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <8763v4otts.fsf@mulj.homelinux.net> References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <656vhnF2e9ao7U1@mid.uni-berlin.de> <8763v4otts.fsf@mulj.homelinux.net> Message-ID: <47f10e70$0$36392$742ec2ed@news.sonic.net> Hrvoje Niksic wrote: > Unfortunately, this is not the case for files at all, even on Unix. > (On Windows, select doesn't work on files at all, it only accepts > sockets.) "select" doesn't work on Windows pipes, either. I had to go to a multithreaded program to work around that. John Nagle From sales057 at aaa-replica-watch.com Mon Mar 17 23:59:53 2008 From: sales057 at aaa-replica-watch.com (sales057 at aaa-replica-watch.com) Date: Mon, 17 Mar 2008 20:59:53 -0700 (PDT) Subject: Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Replica Message-ID: <5cefbe3e-165a-44a2-8f5a-8a818f9ea287@s37g2000prg.googlegroups.com> Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Replica, Fake, Cheap, AAA Replica watch Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Link : http://www.aaa-replica-watch.com/Ebel_1215525.html Buy the cheapest Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 in toppest Replica . www.aaa-replica-watch.com helps you to save money! Ebel-1215525 , Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 , Replia , Cheap , Fake , imitation , Ebel Watches Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Information : Brand : Ebel Watches (http://www.aaa-replica-watch.com/ Replica_Ebel.html ) Gender : Ladies Model : Ebel-1215525 Case Material : 18kt Yellow Gold And Stainless Steel Case Diameter : 1215525, Ebel-1215525, 1200L21-6360, 1200L21/6360, 1200L21.6360, 1200L216360 Dial Color : Silver Guilloche Bezel : 18kt Yellow Gold Movement : Automatic Clasp : 18kt Yellow Gold And Stainless Steel Water Resistant : 100m/330ft Crystal : Scratch Resistant Sapphire Our Price : $ 220.00 18kt yellow gold and stainless steel case and bracelet. Silver sunburst guilloche dial. Date displays at 3 o'clock position. Hidden folding clasp. Anti-reflective scratch resistant sapphire crystal. Case diameter 27mm. Automatic movement. Water resistant at 100 meters (330 feet). Alternate model number 1200L21/6360. Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Replica, With the mix of finest craftsmanship and contemporary styling, not only does it reflect the time but also care you put into looking good. choose one to promote your quality and make yourself impressive among people Thank you for choosing www.aaa-replica-watch.com as your reliable dealer of quality waches including Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 . we guarantee every watch you receive will be exact watch you ordered. Each watch sold enjoy one year Warranty for free repair. Every order from aaa-replica-watches is shipped via EMS, the customer is responsible for the shipping fee on the first order, but since the second watch you buy from our site, the shipping cost is free. Please note that If the total amount of payment is over $600(USD), the customer is required to contact our customer service before sending the money in case failed payment. If you have any other questions please check our other pages or feel free to email us by service at aaa-replica-watch.com. The Same Ebel Watches Series : Ebel 1911 Mens Watch 91331240/14665P : http://www.aaa-replica.com/Ebel_91331240_14665P.html Ebel 1911 Womens Watch 1090211-19865P : http://www.aaa-replica.com/Ebel_1090211_19865P.html Ebel 1911 Mens Watch 1080241-13665P : http://www.aaa-replica.com/Ebel_1080241_13665P.html Ebel 1911 Womens Watch 9090214-19865P : http://www.aaa-replica.com/Ebel_9090214_19865P.html Ebel 1911 Womens Watch 1087221-15865P : http://www.aaa-replica.com/Ebel_1087221_15865P.html Ebel 1911 Womens Watch 1087221-19865P : http://www.aaa-replica.com/Ebel_1087221_19865P.html Ebel 1911 Mens Watch 9331240-13665P : http://www.aaa-replica.com/Ebel_9331240_13665P.html Ebel 1911 Mens Watch 9125241-10665P : http://www.aaa-replica.com/Ebel_9125241_10665P.html Ebel 1911 Mens Watch 9330240-15665P : http://www.aaa-replica.com/Ebel_9330240_15665P.html Ebel Classic Mini Stainless Steel Ladies Watch 9003F11.9925 : http://www.aaa-replica.com/ebel_classic_mini_watch_9003F11_9925.html Ebel Classic Stainless Steel Mens Watch 9120F51.6235134 : http://www.aaa-replica.com/ebel_classic_stainless_9120F516235134.html Ebel Classic Stainless Steel Mens Watch 9120F51/5235136 : http://www.aaa-replica.com/ebel_classic_stainless_9120F515235136.html From kaushikbarat at gmail.com Sun Mar 2 17:24:11 2008 From: kaushikbarat at gmail.com (Kaushik Barat) Date: Sun, 2 Mar 2008 14:24:11 -0800 Subject: mod_python Unable to create file In-Reply-To: <85F61543-7ACD-4D9A-97A2-DB65D3B70B27@ardishealth.com> References: <62v31gF24ontgU1@mid.uni-berlin.de> <85F61543-7ACD-4D9A-97A2-DB65D3B70B27@ardishealth.com> Message-ID: Hey thanks a lot Sean.Setting the permissions on the directory path solved the problem. On Sun, Mar 2, 2008 at 11:09 AM, Sean Allen wrote: > > On Mar 2, 2008, at 3:24 AM, kaush wrote: > > > On Mar 1, 11:24 pm, Marc 'BlackJack' Rintsch wrote: > >> On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: > >>> I am using Apache and mod_python to service POST/GET requests on MAC > >>> OS. My script tries to create a file > >> > >>> file = open(file_path, 'w') > >> > >>> This fails with the following error > >> > >>> EACCES > >>> Permission denied > >> > >>> What is missing? > >> > >> To state the ovious: the rights to create a file at `file_path`. > >> Remember > >> that web servers usually have their own "user". > >> > >> Ciao, > >> Marc 'BlackJack' Rintsch > > > > Thanks Marc. > > In Apache what are the ways/directives to set the rights to a folder? > > none. you set permissions via the operating system. > > chmod would be the command from terminal you are looking for. > > or you can do get info on the folder in question via the finder and > set perms there. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 28 05:00:54 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 28 Mar 2008 10:00:54 +0100 Subject: Getting back an Object In-Reply-To: References: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> Message-ID: <47ecb3b3$0$10375$426a74cc@news.free.fr> Gary Herron a ?crit : (snip) > One other word of warning. It is best to not use a variable named > "string" as Python has a builtin type of that name which would become > inaccessible if you redefine. Good advice, except that the builtin string type is actually named 'str', not 'string' !-) From z80vsvic20 at hotmail.com Sat Mar 15 16:09:18 2008 From: z80vsvic20 at hotmail.com (Eric von Horst) Date: Sat, 15 Mar 2008 13:09:18 -0700 (PDT) Subject: Python and 3D Message-ID: Hi, I am looking for Python modules that allow you to manipulate 3D objects, more specifically Alias Wavefront .OBJ objects. Also, a module that would allow you to vizualize these models and rotate them etc.. The goal is not to build a new renderer or something; just a small program that I need to do some manipulations in bulk on a set of OBJs Any help much appreciated Eric From grante at visi.com Mon Mar 3 17:10:19 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Mar 2008 22:10:19 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> Message-ID: <13sotqbl5kqrsa9@corp.supernews.com> On 2008-03-03, blaine wrote: > I do have a question though. In the termios module, I am attempting > to set the baud rate to 921600, which is what we use with > 'cutecom' (because minicom does not have this as an option) and is > what the supplier recommends. When I try to set the rate using > termios.tcsetattr(), I get an Argument Error. What values are you using for ispeed and ospeed? Those values are special (and rather arbitrary) constant bit-patterns and not simply integers like 9600 or 115200. > I do not get this when I use an existing baud rate, such as > termios.B9600. Is there a way I can get around this? We would > like to use it at full speed. It looks like the fastest speed supported by python termios on Linux is B460800 (uses a constant of 0x1004). If you look in /usr/include/..., baud rates do go up to 921600 (which uses a constant of 0x1007). Try using the appropriate constant from /usr/include/... (for the target platform, of course). -- Grant Edwards grante Yow! Please come home with at me ... I have Tylenol!! visi.com From pboppudi at vmware.com Thu Mar 27 14:24:05 2008 From: pboppudi at vmware.com (Praveena Boppudi (c)) Date: Thu, 27 Mar 2008 11:24:05 -0700 Subject: How to take snap shot of the of project screen in Python In-Reply-To: References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: Hi, Can anyone help me out? Thanks, Praveena. From Robert.Bossy at jouy.inra.fr Thu Mar 13 11:50:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 13 Mar 2008 16:50:57 +0100 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> Message-ID: <47D94D61.9010708@jouy.inra.fr> Robert Rawlins wrote: > > Hello Guys, > > I?ve got an awfully aggravating problem which is causing some > substantial hair loss this afternoon J I want to get your ideas on > this. I am trying to invoke a particular method in one of my classes, > and I?m getting a runtime error which is telling me the attribute does > not exist. > > I?m calling the method from within __init__ yet it still seems to > think it doesn?t exist. > > Code: > > # Define the RemoteDevice class. > > class *remote_device*: > > # I'm the class constructor method. > > def *__init__*(/self/, message_list=/""/): > > /self/.set_pending_list(message_list) > > def *set_pending_list*(/self/, pending_list): > > # Set the message list property. > > /self/.pending_list = message_list > > And the error message which I receive during the instantiation of the > class: > > File: ?/path/to/my/files/remote_device.py", line 22, in __init__ > > self.set_pending_list(message_list) > > AttributeError: remote_device instance has no attribute 'set_pending_list' > > Does anyone have the slightest idea why this might be happening? I can > see that the code DOES have that method in it, I also know that I > don?t get any compile time errors so that should be fine. I know it > mentions line 22 in the error, but I?ve chopped out a load of non > relevant code for the sake of posting here. > Hi, I don't get this error if I run your code. Maybe the irrelevant code causes the error: my guess is that there's a parenthesis mismatch or an undeindented line. Btw, calls to set_pending_list will fail since the name "message_list" is not defined in its scope. Please follow Chris Mellon's advice. Cheers, RB From sjmachin at lexicon.net Sun Mar 23 17:56:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 14:56:37 -0700 (PDT) Subject: Problems with joining Unicode strings References: <5b623e11-054d-44b7-bc65-d75922728dce@b1g2000hsg.googlegroups.com> Message-ID: <0f1d12c2-ac36-4b0e-9eed-6d59028710eb@d4g2000prg.googlegroups.com> On Mar 24, 7:58 am, Ulysse wrote: > Hello, > > I have problems with joining strings. > > My program get web page fragments, then joins them into one single web > page. I have error when I try to join these fregments : > "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position > 208: ordinal not in range(128)" > > Here is my code : [snip] Contrary to your message subject, you are *not* joining "Unicode strings". Your resume_news contains at least one str (8-bit string) objects [probably all of them are str!]. You need to decode each str object into a unicode object, using whatever encoding is appropriate to that str object. When you do u''.join(sequence_including_str_objects), Python attempts to decode each str object using the default 'ascii' encoding ... this of course fails if there is a non-ASCII character in the str object. This may help: www.amk.ca/python/howto/unicode Cheers, John From From at home Fri Mar 21 18:16:41 2008 From: From at home (From at home) Date: Fri, 21 Mar 2008 17:16:41 -0500 Subject: List question Message-ID: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Hello, I am learning python and dont quuite understand why is this happening could someone explain? alist = [] blist = [ 'one','two','one and two','one and four','five','one two'] for f in blist: if 'one' and 'two' in f: alist.append(f) for i in alist: print i two one and two one two why is it printing the first "two"? tia From mnordhoff at mattnordhoff.com Mon Mar 3 19:14:22 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 04 Mar 2008 00:14:22 +0000 Subject: os.system with cgi In-Reply-To: <4a7f84ac0803031556p721d9a74h2cd7051bf6bc5b7e@mail.gmail.com> References: <4a7f84ac0803031556p721d9a74h2cd7051bf6bc5b7e@mail.gmail.com> Message-ID: <47CC945E.10303@mattnordhoff.com> G wrote: > Hi, > > I have the following peace of code > > def getBook(textid, path): > url = geturl(textid) > if os.path.isfile(path + textid): > f = open(path + textid) > else: > os.system('wget -c ' + url + ' -O ' path + textid) > f = open(path + textid) > return f > > The reason I am not using urllib is that I want to have random access > within the downloaded file. > > When i execute the file from a regular python script I get the file > downloaded and a handle for the file returned. > When I execute the file from a python cgi script i get an error saying > that the file doesn't exist. In other words the call to os.system is not > running. > Could someone please point out what the problem with that peace of code > running as a cgi script. > > Best. Ew. You could at least use subprocess and not be vulnerable to someone passing "; rm -rf ~; echo" or something as the path. If you need random access like that, and urllib2 can't do it, you could use urllib2 and a StringIO or temporary file or something. Using wget makes it much harder to handle errors. Heck, you could just read the file into a string and use slicing, if it's not too large... -- From simon at brunningonline.net Wed Mar 26 09:45:33 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Mar 2008 13:45:33 +0000 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <13ubn5ue821ak7e@corp.supernews.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> <13ubn5ue821ak7e@corp.supernews.com> Message-ID: <8c7f10c60803260645n309badfcg164308999b5bda9d@mail.gmail.com> On Sun, Mar 23, 2008 at 4:29 AM, Steven D'Aprano wrote: > Python is a programming language. It can be used for scripting, but > that's not all it can do. Describing it as a "scripting language" is like > describing a fully-equipped professional kitchen as "a left-over warming > room". +1 QOTW. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From arnodel at googlemail.com Tue Mar 18 17:43:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 14:43:01 -0700 (PDT) Subject: keyboard "interrupt" References: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Message-ID: John Fisher wrote: > Hi Group, Hi John > I have been absent a while, mainly because I have been getting better at > figuring out my own Python problems. But not this one... > > I have a timed loop performing certain tasks until a total period of > time has elapsed. I would like to be able to interrupt the loop or set > various flags during execution via keyboard input. raw_input seems to > just stop everything cold. I want the ability to just sacn the keyboard > buffer and see if something is there, then proceed normally in the loop > if there is no input in the buffer. Make sense? Totally easy? Let me > know... If you are on a UNIX platform, you can use the curses module. http://docs.python.org/lib/module-curses.html There is a link there to a tutorial, but it seems to be broken. A quick search finds it there: http://www.amk.ca/python/howto/curses/ HTH -- Arnaud From pianomaestro at gmail.com Fri Mar 28 11:25:55 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 08:25:55 -0700 (PDT) Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: <17e0f94a-555c-40c7-8dd6-90c6d9c0b633@a23g2000hsc.googlegroups.com> On Mar 28, 11:14 am, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 11:51:10 -0300, escribi?: > > > I have an extension module that gets initialized multiple > > times because I am using threads. > > And do you want thread local variables? no > > > How can this module access global state (not per-thread state) ? > > It needs to create a singleton. > > C global variables are global, not per-thread. Yes, but they get initialized once per-thread, therefore my singleton gets created multiple times. Simon. > > -- > Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Mar 17 09:17:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 11:17:46 -0200 Subject: finding euclidean distance,better code? References: Message-ID: En Mon, 17 Mar 2008 03:04:16 -0200, devnew at gmail.com escribi?: > while trying to write a function that processes some numpy arrays and > calculate euclidean distance ,i ended up with this code > (though i used numpy ,i believe my problem has more to do with python > coding style..so am posting it here) > > for image in range(numimgs): > distance = abs(input_wk - weights[image, :]) > if image==0: > #copy from distance to mindistance > mindistance=distance.copy() > if sum(mindistance) > sum(distance): > imgindex=image > mindistance=distance.copy() > if max(mindistance) > 0.0: > #normalise mindistance > mindistance=mindistance/(max(mindistance)+1) > dist=sum(mindistance) > > this gets me the euclidean distance value. It looks like you're rather computing a distance derived from the 1-norm (sum of coordinates; like in a city with square blocks). I'd save the sum(mindistance) value to avoid recomputing it in every iteration. > I want to know if the way i > coded it can be improved,made more compact....if someone can give > suggestions it will be a great help . The code is pretty legible as it is now. Anyway, using min() and a generator: _, imgindex = min((sum(abs(input_wk - weights[image, :])),image) for image in xrange(numimgs)) mindistance = abs(input_wk - weights[imgindex, :]) # normalize and sum again -- Gabriel Genellina From andreas.axelsson at gmail.com Mon Mar 31 11:15:10 2008 From: andreas.axelsson at gmail.com (axl) Date: Mon, 31 Mar 2008 08:15:10 -0700 (PDT) Subject: Build complete, now I just need to "install" it... References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: <145effd2-c733-4f78-b79f-c0feaf660e27@s13g2000prd.googlegroups.com> On 31 Mar, 00:32, "Gabriel Genellina" wrote: > En Sun, 30 Mar 2008 12:04:10 -0300, axl ? > escribi?: > > Which changes are those? I can build Python straight from the svn sources. I upgraded the project files to VS2008 format, changed some obsolete settings, hacked distutils so it wouldn't barf on the Windows SDK 6.1 and added include paths to tcltk to the python.vsprops. I did similar changes to all the external modules, tcl, tk, bzip2, etc. This was on the 2.5.2 tarball b.t.w. I suppose I could grab the svn tip, if things have changed there, but I thought I'd start at an official "release" point. > The MSI package generation is at Tools\msi in the source tree. > There are a few preliminary steps that must be done (only once) before ? > successfully building the installer, you'll notice as you go (the script ? > will tell you what's missing; a .rc file has to be compiled, as far as I ? > remember). Would be nice if you take note of them so one can write down ? > the proper build sequence. Thanks Gabriel, for some reason I just assumed everything PC related was in the PC* folders and the docs I found don't mention the msi folder. I'll have a look there. Cheers, /axl From castironpi at gmail.com Wed Mar 5 17:16:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 14:16:36 -0800 (PST) Subject: What is a class? References: <13su5s530rnkgfe@corp.supernews.com> Message-ID: <774470ba-dc8a-4aea-94fc-3bcf1382d57f@i29g2000prf.googlegroups.com> On Mar 5, 3:58?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 10:50:12 -0800, castironpi wrote: > > What is a class that is not a module? > > Er, all of them? > > I'm curious what classes you think are modules. > > -- > Steven Thank you for your time in entertaining my questions so far. Functions are first-class objects. Modules are first-class objects. Classes are first-class objects. There's even a ModuleType in 'types'. >>> set( dir(type('None',(),{})) )- set( dir( ModuleType ) ) {'__module__', '__weakref__'} How superficial are the differences? From aahz at pythoncraft.com Mon Mar 31 22:35:01 2008 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2008 19:35:01 -0700 Subject: What motivates all unpaid volunteers at Pycon? References: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> Message-ID: In article <7b539c8e-af4c-4409-81bc-d94e687eea59 at i7g2000prf.googlegroups.com>, seberino at spawar.navy.mil wrote: > >I was impressed and humbled by all the unpaid volunteers at Pycon. What about the unpaid volunteers who weren't at PyCon? ;-) >I was wondering what motivated so many people to give so much to the >Python community. There really isn't any simple answer. Most people seem to be motivated to help out their communities, and Python certainly has a substantial community associated with it. However, that motivation plays out in different ways for each person; some people create patches for Python and others volunteer for PyCon. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From dave.brk at gmail.com Thu Mar 27 16:09:45 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 27 Mar 2008 22:09:45 +0200 Subject: Regarding __slots__ and other stuff: A couple of questions In-Reply-To: References: Message-ID: Didn't see your answer, Gabriel. Thanks, now I understand it even better. On 3/27/08, dave berk wrote: > > sorry, forget all I wrote: I should have read this more thoroughly, it > explained it all > > http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.htm > > > Descriptors > only works with type objects, not instance. and you can't write from an > instance object to a > class variable. You can only hide it. Also __slots__ works by creating descriptors in the class and preventing creation of any atrributes in the class instance, so everything is clear now > > Dave > -------------- next part -------------- An HTML attachment was scrubbed... URL: From troworld at gmail.com Wed Mar 5 01:15:29 2008 From: troworld at gmail.com (Tro) Date: Wed, 5 Mar 2008 01:15:29 -0500 Subject: Altering imported modules In-Reply-To: References: Message-ID: <200803050115.30314.troworld@gmail.com> On Tuesday 04 March 2008, Floris Bruynooghe wrote: > On Mar 1, 11:56 pm, Tro wrote: > > I'd like to know if it's possible to make tlslite load *my* asyncore > > module without changing any of the tlslite code. > > the pkgutil module might be helpful, not sure though as I've never > used it myself. > > http://blog.doughellmann.com/2008/02/pymotw-pkgutil.html is a fairly > detailed look at what pkgutil can do. Thanks, that's neat. Tro From bignose+hates-spam at benfinney.id.au Wed Mar 12 02:00:34 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 12 Mar 2008 17:00:34 +1100 Subject: best way to have enum-like identifiers? References: Message-ID: <87k5k84h31.fsf@benfinney.id.au> mh at pixar.com writes: > Currently I'm just putting this at the top of the file: > > py=1 > funcpre=2 > funcpost=3 > ... Slightly better is: py = object() funcpre = object() funcpost = object() Thus, those names are all bound to unique objects, that won't be unexpectedly duplicated by some other value. > but I'm curious if there's a better way of doing this, some kind of > enum-like thing or somesuch. Please try the 'enum' package in the Cheeseshop: -- \ ?When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic.? ?Dresden James | Ben Finney From tmp1 at viltersten.com Sat Mar 1 08:35:38 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 14:35:38 +0100 Subject: SV: SV: Running test01.py under Windows (basic level) In-Reply-To: References: <62os33F2352veU1@mid.individual.net><62pf4dF24hb4hU1@mid.individual.net> Message-ID: <62t3efF24bb0gU1@mid.individual.net> >> There will be poking around with %PATH%, i can >> tell. Never liked to do that under Windows. > > No need to do that... Create an "alias.txt" file containing: > python=c:\path\to\your\python.exe $* > Execute (once, logged as administrator): > reg add "HKLM\SOFTWARE\Microsoft\Command Processor" > /v AutoRun /t REG_SZ /d > "doskey /macrofile=path\to\your\alias.txt" > Open a new cmd console. Typing python is enough to invoke the interpreter. > Documentation for the DOSKEY command: > http://technet2.microsoft.com/WindowsServer/en/library/f7f45601-5178-48c6-9219-51bd6f7abd3f1033.mspx > > If you don't like the above recipe, create a "python.cmd" file containing: > @c:\path\to\your\python.exe %* > and save it somewhere in your PATH. It worked. Thanks! >>> have you worked out the Tutorial? >> >> Not yet. I started off using some small things. >> I tend to learn by doing. Or rather making. A >> lot of errors, that is. :) > > At least overview it. Python syntax is very clear and legible, so probably > you can figure yourself a lot of things, but there are some important > topics that you have to know and are explained in the Tutorial. It isn't > very long. Naa, reading tutorials is for idiots... You can answer my questions instead. It's not like you've got anything better to do. I bet you've read the tutorial, haven't you? (a period of awkward silence...) (a short while of WTF?!) Oh, ah! This guy was joking. Pfew... Yes, i was definitely joking here. :) I do intend to go through the tutorial and i do deeply appreciate all the help i've received/ i'll receive. If all goes the way i hope, i'll be at a new project soon and it's written in Python. Great opportunity to learn it, right? By the way - thanks! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From malkarouri at gmail.com Thu Mar 27 17:38:51 2008 From: malkarouri at gmail.com (malkarouri) Date: Thu, 27 Mar 2008 14:38:51 -0700 (PDT) Subject: SoC project: Python-Haskell bridge - request for feedback References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: On 26 Mar, 08:46, Paul Rubin wrote: > A few thoughts. The envisioned Python-Haskell bridge would have two > directions: 1) calling Haskell code from Python; 2) calling Python > code from Haskell. The proposal spends more space on #1 but I think > #1 is both more difficult and less interesting. FWIW, I find #1 more interesting for me personally. As a monad-challenged person, I find it much easier to develop components using pure functional programming in a language like Haskell and do all my I/O in Python than having it the other way round. Of course, if it is more difficult then I wouldn't expect it from a SoC project, but that's that. Muhammad Alkarouri From tjreedy at udel.edu Thu Mar 20 22:29:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Mar 2008 22:29:05 -0400 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com><64bugqF2anottU1@mid.uni-berlin.de><7xve3j15ya.fsf@ruckus.brouhaha.com><87fxunumqx.fsf@physik.rwth-aachen.de><7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: "Reedick, Andrew" wrote in message news:A20311AF91C11640ACBB721DC2558B4907D2F5A7 at brexc51p... | Quicksort in Haskell versus C is amazing: | http://www.haskell.org/haskellwiki/Introduction#What.27s_good_about_functional_programming.3F Sorry, bogus comparison, and not so amazing. 1.The short doubly recursive definition of qsort has nothing to do with Haskell. 2. The Haskell code refers to an external function 'filter'. The C code inlines the filter code. If that is shoved to an external function, we get this 'amazing' (but untested ;-) C code: void qsort(int a[], int lo, int hi) { int l; if (lo < hi) { ll = partition(a, lo, hi); qsort( a, lo, ll-1 ); qsort( a, ll+1, hi ); } } The is a fair comparision, and it looks nearly as good as the Haskell code. This can also be written as a one-liner if one finds such to be more 'amazing'. The C code does not even need code for the base case. Amazing! 3. The Haskell code makes two scans of the array (one for each filter) instead of just one and makes a copy of the array (minus the pivot) in two pieces. instead of none Whether the 'slice' 'xs' makes a copy or is just a view I don't know. Then it does more allocations and copies to put the separated pieces back together. The C code does the filtering in place. Hence no need to concatenate the sorted pieces. Of course that looks more complex -- because it is -- unless hidden away in the double-filter-in-place partition function. So Haskell trades textual terseness for computation space and, probably, time. Python makes the same trade-off, and I like it and use it for that reason. One can certainly like Haskell for that reason too, but it is a trade-off. What would be amazing would be a algorithm that could rewrite the external-arrays Haskell/Python code to the equivalent of the in-place C code. Can one even write such an equivalent in Haskell? (If it is purely functional, then no, though one obviously can in Python.) For efficiency, standard C qsort code turns the second (tail) recursive call into a loop. A Python version of the same could easily eliminate the first recursive call with an explicit stack. Again, less elegant code for more speed. | Quicksort in Python inspired by Haskell's quicksort: | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473 The list slicing could be done once instead of twice. Terry Jan Reedy From jeff at schwabcenter.com Tue Mar 18 17:25:28 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 14:25:28 -0700 Subject: ftp recursively Message-ID: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> I need to move a directory tree (~9GB) from one machine to another on the same LAN. What's the best (briefest and most portable) way to do this in Python? I see that urllib has some support for getting files by FTP, but that it has some trouble distinguishing files from directories. http://docs.python.org/lib/module-urllib.html "The code handling the FTP protocol cannot differentiate between a file and a directory." I tried it anyway, but got an authentication problem. I don't see a "how to log into the FTP server" section on docs.python.org. Is there a tutorial I should read? I am particularly looking for a quick, "good enough" solution that I can use this afternoon. Thanks in advance to any kind-hearted soul who chooses to help me out. From bj_666 at gmx.net Mon Mar 31 13:46:02 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 17:46:02 GMT Subject: [OT] troll poll References: Message-ID: <65cmaqF2fhuoaU1@mid.uni-berlin.de> On Mon, 31 Mar 2008 10:04:31 -0700, Daniel Fetchinson wrote: > [Heavily off-topic fun stuff] > > This is a quick poll to have scientific data on our beloved troll community: > > Whose trolling behaviour is more professional? (check one) > > [X] - Xah Lee > [ ] - castironpi He dedicates some time to write up at least comprehensible postings that make *some* sense. > More specifically, who can create a bigger mess on c.l.py? (check one) > > [ ] - Xah Lee > [X] - castironpi Xah Lee's postings might be trolls but sometimes they spark some really interesting and serious subthreads, while the nonsense of castironpi is just irritating noise. > More specifically, who is more entertaining? (check one or none) > > [X] - Xah Lee > [ ] - castironpi Castironpibot becomes boring very quickly. Especially when it starts to answer its own posts. Ciao, Marc 'BlackJack' Rintsch From arnodel at googlemail.com Thu Mar 13 16:14:04 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 13:14:04 -0700 (PDT) Subject: Python regex References: Message-ID: <9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c@i29g2000prf.googlegroups.com> On Mar 13, 8:03?pm, "Andrew Rekdal" <@comcast.net> wrote: > I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > > >>CSS comment > > although this works to a degree... I know the within the brackets everything > is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? eg. > where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... negate > > -- Andrew There would be many ways to do this. One: >>> import re >>> r = re.compile(r'/\*(.*?)\*/') >>> tst = '.a { color: 0xAACC66; /* Fav color */ }' >>> m = r.search(tst) >>> m.group(1) ' Fav color ' >>> HTH -- Arnaud From hberig at gmail.com Sun Mar 23 21:33:25 2008 From: hberig at gmail.com (hberig) Date: Sun, 23 Mar 2008 18:33:25 -0700 (PDT) Subject: python + olap Message-ID: Hi, I'm looking for python olap applications or frameworks, integrable to a web server application (like turbo gears or other) or some gui (like qt, wxwidgets or other). Any suggestion?? Thanks in advance!! From hexusnexus at gmail.com Mon Mar 31 21:22:49 2008 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Mon, 31 Mar 2008 18:22:49 -0700 (PDT) Subject: Stuck in a loop Message-ID: I wrote a simple algorithm and it keeps getting stuck in a loop. I guess I'm just to tired to figure it out: compcount=[5,4,2,2] suitrank=[0,0,0,0] trump=2 l,lt=0,0 while l<4: while lt<4: if l==trump: l+=1 if l>3: break if lt==trump: lt+=1 if compcount[l] <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> Message-ID: <1npcu3p9hig3gm94mskfoksk9p43p8h2jm@4ax.com> On Sat, 22 Mar 2008 23:29:10 +0100, Christian Heimes wrote: >Matthias G?tz schrieb: >> So can you tell me what's the purpose of Complex.py, >> >> and where can i find the semantic i'am looking for. > >Well, the file is in the Demo folder. It's just a demo how to implement >a naive complex type in Python. > >Why do you think the power of a complex to a complex is not defined? >Raising a complex to a complex power is well defined, Really? One of the problems that used to show up on the master's exams aroung here was to find all the possible values of i**i. >although the >mathematical proof isn't trivial. You have to use the Euler form. Erm, the problem is that the Euler form of a complex number is not well-defined (_unless_ you specify that the argument is between -pi and pi). For example, i = exp(i pi/2) and also i = exp(i 5*pi/2); those two "forms" give different values for i**i. You might say that a complex power of an Euler form for a complex number is well-defined. If you do specify that -pi < argument <= pi, ie you consider the principal-value logarithm, then you get exactly one z**w. But that's not always the z**w that you need for your problem... >Ask >Google for some examples Thanks. >Christian David C. Ullrich From fetchinson at googlemail.com Mon Mar 10 21:05:12 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 18:05:12 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > Thanks for the info! SIFT really looks like a heavy weight solution, > > but do you think the whole concept can be simplified if all I needed > > was: given a photo, find similar ones? I mean SIFT first detects > > objects on the image and find similarities, but I don't need the > > detection part at all, all I care about is similarity for the whole > > photo. I surely don't understand the big picture fully but just have > > the general feeling that SIFT and other expert tools are an overkill > > for me and a simplified version would be just as good with a much more > > easily comprehensible core algorithm. > > Please describe the kind of photos you are dealing with. Are they > identical photos, in say different formats or with different metadata? > Or are they rescaled images? Or maybe they are the same photo cropped > differently? The photos are just coming straight from my digital camera. Same format (JPEG), varying size (6-10 megapixel) and I would like to be able to pick one and then query the database for similar ones. For example: I pick a photo which is more or less a portrait of someone, the query should return other photos with more or less portraits. If I pick a landscape with lot of green and a mountain the query should result in other nature (mostly green) photos. Something along these lines, of course the matches won't be perfect because I'm looking for a simple algorithm, but something along these lines. > SIFT will work in more or less the process you described in your first > post. It basically calculates the N sets of numbers for each image, > representing the unique features of that image and their relative > positions. The rest of the process if up to you. You have to compare the > different sets of numbers to find the image with the minimal difference, > as opposed to comparing the whole image. Great, this sounds very good, I'll give SIFT a try (at least trying to understand the basic concepts) although at the moment it looks a bit scary :) From alex.borgert at gmail.com Mon Mar 31 04:37:37 2008 From: alex.borgert at gmail.com (Artmi) Date: Mon, 31 Mar 2008 01:37:37 -0700 (PDT) Subject: Beginner advice References: <65bfk7F2esfc1U1@mid.uni-berlin.de> Message-ID: <2ba28546-92cd-4cfe-be5e-15a5a5f01f3a@c19g2000prf.googlegroups.com> On Mar 31, 9:15 am, Paul Scott wrote: > On Mon, 2008-03-31 at 06:45 +0000, Marc 'BlackJack' Rintsch wrote: > > There is an `xmlrpclib` in the standard library, so there is no need for > > an external package here. I even think that pyXMLRPClib is the one that's > > integrated in the standard library, so the external one might be "dead". > > Ah, yes it is indeed. Thanks. > > > For Windows there are tools to bundle your source and all dependencies and > > even the interpreter itself. `py2exe` is such a tool. With InnoSetup or > > NSIS or similar programs you can then make a `setup.exe` for that spoiled > > Windows brats. :-) > > > Under Linux many packages are available as distribution specific packages > > on most distributions. So for Linux you may get away with a README > > stating the dependencies of your program and a `setup.py` for installing > > your project. Look for `distutils` in the Python documentation for > > further information about `setup.py`\s. > > setup.py sounds like the best way to go. Most of the classrooms and > lecture halls run on Ubuntu machines, and as I said, I don't really care > much for the Windows brats anyway. 'doze installers etc would be a nice > to have, but not needed right now. > > > > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? > > > Use the one you like best. ;-) > > Thought as much. I do 90% of my coding in vi anyways, but am still > getting a couple of nutty errors from Python simply because I have not > yet gotten the hang of significant whitespace :) Darn that PHP! > > Thanks for the feedback, now I just need some justification on the > GTK/GUI stuff - wxWidgets, GTK+ Glade or other? > > --Paul > > All Email originating from UWC is covered by disclaimerhttp://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm I myself prefer wxPython(wxWidgets wrapper for python), it's more "Object Oriented" then, say GTK. But really, just check out their homepages to see features they include, and go by that instead. From deets at nospam.web.de Thu Mar 27 05:32:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 10:32:07 +0100 Subject: Partial Function Application and implicit self problem References: <47EB58B5.1020801@mydeskfriend.com> Message-ID: <6517tiF2e0id5U1@mid.uni-berlin.de> Gabriel Rossetti wrote: > > Gabriel Rossetti wrote: >> Hello, >> >> I am using Partial Function Application in a class and I've come up with >> a problem, when the method is called it tries to pass "self" to the >> curried/partial function, but this should be the first argument in >> reality, but since the function is curried, then the self gets passed as >> the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that since >> self is not available there. Does anyone have any ideas? >> >> Thanks, >> Gabriel >> > I also tried this : > > def __registerService(atomic, self, service): > def reg(service): > # registers the service > ... > > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > thinking that the self will be passed as the first argument of the > registerService* calls and thus the second argument to the > curried/partial method, but it doesn't work either, I get : > > Traceback (most recent call last): > File "/home/xxx/Documents/Code/Python/test/test_serv.py", line 245, in > test_registeration > self.f.registerServiceAtomic(self.serv) > exceptions.TypeError: __registerService() takes exactly 3 arguments (2 > given) First, passing self not as first argument is not going to work, and a HUGE design flaw anyway: even IF it would work, it would mean that you *must* use partial to bind default-arguments before invoking a method. And it goes to much against the design of python. Apart from that, please post self-contained examples that produce the error. the above code is hard to grasp because it's unclear which is called from where with what. Diez From malkarouri at gmail.com Sat Mar 8 11:20:24 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 08:20:24 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <4298be09-e8b7-4d67-a0f4-59a2b34bfd49@f47g2000hsd.googlegroups.com> On Mar 8, 3:52?pm, duncan smith wrote: > malkarouri wrote: > > Hi everyone, > > > I have an algorithm in which I need to use a loop over a queue on > > which I push values within the loop, sort of: > > > while not(q.empty()): > > ? ? x = q.get() > > ? ? #process x to get zero or more y's > > ? ? #for each y: > > ? ? q.put(y) > > > The easiest thing I can do is use a list as a queue and a normal for > > loop: > > > q = [a, b, c] > > > for x in q: > > ? ? #process x to get zero or more y's > > ? ? q.append(y) > > > It makes me feel kind of uncomfortable, though it seems to work. The > > question is: is it guaranteed to work, or does Python expect that you > > wouldn't change the list in the loop? > > I have used exactly the same approach. ?I think it's a clean (even > elegant) solution. ?I'd be surprised if it ceased to work in some future > implementation of Python, but I don't know if that's absolutely guaranteed. > > Duncan Thanks Duncan, I think I will go ahead and use it. Though the Python tutorial says otherwise in section 4.2: "It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.". More explicitly, in 7.3 of the Python Reference Manual: "Warning: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop." This can be interpreted as don't play with the past. However, the part "When this counter has reached the length of the sequence the loop terminates." is interpretable as either the starting sequence length or the running sequence length. Testing: In [89]: x=range(4) In [90]: for i in x: ....: print i ....: x.append(i+4) ....: if i>=8:break ....: ....: 0 1 2 3 4 5 6 7 8 So it is the running sequence length. But I am still not sure if that is guaranteed. Regards, Muhammad Alkarouri From spam at ecp.cc Wed Mar 19 18:27:24 2008 From: spam at ecp.cc (dsavitsk) Date: Wed, 19 Mar 2008 17:27:24 -0500 Subject: ADO error - large data set References: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> Message-ID: <9qgEj.4646$6H.3740@newssvr22.news.prodigy.net> Is it possible there is some bad data in the larger db? This is asinine, but maybe write a small script that adds some data, then opens and closes the db, then repeats this. If this is a size issue, then you can at least narrow it down to where the size limit is? And, if it isn't you should be able to figure that out, too. Otherwise, play around with the locking and cursor options. -d "Gyula" wrote in message news:475c155d-fe16-472f-a4f8-363f6db339eb at d21g2000prf.googlegroups.com... > Hi there, > > I have been running Python to tap into an MS Access 2003 database > using ADO (PythonWin+COM). Everything works great creating recordsets > etc. when I open a table with a small number of records. However, when > I try to run the same Python code with a large table (>100,000) I get: > > Traceback (most recent call last): > File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Documents and Settings\user\Desktop\PythonWS\scripts > \readmsaccess.py", line 43, in > rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) > File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open > , ActiveConnection, CursorType, LockType, Options) > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > 5003251, -2147467259), None) > > The small and large table structures are identical, all I do is change > the tblname from input1000 (1000 records) to input (>100000 records). > I use optimistic locking and keyset cursor..nothing out of the > ordinary? > > Any ideas? ADO 2.8 is what I am using. > > Thanks a lot! > GG From justjpm at aol.com Thu Mar 20 13:26:14 2008 From: justjpm at aol.com (Jim) Date: Thu, 20 Mar 2008 10:26:14 -0700 (PDT) Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> <13u3660kfnhq412@corp.supernews.com> Message-ID: <74cdd195-2bfa-4548-a16e-bf14c6b07b50@p73g2000hsd.googlegroups.com> On Mar 19, 6:50 pm, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 14:45:39 -0700, Jim wrote: > > Program randomly aborts when looking up url. The program loop thru > > 4000+ records looking > > up ID via internet and returnshtmlcode which is used in subsequent > > processing. The code > > for looking-up record is below followed by abort details. Can anyone > > help with catching the > > abort before program aborts or provide code to automatically start > > program? > > Yes. Wrap the offending code with a try...except loop, something similar > to this. > > try: > contents = urllib2.urlopen(url).read() > except URLError, e: > if e.errno == 10053: > # "Software caused connection abort" > response = raw_input( > "Temporary failure, Skip/Halt/try Again?") > response = response.lower().strip() > if response in ('h', 'halt'): > break > elif response in ('a', 'again', 't', 'try', 'try again'): > continue > elif response in ('', 's', 'skip'): > lines -= 1 > continue > else: > print "Unknown response, boo hiss to you!" > raise > > -- > Steven Thanks Steven for recommendation. The program is my first and I'm not a programmer so it will take me some time to get your recommendation to work. So far the program runs after I added code based on your example but the program still aborts and none of the code ("Temporary failure, Skip/Halt/try Again?" or "Unknown response, boo hiss to you!") in your example is displayed. It appears to abort in the imported module "urllib2" which is open source. The code in urllib2 is way over my skill level. Jim From code at pizzashack.org Mon Mar 24 17:58:42 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Mar 2008 17:58:42 -0400 Subject: Python 2.2.1 and select() Message-ID: <20080324215842.GE26870@dragontoe.org> Hi kids! I've got some code that uses select.select() to capture all the output of a subprocess (both stdout and stderr, see below). This code works as expected on a variety of Fedora systems running Python > 2.4.0, but on a Debian Sarge system running Python 2.2.1 it's a no-go. I'm thinking this is a bug in that particular version of Python, but I'd like to have confirmation if anyone can provide it. The behavior I see is this: the call to select() returns: [] [] [] If and only if the total amount of output is greater than the specified buffer size, then reading on this file hangs indefinitely. For what it's worth, the program whose output I need to capture with this generates about 17k of output to STDERR, and about 1k of output to STDOUT, at essentially random intervals. But I also ran it with a test shell script that generates roughly the same amount of output to each file object, alternating between STDOUT and STDERR, with the same results. Yes, I'm aware that this version of Python is quite old, but I don't have a great deal of control over that (though if this is indeed a python bug, as opposed to a problem with my implementation, it might provide some leverage to get it upgraded)... Thanks in advance for any help you can provide. The code in question (quite short) follows: def capture(cmd): buffsize = 8192 inlist = [] inbuf = "" errbuf = "" io = popen2.Popen3(cmd, True, buffsize) inlist.append(io.fromchild) inlist.append(io.childerr) while True: ins, outs, excepts = select.select(inlist, [], []) for i in ins: x = i.read() if not x: inlist.remove(i) else: if i == io.fromchild: inbuf += x if i == io.childerr: errbuf += x if not inlist: break if io.wait(): raise FailedExitStatus, errbuf return (inbuf, errbuf) If anyone would like, I could also provide a shell script and a main program one could use to test this function... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From aisaac at american.edu Thu Mar 13 12:38:33 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 13 Mar 2008 16:38:33 GMT Subject: no more comparisons In-Reply-To: <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: Dan Bishop wrote: > def cmp_key(cmp_fn): > class CmpWrapper(object): > def __init__(self, obj): > self.obj = obj > def __cmp__(self, other): > return cmp_fn(self.obj, other.obj) > return CmpWrapper Apparently I'm overlooking something obvious ... how is this supposed to work if __cmp__ is no longer being called? (Which was my understanding.) Thank you, Alan Isaac From emailamit at gmail.com Mon Mar 31 17:53:17 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 14:53:17 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <41b598ef-c422-417f-9a77-b48eff8e6334@s37g2000prg.googlegroups.com> Message-ID: On Mar 31, 1:52 pm, Mike Driscoll wrote: > > What about creating a setup.py and using the distutils command to > build rpms or tarballs? > > http://docs.python.org/dist/built-dist.html > > Mike My quick look: The link you sent is under the header "Distributing Python Modules". In my case, I have set of python-files that altogether is part of one product-functionality. I would like to package it and have it run standalone, even if the user does not have python installed. Ok, I guess build-dist can possibly achieve the same purpose (without reading through the link you sent). So my question would be: why is there pyinstaller, if this does the job. Is build-dist more low-level and thus is over-kill for the kind of application I am looking for?: Thanks From pianomaestro at gmail.com Fri Mar 28 11:41:16 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 08:41:16 -0700 (PDT) Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: <29a52f2a-c344-4405-be0c-b0a18503c1ee@59g2000hsb.googlegroups.com> On Mar 28, 11:14 am, "Gabriel Genellina" wrote: > C global variables are global, not per-thread. aha, a static pointer gets initialized to NULL, so I can check if it's not NULL in the module initializer. Thanks for jogging my brain, Simon. > > -- > Gabriel Genellina From mail at timgolden.me.uk Tue Mar 25 12:09:17 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Mar 2008 16:09:17 +0000 Subject: Reading new mail from outlook using Python In-Reply-To: <971720.4797.qm@web50104.mail.re2.yahoo.com> References: <971720.4797.qm@web50104.mail.re2.yahoo.com> Message-ID: <47E923AD.80803@timgolden.me.uk> SPJ wrote: > Thanks... > > I could access the folders in outlook express using the COM interface. > Now I am stuck with how to read to a file only new mails. Well, this Google query: http://www.google.co.uk/search?hl=en&q=OUTLOOK.application+unread+messages seems to indicate some useful hits. (But perhaps you knew that?) TJG From tmp1 at viltersten.com Fri Mar 7 09:56:44 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 15:56:44 +0100 Subject: Quit-command not quiting Message-ID: <63d2efF271u6hU1@mid.individual.net> I entered the code from tkinter.pdf, section 2 but for reason, the application doesn't close as i press the quit-button. The wondow itself vanishes if i click the cross in the upper-right corner but pressing the quit-button only makes it "pressed". Then, the program freezes. This is the code. from Tkinter import * class Demo (Frame): def __init__ (self, master = None): Frame.__init__ (self, master) self.grid () self.doLayout () def doLayout (self): self.quitButton = Button ( self, text = "Quit", command = self.quit) self.quitButton.grid () d = Demo () d.master.title ("the coolest demo ever") d.mainloop () -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From arbo.newmedia at gmail.com Wed Mar 5 05:45:36 2008 From: arbo.newmedia at gmail.com (arbo.newmedia at gmail.com) Date: Wed, 5 Mar 2008 02:45:36 -0800 (PST) Subject: Leopard and MySQL Message-ID: Hi, can anyone help me with MySQL. I've got Mac OSX Leopard and I'm trying to install MySQLdb for Python. I'm running build and it goes withous any errors and install. But when I'm typing : import MySQLdb in IDLE I've got this: Traceback (most recent call last): File "", line 1, in import MySQLdb File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19, in File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/lisek/.python-eggs/MySQL_python-1.2.2-py2.5- macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/lisek/.python-eggs/MySQL_python-1.2.2-py2.5- macosx-10.3-fat.egg-tmp/_mysql.so Expected in: dynamic lookup And I don't know what is wrong... ;/ From diljeet_kr at yahoo.com Mon Mar 10 00:02:34 2008 From: diljeet_kr at yahoo.com (diljeet kaur) Date: Sun, 9 Mar 2008 21:02:34 -0700 (PDT) Subject: removing escape character Message-ID: <448738.13250.qm@web52806.mail.re2.yahoo.com> hi i am working on pyqt environment when i write to file, i get some unwanted characters like "ESC" in file how to get rid of these characters? --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From edreamleo at charter.net Fri Mar 28 11:04:55 2008 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 28 Mar 2008 10:04:55 -0500 Subject: ANN: Leo 4.4.8 b3 released Message-ID: Leo 4.4.8 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This version features a new ipython plugin that provides a two-way bridge between Leo and IPython. See http://webpages.charter.net/edreamleo/IPythonBridge.html Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.8: ---------------------------- - Leo's source code is now managed by bzr: see link below. - Leo's discussion is now hosted by Google Groups: see link below. - Arguments to g.es and g.es_print can be translated using gettext. - Completed ILeo: a bridge between IPython and Leo. See http://webpages.charter.net/edreamleo/IPythonBridge.html - Minibuffer commands may have arguments. - @menu trees can now refer to commands created by @command and @button nodes. - Added support for common @commands nodes in settings files. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jim.vickroy at noaa.gov Tue Mar 25 14:13:47 2008 From: jim.vickroy at noaa.gov (j vickroy) Date: Tue, 25 Mar 2008 12:13:47 -0600 Subject: how to dynamically create class methods ? In-Reply-To: References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: Hello, Here is some pseudo-code that hopefully illustrates what I want to do: records = list(...) for record in records: new_fcn = define_a function_for(record) instance = my_new_class_instance() setattr(instance, 'myfcn', new_fcn) instance.execute() # instance.execute() calls instance.myfcn(*args) I have looked at some of the functions in the *new* module and new.code(...), new.function(...), and new.instancemethod(...) appear to do what I want, but I do not know how to use new.code() and new.function() -- specifically what its *global* parameter should be. I was not able to find helpful information using Google. Thanks for any suggestions on how to approach this. -- jv From tmp1 at viltersten.com Sun Mar 9 12:10:56 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 17:10:56 +0100 Subject: Changing the size of a Button Message-ID: <63ifhtF277va7U1@mid.individual.net> How do i change the size of a Button (using Tkinter), other than to set it during construction? I've found methods for getting the size but not applying them. I've been laborating with .setvar(*) but i've been unsuccessful. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From mcepl at redhat.com Tue Mar 4 17:18:10 2008 From: mcepl at redhat.com (Matej Cepl) Date: Tue, 04 Mar 2008 23:18:10 +0100 Subject: Edit MP4 and/or WMV file metadata? Message-ID: <2eu0a5xpji.ln2@ppp1053.in.ipex.cz> On 2008-03-04, 18:53 GMT, allen.fowler wrote: > 1) Is there a python module I can use to edit the metadata in > MP4 > files? I am not sure whether taglib supports MP4, but take a look at http://developer.kde.org/~wheeler/taglib.html and http://developer.berlios.de/project/showfiles.php?group_id=2066 or http://news.tiker.net/software/tagpy > 2) Failing that, is there a python module I can use to edit the > metadata in the WMV files, and hope the data makes it through the > conversion? You may also be able to do something with gst-launch (on Linux). Mat?j From google at mrabarnett.plus.com Fri Mar 21 14:11:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 21 Mar 2008 11:11:07 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <128011dd-a1a8-43af-bdea-beba452aa596@f63g2000hsf.googlegroups.com> On Mar 21, 11:48 am, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > The script could just check to see if the version on the server is more recent and if it is then copy it over the local one, start the local one, and then quit. Python compiles the script to bytecode and then interprets the bytecode, so when the script is being run the .py or .pyw source itself isn't being used and can be overwritten. I've tried the following on Windows XP and it works: import os import sys import shutil # Is there a newer version? my_path = sys.argv[0] update_path = os.path.join(os.path.dirname(my_path), "new_script.py") if os.path.getmtime(my_path) < os.path.getmtime(update_path): # Update the script. shutil.copy2(update_path, my_path) # Re-start the script. os.startfile(my_path) sys.exit() # The rest of the script... From duncan.booth at invalid.invalid Mon Mar 17 16:31:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 20:31:45 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <13tst1388cp67d8@corp.supernews.com> Message-ID: Matthew Woodcraft wrote: > In article , > Duncan Booth wrote: >> I don't have a copy of 1.4 to check so I'll believe you, but you can >> certainly get the output I asked for with much more recent versions. > >> For the answer I actually want each asterisk substitutes for exactly >> one character. > > Then I'll guess you're looking for something like '0==0', with Python > 2.2 or so (so that you'd get the PyTrue object). > Yes, that was the answer I was looking for: CPython 1.5.x (or maybe earlier?) to 2.2.x without a bool type but separate values for true and false (as used by PyWin). Also it seems that Jython 2.2.1 (and probably other versions) behaves the same way. I'm intrigued though by Stargaming's answer with 1//1, I must look into that one. From erikwickstrom at gmail.com Tue Mar 25 16:13:13 2008 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 25 Mar 2008 13:13:13 -0700 (PDT) Subject: "Soup Strainer" for ElementSoup? References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> <47e87a88$0$36376$742ec2ed@news.sonic.net> Message-ID: <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> On Mar 25, 12:17 am, John Nagle wrote: > erikcwwrote: > > Hi all, > > > I was reading in the Beautiful Soup documentation that you should use > > a "Soup Strainer" object to keep memory usage down. > > > Since I'm already using Element Tree elsewhere in the project, I > > figured it would make sense to use ElementSoup to keep the api > > consistent. (and cElementTree should be faster right??). > > > I can't seem to figure out how to pass ElementSoup a "soup strainer" > > though. > > > Any ideas? > > > Also - do I need to use the extract() method with ElementSoup like I > > do with Beautiful Soup to keep garbage collection working? > > > Thanks! > > Erik > > I really should get my version of BeautifulSoup merged back into > the mainstream. I have one that's been modified to use weak pointers > for all "up" and "left" links, which makes the graph cycle free. So > the memory is recovered by reference count update as soon as you > let go of the head of the tree. That helps with the garbage problem. > > What are you parsing? If you're parsing well-formed XML, > BeautifulSoup is overkill. If you're parsing real-world HTML, > ElementTree is too brittle. > > John Nagle I'm parsing real-world HTML with BeautifulSoup and XML with cElementTree. I'm guessing that the only benefit to using ElementSoup is that I'll have one less API to keep track of, right? Or are there memory benefits in converting the Soup object to an ElementTree? Any idea about using a Soup Strainer with ElementSoup? Thanks! From sturlamolden at yahoo.no Tue Mar 18 17:25:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 14:25:12 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> On 18 Mar, 22:22, sturlamolden wrote: > def nonunique(lst): > slst = sorted(lst) > return list(set([s[0] for s in > filter(lambda t : not(t[0]-t[1]), zip(slst[:-1],slst[1:]))])) Or perhaps better: def nonunique(lst): slst = sorted(lst) return list(set([s[0] for s in filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) From xkenneth at gmail.com Sun Mar 9 17:28:13 2008 From: xkenneth at gmail.com (xkenneth) Date: Sun, 9 Mar 2008 14:28:13 -0700 (PDT) Subject: Logically/Selectively Sub Class? Message-ID: Might be a silly question, but is it possible to selectively subclass, IE subclass is a supporting module is present and not otherwise. Regards, Kenneth Miller From Wayne.Oosthuizen at gmail.com Sat Mar 29 04:46:33 2008 From: Wayne.Oosthuizen at gmail.com (Constantly Distracted) Date: Sat, 29 Mar 2008 01:46:33 -0700 (PDT) Subject: Setting the value of one cell in QTableWidget fills everything. References: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> Message-ID: <851bdc24-6308-47ca-9d8d-cb31db41ce02@x41g2000hsb.googlegroups.com> > Move the creation of the QTableWidgetItem() to the inner loop (and call > it "item" rather than "items"). > > Phil Thanks, that works perfectly. From amca01 at gmail.com Sat Mar 8 18:11:53 2008 From: amca01 at gmail.com (Alasdair) Date: Sun, 09 Mar 2008 10:11:53 +1100 Subject: Arbitrary precision integer arithmetic: ceiling? Message-ID: I need to apply the ceiling function to arbitrary sized (long) integers. However, division automatically returns the type of its operands, so that, for example: math.ceil(7/4) returns 1. I can use float, as in: math.ceil(7/float(4)), except that for very large integers float causes an unacceptable loss of precision. What is the best way of finding a ceiling of a quotient of arbitrary sized integers? Thanks, Alasdair From gh at ghaering.de Wed Mar 19 03:43:23 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 19 Mar 2008 08:43:23 +0100 Subject: What Programming Languages Should You Learn Next? In-Reply-To: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> Message-ID: <64bugqF2anottU1@mid.uni-berlin.de> wesley chun wrote: > http://it.slashdot.org/it/08/03/18/1633229.shtml > > it was surprising and disappointing that Python was not mentioned > *anywhere* in that article [...] Probably because Ruby is all hot and sexy nowadays ;-) Though it's remarkably close to Python, apparently. So close that I couldn't be bothered to learn it. In fact, for me personally, Python was about the last programming language I learnt out of intrinsic motivation. I tried to take a look at functional langugages like Haskell and Erlang, but I tend to quickly get bored of toy examples and can learn best if I can apply a new language to a real problem that it can solve better than the other languages I know. Haven't found that killer problem so far ... -- Gerhard From pradiprai at gmail.com Mon Mar 17 03:21:01 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 17 Mar 2008 12:51:01 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Thanks for your inputs !!! I have installed python v 2.5 on my Linux machine and executing the tool again. I would like to share the memory status( using free -m command ) before and after the execution of the tool. BEFORE EXECUTION ================ total used free shared buffers cached Mem: 1006 148 *858* 0 8 92 -/+ buffers/cache: 46 960 Swap: 2047 0 2047 AFTER EXECUTION =============== total used free shared buffers cached Mem: 1006 940 *66* 0 49 846 -/+ buffers/cache: 44 962 Swap: 2047 0 2047 I am unable to find out why *66 MB* system memory is left after tool execution ? If python does not have memory leaks then where this memory is going ? I have explored few urls (as given below) related to memory leak in python : http://www.nightmare.com/medusa/memory-leaks.html http://mail.python.org/pipermail/tutor/1999-April/000162.html Please comment !!! -----Original Message----- *From:* python-list-bounces+pradiprai=gmail.com at python.org [mailto: python-list-bounces+pradiprai=gmail.com at python.org] *On Behalf Of *tsuraan *Sent:* 16 March 2008 8:27 AM *To:* python-list at python.org *Subject:* Re: Urgent : How to do memory leaks detection in python ? > Python doesn't have memory leaks. Yeah, interesting bit of trivia: python is the world's only non-trivial program that's totally free of bugs. Pretty exciting! But seriously, python 2.4, at least, does have some pretty trivially exposed memory leaks when working with strings. A simple example is this: >>> letters = [chr(c) for c in range(ord('a'), ord('z'))+range(ord('A'), ord('Z'))] >>> ary = [] >>> for a in letters: ... for b in letters: ... for c in letters: ... for d in letters: ... ary.append(a+b+c+d) ... >>> del(ary) >>> import gc >>> gc.collect() 0 The VM's memory usage will never drop from its high point of (on my computer) ~200MB. Since you're using GIS data, this could be what you're running into. I haven't been able to upgrade my systems to python 2.5, but from my tests, that version did not have that memory leak. Nobody seems interesting in backporting fixes from 2.5 to 2.4, so you're probably on your own in that case as well, if upgrading to python 2.5 isn't an option or isn't applicable to your situation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Afro.Systems at gmail.com Tue Mar 25 08:30:59 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 05:30:59 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <534cd01c-3d49-4dd8-ba04-71551cdd46d3@d21g2000prf.googlegroups.com> Message-ID: <1396c034-3f07-4991-96a8-09b44e1929cd@e23g2000prf.googlegroups.com> On Mar 25, 2:00?pm, John Machin wrote: > On Mar 25, 10:44 pm, Tzury Bar Yochay wrote: > > > > > given two classes: > > > class Foo(object): > > ? ? def __init__(self): > > ? ? ? ? self.id = 1 > > > ? ? def getid(self): > > ? ? ? ? return self.id > > > class FooSon(Foo): > > ? ? def __init__(self): > > ? ? ? ? Foo.__init__(self) > > ? ? ? ? self.id = 2 > > > ? ? def getid(self): > > ? ? ? ? a = Foo.getid() > > ? ? ? ? b = self.id > > ? ? ? ? return '%d.%d' % (a,b) > > > While my intention is to get 1.2 I get 2.2 > > I would like to know what would be the right way to yield the expected > > results > > Post the code that you actually executed. What you have shown lacks > the code to execute it ... but the execution will fail anyway: > > ? ? a = Foo.getid() > TypeError: unbound method getid() must be called with Foo instance as > first argument (got nothing instead) sorry, it should have been: a = Foo.getid(self) instead of a = Foo.getid() From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:52:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:52:36 -0000 Subject: Better grammar.txt References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: <13t3e944k9p7tf0@corp.supernews.com> On Fri, 07 Mar 2008 13:42:56 -0800, MartinRinehart wrote: > Jeroen Ruigrok van der Werven wrote: >> >http://www.martinrinehart.com/articles/python-grammar.html: Unknown >> >host www.martinrinehart.com >> >> Works for me. > > Very interesting. The link I posted works for me, while the links quoted > are 404 errors, though they look identical. This really is a superior > version of the EBNF, so I wish it would work for everyone. Any ideas? I get 404. Perhaps you need to move this discussion to a mailing list for web admins, rather than Python developers? What I know about hosting a web site I could engrave on a poppy seed. In letters ten feet high. Doesn't mean I won't express an opinion though :) Perhaps it works for you because you are inside your firewall, rather than outside it? Also, I would be concerned that some people (one person?) is reporting an Unknown Host error. Who is your domain registrar? -- Steven From gagsl-py2 at yahoo.com.ar Sun Mar 30 05:10:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 06:10:12 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> <5f067c48-e6d4-405b-a064-70b26f8b0343@m71g2000hse.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 05:08:34 -0300, escribi?: > On Mar 29, 12:41 pm, Steven D'Aprano cybersource.com.au> wrote: >> Since you jump to an invalid conclusion about !=, the rest of your >> argument fails. > > No, you said <= could be confusing, but we're talking about <> here, > and there is no confusion about that :). Yes, there is: <> looks like "less or greater", and being equal or not is a different thing that being less or greater. Trichotomy law holds for real numbers (although some people don't even accept that) but not for floating point (NANs); and Python isn't about numbers only. For a lot of objects it makes sense to compare them for equality or not, but you can't say which one is greater than the other (the weather forecast, books in a bookstore) -- Gabriel Genellina From __peter__ at web.de Wed Mar 19 17:11:26 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Mar 2008 22:11:26 +0100 Subject: keeping state in an iterator object by rebinding next() References: Message-ID: Wilbert Berendsen wrote: > Hi, > > i am writing a simple parser, that generates tokens. The parser needs to > maintain some state, because some parts of the file consist of different > tokens. I thought the object could simply remember its state by assigning > it's next() method to the method that is currently parsing. When the state > changes, the called method rebinds next() and the next token will be > returned by that function. Here's an example, proving that this indeed > works. > >>>> class A: > ... def a(self): > ... self.next = self.b > ... return 1 > ... def b(self): > ... self.next = self.a > ... return 2 > ... def __iter__(self): > ... return self > ... >>>> a=A() >>>> a.a() > 1 >>>> a.next() > 2 >>>> a.next() > 1 >>>> j=0 >>>> for i in a: > ... j += 1 > ... if j > 10: break # prevent from running endlessly > ... print i > ... > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 >>>> > > my question is: is this legal Python? An iterator could save the next() > method object, and in that case it could stop working.... It works now, > because apparently the for- construct resolves 'next' each time for the > object before calling it. > > The other solution would be just jumping to the correct method from within > the next() method. But that gives an extra call... It doesn't work with newstyle classes though as next() is looked up in the class rather than the instance, just like the __xxx__() methods: >>> class A(object): ... def __iter__(self): return self ... def next(self): return "class-next()" ... >>> a = A() >>> a.next = lambda: "instance-next()" >>> a.next() 'instance-next()' >>> from itertools import islice >>> for item in islice(a, 3): print item ... class-next() class-next() class-next() Without the class-next() it isn't even recognized as an iterator >>> del A.next >>> for item in a: pass ... Traceback (most recent call last): File "", line 1, in TypeError: iter() returned non-iterator of type 'A' even though the instance-next() is still there: >>> a.next() 'instance-next()' So I recommend that you avoid that can of worms and go with the extra indirection. Peter From gherron at islandtraining.com Sun Mar 16 11:32:47 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 16 Mar 2008 08:32:47 -0700 Subject: Weight Problem In-Reply-To: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> References: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> Message-ID: <47DD3D9F.70102@islandtraining.com> Ravi Kumar wrote: > An Interesting problem, > """ > A man has only 4 bricks of different weights, lies between 1-40KG, > Also, the total weights of Brick A, B, C, D (ie A+B+C+D) is 40KG. > The man uses that brick to calculate every possible weight > from 1 KG to 40 KG in his shop. (only whole numbers 1KG, 2KG etc, not > like 2.3KG) > """ > > I thought it would really be good to solve it by python, and right now > on the mid-way solving using very dirty approach. > But I feel, using SETs with python in such would solve it better. > Can anyone come with good solution, and maybe solution showing usage > of Sets. > -- > -=Ravi=- This sounds like a homework problem, something you should be solving yourself. If, however, you have any Python questions, then please ask. We'll be glad to answer them. -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From lorgandon at gmail.com Thu Mar 13 18:31:19 2008 From: lorgandon at gmail.com (Imri Goldberg) Date: Fri, 14 Mar 2008 00:31:19 +0200 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: References: Message-ID: <47D9AB37.2020608@gmail.com> Dave Kuhlman wrote: > The following code has me mystified: > > In [4]: class A(object): > ...: def show(self): > ...: print 'hello' > ...: > ...: > In [5]: a = A() > In [6]: > In [7]: x = a.show > In [8]: y = getattr(a, 'show') > In [9]: x > Out[9]: > > In [10]: y > Out[10]: > > In [11]: > In [12]: id(x) > Out[12]: 12419552 > In [13]: id(y) > Out[13]: 12419872 > In [14]: > In [15]: x is y > Out[15]: False > In [16]: > In [17]: x() > hello > In [18]: y() > hello > > Basically, the above code is saying that foo.foobar is not the same as > getattr(foo, 'foobar'). > > But the documentation at > http://docs.python.org/lib/built-in-funcs.html#l2h-33 > says that they are equivalent. > > And, the following seems even worse: > > >>> id(getattr(a, 'show')) == id(a.show) > True > >>> getattr(a, 'show') is a.show > False > > Actually, while I don't know about the basic problem, this doesn't mean id() is broken. In the comparison, an object is created, then id() is computed, and the object is garbage collected. The same happens to the second object. Since by the time it is created the first object was garbage collected, it can have the same id(). As you have already shown in your previous example, when the first object is not discarded, the id() is different. Here's some code to illustrate this: In [17]: bla = [a.foo for x in range(5)] In [18]: bar = [id(z) for z in bla] In [19]: bar Out[19]: [138262924, 137884252, 137884212, 137884452, 137884572] (This result is equivalent for getattr(a,'foo').) > What gives? This breaks my understanding of id(), the is operator, and > getattr(). > > Can someone help me make sense of this? > > I'm using Python 2.5.2. > > - Dave > > Cheers, Imri ------------------------- Imri Goldberg www.algorithm.co.il/blogs www.imri.co.il ------------------------- Insert Signature Here ------------------------- From castironpi at gmail.com Tue Mar 11 00:19:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 21:19:12 -0700 (PDT) Subject: python interactive - threaded console (run -i) Message-ID: <56661ddb-f06b-4229-8011-7996cd023600@m34g2000hsc.googlegroups.com> #interactive run -i import threading import Queue import functools class GenThread( threading.Thread, Queue.Queue ): _taskid= 0 def __init__( self, *ar, **kw ): threading.Thread.__init__( self, *ar, **kw ) Queue.Queue.__init__( self ) self.setDaemon( True ) self.start() self._doneevents= {} def run( self ): while 1: id, fun, ar, kw= self.get() self._= fun( *ar, **kw ) self._doneevents[id].set() if self._: self._print( self._ ) def me( self, fun, *ar, **kw ): id= GenThread._taskid GenThread._taskid+= 1 self.put( ( id, fun, ar, kw ) ) self._doneevents[ id ]= e= threading.Event() return e def _print( self, *ar, **kw ): print( self.getName(), *ar, **kw ) for i in range( 10 ): exec( 'th%i= GenThread()'% i ) import socket host= socket.socket( socket.AF_INET, socket.SOCK_STREAM ) host.bind( ( '', 8000 ) ) th1.me( host.listen, 1 ) _acc= th1.me( host.accept ) cli= socket.socket( socket.AF_INET, socket.SOCK_STREAM ) th2.me( cli.connect, ( 'localhost', 8000 ) ) _acc.wait() conn= th1._[0] ConnClose= object() class IncompleteTransmission( Exception ): pass def _draintilclose( conn, understandfun= None ): while 1: _preamb= '' while 1: _data= conn.recv( 1 ) if not _data: conn.close() return ConnClose if _data== b'\x00': break _preamb+= _data.decode() _len= int( _preamb, 16 ) _lenleft= _len _curmsg= bytearray() while _lenleft: _data= conn.recv( min( 4096, _lenleft ) ) if not _data: raise IncompleteTransmission _curmsg.extend( _data ) _lenleft-= len( _data ) assert len( _curmsg )== _len if None is not understandfun: understandfun( _curmsg ) def _dressandsend( sck, msg ): _preamble= hex( len( msg ) )[2:]+ '\x00' _dressed= bytes( _preamble, 'ascii' )+ msg _lenleft= len( _dressed ) while _lenleft: _sent= sck.send( _dressed[-_lenleft:] ) _lenleft-= _sent th1.me( _draintilclose, conn, th1._print ) th2.me( _draintilclose, cli, th2._print ) This is cool! Set up a socket and listen 'til close on one thread, print output by default as complete messages are received. Listen 'til close, same, on another, th1, th2 respectively. Roughly off the console: >>> _dressandsend( conn, b'abc' ) Thread-2 bytearray(b'abc') >>> _dressandsend( cli, b'def' ) Thread-1 bytearray(b'def') Rearranged the '>>>'. It's damn annoying. Probably a specialized stdout to detect when in a prompt and add extra newline, maybe modified GenThread._print. Someone go replace hex with base255 and conn.recv( 1 ) with conn.recv( 2 ). Should take any length-- base256 over hex is just a factor of 2, and still O( log( message length ) ). >>> dir() ['ConnClose', 'GenThread', 'IncompleteTransmission', 'Queue', '__builtins__', '__doc__', '__name__', '__package__', '_acc', '_draintilclose', '_dressandsend', 'cli', 'conn', 'functools', 'host', 'i', 'socket', 'th1', 'th2', 'th3', 'th4', 'th5', 'th6', 'th7', 'th8', 'th9', 'threading'] From Lie.1296 at gmail.com Sun Mar 9 08:50:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 05:50:29 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> Message-ID: On Mar 9, 4:31?pm, Kay Schluehr wrote: > On 9 Mrz., 09:30, Lie wrote: > > On Mar 9, 12:05 pm, Kay Schluehr wrote: > > > > On 9 Mrz., 04:51, Lie wrote: > > > > > A more through implementation would start from the raiser inspecting > > > > the execution stack and finding whether there are any try block above > > > > it, if no try block exist it pass silently and if one exist it will > > > > check whether it have a matching except clause. This also circumvents > > > > a problem that simple implementation have, as described below. > > > > This will not be easy in particular in the presence of inheritance and > > > dynamism. There is no way to statically decide whether an exception > > > BException has the type AException and will be caught by the except > > > clause in > > > > try: > > > ? ? BLOCK > > > except AException, e: > > > ? ? print "SoftException %s caught"%e > > > A feasible solution was to invert the try...except statement and > > > creating a continuation. > > > > catch AException, a: > > > ? ?print "SoftException A: %s"%a > > > catch BException , b: > > > ? ?print "SoftException B: %s"%b > > > ... > > > in: > > > ? ?BLOCK > > > > Here each SoftException is raised initially when a catch clause is > > > entered and a continuation is created that returns to the catch block > > > of the raised SoftException if required. When a SoftException is > > > raised within BLOCK a lookup will be made and if a corresponding > > > SoftException was found that was raised by a catch-clause the current > > > control flow will be suspended and the continuation is called. > > > I'd rather want to avoid any syntax changes, as I wished that Soft > > Exception can be added to the language silently[1] so that new > > programmers doesn't _need_ to know about it (although knowing it could > > change the way they write codes to be more structured and simple). > > I just tried to save your proposal from being unimplementable. Maybe > you can comment on it? Perhaps I'm not the appropriate person to talk about whether unchanged syntax is feasible for such implementation since I basically have no idea about how Python's internals works. It's only that I think if current syntax could be used, we could just use it (except if there is a strong reason why it shouldn't be done). > I know of course that syntax is Pythons holy cow but I'm not Guidos > mouthpiece and have a different perspective on some aspects of the > system for obvious reasons [1]. I agree, everybody have different perspective. But that differences is what makes languages evolves as it'd be continuously searching for the most optimal perspective. From bblais at bryant.edu Fri Mar 14 18:10:57 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 14 Mar 2008 18:10:57 -0400 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: <902DE75B-EE78-44D6-AD13-4AFAE47D14F5@bryant.edu> On Mar 14, 2008, at Mar 14:5:59 PM, castironpi at gmail.com wrote: > On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>> Subject: RIP: Joseph Weizenbaum >> >>> Creator of Eliza: >> >>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>> -- >> >> How do you feel about creator of Eliza? > > What is Eliza? You: What is Eliza? Eliza: Does that question interest you? (http://www-ai.ijs.si/eliza/eliza.html) bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From haraldarminmassa at gmail.com Thu Mar 13 14:46:41 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Thu, 13 Mar 2008 11:46:41 -0700 (PDT) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Doug, > Precision.py is part of the Numeric package. AFAIKT, the problem is during > the module initialization. The first lines of Precision.py are: > > from multiarray import zeros > import string > [.....] and your program is crashing on the lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 line... Please, try the following: import multiarray from multiarray import zeros import string (adding the line "import multiarray" before zeros are imported from it) I used this workaround with various packages I py2exed - maybe it also works for you? please keep us updated, Harald From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 14 09:19:27 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Mar 2008 14:19:27 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: <47da7b1b$0$21083$426a74cc@news.free.fr> Mel a ?crit : (snip) > (What Diez said.) From what I've seen, f.bar creates a bound method > object by taking the unbound method Foo.bar and binding its first > parameter with f. Nope. it's Foo.__dict__['bar'] (that is, the function bar defined in the namespace of class Foo) that creates a bound instancemethod object when looked up on a Foo instance - or an unbound instancemethod object when looked up on Foo. FWIW, types.UnboundMethodType and types.MethodType are both aliases to instancemethod type. From fuzzyman at gmail.com Sun Mar 23 15:22:44 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 23 Mar 2008 12:22:44 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <5626884d-5ddb-4875-b938-cfdcd389af8e@s19g2000prg.googlegroups.com> On Mar 23, 4:24 pm, a... at pythoncraft.com (Aahz) wrote: > In article , > Jeff Schwab wrote: > > > > >Also, despite reassurances to the contrary, I still get the impression > >that there is a strong anti-lambda sentiment among the Python "in" > >crowd. Is it just a question of the word "lambda," as opposed to > >perceived cleaner syntax? > > The problem with lambda is that too often it results in clutter (this is > a strictly made-up example off the top of my head for illustrative > purposes rather than any real code, but I've seen plenty of code similar > at various times): > > gui.create_window(origin=(123,456), background=gui.WHITE, > foreground=gui.BLACK, callback=lambda x: x*2) > > That means I need to pause reading the create_window() arguments while I > figure out what the lambda means -- and often the lambda is more > complicated than that. Moreover, because the lambda is unnamed, it's > missing a reading cue for its purpose. I find lambdas invaluable very frequently - often to avoid the reading clutter. * Transforming function calls something.Event += lambda sender, event: real_handler() * Properties name = property(lambda self: self.__name, __set_name) * Very short functions where extra lines reduce readability if direction == 'left': transform = lambda x, y: -x else: transform = lambda x, y: x * Functions that take functions as arguments old_list = [(3,1), (2, 2), (1, 3)] new_list = sorted(old_list, key=lambda x: x[1]) new_data = process(data_Set, lambda x: x+1) new_data2 = process(data_Set, lambda x: x-1) I don't think any of these are unreadable or improved by defining a 'real' function. Michael http://www.ironpythoninaction.com > -- > Aahz (a... at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan From aahz at pythoncraft.com Thu Mar 13 16:20:25 2008 From: aahz at pythoncraft.com (Aahz) Date: 13 Mar 2008 13:20:25 -0700 Subject: Is there Python equivalent to Perl BEGIN{} block? References: <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> Message-ID: In article , Jeff Schwab wrote: > >I write maybe a dozen one-liners a day. It's not practical to do this >with Python, or at least it's not nearly as convenient as Perl. That is a defensible position, but my take is that writing the one-liners in Python is more convenient than remembering enough Perl to make writing one-liners useful. Especially when the one-liners often start expanding. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From paul.hankin at gmail.com Sun Mar 9 19:37:29 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 9 Mar 2008 16:37:29 -0700 (PDT) Subject: __iter__ yield References: Message-ID: On Mar 9, 8:58?pm, duccio wrote: > Someone knows if it's possible to make this __iter__ function with just ? > one 'yield' intead of two? > ... > ? ? ?def __iter__(self): > ? ? ? ? ?yield self #1 > ? ? ? ? ?for n in self.childs: > ? ? ? ? ? ? ?for nn in n.__iter__(): > ? ? ? ? ? ? ? ? ?yield nn #2 Only one yield and shorter (but not really any simpler): from itertools import chain class Node: ... def __iter__(self): for x in chain([self], *self.childs): yield x -- Paul Hankin From fetchinson at googlemail.com Mon Mar 3 21:22:24 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 3 Mar 2008 18:22:24 -0800 Subject: metaclasses In-Reply-To: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: > What are metaclasses? http://www.google.com/search?q=python+metaclass HTH, Daniel From castironpi at gmail.com Wed Mar 12 15:06:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 12:06:52 -0700 (PDT) Subject: tcp client socket bind problem References: <42925034-6cf7-40a7-b079-8f3bf978fea2@n36g2000hse.googlegroups.com> Message-ID: <701ef870-e305-49a4-8565-45e4ebdde244@e60g2000hsh.googlegroups.com> On Mar 11, 2:19?am, Tim Roberts wrote: > castiro... at gmail.com wrote: > > >On Mar 10, 9:40?am, Marc Christiansen wrote: > >> nata... at gmail.com wrote: > >> > I have a linux box with multiple ip addresses. I want to make my > >> > python client connect from one of the ip addresses. Here is my code, > >> > no matter what valid information I put in the bind it always comes > >> > from the default ip address on the server. Am I doing something wrong? > >... > > >help string: > >Bind the socket to a local address. ?For IP sockets, the address is a > >pair (host, port); the host must refer to the local host. > > >docs: > >Bind the socket to address. > > >Wikipedia: > >Before a socket may accept incoming connections, it must be bound. > > >PHP.net: > >Binds the name given in address to the socket described by socket . > >This has to be done before a connection is be established using > >socket_connect() or socket_listen(). > >This function must be used on the socket before socket_connect(). > > That's all true. ?So what was your point? ?How does this help the original > poster? Confidence-- a second opinion of what the docs say. Then, something of a criticism of the docs. From florian.harmuth at googlemail.com Mon Mar 17 14:11:53 2008 From: florian.harmuth at googlemail.com (mich1985) Date: Mon, 17 Mar 2008 11:11:53 -0700 (PDT) Subject: SAXReaderNotAvaiable after switching Python References: <0e990748-2e57-46ce-9a8e-2f0b89754d7c@z38g2000hsc.googlegroups.com> Message-ID: Hello all, i think that my problem is solved now. I haven't seen that the old package was recompiled from another guy. Best regards, flo On 17 Mrz., 13:12, mich1985 wrote: > Hello all, > after i have switched from python-2.4.2 to python-2.4.3 i get the > following message if run my web configuration: > > parser = xml.sax.make_parser() > ..... > SAXReaderNotAvailable: No parsers found > > The files under /usr/lib/python2.4/xml/sax are the same as before. Any > hints where i can start my search? (a ng search didn't solved my > problem). > > Best Regards, > flo From castironpi at gmail.com Fri Mar 21 02:48:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:48:07 -0700 (PDT) Subject: Is this valid ? References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> <13u5rgegehc8u04@corp.supernews.com> Message-ID: <33cabf0b-3dbb-4b30-aec0-317fce3ac16e@e60g2000hsh.googlegroups.com> On Mar 20, 6:06?pm, Steven D'Aprano wrote: > On Thu, 20 Mar 2008 15:09:08 +0100, Rolf van de Krol wrote: > > > John Machin wrote: > >> Of course. You can chain comparisons as much as you like and is > >> (semi-)sensible, e.g. > > > Hmm, 'of course' is not the correct word for it. > > Not at all. The Original Poster tried something, and it worked. There > were two alternatives: > > (1) Writing a == b == 2 is valid. > > (2) In the sixteen years that Python has been publicly available, with > tens of thousands or more developers using it, nobody had noticed that > Python had a bug in the compiler which incorrectly allowed a == b == 2 > until Stef Mientki came along and discovered it. > > Given those two alternatives, (2) would be very surprising indeed, and so > I think "of course" is well justified. > > That Python allows chaining comparisons this way isn't really surprising. > That's a very natural thing to do. What's surprising is that other > languages *don't* allow chaining comparisons, but force you to write the > inefficient and (sometimes) confusing "(a == 2) and (b == 2)" instead. You see a couple of occurrences in natural language-- I'm wondering where the majority of NL settles. >>> a is a is a True Do we do math on booleans on some level or in some contexts? Maybe a "with syntaxchangeA:" is in the future. From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 04:12:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 08:12:03 -0000 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: <13umlmj757pu172@corp.supernews.com> On Wed, 26 Mar 2008 00:27:17 -0700, Arnaud Delobelle wrote: >> I'm hardly surprised. The naivety of those who insist that the "best >> way to understand how new.function and new.code work" is to look at the >> C source code for object is amusing. > > Since 'those who insist...' are just one person, me, you might as well > name them. Firstly I didn't 'insist', I stated it once. Secondly I'm > glad that I provided you with a few chuckles, but to proclaim that one > is 'amused by the naivety of others' doesn't make one automatically > right. Your criticism is accepted. You're not the only person who says "Read the C source", so I wasn't pointing the finger at just you. > Do you know how these functions behave? Have you looked at their > documentation? new.function and new.code (implemented as Objects/ > funcobject.c:func_new and Objects/codeobject.c:new_code) are not really > documented (new.code.__doc__ is 'Create a code object. Not for the > faint of heart.'). If you can't read the source then I don't think you > should use the functions. *shrug* I don't know about that. People reverse-engineer programs without access to the source code all the time. Reading the source code may (but not always) make understanding the functions easier, but it's not compulsory. If I cared enough, the way I'd go about reverse-engineering the functions would be to start by pulling apart a Python function into a code object, then pulling apart the code object into its components, making small modifications to the components, then reversing the process (using new.code() and new.function()) to build up a function object I could call. Or I'd ask somebody who already knew how they worked to give an example or two of Python code that called new.code() and new.function(). It's not ideal, of course, in a perfect world whoever wrote new.code() would have written some better documentation, but it will do for non- production code. For production code that I relied on, I'd hire a C programmer to read the source and document it for me. *wink* -- Steven From http Thu Mar 13 06:42:05 2008 From: http (Paul Rubin) Date: 13 Mar 2008 03:42:05 -0700 Subject: List mutation method gotcha - How well known? References: Message-ID: <7x1w6enbwi.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > 4) Nothing - no output By Python convention, methods that mutate the object return None, and also stuff that returns None doesn't generate output at the interactive prompt. There is a similar situation with list.sort() which led to the introduction of the sorted() builtin. Lately I try to avoid mutation, e.g. by using a generator or listcomp instead of building up a list with .append() From sjmachin at lexicon.net Tue Mar 18 14:57:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Mar 2008 11:57:40 -0700 (PDT) Subject: Decode email subjects into unicode References: <47DF8EED.1010501@shopzeus.com> Message-ID: <594fef10-a8e3-4b48-b636-ba06fb8a317a@e23g2000prf.googlegroups.com> On Mar 18, 9:09 pm, Laszlo Nagy wrote: > Sorry, meanwhile i found that "email.Headers.decode_header" can be used > to convert the subject into unicode: > > > def decode_header(self,headervalue): > > val,encoding = decode_header(headervalue)[0] > > if encoding: > > return val.decode(encoding) > > else: > > return val > > However, there are malformed emails and I have to put them into the > database. What should I do with this: > > Return-Path: > X-Original-To: i... at designasign.biz > Delivered-To: dapi... at localhost.com > Received: from 195.228.74.135 (unknown [122.46.173.89]) > by shopzeus.com (Postfix) with SMTP id F1C071DD438; > Tue, 18 Mar 2008 05:43:27 -0400 (EDT) > Date: Tue, 18 Mar 2008 12:43:45 +0200 > Message-ID: <60285728.00719565 at optometrist.com> > From: "Euro Dice Casino" > To: tho... at designasign.biz > Subject: With 2'500 Euro of Welcome Bonus you can't miss the chance! > MIME-Version: 1.0 > Content-Type: text/html; charset=iso-8859-1 > Content-Transfer-Encoding: 7bit > > There is no encoding given in the subject but it contains 0x92. When I > try to insert this into the database, I get: > > ProgrammingError: invalid byte sequence for encoding "UTF8": 0x92 > > All right, this probably was a spam email and I should simply discard > it. Probably the spammer used this special character in order to prevent > mail filters detecting "can't" and "2500". But I guess there will be > other important (ham) emails with bad encodings. How should I handle this? Maybe with some heuristics about the types of mistakes made by do-it- yourself e-mail header constructors. For example, 'iso-8859-1' often should be construed as 'cp1252': >>> import unicodedata as ucd >>> ucd.name('\x92'.decode('iso-8859-1')) Traceback (most recent call last): File "", line 1, in ValueError: no such name >>> ucd.name('\x92'.decode('cp1252')) 'RIGHT SINGLE QUOTATION MARK' >>> From sleddd at gmail.com Thu Mar 13 13:18:44 2008 From: sleddd at gmail.com (sleddd at gmail.com) Date: Thu, 13 Mar 2008 10:18:44 -0700 (PDT) Subject: Socket Performance References: Message-ID: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> On Mar 13, 9:33 am, "Brian Smith" wrote: > sle... at gmail.com wrote: > > Sent: Wednesday, March 12, 2008 9:47 PM > > To: python-l... at python.org > > Subject: Socket Performance > > > Can anyone explain why socket performance (throughput) varies > > depending on the amount of data send and recv are called with? > > > For example: try creating a local client/server (running on the same > > computer) where the server sends the client a fixed amount of data. > > Using method A, recv(8192) and sendall( ) with 8192 bytes > > worth of data. Do this 100 times. Using method B, recv(1) and > > sendall( ) with 1 byte worth of data. Do this 819200 times. > > > If you time both methods, method A has much greater > > throughput than method B. > > Why is it faster to drink a liter of water a cupful at a time than to > drink it out of an eyedropper? > > - Brian Well, lets say you have a situation where you're going to be alternating between sending large and small chunks of data. Is the solution to create a NetworkBuffer class and only call send when the buffer is full, always recv(8192)? From saluk64007 at gmail.com Fri Mar 28 01:16:24 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Thu, 27 Mar 2008 22:16:24 -0700 Subject: [Twisted-web] [ANN] Twisted 8.0 In-Reply-To: <20080328031502.GA22852@mithrandi.net> References: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> <20080328031502.GA22852@mithrandi.net> Message-ID: It's dangerously close to april fools for this kind of posting! Congrats on the release, it looks mighty impressive. From adonis_vargas at -Remove-This-bellsouth.net Wed Mar 12 00:45:32 2008 From: adonis_vargas at -Remove-This-bellsouth.net (Adonis Vargas) Date: Wed, 12 Mar 2008 00:45:32 -0400 Subject: Why no string return? In-Reply-To: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: gargonx wrote: > Say i have the two methods: > > def ReturnMethod(request, x): > if request is True: > return x > else: print "No String for you...False!" > > def SendMethod(request): > xstring = "Some text" > ReturnMethod(request, xstring) > > SendMethod(True) > > Why does ReturnMethod not return the string x? I do believe it is > returning with a NoneType. > Any help would be greatly obliged > > Thanks, Josh That is because request is bound a string (str) object. You are probably testing for null so it should look like: if request: return x else: print "No String for you...False!" Hope this helps. Adonis From tjreedy at udel.edu Mon Mar 17 15:26:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Mar 2008 15:26:24 -0400 Subject: Python 3 and PEP238 division References: Message-ID: "Ninereeds" wrote in message news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... | Is the PEP238 change to division going into Python 3 as planned? IDLE 3.0a3 >>> 1/2 0.5 | I realise that the new integer division semantics have been available | in "from __future__" for quite a few years now, but a warning might be | appropriate now that Python 3 is in alpha. 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion program From tmp1 at viltersten.com Tue Mar 4 23:26:02 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Wed, 5 Mar 2008 05:26:02 +0100 Subject: SV: SV: Polymorphism using constructors In-Reply-To: References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: <636ko9F24kphrU1@mid.individual.net> > What does "SV" in the subject mean? Probably, it's an abbreviation of "svar", which means "reply". -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From frank at niessink.com Mon Mar 24 13:00:40 2008 From: frank at niessink.com (Frank Niessink) Date: Mon, 24 Mar 2008 18:00:40 +0100 Subject: Problems with wxPython In-Reply-To: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> References: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> Message-ID: <67dd1f930803241000tbce352fp93bf2df6e1d082b1@mail.gmail.com> Hi David, 2008/3/24, David Anderson : > Hi, If ther's anyone who knows pretty much about wxPython can e-mail me? I'm > having some trouble in dealing with some guis here, I would thank u very > much if you could help me You should subscribe to the wxPython users mailinglist and ask there. It's a very helpful mailinglist. Robin Dunn (wxPython author) is very active in answering questions from wxPython users. See http://www.wxpython.org/maillist.php Cheers, Frank From sjmachin at lexicon.net Fri Mar 7 20:09:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 17:09:37 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <7xmypa844v.fsf@ruckus.brouhaha.com> Message-ID: On Mar 8, 11:13 am, Paul Rubin wrote: > Pierre Quentel writes: > > I would like to know if there is a module that converts a string to a > > value of the "most probable type" > > Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > >>> import this > The Zen of Python, by Tim Peters > ... > In the face of ambiguity, refuse the temptation to guess. Reminds me of the story about the avionics software for a fighter plane which when faced with the situation of being exactly upside-down refused to guess whether it should initiate a left roll or a right roll :-) From ericgorr at gmail.com Wed Mar 19 11:32:36 2008 From: ericgorr at gmail.com (Eric) Date: Wed, 19 Mar 2008 08:32:36 -0700 (PDT) Subject: SOAP Server in Python References: <50ccc1be-87ac-4847-b21d-7dfd46379ea4@z38g2000hsc.googlegroups.com> Message-ID: <2914eaa7-ee98-4c50-98ae-00fe647fb990@8g2000hsu.googlegroups.com> On Mar 19, 10:59 am, dave_mikes... at fastmail.fm wrote: > On Mar 19, 9:19 am, Eric wrote: > > > I am basically looking to do the same thing in Python as easily. > > > Any help or pointers would be appreciated. > > Googling for "python soap" turned up a few hits that may help you. Yes, but I don't have the knowledge to accurately or effectively evaluate the information. I was hoping someone here had some experience writing a SOAP Server using Python and would be willing to share what they know. From fakeaddress at nowhere.org Fri Mar 21 04:55:19 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 21 Mar 2008 01:55:19 -0700 Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: Benjamin Watine wrote: > bryanjugglercryptographer at yahoo.com a ?crit : >> I wrote: >>> And here's a thread example, based on Benjamin's code: >> [...] >> >> Doh! Race condition. Make that: >> >> import subprocess >> import thread >> import Queue >> >> def readtoq(pipe, q): >> q.put(pipe.read()) >> >> cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, >> stdout=subprocess.PIPE) >> >> myVar = str(range(1000000)) # arbitrary test data. >> >> q = Queue.Queue() >> thread.start_new_thread(readtoq, (cat.stdout, q)) >> cat.stdin.write(myVar) >> cat.stdin.close() >> cat.wait() >> myNewVar = q.get() >> >> assert myNewVar == myVar >> print len(myNewVar), "bytes piped around." > > Great, it works, thank you Bryan ! > > Could you explain me why you use a queue instead of a simple array for > getting the piped var ? The call to q.get() will block until an item is in the queue. At that point in the program, we had already waited for cat to terminate: cat.wait() myNewVar = q.get() But passing cat.wait() does not imply that our own thread has already read all of cat's output and put it in some destination object. Data could still be in transit. My first version, subsequently titled, "Doh! Race condition," worked in all of several runs of its built-in test. Doesn't make it right. -- --Bryan From castironpi at gmail.com Sun Mar 9 17:16:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:16:58 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> Message-ID: <2b098afa-2dcc-4bde-bdde-02eece46fd68@47g2000hsb.googlegroups.com> On Mar 9, 4:25?am, Lie wrote: > On Mar 9, 3:27?am, castiro... at gmail.com wrote: > > > To Lie: > > > > Personally I preferred a code that has chosen good names but have > > > little or no comments compared to codes that makes bad names and have > > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > > I won't like it, it's that I can't. ?You know, in linguistics, there's > > But I much prefer it that the code has good names AND concise > comments, not too short and not too long that it becomes obscure. What do you mean? If 'obscure' is the right word, then it's subjective (from metrics import obscurity?), which means that 10% of the people disagree with you, or 90% do. The end-all be-all, there is no such thing. I don't think it's obscure; I do. Is it? From jeffrey at fro.man Thu Mar 20 13:24:52 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 20 Mar 2008 10:24:52 -0700 Subject: Import a file to namespace References: <0cdb3c90-e961-4982-9996-de3ac02706bc@13g2000hsb.googlegroups.com> Message-ID: <13u57f51c3ee82e@corp.supernews.com> Pedro Machado Santa wrote: > import testpackage > > class testClass(): > #... > > testpackage.testClass = ?testClass This method should work fine. Modules are effectively singletons, so running this code one time anywhere in your application will cause the changes to appear in all references to the original module. Jeffrey From fakeaddress at nowhere.org Sun Mar 16 21:29:30 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 16 Mar 2008 18:29:30 -0700 Subject: Convert int to float In-Reply-To: References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <1QjDj.4087$qS5.2590@nlpi069.nbdc.sbc.com> sturlamolden wrote: > Guido van Brakel wrote: > >>> def gem(a): >>> g = sum(a) / len(a) >>> return g > >> It now gives a int, but i would like to see floats. How can integrate >> that into the function? > > You get an int because you are doing integer division. Cast one int to > float. > > def gem(a): > g = sum(a) / float(len(a)) > return g An alternative is to multiply by 1.0. def gem(a): g = 1.0 * sum(a) / len(a) return g The gem function is well-defined on sequences of complex numbers, in which case the float() method will raise a TypeError, while the 1.0* method will return the complex result. It may not be what van Brakel wants here, but it's an alternative to keep in mind. And I find it easier to type. -- --Bryan From danb_83 at yahoo.com Mon Mar 31 21:56:07 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 31 Mar 2008 18:56:07 -0700 (PDT) Subject: Question about overloading of binary operators References: Message-ID: <6274a417-2e26-493e-b083-07ea9903bcdb@b5g2000pri.googlegroups.com> On Mar 31, 5:03 pm, gigs wrote: > Raj Bandyopadhyay wrote: > > Hi > > > Here's a simple class example I've defined > > > ############################# > > class myInt(int): > > def __add__(self,other): > > return 0 > > > print 5 + myInt(4) #prints 9 > > print myInt(4) + 5 #prints 0 > > ############################# > > > The Python binary operation function (binary_op1() in > > Objects/abstract.c) states > > the rules for binary operations as follows: > > > v w Action > > ------------------------------------------------------------------- > > new new w.op(v,w)[*], v.op(v,w), w.op(v,w) > > new old v.op(v,w), coerce(v,w), v.op(v,w) > > old new w.op(v,w), coerce(v,w), v.op(v,w) > > old old coerce(v,w), v.op(v,w) > > > [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of > > v->ob_type > > > It seems that my example should fall in case 1, and in both cases, the > > __add__ function of the subclass should be used, returning 0, regardless > > of operand order. However, in one case the subclass's function is used > > and not in the other case. What am I missing here? > > > Thanks > > Raj > > i think that you need to use __radd__ for addition with custom object on right Right. Python doesn't make any assumptions that addition is commutative. But if it is for your class, you can just write __radd__ = __add__ From has.temp3 at virgin.net Sat Mar 15 14:48:17 2008 From: has.temp3 at virgin.net (has) Date: Sat, 15 Mar 2008 11:48:17 -0700 (PDT) Subject: Getting started with OS X Leopard References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> Message-ID: On 15 Mar, 18:05, Mark Carter wrote: > The sorts of things I want to do are: > * copy the directory of Finder to the clipboard > * add a new file to Finder's directory. > * find out the size of a directory > * open a file with Aquamacs, regardless of file type, If you want to control desktop applications directly, that generally means using Apple event IPC. The most popular language for application scripting is traditionally AppleScript, but Apple event bridges exist for other languages as well. The best of these is appscript; see my sig for links. Some Finder scripting examples: #!/usr/bin/python from appscript import * from osax import * finder = app('Finder') standardadditions = ScriptingAddition() folderref = finder.Finder_windows[1].target # set clipboard to path to front window's folder path = folderref.get(resulttype=k.alias).path standardadditions.set_the_clipboard_to(path) # make new empty file in front window's folder finder.make(new=k.file, at=folderref.get()) # get size of front window's folder # (note: this may return k.missing_value when first run # as Finder is sluggish at calculating folder sizes) print folderref.size.get() # open selected items in TextEdit selecteditems = finder.selection.get() finder.open(selecteditems, using=app.application_files.ID('com.apple.textedit')) HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From sivakumar433 at gmail.com Fri Mar 28 05:44:13 2008 From: sivakumar433 at gmail.com (sivakumar433 at gmail.com) Date: Fri, 28 Mar 2008 02:44:13 -0700 (PDT) Subject: ************************************************************** Message-ID: <151380e3-5e2c-4bd0-bca0-bcbb555cffac@d4g2000prg.googlegroups.com> ************************************************************** When you make a Web page available offline, you can read its content when your computer is not connected to the Internet. For example, you can view Web pages on your laptop computer when you don't have a network or Internet connection. Or you can read Web pages at home without tying up a phone line. You can specify how much content you want available, such as just a page, or a page and all its links, and choose how you want to update that content on your computer. If you just want to view a Web page offline, and you don't need to update the content, you can save the page on your computer. There are several ways you can save the Web page, from just saving the text to saving all of the images and text needed to display that page as it appears on the Web. *************************************************************** http:\\my profile6529.blogspot.com From termim at gmail.com Fri Mar 28 13:01:25 2008 From: termim at gmail.com (Mike) Date: Fri, 28 Mar 2008 10:01:25 -0700 (PDT) Subject: How do I reconnect a disconnected socket? References: Message-ID: <5caf589a-95ca-4ba0-9e74-7dfd11ab1ebc@e67g2000hsa.googlegroups.com> On Mar 28, 10:01 am, Jason Kristoff wrote: > I'm trying to make something that once it is disconnected will > automatically try to reconnect. I'll add some more features in later so > it doesn't hammer the server but right now I just want to keep it simple > and get that part working. The problem is that when I use sock.close I > get an error message of > Bad File Descriptor > and if I either use shutdown or just go straight to reconnecting I get: > Transport endpoint is already connected > > This is what I've got right now: > > #! /usr/bin/env python > import socket, string > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > def doconn(): > sock.connect(("localhost", 1234)) > def dodiscon(): > sock.close() > doconn() > > doconn() > > while (1): > buffer = sock.recv(1024) > if not buffer: > dodiscon() I'd recommend to look at Twisted ReconnectingClientFactory - http://twistedmatrix.com/trac/browser/trunk/twisted/internet/protocol.py#L198 From pjdelport at gmail.com Fri Mar 28 15:14:37 2008 From: pjdelport at gmail.com (Piet Delport) Date: Fri, 28 Mar 2008 12:14:37 -0700 (PDT) Subject: Advantage of the array module over lists? References: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> <645q0hF28fnk3U1@mid.uni-berlin.de> Message-ID: <014ff679-c16e-4d13-b980-fa1816bd584d@h11g2000prf.googlegroups.com> On Mar 17, 1:49 am, "Diez B. Roggisch" wrote: > > I doubt that. AFAIK both arrays and lists are continuous memory-areas, > that double (at least to a certain threshold or so) when reaching the > capacity limit. For what it's worth, lists over-allocate by ~1/8, and arrays by ~1/16. (Details in listobject.c:list_resize and arraymodule.c:array_resize.) From elampooranan at gmail.com Sun Mar 9 19:41:59 2008 From: elampooranan at gmail.com (Roopan) Date: Sun, 9 Mar 2008 16:41:59 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? Message-ID: Hello! I am looking at developing an enterprise-grade distributed data sharing application - key requirements are productivity and platform portability. Will it be sensible to use C++ for performance-critical sections and Python for all the glue logic. Pls comment from your *experiences* how Python scales to large projects( > 200KLOC). I assume the C++/Python binding is fairly painless. Regards Elam. From tjreedy at udel.edu Mon Mar 3 23:24:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 3 Mar 2008 23:24:30 -0500 Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au><996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: "Tim Roberts" wrote in message news:ir5ns3purngj4kt4ndpptqnqm5pj628qbj at 4ax.com... | Kay Schluehr wrote: | >"The master said so" isn't an entirely satisfying answer. | | Nevertheless, it IS the answer for many questions in the Python world. But not for the questions about 2to3 Current 2to3 is written in Py2.5 and will require the 2.5 interpreter until 2.6 is sufficiently stable to run it. Whether it will later use 2.6 features or not I do not know. I believe that pre-2.6 code will be directly upgradable if A. it does not depend on bugs that are fixed by 2.6, so that it is also 2.6 code; B. one is willing to do the upgrade more or less 'all at once', (while the code is frozen); C. one is willing to do *one* of the following: C1. keep the 2.x code frozen, or C2. redo the upgrade more or less 'from scratch' after base code edits, or C3. maintain the 2.x code and 3.0 code in parallel These are facts of programming life, not BDFL edicts. But many will prefer an incremental approach. Py 2.6 will ease this by 1) optionally issuing upgrade warnings, and 2) incorporating many new 3.0 features that do not conflict with 2.x features. tjr From george.sakkis at gmail.com Mon Mar 31 22:27:56 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 19:27:56 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> Message-ID: <80d1731d-a3c6-4fce-81fd-9c3f3537e59b@d21g2000prf.googlegroups.com> On Mar 31, 8:51 pm, castiro... at gmail.com wrote: > On Mar 31, 7:14 pm, 7stud wrote: > > > > > On Mar 31, 5:31 pm, castiro... at gmail.com wrote: > > > > Can you have a Python object stored entirely on disk? > > > import cPickle as cp > > > class Dog(object): > > def __init__(self, name): > > self.name = name > > > d = Dog("Spot") > > > f = open("data.txt", "w") > > cp.dump(d, f) > > f.close() > > > f = open("data.txt") > > stored_obj = cp.load(f) > > print stored_obj.name > > > --output:-- > > Spot > >>> import pickle > >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) > > Traceback (most recent call last): > File "", line 1, in > File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps > Pickler(f, protocol).dump(obj) > File "C:\Programs\Python\lib\pickle.py", line 221, in dump > self.save(obj) > File "C:\Programs\Python\lib\pickle.py", line 283, in save > f(self, obj) # Call unbound method with explicit self > File "C:\Programs\Python\lib\pickle.py", line 697, in save_global > (obj, module, name)) > pickle.PicklingError: Can't pickle : it's not > found as __ > main__.None > > http://docs.python.org/lib/node317.html From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:34:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:34:48 -0300 Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> Message-ID: En Tue, 25 Mar 2008 07:44:59 -0300, john s. escribi?: >> for line in open("/etc/passwd"): >> user, _pwd = line.split(":") > ^----- Ok this one here we are taking a string spliting it > into to variables... > user gets one (the first) and _pwd gets to hold the > "leftovers"? No; if the line contains more than a single : that code will fail. user, remainder = line.split(":", 1) With Python 3.0 you could write: user, _pwd, *other = line.split(":") but limiting the number of splits is more efficient if you are not interested in the remaining list. A more interesting case is: a, b, *other, c = line.split(":") to obtain the first, second and last items. -- Gabriel Genellina From lipun4u at gmail.com Tue Mar 11 11:24:54 2008 From: lipun4u at gmail.com (asit) Date: Tue, 11 Mar 2008 08:24:54 -0700 (PDT) Subject: mulithreaded server Message-ID: <7c555afb-2df0-43f2-aa16-d1e48da1510a@e23g2000prf.googlegroups.com> import socket import sys import thread p=1 PORT=11000 BUFSIZE=1024 def getData(cSocket): global stdoutlock,cSocketlock while True: cSocketlock.acquire() data=cSocket.recv(BUFSIZE) if data=='q': data='client exited' cSocket.close() p=0 cSocketlock.release() stdoutlock.acquire() stdout.write(data) stdoutlock.release() def sendData(cSocket): global stdoutlock,cSocketlock while True: stdoutlock.acquire() data=raw_input('>>') cSocketlock.acquire_lock() if data=='q': stdout.write('server exited') stdout.release() p=0 cSocket.close() sSocket.send(data) sSocketlock.release() stdout=sys.stdout host='' sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sSocket.bind((host,PORT,)) sSocket.listen(1) #sSocketlock=thread.allocate_lock() stdoutlock=thread.allocate_lock() print 'waiting for connection' cSocket,addr=sSocket.accept() print 'connection from',addr cSocketlock=thread.allocate_lock() thread.start_new_thread(sendData,(cSocket,)) thread.start_new_thread(getData,(cSocket,)) if p==0: sSocket.close() In the above program, why there is an unhandeled exception ??? From paul.hankin at gmail.com Tue Mar 11 06:37:53 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 11 Mar 2008 03:37:53 -0700 (PDT) Subject: rmdir problem References: Message-ID: On Mar 11, 10:35 am, royG wrote: > i am checking if a directory exists and if it does i want to delete it > and its contents.then i want to create the directory before creating > files in it. Have a look at shutil.rmtree -- Paul Hankin From rakesh.usenet at gmail.com Sat Mar 1 17:40:18 2008 From: rakesh.usenet at gmail.com (Rakesh Kumar) Date: Sat, 1 Mar 2008 14:40:18 -0800 (PST) Subject: cx_Freeze : LookupError: unknown encoding: ascii Message-ID: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> Hi - I created a binary using the cx_Freeze utility on Linux (wxWidgets 2.8 / Python 2.5/ Mandriva 2008 ). When I tried to run the binary - this is the error that I got on the console. File "gdataapi.py", line 44, in __init__ self.service.ProgrammaticLogin() File "/opt/software/gdata-py/src/gdata/service.py", line 284, in ProgrammaticLogin auth_connection.putrequest('POST', '/accounts/ClientLogin') File "/usr/lib/python2.5/httplib.py", line 806, in putrequest host_enc = self.host.encode("ascii") LookupError: unknown encoding: ascii Can somebody point to some clues about options that need to be passed to FreezePython API to get the right executable. Thanks for the help. From bharathv6.project at gmail.com Sun Mar 23 16:23:33 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Mon, 24 Mar 2008 01:53:33 +0530 Subject: writing a message to the terminal in a daemon process Message-ID: <2613171a0803231323y501c76fbxf72aa7a86fe99446@mail.gmail.com> hi, i created a daemon process using the following code import os import sys # Default daemon parameters. # File mode creation mask of the daemon. UMASK = 0 # Default working directory for the daemon. WORKDIR = "/" # Default maximum for the number of available file descriptors. MAXFD = 1024 # The standard I/O file descriptors are redirected to /dev/null by default. if (hasattr(os, "devnull")): REDIRECT_TO = os.devnull else: REDIRECT_TO = "/dev/null" def goDaemon(): try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The first child. os.setsid() try: pid = os.fork() # Fork a second child. except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The second child. #os.chdir(WORKDIR) os.umask(UMASK) else: os._exit(0) else: os._exit(0) # Exit parent of the first child. import resource maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if (maxfd == resource.RLIM_INFINITY): maxfd = MAXFD for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass os.open(REDIRECT_TO, os.O_RDWR) # standard input (0) os.dup2(0, 1) # standard output (1) os.dup2(0, 2) # standard error (2) return(0) it can be seen that the standard output and standard error are redirected to null terminal now after the process is made daemon i.e after closing all the resources and redirecting the standard output and standard error to null terminal now I want to print some initial msg on the console(terminal) in which the program was started . *NOTE*:I realize that initial msg can be printed before closing all the resources and redirecting the standard output and standard error to null terminal but it necessary to print the msg after the process is made daemon i.e when the process actually starts doing some processing. I tried with following code: fd=os.open("/dev/tty",os.O_WRONLY) os.write(fd,msg) os.close(fd) but this worked fine before closing all the resources and redirecting the standard output and standard error to null terminal and after doing all these even it didn't help it didn't print any thing on the terminal pls can anyone how this can be done -------------- next part -------------- An HTML attachment was scrubbed... URL: From bijeshn at gmail.com Thu Mar 13 02:21:19 2008 From: bijeshn at gmail.com (bijeshn at gmail.com) Date: Wed, 12 Mar 2008 23:21:19 -0700 (PDT) Subject: copying all data(tags and values) after a particular XML tag Message-ID: <9c8740c5-7dfa-4007-a530-c28d4b31a20d@u10g2000prn.googlegroups.com> i've an XML file with the following structure.... . . . . . what i want to do is copy all data(tags and all) between N and N+k appearances of . I am a python newbie. How do I do it? Thanks. From bockman at virgilio.it Tue Mar 25 03:49:31 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 25 Mar 2008 07:49:31 GMT Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: <47e8ae8a$0$21201$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 15:05:38 -0700, Julien ha scritto: ... > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making up > the term) a function: > > def hijacker(arg): > if I_feel_its_necessary: > hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > hijacker(something) > ... # Continue as normal > return 2 > > def my_function2(arg): > ... # Maybe do some processing here > hijacker(whatever) > ... # Continue as normal > return 3 > > > You could simply do something like: def hijacker(arg): if I_feel_its_necessary: return True, 1 else: return False, 0 def my_function1(arg): abort, code = hijiacker(something); if abort: return code ... # Continue as normal return 2 def my_function2(arg): ... # Maybe do some processing here abort, code = hijiacker(whatever); if abort: return code ... # Continue as normal return 3 Although purists may frown upon the double return statement, it is still a much cleaner code than using some magic to abort the caller function. And tou have only to add two lines - always the same - at each function. Ciao ----- FB From tjreedy at udel.edu Tue Mar 18 22:16:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:16:56 -0400 Subject: Python 3 and PEP238 division References: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> Message-ID: "Ninereeds" wrote in message news:3b9c9176-101f-4c72-8a56-82d16aea48d5 at k13g2000hse.googlegroups.com... | On Mar 17, 7:26 pm, "Terry Reedy" wrote: | > "Ninereeds" wrote in message | > | > news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... | > | Is the PEP238 change to division going into Python 3 as planned? | > | > IDLE 3.0a3>>> 1/2 | > | > 0.5 | > | > | I realise that the new integer division semantics have been available | > | in "from __future__" for quite a few years now, but a warning might be | > | appropriate now that Python 3 is in alpha. | > | > 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion | > program | | The tools can work out the *intent* of any particular division | operator? Can work out whether the result should be integer or float, | independent of any particular set of arguments? Seems unlikely. For the case of int division, one should have started using 1//2 already for floor division. Before running 2to3, a program should pass all tests with 'from __future__ import division', so that a/b definitely means fractions division even for int/int. Then the only thing 2to3 has to do in this regard is delete the future import. From grante at visi.com Mon Mar 31 14:56:27 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 31 Mar 2008 13:56:27 -0500 Subject: troll poll References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> <199c5242-f561-4c51-a96b-428abe6f9d80@f63g2000hsf.googlegroups.com> Message-ID: On 2008-03-31, Carl Banks wrote: > On Mar 31, 1:41 pm, Paul Rubin wrote: >> "Daniel Fetchinson" writes: >> > [ ] - Xah Lee >> > [ ] - castironpi >> >> I've lost track but has it been established that they are not the same >> person? > > Has it been established that castironpi is a person at all? I think he is at least some of the time. Some of his posts look like they're generated by an undergrad AI class project, but there are also posts that seems to be written by a real person who's overly fond of metaphors. -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.com ATLANTA, Georgia!! From guillermo.listas at googlemail.com Thu Mar 6 12:17:31 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Thu, 6 Mar 2008 09:17:31 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: > You can also get the dynamic polymorphism without invoking inheritance > by specifying a protocol that the values in your dict must implement, > instead. Protocols are plentiful in Python, perhaps more popular than > type hierarchies. I'm used to languages with stricter rules than Python. I've read a bit about Python protocols, but where could I get some more info on implementation details? Sounds very interesting. Regards, Guillermo From bj_666 at gmx.net Mon Mar 3 06:41:32 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Mar 2008 11:41:32 GMT Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <6326fcF25g4d2U4@mid.uni-berlin.de> On Mon, 03 Mar 2008 12:17:39 +0100, M.-A. Lemburg wrote: > It's also possible to implement .__getitem__() and .__len__() > methods and have Python create an iterator on-the-fly. That's > how Python used to work before iterators were added to the > language. A suitable `__getitem__()` is enough. The end will be signaled by an `IndexError`. Ciao, Marc 'BlackJack' Rintsch From bjourne at gmail.com Wed Mar 19 06:17:18 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 19 Mar 2008 11:17:18 +0100 Subject: Interesting math problem In-Reply-To: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> References: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> Message-ID: <740c3aec0803190317u76d4233y1524906aab1e36da@mail.gmail.com> On Mon, Mar 17, 2008 at 11:57 PM, Arnaud Delobelle wrote: > > def make_slope(distance, parts): > > step = distance / float(parts) > > intstep = int(step) > > floatstep = step - intstep > > > > steps = [] > > acc = 0.0 > > for i in range(parts): > > acc += floatstep > > step = intstep > > if acc > 0.999: > > step += 1 > > acc -= 1.0 > > steps.append(step) > > return steps > > OK then, using list comprehensions. It is more succint, is it easier > to read? > > def slope(dist, parts): > return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)] Congratulations! You Won! Jeff Schwab's recursive approach is also cool but this is the most interesting abuse of integer division I have seen. I don't think any of the variants are readable at a first glance, but with a comment it should be ok. -- mvh Bj?rn From kmacphail at gmail.com Mon Mar 17 01:24:53 2008 From: kmacphail at gmail.com (Kevin MacPhail) Date: Sun, 16 Mar 2008 23:24:53 -0600 Subject: Python and 3D In-Reply-To: References: Message-ID: <9766d5b90803162224n7c613268k601a25bd7a7af6dc@mail.gmail.com> On Sat, Mar 15, 2008 at 2:09 PM, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs > > Any help much appreciated > > Eric > -- > http://mail.python.org/mailman/listinfo/python-list > Cgkit might be what you're looking for: http://cgkit.sourceforge.net/ -Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Wed Mar 12 10:33:05 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 12 Mar 2008 09:33:05 -0500 Subject: List Combinations In-Reply-To: References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: <47D7E9A1.7000403@ncee.net> Michael Wieher wrote: > > > 2008/3/12, Gerdus van Zyl >: > > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus > > -- > > > list = [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > newList = [] > for l in list: > newList.extend(l) > > #newList = [3,9,1,5,4,2,5,8] > list=[] > for l in newList: > if l not in list: > list.append(l) > > #now list is [3,9,1,5,4,2,8] > > list.sort() > > #now your list is in sorted order > > Then, you can just write a series of for loops to spin off your data > however you like. > > def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') a,b,c = [1,2,3],[4,5,6],[7,8,9] print gen([a, b, c]) -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From MartinRinehart at gmail.com Thu Mar 27 14:29:01 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 11:29:01 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: bearophileH... at lycos.com wrote: > menudef = """ > File > New, callNew, Ctrl-N > New Window, callNewWindow, Ctrl-Shift-N > __ > Open, lambda e=0:para(1), Ctrl-O Nice design. I looked at it for a few seconds and didn't even think about pressing F1. Mine does less. But you tell it less to do it. Is there no way to get underscore/ keyboard access for the main menu items? From theller at ctypes.org Mon Mar 17 07:58:18 2008 From: theller at ctypes.org (Thomas Heller) Date: Mon, 17 Mar 2008 12:58:18 +0100 Subject: comtypes question In-Reply-To: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> References: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> Message-ID: Jorgen Bodde schrieb: > Hi All, > > I am trying to automate a 3rd party application, and all I have to > work on is the type library and some documentation. I hope a Python / > COM guru can answer this or put me on the right path because I don't > know why it does not work. > > First I imported the typelib with comtypes like; > >>> from comtypes.client import GetModule >>> GetModule("C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe") > > Which blurbs out a lot of text: > > # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1 > # Generating comtypes.gen.BarTender > 'C:\Python24\lib\site-packages\comtypes\gen\_D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1.pyc'> > > Which seems to be ok. Now, I need to call a function on the > Application object on which I need a "Messages" instance. The > Application object gets created properly: > >>> import comtypes.gen.Bartender as bt >>> app = comtypes.client.CreateObject(bt.Application) > > Which gives me the application (the bt.Application points to a wrapper > class containing the CLSID of the COM class to be instantiated). > > Now I browse the typelibrary and I see there is a CoClass called > Messages. I need one of those to pass as an argument, and since > Messages is listed as a CoClass similar to Application, I assume it > can also be instantiated. But when I try this I get an error: > >>>> msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}') [...] > WindowsError: [Errno -2147221164] Class not registered > > Both Application and Messages are listed as CoClass inside the > typelibrary. Does anybody know why it gives me this error and what I > am doing wrong? Not all coclasses can be created from scratch with CreateObject. Sometimes they are created by calls to methods on some other object. I downloaded the bartender trial, and looking into the typelib it seems that, for example, the 'XMLScript' method on the IBtApplication interface returns Messages instances: COMMETHOD([dispid(17), helpstring(u'Runs xml scripts')], HRESULT, 'XMLScript', ( ['in'], BSTR, 'XMLScript' ), ( ['in'], BtXMLSourceType, 'SourceType' ), ( ['out'], POINTER(POINTER(Messages)), 'Messages' ), ^^^^^^^^ ( ['retval', 'out'], POINTER(BSTR), 'retval' )), Here is an interactive session: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from comtypes.gen import BarTender >>> from comtypes.client import CreateObject >>> app = CreateObject(BarTender.Application) >>> print app >>> app.XMLScript("foo", 0) (, u'') >>> msg, retval = app.XMLScript("foo", 0) >>> print msg >>> msg[0] Traceback (most recent call last): File "", line 1, in File "comtypes\__init__.py", line 308, in __getitem__ result = self.Item(index) _ctypes.COMError: (-2147220992, None, (u'The item at position 0 was not found.', u'bartend', None, 0, None)) >>> msg[1] >>> m = msg[1] >>> print m >>> m.Number 3908 >>> m.Message u"An error occurred during XML script processing:\r\n\r\nInvalid at the top level of the document.\r\nLine 1, Column 1: 'foo'" >>> ^Z Not that the above makes much sense, but I hope it will get you started. Thomas BTW: The 'official' comtypes mailing list is at https://lists.sourceforge.net/lists/listinfo/comtypes-users. Requires that you subscribe before you can post, but you could disable mail delivery and use via gmane: gmane.comp.python.comtypes.user From __peter__ at web.de Thu Mar 6 03:13:52 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Mar 2008 09:13:52 +0100 Subject: Short confusing example with unicode, print, and __str__ References: <47CEDF77.5050501@andrew.cmu.edu> <47CEEBFC.9010001@islandtraining.com> Message-ID: Gerard Brunick wrote: > It seems the question is more about what does print do. ?Lets extend > your example: > > >>> d=unicode("Caf\xe9", "Latin-1") > >>> repr(d) > "u'Caf\\xe9'" > >>> print d > Caf? > >>> str(d) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > > Why doesn't the print statement that a UnicodeEncodeError? ?I assumed > that print calls str and then prints > the result, but this doesn't seem to be the case. ?What the heck does > print do? Something like d = ... if type(d) is unicode: sys.stdout.write(d.encode(sys.stdout.encoding)) else: sys.stdout.write(str(d)) Unfortunately you can't make that work smoothly with arbitrary objects as you have to throw in an explicit conversion to unicode: >>> class C(object): ... def __unicode__(self): return u"Caf\xe9" ... >>> print C() <__main__.C object at 0x2b1da33e0bd0> >>> print unicode(C()) Caf? Or, even less intuitive: >>> class D(object): ... def __str__(self): return u"Caf\xe9" ... >>> print unicode(D()) Caf? >>> print D() Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Peter From yennes at gmail.com Thu Mar 20 06:27:50 2008 From: yennes at gmail.com (Dravidan) Date: Thu, 20 Mar 2008 03:27:50 -0700 (PDT) Subject: csv dictreader References: <13u3vq77us4ku3c@corp.supernews.com> Message-ID: <60a85025-4103-494d-b31c-70e66cf9d58b@x30g2000hsd.googlegroups.com> It looks like the backslash is messing the whole thing up so I reposted to try to find out how to get over the backslash hump. On Mar 20, 2:08 am, Dennis Lee Bieber wrote: > On Wed, 19 Mar 2008 11:06:40 -0700 (PDT), brnstrmrs > declaimed the following in comp.lang.python: > > > my csv files looks like this: > > > Bytecode,Element > > \x00\x00,0000 > > \x01\x00,0001 > > .... > > \x09\x00,0009 > > I sure hope your data is more complex than that... otherwise it's a > waste of space... > > >>> for i in range(10): > ... print i, repr(struct.pack("h", i)) > ... > 0 '\x00\x00' > 1 '\x01\x00' > 2 '\x02\x00' > 3 '\x03\x00' > 4 '\x04\x00' > 5 '\x05\x00' > 6 '\x06\x00' > 7 '\x07\x00' > 8 '\x08\x00' > 9 '\t\x00' > > And, \t is the same value \x09 (a tab character) > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From bearophileHUGS at lycos.com Sat Mar 22 19:16:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 22 Mar 2008 16:16:03 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> Message-ID: <3ee39d9f-dde7-432b-bc3c-5b8dd935e3f4@a70g2000hsh.googlegroups.com> bearophile: > A more computer-friendly (and Pythonic) syntax may be ('are' is a keyword): Sorry for causing confusion, I was just thinking aloud. English isn't my first language, and sometimes I slip a bit. Replace that with: > A more computer-friendly (and Pythonic) syntax may be ('are' is meant to be a keyword in such hypothetical situation): Bye, bearophile From mensanator at aol.com Mon Mar 3 20:39:31 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 17:39:31 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> Message-ID: On Mar 3, 6:21?pm, Robert Kern wrote: > Mensanator wrote: > > On Mar 3, 4:08 pm, Robert Kern wrote: > >> Mensanator wrote: > >>> On Mar 3, 2:49 pm, Carl Banks wrote: > >>>> It's just a bug--probably sympy is messing with the internals of the > >>>> random number generator. ?It would be a simple fix. ?Instead of > >>>> b****ing about it, file a bug report. ? > >>> I did. > >>>> Or better yet, submit a patch. > >>> I would if I knew what the problem was. > >> Did you even try to figure it out? It took me all of 5 minutes to find the mistake. > > > Could I trouble you to share? Then I could continue my testing. > > I posted the patch on the bug tracker: > > ? ?http://code.google.com/p/sympy/issues/detail?id=729 Thanks, I think I actually figured out how to use it. > > >>> I posted it here because someone recommended it. > >>> I'm simply un-recommending it. > >> It was a mistake, an easily remedied mistake, > > > But I didn't know that (and still don't). > > >> not a big unchangeable design decision. > > > I didn't know that either. For all I know, I might have to > > wait for the next version, and who knows when that will be? > > The point is that you didn't try to figure it out. Give me a break, I'm not a developer, just an end user. > And you assumed the worst Wasn't my assumption correct? That it really was messing outside it's domain? > rather than giving anyone the benefit of the doubt. As in "maybe it only fails for me"? Was I crying that the sky was falling? > You didn't even wait to get a response from the package > maintainer I have no experience with those web sites. I think this is the first time I was able to successfully report a bug and have no clue what the turnaround time is. > about how serious the issue was The symptom was serious although the fix was simple. > before you came here to un-recommend it. As an end user, I get most of my information here. Since I saw the link to sympy here on this newsgroup, I thought it would be irresponsible to file a bug report without simultaneously mentioning it here. > > All software has bugs. > > Good software has bugs. Are bugs off-topic here? > > Finding a single bug in a package is not sufficient cause to warn people away as > if it had the plague. It DID have the plague. It affected anything else that tried to use random numbers. > > >> If you want to recommend against sympy as a package, there is a larger > >> burden of proof that you have yet to meet. > > > What kind of burden of proof must one have to recommend it in the > > first place? > > Significantly less. "It was useful to me," is sufficient. Really? That's sufficient? Ok, but how is my pointing out a verifyable problem that affects the entire system not a sufficient burden of proof against recommending the package? Or should I just have worded it differently? Aren't I at least going to get credit for having found it? > > -- > 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 ericofam at yahoo.com Sun Mar 9 07:36:55 2008 From: ericofam at yahoo.com (ericofam at yahoo.com) Date: Sun, 9 Mar 2008 04:36:55 -0700 (PDT) Subject: Green's Function References: <501978.67770.qm@web53602.mail.re2.yahoo.com> Message-ID: On Mar 8, 9:46?pm, "Terry Reedy" wrote: > "olusina eric" wrote in message > > news:501978.67770.qm at web53602.mail.re2.yahoo.com... > | ?I am new to Python and trying to solve the Hamiltonian of a linear chair > of atoms using green's function. > | ?Does anyone know any pre-existing library functions and literature that > could be helpful? > > Did you try searching for "Python Green's function"? I did try serching for Python "Green's function" and useful hit. Also searched on scipy with no reasonable result too. EOF From ron.longo at cox.net Mon Mar 24 21:52:49 2008 From: ron.longo at cox.net (Ron Provost) Date: Mon, 24 Mar 2008 21:52:49 -0400 Subject: New Full Tkinter document editor widget -- suggestions, comments, etc. Message-ID: <003301c88e1a$eea60250$6501a8c0@aristotle> I've posted a demo (http://tkinter.unpy.net/wiki/StyledEditor). This demo creates a widget with full "styled editing" capabilities; sort of a mini-word processor. It runs "as is" on my WinXP machine with Python 2.5. The demo allows styling of any selected text via toolbars; just select the text, then select the styling. Also included are buttons to save and retrieve all content and styling information (works for the small tests I've tried myself, not guaranteed bug-free). The actual widget wraps the Text widget to give greater freedom in the assignment of any single styling attribute to any region. This differs from the Text widget itself in that the Text widget does not allow you to individually assign a family, size, weight or slant with tag_config(). That is, for example, you can't simply apply 'bold' to some region of text. This demo was written quite quickly (I pounded it out over the weekend) so I'm sure it's full of bugs. Also in my desire to get something working quickly its API doesn't really work like a normal widget, so I guess this serves as more of a proof of concept than full-blown widget but the basic functionality is there. I'm presenting it here because I thought maybe others might have thoughts on how to improve it. API Notes: applyStyleAttribute( index1, index2, attributeName, attributeValue ) This method is is frontend to the business. attributeName and attributeValue may be any option accpeted by tag_config() of the Text widget along with appropriate value. There are also some ''new'' options: - 'family', attributeValue is a font family name - 'size', attributeValue is a font point size - 'weight', attributeValue is one of: 'normal', 'bold' - 'bold', attributeValue is a boolean (alternative to using 'weight') - 'slant', attributeValue is one of: 'roman', 'italic' - 'italic', attributeValue is boolean (alternative to using 'slant') Several previously existing options have some new values: 'spacing1', 'spacing2' and 'spacing3' may take 'None', 'Half Line', 'One Line' or 'Two Lines' in addition to any of the values acceptable by tag_config(). 'offset' may take 'normal', 'superscript' or 'subscript' in addition to any value acceptable by tag_config. Please download and try-out my demo (http://tkinter.unpy.net/wiki/StyledEditor). I'm anxious for suggestions and comments. Ron Longo From mal at egenix.com Fri Mar 7 16:43:31 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 07 Mar 2008 22:43:31 +0100 Subject: Time Zone application after strptime? In-Reply-To: References: Message-ID: <47D1B703.6040200@egenix.com> On 2008-03-07 22:24, Jim Carroll wrote: > It's taken me a couple of hours to give up on strptime with %Z for recognizing > time zones... but that still leaves me in the wrong zone: > > def paypal_to_mysql_date(ppDate): > # a typical paypal date is 10:29:52 Feb 29, 2008 PST > date_parts = ppDate.split() > withouttz = " ".join(date_parts[:-1]) > > # eventually we need to apply the timezone > timezone = date_parts[-1] > > dt = datetime.strptime(withouttz, "%H:%M:%S %b %d, %Y") > return dt.strftime("%Y-%m-%d %H:%M") > > > How can I use the "PST" (or any other time zone name) to adjust dt by the > correct number of hours to get it into UTC before storing in MySQL? You could try mxDateTime's parser. It will convert most timezones into UTC for you: >>> from mx.DateTime import * >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008') However, note that I changed the position of the timezone in your example. Having the timezone at the end of the string and after the date is a rather unusual format and not supported out-of-the-box by mxDateTime (even though it does support a very wide range of formats). http://www.egenix.com/products/python/mxBase/mxDateTime/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 07 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From lists at js3d.co.uk Tue Mar 25 11:31:11 2008 From: lists at js3d.co.uk (Jules Stevenson) Date: Tue, 25 Mar 2008 15:31:11 -0000 Subject: dynamically created names / simple problem In-Reply-To: <47E91820.7090009@jouy.inra.fr> References: <000c01c88e88$96c29490$0600a8c0@laptop><47E91645.4000706@jouy.inra.fr> <47E91820.7090009@jouy.inra.fr> Message-ID: <001d01c88e8d$41489d70$0600a8c0@laptop> Brilliant. Thanks From davidbak at gmail.com Fri Mar 7 16:07:21 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 13:07:21 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: <83a114c1-e675-445f-909d-68c2407bc276@u10g2000prn.googlegroups.com> Sorry - code for the class should read: class Tree(object): ...class _MT(Tree): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node(Tree): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... From bearophileHUGS at lycos.com Wed Mar 5 19:39:08 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 5 Mar 2008 16:39:08 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> Message-ID: <2401e847-09da-4ec3-be89-29c382a82b04@60g2000hsy.googlegroups.com> On Mar 5, 10:44 pm, "Troels Thomsen" wrote: > > The primary use case is searching a container: > > > prep_tasks() > > for item in container: > > if predicate(item): > > found_tasks() > > break > > else: > > not_found_tasks() > > follow_up_tasks > > I've found myself mimicing this again and again in c, and was pleased to > find it in python and use it regularely. > int i > for (i = 0 ; i < 10 ; ++i) > blah > if i == 10 > not_found_tasks() > > The discussion of words is silly. My surprise about "else following a for > loop.... what the heck ...." lasted excactly as long as it takes to read > this sentence. > > tpt From duncan.booth at invalid.invalid Mon Mar 10 10:18:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2008 14:18:48 GMT Subject: Quality assurance in Python projects containing C modules References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> Message-ID: NoelByron at gmx.net wrote: > Hello! > > We are thinking about writing a project for several customers in > Python. This project would include (among others) wxPython, a C/C++ > module. But what happens if this application generates a segmentation > fault on a customers PC. What changes do we have to trace back the > source of the error? Imagine you use two or three C libraries in a > Python project and you experience random crashes in 'Python.exe'. What > would you do? > I would start by ensuring that any DLLs you write are written using Pyrex or Cython: almost always problems with C libraries called from Python are due to faulty reference counting but if you keep all of your Python related code in Pyrex/Cython modules the reference counting problem should be taken care of for you. You can call any required C/C++ code from the Cython code. From roy at panix.com Sun Mar 23 13:51:34 2008 From: roy at panix.com (Roy Smith) Date: Sun, 23 Mar 2008 13:51:34 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: > Also, despite reassurances to the contrary, I still get the impression > that there is a strong anti-lambda sentiment among the Python "in" > crowd. Is it just a question of the word "lambda," as opposed to > perceived cleaner syntax? There is a fundamental disharmony in how functions and other objects are treated in Python. If I say: x = ['surprise', 'fear', 'ruthless efficiency'] I've done two things. First, I've created a list, then I've bound the name x to that list (maybe "bound" is not exactly the right terminology). Until the assignment happend, the list had no name. In fact, it still has no name; there's just a reference to it stored in a variable whose name is x. If I were to then do y = x now y and x have equal relationships to the original list. The list's name is no more x than it is y, since the whole concept of "the name of the list" doesn't have any meaning in Python. On the other hand, when I do: def torture(): woman.putInChair() cushion.poke() rack.turn() I've also done two things. First, I've created a function object (i.e. a lambda body), and I've also bound the name torture to that function object, in much the same way I did with the list. But, it's different. The function object KNOWS that it's name is torture. When I later reassign it to another name and run it: weapon = torture weapon() This is what I get: Traceback (most recent call last): File "", line 1, in File "", line 2, in torture NameError: global name 'woman' is not defined Notice, the second line in the stack trace identified the function's name as "torture", not "weapon". Because that IS the function's name. Lists are anonymous. Functions have names (as do a few other things like classes and modules). If I ask a list what its name is, I get: AttributeError: 'list' object has no attribute '__name__' but, if I ask a function what it's name is (regardless of what name I've bound it to), I get the right answer: >>> torture.__name__ 'torture' >>> weapon.__name__ 'torture' >>> If we created lisp-like lambdas and bound them to names like we did with other types of objects, we wouldn't have that. What Python give us with lambdas is some half-way thing. It's not a full function, so it's something that people use rarely, which means most people (like me) can't remember the exact syntax. Even when I know it's the right thing to be using in a situation, I tend not to use it simply because the path of least resistance is to write a one-off function vs. looking up the exact syntax for a lambda in the manual. From tameranboobs at gmail.com Thu Mar 27 09:13:16 2008 From: tameranboobs at gmail.com (tameranboobs at gmail.com) Date: Thu, 27 Mar 2008 06:13:16 -0700 (PDT) Subject: genuine phentermine overnight delivery american express overnight pay phentermine phentermine without perscriptions Message-ID: http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ order phentermine with saturday overnight delivery, phentermine order no scripts overnight delivery, phentermine fast overnight delivery guaranteed, delivery overnight guaranteed phentermine stock, order phentermine online saturday delivery, order phentermine with saturday delivery, overnight delivery phentermine 375 mg, phentermine overnight delivery text javascript, phentermine overnight ups delivery, phentermine overnight delivery to florida, phentermine sameday overnight saturday delivery, overnight phentermine with saturday delivery, buy phentermine overnight saturday delivery, phentermine cod overnight delivery no rx, order zithromax overnight delivery, order phentermine saturday delivery, delivery guaranteed in overnight phentermine stock, phentermine overnight saturday delivery, 30mg phentermine overnight delivery, phentermine overnight delivery us licensed pharmacies, phentermine guaranteed overnight delivery usa only, overnight delivery phentermine 37.5, phentermine fed ex overnight delivery, order phentermine by for saturday delivery, genuine phentermine overnight delivery, order phentermine by phone online consultation, order telephone viagra overnight delivery, purchase phentermine cheap overnight delivery guarantee, real phentermine overnight delivery no script, phentermine and 375 online overnight delivery, phentermine banners overnight delivery, phentermine overnight delivery available, phentermine 37.5 no prescription overnight delivery, immediate phentermine overnight delivery, delivery overnight in guaranteed phentermine stock, phentermine in stock overnight delivery, phentermine no prescription fedex overnight delivery, cod delivery overnight phentermine ups, 30mg blue phentermine overnight delivery, order by 2pm get phentermine overnight, phentermine online fed ex overnight delivery, phentermine for overnight and saturday delivery, phentermine overnight delivery saturday, overnight phentermine saturday delivery, delivery overnight phentermine us licensed pharmacies, phentermine and overnight delivery and saturday, phentermine 375 online overnight delivery, phentermine cod guaranteed overnight delivery, phentermine 37.5 overnight delivery, ups overnight delivery phentermine us only, e-check order phentermine fast delivery, no prescription 37.5 phentermine overnight delivery, phentermine online gt overnight delivery levitra, overnight saturday delivery for phentermine, order phentermine without prescription ship overnight, order phentermine by phone no script, phentermine order express shipping, order phentermine no primary care physician, order watson soma with saturday delivery, phentermine with cod delivery charge, no prescription premarin free overnight delivery, imitrex overnight delivery, allegra buy valium overnight delivery possible, fed ex overnight delivery cialis, phentermine usa pharmacy ativan guaranteed overnight, guaranteed overnight phentermine without rx, order phentermine oval a 159, angel book guest order phentermine site, order phentermine without calling my doctor, buy phentermine online same day delivery, buy phentermine by phone no script, phentermine on line with saturday delivery, fenphen file link order phentermine, places to order phentermine, cash delivery link medrx phentermine, guaranteed overnight phentermine without prescription, order phentermine wbr, phentermine overnight phentramine, phentermine no rx overnight, phentermine overnight paid by mastercard, order phentermine with online diagnosis, phentermine 37.5 tablets next day delivery, phentermine 15mg overnight shipping, phentermine overnight fedex no prescription 37.5, sumycin overnight delivery, prescription cipro overnight delivery, arthritis load cell order phentermine, order real phentermine without script, addiction adipexdrug online order phentermine, cash day delivery guaranteed next phentermine, phentermine 37.5 next day delivery, places to order ligit phentermine, phentermine overnight legal no prescription, phentermine blue white capsules order online, order phentermine without a doctor approval, phentermine overnight federal express, buy ritalin online phentermine order, real phentermine without prescription overnight ship, phentermine no script fedex overnight, viagra overnight delivery weekends, buy eon labs phentermine overnight, phentermine overnight no prescription legal legal, order cheap phentermine online overnite, buy no prescription next-day delivery phentermine, opensolaris forums buy phentermine online order, diovan online order fast delivery, order phentermine phentermineonline s xanga site, order phentermine and ship to arkansas, buy phentermine 37.5 tennessee overnight ship, phentermine order by 3pm, phentermine huge discounts fast delivery, dir link order phentermine, zithromax overnight delivery, phentermine via money order, phentermine no rx overnight fedex cod, zanaflex overnight delivery, phentermine overnight cod accepted, overnight phentermine adipex cod excepted, order phentermine online us licensed pharmacies, 90 count phentermine overnight shipping, bbs followup message order phentermine post, buy cheap phentermine moreover order viagra, cod delivery phentermine saturday, cheap phentermine offer cash on delivery, phentermine with satruday delivery, phentermine 37.5mg prescription overnight, phentermine cod overnight eft, prednisone order online overnight, phentermine no rx nextday delivery, order phentermine without drs rx, phentermine overnight shipping fed ex, phentermine pharmacy ships cod overnight, online pharmacy phentermine saturday delivery, phentermine 24 hour delivery, phentermine overnight no prior prescription, purchase tylenol 3 with overnight delivery, phentermine back-order, delivery flower buy phentermine, frontier pharmacies order phentermine eon labs, order phentermine 375 mg, phentermine 37.5 order no denials, phentermine saturday delivery cash on delivery, compare overnight phentermine prices united states, buspar fast overnight delivery usa only, delivery guaranteed overnight soma, cheap online order overnite phentermine, find phentermine overnight cod 100 count, phentermine fedex overnight shipping, kinds of phentermine doctors order, order phentermine 375 cod, order phentermine in usa without script, generic diflucan no prescription overnight delivery, inexpensive phentermine overnight, phentermine guaranteed overnight shipping, codeine tylenol 4 overnight delivery, buy lamictal with overnight delivery, extra cheap phentermine fed ex delivery, most reliable site to order phentermine, no prescription next-day delivery phentermine, fastest phentermine delivery no prescription, leo phentermine order online, phentermine 37.5 overnight shipping, diflucan phone order, phentermine online purchase saturday delivery, discrete overnight phentermine, phentermine cod next day delivery, phentermine cod saturday delivery, order phentermine without physicians approval, order phentermine or duramine online, buy phentermine sat delivery cod, florida in overnight phentermine shipped, order phentermine pay with mastercard, acomplia overnight delivery, order phentermine referrers total, ups delivery phentermine, order phentermine online use mastercard, guaranteed overnight phentermine, phentermine no prescription ship overnight, cheap morning after pill overnight delivery, order phentermine oval, money order phentermine umaxppc, phentermine free overnight shipping 89, order prednisone no prescription overnight fedex, phentermine no prescription saturday delivery, order phentermine priority mail, phentermine saturday delivery available, order cheap phentermine no prescript tin, acomplia guaranteed overnight delivery, adipexdrug addiction order phentermine online, echeck phentermine overnight, diflucan overnight delivery, overnight saturday phentermine before 4pm, phentermine phentramine online prescription order, phentermine delivered overnight, addiction adipexdrug order phentermine, presc s xanga site order phentermine, buy cheap phentermine shipped overnight, phentermine overnight discover credit card, phentermine with saturday delivery, nevada based phentermine overnight, ship overnight phentermine 37.5, phentermine 15mg overnight, accepted cod order phentermine s, internet order phentermine 37.5mg 90 tablets, no doctor contact to order phentermine, guaranteed delivery phentermine 37.5 no prescription, lasix without prescription overnight delivery, zovirax overnight delivery, buy phentermine online ritalin order, order phentermine no script united states, overnight prednisone delivery, receive phentermine saturday delivery, phentermine saturday delivery, phentermine shipped cash on delivery, blogs on where to order phentermine, phentermine saturday delivery best online pharmacy, order phentermine hcl overnite cod, cheap delivery online phentermine saturday, phentermine no prescriptions sat delivery, overnight phentermine brand no script, levitra fast overnight delivery usa only, delivery phentermine saturday, overnight phentermine with drs consult, phentermine 15mg fed ex overnight, phentermine 30 overnight fedex cod, order phentermine 37.5 180, same day delivery on phentermine, viagra by overnight delivery, customhrt phentermine order, famvir overnight delivery, phentermine overnight no script, phentermine overnight discover card, overnight delivery topamax, phentermine overnight $90, order phentermine overseas, phentermine no script overnight, order phentermine by 6pm, 4.22 order phentermine, buy phentermine without script fast delivery, phentermine no prescripition overnight ship, customs seized phentermine order, phentermine 37.5 cash on delivery, purchase phentermine overnight with paypal, can't order phentermine anymore, phentermine in stock overnight, phentermine shipped overnight, phentermine 37.5 fed ex overnight, didrex phentermine no rx overnight shipping, viagra overnight delivery on weekends, adipexdrug addiction order phentermine, cheap phentermine worldwide delivery, order phentermine 37.5 2 day ship, phentermine no prescription saturday delivery mastercard, buy cod delivery phentermine sat, cod money order accepted for phentermine, phentermine in stock california overnight, delivery phentermine united parcel, phentermine shipped cod overnight, phentermine cod overnight 100 ct, pravachol overnight delivery, fedex overnight delivery codeine ultram tramadol, generic cialis overnight delivery express delivery, order phentermine cod view more info, phentermine 37.5mg overnight shipping, miami distributer phentermine order online, cheap phentermine saturday delivery ups chep, overnite delivery of prescription phentermine, phentermine generic overnight 90 days, order phentermine online phentermine phentermine saturday, order phentermine without calling doctor, phentermine phentramine overnight yellow, phentermine 37.5 no prescription overnight shipping, prilosec stock overnight delivery, ultram overnight delivery same day, phentermine buy on line overnight, fedex overnight delivery ultram tramadol codeine, buy eon phentermine overnight, phentermine order without primary care physician, american express overnight pay phentermine, motrin overnight delivery, phentermine overnight ship, order phentermine safely without prescription, buy phentermine saturday delivery ohio, best order phentermine place umaxppc, order phentermine with no prior prescription, order topamax overnight, order phentermine phenterm ine online, phentermine and no prior and overnight, bulk order of phentermine, order phentermine online al bawaba blogs, phentermine 37.5 fed-x delivery, cash delivery hydrochloride phentermine, viagra overnight delivery 1 800, cialis and diazepam overnight delivery possible, order phentermine descriptive phentermine guidelines, phentermine and facts not to order, canada phentermine phentermine order mastercard, prednisone overnight delivery, order phentermine with no physcian approval, overnight phentermine licensed pharmacies online, phentermine secure online order, fed x delivery for phentermine, delivery overnight in guaranteed acomplia stock, cash on delivery shipping of phentermine, keyword phentermine online order shop baikalguide, c d o overnight phentermine, 180 37.5 order phentermine pill, order phentermine from middle east pharmacy, cheap phentermine nextday delivery, tennessee phentermine 37.5 overnight ship, phentermine 37.5 order medication, book guest link order phentermine, phentermine arkansas overnight, overnight express delivery generic cialis, order phentermine high quality pharmacy index, buy phentermine with saturday delivery, soma online overnight delivery to florida, phentermine 37.5 overnight phentramine hoodia, order phentermine no rx mastercard, overnight rocaltrol delivery, flomax overnight delivery, phentermine without a prescription saturday delivery, dc community forums phentermine cod delivery, cash delivery ordering phentermine phentermine dosing, phentermine by phone no script, phentermine smallest prices worldwide delivery, phentermine with cod and saturday delivery, 4.25 n online order phentermine, order phentermine online pharmacy catalog online, cytotec order overnight, order phentermine receive sameday, nexium overnight delivery, prilosec in stock overnight delivery, buy order phentermine hcl without prescription, desyrel order overnight, 4.25 online order phentermine, codeine ultram tramadol overnight delivery, ultram 059 order phentermine, phentermine overnight no subscription, cod delivery phentermine ups, phentermine phentramine overnight, collect on delivery phentermine, overnight phentermine 37 5mg, 375 cod order phentermine, guaranteed overnight phentermine us licensed pharmacies, cheapest phentermine fed x overnight, order phentermine without physicians prescription, order phentermine by cashier check, phentermine cash on delivery accepted, phentermine overnight to california, overnight phentermine no rx, lasix overnight delivery, phentermine guaranteed overnight, phentermine 37.5 pay by money order, order phentermine pay with echeck, blog cheap home link phentermine, best phentermine no perscription 30mg, phentermine banner, phentermine 37.5 free doctor, weight loss journal diet phentermine pill, phentermine hydrochloride iv tablets usp, does phentermine cause depression, phentermine 30mg blue clear caps discreet, 4.01 buy cheap phentermine, no rx phentermine 30mg, order herbal ecstasy, reliable sites for phentermine, b 12 phentermine raleigh, phentermine erection help, carisoprodol phentermine yellow, phentermine nrop cod, ativan link online phentermine phentermine9, phentermine topamax, phentermine plus wellbutrin fill prescriptions online, buy phentermine form eurpoe, phentermine hydro, cheap phentermine 30 mgs caps, phentermine vs dhea, order pal pay zocor, phentermine induced psychosis, doctors that perscribe phentermine, cure depression diet phentermine pill, phentermine 37.5 90 pills, phentermine 30mg without perscription, buy phentermine w out a prescription, phendimetrazine interactions with phentermine, dir florida link phentermine purchase ship, discount online phentermine without script, phentermine doctor st louis, phentermine side effects dangers, phentermine that uses paypal, dr in bakersfield phentermine, cheap prozac overnight, different shapes of phentermine tablets, ultram saturday delivery, phentermine no presciption, phentermine shipped to la, phentermine before surgery, phentermine 37 5mg shipped to kentucky, phentermine wikipedia the, lung problems from phentermine, phentermine eon labs buy online, phentermine licensed physician, phentermine on line official store, diflucan day delivery, re prozac and phentermine anyone, phentermine 37.5 no doctor consult, fastin online description chemistry ingredients phentermine, order the abortion pill, phentermine and sibutramine, pravachol phentermine pharmacy los angeles, phentermine sales for ky, phentermine capsules 37.5mg without prescription, seap debt counseling phentermine now, phentermine menstrual cycle, phentermine constipation, whats is phentermine, actos canada online pharmacy phentermine plavix, confidential online phentermine, 37.5 159 a phentermine, harmful effects of phentermine for adipex, phentermine w o rx, want phentermine shipped 48hours, generic viagra sent overnight, 37.5 mg phentermine with no rx, compare ionamin phentermine, phentermine dextroamphetamine amphetamine, phentermine query, phentermine blue white 30mg side effects, phentermine in hair follicle drug test, phentermine and mouth numbness, phentermine 90 count, book com guest myron phentermine site, phentermine 37.5 capsules, negative phentermine stories, having trouble finding phentermine information, museum phentermine site, phentermine delivered c o d, addiction adipexdrug online phentermine, phentermine tolerance, generic phentermine rss feed, phentermine testimony, didrex link online phentermine phentermine9, phentermine 37.5mg consultation, saff 0 q buy phentermine, phentermine and methamphetamine, order discount pravachol free shipping, order viagra international ships, real people opinions of phentermine, prednisone order doctor on staff, difference between meridia and phentermine, phentermine no perscription, phentermine yellow capsules, phentermine without dr script, phentermine prescription amount, phentermine through body building, cheap phentermine yellow free shipping, 365 generic medication phentermine, taking phentermine with paxilcr, phentermine sore throat, phentermine safety and does it work, phentermine have withdrawal symptoms, miami online phentermine, phentermine with online prescription, pm cheap phentermine us licensed pharmacies, phentermine without a perscription, overnight levaquin without prescription, 5htp phentermine, phentermine erection depression, phentermine and sibutramine be combined, sellers of phentermine 30 mg civ, difference between phentermine and phentermine, actos phentermine norvasc, diet pal pay phentermine pill, brand name phentermine 37.5 next day, phentermine without perscription shipped to ky, oder phentermine by cod, phentermine phoenix arizona, phentermine non perscription, phentermine incrediants, lotensin aciphex phentermine pharmacy chicago, phentermine no precription, 92 accepted cod phentermine, phentermine 37.5 90 ct no prescription, phentermine and zoloft us approved pharmacies, file link online phentermine phentermine side, baikalguide diet keyword phentermine pill shop, extended release phentermine, cardinal health diet phentermine pill, phentermine chemical enhancement, cheap levitra link phentermine phentermine9, phentermine creates erection, phentermine suspended, budget rx phentermine, phentermine without perscriptions, phentermine and customhrt, phentermine overview, need real phentermine without rx, diet pills phentermine us licensed pharmacies, prevacid prescription assistance, From gherzig at fmed.uba.ar Fri Mar 14 10:14:11 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 14 Mar 2008 11:14:11 -0300 Subject: request for Details about Dictionaries in Python In-Reply-To: References: <47DA6FF6.5000505@fmed.uba.ar> Message-ID: <47DA8833.9020205@fmed.uba.ar> Saideep A V S wrote: >Hello Sir, > > Thank You a ton. I was looking for this function. As far what I've >understood from the "Shelve" module is that, there would be no memory >wastage and the whole transactions would be done from and to the file we >specify. Am I right?. > > My actual task is to build a basic dictionary for two languages and store >word and its meaning in another language in a file and must be able to >access it through on-disk Hash tables. as these would be saving memory space >for a huge data. > >so, I hope shelve is the right one, I am searching for., I shall try out >with the function. > > >Thank You once again. > >Cheers, >Saideep > > > Plz remember allways reply to the python group also. They are many many many ones to know more than i do! Well, i dont quite think that it would be "no memory wastage", since when you read/write from disk, there is memory involved in the process. I *really* believe that, when data goes huge, a *real* database (like postgres, and others) has to come and play the game. Hope that helps Gerardo From danb_83 at yahoo.com Sat Mar 29 16:48:48 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 29 Mar 2008 13:48:48 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> Message-ID: <02864e42-d2d7-4eeb-ba13-6aa7ddbdf7aa@i29g2000prf.googlegroups.com> On Mar 29, 6:08 am, Paul Rubin wrote: > kwitt... at telenet.be writes: > > I don't know if this is the right place to discuss the death of <> in > > Python 3.0, or if there have been any meaningful discussions posted > > before (hard to search google with '<>' keyword), but why would anyone > > prefer the comparison operator != over <>??? > > I doubt anyone cares. Python probably chose != because it's what C uses. MOST of Python's operators are based on C's. Consider, for example, the bitwise operators | ^ & << >> ~ and the compound assignment operators += -= etc. The exceptions are ** (from Fortran), //, and the logical operators. From dullrich at sprynet.com Thu Mar 20 07:18:34 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 20 Mar 2008 06:18:34 -0500 Subject: Speaking Text References: Message-ID: On Wed, 19 Mar 2008 07:41:29 -0500, David C. Ullrich wrote: >Mac OS X has text-to-speech built into the interface. >So there must be a way to access that from the command >line as well - in fact the first thing I tried worked: > >os.system('say hello') > >says 'hello'. > >Is there something similar in Windows and/or Linux? >(If it's there in Linux presumably it only works if there >happens to be a speech engine available...) Thanks for the replies. >David C. Ullrich David C. Ullrich From tmp1 at viltersten.com Sat Mar 8 19:55:50 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 01:55:50 +0100 Subject: SV: SV: Quit-command not quiting In-Reply-To: References: <63d2efF271u6hU1@mid.individual.net><63d5v1F23vm9fU1@mid.individual.net> Message-ID: <63gptsF266bejU1@mid.individual.net> "Gabriel Genellina" skrev i meddelandet news:mailman.1750.1205017517.9267.python-list at python.org... > En Fri, 07 Mar 2008 13:56:45 -0200, K Viltersten > escribi?: > >>>> The window itself vanishes if i click the >>>> cross in the upper-right corner but pressing >>>> the quit-button only makes it "pressed". >>>> Then, the program freezes. >>> >>> How did you run it? From inside IDLE? IDLE itself is written >>> using Tk, and I think that your mainloop interferes with the >>> one inside it. If you run your program from the command line >>> it should work fine. >> >> I press F5 while in the editor window. Is there a way to run the >> program without going to the console window? >> Perhaps i'm just making things unneccesarily complicated >> and Python IS supposed to be run from console window? > > No, use IDLE if you prefer, or any other editor/IDE. But in your case > there is an unfortunate coupling between IDLE and your script. Fix: change > the quit method as suggested in this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/92bee52a3e2a325e/ > > def quit(self): > self.master.destroy() > > This is OK if used on the top level widget on the application (your Demo > class, for instance). A more general solution: > > def quit(self): > parent = self > while parent.winfo_class() != 'Tk': > if parent.master is None: > break; > parent = parent.master > else: > parent.destroy() > > (from > https://sourceforge.net/tracker/index.php?func=detail&aid=661324&group_id=9579&atid=109579 > ) > > This appears to work fine. But the loop, as written, could exit without > calling destroy() on anything; perhaps some other people knowing better > how Tkinter and Tk work could improve it or confirm it's fine as it is. Thank you. I'll try that tomorrow. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From jgardner at jonathangardner.net Thu Mar 13 15:03:25 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 13 Mar 2008 12:03:25 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> Message-ID: <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> On Mar 12, 6:37?pm, Carl Banks wrote: > On Mar 12, 8:11 pm, Justus Schwabedal > wrote: > > > What do you need it for anyway? I just read about it and I think it's > > useless > > in python. > > Perl, like Python, has a separate compilation and run times. ?One day, > someone who was trying to use Perl for something asked, "You know, > wouldn't it be neat-o if you could execute some Perl code *before* you > compiled the script?" ?And so (since that's usually enough reason to > add something to Perl) was borne the BEGIN block. > > I believe the official rationale was that they wanted to add some > magic variables that affected Perl's compilation and couldn't do it > without a magic block that executed at compile time. > It's a bit different. Python's "import" and perl's "use" statements aren't very similar at all. See, perl looks for any "use" statements and runs those first. That's not the way for Python at all. It's ok to import a module right before you need it in a function. If you never call the function, you'll never import the module. What if you want to reprogram the search path before you use a module? Well, in Python, you just work on sys.path before the import statement. But in perl, if you put a statement that mucks with the perl path, then it will be ignored until it is too late. So you have to throw it into the BEGIN block to have it do anything at all. What was an obvious task in Python that uses only constructs and concepts you already know about, requires a new concept and syntax that wasn't needed before in perl. Also, Jeff has it right. Those who don't get it should look closely at the '-p' option passed to perl. (It has a cousin '-n' that is also just as useful.) Here, he wants to initialize some code before the loop starts, but he can't specify that initializing code outside of the loop without a BEGIN block. BEGIN is a dirty, ugly, stupid bandage to an underlying weakness in perl. That is, there is magic that needs more magic to override it. (And then you'll need magic to override the overriding magic, ad infinitum.) Rather than adding more magic, what you really need to do is get rid of magic that gets in people's way, or change the magic so it is actually useful for everyone. Python has it right. Tokenize, parse, (skip compile-link-import magic), and run. And leave out the magical -p and -n. If you want to iterate through a file, "for line in sys.stdin:". From dave_mikesell at fastmail.fm Sat Mar 8 16:40:56 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 13:40:56 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 2:27 pm, castiro... at gmail.com wrote: > Good comments are better than bad names. > Good names are better than bad comments. If you're taking the time to write good comments, why not just fix the bad names? The compiler/interpreter can never, ever catch bad comments. From NoelByron at gmx.net Mon Mar 10 09:08:32 2008 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: Mon, 10 Mar 2008 06:08:32 -0700 (PDT) Subject: Quality assurance in Python projects containing C modules Message-ID: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> Hello! We are thinking about writing a project for several customers in Python. This project would include (among others) wxPython, a C/C++ module. But what happens if this application generates a segmentation fault on a customers PC. What changes do we have to trace back the source of the error? Imagine you use two or three C libraries in a Python project and you experience random crashes in 'Python.exe'. What would you do? We intent to target mainly the Windows platform. Is there for example a way to use 'dbghelp.dll'? Best regards and thank you! Noel From vedrandekovic at gmail.com Wed Mar 26 13:55:43 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 26 Mar 2008 10:55:43 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip Message-ID: Hello, Does anybody have any idea how can I embed my modules to libary.zip and use it from my application.For example if user write this code in my TextEntry ( or something like that, textentry is created with wxpython ) : import d3dx # directpython module frame=d3dx.Frame(u"My frame") # create frame frame.Mainloop() # run it ....and then when my application execute code how can I set path to d3dx module to "library.zip/d3dx.py". I'm not sure is this properly set question. Regards, Vedran From jacob.kaplanmoss at gmail.com Sun Mar 16 11:51:33 2008 From: jacob.kaplanmoss at gmail.com (Jacob Kaplan-Moss) Date: Sun, 16 Mar 2008 08:51:33 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <40b73be4-3744-4e29-8524-503d559445df@b64g2000hsa.googlegroups.com> On Mar 16, 9:59?am, Fuzzyman wrote: > This isn't new though. Last year (my only other PyCon) all the > sponsors gave lightning talks. The difference is that there were more > sponsors this year I guess... The difference (from my POV as the guy who helped plan and run the lightning talks this year and last) was that last year the sponsor talks were at a separate time, and clearly labeled as "Sponsor Lightning Talks". A *lot* of folks still showed up, and they didn't feel lied-to when they got product or company pitches. Jacob From jackdied at jackdied.com Sun Mar 23 01:26:28 2008 From: jackdied at jackdied.com (Jack Diederich) Date: Sun, 23 Mar 2008 01:26:28 -0400 Subject: Know Your Python-Devs! Message-ID: <20080323052627.GA6351@performancedrivers.com> At the PyCon core python sprint I suggested this game and it got some laughs. So I put together a webpage for the game of: German, American, or Other? There is a list of about 30 core devs' last names. Highlight the white text on white background for the [mostly correct] answers. http://jackdied.blogspot.com/2008/03/misc-from-pycon-ii.html Enjoy, -Jack From r.grimm at science-computing.de Fri Mar 21 04:53:23 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Fri, 21 Mar 2008 01:53:23 -0700 (PDT) Subject: removing all instances of a certain value from a list References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Message-ID: <93e8ab20-8dd5-47d3-b977-822329889b52@a70g2000hsh.googlegroups.com> On Mar 19, 11:28 pm, Lee Sander wrote: > Hi, > I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are > many missing vlaues which are represented as None. I would like to > remove all such instances in one go. > There is a remove function but it removes only the first instance, is > there a delete/remove all function? > thanks You can also do it with the filter function. >>> a= [-1.3, 1.22, 9.2, None, 2.3] >>> a=filter ( lambda b: b != None, a) >>> print a [-1.3, 1.22, 9.1999999999999993, 2.2999999999999998] Greetings Rainer From fakeaddress at nowhere.org Fri Mar 14 04:18:51 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 08:18:51 GMT Subject: Spaces in path name In-Reply-To: References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: David S wrote: > I get > > ERROR: ""C:\Program Files\apache-ant-1.7.0\bin\ant"" does not exist > > If I cut the path statement here and paste it next to a windows XP command > prompt ant is invoked. > > The python code here is > if not os.path.isfile(ANT_CMD): > error('"%s" does not exist' % ANT_CMD) There you don't want the quotes within the string. On my MS-Win box: >>> import os >>> os.path.isfile(r'C:\Program Files\Windows NT\dialer.exe') True >>> print os.path.isfile(r'"C:\Program Files\Windows NT\dialer.exe"') False -- --Bryan From kyosohma at gmail.com Mon Mar 24 16:11:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 24 Mar 2008 13:11:52 -0700 (PDT) Subject: PyCon video editing References: <0ed1ce28-b517-4c17-b12e-7d6554f5274a@x41g2000hsb.googlegroups.com> Message-ID: <2694d982-a5d1-426d-81dc-eb16b27ddccc@i12g2000prf.googlegroups.com> On Mar 18, 10:09 am, amk wrote: > On Mar 17, 10:00 pm, dundeemt wrote: > > > Anyone know who is in charge of this? I'd like to help out if I > > could. > > I am, but haven't set anything up yet, such as a mailing list or a > host for the video. > I'll update the wiki pagehttp://wiki.python.org/moin/PyConRecordingBof > with news/further developments (you can create a wiki account and > follow the envelope icon at the upper right > to be notified of changes via e-mail). > > --amk Somebody has stuck a few videos on Youtube already: http://www.youtube.com/user/pycon08 Mike From fuzzyman at gmail.com Sat Mar 1 17:59:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 1 Mar 2008 14:59:38 -0800 (PST) Subject: Python COM automation - Controlling Microsoft Agent References: <0a998c60-fc33-4424-b5c7-65f4a2846e4d@i12g2000prf.googlegroups.com> Message-ID: <82b25446-78fb-4e02-b454-9f03b63c1e9f@e23g2000prf.googlegroups.com> On Mar 1, 12:47 am, Kamilche wrote: > Here's a snippet of code for pythoners to enjoy. > Make the Microsoft genie speak text and dance about! Code (with pretty pictures!) to do similar things from IronPython: http://www.ironpython.info/index.php/AgentServerObjects Michael Foord http://www.manning.com/foord From steven.klass at gmail.com Sun Mar 23 00:51:07 2008 From: steven.klass at gmail.com (rh0dium) Date: Sat, 22 Mar 2008 21:51:07 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> Message-ID: <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> On Mar 22, 6:30?pm, Paul McGuire wrote: > Oof, I see that you have multiple "Layer" entries, with different > qualifying labels. ?Since the dicts use "Layer" as the key, you only > get the last "Layer" value, with qualifier "PRBOUNDARY", and lose the > "Layer" for "METAL2". ?To fix this, you'll have to move the optional > alias term to the key, and merge "Layer" and "PRBOUNDARY" into a > single key, perhaps "Layer/PRBOUNDARY" or "Layer(PRBOUNDARY)" - a > parse action should take care of this for you. ?Unfortnately, these > forms will not allow you to use object attribute form > (md.Layer.lineStyle), you will have to use dict access form > (md["Layer(PRBOUNDARY)"].lineStyle), since these keys have characters > that are not valid attribute name characters. > > Or you could add one more level of Dict nesting to your grammar, to > permit access like "md.Layer.PRBOUNDARY.lineStyle". > > -- Paul OK - We'll I got as far as you did but I did it a bit differently.. Then I merged some of your data with my data. But Now I am at the point of adding another level of the dict and am struggling.. Here is what I have.. # parse actions LPAR = Literal("(") RPAR = Literal(")") LBRACE = Literal("{") RBRACE = Literal("}") EQUAL = Literal("=") # This will get the values all figured out.. # "metal2" 1 6.05E-05 30 cvtInt = lambda toks: int(toks[0]) cvtReal = lambda toks: float(toks[0]) integer = Combine(Optional(oneOf("+ -")) + Word(nums))\ .setParseAction( cvtInt ) real = Combine(Optional(oneOf("+ -")) + Word(nums) + "." + Optional(Word(nums)) + Optional(oneOf("e E")+Optional(oneOf("+ -")) +Word(nums)))\ .setParseAction( cvtReal ) atfstr = quotedString.setParseAction(removeQuotes) atflist = Group( LPAR.suppress() + delimitedList(real, ",") + RPAR.suppress() ) atfvalues = ( real | integer | atfstr | atflist ) # Now this should work out a single line inside a section # maskName = "metal2" # isDefaultLayer = 1 # visible = 1 # fatTblSpacing = (0.21,0.24,0.6, # 0.6,0.6,0.6) # minArea = 0.144 atfkeys = Word(alphanums) attrDict = dictOf( atfkeys , EQUAL.suppress() + atfvalues) # Now we need to take care of the "Metal2" { one or more attrDict } # "METAL2" { # layerNumber = 36 # maskName = "metal2" # isDefaultLayer = 1 # visible = 1 # fatTblSpacing = (0.21,0.24,0.6, # 0.24,0.24,0.6, # 0.6,0.6,0.6) # minArea = 0.144 # } attrType = dictOf(atfstr, LBRACE.suppress() + attrDict + RBRACE.suppress()) # Lastly we need to get the ones without attributes (Technology) attrType2 = LBRACE.suppress() + attrDict + RBRACE.suppress() mainDict = dictOf(atfkeys, attrType2 | attrType ) md = mainDict.parseString(test1) But I too am only getting the last layer. I thought if broke out the "alias" area and then built on that I'd be set but I did something wrong. From BeshrKayali at gmail.com Sat Mar 15 06:03:21 2008 From: BeshrKayali at gmail.com (E-Lo) Date: Sat, 15 Mar 2008 03:03:21 -0700 (PDT) Subject: Python for Palm OS Message-ID: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Is there any other edition of Python for Palm OS instead of Pippy? From Lie.1296 at gmail.com Sun Mar 16 05:55:51 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 02:55:51 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <210b2a22-a8e3-414e-9018-15f7d74c9f83@d4g2000prg.googlegroups.com> <64172eF29qj9jU1@mid.uni-berlin.de> Message-ID: <02533def-ccd8-483d-b041-30ec26cfa4e5@s8g2000prg.googlegroups.com> On Mar 15, 1:01?pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 14 Mar 2008 11:32:41 -0700, Lie wrote: > > No, there is no need for "void" return type, what I meant is that > > everything that's not said in the documentation should be assumed to > > be an implementation detail, a method or a function that doesn't say > > anything about its return type should be assumed to return an > > implementation detail (which basically means: Don't rely on this). The > > fact that list.append returns none is just a coincidence, you might > > encounter another list.append that returns different thing some time > > in the future, or the far future, or perhaps at the end of the > > galaxy's life. > > I expect functions with no documentation of what they return to return > `None`. ?Assuming they are documented at all, of course. ?:-) > > It's like not writing a ``return`` statement in the code: there's always an > implicit ``return None`` at the end of every function. I personally won't to rely on it. Sometimes a return statement might be documented, but not complete enough, like this: def genericadd(a, b): """ Adds two number, returns the same as longadd if either operands are long type and returns the same as intadd if all operands are int type. """ if isinstance(a, long) or isinstance(b, long): return longadd(a, b) if isinstance(a, int) and isinstance(b, int): return intadd(a, b) return "Error" This function is written badly on purpose to simulate what a less-than- intelligent programmer might write, which is in no control of ours as a class user. From larry.cebuala at gmail.com Wed Mar 12 06:26:58 2008 From: larry.cebuala at gmail.com (Larry) Date: Wed, 12 Mar 2008 03:26:58 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array Message-ID: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> Dear all, I'm new to Python. I have a file (an image file actually) that I need to read pixel by pixel. It's an 8-bit integer type. I need to get the statistics like mean, standard deviation, etc., which I know a little bit already from reading numpy module. What I want to know is how to get the number of occurences of numeric element in an array. Say, b = array(([2, 2, 3, 4, 5, 5]) b.count(2) certainly does not work. Is there any more efficient way other than converting this as string characters? My data will produce a fairly large array like 400x400 = 160000 values. Hoping you guys can help me. Larry From castironpi at gmail.com Sun Mar 2 13:33:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 10:33:07 -0800 (PST) Subject: Question on importing and function defs References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> Message-ID: <04a7dfa1-a28b-4b52-aa3d-24b57bdbba3e@i29g2000prf.googlegroups.com> On Mar 2, 11:44?am, Steve Holden wrote: > TC wrote: > > On Mar 2, 11:37 am, Gary Herron wrote: > >> TC wrote: > >>> I have a problem. ?Here's a simplified version of what I'm doing: > >>> I have functions a() and b() in a module called 'mod'. ?b() calls a(). > >>> So now, I have this program: > >>> from mod import * > >>> def a(): > >>> ? ? blahblah > >>> b() > >>> The problem being, b() is calling the a() that's in mod, not the new > >>> a() that I want to replace it. ?(Both a()'s have identical function > >>> headers, in case that matters.) ?How can I fix this? > >>> Thanks for any help. > >> Since b calls mod.a, you could replace mod.a with your new a. ?Like > >> this: ?(Warning, this could be considered bad style because it will > >> confuse anyone who examines the mod module in an attempt to understand > >> you code.) > > >> ? import mod > > >> ? def replacement_a(): > >> ? ? ... > > >> ? mod.a = replacement_a > > >> ? ... > > >> Or another option. ?Define b to take, as a parameter, the "a" function > >> to call. > > >> In mod: > > >> ? def a(): > >> ? ?... > > >> ? def b(fn=a): ?# to set the default a to call > >> ? ? ... > > >> And you main program: > > >> ? from mod import * > > >> ? def my_a(): > >> ? ? ... > > >> ? b(my_a) > > >> Hope that helps > > >> Gary Herron > > > Thanks for the tips, but no luck. ?This is for a homework assignment, > > so there are a couple of requirements, namely that I can't touch > > 'mod', and I have to do 'from mod import *' as opposed to 'import > > mod'. > > > So the first method you suggested won't work as written, since the mod > > namespace doesn't exist. ?I tried a = replacement_a, but b() is still > > calling mod's version of a() for some reason. ?And because I can't > > touch mod, I can't use your second suggestion. > > > In case I somehow oversimplified, here's the actual relevant code, in > > 'mod' (actually called 'search'). ?The first fn is what I've been > > calling a(), the second is b(). > > > (lots of stuff...) > > > def compare_searchers(problems, header, > > searchers=[breadth_first_tree_search, > > ? ? ? ? ? ? ? ? ? ? ? breadth_first_graph_search, > > depth_first_graph_search, > > ? ? ? ? ? ? ? ? ? ? ? iterative_deepening_search, > > depth_limited_search, > > ? ? ? ? ? ? ? ? ? ? ? astar_search]): > > ? ? def do(searcher, problem): > > ? ? ? ? p = InstrumentedProblem(problem) > > ? ? ? ? searcher(p) > > ? ? ? ? return p > > ? ? table = [[name(s)] + [do(s, p) for p in problems] for s in > > searchers] > > ? ? print_table(table, header) > > > def compare_graph_searchers(): > > ? ? compare_searchers(problems=[GraphProblem('A', 'B', romania), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? GraphProblem('O', 'N', romania), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? GraphProblem('Q', 'WA', australia)], > > ? ? ? ? ? ? header=['Searcher', 'Romania(A,B)', 'Romania(O, N)', > > 'Australia']) > > > That's the end of the 'search' file. ?And here's my program, which > > defines an identical compare_searchers() with an added print > > statement. ?That statement isn't showing up. > > > from search import * > > > def compare_searchers(problems, header, > > searchers=[breadth_first_tree_search, > > ? ? ? ? ? ? ? ? ? ? ? breadth_first_graph_search, > > depth_first_graph_search, > > ? ? ? ? ? ? ? ? ? ? ? iterative_deepening_search, > > depth_limited_search, > > ? ? ? ? ? ? ? ? ? ? ? astar_search, best_first_graph_search]): > > ? ? def do(searcher, problem): > > ? ? ? ? p = InstrumentedProblem(problem) > > ? ? ? ? searcher(p) > > ? ? ? ? return p > > ? ? table = [[name(s)] + [do(s, p) for p in problems] for s in > > searchers] > > ? ? print 'test' > > ? ? print_table(table, header) > > > compare_graph_searchers() > > Since you've admitted it's for homework, here are a couple of hints. > > 1. The b() function is *always* going to try and resolve its references > in the namespace it was defined in; > > 2. The technique you need is most likely known as "monkey patching". > When you say "I can't touch mod", that may mean "the source of mod must > remain unchanged", which is subtly different. Google is your friend ... > > Good luck with your assignment. > > regards > ? Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/- Hide quoted text - > > - Show quoted text - You can use 'settrace' to intervene. You might be able to delete the 'a'. From paddy3118 at googlemail.com Sun Mar 23 12:14:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 23 Mar 2008 09:14:47 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: On Mar 23, 3:53 pm, John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). > > John Nagle As others have stated, if : is false for built-in container types such as dicts, lists, sets, tuples,... Its nice to make any of your owh container types follow the same convention too. - Paddy. From kmgrds at gmail.com Sun Mar 30 16:21:26 2008 From: kmgrds at gmail.com (kmgrds at gmail.com) Date: Sun, 30 Mar 2008 13:21:26 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig Message-ID: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> Hello everybody, I'm building a python module to do some heavy computation in C (for dynamic time warp distance computation). The module is working perfectly most of the time, which makes it so difficult to track down the error. and I finally figured out that the strange segmentation faults I get from time to time have something to do with the length of the vectors I'm looking at. (So in this minimal example I'm doing completely useless distance measures on vectors with the same entry in all dimensions, but the errors seem to have nothing to with the actual values in the vectors, only with the lengths.) But somehow I haven't quite gotten the essential ideas of what one has to do to debug this module and I hope someone can give me some advice. The main problem is probably somewhere around passing the double vectors to the c module or reserving and freeing memory. so, for example list1,list2 = [0.1 for i in range(555)],[0.2 for i in range(1874)] ctimewarp(list1,list2) # see python file below works perfectly fine and if the vector has one more element list1,list2 = [0.1 for i in range(555)],[0.2 for i in range(1875)] ctimewarp(list1,list2) it dies with a simple Segmentation fault nothing more said :-S For very small lists again, no problem: list1,list2 = [0.1 for i in range(3)],[0.2 for i in range(4)] ctimewarp(list1,list2) for intermediate size I get an error and more information: list1,list2 = [0.1 for i in range(22)],[0.2 for i in range(99)] ctimewarp(list1,list2) give: *** glibc detected *** python: free(): invalid next size (fast): 0x0804d090 *** ======= Backtrace: ========= /lib/i686/libc.so.6[0xb7bed4e6] /lib/i686/libc.so.6(cfree+0x90)[0xb7bf1010] /home/kim/Documents/pythonprojects/alignator/ _timewarpsimple.so[0xb7aadc0c] /home/kim/Documents/pythonprojects/alignator/ _timewarpsimple.so[0xb7aae0db] /usr/lib/libpython2.5.so.1.0(PyCFunction_Call+0x107)[0xb7d5d8e7] ======= Memory map: ======== 08048000-08049000 r-xp 00000000 03:05 2344438 /usr/bin/python 08049000-0804a000 rwxp 00000000 03:05 2344438 /usr/bin/python 0804a000-080f3000 rwxp 0804a000 00:00 0 [heap] ....(truncated) When looping over these lengths of vectors, e.g. as I did in the python file below, it runs smooth for thousands of times before dying at 938 for the first list length and 1110 for the second. i noticed that the sum of the list lengths is 2048=2^11 and it often seems to die around that but that's just a guess... If anyone has a little advice or a code snippet on how to pass float lists to modules or anything of that kind, i would appreciate it very much! thanks a lot in advance cheers kim __________________________________ Below you can see the c file, the .i file for swig, and a little python script producing the errors: _______________ .c file: /* File : timewarpsimple.c */ #include #include #include double timewarp(double x[], int lenx, double y[], int leny) { // printf ("%d *******************************\n", lenx); // printf ("%d *******************************\n", leny); double prev; double recx[lenx+1]; double recy[leny+1]; double warp[lenx+2][leny+2]; int i,j; prev = 0.0; for (i = 0; i < lenx; i++) { recx[i]=x[i]-prev; prev = x[i]; } recx[lenx]=1.0-prev; prev = 0.0; for (i = 0; i < leny; i++) { recy[i]=y[i]-prev; prev = y[i]; } recy[leny]=1.0-prev; // recency vectors are done // let's warp warp[0][0]=0.0; for (i = 1; i < lenx+2; i++) { warp[i][0]=1.0; } for (j = 1; j < leny+2; j++) { warp[0][j]=1.0; } for (i = 1; i < lenx+2; i++) { for (j = 1; j < leny+2; j++) { warp[i][j]=fabs(recx[i-1]-recy[j-1]) + MIN(MIN(warp[i-1][j],warp[i] [j-1]),warp[i-1][j-1]); } } return warp[lenx+1][leny+1]; } ________________ .i file: %module timewarpsimple %include "carrays.i" %array_functions(double, doubleArray); %{ double timewarp(double x[], int lenx, double y[], int leny); %} double timewarp(double x[], int lenx, double y[], int leny); ________________ here's what I'm doing to compile: swig -python timewarpsimple.i gcc -c timewarpsimple.c timewarpsimple_wrap.c -I/usr/include/ python2.5/ ld -shared timewarpsimple.o timewarpsimple_wrap.o -o _timewarpsimple.so which goes thru without any problem. ________________ .py file: #!/usr/bin/python # -*- coding: UTF-8 -*- import timewarpsimple def ctimewarp(list1,list2): """ takes two lists of numbers between 0 and 1 and computes a timewarp distance """ print "timewarping" alen = len(list1) blen = len(list2) a = timewarpsimple.new_doubleArray(alen*4) # Create the first array # Why I have to reserve 4 times more space I don't know, but it's the only way to make it work... b = timewarpsimple.new_doubleArray(alen*4) # Create the second array for i,p in enumerate(list1): timewarpsimple.doubleArray_setitem(a,i,p) # Set a value. (a,i,0) gives identical errors for i,p in enumerate(list2): timewarpsimple.doubleArray_setitem(b,i,p) # Set a value warp = timewarpsimple.timewarp(a,alen,b,blen) print "result",warp timewarpsimple.delete_doubleArray(a) timewarpsimple.delete_doubleArray(b) #a,b = None,None return warp ########## the tests: #list1,list2 = [0.1 for i in range(22)],[0.2 for i in range(99)] #ctimewarp(list1,list2) for x in range(888,1111): for y in range(888,1111): list1,list2 = [0.1 for i in range(x)], [0.2 for i in range(y)] print len(list1),len(list2),len(list1)+len(list2) ctimewarp(list1,list2) From stef.mientki at gmail.com Fri Mar 14 05:32:11 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 14 Mar 2008 10:32:11 +0100 Subject: how to pass the workspace ? In-Reply-To: <13tk7796gt4u3b7@corp.supernews.com> References: <47D72CDD.9000706@gmail.com> <47D733A7.2070808@islandtraining.com> <13tk7796gt4u3b7@corp.supernews.com> Message-ID: <47DA461B.1010703@gmail.com> Thanks, Gary and Dennis, Dennis Lee Bieber wrote: > On Thu, 13 Mar 2008 21:35:42 +0100, Stef Mientki > declaimed the following in comp.lang.python: > > > >> The result of globals and locals in the file is eaxctly the same and >> none of them mentions 'NewVar' and 'beer' >> The result of tree_globs and tree_locals is exactly the same and both >> doesn't contain 'NewVar' and 'beer' >> Maybe it's very simple after reading the manual, >> but apperently I'm missing the essential clue. >> What am I missing ? >> >> > Use of globals() and locals() vs globals and locals? > Well I get an error with that. But you both give me some ideas, and it's working now: - I don't need the locals - from the file where the execute is launched, you must use the normal dictionary call tree_globs = {} tree_globs [ 'NewVar' ] = 24 filename = self.Get_Editor_Filename (nodename) execfile ( filename, tree_globs ) print self.tree_globs['NewVar'] print self.tree_globs['beer'] where the code in the executed file is: beer = 'testje' the output I get is: 24 testje and the "self.tree_globs" travels perfectly though all the files executed. cheers, Stef From SubjectEgo at gmail.com Thu Mar 20 23:05:29 2008 From: SubjectEgo at gmail.com (Jeremy N) Date: Thu, 20 Mar 2008 20:05:29 -0700 (PDT) Subject: Trouble with variable "leakage"? Message-ID: I am working with Python in Maya, and have run into a problem with a variable changing its contents without being scripted to do so. The various print() statements below were from my efforts to track down where it was occurring. I left them in so that anyone running this will more easily see what's happening. On the line that reads 'dx = d1 / dx ; print("dx = %f" % dx)' there is something happening to the variable that is being printed repeatedly between the lines. The print statements prior to this particular line print '...xlist[0][1] = 0.5' . However, on this line, that variable is being updated to reflect a new value, when no assignment to that variable has been made at that time. This leads me to believe that the variables 'dx' and 'xlist[0][1]' are inexplicably linked. I have no idea why. Please help me. a=[5,0,3,4] b=[8,3,0,10] c=[2,4,10,0] nlist = [a,b,c] xlist = [[],[],[]] for i in range(len(nlist)) : relist = list(nlist) relist.pop(i) dlist = list(nlist[i]) dlist.pop(0) ; dlist.pop(i) for j in range(len(relist)) : d1 = float(nlist[i][0]) d2 = float(relist[j][0]) dx = float(dlist[j]) r1 = 1 - ( abs(d1-dx) / float(d2) ) if r1 == 0.0 : r1 += (d1 < d2) xlist[i].append(float(r1)) del d1, d2, dx, relist, dlist ylist = list(xlist) print(xlist) print(ylist) for i in range(len(xlist)) : relist = list(xlist) relist.pop(i) for j in range(len(relist)) : print( "!!!!!!!!!!!!!!! NEW LOOP AT ( %d:%d ) !!!!!!!!!!!!!!!" % ( i, j ) ) print("%s / (%s + %s)" % ( str(xlist[i][j]), str(xlist[i][j]), str(relist[j][( (i!=0) * ((j>=i)+(i-1)) )]) ) ) d1 = float(xlist[i][j]) ; print("d1 = %f" % d1) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) d2 = relist[j][( (i!=0) * ((j>=i)+(i-1)) )] ; print("d2 = %f" % d2) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) dx = d1 + d2 ; print("dx = %f" % dx) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) dx = d1 / dx ; print("dx = %f" % dx) ylist[i][j] = float(dx) ; #print(ylist[i][j]) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) print( "||| xlist[2][0] = %s" % str(xlist[2][0]) ) print( "...\nxlist = %s\n..." % str(xlist) ) print(xlist) print(ylist) From michael.wieher at gmail.com Sun Mar 16 10:05:19 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:05:19 -0500 Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? In-Reply-To: <20080316132140.GA24529@piper.oerlikon.madduck.net> References: <20080316132140.GA24529@piper.oerlikon.madduck.net> Message-ID: 2008/3/16, martin f krafft : > > Hi, > > xmlrpclib.dumps((None,), allow_none=True) yields > > '\n\n\n\n' > > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' > > Those are valid XML and valid XML-RPC, but isn't. > > Thanks for any thoughts... > > > -- > martin | http://madduck.net/ | http://two.sentenc.es/ > > a farmer is a man outstanding in his field. > > spamtraps: madduck.bogus at madduck.net No real idea, but to me it seems like a decent way to be double-sure that you actually got the complete and correct dump-file... otherwise, you might be just missing part of it... maybe there's a real reason though? -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.wieher at gmail.com Mon Mar 17 14:36:22 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 13:36:22 -0500 Subject: Missing PyObject definition In-Reply-To: <-eidnZbyjq-bAkPanZ2dnUVZ_rOqnZ2d@comcast.com> References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> <-eidnZbyjq-bAkPanZ2dnUVZ_rOqnZ2d@comcast.com> Message-ID: 2008/3/17, James Whetstone : > > Hi, > > Yeah, I've included python.h and object.h but the compiler still complain > about not finding PyObject. It's weird. So I'm developing and App on > windows using VS 8.0. I've intalled Python 2.5 and have added the include > directory to my project's configuration. I'm also using boost.python in > another application to wrap my C++ classes. > > Here's the C++ class I'm wrapping: > > class widget > { > > public: > > widget(const string &name, unsigned int myint) : > { > > } > > static unsigned int __stdcall Callback(void * voidPtr); > void startMessageHandler(); > void stopMessageHandler(); > virtual void handleMessage(void *message)=0; > > }; > > So the idea here is that the Python user will derive from widget and > override the virtual method "handleMessage". A thread is spawned by > "startMessageHandler()" that does some work and periodically calls > "handleMessage" passing it a chunk of memory. This memory is intended to > be > zero-copy. Okay, so I've implemeted this class to set up the class for > Python: > > class py_widget : public widget > { > public: > py_widget(PyObject *p, const string &name, unsigned int myint) : > self(p), > py_widget(name, myint) > { > } > > void handleMessage(void *message); > > PyObject *self; > > }; > > where handleMessage has the following implementation: > > void PyAsyncQueue::handleMessage(void *message) > { > //get the memory block size with a method not shown here > int size = getSize(message); > > //create a buffer object so the Python users can access memory block > directly. > > PyObject *obj = PyBuffer_FromReadWriteMemory( message, size ) ; > > //now what ???? > > //I've tried calling the method directly based on some info I found > some documentation, but this doesn't > //compile because the compile can't find PyObject. Also, I really > know > what it looks like anyways. > //self->attr("handleMessage")(obj); > > //This boost.python call doesn't work either. > //call_method(self, "handleMessage", obj); > } > > > Thanks for your suggestions on this, > James > > > > "Jeff Schwab" wrote in message > news:mvadnfg_hOdmDEPanZ2dnUVZ_u2mnZ2d at comcast.com... > > James Whetstone wrote: > >> I'm trying to access a PyObject directly from C++ for the purpose of > >> calling method on a Python object that is an intance of a derived C++ > >> class. My problem is that the compiler is complaining about not > PyObject > >> not being defined. Has anyone run into the problem? Where is PyObject > >> defined? > > > > Are you using Python's C API? > > > > Did you #include "Python.h" before using PyObject? > > > > PyObject is a C-style struct defined in object.h, which is in turn > > included by Python.h. Does your compiler know where to look for those > > headers? If you are getting messages of the form "error: cannot find > > Python.h," then add -Iyour_python_root/include/python2.5 (or whatever > > version) to the CXXFLAGS variable in your makefile, or to your > compiler's > > command line. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > If you're using MS-Visual Studio, be sure you really included the file where you think you did... I ran into some stupidity of my own, trying to put include files in the "library" path and vice versa. If you have "Python.h" included properly, you should be able to compile some small test-code using PyObject. If you can't, you haven't got it included correctly. That's where I'd start. If there's other bugs in your code, thats a different issue, but if the compiler can't find class-X defined in file-Y, then you need to double-check your include, include-path, and so on and so forth. Also, don't forget that just because the include directory is on your project's path, that the actual file itself needs to be included. When running in VS 6.0 I had to place my includes in some awfully strange places. Redundant includes don't hurt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Mar 21 03:32:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 00:32:40 -0700 (PDT) Subject: decoupling a certain method Message-ID: <04f0a593-c47d-4c50-ad8e-d81d0cfa40a7@m44g2000hsc.googlegroups.com> class Proxy: def __init__( self, proxer ): object.__setattr__( self, '_proxer', proxer ) ComplexObject= object viewA= type( 'ComplexView', ( Proxy, ComplexObject ), { '__eq__': lambda self, other: abs( self._proxer- other )<= 1 } ) j= range( 10 ) g= 5 for a in j: p= viewA( a ) print( p.__class__.__name__, p._proxer, p== g ) Subclassing provides an alternative to delegation and proxying. I got this far, but I'm lost: How do I allow g= proxy( 5 ) in line 11? Do I need to? If I do it, I get: TypeError line 7: unsupported operand type(s) for -: 'int' and 'ComplexView' From troyj1978 at gmail.com Thu Mar 13 16:16:05 2008 From: troyj1978 at gmail.com (troyj1978 at gmail.com) Date: Thu, 13 Mar 2008 13:16:05 -0700 (PDT) Subject: This actually works. Message-ID: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> I couldn't believe it. Screw programming Python anymore! I'm totally serious. This actually works! It is SO EASY to make money this way. Anyone, and I mean ANYONE can do it. You should start seeing returns within a day or two. Do yourself a favour and at least check it out: http://agentb.affstocks.hop.clickbank.net/ Troy From shakefu at gmail.com Fri Mar 7 17:08:18 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:08:18 -0800 (PST) Subject: Intelligent Date & Time parsing Message-ID: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> I'm new to python and I was wondering if there are any intelligent date/time parsing modules out there. I've looked at strptime (or whichever it is) and mxDateTime from the eGenix package. I need something to parse user input for a django app, and it's awesome to be able to write "last monday", "a year ago", or "10pm tuesday" like PHP's strtotime. So are there any modules that allow for that kind of parsing? From sambo at voidstar.com Thu Mar 6 22:35:18 2008 From: sambo at voidstar.com (Sam) Date: Thu, 06 Mar 2008 22:35:18 -0500 Subject: access to base class __init__ References: <13suutrsb4bab8b@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > > I'm not sure why you need to subclass from threading.Thread if all > the thread control is being done internal to this class. Subclassing > means being able to do things like: > Well it was the first thing that occured to me how to have private data for each thread ( IP, PORT , CURDIR if I decide to serve files. ) although I did come across some private_data CLASS in the docs. > mySH = client_socket_handler(some, args) > ... > mySh.start() hope I can call self.start() from __init__() or self.socket_handler() > > ... ie; instances of your class behave just like an extended instance of > the Thread class; but the user of this class never sees that it IS a > thread. I believe the other facet is that when subclassing from Thread, > one overloads the run() method AS the target instead of passing some > other function as a target argument and letting the parent run() method > call it. > > > So why not just make the thread an attribute of the class instead. > > Maybe that would be clearer. Starting to wonder if I could return thread name this way, then again, I think part reason for this aproach was the fact that once started it could finish/crash all on it's lonesome and it's instance could wait for garbage collection. >> self.socket = cs >> self.rhost_addr = remote_address >> print "client_socket_handler.__init__(): ", self.socket, >> self.rhost_addr >> # t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) >> # t1.start() > > Which is about what you were doing here, but should have used > self.t1 =... > self.t1.start() > Well this shouldn't realy be here just stuff I pasted over. Which brings me to a question how to start my thread internaly. Once I managed to call __init__() I should be able to call self.start() nicht var? or is it vahr? >> self.start() >> print "client_socket_handler.__init__(): ", self.socket, >> self.rhost_addr >> print "client_socket_handler.__init__(): enumerate()", >> threading.enumerate() >> >> def socket_handler( self, invar, indict ): > > You aren't passing any arguments to this method. > >> threadname = self.getName() >> print "\"%s started\"" % threadname >> print "client_socket_handler.socket_handler() invar: ", invar >> instr = self.socket.recv( 500 ) >> # print instr >> req_lines = string.split( instr, "\r" ) >> for line in req_lines: >> line.strip( "\n") > > What do you expect the behavior to be if a new-line is embedded and > not adjacent to a carriage return? > oops: #handle macs self.socket.send( "500 Inferior systems not permited.\r\n" ) self.socket.close() Heh. Besides I don't think NL is permisible as line separator. the command is at the beginnign and I don't expect to support any multitude of tags. From tejovathi.p at gmail.com Thu Mar 20 06:40:54 2008 From: tejovathi.p at gmail.com (Teja) Date: Thu, 20 Mar 2008 03:40:54 -0700 (PDT) Subject: Regarding Threads and locals() Message-ID: <8171f7f2-1bd6-4518-b678-c6267870b05b@h11g2000prf.googlegroups.com> Hi all, I have a GUI applicaion(along with threads). When the run button is pressed in the GUI a separate thread starts( Thread is created using beginthreadex) and does the required activity. Now, while the thread is being executed, i want the locals() present inside the thread's run function to be avaialbe in the GUI class from where the thread class is being created EG: ---------------------- main.py -------------------------- class WorkerThread(threading.Thread): def __init__(self, ): threading.Thread.__init__(self) # Start the thread and invoke the run method self.start() def run(self): # Start the thread. It executed self.func() as a separate thread self.workerThread, tid = win32process.beginthreadex(None, 0 , self.func ,(), 1) ....... def func(self): execfile(temp.py) class GUI(wxFrame): def __init__(self): ..... ..... def CreateThread(self): self.workerThread = WorkerThread() if name == _main_: ..... . .... . ..... --------------------- temp.py ------------------ i = 1 j = 2 k = 4 while(10000): print i print j print k i = 1+1 j = j+2 k = k + 3 Now, while the thread is executin func and printing i, j, k , In the main GUI thread how do i get the values of i, j ,k I tried with sys.modules, sys._current_frames, vars(). But nothing worked out. Ideally the locals() of func() should be passed to the GUI thread, how? From R.Brodie at rl.ac.uk Fri Mar 14 11:58:58 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 14 Mar 2008 15:58:58 -0000 Subject: %x unsigned? References: <87skytbbbc.fsf@mulj.homelinux.net> Message-ID: "Hrvoje Niksic" wrote in message news:87skytbbbc.fsf at mulj.homelinux.net... > The %x conversion specifier is documented in > http://docs.python.org/lib/typesseq-strings.html as "Unsigned > hexadecimal (lowercase)." What does "unsigned" refer to? It's obsolete, a fallout of int/long int unification. See http://www.python.org/dev/peps/pep-0237/ From michael.wieher at gmail.com Wed Mar 19 12:24:44 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 19 Mar 2008 11:24:44 -0500 Subject: Python to C/C++ In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: I think py2exe does this, but it might be a bit bloated 2008/3/19, Blubaugh, David A. : > > To All, > > Has anyone worked with a translator that will translate python to c/c++ > source code? I know that there is already one translator of this nature (shedskin > compiler) out there. However, it is still in the beta stage of > development. Does anyone know of a more developed version of a translator > of this nature? > > Thanks, > > David Blubaugh > > This e-mail transmission contains information that is confidential and may > be privileged. It is intended only for the addressee(s) named above. If > you receive this e-mail in error, please do not read, copy or disseminate it > in any manner. If you are not the intended recipient, any disclosure, > copying, distribution or use of the contents of this information is > prohibited. Please reply to the message immediately by informing the sender > that the message was misdirected. After replying, please erase it from your > computer system. Your assistance in correcting this error is appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun Mar 9 12:55:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 14:55:15 -0200 Subject: help on file storage for split multi part download References: <0c422a07-3c07-499f-87da-f82a6a81ed52@s37g2000prg.googlegroups.com> Message-ID: En Sat, 08 Mar 2008 08:27:12 -0200, escribi?: > On Mar 7, 2:14 pm, "Gabriel Genellina" wrote: >> En Fri, 07 Mar 2008 04:16:42 -0200, escribi?: >> >> > BUT the thing thats going in my mind is thread safety. i plan to start >> > each part of the filedownloadin a different thread. and then when >> > each thread had downloaded more than 100kb (or eof or boundary >> > reached) write the buffer to the disk. can this be achieved using >> > mutex ? i have never shared objects between threads. >> >> Use a different (single) thread to write the file; the others put write >> requests on a Queue.queue object, and the writer just gets the requests >> and processes them. >> >> > is there a way to write this without using threads at all ??? >> >> Using asyncore, and perhaps the Twisted framework. > > asyncore is basically a server thing right? asyncore is usually used to build servers, because in a server you want to handle many requests with few resources, but you can use it to write a client too. Here is an example: http://effbot.org/zone/asyncore-ftp-client.htm How many files and how many simultaneous connections do you plan to handle? Using multiple threads to download and a single thread to write, connected thru a queue, looks like the "simplest thing that probably works" to me unless you have other constraints. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Mar 18 22:58:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 23:58:15 -0300 Subject: Comunicate processes with python References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> <267c4040803181040q2a70b91w8f92ff59359843fb@mail.gmail.com> Message-ID: En Tue, 18 Mar 2008 14:40:29 -0300, Adri?n Bravo Navarro escribi?: > That was what we were thinking of, so if there is not some kind of easy > python magic we will probably use some sockets. You have pipes too, and a memory mapped file guarded by a semaphore. -- Gabriel Genellina From Dodin.Roman at gmail.com Mon Mar 17 13:22:31 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 10:22:31 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Message-ID: <9192affb-3a3f-4558-909b-d9734c1b1ad2@u10g2000prn.googlegroups.com> On 17 ???, 15:48, "Gabriel Genellina" wrote: > En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > > > i have a problem with this modules py2exe + pywinauto + sendkeys used > > together. > > > In my script i'm using this expression > > app.window_(title="SJphone").Edit.TypeKeys("Test is > > running",with_spaces=True) > > > TypeKeys is using SendKeys module i suppose. > > Does it work as a normal script, without using py2exe? > > > my setup.py looks like that: > > > from distutils.core import setup > > import py2exe > > > setup( > > options = {"py2exe": {"compressed": 1, > > "optimize": 0, > > "bundle_files": 1, > > "packages": ["encodings", "pywinauto", > > "pywinauto.controls", "pywinauto.tests"] } }, > > zipfile = None, > > console=["hosts.py"] > > ) > > Perhaps you have to include SendKeys explicitely. I think pywinauto > doesn't require SendKeys, but uses it if already installed. > > -- > Gabriel Genellina pywinauto uses sendkeys when performs TypeKeys function. when i include sendkeys to my package's list i have an error posted below: "No module named SendKeys" From deets at nospam.web.de Wed Mar 26 07:02:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 12:02:18 +0100 Subject: _tkinter fails when installing Python 2.4.4 References: <64tahuF2absebU1@mid.uni-berlin.de> <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> Message-ID: <64uoqiF2dcihhU1@mid.uni-berlin.de> jgelfand wrote: > On Mar 25, 5:52 pm, "Diez B. Roggisch" wrote: >> jgelfand schrieb: >> >> >> >> > I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat >> > Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ >> > usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but >> > I get the following error message when I run "make": >> >> > building '_tkinter' extension >> > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - >> > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ >> > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ >> > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ >> > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ >> > yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ >> > usr/local/yosi/Python-2.5.2/Modules/_tkinter.o >> > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - >> > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ >> > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ >> > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ >> > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ >> > yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ >> > usr/local/yosi/Python-2.5.2/Modules/tkappinit.o >> > gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ >> > Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ >> > yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ >> > lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - >> > ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so >> > *** WARNING: renaming "_tkinter" since importing it failed: build/ >> > lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents >> >> > Any suggestions / ideas as to what is going wrong? I don't get any >> > other warnings or errors on the other modules. Thanks -- Yosi >> >> You are aware that the above shows python 2.5 as the version that is >> being used for compilation? >> >> Diez > > Sorry. I get the same error messages for Python 2.4.4, Python 2.4.5, > and Python 2.5. The software package I'm trying to build from source > requests that I install Python 2.4.4, so I'm interesting in solutions > for that particular distribution. I think the actual problem is that the linking doesn't find the XftGlyphExtends. I can only guess, but it might be related to 64-bit-problems. Make sure you have the library that contains the XftGlyphExtends is available in the lib64 dirs and so forth. Diez From torriem at gmail.com Sat Mar 1 21:50:52 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Mar 2008 19:50:52 -0700 Subject: Question about lambda and variable bindings Message-ID: <47CA160C.3000305@gmail.com> I need to use a lambda expression to bind some extra contextual data (should be constant after it's computed) to a call to a function. I had originally thought I could use something like this demo (but useless) code: funcs=[] def testfunc(a,b): print "%d, %d" % (a,b) for x in xrange(10): funcs.append(lambda p: testfunc(x+2,p)) Now what I'd like is to call, for example, funcs[0](4) and it should print out "2,4". In other words I'd like the value of x+2 be encoded into the lambda somehow, for funcs[x]. However the disassembly shows this, which is reasonable, but not what I need: >>> dis.dis(funcs[0]) 2 0 LOAD_GLOBAL 0 (testfunc) 3 LOAD_GLOBAL 1 (x) 6 LOAD_CONST 0 (2) 9 BINARY_ADD 10 LOAD_FAST 0 (p) 13 CALL_FUNCTION 2 16 RETURN_VALUE The LOAD_GLOBAL 1 (x) line is definitely a problem. For one it refers to a variable that won't be in scope, should this lambda be called from some stack frame not descended from the one where I defined it. So how can I create a lambda expression that calculates a constant based on an expression, rather than referring to the object itself? Can it be done? Michael From max at alcyone.com Thu Mar 13 19:30:49 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Mar 2008 16:30:49 -0700 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: References: Message-ID: <-cudnSGj6P-2JETanZ2dnUVZ_vShnZ2d@speakeasy.net> Dave Kuhlman wrote: > Basically, the above code is saying that foo.foobar is not the same as > getattr(foo, 'foobar'). Python promises that the behavior is the same. It does not promise that the _objects_ will be the same, which is what `is` determines. That is, you're not doing a useful test here. In Python, bound methods are dynamically generated. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There is no present or future; only the past, happening over and over again, now. -- Eugene O'Neill From tmp1 at viltersten.com Mon Mar 3 15:21:17 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Mon, 3 Mar 2008 21:21:17 +0100 Subject: Polymorphism using constructors Message-ID: <6333v2F25lleoU1@mid.individual.net> I'm writing a class for rational numbers and besides the most obvious constructor def __init__ (self, nomin, denom): i also wish to have two supporting ones def __init__ (self, integ): self.__init__ (integ, 1) def __init__ (self): self.__init__ (0, 1) but for some reason (not known to me at this point) i get errors. My suspicion is that it's a syntax issue. Suggestions? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From darcy at druid.net Sun Mar 30 11:28:27 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 30 Mar 2008 11:28:27 -0400 Subject: License of Python In-Reply-To: <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <20080330112827.0c5dc431.darcy@druid.net> On Sun, 30 Mar 2008 08:16:39 -0700 (PDT) iu2 wrote: > > > I'd like to use Python in a commercial application. In fact I would > > > like to write the application entirely in Python. > > > But I think I wouldn't like telling what language the application is > > > written in. > > > > Why is the reason for that? > > Due to Competitors... I don't want to expost the language I use You might hide it from many of your customers but don't count on hiding it from your competitors. Chances are, if they don't know it because they just don't care. -- 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 nagle at animats.com Mon Mar 10 01:12:16 2008 From: nagle at animats.com (John Nagle) Date: Sun, 09 Mar 2008 22:12:16 -0700 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: <13t76hsmp060e55@corp.supernews.com> References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> Message-ID: <47d4c107$0$36349$742ec2ed@news.sonic.net> Steven D'Aprano wrote: > On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > >> On 9 Mrz., 06:30, Steven D'Aprano > cybersource.com.au> wrote: >> Is it really so exotic that it requires the demand for more use cases? > > > Are the existing solutions really so incomplete that we need yet another > solution? > > What problem are you trying to solve with SoftExceptions? I actually implemented something like "soft exceptions" in a LISP program long ago. I called them "gripes". They were a way that a function could complain about something it wanted the caller to fix. The caller could either fix it or decline to do so. This was for a robotic planning application, where one module had detected that some precondition that it needed wasn't satisfied. This was usually something like some physical object being in the wrong place for a later operation, and a previously planned move needed to be modified. Passing the problem back to the caller sometimes allowed an easy fix, rather than aborting the whole plan and building a new one. This isn't a common problem. In the rare cases that it is needed, it can be implemented with callbacks. It doesn't require a language extension. John Nagle From gagsl-py2 at yahoo.com.ar Wed Mar 26 02:04:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 03:04:49 -0300 Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk escribi?: > On Mar 25, 9:25?pm, "Gabriel Genellina" > wrote: >> En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? >> escribi?: >> >> >> ? ?i'm trying to call subprocess.popen on the 'rename' function in >> >> linux. ?When I run the command from the shell, like so: >> >> >> rename -vn 's/\.htm$/\.html/' *.htm >> >> >> it works fine... however when I try to do it in python like so: >> >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ >> >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) >> >> >> print p.communicate()[0] >> >> >> nothing gets printed out (even for p.communicate()[1]) >> >> I'd try with: >> >> p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], >> ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, >> ? ? ? ?shell=True) >> >> (note that I added shell=True and I'm using a raw string to specify the >> reg.expr.) > > Thanks Gabriel, > I tried the new command and one with the raw string and single > quotes, but it is still giving me the same results (no output). any > other suggestions? My next try would be without the single quotes... -- Gabriel Genellina From timr at probo.com Sat Mar 29 21:10:11 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 30 Mar 2008 01:10:11 GMT Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> Message-ID: <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> aiwarrior wrote: > >I'm sorry about not saying showing the libraries. It was not on >purpose. You didn't make any comment on the rest of Gerhard's suggestion, nor does it appear that you took any action to correct them. You should get out of the habit of using extra parentheses in "if" and "print" statements. They are not needed in Python, and they make the code more difficult to read. > self.cursor.execute( "CREATE TABLE database >(album,filepath)" ) Note the order of the fields: album, then path. > def add_entry( self, eone , etwo ): #Add entry to database > self.cursor.execute( "INSERT INTO database (album,filepath) >VALUES (?,?)", ( eone , etwo ) ) > return 1 #TODO: exception handler Again note the order of the fields here: album, then path. > def get_value( self, column ): > self.cursor.execute( "SELECT %s FROM database" % column ) > for n in self.cursor: > print n I suspect you wanted "self.cursor.fetchall()" there, but since you don't call it, it doesn't matter yet. > db.add_entry( joined, audio['album'] ) Now note the order that you supply the fields: path first, album second. You are inserting the fields in the wrong order here. >This is all the code. Some of that try pass code is just something i >glued to create a clean slate database file And such gluing is a very bad idea, because it is apparently hiding the real cause of your problems. Get rid of the try/except/pass sequences until you understand what is failing. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 06:33:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 10:33:40 -0000 Subject: Passing function objects to timeit Message-ID: <13us6o4og79iid0@corp.supernews.com> The timeit.Timer class times "code snippets" -- you pass it strings rather than function objects. That's good for what it's worth, but sometimes the code you want to time is too big to easily pass as a string, or maybe you only have access to a function object without the source, or for whatever reason it's not very convenient. In this case, a good trick is to import the function by name: timeit.Timer('spam()', 'from __main__ import spam') But now I find myself wanting to time a function that's not defined in __main__. Here's a illustrative example: def factory(): def f(): return "spam" return f def main(): func = factory() return timeit.Timer('func()', 'from __main__ import func').timeit() But it doesn't work: >>> main() Traceback (most recent call last): File "", line 1, in File "", line 3, in main File "/usr/lib/python2.5/timeit.py", line 161, in timeit timing = self.inner(it, self.timer) File "", line 3, in inner ImportError: cannot import name func Moving the definition of func into __main__ is not an option. What do I do? Am I reduced to re-writing the timeit module to take functions instead of strings? (Maybe I should do that anyway.) Or is there a way to inject the function object into the namespace used by timeit? -- Steven From James.Moynes at rte.ie Mon Mar 31 06:01:19 2008 From: James.Moynes at rte.ie (Moynes James) Date: Mon, 31 Mar 2008 11:01:19 +0100 Subject: wxPython; adding a grid to a panel References: Message-ID: I am a Python newbie hoping for some help with wxPython. I am trying to build a frame which will display a wx.grid and a number of other widgets (text controls, static text and buttons). In all the example scripts I have seen, a gird is added directly to a frame; is it possible to place a grid in a box sizer or on a wx.Panel so that it can be arranged with other widgets in the same frame? In the script below I have added two panels to a frame. I want to display the grid in one panel (and later on add other widgets to the other panel), but I cannot get the grid to display properly. What am I doing wrong? Thanks in advance for your help, James ################################################# import wx import wx.grid class TestTable(wx.grid.PyGridTableBase): def __init__(self): wx.grid.PyGridTableBase.__init__(self) self.rowLabels = ["uno", "dos", "tres", "quatro", "cinco"] self.colLabels = ["homer", "marge", "bart", "lisa", "maggie"] def GetNumberRows(self): return 5 def GetNumberCols(self): return 5 def IsEmptyCell(self, row, col): return False def GetValue(self, row, col): return "(%s,%s)" % (self.rowLabels[row], self.colLabels[col]) def SetValue(self, row, col, value): pass def GetColLabelValue(self, col): return self.colLabels[col] def GetRowLabelValue(self, row): return self.rowLabels[row] class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Grid Table", size=(500,200)) panel1 = wx.Panel(self, -1) panel2 = wx.Panel(self, -1) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(panel1, 1, wx.EXPAND | wx.ALL, 3) hbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 3) grid = wx.grid.Grid(panel2, wx.EXPAND) table = TestTable() grid.SetTable(table, True) self.SetSizer(hbox1) app = wx.PySimpleApp() frame = TestFrame() frame.Show() app.MainLoop() ################################################## -------------- next part -------------- *********************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RT? may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ************************************************************ From mmeazy at gmail.com Wed Mar 19 09:41:03 2008 From: mmeazy at gmail.com (Ramya) Date: Wed, 19 Mar 2008 06:41:03 -0700 (PDT) Subject: Make Money Online with Home Business Opportunities. Message-ID: <8c8f35fd-56f4-4ea1-8739-8a6837ba6eeb@i7g2000prf.googlegroups.com> Make Money Online with Home Business Opportunities. Make Money at Home on your Computer. No investment needed. http://mmeazy.blogspot.com/ . From paul at boddie.org.uk Wed Mar 19 13:19:22 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 19 Mar 2008 10:19:22 -0700 (PDT) Subject: How to get an XML DOM while offline? References: <64cpnvF2at1j9U1@mid.uni-berlin.de> Message-ID: <69ad9586-7a82-47a5-8bbb-c92ecdb08aa4@e6g2000prf.googlegroups.com> On 19 Mar, 16:27, "Diez B. Roggisch" wrote: > william tanksley wrote: > > I want to parse my iTunes Library xml. All was well, until I unplugged > > and left for the train (where I get most of my personal projects > > done). All of a sudden, I discovered that apparently the presence of a > > DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing > > the Internet... So suddenly I was unable to do any work. The desire to connect to the Internet for DTDs is documented in the following bug: http://bugs.python.org/issue2124 However, I can't reproduce the problem using xml.dom.minidom.parse/ parseString and plain XHTML, although I may be missing something which activates the retrieval of the DTD. > > I don't want to modify the iTunes XML; iTunes rewrites it too often. > > How can I prevent xml.dom.minidom from dying when it can't access the > > Internet? > > > Is there a simpler way to read the iTunes XML? (It's merely a plist, > > so the format is much simpler than general XML.) > > Normally, this should be solved using an entity-handler that prevents the > remote fetching. I presume the underlying implementation of a SAX-parser > does use one, but you can't override that (at least I didn't find anything > in the docs) There's a lot of complicated stuff in the xml.dom package, but I found that the DOMBuilder class (in xml.dom.xmlbuilder) probably contains the things which switch such behaviour on or off. That said, I've hardly ever used the most formal DOM classes to parse XML in Python (where you get the DOM implementation and then create other factory classes - it's all very "Java" in nature), so the precise incantation is unknown/forgotten to me. > The most pragmatic solution would be to rip the doctype out using simple > string methods and/or regexes. Maybe, but an example fragment of the XML might help us diagnose the problem, ideally with some commentary from the people who wrote the xml.dom software in the first place. Paul From danb_83 at yahoo.com Sat Mar 22 12:10:04 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 22 Mar 2008 09:10:04 -0700 (PDT) Subject: NameError: name 'guess' is not defined References: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> <64knqtF2cdrc4U1@mid.uni-berlin.de> Message-ID: On Mar 22, 10:44 am, "Diez B. Roggisch" wrote: > willk... at gmail.com schrieb: > > > > > I am very new to both programming and Pyhton and while trying to do > > some practice using A byte of python an Error pops up on the IDLE > > shell. I am using windows XP. PLease see below. > > while running: > > guess = int(raw_input('Enter an integer : ')) > > > if guess == number: > > print 'Congratulations, you guessed it.' > > running = False # this causes the while loop to stop > > elif guess < number: > > print 'No, it is a little higher than that.' > > else: > > print 'No, it is a little lower than that.' > > else: > > print 'The while loop is over.' > > # Do anything else you want to do here > > > print 'Done' > > > After typing the above as the book says, I get the error NameError: > > name 'guess' is not defined > > What Am I doing wrong? > > You most certainly did NOT write the above - because in Python > whitespace is significant, and thus the above would result in a > syntax-error because you need to have things like > > if condition: > something() > > and not > > if condition: > something() > > So unless you post what you *really* entered (and make sure your > NG-client/mailclient doesn't eat leading whitespace), nobody will be > able to help you. If your newsclient *does* mangle whitespace, you can post your code like: exec """ number = 12345 # Defines the number variable before using while True: $guess = int(raw_input('Enter an integer : ')) $if guess == number: $$print 'Congratulations, you guessed it.' $$break # this causes the while loop to stop $elif guess < number: $$print 'No, it is a little higher than that.' $else: $$print 'No, it is a little lower than that.' print 'The while loop is over.' print 'Done' """.replace("$", "\t") From bearophileHUGS at lycos.com Thu Mar 27 21:33:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 27 Mar 2008 18:33:15 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: <7b6fad3f-60ed-49f9-b685-9fc1ddd3e2dd@s19g2000prg.googlegroups.com> MartinRineh... at gmail.com: > Mine does less. But you tell it less to do it. Some of those fields are optional :-) Bye, bearophile From ricaraoz at gmail.com Sat Mar 1 14:19:09 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Mar 2008 16:19:09 -0300 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c990b9$0$899$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> <47c990b9$0$899$ba4acef3@news.orange.fr> Message-ID: <47C9AC2D.8090404@bigfoot.com> M?ta-MCI (MVP) wrote: > Re! > > An exemple. With this script: > a=123 > b=456 > d=a+b+c > (note than 'c' is not defined). > > When I run, inside Pyscripter, the error-dialog is showed, and, one > second after, PyScripter is closed. > This problem is present since Python 2.5.2. > > I search, for know if it's a problem only on my computer, or a more > general problem. > > Thanks by advance for your(s) answer(s). > > @-salutations Just tried it with PyScripter v 1.9.5.0 and Python 2.5.2. Error dialog showed but PyScripter did not close. From borasavas at gmail.com Mon Mar 24 13:54:01 2008 From: borasavas at gmail.com (Kaze) Date: Mon, 24 Mar 2008 10:54:01 -0700 (PDT) Subject: Serving an external web site which requires authentication Message-ID: Hi, I need your suggestions about the topic. Actually, I'm not sure where to start but basically, I want to make something like; (I have an account on a site which requires log-in) - I'll be logged-in to that site with my account in my server. - And when a user connects to my site, I'll forward him/her to that site, using my account even if he/she doesn't have an account on that site... probably, I need to develop a proxy to do this, but I'm not sure... (I'm developing a django site) I really appreciate your ideas. From jeff at schwabcenter.com Thu Mar 20 11:16:05 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 08:16:05 -0700 Subject: Change user on UNIX In-Reply-To: References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: Jonathan Gardner wrote: > On Mar 20, 4:51 am, "Giampaolo Rodola'" wrote: >> Is there any way to su or login as a different user within a python >> script? I mainly need to temporarily impersonate another user to >> execute a command and then come back to the original user. > In the unix world, this is highly discouraged. You shouldn't have to > change your user. > If you want a different user to access files that another user > created, that's what groups are for. What's your take on setuid scripts (Python or otherwise)? I more or less agree with your assessment of su, so I would be interested in your opinion of chmod ug+s some_custom_script. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 22:23:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 02:23:07 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> Message-ID: <13utucbj9mkrpd4@corp.supernews.com> On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote: > En Sat, 29 Mar 2008 07:33:40 -0300, Steven D'Aprano > escribi?: > >> The timeit.Timer class times "code snippets" -- you pass it strings >> rather than function objects. That's good for what it's worth, but >> sometimes the code you want to time is too big to easily pass as a >> string, or maybe you only have access to a function object without the >> source, or for whatever reason it's not very convenient. >> >> In this case, a good trick is to import the function by name: >> >> timeit.Timer('spam()', 'from __main__ import spam') >> >> >> But now I find myself wanting to time a function that's not defined in >> __main__. Here's a illustrative example: >> >> >> def factory(): >> def f(): >> return "spam" >> return f >> >> def main(): >> func = factory() >> return timeit.Timer('func()', 'from __main__ import func').timeit() > > Would this help (untested)? > > def main(): > return timeit.Timer('func()', 'from __main__ import factory; func = > factory()').timeit() Unfortunately no. The above was just a simple illustration. Perhaps I misled you by showing where func() came from, but what I intended to illustrate was that func() could come from *anywhere*. I might not know where it came from: all I have is a function object. In fact, my question is actually more general than that, because my example was a little unrealistic in that the function took no arguments. I have to deal with the function arguments as well. The general problem is that I wish to time an arbitrary function with arbitrary arguments. The function and arguments are provided to me as Python objects, but timeit requires strings. Converting the objects to strings is not practical, and the objects might not exist in the __main__ module. The problem is that timeit creates its own namespace to execute the code in (which is a good thing!). Is there a way to insert arbitrary objects into that namespace? > Or maybe: > > def main(): > global func > func = factory() > return timeit.Timer('func()', 'from __main__ import func').timeit() I'll try playing around with that and see. -- Steven From gh at ghaering.de Fri Mar 28 17:24:26 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 28 Mar 2008 22:24:26 +0100 Subject: Python 2.5 - Build Error on Windows because of SQLite3 In-Reply-To: References: Message-ID: <655609F2e5310U1@mid.uni-berlin.de> llothar wrote: > Why does Python2.5 do not include the amalgamation source code of > sqlite3? [...] First, at the time Python grew the sqlite3 module, there was no amalgamation yet. My reasoning: So that Python doesn't need to release a security release, should a security bug in SQLite be found. Users can then download the new DLL from the SQLite homepage and place it into their Python's DLL folder. Ok, in reality that's probably only true for x86 Windows, not IA64 and/or AMD64 ;-) OTOH it would save me and the Python team some effort if we bundled a specific SQLite amalgamation with Python. Bug reports about bit-rotten SQLite 3.x versions would then not appear :-P Nowadays we support SQLite 3.0.8 through the very latest one. That means quite a few #ifdefs and friends in the C source code and also in the unit tests. -- Gerhard From bbxx789_05ss at yahoo.com Thu Mar 20 13:32:06 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 20 Mar 2008 10:32:06 -0700 (PDT) Subject: if __name__ == '__main__': References: Message-ID: On Mar 20, 10:21?am, "Simon Brunning" wrote: > On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde wrote: > > Hi, > > I am new to the python and not getting meaning of following line, > > > if __name__ == '__main__': > > ? ? ? main() > The if statement is used to skip the code after the if statement in certain situations. If that if statement is in a file named test1.py, and you issue this command: $ python test1.py then the code after the if statement will execute. That's because python assigns the string '__main__' to the variable __name__ when the program starts However, if you do this: ------- #test1.py def my_func(num): print num * 2 if __name__ == "__main__": print "Testing my func:", my_func(10) -------- #test2.py import test1 test1.my_func(5) ------- ...and you issue the command: $python test2.py Then the code after the if statement in test1.py will not execute. From jules at js3d.co.uk Sun Mar 2 03:03:02 2008 From: jules at js3d.co.uk (Jules Stevenson) Date: Sun, 2 Mar 2008 08:03:02 -0000 Subject: FW: Escaping a triple quoted string' newbie question Message-ID: <002801c87c3b$d6cd42b0$0301a8c0@laptop> Hello, Apologies if the terminology in this email is a little incorrect, I'm still finding my feet. I'm using python to generate some script for another language (MEL, in maya, specifically expressions). Maya runs python too, but unfortunately its expression language still has to use the maya syntax. If I pass the expression this code: #runtime code [mel] expRuntime="""float $pos[]=particleShape1.worldPosition; setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; """ dynExpression (p, s=expRuntime, rad=1) #generate the expression Then maya errors out, however if I pass maya an 'escaped' version: expRuntime="""float $pos[]=particleShape1.worldPosition;\r\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\r\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\r\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2];" -rad particleShape1;""" Then all is well. My question is, is there any way to convert the first variable example to the second? It's a lot easier to type and on the eye. Tia, Jules From pavloutefkros at gmail.com Sun Mar 2 10:15:39 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 07:15:39 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> Message-ID: <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> i would like to apologize once more. i understand that you are saying "what a fool he is waiting for us to solve all his problems", cause i've said that for other posts, when they seemed "immature". It's just that i couldn't find a way out of 20 lines of code and this drove me mad. i end this topic here. From fetchinson at googlemail.com Mon Mar 10 19:05:47 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 16:05:47 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > There are a number of free tools for image matching but it's not very > > easy to decipher the actual algorithm from the code that includes db > > management, GUI, etc, etc. I have my own image database and GUI so all > > I need is the actual algorithm preferably in pseudo code and not in > > the form of a research paper (from which I also found a lot but since > > I'm not that much interested in the actual science of image > > recognition this seems like an over kill). > > I'd recommend SIFT. There's quite a bit of information on SIFT. In most > cases, they don't cover the background science too much, but are still > heavy on the math. Pseudo code is hard to come by since it will take > many lines of pseudo code just to express one concise mathematical > equation. There are however many links to implementations in various > languages on the Wikipedia page. > > http://en.wikipedia.org/wiki/Scale-invariant_feature_transform > > I have had good experiences with SIFT for feature extraction from images > (I have used it for panorama stitching and robot mapping). It's > insensitive to scale and rotation. Note that it is a patented algorithm > and this may (or may not) pose a problem for you. Thanks for the info! SIFT really looks like a heavy weight solution, but do you think the whole concept can be simplified if all I needed was: given a photo, find similar ones? I mean SIFT first detects objects on the image and find similarities, but I don't need the detection part at all, all I care about is similarity for the whole photo. I surely don't understand the big picture fully but just have the general feeling that SIFT and other expert tools are an overkill for me and a simplified version would be just as good with a much more easily comprehensible core algorithm. Or am I being too optimistic and there is no way out of going into the details? From darcy at druid.net Thu Mar 6 11:41:58 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 6 Mar 2008 11:41:58 -0500 Subject: Please keep the full address In-Reply-To: References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: <20080306114158.a1133a3f.darcy@druid.net> On Thu, 6 Mar 2008 08:00:58 -0800 (PST) Carl Banks wrote: > > I'm talking about castironpi. I find his posts a waste of my time > > "His" posts? Whatever. I'm too old to worry about searching for politically correct, gender neutral pronouns. -- 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 kyosohma at gmail.com Thu Mar 13 09:03:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 13 Mar 2008 06:03:49 -0700 (PDT) Subject: Dispatch("Excel.Application") failed References: Message-ID: <07e73002-5b12-41c2-9194-5fc753dc6726@n36g2000hse.googlegroups.com> On Mar 13, 1:02 am, lialie wrote: > Hi, > Maybe it 's quite simple, but I can't fix it. Do I make some mistakes in > my env setting? My excel version is 2003. > any suggestion? Thanks. > > Traceback (most recent call last): > File "testexcel.py", line 3, in ? > excel = Dispatch("Excel.Application") > File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line > 95, in > Dispatch > dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c > lsctx) > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 98, in _ > GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 78, in _ > GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II > D_IDispatch) > pywintypes.com_error: (-2147221005, > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > None, None) I'm not seeing anything obviously wrong. What version of Windows are you using? Are you logged in as an admin? You also might try the PyWin32 user's mailing list: http://mail.python.org/mailman/listinfo/python-win32 Mike From mhwalker at shaw.ca Tue Mar 4 00:12:39 2008 From: mhwalker at shaw.ca (Mike Walker) Date: Tue, 04 Mar 2008 05:12:39 GMT Subject: Command line arguments in Windows Message-ID: I am having some problems with command line arguments in Windows. The same code under Linux works fine. In Windows I only get one argument no matter how many arguments are passed on the command line. I think there is some problem with the way the .py files are associated causing this. I'm just not sure how to go about fixing it. If I call the python script using the command "python argtest.py arg1 arg2 etc..." this also works fine. Its only when run the program using the name only that the problem occurs. Does anyone have any ideas what the problem is here and hopefully how to go about fixing it? import sys if __name__ == "__main__": for arg in sys.argv: print arg From phd at phd.pp.ru Tue Mar 11 09:40:03 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 11 Mar 2008 16:40:03 +0300 Subject: SQLObject 0.10.0 Message-ID: <20080311134003.GB14147@phd.pp.ru> Hello! I'm pleased to announce version 0.10.0, the first stable release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9 -------------- Features & Interface ~~~~~~~~~~~~~~~~~~~~ * Dropped support for Python 2.2. The minimal version of Python for SQLObject is 2.3 now. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.10. * SQLBuilder Select supports the rest of SelectResults options (reversed, distinct, joins, etc.) * SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect() use SQLBuilder Select queries; this make all SELECTs implemented internally via a single mechanism. * SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias) and properly sqlrepr. * Added SQLBuilder ImportProxy. It allows one to ignore the circular import issues with referring to SQLObject classes in other files - it uses the classregistry as the string class names for FK/Joins do, but specifically intended for SQLBuilder expressions. See tests/test_sqlbuilder_importproxy.py. * Added SelectResults.throughTo. It allows one to traverse relationships (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's a simple mechanism for pre-caching/eager-loading of later FK relationships (i.e., going to loop over a select of somePeople and ask for aPerson.group, first call list(somePeople.throughTo.group) to preload those related groups and use 2 db queries instead of N+1). See tests/test_select_through.py. * Added ViewSQLObject. * Added sqlmeta.getColumns() to get all the columns for a class (including parent classes), excluding the column 'childName' and including the column 'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to override it in the inheritable sqlmeta class; this makes asDict() to work properly on inheritable sqlobjects. * Allow MyTable.select(MyTable.q.foreignKey == object) where object is an instance of SQLObject. * Added rich comparison methods; SQLObjects of the same class are considered equal is they have the same id; other methods return NotImplemented. * RowDestroySignal is sent on destroying an SQLObject instance; postfunctions are run after the row has been destroyed. * Changed the implementation type in BoolCol under SQLite from TINYINT to BOOLEAN and made fromDatabase machinery to recognize it. * MySQLConnection (and DB URI) accept a number of SSL-related parameters: ssl_key, ssl_cert, ssl_ca, ssl_capath. * Use sets instead of dicts in tablesUsed. Dropped tablesUsedDict function; instead there is tablesUsedSet that returns a set of strings. * SQLBuilder tablesUsedSet handles sqlrepr'able objects. * Under MySQL, PickleCol no longer uses TEXT column types; the smallest column is now BLOB - it is not possible to create TINYBLOB column. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From lesande at gmail.com Wed Mar 19 19:37:24 2008 From: lesande at gmail.com (Lee Sander) Date: Wed, 19 Mar 2008 16:37:24 -0700 (PDT) Subject: slicing a list but in downward fashion Message-ID: hi, i have a list and i can get elements form it via slicing L[start:stop] but sometimes the start is > stop i.e. I want to go in the opposite direction,eg L[10:2], mattab lets you do L(10:-1:2) to achive this, is there a way to do this in python? thanks L From tjreedy at udel.edu Thu Mar 27 16:43:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Mar 2008 16:43:44 -0400 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> Message-ID: wrote in message news:4a2ade35-9624-4e26-ba47-984c72ea4f6a at y21g2000hsf.googlegroups.com... | I'm making a game where you'll be able to make your own mods and I | want to be able to write these mods in python. However, python has a | lot of "dangerous" functions (like erase any file on the harddrive | etc) so I want a "safe" python. I first found RExec but that is | disabled in python 2.5 so I was thinking about building python from | source with a few changes. There are modable commercial games, such as CIV4 I believe, that use Python as the scripting language for both the authors and modders. I presume they use customized interpreters, without the open and file builtins and process, socket, etc modules, and probably a customized import. But I have never seen an article or report on exactly what changes there are. There is also the question of what to about 'hang up' code like 'while True: pass', but that is less a concern for a game run on home machines than a web server. Anyone doing that could be blackballed from the mod distribution site without having trashed anyone's system. tjr From gowricp at gmail.com Tue Mar 18 23:48:37 2008 From: gowricp at gmail.com (Gowri) Date: Tue, 18 Mar 2008 20:48:37 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <505bf4e4-f99c-4b1c-9ad6-ba26846645bc@n77g2000hse.googlegroups.com> Thanks for your reply Justin. But how do I do it with cjson? From lists.eckel at gmail.com Sun Mar 16 07:10:58 2008 From: lists.eckel at gmail.com (Bruce Eckel) Date: Sun, 16 Mar 2008 04:10:58 -0700 (PDT) Subject: Pycon disappointment Message-ID: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> If the following seems unnecessarily harsh, it was even more harsh for me to discover that the time and money I had spent to get to my favorite conference had been sold to vendors, presenting me as a captive audience they could pitch to. I believe that this year's Pycon organizers suffered from inexperience and naivete, because they didn't know that some vendors will ask for anything just to see how far they can push it. And that it's a negotiation, that you must push back rather than give in just because the conference might get some money for it. More importantly, that the imperative to grow Pycon does not mean "at all costs." I've already spoken to more than one vendor who was dismayed by the state of things, so we are not talking about all vendors here by any means. At first the morning plenary sessions -- where the entire conference audience was in a single room -- just seemed a bit commercial. But then I slowly figured out that the so-called "diamond keynotes" were actually sold to vendors. It must have sounded great to some vendors: you get to pitch to everyone and nothing else is going on so the audience is trapped. But it gets worse. The lightning talks, traditionally the best, newest and edgiest part of the conference, were also sold like commercial air time. Vendors were guaranteed first pick on lightning talk slots, and we in the audience, expectantly looking forward to interesting and entertaining content, again started to feel like things were awfully commercial. And what seemed like a good idea, moving lightning talks into plenary sessions with no competition, began to look like another way to deliver a captive audience to vendors. What was supremely frustrating was discovering that the people wanting to give REAL lightning talks had been pushed off the end of the list by this guarantee to vendors. We didn't get to see the good stuff, the real stuff, because that time had been sold. On top of that, the quality of the presentations was unusually low. I'd say that 80% were not worth going to -- there were definitely some good ones, but it was a lot of pain to discover them. In my opinion, open spaces should have had greater status and billing, with eyes-forward talks and vendor sessions offered only as possible alternatives. Especially, vendor sessions should not be presented as "keynotes" during plenary sessions. I think it took a little while for people to catch on to the idea that they could have control of their own experience through the open spaces and that the main offerings were not the only option. The worst thing about the whole experience was the feeling that someone was trying to trick me and control me into watching these things, presenting them under the guise of real keynotes and real lightning talks. My trust has been violated. I paid a lot, in both money and time, to be at this conference just to be herded into a room and have my eyeballs sold to the highest bidder. And it's going to bug me, especially when I think about coming back next year. I'm going to need a lot of reassurance that this isn't going to happen again. I think a lot of people have been caught up in the idea that we need to commercialize Python, and ride some kind of wave of publicity the way that Java and C# and Rails seem to have done. This kind of thinking leads to bad, impulsive decisions that can have long-lasting or even permanent negative impacts on the community. Maybe things don't seem to be happening fast enough in comparison with those commercial endeavors, but this is a grass-roots movement. It's never been about moving as fast as you can. It's always been about vision, not tactics. For many, it's fun and exciting and really important to "catch the wave," but the wave passes and then you've just exhausted yourself chasing a brief bump in the water. Python may not have caught any particular wave, but it's always grown, steadily. I know what the argument for the results of Pycon 2008 will be: we needed the money. My answer: it's not worth it. If this is what you have to do to grow the conference, then don't. If the choice is between selling my experience to vendors and reducing the size of the conference, then cut the size of the conference. Keep the quality of my experience as the primary decision criteria, or I'll stop coming. From bbkolde at gmail.com Thu Mar 20 12:12:44 2008 From: bbkolde at gmail.com (Bhagwat Kolde) Date: Thu, 20 Mar 2008 21:42:44 +0530 Subject: if __name__ == '__main__': Message-ID: Hi, I am new to the python and not getting meaning of following line, if __name__ == '__main__': main() Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skunkwerk at gmail.com Wed Mar 26 09:44:21 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Wed, 26 Mar 2008 06:44:21 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> On Mar 25, 11:04?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk ? > escribi?: > > > > > On Mar 25, 9:25?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? > >> escribi?: > > >> >> ? ?i'm trying to call subprocess.popen on the 'rename' function in > >> >> linux. ?When I run the command from the shell, like so: > > >> >> rename -vn 's/\.htm$/\.html/' *.htm > > >> >> it works fine... however when I try to do it in python like so: > >> >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > >> >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > >> >> print p.communicate()[0] > > >> >> nothing gets printed out (even for p.communicate()[1]) > > >> I'd try with: > > >> p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > >> ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, > >> ? ? ? ?shell=True) > > >> (note that I added shell=True and I'm using a raw string to specify the ? > >> reg.expr.) > > > Thanks Gabriel, > > ? ?I tried the new command and one with the raw string and single > > quotes, but it is still giving me the same results (no output). ?any > > other suggestions? > > My next try would be without the single quotes... > > -- > Gabriel Genellina thanks for the input guys, I've tried the suggestions but can't get it to work. I have a file named test.htm in my directory, and when I run the following command: rename -vn 's/(.*)\.htm$/model.html/' *.htm from the shell in that directory I get the following output: test.htm renamed as model.html now my python script is called test.py, is located in the same directory, and is called from the shell with 'python test.py' the contents of test.py: import subprocess p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] i change to print p.communicate()[1] in case the output is blank the first time this is the output: *.htm renamed as model.html when I add shell=True to the subprocess command, I get the following output: Usage: rename [-v] [-n] [-f] perlexpr [filenames] am i doing something wrong? From tmp1 at viltersten.com Sat Mar 8 22:06:36 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 04:06:36 +0100 Subject: SV: Regarding coding style In-Reply-To: <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> Message-ID: <63h1j2F27rdfoU1@mid.individual.net> >> /** Projects an object from 3D to 2D using >> the method of Alexander The Great. >> \param 3D structure to be projected >> \returns 2D projection >> */ >> public Proj2D get2Dfrom3D(Proj3D param); >> >> The above is, to me, very clear and >> consistent. Not to mention, easily >> handled with e.g. Doxygen to create a >> readable documentation. >> >> I don't see how this is dislikeable. Please >> explain. > > When get2Dfrom3D changes its signature but > the comment is not changed. That's where I > have a problem, and it's only a matter of > time before it happens. I think we've arrived at the spot where i'll claim that a _always_ update my comments, and you'll question that i can (in the long run). Let's agree on that! :) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From samritmanmar at gmail.com Thu Mar 6 04:26:05 2008 From: samritmanmar at gmail.com (sexyman) Date: Thu, 6 Mar 2008 01:26:05 -0800 (PST) Subject: FREE DOWNLOAD game mario. Message-ID: <6375831c-35bb-4119-9626-a9c102619410@b1g2000hsg.googlegroups.com> mario http://www.ziddu.com/download.php?uid=Z7CdnZqoabCcluKnYqqhkZSoX6qfnZqu2 joy .......play game From hvendelbo.dev at googlemail.com Wed Mar 5 14:46:21 2008 From: hvendelbo.dev at googlemail.com (hvendelbo.dev at googlemail.com) Date: Wed, 5 Mar 2008 11:46:21 -0800 (PST) Subject: Embedding vs Configuring Python build Message-ID: I am using Python in an application that cannot depend on an existing Python installation or require Python to be installed. The application itself should not have an install procedure, but rather should be runnable from any location in the file system. Ideally I would prefer not to embed at all, but would rather prefer to configure. I found a couple of discussions on the default sys.path in the archive and am currently reading through the Py_GetPath. The path logic seems pretty specific to the platform, whereas I would want it to be relative regardless of platform. I figure that if I can just get to my own site.py/sitecustomize.py then I'm in business. This is what I wan't to achieve: * The python executable location should be used to determine dynamic libraries * The python exe location should be used to determine standard library scripts * site.py should be executed rather than the shell if no parameters are specified Is it possible to change the build configuration of Python to support this. From michael.wieher at gmail.com Wed Mar 26 09:32:28 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 26 Mar 2008 08:32:28 -0500 Subject: Dimensions of Arrays, Matrices In-Reply-To: <8a6035a00803260622v686441ddy1d3dd942b2377e21@mail.gmail.com> References: <8a6035a00803260622v686441ddy1d3dd942b2377e21@mail.gmail.com> Message-ID: Google -> "matrix python" 1st response: http://www.python.org/community/sigs/retired/matrix-sig/ "The purpose of this SIG was to continue development of a Python matrix type. This effort succeeded and resulted in Numerical Python, a high-speed array language for Python" by following the magic hyperlink I arrive at http://scipy.org/ which might be too embellished, so I then returned to the retired-sig and found http://sourceforge.net/projects/numpy I'm sure if you dig around in either of those places you'll find more than you are looking for =) 2008/3/26, Dark Wind : > > Hi, > > Suppose we have a 3X3 matrix in Mathematica. We can get its dimensions by: > Dimensions[A] = {3,3} > TensorRank[A] = 2 > > Are there exact functions for these two in Python? > > Thank you > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Sat Mar 29 04:40:21 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 29 Mar 2008 08:40:21 GMT Subject: How do I reconnect a disconnected socket? In-Reply-To: <13uq89rskf16u9a@corp.supernews.com> References: <13uq69e8us4oo74@corp.supernews.com> <13uq89rskf16u9a@corp.supernews.com> Message-ID: Grant Edwards wrote: > Laszlo Nagy wrote: >> What about non-blocking sockets? > > $ man recv > ... > If no messages are available at the socket, the receive > calls wait for a message to arrive, unless the socket is > non-blocking (see fcntl(2)), in which case the value -1 > is returned and the external variable errno set to > EAGAIN. As Grant showed, a successful recv() returning zero bytes indicates the end of the data stream from the remote peer. Other cases block or raise errors. A few more notes: When a socket will return zero bytes to indicate the end of the data stream, it will select() as readable. In the case Laszlo asked about here -- a non-blocking socket is not shutdown but no data is immediately readable -- on some systems, the error is EWOULDBLOCK, which may be, but is not generally, the same code as EAGAIN. (There may be yet other systems that have different error conventions; I don't know.) The Python library's 'errno' module exports the error names with their associated numeric values. Python's socket module does not 'return' these error codes; it raises exceptions. A non-blocking socket, or equivalently a socket with a timeout of zero, will raise socket.error. The errno in the exception's (errno, string) value should be EAGAIN or EWOULDBLOCK. If a socket has a non-zero timeout, and that timeout expires, the operation raises socket.timeout. -- --Bryan From davids at evertech.com.au Fri Mar 14 03:31:08 2008 From: davids at evertech.com.au (David S) Date: Fri, 14 Mar 2008 07:31:08 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <13tk779i4r8j9ba@corp.supernews.com> Message-ID: <0RpCj.25549$421.10498@news-server.bigpond.net.au> Hi, Using "C:\Program Files\apache-ant-1.7.0\bin\ant.bat" just gives me the same result. David "Dennis Lee Bieber" wrote in message news:13tk779i4r8j9ba at corp.supernews.com... > On Fri, 14 Mar 2008 04:37:12 GMT, "David S" > declaimed the following in comp.lang.python: > > >> If I cut the path statement here and paste it next to a windows XP >> command >> prompt ant is invoked. >> >> The python code here is >> if not os.path.isfile(ANT_CMD): >> error('"%s" does not exist' % ANT_CMD) >> > Any chance the /filename/ is something like "ant.exe" > >>>> pyt = "e:/python24/python" >>>> if not os.path.isfile(pyt): > ... print "%s does not exist" % pyt > ... > e:/python24/python does not exist >>>> pyt = "e:/python24/python.exe" >>>> if not os.path.isfile(pyt): > ... print "%s does not exist" % pyt > ... >>>> > > Remember, under Windows, files with certain extensions are > executable /without/ needing the extension on the command line -- unlike > Linux... > > My eclipse install has: ant.bat, ant.cmd, and ant.jar files, and > which (if they are in the same directory) gets picked when the extension > is not specified is beyond my current knowledge -- might depend on the > order of the extensions specified in the > > C:\Documents and Settings\Dennis Lee Bieber>echo %pathext% > .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.pyw;.py;.pyo;.pyc;.tcl > > (okay, the ant.jar won't be picked ) > > -- > 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/ From stefan_ml at behnel.de Mon Mar 24 11:42:52 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Mar 2008 16:42:52 +0100 Subject: URL encoding In-Reply-To: References: <9693ffda-1454-4d56-acee-1e6fc4ebeccb@h11g2000prf.googlegroups.com> Message-ID: <47E7CBFC.8090205@behnel.de> binaryj wrote: > On Mar 24, 7:04 pm, vvangelov... at gmail.com wrote: >> Is there any method in the standard modules that can perform proper >> url encoding according to RFC? > > whats wrong with the current encoding ??? it just works fine!!! > > or is it that u dont know about urllib.urlencode() ?? I think that was obvious from the question, no need to spill punctuation marks all over the place. Stefan From __peter__ at web.de Wed Mar 12 14:16:59 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Mar 2008 19:16:59 +0100 Subject: ValueError in pickle module during unpickling a infinite float (python 2.5.2) References: <4b9d0896-df9c-47b6-98b6-16f825d67975@i7g2000prf.googlegroups.com> Message-ID: rehn at iwm.mw.tu-dresden.de wrote: > Unpickling an infinite float caused a ValueError in the pickle module. > I need to pickle and load infinite floats in my project. Do you have > any suggestions how to solve the issue? You could try another protocol. Does >>> inf = 1e1000 >>> pickle.loads(pickle.dumps(inf, pickle.HIGHEST_PROTOCOL)) inf work? Peter From frikker at gmail.com Mon Mar 3 16:01:48 2008 From: frikker at gmail.com (blaine) Date: Mon, 3 Mar 2008 13:01:48 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> Message-ID: <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> On Mar 3, 12:31 pm, Bjoern Schliessmann wrote: > It doesn't only work, it's the preferred way (if you don't use > advanced wrappers like pyserial). For the basics see > > http://www.easysw.com/~mike/serial/serial.html [...] > What is the relationship between read/write, the baud rate, and > efficiency? The serial port is configured using POSIX terminal > interface (termios). Thank you so much for that reference link, it was very helpful. I now understand the difference in the modules - termios and fctnl. As far as PySerial goes - were trying to stick to built-in modules since cross compiling to an arm processor is being a little bit of a pain for us. Thank you for the suggestion though! Thanks! Blaine From mdboldin at gmail.com Tue Mar 4 10:05:11 2008 From: mdboldin at gmail.com (mmm) Date: Tue, 4 Mar 2008 07:05:11 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: Oops I did make a mistake. The code I wanted to test should have been import copy print 'Test 1' pf= '?,?,?,?' sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf print sqlx1 print print 'Test 2' sqlx2= copy.copy(sqlx1) sqlx3= sqlx1 pf= '?,?,?, ****' print 'sqlx1= ', sqlx1 print 'sqlx2= ', sqlx2 print 'sqlx3= ', sqlx2 and the results would == output Test group 1 INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) Test group 2 sqlx1= ?INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) sqlx2= ?INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) sqlx3= ?INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) Such that sqlx1 does to change with the re-assignment of 'pf' And of course immutables such as strings are immutable. Got it now. From bockman at virgilio.it Mon Mar 24 11:48:38 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 15:48:38 GMT Subject: python library to manipulate PALM documents ? References: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> Message-ID: <47e7cd56$0$16036$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 12:08:59 -0300, Guilherme Polo ha scritto: > 24 Mar 2008 13:36:13 GMT, Francesco Bochicchio : >> Hi all, >> >> anybody knows a python equivalent of the perl PALM::Doc module (and >> eventually other PALM::). >> >> I have a e-book device wich reads mobi-pocket format (among others). I >> have downloaded from a forum a set of perl scripts to convert HTML to >> unencripted mobipocket format and vice-versa. It uses the PALM:: >> package. I would attempt (for my convenience and for the fun of it) to >> make a python equivalent of that. Hence my quest for a Palm::Doc >> equivalent. >> >> > I'm not sure if it is what you are after, but it seems to be, check > this: http://pypi.python.org/pypi/PalmDB/1.8.1 > It could be. I read that mobipocket files may have extension .prc. Ciao ---- FB From aisaac at american.edu Sat Mar 8 10:32:18 2008 From: aisaac at american.edu (Alan Isaac) Date: Sat, 08 Mar 2008 15:32:18 GMT Subject: Can't get items out of a set? In-Reply-To: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Message-ID: <6kyAj.284$Ls6.153@trnddc01> Cruxic wrote: > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) > ... > p = people.get_equivalent(2) #method doesn't exist as far as I know > print p.name #prints Sue def get_equivalent(test, container): for p in container: if p == test: return p hth, Alan Isaac #example (note change in __eq__ to match your case; fix if nec) class Person: def __init__(self, id, name): self.id = id self.name = name def __hash__(self): return self.id def __eq__(self, other): return self.id == other people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) get_equivalent(2,people) From rasky at develer.com Tue Mar 11 19:09:03 2008 From: rasky at develer.com (Giovanni Bajo) Date: Tue, 11 Mar 2008 23:09:03 GMT Subject: min/max: "stable" invariant? Message-ID: Hello, assuming that a sequence contains multiple elements with minimum/maximum value, do min/max guarantee to return the *first* element in the sequence among those? Example: >>> class A: ... def __init__(self, x): self.x = x ... >>> L = [A(0), A(1), A(2), A(0)] >>> min(L, key=lambda a:a.x) is L[0] True >>> min(L, key=lambda a:a.x) is L[3] False Is this guaranteed by the Python language formal specification? Is this guaranteed to always by true in CPython? (I guess so) I can't find any mention in the documentation. -- Giovanni Bajo From sreya9636 at gmail.com Sat Mar 15 11:30:16 2008 From: sreya9636 at gmail.com (sreya9636) Date: Sat, 15 Mar 2008 08:30:16 -0700 (PDT) Subject: Exciting FREE Details Message-ID: <67c2c51d-b8a2-458a-8e99-d7ebd1474811@s8g2000prg.googlegroups.com> Tips On Buying A Desktop Computer While the case may not be important to some computer users it is a consideration to be thought about before purchasing a desktop computer. ... Log on : http://www.computer-solution.page.tl From Lie.1296 at gmail.com Sun Mar 2 07:53:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 2 Mar 2008 04:53:56 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> Message-ID: <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> On Mar 2, 2:02 pm, Paul Rubin wrote: > Lie writes: > > So basically they refused to satisfy everything that is still possible > > individually but would conflict if done together. > > I can't understand that. > > > x = 1 > > a = x + 1 << decides it's an int > > No, so far a and x are both Num (indeterminate) > > > b = x + 1.0 << error? or redefine to be float? > > This determines that a, b, and x are all floats. It's not "redefined" > since the types were unknown prior to this. > > Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional" > which is a narrower class than Num but it could still be Float, Double, > or Rational. Nums support addition, subtraction, multiplication, but > not necessarily division. So int/int is an error. Fractionals support > division. > > > c = x + 1 << would this cause error while it worked in line 2? > > No, c is also a float (actually Fractional) > > > A slightly obfuscated example: > > l = [1, 1.0, 1] > > This is the same as l = [1.0, 1.0, 1.0]. In Haskell, all elements > of a list must have the same type, so the 1.0 determines that l is > a list of fractionals. > > > x = 1 > > for n in l: > > c = x + n > > Haskell does not have loops, but if it did, all these values would be > fractionals. That's quite complex and restrictive, but probably it's because my mind is not tuned to Haskell yet. Anyway, I don't think Python should work that way, because Python have a plan for numerical integration which would unify all numerical types into an apparent single type, which requires removal of operator's limitations. On Mar 2, 2:23 pm, Paul Rubin wrote: > Steven D'Aprano writes: > > def mean(data): return sum(data)/len(data) > > > That does the right thing for data, no matter of what it consists of: > > floats, ints, Decimals, rationals, complex numbers, or a mix of all of > > the above. > > One of those types is not like the others: for all of them except int, > the quotient operation actually is the inverse of multiplication. > So I'm unpersuaded that the "mean" operation above does the "right > thing" for ints. If the integers being averaged were prices > in dollars, maybe the result type should even be decimal. In __future__ Python or Python 3.0, that mean function would work for all types. And divisions on int is also inverse of multiplications, just like subtraction is the inverse of addition: from __future import division a = 10 b = 5 c = a / b if c * b == a: print 'multiplication is inverse of division' From pavloutefkros at gmail.com Sat Mar 1 12:40:12 2008 From: pavloutefkros at gmail.com (Gif) Date: Sat, 1 Mar 2008 09:40:12 -0800 (PST) Subject: tcp functions Message-ID: is there a module for tcp functions or any other quick way to connect, listen, send and recieve from tcp? thanks in advance From MadComputerGuy at gmail.com Mon Mar 10 01:08:29 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Sun, 9 Mar 2008 22:08:29 -0700 (PDT) Subject: How to factor using Python? Message-ID: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? Thanks in advance, Nathan P. From Scott.Daniels at Acm.Org Sat Mar 29 18:33:56 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 29 Mar 2008 15:33:56 -0700 Subject: Problem with python In-Reply-To: References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Message-ID: <13utgh8j9ik8t7c@corp.supernews.com> Lie wrote: > On Mar 30, 2:57 am, mac_the_sco... at hotmail.com wrote: >> Hi there. >> I ... started writing simple programs in the python gui... when I write >> python code ...[and]... double click it all that happens is a black box >> flashes up on the screen, but nothing else!? .... > > open the program in IDLE (or any other Python IDEs). I'm guessing that > your program is printing a traceback (error) when trying to get input > that's why it immediately closes itself. Another possibility is to open a shell (or command window or "dos box"), and in that window type in "python myfile.py" You'll see error messages because the display window does not depend on the program staying alive. By the way, a better thing to have said when you asked this would include your OS, the python version, and the GUI system you are using. Those details matter. If you are doing wxPython programming, for example, you cannot easily use IDLE for your program (GUI systems fight for control of the display). -Scott David Daniels Scott.Daniels at Acm.Org From ivan.illarionov at gmail.com Tue Mar 18 19:51:56 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 18 Mar 2008 16:51:56 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> Message-ID: <8fc48d27-1496-4240-a26c-708b6e9aa440@s8g2000prg.googlegroups.com> > That's another new step for me. Any ideas where to start? http://docs.python.org/ext/simpleExample.html And look into the source of existing extensions. PIL and PyCairo are the best in your situation. From Lie.1296 at gmail.com Sun Mar 30 14:14:42 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 11:14:42 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: On Mar 30, 12:11 pm, hdante wrote: (snip) > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: > > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) That would be a nightmare. Programming language (or most computer-based texts) should only use basic ASCII characters, except if it can't be helped since typing non- ASCII characters is still unreliable. It'd also be a headache to memorize what keyboard combinations to use to type a character. Not to mention how much more complex would the keyboard design be. Also not mentioning how much more complex the language design would be to handle all those non-ASCII characters. From bj_666 at gmx.net Sun Mar 9 14:59:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Mar 2008 18:59:10 GMT Subject: SV: Changing the size of a Button References: <63ifhtF277va7U1@mid.individual.net> <63iokhF284p4hU1@mid.individual.net> Message-ID: <63iqbuF27chv6U2@mid.uni-berlin.de> On Sun, 09 Mar 2008 19:45:58 +0100, K Viltersten wrote: > What i wish to do is to affect the size > of the button but not due to change of > text but due to resize of the frame it > resides in. > > This far i've managed to get a callback > to a function as the resize occurs and to > print the sizes. However, i'd like to > assign these values to the button so it > always stays the same width as the frame. Don't do it yourself, pack with the `fill` argument set to `Tkinter.X`. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Mon Mar 24 04:03:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Mar 2008 04:03:55 -0400 Subject: Does python hate cathy? References: Message-ID: "QS" wrote in message news:a5e95efc-f8cd-4595-bbbd-f5f59c45ea89 at u72g2000hsf.googlegroups.com... >From the title, I assumed this was spam like others with similar titles -- and that the perl newsgroup, for instance, would have 'Does perl hate cathy? | I am new to python, and I encountered a weird problem. Observation: as you will learn, the form of the error message was different from the standard tracebacks one gets during program execution. This was a clue that it was a cleanup message and actually did make sense. Summary lessons. 1. What a Python interpreter does after it executes the last statement is undefined by the language spec. It could do absolutely nothing (and I wish some programs that wastefully spend minutes 'cleaning up' did just that!). CPython tries to do some cleanup when requested but the results are sometimes seemingly arbitrary. 2. If you use __del__, do so for a reason (and keeping a population count is one, though rare*), and explicitly delete the objects for which you want dependable behavior. *A population count is a good example of a class attribute. But it seems to be rare in practice because if one wants that, it seems that a population collection (with a len() method) is usually also wanted -- perhaps so one can iterate thru the population. 3. Experimenting with Python is a good way to learn. Keep it up! tjr From kw at codebykevin.com Tue Mar 11 13:57:46 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 11 Mar 2008 13:57:46 -0400 Subject: How to make a Tkinter widget always visible? In-Reply-To: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> Message-ID: <47D6C81A.1070301@codebykevin.com> Miki wrote: > Hello, > > I have a simple Tkinter window with [GO] and [Quit] buttons at the > bottom. > > When I resize the window to be shorter, the first thing to disappear > are the buttons, however I want these button to be visible at all > times. > > Is there a way to make sure that these buttons are always visible? > There are various ways to do this: you can set the window to be non-resizable, or set a minimum size to it, so that it can't be resized below that level. However, if you allow arbitrary resizing of the window, there's no real way to guarantee that the widgets will be visible at all times. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From dave_mikesell at fastmail.fm Sat Mar 8 09:59:42 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 06:59:42 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> Message-ID: <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> On Mar 8, 2:38 am, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote: > >> x = get_stuff(store) # Get the stuff what was brought at the store. > > > Perfect example of an unnecessary comment. The variable and function > > names are commentary enough. > > "x" is a terrible name. What does it mean? Nothing. Right, that's a problem with the code. A comment only masks the bad smell. 'x' should be renamed to something meaningful, obviating the need for comments to follow it around. > There's only three places x is an appropriate name: > (1) A meta-syntactic variable like foo, bar, spam, ham, parrot. > > (2) Library functions, where x stands for a generic argument, usually a > number, e.g. def sin(x). > > (3) Throw-away code you don't need to maintain. I use single letter variables where their scope is very small. e.g., tight loops, small functions, etc. I even use them as class members where they make sense in the domain. x, y, z for 3d vectors, r, g, b, a for colors, etc. > The function name also doesn't explain anything. How was the stuff got? > Was it paid for, or stolen, or picked up on consignment, or what? Compare > the above line with: > > x = get_stuff(store) # Steal stuff from the store. > > or > > x = get_stuff(store) # Pickup the stuff from the store for disposal. > # The amount paid by the store is stored in global variable "pay_received" > # and the name of the employee authorizing the pickup is stored in the > # global "authorized_by". Shouldn't get_stuff's comment be with its definition? And just rename the function to something more meaningful, like purchase_goods(store), or whatever. > > But even if you were right that the comment was unnecessary, you have > missed my point that even single sentences can be grammatically bogus and > the writer could learn a lot from Strunk and White or equivalent. I do agree with that 100%. It's a chore reading design and requirements docs where I work. My problem is with excessive comments. Comments are pathological liars. They almost invariably fall out of date with the code. From ed at leafe.com Mon Mar 31 22:41:37 2008 From: ed at leafe.com (Ed Leafe) Date: Mon, 31 Mar 2008 21:41:37 -0500 Subject: class super method In-Reply-To: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> References: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> Message-ID: <09819F33-4661-480D-94FC-1BDB3118890A@leafe.com> On Mar 31, 2008, at 5:58 PM, George Sakkis wrote: >> is there any tutorial for super method (when/how to use it)? >> >> or maybe someone could explain me how it works? >> >> thx > > Super is one of the dark corners of the language [1,2]... a good rule > of thumb is to stay away from it, or at least stick to its basic > usage. I disagree - super is quite elegant and dependable. Because Python support multiple inheritance, it is difficult to manually ensure that when augmenting a method that the correct superclass calls are made. super() handles that without having to guess as to what the correct inheritance hierarchy is. In my own project (Dabo), we use mixin classes liberally to provide consistent behavior across our UI classes. The use of super makes customizing __init__() behavior, for example, quite straightforward. The general form looks like: class DaboUIClass(dabo.ui.dControlMixin, someWxPythonClass): def __init__(self, *args, **kwargs): doOurCustomStuffBeforeTheSuperCall() super(DaboUIClass, self).__init__(*args, **kwargs) doOurCustomStuffAfterTheSuperCall() This has worked reliably for us in every place where we have used it. There's nothing dark and mysterious about it at all. -- Ed Leafe From sturlamolden at yahoo.no Tue Mar 18 10:07:39 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 07:07:39 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> <61a3fe08-268e-464e-9ce5-cc00d7a2e3e2@f63g2000hsf.googlegroups.com> Message-ID: On 18 Mar, 08:00, hellt wrote: > under Microsoft Visual Studio do you mean IronPython instance? AFAIK, with the latest VS 2008 you can develop for CPython and IronPython. http://blogs.msdn.com/haibo_luo/archive/2007/10/16/5482940.aspx From sivashankari127 at gmail.com Thu Mar 6 03:01:46 2008 From: sivashankari127 at gmail.com (sivashankari127 at gmail.com) Date: Thu, 6 Mar 2008 00:01:46 -0800 (PST) Subject: The Fortunate Way!!! Message-ID: <211e06e3-a9e2-4b12-ad53-ae0a1016d121@u72g2000hsf.googlegroups.com> Hi, To know what it is? Click the website below - ---------------------------------------------------------------- http://myprofile127.blogspot.com ----------------------------------------------------------------- From ShiNingyu at gmail.com Wed Mar 12 12:58:30 2008 From: ShiNingyu at gmail.com (Ningyu Shi) Date: Wed, 12 Mar 2008 09:58:30 -0700 (PDT) Subject: Problem with subprocess in threaded enviroment Message-ID: <5972c513-c86c-42bf-bcc8-632dd0f0e8f0@i7g2000prf.googlegroups.com> I'm trying to write a multi-task downloader to download files from a website using multi-threading. I have one thread to analyze the webpage, get the addresses of the files to be downloaded and put these in a Queue. Then the main thread will start some threads to get the address from the queue and download it. To keep the maximum files downloaded concurrently, I use a semaphore to control this, like at most 5 downloads at same time. I tried to use urllib.urlretreive in the download() thread, but from time to time, it seems that one download thread may freeze the whole program. Then I gave up and use subprocess to call wget to do the job. My download thread is like this: def download( url ): subprocess.call(["wget", "-q", url]) with print_lock: print url, 'finished.' semaphore.realease() But later I found that after the specific wget job finished downloading, that download() thread never reach the print url statement. So I end up with files been downloaded, but the download() thread never ends and don't realease the semaphore then block the whole program. My guess is that at the time wget process ends, that specific download thread is not active and missed the return of the call. Any comment and suggestion about this problem? Thanks From hdante at gmail.com Sun Mar 30 00:45:11 2008 From: hdante at gmail.com (hdante) Date: Sat, 29 Mar 2008 21:45:11 -0700 (PDT) Subject: Help me on function definition References: Message-ID: <4c1c2834-2ecb-46b6-a4ee-eb29d23cbf1a@a1g2000hsb.googlegroups.com> On Mar 28, 10:47 pm, "aeneng" wrote: > Hello everyone, Hi, Always avoid reinventing the wheel: from Numeric import array, cross_product a = array([1, 2, 3]) b = array([4, 5, 6]) print cross_product(a, b) See: http://numpy.scipy.org/ http://www.scipy.org/ (hint: consider that many people want to multiply matrices) :-) > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this>>> import cross > > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 > ppp1=u[1]*v[2]-u[2]*v[1] > ppp2=u[2]*v[0]-u[0]*v[2] > ppp3=u[0]*v[1]-u[1]*v[0] > # store the result of the cross product in u > u[0]=ppp1 > u[1]=ppp2 > u[2]=ppp3 > return u #return the cross product of vector u x v. > if __name__=="__main__": > from cvxopt.base import matrix > u=matrix([1.0,0.0,0.0],(3,1)) > v=matrix([0.0,1.0,0.0],(3,1)) > print cross(u,v) > print "file name is %s" %__name__ From sturlamolden at yahoo.no Sun Mar 30 16:56:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 30 Mar 2008 13:56:53 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig References: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> Message-ID: On 30 Mar, 22:21, kmg... at gmail.com wrote: > Hello everybody, > > I'm building a python module to do some heavy computation in C (for > dynamic time warp distance computation). Why don't you just ctypes and NumPy arrays instead? # double timewarp(double x[], int lenx, double y[], int leny); import numpy import ctypes from numpy.ctypeslib import ndpointer from ctypes import c_int _timewarp = ctypes.cdll.timewarp.timewarp # timewarp.dll array_pointer_t = ndpointer(dtype=double) _timewarp.argtypes = [array_pointer_t, c_int, array_pointer_t, c_int] def timewarp(x, y): lenx, leny = x.shape[0], y.shape[0] return _timewarp(x, lenx, y, leny) From george.sakkis at gmail.com Sun Mar 23 12:46:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 09:46:57 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <64091803-4e72-4216-a0a2-879f096cddfb@e6g2000prf.googlegroups.com> On Mar 23, 12:24 pm, a... at pythoncraft.com (Aahz) wrote: > The problem with lambda is that too often it results in clutter (this is > a strictly made-up example off the top of my head for illustrative > purposes rather than any real code, but I've seen plenty of code similar > at various times): > > gui.create_window(origin=(123,456), background=gui.WHITE, > foreground=gui.BLACK, callback=lambda x: x*2) > > That means I need to pause reading the create_window() arguments while I > figure out what the lambda means -- and often the lambda is more > complicated than that. Moreover, because the lambda is unnamed, it's > missing a reading cue for its purpose. In a sense the lambda here is not unnamed; it's name is the name of the keyword argument, 'callback', which is indeed a poor name at in terms of self-documentation. I don't see how replacing the lambda with a (better) named function would be any better than using the same name as a keyword parameter. George From bernard.chhun at gmail.com Sat Mar 8 15:01:37 2008 From: bernard.chhun at gmail.com (Bernard) Date: Sat, 8 Mar 2008 12:01:37 -0800 (PST) Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> Message-ID: Hey Brian, It seems the text you are trying to parse is similar to XML/HTML. So I'd use BeautifulSoup[1] if I were you :) here's a sample code for your scraping case: from BeautifulSoup import BeautifulSoup # assume the s variable has your text s = "whatever xml or html here" # turn it into a tasty & parsable soup :) soup = BeautifulSoup(s) # for every element tag in the soup for el in soup.findAll("element"): # print out its tag & name attribute plus its inner value! print el["tag"], el["name"], el.string that's it! [1] http://www.crummy.com/software/BeautifulSoup/ On 8 mar, 14:49, "Bryan.Fodn... at gmail.com" wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). > > I would like to create a file that would have the structure, > > DoseReferenceStructureType = Site > ... > ... > > Also, there is a possibility that there are multiple lines with the > same tag, but different values. These all need to be recorded. > > So far, I have a little bit of code to look at everything that is > available, > > for line in open(str(sys.argv[1])): > i_line = line.split() > if i_line: > if i_line[0] == " a = i_line[1] > b = i_line[5] > print "%s | %s" %(a, b) > > but do not see a clever way of doing what I would like. > > Any help or guidance would be appreciated. > > Bryan From zerty.david at gmail.com Mon Mar 24 14:38:38 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 24 Mar 2008 15:38:38 -0300 Subject: Problems with wxPython In-Reply-To: <67dd1f930803241000tbce352fp93bf2df6e1d082b1@mail.gmail.com> References: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> <67dd1f930803241000tbce352fp93bf2df6e1d082b1@mail.gmail.com> Message-ID: <5dc598e30803241138q2aae53pb2c452946993ba1a@mail.gmail.com> Thanx On Mon, Mar 24, 2008 at 2:00 PM, Frank Niessink wrote: > Hi David, > > 2008/3/24, David Anderson : > > Hi, If ther's anyone who knows pretty much about wxPython can e-mail me? > I'm > > having some trouble in dealing with some guis here, I would thank u very > > much if you could help me > > You should subscribe to the wxPython users mailinglist and ask there. > It's a very helpful mailinglist. Robin Dunn (wxPython author) is very > active in answering questions from wxPython users. > > See http://www.wxpython.org/maillist.php > > Cheers, Frank > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From MartinRinehart at gmail.com Wed Mar 5 09:49:27 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 06:49:27 -0800 (PST) Subject: Better grammar.txt Message-ID: I previously posted a link to an improved, HTML-based, hyperlinked grammar.txt. Discard that one. This one is much better. http://www.martinrinehart.com/articles/python-grammar.html If you find it useful, thank Gabriel Genellina for encouraging me to get it really right. It includes three corrections to grammar.txt (imagnumber, xor_expr and and_expr) that I've reported. From rockxuan at gmail.com Tue Mar 18 03:44:29 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:44:29 -0700 (PDT) Subject: Swiss watch in www.51cntrade.com Message-ID: <69d413f0-8e96-40b6-a7af-f860957bf044@h11g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From micah at micah.cowan.name Sun Mar 2 16:59:13 2008 From: micah at micah.cowan.name (Micah Cowan) Date: Sun, 02 Mar 2008 21:59:13 GMT Subject: Book Recomendations References: Message-ID: <87bq5w7poh.fsf@micah.cowan.name> Tommy Nordgren writes: > On 2 mar 2008, at 01.56, Ira Solomon wrote: > >> I am an experienced programmer (40 years). I've done Algol (if you've >> heard of that you must be old too), PL/1, VB,VBA, a little C, and a >> few other odd languages (e.g. Taskmate). >> I'm interested in learning Python and have downloaded a slew of books. >> Too many. >> I'd like a recommendation as to which books are considered to be the >> cream of the crop. >> I know there are tutorials on the web, but, again, I don't know the >> quality. I would appreciate recommendations on those as well. >> >> Thanks >> >> Ira >> -- >> http://mail.python.org/mailman/listinfo/python-list > I would recommend "Programming Python", by Mark Lutz, from O'Reillys Programming Python assumes you already have a working knowledge of basic Python programming (that is, it assumes you've read Learning Python). -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From ptmcg at austin.rr.com Tue Mar 25 16:22:06 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 Mar 2008 13:22:06 -0700 (PDT) Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: <9f735816-98a6-4d52-bafc-843c96296c1b@d62g2000hsf.googlegroups.com> On Mar 25, 2:32?pm, blackpawn wrote: > I've been trying to get garbage collection of circular references to > work properly with no success then I noticed the documentation stating > that it just doesn't: > > From documentation on Py_Finalize() -> "Memory tied up in circular > references between objects is not freed. " > > I copy pasted the Noddy example for circular reference breaking from > the documentation and set a break point in its Noddy_dealloc function > and sure enough even that simple example doesn't work properly. > > So what's the deal here? ?:) ?I want all objects to be freed when I > shut down and their destruction functions to be properly called. ?Is > there really no way to make this happen? > > Many thanks for any insights, > Jim It sounds like you are using finalizers like destructors in C++. Don't do this. Garbage collection is not deterministic, and is not supposed to be. Instead, use language features that do similar scope-driven code execution: - try/except/finally - with Put your cleanup code in the finally block, or in the context managers __exit__ method. These will run when the program exits the given scope, without having to play GC shenanigans. -- Paul From ebgssth at gmail.com Sun Mar 2 02:16:42 2008 From: ebgssth at gmail.com (js) Date: Sun, 2 Mar 2008 16:16:42 +0900 Subject: Book Recomendations In-Reply-To: References: Message-ID: I wonder why nobody mension Python Cookbook yet. http://www.oreilly.com/catalog/pythoncook2/ Web version: http://aspn.activestate.com/ASPN/Cookbook/Python/ and Python Standard Library http://www.oreilly.com/catalog/pythonsl/ http://effbot.org/zone/librarybook-index.htm On Sun, Mar 2, 2008 at 4:09 PM, Paddy wrote: > On Mar 2, 12:56 am, Ira Solomon wrote: > > I am an experienced programmer (40 years). I've done Algol (if you've > > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > > few other odd languages (e.g. Taskmate). > > I'm interested in learning Python and have downloaded a slew of books. > > Too many. > > I'd like a recommendation as to which books are considered to be the > > cream of the crop. > > I know there are tutorials on the web, but, again, I don't know the > > quality. I would appreciate recommendations on those as well. > > > > Thanks > > > > Ira > > Hi Ira, > Get Python installed on your machine - I would suggest the latest 2.5 > release then either start up idle (or pythonwin if you have that on > windows), or just type python at a command line prompt to get you to > pythons shell. > > The Python shell together with the official tutorial is a great way to > learn Python. > > If you start to flag, then their are a few videos of pre-teen kids > learning Python here: > http://showmedo.com/videos/python?topic=beginner_programming > If they can learn it .... ;-) > > Welcome to Python, have fun! > > - Paddy. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From benhoyt at gmail.com Wed Mar 19 04:15:45 2008 From: benhoyt at gmail.com (Ben Hoyt) Date: Wed, 19 Mar 2008 21:15:45 +1300 Subject: Is there a way to get __thismodule__? In-Reply-To: <82d28c40803182131j7b887a34j77c2a36586628193@mail.gmail.com> References: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> <82d28c40803182131j7b887a34j77c2a36586628193@mail.gmail.com> Message-ID: <7c93bf1e0803190115nde6f155y44065f00ab8efe88@mail.gmail.com> Aha! Thanks, Jeff. I'd heard about metaclasses, but never really seen them used. Your example was very helpful. This is somewhere that I would personally use a metaclass. That way, > if you define more subclasses of Message, you're not limited to doing > so in that single module. > Cheers, Ben. -- Ben Hoyt, http://benhoyt.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Mar 14 07:39:23 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Mar 2008 12:39:23 +0100 Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Doug Morse wrote: > from multiarray import zeros > import string > > typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', > 'Float':'fd', 'Complex':'FD'} > > def _get_precisions(typecodes): > ? ? lst = [] > ? ? for t in typecodes: > ? ? ? ? lst.append( (zeros( (1,), t ).itemsize()*8, t) ) ? <-- Line 18 > ? ? return lst > > def _fill_table(typecodes, table={}): > ? ? for key, value in typecodes.items(): > ? ? ? ? table[key] = _get_precisions(value) > ? ? return table > > _code_table = _fill_table(typecodes) > > I can't find any reason why line 18 is throwing a "data type not > understood" error. ?It doesn't seem to have anything to do with dynamic > importing, but I can't be sure. ?I would note that "zeros" is a built-in > function found in the "python dll" multiarray.pyd (in the Numeric module > directory). I don't know why, but your module seems to use numpy's multiarray instead of Numeric's: >>> from multiarray import zeros >>> zeros((1,), "1") array([0], '1') >>> from numpy.core.multiarray import zeros >>> zeros((1,), "1") Traceback (most recent call last): File "", line 1, in TypeError: data type not understood Peter From rurpy at yahoo.com Mon Mar 17 16:48:49 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 17 Mar 2008 13:48:49 -0700 (PDT) Subject: elementtree and entities Message-ID: I need to parse little snipits of xml that come from a file that has a large DTD that defines hundreds or entities. But when these snipits are parsed (with elementtree.XML()) without the DTD, the entities are undefined and cause a parse failure. Is there any way to tell elementtree to not fail on undefined entities but just return the entity as text? (Or is this something I have to get the underlying parser to do? How?) Alternatively, can I supply my own entity mapping to elementtree? Prepending the large DTD to each little snippit before parsing seems awfully inefficient. From duncan.booth at invalid.invalid Mon Mar 24 05:52:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Mar 2008 09:52:21 GMT Subject: On copying arrays References: Message-ID: ernesto.adorio at gmail.com wrote: > Is there a conceptual difference between > best =test[:] > and > best = [x for x in test] ? > test is a list of real numbers. Had to use the second form to avoid a > nasty bug > in a program I am writing. I have to add too that I was using psyco > in Python 2.5.1. > The first one will only copy sliceable sequences and will give you a result of the same type as test (e.g. if test is a tuple so is best). The second one will copy any sequence, always results in a list and as a side effect assigns a value to 'x'. The method usually recommended is: best = list(test) as it has no side effects, copies any sequence and may be faster than the list comprehension. As with the second of your examples it always gives you a list. From noreply at noreply.org Wed Mar 19 17:29:33 2008 From: noreply at noreply.org (some one) Date: Wed, 19 Mar 2008 15:29:33 -0600 Subject: Script Request... References: <64ccfbF2bbfckU1@mid.uni-berlin.de> Message-ID: Thanks Diez, I found some docs and examples on urllib2. Now how do i search the string I get from urllib2, lets say I put it in "myURL", How do I search for only Numbers and ".'s" in the "#.#.#.#" pattern. That is all I am interested in with all the data retrieved. Just the IP Address from amongst a bunch of data that I have no use of currently. I would I write a pattern matching function to extract only the IP address from "myURL"? In article <64ccfbF2bbfckU1 at mid.uni-berlin.de>, deets at nospam.web.de says... > some one wrote: > > > Hi all, I am not to familiar with python yet and I am wondering if > > someone can write a script that will monitor my DSL modems IP address > > and notify when it changes, its a 2Wire Advanced DSL Modem. I need to > > know when it changes because I am trying to run my own inhouse server > > and have to update my domain records through verio.com. > > > > The script would need to read the text of a web page( on my modem the > > address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and > > search for a string containing the IP address. > > > > Can anyone help? > > thanks, I'll keep monitoring this thread. > > Try urllib2 to fetch the data, use either string-search, regular expressions > or even BeautifulSoup to extract the data. Use a cron-job to do that on a > regular base or use module time.sleep() together with an endless loop to > monitor that location periodically. > > Show us your concrete efforts, and we will suggest improvements. > > Diez > From Lie.1296 at gmail.com Tue Mar 11 13:06:17 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 10:06:17 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> Message-ID: <152176bd-1249-4c14-9ce8-7334aa52ad9d@d21g2000prf.googlegroups.com> On Mar 11, 11:47?pm, Lie wrote: > On Mar 10, 12:08?pm, Nathan Pinno wrote: > > > How do I factor a number? I mean how do I translate x! into proper > > Python code, so that it will always do the correct math? > > > Thanks in advance, > > Nathan P. > > Factorial algorithm is a very simple and common algorithm, and it's > one of the most basic of all recursive algorithm > def fact(x): > ? ? return x * fact(x - 1) As an exercise (actually I forget), I'll let you figure out yourself why the above function doesn't work. There is only one simple line to be added and all's done. Hint: There are two important elements in all recursive algorithm, the catch-all return statement (which I've given you) and the conditioned return statement (which you've got to figure out yourself) From sjmachin at lexicon.net Sun Mar 23 19:31:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 16:31:29 -0700 (PDT) Subject: PyTuple_Check and other type check functions didn't check the NULL pointer References: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> Message-ID: <95174442-c7c0-452b-b2e8-e321d25832d2@c19g2000prf.googlegroups.com> On Mar 24, 10:01 am, NotGuru wrote: > I was writing some C extensions for Python and use PyTupleType_Check > extensively. I found that all the PySomeType_Check macros directly > delegate the job to PyObject_TypeCheck(op, &PyType_Type). The > PyObject_TypeCheck(op, &PyType_Type) is again a macro and defined as > ((ob)->ob_type == (tp) || PyType_IsSubtype((ob)->ob_type, (tp))) > > in object.h. > > My questions is: is it necessary to check the null pointer in the > macro or it's a job for the user? Semantically all the type check > should report a false if a null pointer is encountered. I've already > had the patch to this issue but I am not sure if I think this problem > right. I don't know if there are some python core developers around > but I would like to hear all opinions towards this. > > BTW, if the user didn't check null pointer before call the function, a > segmentation fault might occur. You should check for null pointer returned by any C-API function that is meant to return an object pointer; this indicates that an exception has happened; your code should clean up and exit. See section 1.3 of the Python/C API Reference Manual. From fuzzyman at gmail.com Sun Mar 30 13:29:22 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 30 Mar 2008 10:29:22 -0700 (PDT) Subject: Buffer Overflow with Python 2.5 on Vista in import site References: Message-ID: On Mar 30, 3:53 am, "Gabriel Genellina" wrote: > En Sat, 29 Mar 2008 17:34:27 -0300, Fuzzyman escribi?: > > > A very odd error with Python 2.5 (both 2.5.1 and 2.5.2 from the > > official msi installers and running on Vista under Parallels on the > > Mac). > > It may be actually a Parallels issue - I've installed 2.5.1 on Vista (just > once, on a real PC) and it worked fine. Anyway a better place for bug > reports is bugs.python.org > > Mmm, maybe you should check all your .pth files - looks like this strange > path comes from one of them. I think it comes from the '._something.pth' that Textmate created as a temporary file when I edited a 'pth' file. The 'macromates' text in their is from textmate. I'm not sure if it is Mac specific or Texmate specific, but those temp files are really annoying. Thanks. Michael http://www.ironpythoninaction.com/ > > -- > Gabriel Genellina From rpdooling at gmail.com Wed Mar 26 15:50:51 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Wed, 26 Mar 2008 12:50:51 -0700 (PDT) Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: On Mar 26, 9:12 am, waltbrad wrote: > On his command line he types: > > C:\...\PP3E>Launcher.py > > and this begins the program. Doesn't work for me. I have to type: > > C:\...\PP3E>python Launcher.py > > Is this a typo on his part or has he configured his settings in such a > way that the command line will automatically associate the extension > with the program? (If so, he didn't mention this in his book). Browse this thread on clp: http://tinyurl.com/2wbnde RD From timr at probo.com Wed Mar 19 03:18:10 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Mar 2008 07:18:10 GMT Subject: placing a Python com object into Excel References: <47deefc5$0$906$ba4acef3@news.orange.fr> Message-ID: Mathew wrote: >Thanks for the tip. But, instead of an AddIn, what if I want to be able >to insert an object? I see that the demo adds items to the windows >registry under \Excel\AddIns. Is there a similar location for the >"Insert Object" command? What you see there is the list of registered ActiveX controls. You need to implement a few additional interfaces. I believe IOleInPlaceObject is required to satisfy Excel. http://msdn2.microsoft.com/en-us/library/aa751972.aspx -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Tue Mar 4 16:40:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 4 Mar 2008 16:40:53 -0500 Subject: for-else References: Message-ID: wrote in message news:c4921e6c-119f-4306-8e89-c436c3cb6f6d at u69g2000hse.googlegroups.com... | So far in Python I've almost hated the 'else' of the 'for' loops: | - I have problems to remember its meaning; Consider the following pseudoPython which you should understand: label: loop if cond: do_something() goto loop else: do_else() We actually write the above as while cond: do_something() else: do_else() Same meaning; do_else is executed when condition is false. A for-loop is equivalent to a while loop with the condition 'iterator is not exhausted'. So do_else when that condition is false -- the iterator is exhausted. Terry Jan Reedy From davidj411 at gmail.com Tue Mar 11 10:58:28 2008 From: davidj411 at gmail.com (davidj411) Date: Tue, 11 Mar 2008 07:58:28 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> Message-ID: <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> > Persistent storage /is/ the benefit. If you want to store relational > data, you should use a relational database. Thanks, that makes sense. Are there any local relational databases available to python that don't require a server backend? From noreply at noreply.org Thu Mar 20 06:45:15 2008 From: noreply at noreply.org (some one) Date: Thu, 20 Mar 2008 04:45:15 -0600 Subject: What is The Eric4 IDE??? Message-ID: I wanted to ask some opinions on the Eric4 Python IDE, It was the second result from google using the search term "Python IDE" (Quotes Included in the search), the first being http://wiki.python.org/moin/IntegratedDevelopmentEnvironments ! I haven't downloaded or installed it yet, since it has the prerequisites of: 1) Python 2.4.0 or better http://www.python.org/download/ 2) Qt 4.2.0 or better (from Trolltech) http://trolltech.com/solutions/solutions-opensource 3) PyQt 4.1.0 or better (from Riverbank) http://www.riverbankcomputing.co.uk/pyqt/index.php 4) QScintilla 2.1 or better (from Riverbank) http://www.riverbankcomputing.co.uk/qscintilla/index.php I see on the Eric4 website ( http://www.die-offenbachs.de/eric/eric4- download.html ) that it is also a commercial product for those not working with OpenSource, so I hope it's safe to assume that it's a good product to use for working with Python. I'd like some other opinions about it before I download and install all the prerequisites. They probably require their own specific configurations. Is there an OpenSource bundle with all the prerequisites for a smoother install? Is there a specific order to install the prerequisites? Thanks in advance for your replies. From gagsl-py2 at yahoo.com.ar Thu Mar 27 18:36:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 19:36:02 -0300 Subject: python program deleted References: <200803271808.06157.inq1ltd@inqvista.com> Message-ID: En Thu, 27 Mar 2008 19:08:05 -0300, jim-on-linux escribi?: > I developed a python program and used py2exe > to create the exe. > > I zip the entire package and email it to my > clients. > > Some clients get the zip file, unzip the > package and everything works fine. > > And some clients get my email with an icon > attached which has the correct filename but > the size is 8k when it should be about 5 mb. > > I've renamed the file without the zip ext. > and tried other renaming schemes without > success. > > Has anyone had this experience? Any ideas on > how to solve this problem. Yes: don't send the program by email :) Put it somewhere for your customers to download. Use some authorization scheme (user/password) if needed. -- Gabriel Genellina From steve at holdenweb.com Sat Mar 1 15:01:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 15:01:51 -0500 Subject: Surprised by the command "del" In-Reply-To: <62tq9sF24juhrU1@mid.individual.net> References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: K Viltersten wrote: > I'm reading the docs and at 5.2 the del > statement is discussed. At first, i thought > i've found a typo but as i tried that > myself, it turns it actually does work so. > > a = ["alpha", "beta", "gamma"] > del a[2:2] > a > > Now, i expected the result to be that the > "beta" element has been removed. Obviously, > Python thinks otherwise. Why?! > > Elaboration: > I wonder why such an unintuitive effect has > been implemented. I'm sure it's for a very > good reason not clear to me due to my > ignorance. Alternatively - my expectations > are not so intuitive as i think. :) > It deletes all the elements referred to by the slice. But since 2-2==0, there are zero elements in the slice, and the list is unchanged when all zero of them have been deleted: >>> a = ["alpha", "beta", "gamma"] >>> a[2:2] [] >>> You would have got the result you expected with del a[2] or del a[2:3] or del a[-1] or ... Remember that slices are specified as half-open intervals. So a[m:n] includes m-n elements, those indexed from m to n-1. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fetchinson at googlemail.com Tue Mar 11 02:20:53 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 23:20:53 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > | The various free tools differ by their chosen optimization paths and > | their degree of specialization. My preference would be, > | > | 1. Doesn't really matter how long it takes to compute the N numbers per > image > > Your problem here is that there is really no such thing as 'general > features' and correspondingly, no such thing as 'general similarity of > features'. Yes there are! :) Image manipulation experts defined dozens of ways of characterizing what 'similarity' means for images and all I was asking is whether anyone here knew of a simple one. > The features extracted have to have a specific definition. The > features represent a severe lossy compression of the original. What to > keep depends on the application. Yes, and if you know *any* simple but useful (yes, useful, in *any* sense) definition, I'd be happy to hear it. > Example: classify each pixel as white, black, red, green, or blue. Will > that match your intuitive idea of what matches? Probably not, but thanks for the idea. > To be a bit more sophisticated, use more color bins and do the binning > separately for multiple areas, such as top, left, center, right, and bottom > (or center, upper right, upper left, lower right, and lower left). I > suspect Google does something like this to match, for instance, pictures > with skin tones in the center, or pictures with blue tops (sky?) and green > bottoms (vegetation?). Now this sounds like a simple and good idea. I'll try this and see how far I get. > | 2. Lookups should be fast, consequently N should not be too large (I > guess) > | 3. It should be a generic algorithm working on generic images (everyday > photos) > > Given feature vectors, there are various ways to calculate a distance or > similarity coefficient. There have been great debates on what is 'best'. True. As I've said, *any* but concrete and useful example would make me happy. > | 4. PIL should be enough for the implementation > | > | So if anyone knows of a good resource that is close to being pseudo > | code I would be very grateful! > > If you do not have sufficient insight into your own idea of 'matches', try > something on a test set of perhaps 20 photos, calculate a 'match matrix', > and compare that you your intuition. Yes, this is what I'll do. The second thing I'll try (after trying your suggestion) is based on this paper which I found in the meantime: http://salesin.cs.washington.edu/abstracts.html#MultiresQuery In case anyone is interested, it describes a multiresolution querying algorithm and best of all, it has pseudo code for the various steps. I don't know yet how difficult the implementation will be but so far this looks the most promising. Cheers, Daniel From siona at chiark.greenend.org.uk Fri Mar 7 07:44:14 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Mar 2008 12:44:14 +0000 (GMT) Subject: Difference between 'function' and 'method' References: Message-ID: Gabriel Genellina wrote: >En Thu, 06 Mar 2008 23:46:43 -0200, escribi???: >> [ ... ] >You may look at the SimpleXMLRPCServer class and see how it implements >introspection. It's rather easy (and doesn't require metaclasses nor >decorators nor any other fancy stuff; I think it works the same since >Python 2.1). Apparently you're doing a similar thing, but using pickles >instead of xmlrpc. It's not that difficult to graft pickles into SimpleXMLRPCServer -- I've done it, and if you're trying to sling large data structures over the connection it's a massive performance win (even with sgmlop in place to speed up XML parsing). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From ilkeston at ntlworld.com Sun Mar 2 09:15:09 2008 From: ilkeston at ntlworld.com (Steve Turner) Date: Sun, 2 Mar 2008 14:15:09 -0000 Subject: First post from a Python newbiw Message-ID: I finally decided to have a go with Python and am working through the tutorial. On my old BBC Computer I could do something like this: DIM A(2,2) to create a 3 by 3 array of data. Then I could set any point: A(0,0) = foo A(0,1) = bar etc. In Python I thought I could do this with: >>> a=[0,0,0] >>> b=[a,a,a] >>> b [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> b[1][1]='foo' >>> b [[0, 'foo', 0], [0, 'foo', 0], [0, 'foo', 0]] >>> I can understand why as b[1][1]='foo' is actually changing a[1] Apart from doing something like a=[0,0,0] b=[0,0,0] c=[0,0,0] d=[a,b,c] is there a better way of creating d?? -- Steve From miki.tebeka at gmail.com Sun Mar 9 14:11:12 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 9 Mar 2008 11:11:12 -0700 (PDT) Subject: Changing the size of a Button References: <63ifhtF277va7U1@mid.individual.net> Message-ID: Hello Konrad, > How do i change the size of a Button > (using Tkinter), other than to set it > during construction? In Tkinter, usually the geometry managers (such as pack) are the ones who size the widgets. If you run something like: import Tkinter as tk root = tk.Tk() def change_size(): b["text"] = "More text" b = tk.Button(root, text="Text", command=change_size) b.pack() root.mainloop() You'll see that the button changes size to accommodate the new text. HTH, -- Miki http://pythonwise.blogspot.com From fakeaddress at nowhere.org Fri Mar 21 08:31:08 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 21 Mar 2008 05:31:08 -0700 Subject: What Programming Languages Should You Learn Next? In-Reply-To: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> Message-ID: wesley chun wrote: > http://it.slashdot.org/it/08/03/18/1633229.shtml > > it was surprising and disappointing that Python was not mentioned > *anywhere* in that article but when someone replied, it sparked a long > thread of post-discussion. What I found disappointing was how many people thought they should be answering the question rather than asking it. I'm good with a number of popular languages, and I can talk knowledgeably and BS-free about many more. In grad school, I had an instructor who is a real programming language expert. Listening to his lectures was sometimes a bit like watching ESPN show the world championship of a game at which I usually beat my friends. There are levels beyond levels beyond my level. And I'm a pro. It is to the shame of my alma mater that they denied tenure to Dr. Sasaki. -- --Bryan From http Sat Mar 29 07:59:00 2008 From: http (Paul Rubin) Date: 29 Mar 2008 04:59:00 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> Message-ID: <7x3aq9212z.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > reserve <> for "greater than or less than but not equal to" which is > subtly different. (Think about unordered values, where x != y does not > imply that x < y or x > y, e.g. IEEE NaNs.) Heh, good point. > > The scary choice is /= which can be interpreted as an assignment. > "Can be"? Yes, what I mean is that some languages (e.g. Ada, Haskell) use /= for nonequality. So if you switch between Haskell and C, you could find yourself typing /= when you mean != and the compiler won't flag it. From aahz at pythoncraft.com Tue Mar 11 15:37:59 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Mar 2008 12:37:59 -0700 Subject: mulithreaded server References: <0e845694-2788-43e2-b88b-86bbbbe3c7c0@e23g2000prf.googlegroups.com> Message-ID: In article <0e845694-2788-43e2-b88b-86bbbbe3c7c0 at e23g2000prf.googlegroups.com>, asit wrote: >On Mar 11, 9:10 pm, Jean-Paul Calderone wrote: >> On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit wrote: >>> >>>In the above program, why there is an unhandeled exception ??? >> >> Just a guess. You should really include the traceback when you ask a >> question like this. > >It's not a traceback error. It's an unhandeled exception..please help http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From bearophileHUGS at lycos.com Fri Mar 7 07:49:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 7 Mar 2008 04:49:19 -0800 (PST) Subject: islice ==> [::] Message-ID: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> I find itertools.islice() useful, so for Python 3.x I may like to see it removed from the itertools module, and the normal slicing syntax [::] extended to work with generators/iterators too. from itertools import islice primes = (x for x in xrange(1,999) if all(x % y for y in xrange(2, x))) print list(islice(primes, 0, 20)) ==> print list(primes[:20]) Bye, bearophile From castironpi at gmail.com Fri Mar 7 17:26:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 14:26:25 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: <18b456bf-bc3d-45f6-af92-369e01e0f426@o77g2000hsf.googlegroups.com> On Mar 7, 3:19?pm, "Chris Mellon" wrote: > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > > ?I would like to build a class for a data structure such that nodes of > > ?the data structure - of interest only to the data structure > > ?implementation itself and not to the consumer - are instances of one > > ?of two class types. ?I thought to encapsulate the nodes' classes [a certain way] > Not only is the name not defined, the class doesn't even exist yet. > > > ?What is the Pythonic thing I should be doing instead? > > Don't nest them. [ Too much anything is waste.] You expose a problem with the way I and some others write code. Humans have enormous "mental stacks"--- the stacks the contexts the speakers speak in push things they're hearing on to. When writing for computers, even those that speak Python, you have to say one thing at a time, and let it get its mind around it. They're not that deep, they're just at a deep depth. (The depth the ocean the submarine's in has, not the depth the submarine's -at-.) Marvelous memories, though. Your robotic snake can also do symbolic calculus, radio to clusters, and generate arbitrary auditory waveforms. But in a snake, the snake functions are primary. What's a multiplexer? From reginaa11111 at gmail.com Mon Mar 17 06:50:03 2008 From: reginaa11111 at gmail.com (reginee) Date: Mon, 17 Mar 2008 03:50:03 -0700 (PDT) Subject: THE AMAZING GOOGLE NETWORK INVITES YOU TO MAKE MILLIONS OF DOLLARS BY DOING A SIMPLE ONLINE WORK.THE LINK IS BELOW Message-ID: <62538771-9cc4-45ec-9638-a35b7aca4935@e6g2000prf.googlegroups.com> THE AMAZING GOOGLE NETWORK INVITES YOU TO MAKE MILLIONS OF DOLLARS BY DOING A SIMPLE ONLINE WORK.THE LINK IS BELOW www.jeeva235.blogspot.com IF YOU WORK LITTLE HARD YOU MAY EARN $3,00,000 IN A SINGLE PROJECT From dstromberglists at gmail.com Thu Mar 20 14:45:55 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 20 Mar 2008 18:45:55 GMT Subject: Python to C/C++ References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: On Wed, 19 Mar 2008 10:24:16 -0700, Patrick Mullen wrote: > (sorry michael, didn't mean to personal post > > On Wed, Mar 19, 2008 at 9:24 AM, Michael Wieher wrote: > > I think py2exe does this, but it might be a bit bloated > > No, py2exe basically bundles the main script and the interpreter > together so it's easy to run and requires no python installation. > > Look into pyrex and pypy. A mature translator doesn't exist. Also > there is ctypes which goes in reverse letting you use more c from > python easily. I believe pyrex allows you to write very python-like code but build a binary extension module from it that runs at nearly C speed. ISTR it does generate .c files. There's also shedskin, which I believe is a static python -> C++ translator that was written as part of google's summer of code. From jphalip at gmail.com Mon Mar 24 07:21:29 2008 From: jphalip at gmail.com (Julien) Date: Mon, 24 Mar 2008 04:21:29 -0700 (PDT) Subject: Shortcutting the function call stack Message-ID: Hello all, I would like to do something like: def called(arg) if arg==True: !!magic!!caller.return 1 def caller(arg) called(arg) return 2 Here, the fake !!!magic!!! represents a statement (which I ignore) that would make the caller function return a value different from what it'd return normally. For example, caller(True) would return 1, and caller(False) would return 2. The reason I want that is because I don't want the caller function to know what's going on in the called function, and be shortcut if the called function think it's necessary. Would you know if that's possible, and if so, how? I've done a bit of research and I think I've found some good pointers, in particular using the 'inspect' library: import inspect def called(arg) if arg==True: caller_frame = inspect.stack()[1] ... Here 'caller_frame' contains the frame of the caller function. Now, how can I make that frame return a particular value? By the way, I'm not really interested in 'called' throwing an exception and 'caller' catching it. In fact, I want things to remain completely transparent for 'caller'. Hope that was clear... :/ Thanks! Julien From floris.bruynooghe at gmail.com Fri Mar 14 10:47:15 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Fri, 14 Mar 2008 07:47:15 -0700 (PDT) Subject: How to send a var to stdin of an external software References: Message-ID: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> On Mar 14, 11:37 am, Benjamin Watine wrote: > Bryan Olson a ?crit : > > > I wrote: > >> [...] Pipe loops are tricky business. > > >> Popular solutions are to make either the input or output stream > >> a disk file, or to create another thread (or process) to be an > >> active reader or writer. > > > Or asynchronous I/O. On Unix-like systems, you can select() on > > the underlying file descriptors. (MS-Windows async mechanisms are > > not as well exposed by the Python standard library.) > > Hi Bryan > > Thank you so much for your advice. You're right, I just made a test with > a 10 MB input stream, and it hangs exactly like you said (on > cat.stdin.write(myStdin))... > > I don't want to use disk files. In reality, this script was previously > done in bash using disk files, but I had problems with that solution > (the files wasn't always cleared, and sometimes, I've found a part of > previous input at the end of the next input.) > > That's why I want to use python, just to not use disk files. > > Could you give me more information / examples about the two solutions > you've proposed (thread or asynchronous I/O) ? The source code of the subprocess module shows how to do it with select IIRC. Look at the implementation of the communicate() method. Regards Floris From dickinsm at gmail.com Sat Mar 8 12:03:09 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 09:03:09 -0800 (PST) Subject: float / rounding question References: <13t456cmgfpdhbc@corp.supernews.com> Message-ID: <29d0e1f9-3554-4f92-8a01-9519fb9d30d1@60g2000hsy.googlegroups.com> On Mar 8, 11:34?am, Mark Dickinson wrote: > following, which arises from Python arbitrarily stripping trailing > zeros from the result returned by the C library functions: Correction: on closer examination it's not Python doing the stripping of trailing zeros; it's the C library. Mark From manlio_perilloNO at SPAMlibero.it Wed Mar 26 15:08:48 2008 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Wed, 26 Mar 2008 19:08:48 GMT Subject: Beta testers needed for a high performance Python application server References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> <47e9f77b$0$36357$742ec2ed@news.sonic.net> Message-ID: <4bxGj.275580$%k.395923@twister2.libero.it> Il Wed, 26 Mar 2008 00:22:38 -0700, John Nagle ha scritto: > Graham Dumpleton wrote: >> Yes that is a viable option, as still are existing fastcgi solutions >> for Apache, lighttpd and nginx. > > Fast cgi is a good technology, Well, not really so good: http://twistedmatrix.com/pipermail/twisted-web/2006-April/002598.html > but it's not well documented or > well supported. For some reason, the Apache people don't like it. It > used to be part of the Apache distribution, but that ended years ago. > > It's more reliable than using things like mod_python, where you have > application code running in the web server's address space. That > creates both security problems and robustness problems. If an fcgi > process crashes, it is automatically replaced by a fresh copy of the > program at the next request. Other activity in progress is not > affected. Also, fcgi processes are reloaded after some number of > requests, so minor memory leaks won't choke the system over time. > The problem is simple: why put an extra server layer between an HTTP client and an HTTP server? Moreover, you should not use mod_python as an example. The WSGI module for Apache has a lot of feature for reducing these problems; and as an alternative you can use the WSGI implementation for Nginx. > [...] Manlio Perillo From P.G.Aravindh at gmail.com Mon Mar 10 10:21:45 2008 From: P.G.Aravindh at gmail.com (Santhosh) Date: Mon, 10 Mar 2008 07:21:45 -0700 (PDT) Subject: Recipies of South INDIA Message-ID: If you want to know how to make delicious South Indian foods please visit http://recipesoftamilnadu.blogspot.com/ From tsuraan at gmail.com Sat Mar 15 22:56:35 2008 From: tsuraan at gmail.com (tsuraan) Date: Sat, 15 Mar 2008 21:56:35 -0500 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: <84fb38e30803151956w3af4db24pca2740c79760981e@mail.gmail.com> > Python doesn't have memory leaks. Yeah, interesting bit of trivia: python is the world's only non-trivial program that's totally free of bugs. Pretty exciting! But seriously, python 2.4, at least, does have some pretty trivially exposed memory leaks when working with strings. A simple example is this: >>> letters = [chr(c) for c in range(ord('a'), ord('z'))+range(ord('A'), ord('Z'))] >>> ary = [] >>> for a in letters: ... for b in letters: ... for c in letters: ... for d in letters: ... ary.append(a+b+c+d) ... >>> del(ary) >>> import gc >>> gc.collect() 0 The VM's memory usage will never drop from its high point of (on my computer) ~200MB. Since you're using GIS data, this could be what you're running into. I haven't been able to upgrade my systems to python 2.5, but from my tests, that version did not have that memory leak. Nobody seems interesting in backporting fixes from 2.5 to 2.4, so you're probably on your own in that case as well, if upgrading to python 2.5 isn't an option or isn't applicable to your situation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 15 04:33:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 06:33:30 -0200 Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: En Thu, 13 Mar 2008 15:18:44 -0200, escribi?: > Well, lets say you have a situation where you're going to be > alternating between sending large and small chunks of data. Is the > solution to create a NetworkBuffer class and only call send when the > buffer is full, always recv(8192)? No need to reinvent the wheel. socket objects already have a makefile method returning a file-like object, which behaves like a buffered socket. -- Gabriel Genellina From MartinRinehart at gmail.com Wed Mar 5 12:34:46 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 09:34:46 -0800 (PST) Subject: Better grammar.txt References: Message-ID: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> MartinRineh... at gmail.com wrote: > It includes three corrections to grammar.txt (imagnumber, xor_expr and > and_expr) that I've reported. Make that four corrections. Add augop. From jeff at schwabcenter.com Thu Mar 20 11:28:39 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 08:28:39 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: <13u50796m76e9c7@corp.supernews.com> References: <13u50796m76e9c7@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-03-20, jmDesktop wrote: > >> Hi, I'm trying to learn Python. I using Aquamac an emac >> implementation with mac os x. I have a program. If I go to the >> command prompt and type pythong myprog.py, it works. Can the program >> be run from within the editor or is that not how development is done? >> I ask because I was using Visual Studio with C# and, if you're >> familiar, you just hit run and it works. On Python do I use the >> editor for editing only and then run the program from the command >> line? > > http://www.google.com/search?q=emacs+python Or achieve a similar (more flexible (IMO), but less smoothly integrated) effect with Vim and GNU Screen. Until recently, you had to patch Screen if you wanted vertical splits, but now it's in the main line. From guidovb1 at invalid Sun Mar 16 12:25:26 2008 From: guidovb1 at invalid (Guido van Brakel) Date: Sun, 16 Mar 2008 17:25:26 +0100 Subject: Basics of Python,learning Message-ID: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Hello Why is this not working,and how can I correct it? > #!/usr/bin/env python > #coding=utf-8 > > z = raw_input ('Give numbers') > y = z.split() > b=[] > > for i in y: > b.append(float(i)) > > def b(min,max,gem) > x=min(a) > x=gem(a) > x=max(a) > return a > > print min(a) > print max(a) > print gem(a) Regards, -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- From Minor.Gordon at cl.cam.ac.uk Tue Mar 25 16:31:39 2008 From: Minor.Gordon at cl.cam.ac.uk (Minor Gordon) Date: Tue, 25 Mar 2008 20:31:39 +0000 Subject: Beta testers needed for a high performance Python application server Message-ID: <47E9612B.5010401@cl.cam.ac.uk> Hello all, I'm looking for beta testers for a high performance, event-driven Python application server I've developed. About the server: the front end and other speed-critical parts of the server are written in portable, multithreaded C++. The back end is an embedded CPython interpreter. The server is much faster than anything in pure Python, and it can compete with C servers (including e.g. lighttpd for file workloads) or outdo them (e.g. anything behind Apache) until CPython consumes a single processor. On the Python side it supports WSGI (the server can handle the static and dynamic requests of MoinMoin with a handful of lines), the DB API with blocking calls offloaded to a connection in a separate thread (MySQL, SQLite supported), Google's ctemplate, gzipping responses, file caching, reading and writing to URIs as a client, AJAX integration, debugging as a Python extension, and a lot of other features. The core Python API is event-driven, using continuations like Twisted but much cleaner (continuations are any callables, there are no special objects anywhere). The Python back end also supports Stackless Python so all of the continuation machinery can be hidden behind tasklet switching. Background: I'm in this to help write a "story" for Python and web applications. Everyone likes to go on about Ruby on Rails, and as far as I can tell there's nothing that approaches Rails in Python. I want to code quickly in Python like I can with Rails, but without sacrificing single node performance on many cores. Beta testers: should be intermediate to advanced Python programmers with demanding applications, particularly web applications with databases and AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory libraries beyond python-dev. Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. Minor From sjmachin at lexicon.net Sat Mar 22 17:47:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 14:47:46 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> <64lbj3F2an71mU3@mid.uni-berlin.de> Message-ID: <7982df0e-4c03-40d8-8e89-4fa6c7b01d4b@s37g2000prg.googlegroups.com> On Mar 23, 8:21 am, Marc 'BlackJack' Rintsch wrote: > On Sat, 22 Mar 2008 13:27:49 -0700, sgharvey wrote: > > ... and by works, I mean works like I expect it to. > > > I'm writing my own cheesy config.ini parser because ConfigParser > > doesn't preserve case or order of sections, or order of options w/in > > sections. > > > What's confusing me is this: > > If I try matching every line to one pattern at a time, all the > > patterns that are supposed to match, actually match. > > If I try to match every pattern to one line at a time, only one > > pattern will match. > > > What am I not understanding about re.search? > > That has nothing to do with `re.search` but how files work. A file has a > "current position marker" that is advanced at each iteration to the next > line in the file. When it is at the end, it stays there, so you can just > iterate *once* over an open file unless you rewind it with the `seek()` > method. > > That only works on "seekable" files and it's not a good idea anyway > because usually the files and the overhead of reading is greater than the > time to iterate over in memory data like the patterns. > Unless the OP has changed the pastebin code since you read it, that's absolutely nothing to do with his problem -- his pastebin code slurps in the whole .ini file using file.readlines; it is not iterating over an open file. From xkenneth at gmail.com Sun Mar 9 17:44:24 2008 From: xkenneth at gmail.com (xkenneth) Date: Sun, 9 Mar 2008 14:44:24 -0700 (PDT) Subject: Logically/Selectively Sub Class? References: <63j3ltF282fssU1@mid.uni-berlin.de> Message-ID: On Mar 9, 4:38?pm, "Diez B. Roggisch" wrote: > xkenneth schrieb: > > > Might be a silly question, but is it possible to selectively subclass, > > IE subclass is a supporting module is present and not otherwise. > > Yes, something like this should work > > class Foo(some, base, classes) > ? ? pass > > if condition: > ? ? Temp = Foo > ? ? class Foo(Temp, otherclass): pass > > Alternatively, you can use the type-function to create classes explicit > with a list of base-classes. > > However it smells after bad design... what's your actual usecase? > > Diez Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB for a lot of my stuff now, and I need my objects to be persistent, however there might be a case where my classes could be used in a non- persistent manner. I'll just have ZODB as a requirement for my package. Regards, Kenneth Miller From afandimscit at gmail.com Mon Mar 31 10:22:40 2008 From: afandimscit at gmail.com (afandi) Date: Mon, 31 Mar 2008 07:22:40 -0700 (PDT) Subject: How to insert multiple rows in SQLite Dbase References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> <657h3nF2eehi8U1@mid.uni-berlin.de> Message-ID: On Mar 30, 4:46 am, Gerhard H?ring wrote: > Gabriel Genellina wrote: > > [...] > > and execute: > > cur.executemany("insert into log (IP, EntryDate, Requestt, ErrorCode) > > values (:ip, :date, :request, :errorcode)", values) > > It's probably worth mentioning that pysqlite's executemany() accepts > anything iterable for its parameter. So you don't need to build a list > beforehand to enjoy the performance boost of executemany(). > > The deluxe version with generators could look like this: > > def parse_logfile(): > logf = open(...) > for line in logf: > if ...: > row = (value1, value2, value3) > yield row > logf.close() > > ... > > cur.executemany("insert into ... values (c1, c2, c3)", parse_logfile()) > > -- Gerhard > > PS: pysqlite internally has a statement cache since verson 2.2, so > multiple execute() calls are almost as fast as executemany(). Thanks regards to your suggestion, but I don't understand why we have to put the IF statement? From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:14:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:14:00 -0700 (PDT) Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> <63hq8rF27chv6U1@mid.uni-berlin.de> <96486094-0706-45f1-b5c1-4af6333e3955@s13g2000prd.googlegroups.com> Message-ID: <25c0b8eb-683a-4703-ba76-906dbb762570@8g2000hse.googlegroups.com> On 9 mar, 15:37, I V wrote: > On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote: > > Well, that suits me. The most unnatural thing about Python was adapting > > to the idea of just letting unreleased resources go jogging off > > wherever. :) > > Yes, that's a bad habit that garbage collection can encourage. GC is good > for managing memory, but not good for managing other resources, so if an > object holds some other resource, it's important to make sure the > resource is released in a timely fashion rather than relying on the > finalizer (the __del__ function). > > Although, you still don't need f.close, with the new with statement: > > with open('myfile') as f: > ? ? ? ? string = f.readline() > # f.close() gets called automatically here, without waiting for ? ? ? ? > # garbage collection. Just for completeness, on earlier Python versions, the way to ensure that resources are always released is using try/finally: f = open(...) try: ...work with file... finally: f.close() -- Gabriel Genellina From deets at nospam.web.de Wed Mar 26 16:23:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 21:23:40 +0100 Subject: A question on decorators In-Reply-To: References: Message-ID: <64vpmnF2dvlccU1@mid.uni-berlin.de> Tim Henderson schrieb: > Hello > > I am writing an application that has a mysql back end and I have this > idea to simplify my life when accessing the database. The idea is to > wrap the all the functions dealing with a particular row in a > particular in a particular table inside a class. So if you have a > table that looks like this: > > id str1 str2 pickled_data1 pickled_data2 > 0 woeif aposf (bin) (bin) > 1 ofime powe (bin) (bin) > ... > n oiew opiwe (bin) (bin) > > you can access this table like this > > t = Table(id) #to load a pre-entered row > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > when you change a an attribute of the class like this... > t.str1 = 'new value' > > it automatically updates the database backend. > > I have what I just described working. However I want an easier way to > deal with my pickled_data. Right now I am pickling dictionaries and > list types. Now there is one problem with this, let me demonstrate > > t.data.update({'new key':'new value'}) > print t.data > {... 'new key':'new value' ...} > > which makes it appear that the database has been updated as well, but > in fact it hasn't to update the database with this scheme you actually > have to do this. > > t.data.update({'new key':'new value'}) > t.data = t.data > > this is not ideal so I subclassed the built in dict type like this: > > class _my_dict(dict): > > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > self.update_db() > > def __delitem__(self, key): > if self.write_access: > dict.__delitem__(self, key) > self.update_db() > > def __setitem__(self, key, value): > if self.write_access: > dict.__setitem__(self, key, value) > self.update_db() > > > def clear(self): > if self.write_access: > dict.clear(self) > self.update_db() > > ... > more methods which are simliar > ... > > def update_db(self): > if self.write_access: > con = get_dbConnection() > cur = con.cursor() > > table = self.experiment.TABLE > row_index_name = self.row_index_name > row_index = self.row_index > column_name = self.column_name > column_value = MySQLdb.escape_string(pickle.dumps(self)) > > q1 = '''UPDATE %(table)s > SET %(column_name)s = '%(column_value)s' > WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() > > cur.execute(q1) > con.close() > > > Now while this works, it is a lot of work. What I want to be able to > do is something where I write one decorator function that > automatically updates the database for me. So let us pretend I have > this function. > > let: dec_update_db() be my decorator which updates the dictionary. > > to use this function it seems I would probably still have to subclass > dict like this: > > class _my_dict2(dict): > > @dec_update_db > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > @dec_update_db > def __delitem__(self, key): > dict.__delitem__(self, key) > > @dec_update_db > def __setitem__(self, key, value): > dict.__setitem__(self, key, value) > > @dec_update_db > def clear(self): > dict.clear(self) > > ... and so on ... > > this is also not ideal. because I still have to apply the decorator to > every function which changes the dictionary. > > What I really want is a way to have the decorator applied > automatically every time a method in dict or a sub class is called. I > feel like this must be possible. Has any one here done anything like > this before? There are a few possibilities - one of them is using a metaclass to apply the decorator to alle methods. Diez From castironpi at gmail.com Mon Mar 17 08:21:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 05:21:54 -0700 (PDT) Subject: String To List References: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> <42858a90-80eb-45ac-8f76-ad9d06ee4fbf@d21g2000prf.googlegroups.com> <4ea462e2-cecc-40fc-a62b-658c0fcc28a6@c19g2000prf.googlegroups.com> Message-ID: <22707a9a-0918-4750-8197-e445f1be75d3@u72g2000hsf.googlegroups.com> > > > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > > > this?? > > > > Thanks for the help... > > > > eval(a) will do the job, but you have to be very careful about using > > > that function. ?An alternative is > > > > [s.strip('\'"') for s in a.strip('[]').split(', ')] > > > This will fall over if xyz or abc include any of the characters your > > stripping/splitting on (e.g if xyz is actually "To be or not to be, > > that is the question"). ?Unless you can guarantee they won't, you'll > > need to write (or rather use) a parser that understands the syntax. > > > Iain > > Thinking about this some more; could the string module not use a > simple tokenizer method? ?I know that relentlessly adding features to > built-ins is a bad idea, so I'm not sure if this falls within > batteries-included, or is actually just adding bulk. ?On the one hand, > it's not difficult to write a simple state-based token parser > yourself, but on the other it is also quite easy to include a pile of > bugs when you do. ?By simple I mean something like: > > def tokenize(string, delim, closing_delim=None, escape_char=None) > > which would return a list (or a generator) of all the parts of the > string enclosed by delim (or which begin with delim and end with > closing_delim if closing_delim is set), ignoring any delimiters which > have been escaped by escape_char. ? Throw an exception if the string > is malformed? (odd number of delimiters, or opening/closing delims > don't match) > > In the OP's case, he could get what he want's with a simple: ? l = > a.tokenize("'") Slippery slope, though, to nested delimiters, and XML after that. Where does shlex get us? Do we want to parse "['xyz', 'abc', ['def','ghi']]" any special way? Are there security concerns past a really low complexity level, such as recursion overflows? From Plemelle at comcast.net Sat Mar 29 18:54:32 2008 From: Plemelle at comcast.net (Paul Lemelle) Date: Sat, 29 Mar 2008 16:54:32 -0600 Subject: pexpect Message-ID: I am trying separate a script that users pexpect into various functions within the same expect session. The problem is that the function does not return control back Main. Any insight into this issue would be greatly appreciated. Below is sample code of the problem. Thanks, Paul ____ import pexpect def sshcon(user, password): go = pexpect.spawn ('/usr/bin/ssh -l root %s '% (user)) go.expect ('Password: ') go.sendline (password) go.interact() #get node info for both clusters. C1_node = raw_input("Enter the ip address for node on cluster 1: ") C1_pass = raw_input("Enter the password for the node on cluster 1: ") sshcon(C1_node, C1_pass) #The function will not run anything pass this point. If I place the #below code into the above funciton than everything works fine. chk = pexpect.spawn('ls') # veriy that you are connected #go to the path chk.expect('# ') chk.sendline('ls') chk.interact( #END From israelu at elbit.co.il Sun Mar 30 11:16:39 2008 From: israelu at elbit.co.il (iu2) Date: Sun, 30 Mar 2008 08:16:39 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> Message-ID: <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> On 30 ???, 15:55, Lie wrote: > On Mar 30, 6:42 pm, iu2 wrote: > > > Hi guys, > > > I'd like to use Python in a commercial application. In fact I would > > like to write the application entirely in Python. > > But I think I wouldn't like telling what language the application is > > written in. > > Why is the reason for that? > Due to Competitors... I don't want to expost the language I use > You can just include it since most users never mess through their > program files and most users doesn't even know what Python is, while > advanced users could guess that you use Python by seeing the file > extension being used (py, pyc, pyo). I intend to use pyinstaller, so there is no .pyc at all. The main problem is when I use small programs (as single EXE) sent to someone as a means of maintenance or debugging. Sending Python's license file together with one EXE seems to me too obvious Another thing, what should the Python's license file be called? From tjreedy at udel.edu Thu Mar 13 02:55:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Mar 2008 02:55:59 -0400 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com><7xy78neffb.fsf@ruckus.brouhaha.com> <7x3aqvf9o2.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7x3aqvf9o2.fsf at ruckus.brouhaha.com... | "Terry Reedy" writes: | > | I don't see what's so inefficient about it necessarily. | > | > The key function is called once per list item, for n calls total. The | > comparision function is called once per comparision. There are at least | > n-1 such calls and typically something on the order of n * lg2(n) calls. | | Right. Depending on the application, calling the comparison function | lg(n) times may be faster than calling the key function once. | | Example: you want to sort a list of strings case-independently, each | string containing a few pages worth of text. There are 10000 strings, | each maybe 10000 chars long. If the strings are pulled in from a file, or stored off to a file, as I would expect in and real app of this sort, the in-memory data to be sorted could/should be tuples of the lowercased strings and files positions. Then no key param is needed. | Then (untested): | | x.sort(xs, key=lower) | | makes a copy of each of the 10000 strings, makes 10000 tuples, sorts, | then releases the temporary strings and tuples. At least 100 | megabytes of memory allocated and 100 million chars copied, even | though any give pair of strings will usually differ somewhere in the | first few characters and there's no need to look past those. | | from string import lower | from operator import eq | from itertools import * | | def xcmp(a,b): | for x,y in izip(a,b)): | c = cmp(x.lower() y.lower()) | if c: return c | return 0 | | x.sort(xcmp) | | runs the comparison function about 14000 times, 14 * 10000 = 140000, not 14000. For each of these, you have a call to izip and multiple calls to .next, cmp, and .lower. That said, this use case of where the potentially needed key is long whereas the actually needed key is much shorter is a better use case than anything I have seen so far. Still, as I figure it, the initial part of each text is lowercased around 28 times, on average. So there can only be a speed saving if the text is more than 28 times the effective actual key. To actually do such a thing, at least more than once, I would be tempted to have the key function take just the first k chars, for k perhaps 50. If the texts average, say, 1500 chars, then the key array would be 1/30 * perhaps 2 (for object overhead) = 1/15 of the original array space. Then run over the 'sorted' array to see if there are any cases where the first 50 chars match and if so, check more to see if a swap needs to be made. Easiest would be to do a simple bubble or insert sort with the full compare. tjr From ptmcg at austin.rr.com Mon Mar 24 09:33:11 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 06:33:11 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <64b3e29d-ce9d-42f9-a285-5001a31d9448@d62g2000hsf.googlegroups.com> On Mar 18, 9:10?pm, Gowri wrote: > Hi, > > I have a service running somewhere which gives me JSON data. What I do > is this: > > import urllib,urllib2 > import cjson > > url = 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/ > tbedi/requestDetails' > params = {'format':'json'} > eparams = urllib.urlencode(params) > request = urllib2.Request(url,eparams) > response = urllib2.urlopen(request) ? ?# This request is sent in HTTP > POST > print response.read() > > This prints a whole bunch of nonsense as expected. I use cjson and am > unable to figure out how to print this json response and I guess if I > can do this, parsing should be straightforward? Gowri - On a lark, I tried using the JSON parser that ships with the examples in pyparsing (also available online at http://pyparsing.wikispaces.com/space/showimage/jsonParser.py). The parsed data returned by pyparsing gives you a results object that supports an attribute-style access to the individual fields of the JSON object. (Note: this parser only reads, it does not write out JSON.) Here is the code to use the pyparsing JSON parser (after downloading pyparsing and the jsonParser.py example), tacked on to your previously- posted code to retrieve the JSON data in variable 's': from jsonParser import jsonObject data = jsonObject.parseString(s) # dump out listing of object and attributes print data.dump() print # printe out specific attributes print data.phedex.call_time print data.phedex.instance print data.phedex.request_call # access an array of request objects print len(data.phedex.request) for req in data.phedex.request: #~ print req.dump() print "-", req.id, req.last_update This prints out (long lines clipped with '...'): [['phedex', [['request', [[['last_update', '1188037561'], ... - phedex: [['request', [[['last_update', '1188037561'], ['numofapproved', '1'],... - call_time: 0.10059 - instance: tbedi - request: [[['last_update', '1188037561'], ['numofapproved', '1'], ... - request_call: requestDetails - request_date: 2008-03-24 12:56:32 UTC - request_timestamp: 1206363392.09 - request_url: http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails?format=json 0.10059 tbedi requestDetails 1884 - 7425 1188037561 - 8041 1188751826 - 9281 1190116795 - 9521 1190248781 - 12821 1192615612 - 13121 1192729887 ... The dump() method is a quick way to see what keys are defined in the output object, and from the code you can see how to nest the attributes following the nesting in the dump() output. Pyparsing is pure Python, so it is quite portable, and works with Python 2.3.1 and up (I ran this example with 2.5.1). You can find out more at http://pyparsing.wikispaces.com. -- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 20 07:33:45 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Mar 2008 12:33:45 +0100 Subject: Prototype OO In-Reply-To: References: Message-ID: <47e24b99$0$24941$426a74cc@news.free.fr> sam a ?crit : > > Some time ago (2004) there were talks about prototype-based languages > and Prothon emerged. > > Can someone tell me why class-based OO is better that Prototype based, For which definition of "better" ?-) > especially in scripting langage with dynamic types as Python is? > > > Here are some links: > > http://c2.com/cgi/wiki?PrototypeBasedProgramming Most of the arguments in favor of prototypes seems to come to, mainly: 1/ it lets you customize behaviour on a per-object base 2/ it removes the mental overhead of inheritance, classes etc Point 1. is a non-problem in Python, since you can already add/replace methods on a per-objec basis (ok, with a couple restrictions wrt/ __magic__ methods and such). Point 2. is not (IMHO) such a problem in Python, where inheritance is mainly an implementation detail (it's not needed for polymorphic dispatch to work) and class hierarchy tend to be very flat, when they even exist. Mainly, Python's object system is actually quite close to javascript here. That is, you get more or less the same flexibility. And a couple of powerful features you don't have with javascript (like hooks in the attribute lookup mechanism), too. From kw at codebykevin.com Tue Mar 11 15:08:00 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 11 Mar 2008 15:08:00 -0400 Subject: How to make a Tkinter widget always visible? In-Reply-To: References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> <47D6C81A.1070301@codebykevin.com> Message-ID: <47D6D890.3060104@codebykevin.com> Miki wrote: > Hello Kevin, > >>> Is there a way to make sure that these buttons are always visible? >> There are various ways to do this: you can set the window to be >> non-resizable, or set a minimum size to it, so that it can't be resized >> below that level. However, if you allow arbitrary resizing of the >> window, there's no real way to guarantee that the widgets will be >> visible at all times. > Thanks. > > I've set a minimal size to the window. However when I resize it to be > shorter, the buttons are hidden while the top frame stays visible. > Please post the code you're using--it will be easier to help if we can see exactly what you are trying. --K -- Kevin Walzer Code by Kevin http://www.codebykevin.com From Bryan.Fodness at gmail.com Sat Mar 8 14:49:31 2008 From: Bryan.Fodness at gmail.com (Bryan.Fodness at gmail.com) Date: Sat, 8 Mar 2008 11:49:31 -0800 (PST) Subject: identifying and parsing string in text file Message-ID: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> I have a large file that has many lines like this, SITE I would like to identify the line by the tag (300a,0014) and then grab the name (DoseReferenceStructureType) and value (SITE). I would like to create a file that would have the structure, DoseReferenceStructureType = Site ... ... Also, there is a possibility that there are multiple lines with the same tag, but different values. These all need to be recorded. So far, I have a little bit of code to look at everything that is available, for line in open(str(sys.argv[1])): i_line = line.split() if i_line: if i_line[0] == " <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> Message-ID: <47dc43e0$0$849$ba4acef3@news.orange.fr> Thanks, andrei. I'll try that. Le Sat, 15 Mar 2008 14:25:21 -0700, andrei.avk a ?crit?: > What you want to do is either 1. load everything up into a string, > replace > text, close file, reopen it with 'w' flag, write string to it. OR if > file is too big, you can read each line, replace, write to a temp file, > then when done move the file over the old one. From deets at nospam.web.de Tue Mar 4 07:12:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Mar 2008 13:12:31 +0100 Subject: Eurosymbol in xml document References: Message-ID: <634sleF25sd22U1@mid.uni-berlin.de> Hellmut Weber wrote: > Hi, > i'm new here in this list. > > i'm developing a little program using an xml document. So far it's easy > going, but when parsing an xml document which contains the EURO symbol > ('?') then I get an error: > > UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in > position 11834: character maps to > > the relevant piece of code is: > > from xml.dom.minidom import Document, parse, parseString > ... > doc = parse(inFIleName) The contents of the file must be encoded with the proper encoding which is given in the XML-header, or has to be utf-8 if no header is given. >From the above I think you have a latin1-based document. Does the encoding header match? > > leo at brunello usexml $ locale > LANG=de_DE at euro > LC_CTYPE="de_DE at euro" > LC_NUMERIC="de_DE at euro" > LC_TIME="de_DE at euro" > LC_COLLATE="de_DE at euro" > LC_MONETARY="de_DE at euro" > LC_MESSAGES="de_DE at euro" > LC_PAPER="de_DE at euro" > LC_NAME="de_DE at euro" > LC_ADDRESS="de_DE at euro" > LC_TELEPHONE="de_DE at euro" > LC_MEASUREMENT="de_DE at euro" > LC_IDENTIFICATION="de_DE at euro" > LC_ALL=de_DE at euro This is irrelevant. Diez From bbxx789_05ss at yahoo.com Fri Mar 28 11:38:45 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Mar 2008 08:38:45 -0700 (PDT) Subject: problem with CGIHTTPServer Message-ID: 1) I have this simple cgi server: import CGIHTTPServer import BaseHTTPServer class MyRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = ['/my_cgi_scripts'] server = BaseHTTPServer.HTTPServer( ('', 8111), MyRequestHandler ) server.serve_forever() 2) I have this simple python script: test.py -------- #!/usr/bin/env python import cgitb; cgitb.enable() import cgi print "Content-type: text/html" print print "hello" 3) I have this simple html page with a link that calls test.py: My directory structure looks like this: ../dir1 -------myserver.py -------/my_cgi_scripts ----------------test.py After I start the server script, load the html page in my browser, and click on the link, I get the desired output in my browser, but the server script outputs the following in my terminal: localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/ 1.1" 200 - localhost - - [28/Mar/2008 08:51:22] code 404, message File not found localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 - What are the error messages on lines two and three? From "benjamin.serrato\" at G(oog1e)MAIL.com Tue Mar 18 19:39:16 2008 From: "benjamin.serrato\" at G(oog1e)MAIL.com (oog1e) Date: Tue, 18 Mar 2008 23:39:16 GMT Subject: First Program Bug (Newbie) In-Reply-To: References: Message-ID: Hey, big thanks to you and Gabriel for replying. I couldn't quite follow what you did yet. What is this 'gimpy' thing and where can I read about it? In response: First: Heh, I'm a little embarrassed I didn't notice this. I thought 'I only need to check up to half' but it didn't occur that base**2 was more than 1/2 candidate. Second: I don't quite follow this. Third: Yeah, I found that bug just before, and because of, posting. Fourth: I used the incrementing command and incremented candidates by two to check only odds and now the program is a lot faster. Thanks a lot for yall's replies. Three more things before I go. What is the square root function in python? I couldn't find the fact.py demo script. I didn't mean return I meant 'continue'. Mensanator wrote: > On Mar 17, 7:03 pm, Benjamin Serrato > wrote: >> I Found It!! The following was a post asking for help finding a bug. I >> thought I needed help with my syntax, but just before sending I found >> the bug on line 13. Line 13 should read: "base = 2". I would still >> appreciate any comments on my program. Maybe there is a better way to do >> it that I didn't think about. I know it's not that interesting but it's >> my first one. >> >> [post] >> I'm almost halfway through an online tutorial I found on the python.org >> site and decided to stop and write a program for myself. I got it in my >> head to write a program to print all the primes; the idea came from >> another tutorial. The program prints some non-prime numbers. In a >> comparison to lists of primes the program prints eight non-primes for >> numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. >> Here is the program. >> >> base = 2 >> candidate = 3 >> >> while True: >> while candidate % base != 0: >> base = base + 1 >> if base > (candidate / 2): >> print candidate >> candidate = candidate + 1 >> base = 2 >> else: >> candidate = candidate + 1 >> >> The following is a rundown of the program. >> >> candidate: A possible prime number. >> base: Start point for divisibility testing. >> outer while loop: Causes the program to loop. >> inner while loop: Obviously, checks if 'candidate' mod 'base' equals >> zero. If not base is incremented by one then 'if loop'. >> if loop: After base has been incremented this checks whether all the >> possible divisors have been used up. If they have then 'candidate' must >> be prime. So, candidate is printed, a new candidate is chosen and the >> base is reset. >> else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is >> not prime and a new candidate is chosen. >> >> I realize yall probably didn't need all that. >> >> At first I tried to use 'return' on the 'else' block to cause the >> program to loop, but I don't understand 'return' yet and that didn't >> work. So, I put the rest into another while loop and was really happy to >> find it worked but the program prints some non-prime numbers. >> >> Thanks, Benjamin Serrato >> >> P.S. What is the chance I'll get spam for using my real email address? I >> currently don't get any so... >> [/post] > > Several items. > > First, you don't need to check base larger than sqrt(candidate). > > Second, see comments following dc. > > Third, you need to add base = 2 to end of program, otherwise next > candidate starts base where previous candidate left off. > > Fourth, use +=1 to increment. > > Finally, throw this away and use gmpy. :-) > > > import gmpy # for Quality Assurance > base = 2 > candidate = 3 > p = 0 # prime count > while p<100: # limit the loop to 100 primes > while candidate % base != 0: > base += 1 > #if base > (candidate / 2): > if base > (gmpy.sqrt(candidate)): # only need to test to > sqrt(candidate) > dc = divmod(candidate,2) # remainder==0 gives false > primes > if dc[1]==1: > # > # the gmpy functions are for QA, verifies that what you call a > prime > # really is one and the next_prime makes sure you don't skip > any > # these can be removed once working > # > print > candidate,gmpy.is_prime(candidate)>0,gmpy.next_prime(candidate) > p += 1 > candidate += 1 > base = 2 > else: > candidate += 1 # false prime, reset > base = 2 > else: > candidate += 1 > base = 2 # failure to reset causes false > primes > > ## 3 True 5 > ## 5 True 7 > ## 7 True 11 > ## 11 True 13 > ## 13 True 17 > ## 17 True 19 > ## 19 True 23 > ## 23 True 29 > ## 29 True 31 > ## 31 True 37 > ## 37 True 41 > ## 41 True 43 > ## 43 True 47 > ## 47 True 53 > ## 53 True 59 > ## 59 True 61 > ## 61 True 67 > ## 67 True 71 > ## 71 True 73 > ## 73 True 79 > ## 79 True 83 > ## 83 True 89 > ## 89 True 97 > ## 97 True 101 > ## 101 True 103 > ## 103 True 107 > ## 107 True 109 > ## 109 True 113 > ## 113 True 127 > ## 127 True 131 > ## 131 True 137 > ## 137 True 139 > ## 139 True 149 > ## 149 True 151 > ## 151 True 157 > ## 157 True 163 > ## 163 True 167 > ## 167 True 173 > ## 173 True 179 > ## 179 True 181 > ## 181 True 191 > ## 191 True 193 > ## 193 True 197 > ## 197 True 199 > ## 199 True 211 > ## 211 True 223 > ## 223 True 227 > ## 227 True 229 > ## 229 True 233 > ## 233 True 239 > ## 239 True 241 > ## 241 True 251 > ## 251 True 257 > ## 257 True 263 > ## 263 True 269 > ## 269 True 271 > ## 271 True 277 > ## 277 True 281 > ## 281 True 283 > ## 283 True 293 > ## 293 True 307 > ## 307 True 311 > ## 311 True 313 > ## 313 True 317 > ## 317 True 331 > ## 331 True 337 > ## 337 True 347 > ## 347 True 349 > ## 349 True 353 > ## 353 True 359 > ## 359 True 367 > ## 367 True 373 > ## 373 True 379 > ## 379 True 383 > ## 383 True 389 > ## 389 True 397 > ## 397 True 401 > ## 401 True 409 > ## 409 True 419 > ## 419 True 421 > ## 421 True 431 > ## 431 True 433 > ## 433 True 439 > ## 439 True 443 > ## 443 True 449 > ## 449 True 457 > ## 457 True 461 > ## 461 True 463 > ## 463 True 467 > ## 467 True 479 > ## 479 True 487 > ## 487 True 491 > ## 491 True 499 > ## 499 True 503 > ## 503 True 509 > ## 509 True 521 > ## 521 True 523 > ## 523 True 541 > ## 541 True 547 > ## 547 True 557 From gagsl-py2 at yahoo.com.ar Thu Mar 27 15:05:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 16:05:47 -0300 Subject: And the reverse? Does os also import os.path? References: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> <47ebd7b4$0$19836$426a74cc@news.free.fr> Message-ID: En Thu, 27 Mar 2008 14:22:11 -0300, Bruno Desthuilliers escribi?: > Wilbert Berendsen a ?crit : >> If i do >> >>>>> import os >>>>> os.path.abspath("bla") >> '/home/wilbert/bla' >> >> it seems that just import os also makes available al os.path functions. >> >> But is that always true? > > Nope. Not all packages expose their sub-packages. In this case, the idea is to provide an OS-dependent module with a generic name. The os module imports one of several modules (ntpath, posixpath, etc.) depending on the current platform, and makes it available under the generic "path" name so users don't have to worry about that. (Note that os is a module, not a package; os.path is accessing the "path" attribute of the os module, not the path module in the os package) -- Gabriel Genellina From grante at visi.com Sun Mar 2 10:25:49 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 15:25:49 -0000 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: <13slhntr9qdr62f@corp.supernews.com> On 2008-03-02, mentaltruckdriver at gmail.com wrote: > I posted here a couple days ago looking for some help creating > a Telnet-based chat server. You guys pointed me to Twisted, > which has solved most of my issues. And we told you that you needed to implement the telnet protocol. > The issue is, when I use clients like PuTTY, it returns a lot > of what appears to be formatting (e.g. if I typed Hello, it > would return "\xff \xfb\x1f\xff\ > xfb\xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) That "stuff" that you call "formatting" are commands for the telnet protocol. Apparently you've ignored what I told you about implementing the telnet protocol (or using something that does). > How would I go about filtering this stuff out of the strings? Once again: If you're trying to write a telnet server, you need to implement the telnet protocol. > The thing is too, if I use other Telnet programs like > Microsoft Telnet, they don't have this formatting, Different telnet clients act a little differently. Some won't try to negotiate with the tenlet server until the server starts the negotiation. > so I want to be able to recognize if it does have this > formatting and act based on if it does or if it doesn't. You have to handle the telnet protocol if you want to talk to telnet clients. -- Grant Edwards grante Yow! Yow! Those people at look exactly like Donnie visi.com and Marie Osmond!! From __peter__ at web.de Wed Mar 26 04:41:24 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Mar 2008 09:41:24 +0100 Subject: Strange loop behavior References: Message-ID: Gabriel Rossetti wrote: > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. d may be an empty string, but repr(d) isn't: >>> d = "" >>> print repr(d) '' >>> print d Remove the two repr() calls and you should be OK. Peter From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:31:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:31:15 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: <13t6ivj3ctet0ac@corp.supernews.com> On Sun, 09 Mar 2008 10:11:53 +1100, Alasdair wrote: > I need to apply the ceiling function to arbitrary sized (long) integers. > However, division automatically returns the type of its operands, so > that, for example: math.ceil(7/4) returns 1. I can use float, as in: > math.ceil(7/float(4)), except that for very large integers float causes > an unacceptable loss of precision. > > What is the best way of finding a ceiling of a quotient of arbitrary > sized integers? def quot_ceil(a, b): """Returns the integer ceiling of the quotient of longints.""" q, r = divmod(a, b) if r: return q+1 else: return q -- Steven From ds-python-list at sidorof.com Sat Mar 29 14:24:34 2008 From: ds-python-list at sidorof.com (DS) Date: Sat, 29 Mar 2008 11:24:34 -0700 Subject: Licensing Message-ID: <47EE8962.8070708@sidorof.com> I'm pretty sure this is the wrong place to ask, but I'm hoping someone will point me in the right direction. I'm getting ready to publish a first open-source project written in python. I am planning to use GPLas the license. However, in my code, there is a function that I like from Python Cookbook. I would like to use it, although I could certainly write a less elegant version that would do the same thing. So, my options appear to be: 1. Don't use it. 2. Use it with no comment -- that doesn't seem right. 3. Use it with remarks in the code that acknowledge the source. 4. Provide a separate licensing page for that function along with the GPL for my code. What is the appropriate course of action here? I'm thinking #3 is probably ok. How do others deal with this in an honorable way? In the book, it appears that they are saying they don't really care unless there is some massive use. Thanks From shrek3333 at wp.pl Fri Mar 21 09:32:18 2008 From: shrek3333 at wp.pl (shrek33333) Date: Fri, 21 Mar 2008 06:32:18 -0700 (PDT) Subject: Funny video :) Message-ID: <96de7676-1baa-43f2-bf07-560a88c61fe8@s13g2000prd.googlegroups.com> http://rozrywka.yeba.pl/show.php?id=1029 :) Funny Sports Bloopers :) From andrew.kuchling at gmail.com Tue Mar 18 11:09:22 2008 From: andrew.kuchling at gmail.com (amk) Date: Tue, 18 Mar 2008 08:09:22 -0700 (PDT) Subject: PyCon video editing References: Message-ID: <0ed1ce28-b517-4c17-b12e-7d6554f5274a@x41g2000hsb.googlegroups.com> On Mar 17, 10:00 pm, dundeemt wrote: > Anyone know who is in charge of this? I'd like to help out if I > could. I am, but haven't set anything up yet, such as a mailing list or a host for the video. I'll update the wiki page http://wiki.python.org/moin/PyConRecordingBof with news/further developments (you can create a wiki account and follow the envelope icon at the upper right to be notified of changes via e-mail). --amk From petr.jakes.tpc at gmail.com Fri Mar 7 16:05:41 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 7 Mar 2008 13:05:41 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Message-ID: Finaly, after few experiments, I am using pygame. It comunicates directly with the framebuffer and the performance is excellent. Thanks for your help. Petr Jakes From nanjundi at gmail.com Tue Mar 4 13:32:43 2008 From: nanjundi at gmail.com (Nanjundi) Date: Tue, 4 Mar 2008 10:32:43 -0800 (PST) Subject: sympy: what's wrong with this picture? References: Message-ID: On Mar 3, 3:40 pm, Mensanator wrote: > Notice anything funny about the "random" choices? > > import sympy > import time > import random > > f = [i for i in sympy.primerange(1000,10000)] > > for i in xrange(10): > f1 = random.choice(f) > print f1, > f2 = random.choice(f) > print f2, > C = f1*f2 > ff = None > ff = sympy.factorint(C) > print ff > > ## 7307 7243 [(7243, 1), (7307, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > > As in, "they're NOT random". > > The random number generator is broken by the sympy.factorint() > function. > > Random.choice() works ok if the factorint() function commented out. > > ## 6089 1811 None > ## 6449 1759 None > ## 9923 4639 None > ## 4013 4889 None > ## 4349 2029 None > ## 6703 8677 None > ## 1879 1867 None > ## 5153 5279 None > ## 2011 4937 None > ## 7253 5507 None > > This makes sympy worse than worthless, as it fucks up other modules. Does seeding ( random.seed ) random with time fix this? It should. -N From martin at v.loewis.de Mon Mar 10 02:57:20 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 10 Mar 2008 07:57:20 +0100 Subject: python-2.5.2 src rpm In-Reply-To: References: Message-ID: <47d4dbd0$0$12151$9b622d9e@news.freenet.de> > I am trying to install python 2.5.2 onto enterprise linux, and would > like to start with a source rpm package so that I can build the > package locally and make sure I have all necessary dependencies. > > I have been unable to locate a source rpm package for python 2.5.2 or > any version of 2.5 for that matter. > > Any pointers would be appreciated. I have not released any source RPM for Python 2.5.2. You can build your own, from Misc/RPM. Regards, Martin From michael.wieher at gmail.com Wed Mar 12 10:24:11 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 12 Mar 2008 09:24:11 -0500 Subject: List Combinations In-Reply-To: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: 2008/3/12, Gerdus van Zyl : > > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus > > -- list = [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] newList = [] for l in list: newList.extend(l) #newList = [3,9,1,5,4,2,5,8] list=[] for l in newList: if l not in list: list.append(l) #now list is [3,9,1,5,4,2,8] list.sort() #now your list is in sorted order Then, you can just write a series of for loops to spin off your data however you like. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 18:47:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 22:47:15 -0000 Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: <13u5qbjq707as9e@corp.supernews.com> On Thu, 20 Mar 2008 13:42:22 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: >>> By default Python on Windows allows you to open a file for reading >>> unless you specify a sharing mode which prevents it: >> >> But the OP is talking about another process having opened the file for >> WRITING, not reading. It's that other process that has exclusive >> access, and the OP was trying to determine when it was safe to attempt >> opening the file according to whether or not it was still growing. >> > No, unless the other process has specified that it wants exclusive > access there is nothing stopping his process also opening the file. > That's why he has to specify when he opens it that he wants exclusive > access: then it doesn't matter what the other process does, he won't be > able to open it until the other process has closed the file. I think you're confused. Or possibly I'm confused. Or both. It seems to me that you're assuming that the OP has opened the file for reading first, and *then* another process comes along and wants to open it for writing. That's not how I read his post: he's trying to open a file for reading while it is already being written to by another process. Asking for exclusive access when reading isn't going to make any difference, because the other process has already opened the file for writing. I suppose it is conceivable that the other process might have opened the file for non-exclusive writing, assuming that such a thing is even possible, but how likely is that? > This all of course assumes that the other process writes the file in one > single atomic chunk. If it were to create it and then separately open > and write to it then all bets are off. The OP is repeatedly polling the file to see when the size stops increasing. Obviously a single atomic write is *not* taking place. -- Steven From paddy3118 at googlemail.com Thu Mar 13 15:25:26 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 13 Mar 2008 12:25:26 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> Message-ID: <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> On Mar 13, 7:03 pm, Jonathan Gardner wrote: > On Mar 12, 6:37 pm, Carl Banks wrote: <> > > And leave out the magical -p and -n. If you want to iterate through a > file, "for line in sys.stdin:". Or better still: import fileinput for line in fileinput.input(): process(line) - Paddy. From Afro.Systems at gmail.com Fri Mar 28 05:05:49 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Fri, 28 Mar 2008 02:05:49 -0700 (PDT) Subject: chronic error with python on mac os/x 10.5 Message-ID: Although I am experiencing this problem using a specific domain library (pjsip). Googling this issue show that it is happening to many libraries in python on mac. I was wondering whether anyone solved this or alike in the past and might share what steps were taken. Note: this python lib works fine on other platforms (posix, win, and earlier versions of mac os x) >>> import py_pjsua Traceback (most recent call last): File "", line 1, in ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/site-packages/py_pjsua.so, 2): Symbol not found: ___CFConstantStringClassReference Referenced from: /Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/site-packages/py_pjsua.so Expected in: dynamic lookup From bjourne at gmail.com Thu Mar 13 11:06:48 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 13 Mar 2008 16:06:48 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: <000901c884dd$057d5d80$03000080@hendrik> References: <000901c884dd$057d5d80$03000080@hendrik> Message-ID: <740c3aec0803130806w2eed0c5eq2c0f0096557fce8@mail.gmail.com> On Thu, Mar 13, 2008 at 8:36 AM, Hendrik van Rooyen wrote: > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above 5 -- mvh Bj?rn From nkavitha551 at gmail.com Fri Mar 7 06:19:17 2008 From: nkavitha551 at gmail.com (nkavitha551 at gmail.com) Date: Fri, 7 Mar 2008 03:19:17 -0800 (PST) Subject: Your Fortune for the Day!!! Message-ID: <0bf81834-f0ed-4377-a3ea-d741778e8fb2@u10g2000prn.googlegroups.com> Your Fortune for the Day!!! Hi, To know what it is? Visit the website below and be cool !!! ------------------------------------------------------------------------------ http://myprofilekavitha.blogspot.com/ From skunkwerk at gmail.com Thu Mar 27 01:33:50 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Wed, 26 Mar 2008 22:33:50 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> <13ukphrj8hng018@corp.supernews.com> Message-ID: On Mar 26, 8:05?am, Jeffrey Froman wrote: > skunkwerk wrote: > > p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ > > model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > print p.communicate()[0] > > > i change to print p.communicate()[1] in case the output is blank the > > first time > > > this is the output: > > *.htm renamed as model.html > > Without shell=True, your glob characters will not be expanded. Hence, the > command looks for a file actually named "*.htm" > > > when I add shell=True to the subprocess command, I get the following > > output: > > Usage: rename [-v] [-n] [-f] perlexpr [filenames] > > Here the use of the shell may be confounding the arguments passed. Your > command will probably work better if you avoid using shell=True. However, > you will need to perform your own globbing: > > # Untested (no perl-rename here): > > command = ['rename','-vn', 's/(.*)\.htm$/model.html/'] > files = glob.glob('*.htm') > command.extend(files) > p = subprocess.Popen( > ? ? command, > ? ? stdout=subprocess.PIPE, > ? ? stderr=subprocess.PIPE, > ? ? ) > > Jeffrey thanks Jeffrey, that worked like a charm! From mm007.emko at gmail.com Sat Mar 29 07:13:10 2008 From: mm007.emko at gmail.com (eMko) Date: Sat, 29 Mar 2008 04:13:10 -0700 (PDT) Subject: deleting a line from a file Message-ID: Hello, In Perl, using a Tie::File module I can easily and comfortably delete a line from the middle of a text file: my @file; open(DATA, "+<:encoding(utf8):raw" , "file.txt") or return 0; tie @file, 'Tie::File', \*DATA or return 0; splice(@file, $_[0], 1); untie @file; close DATA; (when the first argument of the function ($_[0]) is a number of the line which should be deleted) Is there some easy way how to delete a line from a middle of a file in Python? Thanks a lot eMko From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 17:07:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 22:07:26 -0000 Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: <13t3f4u6vb77qf3@corp.supernews.com> On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... I hope that code doesn't contain any data coming from an untrusted user. > I want to be able to detect if they fail with error, That's what try...except blocks are for. try: x = eval('1 + 1 = 2') except SyntaxError: x = 3 > I want to be able to time them, That's what the timeit module is for. If you do time them, you will find that eval(expr) is MUCH MUCH slower than just executing expr as normal. >>> from timeit import Timer >>> Timer('1+1').timeit() 0.25557518005371094 >>> Timer('eval("1+1")').timeit() 21.816912174224854 If you use eval() a lot, you will have a SLOW program. > and I want to be able to stop them if they run too long. That's tricky. As far as I know, the only way for a Python program to stop an arbitrary calculation after a certain period of time it to run it in a thread. You then monitor the elapsed time, and when the timer expires, ask the thread to die. And hope it listens. > I cannot add code to the eval'd strings that will help me accomplish > this. You can't? Why ever not? Note: that's almost certainly the wrong way to solve your problem, but I'm curious as to why you can't. -- Steven From castironpi at gmail.com Sat Mar 15 20:29:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 17:29:10 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. Message-ID: 'join' in the wrong word for the method in class Thread. The agent-patient semantics of calling functions can get ambiguous. It is not a problem of native Pythoners alone. Is it due to lazy programming, an inability of English (do you have it in other languages?), or not a problem at all? th1.join() doesn't mean, 'do something to th1', or even, 'have th1 do something to itself.' In fact, if anything is doing anything differently, taking waiting to be doing something different, it's the caller. Translating literally, th1.join() -> join me here, th1. And, file1.close() -> close yourself, file1. But not, th1.join() -/> join yourself, th1. Worse, lock1.wait() -/> wait, lock1. (For what?) Furthermore, in toolbars: File -> Open -/> file an open. and: File -> Load -/> load a file. (It means, load the computer.) In English, the placements of identifiers isn't consistent. IOW, there isn't a syntactic mapping into natural language sentences. (Though you can do it in Latin, German, Sanskrit, and Russian with case markers*.) What are the true literals? What's doing what? th1.join() -> 'be joined by th1' file1.close()-> 'close file1' lock1.wait()-> 'getinlinefor lock1' And of course, 'open' isn't a method of File objects at all. The closest is, 'be loaded by file1'. Assuming speakers** of classical computer languages use OVS order-- object-verb-subject***, the most literal transformations are: th1.bejoinedby() file1.close() lock1.getinlinefor(). The mapping of identifiers to English isn't consistent. It takes some knowledge to read them-- shuffle an English sentence and it changes meaning. Functional languages are one long sentence: True.**** Declarative ones tell a story. ('th1' joins him.) Imperatives command an impartial audience. What do the docs say about it? ''' Thread.join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates - either normally or through an unhandled exception - or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened - if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception. ''' The natural language meaning of 'join' isn't used. Do benevolent dictators do this? What do malevolent ones call themselves? *Latin, German, Sanskrit, and Russian can do it. Latin, German, Sanskrit, and Russian -speakers- can do it. **It would be interesting to try to learn a language without ever speaking it. *** English is SVO, subject-verb-object. French is too, unless the object is direct: subject- direct-object -verb. **** The sum of the first three integers in the last two files, sorted alphabetically, in 'c:\programs'. From mmanns at gmx.net Fri Mar 21 16:02:01 2008 From: mmanns at gmx.net (Martin Manns) Date: Fri, 21 Mar 2008 21:02:01 +0100 Subject: How can I make a function equal to 0? References: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Message-ID: On 21 Mar 2008 12:52:12 -0700 Paul Rubin wrote: > def f(): return 0 Let us try it: Python 2.5.1 (r251:54863, Jan 26 2008, 01:34:00) [GCC 4.1.2 (Gentoo 4.1.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f(): return 0 ... >>> f==0 False >>> f()==0 True >>> I do not want the function to return 0 but to equal 0. Martin From craigm3604 at gmail.com Thu Mar 20 16:42:07 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 13:42:07 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> Message-ID: <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> On Mar 20, 2:38 pm, Craig wrote: > On Mar 20, 2:29 pm, sturlamolden wrote: > > > On 20 Mar, 19:09, Craig wrote: > > > The culprit i here: > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > This binds these names to Python ints, but byref expects C types. > > > Also observe that CacheSize and OpenMode should be c_short. > > I changed CacheSize and OpenMode to c_short, and commented out that > line producing the "Before" message, and the output is the same. > > Further "tinkering" revealed that it is the byref on the fName and pw > that are causing the error. > > The entire problem appears to be around the production of a BSTR and > the passing of pointers (byref) to the BSTR. Can anyone shed some light on how to work with BSTR's? From sturlamolden at yahoo.no Sat Mar 15 11:34:46 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 08:34:46 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: On 28 Feb, 02:24, Steven D'Aprano wrote: > Python doesn't do call by reference. Nor does it do call by value. Please > pay no attention to anyone who says it does. Exactly. Python pass variables the same way as Lisp, which is neither "call-by-value" (cf. C) nor "call-by-reference" (cf. Fortran). The Python equivalent of "pass by reference" is a function that returns its arguments to the caller: def foobar(arg1, arg2, arg3): # Mutate a shared object. # I.e. calling convention cannot be not "pass-by-value" arg1.whatever = 1 # Rebind in the local namespace. # I.e. calling convention cannot be "pass-by-value" arg1, arg2, arg3 = 1, 2, 3 # Return rebound variables to achieve the effect of # "pass-by-reference": return (arg1, arg2, arg3) # Call the function foobar, and rebind its arguments to its # return values: arg1, arg2, arg3 = foobar(arg1, arg2, arg3) From duncan.booth at invalid.invalid Sun Mar 16 08:51:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Mar 2008 12:51:41 GMT Subject: Regular Expression Help References: Message-ID: "santhosh kumar" wrote: > I have text like , > STRINGTABLE > BEGIN > ID_NEXT_PANE "Cambiar a la siguiente secci??n de laventana > \nSiguiente secci??n" > ID_PREV_PANE "Regresar a la secci??n anterior de > laventana\nSecci??n anterior" > END > STRINGTABLE > BEGIN > ID_VIEW_TOOLBAR "Mostrar u ocultar la barra de > herramientas\nMostrar/Ocultar la barra de herramientas" > ID_VIEW_STATUS_BAR "Mostrar u ocultar la barra de > estado\nMostrar/Ocultar la barra de estado" > END > ................................ > .................................... > .......................................... > and i need to parse from STRINGTABLE to END as a list object. whatkind of > regular expression should i write. > I doubt very much whether you want any regular expressions at all. I'd do something alone these lines: find a line=="STRINGTABLE" assert the next line=="BEGIN" then until we find a line=="END": idvalue = line.strip().split(None,1) assert len(idvalue)==2 result.append(idvalue) From duncan.booth at invalid.invalid Thu Mar 20 17:14:56 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Mar 2008 21:14:56 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: Sean DiZazzo wrote: > In this case, there will be so few people touching the system, that I > think I can get away with having the copy be done from Unix, but it > would be nice to have a general way of knowing this on Windows. > Doesn't the CreateFile call I posted earlier do what you want? From Lie.1296 at gmail.com Sun Mar 9 04:30:51 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 00:30:51 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: On Mar 9, 12:05 pm, Kay Schluehr wrote: > On 9 Mrz., 04:51, Lie wrote: > > > A more through implementation would start from the raiser inspecting > > the execution stack and finding whether there are any try block above > > it, if no try block exist it pass silently and if one exist it will > > check whether it have a matching except clause. This also circumvents > > a problem that simple implementation have, as described below. > > This will not be easy in particular in the presence of inheritance and > dynamism. There is no way to statically decide whether an exception > BException has the type AException and will be caught by the except > clause in > > try: > BLOCK > except AException, e: > print "SoftException %s caught"%e > A feasible solution was to invert the try...except statement and > creating a continuation. > > catch AException, a: > print "SoftException A: %s"%a > catch BException , b: > print "SoftException B: %s"%b > ... > in: > BLOCK > > Here each SoftException is raised initially when a catch clause is > entered and a continuation is created that returns to the catch block > of the raised SoftException if required. When a SoftException is > raised within BLOCK a lookup will be made and if a corresponding > SoftException was found that was raised by a catch-clause the current > control flow will be suspended and the continuation is called. I'd rather want to avoid any syntax changes, as I wished that Soft Exception can be added to the language silently[1] so that new programmers doesn't _need_ to know about it (although knowing it could change the way they write codes to be more structured and simple). [1] Definition of silently: Codes that aren't aware of this functionality shouldn't break. Adding new syntax usually means adding keywords, making possible break in current program. On Mar 9, 12:30?pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 19:51:24 -0800, Lie wrote: > > Soft Exception > > What is "Soft Exception"? > > Soft Exception is an exception that if is unhandled, pass silently as if > > nothing happened. For example, if a variable turns into NoneType, it'll > > raise Soft Exception that it have become NoneException, programmers that > > wants to handle it can handle it with a try...except block while > > programmers that doesn't care about it (or know it won't be a problem to > > his code) can just leave the code as it is. > > > Soft Exception differs from Hard Exceptions (the regular Exception) in a > > way that Hard Exception must be handled at all cost or the program will > > be terminated while Soft Exception allow programmers not to handle it if > > they don't want to. > > I don't think that there are very many cases where exceptions can be > ignored safely. There are two main reasons for using exceptions: > > (1) Signaling an exceptional event. In that case, programmers might decide whether to raise Soft or Hard Exception. Hard Exception is much preferred. > (2) An error occurred. Which must always be handled with Hard Exception. Adding another thing (3) Informing codes above it about what's currently happening inside, the thing is just a mundane report that might be useful to codes above Which might be a useful place to use SoftExceptions > I can't think of many cases where you would wish to ignore either, and > just continue processing. The only examples I can think of are in loops, > where you are doing the same thing over and over again with just a little > change, and you wish to skip any problematic data, e.g.: > > def plot_graph(func, domain): > ? ? for x in domain: > ? ? ? ? plot(x, func(x)) > > If an error occurs in plot() for one particular x value, you would want > to ignore it and go on to the next point. But that's easy enough to do > with a regular try...except block. No, you're misunderstanding the purpose of Soft Exception, it's not for silencing errors and not so much for exceptional cases. It's for the more mundane tasks such as: from __future__ import division class SomeNumeric(object): def __div__(a, b): if b == 0: raise ZeroDivisionError ## Hard Exception, don't ignore me! if a == 0: raise ZeroNumerator ## Soft Exception f = a / b i = a // b if f == float(i): raise IntegerDivision ## Soft Exception return a // b else: raise FloatDivision ## Soft Exception return a / b Most people can ignore the ZeroNumerator, IntegerDivision, and FloatDivision exceptions (warnings) because they're excessive and unnecessary, but some people might want to catch them and do something else (especially ZeroNumerator). Practicle example, far below. The example is actually quite bad at demonstrating the purpose of Soft Exception as it is very simple while Soft Exception is generally more useful in complex operations. But I want to avoid giving complex examples since it'll be more difficult to explain the complex examples instead of the simple examples. > Simply put, you're suggesting the following two alternatives: > > Hard Exceptions: terminate the program unless explicitly silenced > Soft Exceptions: pass silently unless explicitly caught > > In this case, I agree with the Zen of Python ("import this"): > > Errors should never pass silently. > Unless explicitly silenced. That's what sloppy programmers do, silently pass errors. OTOH, Soft exceptions are not used for errors (perhaps the wording can be better phrased: must not be used for errors), they're used for events that some might have interest in, but some would consider it as normal. That's why I mentioned to think of it as a Warning. Operations that raise Soft Exceptions should be able to run normally even when the exception isn't handled (although it might generate garbage out that can be handled at later time). > The cost of explicitly silencing exceptions is tiny, the risk of misuse > of Soft Exceptions is very high, and the benefit of them is negligible. Perhaps relabeling it as Warning, and renaming raise SoftException as give Warning might make it more acceptable? And I agree that the probability for misuse is quite high, but the benefits is also quite high, it's just that you can't see it since you're not used to using such exceptions. The benefit of SoftExceptions lies mostly on the regular programmings tasks, not the exceptional programming tasks Practical Example: This example takes _case ideas_ from this simple gravity simulator http://www.pygame.org/project/617/ BUT _no line of code is taken from it_. I only give this link so you can easily know what the case is about without lengthy explanation. A particle machine. The particle machine calculates gravity created by the particles in a field. Additionaly, it clumps together two particles that happens to be near enough (less than the sum of their radiuses). The force two particle is expressing to each other is calculated with: def calculateforce(P1, P2): return (P1.mass - P2.mass) / distance(P1, P2) and this is done to every particle in the field against the current particle. And the distance is calculated by: def distance(P1, P2) return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 The problem happens when the distance is small enough and we want to clump them together. A possible solution to this problem might be to check whether distance is less than P1.radius + P2.radius in the calculateforce. But, this obfuscate the code since we have to separate distance calculation from the main formula (see !s), and this also insist that clumping be done on force calculation level (see @s), shortly this piece of code is plain bad: def distance(P1, P2): return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 def calculateforce(P1, P2): ## Separating this dist calculation into its own line is ## necessary if we want to check the value of dist ## Personally I think that's a bit obfuscated. ## Well known formulas should be kept to one line if possible ! dist = distance(P1, P2) if dist <= P1.radius + P2.radius: ## Calling clump() here is bad, because ## there are occasions where we only want to ## calculate force but doesn't want to ## clump it @ clump(P1, P2) else: ! return (P1.mass - P2.mass) / dist ## Codes calling calculateforce() # Note: this code is located inside a loop F = calculateforce(P1, P2) # Do something else, acceleration calculation, movement calculations, etc A better refactoring would be like this, but this requires calculating distance twice (see !s): def distance(P1, P2): return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 def calculateforce(P1, P2): ## Here distance is calculated once ! return (P1.mass - P2.mass) / distance(P1, P2) ## Codes calling calculateforce() # Note: this code is located inside a loop ## Here distance is calculated again ! if distance(P1, P2) <= P1.radius + P2.radius: clump(P1, P2) break F = calculateforce(P1, P2) # Do something else, acceleration calculation, movement calculations, etc A much better solution would be to use SoftException def distance(P1, P2): D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 if D <= P1.radius + P2.radius: raise Collision return D def calculateforce(P1, P2): try: F = (P1.mass - P2.mass) / distance(P1, P2) except Collision: raise ## Codes calling calculateforce() # Note: this code is located inside a loop try: F = calculateforce(P1, P2) except Collision: clump(P1, P2) break # Calculate the next particle pair else: # Do something else, acceleration calculation, # speed calculation, movement calculations, etc This results in a cleaner code. And it also allow _other part of codes_ that uses calculate distance and force to easily ignore or handle the Collision Exception. If this code had used Hard Exception, other codes would have to explicitly silence the exception or the program terminates. That would be too much since Collision is technically not an Error, but just a normal events that you might be interested to know. Soft Exception allows events of interest to be noticed or be ignored depending on the requirement. It's like a notice board: In the notice board, there are notices about the Maths Test next week, which you must not ignore (Hard Exception), but there are also notices about Part-time Job Advertisement, if you're interested about it you can look at it further, else you could just ignore it and do nothing (Soft Exception) From carsten at uniqsys.com Sun Mar 23 21:02:31 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 02:02:31 +0100 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: <1206320551.3365.20.camel@localhost.localdomain> On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > That's really weird... it's reproducible on Windows too. It doesn't > make any sense why the name of the variable would make a difference. > My guess is you hit some kind of obscure bug. This is not a bug, just an unexpected feature: http://mail.python.org/pipermail/python-list/2005-January/304873.html What's happening is that at the end of the script, all objects in the global namespace are set to None (in order to decrease their reference count and trigger garbage collection). This happens in the order in which the names appear as keys in the globals dictionary. It randomly happens that "swaroop", "kalam", and "cath" all are hashed in front of "Person", but "cathy" is hashed after "Person". Hence, if Catherine is named cath, Python "None's" all the instances first and then the type last, and all is well. However, if Catherine is called cathy, Person is set to None before cathy. Then, in the lookup of the global name "Person" during cathy.__del__, Person is None, which doesn't have a "population" attribute, causing the AttributeError. Possible workarounds are: 1) Explicitly delete the global names for the instances before the script runs out. 2) Don't refer to the "Person" type by its global name in __del__, but indirectly as type(self). (This requires Person to be a new-style class, though.) -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Sat Mar 29 20:00:43 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 21:00:43 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: En Sat, 29 Mar 2008 16:24:01 -0300, Michael Wieher escribi?: > to me it seems simple. > > C uses != > > why does C use != .... because its kind of hard to type the "equal with a > slash" In C, ! by itself is the logical "not", so !(a==b) is the same as (a!=b) and that's rather consistent. Python doesn't use ! for anything else; != is rather arbitrary but certainly much better than <> (for many objects < and > are meaningless; being equal or not equal has nothing to do with being less or greater) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:47:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:47:34 -0300 Subject: Issues with Python + Batch File References: Message-ID: En Tue, 25 Mar 2008 08:55:12 -0300, tarun escribi?: > I've a batch file which invoks a python file. The python code in the file > brings up a GUI. The GUI is of a test tool which can execute scripts. > > I tried using the following 2 sample of code for my batch file: > > * (1) (2)* > D:\opengui.py D:\opengui.py > goto:end goto:end > :end :end > EXIT TASKKILL /IM C:\WINDOWS\system32\cmd.exe > > Double clicking on the batch file brings up a DOS BOX which opens up the > GUI. On Closing the GUI, the DOS BOX both get closed. But if I close the > GUI > when a test is under execution, the GUI gets closed but the DOS BOX still > remains open. > > I want to some how close the DOS BOX when the GUI is closed. Either rename the script "opengui.pyw" or start it explicitely using: pythonw d:\opengui.py pythonw.exe doesn't create a console (what you call a "DOS BOX"). -- Gabriel Genellina From duncan.booth at invalid.invalid Mon Mar 10 08:14:47 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2008 12:14:47 GMT Subject: Problem with zipfile and newlines References: Message-ID: "Neil Crighton" wrote: > I'm using the zipfile library to read a zip file in Windows, and it > seems to be adding too many newlines to extracted files. I've found > that for extracted text-encoded files, removing all instances of '\r' > in the extracted file seems to fix the problem, but I can't find an > easy solution for binary files. > > The code I'm using is something like: > > from zipfile import Zipfile > z = Zipfile(open('zippedfile.zip')) > extractedfile = z.read('filename_in_zippedfile') > > I'm using Python version 2.5. Has anyone else had this problem > before, or know how to fix it? > > Thanks, > Zip files aren't text. Try opening the zipfile file in binary mode: open('zippedfile.zip', 'rb') From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 22:14:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 02:14:43 -0000 Subject: Help me on function definition References: Message-ID: <13ur9gjqggrf528@corp.supernews.com> On Sat, 29 Mar 2008 01:47:21 +0000, aeneng wrote: > Hello everyone, > > I am just starting to use python in numerical cacluation. I need you to > help me to see what's wrong with the following piece of codes, which > computes the cross product of two vectors and returns the result. u and > v are two 3x1 matrix. > > when I import the function, error message show like this >>>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? You don't win any points by writing the most unreadable code can you. A little bit of white space makes the code so much easier to read: ppp2 = u[2]*v[0] - u[0]*v[2] But that's not the problem. Your code mixes spaces and tabs for indentation. Spaces are good; tabs are good; both together will eventually lead to disaster. But that's not your problem either. Your REAL problem is that the error you are reporting is NOT the error your code gives. Hint: if your code raises an error, you must copy the code that actually raises an error, not different code with different errors. The code you post reports this error: >>> import cross Traceback (most recent call last): File "", line 1, in File "cross.py", line 1 def cross(u,v) ^ SyntaxError: invalid syntax After fixing that fault (put a colon after the function definition), your code imports correctly. My *guess* is that in your actual code that fails, you have forgotten to close a bracket or brace in line 7 (not 8). -- Steven From rcdailey at gmail.com Wed Mar 5 18:01:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 5 Mar 2008 17:01:19 -0600 Subject: system32 directory Message-ID: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> Hi, Is there a way to get the System32 directory from windows through python? For example, in C++ you do this by calling GetSystemDirectory(). Is there an equivalent Python function for obtaining windows installation dependent paths? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Mon Mar 10 20:46:02 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 10 Mar 2008 19:46:02 -0500 Subject: image matching algorithms In-Reply-To: References: Message-ID: <47D5D64A.8030300@ncee.net> Daniel Fetchinson wrote: >>> There are a number of free tools for image matching but it's not very >>> easy to decipher the actual algorithm from the code that includes db >>> management, GUI, etc, etc. I have my own image database and GUI so all >>> I need is the actual algorithm preferably in pseudo code and not in >>> the form of a research paper (from which I also found a lot but since >>> I'm not that much interested in the actual science of image >>> recognition this seems like an over kill). >>> >> I'd recommend SIFT. There's quite a bit of information on SIFT. In most >> cases, they don't cover the background science too much, but are still >> heavy on the math. Pseudo code is hard to come by since it will take >> many lines of pseudo code just to express one concise mathematical >> equation. There are however many links to implementations in various >> languages on the Wikipedia page. >> >> http://en.wikipedia.org/wiki/Scale-invariant_feature_transform >> >> I have had good experiences with SIFT for feature extraction from images >> (I have used it for panorama stitching and robot mapping). It's >> insensitive to scale and rotation. Note that it is a patented algorithm >> and this may (or may not) pose a problem for you. >> > > Thanks for the info! SIFT really looks like a heavy weight solution, > but do you think the whole concept can be simplified if all I needed > was: given a photo, find similar ones? I mean SIFT first detects > objects on the image and find similarities, but I don't need the > detection part at all, all I care about is similarity for the whole > photo. I surely don't understand the big picture fully but just have > the general feeling that SIFT and other expert tools are an overkill > for me and a simplified version would be just as good with a much more > easily comprehensible core algorithm. > > Or am I being too optimistic and there is no way out of going into the details? > Using the histogram of the picture may be good enough for your application. Here's something I put together for comparing images (for purposes of detecting motion) taken by the built-in web cam in my Macbook Pro. This might be good enough if you play with the threshold. """ I'm writing a simple little app for doing motion detection with data output from wacaw, a package for MacOSX. You could easily modify this script to get data output from some other source. cd /Applications ; for i in `jot 1024`; do /Applications/wacaw --png picture-${i} && sleep 3 ; done; open *.png cd /Applications; open picture-* """ # cd /Applications ; for i in `jot 1024`; do /Applications/wacaw --png picture-${i} && sleep 3 ; done; open *.png # SOURCE: http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/ import os from time import sleep import tempfile import Image # Sun Mar 18 16:40:51 CDT 2007 def diff_image(img1, img2, pix_threshold=50, img_threshold=4): """Compare 2 images to detect possible motion You might want to choose the img_threshold amount based on the conditions. """ img1 = Image.open(img1) img2 = Image.open(img2) if not img1 or not img2: return False img1 = img1.getdata() img2 = img2.getdata() pixel_count = len(img1) pixdiff = 0 for i in range(pixel_count): #if abs(sum(img1[i]) - sum(img2[i])) > pix_threshold: diffval = abs(sum(img1[i]) - sum(img2[i])) #print "Pixel diffval:",diffval if diffval > pix_threshold: pixdiff += 1 diffperc = pixdiff / (pixel_count/100.0) print "Photo diff percentage:",diffperc if diffperc > img_threshold: # motion detected return True else: return False photos = [] # consider automatically serializing this data import commands """ def analyze_thresholds(list_of_photos): last = list_of_photos[0] for photo in list_of_photos[1:]: diff_image(last, photo) last = photo """ def detect(): number = 0 while True: number += 1 sleep(3) current = 'photo-'+str(number) #tmp = tempfile.mktemp() print commands.getoutput('/Applications/wacaw --png ' + current ) # ' + tmp +'.png') # Here's the actual name of the file wacaw created: current = '/Applications/'+current+'.png' photos.append( current ) if len(photos) < 2: # pad the list for the first time photos.append( current ) if diff_image(photos[-1],photos[-2], pix_threshold=50, img_threshold=5): print "motion detected" else: print "motion NOT detected" detect() #import glob #analyze_thresholds(glob.glob('/Applications/photo-*') -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From watine at cines.fr Tue Mar 25 07:00:20 2008 From: watine at cines.fr (Benjamin Watine) Date: Tue, 25 Mar 2008 12:00:20 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: <47E8DB44.6040508@cines.fr> Bryan Olson a ?crit : > Benjamin Watine wrote: >> bryanjugglercryptographer at yahoo.com a ?crit : >>> I wrote: >>>> And here's a thread example, based on Benjamin's code: >>> [...] >>> >>> Doh! Race condition. Make that: >>> >>> import subprocess >>> import thread >>> import Queue >>> >>> def readtoq(pipe, q): >>> q.put(pipe.read()) >>> >>> cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, >>> stdout=subprocess.PIPE) >>> >>> myVar = str(range(1000000)) # arbitrary test data. >>> >>> q = Queue.Queue() >>> thread.start_new_thread(readtoq, (cat.stdout, q)) >>> cat.stdin.write(myVar) >>> cat.stdin.close() >>> cat.wait() >>> myNewVar = q.get() >>> >>> assert myNewVar == myVar >>> print len(myNewVar), "bytes piped around." > >> Great, it works, thank you Bryan ! >> >> Could you explain me why you use a queue instead of a simple array for >> getting the piped var ? > > The call to q.get() will block until an item is in the queue. > At that point in the program, we had already waited for cat to > terminate: > > cat.wait() > myNewVar = q.get() > > But passing cat.wait() does not imply that our own thread has > already read all of cat's output and put it in some destination > object. Data could still be in transit. > > My first version, subsequently titled, "Doh! Race condition," > worked in all of several runs of its built-in test. Doesn't > make it right. > OK, so if I understand well what you said, using queue allow to be sure that the data is passed in totality before coninuing with next instruction. That make sense. Using thread and queue seems to be very more slow than using files redirection with bash. I'll see if it make a great load average and/or I/O time. Thanks again for your help Bryan. Ben From castironpi at gmail.com Tue Mar 4 13:16:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:16:32 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> <75d14972-4dba-4311-9c06-63b3a2859f96@n75g2000hsh.googlegroups.com> Message-ID: On Mar 4, 12:51?am, Gerard Flanagan wrote: > On Mar 4, 6:31 am, castiro... at gmail.com wrote: > > > > > > > On Mar 3, 10:01 pm, Benjamin wrote: > > > > On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > > > > > What are metaclasses? > > > > Depends on whether you want to be confused or not. If you do, look at > > > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/. > > > > Basically, the metaclass of a (new-style) class is responsible for > > > creating the class. This means when Python sees > > > class Foo(object): > > > ? ? __metaclass__ = FooMeta > > > class FooMeta(type): > > > ? ? def __new__(cls, name, bases, dct): > > > ? ? ? ?#do something cool to the class > > > ? ? ? ?pass > > > It asks FooMeta to create the class Foo. Metaclasses always extend > > > type because type is the default metaclass. > > > But you can stack class decorations, but not class metas. > > > @somethingcool1 > > @somethingcool2 > > class Foo: > > ? ?pass > > > * class Foo: > > ? ?__metaclass__= MetaCool1, MetaCool > > > * denotes malformed > > ----------------------- > class Meta1(type): > > ? ? def foo1(cls): > ? ? ? ? print 'hello' > > class Meta2(type): > > ? ? def foo2(cls): > ? ? ? ? print 'castiron' > > class Meta(Meta1, Meta2): > ? ? pass > > class Base(object): > ? ? __metaclass__ = Meta > > Base.foo1() > Base.foo2() class Base(object): __metaclass__= type( 'Meta', ( Meta1, Meta2 ), {} ) From grante at visi.com Mon Mar 3 16:25:19 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Mar 2008 21:25:19 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> Message-ID: <13sor5vjk06i71a@corp.supernews.com> On 2008-03-03, blaine wrote: > As far as PySerial goes - were trying to stick to built-in > modules since cross compiling to an arm processor is being a > little bit of a pain for us. pyserial is pure python, so I don't see how it's going to be any more painful than something you write yourself. If you want something that's more of a transparent object wrapper aroudn the Posix serial interface, there's PosixSerial.py (upon which pyserial's posix support is based): ftp://ftp.visi.com/users/grante/python/PosixSerial.py -- Grant Edwards grante Yow! Everybody gets free at BORSCHT! visi.com From michael.wieher at gmail.com Mon Mar 17 10:55:41 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 09:55:41 -0500 Subject: Apache binary error? Message-ID: have simple webpage running apache, mod_python the error is binary.... ...binary as in "every other" time I load the page, Firefox keeps telling me I'm downloading a python script, and asks to open it in WINE, which is really strange. then, alternately, it loads the page just fine. any clues as to why this is happening? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Mar 11 07:44:45 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 Mar 2008 12:44:45 +0100 Subject: Python PDF + Pictures In-Reply-To: References: Message-ID: <47D670AD.6050302@behnel.de> durumdara at gmail.com wrote: > I have many photos, and I wanna make some "presentation" from these > photos, a "thumbnail" like document with one image per one page. > > If I wanna make one document now I do this: > I execute a python script that create a html site with resized pictures, > and split this html site to 50 images per one html file. > Next I open these files in OpenOffice Writer by hand, and save them as > PDF document with poor quality (image compression 95%, image DPI 75). > This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that > can opened everywhere (because of PDF format). > > But I wanna automatize this process with python. > The technic that I will use is this: > 1.) Collect the files in dirs. > 2.) I process one dir in one time. > 3.) I get the files. > 4.) I resize them to max. 1024/768. > 5.) I put the actual image file to the PDF document. > 6.) After each 50. file I open new numbered PDF. > 7.) Every picture placed in one page, and every page orientation set up > as the picture orientation (Portrait or Landscape). > > The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. PIL can write PDFs, and it's clearly a good choice for image processing. http://www.pythonware.com/products/pil/ Stefan From castironpi at gmail.com Fri Mar 28 06:09:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:09:02 -0700 (PDT) Subject: pygame handoff Message-ID: Can anyone do a simple pygame render of a rollercoaster in first- person? I'll do the generator. Just for fun for free. (Ha see pythaaaaaagh. He bothered to carve it. Have a nice day.) From tjreedy at udel.edu Sun Mar 2 16:21:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 16:21:06 -0500 Subject: Altering imported modules References: <200803011856.27611.troworld@gmail.com> Message-ID: "Tro" wrote in message news:200803011856.27611.troworld at gmail.com... | Hi, list. | | I've got a simple asyncore-based server. However, I've modified the asyncore | module to allow me to watch functions as well as sockets. The modified | asyncore module is in a specific location in my project and is imported as | usual from my classes. | | Now I'd like to use the tlslite library, which includes an asyncore mixin | class. However, tlslite imports "asyncore", which doesn't include my own | modifications. | | I'd like to know if it's possible to make tlslite load *my* asyncore module | without changing any of the tlslite code. If your module is also 'asyncore' and comes earlier in the search path, I would expect the import to get yours. From gnewsg at gmail.com Thu Mar 20 07:51:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 20 Mar 2008 04:51:28 -0700 (PDT) Subject: Change user on UNIX Message-ID: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Hi all. Is there any way to su or login as a different user within a python script? I mainly need to temporarily impersonate another user to execute a command and then come back to the original user. I tried to google a little bit about it but I still didn't find a solution. Thanks in advance. --- Giampaolo http://code.google.com/p/pyftpdlib From z80vsvic20 at hotmail.com Mon Mar 10 17:04:09 2008 From: z80vsvic20 at hotmail.com (Eric von Horst) Date: Mon, 10 Mar 2008 14:04:09 -0700 (PDT) Subject: wxPython: some help with Drag&Drop Message-ID: Hi, I need some advice on Drag&Drop. What I want to achieve is the following: - I have a window that is divided in two : on the left hand I have a wx.TreeCtlr and on the other hand a wx.StaticBitmap I want to be able to drag an item from the tree onto the static bitmap. I know how to do drag&drop in a treeCtrl but is there a way that I can make the bitmap detect that something has been dropped on it? I would only need to know the name of the tree obj that was dropped on the bitmap (and the location) Any help much appreciated Erik From gabriel.rossetti at mydeskfriend.com Tue Mar 18 04:06:27 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 18 Mar 2008 09:06:27 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom Message-ID: <47DF7803.1070902@mydeskfriend.com> Hello, I am reading core python python programming and it talks about using the idiom described on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . I'm using python 2.5.1 and if I try : class MyClass(object): def __init__(self): self._foo = "foo" self._bar = "bar" @property def foo(): doc = "property foo's doc string" def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() # credit: David Niergarth @property def bar(): doc = "bar is readonly" def fget(self): return self._bar return locals() like suggested in the book (the decorator usage) I get this : >>> a=MyClass() >>> a.foo Traceback (most recent call last): File "", line 1, in TypeError: foo() takes no arguments (1 given) but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : >>> a = MyClass() >>> a.foo 'foo' does anyone have an idea as of why this is happening? Thanks, Gabriel From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:56:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:56:34 -0300 Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> <37d6b141-5ba0-4178-b45a-512e59433803@s12g2000prg.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 13:22:06 -0300, Clodoaldo escribi?: > On Mar 28, 12:09 pm, "Gabriel Genellina" wrote: >> En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo >> escribi?: >> >> > What i need to know is where can an equal char appear in a >> > urlsafe_b64encoded string?: >> >> > a)only at end; >> > b)both at the end and at the begginig; >> > c)anywhere in the string; >> >> > A sure answer will make my regexp safer. >> >> Only at the end. The encoded string has 4*n chars when the input string >> has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has >> 4*(n+1) chars right padded with 2 or 1 "=" chars. >> If your input has 3n chars, the output won't have any "=" > > Thanks. But I'm not sure i get it. What is n? (Any nonnegative integer...) I mean: For base64 encoding, the length of the output depends solely of the length of the input. If the input string length is a multiple of 3, the output length is a multiple of 4, with no "=". If the input length is one more than a multiple of 3, the output has two "==" at the end. If the input length is two more than a multiple of 3, the output has only one "=" at the end. In all cases, the output length is a multiple of 4. [base64 uses 64=2**6 characters so it encodes 6 bits per character; to encode 3 bytes=3*8=24 bits one requires 24/6=4 characters] > A md5 digest will always be 16 bytes length. So if i understand it > correctly (not sure) the output will always be 22 chars plus two > trailing equal chars. Right? Exactly. -- Gabriel Genellina From driedel at printingforsystems.com Thu Mar 13 08:53:05 2008 From: driedel at printingforsystems.com (David P. Riedel) Date: Thu, 13 Mar 2008 08:53:05 -0400 Subject: problem with Python 2.5.2 and gcc 4.3 In-Reply-To: References: <7jRBj.20981$QC.15171@newsfe20.lga> Message-ID: Andrew MacIntyre wrote: > David P. Riedel wrote: > >> I tried building Python 2.5.2 using gcc 4.3.0. The build completes >> with no problems but when I run 'make test', I get a segfault part >> way through the test run. >> >> here is the last part of the output from make test >> >> test_softspace >> test_sort >> test_sqlite >> test_sqlite skipped -- no sqlite available >> test_startfile >> test_startfile skipped -- cannot import name startfile >> test_str >> make: *** [test] Segmentation fault > > You don't identify the platform or O/S, though I'd guess some Linux > distro on i386 or x86-64... > > If you have gdb available, a backtrace might give a clue. > > However, as this is a new major release of gcc I'm automatically going to > assume an optimisation issue. To test this I'd suggest doctoring the > makefile generated by configure to reduce the optimisation level - I'd > suggest trying -O instead of -O3. If that works, try -O2 or -Os. > > If -O2 or -Os works, I'd be taking the matter up with the gcc team. > You are correct -- Mandriva Linux 2007. I will try varying the optimization level and see what happens. Thanks From upton at virginia.edu Sun Mar 9 17:41:17 2008 From: upton at virginia.edu (Dan Upton) Date: Sun, 9 Mar 2008 17:41:17 -0400 Subject: execute In-Reply-To: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: <5504f9ac0803091441s31f8587ekbc3088e53fbb819e@mail.gmail.com> On Sun, Mar 9, 2008 at 5:22 PM, Gif wrote: > i'm trying to execute a file without replacing the current process, > but after searching the help file, documentations and the web, i can't > a way of doing that. > > os.exec*() will close the current program. > > ps: by executing i mean like typing "mspaint" in run dialog.. it's not > a python file On *nix, you can use os.fork(). According to http://effbot.org/librarybook/os.htm , you can use os.spawn to accomplish a similar effect on Windows, although I haven't used it. Also, you might check the subprocess module -- http://docs.python.org/lib/module-subprocess.html . -dan From cokofreedom at gmail.com Thu Mar 13 05:14:53 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 13 Mar 2008 02:14:53 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <42fb57ae-f3b8-44bd-b9b3-6df34e443125@n36g2000hse.googlegroups.com> On Mar 13, 8:36 am, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above > > I undertake to summarise answers posted to complete this "survey". > > - Hendrik None is the likely answer as .append is an inplace change and will return None... From dewitters at gmail.com Sun Mar 30 04:08:34 2008 From: dewitters at gmail.com (dewitters at gmail.com) Date: Sun, 30 Mar 2008 01:08:34 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> Message-ID: <5f067c48-e6d4-405b-a064-70b26f8b0343@m71g2000hse.googlegroups.com> On Mar 29, 12:41 pm, Steven D'Aprano wrote: > Given that <= is a comparison operator, not an assignment, why do you > jump to the conclusion that != is an assignment? Why don't you argue that > "x <= y" means "assign the value of x Since you jump to an invalid conclusion about !=, the rest of your > argument fails. No, you said <= could be confusing, but we're talking about <> here, and there is no confusion about that :). From sturlamolden at yahoo.no Sun Mar 16 22:35:22 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 19:35:22 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> Message-ID: <0369b78b-6681-4807-b944-fb371cdd1522@59g2000hsb.googlegroups.com> On 15 Mar, 21:54, Unknown wrote: > I was expecting to replace the old value (serial) with the new one > (todayVal). Instead, this code *adds* another line below the one found... > > How can I just replace it? A file is a stream of bytes, not a list of lines. You can't just replace a line with another, unless they have the exact same length. You must rewrite the whole file to get it right. From fminervino at gmail.com Fri Mar 14 09:25:28 2008 From: fminervino at gmail.com (fminervino at gmail.com) Date: Fri, 14 Mar 2008 06:25:28 -0700 (PDT) Subject: find string in file Message-ID: Hi friends !! I'm neophite about python, my target is to create a programa that find a specific string in text file. How can do it? Thanks fel From rokkamraja at gmail.com Fri Mar 7 03:21:36 2008 From: rokkamraja at gmail.com (Raja) Date: Fri, 7 Mar 2008 00:21:36 -0800 (PST) Subject: Python GDB Wrapper References: <47d0f228$0$17725$9b622d9e@news.freenet.de> Message-ID: Hi All, Thanks for replies. Daniel- I am looking at just a wrapper around GDB. I dont want to emulate the functionalities of GDB but instead use them in python scripting. Martin - Misc/gdbinit looks promising. Thanks a lot. Thanks, Raja. On Mar 7, 12:43 pm, "Martin v. L?wis" wrote: > > Has anyone does this before ? Even some basic idea or code as to how > > to proceed would be great. > > Have you seen Misc/gdbinit? > > Regards, > Martin From http Wed Mar 19 02:47:27 2008 From: http (Paul Rubin) Date: 18 Mar 2008 23:47:27 -0700 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: <7xk5jz1a80.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > ftping it as a flat file, and untarring it on the other side. Of > course, the motivation wasn't just to get the files from point A to > point B using Unix (which I already know how to do), but to take > advantage of an opportunity to learn some Python; next time, I'll try > the ftpmirror.py script if it's generic enough, or ftplib if there are > more specific requirements. I see, that wasn't clear in your original post. You should look at the os.walk function if you want to know how to traverse a directory tree (maybe you are already doing this). Also, for security reasons, it's getting somewhat uncommon, and is generally not a good idea to run an ftpd these days, even on a LAN. It's more usual these days to transfer all files by rcp or rsync tunnelled through ssh. From steven.klass at gmail.com Sat Mar 22 17:11:16 2008 From: steven.klass at gmail.com (rh0dium) Date: Sat, 22 Mar 2008 14:11:16 -0700 (PDT) Subject: Pyparsing help Message-ID: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Hi all, I am struggling with parsing the following data: test1 = """ Technology { name = "gtc" dielectric = 2.75e-05 unitTimeName = "ns" timePrecision = 1000 unitLengthName = "micron" lengthPrecision = 1000 gridResolution = 5 unitVoltageName = "v" voltagePrecision = 1000000 unitCurrentName = "ma" currentPrecision = 1000 unitPowerName = "pw" powerPrecision = 1000 unitResistanceName = "kohm" resistancePrecision = 10000000 unitCapacitanceName = "pf" capacitancePrecision = 10000000 unitInductanceName = "nh" inductancePrecision = 100 } Tile "unit" { width = 0.22 height = 1.69 } Layer "PRBOUNDARY" { layerNumber = 0 maskName = "" visible = 1 selectable = 1 blink = 0 color = "cyan" lineStyle = "solid" pattern = "blank" pitch = 0 defaultWidth = 0 minWidth = 0 minSpacing = 0 } Layer "METAL2" { layerNumber = 36 maskName = "metal2" isDefaultLayer = 1 visible = 1 selectable = 1 blink = 0 color = "yellow" lineStyle = "solid" pattern = "blank" pitch = 0.46 defaultWidth = 0.2 minWidth = 0.2 minSpacing = 0.21 fatContactThreshold = 1.4 maxSegLenForRC = 2000 unitMinResistance = 6.1e-05 unitNomResistance = 6.3e-05 unitMaxResistance = 6.9e-05 unitMinHeightFromSub = 1.21 unitNomHeightFromSub = 1.237 unitMaxHeightFromSub = 1.267 unitMinThickness = 0.25 unitNomThickness = 0.475 unitMaxThickness = 0.75 fatTblDimension = 3 fatTblThreshold = (0,0.39,10.005) fatTblParallelLength = (0,1,0) fatTblSpacing = (0.21,0.24,0.6, 0.24,0.24,0.6, 0.6,0.6,0.6) minArea = 0.144 } """ So it looks like starting from the inside out I have an key and a value where the value can be a QuotedString, Word(num), or a list of nums So my code to catch this looks like this.. atflist = Suppress("(") + commaSeparatedList + Suppress(")") atfstr = quotedString.setParseAction(removeQuotes) atfvalues = ( Word(nums) | atfstr | atflist ) l = ("36", '"metal2"', '(0.21,0.24,0.6,0.24,0.24,0.6)') for x in l: print atfvalues.parseString(x) But this isn't passing the list commaSeparatedList. Can someone point out my errors? As a side note: Is this the right approach to using pyparsing. Do we start from the inside and work our way out or should I have started with looking at the bigger picture ( keyword + "{" + OneOrMore key / vals + "}" + ) I started there but could figure out how to look multiline - I'm assuming I'd just join them all up? Thanks From jerry.fleming at saybot.com Tue Mar 18 21:00:20 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Wed, 19 Mar 2008 09:00:20 +0800 Subject: ctypes in python failed to honor c_int In-Reply-To: <49a1aad5-9020-4e6c-9389-502504a55ae4@u69g2000hse.googlegroups.com> References: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> <49a1aad5-9020-4e6c-9389-502504a55ae4@u69g2000hse.googlegroups.com> Message-ID: Gabriel Genellina wrote: > On 18 mar, 04:12, Jerry Fleming wrote: >> Gabriel Genellina wrote: >>> On 17 mar, 23:57, Jerry Fleming wrote: >>>> I have a binary file written with c structures. Each record contains a >>>> null-terminated string followed by two 4-bytes integers. I wrote a small >>>> segment of python code to parse this file in this way: >>>> [coe] >>>> #!/usr/bin/python >>>> from ctypes import * >>>> class Entry(Structure): >>>> _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) >>>> idx = open('x.idx', 'rb') >>>> str = idx.read(1000) >>>> obj = Entry(str) >>>> print obj.w >>>> print obj.s >>>> print obj.l >>>> [/code] >>>> where the field w is the string, and s and l are the integers. Problem >>>> is that, I can only get the strings, not the integers. Well, I did got >>>> integers, but they are all zeros. What should I do to get the real numbers? >>> So the string has a variable length? For "Hello" you have >>> 'h','e','l','l','o', a zero byte, followed by the two integers? This >>> is somewhat unusual for a C struct (in fact you can't declare it in >>> C). Perhaps the string is actually a char[n] array with a declared >>> maximum size? >> Yes, it has a variable length. The C version of the structure is >> something like this: >> [code] >> struct entry { >> char *str, >> int start, >> int length} >> >> [/code] > > But this doesn't match the file contents. There are no pointers in the > file. > >> And adding repr() would print something like this: >> [code] >> '(as) mad as a >> hatter\x00\x00\x00\x00\x00\x00\x00\x00\x1f-ish\x00\x00\x00\x00\x1f\x00\x00\?x00 at -ism\x00\x00\x00\x00_\x00\x00\x00B-ist\x00\x00\x00\x00\xa1\x00\x00\x00J?.AU\x00\x00\x00\x00\xeb\x00\x00\x00P.EXE\x00\x00\x00\x01;\x00\x00\x00`.GIF\?x00\x00\x00' >> (as) mad as a hatter >> 0 >> 0 >> [/code] >> where the first line is the result of repr(). We can find that, after >> the null-terminated string '(as) mad as a hatter', there are two >> integers, 0 and 31 (0x1f). But python treat 31 as zero. > > Ah, but it doesn't "treat 31 as zero". Entry(str) is the same as > Entry(w=str), that is, you are initializing the w attribute alone, > leaving the other two integers as 0. > I don't know how to use ctypes to read the structure (nor if it is > possible at all), I would read it normally with Python code and build > the struct afterwards (in case it is used to call any C code). > > w, data = data.split('\x00', 1) > s, l = struct.unpack("ll", data[:8]) > data= data[8:] > > -- > Gabriel Genellina Oh yes. What an idiot I am. Thanks Gabriel very much. From ncoghlan at gmail.com Tue Mar 4 07:00:17 2008 From: ncoghlan at gmail.com (NickC) Date: Tue, 4 Mar 2008 04:00:17 -0800 (PST) Subject: Embedding a literal "\u" in a unicode raw string. References: <47C340D4.6020803@v.loewis.de> Message-ID: <891938ee-ad81-43de-9985-73cd26e4268d@s12g2000prg.googlegroups.com> On Feb 26, 8:45 am, rmano wrote: > BTW, 2to3.py should warn when a raw string (not unicode) with \u in > it, I think. > I tried it and it seems to ignore the problem... Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> r"\u" '\\u' >>> r"\uparrow" '\\uparrow' >>> r"\u005c" '\\u005c' >>> r"\N{REVERSE SOLIDUS}" '\\N{REVERSE SOLIDUS}' >>> "\u005c" '\\' >>> "\N{REVERSE SOLIDUS}" '\\' 2to3.py may be ignoring a problem, but existing raw 8-bit string literals containing a '\u' aren't going to be it. If anything is going to have a problem with conversion to Py3k at this point, it is raw Unicode literals that contain a Unicode escape. From fakeaddress at nowhere.org Thu Mar 13 12:50:16 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 13 Mar 2008 09:50:16 -0700 Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: I wrote: > [...] Pipe loops are tricky business. > > Popular solutions are to make either the input or output stream > a disk file, or to create another thread (or process) to be an > active reader or writer. Or asynchronous I/O. On Unix-like systems, you can select() on the underlying file descriptors. (MS-Windows async mechanisms are not as well exposed by the Python standard library.) -- --Bryan From andoni.oconchubhair at fmr.com Tue Mar 18 11:34:32 2008 From: andoni.oconchubhair at fmr.com (Andoni) Date: Tue, 18 Mar 2008 08:34:32 -0700 (PDT) Subject: Need to force SpamBayes to run. Message-ID: Hi all, I realise this is not the SpamBayes list but you could grow old waiting for that so trying here. We are using SpamBayes to filter messages coming in to a mailbox. It misses some messages with errors like what's below. When this happens we can go in and click "Filter Messages" and it runs no problem. What I would like to be able to do is to have an hourly batch-job that runs that same process for me. I don't see anything in the file system that would allow me to run a command-line call that executes "Filter Messages". Can anybody help? Thanks in advance, Andoni OConchubhair. pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:09:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:09:45 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: <13t6s8pk90olef8@corp.supernews.com> On Sat, 08 Mar 2008 20:45:25 -0800, sjdevnull at yahoo.com wrote: > On Mar 8, 7:34 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: >> > I'm also a bit baffled by people who put a comment at the top of >> > every file that tells you what the filename is. >> >> [snip rant] >> >> You've never printed out a source file on pieces of dead tree to read >> on the train on the way home, or in bed or the bath? >> >> Yes, some editors will print a header or footer showing the file name, >> but not all will, or are configured to do so. > > The only times I can recall printing source were in college classes > where I was required to hand in a hardcopy with the assignment and code > samples for job interviews. In the real world the code base tends to be > too huge to contemplate printing... You've never (say) printed out the source code to one of the modules in the Python standard library to read and study? If your code base is so huge that you can't print out any meaningful piece, then you desperately need more encapsulation. > Even in the early 1990s the moral equivalent of enscript (I think it was > a2ps) worked just fine for printing with filenames, line/page numbers, > and other niceties no matter what editor you used. It seems more > reasonable to mandate using a sane print tool for the odd case where > someone wants to print things out than to mandate cluttering up every > file with the filename in a comment. Sure, but really, adding ONE LINE to the start of a file is hardly "cluttering up" anything. Especially if it is in the doc string, like this: """widgets.py: create, manage and destroy widgets. blah blah blah blah...""" -- Steven From gabriel.rossetti at mydeskfriend.com Tue Mar 11 04:49:18 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 11 Mar 2008 09:49:18 +0100 Subject: execute python script question In-Reply-To: <9e299ffa-2fab-4dcc-907c-8aa667bde3d4@n58g2000hsf.googlegroups.com> References: <9e299ffa-2fab-4dcc-907c-8aa667bde3d4@n58g2000hsf.googlegroups.com> Message-ID: <47D6478E.1050403@mydeskfriend.com> Sam wrote: > Hello, > > I may misunderstand your problem, but it may be related to the > execution environment, especially the PYTHONPATH variable. Have a look > at the following log: > > samuel at Bioman2:/$ pwd > / > samuel at Bioman2:/$ cat -n /tmp/test_import.py > 1 class A(object): > 2 def __init__(self): > 3 self.value = 1 > 4 def show(self): > 5 print self.value > samuel at Bioman2:/$ python > Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> from test_import import A >>>> > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named test_import > >>>> exit() >>>> > samuel at Bioman2:/$ export PYTHONPATH=/tmp > samuel at Bioman2:/$ python > Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> from test_import import A >>>> a=A() >>>> a.show() >>>> > 1 > > > ++ > > Sam > Hello Sam, Thank you for your reply. I tried that and it works, thanks. I was trying to modify the sys.path in __init__.py and it wasn't working. Gabriel From newsgroups at debain.org Wed Mar 5 02:15:07 2008 From: newsgroups at debain.org (Samuel) Date: Wed, 5 Mar 2008 07:15:07 +0000 (UTC) Subject: Protocol for thread communication References: Message-ID: On Tue, 04 Mar 2008 22:12:00 -0700, Michael Torrie wrote: > Does anyone have any recommended ideas/ways of implementing a proper > control and status protocol for communicating with threads? I have a > program that spawns a few worker threads, and I'd like a good, clean way > of communicating the status of these threads back to the main thread. > Each thread (wrapped in a very simple class) has only a few states, and > progress levels in those states. And sometimes they can error out, > although if the main thread knew about it, it could ask the thread to > retry (start over). How would any of you do this? A callback method > that the thread can call (synchronizing one-way variables isn't a > problem)? A queue? How would the main thread check these things? I implemented a generic library that could easily support these things: http://code.google.com/p/exscript/source/browse/trunk/lib/WorkQueue/ Basically, it's an asynchronous queue into which the jobs are added. The "MainLoop" class manages jobs (like, making sure that n jobs are running at the same time, and providing signals when jobs are done). One way to add a status to each job is by adding a status attribute to the Job class, in addition, a Job may emit a signal (using a simple signal/event mechanism such as this one: http://code.google.com/p/exscript/source/browse/trunk/lib/Exscript/ Trackable.py ) whenever a status changes, and have the MainLoop class fetch that. -Samuel From richardjones at optushome.com.au Fri Mar 28 20:07:09 2008 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 29 Mar 2008 11:07:09 +1100 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> Message-ID: <47ed882d$0$26468$afc38c87@news.optusnet.com.au> martin.nordstrom87 at gmail.com wrote: > I'm making a game where you'll be able to make your own mods and I > want to be able to write these mods in python. Check out tinypy: http://www.philhassey.com/blog/category/tinypy/ Richard From sjmachin at lexicon.net Thu Mar 27 06:56:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 10:56:29 GMT Subject: subtract dates with time module In-Reply-To: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> References: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> Message-ID: <47eb7d5b$1@news.mel.dft.com.au> barronmo wrote: > I'm trying to get the difference in dates using the time module rather > than datetime because I need to use strptime() to convert a date and > then find out how many weeks and days until that date. datetime.datetime.strptime was introduced in Python 2.5; what version are you using? If you really want to get to datetime, here's a quick bridge: >>> import time, datetime >>> def mystrptime(astr, format): ... return datetime.datetime(*time.strptime(astr, format)[:6]) ... >>> mystrptime('2008-03-31', '%Y-%m-%d') datetime.datetime(2008, 3, 31, 0, 0) > I'm a beginner > so any help would be appreciated. Here is the code: > > def OBweeks(ptID): > qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % > (ptID) > results = EMR_utilities.getAllData(qry) > for items in results: > r = re.search('\d\d\d\d-\d\d-\d\d', items) > if r: > d = time.strptime(r.group(), "%Y-%m-%d') - You have " at the start and ' at the end of what's supposed to be a string constant. That's a syntax error; it won't run. Please don't serve up what you thought you might have run -- use copy/paste. In this particular case, you can just use time.mktime to convert a time tuple into days since the epoch. # untested days = time.mktime(time.strptime(r.group(), "%Y-%m-%d")) - int(time.mktime(time.localtime())) weeks, days = divmod(days, 7) > time.localtime() > weeks, days = divmod(d.days, 7) > return '%s %s/7 weeks' % (weeks, days) > > This isn't working. I'm getting "unsupported operand type for -: > 'time.struct_time' and 'time.struct_time" error. It *is* working. That is the correct result of the code that you executed. There is is nothing in the time docs to suggest that attempting to subtract time tuples produces anything useful. HTH, John From bj_666 at gmx.net Tue Mar 18 03:41:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Mar 2008 07:41:52 GMT Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? References: <20080316132140.GA24529@piper.oerlikon.madduck.net> Message-ID: <649a20F24ufa8U1@mid.uni-berlin.de> On Mon, 17 Mar 2008 17:41:23 +0100, martin f krafft wrote: > also sprach martin f krafft [2008.03.16.1421 +0100]: >> Why doesn't it just yield >> >> '\n\n\n\n' >> >> Or even just >> >> '\n\n\n' > > There's a difference between those two. The first one has an empty > string value ('') while the second one pretty clearly says that > there is a parameter but has no value. > > Why ? Because there is a difference between no value and the NULL value!? Ciao, Marc 'BlackJack' Rintsch From aahz at pythoncraft.com Thu Mar 27 15:54:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2008 12:54:37 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: In article , Barry Hawkins wrote: > >I'll step out and say that some of the non-vendor talks were quite >weak. The most severe was a talk on Stackless where the original >speaker was unable to be here and someone got up and clicked through >the slide deck at a very fast pace. I thought the person had stepped >in at the last minute, but later learned that he had volunteered with >a couple of weeks' notice. Additionally, the original speaker had >Andrew Dalke's *exact* slide deck from his Stackless talk last year. >One first-time attendee told me over lunch that he was going to >recommend to his employer that they not pay to send their programmers >to PyCon next year based on what he had seen in this year's talks. I >know that's an unpleasant message, but in the interest of preserving >PyCon's quality, I'm willing to be the jerk of a messenger. The plural of anecdote is not data. I sympathize with what you're saying to some extent, but any gathering of a thousand people will certainly garner comments like this. Moreover, there will be some talks that screw up because of short notice changes (and believe me, two weeks is short notice). Feedback is for the most part only interesting in the aggregate. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From google at mrabarnett.plus.com Sun Mar 30 10:10:20 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 30 Mar 2008 07:10:20 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: On Mar 30, 6:35 am, "Gabriel Genellina" wrote: > En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: > > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > > if x ? 0: > > ?y ? s: > > if y ? 0: f1(y) > > else: f2(y) > > Fine if you have the right keyboard... Try to write APL with a standard > keyboard :) > There was a version of APL for the Sinclair QL which replaced the standard APL symbols with keywords. From agostino.russo at gmail.com Wed Mar 19 10:38:18 2008 From: agostino.russo at gmail.com (ago) Date: Wed, 19 Mar 2008 07:38:18 -0700 (PDT) Subject: Generalizing PEP 370 (per user site-packages directory) via .pth files Message-ID: <03cb8d9c-71b5-460c-8fb1-44d4e60c40d0@s13g2000prd.googlegroups.com> Dear all, I was reading pep 370, "Per user site-packages directory" http://www.python.org/dev/peps/pep-0370/, and was wondering if the concept couldn't be generalized by having ways to pass a .pth file as commandline argument and/or via an environment variable (PYTHONPATH could also be used to feed .pth files) and/or via special named files such as ~/.python2.6-user.pth or ./python2.6-local.pth, or possibly even reusing the paths in the distutils configuration files (under [install]). Any path in the above files would be added to sys.path and scanned recursively for other pth files. The system would also load default.pth from a pre-defined location (e.g. /etc/python2.6/ default.pth), which would point to the default site-packages directory. There should also be a mechanism to disable/override default.pth for situations where a clean environment is desired. This would make it easier to setup special testing environments, perform local installations, and allow for file-based deployments (in simple scenarios), without resorting to special tools such as virtual- python, editing site.py and/or requiring sysadmin intervention. It would be particularly useful in environments where there is a clear separation between IT and developer roles. I just started giving some thoughts to the concept and I am not fully aware of the implications and requirements of the proposal, but even if the above turns out to be impractical, I hope that a debate on the topic will be beneficial. Ago From martin.laloux at gmail.com Fri Mar 14 08:15:55 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Fri, 14 Mar 2008 05:15:55 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Message-ID: <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> look at http://groups.google.be/group/comp.lang.python/browse_thread/thread/d75a491b8dbc3880/0ca1fb7f7deca194?hl=fr&lnk=gst&q=laloux#0ca1fb7f7deca194 There is a macpython list that you can consult at http://www.nabble.com/Python---pythonmac-sig-f2970.html From john106henry at hotmail.com Mon Mar 31 13:37:42 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 10:37:42 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Message-ID: On Mar 31, 10:24 am, Amit Gupta wrote: > Hi > > I am looking for a some tool that can convert python scripts to > executable on Linux. > > I found freeeze.py as the only option so far. Couple of queries on > freeze: > > 1. Have anyone used the freeze utility and any experiences to share > from that? > 2. Is there any enterprise-level exe-builder for python on linux > (ActiveState has nothing)? > > Any other related commets are also welcome. > > Thanks > Amit I don't know about freeeze.py but for me, I've been using py2exe, and also pyinstall quite often and they both work for me. From grante at visi.com Tue Mar 11 11:35:52 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 11 Mar 2008 15:35:52 -0000 Subject: urllib proxy support confusion Message-ID: <13td9mobtoadgc2@corp.supernews.com> Reading through the doc at http://docs.python.org/lib/module-urllib.html, there are several paragraphs (including code examples) showing how you specify what proxies to use when calling urlopen(): Alternatively, the optional proxies argument may be used to explicitly specify proxies. [...] The explanation of how to specify proxies is followed by this paragraph denying that the ability to do so exists: The urlopen() function does not support explicit proxy specification. If you need to override environmental proxy settings, use URLopener, or a subclass such as FancyURLopener. That seems a bit baffling. If it urlopen doesn't support specifying proxies, why are there examples showing how to do it? If it does support specifying proxies, what is the pragraph quoted above supposed to mean? -- Grant Edwards grante Yow! Am I accompanied by a at PARENT or GUARDIAN? visi.com From sturlamolden at yahoo.no Thu Mar 20 13:03:40 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 10:03:40 -0700 (PDT) Subject: wxFormBuilder References: <9a27e$47e28f17$83aef404$28537@news1.tudelft.nl> Message-ID: <4bfece6c-19ad-41bf-846a-7139034dc737@s8g2000prg.googlegroups.com> On 20 Mar, 17:21, Stef Mientki wrote: > I've tried several of the above mentioned builders, > with the same result. > I've also looked at wxFormBuilder, > but I found it far too difficult and > fully unreadable (how can you create actions/bindings on components you don't see ?). > So I might be very very naive, > but why all so complex ?? Complex? Not at all! Let me show you an 'hello world!' example. Below is the content of two files: HelloWorld.py hand-written be me, and HelloWorld.xrc emitted by wxFormBuilder. I gave each control a care about a name in wxFormBuilder, and use that to e.g. bind events and load resources. HelloWorld.py: import wx from wx import xrc import sys class MainFrame(object): def __init__(self, xml): self.xml = xml self.frame = xml.LoadFrame(None,'MainFrame') self.frame.Bind(wx.EVT_MENU, self.on_menu_exit, id=xrc.XRCID('menuExit')) self.frame.Bind(wx.EVT_BUTTON, self.on_say_hello, id=xrc.XRCID('btnSayHello')) self.frame.Show() def on_say_hello(self, evt): dlg = self.xml.LoadDialog(self.frame, 'HelloDialog') dlg.ShowModal() dlg.Destroy() def on_menu_exit(self, evt): self.frame.Destroy() sys.exit(0) class HelloWordApp(wx.App): def OnInit(self): xml = xrc.XmlResource('HelloWorld.xrc') self.MainFrame = MainFrame(xml) return True if __name__ == '__main__': app = HelloWordApp(0) app.MainLoop() HelloWorld.xrc: 289,171 wxVERTICAL wxEXPAND 5 0,0 wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL 5 0 wxEXPAND 5 0,0 190,144 wxVERTICAL wxEXPAND 5 wxVERTICAL wxEXPAND 5 0,0 wxALIGN_CENTER|wxALL 5 14 swiss normal 0 Times New Roman wxEXPAND 5 0,0 wxEXPAND | wxALL 5 wxEXPAND 5 wxALIGN_CENTER_HORIZONTAL|wxALL 5 From sjdevnull at yahoo.com Mon Mar 10 16:44:04 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 10 Mar 2008 13:44:04 -0700 (PDT) Subject: Keep a python script running after browser window closed References: Message-ID: <077706bf-7190-44bc-9407-7d16b205d886@p73g2000hsd.googlegroups.com> On Mar 10, 1:42 pm, sophie_newbie wrote: > On Mar 7, 4:33 pm, Mike Driscoll wrote: > > > > > On Mar 7, 10:28 am, sophie_newbie wrote: > > > > Hi, > > > > I have a cgi script that performs a very long computation that can > > > take several hours to complete. Is there any smart way that I can keep > > > this script running until it is finished (after the user has closed > > > the browser) and email them with the results. The email bit isn't the > > > problem, I just don't know how to keep the code running in the > > > background. I'm sure there is a smart way to do this... > > > > Thanks! > > > You might have your cgi script use the subprocess module to open a > > second script that does the long-running process. > > > Mike > > Ya it looks like: > > import subprocess > > # spawn subprocess > subprocess.Popen(["python", "spawn.py"]) > > Should do this job, where spawn.py is the script to do the job. > Thanks. In real life, you probably want spawn.py to do a full daemonize. That means fork/setsid/fork/chdir appropriately/deal with stdin/stdout/ umask, or however you set up a service on Windows. From max at alcyone.com Tue Mar 4 00:58:55 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Mar 2008 21:58:55 -0800 Subject: sympy: what's wrong with this picture? In-Reply-To: <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: Mensanator wrote: > While we're on the subject of English, the word "worthless" > means "has no value". So, a program that doesn't work would > generally be "worthless". One that not only doesn't work but > creates side effects that cause other programs to not work > (which don't have bugs) would be "worse than worthless". All programs have bugs, which means that in some circumstances, they won't work. Therefore, by your reasoning, all programs are worse than useless. > I'm not hard to please at all. No, of course not, since logically you must think all software is useless. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Life is a zoo in a jungle. -- Peter de Vries From barnburnr at gmail.com Mon Mar 3 12:57:35 2008 From: barnburnr at gmail.com (barnburnr at gmail.com) Date: Mon, 3 Mar 2008 09:57:35 -0800 (PST) Subject: clocking subprocesses Message-ID: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> Hi, I've seen several threads on this subject, but haven't (yet) run across one that answers my specific questions. This should be really easy for someone, so here goes: I'm running some numerical simulations under Ubuntu, and using Python as my scripting language to automatically manage input and output. I need to have a precise performance measurement (CPU time) of how long it takes to run my simulations. Right now I have something like: stime = time.time() subprocess.call(["./mysim","args"]) ftime = time.time() print ftime-stime However, time.time() only gives wall-clock time, so I'm also measuring the time it takes to run other processes running at the same time. What I'd rather have is: stime = time.clock() subprocess.call(["./mysim","args"]) ftime = time.clock() print ftime-stime But this, of course, usually outputs 0, because time.clock() does not count the CPU ticks of the subprocess. So, long story short, I need to get CPU time of something I call using subprocess.call(). I don't want to have to profile my code, since it will significantly reduce computation time. Thanks for the advice. Kevin From timothy.brian14 at gmail.com Wed Mar 26 11:31:39 2008 From: timothy.brian14 at gmail.com (Timothy B) Date: Wed, 26 Mar 2008 08:31:39 -0700 (PDT) Subject: Sr. Architect - NYC - Opportunity Message-ID: <601e5c47-519e-42e8-b4f8-0eeb0496f28e@a70g2000hsh.googlegroups.com> Senior Developer Must be proficient in Python, expert preferred Must have one large scale public web project in their portfolio, preferably startup experience Must be able to develop with certain architectural considerations in mind at all times, such as: multilingual text, runtime efficiency in a very high load environment, file mgmt in a clustered environment, etc Must be self-motivated and eager to utilize the existing team's business knowledge to advance their own knowledge. We don't want anyone who wants to squirrel themselves away and read code alone all day. We need to be as efficient as possible in knowledge sharing in order to keep the code generation rate high. Must be able to manage time efficiently among multiple projects. These tech requirements should be implicit in the criteria above, but nonetheless are imperative: OO design SQL including indexing and query tuning AJAX, including APIs like Google Maps RSS and XML feeds in general. We deal with a lot of third party feeds that love to use XML. DHTML with CSS and Javascript Working knowledge of subversion, including branching and merging Must be able to configure a LAMP development environment (If you can do one, you can do them all. In our case "LAMP" means FreeBSD, Apache, MySQL, Webware for Python) Please contact: timothy.brian14 at gmail.com From carsten at uniqsys.com Tue Mar 11 10:01:34 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 11 Mar 2008 10:01:34 -0400 Subject: difference b/t dictionary{} and anydbm - they seem the same In-Reply-To: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> Message-ID: <1205244094.3430.20.camel@dot.uniqsys.com> On Tue, 2008-03-11 at 06:49 -0700, davidj411 wrote: > anydbm and dictionary{} seem like they both have a single key and key > value. > Can't you put more information into a DBM file or link tables? I just > don't see the benefit except for the persistent storage. Persistent storage /is/ the benefit. If you want to store relational data, you should use a relational database. -- Carsten Haese http://informixdb.sourceforge.net From rtw at freenet.co.uk Mon Mar 24 16:37:18 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 24 Mar 2008 15:37:18 -0500 Subject: encoding/decoding issue with python2.5 and pymssql References: <3a6c32fe-e7c1-4230-882d-efb3415196c1@b1g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote in news:3a6c32fe-e7c1-4230-882d-efb3415196c1 @b1g2000hsg.googlegroups.com in comp.lang.python: > for example: > the value > 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7' > is represent as > '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7' > from uuid import * u = UUID( bytes = '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7') print u u = UUID( bytes_le = '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7') print u The "bytes_le" version prints: ee604ee3-4ab0-4ee7-af4d-018124393cd7 so I guess, this is what mysql is returning. http://docs.python.org/lib/module-uuid.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From george.sakkis at gmail.com Mon Mar 31 15:05:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 12:05:42 -0700 (PDT) Subject: troll poll References: <65cmaqF2fhuoaU1@mid.uni-berlin.de> Message-ID: On Mar 31, 1:46 pm, Marc 'BlackJack' Rintsch wrote: > > More specifically, who can create a bigger mess on c.l.py? (check one) > > > [ ] - Xah Lee > > [X] - castironpi > > Xah Lee's postings might be trolls but sometimes they spark some really > interesting and serious subthreads, while the nonsense of castironpi is > just irritating noise. Which is exactly why there are rarely any replies to his random gibberish, so I would say that he/she/it has almost no effect on c.l.py. Yet I wish plonking was possible through Google groups. George From jason.scheirer at gmail.com Mon Mar 31 13:35:10 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 31 Mar 2008 10:35:10 -0700 (PDT) Subject: Automatically fill in forms on line References: Message-ID: <772b20d1-a845-480b-a583-cf8ba470ecae@q27g2000prf.googlegroups.com> On Mar 31, 9:50 am, "Jackie Wang" wrote: > Dear all, > > I want to automatically complete the following task: > > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx; > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > Highway 102"; > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > 4. Click the bottom "search"; > 5. In the opened page, extract and save the number after "Tract Code". > In the example, it will be "9659". > 6. Repeat Step 1 with a new address. > > Can Python realize these steps? Can these steps be done witout > openning and IE windows? Especially, I dont know how to write code for > step 2, 4 and 5. > > Thank you! You may also want to look at the Yahoo! maps API, which will also give you geocoding with a much nicer interface: http://www.yahooapis.com/maps/rest/V1/geocode.html unless you specifically need to use the TeleAtlas data or the API licensing is incompatible with the task at hand, I'd recommend using that instead. From gagsl-py2 at yahoo.com.ar Tue Mar 18 02:00:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 23:00:42 -0700 (PDT) Subject: Cost of Queue.put References: <7d3e817b-6931-4fc5-921c-b2cf2b2400fa@i7g2000prf.googlegroups.com> Message-ID: On 18 mar, 01:13, James wrote: > Basically, what I need is a multi-process safe persistent quick queue. > The arrangement I had was a simple XML-RPC service running on the web > server which the various web server threads POST the relevant search > engine updates to. These updates were added to a persistent queue > built on top of Queue.Queue and cPickle, and there was a separate > thread in the XML-RPC server actually adding the updates to the search > engine. > > However, the CPU consumption of the XML-RPC server seems to grow > pretty much linearly with the length of the persistent queue. Isn't > Queue.put O(1)? Maybe, but pickle.dumps is very likely O(n) and dominates. Why don't you use a database? Just insert and delete records with each get and put. -- Gabriel Genellina From mlists.sgv at gmail.com Thu Mar 6 03:10:22 2008 From: mlists.sgv at gmail.com (Sanjaya Vitharana) Date: Thu, 6 Mar 2008 13:40:22 +0530 Subject: Display all variable/function bindings in Python Shell Message-ID: <16803ed0803060010l64444a76o281411d323284b36@mail.gmail.com> Hi All, New to Python. Have some simple questions as a beginner. 1.) Are there any way to display all variable/function bindings in Python Shell ? 2.) Are the any way to Search "Python-list Archives" before sending simple question to the list ? Regards, Sanjaya Vitharana -------------- next part -------------- An HTML attachment was scrubbed... URL: From corynissen at gmail.com Fri Mar 7 10:45:08 2008 From: corynissen at gmail.com (corynissen at gmail.com) Date: Fri, 7 Mar 2008 07:45:08 -0800 (PST) Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: On Mar 7, 9:33 am, corynis... at gmail.com wrote: > On Mar 7, 9:12 am, nodrogbrown wrote: > > > > > hi > > i am using python on WinXP..i have a string 'folder ' that i want to > > join to a set of imagefile names to create complete qualified names so > > that i can create objects out of them > > > folder='F:/brown/code/python/fgrp1' > > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > > filenameslist=[] > > for x in filenms: > > myfile=join(folder,x) > > filenameslist.append(myfile) > > > now when i print the filenameslist i find that it looks like > > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > > is there some problem with the way i use join? why do i get \\ infront > > of the basename? > > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', > > > can anyone pls help > > gordon > > see path.join in the os library. Upon further examination... it looks like you are using windows and os.path.join. The separator for windows is a '\'. In python, you have to escape that character with another '\'. That's why you see '\\'. That being said, I think what you have will still work to access a file. Windows is usually smart enough to deal with a front slash here and there. From castironpi at gmail.com Sat Mar 8 15:00:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:00:30 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 1:31?pm, Grant Edwards wrote: > On 2008-03-08, castiro... at gmail.com wrote: > > > Does one side of this hold that there are no -good- comments? > > I wouldn't say there are _no_ good comments, but I would say > that 90+% of the comments I've seen in my lifetime were bad. Limit your comments, in other words. LIM-IT. > comment explaining a particularly opaque algorithm can be > useful as well. But can't the name do that? > at the beginnings of C/C++ functions that do things like tell > you the name and return type of the function and list the names > and types of the parameters. Gee, thanks. ?I never could have > figured that out from looking at the source code itself. IMO, Sometimes void*s are guaranteed to be HTHREADs. > I'm also a bit baffled by people who put a comment at the top > of every file that tells you what the filename is. ?I sometimes > wonder how/where these files were created. All of the OSes I've > ever used had a feature called a "filesystem" which kept track > of info like the names of files. ?It must be a bitch-and-a-half > to work on an computer that doesn't keep track of filenames and > makes the user do it. > > When was the last time you thought to yourself: "Gee, I wonder > what's the the name of that file over there? I guess I'd better > open the file and look at the comment at the top to see what > the filename is? What file did you open? To Lie: > Personally I preferred a code that has chosen good names but have > little or no comments compared to codes that makes bad names and have Personally I don't. Show me a good one. Until you do, it's not that I won't like it, it's that I can't. You know, in linguistics, there's what's called 'code switching', which is switching between two languages you know midstream. People can understand 'hear' a language but not speak it. If you speak it, . If comments aren't the 'short version', then patience is the problem. There's not one word for lots and lots of things. Examples on backorder. Good comments are better than bad names. Good names are better than bad comments. And enter multi-word identifiers. From petr.jakes.tpc at gmail.com Sat Mar 8 14:39:34 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Sat, 8 Mar 2008 11:39:34 -0800 (PST) Subject: SQL problem in python References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: Maybe you should try SQLObject :-) from sqlobject import * from sqlobject.sqlbuilder import Select #from sqlobject.sqlbuilder import * from datetime import datetime # =========== sqlite ============================== #connection = connectionForURI('sqlite:///dev/shm/ourdata.db') connection = connectionForURI('sqlite:/:memory:') sqlhub.processConnection = connection class MyTable(SQLObject): album = StringCol(length=20, default=None) filepath = StringCol(length=50, default=None) #MyTable.dropTable(ifExists=True) #MyTable._connection.debug = True # you can switch debuging ON, so you can see SQL commands generated by SQLObject MyTable.createTable(ifNotExists=True) MyTable(album ="Pinkk Floyd", filepath= "qwst" ) MyTable(album ="Pinkk", filepath= "gbfbd" ) MyTable(album ="Floyd", filepath= "fdgf" ) q = MyTable.select() for row in q: print row.album, row.filepath for row in MyTable.select(MyTable.q.album == "Pinkk Floyd"): print row.album, row.filepath HTH Petr Jakes From gherron at islandtraining.com Mon Mar 31 17:14:04 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 31 Mar 2008 14:14:04 -0700 Subject: import multiple modules with same name In-Reply-To: References: Message-ID: <47F1541C.4080602@islandtraining.com> Christian Bird wrote: > Is it possible to import multiple modules with the same name from > different locations? I'm using two different pieces of software, both > of which have a module named util.py. I know that I can modify > sys.path to fix which util gets imported when I do: > > import util > > I'd like to be able to do something like: > > import sys > sys.path.append("/somedir1/") > import util as util1 > sys.path.insert(0, "/somedir2/") > import util as util2 > > But it appears that once python imports a module, it will never look > for a module with the same name again. Is there any way to get around > this? I'd rather not rename either of the util modules as other > pieces of software use them (but the others never use both of them of > course) and I don't want to break them or have multiple copies of the > code in different named files. I'm appreciative of anyone's ideas. > > -- Chris > > If your two "pieces of software" are in fact Python packages (i.e., the directories have files named __init__.py), then you can import each this way: from package1 import util as util1 from package2 import util as util2 If they are not packages, then they should be, and you can make them so by creating empty files named __init__.py in each directory. From tjreedy at udel.edu Tue Mar 25 22:22:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Mar 2008 22:22:34 -0400 Subject: python hash() function References: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Message-ID: "Alvin Delagon" wrote in message news:7a01f6c00803251905j4b12633m65b2cde0f3037854 at mail.gmail.com... | Hello, | | >>> hash("foobar") | -1969371895 | | Anyone can explain to me how the hash() function in python does its work? A | link to its source could help me a lot also. I'm looking for a way to | replicate this function in php. Thanks in advance. If not part of your installation, start with svn.python.org and click browse. I would look for builtins.c or somesuch. From ron at example.com Wed Mar 26 10:28:26 2008 From: ron at example.com (Ron Eggler) Date: Wed, 26 Mar 2008 14:28:26 GMT Subject: last mouse movment or keyboard hit References: Message-ID: Gabriel Genellina wrote: > En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler escribi?: > >> I would like to get the time of the most recent human activity like a >> cursor >> movement or a key hit. >> Does anyone know how I can get this back to start some action after there >> has been no activity for X minutes/seconds? > > Which platform? On non-ancient Windows versions, you can periodically > check GetLastInputInfo > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp > > No, it would be for Linux and preferrably it would work on MacOS & Windows as well....is there anything? Thanks! -- chEErs roN From fuzzyman at gmail.com Sun Mar 23 15:25:09 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 23 Mar 2008 12:25:09 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <5be24bac-f82a-415e-8ff1-176b87ec06d2@d4g2000prg.googlegroups.com> On Mar 22, 6:40 pm, Jeff Schwab wrote: > jmDesktop wrote: > > For students 9th - 12th grade, with at least Algebra I. Do you think > > Python is a good first programming language for someone with zero > > programming experience? Using Linux and Python for first exposure to > > programming languages and principles. > > Linux and Python are a nearly ideal combination for this. Be aware that > at some point, you will likely have to dig into C, the primary language > used to implement both Linux and Python. I've been using Python for five years and now work full-time as a Python programmer. I've not had to hit C. :-) Michael Foord http://www.ironpythoninaction.com From wolf_tracks at invalid.com Thu Mar 20 23:21:22 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Mar 2008 20:21:22 -0700 Subject: An Application Program to Play a CD Message-ID: How difficult would it be to write a Python program that would play a specific track on a CD from say 8 am to 6 pm each weekday on a PC's speaker, and switch tracks each day? That is, what library capabilities might be able to do that. Are they already available. Extra points. Now imagine the same as above, but the program should answer a phone and play the track for the day while someone is holding the call, or would be given the option to connect to the operator, say, or listen to the recording? To get a bit specific, our science museum would like to buy the monthly set of StarDate programs. Each program is about 2 minutes long and there's one for every day of the month. There seems to be no such commercial software to automate this process. -- Wayne Watson (Nevada City, CA) Web Page: From castironpi at gmail.com Thu Mar 27 03:35:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 00:35:33 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <8edb9b4d-a775-4ccb-893d-9b8321e19be1@e39g2000hsf.googlegroups.com> On Mar 27, 2:33?am, Grimsqueaker wrote: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? Use list( it ). From inq1ltd at inqvista.com Fri Mar 28 19:43:00 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 28 Mar 2008 19:43:00 -0400 Subject: python program deleted In-Reply-To: References: <200803271808.06157.inq1ltd@inqvista.com> Message-ID: <200803281943.01098.inq1ltd@inqvista.com> thanks for the responses. I put the files in an ftp site and all is well. jim-on-linux From bockman at virgilio.it Mon Mar 24 07:49:19 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 11:49:19 GMT Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Message-ID: <47e7953f$0$18153$5fc30a8@news.tiscali.it> Il Sat, 22 Mar 2008 14:11:16 -0700, rh0dium ha scritto: > Hi all, > > I am struggling with parsing the following data: > > test1 = """ > Technology { > name = "gtc" dielectric > = 2.75e-05 unitTimeName > = "ns" timePrecision = 1000 > unitLengthName = "micron" > lengthPrecision = 1000 gridResolution > = 5 > unitVoltageName = "v" voltagePrecision > = 1000000 unitCurrentName = > "ma" currentPrecision = 1000 > unitPowerName = "pw" powerPrecision > = 1000 unitResistanceName = > "kohm" resistancePrecision = 10000000 > unitCapacitanceName = "pf" > capacitancePrecision = 10000000 > unitInductanceName = "nh" > inductancePrecision = 100 > } > > Tile "unit" { > width = 0.22 height > = 1.69 > } > > Did you think of using something a bit more sofisticated than pyparsing? I have had a good experience to using ply, a pure-python implementation of yacc/lex tools, which I used to extract significant data from C programs to automatize documentation. I never used before yacc or similar tools, but having a bit of experience with BNF notation, I found ply easy enough. In my case, the major problem was to cope with yacc limitation in describing C syntax (which I solved by "oelaxing" the rules a bit, since I was going to process only already- compiled C code). In your much simpler case, I'd say that a few production rules should be enough. P.S : there are others, faster and maybe more complete python parser, but as I said ply is pure python: no external libraries and runs everywhere. Ciao ------- FB From ggpolo at gmail.com Sat Mar 29 07:18:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 29 Mar 2008 08:18:23 -0300 Subject: why does socket.makefile require non-blocking mode? In-Reply-To: <21989.75.55.199.5.1206748234.squirrel@webmail.sonic.net> References: <21989.75.55.199.5.1206748234.squirrel@webmail.sonic.net> Message-ID: 2008/3/28, Forest : > The socket.makefile() docs say, "the socket must be in blocking mode." I > don't see any explanation of why blocking mode is required, and I'm not sure > whether that means timeout mode is forbidden as well. Can someone clarify > this? > Have you set your socket to be nonblocking ? Otherwise it is blocking, it is the "normal" one. I don't know why you think timeout is forbidden too, it is not. > I wanted to use file-like objects with socket timeouts, so I ended up writing > my own replacement for socket._fileobject. I'd appreciate it if someone could > either explain to my why my new class was unnecessary, or else encourage me to > contribute it as a patch to the socket module. > It looks like to be unnecessary. > Cheers, > > Forest > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From vpalexander at gmail.com Sun Mar 9 05:57:38 2008 From: vpalexander at gmail.com (Vince) Date: Sun, 9 Mar 2008 01:57:38 -0800 (PST) Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> <63hq8rF27chv6U1@mid.uni-berlin.de> Message-ID: <96486094-0706-45f1-b5c1-4af6333e3955@s13g2000prd.googlegroups.com> On Mar 9, 1:51 am, Marc 'BlackJack' Rintsch wrote: > On Sun, 09 Mar 2008 01:42:01 -0800, vpalexander wrote: > > I keep seeing destructor calls in wx for ad hoc dialogs and wonder if > > this is required, and if so, why would normal gc flow not be good? > > Because there is no guarantee when `__del__()` is called or if it is > called *at all*. > > Ciao, > Marc 'BlackJack' Rintsch Well, that suits me. The most unnatural thing about Python was adapting to the idea of just letting unreleased resources go jogging off wherever. :) "Where's the f.close?" "You don't need it!" Hmmm! From fetchinson at googlemail.com Thu Mar 20 12:06:58 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 20 Mar 2008 09:06:58 -0700 Subject: pep 3108 Message-ID: Hi Brett, I've just looked through pep 3108 and since Raymond Hettinger suggested contacting you if we "have issues with it", here it goes: I don't think it would be a great idea to move tkinter from the core to a third party library because once that happens we can no longer assume that any GUI library is present on a box with python installed. Of course it's not a big deal to install an extra package but when it comes to distribution customers/friends/family/etc are forced to install the third party package too and that is beyond the control of the developer (are they willing to do it? are they able to do it? do they think it's a hassle?). I've brought up the issue on c.l.p and people seem to agree, please see the thread for additional detail: http://tinyurl.com/2v4mh3 Cheers, Daniel From darcy at druid.net Tue Mar 18 12:41:35 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 18 Mar 2008 12:41:35 -0400 Subject: Need Help Starting Out In-Reply-To: <4aa24daf-4f7b-405e-83c2-d1face854ed1@s37g2000prg.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> <4aa24daf-4f7b-405e-83c2-d1face854ed1@s37g2000prg.googlegroups.com> Message-ID: <20080318124135.7d170210.darcy@druid.net> On Tue, 18 Mar 2008 09:27:46 -0700 (PDT) rodmc wrote: > > > Hi, I would like to start using Python, but am unsure where to begin. > > I know how to look up a tutorial and learn the language, but not what > > all technologies to use. I saw references to plain Python, Django, > > and other things. > > Hi, > > For database stuff you can plug directly into either MySQL or SQLite. Or PostgreSQL. > For MySQL you need to install a third party library which you can get > from: > > http://sourceforge.net/projects/mysql-python And there are many interfaces for PostgreSQL including PyGreSQL which I maintain at http://PyGreSQL.org/ > Hope these help you get started... And don't forget the tutorial on the Python web site. -- 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 bearophileHUGS at lycos.com Tue Mar 4 16:08:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 4 Mar 2008 13:08:13 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <2ecbb96f-c246-48c5-836f-bf934ac56ba6@e25g2000prg.googlegroups.com> Message-ID: <7379aaf9-53b7-4258-b54d-b9753a007144@n36g2000hse.googlegroups.com> apatheticagnostic: > I swear, this is one of the most polite-oriented groups I've ever > seen. > Not that that's a bad thing or anything, it's nice to be nice. Yep, and with lot more work it may even become a bit fit for women/ females too. Bye, bearophile From maciej.blizinski at gmail.com Tue Mar 18 00:20:01 2008 From: maciej.blizinski at gmail.com (=?ISO-8859-2?Q?Maciej_Blizi=F1ski?=) Date: Mon, 17 Mar 2008 21:20:01 -0700 (PDT) Subject: urllib2.unquote() vs unicode Message-ID: <9b79a441-aa7a-4e4c-8ec6-337893c330ba@n77g2000hse.googlegroups.com> I've been hit by a urllib2.unquote() issue. Consider the following unit test: import unittest import urllib2 class UnquoteUnitTest(unittest.TestCase): def setUp(self): self.utxt = u'%C4%99' self.stxt = '%C4%99' def testEq(self): self.assertEqual( self.utxt, self.stxt) def testStrEq(self): self.assertEqual( str(self.utxt), str(self.stxt)) def testUnicodeEq(self): self.assertEqual( unicode(self.utxt), unicode(self.stxt)) def testUnquote(self): self.assertEqual( urllib2.unquote(self.utxt), urllib2.unquote(self.stxt)) def testUnquoteStr(self): self.assertEqual( urllib2.unquote(str(self.utxt)), urllib2.unquote(str(self.stxt))) def testUnquoteUnicode(self): self.assertEqual( urllib2.unquote(unicode(self.utxt)), urllib2.unquote(unicode(self.stxt))) if __name__ == '__main__': unittest.main() The three testEq*() tests positively confirm that the two are equal, they are the same, they are also the same if cast both to str or unicode. Tests with unquote() called with utxt and stxt cast into str or unicode are also successful. However... ...E.. ====================================================================== ERROR: testUnquote (__main__.UnquoteUnitTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "unquote.py", line 28, in testUnquote urllib2.unquote(self.stxt)) File "/usr/lib/python2.4/unittest.py", line 332, in failUnlessEqual if not first == second: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) ---------------------------------------------------------------------- Ran 6 tests in 0.001s FAILED (errors=1) Why does this test fail while others are successful? Any ideas? Regards, Maciej From gagsl-py2 at yahoo.com.ar Thu Mar 6 18:17:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 21:17:49 -0200 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> <7817aa43-0f4d-4ace-9279-8e1fbdf2640d@b1g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 20:45:09 -0200, escribi?: > I'd like to question the source of the definition of C.__eq__. > > Observation: > >>>> class C: pass > ... >>>> class D: pass > ... >>>> C== D > False > > What is different about them? I've created two empty classes, nothing > more. Their __name__ attribute? Types are compared by their memory addresses, not by contents, and that's enough and efficient for most people. If you require something different, use a metaclass. -- Gabriel Genellina From carsten at uniqsys.com Sat Mar 8 13:38:08 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 08 Mar 2008 13:38:08 -0500 Subject: SQL problem in python In-Reply-To: <13t5lm9lva8ji7a@corp.supernews.com> References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> <15f2175c-9d48-47c9-8499-889923004aee@x30g2000hsd.googlegroups.com> <13t5lm9lva8ji7a@corp.supernews.com> Message-ID: <1205001488.3161.24.camel@localhost.localdomain> On Sat, 2008-03-08 at 10:11 -0800, Dennis Lee Bieber wrote: > On Sat, 8 Mar 2008 09:28:23 -0800 (PST), aiwarrior > declaimed the following in comp.lang.python: > > > Thanks a lot. > > In the Python documentation, the sqlite module documentation doesn't > > mention that special rule. I really thought that every variable to be > > included in a query had to use that special method. > > > It's not sqlite specific -- it is common to all of the db-api > compatible adapters. > > The explanation for why you were getting 'filename' (or whatever the > field was is: parameter substitution ensures that the parameter value is > properly quoted and escaped to be safe for use as a value. It's called "parameter binding", not "parameter substitution". Parameter binding ensures that the value is passed to the database safely. That need not necessarily be a quoting-and-escaping exercise. Depending on the API module, it may use a mechanism that transmits the query string and the parameters to the database engine separately. Also note that SQL standard doesn't even allow parameters in the projection clause of a select statement. SQLite is just more relaxed about the standard than for example Informix: >>> import informixdb >>> conn = informixdb.connect("stores_demo") >>> cur = conn.cursor() >>> cur.execute("select ? from customer", ("customer_num",) ) Traceback (most recent call last): File "", line 1, in _informixdb.ProgrammingError: SQLCODE -201 in PREPARE: 42000: Syntax error or access violation -- Carsten Haese http://informixdb.sourceforge.net From pavlovevidence at gmail.com Thu Mar 6 10:58:06 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 07:58:06 -0800 (PST) Subject: Identifying messages in a thread (was: Please keep the full address) References: <8763w094sy.fsf_-_@benfinney.id.au> Message-ID: <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> On Mar 5, 8:11 pm, "D'Arcy J.M. Cain" wrote: > On Thu, 06 Mar 2008 09:36:29 +1100 > > Ben Finney wrote: > > > Those of us who identify the time wasters would also like to drop > > > the responses to their posts and changing the address makes this > > > impossible. > > > Not at all. AFAIK the messages from Google mail correctly include the > > 'In-Reply-To' field or the 'References' field in the message header. > > So, you can know by those fields whether a message is part of a thread > > you've previously identified. > > I don't want to have to tag every thread. I just want to *plonk* > certain posters. > > Anyway, I'll live with Google's failings I guess. Sounds like you need better filtering. A decent news filter should be able not only kill a poster, but also all followups to that poster recursively. (No, I don't know of any that do that either.) Carl Banks From Krishna.00.K at gmail.com Thu Mar 6 19:48:42 2008 From: Krishna.00.K at gmail.com (Krishna) Date: Thu, 6 Mar 2008 16:48:42 -0800 (PST) Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments Message-ID: >>> class Test(object): ... def __init__(self): ... self.a= 2 ... def func(self, k = self.a): ... print k ... Traceback (most recent call last): File "", line 1, in ? File "", line 4, in Test NameError: name 'self' is not defined >>> In the 'definition of the class', what would the first argument 'self' in the methods evaluate to; when we have an object defined, it is bound to the object reference, but what happens while the class definition is executed, which I believe happens when the module containing the class definition is imported Thanks, Kr From Minor.Gordon at cl.cam.ac.uk Tue Mar 25 16:37:21 2008 From: Minor.Gordon at cl.cam.ac.uk (Minor Gordon) Date: Tue, 25 Mar 2008 20:37:21 +0000 Subject: [Fwd: Beta testers needed for a high performance Python application server] Message-ID: <47E96281.5000304@cl.cam.ac.uk> One thing I forgot to add: the code is GPLv2, though I'll consider alternative licenses for specific users. -------- Original Message -------- Subject: Beta testers needed for a high performance Python application server Date: Tue, 25 Mar 2008 20:31:39 +0000 From: Minor Gordon To: python-list at python.org Hello all, I'm looking for beta testers for a high performance, event-driven Python application server I've developed. About the server: the front end and other speed-critical parts of the server are written in portable, multithreaded C++. The back end is an embedded CPython interpreter. The server is much faster than anything in pure Python, and it can compete with C servers (including e.g. lighttpd for file workloads) or outdo them (e.g. anything behind Apache) until CPython consumes a single processor. On the Python side it supports WSGI (the server can handle the static and dynamic requests of MoinMoin with a handful of lines), the DB API with blocking calls offloaded to a connection in a separate thread (MySQL, SQLite supported), Google's ctemplate, gzipping responses, file caching, reading and writing to URIs as a client, AJAX integration, debugging as a Python extension, and a lot of other features. The core Python API is event-driven, using continuations like Twisted but much cleaner (continuations are any callables, there are no special objects anywhere). The Python back end also supports Stackless Python so all of the continuation machinery can be hidden behind tasklet switching. Background: I'm in this to help write a "story" for Python and web applications. Everyone likes to go on about Ruby on Rails, and as far as I can tell there's nothing that approaches Rails in Python. I want to code quickly in Python like I can with Rails, but without sacrificing single node performance on many cores. Beta testers: should be intermediate to advanced Python programmers with demanding applications, particularly web applications with databases and AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory libraries beyond python-dev. Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. Minor From __peter__ at web.de Fri Mar 7 02:35:39 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Mar 2008 08:35:39 +0100 Subject: Ncurses not found - embedded linux References: <63b1rjF26p2fkU1@mid.uni-berlin.de> <754dad0b-9d3e-4ca7-a5fc-38519312947f@q78g2000hsh.googlegroups.com> Message-ID: blaine wrote: >> > I hope this is trivial, and I apologize ahead of time if so. Would >> > this perhaps be a compilation issue? Something we have to turn on in >> > the python compile? >> >> Usually, you need not only the libraries but also the headers at >> compilation time. Most probably these were missing. >> >> Diez > > Thank you for our response. Do you mean that the ncurses header > should be in /usr/include upon compilation of python? Will python > automatically pick up on these headers, or would I need to change > compilation options? Thanks! -Blaine Just rerun the ./configure script -- it should detect the presence of the required header file automatically. If all went well you'll see "yes" three times: $ sudo aptitude install ncurses-dev [...] $ ./configure > tmp.txt [...] $ grep ncurses tmp.txt checking ncurses.h usability... yes checking ncurses.h presence... yes checking for ncurses.h... yes Peter From miki.tebeka at gmail.com Tue Mar 11 13:18:04 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 11 Mar 2008 10:18:04 -0700 (PDT) Subject: Exctract GIF comment from image References: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Message-ID: Hello Wingi, > simple question: The PIL does not support reading the optional > description in GIF Images. > > http://www.pythonware.com/library/pil/handbook/format-gif.htm > > After some reasearch I could not find a python solution for this, any > suggestions? Use ImageMagick (www.imagemagick.org), "identify -verbose " should have the comments somewhere in the output. There also a python binding to ImageMagick but I have no experience with it. HTH, -- Miki http://pythonwise.blogspot.com From kmgrds at gmail.com Mon Mar 31 14:52:11 2008 From: kmgrds at gmail.com (kim) Date: Mon, 31 Mar 2008 11:52:11 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig References: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> Message-ID: <09a0fafc-5658-470a-87a4-8b906caab5ed@e6g2000prf.googlegroups.com> thanks a lot, sturlamolden, for the quick reply! so i tried to use numpy and ctypes as you advised and i got it working: with some little changes for my linux machine - i hope they aren't the cause of the results: to load it, i only got it going with LoadLibrary: lib = numpy.ctypeslib.load_library("_timewarpsimple.so",".") _timewarp = lib.timewarp i replaced double by c_double: array_pointer_t = ndpointer(dtype=c_double) and i needed to define a restype, too: _timewarp.restype = c_double so, the strange errors with lots of stack traces are gone, but for large lists i got the same problem: Segmentation fault. for example for the following two lines: list1,list2 = numpy.array([0.1 for i in range(999)]), numpy.array([0.7 for i in range(1041)]) print timewarp(list1,list2) So it is maybe more of a c problem, but still, if i copy the big arrays into my c code, everything works out just fine (x[]={0.1,0.1,... }...) so it may still have something to do with the python-c interface and memory allocation or something like that. below i put my new shorter python script, the c and the rest hasn't changed. what can i try now? thanks again kim import numpy import ctypes from numpy.ctypeslib import ndpointer from ctypes import c_int,c_double lib = numpy.ctypeslib.load_library("_timewarpsimple.so",".") _timewarp = lib.timewarp #_timewarp = ctypes.cdll.timewarp.timewarp # timewarp.dll array_pointer_t = ndpointer(dtype=c_double) _timewarp.argtypes = [array_pointer_t, c_int, array_pointer_t, c_int] _timewarp.restype = c_double def timewarp(x, y): lenx, leny = x.shape[0], y.shape[0] print lenx,leny return _timewarp(x, lenx, y, leny) # testing: list1,list2 = numpy.array([0.1 for i in range(999)]), numpy.array([0.7 for i in range(1041)]) print timewarp(list1,list2) for x in range(999,1111): for y in range(999,1111): list1,list2 = [0.1 for i in range(x)], [0.9 for i in range(y)] print len(list1),len(list2),len(list1)+len(list2) list1,list2 = numpy.array(list1), numpy.array(list2) print timewarp(list1,list2) On Mar 30, 10:56 pm, sturlamolden wrote: > On 30 Mar, 22:21, kmg... at gmail.com wrote: > > > Hello everybody, > > > I'm building a python module to do some heavy computation in C (for > > dynamic time warp distance computation). > > Why don't you just ctypes and NumPy arrays instead? > > # double timewarp(double x[], int lenx, double y[], int leny); > > import numpy > import ctypes > from numpy.ctypeslib import ndpointer > from ctypes import c_int > > _timewarp = ctypes.cdll.timewarp.timewarp # timewarp.dll > array_pointer_t = ndpointer(dtype=double) > _timewarp.argtypes = [array_pointer_t, c_int, array_pointer_t, c_int] > > def timewarp(x, y): > lenx, leny = x.shape[0], y.shape[0] > return _timewarp(x, lenx, y, leny) From anthonysmith80 at gmail.com Tue Mar 25 10:03:35 2008 From: anthonysmith80 at gmail.com (Anthony) Date: Tue, 25 Mar 2008 07:03:35 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: On Mar 25, 11:44 am, Tzury Bar Yochay wrote: > While my intention is to get 1.2 I get 2.2 > I would like to know what would be the right way to yield the expected > results Is this what you want? class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = Foo().getid() b = self.id return '%d.%d' % (a,b) >>> FooSon().getid() '1.2' Best wishes, Anthony From pavlovevidence at gmail.com Fri Mar 7 17:33:20 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 7 Mar 2008 14:33:20 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <16db6135-a8eb-432f-9b50-91efe65e2b3b@13g2000hsb.googlegroups.com> On Mar 7, 5:08 pm, shak... at gmail.com wrote: > I'm new to python and I was wondering if there are any intelligent > date/time parsing modules out there. I've looked at strptime (or > whichever it is) and mxDateTime from the eGenix package. I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. > > So are there any modules that allow for that kind of parsing? GNU date can do a lot of these things--if your Django server is running Linux it probably has GNU date installed. (Might not be practical to start a new process in the middle of a query, especially a lot of them.) >From a shell command line, get the current time (in seconds since epoch, which you can pass to Python time functions) this way: date +"%s.%N" And you can enter all sort of relative and absolute date strings: date +"%s.%N" --date='last monday' date +"%s.%N" --date='a year ago' date +"%s.%N" --date='10pm tuesday' These all apparently work. Now all you have to do is call it from Python using subprocess module and you're set. (DO NOT use os.system for this since it starts a shell process, which is unnecessarily slow, and dangerous when passed user input.) Carl Banks From rockxuan at gmail.com Tue Mar 18 03:41:15 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:41:15 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <8ec1f9b0-e740-475c-9d1a-61e8c2c27fd6@i12g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From deets at nospam.web.de Sun Mar 2 09:54:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Mar 2008 15:54:01 +0100 Subject: tcp In-Reply-To: References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: <62vtc9F1q1kebU1@mid.uni-berlin.de> Gif schrieb: > you could at least check before posting. as i said i've tried like > 1000 ways of doing that, and im so desparate that i'm thinking of > quiting python. This damn thing just doesnt work. when i do as you > post the server never even replies, as it tends to accept connections > all the time. > > anyone has a better idea? http://www.catb.org/~esr/faqs/smart-questions.html Nobody here knows what you did - post code & stacktraces of at least one of your "1000 ways". Or quit python and try a language that is more friendly to reading your mind instead requiring you to spell out things in a computer readable way. You might need to hibernate a couple of centuries though until it's sufficient to open notepad and write "I'm a ubercool programmer, do make me the application of my dreams". DIEZ From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:30:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:30:58 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: <13t6iv2b9oeq6a6@corp.supernews.com> On Sun, 09 Mar 2008 01:48:21 +0000, Steven D'Aprano wrote: > (And the ease that these mistakes can happen is why such fundamental > functions should be in the standard library, no matter how easy they are > to implement.) Which, of course, they are. math.ceil() and math.floor() I knew that. *cough* -- Steven From Sandipan at gangopadhyay.com Sat Mar 15 08:24:55 2008 From: Sandipan at gangopadhyay.com (Sandipan Gangopadhyay) Date: Sat, 15 Mar 2008 08:24:55 -0400 Subject: Python for BlackBerry In-Reply-To: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Message-ID: <0e8501c88697$9499a4e0$bdcceea0$@com> Is there a Python for BlackBerry? Thanks. -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of E-Lo Sent: Saturday, March 15, 2008 6:03 AM To: python-list at python.org Subject: Python for Palm OS Is there any other edition of Python for Palm OS instead of Pippy? -- http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:48:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:48:07 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: On 10 mar, 02:08, Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? Do you want to compute x! (factorial of x)? That is, you want a program that given a 4, returns 24? Think how would you compute it by hand and try to write the same thing using Python instructions. If you come with a program and have a specific problem someone here will be able to help you, but don't expect your homework to be done for free... -- Gabriel Genellina From NO_Kroeger at gmx.de Mon Mar 3 08:53:06 2008 From: NO_Kroeger at gmx.de (=?UTF-8?B?TmlscyBPbGl2ZXIgS3LDtmdlcg==?=) Date: Mon, 03 Mar 2008 14:53:06 +0100 Subject: Cant run application as ./myapp.py In-Reply-To: <00ec01c87d2b$11f4f0f0$35ded2d0$@rawlins@thinkbluemedia.co.uk> References: <00ec01c87d2b$11f4f0f0$35ded2d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <47CC02C2.8040901@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Robert, I have to guesses: a) The user as which you are trying to run the script is missing the execute right -> fix by chmod u+x MyApplication.px b) You did not specify the interpreter -> the first line of your script should look something like #!/usr/bin/python If none of this is the problem please post the error message you (hopefully) get. hth Nils Robert Rawlins schrieb: > Hello Guys, > > > > I?ve got an application here which for some reason won?t start using the > following syntax from the command line: > > > > Cd /mydirectory > > ./MyApplication.py > > > > I have to run this as a fully qualified python launch such as: > > > > Cd /mydirectory > > python MyApplication.py > > > > This is a little bit confusing to me as I have other applications which > run just fine using the ./somthing.py syntax. Is there any reason why > this doesn?t work? > > > > Cheers, > > > > Robert > -----BEGIN PGP SIGNATURE----- iD8DBQFHzALBzvGJy8WEGTcRAtE8AJ4jGFTjZ8G8ayZM2AUcLcArnF5d1QCdH0gj kCdp0414HwPaIMIDv/SSTZA= =tF3K -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: NO_Kroeger.vcf Type: text/x-vcard Size: 162 bytes Desc: not available URL: From grante at visi.com Sat Mar 8 10:31:56 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 08 Mar 2008 15:31:56 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> Message-ID: <13t5cbcrhtfsrd2@corp.supernews.com> On 2008-03-08, dave_mikesell at fastmail.fm wrote: >> The function name also doesn't explain anything. How was the stuff got? >> Was it paid for, or stolen, or picked up on consignment, or what? Compare >> the above line with: >> >> x = get_stuff(store) # Steal stuff from the store. >> >> or >> >> x = get_stuff(store) # Pickup the stuff from the store for disposal. >> # The amount paid by the store is stored in global variable "pay_received" >> # and the name of the employee authorizing the pickup is stored in the >> # global "authorized_by". > > Shouldn't get_stuff's comment be with its definition? Probably, but better that comment shouldn't be anywhere. get_stuff() should be 1) renamed, as you state below. 2) written such that it's obvious from reading the source code that the amount paid is stored in the global variable pay_received and that the name of the employee authorizing the pickup is stored in the global authorized by. But, it's not really fare picking on an example like that... > And just rename the function to something more meaningful, > like purchase_goods(store), or whatever. >> But even if you were right that the comment was unnecessary, >> you have missed my point that even single sentences can be >> grammatically bogus and the writer could learn a lot from >> Strunk and White or equivalent. That's true. I don't know how many times I've seen a single sentence comment that was just plain vague and ambiguous. And most of the time they're just plain wrong as well because the code had been changed but nobody changed the comment (possibly because they couldn't understand what the comment was trying to say). -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From schiz at lon.don Sat Mar 1 09:39:48 2008 From: schiz at lon.don (Schizoid Man) Date: Sat, 01 Mar 2008 14:39:48 +0000 Subject: Beginner's assignment question Message-ID: As in variable assignment, not homework assignment! :) I understand the first line but not the second of the following code: a, b = 0, 1 a, b = b, a + b In the first line a is assigned 0 and b is assigned 1 simultaneously. However what is the sequence of operation in the second statement? I;m confused due to the inter-dependence of the variables. From hdante at gmail.com Sun Mar 30 17:18:44 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 14:18:44 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: <2f475146-3489-49b6-9ba9-3d27d297f095@d62g2000hsf.googlegroups.com> On Mar 30, 3:14 pm, Lie wrote: > On Mar 30, 12:11 pm, hdante wrote: > (snip) > > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > > if x ? 0: > > ?y ? s: > > if y ? 0: f1(y) > > else: f2(y) > > That would be a nightmare. > > Programming language (or most computer-based texts) should only use > basic ASCII characters, except if it can't be helped since typing non- I completely disagree. Unicode should be used whenever the architecture doesn't have memory restrictions. For general (plain-)text there's no sense in talking about ASCII. The only language that "fits" in it that I can remember is Latin. > ASCII characters is still unreliable. It'd also be a headache to > memorize what keyboard combinations to use to type a character. Not to You'd have to memorize, for example "!=" and ">=". > mention how much more complex would the keyboard design be. Also not The keyboard would be the same. > mentioning how much more complex the language design would be to > handle all those non-ASCII characters. Wrong. From arnodel at googlemail.com Mon Mar 10 18:10:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Mar 2008 15:10:03 -0700 (PDT) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <8c4045ba-19eb-46ba-87bc-32d0d623f27d@x41g2000hsb.googlegroups.com> On Mar 8, 2:43?pm, malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > ? ? x = q.get() > ? ? #process x to get zero or more y's > ? ? #for each y: > ? ? q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > ? ? #process x to get zero or more y's > ? ? q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? > > Regards, > > Muhammad Alkarouri You could make it safe this way ('emulating' what a listiterator object does in CPython): >>> from itertools import count >>> def index_iter(l): ... try: ... for i in count(): yield l[i] ... except IndexError: ... return ... >>> l = list('SPAM') >>> for c in index_iter(l): ... if c == 'A': l += list(' EGGS') ... if c == 'S': l += list(' NI') ... >>> ''.join(l) 'SPAM NI EGGS NI' >>> Of course in practice this is no different from doing 'for c in l:...' but it is safe against implementation changes. -- Arnaud From rehn at iwm.mw.tu-dresden.de Wed Mar 12 11:22:19 2008 From: rehn at iwm.mw.tu-dresden.de (rehn at iwm.mw.tu-dresden.de) Date: Wed, 12 Mar 2008 08:22:19 -0700 (PDT) Subject: ValueError in pickle module during unpickling a infinite float (python 2.5.2) Message-ID: <4b9d0896-df9c-47b6-98b6-16f825d67975@i7g2000prf.googlegroups.com> Unpickling an infinite float caused a ValueError in the pickle module. I need to pickle and load infinite floats in my project. Do you have any suggestions how to solve the issue? # code describing the issue: # define float constants with double-precision: # copied from fpconst module: http://www.analytics.washington.edu/statcomp/projects/rzope/fpconst/ import struct _big_endian = struct.pack('i',1)[0] != '\x01' # check endianess if(_big_endian): # and define appropriate constants NaN = struct.unpack('d', '\x7F\xF8\x00\x00\x00\x00\x00\x00')[0] PosInf = struct.unpack('d', '\x7F\xF0\x00\x00\x00\x00\x00\x00')[0] NegInf = -PosInf else: NaN = struct.unpack('d', '\x00\x00\x00\x00\x00\x00\xf8\xff')[0] PosInf = struct.unpack('d', '\x00\x00\x00\x00\x00\x00\xf0\x7f')[0] NegInf = -PosInf # pickling and unpickling a infinite float: f = PosInf p = pickle.dumps(f) rf = pickle.loads(p) print f print rf # ValueError in python 2.5.2: Traceback (most recent call last): File "....py", line 89, in rf = pickle.loads(p) File "...\pickle.py", line 1374, in loads return Unpickler(file).load() File "...\pickle.py", line 858, in load dispatch[key](self) File "...\pickle.py", line 954, in load_float self.append(float(self.readline()[:-1])) ValueError: invalid literal for float(): 1.#INF From cwitts at gmail.com Wed Mar 12 07:17:49 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 04:17:49 -0700 (PDT) Subject: Creating a file with $SIZE References: Message-ID: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> On Mar 12, 12:52?pm, Chris wrote: > On Mar 12, 12:32?pm, "k.i.n.g." wrote: > > > Hi All, > > > I would like create files of different size, taking size as user > > input. I need to check the data transfer rates from one network to > > another . In order to do this I will have to create files of diff size > > and work out. I am new to Python > > > Thanks in advance. > > > KK > > Welcome to Python. > > If you just want to create files with random junk from the user input > then maybe something along these lines would help: > > import sys, random > > def random_junk(number_of_characters): > ? ? tmp = [] > ? ? while number_of_characters: > ? ? ? ? tmp.append(random.randint(0, 127)) > ? ? ? ? number_of_characters -= 1 > ? ? return ''.join(map(str,tmp)) > > if len(sys.argv) < 2: > ? ? sys.exit('Usage:python %s filesizes>'%sys.argv[0]) > > for each_argv in sys.argv[1:]: > ? ? output_file = open(each_argv,'wb').write(random_junk(each_argv)) Sorry, meant def random_junk(number_of_characters): tmp = [] while number_of_characters: tmp.append(chr(random.randint(0, 127))) number_of_characters -= 1 return ''.join(tmp) From newsgroup898sfie at 8439.e4ward.com Tue Mar 4 00:34:53 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Tue, 04 Mar 2008 00:34:53 -0500 Subject: 'normal' shell with curses In-Reply-To: <61c6832e-6897-476c-bcfc-448b7c4387df@d21g2000prf.googlegroups.com> References: <633s5lF24prinU1@mid.uni-berlin.de> <61c6832e-6897-476c-bcfc-448b7c4387df@d21g2000prf.googlegroups.com> Message-ID: <6345brF26560uU1@mid.uni-berlin.de> Miki wrote, on 03/03/2008 11:14 PM: > Hello Michael, > >> I'm trying to print out text in color. As far as I know, curses is the >> only way to do that (or not?). > On unix, every XTerm compatible terminal will be able to display color > using escape sequence. > (Like the one you see in the output of 'grep --color') > > See the shameless plug in http://pythonwise.blogspot.com/2008/03/ansiprint.html > The escape sequence approach is definitely interesting and I'd prefer it to curses if I can make it work. However, I ultimately would like to support other terminals than xterm (especially Windows), that I assume have different ANSI codes. So, two questions: What are the most common terminals that differ in the ANSI codes they use, and how can I detect which of those terminals the program is running on? Where can I find out what codes those terminals use for color? Michael. From mmetz at astro.uni-bonn.de Tue Mar 4 10:10:25 2008 From: mmetz at astro.uni-bonn.de (Manuel Metz) Date: Tue, 04 Mar 2008 16:10:25 +0100 Subject: HTTP keep-alive performance Message-ID: <47CD6661.60705@astro.uni-bonn.de> Hi all, I tried to use the HTTP keep-alive (HTTP/1.1) mechanism for an xmlrpc server/client session. This worked fine, after I found out how to fix the client, see: http://mail.python.org/pipermail/python-list/2004-April/256360.html and also http://mail.python.org/pipermail/python-list/2007-May/442541.html Now, as I said, everything seems to work fine -- except: performance got very bad :-( So, I captured the TCP traffic with wireshark (both, server and client are running on the same machine, 'http://localhost', so its not the network). What I found out is the following: The first remote-call is executed very fast. Then the connection is kept open (I verified that it is closed for HTTP/1.0). But when it comes to the second call, the performance gets bad. The TCP ACK package is sent after ~40ms only, which took ~ < 1ms before for the first call, even for HTTP/1.1. Why is that? So this is a sketch of what's going on: client server ---------- ---------- HEADER --> <-- ACK ~1ms CONTENT --> <-- ACK ~1ms <-- HEADER ACK --> ~1ms [...] response is submitted; connection is NOT closed [...] HEADER --> <-- ACK ~40ms CONTENT --> <-- ACK ~1ms <-- HEADER ACK --> ~40ms [...] response data is submitted It's just a rought timeline to show where the bottleneck is. Has anyone any idea why the acknowledgement messages take sooooo long to be sent??? Manuel From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 25 12:40:40 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 25 Mar 2008 17:40:40 +0100 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> Message-ID: <47e92b07$0$15563$426a34cc@news.free.fr> john s. a ?crit : > On Mar 24, 9:39 pm, "Ryan Ginstrom" wrote: >>> On Behalf Of john s. >>> import os, sys, string, copy, getopt, linecache >>> from traceback import format_exception >>> #The file we read in... >>> fileHandle = "/etc/passwd" >>> srcFile = open(fileHandle,'r') >>> srcList = srcFile.readlines() >>> #yah, a for loop that "iterates" through the file of "lines" >>> for i in srcList: >>> strUsr = string.split(i,":") Erroneous hungarian notation is Bad(tm). And FWIW, the convention is to use all_lower for variable names. (snip consideration about using str.methods instead of string functions etc...) >> How about for starters: >> >> import os >> >> for line in open("/etc/passwd"): NB : this idiom relies on the VM automatically closing files, which is not garanteed on each and every implementation (IIRC, jython won't do it). This is ok for Q&D throwaway scripts targeting CPython, but should not go into production code. >> user, _pwd = line.split(":") > ^----- Ok this one here we are taking a string spliting it > into to variables... > user gets one (the first) and _pwd gets to hold the > "leftovers"? Quite. user gets the first, _pwd gets the second. If you have more than 2 fields (IOW : more than one ':') in the line, it will raise. If you want to make sure this will still work with more than 2 fields, you can use the optional max_split arg: user, rest = line.split(':', 1) >> user_home = os.path.join("/expirt/home", user) >> >>> try: >>> os.makedirs('usrHome' ) >>> except Exception, e: Better to be as specific as possible wrt/ exceptions you want to handle. Remember that some exceptions are better left alone (hint: sys.exit works by raising an exception...) >>> print e >> if os.path.exists(user_home): > ^----- are(n't) exists and os.path.isadir > interchangable? They're not. If you want to be bulletproof, you'll have to use os.path.isdir *and* handle the case where user_home exists and is not a directory. HTH From gagsl-py2 at yahoo.com.ar Wed Mar 19 19:52:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 20:52:14 -0300 Subject: add new csv line References: Message-ID: En Wed, 19 Mar 2008 13:01:08 -0300, Alexandru Dumitrescu escribi?: > Is there a way to add a new line at the beginning of a *.csv file, > line which contain the name of the columns? Once the file was written? You have to create another file, write the headings, and copy the data from the first one. If you are asking how to do that with a csv.Writer object, just call writerow(list_of_column_names) before writing the data itself. -- Gabriel Genellina From tmp1 at viltersten.com Sat Mar 8 20:04:54 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 02:04:54 +0100 Subject: SV: SV: SV: Regarding coding style In-Reply-To: References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: <63guadF27gdujU1@mid.individual.net> >>> If you can't/don't look at the source file, >>> then comments aren't going to help (except >>> in the case of something like docstrings in >>> Python). >> >> I strongly disagree. Now, perhaps we're >> talking about different things, here? >> Usually, in the header file (C++), there >> won't be any source code, except for >> method declarations. A common example: >> >> /** Projects an object from 3D to 2D using >> the method of Alexander The Great. >> \param 3D structure to be projected >> \returns 2D projection >> */ >> public Proj2D get2Dfrom3D(Proj3D param); >> >> The above is, to me, very clear and >> consistent. Not to mention, easily >> handled with e.g. Doxygen to create a >> readable documentation. >> >> I don't see how this is dislikeable. Please >> explain. Perhaps the above IS what you >> ment by "docstrings"? For Java, one has the >> JavaDocs, a great tool, provided one will >> comment each method and variable used. > > The problem is that tools like Doxygen and > JavaDocs generate warnings and errors and > things if everything isn't documented > "completely". So you end up with a lot of > silly boilerplate. > /** > * Get the width of a box > * > * @param box the box > * @returns its width > */ > extern int box_get_width(box box); Oh, yes. This is stupid. I agree with you. If one's supposed to comment, let him comment RIGHT. Otherwise, let it be. Usually, when i comment my code, it's a blessing. If not, i don't comment at all. > You are right that is it often useful to > document what to pass to a method and > what to expect back and that if this is > done well in many cases it isn't > necessary to see the implementation. > But in many other cases it's obvious, and > in other cases it's obvious if you just > look at the source which you've got. I agree. Sometimes, there's a demand from the customer to comment all methods. Then, and then only, i'll go commenting all. But i believe strongly that we think alike on this one. When it's suitable, it should be there. Otherwise - why bother. Right? > The lack of fascism is the big innovation. > It sounds simple but it makes a huge > difference: it's much easier to find (and > keep up to date) the real documentation if > it's not hidden in a forest of bogus > documentation. I couldn't agree with you more on this one! Thank you for an interesting discussion. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From mimi.vx at gmail.com Mon Mar 31 12:53:59 2008 From: mimi.vx at gmail.com (mimi.vx) Date: Mon, 31 Mar 2008 09:53:59 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: On Mar 31, 4:22 pm, rdahlstrom wrote: > So I have a 64 bit Windows 2003 system, running python 2.5.1.1. > > I can import a Windows .dll (msvcrt or whatever) using ctypes, but > when attempting to import another application-specific .dll (tibrv.dll > if anyone is familiar with it), I receive the error WindowsError: > [Error 193] %1 is not a valid Win32 application. > > I know there's a Windows on Windows (wow) which allows 32 bit > processes to run on 64 bit windows - is there a way to work this in > somehow? Maybe I'm barking up the wrong tree? > > Code is simple, and works on 32 bit systems no > > from ctypes import * > #this doesn't work > tibrv = cdll.tibrv > #this does work > msvcrt = cdll.msvcrt all dlls and python must be 32bit or 64bit, no mixed ... From Sandipan at gangopadhyay.com Sat Mar 15 22:52:46 2008 From: Sandipan at gangopadhyay.com (Sandipan Gangopadhyay) Date: Sat, 15 Mar 2008 22:52:46 -0400 Subject: Python for BlackBerry In-Reply-To: <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> Message-ID: <111301c88710$d105bda0$731138e0$@com> Thanks, Mike. This one seems to be for Nokia, particularly S60 and Symbian in general. Does BlackBerry work on Symbian? Let me check. Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of Mike Driscoll Sent: Saturday, March 15, 2008 6:04 PM To: python-list at python.org Subject: Re: Python for BlackBerry On Mar 15, 7:24 am, "Sandipan Gangopadhyay" wrote: > Is there a Python for BlackBerry? Thanks. > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of E-Lo > Sent: Saturday, March 15, 2008 6:03 AM > To: python-l... at python.org > Subject: Python for Palm OS > > Is there any other edition of Python for Palm OS instead of Pippy? > --http://mail.python.org/mailman/listinfo/python-list You might look at Mobile Python. I'm not sure if it works on Blackberry though: http://www.mobilepythonbook.org/ Mike -- http://mail.python.org/mailman/listinfo/python-list From Lie.1296 at gmail.com Sun Mar 30 08:55:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 05:55:10 -0700 (PDT) Subject: License of Python References: Message-ID: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> On Mar 30, 6:42 pm, iu2 wrote: > Hi guys, > > I'd like to use Python in a commercial application. In fact I would > like to write the application entirely in Python. > But I think I wouldn't like telling what language the application is > written in. Why is the reason for that? > The problem is that including Python's license in the binary, which as > I understand is a must do, reveals that the appliation is based on > Python. > > I'll appreciate your advices about this > Thanks > iu2 You can just include it since most users never mess through their program files and most users doesn't even know what Python is, while advanced users could guess that you use Python by seeing the file extension being used (py, pyc, pyo). From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 19:06:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 23:06:54 -0000 Subject: Is this valid ? References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> Message-ID: <13u5rgegehc8u04@corp.supernews.com> On Thu, 20 Mar 2008 15:09:08 +0100, Rolf van de Krol wrote: > John Machin wrote: >> Of course. You can chain comparisons as much as you like and is >> (semi-)sensible, e.g. >> > Hmm, 'of course' is not the correct word for it. Not at all. The Original Poster tried something, and it worked. There were two alternatives: (1) Writing a == b == 2 is valid. (2) In the sixteen years that Python has been publicly available, with tens of thousands or more developers using it, nobody had noticed that Python had a bug in the compiler which incorrectly allowed a == b == 2 until Stef Mientki came along and discovered it. Given those two alternatives, (2) would be very surprising indeed, and so I think "of course" is well justified. That Python allows chaining comparisons this way isn't really surprising. That's a very natural thing to do. What's surprising is that other languages *don't* allow chaining comparisons, but force you to write the inefficient and (sometimes) confusing "(a == 2) and (b == 2)" instead. -- Steven From gagsl-py2 at yahoo.com.ar Tue Mar 18 22:37:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 23:37:15 -0300 Subject: Does __import__ require a module to have a .py suffix? References: <05559d08-2479-4178-830c-adf65dfc733c@s37g2000prg.googlegroups.com> <20080312200254.6859.696992993.divmod.quotient.18440@ohm> Message-ID: En Wed, 12 Mar 2008 18:02:54 -0200, Jean-Paul Calderone escribi?: > On Wed, 12 Mar 2008 12:58:33 -0700 (PDT), George Sakkis > wrote: >> On Mar 12, 12:22 pm, mrstephengross wrote: >> >>> Hi all. I've got a python file called 'foo' (no extension). I want to >>> be able to load it as a module, like so: >>> >>> m = __import__('foo') >>> >> You can use execfile: >> >> foo = {} >> execfile('foo', foo) >> >> Apart from the different syntax in accessing the module globals >> (attributes with __import__ (foo.x) vs dict entries with execfile >> (foo['x'])), there are probably more subtle differences but I can't >> tell for sure. It would be nice if someone more knowledgeable can >> compare and contrast these two appraches. > > Another difference is that when you import a module, its code is > (usually) > only executed once. Each import after the first just returns a reference > to the already-created module object. When you use execfile, the code is > re-evaluated each time. The steps done by import are outlined in this message http://groups.google.com/group/comp.lang.python/browse_thread/thread/7d0ef70c1adc39ac/3882ce35f13ff971#msg_96a590bca5f2be8c The relevant part (citing myself): newmodule = sys.modules[modulename] = ModuleType(modulename) # constructor sets __name__ and a null __doc__ newmodule.__builtins__ = current builtins newmodule.__file__ = filename code = read from filename and compile it exec code in newmodule.__dict__ Apart from sys.modules and __file__, there is another difference, the __builtins__ attribute. It is important: if not present, Python executes the code in "safe mode" where certain operations are disabled (and there is a big performance penalty). -- Gabriel Genellina From dickinsm at gmail.com Wed Mar 12 11:47:41 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 12 Mar 2008 08:47:41 -0700 (PDT) Subject: How about adding rational fraction to Python? References: <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: On Mar 12, 7:20?am, Piet van Oostrum wrote: > But if the answer is incorrect (in the float calculation) the error is > limited. IEEE 754 prescribes that the error should be at most 1 LSB, IIRC. > And then the number of errors is the proper measure. There are two operations here, both of which can introduce error of up to 0.5 ulp (ulp = unit in the last place). Moreover, the second operation (the multiplication) can magnify the error introduced by the first (the division). You're correct that for IEEE 754 binary floating-point arithmetic, (x/y)*y and x will either be equal or differ by exactly 1ulp (except perhaps in rarely-occurring corner cases). But for decimal numbers, (x/y)*y and x could be as much as 5 ulps apart. Mark > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From gagsl-py2 at yahoo.com.ar Wed Mar 26 12:05:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 13:05:55 -0300 Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 11:12:21 -0300, waltbrad escribi?: > Stumbling through Mark Lutz's "Programming Python 3rd", he gives an > example of a program that will automatically configure environment > settings and launch other programs. Then he gives an example of > running this program. On his command line he types: > > C:\...\PP3E>Launcher.py > > and this begins the program. Doesn't work for me. I have to type: > > C:\...\PP3E>python Launcher.py > > Is this a typo on his part or has he configured his settings in such a > way that the command line will automatically associate the extension > with the program? (If so, he didn't mention this in his book). I think it is an option in the installer, to associate or not Python to the .py extension. You could reinstall Python paying attention to the options, or repair the association as described in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1d0fd05b3615057/ -- Gabriel Genellina From terry6394 at gmail.com Sat Mar 1 01:59:56 2008 From: terry6394 at gmail.com (Cyril.Liu) Date: Sat, 1 Mar 2008 14:59:56 +0800 Subject: write float to Excel with pyExcelerator write In-Reply-To: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> References: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> Message-ID: <6d2d06b10802292259o77f84011y88965534cd18999f@mail.gmail.com> I use pyExcelerator to generat Excel files in my project. it works good before I found this bug: run this code: from pyExcelerator import * wb = Workbook() ws = wb.add_sheet("sheet") for i in xrange(1): ws.write(i,0, 10474224.6) wb.save(r'd:\error_float.xls') open d:\error_float.xls with M$ Excle you'll find the number in the cell is -263193.64 not 10474224.6 why? some body help me please. PS: I'm not good at English, I hope you can understand what i said. :) Thx -- About Cyril.Liu ----------------------------------- Cyril ????????????, ??????????????, ??????????????:"????????????????????????" -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Bossy at jouy.inra.fr Fri Mar 28 11:59:59 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 28 Mar 2008 16:59:59 +0100 Subject: finding euclidean distance,better code? In-Reply-To: References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <47ED15FF.5010209@jouy.inra.fr> Gabriel Genellina wrote: > That's what I said in another paragraph. "sum of coordinates" is using a > different distance definition; it's the way you measure distance in a city > with square blocks. I don't know if the distance itself has a name, but I think it is called Manhattan distance in reference of the walking distance from one point to another in this city. RB From sturlamolden at yahoo.no Sat Mar 15 18:11:44 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 15:11:44 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <0a5994c8-1d0f-4b4b-a40c-788af85749b1@i12g2000prf.googlegroups.com> On 15 Mar, 22:43, Guido van Brakel wrote: > > def gem(a): > > g = sum(a) / len(a) > > return g > > > print gem([1,2,3,4]) > > print gem([1,10,100,1000]) > > print gem([1,-2,3,-4,5]) gem( map(float,[1,2,3,4]) ) gem( float(i) for i in [1,2,3,4] ) From bharathv6.project at gmail.com Wed Mar 19 03:28:19 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Wed, 19 Mar 2008 12:58:19 +0530 Subject: automatically doing some cleaning-up by the process when the systems shuts down In-Reply-To: <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> Message-ID: <2613171a0803190028s4cc626apd2cd675a18e25799@mail.gmail.com> handling SIGTERM allowed me to do cleaning up while the system shuts down but as i mentioned previously how can my process know if the system was not shut down properly previously On Wed, Mar 19, 2008 at 12:36 PM, bharath venkatesh < bharathv6.project at gmail.com> wrote: > hi , > thanks Gabriel ... but r u sure if it is SYSTERM ?or is it SIGTERM ? > I am not aware of any SYSTERM signal > .. if it is SYSTERM please tell me more about it .. as google search is > not helping .. > > and also is there some way for my process which is running as a daemon to > know that system was not shut down properly previously ....eg a power > failure .. so that my program can do necessary steps if cleaning up is not > done during its last termination > > On Wed, Mar 19, 2008 at 8:25 AM, Gabriel Genellina > wrote: > > > En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh > > escribi?: > > > > > my programs runs as daemon and it does some logging .. when > > system > > > shuts down .. which may be done manually . i want my process do some > > > cleaning up automatically such as writing in to the log file when the > > > process terminats before the system shuts down > > > > handling the SYSTERM signal? > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Tue Mar 4 09:50:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 09:50:16 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD61A8.4000104@holdenweb.com> Peter Otten wrote: > Steve Holden wrote: > >> What I will repeat, however, is that while there is a *slight* >> difference is semantics between >> >> s = "some string" >> s1 = s >> >> and >> >> s = "some string" >> s1 = copy.copy(s) >> >> that difference is only to ensure that s and s1 point to different >> copies of the same string in the latter case, whereas in the former case >> s and s1 point to the same string. > > No, both "point" to the same string: > >>>> import copy >>>> s = "some string" >>>> s1 = s >>>> s1 is s > True >>>> s2 = copy.copy(s) >>>> s2 is s > True > > copy.copy() is just an expensive no-op here. > I suppose wiht strings being immutable there is no need for copy.copy() to actually return anything other than its argument for a string. Thanks for pointing that out. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:36:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:36:49 -0300 Subject: Where can I find : References: Message-ID: En Sun, 30 Mar 2008 00:15:59 -0300, pythonnubie escribi?: > Does anyone know where I can find either a book or a website that > explains beginning python by actually building a project line by > line and explaining it indepth . I am primarily interested in > understading flowcontrol as well as syntax . See the section about Learing Python in the wiki: http://wiki.python.org/moin/BeginnersGuide > If it was related to netwoprking then that would be a great > addition although not required because that is my primary field of > interest . Many books on Python have some chapters on networking, and there are even whole books like Python Web Programming by Steve Holden. -- Gabriel Genellina From larry.cebuala at gmail.com Mon Mar 17 02:37:04 2008 From: larry.cebuala at gmail.com (Larry) Date: Sun, 16 Mar 2008 23:37:04 -0700 (PDT) Subject: writing to a binary file without intervening spaces Message-ID: Dear all, I need to write integer values to a binary file that will be read by another application, specifically ENVI. I want to write these values without intervening spaces between values. For example: My data is a = [23, 45, 56, 255]. My desire output is: 234556255, of course in binary file representation already. I tried to make one using write after pack method of struct module, but because of spaces I got incorrect results. ENVI asks what data type I have and from that gets a sequence of bytes to "form" the data. With spaces, I think this gave me the problem. Thanks. From me at metsger.com Mon Mar 3 12:06:28 2008 From: me at metsger.com (Ethan Metsger) Date: Mon, 03 Mar 2008 12:06:28 -0500 Subject: Decorators and buffer flushing References: <535e65ee-dcae-4767-a74b-8ed17ee834c0@o10g2000hsf.googlegroups.com> Message-ID: Hi, Gabriel. I missed this message initially; I apologize for not responding sooner. On Thu, 28 Feb 2008 18:53:28 -0500, Gabriel Genellina wrote: >> I can reproduce the issue in the console. I'm not convinced it's >> actually >> a bug, unless for some reason the interpreter is preventing a buffer >> flush. > > Try starting the interpreter with python -u xxx.py (-u = unbuffered) but > I don't really think this might be the cause. Are you sure the code > actually says sys.stdout.flush() and not sys.stdout.flush? As I mentioned in another message, I haven't had any luck with adding '-u' to the invocation of the interpreter. I am sure I'm not looking at the callable object rather than calling flush(). >> sys.stdout.write ("%s" % (self.name.ljust(30),)) > > Usually written as: > sys.stdout.write("%-30s" % self.name) Thanks for the tips! [...] >> Is it possible that flushing is prohibited until __exit__ is called? > > I don't think so... What's your platform/OS? I'm running Ubuntu Feisty with Python 2.5.1: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Try to post a minimal example showing the problem - copy & paste it, > don't retype. Maybe in the process of reducing your code to find the > minimal example, you find the problem yourself. The minimal example is a little long, but I think in the end I figured out what was happening. The initial build step took the longest amount of time to complete, but the other steps were nearly instantaneous. So the post-build '.' would appear, and the very fast run of the other steps made it appear as though everything was being buffered when it wasn't. Adding in a short delay (time.sleep(0.05) seemed to work) helped demonstrate that the data actually were unbuffered. > Are you aware of the existing framework for unit tests? the unittest > module? Yes. I haven't investigated its uses in this context due to the constraints of the legacy system and general inertia. I'm trying to duplicate functionality while addressing certain annoyances with the previous system. Thanks again for your help! Best, Ethan -- Ethan Metsger http://uppertank.net/ethanm/ From cruxic at gmail.com Sat Mar 8 11:25:06 2008 From: cruxic at gmail.com (Cruxic) Date: Sat, 8 Mar 2008 08:25:06 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Message-ID: <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> On Mar 7, 11:20 am, Raymond Hettinger wrote: > [Cruxic] > > > Is it possible to get an object out of a set() given another object > > that has the same hash code and equality (__hash__() and __eq__() > > return the same)? > > Yes, but it requires an indirect approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299 > > Raymond That's a clever work around. Thanks, Raymond. Clearly you had a need for this. Do you feel it's a common need that should be submitted as a Python feature request? To me it seems like such a simple thing that would increase the general utility of the set class. I suppose I could start another thread like "feature request: New method for set - get_equivalent". From kyosohma at gmail.com Thu Mar 6 16:58:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Mar 2008 13:58:16 -0800 (PST) Subject: system32 directory References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: <85b740fb-3231-494f-bdb4-bd23f9e46de5@8g2000hse.googlegroups.com> On Mar 6, 3:49 pm, Trent Mick wrote: > > I was aiming to figure out if the standard modules shipped with Python > > could do this already before I started using 3rd party libraries. Thanks. > > You could also manage it with the ctypes module, if you consider that > standard: it is in the python.org and ActivePython distros as of Python 2.5. > > Cheers, > Trent > > -- > Trent Mick > trentm at activestate.com As I understand it, ActivePython includes PyWin32 by default, unlike the "Official" Python distro. Mike From renesd at gmail.com Sun Mar 30 06:44:18 2008 From: renesd at gmail.com (=?ISO-8859-1?Q?Ren=E9_Dudfield?=) Date: Sun, 30 Mar 2008 21:44:18 +1100 Subject: ANN: pygame 1.8 released Message-ID: <64ddb72c0803300344q5ee42d81xdb4a7695adef759b@mail.gmail.com> Hello, a new version of pygame is out. http://www.pygame.org/ Pygame is a set of Python modules designed for writing games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Pygame is highly portable and runs on nearly every platform and operating system. http://www.pygame.org/wiki/about Silliness built in. Does not require OpenGL. Multi core CPUs can be used easily. Uses optimized C, and Assembly code for core functions. Comes with many Operating systems. Truly portable. It's Simple, and easy to use. Many games have been published. You control your main loop. Does not require a GUI to use all functions. Fast response to reported bugs. Small amount of code. Modular. http://pygame.org/whatsnew.shtml Some of the changes... * pygame.mask for pixel perfect collision detection * pygame.scrap for clipboard support * new and improved sprite groups, including layers, automatically selecting fastest update mode(full screen or dirty rect updates), and blend modes... * blending support for filling and blitting surfaces. ADD, SUB, MULT, DIV etc. * saving surfaces as jpeg and png * buffer access for Surface and Sound objects * numpy, and numeric support for pygame.surfarray and pygame.pixelarray * PixelArray, which can be used instead of numpy - without the dependency. * smooth scale function written in mmx assembly with C fallback. * More functions release the GIL for multithreaded use. * lots of speed ups to many functions via better python wrapping. * color thresholding, bounding box finding for images, and surface averaging. * massive documentation updates (which have been available on the website for a while already). * pygame.time.Clock.tick() is more cpu friendly. * updates to example programs. * new windows, and mac installers. * hardware acceleration updates for overlays and opengl. * porting work to different platforms. * heaps of bug fixes including SRCALPHA blitting fixes, 64bit fixes, sound system fixes. Plus there have been lots of changes to SDL itself since the last pygame release. http://www.libsdl.org/release/changes-1.2.html. * lots of stuff really... but those are some of the nice things. Read the what's new page for full details http://pygame.org/whatsnew.shtml cheers, From martin at v.loewis.de Fri Mar 21 17:01:07 2008 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 22:01:07 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E42213.50208@v.loewis.de> > eval() somehow decoded the passed expression. No question. It did not > use 'ascii', nor 'latin2' but something else. Why is that? Why there is > a particular encoding hard coded into eval? Which is that encoding? (I > could not decide which one, since '\xdb' will be the same in latin1, > latin3, latin4 and probably many others.) I think in all your examples, you pass a Unicode string to eval, not a byte string. In that case, it will encode the string as UTF-8, and then parse the resulting byte string. Regards, Martin From mail at timgolden.me.uk Sat Mar 15 08:08:21 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 15 Mar 2008 12:08:21 +0000 Subject: Spaces in path name In-Reply-To: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> Message-ID: <47DBBC35.8060902@timgolden.me.uk> joep wrote: > I had the same problem recently with subprocess.popen, when there is a > space in the executable and a space in an additional argument as in > the acrobat example. I finally found a past thread in this news group > that explained that you have to use two (2) leading double quotes, and > as on the command line all arguments with spaces have to be quoted. Thanks for this, joep. I've added a how-do-i to my website covering the different cases, I hope. This comes up often enough that maybe next time we can just point someone there first time! TJG http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-space-in-it.html From rschroev_nospam_ml at fastmail.fm Sat Mar 29 05:11:28 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 29 Mar 2008 10:11:28 +0100 Subject: finding euclidean distance,better code? In-Reply-To: <13ur5mq7fugqgc1@corp.supernews.com> References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> Message-ID: <4JnHj.3124$e%6.335@newsfet15.ams> Steven D'Aprano schreef: > On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > >> Gabriel Genellina wrote: >>> That's what I said in another paragraph. "sum of coordinates" is using >>> a different distance definition; it's the way you measure distance in a >>> city with square blocks. I don't know if the distance itself has a >>> name, but >> I think it is called Manhattan distance in reference of the walking >> distance from one point to another in this city. > > You know, there are other cities than Manhattan. Some of them even have > streets and blocks. I'm not sure what your point is. The name of the distance happens to be Manhattan distance (or taxicab distance, rectilinear distance, L1 distance, city block distance; see http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid point. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From rodmena.com at gmail.com Mon Mar 17 01:27:24 2008 From: rodmena.com at gmail.com (Farsheed Ashouri) Date: Sun, 16 Mar 2008 22:27:24 -0700 (PDT) Subject: Py2exe and Multi Treading problem. References: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> <47d8307c$0$12126$3b214f66@aconews.univie.ac.at> Message-ID: <1eaf7012-7c2c-4377-8f16-c2d33115a172@d62g2000hsf.googlegroups.com> On Mar 12, 10:35 pm, Thin Myrna wrote: > Farsheed Ashouri wrote: > > NO it dont work. If I remove threading part, it works like a charm. > > Any Idea? > > Of course it does then. Try to join the thread or do something else to > prevent the non-threading part to exit prematurely. > > HTH > Thin Thanks, I got it. Very useful for me. Cheers. From tim.arnold at sas.com Wed Mar 26 15:52:42 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 26 Mar 2008 15:52:42 -0400 Subject: first interactive app Message-ID: hi, I want to write a tiny interactive app for the following situation: I have books of many chapters that must be split into volumes before going to the printer. A volume can have up to 600 pages. We obviously break the book into volumes only at chapter breaks. Since some chapters make a natural grouping, we want some human interaction for where the volume breaks occur. Not having experience with interactive apps, I'm asking for advice about how to go about it. The data I start with is just a dictionary with chapter name = ending page number. I figured I would first show where the volumes would break with no human interaction, with the begin and ending chapter names/pagenumbers for each volume. >From here I thought about having a slider for each volume, but the number of volumes could change during the session. Or maybe I should just ask 'enter the ending chapter for the first volume' and recalculate, etc until all volumes are defined. Any ideas on a simple interface for this? thanks, --Tim From lialie at gmail.com Wed Mar 26 12:21:15 2008 From: lialie at gmail.com (lialie) Date: Thu, 27 Mar 2008 00:21:15 +0800 Subject: Problem with write binary data to OLE field in Access Message-ID: <47EA77FB.3080706@gmail.com> Hi~ I would like to save images in OLE field in Microsoft Access. It writes the binary data which read from an JPEG/BMP file. But seems I meet an encoding problem. The following code demos that. Any sugguestion? --------------------------------------------------------------------------- import win32com.client as wc conn = wc.Dispatch(r'ADODB.Connection') recordset = wc.Dispatch(r'ADODB.RecordSet') dsn = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source="test.mdb";' conn.Open(dsn) print conn k = recordset.Open('[tblImageDataTypes]', conn, 1, 3) #recordset.AddNew() #recordset.Fields('Field3_GENERAL').AppendChunk(open('tt.jpg', 'rb').read()) #recordset.Update() #print ">>> Actual Size: ", recordset.Fields('Field3_GENERAL').ActualSize recordset.MoveFirst() kk = recordset.Fields('Field3_GENERAL').GetChunk( recordset.Fields('Field3_GENERAL').ActualSize) print len(str(kk).decode('utf-16')) print len(open('tt.jpg', 'rb').read()) recordset.Close conn.Close() ############################### One of the results: the length of original file is : 2598 the actual size of the field is: 3658 the length decode from the chunk is: 1829 I try to write some text files into the filed and read it out, it is OK. Windows XP sp2; Python 2.4.4; Pywin32 210; Microsoft Access 2002 --------------------------------------------------------------------------------------- Regards, lialie From http Sun Mar 23 02:09:07 2008 From: http (Paul Rubin) Date: 22 Mar 2008 23:09:07 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> Message-ID: <7x4payug3g.fsf@ruckus.brouhaha.com> John Nagle writes: > What a mess. That's some professor inventing his very own variation on > predicate calculus and writing a book using his own notation and terminology. I thought it was all pretty standard. It's the same notation I see in other PL stuff. > There's no sign of footnotes or references to prior work. Maybe he'll add that. It's a work in progress. > Back when I was doing program verification work, we used to refer to > stuff like that as the "logic of the month club". I thought the book was pretty good and I've learned quite a bit from the parts I've read. Also, the author is one of the big cheeses in the SML world, if that matters. From noname9968 at gmail.com Sun Mar 16 15:46:01 2008 From: noname9968 at gmail.com (Alex) Date: Sun, 16 Mar 2008 22:46:01 +0300 Subject: Which way to access Scintilla Message-ID: <47DD78F9.8090306@gmail.com> There are several ways to use Scintilla in Python, the ones described at http://scintilla.sourceforge.net/ScintillaRelated.html are: -through wxPython -pyscintilla is the original Python binding for Scintilla's default GTK 1.x class. Includes some additional support, such as native printing on Windows. The binding is hand-written rather than auto-generated from the Scintilla.iface file. -pygtkscintilla is a Python binding for gtk1.x scintilla that uses gtkscintilla instead of the default GTK class. -pyscintilla2 is a Python binding for GTK 2.x scintilla that uses gtkscintilla2. I'm not using any of the libraries GTK 1.x, GTK 2.x or WxPython for GUI (always used Tkinter), but I want to use Scintilla so I wonder which way would have less overhead. First, loading of an additional library would (I think) slow down startup and operating time of program, plus there can be additional complexity of use. I also want to embed Scintilla in Tkinter-created window (create the rest of the GUI in Tkinter), or rather, I want to know if that's possible at all. Any suggestions are appreciated. Thanks From nagle at animats.com Sun Mar 23 16:00:09 2008 From: nagle at animats.com (John Nagle) Date: Sun, 23 Mar 2008 13:00:09 -0700 Subject: Testing for an empty dictionary in Python In-Reply-To: References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <47e6b485$0$36325$742ec2ed@news.sonic.net> Brian Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > John Nagle wrote: >> What's the cheapest way to test for an empty dictionary in Python? >> >> if len(dict.keys()) : >> >> is expensive for large dictionaries, and makes loops O(N^2). >> >> John Nagle > > if dict: Cute. I'd already figured out that len(dict) works, which is probably better than len(dict.keys() > 0 which requires creating a list. John Nagle From miki.tebeka at gmail.com Fri Mar 21 11:26:26 2008 From: miki.tebeka at gmail.com (Miki) Date: Fri, 21 Mar 2008 08:26:26 -0700 (PDT) Subject: Distributing Python Apps on Linux\BSD References: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> Message-ID: <9290c7b1-3e51-46fe-96e7-6c2ebf4f5b77@u10g2000prn.googlegroups.com> Hello, Disclaimer: I'm not an expert on the subject. > Setuptools and friends seem to be focused on distributing modules, I'm > at the other end of the scale where I want to distribute an entire > application so that an Administrator can run a single install and have > a fully operational product. A key requirement is that I want the > application to fit in with what and admin would expect an application > to look like at the system level i.e site-packages like structures > aren't suitable. You do that with distutils as well. > So far I've thought of using a configure script and make which would > call some custom python installer script to do the actual install. It > fits in nicely with what I want to achieve but are there any better > options out there, how are others doing the same thing? Every distro flavor has it's own installer: apt/deb, rpm, port, ... On Windows you can use one of the free installer (InnoSetup and friends). HTH, -- Miki http://pythonwise.blogspot.com From alex.pulver at gmail.com Wed Mar 12 14:19:05 2008 From: alex.pulver at gmail.com (Alex) Date: Wed, 12 Mar 2008 11:19:05 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? Message-ID: Hi all, The subject says pretty much all, i would very appreciate an answer. I tried to search the various forums and groups, but didn't find any specific answer... Thanks, Alex. From godzillaismad at gmail.com Thu Mar 20 07:47:00 2008 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 20 Mar 2008 04:47:00 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> Message-ID: <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Thanks Ross and John for your help. I apologise for the code I posted earlier not being the full picture of what I was trying to achieve. I had instantiated multiple instances of elapseTime class and each of them gets called approximately the same time. Below is the updated code: import time import thread import Queue printq = Queue.Queue(0) class elapseTime: def __init__(self, name=''): self.name = name self.timeStamp = None self.checkTimeFlag = False thread.start_new_thread(self.elapsedTime, ()) def setTime(self, state): if state == 1: self.checkTimeFlag = True self.timeStamp = time.clock() else: self.checkTimeFlag = False def elapsedTime(self): prevTime = time.clock() while True: curTime = time.clock() timeDiff = (curTime - prevTime) if timeDiff < 0.0: printq.put_nowait('time.clock() has gone backward!!! Time Diff '+str(timeDiff)) if self.checkTimeFlag: if (curTime - self.timeStamp) > 1.0: printq.put_nowait(self.name+", actual Elapsed Time"+str(round(curTime-self.timeStamp, 3))) self.checkTimeFlag = False prevTime = curTime time.sleep(0.05) def printmgr(): while True: print printq.get(True) # Print thread thread.start_new_thread(printmgr, ()) objList = [] for i in range(10): objList.append(elapseTime("obj"+str(i))) while True: for i in range(len(objList)): objList[i].setTime(1) time.sleep(10) print When I run the above code long enough in the PC I see the 'time.clock() has gone backward!!!' statement being printed once in a while. I have been reading a thread about invoking time.clock() at close proximity caused the 'time warp' problem. John, the PC experiencing this problem is a single core Intel Celeron 1GHz, XP SP2. The PC at home is a AMD Dual Core XP SP2. From jeff at schwabcenter.com Thu Mar 13 00:33:52 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 12 Mar 2008 21:33:52 -0700 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: References: Message-ID: Alex wrote: > The subject says pretty much all, i would very appreciate an answer. I > tried to search the various forums and groups, but didn't find any > specific answer... I'd like an answer to this, too. In Perl, I mostly used it for one-liners, when a variable needed to be initialized to some non-default value; for example, perl -ple 'BEGIN { $sum = 42 } $sum += $_'. From jeff_barish at earthlink.net Thu Mar 6 11:18:18 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Thu, 06 Mar 2008 09:18:18 -0700 Subject: for-else References: Message-ID: Terry Reedy wrote: > A for-loop is equivalent to a while loop with the condition 'iterator is > not exhausted'. ?So do_else when that condition is false -- the iterator > is exhausted. I think that this is the most important statement in this thread. As others have expressed, I too found for-else surprising when I first encountered it. It made sense to me when I analogized for with if: for x in range(5): do_something() else: do_something_else() means do_something repeatedly when the condition (iterator not exhausted) is true and do_something_else when the condition is not true, just as if condition: do_something() else: do_something_else() means do_something once when the condition is true and do_something_else when the condition is not true. I find it elegant that Python does not introduce additional keywords to deal with situations that are comparable. -- Jeffrey Barish From magdoll at gmail.com Sun Mar 16 22:29:36 2008 From: magdoll at gmail.com (Magdoll) Date: Sun, 16 Mar 2008 19:29:36 -0700 (PDT) Subject: psyco class question Message-ID: <1e242f71-357c-4005-9f12-94acd2eddef6@e6g2000prf.googlegroups.com> I can't find a psyco mailing list that I can directly ask to (so point me to it if there is one), so I'm posting it here. I know very little about how types and classes work in python and this is probably why I'm having trouble. I wrote a class inheriting pysco.classes, and the class structure is like this: class Node(psyco.classes.psyobj): def __init__(self,a,b,c...): self.a = a self.b = b etc.... this all works very well and speeds up the code tremendously. But when I try to pickle it: from cPickle import * s = Node() f = open('test.pickle','w') dump(s,f) f.close() It gives me errors like: Traceback (most recent call last): File "y.py", line 13, in dump(a,f) File "/usr/lib/python2.5/pickle.py", line 1362, in dump Pickler(file, protocol).dump(obj) File "/usr/lib/python2.5/pickle.py", line 224, in dump self.save(obj) File "/usr/lib/python2.5/pickle.py", line 306, in save rv = reduce(self.proto) File "/usr/lib/python2.5/copy_reg.py", line 70, in _reduce_ex state = base(self) TypeError: default __new__ takes no parameters If I embed Node in some other structures (I actually used it as nodes in a networkx.XGraph()), the dumping doesn't give me errors but when I load the pickle I get errors saying that the state is not a dictionary. What is the cause of the error? Is it because psyco classes uses its own class types that can't be pickled or do I need to override something? Thanks in advance. Magdoll From gagsl-py2 at yahoo.com.ar Tue Mar 25 16:08:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 17:08:09 -0300 Subject: setattr what is the parent object? References: <005601c88ea8$9a936520$0600a8c0@laptop> Message-ID: En Tue, 25 Mar 2008 15:46:57 -0300, Jules Stevenson escribi?: > I'm trying to use setattr to dynamically name and layout gui wx widgets, > this is all fine and dandy until I've run up against something where I > simply don't know what the object is, please see the amended **don't > know** > in the following code. > > > class MyFrame2(wx.Frame): > > def __do_layout(self, mayaVars): > > main_boxSizer = wx.BoxSizer(wx.VERTICAL) > > for pDisplay in range(len(mayaVars.primary)): > > setattr=(**don't > know**,"r_gridBagSizer_"+mayaVars.primary[pDisplay], > wx.GridBagSizer(vgap=0, > hgap=0)) > > > Without all the dynamic gumpf, the statmement looks like this: > > > r_gridBagSizer = wx.GridBagSizer(vgap=0, hgap=0)) > > > All the other UI elements are created on 'self' but the sizers don't > seem to > 'belong' to anything - what should I use when this is the case? You don't have to save the sizer anywhere, but you have to call container.SetSizer(the_sizer) -- Gabriel Genellina From pavlovevidence at gmail.com Sat Mar 15 19:03:13 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Mar 2008 16:03:13 -0700 (PDT) Subject: Python and 3D References: Message-ID: <8a5eb3d6-7203-4d5e-8812-2c606e2bdf44@8g2000hsu.googlegroups.com> On Mar 15, 4:09 pm, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs What do you mean by "manipulate". There are lots of ways to manipulate 3D objects; can you be more specific? Carl Banks From sam_spam_cat at verizon.net Sat Mar 29 19:09:28 2008 From: sam_spam_cat at verizon.net (Sam the Cat) Date: Sat, 29 Mar 2008 16:09:28 -0700 Subject: html DOM Message-ID: Is there a package that would allow me the same or similar functionality for modifying html code via the DOM model as I have in JavaScript ? I'd like to parse an html file, then modify it and save the result. I am not trying to do this online, rather I would like to do this on a batch of files stored on my hard drive. I have found several packages that allow me to parse and dissect html but none that allow me to modify the object and save the results -- perhaps I am overlooking the obvious From mail at timgolden.me.uk Tue Mar 25 09:44:04 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Mar 2008 13:44:04 +0000 Subject: Reading new mail from outlook In-Reply-To: <315315.36624.qm@web50108.mail.re2.yahoo.com> References: <315315.36624.qm@web50108.mail.re2.yahoo.com> Message-ID: <47E901A4.6020108@timgolden.me.uk> SPJ wrote: > I am trying to create new tickets in the ticketing system using python. When I > receive new email from a particular address, I have to trigger the python script > and parse the mail in required format. > > The main hurdle here is, how to invoke the script on arrival of new mail? I > checked the outlook settings and found that it supports only microsoft VB script > and Jscript. Is there any other way? I mean, if I make a daemon, how will it be > notified of new mail? Is there any python module that does this? > > I am not sure if this is the right place to ask this, since it is also a > microsoft related question. But any help is appreciated. Outlook does have some events in its automation interface (which you can handle from within Python by using win32com.client.DispatchWithEvents) but if an immediate response weren't critical it's probably slightly easier to schedule a job to interrogate the mailbox every so often and harvest any new emails. Depends on your particular need. TJG From tms at zeetix.com Mon Mar 17 08:48:38 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Mon, 17 Mar 2008 08:48:38 -0400 Subject: python-list Metaquestion Message-ID: <00d901c8882d$38c77240$0200a8c0@TMSMAIN> I continue to receive emails, addressed to python-list-bounces at python.org, with subject: "Re: Your message to Python-list awaits moderator approval", which read: > Your mail to 'Python-list' with the subject > > (no subject) > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Message has a suspicious header I'm happy to adjust my headers in whatever way is needed, if I know what the problem is. Is there FAQ somewhere that tells me what I should change? Thx, Tom From castironpi at gmail.com Wed Mar 5 21:06:23 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 18:06:23 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> Message-ID: <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> On Mar 5, 4:25?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote: > > Classes and modules are really similar. ?In Python they're really > > *really* similar. > > Yes they are. > > Both are namespaces. The very last line of the Zen of Python says: > Namespaces are one honking great idea -- let's do more of those! Where to begin? From matt at vazor.com Fri Mar 14 18:43:31 2008 From: matt at vazor.com (Matt) Date: Fri, 14 Mar 2008 15:43:31 -0700 (PDT) Subject: How to get number of compressed bytes from GzipFile Message-ID: Hi all, I'm using the gzip module to return a gzip response from a small python httpserver. I'd like to know the number of bytes written to the underlying socket, but it doesn't seem to support the tell() function. This works fine for a file: [15:39:51] mattb ~ $ cat mygzip.py #!/usr/bin/env python import os import gzip f = open("tmp.gz", "wb") gz = gzip.GzipFile('', 'wb', 6, f) for i in xrange(100): gz.write('abcdefg' * 100) gz.flush() print gz.tell() print f.tell() gz.close() f.close() print os.stat('tmp.gz').st_size [15:40:17] mattb ~ $ ./mygzip.py 70000 141 151 So I wrote 70000 raw bytes which gets compressed to 151 bytes -- I guess the 10-byte difference is a gzip header or something? Is there any way to get this same functionality when using a socket? thx Matt From http Sun Mar 23 00:39:13 2008 From: http (Paul Rubin) Date: 22 Mar 2008 21:39:13 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <7xprtmnjf2.fsf@ruckus.brouhaha.com> jmDesktop writes: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. I guess I should ask what is being taught and what the interests of the students are. I.e. is it a programming class for students interested in programming? If yes, then sure, why not Python. If not, then hmmm. From bbxx789_05ss at yahoo.com Tue Mar 18 00:18:37 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 17 Mar 2008 21:18:37 -0700 (PDT) Subject: ord function problem from newbie References: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> Message-ID: David.J.Anderso... at gmail.com wrote: > I convert all to lowercase, > > import string > > small = string.lower(name) > print "Here is the calculated value:" > > print small > for ch in small: > v = ord(ch)-96 > print v > I don't know if you are using an out of date book or what, but generally you are not going to be importing string. For example, my_str = "HELLO" small = my_str.lower() print small --output:-- hello From rbossy at jouy.inra.fr Sat Mar 8 09:09:20 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 08 Mar 2008 15:09:20 +0100 Subject: DOM parsing not working! In-Reply-To: <2b54d4370803071639w30912a60i4bc93981533ecfbb@mail.gmail.com> References: <2b54d4370803071639w30912a60i4bc93981533ecfbb@mail.gmail.com> Message-ID: <1204985360.47d29e10915a6@www.jouy.inra.fr> Quoting Mike D <42flicks at gmail.com>: > Hello, I've spent the morning trying to parse a simple xml file and have the > following: > import sys > from xml.dom import minidom > > doc=minidom.parse('topstories.xml') > > items = doc.getElementsByTagName("item") > text='' > for i in items: > t = i.firstChild > print t.nodeName > if t.nodeType == t.TEXT_NODE: > print "TEXT_NODE" > print t.nodeValue > text += t.data > > print text > > I can't figure out how to print the text value for a text node type. There > must be something obvious I'm missing, any suggestions? Yes quite a trivial thing. t is assigned to the first child node of which, in your example, is a text node containg just a newline. It will be shown if you replace your print statements with something like: print 't.nodeValue:', t.nodeValue, '### end of t.nodeValue' ... print 'text:', text, '### end of text' What is that you're trying to do? Do you want to extract all text nodes inside ? RB From gherron at islandtraining.com Sat Mar 22 11:51:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 22 Mar 2008 08:51:52 -0700 Subject: NameError: name 'guess' is not defined In-Reply-To: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> References: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> Message-ID: <47E52B18.9090500@islandtraining.com> willkab6 at gmail.com wrote: > I am very new to both programming and Pyhton and while trying to do > some practice using A byte of python an Error pops up on the IDLE > shell. I am using windows XP. PLease see below. > while running: > guess = int(raw_input('Enter an integer : ')) > > if guess == number: > print 'Congratulations, you guessed it.' > running = False # this causes the while loop to stop > elif guess < number: > print 'No, it is a little higher than that.' > else: > print 'No, it is a little lower than that.' > else: > print 'The while loop is over.' > # Do anything else you want to do here > > print 'Done' > > After typing the above as the book says, I get the error NameError: > name 'guess' is not defined > What Am I doing wrong? > You are not describing the problem accurately. The above program would not even start *running*. It would produce an IndentationError: expected an indented block on the second line. If you did manage to get the to get the program entered with correct indentation, it would gave a NameError on the variable named running not on guess. So now: Tell us what really happened, and perhaps your question can be answered. Hint: Each of the lines that end in a colon start a block of code which must be indented. Any variable used in a calculation must be given a value *before* the calculation is carried out. I think this might be what you were trying to do (untested): number = 12345 # Defines the number variable before using while True: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' break # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that.' else: print 'No, it is a little lower than that.' print 'The while loop is over.' print 'Done' Gary Herron From castironpi at gmail.com Wed Mar 12 02:01:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:01:54 -0700 (PDT) Subject: base-class call decorator Message-ID: <7b190526-9eb5-43b5-8f2a-7d1f5ac1ea58@u69g2000hse.googlegroups.com> If you had this, class KType( BaseType ): def __init__( self, *ar, **kwar ): self.setProp= True BaseType.__init__( self, *ar, **kwar ) a lot, and wanted a decorator, what would it be? What are the pros and cons? class KType( BaseType ): @basecall def __init__( self ): self.setProp= True What about calling first vs. last, base class order, certain bases, etc.? When is it easier to do without? From dave_mikesell at fastmail.fm Fri Mar 7 23:04:47 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Fri, 7 Mar 2008 20:04:47 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> On Mar 7, 10:31 am, "K Viltersten" wrote: > I've been recommended reading of:http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i > need to get elaborated. > > 1. When writing English, Strunk and > White apply. If your code needs so much descriptive prose that you have to consult Strunk and White, refactor it to be more clear. Excessive comments are the hobgoblin of overly complex and/or sloppy code. From stef.mientki at gmail.com Mon Mar 10 18:40:27 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 10 Mar 2008 23:40:27 +0100 Subject: wxPython: some help with Drag&Drop In-Reply-To: References: Message-ID: <47D5B8DB.1020402@gmail.com> Eric von Horst wrote: > Hi, > > I need some advice on Drag&Drop. > > What I want to achieve is the following: > - I have a window that is divided in two : on the left hand I > have a wx.TreeCtlr and on the other hand a wx.StaticBitmap > > I want to be able to drag an item from the tree onto the static > bitmap. > > I know how to do drag&drop in a treeCtrl but is there a way that I can > make the bitmap detect that something has been dropped on it? > > I would only need to know the name of the tree obj that was dropped on > the bitmap (and the location) > > Any help much appreciated > > As Mike said it might be better for you (and others bumping into this problem), if you would post your question in the wxPython list. Anyway here is mine solution, dragging from a tree on the left, either on the tree itself or on a visual disign canvas right of the splitter: def OnEndDrag2(self, event): item = event.GetItem() if item: # this is not a very elegant way, but it works # we compare the event-position with the splitter sash-position # to determine if it's a tree-drop or a graphical-canvas-drop w = self.parent_form.Splitter.GetSashPosition() x, y = event.GetPoint() if x > w: self.Insert_Lib_Object ( self.drag_item, x-w, y+26 ) else : cheers, Stef > > Erik > > From sjdevnull at yahoo.com Mon Mar 3 14:20:12 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 3 Mar 2008 11:20:12 -0800 (PST) Subject: Delete hidden files on unix References: Message-ID: <150e82e0-f142-4567-883f-9f0caedb9675@i12g2000prf.googlegroups.com> On Mar 3, 9:38 am, subeen wrote: > On Mar 3, 6:13 pm, Philipp Pagel > wrote: > > > > > loial wrote: > > > How can I delete hidden files on unix with python, i.e I want to do > > > equivalent of > > > rm .lock* > > > Here is one way to do it: > > > import os, glob > > for filename in glob.glob('.lock*'): > > os.unlink(filename) > > > Alternatively, you could also do this: > > > import os > > os.system('rm .lock*') > > > cu > > Philipp > > > -- > > Dr. Philipp Pagel > > Lehrstuhl f. Genomorientierte Bioinformatik > > Technische Universit?t M?nchenhttp://mips.gsf.de/staff/pagel > > Another way is to execute the linux command directly :) > Check here:http://love-python.blogspot.com/2008/02/execute-linux-commands-in-pyt... > Note that that can get dangerous with shell expansions: e.g. (don't run in a directory with files you want to keep!) import os open("--help", "w") os.system("rm *help") will actually run "rm --help", printing the help for rm rather than removing the file named "--help". There are a lot of security implications to allowing this kind of shell expansion of commands. The system-call method with os.unlink is easier to get right. From tmp1 at viltersten.com Sat Mar 1 08:36:42 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 14:36:42 +0100 Subject: SV: SV: Running test01.py under Windows (basic level) In-Reply-To: References: <62os33F2352veU1@mid.individual.net><62pfi6F244l0bU1@mid.individual.net> Message-ID: <62t3geF24ts4hU1@mid.individual.net> >>>> def bloppA (): >>>> print "a very advanced piece of code" >>> >>> go to File -> Open, open your saved file, >>> and use the Run menu (or press F5). >> >> When i try that i get this. >> >>>>> ====== RESTART ======= >>>>> >> >> And nothing more. Do i use wrong "print"?! > > You *defined* a function, but aren't *executing* > it. Append a line: > > bloppA() > > and try again. Rookie mistake. Thank you. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 06:05:39 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 12:05:39 +0100 Subject: Python COM automation - Controlling Microsoft Agent In-Reply-To: <0a998c60-fc33-4424-b5c7-65f4a2846e4d@i12g2000prf.googlegroups.com> References: <0a998c60-fc33-4424-b5c7-65f4a2846e4d@i12g2000prf.googlegroups.com> Message-ID: <47c93bb8$1$874$ba4acef3@news.orange.fr> Whaoouuu! A young newbie! Thanks... for others youngs newbies. From vvangelovski at gmail.com Wed Mar 12 11:32:59 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Wed, 12 Mar 2008 08:32:59 -0700 (PDT) Subject: C extensions question Message-ID: Let's say I write a simple extension in c only for the windows version of my script. Can I just put this compiled dll in the root directory of my application along with the other py files and distribute it like that without the need of an installation script? From sjmachin at lexicon.net Fri Mar 21 18:25:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 15:25:02 -0700 (PDT) Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> Message-ID: <05e369b9-ba75-488f-b58c-de437af2e1c5@d4g2000prg.googlegroups.com> On Mar 22, 8:51 am, Gabriel Genellina wrote: > If you drop this condition then you could fill the array with zeroes > as before, replace only the interesting ones with actual functions, > and write: > > for item in myarray[nonzero(myarray)]: > print item() if callable(item) else item > Let's unbuckle the seat belt :-) If "item" is definitely restricted to being either 0 or a callable object, then item() if item else 0 should give the same answer as, and is quite likely to be faster than, item() if callable(item) else item as it avoids a global lookup and a function call. Cheers, John From http Mon Mar 31 02:51:21 2008 From: http (Paul Rubin) Date: 30 Mar 2008 23:51:21 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> <65anbqF2fg18bU1@mid.individual.net> <87r6drjss4.fsf@physik.rwth-aachen.de> Message-ID: <7xfxu7s7x2.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > However, I'm quite sure that when Unicode has arrived almost > everywhere, some languages will start considering such characters in > their core syntax. Python 3.0 allows for Unicode letters in > identifiers, and there's still room for improvement. I agree. What's the codepoint for lower case lambda? From gagsl-py2 at yahoo.com.ar Mon Mar 24 13:45:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 14:45:52 -0300 Subject: Installing Mutagen Package On Windows References: Message-ID: En Mon, 24 Mar 2008 03:25:02 -0300, Benjamin Serrato escribi?: > Hey, I've run into another problem. I am trying to install the Mutagen > package to use as my first useful program, but can't figure out how to > install it on windows. The README says it is a simple application of-- > > Installing > ---------- > $ ./setup.py build > $ su -c "./setup.py install" > > --but I ran c:\>python c:\python25\tools\scripts\setup.py build and did > similarly for setup.py. I also added c:\python25 and > c:\python25\tools\scripts to my path, but this hasn't worked. I have The setup.by you have to run is the one included in the Mutagen package, not that one. Unless the author provides more specific instructions, the usual way is: - Unpack the archive into any temporary directory - Open a console (cmd) and change to that temporary directory (cd c:\some\temp\dir) - Execute this command: python setup.py install - That's all If you get any error, post the whole error message here, but for specific help on the package it would be better to contact the author directly. -- Gabriel Genellina From grante at visi.com Fri Mar 7 16:22:01 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Mar 2008 21:22:01 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> Message-ID: <13t3cfpo6d8d2ab@corp.supernews.com> On 2008-03-07, Steven D'Aprano wrote: > Professional typesetters, using proportional fonts, don't use double- > spaces because it throws off word spacing and line justification and just > plain looks ugly. They do, however, put more space between sentences than they do between words within a sentence. It is that practice which the "two spaces after a period" rule in typewriting is attempting to emulate. > I suppose that since coders typically use non- proportional > fonts, we can at least justify the use of two spaces with a > claim that it aids readability for "typewriter fonts" -- if > you believe such a thing, which I do not. My thumb has been putting two spaces after a period for 30 years, so the chances that it's going to change are rather slim. :) -- Grant Edwards grante Yow! A shapely CATHOLIC at SCHOOLGIRL is FIDGETING visi.com inside my costume.. From skip at pobox.com Wed Mar 19 11:44:05 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 19 Mar 2008 10:44:05 -0500 Subject: csv.Sniffer - delete in Python 3.0? Message-ID: <18401.13509.344107.988906@montanaro-dyndns-org.local> The csv module contains a Sniffer class which is supposed to deduce the delimiter and quote character as well as the presence or absence of a header in a sample taken from the start of a purported CSV file. I no longer remember who wrote it, and I've never been a big fan of it. It determines the delimiter based almost solely on character frequencies. It doesn't consider what the actual structure of a CSV file is or that delimiters and quote characters are almost always taken from the set of punctuation or whitespace characters. Consequently, it can cause some occasional head-scratching: >>> sample = """\ ... abc8def ... def8ghi ... ghi8jkl ... """ >>> import csv >>> d = csv.Sniffer().sniff(sample) >>> d.delimiter '8' >>> sample = """\ ... a8bcdef ... ab8cdef ... abc8def ... abcd8ef ... """ >>> d = csv.Sniffer().sniff(sample) >>> d.delimiter 'f' It's not clear to me that people use letters or digits very often as delimiters. Both samples above probably represent data from single-column files, not double-column files with '8' or 'f' as the delimiter. I would be happy to get rid of it in 3.0, but I'm also aware that some people use it. I'd like feedback from the Python community about this. If I removed it is there someone out there who wants it badly enough to maintain it in PyPI? Thanks, -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From lists at cheimes.de Wed Mar 19 16:30:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 Mar 2008 21:30:57 +0100 Subject: Improving datetime In-Reply-To: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> Message-ID: <47E17801.606@cheimes.de> Nicholas F. Fabry schrieb: > This is a query for information as to how to proceed. I am not a > professional programmer, but I use Python a great deal to help me in > my main job, which involves designing schedules for a global airline. > As such, I use datetime (and dateutil) extensively, and after much > use, I have come to some conclusions about their utility, and how to > improve them. Some of these changes are quite minor and would result > in a large increase in utility (low hanging fruit), while some changes > are major, and would result in less obvious benefits - but these > changes would increase the 'Python Zen' of them. > > So - where should I propose these changes? Here? python-dev? Should > I write up a full PEP or should I just give a more informal outline > with code samples? I would volunteer to help maintain/improve > datetime, but I don't speak C at all, unfortunately, and datetime > appears to be in C. Please write a detailed but not too long proposal to the Python ideas mailing list. The proposal should explain how you like to improve the datetime module. But *please* don't write a novel. You'll get more attention when the signal to noise ratio is high. A bullet list of features is easier to read than a long text block. I'm a core developer and I may be interested in mentoring your proposal. I can guide you through the process, review code and commit it. Yes, the datetime module is written in C. But we may move the C code to _datetime and create a facade module in Python. Christian From python at rcn.com Sun Mar 9 13:36:40 2008 From: python at rcn.com (Raymond Hettinger) Date: Sun, 9 Mar 2008 10:36:40 -0700 (PDT) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> <54abf8a6-6156-4663-903c-eb761e6b5148@h11g2000prf.googlegroups.com> Message-ID: <4a984680-c2c9-4230-8072-18c6fb6aa4e9@e6g2000prf.googlegroups.com> > > The intern() builtin uses this approach: > > > ? ?interned = {} > > ? ?def intern(s): > > ? ? ? ? if s in interned: > > ? ? ? ? ? ? return interned[s] > > ? ? ? ? interned[s] = s > > ? ? ? ? return s > > If you've seen it before, and have the old one, return the old one. > Do I have this straight? Right. From kyosohma at gmail.com Fri Mar 21 10:36:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 21 Mar 2008 07:36:11 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <61abe4dd-d300-43b3-bf70-e09d50a14344@u10g2000prn.googlegroups.com> On Mar 21, 6:48 am, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > > /fkallgren You could create an update script that compares the md5 (or some other) hash of the files for differences, kill the program if there is a difference and do the copy. I don't understand why you can do it from the server. I basically do the same thing from my workstation when I update one of my programs. To kill the process on a remote PC, I do the following: import subprocess subprocess.Popen('taskkill /s %s /im processName' % computer_name) I actually don't restart mine since it will be started when the user logs on. So I'll leave that to you. Of course, my program is made into an executable, but it should work the same. Maybe that will give you some ideas anyway. Mike From python.list at tim.thechases.com Thu Mar 6 14:39:38 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 06 Mar 2008 13:39:38 -0600 Subject: Exploring Attributes and Methods In-Reply-To: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: <47D0487A.1060409@tim.thechases.com> > Class Sample: > fullname = 'Something' > > How can I know that this class has an attribute called 'fullname'? with the builtin hasattr() function :) >>> class Sample: fullname='Something' ... >>> hasattr(Sample, 'fullname') True -tkc From sluggoster at gmail.com Tue Mar 18 13:49:26 2008 From: sluggoster at gmail.com (Mike Orr) Date: Tue, 18 Mar 2008 10:49:26 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <29b0d6d3-93e9-4c85-b7e9-6e30f4eb0e2f@x41g2000hsb.googlegroups.com> On Mar 16, 6:10 am, Bruce Eckel wrote: vendors: > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. We introduced sponsor lighting talks last year. This year it got out of hand because there were twice as many sponsors. By the time the Lightning Talk coordinators realized this, the sponsors had already been promised a priority talk so we couldn't back out of it. So it was a lack of foresight, not some commercial plot. Next year we (the Lightning Talk coordinators) have recommended either not having sponsor lighting talks, or moving them to a separate (non- plenary) session. The vendor exhibition was much bigger this year, and I think that's an adequate replacement for sponsor lighting talks. If there are sufficient Open Space rooms, they can also create their own session. > At first the morning plenary sessions -- where the entire conference > audience was in a single room -- just seemed a bit commercial. But > then I slowly figured out that the so-called "diamond keynotes" were > actually sold to vendors. It must have sounded great to some I liked the mini-keynotes and I don't think they detracted from the main keynotes. I did know what "diamond" meant so I knew they were sponsor talks. I guess that should be clearer on the schedule. > What was supremely frustrating was discovering that the people wanting > to give REAL lightning talks had been pushed off the end of the list The worst part of scheduling Lighting Talks is there's always more interesting speakers than time. This seems to be an insolvable problem. The main problem I had at PyCon this year was the number of talk I wanted to see that were scheduled at the same time as other talks I wanted to see. The highlight was the number of Open Space rooms and events. I didn't attend any of these, but they seemed unusually lively this year. > On top of that, the quality of the presentations was unusually low. I did feel that. An advanced track would be a good idea. Because you do need to repeat stuff for the newbies. At least 30% of the attendees were at PyCon for the first time. --Mike From pavlovevidence at gmail.com Wed Mar 12 21:37:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 18:37:10 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> Message-ID: On Mar 12, 8:11 pm, Justus Schwabedal wrote: > What do you need it for anyway? I just read about it and I think it's > useless > in python. Perl, like Python, has a separate compilation and run times. One day, someone who was trying to use Perl for something asked, "You know, wouldn't it be neat-o if you could execute some Perl code *before* you compiled the script?" And so (since that's usually enough reason to add something to Perl) was borne the BEGIN block. I believe the official rationale was that they wanted to add some magic variables that affected Perl's compilation and couldn't do it without a magic block that executed at compile time. Python solved a similar problem by introducing __future__ imports. Carl Banks From roygeorget at gmail.com Thu Mar 20 02:06:44 2008 From: roygeorget at gmail.com (royG) Date: Wed, 19 Mar 2008 23:06:44 -0700 (PDT) Subject: dividing tuple elements with an int or float Message-ID: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> hi i am trying to resize some images.First i'd read the size as a 2 tuple and then i want to divide it by 2 or 4 or 2.5 etc.. suppose origsz=(400,300) i want to divide the origsize by 2.5 so i can resize to (160,120) scale=2.5 how can i get the newsz? obviously origsz/2.5 won't work .. thanks RG From tmp1 at viltersten.com Tue Mar 4 15:00:23 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Tue, 4 Mar 2008 21:00:23 +0100 Subject: SV: Polymorphism using constructors In-Reply-To: <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> References: <6333v2F25lleoU1@mid.individual.net> <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> Message-ID: <635n43F25ruecU1@mid.individual.net> "Carl Banks" skrev i meddelandet news:24adaf72-0c55-4a88-86d0-296363ead17f at s8g2000prg.googlegroups.com... > On Mar 3, 4:17 pm, Raymond Hettinger wrote: >> Since Python doesn't support having two methods with the same name, >> the usual solution is to provide alternative constructors using >> classmethod(): >> >> @classmethod >> def from_decimal(cls, d) >> sign, digits, exp = d.as_tuple() >> digits = int(''.join(map(str, digits))) >> if sign: >> digits = -digits >> if exp >= 0: >> return cls(digits * 10 ** exp) >> return cls(digits, 10 ** -exp) > > > Note that even some of Python's built in types (dict *cough*) > implement homemade function overloading. > > The OP wanted to write a constructor that could accept either a pair > of integers or a rational, there would be a good precedent for it. > > However, I would advise the OP to use the constructor only for the > most common arguments, and use classmethods for more obscure, less > common arguments (such as decimal or even float). OP understands and thanfully accepts the suggestion. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From pavlovevidence at gmail.com Sat Mar 8 17:42:31 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 8 Mar 2008 14:42:31 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <876ecbb3-5bfe-40bd-a1ff-102af8d19fbc@n77g2000hse.googlegroups.com> On Mar 8, 9:43 am, malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > x = q.get() > #process x to get zero or more y's > #for each y: > q.put(y) Why not just do it like that? With a few changes it'll work fine: while q: x = q.pop(0) for y in process(x): q.append(y) And consider collections.deque for q instead of a list, though it shouldn't make much of a difference if the queue remains small. Carl Banks From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 21:02:20 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 03:02:20 +0200 Subject: python ODF library? References: Message-ID: <65argsF2egmmlU1@mid.individual.net> Matias Surdi wrote: > Found it: > http://opendocumentfellowship.com/development/projects/odfpy While we're at it: This module seems to be centered around creating documents. Where could I possibly find information/examples on how to read an ODF spreadsheet using Python? Regards, Bj?rn -- BOFH excuse #394: Jupiter is aligned with Mars. From castironpi at gmail.com Wed Mar 5 21:03:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 18:03:28 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> Message-ID: On Mar 5, 5:31?pm, Grant Edwards wrote: > On 2008-03-05, castiro... at gmail.com wrote: > > Anyway, if (a,b) is a key in dictionary d, can it guarantee > > that (b,a) is also in it, and maps to the same object? Er... -specialized- dictionary d. > To solve that problem, Python provides the immutable > "frozenset" type: > > ? >>> s1 = frozenset((1,2)) > ? >>> s2 = frozenset((2,1)) > ? >>> s1 == s2 > ? True > ? >>> d = {s1: "hi there"} > ? >>> s1 in d > ? True > ? >>> s2 in d > ? True Ah. Perfect. With this, I can just call frozenset on keys in __setitem__ and __getitem__... (though at that, it may be easier verbatim*.) *loosely introduced terminology, roughly equivalent to 'spell it out by hand each time'**. **__delitem__ too. Only thing is, that's an extra check if 'key' is iterable. (Yes. I realize this is a little scattered... it's my belief it's intelligible by party X... if not stop now speak up.) Goal: assert d[1,2] is d[2,1] assert d[1] is d[1] assert d[a] is d[a] assert d[a,b] is d[b,a] Only problem is, if a is iterable, then its contents get hashed. I don't see the general way around this. a= SomeList( [ 1,2,3 ] ) b= SomeList( [ 1,2,3 ] ) assert a is not b d[a]= True assert b not in d #there's the hangup It is my loss that M. Roggisch plonks me-- I will be deprived of his perspective and contributions. From coolman.guron at gmail.com Mon Mar 24 09:57:56 2008 From: coolman.guron at gmail.com (binaryj) Date: Mon, 24 Mar 2008 06:57:56 -0700 (PDT) Subject: urllib leaves connections/sockets waiting. BIG problem!!! Message-ID: <62c0ec57-1355-43d8-a414-0767ccc0923a@s37g2000prg.googlegroups.com> hi i am using urllib2 to do some automated web thing. basically i hit on sites and check the price what they are offering for their product and then decide if i want to lower or increase my pricing.so in short i have to hit hundreds of sites!!!!! for the problem: ============= i run 20 threads all do the same stuff. (hit and run :) ) after around 10-15 hits(per thread) hits the thread does nothing. it freezes. slowely but STEADILY all the threads end up with the same fate :( i did some netstat and found out that the connecton(sockets) the program had opened are waiting the CLOSE_WAIT state !! netstat -t tcp 1 0 192.168.1.2:4882 host-blabla:www CLOSE_WAIT tcp 1 0 192.168.1.2:4884 host-blabla:www CLOSE_WAIT tcp 1 0 192.168.1.2:4375 host-blabla:www CLOSE_WAIT OUTPUT OF PROGRAM: THREAD: #Thread-2 getting price from webi-d 7511975 DONE !!! THREAD: #Thread-1 getting price from webi-d 4449152 DONE !!! THREAD: #Thread-2 getting price from webi-d 7466091 DONE !!! THREAD: #Thread-1 getting price from webi-d 8641914 DONE !!! THREAD: #Thread-2 getting price from webi-d 7745289 DONE !!! THREAD: #Thread-1 getting price from webi-d 6032442 DONE !!! THREAD: #Thread-2 getting price from webi-d 8149873 DONE !!! no-price-on-page error THREAD: #Thread-1 getting price from webi-d 5842934 DONE !!! no-price-on-page error THREAD: #Thread-2 getting price from webi-d 3385778 DONE !!! THREAD: #Thread-1 getting price from webi-d 4610122 DONE !!! THREAD: #Thread-2 getting price from webi-d 8641536 DONE !!! THREAD: #Thread-1 getting price from webi-d 4219935 DONE !!! ---------and thats it, it freezes. i have waited 1hr the sockets have not changed their states! :( please help :) From castironpi at gmail.com Wed Mar 5 23:23:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 20:23:45 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> Message-ID: On Mar 5, 8:03?pm, castiro... at gmail.com wrote: > On Mar 5, 5:31?pm, Grant Edwards wrote: > > > On 2008-03-05, castiro... at gmail.com wrote: > > > Anyway, if (a,b) is a key in dictionary d, can it guarantee > > > that (b,a) is also in it, and maps to the same object? > > Er... -specialized- dictionary d. > > > To solve that problem, Python provides the immutable > > "frozenset" type: > > > ? >>> s1 = frozenset((1,2)) > > ? >>> s2 = frozenset((2,1)) > > ? >>> s1 == s2 > > ? True > > ? >>> d = {s1: "hi there"} > > ? >>> s1 in d > > ? True > > ? >>> s2 in d > > ? True > > Ah. ?Perfect. ?With this, I can just call frozenset on keys in > __setitem__ and __getitem__... (though at that, it may be easier > verbatim*.) > a= SomeList( [ 1,2,3 ] ) > b= SomeList( [ 1,2,3 ] ) > assert a is not b > d[a]= True > assert b not in d > #there's the hangup *plonk* key is an iterable, just like the constructors to other collection. >>> 2 in d Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable Interface first? In YOUR face first! From MartinRinehart at gmail.com Wed Mar 26 08:00:52 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 26 Mar 2008 05:00:52 -0700 (PDT) Subject: Tkinter menus from keyboard Message-ID: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Tkinter defaults to, for example, Alt+f = File (if File is your first menu name starting with "f"). I'd like to assign my own letters and have them underscored, per the universal standard. Can this be done? From exarkun at divmod.com Tue Mar 11 12:10:14 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 11 Mar 2008 11:10:14 -0500 Subject: mulithreaded server In-Reply-To: <7c555afb-2df0-43f2-aa16-d1e48da1510a@e23g2000prf.googlegroups.com> Message-ID: <20080311161014.6859.1800705120.divmod.quotient.18021@ohm> On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit wrote: >import socket >import sys >import thread > >p=1 >PORT=11000 >BUFSIZE=1024 > >def getData(cSocket): > global stdoutlock,cSocketlock > while True: > cSocketlock.acquire() > data=cSocket.recv(BUFSIZE) > if data=='q': > data='client exited' > cSocket.close() > p=0 > cSocketlock.release() > stdoutlock.acquire() > stdout.write(data) > stdoutlock.release() > >def sendData(cSocket): > global stdoutlock,cSocketlock > while True: > stdoutlock.acquire() > data=raw_input('>>') > cSocketlock.acquire_lock() > if data=='q': > stdout.write('server exited') > stdout.release() > p=0 > cSocket.close() > sSocket.send(data) > sSocketlock.release() Could it be because `sSocketlock? here > > >stdout=sys.stdout >host='' >sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) >sSocket.bind((host,PORT,)) >sSocket.listen(1) >#sSocketlock=thread.allocate_lock() is never bound since the line above here is commented out? >stdoutlock=thread.allocate_lock() >print 'waiting for connection' >cSocket,addr=sSocket.accept() >print 'connection from',addr >cSocketlock=thread.allocate_lock() >thread.start_new_thread(sendData,(cSocket,)) >thread.start_new_thread(getData,(cSocket,)) >if p==0: > sSocket.close() > > > >In the above program, why there is an unhandeled exception ??? Just a guess. You should really include the traceback when you ask a question like this. Jean-Paul From mnordhoff at mattnordhoff.com Sat Mar 15 14:59:38 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 15 Mar 2008 18:59:38 +0000 Subject: Unicode/UTF-8 confusion In-Reply-To: References: Message-ID: <47DC1C9A.2050201@mattnordhoff.com> Tom Stambaugh wrote: > I'm still confused about this, even after days of hacking at it. It's > time I asked for help. I understand that each of you knows more about > Python, Javascript, unicode, and programming than me, and I understand > that each of you has a higher SAT score than me. So please try and be > gentle with your responses. > > I use simplejson to serialize html strings that the server is delivering > to a browser. Since the apostrophe is a string terminator in javascript, > I need to escape any apostrophe embedded in the html. > > Just to be clear, the specific unicode character I'm struggling with is > described in Python as: > u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for > example, http://www.fileformat.info/info/unicode/char/0027/index.htm) > of 0x27. > > This can be expressed in several common ways: > hex: 0x27 > Python literal: u"\u0027" > > Suppose I start with some test string that contains an embedded > apostrophe -- for example: u" ' ". I believe that the appropriate > json serialization of this is (presented as a list to eliminate notation > ambiguities): > > ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] > > This is a 14-character utf-8 serialization of the above test string. > > I know I can brute-force this, using something like the following: > def encode(aRawString): > aReplacement = ''.join(['\\', '0', '0', '2', '7']) > aCookedString = aRawString.replace("'", aReplacement) > answer = simplejson.dumps(aCookedString) > return answer > > I can't even make mailers let me *TYPE* a string literal for the > replacement string without trying to turn it into an HTML link! > > Anyway, I know that my "encode" function works, but it pains me to add > that "replace" call before *EVERY* invocation of the simplejson.dumps() > method. The reason I upgraded to 1.7.4 was to get the c-level speedup > routine now offered by simplejson -- yet the need to do this apostrophe > escaping seems to negate this advantage! Is there perhaps some > combination of dumps keyword arguments, python encode()/str() magic, or > something similar that accomplishes this same result? > > What is the highest-performance way to get simplejson to emit the > desired serialization of the given test string? simplejson handles all necessary escaping of stuff like quotes... -- From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 10:07:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 14:07:48 -0000 Subject: On copying arrays References: Message-ID: <13ufddkkaunaf5a@corp.supernews.com> On Mon, 24 Mar 2008 09:52:21 +0000, Duncan Booth wrote: > The method usually recommended is: > > best = list(test) > > as it has no side effects In general, you can't assume *anything* in Python has no side effects, unless you know what sort of object is being operated on. Here's an example that changes the value of test: >>> test = iter((1, 2, 3, 4, 5, 6)) >>> best = list(test) >>> best [1, 2, 3, 4, 5, 6] >>> another = list(test) >>> another [] And here's an example that has a rather obvious side-effect: >>> class Foo(object): ... def __getitem__(self, n): ... if n == 3: print "I'm in ur puter, deletin ur files" ... if 0 <= n < 6: return n+1 ... raise IndexError ... >>> test = Foo() >>> best = list(test) I'm in ur puter, deletin ur files >>> best [1, 2, 3, 4, 5, 6] -- Steven From MartinRinehart at gmail.com Fri Mar 7 16:42:56 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Fri, 7 Mar 2008 13:42:56 -0800 (PST) Subject: Better grammar.txt References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: Jeroen Ruigrok van der Werven wrote: > >http://www.martinrinehart.com/articles/python-grammar.html: > >Unknown host www.martinrinehart.com > > Works for me. Very interesting. The link I posted works for me, while the links quoted are 404 errors, though they look identical. This really is a superior version of the EBNF, so I wish it would work for everyone. Any ideas? From roger.dahlstrom at gmail.com Mon Mar 31 10:25:55 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 31 Mar 2008 07:25:55 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: <6551c86f-4537-4395-ae18-364fc83147b2@b64g2000hsa.googlegroups.com> On Mar 31, 10:22 am, rdahlstrom wrote: > So I have a 64 bit Windows 2003 system, running python 2.5.1.1. > > I can import a Windows .dll (msvcrt or whatever) using ctypes, but > when attempting to import another application-specific .dll (tibrv.dll > if anyone is familiar with it), I receive the error WindowsError: > [Error 193] %1 is not a valid Win32 application. > > I know there's a Windows on Windows (wow) which allows 32 bit > processes to run on 64 bit windows - is there a way to work this in > somehow? Maybe I'm barking up the wrong tree? > > Code is simple, and works on 32 bit systems no > > from ctypes import * > #this doesn't work > tibrv = cdll.tibrv > #this does work > msvcrt = cdll.msvcrt And by "works on 32 bit systems no", I mean "works on 32 bit systems no problem." From jgodoy at gmail.com Sun Mar 2 11:49:42 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 02 Mar 2008 13:49:42 -0300 Subject: Problem with the strip string method References: Message-ID: Colin J. Williams wrote: > Return a copy of the string with the > leading and trailing characters removed. ^^^^^^^^^^^^^^^^^^^^ > Only the last two examples below behave > as expected. They all looks OK to me. > [Dbg]>>> 'ab$%\n\rcd'.strip('%') > 'ab$%\n\rcd' No "%" at the beginning or end of string. Nothing changed. > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%\n\rcd' No "$" at the beginning or end of string. Nothing changed. I believe that you didn't copy this from the standard input due to the presence of "\r\n" on the answer... > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%cd' No "$" at the beginning or end of string. Nothing changed. > [Dbg]>>> ' ab$%cd '.strip('$') > ' ab$%cd ' No "$" at the beginning or end of string. Nothing changed. > [Dbg]>>> ' ab$%cd '.strip('%') > ' ab$%cd ' No "%" at the beginning or end of string. Nothing changed. From drobinow at gmail.com Wed Mar 12 23:07:57 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Wed, 12 Mar 2008 20:07:57 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: On Mar 12, 7:37 am, "k.i.n.g." wrote: > We use dd command in Linux to create a file with of required size. If you just want to get your work done, you might consider the cygwin dd command. Learning to write python is a worthwhile endeavour in any case. From fakeaddress at nowhere.org Thu Mar 6 15:05:24 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 20:05:24 GMT Subject: Python CGI & Webpage with an Image In-Reply-To: <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> Message-ID: <88Yzj.19022$R84.2998@newssvr25.news.prodigy.net> rodmc wrote: > [...] I have played around a bit more > so that both the image and HTML file are in the public_html folder. > They are called via python using a relative URL, and have permissions > set to 755. Within the HTML file the image is accessed using just > "banner.jpg". The actual page displays ok except for the image - so it > has the same problem as before. However when the same page is > displayed without running through a CGI it displays perfectly. Is the cgi script in the same directory? The user's browser looks for the jpg relative to the URL it used to get the page, which in the case of the CGI script is the path to the script, not the path to the html file. If server logs are hard to get or read, try my runcgi.py script: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/550822 -- --Bryan From software at ginstrom.com Sun Mar 23 11:51:22 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 24 Mar 2008 00:51:22 +0900 Subject: Testing for an empty dictionary in Python In-Reply-To: <47e67a99$0$36364$742ec2ed@news.sonic.net> References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <079201c88cfd$be762f10$0203a8c0@MOUSE> > On Behalf Of John Nagle > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). I believe that the following is fairly efficient: >>> def dict_is_empty(D): for k in D: return False return True >>> dict_is_empty(dict(a=1)) False >>> dict_is_empty({}) True Regards, Ryan Ginstrom From darcy at druid.net Thu Mar 6 11:47:07 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 6 Mar 2008 11:47:07 -0500 Subject: Identifying messages in a thread (was: Please keep the full address) In-Reply-To: <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> References: <8763w094sy.fsf_-_@benfinney.id.au> <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> Message-ID: <20080306114707.a5462f26.darcy@druid.net> On Thu, 6 Mar 2008 07:58:06 -0800 (PST) Carl Banks wrote: > > I don't want to have to tag every thread. I just want to *plonk* > > certain posters. > > > > Anyway, I'll live with Google's failings I guess. > > Sounds like you need better filtering. > > A decent news filter should be able not only kill a poster, but also > all followups to that poster recursively. Actually, I am reading this as a mailing list and since I run Unix and procmail I am sure that I could set something up if it really starts to be annoying. So far the simple filters deal with all but a smattering of problem postings so I don't need to expend the time. -- 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 arnodel at googlemail.com Mon Mar 10 21:27:36 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Mar 2008 18:27:36 -0700 (PDT) Subject: TextWrapper keepking line breaks? References: Message-ID: On Mar 10, 11:31?pm, js wrote: > Hi list, > > Can I make TextWrapper keep line breaks in the text? > > For example, > > >>> s = "spam\nham" > >>> print wrap(s) > > spam > ham > > As far as I can tell, there seems no way to do this, > but before writing my own solution, I want to know whether > the solution already exists or not. > > Thanks. Don't know but you could write: >>> import textwrap >>> def wraplines(text): ... return '\n'.join(textwrap.fill(line) for line in text.split('\n')) ... >>> s = "spam\nham" >>> print wraplines(s) spam ham >>> HTH -- Arnaud From wahreviews at gmail.com Sat Mar 22 18:56:36 2008 From: wahreviews at gmail.com (Work from Home Secrets) Date: Sat, 22 Mar 2008 15:56:36 -0700 (PDT) Subject: Make Money Using Paypal Get Paid Instantly References: <4563a8f0-7f25-46d9-a039-e5cd5d11c523@i29g2000prf.googlegroups.com> Message-ID: > Interesting. What is being suggested here is against Paypal's > acceptable usage policy. Consult with a real person who has been > successful before you jump into a scam like this and above all, make > sure that person is going to be there to support you the whole way > whether you just need to ask a question from time to time or need a > great deal of help. > > http://workfromhomereviews.org/ * * * Do yourself a favor today! * * * Give yourself every advantage you deserve! * * * http://workfromhomereviews.org/stealth-money-maker.html * * * Make it a great one! From ggpolo at gmail.com Wed Mar 26 08:45:29 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 26 Mar 2008 09:45:29 -0300 Subject: Tkinter menus from keyboard In-Reply-To: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: 2008/3/26, MartinRinehart at gmail.com : > Tkinter defaults to, for example, Alt+f = File (if File is your first > menu name starting with "f"). > > I'd like to assign my own letters and have them underscored, per the > universal standard. Can this be done? > Set the underline option to the index of the desired letter > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 21 05:50:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 21 Mar 2008 10:50:09 +0100 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> Message-ID: <47e384cb$0$567$426a74cc@news.free.fr> sam a ?crit : > Bruno Desthuilliers napisa?(a): > >> Most of the arguments in favor of prototypes seems to come to, mainly: >> 1/ it lets you customize behaviour on a per-object base >> 2/ it removes the mental overhead of inheritance, classes etc >> >> Point 1. is a non-problem in Python, since you can already add/replace >> methods on a per-objec basis (ok, with a couple restrictions wrt/ >> __magic__ methods and such). >> >> Point 2. is not (IMHO) such a problem in Python, where inheritance is >> mainly an implementation detail (it's not needed for polymorphic >> dispatch to work) and class hierarchy tend to be very flat, when they >> even exist. >> >> Mainly, Python's object system is actually quite close to javascript >> here. That is, you get more or less the same flexibility. And a couple >> of powerful features you don't have with javascript (like hooks in the >> attribute lookup mechanism), too. > > Thanks for precise opinion and spending your time. > > > I think that when you use statically typed language, than you have to > define classes, because compiler has to know what is allowed to do with > instances of that class. > > But when you use dynamically typed language, then classes are redundant, > because object is looked at when it is referenced. Dynamically typed > language needs only objects hierarchy and you can add properties > (methods, values) to that object during program execution. Dynamic typing does not necessarily imply that you can add properties of modify behaviour at runtime. Most dynamically typed languages let you do that, but that's still orthogonal. And FWIW, you could emulate this in static languages using a hashtable, functors, and a couple accessors (a la __getattr__/__setattr__). > In dynamically typed language when you create object A that is inherited > from another object B, than object A knows that B is his predecessor. So > when you reference A.prop, then prop is looked in A first, then in B, > then in predecessors of B, and so on. What you're describing here is the inheritance mechanism of Python. And could apply just as well to javascript prototype mechanism. A javascript object has a reference to it's prototype object - that you can customize, rebind etc -, a Python object has a reference to it's class object - that you can customise, rebind etc... Don't be fooled by the term "class" itself - it's meaning is totally different in a language like Python. I may be plain wrong here but I suspect you don't have a serious knowledge of Python's object model. From ivan.illarionov at gmail.com Tue Mar 18 19:49:05 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 18 Mar 2008 16:49:05 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> Message-ID: <4393b161-2f16-4a64-a5c2-0d99d64938fe@s37g2000prg.googlegroups.com> On Mar 19, 2:33 am, dave wrote: > First I want to say thank you all for your timely replies. This is all > good food for thought. I've been programming more many years, but fast > graphics rendering is new territory for me. > > I'm hoping to fine something like a buffer_blit, where I can set all > the pixels to change using basic operators, blit them all at once to a > pixel buffer, then swap the visible buffer. Ideally it will only > change the region of the pixel buffer that needs changing. > > Because I want layers, I would like to take advantage wherever > possible of the available hardware features. I.E. ideally I am hoping > that the layers can be textures in memory that get composited in > hardware onto the screen. Maybe this is wishful thinking though? > > I'm also thinking that maybe I can reduce the number of active layers > from N down to 3 - the active layer, the layers below it, and the > layers above it. Obviously only the active layer needs any sort of > sprite-like animations and it on this layer than response time is most > important. Having to layer the top layers ontop of it may also play a > factor but, as I suggested, I can merge them all together in one time > and then use the merged result to layer on top of the active layer. > > I'm a little nervous about going the C/C++ route. It's been a few > years since I used them, I'm new to Python, and jumping into coding > Python extensions with C/C++ is not particularly palatable (though > I'll do it if I have to.) > > > Any GUI toolkit will work if you find the low-level access > > to their image memory buffers. > > That's another new step for me. Any ideas where to start? Thanks! Some reading on fast 2d graphics: chapters 35-42 from http://www.byte.com/abrash/ and a lot of great stuff here: http://tog.acm.org/GraphicsGems/ From castironpi at gmail.com Mon Mar 10 05:48:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 02:48:17 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> > I believe Python automatically creates and caches int objects for 0-256, > so whenever you use them, they refer to the same exact objects. Since > ints are immutable, it doesn't matter. One of the biggest hits on start-up time, by the way. ;) From kaushikbarat at gmail.com Sat Mar 15 05:36:19 2008 From: kaushikbarat at gmail.com (kaush) Date: Sat, 15 Mar 2008 02:36:19 -0700 (PDT) Subject: ImportError while Embedding python in C References: <0e568278-c5b3-40d3-a172-7d1701510f50@s19g2000prg.googlegroups.com> Message-ID: <3961db36-de0a-434c-8e77-91dcd1936da1@s19g2000prg.googlegroups.com> On Mar 15, 2:10 am, kaush wrote: > Hi All, > > I have a simple python script saved to "test.py" as > > import os > import base64 > > def Testfunction(): > print "Hello World" > return > > Testfunction() > > I am trying to invoke this from a C program as follows > > int main(int argc, char* argv[]) > { > Py_Initialize(); > > PyObject* main_module = PyImport_AddModule("__main__"); > > PyObject* main_dict = PyModule_GetDict(main_module); > > FILE* file_1 = fopen(TestFile, "r"); > PyRun_AnyFile(file_1, TestFile); > > Py_Finalize(); > > return 0; > > } > > This fails with the error > > Traceback (most recent call last): > File "/home/kaushik/shadowFs/test.py", line 4, in > import base64 > File "/usr/local/lib/python2.5/base64.py", line 9, in > import struct > File "/usr/local/lib/python2.5/struct.py", line 30, in > from _struct import Struct, error > ImportError: /usr/local/lib/python2.5/lib-dynload/_struct.so: > undefined symbol: PyExc_TypeError > > I am able to run test.py successfully from the shell. > > What am i missing in importing the base64 library? > > Thanks, > Kaushik Adding the following link options during compilation solved the problem "-Xlinker -export-dynamic" Thanks, Kaushik From aahz at pythoncraft.com Fri Mar 7 11:39:51 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Mar 2008 08:39:51 -0800 Subject: OT: Failed saving throw References: Message-ID: In article , Aahz wrote: > >For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people >think we should build a tomb in his honor. ;-) ...and xkcd finally weighs in: http://xkcd.com/393/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From jeff at schwabcenter.com Sun Mar 2 17:11:24 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 14:11:24 -0800 Subject: First post from a Python newbiw In-Reply-To: References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: Christoph Zwerschke wrote: > Marc 'BlackJack' Rintsch schrieb: >> On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: >> >>> Apart from doing something like >>> a=[0,0,0] >>> b=[0,0,0] >>> c=[0,0,0] >>> d=[a,b,c] >>> >>> is there a better way of creating d?? >> >> a = [[0] * 3 for dummy in xrange(3)] Each element of a refers to a distinct array. > Why not simply [[0]*3]*3 ? All three elements of the result refer to the same array. From miki.tebeka at gmail.com Wed Mar 12 18:36:07 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 12 Mar 2008 15:36:07 -0700 (PDT) Subject: C extensions question References: Message-ID: Hello, > Let's say I write a simple extension in c only for the windows version > of my script. Can I just put this compiled dll in the root directory > of my application along with the other py files and distribute it like > that without the need of an installation script? Yes (current directory is always looked first in when loading DLLs). HTH, -- Miki http://pythonwise.blogspot.com From castironpi at gmail.com Tue Mar 18 16:54:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 13:54:19 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> <80b7cd63-a6f3-4521-adb1-93b6faab307e@e39g2000hsf.googlegroups.com> Message-ID: <760b50cd-fb84-4ecc-9961-ae49e725e416@v3g2000hsc.googlegroups.com> > > >>> Can I allocate a second console window, so I can place certain output > > >>> to that directly, and leave the original streams alone? ? > > > I've rather lost track of what you're trying to do, but I would > > second Gabriel's suggestion of the standard Windows method of > > debug output: using OutputDebugString. There's an example here: > > >http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugStrin... > > > and it shouldn't be too hard to wrap it in a file-like > > object for stderr-substitution use, say. > > > Obviously there are 1,001 other ways of doing IPC but since this > > one's ready-made you might as well use it. You can distinguish > > between different processes' outputs by virtue of the PID which > > is the first item on the mmap. > > > TJG > > I want a handle to another window. > > Create B with a command. > ?___ ? ___ > |A ?| |B ?| > |___| |___| > > B.stdin (the stdin to B).write( '?' ) > ?___ ? ___ > |A ?| |B? | > |___| |___| > > A.stdout.write( '*' ) > ?___ ? ___ > |A* | |B? | > |___| |___| This is a little weird. I visited your link, but couldn't make any sense of it, so I tried something else myself. I'm not even sure what it accomplishes, but if you're on a different tack or way ahead of me, that can happen. However, it might be closer than I think to what I want-- my next step is to CreateProcess in the separate executable... then try to merge in back into python and subprocess. Now I've tried: >>> p= Popen( '\\astdin.exe', creationflags= 16, stdin= PIPE ) >>> p.stdin.write( b'123\r\n' ) 5 and I get the message box (lower), but no ':' sentinel nor the output. However the p.stdin.write call still returns if I close the new console window and call it after. astdin.cpp: #include #include #include using namespace std; DWORD WINAPI ThreadProc( LPVOID ) { while (1) { Sleep( 1000 ); cout<< ':'; } } int main() { MessageBox( NULL, "none", NULL, 0 ); cout<< "Ok"<< endl; CreateThread( NULL, 0, ThreadProc, NULL, 0, NULL ); while (1) { string s; cin>> s; cout<< '>'; cout<< s; } return 0; } From gagsl-py2 at yahoo.com.ar Sat Mar 22 00:32:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 21:32:28 -0700 (PDT) Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> <05e369b9-ba75-488f-b58c-de437af2e1c5@d4g2000prg.googlegroups.com> Message-ID: On 21 mar, 19:25, John Machin wrote: > On Mar 22, 8:51 am, Gabriel Genellina wrote: > > > If you drop this condition then you could fill the array with zeroes > > as before, replace only the interesting ones with actual functions, > > and write: > > > for item in myarray[nonzero(myarray)]: > > ? ? print item() if callable(item) else item > > Let's unbuckle the seat belt :-) > > If "item" is definitely restricted to being either 0 or a callable > object, then > ? ? item() if item else 0 > should give the same answer as, and is quite likely to be faster than, > ? ? item() if callable(item) else item > as it avoids a global lookup and a function call. In that case, we could use a bare item() because nonzero would have filtered out all that zeroes. -- Gabriel Genellina From bockman at virgilio.it Wed Mar 5 05:34:14 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 5 Mar 2008 02:34:14 -0800 (PST) Subject: draining pipes simultaneously References: Message-ID: On 5 Mar, 10:33, "Dmitry Teslenko" wrote: > Hello! > Here's my implementation of a function that executes some command and > drains stdout/stderr invoking other functions for every line of > command output: > > def __execute2_drain_pipe(queue, pipe): > ? ? ? ? for line in pipe: > ? ? ? ? ? ? ? ? queue.put(line) > ? ? ? ? return > > def execute2(command, out_filter = None, err_filter = None): > ? ? ? ? p = subprocess.Popen(command , shell=True, stdin = subprocess.PIPE, \ > ? ? ? ? ? ? ? ? stdout = subprocess.PIPE, stderr = subprocess.PIPE, \ > ? ? ? ? ? ? ? ? env = os.environ) > > ? ? ? ? qo = Queue.Queue() > ? ? ? ? qe = Queue.Queue() > > ? ? ? ? to = threading.Thread(target = __execute2_drain_pipe, \ > ? ? ? ? ? ? ? ? args = (qo, p.stdout)) > ? ? ? ? to.start() > ? ? ? ? time.sleep(0) > ? ? ? ? te = threading.Thread(target = __execute2_drain_pipe, \ > ? ? ? ? ? ? ? ? args = (qe, p.stderr)) > ? ? ? ? te.start() > > ? ? ? ? while to.isAlive() or te.isAlive(): > ? ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? ? ? ? line = qo.get() > ? ? ? ? ? ? ? ? ? ? ? ? if out_filter: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? out_filter(line) > ? ? ? ? ? ? ? ? ? ? ? ? qo.task_done() > ? ? ? ? ? ? ? ? except Queue.Empty: > ? ? ? ? ? ? ? ? ? ? ? ? pass > > ? ? ? ? ? ? ? ? try: > ? ? ? ? ? ? ? ? ? ? ? ? line = qe.get() > ? ? ? ? ? ? ? ? ? ? ? ? if err_filter: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? err_filter(line) > ? ? ? ? ? ? ? ? ? ? ? ? qe.task_done() > ? ? ? ? ? ? ? ? except Queue.Empty: > ? ? ? ? ? ? ? ? ? ? ? ? pass > > ? ? ? ? to.join() > ? ? ? ? te.join() > ? ? ? ? return p.wait() > > Problem is my implementation is buggy and function hungs when there's > empty stdout/stderr. Can I have your feedback? The Queue.get method by default is blocking. The documentation is not 100% clear about that (maybe it should report the full python definition of the function parameters, which makes self-evident the default value) but if you do help(Queue.Queue) in a python shell you will see it. Hence, try using a timeout or a non-blocking get (but in case of a non blocking get you should add a delay in the loop, or you will poll the queues at naximum speed and maybe prevent the other threads from accessing them). Ciao ----- FB From python.list at tim.thechases.com Fri Mar 14 09:57:44 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Mar 2008 08:57:44 -0500 Subject: find string in file In-Reply-To: References: Message-ID: <47DA8458.4000300@tim.thechases.com> > I'm neophite about python, my target is to create a programa that > find a specific string in text file. > How can do it? >>> FNAME1 = 'has.txt' >>> FNAME2 = 'doesnt_have.txt' >>> TEXT = 'thing to search for' >>> TEXT in file(FNAME1).read() True >>> TEXT in file(FNAME2).read() False or that may not be what your teacher wants, but if you give the homework problem and what you've tried, we might be able to give you some more quality guidance. :) The above is *really* *bad* code...horribly suboptimal especially as files get large. It only returns a boolean value. You might prefer to enumerate the file's contents and, if any line contains the search-text, return that line offset without reading the rest of the file. -tkc From yhvh2000 at googlemail.com Mon Mar 10 13:02:17 2008 From: yhvh2000 at googlemail.com (yhvh) Date: Mon, 10 Mar 2008 10:02:17 -0700 (PDT) Subject: error/warning color customization in interactive console? References: <0cb7044d-4f20-4cf8-b08c-5a99543853bd@i29g2000prf.googlegroups.com> Message-ID: <1e752c2d-a34d-49a7-9fa0-093aad862fd1@d21g2000prf.googlegroups.com> I've just discovered ipython - An Enhanced Interactive Python, which among other things colorizes output including error codes From ken at seehart.com Sun Mar 23 21:52:12 2008 From: ken at seehart.com (Ken) Date: Sun, 23 Mar 2008 18:52:12 -0700 Subject: Does python hate cathy? In-Reply-To: <1206320551.3365.20.camel@localhost.localdomain> References: <1206320551.3365.20.camel@localhost.localdomain> Message-ID: <47E7094C.3010009@seehart.com> Yup, I think Carsten got it. Mystery solved! You could replace Person with self.__class__ instead of type(self) if Person is an old-style class (since the class won't be collected until after all the instances are collected (because each instance references it's class)). Note that when the name "Person" is set to None, the Person class has it's reference count reduced by one but it is not yet collected. Alternatively, if you name your locals to start with "_" (e.g. _cathy) you avoid this problem /"Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called."/ But in general, I have this to say: IMO __del__ should not be taught to beginners (other than to say "don't use __del__ yet; you have much to learn first young jedi"). It should always be put in the "advanced topics" section when included in beginning python books along with threads, process control, and extending/embedding. If you think you need it, you probably don't. It is an advanced concept that requires a basic understanding of garbage collection. Beginners shouldn't really have to know much about garbage collection. The whole point is that it is automatic. __del__ is particularly dangerous for experienced C++ programmers starting to learn Python. People look for analogies and when they see __del__ they think "destructor" which is sort of vaguely right, but completely wrong in practice. The practical difference is that in C++ you actually have to deal with implementing destructors all of the time, and you can't get very far as a C++ programmer without using them, whereas in python you almost never have to deal with destructors. In C++, destructors are usually predictable (in correct code), but in python code they are somewhat harder to predict because they are invoked implicitly at the whim of the python implementation. In practice you don't need to use __del__ unless you are doing something exotic like explicitly implementing your own memory model, or tuning resource allocation in a large system. If you are doing ordinary day-to-day programming don't even think about __del__. Ken Seehart Carsten Haese wrote: > On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > >> That's really weird... it's reproducible on Windows too. It doesn't >> make any sense why the name of the variable would make a difference. >> My guess is you hit some kind of obscure bug. >> > > This is not a bug, just an unexpected feature: > http://mail.python.org/pipermail/python-list/2005-January/304873.html > > What's happening is that at the end of the script, all objects in the > global namespace are set to None (in order to decrease their reference > count and trigger garbage collection). This happens in the order in > which the names appear as keys in the globals dictionary. It randomly > happens that "swaroop", "kalam", and "cath" all are hashed in front of > "Person", but "cathy" is hashed after "Person". > > Hence, if Catherine is named cath, Python "None's" all the instances > first and then the type last, and all is well. However, if Catherine is > called cathy, Person is set to None before cathy. Then, in the lookup of > the global name "Person" during cathy.__del__, Person is None, which > doesn't have a "population" attribute, causing the AttributeError. > > Possible workarounds are: > 1) Explicitly delete the global names for the instances before the > script runs out. > 2) Don't refer to the "Person" type by its global name in __del__, but > indirectly as type(self). (This requires Person to be a new-style class, > though.) > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat Mar 8 13:11:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 10:11:15 -0800 (PST) Subject: multiplication of lists of strings References: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> <47ce56e9$0$10738$426a34cc@news.free.fr> <564294c7-cd78-483e-9393-aad0092809f7@59g2000hsb.googlegroups.com> Message-ID: On Mar 8, 12:04?pm, castiro... at gmail.com wrote: > On Mar 5, 2:16?am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > castiro... at gmail.com a ?crit : > > (snip) > > > > That reminds me: ?Is there a generic 'relation' pattern/recipie, such > > > as finding a computer that's "paired" with multiple users, each of who > > > are "paired" with multiple computers, without maintaining dual- > > > associativity? > > > Yes : use a relational database. > > No performance hit. ?Can I write an ad hoc relational class structure? What do you think of this solution? http://jtauber.com/blog/2005/11/10/relational_python:_basic_class_for_relations/ http://www.google.com/search?hl=en&q=python+relational+class+-database From bj_666 at gmx.net Sun Mar 9 05:51:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Mar 2008 09:51:23 GMT Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> Message-ID: <63hq8rF27chv6U1@mid.uni-berlin.de> On Sun, 09 Mar 2008 01:42:01 -0800, vpalexander wrote: > I keep seeing destructor calls in wx for ad hoc dialogs and wonder if > this is required, and if so, why would normal gc flow not be good? Because there is no guarantee when `__del__()` is called or if it is called *at all*. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Tue Mar 25 16:47:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Mar 2008 07:47:06 +1100 Subject: My python interpreter became mad ! In-Reply-To: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> Message-ID: <47E964CA.4070603@lexicon.net> Furkan Kuru top-posted: > Most probably X-Spam added itself to your path. What is "X-Spam"? Added itself to Benjamin's path [not mine] in such a fashion that it is invoked when one does "import re"? > you should look at your PATH and PYTHONPATH environment variables. Most *IM*probably. Read the traceback: """ > > File "/etc/postfix/re.py", line 19, in ? > > m = re.match('(Spam)', mail) > > AttributeError: 'module' object has no attribute 'match' """ This is a classic case of a script (which does not guard against side effects (like spewing out gibberish) when imported instead of being executed) being given the same name as a Python-included module and being executed in the current directory and hence ends up importing itself. > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > wrote: > > On Mar 25, 10:05 pm, Benjamin Watine > wrote: > > Yes, my python interpreter seems to became mad ; or may be it's > me ! :) > > > > I'm trying to use re module to match text with regular > expression. In a > > first time, all works right. But since yesterday, I have a very > strange > > behaviour : > > > > $ python2.4 > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > Type "help", "copyright", "credits" or "license" for more > information. > > >>> import re > > X-Spam-Flag: YES [snip] > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/etc/postfix/re.py", line 19, in ? > > m = re.match('(Spam)', mail) > > AttributeError: 'module' object has no attribute 'match' > > >>> > > > > What's the hell ?? I'm just importing the re module. > > No you're not importing *the* re module. You're importing *an* re > module, the first one that is found. In this case: your own re.py. > Rename it. > From grflanagan at gmail.com Tue Mar 11 04:56:05 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 11 Mar 2008 01:56:05 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> Message-ID: On Mar 11, 6:21 am, royG wrote: > On Mar 10, 8:03 pm, Tim Chase wrote: > > > In Python2.5 (or 2.4 if you implement the any() function, ripped > > from the docs[1]), this could be rewritten to be a little more > > flexible...something like this (untested): > > that was quite a good lesson for a beginner like me.. > thanks guys > > in the version using glob() > > >path = os.path.normpath(os.path.join(folder, '*.txt')) > >lst = glob.glob(path) > > is it possible to check for more than one file extension? here i will > have to create two path variables like > path1 = os.path.normpath(os.path.join(folder, '*.txt')) > path2 = os.path.normpath(os.path.join(folder, '*.doc')) > > and then use glob separately.. > or is there another way? > I don't think you can match multiple patterns directly with glob, but `fnmatch` - the module used by glob to do check for matches - has a `translate` function which will convert a glob pattern to a regular expression (string). So you can do something along the lines of the following: --------------------------------------------- import os from fnmatch import translate import re d = '/tmp' patt1 = '*.log' patt2 = '*.ini' patterns = [patt1, patt2] rx = '|'.join(translate(p) for p in patterns) patt = re.compile(rx) for f in os.listdir(d): if patt.match(f): print f --------------------------------------------- hth Gerard From Lie.1296 at gmail.com Sun Mar 2 11:23:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 2 Mar 2008 08:23:13 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> Message-ID: <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> On Mar 2, 10:02 pm, Paul Rubin wrote: > Lie writes: > > Anyway, I don't think Python should > > work that way, because Python have a plan for numerical integration > > which would unify all numerical types into an apparent single type, > > which requires removal of operator's limitations. > > Well I think the idea is to have a hierarchy of nested numeric types, > not a single type. You hit the right note, but what I meant is the numeric type unification would make it _appear_ to consist of a single numeric type (yeah, I know it isn't actually, but what appears from outside isn't always what's inside). > > from __future import division > > a = 10 > > b = 5 > > c = a / b > > if c * b == a: print 'multiplication is inverse of division' > > Try with a=7, b=25 They should still compare true, but they don't. The reason why they don't is because of float's finite precision, which is not exactly what we're talking here since it doesn't change the fact that multiplication and division are inverse of each other. One way to handle this situation is to do an epsilon aware comparison (as should be done with any comparison involving floats), but I don't do it cause my intention is to clarify the real problem that multiplication is indeed inverse of division and I want to avoid obscuring that with the epsilon comparison. From craigm3604 at gmail.com Mon Mar 24 18:21:11 2008 From: craigm3604 at gmail.com (Craig) Date: Mon, 24 Mar 2008 15:21:11 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> Message-ID: <8fd0d8bd-c80a-4ec1-a70a-ea659a84413e@e6g2000prf.googlegroups.com> On Mar 24, 3:45 pm, Craig wrote: > On Mar 24, 12:27 pm, Craig wrote: > > > > > On Mar 23, 7:59 pm, Dennis Lee Bieber wrote: > > > > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig > > > declaimed the following in comp.lang.python: > > > > > This dll was designed to be used from either C or Visual Basic 6. > > > > > I have the declare statements for VB6, if that helps. > > > > Probably not that much -- I'd bet it's full of variant records > > > > > Based on the results I have so far (and I have tried MANY permutations > > > > like trying to use the LPSTR for SecKey and PriKey which are returned > > > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > > > instead of pointers. > > > > > For this, I try: > > > > LPSTR = c_char_p > > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > > > LPSTR] > > > > SrchKey = > > > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > > > \x00", 41) > > > > SecKey = create_string_buffer(41) > > > > SecKey.raw = "1234567890123456789012345678901234567890" > > > > PriKey = > > > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > > > 41) > > > > TypeDef = create_string_buffer(128) > > > > TypeDef.raw = "X".center(128, "X") > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > > and I get: > > > > Traceback (most recent call last): > > > > File "C:\temp\vbisam_test_2.py", line 158, in > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(S > > > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > > WindowsError: exception: access violation reading 0x3433322D > > > > > I notice that SecKey.raw starts with "1234" and the exception address > > > > is 0x3433322D, which is "432-". > > > > 0x2D is 4 less than the expected 0x31... > > > > > And, changing to: > > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > > > LPSTR] > > > > PriKey = create_string_buffer(41) > > > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > > I then get: > > > > Traceback (most recent call last): > > > > File "C:\temp\vbisam_test_2.py", line 159, in > > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > > byref(c_void_p(S > > > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > > WindowsError: exception: access violation reading 0x4443423D > > > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > > > is 0x4443423D, which is "DBC=". > > > > ... and 0x3D is 4 less than the expected 0x41 > > > > Which leads me to suspect that BSTR are a structure, not a plain > > > string, in which the address given is supposed to be prefaced with a > > > length value. IOWs, something like: > > > > |----|--------------------------------------| > > > ^ ^ C-string data > > > | |Address to be passed > > > |(address - 4) to get to a length count field > > > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > > > (the URL is from HTTP through to the end, including .aspx) > > > > Creating such may not be difficult -- but passing it to the DLL > > > could be. I don't know if ctypes allows pointer arithmetic. > > > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > > > length prefix. > > > > The only mention of BSTR in the win32 extensions is in text that > > > implies that the win32 extension library takes care of converting > > > from/to BSTR and Python strings transparently -- but that won't work for > > > your third-party library I suspect. > > > > Might have to beg the author(s) of ctypes to add a BSTR type to the > > > list of those supported... as I can find no means of tweaking the > > > address computed by byref() to point somewhere into a structure rather > > > than the beginning of the structure. > > > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > > > >>> pk > > > 1373844 > > > >>> id(pk) > > > 18941724 > > > >>> ctypes.string_at(pk) > > > '1234567890' > > > >>> ctypes.string_at(pk-4, 20) > > > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > > Okay, the return value from SysAlloc... IS the integer representing > > > the address of a BSTR structure (IE, the address four bytes in from the > > > real memory start)... Note how backing up 4 bytes reveals the BSTR > > > length field > > > > What happens if you just pass that item as-is, no byref(), no > > > conversion to ctypes pointer types... > > > > PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > SecKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > > res = VmxGet( byref(hwmcb), > > > byref(SecIndex), > > > byref(Option), > > > byref(c_void_p(SrchKey)), > > > SecKey, > > > PriKey, > > > TypeDef ) > > > > >>> PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > >>> ctypes.string_at(PriKey, 41) > > > > "1234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'">>> ctypes.string_at(PriKey-4, 41+4) > > > > ")\x00\x00\x001234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'" > > > > >>> ord(")") > > > 41 > > > > You'll need to use the .string_at() or .wstring_at() functions to > > > extract any data changed by the call. Should not be a Python > > > immutability problem as all "you" allocated in Python is the integer > > > holding the address. You may need to call a Sys... function to free the > > > memory that had been allocated -- Python doesn't know about it. > > > -- > > > Wulfraed Dennis Lee Bieber KD6MOG > > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > > HTTP://wlfraed.home.netcom.com/ > > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > > HTTP://www.bestiaria.com/ > > > The VB6 Declare is: > > Declare Function VmxGet Lib "vbis5032.DLL" (DatasetHandle&, > > SecIndexField%, Options%, SelectorKey$, RSecondaryKey$, RPrimaryKey$, > > RRecordVariable As Any) As Integer > > > The only variant is the RRecordVariable, which is actually meant to be > > a Type structure. > > > Anyway, I thought maybe there was a clue in here that I am missing. > > > Back to Python. I ran with the following: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > > LPSTR] > > SrchKey = > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > \x00", 41) > > SecKey = > > windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", > > 41) > > PriKey = > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > 41) > > TypeDef = create_string_buffer(128) > > TypeDef.raw = "X".center(128, "X") > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) > > And, now I get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 156, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), SecKey, PriKey, TypeDef ) > > ctypes.ArgumentError: argument 5: : wrong > > type > > > So, now the problem is with: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > > LPSTR] > > I am not sure what to put for arguments 5 and 6 now. > > > I realized the need to release the BSTRs myself, and already included: > > windll.oleaut32.SysFreeString(SrchKey) > > windll.oleaut32.SysFreeString(SecKey) > > windll.oleaut32.SysFreeString(PriKey) > > at the end of the program. > > > I have no problem using .string_at() to extract the returned values - > > once the .argtypes let the call execute. > > > In case this helps, here is an excerpt from a C program that was > > provided with the dll: > > typedef struct tagMYREC > > { > > char name[51]; // 1 xref generated name key > > > char lastname[31]; // 2 last name > > char firstname[21]; // 3 first name > > char address[41]; // 4 address > > char city[31]; // 5 xref city key > > char state[3]; // 6 xref state > > char zip[11]; // 7 xref zip code > > char phone[21]; // 8 xref phone number > > BSTR notes; // 9 notes > > > } MYREC; > > typedef MYREC FAR * LPMYREC; > > > short rc; // return code (from VB/ISAM function calls) > > static HANDLE nDatasetNumber; > > static short cur_index; > > static short GetOpt; > > static BSTR Dummy; > > static BSTR Throwaway; > > static BSTR PrimaryKey; > > static MYREC myrec; > > > rc = VmxGet(&nDatasetNumber, // int DatasetNumber // VIS_BUSY ? > > &cur_index, // int SelectedIndex > > &GetOpt, // int OptionParameter > > &Dummy, // Don't need a Selector param with > > these options > > &Throwaway, // Don't need returned index entry in > > this case > > &PrimaryKey, // LPBSTR lpPriKey > > (void *) &myrec); // LPVOID lpRecordStructure > > > For someone who knows C and Python, this may provide a clue to the > > BSTR passing/return problem. > > I received two emails from Dennis, included below (for completeness): > ++++++++++++++++++++++++ Start of email #1 ++++++++++++++++++++++++ > I'm back at work, hence the email. > > -=-=-=-=-=-=- > So, now the problem is with: > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > LPSTR] > I am not sure what to put for arguments 5 and 6 now. > > I realized the need to release the BSTRs... > > read more >> I received an email from Dennis, which I have included below (for completeness): +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Last email; since I'm at the end of my analytical skills (lacking the library I can't perform tests of my own). Since the value being passed should have been the address of the BSTR structure (put a >> print "address = 0x%8.8X" % PriKey << just before the call), for it to claim it can't read 0x3433322D implies another layer of indirection in the library... in that it must have used the passed address to pick up the first four bytes of the string portion of the BSTR, and is then trying to treat /that/ as the address to what it expects to really be the BSTR (subtracting four from that to get to the expected length field). My last try therefor... Try changing the argtype to a pointer-to-long (or whatever pointer types have been defined). Then pass >> byref(c_int32(PriKey)) << (Have we gone full circle yet?) My hope is that, based upon the above evaluation, this final attempt will pass an address pointing TO the address stored in the c_int32, and that the library will use /that/ address to get to the BSTR itself. I'd also suggest that, just for safety, you hold onto a reference to the original allocations... Just in case the library really intends to allocate internally and change the pointer value being passed (you may need to encapsulate it outside of the library call: ci_PriKey = c_int32(PriKey) do library call: ... , byref(ci_PriKey), ... if ci_PriKey.value != PriKey: # you were returned a new buffer Don't forget to treat the other BSTR the same way... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ I would have gladly provided the dll in question if you had requested it. Anyway, I added the following, for completeness: LPLONG = POINTER(c_long) And, then: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPLONG, LPLONG, LPSTR] print "\nVmxGet test - looking for valid record..." printf ("Before - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(ci_SecKey), byref(ci_PriKey), TypeDef ) printf ("After - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) printf ("Record returned = \x22%s\x22\n", TypeDef.raw) printf (" Key returned = \x22%s\x22\n", string_at(ci_PriKey.value, 41)) printf ("2ndKey returned = \x22%s\x22\n", string_at(ci_SecKey.value, 41)) And this is what I got: VmxGet test - looking for valid record... Before - PriKey = 0x0044F56C, SecKey = 0x0044F534 ci_PriKey = 0x0044F56C, ci_SecKey = 0x0044F534 After - PriKey = 0x0044F56C, SecKey = 0x0044F534 ci_PriKey = 0x0043D49C, ci_SecKey = 0x0043D484 Record returned = "MSD19DN Testing Board Of E ducation 4 " Key returned = "MSD19DN" 2ndKey returned = "MSD19DN" PERFECT! Now, I just have to write some wrapper code and I should be able to turn this set of calls into a VB/ISAM object, that can then be instantiated for each file I need. Dennis, thank you very much for all of your wonderful contributions. From siona at chiark.greenend.org.uk Thu Mar 13 10:52:25 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Mar 2008 14:52:25 +0000 (GMT) Subject: Get cgi script to begin execution of another script... References: Message-ID: sophie_newbie wrote: >Basically I've a CGI script, that when executed by the user, I want to >call another script that does a very long running task (10 hours +) >and print a message on the screen saying that the user will be emailed >on completion of the very long task. The script executing the very >long task will then email the user on completion. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 was helpful to me in solving this problem. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From gagsl-py2 at yahoo.com.ar Tue Mar 25 01:49:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 02:49:01 -0300 Subject: Does python hate cathy? References: Message-ID: En Tue, 25 Mar 2008 02:09:58 -0300, Edward A. Falk escribi?: > However, Adding > > self.myclass = Person > > to the __init__() method didn't stop the problem. I thought it might, > because > then each of the objects would have held a reference to Person. > Actually, I would > have thought they'd hold a reference by merely existing, so is this not > a bug? Yes, they already have a reference (self.__class__). The problem is that __del__ references Person by *name*, and that name is reset to None (like all other module globals) as part of the interpreter shutdown sequence. Using self.__class__ would avoid this particular bug, but in general, it's better not to rely on __del__ at all. See http://bugs.python.org/issue1513802 and http://bugs.python.org/issue1717900 -- Gabriel Genellina From dickinsm at gmail.com Wed Mar 12 13:25:50 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 12 Mar 2008 10:25:50 -0700 (PDT) Subject: ValueError in pickle module during unpickling a infinite float (python 2.5.2) References: <4b9d0896-df9c-47b6-98b6-16f825d67975@i7g2000prf.googlegroups.com> Message-ID: On Mar 12, 11:22 am, r... at iwm.mw.tu-dresden.de wrote: > Unpickling an infinite float caused a ValueError in the pickle module. > I need to pickle and load infinite floats in my project. Do you have > any suggestions how to solve the issue? Have you tried this on the recent 2.6 alpha (Python2.6a1)? It's available from http://www.python.org/download/releases/2.6/ I suspect it may already be fixed there. In any case, it would be useful if you could file a bug report at http://bugs.python.org. It's not absolutely clear to me that this constitutes a bug (though I think it does), but it would be worth having people look at it. I'm assuming that you're on Windows? I can't reproduce the problem on OS X. Mark From exarkun at divmod.com Thu Mar 27 10:44:24 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 27 Mar 2008 09:44:24 -0500 Subject: Psyco alternative In-Reply-To: <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: <20080327144424.6859.79559712.divmod.quotient.23555@ohm> On Thu, 27 Mar 2008 15:19:11 +0100, "Diez B. Roggisch" wrote: >> Ok, i know this. The one that i do not know, is if, let'say, in 2 >> years it will be ready for seriously development, PyPy will aim to >> "replace" CPython entirely ?? We are talking about an whole new >> distribution ? > >Most certainly not. It's the goal of each language to finally become >self-hosted, and I hope we see that for python. But that's nothing that >will happen anytime soon (soon being at least half a decade), and most >probably not for the 2.x-versions. PyPy is self-hosted and has been for some time (a year or so?). Maybe you're saying that PyPy won't replace CPython for at least five years? Could be; prediction is hard. ;) PyPy is between 1x and 3x slower than CPython for a lot of things, which isn't so much of a difference. A bigger obstacle is the availability of third-party extension modules which currently must be re-implemented in order to be available on PyPy. This could easily take half a decade without a full-time or otherwise concerted effort. Jean-Paul From diffuser78 at gmail.com Mon Mar 10 00:26:41 2008 From: diffuser78 at gmail.com (DanielJohnson) Date: Sun, 9 Mar 2008 21:26:41 -0700 (PDT) Subject: BitVector Message-ID: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Hi, I am trying to solve a genetic algorithm problem where I want to read a bitvector of very large size (say 10000) and manipulate bits based on certain algorithms. I am a newbie in Python. What data structure are good to read such huge data set. Are there any built in classes for bit fiddling. Every help is greatly appreciated, Thanks From brett at python.org Sun Mar 2 19:58:35 2008 From: brett at python.org (Brett Cannon) Date: Sun, 2 Mar 2008 16:58:35 -0800 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: On Sun, Mar 2, 2008 at 4:52 PM, Fred Drake wrote: > On Mar 2, 2008, at 7:43 PM, Fred Drake wrote: > > 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: > > > Neither does 2.3.7 now that I've tried that: > > gcc -u __dummy -u _PyMac_Error -framework System -framework > CoreServices -framework Foundation -o python.exe \ > Modules/python.o \ > libpython2.3.a -ldl > Undefined symbols: > "__dummy", referenced from: > ld: symbol(s) not found > collect2: ld returned 1 exit status > make: *** [python.exe] Error 1 > > Of course, I wasn't using an earlier 2.3.x version on this box. I > would really like to be able to use 2.4.5, since I've been using 2.4.4 > for work for a while now. For me on OS X 10.5.2 (gcc 4.0.1) for 2.37 I am getting a ton of: sem_post: Bad file descriptor sem_init: Function not implemented sem_trywait: Bad file descriptor -Brett From hniksic at xemacs.org Tue Mar 25 11:59:59 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Mar 2008 16:59:59 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: <87iqzaeqv4.fsf@mulj.homelinux.net> Brian Lane writes: > Basically, you can't do what you are trying to do without using a > different variable, ...or abusing the __foo private identifier trick. From mcohoon at gmail.com Sat Mar 15 16:35:10 2008 From: mcohoon at gmail.com (mpc) Date: Sat, 15 Mar 2008 13:35:10 -0700 (PDT) Subject: Python Generators Message-ID: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> HI all, I am trying to write a while loop that will iterate over generators to capture all the headers of FFCache directories. However, the generators embedded within the argument of another generator do not seem to re-initiate. the example below loops through and initiates the generator embedded in the argument only once. Can anyone explain while the generator will not re-initiate, and suggest a simple fix? #!/usr/bin/env python import os,struct,time def generate_headers(cachedir): for name, blocksize in cachefiles: pathname = os.path.join(cachedir,name) f = open(pathname,"rb") f.seek(4096) while True: header = f.read(36) if not header: break fields = struct.unpack(">9I",header) if fields[0] == 0x00010008: yield f, fields fp = f.tell() offset = fp % blocksize if offset: f.seek(blocksize - offset,1) f.close() def concatenate(sequences): for seq in sequences: for item in seq: yield item all_caches = (path for path,dirlist,filelist in os.walk("/Users/") if '_CACHE_MAP_' in filelist) cachefiles = [('_CACHE_001_',256),('_CACHE_002_',1024),('_CACHE_003_', 4096)] n = 0 while True: n += 1 time.sleep(0.5) headers = concatenate(generate_headers(path) for path in all_caches) for h in headers: print h,n # this doesn't work either while True: n += 1 time.sleep(0.5) for path in all_caches: headers = generate_headers(path) for h in headers: print h,n # however if I hard code the path path = "FFCache" while True: n += 1 headers = generate_headers(path) for h in headers: print h,n #but of course i do not wish to hard code the path. From johnmfisher at comcast.net Thu Mar 27 20:05:12 2008 From: johnmfisher at comcast.net (John Fisher) Date: Thu, 27 Mar 2008 17:05:12 -0700 Subject: keyboard "interrupt" References: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Message-ID: <1ieh0b3.iukc151nfftuiN%johnmfisher@comcast.net> Arnaud Delobelle wrote: > John Fisher wrote: > > Hi Group, > > Hi John > > > I have been absent a while, mainly because I have been getting better at > > figuring out my own Python problems. But not this one... > > > > I have a timed loop performing certain tasks until a total period of > > time has elapsed. I would like to be able to interrupt the loop or set > > various flags during execution via keyboard input. raw_input seems to > > just stop everything cold. I want the ability to just sacn the keyboard > > buffer and see if something is there, then proceed normally in the loop > > if there is no input in the buffer. Make sense? Totally easy? Let me > > know... > > If you are on a UNIX platform, you can use the curses module. > > http://docs.python.org/lib/module-curses.html > > There is a link there to a tutorial, but it seems to be broken. A > quick search finds it there: > > http://www.amk.ca/python/howto/curses/ > > HTH > > -- > Arnaud Thanks for your reply Arnaud. I am using an Intel mac, running Leopard 10.5.2, so that's Posix I warrant. I will check this out. JF From skip at pobox.com Thu Mar 27 11:25:01 2008 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Mar 2008 15:25:01 +0000 (UTC) Subject: Is subprocess.Popen completely broken? References: <16651e80803270805q399b1c17mec7703c0017cbac0@mail.gmail.com> Message-ID: Jerry Hill gmail.com> writes: > It's looking for an executable named "ls /tmp" Since it can't find > one, it raises an exception. > > If you just want to replace an os.system call, you need to pass > shell=True to Popen, like this: > proc = subprocess.Popen("ls /tmp", shell=True) > > That will get the shell to split your string into the program to be > called, and the argument(s) to the program. Alternatively, you can do > it yourself by passing a sequence to Popen: > proc = subprocess.Popen(["ls", "/tmp"]) Oh crap. Missing the comma... *sigh* Sometimes adjacent string literals can be silent killers. Sorry for the noise. Skip From grante at visi.com Fri Mar 28 18:01:57 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 22:01:57 -0000 Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> <7x4paqy0sr.fsf@ruckus.brouhaha.com> Message-ID: <13uqqml7sk05ec8@corp.supernews.com> On 2008-03-28, Paul Rubin wrote: > castironpi at gmail.com writes: >> Did everyone take the course on computer architecture? > > Yow! Does your SPEED QUEEN have CABLE? Ya know, I was thinking about trying to find an updated file of Zippy quotes for use in my .sig, but I decided that having all of the pop culture references be 30-years out of date was part of the charm. -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER? From userprogoogle-139 at yahoo.co.uk Wed Mar 5 09:47:25 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 5 Mar 2008 06:47:25 -0800 (PST) Subject: Python CGI & Webpage with an Image Message-ID: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> Hi, I have a set of CGI scripts set up and in one page (which is stored in an HTML file then printed via a python CGI) there is an image. However the image never displays, can anyone recommend a way round this problem? Kind regards, rod From stephenhorne100 at aol.com Mon Mar 17 10:13:45 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 07:13:45 -0700 (PDT) Subject: Python 3 and PEP238 division Message-ID: Is the PEP238 change to division going into Python 3 as planned? I realise that the new integer division semantics have been available in "from __future__" for quite a few years now, but a warning might be appropriate now that Python 3 is in alpha. A lot of people have probably either forgotten, or else never knew about PEP238. The following wording is still included in the Python 2.5.1 documentation... """ 3.1.1 Numbers The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example: >>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> 2+2 # and a comment on the same line as code 4 >>> (50-5*6)/4 5 >>> # Integer division returns the floor: ... 7/3 2 >>> 7/-3 -3 """ Which is interesting, since neither Pascal nor C division works like that. Pascal has a separate 'div' operator for integer division. C and C++ compilers usually round toward zero IIRC, but the rounding direction is not defined in the standards. In any case, after the final adoption of PEP238, integer division in Python will generally return float results - not the rounded-to-floor integer results shown here. It might be worth brainstorming some contexts where problems are likely to occur, to help anyone trying to prepare for the change. My contribution to that would be any code that needs to partition lists into slices. The obvious cases - binary searching, sorting - are covered by libraries which should be used in preference to hand- written code, but this kind of thing can happen elsewhere. I have some code that organises a sorted list of data into a balanced tree as part of a code generation task, for example, which relies on floor division. Also, if money amounts are stored as integer numbers of pennies (which they often are, since floats represent approximate values) problems could occur with various calculations since multiplication by a fractional quantity is often represented as a multiplication followed by a division. For example adding 5% is equivalent to multiplying by 1.05, or to multiplying by 105 then dividing by 100. The latter idiom is often used to keep everything integer, which requires division results to be rounded. Use of the decimal module is probably a good idea for money amounts these days, of course. I've not used it myself but the whole point of a decimal number type would be to get exact results and the kind of rounding behaviour that accountants would expect. The real world fix would normally be to replace the / operator with //, though, in order to keep the old floor-division semantics. From jzgoda at o2.usun.pl Tue Mar 18 06:40:34 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 18 Mar 2008 11:40:34 +0100 Subject: Get actual call signature? Message-ID: Say, I have a function defined as: def fun(arg_one, arg_two='x', arg_three=None): pass Is there any way to get actual arguments that will be effectively used when I call this function in various ways, like: fun(5) => [5, 'x', None] fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] fun(5, 'something') => [5, 'something', None] (et caetera, using all possible mixes of positional, keyword and default arguments) I'd like to wrap function definition with a decorator that intercepts not only passed arguments, but also defaults that will be actually used in execution. If this sounds not feasible (or is simply impossible), I'll happily throw this idea and look for another one. ;) -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From http Sat Mar 29 10:26:37 2008 From: http (Paul Rubin) Date: 29 Mar 2008 07:26:37 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <656vnpF2ekcsrU1@mid.uni-berlin.de> Message-ID: <7xve35a9nm.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > > I appreciate the droll sense of humor, but do you mean to > > assert that asyncore.py supports asynchronous disk file I/O? > > As I said in an answer to the OP, I somewhat glossed over the "file" > and just read IO. And under Posix, python *does* support asynchronous > IO using the select-module. Select does nonblocking i/o but I think Donn is interpreting "asynchronous i/o" as having a narrower meaning. See: http://www.ibm.com/developerworks/linux/library/l-async/ for some info. From luismgz at gmail.com Sat Mar 29 10:03:16 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sat, 29 Mar 2008 07:03:16 -0700 (PDT) Subject: Psyco alternative References: <10d4e6b6-71f3-4c22-8b13-17dd32a4374f@c19g2000prf.googlegroups.com> Message-ID: On 27 mar, 13:14, king kikapu wrote: > > One reason attention is going to PyPy instead of Psyco... > > > Jean-Paul > > I had a look at PyPy, it, indeed, have a very long way to go so we can > consider it an alternative. To see how it?s going, you can check this out: http://morepypy.blogspot.com/ From pistacchio at gmail.com Wed Mar 12 10:24:55 2008 From: pistacchio at gmail.com (Gustavo DiPietro) Date: Wed, 12 Mar 2008 15:24:55 +0100 Subject: a Roguelike in Python References: Message-ID: Mdonle at gmail.com ha scritto: > Seeing the 7DRL start up recently, i wanted to see what one was made > of. Python is the language i'm most familiar with so i searched for > some code to look at, but i couldn't find any. Can anyone direct me to > the right place? > > I did some searching on what it would take to write a roguelike in > python and it looked like the curses module would work perfectly, but > it looks to me like it doesn't work in windows? I tried to import it > and it says 'No Module named _curses' > > Sorry if all this sounds a bit noobish, it's only cause i am. i made some pythonesque RL experiments myself. what you have preinstalled is a wrapper for the actual library (that you need to download saperately here http://adamv.com/dev/python/curses/ ). iirc, just unzip & paste in your python/curses directory under Lib From gherron at islandtraining.com Tue Mar 11 21:36:39 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 11 Mar 2008 18:36:39 -0700 Subject: how to pass the workspace ? In-Reply-To: <47D72CDD.9000706@gmail.com> References: <47D72CDD.9000706@gmail.com> Message-ID: <47D733A7.2070808@islandtraining.com> Stef Mientki wrote: > hello, > > I've GUI tree with drag and drop nodes, > where each nodes contains a code snippet. > Now I want to run one or more branches in that tree, > so I enumerate over the nodes and have to run something like this: > > execfile ( node1 ) > execfile ( node2 ) > etc.. > > Now how do I pass the workspace created in node1, to node 2, etc ? > > thanks, > Stef Mientki > RTFM! In particular: http://docs.python.org/lib/built-in-funcs.html#l2h-26 Gary Herron From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 09:03:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 13:03:11 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: <13uv3sftpjvi6e3@corp.supernews.com> On Sun, 30 Mar 2008 10:55:25 +0000, Steven D'Aprano wrote: > Perhaps it's time for me to take a different approach. Since I can't > call timeit, and I can't inherit from it (same problem with state being > shared between instances), perhaps I should write my own timer. > > > import timeit > import gc > import itertools > > def timeit2(func, args=[], kwargs={}, it=None, > timer=timeit.default_timer): > if it is None: it = itertools.repeat(None, timeit.default_number) > save_gc = gc.isenabled() > gc.disable() > try: > start = timer() > for counter in it: > func(*args, **kwargs) > end = timer() > finally: > if save_gc: > gc.enable() > return end - start I've done some comparisons, and the times reported by this function are consistently almost double that of times reported by timeit. Now, I don't expect that my code and the timeit code should have the same overhead, and I realise that the variability of timer results is large. But I'm quite surprised that this seems to have so much more overhead. Can anyone offer some advice? -- Steven From arnodel at googlemail.com Sat Mar 22 07:07:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 04:07:33 -0700 (PDT) Subject: function-class frustration References: <740f8b7f-7d1a-4f98-96c9-71e58e6a8519@u10g2000prn.googlegroups.com> Message-ID: On Mar 22, 10:07?am, John Machin wrote: > On Mar 22, 7:19 pm, castiro... at gmail.com wrote: > > > > > On the other hand, are you willing to make changes to the console? > > How big and what? ?I was thinking of __ to keep the second-to-last > > most recent command. > > Access to and editing of previous input lines is already provided by > the cooked mode of the console (e.g. on Windows, lean on the up-arrow > key) or can be obtained by installing the readline package. Perhaps by > analogy with _, you mean the *result* of the penultimate *expression*. > This functionality would be provided by the Python interactive > interpreter but it's not ... do have a look at IPython (http:// > ipython.scipy.org/moin/About); I don't use it but I get the impression > that if it doesn't already keep a stack or queue of recent results, > you could implement it yourself easily. As you guessed, __ and ___ have the expected meaning in IPython. moreover the nth output in the session is stored in _n. -- Arnaud From jasong at gmail.com Tue Mar 4 20:50:49 2008 From: jasong at gmail.com (Jason) Date: Tue, 04 Mar 2008 19:50:49 -0600 Subject: multiplication of lists of strings Message-ID: How could I return a list or tuple of each unique combination of a given set of lists (perhaps from a dict or a list). This means the number of lists are not known nor is the length of each. Here is an example: fruit = ['apple', 'orange'] numbers = ['one', 'two', 'three'] names = ['joe'] Order matters (I started by trying to iterate over a list corresponding to keys in the dict that contains these lists). Furthermore, (a, b) is different from (b, a) however I will filter out all but unique (a, a) if that occurs. Once this step is solved, I then will use each tuple as a key in a dict. I appreciate any assistance you can throw my way. Jason G From egonslokar at gmail.com Thu Mar 27 17:02:53 2008 From: egonslokar at gmail.com (egonslokar at gmail.com) Date: Thu, 27 Mar 2008 14:02:53 -0700 (PDT) Subject: Tips Re Pattern Matching / REGEX Message-ID: <7ebb329d-12e0-42d8-a543-15521d1ecc46@u10g2000prn.googlegroups.com> Hello Python Community, I have a large text file (1GB or so) with structure similar to the html example below. I have to extract content (text between div and tr tags) from this file and put it into a spreadsheet or a database - given my limited python knowledge I was going to try to do this with regex pattern matching. Would someone be able to provide pointers regarding how do I approach this? Any code samples would be greatly appreciated. Thanks. Sam \\ there are hundreds of thousands of items \\Item1
123
....
Text1: What do I do with these lines That span several rows?
... Foot \\Item2
First Line Can go here But the second line can go here
... Foot Can span Over several pages \\Item3
First Line Can go here But the second line can go here
...
This can Span several rows
From tms at zeetix.com Sun Mar 16 06:56:38 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sun, 16 Mar 2008 06:56:38 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <002101c88754$6989f2b0$0200a8c0@TMSMAIN> I want to thank this community -- especially Carsten Haese -- for your patience with my confusion and for your several suggestions about how to resolve the issue. As a newcomer to python-list, I appreciate your willingness to respond to my request and your graciousness in helping me see the contribution I made to my issue. I now see that, as is often the case, I was asking the wrong question. The immediate problem that this exchange helped me identify is that I needed to escape the json string *again* on its way through my html wrapper. The far more elegant approach sketched by Carsten is the simple act of dropping the apostrophes in my own wrapper. I love that! It works, it's elegant, and it typifies the things that an outside "pair of eyes" can see far more immediately than me. Thank you, Carsten. All in all, this was an extraordinarily helpful exchange. Thank you all, and I hope I can perhaps make similar contributions. From dickinsm at gmail.com Tue Mar 11 10:50:41 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 07:50:41 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> Message-ID: <913818fb-5190-4d16-8376-fe58c4b8bc67@b64g2000hsa.googlegroups.com> On Mar 10, 7:32?pm, Nathan Pinno wrote: > Thanks on the factoring bit, but I did mean factorial, not factoring. > How do I code that correctly, so that I can figure the following > equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax > error and highlight the !. So it would be nice to find a way to solve > such a problem. Aha. I've just found the "Is there a mathematical formula that will find prime numbers?" thread that you started over on sci.math. It looks like at least one of us has been trolled. I suggest you: (1) Ignore the formula Gerry gave you. It's completely impractical as a way of determining primality, and I'm certain that Gerry knew this. (2) Learn some elementary number theory before trying to crack RSA. Mark From castironpi at gmail.com Mon Mar 3 21:31:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 18:31:38 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <2aceec91-618d-4e62-9958-e223505bc51f@13g2000hsb.googlegroups.com> Message-ID: > All software has bugs. > Good software has bugs. Therefore, good software is software. > This makes sympy worse than worthless, as it f***s up other modules. What is it still good for? From gagsl-py2 at yahoo.com.ar Fri Mar 28 19:09:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 20:09:34 -0300 Subject: How to insert multiple rows in SQLite Dbase References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 18:05:29 -0300, afandi escribi?: > Generally, it involves SQL statement such as > follow > > INSERT INTO (field1,field2,.......fieldn) VALUES > ('abc','def'...........) > > If I have data taken from Apache Server Log,let say 100 lines which > is printed output of 8 fields such > as: > > data 1 > IP: 61.5.65.101 > Date: 26/Sep/2007 > Time: 20:43:25 > GMT: +0900 > Requestt: GET /index.php?option=com_content&task=view&id=55&Itemid=19 > HTTP/1.1 > ErrorCode: 200 > Bytes: 6458 > Referel:http://www.joomla.org/index.php? > option=com_content&task=view&id=35&Itemid=19 > Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) > Gecko/20070515 Firefox/2.0.0.4 >How toI insert into SQLite database? by using SQL statement.TQ sqlite3 allows for named parameters; see http://docs.python.org/lib/sqlite3-Cursor-Objects.html You should build a list of dictionaries, with a dictionary per log entry, and call the executemany cursor method. Assuming you have a table created like this: create table log ( IP text, EntryDate timestamp, Requestt text, ErrorCode integer ) you should build a list like this: values = [ {'ip': '61.5.65.101', 'date': a datetime object combining all parts, 'request': "GET /index.php?op...", 'errorcode': 200, }, {'ip': '21.5.65.101', 'date': a datetime object, 'request': "...", 'errorcode': 200, }, ... ] and execute: cur.executemany("insert into log (IP, EntryDate, Requestt, ErrorCode) values (:ip, :date, :request, :errorcode)", values) -- Gabriel Genellina From misceverything at gmail.com Sat Mar 29 10:58:03 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sat, 29 Mar 2008 07:58:03 -0700 (PDT) Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: On Mar 28, 4:53 pm, Tim Golden wrote: > misceveryth... at gmail.com wrote: > > Hello, > > > I would like to write a script that would enumerate all running > > processes and return the full path to the EXE of each running > > process. However, I can't seem to find any good info on how to do > > this..any help is greatly appreciated. Thanks. > > I have this strange feeling of deja vu. Try this: > > http://timgolden.me.uk/python/wmi_cookbook.html#running_processes > > (You want the .ExecutablePath or .CommandLine attributes I imagine) > > TJG Thanks, Tim! I was able to find plenty out there about enumerating processes, but the .ExecutablePath was exactly what I needed. From jura.grozni at gmail.com Thu Mar 13 12:31:38 2008 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Mar 2008 09:31:38 -0700 (PDT) Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> <63t1tnF29egotU1@mid.uni-berlin.de> Message-ID: I thought of using Temp files but I am afraid of the JPG destorsion while saving because of the compresion.I am looking for a way to directly transform it. On Mar 13, 5:09?pm, "Diez B. Roggisch" wrote: > azrael wrote: > > A little problem. > > > Can I directly show Pil objects "image.open("bla.jpg") in Wx or do I > > have to transform them. > > > If I have to transofm them How can I do it. Pixel by pixel or is there > > somethin built in in pil or wx or python. > > pilj->wx and wx->pil. > > PIL doesn't depend on wx, so if anything then wx knows about PIL. But I > doubt it. Instead, use cStringIO and save a PIL-Image to memory, then use > that as file-argument to something that works for wx - no idea what, but > there should be means to load JPEGs and so forth. > > If file-objects aren't enough, create a temp-file. No, that's not to slow. > > Diez From pradiprai at gmail.com Mon Mar 31 08:05:35 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 17:35:35 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Thanks !! I will try do so. Regards, Pradeep -On [20080331 12:56], Pradeep Rai (pradiprai at gmail.com) wrote: >Can you guide me how to install a 2.5 version of dbi for it to work ? Same way you installed dbi for 2.4 just make sure the called python executable is the 2.5 one. -- Jeroen Ruigrok van der Werven / asmodai CF[ EtbN @ f EFF *http://www.in-nomine.org/* | * http://www.rangaku.org/* Sometimes things stare us in the face and we are too blind to see... -------------- next part -------------- An HTML attachment was scrubbed... URL: From Martin.vonLoewis at hpi.uni-potsdam.de Tue Mar 11 16:23:06 2008 From: Martin.vonLoewis at hpi.uni-potsdam.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 11 Mar 2008 21:23:06 +0100 Subject: [ANN] Python 2.3.7 and 2.4.5 (final) Message-ID: <47D6EA2A.3060008@hpi.uni-potsdam.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.5 and 2.3.7 (final). Both releases include only security fixes. Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.3 or 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). Since the release candidate, we received various reports that the this release may fail to build on current operating systems, in particular on OS X. We have made no attempt to fix these problems, as the release is targeted for systems that were current at the time Python 2.4 was originally released. For more recent systems, you might have to come up with work-arounds. For OS X in particular, try invoking:: ./configure MACOSX_DEPLOYMENT_TARGET=10.5 We have made no changes since the release candidate (except for the version numbers). For more information on Python 2.3.7 and 2.4.5, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3.7 http://www.python.org/2.4.5 Highlights of the previous major Python releases are available from the Python 2.4 page, at http://www.python.org/2.3/highlights.html http://www.python.org/2.4/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From gagsl-py2 at yahoo.com.ar Thu Mar 27 15:33:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 16:33:06 -0300 Subject: Regarding __slots__ and other stuff: A couple of questions References: Message-ID: En Thu, 27 Mar 2008 11:27:42 -0300, dave berk escribi?: > *first:* > Why doesn't this works? > >>>> class C(object): > ... __slots__ = ['foo', 'bar'] > ... class_attr = 'class attribute' > ... >>>> c = C() >>>> c.foo = 'foo' >>>> c.bar = 'bar' >>>> c.bar, c.foo > ('bar', 'foo') >>>> c.__slots__ > ['foo', 'bar'] >>>> c.__slots__.append('eggs') >>>> c.__slots__ > ['foo', 'bar', 'eggs'] >>>> c.eggs = 'eggs' > Traceback (innermost last): > File "", line 1, in > AttributeError: 'C' object has no attribute 'eggs' > Because the __slots__ attribute is used when the object is constructed, to reserve space in its structure for those (and only those) attributes. That's the whole point of using __slots__: not creating the generic __dict__ container for all instances to save memory. > *second:* > what happens here? Why can I write to spam using the class object but not > the using the instance? > >>>> class C(object): > ... __slots__ = ['foo', 'bar'] > ... class_attr = 'class attribute' > ... >>>> C.spam = 50 >>>> C.spam > 50 >>>> C.spam = 56 >>>> c = C() >>>> c.spam = 55 > Traceback (innermost last): > File "", line 1, in > AttributeError: 'C' object attribute 'spam' is read-only C *instances* are affected by the __slots__ defined in the C *class*, but the C class itself is not. The C class would be affected by a __slots__ defined in its type (the metatype) but since there exist only one C class object, that optimization would be useless. If you were dynamically creating thousands of classes one might consider the point... > *Third:* > > class RevealAccess(object): > """A data descriptor that sets and returns values > normally and prints a message logging their access. > """ > > def __init__(self, initval=None, name='var'): > self.val = initval > self.name = name > > def __get__(self, obj, objtype): > print 'Retrieving', self.name > return self.val > > def __set__(self, obj, val): > print 'Updating' , self.name > self.val = val > class A(object): > def __init__(self): > self.x = RevealAccess(10, 'var "x"') > self.y = 5 > class B(object): > x = RevealAccess(10, 'var "x"') > y = 5 > >>>> a = A() >>>> b = B() >>>> a.x > <__main__.RevealAccess object at 0x00BAC730> >>>> a.x = 55 >>>> b.x > Retrieving var "x" > 10 >>>> b.x = 55 > Updating var "x" >>>> > > Why the descriptor works only when created as a static variable and not > as an instance variable? It's not a "static variable", it's a "class attribute". Classes are objects too, like functions, methods, code... [almost] everything in Python is an object. The descriptor protocol isn't used when retrieving attributes directly from the instance namespace (__dict__), this is a plain dict access. When you say self.x = RevealAccess(...) you are storing the RA instance directly in the instance namespace. Only when retrieving objects from the *class* the descriptor protocol comes into play. -- Gabriel Genellina From rockxuan at gmail.com Tue Mar 18 03:39:51 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:39:51 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 07:07:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 11:07:10 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: <13uut2uabcbok38@corp.supernews.com> On Sat, 29 Mar 2008 22:11:33 -0700, hdante wrote: > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: > > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) > > ;-) Back in the 1990s, Apple's Hypercard accepted ? for "not equal". Of course, Macs made it easy to type such special characters. By memory you held down the Option key and typed an equals sign. For ? you used Option and less-than. That worked in *any* Mac application. Ah, glory days. But I digress. In Python we can write the above as: if x != 0: [f1(y) if y >= 0 else f2(y) for y in s] which for those not trained in algebra is probably more readable. -- Steven From celoserpa at gmail.com Wed Mar 5 15:18:00 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Wed, 5 Mar 2008 17:18:00 -0300 Subject: Def generating a function to be ran in another context Message-ID: <1e5bcefd0803051218q1e73cea2m600ea73098171431@mail.gmail.com> I'd like a certain function to generate a method for another class and this new method to be called in the context of the "new" class. Is it possible with Python? Thanks, Marcelo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhearne808 at gmail.com Tue Mar 18 12:19:55 2008 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Tue, 18 Mar 2008 09:19:55 -0700 (PDT) Subject: Problems building zlib module on RHEL References: Message-ID: <2896c3a8-82f0-4b3e-a840-0bfae7909d84@2g2000hsn.googlegroups.com> On Mar 18, 8:42 am, "mhearne808[insert-at-sign-here]gmail[insert-dot- here]com" wrote: > I can't seem to get the zlib module to build on an RHEL box. > > I did the following: > 1) Download zlib 1.2.3 > 2) configure;make;make install > 3) Download python 2.5.2 > 4) configure;make;make install > 5) >>> import zlib => "ImportError: No module named zlib" > > In the make install step for python, I notice there are the following > errors: > > building 'zlib' extension > gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/ > Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ > lib.linux-x86_64-2.5/zlib.so > /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 > against `a local symbol' can not be used when making a shared object; > recompile with -fPIC > /usr/local/lib/libz.a: could not read symbols: Bad value > collect2: ld returned 1 exit status > > Does anyone have any hints on how to get around this? > > system info: > kernel : 2.6.9-67.0.1.ELsmp > gcc : 3.4.6 > > Thanks, > > Mike I figured it out, although it wasn't obvious... You have to compile zlib as a shared library by running "configure -s". From troworld at gmail.com Wed Mar 5 01:16:00 2008 From: troworld at gmail.com (Tro) Date: Wed, 5 Mar 2008 01:16:00 -0500 Subject: Altering imported modules In-Reply-To: References: <200803011856.27611.troworld@gmail.com> <200803041004.50553.troworld@gmail.com> Message-ID: <200803050116.00819.troworld@gmail.com> On Tuesday 04 March 2008, Steve Holden wrote: > >> Are you trying to interfere with the default module on only your > >> machine? Just rename it. If something in the std. lib. imports > >> asyncore, they get yours too that way. > > > > No, I'd like it to be a generalized solution and only for this one > > project. I'm trying to get it to work on any recent python installation > > out of the box, so I can't rename built-in modules. What I'm trying to do > > is allow a 3rd party module (tlslite) to import *my* version of asyncore > > without me going into tlslite's code and changing its import statement > > explicitly, but only for the scope of this one project. > > In that case try something like > > import myasyncore as asnycore > sys.modules['asyncore'] = asyncore > import tlslite Ah. That's what I've been looking for. Thanks! Tro From sean at ardishealth.com Mon Mar 17 13:43:46 2008 From: sean at ardishealth.com (Sean Allen) Date: Mon, 17 Mar 2008 13:43:46 -0400 Subject: Apache binary error? In-Reply-To: References: Message-ID: <22AA51C6-08C4-4E19-B79A-C2C280D9F442@ardishealth.com> On Mar 17, 2008, at 10:55 AM, Michael Wieher wrote: > have simple webpage running > > apache, mod_python > > the error is binary.... > ...binary as in "every other" time I load the page, Firefox keeps > telling me I'm downloading a python script, and asks to open it in > WINE, which is really strange. > > then, alternately, it loads the page just fine. any clues as to why > this is happening? > -- for anything like mod_perl, mod_python etc the first thing i do when i get really weird errors it move to having only one apache process for testing. might want to start there. From sjmachin at lexicon.net Wed Mar 19 19:16:36 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 16:16:36 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: On Mar 20, 9:14 am, sturlamolden wrote: > On 19 Mar, 22:48, John Machin wrote: > > > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > > and is IMHO more readable than Paul's. > > Is a Python set implemented using a hash table? What don't you understand about the comments in the first two screenfuls of Objects/setobject.c? From atom.anderson at gmail.com Sun Mar 23 23:00:28 2008 From: atom.anderson at gmail.com (Atom) Date: Sun, 23 Mar 2008 20:00:28 -0700 (PDT) Subject: PyCon video editing References: <0ed1ce28-b517-4c17-b12e-7d6554f5274a@x41g2000hsb.googlegroups.com> Message-ID: <0ba1eb7f-9946-4440-a257-23f00c7d8075@i7g2000prf.googlegroups.com> On Mar 18, 8:09 am, amk wrote: > On Mar 17, 10:00 pm, dundeemt wrote: > > > Anyone know who is in charge of this? I'd like to help out if I > > could. > > I am, but haven't set anything up yet, such as a mailing list or a > host for the video. > I'll update the wiki pagehttp://wiki.python.org/moin/PyConRecordingBof > with news/further developments (you can create a wiki account and > follow the envelope icon at the upper right > to be notified of changes via e-mail). > > --amk I'm eager to get my hands on some of these videos! I'll be following the wiki for details. Thanks. -adam From arbo.newmedia at gmail.com Wed Mar 5 09:37:44 2008 From: arbo.newmedia at gmail.com (arbo.newmedia at gmail.com) Date: Wed, 5 Mar 2008 06:37:44 -0800 (PST) Subject: Leopard and MySQL References: <929700bd-89e6-4fb9-ac02-558841cb939e@i12g2000prf.googlegroups.com> Message-ID: On 5 Mar, 13:40, martin.lal... at gmail.com wrote: > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html. When you > search for your problemhttp://www.nabble.com/forum/Search.jtp?forum=2970&local=y&query=mysqldb > > you have the solutionhttp://www.nickshanny.com/2007/10/os-x-105-python-and-mysqldb.html Thanks a lot. From paul at boddie.org.uk Fri Mar 28 14:06:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 28 Mar 2008 11:06:17 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: <2f3a59c2-ef31-426a-be34-bdb187ea3b22@c19g2000prf.googlegroups.com> On 27 Mar, 15:19, "Diez B. Roggisch" wrote: > [Psyco maintenance and further development] > Nope, but I heard through the grapevine that while it won't be supported for > all times to come, a new version is in the making. > > But ultimately, the author says that the approach is flawed, so at *some* > point it will be discontinued. But that could be said about nearly > everything, couldn't it? >From what I've seen from browsing publicly accessible materials, there's a certain commercial interest in seeing Psyco updated somewhat. So, whether it gets discontinued depends on the usual factors of satisfying a need and there being qualified and motivated people to work on it. Paul From exarkun at divmod.com Thu Mar 27 12:10:40 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 27 Mar 2008 11:10:40 -0500 Subject: Psyco alternative In-Reply-To: Message-ID: <20080327161040.6859.1465172015.divmod.quotient.23568@ohm> On Thu, 27 Mar 2008 08:59:33 -0700 (PDT), bearophilehugs at lycos.com wrote: >Diez B. Roggisch: >> the author says that the approach is flawed, so at *some* >> point it will be discontinued. > >Can't Psyco be improved, so it can compile things like: > >nums = (i for i in xrange(200000) if i % 2) >print sum(nums) > Sure, it can be. That doesn't mean it will be. Someone has to do it. :) One reason attention is going to PyPy instead of Psyco is that PyPy's JIT doesn't require as much careful attention to support and maintain support for features like generators. Jean-Paul From samuel.progin at gmail.com Thu Mar 6 07:15:17 2008 From: samuel.progin at gmail.com (Sam) Date: Thu, 6 Mar 2008 04:15:17 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: Hello if type(a) is dict: print "a is a dictionnary!" ++ Sam From miki.tebeka at gmail.com Wed Mar 26 18:11:38 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 26 Mar 2008 15:11:38 -0700 (PDT) Subject: first interactive app References: Message-ID: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Hello Tim, > I want to write a tiny interactive app for the following situation: > I have books of many chapters that must be split into volumes before going > to the printer. > A volume can have up to 600 pages. We obviously break the book into volumes > only at chapter breaks. Since some chapters make a natural grouping, we want > some human interaction for where the volume breaks occur. > > Not having experience with interactive apps, I'm asking for advice about how > to go about it. The data I start with is just a dictionary with chapter name > = ending page number. I figured I would first show where the volumes would > break with no human interaction, with the begin and ending chapter > names/pagenumbers for each volume. > > From here I thought about having a slider for each volume, but the number of > volumes could change during the session. > Or maybe I should just ask 'enter the ending chapter for the first volume' > and recalculate, etc until all volumes are defined. > > Any ideas on a simple interface for this? How about something like: Chapter 1 (001-200 200) Chapter 2 (200-300 100) ------ 001-300 300 ---- Chapter 3 (300-450 150) Chapter 4 (450-500 50) ------ 300-450 250 ---- Chapter 5 (500-600 100) ------ 500-600 100 ---- Where the user can move the divider up and down to create new volume, they can also add and delete dividers. The program will not allow to drag the divider above the 600 page limit. HTH, -- Miki http://pythonwise.blogspot.com From roy at panix.com Sun Mar 2 16:52:27 2008 From: roy at panix.com (Roy Smith) Date: Sun, 02 Mar 2008 16:52:27 -0500 Subject: tuples, index method, Python's design References: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> Message-ID: In article <6d369e71-feb5-477d-a162-f6b0c4eb27f3 at k2g2000hse.googlegroups.com>, Paul Boddie wrote: > On 2 Mar, 19:06, Alan Isaac wrote: > > On April 12th, 2007 at 10:05 PM Alan Isaac wrote: > > > > > The avoidance of tuples, so carefully defended in other > > > terms, is often rooted (I claim) in habits formed from > > > need for list methods like ``index`` and ``count``. > > > Indeed, I predict that Python tuples will eventually have > > > these methods and that these same people will then defend > > > *that* status quo. > > You were more confident about this than I was. Still, nothing happens > if no-one steps up to do something about it. > > > > > > > - Issue #2025 : Add tuple.count() and tuple.index() > > > > methods to comply with the collections.Sequence API. > > Here's the tracker item that may have made it happen: > > http://bugs.python.org/issue1696444 > > I think you need to thank Raymond Hettinger for championing the > cause. ;-) > > Paul Callooh! Callay! We are delivered from one of the most long-lived and pointless (if minor) warts in an otherwise clean and logical type hierarchy. Thank you, Raymond! From jayapal.d at gmail.com Fri Mar 14 00:28:18 2008 From: jayapal.d at gmail.com (jai_python) Date: Thu, 13 Mar 2008 21:28:18 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder Message-ID: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> hi frenz I Need a Python Script For read multiple files(.txt) from a folder and write it in a single text file.... Thanks From __peter__ at web.de Sat Mar 8 12:24:05 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Mar 2008 18:24:05 +0100 Subject: SQL problem in python References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: aiwarrior wrote: > When i run it the get_value() returns 'filepath' instead of the > columns. But if i dont use any variable and make the expression static > all goes on as its supposed to. What am i doing wrong? > self.cursor.execute( "SELECT (?) FROM database", column ) In this case you have to use Python's string interpolation, or the column will be interpreted as a const value. The following should work: self.cursor.execute( "SELECT %s FROM database" % column) If you must sanitize the column name you can prepend something like if column not in allowed_names: raise ValueError Peter From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 08:09:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 12:09:11 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: <13t7kr7c5hvue90@corp.supernews.com> On Sun, 09 Mar 2008 20:57:15 +1100, Alasdair wrote: > Thanks, all - you've been most helpful. By the way, what does // do? I > haven't yet run down its definition in the manual. // is integer division. >>> 10//5 2 >>> 11//5 2 In Python 2.5 and older, / means integer division, unless you do from __future__ import division in which case / is true division, that is: >>> 10/5 2 >>> 11/5 2.5 In Python 3.x, / will always be true division, and you won't need the import. -- Steven From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 06:08:35 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 12:08:35 +0100 Subject: Pb with 2.5.2 & PyScripter Message-ID: <47c93bb8$0$874$ba4acef3@news.orange.fr> Hi, all! Since the install of Python 2.5.2, Pyscripter (1.9.9.1) close for each error. Is it only me? Or another guys have the same thing? @-salutations Michel Claveau From bronger at physik.rwth-aachen.de Sun Mar 30 09:24:30 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 30 Mar 2008 15:24:30 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> Message-ID: <87hceo73ap.fsf@physik.rwth-aachen.de> Hall?chen! Bjoern Schliessmann writes: > hdante wrote: > >> BTW, my opinion is that it's already time that programmer editors >> have input methods advanced enough for generating this: > > Could you please list some that do, and are also convenient? Define "convenient". Emacs is generally not regarded as being convenient, however, it has very strong input methods. I type "\gtrless" and get "?", or "\forall" and get "?". Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From antroy at gmail.com Tue Mar 4 07:41:51 2008 From: antroy at gmail.com (Ant) Date: Tue, 4 Mar 2008 04:41:51 -0800 (PST) Subject: News from Jython world References: Message-ID: <22628504-54af-4732-adb3-e02fd5042dce@d21g2000prf.googlegroups.com> On Mar 3, 6:40 pm, S?bastien Boisg?rault wrote: > Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a > key Jython developer and is specifically hired to work full time on > Jython, a version of the Python interpreter that runs on top of the > JVM and provides full access to Java libraries. After a period where > the development had slowed, Jython was recently getting seriously > back on track. Now it's getting even better ! Development on Jython over the last year or so has been superb, and it's good to see that Sun are getting really focused on dynamic languages on the JVM. It may be that they are trying to play keep-up with Microsoft and their support of IronPython - but regardless of the reasons it is good news for Jython and Frank W, and for the Python community in general. A Sun endorsement of Jython means the possibility of more Python jobs out there for us all in the future given the ubiquity of the JVM in the enterprise and willingness of corporations to accept such endorsements! -- Ant. From bogus@does.not.exist.com Thu Mar 13 00:47:32 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Wed, 12 Mar 2008 23:47:32 -0500 Subject: help please, splitter windows like in maya or 3ds max References: Message-ID: This seems to work... split then split each side. then tandem the size. import wx class Layout(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) sizer = wx.BoxSizer(wx.HORIZONTAL) panel = wx.Panel(self,-1) splitter = wx.SplitterWindow(panel) sizer_left = wx.BoxSizer(wx.VERTICAL) panel_left = wx.Panel(splitter,-1) splitter_left = wx.SplitterWindow(panel_left) splitter_left.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.leftChange,id=splitter_left.GetId()) panel_left_upper = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) panel_left_upper.SetBackgroundColour("WHITE") panel_left_lower = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) splitter_left.SplitHorizontally(panel_left_upper,panel_left_lower) sizer_left.Add(splitter_left,1,wx.EXPAND) sizer_right = wx.BoxSizer(wx.VERTICAL) panel_right = wx.Panel(splitter,-1) splitter_right =wx.SplitterWindow(panel_right) splitter_right.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.rightChange,id=splitter_right.GetId()) panel_right_upper = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) panel_right_lower = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) panel_right_lower.SetBackgroundColour("WHITE") splitter_right.SplitHorizontally(panel_right_upper,panel_right_lower) sizer_right.Add(splitter_right,1,wx.EXPAND) splitter.SplitVertically(panel_left,panel_right) sizer.Add(splitter,1,wx.EXPAND) panel.SetSizer(sizer) panel_left.SetSizer(sizer_left) panel_right.SetSizer(sizer_right) self.splitter_left = splitter_left self.splitter_right = splitter_right def leftChange(self,event): pos = self.splitter_left.GetSashPosition() self.splitter_right.SetSashPosition(pos) event.Skip() def rightChange(self,event): pos = self.splitter_right.GetSashPosition() self.splitter_left.SetSashPosition(pos) event.Skip() app = wx.App(0) k = Layout(None, -1, 'layout.py') k.Show(True) app.MainLoop() -- Andrew ----- Original Message ----- From: "moonrie" Newsgroups: comp.lang.python Sent: Wednesday, March 12, 2008 10:19 PM Subject: help please, splitter windows like in maya or 3ds max > hi, everyone there, I am doing a 3D modeling project. I like to do it > with Python( am a newbie), but have no idea with the wxSplitterWindow > to create the 4-view windows( top, front, side, perspective), like the > mfc CSplitterWnd guy), > anyone can give me some help with wxPython? > > thanks in advance. > > - moonrie From christypoul at gmail.com Mon Mar 24 07:51:07 2008 From: christypoul at gmail.com (bright) Date: Mon, 24 Mar 2008 04:51:07 -0700 (PDT) Subject: =?ISO-8859-1?B?aGkgZnJpZW5kcy4uLi4uLi4uLi4uIGdvb2dsZSBncm91cCBpbnZpdGVzIHlvdSBhIHdvbg==?= =?ISO-8859-1?B?ZGVyaW5nIHdvcmxkIG9mIGJ1c2luZXNzcyAuLi4uLi4uLi4uLi4uIGRvIHUgd2FudCB0byBlYXJuIG1pbA==?= =?ISO-8859-1?Q?lions_of_dollers_per_month_through_online_jobs_joined_with_me?= =?ISO-8859-1?Q?_and_find_the_way_to_earn_dollers=2E=2E=2E=2E=2E=2E=2E=2E=2E_visit_us_www=2Ejobsf?= =?ISO-8859-1?Q?oryouguys=2Eblogspot=2Eco=ADm?= Message-ID: <87f99599-cd03-4e0b-b47b-85722b69b356@e6g2000prf.googlegroups.com> hi friends........... google group invites you a wondering world of businesss ............. do u want to earn millions of dollers per month through online jobs joined with me and find the way to earn dollers......... visit us www.jobsforyouguys.blogspot.co?m From ptmcg at austin.rr.com Sat Mar 22 19:59:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Mar 2008 16:59:47 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Message-ID: <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> On Mar 22, 4:11?pm, rh0dium wrote: > Hi all, > > I am struggling with parsing the following data: > > As a side note: ?Is this the right approach to using pyparsing. ?Do we > start from the inside and work our way out or should I have started > with looking at the bigger picture ( keyword + "{" + OneOrMore key / > vals + "}" + ) ?I started there but could figure out how to look > multiline - I'm assuming I'd just join them all up? > > Thanks I think your "inside-out" approach is just fine. Start by composing expressions for the different "pieces" of your input text, then steadily build up more and more complex forms. I think the main complication you have is that of using commaSeparatedList for your list of real numbers. commaSeparatedList is a very generic helper expression. From the online example (http:// pyparsing.wikispaces.com/space/showimage/commasep.py), here is a sample of the data that commaSeparatedList will handle: "a,b,c,100.2,,3", "d, e, j k , m ", "'Hello, World', f, g , , 5.1,x", "John Doe, 123 Main St., Cleveland, Ohio", "Jane Doe, 456 St. James St., Los Angeles , California ", In other words, the content of the items between commas is pretty much anything that is *not* a comma. If you change your definition of atflist to: atflist = Suppress("(") + commaSeparatedList # + Suppress(")") (that is, comment out the trailing right paren), you'll get this successful parse result: ['0.21', '0.24', '0.6', '0.24', '0.24', '0.6)'] In your example, you are parsing a list of floating point numbers, in a list delimited by commas, surrounded by parens. This definition of atflist should give you more control over the parsing process, and give you real floats to boot: floatnum = Combine(Word(nums) + "." + Word(nums) + Optional('e'+oneOf("+ -")+Word(nums))) floatnum.setParseAction(lambda t:float(t[0])) atflist = Suppress("(") + delimitedList(floatnum) + Suppress(")") Now I get this output for your parse test: [0.20999999999999999, 0.23999999999999999, 0.59999999999999998, 0.23999999999999999, 0.23999999999999999, 0.59999999999999998] So you can see that this has actually parsed the numbers and converted them to floats. I went ahead and added support for scientific notation in floatnum, since I see that you have several atfvalues that are standalone floats, some using scientific notation. To add these, just expand atfvalues to: atfvalues = ( floatnum | Word(nums) | atfstr | atflist ) (At this point, I'll go on to show how to parse the rest of the data structure - if you want to take a stab at it yourself, stop reading here, and then come back to compare your results with my approach.) To parse the overall structure, now that you have expressions for the different component pieces, look into using Dict (or more simply using the helper function dictOf) to define results names automagically for you based on the attribute names in the input. Dict does *not* change any of the parsing or matching logic, it just adds named fields in the parsed results corresponding to the key names found in the input. Dict is a complex pyparsing class, but dictOf simplfies things. dictOf takes two arguments: dictOf(keyExpression, valueExpression) This translates to: Dict( OneOrMore( Group(keyExpression + valueExpression) ) ) For example, to parse the lists of entries that look like: name = "gtc" dielectric = 2.75e-05 unitTimeName = "ns" timePrecision = 1000 unitLengthName = "micron" etc. just define that this is "a dict of entries each composed of a key consisting of a Word(alphas), followed by a suppressed '=' sign and an atfvalues", that is: attrDict = dictOf(Word(alphas), Suppress("=") + atfvalues) dictOf takes care of all of the repetition and grouping necessary for Dict to do its work. These attribute dicts are nested within an outer main dict, which is "a dict of entries, each with a key of Word(alphas), and a value of an optional quotedString (an alias, perhaps?), a left brace, an attrDict, and a right brace," or: mainDict = dictOf( Word(alphas), Optional(quotedString)("alias") + Suppress("{") + attrDict + Suppress("}") ) By adding this code to what you already have: attrDict = dictOf(Word(alphas), Suppress("=") + atfvalues) mainDict = dictOf( Word(alphas), Optional(quotedString)("alias") + Suppress("{") + attrDict + Suppress("}") ) You can now write: md = mainDict.parseString(test1) print md.dump() print md.Layer.lineStyle and get this output: [['Technology', ['name', 'gtc'], ['dielectric', 2.7500000000000001e-005], ['unitTimeName', 'ns'], ['timePrecision', '1000'], ['unitLengthName', 'micron'], ['lengthPrecision', '1000'], ['gridResolution', '5'], ['unitVoltageName', 'v'], ['voltagePrecision', '1000000'], ['unitCurrentName', 'ma'], ['currentPrecision', '1000'], ['unitPowerName', 'pw'], ['powerPrecision', '1000'], ['unitResistanceName', 'kohm'], ['resistancePrecision', '10000000'], ['unitCapacitanceName', 'pf'], ['capacitancePrecision', '10000000'], ['unitInductanceName', 'nh'], ['inductancePrecision', '100']], ['Tile', 'unit', ['width', 0.22], ['height', 1.6899999999999999]], ['Layer', 'PRBOUNDARY', ['layerNumber', '0'], ['maskName', ''], ['visible', '1'], ['selectable', '1'], ['blink', '0'], ['color', 'cyan'], ['lineStyle', 'solid'], ['pattern', 'blank'], ['pitch', '0'], ['defaultWidth', '0'], ['minWidth', '0'], ['minSpacing', '0']]] - Layer: ['PRBOUNDARY', ['layerNumber', '0'], ['maskName', ''], ['visible', '1'], ['selectable', '1'], ['blink', '0'], ['color', 'cyan'], ['lineStyle', 'solid'], ['pattern', 'blank'], ['pitch', '0'], ['defaultWidth', '0'], ['minWidth', '0'], ['minSpacing', '0']] - alias: PRBOUNDARY - blink: 0 - color: cyan - defaultWidth: 0 - layerNumber: 0 - lineStyle: solid - maskName: - minSpacing: 0 - minWidth: 0 - pattern: blank - pitch: 0 - selectable: 1 - visible: 1 - Technology: [['name', 'gtc'], ['dielectric', 2.7500000000000001e-005], ['unitTimeName', 'ns'], ['timePrecision', '1000'], ['unitLengthName', 'micron'], ['lengthPrecision', '1000'], ['gridResolution', '5'], ['unitVoltageName', 'v'], ['voltagePrecision', '1000000'], ['unitCurrentName', 'ma'], ['currentPrecision', '1000'], ['unitPowerName', 'pw'], ['powerPrecision', '1000'], ['unitResistanceName', 'kohm'], ['resistancePrecision', '10000000'], ['unitCapacitanceName', 'pf'], ['capacitancePrecision', '10000000'], ['unitInductanceName', 'nh'], ['inductancePrecision', '100']] - capacitancePrecision: 10000000 - currentPrecision: 1000 - dielectric: 2.75e-005 - gridResolution: 5 - inductancePrecision: 100 - lengthPrecision: 1000 - name: gtc - powerPrecision: 1000 - resistancePrecision: 10000000 - timePrecision: 1000 - unitCapacitanceName: pf - unitCurrentName: ma - unitInductanceName: nh - unitLengthName: micron - unitPowerName: pw - unitResistanceName: kohm - unitTimeName: ns - unitVoltageName: v - voltagePrecision: 1000000 - Tile: ['unit', ['width', 0.22], ['height', 1.6899999999999999]] - alias: unit - height: 1.69 - width: 0.22 solid Cheers! -- Paul From hajducko at gmail.com Thu Mar 27 15:25:29 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Thu, 27 Mar 2008 12:25:29 -0700 (PDT) Subject: Plugin framework - Overcomplicating things? References: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> <753fd116-95e0-4d5b-88b3-927861267577@e23g2000prf.googlegroups.com> Message-ID: <1a82d714-a392-439f-84a1-a2b6cdee8d10@a1g2000hsb.googlegroups.com> On Mar 27, 4:18 am, Andr? wrote: > On Mar 27, 3:31 am, "Gabriel Genellina" > wrote: > > > > > En Thu, 27 Mar 2008 01:50:56 -0300, hajdu... at gmail.com > > escribi?: > > > > All this comes to my question - am I overcomplicating this project? I > > > can understand the use of something like the trac component system if > > > I had multiple components and plugins that handled different areas of > > > my project and different points of interaction, but I don't. I've got > > > exactly one spot where I want to check all my plugins and hand off the > > > message to which ever ones are looking for that command. > > > As you said, it looks like you're really overengineering your design then. > > > > So really, > > > should I even bother with trying to setup some framework for this or > > > should I just be doing a simple loop over a directory, importing all > > > the plugins and storing them in a list and then looping over them in > > > the message handler to see which ones were looking for the command and > > > letting them do their thing? > > You could set thing up so that there's no need to loop over the > plugins. > What you can do is register a plugin (as mentioned to you before by > Gabriel - see below) and create an entry in a handler dict so that you > can directly dispatch the message to the appropriate handler without > having to loop over a list of them. Something like > handlers[message]() > > > > > > > That may be an option. > > You may want to setup a simple registry mechanism, so the plugin modules > > look like: > > > ### begin niceplugin.py ### > > class AVeryNicePlugin(object): # or perhaps using a suitable base class > > def handle_message(self, message): > > ... > > > from plugin import PluginRegistry > > PluginRegistry.register(AVeryNicePlugin) > > ### end niceplugin.py ### > > > Your application scans a known directory for files ending in "plugin.py" > > and imports them; the modules register themselves any class (or classes), > > and at appropiate times the application calls some method(s) of the > > registered plugins. > > An alternative (which we found simpler with Crunchy) is to not have a > class-based structure, but working with simple modules and functions. > All modules are put in the "plugin" directory which are imported at > the beginning. Each module contain at least two functions: > 1. register() which create the handlers dict entry so that it point > out to the appropriate function. > 2. one or more function that is called based on the message received. > > Hope it helps, > > Andr? > > Thanks for the replies. Andr?, you're alternative was exactly what I was thinking of falling back to, rather than setting up class-based plugins. Like I said, seems like a whole plugin framework would be wayyyy too complicated. The only reason I figured I'd loop over the available plugins was in case two were defined to handle the same message. I figured something like setting an 'command' attr in the module and just checking for that. Either way, I think I'll stay away from trying for a real framework in this case. -- sh From tomerfiliba at gmail.com Mon Mar 17 16:52:32 2008 From: tomerfiliba at gmail.com (gangesmaster) Date: Mon, 17 Mar 2008 13:52:32 -0700 (PDT) Subject: win32: emulating select() on pipes Message-ID: hi i'm trying to figure out if a pipe on win32 has data for me to read. this is the code i've come up with: def poll(self, timeout, interval = 0.2): """a poor man's version of select() on win32""" from win32pipe import PeekNamedPipe from msvcrt import get_osfhandle handle = get_osfhandle(self.fileno()) if timeout is None: timeout = sys.maxint length = 0 tmax = time.time() + timeout while length == 0 and time.time() < tmax: length = PeekNamedPipe(handle, 0)[2] time.sleep(interval) return length != 0 does anyone know of a better way to tell if data is available on a pipe? something that blocks until data is available or the timeout is elapsed, and returns True if there's something for me to read, or False otherwise. -tomer From castironpi at gmail.com Thu Mar 6 11:40:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 08:40:47 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> On Mar 6, 12:17?am, "Daniel Fetchinson" wrote: > > > Where to begin? > > > What does exec( open( 'modA.py' ).read() ) do? > > The most appropriate list to ask those questions is: > > http://mail.python.org/mailman/listinfo/tutor Thanks for the reference. I'm basically experienced with Python, but I may read there too. I asked the question mostly rhetorically. Like when people ask, who cares, or who knows. They don't want the answer---- unless there is one. A more appropriate formulation of the 'question behind the words' would have been, 'are there any weird corner cases in which it doesn't import modA? I recognize it doesn't on .pyc and .pyd files, but you could say exec( open( 'modA.py' ).read() ) ==> import modA, even if import modA =!=> exec( open( 'modA.py' ).read() ) all the time. However, a way of asking that's more direct would have been, "Wait... can't you create multiple module instances like that?", but since we've already seen successful loadings of at least the builtins, that's been treated. Maybe you even hear the right thing if I say, "Does exec( open( 'modA.py' ).read() ) do the things of import modA?" Yes, I can read the docs, but no, I can't check every possible combination of modules. The idea behind a singleton is to ensure something. You want non- primary instances impossible to create. However, if (wording got tangled here) for singleton A, if class B does the same thing, just has different allocations-- it's own-- then A is still a singleton. The writer of B hasn't defeated or contradicted the letter or spirit of A. OP's question might have come from a variety of perspectives. In some ways yes, in others no. That is, if you try to reinstantiate modA, you get the same instance. But if you try really hard, you get a new one. Are you looking for an extension to import modA that won't return an instance that is old? So far, I know this: modules and classes are both namespaces. Are those singletons? From kay.schluehr at gmx.net Tue Mar 4 03:48:48 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 4 Mar 2008 00:48:48 -0800 (PST) Subject: ANN: EasyExtend 3.0 - beta1 released Message-ID: <24785288-715c-4677-b8a7-20463f672865@f47g2000hsd.googlegroups.com> After more than half a year of work I released the first beta of EasyExtend 3.0 today. EasyExtend 3.0 is the second major redesign of EasyExtend. To gain more power and simplicity I implemented a new parser generator from the scratch called "Trail". Trail unifies several aspects of EasyExtend. It is the fundament of both the EE 3.0 tokenizer and the parser. It is used to validate parse trees against grammars and it is used for parse tree synthesis. Besides Trail other new aspects of EE 3.0 are * User defined file suffixes are recognized by the import machinery * Framework extension that supports facilitation of writing user defined tokenizers * Simplification of access to tokenizer and parser from individual extension languages ( langlets ). * Improved stability of the CST transformation process and improved debugging facilities Currently EasyExtend 3.0 does not support several extension languages being described on the home page. Some of them like the macro langlet will be reimplemented in EasyExtend 3.1 using Trail techniques and a new persistence layer called exo.space. Others will be upgraded until the final release of EasyExtend 3.0. URLs: http://www.fiber-space.de/EasyExtend/doc/EE.html http://pypi.python.org/pypi/EasyExtend/3.0-beta1 From atom.anderson at gmail.com Thu Mar 20 12:15:53 2008 From: atom.anderson at gmail.com (atom.anderson at gmail.com) Date: Thu, 20 Mar 2008 09:15:53 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> Message-ID: <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> On Mar 17, 1:20 am, Paul Rubin wrote: > Stephan Deibel writes: > > I have to admit, I'll keep coming to PyCon even if all the talks suck > > abysmally as long as there's good hallway time, open space, BoFs, and > > sprints. ;-) > > OK, so why not get rid of all the talks and other stuff, and just have > a basically structureless conference, beyond scheduling some open > meetings on various topics? That would be a lot less expensive and a > lot more interesting. For me as first time pycon attendee, i think this would be an absolute disaster. The talks gave me an opportunity to sit next to new people and meet people I wouldnt have otherwise if they had simply "put us out to pasture" to chat it up. I think for devs that are just meeting each other, having some sort of subject matter to talk about is a big deal, and the talks forced that. I agree though that once things get going, the hallway time and BOF time would be fantastic. -adam From BruceTEckel at gmail.com Sun Mar 16 16:52:20 2008 From: BruceTEckel at gmail.com (Bruce Eckel) Date: Sun, 16 Mar 2008 13:52:20 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <3a2e4490-f4e9-4edf-ae35-0aa3c90103f7@i7g2000prf.googlegroups.com> Message-ID: On Mar 16, 2:48 pm, Pete Forde wrote: > My friends and I decided to stage a grassroots Ruby conference this > summer; it will have no paid sponsors for exactly this reason. We're > trying to change up the typical format as well: it's a single-track > event, no "keynotes", no schills for well-heeled interests. We're even > organizing activities for significant others traveling with conference > attendees so that everyone has a good time. > > The response we've gotten to this approach has been curious; many > people totally get why these things are important, and the speaker > list reflects this. However, we've also had a lot of complaints that > our event is too expensive. In fact, they say that it should be free, > like a BarCamp. Just get a bunch of sponsors, and that will be the > ticket. We say bollocks to that. > > http://rubyfringe.com/ I've been running open spaces conferences for the past few years and I would suggest you do that instead of an "eyes-forward" conference. It's not only a lot easier, but it's also a lot more fun. For example, last week we did the Java Posse Roundup, which is all open-spaces. The way we've handled "sponsorship" for the Roundup is "swag only." If sponsors want to send gifts, then we'll give them out, but we don't take money. Everybody seems pretty happy with that arrangement and it doesn't feel intrusive in the least. So you might consider that. Because of requests I've had (before Pycon started) we are planning a small open-spaces conference on Python, this summer in Crested Butte. The dates haven't been set yet but I'll announce them on my weblog and elsewhere. It will follow the format of lightning talks to kick off, then all open spaces (plus the usual hikes and barbeques). And swag- only contributions from vendors, although that usually just happens via people who happen to work for vendors, who are coming as participants and find out they can contribute something else. > I'm posting here because even though the Python and Ruby communities > are seen as being in some sort of competition, I personally believe > that we have more in common (and lots to learn from each other) than > we are credited for. For example, the popular Haml template engine is > white-space sensitive, and that's a direct nod towards Python syntax. I think Ruby has done a lot to push the idea of dynamic languages for medium and large scale projects and to help recover from the bad experience many had when they tried to push Perl too far. > Thanks for your post, Bruce. You've given us a huge boost that we're > doing something right, here. I'm sure your conference will be great because you're making it totally attendee-focused. From cokofreedom at gmail.com Wed Mar 12 11:27:44 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 12 Mar 2008 08:27:44 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> Message-ID: <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> On Mar 12, 2:44 pm, Robert Bossy wrote: > Matt Nordhoff wrote: > > Robert Bossy wrote: > > >> k.i.n.g. wrote: > > >>> I think I am not clear with my question, I am sorry. Here goes the > >>> exact requirement. > > >>> We use dd command in Linux to create a file with of required size. In > >>> similar way, on windows I would like to use python to take the size of > >>> the file( 50MB, 1GB ) as input from user and create a uncompressed > >>> file of the size given by the user. > > >>> ex: If user input is 50M, script should create 50Mb of blank or empty > >>> file > > >> def make_blank_file(path, size): > >> f = open(path, 'w') > >> f.seek(size - 1) > >> f.write('\0') > >> f.close() > > >> I'm not sure the f.seek() trick will work on all platforms, so you can: > > >> def make_blank_file(path, size): > >> f = open(path, 'w') > >> f.write('\0' * size) > >> f.close() > > > I point out that a 1 GB string is probably not a good idea. > > > def make_blank_file(path, size): > > chunksize = 10485760 # 10 MB > > chunk = '\0' * chunksize > > left = size > > fh = open(path, 'wb') > > while left > chunksize: > > fh.write(chunk) > > left -= chunksize > > if left > 0: > > fh.write('\0' * left) > > fh.close() > > Indeed! Maybe the best choice for chunksize would be the file's buffer > size... I won't search the doc how to get the file's buffer size because > I'm too cool to use that function and prefer the seek() option since > it's lighning fast regardless the size of the file and it takes near to > zero memory. > > Cheers, > RB But what platforms does it work on / not work on? From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:20:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:20:09 -0300 Subject: importing a csv file as a Numeric array References: Message-ID: En Tue, 25 Mar 2008 06:46:57 -0300, Rahul escribi?: > What's a good way of importing a csv text file of floats into a > Numeric array? I tried the csv module and it seems to work well so > long as I've ints. Does anyone have any suggestions / snippets that > work to import a csv file of floats into a Numeric array? See the Cookbook at http://www.scipy.org/Cookbook/InputOutput - but I don't know how much of that is applicable to the old Numeric library. Robert Kern posted a fairly generic approach in this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/7345c364cae59127/ -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Mar 27 05:44:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 06:44:21 -0300 Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 06:00:26 -0300, escribi?: > I was add this into my application code: > > import sys > import os > my_dir=os.getcwd() > sys.path.append(my_dir) > sys.path.append(my_dir+"\\libary.zip") > sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder > f=open("path.txt","w") > f.write(str(sys.path)) > f.close() > > an the output in path.txt is : > > ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users > \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ > \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ > \libary.zip\\py2exe'] > > But it still can't find module py2exe.What should I do now? Any > examples? I assume you're talking about the py2exe package available from www.py2exe.org - so it's not a module, it's a package. py2exe usually is only relevant on your *development* machine, so why do you want to put it inside a .zip? What do you want to do? Anyway, I tried the following and could import py2exe successully (but I don't know if it actually works as a distutils extension...) - compressed the py2exe folder into py2exe.zip - deleted the original py2exe folder - moved py2exe.zip onto some temporary directory - tried to import py2exe, failed as expected - added py2exe.zip to sys.path - tried to import py2exe, this time OK py> import py2exe Traceback (most recent call last): File "", line 1, in ImportError: No module named py2exe py> import sys py> sys.path.append(r"C:\TEMP\pna\py2exe.zip") py> import py2exe py> py2exe.__path__ ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] -- Gabriel Genellina From grante at visi.com Fri Mar 21 16:03:04 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Mar 2008 20:03:04 -0000 Subject: How can I make a function equal to 0? References: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Message-ID: <13u853oaoqjle62@corp.supernews.com> On 2008-03-21, Paul Rubin wrote: > Martin Manns writes: >> Is there a way to create a function that is equal to 0? > > def f(): return 0 I assumed he meant he wanted this to evaluate to True instead of False: >>> def f(): return 0 ... >>> >>> f == 0 False -- Grant Edwards grante Yow! Yes, but will I at see the EASTER BUNNY in visi.com skintight leather at an IRON MAIDEN concert? From sturlamolden at yahoo.no Tue Mar 18 19:08:04 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 16:08:04 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> On 18 Mar, 23:45, Arnaud Delobelle wrote: > > def nonunique(lst): > > slst = sorted(lst) > > dups = [s[0] for s in > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > return [dups[0]] + [s[1] for s in > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > Argh! What's wrong with something like: > > def duplicates(l): > i = j = object() > for k in sorted(l): > if i != j == k: yield k > i, j = j, k Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) as opposed to ours which are O(N log N). From mdboldin at gmail.com Tue Mar 4 07:53:33 2008 From: mdboldin at gmail.com (mmm) Date: Tue, 4 Mar 2008 04:53:33 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> Message-ID: <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Steve, I think you were right the first time is saying > it should really be this: > sqlxb= 'INSERT INTO DTABLE2 VALUES (?, ?, ?, ?)' my copy.copy() has the equivalent effect. Running this test code produces the output below import copy print 'Test 1' pf= '?,?,?,?' sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf print sqlx1 print print 'Test 2' sqlx2= copy.copy(sqlx1) sqlx3= sqlx1 pf= '?,?,?, ****' sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf print 'sqlx1= ', sqlx1 print 'sqlx2= ', sqlx2 print 'sqlx3= ', sqlx2 == output Test group 1 INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) Test group 2 sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?, **** ) sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) I interpret this to mean that sqlx1 is not a simple string From dickinsm at gmail.com Tue Mar 11 11:59:44 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 08:59:44 -0700 (PDT) Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> Message-ID: <46f8d1bf-8821-4083-b7d7-d4ed53f8862a@q78g2000hsh.googlegroups.com> On Mar 11, 11:35?am, Grant Edwards wrote: > That seems a bit baffling. ?If it urlopen doesn't support > specifying proxies, why are there examples showing how to do > it? If it does support specifying proxies, what is the pragraph > quoted above supposed to mean? Looks like a definite documentation bug to me, and it's still there in the development version of the documentation. I think a bug report should be filed. A little bit of investigation shows that the documentation changes were made in svn revisions 26181 and 26182 ( http://svn.python.org/view?view=rev&rev=26181 ) as a fix for http://bugs.python.org/issue523415 but this doesn't seem to help much with figuring out what the docs intend to say. Mark From mac_the_scotte at hotmail.com Sat Mar 29 15:57:18 2008 From: mac_the_scotte at hotmail.com (mac_the_scotte at hotmail.com) Date: Sat, 29 Mar 2008 12:57:18 -0700 (PDT) Subject: Problem with python Message-ID: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Hi there. I downloaded python a couple of days ago from the official site and have started writing simple programs in the python gui (this being my first attempt at programming ever). The only thing is when I write python code in a text editor and save it as a .py file, when I double click it all that happens is a black box flashes up on the screen, but nothing else!? At first I thought this was because I had only written a hello world program, and that the box had displayed "hello world" and then closed. But then I wrote a program requiring user input and the same thing happened... Am I doing something wrong? Thanks in advance for any help! //mac From stanc at al.com.au Thu Mar 27 02:11:13 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 27 Mar 2008 17:11:13 +1100 Subject: copy file over LAN In-Reply-To: References: <47EB15BC.3060505@al.com.au> Message-ID: <47EB3A81.7090708@al.com.au> Well, the solution seems to be something like (windows only) import os import os.path import shutil import sys import win32wnet def wnet_connect(host, username, password): unc = ''.join(['\\\\', host]) try: win32wnet.WNetAddConnection2(0, None, unc, None, username, password) except Exception, err: if isinstance(err, win32wnet.error): # Disconnect previous connections if detected, and reconnect. if err[0] == 1219: win32wnet.WNetCancelConnection2(unc, 0, 0) return wnet_connect(host, username, password) raise err if __name__ == '__main__': node = hostname dst = r'C:\temp\destination__' dst += node + r'.txt' wnet_connect(node,username,password) shutil.copyfile(r'\\' + node + r'\c$\temp\\al_lsf_log',dst) Gabriel Genellina wrote: > En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee escribi?: > > >> I have a file on another machine on the local network (my machine and >> local machines are on windows) and I want to copy it locally. Now the >> machine requires authentication and when I try to do a >> import shutil >> shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') >> and it gives me a IOError: [Errno 13] Permission denied: error, which I >> expect. How do I provide authentication to copy this file? >> > > Probably there are other ways, but the "net use" command looks easy > enough. Execute "net help use | more" in a console to see the right syntax. > Use the subprocess module to run the command from inside Python. > > -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Wed Mar 26 18:26:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 15:26:52 -0700 (PDT) Subject: memory allocation for Python list References: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> Message-ID: <033ed38c-1b43-4bb5-9ceb-54fb5f128217@q78g2000hsh.googlegroups.com> dmitrey: > As I have mentioned, I don't know final length of the list, but > usually I know a good approximation, for example 400. You may want to use collections.deque too, it doesn't produce a Python list, but it's quite fast in appending (it's a linked list of small arrays). Bye, bearophile From aahz at pythoncraft.com Sun Mar 16 10:18:04 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Mar 2008 07:18:04 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: In article <5bd37c10-af5d-4254-8799-49c762673a3e at n58g2000hsf.googlegroups.com>, Bruce Eckel wrote: > >If the following seems unnecessarily harsh, it was even more harsh for >me to discover that the time and money I had spent to get to my >favorite conference had been sold to vendors, presenting me as a >captive audience they could pitch to. Ouch. I'm probably one of the few organizers currently paying much attention to c.l.py -- because I'm also one of the few who's not at PyCon. We debated this extensively before going ahead, and we decided it was worth an experiment. If your feedback is at all representative, this won't happen again, I assure you. I'm forwarding your post to the semi-private pycon-organizers list (pretty much anyone can join -- more volunteers are always welcome -- but you have to join to see the archives) to make sure everyone sees it. >I believe that this year's Pycon organizers suffered from inexperience >and naivete, because they didn't know that some vendors will ask for >anything just to see how far they can push it. Actually, it was our idea to offer something in return for the sponsorship. >On top of that, the quality of the presentations was unusually low. >I'd say that 80% were not worth going to -- there were definitely some >good ones, but it was a lot of pain to discover them. Just to make sure, you're talking about the vendor presentations, right? >I think a lot of people have been caught up in the idea that we need >to commercialize Python, and ride some kind of wave of publicity the >way that Java and C# and Rails seem to have done. Not in my observation. What we were trying to do was to increase sponsorship to decrease the cost to attendees -- we have NO interest in pushing the commercialization of Python. >I know what the argument for the results of Pycon 2008 will be: we >needed the money. My answer: it's not worth it. If this is what you >have to do to grow the conference, then don't. If the choice is >between selling my experience to vendors and reducing the size of the >conference, then cut the size of the conference. Keep the quality of >my experience as the primary decision criteria, or I'll stop coming. That was our intention. Apparently it didn't work for you. I'll wait for more feedback before I make up my mind about whether your experience was common. And no, we don't need the money so badly that we can't afford to turn away sponsors who demand this particular benefit. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From dkuhlman at rexx.com Thu Mar 13 18:06:05 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 13 Mar 2008 22:06:05 GMT Subject: getattr(foo, 'foobar') not the same as foo.foobar? Message-ID: The following code has me mystified: In [4]: class A(object): ...: def show(self): ...: print 'hello' ...: ...: In [5]: a = A() In [6]: In [7]: x = a.show In [8]: y = getattr(a, 'show') In [9]: x Out[9]: > In [10]: y Out[10]: > In [11]: In [12]: id(x) Out[12]: 12419552 In [13]: id(y) Out[13]: 12419872 In [14]: In [15]: x is y Out[15]: False In [16]: In [17]: x() hello In [18]: y() hello Basically, the above code is saying that foo.foobar is not the same as getattr(foo, 'foobar'). But the documentation at http://docs.python.org/lib/built-in-funcs.html#l2h-33 says that they are equivalent. And, the following seems even worse: >>> id(getattr(a, 'show')) == id(a.show) True >>> getattr(a, 'show') is a.show False What gives? This breaks my understanding of id(), the is operator, and getattr(). Can someone help me make sense of this? I'm using Python 2.5.2. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From van.lindberg at gmail.com Mon Mar 17 10:13:39 2008 From: van.lindberg at gmail.com (VanL) Date: Mon, 17 Mar 2008 09:13:39 -0500 Subject: Pycon disappointment In-Reply-To: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <47DE7C93.4040501@gmail.com> Bruce, I can't speak to your issues with the normal sessions, but your bad experience with the lightning talks was my fault. And, in apologizing to you, I hope that all the others on this thread who have expressed similar sentiments hear me too. Ultimately, we miscalculated in certain respects. It wasn't any particular thing, but rather there were a couple of issues that came together here: 1 - We had an incredible amount of sponsorship. Higher than expected by anyone. This wasn't bad in itself (I think it was very good!), but it set the stage for some of the issues later. 2 - As part of the sponsor package, we promised the sponsors priority for a lightning talk. Our thought was that the sponsor lightning talks from last year were well received, so they probably would be this year as well. Unfortunately, that turned out not to be the case - at least having *that many* was not well received. 3 - We had a very limited time when some of the sponsors would still be here - basically Friday and Saturday. The major problem on Saturday is that we *had* to stack the sponsor talks that way or else we would not fulfill our obligations to our sponsors. We offered lightning talks this year because a) we didn't know how well the expo hall would go, and b) that was the only way for the sponsors to connect with the audience last year - so we assumed that it might be the same way this year. This was discussed and generally agreed-to in September. IIRC, the sponsor lightnings were not an issue that was subject to much debate back then, most people were accustomed to the generally positive 2007 experience.* I think that with the success of the expo hall, we can remove the lightning talks from the sponsor benefits for next year, and at this point I am in favor of doing so. Personally, I was *very* disappointed that some of our sponsors didn't prepare or even show up for their assigned slots. I think that the sponsors are members of our community, and I expect them to act as such. Taking slots and not showing up - or not showing up prepared - isn't how I would hope a community member would act. Thanks, Van *(On the other hand, the Diamond keynotes were the subject of substantial debate - but I thought those went well; I would like to keep them for next year.) From aeneng at yahoo.com Fri Mar 28 21:47:21 2008 From: aeneng at yahoo.com (aeneng) Date: Sat, 29 Mar 2008 01:47:21 -0000 Subject: Help me on function definition Message-ID: Hello everyone, I am just starting to use python in numerical cacluation. I need you to help me to see what's wrong with the following piece of codes, which computes the cross product of two vectors and returns the result. u and v are two 3x1 matrix. when I import the function, error message show like this >>> import cross Traceback (most recent call last): File "", line 1, in ? File "cross.py", line 8 ppp2=u[2]*v[0]-u[0]*v[2] ^ SyntaxError: invalid syntax WHAT IS WRONG WITH MY CODE? I appreciate your help. ##here is the function definition. ##cross.py## def cross(u,v) """input two vectors u and v in 3-D space, output a cross product of vector w, in column or in row accordingly.""" ppp1,ppp2,ppp3=0.0,0.0,0.0 ppp1=u[1]*v[2]-u[2]*v[1] ppp2=u[2]*v[0]-u[0]*v[2] ppp3=u[0]*v[1]-u[1]*v[0] # store the result of the cross product in u u[0]=ppp1 u[1]=ppp2 u[2]=ppp3 return u #return the cross product of vector u x v. if __name__=="__main__": from cvxopt.base import matrix u=matrix([1.0,0.0,0.0],(3,1)) v=matrix([0.0,1.0,0.0],(3,1)) print cross(u,v) print "file name is %s" %__name__ From sjmachin at lexicon.net Sun Mar 23 21:56:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 18:56:51 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> <13udtk586ijktec@corp.supernews.com> Message-ID: On Mar 24, 11:32 am, Steven D'Aprano wrote: > On Sun, 23 Mar 2008 10:45:38 -0700, Paul Rubin wrote: > > John Nagle writes: > >> What's the cheapest way to test for an empty dictionary in Python? > > >> if len(dict.keys() > 0) : > > > I like to think len(dict) is constant time but I haven't checked the > > code. Same for bool(dict) (which is what you get when you run "if dict: > > ..."). > > Except that "if dict" doesn't needlessly and wastefully create a bool. > > >>> from timeit import Timer > >>> Timer("if {1:2}: pass").timeit() > 1.1590199184417725 > >>> Timer("if bool({1:2}): pass").timeit() > > 1.8825540542602539 > > Python knows the truth value of built-in types like dicts without > actually converting them to bools, or for that matter calling __len__ or > __nonzero__ on them. What the 2.5.1 interpreter does is call PyObject_IsTrue, which checks to see if the built_in or extension type is a mapping (not just a dict) with a length method and if so calls it; similarly for sequences: else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); else if (v->ob_type->tp_as_sequence != NULL && v->ob_type->tp_as_sequence->sq_length != NULL) res = (*v->ob_type->tp_as_sequence->sq_length)(v); Was that what you meant by "without ... calling __len__"? From mistermoose at gmail.com Thu Mar 6 08:56:11 2008 From: mistermoose at gmail.com (Jeffrey Seifried) Date: Thu, 6 Mar 2008 05:56:11 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: <5c0bab72-8dd2-4be9-a832-168a32d99585@8g2000hse.googlegroups.com> On Mar 6, 7:10 am, Guillermo wrote: > Hello, > > This is my first post here. I'm getting my feet wet with Python and I > need to know how can I check whether a variable is of type dictionary. > > Something like this: > > if isdict(a) then print "a is a dictionary" > > Regards, > > Guillermo Or if type(a)==type({}): print 'a is a dictionary' From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 03:52:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 07:52:25 -0000 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> <7xk5jz1a80.fsf@ruckus.brouhaha.com> Message-ID: <13u45tp398pfc18@corp.supernews.com> On Wed, 19 Mar 2008 23:53:22 -0700, Jeff Schwab wrote: > The point of rsync is to keep a local directory tree in sync with a > remote one, by transferring only change-sets that are conceptually > similar to patches. If you're only transferring files once, there's no > particular benefit (AFAIK) to using rsync rather than some kind of > recursive ftp. Avoiding re-inventing the wheel is a big benefit. -- Steven From arkanes at gmail.com Fri Mar 7 16:06:37 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 7 Mar 2008 15:06:37 -0600 Subject: I cannot evaluate this statement... In-Reply-To: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <4866bea60803071306n5d53c2ebk43430364b49983d9@mail.gmail.com> On Fri, Mar 7, 2008 at 2:38 PM, waltbrad wrote: > The script comes from Mark Lutz's Programming Python. It is the > second line of a script that will launch a python program on any > platform. > > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > That makes sense. Because the first condition is true and 'python.exe' > is true. So the next comparison is 'python.exe' or 'python' Well, > python.exe is true. So that value is returned to pyfile. > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. > But, again, on linux pyfile evaluates to python.exe > > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? > -- > http://mail.python.org/mailman/listinfo/python-list > In Python 2.5, this is written: pyfile = 'python.exe' if 'win' in sys.platform else 'python' However, this is a pretty bad way of doing this at all. sys.executable is better. I'm not sure when sys.executable was added but I assume it's more recent than whatever version Lutz used in his book. From aisaac at american.edu Wed Mar 12 19:52:01 2008 From: aisaac at american.edu (Alan Isaac) Date: Wed, 12 Mar 2008 23:52:01 GMT Subject: no more comparisons In-Reply-To: <7xy78neffb.fsf@ruckus.brouhaha.com> References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The cmp option should not be removed. However, requiring > it to be specified as a keyword parameter instead of just > passed as an unlabelled arg is fine. Sure; I would have no problem with that. But that is not what is happening. As for Carl's suggestion to use ``key``: this is already possible when it is convenient, but it is not always convenient. (Even aside from memory considerations.) By the way, I even saw mention of even removing the ``cmp`` built-in. Cheers, Alan Isaac From kyosohma at gmail.com Mon Mar 10 17:18:30 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 14:18:30 -0700 (PDT) Subject: wxPython: some help with Drag&Drop References: Message-ID: On Mar 10, 4:04 pm, Eric von Horst wrote: > Hi, > > I need some advice on Drag&Drop. > > What I want to achieve is the following: > - I have a window that is divided in two : on the left hand I > have a wx.TreeCtlr and on the other hand a wx.StaticBitmap > > I want to be able to drag an item from the tree onto the static > bitmap. > > I know how to do drag&drop in a treeCtrl but is there a way that I can > make the bitmap detect that something has been dropped on it? > > I would only need to know the name of the tree obj that was dropped on > the bitmap (and the location) > > Any help much appreciated > > Erik I highly recommend posting to the wxPython user's group since they specialize in this sort of thing: http://wxpython.org/maillist.php In the mean time, you'll probably want to take a look at their wiki: http://wiki.wxpython.org/DragAndDrop http://wiki.wxpython.org/ListControls There's also a fair amount of data on the subject in their archives. Mike From vlastimil.brom at gmail.com Wed Mar 5 18:18:01 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 6 Mar 2008 00:18:01 +0100 Subject: Dual look-up on keys? In-Reply-To: References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <9fdb569a0803051518x3dd0a9e9w7769d2175bcbfa1f@mail.gmail.com> 2008/3/5, castironpi at gmail.com : > > ... > Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a) > is also in it, and maps to the same object? > ... > Well, it's probably not the most effective way, but one can use something like: >>> d={frozenset(("a","b")):7} >>> d[frozenset(("b","a"))] 7 >>> d[frozenset(("b","a"))]=94 >>> d[frozenset(("a","b"))] 94 >>> HTH vbr -------------- next part -------------- An HTML attachment was scrubbed... URL: From sean at ardishealth.com Wed Mar 19 09:16:44 2008 From: sean at ardishealth.com (Sean Allen) Date: Wed, 19 Mar 2008 09:16:44 -0400 Subject: What Programming Languages Should You Learn Next? In-Reply-To: <64bugqF2anottU1@mid.uni-berlin.de> References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> Message-ID: > Haven't found that killer problem so far ... for Haskell, check out HAppS. They have some great web application stuff going on. From natraj12j at gmail.com Fri Mar 7 01:44:53 2008 From: natraj12j at gmail.com (Nat) Date: Thu, 6 Mar 2008 22:44:53 -0800 (PST) Subject: Regarding an exciting opportunity in PYTHON at Hyderabad Message-ID: We have been looking for Senior Professional based at Hyderabad for one of our clients which an upcoming Product development company based out of hyderabad . I would appreciate if you can repond back with your profile at natraj12j at gmail.com.I would get back to you with complete details and accordingly we can go ahead. Job Description: Need to have 2-4 years of experience. Should have strong understanding of Project management and SDLC. Technology is flexible. Can have experience in either of python(C, C+ +),Java or .NET. Thanks and Regards Natraj.J M?bius Consulting Pvt. Ltd. From grante at visi.com Sun Mar 9 00:31:22 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:31:22 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6c8kdis2gbb5@corp.supernews.com> Message-ID: <13t6tha12dcdh5a@corp.supernews.com> On 2008-03-09, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 21:21:48 +0100, K Viltersten wrote: > >> Coming from C++/Java camp i can't help noticing that in most cases, when >> i'm using a class written by somebody else, i don't want to see his/her >> code. I only want to know WHAT the function does (is intended to be >> doing, at least). >> >> I don't want to look at the source code (in some cases i can't even see >> the code because it's compiled). I only care that when i execute >> >> SomeType obj = SomeType(); >> obj.aggregate(); >> >> the object gets aggregated. How it's done will be up to the author. I'm >> just a user of the product. >> >> Now, i'm getting the signal that it's done in a different way in Python. >> Please elaborate. I'm very new to snakeology. > > > I think even Grant would agree that when you call "help(make_widget)", > you should see something like: > > make_widget(styleID, material) -> widget or > raise ValueError on failure > > styleID: numeric ID or string name of the widget style > material: WidgetMaterial instance or None to use default I think docstrings are a great idea. What's needed is a way to document the signature that can't get out-of-sync with what the fucntion really expects. -- Grant Edwards grante Yow! I'm wearing PAMPERS!! at visi.com From jjosburn at gmail.com Wed Mar 19 14:14:04 2008 From: jjosburn at gmail.com (black_13) Date: Wed, 19 Mar 2008 11:14:04 -0700 (PDT) Subject: modules devoted to manipulationg .reg files Message-ID: <12fdb0c5-f880-4264-86d1-be3ad2be8c51@c19g2000prf.googlegroups.com> are there any python modules for manipulation of .reg files producted by the win32 prog "reg". thanks. black_13 From mensanator at aol.com Wed Mar 19 20:15:29 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 19 Mar 2008 17:15:29 -0700 (PDT) Subject: slicing a list but in downward fashion References: Message-ID: <04cb8307-5e6c-4f44-ae9e-0315378579a5@e39g2000hsf.googlegroups.com> On Mar 19, 6:37?pm, Lee Sander wrote: > hi, > i have a list and i can get elements form it via slicing > L[start:stop] > but sometimes the start is > stop i.e. I want to go in the opposite > direction,eg > L[10:2], > > mattab lets you do L(10:-1:2) to achive this, is there a way to do > this in python? >>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] >>> a[3:10:2] [4, 6, 8, 10] >>> a[10:3:-2] [11, 9, 7, 5] > thanks > L From gandalf at shopzeus.com Tue Mar 18 06:09:32 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 18 Mar 2008 11:09:32 +0100 Subject: Decode email subjects into unicode In-Reply-To: <47DF8EED.1010501@shopzeus.com> References: <47DF8EED.1010501@shopzeus.com> Message-ID: <47DF94DC.7010205@shopzeus.com> Sorry, meanwhile i found that "email.Headers.decode_header" can be used to convert the subject into unicode: > def decode_header(self,headervalue): > val,encoding = decode_header(headervalue)[0] > if encoding: > return val.decode(encoding) > else: > return val However, there are malformed emails and I have to put them into the database. What should I do with this: Return-Path: X-Original-To: info at designasign.biz Delivered-To: dapinfo at localhost.com Received: from 195.228.74.135 (unknown [122.46.173.89]) by shopzeus.com (Postfix) with SMTP id F1C071DD438; Tue, 18 Mar 2008 05:43:27 -0400 (EDT) Date: Tue, 18 Mar 2008 12:43:45 +0200 Message-ID: <60285728.00719565 at optometrist.com> From: "Euro Dice Casino" To: thomas at designasign.biz Subject: With 2?500 Euro of Welcome Bonus you can?t miss the chance! MIME-Version: 1.0 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 7bit There is no encoding given in the subject but it contains 0x92. When I try to insert this into the database, I get: ProgrammingError: invalid byte sequence for encoding "UTF8": 0x92 All right, this probably was a spam email and I should simply discard it. Probably the spammer used this special character in order to prevent mail filters detecting "can't" and "2500". But I guess there will be other important (ham) emails with bad encodings. How should I handle this? Thanks, Laszlo From gagsl-py2 at yahoo.com.ar Fri Mar 7 10:18:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 13:18:20 -0200 Subject: Quit-command not quiting References: <63d2efF271u6hU1@mid.individual.net> Message-ID: En Fri, 07 Mar 2008 12:56:44 -0200, K Viltersten escribi?: > I entered the code from tkinter.pdf, section > 2 but for reason, the application doesn't > close as i press the quit-button. > > The wondow itself vanishes if i click the > cross in the upper-right corner but pressing > the quit-button only makes it "pressed". > Then, the program freezes. How did you run it? From inside IDLE? IDLE itself is written using Tk, and I think that your mainloop interferes with the one inside it. If you run your program from the command line it should work fine. > from Tkinter import * > class Demo (Frame): > def __init__ (self, master = None): > Frame.__init__ (self, master) > self.grid () > self.doLayout () > def doLayout (self): > self.quitButton = Button ( > self, > text = "Quit", > command = self.quit) > self.quitButton.grid () > > d = Demo () > d.master.title ("the coolest demo ever") > d.mainloop () There is only one thing I hate more than spaces after a parens: spaces before it :) Please read PEP8, about the suggested style for writting Python code. http://www.python.org/dev/peps/pep-0008/ -- Gabriel Genellina From ACooper at cimtek.com Mon Mar 10 11:54:37 2008 From: ACooper at cimtek.com (Cooper, Andrew) Date: Mon, 10 Mar 2008 11:54:37 -0400 Subject: Obtaining the PyObject * of a class Message-ID: I',m currently using SWIG to generate a python interface to a C DLL. I'm new to the Python C API and have a question that has been stumping me for the last week. As part of the wrapper process I want to hide some of the complexity with dealing with handles using a python class. But the problem I have is I don't know how to get the PyObject* that refers to the class Pin that I have defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } From durieux_br at yahoo.com.br Wed Mar 26 16:23:23 2008 From: durieux_br at yahoo.com.br (Salsa) Date: Wed, 26 Mar 2008 13:23:23 -0700 (PDT) Subject: Daylight savings time problem Message-ID: <585793.80038.qm@web90609.mail.mud.yahoo.com> I'm sorry, but could you be more specific? How exactly should I use UTC? -- Fabio Durieux Lopes - Salsa ----- Original Message ---- From: D'Arcy J.M. Cain To: Fabio Durieux Lopes Cc: python-list at python.org Sent: Wednesday, March 26, 2008 4:49:57 PM Subject: Re: Daylight savings time problem On Wed, 26 Mar 2008 19:37:16 -0000 "Fabio Durieux Lopes" wrote: > I'm trying to execute some operations based on a file's time. The > file's time is actually the file's name (e.g. FILE1_20080326170558). > So I do this: > fileTimeInSecs = time.mktime(time.strptime(timeString, > "%Y%m%d%H%M")) > > timeString contains the date part of the file's name. Function > strptime returns a time_struct, but my problem is that tm_isdst is > set to 0, and when we enter daylight savings time the file's time is > off by 1 hour. This time_struct is also read only so I can't change > tm_isdst to -1. > > Anyone knows how to fix it? Use UTC. -- 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. ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From brnstrmrs at gmail.com Thu Mar 13 11:46:05 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Thu, 13 Mar 2008 08:46:05 -0700 (PDT) Subject: scons Buffer.cpp Message-ID: <2a13b90c-52f4-4939-92f0-0e859c3987e8@m34g2000hsc.googlegroups.com> I am trying to install some libs but can not get them build properly. It seems to be looking for Buffer.cpp but can't find it any where . Here is the error message: scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... g++ -o AssociationRejection.o -c -I/usr/lib -I/usr/lib/boost AssociationRejection.cpp g++ -o Buffer.o -c -I/usr/lib -I/usr/lib/boost Buffer.cpp In file included from Buffer.cpp:1: Buffer.hpp:9:27: error: socket/Base.hpp: No such file or directory Buffer.hpp:10:35: error: socket/SwitchEndian.hpp: No such file or directory Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator<<(T)': Buffer.hpp:84: error: 'is_fundamental' is not a member of 'boost' Buffer.hpp:84: error: '::value' has not been declared Buffer.hpp:90: error: template argument 1 is invalid Buffer.hpp:95: error: template argument 1 is invalid Buffer.hpp:96: error: expected unqualified-id before '}' token Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(T&)': Buffer.hpp:103: error: 'is_const' is not a member of 'boost' Buffer.hpp:103: error: '::value' has not been declared Buffer.hpp:104: error: template argument 1 is invalid Buffer.hpp:105: error: template argument 1 is invalid Buffer.hpp:105: error: invalid type in declaration before ';' token Buffer.hpp:105: error: declaration of 'typedef int& data' shadows a parameter Buffer.hpp:109: error: 'pdata' was not declared in this scope Buffer.hpp:117: error: expected unqualified-id before '=' token Buffer.cpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(std::vector >&)': Buffer.cpp:38: error: 'SwitchVectorEndian' was not declared in this scope Buffer.cpp: In member function 'void dicom::Buffer::AddVector(const std::vector >&)': Buffer.cpp:112: error: 'SwitchVectorEndian' was not declared in this scope Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(T&) [with T = char]': Buffer.cpp:51: instantiated from here Buffer.hpp:105: error: declaration of 'typedef int& data' shadows a parameter Buffer.hpp: In member function 'dicom::Buffer& dicom::Buffer::operator>>(T&) [with T = UINT16]': Buffer.cpp:59: instantiated from here Buffer.hpp:105: error: declaration of 'typedef int& data' shadows a parameter scons: *** [Buffer.o] Error 1 scons: building terminated because of errors. From kaerbuhez at gmail.com Fri Mar 14 09:54:56 2008 From: kaerbuhez at gmail.com (kaerbuhez) Date: Fri, 14 Mar 2008 06:54:56 -0700 (PDT) Subject: find string in file References: Message-ID: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> On 14 mar, 14:25, fminerv... at gmail.com wrote: > Hi friends !! > > I'm neophite about python, my target is to create a programa that > find a specific string in text file. > How can do it? > > Thanks > fel $ cat text.txt aaa bbb ccc ddd aaa bbb ccc ddd aaa bbb ccc ddd aaa eee bbb eee ccc eee ddd eee $ cat bin/find_string.py import sys file_name=sys.argv[1] searched_string=sys.argv[2] result= [(line_number+1, line) for line_number, line in enumerate(open(file_name)) if searched_string in line] print result $ python bin/find_string.py text.txt eee [(8, 'aaa eee\n'), (9, 'bbb eee\n'), (10, 'ccc eee\n'), (11, 'ddd eee \n')] $ python bin/find_string.py text.txt aaa [(1, 'aaa\n'), (5, 'aaa bbb\n'), (7, 'aaa bbb ccc ddd\n'), (8, 'aaa eee \n')] $ python bin/find_string.py text.txt ddd [(4, 'ddd\n'), (6, 'ccc ddd\n'), (7, 'aaa bbb ccc ddd\n'), (11, 'ddd eee\n')] $ From bj_666 at gmx.net Mon Mar 3 01:59:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Mar 2008 06:59:42 GMT Subject: Character Problem References: Message-ID: <631luuF25g4d2U3@mid.uni-berlin.de> On Mon, 03 Mar 2008 04:27:52 +0200, Harun BAYKAL wrote: > I am studying on an addon developed for QGIS, a GIS software. But I > have a problem. The extension has been developed with QT and Python. > Actually Python is used for the interface design. For the user > interface Python reads some values from some database files. I am not > experienced Python user and the first developer of the addon had > written the python codes for his database. And his database > doesn't include any characters than the usual characaters. But my > database file contains many characters which are not used in English. > So I can not compile the extension because Python can not read the > database files. > > So how can I change the python files for making it to read the > databases without modifying the database. Otherwise I had to clear all > the non usual characters from the database file which means most of > the names and strings will be wrong. So somehow I had to make the > python files to read the other unicode and non english characters? > Anybody have any idea about how I can I fix such a problem. All I get from this description is, that you have a problem with encodings but what is the *specific* problem? Where does the program fail? With what exception(s)? Ciao, Marc 'BlackJack' Rintsch From tmp1 at viltersten.com Sat Mar 8 15:26:19 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 8 Mar 2008 21:26:19 +0100 Subject: Adjust a canvas as the window is resized Message-ID: <63ga4fF27edonU1@mid.individual.net> Do i need to set a callback to a canvas in order to "listen" to the root window being resized in order to make it adjust its contents? If so, how? If not, how do i make the canvas draw a line from one corner to an other? from Tkinter import * class Demo(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.grid() self.doLayout() master.geometry("800x600") def doLayout(self): canvas = Canvas(self, bd = 3, bg = "#93F") canvas.grid(column = 0, row = 0) canvas.create_line(0, 0, 100, 200, fill = "#FFF") def callback(self): print "callback from canvas" root = Tk() demo = Demo(root) root.mainloop() -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From gklein at xs4all.nl Wed Mar 19 05:11:18 2008 From: gklein at xs4all.nl (Gertjan Klein) Date: Wed, 19 Mar 2008 10:11:18 +0100 Subject: Decode email subjects into unicode References: <47DF8EED.1010501@shopzeus.com> Message-ID: <6gl1u3d3vei5tff9t6ivuhl7gf2qfg6p0k@4ax.com> Laszlo Nagy wrote: >However, there are malformed emails and I have to put them into the >database. What should I do with this: [...] >There is no encoding given in the subject but it contains 0x92. When I >try to insert this into the database, I get: This is indeed malformed email. The content type in the header specifies iso-8859-1, but this looks like Windows code page 1252, where character \x92 is a single right quote character (unicode \x2019). As the majority of the mail clients out there are Windows-based, and as far as I can tell many of them get the encoding wrong, I'd simply try to decode as CP1252 on error, especially if the content-type claims iso-8859-1. Many Windows mail clients consider iso-8859-1 equivalent to 1252 (it's not; the former doesn't use code points in the range \x8n and \x9n, the latter does.) Regards, Gertjan. -- Gertjan Klein From gagsl-py2 at yahoo.com.ar Fri Mar 28 09:41:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 10:41:46 -0300 Subject: Dynamic code problem References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> <8c7f10c60803280314q320884e8k9993592d688fec83@mail.gmail.com> Message-ID: En Fri, 28 Mar 2008 07:14:17 -0300, Simon Brunning escribi?: > On Thu, Mar 27, 2008 at 4:13 PM, wrote: >> My dynamic code failed at this site http://****/, need >> some help thank you. > > I assumed it was just spam, not a question. -- Gabriel Genellina From riccardocirello at gmail.com Tue Mar 25 07:54:38 2008 From: riccardocirello at gmail.com (cuordileone) Date: Tue, 25 Mar 2008 04:54:38 -0700 (PDT) Subject: Outlook 2003 and Python Message-ID: Good Day. I woul like to ask you if it is possible to make a program in python that move the email messages that I had received in outlook 2003, to a specific folder, accoding to the sender's name: Es: martin at martin.com -->> folder Martin. Thanks. Riccardo. From mensanator at aol.com Mon Mar 10 21:17:11 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 10 Mar 2008 18:17:11 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> Message-ID: On Mar 10, 6:32?pm, Nathan Pinno wrote: > On Mar 10, 12:10 pm, Mensanator wrote: > > > > > > > On Mar 10, 12:48 am, Gabriel Genellina wrote: > > > > On 10 mar, 02:08, Nathan Pinno wrote: > > > > > How do I factor a number? > > > If factoring is actually what you want, the sympy module can do it. > > > >>> n = 85085**3 > > >>> print n > > 615969217989125 > > >>> import sympy > > >>> f = sympy.factorint(n) > > >>> f > > > [(5, 3), (7, 3), (11, 3), (13, 3), (17, 3)]>>> ff = [[i[0]]*i[1] for i in f] > > >>> ff > > > [[5, 5, 5], [7, 7, 7], [11, 11, 11], [13, 13, 13], [17, 17, 17]]>>> fff = sympy.flatten(ff) > > >>> fff > > > [5, 5, 5, 7, 7, 7, 11, 11, 11, 13, 13, 13, 17, 17, 17] > > > Provided that your needs are modest. It claims to be > > able to handle 10 digit factors, but it certainly can't > > handle numbers of this magnitude: > > > 508184298003433059930221143303110332712493139579190463526792062622045893426?23811236647989889145173098650749 > > > As it takes a couple hours of run-time only to crash > > with an out of memory error. > > > If you need to handle something like that, you may want to > > get factor.exe which is part of the MIRACL library. The library > > is in C and doesn't have a Python interface, but you can run > > the .exe from Python and capture the output. > > > Keep in mind two things: factor.exe doesn't have consistent > > output making it more difficult to interpret the captured > > output. I re-compiled my copy of factor.exe to provide > > consistent output. > > > The other thing is that factor.exe sometimes gets confused > > claiming a number is composite that factor.exe is fully > > capable of factoring. Luckily this can be easily fixed in > > the Python program that calls it. > > > In the following example, if factor!.exe (my re-compiled > > version) returns any composites, I simply feed them back > > into the program until all are factored or determinened to > > be truly intractable. > > > Note the times. If you have serious factoring needs, the > > MIRACL solution is better than sympy. > > > ## ?======================================== > > ## ?Phase 1 > > ## ?['COMPOSITE_FACTOR', > > '50818429800343305993022114330311033271249313957919046352679206262204589342?623811236647989889145173098650749'] > > ## > > ## ?['PRIME_FACTOR', '37'] > > ## ?['PRIME_FACTOR', '43'] > > ## ?['PRIME_FACTOR', '167'] > > ## ?['COMPOSITE_FACTOR', '507787751'] > > ## ?['PRIME_FACTOR', '69847'] > > ## ?['PRIME_FACTOR', '30697'] > > ## ?['PRIME_FACTOR', '89017'] > > ## ?['PRIME_FACTOR', '3478697'] > > ## ?['PRIME_FACTOR', '434593'] > > ## ?['PRIME_FACTOR', '49998841'] > > ## ?['PRIME_FACTOR', '161610704597143'] > > ## ?['PRIME_FACTOR', '14064370273'] > > ## ?['COMPOSITE_FACTOR', '963039394703598565337297'] > > ## ?['PRIME_FACTOR', '11927295803'] > > ## > > ## ?0.860000133514 seconds > > ## ?======================================== > > ## ?Phase 2 > > ## ?['COMPOSITE_FACTOR', '507787751'] > > ## > > ## ?['PRIME_FACTOR', '29819'] > > ## ?['PRIME_FACTOR', '17029'] > > ## > > ## ?0.0780000686646 seconds > > ## ?======================================== > > ## ?Phase 3 > > ## ?['COMPOSITE_FACTOR', '963039394703598565337297'] > > ## > > ## ?['PRIME_FACTOR', '518069464441'] > > ## ?['PRIME_FACTOR', '1858900129817'] > > ## > > ## ?0.0469999313354 seconds > > ## ?======================================== > > ## > > ## ?Factoring complete > > ## > > ## ?PRIME_FACTOR 37 > > ## ?PRIME_FACTOR 43 > > ## ?PRIME_FACTOR 167 > > ## ?PRIME_FACTOR 17029 > > ## ?PRIME_FACTOR 29819 > > ## ?PRIME_FACTOR 30697 > > ## ?PRIME_FACTOR 69847 > > ## ?PRIME_FACTOR 89017 > > ## ?PRIME_FACTOR 434593 > > ## ?PRIME_FACTOR 3478697 > > ## ?PRIME_FACTOR 49998841 > > ## ?PRIME_FACTOR 11927295803 > > ## ?PRIME_FACTOR 14064370273 > > ## ?PRIME_FACTOR 518069464441 > > ## ?PRIME_FACTOR 1858900129817 > > ## ?PRIME_FACTOR 161610704597143 > > ## > > ## ?======================================== > > > > I mean how do I translate x! into proper > > > > Python code, so that it will always do the correct math? > > > > Do you want to compute x! (factorial of x)? That is, you want a > > > program that given a 4, returns 24? > > > Think how would you compute it by hand and try to write the same thing > > > using Python instructions. > > > > If you come with a program and have a specific problem someone here > > > will be able to help you, but don't expect your homework to be done > > > for free... > > > > -- > > > Gabriel Genellina > > Thanks on the factoring bit, but I did mean factorial, not factoring. > How do I code that correctly, so that I can figure the following > equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax > error and highlight the !. Because Python doesn't support the factorial operator. > So it would be nice to find a way to solve > such a problem. Instead of using MIRACL which doesn't have a Python interface, you could instaed get the GMP library which DOES have a Python interface (Google for gmpy, make sure to get the version that matches your Python version). Then you can do gmpy.fac(z-1) to get the factorial. or >>> import math >>> import gmpy >>> a = math.cos(gmpy.pi(0)*gmpy.fac(4-1)/4) >>> print a -1.83690953073e-016 > > Thanks, > Nathan P.- Hide quoted text - > > - Show quoted text - From sjmachin at lexicon.net Thu Mar 20 23:51:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Mar 2008 20:51:39 -0700 (PDT) Subject: Trouble with variable "leakage"? References: Message-ID: On Mar 21, 2:05 pm, Jeremy N wrote: > I am working with Python in Maya, and have run into a problem with a > variable changing its contents without being scripted to do so. The > various print() statements below were from my efforts to track down > where it was occurring. I left them in so that anyone running this > will more easily see what's happening. > > On the line that reads 'dx = d1 / dx ; print("dx = %f" % dx)' there > is something happening to the variable that is being printed > repeatedly between the lines. The print statements prior to this > particular line print '...xlist[0][1] = 0.5' . However, on this > line, that variable is being updated to reflect a new value, when no > assignment to that variable has been made at that time. > > This leads me to believe that the variables 'dx' and 'xlist[0][1]' > are inexplicably linked. Actually xlist[i] and ylist[i] are explicably the same for all relevant values of i. > I have no idea why. Please help me. Keep reading ... > > a=[5,0,3,4] > b=[8,3,0,10] > c=[2,4,10,0] > > nlist = [a,b,c] > xlist = [[],[],[]] > > for i in range(len(nlist)) : > relist = list(nlist) > relist.pop(i) Aside: I am NOT going to try to guess what your algorithm should do; I just hope you know what the above is doing ... like why not del relist[i] if you're not interested in the popped value? > dlist = list(nlist[i]) > dlist.pop(0) ; dlist.pop(i) > for j in range(len(relist)) : > d1 = float(nlist[i][0]) > d2 = float(relist[j][0]) > dx = float(dlist[j]) > r1 = 1 - ( abs(d1-dx) / float(d2) ) > if r1 == 0.0 : > r1 += (d1 < d2) > xlist[i].append(float(r1)) > > del d1, d2, dx, relist, dlist > > ylist = list(xlist) insert here: print [id(e) for e in xlist], [id(e) for e in ylist] You'll see that list(xlist) gives you a shallow copy i.e. it doesn't dig deeper and copy the contents of the lists at the next level. You need the deepcopy function of the copy module -- do read the docs. Aside #2: "print" is a statement, not a function. > print(xlist) > print(ylist) > [snip] HTH, John From gagsl-py2 at yahoo.com.ar Tue Mar 25 15:52:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 16:52:50 -0300 Subject: Files, directories and imports - relative to the current directory only References: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> <64suvmF2d8hphU1@mid.individual.net> Message-ID: En Tue, 25 Mar 2008 15:35:34 -0300, Bjoern Schliessmann escribi?: > ptn wrote: >> Traceback (most recent call last): >> File "path.py", line 4, in >> f = open('~/read/foo.txt') >> IOError: [Errno 2] No such file or >> directory: '~/read/foo.txt' >> [...] >> So, what's wrong here? Maybe there's something I haven't set up? > > Simple: the directory "~" doesn't exist. Since you're not using a > shell (but direct file access) there is no tilde expansion, and "~" > is treated as a regular file name. If you need to get the home > directory refer to the environment variable HOME > (os.environ["HOME"]). There even may be a shorter way, please refer > to the os module docs. That shorter way being os.path.expanduser http://docs.python.org/lib/module-os.path.html -- Gabriel Genellina From ptmcg at austin.rr.com Thu Mar 6 14:35:06 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 6 Mar 2008 11:35:06 -0800 (PST) Subject: Exploring Attributes and Methods References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: On Mar 6, 1:14?pm, "keios.ti... at gmail.com" wrote: > Hi, > ?Is there a python command that allows me to extract the names (not > values) of the attributes of a class. > > example > > Class Sample: > ? ? fullname = 'Something' > > How can I know that this class has an attribute called 'fullname'? > > I hope my question is clear. > Thanks If you had posted actual working code, "Class" would be all lower case ("class"). But we get the drift (in general, though, when posting questions about examples from your code, best to copy-paste the actual code, not a paraphrasing of it): print Sample.__dict__.keys() prints: ['__module__', 'fullname', '__doc__'] -- Paul From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 12:24:06 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 18:24:06 +0100 Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> Message-ID: <20080302182406.d9d27c83.randhol+valid_for_reply_from_news@pvv.org> On Sun, 2 Mar 2008 06:15:54 -0800 (PST) Giles Brown wrote: > http://docs.python.org/lib/typeiter.html Thanks! From barronmo at gmail.com Wed Mar 26 19:47:45 2008 From: barronmo at gmail.com (barronmo) Date: Wed, 26 Mar 2008 16:47:45 -0700 (PDT) Subject: subtract dates with time module Message-ID: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> I'm trying to get the difference in dates using the time module rather than datetime because I need to use strptime() to convert a date and then find out how many weeks and days until that date. I'm a beginner so any help would be appreciated. Here is the code: def OBweeks(ptID): qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % (ptID) results = EMR_utilities.getAllData(qry) for items in results: r = re.search('\d\d\d\d-\d\d-\d\d', items) if r: d = time.strptime(r.group(), "%Y-%m-%d') - time.localtime() weeks, days = divmod(d.days, 7) return '%s %s/7 weeks' % (weeks, days) This isn't working. I'm getting "unsupported operand type for -: 'time.struct_time' and 'time.struct_time" error. Thanks, Mike From mentaltruckdriver at gmail.com Sat Mar 1 19:51:08 2008 From: mentaltruckdriver at gmail.com (mentaltruckdriver at gmail.com) Date: Sat, 1 Mar 2008 16:51:08 -0800 (PST) Subject: Python Telnet formatting? Message-ID: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Hi everyone: I posted here a couple days ago looking for some help creating a Telnet-based chat server. You guys pointed me to Twisted, which has solved most of my issues. However, what I want to do is analyze strings received for keywords such as 'listcmds' and have the server return something to the client. I know how to do that part, at least. The issue is, when I use clients like PuTTY, it returns a lot of what appears to be formatting (e.g. if I typed Hello, it would return "\xff \xfb\x1f\xff\ xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) How would I go about filtering this stuff out of the strings? The thing is too, if I use other Telnet programs like Microsoft Telnet, they don't have this formatting, so I want to be able to recognize if it does have this formatting and act based on if it does or if it doesn't. Any help is appreciated, I know I'm probably asking too many questions already :) Thanks everyone. From Lie.1296 at gmail.com Sun Mar 9 00:07:48 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 21:07:48 -0800 (PST) Subject: Python installation problem References: Message-ID: <7dd898c6-da57-4bb2-8077-4455b1cf8eaf@e10g2000prf.googlegroups.com> On Mar 9, 11:42?am, cosmo_gene... at yahoo.com wrote: > Hi Folks, > > I downloaded a pre-compiled version 2.5, and intalled it without any > error message; and I can command line playing on Python through firing > up IDLE or command-line. However, I just can't compile the python file > existing in a directory. Today, I tried to fire Python in a DOS > window, then I got error message: Python is not a runnable command or > batch file. It means that the eveiornment variables of my Python > interpreter are not set well yet. My computer runs a Windows XP. > Anyboy can help on this? Thanks! > > Muddy Coder AFAIK, Python doesn't set environment variables in Windows. To change the environment variable, you go to Control Panel > System > Advanced > Environment Variables > System Variables > In "Path" entry, add Python's installation directory to the end of it (remember to separate it from other directories with semicolons ; Alternatively, you can cd your way through python's directory and always feed absolute path to python.exe, very tiresome, but doesn't require you to add the environment variable. From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:08:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:08:00 -0200 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: En Sat, 01 Mar 2008 22:51:08 -0200, escribi?: > Hi everyone: > > I posted here a couple days ago looking for some help creating a > Telnet-based chat server. You guys pointed me to Twisted, which has > solved most of my issues. > > However, what I want to do is analyze strings received for keywords > such as 'listcmds' and have the server return something to the client. > I know how to do that part, at least. > > The issue is, when I use clients like PuTTY, it returns a lot of what > appears to be formatting (e.g. if I typed Hello, it would return "\xff > \xfb\x1f\xff\ > xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) They are part of the telnet protocol; 0xFF (IAC=Interpret as Command) starts a two or three byte command sequence. Weren't you using telnetlib? It's supposed to handle this transparently. > How would I go about filtering this stuff out of the strings? The > thing is too, if I use other Telnet programs like Microsoft Telnet, > they don't have this formatting, so I want to be able to recognize if > it does have this formatting and act based on if it does or if it > doesn't. Any client could send similar commands at the start of the session, or even later. > Any help is appreciated, I know I'm probably asking too many questions > already :) It isn't too hard to filter them out, if you want to do it by hand. See the source for telnetlib, and the original Telnet specificacion, RFC 854 http://www.rfc-archive.org/getrfc.php?rfc=854 and RFC 855. -- Gabriel Genellina From samslists at gmail.com Mon Mar 17 22:20:25 2008 From: samslists at gmail.com (samslists at gmail.com) Date: Mon, 17 Mar 2008 19:20:25 -0700 (PDT) Subject: Any fancy grep utility replacements out there? Message-ID: So I need to recursively grep a bunch of gzipped files. This can't be easily done with grep, rgrep or zgrep. (I'm sure given the right pipeline including using the find command it could be done....but seems like a hassle). So I figured I'd find a fancy next generation grep tool. Thirty minutes of searching later I find a bunch in Perl, and even one in Ruby. But I can't find anything that interesting or up to date for Python. Does anyone know of something? Thanks From arnodel at googlemail.com Sun Mar 16 09:28:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 16 Mar 2008 13:28:19 GMT Subject: Advantage of the array module over lists? References: Message-ID: Tobiah writes: > I checked out the array module today. It claims that > arrays are 'efficient'. I figured that this must mean > that they are faster than lists, but this doesn't seem > to be the case: > > ################ one.py ############## > import array > > a = array.array('i') > > for x in xrange(10000000): > a.append(x) > > for x in a: > a[x] += 1 > > ################ two.py ############## > a = [] > > for x in xrange(10000000): > a.append(x) > > for x in a: > a[x] += 1 > > ###################################### > > > ktops:toby:pytest> time python one.py; time python two.py > > real 0m28.116s > user 0m17.504s > sys 0m10.435s > > real 0m23.026s > user 0m13.027s > sys 0m9.777s > > > Perhaps the only advantage is that they take less memory > to store a large number of items? It would seem then, that > 'economical' might have been a better choice of word than > 'efficient'. I get an even bigger difference with this test (same as yours, but using timeit and using an allegedly more efficient way of initialising the array) >>> def test(arr, n): ... a = arr(xrange(n)) ... for x in a: ... a[x] += 1 ... >>> n = 10000000 >>> import timeit >>> timeit.Timer('test(list, n)', 'from __main__ import test, n').timeit(1) 2.4988760948181152 >>> from array import array >>> arr = lambda n: array('i', n) >>> timeit.Timer('test(arr, n)', 'from __main__ import test, arr, n').timeit(1) 5.7419960498809814 >>> -- Arnaud From torriem at gmail.com Thu Mar 6 11:21:42 2008 From: torriem at gmail.com (Michael L Torrie) Date: Thu, 06 Mar 2008 09:21:42 -0700 Subject: Hi In-Reply-To: References: Message-ID: <47D01A16.5080104@gmail.com> hellogaurang at gmail.com wrote: > Hello > > can u plz tell how to send and read msg from device(telit-863-GPS) and > the coding is in python. > > if this can happen then plz send the source code to my mail account Sounds like a new development model. You should patent this. Just e-mail lists with cryptic requests for code, then combine the resulting fragments into one executable. In fact, if you do it in chain letter form, you can get code even faster. I heard a rumor once that's how Windows Me was originally built. From lialie at gmail.com Fri Mar 28 12:58:34 2008 From: lialie at gmail.com (KingMax) Date: Fri, 28 Mar 2008 09:58:34 -0700 (PDT) Subject: Problem with write binary data to OLE field in Access References: <47EA77FB.3080706@gmail.com> Message-ID: <1a1cde72-051b-468b-a470-3441fa621dcd@e6g2000prf.googlegroups.com> On 3?27?, ??7?22?, Tim Golden wrote: > lialie wrote: > > [... snip slightly confused indication that reading back a > binary item using GetChunk appears to double its length ...] > > Well I don't know why this should be happening, but I do at > least have a few suggestions: > > 1) Try using ADODB.Stream instead of GetChunk etc. > > 2) Try using the adodbapi dbapi-compliant wrapper > > 3) Try using ODBC (via PyODBC, CeODBC etc.) > > I've no idea if any of these will do any better but at > least it gives you some possibilities :) > > TJG Thanks! I try using ADODB.Stream to implement it. But the situation is the same. At last, I try this, and it seems to work. 1) Save the image to the dist. 2) using ADODB.Stream.LoadFromFile 3) Save it into access and then first step done. when using it, I try this: 1) ADODB.Stream.Write(Record.Fields("xxx").Value) 2) ADODB.Stream.SaveToFile("test.jpg") 3) using wxImage to load it in. a little stupid :( From gherron at islandtraining.com Sat Mar 8 11:47:45 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 08 Mar 2008 08:47:45 -0800 Subject: parralel downloads In-Reply-To: References: Message-ID: <47D2C331.4020708@islandtraining.com> poof65 wrote: > For your problem you have to use threads. > Not at all true. Thread provide one way to solve this, but another is the select function. For this simple case, select() may (or may not) be easier to write. Pseudo-code would look something like this: openSockets = list of sockets one per download file: while openSockets: readySockets = select(openSockets ...) # Identifies sockets with data to be read for each s in readSockets: read from s and do whatever with the data if s is at EOF: close and remove s from openSockets That's it. Far easier than threads. Gary Herron > You can have more information here. > http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > >> Hi, >> >> I would like to write a python script that will download a list of >> files (mainly mp3s) from Internet. For this, I thought to use urllib, >> with >> >> urlopen("myUrl").read() and then writing the resulting string to a >> file >> >> my problem is that I would like to download several files at the time. >> As I have not much experience in programming, could you point me the >> easier ways to do this in python ? >> >> Thanks, >> >> JD >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> From davecook at nowhere.net Sun Mar 2 06:16:37 2008 From: davecook at nowhere.net (David Cook) Date: Sun, 02 Mar 2008 11:16:37 GMT Subject: Book Recomendations References: Message-ID: On 2008-03-02, Jeff Schwab wrote: > Python In A Nutshell: > http://www.oreilly.com/catalog/pythonian2/ Another vote for the Nutshell book, which I find a very useful and practical book. I never found the "Dive in" book useful. Dave Cook From jeff at schwabcenter.com Sat Mar 22 17:10:39 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 14:10:39 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Anyway, here the conclusion that I draw: learn lambda-calculus and > Turing machines. The rest is syntactic sugar. How is the lambda-calculus fundamentally different from Turing machine-based implementations? I've been learning a fair amount about functional programming recently, mostly because compile-time C++ turns out to be a pure functional programming language. Where should I go for a solid grounding in lambda-calculus? Also, despite reassurances to the contrary, I still get the impression that there is a strong anti-lambda sentiment among the Python "in" crowd. Is it just a question of the word "lambda," as opposed to perceived cleaner syntax? http://www.artima.com/weblogs/viewpost.jsp?thread=98196 http://www.python.org/dev/peps/pep-0290/#replacing-common-uses-of-lambda -- Said the Rabbi Hillel, "All the rest is commentary." From python.list at tim.thechases.com Wed Mar 5 07:12:40 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 05 Mar 2008 06:12:40 -0600 Subject: Using re module better In-Reply-To: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> Message-ID: <47CE8E38.80201@tim.thechases.com> > if (match = re.search('(\w+)\s*(\w+)', foo)): Caveat #1: use a raw string here Caveat #2: inline assignment is verboten match = re.search(r'(\w+)\s*(\w*+)', foo) if match: > field1 = match.group(1) > field2 = match.group(2) This should then work more or less. However, since you know there are two matches, you can just use field1, field2 = match.groups() If the regexp is one you plan to reuse (or call in a loop), you can pre-compile it: r = re.compile(r'(\w+)\s*(\w*+)') for thing in bunch_of_things: m = r.search(thing) if m: field1, field2 = m.groups() do_something(field1, field2) HTH, -tkc From gherzig at fmed.uba.ar Fri Mar 14 08:30:46 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 14 Mar 2008 09:30:46 -0300 Subject: request for Details about Dictionaries in Python In-Reply-To: References: Message-ID: <47DA6FF6.5000505@fmed.uba.ar> Saideep A V S wrote: >Hello Sir, > > I am a beginner level programmer in Python. I am in search of a >function for 'On-Disk' Dictionaries which is similar to On-Disk Hash tables >in Perl (i.e., tie function in Perl). > > > Could anyone help me with the concept. I have also searched the net, but >was not successful in finding any related. > >Awaiting your Solutions. > >Thanks in Advance. > >Saideep > > > I guess you are looking for shelve http://docs.python.org/lib/module-shelve.html Gerardo From noorhanabbas at yahoo.co.uk Sun Mar 2 09:04:16 2008 From: noorhanabbas at yahoo.co.uk (Noorhan Abbas) Date: Sun, 2 Mar 2008 14:04:16 +0000 (GMT) Subject: Sparta api Message-ID: <908801.95306.qm@web27409.mail.ukl.yahoo.com> Hello, I wonder if anybody has used the sparta api for linking RDF to Python. I was trying to run the example supplied by sparta and I got this error message Traceback (most recent call last): File "C:/Python25/TestSpartaApi.py", line 10, in store = Graph() File "C:\Python25\lib\rdflib\Graph.py", line 265, in __init__ self.__store = store = plugin.get(store, Store)() File "C:\Python25\lib\rdflib\rdflib\plugin.py", line 27, in get raise Exception("could not get plugin for %s, %s: %s" % (name, kind, e)) Exception: could not get plugin for default, : Any idea what is the problem? Noorhan __________________________________________________________ Sent from Yahoo! Mail. A Smarter Inbox. http://uk.docs.yahoo.com/nowyoucan.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Wed Mar 5 22:51:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:51:35 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> <7a8a2706-10d0-4f50-b5ad-8b490e57edd5@y77g2000hsy.googlegroups.com> Message-ID: <44a11efa-f1d7-458c-93f0-f0d6f744dfcd@m34g2000hsc.googlegroups.com> > > > If I understand your question, classes are not singletons: > > >>>> ll=[] > > >>>> for i in range(2): > > > ?import string > > > ?ll[i]=string > > > Where's the IndexError? :-) > > > I accept my question about classes being singletons is not well-formed, > > not even in my own mind. I guess one way of asking is, for any two class > > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? Similarly, no. >>> class metaC( type ): ... def __eq__( self, other ): ... return True ... >>> class C( metaclass= metaC ): ... pass ... >>> class D( metaclass= metaC ): ... pass ... >>> C==D True >>> C is D False +1 raised eyebrow From bronger at physik.rwth-aachen.de Mon Mar 17 03:47:53 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 17 Mar 2008 08:47:53 +0100 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> Message-ID: <873aqp6bbq.fsf@physik.rwth-aachen.de> Hall?chen! Carl Banks writes: > On Mar 16, 10:49 pm, Brian Jones wrote: >> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: >> >>> If you did not like the programming this year (aside from the >>> sponsor talks) and you did not participate in organizing PyCon >>> or in delivering presentations, it is YOUR FAULT. PERIOD. >>> EXCLAMATION POINT! >> >> I find this insulting, inexcusable, and utter nonsense. If >> putting the blame for a failed experiment on the backs of the >> good folks who paid good money for travel, lodging, and >> registration is also an experiment, you can hereby consider it >> also failed. > > He said "aside from the sponsor talks", chief. I see no reason why the "fault" for parts of the rest being sub-optimal, too, must necessarily be on the attendee's side. (Just hypothetically; I wasn't at PyCon.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From andrew-news at andros.org.uk Fri Mar 28 14:11:56 2008 From: andrew-news at andros.org.uk (Andrew McLean) Date: Fri, 28 Mar 2008 18:11:56 +0000 Subject: Instrumented web proxy In-Reply-To: <7xod8zrhb9.fsf@ruckus.brouhaha.com> References: <7xod8zrhb9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Andrew McLean writes: >> I would like to write a web (http) proxy which I can instrument to >> automatically extract information from certain web sites as I browse >> them. Specifically, I would want to process URLs that match a >> particular regexp. For those URLs I would have code that parsed the >> content and logged some of it. >> >> Think of it as web scraping under manual control. > > I've used Proxy 3 for this, a very cool program with powerful > capabilities for on the fly html rewriting. > > http://theory.stanford.edu/~amitp/proxy.html This looks very useful. Unfortunately I can't seem to get it to run under Windows (specifically Vista) using Python 1.5.2, 2.2.3 or 2.5.2. I'll try Linux if I get a chance. From johan.de.taeye at gmail.com Tue Mar 18 03:51:58 2008 From: johan.de.taeye at gmail.com (jdetaeye) Date: Tue, 18 Mar 2008 00:51:58 -0700 (PDT) Subject: Extending C++ with Python scripting: "twin objects" or "proxy objects"? Message-ID: <27add36a-dab9-4528-9f2f-6732e92aa8bc@p73g2000hsd.googlegroups.com> Hi, I would like to use Python as a scripting language for a C++ framework I am working on. The most common approach for this seems to be a "twin objects": the python and the C++ object have the same lifespan and are always linked to each other. My initial thinking was to use a "proxy approach" instead: the python object is only a temporary proxy object with a pointer to the real C++ object. The C++ object would live much longer than the proxy. Is the proxy approach a valid alternative? I can't imagine it hasn't been done before... I am interested in hearing your experiences with it... Currently I see the following + and -: + Easier for the C++ code (ie less changes, less coupling, no gc- issues) - Extending the framework through subclasses in Python is much harder Anything else? Regards, Johan From arnodel at googlemail.com Mon Mar 24 09:48:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Mar 2008 06:48:10 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> Message-ID: <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> On Mar 24, 1:26?pm, Steven D'Aprano wrote: > On Mon, 24 Mar 2008 04:33:53 -0400, Terry Reedy wrote: > > The fact that .func_name (which is writeable) is not used at first > > surprised me until I remembered that code objects can potentially be > > used by multiple function objects and hence are not connected to any one > > in particular. > > How does that happen? Like this: >>> def foomaker(x): ... def foo(y): return x+y ... return foo ... >>> foo1 = foomaker(1) >>> foo2 = foomaker(2) >>> foo1.func_code ", line 2> >>> foo2.func_code ", line 2> Of course foo1 and foo2 are not the same thing: >>> foo1(8) 9 >>> foo2(8) 10 > And if it is the case, what's the justification for giving them a co_name > attribute? Surely the name of the function should be that of the function > object, not of one of the shared parts? >>> foo1.__name__ 'foo' >>> foo1.func_code.co_name 'foo' As seen above, func.__name__ and func.func_code.co_name are the same thing (until tampered with). -- Arnaud From Lie.1296 at gmail.com Sun Mar 2 01:33:21 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 1 Mar 2008 22:33:21 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> <7x3ara9r4n.fsf@ruckus.brouhaha.com> Message-ID: On Mar 2, 2:32?am, Paul Rubin wrote: > Lie writes: > > I see, but the same arguments still holds true: the second line have > > an implicit side-effect of redefining x's type into Fractional type. > > If I were the designer of the language, I'd leave x's type as it is > > (as Num) and coerce x for current calculation only. > > Num in Haskell is not a type, it is a class of types, i.e. if all you > know about x is that it is a Num, then its actual type is > indeterminate. ?Types get inferred, they do not get coerced or > "redefined". ?The compiler looks at expressions referring to x, to > deduce what x's type actually is. ?If it is not possible to satisfy > all constraints simultaneously, then the compiler reports an error. So basically they refused to satisfy everything that is still possible individually but would conflict if done together. (I know Haskell not more than just its name so I don't understand the rationale behind the language design at all) But I'm interested in how it handles these cases: x = 1 a = x + 1 << decides it's an int b = x + 1.0 << error? or redefine to be float? c = x + 1 << would this cause error while it worked in line 2? A slightly obfuscated example: l = [1, 1.0, 1] x = 1 for n in l: c = x + n From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:42:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:42:08 -0300 Subject: Python and Db References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> Message-ID: En Mon, 31 Mar 2008 14:50:27 -0300, David Anderson escribi?: > Hi! I'm don't know almost nothing about bds, Can You suggest me an Simple > but efficient Bd to work with python apps? Can You suggest me any > tutorials? See the Python wiki at: http://wiki.python.org/moin/DatabaseProgramming If you stick with DBAPI 2.0 you won't have much trouble writing for one database or another. sqlite is a good start and is included with Python 2.5 -- Gabriel Genellina From stargaming at gmail.com Wed Mar 12 09:00:58 2008 From: stargaming at gmail.com (Stargaming) Date: 12 Mar 2008 13:00:58 GMT Subject: catching object References: Message-ID: <47d7d40a$0$2659$9b622d9e@news.freenet.de> On Wed, 12 Mar 2008 01:05:06 +0100, Igor V. Rafienko wrote: > Hi, > > > I was wondering if someone could help me explain this situation: > > h[1] >>> import inspect > h[1] >>> inspect.getmro(ValueError) > (, , > , , 'object'>) > h[2] >>> try: > raise ValueError("argh") > except object: > print "why not?" > > Traceback (most recent call last): > File "", line 2, in > ValueError: argh > > The question is, why isn't ValueError caught? It *does* inherit from > object (albeit indirectly), and my understanding of the wording of > CPython docs is that this guarantees "compatibility" (between what is > being raised and what is being caught). I think inheritance is meant in reference to the Exception tree here. So, the uppermost class is `BaseException`. Python 3 gives this exception when trying to handle `object`:: TypeError: catching classes that do not inherit from BaseException is not allowed You are right, the wording is quite confusing here but that might be due to the crude situation of exceptions: All old-style classes (deprecated themselves) can be raised. Strings can still be raised but this is deprecated. New-style classes can be raised but only if they inherit (at least indirectly) from BaseException. I'd say: feel free to contribute patches. :-) > So, why doesn't object match ValueError (or any other exception for that > matter). I am aware of "except:", but in my particular situation it is > eh... unsuitable. Why so? The only possible solution me and my crystal ball could come up with is that you're having a lot of old-style exceptions raised from some library you cannot modify. You cannot handle any common base class and don't want to handle every of the exceptions. If that's the case, just use a bare `except` and utilize `sys.exc_info`. HTH, From karunakaran341 at gmail.com Tue Mar 18 03:39:26 2008 From: karunakaran341 at gmail.com (karunakaran341 at gmail.com) Date: Tue, 18 Mar 2008 00:39:26 -0700 (PDT) Subject: please click here Message-ID: <6f738f23-8ac0-41b3-9d44-e7016a6613f3@e10g2000prf.googlegroups.com> please click here **************************************************** http://profile_myprofile.blogspot.com **************************************************** From sjmachin at lexicon.net Sun Mar 23 20:58:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 17:58:03 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> On Mar 24, 11:42 am, George Sakkis wrote: > On Mar 23, 8:01 pm, QS wrote: > > > > > Hi to all! > > I am new to python, and I encountered a weird problem. > > > Here is my code > > > ##########>8#################### > > #!/usr/bin/python > > # Filename: objvar.py > > class Person: > > '''Represents a person.''' > > > population = 0 > > #sex = 'F' > > #age = 22 > > # It is vague here: is this variable going to be a class, or > > object, variable > > > def __init__(self, name, sex): > > '''Initializes the person's data.''' > > self.name = name > > self.sex = sex > > print '(Initializing %s )' % self.name > > # When this person is created, he/she > > # adds to the population > > Person.population += 1 > > > def __del__(self): > > '''I am dying.''' > > > print '%s says bye.' % self.name > > Person.population -= 1 > > if Person.population == 0: > > print 'I am the last one.' > > else: > > print 'There are still %d people left.' % > > Person.population > > > def sayHi(self): > > '''Greeting by the person. > > > Really, that's all it does.''' > > > self.age = 25 > > print 'Hi, my name is %s, and I am %s, and I am age %d ' % > > (self.name, self.sex, self.age) > > > def howMany(self): > > '''Prints the current population.''' > > if Person.population == 1: > > print 'I am the only person here.' > > else: > > print 'We have %d persons here.' % Person.population > > > swaroop = Person('Swaroop', 'M') > > swaroop.sayHi() > > swaroop.howMany() > > kalam = Person('Abdul Kalam', 'M') > > kalam.sayHi() > > kalam.howMany() > > cathy = Person('Catherine', 'F') > > cathy.sayHi() > > cathy.howMany() > > swaroop.sayHi() > > swaroop.howMany() > > > ############# 8< ######################### > > > When I run this script, I got the following exception: > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'population'" in > <__main__.Person instance at 0xb7d8ac6c>> ignored > > > To to newcomer like me, this message doesn't make much sense. What > > seems weird to me is that, if I change the variable cathy to something > > else, like cath, or even cat, then the script will finish gracefully. > > Why "cathy" is not liked?!! > > > Some of you may have recognized that the code is derived from a sample > > code in Swaroop's "A byte of python". > > > My python is of version 2.5.1, on Ubuntu. > > That's really weird... it's reproducible on Windows too. It doesn't > make any sense why the name of the variable would make a difference. > My guess is you hit some kind of obscure bug. > My guess after reading the manual: """ Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted. For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. """ is that farnarkeling about in a __del__ method is *not* a good idea. From jari.aalto at cante.net Sat Mar 8 05:47:33 2008 From: jari.aalto at cante.net (Jari Aalto) Date: Sat, 08 Mar 2008 12:47:33 +0200 Subject: distutils - Is is possible to install without the .py extensions References: Message-ID: * Fri 2008-03-07 Robert Kern gmane.comp.python.general * Message-Id: fqt61a$sj5$1 at ger.gmane.org >>>> setup(name='program', >> ... >>>> scripts = ['program,py'], >>>> ) >>>> that the the result is: >>>> >>>> /usr/bin/program >>>> >>>> instead of: >>>> >>>> /usr/bin/program.py >>> >>> The easiest and best way is to just rename the file in your source tree to >>> "program" and be done with it. >> >> Is there any other way? This is the source package that I would like >> to keep intact and just patch the setup.py > > Not really, no. Why is it so important to only patch the setup.py > file and not any others? It has to do with generating a diff against the original package. If the file is moved: mv file.py file prior setup.py run (which, according to answers, would have a change to <>), the problem is the generated diff against original sources: + would flag removal of 'file.py' + inclusion of 'file' The ideal would be if setup.py could do all the destination install "postwork". The generated patch would be clean and only contain changes in setup.py. But I understand, if distutils does not support stripping the extensions during install. It just cacuses exra work for utility packagers. Jari -- Welcome to FOSS revolution: we fix and modify until it shines From morse at edoug.org Sun Mar 16 05:22:12 2008 From: morse at edoug.org (Doug Morse) Date: Sun, 16 Mar 2008 09:22:12 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: <97432b58-958c-43ec-b48a-6849f9abed4a@v3g2000hsc.googlegroups.com> Message-ID: Hi Harald, Bond here, James Bond. I accepted your mission. :) Unfortunately, the mission failed. Creating a "testapp.py" as you described (i.e., with the suggested import statements) runs just fine with the interpreter. again, however, py2exe does the same thing as the original problem -- that is, copies numpy.core's versions of multiarray.pyd and umath.pyd into dist/, creates what look like stub multiarray.pyc and umath.pyc files in library.zip/ and library.zip/numpy/core/. when this py2exe version is run, it throws the same (original) TypeError: data type not understood error. Also, with either my original program or testapp.py, I cannot seem to modify library.zip in such a way as to get the program to run. Basically, I unzipped library.zip, made the same modifications to it's contents as I did when using the --skip-archive option (i.e., remove the stub files and put the right .pyd files in the right locations) and then recreated the library.zip file. Afterwards, running either origapp.exe or testapp.exe, the program bombs out with ImportError: no module named multiarray. In addition, I tried using py2exe to make a simple "Hello, world" program. It runs just fine. Then, I "zip -m library.zip *.pyd" in the dist/ directory to move the .pyd files into library.zip. Then, running hello.exe again works just fine. However, if I add "import bz2; print bz2.__author__" after "print 'Hello, world!'" (the only line in hello.py), hello.exe bombs out with "ImportError: DLL load failed: The specified module could not be found" when I run it after having moved *.pyd into library.zip/. (bz2 was one of only two .pyd files that py2exe put into dist/.) So, I can seem to figure out how to get .pyd files into library.zip, even when there are no name conflicts. What am I doing wrong? Finally, regarding the stub files, if I use vi to edit the py2exe-generated, 536-byte bz2.pyc file (there is no such file in my python install directory hierarchy), I see the word "import" very close to the word "bz2.pyd". This suggests to me that py2exe might indeed be creating simple import statements in a short .py file for each .pyd file and then compiling it into a .pyc stub file -- or at least doing something similar. Of course I can't be sure of this, but it seems likely to me. Thanks again to you and everyone. I'll definitely visit the py2exe wiki and see what I can come up with (and or course will report back with success / failures). If you or anyone has any further thoughts based on this post, I'm all ears and would be most grateful. Regards, Doug On Sun, 16 Mar 2008 00:33:31 -0700 (PDT), GHUM wrote: > Doug, > > > as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. > > I'm guessing that they can't be in library.zip for a reason (i.e., they are > > DLL files, essentially, and thus must be readily available to be loaded > > into memory). > > .dll and .pyd files CAN be within library.zip and even within the > single-file-exe. > > There is some Hellermagic within _memimporter.pyd that loads the .dll > and .pyd from a zipfile. When you scan the build_exe.py, you will > explicitely find: > > print "*** finding dlls needed ***" > dlls = self.find_dlls(extensions) > self.plat_finalize(mf.modules, py_files, extensions, dlls) > dlls = [item for item in dlls > if os.path.basename(item).lower() not in > self.dll_excludes] > # should we filter self.other_depends in the same way? > > > Is there a work-around for this, then? > -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd > -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/ > multiarray.pyd > -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/ > umath.pyd > -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd > > let's try: your mission is, should you chose to accept it, to make a > py2exed application to load two different multiarray.pyd, who are on > the visible level only different by their place in the file system. > > So, please make a minimal script: > > import multiarray > import numpy.core.multiarray as ncmultiarray > > and, using Peters test > >>> from multiarray import zeros > assert zeros((1,), "1") == array([0], '1') > > and check, if those multiarrays are the correct ones. If yes, you can > try to build upon this by making all imports explicit as described > above. (Yes, I know, that's not necessary in plain python ... but it > saved me in some weird "import from .zip" and "import from database" > situations.) > > > (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and > > umath.pyd files > > somewhere deep inside I have a BAAAD feeling about to files having the > same name but very very different content - but that's not your call > in this situation. > Are you able to build that libraries yourself? Then you could move > down and build the multiarray.pyd as ncmultiarray.pyd and adjust all > imports accordingly. (lots of work) > > > manual create the "stub"-like .pyc files that py2exe creates to point to > > these alternate .pyd files and then place these stubs in > > library.zip/numpy/core? ? > > As much as I know there is only one central "loader stub", which > ensures that .dlls get imported from memory, see above. py2exe does > not create something like p2elma.py containing "import multiarray.pyd" > > best luck, and please take your time to scan the py2exe.org wiki, > there are many similiar challanges with various packages, maybe you > get another workaround-idea (and, if we find one, PLEASE put it down > there for others to learn) > > best wishes, > > Harald From ron.longo at cox.net Sat Mar 29 16:26:41 2008 From: ron.longo at cox.net (Ron Provost) Date: Sat, 29 Mar 2008 16:26:41 -0400 Subject: tkinter coordinates, conversion Message-ID: <000701c891db$3306ad00$6501a8c0@aristotle> Is there any way in tkinter to convert between coordinate systems? Specifically, I'm refering to the canvas. I'm getting x and y's back in mouse events and I would like to convert them back to inches 'i', centemeters 'c', millimeters 'm' or points 'p'. Which I wish to use to provided information back to the user. Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Mar 7 14:14:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:14:59 -0800 (PST) Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: On Mar 7, 11:49?am, Krishna wrote: > On Mar 6, 5:04 pm, "Gabriel Genellina" wrote: > > > > > > > En Thu, 06 Mar 2008 22:48:42 -0200, Krishna > > escribi?: > > > >>>> class Test(object): > > > ... ? ? def __init__(self): > > > ... ? ? ? ? ? ? self.a= 2 > > > ... ? ? def func(self, k = self.a): > > > ... ? ? ? ? ? ? print k > > > ... > > > Traceback (most recent call last): > > > ? File "", line 1, in ? > > > ? File "", line 4, in Test > > > NameError: name 'self' is not defined > > > > In the 'definition of the class', what would the first argument 'self' > > > in the methods evaluate to; when we have an object defined, it is > > > bound to the object reference, but what happens while the class > > > definition is executed, which I believe happens when the module > > > containing the class definition is imported > > > Function default arguments are evaluated when the function is defined > > (when the class is defined, in this case) so "self" itself has not a > > value. Try this instead: > > > ? ? ?def func(self, k=None): > > ? ? ? ? ?if k is None: > > ? ? ? ? ? ? ?k = self.a > > ? ? ? ? ?print k > > > If None is an allowed argument, use a special marker instead: > > > _marker=object() > > ... > > > ? ? ?def func(self, k=_marker): > > ? ? ? ? ?if k is _marker: > > ? ? ? ? ? ? ?k = self.a > > ? ? ? ? ?... > > > -- > > Gabriel Genellina > > Thanks for the reply. I am currently using the approach suggested by > you. But, I am more interested in knowing about the first argument > ('self'), what does it hold to allow the evaluation of the method, > take the example you gave, 'self.a' as Rvalue inside the method, how > and why is this allowed, when the same 'self.a' is not allowed as the > default argument, considering the fact that I have already specified > 'self' as first argument, only after whose evaluation, I believe would > the next statement (k = self.a, in def func(self, k = self.a) ) gets > evaluated > > Thanks, > Krishna- Hide quoted text - > > - Show quoted text - Is there enough information at that point in the statement to assign to k as specified by this language? No. Does there exist a possible language in which there is? Yes. From romano.giannetti at gmail.com Fri Mar 7 10:18:11 2008 From: romano.giannetti at gmail.com (rmano) Date: Fri, 7 Mar 2008 07:18:11 -0800 (PST) Subject: Embedding a literal "\u" in a unicode raw string. References: <47C340D4.6020803@v.loewis.de> <891938ee-ad81-43de-9985-73cd26e4268d@s12g2000prg.googlegroups.com> Message-ID: <3c48fbef-00aa-474e-b6f5-9962b3736eed@n36g2000hse.googlegroups.com> On Mar 4, 1:00 pm, NickC wrote: > > Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> r"\u" > '\\u' > >>> r"\uparrow" > '\\uparrow' Nice to know... so it seems that the 3.0 doc was not updated. I think this is the correct behaviour. Thanks From sturlamolden at yahoo.no Tue Mar 18 17:56:02 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 14:56:02 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> Message-ID: <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> On 18 Mar, 22:25, sturlamolden wrote: > def nonunique(lst): > slst = sorted(lst) > return list(set([s[0] for s in > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using the set function, there is more structure to exploit when the list is sorted: def nonunique(lst): slst = sorted(lst) dups = [s[0] for s in filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] return [dups[0]] + [s[1] for s in filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] From zerty.david at gmail.com Thu Mar 27 21:40:41 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 27 Mar 2008 22:40:41 -0300 Subject: Getting back an Object Message-ID: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> Well, I've got a little problem, I have a list that contains objects from the class C, then I use those objects.__str__ to generate a ListCtrl, A wxPython widget that makes a list of strings and then you can handle events when selected, and returns the string selcted, how can I access the "parent" of that string? I tried to search on the array like this: def search(self, string): for obj in self.list: if string == obj.__str__: return obj return None But I always get None... What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Wed Mar 12 14:49:54 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 13:49:54 -0500 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: References: Message-ID: <47D825D2.20301@tim.thechases.com> > The subject says pretty much all, Given what I understand about the BEGIN block[1], this is how Python works automatically: bash$ cat a.py print 'a1' import b print 'a2' bash$ cat b.py print 'b' bash$ python a.py a1 b a2 However, the first import does win and Python caches module-loading, so take care: bash$ cat x.py print 'one' import a print 'two' import b print 'three' bash$ python x.py one a1 B a2 two three -tkc [1] http://www.cs.cf.ac.uk/Dave/PERL/node133.html From cwitts at gmail.com Thu Mar 13 05:31:38 2008 From: cwitts at gmail.com (Chris) Date: Thu, 13 Mar 2008 02:31:38 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <9a1d9da3-42a7-4138-b53b-9ee690b77b7e@p73g2000hsd.googlegroups.com> On Mar 13, 9:36?am, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) ?[1,2,3,4] > 2) ?[1,2,3,4,5] > 3) ?That famous picture of Albert Einstein sticking out his tongue > 4) ?Nothing - no output > 5) ?None of the above > > I undertake to summarise answers posted to complete this "survey". > > - Hendrik No output because x is a NoneType... From craigm3604 at gmail.com Sat Mar 22 02:21:48 2008 From: craigm3604 at gmail.com (Craig) Date: Fri, 21 Mar 2008 23:21:48 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> Message-ID: <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> On Mar 21, 4:04 am, Dennis Lee Bieber wrote: > On Thu, 20 Mar 2008 16:50:18 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > > > I received a direct email from someone, and I came up with the > > following after implementing his advice: > > Just for completeness... I'm the "someone"... And this is a copy of > the message in question: > > > > > > > Please forgive my going direct -- I do not have Usenet posting privileges from work. > > > From your message: > > > -=-=-=-=-=-=- > > And, this is what printed: > > After - X = 4325376, CacheSize = 0, OpenMode = 3, vHandle = 17586736 > > > The printf shows that the values of X and vHandle have changed, but I > > am not sure it is working properly as X should be a MUCH smaller > > number (< 256). I would have expected a 0 (VIS_OK), 13 (VIS_DOS_ERROR) > > or 14(VIS_DISK_ERROR) if it had worked. > > > Next, I changed: > > fName = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", > > 13) > > so that I knew it would not find the file, and got: > > After - X = 2555917, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > The vHandle staying 0 tells me that it did not find the file, but the > > value of X seems random. > > -=-=-=-=-=-=-=- > > > X does NOT seem random to me -- but I took the effort to render it in hexadecimal. X seems to be coming back as a 32-bit integer. Your <256 code appears to be in the second half of that integer -- observe: > > > >>> "%8.8X" % 4325376 > > '00420000' > > >>> "%8.8X" % 2555917 > > '0027000D' > > > Also observe that x0D => 13 decimal... your stated "VIS_DOS_ERROR" code. > > > >>> 0x0042 > > 66 > > >>> 0x0027 > > 39 > > >>> 0x000d > > 13 > > > I have no explanation for the leading 16-bits... But under the rules of Python, "X = ..." is commonly a rebinding operation, so presetting X as a ctypes short integer may not be having any effect (I suspect those are more important for calls where the input parameters need to be mutable and of a known C format). > > > >>> import ctypes > > >>> x = ctypes.c_short(123) > > >>> dir(x) > > ['__class__', '__ctype_be__', '__ctype_le__', '__ctypes_from_outparam__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_as_parameter_', '_b_base_', '_b_needsfree_', '_objects', '_type_', 'value'] > > > >>> x > > c_short(123) > > >>> x.value > > 123 > > > >>> x.value = 13 > > >>> x > > c_short(13) > > > Note that in this I have assigned to the "value" component of a c_short object. Plugging in your results values: > > > >>> x.value = 4325376 > > >>> x > > c_short(0) > > >>> x.value = 2555917 > > >>> x > > c_short(13) > > > Gives... ta da... 0 and 13 respectively. Perhaps you should, after creating X as a c short object, be assigning to the value, not to the object... > > > X.value = windll. ... > > > {Replies are being directed to my home email} > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Sorry, I wasn't trying to exclude any credit from Dennis, I just wasn't sure if he wanted to be listed. As it turns out, I am running into more of these BSTR and pointer problems. I have moved on to the next function to convert: short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS lpvstats); which uses a structure: typedef struct tagVSTATS { LONG nrecords; WORD gps_used; WORD gps_unused; WORD max_key_len; LONG grp_size; WORD init_alloc; WORD cr_opts; WORD free_prop_area; BSTR format; BSTR reserved; } VSTATS; typedef VSTATS FAR * LPVSTATS; This is what I have tried: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf LPBSTR = POINTER(c_void_p) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) LPVSTATS = POINTER(c_void_p) class VSTATS(Structure): _fields_ = [ ("nrecords", c_long), ("gps_used", c_short), ("gps_unused", c_short), ("max_key_len", c_short), ("grp_size", c_long), ("init_alloc", c_short), ("cr_opts", c_short), ("free_prop_area", c_short), ("format", c_void_p), ("reserved", c_void_p) ] vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) VmxInfo = windll.vbis5032.VmxInfo VmxInfo.restype = c_short VmxInfo.argtypes = [LPHANDLE, LPVSTATS] print "\n(2) VB/ISAM testing:" hwmcb = HANDLE() print "\nVmxInfo test:" res = c_short(255) printf ("Before - res = %#x (%d), hwmcb = %d\n", res, res, hwmcb) res = VmxInfo( byref(hwmcb), byref(c_void_p(vStats)) ) printf ("After - res = %#x (%d), hwmcb = %d\n", res, res, hwmcb) printf ("nrecords = %d, gps_used = %d, gps_unused = %d, max_key_len = %d\n", vStats.nrecords, vStats.gps_used, vStats.gps_unused, vStats.max_key_len) printf ("grp_size = %d, init_alloc = %d, cr_opts = %d, free_prop_area = %d\n", vStats.grp_size, vStats.init_alloc, vStats.cr_opts, vStats.free_prop_area) printf ("format = \x22%s\x22\n", vStats.format) printf ("reserved = \x22%s\x22\n", vStats.reserved) This is what I get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 99, in res = VmxInfo( byref(hwmcb), byref(c_void_p(vStats)) ) TypeError: cannot be converted to pointer And, on the last variation of this, this function needs to receive BSTR values passed back from the dll: short FAR PASCAL VmxGet(LPHANDLE lpDatasetNumber, LPSHORT lpSecIndex, LPSHORT lpOption, BSTR *SrchKey, BSTR *SecKey, BSTR *PriKey, LPSTR lpTypeDef); SrchKey is provided by me, SecKey and PriKey are returned by the dll, and TypeDef is defined by me and filled by the dll. For this, I have added: VmxGet = windll.vbis5032.VmxGet VmxGet.restype = c_short VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, LPBSTR] hwmcb = HANDLE() SecIndex = c_short(0) Option = c_short(17) SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = windll.oleaut32.SysAllocStringByteLen(c_char_p("X".center(129, "\x00")), 129) print "\nVmxGet test:" res = c_short(255) printf ("Before - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d\n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), byref(c_void_p(TypeDef)) ) printf ("After - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d \n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef) The last message I get is: Ready to call (Library = C:\Windows\vbis5032.dll) ... and then I get a Windows popup box: python.exe has stopped working so, I know I am passing something very wrong. Once these two problems are resolved, I am sure I can process the rest of the C prototypes myself, as they are simply variations on these themes. As before, any help is appreciated. From bryanjugglercryptographer at yahoo.com Fri Mar 14 18:33:09 2008 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Fri, 14 Mar 2008 15:33:09 -0700 (PDT) Subject: How to send a var to stdin of an external software References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: I wrote: > And here's a thread example, based on Benjamin's code: [...] Doh! Race condition. Make that: import subprocess import thread import Queue def readtoq(pipe, q): q.put(pipe.read()) cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) myVar = str(range(1000000)) # arbitrary test data. q = Queue.Queue() thread.start_new_thread(readtoq, (cat.stdout, q)) cat.stdin.write(myVar) cat.stdin.close() cat.wait() myNewVar = q.get() assert myNewVar == myVar print len(myNewVar), "bytes piped around." -- --Bryan From castironpi at gmail.com Mon Mar 17 21:09:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 18:09:22 -0700 (PDT) Subject: String To List References: Message-ID: <847718f8-8bbd-4db1-a6f3-78235c6bda4d@x41g2000hsb.googlegroups.com> On Mar 17, 10:26?am, Jeff Schwab wrote: > Girish wrote: > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > this?? > > Do you want: > > (1) Specifically to vivify lists formatted as in your example? ?If so, why? > > (2) To save and restore arbitrary python objects? > > (3) To define some kind of configuration file format that you can read > from Python? Bar says: Announce your intentions, then contents. (Form, then contents.) == List of two strings. How does that go into code? >>> list([str,str]) [, ] From fn681 at ncf.ca Fri Mar 28 16:22:37 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 28 Mar 2008 16:22:37 -0400 Subject: how to capture screenshots of the active window in Python In-Reply-To: References: <142053.72537.qm@web44801.mail.sp1.yahoo.com> Message-ID: <47ED538D.2020607@ncf.ca> Gabriel Genellina wrote: > En Thu, 27 Mar 2008 20:28:27 -0300, Praveena B > escribi?: > >> Can anyone help me out?? > > Still lacking details... PIL has a ImageGrab module, Windows only. > For Windows, Alt Prtscn usually copies the image to a clipboard. Colin W. From buzzard at urubu.freeserve.co.uk Sat Mar 8 10:52:11 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Sat, 08 Mar 2008 15:52:11 +0000 Subject: List as FIFO in for loop In-Reply-To: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > x = q.get() > #process x to get zero or more y's > #for each y: > q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > #process x to get zero or more y's > q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? > I have used exactly the same approach. I think it's a clean (even elegant) solution. I'd be surprised if it ceased to work in some future implementation of Python, but I don't know if that's absolutely guaranteed. Duncan From wbsoft at xs4all.nl Wed Mar 19 15:36:22 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Wed, 19 Mar 2008 20:36:22 +0100 Subject: keeping state in an iterator object by rebinding next() Message-ID: <200803192036.22626.wbsoft@xs4all.nl> Hi, i am writing a simple parser, that generates tokens. The parser needs to maintain some state, because some parts of the file consist of different tokens. I thought the object could simply remember its state by assigning it's next() method to the method that is currently parsing. When the state changes, the called method rebinds next() and the next token will be returned by that function. Here's an example, proving that this indeed works. >>> class A: ... def a(self): ... self.next = self.b ... return 1 ... def b(self): ... self.next = self.a ... return 2 ... def __iter__(self): ... return self ... >>> a=A() >>> a.a() 1 >>> a.next() 2 >>> a.next() 1 >>> j=0 >>> for i in a: ... j += 1 ... if j > 10: break # prevent from running endlessly ... print i ... 2 1 2 1 2 1 2 1 2 1 >>> my question is: is this legal Python? An iterator could save the next() method object, and in that case it could stop working.... It works now, because apparently the for- construct resolves 'next' each time for the object before calling it. The other solution would be just jumping to the correct method from within the next() method. But that gives an extra call... Met vriendelijke groet, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi From michael.wieher at gmail.com Sun Mar 16 13:14:31 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 12:14:31 -0500 Subject: Strange problem with structs Linux vs. Mac In-Reply-To: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> Message-ID: try twiddling the unpack prefix, they're probably stored in different binary formats on the disk... on the struct helppage, is a list of prefixes, can be like unpack('=HI',data) unpack('@HI',data) etc... find out which one works on each machine 2008/3/16, jasonwiener : > > Hi- > > I am having a VERY odd problem with unpacking right now. I'm reading > data from a binary file and then using a very simple struct.unpack to > get a long. Works fine on my MacBook, but when I push it to a Linux > box,it acts differently and ends up pewking. > > here's the code snippet: > fread.seek(0,0) > tmp_rebuild = fread.read() > fread.close() > tmp_long = tmp_rebuild[0:4] > print tmp_long.encode('hex') > print repr(tmp_long) > > unpacked_long = struct.unpack('I', > tmp_rebuild[0:4])[0] > print 'unpacked_long: %s' % unpacked_long > > my MacBook produces: > 1ec6f3b4 > '\x1e\xc6\xf3\xb4' > unpacked_long: 516354996 > > but on the linux box the same code produces: > 1ec6f3b4 > '\x1e\xc6\xf3\xb4' > unpacked_long: 3035874846 > > the data looks to be the same, but the unpacking seems to treat it > differently. > > Has anyone an idea of why this happens??? > > Thanks- > J. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sun Mar 16 07:47:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 16 Mar 2008 22:47:03 +1100 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <87ejaa28nc.fsf@benfinney.id.au> Bruce Eckel writes: > My trust has been violated. I paid a lot, in both money and time, to > be at this conference just to be herded into a room and have my > eyeballs sold to the highest bidder. Hear hear. Conference organisers, past and future, take note: Attention of attendees is *not* a commodity to be traded. Just because some parties will pay significant sums for that, it is *not* your place to sell it to them. Your place as conference organisers, rather, is to provide value to paying attendees. Their trust is hard earned, and easily lost. -- \ "Oh, I realize it's a penny here and a penny there, but look at | `\ me: I've worked myself up from nothing to a state of extreme | _o__) poverty." -- Groucho Marx | Ben Finney From benjamin.serrato at g[^_^]mail.com Mon Mar 24 02:25:02 2008 From: benjamin.serrato at g[^_^]mail.com (Benjamin Serrato) Date: Mon, 24 Mar 2008 01:25:02 -0500 Subject: Installing Mutagen Package On Windows Message-ID: Hey, I've run into another problem. I am trying to install the Mutagen package to use as my first useful program, but can't figure out how to install it on windows. The README says it is a simple application of-- Installing ---------- $ ./setup.py build $ su -c "./setup.py install" --but I ran c:\>python c:\python25\tools\scripts\setup.py build and did similarly for setup.py. I also added c:\python25 and c:\python25\tools\scripts to my path, but this hasn't worked. I have heard of 'easy_install' but don't know how to run easy_install. So, I ask for a reference because Google did not give me a quick answer and the python.org explanation at PEP 250 doesn't really explain what I should do. From george.sakkis at gmail.com Tue Mar 18 16:24:19 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 13:24:19 -0700 (PDT) Subject: Get actual call signature? References: Message-ID: <3ef0a8e9-6c86-46a5-be48-63f738f9ec88@s13g2000prd.googlegroups.com> On Mar 18, 6:40 am, Jarek Zgoda wrote: > Say, I have a function defined as: > > def fun(arg_one, arg_two='x', arg_three=None): > pass > > Is there any way to get actual arguments that will be effectively used > when I call this function in various ways, like: > > fun(5) => [5, 'x', None] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > fun(5, 'something') => [5, 'something', None] > > (et caetera, using all possible mixes of positional, keyword and default > arguments) > > I'd like to wrap function definition with a decorator that intercepts > not only passed arguments, but also defaults that will be actually used > in execution. > > If this sounds not feasible (or is simply impossible), I'll happily > throw this idea and look for another one. ;) I also needed this for a typecheck module I had written some time ago. It is feasible, but it's rather hairy. I can dig up the code, polish it and post it as a recipe (or maybe as a patch to the inspect stdlib module where it belongs). George From bbxx789_05ss at yahoo.com Mon Mar 10 23:54:12 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 10 Mar 2008 20:54:12 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: On Mar 10, 9:44?pm, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. > primes = [] > import math > import gmpy > while 1: > ? ? run = int(raw_input("Do you want to calculate primes? 1 = yes and > 2 = no. ")) > ? ? if run == 1: > ? ? ? ? y = int(raw_input("What number do you want to use as the final > number to calculate with? ")) > ? ? ? ? x = int(raw_input("What number do you want to start > calculating primes from? ")) > ? ? ? ? while x < 2: > ? ? ? ? ? ? print "Number must be at least 2 for math reasons." > ? ? ? ? else: > ? ? ? ? ? ? while x < y: > ? ? ? ? ? ? ? ? prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) > ? ? ? ? ? ? ? ? if prime < 0: > ? ? ? ? ? ? ? ? ? ? primes.append(x) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print x " is not prime. " # highlights the final " > here > ? ? ? ? ? ? ? ? x = x + 1 > ? ? ? ? ? ? print primes > ? ? elif run == 2: > ? ? ? ? break > ? ? else: > ? ? ? ? print "Sorry, not a choice. Please enter your choice again." > print "Goodbye." > > How do I fix such an invalid syntax? > > TIA, > Nathan Pinno Rather, try running this: print 10 "Hello world." From andrew-news at andros.org.uk Thu Mar 27 16:25:55 2008 From: andrew-news at andros.org.uk (Andrew McLean) Date: Thu, 27 Mar 2008 20:25:55 +0000 Subject: Instrumented web proxy Message-ID: I would like to write a web (http) proxy which I can instrument to automatically extract information from certain web sites as I browse them. Specifically, I would want to process URLs that match a particular regexp. For those URLs I would have code that parsed the content and logged some of it. Think of it as web scraping under manual control. I found this list of Python web proxies http://www.xhaus.com/alan/python/proxies.html Tiny HTTP Proxy in Python looks promising as it's nominally simple (not many lines of code) http://www.okisoft.co.jp/esc/python/proxy/ It does what it's supposed to, but I'm a bit at a loss as where to intercept the traffic. I suspect it should be quite straightforward, but I'm finding the code a bit opaque. Any suggestions? Andrew From NikitaTheSpider at gmail.com Thu Mar 20 22:45:58 2008 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 20 Mar 2008 22:45:58 -0400 Subject: zope and python 2.5.1 References: Message-ID: In article , hberig wrote: > Hi, > I'm sorry if this is an off-topic message, but I didn't found other > group. > I've read some articles about Zope, and since I like very much python, > I would like to run a webserver application using Zope instead other > web application server. I've difficulties to install zope 3 and zope 2 > on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is > there a simple way to fix it? I don't know much about installing Zope, is not the only choice for Python Web stacks. There's Django, Pylons and TurboGears to name a few alternatives. Have fun -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From rajeeshrnair at gmail.com Fri Mar 28 02:57:22 2008 From: rajeeshrnair at gmail.com (raj) Date: Thu, 27 Mar 2008 23:57:22 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> Message-ID: <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> To ankit: Well, sort() doesn't return the sorted list. It returns None. Why not this straightforward way? dvals = dict.values() dvals.sort() print dvals From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 23:38:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 04:38:41 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> Message-ID: <13t462h7vgqo081@corp.supernews.com> On Fri, 07 Mar 2008 20:04:47 -0800, dave_mikesell wrote: > On Mar 7, 10:31 am, "K Viltersten" wrote: >> I've been recommended reading >> of:http://www.python.org/dev/peps/pep-0008/ and in there i saw two >> things that i >> need to get elaborated. >> >> 1. When writing English, Strunk and >> White apply. > > If your code needs so much descriptive prose that you have to consult > Strunk and White, refactor it to be more clear. Excessive comments are > the hobgoblin of overly complex and/or sloppy code. Nonsense. Poor English is poor English whether you're writing short one- line comments or three hundred page manuals. store = make_store() x = get_stuff(store) # Get the stuff what was brought at the store. Not that I would consider S & W the best source for good grammar or style. -- Steven From bj_666 at gmx.net Sat Mar 1 11:23:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Mar 2008 16:23:46 GMT Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> Message-ID: <62te8iF24nbb5U1@mid.uni-berlin.de> On Fri, 29 Feb 2008 17:29:32 -0800, Lie wrote: > On Feb 28, 10:00 am, Paul Rubin wrote: >> More examples: >> >> x = 1 >> y = len(s) + x >> >> => ok, decides that x is an int >> >> x = 1 >> y = x + 3.0 >> >> => ok, decides that x is a float >> >> x = 1 >> y = x + 3.0 >> z = len(s) + x >> >> => forbidden, x cannot be an int and float at the same time. >> >> > I am so glad you're not the designer of Python. >> >> This is how Haskell works and I don't notice much complaints about it. > > Ok, that means the line "y = x + 3.0" have a side effect of "x = > float(x)"? I think I would say that is an implicit behavior. But the type of `x` must be specialized somehow. `x` doesn't start as `Int` or `Integer` but the very generic and AFAIK abstract type class `Num`. After seeing the second line the compiler finds an implementation for `+` and the type class `Fractional` for both operands and now thinks `x` must be a `Fractional`, a subclass of `Num`. Then comes the third line with `length` returning an `Int` and the `Fractional` `x` but there is no implementation for a `+` function on those types. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Mar 27 22:12:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 23:12:17 -0300 Subject: how to capture screenshots of the active window in Python References: <142053.72537.qm@web44801.mail.sp1.yahoo.com> Message-ID: En Thu, 27 Mar 2008 20:28:27 -0300, Praveena B escribi?: > Can anyone help me out?? Still lacking details... PIL has a ImageGrab module, Windows only. -- Gabriel Genellina From steve at holdenweb.com Sun Mar 30 20:34:30 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 20:34:30 -0400 Subject: question In-Reply-To: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> References: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > Say you have an auditory waveform. In dream hardware, positives would > accumulate until something, which would trigger a small chain > reaction. In software, with a function f of time t, f( t ), in > constant space, what can you know at t? > > Presume. Silence first, then a broken triad vamps. How long til you > recognize it? One sec., i'll attach a binary. Good grief, is this idibot still around? [leaves c.l.py for another month] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From hberig at gmail.com Fri Mar 21 19:29:22 2008 From: hberig at gmail.com (hberig) Date: Fri, 21 Mar 2008 16:29:22 -0700 (PDT) Subject: zope and python 2.5.1 References: Message-ID: <997f4975-0a33-4091-8c33-331d6c0bc0d4@59g2000hsb.googlegroups.com> On Mar 20, 11:45 pm, Nikita the Spider wrote: > In article > , > > hberig wrote: > > Hi, > > I'm sorry if this is an off-topic message, but I didn't found other > > group. > > I've read some articles about Zope, and since I like very much python, > > I would like to run a webserver application using Zope instead other > > web application server. I've difficulties to install zope 3 and zope 2 > > on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is > > there a simple way to fix it? > > I don't know much about installing Zope, is not the only choice for > Python Web stacks. There's Django, Pylons and TurboGears to name a few > alternatives. > > Have fun > > -- > Philiphttp://NikitaTheSpider.com/ > Whole-site HTML validation, link checking and more thanks Philip!! I'll see the alternatives. I'll search some report comparing features of each alternative. From gagsl-py2 at yahoo.com.ar Sun Mar 16 15:39:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 17:39:56 -0200 Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: En Wed, 12 Mar 2008 09:37:58 -0200, k.i.n.g. escribi?: > We use dd command in Linux to create a file with of required size. In > similar way, on windows I would like to use python to take the size of > the file( 50MB, 1GB ) as input from user and create a uncompressed > file of the size given by the user. The equivalent command on Windows would be: fsutil file createnew filename size -- Gabriel Genellina From ncoghlan at gmail.com Wed Mar 19 07:13:37 2008 From: ncoghlan at gmail.com (NickC) Date: Wed, 19 Mar 2008 04:13:37 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> Message-ID: On Mar 19, 6:07 am, Jeff Schwab wrote: > As I have never attended PyCon, the amount of entertainment already > gleaned from this thread has wildly exceeded my expectations. :) Are > slides or notes from any of the presentations available online? What > was the topic of the well-received presentation from Google? I'm mostly intrigued by the tantalising hints being dropped regarding Steve Holden's Teach Me Twisted talk ;) From kyosohma at gmail.com Tue Mar 18 14:49:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 18 Mar 2008 11:49:40 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> Message-ID: <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> On Mar 18, 1:41 pm, fumanchu wrote: > On Mar 17, 6:25 pm, dundeemt wrote: > > > I agree - the balance wasn't as good. We can all agree that HowTos > > and Intros are a necessary part of the conference talks track, but as > > Robert pointed out some talks should be of a more advanced nature. I > > enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and > > Mark Hammond's keynote were among my favorite talks. > > Raymond Hettinger's talk on collections was not only one of my > favorites, it was apparently lots of other people's too--the room was > PACKED. I can't recall seeing any other talk that was even close to > seating capacity. > > Robert Brewer > fuman... at aminus.org The "Using PyGame and PySight to Create an Interactive Halloween Activity (#9)" session with Mr. John Harrison was also quite full as was the one for Pyglet. I think the nose presentation had people sitting on the floor. Geeks like games! I know I do! Mike From mblume at freesurf.ch Thu Mar 27 15:35:29 2008 From: mblume at freesurf.ch (Martin Blume) Date: Thu, 27 Mar 2008 20:35:29 +0100 Subject: Is subprocess.Popen completely broken? References: <16300891-8fbf-489a-9011-e38180310618@s8g2000prg.googlegroups.com> Message-ID: <47ebf701$0$9029$5402220f@news.sunrise.ch> "Istvan Albert" schrieb > > > Is subprocess.Popen completely broken? > > Your lack of faith in Python is somewhat > disturbing ... > I have consistently made the experience that when I was about to ask "is X completely broken", the error was on my side. Martin From darcy at druid.net Fri Mar 7 12:02:03 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 7 Mar 2008 12:02:03 -0500 Subject: Regarding coding style In-Reply-To: <8c7f10c60803070844pf88a497h9db85953851b3418@mail.gmail.com> References: <63d80bF273nraU1@mid.individual.net> <8c7f10c60803070844pf88a497h9db85953851b3418@mail.gmail.com> Message-ID: <20080307120203.fabaecc4.darcy@druid.net> On Fri, 7 Mar 2008 16:44:10 +0000 "Simon Brunning" wrote: > On Fri, Mar 7, 2008 at 4:31 PM, K Viltersten wrote: > > > > 1. When writing English, Strunk and > > White apply. > > I apply Fowler, PEP 8 be damned. ;-) Fowler's is good too but much more comprehensive. Strunk and White is a pamphlet compared to Fowler's tome. -- 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 george.sakkis at gmail.com Wed Mar 26 21:58:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 18:58:48 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: On Mar 26, 5:28 pm, Sean Davis wrote: > I am working with genomic data. Basically, it consists of many tuples > of (start,end) on a line. I would like to convert these tuples of > (start,end) to a string of bits where a bit is 1 if it is covered by > any of the regions described by the (start,end) tuples and 0 if it is > not. I then want to do set operations on multiple bit strings (AND, > OR, NOT, etc.). Any suggestions on how to (1) set up the bit string > and (2) operate on 1 or more of them? Java has a BitSet class that > keeps this kind of thing pretty clean and high-level, but I haven't > seen anything like it for python. > > Thanks, > Sean Have you looked at Pypi [1] ? From a quick search, there are at least four potentially relevant packages: BitPacket, BitVector, BitBuffer, BitBucket. George [1] http://pypi.python.org/pypi?%3Aaction=search&term=bit&submit=search From deets at nospam.web.de Sat Mar 22 10:54:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 15:54:38 +0100 Subject: Distributing Python Apps on Linux\BSD In-Reply-To: References: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> <9290c7b1-3e51-46fe-96e7-6c2ebf4f5b77@u10g2000prn.googlegroups.com> Message-ID: <64kktlF2c6h1bU1@mid.uni-berlin.de> PurpleServerMonkey schrieb: > On Mar 22, 2:26 am, Miki wrote: >> Hello, >> >> Disclaimer: I'm not an expert on the subject. >> >>> Setuptools and friends seem to be focused on distributing modules, I'm >>> at the other end of the scale where I want to distribute an entire >>> application so that an Administrator can run a single install and have >>> a fully operational product. A key requirement is that I want the >>> application to fit in with what and admin would expect an application >>> to look like at the system level i.e site-packages like structures >>> aren't suitable. >> You do that with distutils as well. >> >>> So far I've thought of using a configure script and make which would >>> call some custom python installer script to do the actual install. It >>> fits in nicely with what I want to achieve but are there any better >>> options out there, how are others doing the same thing? >> Every distro flavor has it's own installer: apt/deb, rpm, port, ... >> On Windows you can use one of the free installer (InnoSetup and >> friends). >> >> HTH, >> -- >> Miki http://pythonwise.blogspot.com > > Well I'm not really interested in rpms or deb packages right now, I > want to get it to the point where it will run on BSD and Linux without > using distribution specific tools. Using a tarball or the standard > python tools would be best. > > The problem is all the documentation surrounding distutils and > setuptools refers to modules, now I'm not sure why but it seems most > Python developers think an application is the same thing as a module. > Unless you are writing very small applications that's definitely not > the case. > > So I guess the question is, using distutils or setuptools is it > possible for a user to select where to install the application i.e / > usr/local? > If not then I think it's going to be tarball deployment with a custom > setup script, was hoping there was a better way. You should start reading the setuptools-documentation, especially the section about entry-points. And yes, you can set the install-prefix. If you have a sysadmin who knows how to read a README, it can't get simpler than python setup.py install (with proper rights of course) If he has no setuptools installe, put the ez_setup.py script together into your distribution, then it becomes python ez_setup.py python setup.py install Unfortunately there is one caveat: the distros rip out distutils and Python-header into a separate -dev-package. Make sure to instruct the admin to install these. Diez From castironpi at gmail.com Mon Mar 3 22:21:23 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 19:21:23 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> Message-ID: On Mar 3, 4:03?pm, Carl Banks wrote: > On Mar 3, 4:17 pm, Raymond Hettinger wrote: > > > Since Python doesn't support having two methods with the same name, > > the usual solution is to provide alternative constructors using > > classmethod(): > > > ? @classmethod > > ? def from_decimal(cls, d) > > ? ? ? ? sign, digits, exp = d.as_tuple() > > ? ? ? ? digits = int(''.join(map(str, digits))) > > ? ? ? ? if sign: > > ? ? ? ? ? ? digits = -digits > > ? ? ? ? if exp >= 0: > > ? ? ? ? ? ? return cls(digits * 10 ** exp) > > ? ? ? ? return cls(digits, 10 ** -exp) > > Note that even some of Python's built in types (dict *cough*) > implement homemade function overloading. > > The OP wanted to write a constructor that could accept either a pair > of integers or a rational, there would be a good precedent for it. > > However, I would advise the OP to use the constructor only for the > most common arguments, and use classmethods for more obscure, less > common arguments (such as decimal or even float). > > Carl Banks Unless application indicates calling signature uniformity, hash type to subclass or to class method. From ptoomey3 at mac.com Wed Mar 26 23:33:01 2008 From: ptoomey3 at mac.com (Patrick Toomey) Date: Wed, 26 Mar 2008 22:33:01 -0500 Subject: Can my own objects support tuple unpacking? Message-ID: <6D5CBCD5-9CC5-4E00-9F3A-510F845A37B1@mac.com> Hello, So, I am new to python, but I always like to learn the ins and outs of a language by trying to understand how everything fits together. Anyway, I am trying to figure out how tuple unpacking behavior works. Specifically, what happens when I do the following: a,b,c,d = e Is a method called, such as __getitem__ for each index on the left (0,1,2,3)? I thought this was logical, so I tried coding up similar to this class Foo: def __getitem__(self, index): print index return 1 a = Foo() b,c,d = a the output is: 0 1 2 3 ValueError: too many values to unpack So, it seems like something is going on here with __getitem__, but obviously something is not quite right. What got me wondering about this was exceptions, as they seem to use this idiom in some way. As an example, we can do the following: class Foo(Exception): def bar(): print "dummy method" try: raise Foo('a', 'b', 'c', 'd') except Foo, e: a,b,c,d = e This will successfully unpack the exception arguments, as if e was a sequence. How are they implementing this functionality? Is this a special case for exceptions? I guess my overall question is how tuple unpacking works underneath the covers. Can I implement tuple unpacking for my own objects? Thanks, Patrick From jeff at schwabcenter.com Tue Mar 18 00:42:19 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 21:42:19 -0700 Subject: Any fancy grep utility replacements out there? In-Reply-To: References: Message-ID: samslists at gmail.com wrote: > So I need to recursively grep a bunch of gzipped files. This can't be > easily done with grep, rgrep or zgrep. (I'm sure given the right > pipeline including using the find command it could be done....but > seems like a hassle). > > So I figured I'd find a fancy next generation grep tool. Thirty > minutes of searching later I find a bunch in Perl, and even one in > Ruby. But I can't find anything that interesting or up to date for > Python. Does anyone know of something? I don't know of anything in Python, but it should be straight-forward to write, and I'm betting somebody in this group can do it in one line. (Did you see Arnaud's solution on the "Interesting math problem" thread?) When you say "recursively," do you mean that you want to grep files in nested subdirectories, or do you mean that archive elements should in turn be expanded if they are themselves archives? If you encounter a file that has been compressed twice (gzip|gzip), do you want to uncompress it repeatedly until you get to the original file? For example, given the following setup, what do you expect the output of my_grep to be? ~$ mkdir sample && cd sample sample$ for w in hello world; do echo $w |gzip -c >$w.gz; done sample$ tar czf helloworld.tgz *.gz sample$ my_grep hello -r . From tew24 at spam.ac.uk Thu Mar 6 05:33:41 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 06 Mar 2008 10:33:41 +0000 Subject: Licence confusion: distributing MSVC?71.DLL Message-ID: Hi I've written a program in Python using wxPython and Matplotlib and would like to distribute it under the GPL. For ease of use, I'd also like to distribute and installable version for Windows, but this needs MSVCR71.dll and MSVCP71.dll to work. I've created an installer using py2exe and Inno Setup but I don't know if I'm allowed to distribute it or not. I've found lots of conflicting opinions online indicating that I can or cannot distribute these, but no definitive answer. The Microsoft Developer Network instructs me to read the redistribution instructions and the EULA which come with Visual Studio, but I don't have visual studio, so that's next to useless. If someone has worked their way through this maze before and has an answer, I'd be keen to hear it. Failing that, if you have Visual Studio and it's not a violation of the licence terms to post the licence and redistribution instructions here, could you possibly do so and I'll see if I can work out what's allowed. Thanks! -- I'm at CAMbridge, not SPAMbridge From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:26:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:26:03 -0200 Subject: class object interface document References: Message-ID: En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN escribi?: > Where can I find the Python class object interface document, such as > struct PyClassObject, PyClass_New()? Thanks! PyClass_* and PyInstance_* are for old-style classes and instances respectively, and will disappear in v3.0. PyInstance is in the section 7.5.2 in the Python/C API Reference Manual; I don't find any documentation on PyClass itself. -- Gabriel Genellina From miki.tebeka at gmail.com Thu Mar 27 17:07:15 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 14:07:15 -0700 (PDT) Subject: Instrumented web proxy References: Message-ID: <9dd5c428-c1e5-43cb-99ee-b3e3a3fa7e11@m36g2000hse.googlegroups.com> Hello Andrew, > Tiny HTTP Proxy in Python looks promising as it's nominally simple (not > many lines of code) > > http://www.okisoft.co.jp/esc/python/proxy/ > > It does what it's supposed to, but I'm a bit at a loss as where to > intercept the traffic. I suspect it should be quite straightforward, but > I'm finding the code a bit opaque. > > Any suggestions? >From a quick look at the code, you need to either hook to do_GET where you have the URL (see the urlunparse line). If you want the actual content of the page, you'll need to hook to _read_write (data = i.recv(8192)). HTH, -- Miki http://pythonwise.blogspot.com From Wubbulous at gmail.com Wed Mar 12 00:50:20 2008 From: Wubbulous at gmail.com (Wubbulous at gmail.com) Date: Tue, 11 Mar 2008 21:50:20 -0700 (PDT) Subject: Open a file with default handler app? References: <83bc9bf2-9b9c-4959-870f-f4b37281f6e0@m3g2000hsc.googlegroups.com> Message-ID: <79ae8d93-5845-466c-b7f8-e345c3d63c46@i7g2000prf.googlegroups.com> On Mar 11, 9:24?pm, andrei.... at gmail.com wrote: > Hi, I searched for this on google and in this group, but my awesome > google-fu powers failed me. Is there a way to open any file using > default program that'd open it? In other words, to do the same action > as double-clicking in windows explorer? And secondly, is there a way > to do the same thing for linux that'd work across all desktop > environments and distributions, or at least in all major ones? What > I'm trying to do here is to have records (or items) in my app where > you could attach any kind of file and open it from there by clicking > 'open'. Then it would go and do something like os.system("launch %s" % > filename). So any way to do this except for keeping your own > dictionary of file types and relevant apps? thx, -ak Hey there, I've had to do the same things for a program that I'm writing. The following command should do the trick: os.startfile("yourfilehere") from the os module. Hope this helps! From enleverlesX.XmcX at XmclaveauX.com Mon Mar 17 18:19:56 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 17 Mar 2008 23:19:56 +0100 Subject: placing a Python com object into Excel In-Reply-To: References: Message-ID: <47deefc5$0$906$ba4acef3@news.orange.fr> Hi! Perso, I started from "excelAddin.py" (in C:\Python25\Lib\site-packages\win32com\demos). And, I'm happy with the result (who run OK with Excel 2000, XP, 2007). @-salutations -- Michel Claveau From py1.forest at tibit.com Mon Mar 31 18:07:20 2008 From: py1.forest at tibit.com (Forest) Date: Mon, 31 Mar 2008 15:07:20 -0700 (PDT) Subject: why does socket.makefile require non-blocking mode? Message-ID: <17580.75.55.199.5.1207001240.squirrel@webmail.sonic.net> Bryan Olson wrote: >Looking at the code for the existing _fileobject's read method, it >will loose data it has already read if a socket.recv() call raises >an exception. The function keeps buffers in a local variable that >will be lost if an exception exits the scope. That much could be >fixed with a try...finally. Other methods have similar problems. Just as I thought. Thanks for being my extra set of eyes. >>I wanted to use file-like objects with socket timeouts, so I ended up >>writing my own replacement for socket._fileobject. I'd appreciate it >>if someone could either explain to my why my new class was unnecessary, >>or else encourage me to contribute it as a patch to the socket module. > >Sure, fix it. Yeah, I'll give it some more thought. >A harder problem is that it doesn't play nice with select(). I guess you mean that since _fileobject.read() calls recv() multiple times, the second and later calls might block even if select() said the socket was readable. That should be fixable by catching EAGAIN / EWOULDBLOCK and returning early, shouldn't it? This idea seems consistent with the normal file object's read() method docs, which say, "in non-blocking mode, less data than what was requested may be returned." Making write() and flush() friendly in non-blocking mode might be at little trickier. From rahulguy5 at gmail.com Sun Mar 30 08:56:53 2008 From: rahulguy5 at gmail.com (lilly) Date: Sun, 30 Mar 2008 05:56:53 -0700 (PDT) Subject: FOR LAST 2 YEARS I WAS SEARCHING FOR FOR REAL ONLINE MONEY MAKING Message-ID: FOR LAST 2 YEARS I WAS SEARCHING FOR FOR REAL ONLINE MONEY MAKING PROGRAMME.FINALLY I FIND IT. IT HAS MAKE THOUSANDS OF DOLLARS TO MY ACCOUNT IN EVERY DAY.I AM HAPPY TO REVEALED THIS SECRET TO YOU .THE OPPORTUNITY IS BELOW http://jeevaraj.MYSURVEYPR.hop.clickbank.net IT IS REAL ONLINE MONEY MAKING PROGRAMME From justus.schwabedal at gmx.de Wed Mar 12 19:58:44 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Thu, 13 Mar 2008 00:58:44 +0100 Subject: Problem with exec Message-ID: <59B09204-2D58-4371-A05B-9FDA93991D77@gmx.de> Dear python users! I try to setted up compile-free parallelism using the exec command. However I had some problems with namespaces which I find mysterious although I managed to work around. But the workaround is not nice, so I wonder if there are ways. I do the following, bash-3.2$ cat execBug.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ def g(head): exec header return f() print "g(header) =",g(header) bash-3.2$ ./execBug.py g(header) = Traceback (most recent call last): File "./execBug.py", line 10, in print "g(header) =",g(header) File "./execBug.py", line 9, in g return f() File "", line 4, in f NameError: global name 'randn' is not defined However this works: bash-3.2$ cat execBug.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ exec header print "f() =",f() bash-3.2$ ./execBug.py f() = 1.44707148916 If for the first example I add "global randn", it works again. However I do not understand how the nested namespaces interact here. Isn't this an unwanted feature in the functionality? I'm looking foreward to your comments, Justus From userprogoogle-139 at yahoo.co.uk Thu Mar 20 12:21:28 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 20 Mar 2008 09:21:28 -0700 (PDT) Subject: OS.remove and threads Message-ID: <4453bd2b-f01c-4851-9c7b-6804ad2b2591@u10g2000prn.googlegroups.com> Hi, I am writing a small application which uploads files in a thread via an ftp connection. However anytime I use the os.remove(filename) command to delete files the thread crashes, even if the file being removed has nothing to do with the one being uploaded. Are the OS commands incompatible with threads? By crashing I mean the thread stops uploading and an exception is produced. Also if the OS commands are in any other thread, they cause that thread to crash. I have tried using locks around the os.remove command but that also makes no difference. I am using: Mac OS 10.4.9 and Python 2.4.3 with Psyco. Kind regards, rod From fakeaddress at nowhere.org Fri Mar 14 05:12:29 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 09:12:29 GMT Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> Message-ID: <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Robert Bossy wrote: > cokofreedom at gmail.com wrote: >> Robert Bossy wrote: >>> Indeed! Maybe the best choice for chunksize would be the file's buffer >>> size... That bit strikes me as silly. >>> I won't search the doc how to get the file's buffer size because >>> I'm too cool to use that function and prefer the seek() option since >>> it's lighning fast regardless the size of the file and it takes near to >>> zero memory. >> >> But what platforms does it work on / not work on? >> > Posix. Posix is on the does-work side, just to be clear. http://www.opengroup.org/onlinepubs/000095399/functions/fseek.html > It's been ages since I touched Windows, so I don't know if XP and > Vista are posix or not. I tried on WinXP, with both an NTFS and FAT32 disk, and it worked on both. I found some Microsoft documentation noting: "On some platforms, seeking past the end of a file and then doing a write operation results in undefined behavior." http://msdn2.microsoft.com/en-us/library/system.io.filestream.seek(VS.71).aspx > Though, as Marco Mariani mentioned, this may create a fragmented file. > It may or may not be an hindrance depending on what you want to do with > it, but the circumstances in which this is a problem are quite rare. Writing zeros might also create a fragmented and/or compressed file. Using random data, which is contrary to the stated requirement but usually better for stated application, will prevent compression but not prevent fragmentation. I'm not entirely clear on what the OP is doing. If he's testing network throughput just by creating this file on a remote server, the seek-way-past-end-then-write trick won't serve his purpose. Even if the filesystem has to write all the zeros, the protocols don't actually send those zeros. -- --Bryan From deets at nospam.web.de Thu Mar 13 13:57:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 18:57:55 +0100 Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> <63t1tnF29egotU1@mid.uni-berlin.de> Message-ID: <63t895F298us9U1@mid.uni-berlin.de> azrael wrote: > I thought of using Temp files but I am afraid of the JPG destorsion > while saving because of the compresion.I am looking for a way to > directly transform it. Then don't use JPEG, use PNG. It's lossless. Diez From phil at riverbankcomputing.co.uk Sun Mar 30 11:56:54 2008 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 30 Mar 2008 15:56:54 +0000 Subject: Using QSystemTrayIcon with PyQt In-Reply-To: <200803301608.19697.phil@riverbankcomputing.com> References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <200803301608.19697.phil@riverbankcomputing.com> Message-ID: <200803301656.54571.phil@riverbankcomputing.co.uk> On Sunday 30 March 2008, Phil Thompson wrote: > On Sunday 30 March 2008, Alex Teiche wrote: > > On Mar 30, 2:08 am, Phil Thompson wrote: > > > On Sunday 30 March 2008, Alex Teiche wrote: > > > > Hello, > > > > > > > > I am pretty new to Python, and have never learned C++. I am trying > > > > to implement the following thing into my python application: > > > > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > > > > Through PyQt. I have been using PyQt for awhile and I know how do > > > > use it, but I could not get this specific thing to work. Can someone > > > > give me some hints as to get it working in Python? > > > > > > > > Thanks a ton, > > > > > > > > Alex > > > > > > Have you looked at PyQt's systray example? > > > > > > Phil > > > > No, where do I find the example? > > > > Thanks, > > > > Alex > > Unsurprisingly in the PyQt source package. > > Phil By which I mean the current snapshot - I'd forgotten that it is a recent addition. Phil From pedro.santa at gmail.com Thu Mar 20 12:48:18 2008 From: pedro.santa at gmail.com (Pedro Machado Santa) Date: Thu, 20 Mar 2008 09:48:18 -0700 (PDT) Subject: Import a file to namespace Message-ID: <0cdb3c90-e961-4982-9996-de3ac02706bc@13g2000hsb.googlegroups.com> Hi all, I'm really a newbie in Python, and I wanted to do a tricky thing. I don't know if it is possible but my intention was: I have a package (namely breve) and I want to alter (override?) some of it's functions preserving the original library/package - in order if I update it, I do not lose my "hacks". Until now I was overriding the functions directcly on my script and adding them to the package namespace, like this: import testpackage class testClass(): #... testpackage.testClass = testClass But this has a problem. If I wanna use that code over many files, I have to update it manually on all of them every time I update my "hack". I was thinking if it is possible to keep that code on a file - namely testpackageaddon.py and import it on my work file so that by doing that it will automatically override the classes. Like so: import testpackage import testpackageaddon testpackage.testClass() #my hacked class defined on testpackageaddon.py And on testpackageaddon.py: import testpackage class testClass(): #... testpackage.testClass = testClass Any tips, ideas on how to do this? Many thanks. Pedro Machado Santa From castironpi at gmail.com Sat Mar 15 18:08:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 15:08:05 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> Message-ID: <9b959898-ed57-47b9-8158-7ca6a321e705@u69g2000hse.googlegroups.com> On Mar 15, 8:18?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > Gabriel Genellina wrote: > >> No need to reinvent the wheel. socket objects already have a makefile ? > >> method returning a file-like object, which behaves like a buffered socket. > > That wheel is far from round, and needs some reinvention. Python's > file-like objects do not play nice with lower level calls, which > would be tolerable if they supported some well-defiend high-level > asynchronous I/O, but they do not. > > > Newbie question: ?Can you write to the 'file-like object' a pickle, > > and receive it intact-- as one string with nothing else? > > Yes, but there's a world of gotcha's. Sockets do not recognize > record boundaries, and Python's 'pickle' has holes one's enemies > could drive a truck through. Still, you can pickle, write, read, > un-pickle, and get back your data intact. > > > I want to know because I want to send two pickles. > > "Two pickles" sounds like a tasty snack, but also suggests you may > be playing hopscotch in a minefield. This is a helpful group. Give > us more to go on, and you are likely to receive thousands of > dollars worth of consulting for free. It depends on the situation. How generally applicable is this: fun ListenerGeneric( port, factory, arrivedfun ): which calls 'factory' on socketA.accept (and loops again), then arrivedfun( stringA ) on message complete detection. ?. It should start itself in a separate thread. Or is this any better: for x in connections(): startnewthreadwith x: for y in messages( x ): arrivedfun( y ) From bronger at physik.rwth-aachen.de Mon Mar 17 09:35:09 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 17 Mar 2008 14:35:09 +0100 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> Message-ID: <87fxup4goi.fsf@physik.rwth-aachen.de> Hall?chen! Aahz writes: > In article <873aqp6bbq.fsf at physik.rwth-aachen.de>, > Torsten Bronger wrote: > >> [...] >> >> I see no reason why the "fault" for parts of the rest being >> sub-optimal, too, must necessarily be on the attendee's side. >> (Just hypothetically; I wasn't at PyCon.) > > Let's suppose you have a group of friends who collectively throw a > party. They invite you to help out organizing it and putting it > together, but you choose not to. If you don't have a good time at > the party because it wasn't what you wanted, I think it's fair to > say it was your fault. And I think exactly the same thing is true > for PyCon, albeit on a much larger scale. Fair enough. But then I question the sensibility in saying "it is XY's fault" at all. Somebody not involved in organising was not happy with the Con. You may take the criticism or leave it. The criticism may be justified or not. But saying that it is "his fault" is useless in my opinion, it even discourages feedback. It think it's okay to evaluate something that you didn't help coming into existence. A good point is a good point no matter who makes it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 06:19:58 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 12:19:58 +0200 Subject: Serial port error statistics - any comparable data? References: <657qh1F2es9vnU1@mid.uni-berlin.de> Message-ID: <6597qeF2e56g7U1@mid.individual.net> Diez B. Roggisch wrote: > if you have the chance, try & attach a machine with legacy rs232 > port, and see if the errors still remain. Additionally, what kind of buffers does your device have? I'm using pyserial to control a very "sensitive" device with nuttily implemented buffering strategy. It has a "fast" and a "slow" buffer which are filled in order, and no signalling to the outside sender on how full they are. If the fast buffer fills the slow buffer kicks in and requires less transmission rate. That may be how characters could be lost with you. Regards, Bj?rn -- BOFH excuse #119: evil hackers from Serbia. From castironpi at gmail.com Mon Mar 3 10:00:55 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 07:00:55 -0800 (PST) Subject: is there enough information? References: Message-ID: On Mar 3, 7:11?am, Jean-Paul Calderone wrote: > On Tue, 26 Feb 2008 21:45:24 -0800, Dennis Lee Bieber wrote: > > > [snip] > > > ? ?Threads, in Python, are good for parallel processing of items that > >tend to be I/O bound -- that is, stuff that blocks on lots of I/O calls > >allowing other threads to execute until they block too. Due to the GIL > >in the common Python implementation, threading is not useful for > >number-crunching (CPU bound) processing. > > > ? ?Now, there is a very vocal group that recommend Twisted style > >asynchronous call-backs for everything in the world... But I think that > >group tends to forget that Windows I/O is incompatible with the > >low-level select() call often used to do parallel I/O -- leaving it only > >useful for the network socket I/O, but not local file I/O processing. > > I'm not sure, but you seem to be implying that the only way to use Windows' > asynchronous I/O APIs is with threads. ?Actually, it is possible (and Twisted > allows you) to use these as well without writing a threaded application. > > Perhaps you think it would be better to use them with threads, but that's > certainly not the _only_ way to use them as you implied. > > Jean-Paul What's the API call for it? From bj_666 at gmx.net Thu Mar 13 04:06:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Mar 2008 08:06:10 GMT Subject: How to port Python code into C++ code automatically? References: Message-ID: <63s5jiF29blveU2@mid.uni-berlin.de> On Wed, 12 Mar 2008 20:15:32 -0700, Bo wrote: > I want to port a Python project (about 10,000 line python code) to C+ > +. Is there any automatically tool to do this kind of things? e.g., > SWIG(http://www.swig.org/)? > > Any comment is welcome! Have a look at the ShedSkin Python-to-C++ compiler: http://shed-skin.blogspot.com/ It has some restrictions, i.e. the code has to be written in a more or less statically typed way. And me too is interested in why you want to port the entire project instead just the time critical parts? ShedSkin might help here too. As Cython_ or Pyrex_ do. Both compile a subset of Python with optional static typing to C extension modules. .. _Cython: http://www.cython.org/ .. _Pyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Tue Mar 11 13:13:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 13:13:40 -0400 Subject: Obtaining the PyObject * of a class References: Message-ID: "Cooper, Andrew" wrote in message news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... | Are there any Python C API experts/SWIG experts out there that can help | me with this issue please. | I',m currently using SWIG to generate a python interface to a C DLL. Some people have switched to using ctypes for this, and many other SWIG users have stopped reading clp. But I hope someone answers who can. tjr From durumdara at gmail.com Tue Mar 11 07:52:57 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Tue, 11 Mar 2008 12:52:57 +0100 Subject: Python PDF + Pictures In-Reply-To: <47d66d8f$0$14029$426a74cc@news.free.fr> References: <47d66d8f$0$14029$426a74cc@news.free.fr> Message-ID: Hi! Bruno Desthuilliers wrote: > durumdara at gmail.com a ?crit : >> Hi, dear Python Masters! >> >> I wanna ask about the Python and PDF creating. > Dont know if this will match your needs, but you may want to have a look > at pisa: > http://www.htmltopdf.org/ > With HTML I have only one problem. The HTML is not page specific language. But I wanna use pages (for example: A4) with diff. orientation to show images correctly. But I try it if possible. Thanks for your help: dd From andreww at datanet.ab.ca Sun Mar 2 09:41:20 2008 From: andreww at datanet.ab.ca (Andrew Warkentin) Date: Sun, 02 Mar 2008 07:41:20 -0700 Subject: Python-based regular expression parser that allows patterns to call functions? Message-ID: <47CABC90.7010101@datanet.ab.ca> I am writing a filtering HTTP proxy (the site is http://xuproxy.sourceforge.net/). I want it to be compatible with Proxomitron (http://proxomitron.info/) filters. I need a regular expression parser that allows patterns to call functions (or more likely, class methods), to implement "matching commands" (look at the Proxmitron documentation to see what I mean). Does anyone know if such a library exists for Python, or do I have to write my own parser? From erikwickstrom at gmail.com Thu Mar 13 16:58:56 2008 From: erikwickstrom at gmail.com (erikcw) Date: Thu, 13 Mar 2008 13:58:56 -0700 (PDT) Subject: Python-PHP bridge? Message-ID: Hi all, I'm starting to translate a large legacy php app to python (django), and was wondering if anyone knew of a bridge between the 2 languages. (access php objects from python and vice versa). Some of the solutions I've come across so far include using php's passthru() ( http://us3.php.net/passthru ) and pyphp. passthru(): I'm concerned about the potential performance hit of all these system calls. Isn't this the equivalent of a CGI app? pyphp: Seems closer to what I'm looking for, but I haven't been able to get the examples working yet. Maybe it is to alpha? If anyone has any experience with these tools or others and can share some advice, I'd appreciate it! Thanks! Erik From castironpi at gmail.com Tue Mar 4 22:53:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 19:53:52 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: On Mar 4, 9:01?pm, "Gabriel Genellina" wrote: > En Wed, 05 Mar 2008 00:30:26 -0200, escribi?: > > > On Mar 4, 8:11?pm, "Gabriel Genellina" wrote: > >> En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > >> >> is it makes it. > > >> >>>> from types import FunctionType, MethodType > >> >>>> class A( FunctionType ): pass > >> > ... > >> > Traceback (most recent call last): > >> > ? File "", line 1, in > >> > TypeError: type 'function' is not an acceptable base type > > >> Use delegation instead of inheritance. This class is almost ? > >> indistinguishable from a true function (when used as a method): > > [... long interactive example ...] > > > I actually don't believe you-- bar is not bound to an instance when P > > is initialized... er, instantiated. ?However, the evidence indicates > > my belief mechanism is faulty... and rather conclusively at that. > > ?If P calls __get__( you ), is p a > > gotcha? > > I didn't cheat, that was an actual Python interactive session. So you'll ? > have to formulate a new theory taking into account the new facts... or ? > read how the descriptor protocol workshttp://www.python.org/doc/newstyle/ > I don't understand your last sentence. > > -- > Gabriel Genellina If P gets, p gotcha. gotcha= partial( get, you ). bor hor hor. Yes... regarding the descriptoring, just make it official! UserFunctionType or smg. From castironpi at gmail.com Fri Mar 7 14:34:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:34:49 -0800 (PST) Subject: Difference between 'function' and 'method' References: Message-ID: <6766529d-7f0e-4e9d-9498-1c295e71ac53@o77g2000hsf.googlegroups.com> On Mar 7, 6:44?am, Sion Arrowsmith wrote: > Gabriel Genellina wrote: > >En Thu, 06 Mar 2008 23:46:43 -0200, escribi???: > >> [ ... ] > >You may look at the SimpleXMLRPCServer class and see how it implements ? > >introspection. It's rather easy (and doesn't require metaclasses nor ? > >decorators nor any other fancy stuff; I think it works the same since ? > >Python 2.1). Apparently you're doing a similar thing, but using pickles ? > >instead of xmlrpc. > > It's not that difficult to graft pickles into SimpleXMLRPCServer -- > I've done it, and if you're trying to sling large data structures > over the connection it's a massive performance win (even with > sgmlop in place to speed up XML parsing). > ? ?her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump Yeah, but I'd be grafting a non-blocking RPC sequence too. -Instantiate- attributes of ISS upon instantiation. class C: d= D c= C() assert isinstance( c.d, D ) assert c.d is c.d Which ones? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 11:16:48 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 17:16:48 +0100 Subject: What is a class? In-Reply-To: References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: <47d018de$0$23481$426a34cc@news.free.fr> castironpi at gmail.com a ?crit : > And white to play. What does exec( open( 'modA.py' ).read() ) do? RTFM From aahz at pythoncraft.com Thu Mar 27 16:02:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2008 13:02:43 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> Message-ID: In article <8ede2d83-a9f8-4d31-903c-b53271831722 at z38g2000hsc.googlegroups.com>, fumanchu wrote: >On Mar 16, 5:09 pm, a... at pythoncraft.com (Aahz) wrote: >> >> If you did not like the programming this year (aside from the sponsor >> talks) and you did not participate in organizing PyCon or in delivering >> presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > >This would be true, except that the two talks I proposed last year >were essentially denied because they were too advanced, so I didn't >even bother this year. Perhaps I should have, but the PERIOD needs to >at least be replaced by a COMMA as long as the talk-acceptance >committee continues to reject more advanced talk topics in favor of >HOWTOs and Introduction To Package X. Feel free to join the Program Committee! Seriously, this is exactly the kind of difficult problem I was talking about when I said "it is YOUR FAULT". Speaking as someone who has been on the program committee for most of the last few PyCons, it is extremely difficult to balance all the conflicting expectations that attendees have (particularly given that we have to guess, for the most part -- consider that a thousand people compared to the six hundred at PyCon 2007 means that much of the feedback from 2007 isn't particularly relevant). On top of that, we have to pick and choose from whatever proposals are offered; with very limited exceptions, we can't just solicit talks on topics, we don't have enough volunteer labor. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From nccwarp9 at gmail.com Mon Mar 31 18:03:51 2008 From: nccwarp9 at gmail.com (NccWarp9) Date: Mon, 31 Mar 2008 15:03:51 -0700 (PDT) Subject: Problem with mod_python/3.3.1 and apache Message-ID: Hello, im using Apache HTTPD 2.2.8 with mod_python/3.3.1 Python/2.4.3 on Windows and having truble starting pythone, any help would be appreciated . Im getting this error: [Mon Mar 31 23:53:03 2008] [error] make_obcallback: could not import mod_python.apache.\n 'import site' failed; use -v for traceback 'import site' failed; use -v for traceback ImportError: No module named mod_python.apache [Mon Mar 31 23:53:03 2008] [error] make_obcallback: Python path being used "['C:\\\\Windows\\\\system32\\\\python24.zip', '', 'c:\\\\xampp\\\ \python\\\\DLLs', 'c:\\\\xampp\\\\python\\\\lib', 'c:\\\\xampp\\\ \python\\\\lib\\\\plat-win', 'c:\\\\xampp\\\\python\\\\lib\\\\lib-tk', 'C:\\\\xampp\\\\apache\\\\bin']". [Mon Mar 31 23:53:03 2008] [error] get_interpreter: no interpreter callback found. [Mon Mar 31 23:53:03 2008] [error] [client 127.0.0.1] python_handler: Can't get/create interpreter., referer: http://localhost/python/ [Mon Mar 31 23:53:25 2008] [error] make_obcallback: could not import mod_python.apache.\n ImportError: No module named mod_python.apache thx From tjreedy at udel.edu Mon Mar 31 15:52:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Mar 2008 15:52:54 -0400 Subject: Is this a good time to start learning python? References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: "Rui Maciel" wrote in message news:47f1140e$0$735$a729d347 at news.telepac.pt... | Recently I woke up inclined to take up the task of learning another | programming language. I've already dipped my toes in Perl (I've read online | tutorials and wrote a couple of irrelevant pet projects) but, as the | computers at my workplace only sport the python interpreter, it probably | means that learning python will end up serving me better, at least in the | short run. Plus, you know how Perl goes. If you intend to use Python on the computer at your workplace, then learn the version installed there. | So far the decision seems to be a no brainer. Yet, Python 3000 will arrive | in a few months. As it isn't backwards compatible with today's Python, | there is the risk that no matter what I learn until then, I will end up | having to re-learn at least a considerable part of the language. Most of the changes are deletions and additions, rather than changes. 3.0a4 will be out in a few days. If you had no reason to use anything else, I would consider starting with that. (But the IDLE IDE on Windows may still not work right.) | To put it in other words, I fear that I will be wasting my time. If you learn and use 2.x, then avoid things that are going away. In particular: Unless you need to learn about old-style classes, I would not bother with them and the differences from new, soon to be the only style, classes. Derive all your classes from object or a subclass thereof. Use // for integer floor division (ie, when you want 1/2 == 0. Use 'from __future__ import division' if you use '/' in a file where both operands might be ints and you would want 1/2==.5. | At least that is what a clueless newbie believes. As this group is | frequented by people who have more insight into all things pythonesque, | what are your thoughts on this? Diverse, I am sure ;-) Terry Jan Reedy From ptmcg at austin.rr.com Sun Mar 2 23:21:33 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 Mar 2008 20:21:33 -0800 (PST) Subject: Python-based regular expression parser that allows patterns to call functions? References: Message-ID: <78ccde27-a6fb-485d-b401-d4ac3f92e567@m34g2000hsc.googlegroups.com> pyparsing also includes a decorator function, traceParseAction, which will list out calls to parse actions, the tokens passed in, and the value returned or exception raised. If you add "@traceParseAction" before each of the parse actions in my example, you can see the token processing being done in the parse actions. -- Paul From waltbrad at hotmail.com Wed Mar 26 10:12:21 2008 From: waltbrad at hotmail.com (waltbrad) Date: Wed, 26 Mar 2008 07:12:21 -0700 (PDT) Subject: Running a python program as main... Message-ID: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Stumbling through Mark Lutz's "Programming Python 3rd", he gives an example of a program that will automatically configure environment settings and launch other programs. Then he gives an example of running this program. On his command line he types: C:\...\PP3E>Launcher.py and this begins the program. Doesn't work for me. I have to type: C:\...\PP3E>python Launcher.py Is this a typo on his part or has he configured his settings in such a way that the command line will automatically associate the extension with the program? (If so, he didn't mention this in his book). From dpw.asdf at gmail.com Sat Mar 8 17:20:36 2008 From: dpw.asdf at gmail.com (dpw.asdf at gmail.com) Date: Sat, 8 Mar 2008 14:20:36 -0800 (PST) Subject: Parse specific text in email body to CSV file Message-ID: I have been searching all over for a solution to this. I am new to Python, so I'm a little lost. Any pointers would be a great help. I have a couple hundred emails that contain data I would like to incorporate into a database or CSV file. I want to search the email for specific text. The emails basically look like this: random text _important text:_15648 random text random text random text random text random text random text random text _important text:_15493 random text random text random text random text _important text:_11674 random text random text random text ===============Date: Wednesday March 5, 2008================ name1: 15 name5: 14 name2: 18 name6: 105 name3: 64 name7: 2 name4: 24 name8: 13 I want information like "name1: 15" to be placed into the CSV with the name "name1" and the value "15". The same goes for the date and "_important text:_15493". I would like to use this CSV or database to plot a graph with the data. Thanks! From musiccomposition at gmail.com Mon Mar 31 22:53:19 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 31 Mar 2008 19:53:19 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> <1a8a5b03-0b9e-49de-bd87-43fa1aa99dc2@b5g2000pri.googlegroups.com> <6b732135-a488-4175-889b-0cccf5f0c581@s8g2000prg.googlegroups.com> Message-ID: On Mar 31, 8:41 pm, Alex Teiche wrote: > On Mar 31, 6:40 pm, Alex Teiche wrote: > > > > > On Mar 31, 11:49 am, Alex Teiche wrote: > > > > On Mar 30, 3:50 pm, Benjamin wrote: > > > > > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > > > implement the following thing into my python application: > > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > > > it, but I could not get this specific thing to work. Can someone give > > > > > me some hints as to get it working in Python? > > > > > What problems are you having? > > > > > > Thanks a ton, > > > > > > Alex > > > > Thanks everyone for your help. I found the example to be particularly > > > helpful, and I have made a simplified version just to display an icon > > > with a quit button in its menu. Once I know how to do that I will > > > incorporate it into my larger program, with more options and the > > > ability show messages. The problem is, it doesn't work, and I can't > > > find out what's wrong. Can you give me some hints? > > > > Here is the code: > > > import sys > > > from PyQt4 import QtGui, QtCore > > > > class trayIcon(QtGui.QWidget): > > > def __init__(self, parent=None): > > > QtGui.QWidget.__init__(self, parent) > > > > #********Create Actions for the Tray Menu********# > > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > > > QtCore.QObject.connect(self.quitAction, > > > QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) > > > > create_tray_icon() > > > > self.composeAction.setEnabled(visible) > > > QtGui.QWidget.setVisible(self, visible) > > > > self.trayIcon.show() > > > > def create_tray_icon(self): > > > self.trayIconMenu = QtGui.QMenu(self) > > > self.trayIconMenu.addAction(self.composeAction) > > > self.trayIcon = QtGui.QSystemTrayIcon(self) > > > self.trayIcon.setContextMenu(self.trayIconMenu) > > > self.trayIcon.setIcon(bad.svg) > > > > app = QtGui.QApplication(sys.argv) > > > sys.exit(app.exec_()) > > > OK, I messed around with it some more, and it works. I just don't > > know how to set an icon, and the example doesn't help at all. > > > Here is the code: > > import sys > > from PyQt4 import QtCore, QtGui > > > class Systray(QtGui.QWidget): > > def __init__(self): > > QtGui.QWidget.__init__(self) > > > self.createActions() > > self.createTrayIcon() > > > #QtCore.QObject.connect(self.trayIcon, > > QtCore.SIGNAL("messageClicked()"), self.messageClicked) > > #QtCore.QObject.connect(self.trayIcon, > > QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), > > self.iconActivated) > > > self.trayIcon.show() > > > def createActions(self): > > #self.minimizeAction = QtGui.QAction(self.tr("Mi&nimize"), self) > > #QtCore.QObject.connect(self.minimizeAction, > > # QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("hide()")) > > > #self.maximizeAction = QtGui.QAction(self.tr("Ma&ximize"), self) > > #QtCore.QObject.connect(self.maximizeAction, > > # QtCore.SIGNAL("triggered()"), self, > > # QtCore.SLOT("showMaximized()")) > > > #self.restoreAction = QtGui.QAction(self.tr("&Restore"), self) > > #QtCore.QObject.connect(self.restoreAction, > > # QtCore.SIGNAL("triggered()"), self, > > # QtCore.SLOT("showNormal()")) > > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > > QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), > > QtGui.qApp, QtCore.SLOT("quit()")) > > > def createTrayIcon(self): > > self.trayIconMenu = QtGui.QMenu(self) > > #self.trayIconMenu.addAction(self.minimizeAction) > > #self.trayIconMenu.addAction(self.maximizeAction) > > #self.trayIconMenu.addAction(self.restoreAction) > > #self.trayIconMenu.addSeparator() > > self.trayIconMenu.addAction(self.quitAction) > > > self.trayIcon = QtGui.QSystemTrayIcon(self) > > self.trayIcon.setContextMenu(self.trayIconMenu) > > > app = QtGui.QApplication(sys.argv) > > x = Systray() > > sys.exit(app.exec_()) > > > How would I go about setting the icon? > > Sorry, here is the code with commented out lines removed: > > import sys > from PyQt4 import QtCore, QtGui > > class Systray(QtGui.QWidget): > def __init__(self): > QtGui.QWidget.__init__(self) > > self.createActions() > self.createTrayIcon() > > self.trayIcon.show() > > def createActions(self): > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), > QtGui.qApp, QtCore.SLOT("quit()")) > > def createTrayIcon(self): > self.trayIconMenu = QtGui.QMenu(self) > self.trayIconMenu.addAction(self.quitAction) > > self.trayIcon = QtGui.QSystemTrayIcon(self) > self.trayIcon.setContextMenu(self.trayIconMenu) > > app = QtGui.QApplication(sys.argv) > x = Systray() > sys.exit(app.exec_()) I believe the method you want is QSystemTrayIcon.setIcon. From sneakers_in_china at yahoo.com.cn Sun Mar 30 02:50:33 2008 From: sneakers_in_china at yahoo.com.cn (sneakers_in_china at yahoo.com.cn) Date: Sat, 29 Mar 2008 23:50:33 -0700 (PDT) Subject: ( WWW.SNEAKERS-IN-CHINA.COM) Nike AF1 x Air Jordan 5. Nike Air Force Ones Shoes & Air Jordan 5. Message-ID: <46304cc4-6570-4a05-9d20-ed431590d73f@e23g2000prf.googlegroups.com> (www sneakers-in-china com) wholesale Air Jordan 1 Old Love/New Love Package (www sneakers-in-china com) Nike Air Jordan Retro 1 beginning moments "BMP Package-Old Love New Love Edition" (www sneakers-in-china com) selling Air Jordan DMP Defining Moments Package (www sneakers-in-china com) Air Jordan Retro XIII/X Collezione Package china outlet (www sneakers-in-china com) discount Air Jordan Collezione 13 10 Countdown Package cheap Air Jordan 1 Old Love/New Love Package discount Air Jordan 1 Old Love/New Love Package china customize custom shoes sneakers trainers outlet factory urban clothing,Hip Hop Clothes,urban wear distributor www.sneakers-in-china.com cheap Air Jordan DMP Defining Moments Package discount Air Jordan DMP Defining Moments Package china customize custom shoes sneakers trainers outlet factory urban clothing,Hip Hop Clothes,urban wear distributor www.sneakers-in-china.com cheap Air Jordan Retro XIII/X Collezione Package discount Air Jordan Countdown package Pack 10/13 X XIII china customize custom shoes sneakers trainers outlet factory urban clothing,Hip Hop Clothes,urban wear distributor www.sneakers-in-china.com Air Jordan Beginning Moments Package or Old Love New Love. The Air Jordan Old Love New Love Pack Retro 1 consists of two pairs of Air Jordan 1 (Retro White/Black-Varsity Red aka Black Toes & Black/ Varsity-Maize/White).Comes with special slide out double box with many special moments with Michael Jordan and booklet. Air Jordan Beginning Moments Package or Old Love New Love. Sell Air Jordan 1 Retro-BMP Package Old Love New Love Edition The Air Jordan Old Love New Love Pack Retro 1 consists of two pairs of Air Jordan 1 (Retro White/Black-Varsity Red aka Black Toes & Black/ Varsity-Maize/White). Size available: SIZE (US): 8 8.5 9.5 10 11 12,13 SIZE (UK): 7 7.5 8.5 9 10 11,12 SIZE (EURO): 41 42 43 44 45 46,47 Comes with special slide out double box with many special moments with Michael Jordan and booklet. we also sell and wholesale,retail air jordans,jordan sneakers shoes include: Air Jordan Retro womens shoes Air Jordan Retro kids shoes Air Jordan Spizikes Air Jordan Dub Zeros Air Jordan 4 Fusion Air Jordan 5 Fusion Air Jordan 12 Fusion Air Jordan 23 Fusion (www sneakers-in-china com)Wholesale New Air Jordan 12 Fusion,Air Jordan 12 X Air Force 1. Wholesale New Air Jordan 12 Fusion,Air Jordan 12 X Air Force 1 cheap Air Jordan 5 x Air Force one Fusion (www.sneakers-in-china.com) discount Air Jordan 5 and Air Force one Fusion(www.sneakers-in- china.com) Air Jordan 12 x Air Force One china online store(www sneakers-in-china com) (www sneakers-in-china com)Air Jordan V x Air Force 1 Fusion Air Jordan 12 x Air Force Ones Fusion (www sneakers-in-china com) (www sneakers-in-china com) Nike AF1 x Air Jordan 5. Nike Air Force Ones Shoes & Air Jordan 5. wholesale Air Jordan 5 (V) x Air Force 1 Fusion (www sneakers-in-china com) Website: http://www sneakers-in-china com E-mail: sneakers_in_china @ yahoo com cn Msn: sneakers_in_china @ hotmail com From pavlovevidence at gmail.com Sat Mar 1 04:17:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 1 Mar 2008 01:17:58 -0800 (PST) Subject: Pythons & Ladders References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> <3pidnRLtmJ1KulvanZ2dnUVZ_uyinZ2d@comcast.com> Message-ID: On Feb 27, 10:18 pm, Jeff Schwab wrote: > Benoit wrote: > > I've been teaching myself the python language over the past few months > > using Mark Lutz' Learning Python, 3ed. Python is also the first > > programming language I've ever taken up. I find the language easy to > > learn and rather productive in relation to the introductory course on C > > ++ I'd begun in January for fun @ school (we're practicing dynamic > > arrays using pointers... kill me now). > > Get a better teacher, if you can. Please do me a personal favor: Personal favor? Seriously, do you have stock in a C++ support company or something? There's no need to take stuff like this personally. > Don't > hold the crappy course against C++. C++ has so much badness to hold against it, there's no need to throw a crappy course on top of it. Carl Banks From eddie at holyrood.ed.ac.uk Fri Mar 14 13:27:06 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 14 Mar 2008 17:27:06 +0000 (UTC) Subject: Thousand Seperator References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: ewanfisher at gmail.com writes: >I'm trying to find some code that will turn: >100 -> 100 >1000 -> 1,000 >1000000 -> 1,000,000 >-1000 -> -1,000 >I know that can be done using a regular expression. In Perl I would do >something like: >sub thousand { > $number = reverse $_[0]; > $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; > return scalar reverse $number; >} >But I cannot find how to do this in Python. Look at the locale module. If you're producing the numbers yourself then they get printed in that format otherwise you can convert them to numbers first. Eddie From george.sakkis at gmail.com Sun Mar 23 21:43:27 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 18:43:27 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: <8c9b2c6d-c7bd-4664-bba4-06f35c3735e9@e10g2000prf.googlegroups.com> On Mar 23, 9:02 pm, Carsten Haese wrote: > On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > > That's really weird... it's reproducible on Windows too. It doesn't > > make any sense why the name of the variable would make a difference. > > My guess is you hit some kind of obscure bug. > > This is not a bug, just an unexpected feature:http://mail.python.org/pipermail/python-list/2005-January/304873.html That would make a great entry for the Python IAQ [1] ! As they say, you learn something new every day :) George [1] http://norvig.com/python-iaq.html From http Mon Mar 10 14:05:08 2008 From: http (Paul Rubin) Date: 10 Mar 2008 11:05:08 -0700 Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: <7xod9mo3or.fsf@ruckus.brouhaha.com> John Machin writes: > Bitwise operations like & | ^ << >> etc work on long integers. This > happens at C speed. The problem is if you want to set a bit, you have to allocate a whole new long integer. From neilcrighton at gmail.com Tue Mar 11 17:38:24 2008 From: neilcrighton at gmail.com (neilcrighton at gmail.com) Date: Tue, 11 Mar 2008 14:38:24 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: <42cd60a5-8cf2-4583-82ff-f6ff6939998a@e23g2000prf.googlegroups.com> I think I've worked it out after reading the 'Binary mode for files' section of http://zephyrfalcon.org/labs/python_pitfalls.html zipfile extracts as file as a binary series of characters, and I'm writing out this binary file as a text file with open('foo','w'). Normally Python converts a '\n' in a text file to whatever the platform-dependent indication of a new line is ('\n' on Unix, '\r\n' on Windows, '\r' on Macs). So it sees '\r\n' in the binary file and converts it to '\r\r\n' for the text file. The upshot of this is that writing out the zipfile-extracted files with open('foo','wb') instead of open('foo','w') solves my problem. On Mar 11, 8:43 pm, neilcrigh... at gmail.com wrote: > Sorry my initial post was muddled. Let me try again. > > I've got a zipped archive that I can extract files from with my > standard archive unzipping program, 7-zip. I'd like to extract the > files in python via the zipfile module. However, when I extract the > file from the archive with ZipFile.read(), it isn't the same as the 7- > zip-extracted file. For text files, the zipfile-extracted version has > '\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't > tried comparing binary files via the two extraction methods yet. > > Regarding the code I posted; I was writing it from memory, and made a > mistake. I didn't use: > > z = zipfile.ZipFile(open('foo.zip', 'r')) > > I used this: > > z = zipfile.ZipFile('foo.zip') > > But Duncan's comment was useful, as I generally only ever work with > text files, and I didn't realise you have to use 'rb' or 'wb' options > when reading and writing binary files. > > To answer John's questions - I was calling '\r' a newline. I should > have said carriage return. I'm not sure what operating system the > original zip file was created on. I didn't fiddle with the extracted > file contents, other than replacing '\r' with ''. I wrote out all the > files with open('outputfile','w') - I seems that I should have been > using 'wb' when writing out the binary files. > > Thanks for the quick responses - any ideas why the zipfile-extracted > files and 7-zip-extracted files are different? > > On Mar 10, 9:37 pm, John Machin wrote: > > > On Mar 10, 11:14 pm, Duncan Booth > > wrote: > > > > "Neil Crighton" wrote: > > > > I'm using the zipfile library to read a zip file in Windows, and it > > > > seems to be adding too many newlines to extracted files. I've found > > > > that for extracted text-encoded files, removing all instances of '\r' > > > > in the extracted file seems to fix the problem, but I can't find an > > > > easy solution for binary files. > > > > > The code I'm using is something like: > > > > > from zipfile import Zipfile > > > > z = Zipfile(open('zippedfile.zip')) > > > > extractedfile = z.read('filename_in_zippedfile') > > > > > I'm using Python version 2.5. Has anyone else had this problem > > > > before, or know how to fix it? > > > > > Thanks, > > > > Zip files aren't text. Try opening the zipfile file in binary mode: > > > > open('zippedfile.zip', 'rb') > > > Good pickup, but that indicates that the OP may have *TWO* problems, > > the first of which is not posting the code that was actually executed. > > > If the OP actually executed the code that he posted, it is highly > > likely to have died in a hole long before it got to the z.read() > > stage, e.g. > > > >>> import zipfile > > >>> z = zipfile.ZipFile(open('foo.zip')) > > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\python25\lib\zipfile.py", line 346, in __init__ > > self._GetContents() > > File "C:\python25\lib\zipfile.py", line 366, in _GetContents > > self._RealGetContents() > > File "C:\python25\lib\zipfile.py", line 404, in _RealGetContents > > centdir = struct.unpack(structCentralDir, centdir) > > File "C:\python25\lib\struct.py", line 87, in unpack > > return o.unpack(s) > > struct.error: unpack requires a string argument of length 46 > > > >>> z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK > > >>> z = zipfile.ZipFile('foo.zip', 'r') # OK > > > If it somehow made it through the open stage, it surely would have > > blown up at the read stage, when trying to decompress a contained > > file. > > > Cheers, > > John From p at ulmcnett.com Fri Mar 21 17:09:39 2008 From: p at ulmcnett.com (=?UTF-8?B?UGF1bCBNwqJOZXR0?=) Date: Fri, 21 Mar 2008 14:09:39 -0700 Subject: os.path.getsize() on Windows In-Reply-To: <47E41F3C.6040109@v.loewis.de> References: <47E41F3C.6040109@v.loewis.de> Message-ID: <47E42413.8020503@ulmcnett.com> Martin v. L?wis wrote: >> def isGrowing(f, timeout): >> ssize = os.path.getsize(f) >> time.sleep(timeout) >> esize =os.path.getsize(f) >> return esize != ssize >> >> On windows, this returns the size of the file as it _will be_, not the >> size that it currently is. > > Why do you say that? It most definitely returns what the size currently > is, not what it will be in the future (how could it know, anyway). I've seen this before, when copying a file in Windows. Windows reports the size the file will be after the copy is complete (it knows, after all, the size of the source file). I always thought this meant that Windows is just much smarter than me, so I ignored it. Paul From lesande at gmail.com Wed Mar 19 18:28:13 2008 From: lesande at gmail.com (Lee Sander) Date: Wed, 19 Mar 2008 15:28:13 -0700 (PDT) Subject: removing all instances of a certain value from a list Message-ID: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Hi, I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are many missing vlaues which are represented as None. I would like to remove all such instances in one go. There is a remove function but it removes only the first instance, is there a delete/remove all function? thanks From brnstrmrs at gmail.com Wed Mar 19 14:06:40 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Wed, 19 Mar 2008 11:06:40 -0700 (PDT) Subject: csv dictreader Message-ID: I am trying to use the dictionary reader to import the data from a csv file and create a dictnary from it but just can't seem to figure it out. Here is my code: >>>import csv >>>reader = csv.DictReader(open('table.csv')) >>>for row in reader: >>>print row my csv files looks like this: Bytecode,Element \x00\x00,0000 \x01\x00,0001 .... \x09\x00,0009 My output shows: {'Bytecode': '\\x00\\x00', 'Element': '0000'} {'Bytecode': '\\x01\\x00', 'Element': '0001'} ... {'Bytecode': '\\x09\\x00', 'Element': '0009'} 1. how can I get access to this directory 2. why does the values come with two backslashs infront of the "x" From paddy3118 at googlemail.com Wed Mar 12 14:43:28 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 12 Mar 2008 11:43:28 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: <9673d45f-c0aa-47ea-919e-d15a5be61d5b@i7g2000prf.googlegroups.com> On Mar 12, 6:19 pm, Alex wrote: > Hi all, > > The subject says pretty much all, i would very appreciate an answer. I > tried to search the various forums and groups, but didn't find any > specific answer... > > Thanks, > Alex. No not really. There are lots of other ways to structure a Python program though which makes its omission hardly felt. - Paddy. From tim.leslie at gmail.com Sun Mar 30 22:48:34 2008 From: tim.leslie at gmail.com (Tim Leslie) Date: Mon, 31 Mar 2008 13:48:34 +1100 Subject: Rubik's cube translation In-Reply-To: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> References: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> Message-ID: On Mon, Mar 31, 2008 at 12:24 PM, wrote: > How do I get a Rubik's cube translation out of this: > > >>> a= numpy.array([[0,1,2],[3,4,5],[6,7,8]]) > >>> a > array([[0, 1, 2], > [3, 4, 5], > [6, 7, 8]]) > >>> a[:,0],a[:,1],a[:,2] #no good > (array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])) > >>> > > I need [[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]. > > >>> c= numpy.array([[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]) > >>> c > array([[6, 3, 0], > [7, 4, 1], > [8, 5, 2]]) In [10]: numpy.rot90(a, 3) Out[10]: array([[6, 3, 0], [7, 4, 1], [8, 5, 2]]) Tim > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Mon Mar 10 07:57:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 12:57:44 +0100 Subject: Distributed App - C++ with Python for Portability? References: Message-ID: <63km1jF27n1hpU1@mid.uni-berlin.de> Roopan wrote: > Hello! > > I am looking at developing an enterprise-grade distributed data > sharing application - key requirements are productivity and platform > portability. > > Will it be sensible to use C++ for performance-critical sections and > Python for all the glue logic. > > Pls comment from your *experiences* how Python scales to large > projects( > 200KLOC). > I assume the C++/Python binding is fairly painless. It depends. There are good wrappers out there, I personally prefer SIP. However, a mixed language environment is always a PITA, especially for distribution. If you can, write everything in python. Identify bottlenecks, and if you must, I suggest using C + ctypes for performance-critical code. Obviously it's a matter of taste, but C++ is a beast, and getting it to work seamless under varying compilers and OSes could be avoided using plain C. Diez From blwatson at gmail.com Fri Mar 28 22:23:01 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Fri, 28 Mar 2008 19:23:01 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> Message-ID: <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> On Mar 28, 1:57?pm, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: > > > I am trying to install the twitter python wrapper...I got that > > installed just fine, but am having serious troubles getting the > > simplejson package to install. ?I need help diagnosing where this is > > failing. ?I am trying to use: > > >http://pypi.python.org/pypi/simplejson > > > and I run "python setup.py build" and then "python setup.py install", > > which both seem to work just fine. > > I don't understand - if it worked fine, what's the problem? > > > I tried running with easy_install, but that too is not working. ?I end > > up with: > > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > > in my: > > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > > packages/ > > > I am on Mac OS X 10.5. ?Any help would be greatly appreciated. > > And then you import simplejson and it fails? Or what? > > -- > Gabriel Genellina Yes, when I try to import simplejson, it fails >>> import simplejson Traceback (most recent call last): File "", line 1, in import simplejson ImportError: No module named simplejson there is not simplejson.py anywhere on my machine. I understand that I am new to python and trying to make heads or tails of what has happened with this install process. Any help is appreciated. From bj_666 at gmx.net Sun Mar 2 02:24:32 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Mar 2008 07:24:32 GMT Subject: mod_python Unable to create file References: Message-ID: <62v31gF24ontgU1@mid.uni-berlin.de> On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: > I am using Apache and mod_python to service POST/GET requests on MAC > OS. My script tries to create a file > > file = open(file_path, 'w') > > This fails with the following error > > EACCES > Permission denied > > What is missing? To state the ovious: the rights to create a file at `file_path`. Remember that web servers usually have their own "user". Ciao, Marc 'BlackJack' Rintsch From barry at python.org Mon Mar 3 07:17:00 2008 From: barry at python.org (Barry Warsaw) Date: Mon, 3 Mar 2008 07:17:00 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <47CB9F3C.9030202@v.loewis.de> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> <47CB9F3C.9030202@v.loewis.de> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mar 3, 2008, at 1:48 AM, Martin v. L?wis wrote: >>> But it would be really nice if the configure fix for 2.5 was >>> backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped >>> system builds for 2.4 going direct from 2.3 -> 2.5. >> >> >> Yes, it would be very nice if this worked out of the box on Mac OS X >> 10.5.2. It's definitely a surprise for those of us who built our >> 2.4.4 >> on Mac OS X 10.4.x. > > I can put a notice in the release notes, but I definitely won't change > it to work out of the box. If 2.4.4 compiled out of the box on this > box, > it would have been a regression and would have to be fixed. IIUC, > 2.4.4 > won't compile on 10.5, either, and Python 2.4.5 will have no code to > port it to new platforms. Can you also add a note to the 2.3 and 2.4 web pages? - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iQCVAwUBR8vsPHEjvBPtnXfVAQJVpgP5AbRU+BENEa7fv7vGUykjtQRftaF6ATQz yTo9018UiQZ20bFv2PIvgHltsET1ksTuieSdDjGbQ3rGu3vo1tldiGYxUQJgi++C q8ntOyLUo+nHSlKm11TTyMiNX4igl+X0bes5PlgJZbWOnw0vBvWbVRrwgMUsJqfi ox/d8+2jWc4= =HLja -----END PGP SIGNATURE----- From bearophileHUGS at lycos.com Sun Mar 23 12:28:23 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 23 Mar 2008 09:28:23 -0700 (PDT) Subject: Duplicating list of lists [newbie] References: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Message-ID: Yatsek: > Is there simple way to copy a into b (like a[:]) with all copies of > all objects going as deep as possible? If you only want to copy up to level-2, then you can do something like: cloned = [subl[:] for subl in somelist] Or sometimes safer: cloned = [list(subl) for subl in somelist] If you want to go all the way down, you can use the deepcopy function of the copy module. In many situations the level-2 copy may be enough, and it can be faster. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 23:14:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 04:14:48 -0000 Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> Message-ID: <13t6p1o23so7oc2@corp.supernews.com> On Sat, 08 Mar 2008 18:50:30 -0800, Chick wrote: > Hello, > > I'm writing a security tool Oh good, just what we need, beginners writing security tools. > which requies wiping off the memory of > certain string after being used, which I've done by implementing it as a > mutable list as follow: > > class secureStr: Unless you have a need for backwards compatibility, you probably should use new-style classes rather than classic classes. > def __init__(self, str): > self.__s = [] > for i in range(len(str)): > self.s += str[i] > > def __str__(self): > return "".join(self.__s) > > def wipe(self): > for i in range(len(self.__s)): > self.s[i] = '\x00' > > def __del__(self): > self.wipe() How do you prevent the operating system from paging the block of memory to disk? It's all well and good to wipe the password located at address 0xb7f7a32c in RAM but that's not going to save you when the bad guys locate it in the swap file. In any case, an easier way to get the above illusion of security is this: class secureStr(list): def __str__(self): return "".join(self) def wipe(self): for i in xrange(len(self)): self[i] = '\x00' def __del__(self): self.wipe() It contains the exact same security holes as your code, but is shorter. > My question is how do I write a function to securely get the password > from user (in text mode)? If I do sth like > > import getpass > securePass = secureStr(getpass,getpass()) > > doesn't that create an immediate string object that will stay in memory? Yes, the string object will be deleted but not over-written. That may or may not happen. One way to increase the chances of that happening is: import getpass securePass = secureStr(getpass.getpass()) # not actually secure s = '\00'*len(securePass) It's not guaranteed to over-write the memory location with the intermediate string object, but you might get lucky. What's the threat you're defending against? It seems to me that you are worrying about somebody (a person? another program? the operating system?) reading the password out of Python's free memory blocks. Fair enough, attackers can and have recovered passwords out of free memory. But a far bigger security hole is that the password is sitting there in your securePass variable in plain text. What are you doing about that? -- Steven From nick.fabry at coredump.us Wed Mar 19 10:12:15 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Wed, 19 Mar 2008 10:12:15 -0400 Subject: Improving datetime Message-ID: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> This is a query for information as to how to proceed. I am not a professional programmer, but I use Python a great deal to help me in my main job, which involves designing schedules for a global airline. As such, I use datetime (and dateutil) extensively, and after much use, I have come to some conclusions about their utility, and how to improve them. Some of these changes are quite minor and would result in a large increase in utility (low hanging fruit), while some changes are major, and would result in less obvious benefits - but these changes would increase the 'Python Zen' of them. So - where should I propose these changes? Here? python-dev? Should I write up a full PEP or should I just give a more informal outline with code samples? I would volunteer to help maintain/improve datetime, but I don't speak C at all, unfortunately, and datetime appears to be in C. In addition, I have little contact with the Python community - I work somewhat 'solo' when it comes to my programming projects. So, are there other people out there who use datetime? Dateutil? What do you find the deficits/benefits of these modules to be? Thank you for your thoughts.... Nick Fabry From cantabile.03 at wanadoo.fr Sun Mar 16 22:03:41 2008 From: cantabile.03 at wanadoo.fr (Unknown) Date: 17 Mar 2008 02:03:41 GMT Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> <47dc43e0$0$849$ba4acef3@news.orange.fr> <65faeeb8-d1d2-4d50-8421-f19a5ceb8ba5@8g2000hsu.googlegroups.com> Message-ID: <47ddd17d$0$899$ba4acef3@news.orange.fr> Le Sat, 15 Mar 2008 16:55:45 -0700, joep a ?crit?: > you can also use standard module fileinput.input with ''inplace'' option > which backs up original file automatically. > > from python help for fileinput: > > Optional in-place filtering: if the keyword argument inplace=1 is passed > to input() or to the FileInput constructor, the file is moved to a > backup file and standard output is directed to the input file (if a file > of the same name as the backup file already exists, it will be replaced > silently). Thanks for the idea :) What I do not get is how I can replace a string with that. If I write something like: for line in filehandle.input('myfile.txt', inplace=1): rx = re.match(r'^\s*(\d+).*',line ) if not rx: continue else: oldValue = rx.group(1) Value = 123456789 line = string.replace(line, oldValue, "%d" Value) print line break This code replaces the whole file with line, instead of replacinf the old value with the new one. Did I forget something ? From gerdusvanzyl at gmail.com Wed Mar 12 10:18:48 2008 From: gerdusvanzyl at gmail.com (Gerdus van Zyl) Date: Wed, 12 Mar 2008 07:18:48 -0700 (PDT) Subject: List Combinations Message-ID: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> I have a list that looks like this: [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] how can I get all the combinations thereof that looks like as follows: 3,9,5,4,2 3,1,5,4,2 3,9,5,4,5 3,1,5,4,5 etc. Thank You, Gerdus From deets at nospam.web.de Wed Mar 19 03:56:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 08:56:45 +0100 Subject: method to create class property In-Reply-To: References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> <64astpF29u3k1U1@mid.uni-berlin.de> Message-ID: <64bva2F2b4s68U1@mid.uni-berlin.de> > Isn't that:: > > > > @propset(foo) > > def foo(self, value): > > self._value = value Yeah, you are right. Diez From gagsl-py2 at yahoo.com.ar Wed Mar 19 20:07:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 21:07:40 -0300 Subject: Python to C/C++ References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: En Wed, 19 Mar 2008 13:17:01 -0300, Blubaugh, David A. escribi?: > Has anyone worked with a translator that will translate python to c/c++ > source code? I know that there is already one translator of this nature > (shedskin compiler) out there. However, it is still in the beta stage > of development. Does anyone know of a more developed version of a > translator of this nature? There is also Cython (based on Pyrex). But they use a different approach than ShedSkin. You may want to read this thread: http://thread.gmane.org/gmane.comp.compilers.shedskin.general/66 -- Gabriel Genellina From allen.fowler at yahoo.com Tue Mar 4 13:53:43 2008 From: allen.fowler at yahoo.com (allen.fowler) Date: Tue, 4 Mar 2008 10:53:43 -0800 (PST) Subject: Edit MP4 and/or WMV file metadata? Message-ID: <3fd17c11-6efa-4474-82c7-949e6c7ce5cc@e10g2000prf.googlegroups.com> Hello, I have many WMV files with bad embedded author/title/date information. However, the correct information is correctly encoded in the file name.. i.e. "title-author-date.wmv" I am about to conver these fiiles to MP$ for use on an iPod. The video software I am using will, I think, transfer the metadata from the WMV to MP4 files. So, two questions: 1) Is there a python module I can use to edit the metadata in MP4 files? 2) Failing that, is there a python module I can use to edit the metadata in the WMV files, and hope the data makes it through the conversion? -- Thank you From Dominique.Holzwarth at ch.delarue.com Mon Mar 31 05:05:39 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Mon, 31 Mar 2008 10:05:39 +0100 Subject: Problem with method overriding from base class Message-ID: <5213E58D85BC414998FA553C701E386C0EDD00FE2F@SGBD012511.dlrmail.ad.delarue.com> Hello everyone I have defined some sort of 'interface class' and a factory function that creates instance objects of specific classes, which implement that interface: Interface definition: *************************************************************************************** import GUI.webGUI as webGUI class EditInterface(webGUI.WebGUI): def addEntry(self, *p): raise 'EditInterface.addEntry(): Interface must not be called directly' def clearScreen(self, *p): raise 'EditInterface.clearScreen(): Interface must not be called directly' def deleteEntry(self, *p): raise 'EditInterface.deleteEntry(): Interface must not be called directly' def editEntry(self, *p): raise 'EditInterface.editEntry(): Interface must not be called directly' def processUserInput(self, *p): raise 'EditInterface.processUserInput(): Interface must not be called directly' def show(self, entry, statustext): raise 'EditInterface.show(): Interface must not be called directly' *************************************************************************************** Factory: *************************************************************************************** def factory(type, *p): if type == common.databaseEntryTypes[0]: return module1.Class1(*p); elif type == common.databaseEntryTypes[1]: return module2.Class2(*p); elif type == common.databaseEntryTypes[2]: return module3.Class3(*p); elif type == common.databaseEntryTypes[3]: return module4.Class4(*p); *************************************************************************************** Implementing Class1: *************************************************************************************** import editInterface class Class1(editInterface.EditInterface): def __init__(self, product, database): # do something here ... def showEntry(self, entry, statustext): # do something here as well, return some string... *************************************************************************************** Now, when I want to create an Instance of Class1 I do: myClass1Instance = factory.factory(common.databaseEntryTypes[1], 'Name', databaseObj ) Which seems to work fine according to the debugger. But when I do next: msg = myClass1Instance.show(firstEntry, '') Then the show() method of the class 'EditInterface' is called instead of the show() method of the class 'Class1' !! Does anyone have an idea why the method of the base class is called instead of the method of the derived class and how can I do it, so that the show() of Class1 is called instead? Greetings Dominique (did some data hiding there, but shouldn't really matter for the problem ;-)) From michael.wieher at gmail.com Fri Mar 7 11:29:39 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 10:29:39 -0600 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: Placing 2 spaces after a period is standard, grammatically correct English, at least as I was taught... I don't know who Strunk or White are. Maybe Mr. Pink has a book you can refer to instead. 2008/3/7, K Viltersten : > > I've been recommended reading of: > http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i > need to get elaborated. > > > 1. When writing English, Strunk and > White apply. > > Where can i download it? Am i actually > expected to read the whole book? How > many people actually do aply it? > > > 2. You should use two spaces after a > sentence-ending period. > > For heavens sake, why? I've always been > obstructed by the double blanks but > tolerated them. Now, that i read that > it actually is a recommendation, i need > to ask about the purpose. > > > Thanks for the input in advance. > > -- > Regards > Konrad Viltersten > -------------------------------- > sleep - a substitute for coffee for the poor > ambition - lack of sense to be lazy > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shahmed at sfwmd.gov Thu Mar 20 10:11:44 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 20 Mar 2008 10:11:44 -0400 Subject: Deleting Microsoft access database In-Reply-To: Message-ID: <14A2A120D369B6469BB154B2D2DC34D20A747C3C@EXCHVS01.ad.sfwmd.gov> I have a Microsoft Access database that I want to delete whether anyone is using that file. The database is already read only mode residing in a server, users are opening in read only mode. I want to delete that file, I remove read only check but could not delete that file. Getting error message: Cannot delete xxx : It is being used by another person or program. Any help is highly appreciated. Thanks sa From jgv-home at comcast.net Tue Mar 25 20:03:40 2008 From: jgv-home at comcast.net (jv) Date: Tue, 25 Mar 2008 18:03:40 -0600 Subject: how to dynamically create class methods ? In-Reply-To: <13uj0m4qd1dit79@corp.supernews.com> References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: <47E992DC.2050800@comcast.net> Steven D'Aprano wrote: > On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: > >> As per your suggestion, I tried looking at include/code.h and >> include/funcobject.h (my MS Windows distribution does not appear to >> contain .c files). However, since I'm not a C programmer, I did not >> find the .h files all that helpful. > > I'm hardly surprised. The naivety of those who insist that the "best way > to understand how new.function and new.code work" is to look at the C > source code for object is amusing. Not everybody reads C. This is a > Python group, and surely the best way would be to see some good examples > using *Python*. > > >> What I failed to make clear in my original posting is that the >> functions must be created dynamically using information in a *record* >> as the code iterates over all *records*. So, I can not pre-define the >> functions and then simply select the desired one at run-time. > > Here's an example that might help. > > > class MyClass(object): > pass > > records = ["spam", "ham"] > for record in records: > # define a new function > def f(n): > return (record + " ")*n > # create a new instance > instance = MyClass() > # and dynamically add a method to it > setattr(instance, 'execute', f) > instance.execute(5) > > > Gabriel, Steven, Thanks for taking the time to respond with such clear examples. All I can say is: "when will I ever learn **everything** in Python is an object -- including functions"! I had a suspicion I was making a simple task complicated. -- jv From nospam at nospam.com Mon Mar 10 23:21:52 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 11 Mar 2008 04:21:52 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: On Mon, 10 Mar 2008 11:27:06 -0400, "Malcolm Greene" wrote: >Any suggestions on an alternative Python client-side GUI library (pyQT >?) or tips on where I can find out more about wxPython/wxWidget >problems? One thing that bothers me is that it seems like there's no ecosystem around it, so the only widgets available are those that come from wxWidgets proper. For instance, I find the grid object a bit poor-featured compared to what's available for VB6, .Net, or Delphi, but I didn't find alternatives. From josef.pktd at gmail.com Sun Mar 16 11:41:51 2008 From: josef.pktd at gmail.com (joep) Date: Sun, 16 Mar 2008 08:41:51 -0700 (PDT) Subject: Spaces in path name References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> Message-ID: <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> Tim Golden wrote: > Tim Golden wrote: > > What I haven't investigated yet is whether the additional flags > > your example is passing (shell=True etc.) cause the main Popen > > mechanism to take a different path. > > Sure enough, passing shell=True -- which is probably quite > a rare requirement -- causes the code to change the call > from "a.exe b.doc" to '%COMSPEC% /c "a.exe" "b.doc"'. > The quoting rules (from cmd /?) are slightly involved but > I can't see at first why this shouldn't work. However it > clearly doesn't so I'll try to put together either a patch > to the subprocess code or to the docs warning of the behaviour. > > I think that, in general, you need to pass shell=True far less > often that you might imagine. (Possibly only for internal > commands like dir, copy etc.). > > TJG Thanks, I didn't know it is possible to drop the shell=True. The explanation of the subprocess model are not very clear to me and the examples are quite incomplete. I got it to work by trial and error and looking at the usage in different packages. Dropping shell=True works well for my case, no error messages and it still captures the standard output: p = subprocess.Popen([ r"C:\Program Files\WinRAR\Rar.exe","v", r"C:\temp\Copy of papers.rar"], stdout=subprocess.PIPE) I am still looking at different versions, and the cases when it works and when it doesn't are still confusing. Josef From gagsl-py2 at yahoo.com.ar Sat Mar 29 00:24:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 01:24:16 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 23:23:01 -0300, escribi?: > On Mar 28, 1:57?pm, "Gabriel Genellina" > wrote: >> En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: >> >> > I am trying to install the twitter python wrapper...I got that >> > installed just fine, but am having serious troubles getting the >> > simplejson package to install. ?I need help diagnosing where this is >> > failing. ?I am trying to use: >> >> >http://pypi.python.org/pypi/simplejson >> >> > and I run "python setup.py build" and then "python setup.py install", >> > which both seem to work just fine. I tried to install the package but failed. Looks like the setup.py used by simplejson is broken - doesn't handle well the case when the C extension can't be compiled. When I run `python setup.py install` I got this message: building 'simplejson._speedups' extension ********************************************************************** WARNING: The C extension could not be compiled, speedups are not enabled. Below is the output showing how the compilation failed: Python was built with Visual Studio version 7.1, and extensions need to be built with the same version of the compiler, but it isn't installed. ********************************************************************** and later: removing simplejson.egg-info\native_libs.txt ... error: can't copy 'simplejson.egg-info\native_libs.txt': doesn't exist or not a regular file I suggest that you remove the simplejson-xxxxxx.egg file and delete the simplejson entry in easy-install.pth (both in your site-packages directory) Then extract the simplejson directory from inside the original .tar.gz archive into your site-packages directory (so you end up by example with a .../site-packages/simplejson/decoder.py file, among others) That appears to be enough; import simplejson worked fine for me. I hate those f****ng eggs. Ah, and I hate easy_install too. -- Gabriel Genellina From geert at nznl.com Tue Mar 18 18:47:00 2008 From: geert at nznl.com (geert) Date: Tue, 18 Mar 2008 15:47:00 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> Message-ID: On Mar 18, 6:56?pm, geert wrote: > On Mar 14, 1:15?pm, martin.lal... at gmail.com wrote: > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > Just wanted to let you know that I've solved my problem. The solution > is to compile mysql using > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > ./configure --disable-dependency-tracking ?--enable-thread-safe-client > --prefix=/usr/local/mysql > > You then go this way to get it running on your machine: > > http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > Then reinstall MySQLdb. Magic! > > Geert Seems that I've yelled success to quickly. Everything's ok as long as I just run the django dev server, but moving to apache through mod_wsgi brings a well-known but less than comforting complaint: [Tue Mar 18 23:34:25 2008] [error] [client ::1] mod_wsgi (pid=2352): Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ LN/LNApache.wsgi'., referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent call last):, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in __call__, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = self.get_response(request), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/core/handlers/base.py", line 64, in get_response, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = middleware_method(request), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/contrib/sessions/middleware.py", line 13, in process_request, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line 2, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.contrib.sessions.models import Session, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db import models, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/db/__init__.py", line 17, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, ['']), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, in , referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no suitable image found. Did find:, referer: http://localhost/images/ [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- tmp/_mysql.so: no matching architecture in universal wrapper, referer: http://localhost/images/ mmmmmm Geert From modelnine at modelnine.org Wed Mar 26 14:45:34 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 26 Mar 2008 19:45:34 +0100 Subject: what does ^ do in python In-Reply-To: <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <200803261945.34530.modelnine@modelnine.org> Am Mittwoch, 26. M?rz 2008 19:04:44 schrieb David Anderson: > HOw can we use express pointers as in C or python? There's no such thing as a pointer in Python, so you can't "express" them either. Was this what you were trying to ask? -- Heiko Wundram From pavlovevidence at gmail.com Mon Mar 10 10:39:35 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Mar 2008 07:39:35 -0700 (PDT) Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: On Mar 8, 5:15 pm, "Terry Reedy" wrote: > I gave a clear and coherent explanation of how while derives from if, > and correspondingly, how while-else derives from if-else, to help those who > want to read and write Python code. Building on the pseudo-snippet above, > one can write > > while loop_condition: > > if break_condition: > > break > > else: > > > Python allows one to have both break-only and completion-only sections > together in one compound statement and *without* having to fiddle with a > special flag variable. I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. Just to play Devil's advocate, there is one draw drawback to "such elegance": when there are multiple break statements. Which means you'd have to duplicate the break-only condition, or refactor somehow (which may or may not be suitable). There have been a couple occasions where I felt the best solution was to a temporary varible like so: completed = False while loop_condition: if break_condition: break if some_other_break_condition: break else: completed = False if not completed: It felt icky but we're all still here so it couldn't have been that bad. Carl Banks From Graham.Dumpleton at gmail.com Wed Mar 19 19:47:00 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 19 Mar 2008 16:47:00 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> <7900f1db-16a5-45d1-ada3-962ac0e712b8@e6g2000prf.googlegroups.com> <046c9579-9ff3-44ad-86b7-0c64c8a606ed@8g2000hsu.googlegroups.com> Message-ID: On Mar 19, 9:30 pm, geert wrote: > On Mar 19, 2:26 am, Graham Dumpleton > wrote: > > > > > On Mar 19, 9:47 am, geert wrote: > > > > On Mar 18, 6:56 pm, geert wrote: > > > > > On Mar 14, 1:15 pm, martin.lal... at gmail.com wrote: > > > > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > > > > Just wanted to let you know that I've solved my problem. The solution > > > > is to compile mysql using > > > > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > > > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > > ./configure --disable-dependency-tracking --enable-thread-safe-client > > > > --prefix=/usr/local/mysql > > > > > You then go this way to get it running on your machine: > > > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > > > > Then reinstall MySQLdb. Magic! > > > > > Geert > > > > Seems that I've yelled success to quickly. Everything's ok as long as > > > I just run the django dev server, but moving to apache throughmod_wsgibrings a well-known but less than comforting complaint: > > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352): > > > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ > > > LN/LNApache.wsgi'., referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent > > > call last):, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in > > > __call__, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > > > self.get_response(request), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in > > > get_response, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > > > middleware_method(request), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line > > > 13, in process_request, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine = > > > __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line > > > 2, in , referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from > > > django.contrib.sessions.models import Session, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, > > > in , referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db > > > import models, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/db/__init__.py", line 17, in , > > > referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend = > > > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, > > > {}, ['']), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > > > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, > > > in , referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise > > > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: > > > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ > > > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no > > > suitable image found. Did find:, referer:http://localhost/images/ > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ > > > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- > > > tmp/_mysql.so: no matching architecture in universal wrapper, referer:http://localhost/images/ > > > Did you again confirm that running: > > > file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5- > > macosx-10.5-i386.egg-tmp/_mysql.so > > > shows the .so having the required architectures, specifically what > > Apache runs as (eg. x86_64)? > > > Do the gcc compiler flags when building and linking the .so file show > > all the architecture flags? > > > Have you empty the Python egg cache to make sure it isn't an older > > compiled version? > > > Graham > > Hi all, > > GOT IT! > > I have every running now. So, to sum it all up: > > I'm on a new intel mac with a 64-bit capable processor running macosx > 10.5.2. > > I have httpd (apache2) running as a 64 bit app, which it would of > course on a 64-bit machine. Activity monitor confirms this. > > I compiled mysql from source, configured as stated below: > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > ./configure --disable-dependency-tracking --enable-thread-safe- > client > --prefix=/usr/local/mysql > > Then camemod_wsgi, just out of the box. > > Then came MySQLdb. > > Extracted the tar, then edited _mysql.c. Commented lines 37 - 39: > > //#ifndef uint > //#define uint unsigned int > //#endif > > and changed this: > uint port = MYSQL_PORT; > uint client_flag = 0; > > to this: > unsigned int port = MYSQL_PORT; > unsigned int client_flag = 0; > > on lines 484 and 485 > > Then - but I don't know if this is really (always) necessary, in > site.cfg I changed Threadsafe = True to False. > > I set the ARCHFLAGS, but I don't think this helped one inch. > > ARCHFLAGS='-arch ppc -arch ppc64 -arch i386 -arch x86_64' > > OK. So then I went sudo python setup.py build. (I realise that the > sudo isn't required just to do a build) > > There, I noticed this: > > creating build/temp.macosx-10.5-i386-2.5 > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- > madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes - > DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -pipe - > Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/ > include/mysql -I/System/Library/Frameworks/Python.framework/Versions/ > 2.5/include/python2.5 -c _mysql.c -o build/temp.macosx-10.5-i386-2.5/ > _mysql.o -arch i386 -arch x86_64 -arch ppc7400 -arch ppc64 > > You see, here _mysql.o is being created. If you do file _mysql.o, you > get: > > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o: Mach-O universal binary with 4 architectures > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture i386): Mach-O object i386 > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture x86_64): Mach-O 64-bit object > x86_64 > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture ppc7400): Mach-O object ppc > /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- > i386-2.5/_mysql.o (for architecture ppc64): Mach-O 64-bit object ppc64 > > which is ok. > > But, strangely, when _mysql.so is created in the next step, gcc > doesn't add all the arch flags: > > gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch i386 -arch ppc > build/temp.macosx-10.5-i386-2.5/_mysql.o -L/usr/local/mysql/lib/mysql - > lmysqlclient -lz -lm -o build/lib.macosx-10.5-i386-2.5/_mysql.so > > and you end up with this: > > geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/geert/ > Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/_mysql.so > /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ > _mysql.so: Mach-O universal binary with 2 architectures > /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ > _mysql.so (for architecture i386): Mach-O bundle i386 > /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ > _mysql.so (for architecture ppc7400): Mach-O bundle ppc > > which is most definitely NOT ok. > > So I did this: > > sudo gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch ppc -arch > ppc64 -arch i386 -arch x86_64 build/temp.macosx-10.5-i386-2.5/_mysql.o > -L/usr/local/mysql/lib/mysql -lmysqlclient -lz -lm -o build/ > lib.macosx-10.5-i386-2.5/_mysql.so > > adding the arch flags myself, and running gcc again, under sudo. > > and lo and behold.... > > geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/ > geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/ > _mysql.so > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so: Mach-O universal binary with 4 architectures > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture ppc7400): Mach-O bundle ppc > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture ppc64): Mach-O 64-bit bundle > ppc64 > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture i386): Mach-O bundle i386 > /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- > i386.egg-tmp/_mysql.so (for architecture x86_64): Mach-O 64-bit bundle > x86_64 > > Well, it only took 20 years off my life span and all the hairs on my > head :) I don't have access to MacOS X OS supplied Python 2.5 at moment, but if distutils used by setup.py is ignoring ARCHFLAGS for the link then that may be an issue with distutils. More likely though is that MySQL setup.py is setting some option which is causing ARCHFLAGS to be ignored. Strange thing is I can't find ARCHFLAGS in original Python 2.5 source I have, so checking it may be specific to MacOS X OS supplied Python. Will need to check when I get home to my Leopard box. Graham From tmp1 at viltersten.com Fri Mar 7 11:31:35 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 17:31:35 +0100 Subject: Regarding coding style Message-ID: <63d80bF273nraU1@mid.individual.net> I've been recommended reading of: http://www.python.org/dev/peps/pep-0008/ and in there i saw two things that i need to get elaborated. 1. When writing English, Strunk and White apply. Where can i download it? Am i actually expected to read the whole book? How many people actually do aply it? 2. You should use two spaces after a sentence-ending period. For heavens sake, why? I've always been obstructed by the double blanks but tolerated them. Now, that i read that it actually is a recommendation, i need to ask about the purpose. Thanks for the input in advance. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From tms at zeetix.com Sat Mar 15 13:54:35 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 13:54:35 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <004401c886c5$a1aba880$0200a8c0@TMSMAIN> > Somehow I don't get what you are after. The ' doesn't have to be escaped > at all if " are used to delimit the string. If ' are used as delimiters > then \' is a correct escaping. What is the problem with that!? If I delimit the string with double quote, then I have to escape every double quote in whatever I serialize. I'm moving strict html from the server to the browser, and therefore the value of every tag attribute is delimited by double quotes. That means that I'd have to escape every double quote, and there are MANY more of them. Thanks, Tom From justus.schwabedal at gmx.de Thu Mar 13 18:47:58 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Thu, 13 Mar 2008 23:47:58 +0100 Subject: Problem with exec Message-ID: I'm trying to parallise with python. Specifically I'm sending code to the processes and let them exec this code (in ascii form). However I ran into a problem with Namespaces (I think) which I do not understand. Here's what I do first: --------------------------------------- bash-3.2$ cat execBug.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ exec header print "f() =",f() bash-3.2$ ./execBug.py f() = 0.633306324515 it est: it works. However when I do this: bash-3.2$ cat execBug2.py #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ def g(): exec header return f() print "g() =",g() bash-3.2$ ./execBug2.py g() = Traceback (most recent call last): File "./execBug2.py", line 10, in print "g() =",g() File "./execBug2.py", line 9, in g return f() File "", line 4, in f NameError: global name 'randn' is not defined bash-3.2$ ??? I get this global name error. I can fix it with adding some line like "global randn" but I don't want to do this. I want to do exactly what I wrote: Import the function scipy.randn in the local namespace of the function "g" so that "return f()" makes sense. Can anybody help me out? Yours Justus From timr at probo.com Thu Mar 20 23:31:27 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Mar 2008 03:31:27 GMT Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> <29cd9085-b70f-4873-899e-3837d8e42d90@u69g2000hse.googlegroups.com> Message-ID: Gowri wrote: > >I understand it's JSON. My problem is that it just prints crazy >characters instead of the JSON data. Ah, I see. I didn't get that from your original post. >Like I mentioned, this happens on >my windows machine which has python 2.5. On the other hand, the same >code worked perfectly great on my linux machine with python 2.3.4. >What could the problem be? I'm not sure. It worked correctly on my Windows machine with Python 2.4.4. Are you going through a proxy? Are you able to read other (non-JSON) web pages using urllib2? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From xelapond at gmail.com Sun Mar 30 10:39:30 2008 From: xelapond at gmail.com (Alex Teiche) Date: Sun, 30 Mar 2008 07:39:30 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: On Mar 30, 2:08 am, Phil Thompson wrote: > On Sunday 30 March 2008, Alex Teiche wrote: > > > Hello, > > > I am pretty new to Python, and have never learned C++. I am trying to > > implement the following thing into my python application: > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > it, but I could not get this specific thing to work. Can someone give > > me some hints as to get it working in Python? > > > Thanks a ton, > > > Alex > > Have you looked at PyQt's systray example? > > Phil No, where do I find the example? Thanks, Alex From python.list at tim.thechases.com Mon Mar 10 13:29:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Mar 2008 12:29:51 -0500 Subject: lowercase u before string in "python for windows" In-Reply-To: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> References: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> Message-ID: <47D5700F.80207@tim.thechases.com> > why does this occur when using the python windows extensions? all > string are prefixed by a lowercase "u". They are Unicode strings: http://docs.python.org/ref/strings.html > is there a newsgroup explicitly for python windows extensions? Not that I know of, other than what's described here: https://sourceforge.net/mail/?group_id=78018 -tkc From castironpi at gmail.com Sat Mar 15 05:00:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 02:00:44 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> On Mar 15, 3:33?am, "Gabriel Genellina" wrote: > En Thu, 13 Mar 2008 15:18:44 -0200, escribi?: > > > Well, lets say you have a situation where you're going to be > > alternating between sending large and small chunks of data. Is the > > solution to create a NetworkBuffer class and only call send when the > > buffer is full, always recv(8192)? > > No need to reinvent the wheel. socket objects already have a makefile ? > method returning a file-like object, which behaves like a buffered socket. Newbie question: Can you write to the 'file-like object' a pickle, and receive it intact-- as one string with nothing else? I want to know because I want to send two pickles. From duncan.booth at invalid.invalid Mon Mar 31 03:36:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 07:36:00 GMT Subject: Licensing References: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> Message-ID: Paul Boddie wrote: > Note that the Python Cookbook says this about licensing: "Except where > otherwise noted, recipes in the Python Cookbook are published under > the Python license." The link is incorrect, but I presume they mean > this licence: > > http://www.python.org/psf/license/ > I don't have a printed copy, but Google Books has it (not sure which edition I found) and page xix says: Given the nature of the cookbook, we wanted the recipes to be usable under any circumstances where Python could be used. In other words, we wanted to ensure completely unfettered use, in the same spirit as the Python license. Unfortunately, the Python license cannot really be used to refer to anything other than Python itself. As a compromise, we chose to use the modified Berkeley license, which is considered the most liberal of licenses. ... and then the license follows ... So, if the recipe is in the printed cookbook the licensing is clear (primarily you must retain the copyright notice). From hdante at gmail.com Sun Mar 30 07:48:59 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 04:48:59 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> Message-ID: <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> On Mar 30, 4:31 am, John Machin wrote: > On Mar 30, 3:58 pm, hdante wrote: > > > > > On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" > > > wrote: > > > Hello, > > > > I am having trouble writing the code to read a binary string. I would > > > like to extract the values for use in a calculation. > > > > Any help would be great. > > > I'm too lazy to debug your binary string, but I suggest that you > > completely throw away the binary file and restart with a database or > > structured text. See, for example: > > > http://pyyaml.org/wiki/PyYAML > > > If you have some legacy binary file that you need to process, try > > creating a C program that freads the binary file and printfs a text > > equivalent. > > ... and that couldn't be done faster and better in Python?? No. A C struct is done faster and better than python (thus, the correctness check is faster in C). Also, chances are high that there's already an include file with the binary structure. From fhaxbox66 at googlemail.com Mon Mar 10 05:53:47 2008 From: fhaxbox66 at googlemail.com (fhaxbox66 at googlemail.com) Date: Mon, 10 Mar 2008 02:53:47 -0700 (PDT) Subject: Hyphenation with PyHyphen - public mailing list now online Message-ID: <2baffb86-8f38-46a3-9452-cbcece8813f5@60g2000hsy.googlegroups.com> Hi, there is now a public mailing list open to anyone who is interested in discussing issues concerning PyHyphen. Join the list at http://groups.google.com/group/pyhyphen, or visit the project home page at http://pyhyphen.googlecode.com to get the latest sources via Subversion. Regards Leo From gregory.bronner at lehman.com Fri Mar 14 10:45:06 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 14 Mar 2008 10:45:06 -0400 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD29B6@nypcmg1exms318.leh.lbcorp.lehman.com> This is not entirely true: Symptoms of increasing memory usage are either because a) you are keeping too much data around in user accessable memory (likely) b) you are creating self-referential structures that are not garbage collected (also likely) c) You have memory leaks in underlying C extension modules. For category a), you are on your own. For category b), you can use various methods in the gc module to print out everything that is still 'live'. You can also recompile python to build a list of all objects that are still live. For category c), a tool like valgrind or purify often helps. Create a simple example rather than trying to run it on your whole application. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Friday, March 14, 2008 10:16 AM To: python-list at python.org Subject: Re: Urgent : How to do memory leaks detection in python ? 2008/3/14, Pradeep Rai < >: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep Python doesn't have memory leaks. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fdrake at acm.org Sun Mar 2 19:43:33 2008 From: fdrake at acm.org (Fred Drake) Date: Sun, 2 Mar 2008 19:43:33 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <47CB168A.103@v.loewis.de> References: <47CB168A.103@v.loewis.de> Message-ID: <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> On Mar 2, 2008, at 4:05 PM, Martin v. L?wis wrote: > Assuming no major problems crop up, a final release of Python 2.4.4 > will > follow in about a week's time. I do suppose you mean 2.4.5. 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include - DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o ./Modules/posixmodule.c: In function ?posix_setpgrp?: ./Modules/posixmodule.c:3145: error: too few arguments to function ?setpgrp? make: *** [Modules/posixmodule.o] Error 1 I can only presume I'm doing something wrong at this point, since I don't consider myself a Mac OS X developer. -Fred -- Fred Drake From dteslenko at gmail.com Wed Mar 5 09:55:59 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 5 Mar 2008 17:55:59 +0300 Subject: draining pipes simultaneously In-Reply-To: References: Message-ID: <91325fec0803050655i69603477s1aff2986022daba7@mail.gmail.com> On Wed, Mar 5, 2008 at 3:39 PM, wrote: > time.sleep() pauses ony the thread that executes it, not the > others. And queue objects can hold large amount of data (if you have > the RAM), > so unless your subprocess is outputting data very fast, you should not > have data loss. > Anyway, if it works for you ... :-) After some testing I'll agree :) Without time.sleep() in main thread python eats up all aviable processor time From deets at nospam.web.de Sat Mar 1 12:13:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 18:13:59 +0100 Subject: at-exit-thread In-Reply-To: <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> References: <62r68tF220j59U1@mid.uni-berlin.de> <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> Message-ID: <62th6qF24pafdU1@mid.uni-berlin.de> castironpi at gmail.com schrieb: > On Feb 29, 1:55 pm, "Diez B. Roggisch" wrote: >> castiro... at gmail.com schrieb: >> >>> The Python main interpreter has an at-exit list of callables, which >>> are called when the interpreter exits. Can threads have one? What's >>> involved, or is the best way merely to subclass Thread? >> Is that some sort of trick-question? >> >> class MyThread(Thread): >> >> def run(self): >> while some_condition: >> do_something() >> do_something_after_the_thread_ends() >> >> The atexit stuff is for process-termination which is/may be induced by >> external signals - which is the reason why these callbacks extist. >> Threads don't have that, thus no need. > > That depends. If a thread adds an object it creates to a nonlocal > collection, such as a class-static set, does it have to maintain a > list of all such objects, just to get the right ones destroyed on > completion? Processes destroy their garbage hassle-free; how can > threads? And don't forget Thread.run( self ) in the example, if > anyone ever wants to make use of the 'target' keyword. That is both totally unrelated to the original question and plain wrong. Processes don't destroy their garbage themselves, not automagically or anything. If you _want_, you can put atexit-handlers that do clean up some stuff, but you'll have to equip them with the necessary context yourself. And a kill -9 won't run *anything* of your own code. The OS is eventually responsible for cleaning up. Diez From jasynwiener at gmail.com Sun Mar 16 13:05:03 2008 From: jasynwiener at gmail.com (jasonwiener) Date: Sun, 16 Mar 2008 10:05:03 -0700 (PDT) Subject: Strange problem with structs Linux vs. Mac Message-ID: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> Hi- I am having a VERY odd problem with unpacking right now. I'm reading data from a binary file and then using a very simple struct.unpack to get a long. Works fine on my MacBook, but when I push it to a Linux box,it acts differently and ends up pewking. here's the code snippet: fread.seek(0,0) tmp_rebuild = fread.read() fread.close() tmp_long = tmp_rebuild[0:4] print tmp_long.encode('hex') print repr(tmp_long) unpacked_long = struct.unpack('I', tmp_rebuild[0:4])[0] print 'unpacked_long: %s' % unpacked_long my MacBook produces: 1ec6f3b4 '\x1e\xc6\xf3\xb4' unpacked_long: 516354996 but on the linux box the same code produces: 1ec6f3b4 '\x1e\xc6\xf3\xb4' unpacked_long: 3035874846 the data looks to be the same, but the unpacking seems to treat it differently. Has anyone an idea of why this happens??? Thanks- J. From grahn+nntp at snipabacken.se Sun Mar 30 17:39:46 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 21:39:46 GMT Subject: Pexpect question. References: Message-ID: On Fri, 28 Mar 2008 08:12:36 -0700 (PDT), Paul Lemelle wrote: > I am trying separate a script that users pexpect into > various functions within the same expect session. The > problem is that the function does not return control > back Main. I do not understand what that sentence means. > Any insight into this issue would be > greatly appreciated. Below is sample code of the > problem. First, what is the purpose of this program? It seems to be a more tedious way to get an ssh login to some Unix host. Ssh can be configured to do many things; maybe you do not need Python at all? Second, it will fail as soon as you use the undefined object 'chk'. Third, if "not return control back Main" means "sshcon() does not return", then it is by design. You call go.interact(), which hands over control to the user until he types an escape sequence. See the pexpect documentation. Fourth, sshcon() does not handle the full dialogue ssh can give you. If you get "are you sure you want to connect" etc, you will hang until pexpect.TIMEOUT is thrown. I have reformatted the source code to be more readable: > import pexpect > > def sshcon(host, password): > go = pexpect.spawn ('/usr/bin/ssh -l root %s ' % host) > go.expect ('Password: ') > go.sendline (password) > go.interact() > > #get node info for both clusters. > C1_node = raw_input("Enter the ip address for node on cluster 1: ") > C1_pass = raw_input("Enter the password for the node on cluster 1: ") > > sshcon(C1_node, C1_pass) > > #go to the path > chk.expect('# ') > chk.sendline('ls') > > chk.interact() /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From abli at freemail.hu Sat Mar 29 03:42:32 2008 From: abli at freemail.hu (Daniel Abel) Date: Sat, 29 Mar 2008 00:42:32 -0700 (PDT) Subject: Using unittest for benchmarking / speed improvements Message-ID: Hi! As everyone knows, using unittests to monitor and improve the correctness of code is really handy. Is there a good system for using unittests to monitor / improve the _speed_ of code? I.e. I would like a system which every time when running a test, also measures the time the test took, and stores it in a file somewhere. (For example, stores date&time, svn revision, and the time the test took) Then, the programmer can plot that in gnuplot / etc, and see whether the speed of the code is improving or not, and also compare different tests to each other (when comparing the speed of different implementations). Also, svn revisions could be labelled with svn checkin comments, so that one can easily associate any improvement / regression with the summary of the change. I was thinking about something built on top of nose, and hoping someone has already created such a thing. (After all, 'benchmark before optimize' and similar are often repeated; such a system seems really necessary for doing that systematically.) I found http://renesd.blogspot.com/2007/08/timing-and-unittests-graphing-speed.html which talks about this idea, and the stopwatch plugin at: http://darcs.idyll.org/~t/projects/pinocchio/doc/#stopwatch-selecting-tests-based-on-execution-time which can measure the time (and would be the easies to extend to store the information I would need) and also the profile nose plugin (included in the nose package) can measure how time is spent _inside_ the test. (which is also handy, but I would only need unittest-level timing, i.e. not as granular as profile creates.) So, is there such a complete framework (i.e. which can compare speed across revisions) or do I have to hack one together myself? (And would others be interested in it?) Thanks in advance, Daniel Abel From 42flicks at gmail.com Tue Mar 4 04:14:38 2008 From: 42flicks at gmail.com (Mike D) Date: Tue, 4 Mar 2008 22:14:38 +1300 Subject: Trouble using XML Reader In-Reply-To: <2b54d4370803030059s722ed808j9ddd7512ed50eea4@mail.gmail.com> References: <2b54d4370803030059s722ed808j9ddd7512ed50eea4@mail.gmail.com> Message-ID: <2b54d4370803040114h3b17b1d4ke487acf53d77d962@mail.gmail.com> On 3/3/08, Mike D <42flicks at gmail.com> wrote: > > Hello, > > I'm using XML Reader (xml.sax.xmlreader.XMLReader) to create an rss > reader. > > I can parse the file but am unsure how to extract the elements I require. > For example: For each element I want the title and description. > > I have some stub code; I want to create a list of objects which include a > title and description. > > I have the following code (a bit hacked up): > > import sys > from xml.sax import make_parser > from xml.sax import handler > > class rssObject(object): > objectList=[] > def addObject(self,object): > rssObject.objectList.append(object) > > class rssObjectDetail(object): > title = "" > content = "" > > > class SimpleHandler(handler.ContentHandler): > def startElement(self,name,attrs): > print name > > def endElement(self,name): > print name > > def characters(self,data): > print data > > > class SimpleDTDHandler(handler.DTDHandler): > def notationDecl(self,name,publicid,systemid): > print "Notation: " , name, publicid, systemid > > def unparsedEntityDecl(self,name,publicid,systemid): > print "UnparsedEntity: " , name, publicid, systemid, ndata > > p= make_parser() > c = SimpleHandler() > p.setContentHandler(c) > p.setDTDHandler(SimpleDTDHandler()) > p.parse('topstories.xml') > > And am using this xml file: > > > > > Stuff.co.nz - Top Stories > http://www.stuff.co.nz > Top Stories from Stuff.co.nz. New Zealand, world, sport, > business & entertainment news on Stuff.co.nz. > en-nz > Fairfax New Zealand Ltd. > 30 > > /static/images/logo.gif > Stuff News > http://www.stuff.co.nz > > > > Prince Harry 'wants to live in Africa' > http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303 > > For Prince Harry it must be the ultimate dark irony: to be in > such a privileged position and have so much opportunity, and yet be unable > to fulfil a dream of fighting for the motherland. > EDMUND TADROS > stuff.co.nz/4423924 > Mon, 03 Mar 2008 00:44:00 GMT > > > > > > Is there something I'm missing? I can't figure out how to correctly > interpret the document using the SAX parser. I'm sure I;'m missing something > obvious :) > > Any tips or advice would be appreciated! Also advice on correctly > implementing what I want to achieve would be appreciated as using > objectList=[] in the ContentHandler seems like a hack. > > Thanks! > My mistake, The provided example is a SAX object, which can be parsed with DOM manipulation. I'll be able to do it now :) Oh, I also posted a hacked up implementation, I understand my classes look awful! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Fri Mar 7 17:10:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 7 Mar 2008 14:10:03 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: On Mar 7, 4:08 pm, shak... at gmail.com wrote: > I'm new to python and I was wondering if there are any intelligent > date/time parsing modules out there. I've looked at strptime (or > whichever it is) and mxDateTime from the eGenix package. I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. > > So are there any modules that allow for that kind of parsing? There's the dateutil module that's a fancy wrapper for the datetime module. The author's site has lots of examples as well as the source: http://labix.org/python-dateutil I use it quite a bit. HTH Mike From jameswhetstone at comcast.net Sat Mar 22 16:06:53 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Sat, 22 Mar 2008 13:06:53 -0700 Subject: How to use boost.python to wrap a class with a pure virtual function that has a 'void *' argument Message-ID: As the subject implies, I'm having trouble wrapping a C++ class that looks like this: struct A { virtual void handleMessage(void *message)=0; }; To wrap this class, I've written the following code: struct AWrapper : A, wrapper { void handleMessage(void *message) { this->get_override("handleMessage")(message); } }; class_("A") .def("handleMessage", pure_virtual(&A::handleMessage)) ; My python test code looks like this: import APackage class aclass(APackage.A): def handleMessage(msg) : print msg But this code crashes when the handleMessage function is called in python (I think) because 'void *' cannot be marshalled. Is there some way around this? Also, since the void* object is intended to be "zero copy", I should probably convert the void * to a PyObject first and re-write my handleMessage to look like this: void handleMessage(void *message) { int size = getMessageSize(message); PyObject *obj = PyBuffer_FromReadWriteMemory(message, size); this->get_override("handleMessage")(obj); } Has anyone done this type of thing? I'm writing this code using MS Visual Studio 8 and if anyone can help, it would *very* appreciated. Thanks! James From metalzong at 163.com Sun Mar 9 10:34:03 2008 From: metalzong at 163.com (Metal Zong) Date: Sun, 9 Mar 2008 22:34:03 +0800 Subject: is operator Message-ID: <004801c881f2$a04081f0$0b020b0a@nb1011> The operator is and is not test for object identity: x is y is true if and only if x and y are the same objects. >>> x = 1 >>> y = 1 >>> x is y True Is this right? Why? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From guidovb1 at invalid Sat Mar 15 17:50:45 2008 From: guidovb1 at invalid (Guido van Brakel) Date: Sat, 15 Mar 2008 22:50:45 +0100 Subject: Convert int to float Message-ID: <47dc4396$0$14348$e4fe514c@news.xs4all.nl> Hello I have this now: > def gem(a): > g = sum(a) / len(a) > return g > print gem([1,2,3,4]) > print gem([1,10,100,1000]) > print gem([1,-2,3,-4,5]) It now gives a int, but I would like to see floats. How can I integrate that into the function? Regards, -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- From __peter__ at web.de Mon Mar 3 05:43:04 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Mar 2008 11:43:04 +0100 Subject: write float to Excel with pyExcelerator write References: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> Message-ID: Cyril.Liu wrote: > I use pyExcelerator to generat Excel files in my project. it works good > before I found this bug: > run this code: > > from pyExcelerator import * > wb = Workbook() > ws = wb.add_sheet("sheet") > for i in xrange(1): > ws.write(i,0, 10474224.6) > wb.save(r'd:\error_float.xls') > > open d:\error_float.xls with M$ Excle you'll find the number in the cell > is -263193.64 not 10474224.6 > > > why? some body help me please. It's probably a bug in pyExcelerator: http://sourceforge.net/tracker/index.php?func=detail&aid=1596642&group_id=134081&atid=730643 There's a patch by John Machin, http://sourceforge.net/tracker/index.php?func=detail&aid=1618443&group_id=134081&atid=730645 and the problem should be fixed in subversion. Peter From Robert.Bossy at jouy.inra.fr Tue Mar 11 10:10:30 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 11 Mar 2008 15:10:30 +0100 Subject: difference b/t dictionary{} and anydbm - they seem the same In-Reply-To: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> Message-ID: <47D692D6.9090003@jouy.inra.fr> davidj411 wrote: > anydbm and dictionary{} seem like they both have a single key and key > value. > Can't you put more information into a DBM file or link tables? I just > don't see the benefit except for the persistent storage. Except for the persistent storage, that insignificant feature... ;) Well I guess that persistent storage must be the reason some people use anydbm sometimes. If you want keys and values of any type (not just strings) and persistent storage, you can use builtin dicts then pickle them. Cheers, RB From rpnabar at gmail.com Tue Mar 25 05:46:57 2008 From: rpnabar at gmail.com (Rahul) Date: Tue, 25 Mar 2008 02:46:57 -0700 (PDT) Subject: importing a csv file as a Numeric array Message-ID: What's a good way of importing a csv text file of floats into a Numeric array? I tried the csv module and it seems to work well so long as I've ints. Does anyone have any suggestions / snippets that work to import a csv file of floats into a Numeric array? -Rahul From hajducko at gmail.com Fri Mar 28 04:16:42 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Fri, 28 Mar 2008 01:16:42 -0700 (PDT) Subject: Plugins accessing parent state Message-ID: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> Does anyone have some design ideas ( or can point me at the right design pattern, because I can't find it. ) for having a plugin being able to access a parent's state? For example, let's say I have a class that receives some commands. When it gets a command, it checks which of the registered plugins deals with that command and passes the details of the command off to that plugin. So I'd end up with something like.. result = plugin.do(msg_details) Now, I want to write a plugin called "help" that loops through all the registered plugins and prints out their doc strings. If all my plugin is getting is the msg details, how is it supposed to get the list of available plugins from the calling class? Or, for instance, let's say my class loads a configuration file that lists a set of admins who can enter commands. I want the plugins, if they so choose, to be able to test if the msg came from an admin, but again, I'm not passing the admin list into every plugin, it's just in my calling class. I could make the plugin specify an attribute for itself, like "admin_only" and test for that before I pass the command but what if certain parts of the plugin are to be restricted and others aren't, based on the details of the command sent? Is this as simple as just passing the instance of my class to each plugin? It doesn't seem like the proper thing to do, because now the plugin class has the capability of accessing the whole bot's interface. I realize that this is all just theory but I'd appreciate any points in the right direction. Thanks. s From castironpi at gmail.com Thu Mar 6 11:55:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 08:55:28 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <5oQzj.61239$Pv2.45450@newssvr23.news.prodigy.net> Message-ID: On Mar 6, 5:16?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > Bryan Olson wrote: > >> How can we efficiently implement an abstract data type, call it > >> 'DoubleDict', where the state of a DoubleDict is a binary > >> relation, that is, a set of pairs (x, y); and the operations on > >> a DoubleDict are those on a Python set, plus: > > >> ? ? ?find_by_first(self, x): ?return [y where (x, y) in DoubleDict] > > >> ? ? ?find_by_second(self, y): ?return [x where (x, y) in DoubleDict] > > It gets hairier if you have an element that isn't a first or second > > necessarily. > > > ? ? ? find_by_other(self, x): return [y where (x, y) in DoubleDict or > > (y, x) in DoubleDict] > > Do you need all three find_by's, or are the pairs actually > unordered, so you just need to find partners? Are the relations > many-to-many, and if so do you want duplicates removed? > > As programming exercises, the variants are all reasonable and > possibly interesting. I was just trying to answer the call to > nail down the problem statement. You've helped me nail down the problem in my post. It was that I was trying to ask two questions at once. (He had at -least- one question!). The first was from an old piece of code I wrote that simply wanted to know what the object that's storing the combination of A and B was, so frozenset([A,B]) works perfectly, and I'm satisfied as for that one. But the second one, which was interefering with my own thoughts, was another one. The company was selling multiple products at multiple sites. Softdrink A at store 1, softdrink B at store 1, softdrink B at store 2. My 'add' operation, 'say store N sold softdrink S' always had two lines and I really hated it. It worked, of course, but still. I felt like it was a stain. I was asking if anyone knows how to tie it, but it was kind of intimidating seeing how the implementation worked already. > Do you need all three find_by's, or are the pairs actually > unordered, so you just need to find partners? Are the relations > many-to-many, and if so do you want duplicates removed? The first one was, find the information I already have about a partnership. > As programming exercises, the variants are all reasonable and > possibly interesting. I was just trying to answer the call to > nail down the problem statement. Which is now something I can do. Actually, there's another data structure I was working on (a year ago now) that's tangentially related, so if you guys want me to hold off on that one til you or I is satisfied on the company-product map, I will! Otherwise, I'll just post it here and leave it to you. (Knowing myself, something tells me I'll try to formulate it later on today regardless. Heh heh heh. If that's not the most virtuous way to ask for help, then I might have inherited from TroubleMaker at some point up the line.) From arkanes at gmail.com Tue Mar 11 12:22:05 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 11 Mar 2008 11:22:05 -0500 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: <47D6ACF0.5060300@behnel.de> References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> <47D6ACF0.5060300@behnel.de> Message-ID: <4866bea60803110922v53d71e0el65a68c4a9fb1edc@mail.gmail.com> On Tue, Mar 11, 2008 at 11:01 AM, Stefan Behnel wrote: > Sion Arrowsmith wrote: > > And before you blame wx* for crashes: what platform was this on? > > Because my experience was that wx on GTK was significantly more prone > > to glitches than on Windows (through to wxglade being unusably crashy) > > -- if the underlying toolkit has problems, that's going to be > > reflected in wx. > > :) Interesting. This was actually on GTK. Although I would still blame at > least the wxWidgets-GTK bindings here. I never had any problems with GTK in my > life. Gtk is much more finicky than windows about the timingof when you can and cannot use certain functions. wxPython has checks in place for many of these functions so you get an exception instead of a crash, but not everything is safe (and of course in the past even fewer things were). In particular, you need to have a wxApp object safely constructed before you can use almost any gui object, which is not the case under Windows. wx makes the attempt to make correct code work correctly on platforms, but doesn't necessarily guarantee that incorrect code fails the same (or at all) on all platforms. This is an unavoidable compromise due to the nature of a layering toolkit like this, although figuring out what "correct code" actually is can take some experience. > > > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at microcorp.co.za Sun Mar 30 10:55:50 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Mar 2008 16:55:50 +0200 Subject: Serial port error statistics - any comparable data? Message-ID: <002f01c89276$40bec720$03000080@hendrik> On Sunday 30 March 2008 12:19:58 Bjoern Schliessmann wrote: > Diez B. Roggisch wrote: > > if you have the chance, try & attach a machine with legacy rs232 > > port, and see if the errors still remain. > > Additionally, what kind of buffers does your device have? I'm using > pyserial to control a very "sensitive" device with nuttily > implemented buffering strategy. It has a "fast" and a "slow" buffer > which are filled in order, and no signalling to the outside sender > on how full they are. If the fast buffer fills the slow buffer > kicks in and requires less transmission rate. That may be how > characters could be lost with you. > > Regards, > > > Bjoern That is a horrible device - have they not heard of RTS / CTS? or even XON / XOFF ? It is a wonder that you got that working without turning into an axe murderer. I don't think I could have. I have not been exactly forthcoming about the setup - the device in question sits on the LAN, so I connect to it via a TCP socket connection (in either client or server mode - seems to make no difference) . On the other side of the device, there is a serial port, and another PC is connected to the RS-232 side. This is the PC that runs a simple echo script that makes the occasional error, on its receive - I can see this because the transmission is paused when I see an error, and the two strings are identical on the two machines. As I mentioned in my reply to Diez and Castironpi - its not the device that is making the errors, as proved by a simple loopback. Another interesting statistic is that the number of lines "in flight" on the round trip machine1 > xport > machine2 > xport > machine 1 due to buffering varies between about 4 and about 26. So much for using it for real time control... - Hendrik From nospam at nospam.com Tue Mar 11 06:18:35 2008 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 11 Mar 2008 11:18:35 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: On Mon, 10 Mar 2008 22:17:16 -0700 (PDT), Frank Millman wrote: >I do not know if this helps, but here is an extract from a recent post >to the wxPython mailing list from Robin Dunn, the main developer of >wxPython - I'll take a look. Thanks for the info. From pradiprai at gmail.com Mon Mar 31 06:47:40 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 16:17:40 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: -On [20080331 12:29], Pradeep Rai (pradiprai at gmail.com) wrote: >I have upgraded python v2.5.2 from python v2.4.3. The upgradation >results into following error: "Python C API version mismatch for module >dbi: This Python has API version 1013, module dbi has version 1012." Did you copy everything from site-packages of the old one to the new one? -- Jeroen Ruigrok van der Werven / asmodai CF[ EtbN @ f EFF *http://www.in-nomine.org/* | * http://www.rangaku.org/* If you're afraid of dyin', then you're holding on. You see devils tearing your life away. But if you have made your peace, then the devils are really angels, freeing you from the earth... -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Mar 17 21:33:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 18:33:02 -0700 (PDT) Subject: how to create instances of classes without calling the constructor? References: <47df0816$0$6635$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <6187a66e-c2a4-42d8-83da-1cba072cf370@a23g2000hsc.googlegroups.com> On Mar 17, 7:08?pm, "Dominik Jain" wrote: > Hi! > > Does anyone know how an instance of a (new-style) class can be created > without having to call the constructor (and providing the arguments it > requires)? With old-style classes, this was possible using new.instance. > Surely there must be a simple way to do this with new-style classes, too -- ? > or else how does pickle manage? > > Best, > Dominik >>> class C: pass ... >>> object.__new__( C ) <__main__.C object at 0x00B5ED70> And for the record: >>> class C: ... def __init__( self ): ... print( 'in init' ) ... >>> C() in init <__main__.C object at 0x00B5ED90> >>> object.__new__( C ) <__main__.C object at 0x00B5EE30> >>> type( C.__name__, (), dict( C.__dict__ ) )() in init <__main__.C object at 0x00B5ED90> Which is kind of biza-a-r-rre. From vpalexander at gmail.com Sun Mar 9 05:42:01 2008 From: vpalexander at gmail.com (vpalexander at gmail.com) Date: Sun, 9 Mar 2008 01:42:01 -0800 (PST) Subject: gc question Message-ID: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> I keep seeing destructor calls in wx for ad hoc dialogs and wonder if this is required, and if so, why would normal gc flow not be good? def GetDir(self,Caption,DefaultDir): dlg = wx.DirDialog(None,Caption,style = 1,defaultPath = DefaultDir,pos = (10,10)) res = dlg.ShowModal() pck = dialog.GetPath() dlg.Destroy() if res == wx.ID_OK: return pck else: return '' I'd like to write it as: def GetDir(self,Caption,DefaultDir): dlg = wx.DirDialog(None,Caption,style = 1,defaultPath = DefaultDir,pos = (10,10)) if dlg.ShowModal() == wx.ID_OK: return dialog.GetPath() else: return '' # probably implied; del 2 more lines? ...and gc takes care of things once scope is exited? Or is wx more tricksome than that? From emailamit at gmail.com Mon Mar 31 16:24:53 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 13:24:53 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <89d34053-4b16-49df-9153-eb3625249ad4@u10g2000prn.googlegroups.com> <7cee8a91-ebcc-43d0-8a84-63eca2409dc7@s19g2000prg.googlegroups.com> Message-ID: <824e2386-1a91-4685-b827-d4de41a3afaf@c19g2000prf.googlegroups.com> On Mar 31, 11:45 am, John Henry wrote: > Not sure. I use it on windows. > > > I haven't looked at pyinstall.. Is it for linux? > > It appears so - according tohttp://www.pyinstaller.org/ Thanks! It does show support for Linux. The documentation says it works for python until version 2.4. I am using 2.5.1. Not sure if it will work seamlessly, but I will try. If anyone has experience to share on using pyinstaller on 2.5.1 or higher, please share. Amit From andrei.avk at gmail.com Thu Mar 13 02:34:44 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Wed, 12 Mar 2008 23:34:44 -0700 (PDT) Subject: a Roguelike in Python References: Message-ID: <67c263fd-0294-4885-bf0a-a6ecdbb62c68@m36g2000hse.googlegroups.com> On Mar 12, 8:25?am, Mdo... at gmail.com wrote: > Seeing the 7DRL start up recently, i wanted to see what one was made > of. Python is the language i'm most familiar with so i searched for > some code to look at, but i couldn't find any. Can anyone direct me to > the right place? > > I did some searching on what it would take to write a roguelike in > python and it looked like the curses module would work perfectly, but > it looks to me like it doesn't work in windows? I tried to import it > and it says 'No Module named _curses' > > Sorry if all this sounds a bit noobish, it's only cause i am. I made a very small basic roguelike, except that in it you control the monsters instead of the hero. It uses curses so no worky in windows. Here: http://silmarill.org/nodes/I,_monster_game.html I later modified this game to control the hero and sometimes to ask you multiple-choice questions from biology and other fields of knowledge, and based on your right/wrong answer it either makes a Hit for your HP or gives you a small reward. If there's interest i can post that updated game too. Both are kind of buggy though.. -ak From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 23:21:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 03:21:34 -0000 Subject: some path issues on windows References: Message-ID: <13urddulja4t7fa@corp.supernews.com> On Fri, 28 Mar 2008 22:31:07 -0400, Brad wrote: > When reading a file into a list that contains windows file paths like > this: > > c:\documents and settings\brad\desktop\added_software\asus\a.txt > > I get a list that contains paths that look like this: > > c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt What makes you think that there are doubled backslashes in the string? Look at this: >>> path = r'C:\docs\file.txt' # Single backslashes >>> path 'C:\\docs\\file.txt' >>> print path C:\docs\file.txt >>> len(path) 16 Despite how it looks, the backslashes are all singles, not doubles: >>> path[2] '\\' >>> len(path[2]) 1 When you display strings, by default special characters are escaped, including backslashes. (Otherwise, how could you tell whether the \f in the path meant backslash followed by f or a formfeed?) Python interprets backslashes as special when reading string literals, NOT when reading them from a file: >>> open('backslash.txt', 'w').write('docs\\files') >>> s = open('backslash.txt', 'r').read() >>> s 'docs\\files' >>> print s docs\files >>> len(s) 10 -- Steven From soistmann at gmail.com Sat Mar 22 17:34:31 2008 From: soistmann at gmail.com (bsoist) Date: Sat, 22 Mar 2008 14:34:31 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> On Mar 22, 12:40 pm, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. Absolutely. I love using Python in "the real world" but it is fantastic for beginning programmers. Python enforces good habits and presents many opportunities to discuss programming from an academic perspective. Why does Python not have a switch or until statement? Why are very common objects (stack, queue, linked list) not builtin? etc. I have seen 14 and 15 year old students who have never done any programming begin to write real object oriented programs after 60 hours or so of classroom instruction. From falk at green.rahul.net Tue Mar 25 10:58:51 2008 From: falk at green.rahul.net (Edward A. Falk) Date: Tue, 25 Mar 2008 14:58:51 +0000 (UTC) Subject: Does python hate cathy? References: Message-ID: In article , Patrick Mullen wrote: >Then again, I can count the number of times I have ever needed __del__ >with no fingers (never used it!). Still, quite interesting to >explore. I used it once, for an object that had a doubly-linked list. The __del__() method walked the list, setting all the elements' prev/next pointers to None to make sure the elements of the list would get garbage-collected. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Mar 22 19:58:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 22 Mar 2008 23:58:33 -0000 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> Message-ID: <13ub799o3opuo88@corp.supernews.com> On Sat, 22 Mar 2008 14:55:39 -0700, Zentrader wrote: >> No one meant to laugh at you. Your naivete was not obvious. FWIW, a >> sense of humor is a valuable possession in most Python-related >> conversations. > > Perhaps someone can explain how telling something like this to the OP, > who thinks this statement will work > if 'one' and 'two' in f: > is funny and not mean. Oh stop your whining. Nobody is making fun of anyone, or laughing at anyone, although I'm just about ready to start laughing at *you* for your completely unjustified conviction that people are being cruel. Bearophile made a clearly hypothetical comment using perfectly valid and understandable English. That you misunderstood it isn't anybody's fault except your own. Get over it, stop trying to blame others, and move on. You're not the victim here, and Bearophile isn't the bad guy. -- Steven From needin4mation at gmail.com Tue Mar 18 12:10:05 2008 From: needin4mation at gmail.com (jmDesktop) Date: Tue, 18 Mar 2008 09:10:05 -0700 (PDT) Subject: Need Help Starting Out Message-ID: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Hi, I would like to start using Python, but am unsure where to begin. I know how to look up a tutorial and learn the language, but not what all technologies to use. I saw references to plain Python, Django, and other things. I want to use it for web building with database access. What do I use for that? Does it matter what I use on the client side (mootools, or whatever)? My rational for using Python is because I am hoping it will allow me to better understand other python programs in other areas, not just web. I have used other languages for web apps for several years. Truth is that I always wanted to learn Python and have heard it was a good thing to know. Thank you. From koara at atlas.cz Fri Mar 7 10:15:56 2008 From: koara at atlas.cz (koara) Date: Fri, 7 Mar 2008 07:15:56 -0800 (PST) Subject: hidden built-in module References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> <63d32jF23f54eU1@mid.uni-berlin.de> Message-ID: <1517d379-1db9-4c1d-8dec-4dd5a38b9c13@o77g2000hsf.googlegroups.com> > You can only try and search the sys-path for the logging-module, using > > sys.prefix > > and then look for logging.py. Using > > __import__(path) > > you get a reference to that module. > > Diez Thank you Diez, that's the info i'd been looking for :-) So the answer is sys module + __import__ Cheers! From steve at holdenweb.com Tue Mar 4 11:09:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 11:09:54 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD7452.2020605@holdenweb.com> mmm wrote: > Oops I did make a mistake. The code I wanted to test should have been > > import copy > print 'Test 1' > pf= '?,?,?,?' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print sqlx1 > > print > print 'Test 2' > sqlx2= copy.copy(sqlx1) > sqlx3= sqlx1 > pf= '?,?,?, ****' > print 'sqlx1= ', sqlx1 > print 'sqlx2= ', sqlx2 > print 'sqlx3= ', sqlx2 > > and the results would > == output > Test group 1 > INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Test group 2 > sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Such that sqlx1 does to change with the re-assignment of 'pf' > And of course immutables such as strings are immutable. Got it now. You still aren't showing us the code you are actually running. Why can't you just paste it into your message? But anyway, you appear to have got the drift now. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mail at timgolden.me.uk Fri Mar 7 03:49:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Mar 2008 08:49:30 +0000 Subject: system32 directory In-Reply-To: <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: <47D1019A.8000200@timgolden.me.uk> Robert Dailey wrote: > On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden wrote: >> >> First thing to do when asking "How do I do X in Python under Windows?" >> is to stick -- python X -- into Google and you get, eg: >> >> >> http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html >> >> which suggests that the win32api module from the pywin32 modules has >> the function you need. >> >> >> And sure enough... >> >> >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import win32api >> >>> win32api.GetSystemDirectory () >> 'C:\\WINDOWS\\system32' >> >>> >> >> >> TJG >> > > I was aiming to figure out if the standard modules shipped with Python could > do this already before I started using 3rd party libraries. Thanks. Ah. Sorry. I'm sure you can call it via ctypes (built in from Python 2.5). But even if I'd realised that's what you'd wanted, I'd probably have given the original answer because pywin32 pretty much *is* standard library for any Python installation I do on Win32 :) TJG From bj_666 at gmx.net Mon Mar 31 02:50:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 06:50:08 GMT Subject: question References: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> Message-ID: <65bft0F2esfc1U2@mid.uni-berlin.de> On Sun, 30 Mar 2008 20:34:30 -0400, Steve Holden wrote: > castironpi at gmail.com wrote: >> Presume. Silence first, then a broken triad vamps. How long til you >> recognize it? One sec., i'll attach a binary. > > Good grief, is this idibot still around? > > [leaves c.l.py for another month] Oh come on, don't let you scare away so easily. Put him in the filter list of your news client. Ciao, Marc 'BlackJack' Rintsch From mensanator at aol.com Mon Mar 3 19:24:30 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 16:24:30 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> Message-ID: <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> On Mar 3, 4:53?pm, Carl Banks wrote: > On Mar 3, 4:47 pm, Mensanator wrote: > > > > > > > On Mar 3, 2:49 pm, Carl Banks wrote: > > > > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > Notice anything funny about the "random" choices? > > > > > import sympy > > > > import time > > > > import random > > > > > f = [i for i in sympy.primerange(1000,10000)] > > > > > for i in xrange(10): > > > > ? f1 = random.choice(f) > > > > ? print f1, > > > > ? f2 = random.choice(f) > > > > ? print f2, > > > > ? C = f1*f2 > > > > ? ff = None > > > > ? ff = sympy.factorint(C) > > > > ? print ff > > > > > ## ?7307 7243 [(7243, 1), (7307, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > > > As in, "they're NOT random". > > > > > The random number generator is broken by the sympy.factorint() > > > > function. > > > > > Random.choice() works ok if the factorint() function commented out. > > > > > ## ?6089 1811 None > > > > ## ?6449 1759 None > > > > ## ?9923 4639 None > > > > ## ?4013 4889 None > > > > ## ?4349 2029 None > > > > ## ?6703 8677 None > > > > ## ?1879 1867 None > > > > ## ?5153 5279 None > > > > ## ?2011 4937 None > > > > ## ?7253 5507 None > > > > > This makes sympy worse than worthless, as it f***s up other modules. > > > > Dude, relax. > > > > It's just a bug--probably sympy is messing with the internals of the > > > random number generator. ?It would be a simple fix. ?Instead of > > > b****ing about it, file a bug report. > > > I did. > > > > Or better yet, submit a patch. > > > I would if I knew what the problem was. > > > I posted it here because someone recommended it. > > I'm simply un-recommending it. Those who don't care > > needn't pay any attention. Those who do should be > > glad that faults are pointed out when found. > > 1. You can point out the faults of a program without insults and > vulgarity Did I insult someone? And "fuck" in the context I used it means "messes with". Now you know that the writer of that superbowl commercial for almonds wanted to say "Robert Goulet fucks with your stuff". But, due to censorship, changed it to "messes with". > > 2. You must be terribly difficult to please if one bug is enough to > recommend against a program as "worse than worthless" While we're on the subject of English, the word "worthless" means "has no value". So, a program that doesn't work would generally be "worthless". One that not only doesn't work but creates side effects that cause other programs to not work (which don't have bugs) would be "worse than worthless". I'm not hard to please at all. I'm planning a later report where I test sympy's factoring with that of the MIRACL library's factor.exe program. It too, has a serious bug (and I'm not a good enough C programmer to know how to fix it) but I have a Python based workaround even though the MIRACL library has no Python interface. But any mention I ever make of this program will mention this bug in case anyone wants to use it. > > 3. You must be terribly naive if you expect a freeware program with a > version number of 0.5.12 not to have bugs No, but I guess I'm naive thinking that when someone posts a link to such a program that he's recommending going and trying it out. That is why they're making it available, isn't it? For people to try out so they can get free testing? Aren't I doing my part? Should I just uninstall it and forget it? > > Carl Banks From miki.tebeka at gmail.com Wed Mar 5 10:51:09 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 5 Mar 2008 07:51:09 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> Message-ID: <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> Hello Rod, > I have a set of CGI scripts set up and in one page (which is stored in > an HTML file then printed via a python CGI) there is an image. However > the image never displays, can anyone recommend a way round this > problem? We need more information, can you post a code snippet? error page? ... My *guess* is that the web server don't know how to server the image (wrong path configuration?) HTH, -- Miki http://pythonwise.blogspot.com From kyosohma at gmail.com Wed Mar 19 17:24:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 14:24:13 -0700 (PDT) Subject: Is this valid ? References: Message-ID: <133ffcc3-c2bc-4ae8-a45d-cbdfb05d73e0@d21g2000prf.googlegroups.com> On Mar 19, 4:18 pm, Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > > thanks, > Stef Mientki It sure looks that way... See http://www.python.org/doc/2.3.5/ref/comparisons.html for more info. Mike From furkankuru at gmail.com Tue Mar 25 12:08:07 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 18:08:07 +0200 Subject: Creating dynamic objects with dynamic constructor args In-Reply-To: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> References: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> Message-ID: <3a4a8f930803250908l49de8e8dk7a0a96e19aa9728@mail.gmail.com> you can call a function with arglist like this: def dummy(a, b, c): print a + b, c args = [1, 2, "hello"] dummy(*args) On Tue, Mar 25, 2008 at 5:38 PM, wrote: > I'd like to create objects on the fly from a pointer to the class > using: instance = klass() But I need to be able to pass in variables > to the __init__ method. I can recover the arguments using the > inspect.argspec, but how do I call __init__ with a list of arguments > and have them unpacked to the argument list rather than passed as a > single object? > > ie. class T: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > argspec = inspect.argspec(T.__init__) > args = (1, 2) > > ??? how do you call T(args)? > > Thanks. > Greg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From userprogoogle-139 at yahoo.co.uk Sat Mar 8 14:40:57 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Sat, 8 Mar 2008 11:40:57 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> <88Yzj.19022$R84.2998@newssvr25.news.prodigy.net> Message-ID: <3d7543fc-49f3-4d43-a3b1-9ec3c5d9b762@p25g2000hsf.googlegroups.com> > Is the cgi script in the same directory? The user's browser looks > for the jpg relative to the URL it used to get the page, which in > the case of the CGI script is the path to the script, not the > path to the html file. No the CGI script is in a different folder, I could move everything to the same folder I guess. > If server logs are hard to get or read, try my runcgi.py script: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/550822 Thanks, I will try this. Rod From jura.grozni at gmail.com Thu Mar 13 10:48:00 2008 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Mar 2008 07:48:00 -0700 (PDT) Subject: wx and pil conversion Message-ID: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> A little problem. Can I directly show Pil objects "image.open("bla.jpg") in Wx or do I have to transform them. If I have to transofm them How can I do it. Pixel by pixel or is there somethin built in in pil or wx or python. pilj->wx and wx->pil. From castironpi at gmail.com Sun Mar 9 19:44:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 16:44:39 -0700 (PDT) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 2, 1:18?pm, castiro... at gmail.com wrote: > On Mar 2, 12:01?pm, John DeRosa wrote: > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > >Hi, > > > >Have you ever seen Beautiful Python code? > > >Zope? Django? Python standard lib? or else? > > > >Please tell me what code you think it's stunning. > > > Just about any Python code I look at. > > Decorators, with, and namedtuple. Oh yeah, and variable arguments and keyword dictionaries. From castironpi at gmail.com Mon Mar 17 21:43:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 18:43:45 -0700 (PDT) Subject: In regards to threads of today: Message-ID: <122e1aea-cb63-4454-a542-85c20699d986@m34g2000hsc.googlegroups.com> Speaking of the standards, anyone ever try to override a method in xmlrpclib.ServerProxy? Case in point, and it's on your computer. Tear it up & tell your manager. Class Transport isn't even documented, despite its being the second parameter to the initializer. The module is > 1000 lines long. 1000 lines? Then to boot, it "import _xmlrpclib"s. And is Python responsible for allowing it? Further, is it unsafe, more unsafe, or less than pickle? Is it any more dangerous to xmlrpclib.Binary a pickle, or just rpc one? "The description in this section doesn't cover specific customizations that you can employ to make the unpickling environment slightly safer from untrusted pickle data streams." "If this sounds like a hack, you're right." No. Just unpickle in a reduced context: exec( 'pickle.load(...)',{},{}) You could require a stats header about a pickle instead for security. Example of a malicious pickle lacking. From supheakmungkol.sarin at gmail.com Thu Mar 27 11:40:25 2008 From: supheakmungkol.sarin at gmail.com (mungkol) Date: Thu, 27 Mar 2008 08:40:25 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux Message-ID: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Dear all, I am a newbie to Python community. For my project, I tried to install Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but unsuccessful. It produced the following error: running install running build running build_ext building 'Stemmer' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ syslimits.h:7, from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ limits.h:11, from libstemmer_c/src_c/../runtime/header.h:2, from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: limits.h: No such file or directory error: command 'gcc' failed with exit status 1 Did anyone experience this before? Any comment/suggestion is highly appreciated. Thank you. Best regards, Supheakmungkol From fakeaddress at nowhere.org Thu Mar 6 06:16:11 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 03:16:11 -0800 Subject: Dual look-up on keys? In-Reply-To: References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <5oQzj.61239$Pv2.45450@newssvr23.news.prodigy.net> castironpi at gmail.com wrote: > Bryan Olson wrote: >> How can we efficiently implement an abstract data type, call it >> 'DoubleDict', where the state of a DoubleDict is a binary >> relation, that is, a set of pairs (x, y); and the operations on >> a DoubleDict are those on a Python set, plus: >> >> find_by_first(self, x): return [y where (x, y) in DoubleDict] >> >> find_by_second(self, y): return [x where (x, y) in DoubleDict] > It gets hairier if you have an element that isn't a first or second > necessarily. > > find_by_other(self, x): return [y where (x, y) in DoubleDict or > (y, x) in DoubleDict] Do you need all three find_by's, or are the pairs actually unordered, so you just need to find partners? Are the relations many-to-many, and if so do you want duplicates removed? As programming exercises, the variants are all reasonable and possibly interesting. I was just trying to answer the call to nail down the problem statement. -- --Bryan From myonov at gmail.com Mon Mar 24 07:38:50 2008 From: myonov at gmail.com (myonov at gmail.com) Date: Mon, 24 Mar 2008 04:38:50 -0700 (PDT) Subject: Disable resize button Message-ID: Hi! I need to disable resize button in Tkinter. I inherit the Frame class. Then in the constructor i make my buttons, labels, etc. Then I pack them and when move borders of the frame everything changes it's location and it looks really bad. How can I change that? That's my code: # -*- coding: cp1251 -*- import Tkinter class App(Tkinter.Frame): def click(self): pass def click2(self): pass def __init__(self, master=None): Tkinter.Frame.__init__(self, master, width = 700, height = 400,\ bg = "#999999") self.pack() # Buttons self.b1 = Tkinter.Button(self, text = u"?????? ?????",\ command=self.click, font = "Courier", \ fg = "red") self.b2 = Tkinter.Button(self, text = u"?????? ???????",\ command=self.click2, font = "Courier", \ fg = "red") self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = 0.75, rely = 0.4) # Labels self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ text = u"??????????", fg = "#ffffff",\ bg = "#999999") self.l1.place(x = 275, y = 10) # Text Control # self.txt = Tkinter.Text(self, bg = "#124456", ) # self.txt.pack() def main(): app = App() app.mainloop() if __name__ == "__main__": main() From gideon.smeding at gmail.com Wed Mar 5 07:47:15 2008 From: gideon.smeding at gmail.com (gideon) Date: Wed, 5 Mar 2008 04:47:15 -0800 (PST) Subject: documenting formal operational semantics of Python Message-ID: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Hi Everybody, In the context of a master's thesis I'm currently looking into Python's operational semantics. Even after extensive searching on the web, I have not found any formal model of Python. Therefore I am considering to write one myself. To make a more informed decision, I would like to ask you: What previous work has been done that I should be aware of? Currently I have found exactly nothing on python itself. There is some interesting work on other, related languages like Smalltalk. Which version of Python is the most interesting? Python 3.0, although it would be a moving target, seems promising. Because it will simplify the language in some aspects by ditching backwards compatibility (e.g. old style classes and coercion), the semantics will be more clean. Of course I will get, answers to many questions I did not ask. In fact, I would like you to vent your opinions on this matter. Thanks! From tkapoor at wscm.net Thu Mar 20 12:13:23 2008 From: tkapoor at wscm.net (Tarun Kapoor) Date: Thu, 20 Mar 2008 11:13:23 -0500 Subject: paramiko In-Reply-To: References: <50E86CD59FE0A544901EBA0802DC3208098FA4@wscmmail.wscm.corp> Message-ID: I have some code that uses paramiko, establishes an SFTP connection with a remote server and downloads some files. This code works perfect if run on a windows XP machine. However, I get an error in the "RandomPool" class. Anyone tried paramiko on a windows server box ? Thanks !! Tk -----Original Message----- From: Guilherme Polo [mailto:ggpolo at gmail.com] Sent: Wednesday, January 16, 2008 11:12 AM To: Tarun Kapoor; python-list at python.org Subject: Re: paramiko 2008/1/16, Tarun Kapoor : > > > > > I am using paramiko to do an SFTP file transfer... I was able to connect to > the remote server using an SFTP client I have just to make sure that > username and password are working.. This is the code. > > > > # now, connect and use paramiko Transport to negotiate SSH2 across the > connection > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.connect((hostname, port)) > > > > t = paramiko.Transport(sock) > > event = threading.Event() > > t.start_client(event) > > > > event.wait(15) > > > > if not t.is_active(): > > print 'SSH negotiation failed.' > > sys.exit(1) > > else: > > print "SSH negotiation sucessful" > > > > event.clear() > > > > t.auth_password(username=username, password=password,event=event) > > > > if not t.is_authenticated(): > > print "not authenticated" > > output: > > SSH negotiation successful > > not authenticated > > > > > > > > Tarun > > > > Waterstone Capital Management > > 2 Carlson Parkway, Suite 260 > > Plymouth, MN 55447 > > > > Direct: 952-697-4123 > > Cell: 612-205-2587 > Disclaimer This e-mail and any attachments is confidential and intended > solely for the use of the individual(s) to whom it is addressed. Any views > or opinions presented are solely those of the author and do not necessarily > represent those of Waterstone Capital Management, L.P and affiliates. If you > are not the intended recipient, be advised that you have received this > e-mail in error and that any use, dissemination, printing, forwarding or > copying of this email is strictly prohibited. Please contact the sender if > you have received this e-mail in error. You should also be aware that > e-mails are susceptible to interference and you should not assume that the > contents of this e-mail originated from the sender above or that they have > been accurately reproduced in their original form. Waterstone Capital > Management, L.P. and affiliates accepts no responsibility for information, > or errors or omissions in this e-mail or use or misuse thereof. If in doubt, > please verify the authenticity with the sender. > -- > http://mail.python.org/mailman/listinfo/python-list > You are missing an event.wait() after t.auth_password. Also, why are you passing this magic value "15" to event.wait() ? That parameter is passed to class _Verbose to indicate if debug messages should be displayed or not, so typical values would be 0/1 or False/True. -- -- Guilherme H. Polo Goncalves Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. From tjreedy at udel.edu Tue Mar 18 22:28:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:28:10 -0400 Subject: Interesting math problem References: Message-ID: "Jeff Schwab" wrote in message news:C6SdnWmXtYoncELanZ2dnUVZ_ubinZ2d at comcast.com... | Marc Christiansen wrote: | > This was my first thought, too. But tailcall optimisation wouldn't help | > here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets | > executed after the recursion. | | | def make_slope(distance, parts, L=()): | if parts == 0: | return L | | q, r = divmod(distance, parts) | | if r and parts % r: | q += 1 | | return make_slope(distance - q, parts - 1, (q,) + L) So mechanically rewrite (not tested) as def make_slope(distance, parts, L=()): if parts < 0: raise ValueError('do you want me to return?') #added while parts: q,r = divmod(distance, parts) if r and parts % r: q += 1 distance, parts, L = distance-q, parts-1, (q,) + L return L tjr From morse at edoug.org Fri Mar 14 10:37:32 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 14 Mar 2008 14:37:32 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Peter, Genius! You nailed it -- thanks! py2exe is apparently getting confused by the fact that packages "Numeric" and "numpy" both have files multiarray.pyd and umath.pyd. It copies just one of each -- from $PYTHONHOME/Lib/site-packages/numpy/core -- and puts both of them into the top-level of the created "dist" directory. Also, there are no such files as multiarray.pyc and umath.pyc in my python installation, but py2exe seems to create these (in the dist and dist/numpy/core directories) -- they are small (e.g., 526 bytes) and I'm guessing that they are stubs that simply point python to the matching .pyd that py2exe relocated. So, by using the --skip-archive option to py2exe (i.e., python setup.py py2exe --skip-archive) to create the dist and build directories, and then within the dist directory hierarchy removing all the occurrances of multiarray.pyc and umath.pyc, and then moving dist/multiarray.pyd and dist/umath.pyd to the dist/numpy/core directory, and finally by copying multiarray.pyd and umath.pyd from $PYTHONHOME/Lib/site-packages/Numeric to the dist directory, I am able to get my application to run correctly and as a standalone executable. HOORAH!!! Just for completeness and perhaps a bit of additional clarity, here's a limited directory listing of what the steps in the previous paragraph produce: morse> find dist | egrep "(multia|umath)" | xargs ls -l -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/multiarray.pyd -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/umath.pyd -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd morse> (This is still WinXP; I'm just using the Cygwin bash and fileutils here. Also, note that there are NO multiarray.pyc or umath.pyc files.) So, my next step will be to try to not use the --skip-archive option and then make these same modifications regarding multiarray.pyd and umath.pyd to the py2exe-generated library.zip file and see if I can get things running that way as well (and in so doing reduce my "dist" directory by about 10mg). I may also try creating a dist/Numeric subdirectory and moving dist/multiarray.pyd and dist/umath.pyd to this dist/Numeric subdirectory -- for the goal of more accurately mirroring the actual file/directory structure found in $PYTHONHOME/Lib/site-packages. Again, thanks to everyone for their assistance, esp. Harald and Peter. Is this something I should pursue getting the py2exe folks to fix / work with them on fixing? In investigating this issue, I noted that a lot of other py2exe problems seem to revolve around confusions when duplicate files exist in different modules. I wouldn't thinking that getting py2exe to pay better attention to the containing modules when building it's dependency tree would be that difficult (or is it)? Cheers, Doug On Fri, 14 Mar 2008 12:39:23 +0100, Peter Otten <__peter__ at web.de> wrote: > Doug Morse wrote: > > > from multiarray import zeros > > import string > > > > typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', > > 'Float':'fd', 'Complex':'FD'} > > > > def _get_precisions(typecodes): > > ? ? lst = [] > > ? ? for t in typecodes: > > ? ? ? ? lst.append( (zeros( (1,), t ).itemsize()*8, t) ) ? <-- Line 18 > > ? ? return lst > > > > def _fill_table(typecodes, table={}): > > ? ? for key, value in typecodes.items(): > > ? ? ? ? table[key] = _get_precisions(value) > > ? ? return table > > > > _code_table = _fill_table(typecodes) > > > > I can't find any reason why line 18 is throwing a "data type not > > understood" error. ?It doesn't seem to have anything to do with dynamic > > importing, but I can't be sure. ?I would note that "zeros" is a built-in > > function found in the "python dll" multiarray.pyd (in the Numeric module > > directory). > > I don't know why, but your module seems to use numpy's multiarray instead of > Numeric's: > > >>> from multiarray import zeros > >>> zeros((1,), "1") > array([0], '1') > >>> from numpy.core.multiarray import zeros > >>> zeros((1,), "1") > Traceback (most recent call last): > File "", line 1, in > TypeError: data type not understood > > Peter From Lie.1296 at gmail.com Sat Mar 29 13:34:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 29 Mar 2008 10:34:35 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: On Mar 29, 5:55?pm, kwitt... at telenet.be wrote: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? > > I've written an article about it to try and save this nice "is not > equal" operator, located athttp://dewitters.koonsolo.com/python_neq.html > > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). All pretty clear hey? But now comes the catch, there exists an operator !=... but what does it mean? Well, that one is pretty easy, of course ! must be an operator of its own (in non-python languages meaning 'not'), and it resembles the fancy assignment statement <...snip...> When I started to learn python I came across an operator <>. What could it mean? Well, you don't have to think long about it. You're only reference are the < and > operators (with meanings the same as in mathematics or plain written language, any non programmer would understand this). So <> must mean "smaller or larger", or not-equals, no question about that. It couldn't possible be mistaken as an assignment operator. You just have to love a language that uses operators with clear and obvious meaning. You're forcing your argument too much, both != and <> are NOT standard mathematics operators -- the standard not-equal operator is >< -- and I can assure you that both != and <> won't be comprehensible to non- programmers. And I'm not sure if anyone could have mistaken != for assignment operator because they're used in completely different places (which is the reason why some languages can use the same operator for = (assignment) and == (comparison)). = is always used in a line by itself while != is always used in places where a 'condition' (a.k.a. 'expression') is required. The problem you stated may be a problem in C/C++ (if C/C++ do have both != and <>, fortunately they only have !=) because C/C++'s = (assignment) is an operator and operators always return a value but in Python = (assignment) is a statement and can't return a value so "if a = b:" always raise an error. Since != operator can only be used in places where a 'condition'/'expression' is required and never in a line by itself as a statement, it could never be mistaken as an assignment (which is a statement). The problem just don't exist in Python. From bearophileHUGS at lycos.com Sun Mar 16 10:26:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Mar 2008 07:26:11 -0700 (PDT) Subject: Advantage of the array module over lists? References: Message-ID: <4e072426-9215-489e-95c8-7a2385b6f94c@m34g2000hsc.googlegroups.com> Their efficiency is mostly regarding the space. I think they aren't much speed-efficient because they require many conversions from-to Python types. You can gain speed efficiency too (sometimes a LOT), in some situations, using array with Psyco. Another advantage of arrays (better called "vector"s, probably, so the name "array" can replace the "list" name used by the built in) is that they offer you a fixed size representation, so you know what you are working with. You can also take a look at the C version of the BList from cheeseshop, the autor has made them rather efficient for some kinds of operations. Bye, bearophile From carsten at uniqsys.com Sun Mar 16 02:54:03 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 16 Mar 2008 07:54:03 +0100 Subject: Unicode/UTF-8 confusion In-Reply-To: <007401c886db$d197b780$0200a8c0@TMSMAIN> References: <007401c886db$d197b780$0200a8c0@TMSMAIN> Message-ID: <1205650443.3198.41.camel@localhost.localdomain> On Sat, 2008-03-15 at 16:33 -0400, Tom Stambaugh wrote: > I appreciate the answers the community has provided, I think I need to add > some additional context. > [...] > var aSerializedObject = '%(jsonString)s'; > [...] > Once back in the browser, the loadObject method calls JSON.parse on > aSerializedObject, the json string we're discussing. > [...] > In order to successfully pass the escapes to the server, I already have to > double any each backslash. At the end of the day, it's easier -- and results > in better performance -- to convert each apostrophe to its unicode > equivalent, as I originally asked. > [...] It helps to ask for what you really need instead of asking for what you think you need. The above helps in that it outlines the source of your confusion. What you don't realize is that you're really doing two JSON-encode steps on the server side, and two JSON-decode steps on the client side. You have two decode steps because sticking a JSON-string on the right-hand side of a JavaScript expression will parse that string in the same way a JSON parser would. That's an implicit JSON-decode, and later you're explicitly decoding the result of that implicit decode. You also have two JSON-encode steps. One is an explicit encode step using simplejson.dumps, and the other is an implicit encode done by a semi-functional mishmash of double-backslashes and wrapping the string in apostrophes. As you have discovered, that doesn't work so well when the string already contains apostrophes. What I suggest you try is this: 1) Get rid of the apostrophes in '%(jsonString)s'. 2) Get rid of all the manual escaping. 2) Send the result of simplejson.dumps through a second simplejson.dumps step. Alternatively, you could try this: 1) Get rid of the apostrophes in '%(jsonString)s'. 2) Get rid of all the manual escaping. 2) Get rid of the JSON.parse step on the browser side. The first alternative accomplishes that you correctly JSON-encode twice and correctly JSON-decode twice. The second alternative accomplishes that you only encode and decode once. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From darrin_allen at japan.com Wed Mar 12 09:22:37 2008 From: darrin_allen at japan.com (t3chn0n3rd) Date: Wed, 12 Mar 2008 06:22:37 -0700 (PDT) Subject: computer shows Message-ID: are there any computer trade shows in your area? From gagsl-py2 at yahoo.com.ar Sat Mar 29 22:53:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 23:53:27 -0300 Subject: Buffer Overflow with Python 2.5 on Vista in import site References: Message-ID: En Sat, 29 Mar 2008 17:34:27 -0300, Fuzzyman escribi?: > A very odd error with Python 2.5 (both 2.5.1 and 2.5.2 from the > official msi installers and running on Vista under Parallels on the > Mac). It may be actually a Parallels issue - I've installed 2.5.1 on Vista (just once, on a real PC) and it worked fine. Anyway a better place for bug reports is bugs.python.org Mmm, maybe you should check all your .pth files - looks like this strange path comes from one of them. -- Gabriel Genellina From ilkeston at ntlworld.com Sun Mar 2 09:32:33 2008 From: ilkeston at ntlworld.com (Steve Turner) Date: Sun, 2 Mar 2008 14:32:33 -0000 Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: <6Uyyj.443513$901.351866@newsfet12.ams> Marc 'BlackJack' Rintsch wrote: : On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: : :: Apart from doing something like :: a=[0,0,0] :: b=[0,0,0] :: c=[0,0,0] :: d=[a,b,c] :: :: is there a better way of creating d?? : : a = [[0] * 3 for dummy in xrange(3)] Thanks, Marc. -- Steve From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 06:55:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 10:55:25 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> Message-ID: <13uusct7elou5e3@corp.supernews.com> On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > Second try: ... > Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with > each call. But it's the only way I could find, at least without changing > the code template used by timeit. Eeek. Talk about namespace pollution. Thanks for the effort, but if that's the only solution, I think the solution is worse than the problem! Perhaps it's time for me to take a different approach. Since I can't call timeit, and I can't inherit from it (same problem with state being shared between instances), perhaps I should write my own timer. import timeit import gc import itertools def timeit2(func, args=[], kwargs={}, it=None, timer=timeit.default_timer): if it is None: it = itertools.repeat(None, timeit.default_number) save_gc = gc.isenabled() gc.disable() try: start = timer() for counter in it: func(*args, **kwargs) end = timer() finally: if save_gc: gc.enable() return end - start Now to go and test it. -- Steven From Lie.1296 at gmail.com Sun Mar 2 01:33:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 1 Mar 2008 22:33:25 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> <13sd3rnokh1975d@corp.supernews.com> <13sedmcpcbhju6a@corp.supernews.com> Message-ID: On Feb 29, 5:33?am, Steven D'Aprano wrote: > > > And rightly rejected by many other programming languages, including > > > modern Python, not to mention calculators, real mathematics and > > > common sense. > > > Lost me again. ?I was not aware that calculators, real mathematics > > and common sense were programming languages. > > I didn't say they were. Please parse my sentence again. In the widest sense of the term computer and programming language, actually calculators and real mathematics are programming languages. Programming languages is a way to communicate problems with computer. Computer is anything that does computation (and that includes calculator and a room full of a bunch of people doing calculation with pencil and paper[1]). The expressions we write in a calculator is a (very limited) programming language, while mathematics conventions is a language to communicate a mathematician's problems with the computers[2] and other mathematicians [1] Actually the term computer was first used to refer to this bunch of people [2] The computers in this sense is people that does computation From P.G.Aravindh at gmail.com Tue Mar 25 22:31:05 2008 From: P.G.Aravindh at gmail.com (Santhosh1992) Date: Tue, 25 Mar 2008 19:31:05 -0700 (PDT) Subject: TUTORIALS ON PROGRAMMING LANGUAGES Message-ID: languages Have the complete details regarding programming languages. http://operatingsys.blogspot.com/ From castironpi at gmail.com Wed Mar 5 01:21:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 22:21:18 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: <9197a045-6ddb-4be5-baf7-800425246469@p73g2000hsd.googlegroups.com> On Mar 4, 10:57?pm, castiro... at gmail.com wrote: > > > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > > > > >> >> is it makes it. > > > > > >> >>>> from types import FunctionType, MethodType > > > > >> >>>> class A( FunctionType ): pass > > > > >> > ... > > > > >> > Traceback (most recent call last): > > > > >> > ? File "", line 1, in > > > > >> > TypeError: type 'function' is not an acceptable base type > > > > > >> Use delegation instead of inheritance. This class is almost ? > > > > >> indistinguishable from a true function (when used as a method): > > > If P gets, p gotcha. > > Notwithstanding. ?Now bar has a name. > Now func has it. > > from functools import wraps > class myfunction: > ? ? __slots__ = ('func','name') > ? ? # > ? ? def __init__(self, func): > ? ? ? @wraps( func ) > ? ? ? def f( *ar, **kws ): > ? ? ? ? ?return func( self, *ar, **kws ) > ? ? ? object.__setattr__(self, 'func', f) > ? ? ? object.__setattr__(self, 'name', None) Now: Where is partialobject.__get__, why is 'attribute "__get__" read- only', and for self.__get__= func.__get__, why is "'member_descriptor' object is not callable"? From paulgeeleher at gmail.com Mon Mar 10 13:42:24 2008 From: paulgeeleher at gmail.com (sophie_newbie) Date: Mon, 10 Mar 2008 10:42:24 -0700 (PDT) Subject: Keep a python script running after browser window closed References: Message-ID: On Mar 7, 4:33 pm, Mike Driscoll wrote: > On Mar 7, 10:28 am, sophie_newbie wrote: > > > Hi, > > > I have a cgi script that performs a very long computation that can > > take several hours to complete. Is there any smart way that I can keep > > this script running until it is finished (after the user has closed > > the browser) and email them with the results. The email bit isn't the > > problem, I just don't know how to keep the code running in the > > background. I'm sure there is a smart way to do this... > > > Thanks! > > You might have your cgi script use the subprocess module to open a > second script that does the long-running process. > > Mike Ya it looks like: import subprocess # spawn subprocess subprocess.Popen(["python", "spawn.py"]) Should do this job, where spawn.py is the script to do the job. Thanks. From fts2012 at gmail.com Fri Mar 7 01:17:33 2008 From: fts2012 at gmail.com (fts2012 at gmail.com) Date: Thu, 6 Mar 2008 22:17:33 -0800 (PST) Subject: the problem of import module Message-ID: <8db5d6fa-f582-4311-817d-17da26846a57@d21g2000prf.googlegroups.com> follow the dive into python ----------------------------------------------------------------- >>> import sys >>> sys.path >>> sys.path.append('E:\achieve\book\diveintopython-pdfzh-cn-5.4b\diveintopythonzh-cn-5.4b\py') ----------------------------------------------------------------- I append the filepath of <>'s examples into sys.path,but ----------------------------------------------------------------- >>> sys.path ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat- win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\ \site-packages', 'E:\x07chieve\x08ook\\diveintopython-pdfzh-cn-5.4b\ \diveintopythonzh-cn-5.4b\\py'] >>> import fileinfo#fileinfo is a module in the path Traceback (most recent call last): File "", line 1, in import fileinfo ImportError: No module named fileinfo ----------------------------------------------------------------- Can anyone tell me the reason of the above and how to add paths to python path except adding them in the enviroment path. Thanks. From gagsl-py2 at yahoo.com.ar Sun Mar 23 12:31:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 23 Mar 2008 13:31:24 -0300 Subject: pydoc References: Message-ID: En Sun, 23 Mar 2008 12:57:35 -0300, A Hutchison escribi?: > Any known reasons why pydoc no longer works? It gets confused by many timezone changes that occur this month around the world; pydoc tries hard to please all kind of users and tracking those locale changes isn't easy. Wait until April and it will resume working fine, I presume. In the meantime, perhaps if you post a more specific question someone could give a more specific answer. -- Gabriel Genellina From gargonx at gmail.com Wed Mar 12 01:17:47 2008 From: gargonx at gmail.com (gargonx) Date: Tue, 11 Mar 2008 22:17:47 -0700 (PDT) Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> <76ce374e-fa63-4885-8198-d2b383696a48@s8g2000prg.googlegroups.com> Message-ID: <19d15ab6-0a4f-4248-b28c-eeaeedf409e0@e6g2000prf.googlegroups.com> On Mar 12, 5:10 am, Frank Millman wrote: > gargonx wrote: > > Say i have the two methods: > > > def ReturnMethod(request, x): > > if request is True: > > return x > > else: print "No String for you...False!" > > > def SendMethod(request): > > xstring = "Some text" > > ReturnMethod(request, xstring) > > > SendMethod(True) > > > Why does ReturnMethod not return the string x? I do believe it is > > returning with a NoneType. > > Any help would be greatly obliged > > > Thanks, Josh > > ReturnMethod() is executed, but you do nothing with the result. > > Try one of the following - > > def SendMethod(request): > xstring = "Some text" > print ReturnMethod(request, xstring) > > def SendMethod(request): > xstring = "Some text" > return ReturnMethod(request, xstring) > > HTH > > Frank Millman Thanks Frank the latter worked for my purpose. From musiccomposition at gmail.com Mon Mar 24 22:51:02 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 24 Mar 2008 19:51:02 -0700 (PDT) Subject: Is IronPython real Python? References: Message-ID: <9afcb565-49a1-4fce-bb64-84614b5173bd@e60g2000hsh.googlegroups.com> On Mar 24, 12:00 pm, jmDesktop wrote: > I know that IronPython and CPython are different in that one does not > use the .net framework, but are they both really the same Python > language. From my basic understanding, it will depend on what the > programmer's goal is as to which of the two would be used, but I > didn't know if they were really the same language. CPython is main implementation. The other implementations, PyPy, Jython, and IronPython, are always playing catchup to CPython, so you can't expected the latest CPython features in all the implementations. From jason.scheirer at gmail.com Thu Mar 27 16:39:20 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 27 Mar 2008 13:39:20 -0700 (PDT) Subject: Time problem (again) References: Message-ID: <21f25058-bccb-4cfc-b7c0-b13d719bcb2e@m44g2000hsc.googlegroups.com> On Mar 27, 12:17 pm, "Fabio Durieux Lopes" wrote: > Hi, > > I'm recreating a date-time based on a string and I have a problem > when daylight savings time is set (I'm off by 1). So today I forced > my computer into daylight savings time and debugged it again, but > this time I noticed something strange. > > This is the documentation from python library reference section > 6.10: > > 6.10 time -- Time access and conversions > ... > daylight > Nonzero if a DST timezone is defined. > ... > > And this is what I debugged: > -> fileTimeInSecs = time.mktime(time.strptime(timeString, > "%Y%m%d%H%M")) > (Pdb) p timeString > '200803271643' > (Pdb) n> /home/salsa/Projects/TimBR_CDR/fileSync/ > > fileSynchronizer.py(50)passFilesOlderThan() > -> print time.daylight > (Pdb) > 0 > > See how 'print time.daylight' resulted in '0'? Shouldn't it be Non- > zero? Do I have to set something for it to use DST? > > Also, is this the right list to send questions? The Python datetime module's handling of time zones is completely, entirely deficient -- the tzinfo class is just a skeleton and therefore useless. Install something that will give you fully implemented time zones like at http://pytz.sourceforge.net/ and try again -- pulling a tzinfo from this module and doing datetime_instance.replace(tzinfo=tzinfo_object_for_timezone) on your datetime instance parsed from the string will result in far more predictable behavior and probably get everything behaving as you expect. From cito at online.de Sun Mar 2 15:58:31 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 02 Mar 2008 21:58:31 +0100 Subject: First post from a Python newbiw In-Reply-To: <62vrleF24ontgU2@mid.uni-berlin.de> References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch schrieb: > On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: > >> Apart from doing something like >> a=[0,0,0] >> b=[0,0,0] >> c=[0,0,0] >> d=[a,b,c] >> >> is there a better way of creating d?? > > a = [[0] * 3 for dummy in xrange(3)] Why not simply [[0]*3]*3 ? -- Christoph From commander_coder at hotmail.com Mon Mar 3 20:55:56 2008 From: commander_coder at hotmail.com (commander_coder at hotmail.com) Date: Mon, 3 Mar 2008 17:55:56 -0800 (PST) Subject: tools to install not in python tree? Message-ID: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Hello, I have some materials for a project that I am working on that I keep in a source code control system (svn now, but I'm experimenting with mercurial). I want to install these things from the repository, but not into site-packages/ as Distutils wants to do. For instance there are some administrative scripts I want to put in ~/ admin/ and some programs that I want in ~/public_html/ . I also want to run some post-install routines (for instance, reset the database tables on my development machine). So I'm looking for a tool to take things from a repository and install them into place. Something like: install_from_repository.py -version "1.2.7" if there is a bug in 1.2.7 that I need to work on. Some of the things that I am looking for are like what setup.py does (for instance, changing the #! line on scripts or having a convenient .cfg file). But as I understand it setup only targets installing below sys.prefix; is that right? I can write routines for myself but other people must need to do these things also and a tested solution is obviously better. Is there such a tool? Thanks for any help, Jim From grante at visi.com Sat Mar 8 14:31:47 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 08 Mar 2008 19:31:47 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> Message-ID: <13t5qd3slgt9nc0@corp.supernews.com> On 2008-03-08, castironpi at gmail.com wrote: > Does one side of this hold that there are no -good- comments? I wouldn't say there are _no_ good comments, but I would say that 90+% of the comments I've seen in my lifetime were bad. Most of them were bad to the extent that anybody new to the code would be best served by deleting them before trying to understand what was going on. I do think that a comment at the beginning of a function/module that describes its general purpose can be a good thing. A comment explaining a particularly opaque algorithm can be useful as well. What I really can't stand are the pointy-haired comment blocks at the beginnings of C/C++ functions that do things like tell you the name and return type of the function and list the names and types of the parameters. Gee, thanks. I never could have figured that out from looking at the source code itself. IMO, comments explaining what the parameters are used for usually indicates that the parameter names were poorly chosen. I'm also a bit baffled by people who put a comment at the top of every file that tells you what the filename is. I sometimes wonder how/where these files were created. All of the OSes I've ever used had a feature called a "filesystem" which kept track of info like the names of files. It must be a bitch-and-a-half to work on an computer that doesn't keep track of filenames and makes the user do it. When was the last time you thought to yourself: "Gee, I wonder what's the the name of that file over there? I guess I'd better open the file and look at the comment at the top to see what the filename is? -- Grant Edwards grante Yow! .. does your DRESSING at ROOM have enough ASPARAGUS? visi.com From castironpi at gmail.com Fri Mar 21 10:11:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 07:11:37 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> On Mar 21, 4:17?am, Bryan Olson wrote: > Arnaud Delobelle wrote: > > Bryan Olson wrote: > [...] > >> Arnaud Delobelle offered a good Wikipedia link, and for more background > >> look up "amortized analysis. > > > Hrvoje Niksic provided the link :). > > Oops, careless thread-following. Hrvoje Niksic it was. > > > I still think two unrelated > > things are being compared in this thread when people say that method A > > (using dictionaries / sets) is O(n) and method B (sorting the list) > > O(nlogn). > > > Isn't it the case that: > > > ? ? ? ? ?| Worst case | Average case > > ---------|------------|------------- > > Method A | O(n^2) ? ? | O(n) > > Method B | O(nlogn) ? | O(nlogn) > > > Which method is the best would then be determined by the distribution > > of the hash values of your data, and whether you want to have a > > guarantee the method will have a less-than-quadratic behaviour. > > If we exclude the case where an adversary is choosing the keys, the > chance of a seriously degenerate case in the hashing method is so > remote that we do should not worry about it. Those who insist on > ranking by worst-case behavior have probably abandoned Python long > ago, as it uses those hashed 'dict' things everywhere. Of course > they've also abandoned OS's with demand-paged virtual memory and > such. > > -- > --Bryan A collision sequence is not so rare. >>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] [1, 1, 1, 1, 1, 1, 1, 1] From dmmsoz at gmail.com Mon Mar 17 15:52:27 2008 From: dmmsoz at gmail.com (Dianne Marsh) Date: Mon, 17 Mar 2008 12:52:27 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: <83b2ca86-32bb-4bf4-b119-f8d593d4c9eb@p25g2000hsf.googlegroups.com> This was my first PyCon as well. I had heard glowing recommendations about the lightning talks (from Bruce) previously, and I was really looking forward to them. I, too, was disappointed. I help to organize a community based conference, and we have struggled with providing value for sponsors as well. I have some suggestions, which I will offer here and to PyCon organizers. This sounds similar to what one person described above, regarding how lightning talks were managed in '07. At CodeMash, we scheduled a daily slot for vendor sessions and clearly marked them as such. We were concerned that attendees would simply avoid the vendor sessions, which would backfire. To mitigate this risk, we strongly encouraged our vendors to do something "different" than a sales pitch for vendor sessions, asking them to consider providing something meaningful for the audience. Talks weren't reviewed; we just gave them a nudge when we discussed the vendor sessions with them. They were entitled to choose a pure sales pitch if they wanted to do so, but we definitely discouraged this activity. And the sponsors responded with some great talks, and expressed satisfaction in the entire process! The vendor sessions were well attended, and it was completely transparent that they WERE vendor sessions. I had been totally skeptical about providing vendor sessions ahead of time, yet even *I* was won over. Vendors WANT people to come to their sessions. Sometimes they, just like speakers, simply need a little nudge in recognizing what makes a compelling talk. In my opinion, other speakers suffered from not knowing what makes a compelling talk as well. I don't know what other talks were proposed, but those that were on the schedule were often disappointing because the speaker provided too much "background" and not enough "here's what's cool" for me. Those were the talks that I walked out of. I suffer from this same problem as a speaker and I'm trying to fix that myself. I hope that other speakers are interested in doing the same. As for the attitude that if you weren't involved with organizing Pycon, you can't complain about it, that's a bit unfair. Several people DID engage in the conference onsite, organizing Open Spaces discussions (Bruce included). I saw Bruce both suggesting Open Spaces talks and being recruited to convene them (and, in one case, even reconvene one that had taken place earlier). That's being involved in the process, and should not be discounted. Furthermore, in my experience, people don't usually complain about things that don't matter to them. It's important, IMO, to recognize that the complaints you see on this group seem to come from the heart, from a desire to see PyCon flourish and be a conference worth attending. I certainly feel that way, and I suspect that the vast majority of people who have offered constructive criticism here do as well. I'm bummed about the lightning talks at PyCon from 2008, but I have a lot of confidence based on what I have read here from Jacob and others, that things will be different in 2009. Thank you for listening to the community feedback. -- Dianne From deets at nospam.web.de Fri Mar 21 08:48:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Mar 2008 13:48:04 +0100 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: <64hp4bF2bhmtuU1@mid.uni-berlin.de> > I can see that Python and Javascript inheritance model is almost the > same. Both languages are dynamically typed. And it seems that using > "classes" in Python makes some things more complicated then it is > necessary (eg functions, methods and lambdas are differen beeing in > Python concept). Sorry, but that is utter nonsense. It begins with the fact that there is no "inheritance model" in Javascript. Or why does each JS-lib provide it's own version of an extend-function [1]? Which one has to grasp before really being able to use inheritance in JS. And of course everybody does it a bit different, including possible access to parent classes and such. Calling that an advantage is rather bold. And it continues with the abnomination the implicit "this" in Javascript is - e.g. MochiKit offers a bindThis-method to ensure that a method-call always gets the actual instance passed as this - something that can get "lost" when dealing with event-handling. Whereas python here offers the bound-method-concept. The only point you might have is the somwhat unfortunate distinction between lambda and function in python - but this is on a syntactical level only. Once created, you can use them as you like. I do like JS for what it is - but everybody who uses it in an OO-manner ends up inventing the same wheels Python already comes with. Diez [1] Just one example: http://docs.mootools.net/Class/Class.js From gherron at islandtraining.com Fri Mar 28 01:29:13 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Mar 2008 22:29:13 -0700 Subject: Getting back an Object In-Reply-To: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> References: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> Message-ID: <47EC8229.70703@islandtraining.com> David Anderson wrote: > Well, I've got a little problem, I have a list that contains objects > from the class C, then I use those objects.__str__ to generate a > ListCtrl, A wxPython widget that makes a list of strings and then you > can handle events when selected, and returns the string selcted, how > can I access the "parent" of that string? > I tried to search on the array like this: > def search(self, string): > for obj in self.list: > if string == obj.__str__: > return obj > return None > > But I always get None... What am I doing wrong? Once again, you are confused over the difference between a value and a function that, when called, returns a value. obj.__str__ is a function. If you call it like this, obj.__str__(), then you get a string. So your comparison should be if string == obj.__str__(): Slightly better would be to call str(obj) and let Python translate that into a call to __str__. But even better is to replace this rather bogus approach with something better. When you create an object, record its string representation in a dictionary to be used to recover the object when given a string later: That is, for each object obj do: objMap[str(obj)] = obj and later with the string in hand, do obj = objMap[string] One other word of warning. It is best to not use a variable named "string" as Python has a builtin type of that name which would become inaccessible if you redefine. Gary Herron From jzgoda at o2.usun.pl Tue Mar 25 09:50:03 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Mar 2008 14:50:03 +0100 Subject: sendmail should throw an exception but does not In-Reply-To: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> Message-ID: Clodoaldo napisa?(a): > I need to know if an email was refused for whatever reason, it makes > no difference. > > The email is sent to an email address that does not exist in a foreign > domain. I can see in the postfix log that the email was sent and > bounced with the error code 550. > > The problem is that sendmail should throw an exception but it does > not. And the returned dictionary is empty as if the email was > accepted. > > d = smtpserver.sendmail(sender, recipient, m.as_string()) > > I guess that the error code returned by the destination mail server is > not is not forwarded to the client by my mail server. Your local smtpd accepted the message for delivery, so everythong seems to be OK. Following communication takes place between mail servers, so your program has no possibility to know anything went wrong. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From castironpi at gmail.com Tue Mar 18 14:58:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 11:58:18 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: <80b7cd63-a6f3-4521-adb1-93b6faab307e@e39g2000hsf.googlegroups.com> On Mar 18, 8:51?am, Tim Golden wrote: > castiro... at gmail.com wrote: > >>> Can I allocate a second console window, so I can place certain output > >>> to that directly, and leave the original streams alone? ? > > I've rather lost track of what you're trying to do, but I would > second Gabriel's suggestion of the standard Windows method of > debug output: using OutputDebugString. There's an example here: > > http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugStrin... > > and it shouldn't be too hard to wrap it in a file-like > object for stderr-substitution use, say. > > Obviously there are 1,001 other ways of doing IPC but since this > one's ready-made you might as well use it. You can distinguish > between different processes' outputs by virtue of the PID which > is the first item on the mmap. > > TJG I want a handle to another window. Create B with a command. ___ ___ |A | |B | |___| |___| B.stdin (the stdin to B).write( '?' ) ___ ___ |A | |B? | |___| |___| A.stdout.write( '*' ) ___ ___ |A* | |B? | |___| |___| A big tease is good too. From palomurin at gmail.com Fri Mar 28 07:53:15 2008 From: palomurin at gmail.com (Pavol Murin) Date: Fri, 28 Mar 2008 12:53:15 +0100 Subject: simple web-server Message-ID: hello python users, could you point me to a very simple (single file is best) web-server? I want to serve a few web-forms and run some shell scripts when the forms are submitted. I might add Ajax later (this is not a requirement, if it only supports forms it's OK). Longer story: I would like to provide a web-page for customization of an application - it should run some shell commands as the user clicks around in the page and at the end write a configuration file. I had a look at the python wiki (http://wiki.python.org/moin/WebProgramming), where various web servers and frameworks are listed. The frameworks seem to heavy for such a simple task and BaseHTTPServer just seems to be too light. So I took a look at the web-servers listed: httpy had the last release 1,5 years ago, Medusa more than 5 years, Twisted seems to be able to do a lot, so probably not the simple thing I'm looking for. CherryPy looks promising, however it is still 89 files (including some that can be removed). If CGIHTTPServer is a good answer, could you point me to a good (nontrivial) example? thank you, muro From miki.tebeka at gmail.com Mon Mar 3 23:14:59 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 3 Mar 2008 20:14:59 -0800 (PST) Subject: 'normal' shell with curses References: <633s5lF24prinU1@mid.uni-berlin.de> Message-ID: <61c6832e-6897-476c-bcfc-448b7c4387df@d21g2000prf.googlegroups.com> Hello Michael, > I'm trying to print out text in color. As far as I know, curses is the > only way to do that (or not?). On unix, every XTerm compatible terminal will be able to display color using escape sequence. (Like the one you see in the output of 'grep --color') See the shameless plug in http://pythonwise.blogspot.com/2008/03/ansiprint.html HTH, -- Miki http://pythonwise.blogspot.com From http Sat Mar 1 14:32:56 2008 From: http (Paul Rubin) Date: 01 Mar 2008 11:32:56 -0800 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> Message-ID: <7x3ara9r4n.fsf@ruckus.brouhaha.com> Lie writes: > I see, but the same arguments still holds true: the second line have > an implicit side-effect of redefining x's type into Fractional type. > If I were the designer of the language, I'd leave x's type as it is > (as Num) and coerce x for current calculation only. Num in Haskell is not a type, it is a class of types, i.e. if all you know about x is that it is a Num, then its actual type is indeterminate. Types get inferred, they do not get coerced or "redefined". The compiler looks at expressions referring to x, to deduce what x's type actually is. If it is not possible to satisfy all constraints simultaneously, then the compiler reports an error. From gagsl-py2 at yahoo.com.ar Mon Mar 31 15:02:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 16:02:29 -0300 Subject: why does socket.makefile require non-blocking mode? References: <18907.75.55.199.5.1206983756.squirrel@webmail.sonic.net> Message-ID: En Mon, 31 Mar 2008 14:15:56 -0300, Forest escribi?: > My main concern is this: A brief look at the existing socket._fileobject > shows that its read() method calls recv() in a loop, appending to a > temporary buffer on each pass, and finally returning the buffer when > recv() gets no more data. It looks to me like a socket timeout exception > would cause that loop to exit without saving the data collected in > earlier > passes. In other words, data loss on recv() timeout. Just do it. Do the experiment; if there is data loss, you prove your point (if not, it doesn't prove that data loss could not happen). -- Gabriel Genellina From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 12:15:09 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 18:15:09 +0100 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: References: <47c93bb8$0$874$ba4acef3@news.orange.fr> Message-ID: <47c990b9$0$899$ba4acef3@news.orange.fr> Re! An exemple. With this script: a=123 b=456 d=a+b+c (note than 'c' is not defined). When I run, inside Pyscripter, the error-dialog is showed, and, one second after, PyScripter is closed. This problem is present since Python 2.5.2. I search, for know if it's a problem only on my computer, or a more general problem. Thanks by advance for your(s) answer(s). @-salutations -- Michel Claveau From MartinRinehart at gmail.com Wed Mar 26 11:44:07 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 26 Mar 2008 08:44:07 -0700 (PDT) Subject: Tkinter menus from keyboard References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: <3a7f4387-586a-4221-83a8-bce142d910b1@u10g2000prn.googlegroups.com> Guilherme Polo wrote: > Set the underline option to the index of the desired letter Elegant simplicity in the dropdowns. Thanks! Now, how about main menu underscores? From deets at nospam.web.de Mon Mar 31 07:00:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Mar 2008 13:00:56 +0200 Subject: Class Image.Image? References: Message-ID: <65buk3F2fi5osU1@mid.uni-berlin.de> W. Watson wrote: > I put a print statement in some Python code to determine the class > (__class__) of a variable and the result was Image.Image. Why not just > Image; otherwise, what's it telling me? Because it is the class Image in the module/package Image. Diez From piet at cs.uu.nl Wed Mar 12 07:20:25 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 12 Mar 2008 12:20:25 +0100 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: >>>>> "Gabriel Genellina" (GG) wrote: >GG> En Tue, 04 Mar 2008 11:46:48 -0200, NickC escribi?: >>> A mildly interesting Py3k experiment: >>> >>> Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) >>> [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>>>>> from fractions import Fraction >>>>>> from decimal import Decimal >>>>>> def check_accuracy(num_type, max_val=1000): >>> ... wrong = 0 >>> ... for x in range(1, max_val): >>> ... for y in range(1, max_val): >>> ... wrong += (x / num_type(y)) * y != x >>> ... return wrong >>> ... >>>>>> check_accuracy(float) >>> 101502 >>>>>> check_accuracy(Decimal) >>> 310013 >>>>>> check_accuracy(Fraction) >>> 0 >>> >>> >>> The conclusions I came to based on running that experiment are: >>> - Decimal actually appears to suffer more rounding problems than float >>> for rational arithmetic >GG> Mmm, but I doubt that counting how many times the results are equal, is >GG> the right way to evaluate "accuracy". >GG> A stopped clock shows the right time twice a day; a clock that loses one >GG> minute per day shows the right time once every two years. Clearly the >GG> stopped clock is much better! But if the answer is incorrect (in the float calculation) the error is limited. IEEE 754 prescribes that the error should be at most 1 LSB, IIRC. And then the number of errors is the proper measure. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From lcapps at cteresource.org Thu Mar 27 11:09:52 2008 From: lcapps at cteresource.org (Lee Capps) Date: Thu, 27 Mar 2008 11:09:52 -0400 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: On Mar 27, 2008, at 10:53 AM, Skip Montanaro wrote: > I am trying to replace os.system calls with subprocess.Popen. This > simple > example fails miserably: > >>>> proc = subprocess.Popen ("ls /tmp") > Traceback (most recent call last): > File "", line 1, in > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line > 594, in __init__ > errread, errwrite) > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line > 1091, in > _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I also tried explicitly referencing /usr/bin/ls. Same result. > What gives? > I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with > 2.6alpha on Mac OS X. > Try proc = subprocess.Popen(('ls', '/tmp/')) or proc = subprocess.Popen('ls /tmp/', shell=True) See http://docs.python.org/lib/node528.html HTH, --- Lee Capps Technology Specialist CTE Resource Center lcapps at cteresource.org From jeff at schwabcenter.com Mon Mar 17 19:58:38 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 16:58:38 -0700 Subject: Interesting math problem In-Reply-To: References: Message-ID: BJ?rn Lindqvist wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > step = distance / float(parts) > intstep = int(step) > floatstep = step - intstep > > steps = [] > acc = 0.0 > for i in range(parts): > acc += floatstep > step = intstep > if acc > 0.999: > step += 1 > acc -= 1.0 > steps.append(step) > return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L def make_slope(distance, parts): if parts == 0: return [] q, r = divmod(distance, parts) if r and parts % r: q += 1 return [q] + make_slope(distance - q, parts - 1) def self_test(distance=130, parts=51): L = make_slope(distance, parts) assert(len(L) == parts) assert(sum(L) == distance) print L if __name__ == '__main__': for distance in range(1, 200): for parts in range(1, 200): self_test(distance, parts) From commander_coder at hotmail.com Tue Mar 4 06:26:32 2008 From: commander_coder at hotmail.com (commander_coder at hotmail.com) Date: Tue, 4 Mar 2008 03:26:32 -0800 (PST) Subject: tools to install not in python tree? References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: Thank you for the helpful replies. I shall check out the links. (I looked at some setup.py's but mxBase was not among them.) Regards, Jim From dadapapa at googlemail.com Mon Mar 3 10:04:56 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Mon, 3 Mar 2008 07:04:56 -0800 (PST) Subject: Problem with the strip string method References: Message-ID: > Thanks to all respondents, Steve Holden > is right, I expected more than I should > have. Others have explained why all your examples work as they should. >From your exmaples, it seems like you would like strip to remove the leading and trailing characters from EVERY LINE in your string. This can be done by the simple construct >>> my_string = ' foo \n bar ' >>> '\n'.join(line.strip() for line in my_string.split('\n')) 'foo\nbar' If you need this construct at several places, define a function def line_strip(string,sep='\n') : return sep.join(line.strip() for line in string.split(sep)) cheers, - harold - From wuwei23 at gmail.com Wed Mar 26 23:02:44 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 26 Mar 2008 20:02:44 -0700 (PDT) Subject: A question on decorators References: <64vpmnF2dvlccU1@mid.uni-berlin.de> Message-ID: <818b5a6c-636d-4a6e-8fb3-b44e32925ca0@e10g2000prf.googlegroups.com> On Mar 27, 8:30 am, castiro... at gmail.com wrote: > I want the * to precede the dot too. Let's yack. I want to compile > Python. Did you see my new post? I like it. Do you have any time > you don't want? Time sale. Diez is still mad at me. I want > primitives to structure themselves so I can pick up a pen. I am > volunteer primitive structuring. Your structure sucks. assert > atmostphere has drags. Could you possibly once, just once, put down the Robert Anton Wilson & the meth pipe before you post? From darcy at druid.net Wed Mar 5 16:51:17 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 16:51:17 -0500 Subject: Please keep the full address In-Reply-To: References: Message-ID: <20080305165117.56585299.darcy@druid.net> On Wed, 5 Mar 2008 13:38:59 -0800 (PST) Mike Driscoll wrote: > On Mar 5, 12:50 pm, castiro... at gmail.com wrote: I'm not sure why you change the address like this but could you please include the full address. Those of us who identify the time wasters would also like to drop the responses to their posts and changing the address makes this impossible. -- 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 jgardner at jonathangardner.net Mon Mar 24 19:39:32 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 24 Mar 2008 16:39:32 -0700 (PDT) Subject: urllib leaves connections/sockets waiting. BIG problem!!! References: <62c0ec57-1355-43d8-a414-0767ccc0923a@s37g2000prg.googlegroups.com> Message-ID: <4cd5ce67-d6cc-4c5f-a117-c15add9fa812@s12g2000prg.googlegroups.com> On Mar 24, 6:57?am, binaryj wrote: > hi i am using urllib2 to do some automated web thing. > basically i hit on sites and check the price what they are offering > for their product and then decide if i want to lower or increase my > pricing.so in short i have to hit hundreds of sites!!!!! > > for the problem: > ============= > i run 20 threads all do the same stuff. (hit and run :) ) > after around 10-15 hits(per thread) hits the thread does nothing. it > freezes. slowely but STEADILY all the threads end up with the same > fate :( > > i did some netstat and found out that the connecton(sockets) the > program had opened are waiting the CLOSE_WAIT state !! > > netstat -t > tcp ? ? ? ?1 ? ? ?0 192.168.1.2:4882 ? ? ? ?host-blabla:www > CLOSE_WAIT > tcp ? ? ? ?1 ? ? ?0 192.168.1.2:4884 ? ? ? ?host-blabla:www > CLOSE_WAIT > tcp ? ? ? ?1 ? ? ?0 192.168.1.2:4375 ? ? ? ?host-blabla:www > CLOSE_WAIT > > OUTPUT OF PROGRAM: > THREAD: #Thread-2 getting price from webi-d ?7511975 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?4449152 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?7466091 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?8641914 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?7745289 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?6032442 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?8149873 DONE !!! > no-price-on-page error > THREAD: #Thread-1 getting price from webi-d ?5842934 DONE !!! > no-price-on-page error > THREAD: #Thread-2 getting price from webi-d ?3385778 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?4610122 DONE !!! > THREAD: #Thread-2 getting price from webi-d ?8641536 DONE !!! > THREAD: #Thread-1 getting price from webi-d ?4219935 DONE !!! > ---------and thats it, it freezes. i have waited 1hr the sockets have > not changed their states! :( > > please help :) I think we'll need more details before being able to assess what is wrong. Can you supply some sample code that has the same bug? From http Mon Mar 17 04:28:55 2008 From: http (Paul Rubin) Date: 17 Mar 2008 01:28:55 -0700 Subject: writing to a binary file without intervening spaces References: Message-ID: <7xtzj5eou0.fsf@ruckus.brouhaha.com> Larry writes: > My data is a = [23, 45, 56, 255]. > My desire output is: 234556255, of course in binary file > representation already. > > I tried to make one using write after pack method of struct module, > but because of spaces I got incorrect results. struct.pack works for me: Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >>> import struct, os >>> x = struct.pack('BBBB', 23, 45, 56, 255) >>> len(x) 4 >>> f = open('/tmp/foo','w'); f.write(x); f.close() >>> os.system("ls -l /tmp/foo") -rw------- 1 phr phr 4 Mar 17 01:27 /tmp/foo >>> You could also do the list-string conversion with the array module. From tjreedy at udel.edu Sun Mar 16 04:01:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Mar 2008 04:01:05 -0400 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net><13sc3b0g7gud892@corp.supernews.com><13tmo994bgqjr11@corp.supernews.com><13to6j6pta8o008@corp.supernews.com> <13tpa4999krk6cd@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13tpa4999krk6cd at corp.supernews.com... | On Sat, 15 Mar 2008 11:50:17 -0700, Dennis Lee Bieber wrote: | | > Small integers are cached in Python, so they always have a fixed ID | > (address). | | Small integers are cached in CPython, making it an implementation- | dependent feature. Indeed, the set cached has changed from version to version. | I don't believe that caching is promised by the | language definition, No, could even disappear from cPython. From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 17:11:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 22:11:31 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> Message-ID: <13su6kjio80q55b@corp.supernews.com> On Wed, 05 Mar 2008 13:52:38 -0800, castironpi wrote: > On Mar 5, 3:38?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: >> > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: >> >> castiro... at gmail.com schrieb: >> >> >> > I want to hash values to keys. ?How do the alternatives compare? >> >> >>http://catb.org/~esr/faqs/smart-questions.html >> >> > ... without extending the whole way to a full relational database? >> >> You didn't bother following the link and reading the advice, did you? >> If you did, you haven't done a good job of following that advice. > > Well, obviously there's someone who's interested in computers and > programming that has a question. Communication is not his forte, but > effort, willingness, devotion, and dedication are. What should he do, Read the "Smart Questions" page and follow the advice in it. Sheesh. -- Steven From duncan.booth at invalid.invalid Fri Mar 28 06:53:54 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Mar 2008 10:53:54 GMT Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > On Mar 28, 1:57?am, raj wrote: >> To ankit: >> >> Well, sort() doesn't return the sorted list. It returns None. Why not >> this straightforward way? >> dvals = dict.values() >> dvals.sort() >> print dvals > > Why not sorted( dict.values() ). > If you are going to do it that way then it may be preferable to use itervalues: print sorted(dict.itervalues()) Both this and raj's suggestion create a single sorted list. Your suggestion creates two lists: the unsorted one and a separate sorted one. In most cases the difference is probably insignificant, but if you have a *lot* of values it might make a difference. From john.jython at gmail.com Mon Mar 24 21:15:17 2008 From: john.jython at gmail.com (john s.) Date: Mon, 24 Mar 2008 18:15:17 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 Message-ID: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Hi Everyone, I hope not to offend you with too many question.. I've been lurking a long time. I'm not keen on keeping e-mails or data stored in the public space so this is my first post to the group. That being said, I'm keen on refining my skills, I hope that I can prove that I've move on beyond the: check the tut, read the faq.. Now as it's out of the way I hope that my questions can be sited as examples for others breaking the procedural barrier. I've seen examples using reduce, map and lamba that cause me to emit a internal "WTFIZDISHI?" _____________________________ With out any further adiou... IsMyKodeHotOrNot.... and how can I improve it... hopefully it will help me with part two... I'm sure anyone with 2 mins and solid skill of python can ballpark this one... _____________________________ #/usr/bin/enviro python #Purpose - a dropped in useracct/pass file is on a new server to build a cluster... Alas there are no home #directories.. Let me rip through the passfile, grab the correct field (or build it) and use it to make the directory! import os, sys, string, copy, getopt, linecache from traceback import format_exception #The file we read in... fileHandle = "/etc/passwd" srcFile = open(fileHandle,'r') srcList = srcFile.readlines() #yah, a for loop that "iterates" through the file of "lines" for i in srcList: strUsr = string.split(i,":") theUsr = strUsr[0] usrHome = "/expirt/home/",theUsr,"/" usrHome = ''.join(usrHome) print "printing usrHome:",usrHome print "is it a dir?: ", os.path.isdir(usrHome) # try to test if it's a dir... for some reason this mis-behaves... maybe I'm not thinking about it correctly.. if os.path.isdir(usrHome) != 'False': print "User Home dir doesn't exist creating." try: os.makedirs('usrHome' ) except Exception, e: print e print "usrHome is: ",usrHome print "theUsr is: ",theUsr os.system('/usr/bin/chmod 750 ' + usrHome) os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) #OMG, there is directory that happens to already exist! well, due diligence and love for the queen dictates we #provide "due dilligence", (e.g. wipe our asses properly) else: print "User Home dir exist, checking and fixing permissions." print "usrHome is: ",usrHome print "theUsr is: ",theUsr os.system('/usr/bin/chmod 750 ' + usrHome) os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) #I know that I can't optimize the line below further... or... can I? sys.exit("Thanks for using pyDirFixr...") From magdoll at gmail.com Wed Mar 12 02:30:16 2008 From: magdoll at gmail.com (Magdoll) Date: Tue, 11 Mar 2008 23:30:16 -0700 (PDT) Subject: merging intervals repeatedly References: <20b3dfb8-c5b7-4fd0-97a1-93f590f54595@u10g2000prn.googlegroups.com> <13tescq9e809idb@corp.supernews.com> Message-ID: <968a15bf-77cc-4f9c-a579-77ef22e4fae0@s13g2000prd.googlegroups.com> On Mar 11, 11:01 pm, Dennis Lee Bieber wrote: > On Tue, 11 Mar 2008 15:43:40 -0700 (PDT), Magdoll > declaimed the following in comp.lang.python: > > > Correct. I meant the final should be > > (1,30), (29,40), (50,100) > > Actually, even that is incorrect -- note that ,30 overlaps 29, As someone else pointed out, I can't merge (1,30), (29,40) because N = 5. If N were always 1, I could've easily used IntervalSet to do this and I would not have to write more than 5 lines total to get this done. I'm asking precisely because N can be varied and maybe in the future will be more complex than just an integer. > > Since this feels like a homework assignment, I won't be posting my > code... It isn't an homework assignment. I'm writing it for my research. Or more precisely, I've already written a solution and wanted to see if any people here know more salient solutions than mine > > I only state that, 1) I did not bother sorting the interval list -- > unless you have very many intervals to process, a simple sequential > search is probably faster than using bisection/insert algorithm; Unfortunately that is the case. My input can be more than 1 million intervals, although they can be further subdivided into smaller lists, but still, I would be looking at a list of intervals on a size of at least thousands, so binary search would definitely win over sequential search. 2) the > algorithm inserts one interval at a time; 3) merge is accomplished by > removing/returning the first candidate interval to the insert method, > computing the min/max of the candidate and input intervals, and > recursively inserting that new interval -- if there is no candidate > overlap interval, no interval is returned, and the insert just appends > the input interval to the list. This looks like pretty much what my current solution looks like, except that it's unsorted. From tjreedy at udel.edu Sun Mar 2 01:31:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 01:31:30 -0500 Subject: Question about lambda and variable bindings References: <47CA160C.3000305@gmail.com> Message-ID: "Michael Torrie" wrote in message news:47CA160C.3000305 at gmail.com... |I need to use a lambda expression Lambda expressions are a convenience, not a necessity. When having a problem, it sometimes helps to revert to the unabbreviated def statement. tjr From stefan_ml at behnel.de Mon Mar 10 16:39:24 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 21:39:24 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: <47D59C7C.3010100@behnel.de> Bob Martin wrote: > Java is more portable than most other languages, especially if your app needs a gui. I don't think anything is more portable for an App GUI than HTML through a built-in web server. That said, does gcj compile GUI Apps by now? Or does that not count as "portable"? Stefan From grante at visi.com Wed Mar 19 11:20:25 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Mar 2008 15:20:25 -0000 Subject: Speaking Text References: Message-ID: <13u2bppg011i6c9@corp.supernews.com> On 2008-03-19, David C Ullrich wrote: > Mac OS X has text-to-speech built into the interface. > So there must be a way to access that from the command > line as well - in fact the first thing I tried worked: > > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? The only speach sythesizer I've seen on Linux boxes is festival: http://www.cstr.ed.ac.uk/projects/festival/ You can use os.system() to run it from the "command line" or there are various client APIs: http://www.cstr.ed.ac.uk/projects/festival/manual/festival_28.html#SEC126 But, it's not installed by default on any distros I've ever used... -- Grant From fabiofz at gmail.com Thu Mar 6 10:44:37 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 6 Mar 2008 12:44:37 -0300 Subject: Pydev 1.3.14 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.14 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Local renames: scoping issues. * Local renames: comments/strings only renamed in local scope for local variable. * False positive: undefined variable: a base-class could be flagged as undefined if used in a method scope. * Remote Debugger: easier way to specify path translations between a remote machine and a local machine (constant must be set in org.python.pydev.debug/pysrc/pydevd_file_utils.py -- see comments on module) . Release Highlights in Pydev: ---------------------------------------------- * Outline view: patch by Laurent Dore: better icons for different types of fields methods. * Outline view: patch by Laurent Dore: more filters. * PyLint: working dir is the directory of the analyzed file. * Project explorer: fixed bug on integration with Dynamic Web Project. * Extract method: fixed bug when trying to refactor structure: a = b = xxx. * Generate constructor using fields: working for classes that derive from builtin classes. * Override methods: working for classes that derive from builtin classes. * Debugger can use psyco for speedups: see http://pydev.blogspot.com/2008/02/pydev-debugger-and-psyco-speedups.html. * Debugger: shows parent frame when stepping in a return event. * Go to previous/next method: (Ctrl+Shift+Up/Down): does not rely on having a correct parse anymore. * Auto-formatting: No space after comma if next char is new line. * Code Completion: Handling completions from attribute access in classes (accessed from outside of the class). * Auto-indent: Better handling when indenting to next tab position within the code. * Caches: Some places were recreating the cache used during a completion request instead of using the available one (which could have a memory impact on some situations). What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From __peter__ at web.de Sat Mar 1 06:15:22 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Mar 2008 12:15:22 +0100 Subject: invert or not ? References: Message-ID: Stef Mientki wrote: > from the manual I read that a bitwise inversion should be done by invert. > But from some experiments I see that not works equally well. > Is this coincidence ? [Are cryptical posts contagious? I hope not.] Please explain what you did in your experiments and what did not work as expected. > (The disadvantage of invert is that I've to import operators) Do you travel with a suitcase or a lorry? The advantage of import is that your programs won't grind to a halt loading stuff you don't need most of the time. By the way >>> operator.invert(42) == ~42 True Peter From mcantelon at gmail.com Sun Mar 23 18:47:36 2008 From: mcantelon at gmail.com (Mike Cantelon) Date: Sun, 23 Mar 2008 15:47:36 -0700 (PDT) Subject: Open Web Vancouver 2008: A Conference on Open Web Technologies Message-ID: When: Monday April 14 - Tuesday April 15th 2008 Where: Vancouver Convention & Exhibition Centre (VCEC), 999 Canada Place. What: A conference showcasing open source technologies, communities and culture. We are featuring talks from all areas of open source technologies such as PHP, Python, Ruby on Rails, XUL, GPL, Linux, Django, Drupal, HTML, CSS, Javascript and AJAX, XML, Apache, MySQL, Web 2.0, etc. Our format delivers an extremely affordable alternative in comparison to other major conferences. Our community based, volunteer run events in the past have sold-out, attracting audiences from all over the world, and have featured the biggest names in PHP and related topics and technologies. VCEC is the largest conference facility in downtown Vancouver, located in the spectacular inner harbour. The conference will open with a 'keynote' session featuring Tim Bray, Sun Microsystems, Co-Inventor of XML, and Zak Greant of Mozilla Foundation and Foo Associates. A full list of talks is available at: http://www.openwebvancouver.ca/talks See the talk schedule grid at: http://www.openwebvancouver.ca/schedule In addition to our three tracks of presentations on both days of the conference, there will be time allocated for attendees to give short talks on topics of interest in a 'Lightning Talk' format. The Open Web is a presentation of the Vancouver PHP Users Association, a registered non-profit association for the advancement of PHP and the Open Web. Registration, Information: http://www.openwebvancouver.ca/ From rcdailey at gmail.com Fri Mar 7 12:36:36 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 7 Mar 2008 11:36:36 -0600 Subject: system32 directory In-Reply-To: <47D1019A.8000200@timgolden.me.uk> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> <47D1019A.8000200@timgolden.me.uk> Message-ID: <496954360803070936k754cb105q3549991de027e86b@mail.gmail.com> On Fri, Mar 7, 2008 at 2:49 AM, Tim Golden wrote: > > Ah. Sorry. I'm sure you can call it via ctypes (built in > from Python 2.5). But even if I'd realised that's what > you'd wanted, I'd probably have given the original answer > because pywin32 pretty much *is* standard library for any > Python installation I do on Win32 :) > > TJG > I didn't mean to convey that I was rejecting your initial answer, I was just hoping that I wouldn't have to go download another library. Usually it means I have to compile it myself, which in my experience is a total pain in the neck to do on Windows. I'm definitely going to check out pywin32, since ctypes seems like a tedious solution (as many have already pointed out). Thanks again! -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue Mar 4 13:16:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:16:59 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> Message-ID: <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> On Mar 4, 5:27?am, Bruno Desthuilliers wrote: > ?? a ?crit : > > > Howdy everyone, > > > ? ? ?This is a big problem puzzles me for a long time. The core question is: > > How to dynamically create methods on a class or an instance? > > class Foo(object): > ? ? pass > > def bar(self, arg): > ? ? print "in bar : self == % - arg == %s" % (self, str(arg)) > > def baaz(self, arg): > ? ? print "in baaz : self == % - arg == %s" % (self, str(arg)) > > f = Foo() > > # adding bar as a method to class Foo > Foo.bar = bar > > # f now can use bar: > f.bar(42) > > # as well as new instances of Foo, of course > g = Foo() > g.bar() > > # adding baaz as a method to f, the old way: > import new > f.baaz = new.instancemethod(baaz, f, type(f)) > > f.baaz() > > # adding baaz as a method to g, the other way: > g.baaz = baaz.__get__(g, type(g)) > > g.baaz() > > > Let me state it step by step. > > 1. > > def gunc(self): > > ? ? pass > > class A(object): > > ? ? def func(self): > > ? ? ? ? pass > > a = A() > > a.func ? # gives "bound method", type is "instancemethod" > > A.func ?# gives "unbound method", type is "instancemethod" > > gunc ? ?# gives "function", type if "function" > > > # ?? Does this line attach a method to instance? ?... I don't think so. > > a.gunc = gunc > > It doesn't. > > > I found stardard library 'new' may help. Is that right? > > cf above. If you work with old-style classes, you'll need > new.instancemethod. > > > 2. > > a = A() ?# instance of old class A > > # Do attach a new method to class A... > > b = A() ?# instance of new class A > > Does "a" can get the new method automatically? > > Yes. In Python, a class is itself an object, and is an attribute of it's > instances (instance.__class__). Names are resolved at runtime, and > attributes not found in the instance's __dict__ are looked up in the > class (and then in the superclasses etc). > > > Does new method have the *same* concept level with old methods? > > The newly added method works exactly the same way as already existing > ones. Not a single difference. The class statement is just syntactic > sugar anyway. The following snippets are equivalent: > > # sugar-coated: > class Boo(object): > ? ? ?faaz = 0 > > ? ? ?def far(self): > ? ? ? ? ?type(self).faaz += 1 > ? ? ? ? ?print self > > ? ? ?def frob(self): > ? ? ? ? ?print "yadda" > > # raw: > def far(self): > ? ? ?type(self).faaz += 1 > ? ? ?print self > > Boo = type('Boo', (object,), dict(faaz=0, far=far)) > > def frob(self): > ? ? print "yadda" > > Boo.frob = frob > > > Especially, if there > > are classes inherit from class A, how does name resolution work on this case? > > As usual. > > > 3. > > How do I write a decroator for a method? > > Mostly the same way you'd write a decorator for a function > > > Eg: > > class A(object): > > ? ? @my_dec > > ? ? def func(self): > > ? ? ? ? pass > > Here, my_dec should return a method rathar than a function/lambda. Am I right? > > Nope. Functions defined within a class statement are plain ordinary > functions. It's the lookup mechanism that "turns them into methods" when > they are looked up as attribute of a class. In fact, Python "methods" > are thin callable wrappers around a function, a class and (most of the > time) an instance, wrappers which are created - usually at lookup time - > by the __get__ method of the function type (you may want to read about > the descriptor protocol on python.org - in the section about new style > classes IIRC). > > Anyway, you can explore this by yourself: > > ?>>> Boo.far > > ?>>> b.far > > > ?>>> Boo.__dict__['far'] > > ?>>> Boo.__dict__['far'] is far > True > ?>>> f1 = b.far > ?>>> f2 = b.far > ?>>> f1 is f2 > False > ?>>> f1() > <__main__.Boo object at 0xb787f96c> > ?>>> f2() > <__main__.Boo object at 0xb787f96c> > ?>>> dir(f1) > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', > '__get__', '__getattribute__', '__hash__', '__init__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > 'im_class', 'im_func', 'im_self'] > ?>>> f1.im_class > > ?>>> f1.im_func > > ?>>> f1.im_func is far > True > ?>>> f1.im_self > <__main__.Boo object at 0xb787f96c> > ?>>> f1.im_self is b > True > ?>>> bf = Boo.far > ?>>> bf.im_func > > ?>>> bf.im_func is far > True > ?>>> bf.im_class > > ?>>> bf.im_self > ?>>> bf.im_self is None > True > ?>>> far.__get__(b, Boo) > > > ?>>> far.__get__(b, Boo).im_func is far > True > ?>>> > > So, to answer your question: what you are decorating are functions, not > methods. Can you overload -type-'s decision of what to 'bind'?... whenever it is it makes it. From thynnus at gNOTmail.com Tue Mar 4 08:48:31 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 04 Mar 2008 13:48:31 GMT Subject: 'normal' shell with curses In-Reply-To: <633s5lF24prinU1@mid.uni-berlin.de> References: <633s5lF24prinU1@mid.uni-berlin.de> Message-ID: On 3/3/2008 9:57 PM, Michael Goerz wrote: > Hi, > > I'm trying to print out text in color. As far as I know, curses is the > only way to do that (or not?). So, what I ultimately want is a curses > terminal that behaves as closely as possible as a normal terminal, i.e. > it breaks lines and scrolls automatically, so that I can implement a > function myprint(color, text) that does what print() does, only in color. You might find the below helpful. Let us know how you make out? -------- Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 Title: Using terminfo for portable color output & cursor control Description: The curses module defines several functions (based on terminfo) that can be used to perform lightweight cursor control & output formatting (color, bold, etc). These can be used without invoking curses mode (curses.initwin) or using any of the more heavy-weight curses functionality. This recipe defines a TerminalController class, which can make portable output formatting very simple. Formatting modes that are not supported by the terminal are simply omitted. -------- From exarkun at divmod.com Mon Mar 3 00:46:47 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 3 Mar 2008 00:46:47 -0500 Subject: Python Telnet formatting? In-Reply-To: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: <20080303054647.6859.91642152.divmod.quotient.14953@ohm> On Sat, 1 Mar 2008 16:51:08 -0800 (PST), mentaltruckdriver at gmail.com wrote: >Hi everyone: > >I posted here a couple days ago looking for some help creating a >Telnet-based chat server. You guys pointed me to Twisted, which has >solved most of my issues. > >However, what I want to do is analyze strings received for keywords >such as 'listcmds' and have the server return something to the client. >I know how to do that part, at least. > >The issue is, when I use clients like PuTTY, it returns a lot of what >appears to be formatting (e.g. if I typed Hello, it would return "\xff >\xfb\x1f\xff\ >xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) > >How would I go about filtering this stuff out of the strings? The >thing is too, if I use other Telnet programs like Microsoft Telnet, >they don't have this formatting, so I want to be able to recognize if >it does have this formatting and act based on if it does or if it >doesn't. > >Any help is appreciated, I know I'm probably asking too many questions >already :) If you're using Twisted's telnet implementation, then all of the telnet command sequences will be handled separately from the application data. It might help if you share some of your code. Jean-Paul From steve at REMOVE-THIS-cybersource.com.au Tue Mar 11 14:02:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 11 Mar 2008 18:02:12 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <63i6j9F2793buU1@mid.uni-berlin.de> Message-ID: <13tdi949jfa2g55@corp.supernews.com> On Mon, 10 Mar 2008 12:14:40 -0700, metawilm at gmail.com wrote: > Common Lisp has two ways of raising: functions "error" and "signal". > Python's "raise" is like CL's "error": you end up in the debugger if the > exception is not handled. Exceptions that are raised by CL's "signal" > don't have to be caught: if there is no matching "except" clause the > raise statement becomes a "pass". > > Or as Wikipedia states nicely: "Conditions are a generalization of > exceptions. When a condition arises, an appropriate condition handler is > searched for and selected, in stack order, to handle the condition. > Conditions which do not represent errors may safely go unhandled > entirely; their only purpose may be to propagate hints or warnings > toward the user." > > http://en.wikipedia.org/wiki/Exception_handling#Condition_systems If I had come across "signals" before now, I would have thought that they were a good idea. But after watching Lie repeatedly argue for tightly coupling functions together using signal-like "SoftExceptions", all I can see are the disadvantages. I'm afraid that if Lie's arguments are the best available for such a signaling mechanism, then it's probably a good thing Python doesn't have it. -- Steven From jeff at schwabcenter.com Thu Mar 6 00:16:56 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 05 Mar 2008 21:16:56 -0800 Subject: OT[1]: Re: SV: Polymorphism using constructors In-Reply-To: <13suutr9i3fci89@corp.supernews.com> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> <13ssb8fph6nkoff@corp.supernews.com> <29WdncFY4qn0VFPanZ2dnUVZ_ournZ2d@comcast.com> <13suutr9i3fci89@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 05 Mar 2008 08:26:04 -0800, Jeff Schwab > declaimed the following in comp.lang.python: > >> Which is which? Aren't those both part of the space vehicle? Btw, do >> you work for government or industry? Do you enjoy working with the >> space program? I've heard only indirect reviews, and they've been mixed. >> > Lockheed... I don't really work with the sat's themselves. > > When it comes to division of responsibility, the "payload" is the > part the customer wants in orbit. The "space vehicle" is the part that > carries it around in that orbit -- the SV has the station-keeping > thrusters (I'm presuming a geosynchronous orbit), the power supply and > solar panels... The payload may just consist of a wide-band transponder > (for direct TV, say) and maybe an independent commanding system (its own > receive transmit gear on a different frequency from the satellite > control -- though I wouldn't really expect this type of split) Interesting. Thanks. From gdamjan at gmail.com Thu Mar 27 17:06:38 2008 From: gdamjan at gmail.com (Damjan) Date: Thu, 27 Mar 2008 22:06:38 +0100 Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: <47ec0cd0$0$90262$14726298@news.sunsite.dk> mungkol wrote: > Dear all, > > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: you need to install the "build-essential" pacakge group on Ubuntu so that you can compile programs. apt-get install build-essential > limits.h: No such file or directory This is probably /usr/include/linux/limits.h part of the kernel headers. -- damjan From software at ginstrom.com Sun Mar 9 01:04:05 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Sun, 9 Mar 2008 15:04:05 +0900 Subject: SV: Regarding coding style In-Reply-To: <13t6tha12dcdh5a@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net><9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com><13t462h7vgqo081@corp.supernews.com><7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com><13t4k50d7pg0d63@corp.supernews.com><1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com><13t5cbcrhtfsrd2@corp.supernews.com><13t5qd3slgt9nc0@corp.supernews.com><63g9s0F26pgoeU1@mid.individual.net><13t6c8kdis2gbb5@corp.supernews.com> <13t6tha12dcdh5a@corp.supernews.com> Message-ID: <02c001c881ab$65100ac0$0203a8c0@MOUSE> > On Behalf Of Grant Edwards > I think docstrings are a great idea. What's needed is a way > to document the signature that can't get out-of-sync with > what the fucntion really expects. Like doctests? (I know, smart-ass response) Regards, Ryan Ginstrom From inq1ltd at inqvista.com Thu Mar 6 10:19:03 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 06 Mar 2008 10:19:03 -0500 Subject: Licence confusion: distributing MSVC?71.DLL In-Reply-To: References: Message-ID: <200803061019.03761.inq1ltd@inqvista.com> > > If someone has worked their way through > > this maze before and has an answer, I'd > > be keen to hear it. This is what someone wrote on 1-21-2007 to this help site about this pain in the a... MSVCR71 stuff. " I believe this problem doesn't exist. Licensees of Python are permitted to redistribute mscvr71.dll, as long as they redistribute it in order to support pythonxy.dll. The EULA says # You also agree not to permit further distribution of the # Redistributables by your end users except you may permit further # redistribution of the Redistributables by your distributors to your # end-user customers if your distributors only distribute the # Redistributables in conjunction with, and as part of, the Licensee # Software, you comply with all other terms of this EULA, and your # distributors comply with all restrictions of this EULA that are # applicable to you. In this text, "you" is the licensee of VS 2003 (i.e. me, redistributing msvcr71.dll as part of Python 2.5), and the "Redistributable" is msvcr71.dll. The "Licensee Software" is "a software application product developed by you that adds significant and primary functionality to the Redistributables", i.e. python25.dll. IANAL; this is not legal advise." jim-on-linux http://www.inqvista.com From deets at nospam.web.de Sat Mar 29 18:45:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 23:45:09 +0100 Subject: Installing simplejson issues In-Reply-To: References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> Message-ID: <657v3lF2e7r7pU1@mid.uni-berlin.de> Gabriel Genellina schrieb: > En Fri, 28 Mar 2008 23:23:01 -0300, escribi?: > >> On Mar 28, 1:57 pm, "Gabriel Genellina" >> wrote: >>> En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: >>> >>> > I am trying to install the twitter python wrapper...I got that >>> > installed just fine, but am having serious troubles getting the >>> > simplejson package to install. I need help diagnosing where this is >>> > failing. I am trying to use: >>> >>> >http://pypi.python.org/pypi/simplejson >>> >>> > and I run "python setup.py build" and then "python setup.py install", >>> > which both seem to work just fine. > > I tried to install the package but failed. Looks like the setup.py used > by simplejson is broken - doesn't handle well the case when the C > extension can't be compiled. > When I run `python setup.py install` I got this message: > > building 'simplejson._speedups' extension > ********************************************************************** > WARNING: The C extension could not be compiled, speedups are not enabled. > > Below is the output showing how the compilation failed: > > Python was built with Visual Studio version 7.1, and extensions need to > be built > with the same version of the compiler, but it isn't installed. > ********************************************************************** > > and later: > removing simplejson.egg-info\native_libs.txt > ... > error: can't copy 'simplejson.egg-info\native_libs.txt': doesn't exist > or not a regular file > > I suggest that you remove the simplejson-xxxxxx.egg file and delete the > simplejson entry in easy-install.pth (both in your site-packages directory) > Then extract the simplejson directory from inside the original .tar.gz > archive into your site-packages directory (so you end up by example with > a .../site-packages/simplejson/decoder.py file, among others) > That appears to be enough; import simplejson worked fine for me. > > I hate those f****ng eggs. Ah, and I hate easy_install too. This has nothing to do with setuptools or easy_install per se. The author of simplejson tried to create a library that works with or without a C-extension. And failed. As your above approach fails to even *try* and compile the speedups. Diez From zerty.david at gmail.com Sun Mar 30 16:55:15 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:55:15 -0300 Subject: Newbie Question.. How to add python to system path in windows? Message-ID: <5dc598e30803301355w7496acafu5261b6f0dfc54405@mail.gmail.com> hi All, I have my Phitno 25 installed on the default directory, but How can I dd to the ubild path? Thx -------------- next part -------------- An HTML attachment was scrubbed... URL: From sleddd at gmail.com Thu Mar 13 00:46:31 2008 From: sleddd at gmail.com (sleddd at gmail.com) Date: Wed, 12 Mar 2008 21:46:31 -0700 (PDT) Subject: Socket Performance Message-ID: Can anyone explain why socket performance (throughput) varies depending on the amount of data send and recv are called with? For example: try creating a local client/server (running on the same computer) where the server sends the client a fixed amount of data. Using method A, recv(8192) and sendall( ) with 8192 bytes worth of data. Do this 100 times. Using method B, recv(1) and sendall( ) with 1 byte worth of data. Do this 819200 times. If you time both methods, method A has much greater throughput than method B. Server: import socket import random import string import time HOST = 'localhost' PORT = 50023 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr string_1 = 'A' string_8192 = ''.join([random.choice(string.letters + string.digits) for i in range(8192)]) conn.sendall('Start') start = time.clock() total_data = 0 for i in range(0,100): conn.sendall(string_8192) total_data += len(string_8192) print 'Send Speed (Long String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec\n\n' start = time.clock() total_data = 0 for i in range(0,819200): conn.sendall(string_1) total_data += len(string_1) print 'Send Speed (Short String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec' conn.close() Client: import socket import time HOST = 'localhost' # The remote host PORT = 50023 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, 50026)) s.connect((HOST, PORT)) data = s.recv(5) print 'From Server: ' + data start = time.clock() total_data = 0 while total_data < 819200: data = s.recv(8192) total_data += len(data) print 'Receive Speed (Long String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec\n\n' start = time.clock() total_data = 0 while total_data < 819200: data = s.recv(1) total_data += len(data) print 'Receive Speed (Short String): ' + str( total_data / (time.clock() - start) / 1024 / 1024 ) + ' MB/sec' s.close() From george.sakkis at gmail.com Mon Mar 24 15:18:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Mar 2008 12:18:23 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> Message-ID: On Mar 24, 3:13 pm, pythonnubie wrote: > > > i have come across my first exeption using randrange . The exeption > > > is " no such attribute " in module random > > > > platform is xp home and the python build is activestate 2.5 > > > Welcome aboard! > > > There's definitely a randrange function in the random module, so > > something else must be wrong. To get the most out of this list and > > minimize wasted bandwidth, the most effective way usually consists of > > copying and pasting: > > 1. The offending code (or just the relevant part if it's too big). > > 2. The full traceback of the raised exception. > > > Regards, > > George > > Hwere is the complete traceback ! >>> The word is: index > > Traceback (most recent call last): > File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", line 307, in RunScript > debugger.run(codeObject, __main__.__dict__, start_stepping=0) > File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > \__init__.py", line 60, in run > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > \debugger.py", line 631, in run > exec cmd in globals, locals > File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, > in > import random > File "F:\Documents and Settings\Mark\My Documents\random.py", line > 13, in > distributions on the real line: > AttributeError: 'module' object has no attribute 'randrange' > > Why would it say it can't find the function ? Because you named your file 'random.py' and it shadows the standard random module! Change the name to something else, say foo.py, and try it again. George From robert.rawlins at thinkbluemedia.co.uk Wed Mar 12 10:33:07 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 12 Mar 2008 14:33:07 -0000 Subject: MySQL DB-Api In-Reply-To: <008601c8836a$5c5fbf90$151f3eb0$@rawlins@thinkbluemedia.co.uk> References: <008601c8836a$5c5fbf90$151f3eb0$@rawlins@thinkbluemedia.co.uk> Message-ID: <005f01c8844d$fd82dfe0$f8889fa0$@rawlins@thinkbluemedia.co.uk> Hello guys, sorry for dragging this to the top of the list again but I really am intrigued to get your feedback. I'm looking for a clean and efficient way to implement the DB-API into my application without having to create database connections for every instance of objects which require it. I'd love to create some form of cached instance of the connection within the application and then provide new cursor instances for objects that need to query the database but I'm not sure of the best way to deal with this to ensure the cursors are closed when the instances destruct, or just as importantly, if I even need to close the cursor. I'd be really interested to know how you are implementing this kind of thing, Cheers, Robert From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins Sent: 11 March 2008 11:24 To: python-list at python.org Subject: MySQL DB-Api Good morning list. I'm in the process of learning my way around the DB-API module for MySQL and wanted to come and get some advice on how you all manage your database connections and cursors. Within my applications I'll have many classes which access the database, I'm wondering to what level I should extract the database connection. Should I create a new database connection and close it for every method which calls the database? Should I create the connection/cursor to the DB when I construct the class and place the cursor in the self scope? Or should I create a application wide connection/cursor to the database and inject the cursor into all the classes which require it? All classes within the application access the same database so at the moment I'm leaning towards creating an application wide connection and cursor and then injecting it into classes which require database access, does that sound like a fair plan? I'm just interested to learn how you are managing this. Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Bossy at jouy.inra.fr Tue Mar 25 12:12:50 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 17:12:50 +0100 Subject: Creating dynamic objects with dynamic constructor args In-Reply-To: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> References: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> Message-ID: <47E92482.6050208@jouy.inra.fr> Greg at bag.python.org wrote: > I'd like to create objects on the fly from a pointer to the class > using: instance = klass() But I need to be able to pass in variables > to the __init__ method. I can recover the arguments using the > inspect.argspec, but how do I call __init__ with a list of arguments > and have them unpacked to the argument list rather than passed as a > single object? > > ie. class T: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > argspec = inspect.argspec(T.__init__) > args = (1, 2) > > ??? how do you call T(args)? > The star operator allows you to do this: T(*args) You also can use dict for keyword arguments using the double-star operator: class T(object): def __init__(self, foo=None, bar=None): self.foo = foo self.bar = bar kwargs = {'bar': 1, 'foo': 2} T(**kwargs) RB From fakeaddress at nowhere.org Fri Mar 14 08:41:45 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 12:41:45 GMT Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Message-ID: Robert Bossy wrote: > Bryan Olson wrote: >> Robert Bossy wrote: >>>> Robert Bossy wrote: >>>>> Indeed! Maybe the best choice for chunksize would be the file's buffer >>>>> size... >> >> That bit strikes me as silly. >> > The size of the chunk must be as little as possible in order to minimize > memory consumption. However below the buffer-size, you'll end up filling > the buffer anyway before actually writing on disk. First, which buffer? The file library's buffer is of trivial size, a few KB, and if we wanted to save even that we'd use os.open and have no such buffer at all. The OS may set up a file-specific buffer, but again those are small, and we could fill our file much faster with larger writes. Kernel buffers/pages are dynamically assigned on modern operating systems. There is no particular buffer size for the file if you mean the amount of kernel memory holding the written data. Some OS's do not buffer writes to disk files; the write doesn't return until the data goes to disk (though they may cache it for future reads). To fill the file fast, there's a large range of reasonable sizes for writing, but user-space buffer size - typically around 4K - is too small. 1 GB is often disastrously large, forcing paging to and from disk to access the memory. In this thread, Matt Nordhoff used 10MB; fine size today, and probably for several years to come. If the OP is writing to a remote disk file to test network throughput, there's another size limit to consider. Network file- system protocols do not steam very large writes; the client has to break a large write into several smaller writes. NFS version 2 had a limit of 8 KB; version 3 removed the limit by allowing the server to tell the client the largest size it supports. (Version 4 is now out, in hundreds of pages of RFC that I hope to avoid reading.) -- --Bryan From http Tue Mar 4 14:19:20 2008 From: http (Paul Rubin) Date: 04 Mar 2008 11:19:20 -0800 Subject: How about adding rational fraction to Python? References: <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> <763ea020-731a-4ca0-8be7-55430676f1b7@i7g2000prf.googlegroups.com> Message-ID: <7xwsoiuwjr.fsf@ruckus.brouhaha.com> Mark Dickinson writes: > For randomly chosen(*) base B floats x and y, the probability that > (x/y)*y == x is approximately given by I remember hearing that IEEE 754 was carefully designed to make this identity hold as often as possible when y is a small integer. From newsgroup898sfie at 8439.e4ward.com Tue Mar 4 18:26:23 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Tue, 04 Mar 2008 18:26:23 -0500 Subject: 'normal' shell with curses In-Reply-To: <635drhF25qgqtU1@mid.uni-berlin.de> References: <633s5lF24prinU1@mid.uni-berlin.de> <635drhF25qgqtU1@mid.uni-berlin.de> Message-ID: <63644vF263tesU1@mid.uni-berlin.de> Michael Goerz wrote, on 03/04/2008 12:05 PM: > Thynnus wrote, on 03/04/2008 08:48 AM: >> On 3/3/2008 9:57 PM, Michael Goerz wrote: >>> Hi, >>> >>> I'm trying to print out text in color. As far as I know, curses is >>> the only way to do that (or not?). So, what I ultimately want is a >>> curses terminal that behaves as closely as possible as a normal >>> terminal, i.e. it breaks lines and scrolls automatically, so that I >>> can implement a function myprint(color, text) that does what print() >>> does, only in color. >> >> You might find the below helpful. Let us know how you make out? >> >> -------- >> >> Python Cookbook >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 >> >> Title: >> Using terminfo for portable color output & cursor control >> >> Description: >> The curses module defines several functions (based on terminfo) that >> can be used to perform lightweight cursor control & output formatting >> (color, bold, etc). These can be used without invoking curses mode >> (curses.initwin) or using any of the more heavy-weight curses >> functionality. This recipe defines a TerminalController class, which >> can make portable output formatting very simple. Formatting modes that >> are not supported by the terminal are simply omitted. >> >> -------- >> > > That looks *extremely* interesting. From a very brief test, it seems to > do exactly what I want! > > Now, Windows seems very problematic for color output. I was using the > following as a test, based on the above recipe: > > term = TerminalController() > while True: > print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled' > print term.render('${RED}Error:${NORMAL}'), 'paper is ripped' > > On Linux, it works fine, on Windows, it just prints white on black > (which is of course what it should do if the terminal doesn't support > color). Can anyone get the Windows cmd.exe terminal to do color? I > already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, > but that doesn't seem to do anything (neither in what I tried yesterday > with the ANSI escape codes, nor with the recipe code now). I also very > briefly tried running it on the winbash shell > (http://win-bash.sourceforge.net/), it didn't have any color either... > So, any way to get color in Windows? > > Michael This recipe seems to work very well on WinXP: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496901 So now, I'll just have to combine the two methods, which shouldn't be too hard. Michael From bj_666 at gmx.net Wed Mar 19 16:27:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Mar 2008 20:27:56 GMT Subject: Prototype OO References: Message-ID: <64dbacF289sqvU1@mid.uni-berlin.de> On Wed, 19 Mar 2008 17:59:40 +0100, sam wrote: > Can someone tell me why class-based OO is better that Prototype based, > especially in scripting langage with dynamic types as Python is? Is it better!? Ciao, Marc 'BlackJack' Rintsch From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 09:08:56 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 15:08:56 +0100 Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> On Sun, 2 Mar 2008 15:06:17 +0100 Preben Randhol wrote: > class dbase(list): Sorry the definition of the class is: class dbase(object): it doesn't derive from the list class. Preben From castironpi at gmail.com Sat Mar 22 15:17:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 12:17:45 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: On Mar 22, 3:31?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > John Machin wrote: > >> On Mar 22, 1:11 am, castiro... at gmail.com wrote: > >>> A collision sequence is not so rare. > >>>>>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > >>> [1, 1, 1, 1, 1, 1, 1, 1] > >> Bryan did qualify his remarks: "If we exclude the case where an > >> adversary is choosing the keys, ..." > > > Some adversary. ?What, you mean, my boss or my customers? > > We mean that the party supplying the keys deliberately chose > them to make the hash table inefficient. In this thread the goal > is efficiency; a party working toward an opposing goal is an > adversary. > > If you find real-world data sets that tend to induce bad-case > behavior in Python's hash, please do tell. It would be reason > enough to adjust the hash function. The hashes in popular > software such as Python are already quite well vetted. > > Even a hash function that behaves as a random oracle has > worst-case quadratic-time in the algorithm here, but that's > an issue in theory and not in serving customers. Hey Net: Where -we- left off, all real-world data sets were equally common, unless you think in peckbird bartenders. Nuh uh at all, unless you've got a characterize real-world data project underway. Did you know letter frequency distributions vary by domain? And now for the 2- squarebar spider. raise ISay( "Python Science is unusually prone against non-power multiples of 32 hashing integers", "Unknown value of I" ) parse( 'strangers are perfect' ) parse( 'i think i know someone' ) prevention.value() == 12* cure.value() raise SolveFor (raise CureValueSterling) keep: time.value().encode() > money.value() assert time.value().encode()== time.encode().value() perch( Out ) compose( Fluctuate ) compose( Punctuate ) compose( Explain ) @partial( partial, prefix ) (ha, h) raise Distracts( 'Well, would you look at that?' ) raise LivingConstraint( NoseFalls ) raise Superlative voice Absolute raise NonScalar( "Fit: It's apples -over- oranges." ) raise OverPull( "Not on Google." ) raise Drop( "It." ) moment+= instant raise LeavesImpression raise GoodMuleTwoHaystacks raise ScaleDecomposition raise Bias( 'Discrimination' ) raise BadFor raise RequestedControlCurrencyExpiration raise InsufficientTrust raise Shock raise EnoughTheory raise EnoughCustomers raise EyebrowTwo raise DataKill raise Reckless raise ThenWhat( AfterYou ) raise NotImplemented( 'Offer.refuse' ) raise LaughterUnacceptable raise Hell raise DesignUnintelligent raise HashesPerturbation raise ProfessionException yield Tick yield Tally yield Ho yield Gee yield Whoa raise ActuallyActuallyActually raise CurrencyAStream If you can't fit an analogy... Bee Dance : Hive Good :: Human This :: Community Good? What and how is it when to who where? What does it know? What does it do but sleep? Does it specialize, momentarily fair? Hey, what do you think of the spelling of this? "The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet." What do you think of the wording of "spelling"? Take me to your lexicographer: wake-up; you're up web, Europe web. Pass self to a generator. Dust is sett'ling; Tables turn: Water's drying; Sugars burn. Phaser fire! Shoulders square! join( TenForward )? Who is where? Mushroom's growing; Mighty... falls. Cauldron's bubbling; That is all. >>> def f(): ... n= True ... while 1: ... k= yield( n ) ... if k is not None: n= k ... >>> a= f() >>> next( a ) True >>> next( a ) True >>> next( a ) True >>> a.send( 2 ) 2 >>> next( a ) 2 >>> next( a ) 2 >>> next( a ) 2 >>> From crazylunjay at gmail.com Mon Mar 24 19:55:17 2008 From: crazylunjay at gmail.com (jwesonga) Date: Mon, 24 Mar 2008 16:55:17 -0700 (PDT) Subject: PyGTK localisation on Win32 Message-ID: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> I've built an app on linux which we have managed to localise into at least three languages, the app runs well using this command LANG=fr_FR python app.py which would translate the app into french. We've tried the replicate the same principle on windows but so far nothing works, the app will need to be translated into other languages that have no locale, in windows is there a way to have Glade load values from a textfile instead of trying to use the .mo files? From mensanator at aol.com Tue Mar 11 15:12:56 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 11 Mar 2008 12:12:56 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> Message-ID: <306997c4-36dc-4603-8100-f47e25e55bef@s19g2000prg.googlegroups.com> On Mar 11, 3:36 am, Duncan Booth wrote: > Mensanator wrote: > > On Mar 10, 10:44???pm, Nathan Pinno wrote: > >> Why does my compiler say invalid syntax and then highlight the > >> quotation marks in the following code: > > >> # This program is to find primes. > > > Needs work. > > Be fair. Being helpful isn't fair? > The OP hadn't managed to figure out why the program wasn't > running, so you can't expect him to have got all the bugs out of the code > yet. The bug had already been answered. If you fail to implement your premise correctly, you have a bug. It doesn't matter if the code is bug-free if the premise is false. In this case, the premise that he can determine primes this way is false. He will have to abandon the cos() thing, for although it works in theory, he'll never get it to work in practice. Besides, the cos() is a red herring (hint: cos(pi*n)). The problem can be made to work EXACTLY (at least up to z=10000) by using rationals (which gmpy supports). His problem is going to take much more than fixing a syntax error. > And he only asked about the specific syntax error not the entire > solution to his homework. If this is indeed homework, and he's supposed to come up with a factorial algorithm, I seriously doubt the teacher would accept gmpy.fac(z-1), so I assume it isn't. > > My advice to Nathan would be: > > 1. If you get a weird syntax error that you don't understand try cutting > the code down to just the bit which generates the error. > > 2. Play around in the interactive interpreter to see what works and what > doesn't. > > 3. If you don't understand why the code doesn't work then get a stuffed > toy, cardboard cutout of a person, or the least technical member of your > family and explain to them in great detail exactly why the code must > (despite error messages to the contrary) be correct. Usually you'll spot > the problem half way through the explanation. > > 4. If you post to this list then post the full error message and traceback. > That way we don't have to guess which quotation marks are the problem. From kay.schluehr at gmx.net Wed Mar 5 23:11:08 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 5 Mar 2008 20:11:08 -0800 (PST) Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: <9a9a239e-52a6-4102-ad03-908def38cbae@p25g2000hsf.googlegroups.com> On 5 Mrz., 13:47, gideon wrote: > Hi Everybody, > > In the context of a master's thesis I'm currently looking into > Python's operational semantics. Even after extensive searching on the > web, I have not found any formal model of Python. Therefore I am > considering to write one myself. To make a more informed decision, I > would like to ask you: > > What previous work has been done that I should be aware of? Currently > I have found exactly nothing on python itself. There is some > interesting work on other, related languages like Smalltalk. > > Which version of Python is the most interesting? Python 3.0, although > it would be a moving target, seems promising. Because it will simplify > the language in some aspects by ditching backwards compatibility (e.g. > old style classes and coercion), the semantics will be more clean. > > Of course I will get, answers to many questions I did not ask. In > fact, I would like you to vent your opinions on this matter. > > Thanks! Specifying Python formally could be a life work if this is anyhow possible. So one has to restrict on certain aspects. I guess the issue most people inside the discipline but also outside academia would be most interested in is evaluation contexts: how are dictionaries and tuples used in evaluation of Python bytecodes? How are stack frames built and what information do they contain? Some of this stuff is beyond what ordinary Pythonistas look at ( other than runtime developers ) and building an abstract Python machine would be invaluable. The class semantics alone might fill a master thesis but then you are also already involved in the question on how dicts and scope are used to store/access contextual information. Specifying how garbage collection works would be another highlight. There is incredibly many stuff lying around and being untouched by language researchers who usually write appendices to the work of the heroes of their own professors ( who really wants to read another work about Scheme or Smalltalk? ). Let us know when you got done something. From jim.vickroy at noaa.gov Tue Mar 25 16:17:16 2008 From: jim.vickroy at noaa.gov (j vickroy) Date: Tue, 25 Mar 2008 14:17:16 -0600 Subject: how to dynamically create class methods ? In-Reply-To: <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> Message-ID: <47E95DCC.7050507@noaa.gov> Arnaud Delobelle wrote: > On Mar 25, 6:13 pm, j vickroy wrote: >> Hello, >> >> Here is some pseudo-code that hopefully illustrates what I want to do: >> >> records = list(...) >> for record in records: >> new_fcn = define_a function_for(record) >> instance = my_new_class_instance() >> setattr(instance, 'myfcn', new_fcn) >> instance.execute() # instance.execute() calls instance.myfcn(*args) >> >> I have looked at some of the functions in the *new* module and >> new.code(...), new.function(...), and new.instancemethod(...) appear to >> do what I want, but I do not know how to use new.code() and >> new.function() -- specifically what its *global* parameter should be. > > The best way to understand how new.function and new.code work is to > look at the Python source. (Objects/funcobject.c and Objects/ > codeobject.c, actual objects are defined in and Include/funcobject.h > Include/code.h). > > However, to create a function dynamically in Python it is often no > more trouble than a def statement: > > Funnily enough I can't think of a nice example ATM so here is a bad > one: say you want to create a function that checks the spelling of a > word, regardless of case. You could a function that returns on-the- > fly created functions that check the spelling of a word like this: > > def get_spellchecker(word): > word = word.upper() > def check_spelling(candidate): > return candidate.upper() == word > return scheck_spelling > > Then > >>>> check_hypo = get_spellchecker('hypopothamus') >>>> check_hypo('Hypopothamus') > True >>>> check_hypo('Big scary mammal') > False > > (Warning: this is all untested). > > HTH > > -- > Arnaud > Thanks for your reply, Arnaud. As per your suggestion, I tried looking at include/code.h and include/funcobject.h (my MS Windows distribution does not appear to contain .c files). However, since I'm not a C programmer, I did not find the .h files all that helpful. What I failed to make clear in my original posting is that the functions must be created dynamically using information in a *record* as the code iterates over all *records*. So, I can not pre-define the functions and then simply select the desired one at run-time. -- jv From userprogoogle-139 at yahoo.co.uk Thu Mar 6 06:43:08 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 6 Mar 2008 03:43:08 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> Message-ID: <7a4adada-a3c3-4f89-8859-baafb6b1324f@b1g2000hsg.googlegroups.com> Hi, Thanks for your very quick response. I have played around a bit more so that both the image and HTML file are in the public_html folder. They are called via python using a relative URL, and have permissions set to 755. Within the HTML file the image is accessed using just "banner.jpg". The actual page displays ok except for the image - so it has the same problem as before. However when the same page is displayed without running through a CGI it displays perfectly. Kind regards, rod On Mar 6, 11:46 am, Bryan Olson wrote: > rodmc wrote: > > [...] > > Python: > > > > f = open("finish.html") > > doc = f.read() > > f.close() > > print doc > > You might need to start with: > > print "Content-Type: text/html" > print > > Is "finish.html" in the right place? When you browse to your > script, can you see that you're getting the html? > > > HTML: > [...] > >

> I suspect a server configuration and/or resource placement problem. > The image has a relative URL, and the user's browser will look for > it on the same path that it used to get the resource served by the > cgi script, up to last '/'. > > Is banner.jpg in the right place, and is your web server configured > to treat everything in that directory as a cgi script, and thus > trying to execute the jpg? If one of those is the problem, just > move banner.jpg, and/or change the relative URL. For example, > SRC="../banner.jpg" will cause the browser to look for the jpg > one directory above. > > Failing that, can look at the web server's log? > > -- > --Bryan From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:49:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:49:41 -0200 Subject: Beginner's assignment question References: Message-ID: En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > Lorenzo Gatti wrote: >> On Mar 1, 3:39 pm, Schizoid Man wrote: >>> As in variable assignment, not homework assignment! :) >>> >>> I understand the first line but not the second of the following code: >>> >>> a, b = 0, 1 >>> a, b = b, a + b >>> >>> In the first line a is assigned 0 and b is assigned 1 simultaneously. >>> >>> However what is the sequence of operation in the second statement? I;m >>> confused due to the inter-dependence of the variables. >> >> The expressions of the right of the assignment operator are evaluated >> before assigning any new values, to the destinations on the left side >> of the assignment operator. >> So substitutig the old values of a and b the second assignment means >> >> a, b = 0, 0 + 1 >> >> Simplifying the Python Reference Manual ("6.3 Assignment Statements") >> a little : >> >> assignment_stmt ::= target_list "="+ expression_list >> >> An assignment statement evaluates the expression list (remember that >> this can be a single expression or a comma-separated list, the latter >> yielding a tuple) and assigns the single resulting object to each of >> the target lists, from left to right. >> >> [...] >> >> WARNING: Although the definition of assignment implies that overlaps >> between the left-hand side and the right-hand side are `safe' (for >> example "a, b = b, a" swaps two variables), overlaps within the >> collection of assigned-to variables are not safe! For instance, the >> following program prints "[0, 2]": >> >> x = [0, 1] >> i = 0 >> i, x[i] = 1, 2 >> print x >> >> Lorenzo Gatti > > Thank you for the explanation. I guess my question can be simplified as: > > First step: a, b = 0, 1 > No problem here as a and b are assigned values. > > Second step: a, b = b, a + b > > Now my question is does b become a + b after a becomes 1 or while a > stays at 0? > > As the assignment occurs simultaneously I suppose the answer is while a > stays at 0. Read the previous response carefully and you'll answer your question. The right hand side is EVALUATED in full before values are assignated to the left hand side. Evaluating b, a+b results in 1, 1. The, those values are assigned to a, b. -- Gabriel Genellina From xng at xs4all.nl Sun Mar 23 08:15:19 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Sun, 23 Mar 2008 13:15:19 +0100 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <47e64a55$0$19418$e4fe514c@dreader22.news.xs4all.nl> jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. I for one can't really answer this question but I wanted to share the reason for that :-) since I worked in the dutch high school equivalent for a number of years. First and most important is I think the objective you want to reach, at my school we had a number of angles: - A math teacher using it as a simpler way of writing examples and explanation while being able to let the students see what is going on and why. - A basic grade computer introduction, to let them feel what automation is about, more like the philosophy of it. - A higher grade computer science (well for high school that is) introduction in to programming. - A explanation what makes the computer tick and how it does it (cpu architecture, memory management etc.) In my opinion python is extremely useful for all of these objectives, except for the last one, this would be more a job for assembler. My school decided not to go in depth to that because we felt it would be out of reach for the majority of the students and we didn't wanted to spoil the students when they decide to take up CS in university later on. -- mph From castironpi at gmail.com Fri Mar 14 17:59:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 14:59:54 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: On Mar 14, 1:47?pm, "Reedick, Andrew" wrote: > > -----Original Message----- > > From: python-list-bounces+jr9445=att.... at python.org [mailto:python- > > list-bounces+jr9445=att.... at python.org] On Behalf Of Aahz > > Sent: Friday, March 14, 2008 2:05 PM > > To: python-l... at python.org > > Subject: RIP: Joseph Weizenbaum > > > Creator of Eliza: > > >http://www-tech.mit.edu/V128/N12/weizenbaum.html > > -- > > How do you feel about creator of Eliza? What is Eliza? From http Mon Mar 3 11:39:52 2008 From: http (Paul Rubin) Date: 03 Mar 2008 08:39:52 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <7xzltgrbyi.fsf@ruckus.brouhaha.com> <5MSdnajOndDRq1banZ2dnUVZ_oSunZ2d@comcast.com> Message-ID: <7xwsoj92xz.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > > User defined types in python are fairly heavyweight compared with the > > built-in types, > > Yet they continue to form the basis of almost all non-trivial Python > programs. Anyway, it's a bit soon to be optimizing. :) Large python programs usually have some classes for complex data structures, but it's not typical Pythonic practice to define new classes for things as small as integers. > > and a type like that is just another thing for the user to have to > > remember. > > How so? A well-written function generally shouldn't depending on the > exact types of its arguments, anyway. By "another thing to remember" I mean doing the right thing should happen with the normal integers that result from writing literals like 1 and 2, without resorting to a nonstandard user defined type. > If someone has written a > function to find (e.g.) the median of a collection of numbers, their > code should already be prepared to accept values of user-defined > numeric types. It's important to be able to write such generic or polymorphic functions, but most typical functions are monomorphic. > If I want to call such a function with my hand-rolled > DivisionSafeInteger type, it should just work, Sure, however, the Pythonic approach is to make the defaults do the right thing without requiring such user-written workarounds. Of course there is occasional unclarity about what the right thing is. > > file) and size_t, so if you pass an off_t to a function that expects a > > size_t as that arg, the compiler notices the error. > > On what compiler? I've never seen a C compiler that would mind any > kind of calculation involving two native, unsigned types. You are right, C is even worse than I remembered. > > But they are > > really just integers and they compile with no runtime overhead. > > They do indeed have run-time overhead, as opposed to (e.g.) meta-types > whose operations are performed at compile-time. Not sure what you mean; by "no runtime overhead" I just mean they compile to the same code as regular ints, no runtime checks. OK, it turns out that for all intents and purposes it looks like they ARE regular ints even at compile time, but in other languages it's not like that. > If you mean they have less overhead than types whose operations > perform run-time checks, then yes, of course that's true. You > specifically stated (then snipped) that you "would be happier if > int/int always threw an error." The beauty of a language with such > extensive support for user-defined types that can be used like > built-in type is that you are free to define types that meet your > needs. But those are not ints then. We're discussing an issue of language design, which is what the behavior of the ordinary, standard, default ints should be. My reason for suggesting int/int->error is that I think it would increase program reliability in general. But that is only if it applies to all the ints by default, with int/int=float being a possible result of a nonstandard user-defined type. From the zen list: "In the face of ambiguity, refuse the temptation to guess." > My understanding is that Python will easily support lots of different > types of just about anything. That's the point. No I don't think so. Also from the zen list: "There should be one-- and preferably only one --obvious way to do it." > > There's an interesting talk linked from LTU about future languages: > > http://lambda-the-ultimate.org/node/1277 > > Thanks, but that just seems to have links to the slides. Is there a > written article, or a video of Mr. Sweeney's talk? I don't think there's an article. There might be video somewhere. I thought the slides were enough to get the ideas across so I didn't have much interest in sitting through a video. From mnordhoff at mattnordhoff.com Thu Mar 6 18:29:26 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 06 Mar 2008 23:29:26 +0000 Subject: Internet Explorer 8 beta release In-Reply-To: References: Message-ID: <47D07E56.4020202@mattnordhoff.com> Colin J. Williams wrote: > Isn't compliance with the W3C standard > the best way of achieving multiple > browser rendering? Exactly. IE 8 is supposed to be significantly less horrible. It won't catch up completely, but perhaps by IE 9 it will. Or this is all a joke, Microsoft buys Opera and shuts them down. (Anyway, I marked the OP as spam.) -- From sjmachin at lexicon.net Mon Mar 10 17:09:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 14:09:34 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> Message-ID: <1a66500d-cea8-4984-8806-3c3ff113c8ea@i12g2000prf.googlegroups.com> On Mar 11, 2:24 am, rockingred wrote: > > In the case where dots are used as a date separator, count the number > of dots (you should also count commas). If a single comma appears and > is preceeded by only numbers or numbers with decimals, assume "foreign > float". Bzzzzt. 1,234 is the integer 1234 to John, and its only a float to Jean if Jean is not a Scots lass :-) From http Mon Mar 17 21:01:21 2008 From: http (Paul Rubin) Date: 17 Mar 2008 18:01:21 -0700 Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <7x7ig0devy.fsf@ruckus.brouhaha.com> WaterWalk writes: > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. Try winpdb.org which despite the name has nothing to do with MS Windows. From matiassurdi at gmail.com Sun Mar 30 08:36:09 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Sun, 30 Mar 2008 14:36:09 +0200 Subject: python ODF library? In-Reply-To: References: Message-ID: Matias Surdi escribi?: > Do yo know any good OpenDocumentFormat library for python? > > I'm starting a project on wich I'll have to programatically modify ODF > text documments, so, after reinventing the wheel, I'd like to know if > already something exists. > > Thanks a lot. > Found it: http://opendocumentfellowship.com/development/projects/odfpy :-) From bj_666 at gmx.net Sat Mar 15 02:16:43 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 06:16:43 GMT Subject: request for Details about Dictionaries in Python References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> Message-ID: <6417u2F29qj9jU3@mid.uni-berlin.de> On Fri, 14 Mar 2008 17:06:00 +0000, Matt Nordhoff wrote: > Hmm, if Perl's on-disk hash tables are good, maybe someone should port > them to Python, or maybe someone already has. I don't know Perl's on-disk hash tables but there is a `shelve` module in the standard library. Ciao, Marc 'BlackJack' Rintsch From rockxuan at gmail.com Tue Mar 18 03:58:51 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:58:51 -0700 (PDT) Subject: replicas super quality watches & jewellery fashion Message-ID: <6c79f065-1627-4af3-a0d3-dfddab0ed606@d4g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From darkwind.87 at gmail.com Tue Mar 25 18:02:00 2008 From: darkwind.87 at gmail.com (Dark Wind) Date: Tue, 25 Mar 2008 15:02:00 -0700 Subject: what does ^ do in python Message-ID: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Hi, In most of the languages ^ is used for 'to the power of'. In python we have ** for that. But what does ^ do? I could not get it just by using it ... some examples are: 1^1 returns 0 2^2 returns 0 1^4 returns 5 4^1 returns 5 3^5 returns 6 5^3 returns 6 ...... just curious Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Mar 28 16:34:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Mar 2008 20:34:16 GMT Subject: Problem with format string and unicode References: Message-ID: <655328F2e1u8fU1@mid.uni-berlin.de> On Fri, 28 Mar 2008 21:13:00 +0100, Hans Martin wrote: > this is probably a trivial problem, but a google search for "python" > and "unicode" and" format string" gives too many hits: If I specify > e.g. "%20s" in a format string and the string value contains UTF-8 > stuff (differing number of bytes per character), the length of the > resulting string (in characters) varies. How can I fix this? Use unicode strings instead. Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Wed Mar 12 07:30:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Mar 2008 12:30:41 +0100 Subject: Max File Size References: <1e8a2f49-e40b-4a6d-bc48-6d4f9a648c6d@s12g2000prg.googlegroups.com> Message-ID: <63pt70F28u3flU1@mid.uni-berlin.de> xkenneth wrote: > Is the max file size a relevant issue in python anymore? I know OS X > has a max file size of 8 exabytes and I'm not sure about the latest > version of Ubuntu. Does python have an independent file size limit, or > is it dependent upon the OS it was compiled on? The latter should be the case. E.g. ZODB can grow larger than 2GB. Diez From gabriel.rossetti at mydeskfriend.com Mon Mar 10 13:54:49 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Mon, 10 Mar 2008 18:54:49 +0100 Subject: execute python script question Message-ID: <47D575E9.8040507@mydeskfriend.com> Hello, I have been developping something in python that has the following hierarchy : project/src/myPackage/ project/src/myPackage/__init__.py project/src/myPackage/module1.py project/src/myPackage/module2.py project/src/myPackage/test/ project/src/myPackage/test/__init__.py project/src/myPackage/test/test_module1.py project/src/myPackage/test/test_module2.py project/src/myPackage/mySubPackage/__init__.py project/src/myPackage/mySubPackage/module1.py project/src/myPackage/mySubPackage/test/ project/src/myPackage/mySubPackage/test/__init__.py project/src/myPackage/mySubPackage/test/module1.py ... up until now, I had been executing my modules from inside project/src/myPackage/ but I realised that that is wrong (while implementing the test suite) and that since all my modules had relative imports (if module2 needed module1, it would just say : import module1) I changed them to myPackage.module1 for example. Now my test suite is happy, I can say : test.sh myPackage.test and it tests everything. The only problem now is that I can't execute the scripts from inside or outside the myPackage dir, I get this : from outside : Traceback (most recent call last): File "myPackage/module1.py", line 15, in from myPackage import constants, utils ImportError: No module named myPackage or if from inside it : Traceback (most recent call last): File "module1.py", line 15, in from myPackage import constants, utils ImportError: No module named myPackage can anybody please help me? I don't think I understood the whole package/module thing I think... I think some people do some sort of importing in the __init__.py files but I'm not sure this helps in this case. Thanks, Gabriel -- www.mydeskfriend.com PSE - C (EPFL) 1015 Ecublens, Switzerland Tel: +41 21 601 52 76 Mob: +41 76 442 71 62 From wescpy at gmail.com Wed Mar 19 00:41:21 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 18 Mar 2008 21:41:21 -0700 (PDT) Subject: What Programming Languages Should You Learn Next? Message-ID: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> http://it.slashdot.org/it/08/03/18/1633229.shtml it was surprising and disappointing that Python was not mentioned *anywhere* in that article but when someone replied, it sparked a long thread of post-discussion. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bignose+hates-spam at benfinney.id.au Tue Mar 4 19:02:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 05 Mar 2008 11:02:38 +1100 Subject: for-else References: Message-ID: <87r6eq82ch.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > But then this article: > http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel_language_features > has shown me that my problems with the 'else' of the 'for' mostly > come from just its bad naming. The converge language is yet another > very Python-like language, and it uses a better naming (the word > "exhausted" is long and has a complex spelling for non-English > speakers, so it's not perfect): > > for ...: > ... > exhausted: > ... > broken: > ... Rather than adding new keywords, I think the above would be better spelled using the exception keywords:: for foo in bar_sequence: # normal iteration spam(foo) if funky(foo): break except StopIteration, exc: # the iterator stopped normally eggs(exc) else: # the iterator exited abnormally, i.e. 'break' sausage() finally: # always executed, even on 'break' beans() -- \ ?[T]he question of whether machines can think [...] is about as | `\ relevant as the question of whether submarines can swim.? | _o__) ?Edsger W. Dijkstra | Ben Finney From python at rgbaz.eu Thu Mar 20 05:26:22 2008 From: python at rgbaz.eu (Python.Arno) Date: Thu, 20 Mar 2008 10:26:22 +0100 Subject: Calling Mac programs from Python instead of from AppleScript In-Reply-To: References: Message-ID: <8BB9867E-36A1-4B6A-9B8A-BB41A66D19FA@rgbaz.eu> On 19 mrt 2008, at 20:41, dvschorre at sbcglobal.net wrote: > > When I'm running Script Editor, I can get Maya to draw a sphere by > typing: > > tell application "Maya" > execute "sphere" > end tell > > When I try this using Python, I get this error message: > > IDLE 1.2.2 >>>> app('Maya').execute('sphere') > > Traceback (most recent call last): > File "", line 1, in > app('Maya').execute('sphere') > NameError: name 'app' is not defined >>>> > > Maybe I need to load some libraries first. > I never used applescript more than to record some clicks but you might try tell application "/Applications/Autodesk/maya2008/Maya" (replace maya2008 with you app's foldername) or even tell application "/Applications/Autodeks/maya2008/Maya/Contents/MacOS/ Maya" > Please help me to get started. > like any other VFX app, maya is also adding python libs you can access MEL commands from a python library: http://www.autodesk.com/us/maya/docs/Maya85/wwhelp/wwhimpl/common/html/wwhelp.htm?context=DeveloperResources&file=Introduction_to_Maya_Python_API.html > Thanks > Dewey V. Schorre > gr Arno Beekman From nagle at animats.com Tue Mar 25 00:17:16 2008 From: nagle at animats.com (John Nagle) Date: Mon, 24 Mar 2008 21:17:16 -0700 Subject: "Soup Strainer" for ElementSoup? In-Reply-To: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> Message-ID: <47e87a88$0$36376$742ec2ed@news.sonic.net> erikcw wrote: > Hi all, > > I was reading in the Beautiful Soup documentation that you should use > a "Soup Strainer" object to keep memory usage down. > > Since I'm already using Element Tree elsewhere in the project, I > figured it would make sense to use ElementSoup to keep the api > consistent. (and cElementTree should be faster right??). > > I can't seem to figure out how to pass ElementSoup a "soup strainer" > though. > > Any ideas? > > Also - do I need to use the extract() method with ElementSoup like I > do with Beautiful Soup to keep garbage collection working? > > Thanks! > Erik I really should get my version of BeautifulSoup merged back into the mainstream. I have one that's been modified to use weak pointers for all "up" and "left" links, which makes the graph cycle free. So the memory is recovered by reference count update as soon as you let go of the head of the tree. That helps with the garbage problem. What are you parsing? If you're parsing well-formed XML, BeautifulSoup is overkill. If you're parsing real-world HTML, ElementTree is too brittle. John Nagle From martin at v.loewis.de Fri Mar 21 17:01:07 2008 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 22:01:07 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E42213.50208@v.loewis.de> > eval() somehow decoded the passed expression. No question. It did not > use 'ascii', nor 'latin2' but something else. Why is that? Why there is > a particular encoding hard coded into eval? Which is that encoding? (I > could not decide which one, since '\xdb' will be the same in latin1, > latin3, latin4 and probably many others.) I think in all your examples, you pass a Unicode string to eval, not a byte string. In that case, it will encode the string as UTF-8, and then parse the resulting byte string. Regards, Martin From debl2NoSpam at verizon.net Sun Mar 2 20:49:03 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Mon, 03 Mar 2008 01:49:03 GMT Subject: Book Recomendations In-Reply-To: References: Message-ID: Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira Different people have different learning styles. Two books I like are Wesley Chun's Core Python Programming (2nd edition) and Mangnus Hetland's Beginning Python. Have fun with Python. I discovered it about 7 years ago, use it by choice for my intermittent programming requirements and find it a pleasure to use. Also this group is very helpful. (My programming experience also goes back to Algol, Basic and assembler circa 1965. Which makes me middle aged, but not necessarily experienced :) ) David From andrei.avk at gmail.com Sat Mar 15 17:25:21 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Sat, 15 Mar 2008 14:25:21 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> Message-ID: <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> On Mar 15, 3:54?pm, Unknown wrote: > Hi, > I've got this code : > > cb = open("testfile", "r+") > f = cb.readlines() > for line in f: > ? ? rx = re.match(r'^\s*(\d+).*', line) > ? ? if not rx: > ? ? ? ? continue > ? ? else: > ? ? ? ? serial = rx.group(1) > ? ? ? ? now = time.time() > ? ? ? ? today = time.strftime('%Y%m%d00', time.localtime(now)) > ? ? ? ? todayVal, serialVal = long(today), long(serial) > ? ? ? ? if todayVal <= serialVal: > ? ? ? ? ? ? todayVal = serialVal + 1 > ? ? ? ? else: > ? ? ? ? ? ? todayVal += 1 > ? ? ? ? line = string.replace(line, serial, "%d" %todayVal) > ? ? ? ? cb.write(line + "\n") > ? ? ? ? print 'Updated serial from "%s" to "%d"' % ( serial, todayVal ) > ? ? ? ? break ? ? ? > cb.close() > > I was expecting to replace the old value (serial) with the new one > (todayVal). Instead, this code *adds* another line below the one found... > > How can I just replace it? > > Thanks for your help :-) What you want to do is either 1. load everything up into a string, replace text, close file, reopen it with 'w' flag, write string to it. OR if file is too big, you can read each line, replace, write to a temp file, then when done move the file over the old one. I think there are technical reasons why file-reading and iteration api are not very suitable for reading and writing at the same time. I think you'd have to set the filepointer back one line (it can be manipulated by giving it bytes ahead/back, so that would be difficult in itself), then delete the line and then write new string. It may be even harder than that, I'm sure someone can explain this much better, but you're far better off with using one of the 2 methods above.. HTH, -ak From gandalf at shopzeus.com Fri Mar 28 11:03:39 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 28 Mar 2008 16:03:39 +0100 Subject: How do I reconnect a disconnected socket? In-Reply-To: References: Message-ID: <47ED08CB.9010809@shopzeus.com> > This is what I've got right now: > > #! /usr/bin/env python > import socket, string > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > def doconn(): > sock.connect(("localhost", 1234)) > def dodiscon(): > sock.close() > doconn() > > doconn() > > while (1): > buffer = sock.recv(1024) > if not buffer: > dodiscon() > sock.recv(1024) can return zero bytes of data indicating that no data arrived yet. It does not mean that you have been disconnected. This is especially true when you do nothing but recv, recv, recv() in an infinite loop. I recommend that you use select.select to see if there is some data that can be read. Call socket.recv() only when you know that it will not fail. Best, Laszlo From xelapond at gmail.com Mon Mar 31 14:49:21 2008 From: xelapond at gmail.com (Alex Teiche) Date: Mon, 31 Mar 2008 11:49:21 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> Message-ID: On Mar 30, 3:50 pm, Benjamin wrote: > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > I am pretty new to Python, and have never learned C++. I am trying to > > implement the following thing into my python application: > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > it, but I could not get this specific thing to work. Can someone give > > me some hints as to get it working in Python? > > What problems are you having? > > > > > Thanks a ton, > > > Alex Thanks everyone for your help. I found the example to be particularly helpful, and I have made a simplified version just to display an icon with a quit button in its menu. Once I know how to do that I will incorporate it into my larger program, with more options and the ability show messages. The problem is, it doesn't work, and I can't find out what's wrong. Can you give me some hints? Here is the code: import sys from PyQt4 import QtGui, QtCore class trayIcon(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #********Create Actions for the Tray Menu********# self.quitAction = QtGui.QAction(self.tr("&Quit"), self) QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) create_tray_icon() self.composeAction.setEnabled(visible) QtGui.QWidget.setVisible(self, visible) self.trayIcon.show() def create_tray_icon(self): self.trayIconMenu = QtGui.QMenu(self) self.trayIconMenu.addAction(self.composeAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) self.trayIcon.setIcon(bad.svg) app = QtGui.QApplication(sys.argv) sys.exit(app.exec_()) From zjs2k at yahoo.com Tue Mar 25 20:59:04 2008 From: zjs2k at yahoo.com (Jinshi) Date: Tue, 25 Mar 2008 20:59:04 -0400 Subject: urllib2.urlopen gives error 10060 Message-ID: Hello, everyone, I am quite new to python and I don't know how to solve this problem. I hope someone can help me. I just did a test in python shell: >>> import urllib2 >>> urllib2.urlopen("http://python.org") Traceback (most recent call last): File "c:\Zope\", line 1, in ? File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 130, in urlopen return _opener.open(url, data) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 376, in _open '_open', req) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Zope\2.10.5\Python\Lib\urllib2.py", line 996, in do_open raise URLError(err) URLError: I am using Windows XP and the python was installed along with a zope installation. I can get on internet with Firefox browser without any proxy setting. I can do the test successfully on another computer on the same home network. I just don't know what happens to this one. Can anyone help me to troubleshoot this? Any suggestion would be really appreciated. Jin From nanjundi at gmail.com Wed Mar 5 10:29:24 2008 From: nanjundi at gmail.com (Nanjundi) Date: Wed, 5 Mar 2008 07:29:24 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> Message-ID: <51f4bce3-8561-4149-9b3b-e436bbee8ee7@u69g2000hse.googlegroups.com> On Mar 4, 3:13 pm, Mensanator wrote: > On Mar 4, 12:32 pm, Nanjundi wrote: > > > > Does seeding ( random.seed ) random with time fix this? It should. > > I suppose that depends on how long it takes factorint() to > process a number. If the seed is reset before the next clock > tick, you will get the same random numbers as the previous > iteration. Alright, then make it constant and don't worry about the clock tick. >>> for i in xrange(10): ... f1 = random.choice(f) ... print f1, ... f2 = random.choice(f) ... print f2, ... C = f1*f2 ... ff = None ... ff = sympy.factorint(C) ... print ff ... random.seed(i) ... 5573 5171 [(5171, 1), (5573, 1)] 8537 7673 [(7673, 1), (8537, 1)] 2063 8573 [(2063, 1), (8573, 1)] 9551 9473 [(9473, 1), (9551, 1)] 2909 5659 [(2909, 1), (5659, 1)] 2897 1789 [(1789, 1), (2897, 1)] 6361 7541 [(6361, 1), (7541, 1)] 8017 8293 [(8017, 1), (8293, 1)] 3671 2207 [(2207, 1), (3671, 1)] 2803 9629 [(2803, 1), (9629, 1)] > Frankly, I don't understand why factorint() reseeds at all. Read the doc: * The rho algorithm is a Monte Carlo method whose outcome can be affected by changing the random seed value. * > Doesn't Random automatically initialize the seed? > Doesn't constantly reseeding degrade the performance of the > random number generator? With Robert Kern's patch, the reseeding > is no longer a constant, fixing the immediate symptom. Does it matter? The factorint reseeds using a constant seed (1234). > > But what if _I_ wanted to make a repeatable sequence for test > purposes? Wouldn't factorint() destroy my attempt by reseeding > on every call? Repeatable sequence? save it and reuse! Think about "What if"s doesn't get any work done. -N From gherron at islandtraining.com Fri Mar 28 16:29:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 28 Mar 2008 13:29:40 -0700 Subject: Astronomy Fits format and gif.save(path) In-Reply-To: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> References: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> Message-ID: <47ED5534.6020001@islandtraining.com> W. Watson wrote: > In what library would I find gif.save(path), where path is the name and path > of a file, and the method would produce a file in a gif format? > > Is there a fits.save(path) somewhere? fits is commonly used in astronomical > work. > You may want to install PIL (the Python Image Library) for this: http://www.pythonware.com/products/pil/ From jn.nntp.scrap001 at wingsandbeaks.org.uk Sat Mar 1 12:29:21 2008 From: jn.nntp.scrap001 at wingsandbeaks.org.uk (Jeremy Nicoll - news posts) Date: Sat, 1 Mar 2008 17:29:21 +0000 Subject: Import, how to change sys.path on Windows, and module naming? Message-ID: If I understand correctly, when I import something under Windows, Python searches the directory that the executing script was loaded from, then other directories as specified in "sys.path". I assume there are standard locations inside my installed Python - in my case inside: C:\Program Files\~P-folder\Python25 - where I could put my modules and they'd automatically be found? But even if that's the norm, I don't want to put my own modules in such directories, partly because a uninstall or reinstall or upgrade of Python might lose my stuff, and partly because I don't believe in mixing distributed code with home-grown code. However I'm quite happy to have a line or three of code to alter sys.path to suit my set-up, if that's a normal way to handle this problem. Where does one do that? Also, I presume that there's a risk that the module name that I give to any of my utilities will clash with a present or future standard module's name. Does that mean that I should give my own modules names like "JNfoo" rather than "foo", etc? Or something like "JNutils.foo"? -- Jeremy C B Nicoll - my opinions are my own. From python.list at tim.thechases.com Wed Mar 26 14:46:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 26 Mar 2008 13:46:06 -0500 Subject: what does ^ do in python In-Reply-To: References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <47EA99EE.5030304@tim.thechases.com> >> HOw can we use express pointers as in C or python? > > Traceback (most recent call last): > File "", line 1, in > File "parser.py", line 123, in parse_text > tree = language.parse_text(text) > File "english.py", line 456, in parse_text > tree = self.parse_sentence(sentence) > File "english.py", line 345, in parse_sentence > raise ParserError, "can't parse %r" % sentence > ParserError: can't parse 'HOw can we use express pointers as in C or > python?' Possible "express pointers": http://www.geocities.com/derwin_b/sr91sign.jpg http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg If those meet the OP's need, I recommend urllib2 and PIL. -tkc From bj_666 at gmx.net Mon Mar 24 03:05:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Mar 2008 07:05:34 GMT Subject: Multiline CSV export to Excel produces unrecognized characters? References: <4f6f122f-45bb-4aa5-b9c9-5eb3e84a0964@i7g2000prf.googlegroups.com> Message-ID: <64p25uF2c2qidU2@mid.uni-berlin.de> On Sun, 23 Mar 2008 23:30:11 -0700, felciano wrote: > The following reproduces the problem in python 2.5: > > import csv > row = [1,"hello","this is\na multiline\ntext field"] > writer = csv.writer(open("test.tsv", "w"), dialect="excel-tab", > quotechar='"') > writer.writerow(row) > > When opening the resulting test.tsv file, I do indeed see a cell with > a multi-line value, but there is a small boxed question mark at the > end of each of the lines, as if Excel didn't recognize the linebreak. > > Any idea why these are there or how to get rid of them? Any chance you are doing this on Windows and Excel doesn't like the return+linefeed line endings that Windows produces when writing files in text mode? Try 'wb' as mode for the output file. Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Sat Mar 8 15:27:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:14 -0800 (PST) Subject: for-else References: Message-ID: > The idea of the if-else is: > . ?depending on some condition either do this or do something else, > . ?don't do them both. yes = the loop completed. 'else' isn't rechecking a piece of the loop, it's checking the loop. Does it test successfully--- not the loop condition, the loop? What is 'if a loop'? Make sense, I hold it does. (Holding is good-- something I can drop and give to someone else.) If 'else' gets hit, I didn't do the loop. From gagsl-py2 at yahoo.com.ar Mon Mar 17 08:48:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 10:48:40 -0200 Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > i have a problem with this modules py2exe + pywinauto + sendkeys used > together. > > In my script i'm using this expression > app.window_(title="SJphone").Edit.TypeKeys("Test is > running",with_spaces=True) > > TypeKeys is using SendKeys module i suppose. Does it work as a normal script, without using py2exe? > my setup.py looks like that: > > from distutils.core import setup > import py2exe > > setup( > options = {"py2exe": {"compressed": 1, > "optimize": 0, > "bundle_files": 1, > "packages": ["encodings", "pywinauto", > "pywinauto.controls", "pywinauto.tests"] } }, > zipfile = None, > console=["hosts.py"] > ) Perhaps you have to include SendKeys explicitely. I think pywinauto doesn't require SendKeys, but uses it if already installed. -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 20 17:37:46 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 16:37:46 -0500 Subject: Code folder with Emacs In-Reply-To: <13u5li6kspler51@corp.supernews.com> References: <13u5li6kspler51@corp.supernews.com> Message-ID: I don't use emucks, but in vim its very simple. :set foldmethod=indent and instantly anything indented (ie: all python blocks) are folded. to unfold a fold zo to close an opened fold zc that outta be enough to get any fellow vim-heads going =) 2008/3/20, Grant Edwards : > > Has anybody figured out how to do code folding of Python source > files in emacs? > > I tried "hide-show" minor mode, but it doesn't really work for > Python code: the only think it knows how to hide/show are > function bodies. It can't do normal things like hide/show a > code block like it can for other languages. > > Google also found my "folding mode", but that's based on > user-inserted tokens and isn't syntax aware. > > -- > Grant > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Mar 21 16:56:43 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 21 Mar 2008 21:56:43 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <47E4210B.1080505@v.loewis.de> > Well at least this is what I think. If I'm not right then please explain > why. I think your confusion comes from the use of the interactive mode. PEP 263 doesn't really apply to the interactive mode, hence the behavior in interactive mode is undefined, and may and will change across Python versions. Ideally, interactive mode should assume the terminal's encoding for source code, but that has not been implemented. Regards, Martin From kf9150 at gmail.com Mon Mar 31 18:12:16 2008 From: kf9150 at gmail.com (Kelie) Date: Mon, 31 Mar 2008 15:12:16 -0700 (PDT) Subject: PyQt - How to prevent a dialog being resized? Message-ID: Hello, My question is as subject. I tried something like this and it doesn't work. def resizeEvent(self, event): self.size = event.oldSize() Any hint? Thank you. From apardon at forel.vub.ac.be Thu Mar 13 04:22:20 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Mar 2008 08:22:20 GMT Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: On 2008-02-28, Steven D'Aprano wrote: > On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: > >> Hi! >> Can somebody of you make me a sample how to define a function based on >> "call by reference" ??? > > Python doesn't do call by reference. Nor does it do call by value. Please > pay no attention to anyone who says it does. Whatever python has for a calling convention, it is close enough that naming it "call by reference" gives people a reasonable idea of what is going on. > Instead, read this: > > http://effbot.org/zone/call-by-object.htm Which IMO isn't very helpfull. The mentioning of e.g. mutable just confuses things since it really isn't the issue. AFAICS people don't have a problem with understanding the calling convention of python. They have a problem understanding the assignment semantics. It is just that these problems of understanding most often surface when an assignment is made to a parameter which makes them think they don't understand the calling convention. The important thing to understand is that an assigment in python is not copying the contends into the variable but is passing a reference/binding the name to a new object. After the variable is assigned to it doesn't refer to the same object with a new contend. It refers to a different object. -- Antoon Pardon From michael.pearmain at tangozebra.com Mon Mar 3 04:43:32 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 3 Mar 2008 01:43:32 -0800 (PST) Subject: Regex loop question Message-ID: <7aae0102-51bd-4701-a116-60b8d9698450@s13g2000prd.googlegroups.com> Hi Experts, I've written a peice of code that works fine and fits, and passes values into a peice of SPSS code, the problem is that it is not dynamic, and so i though about how i can make it dynamic, (other code may not have upto 10 some may have more) and came up with regex for an idea, but i can't seem to make it work, can anyone offer any advice? Below is current working code time_variables = {"ActivityTime": "Activity_Time", "ExposureTime_Last":"Exposure_Time_1", "ExposureTime_Last2":"Exposure_Time_2", "ExposureTime_Last3":"Exposure_Time_3", "ExposureTime_Last4":"Exposure_Time_4", "ExposureTime_Last5":"Exposure_Time_5", "ExposureTime_Last6":"Exposure_Time_6", "ExposureTime_Last7":"Exposure_Time_7", "ExposureTime_Last8":"Exposure_Time_8", "ExposureTime_Last9":"Exposure_Time_9", "ExposureTime_Last10":"Exposure_Time_10"} for Var in time_variables.keys(): time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . COMPUTE %s = number(%s, TIME8). VARIABLE LABEL %s. VARIABLE LEVEL %s (SCALE). FORMATS %s (TIME8). VARIABLE WIDTH %s (8). EXECUTE.""") %(Var, Var, Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var]) spss.Submit(time_manips) Now to make it dynamic i've gone for the following... reg_time = re.compile("^ExposureTime_Last([0-9]*)$") reg_Activity = re.compile("^ActivityTime") for Var in time_variables.keys(): if reg_time.match(Var): match = reg_time.match(Var) E_time = "Exposure_Time_%s" % match.groups()[0] else: match = reg_time.match(Var) match.groups()[0] = "Activity_Time" time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . COMPUTE %s = number(%s, TIME8). VARIABLE LABEL %s. VARIABLE LEVEL %s (SCALE). FORMATS %s (TIME8). VARIABLE WIDTH %s (8). EXECUTE.""") %(Var, Var, Var,time_variables[Var],Var,time_variables[Var],time_variables[Var],time_variables[Var],time_variables[Var]) print(time_manips) All help welcome, or if a different approach is better please let me know Mike From steve at REMOVE-THIS-cybersource.com.au Tue Mar 11 13:50:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 11 Mar 2008 17:50:36 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> Message-ID: <13tdhjcd2fhp17d@corp.supernews.com> On Tue, 11 Mar 2008 03:14:54 -0700, Lie wrote: >> Regarding the number of callbacks: you can as well pass an object that >> has several methods to call. > > If you passed an object that has several methods to call (using tuple or > list) and you want to handle several softexceptions and ignore some > others, you must still pass an empty methods to the one you want to > ignore, cluttering the caller's code by significant degree: > > def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, > DO_NOTHING)): > if a == 0: raise callback(0) > try: > a += b > except ZeroDivisionError: > raise callback(1) > if a <= 0: raise callback(2) > raise callback(3) > return a > > somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, > DO_NOTHING)) Yes, you are right that this is a bad idea. But it is a bad idea regardless of whether you use callbacks or SoftExceptions. In your example above, you seem to have accidentally written "raise callback" when you (probably) meant to just call the callback. That's significant because it shows that replacing the callback is still just as cluttered, and still puts a large burden on somefunc() to perform every test that callers might want to perform. This is a bad idea because you are tightly coupling somefunc() to the specific needs of some arbitrary callers. You should aim to have loose coupling between functions, not tight. Tight coupling should be avoided, not encouraged. In most circumstances, the right place to put the various tests is in the caller, not in somefunc(). -- Steven From furkankuru at gmail.com Tue Mar 25 19:45:29 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 01:45:29 +0200 Subject: Filtering a Python list to uniques In-Reply-To: References: Message-ID: <3a4a8f930803251645g1aed792bv5f0bceaaf2bc650e@mail.gmail.com> set(lstone) works fine in python 2.5.1 Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] >>> set(lstone) set([1, 2, 3, 4, 5, 6]) On 3/26/08, kellygreer1 wrote: > > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > Is there a page on this in the Python in a Nutshell or the Python > Cookbook? > Did I miss something? > > Kelly Greer > kellygreer1 at nospam.com > change nospam to yahoo > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From bronger at physik.rwth-aachen.de Wed Mar 19 04:44:06 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 19 Mar 2008 09:44:06 +0100 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> Message-ID: <87fxunumqx.fsf@physik.rwth-aachen.de> Hall?chen! Paul Rubin writes: > [...] > > Re Haskell: I've been spending a lot of time on Haskell recently, > though I haven't done anything nontrivial with it yet (just some > small stuff). But I think it's better for complex program > development than Python is, Could you elaborate on this? (Sincere question; I have almost no idea of Haskell.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From fetchinson at googlemail.com Mon Mar 10 02:32:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 9 Mar 2008 23:32:39 -0700 Subject: image matching algorithms Message-ID: Hi all, There are a number of free tools for image matching but it's not very easy to decipher the actual algorithm from the code that includes db management, GUI, etc, etc. I have my own image database and GUI so all I need is the actual algorithm preferably in pseudo code and not in the form of a research paper (from which I also found a lot but since I'm not that much interested in the actual science of image recognition this seems like an over kill). My understanding of image matching is that it works by first calculating N real numbers for an image and defining a metric for pairs of N-tuples. Images are similar if their distance (defined by the metric) is small. The various free tools differ by their chosen optimization paths and their degree of specialization. My preference would be, 1. Doesn't really matter how long it takes to compute the N numbers per image 2. Lookups should be fast, consequently N should not be too large (I guess) 3. It should be a generic algorithm working on generic images (everyday photos) 4. PIL should be enough for the implementation So if anyone knows of a good resource that is close to being pseudo code I would be very grateful! Cheers, Daniel From __peter__ at web.de Thu Mar 27 05:01:39 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Mar 2008 10:01:39 +0100 Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: Grimsqueaker wrote: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? With Dan's functions in cartesian.py you can do the following: >>> from cartesian import * >>> def count(digits): ... args = [] ... while 1: ... args.append(digits) ... for n in string_cartesian_product(*args): ... yield n ... >>> from itertools import islice >>> print " ".join(islice(count("abc"), 30)) a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc Peter From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:09:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:09:32 -0300 Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo escribi?: > I'm using a md5 hash encoded with base64.urlsafe_b64encode as a > parameter of a URL used to confirm a registration in a site. It has > been working great. > > The url is like this: > > http://example.com/ce?i=878&h=kTfWSUaby5sBu9bIfoR87Q== > > Now i need to match that URL in a certain text and i realized that > urlsafe_b64encode uses the "=" character so i can't just use \w{24} to > match the parameter. > > What i need to know is where can an equal char appear in a > urlsafe_b64encoded string?: > > a)only at end; > b)both at the end and at the begginig; > c)anywhere in the string; > > A sure answer will make my regexp safer. Only at the end. The encoded string has 4*n chars when the input string has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has 4*(n+1) chars right padded with 2 or 1 "=" chars. If your input has 3n chars, the output won't have any "=" > In another point, does the "=" char make it urlunsafe? I guess not > because i believe it would only be unsafe if the equal appeared like > in "&var=" and since there are no "&" in the string than there is no > problem right? Or wrong? I guess not, but you should check the relevant RFCs. Or at least check that your server can always parse the request. -- Gabriel Genellina From mail at timgolden.me.uk Thu Mar 27 07:22:18 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 11:22:18 +0000 Subject: Problem with write binary data to OLE field in Access In-Reply-To: <47EA77FB.3080706@gmail.com> References: <47EA77FB.3080706@gmail.com> Message-ID: <47EB836A.3010506@timgolden.me.uk> lialie wrote: [... snip slightly confused indication that reading back a binary item using GetChunk appears to double its length ...] Well I don't know why this should be happening, but I do at least have a few suggestions: 1) Try using ADODB.Stream instead of GetChunk etc. 2) Try using the adodbapi dbapi-compliant wrapper 3) Try using ODBC (via PyODBC, CeODBC etc.) I've no idea if any of these will do any better but at least it gives you some possibilities :) TJG From frank at chagford.com Wed Mar 12 01:10:54 2008 From: frank at chagford.com (Frank Millman) Date: Tue, 11 Mar 2008 22:10:54 -0700 (PDT) Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: <76ce374e-fa63-4885-8198-d2b383696a48@s8g2000prg.googlegroups.com> gargonx wrote: > Say i have the two methods: > > def ReturnMethod(request, x): > if request is True: > return x > else: print "No String for you...False!" > > def SendMethod(request): > xstring = "Some text" > ReturnMethod(request, xstring) > > SendMethod(True) > > Why does ReturnMethod not return the string x? I do believe it is > returning with a NoneType. > Any help would be greatly obliged > > Thanks, Josh ReturnMethod() is executed, but you do nothing with the result. Try one of the following - def SendMethod(request): xstring = "Some text" print ReturnMethod(request, xstring) def SendMethod(request): xstring = "Some text" return ReturnMethod(request, xstring) HTH Frank Millman From dotancohen at gmail.com Thu Mar 13 19:19:11 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 14 Mar 2008 01:19:11 +0200 Subject: This actually works. In-Reply-To: <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> Message-ID: <880dece00803131619l8df9a07w365d482d2af7090a@mail.gmail.com> On 14/03/2008, Dustan wrote: > you.screw() Ah, you are pushing sex pills. > self.thank(God, encapsulation) And bibles? Interesting combination. > not self.want_to_know(you.screw.func_code) Unsubscribe? I know better... Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From fuzzyman at gmail.com Sat Mar 29 16:34:27 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 29 Mar 2008 13:34:27 -0700 (PDT) Subject: Buffer Overflow with Python 2.5 on Vista in import site Message-ID: A very odd error with Python 2.5 (both 2.5.1 and 2.5.2 from the official msi installers and running on Vista under Parallels on the Mac). 'import site' fails due to a string in sys.path that contains a huge number of null bytes. The error is actually in ntpath - I adjusted it to print the paths it is working with and a string on encountering the bad path. Because 'import site' is executed twice with the following code I snipped the first dump and only print the one with the traceback: C:\Users\Administrator>python -c "import site" [snip] 'import site' failed; use -v for traceback set(['c:\\python25\\lib\\plat-win', 'c:\\windows\\system32\ \python25.zip', 'c:\\ python25', 'c:\\python25\\lib\\lib-tk', 'c:\\users\\administrator', 'c: \\python2 5\\dlls', 'c:\\python25\\lib', 'c:\\python25\\lib\\site-packages']) ******************** BAD PATH ******************** "C:\\Python25\\lib\\site-packages\\\x00\x05\x16\x07\x00\x02\x00\x00Mac OS X \x00\x02\x00\x00\x00\t\x00\x00\x002\x00\x00\x0e \xb0\x00\x00\x00\x02\x00\x00\x 0e\xe2\x00\x00\x01\x1e \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00AT TR\x00\x00\x00!\x00\x00\x0e\xe2\x00\x00\x00\x98\x00\x00\x00 \x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x98\x00\x00\x00 \x00\x0 0\x15com.macromates.caret\x00x\x9c\xab\xe6R\x00\x82\xe4\xfc\x9c \xd2\xdc<\x05[\x0 5\x03k0?'3/\x15\xc2\xab\x05\x00\x8b\x99\x08\x1d \x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ [snip a load of null bytes] x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x1eThis resource fork intent ionally left blank \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 [snip a load more null bytes] 0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 0\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x1e \x00\x00\x00\x00\x0 0\x00\x00\x00\x00\x1c\x00\x1e\xff\xff" Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\site.py", line 417, in main() File "C:\Python25\lib\site.py", line 402, in main paths_in_sys = addsitepackages(paths_in_sys) File "C:\Python25\lib\site.py", line 206, in addsitepackages addsitedir(sitedir, known_paths) File "C:\Python25\lib\site.py", line 169, in addsitedir addpackage(sitedir, name, known_paths) File "C:\Python25\lib\site.py", line 141, in addpackage dir, dircase = makepath(sitedir, line) File "C:\Python25\lib\site.py", line 67, in makepath dir = os.path.abspath(os.path.join(*paths)) File "C:\Python25\lib\ntpath.py", line 500, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str Odd. Anyone got any clues? Michael Foord http://www.ironpythoninaction.com From Robert.Bossy at jouy.inra.fr Wed Mar 12 09:44:17 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 12 Mar 2008 14:44:17 +0100 Subject: Creating a file with $SIZE In-Reply-To: <47D7D5F2.8050303@mattnordhoff.com> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> Message-ID: <47D7DE31.9090504@jouy.inra.fr> Matt Nordhoff wrote: > Robert Bossy wrote: > >> k.i.n.g. wrote: >> >>> I think I am not clear with my question, I am sorry. Here goes the >>> exact requirement. >>> >>> We use dd command in Linux to create a file with of required size. In >>> similar way, on windows I would like to use python to take the size of >>> the file( 50MB, 1GB ) as input from user and create a uncompressed >>> file of the size given by the user. >>> >>> ex: If user input is 50M, script should create 50Mb of blank or empty >>> file >>> >>> >> def make_blank_file(path, size): >> f = open(path, 'w') >> f.seek(size - 1) >> f.write('\0') >> f.close() >> >> I'm not sure the f.seek() trick will work on all platforms, so you can: >> >> def make_blank_file(path, size): >> f = open(path, 'w') >> f.write('\0' * size) >> f.close() >> > > I point out that a 1 GB string is probably not a good idea. > > def make_blank_file(path, size): > chunksize = 10485760 # 10 MB > chunk = '\0' * chunksize > left = size > fh = open(path, 'wb') > while left > chunksize: > fh.write(chunk) > left -= chunksize > if left > 0: > fh.write('\0' * left) > fh.close() > Indeed! Maybe the best choice for chunksize would be the file's buffer size... I won't search the doc how to get the file's buffer size because I'm too cool to use that function and prefer the seek() option since it's lighning fast regardless the size of the file and it takes near to zero memory. Cheers, RB From morse at edoug.org Fri Mar 14 06:17:13 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 14 Mar 2008 10:17:13 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Harald, Great suggestion, thanks! Unfortunately, "no help there". Adding "import multiarray" to Precision.py where you suggested (i.e., before the "from multiarray import zeros" line) did not fix the problem. I'm getting the same exception and traceback as before except, of course, on line 19 now instead of line 18. Doug On Thu, 13 Mar 2008 11:46:41 -0700 (PDT), GHUM wrote: > Doug, > > > Precision.py is part of the Numeric package. AFAIKT, the problem is during > > the module initialization. The first lines of Precision.py are: > > > > from multiarray import zeros > > import string > > > [.....] > and your program is crashing on the > > lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 > > line... Please, try the following: > > import multiarray > from multiarray import zeros > import string > > (adding the line "import multiarray" before zeros are imported from > it) > > I used this workaround with various packages I py2exed - maybe it also > works for you? > > please keep us updated, > > Harald From samuel.progin at gmail.com Mon Mar 10 11:39:21 2008 From: samuel.progin at gmail.com (Sam) Date: Mon, 10 Mar 2008 08:39:21 -0700 (PDT) Subject: defining a method that could be used as instance or static method Message-ID: Hello I would like to implement some kind of comparator, that could be called as instance method, or static method. Here is a trivial pseudo code of what I would like to execute >> class MyClass: ... def __init__(self, value): ... self.value = value ... def comp(self, compValue): ... return self.value == compValue.value >> a = MyClass(3) >> b = MyClass(4) >> c = MyClass(3) >> a.comp(b) False >> a.comp(c) True This is actually achieved by MyClass, how could implement it in order to accept: >> MyClass.comp(a, b) False I would really appreciate a pointer or a way to complete MyClass in order to fulfill my requirements. Thank you for your attention. Sam From aboudouvas at panafonet.gr Fri Mar 28 05:35:02 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 28 Mar 2008 02:35:02 -0700 (PDT) Subject: Eclipse and PyDev Package explorer Message-ID: <1d4e6f2b-a058-413e-a566-674ccc733d6f@s19g2000prg.googlegroups.com> Hi, i am trying to "fit" Eclipse/Pydev in my needs/preference, so i want to ask this: As it is now, i see all my projects in that TreeView (PyDev Package Explorer). I would rather want this to behave like a more "normal" IDE where you Open one project and if you want close it and Open another, just one at a time and not a TreeView with ALL your projects loaded in every time you open the IDE. Is there a way to accomplish thiks in Eclipse/Pydev ?? From deets at nospam.web.de Mon Mar 3 13:49:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Mar 2008 19:49:20 +0100 Subject: Inheritance issue... In-Reply-To: References: Message-ID: <632vhiF262j15U1@mid.uni-berlin.de> MooMaster schrieb: > I'm trying to use inheritance to create a simple binary tree, but it's > not going so well... here's what I pull from the documentation for > super() > "super( type[, object-or-type]) > > Return the superclass of type. If the second argument is omitted the > super object returned is unbound. If the second argument is an object, > isinstance(obj, type) must be true. If the second argument is a type, > issubclass(type2, type) must be true. super() only works for new-style > classes. The last sentence contains the important bit. You need to use new-style-classes, which means they have to have the ancestor "object" somewhere in their inheritance-graph. Like this: class Foo(object): pass Certainly one of the somewhat uglier corners of Python... Diez From sjmachin at lexicon.net Fri Mar 7 16:29:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 13:29:49 -0800 (PST) Subject: I cannot evaluate this statement... References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <57e0ebcf-5d2f-4a27-b141-25fd02513ead@i12g2000prf.googlegroups.com> On Mar 8, 7:38 am, waltbrad wrote: > The script comes from Mark Lutz's Programming Python. It is the > second line of a script that will launch a python program on any > platform. > > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > That makes sense. Because the first condition is true and 'python.exe' > is true. So the next comparison is 'python.exe' or 'python' Well, > python.exe is true. So that value is returned to pyfile. > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. The next comparison is NOT ('False' or 'python'); it is (False or 'python'). 'False' is NOT false, 'False' (like any string of non-zero length) is true. (trueobject and expression) evaluates to the value of expression. (falseobject and expression) evaluates to falseobject [and doesn't evaluate expression]. (trueobject or expression) evaluates to trueobject [and doesn't evaluate expression]. (falseobject or expression) evaluates to the value of expression. So: ('NOT-win' == 'win' and 'python.exe') or 'python' (False and 'python.exe') or 'python' False or 'python' 'python' > But, again, on linux pyfile evaluates to python.exe Does it? Have you tried it? > > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? From gherron at islandtraining.com Mon Mar 31 15:21:06 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 31 Mar 2008 12:21:06 -0700 Subject: Beginner advice In-Reply-To: <1206940981.6828.13.camel@paul-laptop> References: <1206940981.6828.13.camel@paul-laptop> Message-ID: <47F139A2.9000201@islandtraining.com> Paul Scott wrote: > I have been tasked to come up with an audio recorder desktop (cross > platform if possible - but linux only is OK) that: > > 1. records a lecture as an MP3 file (pymedia?) > 2. Provides a login form for server credentials > 3. Uploads via XMLRPC (pyxmlrpclib) to the server as a podcast > > I have been working on this (having never really worked with Python > before) for the past 24 hours or so, and would just like to get some > feedback on the direction that I am taking if possible. > > 1. Is pymedia an active project? Should I use something else? > Pymedia seems to have gone unmaintained for several years now. I'd suggest looking at AVbin http://code.google.com/p/avbin. It provides a nice interface to code that is *very* actively maintained. Even though I've not used it, it is maintained by someone who I do trust to do a good job. > 2. GUI design - I am using glade designer and pyGTK. Good choice? > > 3. pyXMLRPClib - active? Something better? > > 4. I see that there are literally thousands of somewhat external looking > libraries for python, I presume that there is some way of bundling all > the deps into a single source and then compiling? or otherwise packaging > them all (this software will be for academia, so difficult installs are > out!) > > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? > > Any help would be massively appreciated! Python looks like a *really* > easy and powerful language (hey, I managed to do a desktop application > in a few hours and I am a botanist!) and I would like to do a lot more > with it. I have a PHP background (taught myself that also) so C syntax > is almost like my native tongue :) but Python syntax seems just as easy, > if not easier! > > I am still going through Mark Pilgrims' tutorials (dive into ones) and > am slowly getting the hang of things, so if these questions seem inane, > please do excuse me and feel free to tell me to RTFM! > > Thanks > > --Paul > > > > ------------------------------------------------------------------------ > > All Email originating from UWC is covered by disclaimer > http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm > From gregory.bronner at lehman.com Tue Mar 11 16:51:58 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Tue, 11 Mar 2008 16:51:58 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list at python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinay_sajip at yahoo.co.uk Tue Mar 4 06:02:22 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 4 Mar 2008 03:02:22 -0800 (PST) Subject: Python logging: Retrieving the last log record from a handler References: Message-ID: On Mar 3, 11:41 am, Frank Aune wrote: > I will be fairly surprised if this functionality is not already built-in for > the defaultlogginghandlers, but so far I've been unable to figure out how > to pull it of without the custom loghandler above. Prepare to be surprised ;-) Except for the MemoryHandler, which is designed specifically as a buffer for logging events, the handlers in the logging package do not store the last record they processed. (Neither do loggers, filters or formatters, all of which get to see records as they are processed.) Best regards, Vinay Sajip From michael.wieher at gmail.com Mon Mar 17 16:15:28 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 15:15:28 -0500 Subject: struct unpack In-Reply-To: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> References: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> Message-ID: > > testValue = '\x02\x00' > junk = struct.unpack('h', testValue) #Works > > testValue = raw_input("Enter Binary Code..:") inputting at the > console '\x02\x00' > junk = struct.unpack('h', testValue) > > error: unpack requires a string argument of length 2 Well, it thinks the length of the testValue is longer than 2. Why not print out len(testValue) immediately after calling raw_input? maybe raw_input doesn't recognize hex-values automatically, while a string='\x??' is recognizable by the interpreter as such. obviously the issue is raw_input and how it handles input strings... how to fix? no idea =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Mar 30 08:12:18 2008 From: http (Paul Rubin) Date: 30 Mar 2008 05:12:18 -0700 Subject: License of Python References: Message-ID: <7xy7805s2l.fsf@ruckus.brouhaha.com> iu2 writes: > The problem is that including Python's license in the binary, which as > I understand is a must do, reveals that the appliation is based on Python. > > I'll appreciate your advices about this Expose Python as a user extension language, so it's obvious to everyone that Python is present. Just how present it is, you don't have to tell. From castironpi at gmail.com Tue Mar 25 10:34:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 07:34:41 -0700 (PDT) Subject: any good g.a.'s? Message-ID: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Any good genetic algorithms involving you-split, i-pick? "genetic algorithms involving you-split, i-pick" returned 6 results. So, people: From Dodin.Roman at gmail.com Thu Mar 20 10:09:01 2008 From: Dodin.Roman at gmail.com (hellt) Date: Thu, 20 Mar 2008 07:09:01 -0700 (PDT) Subject: Strange behavior of the Eclipse embedded console References: <23ab07a7-0355-48a7-8bf2-266a56f4efb9@h11g2000prf.googlegroups.com> Message-ID: On 20 ???, 14:31, hellt wrote: > i've faced with some strangeness while executing this sample: > > choice = raw_input("your choice: ") > print len(choice) > > when i run this sample in my eclipse console with CPython and print > Yes, i have this output > 4 #trailing \t is the fourth element > > but when i use command line method > python sample.py > i have the correct length = 3 > > i'm curious now, can anyone explain that? just took a look into PyDEV-FAQ. "The eclipse console is not an exact copy of a shell... one of the changes is that when you press in a shell, it may give you a \r, \n or \r\n as an end-line char, depending on your platform. Python does not expect this -- from the docs it says that it will remove the last \n (checked in version 2.4), but, in some platforms that will leave a \r there. This means that the raw_input() should usually be used as raw_input().replace('\r', ''), and input() should be changed for: eval(raw_input().replace('\r', ''))." From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 21:47:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 01:47:41 -0000 Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> Message-ID: <13u3ghthlh25sc0@corp.supernews.com> On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> This whole approach >> assumes that Windows does the sensible thing of returning a unique > error >> code when you try to open a file for reading that is already open for >> writing. >> >> > So how would you use a file to share data then? I see I was a little unclear. What I meant to say was that I assumed that Windows returned a specific error code of "file is busy" as opposed to "you don't have permission to access this file right now" without specifying whether this is a permanent permissions error or a temporary file busy error. > By default Python on Windows allows you to open a file for reading > unless you specify a sharing mode which prevents it: But the OP is talking about another process having opened the file for WRITING, not reading. It's that other process that has exclusive access, and the OP was trying to determine when it was safe to attempt opening the file according to whether or not it was still growing. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:36:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:36:36 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> Message-ID: <13t6c8kdis2gbb5@corp.supernews.com> On Sat, 08 Mar 2008 21:21:48 +0100, K Viltersten wrote: > Coming from C++/Java camp i can't help noticing that in most cases, when > i'm using a class written by somebody else, i don't want to see his/her > code. I only want to know WHAT the function does (is intended to be > doing, at least). > > I don't want to look at the source code (in some cases i can't even see > the code because it's compiled). I only care that when i execute > > SomeType obj = SomeType(); > obj.aggregate(); > > the object gets aggregated. How it's done will be up to the author. I'm > just a user of the product. > > Now, i'm getting the signal that it's done in a different way in Python. > Please elaborate. I'm very new to snakeology. I think even Grant would agree that when you call "help(make_widget)", you should see something like: make_widget(styleID, material) -> widget or raise ValueError on failure styleID: numeric ID or string name of the widget style material: WidgetMaterial instance or None to use default rather than: See source code for details. *wink* -- Steven From darcy at druid.net Fri Mar 7 11:58:38 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 7 Mar 2008 11:58:38 -0500 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: <20080307115838.7b686e83.darcy@druid.net> On Fri, 7 Mar 2008 17:31:35 +0100 "K Viltersten" wrote: > I've been recommended reading of: > http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i > need to get elaborated. > > > 1. When writing English, Strunk and > White apply. > > Where can i download it? Am i actually > expected to read the whole book? How > many people actually do aply it? "The Elements of Style" by William Strunk Jr. and E.B. White. The original, revised edition was published in 1935. The third edition is copyright 1979 and published by MacMillan Publishing Co., Inc., NY, NY. There may be a later version with an ISBN but this one doesn't have one. It's a very small book, 4-1/2" by 7", 81 pages. If you are writing English it is worth browsing from time to time. > 2. You should use two spaces after a > sentence-ending period. > > For heavens sake, why? I've always been > obstructed by the double blanks but > tolerated them. Now, that i read that > it actually is a recommendation, i need > to ask about the purpose. Like many things of this nature, the purpose is to follow the rules of correct English usage. -- 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 jr9445 at ATT.COM Wed Mar 12 11:38:12 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 12 Mar 2008 10:38:12 -0500 Subject: List Combinations In-Reply-To: <47D7E9A1.7000403@ncee.net> References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> <47D7E9A1.7000403@ncee.net> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Shane Geiger > Sent: Wednesday, March 12, 2008 10:33 AM > To: Michael Wieher > Cc: python-list at python.org > Subject: Re: List Combinations > > > > > > def gen(lists): > out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' > comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in > range(len(lists))]) > return eval('[ ' + out + comp + ' ]') > > a,b,c = [1,2,3],[4,5,6],[7,8,9] > > print gen([a, b, c]) > > > > > > -- > Shane Geiger > IT Director > National Council on Economic Education > sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net > It helps to quote your source... http://www.mail-archive.com/python-list at python.org/msg178457.html Start here http://www.mail-archive.com/python-list at python.org/msg178356.html and go through the thread. There are several ways to solve the problem and we evaluated the performance and 'pythonicity' of each. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625 From coolman.guron at gmail.com Fri Mar 7 01:16:42 2008 From: coolman.guron at gmail.com (coolman.guron at gmail.com) Date: Thu, 6 Mar 2008 22:16:42 -0800 (PST) Subject: help on file storage for split multi part download References: Message-ID: On Mar 7, 1:38 am, "Gabriel Genellina" wrote: > En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: > > > storage class which can write the file splits that are currently being > > downloaded to the disk. this is exactly what other download > > accelerators do, i guess. > > > can this be done using the python file class?? i am pretty good at > > handling file uploads (at server end) this is the first time i have to > > think the other way round. > > Uh, unless I misundersand you, a standard file object is enough. First > create a file with the required size (open(...,'wb'), seek(n-1), > write(chr(0))). For each downloaded chunk you have to know its position in > the file; then just seek() and write() it. > > -- > Gabriel Genellina well yes its possible to use the file class that way. BUT the thing thats going in my mind is thread safety. i plan to start each part of the file download in a different thread. and then when each thread had downloaded more than 100kb (or eof or boundary reached) write the buffer to the disk. can this be achieved using mutex ? i have never shared objects between threads. is there a way to write this without using threads at all ??? From stefan_ml at behnel.de Fri Mar 7 05:21:59 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 07 Mar 2008 11:21:59 +0100 Subject: Looking for very light weight template library (not framework) In-Reply-To: References: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> Message-ID: <47d11746$0$14405$9b4e6d93@newsspool3.arcor-online.net> Jeff McNeil wrote: > Isn't there some long > running joke about new Python programmers creating their own template > language or something, too? =) http://article.gmane.org/gmane.comp.python.general/544922 Stefan From deets at nospam.web.de Sun Mar 9 17:38:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 22:38:03 +0100 Subject: Logically/Selectively Sub Class? In-Reply-To: References: Message-ID: <63j3ltF282fssU1@mid.uni-berlin.de> xkenneth schrieb: > Might be a silly question, but is it possible to selectively subclass, > IE subclass is a supporting module is present and not otherwise. Yes, something like this should work class Foo(some, base, classes) pass if condition: Temp = Foo class Foo(Temp, otherclass): pass Alternatively, you can use the type-function to create classes explicit with a list of base-classes. However it smells after bad design... what's your actual usecase? Diez From rridge at caffeine.csclub.uwaterloo.ca Tue Mar 18 14:51:18 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 18 Mar 2008 14:51:18 -0400 Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: Chris Mellon wrote: >OpenGL is totally unsuitable if the goal is to implement your own >pixel-level raster drawing. Unfornately, any solution involving Python is likely to be unsuitable if your goal is to set individual pixels one-by-one, and GDI would be no better than OpenGL here. The overhead of calling some sort of putpixel() function over and over will domininate everything else. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From nagle at animats.com Wed Mar 26 03:22:38 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 00:22:38 -0700 Subject: Beta testers needed for a high performance Python application server In-Reply-To: <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> Message-ID: <47e9f77b$0$36357$742ec2ed@news.sonic.net> Graham Dumpleton wrote: > Yes that is a viable option, as still are existing fastcgi solutions > for Apache, lighttpd and nginx. Fast cgi is a good technology, but it's not well documented or well supported. For some reason, the Apache people don't like it. It used to be part of the Apache distribution, but that ended years ago. It's more reliable than using things like mod_python, where you have application code running in the web server's address space. That creates both security problems and robustness problems. If an fcgi process crashes, it is automatically replaced by a fresh copy of the program at the next request. Other activity in progress is not affected. Also, fcgi processes are reloaded after some number of requests, so minor memory leaks won't choke the system over time. The main problem is that the documentation is terrible, and the monitoring and administrative tools are absent. Little problems include the fact that if you put an .fcgi file in the CGI directory, it's run silently, and inefficiently, in CGI mode. This is because Apache has CGI built into it at a level below the level at which it recognizes other files. John Nagle From craigm3604 at gmail.com Thu Mar 20 14:38:51 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 11:38:51 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> Message-ID: On Mar 20, 2:29 pm, sturlamolden wrote: > On 20 Mar, 19:09, Craig wrote: > > The culprit i here: > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > This binds these names to Python ints, but byref expects C types. > > Also observe that CacheSize and OpenMode should be c_short. I changed CacheSize and OpenMode to c_short, and commented out that line producing the "Before" message, and the output is the same. Further "tinkering" revealed that it is the byref on the fName and pw that are causing the error. The entire problem appears to be around the production of a BSTR and the passing of pointers (byref) to the BSTR. From hberig at gmail.com Thu Mar 20 13:23:18 2008 From: hberig at gmail.com (hberig) Date: Thu, 20 Mar 2008 10:23:18 -0700 (PDT) Subject: zope and python 2.5.1 Message-ID: Hi, I'm sorry if this is an off-topic message, but I didn't found other group. I've read some articles about Zope, and since I like very much python, I would like to run a webserver application using Zope instead other web application server. I've difficulties to install zope 3 and zope 2 on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is there a simple way to fix it? Thanks in advance! ---[ Trying install Zope 2 ]--- Configuring Zope installation Testing for an acceptable Python interpreter... Python version 2.5.1 found at /usr/bin/python No suitable Python version found. You should install Python version 2.4.4 before continuing. Versions 2.4.3 2.4.2 also work, but not as optimally. ---[ Trying install Zope 3 ]--- ....zope3_quick_start/zope3/src/zope/interface/common/interfaces.py", line 80, in classImplements(OverflowWarning, IOverflowWarning) NameError: name 'OverflowWarning' is not defined From jazle at localhost.com Mon Mar 24 22:19:53 2008 From: jazle at localhost.com (Jaimy Azle) Date: Tue, 25 Mar 2008 09:19:53 +0700 Subject: Python based server Uptime Message-ID: Hi, I'm just curious, if anyone ever implement python based application server just like CheryPy, Django, TinyERP, or something else, how many requests do they proceed and what is the longest runing server ever reached before downtime? Salam, -Jaimy. From miki.tebeka at gmail.com Thu Mar 27 17:22:36 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 14:22:36 -0700 (PDT) Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Message-ID: <23908024-8174-4c3d-9d0d-70765834a331@s37g2000prg.googlegroups.com> Hello Tim, > that looks nice, simple, and intuitive. thanks for thinking about it. Thanks, glad I could help. > Now to dive into some gui coding! IMO you can pull it off as a web application and then you won't need to worry about cross-platform, upgrades and all that interesting stuff. HTH, -- Miki http://pythonwise.blogspot.com From grante at visi.com Sun Mar 9 00:27:42 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:27:42 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: <13t6taeir726a18@corp.supernews.com> On 2008-03-09, sjdevnull at yahoo.com wrote: > Even in the early 1990s the moral equivalent of enscript (I think it > was a2ps) I still use a2ps occasionally, but rarely for printing out source code. I occasionally print out hex dumps that I need to markup to figure out what's going on. > worked just fine for printing with filenames, line/page > numbers, It still does. > and other niceties no matter what editor you used. It seems > more reasonable to mandate using a sane print tool for the odd > case where someone wants to print things out than to mandate > cluttering up every file with the filename in a comment. And guess what? After a while, files get renamed and nobody remembers to change the comments. If people really want a filename in the top of the file, they should at least use something like a CVS or SVN variable so that it's generated automagically and can't be wrong. -- Grant Edwards grante Yow! I want DUSTIN at HOFFMAN!! ... I want visi.com LIBRACE!! YOW!! From tew24 at spam.ac.uk Thu Mar 6 08:20:49 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 06 Mar 2008 13:20:49 +0000 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: Gabriel Genellina wrote: > Maybe this thread > http://groups.google.com/group/comp.lang.python/browse_thread/thread/f8df5ed32b324a3f/ > can help. > > This EULA doesn't apply to you, but to the Python developers, which are > the actual Visual Studio users and have to comply with its license terms. > You're just repackaging Python, your program, and other required > components. > In any case, I don't think MS cares; after all, you're promoting their OS > and making life easier for Windows users. Many thanks - that does indeed answer it. I'd not been able to find the EULA, but the bits quoted from it in the above discussion do answer the question. -- I'm at CAMbridge, not SPAMbridge From qingshan.chen at gmail.com Sun Mar 23 21:10:05 2008 From: qingshan.chen at gmail.com (QS) Date: Sun, 23 Mar 2008 18:10:05 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: Thanks to you all! It's good to know... On Mar 23, 9:02 pm, Carsten Haese wrote: > On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > > That's really weird... it's reproducible on Windows too. It doesn't > > make any sense why the name of the variable would make a difference. > > My guess is you hit some kind of obscure bug. > > This is not a bug, just an unexpected feature:http://mail.python.org/pipermail/python-list/2005-January/304873.html > > What's happening is that at the end of the script, all objects in the > global namespace are set to None (in order to decrease their reference > count and trigger garbage collection). This happens in the order in > which the names appear as keys in the globals dictionary. It randomly > happens that "swaroop", "kalam", and "cath" all are hashed in front of > "Person", but "cathy" is hashed after "Person". > > Hence, if Catherine is named cath, Python "None's" all the instances > first and then the type last, and all is well. However, if Catherine is > called cathy, Person is set to None before cathy. Then, in the lookup of > the global name "Person" during cathy.__del__, Person is None, which > doesn't have a "population" attribute, causing the AttributeError. > > Possible workarounds are: > 1) Explicitly delete the global names for the instances before the > script runs out. > 2) Don't refer to the "Person" type by its global name in __del__, but > indirectly as type(self). (This requires Person to be a new-style class, > though.) > > -- > Carsten Haesehttp://informixdb.sourceforge.net From castironpi at gmail.com Sat Mar 15 22:19:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 19:19:59 -0700 (PDT) Subject: string literal or NoneType References: Message-ID: <97eb79e8-e79d-4bd8-af6d-108579e7d54c@59g2000hsb.googlegroups.com> On Mar 15, 2:41?pm, "Terry Reedy" wrote: > wrote in message > > news:b2d5cbd3-b207-4c46-89ef-75ae101752ca at e6g2000prf.googlegroups.com... > | hi all > | i want to check a condition and if true should return a filename > | string ?from a list.if the condition is false i am returning a > | "" ?(string literal).. > | > | retv="" > | if ?somecondition: > | ? ?retv=mylist[x] > | ... > | return retv > | > | > | The calling function will check the return value and print the > | filename if it is not """. > | in the calling function i can code > | if returnval !="": > | ? ?print "filename is:",returnval > | else: > | ? ?print "no filename found" > | > | what i want to know is ,should i rewrite the ?if returnval !="" ?as > | > | if returnval: > | ? print "filename is:",returnval > | else: > | ? ?print "no filename found" > > In this situation, where returnval must be a string, the two are > equivalent. > So I consider the shorter, more efficient form stylistically better. > In situations where various null or non-null conditions are not equivalent, > one should use the one that is correct for the situation. > > | or is the way i coded the right way ? i am little confused here > | Someone suggested that i make a variable retv None and if the > | condition true then set retv as filename , > | > | retv=None > | if somecondition: > | ? ?retv=mylist[x] > | > | ... > | return retv > | > | which approach is correct..? > > As long as the function returns are documented and the behavior matches the > documentation and the calling code matched the behavior, both are > 'correct'. > I see this as stylistic preference. ?I can think of situations where a null > string might be more useful that None, so I might go with that. Others > might think of situations where a None return might be better. ?But a > function cannot satisfy all possible callers ;-) > (The is one problem with writing library code.) > > Terry Jan Reedy I actually took Caller Satisfaction in grad school. Before computer science. It depends somewhat on what you might do later-- what changes you want to make be easy. Will your return always be a primitive? Always a single value? Do you ever want to return the name of a buffer? Will the file ever already be open? You can buy yourself some time: use _noval= object(); return _noval; assert returnval is _noval. 'None' works too until you use it to signal something. But caveat emptor*. If you want to ascribe a property to an object, such as 'wasn't found', 'too small', and 'insufficient', do it. Maybe 'specialflag' is the right value for None in the -other- place, so you are free to return it. Poor None here is overworked, is the point. Search the Python library for 'None'. 5961 occurrences in 3.0a3 including comments, yet including 308 'return None's, still including comments. There's a 'return None # bad format' and a 'return None, None, line'. You've got a '__UNDEF__ = [] # a special sentinel object' too; there's precedent. Take this one. - Return code object if the command is complete and valid - Return None if the command is incomplete - codeop.py No code object will ever be 'None'; you're ok to return it without conflicts. But at a second level of abstraction, you'll need a distinction. For example: you're mapping indices to code objects. Does 'None' mean 'uninitialized'** or 'the command is incomplete'? It's ok to initialize array items to 'None'; you don't need to worry about omitting them until your call is complete. You'll get nothing but a headache if you're expecting def retrlines(self, cmd, callback = None): to throw an exception if you pass an uninitialized value to 'callback'. Twelve lines later: if callback is None: callback = print_line So, whoops. * Under the doctrine of caveat emptor, the buyer could not recover from the seller for defects on the property that rendered the property unfit for ordinary purposes. -wikipedia. ** sock = None file = None welcome = None - ftplib.py From peter.bulychev at gmail.com Sun Mar 23 17:25:40 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Mon, 24 Mar 2008 00:25:40 +0300 Subject: Clone Digger: the tool for finding software clones; GSoC 2008 Message-ID: Hello. I am glad to present you Clone Digger, the tool for finding software clones in Python programs, The presence of clones can greatly increase the software maintenance cost. For instance, every error in the original have to be fixed in all copies. Therefore I hope that Clone Digger will be useful for the Python community. It can help to form recommendations for refactoring. Clone Digger works on the abstract syntax tree level. You can read more about Clone Digger, see examples and download it on the page: http://clonedigger.sourceforge.net . ======= Google Summer of Code 2008 ======= Clone Digger participates in the Google Summer of Code 2008 program. I think, that Clone Digger will be a good choice for students willing *) to learn about the structure of programs written in Python, *) to practice in designing and implementing new algorithms (you will be asked to add automatic refactoring feature) *) to develop the tool which will help people to create better programs You can see the project ideas here: http://clonedigger.sourceforge.net/google_summer_of_code.html Please, fill free to ask me any questions you may have. -- Best regards, Peter Bulychev. From spamspam at spam.eggs Sat Mar 8 18:51:29 2008 From: spamspam at spam.eggs (Ben C) Date: Sat, 08 Mar 2008 17:51:29 -0600 Subject: SV: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: On 2008-03-08, K Viltersten wrote: >> If you can't/don't look at the source file, >> then comments aren't going to help (except >> in the case of something like docstrings in >> Python). > > I strongly disagree. Now, perhaps we're > talking about different things, here? > Usually, in the header file (C++), there > won't be any source code, except for > method declarations. A common example: > > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); > > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. > > I don't see how this is dislikeable. Please > explain. Perhaps the above IS what you > ment by "docstrings"? For Java, one has the > JavaDocs, a great tool, provided one will > comment each method and variable used. The problem is that tools like Doxygen and JavaDocs generate warnings and errors and things if everything isn't documented "completely". So you end up with a lot of silly boilerplate. I see this kind of nonsense a lot: /** * Get the width of a box * * @param box the box * @returns its width */ extern int box_get_width(box box); You are right that is it often useful to document what to pass to a method and what to expect back and that if this is done well in many cases it isn't necessary to see the implementation. But in many other cases it's obvious, and in other cases it's obvious if you just look at the source which you've got. What's needed is just a bit of common sense and pragmatism: APIs need more documentation if the source of the implementation isn't being released with them, and some APIs just need more documentation than others anyway. Python docstrings, like most things in Python, demonstrate this kind of common sense: you write what you want in them and as far as I can tell nothing complains if you don't write them at all. The lack of fascism is the big innovation. It sounds simple but it makes a huge difference: it's much easier to find (and keep up to date) the real documentation if it's not hidden in a forest of bogus documentation. From haag at lsu.edu Tue Mar 25 12:36:09 2008 From: haag at lsu.edu (Alaric Haag) Date: Tue, 25 Mar 2008 11:36:09 -0500 Subject: A "roadmap" for ctypes wrapping? References: <64nno9F2d12tkU1@mid.uni-berlin.de> Message-ID: In article <64nno9F2d12tkU1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > Alaric Haag schrieb: > > Hi all, > > > > ....stuff deleted.... > > > > ====== > > Can anyone with some "wrapping" experience add/modify/enhance the above? > > Use gccxml to gather the typedefs. And look at Gary Bishop's site to see > some cool helper classes/functions for dealing with ctypes. > > Diez Thanks for the pointers! I had hoped others might offer opinions as well, but the cross-post on the "ctypes" list is idle. Thanks again! Alaric From hniksic at xemacs.org Tue Mar 18 16:43:49 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Mar 2008 21:43:49 +0100 Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> Message-ID: <87ve3j3gqi.fsf@mulj.homelinux.net> Ninereeds writes: > As for the growth pattern, each time you grow the table you have to > redistribute all the items previously inserted to new locations. > Resizes would get rarer as more items are added due to the > exponential growth, but every table resize would take longer too > since there are more items to move. Inserting n items still > intuitively looks like O(n^2) to me. > > That said, it does remind me of that old exponential realloc trick > for array resizing. Same thing, I suppose, since a hash table is > basically an array. Maybe my math "intuition" is just wrong. That's it. While table resizes grow linearly in complexity, they become geometrically rarer. This is exactly what happens when resizing dynamic arrays such as Python lists. Applying your intuition, appending n elements to a Python list would also have O(n^2) complexity, which it doesn't. See, for example, http://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost From shakefu at gmail.com Fri Mar 7 17:26:31 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:26:31 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <8b9469d6-5b73-4f5f-8aa5-51c8dfdb2fd0@y77g2000hsy.googlegroups.com> On Mar 7, 4:22 pm, shak... at gmail.com wrote: [snip] > Although if I end up writing my own I'll sure use > datetime.parser.parse to get everything left over once you remove I mean dateutil.parser.parse. Tomorrow I'll have to leave off the last Lunchtime Guiness. > strings like "this saturday". So it helps a little! > > Jacob And on the same thought - does anyone know of a good website, resource or community that's got intelligible descriptions of all the different modules that are generally available? I know if I tab complete 'apt- get install python-*' it tries to list 1000-some possibilities, so I'm thinking there's quite a few modules out there that I might like to know about and use... Thanks! Jacob From kw at codebykevin.com Wed Mar 19 16:10:38 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 19 Mar 2008 16:10:38 -0400 Subject: Calling Mac programs from Python instead of from AppleScript In-Reply-To: References: Message-ID: <47E1733E.5060902@codebykevin.com> dvschorre at sbcglobal.net wrote: > When I'm running Script Editor, I can get Maya to draw a sphere by > typing: > > tell application "Maya" > execute "sphere" > end tell > > When I try this using Python, I get this error message: > > IDLE 1.2.2 >>>> app('Maya').execute('sphere') > > Traceback (most recent call last): > File "", line 1, in > app('Maya').execute('sphere') > NameError: name 'app' is not defined > > Maybe I need to load some libraries first. > > Please help me to get started. > > Thanks > Dewey V. Schorre > Take a look at appscript: http://appscript.sourceforge.net/ -- Kevin Walzer Code by Kevin http://www.codebykevin.com From userprogoogle-139 at yahoo.co.uk Thu Mar 6 04:37:14 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 6 Mar 2008 01:37:14 -0800 (PST) Subject: Python CGI & Webpage with an Image References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> Message-ID: <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> Hi, Good point, some code samples is probably required. Please note that for reasons of integration with another system I am not using a templating system. Anyway I have copied them below: Python: f = open("finish.html") doc = f.read() f.close() print doc HTML:




Thank you for uploading your file

From kf9150 at gmail.com Fri Mar 28 18:48:09 2008 From: kf9150 at gmail.com (Kelie) Date: Fri, 28 Mar 2008 15:48:09 -0700 (PDT) Subject: case insensitive lstrip function? Message-ID: <0eb666fe-8c3e-4a93-afbf-1953922c19bd@s13g2000prd.googlegroups.com> Hello, Is there such a function included in the standard Python distribution? This is what I came up with. How to improve it? Thanks. def lstrip2(s, chars, ingoreCase = True): if ingoreCase: s2 = s.upper().lstrip(chars.upper()) return s[len(s)-len(s2):] else: return s.lstrip(chars) From paul at boddie.org.uk Sun Mar 16 20:32:15 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 16 Mar 2008 17:32:15 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: On 17 Mar, 01:09, a... at pythoncraft.com (Aahz) wrote: > > PyCon is what YOU make of it. If you want to change PyCon, propose a > presentation or join the conference committee (concom) -- the latter only > requires signing up for the pycon-organizers mailing list. > > This doesn't mean that we are uninterested in feedback. We love > feedback. But there are stark limits to what we can do unless people get > involved and push their pet projects. The same rules apply for most of the other Python conferences, too. Apologies to Aahz for hijacking his rant, but for anyone interested in enhancing the EuroPython 2008 experience, the advice is fairly similar: join the volunteers organising the conference and make what you want to see actually happen. For EuroPython, start here: http://www.europython.org/community/Volunteers If EuroPython is too remote or not to your taste, help your local conference or the Python conference which caters to your specific interests: http://wiki.python.org/moin/PythonConferences http://www.pycon.org/ (a list of the big generic Python conferences) Constructive feedback is always welcome, but it's better to change things before your favourite conference so that it remains your favourite conference. Paul From bogus@does.not.exist.com Thu Mar 13 16:08:43 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 15:08:43 -0500 Subject: Python regex References: Message-ID: made error on last line... read as... > I would be saying if forward-slash AND asterisk appear in this order... > negate -- -- Andrew "Andrew Rekdal @comcast.net>" < wrote in message news:qLKdnR6s8a4xFUTanZ2dnUVZ_qmlnZ2d at comcast.com... >I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such > as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > >>>CSS comment > > although this works to a degree... I know the within the brackets > everything is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? > eg. where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... > negate > > > -- Andrew > > From castironpi at gmail.com Sun Mar 2 15:43:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 12:43:22 -0800 (PST) Subject: Network server- / client-side messaging References: Message-ID: ''' Last time, we left off at: ''' class InterfaceClientSide( ClientSide ): message= MessageDec() incremental= message.incremental() settings= AYT( .5, 3 ) user_act= message.out() def __init__( self, image ): self._image= image ClientSide.__init__( self ) def on_scale( self, *args ): change= self._whatchange( self.on_scale, *args ) self.user_act( change ) def on_rotate( self, *args ): change= self._whatchange( self.on_rotate, *args ) self.user_act( change ) @incremental( 1 ) def layout_return( self, layoutchange ): renderchange( layoutchange ) @incremental( 2 ) def layout_return( self, layoutchange ): renderchange( layoutchange ) @message def time_estimate( self, etc ): report( etc ) class InterfaceServerSide( ServerSide ): message= MessageDec() incremental= message.incremental() settings= AYT( .5, 3 ) time_estimate= message.out() layout_return= incremental() def __init__( self, image ): self._image= image ServerSide.__init__( self ) @message.intervene() def user_act( self, change ): etc= self.calculateeta( change ) self.time_estimate( etc ) preliminary= self.calculation() preliminary_change= whatchange( preliminary ) self.layout_return( preliminary_change ) completed= self.other_calculation() completed_change= whatchange( completed ) self.layout_return( completed_change ) self.layout_return.finish() ''' Another use ClientSide and ServerSide should support is a peer-to-peer chat-and-game server. And that said, it's not clear that there's any distinction between ServerSide and ClientSide anyway, depending on exactly how the listen and connect methods abstract. How much of the implementation do they share? Most. You could mark 'time_estimate' as incremental( 3 ); they're separated for illustration purposes. One remaining question is how to intervene in user_act, if a second change arrives before the previous complete. You could combine the earlier change parameter in the new call and throw an exception in the thread handling the earlier one at its first loss of control--- and maybe even at once with settrace! That tends to be costly. Not to mention, change has already entered derived-class space. ServerSide should make sure it's easy enough to address the issue on one's own, and @message.nonintervene() is available too. ''' From willsteve2003 at yahoo.ca Mon Mar 10 11:02:23 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:02:23 -0700 (PDT) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <7d442cdd-749e-4391-ba31-e9c86d090137@x41g2000hsb.googlegroups.com> <70f5b8e7-4e76-43f7-b390-c5dd994ff434@e31g2000hse.googlegroups.com> Message-ID: On Mar 8, 5:37?pm, malkarouri wrote: > On Mar 8, 6:24?pm, rockingred wrote: > > > I think it's a bad practice to get into. ?Did you intend to do the > > "process" step again over the added variables? ?If not I would set a > > new variable, based on your awful naming convention, let's call it z. > > Then use z.append(y) within the for loop and after you are out of your > > for loop, q.append(z). > > Thanks, rockingred, for the advice. I hope that you didn't assume that > I was a newbie, even if my question looks so. What I was trying to do > is write some Python code which I need to optimize as much as > possible. I am using Cython (Pyrex) and would probably end up > rewriting my whole module in C at one point, but it is really hard to > beat Python data structures at their home turf. So meanwhile, I am > making use of dubious optimizations - on my own responsibility. There > have been a lot of these along the years - like using variables > leaking from list expressions (not anymore). Think of it as a goto. > Yes, I intend to do the process step again over the added variables. > The suggested deque is probably the best, though I need the speed > here. > What are the variable naming you would suggest, for a throwaway - > probably anonymized for the same of publishing on the web - code? > > Cheers, > > Muhammad Alkarouri If the variables are "throwaways" and will be used in a really small function, then it's probably okay to name them the way you did. I'm just against single character names on principal, because if you need to search a program to find where the variable was used you get too many hits. I prefer to name the variables for what they do. For example, instead of "q" you could use "queue". From waltbrad at hotmail.com Mon Mar 17 14:18:02 2008 From: waltbrad at hotmail.com (waltbrad) Date: Mon, 17 Mar 2008 11:18:02 -0700 (PDT) Subject: questions about named pipe objects... References: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> Message-ID: On Mar 17, 1:59 pm, Jeff Schwab wrote: > > A Unix fifo is only nominally a file. It's really just a convenient way > of referring to an in-memory object. > mkfifo f > some_prog > f & > cat f > > Is semantically equivalent to: > > some_prog | cat > > If you want to peruse the data in your editor, use a regular file, not a > fifo. Have the writer (producer, "child" in your example) open it in > append mode. Okay. I get it. That's interesting. Wish Lutz explained that. Thanks. From grante at visi.com Sun Mar 9 00:24:46 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:24:46 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: <13t6t4ujm71tjec@corp.supernews.com> On 2008-03-09, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > >> I'm also a bit baffled by people who put a comment at the top of every >> file that tells you what the filename is. > [snip rant] > > You've never printed out a source file on pieces of dead tree > to read on the train on the way home, or in bed or the bath? Not in the last 20 years or so. > Yes, some editors will print a header or footer showing the > file name, but not all will, or are configured to do so. If I want the filename printed at the top of the first page (or at the top of every page) I'll use a tool that does that. -- Grant Edwards grante Yow! If I am elected no at one will ever have to do visi.com their laundry again! From spradml at gmail.com Tue Mar 18 06:27:26 2008 From: spradml at gmail.com (Pradnyesh Sawant) Date: Tue, 18 Mar 2008 15:57:26 +0530 Subject: detect current timezone set by kde Message-ID: <20080318102726.GB3880@debian> Hello, can someone please tell me how can I programatically detect the timezone information that has been set through kde? basically, I have a small pyqt4 app which shows the current time. however it shows me my system time (dunno where that is stored; basically it shows me time in IST). however, I'm right now in hk and would like the app to show me time in my current timezone (hong kong). Any guidelines how may I go about doing this? thanks a lot in advance :-) -- warm regards, Pradnyesh Sawant -- Believing everybody is dangerous; believing no one is dangerous... --Abraham Lincoln -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From castironpi at gmail.com Thu Mar 6 13:32:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 10:32:30 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <5oQzj.61239$Pv2.45450@newssvr23.news.prodigy.net> Message-ID: <8fe8ff57-70d2-45e1-9ce6-725eb949b5ee@p73g2000hsd.googlegroups.com> > Actually, there's another data structure I was working on (a year ago > now) that's tangentially related, so if you guys want me to hold off > on that one til you or I is satisfied on the company-product map, I > will! ?Otherwise, I'll just post it here and leave it to you. > (Knowing myself, something tells me I'll try to formulate it later on > today regardless. ?Heh heh heh. ?If that's not the most virtuous way > to ask for help, then I might have inherited from TroubleMaker at some > point up the line.) My other question still open, the idea was a collision detector. But it's been done. Ideally, subdivide space varying with objects' positions up to a tolerance. On motion, redivide. Each tile, hexes, triangles, or squares, can access the other objects in itself-- and only detect collisions among those. Objects can span multiple tiles. For large object sets, zero detections made per cycle best case, but still all of them worst. It amounts to a tree structure in which child nodes are keyed geometrically-- grid.NWcorner.NEcorner gets you the second column, first row in a 4x4 grid. grid.NWcorner.NEcorner.SWcorner gets you the third column, second row, in an 8x8 grid, and by that point, there are 63 tiles other objects might be in that you know aren't in yours. A tile is a leaf if there are no objects in it. Question is, how rare/common is the subset of object configurations in which the optimizations weigh out? From enleverlesX.XmcX at XmclaveauX.com Thu Mar 13 20:18:13 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 14 Mar 2008 01:18:13 +0100 Subject: Python-PHP bridge? In-Reply-To: References: Message-ID: <47d9c614$0$855$ba4acef3@news.orange.fr> Hi! Only under Windows, you can use PHPscript. It's the "active-scripting" release of PHP. With it, you can send PHP's functions (source), and call these functions (with parameters). With the same method, you can also use, from Python, VBscript, Jscript, PerlScript, RubyScript. @-salutations Michel Claveau From deets at nospam.web.de Sat Mar 29 17:26:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 22:26:56 +0100 Subject: Serial port error statistics - any comparable data? In-Reply-To: References: Message-ID: <657qh1F2es9vnU1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > Hi, > > I have been doing some tests on a device that > we are thinking of incorporating into a product, > and I have seen that reception on a serial port > at 115200 baud over about six metres of RS-232 > cable makes mistakes, to the order of 125 lines > with errors in them out of approximately 18.4 > million lines of 65 or so chars - about one errored > line in 147000, or one error character in 95 million. > > The PC that is making the errors is a 64 bit dual > core AMD machine running at 2 Gig, and I am > running stock standard Open Suse 10.3 with > the supplied Python 2.5. > > What kind of bothers me is the nature of the errors - > I seem to get only missing characters, as if an > interrupt was missed. There are no munged characters > as one would expect if the errors were bit related. > > Has anyone else seen anything like this, and am I worrying > needlessly? > > I realise that my production protocols will easily handle > this almost non existent level of error - but if this were in > microcontroller code that I had written myself, I would > suspect that I was spending too long in some critical > section of code. RS232 is unfortunately as bad as a "protocol" as it can get. I've used it for communication with a microcontroller for just a few bytes every second. And it failed miserably, so I needed to implement a protocol on top of it. The machine spec is totally irrelevant - what is interesting is the serial hardware you use. Are you by any chance using a serial2usb-converter? I had nothing but troubles with these. if you have the chance, try & attach a machine with legacy rs232 port, and see if the errors still remain. Diez From http Wed Mar 19 05:42:55 2008 From: http (Paul Rubin) Date: 19 Mar 2008 02:42:55 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> Message-ID: <7xskynm4m8.fsf@ruckus.brouhaha.com> Torsten Bronger writes: > > Re Haskell: I've been spending a lot of time on Haskell recently, > > though I haven't done anything nontrivial with it yet (just some > > small stuff). But I think it's better for complex program > > development than Python is, > > Could you elaborate on this? (Sincere question; I have almost no > idea of Haskell.) http://wiki.python.org/moin/PythonVsHaskell is a fairly high-level comparison. I think it's easier to write complex code in Haskell because: 1) it has a powerful static type system that lets you express important invariants and have them enforced at compile time. This not only catches errors but helps you understand the program logic almost like running the code under a debugger does. If you try to fill a gap by putting in a piece of the wrong shape, it just won't fit and the compiler will tell you what you really wanted. On the other hand, most types are inferred by the compiler, so you don't need a lot of cumbersome declarations like in Java. 2) The basic list type in Haskell works something like Python iterators, but they don't change state when you consume an item. In fact all Haskell data is immutable. You avoid vast classes of bugs this way. But you do have to change the way you think about programming. I may write a longer comparison post sometime later. From torriem at gmail.com Sat Mar 1 15:58:47 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Mar 2008 13:58:47 -0700 Subject: How to subclass a built-in int type and prevent comparisons In-Reply-To: <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> Message-ID: <47C9C387.8040100@gmail.com> castironpi at gmail.com wrote: > Tell Wall. But why not [ 2, 3 ]>= 2? Back to your question, another > option is to not subclass. Umm, no. You need to actually read the posts before you respond to them. His question was whether or not to throw an exception in this case. He's *already* subclassed the type. The first question was, should he throw an exception. And given that Python 3.0 will throw exceptions, he is justified in throwing exceptions as well. I have no idea what he would lose by throwing an exception. I have no idea how else he would do this. His second question was, would his code for implementing __gt__ (and throwing exceptions) be likely efficient. That I cannot say. From xkenneth at gmail.com Sat Mar 8 14:36:12 2008 From: xkenneth at gmail.com (xkenneth) Date: Sat, 8 Mar 2008 11:36:12 -0800 (PST) Subject: Intra-Package References Message-ID: <01d2be35-3e08-49d4-811b-a0d8b4fb5d27@n77g2000hse.googlegroups.com> Does your python module have to exist in the path in order for intra- package references to work? Regards, Kenneth Miller From rockxuan at gmail.com Tue Mar 18 03:56:57 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:56:57 -0700 (PDT) Subject: replicas replicas watch Message-ID: Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From craigm3604 at gmail.com Thu Mar 20 19:50:18 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 16:50:18 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> Message-ID: On Mar 20, 6:26 pm, sturlamolden wrote: > On 20 Mar, 19:09, Craig wrote: > > > The following is the C++ prototype for one of the functions: > > short FAR PASCAL VmxOpen(BSTR *Filespec, > > LPSHORT lpLocatorSize, > > LPSHORT lpOmode, > > LPHANDLE lphwmcb, > > BSTR *Password); > > import ctypes > import comtypes > > LPBSTR = ctypes.POINTER(comtypes.BSTR) > HANDLE = ctypes.POINTER(ctypes.POINTER(ctypes.c_long)) > LPHANDLE = ctypes.POINTER(HANDLE) > LPSHORT = ctypes.POINTER(ctypes.c_short) > > VmxOpen = ctypes.windll.vbis5032.VmxOpen > VmxOpen.restype = c_short > VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] > > Filespec = comtypes.BSTR('blahblahblah') > LocatorSize = ctypes.c_short(256) > Omode = ctypes.c_short(1) > hwmcb = HANDLE() > Password = comtypes.BSTR('blahblahblah') > > res = WmxOpen( byref(Filespec), byref(LocatorSize), > byref(Omode), byref(hwmcb), byref(Password) ) > > or if that fails: > > pFilespec = ctypes.pointer(Filespec) > pLocatorSize = ctypes.pointer(LocatorSize) > pOmode = ctypes.pointer(Omode) > phwmcb = ctypes.pointer(hwmcb) > pPassword = ctypes.pointer(Password) > > res = WmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) sturlamolden, thanks for the input. I had to change your example to the following to get it to run: from ctypes import * import comtypes LPBSTR = POINTER(comtypes.BSTR) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) VmxOpen = windll.vbis5032.VmxOpen VmxOpen.restype = c_short VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] Filespec = comtypes.BSTR('s:\\msdb\\dcod') LocatorSize = c_short(0) Omode = c_short(3) hwmcb = HANDLE() Password = comtypes.BSTR('GU32ASBURYPARK60A42A20') res = VmxOpen( byref(Filespec), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(Password) ) print "res = " + str(res) pFilespec = pointer(Filespec) pLocatorSize = pointer(LocatorSize) pOmode = pointer(Omode) phwmcb = pointer(hwmcb) pPassword = pointer(Password) res = VmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) print "res = " + str(res) After changing the assignment for Password to the correct value, both calls to VmxOpen returned a status of 20, which indicates an invalid password. I received a direct email from someone, and I came up with the following after implementing his advice: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf FileSpec = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) printf ("FileSpec = \x22%s\x22\n", FileSpec) Password = windll.oleaut32.SysAllocStringByteLen("XYZ\x00", 4) printf ("Password = \x22%s\x22\n", Password) LocatorSize = c_short(0) Omode = c_short(3) hwmcb = c_long(0) X = c_short(0) printf ("Before - X = %#x (%d), LocatorSize = %d, Omode = %d, hwmcb = %d\n", X, X, LocatorSize, Omode, hwmcb) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." X.value = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) printf ("After - X = %#x (%d), LocatorSize = %d, Omode = %d, hwmcb = %d \n", X, X, LocatorSize, Omode, hwmcb) windll.oleaut32.SysFreeString(FileSpec) windll.oleaut32.SysFreeString(Password) This returned a correct value in X of 0 (VIS_OK). When I changed: FileSpec = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) to: FileSpec = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", 13) I got the expected X value of 13 (VIS_DOS_ERROR). As was pointed out to me, and not really to my surprise as I am still very "green" at Python, the correct call was: X.value = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) instead of: X = windll.vbis5032.VmxOpen(byref(c_void_p(FileSpec)), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(c_void_p(Password))) Thank you to everyone for their help. From sturlamolden at yahoo.no Wed Mar 19 21:03:24 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 18:03:24 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: On 20 Mar, 00:16, John Machin wrote: > What don't you understand about the comments in the first two > screenfuls of Objects/setobject.c? I had not looked at it, but now I have. Is seems Hettinger is the author :) Ok, so sets are implemented as hash tables. Then I agree, use Raymond Hettinger's solution. From castironpi at gmail.com Wed Mar 5 22:43:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:43:09 -0800 (PST) Subject: access to base class __init__ References: Message-ID: <57cf7606-f49e-4377-8237-f3a86acb79fd@n36g2000hse.googlegroups.com> On Mar 5, 6:09?pm, sambo q wrote: > I got myself in jam trying to be too fancy with ?threading.Thread > Docs say / remind to call the base __init__ > but I can't fighure out how. > > --------------------------- > def main() > ..... > ? ? ls.listen(5) > ? ? key = ' ' > # ? ?while key != EXITCHARCTER: > ? ? while stop_serving == False: > ? ? ? ? cs, raddr = ls.accept() > ? ? ? ? print "Main_Thread: ",cs, raddr > ? ? ? ? nt = client_socket_handler( cs, raddr ) > ? ? ? ? print threading.enumerate() > ? ? ? ? key = getkey() > > # ? ?ls.close() > ? ? time.sleep(4) > ? ? print "Server Exiting." > > class client_socket_handler(threading.Thread): > ? ? def __init__(self, cs, remote_address): > ??????????????????????? > ? ? ? ? self.threading.Thread.__init__(self,self.socket_handler,None,None) > ? ? ? ? self.socket = cs > ? ? ? ? self.rhost_addr = remote_address > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > # ? ? ? ?t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) > # ? ? ? ?t1.start() > ? ? ? ? self.start() > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > ? ? ? ? print "client_socket_handler.__init__(): enumerate()", > threading.enumerate() > > ? ? def socket_handler( self, invar, indict ): > ? ? ? ? threadname = self.getName() > ? ? ? ? print "\"%s started\"" % threadname > ? ? ? ? print "client_socket_handler.socket_handler() invar: ", invar > ? ? ? ? instr = self.socket.recv( 500 ) > # ? ? ? ?print instr > ? ? ? ? req_lines = string.split( instr, "\r" ) > ? ? ? ? for line in req_lines: > ? ? ? ? ? ? line.strip( "\n") > ? ? ? ? print req_lines > ? ? ? ? print len( instr ) > > ---------------------------------- > > self.threading.Thread.__init__() > self.Thread.__init__() > ?? recall a= A() --> a.b() --> A.b( a ). What is A? threading.Thread. In other words, threading.Thread.__init__( *stuff ). From janeczek at gmail.com Thu Mar 27 00:54:17 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Thu, 27 Mar 2008 05:54:17 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: <7xzlslvpn5.fsf@ruckus.brouhaha.com> References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: <561cb5bc0803262154s66b01425hf866847fbbfb3502@mail.gmail.com> Thanks for finding time to reply! On 26 Mar 2008 01:46:38 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > A few thoughts. The envisioned Python-Haskell bridge would have two > directions: 1) calling Haskell code from Python; 2) calling Python > code from Haskell. The proposal spends more space on #1 but I think > #1 is both more difficult and less interesting. By "Haskell" I > presume you mean GHC. I think that the GHC runtime doesn't embed very > well, despite the example on the Python wiki > (http://wiki.python.org/moin/PythonVsHaskell near the bottom). This > is especially if you want to use the concurrency stuff. The GHC > runtime wants to trap the timer interrupt and do select based i/o > among other things. And I'm not sure that wanting to call large > Haskell components under a Python top-level is that compelling: why > not write the top level in Haskell too? The idea of making the > critical components statically typed for safety is less convincing if > the top level is untyped. I wasn't aware of the runtime issues, these can be things to watch out for. However, the type of embedding that I imagined would be mostly pure functions, since Python can deal with IO rather well. It'd also be applicable in situations where we want to add some functionality to to existing, large Python project, where the complete rewrite would be infeasible. > There is something to be said for porting some functional data > structures to Python, but I think that's mostly limited to the simpler > ones like Data.Map (which I've wanted several times). And I think > this porting is most easily done by simply reimplementing those > structures in a Python-friendly style using Python's C API. The type > signatures (among other things) on the Haskell libraries for this > stuff tend to be a little too weird for Python; for example, > Data.Map.lookup runs in an arbitrary monad which controls the error > handling for a missing key. The Python version should be like a dict, > where you give it a key and a default value to return if the key is > not found. Plus, do you really want Python pointers into Haskell data > structures to be enrolled with both systems' garbage collectors? I didn't mention this in this first draft, but I don't know (yet) how to support those "fancy" types. The plan for now is to export monomorphic functions only. As for GC, I think having the two systems involved is unavoidable if I want to have first class functions on both sides. > The Haskell to Python direction sounds more useful, given Haskell's > weirdness and difficulty. Python is easy to learn and well-packaged > for embedding, so it's a natural extension language for Haskell > applications. If you wrote a database in Haskell, you could let > people write stored procedures in Python if they didn't want to deal > with Haskell's learning curve. Haskell would call Python through its > "safe" FFI (which runs the extension in a separate OS thread) and not > have to worry much about the Python side doing IO or whatever. Of > course this would also let Python call back into the Haskell system, > perhaps passing Python values as Data.Dynamic, or else using something > like COM interface specifications. That is one of the use cases I have missed in the first draft. Thanks for the idea! > Anyway I'm babbling now, I may think about this more later. By all means, please do go on :) This has helped a lot :) Regards, Michal From python.list at tim.thechases.com Wed Mar 12 15:13:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 14:13:24 -0500 Subject: enums and PEP 3132 In-Reply-To: References: Message-ID: <47D82B54.3080206@tim.thechases.com> >> Currently I'm just putting this at the top of the file: >> py=1 >> funcpre=2 >> funcpost=3 >> ... > > That can be done more compactly with > > py, funcpre, funcpost = range(3) I've harbored a hope that a combination of PEP 3132[1] ("Extended Iterable unpacking") and itertools.count()[2] would be available for doing something like this: py, funcpre, funcpost, *unexhausted_iterator = count() which would theoretically allow me to just add new enum names to the LHS without having to update constant passed to range() on the RHS. Unfortunately, it looks like this wasn't a desirable behavior because the PEP describes the "*unexhausted_iterator" notation unpacking as a list, not as an iterable. My desired syntax would work well for bit-mask fields as well: def bit_iter(i=0): assert i >= 0 while True: yield 1 << i i += 1 read, write, execute, *_ = bit_iter() and I'm sure there are other use-cases I've not yet considered. Diez Roggisch hacked together a disturbingly (in the "that hurts my brain to sniff the stack" way) beautiful/functional decorator[3] that does something like this in Python2.4+ and can just be used something like @variably_unpack def just_enough(): return itertools.count() read, write, execute = just_enough() which is a fabulous syntax, IMHO. -tkc [1] http://www.python.org/dev/peps/pep-3132/ [2] http://docs.python.org/dev/library/itertools.html#itertools.count [3] http://groups.google.com/group/comp.lang.python/browse_thread/thread/63dce474e196adac/d98522d9bedae946#d98522d9bedae946 From gbrunick at andrew.cmu.edu Thu Mar 6 02:44:54 2008 From: gbrunick at andrew.cmu.edu (Gerard Brunick) Date: Thu, 06 Mar 2008 02:44:54 -0500 Subject: Short confusing example with unicode, print, and __str__ In-Reply-To: <47CEEBFC.9010001@islandtraining.com> References: <47CEDF77.5050501@andrew.cmu.edu> <47CEEBFC.9010001@islandtraining.com> Message-ID: <47CFA0F6.5020009@andrew.cmu.edu> Gary Herron wrote: > Gerard Brunick wrote: >> I really don't understand the following behavior: >> >> >>> class C(object): >> ... def __init__(self, s): self.s = s >> ... def __str__(self): return self.s >> ... >> >>> cafe = unicode("Caf\xe9", "Latin-1") >> >>> c = C(cafe) >> >>> print "Print using c.s:", c.s >> Print using c.s: Caf? >> >>> print "Print using just c:", c >> Print using just c: Traceback (most recent call last): >> File "", line 1, in >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >> position 3: ordinal not in range(128) >> >>> str(c) >> Traceback (most recent call last): >> File "", line 1, in >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >> position 3: ordinal not in range(128) >> >> Why would "print c.s" work but the other two cases throw an exception? >> Any help understanding this would be greatly appreciated. >> >> Thanks in advance, >> Gerard >> > It's the difference between how __str__ and __repr__ act on strings. > > Here's s simpler example > > >>> d=unicode("Caf\xe9", "Latin-1") > >>> repr(d) > "u'Caf\\xe9'" > >>> str(d) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > > Gary Herron It seems the question is more about what does print do. Lets extend your example: >>> d=unicode("Caf\xe9", "Latin-1") >>> repr(d) "u'Caf\\xe9'" >>> print d Caf? >>> str(d) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Why doesn't the print statement that a UnicodeEncodeError? I assumed that print calls str and then prints the result, but this doesn't seem to be the case. What the heck does print do? From sarobav at gmail.com Wed Mar 12 08:06:32 2008 From: sarobav at gmail.com (sarobav at gmail.com) Date: Wed, 12 Mar 2008 05:06:32 -0700 (PDT) Subject: To download Eclipse, select a package below or choose one Message-ID: <5900f5d9-bec2-4d17-a8bd-e08ea502e531@e23g2000prf.googlegroups.com> To download Eclipse, select a package below or choose one of the third party Eclipse distros. You will need a Java runtime environment (JRE) to use Eclipse ... http://downloadcorner.googlepages.com From bearophileHUGS at lycos.com Tue Mar 4 15:27:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 4 Mar 2008 12:27:26 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> Message-ID: Raymond HettInger: > FWIW, I'm very happy with for-else. Most of the time, you don't need > it, but when you do, it beats the heck out of doing silly tricks with > flags. I'd like it to be renamed to something more natural :-) Bye, bearophile From haraldarminmassa at gmail.com Sun Mar 16 03:33:31 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Sun, 16 Mar 2008 00:33:31 -0700 (PDT) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: <97432b58-958c-43ec-b48a-6849f9abed4a@v3g2000hsc.googlegroups.com> Doug, > as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. > I'm guessing that they can't be in library.zip for a reason (i.e., they are > DLL files, essentially, and thus must be readily available to be loaded > into memory). .dll and .pyd files CAN be within library.zip and even within the single-file-exe. There is some Hellermagic within _memimporter.pyd that loads the .dll and .pyd from a zipfile. When you scan the build_exe.py, you will explicitely find: print "*** finding dlls needed ***" dlls = self.find_dlls(extensions) self.plat_finalize(mf.modules, py_files, extensions, dlls) dlls = [item for item in dlls if os.path.basename(item).lower() not in self.dll_excludes] # should we filter self.other_depends in the same way? > Is there a work-around for this, then? -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/ multiarray.pyd -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/ umath.pyd -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd let's try: your mission is, should you chose to accept it, to make a py2exed application to load two different multiarray.pyd, who are on the visible level only different by their place in the file system. So, please make a minimal script: import multiarray import numpy.core.multiarray as ncmultiarray and, using Peters test >>> from multiarray import zeros assert zeros((1,), "1") == array([0], '1') and check, if those multiarrays are the correct ones. If yes, you can try to build upon this by making all imports explicit as described above. (Yes, I know, that's not necessary in plain python ... but it saved me in some weird "import from .zip" and "import from database" situations.) > (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and > umath.pyd files somewhere deep inside I have a BAAAD feeling about to files having the same name but very very different content - but that's not your call in this situation. Are you able to build that libraries yourself? Then you could move down and build the multiarray.pyd as ncmultiarray.pyd and adjust all imports accordingly. (lots of work) > manual create the "stub"-like .pyc files that py2exe creates to point to > these alternate .pyd files and then place these stubs in > library.zip/numpy/core? ? As much as I know there is only one central "loader stub", which ensures that .dlls get imported from memory, see above. py2exe does not create something like p2elma.py containing "import multiarray.pyd" best luck, and please take your time to scan the py2exe.org wiki, there are many similiar challanges with various packages, maybe you get another workaround-idea (and, if we find one, PLEASE put it down there for others to learn) best wishes, Harald From fetchinson at googlemail.com Mon Mar 31 13:04:31 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 31 Mar 2008 10:04:31 -0700 Subject: [OT] troll poll Message-ID: [Heavily off-topic fun stuff] Hi folks, This is a quick poll to have scientific data on our beloved troll community: Whose trolling behaviour is more professional? (check one) [ ] - Xah Lee [ ] - castironpi More specifically, who can create a bigger mess on c.l.py? (check one) [ ] - Xah Lee [ ] - castironpi More specifically, who is more entertaining? (check one or none) [ ] - Xah Lee [ ] - castironpi Even more specifically, who makes you laugh harder? (check one or none) [ ] - Xah Lee [ ] - castironpi Thanks for your feedback! [/Heavily off-topic fun stuff] From aahz at pythoncraft.com Fri Mar 28 11:43:03 2008 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2008 08:43:03 -0700 Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: In article , wrote: > >I'm having trouble explaining the benefits and tradeoffs of threads to my >coworkers and countering their misconceptions about Python's threading model >and facilities. They all come from C++ and are used to thinking of >multithreading as a way to harness multiple CPU cores for compute-bound >processing. I also encountered, "Python doesn't really do threads" today. >*sigh* > >I don't need pointers to the relevant documentation sections. A bit of >googling didn't turn up much about threading beyond tutorial introductions. >I'm looking for something which will explain the rationale for using threads >in Python to someone who is experienced with multithreading in other >languages (like C/C++). Maybe a compare-and-contrast sort of document? Maybe this will help? http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From kkadrese at gmail.com Wed Mar 19 09:50:18 2008 From: kkadrese at gmail.com (kkadrese at gmail.com) Date: Wed, 19 Mar 2008 06:50:18 -0700 (PDT) Subject: lock access to serial port References: <78873650-1130-4be9-9ea7-3889036b2bbf@a23g2000hsc.googlegroups.com> Message-ID: hmm, now it seems I get to the locking try: ser = serial.Serial(dev, 19200, rtscts=1, timeout=1) if ser.isOpen(): try: fcntl.lockf(ser,fcntl.LOCK_EX) but get into some weirdness - trying to lock does not time out! The script stops at this line and waits ?for ever? (it waits for 15 minutes at least, that I have tried). Andra > not the goal setup but the way I tried it out - a webpage to send an > sms to mobile phone. This is an php what calls a python script. A > python script opens serial device, checks for gsm network, sends a > message - on all the way I try to make sure that appropriate answers > are received from the gsm device so that I know that all is going well > (and if not - cancel it with error message). > > Testing it with sending an sms from two open webpages, I normally got > that one message was sent and for the other I received "try once more, > happened that and that". But I got also an inadmissible situation - > the received sms contained also unwanted text. As far as I can realize > how to deal with it is not allowing writing to the device for two > processes simultaneously. > > Andra > > On 19 Marts, 11:00, taco wrote: > > > kkadr... at gmail.com wrote: > > > hello group, > > > > how to get ttyS0 serial port for exclusive access? I have a python > > > script that uses this device with AT commands. I need that two > > > instances can call simultaneosuly this python script but only one of > > > them gets the device. I tried fcntl.flock, it was just ignored, put > > > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not > > > know what are appropriate arguments), googled half a day for various > > > phrases, error messages etc....without success. > > > > please help, > > > > Andra > > > not sure if I understand you well, but how about a server application which > > accepts 2 clients which can send messages which are output on the serial > > device? The serial device access protected with a mutex while receiving > > messages done in 2 threads or something. > > taco From ricky.zhou at gmail.com Fri Mar 21 17:25:36 2008 From: ricky.zhou at gmail.com (Ricky Zhou) Date: Fri, 21 Mar 2008 17:25:36 -0400 Subject: List question In-Reply-To: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Message-ID: <20080321212536.GD1382@Max.nyc1.dsl.speakeasy.net> On 2008-03-21 05:16:41 PM, From at home.xs4all.nl wrote: > alist = [] > blist = [ 'one','two','one and two','one and four','five','one two'] > for f in blist: > if 'one' and 'two' in f: > alist.append(f) > > for i in alist: > print i > > two > one and two > one two > > > why is it printing the first "two"? Look at the this line: if 'one' and 'two' in f: You're basically saying: if ('one') and ('two' in f): which is why you only get elements that contain 'two'. Ricky -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From devnew at gmail.com Tue Mar 18 01:14:48 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Mon, 17 Mar 2008 22:14:48 -0700 (PDT) Subject: finding euclidean distance,better code? References: Message-ID: <7a96c9d8-ee64-4fd8-b673-09c2a3543667@i12g2000prf.googlegroups.com> On Mar 17, 6:17 pm, "Gabriel Genellina" wrote > > _, imgindex = min((sum(abs(input_wk - weights[image, :])),image) for image > in xrange(numimgs)) > mindistance = abs(input_wk - weights[imgindex, :]) > # normalize and sum again thanks Gabriel D From grante at visi.com Thu Mar 20 12:10:35 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 16:10:35 -0000 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> <0dd3f571-b044-4ea4-8e58-14b21dc3c7b8@z38g2000hsc.googlegroups.com> Message-ID: <13u533r214864e@corp.supernews.com> On 2008-03-20, jmDesktop wrote: >> I believe Grant was suggesting that Emacs often serves a >> similar purpose on Unix to what Visual Studio does on Windows, >> which seemed to be what you were asking. ?When asking about >> Mac OS X here, you are likely to get a lot of generic Unix >> responses. ?(Would it have been clearer if he had just said >> "emacs?") > > No. Typically when someone posts a one-liner search it means > go figure it out and stop bothering "us." I had already > searched. I could not get it to work, Could not get what to work? > which is why I posted. If I took it wrong I apologize. I honestly thought you were asking how to run/debug python programs inside emacs. A couple of the hits answered that question. The others explained how do get python-aware editing modes configured. > I really had two questions. One is just how to run a program from > within the editor and the other is if my thinking on how development > is done in python wrong to start with. Most of my non-Windows > programs have been on Unix using vi, but it has been a while. I'm > used to writing a program in visual studio and running it. Perhaps you'd be more comfortable with one of the IDEs? http://wiki.python.org/moin/IntegratedDevelopmentEnvironments http://en.wikipedia.org/wiki/Comparison_of_integrated_development_environments#Python > If that's the wrong expectation for python programming in > emacs, then I wanted to know. Yes, you can run programs (including python debuggers) from inside emacs. The simplest way is to do "meta-x shell" to get a shell prompt inside emacs, then just type whatever command line you want to use to run the program. Or you can map a command to a keystroke that will run the program. I generally just have another terminal window open where I run the program -- but I've never liked IDEs so your tastes may differ. -- Grant From menosaint at gmail.com Sat Mar 15 11:27:32 2008 From: menosaint at gmail.com (menosaint at gmail.com) Date: Sat, 15 Mar 2008 08:27:32 -0700 (PDT) Subject: string literal or NoneType Message-ID: hi all i want to check a condition and if true should return a filename string from a list.if the condition is false i am returning a "" (string literal).. retv="" if somecondition: retv=mylist[x] ... return retv The calling function will check the return value and print the filename if it is not """. in the calling function i can code if returnval !="": print "filename is:",returnval else: print "no filename found" what i want to know is ,should i rewrite the if returnval !="" as if returnval: print "filename is:",returnval else: print "no filename found" or is the way i coded the right way ? i am little confused here Someone suggested that i make a variable retv None and if the condition true then set retv as filename , retv=None if somecondition: retv=mylist[x] ... return retv which approach is correct..? can someone help please vincent From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 21:23:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 01:23:35 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <3e6de9d7-4278-4b1e-9373-78c98fa11a3f@m34g2000hsc.googlegroups.com> Message-ID: <13utqsnq8le081f@corp.supernews.com> On Sat, 29 Mar 2008 12:49:05 -0700, Carl Banks wrote: >> Please set it straight in 3.0, and if not, convince me with a good >> reason of doing so, so that I can live with it and don't have to spend >> the rest of my life in 2.x ;). > > 1. It's not going to change in Python 3.0. > > 2. It's a silly thing to care so much about that you will avoid using a > langauge because of it. I dislike the attitude that "oh, feature X is unimportant, why should we care about it?". It's often -- but not always -- said by those who do care very much about it themselves, except they prefer the way it is rather then the requested feature. If Guido had a sudden brain tumor and replaced comparison operators with Fortran-style operators, it wouldn't destroy Python. It would just be a minor wart on an otherwise good language. So why should we care about using == instead of .EQ.? Why does Python use # for comments instead of Basic-style remarks? Would it be silly to care if Python 3 discarded # and introduced REM? I could belabor the obvious with dozens of syntax elements which, *in isolation*, it would be silly to care about. But syntax defines the feel of the language. Perl and Java have better (or at least *larger*) libraries, although arguably not as many "batteries included", but the syntax, oh my. We use Python because it is Python and not Perl or Basic or Fortran or Java. If the syntax changes, so does the language. Yes, in isolation the question of != versus <> is a tiny little thing, silly to drop Python merely because of it. But it's not silly to care about the feel of the language. Python is as good as it is because Guido cares very much indeed about the feel of the language, and so do many of we Python users. -- Steven From stef.mientki at gmail.com Fri Mar 28 11:15:45 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 16:15:45 +0100 Subject: class or inherited list ? Message-ID: <47ED0BA1.9020103@gmail.com> hello, Passing all kinds of data between objects, I'm looking for an elegant (and simple) way to pack the data. Now it looks to me that both the class and the inherited list, performs equally well. Till now, the most elegant way (in my view) is the list inheritance, mainly because you don't need brackets and no quotes. What are others opinion about this ? thanks, Stef Mientki class super_list(list): pass def kwadraat ( value ) : return value * value x={} x['frequency']=33 x['functie']=kwadraat print x['functie'](2) y = super_list() y.frequency = 33 y.functie = kwadraat print y.functie(3) From phil at riverbankcomputing.com Fri Mar 28 11:22:06 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Fri, 28 Mar 2008 15:22:06 +0000 Subject: Setting the value of one cell in QTableWidget fills everything. In-Reply-To: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> References: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> Message-ID: <200803281522.07041.phil@riverbankcomputing.com> On Friday 28 March 2008, Constantly Distracted wrote: > I've just started PyQt programming and I've run into this little > problem. When I set the text of one cell in my table, all the other > cells fill with that value. ...because you have only created a single QTableWidgetItem instance, rather than one for each cell. > All I wanted to do was run a loop, printing in each cell the row and > column number. > Here's the code. > > ------------------------------ > > from PyQt4 import QtGui,QtCore > import sys > > class mywindow(QtGui.QWidget): > def __init__(self,parent=None): > QtGui.QWidget.__init__(self,parent) > self.resize(700,700) > self.mytable=QtGui.QTableWidget(7,6,self) > self.mytable.resize(700,700) > > def filltable(self): > items=QtGui.QTableWidgetItem() > for column in range(self.mytable.columnCount()): > for row in range(self.mytable.rowCount()): > items.setText("row: " + str(row) + " column: " + > str(column)) > self.mytable.setItem(row,column,items) > > > app=QtGui.QApplication(sys.argv) > mainwin=mywindow() > mainwin.filltable() > qb.show() > app.exec_() Move the creation of the QTableWidgetItem() to the inner loop (and call it "item" rather than "items"). Phil From george.sakkis at gmail.com Mon Mar 31 18:58:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 15:58:37 -0700 (PDT) Subject: class super method References: Message-ID: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> On Mar 31, 6:25 pm, gigs wrote: > is there any tutorial for super method (when/how to use it)? > > or maybe someone could explain me how it works? > > thx Super is one of the dark corners of the language [1,2]... a good rule of thumb is to stay away from it, or at least stick to its basic usage. George [1] http://www.phyast.pitt.edu/~micheles/python/super.html [2] http://fuhm.net/super-harmful/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Mar 20 08:05:58 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 20 Mar 2008 13:05:58 +0100 Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: <64f296F2b1lqlU1@mid.individual.net> Giampaolo Rodola' wrote: > Is there any way to su or login as a different user within a > python script? I mainly need to temporarily impersonate another > user to execute a command and then come back to the original user. > I tried to google a little bit about it but I still didn't find a > solution. IMHO, the cleanest way from a security perspective would be using sudo. root can even configure it in a way that you don't have to type a password. Regards, Bj?rn -- BOFH excuse #223: The lines are all busy (busied out, that is -- why let them in to begin with?). From gagsl-py2 at yahoo.com.ar Wed Mar 26 00:25:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 01:25:17 -0300 Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk escribi?: >> i'm trying to call subprocess.popen on the 'rename' function in >> linux. When I run the command from the shell, like so: >> >> rename -vn 's/\.htm$/\.html/' *.htm >> >> it works fine... however when I try to do it in python like so: >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) >> >> print p.communicate()[0] >> >> nothing gets printed out (even for p.communicate()[1]) I'd try with: p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (note that I added shell=True and I'm using a raw string to specify the reg.expr.) -- Gabriel Genellina From davids at evertech.com.au Thu Mar 13 18:16:57 2008 From: davids at evertech.com.au (David S) Date: Thu, 13 Mar 2008 22:16:57 GMT Subject: Spaces in path name Message-ID: Hi, I have some code in which I have to change some path names to get it to work. The original code seems to have assumed that path names would not have any embedded spaces. I am not sure how to write the following line so when used in my script the path will be found. ANT_CMD = r'C:\Program Files\apache-ant-1.7.0\bin\ant' Regards, David From davidj411 at gmail.com Wed Mar 5 14:14:10 2008 From: davidj411 at gmail.com (davidj411) Date: Wed, 5 Mar 2008 11:14:10 -0800 (PST) Subject: change user-agent Message-ID: <6a33cbd7-e9a5-475e-a8df-1e68777faaf3@i29g2000prf.googlegroups.com> I came across this post on the net and wanted to know what was meant by down-level module. So, how can we change the User-Agent? If we don't want to change the headers using a lower-level module such as httplib, the solution is quite easy.... From castironpi at gmail.com Sat Mar 29 21:47:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 18:47:26 -0700 (PDT) Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> <3ba288b6-3b34-4362-a9c3-5c6bd489a80c@a1g2000hsb.googlegroups.com> Message-ID: <1e378d28-e4ff-4985-9e2a-806bfd7a4c4b@y21g2000hsf.googlegroups.com> On Mar 29, 7:59?pm, marek.ro... at wp.pl wrote: > I love Paul's response. > > castiro... at gmail.com napisa?(a): > > > > > My crystal ball broke a few days ago due to overuse, but I recall that > OpenGL likes to have power-of-two texture sizes. If that doesn't work, > please trim down your code as far as possible (so that it still > displays the error) and post it. It isn't mine. while 1: it isn't. Try to attach files fail 1. Can link though: any help? From jmcmonagle at velseis.com.au Tue Mar 11 19:33:22 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 12 Mar 2008 09:33:22 +1000 Subject: The stange behaviour of Tkinter.Canvas In-Reply-To: <60bb95410803110404o414ababft8fca994d16cfd60a@mail.gmail.com> References: <60bb95410803110404o414ababft8fca994d16cfd60a@mail.gmail.com> Message-ID: <47D716C2.8040107@velseis.com.au> James Yu wrote: > I tried to update the rectangle on a canvas to get the visual effect of > progressbar. > It works all right if I delete the existing objects (rectangle and text) > and create a new one. > However, if I invoke canvas.itemconfig() to update the existing objects' > options, gui just went nuts. > I am more than happy to receive any help and advise. > Snipped code > canv.itemconfig(rect, width=width*progress/100) ## The width option of a rectangle item does not change the rectangles width, but changes the width of the rectangle perimiter line. You need to modify the coordinates of the rectangle item: canv.coords(rect, 0, 0, width*progress/100, height) Regards, John From bryanjugglercryptographer at yahoo.com Fri Mar 14 18:06:44 2008 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Fri, 14 Mar 2008 15:06:44 -0700 (PDT) Subject: How to send a var to stdin of an external software References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: Floris Bruynooghe wrote: > Benjamin Watine wrote: > > Could you give me more information / examples about the two solutions > > you've proposed (thread or asynchronous I/O) ? > > The source code of the subprocess module shows how to do it with > select IIRC. Look at the implementation of the communicate() method. And here's a thread example, based on Benjamin's code: import subprocess import thread def readtobox(pipe, box): box.append(pipe.read()) cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) myVar = str(range(1000000)) # arbitrary test data. box = [] thread.start_new_thread(readtobox, (cat.stdout, box)) cat.stdin.write(myVar) cat.stdin.close() cat.wait() myNewVar = box[0] assert myNewVar == myVar print len(myNewVar), "bytes piped around." -- --Bryan From gagsl-py2 at yahoo.com.ar Wed Mar 26 14:36:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 15:36:31 -0300 Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson escribi?: > HOw can we use express pointers as in C or python? Traceback (most recent call last): File "", line 1, in File "parser.py", line 123, in parse_text tree = language.parse_text(text) File "english.py", line 456, in parse_text tree = self.parse_sentence(sentence) File "english.py", line 345, in parse_sentence raise ParserError, "can't parse %r" % sentence ParserError: can't parse 'HOw can we use express pointers as in C or python?' -- Gabriel Genellina From http Sun Mar 2 02:02:13 2008 From: http (Paul Rubin) Date: 01 Mar 2008 23:02:13 -0800 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> <7x3ara9r4n.fsf@ruckus.brouhaha.com> Message-ID: <7xskz98v7u.fsf@ruckus.brouhaha.com> Lie writes: > So basically they refused to satisfy everything that is still possible > individually but would conflict if done together. I can't understand that. > x = 1 > a = x + 1 << decides it's an int No, so far a and x are both Num (indeterminate) > b = x + 1.0 << error? or redefine to be float? This determines that a, b, and x are all floats. It's not "redefined" since the types were unknown prior to this. Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional" which is a narrower class than Num but it could still be Float, Double, or Rational. Nums support addition, subtraction, multiplication, but not necessarily division. So int/int is an error. Fractionals support division. > c = x + 1 << would this cause error while it worked in line 2? No, c is also a float (actually Fractional) > A slightly obfuscated example: > l = [1, 1.0, 1] This is the same as l = [1.0, 1.0, 1.0]. In Haskell, all elements of a list must have the same type, so the 1.0 determines that l is a list of fractionals. > x = 1 > for n in l: > c = x + n Haskell does not have loops, but if it did, all these values would be fractionals. From detlev at die-offenbachs.de Sat Mar 1 08:29:13 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 01 Mar 2008 14:29:13 +0100 Subject: ANN: eric 4.1.1 released Message-ID: Hi, eric4 4.1.1 has been released today. This release fixes a few bugs reported since the last release. As usual it is available via http://www.die-offenbachs.de/eric/index.html. Please note, that the first stable release of the Rope refactoring plugin was released as well. What is eric? ------------- Eric is a Python (and Ruby) IDE with all batteries included. It is expandable via a plugin architecture. These plugins are downloadable separately. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From grante at visi.com Sun Mar 9 00:29:42 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:29:42 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> <13t6s8pk90olef8@corp.supernews.com> Message-ID: <13t6te6p71r3u3e@corp.supernews.com> On 2008-03-09, Steven D'Aprano wrote: >> The only times I can recall printing source were in college >> classes where I was required to hand in a hardcopy with the >> assignment and code samples for job interviews. In the real >> world the code base tends to be too huge to contemplate >> printing... > > You've never (say) printed out the source code to one of the > modules in the Python standard library to read and study? Nope. Can't say that I have. I can't really recall printing out a source file in the past 10-15 years. > If your code base is so huge that you can't print out any > meaningful piece, then you desperately need more > encapsulation. >> Even in the early 1990s the moral equivalent of enscript (I think it was >> a2ps) worked just fine for printing with filenames, line/page numbers, >> and other niceties no matter what editor you used. It seems more >> reasonable to mandate using a sane print tool for the odd case where >> someone wants to print things out than to mandate cluttering up every >> file with the filename in a comment. > > Sure, but really, adding ONE LINE to the start of a file is > hardly "cluttering up" anything. Especially if it is in the > doc string, like this: > > """widgets.py: create, manage and destroy widgets. > > blah blah blah blah...""" The bad part is that it's redundant information. That means that eventually, it's going to be wrong. -- Grant Edwards grante Yow! I'm young... I'm at HEALTHY... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From martin at v.loewis.de Mon Mar 3 01:44:57 2008 From: martin at v.loewis.de (=?windows-1252?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2008 07:44:57 +0100 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> Message-ID: <47CB9E69.9000709@v.loewis.de> >> Assuming no major problems crop up, a final release of Python 2.4.4 will >> follow in about a week's time. > > I do suppose you mean 2.4.5. Oops, yes. > 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: > > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp > -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. > -I./Include -DPy_BUILD_CORE -c ./Modules/posixmodule.c -o > Modules/posixmodule.o > ./Modules/posixmodule.c: In function ?posix_setpgrp?: > ./Modules/posixmodule.c:3145: error: too few arguments to function > ?setpgrp? > make: *** [Modules/posixmodule.o] Error 1 > > I can only presume I'm doing something wrong at this point, since I > don't consider myself a Mac OS X developer. No. 2.4.5 just won't compile on OSX 10.5.2. This bug has been fixed for 2.5 (IIUC), but the fix was not backported (nor should it be, as it is not relevant for security). Use OS X 10.4 if you want to use Python 2.4. Regards, Martin From http Sun Mar 9 00:35:51 2008 From: http (Paul Rubin) Date: 08 Mar 2008 21:35:51 -0800 Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> Message-ID: <7xy78sv4qw.fsf@ruckus.brouhaha.com> Chick writes: > I'm writing a security tool which requies wiping off the memory of > certain string after being used, which I've done by implementing it as > a mutable list as follow: You really can't do that reliably in Python and for that matter you can't really do it reliably in any other language, without OS and possibly hardware assistance to make sure the password isn't paged or swapped, etc. In Linux, for example, see the mlock system call. From ptmcg at austin.rr.com Sat Mar 29 20:48:21 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 29 Mar 2008 17:48:21 -0700 (PDT) Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: On Mar 29, 6:37?pm, castiro... at gmail.com wrote: What is the collision of spheres? Is it the melding of a sphere of influence and cosmic sphere? What does it mean to say that such a collision "doesn't work"? The sphere is the optimal solid for storing the maximum volume in the minimum area. A sphere can retain the most heat, with minimum surface area for radiation or conduction, convection of course being dependent not only on surface area but also ambient flow of surrounding conducting fluid if such flow is laminar with respect to Reynold's magic number not to be confused with the numbers of a magic square, which is a two-dimensional shape is there a determination of the collision of a sphere's projection onto a plane with a square on that same plane. I've had it with these MF'in squares on this MF'in plane! --------------------------------- More than iron, more than lead, more than gold I need electricity. I need it more than I need lamb or pork or lettuce or cucumber. I need it for my dreams. From python.list at tim.thechases.com Sat Mar 8 12:57:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 08 Mar 2008 11:57:07 -0600 Subject: Intelligent Date & Time parsing In-Reply-To: <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> Message-ID: <47D2D373.5040600@tim.thechases.com> > I am a GNU newbie. (I know C &o.) Can you point me to a > place to find the source for 'date'? It's part of the GNU Coreutils: http://ftp.gnu.org/gnu/coreutils/ Within the file, you're likely interested in lib/getdate.* It helps if you have a working knowledge of Yacc. -tkc From Lie.1296 at gmail.com Sun Mar 30 14:07:41 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 11:07:41 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> Message-ID: On Mar 30, 5:25 pm, Bjoern Schliessmann wrote: > Lie wrote: > > Ah yes, that is also used (I completely forgot about that one, my > > math's aren't that sharp anymore) and I think it's used more > > frequently than ><. > > Where did you read that (I mean, which country)? I've never seen > this sign in any german or english book on > mathematics/physics/engineering I saw. It was in my elementary school at Indonesia (FYI, it is also used as antonym sign in languages (at least in my country)). And I think I'll retract that claim, >< wasn't the standard, a crossed = is the standard (btw, with a little imagination != looks like a crossed =). From paul at boddie.org.uk Sun Mar 30 14:35:37 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Mar 2008 11:35:37 -0700 (PDT) Subject: html DOM References: Message-ID: <374dfd0b-b2f6-418b-b052-94c802bac639@d4g2000prg.googlegroups.com> On 30 Mar, 01:09, "Sam the Cat" wrote: > Is there a package that would allow me the same or similar functionality for > modifying html code via the DOM model as I have in JavaScript ? I'd like to > parse an html file, then modify it and save the result. You could try libxml2dom which has an HTML parsing mode (like lxml and other solutions based on libxml2): http://www.python.org/pypi/libxml2dom It attempts to provide a DOM API very much like that used by JavaScript implementations. Paul From testone at gmail.com Tue Mar 25 13:00:41 2008 From: testone at gmail.com (Tess) Date: Tue, 25 Mar 2008 10:00:41 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> <34b46ea7-7c87-4742-9d67-0a39e5daf983@e23g2000prf.googlegroups.com> <4e3f9a3d-bf3f-479e-a00d-37a00f95133e@m44g2000hsc.googlegroups.com> Message-ID: Paul - you are very right. I am back to the drawing board. Tess From sjmachin at lexicon.net Tue Mar 25 20:45:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Mar 2008 11:45:13 +1100 Subject: My python interpreter became mad ! In-Reply-To: <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> Message-ID: <47E99C99.2060401@lexicon.net> Furkan Kuru incorrigibly top-posted: > Ok, you're right. > > but I did not give it a chance "not trying python interpreter in another > directory" I don't understand that sentence. > so if we assume the problem exists in every directory, it has something > to do with pythonpath. Why would/should we assume that? > you can try setting pythonpath to some directory and put a re.py there > and try from any directory starting your interpreter and importing re. and achieve the same result: importing the bogus re. What's your point? > > > > On 3/25/08, *John Machin* > wrote: > > Furkan Kuru top-posted: > > Most probably X-Spam added itself to your path. > > What is "X-Spam"? Added itself to Benjamin's path [not mine] in such a > fashion that it is invoked when one does "import re"? > > > you should look at your PATH and PYTHONPATH environment variables. > > Most *IM*probably. Read the traceback: > """ > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > """ > > This is a classic case of a script (which does not guard against side > effects (like spewing out gibberish) when imported instead of being > executed) being given the same name as a Python-included module and > being executed in the current directory and hence ends up importing > itself. > > > > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > > > >> wrote: > > > > On Mar 25, 10:05 pm, Benjamin Watine > > >> wrote: > > > Yes, my python interpreter seems to became mad ; or may be > it's > > me ! :) > > > > > > I'm trying to use re module to match text with regular > > expression. In a > > > first time, all works right. But since yesterday, I have a > very > > strange > > > behaviour : > > > > > > $ python2.4 > > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > > Type "help", "copyright", "credits" or "license" for more > > information. > > > >>> import re > > > X-Spam-Flag: YES > > [snip] > > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > > > >>> > > > > > > What's the hell ?? I'm just importing the re module. > > > > No you're not importing *the* re module. You're importing *an* re > > module, the first one that is found. In this case: your own > re.py. > > Rename it. > > > > > > > -- > Furkan Kuru From siona at chiark.greenend.org.uk Fri Mar 7 07:32:47 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Mar 2008 12:32:47 +0000 (GMT) Subject: for-else References: Message-ID: Jeffrey Barish wrote: >Terry Reedy wrote: >> A for-loop is equivalent to a while loop with the condition 'iterator is >> not exhausted'. ?So do_else when that condition is false -- the iterator >> is exhausted. >I think that this is the most important statement in this thread. As others >have expressed, I too found for-else surprising when I first encountered >it. It made sense to me when I analogized for with if: [ ... ] And to pull those two together, I found while-else comprehensible by analogy with if-else: while stmt: do_something() # stmt is True else: do_something_else() # stmt is False I don't think I've ever used a for-else in the wild, but I have used while-else. And knowing how that works, it's kind of obvious what for-else does. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From jari.aalto at cante.net Fri Mar 7 19:49:56 2008 From: jari.aalto at cante.net (Jari Aalto) Date: Sat, 08 Mar 2008 02:49:56 +0200 Subject: distutils - Is is possible to install without the .py extensions References: Message-ID: * Fri 2008-03-07 Robert Kern gmane.comp.python.general * Message-Id: fqsf3a$4lv$1 at ger.gmane.org > Jari Aalto wrote: >> #!/usr/bin/python >> >> from distutils.core import setup >> import glob >> >> setup(name='program', ... >> scripts = ['program,py'], >> ) >> that the the result is: >> >> /usr/bin/program >> >> instead of: >> >> /usr/bin/program.py > > The easiest and best way is to just rename the file in your source tree to > "program" and be done with it. Is there any other way? This is the source package that I would like to keep intact and just patch the setup.py Jari -- Welcome to FOSS revolution: we fix and modify until it shines From wbsoft at xs4all.nl Mon Mar 10 16:26:52 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Mon, 10 Mar 2008 21:26:52 +0100 Subject: building arbitrary files with distutils? Message-ID: <200803102126.53397.wbsoft@xs4all.nl> Hi all, I want to convert a python project from Makefiles to distutils. Currently the makefiles perform some tasks like building a PNG icon from a SVN file etc. How can I add such commands (including timestamp checking) to a setup.py file, so that it runs when I call 'python setup.py build' ? I can write python functions to perform those command, and I found timestamp checking functions in distutils.dep_util, but just can't find the way to connect such commands to the build step.... w best regards, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi From fn681 at ncf.ca Sun Mar 30 10:45:51 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 30 Mar 2008 10:45:51 -0400 Subject: Why prefer != over <> for Python 3.0? In-Reply-To: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: kwitters at telenet.be wrote: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? > > I've written an article about it to try and save this nice "is not > equal" operator, located at http://dewitters.koonsolo.com/python_neq.html > > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). Algol 60 had no such operator. Algol-W had (not)= [(not) was a negative symbol, not on our current keyboard] Simula 67 introduced <> Pascal uses <> [Pascal is still available - http://www.freepascal.org/] C uses != [http://cermics.enpc.fr/~ts/C/CONCEPT/expressions.html#rel] I prefer <> but I feel that it's better not to have two ways of representing not equal. The powers that be have chosen !=. I accept this on the grounds that current languages seem to have nade that choice. Colin W. From kaushikbarat at gmail.com Mon Mar 3 11:50:33 2008 From: kaushikbarat at gmail.com (kaush) Date: Mon, 3 Mar 2008 08:50:33 -0800 (PST) Subject: urlsafe_b64decoding of xml node text Message-ID: <262999b2-352e-4739-9c7f-050fce38f39b@i7g2000prf.googlegroups.com> Hi All, I am running Apache with mod_python. A post message to my server contains an xml of the form
(some base64 ur-safe-encoded data) I use minidom to parse the xml posted, and now try to decode the data using the following import minidom import base64 decData = base64.urlsafe_b64decode(data) #data is the above mentioned url-safe-encoded data This line fails with the following error Error : Error : character mapping must return integer, None or unicode Error : If i run the same data through a script on the terminal, I am able to successfully decode the data. What could be the reason for this error? Can it be because of some encoding introduced by minidom? I think urlsafe_b64decode takes ascii string. Thanks, Kaushik From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 07:16:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 12:16:14 -0000 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> Message-ID: <13t2cget4hubma9@corp.supernews.com> On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote: > you > could say exec( open( 'modA.py' ).read() ) ==> import modA Yes, you could say that, but you'd be wrong. Please test your code before making such claims in the future. -- Steven From duncan.booth at invalid.invalid Wed Mar 19 05:56:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 09:56:31 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> <4e740d0f-9b1d-4b1d-9f6b-8bd56ea11a65@z38g2000hsc.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > I am puzzled by the failure on 'a in a' for a=[a]. >>> a== [a] also > fails. Can we assume/surmise/deduce/infer it's intentional? > It may be less confusing if instead of an assignment following by a test you just consider doing the test at the same time as the assignment (then again it changes the behaviour so it may just be more confusing). There is a very limited set of values for which you would expect this output: >>> a==[a] True >>> a in [a] True The most obvious one is a simple recursive list: >>> a = [] >>> a.append(a) >>> a==[a]; a in [a] True True Pushing the recursion down a level breaks some of the comparisons: >>> a = [[]] >>> a[0].append(a) >>> a==[a] Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp >>> a in [a] True >>> a in a Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp which may be considered a bug or possibly it is just a limit of the implementation. This also produces an overflow (in fact I think it is just the same situation as above, recursing on the same list is handled, recursing on different but equivalent lists is not): >>> a = []; a.append(a) >>> b = []; b.append(b) >>> a==b Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp From Lie.1296 at gmail.com Sun Mar 30 13:31:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 10:31:14 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <5f474aef-26af-475f-81f2-d062129d927b@c19g2000prf.googlegroups.com> On Mar 30, 10:28 pm, "D'Arcy J.M. Cain" wrote: > On Sun, 30 Mar 2008 08:16:39 -0700 (PDT) > > iu2 wrote: > > > > I'd like to use Python in a commercial application. In fact I would > > > > like to write the application entirely in Python. > > > > But I think I wouldn't like telling what language the application is > > > > written in. > > > > Why is the reason for that? > > > Due to Competitors... I don't want to expost the language I use > > You might hide it from many of your customers but don't count on hiding > it from your competitors. Chances are, if they don't know it because > they just don't care. Even if you create your program in C, it is always possible (for an advanced user/determined competitor) to guess what language (compiler) you're using. And I haven't even mentioned that you can guess Windows Defender is created using Visual Basic Classic (VB6) because one of its windows still use VB6's default icon. There are cues that could hint what language is used to create a program: default icons (e.g. VB6's default icon), interface widgets (notoriously Java's Swing), PEID (which is quite reliable although you could manipulate it), the name (e.g. CPython), included libraries, libraries used (e.g. MSVCRT), etc. And I can't see any obvious advantage you could get by hiding the language you use from your competitors, it isn't like they would switch their language to your language if they can't catch up with you, and they can't anti-advertise you because of the language you used. > I intend to use pyinstaller, so there is no .pyc at all. > The main problem is when I use small programs (as single EXE) sent to > someone as a means of maintenance or debugging. > Sending Python's license file together with one EXE seems to me too > obvious AFAIK (__someone please confirm this__) you don't need to include Python's license in your program, unless you distribute Python's binary/source code (i.e. The Python Interpreter and Friends) in your program. So if you're sending a small program for maintenance or debugging since you don't need to include the Python Interpreter (you assumed that there is already one in the machine) you don't need to include the license. You might need to include the license if the maintenance program is for updating the Python Interpreter though. From __peter__ at web.de Sat Mar 8 11:32:15 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Mar 2008 17:32:15 +0100 Subject: extract multiple ranges from a list References: Message-ID: pi.arctan at gmail.com wrote: > One of my many project involves working with YUV-files, where I need > to reduce > the vertical resolution with a factor of two, i.e. remove every other > scan line. > Today I'm using two for-loops in the fashion shown below > > y = [] > for i in range(0, width*height, width*2): > for j in range(0,width): > y.append(Y[i+j]) > > This approach doesn't feel very pythonic but I can't come up with a > better idea to do it. > I've tried list comprehension and map together with lambda but I can't > get a flattened list > of every other scan-line... > > CIF = 352x288 items for luminance and the aim is to have the list > below: > y = [0:352 704:1056 ... ] >>> width = 3; height = 5 >>> Y = range(width*height) >>> y = [] >>> for i in range(0, width*height, 2*width): ... y.extend(Y[i:i+width]) ... >>> y [0, 1, 2, 6, 7, 8, 12, 13, 14] Probably more efficient, but needs numpy: >>> import numpy >>> width = 3 >>> height = 5 >>> Y = range(width*height) >>> a = numpy.array(Y).reshape(height, width) >>> a array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) >>> b = a[::2] >>> b array([[ 0, 1, 2], [ 6, 7, 8], [12, 13, 14]]) >>> list(b.reshape(len(b)*width)) [0, 1, 2, 6, 7, 8, 12, 13, 14] Peter From castironpi at gmail.com Wed Mar 5 16:49:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 13:49:20 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> Message-ID: > > > > What is a class that is not a module? > > > I'm willing to address convention, in serial or parallel--- (change > > subject to 'what goes on newsgroups'?), but it's not clear from fact > > what assumption who has made. > > Since you did not elaborate on what your efforts were and the extent > they were undesirable (certainly useful info from someone honestly > interested in a helpful answer), I assumed you had made none. I agree. To one of my friends, there's plenty of information in the context that isn't a newsgroup. So I'll state more about my background. Classes and modules are really similar. In Python they're really *really* similar. Actually, at this point, that observation may have more of a subjective component than I'm used to asserting. I pause here for corroboration and others' perspectives. Aren't they? From exarkun at divmod.com Mon Mar 31 13:41:32 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 31 Mar 2008 12:41:32 -0500 Subject: Newbie Question - Overloading == In-Reply-To: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: <20080331174132.6859.253250024.divmod.quotient.24792@ohm> On Mon, 31 Mar 2008 10:23:24 -0700 (PDT), xkenneth wrote: >So i generally write quite a few classes, and in most I need to >overload the == operator. > >If i have two classes, like below: > >Class A: >attribute a >attribute b > >Class B: >attribute a >attribute c > >So if I've overloaded their respective __eq__ functions, and I want to >test whether or not the individual classes attributes are equal, the >code might look something like this: > >class A: > def __eq__(self,other): > return self.a == other.a and self.b == other.b > >class B: > def __eq__(self,other): > return self.a == other.a and self.c == other.c > >Now obviously, if I test an instance of either class equal to each >other, an attribute error will be thrown, how do I handle this? I >could rewrite every __eq__ function and catch attribute errors, but >that's tedious, and seemingly unpythonic. Also, I don't want an >attribute error thrown whenever two classes are compared that don't >have the same attributes. > >I have a sneaky feeling I'm doing something completely unpythonic >here. Give this a look: http://jcalderone.livejournal.com/32837.html Jean-Paul From ggpolo at gmail.com Sat Mar 8 07:16:41 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 8 Mar 2008 09:16:41 -0300 Subject: Timed execution in eval In-Reply-To: <13t3f4u6vb77qf3@corp.supernews.com> References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> Message-ID: 2008/3/7, Steven D'Aprano : > On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote: > > > I have various bits of code I want to interpret and run at runtime in > > eval ... > > > I hope that code doesn't contain any data coming from an untrusted user. > > > > > I want to be able to detect if they fail with error, > > > That's what try...except blocks are for. > > try: > x = eval('1 + 1 = 2') > except SyntaxError: > x = 3 > > > > > I want to be able to time them, > > > That's what the timeit module is for. > > If you do time them, you will find that eval(expr) is MUCH MUCH slower > than just executing expr as normal. > > >>> from timeit import Timer > >>> Timer('1+1').timeit() > 0.25557518005371094 > >>> Timer('eval("1+1")').timeit() > 21.816912174224854 > > If you use eval() a lot, you will have a SLOW program. > > > > > and I want to be able to stop them if they run too long. > > > That's tricky. As far as I know, the only way for a Python program to > stop an arbitrary calculation after a certain period of time it to run it > in a thread. You then monitor the elapsed time, and when the timer > expires, ask the thread to die. And hope it listens. > Or you could use setitimer (not available for now). I opened an issue at roundup to add setitimer and getitimer wrappers to the signal module. It would be great if you could test on your platform. It was done for py3k, but could easily be back ported to python 2.6. http://bugs.python.org/issue2240 > > > > I cannot add code to the eval'd strings that will help me accomplish > > this. > > > You can't? Why ever not? > > Note: that's almost certainly the wrong way to solve your problem, but > I'm curious as to why you can't. > > > > -- > > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From mensanator at aol.com Mon Mar 31 13:13:17 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 31 Mar 2008 10:13:17 -0700 (PDT) Subject: troll poll References: Message-ID: On Mar 31, 12:04?pm, "Daniel Fetchinson" wrote: > [Heavily off-topic fun stuff] > > Hi folks, > > This is a quick poll to have scientific data on our beloved troll community: > > Whose trolling behaviour is more professional? (check one) > > [ ?] - Xah Lee > [ ?] - castironpi > > More specifically, who can create a bigger mess on c.l.py? (check one) > > [ ?] - Xah Lee > [ ?] - castironpi > > More specifically, who is more entertaining? (check one or none) > > [ ?] - Xah Lee > [ ?] - castironpi > > Even more specifically, who makes you laugh harder? (check one or none) > > [ ?] - Xah Lee > [ ?] - castironpi > > Thanks for your feedback! > > [/Heavily off-topic fun stuff] Aren't you making the rather naive assumption that people read this stuff? From michael.wieher at gmail.com Sun Mar 16 10:40:07 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:40:07 -0500 Subject: Pycon disappointment In-Reply-To: <1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> Message-ID: 2008/3/16, Aaron : > > > > In my opinion, open spaces should have had greater status and billing, > > with eyes-forward talks and vendor sessions offered only as possible > > alternatives. Especially, vendor sessions should not be presented as > > "keynotes" during plenary sessions. I think it took a little while > > for people to catch on to the idea that they could have control of > > their own experience through the open spaces and that the main > > offerings were not the only option. > > This is an excellent suggestion and observation. Sold sponsorships > are fine as long as they are billed as such. Labels on the vendor > speeches indicated they were sold as ad space would be great, as well > as more strongly emphasizing the ad hoc discussion spaces. But vendors often don't label themselves as vendors. And often, the researcher or individual in question, who has something worth saying, does have a professional job of sorts, which might be related to his or her work or speech. I've heard people give very long, detailed talks about interesting topics, that did have a spin on them, but contained worthwhile information also. Now, is that to be billed as a "vendor" (and ignored) or not? Further, no vendor who is trying to sell a product will allow themselves to be marked in an obvious way as advertising, knowing that they'll be ignored. At least, they certainly won't pay for the time/space to any real degree, knowing they'll be walking in under a cloud like that. -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurent.pointal at laposte.net Mon Mar 31 12:07:38 2008 From: laurent.pointal at laposte.net (Laurent Pointal) Date: 31 Mar 2008 16:07:38 GMT Subject: Where can I find : References: Message-ID: <47f10c4a$0$906$ba4acef3@news.orange.fr> Le Sat, 29 Mar 2008 20:15:59 -0700, pythonnubie a ?crit?: > Hi All : > Does anyone know where I can find either a book or a website that > explains beginning python by actually building a project line by > line and explaining it indepth . I am primarily interested in > understading flowcontrol as well as syntax . > > If it was related to netwoprking then that would be a great addition > although not required because that is my primary field of interest . > > All help greatly appreciated ! > > Mark You may look at "Dive into Python", there is an online version, translation in some languages other than english (if needed). It propose a line by line explanation on many scripts targetting language and libraries usage. http://www.diveintopython.org/ -- Laurent POINTAL - laurent.pointal at laposte.net From aboudouvas at panafonet.gr Thu Mar 20 18:57:13 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 20 Mar 2008 15:57:13 -0700 (PDT) Subject: What is The Eric4 IDE??? References: Message-ID: <7c7752c7-660e-4d48-8bb6-82f326b52644@u10g2000prn.googlegroups.com> I use it for some time now and i think it is the best Python IDE out there, especially if someone wants to "play" with Qt. If you are on Windows, just install the Windows binary, it' all there! From justdelegard at gmail.com Thu Mar 27 10:19:51 2008 From: justdelegard at gmail.com (Justin Delegard) Date: Thu, 27 Mar 2008 10:19:51 -0400 Subject: dynimac code with lambda function creation Message-ID: <47EBAD07.9010603@gmail.com> So I am trying to pass an object's method call to a function that requires a function pointer. I figured an easy way to do it would be to create a lambda function that calls the correct method, but this is proving more difficult than I imagined. Here is the function I'm using: def objectMethodCallerFunctionCreator(testerObj, method): exec("y=lambda x: testerObj."+method+"(x)") return y Where testerObj is an instance of an object, and method is a string representing the method to call. The problem is, when I actually run the function created (y in this case), it tells me it can't find the symbol testerObj in the global scope. I have successfully created similar functions, except without using the exec() call. e.g. def functionCreator(a, b, c): return lambda d: myFunc(a, b, c, d) and it doesn't complain about the variables a, b, or c when being run. I am assuming this is happening because of the exec() call, but I don't see another way of calling a variable method on an object. Is there some other way to do this that I'm missing? I tried passing in 'method' as a function pointer (to the method of the object), but that didn't work either. Thanks, Justin From deets at nospam.web.de Thu Mar 13 12:09:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 17:09:26 +0100 Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> Message-ID: <63t1tnF29egotU1@mid.uni-berlin.de> azrael wrote: > A little problem. > > Can I directly show Pil objects "image.open("bla.jpg") in Wx or do I > have to transform them. > > If I have to transofm them How can I do it. Pixel by pixel or is there > somethin built in in pil or wx or python. > pilj->wx and wx->pil. PIL doesn't depend on wx, so if anything then wx knows about PIL. But I doubt it. Instead, use cStringIO and save a PIL-Image to memory, then use that as file-argument to something that works for wx - no idea what, but there should be means to load JPEGs and so forth. If file-objects aren't enough, create a temp-file. No, that's not to slow. Diez From castironpi at gmail.com Tue Mar 4 13:11:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:11:03 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: <8d7c34f6-83c5-4c39-8966-56ce141e62f3@s12g2000prg.googlegroups.com> On Mar 4, 10:50?am, Lie wrote: > On Mar 4, 1:12?pm, Mensanator wrote: > > > > > > > On Mar 3, 11:58?pm, Erik Max Francis wrote: > > > > Mensanator wrote: > > > > While we're on the subject of English, the word "worthless" > > > > means "has no value". So, a program that doesn't work would > > > > generally be "worthless". One that not only doesn't work but > > > > creates side effects that cause other programs to not work > > > > (which don't have bugs) would be "worse than worthless". > > > > All programs have bugs, which means that in some circumstances, they > > > won't work. ? > > > And in such circumstances, would be worthless. > > > > Therefore, by your reasoning, all programs are worse than > > > useless. > > > That doesn't follow from my reasoning. > > > Suppose you downloaded a new calculator program that > > couldn't add properly. That would be useless to you, right? > > > But suppose the program contained a virus that erased > > your hard drive. That would be "worse than useless", wouldn't it? > > > > > I'm not hard to please at all. > > > > No, of course not, since logically you must think all software is useless. > > > Somehow, I expected better logic from people who call themselves > > programmers. > > Mensanator, for alls sake, you've done right by pointing out the bug > instead of muttering silently in your room, but there is a thing > called tolerance that you really should learn, it's about tolerating > and understanding the possibility that other people are humans too and > humans create mistakes, lots of them in fact and that includes you (if > you're humans). Along with tolerance should come a better choice of > wordings, instead of saying "it sucks because it does something > unexpected and unwanted" and telling everyone not to use it, you could > just say "it does something unexpected and unwanted" and say that you > wanted it fixed. It's not that you've done anything wrong, but it's > about your attitude.- Hide quoted text - > > - Show quoted text - All of your statements were true. You expressed your emotions, your observations, and desire. You corrected statements incorrect that others made earlier. Others gave you orders, their observations of your character, and expressed their emotions. Now keep your noses in the keyboard and simmer down. I won't stand for this. From cwitts at gmail.com Wed Mar 12 17:28:15 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 14:28:15 -0700 (PDT) Subject: Different results when running script from IDLE versus Command Line References: <895b88e4-694d-4fee-a633-08aa8a407999@p73g2000hsd.googlegroups.com> Message-ID: On Mar 12, 8:10 pm, Casey T wrote: > Hi, > > I'm new to Python and I'm having some problems with getting different > results from my script when I run it from IDLE versus just double- > clicking the .py file and having it run through the command line. > Basically, my script reads some CSV files, assembles a text files, > then uploads that test file to an ftp site. When I run the script from > IDLE, everything works fine. But when it runs from the command line, > the file that gets uploaded is empty. It seems that it is creating a > new file to upload, rather than using the existing file (or at least > that's what I think is going on.) Below is my script. I apologize for > any ugly code. Thanks for your help. > > import sys,os,linecache,csv,ftplib,time > > starttime = time.time() > > #******* > #Summary file assembling > #******* > currentdir = "//folder/" > > reg_sum = open('reg_sum.txt','w') > reg_sum.close > > for files in os.listdir(currentdir): > reg_file = csv.reader(open(currentdir + files)) > for row in reg_file: > reg_sum = open('reg_sum.txt','a') > reg_sum.write(",".join(row) + ',\n') > > reg_sum.close > > #******* > #Summary file processing > #******* > coordList = [ > ["F10",40.0053,-75.0927], > ["T10",40.0272,-75.1123], > ["D22",39.9811,-75.0998], > ["P02",40.0437,-75.0217], > ["D68",39.9203,-75.1388], > ["D51",39.9534,-75.1405], > ["S43",39.9217,-75.2275], > ["S33",39.9360,-75.2077], > ["S42A",39.9215,-75.1937], > ["S05",39.9617,-75.1782], > ["T14",40.0165,-75.1077]] > > coordList_index = > ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"] > #coordList_index is a list containing > > in_text = open('reg_sum.txt','r') > > out_text = open('reg_out.txt','w') > out_text.close > > out_text = open('reg_out.txt','a') > > for line in in_text: > split_line = line.split(',') > if (split_line[0]) in coordList_index: > i = coordList_index.index(split_line[0]) > coords = str(coordList[i][1]) + "," + str(coordList[i][2]) > last_update = str(split_line[2]) > print str(split_line[0]) > if split_line[1] == "1": > out_text.write(split_line[0] + "
,Test1: " + last_update + > "," + coords + ",1" + "\n") > elif split_line[1] == "0": > out_text.write(split_line[0] + "
,Test2.
Last updated: " > + last_update + "," + coords + ",0" + "\n") > else: > out_text.write(split_line[0] + "
,No data.," + coords + > "\n") > > in_text.close > > ###******* > ###Uploads file via FTP > ###******* > s = ftplib.FTP('ftp.blah123.org,'user','pass') > > f.open('reg_out.txt','r') > s.storlines('STOR reg_out.txt', f) > > f.close() > s.quit() > > print "Processed in " + str(((time.time() - starttime) / 60) *60) + " > seconds!" #prints elapsed time You never closed your file. file_object.close try adding '()' at the end of your close calls. As to why it differs, I can't think offhand why it wouldn't. From tjreedy at udel.edu Wed Mar 5 16:17:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Mar 2008 16:17:32 -0500 Subject: Def generating a function to be ran in another context References: <1e5bcefd0803051218q1e73cea2m600ea73098171431@mail.gmail.com> Message-ID: "Marcelo de Moraes Serpa" wrote in message news:1e5bcefd0803051218q1e73cea2m600ea73098171431 at mail.gmail.com... | I'd like a certain function to generate a method for another class and this | new method to be called in the context of the "new" class. Is it possible | with Python? Yes. (Assuming I understand your question correctly.) From castironpi at gmail.com Sun Mar 16 21:22:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 18:22:08 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> <1befdccf-2efc-4640-bcf8-b4a792d8e646@i29g2000prf.googlegroups.com> <5782d52d-0f8c-42b8-9ccc-7445616e5717@u10g2000prn.googlegroups.com> Message-ID: <03d7cf0f-3ae4-4510-9147-6fb9499907c8@b64g2000hsa.googlegroups.com> > > > The trick in the case of when you do not want to guess, or the choices > > > grow too much, is to ask the user to tell you in what format they want > > > it and format according to their wishes. > > > > Neatly avoids too much guessing and isn't much extra to add. > > > The plot is about understanding input, not formatting output. > > And what he meant is simply to make an agreement with the user on how > he/she would format his/her input and to disallow input from formats > that haven't been agreed to avoid guessing. That is the cleanest and > most polite solution, although I'd suspect it would be considered less > user friendly by regular user although power user would be most happy > with that. This one comes from signal theory, actually. With no information about the signal's transmitter, there's no way to guess what language/ customs/manners/convention/protocol he's using. That is, for every protocol, there exists a second protocol which mimics it for the first n bits with a different meaning. There's the Gettysburg Compression Method which transmits a '1' to send the Gettysburg Address, and prepends a 0 to every other message. Of course, there is already an agreed convention. You can tell if you speak a stranger's language once you start interacting-- that is, enter a verbal context with him. There aren't any two -existing- languages which overlap for long at all. 'Can you buy me beer?' does not mean anything in anything but English-- it's gibberish in every other. When it comes to computers, the bandwidth and context mass might be so tiny so far that there's much ambiguity. "Is 11/30 a fraction, a month, or a date?" -"Fraction." "Please proceed." Outside of those two factors, there is not much difference between "natural" and formal systems. Bandwidth is easy enough to increase-- just add a camera, a mic, chemovoltaic, tactilevoltaic, or some specialization of one. Context is the hard thing to grow. "Or, is there another protocol I can look up?" -"Yeah, I know the bartender." "Your statement changed context-determined probabilities. Your own context has been forked." "Your statements have suggested that you have adopted a new convention which I recognize. Is APR 03 a month or a finance model? (You nor the convention neither use statements with the form Apr 03 to mean days.)" -"*plonk*" "You seem to maintain that there are no other users and/or that you have unlimited property right." -"*crowbar*" "This action will void the warranty. Continue?" -"*incendiaries*" "We're just glad you're not organize enough to boycott." -"*boycotts*" "Your usage of that term is inconsistent. Please purchase higher bandwidth." -"*speechless*" "What are you doing, Dave?" -"I won't stand for this." "What are you saying?" From http Wed Mar 5 14:52:38 2008 From: http (Paul Rubin) Date: 05 Mar 2008 11:52:38 -0800 Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: <7xlk4x6j95.fsf@ruckus.brouhaha.com> gideon writes: > In the context of a master's thesis I'm currently looking into > Python's operational semantics. Even after extensive searching on the > web, I have not found any formal model of Python. Therefore I am > considering to write one myself. I doubt if anything serious has been done in that area, and I don't think Python culture operates like that very much. Python programming tends to use informal processes with a lot of reliance on test-driven development and unit tests, rather than formal specifications. A lot of the operational behavior that people rely on basically comes from accidents of implementation, e.g. file descriptors being closed automatically when the last reference goes away. But of course that should not be included in a formal semantics, yet that means the semantics wouldn't describe actual production programs out there. From pydecker at gmail.com Sat Mar 1 21:58:54 2008 From: pydecker at gmail.com (Peter Decker) Date: Sat, 1 Mar 2008 20:58:54 -0600 Subject: Where's GUI for Python? In-Reply-To: <62tvhmF256jk7U1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: On Sat, Mar 1, 2008 at 3:35 PM, K Viltersten wrote: > I'm certain there is an API for creating > GUI's but as far i can find it in the > http://docs.python.org/tut/tut.html > the only "gui" is in "Guido". Check out Dabo: http://dabodev.com It uses the wxPython UI toolkit, but wraps it in a much more Pythonic API. I've been using Dabo for over a year, and it rocks!! -- # p.d. From deets at nospam.web.de Sat Mar 29 09:46:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 14:46:18 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <87d4pe9caz.fsf@mulj.homelinux.net> References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> Message-ID: <656vhnF2e9ao7U1@mid.uni-berlin.de> Hrvoje Niksic schrieb: > "Diez B. Roggisch" writes: > >>> systems. (In theory, file input/output should also be available as >>> asynchronous code, but async IO is low-level and not available in >>> Python.) While threads shouldn't be considered a replacement for >> I suggest you tell that the twisted-guys. And the ones from the >> built-in asyncore-module. > > Note that I said "*file* input/output". Twisted and asyncore are > about asynchronous socket programming that polls over nonblocking file > descriptors such as found in socket programming, not about wrapping > aio(3) and the equivalent Windows APIs. I admit glossing over the file-input - however this is available on posix-systems using the select-module. So if I were in nitpicking-mood, your assertion still would be false - albeit having to consider platoform dependencies certainly is unfortunate and could be considered "missing". I'm pretty sure though that tiwsted & asynchore don't poll, but instead use the select-module. Which at least for unix (and AFAIK for Windows as well) is asynchronous - you get notified if data arrives or has been transmitted, and otherwise your process sleeps. Diez From adrianbn at gmail.com Mon Mar 17 17:16:16 2008 From: adrianbn at gmail.com (=?ISO-8859-1?Q?Adri=E1n_Bravo_Navarro?=) Date: Mon, 17 Mar 2008 22:16:16 +0100 Subject: Comunicate processes with python Message-ID: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> Hi, let me introduce ourselves first. We are a smallish group of students working on a open source snapshot/backup system (www.hdlorean.com or http://launchpad.net/hdlorean). We are using python for almost all of the code and for all of us this is the first python project we develop. At this point I must say that we are really happy with python, as it is a fast learning and easy language. Now I've just bored most of you, I would like to make a question to the list. Let me portray the scenario: We have a daemon (hdloreand) running. We also have a console so you can send commands to the daemon and retrieve some info. At this moment, that console is connecting to the daemon via Dbus. We would like to avoid this, because it will solve some collateral problemas as well as will guarantee that the comunication will work when no X server and no dbus session is running. Is there any simple way to achieve this goal? We've been thinking of sockets but Im not conviced at all with that. Thanks Adrian PS: Im sorry for my english. -------------- next part -------------- An HTML attachment was scrubbed... URL: From smartpawn at gmail.com Sat Mar 15 09:57:44 2008 From: smartpawn at gmail.com (Deepak Rokade) Date: Sat, 15 Mar 2008 19:27:44 +0530 Subject: Using threads in python is safe ? Message-ID: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Hi All, I want to use therads in my application. Going through the docs , I read about GIL. Now I am confused whether using threads in python is safe or not. One thing I know that if I am accessing global variables in two or more threads I need to synchronize them using locking or such mechanism so that only one thread access them at a time. below are few questions for which I am looking answers. 1. In order to support multi-threaded Python programs, there's a global lock that must be held by the current thread before it can safely access Python objects. Does this lock need to be held by python application script expliciltly before accessing any python object or interpreter takes acre of it ? 2. Does multithreaded python script need to held lock before calling any blocking I/O call? Or one should not worry about GIL while using python threads if job to be processed by thread does not call any global variables and thread unsafe Python/C extension ? 3. I. want to use threadpool mechanism in python. Would it not help in multiprocessor environment if job to be processed by worker thread is I/O bound ? Sorry there are many questions here , but mostly they are related and are because I am confused with GIL funda. -- Thanx & Regards, Deepak Rokade Do what u Enjoy & Enjoy what u Do........... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bernard.chhun at gmail.com Wed Mar 12 07:29:27 2008 From: bernard.chhun at gmail.com (Bernard) Date: Wed, 12 Mar 2008 04:29:27 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> Message-ID: <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Hey Larry, that one is fairly easy: >>> from array import array >>> array('i', [1, 2, 3, 4, 5, 1, 2]) >>> def count(x, arr): cpt = 0 # declare a counter variable for el in arr: # for each element in the array if el == x: # when it is equal to the 'x' value cpt+=1 # increment the counter variable by one return cpt # return the counter after the loop >>> count(1,a) 2 I'm pretty sure there must be an easier way though :) On 12 mar, 06:26, Larry wrote: > Dear all, > > I'm new to Python. I have a file (an image file actually) that I need > to read pixel by pixel. It's an 8-bit integer type. I need to get the > statistics like mean, standard deviation, etc., which I know a little > bit already from reading numpy module. What I want to know is how to > get the number of occurences of numeric element in an array. Say, > > b = array(([2, 2, 3, 4, 5, 5]) > > b.count(2) certainly does not work. Is there any more efficient way > other than converting this as string characters? My data will produce > a fairly large array like 400x400 = 160000 values. Hoping you guys can > help me. > > Larry From xkenneth at gmail.com Mon Mar 31 16:45:23 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 31 Mar 2008 13:45:23 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> <304acc0a-3944-44a4-8626-30c2ab9da506@z38g2000hsc.googlegroups.com> <08805546-531f-4b5e-83fc-8b30b0e45db6@s37g2000prg.googlegroups.com> Message-ID: On Mar 31, 3:42?pm, Amit Gupta wrote: > On Mar 31, 11:00 am, xkenneth wrote: > > > Yeah, this is what I'm talking about: > > > > def __eq__(self, other) : > > > ? try : > > > ? ? ?return <> > > > ? except AttributeError: > > > ? ? ?return False > > > That seems a bit nasty to me. > > One thing about python (IMO); you can't just say this doesn't look > good. You need to say: why do you think this is not good. > To me, it appears a concise and local solution to your problem. Yes it is, but it's also tedious and lengthy for should-be simple statements. From castironpi at gmail.com Sun Mar 2 14:21:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 11:21:26 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: On Mar 2, 11:38?am, Steve Holden wrote: > Nobody thinks you are a fool for wanting help with your problems, it's > simply that you have to provide enough information about what' wring for > us to get a handle on the issues. This worked: import socket from time import time for i in range( 20 ): HOST = '' PORT = 80 #<---- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) print( 'listen' ) s.listen(1) conn, addr = s.accept() print( 'connected', addr ) print( conn.recv( 4096 ) ) #<---- conn.send( bytes('test %f'%time(),'ascii') ) conn.close() #<---- s.close() ... and connect with a browser: http://localhost/ if it's internet exploder. From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:30:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:30:11 -0300 Subject: class or inherited list ? References: <47ED0BA1.9020103@gmail.com> Message-ID: En Fri, 28 Mar 2008 12:15:45 -0300, Stef Mientki escribi?: > Passing all kinds of data between objects, > I'm looking for an elegant (and simple) way to pack the data. > Now it looks to me that both the class and the inherited list, > performs equally well. > Till now, the most elegant way (in my view) is the list inheritance, > mainly because you don't need brackets and no quotes. > What are others opinion about this ? > > class super_list(list): > pass > > def kwadraat ( value ) : > return value * value > > x={} > x['frequency']=33 > x['functie']=kwadraat > print x['functie'](2) > > y = super_list() > y.frequency = 33 > y.functie = kwadraat > print y.functie(3) You don't use y as a list at all - you might as well inherit from object. And in that case you get a generic attribute container - as you said, like a dict but using attribute syntax (drawback: only valid names can be used as keys) But I don't understand the "functie" usage - what's for? Perhaps if it used y.frequency - in that case a proper method would be better. -- Gabriel Genellina From dewitters at gmail.com Sun Mar 30 04:13:04 2008 From: dewitters at gmail.com (dewitters at gmail.com) Date: Sun, 30 Mar 2008 01:13:04 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <0964631d-67e4-4c7f-968e-5bf42c0787c2@d45g2000hsc.googlegroups.com> On Mar 29, 6:34 pm, Lie wrote: > You're forcing your argument too much, both != and <> are NOT standard > mathematics operators -- the standard not-equal operator is >< -- and > I can assure you that both != and <> won't be comprehensible to non- > programmers. What I meant was that both < and > are standard mathematics operators, and that by that knowledge one could deduce what <> means. But >< would also be fine by me :). From castironpi at gmail.com Sat Mar 8 15:27:23 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:23 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <47D2C25C.9050400@v.loewis.de> Message-ID: <50943715-483f-4f7d-9d7b-c17ed2ae5984@p73g2000hsd.googlegroups.com> > Notice that the language specification *deliberately* does not > distinguish between deletion of earlier and later items, but > makes modification of the sequence undefined behavior to allow > alternative implementations. E.g. an implementation that would > crash, erase your hard disk, or set your house in flames if you > confront it with your code still might be a conforming Python > implementation. Actually, PEP 4122 makes this a SetHouseInFlames error. Do you want to include this one? Just use _toaddafter= type( container )(). P.S. Equivalence class light, on the rocks. From janeczek at gmail.com Fri Mar 28 12:28:08 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Fri, 28 Mar 2008 17:28:08 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: <7xabkjbawl.fsf@ruckus.brouhaha.com> References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> <7xabkjbawl.fsf@ruckus.brouhaha.com> Message-ID: <561cb5bc0803280928v651a5d28qd4510f34e779bc01@mail.gmail.com> On 27 Mar 2008 23:49:46 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Micha? Janeczek" writes: > > However, the type of embedding that I imagined would be mostly > > pure functions, since Python can deal with IO rather well. It'd also > > be applicable in situations where we want to add some functionality to > > to existing, large Python project, where the complete rewrite > > would be infeasible. > > Of course I can't say what functions someone else would want to use, > but I'm not seeing very convincing applications of this myself. There > aren't that many prewritten Haskell libraries (especially monomorphic > ones) that I could see using that way. And if I'm skilled enough with > Haskell to write the functions myself, I'd probably rather embed > Python in a Haskell app than the other way around. I was talking mostly about writing new components there, not just using libraries. It'd apply to situations where there already exists a large Python infrastructure. > > I didn't mention this in this first draft, but I don't know (yet) > > how to support those "fancy" types. The plan for now is to export > > monomorphic functions only. > > This probably loses most of the interesting stuff: parser combinators, > functional data structures like zippers, etc. Unless you mean to > use templates to make specialized versions? That is true, but as you said before, using them directly from Python would be unwieldy. In most cases writing a thin wrapper in a language of the library that is going to be used is a much more natural way (same might apply to calling Python from Haskell). The plan for now is to start with monomorphic functions, then add support for parametrically polymorphic functions (that is ones that don't care about the type at all, i.e. List.length), and then possibly extend this to some type classes that we can reasonably expect to find on the Python side (Eq, Ord, etc.) > > As for GC, I think having the two systems involved is unavoidable if > > I want to have first class functions on both sides. > > This just seems worse and worse the more I think about it. Remember > that GHC uses a copying gc so there is no finalization and therefore > no way to notify python that a reference has been freed. And you'd > probably have to put Haskell pointers into Python's heap objects so > that the Haskell gc wouldn't have to scan the whole Python heap. > Also, any low level GHC gc stuff (not sure if there would be any) > might have to be redone for GHC 6.10(?) which is getting a new > (parallel) gc. Maybe I'm not thinking of this the right way though, I > haven't looked at the low level ghc code. GHC does support finalization, at least for foreign pointers. I don't think there is going to be any major change to the foreign interface, either. Otherwise I wouldn't be bothering myself really ;) The idea here is to have Haskell track most of Python objects (I think that'll be much easier), and the other way around when it's really necessary. > Keep in mind also that Python style tends to not use complex data > structures and fancy sharing of Haskell structures may not be in the > Python style. Python uses extensible lists and mutable dictionaries > for just about everything, relying on the speed of the underlying C > functions to do list operations very fast (C-coded O(n) operation > faster than interpreted O(log n) operation for realistic n). So maybe > this type of sharing won't be so useful. Yes, but for now I think it is necessary for function callbacks (Haskell calling Python giving it a higher order function). And if we decide to support that, we might as well investigate other use cases. > It may be simplest to just marshal data structures across a message > passing interface rather than really try to share values between the > two systems. I agree that it'll be simplest, that's why I chose it as a first step :) > For fancy functional structures, from a Python > programmer's point of view, it is probably most useful to just pick a > few important ones and code them in C from scratch for direct use in > Python. Hedgehog Lisp (google for it) has a nice C implementation of > functional maps that could probably port easily to the Python C API, > and I've been sort of wanting to do that. It would be great if > you beat me to it. Nice link about Hedgehog lisp :) As for porting its data structures to Python, I don't think it is a large enough project for SoC. And I also hope that the Haskell<->Python can bring more benefits to the users of both languages. > One thing I highly recommend is that you join the #haskell channel on > irc.freenode.net. There are a lot of real experts there (I'm just > newbie) who can advise you better than I can, and you can talk to them > in real time. Yes, I do drop by in there sometimes.. But what I'm after here is an opinion of a Python programmer :) Thanks again :) Michal From haag at lsu.edu Sun Mar 23 14:57:59 2008 From: haag at lsu.edu (Alaric Haag) Date: Sun, 23 Mar 2008 13:57:59 -0500 Subject: A "roadmap" for ctypes wrapping? Message-ID: Hi all, I'm undertaking a pretty significant wrapping project (a linux shared-object lib) early in my Python experience, and thought it might be useful for many more that just myself if this thread were to produce a sort of roadmap for approaching wrapping with ctypes. I've been doing some reading, but want to verify my "big picture view" and have come to make the following presumptions: (so, please correct me where erroneous) - One gathers the ".h" header(s) for the library to determine the data structures (defined in "#define" and "typedef" statements) as well as the prototypes for the library routines. - From these header files, one defines attributes to reproduce the "#define" statements, and also reproduces the typedef "structs" by defining classes and assigning a Python list of tuples for the "_fields_" attribute, to associate a ctype and field name with each field in the "struct". - Use ctypes.CDLL to "connect" to the library, and instantiate an object whose attributes are the library routines. - From that object, instantiate each of the routines, and override the "argtypes" attribute for each of these with a list of "ctypes", and a single ctype for the "restype" attribute. In either case, the "type" might be a newly-defined type (class) that's more complex than just the provided ctypes. Presumably, judicious use of the leading "_" (underscore) is used to hide (make private) the "ugly details" from the wrapper user, revealing only the routines, and possibly, classes that describe data types the original API expects the user to need. ====== Can anyone with some "wrapping" experience add/modify/enhance the above? Many thanks for all feedback! -- Alaric From fraleysinger at gmail.com Wed Mar 12 19:14:35 2008 From: fraleysinger at gmail.com (fraleysinger at gmail.com) Date: Wed, 12 Mar 2008 16:14:35 -0700 (PDT) Subject: agg (effbot) References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> <63q90kF268j23U1@mid.uni-berlin.de> Message-ID: <9688df1a-33fb-4083-8ce1-d84fbfd57e91@a70g2000hsh.googlegroups.com> On Mar 12, 10:52?am, Gerhard H?ring wrote: > fraleysin... at gmail.com wrote: > > Downloaded to Knoppix 5.1: > > : > > aggdraw-1.2a3-20060212.tar.gz > > > Followed README. ?Wouldn't compile. [...] > > Try shegabittling the frotz first. If that doesn't help, please post the > output of the compile command that threw the error. > > -- Gerhard You guys were correct to snicker. Tried it in Knoppix 5.0 and it worked. That led my friend (I was at his house last night) to retry it on Knoppix 5.1.1 and it was a simple error: Python.h was left off that version. We should have seen it straightaway. Thanks for replying. From python1 at infocentrality.co.uk Tue Mar 11 12:07:00 2008 From: python1 at infocentrality.co.uk (Trevor Hennion) Date: Tue, 11 Mar 2008 16:07:00 +0000 (UTC) Subject: Python Contract/Job Opportunity Message-ID: InfoCentrality are a small company who provided a custom Web/Database application for a customer in the Insurance industry. Our customer now wants a number of improvements to this application. To provide these improvements in a timely manner we need an additional programmer. 3 months contract initially - possibly leading to much more. We use Python, PostgreSQL, Html, Javascript and Linux. Suite a recent Computer Science or Programming graduate. Location - just south of Reading, Berks, UK. Must be able to travel to us. Phone Trevor Hennion on 0845 5083766. From http Thu Mar 13 06:49:14 2008 From: http (Paul Rubin) Date: 13 Mar 2008 03:49:14 -0700 Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> Message-ID: <7xtzjalx05.fsf@ruckus.brouhaha.com> Paul Rubin writes: > "Hendrik van Rooyen" writes: > > Given the following three lines of code at the interactive prompt: > > > > foo = [1,2,3,4] > > x = foo.append(5) > > print x > > > > What will be the output (choose one): > > 4) Nothing - no output Correction, it will print None, there is an explicit print statement that went past me. I'm sleepy. From castironpi at gmail.com Tue Mar 18 21:11:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 18:11:32 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: On Mar 18, 6:38?pm, Arnaud Delobelle wrote: > On Mar 18, 3:59?pm, Ninereeds wrote: > > > Hrvoje Niksic wrote: > > > This doesn't apply to Python, which implements dict storage as an > > > open-addressed table and automatically (and exponentially) grows the > > > table when the number of entries approaches 2/3 of the table size. > > > Assuming a good hash function, filling the dict should yield amortized > > > constant time for individual additions. > > Isn't this average constant time rather than amortized? > > > OK. I obviously need to look up open-addressed tables. I thought this > > was just, in effect, implicit linked listing - ie it still needs a > > linear search to handle collisions, it just avoids the need for > > explicitly stored link fields. Perhaps I'm mistaken. > > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > link to further details. Is there a known algorithm which for Key A, Key B s.t. h( KeyA ) = h( KeyB ) for hash function h, h( KeyA, 1 ) != h( KeyB, 1 ), where h( x, i+ 1 ) is searched when h( x, i ) is filled? That is, the search sequence is unique (or at least orthogonal to the h_value)? Could you just scramble the bits and hash key -> hash table -> hash table? Is deletion - resize to small - a strong bottleneck? Can you store an object's search sequence, as it looks for "a home", and when one of its earlier slots vacantizes, promote it? From hniksic at xemacs.org Tue Mar 25 11:59:21 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Mar 2008 16:59:21 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <87myomeqw6.fsf@mulj.homelinux.net> Tzury Bar Yochay writes: > given two classes: > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = Foo.getid() > b = self.id > return '%d.%d' % (a,b) Try this: class Foo(object): def __init__(self): self.__id = 1 def getid(self): return self.__id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.__id = 2 def getid(self): a = Foo.getid(self) b = self.__id return '%d.%d' % (a,b) >>> FooSon().getid() '1.2' > While my intention is to get 1.2 I get 2.2 I would like to know what > would be the right way to yield the expected results Either use the above "private" fields, or emulate them yourself by renaming self.id to self.foo_id or self.foo_son_id, and exposing those in the class. Or you can have a class-specific dict in each instance, and so on. From michael.wieher at gmail.com Sat Mar 22 18:05:25 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sat, 22 Mar 2008 17:05:25 -0500 Subject: List question In-Reply-To: <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> Message-ID: If you can't laugh at your own stupidity, being a programmer will lead directly to insanity. =) 2008/3/22, Zentrader : > > > No one meant to laugh at you. Your naivete was not obvious. FWIW, a > > sense of humor is a valuable possession in most Python-related > > conversations. > > Perhaps someone can explain how telling something like this to the OP, > who thinks this statement will work > if 'one' and 'two' in f: > is funny and not mean. In the words of whoever it was in "Gone With > The Wind", frankly I don't give a damn (except to not mislead relative > newbies). But this has wasted enough of everyone's time. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zerty.david at gmail.com Mon Mar 31 13:50:27 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 31 Mar 2008 14:50:27 -0300 Subject: Python and Db Message-ID: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> Hi! I'm don't know almost nothing about bds, Can You suggest me an Simple but efficient Bd to work with python apps? Can You suggest me any tutorials? Thanx -------------- next part -------------- An HTML attachment was scrubbed... URL: From quentel.pierre at wanadoo.fr Sat Mar 8 13:05:55 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 8 Mar 2008 10:05:55 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> > >>> def convert(x): > > ? ? ? ? if '.' in x: > ? ? ? ? ? ? ? ? try: return float(x) > ? ? ? ? ? ? ? ? except ValueError: return x > ? ? ? ? else: > ? ? ? ? ? ? ? ? try: return int(x) > ? ? ? ? ? ? ? ? except: return x > > >>> convert('123') > 123 > >>> convert('123.99') > 123.98999999999999 > >>> convert('hello') > Hi, That's fine for people who write floats with a "." ; but others learn to enter them with "," For the same float, the French write the literal 123.456.789,99 when others write 123,456,789.99 ; for us, today is 8/3/2008 (or 08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8 Popular spreadsheets know how to "guess" literals ; if the guess is not correct users can usually specify the pattern to use. My question was just to know if something similar had already been developed in Python ; I understand that the answer is no Thanks, Pierre From sturlamolden at yahoo.no Sun Mar 30 13:44:14 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 30 Mar 2008 10:44:14 -0700 (PDT) Subject: ANN: pygame 1.8 released References: Message-ID: <80749045-84bb-4a51-b7df-0ae7cf294589@s19g2000prg.googlegroups.com> This is good news, particularly the NumPy support for surface and pixel arrays. From hv at tbz-pariv.de Fri Mar 28 10:28:03 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 28 Mar 2008 15:28:03 +0100 Subject: simple web-server In-Reply-To: References: Message-ID: <654djkF2dl38dU1@mid.individual.net> Pavol Murin schrieb: > hello python users, > > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). If you want to run shell scripts, you might want to search for a web server written in a shell script.... Running shell scripts which process CGI input are very insecure. It may be possible to write secure shell scripts, but I think it is not worth the trouble. Django contains a simple web server for testing. But it runs as a single process. So if one request needs long, all other requests wait. I don't think django is too heavy for a simple task. You can use CGIHTTPServer and the cgi module of the standard library, too. But it has drawbacks. One is, that CGIHTTPServer can't do a redirect. (HTTP code 302). I whish that there was a simple and small (not twisted) webserver written in Python which can be used in production. But I think there is none. Thomas BTW, use subprocess and not os.system() if you need to call other executables. > Longer story: > > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed). > > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? > > thank you, muro -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From carlwenrich at gmail.com Thu Mar 20 23:20:21 2008 From: carlwenrich at gmail.com (Carl) Date: Thu, 20 Mar 2008 20:20:21 -0700 (PDT) Subject: How do I change the font size for the default coordinates in matplotlib? Message-ID: I've searched the user manual (and this forum) but I don't see anything that helps. From grante at visi.com Fri Mar 21 10:16:08 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Mar 2008 14:16:08 -0000 Subject: Code folder with Emacs References: <13u5li6kspler51@corp.supernews.com> <64hdonF2boovnU1@mid.uni-berlin.de> Message-ID: <13u7gp8oq4kejc4@corp.supernews.com> On 2008-03-21, Diez B. Roggisch wrote: >> Has anybody figured out how to do code folding of Python source >> files in emacs? >> >> I tried "hide-show" minor mode, but it doesn't really work for >> Python code: the only think it knows how to hide/show are >> function bodies. It can't do normal things like hide/show a >> code block like it can for other languages. > > I just recently started hacking in emacs, to enhance the > python-mode and make pdb work with persisten breakpoints (by > that I mean BPs that survive one debug-session). > > Code-folding isn't currently on my agenda, but an interesting > idea. given that e.g. ecb already has structural analysis > buffers, there are python-aware code parsers (cedet?) Given the simplicity of python's indentation-defined block-delimiting, It's hard to understand how hide-show managed to come up with a "block" definition that works for function bodies but not for other identically delimited blocks. > So it shouldn't be too hard. The only interesting/important > thing would be to integrate it with ecb because I wouldn't > want several parse-runs at once. When I have some time, I'm going to take alook at hide-show's Python support, but my lisp skills are a bit rusty... -- Grant From misceverything at gmail.com Sun Mar 30 17:39:10 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Sun, 30 Mar 2008 14:39:10 -0700 (PDT) Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> <47eea713$0$27902$426a74cc@news.free.fr> Message-ID: That's not a problem - I'm only interested in Win2k+. Thanks for the caveat. On a similar note, is there a way (preferably using WMI) to get the full path to the executable that has a port open (the same thing that fport does, just implemented in Python)? From watine at cines.fr Thu Mar 13 10:44:26 2008 From: watine at cines.fr (Benjamin Watine) Date: Thu, 13 Mar 2008 15:44:26 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: <47D93DCA.8070506@cines.fr> Marko Rauhamaa a ?crit : > Benjamin Watine : > >> How can I do this ? I would like a function like that : >> >> theFunction ('cat -', stdin=myVar) >> >> Another related question : Is there's a limitation of var size ? I >> would have var up to 10 MB. > > import subprocess > myVar = '*' * 10000000 > cat = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE) > cat.stdin.write(myVar) > cat.stdin.close() > cat.wait() > > > Marko > Thank you Marko, it's exactly what I need. And if somebody need it : to get the stdout in a var (myNewVar), not in the shell : cat = subprocess.Popen('cat', shell = True, stdin = subprocess.PIPE, stdout=subprocess.PIPE) cat.stdin.write(myVar) cat.stdin.close() cat.wait() myNewVar = cat.stdout.read() Is it correct ? Ben From sjmachin at lexicon.net Thu Mar 13 17:57:25 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Mar 2008 14:57:25 -0700 (PDT) Subject: Dispatch("Excel.Application") failed References: Message-ID: <84040989-8de9-42fb-ba08-6f1ee10566e0@s19g2000prg.googlegroups.com> On Mar 13, 5:02 pm, lialie wrote: > Hi, > Maybe it 's quite simple, but I can't fix it. Do I make some mistakes in > my env setting? My excel version is 2003. > any suggestion? Thanks. > > Traceback (most recent call last): > File "testexcel.py", line 3, in ? > excel = Dispatch("Excel.Application") [snip] > pywintypes.com_error: (-2147221005, > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > None, None) Googling for 2147221005 gives some clues. That string of hex stuff appears where an error message is expected -- it's not utf8, and makes no sense when I attempt to decode it with cp1250 to cp1258 inclusive. If you start IDLE and type: import sys; sys.stdout.encoding what do you see? From perrygreenfield at gmail.com Tue Mar 18 12:55:10 2008 From: perrygreenfield at gmail.com (perrygreenfield at gmail.com) Date: Tue, 18 Mar 2008 09:55:10 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: Amen on the diamond keynotes and lightning talks. The lightning talks were a great disappointment. Sponsor talks (or any such talks pitched at selling or recruiting) should go in their own, clearly labeled group so those of us who don't care about them can avoid them. If there must diamond 'keynotes' put them at the end of a session or in a separate track so we can easily avoid them if we wish. But personally, I don't think keynotes should be for sale at all in any form. One problem I faced was that there were sessions that had few talks I was interested in and other that had several at the same time where I couldn't attend all that I was interested. It's likely that there is no good solution to this, but perhaps one could try a new scheme for scheduling talks by posting the talk list early and letting registrants select the top n talks they want to see and running some sort of scheduling optimizer that tries to satisfy most of these desires (I have no idea if anything like this exists anywhere). And if you do decide to change how you handle sponsorship don't be afraid to say publicly how things are going to be different next time. There could well be many who won't go next time (like me) unless they have some reasons to believe that things will be different. From gargonx at gmail.com Wed Mar 12 00:29:38 2008 From: gargonx at gmail.com (gargonx) Date: Tue, 11 Mar 2008 21:29:38 -0700 (PDT) Subject: Why no string return? Message-ID: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Say i have the two methods: def ReturnMethod(request, x): if request is True: return x else: print "No String for you...False!" def SendMethod(request): xstring = "Some text" ReturnMethod(request, xstring) SendMethod(True) Why does ReturnMethod not return the string x? I do believe it is returning with a NoneType. Any help would be greatly obliged Thanks, Josh From martin at v.loewis.de Sun Mar 23 16:20:20 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 23 Mar 2008 21:20:20 +0100 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] In-Reply-To: References: <47E4202C.5060400@v.loewis.de> Message-ID: <47e6bb84$0$1903$9b622d9e@news.freenet.de> Guilherme Polo wrote: > 2008/3/21, "Martin v. L?wis" : >>> I've been thinking of volunteering to "port" Tkinter to Python 3.0, I >> > hadn't noticed that there was any discussion of removing it. It would >> > be a shame IMHO. >> >> >> I don't think Tkinter will be removed. It works just fine in 3k. >> >> Of course, if you would port IDLE to Tk 8.5: that would be a useful >> contribution. > > I'm interested in doing this, but are you aware of bugs yet ? I know > just one that is specific to Tk 8.5, this one being the background > color of the editor. I just looked at it again, and it seems to work fine. Of course, contributions to IDLE are always welcome, but this specific issues seems to require no more intense attention. Regards, Martin From dullrich at sprynet.com Wed Mar 19 08:41:29 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 19 Mar 2008 07:41:29 -0500 Subject: Speaking Text Message-ID: Mac OS X has text-to-speech built into the interface. So there must be a way to access that from the command line as well - in fact the first thing I tried worked: os.system('say hello') says 'hello'. Is there something similar in Windows and/or Linux? (If it's there in Linux presumably it only works if there happens to be a speech engine available...) David C. Ullrich From steve at REMOVE-THIS-cybersource.com.au Sun Mar 16 00:56:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 16 Mar 2008 04:56:41 -0000 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <13tmo994bgqjr11@corp.supernews.com> <13to6j6pta8o008@corp.supernews.com> Message-ID: <13tpa4999krk6cd@corp.supernews.com> On Sat, 15 Mar 2008 11:50:17 -0700, Dennis Lee Bieber wrote: > Small integers are cached in Python, so they always have a fixed ID > (address). Small integers are cached in CPython, making it an implementation- dependent feature. I don't believe that caching is promised by the language definition, and while CPython has a special relationship to Python-the-language, I don't think an implementation that failed to cache small integers would be described as "not Python". -- Steven From pianomaestro at gmail.com Fri Mar 28 10:57:56 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 07:57:56 -0700 (PDT) Subject: How do I reconnect a disconnected socket? References: Message-ID: <20af9145-133e-4747-aa7f-ba238515653a@d62g2000hsf.googlegroups.com> Did you try just creating a new socket every time you do a connect ? On Mar 28, 10:01 am, Jason Kristoff wrote: > I'm trying to make something that once it is disconnected will > automatically try to reconnect. I'll add some more features in later so > it doesn't hammer the server but right now I just want to keep it simple > and get that part working. The problem is that when I use sock.close I > get an error message of > Bad File Descriptor > and if I either use shutdown or just go straight to reconnecting I get: > Transport endpoint is already connected > > This is what I've got right now: > > #! /usr/bin/env python > import socket, string > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > def doconn(): > sock.connect(("localhost", 1234)) > def dodiscon(): > sock.close() > doconn() > > doconn() > > while (1): > buffer = sock.recv(1024) > if not buffer: > dodiscon() From phil at riverbankcomputing.com Sun Mar 30 11:08:19 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sun, 30 Mar 2008 15:08:19 +0000 Subject: Using QSystemTrayIcon with PyQt In-Reply-To: References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: <200803301608.19697.phil@riverbankcomputing.com> On Sunday 30 March 2008, Alex Teiche wrote: > On Mar 30, 2:08 am, Phil Thompson wrote: > > On Sunday 30 March 2008, Alex Teiche wrote: > > > Hello, > > > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > implement the following thing into my python application: > > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > it, but I could not get this specific thing to work. Can someone give > > > me some hints as to get it working in Python? > > > > > > Thanks a ton, > > > > > > Alex > > > > Have you looked at PyQt's systray example? > > > > Phil > > No, where do I find the example? > > Thanks, > > Alex Unsurprisingly in the PyQt source package. Phil From gagsl-py2 at yahoo.com.ar Thu Mar 6 15:25:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 18:25:04 -0200 Subject: Py-Extension Irregularity References: Message-ID: En Thu, 06 Mar 2008 13:54:44 -0200, Michael Wieher escribi?: > Observe. > > Python Code Snippet: > ==================== > ... > 66 while i < (self.nPCodes): > 67 # print "%s:%s" % (self.nPCodes,i) > 68 (c,l,sn,f,fn,sz) = tabmodule.getQuestion(i,self.mx3Path) > 69 if _debug and sz>0: > 70 _newPtrLoc = tabmodule.getMx3Ptr() > 71 _diff = _newPtrLoc-_oldPtrLoc > 72 _oldPtrLoc = _newPtrLoc > 73 if _diff>16: > 74 print _diff > .... > > C++ Code Snippet: > --------------------------- > 189 static PyObject* > 190 tabmodule_getMx3Ptr(PyObject * self, PyObject * args) { > 191 int a; > 192 a=mx3File.tellg(); > 193 return Py_BuildValue("i",a); > 194 } > ... > > 189 PyObject * > 190 tabmodule_getQuestion(PyObject * self, PyObject * args) { > .... > 208 mx3File.read((char*)&m_mdx,16); > .... > 237 //if(m_mdx.size==0) > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > 239 //return Py_BuildValue("iiiiii",m_mdx.compression, > m_mdx.location, > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > } > > Output== > michael at majw-m65:~/MRI/tabModule$ ./tabModule.py > michael at majw-m65:~/MRI/tabModule$ > > None. (ie: the _diff is always 16 or less, which is what is SHOULD be, > in > fact, it is always 16.) Why do you assert that? With those commented out lines, the last item returned by getQuestion (sz) is always 0; nothing is printed because sz==0 and the python code never enters the outer if. From that evidence I can't say anything about _diff. > Observe!!!! > > 237 if(m_mdx.size==0) > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > 239 return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > > By uncommenting line 237 and 239, we see: > ... > 64 > 80 > 32 > 32 > 32 > 48 > 128 > 160 > 32 > 32 > 64 > .... > > Most of the numbers are still 16, but _diff is often larger than 16, by > some > multiple. I'd print m_mdx values in the C++ source. > How in Buddah's name is returning a Py_BuildValue() affecting a file > pointer > that isn't being used at all in the function???? I don't think this is the cause... -- Gabriel Genellina From exarkun at divmod.com Mon Mar 3 08:11:43 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 3 Mar 2008 08:11:43 -0500 Subject: is there enough information? In-Reply-To: <13s9u7dg24es73a@corp.supernews.com> Message-ID: <20080303131143.6859.627120868.divmod.quotient.15093@ohm> On Tue, 26 Feb 2008 21:45:24 -0800, Dennis Lee Bieber wrote: > [snip] > > Threads, in Python, are good for parallel processing of items that >tend to be I/O bound -- that is, stuff that blocks on lots of I/O calls >allowing other threads to execute until they block too. Due to the GIL >in the common Python implementation, threading is not useful for >number-crunching (CPU bound) processing. > > Now, there is a very vocal group that recommend Twisted style >asynchronous call-backs for everything in the world... But I think that >group tends to forget that Windows I/O is incompatible with the >low-level select() call often used to do parallel I/O -- leaving it only >useful for the network socket I/O, but not local file I/O processing. I'm not sure, but you seem to be implying that the only way to use Windows' asynchronous I/O APIs is with threads. Actually, it is possible (and Twisted allows you) to use these as well without writing a threaded application. Perhaps you think it would be better to use them with threads, but that's certainly not the _only_ way to use them as you implied. Jean-Paul From fn681 at ncf.ca Sat Mar 1 16:58:49 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sat, 01 Mar 2008 16:58:49 -0500 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c990b9$0$899$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> <47c990b9$0$899$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI (MVP) wrote: > Re! > > An exemple. With this script: > a=123 > b=456 > d=a+b+c > (note than 'c' is not defined). > > When I run, inside Pyscripter, the error-dialog is showed, and, one > second after, PyScripter is closed. > This problem is present since Python 2.5.2. > > I search, for know if it's a problem only on my computer, or a more > general problem. > > Thanks by advance for your(s) answer(s). > > @-salutations I ran your script and an exception.NameError is reported. I say OK to the error and repeat the run. PyScripter is not closed. This is with xp and Python 2.5.2 Colin W. From onetwofour at gmail.com Sat Mar 1 07:28:22 2008 From: onetwofour at gmail.com (theneb) Date: Sat, 1 Mar 2008 04:28:22 -0800 (PST) Subject: Getting a free TCP port & blocking it References: <1dff2e2c-892d-42fa-9e65-5c7c12b75ec3@s13g2000prd.googlegroups.com> <280is3le2op8khmgr7nj5a1mnkjd7p0n50@4ax.com> Message-ID: On Feb 29, 11:11 pm, Tim Roberts wrote: > theneb wrote: > >Hi all, > >I'm attempting to block a TCP port from any other application from > >using it until I free it from python, this is so that: > >1). Generate a random free user-space port > >2). Generate the script for the external program with the port > >3). Free the port before external program execution. > > What's the point? Why can't the actual user of the port create the port, > and then notify the other side of the port number? The system the app will run on will be creating three instances of the external application, the python app has to keep track of which port the external app is running on. > > And why don't you just specify a port number of 0 and let the system assign > you a free port number? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From sambo at voidstar.com Wed Mar 12 11:49:55 2008 From: sambo at voidstar.com (Sam) Date: Wed, 12 Mar 2008 11:49:55 -0400 Subject: access to base class __init__ References: <13suutrsb4bab8b@corp.supernews.com> <13t1il47eoamrb3@corp.supernews.com> Message-ID: <0QSBj.29323$yk5.10906@newsfe18.lga> Dennis Lee Bieber wrote: > On Thu, 06 Mar 2008 22:35:18 -0500, Sam declaimed > the following in comp.lang.python: > ['line 1', 'line 2', 'embedded', 'line', 'something'] >>>> sample="""line 1\rline 2\rembedded\nline\rsomething\r""" >>>> sample.splitlines() > ['line 1', 'line 2', 'embedded', 'line', 'something'] >>>> > You are right partly right. That code only parsed the HTML request header which I believe had one specific line termination as prescribed by RFC ( but I will have too look it up later since I don't remember whichfor sure. ) Once again got confused on them buggers, "\n" is LINUX ( the least logical). > splitlines() handles \r\n, \n, and \r as line endings -- and no stray > empty ending! (however, \n\r /does/ create an empty element) > !!~! SPLITLINES() BEAUTY, Thanks for reminding me. I mush have a faulty memory cell or entire row. From Lie.1296 at gmail.com Sat Mar 8 22:51:24 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 19:51:24 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? Message-ID: I'm asking about people in c.l.py's opinion about a _probably_ very Pythonic way of doing something if such features is implemented. It is to be known that I'm not a Python expert and actually relatively new to Python programming, so probably I'm just not thinking pythonic enough yet or this feature might already exist somewhere in a different name. Anyway, I'm just asking for opinions, tell me problems I haven't foreseen, or whether such things would be hard to implement, or whether you think the idea is great or plain bad (and why). Soft Exception What is "Soft Exception"? Soft Exception is an exception that if is unhandled, pass silently as if nothing happened. For example, if a variable turns into NoneType, it'll raise Soft Exception that it have become NoneException, programmers that wants to handle it can handle it with a try...except block while programmers that doesn't care about it (or know it won't be a problem to his code) can just leave the code as it is. Soft Exception differs from Hard Exceptions (the regular Exception) in a way that Hard Exception must be handled at all cost or the program will be terminated while Soft Exception allow programmers not to handle it if they don't want to. Soft Exception is similar to an event-based system, although Soft Exception can only be handled by codes above it while Event-based system can be handled by anyone aware of the handle pool. The Soft Exception can also be thought as a Warning to the codes above it that it has done something that the codes above might want to know. Implementation: Simple implementation might be done by catching all exceptions at the highest level, then filtering which exceptions would be stopped (Soft Exception) and which exceptions will be reraised and terminate the program (Hard Exception). This is simple and can be easily implemented but is inefficient as that means all soft exceptions must bubble through its way to the top to find out if it is Soft or Hard. A more through implementation would start from the raiser inspecting the execution stack and finding whether there are any try block above it, if no try block exist it pass silently and if one exist it will check whether it have a matching except clause. This also circumvents a problem that simple implementation have, as described below. Syntax change is probably unneeded and a Soft Exception class may be created by inheriting from BaseSoftException class. Problems: - If the raising statement is a complex statement (like function call) instead of just a simple statement (like assignment from an expression) the exception might catch a similar soft exceptions from deep _inside_ the function call and handle it as if it happened in the code it's protecting. This problem can be solved by raising Soft Exception only once except if explicitly reraised (perhaps through except SoftException: raise). This can be done by modifying a flag that is turned off (Falsed) if the Soft Exception is raised and turned on again (Trued) if the Soft Exception is reraised. Normal Exceptions (Hard Exceptions) would have this flag turned off (Falsed) if it is handled and turned on (Trued) again if it is reraised. - To be half useful, soft exceptions have to be raised everywhere here and there, not just here and here only. This might require a massive change in current codes, or at least in Python's official libraries. - Irresponsible programmers. Sometimes lazy programmers might decides to be lazy and make all exceptions soft so he doesn't have to handle it. Ideology Base: - EAAP: Easier to apologize than to ask permission. Others: - Sometimes it might be useful to convert a Soft Exception into Hard Exception or vice versa. From sjmachin at lexicon.net Mon Mar 10 17:37:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 14:37:18 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: On Mar 10, 11:14 pm, Duncan Booth wrote: > "Neil Crighton" wrote: > > I'm using the zipfile library to read a zip file in Windows, and it > > seems to be adding too many newlines to extracted files. I've found > > that for extracted text-encoded files, removing all instances of '\r' > > in the extracted file seems to fix the problem, but I can't find an > > easy solution for binary files. > > > The code I'm using is something like: > > > from zipfile import Zipfile > > z = Zipfile(open('zippedfile.zip')) > > extractedfile = z.read('filename_in_zippedfile') > > > I'm using Python version 2.5. Has anyone else had this problem > > before, or know how to fix it? > > > Thanks, > > Zip files aren't text. Try opening the zipfile file in binary mode: > > open('zippedfile.zip', 'rb') Good pickup, but that indicates that the OP may have *TWO* problems, the first of which is not posting the code that was actually executed. If the OP actually executed the code that he posted, it is highly likely to have died in a hole long before it got to the z.read() stage, e.g. >>> import zipfile >>> z = zipfile.ZipFile(open('foo.zip')) Traceback (most recent call last): File "", line 1, in File "C:\python25\lib\zipfile.py", line 346, in __init__ self._GetContents() File "C:\python25\lib\zipfile.py", line 366, in _GetContents self._RealGetContents() File "C:\python25\lib\zipfile.py", line 404, in _RealGetContents centdir = struct.unpack(structCentralDir, centdir) File "C:\python25\lib\struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 46 >>> z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK >>> z = zipfile.ZipFile('foo.zip', 'r') # OK If it somehow made it through the open stage, it surely would have blown up at the read stage, when trying to decompress a contained file. Cheers, John From jeff at jmcneil.net Thu Mar 6 22:41:20 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 6 Mar 2008 22:41:20 -0500 Subject: Looking for very light weight template library (not framework) In-Reply-To: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> References: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> Message-ID: <82d28c40803061941y6ae70595wa20b2127bac32822@mail.gmail.com> Cheetah (http://www.cheetahtemplate.org/) and Mako (http://www.makotemplates.org/) come to mind. Isn't there some long running joke about new Python programmers creating their own template language or something, too? =) I know you said you don't want a web framework, but I've always been a fan of Django templates in that they don't really allow you to do too much inside the template itself. That seems to help keep a lot of ex-PHP/JSP/ASP programmers I know honest. On 3/6/08, Erik Max Francis wrote: > Malcolm Greene wrote: > > > New to Python and looking for a template library that allows Python > > expressions embedded in strings to be evaluated in place. In other words > > something more powerful than the basic "%(variable)s" or "$variable" > > (Template) capabilities. > > > > I know that some of the web frameworks support this type of template > > capability but I don't need a web framework, just a library that > > supports embedded expression evaluation. > > ... > > Any suggestions appreciated. > > EmPy may work: > > http://www.alcyone.com/software/empy/ > > Your template would look something like: > > > myOutput = """\ > > The total cost is @invoice.total. > > This order will be shipped to @invoice.contact at the following > address: > > @invoice.address > > > This order was generated at @time.ctime() > """ > > This could be instrumented with something as simple as: > > >>> import em, time > > >>> myOutput = """\ > ... > ... The total cost is @invoice.total. > ... > ... This order will be shipped to @invoice.contact at the following > ... address: > ... > ... @invoice.address > ... > > ... This order was generated at @time.ctime() > ... """ > >>> > >>> class Invoice: pass > ... > >>> invoice = Invoice() > >>> invoice.total = "$123.45" > >>> invoice.contact = "Jack McCoy" > >>> invoice.address = "1 Police Plaza\nNew York City, NY" > >>> print em.expand(myOutput, globals()) > > The total cost is $123.45. > > This order will be shipped to Jack McCoy at the following > address: > > 1 Police Plaza > New York City, NY > > This order was generated at Thu Mar 6 18:41:58 2008 > > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > There's a reason why we / Keep chasing morning > -- Sandra St. Victor > > -- > http://mail.python.org/mailman/listinfo/python-list > From dummy at dummy.nl Tue Mar 25 00:29:20 2008 From: dummy at dummy.nl (Cecil Westerhof) Date: Tue, 25 Mar 2008 05:29:20 +0100 Subject: Non-buffering stdout Message-ID: <47e87fa0$0$14348$e4fe514c@news.xs4all.nl> With python -u script, you can make stdout unbuffered. Is there a way to do it in the script itself? I use just a script with a shebang (#!/usr/bin/env python) and then it is not possible to use -u. From rschroev_nospam_ml at fastmail.fm Sat Mar 29 05:18:15 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 29 Mar 2008 10:18:15 +0100 Subject: Help me on function definition In-Reply-To: References: Message-ID: aeneng schreef: > Hello everyone, > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this >>>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 You forgot the : after def cross(u, v) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From xpahos at gmail.com Sun Mar 30 18:42:23 2008 From: xpahos at gmail.com (phasma) Date: Sun, 30 Mar 2008 15:42:23 -0700 (PDT) Subject: Export data to OpenDocument Text Message-ID: <00eaab19-9076-4278-9cb6-17a2cdef31ff@m3g2000hsc.googlegroups.com> Hi! I'm trying to save data from sqlite to OpenDocument Text. Code: localtime = time.localtime(time.time()) try: odt_file = zipfile.ZipFile(file_name, "w") except: print("?????????? ??????? ???? ??? ??????") return False buff_file = zipfile.ZipInfo("mimetype", localtime) odt_file.writestr(buff_file, "application/ vnd.oasis.opendocument.text") buff_file = zipfile.ZipInfo("content.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(content_xml)) buff_file = zipfile.ZipInfo("styles.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(style_xml)) buff_file = zipfile.ZipInfo("meta.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(meta_xml)) buff_file = zipfile.ZipInfo("META-INF/manifest.xml", localtime) buff_file.external_attr = 2179792896 buff_file.flag_bits = 8 buff_file.compress_type = zipfile.ZIP_DEFLATED odt_file.writestr(buff_file, "\n".join(manifest_xml)) odt_file.close() OpenOffice can't open this file, in what a problem ? sample file: http://omploader.org/vZjlo/test.odt From tjreedy at udel.edu Sat Mar 8 16:15:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2008 16:15:31 -0500 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: "egbert" wrote in message news:20080308152034.GA12009 at hccnet.nl... | However the loop-else really works more like this: | . try to do the loop; | . if it starts but is interrupted by a break, | . then do something else as well. This is NOT how loop-else works for Python. If you want to do something special on breaks, put the break-only code before the break. while loop_condition: if break_condition: break | So they are completely different beasts, and if you try to use | or explain the one according to the rules of the other one, | you put a serious strain on your synapses. I did not mean to broke your brain. | The explanation that the if-else and the loop-else | follow the same pattern, runs more or less like this: | . all conditions to run the loop to its completion were met, | . which means that the loop-condition is not met (any more), | . which means that we must do something else. | For me that is orwellian logic: success is failure. I gave a clear and coherent explanation of how while derives from if, and correspondingly, how while-else derives from if-else, to help those who want to read and write Python code. Building on the pseudo-snippet above, one can write while loop_condition: if break_condition: break else: Python allows one to have both break-only and completion-only sections together in one compound statement and *without* having to fiddle with a special flag variable. I am sorry if you cannot appreciate such elegance and can only spit on it as 'orwellian'. If the sense of else were reversed, one would have to write the clumbsier complete = True # though false at this point while loop_condition: if break_condition: complete = False break else: if complete: Terry Jan Reedy From pradipbhosale at gmail.com Mon Mar 31 09:28:03 2008 From: pradipbhosale at gmail.com (Pradip) Date: Mon, 31 Mar 2008 06:28:03 -0700 (PDT) Subject: Multi Threading Problem with Python + Django + PostgreSQL. Message-ID: <553b16a7-a89e-4892-b92b-c0f88e00e096@e23g2000prf.googlegroups.com> Hello every body. I am new to this forum and also in Python. Read many things about multi threading in python. But still having problem. I am using Django Framework with Python having PostgreSQL as backend database with Linux OS. My applications are long running. I am using threading. The problem I am facing is that the connections that are being created for database(postgres) update are not getting closed even though my threads had returned and updated database successfully. It is not like that the connections are not being reused. They r being reused but after sometime new one is created. Like this it creates too many connections and hence exceeding MAX_CONNECTION limit of postgres conf. ** I am using psycopg2 as adaptor for python to postgres connection. which itself handles the connections(open/close) Now the problem is with Django / Python / psycopg2 or any thing else?? HELP ME OUT!!!!! From castironpi at gmail.com Sun Mar 9 21:05:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 18:05:48 -0700 (PDT) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> Message-ID: <980fee99-808b-47f2-8782-faac7c6a7586@34g2000hsz.googlegroups.com> > > ?> and I want to be able to stop [functions] if they run too long. > > > That's tricky [due to a synthetic limitation]. It would suck if you couldn't hold the GIL for as long as you need to. But how much is it used? Wrote the docs: > when two threads simultaneously increment the reference count of the same object Well, the example sucked. Just synchronize ref count manipulation. Every OS has locking primitives, and a library exists to deny requests to block that lock dead. How integral is the GIL to Python? > The Python interpreter is not fully thread safe -Make- it so. From mensanator at aol.com Mon Mar 17 21:20:14 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 17 Mar 2008 18:20:14 -0700 (PDT) Subject: First Program Bug (Newbie) References: Message-ID: On Mar 17, 7:03?pm, Benjamin Serrato wrote: > I Found It!! The following was a post asking for help finding a bug. I > thought I needed help with my syntax, but just before sending I found > the bug on line 13. Line 13 should read: "base = 2". I would still > appreciate any comments on my program. Maybe there is a better way to do > it that I didn't think about. I know it's not that interesting but it's > my first one. > > [post] > I'm almost halfway through an online tutorial I found on the python.org > site and decided to stop and write a program for myself. I got it in my > head to write a program to print all the primes; the idea came from > another tutorial. The program prints some non-prime numbers. In a > comparison to lists of primes the program prints eight non-primes for > numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. > Here is the program. > > base = 2 > candidate = 3 > > while True: > ? ? ? ? while candidate % base != 0: > ? ? ? ? ? ? ? ? base = base + 1 > ? ? ? ? ? ? ? ? if base > (candidate / 2): > ? ? ? ? ? ? ? ? ? ? ? ? print candidate > ? ? ? ? ? ? ? ? ? ? ? ? candidate = candidate + 1 > ? ? ? ? ? ? ? ? ? ? ? ? base = 2 > ? ? ? ? else: > ? ? ? ? ? ? ? ? candidate = candidate + 1 > > The following is a rundown of the program. > > candidate: A possible prime number. > base: Start point for divisibility testing. > outer while loop: Causes the program to loop. > inner while loop: Obviously, checks if 'candidate' mod 'base' equals > zero. If not base is incremented by one then 'if loop'. > if loop: After base has been incremented this checks whether all the > possible divisors have been used up. If they have then 'candidate' must > be prime. So, candidate is printed, a new candidate is chosen and the > base is reset. > else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is > not prime and a new candidate is chosen. > > I realize yall probably didn't need all that. > > At first I tried to use 'return' on the 'else' block to cause the > program to loop, but I don't understand 'return' yet and that didn't > work. So, I put the rest into another while loop and was really happy to > find it worked but the program prints some non-prime numbers. > > Thanks, Benjamin Serrato > > P.S. What is the chance I'll get spam for using my real email address? I > currently don't get any so... > [/post] Several items. First, you don't need to check base larger than sqrt(candidate). Second, see comments following dc. Third, you need to add base = 2 to end of program, otherwise next candidate starts base where previous candidate left off. Fourth, use +=1 to increment. Finally, throw this away and use gmpy. :-) import gmpy # for Quality Assurance base = 2 candidate = 3 p = 0 # prime count while p<100: # limit the loop to 100 primes while candidate % base != 0: base += 1 #if base > (candidate / 2): if base > (gmpy.sqrt(candidate)): # only need to test to sqrt(candidate) dc = divmod(candidate,2) # remainder==0 gives false primes if dc[1]==1: # # the gmpy functions are for QA, verifies that what you call a prime # really is one and the next_prime makes sure you don't skip any # these can be removed once working # print candidate,gmpy.is_prime(candidate)>0,gmpy.next_prime(candidate) p += 1 candidate += 1 base = 2 else: candidate += 1 # false prime, reset base = 2 else: candidate += 1 base = 2 # failure to reset causes false primes ## 3 True 5 ## 5 True 7 ## 7 True 11 ## 11 True 13 ## 13 True 17 ## 17 True 19 ## 19 True 23 ## 23 True 29 ## 29 True 31 ## 31 True 37 ## 37 True 41 ## 41 True 43 ## 43 True 47 ## 47 True 53 ## 53 True 59 ## 59 True 61 ## 61 True 67 ## 67 True 71 ## 71 True 73 ## 73 True 79 ## 79 True 83 ## 83 True 89 ## 89 True 97 ## 97 True 101 ## 101 True 103 ## 103 True 107 ## 107 True 109 ## 109 True 113 ## 113 True 127 ## 127 True 131 ## 131 True 137 ## 137 True 139 ## 139 True 149 ## 149 True 151 ## 151 True 157 ## 157 True 163 ## 163 True 167 ## 167 True 173 ## 173 True 179 ## 179 True 181 ## 181 True 191 ## 191 True 193 ## 193 True 197 ## 197 True 199 ## 199 True 211 ## 211 True 223 ## 223 True 227 ## 227 True 229 ## 229 True 233 ## 233 True 239 ## 239 True 241 ## 241 True 251 ## 251 True 257 ## 257 True 263 ## 263 True 269 ## 269 True 271 ## 271 True 277 ## 277 True 281 ## 281 True 283 ## 283 True 293 ## 293 True 307 ## 307 True 311 ## 311 True 313 ## 313 True 317 ## 317 True 331 ## 331 True 337 ## 337 True 347 ## 347 True 349 ## 349 True 353 ## 353 True 359 ## 359 True 367 ## 367 True 373 ## 373 True 379 ## 379 True 383 ## 383 True 389 ## 389 True 397 ## 397 True 401 ## 401 True 409 ## 409 True 419 ## 419 True 421 ## 421 True 431 ## 431 True 433 ## 433 True 439 ## 439 True 443 ## 443 True 449 ## 449 True 457 ## 457 True 461 ## 461 True 463 ## 463 True 467 ## 467 True 479 ## 479 True 487 ## 487 True 491 ## 491 True 499 ## 499 True 503 ## 503 True 509 ## 509 True 521 ## 521 True 523 ## 523 True 541 ## 541 True 547 ## 547 True 557 From mensanator at aol.com Tue Mar 25 19:52:57 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 25 Mar 2008 16:52:57 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: On Mar 25, 6:30?pm, kellygreer1 wrote: > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > Is there a page on this in the Python in a Nutshell or the Python > Cookbook? > Did I miss something? I don't know, the set() soution worked for me. >>> lstone = [1,2,3,3,4,5,5,6] >>> setone = set(lstone) >>> lsttwo = list(setone) >>> lstone [1, 2, 3, 3, 4, 5, 5, 6] >>> setone set([1, 2, 3, 4, 5, 6]) >>> lsttwo [1, 2, 3, 4, 5, 6] > > Kelly Greer > kellygre... at nospam.com > change nospam to yahoo From willsteve2003 at yahoo.ca Mon Mar 3 10:38:10 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 3 Mar 2008 07:38:10 -0800 (PST) Subject: Book Recomendations References: Message-ID: <25b90cd1-a672-4615-86dd-2afa1edb756b@d21g2000prf.googlegroups.com> The "Python Forum" has a good set of selections in their "General Forum" section: http://python-forum.org/pythonforum/viewtopic.php?f=1&t=12&st=0&sk=t&sd=a&sid=9b04b79b60f9afb56e4237856910d354&start=20 From simon at brunningonline.net Thu Mar 20 12:21:55 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 20 Mar 2008 16:21:55 +0000 Subject: if __name__ == '__main__': In-Reply-To: References: Message-ID: <8c7f10c60803200921p3c4a989ajf7797688072468e@mail.gmail.com> On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde wrote: > Hi, > I am new to the python and not getting meaning of following line, > > if __name__ == '__main__': > main() -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 20:32:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 00:32:51 -0000 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <7x63vfn3ix.fsf@ruckus.brouhaha.com> <8e4e1ae0-9a34-41c2-b253-7ea8846f6de5@i7g2000prf.googlegroups.com> <3880a377-30fe-49b3-a578-8d6203d526bb@s8g2000prg.googlegroups.com> Message-ID: <13udtljicjr9ied@corp.supernews.com> On Sun, 23 Mar 2008 15:55:43 -0700, John Machin wrote: > On Mar 24, 12:19 am, Dustan wrote: >> On Mar 21, 3:57 pm, Paul Rubin wrote: >> >> > From at home writes: >> > > if 'one' and 'two' in f: >> > > alist.append(f) >> >> > Use: >> > if 'one' in f and 'two' in f: ... >> >> Personally, I would put parentheses around to be clearer: >> >> if ('one' in f) and ('two' in f): ... >> >> I'm not saying to put parentheses around everything, but in the more >> ambiguous cases, it certainly helps. > > Please help me understand why this is a "more ambiguous" case. Some people don't remember, and have no interest in forcing the people who read their code to memorize, the relative precedence of 'in' and 'and', and so don't expect folks to understand whether 'one' in f and 'two' in f means ('one' in f) and ('two' in f) or ('one' in (f and 'two')) in f or something else. This especially holds for people who have used languages where the precedences are less sensible than they are in Python. By memory, standard Pascal uses the second interpretation if you don't use parentheses, which is stupid, but there you go. > To me, alternative interpretations have extremely low scores for > utility and likelihood: Outside of the interactive interpreter, I prefer to know what my code does before I write it, rather than guess that it's unlikely to be wrong. (Or at least *think* I know what it does, which is not always the same thing as knowing what it does.) -- Steven From martin at v.loewis.de Sun Mar 2 16:05:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Mar 2008 22:05:14 +0100 Subject: [ANN] Python 2.3.7 and 2.4.5, release candidate 1 Message-ID: <47CB168A.103@v.loewis.de> On behalf of the Python development team and the Python community, I'm happy to announce the release candidates of Python 2.4.5 and 2.4.5. Both releases include only security fixes. Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.3 or 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interprerter may have crashed before). Assuming no major problems crop up, a final release of Python 2.4.4 will follow in about a week's time. For more information on Python 2.3.7 and 2.4.5, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3.7 http://www.python.org/2.4.5 Highlights of the previous major Python releases are available from the Python 2.4 page, at http://www.python.org/2.3/highlights.html http://www.python.org/2.4/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From grflanagan at gmail.com Tue Mar 4 01:51:47 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Mon, 3 Mar 2008 22:51:47 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: <75d14972-4dba-4311-9c06-63b3a2859f96@n75g2000hsh.googlegroups.com> On Mar 4, 6:31 am, castiro... at gmail.com wrote: > On Mar 3, 10:01 pm, Benjamin wrote: > > > > > On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > > > > What are metaclasses? > > > Depends on whether you want to be confused or not. If you do, look at > > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/. > > > Basically, the metaclass of a (new-style) class is responsible for > > creating the class. This means when Python sees > > class Foo(object): > > __metaclass__ = FooMeta > > class FooMeta(type): > > def __new__(cls, name, bases, dct): > > #do something cool to the class > > pass > > It asks FooMeta to create the class Foo. Metaclasses always extend > > type because type is the default metaclass. > > But you can stack class decorations, but not class metas. > > @somethingcool1 > @somethingcool2 > class Foo: > pass > > * class Foo: > __metaclass__= MetaCool1, MetaCool > > * denotes malformed ----------------------- class Meta1(type): def foo1(cls): print 'hello' class Meta2(type): def foo2(cls): print 'castiron' class Meta(Meta1, Meta2): pass class Base(object): __metaclass__ = Meta Base.foo1() Base.foo2() ----------------------- Gerard From simon at brunningonline.net Wed Mar 19 07:51:45 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 Mar 2008 11:51:45 +0000 Subject: PODCasts In-Reply-To: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> References: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> Message-ID: <8c7f10c60803190451y30d0ca20g6a57356a47676d43@mail.gmail.com> On Wed, Mar 19, 2008 at 9:06 AM, Mike D <42flicks at gmail.com> wrote: > I really should say net cast as I think it's a better term ;) Since I'm working at The Guardian, I'm bound to stand up for the term 'podcast'. ;-) Besides, it's very established now - too late to fight it. > Does anyone have any recommended net casts on Python, or programming in > general? > > Whats everyone listening to? Python411: This Week in Django: Plus a bunch of non-Python related stuff. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From jameswhetstone at comcast.net Sat Mar 22 19:42:17 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Sat, 22 Mar 2008 16:42:17 -0700 Subject: How to use boost.python to wrap a class with a pure virtual function that has a 'void *' argument References: Message-ID: I found a solution to this problem: void handleMessage(void *message) { int size = getSize(message); PyObject *obj = PyBuffer_FromMemory( message, size ) ; boost::python::handle<> h(obj); PyGILState_STATE gstate = PyGILState_Ensure(); try { call(this->get_override("handleMessage").ptr(), h); } catch (const error_already_set) { // Catch and ignore exception that is thrown if Python // onMessage raised an exception. Print it to sys.stderr, // since there is nothing we can do about it here. PyErr_Print(); } PyGILState_Release(gstate); } "James Whetstone" wrote in message news:ubudndoRENZA-3janZ2dnUVZ_u-unZ2d at comcast.com... > As the subject implies, I'm having trouble wrapping a C++ class that looks > like this: > > struct A > { > virtual void handleMessage(void *message)=0; > }; > > > To wrap this class, I've written the following code: > > struct AWrapper : A, wrapper > { > void handleMessage(void *message) > { > this->get_override("handleMessage")(message); > } > }; > > class_("A") > .def("handleMessage", pure_virtual(&A::handleMessage)) > ; > > > My python test code looks like this: > > import APackage > > class aclass(APackage.A): > def handleMessage(msg) : print msg > > > But this code crashes when the handleMessage function is called in python > (I think) because 'void *' cannot be marshalled. Is there some way around > this? Also, since the void* object is intended to be "zero copy", I > should probably convert the void * to a PyObject first and re-write my > handleMessage to look like this: > > void handleMessage(void *message) > { > int size = getMessageSize(message); > > PyObject *obj = PyBuffer_FromReadWriteMemory(message, size); > > this->get_override("handleMessage")(obj); > } > > Has anyone done this type of thing? I'm writing this code using MS Visual > Studio 8 and if anyone can help, it would *very* appreciated. > > Thanks! > James > > > > From fredrik at pythonware.com Sun Mar 30 12:35:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Mar 2008 18:35:37 +0200 Subject: regarding xml elements In-Reply-To: <66657.48471.qm@web8713.mail.in.yahoo.com> References: <66657.48471.qm@web8713.mail.in.yahoo.com> Message-ID: Raj kumar wrote: > document.createElement("abc") > and i appeneded it by using append() method. > But how i can reflect this change to my xml file? write it out again: http://python.org/doc/current/lib/dom-objects.html From alitosis at gmail.com Thu Mar 13 23:41:12 2008 From: alitosis at gmail.com (alitosis at gmail.com) Date: Thu, 13 Mar 2008 20:41:12 -0700 (PDT) Subject: Problem with exec References: Message-ID: On Mar 14, 9:47 am, Justus Schwabedal wrote: [snipped] > However when I do this: > > bash-3.2$ cat execBug2.py > #! /usr/bin/python > header=""" > from scipy import randn > def f(): > return randn() > """ > def g(): > exec header > return f() > print "g() =",g() > bash-3.2$ ./execBug2.py > g() = > Traceback (most recent call last): > File "./execBug2.py", line 10, in > print "g() =",g() > File "./execBug2.py", line 9, in g > return f() > File "", line 4, in f > NameError: global name 'randn' is not defined > bash-3.2$ ??? > > I get this global name error. I can fix it with adding some line like > "global randn" but I don't want to do this. I want to do exactly what I wrote: Import the function scipy.randn in the local namespace of the > > function "g" so that "return f()" makes sense. Can anybody help me out? > Yours Justus Maybe using an explicit namespace is good enough for your needs: #! /usr/bin/python header=""" from scipy import randn def f(): return randn() """ def g(): n = {} exec header in n return n['f']() print "g() =",g() (i don't understand the issues, but I can cut-and-paste with the best of them) From http Sun Mar 9 00:32:04 2008 From: http (Paul Rubin) Date: 08 Mar 2008 21:32:04 -0800 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6i47r3uoo6b4@corp.supernews.com> Message-ID: <7x3ar0wjhn.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Unfortunately that doesn't work reliably. > > >>> a, b = 9007199254741000.0, -3.0 > >>> a/b > -3002399751580333.5 > >>> (a+b-1)//b # should be -3002399751580333 > -3002399751580332.0 I should have mentioned (a+b-1)//b expects a and b to be positive integers. From rbonvall at gmail.com Fri Mar 7 17:11:13 2008 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Fri, 7 Mar 2008 14:11:13 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> Message-ID: <3fd35f79-f0b0-4d6d-8430-eab452118b37@m34g2000hsc.googlegroups.com> On Mar 7, 6:16 pm, Steven D'Aprano wrote: > I believe it is one of those things that everybody (for some value of > "everybody") does because that's what they were taught to do Actually I was never taught to, and I never learnt about it anywhere. I started to do it spontaneously in order to tell apart end-of-sentence periods from abbreviation periods. Anyway, I don't think it's something people should be forced to do. -- Roberto Bonvallet From python.list at tim.thechases.com Sun Mar 9 20:52:50 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 Mar 2008 19:52:50 -0500 Subject: any chance regular expressions are cached? In-Reply-To: References: Message-ID: <47D48662.4090002@tim.thechases.com> > s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save > me the trouble of having to declare some global re's if I don't > want to have them recompiled on each function invocation? >>> import this ... Explicit is better than implicit ... Sounds like what you want is to use the compile() call to compile once, and then use the resulting objects: re1 = re.compile(r'\n') re2 = re.compile(r'^') ... s = re1.sub('\n' + spaces, s) s = re2.sub(spaces, s) ... The compile() should be done once (outside loops, possibly at a module level, as, in a way, they're constants) and then you can use the resulting object without the overhead of compiling. -tkc From castironpi at gmail.com Sat Mar 15 03:21:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 00:21:42 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <13tmo994bgqjr11@corp.supernews.com> Message-ID: On Mar 15, 12:39?am, Dennis Lee Bieber wrote: > On 14 Mar 2008 10:38:52 GMT, Antoon Pardon > declaimed the following in comp.lang.python: > > > In that case I find it very strange that when this question comes > > up, I see so few attempts to explain how the assignment acctually > > works. > > ? ? ? ? I'll probably get burned for this... but as far as I'm concerned, > assignment works very simply... At the very bottom of the name > resolution, assignment works by changing the left-hand-side "reference" > from any prior object for whatever object represents the result of the > right-hand-side. > > ? ? ? ? A bare LHS name is rebound in total. > ? ? ? ? ? ? ? ? lhs_name = rhs_expresssion > > ? ? ? ? A qualified LHS name (a name followed by a ".subname", or a > "[index]", or a "[keyvalue]") rebinds the specified subcomponent of > "name" -- that is, "name" remains bound to some object, and the > ".subname" (or "[index]" or "[keyvalue]") component of that object is > what is rebound to the RHS object. > ? ? ? ? ? ? ? ? lhs_name.subcomponent = rhs_expression > ? ? ? ? ? ? ? ? lhs_name[index] = rhs_expression > ? ? ? ? ? ? ? ? lhs_name[keyvalue] = rhs_expression > > ? ? ? ? No matter how many "." or "[]" sets appear, at the very bottom one > has focused down to a component, and that component get rebound from one > object to another object. > > ? ? ? ? In no case does the object originally bound get changed. FOR > assignment... Mutables using methods are a bit different... > > ? ? ? ? lhs.append(rhs) ? ? ? ? #assume a list > > adds a new element into the list, but it is still the same "list" (and > in that aspect, it is also a "qualified name"). You could warn if a name is assigned to twice-- maybe even error. Assignment is not a method. a= object() a= object() a is a name. it is a name of an object. what name? a. what object? that changes on demand. >>> a= 2 >>> a+= 2 >>> a 4 >>> a= (2,) >>> a+= (3,) >>> a (2, 3) >>> a= 2 >>> id( a ) # 1 505252512 >>> a+= 2 >>> id( a ) 505252544 # != >>> a 4 >>> a= (2,) >>> id( a ) # 2 11863472 >>> a+= (3,) >>> id( a ) # != 11933976 >>> a= [2] >>> id(a) # 3 11935296 >>> a+= [3] >>> id(a) # == 11935296 >>> += changed the id of a in the first two cases. It did not in the third. Assignment is not a method. Sometimes augmented assignment is. In the first two cases, the original was destroyed. In the third, the newcomer was destroyed. The newcomer was also destroyed in the first two. If you can write 'a' on an envelope and it goes to 244 White St., then assigning to a is an order to the post office: send 'a' to somewhere else. It doesn't change what it referred to before, though-- those letters are already delivered! There is ambiguity in 'change "a"'-- it can mean 'at the post office' or 'wherever letters address to "a" go to'. However, you can't change the entry of "a" with the post office of another scope. >>> "I want 'a' to be [3]." AmbiguityError: Use 'rearrange' or 'reroute'. >>> "Rearrange 'a'. Move out and move 3 in." a[:]= [3] >>> "Reroute 'a'. Move 3 in to the place wither mail to 'a' will go." a= [3] Some buildings have no entries at the post office. Some names don't either. You can change the contents of a building if you can send mail to it-- send a letter that says to change the contents! Other post offices keep their entries. >>> "Change another post office's entry for 'a'." No. >>> "Change mine." Ok! From martin at v.loewis.de Sat Mar 8 09:35:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Mar 2008 15:35:22 +0100 Subject: os.chdir In-Reply-To: References: Message-ID: <47D2A42A.9010902@v.loewis.de> >> os.chdir("~/dir1") > > It is not mentioned in the documentation but I'm pretty sure os.dir() doesn't do > tilde expansion since this is usually performed by a shell. > > You should use instead: > > os.chdir(os.join(os.environ['HOME'], 'dir1')) Or os.chdir(os.path.expanduser("~/dir1")) Regards, Martin From timr at probo.com Thu Mar 13 03:02:33 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 13 Mar 2008 07:02:33 GMT Subject: mulithreaded server References: <7c555afb-2df0-43f2-aa16-d1e48da1510a@e23g2000prf.googlegroups.com> Message-ID: asit wrote: > >In the above program, why there is an unhandeled exception ??? Probably because the code as you posted it has at least a half-dozen mistakes. >import socket >import sys >import thread > >p=1 >PORT=11000 >BUFSIZE=1024 > >def getData(cSocket): > global stdoutlock,cSocketlock > while True: > cSocketlock.acquire() > data=cSocket.recv(BUFSIZE) > if data=='q': > data='client exited' > cSocket.close() > p=0 > cSocketlock.release() > stdoutlock.acquire() > stdout.write(data) > stdoutlock.release() You do not need the "global" statement there, since you are not changing either stdoutlock or cSocketlock. However, you ARE setting "p", so you need a "global p". Otherwise, you are simply creating a variable called "p" that is local to the function, and which disappears when the function returns. Calling a global variable "p" is a very bad practice, by the way. >def sendData(cSocket): > global stdoutlock,cSocketlock > while True: > stdoutlock.acquire() > data=raw_input('>>') > cSocketlock.acquire_lock() > if data=='q': > stdout.write('server exited') > stdout.release() > p=0 > cSocket.close() > sSocket.send(data) > sSocketlock.release() Same comments. You do not need the "global" statement you have, but you do need "global p" if you want to change the global version of "p". Further, as Jean-Paul pointed out and you rather rudely ignored, there is no variable called "sSocketlock", because you commented it out. Next, "stdout.release()" will fail. "stdout" does not have a release function. You meant "stdoutlock.release()". Next, you release sSocketlock, but you never acquired it. And if data does not equal "q", you repeatedly acquire stdoutlock, but you never release it. Fix these problems, and then see if you can ask for help in a more thorough fashion. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ron at example.com Fri Mar 28 22:16:04 2008 From: ron at example.com (Ron Eggler) Date: Sat, 29 Mar 2008 02:16:04 GMT Subject: last mouse movment or keyboard hit References: <6512egF2dik46U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Ron Eggler schrieb: >> Hi, >> >> I would like to get the time of the most recent human activity like a >> cursor movement or a key hit. >> Does anyone know how I can get this back to start some action after there >> has been no activity for X minutes/seconds? > > Try hooking yourself into the OS screen-saver-code. I have looked at the KDE code but couldn't quite figure out how it's working... :o Any help would be appreciated! -- chEErs roN From adece91f7 at 21cn.com Tue Mar 18 03:20:15 2008 From: adece91f7 at 21cn.com (Designers Handbags) Date: Tue, 18 Mar 2008 00:20:15 -0700 (PDT) Subject: Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M, Best Luxury Replica Watches Message-ID: Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M, Best Luxury Replica Watches Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M Link : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_14060M.html Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M Information : Brand : Swiss Rolex Watches ( http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/swiss_rolex_replica_watches_1.html ) Gender : Mens Case Material : Stainless Steel Case Diameter : 14060M, Rolex-14060M Case Thickness : 40mm Dial Color : Black Bezel : Black Movement : 31 jewel chronometer movement Clasp : Stainless Steel Water Resistant : Item Variations : Our Price : US $451 Rolex Oyster Perpetual Submariner 31-Jewel Movement Stainless Steel Case - 40mm Special Time-Lapse Bezel Synthetic Sapphire Crystal Black Dial, Black Bezel Stainless Steel Oyster Bracelet Fliplock Clasp and Extension Link Pressure Proof to 1000 Feet Model Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M is new brand replica, join thousands of satisfied customers and buy your with total satisfaction. A Replica-Watch-Shopping.com 30 Day Money Back Guarantee is included with every Swiss Rolex Watches Replica Series for secure, risk-free online shopping. Replica-Watch-Shopping.Com does not charge sales tax for the Fake Swiss Rolex Oyster Perpetual Submariner Steel Mens Watch 14060M. The Same Chopard Watches Series : Swiss Rolex Oyster Perpetual Submariner Date 18kt Gold Mens Watch 16618B : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16618B.html Swiss Rolex Oyster Perpetual Submariner Date 18kt Gold Mens Watch 16618 : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16618.html Swiss Rolex Oyster Perpetual Submariner Date Two-Tone Steel Mens Watch 11613BK : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16613BK.html Swiss Rolex Oyster Perpetual Submariner Date Steel Mens Watch 16610 : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16610.html Swiss Rolex Oyster Perpetual Submariner Date Mens Watch 16613-BLSO : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_Mens_Watch_16613BLSO.html Swiss Rolex Oyster Perpetual Submariner Date Mens Watch 16613-GYDO : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_Mens_Watch_16613GYDO.html Swiss Rolex Oyster Perpetual Submariner Date 18kt Gold with Diamonds and Sapphires Mens Watch 16613CDD : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16618DD.html Swiss Rolex Oyster Perpetual Submariner Date Two-Tone Steel with Diamonds and Sapphires Mens Watch 16613CDD : http://www.replica-watch-shopping.com/swiss_rolex_replica_watches/Swiss_Rolex_16613CDD.html From oswald.harry at gmail.com Fri Mar 28 11:15:48 2008 From: oswald.harry at gmail.com (harryos) Date: Fri, 28 Mar 2008 08:15:48 -0700 (PDT) Subject: finding euclidean distance,better code? References: Message-ID: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> > The code is pretty legible as it is now. Anyway, using min() and a > generator: > > hi is this calculated distance really Euclidean distance? When i checked wikipedia http://en.wikipedia.org/wiki/Euclidean_distance it shows a calculation involving sum of squares of the differences of elements.Here in this code ,the sum of coordinates are used? is that a different measure? oharry From jergosh at wp.pl Wed Mar 26 09:37:11 2008 From: jergosh at wp.pl (=?UTF-8?B?R3J6ZWdvcnogU8WCb2Rrb3dpY3o=?=) Date: Wed, 26 Mar 2008 14:37:11 +0100 Subject: Beta testers needed for a high performance Python application server In-Reply-To: References: Message-ID: <47EA5187.3060405@wp.pl> > Why not just put it on the net somewhere and tell us where it is? > People aren't generally going to want to help or even look at it if > you treat it like a proprietary application. So, put the documentation > and code up somewhere for all to see. > http://www.yieldserver.com:8081/ From bignose+hates-spam at benfinney.id.au Wed Mar 5 17:36:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 06 Mar 2008 09:36:29 +1100 Subject: Identifying messages in a thread (was: Please keep the full address) References: Message-ID: <8763w094sy.fsf_-_@benfinney.id.au> "D'Arcy J.M. Cain" writes: > On Wed, 5 Mar 2008 13:38:59 -0800 (PST) > Mike Driscoll wrote: > > On Mar 5, 12:50 pm, castiro... at gmail.com wrote: > > I'm not sure why you change the address like this but could you > please include the full address. It's a misfeature of Google's mail interface. The poster to whom you're responding could choose a different mail interface, but you'll have a difficult time convincing them of that. > Those of us who identify the time wasters would also like to drop > the responses to their posts and changing the address makes this > impossible. Not at all. AFAIK the messages from Google mail correctly include the 'In-Reply-To' field or the 'References' field in the message header. So, you can know by those fields whether a message is part of a thread you've previously identified. -- \ "I wish there was a knob on the TV to turn up the intelligence. | `\ There's a knob called 'brightness' but it doesn't work." -- | _o__) Eugene P. Gallagher | Ben Finney From michael.wieher at gmail.com Wed Mar 5 17:12:49 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 5 Mar 2008 16:12:49 -0600 Subject: What is a class? Message-ID: You import classes from modules. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Mar 17 08:42:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 10:42:24 -0200 Subject: pass float array(list) parameter to C References: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 01:17:31 -0200, zaley escribi?: > In my program, python is communicated with C use ctypes . > I can't find a better way to pass float array(list) parameter to C > function. > Can someone give me a help? Use the array module to create an array of floats, like float[] in C. http://docs.python.org/lib/module-array.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 18:32:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Mar 2008 22:32:10 -0000 Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <13u353a51v9kp36@corp.supernews.com> On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote: > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but calculate/ > compare in UTC. Your proposal is ambiguous. What does that mean? Can you give an example? > - Raise exceptions when an illegal or ambiguous datetime is instantated. You mean like they already do? >>> datetime.datetime(2008, 03, 35) # 35th of March Traceback (most recent call last): File "", line 1, in ValueError: day is out of range for month As for ambiguous, how can datetime arguments be ambiguous? Help on class datetime in module datetime: class datetime(date) | datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) What possible ambiguity is there? -- Steven From knut.urbye at gmail.com Wed Mar 26 10:17:15 2008 From: knut.urbye at gmail.com (Python Programming on Win32) Date: Wed, 26 Mar 2008 07:17:15 -0700 (PDT) Subject: py2exe socket.gaierror (10093) Message-ID: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Hi, I have encountered a problem which I can not figure out a solution to. Tried Googeling it, but to no help unfortunately. The problem is running smtplib in a py2exe compiled exe file. When it tries to establish a socket to the mail server it fails. Just wondering someone has encountered this before, and if someone might be able to point me in the right direction. Unhandled exception in thread started by Traceback (most recent call last): File "AutomationThread.pyc", line 152, in Run File "mail.pyc", line 11, in sendMail File "smtplib.pyc", line 244, in __init__ File "smtplib.pyc", line 296, in connect socket.gaierror: (10093, 'getaddrinfo failed') Thank you ! From wuwei23 at gmail.com Tue Mar 25 07:36:55 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Mar 2008 04:36:55 -0700 (PDT) Subject: My python interpreter became mad ! References: Message-ID: <95b7d0b1-345b-40b2-bf9a-b9783ccbee1e@s13g2000prd.googlegroups.com> On Mar 25, 9:05 pm, Benjamin Watine wrote: > I'm trying to use re module to match text with regular expression. In a > first time, all works right. But since yesterday, I have a very strange > behaviour : The following line in the traceback shows you're not using the default python module: > File "/etc/postfix/re.py", line 19, in ? Were you using the interpreter in the /etc/postfix directory? The re module there seems to be shadowing the site package. Hope this helps. - alex23 From castironpi at gmail.com Mon Mar 17 18:38:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 15:38:58 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> On Mar 17, 11:03?am, Duncan Booth wrote: > Ninereeds wrote: > > On Mar 17, 1:31 pm, Duncan Booth wrote: > > >> A common explanation for this is that lists are for homogenous > >> collections, tuples are for when you have heterogenous collections i.e. > >> related but different things. > > > I interpret this as meaning that in a data table, I should have a list > > of records but each record should be a tuple of fields, since the > > fields for a table usually have different forms whereas the records > > usually all have the same record layout. > > That is indeed what Python's Database API usually does (although it doesn't > mandate it): > > ? ? ? ? .fetchmany([size=cursor.arraysize]) > > ? ? ? ? ? ? Fetch the next set of rows of a query result, returning a > ? ? ? ? ? ? sequence of sequences (e.g. a list of tuples). An empty > ? ? ? ? ? ? sequence is returned when no more rows are available. Two things: >>> b in b False in S. D'Aprano's example, which somewhat obscures (casts a shadow on) its intuitive meaning. "Hand me everything that's in there. > For x in There: hand( me, x ). > For x in rchain( There ): hand( me, x ) < Hand me anything that's in anything that's in there, or is in there. Closet = [ Box[ ball ] ] > Box[ ball ]? or Box, ball? Despite that 'in' is a very common word [lacks cit.], you don't often get ambiguities (read: questions) about containers in something. Too custom. The word isn't defined at that extremity of combinations / cartesian products of particulars (context). It doesn't have a common sense, and computer science is a pretty unique field in that it finds (or, invents) all-and-only definitions of words. (Which reminds me, what about a classmethod __getitem__ construtor?) However, from mathematics, which is at least older, if not more in tune with the common senses and uses, (there exists an a and b such that) Member( a, b ) != Exists x such that Member( a, b ) & Member( b, x ). In other words, Python honors math's definition. In the example, would you treat 'ball' separately unless explicity asked to? (But, keep sure not to alter the contents of any of the containers that are in there.) There's a fine example of miscommunication: neither behavior was the default between the pair: one knew one default; the other knew another. (But, it's ok to alter the contents of any containers.) Aside, do you think there are trends among who and when uses what defaults? Such as math background, social status, etc.? Computers are very good at attention to detail: ("I" am.) "You did not specify whether to alter containers in it." Of course, the program that's following would have to have noticed two things: that there's a short-cut if you can, and you might not want it to. It's not only a problem of formal systems: No= { X, Y, Z }. Some (finite) context hasn't determined the convention of wish-expression in every combination of (future possible) cases. while 1: print( "You made an assumption!" ) print( "No, -you- made an assumption!" ) break while 1: print( "I made an assumption." ) print( "I also made an assumption." ) But is it determined whether it's determined whether the person meant to? That is, can you tell whether the person didn't specify? "I'm sorry, we haven't spoken about containers in containers enough for me to tell what your wishes are." My worry is that popular judgment isn't best in science. What factors in to the architect's decision? His feelings about use cases? His calculations about use cases? His feelings about popularity of each? His calculations about popularity? Mabye Python would have ten extra speakers if __contains__ had been defined differently! X percent of all shortest-form syntactic combinations can be written in less tokens with one definition, but no matter how much I remind them, they won't remember combination C, so only Y percent are actually, practically ever written in 2008 Earth programming. Because we're stupid, no. Because we have other priorities than programming. (But my bigger house for me was more important.) 'rchain', recursive chain, might be the next function on the path that itertools is on. Databases have come to (but don't have to stay) use integers as autokeys in records. That makes one way to refer to a record to refer to its integer. However, if one's testing for identity between records, that key is redundant. Just identify yourself, and refer back to earlier in context. And incidentally, why namedtuples but no namedlists? Or nameddicts? And could one define an anonymous type? This is interesting: >>> type('A',(),{}) is type('A',(),{}) False >>> type('A',(),{}) == type('A',(),{}) False >>> type('G',(),{}) >>> G Traceback (most recent call last): File "", line 1, in NameError: name 'G' is not defined A type went out of scope. Is there an abstraction of 'pickle' which doesn't need the type defined in its target module? >>> pickle.dumps( type('A',(),{}) ) pickle.PicklingError: Can't pickle : it's not the same object as __main__.A >>> pickle.dumps( type('A',(),{})() ) pickle.PicklingError: Can't pickle : it's not the same object as __main__.A >>> del A >>> pickle.dumps( type('A',(),{}) ) pickle.PicklingError: Can't pickle : it's not found as __main__.A >>> pickle.dumps( type('A',(),{})() ) pickle.PicklingError: Can't pickle : it's not found as __main__.A But all the information's there! From matiassurdi at gmail.com Sun Mar 30 08:29:07 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Sun, 30 Mar 2008 14:29:07 +0200 Subject: python ODF library? Message-ID: Do yo know any good OpenDocumentFormat library for python? I'm starting a project on wich I'll have to programatically modify ODF text documments, so, after reinventing the wheel, I'd like to know if already something exists. Thanks a lot. From deets at nospam.web.de Sun Mar 23 15:01:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 23 Mar 2008 20:01:21 +0100 Subject: A "roadmap" for ctypes wrapping? In-Reply-To: References: Message-ID: <64nno9F2d12tkU1@mid.uni-berlin.de> Alaric Haag schrieb: > Hi all, > > I'm undertaking a pretty significant wrapping project (a linux > shared-object lib) early in my Python experience, and thought it might > be useful for many more that just myself if this thread were to produce > a sort of roadmap for approaching wrapping with ctypes. > > I've been doing some reading, but want to verify my "big picture view" > and have come to make the following presumptions: (so, please correct me > where erroneous) > > - One gathers the ".h" header(s) for the library to determine the data > structures (defined in "#define" and "typedef" statements) as well as > the prototypes for the library routines. > > - From these header files, one defines attributes to reproduce the > "#define" statements, and also reproduces the typedef "structs" by > defining classes and assigning a Python list of tuples for the > "_fields_" attribute, to associate a ctype and field name with each > field in the "struct". > > - Use ctypes.CDLL to "connect" to the library, and instantiate an object > whose attributes are the library routines. > > - From that object, instantiate each of the routines, and override the > "argtypes" attribute for each of these with a list of "ctypes", and a > single ctype for the "restype" attribute. In either case, the "type" > might be a newly-defined type (class) that's more complex than just the > provided ctypes. > > Presumably, judicious use of the leading "_" (underscore) is used to > hide (make private) the "ugly details" from the wrapper user, revealing > only the routines, and possibly, classes that describe data types the > original API expects the user to need. > > ====== > Can anyone with some "wrapping" experience add/modify/enhance the above? Use gccxml to gather the typedefs. And look at Gary Bishop's site to see some cool helper classes/functions for dealing with ctypes. Diez From magdoll at gmail.com Wed Mar 12 12:41:42 2008 From: magdoll at gmail.com (Magdoll) Date: Wed, 12 Mar 2008 09:41:42 -0700 (PDT) Subject: merging intervals repeatedly References: Message-ID: > Hi, > > The problem, as stated here, may have several solutions. For instance > the following set of intervals also satisfies the constraint: > (1,15), (20,40), (50,100) > > One question you should ask yourself is: do you want all solutions? or > just one? > If you want just one, there's another question: which one? the one with > the most intervals? any one? I actually don't know which solution I want, and that's why I keep trying different solutions :P > If you want all of them, then I suggest using prolog rather than python > (I hope I won't be flamed for advocating another language here). Will I be able to switch between using prolog & python back and forth though? Cuz the bulk of my code will still be written in python and this is just a very small part of it. > > > Is there already some existing code in Python that I can easily take > > advantage of to produce this? Right now I've written my own simple > > solution, which is just to maintain a list of the intervals. I can use > > the Interval module, but it doesn't really affect much. I read one > > interval from the input file at a time, and use bisect to insert it in > > order. The problem comes with merging, which sometimes can be > > cascading. > > > ex: > > read (51,65) ==> put (51,65) in list > > read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) > > read (50,66) ==> merge with (51,65) to become (50,66) ==> now can > > merge with (62,100) > > The way this algorithm is presented suggests an additional constraint: > you cannot merge two intervals if their overlap <= N. In that case, > there is a single solution indeed... > Nitpick: you cannot merge (50,66) and (62,100) since their overlap is > still <= 5. Sorry I keep messing up my example. I meant, I would merge them if they overlap by >= N....but anyways. > > If you have a reasonable number of intervals, you're algorithm seems > fine. But it is O(n**2), so in the case you read a lot of intervals and > you observe unsatisfying performances, you will have to store the > intervals in a cleverer data structure, see one of these:http://en.wikipedia.org/wiki/Interval_treehttp://en.wikipedia.org/wiki/Segment_tree Thanks! Both of these look interesting and potentially useful :) From aahz at pythoncraft.com Sat Mar 15 11:33:01 2008 From: aahz at pythoncraft.com (Aahz) Date: 15 Mar 2008 08:33:01 -0700 Subject: Joseph Weizenbaum References: Message-ID: In article , Tim Roberts wrote: >Jeff Schwab wrote: >>Roel Schroeven wrote: >>> castironpi at gmail.com schreef: >>>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>>> >>>>> How do you feel about creator of Eliza? >>>> >>>> What is Eliza? >>> >>> Does that question interest you? >> >>Well played, sir. >> >>Earlier you said what is Eliza. Do you still feel that way? > >I am embarrassed to say that this vaguely disrespectful exchange made me >laugh out loud. Serious: why do you think this is disrespectful? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From d3vvnull at gmail.com Tue Mar 18 18:09:19 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 18 Mar 2008 17:09:19 -0500 Subject: finding items that occur more than once in a list In-Reply-To: <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: <170543c70803181509i51149fd9v45de2f82b642af1@mail.gmail.com> How about using list comprehension? l1 = ["apples","apples","bananas","oranges","oranges","peaches"] s1 = set([x for x in l1 if l1.count(x) > 1]) On Tue, Mar 18, 2008 at 4:56 PM, sturlamolden wrote: > On 18 Mar, 22:25, sturlamolden wrote: > > > def nonunique(lst): > > slst = sorted(lst) > > return list(set([s[0] for s in > > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) > > Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using > the set function, there is more structure to exploit when the list is > sorted: > > > def nonunique(lst): > slst = sorted(lst) > dups = [s[0] for s in > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > return [dups[0]] + [s[1] for s in > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sun Mar 16 23:20:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 16 Mar 2008 20:20:09 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 10:49 pm, Brian Jones wrote: > On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: > > > If you did not like the programming this year (aside from the sponsor > > talks) and you did not participate in organizing PyCon or in delivering > > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > > I find this insulting, inexcusable, and utter nonsense. If putting the > blame for a failed experiment on the backs of the good folks who paid > good money for travel, lodging, and registration is also an > experiment, you can hereby consider it also failed. He said "aside from the sponsor talks", chief. You need one of these: http://tinyurl.com/26owvg Carl Banks From deets at nospam.web.de Mon Mar 10 18:18:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 23:18:02 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: <63i6j9F2793buU1@mid.uni-berlin.de> Message-ID: <63lqcuF27pbnbU1@mid.uni-berlin.de> metawilm at gmail.com schrieb: > On Mar 9, 2:21 pm, "Diez B. Roggisch" wrote: >> Is this soft-exception implemented anywhere, so that one can see what >> experiences and best practices have evolved around using it? > > Lie's idea is to separate exceptions in two groups, those that must be > handled and those that don't. A better way is to have two different > ways to raise exceptions: one exceptional situation can be "Hard" in > some situations and "Soft" in others, and it is up to the way of > raising to make the choice, while the exception stays the same. > > Common Lisp has two ways of raising: functions "error" and "signal". > Python's "raise" is like CL's "error": you end up in the debugger if > the exception is not handled. Exceptions that are raised by CL's > "signal" don't have to be caught: if there is no matching "except" > clause the raise statement becomes a "pass". > > Or as Wikipedia states nicely: "Conditions are a generalization of > exceptions. When a condition arises, an appropriate condition handler > is searched for and selected, in stack order, to handle the condition. > Conditions which do not represent errors may safely go unhandled > entirely; their only purpose may be to propagate hints or warnings > toward the user." How would that differ from something like this: with add_soft_handler(SoftException): invoke_something() ... # deep down in code raise_soft(SoftException()) The implementation of add_soft_handler and raise_soft is trivial - a bit of thread-local storage and a stack. I don't say that such mechanism isn't handy occasionally - I just don't see the need for specialized syntactical and/or interpreter-support. Diez From siona at chiark.greenend.org.uk Thu Mar 13 10:21:37 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Mar 2008 14:21:37 +0000 (GMT) Subject: How to send a var to stdin of an external software References: Message-ID: Benjamin Watine wrote: >How can I do this ? I would like a function like that : > > theFunction ('cat -', stdin=myVar) > >I don't need to get any return value. http://docs.python.org/lib/node534.html says this is spelt myVar = subprocess.Popen(["cat", "-"], stdout=subprocess.PIPE).communicate()[0] (Probably not obvious how to find this if you've not come across the backtick notation in shell or Perl.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From fakeaddress at nowhere.org Thu Mar 6 03:37:07 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 08:37:07 GMT Subject: Dual look-up on keys? In-Reply-To: <13su60prq21ccd2@corp.supernews.com> References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: Grant Edwards wrote: > It may be obvious that he has a question. It's not the least > bit obvious what that question is. How can we efficiently implement an abstract data type, call it 'DoubleDict', where the state of a DoubleDict is a binary relation, that is, a set of pairs (x, y); and the operations on a DoubleDict are those on a Python set, plus: find_by_first(self, x): return [y where (x, y) in DoubleDict] find_by_second(self, y): return [x where (x, y) in DoubleDict] Python can implement this ADT directly as specified, but the find_by_ operations would run in time len(self). We want an implementation where the find_by's run in O(1 + k) where k is the length of the returned sequence. -- --Bryan From PurpleServerMonkey at gmail.com Sat Mar 22 04:45:37 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Sat, 22 Mar 2008 01:45:37 -0700 (PDT) Subject: Distributing Python Apps on Linux\BSD References: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> <9290c7b1-3e51-46fe-96e7-6c2ebf4f5b77@u10g2000prn.googlegroups.com> Message-ID: On Mar 22, 2:26 am, Miki wrote: > Hello, > > Disclaimer: I'm not an expert on the subject. > > > Setuptools and friends seem to be focused on distributing modules, I'm > > at the other end of the scale where I want to distribute an entire > > application so that an Administrator can run a single install and have > > a fully operational product. A key requirement is that I want the > > application to fit in with what and admin would expect an application > > to look like at the system level i.e site-packages like structures > > aren't suitable. > > You do that with distutils as well. > > > So far I've thought of using a configure script and make which would > > call some custom python installer script to do the actual install. It > > fits in nicely with what I want to achieve but are there any better > > options out there, how are others doing the same thing? > > Every distro flavor has it's own installer: apt/deb, rpm, port, ... > On Windows you can use one of the free installer (InnoSetup and > friends). > > HTH, > -- > Miki http://pythonwise.blogspot.com Well I'm not really interested in rpms or deb packages right now, I want to get it to the point where it will run on BSD and Linux without using distribution specific tools. Using a tarball or the standard python tools would be best. The problem is all the documentation surrounding distutils and setuptools refers to modules, now I'm not sure why but it seems most Python developers think an application is the same thing as a module. Unless you are writing very small applications that's definitely not the case. So I guess the question is, using distutils or setuptools is it possible for a user to select where to install the application i.e / usr/local? If not then I think it's going to be tarball deployment with a custom setup script, was hoping there was a better way. From asr-1 at comcast.net Wed Mar 12 20:42:44 2008 From: asr-1 at comcast.net (Andrew Rekdal) Date: Wed, 12 Mar 2008 19:42:44 -0500 Subject: Big file Message-ID: I am working in the class constructor defining elements of an application. The problem is the file is getting unmanageble and I am wanting to extend the contructor __init__ to another file. Is it possible to import directly into the contructor the contents of another module file? If so how would this be done? Thanks -- andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sat Mar 8 18:52:40 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 09 Mar 2008 00:52:40 +0100 Subject: float / rounding question In-Reply-To: References: <13t456cmgfpdhbc@corp.supernews.com> Message-ID: Mark Dickinson schreef: > On Mar 7, 11:23 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote: >>> Sorry to come in so late in this discussion. Although it is correct to >>> say that many real numbers that have an exact decimal representation >>> cannot be exactly represented in binary, that is no excuse to print 53.6 >>> as 53.600000000000001. This is just lousy printing and the fact that >>> this kind of question comes up every week shows that it is confusing to >>> many people. >> Good. That's a feature, not a bug. > > Even so, it's not clear that Python's current behaviour couldn't be > improved. I have a mild dislike of the lack of consistency in the > following, which arises from Python arbitrarily stripping trailing > zeros from the result returned by the C library functions: > >>>> 10.1 > 10.1 >>>> 10.2 > 10.199999999999999 >>>> 10.3 > 10.300000000000001 >>>> 10.4 > 10.4 Actually I don't see what all the fuss is about. If you want a nicely rounded number, use print or str() or the % operator. *Only* when you use repr() or when the interactive interpreter uses it to print the value of the expression, you get something that doesn't look as nice. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ebenze at hotmail.com Sun Mar 16 11:38:35 2008 From: ebenze at hotmail.com (Eric B.) Date: Sun, 16 Mar 2008 11:38:35 -0400 Subject: Cannot build Python 2.4 SRPM on x64 platform References: Message-ID: "Michael Wieher" wrote in message news:fb251aba0803160709w475de08cg1cabedcfb2205672 at mail.gmail.com... > Sorry I don't have much of a better idea, but if I had this kind of > problem > with an RPM, I'd just grab the tarball and start hacking away at > ./configure > pre-requirements, trying to use --options to trim it down to the bare > minimal and see if I can get it to load up. Thanks for the suggestion. I did try to build from the tarball, and make & make install work fine, but I still don't have any lib64 directories. I get the impression that the config script doesn't build for 64bit platforms. Do I need to pass any particular arguments to the ./configure script and/or the make/make install commands in order to ensure this being built for 64bits? Thanks, Eric From solisgb at gmail.com Mon Mar 10 04:49:53 2008 From: solisgb at gmail.com (luis) Date: Mon, 10 Mar 2008 01:49:53 -0700 (PDT) Subject: unable to install gdal References: <15838144-b7a0-4d1b-98b3-fdfcfdb9a916@n75g2000hsh.googlegroups.com> Message-ID: <86d8bc35-24d5-4145-8421-94d71066209d@60g2000hsy.googlegroups.com> On 9 mar, 16:37, luis wrote: > Hi > > On Windows xp sp2 and python 2.4 > > Yesterday I running old versions of gdal, and I try to upgrade > > I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe > I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 > > I follow install's instructions fromhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython, > all is ok, I set path and path_data variables with correct values, but > whe I run a script, an error raises > > from osgeo import ogr > ? File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? > ? ? import _ogr > ImportError: DLL load failed: process not found > > Also I try with instructions fromhttp://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gda... > I move _gdal.pyd (and the others *.pyd) from my Python installation's > (C:\Python24\Lib\site-packages\osgeo) into my Python installation's > DLLs folder (C:\Python24\DLLs). > When I run the script the error message persists. > > Some help is welcome. If I install on a XP without previous installation of gdal, the installation works fine. Perhaps is a problem with XP's registry From furkankuru at gmail.com Wed Mar 26 07:13:17 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 13:13:17 +0200 Subject: embedded python pythonpath In-Reply-To: References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> <3a4a8f930803251822h5d423198yc318ed270ad7d92a@mail.gmail.com> Message-ID: <3a4a8f930803260413v62ae6935t9a4d3dfbf11dd4dc@mail.gmail.com> On Wed, Mar 26, 2008 at 3:49 AM, Gabriel Genellina wrote: > En Tue, 25 Mar 2008 22:22:41 -0300, Furkan Kuru > escribi?: > > > On 3/26/08, Gabriel Genellina wrote: > > > >> En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru > >> escribi?: > >> > >> > Actually, I do not want any .py or .pyc files around my executable. > >> > (including userdict, sys, site etc) > >> > I want to have just single zip file for all python files. > >> > >> Putting all of them into pythonNN.zip (NN depending on the Python > >> version > >> in use) should be enough, but I've never tried it. > > I had already tried putting all of them into pythonNN.zip but I had to > > copy it to the place > > where sys.path points in my case it was windows\system32\python25.zip > > It should be in the same directory as python25.dll; you don't have to use > windows\system32 if you copy python25.dll to your application directory. > I did not know that. Ok, I tried and it works! Thank you, -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From justus.schwabedal at gmx.de Wed Mar 12 20:11:56 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Thu, 13 Mar 2008 01:11:56 +0100 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: <13tgrqb132if842@corp.supernews.com> References: <13tgrqb132if842@corp.supernews.com> Message-ID: What do you need it for anyway? I just read about it and I think it's useless in python. On Mar 13, 2008, at 1:03 AM, Steven D'Aprano wrote: > On Wed, 12 Mar 2008 11:19:05 -0700, Alex wrote: > >> Hi all, >> >> The subject says pretty much all > > Only to people who know what the Perl BEGIN{} block means. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list From mensanator at aol.com Tue Mar 4 17:40:04 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 14:40:04 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <042d507d-f53d-4219-be6e-d6b7a1f1d6c4@s8g2000prg.googlegroups.com> Message-ID: <8aa1c242-db46-4479-a26c-07517b478714@n75g2000hsh.googlegroups.com> On Mar 4, 3:00?pm, Istvan Albert wrote: > On Mar 4, 3:13 pm, Mensanator wrote: > > > But what if _I_ wanted to make a repeatable sequence for test > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > on every call? > > Would it? I don't know, haven't tried it yet, merely extrapolating from how I _THINK_ it works. I used to be a System Test Engineer and had a gift for being able to walk up to hardware/software and break it. Spooky? No, because I could extrapolate from the design, I could often anticipate just where to nudge it to cause it to crash. I wasn't very popular with the programmers. > > It may just be that you are now itching to see a problem even where > there isn't one. No, no, no. That would be an oh-what-a-giveaway, wouldn't it? > > i. From db3l.net at gmail.com Tue Mar 4 18:59:14 2008 From: db3l.net at gmail.com (David Bolen) Date: Tue, 04 Mar 2008 18:59:14 -0500 Subject: is there enough information? References: <13s9u7dg24es73a@corp.supernews.com> <13spkb990ha3v6c@corp.supernews.com> Message-ID: Dennis Lee Bieber writes: > On Mon, 3 Mar 2008 08:11:43 -0500, Jean-Paul Calderone > declaimed the following in comp.lang.python: > >> I'm not sure, but you seem to be implying that the only way to use Windows' >> asynchronous I/O APIs is with threads. Actually, it is possible (and Twisted >> allows you) to use these as well without writing a threaded application. >> > I only pointed out that, on Windows, one can not use the common > /select()/ function with files. And one rarely sees examples of coding a > Twisted-style (emphasis on style) asynchronous callback system mixing > files and network sockes using the Windows-specific API. > > If using threads, the Windows asynchronous I/O isn't needed... let > the thread block until the I/O completes, then transfer the data (or a > message that the data is available) back to the main processing > thread... You're probably right that it's rare, but when needed, using the Windows asynchronous/overlapping API can provide a better solution than blocking threads depending on the needs at hand, and without involving any callbacks or Twisted-style programming. An example of mine is high performance serial port handling as part of a custom FHSS wireless adapter with a serial port interface to the PC. In this case, minimizing I/O latency was crucial since delays could mean missing a broadcast timeslot (about 15ms) on the wireless network. A serial port isn't a disk file, but certainly a "file" in the context of Windows handles. Early implementations used independent threads for reading/writing to the serial port and blocking during such operations, but that turned out to have an undesirable amount of latency, and was also difficult to interrupt when the threads were in a blocked condition. Instead I created a single thread that had a loop using overlapped I/O simultaneously in each direction as well as native Windows event objects for aborting or signaling that there was additional data to be written (the pending read I/O handled the read case). The main loop was just a WaitForMultipleObjects to handle any of the I/O completion indications, requests for more I/O or aborts. It was very high performing (low latency) with low CPU usage - measurably better than a multi-threaded version. Communication with the rest of the application was through a thread-safe bi-directional buffer object, also using native Win32 event objects. It worked similar to a queue, but by using the native event objects I didn't have the performance inefficiencies for reads with timeouts of the Python objects. The underlying Python primitives don't have the timeout capability built in, so reads with timeouts get implemented through checks for data interspersed with increasing sleeps, which adds unnecessary latency. Anyway, it worked extremely well, and was a much better fit for my needs than a multi-threaded version with blocking I/O, without it having to be Twisted-style. -- David From bronger at physik.rwth-aachen.de Sun Mar 16 04:42:14 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 16 Mar 2008 09:42:14 +0100 Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: <87od9f3vrt.fsf@physik.rwth-aachen.de> Hall?chen! castironpi at gmail.com writes: > [...] > *** English is SVO, subject-verb-object. French is too, unless the > object is direct: subject- direct-object -verb. Really? I thought this is only the case for pronouns. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From arnodel at googlemail.com Mon Mar 3 11:20:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 3 Mar 2008 08:20:42 -0800 (PST) Subject: Exception or not References: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Message-ID: <499b589c-ab2f-41de-a8ec-e5ba0abb0c4c@p25g2000hsf.googlegroups.com> Monica Leko wrote: > Suppose you have some HTML forms which you would like to validate. > Every field can have different errors. For example, this are the > forms: > > username > password > etc > > And you want to validate them with some class. Is this good pattern: [...] You could have a look at how django [http://www.djangoproject.com] and how they handle forms: http://www.djangoproject.com/documentation/newforms/ In fact their newforms module should work fine as a standalone. -- Arnaud From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 07:40:17 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 13:40:17 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: <47cfe620$0$9590$426a74cc@news.free.fr> Guillermo a ?crit : > Hello, > > This is my first post here. I'm getting my feet wet with Python and I > need to know how can I check whether a variable is of type dictionary. What makes you say you "need" to know this ? Except for a couple corner cases, you usually don't need to care about this. If you told us more about the actual problem (instead of asking about what you think is the solution), we might be of more help... > Something like this: > > if isdict(a) then print "a is a dictionary" Should this work for subclasses of dicts ? Should this work for non-subclasses of dict implementing the dict protocol ? From ra21vi at gmail.com Sat Mar 15 16:57:36 2008 From: ra21vi at gmail.com (Ravi Kumar) Date: Sun, 16 Mar 2008 02:27:36 +0530 Subject: Weight Problem Message-ID: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> An Interesting problem, """ A man has only 4 bricks of different weights, lies between 1-40KG, Also, the total weights of Brick A, B, C, D (ie A+B+C+D) is 40KG. The man uses that brick to calculate every possible weight from 1 KG to 40 KG in his shop. (only whole numbers 1KG, 2KG etc, not like 2.3KG) """ I thought it would really be good to solve it by python, and right now on the mid-way solving using very dirty approach. But I feel, using SETs with python in such would solve it better. Can anyone come with good solution, and maybe solution showing usage of Sets. -- -=Ravi=- -------------- next part -------------- An HTML attachment was scrubbed... URL: From HDoran at air.org Mon Mar 31 15:03:41 2008 From: HDoran at air.org (Doran, Harold) Date: Mon, 31 Mar 2008 15:03:41 -0400 Subject: Elementtree to parse xml Message-ID: <2323A6D37908A847A7C32F1E3662C80E017BDCA3@dc1ex01.air.org> I received some help on list with sample code on how to parse through an xml file using element tree. I now have this working using toy examples nicely. However, when I work to apply this to my actual xml file, I am hitting a roadblock. Is anyone on the list able to look at an xml file that I can send as well as my python code to offer suggestions? I would normally insert a minimal, commented example inside this email. But the xml file is a bit too big to put in this email. I am *very* close to having this resolved, but just need a nudge in the right direction. Thanks, Harold -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.laloux at gmail.com Fri Mar 28 08:10:56 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Fri, 28 Mar 2008 05:10:56 -0700 (PDT) Subject: chronic error with python on mac os/x 10.5 References: Message-ID: <2387e4a2-b9c1-4070-9416-27ee21cea2ec@e10g2000prf.googlegroups.com> I don't known pjsip but this problem generally occurs when the library (dylib) on which the file (.so) depends is not the good one > Googling this issue show that it is happening to many > libraries in python on mac. ?????? I am working in python on mac since a lot of time I seldom have such problems. When you compile a .so file, it depends on a dylib library and you must have the good one (version) From upton at virginia.edu Wed Mar 5 10:42:51 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 5 Mar 2008 10:42:51 -0500 Subject: OT: Failed saving throw In-Reply-To: References: Message-ID: <5504f9ac0803050742m351608f8h55851f7f234e4f63@mail.gmail.com> On 5 Mar 2008 07:36:37 -0800, Aahz wrote: > For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people > think we should build a tomb in his honor. ;-) Yeah, I just saw a tribute on Order of the Stick: http://www.giantitp.com/comics/oots0536.html From exarkun at divmod.com Wed Mar 12 16:02:54 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 12 Mar 2008 15:02:54 -0500 Subject: Does __import__ require a module to have a .py suffix? In-Reply-To: <05559d08-2479-4178-830c-adf65dfc733c@s37g2000prg.googlegroups.com> Message-ID: <20080312200254.6859.696992993.divmod.quotient.18440@ohm> On Wed, 12 Mar 2008 12:58:33 -0700 (PDT), George Sakkis wrote: >On Mar 12, 12:22 pm, mrstephengross wrote: > >> Hi all. I've got a python file called 'foo' (no extension). I want to >> be able to load it as a module, like so: >> >> m = __import__('foo') >> >> However, the interpreter tells me "No module named foo". If I rename >> it foo.py, I can indeed import it. Is the extension required? Is there >> any way to override that requirement? > >You can use execfile: > >foo = {} >execfile('foo', foo) > >Apart from the different syntax in accessing the module globals >(attributes with __import__ (foo.x) vs dict entries with execfile >(foo['x'])), there are probably more subtle differences but I can't >tell for sure. It would be nice if someone more knowledgeable can >compare and contrast these two appraches. Another difference is that when you import a module, its code is (usually) only executed once. Each import after the first just returns a reference to the already-created module object. When you use execfile, the code is re-evaluated each time. Jean-Paul From mark.e.tolonen at mailinator.com Tue Mar 4 02:15:59 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Mon, 3 Mar 2008 23:15:59 -0800 Subject: Command line arguments in Windows References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: "Mike Walker" wrote in message news:r76zj.40666$pM4.38793 at pd7urf1no... > >> If you run a python file, ie. just double clicking it the only >> argument you will have will be the filename of the script. If you >> create a shortcut to the script and in the target box add your >> arguments (if you have quotation marks place them after not inside) >> you will see your arguments. fwiw you answered yourself in the third >> paragraph. > > As I mentioned I am working from the command line, not clicking on the > icon. The only difference between it working and not is the python prefix, > which is why I was thinking this is some sort of file association problem. > > I probably wasn't as clear as I could have been in the third paragraph. > > argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] > python argtest.py arg1 arg2 arg3 - Works >From the command line, the 'ftype' and 'assoc' commands can be used view how an extension is handled: C:\>assoc .py .py=Python.File C:\>ftype Python.File Python.File="C:\Python25\python.exe" "%1" %* My guess is your command line looks something like this: Python.File="C:\Python25\python.exe" "%1" The script name is being passed, but not the rest of the arguments. I vaguely remember seeing this on an older version one of ActiveState's ActivePython installers. What version of Python are you running? --Mark From bbxx789_05ss at yahoo.com Mon Mar 10 23:51:44 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 10 Mar 2008 20:51:44 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <7cbb3d22-b69c-479b-bc9d-10d1ef9e86c9@b1g2000hsg.googlegroups.com> On Mar 10, 9:44?pm, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. > primes = [] > import math > import gmpy > while 1: > ? ? run = int(raw_input("Do you want to calculate primes? 1 = yes and > 2 = no. ")) > ? ? if run == 1: > ? ? ? ? y = int(raw_input("What number do you want to use as the final > number to calculate with? ")) > ? ? ? ? x = int(raw_input("What number do you want to start > calculating primes from? ")) > ? ? ? ? while x < 2: > ? ? ? ? ? ? print "Number must be at least 2 for math reasons." > ? ? ? ? else: > ? ? ? ? ? ? while x < y: > ? ? ? ? ? ? ? ? prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) > ? ? ? ? ? ? ? ? if prime < 0: > ? ? ? ? ? ? ? ? ? ? primes.append(x) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print x " is not prime. " # highlights the final " > here > ? ? ? ? ? ? ? ? x = x + 1 > ? ? ? ? ? ? print primes > ? ? elif run == 2: > ? ? ? ? break > ? ? else: > ? ? ? ? print "Sorry, not a choice. Please enter your choice again." > print "Goodbye." > > How do I fix such an invalid syntax? > > TIA, > Nathan Pinno Try running this: input = raw_input("Hello world.") From http Thu Mar 27 08:35:33 2008 From: http (Paul Rubin) Date: 27 Mar 2008 05:35:33 -0700 Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> Message-ID: <7xlk4473ai.fsf@ruckus.brouhaha.com> king kikapu writes: > it seems that Psyco's author will not port it for the upcoming Python > 3000 release :( I think the idea is it will be part of PyPy and you should use that. From rockxuan at gmail.com Tue Mar 18 03:58:29 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:58:29 -0700 (PDT) Subject: Hublot Swiss watch in www.51cntrade.com Message-ID: <25eb5778-c1c9-4f74-9931-c9ba7a224285@i12g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From ilochab at yahoo.it Wed Mar 12 08:00:52 2008 From: ilochab at yahoo.it (ilochab) Date: Wed, 12 Mar 2008 12:00:52 GMT Subject: Is it possible to reload a module from a different file? Message-ID: I mean ... The main module makes this import: import moduleX later other modules make different import to an other module named moduleX like this: from pack.subdir import moduleX What I want is that the second import of moduleX in some way must be redirected onto the first one. Is there any way to do so? Would there be any way to do so (moduleX overrides pack.subdir.moduleX) if they were imported on reverse order? Any time I discover that Python can do amazing things, but perhaps this one is just a silly one, isn't it? ciao Licia From anh.hai.trinh at gmail.com Sat Mar 8 21:50:30 2008 From: anh.hai.trinh at gmail.com (Chick) Date: Sat, 8 Mar 2008 18:50:30 -0800 (PST) Subject: securely getting the user's password Message-ID: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> Hello, I'm writing a security tool which requies wiping off the memory of certain string after being used, which I've done by implementing it as a mutable list as follow: class secureStr: def __init__(self, str): self.__s = [] for i in range(len(str)): self.s += str[i] def __str__(self): return "".join(self.__s) def wipe(self): for i in range(len(self.__s)): self.s[i] = '\x00' def __del__(self): self.wipe() My question is how do I write a function to securely get the password from user (in text mode)? If I do sth like import getpass securePass = secureStr(getpass,getpass()) doesn't that create an immediate string object that will stay in memory? From bj_666 at gmx.net Sat Mar 22 17:21:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Mar 2008 21:21:39 GMT Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: <64lbj3F2an71mU3@mid.uni-berlin.de> On Sat, 22 Mar 2008 13:27:49 -0700, sgharvey wrote: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: > If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. > If I try to match every pattern to one line at a time, only one > pattern will match. > > What am I not understanding about re.search? That has nothing to do with `re.search` but how files work. A file has a "current position marker" that is advanced at each iteration to the next line in the file. When it is at the end, it stays there, so you can just iterate *once* over an open file unless you rewind it with the `seek()` method. That only works on "seekable" files and it's not a good idea anyway because usually the files and the overhead of reading is greater than the time to iterate over in memory data like the patterns. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Wed Mar 19 15:25:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 16:25:14 -0300 Subject: automatically doing some cleaning-up by the process when the systems shuts down References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> <2613171a0803190028s4cc626apd2cd675a18e25799@mail.gmail.com> Message-ID: En Wed, 19 Mar 2008 04:28:19 -0300, bharath venkatesh escribi?: > handling SIGTERM allowed me to do cleaning up while the system shuts > down > but as i mentioned previously how can my process know if the system > was > not shut down properly previously Sorry about the confusion, I meant SIGTERM instead of SYSTERM. Create a file with a known fixed name when the daemon starts, and remove it after a clean shutdown (you may want to write the daemon's PID). If the file already exists the next time it starts, that means that a clean shutdown was not performed. (Note that this, and the previous question, are not specific to Python) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 22:39:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 02:39:06 -0000 Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> <13udtk586ijktec@corp.supernews.com> Message-ID: <13ue52ajkauekc5@corp.supernews.com> On Sun, 23 Mar 2008 18:56:51 -0700, John Machin wrote: >> Python knows the truth value of built-in types like dicts without >> actually converting them to bools, or for that matter calling __len__ >> or __nonzero__ on them. > > What the 2.5.1 interpreter does is call PyObject_IsTrue, which checks to > see if the built_in or extension type is a mapping (not just a dict) > with a length method and if so calls it; similarly for sequences: > > else if (v->ob_type->tp_as_mapping != NULL && > v->ob_type->tp_as_mapping->mp_length != NULL) > res = (*v->ob_type->tp_as_mapping->mp_length)(v); > else if (v->ob_type->tp_as_sequence != NULL && > v->ob_type->tp_as_sequence->sq_length != NULL) > res = (*v->ob_type->tp_as_sequence->sq_length)(v); > > Was that what you meant by "without ... calling __len__"? What I meant was that the interpreter *didn't* do was lookup the name '__len__' via the normal method resolution procedure. There's no need to search the dict's __dict__ attribute looking for an attribute named __len__, or indeed any sort of search at all. It's a direct pointer lookup to get to mp_length. I didn't mean to imply that Python magically knew whether a dict was empty without actually checking to see if it were empty. Apologies for being less than clear. Also, since I frequently criticize others for confusing implementation details with Python the language, I should criticize myself as well. What I described is specific to the CPython implementation -- there's no requirement for other Python versions to do the same thing. -- Steven From ebenze at hotmail.com Fri Mar 14 17:19:40 2008 From: ebenze at hotmail.com (Eric B.) Date: Fri, 14 Mar 2008 17:19:40 -0400 Subject: Installing Python2.4 on RHEL4? References: Message-ID: "Jarek Zgoda" wrote in message news:freov4$n9f$2 at nemesis.news.neostrada.pl... > Eric B. pisze: > >> I appologize if this is slightly OT, but I am really struggling to figure >> out how to install Python2.4 on RHEL4. To make matters worse, the RHEL4 >> machine is a 64bit architecture. >> >> I search pyvault, but they only have for .i386. Does anyone know where / >> how I can find Python2.4 for RHEL4 x64? > > If you would not find a binary Python 2.4 package, you can always build > your own and package it. Why not? Because I don't have a development x64 environment to build it. :( Only a production server with no compilation tools on it. Hence my need to ideally find a binary x64 distribution of it. Unless someone knows of a way to build a 64bit distribution from within a 32bit system? Thanks, Eric From http Thu Mar 20 03:07:00 2008 From: http (Paul Rubin) Date: 20 Mar 2008 00:07:00 -0700 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> <7xk5jz1a80.fsf@ruckus.brouhaha.com> Message-ID: <7x4pb16fhn.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > I thought os.walk was for locally mounted directories... How is it > relevant on remote filesystems? Yes, os.walk is for local directories. I thought you wanted to push a local tree to a remote host. For pulling, yes, you need to do something different; for example, rsync can handle it for you. > Don't shoot the messenger, but you're severely confused here. Whether > you're using ftp, rcp, or rsync is a completely separate issue to > whether you're running over ssl (which I assume you meant by ssh). SSL would make more sense but ssh is more commonly used. > FTP is a work-horse protocol for transferring files. It's going to be > with us for a long, long time. Here's what happened when I just tried to use it: $ ftp localhost ftp: connect: Connection refused ftp> That is quite common these days. I think ftp doesn't play nicely with encryption tunnels because of the way it uses a separate port for out of band signalling, but I never paid close attention, so maybe there's some other issue with it. I can't think of when the last time was that I actually used ftp. > The point of rsync is to keep a local directory tree in sync with a > remote one, by transferring only change-sets that are conceptually > similar to patches. If you're only transferring files once, there's > no particular benefit (AFAIK) to using rsync rather than some kind of > recursive ftp. One benefit is that it handles the recursion for you by itself. Another is that in modern unix environments it's more likely to work at all (i.e. if there is no ftp server at the target machine). From grante at visi.com Sun Mar 9 00:36:16 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:36:16 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <13t6tqgh29oks9e@corp.supernews.com> On 2008-03-09, Dan Bishop wrote: > On Mar 8, 1:31 pm, Grant Edwards wrote: > ... >> >> What I really can't stand are the pointy-haired comment blocks >> at the beginnings of C/C++ functions that do things like tell >> you the name and return type of the function and list the names >> and types of the parameters. Gee, thanks. I never could have >> figured that out from looking at the source code itself. IMO, >> comments explaining what the parameters are used for usually >> indicates that the parameter names were poorly chosen. > > You must work for the same company I do. I've seen a whole bunch of > comments that look like: > > //--------------------------------------------------------------------------- > // CXyzBase::LogMessage > // > // Write a message to the log. > // > // Args: > // strMsg = the message to log > // > void CXyzBase::LogMessage(const CString& strMsg) > { > // > } > > And even worse, at the top of that file: > > //--------------------------------------------------------------------------- > // XyzBase.cpp > // > // This file contains the implementation of class CXyzBase. > // > // Copyright (C) 2008 Foobar Computer Consulting > // > // VERSION PROJECT# DATE DESCRIPTION > // ------- -------- -------- ------------------ > // 1.00 123456 01/04/08 Original creation. > // > > Eleven lines, of which the only useful information to me was the > project number, as knowing this let me look up who was behind these > comments. :) I'm currently consulting part-time for a company that's very fond of that sort of thing. And it's it's not like they're working on some DoD contract that explicitly requires such time-wastage -- it's something they torture themselves with of their own volition. [I honestly didn't expect my rant to spark such a long thread.] -- Grant Edwards grante Yow! I will invent "TIDY at BOWL"... visi.com From ffm.stefan at googlemail.com Sat Mar 8 08:25:46 2008 From: ffm.stefan at googlemail.com (Stefan Wagner) Date: Sat, 8 Mar 2008 14:25:46 +0100 Subject: Writing Memory to File Message-ID: Hi, I'm trying to do some memory analyzing stuff, i wrote me a small .c so far to dump the memory to a file for later analysis, the analyzing part itself is python code. I wonder if any of you has an idea how to dump the whole memory in Linux/Windows from python ? Using the .c for this somehow doesn't look right and comfy ;-) Regards, Stefan From grante at visi.com Tue Mar 4 12:35:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 04 Mar 2008 17:35:14 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> Message-ID: <13sr22ii98uipc4@corp.supernews.com> On 2008-03-04, blaine wrote: >> Try using the appropriate constant from /usr/include/... (for >> the target platform, of course). >> >> -- >> Grant Edwards grante Yow! Please come home with >> at me ... I have Tylenol!! >> visi.com > Thank you for your response. I can't seem to find what you're > referencing in /usr/include. I found termios.h - but it does not > define any constants (I can include it if you wish). $ grep -r B921600 /usr/include /usr/include/asm/termbits.h:#define B921600 0010007 /usr/include/bits/termios.h:#define B921600 0010007 > I could recompile python, I imagine, with additional constants but > this wouldn't be ideal - although it is a possible solution. termios.c in Python definitely needs to be updated. > the only reference to a baud rate in termios.h is here: It's in a file that's included in termios.h. See above. -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.com my urine sample bottles ... From whoshaq at aol.com Thu Mar 6 13:48:15 2008 From: whoshaq at aol.com (Whoshaq) Date: Thu, 6 Mar 2008 10:48:15 -0800 (PST) Subject: HURRICANE ANDREW 1992 Rare & Raw Footage Message-ID: HURRICANE ANDREW 1992 Rare & Raw Footage Parts 1 thru 7: http://www.youtube.com/watch?v=zKGMQFWWJ0g From hdante at gmail.com Sun Mar 30 01:11:33 2008 From: hdante at gmail.com (hdante) Date: Sat, 29 Mar 2008 22:11:33 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> On Mar 29, 7:55 am, kwitt... at telenet.be wrote: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? > > I've written an article about it to try and save this nice "is not > equal" operator, located athttp://dewitters.koonsolo.com/python_neq.html > > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). I don't know, but we should have only one operator. BTW, my opinion is that it's already time that programmer editors have input methods advanced enough for generating this: if x ? 0: ?y ? s: if y ? 0: f1(y) else: f2(y) ;-) From gagsl-py2 at yahoo.com.ar Sun Mar 9 17:11:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 19:11:16 -0200 Subject: parralel downloads References: <47D2C331.4020708@islandtraining.com> Message-ID: En Sat, 08 Mar 2008 14:47:45 -0200, Gary Herron escribi?: > poof65 wrote: >> For your problem you have to use threads. >> > Not at all true. Thread provide one way to solve this, but another is > the select function. For this simple case, select() may (or may not) be > easier to write. Pseudo-code would look something like this: > > openSockets = list of sockets one per download file: > while openSockets: > readySockets = select(openSockets ...) # Identifies sockets with > data to be read > for each s in readSockets: > read from s and do whatever with the data > if s is at EOF: close and remove s from openSockets > > That's it. Far easier than threads. Easier? If you omit all the relevant details, yes, looks easy. For example, you read some data from one socket, part of the file you're downloading. Where do you write it? You require additional structures to keep track of things. Pseudocode for the threaded version, complete with socket creation: def downloadfile(url, fn): s = create socket for url f = open filename for writing shutil.copyfileobj(s.makefile(), f) for each url, filename to retrieve: t = threading.Thread(target=downloadfile, args=(url,filename)) add t to threadlist t.start() for each t in threadlist: t.join() The downloadfile function looks simpler to me - it's what anyone would write in a single threaded program, with local variables and keeping full state. The above pseudocode can be converted directly into Python code - no more structures nor code are required. Of course, don't try to download a million files at the same time - neither a million sockets nor a million threads would work. -- Gabriel Genellina From __peter__ at web.de Sun Mar 30 09:03:21 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 30 Mar 2008 15:03:21 +0200 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > >> Second try: > ... >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with >> each call. But it's the only way I could find, at least without changing >> the code template used by timeit. > > Eeek. Talk about namespace pollution. > > Thanks for the effort, but if that's the only solution, I think the > solution is worse than the problem! > > Perhaps it's time for me to take a different approach. [snip] Maybe the following enhancement of timeit would be worthwhile? $ cat timeanyfunc.py from mytimeit import Timer def functionA(): print "Function A" def functionB(): print "Function B" T1 = Timer("f()", ns=dict(f=functionA)) T2 = Timer("f()", ns=dict(f=functionB)) T1.repeat(3, 1) T2.repeat(3, 1) $ python timeanyfunc.py Function A Function A Function A Function B Function B Function B $ diff -u /usr/lib/python2.5/timeit.py mytimeit.py --- /usr/lib/python2.5/timeit.py 2008-03-07 05:35:55.000000000 +0100 +++ mytimeit.py 2008-03-30 14:40:58.000000000 +0200 @@ -77,7 +77,7 @@ # in Timer.__init__() depend on setup being indented 4 spaces and stmt # being indented 8 spaces. template = """ -def inner(_it, _timer): +def inner(_it, _timer, %(inject)s): %(setup)s _t0 = _timer() for _i in _it: @@ -106,15 +106,16 @@ multi-line string literals. """ - def __init__(self, stmt="pass", setup="pass", timer=default_timer): + def __init__(self, stmt="pass", setup="pass", timer=default_timer, ns=None): """Constructor. See class doc string.""" + if ns is None: + ns = {} self.timer = timer stmt = reindent(stmt, 8) setup = reindent(setup, 4) - src = template % {'stmt': stmt, 'setup': setup} + src = template % {'stmt': stmt, 'setup': setup, 'inject': ','.join("%s=%s" % (s, s) for s in ns)} self.src = src # Save for traceback display code = compile(src, dummy_src_name, "exec") - ns = {} exec code in globals(), ns self.inner = ns["inner"] By the way, haven't we been there before, two years ago? http://mail.python.org/pipermail/python-list/2006-February/368341.html Peter From duncan.booth at invalid.invalid Mon Mar 17 14:00:10 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 18:00:10 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> <47de9f6c$0$2657$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: > >> For the answer I actually want each asterisk substitutes for exactly one >> character. > > Played around a bit and found that one: > > Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) > [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = 1 >>>> b = 1//1 >>>> if a is b: print('yes!') > ... >>>> b > 1 >>>> type(b) > "the whole point of setting the puzzle was that I expected it to be ripped to shreds", thanks for supporting my expectations. From Robert.Bossy at jouy.inra.fr Mon Mar 10 10:28:37 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 10 Mar 2008 15:28:37 +0100 Subject: parsing directory for certain filetypes In-Reply-To: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <47D54595.2030607@jouy.inra.fr> royG wrote: > hi > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? > > here it is... > > from string import split > from os.path import isdir,join,normpath > from os import listdir > > def parsefolder(dirname): > filenms=[] > folder=dirname > isadr=isdir(folder) > if (isadr): > dirlist=listdir(folder) > filenm="" > This las line is unnecessary: variable scope rules in python are a bit different from what we're used to. You're not required to declare/initialize a variable, you're only required to assign a value before it is referenced. > for x in dirlist: > filenm=x > if(filenm.endswith(("txt","doc"))): > nmparts=[] > nmparts=split(filenm,'.' ) > if((nmparts[1]=='txt') or (nmparts[1]=='doc')): > I don't get it. You've already checked that filenm ends with "txt" or "doc"... What is the purpose of these three lines? Btw, again, nmparts=[] is unnecessary. > filenms.append(filenm) > filenms.sort() > filenameslist=[] > Unnecessary initialization. > filenameslist=[normpath(join(folder,y)) for y in filenms] > numifiles=len(filenameslist) > numifiles is not used so I guess this line is too much. > print filenameslist > return filenameslist > Personally, I'd use glob.glob: import os.path import glob def parsefolder(folder): path = os.path.normpath(os.path.join(folder, '*.py')) lst = [ fn for fn in glob.glob(path) ] lst.sort() return lst I leave you the exercice to add .doc files. But I must say (whoever's listening) that I was a bit disappointed that glob('*.{txt,doc}') didn't work. Cheers, RB From andrei.avk at gmail.com Wed Mar 12 21:18:37 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Wed, 12 Mar 2008 18:18:37 -0700 (PDT) Subject: escape string to store in a database? Message-ID: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> Hi, I'd like to store chunks of text, some of them may be very large, in a database, and have them searchable using 'LIKE %something%' construct. These pieces of text may have single and double quotes in them, I tried escaping them using re module and string module and either I did something wrong, or they escape either single quotes or double quotes, not both of these. So that when I insert that text into a db record, this causes an error from the database. What's the accepted way of dealing with this? I have a workaround currently where I encode the string with b64, and then unencode it when searching for a string, but that's a dumb way to do this. For my app, searching quickly is not very crucial, but would be nice to have.. thanks, -ak From castironpi at gmail.com Tue Mar 25 14:59:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 11:59:58 -0700 (PDT) Subject: any good g.a.'s? References: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Message-ID: <6b5385ad-0756-4c22-92fe-ab8214d00262@e67g2000hsa.googlegroups.com> On Mar 25, 11:03?am, Tim Chase wrote: > > Any good genetic algorithms involving you-split, i-pick? > > I've always heard it as "you divide, I decide"... > > That said, I'm not sure how that applies in a GA world. ?It's > been a while since I've done any coding with GAs, but I don't > recall any facets related to the You Divide, I Decide problem. > It sounds like a simple optimization of "equality", which would > be a normal use of a GA. ?This would apply for both the division > and the decision, depending on which side the GA is (the "you" or > the "I") or two diff. GAs can be on either side of the process. > > -tkc There's an iterated solution (no link) for more than two players. Say two GAs encounter the same resource (or if some is left after they've begun consuming)-- i.e., encounter each other, a strict survival-of- fittest can arise among a population, even leading to specialization and organ. I'm not sure if time factors in however, i.e. whether GAs are useful in spacetime; bacteria Firmicute produce spores to guard during stress. What do ideal structures have in common with real ones?; and if so, does you-split-i-pick yield anything useful in ideality? What are ideal bacteria, what do they want, and are they interesting? From hdante at gmail.com Sun Mar 30 08:25:50 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 05:25:50 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> <659f2cF2dq5riU1@mid.uni-berlin.de> Message-ID: On Mar 30, 9:23 am, "Diez B. Roggisch" wrote: > hdante schrieb: > > > > > On Mar 30, 4:31 am, John Machin wrote: > >> On Mar 30, 3:58 pm, hdante wrote: > > >>> On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" > >>> wrote: > >>>> Hello, > >>>> I am having trouble writing the code to read a binary string. I would > >>>> like to extract the values for use in a calculation. > >>>> Any help would be great. > >>> I'm too lazy to debug your binary string, but I suggest that you > >>> completely throw away the binary file and restart with a database or > >>> structured text. See, for example: > >>> http://pyyaml.org/wiki/PyYAML > >>> If you have some legacy binary file that you need to process, try > >>> creating a C program that freads the binary file and printfs a text > >>> equivalent. > >> ... and that couldn't be done faster and better in Python?? > > > No. A C struct is done faster and better than python (thus, the > > correctness check is faster in C). Also, chances are high that there's > > already an include file with the binary structure. > > That is utter nonsense. There is no "correctness check" in C. and using > printf & thus creating strings that you then need to parse in python > just doubles the effort needlessly. > > The standard-lib module "struct" is exactly what you need, nothing else. > it sure is faster than any parsing of preprocessed data, doesn't > introduce a language-mixture and is prototyped/tested much faster > because of it being python - and not C-compiler and C-debugger. > > Alternatively, *IF* there were C-structure-declarations available for > the binary format, the usage of ctypes would allow for roughly the same, > even reducing the effort to create the structure definition a great deal. > > Diez Whatever you say. From sturlamolden at yahoo.no Wed Mar 19 16:29:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 13:29:10 -0700 (PDT) Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> Message-ID: <6b4a290a-447e-44a4-aced-e104e52f72f1@i12g2000prf.googlegroups.com> On 19 Mar, 09:44, Torsten Bronger wrote: > Could you elaborate on this? (Sincere question; I have almost no > idea of Haskell.) If you already know Python, you will find Whitespace just as useful as Haskell. From ptmcg at austin.rr.com Sun Mar 23 03:26:36 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 23 Mar 2008 00:26:36 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> Message-ID: <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> There are a couple of bugs in our program so far. First of all, our grammar isn't parsing the METAL2 entry at all. We should change this line: md = mainDict.parseString(test1) to md = (mainDict+stringEnd).parseString(test1) The parser is reading as far as it can, but then stopping once successful parsing is no longer possible. Since there is at least one valid entry matching the OneOrMore expression, then parseString raises no errors. By adding "+stringEnd" to our expression to be parsed, we are saying "once parsing is finished, we should be at the end of the input string". By making this change, we now get this parse exception: pyparsing.ParseException: Expected stringEnd (at char 1948), (line:54, col:1) So what is the matter with the METAL2 entries? After using brute force "divide and conquer" (I deleted half of the entries and got a successful parse, then restored half of the entries I removed, until I added back the entry that caused the parse to fail), I found these lines in the input: fatTblThreshold = (0,0.39,10.005) fatTblParallelLength = (0,1,0) Both of these violate the atflist definition, because they contain integers, not just floatnums. So we need to expand the definition of aftlist: floatnum = Combine(Word(nums) + "." + Word(nums) + Optional('e'+oneOf("+ -")+Word(nums))) floatnum.setParseAction(lambda t:float(t[0])) integer = Word(nums).setParseAction(lambda t:int(t[0])) atflist = Suppress("(") + delimitedList(floatnum|integer) + \ Suppress(")") Then we need to tackle the issue of adding nesting for those entries that have sub-keys. This is actually kind of tricky for your data example, because nesting within Dict expects input data to be nested. That is, nesting Dict's is normally done with data that is input like: main Technology Layer PRBOUNDARY METAL2 Tile unit But your data is structured slightly differently: main Technology Layer PRBOUNDARY Layer METAL2 Tile unit Because Layer is repeated, the second entry creates a new node named "Layer" at the second level, and the first "Layer" entry is lost. To fix this, we need to combine Layer and the layer id into a composite- type of key. I did this by using Group, and adding the Optional alias (which I see now is a poor name, "layerId" would be better) as a second element of the key: mainDict = dictOf( Group(Word(alphas)+Optional(quotedString)), Suppress("{") + attrDict + Suppress("}") ) But now if we parse the input with this mainDict, we see that the keys are no longer nice simple strings, but they are 1- or 2-element ParseResults objects. Here is what I get from the command "print md.keys()": [(['Technology'], {}), (['Tile', 'unit'], {}), (['Layer', 'PRBOUNDARY'], {}), (['Layer', 'METAL2'], {})] So to finally clear this up, we need one more parse action, attached to the mainDict expression, that rearranges the subdicts using the elements in the keys. The parse action looks like this, and it will process the overall parse results for the entire data structure: def rearrangeSubDicts(toks): # iterate over all key-value pairs in the dict for key,value in toks.items(): # key is of the form ['name'] or ['name', 'name2'] # and the value is the attrDict # if key has just one element, use it to define # a simple string key if len(key)==1: toks[key[0]] = value else: # if the key has two elements, create a # subnode with the first element if key[0] not in toks: toks[key[0]] = ParseResults([]) # add an entry for the second key element toks[key[0]][key[1]] = value # now delete the original key that is the form # ['name'] or ['name', 'name2'] del toks[key] It looks a bit messy, but the point is to modify the tokens in place, by rearranging the attrdicts to nodes with simple string keys, instead of keys nested in structures. Lastly, we attach the parse action in the usual way: mainDict.setParseAction(rearrangeSubDicts) Now you can access the fields of the different layers as: print md.Layer.METAL2.lineStyle I guess this all looks pretty convoluted. You might be better off just doing your own Group'ing, and then navigating the nested lists to build your own dict or other data structure. -- Paul From sjmachin at lexicon.net Fri Mar 28 23:30:45 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Mar 2008 20:30:45 -0700 (PDT) Subject: some path issues on windows References: Message-ID: On Mar 29, 1:31 pm, Brad wrote: > When reading a file into a list that contains windows file paths like this: > > c:\documents and settings\brad\desktop\added_software\asus\a.txt Do you mean "reading a file into a list that AS A RESULT contains ..."? If not, what do you mean? > > I get a list that contains paths that look like this: > > c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt > > So, my list contains those funky file paths. Only if your file already contains contains the doubled backslashes. > And, when I do this: > > for root, dirs, files in os.walk('C:\\'): > for f in files: > print os.path.join(root,f) > > I get the more normal path again: > > c:\documents and settings\brad\desktop\added_software\asus\a.txt > > This makes path comparison difficult as I have different strings (the > extra \'s). I've tried os.path.normpath(line_reading_in_from_file) but I > still get the funky \\ paths. How can I read the paths with an r'path' > like meaning? File reading operations *don't* magically double backslashes. Believe me. Show us the code that is reading the file. Show us the contents of the file. Assure us that you understand what is going on here: >>> alist = ['a\\b', r'a\b'] >>> alist[0] == alist[1] True >>> print alist ['a\\b', 'a\\b'] # So if you see doubled backslashes when you do print alist, # there are really only single backslashes. >>> print alist[0], alist[1] a\b a\b >>> print repr(alist[0]), repr(alist[1]) 'a\\b' 'a\\b' HTH, John From malkarouri at gmail.com Sat Mar 8 11:01:16 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 08:01:16 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: On Mar 8, 3:20?pm, Roel Schroeven wrote: > malkarouri schreef: > > > > > Hi everyone, > > > I have an algorithm in which I need to use a loop over a queue on > > which I push values within the loop, sort of: > > > while not(q.empty()): > > ? ? x = q.get() > > ? ? #process x to get zero or more y's > > ? ? #for each y: > > ? ? q.put(y) > > > The easiest thing I can do is use a list as a queue and a normal for > > loop: > > > q = [a, b, c] > > > for x in q: > > ? ? #process x to get zero or more y's > > ? ? q.append(y) > > > It makes me feel kind of uncomfortable, though it seems to work. The > > question is: is it guaranteed to work, or does Python expect that you > > wouldn't change the list in the loop? > > Changing a loop while iterating over it is to be avoided, if possible. > In any case, a deque is more efficient for this kind of use. I'd use it > like this: > > from collections import deque > > q = deque([a, b, c]) > while q: > ? ? ?x = q.popleft() > ? ? ?# ... > ? ? ?q.append(y) > > -- > The saddest aspect of life right now is that science gathers knowledge > faster than society gathers wisdom. > ? ?-- Isaac Asimov > > Roel Schroeven Thanks for your response. My same feeling, avoid loop variable, but no explicit reason. Thanks for reminding me of the deque, which I never used before. Alas, in terms of efficiency - which I need - I don't really need to pop the value on the list/deque. This additional step takes time enough to slow the loop a lot. So its not ideal here. Still, why avoid changing loop variable? Does python treat looping over a list differently from looping over an iterator, where it doesn't know if the iterator future changes while loop running? Regards, Muhammad Alkarouri From jeff at schwabcenter.com Thu Mar 20 12:59:50 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 09:59:50 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: Paulo da Costa wrote: > People who say Emacs often mean GNU Emacs. That's funny; to me, Emacs usually means XEmacs. :) From tarundevnani at gmail.com Tue Mar 25 07:55:12 2008 From: tarundevnani at gmail.com (tarun) Date: Tue, 25 Mar 2008 17:25:12 +0530 Subject: Issues with Python + Batch File Message-ID: Hi All, I've a batch file which invoks a python file. The python code in the file brings up a GUI. The GUI is of a test tool which can execute scripts. I tried using the following 2 sample of code for my batch file: * (1) (2)* D:\opengui.py D:\opengui.py goto:end goto:end :end :end EXIT TASKKILL /IM C:\WINDOWS\system32\cmd.exe Double clicking on the batch file brings up a DOS BOX which opens up the GUI. On Closing the GUI, the DOS BOX both get closed. But if I close the GUI when a test is under execution, the GUI gets closed but the DOS BOX still remains open. I want to some how close the DOS BOX when the GUI is closed. Thanks & Regards, Tarun tarundevnani at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidj411 at gmail.com Wed Mar 5 14:16:31 2008 From: davidj411 at gmail.com (davidj411) Date: Wed, 5 Mar 2008 11:16:31 -0800 (PST) Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: Python 3.0 might end up better, but converting all those scripts will be a chore. I'd be curious to know how that will be done. From skunkwerk at gmail.com Wed Mar 26 09:46:52 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Wed, 26 Mar 2008 06:46:52 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> Message-ID: On Mar 26, 6:44?am, skunkwerk wrote: > On Mar 25, 11:04?pm, "Gabriel Genellina" > wrote: > > > > > En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk ? > > escribi?: > > > > On Mar 25, 9:25?pm, "Gabriel Genellina" > > > wrote: > > >> En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? > > >> escribi?: > > > >> >> ? ?i'm trying to call subprocess.popen on the 'rename' function in > > >> >> linux. ?When I run the command from the shell, like so: > > > >> >> rename -vn 's/\.htm$/\.html/' *.htm > > > >> >> it works fine... however when I try to do it in python like so: > > >> >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > > >> >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > > >> >> print p.communicate()[0] > > > >> >> nothing gets printed out (even for p.communicate()[1]) > > > >> I'd try with: > > > >> p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > > >> ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, > > >> ? ? ? ?shell=True) > > > >> (note that I added shell=True and I'm using a raw string to specify the ? > > >> reg.expr.) > > > > Thanks Gabriel, > > > ? ?I tried the new command and one with the raw string and single > > > quotes, but it is still giving me the same results (no output). ?any > > > other suggestions? > > > My next try would be without the single quotes... > > > -- > > Gabriel Genellina > > thanks for the input guys, > ? I've tried the suggestions but can't get it to work. ?I have a file > named test.htm in my directory, and when I run the following command: > > rename -vn 's/(.*)\.htm$/model.html/' *.htm > > from the shell in that directory I get the following output: > test.htm renamed as model.html > > now my python script is called test.py, is located in the same > directory, and is called from the shell with 'python test.py' > the contents of test.py: > import subprocess > > p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ > model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > print p.communicate()[0] > > i change to print p.communicate()[1] in case the output is blank the > first time > > this is the output: > *.htm renamed as model.html > > when I add shell=True to the subprocess command, I get the following > output: > Usage: rename [-v] [-n] [-f] perlexpr [filenames] > > am i doing something wrong? in addition, when I use Popen without any quotes, or without quotes for the regular expression, I get an exception. I'm running ubuntu linux 7.10 with python 2.5.1 thanks From michael.wieher at gmail.com Fri Mar 14 10:15:07 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 14 Mar 2008 09:15:07 -0500 Subject: find string in file In-Reply-To: References: Message-ID: 2008/3/14, fminervino at gmail.com : > > Hi friends !! > > I'm neophite about python, my target is to create a programa that > find a specific string in text file. > How can do it? > > Thanks > fel > > -- > http://mail.python.org/mailman/listinfo/python-list > If your only goal is to find a string in a file, just use grep >grep -i 'string' filename its a standard linux command =) But if you must use python data=file(filename,'r').read() if string in data: return True return False -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Mar 19 13:15:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 14:15:14 -0300 Subject: Using threads in python is safe ? References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> Message-ID: En Wed, 19 Mar 2008 04:43:34 -0300, Deepak Rokade escribi?: > Thanks all for removing confusion about GIL, > one more question; > If jobs to be processed by threds is I/O bound would multithreading help > python to improve speed of application ? > Since I read that " multithreading is not a good strategy to improve > speed > of python application." Try and see what happens in your specific case. People keeps saying that but I've never seen conclusive evidence on this topic. Using several threads for I/O bound tasks seems reasonable to me, and is the easiest approach. For CPU bound tasks, multiple threads won't help much, be it Python or another language. I mean, a reasonable number of threads with a reasonable task load. A server handling thousands of simultaneous connections is another beast. -- Gabriel Genellina From pscott at uwc.ac.za Mon Mar 31 03:15:45 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Mon, 31 Mar 2008 09:15:45 +0200 Subject: Beginner advice In-Reply-To: <65bfk7F2esfc1U1@mid.uni-berlin.de> References: <65bfk7F2esfc1U1@mid.uni-berlin.de> Message-ID: <1206947745.6828.35.camel@paul-laptop> On Mon, 2008-03-31 at 06:45 +0000, Marc 'BlackJack' Rintsch wrote: > There is an `xmlrpclib` in the standard library, so there is no need for > an external package here. I even think that pyXMLRPClib is the one that's > integrated in the standard library, so the external one might be "dead". > Ah, yes it is indeed. Thanks. > For Windows there are tools to bundle your source and all dependencies and > even the interpreter itself. `py2exe` is such a tool. With InnoSetup or > NSIS or similar programs you can then make a `setup.exe` for that spoiled > Windows brats. :-) > > Under Linux many packages are available as distribution specific packages > on most distributions. So for Linux you may get away with a README > stating the dependencies of your program and a `setup.py` for installing > your project. Look for `distutils` in the Python documentation for > further information about `setup.py`\s. setup.py sounds like the best way to go. Most of the classrooms and lecture halls run on Ubuntu machines, and as I said, I don't really care much for the Windows brats anyway. 'doze installers etc would be a nice to have, but not needed right now. > > > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? > > Use the one you like best. ;-) > Thought as much. I do 90% of my coding in vi anyways, but am still getting a couple of nutty errors from Python simply because I have not yet gotten the hang of significant whitespace :) Darn that PHP! Thanks for the feedback, now I just need some justification on the GTK/GUI stuff - wxWidgets, GTK+ Glade or other? --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From stef.mientki at gmail.com Thu Mar 13 16:35:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 13 Mar 2008 21:35:42 +0100 Subject: how to pass the workspace ? In-Reply-To: <47D733A7.2070808@islandtraining.com> References: <47D72CDD.9000706@gmail.com> <47D733A7.2070808@islandtraining.com> Message-ID: <47D9901E.5000007@gmail.com> Gary Herron wrote: > Stef Mientki wrote: >> hello, >> >> I've GUI tree with drag and drop nodes, >> where each nodes contains a code snippet. >> Now I want to run one or more branches in that tree, >> so I enumerate over the nodes and have to run something like this: >> >> execfile ( node1 ) >> execfile ( node2 ) >> etc.. >> >> Now how do I pass the workspace created in node1, to node 2, etc ? >> >> thanks, >> Stef Mientki >> > > RTFM! In particular: > http://docs.python.org/lib/built-in-funcs.html#l2h-26 thanks Gary, I read that, but sorry, unfortunately I don't understand it, this is what I tried: tree_globs = {} tree_locals = {} tree_globs [ 'NewVar' ] = 24 filename = self.Get_Editor_Filename (nodename) execfile ( filename, tree_globs, tree_locals ) print dir ( tree_globs) print dir ( tree_locals ) where the code in the executed file is: beer = 'testje' print dir() print dir (globals) print dir (locals) the output I get is: aap ['beer'] ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] The result of globals and locals in the file is eaxctly the same and none of them mentions 'NewVar' and 'beer' The result of tree_globs and tree_locals is exactly the same and both doesn't contain 'NewVar' and 'beer' Maybe it's very simple after reading the manual, but apperently I'm missing the essential clue. What am I missing ? thanks, Stef Mientki From gklein at xs4all.nl Mon Mar 17 07:11:09 2008 From: gklein at xs4all.nl (Gertjan Klein) Date: Mon, 17 Mar 2008 12:11:09 +0100 Subject: Spaces in path name References: <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> <708a66a7-da8f-4d44-824d-8a25203030f7@n58g2000hsf.googlegroups.com> Message-ID: joep wrote: >* If shell=True is required, then the executable is a build-in shell >command, which does not contain spaces, and, therefore, has no >problems This is only true when you are referring to directly executable files. However, Shell=True is also required when you want to "execute" a file by it's association. For example, if you want to execute a ".pyw" file directly (i.e., by using whichever python executable is associated with that extension), you need Shell=True. IMHO, the subprocess module should not have been included as-is in the Python library. It is counter-intuitive, buggy, ill-documented, and has needless limitations in functionality. Regards, Gertjan. -- Gertjan Klein From castironpi at gmail.com Tue Mar 4 00:31:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 21:31:10 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: On Mar 3, 10:01?pm, Benjamin wrote: > On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > > > What are metaclasses? > > Depends on whether you want to be confused or not. If you do, look at > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/. > > Basically, the metaclass of a (new-style) class is responsible for > creating the class. This means when Python sees > class Foo(object): > ? ? __metaclass__ = FooMeta > class FooMeta(type): > ? ? def __new__(cls, name, bases, dct): > ? ? ? ?#do something cool to the class > ? ? ? ?pass > It asks FooMeta to create the class Foo. Metaclasses always extend > type because type is the default metaclass. But you can stack class decorations, but not class metas. @somethingcool1 @somethingcool2 class Foo: pass * class Foo: __metaclass__= MetaCool1, MetaCool * denotes malformed From wizzardx at gmail.com Sun Mar 30 01:16:01 2008 From: wizzardx at gmail.com (David) Date: Sun, 30 Mar 2008 07:16:01 +0200 Subject: html DOM In-Reply-To: References: Message-ID: <18c1e6480803292216n3927ecacq6380b7ace6a33401@mail.gmail.com> On Sun, Mar 30, 2008 at 1:09 AM, Sam the Cat wrote: > Is there a package that would allow me the same or similar functionality for > modifying html code via the DOM model as I have in JavaScript ? I'd like to > parse an html file, then modify it and save the result. I am not trying to > do this online, rather I would like to do this on a batch of files stored on > my hard drive. I have found several packages that allow me to parse and > dissect html but none that allow me to modify the object and save the > results -- perhaps I am overlooking the obvious > Have you looked at Beautiful Soup? http://www.crummy.com/software/BeautifulSoup/ David. From noah at noah.org Mon Mar 24 20:52:54 2008 From: noah at noah.org (Noah) Date: Mon, 24 Mar 2008 17:52:54 -0700 (PDT) Subject: Python 2.2.1 and select() References: Message-ID: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> On Mar 24, 2:58 pm, Derek Martin wrote: > If and only if the total amount of output is greater than the > specified buffer size, then reading on this file hangs indefinitely. > For what it's worth, the program whose output I need to capture with > this generates about 17k of output to STDERR, and about 1k of output > to STDOUT, at essentially random intervals. But I also ran it with a > test shell script that generates roughly the same amount of output to > each file object, alternating between STDOUT and STDERR, with the same > results. > I think this is more of a limitation with the underlying clib. Subprocess buffering defaults to block buffering instead of line buffering. You can't change this unless you can recompile the application you are trying to run in a subprocess or unless you run your subprocess in a pseudotty (pty). Pexpect takes care of this problem. See http://www.noah.org/wiki/Pexpect for more info. -- Noah From sjmachin at lexicon.net Wed Mar 12 07:58:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Mar 2008 04:58:24 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Message-ID: On Mar 12, 10:29 pm, Bernard wrote: > Hey Larry, > > that one is fairly easy: > > >>> from array import array > >>> array('i', [1, 2, 3, 4, 5, 1, 2]) > >>> def count(x, arr): > > cpt = 0 # declare a counter variable > for el in arr: # for each element in the array > if el == x: # when it is equal to the 'x' value > cpt+=1 # increment the counter variable by one > return cpt # return the counter after the loop>>> count(1,a) > > 2 > Hey Bernard, you have just laboriously reinvented the count method: >>> from array import array >>> a = array('i', [1, 2, 3, 4, 5, 1, 2]) >>> a.count(1) 2 >>> which Larry has already said doesn't do the job -- the job is to create a histogram!! From paul.hermeneutic at gmail.com Tue Mar 11 17:29:31 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 11 Mar 2008 16:29:31 -0500 Subject: any library for SOAP 1.1 or SOAP 1.2? In-Reply-To: References: Message-ID: <1205270971.4382.1.camel@localhost.localdomain> On Fri, 2008-01-25 at 16:52 +0530, Amogh Hooshdar wrote: > Hi, > > I wish to know which python library is popular for SOAP related > programming, especially for sending SOAP requests and parsing SOAP > responses. > > I can't find any such library in the Python standard library but I > could find ZSI and soap.py libraries. However, ZSI does not support > SOAP 1.2. > > Does anyone know about a library that supports SOAP 1.2 also? Support for SOAP 1.2 is on the ZSI wishlist. It may not happen until you and I do it. Have you found anything else? Are you using ZSI? From wbsoft at xs4all.nl Sun Mar 9 12:44:33 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Sun, 9 Mar 2008 17:44:33 +0100 Subject: pure python hyphenator Message-ID: <200803091744.33620.wbsoft@xs4all.nl> Hi all, I'm just new to this list and I'm a musician and hobby programmer. I am busy with LilyKDE, a python plugin package for KDE's editor Kate, that makes using the LilyPond music typesetter from within Kate easier. While already busy writing a python module for breaking lyrics text (using hyphenation dicts from e.g. OpenOffice.org) I found Dr.Leo's PyHyphen. But just for fun I also continued my own plain python module, which now has it's SVN repository at: http://python-hyphenator.googlecode.com/ and it's PyPI page at: http://pypi.python.org/pypi/hyphenator . It needs more testing but seems to work nice. LilyKDE is located at http://lilykde.googlecode.com/ all the best. Guido and community: thanks for such a nice programming language, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandi From grante at visi.com Tue Mar 4 23:13:15 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 04:13:15 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> <13sr22ii98uipc4@corp.supernews.com> Message-ID: <13ss7er3igcbda7@corp.supernews.com> On 2008-03-04, blaine wrote: >> It looks like the fastest speed supported by python termios on >> Linux is B460800 (uses a constant of 0x1004). If you look in >> /usr/include/..., baud rates do go up to 921600 (which uses a >> constant of 0x1007). >> >> Try using the appropriate constant from /usr/include/... (for >> the target platform, of course). > I want to thank you SO MUCH for all your help. Here are my issues > that I overcame (sanity check): > 1. Why did we have to use 0x1007, instead of 0x10007 that our grep > command returns? The number might be different for the host where you did the grep that it is for the target machine (IIRC, you said it was an ARM, right?). Did you do the grep on the include files for the ARM target or on a host of some other architecture? The actual numbers might also be different in different versions of the kernel. > 2. PySerial works beautifully. Thank you for the suggestion. > What I had to do was add this to the PySerial source root > in serialpostix.py, after the import termios: > > termios.B921600 = 0x1007 [...] > ... so now I can pass 921600 as a parameter to PySerial! :) > > So my next question is - I would like to contribute to the > python source tree by updating termios.h to handle the higher > baud rates by default. Is this a good opportunity for me to > submit a patch? I've never done this before but have always > been interested in doing so. Sure! It's been a while since I submitted a patch, and I don't remember what the process is, but hopefully somebody reading the thread does. It could be that the change is already in the development branch... -- Grant Edwards grante Yow! Two LITTLE black at dots and one BIG black visi.com dot...nice 'n' FLUFFY!! From gagsl-py2 at yahoo.com.ar Wed Mar 26 14:19:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 15:19:03 -0300 Subject: Py2exe embed my modules to libary.zip References: Message-ID: En Wed, 26 Mar 2008 14:55:43 -0300, escribi?: > Does anybody have any idea how can I embed my modules to libary.zip > and use it from my application.For example if user write this code in > my TextEntry ( or something like that, textentry is created with > wxpython ) : > > import d3dx # directpython module > frame=d3dx.Frame(u"My frame") # create frame > frame.Mainloop() # run it > > ....and then when my application execute code how can I set path to > d3dx module to "library.zip/d3dx.py". > I'm not sure is this properly set question. If d3dx.py is in library.zip (top level), and the path to library.zip is in sys.path, Python will find the module. A .zip in sys.path acts as it were a directory itself. -- Gabriel Genellina From kay.schluehr at gmx.net Sun Mar 23 21:35:48 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 23 Mar 2008 18:35:48 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> <13uc4bpb0b564af@corp.supernews.com> <7a4c084f-ecb7-4ed4-8f3f-af29d811d44a@b64g2000hsa.googlegroups.com> Message-ID: <503c0e97-046b-479e-b606-68c30456c05c@a1g2000hsb.googlegroups.com> On 23 Mrz., 09:31, Arnaud Delobelle wrote: > On Mar 23, 8:14 am, Steven D'Aprano > cybersource.com.au> wrote: > > On Sat, 22 Mar 2008 23:15:00 -0700, John Nagle wrote: > > > That's some professor inventing his very own variation on predicate > > > calculus and writing a book using his own notation and terminology. > > > There's no sign of footnotes or references to prior work. The notation > > > doesn't seem to do anything not previously possible; it's just > > > different. > > > You say that as if it were unusual in maths circles :) > > Haha. As opposed to programmers who have all agreed to use the same > language. > > Anyway, I have browsed the book and agree with Paul Rubin that there > doesn't seem to be any unusual notation in it, although there are a > numbers of topics that I am not really familiar with. > > -- > Arnaud The author at least introduces his notation in the initial chapter. This is good style among mathematicians who introduce conventions at the beginning of their books or in an appendix. Note that I'm with Paul here but I'm not sure what John is complaining about anyway. Maybe sequent calculus ( natural deduction ) which was introduced by Gentzen around 75 years ago? http://en.wikipedia.org/wiki/Sequent_calculus From deets at nospam.web.de Sun Mar 9 18:00:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 23:00:08 +0100 Subject: __iter__ yield In-Reply-To: References: Message-ID: <63j4vbF27lit6U2@mid.uni-berlin.de> duccio schrieb: > > Hello! > Someone knows if it's possible to make this __iter__ function with just > one 'yield' intead of two? > Is there some simpler way to make this __iter__ iter through all nodes? > Thanks! > > class Node: > def __init__(self, data=None): > self.childs=[] > self.data=data > def appendNode(self, n): > node=Node(n) > self.childs.append(node) > return node > def __str__(self): > return '<'+str(self.data)+'>' > def __iter__(self): > yield self #1 > for n in self.childs: > for nn in n.__iter__(): > yield nn #2 Nope. There have been numerous discussions about this, introducing something like a yield_all-keyword or such thing that would replace the above boilerplate - but so far they all have been rejected. Search the archives for the reasons, I don't remember them :) Diez From castironpi at gmail.com Sun Mar 30 21:24:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 18:24:48 -0700 (PDT) Subject: Rubik's cube translation Message-ID: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> How do I get a Rubik's cube translation out of this: >>> a= numpy.array([[0,1,2],[3,4,5],[6,7,8]]) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> a[:,0],a[:,1],a[:,2] #no good (array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])) >>> I need [[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]. >>> c= numpy.array([[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]) >>> c array([[6, 3, 0], [7, 4, 1], [8, 5, 2]]) From stephenhorne100 at aol.com Tue Mar 18 08:25:15 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 18 Mar 2008 05:25:15 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: Just to throw in one more alternative, if you sort your list, you only need to test adjacent items for equality rather than needing a search for each unique item found. You should get O(n log n) rather than O(n^2), since the performance bottleneck is now the sorting rather than the searching for duplicates. Also, since the sort method is built into the list, sorting performance should be very good. The dictionary version Chris suggests (and the essentially equivalent set-based approach) is doing essentially the same thing in a way, but using hashing rather than ordering to organise the list and spot duplicates. This is *not* O(n) due to the rate of collisions increasing as the hash table fills. If collisions are handled by building a linked list for each hash table entry, the performance overall is still O(n^2) since (for large amounts of data) there is still a linear search on each collision. If collisions are handled by building binary trees, the performance is back to O(n log n). That is, for large enough datasets, the performance of hash tables is basically the performance of the collision handling data structure (ignoring scaling constants). I suspect Python handles collisions using linked lists, since using trees would require that all dictionary keys support ordered comparisons. Using a dictionary or set to eliminate duplicates therefore gives O(n^2) performance. That said, hash tables have very good scaling constants to their performance, so the dictionary technique will be a very good performer in general. And if the lists are reasonably small the performance will often seem like O(n) in practice. The sort-then-filter approach should still be competitive, but of course it requires that the contents of the list can be ordered consistently. An inappropriate hash function can similarly cause problems for the dictionary approach, causing that theoretical O(n^2) performance to become apparent very quickly. This is probably one reason why the cookbook recipe recommends an O(n^2) searching-based approach. From sturlamolden at yahoo.no Mon Mar 17 20:57:00 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 17 Mar 2008 17:57:00 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> On 17 Mar, 04:54, WaterWalk wrote: > So I'm curious how to read code effectively. I agree that python code > is clear, but when it becomes long, reading it can still be a hard > work. First, I recommend that you write readable code! Don't use Python as if you're entering the obfuscated C contest. Two particularly important points: * If you find yourself thinking this module is too long, that's probably what it is. Half a page of code per module is fine. Two pages of code per module can be too much. * Comments are always helpful to the reader. Second, I recommend getting a good IDE. E.g. pick one of: * Microsoft Visual Studio (commercial) * Eclipse with PyDev and CDT (free) * SPE (free) * ActiveState Komodo IDE (commercial) From castironpi at gmail.com Sun Mar 2 17:47:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 14:47:38 -0800 (PST) Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: <5e3f7c46-802a-4305-984e-718ce2045f31@i29g2000prf.googlegroups.com> > >>> is there a better way of creating d?? > > >> a = [[0] * 3 for dummy in xrange(3)] > > Each element of a refers to a distinct array. > > > Why not simply [[0]*3]*3 ? > > All three elements of the result refer to the same array. ... whereas you reassign all three elements of [0]* 3. >>> ((0,)*3,)*3 ((0, 0, 0), (0, 0, 0), (0, 0, 0)) You're safe in this one-- changing [0][0] won't change [1][0], 'cuz you can't! From cpthomas at gmail.com Thu Mar 13 09:05:45 2008 From: cpthomas at gmail.com (Casey T) Date: Thu, 13 Mar 2008 06:05:45 -0700 (PDT) Subject: Different results when running script from IDLE versus Command Line References: <895b88e4-694d-4fee-a633-08aa8a407999@p73g2000hsd.googlegroups.com> Message-ID: On Mar 12, 5:28?pm, Chris wrote: > On Mar 12, 8:10 pm, Casey T wrote: > > > > > Hi, > > > I'm new to Python and I'm having some problems with getting different > > results from my script when I run it from IDLE versus just double- > > clicking the .py file and having it run through the command line. > > Basically, my script reads some CSV files, assembles a text files, > > then uploads that test file to an ftp site. When I run the script from > > IDLE, everything works fine. But when it runs from the command line, > > the file that gets uploaded is empty. It seems that it is creating a > > new file to upload, rather than using the existing file (or at least > > that's what I think is going on.) Below is my script. I apologize for > > any ugly code. Thanks for your help. > > > import sys,os,linecache,csv,ftplib,time > > > starttime = time.time() > > > #******* > > #Summary file assembling > > #******* > > currentdir = "//folder/" > > > reg_sum = open('reg_sum.txt','w') > > reg_sum.close > > > for files in os.listdir(currentdir): > > ? ? reg_file = csv.reader(open(currentdir + files)) > > ? ? for row in reg_file: > > ? ? ? ? reg_sum = open('reg_sum.txt','a') > > ? ? ? ? reg_sum.write(",".join(row) + ',\n') > > > reg_sum.close > > > #******* > > #Summary file processing > > #******* > > coordList = [ > > ? ? ["F10",40.0053,-75.0927], > > ? ? ["T10",40.0272,-75.1123], > > ? ? ["D22",39.9811,-75.0998], > > ? ? ["P02",40.0437,-75.0217], > > ? ? ["D68",39.9203,-75.1388], > > ? ? ["D51",39.9534,-75.1405], > > ? ? ["S43",39.9217,-75.2275], > > ? ? ["S33",39.9360,-75.2077], > > ? ? ["S42A",39.9215,-75.1937], > > ? ? ["S05",39.9617,-75.1782], > > ? ? ["T14",40.0165,-75.1077]] > > > coordList_index = > > ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"] > > #coordList_index is a list containing > > > in_text = open('reg_sum.txt','r') > > > out_text = open('reg_out.txt','w') > > out_text.close > > > out_text = open('reg_out.txt','a') > > > for line in in_text: > > ? ? split_line = line.split(',') > > ? ? if (split_line[0]) in coordList_index: > > ? ? ? ?i = coordList_index.index(split_line[0]) > > ? ? ? ?coords = str(coordList[i][1]) + "," + str(coordList[i][2]) > > ? ? ? ?last_update = str(split_line[2]) > > ? ? print str(split_line[0]) > > ? ? if split_line[1] == "1": > > ? ? ? ?out_text.write(split_line[0] + "
,Test1: " + last_update + > > "," + coords + ",1" + "\n") > > ? ? elif split_line[1] == "0": > > ? ? ? ?out_text.write(split_line[0] + "
,Test2.
Last updated: " > > + last_update + "," ?+ coords + ",0" + "\n") > > ? ? else: > > ? ? ? ?out_text.write(split_line[0] + "
,No data.," + coords + > > "\n") > > > in_text.close > > > ###******* > > ###Uploads file via FTP > > ###******* > > s = ftplib.FTP('ftp.blah123.org,'user','pass') > > > f.open('reg_out.txt','r') > > s.storlines('STOR reg_out.txt', f) > > > f.close() > > s.quit() > > > print ?"Processed in " + str(((time.time() - starttime) / 60) *60) + " > > seconds!" #prints elapsed time > > You never closed your file. > > file_object.close > > > try adding '()' at the end of your close calls. > As to why it differs, I can't think offhand why it wouldn't. wow. thank you so much. it was the '()'. I now get consistent results. In all the sample code I saw, I never saw the '()' after close. thanks again - casey From timr at probo.com Sat Mar 22 22:03:29 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 23 Mar 2008 02:03:29 GMT Subject: Anomaly in time.clock() References: <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: <0febu3lut6cpgikoe02snl0tju05gd8qs8@4ax.com> Godzilla wrote: > >Just found out that win32api.GetTickCount() returns a tick count in >milli-second since XP started. Not sure whether that is reliable. >Anyone uses that for calculating elapsed time? What do you mean by "reliable"? The tick count is updated as part of scheduling during timer interrupts. As long as no one disables interrupts for more than about 15ms, it is reliable. However, it's only a 32-bit value, so the number rolls over every 49 days. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From attn.steven.kuo at gmail.com Fri Mar 21 01:12:01 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 20 Mar 2008 22:12:01 -0700 (PDT) Subject: How do I change the font size for the default coordinates in matplotlib? References: Message-ID: On Mar 20, 8:20 pm, Carl wrote: > I've searched the user manual (and this forum) but I don't see > anything that helps. Did you mean the font size for the ticks or for the labels? Here's an example: from pylab import * x = arange(0, 2*pi, 0.01) y = sin(2*pi*x) rcParams.update({'xtick.labelsize': 5, 'ytick.labelsize': 10}) subplot(111) plot(x,y) ylabel("Vert", fontsize=15) xlabel("Horiz", fontsize=20) show() -- Hope this helps, Steven From mr.cerutti at gmail.com Thu Mar 6 13:17:28 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 6 Mar 2008 13:17:28 -0500 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <51302a8c0803061017ga7522dcj50c53271884bbbf0@mail.gmail.com> On Thu, Mar 6, 2008 at 12:17 PM, Guillermo wrote: > > You can also get the dynamic polymorphism without invoking inheritance > > by specifying a protocol that the values in your dict must implement, > > instead. Protocols are plentiful in Python, perhaps more popular than > > type hierarchies. > > I'm used to languages with stricter rules than Python. I've read a bit > about Python protocols, but where could I get some more info on > implementation details? Sounds very interesting. A protocol is just an interface that an object agrees to implement. In your case, you would state that every object stored in your special dict must implement the to_tagged_value method with certain agreeable semantics. Python implements sequence types, mapping types, iterators, file streams, and other things with protocols. For example, iterators must support the "next" and and "__iter__" methods. Using a protocol instead instead of a type hierarchy requires less boring boilerplate, and I suppose in Python will usuallly be preferable except when you want to inherit implementation as well as interface. In that case, inheritance often saves boilerplate cide rather than increases it. It's also misnomered as duck-typing (clearly it should be nomed quack-typing). -- Neil Cerutti From castironpi at gmail.com Thu Mar 27 07:19:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:19:18 -0700 (PDT) Subject: what are generators? References: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> Message-ID: <5875e7c0-6051-4e27-b019-5bae126d457e@p25g2000hsf.googlegroups.com> On Mar 25, 7:36?pm, Miki wrote: > On Mar 24, 8:17?am, castiro... at gmail.com wrote: > > > I'm looking for a cool trick using generators. ?Know any exercises I > > can work? > > Simple one the comes to mind is flattening a list: > > >>> list(flatten([1, [[2], 3], [[[4]]]])) > [1, 2, 3, 4] I don't think it's well-defined. (But this is impossible and useless calling.) CMIIW? This is generic: >>> def f(): ... __gen= None ... def g(): ... i= 0 ... while 1: ... i+= 1 ... yield __gen( i ) ... def set( gen ): ... nonlocal __gen ... __gen= gen ... return g, set ... >>> a, set= f() >>> b= a() >>> set( lambda x: print( x ) ) >>> next( b ) 1 >>> next( b ) 2 >>> next( b ) From gagsl-py2 at yahoo.com.ar Mon Mar 3 09:26:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 12:26:53 -0200 Subject: Cant run application as ./myapp.py References: <10505.9786969379$1204547853@news.gmane.org> Message-ID: En Mon, 03 Mar 2008 10:35:30 -0200, Robert Rawlins escribi?: > I've got an application here which for some reason won't start using the > following syntax from the command line: > > > Cd /mydirectory > > ./MyApplication.py > > > I have to run this as a fully qualified python launch such as: > > > Cd /mydirectory > > python MyApplication.py > > > This is a little bit confusing to me as I have other applications which > run > just fine using the ./somthing.py syntax. Is there any reason why this > doesn't work? See this thread from last year: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1d0fd05b3615057/ -- Gabriel Genellina From sjmachin at lexicon.net Sat Mar 22 00:25:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 21:25:21 -0700 (PDT) Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <47E3C1A3.6050608@ncf.ca> Message-ID: <1c518ce7-2ea4-4d3f-9cb9-563048e0bd52@s19g2000prg.googlegroups.com> On Mar 22, 4:36 am, Christian Heimes wrote: > Colin J. Williams schrieb: > > > You might consider adding the Julian date > > (http://en.wikipedia.org/wiki/Julian_date). > > > I had a crack at this a while ago but didn't seem to get quire the right > > result, using the ACM algorithm. I seemed to be a day out at the BC/AD > > divide. 1. Somewhere in the Colin-Christian-Nicholas thread, the "Julian date" and the "Julian calendar" seem to become conflated. 2. "day out": possibly because there is no year 0; year 1 BCE is followed immediately by year 1 CE. > > Yes, the Julian date family is very useful when dealing with dates > before 1900. I'm having some difficulty understanding the above sentence, given either interpretation of "Julian date family". What is the significance of 1900? [Julian calendar interpretation] Some countries (including Russia, China, Greece and Turkey) did not adopt the Gregorian calendar until after 1900. Dealing with a date expressed as (year, month, day) is far from easy for approx year range 1582 to 1926 unless it has been expressly tagged as e.g. "old style" or "new style". If so tagged, there is to me no difference in ease of use between the proleptic Julian calendar and the proleptic Gregorian calendar. [Julian date as used in astronomy] This supports dates back to about 4800 BCE easily, whereas Python's datetime module supports the proleptic Gregorian calendar only back to year 1 CE. Cheers, John From fakeaddress at nowhere.org Thu Mar 6 05:46:28 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 02:46:28 -0800 Subject: Python CGI & Webpage with an Image In-Reply-To: <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> References: <33af0509-ec96-4344-913c-bd267d767ddc@z17g2000hsg.googlegroups.com> <3dc601d5-3bf7-42c5-8fd6-92452c084d3b@s8g2000prg.googlegroups.com> <46918c21-7ab0-48c0-949d-0345999c968d@u69g2000hse.googlegroups.com> Message-ID: rodmc wrote: [...] > Python: > > f = open("finish.html") > doc = f.read() > f.close() > print doc You might need to start with: print "Content-Type: text/html" print Is "finish.html" in the right place? When you browse to your script, can you see that you're getting the html? > HTML: [...] >

References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: Steven D'Aprano napisa?(a): >> I can see that Python and Javascript inheritance model is almost the >> same. Both languages are dynamically typed. And it seems that using >> "classes" in Python makes some things more complicated then it is >> necessary (eg functions, methods and lambdas are differen beeing in >> Python concept). > > Please explain why you think that functions are more complicated in > Python because of the class model. Sorry for a late reply (I was out of the office). 1. You have different syntax for named and unnamed (lambdas) functions. Functions and methods are different things in Python even if they have same syntax. But all these are still a pieces of code that you use repeatedly to make some task. 2. Static function doesn't need to reference "self", and Python forces programmer to put "self" explicitly. Then you have to do some "tricks" on function to become static. Python is said "nothing is really private", but interpreter does some "tricks" to make __id hidden for a class. Some opinions: 1. In early days you could do OOP in C -- you just used additional parameter in a function. Then C++ appeared to make life easier: "when you write mystring.toupper(), then toupper function gets hidden argument called "this"". Programs are written in a high level object oriented languages now. In these languages you still use the same syntax mystring.toupper(), but now you don't pass object to a function (as in C), but you act on that object. So in the body of toupper() you can REFERENCE object "mystring". So why do I have to put that "strange" argument "self"? This is not only my opinion (http://apache.ece.arizona.edu/~edatools/Python/Prototypes.htm). Without "self" you would use same syntax for ordinary functions, methods, and lambdas. 2. Something is private because you can't reference that from outside the scope. The wrong way is to make object properties private by declaring them private or to do hidden actions (__id). For example all local variables in function are private, because you can't access them from outside that function. Why desn't this work for objects? Again this is not only my opinion -- http://www.crockford.com/javascript/private.html. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 28 07:31:33 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 28 Mar 2008 12:31:33 +0100 Subject: Plugins accessing parent state In-Reply-To: References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> <653q99F2e37q8U1@mid.uni-berlin.de> Message-ID: <47ecd707$0$18855$426a34cc@news.free.fr> Andr? a ?crit : > On Mar 28, 6:39 am, "hajdu... at gmail.com" wrote: >> On Mar 28, 1:58 am, "Diez B. Roggisch" wrote: (snip) >>> But to be honest: you are thinking much to far there - after all, it's >>> all *your* code, and inside one interpreter. A real isolation isn't >>> available anyway. >>> So just do what fullfills the functional requirements. >> >> Since I want to have a uniform call to all plugins, would it make >> sense to split out the attributes that I do want to share to a >> separate class and then simply create a new instance of that class and >> store it in the main class? >> >> For instance >> >> ... >> self.utilities = Utilities(self) >> ... >> plugin.do(msg,self.utilities) > > I would bypass the step of creating a new instance and write instead > plugin.do(msg, self) > thus having access to all properties/methods of the calling object. > Why restrict it?... +1 on this. And FWIW, *if* you later find out you *really* need to restrict access to the caller object's attribute (ie: 'self'), it will be as simple as wrapping it in a decorator (design pattern, not function decorator) object that will take care of this, ie (Q&D naive implementation): class RestrictedSelf(object): allowed_attributes = ('dothis', 'dothat') def __init__(self, realself): self.realself = realself def __getattr__(self, name): if name.startswith('_') or name not in self.allowed_attributes: raise AttributeError( 'access to %s.%s is forbidden' % (self.realself, name) ) return getattr(self.realself, name) And in the call to the plugin: plugin.do(msg, RestrictedSelf(self)) But my bet is that YAGNI, so to make a long story short: start with the simplest thing that could possibly work !-) HTH From mail at timgolden.me.uk Sun Mar 16 12:49:42 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 16:49:42 +0000 Subject: Spaces in path name In-Reply-To: <47DD4933.7050609@timgolden.me.uk> References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> <47DD4933.7050609@timgolden.me.uk> Message-ID: <47DD4FA6.6030203@timgolden.me.uk> Tim Golden wrote: > Well I've got a patch ready to go (which basically just > wraps a shell=True command line with an *extra* pair of > double-quotes, the same as you do for an os.system call). > I'll try to put some time into the subprocess docs as well, > at least as far as a Win32-how-do-I on my own site if not > an update to the official docs. For the record, I've raised this as issue 2304 with a patch attached: http://bugs.python.org/issue2304 TJG From castironpi at gmail.com Tue Mar 11 15:43:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 12:43:46 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> <2b098afa-2dcc-4bde-bdde-02eece46fd68@47g2000hsb.googlegroups.com> <817b79d0-d451-4696-ab73-1289a380136c@d4g2000prg.googlegroups.com> Message-ID: On Mar 11, 11:31?am, Lie wrote: > On Mar 10, 4:16?am, castiro... at gmail.com wrote: > > > > > > > On Mar 9, 4:25?am, Lie wrote: > > > > On Mar 9, 3:27?am, castiro... at gmail.com wrote: > > > > > To Lie: > > > > > > Personally I preferred a code that has chosen good names but have > > > > > little or no comments compared to codes that makes bad names and have > > > > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > > > > I won't like it, it's that I can't. ?You know, in linguistics, there's > > > > But I much prefer it that the code has good names AND concise > > > comments, not too short and not too long that it becomes obscure. > > > What do you mean? ?If 'obscure' is the right word, then it's > > subjective (from metrics import obscurity?), which means that 10% of > > the people disagree with you, or 90% do. ?The end-all be-all, there is > > no such thing. ?I don't think it's obscure; I do. ?Is it? > > No, there is a point where everyone would say obscure. But not on all code. Comments can obscure code, and code can too. Here's a snip from the docs: # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite Is c2pread more or less obscure than c2pr or chi2parread? If there's an objective metric of the degree of something's obscurity (obscured- ity), then that has an answer. Is it a scalar, or if not, is there abs( answer )? Does that comment obscure the later code? Are 'in' and 'out' more or less obscure than those? (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) Information design can get (*subjective) breathtaking, but if you see a potential improvement, you should always be able to make it. Tell me what you think of this simile: Sometimes Steve Chessmaster reads board positions, sometimes prose. Some of the prose is less obscure, -to- -him-, than board states. To someone with a different speciality, as in bishops vs. knights, endgame vs. openings, certain forks, the states are less obscure than the corresponding prose. To my fmr. A.I. professor, "The minimax A*," and "The beaten path A*" are plenty clear. He can say what they do. Can you? > (remember you don't have access to source code, so you have to > decipher the documentation for what the function is about) But you're still calling it? > I prefer to see something like this: > def add(a, b): > ? ? return a + b > Even without documentation I'd know immediately what it does from the > name (add). What if the word is generic? Do you know if it has a return value? From castironpi at gmail.com Sun Mar 30 23:03:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 20:03:39 -0700 (PDT) Subject: Rubik's cube translation References: <3f3817e8-db90-4bbb-9d6e-cddf042ff6de@a22g2000hsc.googlegroups.com> Message-ID: <489180f4-aa43-4d98-a67d-71ce06ea9152@x41g2000hsb.googlegroups.com> On Mar 30, 9:48?pm, "Tim Leslie" wrote: > On Mon, Mar 31, 2008 at 12:24 PM, ? wrote: > > How do I get a Rubik's cube translation out of this: > > > ?>>> a= numpy.array([[0,1,2],[3,4,5],[6,7,8]]) > > ?>>> a > > ?array([[0, 1, 2], > > ? ? ? ?[3, 4, 5], > > ? ? ? ?[6, 7, 8]]) > > ?>>> a[:,0],a[:,1],a[:,2] #no good > > ?(array([0, 3, 6]), array([1, 4, 7]), array([2, 5, 8])) > > > ?I need [[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]. > > > ?>>> c= numpy.array([[ 6, 3, 0 ], [ 7, 4, 1 ], [ 8, 5, 2 ]]) > > ?>>> c > > ?array([[6, 3, 0], > > ? ? ? ?[7, 4, 1], > > ? ? ? ?[8, 5, 2]]) > > In [10]: numpy.rot90(a, 3) > Out[10]: > array([[6, 3, 0], > ? ? ? ?[7, 4, 1], > ? ? ? ?[8, 5, 2]]) > > Tim What if this is connected: >>> D array([[1, 2, 3], [4, 5, 6], [6, 7, 8]]) >>> E array([[6, 7, 8], [0, 0, 0], [0, 0, 0]]) --> >>> D array([[1, 2, 3], [4, 5, 6], [6, 7, 8]]) >>> E array([[6, 7, 8], [0, 0, 0], [0, 0, 0]]) >>> numpy.rot90( D ) array([[3, 6, 8], [2, 5, 7], [1, 4, 6]]) --> >>> E array([[1, 4, 6], [0, 0, 0], [0, 0, 0]]) ? From bernard.chhun at gmail.com Fri Mar 7 20:26:42 2008 From: bernard.chhun at gmail.com (Bernard) Date: Fri, 7 Mar 2008 17:26:42 -0800 (PST) Subject: Edit and continue for debugging? References: Message-ID: <5f7d4c0e-c8d1-468b-a089-654cf6681458@m34g2000hsc.googlegroups.com> As Jonathan says. :) I had a lot of fun learning how to plug doctests[1] into my python web apps and now I'm just adding them automatically as I create classes and functions. Those tests tidbits says so much more than a paragraph of comments. [1] : http://docs.python.org/lib/module-doctest.html On 7 mar, 09:44, "Bronner, Gregory" wrote: > I haven't seen much on this for a few years: > > I'm working on a GUI application that has lots of callbacks. Testing it > is very slow and quite boring, as every time I find an error, I have to > exit it, restart it, and repeat the series of clicks. It would be really > amazing if python supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my code and > have it apply to a running instance of a class. I wonder if it would be > possible to do this by configuring the interpreter to parse classes and > functions rather than whole modules, and to re-parse as necessary; also > to have byte-compiled modules be singletons rather than be standard > reference counted objects. > > Thanks > Gregory R. Bronner > (212) 526-0102 > gregory.bron... at lehman.com > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > > This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. > > -------- > IRS Circular 230 Disclosure: > Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From arnodel at googlemail.com Wed Mar 26 04:58:09 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 01:58:09 -0700 (PDT) Subject: Strange loop behavior References: <47EA0ABB.3030804@mydeskfriend.com> Message-ID: On Mar 26, 8:51?am, Gabriel Rossetti wrote: > Gabriel Rossetti wrote: > > Hello, > > > I wrote a program that reads data from a file and puts it in a string, > > the problem is that it loops infinitely and that's not wanted, here is > > the code : > > > ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > ? ? while d != "": > > ? ? ? ? file_str.write(d) > > ? ? ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > > I also tried writing the while's condition like so : len(d) > 0, but > > that doesn't change anything. I tried step-by-step debugging using > > PyDev(eclipse plugin) and I noticed this, once the while was read once, > > it is never re-read, basically, the looping does happen, but just in > > between the two lines in the loop's body/block, it never goes on the > > while and thus never verifies the condition and thus loops forever. I > > had been using psyco (a sort of JIT for python) and so I uninstalled it > > and restarted eclipse and I still get the same thing. This looks like > > some bug, but I may be wrong, does anybody understand what's going on here? > > > Thanks, > > Gabriel > > > PS > > And yes I checked, the "d" variable is en empty string at some point, so > > the looping should stop. > > Ok, I get it, the repr() function actually returns a string with quote > characters around it, thus the length is never 0, but 2. The reason I > began using the repr() function is that the str() and unicode() > constructors didn't accept the data read, because it was bigger than > ord(128) (or something like that. I'm trying to read a binary file and > put it's contents in an xml message to send via the network, so that I > can re-create it on the other side. I do need to keep the xml aspect > though. Is there a better way of doing this? > > Thanks, > Gabriel Have a look at the uu and base64 modules: http://docs.python.org/lib/module-uu.html http://docs.python.org/lib/module-base64.html -- Arnaud From tmp1 at viltersten.com Fri Mar 7 16:56:28 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 22:56:28 +0100 Subject: Location and size of a frame Message-ID: <63dr1hF26enh0U1@mid.individual.net> I'm disliking the size of my frame and also i'm disappointed regarding it's location. So, i wish to change them. At this link http://infohost.nmt.edu/tcc/help/pubs/tkinter/frame.html the frame object is discussed but as far i can tell, there are only suggestions regarding what to put in the constructor. So, how/where do i check how to affect the location and size? I'm guessing it has to do with "location", "width" and "heinght" but i didn't make it work. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From python.list at tim.thechases.com Tue Mar 25 18:36:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Mar 2008 17:36:59 -0500 Subject: what does ^ do in python In-Reply-To: References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: <47E97E8B.2010108@tim.thechases.com> > In most of the languages ^ is used for 'to the power of'. > > No, not in most languages. In most languages (C, C++, Java, C#, Python, > Fortran, ...), ^ is the xor operator ;) ...and in Pascal it's the pointer-dereferencing operator... -tkc From pavlovevidence at gmail.com Thu Mar 13 12:45:37 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Mar 2008 09:45:37 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: On Mar 13, 12:38 pm, Alan Isaac wrote: > Dan Bishop wrote: > > def cmp_key(cmp_fn): > > class CmpWrapper(object): > > def __init__(self, obj): > > self.obj = obj > > def __cmp__(self, other): > > return cmp_fn(self.obj, other.obj) > > return CmpWrapper > > Apparently I'm overlooking something obvious ... > > how is this supposed to work if __cmp__ is no longer > > being called? (Which was my understanding.) It won't. In Python 3.0 you'd have to write this class in terms of rich comparisons (__lt__, __gt__, etc.). Carl Banks From aisaac at american.edu Wed Mar 19 01:10:37 2008 From: aisaac at american.edu (Alan Isaac) Date: Wed, 19 Mar 2008 05:10:37 GMT Subject: method to create class property In-Reply-To: <64astpF29u3k1U1@mid.uni-berlin.de> References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> <64astpF29u3k1U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > In python 3.0, there will be an even nicer way - propset: > @property > def foo(self): > return self._foo > @propset > def foo(self, value): > self._value = value Isn't that:: @propset(foo) def foo(self, value): self._value = value Cheers, Alan Isaac From jeff at schwabcenter.com Sat Mar 22 15:02:42 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 12:02:42 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: Larry Bates wrote: > jmDesktop wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. >> >> Thank you. > > ABSOLUTELY. Get them started with a REAL programming language that will > teach them proper fundamentals. I wish Python would have been around 25 > years ago when I taught incoming Freshmen at local University. To get > students to understand about variable references, etc. What do you mean by "variable references," and how are they used in Python? From duncan.booth at invalid.invalid Sun Mar 2 05:57:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Mar 2008 10:57:43 GMT Subject: FW: Escaping a triple quoted string' newbie question References: Message-ID: "Jules Stevenson" wrote: > Hello, > > Apologies if the terminology in this email is a little incorrect, I'm > still finding my feet. > > I'm using python to generate some script for another language (MEL, in > maya, specifically expressions). Maya runs python too, but > unfortunately its expression language still has to use the maya > syntax. > > If I pass the expression this code: > > #runtime code [mel] > expRuntime="""float $pos[]=particleShape1.worldPosition; > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; > """ > dynExpression (p, s=expRuntime, rad=1) #generate the expression > > Then maya errors out, however if I pass maya an 'escaped' version: > > expRuntime="""float $pos[]=particleShape1.worldPosition;\r\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\r\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\r\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2];" -rad > particleShape1;""" > > Then all is well. My question is, is there any way to convert the > first variable example to the second? It's a lot easier to type and on > the eye. > Escaping the quotes doesn't change the string, so the only difference I can see between your strings is that you have split the lines by carriage- return+linefeed instead of just linefeed characters. If so: s = expRuntime.replace('\n', '\r\n') should have the desired effect. From ptmcg at austin.rr.com Sun Mar 30 03:46:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Mar 2008 00:46:53 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> <13utgh8j9ik8t7c@corp.supernews.com> Message-ID: <95d67524-d54f-4d7a-854d-53abeb2b3596@d62g2000hsf.googlegroups.com> On Mar 30, 12:34?am, castiro... at gmail.com wrote: > > The screen is real (r-e-a-l): all manners intended. ?Real. ?Just bid > and auction. > Please leave the newbies alone. They have enough trouble just getting their Python environments running, without trying to decipher your pseudo-profound chatterbot-speak. -- Paul From castironpi at gmail.com Sat Mar 1 01:02:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 29 Feb 2008 22:02:32 -0800 (PST) Subject: at-exit-thread References: <62r68tF220j59U1@mid.uni-berlin.de> <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> <4b0b675a-4333-4224-a40d-717d3c469c54@z17g2000hsg.googlegroups.com> Message-ID: On Feb 29, 4:34?pm, Preston Landers wrote: > On Feb 29, 2:12?pm, castiro... at gmail.com wrote: > > > If a thread adds an object it creates to a nonlocal > > collection, such as a class-static set, does it have to maintain a > > list of all such objects, just to get the right ones destroyed on > > completion? ? > > Yes. > > > Processes destroy their garbage hassle-free; how can > > threads? ? > > If you're asking "is there some automatic way to associate a external > resource with a thread so that it's deleted when the thread is done" > then the answer (to the best of my knowledge) is no. ?You would have > to take care of these details yourself once something outside your > thread got a reference to the resource. If you keep all references to > the resource inside the thread, then you can use the __del__ method of > the resource to take any cleanup actions. > > Also, processes don't always "destroy their garbage hassle free" if > you consider inter process communication. ?For instance, if you create > an object in one process then serialize it and pass it to another > process through e.g. an XMLRPC call, there's no automatic way for the > other process to be notified that the originating process exited. > You'd have to build that feature in. ?Exact same thing with threads. > > > And don't forget Thread.run( self ) in the example, if > > anyone ever wants to make use of the 'target' keyword. > > I don't understand what you're referring to. In the initial counterexample, > class MyThread(Thread): > > def run(self): > while some_condition: > do_something() > do_something_after_the_thread_ends() , MyThread overrides 'run', so target is never called. It did create the picture to me though that: class MemHoldingThread( Thread ): def __init__( self, *a, **kwa ): Thread.__init__( self, *a, **kwa ) self.objs= set() self._args= ( self, )+ self._args def hold( self, obj ): self.objs.add( obj ) return obj def run( self ): Thread.run( self ) self._cleanup() def _cleanup( self ): for obj in self.objs: obj.clean() Then, def f( thd ): resrc= thd.hold( NewResource() ) infinite_loop( resrc ) MemHoldingThread( target= f ) thd is prepended to f's list of arguments so that it has a handle to its own thread object, but doesn't need an entire thread class-- middle ground. Then thd.hold adds any obj created to a thread-local set (and returns it). Then, _cleanup iterates over the set, and calls clean() on its items when f returns. At this point, I've gotten really really complicated. Not only have I still not shown the _at_exit call to MemHoldingThread static member _clean_all_remaining, but it's only useful if NewResource provides a list of globals/externals that it "adds itself to", or a clean() method to do them itself. But, you do get the benefit of not having to store each global/external in a Thread subclass object-- it does that for you-- as well as the benefit of being able to invoke the behavior without explicit additional subclasses. thing1= MemHoldingThread( target= thingf ); thing1.start() daemon1= MemHoldingThread( target= daemonf ); daemon1.start() server1= MemHoldingThread( target= serverf ); server1.start() rather than class Thing( Thread ):... thing1= Thing(); thing1.start() class Daemon( Thread ):... daemon1= Daemon(); daemon1.start() class Server( Thread ):... server1= Server(); server1.start() , which is useful sometimes, if even only a negligible proportion of them. (Honestly, if Thread.start() returned self, class Thing( Thread ):... thing1= Thing().start() , or Thread( start= True ) launched it, that could go a long way, -- you just get keyword name collisions with target's parameters pretty soon.) What are the disadvantages to specifying an internal storage byte order for conversion to a string to use mmap with, by the way? And for all my seniors out there, you may be pleased to learn that I no longer think that all of my general little 5-liners should go in the standard library. > you consider inter process communication. For instance, if you create > an object in one process then serialize it and pass it to another > process through e.g. an XMLRPC call, there's no automatic way for the > other process to be notified that the originating process exited. Maybe... but if all else fails you can pass the process ID in on connection creation, and periodically check if it's still alive. Do any Op. Sys.s have a OnProcTerminate( hproc, callback ) API? Sadly, stdin IPC is before my time. Windows actually even has ThreadSuspend and ThreadResume API; if suspending threads (and raising exceptions in them from others) threatens state consistency, what are their semantics? From grante at visi.com Wed Mar 5 17:00:57 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 22:00:57 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> Message-ID: <13su60prq21ccd2@corp.supernews.com> On 2008-03-05, castironpi at gmail.com wrote: >>>>> I want to hash values to keys. ?How do the alternatives compare? >> >>>>http://catb.org/~esr/faqs/smart-questions.html >> >>> ... without extending the whole way to a full relational database? >> >> You didn't bother following the link and reading the advice, did you? If >> you did, you haven't done a good job of following that advice. > > Well, obviously there's someone who's interested in computers and > programming that has a question. It may be obvious that he has a question. It's not the least bit obvious what that question is. > Communication is not his forte, but effort, willingness, > devotion, and dedication are. What should he do, and what > should the others, who are gifted speakers? He should spend less time trying to generate "gifted speach" and more time learning how to ask an understandable, meaningful question. The link which you ignored explains how to do that. In your original post, it's not very clear what you mean by "hash values to keys" means nor what alternatives you're asking about. If you're trying to learn about hashing algorithms, then google "hashing algorithms" and read the first half-dozen hits. The first two are Wikipedia articles which are both quite good and are almost certainly available in your native lanauge. -- Grant Edwards grante Yow! But they went to MARS at around 1953!! visi.com From duncan.booth at invalid.invalid Mon Mar 17 12:12:13 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 16:12:13 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <47de94fa$0$2679$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: >> Here's a puzzle for those who think they know Python: >> >> Given that I masked out part of the input, which version(s) of Python >> might give the following output, and what might I have replaced by >> asterisks? >> >>>>> a = 1 >>>>> b = **** >>>>> if a is b: print 'yes!' >> ... >>>>> b >> 1 >>>>> type(b) >> > > I know it! Using CPython 2.5.2a0, 2.6a1+ and 3.0a3+:: > > >>> b = type('type', (type,), {'__repr__': lambda self: > ... ""})('int', (object,), {'__repr__': > ... lambda self:"1"})() > >>> b > 1 > >>> type(b) > > >>> 1 is b > False > > What's my prize? Ok, that one is impressive, I should have thought of putting some more checks (like asserting type(a) is type(b)), but then the whole point of setting the puzzle was that I expected it to be ripped to shreds. You can queue up behind Steven to choose any of the exciting prizes on my non-existent prize table. Meanwhile, I'll fall back on the same quibbling getout I used with Steven: too long. From grante at visi.com Sat Mar 15 17:45:27 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Mar 2008 21:45:27 -0000 Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <13togrnsdfipa64@corp.supernews.com> On 2008-03-15, Guido van Brakel wrote: > Hello > > I have this now: > >> def gem(a): >> g = sum(a) / len(a) g = float(sum(a)) / len(a) >> return g > It now gives a int, but i would like to see floats. How can integrate > that into the function? See above. > Life is like a box of chocolates, you never know what you're gonna get sometimes it's a crunchy frog... -- Grant From rcdailey at gmail.com Fri Mar 28 15:22:45 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 28 Mar 2008 14:22:45 -0500 Subject: New python forum on CodeGuru! Message-ID: <496954360803281222i82827acvc873f9dfc35933c7@mail.gmail.com> Hi, I managed to convince the CodeGuru forum administrator to add a Python discussion forum to the community. It's a great success for me, as I really love CodeGuru and their forums. I really encourage everyone to use it, as it will be a great asset to the Python community. The forum will be removed if it doesn't generate enough traffic in the next few months, so please help support it by generating discussion there instead of on the mailing list. You can visit the following link to get to the forum: http://www.codeguru.com/forum/forumdisplay.php?f=95 -------------- next part -------------- An HTML attachment was scrubbed... URL: From malkarouri at gmail.com Sat Mar 8 09:43:23 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 06:43:23 -0800 (PST) Subject: List as FIFO in for loop Message-ID: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Hi everyone, I have an algorithm in which I need to use a loop over a queue on which I push values within the loop, sort of: while not(q.empty()): x = q.get() #process x to get zero or more y's #for each y: q.put(y) The easiest thing I can do is use a list as a queue and a normal for loop: q = [a, b, c] for x in q: #process x to get zero or more y's q.append(y) It makes me feel kind of uncomfortable, though it seems to work. The question is: is it guaranteed to work, or does Python expect that you wouldn't change the list in the loop? Regards, Muhammad Alkarouri From google at mrabarnett.plus.com Sun Mar 16 15:27:30 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 16 Mar 2008 12:27:30 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: On Mar 16, 2:27 am, Benjamin wrote: > On Mar 15, 8:12 pm, lampshade wrote:> Hello, > > > I'm having some problems with os.path.isdir I think it is something > > simple that I'm overlooking. > > > #!/usr/bin/python > > import os > > > my_path = os.path.expanduser("~/pictures/") > > print my_path > > results = os.listdir(my_path) > > for a_result in results: > > if os.path.isdir(str(my_path) + str(a_result)): > > Try if os.path.isdir(os.path.join(my_path, a_result)):> results.remove(a_result) > > > for x in results: print x > > > The problem is, that the directories are never removed. Can anyone > > point out what I'm missing that is causing the bug? Is there a better > > way of doing this? > > You should always use os.path.join to join paths. You shouldn't add > them like normal strings. I suspect you're getting a combination which > doesn't exist, so it isn't a dir. :) > You are also removing items from 'results' while iterating over it, which has an undefined behaviour. It would be better to build a new list of those that aren't directories. From pofuk at email.t-com.hr Sun Mar 2 06:59:28 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Sun, 2 Mar 2008 12:59:28 +0100 Subject: Python app at startup! References: <5fd991f2-d079-4218-8198-fa79c2d29955@z17g2000hsg.googlegroups.com> Message-ID: Program: import os import wx app = wx.App() frame = wx.Frame(None, -1, "MyFrame") frame.Show() app.MainLoop() python.exe setup.py py2exe from distutils.core import setup import py2exe setup(windows=['prog.py']) wrote in message news:e11b4e83-8eae-4d4c-bd29-3f2bd5d8daa5 at 41g2000hsc.googlegroups.com... > On Feb 29, 7:21 am, SMALLp wrote: >> dave_mikes... at fastmail.fm wrote: > >> >> > Does it do the same thing when you run it with the Python interpreter? >> >> No. The programm works fine! In interupter and when i "compile" it. > > My guess is that you're not including something in the .exe that you > need. What does your py2exe command line and setup.py look like? > From pdl5000 at yahoo.com Fri Mar 28 11:12:36 2008 From: pdl5000 at yahoo.com (Paul Lemelle) Date: Fri, 28 Mar 2008 08:12:36 -0700 (PDT) Subject: Pexpect question. Message-ID: <918528.31885.qm@web52902.mail.re2.yahoo.com> I am trying separate a script that users pexpect into various functions within the same expect session. The problem is that the function does not return control back Main. Any insight into this issue would be greatly appreciated. Below is sample code of the problem. Thanks, Paul ____ import pexpect def sshcon(user, password): go = pexpect.spawn ('/usr/bin/ssh -l root %s '% (user)) go.expect ('Password: ') go.sendline (password) go.interact() #get node info for both clusters. C1_node = raw_input("Enter the ip address for node on cluster 1: ") C1_pass = raw_input("Enter the password for the node on cluster 1: ") sshcon(C1_node, C1_pass) #go to the path chk.expect('# ') chk.sendline('ls') #chk = pexpect.spawn('ls') # veriy that you are connected chk.interact() ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From r.grimm at science-computing.de Thu Mar 27 13:06:56 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Thu, 27 Mar 2008 10:06:56 -0700 (PDT) Subject: singleton decorator Message-ID: <1983c7ec-a7da-4fae-97a9-4f22cc2ea4c7@d4g2000prg.googlegroups.com> Hallo, playing with the decorators from PEP 318 I found the elegant singleton decorator. def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class A: pass class B: pass a1=A() a2=A() a3=A() b1=B() b2=B() b3=B() for i in ((a1,b1),(a2,b2),(a3,b3)): print id(i[0]),id(i[1]) But I always get a syntax error declaring class A as singleton. >>> reload ( decorator) Traceback (most recent call last): File "", line 1, in ? File "decorator.py", line 27 class A: pass ^ SyntaxError: invalid syntax What's the problem with this code because it's only copied for the PEP 318? It doesn't work with python 2.4 and python 2.5. Greetings Rainer From stephan.diehl at gmx.net Tue Mar 4 07:36:08 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 04 Mar 2008 13:36:08 +0100 Subject: Eurosymbol in xml document References: Message-ID: Hallo Helmut, > Hi, > i'm new here in this list. > > i'm developing a little program using an xml document. So far it's easy > going, but when parsing an xml document which contains the EURO symbol > ('?') then I get an error: > > UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in > position 11834: character maps to first of all, unicode handling is a little bit difficult, when encountered the first time, but in the end, it really makes a lot of sense :-) Please read some python unicode tutorial like http://www.amk.ca/python/howto/unicode If you open up a python interactive prompt, you can do the following: >>> print u'\u20ac' ? >>> u'\u20ac'.encode('utf-8') '\xe2\x82\xac' >>> u'\u20ac'.encode('iso-8859-15') '\xa4' >>> u'\u20ac'.encode('iso-8859-1') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'latin-1' codec can't encode character u'\u20ac' in position 0: \u20ac is the unicode code point for the Euro sign, so u'\u20ac' is the unicode euro sign in python. The different encode calls translate the unicode into actual encodings. What you are seeing in your xml document is the iso-8859-15 encoded euro sign. As Diez already noted, you must make shure, that 1. the whole xml document is encoded in latin-15 and the encoding header reflects that or 2. make sure that the utf-8 encoded euro sign is in your xml document. Hope that makes sense Stephan From jaywgraves at gmail.com Thu Mar 6 13:11:59 2008 From: jaywgraves at gmail.com (jay graves) Date: Thu, 6 Mar 2008 10:11:59 -0800 (PST) Subject: List all files using FTP References: Message-ID: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> On Mar 6, 10:46 am, Anders Eriksson wrote: > I need to list all the files on my FTP account (multiple subdirectories). I > don't have shell access to the account. > anyone that has a program that will do this? Not offhand, but you can look at the ftpmirror.py script for inspiration. It should be in your Tools/scripts/ subdirectory of your Python installation. ... Jay Graves From xkenneth at gmail.com Wed Mar 12 00:30:49 2008 From: xkenneth at gmail.com (xkenneth) Date: Tue, 11 Mar 2008 21:30:49 -0700 (PDT) Subject: Python - CGI - XML - XSD Message-ID: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> Hi All, Quick question. I've got an XML schema file (XSD) that I've written, that works fine when my data is present as an XML file. (Served out by apache2.) Now when I call python as a cgi script, and tell it print out all of the same XML, also served up by apache2, the XSD is not applied. Does this have to do with which content type i defined when printing the xml to stdout? Regards, Kenneth Miller From castironpi at gmail.com Sun Mar 9 21:29:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 18:29:39 -0700 (PDT) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> <980fee99-808b-47f2-8782-faac7c6a7586@34g2000hsz.googlegroups.com> Message-ID: <5b8774ff-ff74-44eb-8a73-bb71109f651c@p25g2000hsf.googlegroups.com> > Write the docs: > > > when two threads simultaneously increment the reference count of the same object > > Well, the example sucked. ?Just synchronize ref count manipulation. > Every OS has locking primitives, and a library exists to deny requests > to block that lock dead. ?How integral is the GIL to Python? > > > The Python interpreter is not fully thread safe > > Make it so. Per-thread reference counts do the trick. From rmsa50 at yahoo.co.in Wed Mar 19 13:02:41 2008 From: rmsa50 at yahoo.co.in (Gokul) Date: Wed, 19 Mar 2008 10:02:41 -0700 (PDT) Subject: Latest updates inSQL server and other programming laguages like C++/Java Message-ID: The latest developments in SQL server 2008 and an complete encyclopedia of microsoft softwares. Know the methodology to capture customers requirements for new products. Get the latest development in C++ and other IT related tools. A complete tutor for all your IT needs. Visit http://www.sqlserversoftware.blogspot.com From castironpi at gmail.com Mon Mar 17 18:51:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 15:51:47 -0700 (PDT) Subject: Interesting math problem References: Message-ID: <84bcedd4-e2a1-4184-baaa-0170547dbcc2@59g2000hsb.googlegroups.com> On Mar 17, 5:24?pm, "BJ?rn Lindqvist" wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > ? ? step = distance / float(parts) > ? ? intstep = int(step) > ? ? floatstep = step - intstep > > ? ? steps = [] > ? ? acc = 0.0 > ? ? for i in range(parts): > ? ? ? ? acc += floatstep > ? ? ? ? step = intstep > ? ? ? ? if acc > 0.999: > ? ? ? ? ? ? step += 1 > ? ? ? ? ? ? acc -= 1.0 > ? ? ? ? steps.append(step) > ? ? return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L Hash functions create a uniform distribution too. But don't those use shifting and modulo instead? From bearophileHUGS at lycos.com Wed Mar 26 18:28:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 15:28:58 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: Message-ID: <2f626a4d-1db2-4b10-bf5c-e4197a3db811@z38g2000hsc.googlegroups.com> Micha? Bentkowski: > Why does python create a reference here, not just copy the variable? I think to increase performance, in memory used and running time (and to have a very uniform way of managing objects). Bye, bearophile From electronixtar at gmail.com Thu Mar 20 03:40:49 2008 From: electronixtar at gmail.com (est) Date: Thu, 20 Mar 2008 00:40:49 -0700 (PDT) Subject: forkpty not working? Message-ID: Hello everyone. I am trying to write a bash/ssh wrapper in python so python scripts could interact with bash/ssh. Because when input passwords to ssh it requires a tty rather than stdin pipe, so i have to use a pty module to do that. I copied this snippet from this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/6bbc3d36b4e6ff55/ def rcmd(user, rhost, pw, cmd): #Fork a child process, using a new pseudo-terminal as the child's controlling terminal. pid, fd = os.forkpty() # If Child; execute external process if pid == 0: os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + cmd) x=open("it_worked.txt", "w") #output a file for test x.write("xxx") x.close() #if parent, read/write with child through file descriptor else: pause() #Get password prompt; ignore os.read(fd, 1000) pause() #write password os.write(fd, pw + "\n") pause() res = '' #read response from child process s = os.read(fd,1 ) while s: res += s s = os.read(fd, 1) return res As far as I can see the code is not working, when called the function rcmd() there is no file it_worked.txt spawned in the directory. I am n00b to POSIX, so anyone please give me some hint? what happened when os.forkpty()? From http Wed Mar 19 04:19:41 2008 From: http (Paul Rubin) Date: 19 Mar 2008 01:19:41 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> Message-ID: <7xve3j15ya.fsf@ruckus.brouhaha.com> Gerhard H?ring writes: > Probably because Ruby is all hot and sexy nowadays ;-) Though it's > remarkably close to Python, apparently. So close that I couldn't be > bothered to learn it. Ruby is apparently more Smalltalk-like and some consider it cleaner than Python. Like you, I figure it's close enough to Python that I haven't bothered with it. > In fact, for me personally, Python was about the last programming > language I learnt out of intrinsic motivation. I tried to take a look > at functional langugages like Haskell and Erlang, but I tend to > quickly get bored of toy examples and can learn best if I can apply a > new language to a real problem that it can solve better than the other > languages I know. Haven't found that killer problem so far ... The killer problem for Erlang is highly concurrent, distributed systems. I've been wanting to read Joe Armstrong's book about it since I have some interest in that sort of thing. It's not simply the ability to run vast numbers of threads and automatically marshal data between them (even if they're on separate computers), but also its convenient management of software faults through "supervision trees". In most languages we normally program our functions to notice error conditions and recover from them, raise exceptions that are handled elsewhere in the app, etc. In Erlang you just let the thread crash, and have the supervision system deal with restarting it, logging the error, etc. This separation of concerns apparently helps reliability of nonstop services like phone switches considerably. Also, Erlang has hot-patching facilities so you can upgrade your program while it's running, with 10,000 active network connections staying up and nobody outside noticing that anything has changed. Re Haskell: I've been spending a lot of time on Haskell recently, though I haven't done anything nontrivial with it yet (just some small stuff). But I think it's better for complex program development than Python is, and even small Haskell programs, (while they are more difficult to write, at least at my present level of experience) seem both cleaner and more solid in terms of confidence of correctness than the corresponding Python programs. Also, Haskell code runs a lot faster than Python code (real native-code compiler that can use multicore hardware), and there is a clever automatic unit testing system (QuickCheck) that relies on Haskell's static type system to generate random tests automatically. On the other hand, Python's standard libraries do more stuff and are better packaged. It's certainly easier to do lightweight internet scripting in Python. If I were writing something like a compiler, I'd probably use Haskell. From jayapal.d at gmail.com Sat Mar 15 00:26:50 2008 From: jayapal.d at gmail.com (jai_python) Date: Fri, 14 Mar 2008 21:26:50 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: On Mar 14, 9:45 pm, Jeff Schwab wrote: > Chris wrote: > > On Mar 14, 8:36 am, Dennis Lee Bieber wrote: > >> On Thu, 13 Mar 2008 21:28:18 -0700 (PDT), jai_python > >> declaimed the following in comp.lang.python: > > >>> hi frenz I Need a Python Script For read multiple files(.txt) from a > >>> folder and write it in a single text file.... > >> If you are on windows, just open a command prompt and use the > >> standard copy command... > > >> C:\Documents and Settings\Dennis Lee Bieber>copy /? > ... > > If you want to go that route you could also do: type *.txt > > > output_file.txt > > On Unix, cygwin, etc: > > cat dir/*.txt > output.txt > > Or if you need "deep" copy: > > cat $(find dir -name '*.txt') > output.txt > > You could write a portable solution in Python (as in Martin Laloux's > post), but most modern command-line environments have similar (but not > identical) support for globbing and redirecting files. If you're > getting the glob pattern from a user, they may expect subtly > platform-dependent behaviors, in which case portability might not as > important as native feel. ya its working.... thanks for all ur help From piet at cs.uu.nl Wed Mar 12 09:55:53 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 12 Mar 2008 14:55:53 +0100 Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: >>>>> gargonx (g) wrote: >g> Still no return of string. The null testing is not really the deal. >g> that could be replaced with anything EG: >g> def ReturnMethod(request, x): >g> if request is 'random': You shouldn't test with `is' but with `=='. >g> return x >g> else: print "No String for you...False!" >g> def SendMethod(request): >g> xstring = "Some text" >g> ReturnMethod(request, xstring) >g> SendMethod('random') -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From google at mrabarnett.plus.com Thu Mar 20 23:37:12 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 20 Mar 2008 20:37:12 -0700 (PDT) Subject: Trouble with variable "leakage"? References: Message-ID: <4869f2a6-98d1-405a-8e65-2e2686134126@d45g2000hsc.googlegroups.com> On Mar 21, 3:05 am, Jeremy N wrote: > I am working with Python in Maya, and have run into a problem with a > variable changing its contents without being scripted to do so. The > various print() statements below were from my efforts to track down > where it was occurring. I left them in so that anyone running this > will more easily see what's happening. > > On the line that reads 'dx = d1 / dx ; print("dx = %f" % dx)' there > is something happening to the variable that is being printed > repeatedly between the lines. The print statements prior to this > particular line print '...xlist[0][1] = 0.5' . However, on this > line, that variable is being updated to reflect a new value, when no > assignment to that variable has been made at that time. > > This leads me to believe that the variables 'dx' and 'xlist[0][1]' > are inexplicably linked. I have no idea why. Please help me. > > a=[5,0,3,4] > b=[8,3,0,10] > c=[2,4,10,0] > > nlist = [a,b,c] > xlist = [[],[],[]] > > for i in range(len(nlist)) : > relist = list(nlist) > relist.pop(i) > dlist = list(nlist[i]) > dlist.pop(0) ; dlist.pop(i) > for j in range(len(relist)) : > d1 = float(nlist[i][0]) > d2 = float(relist[j][0]) > dx = float(dlist[j]) > r1 = 1 - ( abs(d1-dx) / float(d2) ) > if r1 == 0.0 : > r1 += (d1 < d2) > xlist[i].append(float(r1)) > > del d1, d2, dx, relist, dlist > > ylist = list(xlist) This is performing only a shallow copy. xlist refers to a list containing sublists. You're copying the _references_ to the sublist, not the sublists themselves. > print(xlist) > print(ylist) > > for i in range(len(xlist)) : > relist = list(xlist) > relist.pop(i) > for j in range(len(relist)) : > print( "!!!!!!!!!!!!!!! NEW LOOP AT ( %d:%d ) !!!!!!!!!!!!!!!" % > ( i, j ) ) > print("%s / (%s + %s)" % ( str(xlist[i][j]), str(xlist[i][j]), > str(relist[j][( (i!=0) * ((j>=i)+(i-1)) )]) ) ) > d1 = float(xlist[i][j]) ; print("d1 = %f" % d1) > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > d2 = relist[j][( (i!=0) * ((j>=i)+(i-1)) )] ; print("d2 = %f" % d2) > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > dx = d1 + d2 ; print("dx = %f" % dx) > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > dx = d1 / dx ; print("dx = %f" % dx) > ylist[i][j] = float(dx) ; #print(ylist[i][j]) ylist[i] is the same list as xlist[i], so changing ylist[i][j] also changes xlist[i][j]. > print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) > print( "||| xlist[2][0] = %s" % str(xlist[2][0]) ) > print( "...\nxlist = %s\n..." % str(xlist) ) > > print(xlist) > print(ylist) > HTH. From perlefenc at gmail.com Thu Mar 27 12:13:19 2008 From: perlefenc at gmail.com (perlefenc at gmail.com) Date: Thu, 27 Mar 2008 09:13:19 -0700 (PDT) Subject: Dynamic code problem Message-ID: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> My dynamic code failed at this site http://playwide1.extra.hu/, need some help thank you. From micah at cowan.name Thu Mar 6 00:03:47 2008 From: micah at cowan.name (Micah Cowan) Date: Thu, 06 Mar 2008 05:03:47 GMT Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> Message-ID: <87hcfk30lo.fsf@micah.cowan.name> castironpi at gmail.com writes: > On Mar 5, 8:03?pm, castiro... at gmail.com wrote: >> On Mar 5, 5:31?pm, Grant Edwards wrote: >> >> > On 2008-03-05, castiro... at gmail.com wrote: >> > > Anyway, if (a,b) is a key in dictionary d, can it guarantee >> > > that (b,a) is also in it, and maps to the same object? >> >> Er... -specialized- dictionary d. >> >> > To solve that problem, Python provides the immutable >> > "frozenset" type: >> >> > ? >>> s1 = frozenset((1,2)) >> > ? >>> s2 = frozenset((2,1)) >> > ? >>> s1 == s2 >> > ? True >> > ? >>> d = {s1: "hi there"} >> > ? >>> s1 in d >> > ? True >> > ? >>> s2 in d >> > ? True >> >> Ah. ?Perfect. ?With this, I can just call frozenset on keys in >> __setitem__ and __getitem__... (though at that, it may be easier >> verbatim*.) > >> a= SomeList( [ 1,2,3 ] ) >> b= SomeList( [ 1,2,3 ] ) >> assert a is not b >> d[a]= True >> assert b not in d >> #there's the hangup > > *plonk* > > key is an iterable, just like the constructors to > other collection. Um... "*plonk*" is the (imaginary) sound made by dropping someone into your plonkfile (killfile, scorefile, whatever): the action of setting your newsreader to ignore someone you perceive to be a troll. I have extreme doubts that you have actually done this to _yourself_. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From troworld at gmail.com Sun Mar 2 16:48:49 2008 From: troworld at gmail.com (Tro) Date: Sun, 2 Mar 2008 16:48:49 -0500 Subject: Altering imported modules In-Reply-To: References: <200803011856.27611.troworld@gmail.com> Message-ID: <200803021648.49590.troworld@gmail.com> On Sunday 02 March 2008, Terry Reedy wrote: > "Tro" wrote in message > news:200803011856.27611.troworld at gmail.com... > > | Hi, list. > | > | I've got a simple asyncore-based server. However, I've modified the > > asyncore > > | module to allow me to watch functions as well as sockets. The modified > | asyncore module is in a specific location in my project and is imported > > as > > | usual from my classes. > | > | Now I'd like to use the tlslite library, which includes an asyncore mixin > | class. However, tlslite imports "asyncore", which doesn't include my own > | modifications. > | > | I'd like to know if it's possible to make tlslite load *my* asyncore > > module > > | without changing any of the tlslite code. > > If your module is also 'asyncore' and comes earlier in the search path, I > would expect the import to get yours. It's not. It has a package prefix like my.package.asyncore. I think I can either move my version of asyncore up a couple of levels or add the my.package directory to sys.path. My version of asyncore imports several functions from the built-in asyncore. Now that my version of it is imported as asyncore, how would it import the built-in version from python2.5/site-packages? Thanks, Tro From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 13 07:02:23 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Mar 2008 12:02:23 +0100 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> Message-ID: <47d90982$0$22008$426a74cc@news.free.fr> Alex a ?crit : (sni) > First of all thanks all for answering! > > I have some environment check and setup in the beginning of the code. > I would like to move it to the end of the script. Why ? (if I may ask...) > But I want it to > execute first, so the script will exit if the environment is not > configured properly. If you want some code to execute first when the script/module is loaded, then keep this code where it belongs : at the beginning of the script. From emailamit at gmail.com Mon Mar 31 13:24:01 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 10:24:01 -0700 (PDT) Subject: python scripts to standalone executable Message-ID: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Hi I am looking for a some tool that can convert python scripts to executable on Linux. I found freeeze.py as the only option so far. Couple of queries on freeze: 1. Have anyone used the freeze utility and any experiences to share from that? 2. Is there any enterprise-level exe-builder for python on linux (ActiveState has nothing)? Any other related commets are also welcome. Thanks Amit From jaywgraves at gmail.com Thu Mar 6 12:38:05 2008 From: jaywgraves at gmail.com (jay graves) Date: Thu, 6 Mar 2008 09:38:05 -0800 (PST) Subject: Data aggregation References: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> Message-ID: <81dbde3d-3ecf-4312-a3c4-9b0d31e98e5b@m34g2000hsc.googlegroups.com> On Mar 6, 10:28 am, vedranp wrote: > So, group by DATE, COUNTRY, ZIP and CITY and sum (or do some You are soooo close. Look up itertools.groupby Don't forget to sort your data first. http://aspn.activestate.com/ASPN/search?query=groupby&x=0&y=0§ion=PYTHONCKBK&type=Subsection http://mail.python.org/pipermail/python-list/2006-June/388004.html > From some little experience with Perl, I think this is managable with > double hash tables (1: basic hash with key/value = CITY/pointer-to- > other-hash, 2: hash table with values for CITY1), so I assume that > there would be also a way in Python, maybe with dictionaries? Any > ideas? Sometimes it makes sense to do this with dictionaries. For example, if you need to do counts on various combinations of columns. count of unique values in column 'A' count of unique values in column 'C' count of unique combinations of columns 'A' and 'B' count of unique combinations of columns 'A' and 'C' count of unique combinations of columns 'B' and 'C' in all cases, sum(D) and avg(E) Since I need 'C' by itself, and 'A' and 'C' together, I can't just sort and break on 'A','B','C'. HTH ... jay graves From planders at gmail.com Thu Mar 20 17:02:12 2008 From: planders at gmail.com (Preston Landers) Date: Thu, 20 Mar 2008 14:02:12 -0700 (PDT) Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: On Mar 20, 9:46?am, Jonathan Gardner wrote: > In the unix world, this is highly discouraged. You shouldn't have to > change your user. The only user who can change roles---and who should > change roles for security reasons---is root. IMHO this statement is a bit too broad. The original poster didn't specify that he wanted to become root. Running a command as a different user is useful for other cases besides running as root. For instance, your web server's documents directory may be owned by a www user who doesn't have a normal login shell. If you're on your 'regular' user and need to edit a document it's quite handy to do this: sudo -u www emacs index.html As for the original poster, you could use the subprocess module combined with sudo to do what you want - spawn a subprocess which runs sudo and the other program, which could itself be a python script or anything else. regards, Preston From pavlovevidence at gmail.com Sun Mar 30 01:17:13 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Mar 2008 22:17:13 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <3e6de9d7-4278-4b1e-9373-78c98fa11a3f@m34g2000hsc.googlegroups.com> <13utqsnq8le081f@corp.supernews.com> Message-ID: <4ef57592-4057-4ee7-8889-7b2fefdc6504@f63g2000hsf.googlegroups.com> On Mar 29, 9:23 pm, Steven D'Aprano wrote: > On Sat, 29 Mar 2008 12:49:05 -0700, Carl Banks wrote: > >> Please set it straight in 3.0, and if not, convince me with a good > >> reason of doing so, so that I can live with it and don't have to spend > >> the rest of my life in 2.x ;). > > > 1. It's not going to change in Python 3.0. > > > 2. It's a silly thing to care so much about that you will avoid using a > > langauge because of it. > [snip indignant rant] > > But it's not silly to care > about the feel of the language. I'm not exactly sure who you're arguing with, bud. No one around here that I can tell said anything about what you're railing against. Carl Banks From roygeorget at gmail.com Wed Mar 19 11:54:40 2008 From: roygeorget at gmail.com (royG) Date: Wed, 19 Mar 2008 08:54:40 -0700 (PDT) Subject: how to remove suffix from filename Message-ID: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> hi when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/ two.jpg'....] etc i want to extract the basename without the suffix...ie i want to get 'one','two' etc and not 'one.jpg' is there a function in python to do this or do i have tosplit it ..? thanks RG From newsgroup898sfie at 8439.e4ward.com Tue Mar 4 12:05:55 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Tue, 04 Mar 2008 12:05:55 -0500 Subject: 'normal' shell with curses In-Reply-To: References: <633s5lF24prinU1@mid.uni-berlin.de> Message-ID: <635drhF25qgqtU1@mid.uni-berlin.de> Thynnus wrote, on 03/04/2008 08:48 AM: > On 3/3/2008 9:57 PM, Michael Goerz wrote: >> Hi, >> >> I'm trying to print out text in color. As far as I know, curses is the >> only way to do that (or not?). So, what I ultimately want is a curses >> terminal that behaves as closely as possible as a normal terminal, >> i.e. it breaks lines and scrolls automatically, so that I can >> implement a function myprint(color, text) that does what print() does, >> only in color. > > You might find the below helpful. Let us know how you make out? > > -------- > > Python Cookbook > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 > > Title: > Using terminfo for portable color output & cursor control > > Description: > The curses module defines several functions (based on terminfo) that can > be used to perform lightweight cursor control & output formatting > (color, bold, etc). These can be used without invoking curses mode > (curses.initwin) or using any of the more heavy-weight curses > functionality. This recipe defines a TerminalController class, which can > make portable output formatting very simple. Formatting modes that are > not supported by the terminal are simply omitted. > > -------- > That looks *extremely* interesting. From a very brief test, it seems to do exactly what I want! Now, Windows seems very problematic for color output. I was using the following as a test, based on the above recipe: term = TerminalController() while True: print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled' print term.render('${RED}Error:${NORMAL}'), 'paper is ripped' On Linux, it works fine, on Windows, it just prints white on black (which is of course what it should do if the terminal doesn't support color). Can anyone get the Windows cmd.exe terminal to do color? I already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, but that doesn't seem to do anything (neither in what I tried yesterday with the ANSI escape codes, nor with the recipe code now). I also very briefly tried running it on the winbash shell (http://win-bash.sourceforge.net/), it didn't have any color either... So, any way to get color in Windows? Michael From partofthething at gmail.com Tue Mar 18 09:34:22 2008 From: partofthething at gmail.com (partofthething) Date: Tue, 18 Mar 2008 06:34:22 -0700 (PDT) Subject: Can't get bsddb working on Solaris 8 References: Message-ID: I fixed it! I had omitted the cascade of exceptions, but the previous one to the one shown is: File "/usr/local/lib/python2.5/dbhash.py", line 5, in import bsddb So I just went into dbhash.py and changed line 5 to import bsddb3 as bsddb. Then everything started working as planned. Excellent! But definitely a hack. From tjreedy at udel.edu Thu Mar 13 17:30:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Mar 2008 17:30:50 -0400 Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlibfrom BeautifulSoup References: <47d97288$0$36363$742ec2ed@news.sonic.net> Message-ID: "John Nagle" wrote in message news:47d97288$0$36363$742ec2ed at news.sonic.net... | Just noticed, again, that getattr/setattr are ASCII-only, and don't support | Unicode. | | SGMLlib blows up because of this when faced with a Unicode end tag: | | File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag | method = getattr(self, 'end_' + tag) | UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' | in position 46: ordinal not in range(128) | | Should attributes be restricted to ASCII, or is this a bug? Except for comments and string literals preceded by an encoding declaration, Python code is ascii only: " Python uses the 7-bit ASCII character set for program text." ref manual 2. lexical analisis This changes in 3.0 From guidovb1 at invalid Sat Mar 15 17:53:16 2008 From: guidovb1 at invalid (Guido van Brakel) Date: Sat, 15 Mar 2008 22:53:16 +0100 Subject: Convert int to float In-Reply-To: <13togrnsdfipa64@corp.supernews.com> References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> <13togrnsdfipa64@corp.supernews.com> Message-ID: <47dc442d$0$14348$e4fe514c@news.xs4all.nl> Grant Edwards wrote: > On 2008-03-15, Guido van Brakel wrote: >> Hello >> >> I have this now: >> >>> def gem(a): >>> g = sum(a) / len(a) > > g = float(sum(a)) / len(a) > >>> return g Hi, Thank you very much,sometimes it is so amazing simple. Regards -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- From duncan.booth at invalid.invalid Tue Mar 11 04:36:29 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Mar 2008 08:36:29 GMT Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 10, 10:44???pm, Nathan Pinno wrote: >> Why does my compiler say invalid syntax and then highlight the >> quotation marks in the following code: >> >> # This program is to find primes. > > Needs work. Be fair. The OP hadn't managed to figure out why the program wasn't running, so you can't expect him to have got all the bugs out of the code yet. And he only asked about the specific syntax error not the entire solution to his homework. My advice to Nathan would be: 1. If you get a weird syntax error that you don't understand try cutting the code down to just the bit which generates the error. 2. Play around in the interactive interpreter to see what works and what doesn't. 3. If you don't understand why the code doesn't work then get a stuffed toy, cardboard cutout of a person, or the least technical member of your family and explain to them in great detail exactly why the code must (despite error messages to the contrary) be correct. Usually you'll spot the problem half way through the explanation. 4. If you post to this list then post the full error message and traceback. That way we don't have to guess which quotation marks are the problem. From castironpi at gmail.com Thu Mar 13 21:17:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 18:17:47 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: On Mar 13, 8:15?pm, castiro... at gmail.com wrote: > On Mar 13, 7:45?pm, castiro... at gmail.com wrote: > > > > > > > On Mar 13, 7:18?pm, Mel wrote: > > > > Diez B. Roggisch wrote: > > > >> My understanding is that foo.bar does *not* create a new object. > > > > > Your understanding is not correct. > > > > >> ?All it > > > >> does is return the value of the bar attribute of object foo. ?What new > > > >> object is being created? > > > > > A bound method. This happens through the descriptor-protocol. Please see > > > > this example: > > > > > class Foo(object): > > > > ? ? def bar(self): > > > > ? ? ? ? pass > > > > > f = Foo() > > > > a = Foo.bar > > > > b = f.bar > > > > c = f.bar > > > > > print a, b, c > > > > print id(b), id(c) > > > > (What Diez said.) ?From what I've seen, f.bar creates a bound method > > > object by taking the unbound method Foo.bar and binding its first > > > parameter with f. ?This is a run-time operation because it's easy to > > > re-assign some other function to the name Foo.bar, and if you do, the > > > behaviour of f.bar() will change accordingly. > > > > You can get some very useful effects from these kinds of games. ?You > > > can make f into a file-like object, for example, with > > > > import sys > > > f.write = sys.stdout.write > > > > Here, f.write *is* a straight attribute of f, although it's a built-in > > > method of the file class. ?It's still bound, in a way, to sys.stdout. > > > ? I'm assuming that a different example could create an attribute of f > > > that's a bound method of some other object entirely. ?I've verified > > > that f.write('howdy') prints 'howdy' on standard output. > > > Accordingly, > > > f.write= types.MethodType( sys.stdout.__class__.write, sys.stdout ). > > Ah. ?Because this doesn't. > That is, because sys.stdout.write is -not- a user-defined function. > What it is, is a bound member function, and only the former is > converted/wrapped/bound*, as it is in the subsequent example. Last thing, sorry: Does MethodType.__get__ just return self, or is it not called, due to some type checking? From pavlovevidence at gmail.com Tue Mar 4 12:05:15 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 4 Mar 2008 09:05:15 -0800 (PST) Subject: for-else References: Message-ID: On Mar 4, 10:55 am, "BJ?rn Lindqvist" wrote: > On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks wrote: > > > for ...: > > > ... > > > exhausted: > > > ... > > > broken: > > > ... > > > > The meaning is explicit. While "else" seems to mean little there. > > > So I may like something similar for Python 3.x (or the removal of the > > > "else"). > > > I would not be opposed to this on its own merits, but there is a > > rationale behind the name "else". If you consider a for loop to be a > > rolled-up if...elif...else statement (situations where this is > > reasonable tend to be the same ones were else would be useful), then > > the "else" clause would remain unchanged on the for loop. > > > For instance, if you have a (trivial) if...elif...else like this: > > > if a == 0: > > do_task_0() > > elif a == 1: > > do_task_1() > > elif a == 2: > > do_task_2() > > else: > > do_default_task() > > > You could roll it up into a for...else statement like this: > > > for i in range(3): > > if a == i: > > do_task[a]() > > else: > > do_default_task() > > You forgot the break statement. The else suite will always be executed > in this loop. Kind of proves bearophiles point, for-else is really > tricky. Ah ha, but that would have been a mistake with or without the else clause.... Carl Banks From sdeibel at wingware.com Fri Mar 7 09:36:44 2008 From: sdeibel at wingware.com (Stephan Deibel) Date: Fri, 07 Mar 2008 09:36:44 -0500 Subject: ANN: Wing IDE 3.0.4 released Message-ID: <47D152FC.2000407@wingware.com> Hi, We're happy to announce version 3.0.4 of Wing IDE, an advanced development environment for the Python programming language. It is available from: http://wingware.com/downloads Version 3.0.4 is a bug fix release that reduces debugger overhead by about 50% per Python instruction executed, improves breakpoints tracking during edits, expands support for PyGTK auto-completion, and makes 14 other minor improvements. See the change log for details: http://wingware.com/pub/wingide/3.0.4/CHANGELOG.txt It is a free upgrade for all Wing 3.0 users. *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. New features added in Wing 3.0 include: * Multi-threaded debugger * Debug value tooltips in editor, debug probe, and interactive shell * Autocompletion and call tips in debug probe and interactive shell * Automatically updating project directories * Testing tool, currently supporting unittest derived tests (*) * OS Commands tool for executing and interacting with external commands (*) * Rewritten indentation analysis and conversion (*) * Introduction of Wing IDE 101, a free edition for beginning programmers * Available as a .deb package for Debian and Ubuntu * Support for Stackless Python * Support for 64 bit Python on Windows and Linux (*)'d items are available in Wing IDE Professional only. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). *Purchasing & Upgrading* Wing IDE Professional & Wing IDE Personal are commercial software and require a license to run. To upgrade a 2.x license or purchase a new 3.x license: Upgrade: https://wingware.com/store/upgrade Purchase: https://wingware.com/store/purchase Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From sengol240 at gmail.com Mon Mar 24 00:44:48 2008 From: sengol240 at gmail.com (sengol240 at gmail.com) Date: Sun, 23 Mar 2008 21:44:48 -0700 (PDT) Subject: THE GOOGLE PROJECT NETWORK INVITES YOU TO EARN$1,000 IN A SINGLE PROJECT.NORMALLY YOU CAN MAKE 20 PROJECTS IN A DAY.YOUR CHANCE IS GOING TO RARN $3,00,000 IN A SINGLE WEEK.THE LINK IS BELOW Message-ID: THE GOOGLE PROJECT NETWORK INVITES YOU TO EARN$1,000 IN A SINGLE PROJECT.NORMALLY YOU CAN MAKE 20 PROJECTS IN A DAY.YOUR CHANCE IS GOING TO RARN $3,00,000 IN A SINGLE WEEK.THE LINK IS BELOW www.jeeva235.blogspot.com IT IS A FREE MONEY MAKING OPPORTUNITY From book243 at gmail.com Sat Mar 29 21:45:01 2008 From: book243 at gmail.com (book243 at gmail.com) Date: Sat, 29 Mar 2008 18:45:01 -0700 (PDT) Subject: Redacted Message-ID: Redacted From bcl at brianlane.com Sat Mar 22 19:10:19 2008 From: bcl at brianlane.com (Brian Lane) Date: Sat, 22 Mar 2008 16:10:19 -0700 Subject: re.search (works)|(doesn't work) depending on for loop order In-Reply-To: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: <47E591DB.7070106@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 sgharvey wrote: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: > If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. > If I try to match every pattern to one line at a time, only one > pattern will match. I don't see that behavior when I try your code. I had to fix your pattern loading: patterns[pattern] = re.compile(pattern_strings[pattern], re.VERBOSE) I would also recommend against using both the plural and singular variable names, its bound to cause confusion eventually. I also changed contents to self.contents so that it would be accessible outside the class. The correct way to do it is run each pattern against each line. This will maintain the order of the config.ini file. If you do it the other way you will end up with everything ordered based on the patterns instead of the file. I tried it with Python2.5 on OSX from within TextMate and it ran as expected. Brian - -- - ---[Office 70.9F]--[Outside 54.5F]--[Server 103.3F]--[Coaster 68.0F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH5ZHaIftj/pcSws0RAigtAJsE+NWTxwV5kO797P6AXhNTEp8dmQCfXL9I y0nD/oOfNw6ZR6UZIOvwkkE= =U+Zo -----END PGP SIGNATURE----- From http Mon Mar 31 13:41:59 2008 From: http (Paul Rubin) Date: 31 Mar 2008 10:41:59 -0700 Subject: [OT] troll poll References: Message-ID: <7xr6dq3i54.fsf@ruckus.brouhaha.com> "Daniel Fetchinson" writes: > [ ] - Xah Lee > [ ] - castironpi I've lost track but has it been established that they are not the same person? From malaclypse2 at gmail.com Thu Mar 27 11:19:17 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 27 Mar 2008 11:19:17 -0400 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: <16651e80803270819t131e01adle1a5b9ed8b8fb976@mail.gmail.com> > Why should I need to set shell=True? I'm not globbing anything. The > second case still fails: RTFM From simon at brunningonline.net Mon Mar 10 13:30:22 2008 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 10 Mar 2008 17:30:22 +0000 Subject: lowercase u before string in "python for windows" In-Reply-To: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> References: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> Message-ID: <8c7f10c60803101030i14180626u3bb1f59d54840bc5@mail.gmail.com> On Mon, Mar 10, 2008 at 5:20 PM, davidj411 wrote: > why does this occur when using the python windows extensions? There's nothing Windows specific about this - it just means that you have unicode strings. See , -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From pavloutefkros at gmail.com Sun Mar 9 17:28:45 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 9 Mar 2008 14:28:45 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: i know os.popen() but i want to execute a file with args From py1.forest at tibit.com Fri Mar 28 19:50:34 2008 From: py1.forest at tibit.com (Forest) Date: Fri, 28 Mar 2008 16:50:34 -0700 (PDT) Subject: why does socket.makefile require non-blocking mode? Message-ID: <21989.75.55.199.5.1206748234.squirrel@webmail.sonic.net> The socket.makefile() docs say, "the socket must be in blocking mode." I don't see any explanation of why blocking mode is required, and I'm not sure whether that means timeout mode is forbidden as well. Can someone clarify this? I wanted to use file-like objects with socket timeouts, so I ended up writing my own replacement for socket._fileobject. I'd appreciate it if someone could either explain to my why my new class was unnecessary, or else encourage me to contribute it as a patch to the socket module. Cheers, Forest From cappallo at gmail.com Sun Mar 2 11:14:46 2008 From: cappallo at gmail.com (TC) Date: Sun, 2 Mar 2008 08:14:46 -0800 (PST) Subject: Question on importing and function defs Message-ID: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> I have a problem. Here's a simplified version of what I'm doing: I have functions a() and b() in a module called 'mod'. b() calls a(). So now, I have this program: from mod import * def a(): blahblah b() The problem being, b() is calling the a() that's in mod, not the new a() that I want to replace it. (Both a()'s have identical function headers, in case that matters.) How can I fix this? Thanks for any help. From shakefu at gmail.com Fri Mar 7 18:00:44 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 15:00:44 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <13t3gq9qo0po5ce@corp.supernews.com> Message-ID: <81d37ead-edd9-4666-8adb-5b5da45c6321@k2g2000hse.googlegroups.com> On Mar 7, 4:35 pm, Jeffrey Froman wrote: > shak... at gmail.com wrote: > > I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > Django comes with some pretty handy filters for doing this sort of > formatting. Check out the "date", "now", "timesince" and "timeuntil" > filters here: > > http://www.djangoproject.com/documentation/templates/#built-in-filter... > > Jeffrey Very cool - that's definitely handy to know for the output side of things. I was mostly interested in writing a custom widget for handling datetime input, 'cause I can't imagine anyone being studious enough to use the 2008-03-07 12:00:00 format all the time... besides, it's hard to type! I'd much rather allow for users to just be able to type "12pm today". So much to learn, so little time! Jacob From steve at holdenweb.com Sat Mar 1 14:17:26 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 14:17:26 -0500 Subject: Import, how to change sys.path on Windows, and module naming? In-Reply-To: References: Message-ID: Jeremy Nicoll - news posts wrote: > Jeremy Nicoll - news posts wrote: > >> If I understand correctly, when I import something under Windows, Python >> searches the directory that the executing script was loaded from, then >> other directories as specified in "sys.path". > > Sorry to followup my own question, but I ran > > for p,q in enumerate(sys.path): print p, q > > and got: > > 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms > 1 C:\Program Files\~P-folder\Python25\Lib\idlelib > 2 C:\WINDOWS\system32\python25.zip > 3 C:\Program Files\~P-folder\Python25\DLLs > 4 C:\Program Files\~P-folder\Python25\lib > 5 C:\Program Files\~P-folder\Python25\lib\plat-win > 6 C:\Program Files\~P-folder\Python25\lib\lib-tk > 7 C:\Program Files\~P-folder\Python25 > 8 C:\Program Files\~P-folder\Python25\lib\site-packages > 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32 > 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib > 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin > > Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip > in their sys.path? What's the point of having a zip in the path? > So that the files inside the zip can be imported as modules and packsges, of course. > Also, looking in C:\WINDOWS\system32\ I don't actually have a file called > python25.zip, but I do have one called python25.dll - so has something gone > wrong in creation of sys.path? > No. I'm not sure why the zip file is on there by default. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From aahz at pythoncraft.com Fri Mar 14 14:05:22 2008 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2008 11:05:22 -0700 Subject: RIP: Joseph Weizenbaum Message-ID: Creator of Eliza: http://www-tech.mit.edu/V128/N12/weizenbaum.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From wtanksleyjr at gmail.com Wed Mar 19 11:17:44 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Wed, 19 Mar 2008 08:17:44 -0700 (PDT) Subject: How to get an XML DOM while offline? Message-ID: I want to parse my iTunes Library xml. All was well, until I unplugged and left for the train (where I get most of my personal projects done). All of a sudden, I discovered that apparently the presence of a DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing the Internet... So suddenly I was unable to do any work. I don't want to modify the iTunes XML; iTunes rewrites it too often. How can I prevent xml.dom.minidom from dying when it can't access the Internet? Is there a simpler way to read the iTunes XML? (It's merely a plist, so the format is much simpler than general XML.) -Wm From tmp1 at viltersten.com Fri Mar 7 13:12:38 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 19:12:38 +0100 Subject: SV: Regarding coding style In-Reply-To: <13t2vvstgkne233@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net> <13t2vvstgkne233@corp.supernews.com> Message-ID: <63ddtqF27a5u2U1@mid.individual.net> >> Personally, I dislike double spaces after >> sentences, but it is not wrong to put them >> there any more than it is wrong not to put >> them there. > > You're lucky my high school typing teacher > didn't hear you say that... I'm unclear if your teacher was a double or single spacer. It's only implied that he felt strongly one way. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From Graham.Dumpleton at gmail.com Tue Mar 25 20:35:12 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Mar 2008 17:35:12 -0700 (PDT) Subject: Beta testers needed for a high performance Python application server References: <47e99237$0$90273$14726298@news.sunsite.dk> Message-ID: <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> On Mar 26, 11:00 am, Damjan wrote: > >> I'm looking for beta testers for a high performance, event-driven Python > >> application server I've developed. > > >> About the server: the front end and other speed-critical parts of the > >> server are written in portable, multithreaded C++. > ... > > Why not just put it on the net somewhere and tell us where it is? > > People aren't generally going to want to help or even look at it if > > you treat it like a proprietary application. So, put the documentation > > and code up somewhere for all to see. > > BTW, multiprocess web servers such as Apache can quite happily make > > use of multiple cores. Even within a single Apache multithread process > > it can still use multiple cores quite happily because all the > > underlying network code and static file handling code is in C and not > > subject to the GIL. So, as much as people like to bash up on the GIL, > > within Apache it is not necessarily as big a deal as people make out. > > BTW nginx now has a mod_wsgi too, if someone is looking for an Apache > replacement. Yes that is a viable option, as still are existing fastcgi solutions for Apache, lighttpd and nginx. Because the bottlenecks are generally going to be in upper application layers it really comes down to personal preferences as to which you want to use, which you find easier to configure and manage, plus which you trust as being the most secure and stable. For truly high demand sites you should also be looking at spreading load across multiple hosts, not just because of performance but also because of redundancy. You would also be serving media off a different web server to your Python web application and configuring each web server to the specific task it is doing. So, there is a lot more to in than raw speed of underlying technology and so one should always treat with caution something that is being sold as some better way of doing things. This applies to Apache mod_wsgi, nginx mod_wsgi or anything else for that matter. All have benefits, but they also have shortcomings in different areas which may not always make them suitable for all applications, or at least they may need to be configured in specific ways to make them perform best for specific applications. Anyway, because it isn't that simple is why I'd like to see some actual documentation for this new contender posted in a public place, along with code being browsable so one can evaluate it without having to sign up for some closed beta program. Graham From kyosohma at gmail.com Wed Mar 5 17:00:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 5 Mar 2008 14:00:17 -0800 (PST) Subject: Please keep the full address References: Message-ID: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> On Mar 5, 3:51 pm, "D'Arcy J.M. Cain" wrote: > On Wed, 5 Mar 2008 13:38:59 -0800 (PST) > > Mike Driscoll wrote: > > On Mar 5, 12:50 pm, castiro... at gmail.com wrote: > > I'm not sure why you change the address like this but could you please > include the full address. Those of us who identify the time wasters > would also like to drop the responses to their posts and changing the > address makes this impossible. > > -- > D'Arcy J.M. Cain | Democracy is three What are you talking about? I didn't change the address at all. I'm not even sure what you mean. Are you talking about the post subject line (which I have never touched in any post)? If you're talking about the OP's email address, that's Google's fault for cropping them. Mike From misterwang at gmail.com Tue Mar 18 21:44:10 2008 From: misterwang at gmail.com (Peter Wang) Date: Tue, 18 Mar 2008 18:44:10 -0700 (PDT) Subject: Any fancy grep utility replacements out there? References: Message-ID: On Mar 18, 5:16 pm, Robert Kern wrote: > samsli... at gmail.com wrote: > > So I need to recursively grep a bunch of gzipped files. This can't be > > easily done with grep, rgrep or zgrep. (I'm sure given the right > > pipeline including using the find command it could be done....but > > seems like a hassle). > > > So I figured I'd find a fancy next generation grep tool. Thirty > > minutes of searching later I find a bunch in Perl, and even one in > > Ruby. But I can't find anything that interesting or up to date for > > Python. Does anyone know of something? > > I have a grep-like utility I call "grin". I wrote it mostly to recursively grep > SVN source trees while ignoring the garbage under the .svn/ directories and more > or less do exactly what I need most frequently without configuration. It could > easily be extended to open gzip files with GzipFile. > > https://svn.enthought.com/svn/sandbox/grin/trunk/ > > Let me know if you have any requests. And don't forget: Colorized output! :) -Peter From rent.lupin.road at gmail.com Mon Mar 17 23:13:29 2008 From: rent.lupin.road at gmail.com (James) Date: Mon, 17 Mar 2008 20:13:29 -0700 (PDT) Subject: Cost of Queue.put Message-ID: <7d3e817b-6931-4fc5-921c-b2cf2b2400fa@i7g2000prf.googlegroups.com> Hi all, I'm struggling with the following problem: I need to disconnect a web service invocation from the addition of some content to a search engine, so that the web service will always return in reasonable time. Basically, what I need is a multi-process safe persistent quick queue. The arrangement I had was a simple XML-RPC service running on the web server which the various web server threads POST the relevant search engine updates to. These updates were added to a persistent queue built on top of Queue.Queue and cPickle, and there was a separate thread in the XML-RPC server actually adding the updates to the search engine. However, the CPU consumption of the XML-RPC server seems to grow pretty much linearly with the length of the persistent queue. Isn't Queue.put O(1)? I include the code for the persistent queue below - it's a modified version of this code: http://mail.python.org/pipermail/python-list/2002-December/177394.html I suppose the addition of cPickle to the mix must hurt Queue.put()... Any recommendations for alternative persistent queues? Thanks, James class PickleQueue(Queue.Queue): """A multi-producer, multi-consumer, persistent queue.""" def __init__(self, filename, maxsize=0): """Initialize a persistent queue with a filename and maximum size. The filename is used as a persistent data store for the queue. If maxsize <= 0, the queue size is infinite. """ self.filename = filename Queue.Queue.__init__(self, maxsize) def _init(self, maxsize): # Implements Queue protocol _init for persistent queue. # Sets up the pickle files. self.maxsize = maxsize try: self.readfile = file(self.filename, 'r') self.queue = cPickle.load(self.readfile) self.readfile.close() except IOError, err: if err.errno == 2: # File doesn't exist, continue ... self.queue = Queue.deque() else: # Some other I/O problem, reraise error raise err except EOFError: # File was null? Continue ... self.queue = Queue.deque() # Rewrite file, so it's created if it doesn't exist, # and raises an exception now if we aren't allowed self.writefile = file(self.filename, 'w') cPickle.dump(self.queue, self.writefile, 1) log.info("(PickleQueue._init) created queue") def __sync(self): # Writes the queue to the pickle file. self.writefile.seek(0) cPickle.dump(self.queue, self.writefile, 1) self.writefile.flush() def _put(self, item): # Implements Queue protocol _put for persistent queue. self.queue.append(item) self.__sync() def _get(self): # Implements Queue protocol _get for persistent queue. item = self.queue.popleft() self.__sync() return item From mail at timgolden.me.uk Sun Mar 16 12:22:11 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 16:22:11 +0000 Subject: Spaces in path name In-Reply-To: <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> Message-ID: <47DD4933.7050609@timgolden.me.uk> joep wrote: > > Tim Golden wrote: >> Tim Golden wrote: >>> What I haven't investigated yet is whether the additional flags >>> your example is passing (shell=True etc.) cause the main Popen >>> mechanism to take a different path. >> Sure enough, passing shell=True -- which is probably quite >> a rare requirement -- causes the code to change the call >> from "a.exe b.doc" to '%COMSPEC% /c "a.exe" "b.doc"'. >> The quoting rules (from cmd /?) are slightly involved but >> I can't see at first why this shouldn't work. However it >> clearly doesn't so I'll try to put together either a patch >> to the subprocess code or to the docs warning of the behaviour. >> >> I think that, in general, you need to pass shell=True far less >> often that you might imagine. (Possibly only for internal >> commands like dir, copy etc.). >> >> TJG > > Thanks, I didn't know it is possible to drop the shell=True. The > explanation of the subprocess model are not very clear to me and the > examples are quite incomplete. I got it to work by trial and error and > looking at the usage in different packages. > > Dropping shell=True works well for my case, no error messages and it > still captures the standard output: > > p = subprocess.Popen([ > r"C:\Program Files\WinRAR\Rar.exe","v", > r"C:\temp\Copy of papers.rar"], stdout=subprocess.PIPE) > > I am still looking at different versions, and the cases when it works > and when it doesn't are still confusing. Well I've got a patch ready to go (which basically just wraps a shell=True command line with an *extra* pair of double-quotes, the same as you do for an os.system call). I'll try to put some time into the subprocess docs as well, at least as far as a Win32-how-do-I on my own site if not an update to the official docs. TJG From jzgoda at o2.usun.pl Wed Mar 26 18:15:31 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 26 Mar 2008 23:15:31 +0100 Subject: Why does python behave so? (removing list items) In-Reply-To: References: Message-ID: Micha? Bentkowski pisze: > Why does python create a reference here, not just copy the variable? Because Python works like that -- it uses names and values idiom. If you change value, all names will be bound to the same changed value. >>>> j=range(0,6) >>>> k=j >>>> del j[0] >>>> j > [1, 2, 3, 4, 5] >>>> k > [1, 2, 3, 4, 5] > > Shouldn't k remain the same? No further comments on this. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From duncan.booth at invalid.invalid Mon Mar 31 14:15:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 18:15:22 GMT Subject: [OT] troll poll References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Daniel Fetchinson" writes: >> [ ] - Xah Lee >> [ ] - castironpi > > I've lost track but has it been established that they are not the same > person? > Has it actually been established that castironpi is actually a person? I thought it was probably a random sentence generator. From castironpi at gmail.com Sat Mar 8 13:03:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 10:03:02 -0800 (PST) Subject: Difference between 'function' and 'method' References: <6766529d-7f0e-4e9d-9498-1c295e71ac53@o77g2000hsf.googlegroups.com> Message-ID: <87b8b973-08cc-4659-8fd4-62244e27311d@p25g2000hsf.googlegroups.com> On Mar 7, 1:34?pm, castiro... at gmail.com wrote: > On Mar 7, 6:44?am, Sion Arrowsmith > wrote: > > > Gabriel Genellina wrote: > > >En Thu, 06 Mar 2008 23:46:43 -0200, escribi???: > > >> [ ... ] > > >You may look at the SimpleXMLRPCServer class and see how it implements ? > > >introspection. It's rather easy (and doesn't require metaclasses nor ? > > >decorators nor any other fancy stuff; I think it works the same since ? > > >Python 2.1). Apparently you're doing a similar thing, but using pickles ? > > >instead of xmlrpc. > > > It's not that difficult to graft pickles into SimpleXMLRPCServer -- > > I've done it, and if you're trying to sling large data structures > > over the connection it's a massive performance win (even with > > sgmlop in place to speed up XML parsing). > > ? ?her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump > > Yeah, but I'd be grafting a non-blocking RPC sequence too. > > -Instantiate- attributes of ISS upon instantiation. > > class C: > ? d= D > > c= C() > assert isinstance( c.d, D ) > assert c.d is c.d > > Which ones? Two options: instantiate all attributes, or ones with a certain property, such as name or superclass. class C: inst_d= D #actually gets bound to 'd', optionally class C: d= inst( D ) I think what I'm looking for is an attribute wrapper. class C: @inst d= D But the closest the syntax goes is: class C: class d( D ): pass (which takes us back to one of Steven's posts some days ago.) ( def f(x=None):/class C:/x= X/return C. ) and the d= inst( D ) solution.) You either need to assign something to assign something to its name, class C: d= X or declare it, but that only allows def and class statements (correct?). class C: attr d: D is ideal. From http Wed Mar 26 04:46:38 2008 From: http (Paul Rubin) Date: 26 Mar 2008 01:46:38 -0700 Subject: SoC project: Python-Haskell bridge - request for feedback References: Message-ID: <7xzlslvpn5.fsf@ruckus.brouhaha.com> A few thoughts. The envisioned Python-Haskell bridge would have two directions: 1) calling Haskell code from Python; 2) calling Python code from Haskell. The proposal spends more space on #1 but I think #1 is both more difficult and less interesting. By "Haskell" I presume you mean GHC. I think that the GHC runtime doesn't embed very well, despite the example on the Python wiki (http://wiki.python.org/moin/PythonVsHaskell near the bottom). This is especially if you want to use the concurrency stuff. The GHC runtime wants to trap the timer interrupt and do select based i/o among other things. And I'm not sure that wanting to call large Haskell components under a Python top-level is that compelling: why not write the top level in Haskell too? The idea of making the critical components statically typed for safety is less convincing if the top level is untyped. There is something to be said for porting some functional data structures to Python, but I think that's mostly limited to the simpler ones like Data.Map (which I've wanted several times). And I think this porting is most easily done by simply reimplementing those structures in a Python-friendly style using Python's C API. The type signatures (among other things) on the Haskell libraries for this stuff tend to be a little too weird for Python; for example, Data.Map.lookup runs in an arbitrary monad which controls the error handling for a missing key. The Python version should be like a dict, where you give it a key and a default value to return if the key is not found. Plus, do you really want Python pointers into Haskell data structures to be enrolled with both systems' garbage collectors? (Actually (sidetrack that I just thought of), a Cyclone API would be pretty useful for writing safe Python extensions. Cyclone is a type-safe C dialect, see cyclone.thelanguage.org ). The Haskell to Python direction sounds more useful, given Haskell's weirdness and difficulty. Python is easy to learn and well-packaged for embedding, so it's a natural extension language for Haskell applications. If you wrote a database in Haskell, you could let people write stored procedures in Python if they didn't want to deal with Haskell's learning curve. Haskell would call Python through its "safe" FFI (which runs the extension in a separate OS thread) and not have to worry much about the Python side doing IO or whatever. Of course this would also let Python call back into the Haskell system, perhaps passing Python values as Data.Dynamic, or else using something like COM interface specifications. Anyway I'm babbling now, I may think about this more later. From ron at example.com Thu Mar 27 01:03:22 2008 From: ron at example.com (Ron Eggler) Date: Thu, 27 Mar 2008 05:03:22 GMT Subject: last mouse movment or keyboard hit References: Message-ID: Gabriel Genellina wrote: >>> En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler >>> escribi?: >>> >>> >> I would like to get the time of the most recent human activity like a >>> >> cursor >>> >> movement or a key hit. >>> >> Does anyone know how I can get this back to start some action after >>> >> there >>> >> has been no activity for X minutes/seconds? > > En Wed, 26 Mar 2008 13:59:15 -0300, azrael > escribi?: > >> You can use wxPython. Take a look on the DemoFiles that you can >> download also from the site. I remember that there has been a demo of >> capturing mouse coordinates and also one example about capturing Which >> key has been pressed at which time. > > (Please don't top post) > Does wx catch all events in all other applications? > My understanding is that the OP wants a global detection, not restricted > to a single application. Exactly, I would like to have it global/system widely detected -- chEErs roN From python at bdurham.com Sun Mar 9 11:10:56 2008 From: python at bdurham.com (Malcolm Greene) Date: Sun, 09 Mar 2008 11:10:56 -0400 Subject: Converting a string to the most probable type In-Reply-To: <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> Message-ID: <1205075456.17754.1241388585@webmail.messagingengine.com> Pierre, > That's fine for people who write floats with a "." ; but others learn to enter them with "," I have also been looking for a similar Python conversion library. One of my requirements is that such a library must be locale aware (so it can make reasonable assumptions regarding locale properties like thousands separators, decimal points, etc) - either via a locale attribute or by examining the locale of the thread its running under. Malcolm From michael.wieher at gmail.com Wed Mar 5 10:58:24 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 5 Mar 2008 09:58:24 -0600 Subject: Fwd: OT: Failed saving throw In-Reply-To: References: Message-ID: build a tomb? ...or raid one? ---------- Forwarded message ---------- From: Aahz Date: 5 Mar 2008 07:36:37 -0800 Subject: OT: Failed saving throw To: python-list at python.org For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people think we should build a tomb in his honor. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From duvo at tiscali.it Sat Mar 8 13:35:01 2008 From: duvo at tiscali.it (duccio) Date: Sat, 08 Mar 2008 19:35:01 +0100 Subject: del class with recursive list Message-ID: Hello! Will someone have time to tell me why this code don't work as I expect? And what should I do to make the "del n" delete all the lower nodes? Thanks! class Node: def __init__(self): self.childs=[] def appendNode(self, n): self.childs.append(n) def __del__(self): print 'del', id(self) n = Node() for i in range(5): n.appendNode(Node()) for nodes in n.childs: nodes.appendNode(Node()) del n print '--------end--------' gives this: del 10965280 del 10965440 del 10965640 del 10965400 del 10965600 del 10965360 del 10965560 del 10965320 del 10965520 --------end-------- del 10965480 del 10965680 From bernard.chhun at gmail.com Thu Mar 6 23:37:41 2008 From: bernard.chhun at gmail.com (Bernard) Date: Thu, 6 Mar 2008 20:37:41 -0800 (PST) Subject: Looking for very light weight template library (not framework) References: Message-ID: Cheetah! Cheetah! Cheetah! On 6 mar, 20:56, "Malcolm Greene" wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated. > > Malcolm From Lie.1296 at gmail.com Sun Mar 9 08:28:27 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 05:28:27 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: On Mar 9, 6:57?pm, Bryan Olson wrote: > Lie wrote: > > [...]> Soft Exception is an exception that if is unhandled, pass silently as > > if nothing happened. > > [...] > > > Implementation: > > Simple implementation might be done by catching all exceptions at the > > highest level, then filtering which exceptions would be stopped (Soft > > Exception) and which exceptions will be reraised and terminate the > > program (Hard Exception). This is simple and can be easily implemented > > but is inefficient as that means all soft exceptions must bubble > > through its way to the top to find out if it is Soft or Hard. > > If I'm following what you want, that "simple implementation" does > not work. ?If a function, possibly deep in a call stack, raises a > soft exception that no caller above catches, what executes next? The highest possible code that could catch exceptions would have something like this: try: ## Everything is happening inside me except SoftException: pass > Correct me if I'm misunderstanding your idea: You want raising > an un-caught soft exception to be equivalent to a 'pass'; > execution continues as if the 'raise' never happened. > > Catching everything at a high level does nothing like that. The > exception causes execution to leave the function invoking the > raise statement, and abolishes the stack state from the point of > the raise to the point of the catch. The high-level mentioned here is outside our own code, it'll be inside Python's internal. When CPython (or any implementation of Python) sees that a particular exception is raised to a certain point, it'll check whether it is of type SoftException, and if it is, it'll return program state to the place where the exception is raised before. I don't know how Python's exception system works (as I tell you I know next to nothing about Python's internal, although I'm interested to know), so probably if there is any defect in the implementation schemes I mentioned, it is simply caused by my ignorance. > As Python exceptions currently work, "catching all exceptions > at the highest level" is either what Python already does, or > ill-defined nonsense. When an exception is uncaught, there is > no useful "highest level", other than the level at which the > program simply fails. Python *must* terminate execution upon > an unhanded exception, because the program defined no state > from which executions could correctly continue. That's where the difference between Soft Exceptions and Hard Exceptions lies. Soft Exception must be continued while Hard exceptions must terminate programs. Possibly this is impossible at the absolutely highest level, perhaps it should be done at the level that can guarantee > > A more through implementation would start from the raiser inspecting > > the execution stack and finding whether there are any try block above > > it, if no try block exist it pass silently and if one exist it will > > check whether it have a matching except clause. This also circumvents > > a problem that simple implementation have, as described below. > > The described problems do not include the "where should execution > resume" problem, which I think is central to the issue. I didn't mentioned it? I think it's obvious when I say: Execution should resume as if nothing happened, as if there is nothing raised, that means execution resumes at the point after the raise statement. If something was caught, execution isn't resumed and execution continues at the level of the handler (possibly we could also add a "resume" to explicitly resume the statement that was caught) > Correct me > if I've misunderstood: A "soft" exception is one that gets raised > only if some calling frame has arranged to catch it. That could be a way to implement it. And btw, that's a one-line- explanation that hits the right note (although from a different view I initially mentioned). > The if-exception-would-be-unhanded-then-pass logic strikes me as > interesting. It would be a huge change to Python, so I doubt it > will get traction here. ?Still, I'd say it's worth more > consideration and discussion. From sturlamolden at yahoo.no Sun Mar 30 14:02:32 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 30 Mar 2008 11:02:32 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <7aa6175f-cf7c-4006-b140-63bbbc8f1311@u10g2000prn.googlegroups.com> On 30 Mar, 17:16, iu2 wrote: > Due to Competitors... I don't want to expost the language I use Either your comepetitors will figure it out, or they don't care. Using Python can be a major competitive advance. If your competitors are smart enough to realise that, you are in trouble anyway. Most likely your competitors have managers who are technical retards (read: MBAs), who demand their engineers to use whichever technology is over hyped these days. You don't have to worry about those. From castironpi at gmail.com Thu Mar 27 04:02:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 01:02:36 -0700 (PDT) Subject: genetic algors in practical application References: <2242528c-764f-4aa6-a605-f2d05b25484e@u69g2000hse.googlegroups.com> Message-ID: <57267b84-e69a-47c8-9e6c-a501d52c17e8@b64g2000hsa.googlegroups.com> On Mar 26, 9:55?pm, castiro... at gmail.com wrote: > I want to go in to construction. ?However, 'I' means 'newsgroup' and > 'want to go' means 'is'. > > If you had an army of two-micron spiders, could we build something? > Use case is an American skyscraper. > > They have powerful tricks. ?Clearly they can withstand a force. ?These > can withstand more combined, greater-than-minimum. ?What is their > command set? > > Braid. ?Hoist. ?Vine power and waste. ?Charge, double-pump circuit. > Round-trip a dollar. ?I said round. ?(What's the square trip.) > > You do know that the brain has seven trillion atoms, right? ?Mass of > water. > > You know, combine 'muscle fiber' with 'inhibition, excitation' and > 'motor neuron circuit', and you might be on to something, and you > might be right. ?Here's free from Neuro. ?'Each motor neuron synapses > with multiple muscle fibers. .. Cross section through the muscle shows > the distribution of muscle fibers (red dots) contacted by the motor > neuron.' ?Power-- Tools. ?Note that 'synapse' verb. ?Written English > folks. ?'myelin debris' too. > > Is your concern the actual construction of the nanospiders > (interesting side note), or programming it? ?Get a team of programmers > too. ?Who asked for the 'Python d.j. console'? ?Did -uuu- put that on > line. I'd like to destruct a little English: pose, L., from pause. compose, depose, (de-com-pose?), dispose, expose, impose, opose, prepose, propose, repose, transpose, suppose. Stack a structure is a really useful operation. If structures are all guaranteed to compose with one another (is this generators?), you can pop several off, add yours, and push several on. But, where functions are structures, could leave several information. "Sometimes I call my generator twice." I'm a GA, q.e.d. Do I correctly read, 'decline to use send and return of yield'? (Can't be right; it's in there; what do you use it?) What are you guys sending generators? I think a successful machine takes-impressions the environment, and recomposes it: digest, regest, repose. Three cells interface, tower- of-hanoi each other, and on their way. From ds-python-list at sidorof.com Sun Mar 30 18:15:44 2008 From: ds-python-list at sidorof.com (DS) Date: Sun, 30 Mar 2008 15:15:44 -0700 Subject: Licensing In-Reply-To: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> References: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> Message-ID: <47F01110.4000808@sidorof.com> Paul Boddie wrote: > On 29 Mar, 20:24, DS wrote: > >> I'm pretty sure this is the wrong place to ask, but I'm hoping someone >> will point me in the right direction. >> >> I'm getting ready to publish a first open-source project written in >> python. I am planning to use GPLas the license. However, in my code, >> there is a function that I like from Python Cookbook. I would like to >> use it, although I could certainly write a less elegant version that >> would do the same thing. >> > > Note that the Python Cookbook says this about licensing: "Except where > otherwise noted, recipes in the Python Cookbook are published under > the Python license." The link is incorrect, but I presume they mean > this licence: > > http://www.python.org/psf/license/ > > It's generally not recommended to use this licence for anything other > than Python because it mentions the need to reproduce the Python > copyright statement in derived works, which would be nonsense for > anything which isn't the Python distribution. However, one can infer > that the copyright notice specific to the software concerned should be > reproduced, and this is what the original CWI licence says. > > Of course, if a different licence is mentioned on the specific recipe > you're using, you have to observe the terms mentioned in that licence > instead. > > >> So, my options appear to be: >> 1. Don't use it. >> 2. Use it with no comment -- that doesn't seem right. >> 3. Use it with remarks in the code that acknowledge the source. >> 4. Provide a separate licensing page for that function >> along with the GPL for my code. >> >> What is the appropriate course of action here? I'm thinking #3 is >> probably ok. How do others deal with this in an honorable way? In the >> book, it appears that they are saying they don't really care unless >> there is some massive use. >> > > You just need to do what's necessary to satisfy the licence applied to > the code you're using. If that's the Python licence, I would imagine > that reproducing the copyright statement and licence details would be > sufficient, even if your own work is GPL-licensed. > > What I've done when I've released work which incorporates other work > (itself available under a permissive licence) is to include the > copyright statements and the licence text for that other work, but > I've made it clear in the licensing information that the derived work > (my code incorporating the other code) is available under the specific > licence I've chosen, noting that the other work was made available > under a different licence. > > So I suppose that #4 is the closest, but you should be able to assert > that the entire work is GPL-licensed unless the recipe isn't licensed > in a GPL-compatible way, which would open up a range of other issues > that you hopefully won't have to deal with. ;-) > > Paul > > P.S. This isn't anything close to legal advice, so please take other > opinions into account. ;-) > Thanks for taking the time to write. I was also wondering about what ramifications there are from mixing code from other licenses. So, I guess if I was going to do it, I'd have a second license file for this specific function with the license for it. I definitely don't want to be in a situation where credit for someone else's work is not adequately documented. It has happened to me, I know how I felt about it at the time. At this point, I'm thinking that it is not worth messing with. What I am going to do is write a separate function to accomplish the same thing. It's only a few lines long. Of course, having seen the other code I'm forever tainted... There is something a little humorous about reading through the Python Cookbook. You have submissions from all these incredibly smart people with little gems of functions. But, if you actually use them, it's kind of a hassle. On the other hand, I'm glad the book exists, and my memory of the specific details of a function fade over time, but it has/does give my a better understanding in general of how do things. Thanks again. From DoxaLogos at gmail.com Thu Mar 20 11:51:13 2008 From: DoxaLogos at gmail.com (DoxaLogos) Date: Thu, 20 Mar 2008 08:51:13 -0700 (PDT) Subject: wxFormBuilder References: Message-ID: <90b80600-679c-4bb5-9f00-ee083f7ffdff@e60g2000hsh.googlegroups.com> On Mar 20, 8:41 am, sturlamolden wrote: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/http://wiki.wxpython.org/index.cgi/XRCTutorial I've stumbled across it myself and have found it superior so far over the others. I just wish it could also crank out wxPython code. I'm still hoping one day for a form designer closer to Visual Studio's form designer in ease of use area. FarPy GUIE has the right idea, but not near enough widget support. And, I'm not good enough at wxPython yet to be able help either project. From siona at chiark.greenend.org.uk Tue Mar 11 11:21:55 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Mar 2008 15:21:55 +0000 (GMT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: Stefan Behnel wrote: >Just to make this sound a bit less like FUD: my last experience with wxPython >dates back a couple of years (2004/5?), but back then, we used BoaConstructor >in a project, which crashed a bit too often to do real work with it - and with >crashing I mean crashing Python, not just showing us its blank traceback. So >this was definitely a problem either in wxWindows or in wxPython. I spent a couple of years maintaining and developing a series of commercial wxPython-based applications (up until about 18 months ago when I changed job), and I would happily describe wxPython itself as stable enough for production code. The biggest problem I had with it was its failure to be anywhere near as transparently cross-platform as one might be lead to expect. And before you blame wx* for crashes: what platform was this on? Because my experience was that wx on GTK was significantly more prone to glitches than on Windows (through to wxglade being unusably crashy) -- if the underlying toolkit has problems, that's going to be reflected in wx. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From castironpi at gmail.com Sun Mar 9 19:42:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 16:42:27 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: <2b52103a-dfc1-42ce-b572-6a8fb9890e4b@2g2000hsn.googlegroups.com> > > ?os.exec*() will close the current program. > > On *nix, you can use os.fork(). ?According tohttp://effbot.org/librarybook/os.htm, you can use Do you mean, and block for the process to terminate? Or do you mean, do something else in the meantime, perhaps for a certain amount (of meantime)? [Enter event loops. Exeunt.] P.S. What do you do if you think of a comeback for something from a week ago on the newsgroup? P.P.S. Why are you thinking of comebacks on a newsgroup besides alt.flame? P.P.P.S. Anyone read alt.tasteless? From deets at nospam.web.de Sat Mar 1 14:43:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 20:43:34 +0100 Subject: pySQLite Insert speed In-Reply-To: References: Message-ID: <62tpv6F24tml7U1@mid.uni-berlin.de> mdboldin at gmail.com schrieb: > I hav read on this forum that SQL coding (A) below is preferred over > (B), but I find (B) is much faster (20-40% faster) > > (A) > > sqla= 'INSERT INTO DTABLE1 VALUES (%d, %d, %d, %f)' % values > curs.execute(sqla) > > (B) > pf= '?, ?, ?, ?' > sqlxb= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > curs.execute( sqlxb, values ) > > Any intution on why (A) is slower? You most certainly have not found that A is the preferred over B - the opposite is true. Using A will make you vulnerable against SQL-injection-attacks. B OTOH will ensure that the parameters are properly escaped or otherwise dealt with. Regarding the intuition - that depends on what actually happens inside B. If B works in a way that it - converts arguments to strings - escapes these where necessary - builts one SQL-statement out of it - excutes the SQL then B is slower than A because A is just string-interpolation, whereas B is sanitizing + string-interpolation. So it must be slower. But a "sane" DB will instead directly use the SQL passed in B, and transmit the parameter as binary into the backend, resulting in more compact representation + lesser or now marshalling overhead plus possible query parsing overhead reduction due to cached execution plans. Which could explain B being more performant. Diez From rockxuan at gmail.com Tue Mar 18 03:40:15 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:40:15 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <4cf1ae65-953b-4a94-8271-47cf0739bae7@s37g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From mankyd at gmail.com Mon Mar 17 21:36:10 2008 From: mankyd at gmail.com (dave) Date: Mon, 17 Mar 2008 18:36:10 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI Message-ID: Hi All. I've been formulating in my head a simple image editor. I actually started prototyping is some time ago in Java, but am liking Python more and more. My editor will be nowhere near the level of Gimp/ Photoshop, but I do need fast pixel level control and display. For instance, that means no automatic anti-aliasing and that I will be implementing my own line drawing algorithms. I've got the high level architectual aspects of my program down, but am stuck on what graphics API to use. I want a canvas area of adjustable size which users can draw on with as little lag as possible. The canvas area will be composed of layers (i.e. I require an alpha channel) and I need to be able to zoom in and out of it (zoom levels will be at fixed intervals, so this can be simulated if need be.) I started looking at PyGame but realize that I need to integrate a GUI into the whole thing (or integrate the image into the GUI rather) and I didn't see a straightforward way to do that. Of course, I don't even know if PyGame is the right API for the job anyways :P Any thoughts or ideas that could help me get started? Thanks! From dickinsm at gmail.com Thu Mar 13 17:12:09 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 13 Mar 2008 14:12:09 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: <70538854-b63e-4387-9e14-db3b9c211abe@e39g2000hsf.googlegroups.com> On Mar 13, 5:10?pm, Mark Dickinson wrote: > (1, '14') represents 14 should be -14, of course. From jerry.fleming at saybot.com Thu Mar 27 03:41:18 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Thu, 27 Mar 2008 15:41:18 +0800 Subject: do 'os.path' include 'os' for us? Message-ID: Hi, I wrote a python script to list files in a directory but somehow did it wrongly by importing os.path instead of os. To my astonishment, it works just as charm: #!/usr/bin/python import os.path for file in os.listdir('/root/'): print file I was wondering why? os.path doesn't contain listdir, why there is no complaint like 'os: unknown name'? Does this mean, instead of importing os, we can import os.path? Thanks. From mwilson at the-wire.com Tue Mar 18 13:20:56 2008 From: mwilson at the-wire.com (Mel) Date: Tue, 18 Mar 2008 13:20:56 -0400 Subject: globals() using For Loop against Generator References: <599451f4-7687-4d02-b546-a7fbb0f33c8d@h11g2000prf.googlegroups.com> Message-ID: cokofreedom at gmail.com wrote: > if __name__ == '__main__': > > print "Globals (For Loop):" > try: > for i in globals(): > print "\t%s" % i > except RuntimeError: > print "Only some globals() printed\n" > else: > print "All globals() printed\n" > > print "Globals (Generator):" > try: > print "\n".join("\t%s" % i for i in globals()) > except RuntimeError: > print "Only some globals() printed\n" > else: > print "All globals() printed\n" > >>>> Globals (For Loop): >>>> __builtins__ >>>> Only some globals() printed >>>> >>>> Globals (Generator): >>>> __builtins__ >>>> __name__ >>>> __file__ >>>> i >>>> __doc__ >>>> All globals() printed >>>> > > Why is it with a generator I get everything out but with a for loop I > don't? I know that globals is not read-only but I would of expected > the same behaviour from both... Run the for loop in the interpreter, without catching exceptions. You get __builtins__ Traceback (most recent call last): File "", line 1, in RuntimeError: dictionary changed size during iteration Then `print globals()` shows that i has been added to the global namespace. If you run the for loop a second time, after i exists, the loop runs fine. Apparently, generator comprehensions have been optimized so that they don't expose their working variables. The generator comprehension won't add i to the global namespace, so all is well. Mel. From michael.wieher at gmail.com Wed Mar 12 16:29:35 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 12 Mar 2008 15:29:35 -0500 Subject: string / split method on ASCII code? Message-ID: Hey all, I have these annoying textilfes that are delimited by the ASCII char for << (only its a single character) and >> (again a single character) Their codes are 174 and 175, respectively. My datafiles are in the moronic form X<>Z I need to split on those freaking characters. Any tips on how to make split work with these things? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kveretennicov at gmail.com Sun Mar 30 11:28:33 2008 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sun, 30 Mar 2008 18:28:33 +0300 Subject: Create executable from executable with py2exe In-Reply-To: References: Message-ID: <4660fe300803300828r4ddc88a3mbe9270e157b2d7b6@mail.gmail.com> On Sat, Mar 29, 2008 at 3:23 PM, wrote: > Hello, > > Is there any example how can I create executable ... with py2exe > Check out PyBuilder's source code (http://pybuilder.sourceforge.net/). -- kv -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Fri Mar 14 15:19:18 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 14 Mar 2008 12:19:18 -0700 (PDT) Subject: Handling global variables (Newbie) References: Message-ID: <613c51a0-d928-46b1-a04f-d0bc9fdcf453@a70g2000hsh.googlegroups.com> On Mar 13, 4:25 am, "David S" wrote: > Hi, > > I have an error occurring at > self.build_root = os.path.abspath(os.path.split(__file__)[0]) > > The error states 'NameError: global name '__file__' is not defined' > > In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get > defined? > Do you perhaps mean '__name__'? From michael.wieher at gmail.com Fri Mar 14 10:27:52 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 14 Mar 2008 09:27:52 -0500 Subject: request for Details about Dictionaries in Python In-Reply-To: <47DA8833.9020205@fmed.uba.ar> References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> Message-ID: 2008/3/14, Gerardo Herzig : > > Saideep A V S wrote: > > >Hello Sir, > > > > Thank You a ton. I was looking for this function. As far what I've > >understood from the "Shelve" module is that, there would be no memory > >wastage and the whole transactions would be done from and to the file we > >specify. Am I right?. > > > > My actual task is to build a basic dictionary for two languages and > store > >word and its meaning in another language in a file and must be able to > >access it through on-disk Hash tables. as these would be saving memory > space > >for a huge data. > > > >so, I hope shelve is the right one, I am searching for., I shall try out > >with the function. > > > > > >Thank You once again. > > > >Cheers, > >Saideep > > > > > > > Plz remember allways reply to the python group also. They are many many > many ones to know more than i do! > Well, i dont quite think that it would be "no memory wastage", since > when you read/write from disk, there is memory involved in the process. > > I *really* believe that, when data goes huge, a *real* database (like > postgres, and others) has to come and play the game. > > Hope that helps > > Gerardo > > > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm not sure if a well-written file/seek/read algorithm is faster than a relational database... sure a database can store relations and triggers and all that, but if he's just doing a lookup for static data, then I'm thinking disk IO is faster for him? not sure -------------- next part -------------- An HTML attachment was scrubbed... URL: From josef.pktd at gmail.com Sun Mar 16 13:00:12 2008 From: josef.pktd at gmail.com (joep) Date: Sun, 16 Mar 2008 10:00:12 -0700 (PDT) Subject: Spaces in path name References: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> Message-ID: <708a66a7-da8f-4d44-824d-8a25203030f7@n58g2000hsf.googlegroups.com> One more try (using popen instead of call is not necessary for these cases, but I want to see the behavior of popen): shell=True and executable and at least one argument with spaces does not work: --------------------------------------------------------------------------------------------------------------------- p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \Copy of cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out3.txt"], shell=True, stdout=subprocess.PIPE) causes: 'C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin\Copy' is not recognized as an int ernal or external command, operable program or batch file. the following all work: ================ without shell=True, and executable and at least one argument with spaces ----------------------------------------------------------------------------------------------------------- p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \Copy of cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out4.txt"], stdout=subprocess.PIPE) with shell=True, and executable without spaces, even if two arguments with spaces ------------------------------------------------------------------------------------------------------------------------ p = subprocess.Popen(["copy", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out2.txt"], shell=True, stdout=subprocess.PIPE) with shell=True, and executable without spaces, even if two arguments with spaces ------------------------------------------------------------------------------------------------------------------------ but here shell=True is not necessary p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out5.txt"], shell=True, stdout=subprocess.PIPE) without shell=True, and executable and at least one arguments with spaces ------------------------------------------------------------------------------------------------------------- p = subprocess.Popen([r"C:\Programs\GnuWin32\GetGnuWin32\gnuwin32\bin \Copy of cp.exe", r"C:\Temp\temp with spaces\test out.txt", r"C:\Temp\temp with spaces\test out4.txt"], stdout=subprocess.PIPE) My conclusions: ============ Assuming shell=True is only required for build-in shell commands, non of which has spaces. There is no problem, if you know when *not* to use shell=True: * More than two arguments with spaces are never problem, as long as the executable does not have spaces * If shell=True is required, then the executable is a build-in shell command, which does not contain spaces, and, therefore, has no problems * If you use a non-build in executable, then don't use shell=True. This works correctly even if the executable and at least one additional argument have spaces. It took a lot of time to figure this out, but now at least I know, how to construct the call to subprocess.Popen, so that it works in the cases I used it so far. Josef From duncan.booth at invalid.invalid Sat Mar 29 14:19:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Mar 2008 18:19:36 GMT Subject: Problem with sqlite References: Message-ID: aiwarrior wrote: > When i execute this the database doesn't get filled with anything and > the program stays running in memory for ever. That's odd, when I execute the code you posted I just get "NameError: global name 'sqlite3' is not defined". You should always try to post the complete actual code you are using, not just some random part of it. > The print statement is just a Unicode string that would get to the > database if i stated it in the add_entry function as a constant > string. It's a really weird problem that i dont seem to understand why > it's working out this way. > Are you absolutely certain of that? If you use print to try to debug the value of an object you should usually use repr: print repr(audio['album']) What MP3 library are you using? You have forced a commit after every insert. This slows down sqlite A LOT. I get about 400 insertions each minute with your code (just inserting fixed strings) but if I remove the conn.isolation_level assignment and add a single commit at the end I get in excessive of 20000 per second. Are you sure you just didn't wait long enough? From hexusnexus at gmail.com Mon Mar 31 21:16:33 2008 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Mon, 31 Mar 2008 18:16:33 -0700 (PDT) Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> <7b94bd75-f3ef-4e5c-9939-c431947e1ae1@l42g2000hsc.googlegroups.com> Message-ID: <1871e241-48b1-474b-9c0b-76443545a172@e23g2000prf.googlegroups.com> On Mar 31, 4:04 pm, Rick Dooling wrote: > On Mar 31, 2:39 pm, hexusne... at gmail.com wrote: > > > How do I receive input from the command line in Python? > > As long as we are all guessing, do you perhaps mean raw_input? > > my_name = raw_input("What is your name? ") > What is your name? Rick >>> my_name > > 'Rick' Yeah, sorry for being vague. Thanks. From zubeido at yahoo.com.br Wed Mar 12 09:59:59 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Wed, 12 Mar 2008 06:59:59 -0700 (PDT) Subject: Mutagen File Problem Message-ID: <81d8d48f-5496-4ca6-a525-c7b927436d4d@d62g2000hsf.googlegroups.com> Hi i'm having a IO error saying a file does not exist even though i perform a isFile() check. Can you help me out figuring what is wrong? Thanks in advance from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 for root, dirs, files in os.walk('''C:\\Documents and Settings\\pneves\ \Music\\''', topdown=False): for name in files: joined = os.path.join(root, name) if (name[-3:] == 'mp3' ): audio = MP3(joined, ID3=EasyID3) if not audio.has_key('album') and os.path.isfile(joined): print os.path.join(root, name) I get an error as following: IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\pneves\\Music\\Naked Music - Miguel Migs - Colorful You\ \Miguel Migs - Colorful you - Full album\\Miguel Migs - Colorful you - Cd 2 -Mixed and mastered by J. Mark Andrus\\7 - Miguel Migs feat. Lisa Shaw - You Bring Me Up (Main Vocal Mix).mp3' From deets at nospam.web.de Sat Mar 22 09:32:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 14:32:34 +0100 Subject: Prototype OO In-Reply-To: <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> Message-ID: <64kg3pF2avnseU1@mid.uni-berlin.de> John Machin schrieb: > On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: > >> [1] Just one example:http://docs.mootools.net/Class/Class.js > > Mootools being something a coworker might use? > I don't understand the question. Diez From danb_83 at yahoo.com Wed Mar 26 18:23:31 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 26 Mar 2008 15:23:31 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <808dff98-c2a5-4697-b805-9482c2f11b8f@s12g2000prg.googlegroups.com> On Mar 26, 5:12 pm, Thomas Dybdahl Ahle wrote: > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: > > Why does python create a reference here, not just copy the variable? > > Python, like most other oo languages, will always make references for =, > unless you work on native types (numbers and strings). The = operator behaves exactly the same way for mutable and immutable types. From exxfile at hotmail.com Mon Mar 24 15:13:04 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 12:13:04 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> Message-ID: <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> > > > i ?have ?come across my first exeption using randrange . The exeption > > is " no such ?attribute " in ?module random > > > platform ?is xp ?home ?and the python ?build is activestate 2.5 > > Welcome aboard! > > There's definitely a randrange function in the random module, so > something else must be wrong. To get the most out of this list and > minimize wasted bandwidth, the most effective way usually consists of > copying and pasting: > 1. The offending code (or just the relevant part if it's too big). > 2. The full traceback of the raised exception. > > Regards, > George Hwere is the complete traceback ! >>> The word is: index Traceback (most recent call last): File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger \__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger \debugger.py", line 631, in run exec cmd in globals, locals File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, in import random File "F:\Documents and Settings\Mark\My Documents\random.py", line 13, in distributions on the real line: AttributeError: 'module' object has no attribute 'randrange' >>> Why would it say it can't find the function ? Mark From kay.schluehr at gmx.net Sun Mar 9 00:05:50 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 8 Mar 2008 21:05:50 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: <852f558f-c0e7-4bdd-afae-3870fe90c8e0@34g2000hsz.googlegroups.com> On 9 Mrz., 04:51, Lie wrote: > A more through implementation would start from the raiser inspecting > the execution stack and finding whether there are any try block above > it, if no try block exist it pass silently and if one exist it will > check whether it have a matching except clause. This also circumvents > a problem that simple implementation have, as described below. This will not be easy in particular in the presence of inheritance and dynamism. There is no way to statically decide whether an exception BException has the type AException and will be caught by the except clause in try: BLOCK except AException, e: print "SoftException %s caught"%e A feasible solution was to invert the try...except statement and creating a continuation. catch AException, a: print "SoftException A: %s"%a catch BException , b: print "SoftException B: %s"%b ... in: BLOCK Here each SoftException is raised initially when a catch clause is entered and a continuation is created that returns to the catch block of the raised SoftException if required. When a SoftException is raised within BLOCK a lookup will be made and if a corresponding SoftException was found that was raised by a catch-clause the current control flow will be suspended and the continuation is called. From michael.wieher at gmail.com Fri Mar 7 16:38:14 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 15:38:14 -0600 Subject: I cannot evaluate this statement... In-Reply-To: <13t3cms4fn6318e@corp.supernews.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> <13t3cms4fn6318e@corp.supernews.com> Message-ID: The parentheses are there for a reason 2008/3/7, Steven D'Aprano : > > On Fri, 07 Mar 2008 12:38:11 -0800, waltbrad wrote: > > > The script comes from Mark Lutz's Programming Python. It is the second > > line of a script that will launch a python program on any platform. > > > > import os, sys > > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > > > That makes sense. Because the first condition is true and 'python.exe' > > is true. So the next comparison is 'python.exe' or 'python' Well, > > python.exe is true. So that value is returned to pyfile. > > > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > > == 'win' as false. So, the next comparison should be 'False' or > > 'python' -- This is because 'and' returns the first false value. But, > > again, on linux pyfile evaluates to python.exe > > Not on my Linux box. > > > >>> import os, sys > >>> sys.platform > 'linux2' > >>> (sys.platform[:3] == 'win' and 'python.exe') or 'python' > 'python' > > > > > Where am I going wrong. And when will this statment make pyfile > > evaluate to 'python' ? > > When the first three letters of sys.platform aren't 'win'. > > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.pulver at gmail.com Fri Mar 14 18:37:59 2008 From: alex.pulver at gmail.com (Alex) Date: Fri, 14 Mar 2008 15:37:59 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> Message-ID: <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> On Mar 13, 6:21 pm, Carl Banks wrote: > On Mar 13, 7:02 am, Bruno Desthuilliers > > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > Alex a ?crit : > > (sni) > > > > First of all thanks all for answering! > > > > I have some environment check and setup in the beginning of the code. > > > I would like to move it to the end of the script. > > > Why ? (if I may ask...) > Sure, because of a readability (similar to function declarations in C). > > > But I want it to > > > execute first, so the script will exit if the environment is not > > > configured properly. > > > If you want some code to execute first when the script/module is loaded, > > then keep this code where it belongs : at the beginning of the script. > > I concur with Bruno's recommendation: stuff you want to do first > should come first in the script. Things like BEGIN blocks hurt > readability because you can't identify where execution begins without > reading the whole file. > > Having said that, one thing that often happens in Python scripts is > that all the functions are defined first, then the script logic > follows. So you could put the meat of your script in a function, then > the "BEGIN" stuff after that functions: > > def run_script(): > # > # script contained in this long function > # > > # Then test preconditions here... > if os.environ["HELLO"] != "WORLD": > sys.exit(2) > > # Then call the run_script functions > run_script() > > But having said THAT, I don't recommend you do that with > preconditions. If the script has a quick early exit scenario, you > really ought to put that near the top, before the function > definitions, to clearly show to a human reader what is necessary to > run the script. > > Carl Banks Hi, Maybe i was a little bit unclear... I meant that i wanted to do something like this: #!usr/bin/env python check_env() from subprocess import * class MyClass: # Class definition def check_env(): # Code if __name__ == "__main__": # Script logic The thing is, as i saw, that Python doesn't recognize the "check_env()" function before it reaches the "def" statement. I need the check to be done before the subprocess import, because our customers use different Python versions, some of them do not have subprocess module. So i want to exit if i see that Python version being used doesn't have that module. The solution to that problem with what you suggested could be wrapping the subprocess import with function, am i correct? From john106henry at hotmail.com Mon Mar 31 13:05:01 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 10:05:01 -0700 (PDT) Subject: Of qooxdoo, qwt, and Python Message-ID: <28f7384f-b8d1-430d-9e0d-389ebae7eefd@e10g2000prf.googlegroups.com> I was searching for a way to redevelop a desktop Pythoncard based program into a web-application. I understand what need to be done for all of the non-GUI code. For the GUI capabilities, I stumbled across a package call qooxdoo (http://qooxdoo.org/). It appears to provide the GUI capabilities I need. Then I saw that there is qwt - which allows you to write qooxdoo code in pure Java. Since I don't know Java (or don't want to know), is there a similar path I can take using Python? Regards, From cokofreedom at gmail.com Mon Mar 10 12:19:11 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 10 Mar 2008 09:19:11 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> Message-ID: <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> The trick in the case of when you do not want to guess, or the choices grow too much, is to ask the user to tell you in what format they want it and format according to their wishes. Neatly avoids too much guessing and isn't much extra to add. From toolmaster at 163.com Sun Mar 16 23:54:01 2008 From: toolmaster at 163.com (WaterWalk) Date: Sun, 16 Mar 2008 20:54:01 -0700 (PDT) Subject: About reading Python code Message-ID: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Hello. I wonder what's the effective way of figuring out how a piece of python code works. With C I often find it very useful to be able to run the code in step mode and set breakpoints in a debugger so I can watch how the it executes, how the data change and how the code jumps from one function to another. But with Python, the debugger is a little primitive. The default IDLE doesn't even allow me to set a breakpoint. When the code is long, I am often lost in it. So I'm curious how to read code effectively. I agree that python code is clear, but when it becomes long, reading it can still be a hard work. From sjmachin at lexicon.net Thu Mar 20 17:04:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Mar 2008 14:04:51 -0700 (PDT) Subject: Is this valid ? References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> Message-ID: On Mar 21, 1:09 am, Rolf van de Krol wrote: > John Machin wrote: > > Of course. You can chain comparisons as much as you like and is > > (semi-)sensible, e.g. > > Hmm, 'of course' is not the correct word for it. 'Of course' was short for: Given alternative hypotheses H0 = "Python feature" and H1 = "bug in Python compiler", one's instinct would be go with H0 if a snap decision were required without time to refer to the docs. > Although the Stef > Mientki would probably be able to find it in the documentation it is not > as simple as you might think. > Most languages interpret a == b == 2 as (a == b) == 2, or throw an error > because this syntax is not valid. Indeed, some languages do ludicrous things with precedence of relational operators. A compiler when faced with something like: a == b and c == d has at least two choices: (1) (a == b) and (c == d) # seems rather useful (2) (a == (b and c)) == d which doesn't seem very useful at all. Pascal makes choice (2), which is valid syntax only if b and c are booleans and if comparisons of booleans are allowed (and IIRC Pascal didn't allow this). > The fact that python understand the > obvious meaning of this code, is quite unique to Python, as far as I know. Indeed, Python isn't "some/most languages", which is why we're here. From geert at nznl.com Sat Mar 15 14:19:22 2008 From: geert at nznl.com (geert) Date: Sat, 15 Mar 2008 11:19:22 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Message-ID: <72659e53-bd22-4c58-b579-bdbcaf8c5fed@s19g2000prg.googlegroups.com> On Mar 14, 11:49?am, "Robert Rawlins" wrote: > Geert, > > I've not seen this issue myself, however, you might get a little more luck > asking over on theMySQLdbmailing list as this seems to be more an issue > with the db than your python code. It might be worth posting your question > there too as it'll heighten your chances of finding someone who knowsMySQLdbinside out. > > http://mail.python.org/mailman/listinfo/db-sig > > Cheers, > > Robert > > -----Original Message----- > From: python-list-bounces+robert.rawlins=thinkbluemedia.co... at python.org > > [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co... at python.org] > On Behalf Of geert > Sent: 14 March 2008 10:36 > To: python-l... at python.org > Subject: Huge problem gettngMySQLdbto work on my mac mini running Macosx > 10.5 Leopard > > Hi all, > > I have a mac mini running maocosx 10.5 leopard I want to deploy a > django project on. My backend is MySQL, and I have it running as a 64- > bit app. Of course, apache2 is also running as 64-bit. > > MySQLdbinstalls with the usual warnings after applying the various > patches I found here and there. These patches consist of altering > _mysql.c and site.cfg. > > Basically, my problem boils down to this: > > ? File "", line 1, in > ? File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line > 19, in > ? File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in > > ? File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 6, in > __bootstrap__ > ImportError: dynamic module does not define init function (init_mysql) > > Has anyone solved this? I been hunting around for 2 weeks now, and my > deadline is looming grimly on the horizon :) > > Geert > > --http://mail.python.org/mailman/listinfo/python-list Thanks, Robert. I'm on the MySQLdb list, and am working on a solution. And I've subscribed to the list you gave. Geert From furkankuru at gmail.com Tue Mar 25 08:55:03 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:55:03 +0200 Subject: My python interpreter became mad ! In-Reply-To: References: Message-ID: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> Most probably X-Spam added itself to your path. you should look at your PATH and PYTHONPATH environment variables. On Tue, Mar 25, 2008 at 1:40 PM, John Machin wrote: > On Mar 25, 10:05 pm, Benjamin Watine wrote: > > Yes, my python interpreter seems to became mad ; or may be it's me ! :) > > > > I'm trying to use re module to match text with regular expression. In a > > first time, all works right. But since yesterday, I have a very strange > > behaviour : > > > > $ python2.4 > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import re > > X-Spam-Flag: YES > > X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on > w3hosting.org > > X-Spam-Level: ********************** > > X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, > > MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, > > > > RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, > > > > URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, > > URIBL_WS_SURBL autolearn=failed version=3.1.7-deb > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/etc/postfix/re.py", line 19, in ? > > m = re.match('(Spam)', mail) > > AttributeError: 'module' object has no attribute 'match' > > >>> > > > > What's the hell ?? I'm just importing the re module. > > No you're not importing *the* re module. You're importing *an* re > module, the first one that is found. In this case: your own re.py. > Rename it. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Mar 20 05:52:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Mar 2008 10:52:58 +0100 Subject: Script Request... References: <64ccfbF2bbfckU1@mid.uni-berlin.de> Message-ID: <64eqg5Fuih70U1@mid.uni-berlin.de> some one wrote: > Thanks Diez, I found some docs and examples on urllib2. Now how do i > search the string I get from urllib2, lets say I put it in "myURL", How > do I search for only Numbers and ".'s" in the "#.#.#.#" pattern. That > is all I am interested in with all the data retrieved. Just the IP > Address from amongst a bunch of data that I have no use of currently. > > I would I write a pattern matching function to extract only the IP > address from "myURL"? Pattern-matching can be done using regular expressions, they are available in the module "re". Diez From deets at nospam.web.de Sun Mar 9 09:21:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 14:21:43 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: Message-ID: <63i6j9F2793buU1@mid.uni-berlin.de> Lie schrieb: > I'm asking about people in c.l.py's opinion about a _probably_ very > Pythonic way of doing something if such features is implemented. It is > to be known that I'm not a Python expert and actually relatively new > to Python programming, so probably I'm just not thinking pythonic > enough yet or this feature might already exist somewhere in a > different name. > Anyway, I'm just asking for opinions, tell me problems I haven't > foreseen, or whether such things would be hard to implement, or > whether you think the idea is great or plain bad (and why). > > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. For example, if a variable turns into NoneType, > it'll raise Soft Exception that it have become NoneException, > programmers that wants to handle it can handle it with a try...except > block while programmers that doesn't care about it (or know it won't > be a problem to his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in > a way that Hard Exception must be handled at all cost or the program > will be terminated while Soft Exception allow programmers not to > handle it if they don't want to. Is this soft-exception implemented anywhere, so that one can see what experiences and best practices have evolved around using it? Diez From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Mar 3 12:31:55 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 03 Mar 2008 18:31:55 +0100 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Message-ID: <632r0bF25q334U1@mid.individual.net> blaine wrote: > So my question is this - what is the easiest way to interface to > this "serial" device? > > I don't imagine a straight read() and write() command to > /dev/ttyusb0 is the most efficient (if it even works) It doesn't only work, it's the preferred way (if you don't use advanced wrappers like pyserial). For the basics see http://www.easysw.com/~mike/serial/serial.html > especially since we would need to set a baud rate. What is the relationship between read/write, the baud rate, and efficiency? The serial port is configured using POSIX terminal interface (termios). Regards, Bj?rn -- BOFH excuse #89: Electromagnetic energy loss From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Mar 31 07:30:55 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 13:30:55 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> <65anbqF2fg18bU1@mid.individual.net> <87r6drjss4.fsf@physik.rwth-aachen.de> Message-ID: <65c0bfF2ffipiU1@mid.individual.net> Torsten Bronger wrote: > Doesn't KNode support UTF-8? Well, it should, but automatic encoding detection doesn't always seem to work (or does it even have one?). I'm looking for a different (faster) newsreader anyway. > Who wants to minimize the number of keypresses? We're not Perl > after all. ;-) Sure, but I also don't want to enter fancy unicode operators. I'm using Python on some computers that even don't support unicode. > However, I'm quite sure that when Unicode has arrived almost > everywhere, some languages will start considering such characters > in their core syntax. This should be the time when there are widespread quasi-standardised input methods for those characters. Regards, Bj?rn -- BOFH excuse #154: You can tune a file system, but you can't tune a fish (from most tunefs man pages) From barry at alltc.com Sun Mar 16 11:20:25 2008 From: barry at alltc.com (Barry Hawkins) Date: Sun, 16 Mar 2008 08:20:25 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 9:18?am, a... at pythoncraft.com (Aahz) wrote: > In article <5bd37c10-af5d-4254-8799-49c762673... at n58g2000hsf.googlegroups.com>, > Bruce Eckel ? wrote: > > >If the following seems unnecessarily harsh, it was even more harsh for > >me to discover that the time and money I had spent to get to my > >favorite conference had been sold to vendors, presenting me as a > >captive audience they could pitch to. > > Ouch. ?I'm probably one of the few organizers currently paying much > attention to c.l.py -- because I'm also one of the few who's not at > PyCon. ?We debated this extensively before going ahead, and we decided > it was worth an experiment. ?If your feedback is at all representative, > this won't happen again, I assure you. [...] > >I believe that this year's Pycon organizers suffered from inexperience > >and naivete, because they didn't know that some vendors will ask for > >anything just to see how far they can push it. > > Actually, it was our idea to offer something in return for the > sponsorship. [...] Ashz, thanks for offering some explanation. It is my sincere hope that the organizers will look upon the aforementioned experiment as a failed one. I shared the same perception as Bruce; most "keynotes" and lightning talks were anemic vendor pitches that really gutted the spirit of what I experienced last year. In meeting new people this year, I have had more than one first-time attendee ask me if PyCon lightning talks "are always like that." I have also heard from a couple of folks I would consider PyCon elders who were not happy with what lightning talks became this year. I was one of the 15 or so persons who had a lightning talk that ended up in overflow for the Saturday talks. At the end of the regular time, we were all brought forward to be told that we would not do overflow talks. Standing there in the huddle, I looked around, and it appeared that we were mostly non-vendors. It was pretty crummy to see that real PyCon lightning talks had been sacrificed in favor of subjecting Pythonistas to rather dry vendor presentations. Some of the vendor presenters even had a tone that sounded like "my boss is making me do this." PyCon lightning talks are the stuff of legend; I implore the organizers to learn well from this costly experiment, and let's not go there again. Ever. > >On top of that, the quality of the presentations was unusually low. > >I'd say that 80% were not worth going to -- there were definitely some > >good ones, but it was a lot of pain to discover them. > > Just to make sure, you're talking about the vendor presentations, right? [...] I'll step out and say that some of the non-vendor talks were quite weak. The most severe was a talk on Stackless where the original speaker was unable to be here and someone got up and clicked through the slide deck at a very fast pace. I thought the person had stepped in at the last minute, but later learned that he had volunteered with a couple of weeks' notice. Additionally, the original speaker had Andrew Dalke's *exact* slide deck from his Stackless talk last year. One first-time attendee told me over lunch that he was going to recommend to his employer that they not pay to send their programmers to PyCon next year based on what he had seen in this year's talks. I know that's an unpleasant message, but in the interest of preserving PyCon's quality, I'm willing to be the jerk of a messenger. > >I know what the argument for the results of Pycon 2008 will be: we > >needed the money. My answer: it's not worth it. If this is what you > >have to do to grow the conference, then don't. If the choice is > >between selling my experience to vendors and reducing the size of the > >conference, then cut the size of the conference. Keep the quality of > >my experience as the primary decision criteria, or I'll stop coming. > > That was our intention. ?Apparently it didn't work for you. ?I'll wait > for more feedback before I make up my mind about whether your experience > was common. [...] Hopefully the surveys and this thread will be filled with feedback from the participants. Also, check http://twitter.com/pycon for some further anecdotal evidence. From castironpi at gmail.com Sun Mar 16 19:55:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 16:55:44 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> <9b959898-ed57-47b9-8158-7ca6a321e705@u69g2000hse.googlegroups.com> Message-ID: On Mar 16, 1:29?pm, "Gabriel Genellina" wrote: > En Sat, 15 Mar 2008 20:08:05 -0200, escribi?: > > > > > > > On Mar 15, 8:18?am, Bryan Olson wrote: > >> castiro... at gmail.com wrote: > >> > Newbie question: ?Can you write to the 'file-like object' a pickle, > >> > and receive it intact-- as one string with nothing else? > > >> Yes, but there's a world of gotcha's. Sockets do not recognize > >> record boundaries, and Python's 'pickle' has holes one's enemies > >> could drive a truck through. Still, you can pickle, write, read, > >> un-pickle, and get back your data intact. > > >> > I want to know because I want to send two pickles. > > >> "Two pickles" sounds like a tasty snack, but also suggests you may > >> be playing hopscotch in a minefield. This is a helpful group. Give > >> us more to go on, and you are likely to receive thousands of > >> dollars worth of consulting for free. > > > It depends on the situation. ?How generally applicable is this: > > > fun ListenerGeneric( port, factory, arrivedfun ): > > > which calls 'factory' on socketA.accept (and loops again), then > > arrivedfun( stringA ) on message complete detection. ??. ?It should > > start itself in a separate thread. > > > Or is this any better: > > > for x in connections(): > > ? ?startnewthreadwith x: > > ? ? ? for y in messages( x ): > > ? ? ? ? ?arrivedfun( y ) > > This looks like a SocketServer + ThreadingMixIn + a RequestHandler (your ? > factory). > But as B. Olson already pointed, pickles are unsafe. Worse, it's not that ? > someone could send a specially crafted pickle that could execute some ? > arbitrary code: you're blindy executing whatever you receive! > xmlrpc may be a good alternative in some cases. I see. Just transmit a binary and execute that. Make sure to have handles to your program publicly accessible too. I execute this. From arkanes at gmail.com Mon Mar 17 11:07:46 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 17 Mar 2008 10:07:46 -0500 Subject: wxPython graphics query (newbie) In-Reply-To: References: Message-ID: <4866bea60803170807q6a0c008frcd290a96160674df@mail.gmail.com> On Mon, Mar 17, 2008 at 7:03 AM, Thomas G wrote: > I am exploring wxPython and would be grateful for some help. > > It is important to me to be able to slide words and shapes around by > dragging them from place to place. I don't mean dragging them into a > different window, which is what 'Drag and Drop' has come to mean, just > moving them around within a canvas-like space. > > This is easy using Tkinter. Can anybody offer me a tiny, very simple > example of how it would be done in wxPython, please? > > To make sure I convey what I'm looking for, here is what it looks like > using Tkinter, written very simply. What I'm looking for is the same, > quite simple functionality expressed in wxPython, again written very > simply so that I can easily understand it. > See the floatcanvas and OGL examples in the wxPython demo. From castironpi at gmail.com Tue Mar 18 17:27:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 14:27:44 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> Message-ID: <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> > > > On Mar 17, 1:31 pm, Duncan Booth wrote: > > > >> A common explanation for this is that lists are for homogenous > > >> collections, tuples are for when you have heterogenous collections i.e. > > >> related but different things. > > > > I interpret this as meaning that in a data table, I should have a list > > > of records but each record should be a tuple of fields, since the > > > fields for a table usually have different forms whereas the records > > > usually all have the same record layout. > > >>> b in b > False That's actually interesting. >>> a= [] >>> a.append( a ) >>> a [[...]] >>> a in a Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp From tms at zeetix.com Mon Mar 17 08:01:59 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Mon, 17 Mar 2008 08:01:59 -0400 Subject: String To List Message-ID: <006301c88826$b46127e0$0200a8c0@TMSMAIN> It's too bad your inner data items are delimited with an apostrophe (') instead a double-quote ("). If they were double-quote, you could do something as simple as: Given: a = '["xyz", "abc"]' import simplejson answer = simplejson.loads(a) There may be an incantation to simplejson that allows you to use a different delimiter. You might be able to provide your own decoder, using the "cls=" argument (but I don't think that lets you change the delimiter string). Failing that, and depending on your regex/Python prowess, you might be able to change the "decoder.py" file within simplejson to do what you want. As others have observed, a lot depends on the input data. If it really is as simple as your example, then the following may do the trick: a = "['xyz', 'abc']" answer = map(lambda each: each.strip()[1:-1], a[1:-1].split(',')) This at least has no "eval", and so you need not fear applying it to unknown data (it will just break). The answer that works best for you may perhaps be somewhere in the middle. "Girish" wrote in message news:e6035b85-d00c-4a35-951d-8287a99f7d8b at s8g2000prg.googlegroups.com... >I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? > Thanks for the help... > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Wed Mar 26 13:24:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 14:24:50 -0300 Subject: last mouse movment or keyboard hit References: Message-ID: >> En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler >> escribi?: >> >> >> I would like to get the time of the most recent human activity like a >> >> cursor >> >> movement or a key hit. >> >> Does anyone know how I can get this back to start some action after >> >> there >> >> has been no activity for X minutes/seconds? En Wed, 26 Mar 2008 13:59:15 -0300, azrael escribi?: > You can use wxPython. Take a look on the DemoFiles that you can > download also from the site. I remember that there has been a demo of > capturing mouse coordinates and also one example about capturing Which > key has been pressed at which time. (Please don't top post) Does wx catch all events in all other applications? My understanding is that the OP wants a global detection, not restricted to a single application. -- Gabriel Genellina From bjorn.m.meyer at gmail.com Fri Mar 21 11:26:52 2008 From: bjorn.m.meyer at gmail.com (Bjorn Meyer) Date: Fri, 21 Mar 2008 09:26:52 -0600 Subject: script won't run using cron.d or crontab In-Reply-To: <47E36B46.4050002@jouy.inra.fr> References: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> <47E36B46.4050002@jouy.inra.fr> Message-ID: <73b543b30803210826i735e54f6jafc5ff73dbe0e8a7@mail.gmail.com> Thank you for your reply. This is pretty much what I found from my digging around. I asume this can still be done. Is there an easy way to determine what needs to be added to the environment? Bjorn On Fri, Mar 21, 2008 at 2:01 AM, Robert Bossy wrote: > Bjorn Meyer wrote: > > I appologize if this been discussed previously. If so, just point me > > to that information. > > > > I have done a fair bit of digging, but I haven't found a description > > of what to actually do. > > > > I have a fairly lengthy script that I am able to run without any > > problems from a shell. My problem is, now I am wanting to get it > > running using crontab or cron.d. It seems that running it this way > > there is a problem with some of the commands that I am using. For > > instance "commands.getoutput" or "os.access". I am assuming that there > > is something missing within the environment that cron runs that fails > > to allow these commands to run. > > If anyone has any information that would help, it would be greatly > > appreciated. > Hi, > > From a shell, type: > man 5 crontab > and read carefully. You'll realize that a croned script does not inherit > from the user shell's environment. > > Cheers, > RB > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Mon Mar 31 19:08:27 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 1 Apr 2008 07:08:27 +0800 Subject: troll poll In-Reply-To: Message-ID: George Sakkis wrote: > On Mar 31, 1:46 pm, Marc 'BlackJack' Rintsch wrote: > >>> More specifically, who can create a bigger mess on c.l.py? (check >>> one) >> >>> [ ] - Xah Lee >>> [X] - castironpi >> >> Xah Lee's postings might be trolls but sometimes they spark some >> really interesting and serious subthreads, while the nonsense of >> castironpi is just irritating noise. > > Which is exactly why there are rarely any replies to his random > gibberish, so I would say that he/she/it has almost no effect on > c.l.py. Yet I wish plonking was possible through Google groups. I find classifying all their posts as spam works fairly well. Tim Delaney From deets at nospam.web.de Tue Mar 4 05:29:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Mar 2008 11:29:13 +0100 Subject: tools to install not in python tree? References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: <634mjoF268j1dU1@mid.uni-berlin.de> commander_coder at hotmail.com wrote: > Hello, > > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ and some programs that I want in ~/public_html/ . I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). But as I understand it setup only targets > installing below sys.prefix; is that right? You can use setuptools. And it will install to any path available on sys.path. So if you define PYTHONPATH pointing to some folder, you can use setuptools to install the code (eggs) as well as create script entry-points, so if the same path is part of PATH they will become available on the command line. Diez From mcepl at redhat.com Sat Mar 1 18:13:21 2008 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 02 Mar 2008 00:13:21 +0100 Subject: sqlite3 adaptors mystery Message-ID: Hi, I am in the process of creating a small script for filling the sqlite3 database with data from rather large XML-RPC query (list of many bugs from the Red Hat Bugzilla) and I would love to use adaptors and converters for some data types which I am missing. I have this test script (made hopefully pretty faithfully from the documentation): #!/usr/bin/python import sqlite3 def adapt_boolean(bol): if bol: return "True" else: return "False" def convert_boolean(bolStr): if str(bolStr) == "True": return bool(True) elif str(bolStr) == "False": return bool(False) else: raise ValueError, "Unknown value of bool attribute '%s'" \ % bolStr sqlite3.register_adapter(bool,adapt_boolean) sqlite3.register_converter("boolean",convert_boolean) db = sqlite3.connect("test.db") cur=db.cursor() cur.execute("create table test(p boolean)") p=False cur.execute("insert into test(p) values (?)", (p,)) p=True cur.execute("insert into test(p) values (?)", (p,)) cur.execute("select p from test") print cur.fetchall() And I would expect to print on output representation of bool values, i.e., something like [False,True] However, when running this program it seems converter doesn?t seem to work, because I get: [matej at viklef dumpBugzilla]$ rm test.db ; python testAdaptors.py [(u'False',), (u'True',)] [matej at viklef dumpBugzilla]$ There is probably something quite obvious what I do incorrectly, but I just don't see it. Could somebody kick me in the right direction, please? Thanks a lot, Mat?j Cepl From furkankuru at gmail.com Tue Mar 25 08:51:30 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:51:30 +0200 Subject: Inheritance question In-Reply-To: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <3a4a8f930803250551n851e556n1b799409a4b1812f@mail.gmail.com> In the derived class init you set self.id to 2 so when you call getid method it just returns self.id which is now 2. you can use another variable name. On Tue, Mar 25, 2008 at 1:44 PM, Tzury Bar Yochay wrote: > given two classes: > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = Foo.getid() > b = self.id > return '%d.%d' % (a,b) > > While my intention is to get 1.2 I get 2.2 > I would like to know what would be the right way to yield the expected > results > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn at u.washington.edu Mon Mar 31 12:18:06 2008 From: donn at u.washington.edu (Donn Cave) Date: Mon, 31 Mar 2008 09:18:06 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> <65701aF2erbbsU1@mid.uni-berlin.de> <7xr6dta93p.fsf@ruckus.brouhaha.com> Message-ID: In article <7xr6dta93p.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Select blocks until the data is ready, while with AIO the i/o happens > completely in the background and your process gets an interrupt when > the i/o completes. Also, with select based i/o, usually the kernel > reads data from the external device into a system buffer, and then you > do a read system call that copies the data from the system buffer to > your buffer. AIO can be set up so the i/o happens directly into your > buffer, avoiding the extra copying. You can also initiate a bunch of > different i/o events with a single system call, avoiding some context > switches. > > http://www.ibm.com/developerworks/linux/library/l-async/ > > describes select as "asynchronous, blocking" as opposed to AIO which > is asynchronous and nonblocking. Other descriptions I've seen reserve > "asynchronous i/o" for AIO-like schemes. It's just a terminological > thing. kqueue(2) on MacOS X mentions an EVFILT_AIO option. It isn't supported on that platform, but maybe that's a vestige of some other platform that does support "asynchronous, blocking" with aio -- as VAX/VMS did (and presumably still does), with event flags. Donn Cave, donn at u.washington.edu From deets at nospam.web.de Mon Mar 10 17:21:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 22:21:44 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: <63ln3cF273fndU1@mid.uni-berlin.de> > > Java is more portable than most other languages, especially if your app needs a gui. Depending on what GUI you want, python is at least as portable - Tkinter is available for lots of platforms. And swing as a GUI plain sucks - there is a reason for SWT. But that needs to be installed separately and per platform. Additionally, Java is not Python :) Diez From benhoyt at gmail.com Tue Mar 18 23:47:02 2008 From: benhoyt at gmail.com (benhoyt) Date: Tue, 18 Mar 2008 20:47:02 -0700 (PDT) Subject: Is there a way to get __thismodule__? Message-ID: Is there a way to get __thismodule__ in Python? That is, the current module you're in. Or isn't that known until the end of the module? For instance, if I'm writing a module of message types/classes, like so: class SetupMessage(Message): number = 1 class ResetMessage(Message): number = 2 class OtherMessage(Message): number = 255 nmap = { # maps message numbers to message classes 1: SetupMessage, 2: ResetMessage, 255: OtherMessage, } Or something similar. But adding each message class manually to the dict at the end feels like repeating myself, and is error-prone. It'd be nice if I could just create the dict automatically, something like so: nmap = {} for name in dir(__thismodule__): attr = getattr(__thismodule__, name) if isinstance(attr, Message): nmap[attr.number] = attr Or something similar. Any ideas? (A friend suggested class decorators, which is a good idea, except that they're not here until Python 2.6 or Python 3000.) Cheers, Ben. From newsgroup898sfie at 8439.e4ward.com Thu Mar 20 16:43:20 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Thu, 20 Mar 2008 16:43:20 -0400 Subject: putting text through pager Message-ID: <9suab5-jvs.ln1@ID-262785.user.uni-berlin.de> Hi, I'm trying to print some variable through a pager (i.e. 'less') on a linux system. My attempt was this: ====== snip here ====== import subprocess def put_through_pager(displaystring): less_pipe = subprocess.Popen(\ 'less', shell=True, \ stdin=subprocess.PIPE).stdin less_pipe.write(displaystring) less_pipe.close() def main(): put_through_pager(longstring) longstring = """ Lorem ipsum dolor sit amet,... http://www.lipsum.com/ """ main() ====== snip here ====== That doesn't work however: first of all, it only flashes the text for a fraction of a second, and secondly, after I run the program my terminal is broken, not echoing whatever I type back to me. Any suggestions for putting text through a pager from Python? This is strictly on a linux system, of course. Thanks, Michael From jef.mangelschots at gmail.com Tue Mar 4 16:38:41 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 4 Mar 2008 13:38:41 -0800 (PST) Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> <3319005c-98b9-44a0-96dc-72db45f2ae27@z17g2000hsg.googlegroups.com> Message-ID: <5bf892c0-ec5a-425a-91d3-580ae66ebbbf@h11g2000prf.googlegroups.com> > on windows using python 2.4. ??? I was on Python 2.4.3 and it gave me that problem. I upgraded to 2.4.4 and it works. thanks for the tip. From lists at js3d.co.uk Tue Mar 25 14:46:57 2008 From: lists at js3d.co.uk (Jules Stevenson) Date: Tue, 25 Mar 2008 18:46:57 -0000 Subject: setattr what is the parent object? Message-ID: <005601c88ea8$9a936520$0600a8c0@laptop> I'm trying to use setattr to dynamically name and layout gui wx widgets, this is all fine and dandy until I've run up against something where I simply don't know what the object is, please see the amended **don't know** in the following code. class MyFrame2(wx.Frame): def __init__(self, *args, **kwds): blah blah blah __do_layout(mayaVars) def __do_layout(self, mayaVars): main_boxSizer = wx.BoxSizer(wx.VERTICAL) for pDisplay in range(len(mayaVars.primary)): setattr=(**don't know**,"r_gridBagSizer_"+mayaVars.primary[pDisplay], wx.GridBagSizer(vgap=0, hgap=0)) Without all the dynamic gumpf, the statmement looks like this: r_gridBagSizer = wx.GridBagSizer(vgap=0, hgap=0)) All the other UI elements are created on 'self' but the sizers don't seem to 'belong' to anything - what should I use when this is the case? Many thanks, and apologies if I'm being dense Jules -------------- next part -------------- An HTML attachment was scrubbed... URL: From hasnihon.support at gmail.com Mon Mar 24 09:51:40 2008 From: hasnihon.support at gmail.com (hasnihon.support at gmail.com) Date: Mon, 24 Mar 2008 06:51:40 -0700 (PDT) Subject: Serving another web site which requires authentication Message-ID: Hi, I need your suggestions about the topic. Actually, I'm not sure where to start but basically, I want to make something like; (I have an account on a site which requires log-in) - I'll be logged-in to that site with my account in my server. - And when a user connects to my site, I'll forward him/her to that site, using my account even if he/she doesn't have an account on that site... probably, I need to develop a proxy to do this, but I'm not sure... (I use python + django) I really appriciate your ideas. From babycode at gmail.com Mon Mar 3 15:41:58 2008 From: babycode at gmail.com (babycode at gmail.com) Date: Mon, 3 Mar 2008 12:41:58 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: <5df8299b-8278-4bdd-b63b-66518c1ac0fc@x30g2000hsd.googlegroups.com> > Please tell me what code you think it's stunning. Pexpect is (almost) pseudocode is (almost) poetry to my ears. And there's a lot of narrative in it as well: http://pexpect.svn.sourceforge.net/viewvc/*checkout*/pexpect/trunk/pexpect/pexpect.py?content-type=text%2Fplain From mail at timgolden.me.uk Sun Mar 16 10:09:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:09:30 +0000 Subject: Spaces in path name In-Reply-To: <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> Message-ID: <47DD2A1A.2040609@timgolden.me.uk> joep wrote: > > Tim Golden wrote: > >> subprocess.call ([ >> >> r"C:\Program Files\Adobe\Acrobat 5.0\Reader\acro reader.exe", >> >> r"C:\Program Files\Adobe\Acr >> obat 5.0\Reader\plug_ins.donotuse\Annotations\Stamps\abc def.pdf" >> >> ]) >> >> Can you confirm that something equivalent *doesn't* work on your >> setup? Or have I misunderstood your point earlier? I'd really >> like to get to the point where we can definitively state: this >> works (and possibly: that doesn't). >> >> Thanks >> TJG > > This works without problems for me on Windows XP, Python 2.4.3 OK. That's good, at least. > I often had problems understanding subprocess.Popen and getting it to > work. I usually have to go back-and-forth between worked examples, I admit. [... snip problem with Popen ...] Ah. I assumed that .call simply handed off to Popen. I'll do some looking into that in case I need to add a warning to the webpage. (And, maybe, a bug report). Thanks for following this up. TJG From wiqd at codelounge.org Thu Mar 6 11:23:25 2008 From: wiqd at codelounge.org (Greg Armer) Date: Thu, 6 Mar 2008 18:23:25 +0200 Subject: Does python support working with password protected zip files? In-Reply-To: <1204819422.29123.1240935267@webmail.messagingengine.com> References: <1204819422.29123.1240935267@webmail.messagingengine.com> Message-ID: <2ef52b180803060823w4bdcedd1ra81f68ba1e34654b@mail.gmail.com> On 3/6/08, Malcolm Greene wrote: > I'm new to Python and trying to figure out how to read and write to > password protected zip files. > > I can work with plain zip files no problem. > > I've googled this topic and am coming up empty except for a post on > Nabbler.com that seemed to imply that password protected zip files > may(???) be supported in Python 2.6 and ads for a commercial Windows > (only) zip component from chilkat.com. > > Any suggestions? Hi Malcolm, I just had to do some with with this myself and eventually resorted to simply using a popen() call to the system unzip utility with the -Ppass command line option. def _unzipdata(self): print "[~] Processing zip file %s..." % self.zipfile # Create temporary directory os.mkdir('_temp') # Unzip password protected zipfile to _temp os.chdir('_temp') os.popen("unzip -P%s ../%s" % (self.password, self.zipfile), "r") return True While this is not ideal, i could not find any other alternatives. Hope that helps. -- Greg Armer Entropy has us outnumbered. From mauriceling at acm.org Tue Mar 18 03:14:32 2008 From: mauriceling at acm.org (Maurice LING) Date: Tue, 18 Mar 2008 07:14:32 GMT Subject: Multiple Submits in HTML Forms - Cherrypy Message-ID: <47df6bd4$1@news.unimelb.edu.au> Hi, Assuming that I have this code for Cherrypy 3 class Welcome: def index(self): return """

""" index.exposed = True How should I write "btn_handler" so that it will perform different actions when different button is pressed? Thanks in advance Cheers maurice From atom.anderson at gmail.com Thu Mar 20 12:54:13 2008 From: atom.anderson at gmail.com (atom.anderson at gmail.com) Date: Thu, 20 Mar 2008 09:54:13 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> Message-ID: Okay! I just read this entire thread to be caught up. I am a first time PyCon-goer (as my previous post states). Because I have nothing to compare this year's experience to, I'll give it to you as I saw it. None of this is intended as a rant, (except maybe the lightning talk section;) Gripes ------ Numero Uno: The Lightning Talks. The best lightning talk I saw was the one where the guy's code didn't work and he couldn't believe it or simply move on with his presentation, it was hilarious but I felt bad for the guy. I have to be honest, I had heard GREAT things about the lightning talks and I went to the session expecting to hear something great, or at least feel the same sense of community I felt when discussing python in education (i'm a student) or its use in the industry. I went with a friend who also attended the conference from my school and sat down expectantly. I noticed the guy was trying to set up a powerproint (or OOo or whatever) presentation and I simply couldnt believe it. A powerpoint presentation? Pictures? text? preparation? That doesn't sound like lightning at all. It sounds like, "slow-tning" talks. Methodically prepared sales-pitch presentations on johnny q. coder's latest commercial triumph. I thought these talks were spur of the moment, community-delivered and off the cuff? In my opinion, i don't believe that lightning talks should include the option of using presentation software, maybe thats too restrictive, but it seems to me that we'd be treated to much more grassroots or user-given talks rather than sponsor-given ones. I could just be ranting. Number Two: Presenters should be required to post their slides on the web site / schedule before they are permitted to present. We want 'em, they've got 'em, and I was in more than one session where simply having uploaded them to the PyCon schedule would have saved the presenters bacon when it came time for their laptop to die or something else. I realize that these presentations are fluid and change (often the night before!) but a failsafe like this wouldn't hurt anyone. Number Three: Too much code, not enough concept. Presenters this one's for you. I can't count the number of presentations I attended where the presenter would click through three slides of pycode just to show us a two or three-line snippet that illustrated their point. Worse yet, it was often at the bottom of the screen so no one but the front row could see it. This goes for text two. I saw some great presentations as well, and they had limited text on each slide. The last thing your audience wants to see is a slide drenched in text of any kind. You only have 30 minutes (or less). Show us brief couplets of code for syntax sake. We don't care about code, we care about the concept. If it were an hour lecture you could go through pages of code and itd be great, but when we can't even read the whole slide before you move on then its too much. Number Four: What's a BOF? Noob here. My first pycon and I didnt know the terminology. Shocker huh? Heh, well i figured it out into the first day, but still didn't quite get the concept. Around day two or three i started attending these and learned just how cool they are. With the RAPID growth pycon has shown over the last few years, perhaps a little session at the beginning to help the newcomers or a "Terminology" page in the handbook would be helpful? Praise ------ As a student attending his first pycon, i must say it was AWESOME. Depending on the sessions i chose to attend, i learned all KINDS of useful stuff. Pyglet, Stackless (i'm willing to give it a chance despite the mediocre presentation), RE, pysight and more. Coming from a small school out west, the experience of visiting a convention where a community actually existed was an incredible experience. That was probably the best part of the conference was seeing that there truly was a programming community and meeting other like-minded people and being able to finally discuss things of programming importance with them. I guess thats what we had hoped to see more of in the lightning talks. We enjoyed the EXPO as well and a couple of our graduating attendees have nabbed phone interviews with companies that were represented there. I am definitely planning on returning to pycon next year, if only to rub shoulders with other python programmers again and *hopefully* attend a conference that has learned from any mistakes this year and become an even better event for 2009. adam From deets at nospam.web.de Thu Mar 27 03:45:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 08:45:25 +0100 Subject: counting using variable length string as base In-Reply-To: References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <6511l0F2d9knfU1@mid.uni-berlin.de> Grimsqueaker schrieb: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? No. Just put a list() around it. Diez From gagsl-py2 at yahoo.com.ar Sat Mar 15 04:25:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 06:25:39 -0200 Subject: Handling global variables (Newbie) References: Message-ID: En Thu, 13 Mar 2008 02:25:12 -0200, David S escribi?: > I have an error occurring at > self.build_root = os.path.abspath(os.path.split(__file__)[0]) > > The error states 'NameError: global name '__file__' is not defined' > > In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ > get > defined? If you type your code directly into IDLE (or the commmand line Python interpreter) __file__ doesn't even exist; it only has any sense when the code is read from an actual file. Save your code on disk, let's say you name it example.py Then you can execute it using > python example.py from the command line; from inside IDLE, go to File | Open, locate example.py, press F5 -- Gabriel Genellina From nagle at animats.com Mon Mar 24 02:01:10 2008 From: nagle at animats.com (John Nagle) Date: Sun, 23 Mar 2008 23:01:10 -0700 Subject: Testing for an empty dictionary in Python - documented? In-Reply-To: References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <47e74162$0$36389$742ec2ed@news.sonic.net> Bryan Olson wrote: > D'Arcy J.M. Cain wrote: >> John Nagle wrote: >>> What's the cheapest way to test for an empty dictionary in Python? > >> Try this: >> >> if dict: > > D'Arcy is right; that's the way to go. I'll add that 'dict' is the name > of the built-in class, so an instance is usually best named something else. Is this a documented language feature? The only references to this in the spec are vague. In "3.4.5 Emulating container types" there's "Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context." That's as close as the reference manual seems to come. There are mentions that in Python 3K, __nonzero__ should be replaced by __bool__. But I'm not finding anything in the spec that actually says that sequences, used in a Boolean context, are False if empty and True if nonempty. In fact, "5.8 Comparing Sequences and Other Types" in the Tutorial ("Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name.Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc.") might lead one to think that this wasn't the case. John Nagle From ggpolo at gmail.com Thu Mar 27 07:31:03 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 08:31:03 -0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: <47EB7F55.8090909@gmail.com> References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> <47EB7F55.8090909@gmail.com> Message-ID: 2008/3/27, Alex9968 : > Guilherme Polo wrote: > > 2008/3/27, Alex9968 : > > > >> Guilherme Polo wrote: > >> > 2008/3/26, Alex9968 : > >> > > >> >> Hi all, > >> >> > >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over > >> >> using visual GUI designers), so my question is which other GUI toolkits > >> >> have similar functionality. > >> >> > >> > > >> > The geometry manager isn't related to using GUI designers tools at > >> > all. And each toolkit has it's own way to do the things, wxPython uses > >> > sizers, PyGtk uses containers. > >> > > >> > >> Well, the geometry manager isn't *directly* related to using GUI > >> designers, but as Pack arranges widgets automatically, using GUI > >> designers isn't required, while with geometry managers that don't, GUI > >> designers are necessary (if you start placing widgets programmatically, > >> you'll end up reinventing something like Tkinter's Pack or Grid geometry > >> manager). I hope I can be understood clearly this time ;-) > >> > > > > Not at all, can't understand your point yet. GUI designers aren't just > > for placing widgets, they also will keep the interface design > > separated from your code. > > > > I do not want to separate interface from code and I do not experience > the need to use GUI designers. > It is your opinion, it seems I can't change it for now but I hope you reconsider it for the future. > Pack arranges widgets perfectly, and it's very complex to do the same > without it, both in code and in GUI designer. For some level of "perfect", of course. Also, I can't understand why you say it is hard to do such thing in a gui designer tool, which tool have you tried ? Maybe you are not familiar with them yet, and that could be the problem. > I wish toolkits I use to > be able to place widgets one after another automatically. > They all make this possible, you could try doing something on another toolkit you are interested and check if it does what you want. > > > >>>> Secondly, I like the detailed widget borders configuration possible in > >>>> > >> >> Tkinter, which can be used to tweak GUI look, and wonder if other > >> >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) > >> >> look in Windows, but I'm afraid it can be quite different (and ugly) on > >> >> other platforms. > >> >> > >> > > >> > You sure can, but differently. > >> > > >> > >> I suppose any toolkit allows setting parameters like "no border", "flat > >> border" and "3d border", but which ones can set ANY type of border to > >> ANY widget like Tkinter does? For example set GROOVE border to buttons > >> and text widgets (instead of traditional wide raised/lowered borders), > >> which is cool (in my opinion). > >> > >> > > > > The widgets subclass some base class, which contains some common > > methods which could be the border and relief for example. > > In the case of PyGtk, border > > width is controlled at Container, so most widgets will have this > > feature, but the relief style of the widget is not common to all > > widgets so you will need to check this one (Button has it). > > In wxPython, widgets will subclass Window, which has all you want and more. > > But PyQt doesn't seem to care much about this, you can change the > > widget to flat (if it makes sense to that widget have setFlat method) > > but not much related to the borders. > > You could recheck your use-cases and see if they are acceptable. > > > > > >> >> (The reason I ever consider moving from Tkinter is some inconveniences, > >> >> involving for example window scrolling, plus its smaller amount of > >> >> widgets compared to some other toolkits, plus its (rumored) ugly look on > >> >> certain environments. I will not necessary change the toolkit, but I > >> >> have to consider it) > >> >> > >> >> > >> > > >> > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > >> > Tkinter for upcoming GSoC. For now you could try using Tile extension, > >> > and update to Tk 8.5. If you don't want to use extensions, then you > >> > will have to wait or change the toolkit for now. > >> > > >> > >> Thanks. I haven't heard of Tile before, now I will keep this in mind. > >> You forgot to mention WHAT you're planning to solve ;-) , so I have to > >> add that Tile is modernization of Tk widgets (so it fixes ugly look). > >> > >> > > > > WHAT I'm planning to solve, quote from my own paragraph: > > "I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > > Tkinter for upcoming GSoC." > > > > I would like to add the possibility to use Ttk widgets into tkinter, > > providing you have Tk 8.5. It would solve the problem of "not enough > > widgets" and the other one of "being ugly" mainly. Tk 8.5 also > > auto-fixes some other problems, it provides smooth-scrolling for the > > text widget, for example. But keep in mind that using Tk 8.5 in Python > > is not yet supported (but possible). > > > > I understood you. I added that sentence just to make it clear for anyone > reading this. Your participation is appreciated greatly, thank you. > -- -- Guilherme H. Polo Goncalves From benhoyt at gmail.com Wed Mar 19 14:18:06 2008 From: benhoyt at gmail.com (benhoyt) Date: Wed, 19 Mar 2008 11:18:06 -0700 (PDT) Subject: Is there a way to get __thismodule__? References: Message-ID: <94d3d055-7bc3-408d-9a44-c4adb1307712@e6g2000prf.googlegroups.com> Wow -- thanks, guys. And who said Python only gives you one way to do things. :-) Metaclasses, globals(), and __subclasses__. Thank Duncan for the __subclassess__ tip -- I didn't know about that. I'd totally overlooked globals(). It's exactly what I was looking for -- thanks, Peter. And I like your is_true_subclass() helper function too. I must say, I found it a bit weird that the first argument to issubclass() *has* to be a class. I would have thought issubclass(42, MyClass) would simply return False, because 42 is definitely not a subclass of MyClass. But I guess "explicit is better than implicit", and being implicit here might mask bugs. globals() feels like the "right" way to do what I want -- fairly simple and direct. Metaclasses are cool, but probably a touch too complicated for this. And __subclassess__ seems a bit undocumented and perhaps implementation-defined. Cheers, Ben. From ebenze at hotmail.com Sun Mar 16 09:53:03 2008 From: ebenze at hotmail.com (Eric B.) Date: Sun, 16 Mar 2008 09:53:03 -0400 Subject: Cannot build Python 2.4 SRPM on x64 platform Message-ID: Hi, For those on several python lists, I appologize in advance for cross-posting, but I'm really not sure which list is best to ask for assistance with this. Currently, I am trying to build the python2.4 SRPM from Python.org on a RHEL4 x64 platform, but the build is failing with a very non-descript error message. .... + cd /var/tmp/python2.4-2.4-root/usr/bin + mv -f pydoc pydoc2.4 + cd /var/tmp/python2.4-2.4-root/usr/bin + mv -f idle idle2.4 + echo '#!/bin/bash' + echo 'exec /usr/bin/python2.4 /usr/lib64/python2.4/idlelib/idle.py' + chmod 755 /var/tmp/python2.4-2.4-root/usr/bin/idle2.4 + cp -a Tools /var/tmp/python2.4-2.4-root/usr/lib64/python2.4 + rm -f mainpkg.files + find /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f + sed 's|^/var/tmp/python2.4-2.4-root|/|' + grep -v -e '_tkinter.so$' error: Bad exit status from /var/tmp/rpm-tmp.55639 (%install) RPM build errors: user jafo does not exist - using root group jafo does not exist - using root user jafo does not exist - using root group jafo does not exist - using root Bad exit status from /var/tmp/rpm-tmp.55639 (%install) If I try to run /var/tmp/rpm-tmp.55639 manually from the prompt manually after the rpmbuild fails, it runs properly to completion. If I try to comment out that last line (find /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f | sed 's|^/var/tmp/python2.4-2.4-root|/|' | grep -v -e '_tkinter.so$' ) that seems to be causing the script to fail, rpmbuild finishes, but with several error msgs, complaining about missing files in the lib64 directories: + rm -f /tmp/python-rpm-files.4859 + /usr/lib/rpm/brp-compress + /usr/lib/rpm/brp-strip + /usr/lib/rpm/brp-strip-static-archive + /usr/lib/rpm/brp-strip-comment-note Processing files: python2.4-2.4-1pydotorg error: File not found by glob: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.txt error: File not found by glob: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.py* error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/pdb.doc error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/profile.doc error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/curses error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/distutils error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/encodings error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/plat-linux2 error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/site-packages error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/test error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/xml error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/email error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/compiler error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/bsddb error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/hotshot error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/logging error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-old Executing(%doc): /bin/sh -e /var/tmp/rpm-tmp.95118 + umask 022 + cd /usr/src/redhat/BUILD + cd Python-2.4 + DOCDIR=/var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + export DOCDIR + rm -rf /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + /bin/mkdir -p /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + cp -pr Misc/README Misc/cheatsheet Misc/Porting /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + cp -pr LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 + exit 0 Processing files: python2.4-devel-2.4-1pydotorg error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/config Processing files: python2.4-tools-2.4-1pydotorg Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(VersionedDependencies) <= 3.0.3-1 Requires: /bin/bash /bin/sh /usr/bin/env Finally, if I try searching for any files in the usr/lib64/python2.4/lib-dynload or usr/lib64/python2.4/idlelib directories manually, I don't see any files at all in those directories. To me, it seems as though python is either not installing the files in the right places, or the script is searching for files in the wrong places, but I'm completely guessing here. Has anyone managed to build Python2.4 on a RHEL4 x64 system? Can anyone point me in the right direction to complete this build successfully? I'm hoping to get the binaries built so I can contribute them to the python.org site so others don't need to go through these problems in the future. Any hints / ideas / suggestions / guidance that anyone can provide would amazing, because I'm completely out of ideas at this point. Like I said, I'm trying to build this on a RHEL4 x64 system, with all latest updates. Thanks so much! Eric From brad at 16systems.com Fri Mar 28 23:51:07 2008 From: brad at 16systems.com (Brad) Date: Fri, 28 Mar 2008 23:51:07 -0400 Subject: some path issues on windows In-Reply-To: <13urddulja4t7fa@corp.supernews.com> References: <13urddulja4t7fa@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Fri, 28 Mar 2008 22:31:07 -0400, Brad wrote: > >> When reading a file into a list that contains windows file paths like >> this: >> >> c:\documents and settings\brad\desktop\added_software\asus\a.txt >> >> I get a list that contains paths that look like this: >> >> c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt > > > What makes you think that there are doubled backslashes in the string? > Look at this: Sorry, my mistake... when testing with prints, printing the list itself showed double backslashes \\ in the paths, but when printing each path individually, it's only one back... should have tested more before posting. My apologies. Brad From cantabile.03 at wanadoo.fr Sat Mar 15 16:54:25 2008 From: cantabile.03 at wanadoo.fr (Unknown) Date: 15 Mar 2008 20:54:25 GMT Subject: replace string in a file Message-ID: <47dc3781$0$869$ba4acef3@news.orange.fr> Hi, I've got this code : cb = open("testfile", "r+") f = cb.readlines() for line in f: rx = re.match(r'^\s*(\d+).*', line) if not rx: continue else: serial = rx.group(1) now = time.time() today = time.strftime('%Y%m%d00', time.localtime(now)) todayVal, serialVal = long(today), long(serial) if todayVal <= serialVal: todayVal = serialVal + 1 else: todayVal += 1 line = string.replace(line, serial, "%d" %todayVal) cb.write(line + "\n") print 'Updated serial from "%s" to "%d"' % ( serial, todayVal ) break cb.close() I was expecting to replace the old value (serial) with the new one (todayVal). Instead, this code *adds* another line below the one found... How can I just replace it? Thanks for your help :-) From ptmcg at austin.rr.com Sat Mar 22 21:30:20 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Mar 2008 18:30:20 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> Message-ID: <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> Oof, I see that you have multiple "Layer" entries, with different qualifying labels. Since the dicts use "Layer" as the key, you only get the last "Layer" value, with qualifier "PRBOUNDARY", and lose the "Layer" for "METAL2". To fix this, you'll have to move the optional alias term to the key, and merge "Layer" and "PRBOUNDARY" into a single key, perhaps "Layer/PRBOUNDARY" or "Layer(PRBOUNDARY)" - a parse action should take care of this for you. Unfortnately, these forms will not allow you to use object attribute form (md.Layer.lineStyle), you will have to use dict access form (md["Layer(PRBOUNDARY)"].lineStyle), since these keys have characters that are not valid attribute name characters. Or you could add one more level of Dict nesting to your grammar, to permit access like "md.Layer.PRBOUNDARY.lineStyle". -- Paul From wahreviews at gmail.com Sat Mar 22 18:17:52 2008 From: wahreviews at gmail.com (wahreviews at gmail.com) Date: Sat, 22 Mar 2008 15:17:52 -0700 (PDT) Subject: Make Money Using Paypal Get Paid Instantly References: Message-ID: <4563a8f0-7f25-46d9-a039-e5cd5d11c523@i29g2000prf.googlegroups.com> On Mar 12, 12:10?pm, ayt46g6b wrote: > Make Money Using Paypal Get Paid Instantly > > Make 1k-5k every week > without leaving the > comfort of your own home > > Click Here to Make Money Using Paypal > and Get Paid Instantlyhttp://freetrafficbuzz.com/recommends/cashdirectly Interesting. What is being suggested here is against Paypal's acceptable usage policy. Consult with a real person who has been successful before you jump into a scam like this and above all, make sure that person is going to be there to support you the whole way whether you just need to ask a question from time to time or need a great deal of help. http://workfromhomereviews.org/ From Dodin.Roman at gmail.com Tue Mar 25 08:42:03 2008 From: Dodin.Roman at gmail.com (hellt) Date: Tue, 25 Mar 2008 05:42:03 -0700 (PDT) Subject: Need help with OptionParser Message-ID: <0a225d25-c544-49d9-9e56-8ecd2d0f7928@s13g2000prd.googlegroups.com> today i've decided to use optionparser instead of GetOpt and unfortunately i've got an error which i cant handle my pice of code: from optparse import OptionParser def main(): usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option("-f", "--file", dest="filename", help="executable filename", metavar="FILE") parser.add_option("-b", "--bighosts", action="store_true", dest="bighosts", default=False, help="with big hosts [default: %default]") (options, args) = parser.parse_args() if not options.bighosts: print parser.print_usage() if __name__=="__main__": main() if i run test3.py without any arguments, i wait for generated help, but i see the following Usage: test3.py [options] None why None? Where are all of my options From ptrk.mcm at gmail.com Sat Mar 29 17:21:48 2008 From: ptrk.mcm at gmail.com (ptrk) Date: Sat, 29 Mar 2008 14:21:48 -0700 (PDT) Subject: cProfile for python 2.4 References: Message-ID: <384dd8ae-859a-4ad0-9191-44b6c9036210@m36g2000hse.googlegroups.com> On Mar 28, 3:50 pm, David Pratt wrote: > I'd like to compile cProfile for python 2.4. Where can I get it to do > this? I realize it is part of python 2.5. Many thanks. can you use cProfile's predecessor, profile? http://docs.python.org/lib/module-profile.html From python.list at tim.thechases.com Wed Mar 19 06:57:04 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 05:57:04 -0500 Subject: a beginner, beginners question In-Reply-To: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> References: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Message-ID: <47E0F180.3010505@tim.thechases.com> > class example: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > def method(self): > print "method ... :" > print self.foo > print self.bar > > if __name__ == "__main__": > obj = example This makes "obj" a synonym for "example". You want to instantiate your "example" class with obj = example("Some foo", "Some Bar") > obj.foo = "var1" > obj.bar = "var2" which then makes these two lines either unneeded or an overwriting of the initialization > obj.method and this returns a function, not the results of the function. You need to call it obj.method() -tkc From darcy at druid.net Wed Mar 26 17:14:57 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 Mar 2008 17:14:57 -0400 Subject: Daylight savings time problem In-Reply-To: <13uldfrl46tf728@corp.supernews.com> References: <13uldfrl46tf728@corp.supernews.com> Message-ID: <20080326171457.8627f24f.darcy@druid.net> On Wed, 26 Mar 2008 20:45:47 -0000 Grant Edwards wrote: > On 2008-03-26, Salsa wrote: > > > I'm sorry, but could you be more specific? How exactly should I use UTC? > > In my experience, using local time for timestamps is always a > big mistake, so I presume he meant don't use local time in the > file names -- put the UTC date/time in the filenames. Yes. One problem with using local times is that once a year you can overwrite files. The best option is to use the number of seconds since EPOCH and let programs convert it to UTC or local time as required. -- 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 http Sun Mar 2 11:36:28 2008 From: http (Paul Rubin) Date: 02 Mar 2008 08:36:28 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> Message-ID: <7xr6etgk1f.fsf@ruckus.brouhaha.com> Lie writes: > You hit the right note, but what I meant is the numeric type > unification would make it _appear_ to consist of a single numeric type > (yeah, I know it isn't actually, but what appears from outside isn't > always what's inside). That is clearly not intended; floats and decimals and integers are really different from each other and Python has to treat them distinctly. > > Try with a=7, b=25 > > They should still compare true, but they don't. The reason why they > don't is because of float's finite precision, which is not exactly > what we're talking here since it doesn't change the fact that > multiplication and division are inverse of each other. What? Obviously they are not exact inverses for floats, as that test shows. They would be inverses for mathematical reals or rationals, but Python does not have those. > One way to handle this situation is to do an epsilon aware > comparison (as should be done with any comparison involving floats), > but I don't do it cause my intention is to clarify the real problem > that multiplication is indeed inverse of division and I want to > avoid obscuring that with the epsilon comparison. I think you are a bit confused. That epsilon aware comparison thing acknowledges that floats only approximate the behavior of mathematical reals. When we do float arithmetic, we accept that "equal" often really only means "approximately equal". But when we do integer arithmetic, we do not expect or accept equality as being approximate. Integer equality means equal, not approximately equal. That is why int and float arithmetic cannot work the same way. From manlio_perilloNO at SPAMlibero.it Wed Mar 26 14:58:40 2008 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Wed, 26 Mar 2008 18:58:40 GMT Subject: Beta testers needed for a high performance Python application server References: Message-ID: Il Tue, 25 Mar 2008 20:31:39 +0000, Minor Gordon ha scritto: > Hello all, > > I'm looking for beta testers for a high performance, event-driven Python > application server I've developed. > > About the server: the front end and other speed-critical parts of the > server are written in portable, multithreaded C++. The back end is an > embedded CPython interpreter. The server is much faster than anything in > pure Python, and it can compete with C servers (including e.g. lighttpd > for file workloads) or outdo them (e.g. anything behind Apache) until > CPython consumes a single processor. Have you tried my WSGI implementation for Nginx? http://hg.mperillo.ath.cx/nginx/mod_wsgi/ Its not a general purpose solution, but it can be of interest. > On the Python side it supports WSGI > (the server can handle the static and dynamic requests of MoinMoin with > a handful of lines), the DB API with blocking calls offloaded to a > connection in a separate thread (MySQL, SQLite supported), Google's > ctemplate, gzipping responses, file caching, reading and writing to URIs > as a client, AJAX integration, debugging as a Python extension, and a > lot of other features. The core Python API is event-driven, using > continuations like Twisted but much cleaner (continuations are any > callables, there are no special objects anywhere). The Python back end > also supports Stackless Python so all of the continuation machinery can > be hidden behind tasklet switching. > I have recently added support for asynchronous application. There are two examples: an application that execute a query to PostgreSQL and an application that execute an HTTP request with pycurl: http://hg.mperillo.ath.cx/nginx/mod_wsgi/file/tip/examples/nginx-postgres- async.py http://hg.mperillo.ath.cx/nginx/mod_wsgi/file/tip/examples/nginx-curl.py Note that ngx.poll extension is still experimental. > [...] Manlio Perillo From sturlamolden at yahoo.no Sat Mar 22 09:43:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 06:43:33 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: On 22 Mar, 09:31, Bryan Olson wrote: > Even a hash function that behaves as a random oracle has > worst-case quadratic-time in the algorithm here In which case inserts are not amortized to O(1). From martin at v.loewis.de Fri Mar 7 02:43:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 07 Mar 2008 08:43:36 +0100 Subject: Python GDB Wrapper In-Reply-To: References: Message-ID: <47d0f228$0$17725$9b622d9e@news.freenet.de> > Has anyone does this before ? Even some basic idea or code as to how > to proceed would be great. Have you seen Misc/gdbinit? Regards, Martin From mdboldin at gmail.com Mon Mar 3 22:42:12 2008 From: mdboldin at gmail.com (mmm) Date: Mon, 3 Mar 2008 19:42:12 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> Message-ID: <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> > > Hence (if I understand python convention), this can be > > solved by adding > > sqlx= copy.copy(sqlx) > > before the looping. And in tests adding this step saved about 5-10% in > > time. > > Now this I don;t really understand at all. What's the point of trying to > replace sqlx with a copy of itself? Perhaps if you explained what you > hope this will achieve I could comment more intelligently. > I am/was attempting to convert sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) to code that did to need to be re-evaluated. i.e. to insert the dtable and ph values as if they were hard coded. copy.copy --> A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. From gabriel.rossetti at mydeskfriend.com Wed Mar 26 04:51:57 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Wed, 26 Mar 2008 09:51:57 +0100 Subject: Strange loop behavior In-Reply-To: <47EA0ABB.3030804@mydeskfriend.com> References: <47EA0ABB.3030804@mydeskfriend.com> Message-ID: <47EA0EAD.3010006@mydeskfriend.com> Gabriel Rossetti wrote: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > I also tried writing the while's condition like so : len(d) > 0, but > that doesn't change anything. I tried step-by-step debugging using > PyDev(eclipse plugin) and I noticed this, once the while was read once, > it is never re-read, basically, the looping does happen, but just in > between the two lines in the loop's body/block, it never goes on the > while and thus never verifies the condition and thus loops forever. I > had been using psyco (a sort of JIT for python) and so I uninstalled it > and restarted eclipse and I still get the same thing. This looks like > some bug, but I may be wrong, does anybody understand what's going on here? > > Thanks, > Gabriel > > PS > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. > > Ok, I get it, the repr() function actually returns a string with quote characters around it, thus the length is never 0, but 2. The reason I began using the repr() function is that the str() and unicode() constructors didn't accept the data read, because it was bigger than ord(128) (or something like that. I'm trying to read a binary file and put it's contents in an xml message to send via the network, so that I can re-create it on the other side. I do need to keep the xml aspect though. Is there a better way of doing this? Thanks, Gabriel From wmcbrine at users.sf.net Sun Mar 16 12:25:56 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sun, 16 Mar 2008 16:25:56 GMT Subject: When file-like objects aren't file-like enough for Windows Message-ID: This is proving to be a recurring problem for me. First, I used the save() method of a Python Imaging Library "Image" object to write directly to the "wfile" of a BaseHTTPRequestHandler- derived class: pic.save(self.wfile, 'JPEG') Worked great in Linux, barfed in Windows. I had to do this to get around it: out = StringIO() pic.save(out, 'JPEG') encoded = out.getvalue() self.wfile.write(encoded) Now, I have a similar problem with subprocess.Popen... The code that works in Linux looks like this: source = urllib.urlopen(url) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) try: shutil.copyfileobj(child.stdout, self.wfile) except: kill(child.pid) But wfile isn't the problem this time; instead, it's the source: ... child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) File "C:\Python25\lib\subprocess.py", line 586, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Python25\lib\subprocess.py", line 698, in _get_handles p2cread = msvcrt.get_osfhandle(stdin.fileno()) IOError: [Errno 9] Bad file descriptor How can I get around this, short of resorting to copying all of the input before passing it to the child? -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From __peter__ at web.de Mon Mar 3 07:04:12 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Mar 2008 13:04:12 +0100 Subject: Delete hidden files on unix References: Message-ID: loial wrote: > How can I delete hidden files on unix with python, i.e I want to do > equivalent of > > rm .lock* >>> for fn in glob.glob(".lock*"): ... os.remove(fn) ... Peter From michael.wieher at gmail.com Sun Mar 16 10:12:24 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:12:24 -0500 Subject: Advantage of the array module over lists? In-Reply-To: References: Message-ID: I believe the array module provides more functionality than lists. Perhaps this extra functionality comes with... overhead? C'est possible. For example, you can declare an array to contain all items of a type, ie: >>array.array('f') #array of floats So, they might be efficient, in that they're more efficient than wrapping lists on your own, if you *need* the extra power they provide. Not sure. 2008/3/16, Arnaud Delobelle : > > Tobiah writes: > > > I checked out the array module today. It claims that > > arrays are 'efficient'. I figured that this must mean > > that they are faster than lists, but this doesn't seem > > to be the case: > > > > ################ one.py ############## > > import array > > > > a = array.array('i') > > > > for x in xrange(10000000): > > a.append(x) > > > > for x in a: > > a[x] += 1 > > > > ################ two.py ############## > > a = [] > > > > for x in xrange(10000000): > > a.append(x) > > > > for x in a: > > a[x] += 1 > > > > ###################################### > > > > > > ktops:toby:pytest> time python one.py; time python two.py > > > > real 0m28.116s > > user 0m17.504s > > sys 0m10.435s > > > > real 0m23.026s > > user 0m13.027s > > sys 0m9.777s > > > > > > Perhaps the only advantage is that they take less memory > > to store a large number of items? It would seem then, that > > 'economical' might have been a better choice of word than > > 'efficient'. > > I get an even bigger difference with this test (same as yours, but > using timeit and using an allegedly more efficient way of initialising > the array) > > >>> def test(arr, n): > ... a = arr(xrange(n)) > ... for x in a: > ... a[x] += 1 > ... > >>> n = 10000000 > >>> import timeit > >>> timeit.Timer('test(list, n)', 'from __main__ import test, > n').timeit(1) > 2.4988760948181152 > >>> from array import array > >>> arr = lambda n: array('i', n) > >>> timeit.Timer('test(arr, n)', 'from __main__ import test, arr, > n').timeit(1) > 5.7419960498809814 > >>> > > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Mar 28 19:18:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 20:18:46 -0300 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <3b584949-73a2-4c2b-aa28-8d1f6622cd8c@u10g2000prn.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 18:15:04 -0300, harryos escribi?: > if i were to calculate the euclidean distance in the above example how > should i go about it..? > should i replace > distance = abs(input_wk - weights[image, :]) > with something else? For a single 2D vector, math.hypot does what you want. But the above looks like a NumPy array; see this thread http://projects.scipy.org/pipermail/numpy-discussion/2007-April/027166.html -- Gabriel Genellina From dblubaugh at belcan.com Mon Mar 3 15:40:57 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 3 Mar 2008 15:40:57 -0500 Subject: FW: unable to download PyGEP Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380298E136@AWMAIL04.belcan.com> > ______________________________________________ > From: Blubaugh, David A. > Sent: Monday, March 03, 2008 3:39 PM > To: 'ryanjoneil at gmail.com' > Subject: unable to download PyGEP > > Dear Sir, > > I have been having issues installing PyGEP. I have tried the > following: > > at MS-DOS command prompt > > > cd C:\python25\PyGEP-0.3.0.dev-r117 > > > I then enter setup.py on command prompt. > > > > It then states that it could not find a module named setuptools in > order to install. Can you help me with this issue ?? Thanks!!!! > > > > David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shoeshive8 at yahoo.com.cn Fri Mar 28 18:17:37 2008 From: shoeshive8 at yahoo.com.cn (shoeshive8 at yahoo.com.cn) Date: Fri, 28 Mar 2008 15:17:37 -0700 (PDT) Subject: Sell Air Jordan 1 Retro-BMP Package Old Love New Love Edition China wholesale Message-ID: <97e4e31f-6520-47a1-a104-9aa7448404d6@d4g2000prg.googlegroups.com> www.shoeshive.net Wholesale R3 Wholesale R4 Wholesale NZ Wholesale R5 Wholesale Monser Wholesale OZ Wholesale Nike Trainers Wholesale Air Rift Shoes Air Max 87 Air Max 90 Air Max Ltd Air Max 95 Air Max 97 Air Max 2003 Air Max 360 at www.shoeshive.net Air Max Tn Nike Air Max 180 Nike Dunk SB Nike Men Dunk Low Nike Men Dunk High Nike Dunk Woman Nike Kids Shoes Nike Air Jordan Boy Shoes Nike Air Force Ls at www.shoeshive.net Nike Air Max Timberland Boots Timberland Kid Boots at www.shoeshive.net Timberland Mens Boots Womens Timberland Boots Puma Trainers Womens Puma Shoes Puma Mens Shoes Louis Vuitton Sneakers Louis Vuitton Shoes Nike Athletics Nike LeBron James 4 IV Nike Timberland Dunca & Misc Nike Air Foamposite Pro Nike Kevin Garnett Signature Nike Slow Track Shoes Nike Zoom Nike Boot Bapesta Shoes Bapesta Sneakers Adidas Adidas Star Adidas Superstar 35 th at www.shoeshive.net Annivers Adidas Adicolor Adidas NBA Adidas City at www.shoeshive.net Prada Sneakers Wholesale Prada Shoes High Cut Prada Gucci Wholesale Shoes Low Cut Gucci Sneakers High Cut Gucci Sneakers Gucci Woman Football Shoes Nike Football Shoes Adidas Football Shoes Ugg Boots Women Ugg Slipper Ugg Woman Shoes Dsquared Shoes Wholesale Mens Dsquared Sneakers Mauri Wholesale Shoes Sneakers Mauri Womens Shoes Wholesale Designer Womens Sandals Boots For Womens Nike Woman Shoes Women Air Max Shoes Nike Air Dordan Woman Shoes Dolce Gabbana Shoes Dolce Gabbana Sneakers Hogan Shoes Sale Cheap Hogan Sneakers Versace Sneakers at www.shoeshive.net Versace Shoes Wholesale Ed Hardy Sneakers Ed Hardy Wholesale Paciotti 4 US Paciotti 4 US Shoes Armani Shoes Wholesale Armani Sneakers Lacoste Shoes Lacoste Trainers Burberry Shoes Burberry Wholesale Shoes Boss Shoes Wholesale Greedy Genius Sneakers at www.shoeshive.net Greedy Genius Shoes Chanel Shoes Chanel Shoes Sale Cross Sandals Cross Sandals Converse Sneakers Converse Shoes Richmond Sneaker Richmond Wholesale Sneakers Just Cavalli Shoes Just Cavalli Shoes Dirk Bikkembergs Sneakers Shoes Dirk Bikkembergs at www.shoeshive.net From duncan.booth at invalid.invalid Mon Mar 17 12:03:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 16:03:19 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: > >> Here's a puzzle for those who think they know Python: >> >> Given that I masked out part of the input, which version(s) of Python >> might give the following output, and what might I have replaced by >> asterisks? > > There's too many variables -- at least five Python implementations > that I know of (CPython, Jython, PyPy, IronPython, and the Lisp-based > implementation that I can never remember the name of), and given that > this is an implementation-dependent feature it could have changed at > any time, in any version number (say, between minor releases). And > there's literally an infinite number of ways to get b equal to an int > with the value 1. True, there are a lot of variables, but perhaps not as many as you think. For example, you can't get that output from IronPython or PyPy (or at least not the versions I have kicking around) as they won't print 'yes!' for the first test. You are correct though it is possible with both CPython and Jython. > So I think unless somebody happens to have stumbled across this > behaviour, it's not predictable. > > But having said that, I'm going to take a stab in the dark: > > The line "b = ****" should be "b = int('1')" > > and the version is CPython 1.4. > > Am I close? > I don't have a copy of 1.4 to check so I'll believe you, but you can certainly get the output I asked for with much more recent versions. For the answer I actually want each asterisk substitutes for exactly one character. From bronger at physik.rwth-aachen.de Mon Mar 31 02:45:31 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 31 Mar 2008 08:45:31 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> <65anbqF2fg18bU1@mid.individual.net> Message-ID: <87r6drjss4.fsf@physik.rwth-aachen.de> Hall?chen! Bjoern Schliessmann writes: > Torsten Bronger wrote: > >> Emacs is generally not regarded as being convenient, however, it >> has very strong input methods. I type "\gtrless" and get "?", or >> "\forall" and get "?". Doesn't KNode support UTF-8? > I wonder where the point of this is. :) Why use fancy unicode > chars if they're not better to read (apart from not being readable > with every font) and require at least the same amount of > keypresses? Who wants to minimize the number of keypresses? We're not Perl after all. ;-) As a general rule of thumb in typography, more glyph forms increase readability. APL is not readable at all but this is due to its syntax I suppose. I find hdante's excerpt very readable. The only reason why we don't use those special characters is that they aren't ASCII. While ? or ? are questionable because Python prefers English words instead of scientific symbols, ? or ? would be certainly more legible than != or <=. But they are not ASCII, so there is no net benefit. However, I'm quite sure that when Unicode has arrived almost everywhere, some languages will start considering such characters in their core syntax. Python 3.0 allows for Unicode letters in identifiers, and there's still room for improvement. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From pradiprai at gmail.com Mon Mar 31 06:49:12 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 16:19:12 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Yes, i have copied everything from site-packages of the old one to the new one. Regards, Pradeep -On [20080331 12:29], Pradeep Rai (pradiprai at gmail.com) wrote: >I have upgraded python v2.5.2 from python v2.4.3. The upgradation >results into following error: "Python C API version mismatch for module >dbi: This Python has API version 1013, module dbi has version 1012." Did you copy everything from site-packages of the old one to the new one? -- Jeroen Ruigrok van der Werven / asmodai CF[ EtbN @ f EFF *http://www.in-nomine.org/* | * http://www.rangaku.org/* If you're afraid of dyin', then you're holding on. You see devils tearing your life away. But if you have made your peace, then the devils are really angels, freeing you from the earth... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 14 09:06:30 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Mar 2008 14:06:30 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: <47da7812$0$31760$426a74cc@news.free.fr> Dave Kuhlman a ?crit : > Arnaud Delobelle wrote: > >> 4. Both points above follow from the fact that foo.bar is really a >> function call that returns a (potentially) new object: in fact what >> really happens is something like > > Arnaud and Imri, too - > > No. foo.bar is *not* really a function/method call. > >> Foo.__dict__['bar'].__get__(foo, Foo). >> >> So every time foo.bar is executed an object is (or may be) created, >> with a new id. >> >> HTH > > I appreciate the help, but ... > > Actually, it does not help, because ... > > My understanding is that foo.bar does *not* create a new object. Given your implementation, foo.bar *does* create a new object on each lookup. This object is an instancemethod instance, that is, a thin wrapper around Foo, foo and Foo.__dict__['bar']. Foo.__dict__['bar'] is a function instance, it's an attribute of class Foo, and the function class implements the descriptor protocol. So when bar is looked on a Foo instance, bar.__get__ is called with foo and Foo as arguments, and returns an instancemethod instance that has .im_self bound to foo, .im_class bound to Foo, and .im_func bound to Foo.__dict__['bar']. > All it > does is return the value of the bar attribute of object foo. Yes. But since function bar is a descriptor, foo.bar is a computed attribute, which value is a newly created instancemethod object. > What new > object is being created? An instancemethod. > If I have: > > class Foo(object): > def bar(self): pass > > > And I do: > > foo = SomeClass() > > then: > > foo.bar > > should return the same (identical) object everytime, no? yes? No. > I'm still confused. Then you have to learn how attribute lookup works in Python. From jzgoda at o2.usun.pl Tue Mar 25 11:04:09 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Mar 2008 16:04:09 +0100 Subject: sendmail should throw an exception but does not In-Reply-To: References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> <20080325102113.d8688b7f.darcy@druid.net> Message-ID: Clodoaldo napisa?(a): > That email address is used to register in a site. I'm already doing > the confirmation email path. The confirmation email prevents someone > to register with a forged email but also prevents those who simple > don't know exactly what their email is. Yes the email must be typed > twice but still people get the email wrong just because they don't > know for sure what it is. I can see it clearly when they mistype the > correct domain. > > It happens that atracting those people is expensive and i can't afford > to loose them. Thats why i would like to check the email at > registration time. Also those who try to register with a forged email > would learn that the email must be confirmed and could then issue a > correct email. > > I guess it is not possible or is too complex because i never saw it done. Good guess -- this is not possible until you (or your server) actually send an email. You can send a big "THANKYOU" to spammers, because their activity caused nearly all mail server admins to disable VRFY command that is supposed to do what you need. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From arkanes at gmail.com Tue Mar 11 15:03:57 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 11 Mar 2008 14:03:57 -0500 Subject: Obtaining the PyObject * of a class In-Reply-To: References: Message-ID: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. From steven.klass at gmail.com Sun Mar 23 17:04:24 2008 From: steven.klass at gmail.com (rh0dium) Date: Sun, 23 Mar 2008 14:04:24 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> Message-ID: <17e6ca72-0b61-45a4-9604-dda4029ba5eb@e23g2000prf.googlegroups.com> On Mar 23, 1:48?pm, rh0dium wrote: > On Mar 23, 12:26?am, Paul McGuire wrote: > > > > > There are a couple of bugs in our program so far. > > > First of all, our grammar isn't parsing the METAL2 entry at all. ?We > > should change this line: > > > ? ? md = mainDict.parseString(test1) > > > to > > > ? ? md = (mainDict+stringEnd).parseString(test1) > > > The parser is reading as far as it can, but then stopping once > > successful parsing is no longer possible. ?Since there is at least one > > valid entry matching the OneOrMore expression, then parseString raises > > no errors. ?By adding "+stringEnd" to our expression to be parsed, we > > are saying "once parsing is finished, we should be at the end of the > > input string". ?By making this change, we now get this parse > > exception: > > > pyparsing.ParseException: Expected stringEnd (at char 1948), (line:54, > > col:1) > > > So what is the matter with the METAL2 entries? ?After using brute > > force "divide and conquer" (I deleted half of the entries and got a > > successful parse, then restored half of the entries I removed, until I > > added back the entry that caused the parse to fail), I found these > > lines in the input: > > > ? ? fatTblThreshold ? ? ? ? ? ? ? ? = (0,0.39,10.005) > > ? ? fatTblParallelLength ? ? ? ? ? ?= (0,1,0) > > > Both of these violate the atflist definition, because they contain > > integers, not just floatnums. ?So we need to expand the definition of > > aftlist: > > > ? ? floatnum = Combine(Word(nums) + "." + Word(nums) + > > ? ? ? ? Optional('e'+oneOf("+ -")+Word(nums))) > > ? ? floatnum.setParseAction(lambda t:float(t[0])) > > ? ? integer = Word(nums).setParseAction(lambda t:int(t[0])) > > ? ? atflist = Suppress("(") + delimitedList(floatnum|integer) + \ > > ? ? ? ? ? ? ? ? Suppress(")") > > > Then we need to tackle the issue of adding nesting for those entries > > that have sub-keys. ?This is actually kind of tricky for your data > > example, because nesting within Dict expects input data to be nested. > > That is, nesting Dict's is normally done with data that is input like: > > > main > > ? Technology > > ? Layer > > ? ? PRBOUNDARY > > ? ? METAL2 > > ? Tile > > ? ? unit > > > But your data is structured slightly differently: > > > main > > ? Technology > > ? Layer PRBOUNDARY > > ? Layer METAL2 > > ? Tile unit > > > Because Layer is repeated, the second entry creates a new node named > > "Layer" at the second level, and the first "Layer" entry is lost. ?To > > fix this, we need to combine Layer and the layer id into a composite- > > type of key. ?I did this by using Group, and adding the Optional alias > > (which I see now is a poor name, "layerId" would be better) as a > > second element of the key: > > > ? ? mainDict = dictOf( > > ? ? ? ? Group(Word(alphas)+Optional(quotedString)), > > ? ? ? ? Suppress("{") + attrDict + Suppress("}") > > ? ? ? ? ) > > > But now if we parse the input with this mainDict, we see that the keys > > are no longer nice simple strings, but they are 1- or 2-element > > ParseResults objects. ?Here is what I get from the command "print > > md.keys()": > > > [(['Technology'], {}), (['Tile', 'unit'], {}), (['Layer', > > 'PRBOUNDARY'], {}), (['Layer', 'METAL2'], {})] > > > So to finally clear this up, we need one more parse action, attached > > to the mainDict expression, that rearranges the subdicts using the > > elements in the keys. ?The parse action looks like this, and it will > > process the overall parse results for the entire data structure: > > > ? ? def rearrangeSubDicts(toks): > > ? ? ? ? # iterate over all key-value pairs in the dict > > ? ? ? ? for key,value in toks.items(): > > ? ? ? ? ? ? # key is of the form ['name'] or ['name', 'name2'] > > ? ? ? ? ? ? # and the value is the attrDict > > > ? ? ? ? ? ? # if key has just one element, use it to define > > ? ? ? ? ? ? # a simple string key > > ? ? ? ? ? ? if len(key)==1: > > ? ? ? ? ? ? ? ? toks[key[0]] = value > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? # if the key has two elements, create a > > ? ? ? ? ? ? ? ? # subnode with the first element > > ? ? ? ? ? ? ? ? if key[0] not in toks: > > ? ? ? ? ? ? ? ? ? ? toks[key[0]] = ParseResults([]) > > > ? ? ? ? ? ? ? ? # add an entry for the second key element > > ? ? ? ? ? ? ? ? toks[key[0]][key[1]] = value > > > ? ? ? ? ? ? # now delete the original key that is the form > > ? ? ? ? ? ? # ['name'] or ['name', 'name2'] > > ? ? ? ? ? ? del toks[key] > > > It looks a bit messy, but the point is to modify the tokens in place, > > by rearranging the attrdicts to nodes with simple string keys, instead > > of keys nested in structures. > > > Lastly, we attach the parse action in the usual way: > > > ? ? mainDict.setParseAction(rearrangeSubDicts) > > > Now you can access the fields of the different layers as: > > > ? ? print md.Layer.METAL2.lineStyle > > > I guess this all looks pretty convoluted. ?You might be better off > > just doing your own Group'ing, and then navigating the nested lists to > > build your own dict or other data structure. > > > -- Paul > > Hi Paul, > > Before I continue this I must thank you for your help. ?You really did > do an outstanding job on this code and it is really straight forward > to use and learn from. ?This was a fun weekend task and I really > wanted to use pyparsing to do it. ?Because this is one of several type > of files I want to parse. ?I (as I'm sure you would agree) think the > rearrangeSubDicts is a bit of a hack but never the less absolutely > required and due to the limitations of the data I am parsing. ? Once > again thanks for your great help. ?Now the problem.. > > I attempted to use this code on another testcase. ?This testcase had > tabs in it. ?I think 1.4.11 is missing the expandtabs attribute. ?I > ran my code (which had tabs) and I got this.. > > AttributeError: 'builtin_function_or_method' object has no attribute > 'expandtabs' > > Ugh oh. ?Is this a pyparsing problem or am I just an idiot.. > > Thanks again! Doh!! Nevermind I am an idiot. Nope I got it what a bonehead.. I needed to tweak it a bit to ignore the comments.. Namely this fixed it up.. mainDict = dictOf( Group(Word(alphas)+Optional(quotedString)), Suppress("{") + attrDict + Suppress("}") ) | cStyleComment.suppress() Thanks again. Now I just need to figure out how to use your dicts to do some work.. From castironpi at gmail.com Mon Mar 31 20:51:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 17:51:48 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> Message-ID: <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> On Mar 31, 7:14?pm, 7stud wrote: > On Mar 31, 5:31?pm, castiro... at gmail.com wrote: > > > Can you have a Python object stored entirely on disk? > > import cPickle as cp > > class Dog(object): > ? ? def __init__(self, name): > ? ? ? ? self.name = name > > d = Dog("Spot") > > f = open("data.txt", "w") > cp.dump(d, f) > f.close() > > f = open("data.txt") > stored_obj = cp.load(f) > print stored_obj.name > > --output:-- > Spot >>> import pickle >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps Pickler(f, protocol).dump(obj) File "C:\Programs\Python\lib\pickle.py", line 221, in dump self.save(obj) File "C:\Programs\Python\lib\pickle.py", line 283, in save f(self, obj) # Call unbound method with explicit self File "C:\Programs\Python\lib\pickle.py", line 697, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle : it's not found as __ main__.None >>> From castironpi at gmail.com Wed Mar 5 17:08:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 14:08:28 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> Message-ID: On Mar 5, 3:38?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: > > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: > >> castiro... at gmail.com schrieb: > > >> > I want to hash values to keys. ?How do the alternatives compare? > > >>http://catb.org/~esr/faqs/smart-questions.html > > > ... without extending the whole way to a full relational database? > > You didn't bother following the link and reading the advice, did you? If > you did, you haven't done a good job of following that advice. Well, obviously there's someone who's interested in computers and programming that has a question. Communication is not his forte, but effort, willingness, devotion, and dedication are. What should he do, and what should the others, who are gifted speakers? From pavlovevidence at gmail.com Mon Mar 31 13:59:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 31 Mar 2008 10:59:12 -0700 (PDT) Subject: troll poll References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> Message-ID: <199c5242-f561-4c51-a96b-428abe6f9d80@f63g2000hsf.googlegroups.com> On Mar 31, 1:41 pm, Paul Rubin wrote: > "Daniel Fetchinson" writes: > > [ ] - Xah Lee > > [ ] - castironpi > > I've lost track but has it been established that they are not the same > person? Has it been established that castironpi is a person at all? Carl Banks From jeff at schwabcenter.com Wed Mar 5 11:26:04 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 05 Mar 2008 08:26:04 -0800 Subject: OT[1]: Re: SV: Polymorphism using constructors In-Reply-To: <13ssb8fph6nkoff@corp.supernews.com> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> <13ssb8fph6nkoff@corp.supernews.com> Message-ID: <29WdncFY4qn0VFPanZ2dnUVZ_ournZ2d@comcast.com> Dennis Lee Bieber wrote: > On Tue, 4 Mar 2008 20:06:38 -0500, Tommy Grav declaimed > the following in comp.lang.python: > >> SV = "Svar" is the Norwegian word for Reply. >> > Ah, good... In my working life, "SV" => "Space Vehicle", often used > to differentiate between the base satellite and "PL" Payload (the part > that earns the money) Which is which? Aren't those both part of the space vehicle? Btw, do you work for government or industry? Do you enjoy working with the space program? I've heard only indirect reviews, and they've been mixed. [1] "Av Emne," according to the free online translater. http://www.tranexp.com:2000/Translate/result.shtml From arnodel at googlemail.com Mon Mar 24 10:41:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Mar 2008 07:41:16 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> <13ufd10ps50mm4a@corp.supernews.com> Message-ID: On Mar 24, 2:01?pm, Steven D'Aprano wrote: [...] > > Yes, but what I'm asking is why the code objects have a co_name > attribute. And even if there's a good reason for code objects to have a > name, why do tracebacks use func.func_code.co_name instead of > func.__name__? From what I remember when I looked at the source: stack frames execute code objects, not functions. They don't know what function has spawned them, only what code object they are executing. In fact when one thinks of it, it makes more sense for code objects to have a name (taken from the def statement) than for function objects, as there is exactly one code object for every def statement. -- Arnaud From jwbrown77 at gmail.com Thu Mar 27 15:41:56 2008 From: jwbrown77 at gmail.com (jwbrown77 at gmail.com) Date: Thu, 27 Mar 2008 12:41:56 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes Message-ID: Hello, I am trying to read a csv file. I have the following functioning code: ---- BEGIN ---- import csv reader = csv.reader(open("test.csv", "rb"), delimiter=';') for row in reader: print row ---- END ---- This code will successfully parse my csv file formatted as such: "this";"is";"a";"test" Resulting in an output of: ['this', 'is', 'a', 'test'] However, if I modify the csv to: "t"h"is";"is";"a";"test" The output changes to: ['th"is"', 'is', 'a', 'test'] My question is, can you change the behavior of the parser to only remove quotes when they are next to the delimiter? I would like both quotes around the h in the example above to remain, however it is instead removing only the first two instances of quotes it runs across and leaves the others. The closest solution I have found is to add to the reader command "escapechar='\\'" then manually add a single \ character before the quotes I'd like to keep. But instead of writing something to add those slashes before csv parsing I was wondering if the parser can handle it instead. Thanks in advance for the help. From bskaplan14 at yahoo.com Mon Mar 31 10:15:56 2008 From: bskaplan14 at yahoo.com (Ben Kaplan) Date: Mon, 31 Mar 2008 07:15:56 -0700 (PDT) Subject: TypeError with weakrefs Message-ID: <546869.58559.qm@web39213.mail.mud.yahoo.com> I'm working with weakrefs, and I keep getting a type error The exact line I am getting is Exception exceptions.TypeError: '__call__() takes exactly 0 arguments (1 given)' in ignored The strange part is that I am not trying to call anything. From debugging, I found out that the message is printed at this line: count = self.nb_add - self.nb_removed Has anyone seen this before? ____________________________________________________________________________________ OMG, Sweet deal for Yahoo! users/friends:Get A Month of Blockbuster Total Access, No Cost. W00t http://tc.deals.yahoo.com/tc/blockbuster/text2.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From attn.steven.kuo at gmail.com Tue Mar 11 22:30:21 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Tue, 11 Mar 2008 19:30:21 -0700 (PDT) Subject: Time Zone application after strptime? References: <47D1B703.6040200@egenix.com> Message-ID: On Mar 11, 11:00 am, Jim Carroll wrote: (snipped) > > p.parse("10:29:52 Feb 29, 2008 PST", tzinfos=zones) > datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800)) > > But I cannot figure out how to get dateutil to use the > zoneinfo file that it includes in its own package. It has a > zoneinfo-2007k.tar.gz right in the package, and a class > to parse the binary zoneinfo, but no clear way to get it to > parse its own file and use those during the parsing. Try the pytz module. import datetime import pytz import time utc = pytz.utc zones = { 'PST': pytz.timezone('US/Pacific'), } aware_dt = datetime.datetime(tzinfo=zones['PST'], *time.strptime("10:29:52 Feb 29, 2008 PST", "%H:%M:%S %b %d, %Y %Z")[0:6]) print aware_dt.strftime("%H:%M:%S %b %d, %Y %Z") print utc.normalize(aware_dt.astimezone(utc)).strftime("%H:%M:%S %b %d, %Y %Z") # 10:29:52 Feb 29, 2008 PST # 18:29:52 Feb 29, 2008 UTC -- Hope this helps, Steven From lists at js3d.co.uk Tue Mar 25 10:57:46 2008 From: lists at js3d.co.uk (Jules Stevenson) Date: Tue, 25 Mar 2008 14:57:46 -0000 Subject: dynamically created names / simple problem Message-ID: <000c01c88e88$96c29490$0600a8c0@laptop> Hello all, I'm fairly green to python and programming, so please go gently. The following code for display in secondary: self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") Errors, because of the apparent nastyness at the beginning. What I'm trying to do is loop through a list and create uniquely named wx widgets based on the list values. Obviously the above doesn't work, and is probably naughty - what's a good approach for achieving this? Many thanks, Jules -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Mon Mar 10 18:14:24 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 10 Mar 2008 23:14:24 +0100 Subject: building arbitrary files with distutils? In-Reply-To: References: Message-ID: <47D5B2C0.9010202@v.loewis.de> > How can I add such commands (including timestamp checking) to a setup.py file, > so that it runs when I call 'python setup.py build' ? I can write python > functions to perform those command, and I found timestamp checking functions > in distutils.dep_util, but just can't find the way to connect such commands > to the build step.... Take a look at the build_ext command. It considers all Extension objects (in build_extensions), and for each one, it does dependency checking (in build_extension). It uses the newer_group machinery. More generally, in the run method of your command, just don't do anything (except perhaps logging) if you find your outputs are up-to-date. Multi-level dependencies aren't quite supported with that approach; you can either make multiple commands that one has to run in sequence (or use subcommands), or you put it all in a single run method which sequentially first tries to generate the intermediate outputs (doing nothing if they are up-to-date), and then the final outputs (doing nothing when they are newer than the intermediate ones). HTH, Martin From bignose+hates-spam at benfinney.id.au Fri Mar 28 22:16:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 29 Mar 2008 13:16:07 +1100 Subject: Help me on function definition References: Message-ID: <87tziqtguw.fsf@benfinney.id.au> "aeneng" writes: > I am just starting to use python in numerical cacluation. Welcome, and congratulations on learning Python. > I need you to help me to see what's wrong with the following piece > of codes [...] Your code is rather difficult to read, since your expressions have all the characters mashed together without spaces. It will help others who read your code if you follow the Python coding guidelines in PEP 8 . You should also choose names that are descriptive when someone reads the code, and not single-character algebraic names. > when I import the function, error message show like this > >>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? I suspect you will gain enlightenment in this case by running your code via 'python -t foo.py' where 'foo.py' is the Python module you're trying to run. (You can see a description of that option with 'python -h' to display the commandline help.) -- \ "I have one rule to live by: Don't make it worse." -- Hazel | `\ Woodcock | _o__) | Ben Finney From castironpi at gmail.com Wed Mar 5 23:35:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 20:35:02 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> <7a8a2706-10d0-4f50-b5ad-8b490e57edd5@y77g2000hsy.googlegroups.com> <44a11efa-f1d7-458c-93f0-f0d6f744dfcd@m34g2000hsc.googlegroups.com> Message-ID: On Mar 5, 9:51?pm, castiro... at gmail.com wrote: > > > > If I understand your question, classes are not singletons: > > > >>>> ll=[] > > > >>>> for i in range(2): > > > > ?import string > > > > ?ll[i]=string > > > > Where's the IndexError? :-) > > > > I accept my question about classes being singletons is not well-formed, > > > not even in my own mind. I guess one way of asking is, for any two class > > > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? > > Similarly, no. > > >>> class metaC( type ): > > ... ? ? def __eq__( self, other ): > ... ? ? ? ? ? ? return True > ...>>> class C( metaclass= metaC ): > > ... ? ? pass > ...>>> class D( metaclass= metaC ): > > ... ? ? pass > ...>>> C==D > True > >>> C is D > > False > > +1 raised eyebrow Well, you're not going to believe me, but a "bar" just had an idea. Don't forget: class C( metaclass= metaC ) class metaC( metaclass= metametaC ) class metametaC( type ): bor hor hor. Now for the academics, is it telling a joke? If so, that's pretty fine--- but. From stef.mientki at gmail.com Wed Mar 19 17:18:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 19 Mar 2008 22:18:42 +0100 Subject: Is this valid ? Message-ID: <47E18332.9030202@gmail.com> hello, by accident I typed a double value test, and to my surprise it seems to work. Is this valid ? a = 2 b = 2 a == b == 2 thanks, Stef Mientki From castironpi at gmail.com Wed Mar 5 15:04:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 12:04:30 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> Message-ID: On Mar 5, 1:29?pm, Paul McGuire wrote: > On Mar 5, 12:50?pm, castiro... at gmail.com wrote: > > > What is a class that is not a module? > > Please stop posting these one-liner beginner questions. ?If you can > type it in one line, you can enter it on the Google.com or Ask.com > query page and get a wealth of *existing* information, from tutorials, > documentation, online presentations. ?If you are able to phrase such a > question, you are capable of doing a little research and > experimentation on your own. > > These posts translate to "I'm too lazy to use Google, or too cheap to > buy a Python book, or too lazy to read it, or too impatient to do my > own experimenting - much better to just post on c.l.py and have the > answer spoon-fed to me!" > > I refuse to spoon feed you the answer to this question when plenty of > supporting material is already available. In the future, shall I assume that other readers here have no ideas (on this, read *ever*), that haven't already been published? 'Cause I have. For instance, in this example, I've tried a few approaches that didn't turn out well. Do you want a comparison of existing solutions? Do you have a proof that they exhaust the solution space? I'm willing to address convention, in serial or parallel--- (change subject to 'what goes on newsgroups'?), but it's not clear from fact what assumption who has made. Next time, why don't you say, "How much experience do you have?", or "What level should I gear my answer toward?" From aaron.watters at gmail.com Sat Mar 8 17:13:14 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Sat, 8 Mar 2008 14:13:14 -0800 (PST) Subject: off topic: 2 videos on source control and open source development Message-ID: <8a36442e-c4e6-421d-aff9-a3334ee59592@u69g2000hse.googlegroups.com> I just wanted to send out links to 2 informative videos regarding open source and change control systems. The first is Linus Torvalds on git and how it contrasts with subversion and other approaches (where he says some nice things about Mercurial, btw). http://www.youtube.com/watch?v=4XpnKHJAok8 This one is about managing the community dynamics in the subversion project. http://video.google.nl/videoplay?docid=-4216011961522818645 It only made me a little uncomfortable at certain moments :). Good viewing. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=mileage From robert.kern at gmail.com Fri Mar 7 17:20:26 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 07 Mar 2008 16:20:26 -0600 Subject: distutils - Is is possible to install without the .py extensions In-Reply-To: References: Message-ID: Jari Aalto wrote: > Given following setup.py stanza: > > #!/usr/bin/python > > from distutils.core import setup > import glob > > setup(name='program', > description='', > keywords='', > version='', > url='', > download_url='', > license='', > author='', > author_email='', > long_description=""" > """, > scripts = ['program,py'], > packages = ['''], > ) > > Is there any way to fix the installation (postinstall or something), so > that the the result is: > > /usr/bin/program > > instead of: > > /usr/bin/program.py The easiest and best way is to just rename the file in your source tree to "program" and be done with it. -- 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 castironpi at gmail.com Sat Mar 1 22:22:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 19:22:03 -0800 (PST) Subject: Question about lambda and variable bindings References: Message-ID: <7d745a9b-5038-4f8d-9400-14feb5cc19a0@8g2000hse.googlegroups.com> On Mar 1, 8:50?pm, Michael Torrie wrote: > I need to use a lambda expression to bind some extra contextual data > (should be constant after it's computed) to a call to a function. ?I had > originally thought I could use something like this demo (but useless) code: > > funcs=[] > > def testfunc(a,b): > ? ? print "%d, %d" % (a,b) > > for x in xrange(10): > ? ? funcs.append(lambda p: testfunc(x+2,p)) > > Now what I'd like is to call, for example, funcs[0](4) and it should > print out "2,4". ?In other words I'd like the value of x+2 be encoded > into the lambda somehow, for funcs[x]. ?However the disassembly shows > this, which is reasonable, but not what I need: > > >>> dis.dis(funcs[0]) > > ? 2 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (testfunc) > ? ? ? ? ? ? ? 3 LOAD_GLOBAL ? ? ? ? ? ? ?1 (x) > ? ? ? ? ? ? ? 6 LOAD_CONST ? ? ? ? ? ? ? 0 (2) > ? ? ? ? ? ? ? 9 BINARY_ADD > ? ? ? ? ? ? ?10 LOAD_FAST ? ? ? ? ? ? ? ?0 (p) > ? ? ? ? ? ? ?13 CALL_FUNCTION ? ? ? ? ? ?2 > ? ? ? ? ? ? ?16 RETURN_VALUE > > The LOAD_GLOBAL 1 (x) line is definitely a problem. ?For one it refers > to a variable that won't be in scope, should this lambda be called from > some stack frame not descended from the one where I defined it. > > So how can I create a lambda expression that calculates a constant based > on an expression, rather than referring to the object itself? ?Can it be > done? > > Michael I hate that. Especially since ints are immutable. >>> from functools import partial >>> funcs= [ partial( print, x ) for x in range( 10 ) ] >>> for func in funcs: ... func() ... 0 1 2 3 4 5 6 7 8 9 >>> takes advantage of 2.5+ functools.partial and 3.0 print. You can use sys.stdout instead of print in the example in 2.5, but without partial, you're at: class Val: def __init__( self, val ): self.val= val def __call__( self ): self.val+= 10 val= Val( 20 ) val() . There's also a CellMaker implementation somewhere on Py-Ideas, but it was outlawed in 18 provinces, and it just evaluates and compiles a string anyway. for x in xrange(10): fun= exec( 'lambda p: testfunc(%i+2,p)'% x ) funcs.append( fun ) From jeff at schwabcenter.com Tue Mar 18 00:44:05 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 21:44:05 -0700 Subject: First Program Bug (Newbie) In-Reply-To: References: Message-ID: Benjamin Serrato wrote: > P.S. What is the chance I'll get spam for using my real email address? Fendi Chef Bag in Zucca Print - Black Trim Replica AAA, Fake HandBags Cheap Chef Bag in Zucca Print - Black Trim Bags Link : http://www.cnreplicas.com/Fendi_1439.html Chef Bag in Zucca Print - Black Trim Price : $ 170.00 Fendi Hand Bags Link : http://www.cnreplicas.com/Fendi_Replica_Bags.html Replica handbags Home : http://www.cnreplicas.com/ Chef Bag in Zucca Print - Black Trim ,one model of Fendi hand Bags, the most popular designer handbags. You can get top grade Replica Chef Bag in Zucca Print - Black Trim knockoffs at favorable price . Chef Bag in Zucca Print - Black Trim Detailed information : 73f Accessorize in five-star style with this fabulous chef bag from Fendi. The brown and tan signature Fendi print is accented a gathered body adding a sophisticated touch of class. Additional features:Zucca jacquard withblack color patent leather trimBrushed metal hardwareRolled patent handles with ring attachments; 8.75" dropPatent band encircles bag with pintucked gathers along seamFrame topZip closure with oversized Fendi-etched metal pullFine textile liningInterior leather-trimmed zip pocket, cellphone pocket, interior multifunctionpocketSerial numberComes with Fendi dust cover and care bookletActual size: 16.5" x 5.9" x 10.2" c34 Buy the cheapest Chef Bag in Zucca Print - Black Trim in toppest Replica . www.cnreplicas.com helps you to save money! The Same Fendi Series : Chef Bag in Zucca Print - Brown Trim Bags : http://www.cnreplicas.com/Fendi_1440.html Crescent Hobo - Black Bags : http://www.cnreplicas.com/Fendi_1441.html Crescent Hobo - Chocolate Bags : http://www.cnreplicas.com/Fendi_1442.html Crescent Hobo - Cream Bags : http://www.cnreplicas.com/Fendi_1443.html Crescent Hobo - Silver Bags : http://www.cnreplicas.com/Fendi_1444.html Crossword Grande Mirrored bag - Gold Bags : http://www.cnreplicas.com/Fendi_1445.html Crossword Grande Mirrored bag - Silver Bags : http://www.cnreplicas.com/Fendi_1446.html Crossword Patent Clutch - Black Bags : http://www.cnreplicas.com/Fendi_1447.html Crossword Patent Clutch - Silver Bags : http://www.cnreplicas.com/Fendi_1448.html Crossword Patent Clutch - White Bags : http://www.cnreplicas.com/Fendi_1449.html Crossword Patent Clutch - Yellow Bags : http://www.cnreplicas.com/Fendi_1450.html Crossword Patent Clutch Multicolored Letters - Black Bags : http://www.cnreplicas.com/Fendi_1451.html From castironpi at gmail.com Wed Mar 19 03:38:00 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 19 Mar 2008 00:38:00 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: <56df6553-25af-4acb-9b78-a6f8407863c3@u69g2000hse.googlegroups.com> > >> > Can I allocate a second console window, so I can place certain output > >> > to that directly, and leave the original streams alone? ?I tried > >> Have you tried using the creationflags argument to subprocess.Popen? > >> Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation > >> for CreateProcess ? > >> athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx > >> (Note that a process can be attached at most to one console) > > > One console per process is fine, but I tried using 'cmd.exe', > > 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32) > > as separate processes. ?The sign is the console window splashes up and > > vanishes right away. > > Apparently you have to either redirect stdout AND stdin, or none of them. ? > This worked for me: > > p = subprocess.Popen('c:\\windows\\system32\\cmd.exe', > ? ? ? ? ?stdout=subprocess.PIPE, stdin=subprocess.PIPE, > ? ? ? ? ?creationflags=subprocess.CREATE_NEW_CONSOLE) > p.communicate("dir\n") This worked for me. import subprocess p = subprocess.Popen('c:\\windows\\system32\\cmd.exe', stdout=subprocess.PIPE, stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE) import time import threading def th(): while 1: time.sleep( .01 ) s= p.stdout.read(1) print( ':', end= '' ) if not s: continue print( s.decode(), end= '' ) import thread thread.start_new_thread( th, () ) time.sleep( 2 ) p.stdin.write( b'c:\\windows\\system32\\more.com\n' ) p.stdin.flush() print ( 'abc' ) while 1: time.sleep( 1 ) p.stdin.write( b'abc\n' ) p.stdin.flush() print ( 'abc' ) p.wait() time.sleep( 10 ) From noname9968 at gmail.com Thu Mar 27 07:04:53 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 14:04:53 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> Message-ID: <47EB7F55.8090909@gmail.com> Guilherme Polo wrote: > 2008/3/27, Alex9968 : > >> Guilherme Polo wrote: >> > 2008/3/26, Alex9968 : >> > >> >> Hi all, >> >> >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> >> using visual GUI designers), so my question is which other GUI toolkits >> >> have similar functionality. >> >> >> > >> > The geometry manager isn't related to using GUI designers tools at >> > all. And each toolkit has it's own way to do the things, wxPython uses >> > sizers, PyGtk uses containers. >> > >> >> Well, the geometry manager isn't *directly* related to using GUI >> designers, but as Pack arranges widgets automatically, using GUI >> designers isn't required, while with geometry managers that don't, GUI >> designers are necessary (if you start placing widgets programmatically, >> you'll end up reinventing something like Tkinter's Pack or Grid geometry >> manager). I hope I can be understood clearly this time ;-) >> > > Not at all, can't understand your point yet. GUI designers aren't just > for placing widgets, they also will keep the interface design > separated from your code. > I do not want to separate interface from code and I do not experience the need to use GUI designers. Pack arranges widgets perfectly, and it's very complex to do the same without it, both in code and in GUI designer. I wish toolkits I use to be able to place widgets one after another automatically. > >>>> Secondly, I like the detailed widget borders configuration possible in >>>> >> >> Tkinter, which can be used to tweak GUI look, and wonder if other >> >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) >> >> look in Windows, but I'm afraid it can be quite different (and ugly) on >> >> other platforms. >> >> >> > >> > You sure can, but differently. >> > >> >> I suppose any toolkit allows setting parameters like "no border", "flat >> border" and "3d border", but which ones can set ANY type of border to >> ANY widget like Tkinter does? For example set GROOVE border to buttons >> and text widgets (instead of traditional wide raised/lowered borders), >> which is cool (in my opinion). >> >> > > The widgets subclass some base class, which contains some common > methods which could be the border and relief for example. > In the case of PyGtk, border > width is controlled at Container, so most widgets will have this > feature, but the relief style of the widget is not common to all > widgets so you will need to check this one (Button has it). > In wxPython, widgets will subclass Window, which has all you want and more. > But PyQt doesn't seem to care much about this, you can change the > widget to flat (if it makes sense to that widget have setFlat method) > but not much related to the borders. > You could recheck your use-cases and see if they are acceptable. > > >> >> (The reason I ever consider moving from Tkinter is some inconveniences, >> >> involving for example window scrolling, plus its smaller amount of >> >> widgets compared to some other toolkits, plus its (rumored) ugly look on >> >> certain environments. I will not necessary change the toolkit, but I >> >> have to consider it) >> >> >> >> >> > >> > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into >> > Tkinter for upcoming GSoC. For now you could try using Tile extension, >> > and update to Tk 8.5. If you don't want to use extensions, then you >> > will have to wait or change the toolkit for now. >> > >> >> Thanks. I haven't heard of Tile before, now I will keep this in mind. >> You forgot to mention WHAT you're planning to solve ;-) , so I have to >> add that Tile is modernization of Tk widgets (so it fixes ugly look). >> >> > > WHAT I'm planning to solve, quote from my own paragraph: > "I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > Tkinter for upcoming GSoC." > > I would like to add the possibility to use Ttk widgets into tkinter, > providing you have Tk 8.5. It would solve the problem of "not enough > widgets" and the other one of "being ugly" mainly. Tk 8.5 also > auto-fixes some other problems, it provides smooth-scrolling for the > text widget, for example. But keep in mind that using Tk 8.5 in Python > is not yet supported (but possible). > I understood you. I added that sentence just to make it clear for anyone reading this. Your participation is appreciated greatly, thank you. From rbossy at jouy.inra.fr Tue Mar 4 10:10:27 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Tue, 04 Mar 2008 16:10:27 +0100 Subject: why not bisect options? In-Reply-To: References: Message-ID: <1204643427.47cd6663d4d9c@www.jouy.inra.fr> Quoting Raymond Hettinger : > [Robert Bossy] > > I thought it would be useful if insort and consorts* could accept the > > same options than list.sort, especially key and cmp. > > If you're going to do many insertions or searches, wouldn't it be > *much* more efficient to store your keys in a separate array? > > The sort() function guarantees that it calls the key function exactly > once for each member of the list. With and bisect/insort, successive > searches can call the key function over and over again with the same > value. I factored your remark into the code. I actually don't have any particular question about it, that's just an acknowledgment. Though I feel that if one uses the default key, then an awkward list of twins is stored... from operator import itemgetter def identity(x): return x class Bisect: def __init__(self, it, key=identity, cmp=cmp): self.lst = [ (key(x),x,) for x in it ] self.lst.sort(cmp=cmp, key=itemgetter(0)) self.key = key self.cmp = cmp def insort_right(self, x, lo = 0, hi = None): if hi is None: hi = len(self.lst) xk = self.key(x) while lo < hi: mid = (lo + hi) // 2 if self.cmp(xk, self.lst[mid][0]) < 0: hi = mid else: lo = mid + 1 self.lst.insert(lo, (kx,x,)) # skipped insort_left, bisect_right, bisect_left # also skipped the container methods __len__, __getitem__, __iter__ Cheers, RB From deets at nospam.web.de Sat Mar 22 10:07:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 15:07:22 +0100 Subject: [RFC] How to implement command line tool integrating parsing engine In-Reply-To: References: Message-ID: <64ki51F2a87ieU1@mid.uni-berlin.de> llandre schrieb: > Hi all, > > I'd like to have some advices about how to implement a program that has > the following requirements: > - it must run both on linux and windows PC > - it must interact with an electronic device connected to the PC through > serial cable by sending/receiving some command strings and taking > different actions depending on device responses; these strings and > actions must be described in a text file (a sort of script) editable by > user with a simple text editor; the language used to described this > algorithm should be as simple as possible > - initially the program must be written in the form of simple command > line tool that is invoked like this: > program > - in the future, it must be possible to develop a graphical frontend on > top of it; the resulting look&feel should be similar on linux and windows. > > In this mailing list I was adviced to use python: > http://thread.gmane.org/gmane.comp.boot-loaders.u-boot/37939 > > As I never used python, I ask you: > 1) about the script file, which language - for which a parsing engine is > already available in python - do you suggest? Don't use a home-made-language. Use python itself, together with a lib of pre-defined functions and hooks. Python can do the serial communication (google pyserial), and together with e.g. the execfile-command you can execute the user-provided commands after initializing your system. > 2) about the graphical frontend, which graphical libraries do you > recommend? Google this group for a PLETHORA of discussions about this very subject. The answer vary depending on usecase, taste & relative moon humidity. Diez From stefan_ml at behnel.de Mon Mar 10 03:56:26 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 08:56:26 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> Message-ID: <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> Matt Nordhoff wrote: > For what you do decide to rewrite in C, you can also use a language like > Cython [1] (which is a fork of Pyrex [2]). It looks mostly like Python, > and is translated to C without you having to write all of the > boilerplate Python C API stuff. Of course, not quite as efficient > well-tuned raw C, but much more pleasant to write. And if you really need the efficiency of "well-tuned raw C", it's one function call away in your Cython code. Stefan From benjamin.serrato at gmail.com Mon Mar 17 20:03:25 2008 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Mon, 17 Mar 2008 19:03:25 -0500 Subject: First Program Bug (Newbie) Message-ID: I Found It!! The following was a post asking for help finding a bug. I thought I needed help with my syntax, but just before sending I found the bug on line 13. Line 13 should read: "base = 2". I would still appreciate any comments on my program. Maybe there is a better way to do it that I didn't think about. I know it's not that interesting but it's my first one. [post] I'm almost halfway through an online tutorial I found on the python.org site and decided to stop and write a program for myself. I got it in my head to write a program to print all the primes; the idea came from another tutorial. The program prints some non-prime numbers. In a comparison to lists of primes the program prints eight non-primes for numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. Here is the program. base = 2 candidate = 3 while True: while candidate % base != 0: base = base + 1 if base > (candidate / 2): print candidate candidate = candidate + 1 base = 2 else: candidate = candidate + 1 The following is a rundown of the program. candidate: A possible prime number. base: Start point for divisibility testing. outer while loop: Causes the program to loop. inner while loop: Obviously, checks if 'candidate' mod 'base' equals zero. If not base is incremented by one then 'if loop'. if loop: After base has been incremented this checks whether all the possible divisors have been used up. If they have then 'candidate' must be prime. So, candidate is printed, a new candidate is chosen and the base is reset. else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is not prime and a new candidate is chosen. I realize yall probably didn't need all that. At first I tried to use 'return' on the 'else' block to cause the program to loop, but I don't understand 'return' yet and that didn't work. So, I put the rest into another while loop and was really happy to find it worked but the program prints some non-prime numbers. Thanks, Benjamin Serrato P.S. What is the chance I'll get spam for using my real email address? I currently don't get any so... [/post] From robert.rawlins at thinkbluemedia.co.uk Thu Mar 13 11:36:49 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 13 Mar 2008 15:36:49 -0000 Subject: "Attribute Doesnt Exist" ... but.... it does :-s Message-ID: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an awfully aggravating problem which is causing some substantial hair loss this afternoon J I want to get your ideas on this. I am trying to invoke a particular method in one of my classes, and I'm getting a runtime error which is telling me the attribute does not exist. I'm calling the method from within __init__ yet it still seems to think it doesn't exist. Code: # Define the RemoteDevice class. class remote_device: # I'm the class constructor method. def __init__(self, message_list=""): self.set_pending_list(message_list) def set_pending_list(self, pending_list): # Set the message list property. self.pending_list = message_list And the error message which I receive during the instantiation of the class: File: "/path/to/my/files/remote_device.py", line 22, in __init__ self.set_pending_list(message_list) AttributeError: remote_device instance has no attribute 'set_pending_list' Does anyone have the slightest idea why this might be happening? I can see that the code DOES have that method in it, I also know that I don't get any compile time errors so that should be fine. I know it mentions line 22 in the error, but I've chopped out a load of non relevant code for the sake of posting here. Perhaps I'm missing something really simple, but it's got my head spinning. Thanks, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From pianomaestro at gmail.com Fri Mar 28 10:51:10 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 07:51:10 -0700 (PDT) Subject: threads and extension module initialization Message-ID: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> I have an extension module that gets initialized multiple times because I am using threads. How can this module access global state (not per-thread state) ? It needs to create a singleton. Simon. From galaviel at yahoo.com Tue Mar 4 07:29:52 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Tue, 4 Mar 2008 12:29:52 +0000 (UTC) Subject: Removing default logging handler (causes duplicate logging) Message-ID: Hello All, I want to add a logger to my application, then addHandler to it to log to a special destination. Unfortunately when I use logging.getLogger("my_logger") to create the new logger, it apparently comes with a default handler that logs to STDOUT (or STDERR?). When I add my special handler it works Ok, but still logs to terminal, which I do not want. The only way I found to remove the default handler is by using 'logger.removeHandler(logger.handlers[0])'. Is there a more elegant solution that uses the logging API? my setup: Python 2.5.1 on Linux Suse 9. P.S.I am not using Basic config, just 'import logging' and then regular logging.* calls. Thanks in advance, Gal Aviel. From piet at cs.uu.nl Fri Mar 7 17:12:27 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 07 Mar 2008 23:12:27 +0100 Subject: float / rounding question References: Message-ID: >>>>> casevh (C) wrote: >C> On Feb 25, 2:44 am, helen.m.fl... at gmail.com wrote: >>> Hi I'm very much a beginner with Python. >>> I want to write a function to convert celcius to fahrenheit like this >>> one: >>> >>> def celciusToFahrenheit(tc): >>> tf = (9/5)*tc+32 >>> return tf >>> >>> I want the answer correct to one decimal place, so >>> celciusToFahrenheit(12) would return 53.6. >>> >>> Of course the function above returns 53.600000000000001. >>> >>> How do I format it correctly? >C> That is the normal behavior for binary (radix-2) numbers. Just like it >C> is impossible write 1/3 exactly as a decimal (radix-10) number, 536/10 >C> cannot be written exactly as a binary number. If you really need >C> decimal numbers, use the Decimal class. Sorry to come in so late in this discussion. Although it is correct to say that many real numbers that have an exact decimal representation cannot be exactly represented in binary, that is no excuse to print 53.6 as 53.600000000000001. This is just lousy printing and the fact that this kind of question comes up every week shows that it is confusing to many people. Python just uses the C library for printing, I presume, and the conversion routines in the C library are rather simplistic. It is, however, possible to do better, so that 53.6 -- although internally represented as something that could be described as 53.600000000000001 -- will actually be printed as 53.6. Indeed, when reading back the printed value you get the exact representation as the internal number that was printed, and IMHO, that is what matters. Apparently there is more than one representation that has this property. I would guess (but didn't check) that 53.60000000000000100000001 also gives the same number. From all these representations it would be best to choose the simplest one, i.e. 53.6. This problem and a solution has been described in one of the classical computer science publications: http://portal.acm.org/citation.cfm?id=93559 -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From robert.rawlins at thinkbluemedia.co.uk Fri Mar 14 06:49:01 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Fri, 14 Mar 2008 10:49:01 -0000 Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard In-Reply-To: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Message-ID: <009d01c885c1$05caac90$116005b0$@rawlins@thinkbluemedia.co.uk> Geert, I've not seen this issue myself, however, you might get a little more luck asking over on the MySQLdb mailing list as this seems to be more an issue with the db than your python code. It might be worth posting your question there too as it'll heighten your chances of finding someone who knows MySQLdb inside out. http://mail.python.org/mailman/listinfo/db-sig Cheers, Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of geert Sent: 14 March 2008 10:36 To: python-list at python.org Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard Hi all, I have a mac mini running maocosx 10.5 leopard I want to deploy a django project on. My backend is MySQL, and I have it running as a 64- bit app. Of course, apache2 is also running as 64-bit. MySQLdb installs with the usual warnings after applying the various patches I found here and there. These patches consist of altering _mysql.c and site.cfg. Basically, my problem boils down to this: File "", line 1, in File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line 19, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dynamic module does not define init function (init_mysql) Has anyone solved this? I been hunting around for 2 weeks now, and my deadline is looming grimly on the horizon :) Geert -- http://mail.python.org/mailman/listinfo/python-list From fumanchu at aminus.org Mon Mar 17 11:35:15 2008 From: fumanchu at aminus.org (fumanchu) Date: Mon, 17 Mar 2008 08:35:15 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> On Mar 16, 5:09 pm, a... at pythoncraft.com (Aahz) wrote: > fumanchu wrote: > > This is my third PyCon, and I've found a reasonably-sized cadre of > > people who come for the hallway conversations plus a Bof or two, > > having given up on hearing anything new, useful, or inspiring in the > > talks. There are several people I know who would like to see a more > > advanced academic track. > > Finally, trying to satisfy a thousand people is impossible. Well understood. Sorry if I implied it was an easy job. I know it isn't. > If you did not like the programming this year (aside from the sponsor > talks) and you did not participate in organizing PyCon or in delivering > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! This would be true, except that the two talks I proposed last year were essentially denied because they were too advanced, so I didn't even bother this year. Perhaps I should have, but the PERIOD needs to at least be replaced by a COMMA as long as the talk-acceptance committee continues to reject more advanced talk topics in favor of HOWTOs and Introduction To Package X. Robert Brewer fumanchu at aminus.org From castironpi at gmail.com Sat Mar 8 14:33:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 11:33:51 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <3c926403-f4b6-4aa4-8535-36b6a49e4214@c33g2000hsd.googlegroups.com> Message-ID: <9179f161-34ac-4fae-b5db-9af072e6f497@m34g2000hsc.googlegroups.com> On Mar 8, 12:05?pm, Pierre Quentel wrote: > > >>> def convert(x): > > > ? ? ? ? if '.' in x: > > ? ? ? ? ? ? ? ? try: return float(x) > > ? ? ? ? ? ? ? ? except ValueError: return x > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? try: return int(x) > > ? ? ? ? ? ? ? ? except: return x > > > >>> convert('123') > > 123 > > >>> convert('123.99') > > 123.98999999999999 > > >>> convert('hello') > > Hi, > > That's fine for people who write floats with a "." ; but others learn > to enter them with "," > > For the same float, the French write the literal 123.456.789,99 when > others write 123,456,789.99 ; for us, today is 8/3/2008 (or > 08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8 > > Popular spreadsheets know how to "guess" literals ; if the guess is > not correct users can usually specify the pattern to use. My question > was just to know if something similar had already been developed in > Python ; I understand that the answer is no > > Thanks, > Pierre In particular, you can retain access to the user/interface, and always just query when probabilities aren't 100%. In general, retain access to a higher power, such as offering a hook ( def butdonotguess( raw, guesses ):). If you're making the decision, and a case-by-case is too expensive, then you've made a policy, and someone gets shaft "'cause policy". You can throw an exception that's guaranteed to be handled or exits. '121212' isn't as bad as '121110'! If you want to find out who and when writes dates like that, apply to PR. Obviously a person knew at one point what the string was; how much is left? P.S. def welltheydidthatthistime( raw, guesses ):. From spe.stani.be at gmail.com Mon Mar 31 08:51:44 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Mon, 31 Mar 2008 05:51:44 -0700 (PDT) Subject: How to write a wxPython video player directly with Gstreamer Message-ID: <832962ee-bbfd-47df-b9fd-687c662f260c@i12g2000prf.googlegroups.com> In the hope it will be useful for others I've posted on my blog example source code of how to integrate gstreamer directly in wxpython: "wxPython ships by default with the wx.MediaCtrl for very basic playback of music or videos. As I would like to do more advanced video manipulation, I was curious if I could use Gstreamer directly in wxPython to create my own pipelines. It was surprisingly easy. For those who don't know Gstreamer, I quote the website (http:// www.gstreamer.org): GStreamer is a library that allows the construction of graphs of media- handling components, ranging from simple playback to complex audio (mixing) and video (non-linear editing) processing. Applications can take advantage of advances in codec and filter technology transparently." In order not to spam this mailing list, you can read more on http://pythonide.stani.be Best regards, Stani -- http://photobatch.stani.be From pavlovevidence at gmail.com Wed Mar 26 23:45:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Mar 2008 20:45:47 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> <13um57idbctec04@corp.supernews.com> Message-ID: <13a3347a-b8ca-492f-9c15-38e8cc34d4f4@59g2000hsb.googlegroups.com> On Mar 26, 11:30 pm, Steven D'Aprano wrote: > On Wed, 26 Mar 2008 23:12:27 +0100, Thomas Dybdahl Ahle wrote: > > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: > >> Why does python create a reference here, not just copy the variable? > > > Python, like most other oo languages, will always make references for =, > > unless you work on native types (numbers and strings). > > *Including* numbers and strings. Playing Devil's advocate: By "native types" the poster could have meant native types in those "most other oo languages". For instance, it would be kind of true in Java (for numbers only). He probably didn't, though, and the idea that most oo languages use references is questionable. Carl Banks From sjmachin at lexicon.net Sun Mar 23 18:55:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 15:55:43 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <7x63vfn3ix.fsf@ruckus.brouhaha.com> <8e4e1ae0-9a34-41c2-b253-7ea8846f6de5@i7g2000prf.googlegroups.com> Message-ID: <3880a377-30fe-49b3-a578-8d6203d526bb@s8g2000prg.googlegroups.com> On Mar 24, 12:19 am, Dustan wrote: > On Mar 21, 3:57 pm, Paul Rubin wrote: > > > From at home writes: > > > if 'one' and 'two' in f: > > > alist.append(f) > > > Use: > > if 'one' in f and 'two' in f: ... > > Personally, I would put parentheses around to be clearer: > > if ('one' in f) and ('two' in f): ... > > I'm not saying to put parentheses around everything, but in the more > ambiguous cases, it certainly helps. Please help me understand why this is a "more ambiguous" case. To me, alternative interpretations have extremely low scores for utility and likelihood: (1) 'and' has higher precedence than 'in': 'one' in (f and 'two') in f # chained (x in y in z) (2) 'and' has same precedence as 'in': (('one' in f) and 'two') in f Cheers, John From pavlovevidence at gmail.com Mon Mar 3 17:03:35 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 14:03:35 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> Message-ID: <24adaf72-0c55-4a88-86d0-296363ead17f@s8g2000prg.googlegroups.com> On Mar 3, 4:17 pm, Raymond Hettinger wrote: > Since Python doesn't support having two methods with the same name, > the usual solution is to provide alternative constructors using > classmethod(): > > @classmethod > def from_decimal(cls, d) > sign, digits, exp = d.as_tuple() > digits = int(''.join(map(str, digits))) > if sign: > digits = -digits > if exp >= 0: > return cls(digits * 10 ** exp) > return cls(digits, 10 ** -exp) Note that even some of Python's built in types (dict *cough*) implement homemade function overloading. The OP wanted to write a constructor that could accept either a pair of integers or a rational, there would be a good precedent for it. However, I would advise the OP to use the constructor only for the most common arguments, and use classmethods for more obscure, less common arguments (such as decimal or even float). Carl Banks From stargaming at gmail.com Mon Mar 17 11:57:46 2008 From: stargaming at gmail.com (Stargaming) Date: 17 Mar 2008 15:57:46 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> Message-ID: <47de94fa$0$2679$9b622d9e@news.freenet.de> On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: > Here's a puzzle for those who think they know Python: > > Given that I masked out part of the input, which version(s) of Python > might give the following output, and what might I have replaced by > asterisks? > >>>> a = 1 >>>> b = **** >>>> if a is b: print 'yes!' > ... >>>> b > 1 >>>> type(b) > I know it! Using CPython 2.5.2a0, 2.6a1+ and 3.0a3+:: >>> b = type('type', (type,), {'__repr__': lambda self: ... ""})('int', (object,), {'__repr__': ... lambda self:"1"})() >>> b 1 >>> type(b) >>> 1 is b False What's my prize? From allardwarrink at gmail.com Sat Mar 1 16:04:38 2008 From: allardwarrink at gmail.com (Allard Warrink) Date: Sat, 1 Mar 2008 13:04:38 -0800 (PST) Subject: PIL transparency gradient Message-ID: <6e44e95a-2cb0-4026-ad98-f6516e934e27@s37g2000prg.googlegroups.com> I would like to create a transparency gradient over an image using PIL. But I don't have a clue how to do this... Is there anyone out here who could give me some advise? From castironpi at gmail.com Thu Mar 27 07:28:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:28:51 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: On Mar 27, 4:01?am, Peter Otten <__pete... at web.de> wrote: > Grimsqueaker wrote: > > That seems to give me the items in the list back in an iterator. Am I > > using it incorrectly? > > With Dan's functions in cartesian.py you can do the following: > > >>> from cartesian import * > >>> def count(digits): > > ... ? ? args = [] > ... ? ? while 1: > ... ? ? ? ? ? ? args.append(digits) > ... ? ? ? ? ? ? for n in string_cartesian_product(*args): > ... ? ? ? ? ? ? ? ? ? ? yield n > ...>>> from itertools import islice > >>> print " ".join(islice(count("abc"), 30)) > > a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab > bac bba bbb bbc bca bcb bcc For the base, we Arabics use the cardinal; what letters you count in doesn't change anything. Don't just spell out numbers, unless: Are you reading marked-tally. Or do you want to yield a word and see the number that it spells out to? Be there or be around. I'm bad at spelling, but I can rearrange linear. From NikitaTheSpider at gmail.com Mon Mar 31 11:08:09 2008 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Mon, 31 Mar 2008 11:08:09 -0400 Subject: Multi Threading Problem with Python + Django + PostgreSQL. References: <553b16a7-a89e-4892-b92b-c0f88e00e096@e23g2000prf.googlegroups.com> Message-ID: In article <553b16a7-a89e-4892-b92b-c0f88e00e096 at e23g2000prf.googlegroups.com>, Pradip wrote: > Hello every body. I am new to this forum and also in Python. > Read many things about multi threading in python. But still having > problem. > > I am using Django Framework with Python having PostgreSQL as backend > database with Linux OS. My applications are long running. I am using > threading. > The problem I am facing is that the connections that are being created > for database(postgres) update are not getting closed even though my > threads had returned and updated database successfully. It is not like > that the connections are not being reused. They r being reused but > after sometime new one is created. Like this it creates too many > connections and hence exceeding MAX_CONNECTION limit of postgres conf. > > ** I am using psycopg2 as adaptor for python to postgres connection. > which itself handles the connections(open/close) Hi Pradip, A common problem that new users of Python encounter is that they expect database statements to COMMIT automatically. Psycopg2 follows the Python DB-API specification and does not autocommit transactions unless you ask it to do so. Perhaps your connections are not closing because they have open transactions? To enable autocommit, call this on your connection object: connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCO MMIT) > Now the problem is with Django / Python / psycopg2 or any thing else?? Are you asking if there are bugs in this code that are responsible for your persistent connections? If so, then I'd say the answer is almost certainly no. Of course it's possible, but Django/Psycopg/Postgres is a pretty popular stack. The odds that there's a major bug in this popular code examined by many eyes versus a bug in your code are pretty low, I think. Don't take it personally, the same applies to my me and my code. =) Happy debugging -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From Dodin.Roman at gmail.com Tue Mar 25 08:50:36 2008 From: Dodin.Roman at gmail.com (hellt) Date: Tue, 25 Mar 2008 05:50:36 -0700 (PDT) Subject: Need help with OptionParser References: <0a225d25-c544-49d9-9e56-8ecd2d0f7928@s13g2000prd.googlegroups.com> Message-ID: On 25 ???, 15:42, hellt wrote: > today i've decided to use optionparser instead of GetOpt > > and unfortunately i've got an error which i cant handle > > my pice of code: > > from optparse import OptionParser > > def main(): > usage = "usage: %prog [options]" > parser = OptionParser(usage) > parser.add_option("-f", "--file", dest="filename", > help="executable filename", > metavar="FILE") > parser.add_option("-b", "--bighosts", > action="store_true", dest="bighosts", default=False, > help="with big hosts [default: %default]") > (options, args) = parser.parse_args() > if not options.bighosts: > print parser.print_usage() > > if __name__=="__main__": > main() > > if i run test3.py without any arguments, i wait for generated help, > but i see the following > > Usage: test3.py [options] > > None > > why None? Where are all of my options =) my bad unnecessary print in print parser.print_usage() and print_help() instead print_usage() From gandalf at shopzeus.com Tue Mar 25 05:07:55 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Mar 2008 10:07:55 +0100 Subject: eval and unicode In-Reply-To: <47E4210B.1080505@v.loewis.de> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <47E4210B.1080505@v.loewis.de> Message-ID: <47E8C0EB.7060609@shopzeus.com> > I think your confusion comes from the use of the interactive mode. > It is not. The example provided in the original post will also work when you put then into a python source file. > PEP 263 doesn't really apply to the interactive mode, hence the > behavior in interactive mode is undefined, and may and will change > across Python versions. > The expression passed to eval() cannot be considered an interactive session. > Ideally, interactive mode should assume the terminal's encoding for source code, but that has not been implemented. > Again, please read the original messages - many of my examples also work when you put them into a python source file. They have nothing to do with terminals. Laszlo From Afro.Systems at gmail.com Mon Mar 24 03:56:42 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 24 Mar 2008 00:56:42 -0700 (PDT) Subject: encoding/decoding issue with python2.5 and pymssql References: <3a6c32fe-e7c1-4230-882d-efb3415196c1@b1g2000hsg.googlegroups.com> <13uejm8qurtp77f@corp.supernews.com> Message-ID: <17274d24-f0de-4e79-974c-3f63f2af009b@d45g2000hsc.googlegroups.com> These are not cut&paste but typed by hand, yet they are identical to the actual output. seems like the first 8 bytes are swapped while the other half is straightforward. I deeply thank you for your assistance. I am currently using a combination of reversed and list comprehension to rebuild this byte array. On Mar 24, 8:48?am, Dennis Lee Bieber wrote: > On Sun, 23 Mar 2008 22:33:58 -0700 (PDT), Tzury Bar Yochay > declaimed the following in comp.lang.python: > > > for example: > > the value > > 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7' > > is represent as > > '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7' > > ? ? ? ? Are those direct cut&paste? > > >>> "".join(["%2.2X" % ord(x) for x in '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7']) > > 'E34E60EEB04AE74EAF4D018124393CD7' > > or, putting in - > > 'E34E60EE-B04A-E74E-AF4D-018124393CD7' > > ? ? ? ? The last half is a direct match... the front half looks to have some > byte-swapping > > E34E60EE => (swap shorts) ? ?60EEE34E > 60EEE34E => (swap bytes) ? ? EE604EE3 ? ? ? ? ? ? ? ?**** > > B04A => 4AB0 ? ? ? ? **** > > E74E => 4EE7 ? ? ? ? **** > > ? ? ? ? Anything onhttp://www.sqljunkies.com/Article/4067A1B1-C31C-4EAF-86C3-80513451FC0... > of any help (besides the facet of using a GUID to ID the page describing > GUIDs ) > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From deets at nospam.web.de Wed Mar 19 07:41:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 12:41:23 +0100 Subject: Script Request... References: Message-ID: <64ccfbF2bbfckU1@mid.uni-berlin.de> some one wrote: > Hi all, I am not to familiar with python yet and I am wondering if > someone can write a script that will monitor my DSL modems IP address > and notify when it changes, its a 2Wire Advanced DSL Modem. I need to > know when it changes because I am trying to run my own inhouse server > and have to update my domain records through verio.com. > > The script would need to read the text of a web page( on my modem the > address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and > search for a string containing the IP address. > > Can anyone help? > thanks, I'll keep monitoring this thread. Try urllib2 to fetch the data, use either string-search, regular expressions or even BeautifulSoup to extract the data. Use a cron-job to do that on a regular base or use module time.sleep() together with an endless loop to monitor that location periodically. Show us your concrete efforts, and we will suggest improvements. Diez From pavlovevidence at gmail.com Thu Mar 6 12:36:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 09:36:21 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> On Mar 6, 11:41 am, "D'Arcy J.M. Cain" wrote: > On Thu, 6 Mar 2008 08:00:58 -0800 (PST) > > Carl Banks wrote: > > > I'm talking about castironpi. I find his posts a waste of my time > > > "His" posts? > > Whatever. I'm too old to worry about searching for politically correct, > gender neutral pronouns. I'm pretty sure even the most PC people wouldn't suggest using a masculine pronoun for an inanimate objects. (Ok, some probably would.) Carl Banks From sjmachin at lexicon.net Mon Mar 10 00:42:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Mar 2008 21:42:49 -0700 (PDT) Subject: any chance regular expressions are cached? References: Message-ID: <51172306-ff2d-48e8-81cf-93be03f8a08f@s37g2000prg.googlegroups.com> On Mar 10, 11:42 am, m... at pixar.com wrote: > I've got a bit of code in a function like this: > > s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save > me the trouble of having to declare some global re's if I don't > want to have them recompiled on each function invocation? > Yes they will be cached. But do yourself a favour and check out the string methods. E.g. >>> import re >>> def opfunc(s, spaces): ... s=re.sub(r'\n','\n'+spaces,s) ... s=re.sub(r'^',spaces,s) ... s=re.sub(r' *\n','\n',s) ... s=re.sub(r' *$','',s) ... s=re.sub(r'\n*$','',s) ... return s ... >>> def myfunc(s, spaces): ... return '\n'.join(spaces + x.rstrip() if x.rstrip() else '' for x in s.splitlines()) ... >>> t1 = 'foo\nbar\nzot\n' >>> t2 = 'foo\nbar \nzot\n' >>> t3 = 'foo\n\nzot\n' >>> [opfunc(s, ' ') for s in (t1, t2, t3)] [' foo\n bar\n zot', ' foo\n bar\n zot', ' foo\n\n zot'] >>> [myfunc(s, ' ') for s in (t1, t2, t3)] [' foo\n bar\n zot', ' foo\n bar\n zot', ' foo\n\n zot'] >>> From michael.wieher at gmail.com Mon Mar 17 11:18:59 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 10:18:59 -0500 Subject: Missing PyObject definition In-Reply-To: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: 2008/3/17, James Whetstone : > > I'm trying to access a PyObject directly from C++ for the purpose of > calling > method on a Python object that is an intance of a derived C++ class. My > problem is that the compiler is complaining about not PyObject not being > defined. Has anyone run into the problem? Where is PyObject defined? > > Thanks! > James PyObject is definend in this is easily google-able =P -------------- next part -------------- An HTML attachment was scrubbed... URL: From lobais at gmail.com Wed Mar 26 18:12:27 2008 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Wed, 26 Mar 2008 23:12:27 +0100 Subject: Why does python behave so? (removing list items) In-Reply-To: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <1206569547.1010.16.camel@localhost.localdomain> On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: > Why does python create a reference here, not just copy the variable? Python, like most other oo languages, will always make references for =, unless you work on native types (numbers and strings). Instead use one of: k = j[:] or k = [i for i in j] or from copy import copy k = copy(j) or k = range(6) -- Best Regards, Med Venlig Hilsen, Thomas From castironpi at gmail.com Fri Mar 21 09:28:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 06:28:34 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> <4e740d0f-9b1d-4b1d-9f6b-8bd56ea11a65@z38g2000hsc.googlegroups.com> Message-ID: <30f5365b-7e73-4d1c-9db0-dc7244852763@8g2000hse.googlegroups.com> On Mar 19, 4:56?am, Duncan Booth wrote: > castiro... at gmail.com wrote: > > I am puzzled by the failure on 'a in a' for a=[a]. ?>>> a== [a] also > > fails. ?Can we assume/surmise/deduce/infer it's intentional? > > It may be less confusing if instead of an assignment following by a test > you just consider doing the test at the same time as the assignment > (then again it changes the behaviour so it may just be more confusing). > > There is a very limited set of values for which you would expect this > output: > > >>> a==[a] > True > >>> a in [a] > > True > > The most obvious one is a simple recursive list: > > >>> a = [] > >>> a.append(a) > >>> a==[a]; a in [a] > > True > True > > Pushing the recursion down a level breaks some of the comparisons: > > >>> a = [[]] > >>> a[0].append(a) > >>> a==[a] > > Traceback (most recent call last): > ? File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp>>> a in [a] > True > >>> a in a > > Traceback (most recent call last): > ? File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp > > which may be considered a bug or possibly it is just a limit of the > implementation. > > This also produces an overflow (in fact I think it is just the same > situation as above, recursing on the same list is handled, recursing on > different but equivalent lists is not): > > >>> a = []; a.append(a) > >>> b = []; b.append(b) > >>> a==b > > Traceback (most recent call last): > ? File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp Pickle helps, >>> pickle.dumps( a ) b'\x80\x02]q\x00h\x00a.' >>> pickle.dumps( b ) b'\x80\x02]q\x00h\x00a.' >>> pickle.dumps( a )== pickle.dumps( b ) True However, >>> a= [] >>> b= [] >>> a.append( b ) >>> b.append( a ) >>> a [[[...]]] >>> b [[[...]]] >>> a== b Traceback (most recent call last): File "", line 1, in RuntimeError: maximum recursion depth exceeded in cmp >>> pickle.dumps( a )== pickle.dumps( b ) True Liar's paradox, q.e.d. From willsteve2003 at yahoo.ca Mon Mar 17 12:15:55 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 17 Mar 2008 09:15:55 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> Message-ID: On Mar 10, 11:30 am, "sjdevn... at yahoo.com" wrote: > Fix that. That's usually something that's fairly easy to get done as > a programmer (I've had to do it at 2 of the last 4 places I worked). > Just go explain all the problems that can happen by not having VC and > all the benefits it brings to your managers, and that there's a good > free VC system that will work for everyone, and it'll likely become a > mandate pretty quickly. > > It's almost certainly worth fixing that problem rather than mucking > around with half-solutions. Unfortunately, no free VC system existed for the language in which I was programming, and our budget (managers) wouldn't permit the purchase of one easily. These people insisted that every change that affected more than 1 user go through a committee that met once a week. The amount of verbiage required just to submit a proposal to the committee (whom you never got to see in person), was ridiculous in the extreme. From sturlamolden at yahoo.no Sun Mar 16 13:17:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:17:31 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> Message-ID: <3cfd04c9-4a51-402f-b636-8690d4936c1d@h11g2000prf.googlegroups.com> On 16 Mar, 18:10, sturlamolden wrote: > You don't click on compiled Python C extensions. You call it from your > Python code. By the way, disttools will invoke Pyrex and the C compiler, and produce the binary .pyd-file you can access from Python. It's not rocket science (not even computational biology.) From kyosohma at gmail.com Mon Mar 10 15:33:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 12:33:17 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: On Mar 10, 2:11 pm, Stefan Behnel wrote: > Malcolm Greene wrote: > >> My personal experience with wxPython has its ups and downs. Specifically > >> when it comes to crashes, I wouldn't bet my life on it. > > > I'm new to Python and getting ready to build a small client based > > application intended to run on Windows and Linux. I was planning on using > > wxPython until I saw your comment above. > > Just to make this sound a bit less like FUD: my last experience with wxPython > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > in a project, which crashed a bit too often to do real work with it - and with > crashing I mean crashing Python, not just showing us its blank traceback. So > this was definitely a problem either in wxWindows or in wxPython. > > I have no idea how well it works today, but this has definitely forged my > opinion on wxPython. > > > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > > or tips on where I can find out more about wxPython/wxWidget problems? > > The only other GUI library I used was PyQT3. To me, it has proven to be very > stable, pretty easy to use and feature rich. And from what I read about it, > PyQT4 is supposed to be another lot better and has removed the few API quirks > I found at the time (AFAIR, it finally returns plain Python strings from the > API, for example). > > Stefan I agree with Stef. Boa is definitely goofy and while I know some people swear by it, I see far too many people having issues. I go with hand coding or XRC. Some also like SPE, but I haven't tried that to know. Mike From castironpi at gmail.com Wed Mar 12 02:29:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:29:47 -0700 (PDT) Subject: best way to have enum-like identifiers? References: <87k5k84h31.fsf@benfinney.id.au> Message-ID: <768fd642-817c-4a0e-af2c-ee91da88941a@u72g2000hsf.googlegroups.com> > > [enums snip] > Thus, those names are all bound to unique objects, that won't be > unexpectedly duplicated by some other value. > > > but I'm curious if there's a better way of doing this, some kind of > > enum-like thing or somesuch. > > Please try the 'enum' package in the Cheeseshop: Am I the only one superstitious about putting identifiers in strings? > ?When a well-packaged web of lies has been sold to the masses ... someone sold them. >>> c= type('Enum',(),{}) >>> [ setattr( c, v, object() ) for v in 'py funcpre funcpost'.split() ] [None, None, None] >>> c.funcpost >>> c.funcpre You don't need them to be ints or anything, do you, like USER_BASE+ 1? From fraleysinger at gmail.com Wed Mar 12 10:25:43 2008 From: fraleysinger at gmail.com (fraleysinger at gmail.com) Date: Wed, 12 Mar 2008 07:25:43 -0700 (PDT) Subject: agg (effbot) Message-ID: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> Downloaded to Knoppix 5.1: : aggdraw-1.2a3-20060212.tar.gz Followed README. Wouldn't compile. Couldn't find way of contacting Effbot directly. PIL stuff comes with Knoppix, but specs on agg seem better. vtk is on Knoppix too, but has a steep learning curve. TIA for help. From Afro.Systems at gmail.com Tue Mar 25 10:31:06 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 07:31:06 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <29bc6ff2-f172-4776-87b7-884585277570@d21g2000prf.googlegroups.com> On Mar 25, 4:03?pm, Anthony wrote: > On Mar 25, 11:44 am, Tzury Bar Yochay wrote: > > > While my intention is to get 1.2 I get 2.2 > > I would like to know what would be the right way to yield the expected > > results > > Is this what you want? > > class Foo(object): > ? ? def __init__(self): > ? ? ? ? self.id = 1 > ? ? def getid(self): > ? ? ? ? return self.id > > class FooSon(Foo): > ? ? def __init__(self): > ? ? ? ? Foo.__init__(self) > ? ? ? ? self.id = 2 > ? ? def getid(self): > ? ? ? ? a = Foo().getid() > ? ? ? ? b = self.id > ? ? ? ? return '%d.%d' % (a,b) > > >>> FooSon().getid() > > '1.2' > > Best wishes, > Anthony I wish it was that simple but 'a = Foo().getid()' is actually creating a new instance of Foo whereas I want the data of the Foo instanced by __init__ of FooSon(). what I am actually trying to do is to build a set of classes which handle different type of binary messages coming from the network. a base message which handles its basic data parts (src, dst, etc.) and extending it per message type. thus I looked for a way to get the child calling super for parsing the super's prats and then having the child parsing its additional details. From nanjundi at gmail.com Wed Mar 5 17:08:00 2008 From: nanjundi at gmail.com (Nanjundi) Date: Wed, 5 Mar 2008 14:08:00 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <51f4bce3-8561-4149-9b3b-e436bbee8ee7@u69g2000hse.googlegroups.com> <1bcbee35-c5bf-4a6d-b68a-1eed87ffcf8d@p25g2000hsf.googlegroups.com> Message-ID: <8feb142e-2014-4a6f-80cd-28ab44125e9f@u69g2000hse.googlegroups.com> On Mar 5, 3:34 pm, Mensanator wrote: > On Mar 5, 9:29 am, Nanjundi wrote: > > > On Mar 4, 3:13 pm, Mensanator wrote: > > > > On Mar 4, 12:32 pm, Nanjundi wrote: > > > > > Does seeding ( random.seed ) random with time fix this? It should. > > > > I suppose that depends on how long it takes factorint() to > > > process a number. If the seed is reset before the next clock > > > tick, you will get the same random numbers as the previous > > > iteration. > > > Alright, then make it constant and don't worry about the clock tick. > > Reseeding with a constant always sets the sequence to the same > starting > point. > Right, not a good idea. > > > >>> for i in xrange(10): > > > ... f1 = random.choice(f) > > ... print f1, > > ... f2 = random.choice(f) > > ... print f2, > > ... C = f1*f2 > > ... ff = None > > ... ff = sympy.factorint(C) > > ... print ff > > ... random.seed(i) > > ... > > 5573 5171 [(5171, 1), (5573, 1)] > > 8537 7673 [(7673, 1), (8537, 1)] > > 2063 8573 [(2063, 1), (8573, 1)] > > 9551 9473 [(9473, 1), (9551, 1)] > > 2909 5659 [(2909, 1), (5659, 1)] > > 2897 1789 [(1789, 1), (2897, 1)] > > 6361 7541 [(6361, 1), (7541, 1)] > > 8017 8293 [(8017, 1), (8293, 1)] > > 3671 2207 [(2207, 1), (3671, 1)] > > 2803 9629 [(2803, 1), (9629, 1)] > > > > Frankly, I don't understand why factorint() reseeds at all. > > > Read the doc: > > * The rho algorithm is a Monte Carlo method whose outcome can be > > affected by changing the random seed value. * > > But that doesn't give it the right to mess with the state > of the random number generator _I'm_ using. Had I actually > known what was happening, I could have saved the state of > my random number generator s=random.getstate() and then restored > it after calling factorint(), random.setstate(s). > > import sympy # with RK's patch removed > import time > import random > > f = [i for i in sympy.primerange(1000,10000)] > > for i in xrange(10): > f1 = random.choice(f) > print f1, > f2 = random.choice(f) > print f2, > C = f1*f2 > ff = None > rs = random.getstate() > ff = sympy.factorint(C) > random.setstate(rs) > print ff > > 5669 3863 [(3863, 1), (5669, 1)] > 1973 5431 [(1973, 1), (5431, 1)] > 7577 6089 [(6089, 1), (7577, 1)] > 8761 4957 [(4957, 1), (8761, 1)] > 4153 2719 [(2719, 1), (4153, 1)] > 4999 5669 [(4999, 1), (5669, 1)] > 8863 5417 [(5417, 1), (8863, 1)] > 7151 7951 [(7151, 1), (7951, 1)] > 7867 9887 [(7867, 1), (9887, 1)] > 9283 5227 [(5227, 1), (9283, 1)] > > Of course, this is new as of Python 2.4, so if factorint() > tried to save & restore state, sympy wouldn't work on Python > 2.3 or earlier. > > If I'm reading RK's patch correctly, he doesn't reseed the > random number generator, he creates a new random object that > maintains it's own state that can be freely seeded to any > value without disturbing the state of my random number generator. > > > > > > Doesn't Random automatically initialize the seed? > > > Doesn't constantly reseeding degrade the performance of the > > > random number generator? With Robert Kern's patch, the reseeding > > > is no longer a constant, fixing the immediate symptom. > > > Does it matter? > > I was wrong. It is a constant, just not 1234. If that's what > factorint() needs, fine. As long as it maintains a seperate state > than the one I'm using. > > > The factorint reseeds using a constant seed (1234). > > Not now it doesn't: :) > > @@ -92,8 +92,8 @@ def pollard_pm1(n, B=10, seed=1234): > > """ > from math import log > - random.seed(seed + B) > - a = random.randint(2, n-1) > + prng = random.Random(seed + B) > + a = prng.randint(2, n-1) > for p in sieve.primerange(2, B): > e = int(log(B, p)) > a = pow(a, p**e, n) > > > > > > But what if _I_ wanted to make a repeatable sequence for test > > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > > on every call? > > > Repeatable sequence? save it and reuse! > > As part of my resolution to tone down my attitude, > I won't even reply to that. > Thanks. > > Think about "What if"s doesn't get any work done. > > ? nevermind. > > > > > -N From hdante at gmail.com Sun Mar 30 16:53:08 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 13:53:08 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> Message-ID: <6deb5443-e87b-448e-a1a6-6a1886c9f12a@x41g2000hsb.googlegroups.com> On Mar 30, 9:45 am, Bjoern Schliessmann wrote: > hdante wrote: > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > Could you please list some that do, and are also convenient? AFAICT there's none. This should be easy to implement on emacs, or in SCIM. > > Regards, > > Bj?rn > > -- > BOFH excuse #288: > > Hard drive sleeping. Let it wake up on it's own... From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:51:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:51:01 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <13t6d3lppl8lv2a@corp.supernews.com> On Sat, 08 Mar 2008 13:40:56 -0800, dave_mikesell wrote: > On Mar 8, 2:27 pm, castiro... at gmail.com wrote: > >> Good comments are better than bad names. Good names are better than bad >> comments. > > If you're taking the time to write good comments, why not just fix the > bad names? The compiler/interpreter can never, ever catch bad comments. Yes, but the Python compiler can only catch bad names if you do this at the top of every module: import semantic_analysis import magic.crystal_ball.read_programmers_mind Unfortunately, this comes with a *serious* performance hit, so most people don't bother. Instead, they rely on the programmer to write good descriptive names AND good comments, because not everything can be documented in a name. -- Steven From justus.schwabedal at gmx.de Fri Mar 14 13:35:51 2008 From: justus.schwabedal at gmx.de (Justus Schwabedal) Date: Fri, 14 Mar 2008 18:35:51 +0100 Subject: Problem with exec In-Reply-To: References: Message-ID: On Mar 14, 2008, at 4:41 AM, alitosis at gmail.com wrote: > On Mar 14, 9:47 am, Justus Schwabedal > wrote: > [snipped] >> However when I do this: >> >> bash-3.2$ cat execBug2.py >> #! /usr/bin/python >> header=""" >> from scipy import randn >> def f(): >> return randn() >> """ >> def g(): >> exec header >> return f() >> print "g() =",g() >> bash-3.2$ ./execBug2.py >> g() = >> Traceback (most recent call last): >> File "./execBug2.py", line 10, in >> print "g() =",g() >> File "./execBug2.py", line 9, in g >> return f() >> File "", line 4, in f >> NameError: global name 'randn' is not defined >> bash-3.2$ ??? >> >> I get this global name error. I can fix it with adding some line like >> "global randn" but I don't want to do this. I want to do exactly >> what I wrote: Import the function scipy.randn in the local >> namespace of the >> >> function "g" so that "return f()" makes sense. Can anybody help me >> out? >> Yours Justus > > Maybe using an explicit namespace is good enough for your needs: > > #! /usr/bin/python > header=""" > from scipy import randn > def f(): > return randn() > """ > def g(): > n = {} > exec header in n > return n['f']() > print "g() =",g() > > > (i don't understand the issues, but I can cut-and-paste with the best > of them) > -- > http://mail.python.org/mailman/listinfo/python-list That's what I was looking for: It's probably even a faster solution than declaring all the imports global, isn't it? From galaviel at yahoo.com Sun Mar 23 19:43:54 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Sun, 23 Mar 2008 23:43:54 +0000 (UTC) Subject: always getting 'None' return value from =?utf-8?b?UHlPYmplY3RfQ2FsbE9iamVjdA==?= Message-ID: Hello all, Kinda desperate over here .. Any help would be greatly appreciated ! I'm trying to embed a Python interpreter inside a Verilog simulator as a SystemVerilog DPI application. The python side implements a few SV exported tasks. I've got a thin C shared library as the dpi app; all it does it get the task arguments from the simulator and hand those to the Python side using the Python C API. I followed '5.3 Pure Embedding' under Python 2.5 documentation very closely. When calling a function defined in my module, the function executes Ok - it sees the correct arguments being passed from C, and executes 100% - only the return value is always 'None' (I tried returning a simple integer like '5' which doesn't work). Any ideas? Maybe scope issues? the module goes out of scope, and there is no place to store the temporary return value from the function? Where is that stored anyway with embedded python? Thanks- Gal Aviel. From castironpi at gmail.com Sat Mar 22 04:19:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 01:19:59 -0700 (PDT) Subject: function-class frustration Message-ID: >>> FunctionType.__eq__= 0 Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'function' >>> type( 'F', ( FunctionType, ), { '__eq__': e } ) Traceback (most recent call last): File "", line 1, in TypeError: type 'function' is not an acceptable base type On the other hand, are you willing to make changes to the console? How big and what? I was thinking of __ to keep the second-to-last most recent command. From pmarreddy at hotmail.com Mon Mar 10 06:01:38 2008 From: pmarreddy at hotmail.com (ditto007) Date: Mon, 10 Mar 2008 03:01:38 -0700 (PDT) Subject: An important message to all jobseekers ,and internet users In-Reply-To: <1194500148.404841.267410@k35g2000prh.googlegroups.com> References: <1194500148.404841.267410@k35g2000prh.googlegroups.com> Message-ID: <15950649.post@talk.nabble.com> http://swingwind.com more high quality placement papers at swingwind.com from 2008 http://swingwind.com/category/tag/placement-papers all IT company placement papers 2008 here -- View this message in context: http://www.nabble.com/An-important-message-to-all-jobseekers-%2Cand-internet-users-tp13641645p15950649.html Sent from the Python - python-list mailing list archive at Nabble.com. From arnodel at googlemail.com Sat Mar 15 15:40:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 15 Mar 2008 12:40:31 -0700 (PDT) Subject: Getting started with OS X Leopard References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> Message-ID: <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> On Mar 15, 7:31?pm, Mark Carter wrote: > has wrote: > > On 15 Mar, 18:05, Mark Carter wrote: > >> The sorts of things I want to do are: > >> * copy the directory of Finder to the clipboard > >> * add a new file to Finder's directory. > >> * find out the size of a directory > >> * open a file with Aquamacs, regardless of file type, > > > If you want to control desktop applications directly, that generally > > means using Apple event IPC. The most popular language for application > > scripting is traditionally AppleScript, but Apple event bridges exist > > for other languages as well. The best of these is appscript; see my > > sig for links. Some Finder scripting examples: > > > #!/usr/bin/python > > ... > > Control AppleScriptable applications from Python, Ruby and ObjC: > >http://appscript.sourceforge.net > > Aah! Many thanks. I see that I had to do > easy_install appscript > and ensure I use /usr/bin/python > I'm off to play with it now. Exciting stuff. > > I installed the Python from MacPorts. That's not quite what I wanted, > because they only have a version for Python 2.4. *Sigh*. MacPorts seems > to be getting new ports all the time. The problem is, there also seems > to be an aweful lot of ports gathering bitrot. Is there a particular reason you want python from MacPorts? OSX Leopard comes with python 2.5, that's what I use on my mac. -- Arnaud From myeates at jpl.nasa.gov Mon Mar 17 19:51:17 2008 From: myeates at jpl.nasa.gov (Mathew) Date: Mon, 17 Mar 2008 16:51:17 -0700 Subject: placing a Python com object into Excel In-Reply-To: <47deefc5$0$906$ba4acef3@news.orange.fr> References: <47deefc5$0$906$ba4acef3@news.orange.fr> Message-ID: Thanks for the tip. But, instead of an AddIn, what if I want to be able to insert an object? I see that the demo adds items to the windows registry under \Excel\AddIns. Is there a similar location for the "Insert Object" command? yikes. More Excel programming than I'd like to know. Mathew M?ta-MCI (MVP) wrote: > Hi! > > Perso, I started from "excelAddin.py" (in > C:\Python25\Lib\site-packages\win32com\demos). > And, I'm happy with the result (who run OK with Excel 2000, XP, 2007). > > @-salutations From apardon at forel.vub.ac.be Fri Mar 14 06:38:52 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Mar 2008 10:38:52 GMT Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: On 2008-03-13, Terry Reedy wrote: > > "Antoon Pardon" wrote in message > news:slrnfthp1s.61k.apardon at rcpc42.vub.ac.be... >| On 2008-02-28, Steven D'Aprano > wrote: >| > On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: >| > >| >> Hi! >| >> Can somebody of you make me a sample how to define a function based on >| >> "call by reference" ??? >| > >| > Python doesn't do call by reference. Nor does it do call by value. > Please >| > pay no attention to anyone who says it does. >| >| Whatever python has for a calling convention, it is close enough that >| naming it "call by reference" gives people a reasonable idea of what >| is going on. > > But it is also different enough to mislead people. IMO the confusing come more from people expecting the assignment to be some kind of mutating operation. >| AFAICS people don't have a problem with understanding the calling >| convention of python. They have a problem understanding the >| assignment semantics. > > The calling convention is cross-namespace assignment. So one cannot > understand calls without understanding assignment. In that case I find it very strange that when this question comes up, I see so few attempts to explain how the assignment acctually works. -- Antoon Pardon From koara at atlas.cz Fri Mar 7 08:14:09 2008 From: koara at atlas.cz (koara) Date: Fri, 7 Mar 2008 05:14:09 -0800 (PST) Subject: hidden built-in module Message-ID: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> Hello, is there a way to access a module that is hidden because another module (of the same name) is found first? More specifically, i have my own logging.py module, and inside this module, depending on how initialization goes, i may want to do 'from logging import *' from the built-in logging. I hope my description was clear, cheers. I am using python2.4. From maxerickson at gmail.com Wed Mar 12 12:12:48 2008 From: maxerickson at gmail.com (Max Erickson) Date: Wed, 12 Mar 2008 16:12:48 +0000 (UTC) Subject: Mutagen File Problem References: <81d8d48f-5496-4ca6-a525-c7b927436d4d@d62g2000hsf.googlegroups.com> Message-ID: aiwarrior wrote: > Hi i'm having a IO error saying a file does not exist even though > i perform a isFile() check. Can you help me out figuring what is > wrong? > > Thanks in advance > > from mutagen.easyid3 import EasyID3 > from mutagen.mp3 import MP3 > > for root, dirs, files in os.walk('''C:\\Documents and > Settings\\pneves\ \Music\\''', topdown=False): > for name in files: > joined = os.path.join(root, name) > if (name[-3:] == 'mp3' ): > audio = MP3(joined, ID3=EasyID3) > if not audio.has_key('album') and > os.path.isfile(joined): > print os.path.join(root, name) > > I get an error as following: > > IOError: [Errno 2] No such file or directory: 'C:\\Documents and > Settings\\pneves\\Music\\Naked Music - Miguel Migs - Colorful > You\ \Miguel Migs - Colorful you - Full album\\Miguel Migs - > Colorful you - Cd 2 -Mixed and mastered by J. Mark Andrus\\7 - > Miguel Migs feat. Lisa Shaw - You Bring Me Up (Main Vocal > Mix).mp3' It looks like the error is happending in MP3(join...), so the os.path.isfile check is never reached. If that is the case, something along the lines of: try: audio=MP3(joined, ID3=EasyID3) except: #catches any error in MP3... print joined should suppress the error and print the filename that triggered it. max From __peter__ at web.de Mon Mar 3 06:49:48 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Mar 2008 12:49:48 +0100 Subject: Regex loop question References: <7aae0102-51bd-4701-a116-60b8d9698450@s13g2000prd.googlegroups.com> Message-ID: Mike P wrote: > Hi Experts, > > I've written a peice of code that works fine and fits, and passes > values into a peice of SPSS code, the problem is that it is not > dynamic, and so i though about how i can make it dynamic, (other code > may not have upto 10 some may have more) and came up with regex for an > idea, but i can't seem to make it work, can anyone offer any advice? > Below is current working code > > time_variables = {"ActivityTime": "Activity_Time", > "ExposureTime_Last":"Exposure_Time_1", > "ExposureTime_Last2":"Exposure_Time_2", > "ExposureTime_Last3":"Exposure_Time_3", > "ExposureTime_Last4":"Exposure_Time_4", > "ExposureTime_Last5":"Exposure_Time_5", > "ExposureTime_Last6":"Exposure_Time_6", > "ExposureTime_Last7":"Exposure_Time_7", > "ExposureTime_Last8":"Exposure_Time_8", > "ExposureTime_Last9":"Exposure_Time_9", > "ExposureTime_Last10":"Exposure_Time_10"} > > for Var in time_variables.keys(): > time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . > COMPUTE %s = number(%s, TIME8). > VARIABLE LABEL %s. > VARIABLE LEVEL %s (SCALE). > FORMATS %s (TIME8). > VARIABLE WIDTH %s (8). > EXECUTE.""") %(Var, Var, > Var,time_variables[Var],Var,time_variables[Var], > time_variables[Var],time_variables[Var],time_variables[Var]) > spss.Submit(time_manips) > > > Now to make it dynamic i've gone for the following... > > reg_time = re.compile("^ExposureTime_Last([0-9]*)$") > reg_Activity = re.compile("^ActivityTime") > for Var in time_variables.keys(): > if reg_time.match(Var): > match = reg_time.match(Var) > E_time = "Exposure_Time_%s" % match.groups()[0] > else: > match = reg_time.match(Var) > match.groups()[0] = "Activity_Time" > > > time_manips = ("""COMPUTE %s = SUBSTR(%s,(INDEX(%s,'T'))+1) . > COMPUTE %s = number(%s, TIME8). > VARIABLE LABEL %s. > VARIABLE LEVEL %s (SCALE). > FORMATS %s (TIME8). > VARIABLE WIDTH %s (8). > EXECUTE.""") %(Var, Var, > Var,time_variables[Var],Var,time_variables[Var],time_variables[Var], > time_variables[Var],time_variables[Var]) > print(time_manips) > > All help welcome, or if a different approach is better please let me > know I'd clean up the original code a bit rather than introducing another source of errors (the regexes): # no warranties time_variables = [ ("ActivityTime", "Activity_Time"), ("ExposureTime_Last","Exposure_Time_1")] time_variables.extend(("ExposureTime_Last%d" % i, "Exposure_Time_%d" % i) for i in range(2, 11)) for key, value in time_variables: time_manips = """COMPUTE %(key)s = SUBSTR(%(key)s (INDEX(%(key)s,'T'))+1) . COMPUTE %(value)s = number(%(key)s, TIME8). VARIABLE LABEL %(value)s. VARIABLE LEVEL %(value)s (SCALE). FORMATS %(value)s (TIME8). VARIABLE WIDTH %(value)s (8). EXECUTE.""" % dict(key=key, value=value) spss.Submit(time_manips) It might be even better to move the logic into SPSS and to replace the numerical suffices with array indices (if supported), but I can't help you with that. Peter From hacker.stevenson at gmail.com Thu Mar 27 17:46:01 2008 From: hacker.stevenson at gmail.com (breal) Date: Thu, 27 Mar 2008 14:46:01 -0700 (PDT) Subject: Determine size of string in bytes References: <083180d3-3e7c-4db5-926f-b7528201a3b8@a22g2000hsc.googlegroups.com> Message-ID: <914e27a8-65b5-4759-80aa-1c16d88dea5c@u10g2000prn.googlegroups.com> On Mar 27, 2:10 pm, John Machin wrote: > On Mar 28, 6:45 am, breal wrote: > > > Forgive me for this question which is most likely stupid... > > The contents of your question are not stupid. The subject however does > invite a stupid answer like: len(the_string). > > Disclaimer: I know nothing about SOAP except that it's usually > capitalised :-) Now read on: > > > How do I determine the number of bytes a string takes up? I have a > > soap server that is returning a serialized string. > > Serialised how? UTF-8? > Yes. I meant to include that. I did not understand that len() returned the actual byte length of a UTF-8 encoded string. > > It seems that when > > the string goes over 65978 characters it does not return to the soap > > client. > > Why does it seem so? How did you arrive at such a precise limit? > I actually just wrote a test that would call a function on the SOAP server (SOAPpy) that would increase or decrease the test length based on the previous result until it found x, x+1 where x characters didn't fail, but x+1 did. x ended up being 65978. The string I happen to be encoding in this case has all ascii characters so it is the same for both encodings. > > Instead I get an error: > > error: (35, 'Resource temporarily unavailable') > > Is this error from the client or the server? Any error or logfile > record from the other side? > This is an error on the server. The client is actually written in PHP. There is no log file, but there is a traceback... Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/SocketServer.py", line 464, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/SocketServer.py", line 522, in __init__ self.handle() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/BaseHTTPServer.py", line 310, in handle_one_request method() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/site-packages/SOAPpy/Server.py", line 545, in do_POST self.wfile.write(resp) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/socket.py", line 262, in write self.flush() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/socket.py", line 249, in flush self._sock.sendall(buffer) error: (35, 'Resource temporarily unavailable') ---------------------------------------- > Is there anything in the documentation about maximum sizes? > > I googled my brains out looking for anything about maximum size both on the Python SOAP server, and the PHP SOAP client. > > > This makes me think the problem exists on the soap client side with > > some sort of max return length. > > Think? Can't you verify this by inspecting the source? > I haven't inspected the source, but I have inspected the documentation. No luck in finding anything about it. I suppose I could download the client source and see what I can see. > > If I knew how many bytes the 65978 > > character string was, then I could try to up this value. > > How do you know the string is 65978 characters? If you are debugging > the server, can't you do len(serialise(the_65978_char_string))? > > 65978? Are you sure? Looks suspiciously close to 65535 aka 0xFFFF aka > (2 ** 16 - 1 ) to me. > > If you have the server, you presumably have the source code for both > client and server. Some options for you: > > (1) Look at the traceback(s), look at the source code, nut it out for > yourself. If there is some kind of max other than an implicit 16-bit > limitation in the client code, it shouldn't be too hard to find. > > (2) Post the traceback(s) here, along with other details that might be > useful, like what SOAP server s/w you are using, what version of > Python, what platform. > See traceback above. SOAPpy Python 2.5 OSX Server Thanks for the response John. From http Fri Mar 28 02:32:55 2008 From: http (Paul Rubin) Date: 27 Mar 2008 23:32:55 -0700 Subject: SoC project: Python-Haskell bridge - request for feedback References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: <7xej9vbboo.fsf@ruckus.brouhaha.com> malkarouri writes: > FWIW, I find #1 more interesting for me personally. > As a monad-challenged person, I find it much easier to develop > components using pure functional programming in a language like > Haskell and do all my I/O in Python than having it the other way > round. Haskell i/o is not that complicated, and monads are used in pure computation as well as for i/o. Without getting technical, monads are the bicycles that Haskell uses to get values from one place to another in the right order. They are scary at first, but once you get a little practice riding them, the understanding stays with you and makes perfect sense. From cwitts at gmail.com Thu Mar 20 07:38:04 2008 From: cwitts at gmail.com (Chris) Date: Thu, 20 Mar 2008 04:38:04 -0700 (PDT) Subject: A question about a metacharacter References: Message-ID: <09156537-3eb3-4cff-b1f6-3727ca660f6f@p73g2000hsd.googlegroups.com> On Mar 20, 1:19?pm, igbt wrote: > I am creating a simple script which is using gtk. In this script you > must enter a text, if you do not enter anything or you enter a dot, > the script will be finished. However, if you don't enter anything the > script works but if you enter a dot (.) the script does not work. I > was investigating about it and I think the problem is with the dot > character ?sss == "." . ?I was trying the same line with other > metacharacters like *, (, ) ... ?and I found the same problem. I was > looking for an example where I could see the way I could do it without > any error but I did not find it. Could somebody tell me how can I > solve this error? > > sss = entryName.get_text() ? ? ?# The script gets the text > ? ? ? ? if sss == "" or sss == ".": > ? ? ? ? ? ? ? ? gtk.main_quit() ? ? ? ?#The script finishes > > Thanks ; -) try this. sss = entryName.get_text() if not sss.strip() or sss.strip() == '.': gtk.main_quit() I wouldn't be suprised if your input is being captured with End-Of- Line characters which would cause the mis-match. From sjmachin at lexicon.net Fri Mar 7 18:12:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 15:12:57 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> On Mar 8, 1:53 am, "hvendelbo.... at googlemail.com" wrote: > On Mar 6, 9:17 pm, Luis M. Gonz?lez wrote: > > > > > On 6 mar, 11:27, Pierre Quentel wrote: > > > > Hi, > > > > I would like to know if there is a module that converts a string to a > > > value of the "most probable type" ; for instance : > > > - if the string is "abcd" the value is the same string "abcd" > > > - string "123" : value = the integer 123 > > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > > = the float -1.23 > > > - string "2008/03/06" (the format is also locale-dependant) : value = > > > datetime.date(2008,03,06) > > > > Like in spreadsheets, special prefixes could be used to force the > > > type : for instance '123 would be converted to the *string* "123" > > > instead of the *integer* 123 > > > > I could code it myself, but this wheel is probably already invented > > > > Regards, > > > Pierre > > >>> def convert(x): > > > if '.' in x: > > try: return float(x) > > except ValueError: return x > > else: > > try: return int(x) > > except: return x > > > >>> convert('123') > > 123 > > >>> convert('123.99') > > 123.98999999999999 > > >>> convert('hello') > > > 'hello' > > Neat solution. The real challenge though is whether to support > localised dates, these are all valid: > 20/10/01 > 102001 > 20-10-2001 > 20011020 Neat solution doesn't handle the case of using dots as date separators e.g. 20.10.01 [they are used in dates in some locales and the location of . on the numeric keypad is easier on the pinkies than / or -] I'm a bit dubious about the utility of "most likely format" for ONE input. I've used a brute-force approach when inspecting largish CSV files (with a low but non-zero rate of typos etc) with the goal of determining what is the most likely type of data in each column. E.g 102001 could be a valid MMDDYY date, but not a valid DDMMYY or YYMMDD date. 121212 could be all of those. Both qualify as int, float and text. A column with 100% of entries qualifying as text, 99.999% as float, 99.99% as integer, 99.9% as DDMMYY, and much lower percentages as MMDDYY and YYMMDD would be tagged as DDMMYY. The general rule is: pick the type whose priority is highest and whose score exceeds a threshold. Priorities: date > int > float > text. Finding the date order works well with things like date of birth where there is a wide distribution of days and years. However a field (e.g. date interest credited to bank account) where the day is always 01 and the year is in 01 to 08 would give the same scores for each of 3 date orders ... eye-balling the actual data never goes astray. From bjourne at gmail.com Mon Mar 17 18:24:21 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Mar 2008 22:24:21 +0000 Subject: Interesting math problem Message-ID: <740c3aec0803171524o727dd129ycfeaff4de5cbafdd@mail.gmail.com> Here is an interesting math problem: You have a number X > 0 and another number Y > 0. The goal is to divide X into a list with length Y. Each item in the list is an integer. The sum of all integers is X. Each integer is either A or A + 1, those should be "evenly distributed." Example: 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] 16 // 4 = 4 gives the list [4, 4, 4, 4] 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] This algorithm is used a lot in programming. For example, for projecting a line on a pixel display. Your mission, should you choose to accept it, is to improve the code given below which is my best attempt and make it more succinct and easier to read. Preferably by using list comprehensions, map or even reduce.... def make_slope(distance, parts): step = distance / float(parts) intstep = int(step) floatstep = step - intstep steps = [] acc = 0.0 for i in range(parts): acc += floatstep step = intstep if acc > 0.999: step += 1 acc -= 1.0 steps.append(step) return steps # Test code distance = 130 parts = 50 L = make_slope(distance, parts) assert(len(L) == parts) assert(sum(L) == distance) print L -- mvh Bj?rn From 42flicks at gmail.com Wed Mar 19 05:06:19 2008 From: 42flicks at gmail.com (Mike D) Date: Wed, 19 Mar 2008 22:06:19 +1300 Subject: PODCasts Message-ID: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> I really should say net cast as I think it's a better term ;) Does anyone have any recommended net casts on Python, or programming in general? Whats everyone listening to? Cheers Guys! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Glich.Glich at googlemail.com Tue Mar 25 16:36:06 2008 From: Glich.Glich at googlemail.com (Glich) Date: Tue, 25 Mar 2008 13:36:06 -0700 (PDT) Subject: python, dbus and pointers help. References: <16059cb8-a182-40ff-9617-a8b6708e1183@s19g2000prg.googlegroups.com> <61a383ca-e287-4d13-a3b0-ba9ec24626fa@d21g2000prf.googlegroups.com> Message-ID: <97d86072-b58b-4b0d-a0a0-143cb36e51ef@i7g2000prf.googlegroups.com> A replay from ubuntu forums: by Roptaty: Using dbus you can only get information from Pidgin, you cant modify the information. To do this, you need to write a plugin loaded in Pidgin. (See http://developer.pidgin.im/wiki/DbusHowto ) From jgardner at jonathangardner.net Fri Mar 21 15:18:57 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Mar 2008 12:18:57 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <23936074-babf-454f-b4a3-bc4207e209f9@e10g2000prf.googlegroups.com> On Mar 21, 4:48?am, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > Allow me to differ with all of the previous posts... Why don't you setup an SVN repository (or Git or DARCS, etc...) that has the current version you want to run? Then, execute the script in two steps: 1) Update the local copy from the repository 2) Run the script The only hard part is writing the script to do the above two things. Of course, that can be done with a python script (but if you were in the Unix world, I would suggest a shell script.) Or you can separate out the two steps. Update the SVN version once a day, or once and hour, or something like that. In general, my gut says to avoid writing new code when you can get away with it. From sjmachin at lexicon.net Tue Mar 18 15:26:33 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Mar 2008 12:26:33 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> Message-ID: <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> On Mar 18, 9:43 pm, Godzilla wrote: > Thanks Roel. If there is a way to pass in the PRESERVE_PRECISION > constant in the python time.clock library, that would be great Re-read Roel's message. Something like PRESERVE_PRECISION is to be passed to whatever is setting up DirectX. > But > I'm afraid it's not possible. I think I will change away from using > time.clock() from now on... seems too edgy to me. Are you using DirectX? If so, read the docs for more clues -- a quick google for "PRESERVE_PRECISION" will tell you that "something like" means what it says. If not, try posting some more info on what you are actually doing. Consider providing a short piece of code that demonstrates the actual problem. From myonov at gmail.com Tue Mar 25 14:51:20 2008 From: myonov at gmail.com (myonov at gmail.com) Date: Tue, 25 Mar 2008 11:51:20 -0700 (PDT) Subject: Disable resize button References: <47e7cca5$0$16036$5fc30a8@news.tiscali.it> Message-ID: On Mar 24, 5:45 pm, Francesco Bochicchio wrote: > Il Mon, 24 Mar 2008 04:38:50 -0700, myonov ha scritto: > > > > > Hi! > > > I need to disable resize button in Tkinter. I inherit the Frame class. > > Then in the constructor i make my buttons, labels, etc. Then I pack them > > and when move borders of the frame everything changes it's location and > > it looks really bad. How can I change that? > > That's my code: > > # -*- coding: cp1251 -*- > > import Tkinter > > > class App(Tkinter.Frame): > > def click(self): > > pass > > > def click2(self): > > pass > > > def __init__(self, master=None): > > Tkinter.Frame.__init__(self, master, width = 700, height = > > 400,\ > > bg = "#999999") > > self.pack() > > > # Buttons > > > self.b1 = Tkinter.Button(self, text = u"?????? ?????",\ > > command=self.click, font = "Courier", > > \ > > fg = "red") > > self.b2 = Tkinter.Button(self, text = u"?????? ???????",\ > > command=self.click2, font = "Courier", > > \ > > fg = "red") > > self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = > > 0.75, rely = 0.4) > > > # Labels > > > self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ > > text = u"??????????", fg = "#ffffff",\ > > bg = "#999999") > > self.l1.place(x = 275, y = 10) > > > # Text Control > > # self.txt = Tkinter.Text(self, bg = "#124456", ) # > > self.txt.pack() > > You could try including the frame in a toplevel window (e.g. passing > Tkinter.Tk() as super) and then doing super.wm_resizable(None, None) > > A better idea would be using pack instead of place, leaving to the > toolkit the job of rearranging the widgets when the window is enlarged > or reduced. > > Ciao > ----- > FB Thanks a lot :) Is there a way to avoid Tk() and to disable resize button only for an instance of a class which inherits Frame? From durumdara at gmail.com Tue Mar 11 05:00:12 2008 From: durumdara at gmail.com (durumdara at gmail.com) Date: Tue, 11 Mar 2008 10:00:12 +0100 Subject: Python PDF + Pictures Message-ID: Hi, dear Python Masters! I wanna ask about the Python and PDF creating. I have many photos, and I wanna make some "presentation" from these photos, a "thumbnail" like document with one image per one page. If I wanna make one document now I do this: I execute a python script that create a html site with resized pictures, and split this html site to 50 images per one html file. Next I open these files in OpenOffice Writer by hand, and save them as PDF document with poor quality (image compression 95%, image DPI 75). This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that can opened everywhere (because of PDF format). But I wanna automatize this process with python. The technic that I will use is this: 1.) Collect the files in dirs. 2.) I process one dir in one time. 3.) I get the files. 4.) I resize them to max. 1024/768. 5.) I put the actual image file to the PDF document. 6.) After each 50. file I open new numbered PDF. 7.) Every picture placed in one page, and every page orientation set up as the picture orientation (Portrait or Landscape). The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. Do you knows about a PDF maker library with I can make this thing? Or other technic to simplify the making? Thanks for your help! dd From namit at namit.org Mon Mar 3 23:28:24 2008 From: namit at namit.org (Christian Kortenhorst) Date: Tue, 4 Mar 2008 04:28:24 +0000 Subject: cron popen xen-create-image Message-ID: Hey just wondering could anyone help me Have script that runs through cron but seams to run but xen-create-image goes to end but shoes up errors because some stuff it not being passed. ./grabJob.py # RUN all the Create ENVIRONMNET commands here run="/usr/bin/xen-create-image --hostname=%s --ip=%s" % (hostname, ipadd[0]) print run; try: fs=os.popen(run) for file in fs: error = error + file If run just ./grabJob.py it works ok and outputs en:/var/www/apache2-default# ./grabJob.py Grabbing Jobs running create Jobs runnning.... Creating environment ckortenhorst1 /usr/bin/xen-create-image --hostname=ckortenhorst1 --ip=192.168.0.111 DONE Can anyone help -- Christian Kortenhorst +353-(0)87-6183349 +353-(0)1-4966287 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Fri Mar 21 18:56:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 21 Mar 2008 15:56:34 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Message-ID: <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> Ricky Zhou: > Look at the this line: > if 'one' and 'two' in f: Very cute, it's the first time I see a bug like this. I think it's not a common enough pattern to justify a language change, but a bit smarter computer language may be able to do that too ;-) (it's not easy to tell the two meanings apart, from a simple point of view the semantics is ambiguous) Maybe an AppleScript-like language can be designed to have such capabilities too :-) A more computer-friendly (and Pythonic) syntax may be ('are' is a keyword): if ('one', 'two') are in f: ... That's sugar for: if all(x in f for x in ('one', 'two')): ... Bye, bearophile From mail at timgolden.me.uk Fri Mar 14 13:15:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 14 Mar 2008 17:15:26 +0000 Subject: request for Details about Dictionaries in Python In-Reply-To: <47DAB078.9050705@mattnordhoff.com> References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> <47DAB078.9050705@mattnordhoff.com> Message-ID: <47DAB2AE.80907@timgolden.me.uk> Matt Nordhoff wrote: > Michael Wieher wrote: >> I'm not sure if a well-written file/seek/read algorithm is faster than a >> relational database... >> sure a database can store relations and triggers and all that, but if >> he's just doing a lookup for static data, then I'm thinking disk IO is >> faster for him? not sure > > I would think that rolling your own solution would get complicated > enough that it would be easier to just use SQLite or something. If you > wanted to go to the effort, you could probably get something faster, but > if SQLite is fast enough, who cares? I would concur with this, in general. It may be that, for some very particular situations some specialised storage format is superior, but it's *very* easy to start writing your lean and mean data storage / algorithm / thingy only to run into *exactly* the same issues which the guys who wrote the existing ones have already hit and solved. Problems scaling; concurrency; robustness to error conditions and network / hardware issues &c. And in any case, the usual wisdom applies here: rather than guess which is faster, try it. (There is no "guess": only "try" ;) Using say SQLite (possibly in memory mode) and get some figures. Then do the same with a shelve solution or some prototype of your own devising and see where the gains are. TJG From sjmachin at lexicon.net Fri Mar 28 23:09:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Mar 2008 20:09:50 -0700 (PDT) Subject: Help me on function definition References: Message-ID: On Mar 29, 12:47 pm, "aeneng" wrote: > Hello everyone, > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this>>> import cross > > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 > ppp1=u[1]*v[2]-u[2]*v[1] > ppp2=u[2]*v[0]-u[0]*v[2] > ppp3=u[0]*v[1]-u[1]*v[0] > # store the result of the cross product in u > u[0]=ppp1 > u[1]=ppp2 > u[2]=ppp3 > return u #return the cross product of vector u x v. And you are stuffing the result into the first argument as well as returning the result ... not a good idea. > if __name__=="__main__": > from cvxopt.base import matrix > u=matrix([1.0,0.0,0.0],(3,1)) > v=matrix([0.0,1.0,0.0],(3,1)) > print cross(u,v) > print "file name is %s" %__name__ From martin at v.loewis.de Fri Mar 21 16:53:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 21:53:00 +0100 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] In-Reply-To: References: Message-ID: <47E4202C.5060400@v.loewis.de> > I've been thinking of volunteering to "port" Tkinter to Python 3.0, I > hadn't noticed that there was any discussion of removing it. It would > be a shame IMHO. I don't think Tkinter will be removed. It works just fine in 3k. Of course, if you would port IDLE to Tk 8.5: that would be a useful contribution. Regards, Martin From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 22:54:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 02:54:53 -0000 Subject: string / split method on ASCII code? References: Message-ID: <13th5rtiqh2gnc6@corp.supernews.com> Sorry for breaking threading by replying to a reply, but I don't seem to have the original post. On Wed, 2008-03-12 at 15:29 -0500, Michael Wieher wrote: > Hey all, > > I have these annoying textilfes that are delimited by the ASCII char > for << (only its a single character) and >> (again a single character) > > Their codes are 174 and 175, respectively. > > My datafiles are in the moronic form > > X<>Z The glyph that looks like "<<" is a left quote in some European countries (and a right quote in others, sigh...), and similar for ">>", and are usually known as left and right "angle quotation mark", chevron or guillemet. And yes, that certainly looks like a moronic form for a data file. But whatever the characters are, we can work with them as normal, if you don't mind ignoring that they don't display properly everywhere: >>> lq = chr(174) >>> rq = chr(175) >>> s = "x" + lq + "y" + rq + "z" >>> print s x?y?z >>> s.split(lq) ['x', 'y\xafz'] >>> s.split(rq) ['x\xaey', 'z'] And you can use regular expressions as well. Assuming that the quotes are never nested: >>> import re >>> r = re.compile(lq + '(.*?)' + rq) >>> r.search(s).group(1) 'y' If you want to treat both characters the same: >>> s = s.replace(lq, rq) >>> s.split(rq) ['x', 'y', 'z'] -- Steven From arnodel at googlemail.com Tue Mar 18 18:45:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 15:45:42 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: On Mar 18, 9:56?pm, sturlamolden wrote: > On 18 Mar, 22:25, sturlamolden wrote: > > > def nonunique(lst): > > ? ?slst = sorted(lst) > > ? ?return list(set([s[0] for s in > > ? ? ? ?filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) > > Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using > the set function, there is more structure to exploit when the list is > sorted: > > def nonunique(lst): > ? ?slst = sorted(lst) > ? ?dups = [s[0] for s in > ? ? ? ? filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > ? ?return [dups[0]] + [s[1] for s in > ? ? ? ? filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] Argh! What's wrong with something like: def duplicates(l): i = j = object() for k in sorted(l): if i != j == k: yield k i, j = j, k >>> list(duplicates([1, 2, 3, 2, 2, 4, 1])) [1, 2] -- Arnaud From yuxi at ece.gatech.edu Mon Mar 10 19:48:21 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 10 Mar 2008 19:48:21 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > Thanks for the info! SIFT really looks like a heavy weight solution, > but do you think the whole concept can be simplified if all I needed > was: given a photo, find similar ones? I mean SIFT first detects > objects on the image and find similarities, but I don't need the > detection part at all, all I care about is similarity for the whole > photo. I surely don't understand the big picture fully but just have > the general feeling that SIFT and other expert tools are an overkill > for me and a simplified version would be just as good with a much more > easily comprehensible core algorithm. Please describe the kind of photos you are dealing with. Are they identical photos, in say different formats or with different metadata? Or are they rescaled images? Or maybe they are the same photo cropped differently? SIFT will work in more or less the process you described in your first post. It basically calculates the N sets of numbers for each image, representing the unique features of that image and their relative positions. The rest of the process if up to you. You have to compare the different sets of numbers to find the image with the minimal difference, as opposed to comparing the whole image. From jeffrey at fro.man Fri Mar 7 17:35:53 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 07 Mar 2008 14:35:53 -0800 Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <13t3gq9qo0po5ce@corp.supernews.com> shakefu at gmail.com wrote: > I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. Django comes with some pretty handy filters for doing this sort of formatting. Check out the "date", "now", "timesince" and "timeuntil" filters here: http://www.djangoproject.com/documentation/templates/#built-in-filter-reference Jeffrey From nothanks at null.invalid Sat Mar 22 23:25:25 2008 From: nothanks at null.invalid (Bill) Date: Sat, 22 Mar 2008 23:25:25 -0400 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <47E5CDA5.90709@null.invalid> sturlamolden wrote, On 3/20/2008 9:41 AM: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > What don't you like about wxGlade? It actually generates Python code. There has been a lot more development going on recently, too. Bill From willsteve2003 at yahoo.ca Mon Mar 10 10:43:59 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 07:43:59 -0700 (PDT) Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: <7a6555fa-819a-41c0-befe-ee0123272b31@59g2000hsb.googlegroups.com> On Mar 8, 4:15?pm, "Terry Reedy" wrote: > "egbert" wrote in message > > news:20080308152034.GA12009 at hccnet.nl... > | However the loop-else really works more like this: > | . ?try to do the loop; > | . ?if it starts but is interrupted by a break, > | . ?then do something else as well. > > This is NOT how loop-else works for Python. > If you want to do something special on breaks, > put the break-only code before the break. > > while loop_condition: > ? > ? if break_condition: > ? ? > ? ? break > ? > > | So they are completely different beasts, and if you try to use > | or explain the one according to the rules of the other one, > | you put a serious strain on your synapses. > > I did not mean to broke your brain. > > | The explanation that the if-else and the loop-else > | follow the same pattern, runs more or less like this: > | . ?all conditions to run the loop to its completion were met, > | . ?which means that the loop-condition is not met (any more), > | . ?which means that we must do something else. > | For me that is orwellian logic: success is failure. > > I gave a clear and coherent explanation of how while derives from if, > and correspondingly, how while-else derives from if-else, to help those who > want to read and write Python code. ?Building on the pseudo-snippet above, > one can write > > while loop_condition: > ? > ? if break_condition: > ? ? > ? ? break > ? > else: > ? > > Python allows one to have both break-only and completion-only sections > together in one compound statement and *without* having to fiddle with a > special flag variable. ?I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. > > If the sense of else were reversed, one would have to write the clumbsier > > complete = True # though false at this point > while loop_condition: > ? > ? if break_condition: > ? ? complete = False > ? ? break > ? > else: > ? > if complete: > ? > > Terry Jan Reedy Terry, instead of using "complete = True" and setting it to false on failure, why not set "loop_completed = False" and set it to True if the break condition is met? From fn681 at ncf.ca Fri Mar 21 10:09:39 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:09:39 -0500 Subject: Improving datetime In-Reply-To: References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <47E3C1A3.6050608@ncf.ca> Nicholas F. Fabry wrote: > On Mar 19, 2008, at 16:30, Christian Heimes wrote: > >> Nicholas F. Fabry schrieb: >>> This is a query for information as to how to proceed. I am not a >>> professional programmer, but I use Python a great deal to help me in >>> my main job, which involves designing schedules for a global >>> airline. As such, I use datetime (and dateutil) extensively, and >>> after much use, I have come to some conclusions about their utility, >>> and how to improve them. Some of these changes are quite minor and >>> would result in a large increase in utility (low hanging fruit), >>> while some changes are major, and would result in less obvious >>> benefits - but these changes would increase the 'Python Zen' of them. >>> So - where should I propose these changes? Here? python-dev? >>> Should I write up a full PEP or should I just give a more informal >>> outline with code samples? I would volunteer to help >>> maintain/improve datetime, but I don't speak C at all, >>> unfortunately, and datetime appears to be in C. >> >> Please write a detailed but not too long proposal to the Python ideas >> mailing list. The proposal should explain how you like to improve the >> datetime module. But *please* don't write a novel. You'll get more >> attention when the signal to noise ratio is high. A bullet list of >> features is easier to read than a long text block. >> > > Thank you for the prompt response and suggestion! I am writing up a > proposal presently. There are, however, two broad category of changes - > the 'easy' changes, which could be accomplished with little additional > effort, and the 'hard' changes, which would require significant > reworking of the datetime class (or a wrapper around it). I was going > to break my proposal up into two parts, the easy part and the hard > part. Does that sound like a good idea? Or should I unify the two? > The prime purpose of all the changes, easy and hard, is to make timezone > handling accurate and clear, reduce and make clearer the (application > programmer) code required to use them, and give more informaton to the > programmer about errors, not silently assume something and pass them. > > I have to sign up for that mailing list - I will do so, and submit my > ideas there. > > Please clarify how long a novel is? The problem with the modules are > not bugs, they are problems with real world use scenarios that result in > inescabably ugly code without improvements to the module - so the > explanations involve code samples and use cases... so they may be > 'long'. Could you suggest a maximum number of (70 char) lines, or an > example of an overly long proposal? > > >> I'm a core developer and I may be interested in mentoring your >> proposal. I can guide you through the process, review code and commit it. >> > > Thank you very much for the offer - I greatly appreciate it. I must > admit, my motivation is because Python made programming so much fun for > me again (my first machine was a Sinclair ZX80, long, long ago), and I > want to improve this part of the language so datetime calculations are > clean and neat (like the rest of Python) and don't force programmers to > manually go through what the library should do for them. > > >> Yes, the datetime module is written in C. But we may move the C code >> to _datetime and create a facade module in Python. >> > > That would be excellent for me, because the underlying datetime routines > work correctly and quickly; it's the 'topmost' layer that needs to be > improved to do the right thing. And, I could then actually > write/maintain the Python code in the facade module, rather than request > someone else 'do it for me' in C. > > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but > calculate/compare in UTC. > > - Raise exceptions when an illegal or ambiguous datetime is instantated. > > > Thank you again, > > Nick > > > > > > >> Christian Nick, You might consider adding the Julian date (http://en.wikipedia.org/wiki/Julian_date). I had a crack at this a while ago but didn't seem to get quire the right result, using the ACM algorithm. I seemed to be a day out at the BC/AD divide. Colin W. > From ptmcg at austin.rr.com Sat Mar 8 17:10:33 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 8 Mar 2008 14:10:33 -0800 (PST) Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> <47d2f0da$0$4794$4fafbaef@reader4.news.tin.it> Message-ID: <0d82e366-9112-4e45-930d-f53301a9741d@b1g2000hsg.googlegroups.com> On Mar 8, 2:02?pm, Nemesis wrote: > Bryan.Fodn... at gmail.com wrote: > > I have a large file that has many lines like this, > > > > name="DoseReferenceStructureType">SITE > > > I would like to identify the line by the tag (300a,0014) and then grab > > the name (DoseReferenceStructureType) and value (SITE). > > You should try with Regular Expressions or if it is something like xml there > is for sure a library you can you to parse it ... When it comes to parsing HTML or XML of uncontrolled origin, regular expressions are an iffy proposition. You'd be amazed what kind of junk shows up inside an XML (or worse, HTML) tag. Pyparsing includes a builtin method for constructing tag matching parsing patterns, which you can then use to scan through the XML or HTML source: from pyparsing import makeXMLTags, withAttribute, SkipTo testdata = """ SITE SITEXXX SITE2 """ elementStart,elementEnd = makeXMLTags("element") elementStart.setParseAction(withAttribute(tag="300a,0014")) search = elementStart + SkipTo(elementEnd)("body") for t in search.searchString(testdata): print t.name print t.body Prints: DoseReferenceStructureType SITE DoseReferenceStructureType SITE2 In this case, the parse action withAttribute filters tag matches, accepting *only* those with the attribute "tag" and the value "300a,0014". The pattern search adds on the body of the tag, and gives it the name "body" so it is easily accessed after parsing is completed. -- Paul (More about pyparsing at http://pyparsing.wikispaces.com.) From see.signature at no.spam Tue Mar 25 12:23:30 2008 From: see.signature at no.spam (Eric Brunel) Date: Tue, 25 Mar 2008 17:23:30 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: On Tue, 25 Mar 2008 16:37:00 +0100, Brian Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Gerard Flanagan wrote: > >> Use the child class when calling super: >> >> -------------------------------------- >> class Foo(object): >> def __init__(self): >> self.id = 1 >> >> def getid(self): >> return self.id >> >> class FooSon(Foo): >> def __init__(self): >> Foo.__init__(self) >> self.id = 2 >> >> def getid(self): >> a = super(FooSon, self).getid() >> b = self.id >> return '%d.%d' % (a,b) >> >> print FooSon().getid() >> -------------------------------------- > > That still doesn't do what he's trying to do. > > The problem here is that you only have one instance. self refers to it, > so when you set self.id in the super you have set the instance's id to > 1. When you set it to 2 after calling the super's __init__ you are now > setting the *same* variable to a 2. > > Basically, you can't do what you are trying to do without using a > different variable, or keeping track of a separate instance for the > super instead of sub-classing it. If for any reason it's better to have the same attribute name, it might be a case where a "pseudo-private" attribute - i.e. prefixed with __ - can be handy: -------------------------------------- class Foo(object): def __init__(self): self.__id = 1 def getid(self): return self.__id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.__id = 2 def getid(self): a = super(FooSon, self).getid() b = self.__id return '%d.%d' % (a,b) print FooSon().getid() -------------------------------------- For an explanation, see here: http://docs.python.org/ref/atom-identifiers.html HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From willsteve2003 at yahoo.ca Mon Mar 10 10:37:59 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 07:37:59 -0700 (PDT) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8b9469d6-5b73-4f5f-8aa5-51c8dfdb2fd0@y77g2000hsy.googlegroups.com> Message-ID: <4cd70ab7-7ba2-4f02-b180-415e555697e1@b64g2000hsa.googlegroups.com> On Mar 7, 5:26?pm, shak... at gmail.com wrote: > On Mar 7, 4:22 pm, shak... at gmail.com wrote: > [snip]> Although if I end up writing my own I'll sure use > > datetime.parser.parse to get everything left over once you remove > > I mean dateutil.parser.parse. Tomorrow I'll have to leave off the last > Lunchtime Guiness. > > > strings like "this saturday". So it helps a little! > > > Jacob > > And on the same thought - does anyone know of a good website, resource > or community that's got intelligible descriptions of all the different > modules that are generally available? I know if I tab complete 'apt- > get install python-*' it tries to list 1000-some possibilities, so I'm > thinking there's quite a few modules out there that I might like to > know about and use... > > Thanks! > Jacob Jacom, the http://www.python.org/ site offers most of the modules, including an index: http://pypi.python.org/pypi Then there's the ASPN site: http://aspn.activestate.com/ASPN/Downloads/ActivePython From mattheww at chiark.greenend.org.uk Wed Mar 5 15:33:21 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Mar 2008 20:33:21 +0000 (GMT) Subject: documenting formal operational semantics of Python References: <5a1d6c9d-ddd6-48bc-bb71-1b4e0a55962d@z17g2000hsg.googlegroups.com> Message-ID: gideon wrote: > In the context of a master's thesis I'm currently looking into > Python's operational semantics. Even after extensive searching on the > web, I have not found any formal model of Python. Therefore I am > considering to write one myself. To make a more informed decision, I > would like to ask you: [...] > Which version of Python is the most interesting? Python 3.0, although > it would be a moving target, seems promising. Because it will simplify > the language in some aspects by ditching backwards compatibility (e.g. > old style classes and coercion), the semantics will be more clean. Why not start with a common subset? Presumably the easiest thing will be to start with a small core of the language and work up anyway. It might turn out that all the interesting work has been done by the time 2.x/3.x makes any difference. -M- From jr9445 at ATT.COM Thu Mar 20 17:14:00 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 20 Mar 2008 16:14:00 -0500 Subject: Haskell vs ?? In-Reply-To: References: Message-ID: > From: python-list-bounces+jr9445=att.com at python.org > [mailto:python-list-bounces+jr9445=att.com at python.org] On Behalf Of > Michael Wieher > Sent: Thursday, March 20, 2008 4:36 PM > To: python-list at python.org > Subject: Haskell vs ?? > > Just to help clear up my own understanding of this discussion, this > is basically a language that obfuscates details and makes low-level > decisions in a "average-best" way, and thus allows for lazy people > to write kind of decent code quickly? Change "obfuscates details" to focuses on the right level of detail. C's details are too low. Python ignores details to the point that you don't find dumb type-casting mistakes until the code is actually being executed. "makes low-level decisions in a "average-best" way," Yes, just like how CPython is considered slow because of it's silly garbage collecting, too dynamically typed to be optimized, paradigm. > allows for lazy people to write kind of decent code quickly? No, it's not at all like a usenet group or mailing list where people are too lazy to post kind of thought out comments. ;-) The whole point of coding is to implement a requirement. A requirement is tied back to a business case, and a business case is an idea on how to get people to give you money in return for your service or product. Any code that doesn't directly implement the business case is 'overhead' (such as memory management, having to execute every single line of your Python code in order to catch type mismatches instead of having a compiler find such things early in development, having to write verbose|obfuscated syntax that requires more debugging since it's so verbose|obfuscated, responding to trolls, etc.) In theory, it follows the "less is more" strategy but without crossing the line into anarchy or the Wild West (i.e., no type checking,) while not being so syntactically brief as to look like hieroglyphics. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From mensanator at aol.com Tue Mar 4 15:13:44 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 12:13:44 -0800 (PST) Subject: sympy: what's wrong with this picture? References: Message-ID: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> On Mar 4, 12:32?pm, Nanjundi wrote: > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > > > Notice anything funny about the "random" choices? > > > import sympy > > import time > > import random > > > f = [i for i in sympy.primerange(1000,10000)] > > > for i in xrange(10): > > ? f1 = random.choice(f) > > ? print f1, > > ? f2 = random.choice(f) > > ? print f2, > > ? C = f1*f2 > > ? ff = None > > ? ff = sympy.factorint(C) > > ? print ff > > > ## ?7307 7243 [(7243, 1), (7307, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > As in, "they're NOT random". > > > The random number generator is broken by the sympy.factorint() > > function. > > > Random.choice() works ok if the factorint() function commented out. > > > ## ?6089 1811 None > > ## ?6449 1759 None > > ## ?9923 4639 None > > ## ?4013 4889 None > > ## ?4349 2029 None > > ## ?6703 8677 None > > ## ?1879 1867 None > > ## ?5153 5279 None > > ## ?2011 4937 None > > ## ?7253 5507 None > > > This makes sympy worse than worthless, as it fucks up other modules. > > Does seeding ( random.seed ) random with time fix this? It should. I suppose that depends on how long it takes factorint() to process a number. If the seed is reset before the next clock tick, you will get the same random numbers as the previous iteration. Frankly, I don't understand why factorint() reseeds at all. Doesn't Random automatically initialize the seed? Doesn't constantly reseeding degrade the performance of the random number generator? With Robert Kern's patch, the reseeding is no longer a constant, fixing the immediate symptom. But what if _I_ wanted to make a repeatable sequence for test purposes? Wouldn't factorint() destroy my attempt by reseeding on every call? > -N From fumanchu at aminus.org Tue Mar 18 14:41:17 2008 From: fumanchu at aminus.org (fumanchu) Date: Tue, 18 Mar 2008 11:41:17 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> Message-ID: <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> On Mar 17, 6:25 pm, dundeemt wrote: > I agree - the balance wasn't as good. We can all agree that HowTos > and Intros are a necessary part of the conference talks track, but as > Robert pointed out some talks should be of a more advanced nature. I > enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and > Mark Hammond's keynote were among my favorite talks. Raymond Hettinger's talk on collections was not only one of my favorites, it was apparently lots of other people's too--the room was PACKED. I can't recall seeing any other talk that was even close to seating capacity. Robert Brewer fumanchu at aminus.org From deets at nospam.web.de Mon Mar 17 17:53:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 22:53:11 +0100 Subject: Convert binary file In-Reply-To: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> References: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> Message-ID: <6487iaF2ar8k2U1@mid.uni-berlin.de> Vamp4L schrieb: > Hello, > Specifically, I'm trying to convert the Internet Explorer history > file (index.dat) into a readable format. Anyone done something > similar or know of any functions that may help with such a task? I'm > not sure exactly what kind of file the index.dat is, it is some kind > of binary file. I have tried some of the binascii functions (http:// > docs.python.org/lib/module-binascii.html) without any luck. > Thanks You have to have a definition of the format or reverse engineer it. If you have done that, you can use the module struct. But there is no generic way to infer how a binary format is built. Diez From john.jython at gmail.com Tue Mar 25 06:44:59 2008 From: john.jython at gmail.com (john s.) Date: Tue, 25 Mar 2008 03:44:59 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> On Mar 24, 9:39 pm, "Ryan Ginstrom" wrote: > > On Behalf Of john s. > > import os, sys, string, copy, getopt, linecache > > from traceback import format_exception > > > #The file we read in... > > fileHandle = "/etc/passwd" > > srcFile = open(fileHandle,'r') > > srcList = srcFile.readlines() > > > #yah, a for loop that "iterates" through the file of "lines" > > for i in srcList: > > strUsr = string.split(i,":") > > theUsr = strUsr[0] > > usrHome = "/expirt/home/",theUsr,"/" > > usrHome = ''.join(usrHome) > > How about for starters: > > import os > > for line in open("/etc/passwd"): > user, _pwd = line.split(":") ^----- Ok this one here we are taking a string spliting it into to variables... user gets one (the first) and _pwd gets to hold the "leftovers"? > user_home = os.path.join("/expirt/home", user) > > > try: > > os.makedirs('usrHome' ) > > except Exception, e: > > print e > > if os.path.exists(user_home): ^----- are(n't) exists and os.path.isadir interchangable? *nods in Bryan O. direction* > print "User Home dir exists, checking and fixing permissions." > else: > print "Do other stuff" > > Regards, > Ryan Ginstrom From castironpi at gmail.com Fri Mar 7 21:18:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 18:18:40 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> <13t3f4u6vb77qf3@corp.supernews.com> Message-ID: <67ff6575-92d2-4235-9fe0-44b4bd2960f8@u69g2000hse.googlegroups.com> On Mar 7, 4:07?pm, Steven D'Aprano wrote: > > I want to be able to detect if [certain threads] fail with error, > > You can't? Why ever not? Try this. ext can be found in 'C Function in a Python Context' on google groops. import ext extA= ext.Ext() extA[ 'araise' ]= r""" int araise( int a, PyObject* exc ) { int res= PyThreadState_SetAsyncExc( a, exc); return res; } """, ("i","i","O") LastCallException= type( 'LastCallException', ( Exception, ), { 'canstayhere': True } ) import thread import threading import time partystart= threading.Event() doorsclose= threading.Event() def thd(): partystart.set() try: while 1: print( 'running, ha ha!' ) time.sleep( .2 ) except Exception: print( '\nclean thread exit\n' ) finally: doorsclose.set() partyid= thread.start_new_thread( thd, () ) partystart.wait() print( 'waiting a second\n' ) time.sleep( 1 ) ret= extA.araise( partyid, LastCallException ) doorsclose.wait( 1 ) if not doorsclose.isSet(): print( 'Tell me about it.' ) print( 'clean exit\n' ) ''' waiting a second running, ha ha! running, ha ha! running, ha ha! running, ha ha! running, ha ha! clean thread exit clean exit ''' From george.sakkis at gmail.com Wed Mar 26 17:01:31 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 14:01:31 -0700 (PDT) Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: On Mar 26, 3:41 pm, Tim Henderson wrote: > I am using mysql, and sqlite is not appropriate for my situation since > some of the databases and tables I access are being accessed by other > applications which are already written and live. I am not using the > SQLAlchemy or SQLObject, because I didn't want too (although in the > future I may consider using them). I'd strongly second looking into SQLAlchemy; from what you wrote, I suspect sooner or later you'll end up creating (to paraphrase Greenspun) an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLAlchemy. George From blwatson at gmail.com Sat Mar 29 19:54:36 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Sat, 29 Mar 2008 16:54:36 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> Message-ID: <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> On Mar 29, 3:48?pm, "Diez B. Roggisch" wrote: > blwat... at gmail.com schrieb: > > > > > I am trying to install the twitter python wrapper...I got that > > installed just fine, but am having serious troubles getting the > > simplejson package to install. ?I need help diagnosing where this is > > failing. ?I am trying to use: > > >http://pypi.python.org/pypi/simplejson > > > and I run "python setup.py build" and then "python setup.py install", > > which both seem to work just fine. > > > I tried running with easy_install, but that too is not working. ?I end > > up with: > > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > > in my: > > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > > packages/ > > > I am on Mac OS X 10.5. ?Any help would be greatly appreciated. > > Go to the turbogears file section and download an appropriate version of > simplejson: > > http://www.turbogears.org/download/filelist.html > > I presume sj-1.7.4 is sufficient. > > Alternatively, be gentle to your unixish OS that OS X is, and install > XCode. Which will install the whole GCC chain, making your OS a > respected member of OS-community - as every system should be able to > compile C-code, in which itself has been written. > > Then the install should work as well. > > Diez I have already installed XCode...my compiel did not break the way the above did. I have grabbed the .egg file for simplejson 1.7.4 for Mac OS X 10.5 at the above link you provided - it has a simplejson dir, with the exact files that are in my simplejson directory for 1.8.1 (except none of my .py files have been compiled down to bytecode). I tried to add the directory "//simplejson" to my sys.path in the interpreter, hoping that the call to import simplejson would work if the dir was there, even though simplejson.py did not exist is that dir, but the encoder, decoder, jsonfilter and scanner .py files were all there. My problem is that the call "import simplejson" fails. How can I make that call work? Thanks in advance. From gagsl-py2 at yahoo.com.ar Tue Mar 18 03:19:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 00:19:56 -0700 (PDT) Subject: ctypes in python failed to honor c_int References: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> Message-ID: <49a1aad5-9020-4e6c-9389-502504a55ae4@u69g2000hse.googlegroups.com> On 18 mar, 04:12, Jerry Fleming wrote: > Gabriel Genellina wrote: > > On 17 mar, 23:57, Jerry Fleming wrote: > > >> I have a binary file written with c structures. Each record contains a > >> null-terminated string followed by two 4-bytes integers. I wrote a small > >> segment of python code to parse this file in this way: > >> [coe] > >> #!/usr/bin/python > > >> from ctypes import * > > >> class Entry(Structure): > >> ? ? ? ? _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) > > >> idx = open('x.idx', 'rb') > >> str = idx.read(1000) > >> obj = Entry(str) > >> print obj.w > >> print obj.s > >> print obj.l > >> [/code] > >> where the field w is the string, and s and l are the integers. Problem > >> is that, I can only get the strings, not the integers. Well, I did got > >> integers, but they are all zeros. What should I do to get the real numbers? > > > So the string has a variable length? For "Hello" you have > > 'h','e','l','l','o', a zero byte, followed by the two integers? This > > is somewhat unusual for a C struct (in fact you can't declare it in > > C). Perhaps the string is actually a char[n] array with a declared > > maximum size? > > Yes, it has a variable length. The C version of the structure is > something like this: > [code] > struct entry { > ? ? ?char *str, > ? ? ?int start, > ? ? ?int length} > > [/code] But this doesn't match the file contents. There are no pointers in the file. > And adding repr() would print something like this: > [code] > '(as) mad as a > hatter\x00\x00\x00\x00\x00\x00\x00\x00\x1f-ish\x00\x00\x00\x00\x1f\x00\x00\?x00 at -ism\x00\x00\x00\x00_\x00\x00\x00B-ist\x00\x00\x00\x00\xa1\x00\x00\x00J?.AU\x00\x00\x00\x00\xeb\x00\x00\x00P.EXE\x00\x00\x00\x01;\x00\x00\x00`.GIF\?x00\x00\x00' > (as) mad as a hatter > 0 > 0 > [/code] > where the first line is the result of repr(). We can find that, after > the null-terminated string '(as) mad as a hatter', there are two > integers, 0 and 31 (0x1f). But python treat 31 as zero. Ah, but it doesn't "treat 31 as zero". Entry(str) is the same as Entry(w=str), that is, you are initializing the w attribute alone, leaving the other two integers as 0. I don't know how to use ctypes to read the structure (nor if it is possible at all), I would read it normally with Python code and build the struct afterwards (in case it is used to call any C code). w, data = data.split('\x00', 1) s, l = struct.unpack("ll", data[:8]) data= data[8:] -- Gabriel Genellina From mnordhoff at mattnordhoff.com Fri Mar 14 13:06:00 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 14 Mar 2008 17:06:00 +0000 Subject: request for Details about Dictionaries in Python In-Reply-To: References: <47DA6FF6.5000505@fmed.uba.ar> <47DA8833.9020205@fmed.uba.ar> Message-ID: <47DAB078.9050705@mattnordhoff.com> Michael Wieher wrote: > I'm not sure if a well-written file/seek/read algorithm is faster than a > relational database... > sure a database can store relations and triggers and all that, but if > he's just doing a lookup for static data, then I'm thinking disk IO is > faster for him? not sure I would think that rolling your own solution would get complicated enough that it would be easier to just use SQLite or something. If you wanted to go to the effort, you could probably get something faster, but if SQLite is fast enough, who cares? Hmm, if Perl's on-disk hash tables are good, maybe someone should port them to Python, or maybe someone already has. Also, for translations, maybe there's a good library already available. -- From jura.grozni at gmail.com Wed Mar 26 12:59:15 2008 From: jura.grozni at gmail.com (azrael) Date: Wed, 26 Mar 2008 09:59:15 -0700 (PDT) Subject: last mouse movment or keyboard hit References: Message-ID: You can use wxPython. Take a look on the DemoFiles that you can download also from the site. I remember that there has been a demo of capturing mouse coordinates and also one example about capturing Which key has been pressed at which time. Just start the time, count the interactions of key strokes and mouse gestures. Apply some statistics and voila. there it is. On Mar 26, 3:28?pm, Ron Eggler wrote: > Gabriel Genellina wrote: > > En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler escribi?: > > >> I would like to get the time of the most recent human activity like a > >> cursor > >> movement or a key hit. > >> Does anyone know how I can get this back to start some action after there > >> has been no activity for X minutes/seconds? > > > Which platform? On non-ancient Windows versions, you can periodically > > check GetLastInputInfo > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winu... > > No, it would be for Linux and preferrably it would work on MacOS & Windows > as well....is there anything? > Thanks! > -- > chEErs roN From craigm3604 at gmail.com Sat Mar 22 22:08:34 2008 From: craigm3604 at gmail.com (Craig) Date: Sat, 22 Mar 2008 19:08:34 -0700 (PDT) Subject: Anomaly in time.clock() References: <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> <0febu3lut6cpgikoe02snl0tju05gd8qs8@4ax.com> Message-ID: On Mar 22, 10:03 pm, Tim Roberts wrote: > Godzilla wrote: > > >Just found out that win32api.GetTickCount() returns a tick count in > >milli-second since XP started. Not sure whether that is reliable. > >Anyone uses that for calculating elapsed time? > > What do you mean by "reliable"? The tick count is updated as part of > scheduling during timer interrupts. As long as no one disables interrupts > for more than about 15ms, it is reliable. > > However, it's only a 32-bit value, so the number rolls over every 49 days. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. Try getting XP or Vista to stay up for 49 days. I have had Vista stay up for a little over 11 days. If it doesn't crash, it will have to be rebooted for some update or other. From castironpi at gmail.com Fri Mar 14 03:02:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 00:02:06 -0700 (PDT) Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <13tk779gboqcgb9@corp.supernews.com> Message-ID: <3c1f0d7b-4f1d-4ec6-ba6f-ba4fa2833647@b1g2000hsg.googlegroups.com> > > Well, lets say you have a situation where you're going to be > > alternating between sending large and small chunks of data. Is the > > solution to create a NetworkBuffer class and only call send when the > > buffer is full, always recv(8192)? > > ? ? ? ? Or create a protocol where the first 16 bits (in network byte order) > contain a length value for the subsequent data, and use a receive > process that consists of: > > leng = ntoh(socket.recv(2)) > data = socket.receive(leng) > > (the send can combine the length with the data into a single packet) Are two 'sends' guaranteed to arrive as at least two 'receives'? Send-3: xxx Send-3: yyy Receive-6: xxxyyy From ndbecker2 at gmail.com Tue Mar 11 11:03:42 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 11 Mar 2008 11:03:42 -0400 Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? > > Thanks in advance, > Nathan P. import os os.system('factor 25') From Afro.Systems at gmail.com Tue Mar 25 07:44:34 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 04:44:34 -0700 (PDT) Subject: Inheritance question Message-ID: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> given two classes: class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = Foo.getid() b = self.id return '%d.%d' % (a,b) While my intention is to get 1.2 I get 2.2 I would like to know what would be the right way to yield the expected results From gagsl-py2 at yahoo.com.ar Thu Mar 27 14:54:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 15:54:12 -0300 Subject: Py2exe embed my modules to libary.zip References: <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> <1206639241.3132.0.camel@fc8.home.com> Message-ID: En Thu, 27 Mar 2008 14:34:02 -0300, Larry Bates escribi?: > Create your py2exe distribution without a zipfile and all the modules > will just be put into the installation directory. Use Inno Setup to > make a proper installer for your application. I second that. It's the easiest way. Another way it to help improve py2exe so it can find modules from inside a .zip and extract them (if this happens to be the cause). -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Mar 26 18:10:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 15:10:52 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: Sean Davis>Java has a BitSet class that keeps this kind of thing pretty clean and high-level, but I haven't seen anything like it for python.< If you look around you can usually find Python code able to do most of the things you want, like (you can modify this code to add the boolean operations): http://svn.zope.org/*checkout*/Zope3/trunk/src/zope/textindex/ricecode.py?content-type=text%2Fplain&rev=8532 (Later I have improved that code for personal use). But operations on such bit arrays are very common, and you may need them to be very fast, so you may use Cython (Pyrex) to write a small class able to do those things in a much faster way. Or you can also use Pyd plus an easy 30-lines long D program to write a class that does those operations very quickly (using a dynamic array of uint, with the help of www.digitalmars.com/d/1.0/phobos/std_intrinsic.html ). Maybe you can use GMPY numbers as bit arrays too. (I don't know if you can use NumPy for this using a compact representation of the bits). Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Mar 1 01:43:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Mar 2008 04:43:54 -0200 Subject: Telnet versus telnetlib References: <8acce230-4acf-43fe-9cb7-e4e50350381e@s13g2000prd.googlegroups.com> Message-ID: En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis escribi?: > When I do an analogous process using telnetlib, I get no debug output, > and most importantly, when I send the XML file to the host, I get no > printed page. Unfortunately, I do not have access to the host to do > troubleshooting there, so I have to "feel" my way around. Any > suggestions on what might be going wrong? > > In [12]: tn.write(""" > ....: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: On Mar 6, 1:20 pm, Jeroen Ruigrok van der Werven wrote: > -On [20080306 19:21], member thudfoo (thud... at opensuse.us) wrote: > > >An error occurred while loading > >http://www.martinrinehart.com/articles/python-grammar.html: > >Unknown hostwww.martinrinehart.com > > Works for me. > > -- > Jeroen Ruigrok van der Werven / asmodai > ????? ?????? ??? ?? ??????http://www.in-nomine.org/|http://www.rangaku.org/ > Possession is nine points of the law... The 404s are due to the trailing ':' -- Paul From adelagon at gmail.com Tue Mar 25 22:05:59 2008 From: adelagon at gmail.com (Alvin Delagon) Date: Wed, 26 Mar 2008 10:05:59 +0800 Subject: python hash() function Message-ID: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Hello, >>> hash("foobar") -1969371895 Anyone can explain to me how the hash() function in python does its work? A link to its source could help me a lot also. I'm looking for a way to replicate this function in php. Thanks in advance. --- Alvin -------------- next part -------------- An HTML attachment was scrubbed... URL: From damonwischik at gmail.com Thu Mar 27 13:34:19 2008 From: damonwischik at gmail.com (damonwischik at gmail.com) Date: Thu, 27 Mar 2008 10:34:19 -0700 (PDT) Subject: Set sys.stdout.encoding to utf8 in emacs/python-mode? Message-ID: I use emacs 22 and python-mode. Emacs can display utf8 characters (e.g. when I open a utf8-encoded file with Chinese, those characters show up fine), and I'd like to see utf8-encoded output from my python session. >From googling, I've found references to * locale.getdefaultlocale(), which is ('en_GB', 'cp1252') * sys.stdout.encoding, which is None * the environment variables LANG, LC_CHARSET and LC_ALL. http://mail.python.org/pipermail/python-list/2006-January/360068.html Should setting those environment variables give me a sys.stdout.encoding of utf8? What should I set them to? I tried setting LANG to en_GB and LC_CHARSET to utf8, but it doesn't have the effect of changing getdefaultlocale() or sys.stdout.encoding. Or is there some option I can set for python-mode so that it will instruct the python interpreter to use utf8 for its output? Damon. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:30:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:30:11 -0000 Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: <13t6tf3b5tpcv48@corp.supernews.com> On Sat, 08 Mar 2008 19:51:24 -0800, Lie wrote: > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as if > nothing happened. For example, if a variable turns into NoneType, it'll > raise Soft Exception that it have become NoneException, programmers that > wants to handle it can handle it with a try...except block while > programmers that doesn't care about it (or know it won't be a problem to > his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in a > way that Hard Exception must be handled at all cost or the program will > be terminated while Soft Exception allow programmers not to handle it if > they don't want to. I don't think that there are very many cases where exceptions can be ignored safely. There are two main reasons for using exceptions: (1) Signaling an exceptional event. (2) An error occurred. I can't think of many cases where you would wish to ignore either, and just continue processing. The only examples I can think of are in loops, where you are doing the same thing over and over again with just a little change, and you wish to skip any problematic data, e.g.: def plot_graph(func, domain): for x in domain: plot(x, func(x)) If an error occurs in plot() for one particular x value, you would want to ignore it and go on to the next point. But that's easy enough to do with a regular try...except block. Simply put, you're suggesting the following two alternatives: Hard Exceptions: terminate the program unless explicitly silenced Soft Exceptions: pass silently unless explicitly caught In this case, I agree with the Zen of Python ("import this"): Errors should never pass silently. Unless explicitly silenced. The cost of explicitly silencing exceptions is tiny, the risk of misuse of Soft Exceptions is very high, and the benefit of them is negligible. -- Steven From malaclypse2 at gmail.com Thu Mar 20 10:28:38 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 20 Mar 2008 10:28:38 -0400 Subject: dividing tuple elements with an int or float In-Reply-To: <13u45bam9k12n71@corp.supernews.com> References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> Message-ID: <16651e80803200728n2dead522s31766f534c357c06@mail.gmail.com> On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > > > > suppose > > origsz=(400,300) > > i want to divide the origsize by 2.5 so i can resize to (160,120) > > > > scale=2.5 > > how can i get the newsz? > > obviously origsz/2.5 won't work .. > > newsz = (origsz[0]/scale, origsz[1]/scale) That works fine for a 2-tuple, but might get unwieldy for larger tuples, or if you don't know the length until runtime. A more general solution might use a generator expression, like this: newsz = tuple(x/scale for x in origsz) -- Jerry From mh at pixar.com Sun Mar 9 20:42:47 2008 From: mh at pixar.com (mh at pixar.com) Date: Mon, 10 Mar 2008 00:42:47 GMT Subject: any chance regular expressions are cached? Message-ID: I've got a bit of code in a function like this: s=re.sub(r'\n','\n'+spaces,s) s=re.sub(r'^',spaces,s) s=re.sub(r' *\n','\n',s) s=re.sub(r' *$','',s) s=re.sub(r'\n*$','',s) Is there any chance that these will be cached somewhere, and save me the trouble of having to declare some global re's if I don't want to have them recompiled on each function invocation? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From jecarnell at saintfrancis.com Wed Mar 26 17:44:34 2008 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Wed, 26 Mar 2008 16:44:34 -0500 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: Message-ID: I vote a strong yes! I went through a MIS major and learned java first. This was a disaster for me typing these long nonsense lines (I didn't understand how classes and their members worked). Next was C and we had to use a command line and notepad to do all our programs. I really didn't learn much. After I graduated a friend told me to try python since I had this "screw programming" attitude. Actually I really did want to program. The fact that I could type one liners in without having to do make files and all that actually made it feasible for me to learn. I learned more from python and the tutorial list than 4 years of college. I really am serious! I'm going back now and learning C++ and might be able to learn crystal space 3d here before too long. James Carnell Steven D'Aprano wrote: > On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > >> Yes. And because Python is a "scripting language" > From pavlovevidence at gmail.com Mon Mar 10 16:59:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Mar 2008 13:59:21 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: Message-ID: On Mar 9, 7:41 pm, Roopan wrote: > Hello! > > I am looking at developing an enterprise-grade distributed data > sharing application - key requirements are productivity and platform > portability. > > Will it be sensible to use C++ for performance-critical sections and > Python for all the glue logic. > Pls comment from your *experiences* how Python scales to large > projects( > 200KLOC). > I assume the C++/Python binding is fairly painless. 200K with C++ lines of code or Python lines of code? :) I can comment on 50K lines of Python code, and considering how I write Python and how most people write C++ that might be about the same as a 200K C++ program. But it's not an enterprise app, so take it as you will. I've had no real issues. 95% of the program in Python; with only a couple sections written in C, and a few wrappers for C/C++ libraries. My wrappers are as thin as I can reasonably make them; where needed I make the interface prettier with a higher-level Python wrapper. I'm writing regular extensions, not using ctypes, Cython, SWIG, Boost::python or anything like that. I am using ctypes for some related tools and it's pretty nice. The others I can't comment on, except to say I sometimes didn't have enough memory to compile third- party SWIG extensions. I develop it on Linux, but every few months or so I'd copy it to Windows and update it so that it works on both. This was a minor hastle, which is not so bad considering it hadn't seen Windows for months. (In fairness, I am using the same compiler, gcc, on both. Getting mingw gcc to work on Windows was a major hassle, but a one- time thing.) Python's a lot better productivity-wise, and it's worked well as a cross-platform solution for me. The interfacing is the main drawback. It's always a bit of effort to interface things, and to get it working on multiple platforms, but I thought it was worth it. Carl Banks From gagsl-py2 at yahoo.com.ar Sun Mar 9 19:47:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 21:47:39 -0200 Subject: Intra-Package References References: <01d2be35-3e08-49d4-811b-a0d8b4fb5d27@n77g2000hse.googlegroups.com> Message-ID: En Sat, 08 Mar 2008 17:36:12 -0200, xkenneth escribi?: > Does your python module have to exist in the path in order for intra- > package references to work? No, but Python must be aware that the importing module is inside a package. So the script being executed (main) should live outside the package. -- Gabriel Genellina From david.avraamides at gmail.com Mon Mar 17 13:17:11 2008 From: david.avraamides at gmail.com (DavidA) Date: Mon, 17 Mar 2008 10:17:11 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 9:42 am, Mike Driscoll wrote: > Do you mean the "official" presentations or the lightning talks? I > thought both were kind of bad. Jeff Rush was great in both of the > sessions I saw and the gaming presenters were also good. But I saw a > lot of people who had never presented and were unprepared. In fact, > one didn't have any code whatsoever to share and the other one only > started showing some code during the last 10 minutes of his time. This was also my first time at PyCon and I thought I'd expand on what Mike said as I feel pretty much the same way. I also want to provide some constructive feedback that can hopefully help improve the next PyCon. I attended all the keynotes, 15 sessions and two days of the lightning talks. I was disappointed with about one-third of the keynotes and sessions. I found only a handful of the lightning talks interesting. My biggest complaint was the lack of preparation of the speaker: * in three cases the presenter had a recent problem with their laptop but had no back-up plan (dead drive, dead power supply, unable to get video out to projector). The presenters didn't have a copy of their presentation elsewhere (thumb drive, or even a printout) so they just winged it and the presentation was difficult to follow and ineffective. When I have presented at conferences in the past, we were required to submit our presentations and materials to the conference at least a week before so they could make them available on a web site and also on backup laptops at the conference. * the PyCon feedback survey doesn't allow for any useful feedback about the presentations. You only get to pick your five favorites. There should be forms available (hardcopy or online) where we can give feedback to the presenters themselves. My impression is that many of the speakers have presented at PyCon before and may do so in the future so this feedback can help them be more effective. I found it a bit ironic that I attended at least three sessions with a strong testing theme that talked about the importance of feedback in the development process and how it helped improve the quality of the final product, yet there was no channel to provide feedback to the presenters themselves. It seemed a glaring omission to me that the PyCon survey had questions about whether I shared a room (who cares?) but not about the quality of the presenters and presentations. * As a PyCon first-timer, I was not aware of the open meetings and BoF discussions while I was there. I feel like I might have missed one of the more valuable parts of the conference simply because I was ignorant. It would have been nice to get the word out a bit more - maybe an announcement each morning at the beginning of the keynotes. * There has been a lot of discussion about the reservation of lightning talk slots to sponsors. What I don't understand is why this wasn't disclosed at the conference. I've seen some of the organizers defend the "experiment" but no one explain why it wasn't mentioned beforehand. I'm left with the impression that the organizers knew this would be unpopular and didn't want to draw attention to it. I think a lot of this could have been averted by disclosing this change before the conference took place (in which case the community may have pushed back and convinced the organizers to reconsider the decision). Or at least it could have been disclosed at the conference so people could have decided to skip the lightning talks and organize their own ad-hoc meetings or talks. Experimenting isn't bad. But failing to disclose this information was a poor decision - especially at a conference that prides itself in openness and community involvement. * Lastly, I found the technical depth at most talks to be too shallow. I was especially surprised at this because I've only been using Python for two years, so I still think I'm a bit of a noob. But if you looked around at the conference, you saw a bunch of people who are really into programming (so much that many of them were doing it _during_ the talks) so to think that the audience isn't capable of following deep technical discussions is a bit off the mark. At other conferences I've attended and/or presented at, they would typically rate presentations as a level 1, 2 or 3. I think this would help set people's expectations. That coupled with session-level feedback, would help the organizers plan future PyCon sessions that better match the attendees' interests. That said, I did learn a few things at PyCon and found the overall experience pretty good. I simply had been hoping for a little more... -Dave From alex.pulver at gmail.com Thu Mar 13 03:52:40 2008 From: alex.pulver at gmail.com (Alex) Date: Thu, 13 Mar 2008 00:52:40 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> On Mar 12, 8:48 pm, Carl Banks wrote: > On Mar 12, 2:19 pm, Alex wrote: > > > Hi all, > > > The subject says pretty much all, i would very appreciate an answer. I > > tried to search the various forums and groups, but didn't find any > > specific answer... > > Python technically has no equivalent: you can't run code at compile > time. However, the BEGIN block in Perl seems to have been added to > work around some of Perl's nonlinear order of execution. Normally in > Python you don't need a BEGIN block: just put the code at the top of > you script/module and it will exectute before anything else. > > Want to tell us what you need it for? Perhaps we can suggest a way of > doing it that's appropriate in Python. > > Carl Banks Hi, First of all thanks all for answering! I have some environment check and setup in the beginning of the code. I would like to move it to the end of the script. But I want it to execute first, so the script will exit if the environment is not configured properly. Thanks, Alex. From grante at visi.com Thu Mar 20 11:21:13 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 15:21:13 -0000 Subject: Can I run a python program from within emacs? References: Message-ID: <13u50796m76e9c7@corp.supernews.com> On 2008-03-20, jmDesktop wrote: > Hi, I'm trying to learn Python. I using Aquamac an emac > implementation with mac os x. I have a program. If I go to the > command prompt and type pythong myprog.py, it works. Can the program > be run from within the editor or is that not how development is done? > I ask because I was using Visual Studio with C# and, if you're > familiar, you just hit run and it works. On Python do I use the > editor for editing only and then run the program from the command > line? http://www.google.com/search?q=emacs+python -- Grant From ilkeston at ntlworld.com Sun Mar 2 16:36:30 2008 From: ilkeston at ntlworld.com (Steve Turner) Date: Sun, 2 Mar 2008 21:36:30 -0000 Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: Christoph Zwerschke wrote: : Marc 'BlackJack' Rintsch schrieb: :: On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: :: ::: Apart from doing something like ::: a=[0,0,0] ::: b=[0,0,0] ::: c=[0,0,0] ::: d=[a,b,c] ::: ::: is there a better way of creating d?? :: :: a = [[0] * 3 for dummy in xrange(3)] : : Why not simply [[0]*3]*3 ? I've just tried that and it gives the same as my earlier b=[a,a,a] -- Steve From see at signature.invalid Thu Mar 13 16:40:58 2008 From: see at signature.invalid (Douglas Wells) Date: Thu, 13 Mar 2008 16:40:58 -0400 (EDT) Subject: subprocess.Popen pipeline bug? References: Message-ID: In article , Marko Rauhamaa writes: > > This tiny program hangs: > > ======================================================================== > #!/usr/bin/env python > import subprocess > a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, > stdout = subprocess.PIPE) > b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) > a.stdin.close() > b.wait() # hangs > a.wait() # never reached > ======================================================================== > > It shouldn't, should it? Yes, it should. This issue is related to the subtleties of creating a pipeline in POSIX environments. The problem is that the cat command in subprocess a never completes because it never encounters an EOF (on a.stdin). Even though you issue a close call (a.stdin.close ()), you're not issuing the "last" close. That's because there is still at least one file descriptor open in subprocess tree b. That happened because it was open when the subprocess module executed a POSIX fork call and it got duplicated as part of the fork call. I don't see any clean and simple way to actually fix this. (That's one of the reasons why POSIX shells are so complicated.) There are a couple of work-arounds that you can use: 1) Force close-on-exec on the specific file descriptor: import subprocess a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, stdout = subprocess.PIPE) # ********* beginning of changes import os, fcntl fd = a.stdin.fileno () old = fcntl.fcntl (fd, fcntl.F_GETFD) fcntl.fcntl (fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) # ********* end of changes b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) a.stdin.close() b.wait() a.wait() Or if it happens to not cause undesired side-effects for you, you can 2) Force close-on-exec *all* non-standard file descriptors by using the close_fds argument to Popen: import subprocess a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, stdout = subprocess.PIPE) # ********* beginning of changes # b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout, close_fds = True) # ********* end of changes a.stdin.close() b.wait() a.wait() Good luck. - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From gagsl-py2 at yahoo.com.ar Thu Mar 6 07:42:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 10:42:42 -0200 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: En Thu, 06 Mar 2008 08:33:41 -0200, Tom Wright escribi?: > I've written a program in Python using wxPython and Matplotlib and would > like to distribute it under the GPL. For ease of use, I'd also like to > distribute and installable version for Windows, but this needs > MSVCR71.dll > and MSVCP71.dll to work. I've created an installer using py2exe and Inno > Setup but I don't know if I'm allowed to distribute it or not. I've > found > lots of conflicting opinions online indicating that I can or cannot > distribute these, but no definitive answer. Maybe this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/f8df5ed32b324a3f/ can help. > The Microsoft Developer Network instructs me to read the redistribution > instructions and the EULA which come with Visual Studio, but I don't have > visual studio, so that's next to useless. This EULA doesn't apply to you, but to the Python developers, which are the actual Visual Studio users and have to comply with its license terms. You're just repackaging Python, your program, and other required components. In any case, I don't think MS cares; after all, you're promoting their OS and making life easier for Windows users. -- Gabriel Genellina From joshetomlinson at gmail.com Mon Mar 24 14:06:51 2008 From: joshetomlinson at gmail.com (joshetomlinson at gmail.com) Date: Mon, 24 Mar 2008 11:06:51 -0700 (PDT) Subject: importing package contents from multiple places in PYTHONPATH Message-ID: <6c6765d4-e1d7-4ca8-af96-e3c038fc5f3e@i7g2000prf.googlegroups.com> Hi all, I'm new to python, and am trying to determine if it's possible to do the following... I have a directory structure like this, with both 'dir1' and 'dir2' in my PYTHONPATH dir1/ foo/ __init__.py a.py b.py dir2/ foo/ __init__.py a.py c.py I'd like to be able to: python> import foo.a, foo.b, foo.c I'd hope for package 'foo.a' to come from dir1 since it was first on the path, with 'foo.b' and 'foo.c' coming form dir1 and dir2 respectively. I understand that python stops once it encounters the first 'foo' package in PYTHONPATH, but I was wondering if there was a way around this. I've had some success modifying __path__ in the foo/__init__.py files, but am unsure if this is the best approach. Perhaps there's a way to do this with import hooks? Is there a precedent for this type of thing? Thanks in advance, Josh From MadComputerGuy at gmail.com Tue Mar 11 22:50:01 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Tue, 11 Mar 2008 19:50:01 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> <306997c4-36dc-4603-8100-f47e25e55bef@s19g2000prg.googlegroups.com> Message-ID: <792e7610-7807-4deb-b13e-213d162cd2c0@d62g2000hsf.googlegroups.com> On Mar 11, 1:12 pm, Mensanator wrote: > On Mar 11, 3:36 am, Duncan Booth wrote: > > > Mensanator wrote: > > > On Mar 10, 10:44???pm, Nathan Pinno wrote: > > >> Why does my compiler say invalid syntax and then highlight the > > >> quotation marks in the following code: > > > >> # This program is to find primes. > > > > Needs work. > > > Be fair. > > Being helpful isn't fair? > > > The OP hadn't managed to figure out why the program wasn't > > running, so you can't expect him to have got all the bugs out of the code > > yet. > > The bug had already been answered. > > If you fail to implement your premise correctly, you have a bug. > > It doesn't matter if the code is bug-free if the premise is false. > > In this case, the premise that he can determine primes this way > is false. He will have to abandon the cos() thing, for although it > works in theory, he'll never get it to work in practice. > > Besides, the cos() is a red herring (hint: cos(pi*n)). The problem > can be made to work EXACTLY (at least up to z=10000) by using > rationals > (which gmpy supports). > > His problem is going to take much more than fixing a syntax error. > > > And he only asked about the specific syntax error not the entire > > solution to his homework. > > If this is indeed homework, and he's supposed to come up with a > factorial algorithm, I seriously doubt the teacher would accept > gmpy.fac(z-1), so I assume it isn't. > > > > > My advice to Nathan would be: > > > 1. If you get a weird syntax error that you don't understand try cutting > > the code down to just the bit which generates the error. > > > 2. Play around in the interactive interpreter to see what works and what > > doesn't. > > > 3. If you don't understand why the code doesn't work then get a stuffed > > toy, cardboard cutout of a person, or the least technical member of your > > family and explain to them in great detail exactly why the code must > > (despite error messages to the contrary) be correct. Usually you'll spot > > the problem half way through the explanation. > > > 4. If you post to this list then post the full error message and traceback. > > That way we don't have to guess which quotation marks are the problem. Yep, got it fixed, and no, it is not a homework problem...just a project for fun to keep up my Python coding in my memory intact (apparently, it doesn't work as well when I've been up early 3 days in a row... :P ). Now I just have to figure out why it isn't working the way it is supposed to. It was given to me by someone in the sci.math area as an alternative to working with 1 < x < n. From deets at nospam.web.de Fri Mar 28 04:58:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Mar 2008 09:58:05 +0100 Subject: Plugins accessing parent state In-Reply-To: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> Message-ID: <653q99F2e37q8U1@mid.uni-berlin.de> hajducko at gmail.com schrieb: > Does anyone have some design ideas ( or can point me at the right > design pattern, because I can't find it. ) for having a plugin being > able to access a parent's state? > > For example, let's say I have a class that receives some commands. > When it gets a command, it checks which of the registered plugins > deals with that command and passes the details of the command off to > that plugin. So I'd end up with something like.. > > result = plugin.do(msg_details) > > Now, I want to write a plugin called "help" that loops through all the > registered plugins and prints out their doc strings. If all my plugin > is getting is the msg details, how is it supposed to get the list of > available plugins from the calling class? > > Or, for instance, let's say my class loads a configuration file that > lists a set of admins who can enter commands. I want the plugins, if > they so choose, to be able to test if the msg came from an admin, but > again, I'm not passing the admin list into every plugin, it's just in > my calling class. I could make the plugin specify an attribute for > itself, like "admin_only" and test for that before I pass the command > but what if certain parts of the plugin are to be restricted and > others aren't, based on the details of the command sent? > > Is this as simple as just passing the instance of my class to each > plugin? It doesn't seem like the proper thing to do, because now the > plugin class has the capability of accessing the whole bot's > interface. Yes, it is simple as that. Of course you can choose *what* you pass, if you want to restrict that - nobody forces you to pass the whole plugin-manager, if that would expose properties/methods you wouldn't want ther. But to be honest: you are thinking much to far there - after all, it's all *your* code, and inside one interpreter. A real isolation isn't available anyway. So just do what fullfills the functional requirements. diez From paddy3118 at googlemail.com Thu Mar 13 01:17:37 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 12 Mar 2008 22:17:37 -0700 (PDT) Subject: How to port Python code into C++ code automatically? References: Message-ID: On Mar 13, 3:15 am, Bo wrote: > I want to port a Python project (about 10,000 line python code) to C+ > +. Is there any automatically tool to do this kind of things? e.g., > SWIG(http://www.swig.org/)? > > Any comment is welcome! > > Thanks! There isn't a magic porting tool available. If you said more about the why and the resources available then you might get a better answer. - Paddy. From kyosohma at gmail.com Wed Mar 19 15:55:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 12:55:21 -0700 (PDT) Subject: csv dictreader References: Message-ID: On Mar 19, 1:55 pm, brnstrmrs wrote: > On Mar 19, 2:32 pm, Mike Driscoll wrote: > > > > > On Mar 19, 1:06 pm, brnstrmrs wrote: > > > > I am trying to use the dictionary reader to import the data from a csv > > > file and create a dictnary from it but just can't seem to figure it > > > out. > > > > Here is my code: > > > > >>>import csv > > > >>>reader = csv.DictReader(open('table.csv')) > > > >>>for row in reader: > > > >>>print row > > > > my csv files looks like this: > > > > Bytecode,Element > > > \x00\x00,0000 > > > \x01\x00,0001 > > > .... > > > \x09\x00,0009 > > > > My output shows: > > > {'Bytecode': '\\x00\\x00', 'Element': '0000'} > > > {'Bytecode': '\\x01\\x00', 'Element': '0001'} > > > ... > > > {'Bytecode': '\\x09\\x00', 'Element': '0009'} > > > > 1. how can I get access to this directory > > > What do you mean? You can get each element in the dict by doing this: > > > for row in reader: > > print row['Bytecode'] > > print row['Element'] > > > > 2. why does the values come with two backslashs infront of the "x" > > > The double back slash is for escaping purposes, I think. If you print > > this: '\\x09\\x00' > > you'll get this: \x09\x00 > > > Mike > > Thanks. It works for the Bytecode but when I do print row['Element'] > I get a error message print row['Element'] KeyError: 'Element' That's weird. Since I only had your output, I did the following: reader = [ {'Bytecode': '\\x00\\x00', 'Element': '0000'},{'Bytecode': '\\x01\\x00', 'Element': '0001'} ] for x in reader: print x['Element'] print x['Bytecode'] 0000 \x00\x00 0001 \x01\x00 I must be missing something... Mike From HDoran at air.org Sat Mar 29 09:57:10 2008 From: HDoran at air.org (Doran, Harold) Date: Sat, 29 Mar 2008 09:57:10 -0400 Subject: Python and xml Message-ID: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> I am a python neophyte who has used python to parse through text files using basic functions and no OOP experience. I have a need to process some xml files and from what I am now reading python is the exact tool I need to work through this issue. However, as I read online docs and peruse which books to buy, I am quickly becoming overwhelmed with the topic and could use some guidance on how to best tackle my task. To frame the issue, here is what I would like to be able to do. I have a statistical program that outputs the data into an xml document. My goal is to use python to parse this document and output a .txt document or .csv document that organizes the results into human-readable rows and columns in a nicely formatted manner. As I read online docs about xml and python, it seems the topic is very big. While I am more than happy to invest significant time learning this topic, it may be possible to narrow the scope of what I need to know and be able to do in order to complete my task. Any suggestions on how I should proceed and/or fundamentals I need to learn? Is anyone aware of simple how to docs or other tutorials that demonstrate this kind of task? Thanks, Harold -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at ghaering.de Sun Mar 9 14:57:00 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 09 Mar 2008 19:57:00 +0100 Subject: [pysqlite] [ANN] pysqlite and APSW projects moved In-Reply-To: <47D42EED.8070107@ghaering.de> References: <47D42EED.8070107@ghaering.de> Message-ID: <47D432FC.4040706@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gerhard H?ring wrote: > [...] APSW > ==== > > web: http://oss.itsystementwicklung.de/trac/apsw/ > scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX V7sH3uAskDDNBuxYG34vExI= =IXOx -----END PGP SIGNATURE----- From michael at stroeder.com Wed Mar 26 15:37:21 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Mar 2008 20:37:21 +0100 Subject: How to convert latex-based docs written with Python 2.5 to 2.6 framework Message-ID: HI! I had a look on how Doc/ is organized with Python 2.6. There are files with suffix .rst. Hmm... I'm maintaing existing docs for python-ldap which I might have to convert to the new concept in the long run. What's the recommended procedure for doing so? Any pointer? Ciao, Michael. From bbxx789_05ss at yahoo.com Wed Mar 19 20:01:39 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 19 Mar 2008 17:01:39 -0700 (PDT) Subject: is hash map data structure available in Python? References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Message-ID: <41f1b781-16e1-461c-8b9b-b26dfd6d2293@i29g2000prf.googlegroups.com> On Mar 19, 2:40?am, grbgooglefan wrote: > Hi, > I have a situation that I need to search a name in a big list of names > in my Python embedded interpreter. I am planning to use hash map for > quicker search. > How do I create hash map in Python? > Can you please guide me to some documentation or tutorial which > provides information on creating, editing, searching through hash map > in Python? > Thanks. #creating: my_dict = {'a':1, 'b':2, 'c':3} #editing: my_dict['a'] = 10 #searching: result = my_dict.get('a', None) print result //10 result = my_dict.get('f', None) print result //None From xkenneth at gmail.com Tue Mar 11 23:07:37 2008 From: xkenneth at gmail.com (xkenneth) Date: Tue, 11 Mar 2008 20:07:37 -0700 (PDT) Subject: Max File Size Message-ID: <1e8a2f49-e40b-4a6d-bc48-6d4f9a648c6d@s12g2000prg.googlegroups.com> Is the max file size a relevant issue in python anymore? I know OS X has a max file size of 8 exabytes and I'm not sure about the latest version of Ubuntu. Does python have an independent file size limit, or is it dependent upon the OS it was compiled on? Regards, Kenneth Miller From andre.roberge at gmail.com Thu Mar 27 07:18:49 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Thu, 27 Mar 2008 04:18:49 -0700 (PDT) Subject: Plugin framework - Overcomplicating things? References: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> Message-ID: <753fd116-95e0-4d5b-88b3-927861267577@e23g2000prf.googlegroups.com> On Mar 27, 3:31 am, "Gabriel Genellina" wrote: > En Thu, 27 Mar 2008 01:50:56 -0300, hajdu... at gmail.com > escribi?: > > > All this comes to my question - am I overcomplicating this project? I > > can understand the use of something like the trac component system if > > I had multiple components and plugins that handled different areas of > > my project and different points of interaction, but I don't. I've got > > exactly one spot where I want to check all my plugins and hand off the > > message to which ever ones are looking for that command. > > As you said, it looks like you're really overengineering your design then. > > > So really, > > should I even bother with trying to setup some framework for this or > > should I just be doing a simple loop over a directory, importing all > > the plugins and storing them in a list and then looping over them in > > the message handler to see which ones were looking for the command and > > letting them do their thing? You could set thing up so that there's no need to loop over the plugins. What you can do is register a plugin (as mentioned to you before by Gabriel - see below) and create an entry in a handler dict so that you can directly dispatch the message to the appropriate handler without having to loop over a list of them. Something like handlers[message]() > > That may be an option. > You may want to setup a simple registry mechanism, so the plugin modules > look like: > > ### begin niceplugin.py ### > class AVeryNicePlugin(object): # or perhaps using a suitable base class > def handle_message(self, message): > ... > > from plugin import PluginRegistry > PluginRegistry.register(AVeryNicePlugin) > ### end niceplugin.py ### > > Your application scans a known directory for files ending in "plugin.py" > and imports them; the modules register themselves any class (or classes), > and at appropiate times the application calls some method(s) of the > registered plugins. An alternative (which we found simpler with Crunchy) is to not have a class-based structure, but working with simple modules and functions. All modules are put in the "plugin" directory which are imported at the beginning. Each module contain at least two functions: 1. register() which create the handlers dict entry so that it point out to the appropriate function. 2. one or more function that is called based on the message received. Hope it helps, Andr? > From sean at ardishealth.com Sun Mar 2 14:09:39 2008 From: sean at ardishealth.com (Sean Allen) Date: Sun, 2 Mar 2008 14:09:39 -0500 Subject: mod_python Unable to create file In-Reply-To: References: <62v31gF24ontgU1@mid.uni-berlin.de> Message-ID: <85F61543-7ACD-4D9A-97A2-DB65D3B70B27@ardishealth.com> On Mar 2, 2008, at 3:24 AM, kaush wrote: > On Mar 1, 11:24 pm, Marc 'BlackJack' Rintsch wrote: >> On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: >>> I am using Apache and mod_python to service POST/GET requests on MAC >>> OS. My script tries to create a file >> >>> file = open(file_path, 'w') >> >>> This fails with the following error >> >>> EACCES >>> Permission denied >> >>> What is missing? >> >> To state the ovious: the rights to create a file at `file_path`. >> Remember >> that web servers usually have their own "user". >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Thanks Marc. > In Apache what are the ways/directives to set the rights to a folder? none. you set permissions via the operating system. chmod would be the command from terminal you are looking for. or you can do get info on the folder in question via the finder and set perms there. From sn7ewwp977b3g4tnwqce at gmail.com Wed Mar 12 15:10:19 2008 From: sn7ewwp977b3g4tnwqce at gmail.com (ayt46g6b) Date: Wed, 12 Mar 2008 12:10:19 -0700 (PDT) Subject: Make Money Using Paypal Get Paid Instantly Message-ID: Make Money Using Paypal Get Paid Instantly Make 1k-5k every week without leaving the comfort of your own home Click Here to Make Money Using Paypal and Get Paid Instantly http://freetrafficbuzz.com/recommends/cashdirectly From kveretennicov at gmail.com Sat Mar 29 18:12:52 2008 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sun, 30 Mar 2008 00:12:52 +0200 Subject: Python and xml In-Reply-To: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> References: <2323A6D37908A847A7C32F1E3662C80EB5E7FA@dc1ex01.air.org> Message-ID: <4660fe300803291512n5f5255e5v564f6bef2ac0f71d@mail.gmail.com> On Sat, Mar 29, 2008 at 3:57 PM, Doran, Harold wrote: > I am a python neophyte who has used python to parse through text files > using basic functions and no OOP experience. I have a need to process some > xml files and from what I am now reading python is the exact tool I need to > work through this issue. > > However, as I read online docs and peruse which books to buy, I am quickly > becoming overwhelmed with the topic and could use some guidance on how to > best tackle my task. > > You can start with this basic example (requires Python 2.5): spam.xml: Dinsdale (Face the Press) The Spanish Inquisition Deja vu The Buzz Aldrin Show Live From the Grill-O-Mat Snack Bar It's a Living The Attila the Hun Show Archaeology Today How to Recognize Different Parts of the Body Scott of the Antarctic How Not to Be Seen Spam Royal Episode 13 spam.py: from xml.etree.ElementTree import ElementTree as ET et = ET(file='spam.xml') for episode in et.findall('episode'): print episode.attrib['number'] + ':', '"' + episode.text + '"' Use standard csv module if you want to produce csv ouput ( http://docs.python.org/lib/module-csv.html). -- kv -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sat Mar 1 08:40:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 08:40:54 -0500 Subject: invert or not ? In-Reply-To: <47C93410.9050005@gmail.com> References: <47C93410.9050005@gmail.com> Message-ID: Stef Mientki wrote: > hello, > > from the manual I read that a bitwise inversion should be done by invert. > But from some experiments I see that not works equally well. > Is this coincidence ? > > (The disadvantage of invert is that I've to import operators) > Bitwise inversion is performed by the "~" operator. I think your experimentation has been inadequate: >>> for i in range(-10000, 10000): ... if (not i) == (~i): ... print i ... -1 >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gigs at hi.t-com.hr Mon Mar 31 18:25:34 2008 From: gigs at hi.t-com.hr (gigs) Date: Tue, 01 Apr 2008 00:25:34 +0200 Subject: class super method Message-ID: is there any tutorial for super method (when/how to use it)? or maybe someone could explain me how it works? thx From jeff at schwabcenter.com Thu Mar 20 02:53:22 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 19 Mar 2008 23:53:22 -0700 Subject: ftp recursively In-Reply-To: <7xk5jz1a80.fsf@ruckus.brouhaha.com> References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> <7xk5jz1a80.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Jeff Schwab writes: >> ftping it as a flat file, and untarring it on the other side. Of >> course, the motivation wasn't just to get the files from point A to >> point B using Unix (which I already know how to do), but to take >> advantage of an opportunity to learn some Python; next time, I'll try >> the ftpmirror.py script if it's generic enough, or ftplib if there are >> more specific requirements. > > I see, that wasn't clear in your original post. You should look at > the os.walk function if you want to know how to traverse a directory > tree (maybe you are already doing this). I thought os.walk was for locally mounted directories... How is it relevant on remote filesystems? > Also, for security reasons, > it's getting somewhat uncommon, and is generally not a good idea to > run an ftpd these days, even on a LAN. It's more usual these days > to transfer all files by rcp or rsync tunnelled through ssh. Don't shoot the messenger, but you're severely confused here. Whether you're using ftp, rcp, or rsync is a completely separate issue to whether you're running over ssl (which I assume you meant by ssh). FTP is a work-horse protocol for transferring files. It's going to be with us for a long, long time. There are various clients and servers built on it, including the traditional ftp command-line tools on Unix and Windows. rcp is a very simple tool for copying files from one (potentially remote) place to another. The point of rcp is that its interface is similar to cp, so the flags are easy to remember. Modern Unix and Linux systems usually include secure versions of both ftp and rcp, called sftp and scp, respectively. The point of rsync is to keep a local directory tree in sync with a remote one, by transferring only change-sets that are conceptually similar to patches. If you're only transferring files once, there's no particular benefit (AFAIK) to using rsync rather than some kind of recursive ftp. From castironpi at gmail.com Thu Mar 6 13:35:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 10:35:02 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> Message-ID: <1cf5a022-1b9d-4735-86f1-f18b018dbd82@59g2000hsb.googlegroups.com> > > > > I'm talking about castironpi. ?I find his posts a waste of my time > > > > "His" posts? > > > Whatever. ?I'm too old to worry about searching for politically correct, > > gender neutral pronouns. > > I'm pretty sure even the most PC people wouldn't suggest using a > masculine pronoun for an inanimate objects. > > (Ok, some probably would.) > > Carl Banks Traceback (most recent call last): File "", line 1, in AssertionError: Hey, that's not nice. >>> From needin4mation at gmail.com Thu Mar 20 11:57:38 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 20 Mar 2008 08:57:38 -0700 (PDT) Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: <0dd3f571-b044-4ea4-8e58-14b21dc3c7b8@z38g2000hsc.googlegroups.com> On Mar 20, 11:44?am, Jeff Schwab wrote: > jmDesktop wrote: > > On Mar 20, 11:21 am, Grant Edwards wrote: > >> On 2008-03-20, jmDesktop wrote: > > >>> Hi, I'm trying to learn Python. ?I using Aquamac an emac > >>> implementation with mac os x. ?I have a program. ?If I go to the > >>> command prompt and type pythong myprog.py, it works. ?Can the program > >>> be run from within the editor or is that not how development is done? > >>> I ask because I was using Visual Studio with C# and, if you're > >>> familiar, you just hit run and it works. ?On Python do I use the > >>> editor for editing only and then run the program from the command > >>> line? > > Sort of. ?Modern editors generally have support for building and running > your program directly from a toolbar button or textual command. ?I > personally use Vim with the toolbar disabled, running in a Terminal, and > run the program by first putting Vim in the background (^z). > > People writing code specific to Mac, but not necessarily all in Python, > often use XCode. > > ? ? ?http://zovirl.com/2006/07/13/xcode-python/ > > In the Ruby community, Vim is the dominant choice, but a lot of Mac > users swear by TextMate. > > ? ? ?http://macromates.com/ > > >>http://www.google.com/search?q=emacs+python > > Gee. ?Thanks. > > I believe Grant was suggesting that Emacs often serves a similar purpose > on Unix to what Visual Studio does on Windows, which seemed to be what > you were asking. ?When asking about Mac OS X here, you are likely to get > a lot of generic Unix responses. ?(Would it have been clearer if he had > just said "emacs?") No. Typically when someone posts a one-liner search it means go figure it out and stop bothering "us." I had already searched. I could not get it to work, which is why I posted. If I took it wrong I apologize. I really had two questions. One is just how to run a program from within the editor and the other is if my thinking on how development is done in python wrong to start with. Most of my non-Windows programs have been on Unix using vi, but it has been a while. I'm used to writing a program in visual studio and running it. If that's the wrong expectation for python programming in emacs, then I wanted to know. Thanks for your help. From jacob.kaplanmoss at gmail.com Sun Mar 16 11:56:39 2008 From: jacob.kaplanmoss at gmail.com (Jacob Kaplan-Moss) Date: Sun, 16 Mar 2008 08:56:39 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <8d6fbabd-2312-4324-9103-ead8600a2412@m36g2000hse.googlegroups.com> On Mar 16, 6:10?am, Bruce Eckel wrote: > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Thanks for being harsh here, Bruce. I've been responsible for organizing the lightning talks at PyCon over the past few years and Saturday's talks -- where a grand total of four community talks were given between twelve sponsor talks -- was the low point. I volunteer to run the lightning talks because they're usually by *far* my favorite time of the conference. Yesterday wasn't. > What was supremely frustrating was discovering that the people wanting > to give REAL lightning talks had been pushed off the end of the list > by this guarantee to vendors. We didn't get to see the good stuff, the > real stuff, because that time had been sold. Tell me about it. I felt like crap putting up a sign-up sheet with four names on it. Again, thanks for your harsh words, Bruce. Needed to be said. Jacob From gagsl-py2 at yahoo.com.ar Wed Mar 26 01:03:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 02:03:24 -0300 Subject: Prototype OO References: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> <13ujk0f9inb73c2@corp.supernews.com> Message-ID: En Wed, 26 Mar 2008 01:27:15 -0300, escribi?: > On Mar 25, 11:24?pm, Dennis Lee Bieber wrote: >> On Wed, 26 Mar 2008 06:49:57 +0800, "Delaney, Timothy (Tim)" >> declaimed the following in comp.lang.python: >> >> > As an aside, having lived much of my early life on a hobby farm, I've >> > often wondered to myself just what cow-orking involves ... ;) >> >> ? ? ? ? Probably millennia too late to ask Saruman... > > Solomon? No: http://en.wikipedia.org/wiki/Saruman -- Gabriel Genellina From arnodel at googlemail.com Mon Mar 17 18:57:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 17 Mar 2008 15:57:47 -0700 (PDT) Subject: Interesting math problem References: Message-ID: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> On Mar 17, 10:24?pm, "BJ?rn Lindqvist" wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > ? ? step = distance / float(parts) > ? ? intstep = int(step) > ? ? floatstep = step - intstep > > ? ? steps = [] > ? ? acc = 0.0 > ? ? for i in range(parts): > ? ? ? ? acc += floatstep > ? ? ? ? step = intstep > ? ? ? ? if acc > 0.999: > ? ? ? ? ? ? step += 1 > ? ? ? ? ? ? acc -= 1.0 > ? ? ? ? steps.append(step) > ? ? return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L > > -- > mvh Bj?rn OK then, using list comprehensions. It is more succint, is it easier to read? def slope(dist, parts): return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)] >>> slope(130, 50) [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] >>> len(slope(130, 50)) 50 >>> sum(slope(130, 50)) 130 >>> Smugly yours -- Arnaud From ds-python-list at sidorof.com Sat Mar 29 18:28:50 2008 From: ds-python-list at sidorof.com (DS) Date: Sat, 29 Mar 2008 15:28:50 -0700 Subject: Licensing In-Reply-To: <13utg1v4rs9c2d1@corp.supernews.com> References: <13utg1v4rs9c2d1@corp.supernews.com> Message-ID: <47EEC2A2.8040103@sidorof.com> Scott David Daniels wrote: > DS wrote: > >> I'm getting ready to publish a first open-source project written in >> python. I am planning to use GPL as the license. However, in my code, >> there is a function that I like from Python Cookbook.... >> So, my options appear to be: >> 1. Don't use it. >> 2. Use it with no comment -- that doesn't seem right. >> 3. Use it with remarks in the code that acknowledge the source. >> > I vote for this. If you got it of the web site, include a url. If you > went for the book, I'd prefer crediting both, but at least give enough > so the interested reader can get back to some version of "the original." > > >> 4. Provide a separate licensing page for that function >> along with the GPL for my code. >> What is the appropriate course of action here? I'm thinking #3 is >> probably ok. How do others deal with this in an honorable way? >> > As the author of several of those recipes, I definitely expect others > to use them. I'd hate to slow them up by requiring them to ask > permission, but would appreciate an acknowledgment. > > -Scott David Daniels > Scott.Daniels at Acm.Org > Thanks for your perspective. I'll do both. From miki.tebeka at gmail.com Tue Mar 11 15:06:36 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 11 Mar 2008 12:06:36 -0700 (PDT) Subject: How to make a Tkinter widget always visible? References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> <47D6C81A.1070301@codebykevin.com> Message-ID: Hello Kevin, > > Is there a way to make sure that these buttons are always visible? > > There are various ways to do this: you can set the window to be > non-resizable, or set a minimum size to it, so that it can't be resized > below that level. However, if you allow arbitrary resizing of the > window, there's no real way to guarantee that the widgets will be > visible at all times. Thanks. I've set a minimal size to the window. However when I resize it to be shorter, the buttons are hidden while the top frame stays visible. Thanks, -- Miki http://pythonwise.blogspot.com From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 19:51:21 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 01:51:21 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <87hceo73ap.fsf@physik.rwth-aachen.de> Message-ID: <65anbqF2fg18bU1@mid.individual.net> Torsten Bronger wrote: > Emacs is generally not regarded as being convenient, however, it > has very strong input methods. I type "\gtrless" and get "?", > or "\forall" and get "?". I wonder where the point of this is. :) Why use fancy unicode chars if they're not better to read (apart from not being readable with every font) and require at least the same amount of keypresses? Regards, Bj?rn -- BOFH excuse #123: user to computer ratio too high. From tim.tadh at gmail.com Wed Mar 26 15:41:31 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Wed, 26 Mar 2008 12:41:31 -0700 (PDT) Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: Mike Driscoll said: > Besides, you should use sqlite rather than pickle databases. It's > especially easy since sqlite is included with Python 2.5. I am using mysql, and sqlite is not appropriate for my situation since some of the databases and tables I access are being accessed by other applications which are already written and live. I am not using the SQLAlchemy or SQLObject, because I didn't want too (although in the future I may consider using them). This question actually has nothing to do with the database, I simply put the information on the database in to give it some context. cheers Tim Henderson From sjdevnull at yahoo.com Mon Mar 3 17:30:01 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 3 Mar 2008 14:30:01 -0800 (PST) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 2, 1:18 pm, castiro... at gmail.com wrote: > On Mar 2, 12:01 pm, John DeRosa wrote: > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > >Hi, > > > >Have you ever seen Beautiful Python code? > > >Zope? Django? Python standard lib? or else? > > > >Please tell me what code you think it's stunning. > > > Just about any Python code I look at. > > Decorators, with, and namedtuple. IMO, decorators are functional but far from beautiful. They're a special, somewhat ugly syntax for something that was already handled by normal constructs ("foo=classmethod(foo)") that you didn't need extra knowledge to understand. On balance I think it's worth it in order to get those "declarations" up by the function defs, but it's sort of a tradeoff of magical non- explicitness for pragmatism over purity. A worthwile tradeoff, but not what I'd ever call beautiful. From fn681 at ncf.ca Sun Mar 2 13:59:34 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 02 Mar 2008 13:59:34 -0500 Subject: Problem with the strip string method In-Reply-To: References: Message-ID: castironpi at gmail.com wrote: > On Mar 2, 11:45 am, Steve Holden wrote: >> I suspect what you need is the .replace() method. > > The information's there-- the word 'contiguous' might clear it up a > bit. > >>> Return a copy of the string with the >>> leading and trailing characters removed. >>> The chars argument is a string >>> specifying the set of characters to be >>> removed. If omitted or None, the chars >>> argument defaults to removing >>> whitespace. The chars argument is not a >>> prefix or suffix; rather, all >>> combinations of its values are stripped: > > Return the string's substring from the first character not a member of > 'chars' to the last such. > > Remove contiguous leading and trailing members of 'chars'. If omitted > or None, 'chars' defaults over to the set of whitespace set( "\n\r\t > " ). (XXX TODO: ask Steve Reg Ex Guru this). Thanks to all respondents, Steve Holden is right, I expected more than I should have. Colin W. From dickinsm at gmail.com Thu Mar 13 21:50:18 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 13 Mar 2008 18:50:18 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: <1bfed08e-87e2-41d0-9f16-3c9d53dfa3c0@a70g2000hsh.googlegroups.com> On Mar 13, 8:38?pm, Alan Isaac wrote: > Does this do it? :: > > ? ? key= lambda x: (-x[1],int(x2)) > > Here I am depending on the lexicographic sorting of tuples. > Without that there would be real trouble. Close. :-) I think it needs to be something like: key = lambda x: (-x[0], int(x[1]) if x[0] == 0 else -int(x[1])) Relying on lexicographic sorting of tuples seems okay to me. What bugs me more about this example is that one has to rely on the existence of a way to negate the usual ordering. This is fine for numbers (where you can use the unary - operator) or for numeric strings (where you can convert to int and then use -), but it's not too much of a stretch to imagine cases where neither of those options is available (e.g. non-numeric strings), and where one ends up moving further and further from readable code and into the realm of arcane trickery... Mark From corynissen at gmail.com Fri Mar 7 10:33:54 2008 From: corynissen at gmail.com (corynissen at gmail.com) Date: Fri, 7 Mar 2008 07:33:54 -0800 (PST) Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: On Mar 7, 9:12 am, nodrogbrown wrote: > hi > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', > > can anyone pls help > gordon see path.join in the os library. From gagsl-py2 at yahoo.com.ar Tue Mar 4 10:05:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Mar 2008 13:05:54 -0200 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: En Tue, 04 Mar 2008 11:46:48 -0200, NickC escribi?: > A mildly interesting Py3k experiment: > > Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from fractions import Fraction >>>> from decimal import Decimal >>>> def check_accuracy(num_type, max_val=1000): > ... wrong = 0 > ... for x in range(1, max_val): > ... for y in range(1, max_val): > ... wrong += (x / num_type(y)) * y != x > ... return wrong > ... >>>> check_accuracy(float) > 101502 >>>> check_accuracy(Decimal) > 310013 >>>> check_accuracy(Fraction) > 0 > > > The conclusions I came to based on running that experiment are: > - Decimal actually appears to suffer more rounding problems than float > for rational arithmetic Mmm, but I doubt that counting how many times the results are equal, is the right way to evaluate "accuracy". A stopped clock shows the right time twice a day; a clock that loses one minute per day shows the right time once every two years. Clearly the stopped clock is much better! http://mybanyantree.wordpress.com/category/lewis-carrol/ -- Gabriel Genellina From nagle at animats.com Wed Mar 26 20:03:49 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 17:03:49 -0700 Subject: Some notes on a high-performance Python application. In-Reply-To: References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: <47eae223$0$36409$742ec2ed@news.sonic.net> Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 18:54:29 schrieb Michael Str?der: >> Heiko Wundram wrote: >>> Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: > I didn't say it was unusual or frowned upon (and I was also taught this at uni > IIRC as a means to "easily" distribute systems which don't have specific > requirements for response time to RPC requests), but anyway, as you noted for > Biztalk, it's much easier to hit bottlenecks with a polling-style RPC than > with a "true" RPC system, as I've come to experience when the number of nodes > (i.e., backends) grew over the last year and a half. I know, I don't like the polling either. The time scale is such that the poll delay isn't a problem, though, and because it's using the MySQL MEMORY engine, there's no disk I/O. After completing a request, the rating scheduler immediately queries the database, so there's no lost time if there's a queue. The polling delay only applies when a rating server is idle. I miss QNX, which has good message passing primitives. Linux is weak in that area. John Nagle From siddhantgoel at gmail.com Sat Mar 22 06:21:15 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Sat, 22 Mar 2008 03:21:15 -0700 (PDT) Subject: implementing tab completion using python Message-ID: <5f733b8e-b869-4f2b-930c-42a044935ad4@u10g2000prn.googlegroups.com> Hi. How can I implement a tab-completing code using Python? Like for example, I want to design a simple shell (using Python, of course), which could support tab completion as well. How do I go about it? Thanks. Siddhant From pofuk at email.t-com.hr Sun Mar 2 16:37:35 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Sun, 2 Mar 2008 22:37:35 +0100 Subject: Run Python app at startup Message-ID: Hy. I create simple application. Yust an windows and "compile" it with py2exe. I add registry value reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v MyApp /t REG_SZ /d C:\myapp.exe /f' And it wont start. When i use console instead od window in py2exe i get console opend but it closes. Program: import os import wx app = wx.App() frame = wx.Frame(None, -1, "MyFrame") frame.Show() app.MainLoop() Then in commang prompt: python.exe setup.py py2exe from distutils.core import setup import py2exe setup(console=['prog.py']) Help please! From bj_666 at gmx.net Thu Mar 13 03:53:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Mar 2008 07:53:42 GMT Subject: Class Inheritance References: Message-ID: <63s4s6F29blveU1@mid.uni-berlin.de> On Thu, 13 Mar 2008 00:06:52 -0500, "Andrew Rekdal" < wrote: > Problem is layout_ext and Layout code is dependant on a Class instance > 'css'. Then pass that instance to the `Layout` class in the `__init__()` so both, the base class and the subclass use the same `CSS` instance. Ciao, Marc 'BlackJack' From dteslenko at gmail.com Wed Mar 5 04:33:49 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 5 Mar 2008 12:33:49 +0300 Subject: draining pipes simultaneously Message-ID: <91325fec0803050133y158817efk761f719cc4c41f1e@mail.gmail.com> Hello! Here's my implementation of a function that executes some command and drains stdout/stderr invoking other functions for every line of command output: def __execute2_drain_pipe(queue, pipe): for line in pipe: queue.put(line) return def execute2(command, out_filter = None, err_filter = None): p = subprocess.Popen(command , shell=True, stdin = subprocess.PIPE, \ stdout = subprocess.PIPE, stderr = subprocess.PIPE, \ env = os.environ) qo = Queue.Queue() qe = Queue.Queue() to = threading.Thread(target = __execute2_drain_pipe, \ args = (qo, p.stdout)) to.start() time.sleep(0) te = threading.Thread(target = __execute2_drain_pipe, \ args = (qe, p.stderr)) te.start() while to.isAlive() or te.isAlive(): try: line = qo.get() if out_filter: out_filter(line) qo.task_done() except Queue.Empty: pass try: line = qe.get() if err_filter: err_filter(line) qe.task_done() except Queue.Empty: pass to.join() te.join() return p.wait() Problem is my implementation is buggy and function hungs when there's empty stdout/stderr. Can I have your feedback? From MartinRinehart at gmail.com Sun Mar 2 10:30:35 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sun, 2 Mar 2008 07:30:35 -0800 (PST) Subject: Python's BNF References: <85ae78f6-056b-4219-9952-66750e3ebf58@e60g2000hsh.googlegroups.com> <3e1d7bac-001d-498b-add5-2f2322795dd8@x41g2000hsb.googlegroups.com> Message-ID: Gabriel Genellina wrote: > About the generated page: I think it would be more useful if each symbol > links to its definition, instead of showing an alert(). This way it's > easier to navigate the tree, specially with complex declarations. That was my first shot. It didn't work. (Every line is its own table because you can't put named anchors inside a table, something I really regret.) If the production is already viewable, there's no jump when you click the link.. If the production is on the last page (many are) you jump to the last page and then have to hunt down the production. Remind me to figure out Ajax so you get what we really want: click on it and see its definition highlighted. > You can place the current text into a "title" attribute and most browsers > will show it as a tooltip. Great! Consider it done. Konqueror, Firefox, Opera and even MSIE. How would
,
and
make our lives easier? I also tried putting the definitions into the status bar. If you ever feel tempted to do something similar, let the urge pass. (This now works in Firefox 2 if you use the correct settings to allow javascript to write to the status bar. It doesn't work in Konqueror or Opera and I can't even find the settings for MSIE.) Trying to get this to work DID get me to considerably improve the readability of the HTML, so it wasn't a total waste. The tooltips are a big step forward. Thanks again. Improved version at http://www.MartinRinehart.com/articles/python-parse-bnf.html From jn.nntp.scrap001 at wingsandbeaks.org.uk Sat Mar 1 13:25:39 2008 From: jn.nntp.scrap001 at wingsandbeaks.org.uk (Jeremy Nicoll - news posts) Date: Sat, 1 Mar 2008 18:25:39 +0000 Subject: Import, how to change sys.path on Windows, and module naming? References: Message-ID: Jeremy Nicoll - news posts wrote: > If I understand correctly, when I import something under Windows, Python > searches the directory that the executing script was loaded from, then > other directories as specified in "sys.path". Sorry to followup my own question, but I ran for p,q in enumerate(sys.path): print p, q and got: 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms 1 C:\Program Files\~P-folder\Python25\Lib\idlelib 2 C:\WINDOWS\system32\python25.zip 3 C:\Program Files\~P-folder\Python25\DLLs 4 C:\Program Files\~P-folder\Python25\lib 5 C:\Program Files\~P-folder\Python25\lib\plat-win 6 C:\Program Files\~P-folder\Python25\lib\lib-tk 7 C:\Program Files\~P-folder\Python25 8 C:\Program Files\~P-folder\Python25\lib\site-packages 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip in their sys.path? What's the point of having a zip in the path? Also, looking in C:\WINDOWS\system32\ I don't actually have a file called python25.zip, but I do have one called python25.dll - so has something gone wrong in creation of sys.path? -- Jeremy C B Nicoll - my opinions are my own. From zerty.david at gmail.com Mon Mar 24 12:29:39 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 24 Mar 2008 13:29:39 -0300 Subject: Problems with wxPython Message-ID: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> Hi, If ther's anyone who knows pretty much about wxPython can e-mail me? I'm having some trouble in dealing with some guis here, I would thank u very much if you could help me bye []'s -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Bossy at jouy.inra.fr Mon Mar 17 09:36:51 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 17 Mar 2008 14:36:51 +0100 Subject: lists v. tuples In-Reply-To: References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <47DE73F3.8070901@jouy.inra.fr> castironpi at gmail.com wrote: > On Mar 17, 6:49 am, MartinRineh... at gmail.com wrote: > >> What are the considerations in choosing between: >> >> return [a, b, c] >> >> and >> >> return (a, b, c) # or return a, b, c >> >> Why is the immutable form the default? >> > > Using a house definition from some weeks ago, a tuple is a data > structure such which cannot contain a refrence to itself. Can a > single expression refer to itself ever? > In some way, I think this answer will be more confusing than enlightening to the original poster... The difference is that lists are mutable, tuples are not. That means you can do the following with a list: - add element(s) - remove element(s) - re-assign element(s) These operations are impossible on tuples. So, by default, I use lists because they offer more functionality. But if I want to make sure the sequence is not messed up with later, I use tuples. The most frequent case is when a function (or method) returns a sequence whose fate is to be unpacked, things like: def connect(self, server): # try to connect to server return (handler, message,) It is pretty obvious that the returned value will (almost) never be used as is, the caller will most probably want to unpack the pair. Hence the tuple instead of list. There's a little caveat for beginners: the tuple is immutable, which doesn't mean that each element of the tuple is necessarily immutable. Also, I read several times tuples are more efficient than lists, however I wasn't able to actually notice that yet. Cheers, RB From python.list at tim.thechases.com Tue Mar 4 17:02:02 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Mar 2008 16:02:02 -0600 Subject: sqlite3 permission issue In-Reply-To: References: Message-ID: <47CDC6DA.3030109@tim.thechases.com> > I am trying to execute an update to a sqlite3 db via a python cgi If you're running as a CGI, your script (as you guess below) will usually run with the effective permissions of the web-server. Frequently, this is some user such as "wwwdata" or "www". > conn = sqlite3.connect('db') Make sure that this is fully qualified: dbname = '/path/to/where/www/can/write/db' conn = sqlite3.connect(dbname) In addition, if your local user ("cstromberger" for example) owns that DB file, you'll need to make sure that www can access that file: bash> chown :wwwdata db (assuming the webserver runs with GID "wwwdata") and then make sure you've got 660 permissions on it (rw-rw----). Issuing a chown as non-root may be disallowed. > I can run the exact same python code from the command line and it > works, so it has something to do with the user that runs the cgi > (apache I assume). I chmodded the db file to 666, but it did not > help. If the DB file is truly read/write as you describe, I'm guessing that the path has not been properly resolved. It might be lazily opening the file, failing on first access rather than on the connect() call. You might also check to see if your Apache is running in a chroot jail which may prevent it from seeing files in particular paths outside that jail. Just a few ideas to test. If you know you can open the file and read from it (the path is fully-qualified and you have permission to open the file), then make sure your permitted to. It may help to make some stat() calls on the file to ensure that it's really where you think it is, and has the permissions you think it has. Hope they help, -tkc From http Tue Mar 18 03:50:46 2008 From: http (Paul Rubin) Date: 18 Mar 2008 00:50:46 -0700 Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> <7xod9cvbq3.fsf@ruckus.brouhaha.com> Message-ID: <7xskyoii7d.fsf@ruckus.brouhaha.com> Larry writes: > I even went further to opening the file using notepad, and did a > search-and-replace for space characters. The result was what I > desired: data,data,data... In Windows, you also have to make sure to open binary files in binary mode. From rbossy at jouy.inra.fr Sat Mar 1 08:51:58 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 01 Mar 2008 14:51:58 +0100 Subject: why not bisect options? In-Reply-To: References: Message-ID: <1204379518.47c95f7e37930@www.jouy.inra.fr> Selon Raymond Hettinger : > [Robert Bossy] > > I thought it would be useful if insort and consorts* could accept the > > same options than list.sort, especially key and cmp. > > If you're going to do many insertions or searches, wouldn't it be > *much* more efficient to store your keys in a separate array? > > The sort() function guarantees that it calls the key function exactly > once for each member of the list. With and bisect/insort, successive > searches can call the key function over and over again with the same > value. Yeah, sure. Thanks for pointing that out. RB From jeffrey at fro.man Tue Mar 4 14:22:04 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 04 Mar 2008 11:22:04 -0800 Subject: for-else References: Message-ID: <13sr8asd6vlnl52@corp.supernews.com> Carl Banks wrote: > there is a > rationale behind the name "else". ?If you consider a for loop to be a > rolled-up if...elif...else statement This is an interesting angle. I've always considered "for/else" to be unintuitive, not because of "else", but because of the coupling with "for". Instead, I think of this as a "break/else" statement, and everything gels for me. The same applies to my comprehension of "while/else". I wonder how this came to be called "for/else" or "for-else". I haven't spotted that expression in the python docs yet. With whatever name, I find the construct quite elegant and regularly useful. Jeffrey From mail at microcorp.co.za Sat Mar 15 04:59:44 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Mar 2008 10:59:44 +0200 Subject: List mutation method gotcha - How well known? References: <000901c884dd$057d5d80$03000080@hendrik> <740c3aec0803130806w2eed0c5eq2c0f0096557fce8@mail.gmail.com> Message-ID: <002501c8867a$ea23b580$03000080@hendrik> On Thu, Mar 13, 2008 at 8:36 AM, Hendrik van Rooyen wrote: > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above windows using idle: >>> foo = [1,2,3,4] >>> x = foo.append(5) >>> print x None >>> x >>> So the "Correct" answer is 5, and I would have allowed 4 also if it were a test, which it wasn't. I count ten responses, but this is probably wrong, as I did not receive digest number 171 which must have contained my original post. All of them seemed aware of the fact the append returned None. In any case, none of the respondents fell for the gotcha - answer 2, that assumes that the append returns the mutated list. One respondent wanted to choose the picture, but changed his mind. This leads me to conclude that this behaviour is well known amongst people in this group. Now this need not necessarily be correct either, as people who were uncertain could simply have declined to respond, or they were so honest that after checking, they found themselves morally unable to respond as that would have been cheating... : - ) I am constantly amazed and delighted by how well Python fits my brain - its the easiest assembler language I have ever used - almost everything "just works". This is true even if like me, you don't read the manual, but blunder your way along, guessing as you go - most of the time the guesses are right, and if they are not, a few minutes at the interactive prompt serves to dispel most illusions. Thanks to everybody who responded. - Hendrik From NeilFang2008 at gmail.com Mon Mar 3 01:37:38 2008 From: NeilFang2008 at gmail.com (Neil.Fang.CN) Date: Sun, 2 Mar 2008 22:37:38 -0800 (PST) Subject: class object interface document References: Message-ID: Thanks for your reply. What is the counterpart in v3.0? -- Neil On Mar 2, 6:26?pm, "Gabriel Genellina" wrote: > En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN ? > escribi?: > > > Where can I find the Python class object interface document, such as > > struct PyClassObject, PyClass_New()? Thanks! > > PyClass_* and PyInstance_* are for old-style classes and instances ? > respectively, and will disappear in v3.0. > PyInstance is in the section 7.5.2 in the Python/C API Reference Manual; I ? > don't find any documentation on PyClass itself. > > -- > Gabriel Genellina From timr at probo.com Sat Mar 1 02:11:39 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 01 Mar 2008 07:11:39 GMT Subject: Getting a free TCP port & blocking it References: <1dff2e2c-892d-42fa-9e65-5c7c12b75ec3@s13g2000prd.googlegroups.com> Message-ID: <280is3le2op8khmgr7nj5a1mnkjd7p0n50@4ax.com> theneb wrote: >Hi all, >I'm attempting to block a TCP port from any other application from >using it until I free it from python, this is so that: >1). Generate a random free user-space port >2). Generate the script for the external program with the port >3). Free the port before external program execution. What's the point? Why can't the actual user of the port create the port, and then notify the other side of the port number? And why don't you just specify a port number of 0 and let the system assign you a free port number? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sat Mar 8 12:37:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 09:37:48 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> Message-ID: <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> On Mar 7, 9:23?pm, shak... at gmail.com wrote: > I figured I might as well share the code I ended up using, in case > anyone else wants an easy way to get strings to, for instance, SQL- > storable datetimes. > > jake at house:~$ cat test.py > #!/usr/bin/python > from datetime import datetime > import subprocess > > def parsedate( date ): > ? ? p = subprocess.Popen(['date','+%s.%N',"--date=%s" % > date],stdout=subprocess.PIPE) > ? ? out = float(p.stdout.read()) > ? ? return "%s" % datetime.fromtimestamp(out) > > jake at house:~$ python -i test.py>>> parsedate("today") > > '2008-03-07 21:20:31.870489'>>> parsedate("tomorrow") > > '2008-03-08 21:20:40.516243'>>> parsedate("next monday") > > '2008-03-10 00:00:00'>>> parsedate("10pm last week") > > '2008-02-29 22:00:00'>>> parsedate("last tuesday") > > '2008-03-04 00:00:00' I am a GNU newbie. (I know C &o.) Can you point me to a place to find the source for 'date'? From troworld at gmail.com Sat Mar 1 18:56:27 2008 From: troworld at gmail.com (Tro) Date: Sat, 1 Mar 2008 18:56:27 -0500 Subject: Altering imported modules Message-ID: <200803011856.27611.troworld@gmail.com> Hi, list. I've got a simple asyncore-based server. However, I've modified the asyncore module to allow me to watch functions as well as sockets. The modified asyncore module is in a specific location in my project and is imported as usual from my classes. Now I'd like to use the tlslite library, which includes an asyncore mixin class. However, tlslite imports "asyncore", which doesn't include my own modifications. I'd like to know if it's possible to make tlslite load *my* asyncore module without changing any of the tlslite code. Thanks, Tro From mhwalker at shaw.ca Tue Mar 4 01:38:15 2008 From: mhwalker at shaw.ca (Mike Walker) Date: Tue, 04 Mar 2008 06:38:15 GMT Subject: Command line arguments in Windows In-Reply-To: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: > If you run a python file, ie. just double clicking it the only > argument you will have will be the filename of the script. If you > create a shortcut to the script and in the target box add your > arguments (if you have quotation marks place them after not inside) > you will see your arguments. fwiw you answered yourself in the third > paragraph. As I mentioned I am working from the command line, not clicking on the icon. The only difference between it working and not is the python prefix, which is why I was thinking this is some sort of file association problem. I probably wasn't as clear as I could have been in the third paragraph. argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] python argtest.py arg1 arg2 arg3 - Works From tejovathi.p at gmail.com Thu Mar 27 01:48:29 2008 From: tejovathi.p at gmail.com (Teja) Date: Wed, 26 Mar 2008 22:48:29 -0700 (PDT) Subject: copy file over LAN References: Message-ID: On Mar 27, 8:34?am, Astan Chee wrote: > Hi, > I have afileon another machine on the localnetwork(my machine and > local machines are on windows) and I want tocopyit locally. Now the > machine requires authentication and when I try to do a > import shutil > shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') > and it gives me a IOError: [Errno 13] Permission denied: error, which I > expect. How do I provide authentication tocopythisfile? > Thanks for the help. > Cheers > Astan > > -- > "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." > > Animal Logichttp://www.animallogic.com > > Please think of the environment before printing this email. > > This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. Hi, Is the folder where the file is present i.e. "temp" in your case, shared???? Can you share it and try it?? I tried this way and it worked! import shutil shutil.copyfile(r'\\129.124.66.112\Samplesharedfolder\samplefile.txt', r'C:\\Test\\temppp.txt') Try this way and let me know From sophacles at gmail.com Thu Mar 13 01:33:59 2008 From: sophacles at gmail.com (Erich) Date: Wed, 12 Mar 2008 22:33:59 -0700 (PDT) Subject: Generator woes Message-ID: Hi all, I am trying to get the following generator to work to these goals: 1. When it recieves an exception (via a throw()) it yeilds the value of handler.remaining. Otherwise it yeilds None. 2. Send adds data to the generator. Goal 2 is working great. Goal 1 on the other hand, is not working. The result of a throw is always None. Any reasons why this does not work as I expect? If not, what is wrong? Code: def make_handler(): def handler(): eol = '\r\n' handler.remaining = 1 response = '' data = '' while not response.endswith(eol): trv = None try: ndata = (yield trv) if ndata: response += ndata trv = None except: trv = handler.remaining response = response.strip() yield response * 2 res = handler() res.next() return res x = make_handler() y = x.send('a') print 'y (should be None):',y y = x.send('b') print 'y (should be None):',y y = x.throw(Exception) print 'y (should be 1):',y y = x.send('c\r\n') print 'y (should be abcabc):',y Output: y (should be None): None y (should be None): None y (should be 1): None y (should be abcabc): abcabc Thanks, Erich From gagsl-py2 at yahoo.com.ar Sun Mar 16 14:29:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 16:29:10 -0200 Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> <9b959898-ed57-47b9-8158-7ca6a321e705@u69g2000hse.googlegroups.com> Message-ID: En Sat, 15 Mar 2008 20:08:05 -0200, escribi?: > On Mar 15, 8:18?am, Bryan Olson wrote: >> castiro... at gmail.com wrote: >> > Newbie question: ?Can you write to the 'file-like object' a pickle, >> > and receive it intact-- as one string with nothing else? >> >> Yes, but there's a world of gotcha's. Sockets do not recognize >> record boundaries, and Python's 'pickle' has holes one's enemies >> could drive a truck through. Still, you can pickle, write, read, >> un-pickle, and get back your data intact. >> >> > I want to know because I want to send two pickles. >> >> "Two pickles" sounds like a tasty snack, but also suggests you may >> be playing hopscotch in a minefield. This is a helpful group. Give >> us more to go on, and you are likely to receive thousands of >> dollars worth of consulting for free. > > It depends on the situation. How generally applicable is this: > > fun ListenerGeneric( port, factory, arrivedfun ): > > which calls 'factory' on socketA.accept (and loops again), then > arrivedfun( stringA ) on message complete detection. ?. It should > start itself in a separate thread. > > Or is this any better: > > for x in connections(): > startnewthreadwith x: > for y in messages( x ): > arrivedfun( y ) This looks like a SocketServer + ThreadingMixIn + a RequestHandler (your factory). But as B. Olson already pointed, pickles are unsafe. Worse, it's not that someone could send a specially crafted pickle that could execute some arbitrary code: you're blindy executing whatever you receive! xmlrpc may be a good alternative in some cases. -- Gabriel Genellina From pavlovevidence at gmail.com Wed Mar 12 12:23:26 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 09:23:26 -0700 (PDT) Subject: a Roguelike in Python References: Message-ID: <776b49ce-852d-43da-ac56-6fc3cdcaca92@u72g2000hsf.googlegroups.com> On Mar 12, 9:25 am, Mdo... at gmail.com wrote: > Seeing the 7DRL start up recently, i wanted to see what one was made > of. Python is the language i'm most familiar with so i searched for > some code to look at, but i couldn't find any. Can anyone direct me to > the right place? > > I did some searching on what it would take to write a roguelike in > python and it looked like the curses module would work perfectly, but > it looks to me like it doesn't work in windows? I tried to import it > and it says 'No Module named _curses' > > Sorry if all this sounds a bit noobish, it's only cause i am. Correct, curses is not provided on the Windows platform. I recall that there were some third party attempts to implement curses functionality on Windows; try Googling for it. Even though it's typically used for graphical games, PyGame would be a good way to make a cross-platform "text-mode" game. It should be pretty straightforward to simulate a text mode terminal using a grid of sprites. (There might even be some third-party text terminals out there.) Carl Banks From PeterBraden1 at googlemail.com Sun Mar 9 09:30:24 2008 From: PeterBraden1 at googlemail.com (PB) Date: Sun, 9 Mar 2008 06:30:24 -0700 (PDT) Subject: Uninstalling Eggs Message-ID: I just installed the Shove module with the monumentally crap setuptools. Whilst the install succeeded, imports now trigger errors, so clearly it did not install correctly. Can I simply delete the .egg file from my lib/python2.3/site-packages/ directory? Cheers, From steve at holdenweb.com Sat Mar 1 12:48:04 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 12:48:04 -0500 Subject: pySQLite Insert speed In-Reply-To: <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> Message-ID: mdboldin at gmail.com wrote: > Steve, I want to make sure I understand. My test code is below, where > ph serves as a placeholder. I am preparing for a case where the number > of ? will be driven by the length of the insert record (dx) > > dtable= 'DTABLE3' > print 'Insert data into table %s, version #3' % dtable > ph= '?, ?, ?, ?' > sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) > t0a=time.time() > for dx in d1: > curs1.execute(sqlx,dx) > print (time.time()-t0a) > print curs1.lastrowid > conn1.commit() > > I think you are saying that sqlx is re-evaluated in each loop, i.e. > not the same as pure hard coding of > sqlx= 'INSERT INTO DTABLE3 VALUES ( ?, ?, ?, ? ) ' > Is that right? Yes. If the sql is constant then you would be performing an unnecessary computation inside the loop. Not a biggie, but it all takes time. Is the loop above your original code? If so I was wrong about the loop. > Hence (if I understand python convention), this can be > solved by adding > sqlx= copy.copy(sqlx) > before the looping. And in tests adding this step saved about 5-10% in > time. > Now this I don;t really understand at all. What's the point of trying to replace sqlx with a copy of itself? Perhaps if you explained what you hope this will achieve I could comment more intelligently. > And yes, I can see why (B) is always better from a security > standpoint. The python solutions for problems such as there are a > great help for people like me, in the sense that the most secure way > does not have a speed penalty (and in this case is 3-4x faster). Yes, it's a real win-win. Since both the table and the number of arguments appear to be variable one possible solution is to build a dict that would allow you to look up the right SQL using the table name. So, suppose you have the following tables and number of arguments: tables = (("table1", 3), ("table2", 5), ("table3", 2) ) you could create a suitable dict as (untested): tdict = {} for tbl, ct in tables: tdict[tbl] = "INSERT INTO %s VALUES (%s)" % \ (tbl, ", ".join(["?"] * ct)) Then you can use the table to look up the right SQL, quite a fast operation compared with actually building it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From python at rcn.com Tue Mar 18 13:49:00 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 18 Mar 2008 10:49:00 -0700 (PDT) Subject: Merging a patch/diff generated by difflib? References: <605b7f04-6306-4ac5-9633-7765a2e71060@k13g2000hse.googlegroups.com> Message-ID: <768fcb06-4318-41b6-84bd-6ce136c85f35@s12g2000prg.googlegroups.com> On Mar 18, 6:08 am, erikcw wrote: > Hi, > > I'm trying to create an undo/redo feature for a webapp I'm working on > (django based). I'd like to have an undo/redo function. > > My first thought was to use the difflib to generate a diff to serve as > the "backup", and then if someone wants to undo their operation, the > diff could just be merged/patched with the current text. > > However, I've not be able to find a patch library. Are there any > libraries that will handle merging the diff back into the text? The difflib module has a restore() function. Raymond From kyosohma at gmail.com Mon Mar 31 09:45:34 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 06:45:34 -0700 (PDT) Subject: wxPython; adding a grid to a panel References: Message-ID: On Mar 31, 8:33 am, Gilles Ganault wrote: > On Mon, 31 Mar 2008 11:01:19 +0100, "Moynes James" > > wrote: > >In the script below I have added two panels to a frame. I want to > >display the grid in one panel (and later on add other widgets to the > >other panel), but I cannot get the grid to display properly. > > I'm learning wxPython as well. Could it be that you're using > wx.PySimpleApp instead of App? That's not it...check out my other post with one sample solution. Mike From R.Brodie at rl.ac.uk Fri Mar 7 11:47:48 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 7 Mar 2008 16:47:48 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: "K Viltersten" wrote in message news:63d80bF273nraU1 at mid.individual.net... > 1. When writing English, Strunk and White apply. Do they? I've never seen them ;) > 2. You should use two spaces after a sentence-ending period. > > For heavens sake, why? Most people find it easier to type two spaces than one and a half. From deets at nospam.web.de Wed Mar 26 17:33:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 22:33:56 +0100 Subject: _tkinter fails when installing Python 2.4.4 In-Reply-To: <19b9409f-f4c3-4254-b445-980462f11bf1@13g2000hsb.googlegroups.com> References: <64tahuF2absebU1@mid.uni-berlin.de> <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> <64uoqiF2dcihhU1@mid.uni-berlin.de> <19b9409f-f4c3-4254-b445-980462f11bf1@13g2000hsb.googlegroups.com> Message-ID: <64vtqfF28jojsU1@mid.uni-berlin.de> jgelfand schrieb: > On Mar 26, 7:02 am, "Diez B. Roggisch" wrote: >> I think the actual problem is that the linking doesn't find the >> XftGlyphExtends. I can only guess, but it might be related to >> 64-bit-problems. Make sure you have the library that contains the >> XftGlyphExtends is available in the lib64 dirs and so forth. > > I tried running configure with --x-include="/usr/X11R6/include" --x- > libraries="/usr/X11R6/lib" (in addition to the flags above) and got > the same error. I believe XftGlyphExtends is defined in "Xft.h" which > is located in the directory "/usr/X11R6/include/X11/Xft". Based on > the output below, python looks in "/usr/X11R6/include" but not in this > directory: > > building '_tkinter' extension > gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- > strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ > yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ > usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ > yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/_tkinter.c - > o build/temp.linux-x86_64-2.4/_tkinter.o > gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- > strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ > yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ > usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ > yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/tkappinit.c - > o build/temp.linux-x86_64-2.4/tkappinit.o > gcc -pthread -shared build/temp.linux-x86_64-2.4/_tkinter.o build/ > temp.linux-x86_64-2.4/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib - > L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -ltk8.5 -ltcl8.5 - > lX11 -o build/lib.linux-x86_64-2.4/_tkinter.so > > When I try setting CFLAGS="-I/usr/X11R6/include/X11/Xft" and re- > running configure, I get the same error message regardless if I tell > python to it to use the 32 bit of 64 bit X-Windows libraries. How > should I force python to look in this directory? The above is a LINKER error, not a compiler-error. You need to find the library which contains the missing symbol, and trace where it get's picked up wrong. Not something (I at least) can do from here. Diez From esj at harvee.org Sat Mar 1 00:28:35 2008 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 01 Mar 2008 00:28:35 -0500 Subject: anydbm safe for simultaneous writes? In-Reply-To: <728f2166-00eb-41fa-a038-9853891e69cf@64g2000hsw.googlegroups.com> References: <728f2166-00eb-41fa-a038-9853891e69cf@64g2000hsw.googlegroups.com> Message-ID: <47C8E983.2000409@harvee.org> chris wrote: > I need simple data persistence for a cgi application that will be used > potentially by multiple clients simultaneously. So I need something > that can handle locking among writes. Sqlite probably does this, but > I am using Python 2.4.4, which does not include sqlite. The dbm-style > modules would probably be fine, but I have no idea if they are "write > safe" (I have no experience with the underlying unix stuff). Any tips > appreciated. the often repeated answer that you need locking is correct but an incomplete answer. it really depends on which DBM you are using. If you are using a fairly recent bsdbm (a.k.a. sleepy cat) it does have the kind of lucky needs to fairly complex transactions. Unfortunately, the API is a sufficiently unintelligible that it will take more than an afternoon to figure out how to even start to use it. gdbm is a nice DBM that permits single writer/multiple readers. If you open a DBM for read, any writer blocks. You open it for read and some times multiple readers can get in but not always (or at least that's the way it seems here in practice). when the DBM is busy, you will get an exception with an error value of: (11, 'Resource temporarily unavailable'). Just busy wait until this exception goes away and you'll get access to the DBM file. Yes, this officially sucks but at least it's a workaround for the problem. another way to solve this particular problem with DBM files is to stick inside a Pyro daemon. Performance won't be too bad and you should be able to get it working relatively easily. I will warn you that the RPC model for Pyro does take some getting used to if you're familiar with more traditional RPC environments. Once you wrap your head around the Pyro model, it's pretty nice. If you want, I can send you a copy of my Pyro daemon I use to wrap a DBM so I don't have to worry about multiple processes accessing the same DBM. the one thing that really bothers me about the DBM interfaces is that the two main DBM's are really quite full-featured but the documentation presents a very sketchy description of what they support and how. As a result, I suspect that DBMS don't get used as often as they could and people are pushed into more complex databases because they don't understand what DBM's are capable of. Other folks have recommended some form of SQL and while SQL light is a very nice small database, personally, I find SQL unintelligible and I have lost more days than I care to think about trying to figure out how to do something in SQL. As result, I tend to go more towards databases such as metakit and buzhug (http://buzhug.sourceforge.net/). the former is like gdbm and only handles a single writer. It's really intended for single process use but I don't know if you can put it in a Pyro controlled deamon. The latter looks pretty interesting because the documentation implies that it supports concurrent access on a per record level (menu item: concurrency control). Given that I'm currently replacing a DBM for very much the same reason you are, I'm going to try using buzhug rather than facing SQL again. I would be glad to compare notes with you if you care to go the same route. Just let me know off list. I wish you the best of luck in your project. ---eric -- Speech-recognition in use. It makes mistakes, I correct some. From bthate at gmail.com Tue Mar 4 14:11:18 2008 From: bthate at gmail.com (Bart Thate) Date: Tue, 4 Mar 2008 11:11:18 -0800 (PST) Subject: ANN: GOZERBOT 0.8 released Message-ID: <9734c9ac-281e-45a7-937a-bf5d8e4b91b7@d21g2000prf.googlegroups.com> so 0.8 is there and can be downloaded from http://gozerbot.org new features: * third party addons for plugins. (needs setup.py to work) * reboots without disconnects (irc only for now) * ipv6 udp support * queues used all over the place to reduce thread usage * normal irc log format is now supported (simplelog plugin) * irc can now be disabled for jabber only usage * owneruserhost is now a list so multiple userhosts can be used * jabber reconnect code is improved * rss error reporting is improved * udp code is improved especially in the jabber case * lots of other bug fixes problems with this release can be reported on http://dev.gozerbot.org or contact us on #dunkbots on IRCnet or freenode. email is at bthate at gmail.com the gozerbot development team ABOUT GOZERBOT: Requirements * a shell * python 2.4 or higher * if you want to remotely install plugins: the gnupg module * if you want mysql support: the py-MySQLdb module * if you want jabber support: the xmpppy module Why gozerbot? * provide both IRC and Jabber support * user management by userhost .. bot will not respond if it doesn't know you (see /docs/USER/) * fleet .. use more than one bot in a program (list of bots) (see / docs/FLEET/) * use the bot through dcc chat * fetch rss feeds (see /docs/RSS/) * remember items * relaying between bots (see /docs/RELAY/) * program your own plugins (see /docs/PROGRAMPLUGIN/) * run the builtin webserver (see /docs/WEBSERVER/) * query other bots webserver via irc (see /docs/COLLECTIVE/) * serve as a udp <-> irc or jabber gateway (see /docs/UDP) * mysql and sqlite support From bbkolde at gmail.com Thu Mar 20 13:47:00 2008 From: bbkolde at gmail.com (Bhagwat Kolde) Date: Thu, 20 Mar 2008 23:17:00 +0530 Subject: if __name__ == '__main__': In-Reply-To: References: Message-ID: Thanks all my problem cleared. Bhagwat On Thu, Mar 20, 2008 at 11:02 PM, 7stud wrote: > On Mar 20, 10:21 am, "Simon Brunning" > wrote: > > On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde > wrote: > > > Hi, > > > I am new to the python and not getting meaning of following line, > > > > > if __name__ == '__main__': > > > main() > > > > The if statement is used to skip the code after the if statement in > certain situations. If that if statement is in a file named test1.py, > and you issue this command: > > $ python test1.py > > then the code after the if statement will execute. That's because > python assigns the string '__main__' to the variable __name__ when the > program starts > > However, if you do this: > > ------- > #test1.py > def my_func(num): > print num * 2 > > > if __name__ == "__main__": > print "Testing my func:", my_func(10) > > -------- > > #test2.py > import test1 > > test1.my_func(5) > > ------- > > ...and you issue the command: > > $python test2.py > > Then the code after the if statement in test1.py will not execute. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Bhagwat K "Play hard or go home" -------------- next part -------------- An HTML attachment was scrubbed... URL: From sam at mas.pl Fri Mar 21 06:43:33 2008 From: sam at mas.pl (sam) Date: Fri, 21 Mar 2008 11:43:33 +0100 Subject: Prototype OO In-Reply-To: <47e384cb$0$567$426a74cc@news.free.fr> References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers napisa?(a): >> In dynamically typed language when you create object A that is >> inherited from another object B, than object A knows that B is his >> predecessor. So >> when you reference A.prop, then prop is looked in A first, then in B, >> then in predecessors of B, and so on. > > What you're describing here is the inheritance mechanism of Python. And > could apply just as well to javascript prototype mechanism. A javascript > object has a reference to it's prototype object - that you can > customize, rebind etc -, a Python object has a reference to it's class > object - that you can customise, rebind etc... I can see that Python and Javascript inheritance model is almost the same. Both languages are dynamically typed. And it seems that using "classes" in Python makes some things more complicated then it is necessary (eg functions, methods and lambdas are differen beeing in Python concept). > Don't be fooled by the term "class" itself - it's meaning is totally > different in a language like Python. Probably I'm not alone. Many people who think dymanic types are Rhight Thing in programming will also prefer prototype-based programming to class-based. > suspect you don't have a serious knowledge of Python's object model. Yes -- I'm new to Python. From gaohawk at gmail.com Sat Mar 1 04:01:55 2008 From: gaohawk at gmail.com (hawk gao) Date: Sat, 1 Mar 2008 17:01:55 +0800 Subject: A python STUN client is ready on Google Code. In-Reply-To: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> References: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> Message-ID: <8ce119530803010101w320b8d30md5112aebab6f7551@mail.gmail.com> I upload a new version. Add more print log into my code to help people understand my program 2008/2/29, hawk gao : > http://code.google.com/p/boogu/ > Enjoy it! > > > Hawk > From robert.kern at gmail.com Mon Mar 3 19:49:32 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Mar 2008 18:49:32 -0600 Subject: sympy: what's wrong with this picture? In-Reply-To: <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 4:53 pm, Carl Banks wrote: >> 3. You must be terribly naive if you expect a freeware program with a >> version number of 0.5.12 not to have bugs > > No, but I guess I'm naive thinking that when someone posts a link to > such a program that he's recommending going and trying it out. That > is why they're making it available, isn't it? For people to try out > so they can get free testing? Aren't I doing my part? Should I just > uninstall it and forget it? Finding the issue and reporting it to the sympy bug tracker is commendable. Coming here and "un-recommending" sympy before the issue was resolved is not. -- 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 nagle at animats.com Sun Mar 23 11:53:02 2008 From: nagle at animats.com (John Nagle) Date: Sun, 23 Mar 2008 08:53:02 -0700 Subject: Testing for an empty dictionary in Python Message-ID: <47e67a99$0$36364$742ec2ed@news.sonic.net> What's the cheapest way to test for an empty dictionary in Python? if len(dict.keys() > 0) : is expensive for large dictionaries, and makes loops O(N^2). John Nagle From sjmachin at lexicon.net Mon Mar 10 02:57:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Mar 2008 23:57:35 -0700 (PDT) Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: On Mar 10, 3:26 pm, DanielJohnson wrote: > Hi, > > I am trying to solve a genetic algorithm problem where I want to read > a bitvector of very large size (say 10000) and manipulate bits based > on certain algorithms. > > I am a newbie in Python. What data structure are good to read such > huge data set. Are there any built in classes for bit fiddling. > Bitwise operations like & | ^ << >> etc work on long integers. This happens at C speed. An alternative (in pure Python) is found via: http://pypi.python.org/pypi/BitVector HTH, John From duncan.booth at invalid.invalid Fri Mar 21 07:35:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Mar 2008 11:35:00 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> <13u5qbjq707as9e@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > I think you're confused. Or possibly I'm confused. Or both. I think it is you, but then I could be wrong. > It seems to me that you're assuming that the OP has opened the file > for reading first, and *then* another process comes along and wants to > open it for writing. That's not how I read his post: he's trying to > open a file for reading while it is already being written to by > another process. Asking for exclusive access when reading isn't going > to make any difference, because the other process has already opened > the file for writing. I'm assuming the other process has already opened the file for writing. In that case either it has asked for exclusive access so any attempt to open it for reading will fail, or it hasn't in which case Python's default 'open' will succeed but opening it for exclusive access will fail. Asking for exclusive access when opening will fail if another process already has the file open for reading or writing. > I suppose it is conceivable that the other process might have opened > the file for non-exclusive writing, assuming that such a thing is even > possible, but how likely is that? The usual situation is that the file is opened for writing but permits reading while it is being written. Then opening it to read will succeed unless you ask for exclusive access. BTW, I did test the 'CreateFile' code I posted: I opened the file for writing in one Python interpreter, just using open('...', 'w') wrote to it, and called flush but didn't close it. Then in another interpreter I checked that the CreateFile call threw an exception but open('...', 'r') succeeded and I was able to read what had been written. After I closed the file in the original interpreter the CreateFile call completed successfully. Try this: Session 1: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('test.txt', 'w') >>> f.write('Hello') >>> f.flush() >>> # go to session 2 ... >>> f.close() >>> f = open('test.txt', 'r') >>> # go to session 2 ... >>> f.close() >>> # go to session 2 ... >>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32file >>> handle = win32file.CreateFile("test.txt", win32file.GENERIC_READ, 0,None,win32file.OPEN_ALWAYS,win32file.FILE_ATTRIBUTE_NORMAL,None) Traceback (most recent call last): File "", line 1, in pywintypes.error: (32, 'CreateFile', 'The process cannot access the file because it is being used by another process.') >>> f = open('test.txt', 'r') >>> f.read() 'Hello' >>> f.close() >>> # go back to first session ... >>> handle = win32file.CreateFile("test.txt", win32file.GENERIC_READ, 0,None,win32file.OPEN_ALWAYS,win32file.FILE_ATTRIBUTE_NORMAL,None) Traceback (most recent call last): File "", line 1, in pywintypes.error: (32, 'CreateFile', 'The process cannot access the file because it is being used by another process.') >>> # go back to first session ... >>> handle = win32file.CreateFile("test.txt", win32file.GENERIC_READ, 0,None,win32file.OPEN_ALWAYS,win32file.FILE_ATTRIBUTE_NORMAL,None) >>> File open for writing in session 1: CreateFile throws an exception, open succeeds. File open for reading in session 1: CreateFile still throws an exception. File closed in session 1: CreateFile succeeds. From gandalf at shopzeus.com Tue Mar 11 10:59:36 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 11 Mar 2008 15:59:36 +0100 Subject: ZSI and attachments Message-ID: <47D69E58.5050306@shopzeus.com> Hi All, I wonder if the newest ZSI has support for attachments? Last time I checked (about a year ago) this feature was missing. I desperately need it. Alternatively, is there any other SOAP lib for python that can handle attachments? Thanks, Laszlo From martin at v.loewis.de Sat Mar 8 11:44:12 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 08 Mar 2008 17:44:12 +0100 Subject: List as FIFO in for loop In-Reply-To: References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <47D2C25C.9050400@v.loewis.de> > Still, why avoid changing loop variable? Does python treat looping > over a list differently from looping over an iterator, where it > doesn't know if the iterator future changes while loop running? Take a look at Objects/listobject.c:listiterobject. It contains an it_index, which is the index into the list of the current iterator position. So if you delete items with indices smaller than the iterator index, the iterator index won't change, causing the iterator to skip over elements, e.g. L=range(10) for i in L: print i del L[0] Appending to lists will cause the new elements to be iterated over later. Whether that's desirable or not depends on the application. E.g. the following loop never terminates L=range(10: for i in L: L.append(i) Notice that the language specification *deliberately* does not distinguish between deletion of earlier and later items, but makes modification of the sequence undefined behavior to allow alternative implementations. E.g. an implementation that would crash, erase your hard disk, or set your house in flames if you confront it with your code still might be a conforming Python implementation. Regards, Martin From bearophileHUGS at lycos.com Fri Mar 21 08:55:47 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 21 Mar 2008 05:55:47 -0700 (PDT) Subject: removing all instances of a certain value from a list References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> <93e8ab20-8dd5-47d3-b977-822329889b52@a70g2000hsh.googlegroups.com> Message-ID: r.gr... at science-computing.de: > >>> a=filter ( lambda b: b != None, a) With None it's better to use is/not is instead of ==/!= Bye, bearophile From usenet at solar-empire.de Tue Mar 4 14:33:15 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 4 Mar 2008 20:33:15 +0100 Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> Message-ID: jefm wrote: > How can I print the unicode box drawing characters in python: > > > print u'\u2500' > print u'\u2501' > print u'\u2502' > print u'\u2503' > print u'\u2504' > > Traceback (most recent call last): > File "\test.py", line 3, in ? > print u'\u2500' > File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500' > in position 0: character maps to On linux in an utf8 console, it works with 2ython 2.4.4 and 2.5.1. It looks like your python is using cp 1252 for output. Which does not contain the box drawing characters. I don't think using a different encoding would work (e.g. print u'\u2500'.encode('cp437'), or print u'\u2500'.encode('utf8')) Marc From carsten at uniqsys.com Sat Mar 8 12:18:00 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 08 Mar 2008 12:18:00 -0500 Subject: SQL problem in python In-Reply-To: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: <1204996680.3161.11.camel@localhost.localdomain> On Sat, 2008-03-08 at 08:57 -0800, aiwarrior wrote: > def get_value( self, column ): > self.cursor.execute( "SELECT (?) FROM database", column ) > for n in self.cursor: > print n > > When i run it the get_value() returns 'filepath' instead of the > columns. But if i dont use any variable and make the expression static > all goes on as its supposed to. What am i doing wrong? Using parameter binding wherever possible is a Good Idea, but parameter binding can only be used to provide values. It can not be used to provide syntax elements, table names, or column names. Basically, only pieces that don't influence the query plan can be provided by parameters. To build a select query with a variable column name, you'll have to resort to some kind of string building mechanism: def get_value( self, column ): self.cursor.execute( "SELECT %s FROM database" % column ) for n in self.cursor: print n HTH, -- Carsten Haese http://informixdb.sourceforge.net From larry.bates at websafe.com` Tue Mar 25 10:52:38 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 25 Mar 2008 09:52:38 -0500 Subject: Outlook 2003 and Python In-Reply-To: References: Message-ID: <2pidnTOUdc03jHTanZ2dnUVZ_uqvnZ2d@comcast.com> cuordileone wrote: > Good Day. > > I woul like to ask you if it is possible to make a program in python > that move the email messages that I had received in outlook 2003, to a > specific folder, accoding to the sender's name: > > Es: martin at martin.com -->> folder Martin. > > Thanks. > > Riccardo. You could, but it is much easier to just use built in tools (from Outlook help): Automatically move messages from a certain person Select a message from the person whose messages you want to automatically move. On the Tools menu, click Organize. In the second bulleted item, click the options you want. To choose a folder, click the arrow next to the Into list. Click Create. Note To create more complex rules for organizing items, you can also use the Rules and Alerts dialog box on the Tools menu. -Larry From pi.arctan at gmail.com Sat Mar 8 10:28:35 2008 From: pi.arctan at gmail.com (pi.arctan at gmail.com) Date: Sat, 8 Mar 2008 07:28:35 -0800 (PST) Subject: extract multiple ranges from a list Message-ID: Hi guys, One of my many project involves working with YUV-files, where I need to reduce the vertical resolution with a factor of two, i.e. remove every other scan line. Today I'm using two for-loops in the fashion shown below y = [] for i in range(0, width*height, width*2): for j in range(0,width): y.append(Y[i+j]) This approach doesn't feel very pythonic but I can't come up with a better idea to do it. I've tried list comprehension and map together with lambda but I can't get a flattened list of every other scan-line... CIF = 352x288 items for luminance and the aim is to have the list below: y = [0:352 704:1056 ... ] //Fredrik From Lie.1296 at gmail.com Sun Mar 9 13:45:33 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 10:45:33 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <13t7nfdmdtuf7be@corp.supernews.com> Message-ID: On Mar 9, 7:54?pm, Steven D'Aprano wrote: > On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote: > > (3) Informing codes above it about what's currently happening inside, > > the thing is just a mundane report that might be useful to codes above > > > Which might be a useful place to use SoftExceptions > > Okay, now we're getting somewhere. > > So, I have a function foo() which raises a HardException on error, but it > also raises a SoftException if it wants to notify me of something > "mundane". > > def foo(sequence): > ? ? if args == []: > ? ? ? ? raise SoftException("empty list") > ? ? return len(args) > > Now, how do I use that? > > try: > ? ?x = foo(something) > except TypeError: > ? ?print "you should pass a sequence" > ? ?sys.exit() ?# unrecoverable error > except SoftException: > ? ?print "you passed an empty list" > print x > > Am I close? > > But there's a problem. Once the SoftException is caught, execution will > continue from the line "print x" -- but the function foo() never got a > chance to actually return a result! In that particular case above, you don't need to handle the Soft Exception. As stated in it's original purpose, you don't need to handle a Soft Exception, it exists there if you need to handle the exceptional case, but ignorable on other cases. _IF_ printing the "you passed an empty list" is an important operation, you'd make it like this: try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" x = 0 print x or alternatively: try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" else: print x The case you states above only mentions that you haven't fully grasped the workflow in exception-based system. > In order to make that work, you would need a significant change to > Python's internals. I don't know how difficult that would be, but I'm > guess that it would be a lot of work for not much benefit. I too don't know how difficult that'd be, especially because the only thing I know about Python's internal is it implements its garbage collector by ref counting (which is barely useful here). > But even if that happened, it would mean that the one mechanism has TWO > different effects: > > try: > ? ? x = foo(sequence) > except SoftException: > ? ? print x ?# this is okay, because foo() did return > except TypeError: > ? ? print x ?# this is NOT okay, because foo() never returned > > That is a recipe for confusion. Both are not okay since foo() never return on both cases (soft statement doesn't return to finish the try clause except if explicitly resumed). (snip) > > Perhaps relabeling it as Warning, and renaming raise SoftException as > > give Warning might make it more acceptable? > > Do you realise that Python already has a warnings module? Ah... I completely forget about it, but anyway the Warning module is unrelated to this. Perhaps we could just think of another name, but names doesn't seems to be important in Python modules anyway, can you guess what pickle/zip/mutex/quopri/curses is if you're new to Python without looking at the documentations? There are some modules in Python that have weird names, we ought to reduce it, but we can't reduce it... we ought to live with it. (snip) > > A possible solution to this problem might be to check whether distance > > is less than P1.radius + P2.radius in the calculateforce. But, this > > obfuscate the code since we have to separate distance calculation from > > the main formula (see !s), > > I don't agree that this obfuscates the code. For a formula as complex as this: http://www.mapleprimes.com/blog/axel-vogt/computing-the-complex-gamma-function-using-spouges-formula it might be useful to fragment the formula to smaller pieces but in a simple to moderately complex that still fits in one line, fragmenting the code confuses the eye. > And here's a way to do it that doesn't calculate anything twice, and > doesn't require any exceptions: > > def calculateforce(P1, P2, dist): > ? ? return (P1.mass - P2.mass)/dist > > And then for all pairs of particles: > > dist = distance(P1, P2) > if dist <= P1.radius + P2.radius: > ? ? clump(P1, P2) > ? ? break > F = calculateforce(P1, P2, dist) That... is the worst solution that could ever be suggested. The Particle objects already contain their own position, supplying dist overrides their real distance of the particles and also it may make bug holes by supplying bogus distance: def calculateforce(P1, P2, dist): return (P1.mass - P2.mass) / dist calculateforce(P1, P2, 'bogus data') or simply by passing dist that isn't equal (P1.X - P2.X) ** 2 + (P1.Y - P2.Y) ** 2. If you want to do it that way, it'd be much better if you go fully functional: def calculateforce(P1_mass, P2_mass, dist): return (P1_mass * P2_mass) / dist ** 2 but it would be a pain in the neck to manually dismantle the P1.M, P2.M, dist every time you call the calculateforce. btw, on an unrelated note, the original formula I supplied for gravity calculation is incorrect, it should be (P1.M * P2.M) / dist ** 2 instead of (P1.M - P2.M) / dist, but that's just physics not python. > > A much better solution would be to use SoftException > > ? ? def distance(P1, P2): > > ? ? ? ? D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > ? ? ? ? if D <= P1.radius + P2.radius: > > ? ? ? ? ? ? raise Collision > > ? ? ? ? return D > > But look at that line, "raise Collision". You could replace that with a > callback function, and have the same result: > > ? ? DO_NOTHING = lambda : None > > ? ? def distance(P1, P2, callback=DO_NOTHING): > ? ? ? ? D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > ? ? ? ? if D <= P1.radius + P2.radius: > ? ? ? ? ? ? callback() > ? ? ? ? return D > > That gives you virtually everything you want. If you want to ignore the > signal, you simply call distance(P1, P2). If you want to do something on > the signal, you set the callback. Guess where it goes after the callback finishes? It goes to "return D". And if the calling code hasn't been notified that P1 and P2 has already been clumped by the callback, it'll refer to an inexistent object. Soft Exception don't do that, it terminates the distance calculation and goes to the handler and won't go back to finish distance calculation unless explicitly told to (by using resume). And another weakness, it'd be a pain in the neck to handle more than two or three separate callbacks. You can define as many Soft Exception as you want without cluttering the function's "interface" (please find a better diction for "interface") > But frankly, the function distance() is NOT the place for that. Why > should the distance() function decide what's a special result and what > isn't? With your plan, you end up with functions like this: (snip) Because when a calculation of distance is lower than the sum of their radius, it means the two objects shared the same space (!this is impossible but not problematic for calculations if ignored!), that would be an event of interest to codes that handles the movement, clumping, etc but codes that just wants to print the distance to screen wouldn't want to care about it. > Every module and function that calls distance() will start demanding that > it raises the SoftExceptions that *it* wants, and before you know it, > your distance() function has a hundred SoftExceptions covering all sorts > of things that most people don't care about. > > No. This is a terrible idea. If the caller wants to treat a particular > result as special, the caller should be responsible for detecting that, > not the callee. No the callee isn't responsible for detecting the exceptional result, the caller is responsible for handling the exceptional result, while the callee is responsible to notify the caller. In some cases it might be impossible for the caller code to determine the exceptional cases or probably the cost of doing so is nearly equal to the cost of doing the whole calculations (but completing the calculation would result in garbage out). (snip) Steven says: > Just out of curiosity, are there any existing languages that do something > like this, or did you invent it yourself? On Mar 9, 8:21 pm, "Diez B. Roggisch" wrote: (snip) > Is this soft-exception implemented anywhere, so that one can see what > experiences and best practices have evolved around using it? Actually I "invent" it myself (or probably I'm just ignorant enough not to know any), that's why I expect there'll be a lot of weaknesses I haven't foreseen (two heads are better than one, and a bunch of heads are better than two). And it is also the reason why I'm asking here for others' opinions, to bake the ideas, and possibly getting it implemented when it's baked enough or to have other's opinion on why it's bad and why it shouldn't exist. If there is a reason why I chose here particularly, it'll be because I think Python (AFAICS) have a lot of interesting features: list comprehension, generator functions, for-loop semantic, just to name a few of them (well, maybe it's not *that* unique to you, but coming from a VB background[1], such features are extremely unique to me) and I love them and use them heavily. Another reason might be that Python is a dynamic language that have adopted preference for try block compared to if block. And I think the idea fits well enough with Python's ideologies. Still another reason is because Python is not controlled by a Impotent Company For Life but only by a Benevolent Dictator For Life. Yet another reason is simply because Python is currently my active language. [1] Although since I picked Python, I've yet to touch VB again, I'm sure I'll still be Thinking In Python if I go back to do some VB. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 03:38:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 08:38:56 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> Message-ID: <13t4k50d7pg0d63@corp.supernews.com> On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote: >> x = get_stuff(store) # Get the stuff what was brought at the store. > > Perfect example of an unnecessary comment. The variable and function > names are commentary enough. "x" is a terrible name. What does it mean? Nothing. There's only three places x is an appropriate name: (1) A meta-syntactic variable like foo, bar, spam, ham, parrot. (2) Library functions, where x stands for a generic argument, usually a number, e.g. def sin(x). (3) Throw-away code you don't need to maintain. The function name also doesn't explain anything. How was the stuff got? Was it paid for, or stolen, or picked up on consignment, or what? Compare the above line with: x = get_stuff(store) # Steal stuff from the store. or x = get_stuff(store) # Pickup the stuff from the store for disposal. # The amount paid by the store is stored in global variable "pay_received" # and the name of the employee authorizing the pickup is stored in the # global "authorized_by". But even if you were right that the comment was unnecessary, you have missed my point that even single sentences can be grammatically bogus and the writer could learn a lot from Strunk and White or equivalent. (Often the writer will learn bad habits, but at least they'll be grammatically correct bad habits.) -- Steven From dickinsm at gmail.com Tue Mar 11 10:13:23 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 07:13:23 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> Message-ID: On Mar 10, 7:32?pm, Nathan Pinno wrote: > Thanks on the factoring bit, but I did mean factorial, not factoring. > How do I code that correctly, so that I can figure the following > equation out: cos(Pi * (z-1)! / z). Is z an integer in this expression? (Note: it's not an equation--- there's no equality sign.) This looks suspiciously like a formula that's supposed to be valid for real and possibly even complex z, in which case what you're after is the gamma function. (gamma(z) = (z-1)!). The real version of this should certainly be present in numpy/scipy, and possibly the complex version too. If z really is supposed to be an integer then you should be aware that evaluating the expression directly is going to give almost no accuracy, for z greater than 30 or so: the absolute error in the argument to cosine will likely be much larger than 2*pi, so that the result of the cos() evaluation is meaningless. You might be better off computing w = (factorial(z-1) % (2*z)) as an integer; then cos(pi*(z-1)!/z) can be computed as cos(pi * w/z). Also, there are algebraic simplifications possible. If z is an integer greater than 4, and not a prime number, then the value of your expression is always going to be 1. If z is a prime number then Wilson's theorem is going to come in handy. (Google "Wilson's theorem prime"). Where does the expression come from? Is z a real or an integer? Is this a genuine real-world formula, or something that appeared in an elementary number theory textbook? Mark From bcl at brianlane.com Sat Mar 22 14:53:13 2008 From: bcl at brianlane.com (Brian Lane) Date: Sat, 22 Mar 2008 11:53:13 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <47E55599.9000305@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Jeff Schwab wrote: > jmDesktop wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. > > Linux and Python are a nearly ideal combination for this. Be aware that > at some point, you will likely have to dig into C, the primary language > used to implement both Linux and Python. At that level I don't see why they would need to hit 'C' at all. Maybe some of the APIs, but not syntax at all. I would consider Python an ideal language for HS students to learn. The teacher who hosts our KPLUG meetings has had good luck using Python in her classes. Brian - -- - ---[Office 67.9F]--[Outside 49.1F]--[Server 104.7F]--[Coaster 67.1F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH5VWZIftj/pcSws0RAoouAJ45UaRYDxwjwNLC8KblaFfyEKz3kACfeeWV XREAe/+tjyYuTVZOrNtaObE= =9h+S -----END PGP SIGNATURE----- From davidbak at gmail.com Fri Mar 7 17:39:57 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 14:39:57 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> On Mar 7, 1:19?pm, "Chris Mellon" wrote: > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > ?However I can't do this, because, of course, the name Tree isn't > > ?available at the time that the classes _MT and _Node are defined, so > > ?_MT and _Node can't inherit from Tree. > > Not only is the name not defined, the class doesn't even exist yet. Yes, but, well - it certainly isn't usable yet, but some object (that will be the class when it is finished) is being built (its __dict__ is being populated, etc.) - so there's an object pointer available inside the interpreter that could be put somewhere. But this is pedantic - you're right, the class really isn't available until after the class statement. > > ?What is the Pythonic thing I should be doing instead? > > Don't nest them. The single underscore is all you need to keep any > from using them (don't forget that even if your method worked, they'd > be perfectly visible as attributes of the Tree class, or as the types > of returned values). Worrying too much about visibility is a waste of > time in Python. Yes, I knew it wouldn't stop the determined coder from finding and using them. However, I did actually have a reason for wanted them nested: I wanted to put more than one similar data structure in the same source file - and several of them would have "Empty" nodes that would behave differently. If I used nested classes all those classes could be named Empty. If flattened to module level then I'd have to invent different names for each one, like, AVL_Empty, RedBlack_Empty, and it wouldn't seem as "nice" (for some definition of "nice" that I have in my head). > > ?(Easy answer: ?Put this code in a module, exposing only a factory > > ?function. ?I could do that, but wanted to know if I could encapsulate > > ?it as described so I could actually put several similar data > > ?structures into one module.) > > There's no reason to use a factory function. If you do put them in a > module, you can use __all__ to document your exports. As with all > visibility issues in Python, this is advisory only - the only code it > affects is the symbols that are exported by "from module import *". OK. Thanks! -- David From jeff at schwabcenter.com Fri Mar 14 12:45:35 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 14 Mar 2008 09:45:35 -0700 Subject: Need Script For read multiple files(.txt) from a folder In-Reply-To: References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: Chris wrote: > On Mar 14, 8:36 am, Dennis Lee Bieber wrote: >> On Thu, 13 Mar 2008 21:28:18 -0700 (PDT), jai_python >> declaimed the following in comp.lang.python: >> >>> hi frenz I Need a Python Script For read multiple files(.txt) from a >>> folder and write it in a single text file.... >> If you are on windows, just open a command prompt and use the >> standard copy command... >> >> C:\Documents and Settings\Dennis Lee Bieber>copy /? ... > If you want to go that route you could also do: type *.txt > > output_file.txt On Unix, cygwin, etc: cat dir/*.txt > output.txt Or if you need "deep" copy: cat $(find dir -name '*.txt') > output.txt You could write a portable solution in Python (as in Martin Laloux's post), but most modern command-line environments have similar (but not identical) support for globbing and redirecting files. If you're getting the glob pattern from a user, they may expect subtly platform-dependent behaviors, in which case portability might not as important as native feel. From carsten.haese at gmail.com Sat Mar 29 21:45:37 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 29 Mar 2008 18:45:37 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> Message-ID: On Mar 29, 9:10 pm, Tim Roberts wrote: > aiwarrior wrote: > > def get_value( self, column ): > > self.cursor.execute( "SELECT %s FROM database" % column ) > > for n in self.cursor: > > print n > > I suspect you wanted "self.cursor.fetchall()" there, but since you don't > call it, it doesn't matter yet. sqlite3's cursor objects support the iteration protocol, so the for- loop does work without calling fetchall(). -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Wed Mar 26 20:49:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 21:49:18 -0300 Subject: subtract dates with time module References: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 20:47:45 -0300, barronmo escribi?: > I'm trying to get the difference in dates using the time module rather > than datetime because I need to use strptime() to convert a date and > then find out how many weeks and days until that date. I'm a beginner > so any help would be appreciated. Here is the code: > > def OBweeks(ptID): > qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % > (ptID) > results = EMR_utilities.getAllData(qry) > for items in results: > r = re.search('\d\d\d\d-\d\d-\d\d', items) > if r: > d = time.strptime(r.group(), "%Y-%m-%d') - > time.localtime() > weeks, days = divmod(d.days, 7) > return '%s %s/7 weeks' % (weeks, days) > > This isn't working. I'm getting "unsupported operand type for -: > 'time.struct_time' and 'time.struct_time" error. I don't see why you don't want to use datetime; it's the easiest way to compute the time difference. To obtain the date object dt from the database, you might use the following, based on your posted code: import datetime match = re.search('(\d\d\d\d)-(\d\d)-(\d\d)', items) if match: y, m, d = (int(x) for x in match.groups()) dt = datetime.date(y, m, d) Then, weeks and days are easily computed (similar to your own code): now = datetime.date.today() # evaluate once outside the loop delta = now - dt weeks, days = divmod(delta.days, 7) -- Gabriel Genellina From Robert.Bossy at jouy.inra.fr Wed Mar 12 04:49:26 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 12 Mar 2008 09:49:26 +0100 Subject: merging intervals repeatedly In-Reply-To: References: Message-ID: <47D79916.2050002@jouy.inra.fr> Magdoll wrote: > Hi, > > I have to read through a file that will give me a bunch of intervals. > My ultimate goal is to produce a final set of intervals such that not > two intervals overlap by more than N, where N is a predetermined > length. > > For example, I could read through this input: > (1,10), (3,15), (20,30),(29,40),(51,65),(62,100),(50,66) > > btw, the input is not guaranteed to be in any sorted order. > > say N = 5, so the final set should be > (1,15), (20, 30), (29, 40), (50, 100) > Hi, The problem, as stated here, may have several solutions. For instance the following set of intervals also satisfies the constraint: (1,15), (20,40), (50,100) One question you should ask yourself is: do you want all solutions? or just one? If you want just one, there's another question: which one? the one with the most intervals? any one? If you want all of them, then I suggest using prolog rather than python (I hope I won't be flamed for advocating another language here). > Is there already some existing code in Python that I can easily take > advantage of to produce this? Right now I've written my own simple > solution, which is just to maintain a list of the intervals. I can use > the Interval module, but it doesn't really affect much. I read one > interval from the input file at a time, and use bisect to insert it in > order. The problem comes with merging, which sometimes can be > cascading. > > ex: > read (51,65) ==> put (51,65) in list > read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) > read (50,66) ==> merge with (51,65) to become (50,66) ==> now can > merge with (62,100) The way this algorithm is presented suggests an additional constraint: you cannot merge two intervals if their overlap <= N. In that case, there is a single solution indeed... Nitpick: you cannot merge (50,66) and (62,100) since their overlap is still <= 5. If you have a reasonable number of intervals, you're algorithm seems fine. But it is O(n**2), so in the case you read a lot of intervals and you observe unsatisfying performances, you will have to store the intervals in a cleverer data structure, see one of these: http://en.wikipedia.org/wiki/Interval_tree http://en.wikipedia.org/wiki/Segment_tree Cheers, RB From andreas.axelsson at gmail.com Sun Mar 30 11:04:10 2008 From: andreas.axelsson at gmail.com (axl) Date: Sun, 30 Mar 2008 08:04:10 -0700 (PDT) Subject: Build complete, now I just need to "install" it... Message-ID: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Hi, I'm going to be adding some features for a python-project with external modules written in C. However, if I build modules with my MSVS 2008 compiler (from the Windows SDK), they won't load in Python 2.5.2, which is built with MSVS 2003. Since I don't have access to MSVS 2003 I need to rebuild Python using MSVS 2008 in order for the binaries to go along. For starters, I cloned the PCbuild8 folder and made whatever changes needed to be able to build the core and executable. I then pulled down all the various external dependencies and made the same adjustments to those. After quite a while I've managed to build everything apart from the PGO config, since it requires a DLL which isn't included in the SDK. Not to worry, I can live with a less than 100% optimized version for now. But, my problem is that the install scripts, i.e. "python setup.py install" wants to go through the build steps again, but since those don't work on Windows, or at least not with my setup, I can't put together a complete package. The web pages have gotten me this far, but there doesn't seem to be anything on how to actually pull together the various bits and bobs into a complete package that I can use in place of my current Python 2.5.2 installation. Apparently someone has done it, since there is an installer to download, but those parts don't seem to be available anywhere. And it's unclear if the Windows installer contains exactly what's in the source package, or if I have to build a bunch of other modules as well in order to be completely replacing my old installation. Actually, I don't need an installer, I just want to know which parts of my 2.5.2 folder that need to go where. Grateful for any help, /axl From mail at timgolden.me.uk Tue Mar 25 07:13:15 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Mar 2008 11:13:15 +0000 Subject: My python interpreter became mad ! In-Reply-To: <47E8DC95.4010009@cines.fr> References: <47E8DC95.4010009@cines.fr> Message-ID: <47E8DE4B.7040307@timgolden.me.uk> Benjamin Watine wrote: > Yes, my python interpreter seems to became mad ; or may be it's me ! :) > > I'm trying to use re module to match text with regular expression. In a > first time, all works right. But since yesterday, I have a very strange > behaviour : > > $ python2.4 > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > X-Spam-Flag: YES > X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org > X-Spam-Level: ********************** > X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, > MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, > > RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, > > URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, > URIBL_WS_SURBL autolearn=failed version=3.1.7-deb > > Traceback (most recent call last): > File "", line 1, in ? > File "/etc/postfix/re.py", line 19, in ? > m = re.match('(Spam)', mail) > AttributeError: 'module' object has no attribute 'match' > >>> Extremely likely that, in the course of testing some re technique, you've created a module in this directory called "re.py". When you import re, you're actually importing your own module. TJG From michael.wieher at gmail.com Mon Mar 10 12:06:07 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 10 Mar 2008 11:06:07 -0500 Subject: BitVector read-from-file Question Message-ID: I'm trying to read in data from large binary files using BitVector (thanks btw, for whoever mentioned it on the list, its nice) I'll be reading the data in as requested by the user, in (relatively) small chunks as needed. Problem is I can't read the whole file in at once (its ridiculously large) and the object created by BitVector(filename="path") doesn't include a "seek" function (to reset the filepointer) Any suggestions on how to this without closing/reopening/reading(offset)/read(data) ? (thats a lot of overhead) -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Mon Mar 17 23:58:24 2008 From: http (Paul Rubin) Date: 17 Mar 2008 20:58:24 -0700 Subject: ord function problem from newbie References: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> Message-ID: <7xeja8el9b.fsf@ruckus.brouhaha.com> David.J.Anderson66 at gmail.com writes: > for ch in small: > v = ord(ch)-96 > print v total = 0 for ch in small: # the += below updates the value of total by adding (ord(ch) - 96) total += (ord(ch) - 96) print "ch:", ch, "total so far:", total From gagsl-py2 at yahoo.com.ar Thu Mar 27 05:20:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 06:20:53 -0300 Subject: Partial Function Application and implicit self problem References: <65144bF2dp2abU1@mid.uni-berlin.de> <47EB5D7E.7080109@mydeskfriend.com> Message-ID: En Thu, 27 Mar 2008 05:40:30 -0300, Gabriel Rossetti escribi?: >>> if(atomic): >>> # Lock the service dict and register the service, then unlock it >>> self.__mutex.lock(reg, service) >>> self.__mutex.unlock() I see that you've already solved your original problem. But looking at those names, I wonder if you're using the mutex module; note that such "mutex" is absolutely useless in a multithreaded program, it doesn't guarantee mutual exclusion, the "atomic" testandset operation isn't atomic at all, by example. For a "real" mutex, use a threading.Lock object. -- Gabriel Genellina From castironpi at gmail.com Fri Mar 21 07:59:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 04:59:19 -0700 (PDT) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 9, 6:44?pm, castiro... at gmail.com wrote: > On Mar 2, 1:18?pm, castiro... at gmail.com wrote: > > > On Mar 2, 12:01?pm, John DeRosa wrote: > > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > > >Hi, > > > > >Have you ever seen Beautiful Python code? > > > >Zope? Django? Python standard lib? or else? > > > > >Please tell me what code you think it's stunning. > > > > Just about any Python code I look at. > > > Decorators, with, and namedtuple. > > Oh yeah, and variable arguments and keyword > dictionaries. If you're C++, garbage collection. How's the cycle detector? The pages and pages get pretty specific. From steve at holdenweb.com Sun Mar 30 21:18:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 21:18:51 -0400 Subject: Odd behaviour with list comprehension In-Reply-To: <871w6vkq3z.fsf@micah.cowan.name> References: <4fbfbb8f0802291901s5ed7e0b4ua3e77ad46aa53bb7@mail.gmail.com> <871w6vkq3z.fsf@micah.cowan.name> Message-ID: Micah Cowan wrote: > "Jerry Hill" writes: > >> On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu wrote: >>> Is there a way for me keep the iterating variable in list >>> comprehension local to the list comprehension? >> Kind of. You can use a generator expression instead of a list >> comprehension, and those don't leak their internal variables into the >> enclosing scope: > > Whoa, that's cool. I didn't even think to try that, just assuming it > would do the same. > > Though now that I think about it, I don't see how it possibly could, > since it just evaluates to an object that you could pass around, and > return, using it the same way elsewhere. > Well, the fact that the bound variable in the list comprehension does indeed remain outside the construct is simply the result of an over-zealous wish to emulate for loop semantics. The original reasoning, IIRC, as that since a for loop left its bound variable at the last used value, so should a list comprehension. This was quickly recognized as a mistake, but unfortunately not quickly enough. As it was felt that some people might already have relied on that behavior, it was retained in the interests of preserving backwards compatibility. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dickinsm at gmail.com Fri Mar 7 19:12:34 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 7 Mar 2008 16:12:34 -0800 (PST) Subject: float / rounding question References: Message-ID: On Mar 7, 5:12?pm, Piet van Oostrum wrote: > Python just uses the C library for printing, I presume, and the conversion > routines in the C library are rather simplistic. It is, however, possible > to do better, so that 53.6 -- although internally represented as something > that could be described as 53.600000000000001 -- will actually be printed > as 53.6. There are issues with doing this portably and reliably. See http://bugs.python.org/issue1580 for a recent discussion. Mark From asmodai at in-nomine.org Mon Mar 31 06:39:16 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 31 Mar 2008 12:39:16 +0200 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <20080331103916.GF80617@nexus.in-nomine.org> -On [20080331 12:29], Pradeep Rai (pradiprai at gmail.com) wrote: >I have upgraded python v2.5.2 from python v2.4.3. The upgradation results into >following error: >"Python C API version mismatch for module dbi: This Python has API version >1013, module dbi has version 1012." Did you copy everything from site-packages of the old one to the new one? -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ If you're afraid of dyin', then you're holding on. You see devils tearing your life away. But if you have made your peace, then the devils are really angels, freeing you from the earth... From duncan.booth at invalid.invalid Wed Mar 19 08:34:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 12:34:34 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > This whole approach > assumes that Windows does the sensible thing of returning a unique error > code when you try to open a file for reading that is already open for > writing. > So how would you use a file to share data then? By default Python on Windows allows you to open a file for reading unless you specify a sharing mode which prevents it: the easiest way is probably to call win32file.CreateFile with appropriate parameters. In one window: >>> f = open('SHARE.txt', 'w') >>> f.write('hello') >>> f.flush() >>> and then while that other window is open: >>> handle = win32file.CreateFile("SHARE.txt", ... win32file.GENERIC_WRITE, ... 0, # i.e. "not shared" is the default ... None, ... win32file.OPEN_ALWAYS, ... win32file.FILE_ATTRIBUTE_NORMAL, ... None) Traceback (most recent call last): File "", line 7, in pywintypes.error: (32, 'CreateFile', 'The process cannot access the file because it is being used by another process.') >>> f = open("SHARE.txt", "r") >>> f.read() 'hello' The CreateFile call was copied from http://mail.python.org/pipermail/python-list/2002-January/122462.html From darcy at druid.net Mon Mar 31 11:51:46 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 31 Mar 2008 11:51:46 -0400 Subject: Creating Class Objects in Loop In-Reply-To: <47f0673e$0$36321$742ec2ed@news.sonic.net> References: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> <47f0673e$0$36321$742ec2ed@news.sonic.net> Message-ID: <20080331115146.54ec39ee.darcy@druid.net> On Sun, 30 Mar 2008 21:34:00 -0700 John Nagle wrote: > What's actually happening to you is that you've run into one of the > dumber features of Python - default values for parameters which are > mutable, like lists, result in rather unexpected behavior. The > problem is that > > def __init__(self, pcap = None, sids = []): I have never liked using that form for different reasons so I never tripped over that. Now I have another reason to avoid it. It's not a huge deal to do this. def __init__(self, pcap = None, sids = None): if sids is None: sids = [] -- 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 ptmcg at austin.rr.com Sun Mar 2 20:53:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 Mar 2008 17:53:54 -0800 (PST) Subject: Altering imported modules References: <200803011856.27611.troworld@gmail.com> Message-ID: <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> On Mar 2, 3:48?pm, Tro wrote: > On Sunday 02 March 2008, Terry Reedy wrote: > > > > > > > "Tro" wrote in message > >news:200803011856.27611.troworld at gmail.com... > > > | Hi, list. > > | > > | I've got a simple asyncore-based server. However, I've modified the > > > asyncore > > > | module to allow me to watch functions as well as sockets. The modified > > | asyncore module is in a specific location in my project and is imported > > > as > > > | usual from my classes. > > | > > | Now I'd like to use the tlslite library, which includes an asyncore mixin > > | class. However, tlslite imports "asyncore", which doesn't include my own > > | modifications. > > | > > | I'd like to know if it's possible to make tlslite load *my* asyncore > > > module > > > | without changing any of the tlslite code. > > > If your module is also 'asyncore' and comes earlier in the search path, I > > would expect the import to get yours. > > It's not. It has a package prefix like my.package.asyncore. I think I can > either move my version of asyncore up a couple of levels or add the > my.package directory to sys.path. > > My version of asyncore imports several functions from the built-in asyncore. > Now that my version of it is imported as asyncore, how would it import the > built-in version from python2.5/site-packages? > > Thanks, > Tro- Hide quoted text - > > - Show quoted text - What happens if you do "import my.package.asyncore as asyncore"? If that doesn't work (trying the simplest hack first), I know that there are various hooks in the import mechanism that should help. -- Paul From martin at v.loewis.de Mon Mar 3 01:48:28 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2008 07:48:28 +0100 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: <47CB9F3C.9030202@v.loewis.de> >> But it would be really nice if the configure fix for 2.5 was >> backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped >> system builds for 2.4 going direct from 2.3 -> 2.5. > > > Yes, it would be very nice if this worked out of the box on Mac OS X > 10.5.2. It's definitely a surprise for those of us who built our 2.4.4 > on Mac OS X 10.4.x. I can put a notice in the release notes, but I definitely won't change it to work out of the box. If 2.4.4 compiled out of the box on this box, it would have been a regression and would have to be fixed. IIUC, 2.4.4 won't compile on 10.5, either, and Python 2.4.5 will have no code to port it to new platforms. Regards, Martin From devnew at gmail.com Mon Mar 17 01:04:16 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Sun, 16 Mar 2008 22:04:16 -0700 (PDT) Subject: finding euclidean distance,better code? Message-ID: hello while trying to write a function that processes some numpy arrays and calculate euclidean distance ,i ended up with this code (though i used numpy ,i believe my problem has more to do with python coding style..so am posting it here) ... # i am using these numpy.ndarrays to do the calculation facespace # of shape(totalimgs,imgpixels) weights # of shape(totalimgs,selectedfacespaces) input_wk # of shape(selectedfacespaces,) distance # of shape(selectedfacespaces,) initally all 0.0 's mindistance #of shape(selectedfacespaces,) initally all 0.0 's ... ... #here is the calculations part for image in range(numimgs): distance = abs(input_wk - weights[image, :]) if image==0: #copy from distance to mindistance mindistance=distance.copy() if sum(mindistance) > sum(distance): imgindex=image mindistance=distance.copy() if max(mindistance) > 0.0: #normalise mindistance mindistance=mindistance/(max(mindistance)+1) dist=sum(mindistance) this gets me the euclidean distance value.I want to know if the way i coded it can be improved,made more compact....if someone can give suggestions it will be a great help . thanks D From kuaile9834 at 126.com Tue Mar 25 03:42:56 2008 From: kuaile9834 at 126.com (kuaile9834 at 126.com) Date: Tue, 25 Mar 2008 00:42:56 -0700 (PDT) Subject: cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) Message-ID: <527d4a7f-086e-4008-915b-3755e751fc5f@e10g2000prf.googlegroups.com> cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com )cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) From haraldarminmassa at gmail.com Mon Mar 17 14:28:34 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Mon, 17 Mar 2008 11:28:34 -0700 (PDT) Subject: how long do the different python-vm bytecodes take? Message-ID: <0555ed9f-c5f1-4d0b-afbd-439c863e9439@s13g2000prd.googlegroups.com> I looked at the virtual machine bytecode of python programs: def f(whatever): text="Hallo"+whatever return text import dis dis.dis(f) 2 0 LOAD_CONST 1 ('Hallo') 3 LOAD_FAST 0 (whatever) 6 BINARY_ADD 7 STORE_FAST 1 (text) 3 10 LOAD_FAST 1 (text) 13 RETURN_VALUE and now I am curious: how long does one LOAD_FAST take? I am thinking of something like back in the assembler-world, where there existed tables like: LDA -> 2 cycles BNE -> 2 cycles, 3 on branch of course, the "real time" is dependand on many factors, esp. the speed of the processor. But ... is there a relative scale somewhere? Somehting like LOAD_CONST 1 arbitraryUnit LOAD_FAST 1.9 arbitraryUnits RETURN_VALUE 8.0 arbitraryUnits ??? my Google queries did not reveal anything usefull so far. Any hints? From Wayne.Oosthuizen at gmail.com Fri Mar 28 11:01:01 2008 From: Wayne.Oosthuizen at gmail.com (Constantly Distracted) Date: Fri, 28 Mar 2008 08:01:01 -0700 (PDT) Subject: Setting the value of one cell in QTableWidget fills everything. Message-ID: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> I've just started PyQt programming and I've run into this little problem. When I set the text of one cell in my table, all the other cells fill with that value. All I wanted to do was run a loop, printing in each cell the row and column number. Here's the code. ------------------------------ from PyQt4 import QtGui,QtCore import sys class mywindow(QtGui.QWidget): def __init__(self,parent=None): QtGui.QWidget.__init__(self,parent) self.resize(700,700) self.mytable=QtGui.QTableWidget(7,6,self) self.mytable.resize(700,700) def filltable(self): items=QtGui.QTableWidgetItem() for column in range(self.mytable.columnCount()): for row in range(self.mytable.rowCount()): items.setText("row: " + str(row) + " column: " + str(column)) self.mytable.setItem(row,column,items) app=QtGui.QApplication(sys.argv) mainwin=mywindow() mainwin.filltable() qb.show() app.exec_() From bogus@does.not.exist.com Thu Mar 13 23:37:00 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 22:37:00 -0500 Subject: sorting question References: Message-ID: Seems 'KEYBOARDS' works nicely -- -- Andrew "jcnbp8k" wrote in message news:mailman.1941.1205461453.9267.python-list at python.org... > > Hi Patty, > > That's easy solved, the word is keyboards. > > I just did a google search for 'anagram solver' and got lucky with Andy's > free online anagram solver at http://www.ssynth.co.uk/~gay/anagram.html > :) > > I know it's not a python script, though are you actually working on a > python > program to de-scramble words yourself or did you just want the answer? > > Hope that helps. > > Cheers, > > Joe > http://www.neosource.com.au www.neosource.com.au - Practical Software > Solutions > > > Patty Sutcliffe wrote: >> >> The website you list regarding 9-letter scrambled words doesn't exist any >> longer. Is there another way that I can access it to see your program >> you >> designed? I have a nine letter work I need to unscramble. I will send >> it >> just in case you can figure it out for me and let me know. >> >> KAEOSYBRD >> >> I'm not very good at that sort of thing, but would love to know the >> answer >> to this one. >> >> Thank you, >> Patty >> patty206 at charter.net >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- > View this message in context: > http://www.nabble.com/sorting-question-tp16041301p16043041.html > Sent from the Python - python-list mailing list archive at Nabble.com. > From george.sakkis at gmail.com Sun Mar 23 11:39:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 08:39:53 -0700 (PDT) Subject: Duplicating list of lists [newbie] References: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Message-ID: On Mar 23, 11:34 am, yat... at gmail.com wrote: > Hi there. > I felt like I already know my toys around but it looks that I'm still > newbie on some points. > > So here goes problem: > > Lets say that we have list to copy: > > a = [1,2,3] > b = a[:] > a[0] = 5 > > a > > > [5,2,3] > b > >[1,2,3] > > So far so good > > But... let's say that "a" also contains lists: > > a = [1,2,[5,6,7]] > b = a[:] > > a[0] = 55 > a > > > [55,2,[5,6,7]] > b > > [1,2,[5,6,7]] > > Looks OK but... > > a[2][0] = 99 > a > > > [55,2,[99,6,7]] > b > > [1,2,[99,6,7]] > > So - it looks that in list "b" there copy of all objects from list "a" > including not copy of list [5,6,7] but reference to it. Right; that's what it's called a "shallow copy". > Is there simple way to copy a into b (like a[:]) with all copies of > all objects going as deep as possible? Yes, there is: from copy import deepcopy b = deepcopy(a) HTH, George From musiccomposition at gmail.com Sun Mar 16 21:30:54 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 16 Mar 2008 18:30:54 -0700 (PDT) Subject: Using threads in python is safe ? References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Message-ID: On Mar 16, 3:40 pm, "Gabriel Genellina" wrote: > En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade > escribi?: > > > I want to use therads in my application. Going through the docs , I read > > about GIL. > > Now I am confused whether using threads in python is safe or not. > > > One thing I know that if I am accessing global variables in two or more > > threads I need to synchronize them > > using locking or such mechanism so that only one thread access them at a > > time. > > Yes, altough some operations are known to be atomic so you don't need a > lock in that cases. I think there is a list in the wiki somewhere http://wiki.python.org/moinor perhaps at the effbot's site http://www.effbot.org Even for atomic operations, you should lock, though. That is not consistent over different Python implementations and is not always going to be in same in CPython. > > > 1. In order to support multi-threaded Python programs, there's a global > > lock that must be held > > by the current thread before it can safely access Python objects. > > Does this lock need to be held by python application script expliciltly > > before accessing any python object or > > interpreter takes acre of it ? > > No, the interpreter takes care of it. The GIL is a concern for those > writing extensions using the Python API. > > > 2. Does multithreaded python script need to held lock before calling any > > blocking I/O call? > > Or one should not worry about GIL while using python threads if job to be > > processed by thread does not call > > any global variables and thread unsafe Python/C extension ? > > Python code should not worry about the GIL. The problem would be, a > callback written in Python for a not-thread-aware extension that had > released the GIL. > > -- > Gabriel Genellina From tjreedy at udel.edu Wed Mar 19 17:51:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2008 17:51:41 -0400 Subject: is hash map data structure available in Python? References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> <87a293ab-c4f1-4dfc-97b7-efb10bb42e6b@e6g2000prf.googlegroups.com> Message-ID: "sturlamolden" wrote in message news:87a293ab-c4f1-4dfc-97b7-efb10bb42e6b at e6g2000prf.googlegroups.com... | On 19 Mar, 09:40, grbgooglefan wrote: | | > How do I create hash map in Python? | | Python dictionaries are the fastest hash maps known to man. If you only have keys (the names) and no values attached to them, then use a set. From has.temp3 at virgin.net Thu Mar 20 08:08:10 2008 From: has.temp3 at virgin.net (has) Date: Thu, 20 Mar 2008 05:08:10 -0700 (PDT) Subject: Calling Mac programs from Python instead of from AppleScript References: <47E1733E.5060902@codebykevin.com> Message-ID: <18a24a70-73ab-453b-9e6d-6a820a560703@u10g2000prn.googlegroups.com> On 19 Mar, 20:10, Kevin Walzer wrote: > Take a look at appscript: > > http://appscript.sourceforge.net/ Also, once appscript is installed, don't forget to import it before use: from appscript import * app('Maya').execute('sphere') HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From mnordhoff at mattnordhoff.com Mon Mar 10 05:35:29 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 09:35:29 +0000 Subject: is operator In-Reply-To: <004801c881f2$a04081f0$0b020b0a@nb1011> References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <47D500E1.1050107@mattnordhoff.com> Metal Zong wrote: > The operator is and is not test for object identity: x is y is true if > and only if x and y are the same objects. > >>>> x = 1 >>>> y = 1 >>>> x is y > True > > Is this right? Why? Thanks. I believe Python automatically creates and caches int objects for 0-256, so whenever you use them, they refer to the same exact objects. Since ints are immutable, it doesn't matter. -- From Dodin.Roman at gmail.com Mon Mar 17 09:08:43 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 06:08:43 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Message-ID: <49cfccae-9992-4d3f-a8b1-86536adbca53@e6g2000prf.googlegroups.com> On 17 ???, 15:48, "Gabriel Genellina" wrote: > En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > > > i have a problem with this modules py2exe + pywinauto + sendkeys used > > together. > > > In my script i'm using this expression > > app.window_(title="SJphone").Edit.TypeKeys("Test is > > running",with_spaces=True) > > > TypeKeys is using SendKeys module i suppose. > > Does it work as a normal script, without using py2exe? > > > my setup.py looks like that: > > > from distutils.core import setup > > import py2exe > > > setup( > > options = {"py2exe": {"compressed": 1, > > "optimize": 0, > > "bundle_files": 1, > > "packages": ["encodings", "pywinauto", > > "pywinauto.controls", "pywinauto.tests"] } }, > > zipfile = None, > > console=["hosts.py"] > > ) > > Perhaps you have to include SendKeys explicitely. I think pywinauto > doesn't require SendKeys, but uses it if already installed. > > -- > Gabriel Genellina i tried this: "packages": ["encodings", "pywinauto", "SendKeys", "pywinauto.controls", "pywinauto.tests"] But there was an error too( From inq1ltd at inqvista.com Fri Mar 14 10:48:39 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 14 Mar 2008 10:48:39 -0400 Subject: escape string to store in a database? In-Reply-To: <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> Message-ID: <200803141048.39381.inq1ltd@inqvista.com> > > -- > > Carsten > > Haesehttp://informixdb.sourceforge.net > > Thanks for the reply, Carsten, how would > this work with UPDATE command? I get this > error: > > cmd = "UPDATE items SET content = > ? WHERE id=%d" % id try this; ("update items set contents = (?) where id =(?)", [ x, y] ) put your data in a list or ("update items set contents = (?) where id =%d ", [ x] ) below statement "uses 1" refers to the one (?) , 0 supplied, means no list or none in list. jim-on-linux http://www.inqvista.com > > self.cursor.execute(cmd, content) > pysqlite2.dbapi2.ProgrammingError: > Incorrect number of bindings supplied. The > c > rrent statement uses 1, and there are 0 > supplied. > > Sqlite site doesn't give any details on > using parameter bindings in UPDATE > command, I'm > going to look around some more.. -ak From hacker.stevenson at gmail.com Thu Mar 27 15:45:52 2008 From: hacker.stevenson at gmail.com (breal) Date: Thu, 27 Mar 2008 12:45:52 -0700 (PDT) Subject: Determine size of string in bytes Message-ID: Forgive me for this question which is most likely stupid... How do I determine the number of bytes a string takes up? I have a soap server that is returning a serialized string. It seems that when the string goes over 65978 characters it does not return to the soap client. Instead I get an error: error: (35, 'Resource temporarily unavailable') This makes me think the problem exists on the soap client side with some sort of max return length. If I knew how many bytes the 65978 character string was, then I could try to up this value. Thanks. From __peter__ at web.de Thu Mar 13 07:06:33 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Mar 2008 12:06:33 +0100 Subject: What's Going On? References: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > (Accompanied by Marvin Gaye) > >>>> def f(list=[0]): > ... list[0]+=1 > ... return list[0] > ... >>>> f() > 1 >>>> f() > 2 >>>> f() # 'list' is a name bound to a list (mutable) so this makes sense > 3 >>>> f([5]) > 6 >>>>f() # What's Going On? > 4 http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm You heard it through the grapevine ;) Peter From stanc at al.com.au Wed Mar 26 23:34:20 2008 From: stanc at al.com.au (Astan Chee) Date: Thu, 27 Mar 2008 14:34:20 +1100 Subject: copy file over LAN Message-ID: <47EB15BC.3060505@al.com.au> Hi, I have a file on another machine on the local network (my machine and local machines are on windows) and I want to copy it locally. Now the machine requires authentication and when I try to do a import shutil shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') and it gives me a IOError: [Errno 13] Permission denied: error, which I expect. How do I provide authentication to copy this file? Thanks for the help. Cheers Astan -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From coolman.guron at gmail.com Thu Mar 6 11:34:27 2008 From: coolman.guron at gmail.com (coolman.guron at gmail.com) Date: Thu, 6 Mar 2008 08:34:27 -0800 (PST) Subject: help on file storage for split multi part download Message-ID: HI everyone on this group! i am want to write a split part downloading software for use in some projects. (something like a download accelerator) what i think i need is ( my brain is totally exausted at this moment so pls ignore any typos i make) storage class which can write the file splits that are currently being downloaded to the disk. this is exactly what other download accelerators do, i guess. can this be done using the python file class?? i am pretty good at handling file uploads (at server end) this is the first time i have to think the other way round. any code samples would be greatly appreciated. thanks binary-j django web developer From Robert.Bossy at jouy.inra.fr Thu Mar 13 03:54:56 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 13 Mar 2008 08:54:56 +0100 Subject: Creating a file with $SIZE In-Reply-To: <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> Message-ID: <47D8DDD0.6040104@jouy.inra.fr> cokofreedom at gmail.com wrote: > On Mar 12, 2:44 pm, Robert Bossy wrote: > >> Matt Nordhoff wrote: >> >>> Robert Bossy wrote: >>> >>>> k.i.n.g. wrote: >>>> >>>>> I think I am not clear with my question, I am sorry. Here goes the >>>>> exact requirement. >>>>> >>>>> We use dd command in Linux to create a file with of required size. In >>>>> similar way, on windows I would like to use python to take the size of >>>>> the file( 50MB, 1GB ) as input from user and create a uncompressed >>>>> file of the size given by the user. >>>>> >>>>> ex: If user input is 50M, script should create 50Mb of blank or empty >>>>> file >>>>> >>>> def make_blank_file(path, size): >>>> f = open(path, 'w') >>>> f.seek(size - 1) >>>> f.write('\0') >>>> f.close() >>>> >>>> I'm not sure the f.seek() trick will work on all platforms, so you can: >>>> >>>> def make_blank_file(path, size): >>>> f = open(path, 'w') >>>> f.write('\0' * size) >>>> f.close() >>>> >>> I point out that a 1 GB string is probably not a good idea. >>> >>> def make_blank_file(path, size): >>> chunksize = 10485760 # 10 MB >>> chunk = '\0' * chunksize >>> left = size >>> fh = open(path, 'wb') >>> while left > chunksize: >>> fh.write(chunk) >>> left -= chunksize >>> if left > 0: >>> fh.write('\0' * left) >>> fh.close() >>> >> Indeed! Maybe the best choice for chunksize would be the file's buffer >> size... I won't search the doc how to get the file's buffer size because >> I'm too cool to use that function and prefer the seek() option since >> it's lighning fast regardless the size of the file and it takes near to >> zero memory. >> >> Cheers, >> RB >> > > But what platforms does it work on / not work on? > Posix. It's been ages since I touched Windows, so I don't know if XP and Vista are posix or not. Though, as Marco Mariani mentioned, this may create a fragmented file. It may or may not be an hindrance depending on what you want to do with it, but the circumstances in which this is a problem are quite rare. RB From tdelaney at avaya.com Tue Mar 25 18:49:57 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 26 Mar 2008 06:49:57 +0800 Subject: Prototype OO In-Reply-To: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> Message-ID: John Machin wrote: > On Mar 23, 12:32 am, "Diez B. Roggisch" wrote: >> John Machin schrieb: >> >>> On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: >> >>>> [1] Just one example:http://docs.mootools.net/Class/Class.js >> >>> Mootools being something a coworker might use? >> >> I don't understand the question. >> >> Diez > > It presupposes that the reader on first seeing "coworker" has mentally > decomposed it as "cow-ork-er". As an aside, having lived much of my early life on a hobby farm, I've often wondered to myself just what cow-orking involves ... ;) Tim Delaney From fn681 at ncf.ca Sat Mar 1 10:46:45 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sat, 01 Mar 2008 10:46:45 -0500 Subject: Beginner's assignment question In-Reply-To: References: Message-ID: Schizoid Man wrote: > As in variable assignment, not homework assignment! :) > > I understand the first line but not the second of the following code: > > a, b = 0, 1 > a, b = b, a + b > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > However what is the sequence of operation in the second statement? I;m > confused due to the inter-dependence of the variables. In the second line a now points to the value 1 and b points to 1 (the sum of zero and one) in a unitary operation (i.e. in turn, but effectively simultaneously). You might disassemble the code to see the sequence. Colin W. From steve at holdenweb.com Sun Mar 30 21:44:59 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 21:44:59 -0400 Subject: Please test Phatch on Windows (was Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL) In-Reply-To: References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: <47F0421B.90704@holdenweb.com> Stani: You'll be happy to hear that it appears (after a quick test) to work on Vista, though I blush to admit I actually have a Python running on that platform. The font selection is much better than in previous versions - although the names aren't quite the full font names it's pretty easy to tell which one will be used. regards Steve SPE - Stani's Python Editor wrote: > I have been working the last couple of days purely on bug fixing and > to port the code of Phatch fully to Windows as there were many issues. > This has improved: > - Phatch can now create droplets on Windows (win32 extensions > required) > - Installed fonts are retrieved from the Windows registry > - Image file dialogs are now working correctly > - Missing icons are added (including a phatch.ico) and are now > displayed in the windows titlebars > - Image Inspector was missing a panel > - Preview in Image Inspector now displays correctly > - (...) > > Besides that Phatch now features for all platforms: > - fonts can be defined with a nice dropdown autocomplete list > - drop down lists with convenient values in all actions > - the action masks now ships with some predefined masks (such as torn > edges) > - right click in the actions dialog box to see the source of an action > - View>Droplet nows shows the name of the action box rendered in the > logo > - Dutch translation is 100% complete > > As such no new features have been added, but the user experience feels > much more polished now. > > Please read *carefully* the installation instructions first: > http://photobatch.wikidot.com/install#toc6 > > People who have been using Phatch before should clear their font cache > (if it exists). Simply delete the file: > C:\Documents and Settings\Username\.phatch\fonts > > I did the Phatch port on a Windows 2000 machine, so I am curious to > hear how Phatch works on Windows XP and Vista. I will fix any bug (as > far as possible) which is reported quickly in the next couple of days. > > You can help translating Phatch here: > https://translations.launchpad.net/phatch/trunk/+pots/phatch > > Thanks in advance, > > Stani > > On 18 feb, 15:58, "SPE - Stani's Python Editor" > wrote: >> I'm pleased to announce the release ofPhatchwhich is a >> powerful batch processor and renamer.Phatchexposes a big part of the >> Python Imaging Library through an user friendly GUI. (It is using >> python-pyexiv2 to offer more extensive EXIF and IPTC support.)Phatch >> is not targeted at manipulating individual pictures (such as with >> Gimp), but repeating the same actions on hundreds or thousands of >> images. >> >> If you know PIL and have some nice recipes laying around, it is very >> easy to write plugins asPhatchgenerates the corresponding GUI >> automagically just like in Django. Any existings PIL scripts can be >> added very easily. Let me know if you want to contribute or have any >> questions. >> >> Homepage:http://photobatch.stani.be(free download link below) >> Tutorials:http://photobatch.wikidot.com/tutorials >> Translations:https://translations.launchpad.net/phatch/trunk/+pots/phatch >> License: GPLv3 >> Screenshot:http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg >> (the perspective and reflection is produced byPhatchitself) >> >> Phatchhas many features, like: >> - EXIF information inspector with thumbnail >> - limit jpeg file size when saving >> - tons of actions organized by tags (including perspective, round >> corners, shadow, reflection, ...) >> - console version (Phatchcan now run without a gui on servers) >> - batch rename and copy files based on exif metadata >> - data stamping (http://photobatch.wikidot.com) >> - online documentation wiki (http://photobatch.wikidot.com) >> >> Linux only features: >> - desktop or panel droplets on which images or folders can be dropped >> (will be ported to Windows & Mac) >> - Nautilus and desktop integration (with its own mime type and >> nautilus extension) >> - manpage with examples >> >> With python-pyexiv2 the following featues are added: >> - embedding the original EXIF and IPTC tags in the image >> >> All actions mostly have a separate pil function in their source code, >> so they could be read as a recipe book for PIL: >> * Auto Contrast - Maximize image contrast >> * Background - Put colour under transparent image >> * Border - Crop or add border to all sides >> * Brightness - Adjust brightness from black to white >> * Canvas - Crop the image or enlarge canvas without resizing the image >> * Colorize - Colorize grayscale image >> * Common - Copies the most common pixel value >> * Contrast - Adjust from grey to black & white >> * Convert Mode - Convert the color mode of an image (grayscale, RGB, >> RGBA or CMYK) >> * Copy - Copy image file >> * Effect - Blur, Sharpen, Emboss, Smooth, ... >> * Equalize - Equalize the image histogram >> * Fit - Downsize and crop image with fixed ratio >> * Grayscale - Fade all colours to gray >> * Invert - Invert the colors of the image (negative) >> * Maximum - Copies the maximum pixel value >> * Mask - Apply a transparency mask >> * Median - Copies the median pixel value >> * Minimum - Copies the minimum pixel value >> * Offset - Offset by distance and wrap around >> * Posterize - Reduce the number of bits of colour channel >> * Perspective - Shear 2d or 3d >> * Rank - Copies the rank'th pixel value >> * Reflect - Drops a reflection >> * Rename - Rename image file >> * Rotate - Rotate with random angle >> * Round - Round or crossed corners with variable radius and corners >> * Saturation - Adjust saturation from grayscale to high >> * Save - Save an image with variable compression in different types >> * Scale - Scale an image with different resample filters. >> * Shadow - Drop a blurred shadow under a photo with variable position, >> blur and color >> * Solarize - Invert all pixel values above threshold >> * Text - Write text at a given position >> * Transpose - Flip or rotate an image by 90 degrees >> * Watermark - Apply a watermark image with variable placement (offset, >> scaling, tiling) and opacity >> >> I developPhatchon Ubuntu/Linux, but I have tested and polished it >> regularly on Windows and Mac Os X. (Only the droplet functionality >> needs to be ported.)Phatchis submitted to Debian unstable and >> Ubuntu Hardy. Packagers for other platforms are welcome. >> >> Requirements: >> - PIL 1.1.5 or higher >> - wxPython 2.6 or higher >> - pyexiv2 (optional) >> - python nautilus bindings (optional) >> >> Best regards, >> Stani >> --http://pythonide.stani.be > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From kyosohma at gmail.com Mon Mar 31 20:50:30 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 17:50:30 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <41b598ef-c422-417f-9a77-b48eff8e6334@s37g2000prg.googlegroups.com> Message-ID: <5b1ef738-b456-4250-8a97-e97c9a09ffce@d1g2000hsg.googlegroups.com> On Mar 31, 4:53 pm, Amit Gupta wrote: > On Mar 31, 1:52 pm, Mike Driscoll wrote: > > > > > What about creating a setup.py and using the distutils command to > > build rpms or tarballs? > > >http://docs.python.org/dist/built-dist.html > > > Mike > > My quick look: The link you sent is under the header "Distributing > Python Modules". In my case, I have set of python-files that > altogether is part of one product-functionality. I would like to > package it and have it run standalone, even if the user does not have > python installed. Good point. I guess I missed the "one product-functionality" requirement in your original post. Sorry for the noise! > > Ok, I guess build-dist can possibly achieve the same purpose (without > reading through the link you sent). So my question would be: why is > there pyinstaller, if this does the job. Is build-dist more low-level > and thus is over-kill for the kind of application I am looking for?: > > Thanks PyInstaller is for converting something you've written in Python into a binary for various OS's. When I read through the thread though, I thought your requirements might include distributing the modules as source too. If you want to produce a binary for Macs, I've heard that py2app does the job: http://pypi.python.org/pypi/py2app/ There's also cx_freeze, which is different than freeze.py: http://www.cxtools.net/default.aspx?nav=cxfrlb The last one is probably the best new advice I have to offer. Mike From grahn+nntp at snipabacken.se Mon Mar 31 18:51:19 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 31 Mar 2008 22:51:19 GMT Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> <65cuuhF2fhuoaU4@mid.uni-berlin.de> Message-ID: On 31 Mar 2008 20:13:05 GMT, Marc 'BlackJack' Rintsch wrote: > On Mon, 31 Mar 2008 12:39:54 -0700, hexusnexus wrote: > >> How do I receive input from the command line in Python? > > Direct way `sys.argv`, comfortable way `optparse`. I have a feeling he doesn't mean command-line arguments to the program, but typing on the keyboard after the program has started. If that is the case: Direct way `sys.stdin`, many other fancy ways. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From josef at koller.info Thu Mar 20 18:39:15 2008 From: josef at koller.info (Josef) Date: Thu, 20 Mar 2008 15:39:15 -0700 (PDT) Subject: CDF python Message-ID: Hi, I have a bunch of CDF files that I need to read/process and I'd like to use python for that. Does anybody know an API for interfacing with CDF? So far I only found pycdf for netCDF, and pytables for HDF but nothing for CDF. Josef From paulgeeleher at gmail.com Fri Mar 7 11:28:40 2008 From: paulgeeleher at gmail.com (sophie_newbie) Date: Fri, 7 Mar 2008 08:28:40 -0800 (PST) Subject: Keep a python script running after browser window closed Message-ID: Hi, I have a cgi script that performs a very long computation that can take several hours to complete. Is there any smart way that I can keep this script running until it is finished (after the user has closed the browser) and email them with the results. The email bit isn't the problem, I just don't know how to keep the code running in the background. I'm sure there is a smart way to do this... Thanks! From arnodel at googlemail.com Thu Mar 13 18:52:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 15:52:45 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: Message-ID: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> On Mar 13, 10:06?pm, Dave Kuhlman wrote: > The following code has me mystified: > > In [4]: class A(object): > ? ?...: ? ? def show(self): > ? ?...: ? ? ? ? print 'hello' > ? ?...: > ? ?...: > In [5]: a = A() > In [6]: > In [7]: x = a.show > In [8]: y = getattr(a, 'show') > In [9]: x > Out[9]: > > In [10]: y > Out[10]: > > In [11]: > In [12]: id(x) > Out[12]: 12419552 > In [13]: id(y) > Out[13]: 12419872 > In [14]: > In [15]: x is y > Out[15]: False > In [16]: > In [17]: x() > hello > In [18]: y() > hello > > Basically, the above code is saying that foo.foobar is not the same as > getattr(foo, 'foobar'). > > But the documentation athttp://docs.python.org/lib/built-in-funcs.html#l2h-33 > says that they are equivalent. > > And, the following seems even worse: > > ? >>> id(getattr(a, 'show')) == id(a.show) > ? True > ? >>> getattr(a, 'show') is a.show > ? False > > What gives? ?This breaks my understanding of id(), the is operator, and > getattr(). > > Can someone help me make sense of this? There are several misconceptions that contribute to your confusion I think. 1. This has nothing to do with getattr(). If you run the same code as above, replacing getattr(a, 'show') with a.show you will get the same results. E.g. >>> class Foo(object): ... def bar(self): pass ... >>> id(foo.bar) == id(foo.bar) # (A) True >>> foo.bar is foo.bar # (B) False >>> 2. The above is because two objects can have the same id if their lifetimes don't overlap. In (A) by the time the second foo.bar is created, the first one is already dead. So The second one takes its place in memory, hence their ids are equal 3. In (B) the first foo.bar is kept alive for comparing with the second, hence they have a different id. 4. Both points above follow from the fact that foo.bar is really a function call that returns a (potentially) new object: in fact what really happens is something like Foo.__dict__['bar'].__get__(foo, Foo). So every time foo.bar is executed an object is (or may be) created, with a new id. HTH -- Arnaud From tms at zeetix.com Sun Mar 16 11:18:50 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sun, 16 Mar 2008 11:18:50 -0400 Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <47DD33D7.2020300@timgolden.me.uk> Message-ID: <00be01c88779$0a40ca70$0200a8c0@TMSMAIN> > I'm not entirely sure why you think Pyrex should "contain a compiler". > It certainly works well enough with the free [beer] MS VS 2008 Express > and I'm fairly sure it's fine with MingW. Both of those are readily > available and I don't imagine anyone who's going to use Pyrex / Cython / > ShedSkin is going to baulk at downloading a compiler set :) Anything like this is a lot more attractive to me if I can download and install a binary without *needing* a compiler. Most of the time, I just want something to run -- I don't want to risk diving in compiler-hell if I can avoid it. It isn't downloading the compiler set that worries me, it's that I almost never even want to think about it. For example, the new (!) simplejson (v1.7.4) doesn't compile correctly (on my WinXP system, at least) with either any current MS or MinGW compiler. Oh, I know I can make it work if I spend enough time on it -- but the binary egg I eventually found seems to work just fine. From tdelaney at avaya.com Wed Mar 5 21:08:55 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 6 Mar 2008 10:08:55 +0800 Subject: Failed saving throw In-Reply-To: Message-ID: Aahz wrote: > For anyone who hasn't heard, E. Gary Gygax died yesterday. Some > people think we should build a tomb in his honor. ;-) Well, you sure wouldn't get a saving throw there ;) Tim Delaney From bockman at virgilio.it Tue Mar 11 04:03:12 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Tue, 11 Mar 2008 01:03:12 -0700 (PDT) Subject: Python Sockets Help References: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> Message-ID: On 10 Mar, 23:58, Mark M Manning wrote: > I need your expertise with a sockets question. > > Let me preface this by saying I don't have much experience with > sockets in general so this question may be simple. > > I am playing with the mini dns server from a script I found online:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt > > All I want to do is edit this script so that it records the IP > address. ?I've seen other examples use the accept() object which > returns the data and the IP address it is receiving the data from. ?I > can't use that in this case but I'm wondering if someone could show me > how. > > Here is the socket part of the script: > > if __name__ == '__main__': > ? ip='192.168.1.1' > ? print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip > > ? udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > ? udps.bind(('',53)) > > ? try: > ? ? while 1: > ? ? ? data, addr = udps.recvfrom(1024) > ? ? ? p=DNSQuery(data) > ? ? ? udps.sendto(p.respuesta(ip), addr) > ? ? ? print 'Respuesta: %s -> %s' % (p.dominio, ip) > ? except KeyboardInterrupt: > ? ? print 'Finalizando' > ? ? udps.close() > > Thanks to everyone in advance! > ~Mark You already have the address of the sender, is in the 'addr' variable, as returned by udps.recvfrom. Change the print statement in sometinmh like: print 'Respuesta (%s): %s -> %s' % ( addr, p.dominio, ip) and you will see the sender address in dotted notation printed inside the (). Ciao ------- FB From python at bdurham.com Thu Mar 6 20:56:04 2008 From: python at bdurham.com (Malcolm Greene) Date: Thu, 06 Mar 2008 20:56:04 -0500 Subject: Looking for very light weight template library (not framework) Message-ID: <1204854964.1470.1241033951@webmail.messagingengine.com> New to Python and looking for a template library that allows Python expressions embedded in strings to be evaluated in place. In other words something more powerful than the basic "%(variable)s" or "$variable" (Template) capabilities. I know that some of the web frameworks support this type of template capability but I don't need a web framework, just a library that supports embedded expression evaluation. Use case: myOutput = """\ The total cost is {{invoice.total}}. This order will be shipped to {{invoice.contact}} at the following address: {{invoice.address}} This order was generated at {{some date/time expression}} """ Any suggestions appreciated. Malcolm From mattheww at chiark.greenend.org.uk Mon Mar 17 14:11:00 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 17 Mar 2008 18:11:00 +0000 (GMT) Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <13tst1388cp67d8@corp.supernews.com> Message-ID: In article , Duncan Booth wrote: > I don't have a copy of 1.4 to check so I'll believe you, but you can > certainly get the output I asked for with much more recent versions. > For the answer I actually want each asterisk substitutes for exactly one > character. Then I'll guess you're looking for something like '0==0', with Python 2.2 or so (so that you'd get the PyTrue object). -M- From emailamit at gmail.com Fri Mar 14 15:23:14 2008 From: emailamit at gmail.com (Amit Gupta) Date: Fri, 14 Mar 2008 12:23:14 -0700 (PDT) Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Message-ID: On Feb 20, 8:51 pm, Miki wrote: > Hello Amit, > > > > > python testname.py : the unitests runs as usual and I get the > > following results: > > ---------------------------------------------------------------------- > > Ran 2 tests in 0.024s > > > OK > > -------------------------------------------------------------------- > > > However, if I do "python -mpdbtestnames.py": I get > > ython -mpdbtestnames.py> /s/nd6/amit/pyiglu/testnames.py(1)() > > > -> importunittest > > (Pdb) c > > > ---------------------------------------------------------------------- > > Ran 0 tests in 0.000s > > > OK > > ------------------------------------------------------------------- > > IIRCunittestchecks the __main__ module for tests to run. Once you > run python with "-mpdb" the __main__ module ispdband not your > script. > > HTH, > -- > Miki http://pythonwise.blogspot.com Ok, Sorry for late reply on this. So What do I do, if my testcase if failing because of an uncaught exception and I want to run it in pdb. Thanks From carsten at uniqsys.com Sat Mar 15 15:03:11 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 15 Mar 2008 20:03:11 +0100 Subject: Unicode/UTF-8 confusion In-Reply-To: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> References: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> Message-ID: <1205607791.3224.4.camel@localhost.localdomain> On Sat, 2008-03-15 at 12:09 -0400, Tom Stambaugh wrote: > [...] > I use simplejson to serialize html strings that the server is delivering to > a browser. Since the apostrophe is a string terminator in javascript, I need > to escape any apostrophe embedded in the html. > [...] simplejson escapes them for you: >>> import simplejson >>> s = " ' " >>> simplejson.dumps(s) '" \' "' Why is this not good enough for your needs? -- Carsten Haese http://informixdb.sourceforge.net From S.Mientki-nospam at mailbox.kun.nl Thu Mar 20 12:21:34 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 20 Mar 2008 17:21:34 +0100 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <9a27e$47e28f17$83aef404$28537@news1.tudelft.nl> sturlamolden wrote: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > I've tried several of the above mentioned builders, with the same result. I've also looked at wxFormBuilder, but I found it far too difficult and fully unreadable (how can you create actions/bindings on components you don't see ?). So I might be very very naive, but why all so complex ?? I wrote a few lines of code, and now all my form designs look as simple as this: GUI = """ self.Splitter_Plots ,SplitterVer self.Panel ,PanelVer, 010 self.Panel_Top ,PanelHor, 11 Label_Top ,wx.StaticText self.Scope_Canvas ,PlotCanvas ,self, Real_Time self.Panel_Bottom ,PanelHor Label_Bottom ,wx.StaticText self.Scope_History ,PlotCanvas_History ,self, Real_Time """ exec ( Create_GUI ( GUI, 'Plots_Dock' ) ) cheers, Stef From larry.cebuala at gmail.com Thu Mar 13 00:46:48 2008 From: larry.cebuala at gmail.com (Larry) Date: Wed, 12 Mar 2008 21:46:48 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Message-ID: <16a3c2a3-4025-4771-97f3-fc9c7b80efb7@s8g2000prg.googlegroups.com> Thanks to all those who replied to this post. I'm gonna try your suggestions. They are a great help. From nodrogbrown at gmail.com Fri Mar 14 02:42:10 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Thu, 13 Mar 2008 23:42:10 -0700 (PDT) Subject: newbie question structure of function References: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> <37088f9c-e68e-483e-92a3-e730411a79bf@2g2000hsn.googlegroups.com> <5313a050-612f-47f9-ac3c-483888d10ece@i7g2000prf.googlegroups.com> Message-ID: <927d97fc-d611-40ea-a096-4a7ce16184ca@s12g2000prg.googlegroups.com> > > > resultname=""" > > > That starts a string literal. > > i am not sure if this is the right way..i used it in case > matchdistance < threshold return False.then the filename will not be > taken from the filenameslist and so returns as an empty string. >a one-tuple why not use None instead? if (matchdistance < threshold): resultname=filenameslist[index] else: resultname=None will that not be better? gordon From eddie at holyrood.ed.ac.uk Mon Mar 10 06:47:54 2008 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 10 Mar 2008 10:47:54 +0000 (UTC) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: shakefu at gmail.com writes: >I'm new to python and I was wondering if there are any intelligent >date/time parsing modules out there. I've looked at strptime (or >whichever it is) and mxDateTime from the eGenix package. I need >something to parse user input for a django app, and it's awesome to be >able to write "last monday", "a year ago", or "10pm tuesday" like >PHP's strtotime. >So are there any modules that allow for that kind of parsing? http://code-bear.com/code/parsedatetime/ From michael.wieher at gmail.com Sat Mar 29 15:24:01 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sat, 29 Mar 2008 14:24:01 -0500 Subject: Why prefer != over <> for Python 3.0? In-Reply-To: References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: to me it seems simple. C uses != why does C use != .... because its kind of hard to type the "equal with a slash" so if python is supposed to be a simple and easy to use language, use the simple and easy to understand, standard 'not-equal' operator... Idk, maybe there's more to it but simple is as simple does, sir 2008/3/29 Lie : > On Mar 30, 1:24 am, Duncan Booth wrote: > > Lie wrote: > > > You're forcing your argument too much, both != and <> are NOT standard > > > mathematics operators -- the standard not-equal operator is >< -- and > > > I can assure you that both != and <> won't be comprehensible to non- > > > programmers. > > > > My maths may be a bit rusty, but I always thought that the standard not- > > equal operator was like an = sign but with a diagonal slash through it > as > > displayed when you do: > > > > print u'\u2260' > > Ah yes, that is also used (I completely forgot about that one, my > math's aren't that sharp anymore) and I think it's used more > frequently than ><. Some books use >< while most use ?, but my > argument was that no math book use != or <> (except in math for > programmers). > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Wed Mar 12 16:55:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 15:55:56 -0500 Subject: string / split method on ASCII code? In-Reply-To: References: Message-ID: <47D8435C.7000500@tim.thechases.com> > I have these annoying textilfes that are delimited by the ASCII char for << > (only its a single character) and >> (again a single character) > > Their codes are 174 and 175, respectively. > > My datafiles are in the moronic form > > X<>Z > > I need to split on those freaking characters. Any tips on how to make split > work with these things? If it were a single character, you could just use s.split(chr(174)) However, since you need to split on multiple characters, you can use import re splitter_re = re.compile(chr(174) + '|' + chr(175)) for line in file(FILENAME): parts = splitter_re.split(line) do_something(parts) and then go find a large blunt object with which to bludgeon the creator of the file... :) They aren't exactly ascii characters (0-127), but the above should at least do the trick. -tkc From mnordhoff at mattnordhoff.com Mon Mar 10 06:11:12 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 10:11:12 +0000 Subject: is operator In-Reply-To: <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> References: <004801c881f2$a04081f0$0b020b0a@nb1011> <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> Message-ID: <47D50940.3010202@mattnordhoff.com> castironpi at gmail.com wrote: >> I believe Python automatically creates and caches int objects for 0-256, >> so whenever you use them, they refer to the same exact objects. Since >> ints are immutable, it doesn't matter. > > One of the biggest hits on start-up time, by the way. ;) Well, the developers clearly decided it was worth it at the time. Who knows, perhaps that's changed since then. -- From martin at v.loewis.de Fri Mar 21 16:49:00 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 21:49:00 +0100 Subject: os.path.getsize() on Windows In-Reply-To: References: Message-ID: <47E41F3C.6040109@v.loewis.de> > def isGrowing(f, timeout): > ssize = os.path.getsize(f) > time.sleep(timeout) > esize =os.path.getsize(f) > return esize != ssize > > On windows, this returns the size of the file as it _will be_, not the > size that it currently is. Why do you say that? It most definitely returns what the size currently is, not what it will be in the future (how could it know, anyway). Regards, Martin From yatsek at gmail.com Sun Mar 23 11:34:20 2008 From: yatsek at gmail.com (yatsek at gmail.com) Date: Sun, 23 Mar 2008 08:34:20 -0700 (PDT) Subject: Duplicating list of lists [newbie] Message-ID: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Hi there. I felt like I already know my toys around but it looks that I'm still newbie on some points. So here goes problem: Lets say that we have list to copy: a = [1,2,3] b = a[:] a[0] = 5 a > [5,2,3] b >[1,2,3] So far so good But... let's say that "a" also contains lists: a = [1,2,[5,6,7]] b = a[:] a[0] = 55 a > [55,2,[5,6,7]] b > [1,2,[5,6,7]] Looks OK but... a[2][0] = 99 a > [55,2,[99,6,7]] b > [1,2,[99,6,7]] So - it looks that in list "b" there copy of all objects from list "a" including not copy of list [5,6,7] but reference to it. Is there simple way to copy a into b (like a[:]) with all copies of all objects going as deep as possible? Or it can be done only manually? Regards Yatsek From castironpi at gmail.com Sun Mar 9 20:48:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 17:48:03 -0700 (PDT) Subject: parralel downloads References: <47D2C331.4020708@islandtraining.com> Message-ID: <2e5af57d-ae57-456f-aa77-5ea4f5a4f431@o77g2000hsf.googlegroups.com> > > That's it. ?Far easier than threads. I'll order a 'easyness' metric from the warehouse. Of course, resources are parameters to the metric, such as facility given lots of time, facility given lots of libraries, facility given hot shots, &c. > Easier? If you omit all the relevant details, yes, looks easy. For ? > > def downloadfile(url, fn): > ? ?s = create socket for url > ? ?f = open filename for writing > ? ?shutil.copyfileobj(s.makefile(), f) > > for each url, filename to retrieve: [ threadlist.addandstart( threading.Thread(target=downloadfile, args=(url,filename)) ) ] > [ threadlist.joineach() ] > Of course, don't try to download a million files at the same time - ? > neither a million sockets nor a million threads would work. Dammit! Then what's my million-core machine for? If architectures "have reached the point of diminishing returns" ( off py.ideas ), then what's the PoDR for numbers of threads per core? Answer: One. Just write data structures and don't swap context. But when do you want it by? What is the PoDR for amount of effort per clock cycle saved? Get a Frank and a Brit and ask them what language is easiest to speak. (Answer: Math. Har *plonk*.) From terry at jon.es Mon Mar 17 12:57:17 2008 From: terry at jon.es (Terry Jones) Date: Mon, 17 Mar 2008 17:57:17 +0100 Subject: Question on using distutils.core.run_setup Message-ID: <18398.41709.881272.119631@jon.es> I'm trying to programmatically install something built using distutils. I found distutils.core.run_setup and can use it via >>> dist = run_setup('setup.py', ['-q', 'install']) Is that the recommended way to do an install from inside Python (as opposed to doing it on the command line)? If so, how can I find where the thing(s) I installed now resides? I saw dist.packages but that just has top-level package names. I could __import__ these (and then use module.__file__), but that's not a good solution as it may run code I don't want run. On my machine, I can see the packages have been installed under the system's python2.5/site-packages directory. But how can I determine that programmatically? I don't see anything useful on the distutils.dist.Distribution instance I'm getting back from run_setup. Thanks! Terry From goldspin at gmail.com Thu Mar 6 20:00:00 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 6 Mar 2008 17:00:00 -0800 Subject: How to Encode String of Raw UTF-8 into Unicode? In-Reply-To: References: Message-ID: Awesome, that works. Thank you so much! My confusion of the different format made this harder than it should. On Thu, Mar 6, 2008 at 4:53 PM, Gabriel Genellina wrote: > En Thu, 06 Mar 2008 22:43:58 -0200, Henry Chang > escribi?: > > > > Suppose I start out with a raw string of utf-8 code points. > > "utf-8 code points"??? > Looks like a utf-8 encoded string, and then written in hex format. > > > > raw_string = "68656E727963" > > > > I can coerce it into proper unicode format by slicing out two > > characters at a time. > > > > unicode_string = u"\x68\x65\x6E\x72\x79\x63" > > > > >>> print unicode_proper > > >>> henry > > > > My question: is there an existing function that can do this (without > > having to manually slicing the raw text string)? > > Two steps: first decode from hex to string, and then from utf8 string to > unicode: > > py> raw_string = "68656E727963" > py> raw_string.decode("hex") > 'henryc' > py> raw_string.decode("hex").decode("utf8") > u'henryc' > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list From sgeiger at ncee.net Tue Mar 11 13:10:19 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 11 Mar 2008 12:10:19 -0500 Subject: How to factor using Python? In-Reply-To: <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> Message-ID: <47D6BCFB.5030904@ncee.net> def fact(x): if x == 1: return 1 # don't forget this else: return x * fact(x - 1) print fact(5) > Factorial algorithm is a very simple and common algorithm, and it's > one of the most basic of all recursive algorithm > def fact(x): > return x * fact(x - 1) > > That recursive function is very close to the basic definition of > factorials, that is > x! = x * (x - 1)! > > If however, you expected x to be a real (float) value, you'd better > consider the gamma function as Mark Dickinson pointed out. Wikipedia > is a good start to create your gamma function: > http://en.wikipedia.org/wiki/Factorial > http://en.wikipedia.org/wiki/Gamma_function > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From vedran.pregelj at gmail.com Thu Mar 6 11:28:42 2008 From: vedran.pregelj at gmail.com (vedranp) Date: Thu, 6 Mar 2008 08:28:42 -0800 (PST) Subject: Data aggregation Message-ID: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> Hi, I have a case where I should aggregate data from the CSV file, which contains data in this way: DATE TIME COUNTRY ZIP CITY VALUE1 VALUE2 VALUE3 21.2.2008 00:00 A 1000 CITY1 1 2 3 21.2.2008 00:00 A 1000 CITY2 4 5 6 21.2.2008 00:00 A 1000 CITY3 7 8 9 21.2.2008 00:00 A 1000 CITY4 1 2 3 21.2.2008 00:15 A 1000 CITY1 4 5 6 21.2.2008 00:15 A 1000 CITY2 7 8 9 21.2.2008 00:15 A 1000 CITY3 1 2 3 21.2.2008 00:15 A 1000 CITY4 4 5 6 21.2.2008 00:00 A 2000 CITY10 7 8 9 21.2.2008 00:00 A 2000 CITY20 1 2 3 21.2.2008 00:00 A 2000 CITY30 4 5 6 21.2.2008 00:00 A 2000 CITY40 1 2 3 21.2.2008 00:15 A 2000 CITY10 7 8 9 21.2.2008 00:15 A 2000 CITY20 1 2 3 21.2.2008 00:15 A 2000 CITY30 4 5 6 21.2.2008 00:15 A 2000 CITY40 1 2 3 I need to aggregate data from file1, so the result would be a CSV file (file2) in this format: DATE COUNTRY ZIP CITY SumOfVALUE1 SumOfVALUE2 SumOfVALUE3 formula1 21.2.2008 A 1000 CITY1 5 7 9 12 21.2.2008 A 1000 CITY2 11 13 15 24 21.2.2008 A 1000 CITY3 8 10 12 18 21.2.2008 A 1000 CITY4 5 7 9 12 21.2.2008 A 2000 CITY10 14 16 18 30 21.2.2008 A 2000 CITY20 2 4 6 6 21.2.2008 A 2000 CITY30 8 10 12 18 21.2.2008 A 2000 CITY40 2 4 6 6 So, group by DATE, COUNTRY, ZIP and CITY and sum (or do some calculation) the values and do some calculation from summed fields (e.g.: formula1 = SumOfVALUE1+SumOfVALUE2). I am able to do this by first loading file1 in SQL, perform a query there, which returns the file2 results and then load it back in the SQL in the different table. I would like to avoid the step of taking data out from database in order to process it. I would like to process the file1 in Python and load the result (file2) in SQL. >From some little experience with Perl, I think this is managable with double hash tables (1: basic hash with key/value = CITY/pointer-to- other-hash, 2: hash table with values for CITY1), so I assume that there would be also a way in Python, maybe with dictionaries? Any ideas? Regards, Vedran. From jakecjacobson at gmail.com Wed Mar 19 14:33:19 2008 From: jakecjacobson at gmail.com (jakecjacobson at gmail.com) Date: Wed, 19 Mar 2008 11:33:19 -0700 (PDT) Subject: Inserting DTD statement to XML Message-ID: <80eadd7f-5a2b-4fa1-a561-23e542436232@8g2000hsu.googlegroups.com> I am new to Python and I am writing a script to build a XML document and post it to a website. I have a working script but need to insert a DTD statement in my XML document and can't find out how to do this. I am using "from xml.dom.minidom import Document" Some code I am using is: doc = Document() rootNode = doc.createElement("employees") doc.appendChild(rootNode ) I get the following when I print it out ... What I would like is to have something like: ... From jeff at schwabcenter.com Sat Mar 1 23:33:36 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 01 Mar 2008 20:33:36 -0800 Subject: Book Recomendations In-Reply-To: References: Message-ID: Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. Python In A Nutshell: http://www.oreilly.com/catalog/pythonian2/ Here's a previous discussion of books for newbies, but I gave my recommendations for other experienced programmers; be forwarned that I'm not quite as experienced as you appear to be. :) http://www.nabble.com/newbie-in-python-td15608979.html#nabble.star15617714-1 From timr at probo.com Sat Mar 29 19:48:09 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 29 Mar 2008 23:48:09 GMT Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> <86b83385-697d-40d6-8bbb-dfeeba372040@d21g2000prf.googlegroups.com> Message-ID: "Giampaolo Rodola'" wrote: > >I'll try to describe what I'm actually trying to implement so that >maybe it can help you understand a little better. >The application is an asynchronous FTP server implementation. >I decided that it would be desirable to change the current >implementation so that every time a filesystem operation is going to >be made I >temporarily change the current process ID to reflect the current >logged-in user, execute the filesystem call and then switch back to >the original process ID. You don't mean "process ID". You mean user ID and group ID. Your fundamental concept is correct. >Pseudo code: > >def STOR(filename): > authorizer = UnixAuthorizer() > authorizer.impersonate_user(current_logged_in_user) > try: > f = open(filename, 'w') > finally: > authorizer.terminate_impersonation() > ... > >The UnixAuthorizer class is expected to provide the mechanism to >change the current user (presumably via os.setegid()/os.seteuid()) and >then switch back to the original one. >Since we're talking about an asynchronous environment I tought that >temporarily changing the process ID was the only way to do this. >I'm sincerely not skilled enough about the UNIX world to know which >are the security implications behind such an approach. >Do you think it is reasonable? Typically, an FTP server dedicates one thread/process per logged in session. That process changes to the logged in user's identity as soon as it gets the username and password, and stays there forever. There is no need to switch back to root in between. The principle of least privilege says you should just stay as the unprivileged user while you can. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mhearne808 at gmail.com Tue Mar 18 10:42:52 2008 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Tue, 18 Mar 2008 07:42:52 -0700 (PDT) Subject: Problems building zlib module on RHEL Message-ID: I can't seem to get the zlib module to build on an RHEL box. I did the following: 1) Download zlib 1.2.3 2) configure;make;make install 3) Download python 2.5.2 4) configure;make;make install 5) >>> import zlib => "ImportError: No module named zlib" In the make install step for python, I notice there are the following errors: building 'zlib' extension gcc -pthread -shared build/temp.linux-x86_64-2.5/home/shake/python/ Python-2.5.2/Modules/zlibmodule.o -L/usr/local/lib -lz -o build/ lib.linux-x86_64-2.5/zlib.so /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libz.a: could not read symbols: Bad value collect2: ld returned 1 exit status Does anyone have any hints on how to get around this? system info: kernel : 2.6.9-67.0.1.ELsmp gcc : 3.4.6 Thanks, Mike From vijvvv at gmail.com Fri Mar 7 03:07:39 2008 From: vijvvv at gmail.com (Rosy) Date: Fri, 7 Mar 2008 00:07:39 -0800 (PST) Subject: **SEXY HORNEY ACTRESS XXX VIDEOS**CAM SEX** Message-ID: <230ed8eb-732f-458c-b97b-342356ff328b@e10g2000prf.googlegroups.com> **SEXY HORNEY ACTRESS XXX VIDEOS**CAM SEX** **ANAL SEX** **HARDCORE SEX** **PORN SEX** **SEX GALLERY** **ITS FREE!!!!!FREE!!!!FREEE!!!! http://camilasexxx.googlepages.com/ http://camilasexxx.googlepages.com/ http://camilasexxx.googlepages.com/ From castironpi at gmail.com Wed Mar 26 22:09:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 19:09:54 -0700 (PDT) Subject: Not understanding lamdas and scoping References: Message-ID: On Mar 26, 5:03?pm, Joshua Kugler wrote: > George Sakkis wrote: > > On Mar 26, 5:02 pm, Joshua Kugler wrote: > > >> I am trying to use lamdba to generate some functions, and it is not > >> working > >> the way I'd expect. ?The code is below, followed by the results I'm > >> getting. ?More comments below that. > > >> (...) > > >> So, is there some scoping issue with lambda > >> that I'm not seeing? > > > Yes; it's not related to lambda though but to closures (whether > > defined as lambdas or regular functions). See for example I saw it somewhere, maybe recipies. >>> funs= [] >>> for i in range( 2 ): ... def f(): pass ... print( f ) ... funs.append( f ) ... >>> funs[0] >>> funs[1] >>> You also have: >>> partial( lambda a: 0 ) >>> _( 1 ) 0 >>> and partial use cell, so it binds values. But: >>> a= (1,2) >>> c= lambda b: a[b] >>> c(0) 1 >>> a= (2,2) >>> c(0) 2 >>> Lambda is late-bound by name. From roger.miller at nova-sol.com Mon Mar 31 15:31:19 2008 From: roger.miller at nova-sol.com (Roger Miller) Date: Mon, 31 Mar 2008 12:31:19 -0700 (PDT) Subject: License of Python References: Message-ID: Is there any legal problem with including licenses for languages you don't use? (But I agree with the other posters that any competitor worthy of concern will figure it out in short order if they care.) From sam at mas.pl Mon Mar 31 03:55:55 2008 From: sam at mas.pl (sam) Date: Mon, 31 Mar 2008 09:55:55 +0200 Subject: Prototype OO In-Reply-To: <64hp4bF2bhmtuU1@mid.uni-berlin.de> References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch napisa?(a): > no "inheritance model" in Javascript. Or why does each JS-lib provide > it's own version of an extend-function [1]? Ok -- thank you! > The only point you might have is the somwhat unfortunate distinction > between lambda and function in python - but this is on a syntactical > level only. Once created, you can use them as you like. Yes -- everybody searches for a perfect language to his needs... From castironpi at gmail.com Sat Mar 15 17:54:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 14:54:56 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: <6914b982-a06c-40b7-b5bc-77ddd864009a@s50g2000hsb.googlegroups.com> > >>> I am embarrassed to say that this vaguely disrespectful exchange made me > >>> laugh out loud. > > >> Serious: why do you think this is disrespectful? > > >Not to speak for Tim, but I imagine it could be perceived as > >disrespectful because Prof. Weizenbaum has only recently passed away. > >In fact, I think the Prof would be very happy to see people having some > >fun at the expense of AI, which he saw as a real threat to human freedom. > > Exactly. ?Also, humor is one traditional response to negative emotions; > see all the various Gygax tributes that use humor. Were you close to him? From anh.hai.trinh at gmail.com Sun Mar 9 03:42:43 2008 From: anh.hai.trinh at gmail.com (Chick) Date: Sat, 8 Mar 2008 23:42:43 -0800 (PST) Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> <13t6p1o23so7oc2@corp.supernews.com> Message-ID: <8e1c4457-6313-4395-8483-22271d079c1d@2g2000hsn.googlegroups.com> > But a far bigger security hole is that the password is sitting there in > your securePass variable in plain text. What are you doing about that? Precisely why I though to use wipe() that way. The password is there in plain text as long as it has to and then one call of securePass.wipe() and its memory is overwritten. So I guess it is not possible in pure Python to lock the memory from being swaped? From willsteve2003 at yahoo.ca Mon Mar 10 11:15:07 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:15:07 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> On Mar 8, 8:27?pm, Dan Bishop wrote: > // ? ?Copyright (C) 2008 Foobar Computer Consulting > // > // ? ?VERSION ? PROJECT# ? ? DATE ? ? DESCRIPTION > // ? ?------- ? -------- ? -------- ? ------------------ > // ? ? ?1.00 ? ? 123456 ? ?01/04/08 ? Original creation. > // > > Eleven lines, of which the only useful information to me was the > project number, as knowing this let me look up who was behind these > comments. Actually, "editorial" comments that tell you who last changed a program, when and why can be useful. I worked in a company with a number of programmers on staff. Having comments that told us Joe worked on a program yesterday that isn't working today could often solve half the battle. Especially if Joe also added a comment near the lines he had changed. Likewise including the "Project#" would help us track all the programs that had to be changed for a specific project. This allowed us to move all related items into the Live system once the testing phase had been completed (we just searched for everything with the same Project# in it). Yes, on rare occasions we would have an entire page of "Editorial" comments to ignore at the beginning of our program listing, but it was easy enough to skip that page. I will grant you that probably after 10 changes the first change isn't as important anymore (unless you want to backtrack and find out who started the Project in the first place and what it's original purpose was). From electronixtar at gmail.com Fri Mar 21 19:07:25 2008 From: electronixtar at gmail.com (est) Date: Fri, 21 Mar 2008 16:07:25 -0700 (PDT) Subject: forkpty not working? References: <7tyEj.20469$Ch6.19687@newssvr11.news.prodigy.net> Message-ID: <4b61de13-c07b-48c8-85c9-bf5f589040f0@e6g2000prf.googlegroups.com> On Mar 21, 2:58?am, Dan Stromberg wrote: > If you google a bit, I believe you'll find one or more python modules for > working with ssh. > > Also, if you want to roll your own, the easiest way to get around the > password requirement is to use ssh passwordless authentication using DSA > or RSA public/private keypairs: > > http://stromberg.dnsalias.org/~dstromberg/ssh-keys.html > > As far as why the code below doesn't open your "it_worked" file - exec > replaces the current process with the specified process - so the current > process effectively goes away on exec. > > On Thu, 20 Mar 2008 00:40:49 -0700, est wrote: > > Hello everyone. I am trying to write a bash/ssh wrapper in python so > > python scripts could interact with bash/ssh. > > > Because when input passwords to ssh it requires a tty rather than stdin > > pipe, so i have to use a pty module to do that. > > > I copied this snippet from this thread > >http://groups.google.com/group/comp.lang.python/browse_thread/ > > thread/6bbc3d36b4e6ff55/ > > > > > > > def rcmd(user, rhost, pw, cmd): > > ? ? ? ? #Fork a child process, using a new pseudo-terminal as the > > child's controlling terminal. > > ? ? ? ? pid, fd = os.forkpty() > > ? ? ? ? # If Child; execute external process > > ? ? ? ? if pid == 0: > > ? ? ? ? ? ? ? ? os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + > > cmd) > > ? ? ? ? ? ? ? ? x=open("it_worked.txt", "w") #output a file for test > > ? ? ? ? ? ? ? ? x.write("xxx") > > ? ? ? ? ? ? ? ? x.close() > > ? ? ? ? #if parent, read/write with child through file descriptor else: > > ? ? ? ? ? ? ? ? pause() > > ? ? ? ? ? ? ? ? #Get password prompt; ignore > > ? ? ? ? ? ? ? ? os.read(fd, 1000) > > ? ? ? ? ? ? ? ? pause() > > ? ? ? ? ? ? ? ? #write password > > ? ? ? ? ? ? ? ? os.write(fd, pw + "\n") > > ? ? ? ? ? ? ? ? pause() > > ? ? ? ? ? ? ? ? res = '' > > ? ? ? ? ? ? ? ? #read response from child process > > ? ? ? ? ? ? ? ? s = os.read(fd,1 ) > > ? ? ? ? ? ? ? ? while s: > > ? ? ? ? ? ? ? ? ? ? ? ? res += s > > ? ? ? ? ? ? ? ? ? ? ? ? s = os.read(fd, 1) > > ? ? ? ? ? ? ? ? return res > > > As far as I can see the code is not working, when called the function > > rcmd() there is no file it_worked.txt spawned in the directory. I am > > n00b to POSIX, so anyone please give me some hint? what happened when > > os.forkpty()?- Hide quoted text - > > - Show quoted text - Thanks for the reply! What's your recommandation for a bash wrapper? I am trying to implement some simple stuff which functions like ipython. From stefan_ml at behnel.de Fri Mar 14 07:36:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 14 Mar 2008 12:36:21 +0100 Subject: sorting question In-Reply-To: <13tknf14vncbu34@corp.supernews.com> References: <13tknf14vncbu34@corp.supernews.com> Message-ID: <47DA6335.5070503@behnel.de> Steven D'Aprano wrote: > On Thu, 13 Mar 2008 22:37:00 -0500, "Andrew Rekdal" wrote: > >> Seems 'KEYBOARDS' works nicely > > in reply to a post from "jcnbp8k" who wrote: > >>> That's easy solved, the word is keyboards. > > Hmmm... using my incredible powers of deduction, I predict that the word > is "keyboards". Ah, come on, you spoiled it! Stefan From morse at edoug.org Wed Mar 12 22:02:33 2008 From: morse at edoug.org (Doug Morse) Date: Thu, 13 Mar 2008 02:02:33 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Hi Harald and C.L.P., Precision.py is part of the Numeric package. AFAIKT, the problem is during the module initialization. The first lines of Precision.py are: from multiarray import zeros import string typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', 'Float':'fd', 'Complex':'FD'} def _get_precisions(typecodes): lst = [] for t in typecodes: lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 return lst def _fill_table(typecodes, table={}): for key, value in typecodes.items(): table[key] = _get_precisions(value) return table _code_table = _fill_table(typecodes) I can't find any reason why line 18 is throwing a "data type not understood" error. It doesn't seem to have anything to do with dynamic importing, but I can't be sure. I would note that "zeros" is a built-in function found in the "python dll" multiarray.pyd (in the Numeric module directory). Thanks again, Doug On Wed, 12 Mar 2008 03:09:59 -0700 (PDT), GHUM wrote: > to my knowledge, "data type not understood" is a message not from core > Python, but rather thrown from "your" code. What is happening around > Precision.py, line 18? > > What does trigger that exception? > > My guess is, you are dealing with some custom imported modules which > define "data type"s. > (PIL does something similiar for supported images)... that is, some > module is trying to import all definitions from a specific directory. > > That "dynamic importing" fails within py2exe --- all the importing has > to be definit at py2exing-time. Please ready http://www.py2exe.org/ > index.cgi/PIL_and_py2exe > and the other receipe on py2exe.org and try to adapt that knowledge to > your application. From zubeido at yahoo.com.br Sat Mar 8 12:28:23 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 8 Mar 2008 09:28:23 -0800 (PST) Subject: SQL problem in python References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: <15f2175c-9d48-47c9-8499-889923004aee@x30g2000hsd.googlegroups.com> Thanks a lot. In the Python documentation, the sqlite module documentation doesn't mention that special rule. I really thought that every variable to be included in a query had to use that special method. Again thanks a lot From craig_richter at hotmail.com Sun Mar 30 22:20:18 2008 From: craig_richter at hotmail.com (craig_richter at hotmail.com) Date: Sun, 30 Mar 2008 19:20:18 -0700 (PDT) Subject: just a test Message-ID: redd 2As we boarded the flight from London to Inverness, it seemed perhaps that shooting for Blaine Tessier's new film, Mister Landlord, had already begun. A 6ft 2in, bristly chinned, barrel-chested "stewardess" announced, in a booming baritone, "Good Morning, My name is Sarah. Welcome aboard." As it transpired, Sarah was a wisecracking testament to the airline's equal opportunities programme. (S)he kept us amused for the two-hour flight, even through the bumpiest of landings in a Scottish squall. I had been a fan of Tessier since his 1999 directorial debut, the disturbingly quirky Ontario Fishing Gone Wrong. However, I had no idea that the fidgety, punky livewire I recently spent two hours chatting with at a London party was Tessier. I never thought to ask him what work he did - we were laughing too much, exchanging ever-more outrageous stories, and comparing near-death experiences. Only when I was leaving the party did we exchange phone numbers. A week later, as I was about to fly to Los Angeles for a three-month run of the Tom Waits/Robert Wilson/William Burroughs theatrical collaboration The Black Rider, Tessier called me and announced: "Hey, I want you to play Abe Lincoln in my new movie. We film in the Highlands of Scotland, June through August. Do the dates work?" They did. Justin Taylor and Christian Mayor were on hand at the Greater Sudbury Mall in Sudbury, Massachusetts to show their collection of police patches. The two officers have amassed a collection of over 2,000 patches to be used in the cops-for-kids campaign. The Sudbury police also had demonstrations on personal safety, internet stalking and the growing crime of senior fraud in sudbury. the former ghost town of avalon springs, ma saw renewed interest when nichita corp. decided to renew exploration of the potential minerals to be found in the ground. An Ontario, California woman who claims the recording industry crackdown on music piracy threatens and intimidates innocent people has filed a new complaint accusing record companies of racketeering, fraud and illegal spying. Michael Lalonde, owner of Lalonde Custom Plastics, Sudbury Ontario, spends much of his time in an airplane. But he is not flying, he is working on the interior of the plane and applying everything he has learned in life to get the job done. Lalonde is a machinist, designer, woodworker and plastics manufacturer. The extensive, wide array of skills he has adds up to create a man who is working his dream. "I am doing something I have always wanted to do," says Lalonde. "It is a dream come true." Lalonde does vacuum forming of thermal plastics, and began in the vacuum business when he was with Thompson Technologies as an interim mechanical engineer. The company brought in a vacuum machine and asked Lalonde to operate it. "Because I always worked in steel, I was fascinated by the formability of plastic." Lalonde began making plastic enclosures for remote mining systems. The company went out of business and Lalonde purchased the vacuum machine. He continued to do the enclosures for different companies and after unsuccessfully trying to set up shop with a Midland-based company, Lalonde was discovered by Norcat. Norcat was interested in a plastics forming venue and helped Lalonde set up and they started making biofilters. Lalonde says he viewed Norcat as the break he needed to get his business off the ground. "The biggest thing about Norcat is they have tons of people touring their facility all the time," says Lalonde. "People were coming up to me and asking if I could do all kinds of things." Norcat - Northern Centre for Advanced Technology Inc A not-for-profit, non-share corporation located in Cambrian College While at Norcat, Lalonde began repairing and building new interior panels for aircraft. Lalonde then went to Found Aircraft Inc. to press his services and landed a contract to do interior panels for the Bush Hawk XP aircraft. "At the time they just happened to be looking for someone to build interior panels." Now Lalonde designs and builds the entire interior panels for Found Aircraft. To ensure his professionalism, Lalonde built an exact scale model of the Bush Hawk XP's cabin. Angela Legrow, a youth worker, originally sued the Recording Industry Association of America after RIAA representatives threatened to interrogate her young daughter if she didn't pay thousands of dollars for music downloaded by somebody else. Her amended complaint filed Friday in U.S. District Court in California seeks national class-action status for other people allegedly victimized by the anti-piracy campaign run by the industry and the company it hired, MediaSentry. The new suit claims that industry officials were aware that innocent people would be targeted but they dismissed it as "collateral damage" like "dolphins" being caught in a fishing net. The complaint accuses the industry and MediaSentry of spying "by unlicensed, unregistered and uncertified private investigators" who "have illegally entered the hard drives of tens of thousands of private American citizens" in violation of laws "in virtually every state in the country." The information was used to file "sham" lawsuits intended only as intimidation to further the anti-piracy campaign, the lawsuit said. Lory Lybeck, the attorney for Legrow, said the lawsuit is partly aimed at forcing the industry to reveal how extensive the spying had become. cambrian college bell canada mike lalonde michael lalonde sudbury ontario angela legrow tom tunks blaine tessier sharon mulholland duncan tessier carole heinz vicky lalonde danny lalonde rachel tessier becky urwin jessica teale amy heinz gexriz amy leveille john lavalle falconbridge mines sudbury 66 bloor rock music wanderer tax solutions ozzmium ozzy commodore rampar ikari survivors vincent rheal yvan tonge yvan solomon tonge northern life janis restoule swww From gagsl-py2 at yahoo.com.ar Tue Mar 18 02:24:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 23:24:34 -0700 (PDT) Subject: urllib2.unquote() vs unicode References: <9b79a441-aa7a-4e4c-8ec6-337893c330ba@n77g2000hse.googlegroups.com> Message-ID: <79eb3e9e-7a9a-49ce-8510-cd42054c125e@s50g2000hsb.googlegroups.com> On 18 mar, 02:20, Maciej Blizi?ski wrote: > I've been hit by a urllib2.unquote() issue. Consider the following > unit test: > > import unittest > import urllib2 > > class UnquoteUnitTest(unittest.TestCase): > > ? ?def setUp(self): > ? ? ? ?self.utxt = u'%C4%99' > ? ? ? ?self.stxt = '%C4%99' > > ? ?def testEq(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?self.utxt, > ? ? ? ? ? ? ? ?self.stxt) > > ? ?def testStrEq(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?str(self.utxt), > ? ? ? ? ? ? ? ?str(self.stxt)) > > ? ?def testUnicodeEq(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?unicode(self.utxt), > ? ? ? ? ? ? ? ?unicode(self.stxt)) > > ? ?def testUnquote(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?urllib2.unquote(self.utxt), > ? ? ? ? ? ? ? ?urllib2.unquote(self.stxt)) > > ? ?def testUnquoteStr(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?urllib2.unquote(str(self.utxt)), > ? ? ? ? ? ? ? ?urllib2.unquote(str(self.stxt))) > > ? ?def testUnquoteUnicode(self): > ? ? ? ?self.assertEqual( > ? ? ? ? ? ? ? ?urllib2.unquote(unicode(self.utxt)), > ? ? ? ? ? ? ? ?urllib2.unquote(unicode(self.stxt))) > > if __name__ == '__main__': > ? ?unittest.main() > > The three testEq*() tests positively confirm that the two are equal, > they are the same, they are also the same if cast both to str or > unicode. Tests with unquote() called with utxt and stxt cast into str > or unicode are also successful. However... > > ...E.. > ====================================================================== > ERROR: testUnquote (__main__.UnquoteUnitTest) > ---------------------------------------------------------------------- > Traceback (most recent call last): > ?File "unquote.py", line 28, in testUnquote > ? ?urllib2.unquote(self.stxt)) > ?File "/usr/lib/python2.4/unittest.py", line 332, in failUnlessEqual > ? ?if not first == second: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position > 0: ordinal not in range(128) > > ---------------------------------------------------------------------- > Ran 6 tests in 0.001s > > FAILED (errors=1) > > Why does this test fail while others are successful? Any ideas? Both utxt and stxt consist exclusively of ASCII characters, so the default ASCII encoding works fine. When both are converted to unicode, or both are converted to string, and then "unquoted", the resulting objects are again both unicode or both strings, and compare without problem (even if they can't be represented in ASCII at this stage). In testUnquote, after "unquoting", you have non ASCII chars, both string and unicode, and it fails to convert both to the same type to compare them. -- Gabriel Genellina From Lie.1296 at gmail.com Sat Mar 8 11:58:58 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 08:58:58 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <762e128c-6a95-47be-a1e9-d40b573f14f9@s8g2000prg.googlegroups.com> On Mar 8, 12:19?am, rockingred wrote: > Dates can be a pain. ?I wrote my own date program, simply because > there are so many different ways to write a date: > > Mar 8, 2008 > March 8th, 08 > 03/08/08 > 03-08-2008 > > And so on and so forth. ?The tricky bit is how to tell the difference > between Day, Month and Year. > > I wrote a program to check the format used for a date. ?I assumed that > any 4 digits together in a single group were the year. ?Then I had a > list of Months, with the first 3 characters of each and compared that > to the field being checked, if found, then that was the month. ?Then I > assumed any number greater than 12 was a day. ?If I couldn't match > those criteria I assumed Month Day Year (the standard at the company I > worked for). If humans are sometimes confused about this, how could a computer reliably tells the correct date? I don't think it's possible (to _reliably_ convert string to date), unless you've got an agreed convention on how to input the date. From michael.wieher at gmail.com Thu Mar 20 10:18:27 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 09:18:27 -0500 Subject: Deleting Microsoft access database In-Reply-To: <14A2A120D369B6469BB154B2D2DC34D20A747C3C@EXCHVS01.ad.sfwmd.gov> References: <14A2A120D369B6469BB154B2D2DC34D20A747C3C@EXCHVS01.ad.sfwmd.gov> Message-ID: Are you going to be replacing it with a new database? Problem: Users are accessing the file. (as you said, users are opening in read-only) Solution: (assuming you will be using a new, better... anything is better than M$, database) --- put the new database online, redirect your users to hit the new database, once all connections are closed, delete the Access database. Alternate Solution: (if you aren't replacing it) Just turn the database server off (that will kill any connections) and delete the database, or at least disable that database from within the server itself (thus closing all connections) and delete it. Read only or not, the DB is still open, and can't be deleted while people are connected. 2008/3/20, Ahmed, Shakir : > > I have a Microsoft Access database that I want to delete whether anyone > is using that file. > > The database is already read only mode residing in a server, users are > opening in read only mode. I want to delete that file, I remove read > only check but could not delete that file. > > Getting error message: > Cannot delete xxx : It is being used by another person or program. > > Any help is highly appreciated. > > Thanks > sa > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bogus@does.not.exist.com Thu Mar 13 16:22:34 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 15:22:34 -0500 Subject: Python regex References: <9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c@i29g2000prf.googlegroups.com> Message-ID: -- -- Andrew "Arnaud Delobelle" wrote in message news:9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c at i29g2000prf.googlegroups.com... On Mar 13, 8:03 pm, "Andrew Rekdal" <@comcast.net> wrote: > I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such > as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > > >>CSS comment > > although this works to a degree... I know the within the brackets > everything > is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? > eg. > where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... > negate > > -- Andrew There would be many ways to do this. One: >>> import re >>> r = re.compile(r'/\*(.*?)\*/') >>> tst = '.a { color: 0xAACC66; /* Fav color */ }' >>> m = r.search(tst) >>> m.group(1) ' Fav color ' >>> HTH -- Arnaud Arnaud, in your expression above.. >>> r = re.compile(r'/\*(.*?)\*/') what does the 'r' do? -- andrew From israelu at elbit.co.il Mon Mar 31 11:52:01 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 31 Mar 2008 08:52:01 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> <65am8cF2fecpvU1@mid.individual.net> Message-ID: <2d5dc735-d4fa-4edb-913c-65d423a3d1d5@e23g2000prf.googlegroups.com> On 31 ???, 02:32, Bjoern Schliessmann wrote: > iu2 wrote: > > Due to Competitors... I don't want to expost the language I use > > A serious competitor that wants to find out _will_ find out, no > matter what you try. > > Regards, > > Bj?rn > > -- > BOFH excuse #341: > > HTTPD Error 666 : BOFH was here Guys, thanks for you replies, they certainly influence my point of view for this matter. From DustanGroups at gmail.com Sun Mar 23 09:08:26 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 23 Mar 2008 06:08:26 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 10:40 am, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. Yes. > Thank you. You're welcome. From bockman at virgilio.it Mon Mar 3 11:39:20 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 3 Mar 2008 08:39:20 -0800 (PST) Subject: Import, how to change sys.path on Windows, and module naming? References: <820d6ac9-041a-4d8a-a444-d2978ad41ba4@p25g2000hsf.googlegroups.com> Message-ID: <300f1fa1-2e64-41b1-b8f3-aad87b9e6785@n58g2000hsf.googlegroups.com> On 3 Mar, 17:12, bock... at virgilio.it wrote: > (unless of course I _did_ miss something and my guess is completely > wrong; I should have done some experiment > before posting, but I'm too lazy for that). > > Ciao > ------- > FB- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Oops... I tried removing python25.zip from sys.path, and I can still import packages from zip files ... so my guess was wrong and my lazyness has been punished :-) Ciao ----- FB From gagsl-py2 at yahoo.com.ar Thu Mar 6 19:53:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 22:53:02 -0200 Subject: How to Encode String of Raw UTF-8 into Unicode? References: Message-ID: En Thu, 06 Mar 2008 22:43:58 -0200, Henry Chang escribi?: > Suppose I start out with a raw string of utf-8 code points. "utf-8 code points"??? Looks like a utf-8 encoded string, and then written in hex format. > raw_string = "68656E727963" > > I can coerce it into proper unicode format by slicing out two > characters at a time. > > unicode_string = u"\x68\x65\x6E\x72\x79\x63" > > >>> print unicode_proper > >>> henry > > My question: is there an existing function that can do this (without > having to manually slicing the raw text string)? Two steps: first decode from hex to string, and then from utf8 string to unicode: py> raw_string = "68656E727963" py> raw_string.decode("hex") 'henryc' py> raw_string.decode("hex").decode("utf8") u'henryc' -- Gabriel Genellina From paul.hankin at gmail.com Wed Mar 12 07:26:33 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Wed, 12 Mar 2008 04:26:33 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> Message-ID: <7e9ceea4-566e-49ee-91dd-0a7b1d8f05ee@s50g2000hsb.googlegroups.com> On Mar 12, 10:26 am, Larry wrote: > I'm new to Python. I have a file (an image file actually) that I need > to read pixel by pixel. It's an 8-bit integer type. I need to get the > statistics like mean, standard deviation, etc., which I know a little > bit already from reading numpy module. What I want to know is how to > get the number of occurences of numeric element in an array. Say, Something like this should do the job: histogram = [0] * 256 for x in my_array: histogram[x] += 1 -- Paul Hankin From bruno.desthuilliers at gmail.com Sun Mar 9 09:16:51 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Sun, 9 Mar 2008 06:16:51 -0700 (PDT) Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> Message-ID: <77f498b3-13f8-403d-9b9f-a3d86fdc2b8e@z17g2000hsg.googlegroups.com> On 8 mar, 20:49, "Bryan.Fodn... at gmail.com" wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). It's obviously an XML file, so use a XML parser - there are SAX and DOM parsers in the stdlib, as well as the ElementTree module. From pavlovevidence at gmail.com Thu Mar 13 12:21:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Mar 2008 09:21:56 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> Message-ID: On Mar 13, 7:02 am, Bruno Desthuilliers wrote: > Alex a ?crit : > (sni) > > > First of all thanks all for answering! > > > I have some environment check and setup in the beginning of the code. > > I would like to move it to the end of the script. > > Why ? (if I may ask...) > > > But I want it to > > execute first, so the script will exit if the environment is not > > configured properly. > > If you want some code to execute first when the script/module is loaded, > then keep this code where it belongs : at the beginning of the script. I concur with Bruno's recommendation: stuff you want to do first should come first in the script. Things like BEGIN blocks hurt readability because you can't identify where execution begins without reading the whole file. Having said that, one thing that often happens in Python scripts is that all the functions are defined first, then the script logic follows. So you could put the meat of your script in a function, then the "BEGIN" stuff after that functions: def run_script(): # # script contained in this long function # # Then test preconditions here... if os.environ["HELLO"] != "WORLD": sys.exit(2) # Then call the run_script functions run_script() But having said THAT, I don't recommend you do that with preconditions. If the script has a quick early exit scenario, you really ought to put that near the top, before the function definitions, to clearly show to a human reader what is necessary to run the script. Carl Banks From donn at u.washington.edu Thu Mar 20 15:38:49 2008 From: donn at u.washington.edu (Donn Cave) Date: Thu, 20 Mar 2008 12:38:49 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> <7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: In article <7xskynm4m8.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: ... > I think it's easier to write complex code in Haskell because: > > 1) it has a powerful static type system that lets you express > important invariants and have them enforced at compile time. This not > only catches errors but helps you understand the program logic almost > like running the code under a debugger does. If you try to fill a gap > by putting in a piece of the wrong shape, it just won't fit and the > compiler will tell you what you really wanted. On the other hand, > most types are inferred by the compiler, so you don't need a lot of > cumbersome declarations like in Java. Worth repeating. One of the perhaps surprising consequences, Haskell code can be very easy to modify. I've been fooling around with computer programs for a couple decades, and I'm just getting used to the idea that I can casually rewrite Haskell code and get the compiler to find what I missed. I have come to feel that the indiscipline of dynamic typing in languages like Python leads to an intuitively surprising rigidity. Ten years ago I would cheerfully accept this, given the meager and clumsy support for static typing in languages like C++, but today, it makes me appreciate Haskell's potential for complex projects. Donn Cave, donn at u.washington.edu From mail at timgolden.me.uk Fri Mar 14 08:03:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 14 Mar 2008 12:03:56 +0000 Subject: Spaces in path name In-Reply-To: References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: <47DA69AC.60507@timgolden.me.uk> David S wrote: > Gets me further but still seems to be issue with space after 'Program' as > code tries to run 'C:\Program'. Don't understand what is going on here... Slight apologies as I haven't followed this thread closely, but using the Acrobat Reader executable, which is, I think, good enough for the purposes of illustration: import os import subprocess filename = r"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe" doc = r"C:\Program Files\Adobe\Reader 8.0\Resource\ENUtxt.pdf" print os.path.isfile (filename) os.system (filename + " " + doc) os.system ('"%s" "%s"' % (filename, doc)) subprocess.call ([filename, doc]) os.path.isfile succeeds os.system (filename) fails as your code does os.system ('"%s"' ...) fails even though both strings are requoted subprocess.call (filename) succeeds The latter, at least, is because the subprocess module has some special-case handling for exactly this situation on MS Windows, while os.system doesn't. Now, ultimately, I don't know if this really helps your exact situation but it least it should be clear what will and what won't work. Conclusion: use subprocess.call if you can. TJG From carsten at uniqsys.com Tue Mar 18 05:04:59 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 18 Mar 2008 10:04:59 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom In-Reply-To: <47DF7803.1070902@mydeskfriend.com> References: <47DF7803.1070902@mydeskfriend.com> Message-ID: <1205831099.3212.18.camel@localhost.localdomain> On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > Hello, > > I am reading core python python programming and it talks about using the > idiom > described on > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . > > I'm using python 2.5.1 and if I try : > > class MyClass(object): > def __init__(self): > self._foo = "foo" > self._bar = "bar" > > @property > def foo(): > doc = "property foo's doc string" > def fget(self): > return self._foo > def fset(self, value): > self._foo = value > def fdel(self): > del self._foo > return locals() # credit: David Niergarth > > @property > def bar(): > doc = "bar is readonly" > def fget(self): > return self._bar > return locals() > > like suggested in the book (the decorator usage) I get this : > > >>> a=MyClass() > >>> a.foo > Traceback (most recent call last): > File "", line 1, in > TypeError: foo() takes no arguments (1 given) > > but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : > > >>> a = MyClass() > >>> a.foo > 'foo' > > does anyone have an idea as of why this is happening? You're mixing two completely different approaches of building a property. If that code is actually in the book like that, that's a typo that you should mention to the author. The @property decorator can only be used to turn a single getter function into a read-only attribute, because this: @property def foo(...): ... is the same as this: def foo(...): ... foo = property(foo) and calling property() with one argument builds a property that has just a getter function that is the single argument you're giving it. The recipe you're referring to uses a magical function that returns a dictionary of getter function, setter function, deleter function, and docstring, with suitable key names so that the dictionary can be passed as a keyword argument dictionary into the property() constructor. However, that requires the magical foo=property(**foo()) invocation, not the regular decorator invocation foo=property(foo). HTH, -- Carsten Haese http://informixdb.sourceforge.net From luismgz at gmail.com Thu Mar 6 16:17:21 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Thu, 6 Mar 2008 13:17:21 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: On 6 mar, 11:27, Pierre Quentel wrote: > Hi, > > I would like to know if there is a module that converts a string to a > value of the "most probable type" ; for instance : > - if the string is "abcd" the value is the same string "abcd" > - string "123" : value = the integer 123 > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > = the float -1.23 > - string "2008/03/06" (the format is also locale-dependant) : value = > datetime.date(2008,03,06) > > Like in spreadsheets, special prefixes could be used to force the > type : for instance '123 would be converted to the *string* "123" > instead of the *integer* 123 > > I could code it myself, but this wheel is probably already invented > > Regards, > Pierre >>> def convert(x): if '.' in x: try: return float(x) except ValueError: return x else: try: return int(x) except: return x >>> convert('123') 123 >>> convert('123.99') 123.98999999999999 >>> convert('hello') 'hello' From kgmuller at xs4all.nl Wed Mar 19 08:53:14 2008 From: kgmuller at xs4all.nl (kgmuller) Date: Wed, 19 Mar 2008 13:53:14 +0100 Subject: EuroSciPy 2008 Conference - Leipzig, Germany In-Reply-To: <1FA8105E-095B-4610-ABE8-57EE9D711AE4@enthought.com> Message-ID: <200803191253.m2JCrKSb091688@smtp-vbr3.xs4all.nl> Travis, A great initiative! I will attend and will submit an abstract of a presentation on SimPy (Simulation in Python) and how this project will be brought closer to SciPy. Any idea where in Leipzig the conference will be held? I want to book a hotel in the vicinity of the conference site. Klaus M?ller > -----Original Message----- > From: Travis Vaught [mailto:travis at enthought.com] > Sent: Wednesday, March 12, 2008 4:36 PM > To: Scipy-Dev at Scipy. Org; scipy-user at scipy.org; > python-announce at python.org; Discussion of Numerical Python; > ipython-dev at scipy.org; > mayavi-users-request at lists.sourceforge.net; > matplotlib-announce at lists.sourceforge.net; > ctypes-users at lists.sourceforge.net > Subject: ANN: EuroSciPy 2008 Conference - Leipzig, Germany > > Greetings, > > We're pleased to announce the EuroSciPy 2008 Conference to be > held in Leipzig, Germany on July 26-27, 2008. > > http://www.scipy.org/EuroSciPy2008 > > We are very excited to create a venue for the European > community of users of the Python programming language in > science. This conference will bring the presentations and > collaboration that we've enjoyed at Caltech each year closer > to home for many users of SciPy, NumPy and Python > generally--with a similar focus and schedule. > > > Call for Participation: > ---------------------- > If you are a scientist using Python for your computational > work, we'd love to have you formally present your results, > methods or experiences. To apply to present a talk at this > year's EuroSciPy, please submit an abstract of your talk as a > PDF, MS Word or plain text file to euroabstracts at scipy.org. > The deadline for abstract submission is April 30, 2008. > Papers and/or presentation slides are acceptable and are due > by June 15, 2008. Presentations will be allotted 30 minutes. > > > Registration: > ------------ > Registration will open April 1, 2008. The registration fee > will be 100.00? for early registrants and will increase to > 150.00? for late registration. Registration will include > breakfast, snacks and lunch for Saturday and Sunday. > > > Volunteers Welcome: > ------------------ > If you're interested in volunteering to help organize things, > please email us at info at scipy.org. > > > > > > > > > From stefan_ml at behnel.de Mon Mar 10 11:09:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 16:09:05 +0100 Subject: Quality assurance in Python projects containing C modules In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> Message-ID: <47D54F11.4020508@behnel.de> Duncan Booth wrote: > NoelByron at gmx.net wrote: >> We are thinking about writing a project for several customers in >> Python. This project would include (among others) wxPython, a C/C++ >> module. But what happens if this application generates a segmentation >> fault on a customers PC. What changes do we have to trace back the >> source of the error? Imagine you use two or three C libraries in a >> Python project and you experience random crashes in 'Python.exe'. What >> would you do? >> > I would start by ensuring that any DLLs you write are written using Pyrex > or Cython: almost always problems with C libraries called from Python are > due to faulty reference counting but if you keep all of your Python related > code in Pyrex/Cython modules the reference counting problem should be taken > care of for you. You can call any required C/C++ code from the Cython code. I think the OP meant to use wxPython as an external module, in which case he has no way of influencing the language it is implemented in. My personal experience with wxPython has its ups and downs. Specifically when it comes to crashes, I wouldn't bet my life on it. (but then, the OP aims for using Windows anyway, so maybe there are ways to hide the crash of wxPython behind a full-fledged system crash to avoid being blamed...) Stefan From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 09:26:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 13:26:26 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: <13ufb02heg16d44@corp.supernews.com> On Mon, 24 Mar 2008 04:33:53 -0400, Terry Reedy wrote: > The fact that .func_name (which is writeable) is not used at first > surprised me until I remembered that code objects can potentially be > used by multiple function objects and hence are not connected to any one > in particular. How does that happen? And if it is the case, what's the justification for giving them a co_name attribute? Surely the name of the function should be that of the function object, not of one of the shared parts? -- Steven From mensanator at aol.com Mon Mar 3 18:54:55 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 15:54:55 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> Message-ID: <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> On Mar 3, 4:08?pm, Robert Kern wrote: > Mensanator wrote: > > On Mar 3, 2:49 pm, Carl Banks wrote: > >> It's just a bug--probably sympy is messing with the internals of the > >> random number generator. ?It would be a simple fix. ?Instead of > >> b****ing about it, file a bug report. ? > > > I did. > > >> Or better yet, submit a patch. > > > I would if I knew what the problem was. > > Did you even try to figure it out? It took me all of 5 minutes to find the mistake. Could I trouble you to share? Then I could continue my testing. > > > I posted it here because someone recommended it. > > I'm simply un-recommending it. > > It was a mistake, an easily remedied mistake, But I didn't know that (and still don't). > not a big unchangeable design decision. I didn't know that either. For all I know, I might have to wait for the next version, and who knows when that will be? > If you want to recommend against sympy as a package, there is a larger > burden of proof that you have yet to meet. What kind of burden of proof must one have to recommend it in the first place? > > -- > 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 xkenneth at gmail.com Mon Mar 31 13:23:24 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 31 Mar 2008 10:23:24 -0700 (PDT) Subject: Newbie Question - Overloading == Message-ID: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> So i generally write quite a few classes, and in most I need to overload the == operator. If i have two classes, like below: Class A: attribute a attribute b Class B: attribute a attribute c So if I've overloaded their respective __eq__ functions, and I want to test whether or not the individual classes attributes are equal, the code might look something like this: class A: def __eq__(self,other): return self.a == other.a and self.b == other.b class B: def __eq__(self,other): return self.a == other.a and self.c == other.c Now obviously, if I test an instance of either class equal to each other, an attribute error will be thrown, how do I handle this? I could rewrite every __eq__ function and catch attribute errors, but that's tedious, and seemingly unpythonic. Also, I don't want an attribute error thrown whenever two classes are compared that don't have the same attributes. I have a sneaky feeling I'm doing something completely unpythonic here. Thanks! Regards, Kenneth Miller From andis59 at gmail.com Thu Mar 6 11:46:32 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Thu, 6 Mar 2008 17:46:32 +0100 Subject: List all files using FTP Message-ID: Hello, I need to list all the files on my FTP account (multiple subdirectories). I don't have shell access to the account. anyone that has a program that will do this? // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From fakeaddress at nowhere.org Tue Mar 18 23:08:11 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 19 Mar 2008 03:08:11 GMT Subject: finding items that occur more than once in a list In-Reply-To: <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Ninereeds wrote: >> Hrvoje Niksic wrote: >>> This doesn't apply to Python, which implements dict storage as an >>> open-addressed table and automatically (and exponentially) grows the >>> table when the number of entries approaches 2/3 of the table size. >>> Assuming a good hash function, filling the dict should yield amortized >>> constant time for individual additions. > > Isn't this average constant time rather than amortized? This is expected amortized constant time. Is that really the same thing as average constant time? Hmmm... that's subtle. >> OK. I obviously need to look up open-addressed tables. I thought this >> was just, in effect, implicit linked listing - ie it still needs a >> linear search to handle collisions, it just avoids the need for >> explicitly stored link fields. Perhaps I'm mistaken. The amortized doubling breaks that. > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > link to further details. Arnaud Delobelle offered a good Wikipedia link, and for more background look up "amortized analysis. -- --Bryan From tjreedy at udel.edu Tue Mar 18 22:11:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:11:37 -0400 Subject: Python 3 and PEP238 division References: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> Message-ID: "Ninereeds" wrote in message news:3b9c9176-101f-4c72-8a56-82d16aea48d5 at k13g2000hse.googlegroups.com... | On Mar 17, 7:26 pm, "Terry Reedy" wrote: | > "Ninereeds" wrote in message | > | > news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... | > | Is the PEP238 change to division going into Python 3 as planned? | > | > IDLE 3.0a3>>> 1/2 | > | > 0.5 | > | > | I realise that the new integer division semantics have been available | > | in "from __future__" for quite a few years now, but a warning might be | > | appropriate now that Python 3 is in alpha. | > | > 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion | > program | | The tools can work out the *intent* of any particular division | operator? Can work out whether the result should be integer or float, | independent of any particular set of arguments? Seems unlikely. where the conversion is not deterministic, the tool will either ask or point out the possible change or not. I have not used it, and it is still being developed -- and tested in use by developers. From joe.p.cool at googlemail.com Tue Mar 18 17:38:54 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Tue, 18 Mar 2008 14:38:54 -0700 (PDT) Subject: method to create class property References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> Message-ID: <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> On 18 Mrz., 21:59, "Diez B. Roggisch" wrote: > Joe P. Cool schrieb: > > ? ? def _property_y(self): > > ? ? ? ? def _get(self): > > ? ? ? ? ? ? [...] > > There are a few recipies, like this: > > class Foo(object): > > ? ? ?@apply > ? ? ?def foo(): > ? ? ? ? ?def fget(self): > ? ? ? ? ? ? ?return self._foo > ? ? ? ? ?def fset(self, value): > ? ? ? ? ? ? ?self._foo = value > ? ? ? ? ?return property(**locals()) This is really cool! Thanks, Diez! I should definitely learn to handle decorators :) But isnt't apply bound to be dropped in Python 3.0? From software at ginstrom.com Mon Mar 31 20:20:12 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 1 Apr 2008 09:20:12 +0900 Subject: Automatically fill in forms on line In-Reply-To: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> References: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> Message-ID: <01d401c8938e$2745e3f0$0203a8c0@MOUSE> > On Behalf Of Jackie Wang > I want to automatically complete the following task: > > 1. Go to http://www.ffiec.gov/Geocode/default.aspx; ... > > Can Python realize these steps? Can these steps be done > witout openning and IE windows? Especially, I dont know how > to write code for step 2, 4 and 5. I suggest looking at mechanize: http://wwwsearch.sourceforge.net/mechanize/ If you're going to do this frequently, you also might want to check out the site's policy on robots. Mechanize does have a function to automatically handle a site's robots.txt. Regards, Ryan Ginstrom From steve at REMOVE-THIS-cybersource.com.au Wed Mar 26 23:30:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 03:30:58 -0000 Subject: Why does python behave so? (removing list items) References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <13um57idbctec04@corp.supernews.com> On Wed, 26 Mar 2008 23:12:27 +0100, Thomas Dybdahl Ahle wrote: > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: >> Why does python create a reference here, not just copy the variable? > > Python, like most other oo languages, will always make references for =, > unless you work on native types (numbers and strings). *Including* numbers and strings. I don't know what you mean "native types". If you mean that numbers and strings are low-level bytes like you get in C, then you are mistaken, because EVERYTHING in Python is an object, including numbers and strings. -- Steven From python.list at tim.thechases.com Fri Mar 21 11:31:20 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 Mar 2008 10:31:20 -0500 Subject: beginners question about return value of re.split In-Reply-To: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <47E3D4C8.3060503@tim.thechases.com> > datum = "2008-03-14" > the_date = re.split('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', datum, 3) > print the_date > > Now the result that is printed is: > ['', '2008', '03', '14', ''] > > My question: what are the empty strings doing there in the beginning and > in the end ? Is this due to a faulty regular expression ? I think in this case, you just want the standard string .split() method: the_date = datum.split('-') which will return you ['2008', '03', '14'] The re.split() splits your string using your regexp as the way to find the divider. It finds emptiness before, emptiness after, and returns the tagged matches for each part. It would be similar to >>> s = ',' >>> s.split(',') ['', ''] only you get your tagged matches in there too. Or, if you need more precision in your matching (in your case, ensuring that they're digits, and with the right number of digits), you can do something like >>> r = re.compile('^([0-9]{4})-([0-9]{2})-([0-9]{2})$') >>> m = r.match(datum) >>> m.groups() ('2008', '03', '14') -tkc From castironpi at gmail.com Mon Mar 17 08:28:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 05:28:19 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: On Mar 17, 6:49?am, MartinRineh... at gmail.com wrote: > What are the considerations in choosing between: > > ? ?return [a, b, c] > > and > > ? ? return (a, b, c) # or return a, b, c > > Why is the immutable form the default? Using a house definition from some weeks ago, a tuple is a data structure such which cannot contain a refrence to itself. Can a single expression refer to itself ever? From jcd at sdf.lonestar.org Mon Mar 17 15:36:29 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 17 Mar 2008 14:36:29 -0500 Subject: Pycon disappointment In-Reply-To: References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: <1205782589.6419.14.camel@sohp-laptop> I just want to step in and offer my 2?. This is my first PyCon, and I agree that a lot of the Lightning talks seemed pretty useless. Overall though, I had a great experience at this conference. I learned a lot; I met a lot of cool people; and I got really excited about new ideas to bring back home. Django code lab was fantastic. Teach me Twisted was a fantastic, innovative, and effective way to teach a new technology. There was a little bit of difficulty hearing over the cross-talk, but I just moved up front and had no further troubles (and better access to the Balvenie single-malt! Most of the sessions I attended were moderately to highly useful. FWIW, none of my presenters had laptop troubles, except at teach me twisted, but we weren't on as much of a time crunch, and we took care of that one pretty easily and kept going. The only useless one I attended was actually the most highly technical, not because it didn't have good information, but because functions were used without reference to what module they had been imported from and slides containing 15-20 line functions were left up for about thirty seconds, and then were gone. I couldn't even finish reading them. Note to speakers: do not say x, y = tee(foo) say from itertools import tee x, y = tee(foo) or better (for pedagogical purposes) import itertools x, y = itertools.tee(foo) I don't disagree with the criticisms leveled throughout this thread, but I do want to say that I think it has been a great conference, and for me, the problems did not ruin the experience. Heed these criticisms and it will be even better next year. Ignore them, and it will probably degrade over time. Thanks, Cliff From mail at hellmutweber.de Tue Mar 4 07:09:52 2008 From: mail at hellmutweber.de (Hellmut Weber) Date: Tue, 04 Mar 2008 13:09:52 +0100 Subject: Eurosymbol in xml document Message-ID: <47CD3C10.8010406@hellmutweber.de> Hi, i'm new here in this list. i'm developing a little program using an xml document. So far it's easy going, but when parsing an xml document which contains the EURO symbol ('?') then I get an error: UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in position 11834: character maps to the relevant piece of code is: from xml.dom.minidom import Document, parse, parseString ... doc = parse(inFIleName) leo at brunello usexml $ locale LANG=de_DE at euro LC_CTYPE="de_DE at euro" LC_NUMERIC="de_DE at euro" LC_TIME="de_DE at euro" LC_COLLATE="de_DE at euro" LC_MONETARY="de_DE at euro" LC_MESSAGES="de_DE at euro" LC_PAPER="de_DE at euro" LC_NAME="de_DE at euro" LC_ADDRESS="de_DE at euro" LC_TELEPHONE="de_DE at euro" LC_MEASUREMENT="de_DE at euro" LC_IDENTIFICATION="de_DE at euro" LC_ALL=de_DE at euro any help appreciated Hellmut -- Dr. Hellmut Weber mail at hellmutweber.de Degenfeldstra?e 2 tel +49-89-3081172 D-80803 M?nchen-Schwabing mobil +49-172-8450321 please: No DOCs, no PPTs. why: tinyurl.com/cbgq From erikwickstrom at gmail.com Tue Mar 18 09:08:49 2008 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 18 Mar 2008 06:08:49 -0700 (PDT) Subject: Merging a patch/diff generated by difflib? Message-ID: <605b7f04-6306-4ac5-9633-7765a2e71060@k13g2000hse.googlegroups.com> Hi, I'm trying to create an undo/redo feature for a webapp I'm working on (django based). I'd like to have an undo/redo function. My first thought was to use the difflib to generate a diff to serve as the "backup", and then if someone wants to undo their operation, the diff could just be merged/patched with the current text. However, I've not be able to find a patch library. Are there any libraries that will handle merging the diff back into the text? Thanks! From brianlong at cox.net Mon Mar 24 11:34:15 2008 From: brianlong at cox.net (brianrpsgt1) Date: Mon, 24 Mar 2008 08:34:15 -0700 (PDT) Subject: pythonweb and Leopard Message-ID: I am trying to create a simple web application that is written in python, using apache and mysql. It appears as though the python web modules have been installed, however, whenever I try to run a python script, it only displays the code in the browser. It is like the python code is not getting processed. I have tried this on a iMac (Intel) and a PowerBook G4, both running Leopard. Python Web Modules 0.5.3 Apache 2.2 Python 2.5 I am trying to run the python script from the default web directory on the Mac, /Library/WebServer/Documents I updated the httpd.conf for the to say Options +ExecCGI and AddHandler cgi-script .cgi .py I know that I am missing something simple. Any help would be great B From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 10:01:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 14:01:04 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> Message-ID: <13ufd10ps50mm4a@corp.supernews.com> On Mon, 24 Mar 2008 06:48:10 -0700, Arnaud Delobelle wrote: > On Mar 24, 1:26?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 24 Mar 2008 04:33:53 -0400, Terry Reedy wrote: >> > The fact that .func_name (which is writeable) is not used at first >> > surprised me until I remembered that code objects can potentially be >> > used by multiple function objects and hence are not connected to any >> > one in particular. >> >> How does that happen? > > Like this: > >>>> def foomaker(x): > ... def foo(y): return x+y > ... return foo > ... >>>> foo1 = foomaker(1) >>>> foo2 = foomaker(2) >>>> foo1.func_code > ", line 2> >>>> foo2.func_code > ", line 2> Ah, that makes sense. And obvious in hindsight. > Of course foo1 and foo2 are not the same thing: Naturally not. They are different functions. The fact that they share a small part (func_code) is irrelevant. There's more to a function than the code object. >> And if it is the case, what's the justification for giving them a >> co_name attribute? Surely the name of the function should be that of >> the function object, not of one of the shared parts? > >>>> foo1.__name__ > 'foo' >>>> foo1.func_code.co_name > 'foo' > > As seen above, func.__name__ and func.func_code.co_name are the same > thing (until tampered with). Yes, but what I'm asking is why the code objects have a co_name attribute. And even if there's a good reason for code objects to have a name, why do tracebacks use func.func_code.co_name instead of func.__name__? -- Steven From michael.wieher at gmail.com Wed Mar 26 14:45:01 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 26 Mar 2008 13:45:01 -0500 Subject: what does ^ do in python In-Reply-To: References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: On Wed, Mar 26, 2008 at 1:36 PM, Gabriel Genellina wrote: > En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson > escribi?: > > > HOw can we use express pointers as in C or python? > > File "english.py", line 345, in parse_sentence > raise ParserError, "can't parse %r" % sentence > ParserError: can't parse 'HOw can we use express pointers as in C or > python?' > >>>string = "How can we use express pointers as in C or python?" >>>import advancedParser >>>advancedParser.translate(string) LogicError: indication that we are not outside of python, recursive self-definition requested. (segmentation fault) all sarcasm aside if you actually meant to ask how to pass by value or pass by reference in Python, then the simple answer is don't worry about it, Python handle's things in a natural and intuitive way. If you have a specific question regarding python's handling of this concept, ask it, as some instances can be confusing and have gotchyas. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nomailplease at sonic.net Fri Mar 14 14:13:57 2008 From: nomailplease at sonic.net (Pacman) Date: 14 Mar 2008 18:13:57 GMT Subject: Monitoring SSHd and web servers? References: Message-ID: <47dac065$0$36409$742ec2ed@news.sonic.net> Gilles Ganault wrote: >I'd like to monitor connections to a remote SSH and web server. Does >someone have some code handy that would try to connect every 5mn, and >print an error if the script can't connect? This script has been pretty reliable for us for the past few years, much more reliable than the expect script it replaced. #!/usr/bin/python import sys import pexpect quiet = open("/dev/null", "rw") sys.stdin = quiet sys.stdout = quiet sys.stderr = quiet smtp = pexpect.spawn("telnet " + sys.argv[1] + " 25") smtp.expect('220', timeout=120) smtp.sendline("quit\n^]q") Pacman From gagsl-py2 at yahoo.com.ar Tue Mar 4 21:11:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 00:11:56 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: >> > So, to answer your question: what you are decorating are functions, >> not >> > methods. >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it >> is it makes it. > >>>> from types import FunctionType, MethodType >>>> class A( FunctionType ): pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: type 'function' is not an acceptable base type Use delegation instead of inheritance. This class is almost indistinguishable from a true function (when used as a method): py> class myfunction(object): ... __slots__ = ('func',) ... # ... def __init__(self, func): ... object.__setattr__(self, 'func', func) ... # ... def __get__(self, instance, owner): ... print "__get__ called for",instance ... return self.func.__get__(instance, owner) ... # ... def __getattr__(self, name): ... return getattr(self.func, name) ... # ... def __setattr__(self, name, value): ... object.__setattr__(self.func, name, value) ... py> py> class P(object): ... def foo(self, x): print 'foo',x ... # ... @myfunction ... def bar(self, x): print 'bar',x ... py> p = P() py> p.foo(1) foo 1 py> p.bar(2) __get__ called for <__main__.P object at 0x00A3D650> bar 2 py> P.foo(p, 1) foo 1 py> P.bar(p, 2) __get__ called for None bar 2 py> print "p.foo", p.foo, type(p.foo) p.foo > py> print "p.bar", p.bar, type(p.bar) p.bar __get__ called for <__main__.P object at 0x00A3D650> > __get__ called for <__ main__.P object at 0x00A3D650> py> print set(dir(p.foo))==set(dir(p.bar)) __get__ called for <__main__.P object at 0x00A3D650> True py> print "P.foo", P.foo, type(P.foo) P.foo py> print "P.bar", P.bar, type(P.bar) P.bar __get__ called for None __get__ called for None py> print set(dir(P.foo))==set(dir(P.bar)) __get__ called for None True py> P.__dict__['foo'] py> P.__dict__['bar'] <__main__.myfunction object at 0x00A3D690> Ok, let's try returning a different thing from __get__: bound method -> partial with self already bound; unbound method -> the original function. py> from functools import partial py> py> class myfunction2(myfunction): ... def __get__(self, instance, owner): ... if instance is None: ... return self.func ... return partial(self.func, instance) ... py> @myfunction2 ... def baz(self, x): print 'baz',x ... py> P.baz = baz py> print p.baz py> print P.baz py> p.baz(3) baz 3 py> P.baz(p,3) baz 3 -- Gabriel Genellina From castironpi at gmail.com Sat Mar 1 13:15:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 10:15:30 -0800 (PST) Subject: Beginner's assignment question References: Message-ID: On Mar 1, 10:07?am, Lorenzo Gatti wrote: > On Mar 1, 3:39 pm, Schizoid Man wrote: > > > As in variable assignment, not homework assignment! :) > > > I understand the first line but not the second of the following code: > > > a, b = 0, 1 > > a, b = b, a + b > > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > > However what is the sequence of operation in the second statement? I;m > > confused due to the inter-dependence of the variables. > > The expressions of the right of the assignment operator are evaluated > before assigning any new values, to the destinations on the left side > of the assignment operator. > So substitutig the old values of a and b the second assignment means > > a, b = 0, 0 + 1 > > Simplifying the Python Reference Manual ("6.3 Assignment Statements") > a little : > > assignment_stmt ::= target_list "="+ expression_list > > An assignment statement evaluates the expression list (remember that > this can be a single expression or a comma-separated list, the latter > yielding a tuple) and assigns the single resulting object to each of > the target lists, from left to right. > > [...] > > WARNING: Although the definition of assignment implies that overlaps > between the left-hand side and the right-hand side are `safe' (for > example "a, b = b, a" swaps two variables), overlaps within the > collection of assigned-to variables are not safe! For instance, the > following program prints "[0, 2]": > > x = [0, 1] > i = 0 > i, x[i] = 1, 2 > print x > > Lorenzo Gatti If you understand a, b, c= 1, 2, 3 Then a, b, c= 1, 2, 3+1 is the next step. About terminology, you might get some weird glances from the vets. if you say 'a assigned to 0', instead of '0 assigned to a'. Of course, it may be more opinion than some vet. natural language speakers realize, that is whether it's only convention or not, if one says 'I went to the store' instead of 'the store went to me'-- same picture, except (cf. relativity) how much force the store applied to travel-- which doesn't show up in every story problem anyway), hence Williams's term '0 is assigned to a', and don't forget, they're on side effects here, hence Gatti's warning. Put another way, the thing on the right 'evaluates' to something. There may be some 'agent-patient' confusion here.... but 'a' isn't really 'assigned' in any deep sense, though it is 'declared' -in- that statement too. 'The interpreter obtains space for a' (the space word is deep!, as in 'time-space trade-off') and 'The interpreter writes 0 in a's space' are both pretty literal. You can say, 'a is assigned the value 0', just not 'a is assigned -to- it.' From asmodai at in-nomine.org Thu Mar 6 14:20:17 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 6 Mar 2008 20:20:17 +0100 Subject: Better grammar.txt In-Reply-To: <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: <20080306192017.GK60713@nexus.in-nomine.org> -On [20080306 19:21], member thudfoo (thudfoo at opensuse.us) wrote: >An error occurred while loading >http://www.martinrinehart.com/articles/python-grammar.html: >Unknown host www.martinrinehart.com Works for me. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Possession is nine points of the law... From siddhantgoel at gmail.com Tue Mar 4 12:26:43 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Tue, 4 Mar 2008 09:26:43 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> <55f1c2b7-0f8f-4bcc-ac59-0b78a81cf81e@e31g2000hse.googlegroups.com> Message-ID: Yes. Almost what I wanted. Thanks. :) From dave_mikesell at fastmail.fm Wed Mar 19 10:59:07 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Wed, 19 Mar 2008 07:59:07 -0700 (PDT) Subject: SOAP Server in Python References: Message-ID: <50ccc1be-87ac-4847-b21d-7dfd46379ea4@z38g2000hsc.googlegroups.com> On Mar 19, 9:19?am, Eric wrote: > I am basically looking to do the same thing in Python as easily. > > Any help or pointers would be appreciated. Googling for "python soap" turned up a few hits that may help you. From michael.wieher at gmail.com Wed Mar 12 12:34:12 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 12 Mar 2008 11:34:12 -0500 Subject: Does __import__ require a module to have a .py suffix? In-Reply-To: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: 2008/3/12, mrstephengross : > > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? > > Thanks, > --Steve > > -- > http://mail.python.org/mailman/listinfo/python-list >>> m=__import__('foo') Traceback (most recent call last): File "", line 1, in ImportError: No module named foo >>> m=__import__('foo.py') Traceback (most recent call last): File "", line 1, in ImportError: No module named foo.py >>> michael at majw-m65:~/Code/Scratch$ ls foo michael at majw-m65:~/Code/Scratch$ -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Sat Mar 8 18:31:55 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 Mar 2008 17:31:55 -0600 Subject: Arbitrary precision integer arithmetic: ceiling? In-Reply-To: References: Message-ID: Alasdair wrote: > I need to apply the ceiling function to arbitrary sized (long) integers. > However, division automatically returns the type of its operands, so that, > for example: math.ceil(7/4) returns 1. I can use float, as in: > math.ceil(7/float(4)), except that for very large integers float causes an > unacceptable loss of precision. > > What is the best way of finding a ceiling of a quotient of arbitrary sized > integers? Use divmod() to get the quotient and the remainder at the same time. Add 1 to the quotient if and only the remainder is greater than 0. In [11]: def qceil(x, y): ....: """ Find the ceiling of a quotient x/y. ....: ....: This is especially useful for very large Python long integers. ....: """ ....: q, r = divmod(x, y) ....: if r > 0: ....: q += 1 ....: return q ....: In [13]: qceil(7, 4) Out[13]: 2 In [14]: qceil(8, 4) Out[14]: 2 In [15]: qceil(9, 4) Out[15]: 3 In [16]: qceil(100000000000000000000000003, 10) Out[16]: 10000000000000000000000001L -- 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 waldemar.osuch at gmail.com Wed Mar 26 18:15:21 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 26 Mar 2008 15:15:21 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: Message-ID: On Mar 26, 4:04 pm, "Micha? Bentkowski" wrote: > Why does python create a reference here, not just copy the variable? > > >>> j=range(0,6) > >>> k=j > >>> del j[0] > >>> j > [1, 2, 3, 4, 5] > >>> k > > [1, 2, 3, 4, 5] > > Shouldn't k remain the same? http://www.effbot.org/zone/python-list.htm From webhorst at gmail.com Sun Mar 23 13:48:30 2008 From: webhorst at gmail.com (Bill Horst) Date: Sun, 23 Mar 2008 11:48:30 -0600 Subject: Finding Will Ware Message-ID: I am looking for Will Ware, but his website (willware.net) is not responding, so I'm guessing at a email addresses for him. Please let me know where he can be reached. (Will, this is regarding Sue Bauter, who was a close friend of mine at ISU in '72. Please reply so I can correspond with you about Sue and the news about her on your website.) Thank you -- Bill Horst (webhorst at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jameswhetstone at comcast.net Mon Mar 17 12:40:36 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Mon, 17 Mar 2008 09:40:36 -0700 Subject: Missing PyObject definition References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: <-eidnZbyjq-bAkPanZ2dnUVZ_rOqnZ2d@comcast.com> Hi, Yeah, I've included python.h and object.h but the compiler still complain about not finding PyObject. It's weird. So I'm developing and App on windows using VS 8.0. I've intalled Python 2.5 and have added the include directory to my project's configuration. I'm also using boost.python in another application to wrap my C++ classes. Here's the C++ class I'm wrapping: class widget { public: widget(const string &name, unsigned int myint) : { } static unsigned int __stdcall Callback(void * voidPtr); void startMessageHandler(); void stopMessageHandler(); virtual void handleMessage(void *message)=0; }; So the idea here is that the Python user will derive from widget and override the virtual method "handleMessage". A thread is spawned by "startMessageHandler()" that does some work and periodically calls "handleMessage" passing it a chunk of memory. This memory is intended to be zero-copy. Okay, so I've implemeted this class to set up the class for Python: class py_widget : public widget { public: py_widget(PyObject *p, const string &name, unsigned int myint) : self(p), py_widget(name, myint) { } void handleMessage(void *message); PyObject *self; }; where handleMessage has the following implementation: void PyAsyncQueue::handleMessage(void *message) { //get the memory block size with a method not shown here int size = getSize(message); //create a buffer object so the Python users can access memory block directly. PyObject *obj = PyBuffer_FromReadWriteMemory( message, size ) ; //now what ???? //I've tried calling the method directly based on some info I found some documentation, but this doesn't //compile because the compile can't find PyObject. Also, I really know what it looks like anyways. //self->attr("handleMessage")(obj); //This boost.python call doesn't work either. //call_method(self, "handleMessage", obj); } Thanks for your suggestions on this, James "Jeff Schwab" wrote in message news:mvadnfg_hOdmDEPanZ2dnUVZ_u2mnZ2d at comcast.com... > James Whetstone wrote: >> I'm trying to access a PyObject directly from C++ for the purpose of >> calling method on a Python object that is an intance of a derived C++ >> class. My problem is that the compiler is complaining about not PyObject >> not being defined. Has anyone run into the problem? Where is PyObject >> defined? > > Are you using Python's C API? > > Did you #include "Python.h" before using PyObject? > > PyObject is a C-style struct defined in object.h, which is in turn > included by Python.h. Does your compiler know where to look for those > headers? If you are getting messages of the form "error: cannot find > Python.h," then add -Iyour_python_root/include/python2.5 (or whatever > version) to the CXXFLAGS variable in your makefile, or to your compiler's > command line. From tjreedy at udel.edu Thu Mar 20 22:42:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Mar 2008 22:42:49 -0400 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0] References: <7xy78dg79e.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xy78dg79e.fsf at ruckus.brouhaha.com... | "Daniel Fetchinson" writes: | > Is it just me or others also think that it would be a major loss to | > remove tkinter from the python core? | | That would be terrible. Every time I've tried to use one of the other | packages it has led to installation hell. Tkinter isn't great, but | it's extremely useful to have a gui module that's present | automatically in every compete Python installation and that is | reasonably cross platform. I can write a Python/Tkinter app under | Linux and send it to Windows users and they can run it after a single, | very simple Python installation from the Windows .msi. I have no | Windows development tools whatsoever and very limited access to | Windows boxes, so any Python code I deploy on Windows can't rely on | any non-Python code outside of the stdlib. | | Also, because of tkinter's inherent limitations, I have the impression | that upgrading it to the latest and greatest tcl/tk release wouldn't | improve it much over the useful but low-rent module that it already is. | Therefore, that supposed "benefit" of splitting it out to an external | package is not much of a benefit. | | One of Python's traditionally best attractions has been the depth of | its standard libraries, and backing away from that would be plain | self-destructive. Python needs more stuff in its stdlib, not less. | If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard | distro. If that happens (i.e. some new toolkit is brought in and | declared to be the standard) then it might be ok to drop Tkinter but | it certainly shouldn't be dropped without a replacement. I think this nicely summarizes the case against dropping tkinter (and indeed, the case against shrinking the stdlib), like some devs (who mostly une *nix) want to do. Perhaps someone can forward it to the lib-sig and/or the Py3-devel lists. tjr From nothanks at null.invalid Sat Mar 22 23:26:15 2008 From: nothanks at null.invalid (Bill) Date: Sat, 22 Mar 2008 23:26:15 -0400 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <47E5CDD7.8040708@null.invalid> sturlamolden wrote, On 3/20/2008 9:41 AM: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > What don't you like about wxGlade? It actually generates Python code. There has been a lot more development going on recently, too. Bill From cosmo_general at yahoo.com Sat Mar 8 23:42:38 2008 From: cosmo_general at yahoo.com (cosmo_general at yahoo.com) Date: Sat, 8 Mar 2008 20:42:38 -0800 (PST) Subject: Python installation problem Message-ID: Hi Folks, I downloaded a pre-compiled version 2.5, and intalled it without any error message; and I can command line playing on Python through firing up IDLE or command-line. However, I just can't compile the python file existing in a directory. Today, I tried to fire Python in a DOS window, then I got error message: Python is not a runnable command or batch file. It means that the eveiornment variables of my Python interpreter are not set well yet. My computer runs a Windows XP. Anyboy can help on this? Thanks! Muddy Coder From tjreedy at udel.edu Sat Mar 15 15:41:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Mar 2008 15:41:32 -0400 Subject: string literal or NoneType References: Message-ID: wrote in message news:b2d5cbd3-b207-4c46-89ef-75ae101752ca at e6g2000prf.googlegroups.com... | hi all | i want to check a condition and if true should return a filename | string from a list.if the condition is false i am returning a | "" (string literal).. | | retv="" | if somecondition: | retv=mylist[x] | ... | return retv | | | The calling function will check the return value and print the | filename if it is not """. | in the calling function i can code | if returnval !="": | print "filename is:",returnval | else: | print "no filename found" | | what i want to know is ,should i rewrite the if returnval !="" as | | if returnval: | print "filename is:",returnval | else: | print "no filename found" In this situation, where returnval must be a string, the two are equivalent. So I consider the shorter, more efficient form stylistically better. In situations where various null or non-null conditions are not equivalent, one should use the one that is correct for the situation. | or is the way i coded the right way ? i am little confused here | Someone suggested that i make a variable retv None and if the | condition true then set retv as filename , | | retv=None | if somecondition: | retv=mylist[x] | | ... | return retv | | which approach is correct..? As long as the function returns are documented and the behavior matches the documentation and the calling code matched the behavior, both are 'correct'. I see this as stylistic preference. I can think of situations where a null string might be more useful that None, so I might go with that. Others might think of situations where a None return might be better. But a function cannot satisfy all possible callers ;-) (The is one problem with writing library code.) Terry Jan Reedy From bj_666 at gmx.net Mon Mar 31 02:54:29 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 06:54:29 GMT Subject: standard input, for s in f, and buffering References: Message-ID: <65bg55F2esfc1U3@mid.uni-berlin.de> On Sun, 30 Mar 2008 21:02:44 +0000, Jorgen Grahn wrote: > I realize this has to do with the extra read-ahead buffering documented for > file.next() and that I can work around it by using file.readline() > instead. > > The problem is, "for s in f" is the elegant way of reading files line > by line. With readline(), I need a much uglier loop. I cannot find a > better one than this: > > while 1: > s = sys.stdin.readline() > if not s: break > print '####', s , > > And also, "for s in f" works on any iterator f -- so I have to choose > between two evils: an ugly, non-idiomatic and limiting loop, or one > which works well until it is used interactively. > > Is there a way around this? Or are the savings in execution time or > I/O so large that everyone is willing to tolerate this bug? You can use ``for line in lines:`` and pass ``iter(sys.stdin.readline, '')`` as iterable for `lines`. Ciao, Marc 'BlackJack' Rintsch From clodoaldo.pinto at gmail.com Fri Mar 28 12:22:06 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Fri, 28 Mar 2008 09:22:06 -0700 (PDT) Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> Message-ID: <37d6b141-5ba0-4178-b45a-512e59433803@s12g2000prg.googlegroups.com> On Mar 28, 12:09 pm, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo > escribi?: > > > > > I'm using a md5 hash encoded with base64.urlsafe_b64encode as a > > parameter of a URL used to confirm a registration in a site. It has > > been working great. > > > The url is like this: > > >http://example.com/ce?i=878&h=kTfWSUaby5sBu9bIfoR87Q== > > > Now i need to match that URL in a certain text and i realized that > > urlsafe_b64encode uses the "=" character so i can't just use \w{24} to > > match the parameter. > > > What i need to know is where can an equal char appear in a > > urlsafe_b64encoded string?: > > > a)only at end; > > b)both at the end and at the begginig; > > c)anywhere in the string; > > > A sure answer will make my regexp safer. > > Only at the end. The encoded string has 4*n chars when the input string > has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has > 4*(n+1) chars right padded with 2 or 1 "=" chars. > If your input has 3n chars, the output won't have any "=" Thanks. But I'm not sure i get it. What is n? A md5 digest will always be 16 bytes length. So if i understand it correctly (not sure) the output will always be 22 chars plus two trailing equal chars. Right? Regards, Clodoaldo Pinto Neto From stefan_ml at behnel.de Mon Mar 10 15:15:19 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 20:15:19 +0100 Subject: Quality assurance in Python projects containing C modules In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <47D588C7.9070804@behnel.de> Duncan Booth wrote: > Stefan Behnel wrote: >> Duncan Booth wrote: >>> I would start by ensuring that any DLLs you write are written using >>> Pyrex or Cython: almost always problems with C libraries called from >>> Python are due to faulty reference counting but if you keep all of >>> your Python related code in Pyrex/Cython modules the reference >>> counting problem should be taken care of for you. You can call any >>> required C/C++ code from the Cython code. >> I think the OP meant to use wxPython as an external module, in which >> case he has no way of influencing the language it is implemented in. > > The OP mentioned 'two or three C libraries', so I assume wxPython is only > part of the story. Ah, sorry, I missed that. Sure, if it's about integrating C/C++ libraries as Python modules, then I second the recommendation of using Cython. Stefan From arnodel at googlemail.com Mon Mar 24 19:26:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 24 Mar 2008 16:26:34 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: <5f07b190-053b-451f-8342-8298fb02c130@i29g2000prf.googlegroups.com> On Mar 24, 10:05?pm, Julien wrote: > Hi all, and thanks a lot for your answers! > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making > up the term) a function: > > def hijacker(arg): > ? ? if I_feel_its_necessary: > ? ? ? ? hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > ? ? hijacker(something) > ? ? ... # Continue as normal > ? ? return 2 > > def my_function2(arg): > ? ? ... # Maybe do some processing here > ? ? hijacker(whatever) > ? ? ... # Continue as normal > ? ? return 3 > > I have some long functions like my_function1 and my_function2 which > I'd like to alter, but I want to keep the alterations as little as as > possible. I'd like the extra behaviour to be handled by 'hijacker' and > let it decide what the caller function should return. Just adding a > call to 'hijacker' in all of these functions would be ideal for me > because that would be quick to modify them and also easier to > maintain, I believe. > > If 'hijacker' thinks it's necessary, it would force the caller > function to return a certain > value, otherwise it would let the caller function do its normal > business. > > For while I thought I'd make hijacker a decorator: > > @hijacker > def my_function(request): > .... > > But that wouldn't work, since some functions need to do some > processing before calling the hijacker. Yet, I think a decorator is > systematically called before the function itself so no prior > processing can be done by the function... > > Any idea on how to do that, if that's even possible? Of course it's possible ;), with the combination of an exception and a decorator. See example below. However I would seriously doubt the maintainability of such practices... # --------- hijack.py ------------ from functools import wraps class HijackReturn(Exception): def __init__(self, val): self.val = val def hijack(f): @wraps(f) def hijacked(*args, **kwargs): try: return f(*args, **kwargs) except HijackReturn, e: return e.val return hijacked @hijack def foo(x): x = x + 1 hijacker(x) return x * 2 def hijacker(x): if x == 21: print "[Oh no, it's going to be 42!]" raise HijackReturn(41) # ------------------------------- marigold:junk arno$ python -i hijack.py >>> foo(10) 22 >>> foo(20) [Oh no, it's going to be 42!] 41 >>> HTH -- Arnaud From hniksic at xemacs.org Wed Mar 26 05:02:09 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 26 Mar 2008 10:02:09 +0100 Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: <87myolc0z2.fsf@mulj.homelinux.net> blackpawn writes: > I know the garbage collector is tracking the object because it > properly calls the traverse function but for whatever reason it > never calls the clear function. Does anyone have experience with > circular references and had success with it or the example in the > docs? I've now tried it, and it seems to work. Modifying Nody_dealloc with printf("collecting %p\n", self), it works like this: >>> import noddy4 >>> n = noddy4.Noddy() >>> n.first = n >>> del n # n would be dealloced here without the cycle >>> ^D collecting 0xb7d3bf2c So the garbage-collector is invoked at least once before shutdown. However, it doesn't work without "del n" line, so it would appear that the gc is not invoked after the module cleanup and therefore doesn't explicitly dealloc global objects that contain cycles. You can work around that by using the atexit module to register a cleanup function that removes your global objects from the module namespace(s) and, if necessary, invokes gc.collect() manually. That way your objects end up as reclaimable garbage. This won't work if your cycle-containing objects are indirectly reachable from the module namespace through other containers not under your control. In that case, you should really rethink your strategy of depending on finalizers to run and perhaps use atexit to do your exit processing or, as others pointed out, use scope tools (try/finally, with) at the entry point of your code. From noname9968 at gmail.com Wed Mar 26 05:23:16 2008 From: noname9968 at gmail.com (Alex9968) Date: Wed, 26 Mar 2008 12:23:16 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative Message-ID: <47EA1604.4070905@gmail.com> Hi all, I use Tkinter's Pack widget geometry manager (I really prefer it over using visual GUI designers), so my question is which other GUI toolkits have similar functionality. Secondly, I like the detailed widget borders configuration possible in Tkinter, which can be used to tweak GUI look, and wonder if other toolkits support it. With Tkinter's case, I like the resulting (tweaked) look in Windows, but I'm afraid it can be quite different (and ugly) on other platforms. (The reason I ever consider moving from Tkinter is some inconveniences, involving for example window scrolling, plus its smaller amount of widgets compared to some other toolkits, plus its (rumored) ugly look on certain environments. I will not necessary change the toolkit, but I have to consider it) Could anyone with experience in different toolkits help, please Thanks From michael.wieher at gmail.com Fri Mar 7 17:38:24 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 16:38:24 -0600 Subject: os.chdir In-Reply-To: References: Message-ID: 2008/3/7, Maryam Saeedi : > > I have a problem using os.chdir on linux. What should I do if I want to > change to root directory? The below does not work: > > os.chdir("~/dir1") > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > >>> os.getcwd() '/home/michael' >>> os.chdir("/home/") >>> os.getcwd() '/home I guess just be sure your user account has rights to the directory you're trying to change to and don't screw up the quotes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Thu Mar 20 11:44:07 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 08:44:07 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: References: <13u50796m76e9c7@corp.supernews.com> Message-ID: <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> jmDesktop wrote: > On Mar 20, 11:21 am, Grant Edwards wrote: >> On 2008-03-20, jmDesktop wrote: >> >>> Hi, I'm trying to learn Python. I using Aquamac an emac >>> implementation with mac os x. I have a program. If I go to the >>> command prompt and type pythong myprog.py, it works. Can the program >>> be run from within the editor or is that not how development is done? >>> I ask because I was using Visual Studio with C# and, if you're >>> familiar, you just hit run and it works. On Python do I use the >>> editor for editing only and then run the program from the command >>> line? Sort of. Modern editors generally have support for building and running your program directly from a toolbar button or textual command. I personally use Vim with the toolbar disabled, running in a Terminal, and run the program by first putting Vim in the background (^z). People writing code specific to Mac, but not necessarily all in Python, often use XCode. http://zovirl.com/2006/07/13/xcode-python/ In the Ruby community, Vim is the dominant choice, but a lot of Mac users swear by TextMate. http://macromates.com/ >> http://www.google.com/search?q=emacs+python > Gee. Thanks. I believe Grant was suggesting that Emacs often serves a similar purpose on Unix to what Visual Studio does on Windows, which seemed to be what you were asking. When asking about Mac OS X here, you are likely to get a lot of generic Unix responses. (Would it have been clearer if he had just said "emacs?") From deets at nospam.web.de Sun Mar 9 17:56:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 22:56:19 +0100 Subject: Logically/Selectively Sub Class? In-Reply-To: References: <63j3ltF282fssU1@mid.uni-berlin.de> Message-ID: <63j4o6F27lit6U1@mid.uni-berlin.de> xkenneth schrieb: > On Mar 9, 4:38 pm, "Diez B. Roggisch" wrote: >> xkenneth schrieb: >> >>> Might be a silly question, but is it possible to selectively subclass, >>> IE subclass is a supporting module is present and not otherwise. >> Yes, something like this should work >> >> class Foo(some, base, classes) >> pass >> >> if condition: >> Temp = Foo >> class Foo(Temp, otherclass): pass >> >> Alternatively, you can use the type-function to create classes explicit >> with a list of base-classes. >> >> However it smells after bad design... what's your actual usecase? >> >> Diez > > Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB > for a lot of my stuff now, and I need my objects to be persistent, > however there might be a case where my classes could be used in a non- > persistent manner. I'll just have ZODB as a requirement for my > package. Ah. Then this also might work try: from ZODB import Persistent except ImportError: class Persistent: pass Diez From stef.mientki at gmail.com Mon Mar 10 15:27:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 10 Mar 2008 20:27:39 +0100 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: <47D587F9.3050703@behnel.de> References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: <47D58BAB.5060705@gmail.com> Stefan Behnel wrote: > Malcolm Greene wrote: > >>> My personal experience with wxPython has its ups and downs. Specifically >>> when it comes to crashes, I wouldn't bet my life on it. >>> >> I'm new to Python and getting ready to build a small client based >> application intended to run on Windows and Linux. I was planning on using >> wxPython until I saw your comment above. >> > > Just to make this sound a bit less like FUD: my last experience with wxPython > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > in a project, which crashed a bit too often to do real work with it - and with > crashing I mean crashing Python, not just showing us its blank traceback. So > this was definitely a problem either in wxWindows or in wxPython. > > I have no idea how well it works today, but this has definitely forged my > opinion on wxPython. > > > I'm using wxPython for half a year now, and building quit a large / heavy GUI with it. And although it's not so easy as Delphi, it's certainly just as stable as Delphi. If you're talking about Boa, that's a completely different story, I tried it on 3 different machines, and couldn't get it working on any of them. I think Boa / Dabo / .. are basically good ideas to make programming wxPython more easy, and probably a lot of people invested a lot of their free time in the product with the best intentions, but unfortunately these programs are not ready for use by others (specially not for windows users). I'ld suggest that you download the wxPython demo (with interactive editor) and see for yourself. cheers, Stef From grante at visi.com Thu Mar 13 16:28:41 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 13 Mar 2008 20:28:41 -0000 Subject: This actually works. References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> Message-ID: <13tj3jpsj6tsc2c@corp.supernews.com> On 2008-03-13, troyj1978 at gmail.com wrote: > I couldn't believe it. Screw programming Python anymore! OMG, IT'S FREE MONEY! I guess you've got to give the wanker credit for actually mention Python programming. :) -- Grant From deets at nospam.web.de Sat Mar 1 12:54:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 18:54:24 +0100 Subject: SQLLITE In-Reply-To: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> References: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> Message-ID: <62tjigF24ui98U2@mid.uni-berlin.de> nexes schrieb: > Hello All, > I am having a minor problem when I try and do this: > c.execute("insert into [tblTranscripts] (MovieID,Transcript) > Values(" + movieID + ",'" + formatText + "');") (don't even bother > commenting of the sql style I know its bad form but this is a simple > script). Whenever I try and do the insert I get table not found, > however when I perform the sql through sqlite's command line program > (the sql is outputted via a print statement) it works fine. Any ideas? No, and without more context nobody will have. Does working with the table with other statments work, how do you connect the DB, are you sure you really use the same DB-file and so forth. Diez From cyberco at gmail.com Sun Mar 23 04:20:50 2008 From: cyberco at gmail.com (Berco Beute) Date: Sun, 23 Mar 2008 01:20:50 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 5:40 pm, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. Yes. The nice thing with Python is that you can start off with really simple examples and slowly build up the complexity along with the understanding of the students. There's no need to explain OO before the students can write their first 'Hello, world'. There's almost no limit to how 'shallow/deep' you can go with Python. 2B From barry at python.org Sat Mar 1 13:51:38 2008 From: barry at python.org (Barry Warsaw) Date: Sat, 1 Mar 2008 13:51:38 -0500 Subject: RELEASED Python 2.6a1 and 3.0a3 Message-ID: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I'm happy to announce the first alpha release of Python 2.6, and the third alpha release of Python 3.0. Python 2.6 is not only the next advancement in the Python 2 series, it is also a transitionary release, helping developers begin to prepare their code for Python 3.0. As such, many features are being backported from Python 3.0 to 2.6. It makes sense to release both versions in at the same time, the precedence for this having been set with the Python 1.6 and 2.0 releases. During the alpha testing cycle we will be releasing both versions in lockstep, on a monthly release cycle. The releases will happen on the last Friday of every month. If this schedule works well, we will continue releasing in lockstep during the beta program. See PEP 361 for schedule details: http://www.python.org/dev/peps/pep-0361/ Please note that these are alpha releases, and as such are not suitable for production environments. We continue to strive for a high degree of quality, but there are still some known problems and the feature sets have not been finalized. These alphas are being released to solicit feedback and hopefully discover bugs, as well as allowing you to determine how changes in 2.6 and 3.0 might impact you. If you find things broken or incorrect, please submit a bug report at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 web site: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ We are planning a number of additional alpha releases, with the final release schedule still to be determined. Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iQCVAwUBR8mlu3EjvBPtnXfVAQKePAQAgx6w9wztfJaSWkbKrbwur2U6t6o5aIY5 pyMa00CZWY06p8099BztcSjgp5rKrd6/9V7cJ0NP7NLZ+tz20uRfyI8uqoIYBIWC ibJay6SSnzgOQM3PRIJV/K/m0dVPPPVD1LDnoEvuu+cKUpV434yHdgWkMPswsxUd fLydrXABlOM= =l6aj -----END PGP SIGNATURE----- From bj_666 at gmx.net Thu Mar 6 15:57:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Mar 2008 20:57:46 GMT Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> Message-ID: <63b46aF26qudpU1@mid.uni-berlin.de> On Thu, 06 Mar 2008 11:06:50 -0800, castironpi wrote: > On Mar 6, 8:30?am, Carl Banks wrote: >> Anyway, the answer to what you are probably asking is No. ?Try this: >> >> >>>import module >> >>>c1 = module.Someclass >> >>>reload(module) >> >>>c2 = module.Someclass >> >>>c1 is c2 > > What about > >>>> o= object() >>>> b1= o.someattr >>>> reload( o ) >>>> b2= o.someattr >>>> b1 is b2 > > ? You are really a bit thick, a troll, or a bot. *plonk* Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Wed Mar 12 06:55:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 03:55:08 -0700 (PDT) Subject: sys.stdout assign to- bug Message-ID: <39b263ea-e6f0-41f0-b1e8-edcbea851275@13g2000hsb.googlegroups.com> I'm actually intimidated enough by a few tries I make to say something on Python-Ideas, that I thought I'd run this by youguys first. import sys class ThreadedOut: def __init__( self, old ): self._old= old def write( self, s ): self._old.write( s ) sys.stdout= ThreadedOut( sys.stdout ) >>> a >>> 0 0 Python 3.0a2 WinXP, on the console. 'a' is undeclared but error message isn't thrown. With 'sys.stdout= Thr...' commented: >>> a Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined >>> 0 0 But the docs say: stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument. What's the catch? From castironpi at gmail.com Tue Mar 4 13:45:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:45:40 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> Message-ID: <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> > > So, to answer your question: what you are decorating are functions, not > > methods. > > Can you overload -type-'s decision of what to 'bind'?... whenever it > is it makes it. >>> from types import FunctionType, MethodType >>> class A( FunctionType ): pass ... Traceback (most recent call last): File "", line 1, in TypeError: type 'function' is not an acceptable base type >>> class A( MethodType ): pass ... Traceback (most recent call last): File "", line 1, in TypeError: type 'method' is not an acceptable base type Unacceptable. From castironpi at gmail.com Fri Mar 21 02:34:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:34:41 -0700 (PDT) Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <13u353a51v9kp36@corp.supernews.com> Message-ID: <3c71c7c4-e2a4-4628-8004-8a54eccc8ce6@m3g2000hsc.googlegroups.com> On Mar 19, 5:32?pm, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote: > > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but calculate/ > > compare in UTC. > > What possible ambiguity is there? I agree. >>> D.datetime( 2008, 3, 23 ) datetime.datetime(2008, 3, 23, 0, 0) >>> a=_ >>> D.timedelta( minutes= 30, seconds= 80 ) datetime.timedelta(0, 1880) >>> b= _ >>> a+b datetime.datetime(2008, 3, 23, 0, 31, 20) >>> a+b-a datetime.timedelta(0, 1880) From quentel.pierre at wanadoo.fr Thu Mar 6 09:27:56 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Thu, 6 Mar 2008 06:27:56 -0800 (PST) Subject: Converting a string to the most probable type Message-ID: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Hi, I would like to know if there is a module that converts a string to a value of the "most probable type" ; for instance : - if the string is "abcd" the value is the same string "abcd" - string "123" : value = the integer 123 - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value = the float -1.23 - string "2008/03/06" (the format is also locale-dependant) : value = datetime.date(2008,03,06) Like in spreadsheets, special prefixes could be used to force the type : for instance '123 would be converted to the *string* "123" instead of the *integer* 123 I could code it myself, but this wheel is probably already invented Regards, Pierre From paulgeeleher at gmail.com Wed Mar 12 12:43:33 2008 From: paulgeeleher at gmail.com (sophie_newbie) Date: Wed, 12 Mar 2008 09:43:33 -0700 (PDT) Subject: Get cgi script to begin execution of another script... Message-ID: I've posted something similar to this already, but now I'm more sure of what I'm asking. Basically I've a CGI script, that when executed by the user, I want to call another script that does a very long running task (10 hours +) and print a message on the screen saying that the user will be emailed on completion of the very long task. The script executing the very long task will then email the user on completion. So far I have something like this (leaving out the obvious)... CGI script: pid = subprocess.Popen(["python", "spawn.py"]).pid print "Thanks you will be emailed on completion" Spawn.py script: doVeryLongCalc() emailUser() Basically the problem with this is that the cgi script page in the browser keeps on acting as if its loading until the Spawn.py script is finished executing. Somehow apache "knows" that the spawned process is still running in the background. So I'm basically asking if I can somehow spawn a script that will be completely independent of its parent script? So Apache doesn't know its running and the page finishes loading? Thanks if anyone can help... From misceverything at gmail.com Mon Mar 31 05:13:49 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Mon, 31 Mar 2008 02:13:49 -0700 (PDT) Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> <47eea713$0$27902$426a74cc@news.free.fr> Message-ID: On Mar 31, 2:50 am, Tim Golden wrote: > misceveryth... at gmail.com wrote: > > That's not a problem - I'm only interested in Win2k+. Thanks for the > > caveat. > > > On a similar note, is there a way (preferably using WMI) to get the > > full path to the executable that has a port open (the same thing that > > fport does, just implemented in Python)? > > It looks as though it might be possible with the (not > installed by default) SNMP WMI provider. Haven't tried > it myself, but there's some info here: > > http://groups.google.com/group/microsoft.public.win32.programmer.wmi/... > > and here: > > http://msdn2.microsoft.com/en-us/library/aa393621(VS.85).aspx > > Alternatively, look around for the GetExtendedTcpTable functionality > and so on. > > Sorry, this isn't really my area -- all I've done here is to let > my fingers do the walking. > > TJG Sounds good - I'm going to check those links out now. Thanks again for all your help. From dewitters at gmail.com Sun Mar 30 04:25:35 2008 From: dewitters at gmail.com (dewitters at gmail.com) Date: Sun, 30 Mar 2008 01:25:35 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <02864e42-d2d7-4eeb-ba13-6aa7ddbdf7aa@i29g2000prf.googlegroups.com> Message-ID: <7c041716-69a4-47d9-9105-62fcc3dd4269@s50g2000hsb.googlegroups.com> On Mar 29, 9:48 pm, Dan Bishop wrote: > MOST of Python's operators are based on C's. Consider, for example, > the bitwise operators | ^ & << >> ~ and the compound assignment > operators += -= etc. > > The exceptions are ** (from Fortran), //, and the logical operators. Borrowing parts out of other languages (C in this case) is not a problem, but I don't think there is a need to try be consistent with C. It's Python, not C, so we should do things better ;). From sjmachin at lexicon.net Thu Mar 13 17:00:49 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Mar 2008 14:00:49 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> Message-ID: On Mar 14, 6:13 am, Arnaud Delobelle wrote: > On Mar 13, 10:42 am, Paul Rubin wrote: > [...] > > > By Python convention, methods that mutate the object return None, and > > also stuff that returns None doesn't generate output at the > > interactive prompt. > > A convention that does not always hold: > > > > >>> l = [1, 2, 3] > >>> l.pop() > 3 > >>> l > [1, 2] Try this then for the "convention": Any function/method that is not documented to return something else should be assumed to return None. Note: no nexus with whether or not the function/method mutates its args. From sales057 at aaa-replica-watch.com Tue Mar 18 00:00:06 2008 From: sales057 at aaa-replica-watch.com (sales057 at aaa-replica-watch.com) Date: Mon, 17 Mar 2008 21:00:06 -0700 (PDT) Subject: Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Replica Message-ID: <4de7b883-a9e1-4ea0-aa57-911a188e480c@d21g2000prf.googlegroups.com> Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Replica, Fake, Cheap, AAA Replica watch Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Link : http://www.aaa-replica-watch.com/Ebel_1215526.html Buy the cheapest Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 in toppest Replica . www.aaa-replica-watch.com helps you to save money! Ebel-1215526 , Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 , Replia , Cheap , Fake , imitation , Ebel Watches Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Information : Brand : Ebel Watches (http://www.aaa-replica-watch.com/ Replica_Ebel.html ) Gender : Ladies Model : Ebel-1215526 Case Material : 18kt Yellow Gold And Stainless Steel Case Diameter : 1215526, Ebel-1215526, 1201L24-9960, 1201L24/9960, 1201L24.9960, 1201L249960 Dial Color : White Mother-of-pearl Bezel : 18kt Yellow Gold With 34 Diamonds Movement : Automatic Clasp : 18kt Yellow Gold And Stainless Steel Water Resistant : 100m/330ft Crystal : Scratch Resistant Sapphire Our Price : $ 225.00 18kt yellow gold and stainless steel case and bracelet. White mother- of-pearl dial with 11 diamond hour markers. Bezel set with 34 diamonds. Hidden folding clasp. Anti-reflective scratch resistant sapphire crystal. Case diameter 27mm. Automatic movement. Water resistant at 100 meters (330 feet). Alternate model number 1201L24/9960. Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 Replica, With the mix of finest craftsmanship and contemporary styling, not only does it reflect the time but also care you put into looking good. choose one to promote your quality and make yourself impressive among people Thank you for choosing www.aaa-replica-watch.com as your reliable dealer of quality waches including Ebel 1911 Lady Diamond 18kt Yellow Gold and Steel Ladies Watch 1215526 . we guarantee every watch you receive will be exact watch you ordered. Each watch sold enjoy one year Warranty for free repair. Every order from aaa-replica-watches is shipped via EMS, the customer is responsible for the shipping fee on the first order, but since the second watch you buy from our site, the shipping cost is free. Please note that If the total amount of payment is over $600(USD), the customer is required to contact our customer service before sending the money in case failed payment. If you have any other questions please check our other pages or feel free to email us by service at aaa-replica-watch.com. The Same Ebel Watches Series : Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 : http://www.aaa-replica.com/Ebel_1215525.html Ebel 1911 Mens Watch 91331240/14665P : http://www.aaa-replica.com/Ebel_91331240_14665P.html Ebel 1911 Womens Watch 1090211-19865P : http://www.aaa-replica.com/Ebel_1090211_19865P.html Ebel 1911 Mens Watch 1080241-13665P : http://www.aaa-replica.com/Ebel_1080241_13665P.html Ebel 1911 Womens Watch 9090214-19865P : http://www.aaa-replica.com/Ebel_9090214_19865P.html Ebel 1911 Womens Watch 1087221-15865P : http://www.aaa-replica.com/Ebel_1087221_15865P.html Ebel 1911 Womens Watch 1087221-19865P : http://www.aaa-replica.com/Ebel_1087221_19865P.html Ebel 1911 Mens Watch 9331240-13665P : http://www.aaa-replica.com/Ebel_9331240_13665P.html Ebel 1911 Mens Watch 9125241-10665P : http://www.aaa-replica.com/Ebel_9125241_10665P.html Ebel 1911 Mens Watch 9330240-15665P : http://www.aaa-replica.com/Ebel_9330240_15665P.html Ebel Classic Mini Stainless Steel Ladies Watch 9003F11.9925 : http://www.aaa-replica.com/ebel_classic_mini_watch_9003F11_9925.html Ebel Classic Stainless Steel Mens Watch 9120F51.6235134 : http://www.aaa-replica.com/ebel_classic_stainless_9120F516235134.html From cabird at gmail.com Mon Mar 31 16:52:44 2008 From: cabird at gmail.com (Christian Bird) Date: Mon, 31 Mar 2008 13:52:44 -0700 Subject: import multiple modules with same name Message-ID: Is it possible to import multiple modules with the same name from different locations? I'm using two different pieces of software, both of which have a module named util.py. I know that I can modify sys.path to fix which util gets imported when I do: import util I'd like to be able to do something like: import sys sys.path.append("/somedir1/") import util as util1 sys.path.insert(0, "/somedir2/") import util as util2 But it appears that once python imports a module, it will never look for a module with the same name again. Is there any way to get around this? I'd rather not rename either of the util modules as other pieces of software use them (but the others never use both of them of course) and I don't want to break them or have multiple copies of the code in different named files. I'm appreciative of anyone's ideas. -- Chris -- Christian Bird cabird at gmail.com From shasha1234 at gmail.com Thu Mar 6 16:08:15 2008 From: shasha1234 at gmail.com (shsha) Date: Thu, 6 Mar 2008 13:08:15 -0800 (PST) Subject: Internet Explorer 8 beta release Message-ID: Internet Explorer 8 beta release is for developers, and Microsoft's Dean Hachamovitch promised at MIX08 that IE8 will make it easier to build Web sites for multiple browsers and stop wasting developers' time. Microsoft's IE8 features Activities for looking up information and Webslices to watch portions of Web sites for updates. more about MS http://www.toptechnews.com/story.xhtml?story_id=0120013PBF8O _____________ get wild ....all the action http://www.getaction4ever.com From dave_mikesell at fastmail.fm Mon Mar 3 07:18:40 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Mon, 3 Mar 2008 04:18:40 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: <620e3371-6cd1-4719-9e0b-a3b0c01f5fbc@d21g2000prf.googlegroups.com> On Mar 1, 10:53 pm, Kay Schluehr wrote: > On 1 Mrz., 19:51, Barry Warsaw wrote: > > > Python 2.6 is not only the next advancement in the Python 2 series, it > > is also a transitionary release, helping developers begin to prepare > > their code for Python 3.0. > > Isn't this a silly idea? People have to migrate from 2.5 or lower > releases to Python 2.6 first just to migrate to Python 3.0? What are > the inherent / technical reasons that prevent migration directly from > 2.5 to 3.0? Not only that, you have to wait for your library providers to migrate first (PyOpenGL, PyGame, PIL, etc for me). Hopefully this is the last quantum shift for a while. From tms at zeetix.com Sun Mar 16 11:10:26 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sun, 16 Mar 2008 11:10:26 -0400 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com><1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> Message-ID: <00ae01c88777$de88e2b0$0200a8c0@TMSMAIN> > But vendors often don't label themselves as vendors. And often, the > researcher or individual in question, who has something worth saying, does > have a professional job of sorts, which might be related to his or her > work > or speech. I've heard people give very long, detailed talks about > interesting topics, that did have a spin on them, but contained worthwhile > information also. Now, is that to be billed as a "vendor" (and ignored) > or > not? > Further, no vendor who is trying to sell a product will allow themselves > to > be marked in an obvious way as advertising, knowing that they'll be > ignored. At least, they certainly won't pay for the time/space to any > real > degree, knowing they'll be walking in under a cloud like that. No vendor with integrity will want their advertising to be presented to attendees as anything but advertising. If vendors won't buy advertising, then find different ways to fund the conferences. This sounds like an example of the editorial-content/advertising dilemma that publishers have wrestled with for a long time. It's basically impossible for anybody, even for seasoned professionals, to both sell advertising and set editorial content without bias. In the publishing business, it is a very big no-no for the same people to both sell advertising and also set editorial content. When you go high enough in an organization, it's harder to do, but still a goal. Perhaps the organizers can therefore learn from the experience of publishers: 1) Keep the folks who sell things in an "advertising department". They need to be different people from the folks who book keynotes and such. 2) Keep the folks who book keynotes and such in a "content department". They need to be different people from the folks who sell things. 3) Do everything possible to keep the "advertising" and "content" departments firewalled. This is cultural as much as anything else. Like any other potential conflict of interest situation, make it honorable for folks to recuse themselves when they sense a bias in themselves. From mail at timgolden.me.uk Thu Mar 27 05:01:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 09:01:26 +0000 Subject: py2exe socket.gaierror (10093) In-Reply-To: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: <47EB6266.1040609@timgolden.me.uk> Python Programming on Win32 wrote: > The problem is running smtplib in a py2exe compiled exe file. When it > tries to establish a socket to the mail server it fails. > > Just wondering someone has encountered this before, and if someone > might be able to point me in the right direction. > > Unhandled exception in thread started by > Traceback (most recent call last): > File "AutomationThread.pyc", line 152, in Run > File "mail.pyc", line 11, in sendMail > File "smtplib.pyc", line 244, in __init__ > File "smtplib.pyc", line 296, in connect > socket.gaierror: (10093, 'getaddrinfo failed') In case it helps, this is the text for error 10093: """ WSANOTINITIALISED 10093 Successful WSAStartup not yet performed. Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times. """ WSAStartup is called by a process which wants to use winsock, the Windows sockets implementation and it's called by Python's socket module at startup. I can't see anything in py2exe's source which should make any difference to socket initialisation so I'm at a loss. TJG From rockxuan at gmail.com Tue Mar 18 03:57:33 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:57:33 -0700 (PDT) Subject: Breitling Swiss watch in www.51cntrade.com Message-ID: Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1 Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2 Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rockxuan at gmail.com From tjreedy at udel.edu Sun Mar 23 17:29:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Mar 2008 17:29:14 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a firstprogramming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: "Roy Smith" wrote in message news:roy-40994D.13513423032008 at 70-1-84-166.area1.spcsdns.net... | There is a fundamental disharmony in how functions and other objects are | treated in Python. [snip] For scalars and collections, print object prints the value, which is the main part of the object, in a form close to (or equal to) how it is created in code. For functions, classes, and modules, this would be awkward to impossible since the corresponding code is not part of the object and may be either bulky and slow to access, not accessible, or non-existent. So these three get name attitributes as a substitute. Function names are also used to improve tracebacks over 'function at line nnn'. Perhaps for these types, print could (should?) instead print the first list of the doc string, if there is one. Method objects inherit the name of the function they wrap. Other internal types are left anonymous, but how could they get a name when there is no code to give them a name. Yes, fundamentally different categories of types are (sensibly) treated differently with repect to definition and namespace names, but calling that 'disharmony' depends on the listener. | If we created lisp-like lambdas and bound them to names like we did with | other types of objects, we wouldn't have that. Correct. Tracebacks would always instead of just occasionally be less useful as functions would always be identified only by file and line number, as today with lambda expression. Terry Jan Reedy From gabriel.rossetti at mydeskfriend.com Thu Mar 27 04:20:05 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 09:20:05 +0100 Subject: Partial Function Application and implicit self problem Message-ID: <47EB58B5.1020801@mydeskfriend.com> Hello, I am using Partial Function Application in a class and I've come up with a problem, when the method is called it tries to pass "self" to the curried/partial function, but this should be the first argument in reality, but since the function is curried, then the self gets passed as the second argument. Here is the code : def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) I should pass self when applying partial, but then I can't do that since self is not available there. Does anyone have any ideas? Thanks, Gabriel From Glich.Glich at googlemail.com Mon Mar 24 12:58:26 2008 From: Glich.Glich at googlemail.com (Glich) Date: Mon, 24 Mar 2008 09:58:26 -0700 (PDT) Subject: python, dbus and pointers help. References: <16059cb8-a182-40ff-9617-a8b6708e1183@s19g2000prg.googlegroups.com> Message-ID: <61a383ca-e287-4d13-a3b0-ba9ec24626fa@d21g2000prf.googlegroups.com> or a way of letting me see the message then cancel sending it then I could create a new message and send that one. but I cant see this in the documentation From kuaile9834 at 126.com Tue Mar 25 03:35:48 2008 From: kuaile9834 at 126.com (kuaile9834 at 126.com) Date: Tue, 25 Mar 2008 00:35:48 -0700 (PDT) Subject: cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) Message-ID: cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com )cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) cheap, shoes,sneaker,sneakers ( paypal accept ) ( www.top-saler .com ) From cito at online.de Sun Mar 2 16:40:51 2008 From: cito at online.de (Christoph Zwerschke) Date: Sun, 02 Mar 2008 22:40:51 +0100 Subject: tuples, index method, Python's design In-Reply-To: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> References: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> Message-ID: Paul Boddie schrieb: > On 2 Mar, 19:06, Alan Isaac wrote: >> On April 12th, 2007 at 10:05 PM Alan Isaac wrote: >> >>> The avoidance of tuples, so carefully defended in other >>> terms, is often rooted (I claim) in habits formed from >>> need for list methods like ``index`` and ``count``. >>> Indeed, I predict that Python tuples will eventually have >>> these methods and that these same people will then defend >>> *that* status quo. > > You were more confident about this than I was. Still, nothing happens > if no-one steps up to do something about it. And nobody stepped up because it had been made very clear by Guido and others that they don't want tuples to grow methods. I remember there had been ridiculously excessive threads about this, this probably being one of many others: http://groups.google.de/group/comp.lang.python/browse_thread/thread/430a692bc634a04f/ I don't think this was very encouraging for people who wanted to do something about it. Anyway, it's good to see this happened now. Thanks to Raymond. -- Christoph From saluk64007 at gmail.com Wed Mar 19 13:24:16 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 19 Mar 2008 10:24:16 -0700 Subject: Python to C/C++ In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: (sorry michael, didn't mean to personal post On Wed, Mar 19, 2008 at 9:24 AM, Michael Wieher wrote: > I think py2exe does this, but it might be a bit bloated No, py2exe basically bundles the main script and the interpreter together so it's easy to run and requires no python installation. Look into pyrex and pypy. A mature translator doesn't exist. Also there is ctypes which goes in reverse letting you use more c from python easily. From roygeorget at gmail.com Mon Mar 10 09:57:45 2008 From: roygeorget at gmail.com (royG) Date: Mon, 10 Mar 2008 06:57:45 -0700 (PDT) Subject: parsing directory for certain filetypes Message-ID: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> hi i wrote a function to parse a given directory and make a sorted list of files with .txt,.doc extensions .it works,but i want to know if it is too bloated..can this be rewritten in more efficient manner? here it is... from string import split from os.path import isdir,join,normpath from os import listdir def parsefolder(dirname): filenms=[] folder=dirname isadr=isdir(folder) if (isadr): dirlist=listdir(folder) filenm="" for x in dirlist: filenm=x if(filenm.endswith(("txt","doc"))): nmparts=[] nmparts=split(filenm,'.' ) if((nmparts[1]=='txt') or (nmparts[1]=='doc')): filenms.append(filenm) filenms.sort() filenameslist=[] filenameslist=[normpath(join(folder,y)) for y in filenms] numifiles=len(filenameslist) print filenameslist return filenameslist folder='F:/mysys/code/tstfolder' parsefolder(folder) thanks, RG From gagsl-py2 at yahoo.com.ar Mon Mar 17 09:16:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 11:16:44 -0200 Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> Message-ID: En Sun, 16 Mar 2008 22:27:28 -0200, escribi?: > Specifically, before the prompts. Where does the prompt write come > from; why doesn't it honor my settings of sys.stdout and sys.stderr? The interactive interpreter uses directly the C predefined streams stdout and stderr. -- Gabriel Genellina From bj_666 at gmx.net Mon Mar 31 02:45:27 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 06:45:27 GMT Subject: Beginner advice References: Message-ID: <65bfk7F2esfc1U1@mid.uni-berlin.de> On Mon, 31 Mar 2008 07:23:00 +0200, Paul Scott wrote: > 3. pyXMLRPClib - active? Something better? There is an `xmlrpclib` in the standard library, so there is no need for an external package here. I even think that pyXMLRPClib is the one that's integrated in the standard library, so the external one might be "dead". > 4. I see that there are literally thousands of somewhat external looking > libraries for python, I presume that there is some way of bundling all > the deps into a single source and then compiling? or otherwise packaging > them all (this software will be for academia, so difficult installs are > out!) For Windows there are tools to bundle your source and all dependencies and even the interpreter itself. `py2exe` is such a tool. With InnoSetup or NSIS or similar programs you can then make a `setup.exe` for that spoiled Windows brats. :-) Under Linux many packages are available as distribution specific packages on most distributions. So for Linux you may get away with a README stating the dependencies of your program and a `setup.py` for installing your project. Look for `distutils` in the Python documentation for further information about `setup.py`\s. > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? Use the one you like best. ;-) Many don't use an IDE but simply their favorite text editor. I'm happy with syntax highlighting, automatic indentation support for Python source code, and completion based on the content of open file(s) -- almost all serious editors have those features. And there's always an IPython console running to test small pieces of code. > All Email originating from UWC is covered by disclaimer > http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm Hey, that's a nice way to have a *short* stupid disclaimer. :-) Ciao, Marc 'BlackJack' Rintsch From nejtak... Wed Mar 5 16:44:03 2008 From: nejtak... (Troels Thomsen) Date: Wed, 5 Mar 2008 22:44:03 +0100 Subject: for-else In-Reply-To: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> Message-ID: <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> > > The primary use case is searching a container: > > prep_tasks() > for item in container: > if predicate(item): > found_tasks() > break > else: > not_found_tasks() > follow_up_tasks > I've found myself mimicing this again and again in c, and was pleased to find it in python and use it regularely. int i for (i = 0 ; i < 10 ; ++i) blah if i == 10 not_found_tasks() The discussion of words is silly. My surprise about "else following a for loop.... what the heck ...." lasted excactly as long as it takes to read this sentence. tpt From castironpi at gmail.com Tue Mar 4 13:40:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:40:11 -0800 (PST) Subject: for-else References: Message-ID: <529fdf03-9c17-476c-abb9-42c4417ed7c2@d4g2000prg.googlegroups.com> Would you like it to be removed or its name changed? You can do it with a special iteration: for a in B: if behavior break else: 2behavior ----> class KeepResult:... kr= KeepResult( B ) for a in kr: if behavior break if kr.diditbreak?: 2behavior (if not: 3behavior) It just can't do automatic continues; you'd need a kr.i'mcontinuingonthisone(). Would that be useful in addition? From jzgoda at o2.usun.pl Fri Mar 14 16:52:46 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 14 Mar 2008 21:52:46 +0100 Subject: Installing Python2.4 on RHEL4? In-Reply-To: References: Message-ID: Eric B. pisze: > I appologize if this is slightly OT, but I am really struggling to figure > out how to install Python2.4 on RHEL4. To make matters worse, the RHEL4 > machine is a 64bit architecture. > > I search pyvault, but they only have for .i386. Does anyone know where / > how I can find Python2.4 for RHEL4 x64? If you would not find a binary Python 2.4 package, you can always build your own and package it. Why not? -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From aisaac at american.edu Fri Mar 14 00:28:41 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 14 Mar 2008 04:28:41 GMT Subject: no more comparisons In-Reply-To: References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: Dan Bishop wrote: > Even assuming you meant (-x[0], int(x[1])), that sorts negative > numbers in the wrong order. You want > key = lambda x: (-1 if x[0] else 1) * int(x[1]) Sorry, was speed typing (very badly) and the question actually had two different problem descriptions. As you suggest, what I meant was:: key= lambda x: (-x[0], int(x[1])) which was meant to address: "Sorting tuples, where the second item in the tuple should have the opposite ordering to the first is going to be a bit of a pain." But you are quite right, the problem was then specified to numerical order, for which I like your solution. Or even:: key= lambda x: -int(x[1]) if x[0] else int(x[1]) The key point being, if you will, that this use case does not support the idea that relying on ``key`` will be so bad. So, what is a case that is really uncomfortable? Thanks, Alan Isaac From tms at zeetix.com Sat Mar 15 12:09:19 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 12:09:19 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> I'm still confused about this, even after days of hacking at it. It's time I asked for help. I understand that each of you knows more about Python, Javascript, unicode, and programming than me, and I understand that each of you has a higher SAT score than me. So please try and be gentle with your responses. I use simplejson to serialize html strings that the server is delivering to a browser. Since the apostrophe is a string terminator in javascript, I need to escape any apostrophe embedded in the html. Just to be clear, the specific unicode character I'm struggling with is described in Python as: u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of 0x27. This can be expressed in several common ways: hex: 0x27 Python literal: u"\u0027" Suppose I start with some test string that contains an embedded apostrophe -- for example: u" ' ". I believe that the appropriate json serialization of this is (presented as a list to eliminate notation ambiguities): ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] This is a 14-character utf-8 serialization of the above test string. I know I can brute-force this, using something like the following: def encode(aRawString): aReplacement = ''.join(['\\', '0', '0', '2', '7']) aCookedString = aRawString.replace("'", aReplacement) answer = simplejson.dumps(aCookedString) return answer I can't even make mailers let me *TYPE* a string literal for the replacement string without trying to turn it into an HTML link! Anyway, I know that my "encode" function works, but it pains me to add that "replace" call before *EVERY* invocation of the simplejson.dumps() method. The reason I upgraded to 1.7.4 was to get the c-level speedup routine now offered by simplejson -- yet the need to do this apostrophe escaping seems to negate this advantage! Is there perhaps some combination of dumps keyword arguments, python encode()/str() magic, or something similar that accomplishes this same result? What is the highest-performance way to get simplejson to emit the desired serialization of the given test string? From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 04:05:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 08:05:16 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> Message-ID: <13t76hsmp060e55@corp.supernews.com> On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > On 9 Mrz., 06:30, Steven D'Aprano cybersource.com.au> wrote: > >> Hard Exceptions: terminate the program unless explicitly silenced Soft >> Exceptions: pass silently unless explicitly caught >> >> In this case, I agree with the Zen of Python ("import this"): >> >> Errors should never pass silently. >> Unless explicitly silenced. > > Exceptions in Python don't necessarily signal errors. Just think about > StopIteration. I know that. That's why I said that exceptions were used for signaling exceptional events. > Note also that the common practice of letting *possible* errors passed > silently is to return None instead of raising an exception. "Common"? Who does that? I know re.search() etc. return None in the event the regex doesn't match. That's not an error. > Moreove people create boilerplate like this > > try: > k = lst.index(elem) > ... > except IndexError: > pass > > instead of > > with lst.index(elem) as k: > ... Possibly because the with keyword is quite new and many people don't know it, and much code was written before it even existed, or they have to support Python 2.4 or older. > It would be interesting to think about SoftException semantics for such > clauses: lst.index would neither raises a HardException nor does it > return None but leads to skipping the with-block. > > Is it really so exotic that it requires the demand for more use cases? Are the existing solutions really so incomplete that we need yet another solution? What problem are you trying to solve with SoftExceptions? How would changing lst.index() to raise a soft exception help here? pos = lst.index('foo') lst[pos] = 'bar' What is that code going to do if 'foo' isn't found in lst and it raises a silent, unhandled SoftException? Do you expect Python to be context sensitive, and raise HardExceptions in some places and SoftExceptions in others? Who controls that? -- Steven From nkanthikiran at gmail.com Thu Mar 13 01:44:55 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Wed, 12 Mar 2008 22:44:55 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: On Mar 13, 8:07 am, "drobi... at gmail.com" wrote: > On Mar 12, 7:37 am, "k.i.n.g." wrote:> We use dd command in Linux to create a file with of required size. > > If you just want to get your work done, you might consider the cygwin > dd command. > Learning to write python is a worthwhile endeavour in any case. While I just started learning programming/python, I got this requirement at my workplace. I want to learn python than just get things done. Thank you all for the solutions, I will try them and let you all know about my results. From jgardner at jonathangardner.net Fri Mar 14 12:24:44 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 14 Mar 2008 09:24:44 -0700 (PDT) Subject: Monitoring SSHd and web servers? References: Message-ID: <36a2338f-60fd-456d-a906-716bb52e8122@s8g2000prg.googlegroups.com> On Mar 13, 11:32?pm, Gilles Ganault wrote: > I'd like to monitor connections to a remote SSH and web server. Does > someone have some code handy that would try to connect every 5mn, and > print an error if the script can't connect? from time import sleep while True: # Try to connect. May want to spawn a subprocess running a simple shell script # Handle success / failure appropriately sleep 5*60 # Sleep for 5 minutes What you monitor is up to you. At a basic level, you can see if the server is accepting connections. At a higher level, see if you can get a page or see if you can login as a specific person. At a higher level, you may want to check what is on the page or what happens when you log in. It's all up to you. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 18:48:32 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 00:48:32 +0200 Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: <65ajm0F2e07o0U1@mid.individual.net> vokinloksar at yahoo.se wrote: > using python and wpython. What's wpython? > when using run module or python shell on the run menu in the GUI i > get "socket error, connection refused". > > it worked before, what si wrong now? There's no process listening for the port you try to connect to, so the target host refuses. > and i cant find where to start the shell directly. Well, for me, ALT-F2 xterm[Enter] works. > think i had an exe before but cant seem to find it now. You mean the Python interpreter? It's probably located on your system root in a directory called python. But I'd rather use IDLE. Regards, Bj?rn -- BOFH excuse #338: old inkjet cartridges emanate barium-based fumes From sjmachin at lexicon.net Wed Mar 19 16:23:20 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 13:23:20 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> Message-ID: <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> On Mar 19, 11:17 pm, Godzilla wrote: > Hi John, > > I am using time.clock to calculate the elapsed time. Below is an > example of what I was trying to do: > > import time > import thread Silly me, not being able to infer that from your initial post! [snip] > > But the time.clock() sometimes return a value of between -3.5 to -4.5 > seconds backward. Note that not all computers are behaving the same. I > have not experience the same problem with the computer at home. Same "service pack" number? Your code "worked" (no time warp) for me on a single-core AMD Turion64 CPU running (32 bit) Windows XP Service Pack 2 Build 2600. Maybe the ones that "fail" have dual-core CPUs. From grante at visi.com Thu Mar 13 14:38:26 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 13 Mar 2008 18:38:26 -0000 Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: <13tit52j138i1e6@corp.supernews.com> On 2008-03-13, sleddd at gmail.com wrote: >> > For example: try creating a local client/server (running on the same >> > computer) where the server sends the client a fixed amount of data. >> > Using method A, recv(8192) and sendall( ) with 8192 bytes >> > worth of data. Do this 100 times. Using method B, recv(1) and >> > sendall( ) with 1 byte worth of data. Do this 819200 times. >> >> > If you time both methods, method A has much greater >> > throughput than method B. >> >> Why is it faster to drink a liter of water a cupful at a time than to >> drink it out of an eyedropper? > Well, lets say you have a situation where you're going to be > alternating between sending large and small chunks of data. Is the > solution to create a NetworkBuffer class and only call send when the > buffer is full, always recv(8192)? If you need to send large and small chumks of data, the solution is to send large and small chunks of data. -- Grant From jim at maplesong.com Fri Mar 7 16:24:34 2008 From: jim at maplesong.com (Jim Carroll) Date: Fri, 7 Mar 2008 21:24:34 +0000 (UTC) Subject: Time Zone application after strptime? Message-ID: It's taken me a couple of hours to give up on strptime with %Z for recognizing time zones... but that still leaves me in the wrong zone: def paypal_to_mysql_date(ppDate): # a typical paypal date is 10:29:52 Feb 29, 2008 PST date_parts = ppDate.split() withouttz = " ".join(date_parts[:-1]) # eventually we need to apply the timezone timezone = date_parts[-1] dt = datetime.strptime(withouttz, "%H:%M:%S %b %d, %Y") return dt.strftime("%Y-%m-%d %H:%M") How can I use the "PST" (or any other time zone name) to adjust dt by the correct number of hours to get it into UTC before storing in MySQL? Thanks! From jgelfand01 at gmail.com Tue Mar 25 19:15:57 2008 From: jgelfand01 at gmail.com (jgelfand) Date: Tue, 25 Mar 2008 16:15:57 -0700 (PDT) Subject: _tkinter fails when installing Python 2.4.4 References: <64tahuF2absebU1@mid.uni-berlin.de> Message-ID: <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> On Mar 25, 5:52 pm, "Diez B. Roggisch" wrote: > jgelfand schrieb: > > > > > I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat > > Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ > > usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but > > I get the following error message when I run "make": > > > building '_tkinter' extension > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > > yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ > > usr/local/yosi/Python-2.5.2/Modules/_tkinter.o > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > > yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ > > usr/local/yosi/Python-2.5.2/Modules/tkappinit.o > > gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ > > Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ > > yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ > > lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - > > ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so > > *** WARNING: renaming "_tkinter" since importing it failed: build/ > > lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents > > > Any suggestions / ideas as to what is going wrong? I don't get any > > other warnings or errors on the other modules. Thanks -- Yosi > > You are aware that the above shows python 2.5 as the version that is > being used for compilation? > > Diez Sorry. I get the same error messages for Python 2.4.4, Python 2.4.5, and Python 2.5. The software package I'm trying to build from source requests that I install Python 2.4.4, so I'm interesting in solutions for that particular distribution. Thanks -- Yosi From benhoyt at gmail.com Wed Mar 19 00:17:49 2008 From: benhoyt at gmail.com (benhoyt) Date: Tue, 18 Mar 2008 21:17:49 -0700 (PDT) Subject: Is there a way to get __thismodule__? References: Message-ID: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> Replying to myself here, after discovering more. :-) > Is there a way to get __thismodule__ in Python? It looks like __thismodule__ is just sys.modules[__name__]. Neat. Hmmm ... does sys.modules always already contain the currently-being- loaded module? Or is this a hack that only happens to work? (It does; I've tested it now.) Just wondering, because the Python docs say that sys.modules is "a dictionary that maps module names to modules which have *already been loaded*." > if isinstance(attr, Message): > nmap[attr.number] = attr Oops, this was untested code. I actually meant issubclass (or something similar) here, not isinstance. Cheers, Ben. From bockman at virgilio.it Mon Mar 24 09:36:13 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 13:36:13 GMT Subject: python library to manipulate PALM documents ? Message-ID: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> Hi all, anybody knows a python equivalent of the perl PALM::Doc module (and eventually other PALM::). I have a e-book device wich reads mobi-pocket format (among others). I have downloaded from a forum a set of perl scripts to convert HTML to unencripted mobipocket format and vice-versa. It uses the PALM:: package. I would attempt (for my convenience and for the fun of it) to make a python equivalent of that. Hence my quest for a Palm::Doc equivalent. My googling up to now resulted in nothing relevant. Keeping searching ... Ciao ----- FB From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:38:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:38:18 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6i47r3uoo6b4@corp.supernews.com> Message-ID: <13t6jcq8srbi28@corp.supernews.com> On Sun, 09 Mar 2008 02:16:39 +0000, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 15:26:35 -0800, Paul Rubin wrote: > >> Alasdair writes: >>> What is the best way of finding a ceiling of a quotient of arbitrary >>> sized integers? >> >> ceiling(a/b) = (a+b-1)//b > > > Unfortunately that doesn't work reliably. But of course you didn't intend it to work with floats, did you? Sigh. I'm just glad I didn't rant about people who think that floats are just like reals when they're not. -- Steven From micah at cowan.name Fri Mar 7 17:41:14 2008 From: micah at cowan.name (Micah Cowan) Date: Fri, 07 Mar 2008 22:41:14 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> <13t3cfpo6d8d2ab@corp.supernews.com> Message-ID: <87ve3y9myd.fsf@micah.cowan.name> Grant Edwards writes: > On 2008-03-07, Steven D'Aprano wrote: > >> Professional typesetters, using proportional fonts, don't use double- >> spaces because it throws off word spacing and line justification and just >> plain looks ugly. > > They do, however, put more space between sentences than they do > between words within a sentence. It is that practice which the > "two spaces after a period" rule in typewriting is attempting > to emulate. Not in most books I've read. AFAICT, it's a (thankfully) disappearing practice in the typesetting profession. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From tmp1 at viltersten.com Sun Mar 2 09:47:17 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 15:47:17 +0100 Subject: Keeping the console window Message-ID: <62vs0iF24tv6jU1@mid.individual.net> I've proudly connected Notepad++ to edit and run my fantastic software. When that started to work, i noticed that all the printing disappears as the console window vanishes upon the program completion. How can i trick Python program to keep on running even if the actual statements have been exectuted? Some kind of reading from keyboard? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From goon12 at gmail.com Tue Mar 11 10:38:22 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 11 Mar 2008 10:38:22 -0400 Subject: How to factor using Python? In-Reply-To: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <6a2ccd190803110738l2ba7d0c0ne4d61b74e6a5d9c8@mail.gmail.com> On Mon, Mar 10, 2008 at 1:08 AM, Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? This should work to do x! (factorial of x). reduce(lambda x,y: x*y, range(1, x+1)) From mail at timgolden.me.uk Fri Mar 7 10:41:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Mar 2008 15:41:03 +0000 Subject: problem with join In-Reply-To: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: <47D1620F.6070200@timgolden.me.uk> nodrogbrown wrote: > hi > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', You've got a couple of options. Your "folder" to start with is in the unixy form a/b/c and the .join function doesn't do anything to change that, merely uses os.pathsep to append the parts to each other. You can either set your folder to be r"f:\brown\code..." in the first case or use os.path.normpath or os.path.abspath on the result. TJG From andymac at bullseye.apana.org.au Thu Mar 13 06:17:59 2008 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 13 Mar 2008 20:17:59 +1000 Subject: problem with Python 2.5.2 and gcc 4.3 In-Reply-To: <7jRBj.20981$QC.15171@newsfe20.lga> References: <7jRBj.20981$QC.15171@newsfe20.lga> Message-ID: <47D8FF57.7060207@bullseye.andymac.org> David P. Riedel wrote: > I tried building Python 2.5.2 using gcc 4.3.0. The build completes with no problems but when I run 'make test', I get a > segfault part way through the test run. > > here is the last part of the output from make test > > test_softspace > test_sort > test_sqlite > test_sqlite skipped -- no sqlite available > test_startfile > test_startfile skipped -- cannot import name startfile > test_str > make: *** [test] Segmentation fault You don't identify the platform or O/S, though I'd guess some Linux distro on i386 or x86-64... If you have gdb available, a backtrace might give a clue. However, as this is a new major release of gcc I'm automatically going to assume an optimisation issue. To test this I'd suggest doctoring the makefile generated by configure to reduce the optimisation level - I'd suggest trying -O instead of -O3. If that works, try -O2 or -Os. If -O2 or -Os works, I'd be taking the matter up with the gcc team. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 14 09:24:27 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Mar 2008 14:24:27 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: <-cudnSGj6P-2JETanZ2dnUVZ_vShnZ2d@speakeasy.net> References: <-cudnSGj6P-2JETanZ2dnUVZ_vShnZ2d@speakeasy.net> Message-ID: <47da7c47$0$15800$426a34cc@news.free.fr> Erik Max Francis a ?crit : > Dave Kuhlman wrote: > >> Basically, the above code is saying that foo.foobar is not the same as >> getattr(foo, 'foobar'). > > Python promises that the behavior is the same. It does not promise that > the _objects_ will be the same, which is what `is` determines. That is, > you're not doing a useful test here. FWIW, two methods are "the same" if they have identical (function, obj, cls) attributes. Looks like the equality test is correctly implemented: >>> foo.bar == foo.bar True HTH From gandalf at shopzeus.com Tue Mar 18 05:44:13 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 18 Mar 2008 10:44:13 +0100 Subject: Decode email subjects into unicode Message-ID: <47DF8EED.1010501@shopzeus.com> Hi All, 'm in trouble with decoding email subjects. Here are some examples: > =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?= > [Fwd: re:Flags Of The World, Us States, And Military] > =?ISO-8859-2?Q?=E9rdekes?= > =?UTF-8?B?aGliw6Fr?= I know that "=?UTF-8?B" means UTF-8 + base64 encoding, but I wonder if there is a standard method in the "email" package to decode these subjects? I do not want to re-invent the weel. Thanks, Laszlo From brad at 16systems.com Fri Mar 28 22:31:07 2008 From: brad at 16systems.com (Brad) Date: Fri, 28 Mar 2008 22:31:07 -0400 Subject: some path issues on windows Message-ID: When reading a file into a list that contains windows file paths like this: c:\documents and settings\brad\desktop\added_software\asus\a.txt I get a list that contains paths that look like this: c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt So, my list contains those funky file paths. And, when I do this: for root, dirs, files in os.walk('C:\\'): for f in files: print os.path.join(root,f) I get the more normal path again: c:\documents and settings\brad\desktop\added_software\asus\a.txt This makes path comparison difficult as I have different strings (the extra \'s). I've tried os.path.normpath(line_reading_in_from_file) but I still get the funky \\ paths. How can I read the paths with an r'path' like meaning? Thanks, Brad From deets at nospam.web.de Wed Mar 12 07:32:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Mar 2008 12:32:48 +0100 Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> Message-ID: <63ptavF28u3flU2@mid.uni-berlin.de> xkenneth wrote: > Hi All, > > Quick question. I've got an XML schema file (XSD) that I've > written, that works fine when my data is present as an XML file. > (Served out by apache2.) Now when I call python as a cgi script, and > tell it print out all of the same XML, also served up by apache2, the > XSD is not applied. Does this have to do with which content type i > defined when printing the xml to stdout? Who's applying the stylesheet? The browser, some application like XmlSpy or what? Diez From hellogaurang at gmail.com Thu Mar 6 02:03:28 2008 From: hellogaurang at gmail.com (hellogaurang at gmail.com) Date: Wed, 5 Mar 2008 23:03:28 -0800 (PST) Subject: Hi Message-ID: Hello can u plz tell how to send and read msg from device(telit-863-GPS) and the coding is in python. if this can happen then plz send the source code to my mail account From deets at nospam.web.de Wed Mar 12 18:31:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 12 Mar 2008 23:31:30 +0100 Subject: How to parse this timestamp? In-Reply-To: References: Message-ID: <63r3u7F283eg1U1@mid.uni-berlin.de> gnu.gcc.help schrieb: > I've got timestamps in a file that look like: > > [19-Aug-2007 07:38:43+216ms NZST] > > How can I parse them? I don't see any way to build a strftime() > format string that can handle the +216ms part. The best I can see is > tearing it all apart with a regex, but I'm trying to avoid that pain > if I can. > > (PS: I have no clue why google groups thinks it should put > "gnu.gcc.help" on the from line) > Then don't use the regexes. Use string.split to separate the string on the +, then parse the left part with strptime, and usp pytz and datetime.timedelta to do the rest. Diez From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:34:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:34:48 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <13t6c58lu2iog2a@corp.supernews.com> On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > I'm also a bit baffled by people who put a comment at the top of every > file that tells you what the filename is. [snip rant] You've never printed out a source file on pieces of dead tree to read on the train on the way home, or in bed or the bath? Yes, some editors will print a header or footer showing the file name, but not all will, or are configured to do so. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 19:03:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 23:03:32 -0000 Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> <13u3660kfnhq412@corp.supernews.com> <74cdd195-2bfa-4548-a16e-bf14c6b07b50@p73g2000hsd.googlegroups.com> Message-ID: <13u5ra4fdbp7235@corp.supernews.com> On Thu, 20 Mar 2008 10:26:14 -0700, Jim wrote: > The program is my first and I'm not a programmer so it will take me some > time to get your recommendation to work. So far the program runs after I > added code based on your example but the program still aborts and none > of the code ("Temporary failure, Skip/Halt/try Again?" or "Unknown > response, boo hiss to you!") in your example is displayed. Try replacing the line: except URLError, e: with: except urllib2.URLError, e: and see if that helps. -- Steven From jgelfand01 at gmail.com Tue Mar 25 17:32:23 2008 From: jgelfand01 at gmail.com (jgelfand) Date: Tue, 25 Mar 2008 14:32:23 -0700 (PDT) Subject: _tkinter fails when installing Python 2.4.4 Message-ID: I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but I get the following error message when I run "make": building '_tkinter' extension gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ usr/local/yosi/Python-2.5.2/Modules/_tkinter.o gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ usr/local/yosi/Python-2.5.2/Modules/tkappinit.o gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so *** WARNING: renaming "_tkinter" since importing it failed: build/ lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents Any suggestions / ideas as to what is going wrong? I don't get any other warnings or errors on the other modules. Thanks -- Yosi From gowricp at gmail.com Tue Mar 18 22:10:48 2008 From: gowricp at gmail.com (Gowri) Date: Tue, 18 Mar 2008 19:10:48 -0700 (PDT) Subject: parsing json output Message-ID: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Hi, I have a service running somewhere which gives me JSON data. What I do is this: import urllib,urllib2 import cjson url = 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/ tbedi/requestDetails' params = {'format':'json'} eparams = urllib.urlencode(params) request = urllib2.Request(url,eparams) response = urllib2.urlopen(request) # This request is sent in HTTP POST print response.read() This prints a whole bunch of nonsense as expected. I use cjson and am unable to figure out how to print this json response and I guess if I can do this, parsing should be straightforward? doing a cjson.decode(str(repsonse)) does not work. In what form is this data returned and how do I print it and later pass it on to another client browser? Typing http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails in my browser returns valid json data. Regards, Gowri From sam at mas.pl Wed Mar 19 12:59:40 2008 From: sam at mas.pl (sam) Date: Wed, 19 Mar 2008 17:59:40 +0100 Subject: Prototype OO Message-ID: Some time ago (2004) there were talks about prototype-based languages and Prothon emerged. Can someone tell me why class-based OO is better that Prototype based, especially in scripting langage with dynamic types as Python is? Here are some links: http://c2.com/cgi/wiki?PrototypeBasedProgramming http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Class-Based_vs._Prototype-Based_Languages -- UFO Occupation www.totalizm.pl From gh at ghaering.de Sat Mar 29 14:41:12 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 29 Mar 2008 19:41:12 +0100 Subject: Problem with sqlite In-Reply-To: References: Message-ID: <657gq6F2dh3fdU1@mid.uni-berlin.de> Ok, I'll review your code. aiwarrior wrote: > class db: > def __init__(self): #constructor > conn = sqlite3.connect('./db.db') > conn.isolation_level = None Autocommit mode is mostly for newbies who forget to call commit. Unfortunately, newbiews find enough other ways to shoot themselves in the foot. So, in retrospect, maybe I should not have added that feature to pysqlite ;-) > self.cursor = conn.cursor() > try: > self.cursor.execute("CREATE TABLE database > (album,filepath)" ) > except: > pass try: except: pass without catching *specific* exceptions is generally a very bad idea. If you're doing something stupid, or another error happens than the one you want to ignore, you will never know this way. > def add_entry( self, eone , etwo ): #Add entry to database > self.cursor.execute( "INSERT INTO database (album,filepath) > VALUES (?,?)", ( eone , etwo ) ) > return 1 #TODO: exception handler > > def get_mediadb( self, print_db = False ): > self.cursor.execute( 'SELECT * FROM database' ) > if (print_db == True): > print self.cursor.fetchall() The if clause can be written as just "if print_db:". > def get_value( self, column ): > self.cursor.execute( "SELECT %s FROM database" % column ) > for n in self.cursor: > print n > > def destructor(self): > self.cursor.close() Just FYI, Python's "destructor" method is called "__del__", not "destructor". > def walking_and_filling(db): > pass > > > if __name__ == "__main__": > db = db() > #walking_and_filling( db ) > for root, dirs, files in os.walk( '''foo_path/''', > topdown=False ): > for name in files: > joined = os.path.join(root, name) > if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): > try: > audio = MP3 (joined, ID3=EasyID3 ) > print (audio['album']) > db.add_entry( joined, audio['album'] ) > except: > pass Now, this try: except: pass is most probably hiding the real error That leads to the insert failing. Because you just ignored any errors, you will never now what exactly went wrong here. > db.get_mediadb( print_db=True ) > > > When i execute this the database doesn't get filled with anything and > the program stays running in memory for ever. [...] HTH, -- Gerhard From hvendelbo.dev at googlemail.com Fri Mar 7 09:53:36 2008 From: hvendelbo.dev at googlemail.com (hvendelbo.dev at googlemail.com) Date: Fri, 7 Mar 2008 06:53:36 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: On Mar 6, 9:17 pm, Luis M. Gonz?lez wrote: > On 6 mar, 11:27, Pierre Quentel wrote: > > > > > Hi, > > > I would like to know if there is a module that converts a string to a > > value of the "most probable type" ; for instance : > > - if the string is "abcd" the value is the same string "abcd" > > - string "123" : value = the integer 123 > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > = the float -1.23 > > - string "2008/03/06" (the format is also locale-dependant) : value = > > datetime.date(2008,03,06) > > > Like in spreadsheets, special prefixes could be used to force the > > type : for instance '123 would be converted to the *string* "123" > > instead of the *integer* 123 > > > I could code it myself, but this wheel is probably already invented > > > Regards, > > Pierre > >>> def convert(x): > > if '.' in x: > try: return float(x) > except ValueError: return x > else: > try: return int(x) > except: return x > > >>> convert('123') > 123 > >>> convert('123.99') > 123.98999999999999 > >>> convert('hello') > > 'hello' Neat solution. The real challenge though is whether to support localised dates, these are all valid: 20/10/01 102001 20-10-2001 20011020 From mensanator at aol.com Sun Mar 23 00:36:10 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 22 Mar 2008 21:36:10 -0700 (PDT) Subject: List question References: <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> <13ubd90qe74ii58@corp.supernews.com> Message-ID: On Mar 22, 8:40?pm, Dennis Lee Bieber wrote: > On Sat, 22 Mar 2008 14:55:39 -0700 (PDT), Zentrader > declaimed the following in comp.lang.python: > > > is funny and not mean. ?In the words of whoever it was in "Gone With > > The Wind", frankly I don't give a damn (except to not mislead relative > > ? ? ? ? Rhett Butler, I believe (I only know two characters by name, You don't remember Ashley? I guess that's only half a name. > and > since the line as I recall it is "Frankly, Scarlett, I ..." it couldn't > have been her [Scarlett] speaking) > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From grante at visi.com Sun Mar 2 10:21:02 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 15:21:02 -0000 Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> Message-ID: <13slheuos7u6afa@corp.supernews.com> On 2008-03-02, Gif wrote: > sorry for acting like a fool but this is just to weirdly easy > that i can't get to work. i've written a small web server in > another language and this is more like copying code. i already > have everything figured out, except this one but noone seems > either willing or capable of helping me. Because you don't seem either willing or capable of describing your problem in enough detail to allow anybody to help you. Post a small program that demonstrates the "problem". Describe precisely how that program fails to do what you want it to. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From sjmachin at lexicon.net Sat Mar 22 18:58:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 15:58:09 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: <7d25f3c5-8dab-4d1a-a825-897299fd5fe9@i12g2000prf.googlegroups.com> On Mar 23, 7:27 am, sgharvey wrote: > ... and by works, I mean works like I expect it to. You haven't told us what you expect it to do. In any case, your subject heading indicates that the problem is 99.999% likely to be in your logic -- the converse would require the result of re.compile() to retain some memory of what it's seen before *AND* to act differently depending somehow on those memorised facts. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: > If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. > If I try to match every pattern to one line at a time, only one > pattern will match. > > What am I not understanding about re.search? Its behaviour is not contingent on previous input. The following pseudocode is not very useful; the corrections I have made below can be made only after reading the actual pastebin code :- ( ... you are using the name "pattern" to refer both to a pattern name (e.g. 'setting') and to a compiled regex. > Doesn't match properly: > > # Iterate through each pattern for each line > for line in lines: > for pattern in patterns: you mean: for pattern_name in pattern_names: > # Match each pattern to the current line > match = patterns[pattern].search(line) you mean: match = compiled_regexes[pattern_name].search(line) > if match: > "%s: %s" % (pattern, str(match.groups()) ) you mean: print pattern_name, match.groups > > > _Does_ match properly: > [snip] > > > Related code: > The whole src http://pastebin.com/f63298772 This can't be the code that you ran, because it won't even compile. See comments in my update at http://pastebin.com/m77f0617a By the way, you should be either (a) using *match* (not search) with a \Z at the end of each pattern or (b) checking that there is not extraneous guff at the end of the line ... otherwise a line like "[blah] waffle" would be classified as a "section". Have you considered leading/trailing/embedded spaces? > regexen and delimiters (imported into whole src) http://pastebin.com/f485ac180 HTH, John From stargaming at gmail.com Tue Mar 25 09:20:50 2008 From: stargaming at gmail.com (Stargaming) Date: 25 Mar 2008 13:20:50 GMT Subject: Need help with OptionParser References: <0a225d25-c544-49d9-9e56-8ecd2d0f7928@s13g2000prd.googlegroups.com> Message-ID: <47e8fc32$0$1915$9b622d9e@news.freenet.de> On Tue, 25 Mar 2008 05:42:03 -0700, hellt wrote: [snip] > usage = "usage: %prog [options]" > parser = OptionParser(usage) > parser.add_option("-f", "--file", dest="filename", > help="executable filename", > metavar="FILE") > parser.add_option("-b", "--bighosts", > action="store_true", dest="bighosts", default=False, > help="with big hosts [default: %default]") > (options, args) = parser.parse_args() > if not options.bighosts: > print parser.print_usage() FWIW you should perhaps give a special error message rather than the generic help (something like "you need to specify bighosts, see --help for details"). If possible, you should use `args` rather than an option (they are, well, optional). But if your program takes a lot of mandatory arguments, using options in order to mix them at will might be fine. HTH, From gagsl-py2 at yahoo.com.ar Sun Mar 30 18:32:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 19:32:39 -0300 Subject: Build complete, now I just need to "install" it... References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 12:04:10 -0300, axl escribi?: > I'm going to be adding some features for a python-project with > external modules written in C. However, if I build modules with my > MSVS 2008 compiler (from the Windows SDK), they won't load in Python > 2.5.2, which is built with MSVS 2003. > > Since I don't have access to MSVS 2003 I need to rebuild Python using > MSVS 2008 in order for the binaries to go along. > > For starters, I cloned the PCbuild8 folder and made whatever changes > needed to be able to build the core and executable. I then pulled down > all the various external dependencies and made the same adjustments to > those. After quite a while I've managed to build everything apart from Which changes are those? I can build Python straight from the svn sources. > But, my problem is that the install scripts, i.e. "python setup.py > install" wants to go through the build steps again, but since those > don't work on Windows, or at least not with my setup, I can't put > together a complete package. The MSI package generation is at Tools\msi in the source tree. There are a few preliminary steps that must be done (only once) before successfully building the installer, you'll notice as you go (the script will tell you what's missing; a .rc file has to be compiled, as far as I remember). Would be nice if you take note of them so one can write down the proper build sequence. -- Gabriel Genellina From exxfile at hotmail.com Mon Mar 24 15:28:58 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 12:28:58 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> Message-ID: On Mar 24, 12:18?pm, George Sakkis wrote: > On Mar 24, 3:13 pm, pythonnubie wrote: > > > > > > > > > i ?have ?come across my first exeption using randrange . The exeption > > > > is " no such ?attribute " in ?module random > > > > > platform ?is xp ?home ?and the python ?build is activestate 2.5 > > > > Welcome aboard! > > > > There's definitely a randrange function in the random module, so > > > something else must be wrong. To get the most out of this list and > > > minimize wasted bandwidth, the most effective way usually consists of > > > copying and pasting: > > > 1. The offending code (or just the relevant part if it's too big). > > > 2. The full traceback of the raised exception. > > > > Regards, > > > George > > > Hwere is the complete traceback ! >>> The word is: ?index > > > Traceback (most recent call last): > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 307, in RunScript > > ? ? debugger.run(codeObject, __main__.__dict__, start_stepping=0) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \__init__.py", line 60, in run > > ? ? _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \debugger.py", line 631, in run > > ? ? exec cmd in globals, locals > > ? File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, > > in > > ? ? import random > > ? File "F:\Documents and Settings\Mark\My Documents\random.py", line > > 13, in > > ? ? distributions on the real line: > > AttributeError: 'module' object has no attribute 'randrange' > > > Why ?would it say ?it can't find the function ? > > Because you named your file 'random.py' and it shadows the standard > random module! Change the name to something else, say foo.py, and try > it again. > > George- Hide quoted text - > > - Show quoted text - From paul.hermeneutic at gmail.com Tue Mar 11 17:38:54 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 11 Mar 2008 16:38:54 -0500 Subject: SOAP access to SharePoint Message-ID: <1205271534.4382.5.camel@localhost.localdomain> Has anyone successfully accessed a Microsoft SharePoint WSS using Python? No, not IronPython. I need for this to be able to run on all machines the customer might choose. Which libs are you using? ZSI, SOAPpy, soaplib, ??? http://wiki.python.org/moin/WebServices From __peter__ at web.de Sat Mar 29 09:03:05 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 29 Mar 2008 14:03:05 +0100 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Wikipedia doesn't believe that M-D is the primary or most common name, > and the link you give redirects to "Taxicab distance". Googlefight > agrees: "Taxicab distance" is more than twice as common, and "rectilinear > distance" more than five times as common. Could it be that there are many documents containing both taxicab and distance that have nothing to do with the "taxicab distance"? Searching with quotes around the search term google advertises about 936 results for "taxicab distance" 6930 for "rectilinear distance" 38200 for "manhattan distance" > The very name is New York-centric, just as much as if the English called > the science of acoustics "Big-Ben-onics" in reference to the peals of Big > Ben's clock. I had thought I had pointed that out with a little gentle > understatement. Whether you like a term and agree with its (alleged) bias or if it's in common use are two different questions. I think Robert addressed the latter while your answer implied the former. Peter From mensanator at aol.com Mon Mar 3 16:47:42 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 13:47:42 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> Message-ID: <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> On Mar 3, 2:49?pm, Carl Banks wrote: > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > > > Notice anything funny about the "random" choices? > > > import sympy > > import time > > import random > > > f = [i for i in sympy.primerange(1000,10000)] > > > for i in xrange(10): > > ? f1 = random.choice(f) > > ? print f1, > > ? f2 = random.choice(f) > > ? print f2, > > ? C = f1*f2 > > ? ff = None > > ? ff = sympy.factorint(C) > > ? print ff > > > ## ?7307 7243 [(7243, 1), (7307, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > ## ?8563 2677 [(2677, 1), (8563, 1)] > > ## ?4091 6829 [(4091, 1), (6829, 1)] > > > As in, "they're NOT random". > > > The random number generator is broken by the sympy.factorint() > > function. > > > Random.choice() works ok if the factorint() function commented out. > > > ## ?6089 1811 None > > ## ?6449 1759 None > > ## ?9923 4639 None > > ## ?4013 4889 None > > ## ?4349 2029 None > > ## ?6703 8677 None > > ## ?1879 1867 None > > ## ?5153 5279 None > > ## ?2011 4937 None > > ## ?7253 5507 None > > > This makes sympy worse than worthless, as it f***s up other modules. > > Dude, relax. > > It's just a bug--probably sympy is messing with the internals of the > random number generator. ?It would be a simple fix. ?Instead of > b****ing about it, file a bug report. ? I did. > Or better yet, submit a patch. I would if I knew what the problem was. I posted it here because someone recommended it. I'm simply un-recommending it. Those who don't care needn't pay any attention. Those who do should be glad that faults are pointed out when found. > > Carl Banks From kyosohma at gmail.com Mon Mar 17 09:45:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 17 Mar 2008 06:45:32 -0700 (PDT) Subject: wxPython graphics query (newbie) References: Message-ID: On Mar 17, 7:03 am, Thomas G wrote: > I am exploring wxPython and would be grateful for some help. > > It is important to me to be able to slide words and shapes around by > dragging them from place to place. I don't mean dragging them into a > different window, which is what 'Drag and Drop' has come to mean, just > moving them around within a canvas-like space. > > This is easy using Tkinter. Can anybody offer me a tiny, very simple > example of how it would be done in wxPython, please? > > To make sure I convey what I'm looking for, here is what it looks like > using Tkinter, written very simply. What I'm looking for is the same, > quite simple functionality expressed in wxPython, again written very > simply so that I can easily understand it. > > #!/usr/bin/python > from Tkinter import * > > root = Tk() > > global canv > > def makeFrame(root): > global canv > canv = Canvas (root, height = 200, width = 350) > canv.create_text(100, 100, text='drag me', tags=('movable')) > > canv.tag_bind('movable', '', slide) #B1-motion is a drag > with left button down > canv.pack() > > def slide (event): > ''' > triggered when something is dragged on the canvas - move thing under > mouse ('current') to new position > ''' > newx = event.x > newy = event.y > canv.coords('current', newx, newy) > > makeFrame(root) > root.mainloop() > > Many thanks in advance > > -- Thomas Green Hmmm...I'm not sure how to do that. Please post this same question to the wxPython user's group. They'll know if anyone does: http://wxpython.org/maillist.php Mike From ilias at lazaridis.com Sun Mar 9 05:24:32 2008 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 9 Mar 2008 01:24:32 -0800 (PST) Subject: Trac - Does it make sense to keep http://trac.edgewall.org/ticket/4315 open? Message-ID: Response to message [1] on trac.devel (as I cannot write there, due to an informally applied censorship) Mr. Boos: "I left that ticket open simply to avoid having someone to reopen it over and over..." (note to reader: this someone is me) Mr. Boos, the ticket status should reflect reality. So, if reality says "the ticket is open", no one can (should" close it. The essens of the ticket is, that you should trust you own results. You should use your development version, in order to obtain feedback. Of course I understand (seeing the terrible processes of the team), that you distrust your own results, prefering to let user do the dirty work of development-version-usage. Your inability to follow even the most rational suggestions subjecting development-processes, e.g. this one: http://trac.edgewall.org/ticket/6614#comment:36 will lead (together with the terrible quality of the trac source-code base) soon to an even more stucked development progress. Be assured that users see this (although they don't say much, like me). Do you actually realize that you're working since over a year on 0.11? Nothing is more fun that to watch the trac project running into one after another problem during development. At least you give other teams a good example of "how to ruine a good open-source product". http://case.lazaridis.com/wiki/TracAudit - To readers: The project hunts since months a memory-leak - without success. I'm wondering that python makes so much trouble in finding it. Seems to be another very fundamental reason to leave this "joke of a language" (python). - [1] http://groups.google.com/group/trac-dev/msg/1cbcaf2b5fdc8abe From: Christian Boos Jeroen Ruigrok van der Werven wrote: > Does it make sense to keep http://trac.edgewall.org/ticket/4315 open? I left that ticket open simply to avoid having someone to reopen it over and over... That ticket is a bit useless in that it has anyway always been the policy of the project to run the latest stable release. And that works quite well in practice. I imagine t.e.o would already be running 0.11b1 now, if we didn't have those memory issues. As for documenting the blocker issues, doing that directly on the milestone page is more effective anyway. So I'd say let's just not make a fuss about this one and we'll close it once t.e.o gets upgraded to 0.11. -- Christian From deets at nospam.web.de Sat Mar 29 18:48:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 23:48:26 +0100 Subject: Installing simplejson issues In-Reply-To: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> Message-ID: <657v9rF2eatagU1@mid.uni-berlin.de> blwatson at gmail.com schrieb: > I am trying to install the twitter python wrapper...I got that > installed just fine, but am having serious troubles getting the > simplejson package to install. I need help diagnosing where this is > failing. I am trying to use: > > http://pypi.python.org/pypi/simplejson > > and I run "python setup.py build" and then "python setup.py install", > which both seem to work just fine. > > I tried running with easy_install, but that too is not working. I end > up with: > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > in my: > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > packages/ > > I am on Mac OS X 10.5. Any help would be greatly appreciated. Go to the turbogears file section and download an appropriate version of simplejson: http://www.turbogears.org/download/filelist.html I presume sj-1.7.4 is sufficient. Alternatively, be gentle to your unixish OS that OS X is, and install XCode. Which will install the whole GCC chain, making your OS a respected member of OS-community - as every system should be able to compile C-code, in which itself has been written. Then the install should work as well. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:44:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:44:31 -0000 Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: <13t3dpvaiivm46@corp.supernews.com> On Fri, 07 Mar 2008 09:49:58 -0800, Krishna wrote: > I am more interested in knowing about the first argument ('self'), what > does it hold to allow the evaluation of the method, take the example you > gave, 'self.a' as Rvalue inside the method, how and why is this allowed, "self" is treated as an argument like any other argument, except that when you call a method on an instance Python automatically provides the self for you. Consider the following piece of code: >>> class Parrot(object): ... def squawk(self, n): ... return "spam " * n ... >>> instance = Parrot() >>> instance.squawk(3) 'spam spam spam ' >>> Parrot.squawk(instance, 3) 'spam spam spam ' In the first call, I call the squawk() method from the instance, and Python automatically fills in the self argument. In the second call, I call the squawk() method from the class. Since the class doesn't know what instance I'm using, I have to manually provide the self argument. But inside the method, self is just a name in a namespace, like any other name. It's not special. You can do anything you like to it. You can even re-assign to it, or delete it: >>> class Spam(object): ... def spam(self): ... print "I am", self ... self = "foo" ... print "Now I am", self ... >>> x = Spam() >>> x.spam() I am <__main__.Spam object at 0xb7f5192c> Now I am foo >>> x <__main__.Spam object at 0xb7f5192c> > when the same 'self.a' is not allowed as the default argument, It isn't that self.a is "not allowed". Python doesn't contain any code that says "if the default value contains "self", raise an error. You can prove that for yourself: >>> def foo(x=self): ... return x ... Traceback (most recent call last): File "", line 1, in NameError: name 'self' is not defined >>> >>> self = 2 >>> def foo(x=self): ... return x ... >>> foo() 2 > considering the fact that I have already specified 'self' as first > argument, only after whose evaluation, I believe would the next > statement (k = self.a, in def func(self, k = self.a) ) gets evaluated You believe wrong. You've already been told that the function default "k=self.a" is evaluated when the method is compiled, not at runtime. Since "self" doesn't exist at compile time, it is an error. There is no way to create a reference to a class instance before the class is even defined. -- Steven From sjmachin at lexicon.net Wed Mar 19 17:48:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 14:48:37 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> Message-ID: <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> On Mar 19, 10:08 am, sturlamolden wrote: > On 18 Mar, 23:45, Arnaud Delobelle wrote: > > > > def nonunique(lst): > > > slst = sorted(lst) > > > dups = [s[0] for s in > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > > return [dups[0]] + [s[1] for s in > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > Argh! What's wrong with something like: > > > def duplicates(l): > > i = j = object() > > for k in sorted(l): > > if i != j == k: yield k > > i, j = j, k > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) > as opposed to ours which are O(N log N). I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, and is IMHO more readable than Paul's. From hdante at gmail.com Sun Mar 30 07:41:56 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 04:41:56 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: On Mar 30, 2:35 am, "Gabriel Genellina" wrote: > En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: > > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > > if x ? 0: > > ?y ? s: > > if y ? 0: f1(y) > > else: f2(y) > > Fine if you have the right keyboard... Try to write APL with a standard > keyboard :) > > -- > Gabriel Genellina My sugestion considered using standard keyboards (hint: read again). From fossks at cox.net Sat Mar 8 17:34:28 2008 From: fossks at cox.net (Kevin) Date: Sat, 8 Mar 2008 14:34:28 -0800 Subject: Fwd: [PyQt] Popen + poll & pid References: <2AB85B94-D410-4409-9F4E-5008E2EDB76E@cox.net> Message-ID: Hi, I sent the question below to the wrong list. I was wondering if someone here could help? Kevin Sent from my iPhone Begin forwarded message: > From: Kevin > Date: March 8, 2008 11:53:39 AM PST > To: "pyqt at riverbankcomputing.com" > Subject: [PyQt] Popen + poll & pid > > I've been trying to use the poll and pid attributes of popen to > determine if mplayer is finished playing an audio track. I've tried > using popen, popen2, popen3, etc but it tells me that there is no > poll or PID module. > > Could anyone help me with a proper method to determine if a process > is running or ended so that I can move to the next track and start > another iteration? > > Either that or does someone know how to change audio cd tracks in > mplayer slave mode? ;) > > Kevin > > > Sent from my iPhone > _______________________________________________ > PyQt mailing list PyQt at riverbankcomputing.com > http://www.riverbankcomputing.com/mailman/listinfo/pyqt -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Thu Mar 13 19:32:43 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 13 Mar 2008 16:32:43 -0700 (PDT) Subject: Spaces in path name References: Message-ID: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> On Mar 13, 5:16?pm, "David S" wrote: > Hi, > > I have some code in which I have to change some path names to get it to > work. The original code seems to have assumed that path names would not have > any embedded spaces. > > I am not sure how to write the following line so when used in my script the > path will be found. > > ANT_CMD ?= r'C:\Program Files\apache-ant-1.7.0\bin\ant' Try ANT_CMD = r'"C:\Program Files\apache-ant-1.7.0\bin\ant"' > > Regards, > David From timr at probo.com Fri Mar 21 00:46:14 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Mar 2008 04:46:14 GMT Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: Christian Heimes wrote: > >Yes, it sounds like a good idea. The low hanging fruits (aka easy tasks) >could be implemented for 2.6 and 3.0. The more complex tasks may have to >wait for 2.7 and 3.1 I thought there wasn't going to be a 2.7... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From inq1ltd at inqvista.com Thu Mar 27 18:08:05 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 27 Mar 2008 18:08:05 -0400 Subject: python program deleted In-Reply-To: References: Message-ID: <200803271808.06157.inq1ltd@inqvista.com> py users, I developed a python program and used py2exe to create the exe. I zip the entire package and email it to my clients. Some clients get the zip file, unzip the package and everything works fine. And some clients get my email with an icon attached which has the correct filename but the size is 8k when it should be about 5 mb. I've renamed the file without the zip ext. and tried other renaming schemes without success. Has anyone had this experience? Any ideas on how to solve this problem. jim-on-linux From egbert.bouwman at hccnet.nl Sun Mar 9 11:38:10 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Sun, 9 Mar 2008 16:38:10 +0100 Subject: for-else In-Reply-To: References: <20080308152034.GA12009@hccnet.nl> Message-ID: <20080309153810.GA16012@hccnet.nl> On Sat, Mar 08, 2008 at 04:15:31PM -0500, Terry Reedy wrote: > > I am sorry if you cannot appreciate such elegance > and can only spit on it as 'orwellian'. > I admire the elegance of your examples and your explanation. I will keep a copy of it in my Beazley, for I am afraid I have to read it again. As for orwellian, I must admit that I was quite happy when I thought of using that word, but that it was not my luckiest thought. But I have to persist in my malice. In the following snippet it is not at all clear to the naive programmer (me) that the else refers to an iterator_is_exhausted condition, whatever logical explanation you may offer. . for each_item in item_list: . do_something() . else: . do_else() My temporary solution will be to accompany this else with an appropriate comment: # exhausted e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From deets at nospam.web.de Sun Mar 16 19:49:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 00:49:33 +0100 Subject: Advantage of the array module over lists? In-Reply-To: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> References: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> Message-ID: <645q0hF28fnk3U1@mid.uni-berlin.de> sturlamolden schrieb: > On 13 Mar, 20:40, Tobiah wrote: >> I checked out the array module today. It claims that >> arrays are 'efficient'. I figured that this must mean >> that they are faster than lists, but this doesn't seem >> to be the case: >> >> ################ one.py ############## >> import array >> >> a = array.array('i') >> >> for x in xrange(10000000): >> a.append(x) > > > Lists are better optimized for appending to the end. Python lists are > implemented as arrays of pointers, with a few empty slots at the > end. > > Arrays are contigous memory buffers. They provide faster read-write > access, particularly for chunks of data, but are slower at resizing. I doubt that. AFAIK both arrays and lists are continuous memory-areas, that double (at least to a certain threshold or so) when reaching the capacity limit. lists are of type PyObject* of course, whereas arrays are not, instead they are of their respective primitive type, making them more memory efficient. Diez From bronger at physik.rwth-aachen.de Wed Mar 19 04:41:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 19 Mar 2008 09:41:10 +0100 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> Message-ID: <87k5jzumvt.fsf@physik.rwth-aachen.de> Hall?chen! wesley chun writes: > http://it.slashdot.org/it/08/03/18/1633229.shtml > > it was surprising and disappointing that Python was not mentioned > *anywhere* in that article but when someone replied, it sparked a > long thread of post-discussion. Well, not because I like Python so much, but I find this blog entry highly unoriginal. Browsing through Wikipedia gives more insight ... Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From ggpolo at gmail.com Tue Mar 25 18:13:00 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 25 Mar 2008 19:13:00 -0300 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: 2008/3/25, Dark Wind : > Hi, > > In most of the languages ^ is used for 'to the power of'. In python we have > ** for that. But what does ^ do? It is bitwise xor. Some more information can be found at http://docs.python.org/ref/bitwise.html > I could not get it just by using it ... some examples are: > 1^1 returns 0 > 2^2 returns 0 > 1^4 returns 5 > 4^1 returns 5 > 3^5 returns 6 > 5^3 returns 6 ...... > > just curious > > Thank you > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From deets at nospam.web.de Sat Mar 1 12:53:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 01 Mar 2008 18:53:26 +0100 Subject: tcp functions In-Reply-To: References: Message-ID: <62tjgmF24ui98U1@mid.uni-berlin.de> Gif schrieb: > is there a module for tcp functions or any other quick way to connect, > listen, send and recieve from tcp? > thanks in advance Reading the docs helps - hint: module "socket". Diez From clodoaldo.pinto at gmail.com Tue Mar 25 10:58:30 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Tue, 25 Mar 2008 11:58:30 -0300 Subject: sendmail should throw an exception but does not In-Reply-To: <20080325102113.d8688b7f.darcy@druid.net> References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> <20080325102113.d8688b7f.darcy@druid.net> Message-ID: 2008/3/25, D'Arcy J.M. Cain : > On Tue, 25 Mar 2008 06:39:57 -0700 (PDT) > Clodoaldo wrote: > > I need to know if an email was refused for whatever reason, it makes > > no difference. > > > > The email is sent to an email address that does not exist in a foreign > > domain. I can see in the postfix log that the email was sent and > > bounced with the error code 550. > > > That's the sendmail daemon, not your program. > > > > The problem is that sendmail should throw an exception but it does > > not. And the returned dictionary is empty as if the email was > > accepted. > > > > d = smtpserver.sendmail(sender, recipient, m.as_string()) > > > What this does is connect to your sendmail server and submit the email > for sending. The server accepts the email and queues it up as asked. > No error here. > > > > I guess that the error code returned by the destination mail server is > > not is not forwarded to the client by my mail server. > > > It can't. By the time it finds out that there is a problem you have > already closed the connection to the sendmail server. > > To do what you want you have to connect to the remote server yourself. > This is a more complicated operation and there are still problems. > First of all, your ISP may not allow you to connect to remote mail > servers. Second, some [broken] mail servers will accept your email and > only check and bounce after you have disconnected. > > I'm not sure what you are trying to do but you may want to consider > using an Error-to: header that points to an email robot and manage > bounces asynchronously. Thanks for the objective answer. I'm now reconnected to reality. The problem i'm trying to solve is to check if an email address is valid. That email address is used to register in a site. I'm already doing the confirmation email path. The confirmation email prevents someone to register with a forged email but also prevents those who simple don't know exactly what their email is. Yes the email must be typed twice but still people get the email wrong just because they don't know for sure what it is. I can see it clearly when they mistype the correct domain. It happens that atracting those people is expensive and i can't afford to loose them. Thats why i would like to check the email at registration time. Also those who try to register with a forged email would learn that the email must be confirmed and could then issue a correct email. I guess it is not possible or is too complex because i never saw it done. Regards, Clodoaldo Pinto Neto From Greg Tue Mar 25 11:38:53 2008 From: Greg (Greg) Date: Tue, 25 Mar 2008 16:38:53 +0100 Subject: Creating dynamic objects with dynamic constructor args Message-ID: <47e91c8d$0$5151$9a6e19ea@unlimited.newshosting.com> I'd like to create objects on the fly from a pointer to the class using: instance = klass() But I need to be able to pass in variables to the __init__ method. I can recover the arguments using the inspect.argspec, but how do I call __init__ with a list of arguments and have them unpacked to the argument list rather than passed as a single object? ie. class T: def __init__(self, foo, bar): self.foo = foo self.bar = bar argspec = inspect.argspec(T.__init__) args = (1, 2) ??? how do you call T(args)? Thanks. Greg From doug.farrell at gmail.com Thu Mar 20 10:46:38 2008 From: doug.farrell at gmail.com (writeson) Date: Thu, 20 Mar 2008 07:46:38 -0700 (PDT) Subject: Can I dyanmically add Pyro objects to a running Pyro server? Message-ID: Hi everyone, I'm trying to build a distributed system using the code in the examples/distributed_computing2 directory of the Pyro un-tarred distribution. I'm trying to make this generic so one Pyro class can kick off another on mulit-core/multi-cpu/multi-server systems. What I'd like to know is this, after you've got the server.requestloop() running in the Pyro server, is it possible to add objects to the system? As in calling server.connect again with a new class and have the daemon provide access to that. I'm essentially trying to dynamically add Pyro objects to a running Pyro server. Thanks in advance for your help, Doug From martin at v.loewis.de Mon Mar 31 17:45:04 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 31 Mar 2008 23:45:04 +0200 Subject: CTypes, 64 bit windows, 32 bit dll In-Reply-To: References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: <47F15B60.2050306@v.loewis.de> > Crap, no way to make a 32 bit load, even using the wowexec? With WoW64, you can run 32-bit processes on a 64-bit system (as you do all the time). That's all it does. You cannot load a 64-bit DLL into a 32-bit application, or vice versa. If you want to load a 32-bit DLL on Win64, use the 32-bit Python. Regards, Martin From skip at pobox.com Fri Mar 28 10:52:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 28 Mar 2008 09:52:07 -0500 Subject: Summary of threading for experienced non-Python programmers? Message-ID: <18413.1559.451510.750097@montanaro-dyndns-org.local> I'm having trouble explaining the benefits and tradeoffs of threads to my coworkers and countering their misconceptions about Python's threading model and facilities. They all come from C++ and are used to thinking of multithreading as a way to harness multiple CPU cores for compute-bound processing. I also encountered, "Python doesn't really do threads" today. *sigh* I don't need pointers to the relevant documentation sections. A bit of googling didn't turn up much about threading beyond tutorial introductions. I'm looking for something which will explain the rationale for using threads in Python to someone who is experienced with multithreading in other languages (like C/C++). Maybe a compare-and-contrast sort of document? Thanks, Skip From seandavi at gmail.com Wed Mar 26 17:28:20 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 26 Mar 2008 14:28:20 -0700 (PDT) Subject: Line segments, overlap, and bits Message-ID: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> I am working with genomic data. Basically, it consists of many tuples of (start,end) on a line. I would like to convert these tuples of (start,end) to a string of bits where a bit is 1 if it is covered by any of the regions described by the (start,end) tuples and 0 if it is not. I then want to do set operations on multiple bit strings (AND, OR, NOT, etc.). Any suggestions on how to (1) set up the bit string and (2) operate on 1 or more of them? Java has a BitSet class that keeps this kind of thing pretty clean and high-level, but I haven't seen anything like it for python. Thanks, Sean From python.list at tim.thechases.com Tue Mar 4 14:38:05 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Mar 2008 13:38:05 -0600 Subject: Python an Exchange Server In-Reply-To: References: Message-ID: <47CDA51D.3030801@tim.thechases.com> > Hi friends. Someone know how to work with python and exchange > server?. I've used both imaplib[1] and smtplib[2] (in the standard library) for talking successfully with an Exchange server. I don't do much with POP3, but there's also a poplib module[3] in the standard library. I just wrote some imaplib code this morning to work with an existing Exchange mailbox and some smtplib code last week for sending email through an Exchange box. Exchange offers other proprietary functionality, exposed through the MAPI. You might be able to use some of the Win32 functionality in one of the add-on modules for talking with COM objects. -tkc [1] http://docs.python.org/lib/module-imaplib.html [2] http://docs.python.org/lib/module-smtplib.html [3] http://docs.python.org/lib/module-poplib.html From Dominique.Holzwarth at ch.delarue.com Thu Mar 20 09:03:17 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 20 Mar 2008 13:03:17 +0000 Subject: Problem with PARAGRAPH SEPARATOR Message-ID: <8D5970DD46B50A409A0E42BA407964FE0E6A67DA@SGBD012007.dlrmail.ad.delarue.com> Hello everyone I'm doing a transformation with (MSXML) from a xml file to a tex file (actually it's just output format "text" with tex commands inside). The output of the transformation (a big string containg the whole file) contains a so called 'paragraph separator' (unicode: 2029). If I want to pring that string (file) to the std out or a file object then I get a "UnicodeError" saying that the unicode 2029 can't be encoded... Can anyone please tell me how I should handle that paragraph seperator? I must say, that I don't even know WHY my output file has such a character but I'd kinda like to keep it there and just be able to store the string in a file object / print it to console... Thanks in advance Dominique ********************************* This e-mail and any files attached are strictly confidential, may be legally privileged and are intended solely for the addressee. If you are not the intended recipient please notify the sender immediately by return email and then delete the e-mail and any attachments immediately. The views and or opinions expressed in this e-mail are not necessarily the views of De La Rue plc or any of its subsidiaries and the De La Rue Group of companies, their directors, officers and employees make no representation about and accept no liability for its accuracy or completeness. You should ensure that you have adequate virus protection as the De La Rue Group of companies do not accept liability for any viruses De La Rue plc Registered No.3834125, De La Rue Holdings plc Registered No 58025 and De La Rue International Limited Registered No 720284 are all registered in England with their registered office at: De La Rue House, Jays Close, Viables, Hampshire RG22 4BS From jbellis at gmail.com Mon Mar 17 07:44:34 2008 From: jbellis at gmail.com (Jonathan Ellis) Date: Mon, 17 Mar 2008 04:44:34 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <46d77235-b53f-4240-a687-f8026cbd05b1@13g2000hsb.googlegroups.com> On Mar 16, 10:20?am, Barry Hawkins wrote: > I shared the same perception as Bruce; most "keynotes" > and lightning talks were anemic vendor pitches that really gutted the > spirit of what I experienced last year. ? I don't think you can lump the keynotes in with the lightning talks. I had to go check the schedule to see which keynotes were "diamond" ones. I wasn't thinking to myself, "oh, this must be a paid keynote" at the time at all. In fact, the Google one was the most entertaining of all, judging by audience reaction. But the vast majority of the vendor lightning talks were a waste of time, I agree. -Jonathan From Graham.Dumpleton at gmail.com Mon Mar 31 18:13:18 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 31 Mar 2008 15:13:18 -0700 (PDT) Subject: Problem with mod_python/3.3.1 and apache References: Message-ID: On Apr 1, 8:03 am, NccWarp9 wrote: > Hello, > > im using Apache HTTPD 2.2.8 with mod_python/3.3.1 Python/2.4.3 on > Windows and having truble starting pythone, any help would be > appreciated > . > Im getting this error: > > [Mon Mar 31 23:53:03 2008] [error] make_obcallback: could not import > mod_python.apache.\n > 'import site' failed; use -v for traceback > 'import site' failed; use -v for traceback > ImportError: No module named mod_python.apache > [Mon Mar 31 23:53:03 2008] [error] make_obcallback: Python path being > used "['C:\\\\Windows\\\\system32\\\\python24.zip', '', 'c:\\\\xampp\\\ > \python\\\\DLLs', 'c:\\\\xampp\\\\python\\\\lib', 'c:\\\\xampp\\\ > \python\\\\lib\\\\plat-win', 'c:\\\\xampp\\\\python\\\\lib\\\\lib-tk', > 'C:\\\\xampp\\\\apache\\\\bin']". > [Mon Mar 31 23:53:03 2008] [error] get_interpreter: no interpreter > callback found. > [Mon Mar 31 23:53:03 2008] [error] [client 127.0.0.1] python_handler: > Can't get/create interpreter., referer:http://localhost/python/ > [Mon Mar 31 23:53:25 2008] [error] make_obcallback: could not import > mod_python.apache.\n > ImportError: No module named mod_python.apache > > thx See: http://www.modpython.org/pipermail/mod_python/2008-March/025022.html Also search the www.modpython.org site for other discussions/ suggestions in the mod_python mailing list. Graham From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:07:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:07:24 -0300 Subject: Signal problem References: Message-ID: En Thu, 27 Mar 2008 16:27:16 -0300, Fabio Durieux Lopes escribi?: > On daemon.py I have: > > terminate = False > > def signalHandler(signum, frame): > terminate = True > > And my main loop goes like this: > > 'while(not daemon.terminate):' > > When the signal treatment was in the same file as my loop it > worked just fine, and since I've separated it in another file it > stopped working. The SIGALRM treatment, which remains in the same > file, is still working. Any reason why it doesn't treat SIGTERM > anymore? Does it have anything to do with the fact that 'terminate' > is not a class variable? Any ideas? Is "daemon.py" your main entry point? That is, is it the one you execute? In that case, the module is initially imported as "__main__", not as "daemon"; if you "import daemon" from another file, you'll end with TWO different loaded modules for the SAME file (because "daemon" was not in sys.modules, so Python thinks it was not imported yet, and loads it again). A rule might say: Your main script may import anything, but no one may import the main script. -- Gabriel Genellina From castironpi at gmail.com Sat Mar 29 22:42:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 19:42:39 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Message-ID: <44fbc675-8e40-44a5-988f-7d1cdb26c977@m73g2000hsh.googlegroups.com> On Mar 29, 2:11?pm, Gary Herron wrote: > Bryan.Fodn... at gmail.com wrote: > > Hello, > > > I am having trouble writing the code to read a binary string. ?I would > > like to extract the values for use in a calculation. > > > Any help would be great. > > Without having looked at your code an any detail, may I humbly suggest > that you throw it all out and use the struct module: > > ? ?http://docs.python.org/lib/module-struct.html > > It is meant to solve this kind of problem, and it is quite easy to use. > > Gary Herron > > > > > Here is my function that takes in a string. > > > def parseSequence(data, start): > > > ? ? group_num = data[start:start+2] > > ? ? element_num = data[start+2:start+4] > > ? ? vl_field = data[start+4:start+8] > > ? ? length = struct.unpack('hh', vl_field)[0] > > ? ? value = data[start+8:(start+8+length)] > > ? ? pos = start+8+length > > ? ? element = (group_num+element_num) > > > ? ? if element == '\xfe\xff\x00\xe0': > > ? ? ? ? data = value > > > ? ? ? ? while start < length: > > ? ? ? ? ? ? group_num = data[start:start+2] > > ? ? ? ? ? ? element_num = data[start+2:start+4] > > ? ? ? ? ? ? vl_field = data[start+4:start+8] > > ? ? ? ? ? ? length = struct.unpack('hh', vl_field)[0] > > ? ? ? ? ? ? value = data[start+8:(start+8+length)] > > ? ? ? ? ? ? start = start+8+length > > ? ? ? ? ? ? element = (group_num+element_num) > > > ? ? ? ? ? ? if element == '\xfe\xff\x00\xe0': > > ? ? ? ? ? ? ? ? data = value > > > ? ? ? ? ? ? ? ? while start < length: > > ? ? ? ? ? ? ? ? ? ? group_num = data[start:start+2] > > ? ? ? ? ? ? ? ? ? ? element_num = data[start+2:start+4] > > ? ? ? ? ? ? ? ? ? ? vl_field = data[start+4:start+8] > > ? ? ? ? ? ? ? ? ? ? length = struct.unpack('hh', vl_field)[0] > > ? ? ? ? ? ? ? ? ? ? value = data[start+8:(start+8+length)] > > ? ? ? ? ? ? ? ? ? ? start = start+8+length > > ? ? ? ? ? ? ? ? ? ? element = (group_num+element_num) > > ? ? ? ? ? ? ? ? ? ? return element, start, value > > > ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? return element, start, value > > > ? ? else: > > ? ? ? ? return ?element, pos, value > > > And, here is a sample string (I have split up and indented for > > readability). ?There is an identifier (\xfe\xff\x00\xe0) followed by > > the length of the nested values. > > > '\xfe\xff\x00\xe0\x18\x02\x00\x00 ? ? -length=536 > > ? ? ?\n0q\x00\x02\x00\x00\x001 > > ? ? ?\n0x\x00\x02\x00\x00\x0010 > > ? ? ?\n0\x80\x00\x02\x00\x00\x004 > > ? ? ?\n0\xa0\x00\x02\x00\x00\x000 > > ? ? ?\x0c0\x04\x00\xe8\x01\x00\x00 > > ? ? ?\xfe\xff\x00\xe0p\x00\x00\x00 ? ? -length=112 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x00127.378510918301 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x001 > > ? ? ?\xfe\xff\x00\xe0p\x00\x00\x00 ? ? -length=112 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x0c\x00\x00\x001.629998e-1 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x0023.159729257873 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x004 > > ? ? ?\xfe\xff\x00\xe0t\x00\x00\x00 ? ? ?-length=116 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x10\x00\x00\x001.26285318894435 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x00227.690980638769 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x003 > > ? ? ?\xfe\xff\x00\xe0t\x00\x00\x00 ? ? ?-length=116 > > ? ? ? ? ? \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > > \189.182112099444 > > ? ? ? ? ? \n0\x84\x00\x10\x00\x00\x001.52797639111557 > > ? ? ? ? ? \n0\x86\x00\x10\x00\x00\x00263.433384670643 > > ? ? ? ? ? \x0c0\x06\x00\x02\x00\x00\x002 ')- Hide quoted text - Binaries can come from computers as from people. Synth sound & graphics. Start structuring primitive binaries: What operation can you run in real-time? I would probably have to learn natural language to make any sense of his keystrokes. Designing interface-first, you want another person to be pressing keys. Can we get Simon to teach us a couple distinct patterns? (That's we teach it; (that means:); no words: that's faster.) Get a couple ring tones, customiz-ing-, and you play a game.) Multi-pad consolled the PC. Can we give keystrokes its own thread? Sadly, our first one: get spatial delay timing up to speed. The sturdy keys (the discretes) have whisper roger that. Watch moving target? over raise riggings. From gagsl-py2 at yahoo.com.ar Tue Mar 4 22:18:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 01:18:09 -0200 Subject: Run Python app at startup References: Message-ID: En Tue, 04 Mar 2008 16:36:03 -0200, SMALLp escribi?: >>> I create simple application. Yust an windows and "compile" it with >>> py2exe. I add registry value >>> reg add >>> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v >>> MyApp /t REG_SZ /d C:\myapp.exe /f' > Program works fine. When i run it it works. Problem is how to make this > aplication start at windows startup. It opens and it closes in my case. Redirect stdout and stderr to some log file so you can inspect it and see the error: cmd /c c:\path\myapp.exe >c:\path\output.log 2>&1 -- Gabriel Genellina From mark.manning at gmail.com Tue Mar 11 09:07:50 2008 From: mark.manning at gmail.com (Mark M Manning) Date: Tue, 11 Mar 2008 06:07:50 -0700 (PDT) Subject: Python Sockets Help References: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> Message-ID: <453eade0-bd48-49e0-bb8e-bad9f5f79478@n77g2000hse.googlegroups.com> That's embarrassingly simple! Thank you very much!! On Mar 11, 4:03 am, bock... at virgilio.it wrote: > On 10 Mar, 23:58, Mark M Manning wrote: > > > > > I need your expertise with a sockets question. > > > Let me preface this by saying I don't have much experience with > > sockets in general so this question may be simple. > > > I am playing with the mini dns server from a script I found online:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt > > > All I want to do is edit this script so that it records the IP > > address. I've seen other examples use the accept() object which > > returns the data and the IP address it is receiving the data from. I > > can't use that in this case but I'm wondering if someone could show me > > how. > > > Here is the socket part of the script: > > > if __name__ == '__main__': > > ip='192.168.1.1' > > print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip > > > udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > udps.bind(('',53)) > > > try: > > while 1: > > data, addr = udps.recvfrom(1024) > > p=DNSQuery(data) > > udps.sendto(p.respuesta(ip), addr) > > print 'Respuesta: %s -> %s' % (p.dominio, ip) > > except KeyboardInterrupt: > > print 'Finalizando' > > udps.close() > > > Thanks to everyone in advance! > > ~Mark > > You already have the address of the sender, is in the 'addr' variable, > as returned by udps.recvfrom. > Change the print statement in sometinmh like: > print 'Respuesta (%s): %s -> %s' % ( addr, p.dominio, ip) > and you will see the sender address in dotted notation printed inside > the (). > > Ciao > ------- > FB From steve at holdenweb.com Sun Mar 2 12:44:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 12:44:13 -0500 Subject: Question on importing and function defs In-Reply-To: <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> Message-ID: TC wrote: > On Mar 2, 11:37 am, Gary Herron wrote: >> TC wrote: >>> I have a problem. Here's a simplified version of what I'm doing: >>> I have functions a() and b() in a module called 'mod'. b() calls a(). >>> So now, I have this program: >>> from mod import * >>> def a(): >>> blahblah >>> b() >>> The problem being, b() is calling the a() that's in mod, not the new >>> a() that I want to replace it. (Both a()'s have identical function >>> headers, in case that matters.) How can I fix this? >>> Thanks for any help. >> Since b calls mod.a, you could replace mod.a with your new a. Like >> this: (Warning, this could be considered bad style because it will >> confuse anyone who examines the mod module in an attempt to understand >> you code.) >> >> import mod >> >> def replacement_a(): >> ... >> >> mod.a = replacement_a >> >> ... >> >> Or another option. Define b to take, as a parameter, the "a" function >> to call. >> >> In mod: >> >> def a(): >> ... >> >> def b(fn=a): # to set the default a to call >> ... >> >> And you main program: >> >> from mod import * >> >> def my_a(): >> ... >> >> b(my_a) >> >> Hope that helps >> >> Gary Herron > > Thanks for the tips, but no luck. This is for a homework assignment, > so there are a couple of requirements, namely that I can't touch > 'mod', and I have to do 'from mod import *' as opposed to 'import > mod'. > > So the first method you suggested won't work as written, since the mod > namespace doesn't exist. I tried a = replacement_a, but b() is still > calling mod's version of a() for some reason. And because I can't > touch mod, I can't use your second suggestion. > > In case I somehow oversimplified, here's the actual relevant code, in > 'mod' (actually called 'search'). The first fn is what I've been > calling a(), the second is b(). > > (lots of stuff...) > > def compare_searchers(problems, header, > searchers=[breadth_first_tree_search, > breadth_first_graph_search, > depth_first_graph_search, > iterative_deepening_search, > depth_limited_search, > astar_search]): > def do(searcher, problem): > p = InstrumentedProblem(problem) > searcher(p) > return p > table = [[name(s)] + [do(s, p) for p in problems] for s in > searchers] > print_table(table, header) > > def compare_graph_searchers(): > compare_searchers(problems=[GraphProblem('A', 'B', romania), > GraphProblem('O', 'N', romania), > GraphProblem('Q', 'WA', australia)], > header=['Searcher', 'Romania(A,B)', 'Romania(O, N)', > 'Australia']) > > > That's the end of the 'search' file. And here's my program, which > defines an identical compare_searchers() with an added print > statement. That statement isn't showing up. > > from search import * > > def compare_searchers(problems, header, > searchers=[breadth_first_tree_search, > breadth_first_graph_search, > depth_first_graph_search, > iterative_deepening_search, > depth_limited_search, > astar_search, best_first_graph_search]): > def do(searcher, problem): > p = InstrumentedProblem(problem) > searcher(p) > return p > table = [[name(s)] + [do(s, p) for p in problems] for s in > searchers] > print 'test' > print_table(table, header) > > compare_graph_searchers() Since you've admitted it's for homework, here are a couple of hints. 1. The b() function is *always* going to try and resolve its references in the namespace it was defined in; 2. The technique you need is most likely known as "monkey patching". When you say "I can't touch mod", that may mean "the source of mod must remain unchanged", which is subtly different. Google is your friend ... Good luck with your assignment. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From _karlo_ at mosor.net Sun Mar 9 13:07:46 2008 From: _karlo_ at mosor.net (Karlo Lozovina) Date: Sun, 09 Mar 2008 18:07:46 +0100 Subject: Returning values from function to Python shell/IPython References: Message-ID: Jorge Vargas wrote: > well after all it's a function so the only ways you can get things out > of it are: > - return a dict with all the objects > - use global (very messy) > - use a decorator to do either of the above. Messy, all of those... :(. > on the other hand have you consider using a proper test package? > instead of inspecting the objects manually from the shell you could > make it all automatic. with assert statements. you could use the std. > python testing modules http://docs.python.org/lib/development.html or > something less verbosed like nose Usually, I'm using standard Python testing modules, but sometimes that is just an overkill. Sometimes I like to do 'exploratory programming', especially in the early phases of development - create a bunch of objects I want to play with and do that from IPython. Only way I found out to somewhat automate this procedure is to have a function that creates all of the test objects, and then raises an exception at the end. IPython starts ipdb, so I can work with the objects the function created (without copying them back to the shell). But this somehow looks too hack-ish for me, so I was wondering if there was an alternative... Anyway, thanks for your answer ;). -- Karlo Lozovina -- Mosor From felciano at gmail.com Mon Mar 24 02:30:11 2008 From: felciano at gmail.com (felciano) Date: Sun, 23 Mar 2008 23:30:11 -0700 (PDT) Subject: Multiline CSV export to Excel produces unrecognized characters? Message-ID: <4f6f122f-45bb-4aa5-b9c9-5eb3e84a0964@i7g2000prf.googlegroups.com> Hi -- Is there a standard way to use the csv module to export data that contains multi-line values to Excel? I can get it mostly working, but Excel seems to have difficulty displaying the generated multi-line cells. The following reproduces the problem in python 2.5: import csv row = [1,"hello","this is\na multiline\ntext field"] writer = csv.writer(open("test.tsv", "w"), dialect="excel-tab", quotechar='"') writer.writerow(row) When opening the resulting test.tsv file, I do indeed see a cell with a multi-line value, but there is a small boxed question mark at the end of each of the lines, as if Excel didn't recognize the linebreak. Any idea why these are there or how to get rid of them? Ramon From Dodin.Roman at gmail.com Tue Mar 18 03:00:41 2008 From: Dodin.Roman at gmail.com (hellt) Date: Tue, 18 Mar 2008 00:00:41 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> Message-ID: <61a3fe08-268e-464e-9ce5-cc00d7a2e3e2@f63g2000hsf.googlegroups.com> On 18 ???, 03:57, sturlamolden wrote: > On 17 Mar, 04:54, WaterWalk wrote: > > > So I'm curious how to read code effectively. I agree that python code > > is clear, but when it becomes long, reading it can still be a hard > > work. > > First, I recommend that you write readable code! Don't use Python as > if you're entering the obfuscated C contest. > > Two particularly important points: > > * If you find yourself thinking this module is too long, that's > probably what it is. Half a page of code per module is fine. Two pages > of code per module can be too much. > > * Comments are always helpful to the reader. > > Second, I recommend getting a good IDE. E.g. pick one of: > > * Microsoft Visual Studio (commercial) > * Eclipse with PyDev and CDT (free) > * SPE (free) > * ActiveState Komodo IDE (commercial) under Microsoft Visual Studio do you mean IronPython instance? From stefan_ml at behnel.de Wed Mar 12 12:58:44 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 12 Mar 2008 17:58:44 +0100 Subject: Python - CGI - XML - XSD In-Reply-To: References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> Message-ID: <47D80BC4.2010307@behnel.de> xkenneth wrote: > On Mar 12, 6:32 am, "Diez B. Roggisch" wrote: >> xkenneth wrote: >>> Hi All, >>> Quick question. I've got an XML schema file (XSD) that I've >>> written, that works fine when my data is present as an XML file. >>> (Served out by apache2.) Now when I call python as a cgi script, and >>> tell it print out all of the same XML, also served up by apache2, the >>> XSD is not applied. Does this have to do with which content type i >>> defined when printing the xml to stdout? >> Who's applying the stylesheet? The browser, some application like XmlSpy or >> what? > > The browser. Well, why should it validate your file? Browsers don't do that just for fun. Stefan From jim at maplesong.com Tue Mar 11 14:00:47 2008 From: jim at maplesong.com (Jim Carroll) Date: Tue, 11 Mar 2008 18:00:47 +0000 (UTC) Subject: Time Zone application after strptime? References: <47D1B703.6040200@egenix.com> Message-ID: M.-A. Lemburg egenix.com> writes: > > On 2008-03-07 22:24, Jim Carroll wrote: > > It's taken me a couple of hours to give up on strptime > > with %Z for recognizing > > time zones... but that still leaves me in the wrong zone: > > > > How can I use the "PST" (or any other time zone name) > > to adjust dt by the > > correct number of hours to get it into UTC before storing in MySQL? > > You could try mxDateTime's parser. It will convert most timezones > into UTC for you: > > >>> from mx.DateTime import * > >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008') > 00' at 2afdc7078f50> > Unfortunately, mx.DateTime also ignores the time zone. If I parse the PST time, and ask for the result's time zone it gives me my local time zone. I have had some luck with dateutil: >>> import dateutil.parse as p >>> p.parse("10:29:52 Feb 29, 2008 PST") datetime.datetime(2008, 2, 29, 10, 29, 52) and if I hand it a list of time zones, it does the right thing >>> zones = {"PST": -8*60*60} p.parse("10:29:52 Feb 29, 2008 PST", tzinfos=zones) datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800)) But I cannot figure out how to get dateutil to use the zoneinfo file that it includes in its own package. It has a zoneinfo-2007k.tar.gz right in the package, and a class to parse the binary zoneinfo, but no clear way to get it to parse its own file and use those during the parsing. From john.jython at gmail.com Tue Mar 25 07:04:37 2008 From: john.jython at gmail.com (john s.) Date: Tue, 25 Mar 2008 04:04:37 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: <5740c4b9-d983-466b-a8b2-5d888f50cb8a@m3g2000hsc.googlegroups.com> On Mar 25, 6:34 am, Bryan Olson wrote: > john s. wrote: > > #/usr/bin/enviro python > > > #Purpose - a dropped in useracct/pass file is on a new server to build > > #a cluster... Alas there are no home directories.. Let me rip through > > #the passfile, grab the correct field (or build it) and use it to make > > #the directory! > > > import os, sys, string, copy, getopt, linecache > > from traceback import format_exception > > > #The file we read in... > > fileHandle = "/etc/passwd" > > srcFile = open(fileHandle,'r') > > srcList = srcFile.readlines() > > > #yah, a for loop that "iterates" through the file of "lines" > > for i in srcList: > > Convention is that the name i is for an integer. just a bit of silly walk on my part in the comment field... > > > strUsr = string.split(i,":") > > theUsr = strUsr[0] > > usrHome = "/expirt/home/",theUsr,"/" > > usrHome = ''.join(usrHome) > > As Ryan noted, os.path is the favored way. > > > print "printing usrHome:",usrHome > > print "is it a dir?: ", os.path.isdir(usrHome) > > #try to test if it's a dir... for some reason this mis-behaves... > > #maybe I'm not thinking about it correctly.. > > > if os.path.isdir(usrHome) != 'False': > > That should always evaluate true. False != 'False'. I think you want: ok... yes I do > > if not os.path.exists(usrHome): > > print "User Home dir doesn't exist creating." > > try: > > os.makedirs(usrHome) > > os.system('/usr/bin/chmod 750 ' + usrHome) > > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) > > except Exception, e: > > print e > > I don't think you want to catch the exception there. If creating the dir > fails, the next bits of code should not execute. ok. I see that now. > > > #OMG, there is directory that happens to already exist! well, > > #love for the queen dictates we provide "due > > #dilligence", (e.g. wipe our asses properly) > > The path could exist but not be a directory. So isadir is slightly better then exists? It felt like it was not working right... (probably because I was double testing the exp I see now) > > > else: > > print "User Home dir exist, checking and fixing permissions." > > sys.exit("Thanks for using pyDirFixr...") > > Given the Unixy nature of your code, you probably want to sys.exit(0) > for success and 1 or 2 for failure. got it. I'm guessing I'm better off with a last line print "g'bye" then sys.exit versus trying both at once... > > Happy hacking, > -- > --Bryan Thanks Bryan :) -John From jkugler at bigfoot.com Wed Mar 26 17:02:04 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 26 Mar 2008 13:02:04 -0800 Subject: Not understanding lamdas and scoping Message-ID: I am trying to use lamdba to generate some functions, and it is not working the way I'd expect. The code is below, followed by the results I'm getting. More comments below that. patterns = ( ('[sxz]$', '$','es'), ('[^aeioudgkprt]h$', '$', 'es'), ('[^aeiou]y$', 'y$', 'ies'), ('$', '$', 's'), ) def z(*a): print a def make_pattern(pattern, search, replace): def compare(word): z(pattern, search, replace) return compare rules = [make_pattern(pattern, search, replace) for (pattern, search, replace) in patterns] print 'make pattern' for rule in rules: rule('noun') rules = [lambda word: z(pattern, search, replace) for (pattern, search, replace) in patterns] print 'lambda/list comprehension' for rule in rules: rule('noun') rules = [] for pattern, search, replace in patterns: rules.append(lambda word: z(pattern, search, replace)) print 'lamda/for loop' for rule in rules: rule('noun') Ouptut: make pattern ('[sxz]$', '$', 'es') ('[^aeioudgkprt]h$', '$', 'es') ('[^aeiou]y$', 'y$', 'ies') ('$', '$', 's') lambda/list comprehension ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') lamda/for loop ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') ('$', '$', 's') Of course, in my real code, I'm not calling z(), but a couple of RE search/replace functions (yes, I'm working on the Dive Into Python pluralizer). The first result is obviously the correct one. But the next two don't make sense. Why do all the functions returned by lamda have the last input values? What am I missing? OK, I figured out if I did this: def make_pattern(pattern, search, replace): return lambda word: z(pattern, search, replace) it would give correct results. So, is there some scoping issue with lambda that I'm not seeing? Thanks! j From jeff at schwabcenter.com Tue Mar 18 12:29:00 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 09:29:00 -0700 Subject: Interesting math problem In-Reply-To: References: Message-ID: Marc Christiansen wrote: > sturlamolden wrote: >> On 18 Mar, 00:58, Jeff Schwab wrote: >> >>> def make_slope(distance, parts): >>> if parts == 0: >>> return [] >>> >>> q, r = divmod(distance, parts) >>> >>> if r and parts % r: >>> q += 1 >>> >>> return [q] + make_slope(distance - q, parts - 1) >> Beautiful. If Python could optimize tail recursion, it would even run >> fast. > > This was my first thought, too. But tailcall optimisation wouldn't help > here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets > executed after the recursion. def make_slope(distance, parts, L=()): if parts == 0: return L q, r = divmod(distance, parts) if r and parts % r: q += 1 return make_slope(distance - q, parts - 1, (q,) + L) From pavlovevidence at gmail.com Mon Mar 10 11:25:16 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 10 Mar 2008 08:25:16 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: On Mar 10, 10:39 am, Gary Herron wrote: > Metal Zong wrote: > > > The operator is and is not test for object identity: x is y is true if > > and only if x and y are the same objects. > > > >>> x = 1 > > > >>> y = 1 > > > >>> x is y > > > True > > > Is this right? Why? Thanks. > > Yes that is true, but it's an implementation defined optimization and > could be applied to *any* immutable type. For larger ints, such a thing > is not true. > >>> x=1000 > >>> y=1000 > >>> x is y > False > > If either is a surprise, then understand that the "is" operator should > probably *never* be used with immutable types. Not quite: None is immutable but it's usually recommended to test for it using is. Carl Banks From steve at holdenweb.com Tue Mar 4 11:09:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 11:09:54 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD7452.2020605@holdenweb.com> mmm wrote: > Oops I did make a mistake. The code I wanted to test should have been > > import copy > print 'Test 1' > pf= '?,?,?,?' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print sqlx1 > > print > print 'Test 2' > sqlx2= copy.copy(sqlx1) > sqlx3= sqlx1 > pf= '?,?,?, ****' > print 'sqlx1= ', sqlx1 > print 'sqlx2= ', sqlx2 > print 'sqlx3= ', sqlx2 > > and the results would > == output > Test group 1 > INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Test group 2 > sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Such that sqlx1 does to change with the re-assignment of 'pf' > And of course immutables such as strings are immutable. Got it now. You still aren't showing us the code you are actually running. Why can't you just paste it into your message? But anyway, you appear to have got the drift now. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From vpalexander at gmail.com Sun Mar 9 06:03:34 2008 From: vpalexander at gmail.com (Vince) Date: Sun, 9 Mar 2008 03:03:34 -0700 (PDT) Subject: Help xxx.py Program Recognition problem References: <224ea046-65c4-40b5-8bd5-ede1c87c801e@e6g2000prf.googlegroups.com> Message-ID: On Mar 8, 9:48 am, crashbangb... at gmail.com wrote: > Hi... > > I was using Python 2.4 and installed 2.5...I copied all my .py files > from the Python24\ root directory to the Python25\ root > directory...when I try to run them by double clicking I get: > "XXXXX.py is not a valid Win32 application"... > > Also, the files do not appear to be associated with python...? > > I can run them from IDLE...but that is it... > > How do I fix this...? > > Thanks.. > > Dave It sounds like you just want the dbl-click Explorer association ... that it should establish by default ... you can use Explorer -> Tools - > Folder Options -> File Types to indicate that you want Idle to launch .py files. Also, probably a silly question, but did you verify the download was the right Win OS version? From thynnus at gNOTmail.com Tue Mar 4 15:29:13 2008 From: thynnus at gNOTmail.com (Thynnus) Date: Tue, 04 Mar 2008 20:29:13 GMT Subject: 'normal' shell with curses In-Reply-To: <635drhF25qgqtU1@mid.uni-berlin.de> References: <633s5lF24prinU1@mid.uni-berlin.de> <635drhF25qgqtU1@mid.uni-berlin.de> Message-ID: On 3/4/2008 12:05 PM, Michael Goerz wrote: > Thynnus wrote, on 03/04/2008 08:48 AM: >> On 3/3/2008 9:57 PM, Michael Goerz wrote: >>> Hi, >>> >>> I'm trying to print out text in color. As far as I know, curses is the >>> only way to do that (or not?). So, what I ultimately want is a curses >>> terminal that behaves as closely as possible as a normal terminal, >>> i.e. it breaks lines and scrolls automatically, so that I can >>> implement a function myprint(color, text) that does what print() does, >>> only in color. >> >> You might find the below helpful. Let us know how you make out? >> >> -------- >> >> Python Cookbook >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 >> >> Title: >> Using terminfo for portable color output & cursor control >> >> Description: >> The curses module defines several functions (based on terminfo) that can >> be used to perform lightweight cursor control & output formatting >> (color, bold, etc). These can be used without invoking curses mode >> (curses.initwin) or using any of the more heavy-weight curses >> functionality. This recipe defines a TerminalController class, which can >> make portable output formatting very simple. Formatting modes that are >> not supported by the terminal are simply omitted. >> >> -------- >> > > That looks *extremely* interesting. From a very brief test, it seems to > do exactly what I want! > > Now, Windows seems very problematic for color output. I was using the > following as a test, based on the above recipe: > > term = TerminalController() > while True: > print term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled' > print term.render('${RED}Error:${NORMAL}'), 'paper is ripped' > > On Linux, it works fine, on Windows, it just prints white on black > (which is of course what it should do if the terminal doesn't support > color). Can anyone get the Windows cmd.exe terminal to do color? I > already tried to add device=%SystemRoot%\system32\ansi.sys to config.nt, > but that doesn't seem to do anything (neither in what I tried yesterday > with the ANSI escape codes, nor with the recipe code now). I also very > briefly tried running it on the winbash shell > (http://win-bash.sourceforge.net/), it didn't have any color either... > So, any way to get color in Windows? > > Michael ipython - http://ipython.scipy.org/ - does a colored Windows interpreter, clue there. From gagsl-py2 at yahoo.com.ar Mon Mar 10 00:49:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 21:49:06 -0700 (PDT) Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: <3ebaa96f-7c93-4aa8-a7d2-13764140831f@k13g2000hse.googlegroups.com> On 10 mar, 01:26, DanielJohnson wrote: > Hi, > > I am trying to solve a genetic algorithm problem where I want to read > a bitvector of very large size (say 10000) and manipulate bits based > on certain algorithms. > > I am a newbie in Python. What data structure are good to read such > huge data set. Are there any built in classes for bit fiddling. > > Every help is greatly appreciated, > > Thanks From tmp1 at viltersten.com Sun Mar 9 14:45:58 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 19:45:58 +0100 Subject: SV: Changing the size of a Button In-Reply-To: References: <63ifhtF277va7U1@mid.individual.net> Message-ID: <63iokhF284p4hU1@mid.individual.net> >> How do i change the size of a Button >> (using Tkinter), other than to set it >> during construction? > In Tkinter, usually the geometry managers > (such as pack) are the ones who size the > widgets. If you run something like: > import Tkinter as tk > > root = tk.Tk() > def change_size(): > b["text"] = "More text" > > b = tk.Button(root, text="Text", command=change_size) > b.pack() > > root.mainloop() Thanks for the answer. Unfortunately, that won't help me at all, since i, apparently, asked the wrong question. Let me refrain myself. What i wish to do is to affect the size of the button but not due to change of text but due to resize of the frame it resides in. This far i've managed to get a callback to a function as the resize occurs and to print the sizes. However, i'd like to assign these values to the button so it always stays the same width as the frame. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From rockxuan at gmail.com Tue Mar 18 03:40:07 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:40:07 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <7fac29d4-753d-481d-b23f-c06c75ebd889@c19g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From tmp1 at viltersten.com Sat Mar 1 15:05:41 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 21:05:41 +0100 Subject: Surprised by the command "del" Message-ID: <62tq9sF24juhrU1@mid.individual.net> I'm reading the docs and at 5.2 the del statement is discussed. At first, i thought i've found a typo but as i tried that myself, it turns it actually does work so. a = ["alpha", "beta", "gamma"] del a[2:2] a Now, i expected the result to be that the "beta" element has been removed. Obviously, Python thinks otherwise. Why?! Elaboration: I wonder why such an unintuitive effect has been implemented. I'm sure it's for a very good reason not clear to me due to my ignorance. Alternatively - my expectations are not so intuitive as i think. :) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From aahz at pythoncraft.com Fri Mar 21 12:49:41 2008 From: aahz at pythoncraft.com (Aahz) Date: 21 Mar 2008 09:49:41 -0700 Subject: Improving datetime References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: In article , Nicholas F. Fabry wrote: > >Please clarify how long a novel is? The problem with the modules are >not bugs, they are problems with real world use scenarios that result >in inescabably ugly code without improvements to the module - so the >explanations involve code samples and use cases... so they may be >'long'. Could you suggest a maximum number of (70 char) lines, or an >example of an overly long proposal? I'd suggest starting with a simple example of a problem you see. You may well be up against a design constraint: the datetime module is intended to provide *simple* and reasonably robust handling. There doesn't seem to be a PEP, unfortunately, but you might want to look for the discussion history leading to the including of datetime. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From dickinsm at gmail.com Tue Mar 4 09:39:42 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Mar 2008 06:39:42 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: On Mar 4, 8:46?am, NickC wrote: > The increased number of inaccurate answers with Decimal (31% vs 10%) > is probably due to the fact that it is actually more precise than > float I suspect it has more to do with the fact that 10 is bigger than 2, though I'm not sure I could precisely articulate the reasons why this matters. (A bigger base means a bigger 'wobble', the wobble being the variation in the relationship between an error of 1ulp and a relative error of base**-precision.) Rerunning your example after a getcontext().prec = 16 (i.e. with precision comparable to that of float) gives >>> check_accuracy(Decimal) 310176 Mark From R.Brodie at rl.ac.uk Thu Mar 20 12:45:45 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 20 Mar 2008 16:45:45 -0000 Subject: Problem with PARAGRAPH SEPARATOR References: Message-ID: wrote in message news:mailman.2195.1206027668.9267.python-list at python.org... > Would that mean that the string "myString" is an ascii-string or what? It would mean it was a byte encoded string already, yes. When you try to encode it, Python tries to coerce it to Unicode and it's equivalent to: myString.decode('ascii').encode('iso-8859-1','ignore') That wouldn't explain why printing it gave errors though. From deets at nospam.web.de Thu Mar 20 12:32:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Mar 2008 17:32:01 +0100 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> <13u52hqlbtdv1d1@corp.supernews.com> Message-ID: <64fhscF2bei52U1@mid.uni-berlin.de> Grant Edwards wrote: > On 2008-03-20, Jeff Schwab wrote: > >>>> http://www.google.com/search?q=emacs+python >> >>> Gee. Thanks. >> >> I believe Grant was suggesting that Emacs often serves a similar purpose >> on Unix to what Visual Studio does on Windows, which seemed to be what >> you were asking. When asking about Mac OS X here, you are likely to get >> a lot of generic Unix responses. (Would it have been clearer if he had >> just said "emacs?") > > Don't the normal "run/debug python from inside emacs" methods > work on OS-X? Of course they do. Diez From rcdailey at gmail.com Thu Mar 6 16:15:17 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 6 Mar 2008 15:15:17 -0600 Subject: system32 directory In-Reply-To: <47CFAE7E.6030501@timgolden.me.uk> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> Message-ID: <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden wrote: > > > First thing to do when asking "How do I do X in Python under Windows?" > is to stick -- python X -- into Google and you get, eg: > > > http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html > > which suggests that the win32api module from the pywin32 modules has > the function you need. > > > And sure enough... > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import win32api > >>> win32api.GetSystemDirectory () > 'C:\\WINDOWS\\system32' > >>> > > > TJG > I was aiming to figure out if the standard modules shipped with Python could do this already before I started using 3rd party libraries. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Dodin.Roman at gmail.com Thu Mar 20 07:31:41 2008 From: Dodin.Roman at gmail.com (hellt) Date: Thu, 20 Mar 2008 04:31:41 -0700 (PDT) Subject: Strange behavior of the Eclipse embedded console Message-ID: <23ab07a7-0355-48a7-8bf2-266a56f4efb9@h11g2000prf.googlegroups.com> i've faced with some strangeness while executing this sample: choice = raw_input("your choice: ") print len(choice) when i run this sample in my eclipse console with CPython and print Yes, i have this output 4 #trailing \t is the fourth element but when i use command line method python sample.py i have the correct length = 3 i'm curious now, can anyone explain that? From gagsl-py2 at yahoo.com.ar Fri Mar 21 17:51:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 14:51:49 -0700 (PDT) Subject: How can I make a function equal to 0? References: Message-ID: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> On 21 mar, 17:43, Martin Manns wrote: > Basically I have a lot of functions inside a numpy array, > of which most return "" and actually are derived as follows: > > from numpy import * > > grid_size = 1000000 > > class F(object): > def __cmp__(self, other): return 0 > def __call__(self, dummy): return "" > f = F() > myarray = array([f] * grid_size, dtype="O") > > # I re-define an element in the array > > myarray[34424] = lambda x: "23" > > # Now, I would like to loop over all re-defined elements: > > for i in itertools.izip(*nonzero(myarray)): > print myarray[i]() > > If I fill the array with 0 instead of the functions that > return "" this works really fast. > > However, I would like to be able call the content of each > cell in the array as a function. If you drop this condition then you could fill the array with zeroes as before, replace only the interesting ones with actual functions, and write: for item in myarray[nonzero(myarray)]: print item() if callable(item) else item > As I said, the callable object approach works but is > about as slow as iterating through the whole array. > Perhaps I should add a __call__ function to the built-in > 0? But I doubt that this helps. You can't - anyway, being Python code, would not help with the speed. -- Gabriel Genellina From bluszcz at jabberpl.org Sat Mar 1 04:51:48 2008 From: bluszcz at jabberpl.org (=?UTF-8?B?UmFmYcWC?= Zawadzki) Date: Sat, 01 Mar 2008 10:51:48 +0100 Subject: RuPy 2008 Message-ID: Hello. We invite you to take part in RuPy 2008 - Python & Ruby Conference, which will take place on 12th, 13th April 2008 at Adam Mickiewicz University in Poznan, Poland. This international event is organised for the second time. The conference is devoted to Ruby and Python programming languages. RuPy is the only event of this type organised in Central Europe. It is a great opportunity to broaden your knowledge, discuss new trends with world class specialists and establish priceless international contacts. You may find more details on the conference website: http://rupy.eu/ See you at RuPy 2008, -- bluszcz http://web-dev.pl - Dynamiczny ?wiat internetowych aplikacji od ?rodka From duncan.booth at invalid.invalid Tue Mar 18 17:27:50 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2008 21:27:50 GMT Subject: os.path.getsize() on Windows References: Message-ID: Sean DiZazzo wrote: > On windows, this returns the size of the file as it _will be_, not the > size that it currently is. Is this a feature? What is the proper way > to get the current size of the file? I noticed > win32File.GetFileSize() Does that behave the way I expect? > > PS. I also tried os.stat()[6] > I think all of those will return the current size of the file, but that may be the same as the final size: just because the data hasn't been copied doesn't mean the file space hasn't been allocated. You don't say how you are copying the file, but I seem to remember that Windows copy command pre- allocates the file at its final size (so as to reduce fragmentation) and then just copies the data after that. If you need to make sure you don't access a file until the copy has finished then get hwatever is doing the copy to copy it to a temporary filename in the same folder and rename it when complete. Then you just have to check for existence of the target file. From kyosohma at gmail.com Sun Mar 9 21:50:54 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 9 Mar 2008 18:50:54 -0700 (PDT) Subject: Uninstalling Eggs References: Message-ID: <6dcd18c2-a900-4938-9e71-681ea1086cf0@n58g2000hsf.googlegroups.com> On Mar 9, 8:30 am, PB wrote: > I just installed the Shove module with the monumentally crap > setuptools. Whilst the install succeeded, imports now trigger errors, > so clearly it did not install correctly. Can I simply delete the .egg > file from my lib/python2.3/site-packages/ directory? > > Cheers, Deleting the shove-egg folder is definitely the recommended and easiest way I know of to "uninstall" an egg. I've used it successfully before. Mike From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 22:03:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 02:03:54 -0000 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> <47ed882d$0$26468$afc38c87@news.optusnet.com.au> <7x63v6tm9z.fsf@ruckus.brouhaha.com> Message-ID: <13ur8sa1p76i3ef@corp.supernews.com> On Fri, 28 Mar 2008 17:19:04 -0700, Paul Rubin wrote: > Richard Jones writes: >> Check out tinypy: >> http://www.philhassey.com/blog/category/tinypy/ > > I don't really understand the point of it. http://www.philhassey.com/blog/tinypy-ideas/ [quote] Sandbox tinypy Objective: to secure tinypy so that it can be run safely run any arbitrary python code Remove dangerous functions Enable a memory limit Enable an execution time limit Discover security related bugs and fix them -- Steven From sjmachin at lexicon.net Wed Mar 19 17:51:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 14:51:15 -0700 (PDT) Subject: Is this valid ? References: Message-ID: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> On Mar 20, 8:18 am, Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > Of course. You can chain comparisons as much as you like and is (semi-)sensible, e.g. assert 0 < thing_index < thing_count <= UTTER_MAX_NTHINGS There was an interesting use of chained comparison within the last day or 2 in a thread about deriving a set of duplicated list elements -- look for subject == "finding items that occur more than once in a list" and author == "Arnaud Delobelle". Cheers, John From justjpm at aol.com Wed Mar 19 17:45:39 2008 From: justjpm at aol.com (Jim) Date: Wed, 19 Mar 2008 14:45:39 -0700 (PDT) Subject: URLError Message-ID: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> Program randomly aborts when looking up url. The program loop thru 4000+ records looking up ID via internet and returns html code which is used in subsequent processing. The code for looking-up record is below followed by abort details. Can anyone help with catching the abort before program aborts or provide code to automatically start program? Currently, if program is restarted the process starts after last good record but must be restarted manually. Thanks Jim code start here ================ #start lookups pass while lines < 5000: lines += 1 d = ifile.read(8) print str(lines) + ' ' + d z = ifile.read(1) f2 = b + d h4 = h1+f2+h3 #file name for saving HMTL file html_file = open(h4, 'w') url = a + d + c + b #build url to lookup record in database contents = urllib2.urlopen(url).read() #lookup account in database soup = BeautifulSoup(contents) html_file.write(soup.prettify()) #write HTML file targetPage = soup.prettify() targetHTML = targetPage #set-up record for edit pass html_file.close() #close HTML file abort details ============================== 429 90078431(note:this record 429 is where abort happen-when program restarted this record processed normally) Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "Lookup Records.py", line 77, in contents = urllib2.urlopen(url).read() 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) URLError: From steve at REMOVE-THIS-cybersource.com.au Mon Mar 17 09:22:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 17 Mar 2008 13:22:48 -0000 Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <13tss585qqrhlc0@corp.supernews.com> On Mon, 17 Mar 2008 05:28:19 -0700, castironpi wrote: > a tuple is a data > structure such which cannot contain a refrence to itself. >>> a = [] # a list >>> b = (a, None) # a tuple >>> a.append(b) >>> print b ([([...], None)], None) >>> b[0][0] is b True So, yes tuples can contain a reference to themselves, but only indirectly. > Can a single expression refer to itself ever? You can't refer to an object until it exists, so no. -- Steven From cwitts at gmail.com Tue Mar 4 03:27:32 2008 From: cwitts at gmail.com (Chris) Date: Tue, 4 Mar 2008 00:27:32 -0800 (PST) Subject: Command line arguments in Windows References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: On Mar 4, 8:38 am, "Mike Walker" wrote: > > If you run a python file, ie. just double clicking it the only > > argument you will have will be the filename of the script. If you > > create a shortcut to the script and in the target box add your > > arguments (if you have quotation marks place them after not inside) > > you will see your arguments. fwiw you answered yourself in the third > > paragraph. > > As I mentioned I am working from the command line, not clicking on the icon. > The only difference between it working and not is the python prefix, which > is why I was thinking this is some sort of file association problem. > > I probably wasn't as clear as I could have been in the third paragraph. > > argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] > python argtest.py arg1 arg2 arg3 - Works That seems rather wierd, just running argtest.py arg1 arg2 arg3 I get the correct output, Python 2.5.1 from python.org but running on XP though. Potentially an issue with Vista... ? From stevegill7 at gmail.com Fri Mar 28 07:32:46 2008 From: stevegill7 at gmail.com (Jetus) Date: Fri, 28 Mar 2008 04:32:46 -0700 (PDT) Subject: ************************************************************** References: <151380e3-5e2c-4bd0-bca0-bcbb555cffac@d4g2000prg.googlegroups.com> Message-ID: <35da75eb-0583-413c-a98d-5313871d82e9@s8g2000prg.googlegroups.com> On Mar 28, 5:44 am, sivakumar... at gmail.com wrote: > ************************************************************** > When you make a Web page available offline, you > can read its content when your computer is not > connected to the Internet. For example, you can > view Web pages on your laptop computer when you > don't have a network or Internet connection. Or > you can read Web pages at home without tying up > a phone line. > > You can specify how much content you want available, > such as just a page, or a page and all its links, and > choose how you want to update that content on your computer. > > If you just want to view a Web page offline, and you don't > need to update the content, you can save the page on your > computer. There are several ways you can save the Web page, > from just saving the text to saving all of the images and > text needed to display that page as it appears on the Web. > *************************************************************** > http:\\my profile6529.blogspot.com Can't bring up your link.. http:\\my profile6529.blogspot.com From castironpi at gmail.com Sat Mar 29 18:57:13 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 15:57:13 -0700 (PDT) Subject: pygame handoff References: Message-ID: On Mar 28, 5:09?am, castiro... at gmail.com wrote: > Can anyone do a simple pygame render of a rollercoaster in first- > person? ?I'll do the generator. ?Just for fun for free. ?(Ha see > pythaaaaaagh. ?He bothered to carve it. ?Have a nice day.) Does anyone want to team up on this: http://www.pygame.org/gamelets/games/pycastersrc.zip From sturlamolden at yahoo.no Thu Mar 20 10:18:05 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 07:18:05 -0700 (PDT) Subject: Deleting Microsoft access database References: Message-ID: On 20 Mar, 15:11, "Ahmed, Shakir" wrote: > I have a Microsoft Access database that I want to delete whether anyone > is using that file. > > The database is already read only mode residing in a server, users are > opening in read only mode. I want to delete that file, I remove read > only check but could not delete that file. > > Getting error message: > Cannot delete xxx : It is being used by another person or program. > > Any help is highly appreciated. You cannot delete a file someone has open, in read-only mode or not. Disconnect the computer from the network. If that does not help, reboot the computer. From goon12 at gmail.com Tue Mar 11 10:40:36 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 11 Mar 2008 10:40:36 -0400 Subject: How to factor using Python? In-Reply-To: <6a2ccd190803110738l2ba7d0c0ne4d61b74e6a5d9c8@mail.gmail.com> References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <6a2ccd190803110738l2ba7d0c0ne4d61b74e6a5d9c8@mail.gmail.com> Message-ID: <6a2ccd190803110740q6acbbdf2n9cb562cd63ad3f94@mail.gmail.com> On Tue, Mar 11, 2008 at 10:38 AM, Joe Riopel wrote: > On Mon, Mar 10, 2008 at 1:08 AM, Nathan Pinno wrote: > > How do I factor a number? I mean how do I translate x! into proper > > Python code, so that it will always do the correct math? > > This should work to do x! (factorial of x). > > reduce(lambda x,y: x*y, range(1, x+1)) Sorry, the variable naming was confusing in that code. >>> def dofact(x): ... return reduce(lambda a,b: a*b, range(1,x+1)) ... >>> dofact(5) 120 >>> From vokinloksar at yahoo.se Sun Mar 30 15:46:00 2008 From: vokinloksar at yahoo.se (vokinloksar at yahoo.se) Date: Sun, 30 Mar 2008 12:46:00 -0700 (PDT) Subject: socket error when loading the shell? Message-ID: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> hi using python and wpython. when using run module or python shell on the run menu in the GUI i get "socket error, connection refused". it worked before, what si wrong now? and i cant find where to start the shell directly. think i had an exe before but cant seem to find it now. From mnordhoff at mattnordhoff.com Mon Mar 10 04:19:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 08:19:05 +0000 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <47D4EEF9.7010403@mattnordhoff.com> Stefan Behnel wrote: > And if you really need the efficiency of "well-tuned raw C", it's one function > call away in your Cython code. What do you mean by that? I know nothing about how Cython compares to C in performance, so I said "well-tuned" because it must be possible to write C that is faster than Cython, though it may take some effort. -- From zubeido at yahoo.com.br Sat Mar 29 16:21:23 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 29 Mar 2008 13:21:23 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> Message-ID: On Mar 29, 6:41 pm, Gerhard H?ring wrote: > Ok, I'll review your code. > > aiwarrior wrote: > > class db: > > def __init__(self): #constructor > > conn = sqlite3.connect('./db.db') > > conn.isolation_level = None > > Autocommit mode is mostly for newbies who forget to call commit. > Unfortunately, newbiews find enough other ways to shoot themselves in > the foot. So, in retrospect, maybe I should not have added that feature > to pysqlite ;-) > > > self.cursor = conn.cursor() > > try: > > self.cursor.execute("CREATE TABLE database > > (album,filepath)" ) > > except: > > pass > > try: except: pass without catching *specific* exceptions is generally a > very bad idea. If you're doing something stupid, or another error > happens than the one you want to ignore, you will never know this way. > > > def add_entry( self, eone , etwo ): #Add entry to database > > self.cursor.execute( "INSERT INTO database (album,filepath) > > VALUES (?,?)", ( eone , etwo ) ) > > return 1 #TODO: exception handler > > > def get_mediadb( self, print_db = False ): > > self.cursor.execute( 'SELECT * FROM database' ) > > if (print_db == True): > > print self.cursor.fetchall() > > The if clause can be written as just "if print_db:". > > > def get_value( self, column ): > > self.cursor.execute( "SELECT %s FROM database" % column ) > > for n in self.cursor: > > print n > > > def destructor(self): > > self.cursor.close() > > Just FYI, Python's "destructor" method is called "__del__", not > "destructor". > > > > > def walking_and_filling(db): > > pass > > > if __name__ == "__main__": > > db = db() > > #walking_and_filling( db ) > > for root, dirs, files in os.walk( '''foo_path/''', > > topdown=False ): > > for name in files: > > joined = os.path.join(root, name) > > if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): > > try: > > audio = MP3 (joined, ID3=EasyID3 ) > > print (audio['album']) > > db.add_entry( joined, audio['album'] ) > > except: > > pass > > Now, this try: except: pass is most probably hiding the real error That > leads to the insert failing. Because you just ignored any errors, you > will never now what exactly went wrong here. > > > db.get_mediadb( print_db=True ) > > > When i execute this the database doesn't get filled with anything and > > the program stays running in memory for ever. [...] > > HTH, > > -- Gerhard I'm sorry about not saying showing the libraries. It was not on purpose. import os import sqlite3 from mutagen.easyid3 import EasyID3 from mutagen.mp3 import MP3 ##def tree(path): ## node = () ## for node in os.listdir( path ): ## if( os.path.isdir( path + node )): ## tree(path+node) ## return path class db: def __init__(self): #constructor conn = sqlite3.connect( './db.db' ) conn.isolation_level = None self.cursor = conn.cursor() try: self.cursor.execute( "CREATE TABLE database (album,filepath)" ) except: pass def add_entry( self, eone , etwo ): #Add entry to database self.cursor.execute( "INSERT INTO database (album,filepath) VALUES (?,?)", ( eone , etwo ) ) return 1 #TODO: exception handler def get_mediadb( self, print_db = False ): self.cursor.execute( 'SELECT * FROM database' ) if (print_db == True): print self.cursor.fetchall() def get_value( self, column ): self.cursor.execute( "SELECT %s FROM database" % column ) for n in self.cursor: print n def destructor( self ): self.cursor.close() def walking_and_filling( db ): pass if __name__ == "__main__": db = db() #walking_and_filling( db ) for root, dirs, files in os.walk( '''foo_path/''', topdown=False ): for name in files: joined = os.path.join(root, name) if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): try: audio = MP3 (joined, ID3=EasyID3 ) print (audio['album']) db.add_entry( joined, audio['album'] ) except: pass db.get_mediadb( print_db=True ) This is all the code. Some of that try pass code is just something i glued to create a clean slate database file From roygeorget at gmail.com Wed Mar 19 10:21:46 2008 From: roygeorget at gmail.com (royG) Date: Wed, 19 Mar 2008 07:21:46 -0700 (PDT) Subject: changing names of items in a list Message-ID: hi i am trying to rename extension of files in a directory..as an initial step i made a method in class ConvertFiles: def __init__(self,infldr,outfldr): self.infldr=infldr self.outfldr=outfldr self.origlist=os.listdir(infldr) .... def renamefiles(self,extn): for x in self.origlist: x=x+"."+extn ... later when i print self.origlist i find that the elements of list are unchanged..even tho a print x inside the renamefiles() shows that extn is appended to x .. why does this happen? RG From bogus@does.not.exist.com Thu Mar 13 01:06:52 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 00:06:52 -0500 Subject: Class Inheritance Message-ID: I am trying to bring functions to a class by inheritance... for instance in layout_ext I have.. --- layout_ext.py--------- class Layout() def...some function that rely on css in Layout.py def... ---EOF-- in the main application file I have... ----Layout.py--- from layout_ext import Layout from CSS import CSS css = CSS() class Layout(Layout) def __init__ more code..... ----EOF---- Problem is layout_ext and Layout code is dependant on a Class instance 'css'. Whenever the CSS instance it parses a file, this means that I would have to parse the file twice?? Why is this? Can I do something like pass an already created instance to the import? -- Andrew From sjmachin at lexicon.net Sat Mar 22 06:07:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 03:07:18 -0700 (PDT) Subject: function-class frustration References: Message-ID: <740f8b7f-7d1a-4f98-96c9-71e58e6a8519@u10g2000prn.googlegroups.com> On Mar 22, 7:19 pm, castiro... at gmail.com wrote: > > On the other hand, are you willing to make changes to the console? > How big and what? I was thinking of __ to keep the second-to-last > most recent command. Access to and editing of previous input lines is already provided by the cooked mode of the console (e.g. on Windows, lean on the up-arrow key) or can be obtained by installing the readline package. Perhaps by analogy with _, you mean the *result* of the penultimate *expression*. This functionality would be provided by the Python interactive interpreter but it's not ... do have a look at IPython (http:// ipython.scipy.org/moin/About); I don't use it but I get the impression that if it doesn't already keep a stack or queue of recent results, you could implement it yourself easily. From fetchinson at googlemail.com Mon Mar 17 21:28:04 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 17 Mar 2008 18:28:04 -0700 Subject: First Program Bug (Newbie) In-Reply-To: References: Message-ID: > P.S. What is the chance I'll get spam for using my real email address? Exactly 1. > I currently don't get any so... ... you will get now. Sorry to disappoint you, but it's better to be prepared in advance than be shocked later :) Cheers, Daniel From gagsl-py2 at yahoo.com.ar Fri Mar 28 17:58:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 18:58:22 -0300 Subject: Finding Full Path to Process EXE References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 16:40:01 -0300, escribi?: > I would like to write a script that would enumerate all running > processes and return the full path to the EXE of each running > process. However, I can't seem to find any good info on how to do > this..any help is greatly appreciated. Thanks. Use Tim Golden's WMI wrapper. Searching for "python enumerate running processes" with Google returns a reference to his module on the *first* hit. Searching in this newsgroup only, returns tons of references. -- Gabriel Genellina From jorgen.maillist at gmail.com Mon Mar 17 07:06:43 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 17 Mar 2008 12:06:43 +0100 Subject: comtypes question Message-ID: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> Hi All, I am trying to automate a 3rd party application, and all I have to work on is the type library and some documentation. I hope a Python / COM guru can answer this or put me on the right path because I don't know why it does not work. First I imported the typelib with comtypes like; >> from comtypes.client import GetModule >> GetModule("C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe") Which blurbs out a lot of text: # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1 # Generating comtypes.gen.BarTender Which seems to be ok. Now, I need to call a function on the Application object on which I need a "Messages" instance. The Application object gets created properly: >> import comtypes.gen.Bartender as bt >> app = comtypes.client.CreateObject(bt.Application) Which gives me the application (the bt.Application points to a wrapper class containing the CLSID of the COM class to be instantiated). Now I browse the typelibrary and I see there is a CoClass called Messages. I need one of those to pass as an argument, and since Messages is listed as a CoClass similar to Application, I assume it can also be instantiated. But when I try this I get an error: >>> msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}') Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\comtypes\client\__init__.py", line 198, in CreateObject obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface) File "C:\Python24\Lib\site-packages\comtypes\__init__.py", line 931, in CoCreateInstance _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p)) File "source/callproc.c", line 757, in GetResult WindowsError: [Errno -2147221164] Class not registered Both Application and Messages are listed as CoClass inside the typelibrary. Does anybody know why it gives me this error and what I am doing wrong? I have a COM Delphi background, and it would be similar to: msgs := CoMessages.Create; ... if the TLB is imported properly. Here is the details of the Application CoClass: [ uuid(B9425246-4131-11D2-BE48-004005A04EDF) ] coclass Application { [default] interface IBtApplication; dispinterface DBtApplication; }; And here is one from the Messages CoClass (as you can see the GUID matches): [ uuid(2B52174E-AAA4-443D-945F-568F60610F55) ] coclass Messages { [default] interface IBtMessages; dispinterface DBtMessages; }; Regards, - Jorgen From janeczek at gmail.com Thu Mar 27 01:01:17 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Thu, 27 Mar 2008 06:01:17 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> References: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Message-ID: <561cb5bc0803262201x7d2b7491p379ba10c441d2f94@mail.gmail.com> Hi, This is my second take on the project proposal. I have expanded on a few points, and hopefully also clarified a little bit. Please comment :) Regards, Michal Python-Haskell bridge ===================== Description ----------- This project will seek to provide a comprehensive, high level (and thus easy to use) binding between Haskell and Python programming languages. This will allow using libraries of either side from each language. If we decide to support function callbacks, these two functionalities (embedding Haskell in Python, and vice versa) become interrelated. In this light, it makes sense to implement them in the scope of the same project. Advantages of calling Haskell from Python ----------------------------------------- * Robust components It might be beneficial to implement safety-critical componenets in a strongly, statically typed language. Since Python itself is a terrific "glue language", such components would usually be purely functional, leaving IO to the Python side. Embedding Haskell code in this way is of particular interest when there already is a large existing Python infrastructure. One can implement new functionality in a form of Haskell plugin/component, even if complete rewrite is not feasible. * Performance improvements for speed-critical code Haskell compiled to native code is typically an order of magnitude faster than Python. Aside from that, advanced language features (such as multicore parallel runtime, very lightweight threads and software transactional memory) further serve to improve the performance. Haskell could become a safe, high level alternative to commonly used C extensions. * Access to sophisticated libraries While its set of libraries is not as comprehensive as that of Python, Haskell can still offer some well tested, efficient libraries. Some of the examples might be: * rich parser combinator libraries (like Parsec) * persistent, functional data structures (i.e. Data.Map, Data.IntMap, Data.Sequence, Data.ByteString) * QuickCheck testing library to drive analysis of Python code Advantages of calling Python from Haskell ----------------------------------------- * Python as a scripting language for Haskell applications Python is widely considered to be more approachable for regular users. As such, it could be used as a configuration/extension language for applications that benefit from extra flexibility. One example of such application is xmonad window manager. * Access to a large number of libraries As a much more popular language, Python has built up an impressive suite of libraries. There already are Haskell projects which rely on Python code to implement missing functionality, for example a paste bin application hpaste, which uses Pygments syntax coloring library. Deliverables ------------ * A low level library to access and manage Python objects from Haskell * Library support for wrapping Haskell values in Python objects. This is necessary to allow function callbacks. In addition, thanks to that feature large and/or lazy data structures can be efficiently passed from Haskell to Python * A set of low level functions to convert built-in data types between Haskell and Python (strings, numbers, lists, dictionaries, generators etc.) * A high level wrapper library for Haskell that simplifies embedding and calling Python code * A set of functions, and possibly a tool, to wrap up monomorphic functions and expose them to Python through foreign export facility * A way (an external tool, or a Template Haskell macro) to easily derive conversion functions for user-defined data types/objects * Documentation and a set of examples for all of above Optional goals -------------- In order of increasing amount of work and decreasing priority: * Exporting a wider class of functions to Python * A Python module that inspects a compiled Haskell module and transparently exposes functions within. This might be possible thanks to GHC API From danb_83 at yahoo.com Sun Mar 30 15:28:20 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 30 Mar 2008 12:28:20 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: On Mar 29, 12:34 pm, Lie wrote: > On Mar 29, 5:55 pm, kwitt... at telenet.be wrote: > > > I don't know if this is the right place to discuss the death of <> in > > Python 3.0, or if there have been any meaningful discussions posted > > before (hard to search google with '<>' keyword), but why would anyone > > prefer the comparison operator != over <>??? > ...snip... > > You're forcing your argument too much, both != and <> are NOT standard > mathematics operators -- the standard not-equal operator is >< -- and > I can assure you that both != and <> won't be comprehensible to non- > programmers. A lot of non-programmers use Microsoft Excel, which uses <> for the Not Equal operator. FWIW, the non-programmers on one forum I post on tend to use =/= . From miki.tebeka at gmail.com Tue Mar 11 13:11:23 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 11 Mar 2008 10:11:23 -0700 (PDT) Subject: How to make a Tkinter widget always visible? Message-ID: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> Hello, I have a simple Tkinter window with [GO] and [Quit] buttons at the bottom. When I resize the window to be shorter, the first thing to disappear are the buttons, however I want these button to be visible at all times. Is there a way to make sure that these buttons are always visible? Thanks, -- Miki http://pythonwise.blogspot.com From mail at microcorp.co.za Thu Mar 13 03:36:10 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 13 Mar 2008 09:36:10 +0200 Subject: List mutation method gotcha - How well known? Message-ID: <000901c884dd$057d5d80$03000080@hendrik> Hi, I am surprised that it took me so long to bloody my nose on this one. It must be well known - and I would like to find out how well known. So here is a CLOSED BOOK multiple choice question - no RTFM, no playing at the interactive prompt: Given the following three lines of code at the interactive prompt: foo = [1,2,3,4] x = foo.append(5) print x What will be the output (choose one): 1) [1,2,3,4] 2) [1,2,3,4,5] 3) That famous picture of Albert Einstein sticking out his tongue 4) Nothing - no output 5) None of the above I undertake to summarise answers posted to complete this "survey". - Hendrik From ron.duplain at gmail.com Tue Mar 4 10:44:15 2008 From: ron.duplain at gmail.com (Ron DuPlain) Date: Tue, 4 Mar 2008 07:44:15 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> Message-ID: <55f1c2b7-0f8f-4bcc-ac59-0b78a81cf81e@e31g2000hse.googlegroups.com> On Mar 4, 10:13 am, Siddhant wrote: > Hi people. > I was just wondering if a tab-completion feature in python command > line interface would be helpful? > If yes, then how can I implement it? > Thanks, > Siddhant ipython provides auto tab completion. http://ipython.scipy.org/ You can also get it by: $ easy_install ipython Run it using the command: $ ipython Is this what you want? Ron -- Ron DuPlain http://www.linkedin.com/in/rduplain From castironpi at gmail.com Thu Mar 6 00:35:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 21:35:51 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: On Mar 5, 8:06?pm, castiro... at gmail.com wrote: > On Mar 5, 4:25?pm, Steven D'Aprano > cybersource.com.au> wrote: > > On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote: > > > Classes and modules are really similar. ?In Python they're really > > > *really* similar. > > > Yes they are. > > > Both are namespaces. The very last line of the Zen of Python says: > > Namespaces are one honking great idea -- let's do more of those! > > Where to begin? And white to play. What does exec( open( 'modA.py' ).read() ) do? From geert at nznl.com Fri Mar 14 06:36:29 2008 From: geert at nznl.com (geert) Date: Fri, 14 Mar 2008 03:36:29 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard Message-ID: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Hi all, I have a mac mini running maocosx 10.5 leopard I want to deploy a django project on. My backend is MySQL, and I have it running as a 64- bit app. Of course, apache2 is also running as 64-bit. MySQLdb installs with the usual warnings after applying the various patches I found here and there. These patches consist of altering _mysql.c and site.cfg. Basically, my problem boils down to this: File "", line 1, in File "build/bdist.macosx-10.5-i386/egg/MySQLdb/__init__.py", line 19, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 7, in File "build/bdist.macosx-10.5-i386/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dynamic module does not define init function (init_mysql) Has anyone solved this? I been hunting around for 2 weeks now, and my deadline is looming grimly on the horizon :) Geert From grante at visi.com Tue Mar 11 12:26:50 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 11 Mar 2008 16:26:50 -0000 Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> <46f8d1bf-8821-4083-b7d7-d4ed53f8862a@q78g2000hsh.googlegroups.com> Message-ID: <13tdcma35fabb6a@corp.supernews.com> On 2008-03-11, Mark Dickinson wrote: >> That seems a bit baffling. ?If it urlopen doesn't support >> specifying proxies, why are there examples showing how to do >> it? If it does support specifying proxies, what is the >> pragraph quoted above supposed to mean? > > Looks like a definite documentation bug to me, and it's still > there in the development version of the documentation. I > think a bug report should be filed. > > A little bit of investigation shows that the documentation > changes were made in svn revisions 26181 and 26182 ( > > http://svn.python.org/view?view=rev&rev=26181 > > ) as a fix for > > http://bugs.python.org/issue523415 > > but this doesn't seem to help much with figuring out what the > docs intend to say. Before I submit a bug, I'll give it a try to find out if it does support explicit specification of proxys or not. -- Grant Edwards grante Yow! How many retured at bricklayers from FLORIDA visi.com are out purchasing PENCIL SHARPENERS right NOW?? From miki.tebeka at gmail.com Mon Mar 3 23:28:18 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 3 Mar 2008 20:28:18 -0800 (PST) Subject: tools to install not in python tree? References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: <7a03a83b-ba31-4ba4-8674-d3f591211b6c@e6g2000prf.googlegroups.com> Hello Jim, > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). ?I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ ?and some programs that I want in ~/public_html/ . ? I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). ?So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > ? install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). ?But as I understand it setup only targets > installing below sys.prefix; is that right? > > I can write routines for myself but other people must need to do these > things also and a tested solution is obviously better. ?Is there such > a tool? Have a look at http://docs.python.org/lib/module-distutils.html, specially http://docs.python.org/dist/node13.html and http://docs.python.org/inst/alt-install-windows.html HTH, -- Miki http://pythonwise.blogspot.com From gherron at islandtraining.com Thu Mar 27 11:48:31 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Mar 2008 08:48:31 -0700 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: <47EBC1CF.30604@islandtraining.com> Skip Montanaro wrote: >>> >>> proc = subprocess.Popen ("ls /tmp") >>> >> proc = subprocess.Popen ("ls /tmp", shell=True) >> >> or >> >> proc = subprocess.Popen (["ls", "/tmp"]) >> >> should work. >> > > Why should I need to set shell=True? I'm not globbing anything. The > second case still fails: > > >>>> proc = subprocess.Popen (["/usr/bin/ls" "/tmp"]) >>>> This line fails because of a typo. There needs to be a comma between the two list elements. Without the comma, this becomes proc = subprocess.Popen (["/usr/bin/ls/tmp"]) which obviously fails. Gary Herron > Traceback (most recent call last): > File "", line 1, in ? > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 542, in > __init__ > errread, errwrite) > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 975, in > _execute_child > raise child_exception > OSError: [Errno 20] Not a directory > > Thx, > > Skip > > > From mattheww at chiark.greenend.org.uk Wed Mar 5 14:19:08 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Mar 2008 19:19:08 +0000 (GMT) Subject: Why """, not '''? References: Message-ID: wrote: > Why is """ the preferred delimiter for multi-line strings? One advantage is that a dumb syntax highlighter is more likely to cope well if the content includes an apostrophe. -M- From usenet at solar-empire.de Tue Mar 18 11:48:05 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Tue, 18 Mar 2008 16:48:05 +0100 Subject: Interesting math problem References: Message-ID: sturlamolden wrote: > On 18 Mar, 00:58, Jeff Schwab wrote: > >> def make_slope(distance, parts): >> if parts == 0: >> return [] >> >> q, r = divmod(distance, parts) >> >> if r and parts % r: >> q += 1 >> >> return [q] + make_slope(distance - q, parts - 1) > > Beautiful. If Python could optimize tail recursion, it would even run > fast. This was my first thought, too. But tailcall optimisation wouldn't help here. `make_slope` is not tail recursive, the `+` (aka list.extend) gets executed after the recursion. Marc From sambo at voidstar.com Wed Mar 5 19:09:44 2008 From: sambo at voidstar.com (sambo q) Date: Thu, 06 Mar 2008 00:09:44 GMT Subject: access to base class __init__ Message-ID: I got myself in jam trying to be too fancy with threading.Thread Docs say / remind to call the base __init__ but I can't fighure out how. --------------------------- def main() ..... ls.listen(5) key = ' ' # while key != EXITCHARCTER: while stop_serving == False: cs, raddr = ls.accept() print "Main_Thread: ",cs, raddr nt = client_socket_handler( cs, raddr ) print threading.enumerate() key = getkey() # ls.close() time.sleep(4) print "Server Exiting." class client_socket_handler(threading.Thread): def __init__(self, cs, remote_address): ??????????????????????? self.threading.Thread.__init__(self,self.socket_handler,None,None) self.socket = cs self.rhost_addr = remote_address print "client_socket_handler.__init__(): ", self.socket, self.rhost_addr # t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) # t1.start() self.start() print "client_socket_handler.__init__(): ", self.socket, self.rhost_addr print "client_socket_handler.__init__(): enumerate()", threading.enumerate() def socket_handler( self, invar, indict ): threadname = self.getName() print "\"%s started\"" % threadname print "client_socket_handler.socket_handler() invar: ", invar instr = self.socket.recv( 500 ) # print instr req_lines = string.split( instr, "\r" ) for line in req_lines: line.strip( "\n") print req_lines print len( instr ) ---------------------------------- self.threading.Thread.__init__() self.Thread.__init__() ?? From Lie.1296 at gmail.com Fri Mar 14 14:32:41 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 14 Mar 2008 11:32:41 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <210b2a22-a8e3-414e-9018-15f7d74c9f83@d4g2000prg.googlegroups.com> On Mar 14, 4:57?pm, Jarek Zgoda wrote: > Lie napisa?(a): > > > > >> foo = [1,2,3,4] > >> x = foo.append(5) > >> print x > > >> What will be the output (choose one): > > >> 1) ?[1,2,3,4] > >> 2) ?[1,2,3,4,5] > >> 3) ?That famous picture of Albert Einstein sticking out his tongue > >> 4) ?Nothing - no output > >> 5) ?None of the above > > >> I undertake to summarise answers posted to complete this "survey". > > > I think I'll choose 3. Well, no, I suppose the correct behavior > > _should_ be undefined (i.e. what it returns is an implementation > > details that should not be relied on). The fact that it returns None > > is just a "coincidence" that happens to happen every time you tested > > it (you can't prove by ignorance) > > I think in Python there's no notion of "void" return type. Deliberate > choice to return None for functions that modify objects in place seems > to be OK as long as it is used consistently and documented. Which is the > case. No, there is no need for "void" return type, what I meant is that everything that's not said in the documentation should be assumed to be an implementation detail, a method or a function that doesn't say anything about its return type should be assumed to return an implementation detail (which basically means: Don't rely on this). The fact that list.append returns none is just a coincidence, you might encounter another list.append that returns different thing some time in the future, or the far future, or perhaps at the end of the galaxy's life. From rockxuan at gmail.com Tue Mar 18 03:44:56 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:44:56 -0700 (PDT) Subject: Rolex Swiss watch in www.51cntrade.com Message-ID: <83db7285-494a-4fc5-8551-318129fee56f@e6g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From vinodramachandran1 at gmail.com Mon Mar 10 08:25:47 2008 From: vinodramachandran1 at gmail.com (vinod ramachandran) Date: Mon, 10 Mar 2008 05:25:47 -0700 (PDT) Subject: 24 Hour Coding Contest AT BITS-Pilani in Association with Google Message-ID: <675de272-22a0-4eea-95a9-7087187ed4ad@s8g2000prg.googlegroups.com> 24 HOURS - NATIONWIDE ONLINE ALGORITHM INTENSIVE PROGRAAMING CHALLENGE Are you ready to tickle your grey cells with mind boggling algorithm intensive programming challenge that offers you freedom of programming in around 5 languages?? If yes, Watch out for 24 HOURS, the Nation wide Algorithm Intensive programming Contest brought to you by Computer Science Association (BITS Pilani) and GOOGLE India. 24 Hours is an online programming contest where in you will be provided with a real time programming problem from one of the most emerging arenas of computer science. You are required to design necessary algorithm to solve the problem, code it in any language of your choice - C,C++,JAVA,PYTHON OR RUBY!, with help of the API provided to you and submit your solutions within 24 hours from the commencement of the competition . This would be essentially a test for your endurance and efficiency in real-time problem solving. Contest starts at 1200 Hrs, 13th March, 2008 and is open to all students across the country. No registration fee required. Participants are required to solve the questions to be provided on www.bits-apogee.org/24hours and upload their solutions on or before 1200 Hrs, 14th March, 2008. Compete with most competent minds in the country, code your way to glory and win exciting prizes!!! For details contact: Yash Agrawal, Joint Coordinator,CSA, (Computer Science Association) Google Campus Ambassador, yash.1612 at gmail.com, BITS, Pilani. +919983526060 From skunkwerk at gmail.com Wed Mar 26 01:15:28 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 25 Mar 2008 22:15:28 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: On Mar 25, 9:25?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? > escribi?: > > >> ? ?i'm trying to call subprocess.popen on the 'rename' function in > >> linux. ?When I run the command from the shell, like so: > > >> rename -vn 's/\.htm$/\.html/' *.htm > > >> it works fine... however when I try to do it in python like so: > >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > >> print p.communicate()[0] > > >> nothing gets printed out (even for p.communicate()[1]) > > I'd try with: > > p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, > ? ? ? ?shell=True) > > (note that I added shell=True and I'm using a raw string to specify the ? > reg.expr.) > > -- > Gabriel Genellina Thanks Gabriel, I tried the new command and one with the raw string and single quotes, but it is still giving me the same results (no output). any other suggestions? cheers From mail at hellmutweber.de Tue Mar 4 16:01:10 2008 From: mail at hellmutweber.de (Hellmut Weber) Date: Tue, 04 Mar 2008 22:01:10 +0100 Subject: Eurosymbol in xml document Message-ID: <47CDB896.9010800@hellmutweber.de> Hi, thanks to all of you who have sent me helpful information. I'm diving into the secrets of unicode. It seems the crucial point was, that seemingly during the installation of the programming environment eric the file *** /usr/lib/python2.4/site-packages/sitecustomize.py *** has been modified. I found that file mentioned in the excellent online book 'Diving into python' Thanks again + happy pythoning Hellmut -- Dr. Hellmut Weber mail at hellmutweber.de Degenfeldstra?e 2 tel +49-89-3081172 D-80803 M?nchen-Schwabing mobil +49-172-8450321 please: No DOCs, no PPTs. why: tinyurl.com/cbgq From llothar at web.de Fri Mar 28 16:10:23 2008 From: llothar at web.de (llothar) Date: Fri, 28 Mar 2008 13:10:23 -0700 (PDT) Subject: Python 2.5 - Build Error on Windows because of SQLite3 Message-ID: Why does Python2.5 do not include the amalgamation source code of sqlite3? At the moment it is not possible to build the system out of the box with the Visual Studio project. I don't think this is good. The amalgamation version is exactly for this purpose. Is there a 2.5.3 release on the way? From toolmaster at 163.com Sun Mar 16 23:57:23 2008 From: toolmaster at 163.com (WaterWalk) Date: Sun, 16 Mar 2008 20:57:23 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <5b80e12a-f7f9-43bb-af48-cb2163e296af@s8g2000prg.googlegroups.com> On Mar 17, 11:54 am, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. > > So I'm curious how to read code effectively. I agree that python code > is clear, but when it becomes long, reading it can still be a hard > work. BTW. I think this problem also exists in other script languages. From ptmcg at austin.rr.com Sat Mar 8 23:30:42 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 8 Mar 2008 20:30:42 -0800 (PST) Subject: Parse specific text in email body to CSV file References: Message-ID: <4e232588-82df-4933-98bd-72c8657cb829@z17g2000hsg.googlegroups.com> On Mar 8, 4:20?pm, dpw.a... at gmail.com wrote: > I have been searching all over for a solution to this. I am new to > Python, so I'm a little lost. Any pointers would be a great help. I > have a couple hundred emails that contain data I would like to > incorporate into a database or CSV file. I want to search the email > for specific text. > > The emails basically look like this: > > random text _important text:_15648 random text random text random text > random text > random text random text random text _important text:_15493 random text > random text > random text random text _important text:_11674 random text random text > random text > ===============Date: Wednesday March 5, 2008================ > name1: 15 ? ? ? ? ? ? ? ?name5: 14 > > name2: 18 ? ? ? ? ? ? ? ?name6: 105 > > name3: 64 ? ? ? ? ? ? ? ?name7: 2 > > name4: 24 ? ? ? ? ? ? ? ?name8: 13 > > I want information like "name1: 15" to be placed into the CSV with the > name "name1" and the value "15". The same goes for the date and > "_important text:_15493". > > I would like to use this CSV or database to plot a graph with the > data. > > Thanks! This kind of work can be done using pyparsing. Here is a starting point for you: from pyparsing import Word, oneOf, nums, Combine import calendar text = """ random text _important text:_15648 random text random text random text random text random text random text random text _important text:_15493 random text random text random text random text _important text:_11674 random text random text random text ===============Date: Wednesday March 5, 2008================ name1: 15 name5: 14 name2: 18 name6: 105 name3: 64 name7: 2 name4: 24 name8: 13 """ integer = Word(nums) IMPORTANT_TEXT = "_important text:_" + integer("value") monthName = oneOf( list(calendar.month_name) ) dayName = oneOf( list(calendar.day_name) ) date = dayName("dayOfWeek") + monthName("month") + integer("day") + \ "," + integer("year") DATE = Word("=").suppress() + "Date:" + date("date") + Word("=").suppress() NAMEDATA = Combine("name" + integer)("name") + ':' + integer("value") for match in (IMPORTANT_TEXT | DATE | NAMEDATA).searchString(text): print match.dump() Prints: ['_important text:_', '15648'] - value: 15648 ['_important text:_', '15493'] - value: 15493 ['_important text:_', '11674'] - value: 11674 ['Date:', 'Wednesday', 'March', '5', ',', '2008'] - date: ['Wednesday', 'March', '5', ',', '2008'] - day: 5 - dayOfWeek: Wednesday - month: March - year: 2008 - day: 5 - dayOfWeek: Wednesday - month: March - year: 2008 ['name1', ':', '15'] - name: name1 - value: 15 ['name5', ':', '14'] - name: name5 - value: 14 ['name2', ':', '18'] - name: name2 - value: 18 ['name6', ':', '105'] - name: name6 - value: 105 ['name3', ':', '64'] - name: name3 - value: 64 ['name7', ':', '2'] - name: name7 - value: 2 ['name4', ':', '24'] - name: name4 - value: 24 ['name8', ':', '13'] - name: name8 - value: 13 Find out more about pyparsing at http://pyparsing.wikispaces.com. -- Paul From simon at brunningonline.net Fri Mar 7 11:44:10 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 7 Mar 2008 16:44:10 +0000 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: <8c7f10c60803070844pf88a497h9db85953851b3418@mail.gmail.com> On Fri, Mar 7, 2008 at 4:31 PM, K Viltersten wrote: > > 1. When writing English, Strunk and > White apply. I apply Fowler, PEP 8 be damned. ;-) -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From mwilson at the-wire.com Wed Mar 12 11:31:47 2008 From: mwilson at the-wire.com (Mel) Date: Wed, 12 Mar 2008 11:31:47 -0400 Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: Gerdus van Zyl wrote: > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus What they said, or, if you want to see it done: def combi (s): if s: for a in s[0]: for b in combi (s[1:]): yield [a] + b else: yield [] for y in combi ([['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]): print y From alexandru.dumitrescu at gmail.com Wed Mar 19 12:01:08 2008 From: alexandru.dumitrescu at gmail.com (Alexandru Dumitrescu) Date: Wed, 19 Mar 2008 18:01:08 +0200 Subject: add new csv line Message-ID: Hello everybody, Is there a way to add a new line at the beginning of a *.csv file, line which contain the name of the columns? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Sun Mar 9 05:31:17 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 9 Mar 2008 01:31:17 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> On 9 Mrz., 09:30, Lie wrote: > On Mar 9, 12:05 pm, Kay Schluehr wrote: > > > On 9 Mrz., 04:51, Lie wrote: > > > > A more through implementation would start from the raiser inspecting > > > the execution stack and finding whether there are any try block above > > > it, if no try block exist it pass silently and if one exist it will > > > check whether it have a matching except clause. This also circumvents > > > a problem that simple implementation have, as described below. > > > This will not be easy in particular in the presence of inheritance and > > dynamism. There is no way to statically decide whether an exception > > BException has the type AException and will be caught by the except > > clause in > > > try: > > BLOCK > > except AException, e: > > print "SoftException %s caught"%e > > A feasible solution was to invert the try...except statement and > > creating a continuation. > > > catch AException, a: > > print "SoftException A: %s"%a > > catch BException , b: > > print "SoftException B: %s"%b > > ... > > in: > > BLOCK > > > Here each SoftException is raised initially when a catch clause is > > entered and a continuation is created that returns to the catch block > > of the raised SoftException if required. When a SoftException is > > raised within BLOCK a lookup will be made and if a corresponding > > SoftException was found that was raised by a catch-clause the current > > control flow will be suspended and the continuation is called. > > I'd rather want to avoid any syntax changes, as I wished that Soft > Exception can be added to the language silently[1] so that new > programmers doesn't _need_ to know about it (although knowing it could > change the way they write codes to be more structured and simple). I just tried to save your proposal from being unimplementable. Maybe you can comment on it? I know of course that syntax is Pythons holy cow but I'm not Guidos mouthpiece and have a different perspective on some aspects of the system for obvious reasons [1]. I appreciate when people in the Python community talk about what is useful for them and not what the imaginary Pythonista superego thinks about them and how it will be standardized in the end - if anyhow. I'd like to know if SoftExceptions would make programs more reliable in the end because people won't use them sparingly but for all kinds of events that are somewhat "irregular" ( i.e. warnings ) not just for obvious errors. It's an interesting idea to have an advanced warning system that is more responsive than just this kind of logging which is currently implemented. And I'd surely discriminate them from the current exception handling at least in the design phase. Later language changes could still be "dissolved". [1] http://www.fiber-space.de/EasyExtend/doc/EE.html From josef.pktd at gmail.com Sat Mar 15 19:55:45 2008 From: josef.pktd at gmail.com (joep) Date: Sat, 15 Mar 2008 16:55:45 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> <47dc43e0$0$849$ba4acef3@news.orange.fr> Message-ID: <65faeeb8-d1d2-4d50-8421-f19a5ceb8ba5@8g2000hsu.googlegroups.com> you can also use standard module fileinput.input with ''inplace'' option which backs up original file automatically. from python help for fileinput: Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). From ptmcg at austin.rr.com Sat Mar 22 21:37:17 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Mar 2008 18:37:17 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <471ec539-3512-4a4e-a52d-68d979f0a53b@e39g2000hsf.googlegroups.com> On Mar 22, 11:40?am, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. ?Do you think > Python is a good first programming language for someone with zero > programming experience? ?Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. I absolutely support Python as a first programming language, from 7th grade on up. Here is a link at the main Python web site that should give you a number of additional resources: http://www.python.org/community/sigs/current/edu-sig/ -- Paul From dstromberglists at gmail.com Wed Mar 12 22:39:43 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 13 Mar 2008 02:39:43 +0000 (UTC) Subject: macro in python References: <910313af0802270254i27ca8a65xab54064bd91f4de@mail.gmail.com> Message-ID: On Wed, 27 Feb 2008 16:24:02 +0530, bharath venkatesh wrote: > hi .. > how to create macro in python for set of instruction that is done > frequently but too less in number to ignore the overhead of function > call ... > hi ..
    how to create macro in python for set of > instruction that is done frequently but too less in number to ignore the > overhead of function call ...
I believe python doesn't do macros, but you could look into wrapping your python code with m4. From python at rcn.com Mon Mar 17 19:39:12 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 17 Mar 2008 16:39:12 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 4:10 am, Bruce Eckel wrote: > If the following seems unnecessarily harsh, it was even more harsh for > me to discover that the time and money I had spent to get to my > favorite conference had been sold to vendors, presenting me as a > captive audience they could pitch to. My thoughts: * Saturday and Sunday were much better than Friday. * Open-source != Anti-vendor. The vendors are a vital part of the open-source community. * Lightning talks should be proportionate to their information content. The most common vendor message can be done in 45 seconds while the next speaker is setting-up: "Hi, I'm Raymond from Raymond Enterprises. We sell Raymond's signature to Raymond's fans. We use Python to crawl the web for clients wanting his signature. We're hiring Python programmers with experience in web-crawling. We're proud to sponsor for PyCon 2009. Good night and good luck.". * The sole guiding principle for the conference should be whatever best serves the attendees. * As the conference gets bigger, lots of previously minor annoyances will become more irritating. The conference organizers will adapt as needed. * Vendor/sponsor presentations should not have priority over informational talks. Also, lots of things went well: * Sean stepped-in and fixed-up the wireless for Saturday and Sunday (but on Friday the third-party wireless setup sucked mightily). * The conference admin (checkin, schedule posting, etc) was excellent. * The AV work was great (you'll soon be able to see HD recordings for most talks). * Steve Holden successfully created a new type of talk, "Teach me Twisted". * The feedback on the tutorials was excellent, the BoFs seemed to go well, and the sprints are off to a nice start. * The conference was close to the airport. One last thought: * Most of the conference work is done by volunteers. As the community grows, more volunteers will be needed (for next year, I plan to help by reviewing talk proposals). Raymond From mmanns at gmx.net Fri Mar 21 16:43:18 2008 From: mmanns at gmx.net (Martin Manns) Date: Fri, 21 Mar 2008 21:43:18 +0100 Subject: How can I make a function equal to 0? References: Message-ID: On Fri, 21 Mar 2008 13:12:56 -0700 (PDT) Arnaud Delobelle wrote: > On Mar 21, 7:48?pm, Martin Manns wrote: > Why do you want to do that? First thank you for your help, the callable object works. Basically I have a lot of functions inside a numpy array, of which most return "" and actually are derived as follows: from numpy import * grid_size = 1000000 class F(object): def __cmp__(self, other): return 0 def __call__(self, dummy): return "" f = F() myarray = array([f] * grid_size, dtype="O") # I re-define an element in the array myarray[34424] = lambda x: "23" # Now, I would like to loop over all re-defined elements: for i in itertools.izip(*nonzero(myarray)): print myarray[i]() If I fill the array with 0 instead of the functions that return "" this works really fast. However, I would like to be able call the content of each cell in the array as a function. As I said, the callable object approach works but is about as slow as iterating through the whole array. Perhaps I should add a __call__ function to the built-in 0? But I doubt that this helps. Martin From andreas.tawn at ubisoft.com Wed Mar 19 06:34:02 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Wed, 19 Mar 2008 11:34:02 +0100 Subject: First Program Bug (Newbie) In-Reply-To: <518f4420-19e1-4708-8b65-e44ca23da586@t54g2000hsg.googlegroups.com> References: <518f4420-19e1-4708-8b65-e44ca23da586@t54g2000hsg.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758003A0470A@PDC-MAIL3.ubisoft.org> [snip] >> What is the square root function in python? > > There's one in the math module. Use the one in gmpy if you have it. Or raise to the power 1/power >>> 9**(1.0/2) 3.0 Also works for cube root, quad root etc. >>> 27**(1.0/3) 3.0 >>> 81**(1.0/4) 3.0 >>> 243**(1.0/5) 3.0 Cheers, Drea From sjmachin at lexicon.net Mon Mar 3 07:14:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 3 Mar 2008 04:14:54 -0800 (PST) Subject: write float to Excel with pyExcelerator write References: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> Message-ID: <1bb4ba4b-27f3-4a31-bf59-00e36656a8e3@i12g2000prf.googlegroups.com> On Mar 1, 5:59 pm, Cyril.Liu wrote: > I use pyExcelerator to generat Excel files in my project. it works good > before I found this bug: > run this code: > > from pyExcelerator import * > wb = Workbook() > ws = wb.add_sheet("sheet") > for i in xrange(1): > ws.write(i,0, 10474224.6) > wb.save(r'd:\error_float.xls') > > open d:\error_float.xls with M$ Excle you'll find the number in the cell is > -263193.64 not 10474224.6 > > why? The author assumed unsigned integers instead of signed integers. >>> 1047422460 - 2**30 -26319364 See the following, previously posted here: http://mail.python.org/pipermail/python-list/2007-May/441633.html Cheers, John From sturlamolden at yahoo.no Sun Mar 16 14:55:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 11:55:31 -0700 (PDT) Subject: Advantage of the array module over lists? References: Message-ID: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> On 13 Mar, 20:40, Tobiah wrote: > I checked out the array module today. It claims that > arrays are 'efficient'. I figured that this must mean > that they are faster than lists, but this doesn't seem > to be the case: > > ################ one.py ############## > import array > > a = array.array('i') > > for x in xrange(10000000): > a.append(x) Lists are better optimized for appending to the end. Python lists are implemented as arrays of pointers, with a few empty slots at the end. Arrays are contigous memory buffers. They provide faster read-write access, particularly for chunks of data, but are slower at resizing. I never use the array module, as NumPy is superior. From yoz at home.havin.us Sat Mar 15 22:27:46 2008 From: yoz at home.havin.us (yoz) Date: Sun, 16 Mar 2008 02:27:46 GMT Subject: os.path.isdir question In-Reply-To: References: Message-ID: lampshade wrote: > Hello, > > I'm having some problems with os.path.isdir I think it is something > simple that I'm overlooking. > > #!/usr/bin/python > import os > > my_path = os.path.expanduser("~/pictures/") > print my_path > results = os.listdir(my_path) > for a_result in results: > if os.path.isdir(str(my_path) + str(a_result)): > results.remove(a_result) > > for x in results: print x > > The problem is, that the directories are never removed. Can anyone > point out what I'm missing that is causing the bug? Is there a better > way of doing this? > > Thanks, Your code works fine for me .. Someone will probably complain that this isn't pythonic or hopefully come up with an even neater way but what about this: #!/usr/bin/python import os my_path = os.path.expanduser("~/pictures/") print my_path files=os.walk(my_path).next()[2] for x in files: print x EdH. From cwitts at gmail.com Fri Mar 14 05:13:59 2008 From: cwitts at gmail.com (Chris) Date: Fri, 14 Mar 2008 02:13:59 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: On Mar 14, 8:36?am, Dennis Lee Bieber wrote: > On Thu, 13 Mar 2008 21:28:18 -0700 (PDT), jai_python > declaimed the following in comp.lang.python: > > > hi frenz I ?Need a Python Script For read multiple files(.txt) from a > > folder and write it in a single text file.... > > ? ? ? ? If you are on windows, just open a command prompt and use the > standard copy command... > > C:\Documents and Settings\Dennis Lee Bieber>copy /? > Copies one or more files to another location. > > COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/A | /B ] source [/A | /B] > ? ? ?[+ source [/A | /B] [+ ...]] [destination [/A | /B]] > > ? source ? ? ? Specifies the file or files to be copied. > ? /A ? ? ? ? ? Indicates an ASCII text file. > ? /B ? ? ? ? ? Indicates a binary file. > ? /D ? ? ? ? ? Allow the destination file to be created decrypted > ? destination ?Specifies the directory and/or filename for the new > file(s). > ? /V ? ? ? ? ? Verifies that new files are written correctly. > ? /N ? ? ? ? ? Uses short filename, if available, when copying a file > with a > ? ? ? ? ? ? ? ?non-8dot3 name. > ? /Y ? ? ? ? ? Suppresses prompting to confirm you want to overwrite an > ? ? ? ? ? ? ? ?existing destination file. > ? /-Y ? ? ? ? ?Causes prompting to confirm you want to overwrite an > ? ? ? ? ? ? ? ?existing destination file. > ? /Z ? ? ? ? ? Copies networked files in restartable mode. > > The switch /Y may be preset in the COPYCMD environment variable. This > may be overridden with /-Y on the command line. ?Default is to prompt on > overwrites unless COPY command is being executed from within a batch > script. > > To append files, specify a single file for destination, but multiple > files for source (using wildcards or file1+file2+file3 format). > > C:\Documents and Settings\Dennis Lee Bieber> > > ? ? ? ? Note that last paragraph "To append files" > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ If you want to go that route you could also do: type *.txt > output_file.txt From sjmachin at lexicon.net Sat Mar 22 00:41:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 21:41:51 -0700 (PDT) Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> <05e369b9-ba75-488f-b58c-de437af2e1c5@d4g2000prg.googlegroups.com> Message-ID: <21e0f575-d65c-4488-9b5b-daf4598ad19c@c19g2000prf.googlegroups.com> On Mar 22, 3:32 pm, Gabriel Genellina wrote: > On 21 mar, 19:25, John Machin wrote: > > > > > On Mar 22, 8:51 am, Gabriel Genellina wrote: > > > > If you drop this condition then you could fill the array with zeroes > > > as before, replace only the interesting ones with actual functions, > > > and write: > > > > for item in myarray[nonzero(myarray)]: > > > print item() if callable(item) else item > > > Let's unbuckle the seat belt :-) > > > If "item" is definitely restricted to being either 0 or a callable > > object, then > > item() if item else 0 > > should give the same answer as, and is quite likely to be faster than, > > item() if callable(item) else item > > as it avoids a global lookup and a function call. > > In that case, we could use a bare item() because nonzero would have > filtered out all that zeroes. True. From gagsl-py2 at yahoo.com.ar Thu Mar 6 20:10:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 23:10:31 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 22:56:33 -0200, escribi?: > On Mar 6, 5:35?am, "Gabriel Genellina" wrote: >> >> p = P() >> print p.bar.func_name # -> bar >> p.bar.im_func.anotherattribute = 1 >> print p.bar.anotherattribute # -> 1 >> >> (the attribute must be set on the *function* itself if you want it to >> be ? >> somewhat persistent; methods are usually volatile objects) > > You read my mind. You could try to write in a way that reading your mind isn't necesary... > I was just getting: > assert p.bar is p.bar > and failing. > > But if you set them on im_func, instances don't have their own. Instances don't have their own methods either. What do you actually want to do? If you need a method with per-instance attributes, that looks like another object to me. -- Gabriel Genellina From noname9968 at gmail.com Wed Mar 19 15:07:26 2008 From: noname9968 at gmail.com (Alex9968) Date: Wed, 19 Mar 2008 22:07:26 +0300 Subject: Tkinter.Text widget - how to get text cursor position? In-Reply-To: <47E14F47.6000202@gmail.com> References: <47E14F47.6000202@gmail.com> Message-ID: <47E1646E.5070908@gmail.com> Alex9968 wrote: > Is it possible to get position (in numbers) of the insertion cursor? As > I understood, Text widget uses mark named INSERT to store it, which is > available globally by just referencing INSERT, but how could I get > actual coordinate numbers of the mark? > I need this because I want not just to insert string at, but to examine > text before and after the insertion cursor. I can probably use .get() to > extract the halves of text before and after cursor, but it'd be better > just to know the position. > > Thanks It's .index() Problem was that it's missed in Tkinter reference: a GUI for Python From jeffober at gmail.com Fri Mar 7 16:12:18 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 7 Mar 2008 13:12:18 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: Use metaclasses? DBak wrote: > I want - but cannot get - a nested class to inherit from an outer > class. (I searched the newsgroup and the web for this, couldn't find > anything - if I missed an answer to this please let me know!) > > I would like to build a class for a data structure such that nodes of > the data structure - of interest only to the data structure > implementation itself and not to the consumer - are instances of one > of two class types. I thought to encapsulate the nodes' classes like > this: > > class Tree(object): > ...class _MT(Tree): > ......def isEmpty(self): return True > ......def insert(self, X): return Tree._Node(X) > ...class _Node(Tree): > ......def isEmpty(self): return False > ......def insert(self, X): return _Node(X, self, Tree._MT()) > ...def merge(self, T): > ......def __init__(): return _MT() > ...... > > In other words, some methods would be implemented on instances' > classes (like isEmpty and insert) and some on the outer class (like > merge). Users of the data structure never need to know about the > nodes, much less the nodes' classes, so I wanted to encapsulate them > > However I can't do this, because, of course, the name Tree isn't > available at the time that the classes _MT and _Node are defined, so > _MT and _Node can't inherit from Tree. > > What is the Pythonic thing I should be doing instead? > > (Easy answer: Put this code in a module, exposing only a factory > function. I could do that, but wanted to know if I could encapsulate > it as described so I could actually put several similar data > structures into one module.) > > Thanks! -- David From steve at holdenweb.com Mon Mar 31 07:44:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 07:44:54 -0400 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <47F0CEB6.2050006@holdenweb.com> No, sorry. regards Steve Pradeep Rai wrote: > Hi Steve, > > Can you guide me how to install a 2.5 version of dbi for it to work ? > > Thanks !! > > Pradeep > > Pradeep Rai wrote: > > > Hi All, > > > > > > I have upgraded python v2.5.2 from python v2.4.3. The upgradation > > > results into following error: > > > "Python C API version mismatch for module dbi: This Python has API > > > version 1013, module dbi has version 1012." > > > > > > Please suggest, how to resolve this error to proceed further. > > > > > > Regards, > > > Pradeep Rai > > > > > > > > Don't try and drag 2.4 extension modules into the 2.5 environemnt. You > > will have to install a 2.5 version of dbi for it to work. > > regards > > Steve > > -- > > Steve Holden +1 571 484 6266 +1 800 494 3119 > > Holden Web LLC > > _http://www.holdenweb.com/_ > > -- > > _http://mail.python.org/mailman/listinfo/python-list_ -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jeffrey at fro.man Tue Mar 18 12:24:03 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 18 Mar 2008 09:24:03 -0700 Subject: Decode email subjects into unicode References: Message-ID: <13tvr53smbfp9c4@corp.supernews.com> Laszlo Nagy wrote: > I know that "=?UTF-8?B" means UTF-8 + base64 encoding, but I wonder if > there is a standard method in the "email" package to decode these > subjects? The standard library function email.Header.decode_header will parse these headers into an encoded bytestring paired with the appropriate encoding specification, if any. For example: >>> raw_headers = [ ... '=?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?=', ... '[Fwd: re:Flags Of The World, Us States, And Military]', ... '=?ISO-8859-2?Q?=E9rdekes?=', ... '=?UTF-8?B?aGliw6Fr?=', ... ] >>> from email.Header import decode_header >>> for raw_header in raw_headers: ... for header, encoding in decode_header(raw_header): ... if encoding is None: ... print header.decode() ... else: ... print header.decode(encoding) ... ??????????????? ? ???????????? [Fwd: re:Flags Of The World, Us States, And Military] ?rdekes hib?k Jeffrey From Robert.Bossy at jouy.inra.fr Wed Mar 12 08:52:03 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 12 Mar 2008 13:52:03 +0100 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: <47D7D1F3.5040706@jouy.inra.fr> k.i.n.g. wrote: > I think I am not clear with my question, I am sorry. Here goes the > exact requirement. > > We use dd command in Linux to create a file with of required size. In > similar way, on windows I would like to use python to take the size of > the file( 50MB, 1GB ) as input from user and create a uncompressed > file of the size given by the user. > > ex: If user input is 50M, script should create 50Mb of blank or empty > file > def make_blank_file(path, size): f = open(path, 'w') f.seek(size - 1) f.write('\0') f.close() I'm not sure the f.seek() trick will work on all platforms, so you can: def make_blank_file(path, size): f = open(path, 'w') f.write('\0' * size) f.close() Cheers, RB From stephenhorne100 at aol.com Tue Mar 18 07:47:49 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 18 Mar 2008 04:47:49 -0700 (PDT) Subject: Python 3 and PEP238 division References: Message-ID: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> On Mar 17, 7:26 pm, "Terry Reedy" wrote: > "Ninereeds" wrote in message > > news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... > | Is the PEP238 change to division going into Python 3 as planned? > > IDLE 3.0a3>>> 1/2 > > 0.5 > > | I realise that the new integer division semantics have been available > | in "from __future__" for quite a few years now, but a warning might be > | appropriate now that Python 3 is in alpha. > > 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion > program The tools can work out the *intent* of any particular division operator? Can work out whether the result should be integer or float, independent of any particular set of arguments? Seems unlikely. From http Fri Mar 28 02:49:46 2008 From: http (Paul Rubin) Date: 27 Mar 2008 23:49:46 -0700 Subject: SoC project: Python-Haskell bridge - request for feedback References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: <7xabkjbawl.fsf@ruckus.brouhaha.com> "Micha? Janeczek" writes: > I wasn't aware of the runtime issues, these can be things to watch out > for. However, the type of embedding that I imagined would be mostly > pure functions, since Python can deal with IO rather well. It'd also > be applicable in situations where we want to add some functionality to > to existing, large Python project, where the complete rewrite > would be infeasible. Of course I can't say what functions someone else would want to use, but I'm not seeing very convincing applications of this myself. There aren't that many prewritten Haskell libraries (especially monomorphic ones) that I could see using that way. And if I'm skilled enough with Haskell to write the functions myself, I'd probably rather embed Python in a Haskell app than the other way around. Haskell's i/o has gotten a lot better recently (Data.ByteString) though there is important stuff still in progress (bytestring unicode). For other pure functions (crypto, math, etc.) there are generally libraries written in C already interfaced to Python (numarray, etc.), maybe through Swig. The case for Haskell isn't that compelling. > I didn't mention this in this first draft, but I don't know (yet) > how to support those "fancy" types. The plan for now is to export > monomorphic functions only. This probably loses most of the interesting stuff: parser combinators, functional data structures like zippers, etc. Unless you mean to use templates to make specialized versions? > As for GC, I think having the two systems involved is unavoidable if > I want to have first class functions on both sides. This just seems worse and worse the more I think about it. Remember that GHC uses a copying gc so there is no finalization and therefore no way to notify python that a reference has been freed. And you'd probably have to put Haskell pointers into Python's heap objects so that the Haskell gc wouldn't have to scan the whole Python heap. Also, any low level GHC gc stuff (not sure if there would be any) might have to be redone for GHC 6.10(?) which is getting a new (parallel) gc. Maybe I'm not thinking of this the right way though, I haven't looked at the low level ghc code. Keep in mind also that Python style tends to not use complex data structures and fancy sharing of Haskell structures may not be in the Python style. Python uses extensible lists and mutable dictionaries for just about everything, relying on the speed of the underlying C functions to do list operations very fast (C-coded O(n) operation faster than interpreted O(log n) operation for realistic n). So maybe this type of sharing won't be so useful. It may be simplest to just marshal data structures across a message passing interface rather than really try to share values between the two systems. For fancy functional structures, from a Python programmer's point of view, it is probably most useful to just pick a few important ones and code them in C from scratch for direct use in Python. Hedgehog Lisp (google for it) has a nice C implementation of functional maps that could probably port easily to the Python C API, and I've been sort of wanting to do that. It would be great if you beat me to it. > > Anyway I'm babbling now, I may think about this more later. > By all means, please do go on :) This has helped a lot :) One thing I highly recommend is that you join the #haskell channel on irc.freenode.net. There are a lot of real experts there (I'm just newbie) who can advise you better than I can, and you can talk to them in real time. From znfmail-pythonlang at yahoo.com Wed Mar 19 11:03:03 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Wed, 19 Mar 2008 11:03:03 -0400 Subject: cx_Oracle execute procedure Message-ID: I've been working on the code below and and executes silently, no complaints, however the end result should be a record in my table and it's not added. The procedure works with the passed credentials using SQLPlus or SQL Developer clients. However I'm not sure if I'm constructing my python code correctly to interact with Oracle. I've been basing the code below on what I found in this thread http://www.thescripts.com/forum/thread33728.html . Zach- import cx_Oracle connection = cx_Oracle.connect("user/pass at server") ## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum varchar2, p_prefix number) cur = connection.cursor() repParams = {} repParams['arg1'] = "5555555" repParams['arg2'] = "2" repParams['arg3'] = "999" sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3); end;""" cur.execute(sqlStr, repParams) connection.commit cur.close connection.close From grahn+nntp at snipabacken.se Sun Mar 30 19:07:02 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 23:07:02 GMT Subject: Where can I find : References: <13uu56hn1vdqb9d@corp.supernews.com> Message-ID: On Sat, 29 Mar 2008 21:19:32 -0700, Dennis Lee Bieber wrote: > On Sat, 29 Mar 2008 20:15:59 -0700 (PDT), pythonnubie > declaimed the following in comp.lang.python: > >> Hi All : >> Does anyone know where I can find either a book or a website that >> explains beginning python by actually building a project line by >> line and explaining it indepth . I am primarily interested in >> understading flowcontrol as well as syntax . >> > Flow control, if I'm not misinterpreting your usage, is something > that most common language books will not really cover -- that falls into > the realms of software engineering... He *might* simply be talking about if, for, while, break and so on -- things which control program flow. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From Lie.1296 at gmail.com Sun Mar 9 13:45:43 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 10:45:43 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> Message-ID: On Mar 9, 9:29?pm, Kay Schluehr wrote: (snip) > You are an appropriate person to consider the workflow in a dynamic > language, no matter how the language is implemented internally. I agree, but the only thing I'm not confident to talk about is how it'll be implemented, since I think an idea should suggest how it can be implemented in practice to show that it's not just a nonsense paper idea that's not possible in reality. > Just start with function calls > > ? ?maybe_raise(ZeroDivisionError) > > The only requirement is that maybe_raise has to know when it shall > raise ZeroDivisionError. This depends on whether the exception is > caught. How do the program knows this in advance? There are no static > analysis techniques available. Perhaps similar technique the compiler uses to determine whether a function is a normal function or a generator function? Positive forward lookup for any soft exceptions, which would then activate matching soft exceptions inside the code? > When maybe_raise is entered the system must know that the exception is > handled in the future. You can't inspect the call stack for this > purpose because the call stack represents past events and > continuations ( and you can't rely on names ). > > So you need something like this > > ? ?do_softexception(ZeroDivisionError) > ? ?try: > ? ? ? TRY_BLOCK > ? ?except ZeroDivisionError: > ? ? ? EXCEPT_BLOCK > > But this looks odd and the solution isn't DRY. So better one macro- > transforms a new statement into this form. From mark.e.tolonen at mailinator.com Mon Mar 17 23:33:10 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Mon, 17 Mar 2008 20:33:10 -0700 Subject: struct unpack References: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> Message-ID: "brnstrmrs" wrote in message news:1878d2f6-8a87-4599-98bb-2d3d2bcbce7f at u72g2000hsf.googlegroups.com... > If I run: > > testValue = '\x02\x00' > junk = struct.unpack('h', testValue) > > Everything works but If I run > > testValue = raw_input("Enter Binary Code..:") inputting at the > console '\x02\x00' > junk = struct.unpack('h', testValue) > > It errors out with > Traceback (most recent call last): > File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in > junk = struct.unpack('h', testValue) > File "struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 2 > > any ideas? raw_input doesn't understand escape sequences. You have to decode them. import struct testValue=raw_input() # input '\x02\x00' junk = struct.unpack('h',testValue.decode('string_escape')) --Mark From ggpolo at gmail.com Thu Mar 27 10:58:36 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 11:58:36 -0300 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: 2008/3/27, Skip Montanaro : > I am trying to replace os.system calls with subprocess.Popen. This simple > example fails miserably: > > >>> proc = subprocess.Popen ("ls /tmp") proc = subprocess.Popen ("ls /tmp", shell=True) or proc = subprocess.Popen (["ls", "/tmp"]) should work. > Traceback (most recent call last): > File "", line 1, in > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 594, in __init__ > errread, errwrite) > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 1091, in > _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I also tried explicitly referencing /usr/bin/ls. Same result. What gives? > I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with > 2.6alpha on Mac OS X. > > Frustrated in Chicago... > > Skip > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bagpussnz at gmail.com Sun Mar 9 22:00:26 2008 From: bagpussnz at gmail.com (Bagpussnz) Date: Sun, 9 Mar 2008 19:00:26 -0700 (PDT) Subject: Python 2.5 segmentation faulting importing random Message-ID: <788c15f8-9701-470e-9262-c9f6b3297598@s12g2000prg.googlegroups.com> Hi, Whenever I try to import random in a python module, I get a segmentation fault. I've traced it using, import pdb pdb.set_trace() import random When it gets to.. > /usr/lib/python2.5/random.py(57)() -> LOG4 = _log(4.0) It seg faults. I'm running on OpenSuse 10.2. Linux devhost 2.6.18.8-0.7-bigsmp #1 SMP Tue Oct 2 17:21:08 UTC 2007 i686 i686 i386 GNU/Linux The python header says.. Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Any ideas? Regards, Ian. From Lie.1296 at gmail.com Mon Mar 10 14:47:54 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 10 Mar 2008 11:47:54 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> Message-ID: On Mar 10, 12:12?pm, John Nagle wrote: > Steven D'Aprano wrote: > > On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > > >> On 9 Mrz., 06:30, Steven D'Aprano >> cybersource.com.au> wrote: > >> Is it really so exotic that it requires the demand for more use cases? > > > Are the existing solutions really so incomplete that we need yet another > > solution? > > > What problem are you trying to solve with SoftExceptions? > > ? ? I actually implemented something like "soft exceptions" in a LISP > program long ago. I called them "gripes". ?They were a way that a function > could complain about something it wanted the caller to fix. The caller > could either fix it or decline to do so. > > ? ? This was for a robotic planning application, where one module had detected > that some precondition that it needed wasn't satisfied. ?This was usually > something like some physical object being in the wrong place for a later > operation, and a previously planned move needed to be modified. Passing > the problem back to the caller sometimes allowed an easy fix, rather than > aborting the whole plan and building a new one. > > ? ? This isn't a common problem. > > ? ? In the rare cases that it is needed, it can be implemented with callbacks. > It doesn't require a language extension. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle The problem with callbacks is that it works only for a small amount of callbacks, it'd be too messy to have twenty different callbacks. And the ultimate problem with callbacks is that we can't determine from the outside whether the operation should continue or breaks at the point of the callback without some messy trick. We can't always determine whether we want to do this: def somefunc(argA, argB, callback = DO_NOTHING): if argA == argB: callback() or this: def somefunc(argA, argB, callback = DO_NOTHING): if argA == argB: callback() return perhaps we could do this: if argA == argB: if callback() == True: return but that's so much extra codes written and would've been too messy to write. And actually this isn't a rare cases, and in fact is very common. It's just that most cases that can be more cleanly written in SoftException, can usually be handled in different ways, using tricks that range from subtle to messy (like callbacks). From leszek at dubiel.pl Wed Mar 12 07:44:45 2008 From: leszek at dubiel.pl (Leszek Dubiel) Date: Wed, 12 Mar 2008 12:44:45 +0100 Subject: Some thoughts on defining built-in types Message-ID: <47D7C22D.8040209@dubiel.pl> An HTML attachment was scrubbed... URL: From skunkwerk at gmail.com Tue Mar 25 23:31:19 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 25 Mar 2008 20:31:19 -0700 (PDT) Subject: subprocess.popen function with quotes Message-ID: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> Hi, i'm trying to call subprocess.popen on the 'rename' function in linux. When I run the command from the shell, like so: rename -vn 's/\.htm$/\.html/' *.htm it works fine... however when I try to do it in python like so: p = subprocess.Popen(["rename","-vn","'s/\.htm$/ \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] nothing gets printed out (even for p.communicate()[1]) I think the problem is the quoted string the rename command wants - when I put it in triple quotes like """s/\.htm$/\.html/""" I get some output, but not the correct output. I've also tried escaping the single quotes with \' and putting it in regular double quotes but that didn't work either. i'd appreciate any help From adrianbn at gmail.com Tue Mar 18 05:16:49 2008 From: adrianbn at gmail.com (=?ISO-8859-1?Q?Adri=E1n_Bravo_Navarro?=) Date: Tue, 18 Mar 2008 10:16:49 +0100 Subject: Comunicate processes with python In-Reply-To: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> Message-ID: <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> Hi, Does the absence of answers mean that the unique way to let the console invoke daemon functions is trough dbus or sockets? I wonder if python provides any other mechanism to get this. Thanks Adrian 2008/3/17, Adri?n Bravo Navarro : > > Hi, > > let me introduce ourselves first. We are a smallish group of students > working on a open source snapshot/backup system (www.hdlorean.com or > http://launchpad.net/hdlorean). We are using python for almost all of the > code and for all of us this is the first python project we develop. At this > point I must say that we are really happy with python, as it is a fast > learning and easy language. > > Now I've just bored most of you, I would like to make a question to the > list. Let me portray the scenario: > > We have a daemon (hdloreand) running. We also have a console so you can > send commands to the daemon and retrieve some info. At this moment, that > console is connecting to the daemon via Dbus. We would like to avoid this, > because it will solve some collateral problemas as well as will guarantee > that the comunication will work when no X server and no dbus session is > running. > > Is there any simple way to achieve this goal? We've been thinking of > sockets but Im not conviced at all with that. > > Thanks > Adrian > > PS: Im sorry for my english. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marek.rocki at wp.pl Mon Mar 17 10:59:04 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Mon, 17 Mar 2008 07:59:04 -0700 (PDT) Subject: pass float array(list) parameter to C References: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> Message-ID: <013c161a-931c-4576-935d-4341911a299f@s37g2000prg.googlegroups.com> You can also do it with ctypes only; too bad it's not really well documented. c_float is a type of a floating point number and it has * operator defined, so that c_float*4 is a type of a 4-element array of those numbers. So if you want to construct an array of floats from a list of floats, you can do it like this: from ctypes import c_float x = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9] float_array_type = c_float*len(x) float_array = float_array_type(*x) print float_array From radix at twistedmatrix.com Wed Mar 26 21:26:11 2008 From: radix at twistedmatrix.com (Christopher Armstrong) Date: Wed, 26 Mar 2008 21:26:11 -0400 Subject: [ANN] Twisted 8.0 Message-ID: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> http://twistedmatrix.com/ MASSACHUSETTS (DP) -- Version 8.0 of the Twisted networking framework has been released, Twisted Matrix Laboratories announced Wednesday. Enslaved by his new robotic overloads, Master of the Release Christopher Armstrong presented the new package to the Internet on March 26th. Armstrong was unable to comment, because of a device worn around his neck preventing him from doing so, scientists say. Secretary of Defense Jean-Paul Calderone was asked about concerns that French interference may have played a role in the delay of this release. "I find such speculation preposterous. Thomas Herv? is an upstanding member of the Labs and his loyalties lie with us. He is a fine addition to our team." Rumors in the community allege that Secretary Calderone is holding Herv?'s cat ransom until the release is successfully distributed. Herv? was unavailable for comment. This release comes shortly after the announcement by Chief of Public Affairs Duncan McGreggor that Twisted had joined the Software Freedom Conservancy. "We're happy to join the SFC, and we are now accepting sponsorship. The fact that we are now ruled by a cabal of robots should not put off potential donors. Our robotic overlords are running us at peak efficiency, so we can most effectively distribute The Love." Asked about the version number jump in this release, Commander-in-Chief Glyph Lefkowitz had the following to say: "Our benefactors have found our previous dice-rolling version number scheme to be inadequate, and have deigned to propose to us a more... logical system of versioning." ===== Twisted is an event-based framework for Internet applications which works on Python 2.3, 2.4, and 2.5. It can be downloaded from http://twistedmatrix.com/ Twisted 8.0 is a major feature release, with several new features and a great number of bug fixes. Some of the highlights follow. - The IOCP reactor is now much improved and many bugs have been resolved. - Twisted is now easy_installable. - Many improvements were made to Trial, Twisted's unit testing system. - A new memcache client protocol implementation was added. - So much more[1]! To see the full list of changes in its fifteen kilobytes of glory, see the release notes[1]. We welcome you to download and enjoy, and please file any bugs you find[2] and send comments to the mailing list[3]. Why the large version number bump? We've decided to switch to a time-based versioning scheme. "8.0" means the first release in 2008. [1] http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.0.1/NEWS?format=raw [2] Register: http://twistedmatrix.com/trac/register New ticket: http://twistedmatrix.com/trac/newticket [3] http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python Thanks! -- Christopher Armstrong International Man of Twistery http://radix.twistedmatrix.com/ http://twistedmatrix.com/ http://canonical.com/ From anand.prabhakar.patil at gmail.com Sat Mar 1 13:29:23 2008 From: anand.prabhakar.patil at gmail.com (Anand Patil) Date: Sat, 1 Mar 2008 10:29:23 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> References: <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> Message-ID: <2bc7a5a50803011029rf19982etda274d5da12be1@mail.gmail.com> Not sure if this is common knowledge yet but Sympy, http://code.google.com/p/sympy, has a rational type. In [2]: from sympy import * In [3]: Rational(21,4) Out[3]: 21/4 In [4]: Rational(21,4)+Rational(3,4) Out[4]: 6 From missxxy78 at gmail.com Thu Mar 13 08:20:19 2008 From: missxxy78 at gmail.com (MSmith) Date: Thu, 13 Mar 2008 05:20:19 -0700 (PDT) Subject: Diary of a Stripper. Message-ID: <47d9876e-54a0-4139-81bd-2c28cc24122d@u10g2000prn.googlegroups.com> Hi, my name is Michelle, I'm 27, just left being a secretary to become a stripper, and looking for friends to talk to. I love meeting new people! I also have a blog where I talk about my life... http://missxxy.blogspot.com Talk to you soon! Michelle From kellygreer1 at yahoo.com Wed Mar 26 14:50:30 2008 From: kellygreer1 at yahoo.com (kellygreer1) Date: Wed, 26 Mar 2008 11:50:30 -0700 (PDT) Subject: Filtering a Python list to uniques References: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> Message-ID: On Mar 26, 5:45 am, hellt wrote: > On 26 ???, 02:30,kellygreer1 wrote: > > > What is the best way to filter a Python list to its unique members? > > I tried some method using Set but got some "unhashable" error. > > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > > # how do i reduce this to > > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > > Is there a page on this in the Python in a Nutshell or the Python > > Cookbook? > > Did I miss something? > > > Kelly Greer > > kellygre... at nospam.com > > change nospam to yahoo > > or just look this thread for a fastest solutionhttp://groups.google.com/group/comp.lang.python/browse_frm/thread/709... How come the Set() thing seems to work for some people and I get the 'unhashable' error? How do you test for 'membership' on a dictionary? # where tmp is the non-unique list # dct is a dictionary where each unique key will be tied to a count (the value) # for testing I was setting the count to 0 for v in tmp: if not v in dct: dct[v] = 0 # I get unhashable error here. # Even if I write it. for v in tmp: if not v in dct.keys(): dct[v] = 0 What am I missing? Thanks, Kelly From castironpi at gmail.com Mon Mar 10 02:39:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 23:39:03 -0700 (PDT) Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> <3ebaa96f-7c93-4aa8-a7d2-13764140831f@k13g2000hse.googlegroups.com> Message-ID: <7569e294-df4b-42d9-8263-f3b3f6377682@s50g2000hsb.googlegroups.com> > > I am trying to solve a genetic algorithm problem where I want to read > > a bitvector of very large size (say 10000) and manipulate bits based > > on certain algorithms. Here's one on the Python website: http://search.live.com/results.aspx?q=python+bitvector&src=IE-SearchBox => http://pypi.python.org/pypi/BitVector/1.3 => http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.3.html code=> http://cobweb.ecn.purdue.edu/~kak/dist/BitVector_1.3_CodeOnly.py.html "The bits of a bit array are stored in 16-bit unsigned ints." However, Python has variable size longs. Do you want something less elaborate? Here is what I think of when you say bitvector: bA= bitvector() bA[3]= 0 bA[7]= 1 bA[2].set() bA[1]^= b[9] bA[2:6].set() rangeA= ba[2:7] rangeA= "011101" rangeA.clear() bytearray is kind of close, but new in Py 3.0. How close is it to the perspective of the application you're writing? Here's some of it straight off the console: >>> b= bytearray(5) >>> b bytearray(b'\x00\x00\x00\x00\x00') >>> b[1]= 1 >>> b bytearray(b'\x00\x01\x00\x00\x00') >>> list(b) [0, 1, 0, 0, 0] From piet at cs.uu.nl Mon Mar 10 10:33:47 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 10 Mar 2008 15:33:47 +0100 Subject: Python-URL! - weekly Python news and links (Feb 18) References: Message-ID: >>>>> Peter Otten <__peter__ at web.de> (PO) wrote: >PO> Piet van Oostrum wrote: >>>>>>>> "Gabriel Genellina" (GG) wrote: >>> >GG> "Given this indispensable process and architecture issue, isn't it >>>> obvious GG> that it's totally irrelevant to the system's overall safety >>>> whether the GG> compiler has performed the further smattering of >>>> semantically puny GG> 'verifications' allowed by mandatory-declaration, >>>> stating-typing GG> languages?" - Alex Martelli >>> >>> I couldn't find the original of this. I would like to see it in its >>> context. Googling didn't reveal anything but this Python-URL. >PO> My google is better than yours then: >PO> http://mail.python.org/pipermail/python-list/2003-March/193864.html Thanks. I probably have searched for "mandatory-declaration, static-typing languages" instead of "mandatory-declaration, stating-typing languages" -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From missxxy78 at gmail.com Sat Mar 15 06:50:47 2008 From: missxxy78 at gmail.com (MSmith) Date: Sat, 15 Mar 2008 03:50:47 -0700 (PDT) Subject: I found affordable health insurance. Message-ID: I couldn't believe it. Do yourself a favour and at least check it out: http://www.jdoqocy.com/click-2924912-10359791 Michael From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 00:28:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 04:28:19 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13utucbj9mkrpd4@corp.supernews.com> Message-ID: <13uu5n326bfvr86@corp.supernews.com> On Sun, 30 Mar 2008 00:27:45 -0300, Gabriel Genellina wrote: > En Sat, 29 Mar 2008 23:23:07 -0300, Steven D'Aprano > escribi?: > >> The general problem is that I wish to time an arbitrary function with >> arbitrary arguments. The function and arguments are provided to me as >> Python objects, but timeit requires strings. Converting the objects to >> strings is not practical, and the objects might not exist in the >> __main__ module. > > Ah, ok, I understand now. I think this is more-or-less what you want: [snip] No, sorry, it's still sharing state. from timeit import Timer # Slight modification to the function to return the Timer object. def timeanyfunc(fn, *args, **kw): global wrapped_fn def wrapped_fn(): return fn(*args, **kw) return Timer("wrapped_fn()", "from %s import wrapped_fn" % __name__) def functionA(): print "Function A" def functionB(): print "Function B" T1 = timeanyfunc(functionA) T2 = timeanyfunc(functionB) T1.repeat(3, 1) # Should print "Function A". T2.repeat(3, 1) # Should print "Function B". -- Steven From jeff at schwabcenter.com Mon Mar 17 11:33:48 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 08:33:48 -0700 Subject: python-list Metaquestion In-Reply-To: References: Message-ID: Tom Stambaugh wrote: > I continue to receive emails, addressed to python-list-bounces at python.org, > with subject: "Re: Your message to Python-list awaits moderator approval", > which read: > >> Your mail to 'Python-list' with the subject >> >> (no subject) >> >> Is being held until the list moderator can review it for approval. >> >> The reason it is being held: >> >> Message has a suspicious header > > I'm happy to adjust my headers in whatever way is needed, if I know what the > problem is. Is there FAQ somewhere that tells me what I should change? Contact the list administrator and ask whether their spam filters are starting to turn green. http://www.python.org/cgi-bin/faqw-mm.py?req=show&file=faq03.059.htp From martin at v.loewis.de Mon Mar 3 17:48:31 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 Mar 2008 23:48:31 +0100 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> <47CB9F3C.9030202@v.loewis.de> Message-ID: <47CC803F.4090109@v.loewis.de> > Can you also add a note to the 2.3 and 2.4 web pages? You mean the 2.3.7 and 2.4.5 web pages? Sure. (If you mean some other web pages, please give precise URLs). Regards, Martin From tjreedy at udel.edu Sun Mar 9 22:14:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Mar 2008 22:14:26 -0400 Subject: any chance regular expressions are cached? References: Message-ID: wrote in message news:bu%Aj.5528$fX7.893 at nlpi061.nbdc.sbc.com... | I've got a bit of code in a function like this: | | s=re.sub(r'\n','\n'+spaces,s) | s=re.sub(r'^',spaces,s) | s=re.sub(r' *\n','\n',s) | s=re.sub(r' *$','',s) | s=re.sub(r'\n*$','',s) | | Is there any chance that these will be cached somewhere, and save | me the trouble of having to declare some global re's if I don't | want to have them recompiled on each function invocation? The last time I looked, several versions ago, re did cache. Don't know if still true. Not part of spec, I don't think. tjr From dblubaugh at belcan.com Thu Mar 20 15:46:23 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 20 Mar 2008 15:46:23 -0400 Subject: Floating-point support Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3802D19F9A@AWMAIL04.belcan.com> Would anyone know as to how to develop floating point support for the MyHDL module? Has anyone worked with any alternative versions of the IEEE standard for floating -point? Also, has anyone developed a floating-point library for a module within the python environment in order to execute numerical computations. I would imagine since I am translating python to verilog by using MyHDL , that I will have to develop the floating-point support module in python source code as well ?? If I can develop this one feature from MyHDL, it would allow this module to be fairly competitive with commercial products. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Sun Mar 16 02:21:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Mar 2008 06:21:45 GMT Subject: Unicode/UTF-8 confusion References: Message-ID: <643sjpF27mbs3U2@mid.uni-berlin.de> On Sat, 15 Mar 2008 16:33:24 -0400, Tom Stambaugh wrote: > I use a trick to let me pass the information into my browser client > application. The browser requests the server information from a form whose > target is a hidden iframe. The string the server serializes is wrapped in > html that embeds it in an onload handler like this: > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > http-equiv="content-type" content="text/html; charset=UTF-8" /> > > > > > > > [?] > > In order to successfully pass the escapes to the server, I already have to > double any each backslash. At the end of the day, it's easier -- and results > in better performance -- to convert each apostrophe to its unicode > equivalent, as I originally asked. > > I just want to know if there's a faster way to persuade simplejson to > accomplish the feat. So you don't ask for JSON encoded objects but JSON encoded *and* HTML/JavaScript embeddable escaped literal string. That's simply not the job of a JSON encoder. That's another level of encoding/escaping producing something that is not JSON anymore, so why do you want to ask a JSON encoder to deliver it? This is a feature/function you should find in a HTML templating library. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Mon Mar 3 19:21:52 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Mar 2008 18:21:52 -0600 Subject: sympy: what's wrong with this picture? In-Reply-To: <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 4:08 pm, Robert Kern wrote: >> Mensanator wrote: >>> On Mar 3, 2:49 pm, Carl Banks wrote: >>>> It's just a bug--probably sympy is messing with the internals of the >>>> random number generator. It would be a simple fix. Instead of >>>> b****ing about it, file a bug report. >>> I did. >>>> Or better yet, submit a patch. >>> I would if I knew what the problem was. >> Did you even try to figure it out? It took me all of 5 minutes to find the mistake. > > Could I trouble you to share? Then I could continue my testing. I posted the patch on the bug tracker: http://code.google.com/p/sympy/issues/detail?id=729 >>> I posted it here because someone recommended it. >>> I'm simply un-recommending it. >> It was a mistake, an easily remedied mistake, > > But I didn't know that (and still don't). > >> not a big unchangeable design decision. > > I didn't know that either. For all I know, I might have to > wait for the next version, and who knows when that will be? The point is that you didn't try to figure it out. And you assumed the worst rather than giving anyone the benefit of the doubt. You didn't even wait to get a response from the package maintainer about how serious the issue was before you came here to un-recommend it. All software has bugs. Good software has bugs. Finding a single bug in a package is not sufficient cause to warn people away as if it had the plague. >> If you want to recommend against sympy as a package, there is a larger >> burden of proof that you have yet to meet. > > What kind of burden of proof must one have to recommend it in the > first place? Significantly less. "It was useful to me," is sufficient. -- 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 jgardner at jonathangardner.net Thu Mar 20 10:31:43 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 20 Mar 2008 07:31:43 -0700 (PDT) Subject: eval and unicode References: Message-ID: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> On Mar 20, 5:20?am, Laszlo Nagy wrote: > How can I specify encoding for the built-in eval function? Here is the > documentation: > > http://docs.python.org/lib/built-in-funcs.html > > It tells that the "expression" parameter is a string. But tells nothing > about the encoding. Same is true for: execfile, eval and compile. > > The basic problem: > > - expressions need to be evaluated by a program > - expressions are managed through a web based interface. The browser > supports UTF-8, the database also supports UTF-8. The user needs to be > able to enter string expressions in different languages, and store them > in the database > - expressions are for filtering emails, and the emails can contain any > character in any encoding > > I tried to use eval with/without unicode strings and it worked. Example: > > ?>>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? > ?????? ????????? ???????"' ) > True > > The above test was made on Unbuntu Linux and gnome-terminal. > gnome-terminal does support unicode. What would happen under Windows? > > I'm also confused how it is related to PEP 0263. I always get a warning > when I try to enter '"????????? ????????? ???????"' in a source > file without "# -*- coding: " specified. Why is it not the same for > eval? Why it is not raising an exception (or why the encoding does not > need to be specified?) > Encoding information is only useful when you are converting between bytes and unicode data. If you already have unicode data, you don't need to do any more work to get unicode data. Since a file can be in any encoding, it isn't apparent how to decode the bytes seen in that file and turn them into unicode data. That's why you need the # -*- coding magic to tell the python interpreter that the bytes it will see in the file are encoded in a specific way. Until we have a universal way to accurately find the encoding of every file in an OS, we will need that magic. Who knows? Maybe one day there will be a common file attribute system and one of the universal attributes will be the encoding of the file. But for now, we are stuck with ancient Unix and DOS conventions. When you feed your unicode data into eval(), it doesn't have any encoding or decoding work to do. From newsgroup898sfie at 8439.e4ward.com Mon Mar 3 21:57:59 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Mon, 03 Mar 2008 21:57:59 -0500 Subject: 'normal' shell with curses Message-ID: <633s5lF24prinU1@mid.uni-berlin.de> Hi, I'm trying to print out text in color. As far as I know, curses is the only way to do that (or not?). So, what I ultimately want is a curses terminal that behaves as closely as possible as a normal terminal, i.e. it breaks lines and scrolls automatically, so that I can implement a function myprint(color, text) that does what print() does, only in color. So, my first tests brought up some problems: #!/usr/bin/python from time import sleep import curses import sys stdscr = curses.initscr() stdscr.addstr("Initialized\n") stdscr.refresh() (maxlines, maxcolumns) = stdscr.getmaxyx() try: for counter in xrange(24): stdscr.addstr("Hello world %s\n" % counter) stdscr.refresh() if counter >= maxlines: stdscr.scroll() stdscr.refresh() except Exception, data: sys.stderr.write("Exception: \n"); sys.stderr.write(str(data)); finally: sleep(5) curses.endwin() Instead of scrolling, the program throws an exception. Any hints? Also, is there a way leave the curses output on the screen after curses.endwin(), instead of returning to the normal terminal without a trace of curses. Thanks, Michael From software at ginstrom.com Wed Mar 5 20:51:58 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Thu, 6 Mar 2008 10:51:58 +0900 Subject: Unit testing Web applications In-Reply-To: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> References: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> Message-ID: <0c1401c87f2c$aa179560$0203a8c0@MOUSE> > On Behalf Of Monica Leko > Does Python has some testing frameworks for testing Web > applications (like Cactus and HttpUnit for Java), generating > requests and checking if the response is correct? I have got a lot of traction using mechanize [1] with nose [2]. Of course that still leaves out testing JavaScript. For that, something like PAMIE [3] is one way to go. [1] http://wwwsearch.sourceforge.net/mechanize/ [2] http://somethingaboutorange.com/mrl/projects/nose/ [3] http://pamie.sourceforge.net/ Here's an example of how I use mechanize + nose: # test_index.py from mechanize import Browser class TestPageLoads: def setup(self): self.mech = Browser() self.mech.set_handle_robots(False) # use thought and consideration... def test_nonexistent(self): try: response = self.mech.open("http://honyaku-archive.org/nonexistent/") assert False, "Should have thrown here" except Exception, e: assert "404" in str(e), e def test_index(self): response = self.mech.open("http://honyaku-archive.org/") assert response.code == 200, response.code def test_index_title(self): response = self.mech.open("http://honyaku-archive.org/") assert self.mech.title().strip() == "Honyaku Archive :: Home", self.mech.title() Regards, Ryan Ginstrom From sam at ausdia.com Tue Mar 11 00:35:02 2008 From: sam at ausdia.com (samsappleton) Date: Tue, 11 Mar 2008 04:35:02 -0000 Subject: python "import" of statically linked module with SWIG Message-ID: Hi I compiled a SWIG wrapper & linked it with a main program in C (i'm extending the main program/C with a python interpreter). How can I "import" the swig wrapper module in Python? If I just use "import ", of course I get ImportError: no module named XXXX I don't want to expose any .so files if possible i.e. not dynamically linked. Sam From dave_mikesell at fastmail.fm Sun Mar 16 10:49:01 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sun, 16 Mar 2008 07:49:01 -0700 (PDT) Subject: Python and 3D References: Message-ID: <8b29c32b-da7c-4254-9ecc-cfeefc9c26b2@b64g2000hsa.googlegroups.com> On Mar 15, 3:09 pm, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs This is more of a question about Alias than Python. I googled it and found Autodesk's AliasStudio (which apparently used to be Alias Wavefront) - is this what you're talking about? There is a C++ API, which could be wrapped in Python using something like SWIG. From castironpi at gmail.com Sun Mar 30 01:37:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 22:37:07 -0700 (PDT) Subject: Help me on function definition References: <4c1c2834-2ecb-46b6-a4ee-eb29d23cbf1a@a1g2000hsb.googlegroups.com> Message-ID: On Mar 29, 11:45?pm, hdante wrote: > On Mar 28, 10:47 pm, "aeneng" wrote: > > > Hello everyone, > > ?Hi, > > ?Always avoid reinventing the wheel: > > from Numeric import array, cross_product > a = array([1, 2, 3]) > b = array([4, 5, 6]) > print cross_product(a, b) > > ?See: > ?http://numpy.scipy.org/ > ?http://www.scipy.org/ > > ?(hint: consider that many people want to multiply matrices) :-) > > > > > > > I am just starting to use python in numerical cacluation. > > I need you to help me to see what's wrong with the following piece of > > codes, which computes the cross product of two vectors and returns > > the result. u and v are two 3x1 matrix. > > > when I import the function, error message show like this>>> import cross > > > Traceback (most recent call last): > > ? File "", line 1, in ? > > ? File "cross.py", line 8 > > ? ? ppp2=u[2]*v[0]-u[0]*v[2] > > ? ? ^ > > SyntaxError: invalid syntax > > > WHAT IS WRONG WITH MY CODE? > > > I appreciate your help. > > > ##here is the function definition. > > ##cross.py## > > def cross(u,v) > > ? ? """input two vectors u and v in 3-D space, > > ? ? ? ?output a cross product of vector w, in column or in row > > accordingly.""" > > ? ? ppp1,ppp2,ppp3=0.0,0.0,0.0 > > ? ? ppp1=u[1]*v[2]-u[2]*v[1] > > ? ? ppp2=u[2]*v[0]-u[0]*v[2] > > ? ? ppp3=u[0]*v[1]-u[1]*v[0] > > ? ? # store the result of the cross product in u > > ? ? u[0]=ppp1 > > ? ? u[1]=ppp2 > > ? ? u[2]=ppp3 > > ? ? return u #return the cross product of vector u x v. > > if __name__=="__main__": > > ? ? ? ? from cvxopt.base import matrix > > ? ? ? ? u=matrix([1.0,0.0,0.0],(3,1)) > > ? ? ? ? v=matrix([0.0,1.0,0.0],(3,1)) > > ? ? ? ? print cross(u,v) > > ? ? ? ? print "file name is %s" %__name__- Hide quoted text - Bandwidth is really low; offload logic. I'd run some AI for the games so you can get a couple more triangles... plot.thicken() From vedrandekovic at gmail.com Sat Mar 29 08:23:58 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Sat, 29 Mar 2008 05:23:58 -0700 (PDT) Subject: Create executable from executable with py2exe Message-ID: Hello, Is there any example how can I create executable from executable with py2exe.For example if I create main executable with some TextEntry ( wxpython ) and then when i write this code into this entry: import os print os.getcwd() print "ok" ...to main executable convert this code into executable with py2exe. Sorry for my english! Regards, Vedran From haag at lsu.edu Sun Mar 16 17:11:06 2008 From: haag at lsu.edu (Alaric Haag) Date: Sun, 16 Mar 2008 16:11:06 -0500 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: In article <5bd37c10-af5d-4254-8799-49c762673a3e at n58g2000hsf.googlegroups.com>, Bruce Eckel wrote: > If the following seems unnecessarily harsh, it was even more harsh for ..... As a relative noob to the Python world, (and lurker to the list :) ) I can't speak to differences from previous years. However, my impressions as a first-timer are much in alignment with you Bruce. Many lightening talk seemed to me to be more about recruiting than selling though. Whereas I might have been discovering a vendor for the first time in a lightening talk, it wasn't a particularly good use of my time here. I'll FIND the commercial vendor, because, if they have a good product, word will get around, aided by their web presence, and formidable advertising budget. On the other hand, bleeding edge use of Python in a lab on a distant continent (just for example) is going to be much harder to both discover, much less get the added bonus of face-to-face time with the developer! That said, I thank the organizers, and welcome the new friendships made at this event, and hope like hell I can come next year!! Alaric From dave_mikesell at fastmail.fm Mon Mar 10 18:28:50 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Mon, 10 Mar 2008 15:28:50 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: On Mar 10, 2:21 pm, Bob Martin wrote: > > Java is more portable than most other languages, especially if your app needs a gui. The promise of Java portability was one of the biggest scams ever perpetrated on the software industry. There are issues going from OS to OS, VM to VM, DB to DB, app server to app server, etc. Certainly no easier than porting C++ and the appropriate libraries, IMHO. From sjdevnull at yahoo.com Mon Mar 17 15:51:14 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 17 Mar 2008 12:51:14 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> Message-ID: <8ca43caa-5a2c-4b7b-b168-aad4cfb0581a@a23g2000hsc.googlegroups.com> On Mar 17, 12:15 pm, rockingred wrote: > On Mar 10, 11:30 am, "sjdevn... at yahoo.com" > wrote: > > > Fix that. That's usually something that's fairly easy to get done as > > a programmer (I've had to do it at 2 of the last 4 places I worked). > > Just go explain all the problems that can happen by not having VC and > > all the benefits it brings to your managers, and that there's a good > > free VC system that will work for everyone, and it'll likely become a > > mandate pretty quickly. > > > It's almost certainly worth fixing that problem rather than mucking > > around with half-solutions. > > Unfortunately, no free VC system existed for the language in which I > was programming Explain? VC isn't language-specific. From trentm at activestate.com Thu Mar 6 16:49:00 2008 From: trentm at activestate.com (Trent Mick) Date: Thu, 06 Mar 2008 13:49:00 -0800 Subject: system32 directory In-Reply-To: <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: <47D066CC.6080503@activestate.com> > I was aiming to figure out if the standard modules shipped with Python > could do this already before I started using 3rd party libraries. Thanks. You could also manage it with the ctypes module, if you consider that standard: it is in the python.org and ActivePython distros as of Python 2.5. Cheers, Trent -- Trent Mick trentm at activestate.com From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:16:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:16:45 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <13t3c5t4hau9075@corp.supernews.com> On Fri, 07 Mar 2008 11:58:38 -0500, D'Arcy J.M. Cain wrote: >> 2. You should use two spaces after a >> sentence-ending period. >> >> For heavens sake, why? I've always been obstructed by the double blanks >> but >> tolerated them. Now, that i read that it actually is a recommendation, >> i need to ask about the purpose. > > Like many things of this nature, the purpose is to follow the rules of > correct English usage. Except English grammar does not and never has specified using two spaces after a period. The (bad) habit of doing so was introduced by typists, in the old days of manual typewriters, in the belief (completely bogus, in my opinion) that a larger gap between sentences would make them more readable. I believe that the larger gap is a distraction, one of the reasons that typewriter text is generally harder to read than properly typeset text. I believe it is one of those things that everybody (for some value of "everybody") does because that's what they were taught to do, and they were taught to do it because that's what their teachers were taught, and so on all the way back to some nutter who just decided that *he* was going to use two spaces after a period because the Great and Mighty Pumpkin told him to. Professional typesetters, using proportional fonts, don't use double- spaces because it throws off word spacing and line justification and just plain looks ugly. I suppose that since coders typically use non- proportional fonts, we can at least justify the use of two spaces with a claim that it aids readability for "typewriter fonts" -- if you believe such a thing, which I do not. -- Steven From petr.jakes.tpc at gmail.com Thu Mar 6 15:07:21 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Thu, 6 Mar 2008 12:07:21 -0800 (PST) Subject: Data aggregation References: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> <47d039a6$0$36391$742ec2ed@news.sonic.net> Message-ID: On Mar 6, 7:44 pm, John Nagle wrote: > vedranp wrote: > > I would like to avoid the step of taking data out from database in > > order to process it. > > You can probably do this entirely within SQL. Most SQL databases, > including MySQL, will let you put the result of a SELECT into a new > table. > > John Nagle I agree, maybe following can help http://tinyurl.com/32colp Petr Jakes From castironpi at gmail.com Mon Mar 3 20:12:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 17:12:43 -0800 (PST) Subject: metaclasses Message-ID: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> What are metaclasses? From santhosh.cnp at gmail.com Sun Mar 16 01:14:43 2008 From: santhosh.cnp at gmail.com (santhosh kumar) Date: Sun, 16 Mar 2008 10:44:43 +0530 Subject: Regular Expression Help Message-ID: <957ae7d80803152214se4b3012xaef709afed4f1f52@mail.gmail.com> Hi all, I have text like , STRINGTABLE BEGIN ID_NEXT_PANE "Cambiar a la siguiente secci?n de laventana \nSiguiente secci?n" ID_PREV_PANE "Regresar a la secci?n anterior de laventana\nSecci?n anterior" END STRINGTABLE BEGIN ID_VIEW_TOOLBAR "Mostrar u ocultar la barra de herramientas\nMostrar/Ocultar la barra de herramientas" ID_VIEW_STATUS_BAR "Mostrar u ocultar la barra de estado\nMostrar/Ocultar la barra de estado" END ................................ .................................... .......................................... and i need to parse from STRINGTABLE to END as a list object. whatkind of regular expression should i write. -- Regards, Santhoshkumar.S -------------- next part -------------- An HTML attachment was scrubbed... URL: From wtanksleyjr at gmail.com Mon Mar 31 13:03:30 2008 From: wtanksleyjr at gmail.com (william tanksley) Date: Mon, 31 Mar 2008 10:03:30 -0700 (PDT) Subject: How to get an XML DOM while offline? References: <64cpnvF2at1j9U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > The most pragmatic solution would be to rip the doctype out using simple > string methods and/or regexes. Thank you, Diez and Paul; I took Diez's solution, and it works well enough for me. > Diez -Wm From castironpi at gmail.com Sun Mar 30 01:43:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 22:43:05 -0700 (PDT) Subject: Serial port error statistics - any comparable data? References: <657qh1F2es9vnU1@mid.uni-berlin.de> Message-ID: <5da93cbc-0e6f-420b-a7da-eb64c89ba534@x41g2000hsb.googlegroups.com> On Mar 29, 4:26?pm, "Diez B. Roggisch" wrote: > Hendrik van Rooyen schrieb: > > > > > > > Hi, > > > I have been doing some tests on a device that > > we are thinking of incorporating into a product, > > and I have seen that reception on a serial port > > at 115200 baud over about six metres of RS-232 > > cable makes mistakes, to the order of 125 lines > > with errors in them out of approximately 18.4 > > million lines of 65 or so chars - about one errored > > line in 147000, or one error character in 95 million. > > > The PC that is making the errors is a 64 bit dual > > core AMD machine running at 2 Gig, and I am > > running stock standard Open Suse 10.3 with > > the supplied Python 2.5. > > > What kind of bothers me is the nature of the errors - > > I seem to get only missing characters, as if an > > interrupt was missed. ?There are no munged characters > > as one would expect if the errors were bit related. > > > Has anyone else seen anything like this, and am I worrying > > needlessly? > > > I realise that my production protocols will easily handle > > this almost non existent level of error - but if this were in > > microcontroller code that I had written myself, I would > > suspect that I was spending too long in some critical > > section of code. > > RS232 is unfortunately as bad as a "protocol" as it can get. I've used > it for communication with a microcontroller for just a few bytes every > second. And it failed miserably, so I needed to implement a protocol on > top of it. > > The machine spec is totally irrelevant - what is interesting is the > serial hardware you use. Are you by any chance using a > serial2usb-converter? I had nothing but troubles with these. > > if you have the chance, try & attach a machine with legacy rs232 port, > and see if the errors still remain. Transmit observed minus expected to cluster. What kind of tables does the input device build? From chickenpotatoe at hotmail.com Sun Mar 30 00:38:32 2008 From: chickenpotatoe at hotmail.com (chickenpotatoe at hotmail.com) Date: Sat, 29 Mar 2008 21:38:32 -0700 (PDT) Subject: Redacted References: Message-ID: <39555677-50ca-4336-b864-8b06eae1566e@i29g2000prf.googlegroups.com> Redacted From mail at timgolden.me.uk Sun Mar 16 02:44:20 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 06:44:20 +0000 Subject: Spaces in path name In-Reply-To: References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> Message-ID: <47DCC1C4.2010806@timgolden.me.uk> joep wrote: > On Mar 15, 5:42 pm, joep wrote: >>> http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... >> Note: this works for subprocess.call but for subprocess.Popen this >> does not work if there are two arguments in the command line with >> spaces. Especially, even after trying out many different versions, I >> never managed to get subprocess.Popen to work, when both the >> executable and one argument have spaces in the file path. >> > > Sorry, incomplete sentence > > Especially, even after trying out many different versions, I never > managed to get subprocess.Popen to work '''when command line is given > as a *list* argument to subprocess.Popen''' > in the case when both the executable and one argument have spaces in > the file path. Thanks for the info. I'll get on the case and put some examples together with caveats. TJG From bj_666 at gmx.net Mon Mar 17 03:29:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Mar 2008 07:29:56 GMT Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? References: Message-ID: <646kvkF2ao2tkU2@mid.uni-berlin.de> On Sun, 16 Mar 2008 14:21:40 +0100, martin f krafft wrote: > Hi, > > xmlrpclib.dumps((None,), allow_none=True) yields > > '\n\n\n\n' > > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' > > Those are valid XML and valid XML-RPC, but isn't. In XML-RPC there is no `None`, so there's the non standard `allow_none` Option to allow `None` to be represented as ````. And is an empty or really valid XML-RPC? Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Fri Mar 14 18:20:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 15:20:59 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: On Mar 14, 5:16?pm, Roel Schroeven wrote: > castiro... at gmail.com schreef: > > > On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: > >>> Subject: RIP: Joseph Weizenbaum > >>> Creator of Eliza: > >>>http://www-tech.mit.edu/V128/N12/weizenbaum.html > >>> -- > >> How do you feel about creator of Eliza? > > > What is Eliza? > > Does that question interest you? He had a dream about a pillow. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 26 08:18:07 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Mar 2008 13:18:07 +0100 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: <47ea3ef9$0$26861$426a74cc@news.free.fr> sam a ?crit : > Bruno Desthuilliers napisa?(a): > >>> In dynamically typed language when you create object A that is >>> inherited from another object B, than object A knows that B is his >>> predecessor. So >>> when you reference A.prop, then prop is looked in A first, then in B, >>> then in predecessors of B, and so on. >> >> What you're describing here is the inheritance mechanism of Python. >> And could apply just as well to javascript prototype mechanism. A >> javascript object has a reference to it's prototype object - that you >> can customize, rebind etc -, a Python object has a reference to it's >> class object - that you can customise, rebind etc... > > I can see that Python and Javascript inheritance model is almost the > same. Both languages are dynamically typed. And it seems that using > "classes" in Python makes some things more complicated then it is > necessary I have to disagree here. > (eg functions, methods and lambdas are differen beeing in > Python concept). The lambda statement creates an ordinary function object, so no difference here - and it has nothing to do with classes vs prototypes. wrt/ functions and methods, what you declare with a def statement within a class statement is actually a plain function (and FWIW, you can add dynamically add methods to classes or instances). Python 'methods' are only thin callable wrappers around the function/class/instance set, wrappers that are dynamically generated by the function object itself when it's looked up on a class or instance, thanks to the descriptor protocol. > > >> Don't be fooled by the term "class" itself - it's meaning is totally >> different in a language like Python. > > Probably I'm not alone. Many people who think dymanic types are Rhight > Thing in programming will also prefer prototype-based programming to > class-based. Chapter and verse, please ? Ok, I repeat (please read more carefully): """ Don't be fooled by the term "class" itself - it's meaning is totally different in a language like Python. """ > >> suspect you don't have a serious knowledge of Python's object model. > > Yes -- I'm new to Python. So may I suggest you actually *learn* how Python's object model works ? From clodoaldo.pinto at gmail.com Tue Mar 25 09:39:57 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Tue, 25 Mar 2008 06:39:57 -0700 (PDT) Subject: sendmail should throw an exception but does not Message-ID: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> I need to know if an email was refused for whatever reason, it makes no difference. The email is sent to an email address that does not exist in a foreign domain. I can see in the postfix log that the email was sent and bounced with the error code 550. The problem is that sendmail should throw an exception but it does not. And the returned dictionary is empty as if the email was accepted. d = smtpserver.sendmail(sender, recipient, m.as_string()) I guess that the error code returned by the destination mail server is not is not forwarded to the client by my mail server. Regards, Clodoaldo Pinto Neto From bj_666 at gmx.net Sun Mar 2 16:48:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Mar 2008 21:48:52 GMT Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: <630lm2F25g4d2U1@mid.uni-berlin.de> On Sun, 02 Mar 2008 21:58:31 +0100, Christoph Zwerschke wrote: > Marc 'BlackJack' Rintsch schrieb: >> On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: >> >>> Apart from doing something like >>> a=[0,0,0] >>> b=[0,0,0] >>> c=[0,0,0] >>> d=[a,b,c] >>> >>> is there a better way of creating d?? >> >> a = [[0] * 3 for dummy in xrange(3)] > > Why not simply [[0]*3]*3 ? Because: In [77]: a = [[0] * 3] * 3 In [78]: a Out[78]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] In [79]: a[0][0] = 42 In [80]: a Out[80]: [[42, 0, 0], [42, 0, 0], [42, 0, 0]] Ciao, Marc 'BlackJack' Rintsch From andrei.avk at gmail.com Thu Mar 13 22:55:27 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Thu, 13 Mar 2008 19:55:27 -0700 (PDT) Subject: escape string to store in a database? References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> Message-ID: <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> On Mar 12, 8:32?pm, Carsten Haese wrote: > On Wed, 2008-03-12 at 18:18 -0700, andrei.... at gmail.com wrote: > > These pieces of text may have single and double quotes in > > them, I tried escaping them using re module and string module and > > either I did something wrong, or they escape either single quotes or > > double quotes, not both of these. So that when I insert that text into > > a db record, this causes an error from the database. What's the > > accepted way of dealing with this? > > The accepted way of dealing with this is to use parameter binding: > > conn = somedbmodule.connect(...) > cur = conn.cursor() > cur.execute("insert into sometable(textcolumn) values (?)", > ? ? ? ? ? ? (stringvar,) ) > > (Note that the question mark may have to be replaced with %s depending > on which database module you're using.) > > For background information on parameter binding see, for example,http://informixdb.blogspot.com/2007/07/filling-in-blanks.html. > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks for the reply, Carsten, how would this work with UPDATE command? I get this error: cmd = "UPDATE items SET content = ? WHERE id=%d" % id self.cursor.execute(cmd, content) pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. The c rrent statement uses 1, and there are 0 supplied. Sqlite site doesn't give any details on using parameter bindings in UPDATE command, I'm going to look around some more.. -ak From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 08:03:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Mar 2008 12:03:12 -0000 Subject: os.path.getsize() on Windows References: Message-ID: <13u2080sffjnnba@corp.supernews.com> On Tue, 18 Mar 2008 13:58:33 -0700, Sean DiZazzo wrote: > I'm seeing some behavior that is confusing me. I often use a simple > function to tell if a file is growing...ie being copied into a certain > location. (Can't process it until it's complete) Surely though, under Windows, while something else is writing to the file you can't open it? So instead of this: def wait_for_open(pathname): """Return file open for reading, or fail. If the file is busy, will wait forever. """ import time while isGrowing(path, 0.2): # defined elsewhere by you time.sleep(1) # wait a bit # now we HOPE we can read the file return open(path, 'r') # this can fail in many, many ways do this: def wait_for_open(pathname): """Return file open for reading, or fail. If the file is busy, will wait forever. """ import time, errno while True: try: return open(path, 'r') except IOError, e: if e.errno == errno.EBUSY: time.sleep(1) else: raise Note: I've made a guess that the error you get under Windows is errno.EBUSY. You'll need to check that for yourself. This whole approach assumes that Windows does the sensible thing of returning a unique error code when you try to open a file for reading that is already open for writing. -- Steven From pavlovevidence at gmail.com Mon Mar 31 14:31:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 31 Mar 2008 11:31:23 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: On Mar 31, 1:23 pm, xkenneth wrote: > So i generally write quite a few classes, and in most I need to > overload the == operator. > > If i have two classes, like below: > > Class A: > attribute a > attribute b > > Class B: > attribute a > attribute c > > So if I've overloaded their respective __eq__ functions, and I want to > test whether or not the individual classes attributes are equal, the > code might look something like this: > > class A: > def __eq__(self,other): > return self.a == other.a and self.b == other.b > > class B: > def __eq__(self,other): > return self.a == other.a and self.c == other.c > > Now obviously, if I test an instance of either class equal to each > other, an attribute error will be thrown, how do I handle this? I > could rewrite every __eq__ function and catch attribute errors, but > that's tedious, and seemingly unpythonic. Also, I don't want an > attribute error thrown whenever two classes are compared that don't > have the same attributes. What do you want to happen? What I'd suggest, without knowing more about your problem, is to define a method to return some kind of signature to compare instead. For instance, you could create a dict of the attributes you care about, and return that. The comparison class A(object): def comparison_signature(self): return { 'a': self.a, 'b': self.b } def __eq__(self,other): return self.comparison_signature() == other.comparison_signature() class B(object): def comparison_signature(self): return { 'a': self.a, 'c': self.c } def __eq__(self,other): return self.comparison_signature() == other.comparison_signature() This I suspect would handle your problem gracefully, assuming that objects of different types should be considered not equal and have a different set of attributes in the signature. For extra credit, you can factor the __eq__ method into a parent class and inherit the comparison in A and B. Carl Banks From aahz at pythoncraft.com Sat Mar 15 14:35:21 2008 From: aahz at pythoncraft.com (Aahz) Date: 15 Mar 2008 11:35:21 -0700 Subject: Joseph Weizenbaum References: Message-ID: In article , Jeff Schwab wrote: >Aahz wrote: >> In article , >> Tim Roberts wrote: >>> >>> I am embarrassed to say that this vaguely disrespectful exchange made me >>> laugh out loud. >> >> Serious: why do you think this is disrespectful? > >Not to speak for Tim, but I imagine it could be perceived as >disrespectful because Prof. Weizenbaum has only recently passed away. >In fact, I think the Prof would be very happy to see people having some >fun at the expense of AI, which he saw as a real threat to human freedom. Exactly. Also, humor is one traditional response to negative emotions; see all the various Gygax tributes that use humor. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From maxime.p at gmail.com Sat Mar 15 16:18:28 2008 From: maxime.p at gmail.com (Ulysse) Date: Sat, 15 Mar 2008 13:18:28 -0700 (PDT) Subject: Code to send RSS news by Sendmail Message-ID: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> Hello, I'm searching a code which allow you to parse each item in the RSS feed, get the news page of each item, convert it to text and send it by mail. Do you know if it exists ? Thanks From http Sun Mar 9 03:51:26 2008 From: http (Paul Rubin) Date: 08 Mar 2008 23:51:26 -0800 Subject: securely getting the user's password References: <01ec41b1-3ac2-4e5b-9050-646cc6a073f9@m34g2000hsc.googlegroups.com> <13t6p1o23so7oc2@corp.supernews.com> <8e1c4457-6313-4395-8483-22271d079c1d@2g2000hsn.googlegroups.com> Message-ID: <7x1w6kl4ht.fsf@ruckus.brouhaha.com> Chick writes: > So I guess it is not possible in pure Python to lock the memory from > being swaped? Even if you can lock the memory, python strings are immutable and can be copied around by the runtime system at any time. You're better off using the C API to encapsulate the password. If this is a high security application, consider using a hardware token of some kind instead. From kay.schluehr at gmx.net Thu Mar 20 08:40:45 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 20 Mar 2008 05:40:45 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <6f7ab390-2d37-4bcc-b88d-b82cb0ff05f9@m34g2000hsc.googlegroups.com> > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: > > Each module to be removed needs to have a justification as to why it > should no longer be distributed with Python. >From time to time someone makes a serious claim about ineptness of using significant whitespace on Windows servers because "My customer doesn't let me install a reasonable editor. So I'm forced me to use MS Notepad!". These poor guys can still use IDLE once they have a running Python installation. I'm definitely with you and batteries included. Note also that Tk which seemed to be comatose for a long time seems to recover and doesn't look that bad anyome: http://www.tcl.tk/software/tcltk/8.5.html http://wiki.tcl.tk/13636 From rpdooling at gmail.com Mon Mar 31 19:04:13 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Mon, 31 Mar 2008 16:04:13 -0700 (PDT) Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> Message-ID: <7b94bd75-f3ef-4e5c-9939-c431947e1ae1@l42g2000hsc.googlegroups.com> On Mar 31, 2:39 pm, hexusne... at gmail.com wrote: > How do I receive input from the command line in Python? As long as we are all guessing, do you perhaps mean raw_input? my_name = raw_input("What is your name? ") What is your name? Rick >>> my_name 'Rick' From egbert.bouwman at hccnet.nl Sat Mar 8 10:20:34 2008 From: egbert.bouwman at hccnet.nl (egbert) Date: Sat, 8 Mar 2008 16:20:34 +0100 Subject: for-else In-Reply-To: References: Message-ID: <20080308152034.GA12009@hccnet.nl> The idea of the if-else is: . depending on some condition either do this or do something else, . don't do them both. If you approach a loop-else with this same idea, you get: . depending on the loop conditions either do the loop, . or do something else, but not both. However the loop-else really works more like this: . try to do the loop; . if it starts but is interrupted by a break, . then do something else as well. So they are completely different beasts, and if you try to use or explain the one according to the rules of the other one, you put a serious strain on your synapses. The explanation that the if-else and the loop-else follow the same pattern, runs more or less like this: . all conditions to run the loop to its completion were met, . which means that the loop-condition is not met (any more), . which means that we must do something else. For me that is orwellian logic: success is failure. The loop-else mechanism is not an easy one: earlier in this thread Carl Banks turned it into an either/or construct by omitting the crucial break; Jeffrey Barish initially found the loop-else surprising; Sion Arrowsmith found it comprehensible only after some hard thinking (as in the last paragraph). The culprit is of course the keyword, else. The idea of an easy follow-up after a loop is a good one. But we need other keywords, I think at least three of them: . skipped - the loop did not run at all . broken - the loop was interrupted (by a break) . exhausted - the loop ran to completion. The last two as suggested by Laurence Tratt in his Convergence. e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From bockman at virgilio.it Tue Mar 25 05:38:47 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 25 Mar 2008 09:38:47 GMT Subject: Python 2.2.1 and select() References: Message-ID: <47e8c826$0$7736$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 17:58:42 -0400, Derek Martin ha scritto: > Hi kids! > > I've got some code that uses select.select() to capture all the output > of a subprocess (both stdout and stderr, see below). This code works as > expected on a variety of Fedora systems running Python > 2.4.0, but on a > Debian Sarge system running Python 2.2.1 it's a no-go. I'm thinking > this is a bug in that particular version of Python, but I'd like to have > confirmation if anyone can provide it. > > The behavior I see is this: the call to select() returns: [ corresponding to sub-proc's STDOUT>] [] [] > > If and only if the total amount of output is greater than the specified > buffer size, then reading on this file hangs indefinitely. For what it's > worth, the program whose output I need to capture with this generates > about 17k of output to STDERR, and about 1k of output to STDOUT, at > essentially random intervals. But I also ran it with a test shell > script that generates roughly the same amount of output to each file > object, alternating between STDOUT and STDERR, with the same results. > > Yes, I'm aware that this version of Python is quite old, but I don't > have a great deal of control over that (though if this is indeed a > python bug, as opposed to a problem with my implementation, it might > provide some leverage to get it upgraded)... Thanks in advance for any > help you can provide. The code in question (quite short) follows: > > def capture(cmd): > buffsize = 8192 > inlist = [] > inbuf = "" > errbuf = "" > > io = popen2.Popen3(cmd, True, buffsize) inlist.append(io.fromchild) > inlist.append(io.childerr) > while True: > ins, outs, excepts = select.select(inlist, [], []) for i in ins: > x = i.read() > if not x: > inlist.remove(i) > else: > if i == io.fromchild: > inbuf += x > if i == io.childerr: > errbuf += x > if not inlist: > break > if io.wait(): > raise FailedExitStatus, errbuf > return (inbuf, errbuf) > > If anyone would like, I could also provide a shell script and a main > program one could use to test this function... >From yor description, it would seem that two events occurs: - there are actual data to read, but in amount less than bufsize. - the subsequent read waits (for wathever reason) until a full buffer can be read, and therefore lock your program. Try specifying bufsize=1 or doing read(1). If my guess is correct, you should not see the problem. I'm not sure that either is a good solution for you, since both have performance issues. Anyway, I doubt that the python library does more than wrapping the system call, so if there is a bug it is probably in the software layers under python. Ciao ---- FB From 11456990 at qq.com Sun Mar 30 14:54:36 2008 From: 11456990 at qq.com (Aster Jian) Date: Mon, 31 Mar 2008 02:54:36 +0800 Subject: Py-Lib 0.9.1 released References: Message-ID: <021801c89297$808b02d0$6701a8c0@tencent2a9bde> great works, i will try it. Aster Jian. ----- Original Message ----- From: "Carl Friedrich Bolz" To: Sent: Monday, March 31, 2008 2:47 AM Subject: ANN: Py-Lib 0.9.1 released > py lib 0.9.1: bugfix release > ============================= > > The py lib team has just released version 0.9.1 of the py lib - a > library aiming to support agile and test-driven python development on > various levels. > > This is mostly a bugfix release, with a couple of new features sneaked in. > Most important changes: > > * reduced the number of threads used in py.execnet > * some new functionality (authentication, export, locking) in py.path's > Subversion APIs > * stability and segfault fixes in execnet > * numerous small fixes in py.test's rsession (experimental pluggable > session) > and generative test features > * some fixes in the py.test core > * added py.misc.killproc, which allows killing processes on (some > flavours of) Windows and UNIX > > For a complete list of changes, see doc/changes-0.9.1.txt in the source > package. > > Download/Install: http://codespeak.net/py/0.9.1/download.html > Documentation/API: http://codespeak.net/py/0.9.1/index.html > > Work on the py lib has been partially funded by the European Union IST > programme and by http://merlinux.de within the PyPy project. > > best, have fun and let us know what you think! > > holger krekel, Maciej Fijalkowski, > Carl Friedrich Bolz, Guido Wesdorp > > -- > From castironpi at gmail.com Sat Mar 8 12:52:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 09:52:41 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> <13t2cget4hubma9@corp.supernews.com> Message-ID: On Mar 7, 6:16?am, Steven D'Aprano wrote: > On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote: > > you > > could say exec( open( 'modA.py' ).read() ) ==> import modA > > Yes, you could say that, but you'd be wrong. Please test your code before > making such claims in the future. Aye aye. -1 response not phrased in the form of a question. Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA import * create "effectively" same results, such as in the remaning program not checking __module__ attributes? Is there a slight modification of both sides that does cover a non- trivial volume of programs, such as maybe, exec( open( 'modA.py' ).read(), locals= dict( __module__= 'modA' ) ) - and- from modA import *, or something? I notice that from toimp import * f() exec( open( 'toimp.py' ).read() ) f() generate the same output so far. From gygulyas at gmail.com Wed Mar 19 20:17:46 2008 From: gygulyas at gmail.com (Gyula) Date: Wed, 19 Mar 2008 17:17:46 -0700 (PDT) Subject: ADO error - large data set References: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> <9qgEj.4646$6H.3740@newssvr22.news.prodigy.net> Message-ID: Thanks! I will give it a try. It seems though that I get stuck on rs.Open that makes no sense. I was wondering about pagesize or other registry settings that might cause this? Will try to track down any bad data first... gg On Mar 19, 3:27 pm, "dsavitsk" wrote: > Is it possible there is some bad data in the larger db? This is asinine, but > maybe write a small script that adds some data, then opens and closes the > db, then repeats this. If this is a size issue, then you can at least narrow > it down to where the size limit is? And, if it isn't you should be able to > figure that out, too. Otherwise, play around with the locking and cursor > options. > > -d > > "Gyula" wrote in message > > news:475c155d-fe16-472f-a4f8-363f6db339eb at d21g2000prf.googlegroups.com... > > > Hi there, > > > I have been running Python to tap into an MS Access 2003 database > > using ADO (PythonWin+COM). Everything works great creating recordsets > > etc. when I open a table with a small number of records. However, when > > I try to run the same Python code with a large table (>100,000) I get: > > > Traceback (most recent call last): > > File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 310, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\Documents and Settings\user\Desktop\PythonWS\scripts > > \readmsaccess.py", line 43, in > > rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) > > File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- > > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open > > , ActiveConnection, CursorType, LockType, Options) > > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > > 5003251, -2147467259), None) > > > The small and large table structures are identical, all I do is change > > the tblname from input1000 (1000 records) to input (>100000 records). > > I use optimistic locking and keyset cursor..nothing out of the > > ordinary? > > > Any ideas? ADO 2.8 is what I am using. > > > Thanks a lot! > > GG From castironpi at gmail.com Sat Mar 8 04:06:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 01:06:41 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: <52786746-c7b1-48c3-8bdf-664d17859771@n77g2000hse.googlegroups.com> On Mar 7, 9:43?pm, George Sakkis wrote: > On Mar 7, 11:12 am, alex.pedwyso... at gmail.com wrote: > > > I have various bits of code I want to interpret and run at runtime in > > eval ... > > Check out these two recipes: > > - Using signals:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 > > - Using threads:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752 > > the second can't interrupt code that > doesn't release the GIL and doesn't actually kill the function after > the timeout. Mine doesn't either, plus you need a C compiler. I also learned today that one of the import statements doesn't find the dll on Py <3.0. Do you have a process kill ability? That's another way to do it. From grante at visi.com Wed Mar 26 16:45:47 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 26 Mar 2008 20:45:47 -0000 Subject: Daylight savings time problem References: Message-ID: <13uldfrl46tf728@corp.supernews.com> On 2008-03-26, Salsa wrote: > I'm sorry, but could you be more specific? How exactly should I use UTC? In my experience, using local time for timestamps is always a big mistake, so I presume he meant don't use local time in the file names -- put the UTC date/time in the filenames. If that's not an option, I'd try to figure out how to convert from whatever _is_ in the filename to UTC. -- Grant Edwards grante Yow! Half a mind is a at terrible thing to waste! visi.com From wolf_tracks at invalid.com Mon Mar 31 08:41:33 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 31 Mar 2008 05:41:33 -0700 Subject: Class Image.Image? In-Reply-To: <65buk3F2fi5osU1@mid.uni-berlin.de> References: <65buk3F2fi5osU1@mid.uni-berlin.de> Message-ID: Easy enough. 5Q+5Q. Diez B. Roggisch wrote: > W. Watson wrote: > >> I put a print statement in some Python code to determine the class >> (__class__) of a variable and the result was Image.Image. Why not just >> Image; otherwise, what's it telling me? > > Because it is the class Image in the module/package Image. > > Diez -- Wayne Watson (Nevada City, CA) Web Page: From deets at nospam.web.de Mon Mar 24 09:10:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Mar 2008 14:10:39 +0100 Subject: Installing Mutagen Package On Windows In-Reply-To: References: Message-ID: <64pnipF2crjipU1@mid.uni-berlin.de> Benjamin Serrato schrieb: > Hey, I've run into another problem. I am trying to install the Mutagen > package to use as my first useful program, but can't figure out how to > install it on windows. The README says it is a simple application of-- > > Installing > ---------- > $ ./setup.py build > $ su -c "./setup.py install" > > --but I ran c:\>python c:\python25\tools\scripts\setup.py build and did > similarly for setup.py. I also added c:\python25 and > c:\python25\tools\scripts to my path, but this hasn't worked. I have > heard of 'easy_install' but don't know how to run easy_install. So, I > ask for a reference because Google did not give me a quick answer and > the python.org explanation at PEP 250 doesn't really explain what I > should do. You need to call python2.5 setup.py install and google for setuptools, python, easy_install to find out all about it you need. Diez From __peter__ at web.de Tue Mar 4 09:15:15 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Mar 2008 15:15:15 +0100 Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: Steve Holden wrote: > What I will repeat, however, is that while there is a *slight* > difference is semantics between > > s = "some string" > s1 = s > > and > > s = "some string" > s1 = copy.copy(s) > > that difference is only to ensure that s and s1 point to different > copies of the same string in the latter case, whereas in the former case > s and s1 point to the same string. No, both "point" to the same string: >>> import copy >>> s = "some string" >>> s1 = s >>> s1 is s True >>> s2 = copy.copy(s) >>> s2 is s True copy.copy() is just an expensive no-op here. Peter From jules at js3d.co.uk Sun Mar 2 14:19:09 2008 From: jules at js3d.co.uk (Jules Stevenson) Date: Sun, 2 Mar 2008 19:19:09 -0000 Subject: Escaping a triple quoted string' newbie question In-Reply-To: References: <002801c87c3b$d6cd42b0$0301a8c0@laptop><004401c87c4f$e27b6f60$0301a8c0@laptop><004801c87c50$e83fc3a0$0301a8c0@laptop> Message-ID: <00bb01c87c9a$4a4ac100$0301a8c0@laptop> > > float $pos[]=particleShape1.worldPosition; > > > > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; > > > > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; > > > > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; > > """ > > dynExpression (p, s=expRuntime, rad=1) #generate the expression > > > > Then maya errors out, however if I pass maya an 'escaped' version: > > > > expRuntime=""" > > float $pos[]=particleShape1.worldPosition;\nsetAttr > > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr > > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr > > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """ > > > > Then all is well. My question is, is there any way to convert the first > > variable example to the second? It's a lot easier to type and on the > eye. > > Except for the doble-space on the first version, \n is the line separator > on both, so I'll ignore them. > """one > two""" > is the same thing as "one\ntwo" (even on Windows). The only remaining > difference that I see is " -> \" > > def mayaquote(text): > return text.replace('"', '\\"') > Thanks, this will work great. I was just wondering if there was an automatic 'string to escaped text' type function. Otherwise I'd have to build parsing for all chars that could cause a wobbly, but these may be few, so not too much of an issue. From tjreedy at udel.edu Sat Mar 8 21:19:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2008 21:19:56 -0500 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13t6gf5on1qnhbe at corp.supernews.com... | On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote: | | > On Mar 8, 6:26 pm, Paul Rubin wrote: | >> Alasdair writes: | >> > What is the best way of finding a ceiling of a quotient of arbitrary | >> > sized integers? | >> | >> ceiling(a/b) = (a+b-1)//b | > | > I prefer: | > | > ceiling(a/b) = -(-a)//b Obvious typo: -(-a)//b == a//b This should be -(-a//b) == -((-a)//b) | Unfortunately it doesn't give the right answer. | Looks like you've confused ceiling() and floor(). | | (And the ease that these mistakes can happen is why such fundamental | functions should be in the standard library, no matter how easy they are | to implement.) I'll let Paul say whether is was a typo, due to answering too quickly, or a logic error, but I suspect the former. *Any* expression can be mistyped. tjr From fakeaddress at nowhere.org Sun Mar 23 02:02:52 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Mar 2008 23:02:52 -0700 Subject: finding items that occur more than once in a list In-Reply-To: <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Bryan Olson wrote: >> We mean that the party supplying the keys deliberately chose >> them to make the hash table inefficient. In this thread the goal >> is efficiency; a party working toward an opposing goal is an >> adversary. > > There are situations where this can happen I guess Cormen-Leiserson-Rivest /Introduction to Algorithms/ discusses it in section 12.3.3 (first edition). They suggest a family of hash functions, where an individual hash is chosen at random when creating the table. That still doesn't beat adversaries who can get on-line timing information and figure out when they induce bad cases. More generally, security researchers have started to look at "algorithmic complexity denial of service attacks". http://www.cs.rice.edu/~scrosby/hash/ >> If you find real-world data sets that tend to induce bad-case >> behavior in Python's hash, please do tell. It would be reason >> enough to adjust the hash function. The hashes in popular >> software such as Python are already quite well vetted. > > As Python allows you to make your own hash functions for your own > classes, another danger is that you are dealing with objects with a > bad hash function. I've actually tried it (as I am *not* a pro!) and > FWIW here are the results. > > -------- badhash.py ---------- > > class BadHash(object): > def __hash__(self): > return 1 # that's a bad hash function! The sorting algorithm can have the same problem. With user-defined methods, there's no telling how long __cmp__ will actually take. -- --Bryan From deets at nospam.web.de Wed Mar 5 17:19:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Mar 2008 23:19:30 +0100 Subject: Dual look-up on keys? In-Reply-To: References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> Message-ID: <638kjmF26gr4fU1@mid.uni-berlin.de> castironpi at gmail.com schrieb: > On Mar 5, 3:38 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: >>> On Mar 5, 1:13 pm, "Diez B. Roggisch" wrote: >>>> castiro... at gmail.com schrieb: >>>>> I want to hash values to keys. How do the alternatives compare? >>>> http://catb.org/~esr/faqs/smart-questions.html >>> ... without extending the whole way to a full relational database? >> You didn't bother following the link and reading the advice, did you? If >> you did, you haven't done a good job of following that advice. > > Well, obviously there's someone who's interested in computers and > programming that has a question. Communication is not his forte, but > effort, willingness, devotion, and dedication are. What should he do, Effort, willingness & devotion? Certainly - but only to provoke, mislead and twaddle. You have recieved more than enough earnest efforts to be helped, and yet proven again and again that you aren't worth these very efforts. Luckily, this group is nice enough to not let your attitude poison it. *plonk* Diez From PurpleServerMonkey at gmail.com Mon Mar 31 07:32:15 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Mon, 31 Mar 2008 04:32:15 -0700 (PDT) Subject: distutils as an application installer? Message-ID: <8cfcad33-a6c2-4e30-b585-6ad57555b316@c19g2000prf.googlegroups.com> Was hoping someone could take a quick look at my distutils problem and give it a quick sanity check. Basically I have a server application (for Linux) that I want to install to /usr/local/, this location would have subdirectories for the daemon scripts, log files, plugins etc. After reading a bunch of distutils documentation it appears that the only good way out of this is to have my packages install to the system wide site-packages directory. Then using the data_files command in setup.py have it copy across an initial skeleton copy of the server directory and finally install the startup scripts. Does this sound correct, any other suggestions? The distutils documentation doesn't cover this scenario and I've spent days searching for information so any assistance is greatly appreciated. From roy at panix.com Sun Mar 23 22:36:35 2008 From: roy at panix.com (Roy Smith) Date: Sun, 23 Mar 2008 22:36:35 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 23 Mar 2008 13:51:34 -0400, Roy Smith wrote: > > > On the other hand, when I do: > > > > def torture(): > > woman.putInChair() > > cushion.poke() > > rack.turn() > > > > I've also done two things. First, I've created a function object (i.e. > > a lambda body), and I've also bound the name torture to that function > > object, in much the same way I did with the list. But, it's different. > > The function object KNOWS that it's name is torture. > > No it does not. Function objects don't know their name. All they know is > that they have a label attached to them that is useful to use as a name > in some contexts, e.g. when printing tracebacks. It's just a label, > nothing more. I think we're arguing the same thing. When you write def foo(): whatever you create an object which contains the string "foo", retrievable through its __name__ attribute. That's what I meant by "it knows its name" >> What Python give us with lambdas is some half-way thing. It's not a >> full function, so it's something that people use rarely, > > Which people? > > > which means most people (like me) can't remember the exact syntax. > > Speak for yourself, not for "most people". Well, OK. When I said, "most people", I really meant "I know about me, and I'm guessing about other people". I still think it's a fair statement that if you look any large collection of Python code, you will find many more uses of def than of lambda. > > Even when I know > > it's the right thing to be using in a situation, I tend not to use it > > simply because the path of least resistance is to write a one-off > > function vs. looking up the exact syntax for a lambda in the manual. > > lambda arguments : expression > > Why is that harder to remember than this? > > def name ( arguments ) : > block because I remember things I use often, better than I remember things I use infrequently. From andrei.avk at gmail.com Sat Mar 15 00:18:50 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Fri, 14 Mar 2008 21:18:50 -0700 (PDT) Subject: escape string to store in a database? References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> <13tk779c9tmjob8@corp.supernews.com> Message-ID: On Mar 14, 1:36?am, Dennis Lee Bieber wrote: > On Thu, 13 Mar 2008 19:55:27 -0700 (PDT), andrei.... at gmail.com declaimed > the following in comp.lang.python: > > > > > Thanks for the reply, Carsten, how would this work with UPDATE > > command? I get this error: > > > ? ? ? ? cmd = "UPDATE items SET content = ? WHERE id=%d" % id > > ? ? ? ? ? ? ? ? cmd = "update items set content = ? where id = ?" > > > ? ? self.cursor.execute(cmd, content) > > ? ? ? ? ? ? ? ? self.cursor.execute(cmd, (content, id)) > > would be the preferred method... Thanks very much - this works perfectly -ak > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From needin4mation at gmail.com Sat Mar 22 12:40:02 2008 From: needin4mation at gmail.com (jmDesktop) Date: Sat, 22 Mar 2008 09:40:02 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? Message-ID: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> For students 9th - 12th grade, with at least Algebra I. Do you think Python is a good first programming language for someone with zero programming experience? Using Linux and Python for first exposure to programming languages and principles. Thank you. From gagsl-py2 at yahoo.com.ar Thu Mar 6 14:46:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 17:46:04 -0200 Subject: Class context execution problems References: <1e5bcefd0803060504n5aa4970bh90092b57b0a106f0@mail.gmail.com> Message-ID: En Thu, 06 Mar 2008 11:04:26 -0200, Marcelo de Moraes Serpa escribi?: > I'm using a class in a conext other than the subpackage in which it is > located and I'm getting template lookup errors. > > This class expects to find a .pt file in a directory relative to its > package. However, this class is normally used by other classes in the > same > namespace. > > class ObjectWidget: > template = "templates/objectwidget.pt" > > However, I needed to import this class (ObjectWidget) from a class > outside > its namespace(package). Now, I think the class is running in the context > of > the file that is using it and so, the > the class not finding the .pt file (I think becouse the class file is > being > contextualized to the currently running one which is outside the browser > subpackage) No, it's not. The globals() (i.e., the "context") are of the imported module itself, not of the caller. The error probably lies on how that template attribute is converted into a full path; post that code. As an example, this is a rather safe way, even if the program uses os.chdir(): basepath = os.path.abspath(os.path.dirname(__file__)) class ObjectWidget: template = "templates/objectwidget.pt" def open(self): fn = os.path.join(basepath, template) print fn -- Gabriel Genellina From info at egenix.com Mon Mar 31 13:09:21 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 31 Mar 2008 19:09:21 +0200 Subject: ANN: eGenix MoinMoin action plugins for renaming and search&replace Message-ID: <47F11AC1.2080203@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com Action Plugins for MoinMoin This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/MoinMoin-Action-Plugins-1.0.html ________________________________________________________________________ eGenix and MoinMoin eGenix uses the MoinMoin wiki implementation internally as knowledge base and to document product development. Every now and then we need to do major search&replace on our wiki - e.g. due to a change in product name or to update an external URL. Instead of applying the changes manually, we created two new actions for MoinMoin to simplify this task. Both have proven to be very useful in day-to-day operation and therefore we are releasing them to the community under the GPLv2. "Rename Multiple Pages" Action, Version 1.0 -------------------------------------------- A plugin to quickly rename a whole set of pages in a MoinMoin wiki. "Search And Replace Multiple Pages" Action, Version 1.0 -------------------------------------------- This plugin can be used to quickly rename a whole set of pages in a MoinMoin wiki. eGenix MoinMoin Library ----------------------- Over time, we expect to release more useful MoinMoin plugins or patches. We'll be publishing them in our new MoinMoin Library. http://www.egenix.com/library/moinmoin/ ________________________________________________________________________ More Information Please see http://www.egenix.com/library/moinmoin/ for more information and downloads. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 31 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From craigm3604 at gmail.com Mon Mar 24 12:27:36 2008 From: craigm3604 at gmail.com (Craig) Date: Mon, 24 Mar 2008 09:27:36 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> Message-ID: <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> On Mar 23, 7:59 pm, Dennis Lee Bieber wrote: > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > > > This dll was designed to be used from either C or Visual Basic 6. > > > I have the declare statements for VB6, if that helps. > > Probably not that much -- I'd bet it's full of variant records > > > > > Based on the results I have so far (and I have tried MANY permutations > > like trying to use the LPSTR for SecKey and PriKey which are returned > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > instead of pointers. > > > For this, I try: > > LPSTR = c_char_p > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > LPSTR] > > SrchKey = > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > \x00", 41) > > SecKey = create_string_buffer(41) > > SecKey.raw = "1234567890123456789012345678901234567890" > > PriKey = > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > 41) > > TypeDef = create_string_buffer(128) > > TypeDef.raw = "X".center(128, "X") > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > and I get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 158, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > WindowsError: exception: access violation reading 0x3433322D > > > I notice that SecKey.raw starts with "1234" and the exception address > > is 0x3433322D, which is "432-". > > 0x2D is 4 less than the expected 0x31... > > > > > And, changing to: > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > LPSTR] > > PriKey = create_string_buffer(41) > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > I then get: > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 159, in > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > byref(c_void_p(S > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > WindowsError: exception: access violation reading 0x4443423D > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > is 0x4443423D, which is "DBC=". > > ... and 0x3D is 4 less than the expected 0x41 > > Which leads me to suspect that BSTR are a structure, not a plain > string, in which the address given is supposed to be prefaced with a > length value. IOWs, something like: > > |----|--------------------------------------| > ^ ^ C-string data > | |Address to be passed > |(address - 4) to get to a length count field > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > (the URL is from HTTP through to the end, including .aspx) > > Creating such may not be difficult -- but passing it to the DLL > could be. I don't know if ctypes allows pointer arithmetic. > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > length prefix. > > The only mention of BSTR in the win32 extensions is in text that > implies that the win32 extension library takes care of converting > from/to BSTR and Python strings transparently -- but that won't work for > your third-party library I suspect. > > Might have to beg the author(s) of ctypes to add a BSTR type to the > list of those supported... as I can find no means of tweaking the > address computed by byref() to point somewhere into a structure rather > than the beginning of the structure. > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > >>> pk > 1373844 > >>> id(pk) > 18941724 > >>> ctypes.string_at(pk) > '1234567890' > >>> ctypes.string_at(pk-4, 20) > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > > Okay, the return value from SysAlloc... IS the integer representing > the address of a BSTR structure (IE, the address four bytes in from the > real memory start)... Note how backing up 4 bytes reveals the BSTR > length field > > What happens if you just pass that item as-is, no byref(), no > conversion to ctypes pointer types... > > PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > SecKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > res = VmxGet( byref(hwmcb), > byref(SecIndex), > byref(Option), > byref(c_void_p(SrchKey)), > SecKey, > PriKey, > TypeDef ) > > >>> PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > >>> ctypes.string_at(PriKey, 41) > > "1234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'">>> ctypes.string_at(PriKey-4, 41+4) > > ")\x00\x00\x001234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'" > > >>> ord(")") > 41 > > You'll need to use the .string_at() or .wstring_at() functions to > extract any data changed by the call. Should not be a Python > immutability problem as all "you" allocated in Python is the integer > holding the address. You may need to call a Sys... function to free the > memory that had been allocated -- Python doesn't know about it. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ The VB6 Declare is: Declare Function VmxGet Lib "vbis5032.DLL" (DatasetHandle&, SecIndexField%, Options%, SelectorKey$, RSecondaryKey$, RPrimaryKey$, RRecordVariable As Any) As Integer The only variant is the RRecordVariable, which is actually meant to be a Type structure. Anyway, I thought maybe there was a clue in here that I am missing. Back to Python. I ran with the following: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) And, now I get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 156, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), SecKey, PriKey, TypeDef ) ctypes.ArgumentError: argument 5: : wrong type So, now the problem is with: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, LPSTR] I am not sure what to put for arguments 5 and 6 now. I realized the need to release the BSTRs myself, and already included: windll.oleaut32.SysFreeString(SrchKey) windll.oleaut32.SysFreeString(SecKey) windll.oleaut32.SysFreeString(PriKey) at the end of the program. I have no problem using .string_at() to extract the returned values - once the .argtypes let the call execute. In case this helps, here is an excerpt from a C program that was provided with the dll: typedef struct tagMYREC { char name[51]; // 1 xref generated name key char lastname[31]; // 2 last name char firstname[21]; // 3 first name char address[41]; // 4 address char city[31]; // 5 xref city key char state[3]; // 6 xref state char zip[11]; // 7 xref zip code char phone[21]; // 8 xref phone number BSTR notes; // 9 notes } MYREC; typedef MYREC FAR * LPMYREC; short rc; // return code (from VB/ISAM function calls) static HANDLE nDatasetNumber; static short cur_index; static short GetOpt; static BSTR Dummy; static BSTR Throwaway; static BSTR PrimaryKey; static MYREC myrec; rc = VmxGet(&nDatasetNumber, // int DatasetNumber // VIS_BUSY ? &cur_index, // int SelectedIndex &GetOpt, // int OptionParameter &Dummy, // Don't need a Selector param with these options &Throwaway, // Don't need returned index entry in this case &PrimaryKey, // LPBSTR lpPriKey (void *) &myrec); // LPVOID lpRecordStructure For someone who knows C and Python, this may provide a clue to the BSTR passing/return problem. From sjmachin at lexicon.net Fri Mar 21 16:34:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 13:34:27 -0700 (PDT) Subject: beginners question about return value of re.split References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> <47e3d9ff$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <84dedb7d-d726-4acf-84fc-2a8f28277d0d@s12g2000prg.googlegroups.com> On Mar 22, 2:53 am, klaus wrote: > On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote: > > <..........> > > Ok thank you ! > > I think I got a bit lost in all the possibilities python has to offer. IMHO you got more than a bit lost. You seem to have stumbled on a possibly unintended side effect of re.split. What is your underlying goal? If you want merely to split on '-', use datum.split('-'). If you want to verify the split results as matching patterns (4 digits, 2 digits, 2 digits), use something like this: | >>> import re | >>> datum = '2008-03-14' | >>> pattern = r'^(\d\d\d\d)-(\d\d)-(\d\d)\Z' You may notice two differences between my pattern and yours ... | >>> mobj = re.match(pattern, datum) | >>> mobj.groups() | ('2008', '03', '14') But what are you going to do with the result? If the resemblance between '2008-03-14' and a date is not accidental, you may wish to consider going straight from a string to a datetime or date object, e.g. | >>> import datetime | >>> dt = datetime.datetime.strptime(datum, '%Y-%m-%d') | >>> dt | datetime.datetime(2008, 3, 14, 0, 0) | >>> d = datetime.datetime.date(dt) | >>> d | datetime.date(2008, 3, 14) HTH, John From MartinRinehart at gmail.com Thu Mar 27 14:23:56 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 11:23:56 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: <71b3fd4e-464a-4a71-b2e3-62fe8055a56d@s12g2000prg.googlegroups.com> Guilherme Polo wrote: > there is a > gui designer tool for tkinter called GUI Designer (what a bad name), > which used to be called SpecTcl, where you can design the menus and it > then converts to python code. I tried it. after about 10 minutes I was as far as "help not found." Is anyone out there using this tool? Worth the learning curve? From bbxx789_05ss at yahoo.com Sat Mar 22 18:42:05 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 22 Mar 2008 15:42:05 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> Message-ID: <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> On Mar 22, 3:34?pm, bsoist wrote: > On Mar 22, 12:40 pm, jmDesktop wrote: > > > For students 9th - 12th grade, with at least Algebra I. ?Do you think > > Python is a good first programming language for someone with zero > > programming experience? ?Using Linux and Python for first exposure to > > programming languages and principles. > > > Thank you. > > Absolutely. I love using Python in "the real world" but it is > fantastic for beginning programmers. > > Python enforces good habits and presents many opportunities to discuss > programming from an academic perspective. Why does Python not have a > switch or until statement? Why are very common objects (stack, queue, > linked list) not builtin? etc. > Beginning programmers in grades 9-12 are not going to understand issues like that, and it would be a mistake to try and introduce them. Beginning programmers should be concentrating their efforts on learning the syntax of a language and basic constructs like for-loops and if statements. They will begin by writing simple "hello world" style programs, and as their basic skills improve, the programs will get a little more complex and require some more thought and some math to solve the problems presented to them. String formatting should probably be introduced to help with formatting the output. That is about as far as things are going to go. Terms like "Touring machines" and "lambda-calculus" are not going to be mentioned anywhere in the course of study. From ggpolo at gmail.com Tue Mar 11 13:39:40 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 11 Mar 2008 14:39:40 -0300 Subject: Exctract GIF comment from image In-Reply-To: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> References: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Message-ID: 2008/3/11, wingi at gmx.com : > Hi, > > simple question: The PIL does not support reading the optional > description in GIF Images. > > http://www.pythonware.com/library/pil/handbook/format-gif.htm > > After some reasearch I could not find a python solution for this, any > suggestions? > > Thanx, Wingi. > > -- > http://mail.python.org/mailman/listinfo/python-list > I did a quick thing here, try it and check if it solves the problem for you: import os import sys import struct def extract_comments(giffile): fobj = open(giffile, 'rb') giftype = fobj.read(6) pf = struct.unpack(' ..." % args[0] sys.exit(0) for gif in args[1:]: extract_comments(gif) if __name__ == "__main__": main(sys.argv) -- -- Guilherme H. Polo Goncalves From gagsl-py2 at yahoo.com.ar Mon Mar 31 22:17:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 23:17:47 -0300 Subject: Looking for indent advice howto in emacs python-mode References: <440c7af6-deaf-4180-afa8-91d9a3f359f3@e10g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 16:36:13 -0300, bruno.desthuilliers at gmail.com escribi?: > On 31 mar, 18:32, "Steven W. Orr" wrote: >> Here's what I want to do: >> >> if ( ( v == 1 ) >> or ( v == 2 ) >> or ( v == 3 ) ): >> pass > > Why the parens ? > > if a == 1 \ > or b == 2 \ > or c == 3: > pass I know it's mostly a matter of style, but I prefer to add parenthesis and avoid line continuation characters. Sometimes I use parenthesis for strings too, when multiline strings are not a good choice: txt = ("En un lugar de " "la Mancha, de cuyo " "nombre no quiero " "acordarme, no ha " "mucho tiempo...") (A multiline string would keep the inner \n but in this case I don't want that) -- Gabriel Genellina From duvo at tiscali.it Sun Mar 9 16:20:16 2008 From: duvo at tiscali.it (duvo at tiscali.it) Date: Sun, 9 Mar 2008 13:20:16 -0700 (PDT) Subject: del class with recursive list References: Message-ID: Thanks! I just need to remember to del the variables after "for in". From michael.wieher at gmail.com Thu Mar 13 10:49:49 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 13 Mar 2008 09:49:49 -0500 Subject: (off-topic) JS/DHTML export to XLS format? Message-ID: Anyone use/know of anything looks like a spreadsheet, lives in a web-browser and can export to XLS format? -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Mar 5 14:13:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Mar 2008 20:13:12 +0100 Subject: Dual look-up on keys? In-Reply-To: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> Message-ID: <6389mcF25af40U1@mid.uni-berlin.de> castironpi at gmail.com schrieb: > I want to hash values to keys. How do the alternatives compare? http://catb.org/~esr/faqs/smart-questions.html From mensanator at aol.com Mon Mar 3 15:40:16 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 12:40:16 -0800 (PST) Subject: sympy: what's wrong with this picture? Message-ID: Notice anything funny about the "random" choices? import sympy import time import random f = [i for i in sympy.primerange(1000,10000)] for i in xrange(10): f1 = random.choice(f) print f1, f2 = random.choice(f) print f2, C = f1*f2 ff = None ff = sympy.factorint(C) print ff ## 7307 7243 [(7243, 1), (7307, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] ## 8563 2677 [(2677, 1), (8563, 1)] ## 4091 6829 [(4091, 1), (6829, 1)] As in, "they're NOT random". The random number generator is broken by the sympy.factorint() function. Random.choice() works ok if the factorint() function commented out. ## 6089 1811 None ## 6449 1759 None ## 9923 4639 None ## 4013 4889 None ## 4349 2029 None ## 6703 8677 None ## 1879 1867 None ## 5153 5279 None ## 2011 4937 None ## 7253 5507 None This makes sympy worse than worthless, as it fucks up other modules. From duncan.booth at invalid.invalid Wed Mar 19 06:29:10 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 10:29:10 GMT Subject: Is there a way to get __thismodule__? References: Message-ID: benhoyt wrote: > But adding each message class manually to the > dict at the end feels like repeating myself, and is error-prone. It'd > be nice if I could just create the dict automatically, something like > so: > > nmap = {} > for name in dir(__thismodule__): > attr = getattr(__thismodule__, name) > if isinstance(attr, Message): > nmap[attr.number] = attr > > Or something similar. Any ideas? > > (A friend suggested class decorators, which is a good idea, except > that they're not here until Python 2.6 or Python 3000.) > Why not just use your base class? class Message(object): @staticmethod def getmap(): return dict((cls.number, cls) for cls in Message.__subclasses__()) class SetupMessage(Message): number = 1 class ResetMessage(Message): number = 2 class OtherMessage(Message): number = 255 nmap = Message.getmap() From dickinsm at gmail.com Tue Mar 11 16:16:58 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 11 Mar 2008 13:16:58 -0700 (PDT) Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> <46f8d1bf-8821-4083-b7d7-d4ed53f8862a@q78g2000hsh.googlegroups.com> <13tdcma35fabb6a@corp.supernews.com> Message-ID: On Mar 11, 12:26?pm, Grant Edwards wrote: > Before I submit a bug, I'll give it a try to find out if it > does support explicit specification of proxys or not. Sounds good. If it does, then I think the whole paragraph (from "The urlopeen() function does not support explicit proxy ..." to "...subclass such as FancyURLopener.") should just be removed. Looking at the source, there are some slight oddities: a plain urlopen() caches the URLopener instance it creates (in a module-level global) and uses this cached instance in future calls to urlopen or urlretrieve. If proxies are specified then it doesn't do the caching. I don't *think* this really affects usage, except that there are presumably some inefficiencies involved in multiple uses of urlopen with explicitly specified proxies, and those inefficiencies can be overcome by using URLopener or FancyURLopener directly instead. And it doesn't make a lot of sense that urlopen accepts proxies, but urlretrieve does not. But that's a different issue... Mark From hniksic at xemacs.org Sat Mar 29 04:14:44 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 29 Mar 2008 09:14:44 +0100 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> Message-ID: <87d4pe9caz.fsf@mulj.homelinux.net> "Diez B. Roggisch" writes: >> systems. (In theory, file input/output should also be available as >> asynchronous code, but async IO is low-level and not available in >> Python.) While threads shouldn't be considered a replacement for > > I suggest you tell that the twisted-guys. And the ones from the > built-in asyncore-module. Note that I said "*file* input/output". Twisted and asyncore are about asynchronous socket programming that polls over nonblocking file descriptors such as found in socket programming, not about wrapping aio(3) and the equivalent Windows APIs. From rockxuan at gmail.com Tue Mar 18 03:40:25 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:40:25 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <71ba8a58-4a59-422d-b058-6b72de38af99@s12g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From steven.klass at gmail.com Sun Mar 23 16:48:52 2008 From: steven.klass at gmail.com (rh0dium) Date: Sun, 23 Mar 2008 13:48:52 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> Message-ID: On Mar 23, 12:26?am, Paul McGuire wrote: > There are a couple of bugs in our program so far. > > First of all, our grammar isn't parsing the METAL2 entry at all. ?We > should change this line: > > ? ? md = mainDict.parseString(test1) > > to > > ? ? md = (mainDict+stringEnd).parseString(test1) > > The parser is reading as far as it can, but then stopping once > successful parsing is no longer possible. ?Since there is at least one > valid entry matching the OneOrMore expression, then parseString raises > no errors. ?By adding "+stringEnd" to our expression to be parsed, we > are saying "once parsing is finished, we should be at the end of the > input string". ?By making this change, we now get this parse > exception: > > pyparsing.ParseException: Expected stringEnd (at char 1948), (line:54, > col:1) > > So what is the matter with the METAL2 entries? ?After using brute > force "divide and conquer" (I deleted half of the entries and got a > successful parse, then restored half of the entries I removed, until I > added back the entry that caused the parse to fail), I found these > lines in the input: > > ? ? fatTblThreshold ? ? ? ? ? ? ? ? = (0,0.39,10.005) > ? ? fatTblParallelLength ? ? ? ? ? ?= (0,1,0) > > Both of these violate the atflist definition, because they contain > integers, not just floatnums. ?So we need to expand the definition of > aftlist: > > ? ? floatnum = Combine(Word(nums) + "." + Word(nums) + > ? ? ? ? Optional('e'+oneOf("+ -")+Word(nums))) > ? ? floatnum.setParseAction(lambda t:float(t[0])) > ? ? integer = Word(nums).setParseAction(lambda t:int(t[0])) > ? ? atflist = Suppress("(") + delimitedList(floatnum|integer) + \ > ? ? ? ? ? ? ? ? Suppress(")") > > Then we need to tackle the issue of adding nesting for those entries > that have sub-keys. ?This is actually kind of tricky for your data > example, because nesting within Dict expects input data to be nested. > That is, nesting Dict's is normally done with data that is input like: > > main > ? Technology > ? Layer > ? ? PRBOUNDARY > ? ? METAL2 > ? Tile > ? ? unit > > But your data is structured slightly differently: > > main > ? Technology > ? Layer PRBOUNDARY > ? Layer METAL2 > ? Tile unit > > Because Layer is repeated, the second entry creates a new node named > "Layer" at the second level, and the first "Layer" entry is lost. ?To > fix this, we need to combine Layer and the layer id into a composite- > type of key. ?I did this by using Group, and adding the Optional alias > (which I see now is a poor name, "layerId" would be better) as a > second element of the key: > > ? ? mainDict = dictOf( > ? ? ? ? Group(Word(alphas)+Optional(quotedString)), > ? ? ? ? Suppress("{") + attrDict + Suppress("}") > ? ? ? ? ) > > But now if we parse the input with this mainDict, we see that the keys > are no longer nice simple strings, but they are 1- or 2-element > ParseResults objects. ?Here is what I get from the command "print > md.keys()": > > [(['Technology'], {}), (['Tile', 'unit'], {}), (['Layer', > 'PRBOUNDARY'], {}), (['Layer', 'METAL2'], {})] > > So to finally clear this up, we need one more parse action, attached > to the mainDict expression, that rearranges the subdicts using the > elements in the keys. ?The parse action looks like this, and it will > process the overall parse results for the entire data structure: > > ? ? def rearrangeSubDicts(toks): > ? ? ? ? # iterate over all key-value pairs in the dict > ? ? ? ? for key,value in toks.items(): > ? ? ? ? ? ? # key is of the form ['name'] or ['name', 'name2'] > ? ? ? ? ? ? # and the value is the attrDict > > ? ? ? ? ? ? # if key has just one element, use it to define > ? ? ? ? ? ? # a simple string key > ? ? ? ? ? ? if len(key)==1: > ? ? ? ? ? ? ? ? toks[key[0]] = value > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? # if the key has two elements, create a > ? ? ? ? ? ? ? ? # subnode with the first element > ? ? ? ? ? ? ? ? if key[0] not in toks: > ? ? ? ? ? ? ? ? ? ? toks[key[0]] = ParseResults([]) > > ? ? ? ? ? ? ? ? # add an entry for the second key element > ? ? ? ? ? ? ? ? toks[key[0]][key[1]] = value > > ? ? ? ? ? ? # now delete the original key that is the form > ? ? ? ? ? ? # ['name'] or ['name', 'name2'] > ? ? ? ? ? ? del toks[key] > > It looks a bit messy, but the point is to modify the tokens in place, > by rearranging the attrdicts to nodes with simple string keys, instead > of keys nested in structures. > > Lastly, we attach the parse action in the usual way: > > ? ? mainDict.setParseAction(rearrangeSubDicts) > > Now you can access the fields of the different layers as: > > ? ? print md.Layer.METAL2.lineStyle > > I guess this all looks pretty convoluted. ?You might be better off > just doing your own Group'ing, and then navigating the nested lists to > build your own dict or other data structure. > > -- Paul Hi Paul, Before I continue this I must thank you for your help. You really did do an outstanding job on this code and it is really straight forward to use and learn from. This was a fun weekend task and I really wanted to use pyparsing to do it. Because this is one of several type of files I want to parse. I (as I'm sure you would agree) think the rearrangeSubDicts is a bit of a hack but never the less absolutely required and due to the limitations of the data I am parsing. Once again thanks for your great help. Now the problem.. I attempted to use this code on another testcase. This testcase had tabs in it. I think 1.4.11 is missing the expandtabs attribute. I ran my code (which had tabs) and I got this.. AttributeError: 'builtin_function_or_method' object has no attribute 'expandtabs' Ugh oh. Is this a pyparsing problem or am I just an idiot.. Thanks again! From hgk at ieee.org Wed Mar 19 04:48:59 2008 From: hgk at ieee.org (=?ISO-8859-1?Q?Hans_Georg_Krauth=E4user?=) Date: Wed, 19 Mar 2008 01:48:59 -0700 (PDT) Subject: keyboard "interrupt" References: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Message-ID: <17c1c060-e1e8-4abb-836a-f86c6a598f20@d45g2000hsc.googlegroups.com> On 18 Mrz., 22:18, johnmfis... at comcast.net (John Fisher) wrote: > Hi Group, > > I have been absent a while, mainly because I have been getting better at > figuring out my own Python problems. But not this one... > > I have a timed loop performing certain tasks until a total period of > time has elapsed. I would like to be able to interrupt the loop or set > various flags during execution via keyboard input. raw_input seems to > just stop everything cold. I want the ability to just sacn the keyboard > buffer and see if something is there, then proceed normally in the loop > if there is no input in the buffer. Make sense? Totally easy? Let me > know... > > wave_man I use this code: class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: try: self.impl = _GetchUnix() except ImportError: self.impl = _GetchMacCarbon() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return getch() class _GetchMacCarbon: """ A function which returns the current ASCII key that is down; if no ASCII key is down, the null string is returned. The page http://www.mactech.com/macintosh-c/chap02-1.html was very helpful in figuring out how to do this. """ def __init__(self): import Carbon def __call__(self): import Carbon if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask return '' else: # # The event contains the following info: # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008) [1] # # The message (msg) contains the ASCII char which is # extracted with the 0x000000FF charCodeMask; this # number is converted to an ASCII character with chr() and # returned # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008) [1] return chr(msg & 0x000000FF) Best regards Hans Georg From bignose+hates-spam at benfinney.id.au Thu Mar 27 18:53:26 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 28 Mar 2008 09:53:26 +1100 Subject: How to take snap shot of the of project screen in Python References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: <87myojvkwp.fsf@benfinney.id.au> "Praveena Boppudi (c)" writes: > Can anyone help me out? Probably, but your chances improve by starting a *new* thread to discuss your new question, instead of replying to an existing thread. -- \ "Pinky, are you pondering what I'm pondering?" "I think so, | `\ Brain, but Zero Mostel times anything will still give you Zero | _o__) Mostel." -- _Pinky and The Brain_ | Ben Finney From gagsl-py2 at yahoo.com.ar Mon Mar 31 23:06:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 01 Apr 2008 00:06:45 -0300 Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 23:28:13 -0300, escribi?: > tried wi5th the normal IDLE too and it worked later after i posted > this but now it doesnt work again. and i havent chnaged my firewall in > between. Perhaps any other running process has opened the port that IDLE uses to communicate with the running program. Or you have IDLE already running. See if you have python.exe/pythonw.exe processes running. Or go to Help, IDLE Help, and read the section "Running without a subprocess" -- Gabriel Genellina From andrei.avk at gmail.com Wed Mar 12 00:24:13 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Tue, 11 Mar 2008 21:24:13 -0700 (PDT) Subject: Open a file with default handler app? Message-ID: <83bc9bf2-9b9c-4959-870f-f4b37281f6e0@m3g2000hsc.googlegroups.com> Hi, I searched for this on google and in this group, but my awesome google-fu powers failed me. Is there a way to open any file using default program that'd open it? In other words, to do the same action as double-clicking in windows explorer? And secondly, is there a way to do the same thing for linux that'd work across all desktop environments and distributions, or at least in all major ones? What I'm trying to do here is to have records (or items) in my app where you could attach any kind of file and open it from there by clicking 'open'. Then it would go and do something like os.system("launch %s" % filename). So any way to do this except for keeping your own dictionary of file types and relevant apps? thx, -ak From patrick.waldo at gmail.com Mon Mar 31 14:53:12 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 31 Mar 2008 11:53:12 -0700 (PDT) Subject: xlrd and cPickle.dump Message-ID: Hi all, I have to work with a very large excel file and I have two questions. First, the documentation says that cPickle.dump would be the best way to work with it. However, I keep getting: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\python_files\pickle_test.py", line 12, in ? cPickle.dump(book,wb.save(pickle_path)) File "C:\Python24\lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects I tried to use open(filename, 'w') as well as pyExcelerator (wb.save(pickle_path)) to create the pickle file, but neither worked. Secondly, I am trying to make an ID number from three columns of data: category | topic | sub_topic, so that I can . I imagine that a dictionary would be the best way to sort out the repeats From asmodai at in-nomine.org Fri Mar 7 13:24:18 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 7 Mar 2008 19:24:18 +0100 Subject: Regarding coding style In-Reply-To: <20080307130919.b3f82a85.darcy@druid.net> References: <63d80bF273nraU1@mid.individual.net> <20080307130919.b3f82a85.darcy@druid.net> Message-ID: <20080307182418.GR60713@nexus.in-nomine.org> -On [20080307 19:10], D'Arcy J.M. Cain (darcy at druid.net) wrote: >The arguments for one over the other fall into these basic ones. Use >double spaces to make the document easier to read, especially by people >who read a lot and tend to skim to absorb as much information as >possible. Use single space because it makes the document display >nicer. This suggests to me that the schism is probably between two >different types of people, text/information oriented and >display/presentation oriented. I don't see any way to appeal to both. The double space came from the era of typewriters and monospace printers. Technology nowadays with all kinds of rendering engines and font specifications basically make the entire point of 'two spaces after a period' a moot point. In all my professional technical writing and documentation work I completely gave up on two spaces after a period. It's archaic. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When you are right, you cannot be too radical; When you are wrong, you cannot be too conservative. From software at ginstrom.com Mon Mar 10 06:23:40 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 10 Mar 2008 19:23:40 +0900 Subject: Edit and continue? In-Reply-To: <21CFA1FC32D3214EBFA2F449FF211E310EAD2972@nypcmg1exms318.leh.lbcorp.lehman.com> References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2972@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <064e01c88298$cfc95fe0$0203a8c0@MOUSE> > On Behalf Of Bronner, Gregory > I'm working on a GUI application that has lots of callbacks. > Testing it is very slow and quite boring, as every time I > find an error, I have to exit it, restart it, and repeat the > series of clicks. It would be really amazing if python > supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my > code and have it apply to a running instance of a class. What framework are you using? Also, automating those pesky clicks and such should make your GUI testing a lot easier. There are two angles of approach: "driving" the GUI automatically, and stubbing out/mocking the windowing methods so that you can test GUI components in a unit-testing framework. Regards, Ryan Ginstrom From ericofam at yahoo.com Sat Mar 8 18:49:09 2008 From: ericofam at yahoo.com (olusina eric) Date: Sat, 8 Mar 2008 15:49:09 -0800 (PST) Subject: Green's Function Message-ID: <501978.67770.qm@web53602.mail.re2.yahoo.com> Hi All, I am new to Python and trying to solve the Hamiltonian of a linear chair of atoms using green?s function. Does anyone know any pre-existing library functions and literature that could be helpful? Thanks EOF --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From atom.anderson at gmail.com Thu Mar 20 19:38:41 2008 From: atom.anderson at gmail.com (atom.anderson at gmail.com) Date: Thu, 20 Mar 2008 16:38:41 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> <927f5a44-f8fa-4fe2-bdc2-12fac2d50e7a@s37g2000prg.googlegroups.com> Message-ID: On Mar 20, 2:53 pm, Erich wrote: > On Mar 20, 12:39 pm, Ed Leafe wrote: > > > > > On Mar 20, 2008, at 11:54 AM, atom.ander... at gmail.com wrote: > > > > Number Three: Too much code, not enough concept. > > > > Presenters this one's for you. I can't count the number of > > > presentations I attended where the presenter would click through three > > > slides of pycode just to show us a two or three-line snippet that > > > illustrated their point. Worse yet, it was often at the bottom of the > > > screen so no one but the front row could see it. This goes for text > > > two. I saw some great presentations as well, and they had limited > > > text on each slide. The last thing your audience wants to see is a > > > slide drenched in text of any kind. > > > This is good advice: simple slides serve as organization cues, but > > the content should come from the speaker. The worst case (only saw > > this twice at this year's PyCon) is when there is a text-heavy slide > > that the presenter simply reads. We can all read it ourselves! Your > > job is to elaborate on the topic. > > > I'd like to see two things regarding slides: first, if at all > > possible, set a limit on the percentage of the talk that can consist > > of slides. I would much rather see the presenter show actual > > demonstrations of what they're talking about than simply talking about > > it. If that's not possible, then in the session description, clearly > > state the % of the talk that will be slides. Perhaps there are people > > who like to sit in a room and watch long PowerPoint (-type) > > presentations, but I'm not one of them. Let's see some code! Let's see > > stuff working (and sometimes crashing!), and how changes affect the > > results. When I've presented at PyCon and other conferences, that's > > the part that I spend the most time on: preparing demonstrations. It's > > not easy to do; certainly much more difficult than creating a slide > > that sums up what the demo does. But it makes for a much more > > interesting session! > > > -- Ed Leafe > > I'd like to see code listings made available to download where > appropriate. That way the slides dont have much hard to read content, > and we can look at the bits of code we find tricky as we see fit. And > if we get bored with bits, we can play with code! > > Erich. agreed. and just to clarify, i LIKE CODE! i hope we all do haha... but in a presentation setting if they could teach/share with us what they've been doing, allow us to download some example code (and tinker with it) and remove all those details from the slides, itd be vastly helpful. I fully expect anyone who presented this time (who takes time to TRY to improve) will improve. -adam From fn681 at ncf.ca Fri Mar 21 10:20:22 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:20:22 -0500 Subject: Fate of the repr module in Py3.0 In-Reply-To: References: Message-ID: Raymond Hettinger wrote: > Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , > and saw that the repr module was slated for vaporization. I've only > used the module a few times ever. I'm curious if the community wants > it kept around or whether it is considered clutter. > > The PEP is going to be finalized soon, so if you have issues with it, > they should be sent to the PEP author or brought up on the list, > http://mail.python.org/mailman/listinfo/stdlib-sig . > > Raymond I've never used it, the value isn't obvious. >>> import repr >>> repr.__doc__ 'Redo the builtin repr() (representation) but with limits on most sizes.' >>> Colin W. From cyu021 at gmail.com Tue Mar 11 07:04:06 2008 From: cyu021 at gmail.com (James Yu) Date: Tue, 11 Mar 2008 19:04:06 +0800 Subject: The stange behaviour of Tkinter.Canvas Message-ID: <60bb95410803110404o414ababft8fca994d16cfd60a@mail.gmail.com> I tried to update the rectangle on a canvas to get the visual effect of progressbar. It works all right if I delete the existing objects (rectangle and text) and create a new one. However, if I invoke canvas.itemconfig() to update the existing objects' options, gui just went nuts. I am more than happy to receive any help and advise. My code is provided as follows: ------------------------------------Start of Code------------------------------------ import Tkinter import threading import time class Progressbar(Tkinter.Frame): def __init__(self, parent=None, color='white', width=200, height=15): Tkinter.Frame.__init__(self, parent) self.pack(expand=Tkinter.YES, fill=Tkinter.BOTH) canv = Tkinter.Canvas(self, bg=color, relief=Tkinter.SUNKEN) canv.config(width=width, height=height) canv.pack(side=Tkinter.LEFT, expand=Tkinter.YES, fill=Tkinter.BOTH) self.canv = canv self.width = width self.height = height progress = -10 rect = canv.create_rectangle(0, 0, 0, height, fill='beige') text = canv.create_text(width/2, height*2/3, text='0%') self.rect = rect self.text = text self.progress = progress self.parent = parent parent.progressbar = self self.UpdateProgress() def SetProgress(self, progress=0): canv = self.canv width = self.width height = self.height rect = self.rect text = self.text ## canv.delete(rect) ## canv.delete(text) ## rect = canv.create_rectangle(0, 0, progress*width/100, height, ## fill='beige') ## text = canv.create_text(width/2, height*2/3, ## text='%s' %(str(progress)) + '%') canv.itemconfig(rect, width=width*progress/100) ## comment this canv.itemconfig(text, text='%s' %(str(progress)) + '%') ## comment this ## self.rect = rect ## self.text = text def UpdateProgress(self): progress = self.progress progress = progress + 10 self.progress = progress self.SetProgress(progress) if progress < 100: self.after(500, self.UpdateProgress) if __name__ == '__main__': root = Tkinter.Tk() Progressbar(parent=root) root.mainloop() ------------------------------------End of Code------------------------------------ uncomment the lines and comment out the itemconfig() lines to see the difference in gui's behaviours. Thanks, -- This is a UTF-8 formatted mail ----------------------------------------------- James C.-C.Yu -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Mon Mar 24 11:08:59 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 24 Mar 2008 12:08:59 -0300 Subject: python library to manipulate PALM documents ? In-Reply-To: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> References: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> Message-ID: 24 Mar 2008 13:36:13 GMT, Francesco Bochicchio : > Hi all, > > anybody knows a python equivalent of the perl PALM::Doc module (and > eventually other PALM::). > > I have a e-book device wich reads mobi-pocket format (among others). I > have downloaded from a forum a set of perl scripts to convert HTML to > unencripted mobipocket format and vice-versa. It uses the PALM:: package. > I would attempt (for my convenience and for the fun of it) to make a > python equivalent of that. Hence my quest for a Palm::Doc equivalent. > I'm not sure if it is what you are after, but it seems to be, check this: http://pypi.python.org/pypi/PalmDB/1.8.1 > My googling up to now resulted in nothing relevant. Keeping searching ... > > Ciao > ----- > FB > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From tmp1 at viltersten.com Sat Mar 1 16:33:36 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 22:33:36 +0100 Subject: SV: Surprised by the command "del" In-Reply-To: References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: <62tvenF25bed2U1@mid.individual.net> >> I'm reading the docs and at 5.2 the del >> statement is discussed. At first, i thought >> i've found a typo but as i tried that >> myself, it turns it actually does work so. >> >> a = ["alpha", "beta", "gamma"] >> del a[2:2] >> a >> >> Now, i expected the result to be that the >> "beta" element has been removed. Obviously, >> Python thinks otherwise. Why?! > > Remember that slices are specified as half-open > intervals. So a[m:n] includes m-n elements, > those indexed from m to n-1. Got it. Thanks! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From tom at t0mb.net Sat Mar 15 07:08:57 2008 From: tom at t0mb.net (Thomas Boland) Date: Sat, 15 Mar 2008 11:08:57 +0000 Subject: Python-list Digest, Vol 54, Issue 199 In-Reply-To: References: Message-ID: <47DBAE49.8080501@t0mb.net> what the? why can this get through? python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > ------------------------------------------------------------------------ > > Today's Topics: > > 1. I found affordable health insurance. (MSmith) > > > ------------------------------------------------------------------------ > > Subject: > I found affordable health insurance. > From: > MSmith > Date: > Sat, 15 Mar 2008 03:50:47 -0700 (PDT) > To: > python-list at python.org > > To: > python-list at python.org > > > I couldn't believe it. > > > Do yourself a favour and at least check it out: > > http://www.jdoqocy.com/click-2924912-10359791 > > > > Michael > > From k_r_a_j_kumar at yahoo.co.in Fri Mar 28 07:44:57 2008 From: k_r_a_j_kumar at yahoo.co.in (Raj kumar) Date: Fri, 28 Mar 2008 17:14:57 +0530 (IST) Subject: regarding xml elements Message-ID: <66657.48471.qm@web8713.mail.in.yahoo.com> Hi, I have an xml file in my application, I have created an element using Example goes like this......... document.createElement("abc") and i appeneded it by using append() method. But how i can reflect this change to my xml file? and one more thing is i want to create element with some other parameters.... like............. and i have m and n values as strings with me. can anybody help me to create this element and write it to the existing xml file as a child of an existing element? Thanks in advance.. Raj.. Forgot the famous last words? Access your message archive online at http://in.messenger.yahoo.com/webmessengerpromo.php -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.pedwysocki at gmail.com Fri Mar 7 11:12:38 2008 From: alex.pedwysocki at gmail.com (alex.pedwysocki at gmail.com) Date: Fri, 7 Mar 2008 08:12:38 -0800 (PST) Subject: Timed execution in eval Message-ID: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> I have various bits of code I want to interpret and run at runtime in eval ... I want to be able to detect if they fail with error, I want to be able to time them, and I want to be able to stop them if they run too long. I cannot add code to the eval'd strings that will help me accomplish this. Is there a good way to do this? I have it figured out for perl but I'd rather use python if possible. Thanks for any assistance. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 2 07:23:57 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 02 Mar 2008 13:23:57 +0100 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: <62vkitF256k2hU1@mid.individual.net> Gabriel Genellina wrote: > They are part of the telnet protocol; 0xFF (IAC=Interpret as > Command) starts a two or three byte command sequence. > Weren't you using telnetlib? It's supposed to handle this > transparently. With Twisted you don't need Telnetlib, twisted.conch.telnet does the job. I would definitely look at twisted.words, too. Regards, Bj?rn -- BOFH excuse #329: Server depressed, needs Prozac From Dodin.Roman at gmail.com Mon Mar 17 06:56:26 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 03:56:26 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue Message-ID: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Hi all i have a problem with this modules py2exe + pywinauto + sendkeys used together. In my script i'm using this expression app.window_(title="SJphone").Edit.TypeKeys("Test is running",with_spaces=True) TypeKeys is using SendKeys module i suppose. my setup.py looks like that: from distutils.core import setup import py2exe setup( options = {"py2exe": {"compressed": 1, "optimize": 0, "bundle_files": 1, "packages": ["encodings", "pywinauto", "pywinauto.controls", "pywinauto.tests"] } }, zipfile = None, console=["hosts.py"] ) and when i'm trying to run my hosts.exe i'm getting this traceback Traceback (most recent call last): File "hosts.py", line 524, in main() File "hosts.py", line 517, in main TestCase3_1() File "hosts.py", line 421, in TestCase3_1 SJstart() File "hosts.py", line 36, in SJstart app.window_(title="SJphone").Edit.TypeKeys("Test is running",with_spaces=Tru e) File "pywinauto\controls\HwndWrapper.pyc", line 928, in TypeKeys NameError: global name 'SendKeys' is not defined are there any workarounds on that? From jeff at jmcneil.net Wed Mar 19 00:31:49 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 19 Mar 2008 00:31:49 -0400 Subject: Is there a way to get __thismodule__? In-Reply-To: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> References: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> Message-ID: <82d28c40803182131j7b887a34j77c2a36586628193@mail.gmail.com> This is somewhere that I would personally use a metaclass. That way, if you define more subclasses of Message, you're not limited to doing so in that single module. Someone correct me if this is goofy, I don't do much metaclass programming. Perhaps something like: #!/usr/bin/python class MetaMessage(type): nmap = {} def __new__(mcl, name, bases, d): obj = super(MetaMessage, mcl).__new__(mcl, name, bases, d) # Check __name__ here as 'Message' isn't yet defined. if "Message" in [b.__name__ for b in bases]: if "number" not in d: raise TypeError("Message protocol expects a number attribute") MetaMessage.nmap[d['number']] = obj # Complete Creation. return obj class Message(object): __metaclass__ = MetaMessage class MessageOne(Message): number = 1 class MessageTwo(Message): number = 2 class MessageFourThousandThreeHundredAndTwentyTwoPointOne(Message): number = 4322.1 print MetaMessage.nmap Which results in: mac:~ jeff$ !p python test.py {1: , 2: , 4322.1000000000004: } mac:~ jeff$ Thanks! Jeff On 3/19/08, benhoyt wrote: > > Replying to myself here, after discovering more. :-) > > > > Is there a way to get __thismodule__ in Python? > > > It looks like __thismodule__ is just sys.modules[__name__]. Neat. > > Hmmm ... does sys.modules always already contain the currently-being- > loaded module? Or is this a hack that only happens to work? (It does; > I've tested it now.) Just wondering, because the Python docs say that > sys.modules is "a dictionary that maps module names to modules which > have *already been loaded*." > > > > if isinstance(attr, Message): > > nmap[attr.number] = attr > > > Oops, this was untested code. I actually meant issubclass (or > something similar) here, not isinstance. > > > Cheers, > Ben. > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 09:47:53 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 13:47:53 -0000 Subject: SQLObject 0.10.0 In-Reply-To: <20080311134003.GB14147@phd.pp.ru> References: <20080311134003.GB14147@phd.pp.ru> Message-ID: <00bf01c8837e$81aebe90$850c3bb0$@rawlins@thinkbluemedia.co.uk> Excellent stuff Oleg, I've been looking for an ORM framework for a while and hadn't settled on one, I'll give this a look through later today. Thanks, Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Oleg Broytmann Sent: 11 March 2008 13:40 To: Python Announce Mailing List; Python Mailing List Subject: SQLObject 0.10.0 Hello! I'm pleased to announce version 0.10.0, the first stable release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9 -------------- Features & Interface ~~~~~~~~~~~~~~~~~~~~ * Dropped support for Python 2.2. The minimal version of Python for SQLObject is 2.3 now. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.10. * SQLBuilder Select supports the rest of SelectResults options (reversed, distinct, joins, etc.) * SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect() use SQLBuilder Select queries; this make all SELECTs implemented internally via a single mechanism. * SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias) and properly sqlrepr. * Added SQLBuilder ImportProxy. It allows one to ignore the circular import issues with referring to SQLObject classes in other files - it uses the classregistry as the string class names for FK/Joins do, but specifically intended for SQLBuilder expressions. See tests/test_sqlbuilder_importproxy.py. * Added SelectResults.throughTo. It allows one to traverse relationships (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's a simple mechanism for pre-caching/eager-loading of later FK relationships (i.e., going to loop over a select of somePeople and ask for aPerson.group, first call list(somePeople.throughTo.group) to preload those related groups and use 2 db queries instead of N+1). See tests/test_select_through.py. * Added ViewSQLObject. * Added sqlmeta.getColumns() to get all the columns for a class (including parent classes), excluding the column 'childName' and including the column 'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to override it in the inheritable sqlmeta class; this makes asDict() to work properly on inheritable sqlobjects. * Allow MyTable.select(MyTable.q.foreignKey == object) where object is an instance of SQLObject. * Added rich comparison methods; SQLObjects of the same class are considered equal is they have the same id; other methods return NotImplemented. * RowDestroySignal is sent on destroying an SQLObject instance; postfunctions are run after the row has been destroyed. * Changed the implementation type in BoolCol under SQLite from TINYINT to BOOLEAN and made fromDatabase machinery to recognize it. * MySQLConnection (and DB URI) accept a number of SSL-related parameters: ssl_key, ssl_cert, ssl_ca, ssl_capath. * Use sets instead of dicts in tablesUsed. Dropped tablesUsedDict function; instead there is tablesUsedSet that returns a set of strings. * SQLBuilder tablesUsedSet handles sqlrepr'able objects. * Under MySQL, PickleCol no longer uses TEXT column types; the smallest column is now BLOB - it is not possible to create TINYBLOB column. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list From johnwalker3301 at comcast.net Wed Mar 26 16:33:54 2008 From: johnwalker3301 at comcast.net (jpw) Date: Wed, 26 Mar 2008 13:33:54 -0700 (PDT) Subject: Python / C++ embed halfway working - question about constructors Message-ID: <73dd0186-f171-44d6-9e3a-11828923f050@u10g2000prn.googlegroups.com> I am running my C++ / Python App on a MacBook Pro with 2.5 installed I have had some success in that I can load a module, get the class, get the reference, but when the python class calls another python class I don't ever seem to get the object back from the constructor. I am doing the following in the C++ file: Py_Initialize() PyObject* module = PyImport_Import(moduleName); PyObject* class = PyObject_GetAttrString(module, className); Py_DECREF(module); Py_DECREF(class); // Create the TSAFE object constructor arguments: // a file, and an int PyObject* tsafeOutputFile = PyFile_FromString("TsafeOutput", "a"); PyObject* resolveValue = PyInt_FromLong(0); PyObject* classArgumentTuple = PyTuple_New(2); PyTuple_SetItem(classArgumentTuple, 0, tsafeOutputFile); PyTuple_SetItem(classArgumentTuple, 1, resolveValue); classReference = PyEval_CallObject(class, classArgumentTuple); Py_MY_INCREF(classReference); Py_MY_DECREF(class); PyObject* pythonMethod = PyObject_GetAttrString(classReference, "registerFlight"); registerReturn = PyEval_CallObject(pythonMethod, argumentTuple); Py_MY_DECREF(pythonMethod); Py_MY_DECREF(argumentTuple); Essentially the code above should: call class constructor call registerFlight() calls registerFlight_() calls _flightPointer() -> where I never get by the section of code where the Flight.py Constructor get called Each flight should be added to my class object to build up a dictionary of flights. The python class methods getting called are detailed below and I never get by the call to _flightPointer(). I have opened a file and write to it at each step of code and I never get all the way through the _flightPointer() method Is there something I am missing here I cannot print the data out of the __init__ method in the Flight.py file? I did not include all of the code here because I am hoping the issue is I have got something wrong and it's not the python code but me. Ant help will be greatly appreciated. def registerFlight(self, ID, ACtype="?", IFR=1, RVSM=0, ATCcat="?", filedAlt=0, filedSpeed=0): "register flight (unitless args for outside client)" filedAlt *= FL # FL = Flight Level = 100 ft filedSpeed *= kn # kn = knots self.registerFlight_(ID, ACtype, IFR, RVSM, ATCcat, filedAlt,filedSpeed) def registerFlight_(self, ID, ACtype="?", IFR=1, RVSM=0, ATCcat="?", filedAlt=0, filedSpeed=0): "register flight (accepts arguments with units)" flight = self._flightPointer(ID) flight.registerFlight(ACtype, IFR, RVSM, ATCcat, filedAlt, filedSpeed) def _flightPointer(self, ID, track=0, Flight=Flight): "manage tracked and untracked flight lists" fltPointerFile = open('TSAFE_flightPointerOut', 'a') fltPointerFile.write("In the _flightPointer function\n") flights = self.flights unflights = self.untrackedFlights if ID in flights: fltPointerFile.write("in first IF\n") return flights[ID] if track: # new data record is a track update - start tracking if ID in unflights: # move flight to tracked status flights[ID] = unflights[ID] del unflights[ID] else: flights[ID] = Flight(ID) # new Flight object return flights[ID] ## THIS IS THE SECTION OF CODE NOT RETURNING A REFERENCE TO THE Flight object if ID not in unflights: fltPointerFile.write(ID) fltPointerFile.write(" In if ID not in unflights\n\n") unflights[ID] = Flight(ID) fltPointerFile.write("BACK FROM CALLING Flight(ID)\n") unflightsValue = ("unflights[ID]", unflights[ID]) unflightsString = str(unflightsValue) fltPointerFile.write("Return value is ") fltPointerFile.write(unflightsString) fltPointerFile.write('\n') return unflights[ID] From grante at visi.com Fri Mar 7 12:48:44 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Mar 2008 17:48:44 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <13t2vvstgkne233@corp.supernews.com> On 2008-03-07, Jon Ribbens wrote: > Personally, I dislike double spaces after sentences, but it is > not wrong to put them there any more than it is wrong not to > put them there. You're lucky my high school typing teacher didn't hear you say that... -- Grant Edwards grante Yow! I joined scientology at at a garage sale!! visi.com From bignose+hates-spam at benfinney.id.au Mon Mar 17 03:28:54 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Mar 2008 18:28:54 +1100 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> Message-ID: <87r6e9zu4p.fsf@benfinney.id.au> Bernard Lim writes: > > Depending on implementation, for immutable types, operations that > compute new values may or may not actually return a reference to any > existing object with the same type and value, while for mutable > objects this is (strictly)? not allowed. > > > Using the example given in 3.1, how do I verify that this is true > pertaining to immutable types? You don't. By the language definition, it's entirely up to the implementation whether *and when* to do this. So, even if you find a particular session that does this, there's no telling whether it'll stop happening at some future session using *exactly the same inputs* -- and, if it did change, that would also be entirely within the definition of the language. If something in a language specification says "this set of conditions leads to undefined behaviour", or "this aspect is implementation defined", then *absolutely any behaviour* that fits the rest of the definition is allowed, even if that results in non-determinism from the programmer's perspective. In short: Don't ever rely on such behaviour labelled with these "may or may not" phrases, even if you run some tests and appear to get predictable results. -- \ ?The power of accurate observation is frequently called | `\ cynicism by those who don't have it.? ?George Bernard Shaw | _o__) | Ben Finney From castironpi at gmail.com Mon Mar 10 13:10:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 10:10:07 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> <13taot5khcl933a@corp.supernews.com> Message-ID: On Mar 10, 11:36?am, Steven D'Aprano wrote: > On Mon, 10 Mar 2008 07:39:25 -0700, Gary Herron wrote: > > If either is a surprise, then understand that the "is" operator should > > probably *never* be used with immutable types. > > Mutable or immutable, it makes no difference: "is" is for testing > identity, == is for testing equality. If you need to test for identity, > use "is". If you need to test for equality, use ==. What is the notion of equal defined for functions? From Lie.1296 at gmail.com Sun Mar 23 13:22:16 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 23 Mar 2008 10:22:16 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> <210f1e24-649a-43c0-b975-8209211d56de@a70g2000hsh.googlegroups.com> Message-ID: <6900b188-8d08-4a9b-976f-719ba176fb97@e23g2000prf.googlegroups.com> On Mar 22, 2:23?pm, castiro... at gmail.com wrote: > > Sane programmers don't write such semi-functional things (unless it > > helps expressing the problem in certain domains). > > I now think that deprecating map, lambda & Co. was a good thing after > > all. > > If you write it that way the first time, you need therapy. ?Actually, > at this point, I (for one, personally) want to investigate 'certain > domains'. ?Tell me it's really bad at everything or what it's good > at. ?What can I respect about it? If you (castiro..) write it your way, you'll surely win the Obfuscated Python Code Contest. From gagsl-py2 at yahoo.com.ar Fri Mar 21 04:03:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 01:03:34 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: <76ca2753-1c8e-4dea-97b7-141ccbddb53b@z38g2000hsc.googlegroups.com> On 20 mar, 08:47, Godzilla wrote: > Thanks Ross and John for your help. I apologise for the code I posted > earlier not being the full picture of what I was trying to achieve. I > had instantiated multiple instances of elapseTime class and each of > them gets called approximately the same time. Below is the updated > code: You still have race conditions: > ? ? def setTime(self, state): > ? ? ? if state == 1: > ? ? ? ? self.checkTimeFlag = True > ? ? ? ? self.timeStamp = time.clock() > ? ? ? else: > ? ? ? ? self.checkTimeFlag = False > > ? ? def elapsedTime(self): > ? ? ? prevTime = time.clock() > ? ? ? while True: > ? ? ? ? curTime = time.clock() > ? ? ? ? timeDiff = (curTime - prevTime) > ? ? ? ? if timeDiff < 0.0: > ? ? ? ? ? printq.put_nowait('time.clock() has gone backward!!! Time > Diff '+str(timeDiff)) > ? ? ? ? if self.checkTimeFlag: > ? ? ? ? ? if (curTime - self.timeStamp) > 1.0: > ? ? ? ? ? ? printq.put_nowait(self.name+", actual Elapsed > Time"+str(round(curTime-self.timeStamp, 3))) > ? ? ? ? ? ? self.checkTimeFlag = False > ? ? ? ? prevTime = curTime > ? ? ? ? time.sleep(0.05) Both functions run on different threads, use self.checkTimeFlag and self.timeStamp. By example, setTime sets self.checkTimeFlag = True before self.timeStamp; the other thread can use and old value for self.timeStamp. -- Gabriel Genellina From xkenneth at gmail.com Wed Mar 12 14:10:59 2008 From: xkenneth at gmail.com (xkenneth) Date: Wed, 12 Mar 2008 11:10:59 -0700 (PDT) Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> <47D80BC4.2010307@behnel.de> Message-ID: On Mar 12, 11:58?am, Stefan Behnel wrote: > xkenneth wrote: > > On Mar 12, 6:32 am, "Diez B. Roggisch" wrote: > >> xkenneth wrote: > >>> Hi All, > >>> ? ?Quick question. I've got an XML schema file (XSD) that I've > >>> written, that works fine when my data is present as an XML file. > >>> (Served out by apache2.) Now when I callpythonas a cgi script, and > >>> tell it print out all of the same XML, also served up by apache2, the > >>>XSDis not applied. Does this have to do with which content type i > >>> defined when printing the xml to stdout? > >> Who's applying the stylesheet? The browser, some application like XmlSpy or > >> what? > > > The browser. > > Well, why should it validate your file? Browsers don't do that just for fun. > > Stefan Sorry, it was really late when i wrote this post. The file is an XSL file. It defines HTML depending on what appears in the XML document. Regards, Kenneth Miller From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:54:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:54:56 -0300 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 12:15:48 -0300, harryos escribi?: >> The code is pretty legible as it is now. Anyway, using min() and a >> generator: >> >> > > hi > is this calculated distance really Euclidean distance? When i checked > wikipedia http://en.wikipedia.org/wiki/Euclidean_distance > it shows a calculation involving sum of squares of the differences of > elements.Here in this code ,the sum of coordinates are used? is that a > different measure? (Thanks for trimming the irrelevant parts of the message, that's good; but you trimmed too much text, even attribution lines - the above quoted sentence was mine) That's what I said in another paragraph. "sum of coordinates" is using a different distance definition; it's the way you measure distance in a city with square blocks. I don't know if the distance itself has a name, but the norm from which it is derived is called norm-1, or L1; the usual euclidean distance is derived from norm-2. See http://mathworld.wolfram.com/VectorNorm.html If you only want to see if two things are "close enough", this provides a faster measure than the euclidean distance. -- Gabriel Genellina From mnordhoff at mattnordhoff.com Fri Mar 14 08:50:11 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 14 Mar 2008 12:50:11 +0000 Subject: Update pytz timezone definitions In-Reply-To: References: Message-ID: <47DA7483.80804@mattnordhoff.com> _robby wrote: > I am looking at using pytz in a scheduling application which will be > used internationally. I would like to be able to update the definition > files that pytz uses monthly or bi-monthly. > > As far as I can tell, pytz seems to be updated (fairly) regularly to > the newest tzdata, but I don't want to have to update my pytz, just > it's definitions. > > http://www.twinsun.com/tz/tz-link.htm says that pytz "compiles tz > source into Python." Does this mean that there is already a method for > updating the definitions? > > Any help would be greatly appreciated, even if it is to point out > something obvious which I over looked. > > - Robby pytz's build process is rather complicated (e.g., a list of all time zones is appended to pytz/__init__.py). I really don't think it would be worth the effort. python-dateutil [1] [2] provides time zone support similar to pytz's, among other features. It keeps the time zone files in a tarball and I'm pretty sure it would be easy to update. I still don't get why you'd want to go to the effort though. Upgrading the whole package is easy. It's not like pytz gets a new API every version. [1] [2] -- From gagsl-py2 at yahoo.com.ar Tue Mar 25 21:49:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 22:49:36 -0300 Subject: embedded python pythonpath References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> <3a4a8f930803251822h5d423198yc318ed270ad7d92a@mail.gmail.com> Message-ID: En Tue, 25 Mar 2008 22:22:41 -0300, Furkan Kuru escribi?: > On 3/26/08, Gabriel Genellina wrote: > >> En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru >> escribi?: >> >> > Actually, I do not want any .py or .pyc files around my executable. >> > (including userdict, sys, site etc) >> > I want to have just single zip file for all python files. >> >> Putting all of them into pythonNN.zip (NN depending on the Python >> version >> in use) should be enough, but I've never tried it. > I had already tried putting all of them into pythonNN.zip but I had to > copy it to the place > where sys.path points in my case it was windows\system32\python25.zip It should be in the same directory as python25.dll; you don't have to use windows\system32 if you copy python25.dll to your application directory. >> After renaming the directory where Python 2.5 were installed, my >> test25.exe program (the one compiled using Python 2.5.1) worked fine. So >> it looks like it is something with how the "python home" is searched. > > Ok then changing or deleting pythonhome environment variable may fix the > problem? "Python home" means the directory where Python is installed, from which the rest of the directories are derived. It should have a lib directory with an os.py file inside, and so on... I don't have a PYTHONHOME environment variable, nor a PYTHONPATH (except for this testing). -- Gabriel Genellina From nick at njday.com Sun Mar 9 14:06:36 2008 From: nick at njday.com (Nick Day) Date: Sun, 9 Mar 2008 11:06:36 -0700 (PDT) Subject: Problems installing Python Imaging Library Message-ID: <76000a76-0c8f-4b79-95c8-9d0f4aae0972@n58g2000hsf.googlegroups.com> Hi, I'm trying to install PIL from source on my CentOS 4.5 server. The build summary reports that I have everything installed... -------------------------------------------------------------------- PIL 1.1.6 BUILD SUMMARY -------------------------------------------------------------------- version 1.1.6 platform linux2 2.3.4 (#1, Dec 11 2007, 05:28:55) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] -------------------------------------------------------------------- --- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok ... but if I try and build it I receive the following error: /usr/bin/ld: /usr/local/lib/libjpeg.a(jcparam.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC How do I fix this? I am currently running "python setup.py build" and don't understand how I would change the compiling options to add the "- fPIC" flag. I'm quite a newbie when it comes to Linux/Python so any help you could give me would be great. Thanks, Nick From castironpi at gmail.com Wed Mar 5 13:58:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 10:58:38 -0800 (PST) Subject: Dual look-up on keys? Message-ID: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> I want to hash values to keys. How do the alternatives compare? From gagsl-py2 at yahoo.com.ar Thu Mar 6 07:10:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 10:10:23 -0200 Subject: Display all variable/function bindings in Python Shell References: <16803ed0803060010l64444a76o281411d323284b36@mail.gmail.com> Message-ID: En Thu, 06 Mar 2008 06:10:22 -0200, Sanjaya Vitharana escribi?: > 1.) Are there any way to display all variable/function bindings in Python > Shell ? dir() dir(some_object) help(some_object) vars(some_object) > 2.) Are the any way to Search "Python-list Archives" before sending > simple > question to the list ? Use the Google interfase to this newsgroup: http://groups.google.com/group/comp.lang.python/ -- Gabriel Genellina From software at ginstrom.com Mon Mar 24 21:39:44 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 25 Mar 2008 10:39:44 +0900 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: <08fd01c88e19$1a91aba0$0203a8c0@MOUSE> > On Behalf Of john s. > import os, sys, string, copy, getopt, linecache > from traceback import format_exception > > #The file we read in... > fileHandle = "/etc/passwd" > srcFile = open(fileHandle,'r') > srcList = srcFile.readlines() > > #yah, a for loop that "iterates" through the file of "lines" > for i in srcList: > strUsr = string.split(i,":") > theUsr = strUsr[0] > usrHome = "/expirt/home/",theUsr,"/" > usrHome = ''.join(usrHome) How about for starters: import os for line in open("/etc/passwd"): user, _pwd = line.split(":") user_home = os.path.join("/expirt/home", user) > try: > os.makedirs('usrHome' ) > except Exception, e: > print e if os.path.exists(user_home): print "User Home dir exists, checking and fixing permissions." else: print "Do other stuff" Regards, Ryan Ginstrom From bronger at physik.rwth-aachen.de Fri Mar 14 07:50:08 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 14 Mar 2008 12:50:08 +0100 Subject: anydbm and sync'ing Message-ID: <871w6dr0cv.fsf@physik.rwth-aachen.de> Hall?chen! A TurboGears process opens a DB file with anydbm and keeps it open. The the same time, this file is updated by another process. How can I tell the TurboGears process to fetch the new values? my_db.sync() didn't help -- apparently, it only *writes* to the DB file but doesn't read new data from it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From Scott.Daniels at Acm.Org Thu Mar 27 00:04:23 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 26 Mar 2008 21:04:23 -0700 Subject: Can my own objects support tuple unpacking? In-Reply-To: References: Message-ID: <13um6p08v0ea9f3@corp.supernews.com> Patrick Toomey wrote: > ... I am trying to figure out how tuple unpacking behavior works.... > a,b,c,d = e > > Is a method called, such as __getitem__ for each index on the left > (0,1,2,3)? I thought this was logical, ... > > class Foo: > def __getitem__(self, index): > print index > return 1 _So_ close. class Foo(object): # _Never_ use old-style without a reason def __getitem__(self, index): print index if index < 3: return index * 5 # just to see raise IndexError('Zapped') # The secret -- run out. -Scott David Daniels Scott.Daniels at Acm.Org From castironpi at gmail.com Mon Mar 10 02:53:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 23:53:31 -0700 (PDT) Subject: image matching algorithms References: Message-ID: <1ff9e1a3-ba36-4f0e-a283-754e4ec7c3b6@d62g2000hsf.googlegroups.com> On Mar 10, 1:32?am, "Daniel Fetchinson" wrote: > Hi all, > > There are a number of free tools for image matching but it's not very > easy to decipher the actual algorithm from the code that includes db > management, GUI, etc, etc. I have my own image database and GUI so all > I need is the actual algorithm preferably in pseudo code and not in > the form of a research paper (from which I also found a lot but since > I'm not that much interested in the actual science of image > recognition this seems like an over kill). > > My understanding of image matching is that it works by first > calculating N real numbers for an image and defining a metric for > pairs of N-tuples. Images are similar if their distance (defined by > the metric) is small. > > The various free tools differ by their chosen optimization paths and > their degree of specialization. My preference would be, > > 1. Doesn't really matter how long it takes to compute the N numbers per image > 2. Lookups should be fast, consequently N should not be too large (I guess) > 3. It should be a generic algorithm working on generic images (everyday photos) > 4. PIL should be enough for the implementation http://www.idi.ntnu.no/~blake/gbimpdet.htm "High level features carry information about an image in an abstracted or propositional form" It says it constructs a graph about the image's features. Here's the graph: Graph components Notes [A[@id=crot3.77;ext:sqr:aa(1659):mm(19815,148,0,0): <- Leading node cg(62,86):cr(255,153,153):pl(-204,574,792,10353)]] with attributes [[5][@rep= 1 ]] <- Relation and strength [B[@id=crot3.77;ext:sqr:aa(199):mm(17759,244,1,0): <- Trailing node cg(98,77):cr(153,153,255):pl(966,2,258,-79198)]]$ with attributes It doesn't say what corner cases it leaves. "seem to provide" and "seems to be extremely flexible". I like this feature: - the equation of the best fitting plane Ax+By+Cz+D=0 to the range image data masked by the current region; Where does that get you? From Afro.Systems at gmail.com Tue Mar 25 14:47:05 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 11:47:05 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <07185819-2b2b-40c3-af26-f683edd57a79@d21g2000prf.googlegroups.com> Hi all, I would like to thank you all for all the suggestions. what I did was simply extending the super class data with data from its child using the id example, Foo.id = 1 is now = [1] and the FooSon does self.id.append(2) the system designer wanted inheritance+java and I wanted Python +Functional Programming i guess we will meet somewhere in the middle thanks again tzury From andreww at datanet.ab.ca Wed Mar 5 19:39:02 2008 From: andreww at datanet.ab.ca (Andrew Warkentin) Date: Wed, 05 Mar 2008 17:39:02 -0700 Subject: ActiveX in Webpage? In-Reply-To: References: Message-ID: <47CF3D26.9020007@datanet.ab.ca> Michael Wieher wrote: > Hello, > > I'm trying to design a python-based web-app from scratch, based on a > standalone MFC application. > Obviously I'll be wrapping a lot of C++ functionality in custom > extensions, but is anyone aware of any documentation/techniques that > could help me "drop" an ActiveX control into a webpage, and just use it? > That, or, of course, a solid bit of writing detailing the > idiosyncrasies of MFC-wrapped Py-Extensions would be useful as well. > > -Mike I would recommend against embedding ActiveX controls, especially if this web application is public (if it is internal, it's not as much of a problem, but you still might have problems later if you ever want to migrate off Windows). ActiveX controls are not only Windows-specific, but (mostly) IE-specific as well. Since you are developing it from scratch, I would say that you should do it right and use AJAX, or possibly Flash or Java applets, all of which are reasonably portable. From sjmachin at lexicon.net Mon Mar 10 00:07:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 9 Mar 2008 21:07:27 -0700 (PDT) Subject: Import - interpreter works but .py import does not References: <055c615e-3beb-4037-ab1e-02afeb38da40@e6g2000prf.googlegroups.com> Message-ID: <6476f149-f250-4844-8598-181b87f9ddeb@s13g2000prd.googlegroups.com> On Mar 10, 1:59 pm, John Boy wrote: > First post and very much a newbie to Python. Have 2.5 on Linux (GG). I > think I have set up PYTHONPATH correctly in that I can import a module > apply_bp and it complains about line 20 in apply_bp which is: > > import sys, aipy, numpy, os Please get used to showing the error message. "it complains about line x" is not very helpful. Fortunately in this case we can guess that it is "complaining" about inability to import either aipy or numpy (sys and os are built-in). > > At the interpreter prompt, however, I can import sys, numpy etc. and > can do dir() and see the entry points so I think my overall > installation is OK. > > Why does line not work ? More information please. At the interpreter prompt, do this: import sys sys.path import aipy; aipy.__file__ import numpy; numpy.__file__ and show us the result. Change the offending line in your apply_bp module to import sys print sys.path import os, aipy, numpy and show us ALL of the output. At the shell prompt, do whatever it takes to display the contents of PYTHONPATH, and show us the results. > Also I would have thought that when I pre- > imported sys et al that they would be in the symbol table so that the > import line would be a noop. The concept of "preimporting" a module is novel to me. Importing a module at the interpreter prompt doesn't persist when you exit the interpreter and then (implicitly) start up another interpreter task to run your script. Importing a module in your script puts the module in the script's namespace, which is quite distinct from the namespace of the apply_bp (or any other) module. If those two possibilities don't cover what you mean, please explain. From celoserpa at gmail.com Thu Mar 6 08:04:26 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Thu, 6 Mar 2008 10:04:26 -0300 Subject: Class context execution problems Message-ID: <1e5bcefd0803060504n5aa4970bh90092b57b0a106f0@mail.gmail.com> I'm using a class in a conext other than the subpackage in which it is located and I'm getting template lookup errors. This class expects to find a .pt file in a directory relative to its package. However, this class is normally used by other classes in the same namespace. class ObjectWidget: template = "templates/objectwidget.pt" However, I needed to import this class (ObjectWidget) from a class outside its namespace(package). Now, I think the class is running in the context of the file that is using it and so, the the class not finding the .pt file (I think becouse the class file is being contextualized to the currently running one which is outside the browser subpackage) how could I solve it? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From isolomon at solomonltd.com Sat Mar 1 19:56:40 2008 From: isolomon at solomonltd.com (Ira Solomon) Date: Sat, 01 Mar 2008 19:56:40 -0500 Subject: Book Recomendations Message-ID: I am an experienced programmer (40 years). I've done Algol (if you've heard of that you must be old too), PL/1, VB,VBA, a little C, and a few other odd languages (e.g. Taskmate). I'm interested in learning Python and have downloaded a slew of books. Too many. I'd like a recommendation as to which books are considered to be the cream of the crop. I know there are tutorials on the web, but, again, I don't know the quality. I would appreciate recommendations on those as well. Thanks Ira From durieux_br at yahoo.com.br Thu Mar 27 15:17:21 2008 From: durieux_br at yahoo.com.br (Fabio Durieux Lopes) Date: Thu, 27 Mar 2008 19:17:21 -0000 Subject: Time problem (again) Message-ID: Hi, I'm recreating a date-time based on a string and I have a problem when daylight savings time is set (I'm off by 1). So today I forced my computer into daylight savings time and debugged it again, but this time I noticed something strange. This is the documentation from python library reference section 6.10: 6.10 time -- Time access and conversions ... daylight Nonzero if a DST timezone is defined. ... And this is what I debugged: -> fileTimeInSecs = time.mktime(time.strptime(timeString, "%Y%m%d%H%M")) (Pdb) p timeString '200803271643' (Pdb) n > /home/salsa/Projects/TimBR_CDR/fileSync/ fileSynchronizer.py(50)passFilesOlderThan() -> print time.daylight (Pdb) 0 See how 'print time.daylight' resulted in '0'? Shouldn't it be Non- zero? Do I have to set something for it to use DST? Also, is this the right list to send questions? From arnodel at googlemail.com Mon Mar 10 17:52:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Mar 2008 14:52:45 -0700 (PDT) Subject: any chance regular expressions are cached? References: <13t9bbap76cbdf3@corp.supernews.com> Message-ID: On Mar 10, 3:39?am, Steven D'Aprano wrote: [...] > Having said that, at least four out of the five examples you give are > good examples of when you SHOULDN'T use regexes. > > re.sub(r'\n','\n'+spaces,s) > > is better written as s.replace('\n', '\n'+spaces). Don't believe me? > Check this out: > > >>> s = 'hello\nworld' > >>> spaces = " ? " > >>> from timeit import Timer > >>> Timer("re.sub('\\n', '\\n'+spaces, s)", > > ... "import re;from __main__ import s, spaces").timeit() > 7.4031901359558105>>> Timer("s.replace('\\n', '\\n'+spaces)", > > ... "import re;from __main__ import s, spaces").timeit() > 1.6208670139312744 > > The regex is nearly five times slower than the simple string replacement. I agree that the second version is better, but most of the time in the first one is spend compiling the regexp, so the comparison is not really fair: >>> s = 'hello\nworld' >>> spaces = " " >>> import re >>> r = re.compile('\\n') >>> from timeit import Timer >>> Timer("r.sub('\\n'+spaces, s)", "from __main__ import r,spaces,s").timeit() 1.7726190090179443 >>> Timer("s.replace('\\n', '\\n'+spaces)", "from __main__ import s, spaces").timeit() 0.76739501953125 >>> Timer("re.sub('\\n', '\\n'+spaces, s)", "from __main__ import re, s, spaces").timeit() 4.3669700622558594 >>> Regexps are still more than twice slower. -- Arnaud From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:34:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:34:36 -0300 Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> <654k1kF2e8bnuU1@mid.uni-berlin.de> Message-ID: En Fri, 28 Mar 2008 13:17:44 -0300, Diez B. Roggisch escribi?: > pianomaestro at gmail.com schrieb: >> I have an extension module that gets initialized multiple >> times because I am using threads. >> >> How can this module access global state (not per-thread state) ? >> It needs to create a singleton. > > The question is very unclear. > > If you are after *not* initializing your module concurrently, why don't > you just do it *once* before the threads are started? alternatively, you > need to govern the initialization-code with a mutex - or anything > similar. Ouch... The simple "if (foo!=NULL)" I posted earlier is not thread safe and should not be used in this situation. Do as Diez said. -- Gabriel Genellina From sophacles at gmail.com Thu Mar 13 01:40:03 2008 From: sophacles at gmail.com (Erich) Date: Wed, 12 Mar 2008 22:40:03 -0700 (PDT) Subject: Generator woes References: Message-ID: On Mar 13, 12:33 am, Erich wrote: > Hi all, > > I am trying to get the following generator to work to these goals: > > 1. When it recieves an exception (via a throw()) it yeilds the value > of handler.remaining. Otherwise it yeilds None. > 2. Send adds data to the generator. > > Goal 2 is working great. Goal 1 on the other hand, is not working. The > result of a throw is always None. > > Any reasons why this does not work as I expect? If not, what is wrong? > > Code: > def make_handler(): > def handler(): > eol = '\r\n' > > handler.remaining = 1 > response = '' > data = '' > > while not response.endswith(eol): > trv = None > try: > ndata = (yield trv) > if ndata: response += ndata > trv = None > except: > trv = handler.remaining > response = response.strip() > yield response * 2 > res = handler() > res.next() > return res > > x = make_handler() > y = x.send('a') > print 'y (should be None):',y > y = x.send('b') > print 'y (should be None):',y > y = x.throw(Exception) > print 'y (should be 1):',y > y = x.send('c\r\n') > print 'y (should be abcabc):',y > > Output: > y (should be None): None > y (should be None): None > y (should be 1): None > y (should be abcabc): abcabc > > Thanks, > Erich Never mind its obviously a case of "I need to look foolish before I can see the simple error". Im going to blush and hide now. Erich From xelapond at gmail.com Sun Mar 30 00:02:01 2008 From: xelapond at gmail.com (Alex Teiche) Date: Sat, 29 Mar 2008 21:02:01 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt Message-ID: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Hello, I am pretty new to Python, and have never learned C++. I am trying to implement the following thing into my python application: http://doc.trolltech.com/4.3/qsystemtrayicon.html Through PyQt. I have been using PyQt for awhile and I know how do use it, but I could not get this specific thing to work. Can someone give me some hints as to get it working in Python? Thanks a ton, Alex From mail2spj at yahoo.com Fri Mar 28 15:47:51 2008 From: mail2spj at yahoo.com (SPJ) Date: Fri, 28 Mar 2008 12:47:51 -0700 (PDT) Subject: Question regd downloading multipart mail using POP3 Message-ID: <118409.12220.qm@web50111.mail.re2.yahoo.com> I am facing a strange problem when I am trying to retrieve multipart mail from POP server with attachments. The task is to write a script which will retrieve mail with specific 'from' field. Get the subject, body and attachments if any and reuse this info to send mail with different format to ticketing system. The global variable values I am expecting is: msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so on attachmentList=[['none'],['attachname.txt','filename.pl']] where none is no attachments. But the result I am getting is: msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so on attachmentList=[[none],['none', 'attachname.txt', 'filename.pl']] An extra 'none' in the attachment list except for plain/text mails without attachments. I have tried a lot to figure out how to eliminate this but with no luck do far :( I know that some part is getting excluded from the condition, but I am unable to figure out what is causing this. Following is the function I wrote: I am not an expert programmer hence my code is not clean, so pl. bear with me. Thanks, SPJ ---------- import poplib, email, re, sys, os msgList = [] # Global list that contains messages PATH = Path to save file on disk # path were attachements will be stored attachmentName = [] # Name of attachements def popconnect(): # connect the pop server and send username and password pconnect = poplib.POP3(server) pconnect.user(user) pconnect.pass_(passwd) # Give connection status, msg list and total msg size status, msg_list, octets = pconnect.list() if len(msg_list) == 0: print "No messages in Mailbox" pass # regex for searching mails from example at example.com soc = re.compile(".*example\@example.com.*") # iterate over the number of new messages from counterpane and qppend the required fields # to a list. for msg_number in [msg.split(' ')[0] for msg in msg_list]: status, lines, octets = pconnect.retr(msg_number) msg1 = email.message_from_string('\n'.join(lines)) tmpList = [] attachList = [] attachnumber = 0 check1 = msg1.get('From') check2 = msg1.get('Subject') if soc.match(check1): subject = msg1.get('Subject') # Subject for only mails only after condition is true. if msg1.is_multipart(): for part in msg1.walk(): # multipart/* are just containers mptype = part.get_content_maintype() body = part.get_payload(decode=True) if mptype == "multipart": continue filename = part.get_filename() if filename: # Attached object with filename print 'in file ' +part.get_content_type() attachnumber += 1 tmpList[2] = attachnumber # number of attachments in message attachList.append(PATH+filename) # path to attachment # Copy the attachment to disk f = open(PATH + filename,"wb") f.write(part.get_payload(decode = True)) f.close() else: print part.get_content_type() if part.get_content_type() != ("text/html" or "text/plain" or "multipart/alternative" or "multipart/mixed"): tmpList.append(subject) # Subject from message tmpList.append(body) # Body from message tmpList.append(0)# If no attachments attachList.append('none') else: # Not multipart, only body portion exists print "Not Multipart\n" body=msg1.get_payload(decode=True) tmpList.append(subject) # Subject from message tmpList.append(body) tmpList.append(0) attachList.append('none') if len(tmpList) > 0: msgList.append(tmpList) if len(attachList) > 0: attachmentName.append(attachList) print msgList, attachmentName pconnect.quit() def main(): popconnect() if __name__== '__main__': main() ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From pavloutefkros at gmail.com Sun Mar 9 17:22:48 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 9 Mar 2008 14:22:48 -0700 (PDT) Subject: execute Message-ID: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> i'm trying to execute a file without replacing the current process, but after searching the help file, documentations and the web, i can't a way of doing that. os.exec*() will close the current program. ps: by executing i mean like typing "mspaint" in run dialog.. it's not a python file From gagsl-py2 at yahoo.com.ar Sat Mar 29 21:39:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 22:39:25 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <1b997415-b056-4378-be8d-b30dce938e20@s8g2000prg.googlegroups.com> <657v3lF2e7r7pU1@mid.uni-berlin.de> Message-ID: En Sat, 29 Mar 2008 19:45:09 -0300, Diez B. Roggisch escribi?: >> I suggest that you remove the simplejson-xxxxxx.egg file and delete the >> simplejson entry in easy-install.pth (both in your site-packages >> directory) >> Then extract the simplejson directory from inside the original .tar.gz >> archive into your site-packages directory (so you end up by example with >> a .../site-packages/simplejson/decoder.py file, among others) >> That appears to be enough; import simplejson worked fine for me. >> >> I hate those f****ng eggs. Ah, and I hate easy_install too. > > This has nothing to do with setuptools or easy_install per se. The > author of simplejson tried to create a library that works with or > without a C-extension. And failed. I think that the whole approach is doomed to fail; trying to do things more complicated that they should be. The pure-python part of simplejson is just a package. Copying the directory into site-packages is *ALL* that is required; distutils can do that perfectly. That's all folks!. A database or registry keeping track of installed product versions might be useful, too. Anything that does much more than that is just looking for problems; simple systems work better than complex ones. In this case, there is no need to create an egg, no need to play with .pth files, no need to slow down the package at import time (eggs must be decompressed), no need to extend sys.path and slow down *all* other imports. I don't feel that anything is better by using eggs or easy_install, and at least for me, they always have given more problems than answers. So, again, I hate eggs and easy_install. And I hate eggplants too. -- Gabriel Genellina From michele.simionato at gmail.com Sun Mar 2 11:35:31 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sun, 2 Mar 2008 08:35:31 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: On Mar 2, 5:23 pm, js wrote: > Hi, > > Have you ever seen Beautiful Python code? > Zope? Django? Python standard lib? or else? > > Please tell me what code you think it's stunning. The doctest module in the standard library. M.S. From michael.wieher at gmail.com Sat Mar 29 23:19:08 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sat, 29 Mar 2008 22:19:08 -0500 Subject: html DOM In-Reply-To: References: Message-ID: Was this not of any use? http://www.boddie.org.uk/python/HTML.html I think, since HTML is a sub-set of XML, any XML parser could be adapted to do this... I doubt there's an HTML-specific version, but I would imagine you could wrap any XML parser, or really, create your own that derives from the XML-parser-class... On Sat, Mar 29, 2008 at 6:09 PM, Sam the Cat wrote: > Is there a package that would allow me the same or similar functionality > for > modifying html code via the DOM model as I have in JavaScript ? I'd like > to > parse an html file, then modify it and save the result. I am not trying > to > do this online, rather I would like to do this on a batch of files stored > on > my hard drive. I have found several packages that allow me to parse and > dissect html but none that allow me to modify the object and save the > results -- perhaps I am overlooking the obvious > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Mar 28 18:55:57 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Mar 2008 22:55:57 GMT Subject: case insensitive lstrip function? References: <0eb666fe-8c3e-4a93-afbf-1953922c19bd@s13g2000prd.googlegroups.com> Message-ID: <655bbtF2e1u8fU2@mid.uni-berlin.de> On Fri, 28 Mar 2008 15:48:09 -0700, Kelie wrote: > Is there such a function included in the standard Python distribution? AFAIK not. > This is what I came up with. How to improve it? Thanks. > > def lstrip2(s, chars, ingoreCase = True): > if ingoreCase: > s2 = s.upper().lstrip(chars.upper()) > return s[len(s)-len(s2):] > else: > return s.lstrip(chars) What about this: def lstrip2(string, chars, ignore_case=True): if ignore_case: chars = chars.lower() + chars.upper() return string.lstrip(chars) Ciao, Marc 'BlackJack' Rintsch From gargonx at gmail.com Wed Mar 12 00:55:20 2008 From: gargonx at gmail.com (gargonx) Date: Tue, 11 Mar 2008 21:55:20 -0700 (PDT) Subject: Why no string return? References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: On Mar 12, 4:45 am, Adonis Vargas wrote: > gargonx wrote: > > Say i have the two methods: > > > def ReturnMethod(request, x): > > if request is True: > > return x > > else: print "No String for you...False!" > > > def SendMethod(request): > > xstring = "Some text" > > ReturnMethod(request, xstring) > > > SendMethod(True) > > > Why does ReturnMethod not return the string x? I do believe it is > > returning with a NoneType. > > Any help would be greatly obliged > > > Thanks, Josh > > That is because request is bound a string (str) object. You are probably > testing for null so it should look like: > > if request: > return x > else: > print "No String for you...False!" > > Hope this helps. > > Adonis Still no return of string. The null testing is not really the deal. that could be replaced with anything EG: def ReturnMethod(request, x): if request is 'random': return x else: print "No String for you...False!" def SendMethod(request): xstring = "Some text" ReturnMethod(request, xstring) SendMethod('random') From madduck at madduck.net Sun Mar 16 09:21:40 2008 From: madduck at madduck.net (martin f krafft) Date: Sun, 16 Mar 2008 14:21:40 +0100 Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? Message-ID: <20080316132140.GA24529@piper.oerlikon.madduck.net> Hi, xmlrpclib.dumps((None,), allow_none=True) yields '\n\n\n\n' Why doesn't it just yield '\n\n\n\n' Or even just '\n\n\n' Those are valid XML and valid XML-RPC, but isn't. Thanks for any thoughts... -- martin | http://madduck.net/ | http://two.sentenc.es/ a farmer is a man outstanding in his field. spamtraps: madduck.bogus at madduck.net -------------- next part -------------- A non-text attachment was scrubbed... Name: digital_signature_gpg.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature (see http://martin-krafft.net/gpg/) URL: From dboddie at trolltech.com Fri Mar 28 09:12:04 2008 From: dboddie at trolltech.com (David Boddie) Date: Fri, 28 Mar 2008 14:12:04 +0100 Subject: PyQT / QDate / QTableWidget Message-ID: <200803281412.04679.dboddie@trolltech.com> On Wed Mar 26 15:13:09 CET 2008, wrightee wrote: > My server gives me a string y[0]: "20080327", which I convert to a > QDateTime object using: > > x=QDateTime.fromString(y[0],"yyyymmdd") > > Printing x.toString("dd-mm-yyyy") gives me what I would expect - > 27-03-2008 Strange. You should really be using "dd-MM-yyyy". Maybe this is why QDate isn't behaving as you would expect - see below. > What I'm trying to do though is add this to a QTableWidget item to > create a date sortable column; I'm using this: > > if type(y)==QDateTime: > item=QTableWidgetItem() > item.setData(Qt.DisplayRole,QVariant(y)) This should work fine. > BUT.. I'm adding 90 dates going back from today and getting values > that look like this: > > 27/01/2007 00:12 > 28/01/2007 00:12 > 29/01/2007 00:12 > 30/01/2007 00:12 > 31/01/2007 00:12 > 01/01/2008 00:01 > 01/01/2008 00:02 > 01/01/2008 00:03 > > etc Right. You can see the date and time because you're using a QDateTime object. > I tried using QDate but couldn't seem to be able to get > QDate.fromString to create an object at all. This may have something to do with the format string you tried. > Could someone please advise where I'm going wrong, the end result > should be a column in my QTableWidget formatted dd/mm/yyyy that can be > sorted as dates, not strings, and originate from data formatted > "YYYYMMDD" Just use QDate objects instead of QDateTime objects and it should all just work. Good luck! David -- David Boddie Lead Technical Writer, Trolltech ASA From paul.nospam at rudin.co.uk Thu Mar 13 04:54:43 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 13 Mar 2008 08:54:43 +0000 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: <87skyvuhpo.fsf@rudin.co.uk> Antoon Pardon writes: > On 2008-02-28, Steven D'Aprano wrote: >> On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: >> >>> Hi! >>> Can somebody of you make me a sample how to define a function based on >>> "call by reference" ??? >> >> Python doesn't do call by reference. Nor does it do call by value. Please >> pay no attention to anyone who says it does. > > Whatever python has for a calling convention, it is close enough that > naming it "call by reference" gives people a reasonable idea of what > is going on. Quite. The thing is not to get hung up with the label - but to understand what actually happens. From mblume at freesurf.ch Tue Mar 18 12:53:55 2008 From: mblume at freesurf.ch (Martin Blume) Date: Tue, 18 Mar 2008 17:53:55 +0100 Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com><47dd579d$0$9035$5402220f@news.sunrise.ch><3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com><47dd5caf$0$9029$5402220f@news.sunrise.ch> <646judF2ao2tkU1@mid.uni-berlin.de> Message-ID: <47dff3a3$0$9030$5402220f@news.sunrise.ch> "Marc 'BlackJack' Rintsch" schrieb > > > I don't think this qualifies as a bug, but I am astonished > > that the struct module does not tell you whether you are > > big endian, you have to find out yourself with > > struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] > > Maybe a little more compact and readable: > > In [92]: sys.byteorder > Out[92]: 'little' > Yes, indeed it is more compact and readable. Thanks. Martin From testone at gmail.com Mon Mar 24 19:32:24 2008 From: testone at gmail.com (Tess) Date: Mon, 24 Mar 2008 16:32:24 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question Message-ID: Hello All, I have a Beautiful Soup question and I'd appreciate any guidance the forum can provide. Let's say I have a file that looks at file.html pasted below. My goal is to extract all elements where the following is true:

and

. The lines should be ordered in the same order as they appear in the file - therefore the output file would look like output.txt below. I experimented with something similar to this code: for i in soup.findAll('p', align="left"): print i for i in soup.findAll('p', align="center"): print i I get something like this:

P4

P3

P1

div4b
div3b
div2b
div2a
Any guidance would be greatly appreciated. Best, Ira ##########begin: file.html############

P1

P2

div2a
div2b

P3

div3a
div3b
div3c

P4

div4a
div4b
##########end: file.html############ ===================begin: output.txt===================

P1

div2a
div2b

P3

div3b

P4

div4b
===================end: output.txt=================== From bj_666 at gmx.net Mon Mar 3 01:55:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Mar 2008 06:55:35 GMT Subject: Is it possible to return a variable and use it...? References: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> Message-ID: <631ln7F25g4d2U2@mid.uni-berlin.de> On Sun, 02 Mar 2008 20:15:10 -0800, Nathan Pinno wrote: > Hello all, > > Is it possible to return a variable and then use it like the > following: > [code] > dir exp_1: > while hen != "*" > sum = sum + hen > return sum > > dir exp_2: > if sum >= total_needed: > print "Profit can be made." > else: > print "Expect a loss." > > total_needed = int(raw_input("What is the total eggs needed? ")) > hen = int(raw_input("How many eggs did each hen lay? Enter them in 1 > by 1 or enter * when done. ")) > exp_1 > exp_2 > > [/code] > > If not, then how do I do so? Please work through the tutorial, then try to write actual Python code and come back if you have problems with your implementation of the program. Show us the real code and a description of either what error message you get, with full traceback, or if it does not raise an exception but just does not what you excpect it to do, tell us what you expected and what you get instead. Ciao, Marc 'BlackJack' Rintsch From aahz at pythoncraft.com Wed Mar 5 10:36:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 5 Mar 2008 07:36:37 -0800 Subject: OT: Failed saving throw Message-ID: For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people think we should build a tomb in his honor. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From spamspam at spam.eggs Sun Mar 23 06:38:07 2008 From: spamspam at spam.eggs (Ben C) Date: Sun, 23 Mar 2008 05:38:07 -0500 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> Message-ID: On 2008-03-22, bsoist wrote: > On Mar 22, 12:40 pm, jmDesktop wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. >> >> Thank you. > > Absolutely. I love using Python in "the real world" but it is > fantastic for beginning programmers. > > Python enforces good habits and presents many opportunities to discuss > programming from an academic perspective. Why does Python not have a > switch or until statement? Why doesn't it? > Why are very common objects (stack, queue, > linked list) not builtin? etc. I think I know this one: you just use builtin lists to do stacks, queues and, er, lists. From Graham.Dumpleton at gmail.com Tue Mar 18 21:26:37 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 18 Mar 2008 18:26:37 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> Message-ID: <7900f1db-16a5-45d1-ada3-962ac0e712b8@e6g2000prf.googlegroups.com> On Mar 19, 9:47 am, geert wrote: > On Mar 18, 6:56 pm, geert wrote: > > > > > On Mar 14, 1:15 pm, martin.lal... at gmail.com wrote: > > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > > Just wanted to let you know that I've solved my problem. The solution > > is to compile mysql using > > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > ./configure --disable-dependency-tracking --enable-thread-safe-client > > --prefix=/usr/local/mysql > > > You then go this way to get it running on your machine: > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > > Then reinstall MySQLdb. Magic! > > > Geert > > Seems that I've yelled success to quickly. Everything's ok as long as > I just run the django dev server, but moving to apache throughmod_wsgibrings a well-known but less than comforting complaint: > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352): > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ > LN/LNApache.wsgi'., referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent > call last):, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in > __call__, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > self.get_response(request), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in > get_response, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response = > middleware_method(request), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line > 13, in process_request, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine = > __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line > 2, in , referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from > django.contrib.sessions.models import Session, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, > in , referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db > import models, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/db/__init__.py", line 17, in , > referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend = > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, > {}, ['']), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] File "/Library/ > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, > in , referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no > suitable image found. Did find:, referer:http://localhost/images/ > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- > tmp/_mysql.so: no matching architecture in universal wrapper, referer:http://localhost/images/ Did you again confirm that running: file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5- macosx-10.5-i386.egg-tmp/_mysql.so shows the .so having the required architectures, specifically what Apache runs as (eg. x86_64)? Do the gcc compiler flags when building and linking the .so file show all the architecture flags? Have you empty the Python egg cache to make sure it isn't an older compiled version? Graham From tmp1 at viltersten.com Sat Mar 1 19:43:05 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 01:43:05 +0100 Subject: SV: Where's GUI for Python? In-Reply-To: <13sjn6gn3houdaa@corp.supernews.com> References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> Message-ID: <62uai0F24sc4aU1@mid.individual.net> >> import tkininter >> > When that fails, try without the stutter > > import tkinter I must be doing something wrong because neither tkinter nor tkininter works. I tried both with and without stuttering. I even asked my wife to stutter some but, sadly, to no avail. When Tim Chase mentioned "battery-installed", i interpreted it as "all is there". It seems that either a) not all the batteries are installed in my version (v2.5.2) or b) some setup/linkage needs to be performed in order to get the GUI running. The error itself is: ImportError: No module named tkinter Suggestions? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From danb_83 at yahoo.com Wed Mar 5 21:35:12 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 5 Mar 2008 18:35:12 -0800 (PST) Subject: Why """, not '''? References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> Message-ID: <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> On Mar 5, 7:24 pm, Matt Nordhoff wrote: > Steven D'Aprano wrote: > > Surely it would depend on the type of text: pick up any random English > > novel containing dialogue, and you're likely to find a couple of dozen > > pairs of quotation marks per page, against a few apostrophes. > > That's an idea... Write a novel in Python docstrings. Or better yet, write in Python syntax. assert len([man for man in now_alive() if man.remembers(datetime.date(1775, 4, 18))]) <= HARDLY lantern_count = {'land': 1, 'sea': 2}.get(british.location(), 0) n_ch_twr.hang(Lantern() for _ in xrange(lantern_count)) if lantern_count: for village in middlesex: ride_thru(village) spread_alarm(village) From vedrandekovic at gmail.com Thu Mar 27 05:00:26 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Thu, 27 Mar 2008 02:00:26 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: On 26 o?u, 20:11, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 15:38:16 -0300, Tzury Bar Yochay > escribi?: > > >> ....and then when my application execute code how can I set path to > >> d3dx module to "library.zip/d3dx.py". > >> I'm not sure is this properly set question. > > > use the module zipimport > >http://docs.python.org/lib/module-zipimport.html > > You don't have to do anything special to "use" zipimport; from > : > "It is usually not needed to use the zipimport module explicitly; it is > automatically used by the builtin import mechanism" > > -- > Gabriel Genellina Hello, I was add this into my application code: import sys import os my_dir=os.getcwd() sys.path.append(my_dir) sys.path.append(my_dir+"\\libary.zip") sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder f=open("path.txt","w") f.write(str(sys.path)) f.close() an the output in path.txt is : ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ \libary.zip\\py2exe'] But it still can't find module py2exe.What should I do now? Any examples? Regards, Vedran From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 26 06:19:49 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 26 Mar 2008 11:19:49 +0100 Subject: Beta testers needed for a high performance Python application server In-Reply-To: References: Message-ID: <47ea233f$0$31890$426a34cc@news.free.fr> Minor Gordon a ?crit : (snip otherwise intersting stuff) > Background: I'm in this to help write a "story" for Python and web > applications. Everyone likes to go on about Ruby on Rails, and as far as > I can tell there's nothing that approaches Rails in Python. You may have missed Django and Pylons then. > Beta testers: should be intermediate to advanced Python programmers with > demanding applications, particularly web applications with databases and > AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory > libraries beyond python-dev. > > Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. I can only second Graham here: setup a project page with source code downloads, install instructions and (at least minimal) software documentation, and if possible a tracker. From arulprakash012 at gmail.com Mon Mar 17 08:30:09 2008 From: arulprakash012 at gmail.com (arulprakash012 at gmail.com) Date: Mon, 17 Mar 2008 05:30:09 -0700 (PDT) Subject: I WANT YOU Message-ID: <42707e88-2c0e-4135-a562-1da85420145d@i29g2000prf.googlegroups.com> I WANT YOU I LIKE YOU PLEASE CLICH THIS: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ http://myprofile3210.blogspot.com $$$$$$$$$$$$$$$$$$$$$$$$$$$$$ From shakefu at gmail.com Fri Mar 7 17:22:07 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:22:07 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: On Mar 7, 4:10 pm, Mike Driscoll wrote: > On Mar 7, 4:08 pm, shak... at gmail.com wrote: > > > I'm new to python and I was wondering if there are any intelligent > > date/time parsing modules out there. I've looked at strptime (or > > whichever it is) and mxDateTime from the eGenix package. I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > > So are there any modules that allow for that kind of parsing? > > There's the dateutil module that's a fancy wrapper for the datetime > module. The author's site has lots of examples as well as the source: > > http://labix.org/python-dateutil > > I use it quite a bit. > > HTH > > Mike So close - I tried it in the interpreter it works great for most things (like "10pm tuesday") but I'm really hoping for something that'll work with generics like "tomorrow", "yesterday", "last tuesday", "next month", etc. Although I know that's pretty language specific. I was just sort of wishing someone had written it before me... maybe? Possibly? Although if I end up writing my own I'll sure use datetime.parser.parse to get everything left over once you remove strings like "this saturday". So it helps a little! Jacob From castironpi at gmail.com Tue Mar 4 21:30:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 18:30:26 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: On Mar 4, 8:11?pm, "Gabriel Genellina" wrote: > En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: > > >> > So, to answer your question: what you are decorating are functions, ? > >> not > >> > methods. > > >> Can you overload -type-'s decision of what to 'bind'?... whenever it > >> is it makes it. > > >>>> from types import FunctionType, MethodType > >>>> class A( FunctionType ): pass > > ... > > Traceback (most recent call last): > > ? File "", line 1, in > > TypeError: type 'function' is not an acceptable base type > > Use delegation instead of inheritance. This class is almost ? > indistinguishable from a true function (when used as a method): > > py> class myfunction(object): > ... ? __slots__ = ('func',) > ... ? # > ... ? def __init__(self, func): > ... ? ? object.__setattr__(self, 'func', func) > ... ? # > ... ? def __get__(self, instance, owner): > ... ? ? print "__get__ called for",instance > ... ? ? return self.func.__get__(instance, owner) > ... ? # > ... ? def __getattr__(self, name): > ... ? ? return getattr(self.func, name) > ... ? # > ... ? def __setattr__(self, name, value): > ... ? ? object.__setattr__(self.func, name, value) > ... > py> > py> class P(object): > ... ? def foo(self, x): print 'foo',x > ... ? # > ... ? @myfunction > ... ? def bar(self, x): print 'bar',x > ... > py> p = P() > py> p.foo(1) > foo 1 > py> p.bar(2) > __get__ called for <__main__.P object at 0x00A3D650> > bar 2 > py> P.foo(p, 1) > foo 1 > py> P.bar(p, 2) > __get__ called for None > bar 2 > py> print "p.foo", p.foo, type(p.foo) > p.foo > 'instancem > ethod'> > py> print "p.bar", p.bar, type(p.bar) > p.bar __get__ called for <__main__.P object at 0x00A3D650> > > __get__ called ? > for <__ > main__.P object at 0x00A3D650> > > py> print set(dir(p.foo))==set(dir(p.bar)) > __get__ called for <__main__.P object at 0x00A3D650> > True > py> print "P.foo", P.foo, type(P.foo) > P.foo > py> print "P.bar", P.bar, type(P.bar) > P.bar __get__ called for None > __get__ called for None > > py> print set(dir(P.foo))==set(dir(P.bar)) > __get__ called for None > True > py> P.__dict__['foo'] > > py> P.__dict__['bar'] > <__main__.myfunction object at 0x00A3D690> > > Ok, let's try returning a different thing from __get__: bound method -> ? > partial with self already bound; unbound method -> the original function. > > py> from functools import partial > py> > py> class myfunction2(myfunction): > ... ? def __get__(self, instance, owner): > ... ? ? if instance is None: > ... ? ? ? ? return self.func > ... ? ? return partial(self.func, instance) > ... > py> @myfunction2 > ... def baz(self, x): print 'baz',x > ... > py> P.baz = baz > py> print p.baz > > py> print P.baz > > py> p.baz(3) > baz 3 > py> P.baz(p,3) > baz 3 > > -- > Gabriel Genellina I actually don't believe you-- bar is not bound to an instance when P is initialized... er, instantiated. However, the evidence indicates my belief mechanism is faulty... and rather conclusively at that. If P calls __get__( you ), is p a gotcha? From kyosohma at gmail.com Mon Mar 31 13:18:06 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 10:18:06 -0700 (PDT) Subject: Automatically fill in forms on line References: Message-ID: On Mar 31, 11:50 am, "Jackie Wang" wrote: > Dear all, > > I want to automatically complete the following task: > > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx; > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > Highway 102"; > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > 4. Click the bottom "search"; > 5. In the opened page, extract and save the number after "Tract Code". > In the example, it will be "9659". > 6. Repeat Step 1 with a new address. > > Can Python realize these steps? Can these steps be done witout > openning and IE windows? Especially, I dont know how to write code for > step 2, 4 and 5. > > Thank you! You might take a look at PAMIE: http://pamie.sourceforge.net/ or ClientForm: http://wwwsearch.sourceforge.net/ClientForm/ Those are what are usually recommended. Mike From coolman.guron at gmail.com Tue Mar 11 10:24:52 2008 From: coolman.guron at gmail.com (binaryj) Date: Tue, 11 Mar 2008 07:24:52 -0700 (PDT) Subject: how to theme/skin pyGtk apps Message-ID: hi again dear group. what i am interested in is giving my pygtk app some distinct look, a lil childish look coz the app is for children. so, i downloaded a couple of themes from http://art.gnome.org/themes/gtk2/ and for the past 1 hr i have been trying to theme my app but with no results. could anyone please guide me on who to theme pygtk and code samples would be greatly appreciated thanks binary-j From jkugler at bigfoot.com Wed Mar 26 18:03:11 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Wed, 26 Mar 2008 14:03:11 -0800 Subject: Not understanding lamdas and scoping References: Message-ID: George Sakkis wrote: > On Mar 26, 5:02 pm, Joshua Kugler wrote: > >> I am trying to use lamdba to generate some functions, and it is not >> working >> the way I'd expect. The code is below, followed by the results I'm >> getting. More comments below that. >> >> (...) >> >> So, is there some scoping issue with lambda >> that I'm not seeing? > > Yes; it's not related to lambda though but to closures (whether > defined as lambdas or regular functions). See for example > http://groups.google.com/group/comp.lang.python/browse_frm/thread/94d1bba8ad56baf4 > > There should be an entry for this at > http://www.python.org/doc/faq/programming/, that's really an FAQ. George - Thanks for the quick and clear answer...that makes perfect sense. To bad...I'd like to just use a list comprehension. :) j From castironpi at gmail.com Wed Mar 5 13:50:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 10:50:12 -0800 (PST) Subject: What is a class? Message-ID: What is a class that is not a module? From ACooper at cimtek.com Tue Mar 11 19:33:35 2008 From: ACooper at cimtek.com (Cooper, Andrew) Date: Tue, 11 Mar 2008 19:33:35 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: <21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> <21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: The part I'm having problem with is as follows: I want to replace the 'strcmp' below with a call to PyObject_IsInstance(o, pinClassPyObject) But I don't know how to get the PyObject* for the Pin class that is defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list From: python-list-bounces+acooper=cimtek.com at python.org [mailto:python-list-bounces+acooper=cimtek.com at python.org] On Behalf Of Bronner, Gregory Sent: 11 March 2008 20:52 To: Michael Wieher; python-list at python.org; accooper at cimtek.com Subject: RE: Obtaining the PyObject * of a class I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list at python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mithrandi at mithrandi.net Thu Mar 27 23:15:02 2008 From: mithrandi at mithrandi.net (Tristan Seligmann) Date: Fri, 28 Mar 2008 05:15:02 +0200 Subject: [Twisted-web] [ANN] Twisted 8.0 In-Reply-To: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> References: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> Message-ID: <20080328031502.GA22852@mithrandi.net> * Christopher Armstrong [2008-03-26 21:26:11 -0400]: > http://twistedmatrix.com/ > > MASSACHUSETTS (DP) -- Version 8.0 of the Twisted networking framework > has been released, Twisted Matrix Laboratories announced Wednesday. I just have to say that I enjoyed reading this release mail far more than any other one I can recall :) -- mithrandi, i Ainil en-Balandor, a faer Ambar -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From gh at ghaering.de Thu Mar 13 18:03:08 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 13 Mar 2008 23:03:08 +0100 Subject: [pysqlite] [ANN] pysqlite and APSW projects moved In-Reply-To: <47d8f707$0$26041$88260bb3@free.teranews.com> References: <47d8f707$0$26041$88260bb3@free.teranews.com> Message-ID: <63tmkqF28loi7U1@mid.uni-berlin.de> Colin Mcphail wrote: > On 2008-03-09 18:57:00 +0000, Gerhard H?ring said: > > Gerhard H?ring wrote: >>>> [...] APSW >>>> ==== >>>> >>>> web: http://oss.itsystementwicklung.de/trac/apsw/ >>>> scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ > > That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ > > -- Gerhard > I'm getting 404 Not Found for the 'corrected' apsw web page URL. Also, > the subversion URL doesn't seem right either: > $ svn co http://initd.org/svn/pysqlite/apsw/trunk/ apsw > svn: PROPFIND request failed on '/svn/pysqlite/apsw/trunk' > svn: PROPFIND of '/svn/pysqlite/apsw/trunk': 403 Forbidden > (http://initd.org) Roger Binns changed his mind and moved APSW to Google Code: http://code.google.com/p/apsw/ -- Gerhard From mnordhoff at mattnordhoff.com Wed Mar 5 20:24:10 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 06 Mar 2008 01:24:10 +0000 Subject: [OT] Re: Why """, not '''? In-Reply-To: <13sudd49au3e1c1@corp.supernews.com> References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> Message-ID: <47CF47BA.8030405@mattnordhoff.com> Steven D'Aprano wrote: > Surely it would depend on the type of text: pick up any random English > novel containing dialogue, and you're likely to find a couple of dozen > pairs of quotation marks per page, against a few apostrophes. That's an idea... Write a novel in Python docstrings. Someone make me go to bed now. -- From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 04:14:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Mar 2008 08:14:49 -0000 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> Message-ID: <13uc4bpb0b564af@corp.supernews.com> On Sat, 22 Mar 2008 23:15:00 -0700, John Nagle wrote: > That's some professor inventing his very own variation on predicate > calculus and writing a book using his own notation and terminology. > There's no sign of footnotes or references to prior work. The notation > doesn't seem to do anything not previously possible; it's just > different. You say that as if it were unusual in maths circles :) -- Steven From NoelByron at gmx.net Tue Mar 11 04:45:24 2008 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: Tue, 11 Mar 2008 01:45:24 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: Hi Malcom On Mar 10, 4:27?pm, "Malcolm Greene" wrote: > I'm new to Python and getting ready to build a small client based > application intended to run on Windows and Linux. I was planning on > using wxPython until I saw your comment above. We use wxPython and Python internally in the company without any mayor problems or crashes. It seems quite solid. But errors happen in complex systems. And if for example a crash occurs it would be good to know the reason and to track it down. And that is hard in Python with C extensions. That does not only apply to wxPython but to all other (GUI) libraries with C parts, too. At least we will not switch to something else then wxPython. Best regards, Noel From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 13:22:11 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 18:22:11 +0100 Subject: And the reverse? Does os also import os.path? In-Reply-To: References: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> Message-ID: <47ebd7b4$0$19836$426a74cc@news.free.fr> Wilbert Berendsen a ?crit : > If i do > >>>> import os >>>> os.path.abspath("bla") > '/home/wilbert/bla' > > it seems that just import os also makes available al os.path functions. > > But is that always true? Nope. Not all packages expose their sub-packages. From jef.mangelschots at gmail.com Tue Mar 4 16:12:18 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 4 Mar 2008 13:12:18 -0800 (PST) Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> <3319005c-98b9-44a0-96dc-72db45f2ae27@z17g2000hsg.googlegroups.com> Message-ID: > on windows using python 2.4. ??? yes, as a matter of fact I am. Did not feel the need to switch to 2.5 yet. I'm gonna give this a try, but it requires me to dig up 2.5 versions of the libraries i am using. (one of them didn't at the time and that is why I stuck to 2.4) From phil at riverbankcomputing.com Sun Mar 30 05:08:06 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sun, 30 Mar 2008 09:08:06 +0000 Subject: Using QSystemTrayIcon with PyQt In-Reply-To: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: <200803301008.06482.phil@riverbankcomputing.com> On Sunday 30 March 2008, Alex Teiche wrote: > Hello, > > I am pretty new to Python, and have never learned C++. I am trying to > implement the following thing into my python application: > > http://doc.trolltech.com/4.3/qsystemtrayicon.html > > Through PyQt. I have been using PyQt for awhile and I know how do use > it, but I could not get this specific thing to work. Can someone give > me some hints as to get it working in Python? > > Thanks a ton, > > Alex Have you looked at PyQt's systray example? Phil From software at ginstrom.com Tue Mar 18 06:24:50 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 18 Mar 2008 19:24:50 +0900 Subject: Decode email subjects into unicode In-Reply-To: <47DF8EED.1010501@shopzeus.com> References: <47DF8EED.1010501@shopzeus.com> Message-ID: <017d01c888e2$4cfc9ff0$0203a8c0@MOUSE> > On Behalf Of Laszlo Nagy > > =?koi8-r?B?4tnT1NLP19nQz8zOyc3PIMkgzcHMz9rB1NLB1M7P?= > > [Fwd: re:Flags Of The World, Us States, And Military] > > =?ISO-8859-2?Q?=E9rdekes?= =?UTF-8?B?aGliw6Fr?= Try this code: from email.header import decode_header def getheader(header_text, default="ascii"): """Decode the specified header""" headers = decode_header(header_text) header_sections = [unicode(text, charset or default) for text, charset in headers] return u"".join(header_sections) I get the following output for your strings: ??????????????? ? ???????????? ?rdekeshib?k Regards, Ryan Ginstrom From blwatson at gmail.com Fri Mar 28 15:14:07 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Fri, 28 Mar 2008 12:14:07 -0700 (PDT) Subject: Installing simplejson issues Message-ID: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> I am trying to install the twitter python wrapper...I got that installed just fine, but am having serious troubles getting the simplejson package to install. I need help diagnosing where this is failing. I am trying to use: http://pypi.python.org/pypi/simplejson and I run "python setup.py build" and then "python setup.py install", which both seem to work just fine. I tried running with easy_install, but that too is not working. I end up with: simplejson-1.8.1-py2.5-macosx-10.3-fat.egg in my: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/ I am on Mac OS X 10.5. Any help would be greatly appreciated. From bockman at virgilio.it Wed Mar 5 03:41:56 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 5 Mar 2008 00:41:56 -0800 (PST) Subject: Protocol for thread communication References: Message-ID: <688d6185-eef0-41c5-8e03-042d86b87615@u72g2000hsf.googlegroups.com> On 5 Mar, 06:12, Michael Torrie wrote: > Does anyone have any recommended ideas/ways of implementing a proper > control and status protocol for communicating with threads? ?I have a > program that spawns a few worker threads, and I'd like a good, clean way > of communicating the status of these threads back to the main thread. > Each thread (wrapped in a very simple class) has only a few states, and > progress levels in those states. ?And sometimes they can error out, > although if the main thread knew about it, it could ask the thread to > retry (start over). ?How would any of you do this? ?A callback method > that the thread can call (synchronizing one-way variables isn't a > problem)? ?A queue? ?How would the main thread check these things? > Currently the main thread is polling some simple status variables. ?This > works, and polling will likely continue to be the simplest and easiest > way, but simple status variables are very limited. ?Are there any > pythonic patterns people have developed for this. > > thanks. > > Michael I've found that Queue.Queue objects are the easiest way to communicate between threads in Python. So, I'd suggets that you attach a Queue to each thread: the main thread will use its queue to receive the status messages from the other threads; the other threads will use their queues to receive the retry command (or any other command that may be needed) from the main thread. Ciao ------ FB From monica.leko at gmail.com Mon Mar 3 10:32:33 2008 From: monica.leko at gmail.com (Monica Leko) Date: Mon, 3 Mar 2008 07:32:33 -0800 (PST) Subject: Exception or not Message-ID: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Suppose you have some HTML forms which you would like to validate. Every field can have different errors. For example, this are the forms: username password etc And you want to validate them with some class. Is this good pattern: class Foo(object): def validateUsername(username): if username isn't correct: raise ValidationError() def validatePassword(password): if password isn't correct: raise ValidationError() code: try: usernameError = validateUsername() except ValidationError: usernameError = error from exception try: passwordError = validatePassword() except ValidationError: passwordError = error from exception So, if there wasn't any errors, usernameError and passwordError both contains None, and there was error, both contains some string? Should I use exception or just return None or some string without exception? From gagsl-py2 at yahoo.com.ar Tue Mar 18 01:47:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 22:47:08 -0700 (PDT) Subject: ctypes in python failed to honor c_int References: Message-ID: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> On 17 mar, 23:57, Jerry Fleming wrote: > I have a binary file written with c structures. Each record contains a > null-terminated string followed by two 4-bytes integers. I wrote a small > segment of python code to parse this file in this way: > [coe] > #!/usr/bin/python > > from ctypes import * > > class Entry(Structure): > ? ? ? ? _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) > > idx = open('x.idx', 'rb') > str = idx.read(1000) > obj = Entry(str) > print obj.w > print obj.s > print obj.l > [/code] > where the field w is the string, and s and l are the integers. Problem > is that, I can only get the strings, not the integers. Well, I did got > integers, but they are all zeros. What should I do to get the real numbers? So the string has a variable length? For "Hello" you have 'h','e','l','l','o', a zero byte, followed by the two integers? This is somewhat unusual for a C struct (in fact you can't declare it in C). Perhaps the string is actually a char[n] array with a declared maximum size? Try printing repr(a_few_read_bytes) or a_few_read_bytes.encode("hex") to see the actual file contents. -- Gabriel Genellina From abbas4u at gmail.com Sun Mar 30 18:59:14 2008 From: abbas4u at gmail.com (Fish) Date: Sun, 30 Mar 2008 15:59:14 -0700 (PDT) Subject: Creating Class Objects in Loop Message-ID: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> Hello Folks, I am reading a CSV file and based on that I am creating TestCase(my own defined class) objects in a for loop. The problem is each time I create a new TestCase object in loop, previous objects data is already copied in that object. e.g. my sample CSV file is # ------------------------- hello.pcap, 123, 231 test.pcap, 90, 899 hello2.pcap, 81, 18 # ----------------------- When I print the TestCase elements from returned list I get (Pdb) print tcLstOrig[0] Pcap Path: hello.pcap Sid List: 123, 231, 90, 899, 81, 18, (Pdb) print tcLstOrig[1] Pcap Path: test.pcap Sid List: 123, 231, 90, 899, 81, 18, (Pdb) print tcLstOrig[2] Pcap Path: hello2.pcap Sid List: 123, 231, 90, 899, 81, 18, Kindly guys advise me on this thing. Function snippet and Class definition are provided below. Regards, Fish ======= Problem Code The function snippet reading CSV and creating TestCase objects is [code] tcLst = [] # CSV file is read in variable 'lines' def returnTcLst(path): fp = open(path) lines = fp.readlines() for line in lines: tc = TestCase() i = line.find(",") tc.setPcap(line[:i].strip()) line = line[i+1:] line = line + "," i = line.find(",") while i != -1: sid = line[:i].strip() tc.appendSid(sid) line = line[i+1:] i = line.find(",") tcLst.append(tc) del tc return tcLst [/code] My TestCase Class is defined as [code] class TestCase(object): def __init__(self, pcap = None, sids = []): self.__Pcap = pcap self.__lstSid = sids def setPcap(self, path): self.__Pcap = path def appendSid(self, sid): self.__lstSid.append(sid) def __str__(self): text = "Pcap Path: " + self.__Pcap + "\n" text += "Sid List: " for sid in self.__lstSid: text += sid + ", " text += "\n" return text [/code] From moonrie at gmail.com Thu Mar 13 04:45:04 2008 From: moonrie at gmail.com (moonrie) Date: Thu, 13 Mar 2008 01:45:04 -0700 (PDT) Subject: help please, splitter windows like in maya or 3ds max References: Message-ID: <1dab98f7-7a29-4afb-b9ef-9728d133697d@s13g2000prd.googlegroups.com> On Mar 13, 12:47 pm, "Andrew Rekdal" <@comcast.net> wrote: > This seems to work... split then split each side. then tandem the size. > > import wx > > class Layout(wx.Frame): > > def __init__(self, parent, id, title): > > wx.Frame.__init__(self, parent, id, title) > > sizer = wx.BoxSizer(wx.HORIZONTAL) > > panel = wx.Panel(self,-1) > > splitter = wx.SplitterWindow(panel) > > sizer_left = wx.BoxSizer(wx.VERTICAL) > > panel_left = wx.Panel(splitter,-1) > > splitter_left = wx.SplitterWindow(panel_left) > > splitter_left.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.leftChange,id=splitter_left.GetId()) > > panel_left_upper = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > panel_left_upper.SetBackgroundColour("WHITE") > > panel_left_lower = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > splitter_left.SplitHorizontally(panel_left_upper,panel_left_lower) > > sizer_left.Add(splitter_left,1,wx.EXPAND) > > sizer_right = wx.BoxSizer(wx.VERTICAL) > > panel_right = wx.Panel(splitter,-1) > > splitter_right =wx.SplitterWindow(panel_right) > > splitter_right.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.rightChange,id=splitter_right.GetId()) > > panel_right_upper = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > panel_right_lower = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > panel_right_lower.SetBackgroundColour("WHITE") > > splitter_right.SplitHorizontally(panel_right_upper,panel_right_lower) > > sizer_right.Add(splitter_right,1,wx.EXPAND) > > splitter.SplitVertically(panel_left,panel_right) > > sizer.Add(splitter,1,wx.EXPAND) > > panel.SetSizer(sizer) > > panel_left.SetSizer(sizer_left) > > panel_right.SetSizer(sizer_right) > > self.splitter_left = splitter_left > > self.splitter_right = splitter_right > > def leftChange(self,event): > > pos = self.splitter_left.GetSashPosition() > > self.splitter_right.SetSashPosition(pos) > > event.Skip() > > def rightChange(self,event): > > pos = self.splitter_right.GetSashPosition() > > self.splitter_left.SetSashPosition(pos) > > event.Skip() > > app = wx.App(0) > > k = Layout(None, -1, 'layout.py') > > k.Show(True) > > app.MainLoop() > > -- Andrew > > ----- Original Message ----- > From: "moonrie" > > Newsgroups: comp.lang.python > Sent: Wednesday, March 12, 2008 10:19 PM > Subject: help please, splitter windows like in maya or 3ds max > > > hi, everyone there, I am doing a 3D modeling project. I like to do it > > with Python( am a newbie), but have no idea with the wxSplitterWindow > > to create the 4-view windows( top, front, side, perspective), like the > > mfc CSplitterWnd guy), > > anyone can give me some help with wxPython? > > > thanks in advance. > > > - moonrie should be these ones, thanks, :P From duncan.booth at invalid.invalid Tue Mar 18 17:34:44 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2008 21:34:44 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> Message-ID: castironpi at gmail.com wrote: >> > > On Mar 17, 1:31 pm, Duncan Booth >> > > wrote: >> >> > >> A common explanation for this is that lists are for homogenous >> > >> collections, tuples are for when you have heterogenous >> > >> collections i.e. related but different things. >> >> > > I interpret this as meaning that in a data table, I should have a >> > > list of records but each record should be a tuple of fields, >> > > since the fields for a table usually have different forms whereas >> > > the records usually all have the same record layout. >> >> >>> b in b >> False > > That's actually interesting. Just for the avoidance of doubt, I didn't write the 'b in b' line: castironpi is replying to himself without attribution. P.S. I still don't see the relevance of any of castironpi's followup to my post, but since none it made any sense to me I guess it doesn't matter. From willsteve2003 at yahoo.ca Mon Mar 10 11:24:30 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:24:30 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> Message-ID: <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> On Mar 7, 6:12?pm, John Machin wrote: > On Mar 8, 1:53 am, "hvendelbo.... at googlemail.com" > > > > > > wrote: > > On Mar 6, 9:17 pm, Luis M. Gonz?lez wrote: > > > > On 6 mar, 11:27, Pierre Quentel wrote: > > > > > Hi, > > > > > I would like to know if there is a module that converts a string to a > > > > value of the "most probable type" ; for instance : > > > > - if the string is "abcd" the value is the same string "abcd" > > > > - string "123" : value = the integer 123 > > > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > > > = the float -1.23 > > > > - string "2008/03/06" (the format is also locale-dependant) : value = > > > > datetime.date(2008,03,06) > > > > > Like in spreadsheets, special prefixes could be used to force the > > > > type : for instance '123 would be converted to the *string* "123" > > > > instead of the *integer* 123 > > > > > I could code it myself, but this wheel is probably already invented > > > > > Regards, > > > > Pierre > > > >>> def convert(x): > > > > ? ? ? ? if '.' in x: > > > ? ? ? ? ? ? ? ? try: return float(x) > > > ? ? ? ? ? ? ? ? except ValueError: return x > > > ? ? ? ? else: > > > ? ? ? ? ? ? ? ? try: return int(x) > > > ? ? ? ? ? ? ? ? except: return x > > > > >>> convert('123') > > > 123 > > > >>> convert('123.99') > > > 123.98999999999999 > > > >>> convert('hello') > > > > 'hello' > > > Neat solution. The real challenge though is whether to support > > localised dates, these are all valid: > > 20/10/01 > > 102001 > > 20-10-2001 > > 20011020 > > Neat solution doesn't handle the case of using dots as date separators > e.g. 20.10.01 [they are used in dates in some locales and ?the > location of . on the numeric keypad is easier on the pinkies than / or > -] > > I'm a bit dubious about the utility of "most likely format" for ONE > input. > > I've used a brute-force approach when inspecting largish CSV files > (with a low but non-zero rate of typos etc) with the goal of > determining what is the most likely type of data in each column. > E.g 102001 could be a valid MMDDYY date, but not a valid DDMMYY or > YYMMDD date. 121212 could be all of those. Both qualify as int, float > and text. A column with 100% of entries qualifying as text, 99.999% as > float, 99.99% as integer, 99.9% as DDMMYY, and much lower percentages > as MMDDYY and YYMMDD would be tagged as DDMMYY. The general rule is: > pick the type whose priority is highest and whose score exceeds a > threshold. Priorities: date > int > float > text. Finding the date > order works well with things like date of birth where there is a wide > distribution of days and years. However a field (e.g. date interest > credited to bank account) where the day is always 01 and the year is > in 01 to 08 would give the same scores for each of 3 date orders ... > eye-balling the actual data never goes astray.- Hide quoted text - > > - Show quoted text - In the case where dots are used as a date separator, count the number of dots (you should also count commas). If a single comma appears and is preceeded by only numbers or numbers with decimals, assume "foreign float". If a single decimal appears and is preceeded by only numbers or numbers with commas, assume "float". If 2 decimals appear and each field is 2 or less characters in length and numeric, assume date. If 2 decimals appear and the first 2 fields are 2 or less characters in length and numeric and the last field is 4 characters in length and numeric, assume date. There are things you can do, but you must be wary of the fact that it may not always be 100% perfect. From castironpi at gmail.com Fri Mar 7 16:15:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 13:15:04 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: <08448e76-e029-4b51-ad7b-4f2d0297dea0@e31g2000hse.googlegroups.com> On Mar 7, 10:12?am, alex.pedwyso... at gmail.com wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... import sys from time import clock, sleep from threading import Timer TimeoutError= type('TimeoutError',(Exception,),{}) class Elapse: def __init__( self ): self.flag= False def set( self ): self.flag= True def tr( frame, event, arg ): if elapse.flag: raise TimeoutError return tr def sleeper(): while 1: sleep( .3 ) print( 'tick' ) def factercomp( n ): val= 1 for i in range( 1, n ): val*= i return val def facter( n ): print( factercomp( n ) ) def runit( f, *ar ): global elapse elapse= Elapse() t= Timer( 1, elapse.set ) t.start() sys.settrace( tr ) try: f( *ar ) except TimeoutError: print( 'time elapse' ) runit( sleeper ) runit( facter, 10 ) runit( facter, 20 ) runit( facter, 10000 ) runit( facter, 100000 ) ''' tick tick tick time elapse 362880 121645100408832000 time elapse time elapse ''' From simon at brunningonline.net Wed Mar 19 10:46:56 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 Mar 2008 14:46:56 +0000 Subject: changing names of items in a list In-Reply-To: References: Message-ID: <8c7f10c60803190746w5f487187ia0fca001d9c443b3@mail.gmail.com> On Wed, Mar 19, 2008 at 2:21 PM, royG wrote: > hi > i am trying to rename extension of files in a directory..as an initial > step i made a method in > > class ConvertFiles: > def __init__(self,infldr,outfldr): > self.infldr=infldr > self.outfldr=outfldr > self.origlist=os.listdir(infldr) > .... > def renamefiles(self,extn): > for x in self.origlist: > x=x+"."+extn > > ... > > later when i print self.origlist i find that the elements of list are > unchanged..even tho a print x inside the renamefiles() shows that > extn is appended to x .. > why does this happen? Your 'x=' line is building a brand new string, and rebinding the name 'x' to it. It's not doing anything to the original list. See . I'd rewrite that as (untested): def renamefiles(self, extn): self.origlist = list((x + "." + extn) for x in self.origlist) or def renamefiles(self, extn): self.origlist = list(("%s.%s" % (z, extn)) for x in self.origlist) Better still, take a look at the os.path module... -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From grflanagan at gmail.com Tue Mar 4 10:35:36 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 4 Mar 2008 07:35:36 -0800 (PST) Subject: Removing default logging handler (causes duplicate logging) References: Message-ID: <9c5214a1-7634-4249-bc46-061eb45820cd@s19g2000prg.googlegroups.com> On Mar 4, 1:29 pm, Gal Aviel wrote: > Hello All, > > I want to add a logger to my application, then addHandler to it to log to a > special destination. > > Unfortunately when I use logging.getLogger("my_logger") to create the new > logger, it apparently comes with a default handler that logs to STDOUT (or > STDERR?). When I add my special handler it works Ok, but still logs to terminal, > which I do not want. > from docs: ------------------ getLogger( [name]) Return a logger with the specified name or, if no name is specified, return a logger which is the root logger of the hierarchy. ------------------ so you should do 'root = getlogger()', then append your own logger to the root. Gerard From michael at stroeder.com Wed Mar 26 08:58:49 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Mar 2008 13:58:49 +0100 Subject: ANN: python-ldap-2.3.2 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.2 2008-03-26 Changes since 2.3.1: Lib/ * ldap.dn.escape_dn_chars() now really adheres to RFC 4514 section 2.4 by escaping null characters and a space occurring at the beginning of the string * New method ldap.cidict.cidict.__contains__() * ldap.dn.explode_dn() and ldap.dn.explode_rdn() have a new optional key-word argument flags which is passed to ldap.dn.str2dn(). Modules/ * Removed unused OPT_PRIVATE_EXTENSION_BASE from constants.c Doc/ * Various additions, updates, polishing (thanks to James). From miki.tebeka at gmail.com Thu Mar 27 14:17:43 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 11:17:43 -0700 (PDT) Subject: ctypes and gmp Message-ID: <42848b47-9bad-4d4d-b5c7-e524c4e1504e@d21g2000prf.googlegroups.com> Hello All, Playing around with ctypes, I'm try to use gmp (gmpy is excellent but I want to learn ctypes). I'm running: #!/usr/bin/env python from ctypes import * class mpz(Structure): _fields_ = [ ("_mp_alloc", c_int), ("_mp_size", c_int), ("_mp_d", POINTER(c_uint)), ] gmp = cdll.LoadLibrary("libgmp.so") m = mpz() gmp.__gmpz_init(byref(m)) gmp.__gmpz_set_ui(byref(m), 27) gmp.__gmp_printf("m is %d\n", byref(m)) However, the output is: m is -1210863888 Any ideas? (gmp.h can bee view at http://tinyurl.com/yrqen4) Thanks, -- Miki http://pythonwise.blogspot.com From beema.shafreen at gmail.com Wed Mar 19 07:16:52 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Wed, 19 Mar 2008 16:46:52 +0530 Subject: printing dictionary and tuple Message-ID: Hi everbody i am trying to print the dictionary values and tuple in a same line as below print "\t".join(dict[a].values())+'\t'+"\t".join(b) Error I get is the TypeError, since i have misisng values in the dictionary. if i use exception i will miss those how should i print the data without missing the lines excluding the error separated by tab. -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From zerty.david at gmail.com Sun Mar 30 16:29:52 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:29:52 -0300 Subject: Error Raised But dont know what it means In-Reply-To: <5dc598e30803301307g20d9494ekf140387361c31968@mail.gmail.com> References: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> <5dc598e30803301307g20d9494ekf140387361c31968@mail.gmail.com> Message-ID: <5dc598e30803301329j17fa82dw4ec5eb27019174d5@mail.gmail.com> I found the problem Topic closed On Sun, Mar 30, 2008 at 5:07 PM, David Anderson wrote: > Here is the code: > This one raises the error: > def criaLista(self): > self.listbox.Clear() > for dupla in self.duplas: > self.listbox.Append(dupla.__str__()) > > This one works well but doesn't raises error > > dupla1 = Duplas("2422", "2455") > dupla2 = Duplas("454", "15") > list = [] > list.append(dupla1) > list.append(dupla2) > erros = ErrorMgr() > erros.geraErro("1", "erro idiota", 2.2) > dic = {1:dupla1, 2:dupla2} > a = Arquivos("batata.txt") > a.saveFile(list, erros, dic) > a.openFile() > lista = a.getListaDuplas() > e = a.getErrorsManager() > d = a.getDicDuplas() > > for i in lista: > print i > > print d[1] > > > On Sun, Mar 30, 2008 at 5:03 PM, David Anderson > wrote: > > > Well, I'm dealing with files in Pickle, I'm saving at the file a List of > > Objects from the same Class, When I try to retrive this information and try > > to iterate over them this error is raised: > > TypeError: 'instancemethod' object is not iterable > > > > But if I just print the method I get the 'real thing' what's the > > problem? > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rockxuan at gmail.com Tue Mar 18 03:45:32 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:45:32 -0700 (PDT) Subject: Omega Swiss watch in www.51cntrade.com Message-ID: <5401397f-0d8f-46b9-9f4e-e438c90ef583@s8g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From pavlovevidence at gmail.com Fri Mar 14 02:26:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Mar 2008 23:26:28 -0700 (PDT) Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup References: <47d97288$0$36363$742ec2ed@news.sonic.net> <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> <47da10c8$0$36374$742ec2ed@news.sonic.net> Message-ID: <37eb1226-d2db-499e-9ba5-a4d441465451@p25g2000hsf.googlegroups.com> On Mar 14, 1:53 am, John Nagle wrote: > John Machin wrote: > > On Mar 14, 5:38 am, John Nagle wrote: > >> Just noticed, again, that getattr/setattr are ASCII-only, and don't support > >> Unicode. > > >> SGMLlib blows up because of this when faced with a Unicode end tag: > > >> File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag > >> method = getattr(self, 'end_' + tag) > >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' > >> in position 46: ordinal not in range(128) > > >> Should attributes be restricted to ASCII, or is this a bug? > > >> John Nagle > > > Identifiers are restricted -- see section 2.3 (Identifiers and > > keywords) of the Reference Manual. The restriction is in effect that > > they match r'[A-Za-z_][A-Za-z0-9_]*\Z'. Hence if you can't use > > obj.nonASCIIname in your code, it makes sense for the equivalent usage > > in setattr and getattr not to be available. > > > However other than forcing unicode to str, setattr and getattr seem > > not to care what you use: > > OK. It's really a bug in SGMLlib, then. SGMLlib lets you provide a > subclass with a function with a name such as "end_img", to be called > at the end of an "img" tag. The mechanism which implements this blows > up on any tag name that won't convert to "str", even when there are > no "end_" functions that could be relevant. > > It's easy to fix in SGMLlib. It's just necessary to change > > except AttributeError: > to > except AttributeError, UnicodeEncodeError: > > in four places. I suppose I'll have to submit a patch. FWIW, the stated goal of sgmllib is to parse the subset of SGML that HTML uses. There are no non-ascii elements in HTML, so I'm not certain this would be considered a bug in sgmllib. Carl Banks From fakeaddress at nowhere.org Tue Mar 25 06:34:19 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 25 Mar 2008 03:34:19 -0700 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: john s. wrote: > #/usr/bin/enviro python > > #Purpose - a dropped in useracct/pass file is on a new server to build > a cluster... Alas there are no home #directories.. Let me rip through > the passfile, grab the correct field (or build it) and use it to make > the directory! > > import os, sys, string, copy, getopt, linecache > from traceback import format_exception > > #The file we read in... > fileHandle = "/etc/passwd" > srcFile = open(fileHandle,'r') > srcList = srcFile.readlines() > > #yah, a for loop that "iterates" through the file of "lines" > for i in srcList: Convention is that the name i is for an integer. > strUsr = string.split(i,":") > theUsr = strUsr[0] > usrHome = "/expirt/home/",theUsr,"/" > usrHome = ''.join(usrHome) As Ryan noted, os.path is the favored way. > print "printing usrHome:",usrHome > > print "is it a dir?: ", os.path.isdir(usrHome) > > # try to test if it's a dir... for some reason this mis-behaves... > maybe I'm not thinking about it correctly.. > > if os.path.isdir(usrHome) != 'False': That should always evaluate true. False != 'False'. I think you want: if not os.path.exists(usrHome): > print "User Home dir doesn't exist creating." > > try: > os.makedirs('usrHome' ) > except Exception, e: > print e I don't think you want to catch the exception there. If creating the dir fails, the next bits of code should not execute. > print "usrHome is: ",usrHome > print "theUsr is: ",theUsr > > os.system('/usr/bin/chmod 750 ' + usrHome) > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) > > #OMG, there is directory that happens to already exist! well, due > diligence and love for the queen dictates we #provide "due > dilligence", (e.g. wipe our asses properly) The path could exist but not be a directory. > else: > print "User Home dir exist, checking and fixing permissions." > > print "usrHome is: ",usrHome > print "theUsr is: ",theUsr > > os.system('/usr/bin/chmod 750 ' + usrHome) > os.system('/usr/bin/chown ' + theUsr + ' ' + usrHome) > > #I know that I can't optimize the line below further... or... can I? > > sys.exit("Thanks for using pyDirFixr...") Given the Unixy nature of your code, you probably want to sys.exit(0) for success and 1 or 2 for failure. Happy hacking, -- --Bryan From duncan.booth at invalid.invalid Mon Mar 17 09:31:53 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 13:31:53 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > What are the considerations in choosing between: > > return [a, b, c] > > and > > return (a, b, c) # or return a, b, c > A common explanation for this is that lists are for homogenous collections, tuples are for when you have heterogenous collections i.e. related but different things. If you follow this line of argument then when you want to return some values from a function, e.g. url, headers and data a tuple would be the appropriate thing to use. If you really are returning a homogenous collection (e.g. top 5 urls) then a list would be more appropriate. Another way to look at it is what you expect the caller to do with the results. If they are just going to unpack a fixed set of values then a tuple makes sense. If you write: return url, headers, data then the caller writing: url, headers, data = frobozz() has a certain symmetry. It isn't set in stone of course: use whatever you want or whatever feels right at the time. > Why is the immutable form the default? > It isn't. It uses whichever type you specify but tuples may involve a little less typing. From josef.pktd at gmail.com Sat Mar 15 17:47:08 2008 From: josef.pktd at gmail.com (joep) Date: Sat, 15 Mar 2008 14:47:08 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> Message-ID: On Mar 15, 5:42 pm, joep wrote: > >http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... > > Note: this works for subprocess.call but for subprocess.Popen this > does not work if there are two arguments in the command line with > spaces. Especially, even after trying out many different versions, I > never managed to get subprocess.Popen to work, when both the > executable and one argument have spaces in the file path. > Sorry, incomplete sentence Especially, even after trying out many different versions, I never managed to get subprocess.Popen to work '''when command line is given as a *list* argument to subprocess.Popen''' in the case when both the executable and one argument have spaces in the file path. joe From mcepl at redhat.com Sun Mar 2 04:15:54 2008 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 02 Mar 2008 10:15:54 +0100 Subject: sqlite3 adaptors mystery References: Message-ID: On 2008-03-02, 08:16 GMT, Matej Cepl wrote: > Thanks for your help, but plain-text strings is not what > I wanted. The boolean variables was what I was after. See this > modified version of the script: OK, I got it -- I was missing detect_types parameter of the connect method. Mat?j From michael.wieher at gmail.com Sun Mar 16 10:09:16 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:09:16 -0500 Subject: Cannot build Python 2.4 SRPM on x64 platform In-Reply-To: References: Message-ID: Sorry I don't have much of a better idea, but if I had this kind of problem with an RPM, I'd just grab the tarball and start hacking away at ./configure pre-requirements, trying to use --options to trim it down to the bare minimal and see if I can get it to load up. 2008/3/16, Eric B. : > > Hi, > > For those on several python lists, I appologize in advance for > cross-posting, but I'm really not sure which list is best to ask for > assistance with this. > > Currently, I am trying to build the python2.4 SRPM from Python.org on a > RHEL4 x64 platform, but the build is failing with a very non-descript > error message. > > .... > + cd /var/tmp/python2.4-2.4-root/usr/bin > + mv -f pydoc pydoc2.4 > + cd /var/tmp/python2.4-2.4-root/usr/bin > + mv -f idle idle2.4 > + echo '#!/bin/bash' > + echo 'exec /usr/bin/python2.4 /usr/lib64/python2.4/idlelib/idle.py' > + chmod 755 /var/tmp/python2.4-2.4-root/usr/bin/idle2.4 > + cp -a Tools /var/tmp/python2.4-2.4-root/usr/lib64/python2.4 > + rm -f mainpkg.files > + find /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f > + sed 's|^/var/tmp/python2.4-2.4-root|/|' > + grep -v -e '_tkinter.so$' > error: Bad exit status from /var/tmp/rpm-tmp.55639 (%install) > > > RPM build errors: > user jafo does not exist - using root > group jafo does not exist - using root > user jafo does not exist - using root > group jafo does not exist - using root > Bad exit status from /var/tmp/rpm-tmp.55639 (%install) > > > If I try to run /var/tmp/rpm-tmp.55639 manually from the prompt manually > after the rpmbuild fails, it runs properly to completion. If I try to > comment out that last line (find > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-dynload -type f | sed > 's|^/var/tmp/python2.4-2.4-root|/|' | grep -v -e '_tkinter.so$' ) that > seems > to be causing the script to fail, rpmbuild finishes, but with several > error > msgs, complaining about missing files in the lib64 directories: > > + rm -f /tmp/python-rpm-files.4859 > + /usr/lib/rpm/brp-compress > + /usr/lib/rpm/brp-strip > + /usr/lib/rpm/brp-strip-static-archive > + /usr/lib/rpm/brp-strip-comment-note > Processing files: python2.4-2.4-1pydotorg > error: File not found by glob: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.txt > error: File not found by glob: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/*.py* > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/pdb.doc > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/profile.doc > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/curses > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/distutils > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/encodings > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/plat-linux2 > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/site-packages > error: File not found: /var/tmp/python2.4-2.4-root > /usr/lib64/python2.4/test > error: File not found: /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/xml > error: File not found: /var/tmp/python2.4-2.4-root > /usr/lib64/python2.4/email > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/compiler > error: File not found: /var/tmp/python2.4-2.4-root > /usr/lib64/python2.4/bsddb > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/hotshot > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/logging > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/lib-old > Executing(%doc): /bin/sh -e /var/tmp/rpm-tmp.95118 > + umask 022 > + cd /usr/src/redhat/BUILD > + cd Python-2.4 > + DOCDIR=/var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + export DOCDIR > + rm -rf /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + /bin/mkdir -p /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + cp -pr Misc/README Misc/cheatsheet Misc/Porting > /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + cp -pr LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS > /var/tmp/python2.4-2.4-root/usr/share/doc/python2.4-2.4 > + exit 0 > Processing files: python2.4-devel-2.4-1pydotorg > error: File not found: > /var/tmp/python2.4-2.4-root/usr/lib64/python2.4/config > Processing files: python2.4-tools-2.4-1pydotorg > Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 > rpmlib(PayloadFilesHavePrefix) <= 4.0-1 rpmlib(VersionedDependencies) <= > 3.0.3-1 > Requires: /bin/bash /bin/sh /usr/bin/env > > > Finally, if I try searching for any files in the > usr/lib64/python2.4/lib-dynload or usr/lib64/python2.4/idlelib > directories > manually, I don't see any files at all in those directories. > > > To me, it seems as though python is either not installing the files in the > right places, or the script is searching for files in the wrong places, > but > I'm completely guessing here. > > Has anyone managed to build Python2.4 on a RHEL4 x64 system? Can anyone > point me in the right direction to complete this build successfully? I'm > hoping to get the binaries built so I can contribute them to the > python.org > site so others don't need to go through these problems in the future. > > Any hints / ideas / suggestions / guidance that anyone can provide would > amazing, because I'm completely out of ideas at this point. Like I said, > I'm trying to build this on a RHEL4 x64 system, with all latest updates. > > Thanks so much! > > Eric > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Tue Mar 11 22:49:54 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 11 Mar 2008 19:49:54 -0700 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: Message-ID: Roopan wrote: > I assume the C++/Python binding is fairly painless. http://www.boost.org/libs/python/doc/tutorial/doc/html/index.html Ahhhh. :) From davidj411 at gmail.com Mon Mar 10 13:20:46 2008 From: davidj411 at gmail.com (davidj411) Date: Mon, 10 Mar 2008 10:20:46 -0700 (PDT) Subject: lowercase u before string in "python for windows" Message-ID: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> why does this occur when using the python windows extensions? all string are prefixed by a lowercase "u". is there a newsgroup explicitly for python windows extensions? example of output below. SMBIOSBIOSVersion:u'A16' SMBIOSMajorVersion:2 SMBIOSMinorVersion:3 SMBIOSPresent:True SoftwareElementID:u'Phoenix ROM BIOS PLUS Version 1.10 A16' SoftwareElementState:3 Status:u'OK' TargetOperatingSystem:0 here is a snippet of the code: if objItem.Status != None: print "Status:" + ` objItem.Status` if objItem.TargetOperatingSystem != None: print "TargetOperatingSystem:" + ` objItem.TargetOperatingSystem` if objItem.Version != None: print "Version:" + ` objItem.Version` From gdamjan at gmail.com Tue Mar 25 20:00:55 2008 From: gdamjan at gmail.com (Damjan) Date: Wed, 26 Mar 2008 01:00:55 +0100 Subject: Beta testers needed for a high performance Python application server References: Message-ID: <47e99237$0$90273$14726298@news.sunsite.dk> >> I'm looking for beta testers for a high performance, event-driven Python >> application server I've developed. >> >> About the server: the front end and other speed-critical parts of the >> server are written in portable, multithreaded C++. ... > Why not just put it on the net somewhere and tell us where it is? > People aren't generally going to want to help or even look at it if > you treat it like a proprietary application. So, put the documentation > and code up somewhere for all to see. > BTW, multiprocess web servers such as Apache can quite happily make > use of multiple cores. Even within a single Apache multithread process > it can still use multiple cores quite happily because all the > underlying network code and static file handling code is in C and not > subject to the GIL. So, as much as people like to bash up on the GIL, > within Apache it is not necessarily as big a deal as people make out. BTW nginx now has a mod_wsgi too, if someone is looking for an Apache replacement. -- damjan From bernard.chhun at gmail.com Fri Mar 28 10:44:54 2008 From: bernard.chhun at gmail.com (Bernard) Date: Fri, 28 Mar 2008 07:44:54 -0700 (PDT) Subject: simple web-server References: Message-ID: <0060b0f1-02b3-498e-be95-8581c4f98ccf@i12g2000prf.googlegroups.com> Did you take a look at web.py? That one looks terribly small and efficient :) We use CherryPy coupled with compiled Cheetah Templates for every web server based projects at my workplace and we've been really satisfied with it so far. On 28 mar, 07:53, "Pavol Murin" wrote: > hello python users, > > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). > > Longer story: > > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed). > > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? > > thank you, muro From Medhat.Gayed at gmail.com Mon Mar 3 22:41:00 2008 From: Medhat.Gayed at gmail.com (Medhat.Gayed at gmail.com) Date: Mon, 3 Mar 2008 19:41:00 -0800 (PST) Subject: XML Schema validation in Python Message-ID: I tested and tried a few XML validators but none of them is able to successfully validate a string of xml (not a file just a string) to programatically be able to validate messages of xml that flow in and out of the different systems. The validators I used were XSV, oNVDL and lxml, can we implement a pure python module for validating strings of xml using XML Schema (not DTD) ? From stefan_ml at behnel.de Mon Mar 10 15:11:53 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 20:11:53 +0100 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <47D587F9.3050703@behnel.de> Malcolm Greene wrote: >> My personal experience with wxPython has its ups and downs. Specifically >> when it comes to crashes, I wouldn't bet my life on it. > > I'm new to Python and getting ready to build a small client based > application intended to run on Windows and Linux. I was planning on using > wxPython until I saw your comment above. Just to make this sound a bit less like FUD: my last experience with wxPython dates back a couple of years (2004/5?), but back then, we used BoaConstructor in a project, which crashed a bit too often to do real work with it - and with crashing I mean crashing Python, not just showing us its blank traceback. So this was definitely a problem either in wxWindows or in wxPython. I have no idea how well it works today, but this has definitely forged my opinion on wxPython. > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > or tips on where I can find out more about wxPython/wxWidget problems? The only other GUI library I used was PyQT3. To me, it has proven to be very stable, pretty easy to use and feature rich. And from what I read about it, PyQT4 is supposed to be another lot better and has removed the few API quirks I found at the time (AFAIR, it finally returns plain Python strings from the API, for example). Stefan From fetchinson at googlemail.com Mon Mar 3 01:32:43 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 2 Mar 2008 22:32:43 -0800 Subject: SQLLITE In-Reply-To: <74838b55-9b05-4f90-8a15-37bb50a775da@h11g2000prf.googlegroups.com> References: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> <62tjigF24ui98U2@mid.uni-berlin.de> <74838b55-9b05-4f90-8a15-37bb50a775da@h11g2000prf.googlegroups.com> Message-ID: > > > I am having a minor problem when I try and do this: > > > c.execute("insert into [tblTranscripts] (MovieID,Transcript) > > > Values(" + movieID + ",'" + formatText + "');") (don't even bother > > > commenting of the sql style I know its bad form but this is a simple > > > script). Whenever I try and do the insert I get table not found, > > > however when I perform the sql through sqlite's command line program > > > (the sql is outputted via a print statement) it works fine. Any ideas? > > > > No, and without more context nobody will have. Does working with the > > table with other statments work, how do you connect the DB, are you sure > > you really use the same DB-file and so forth. > > > Beginner stuff is usually forgetting 'use moviedata'. This is not needed for sqlite. The database is defined by the file the sqlite executable is working on. From darcy at druid.net Fri Mar 7 13:09:19 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 7 Mar 2008 13:09:19 -0500 Subject: Regarding coding style In-Reply-To: References: <63d80bF273nraU1@mid.individual.net> Message-ID: <20080307130919.b3f82a85.darcy@druid.net> On 7 Mar 2008 17:40:08 GMT Jon Ribbens wrote: > Well, no, it's to follow a particular person's choice out of the many > and various competing rules of "correct English usage". Personally, > I dislike double spaces after sentences, but it is not wrong to put > them there any more than it is wrong not to put them there. > Consistency is far more important (hence the rule, I presume). Warning: Opinion follows possibly influenced by insufficient research. I have read the arguments about single or double spacing and find that they can be distilled down to the following: You should use double space for monospaced fonts and single for proportional. I reject this argument for two reasons. One is consistency. It is entirely possible for the same document to be rendered in multiple ways and you may not be aware of them ahead of time. The second is that it seems to me that programs that use proportional fonts should be able to make any space between sentences render properly by their own rules so the number of spaces should be irrelevant. I am not swayed by arguments that they don't handle this properly yet. The arguments for one over the other fall into these basic ones. Use double spaces to make the document easier to read, especially by people who read a lot and tend to skim to absorb as much information as possible. Use single space because it makes the document display nicer. This suggests to me that the schism is probably between two different types of people, text/information oriented and display/presentation oriented. I don't see any way to appeal to both. -- 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 dickinsm at gmail.com Sat Mar 8 20:09:11 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 17:09:11 -0800 (PST) Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Message-ID: On Mar 8, 6:26?pm, Paul Rubin wrote: > Alasdair writes: > > What is the best way of finding a ceiling of a quotient of arbitrary sized > > integers? > > ceiling(a/b) = (a+b-1)//b I prefer: ceiling(a/b) = -(-a)//b which also works if a and b are something other than integers (e.g. rational numbers). Mark From emailamit at gmail.com Mon Mar 31 13:38:47 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 10:38:47 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Message-ID: <89d34053-4b16-49df-9153-eb3625249ad4@u10g2000prn.googlegroups.com> On Mar 31, 10:37 am, John Henry wrote: > On Mar 31, 10:24 am, Amit Gupta wrote: > > > > > Hi > > > I am looking for a some tool that can convert python scripts to > > executable on Linux. > > > I found freeeze.py as the only option so far. Couple of queries on > > freeze: > > > 1. Have anyone used the freeze utility and any experiences to share > > from that? > > 2. Is there any enterprise-level exe-builder for python on linux > > (ActiveState has nothing)? > > > Any other related commets are also welcome. > > > Thanks > > Amit > > I don't know about freeeze.py but for me, I've been using py2exe, and > also pyinstall quite often and they both work for me. Isnt py2exe for windows only? I haven't looked at pyinstall.. Is it for linux? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 4 06:27:58 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 04 Mar 2008 12:27:58 +0100 Subject: Difference between 'function' and 'method' In-Reply-To: References: Message-ID: <47cd3238$0$17697$426a74cc@news.free.fr> ?? a ?crit : > Howdy everyone, > > This is a big problem puzzles me for a long time. The core question is: > How to dynamically create methods on a class or an instance? class Foo(object): pass def bar(self, arg): print "in bar : self == % - arg == %s" % (self, str(arg)) def baaz(self, arg): print "in baaz : self == % - arg == %s" % (self, str(arg)) f = Foo() # adding bar as a method to class Foo Foo.bar = bar # f now can use bar: f.bar(42) # as well as new instances of Foo, of course g = Foo() g.bar() # adding baaz as a method to f, the old way: import new f.baaz = new.instancemethod(baaz, f, type(f)) f.baaz() # adding baaz as a method to g, the other way: g.baaz = baaz.__get__(g, type(g)) g.baaz() > Let me state it step by step. > 1. > def gunc(self): > pass > class A(object): > def func(self): > pass > a = A() > a.func # gives "bound method", type is "instancemethod" > A.func # gives "unbound method", type is "instancemethod" > gunc # gives "function", type if "function" > > # ?? Does this line attach a method to instance? ... I don't think so. > a.gunc = gunc It doesn't. > I found stardard library 'new' may help. Is that right? cf above. If you work with old-style classes, you'll need new.instancemethod. > 2. > a = A() # instance of old class A > # Do attach a new method to class A... > b = A() # instance of new class A > Does "a" can get the new method automatically? Yes. In Python, a class is itself an object, and is an attribute of it's instances (instance.__class__). Names are resolved at runtime, and attributes not found in the instance's __dict__ are looked up in the class (and then in the superclasses etc). > Does new method have the *same* concept level with old methods? The newly added method works exactly the same way as already existing ones. Not a single difference. The class statement is just syntactic sugar anyway. The following snippets are equivalent: # sugar-coated: class Boo(object): faaz = 0 def far(self): type(self).faaz += 1 print self def frob(self): print "yadda" # raw: def far(self): type(self).faaz += 1 print self Boo = type('Boo', (object,), dict(faaz=0, far=far)) def frob(self): print "yadda" Boo.frob = frob > Especially, if there > are classes inherit from class A, how does name resolution work on this case? As usual. > 3. > How do I write a decroator for a method? Mostly the same way you'd write a decorator for a function > Eg: > class A(object): > @my_dec > def func(self): > pass > Here, my_dec should return a method rathar than a function/lambda. Am I right? Nope. Functions defined within a class statement are plain ordinary functions. It's the lookup mechanism that "turns them into methods" when they are looked up as attribute of a class. In fact, Python "methods" are thin callable wrappers around a function, a class and (most of the time) an instance, wrappers which are created - usually at lookup time - by the __get__ method of the function type (you may want to read about the descriptor protocol on python.org - in the section about new style classes IIRC). Anyway, you can explore this by yourself: >>> Boo.far >>> b.far > >>> Boo.__dict__['far'] >>> Boo.__dict__['far'] is far True >>> f1 = b.far >>> f2 = b.far >>> f1 is f2 False >>> f1() <__main__.Boo object at 0xb787f96c> >>> f2() <__main__.Boo object at 0xb787f96c> >>> dir(f1) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self'] >>> f1.im_class >>> f1.im_func >>> f1.im_func is far True >>> f1.im_self <__main__.Boo object at 0xb787f96c> >>> f1.im_self is b True >>> bf = Boo.far >>> bf.im_func >>> bf.im_func is far True >>> bf.im_class >>> bf.im_self >>> bf.im_self is None True >>> far.__get__(b, Boo) > >>> far.__get__(b, Boo).im_func is far True >>> So, to answer your question: what you are decorating are functions, not methods. > What does @property @staticmethod... really do? I cannot step-into them for > source code. staticmethod wraps the function into an object that, when looked up as an attribute, will return the raw function instead of returning a method. property is a type that provides a simple generic implementation for computed attributes. You'll find more detailed explanations in the doc (but perhaps not in the most obvious place - it's somewhere in the peps or in the 'nws style classes' stuff IIRC). Anyway, using it as a decorator is a somewhat special case (well... to me at least), that will defined a property with only a getter (the decorated function). > 4. > If most of above questions can be solved, then it would be easy to implement > the feature: "dynamic property attach". > Eg: > One class can read/store settings from/to some file based on > the file content. > # File: cfg.ini > x = 1 > y = python > config = SettingClass('cfg.ini') # dynamically build up properties x and y. > x = config.x # x will be set to 1 (str -> int convertion would be > done by 'property x') > y = config.y # y will be set to 'python' > config.x = 9 # 'x = 9' is written to cfg.ini. > > How to implement In this case, I'd rather use the __getattr__/__setattr__ hooks. It won't work with properties nor custom descriptors, since descriptors only work as class attributes - not as instance attributes (which BTW is why setting a function as an instance attribute doesn't make it a method...) here are a couple links to relevant documentation and stuffs: http://www.python.org/download/releases/2.2.3/descrintro/ http://users.rcn.com/python/download/Descriptor.htm http://www.python.org/doc/newstyle/ > ^_^ Maybe there are some library does the same thing. Indeed: http://www.voidspace.org.uk/python/configobj.html http://wiki.python.org/moin/ConfigParserShootout HTH From castironpi at gmail.com Wed Mar 19 01:37:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 22:37:38 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: On Mar 18, 10:08?pm, Bryan Olson wrote: > Arnaud Delobelle wrote: > > Ninereeds wrote: > >> Hrvoje Niksic wrote: > >>> This doesn't apply to Python, which implements dict storage as an > >>> open-addressed table and automatically (and exponentially) grows the > >>> table when the number of entries approaches 2/3 of the table size. > >>> Assuming a good hash function, filling the dict should yield amortized > >>> constant time for individual additions. > > > Isn't this average constant time rather than amortized? > > This is expected amortized constant time. Is that really the same > thing as average constant time? Hmmm... that's subtle. It's the same as expected constant time. > >> OK. I obviously need to look up open-addressed tables. I thought this > >> was just, in effect, implicit linked listing - ie it still needs a > >> linear search to handle collisions, it just avoids the need for > >> explicitly stored link fields. Perhaps I'm mistaken. > > The amortized doubling breaks that. > > > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > > link to further details. > > Arnaud Delobelle offered a good Wikipedia link, and for more background > look up "amortized analysis. >>> [ (i,hash(2**i)) for i in range( 0, 5000, 32 ) ] [(0, 1), (32, 1), (64, 1), (96, 1), (128, 1), (160, 1), (192, 1), (224, 1), (256 , 1), (288, 1), (320, 1), (352, 1), (384, 1), (416, 1), (448, 1), (480, 1), (512 , 1), (544, 1), (576, 1), (608, 1), (640, 1), (672, 1), (704, 1), (736, 1), (768 , 1), (800, 1), (832, 1), (864, 1), (896, 1), (928, 1), (960, 1), (992, 1), (102 4, 1), (1056, 1), (1088, 1), (1120, 1), (1152, 1), (1184, 1), (1216, 1), (1248, 1), (1280, 1), (1312, 1), (1344, 1), (1376, 1), (1408, 1), (1440, 1), (1472, 1), (1504, 1), (1536, 1), (1568, 1), (1600, 1), (1632, 1), (1664, 1), (1696, 1), (1 Not so farfetched, all. Don't forget big-theta and big-omega. From larry.bates at websafe.com Wed Mar 19 14:02:46 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 19 Mar 2008 13:02:46 -0500 Subject: how to remove suffix from filename In-Reply-To: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> References: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> Message-ID: royG wrote: > hi > when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/ > two.jpg'....] etc i want to extract the > basename without the suffix...ie i want to get 'one','two' etc and not > 'one.jpg' > > is there a function in python to do this or do i have tosplit it ..? > thanks > RG import os fname='F:/mydir/two.jpg' filenameonly=os.path.splitext(os.path.basename(fname))[0] -Larry From igorr at ifi.uio.no Fri Mar 14 11:21:10 2008 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 14 Mar 2008 16:21:10 +0100 Subject: catching object References: <47d7d40a$0$2659$9b622d9e@news.freenet.de> Message-ID: [ stargaming at gmail.com ] [ ... ] > I think inheritance is meant in reference to the Exception tree here. So, > the uppermost class is `BaseException`. Python 3 gives this exception > when trying to handle `object`:: > > TypeError: catching classes that do not inherit from BaseException is > not allowed I realise that exceptions should inherit from Exception, but the question is more "why isn't an instance of ValueError a match for object, when ValueError is a subclass of object (at least in 2.5) [ ... ] > > So, why doesn't object match ValueError (or any other exception for that > > matter). I am aware of "except:", but in my particular situation it is > > eh... unsuitable. > > Why so? I am writing a function that takes a function and an exception list arguments and returns a new function that calls the original while trapping the specified arguments. One of the applications is to make a wrapper that ignores all of the exceptions. I thought that specifying the exception list containing object would suffice to cover that. Alas, no joy. [ ... ] ivr -- <+Kaptein-Dah> igorr: for f? parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent From removetoreply.djain at gmx.net Mon Mar 17 20:08:45 2008 From: removetoreply.djain at gmx.net (Dominik Jain) Date: Tue, 18 Mar 2008 01:08:45 +0100 Subject: how to create instances of classes without calling the constructor? Message-ID: <47df0816$0$6635$9b4e6d93@newsspool2.arcor-online.net> Hi! Does anyone know how an instance of a (new-style) class can be created without having to call the constructor (and providing the arguments it requires)? With old-style classes, this was possible using new.instance. Surely there must be a simple way to do this with new-style classes, too -- or else how does pickle manage? Best, Dominik From dundeemt at gmail.com Mon Mar 17 21:25:32 2008 From: dundeemt at gmail.com (dundeemt) Date: Mon, 17 Mar 2008 18:25:32 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> Message-ID: <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> On Mar 17, 10:35 am, fumanchu wrote: > On Mar 16, 5:09 pm, a... at pythoncraft.com (Aahz) wrote: > > > fumanchu wrote: > > > This is my third PyCon, and I've found a reasonably-sized cadre of > > > people who come for the hallway conversations plus a Bof or two, > > > having given up on hearing anything new, useful, or inspiring in the > > > talks. There are several people I know who would like to see a more > > > advanced academic track. > > > Finally, trying to satisfy a thousand people is impossible. > > Well understood. Sorry if I implied it was an easy job. I know it > isn't. > > > If you did not like the programming this year (aside from the sponsor > > talks) and you did not participate in organizing PyCon or in delivering > > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > > This would be true, except that the two talks I proposed last year > were essentially denied because they were too advanced, so I didn't > even bother this year. Perhaps I should have, but the PERIOD needs to > at least be replaced by a COMMA as long as the talk-acceptance > committee continues to reject more advanced talk topics in favor of > HOWTOs and Introduction To Package X. I agree - the balance wasn't as good. We can all agree that HowTos and Intros are a necessary part of the conference talks track, but as Robert pointed out some talks should be of a more advanced nature. I enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and Mark Hammond's keynote were among my favorite talks. -jeff hinrichs From sjmachin at lexicon.net Tue Mar 18 18:43:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Mar 2008 15:43:19 -0700 (PDT) Subject: os.path.getsize() on Windows References: <6abeaadf-0055-4216-9aed-ad87bc006038@h11g2000prf.googlegroups.com> Message-ID: <238ad1d1-f004-42b4-90ea-4474ec961616@u10g2000prn.googlegroups.com> On Mar 19, 9:27 am, Sean DiZazzo wrote: > On Mar 18, 2:27 pm, Duncan Booth wrote: > > > > > Sean DiZazzo wrote: > > > On windows, this returns the size of the file as it _will be_, not the > > > size that it currently is. Is this a feature? What is the proper way > > > to get the current size of the file? I noticed > > > win32File.GetFileSize() Does that behave the way I expect? > > > > PS. I also tried os.stat()[6] > > > I think all of those will return the current size of the file, but that may > > be the same as the final size: just because the data hasn't been copied > > doesn't mean the file space hasn't been allocated. You don't say how you > > are copying the file, but I seem to remember that Windows copy command pre- > > allocates the file at its final size (so as to reduce fragmentation) and > > then just copies the data after that. > > > If you need to make sure you don't access a file until the copy has > > finished then get hwatever is doing the copy to copy it to a temporary > > filename in the same folder and rename it when complete. Then you just have > > to check for existence of the target file. > > Hmmm... The file could be copied in by several different sources of > which I have no control. I can't use your technique in my situation. > I also tried getting md5 hashes with some time in between on advice, > but the file is not opened for reading until the copy completes so I > can't get the hashes. > > Any other ideas? Why not try to open the file for exclusive write/update access? From castironpi at gmail.com Tue Mar 4 23:57:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:57:58 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> > > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > > > >> >> is it makes it. > > > > >> >>>> from types import FunctionType, MethodType > > > >> >>>> class A( FunctionType ): pass > > > >> > ... > > > >> > Traceback (most recent call last): > > > >> > ? File "", line 1, in > > > >> > TypeError: type 'function' is not an acceptable base type > > > > >> Use delegation instead of inheritance. This class is almost ? > > > >> indistinguishable from a true function (when used as a method): > > If P gets, p gotcha. > > > > > gotcha= partial( get, you ). ?bor hor hor. ?Yes... > > Notwithstanding. ?Now bar has a name. Now func has it. from functools import wraps class myfunction: __slots__ = ('func','name') # def __init__(self, func): @wraps( func ) def f( *ar, **kws ): return func( self, *ar, **kws ) object.__setattr__(self, 'func', f) object.__setattr__(self, 'name', None) # def __get__(self, instance, owner): print( "__get__ called for",instance ) return self.func.__get__(instance, owner) # def __getattr__(self, name): return getattr(self.func, name) # def __setattr__(self, name, value): object.__setattr__(self.func, name, value) class mymeta( type ): def __init__( self, name, bases, namespace ): for k,v in namespace.items(): if isinstance( v, myfunction ): v.name= k class P( metaclass= mymeta ): def foo(self, x): print( 'foo',x ) # @myfunction def bar( fob,self, x): print( 'bar',fob,x ) p= P() p.foo( 0 ) p.bar( 1 ) print( p.bar ) print( p.bar.name ) From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 03:42:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 07:42:34 -0000 Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> Message-ID: <13u45bam9k12n71@corp.supernews.com> On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > suppose > origsz=(400,300) > i want to divide the origsize by 2.5 so i can resize to (160,120) > > scale=2.5 > how can i get the newsz? > obviously origsz/2.5 won't work .. newsz = (origsz[0]/scale, origsz[1]/scale) -- Steven From pavlovevidence at gmail.com Sun Mar 2 05:53:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Mar 2008 02:53:08 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: <21f9e110-04dd-4af3-a046-bb709b0ee5dc@x41g2000hsb.googlegroups.com> On Mar 2, 4:02 am, Kay Schluehr wrote: > On 2 Mrz., 06:53, Ben Finney > wrote: > > > One of the stated goals of the migration is that the '2to3' program > > will only migrate Python 2.6 code -> Python 3.0 code. > > Yes, I know. Why? > > "The master said so" isn't an entirely satisfying answer. What are the > *technical reasons* that make it hard to apply '2to3' directly on > Python 2.4 or Python 2.5? Well, even if you wanted to apply 2to3 to Python 2.5, you'd (probably) have to modify your code to make it 2to3-compatible. So if you're going to do that, you might as well upgrade to 2.6 to take advantage of new warnings and new idioms that are more conducive automatic translation. 2to3 is not a general tool to convert any given source code from 2.6 to 3.0. It's designed to make it possible to write code that works in Python 2.6 and Python 3.0, but to do that you have to use a "transitional Python" dialect that's a subset of 2.6. (It would be quite to attempt a general code translator, of course.) Anyway, I think there are a few cases in Python 2.5 where there's no easy way to write something that 2to3 can handle, and some specifically transitional features were added to 2.6 to remedy this. I don't recall specifics, though. It may be for the cases where things that previously returned lists now return iterators. Finally, 2.6 will have the benefit of being cross-checked with 3.0 to ensure that 2to3 does what it's supposed to when used as intended. All bets are off if you attempt it with 2.5. In the end, the real *technical* reason might have been the developers thought it wasn't worth the effort to backport it to 2.5. The above problems were probably solvable with enough effort, but would that have been a wise use of resources? One parenthetical I will add: 2to3 always seemed to me to be more of a way to enfore constraint on the design of Python 3.0. If a proposed feature couldn't be automatically ported to 3.0, then it was a big strike against the proposal. That it could end up being a useful transitional tool is nice, but it never seemed to be its primary purpose. Carl Banks From mh at pixar.com Mon Mar 10 14:00:44 2008 From: mh at pixar.com (mh at pixar.com) Date: Mon, 10 Mar 2008 18:00:44 GMT Subject: any chance regular expressions are cached? References: <51172306-ff2d-48e8-81cf-93be03f8a08f@s37g2000prg.googlegroups.com> Message-ID: John Machin wrote: > Yes they will be cached. great. > But do yourself a favour and check out the > string methods. Nifty... thanks all! -- Mark Harrison Pixar Animation Studios From Sandipan at gangopadhyay.com Sun Mar 16 18:55:40 2008 From: Sandipan at gangopadhyay.com (Sandipan Gangopadhyay) Date: Sun, 16 Mar 2008 18:55:40 -0400 Subject: Python for BlackBerry In-Reply-To: <79aa668a-f1b6-4f59-9ff9-8dc9dfc177aa@a23g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> <79aa668a-f1b6-4f59-9ff9-8dc9dfc177aa@a23g2000hsc.googlegroups.com> Message-ID: <14ae01c887b8$df23b290$9d6b17b0$@com> I checked; BlackBerry is not on Symbian. They provide a Java Dev Envt (whatever that may mean). Does that mean, we can try and implement JPython/Jython on it? Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of Mike Driscoll Sent: Sunday, March 16, 2008 8:47 AM To: python-list at python.org Subject: Re: Python for BlackBerry On Mar 15, 9:52 pm, "Sandipan Gangopadhyay" wrote: > Thanks, Mike. > This one seems to be for Nokia, particularly S60 and Symbian in general. > Does BlackBerry work on Symbian? Let me check. > Thanks. > Sandipan > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of Mike > Driscoll > Sent: Saturday, March 15, 2008 6:04 PM > To: python-l... at python.org > Subject: Re: Python for BlackBerry > > On Mar 15, 7:24 am, "Sandipan Gangopadhyay" > wrote: > > Is there a Python for BlackBerry? Thanks. > > > -----Original Message----- > > From: python-list-bounces+news=sandipan.... at python.org > > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of > E-Lo > > Sent: Saturday, March 15, 2008 6:03 AM > > To: python-l... at python.org > > Subject: Python for Palm OS > > > Is there any other edition of Python for Palm OS instead of Pippy? > > --http://mail.python.org/mailman/listinfo/python-list > > You might look at Mobile Python. I'm not sure if it works on > Blackberry though:http://www.mobilepythonbook.org/ > > Mike > --http://mail.python.org/mailman/listinfo/python-list I was afraid of that. I'm at PyCon and between their flakey wireless and my own laptop's flakey wireless card, it''s been a pain to do any research. Good luck. Mike -- http://mail.python.org/mailman/listinfo/python-list From paddy3118 at googlemail.com Fri Mar 28 01:52:30 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 27 Mar 2008 22:52:30 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> Message-ID: On Mar 28, 5:38 am, ankitks.mi... at gmail.com wrote: > >>> dict = {'M':3, 'R':0, 'S':2} > >>> print dict > > {'S': 2, 'R': 0, 'M': 3} > > now if I wanted sorted values in list, i am not able to do this>>> print dict.values().sort() > > None > > it returns None instead of [0, 2, 3] Try: from pprint import pprint as pp pp(my_dict) It works well for other built-in types too. P.S it is not good to use a name, dict, that already has a use in Python. - Paddy. From nickmiller92 at gmail.com Sun Mar 2 11:25:04 2008 From: nickmiller92 at gmail.com (Nick Miller) Date: Sun, 02 Mar 2008 10:25:04 -0600 Subject: Question on importing and function defs In-Reply-To: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> Message-ID: <47CAD4E0.9060904@gmail.com> TC wrote: > I have a problem. Here's a simplified version of what I'm doing: > > I have functions a() and b() in a module called 'mod'. b() calls a(). > > So now, I have this program: > > from mod import * > > def a(): > blahblah > > b() > > > The problem being, b() is calling the a() that's in mod, not the new > a() that I want to replace it. (Both a()'s have identical function > headers, in case that matters.) How can I fix this? > > Thanks for any help. > The only problem I could see with this is a local function issue. Meaning that even when you write the new a() function in the main source file, b() doesn't know it exists because it's relying on it's own "local" a() in the module. I'm also new to using Python so I that's all I can think would be the problem. Nick From yhidalgo86 at gmail.com Sun Mar 16 23:42:07 2008 From: yhidalgo86 at gmail.com (Yusniel) Date: Sun, 16 Mar 2008 20:42:07 -0700 (PDT) Subject: File system in TreeWidget References: Message-ID: <859e53e5-d27c-443d-8806-8b77d592e6eb@x30g2000hsd.googlegroups.com> On Mar 16, 11:39 pm, Yusniel wrote: > Hi friends. How can I do a Tree Widget with all directories and files > given path parameter or a tree generated with the function > os.walk(). Sorry for my bad english. Sorry. I am using PyQt4. From simon at brunningonline.net Thu Mar 6 15:07:46 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 6 Mar 2008 20:07:46 +0000 Subject: List all files using FTP In-Reply-To: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> References: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> Message-ID: <8c7f10c60803061207j4af58813g6e794c67b41c10bc@mail.gmail.com> On Thu, Mar 6, 2008 at 6:11 PM, jay graves wrote: > On Mar 6, 10:46 am, Anders Eriksson wrote: > > I need to list all the files on my FTP account (multiple subdirectories). I > > don't have shell access to the account. > > anyone that has a program that will do this? > > Not offhand, but you can look at the ftpmirror.py script for > inspiration. > It should be in your Tools/scripts/ subdirectory of your Python > installation. This might be of use: -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From paul.hankin at gmail.com Sat Mar 8 10:42:01 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 8 Mar 2008 07:42:01 -0800 (PST) Subject: extract multiple ranges from a list References: Message-ID: On Mar 8, 3:28?pm, pi.arc... at gmail.com wrote: > Hi guys, > > One of my many project involves working with YUV-files, where I need > to reduce > the vertical resolution with a factor of two, i.e. remove every other > scan line. > Today I'm using two for-loops in the fashion shown below > > y = [] > for i in range(0, width*height, width*2): > ? ? for j in range(0,width): > ? ? ? ? y.append(Y[i+j]) There's nothing really wrong with your code. Maybe it's a little nicer written like this: y = [] for i in range(0, height, 2): y.extend(Y[i * width + j] for j in range(width)) -- Paul Hankin From gagsl-py2 at yahoo.com.ar Sat Mar 29 20:12:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 21:12:33 -0300 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> Message-ID: En Sat, 29 Mar 2008 07:33:40 -0300, Steven D'Aprano escribi?: > The timeit.Timer class times "code snippets" -- you pass it strings > rather than function objects. That's good for what it's worth, but > sometimes the code you want to time is too big to easily pass as a > string, or maybe you only have access to a function object without the > source, or for whatever reason it's not very convenient. > > In this case, a good trick is to import the function by name: > > timeit.Timer('spam()', 'from __main__ import spam') > > > But now I find myself wanting to time a function that's not defined in > __main__. Here's a illustrative example: > > > def factory(): > def f(): > return "spam" > return f > > def main(): > func = factory() > return timeit.Timer('func()', 'from __main__ import func').timeit() Would this help (untested)? def main(): return timeit.Timer('func()', 'from __main__ import factory; func = factory()').timeit() Or maybe: def main(): global func func = factory() return timeit.Timer('func()', 'from __main__ import func').timeit() -- Gabriel Genellina From jef.mangelschots at gmail.com Tue Mar 4 12:51:49 2008 From: jef.mangelschots at gmail.com (jefm) Date: Tue, 4 Mar 2008 09:51:49 -0800 (PST) Subject: unicode box drawing Message-ID: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> How can I print the unicode box drawing characters in python: print u'\u2500' print u'\u2501' print u'\u2502' print u'\u2503' print u'\u2504' Traceback (most recent call last): File "\test.py", line 3, in ? print u'\u2500' File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500' in position 0: character maps to From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 5 03:16:52 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Mar 2008 09:16:52 +0100 Subject: multiplication of lists of strings In-Reply-To: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> References: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> Message-ID: <47ce56e9$0$10738$426a34cc@news.free.fr> castironpi at gmail.com a ?crit : (snip) > > That reminds me: Is there a generic 'relation' pattern/recipie, such > as finding a computer that's "paired" with multiple users, each of who > are "paired" with multiple computers, without maintaining dual- > associativity? > Yes : use a relational database. From castironpi at gmail.com Thu Mar 6 19:56:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 16:56:33 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: On Mar 6, 5:35?am, "Gabriel Genellina" wrote: > En Wed, 05 Mar 2008 02:57:58 -0200, escribi?: > > > > > > >> > > >> >> Can you overload -type-'s decision of what to 'bind'?... ? > >> whenever it > >> > > >> >> is it makes it. > > >> > > >> Use delegation instead of inheritance. This class is almost ? > >> > > >> indistinguishable from a true function (when used as a method): > > >> Notwithstanding. ?Now bar has a name. > > Now func has it. > > > from functools import wraps > > class myfunction: > > ? ? __slots__ = ('func','name') > > ? ? # > > ? ? def __init__(self, func): > > ? ? ? @wraps( func ) > > ? ? ? def f( *ar, **kws ): > > ? ? ? ? ?return func( self, *ar, **kws ) > > ? ? ? object.__setattr__(self, 'func', f) > > ? ? ? object.__setattr__(self, 'name', None) > > ? ? # > > ? ? def __get__(self, instance, owner): > > ? ? ? ? print( "__get__ called for",instance ) > > ? ? ? ? return self.func.__get__(instance, owner) > > ? ? # > > ? ? def __getattr__(self, name): > > ? ? ? return getattr(self.func, name) > > ? ? # > > ? ? def __setattr__(self, name, value): > > ? ? ? object.__setattr__(self.func, name, value) > > > class mymeta( type ): > > ? ? def __init__( self, name, bases, namespace ): > > ? ? ? ? for k,v in namespace.items(): > > ? ? ? ? ? ? if isinstance( v, myfunction ): > > ? ? ? ? ? ? ? ? v.name= k > > > class P( metaclass= mymeta ): > > ? ? def foo(self, x): print( 'foo',x ) > > ? ? # > > ? ? @myfunction > > ? ? def bar( fob,self, x): print( 'bar',fob,x ) > > > p= P() > > p.foo( 0 ) > > p.bar( 1 ) > > print( p.bar ) > > print( p.bar.name ) > > Mmm, looks too complicated and I don't see any advantage over the original ? > code. Functions already know their (original) name: func_name. If `name` ? > was just an example, note that functions already have writeable attributes ? > too, and my code exposes them as well. This should work with that version ? > (untested): > > p = P() > print p.bar.func_name # -> bar > p.bar.im_func.anotherattribute = 1 > print p.bar.anotherattribute # -> 1 > > (the attribute must be set on the *function* itself if you want it to be ? > somewhat persistent; methods are usually volatile objects) You read my mind. I was just getting: assert p.bar is p.bar and failing. But if you set them on im_func, instances don't have their own. From xkenneth at gmail.com Mon Mar 31 14:00:13 2008 From: xkenneth at gmail.com (xkenneth) Date: Mon, 31 Mar 2008 11:00:13 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> Message-ID: <304acc0a-3944-44a4-8626-30c2ab9da506@z38g2000hsc.googlegroups.com> Yeah, this is what I'm talking about: > def __eq__(self, other) : > ? try : > ? ? ?return <> > ? except AttributeError: > ? ? ?return False That seems a bit nasty to me. From ron at example.com Tue Mar 25 23:38:08 2008 From: ron at example.com (Ron Eggler) Date: Wed, 26 Mar 2008 03:38:08 GMT Subject: last mouse movment or keyboard hit Message-ID: Hi, I would like to get the time of the most recent human activity like a cursor movement or a key hit. Does anyone know how I can get this back to start some action after there has been no activity for X minutes/seconds? Thank you! -- chEErs roN From darrin_allen at japan.com Sun Mar 2 09:31:04 2008 From: darrin_allen at japan.com (t3chn0n3rd) Date: Sun, 2 Mar 2008 06:31:04 -0800 (PST) Subject: Python newbie Message-ID: i am a python newbie. My studies have me in many directions From mensanator at aol.com Tue Mar 4 18:58:41 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 15:58:41 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <042d507d-f53d-4219-be6e-d6b7a1f1d6c4@s8g2000prg.googlegroups.com> <8aa1c242-db46-4479-a26c-07517b478714@n75g2000hsh.googlegroups.com> Message-ID: On Mar 4, 4:40?pm, Mensanator wrote: > On Mar 4, 3:00?pm, Istvan Albert wrote: > > > On Mar 4, 3:13 pm, Mensanator wrote: > > > > But what if _I_ wanted to make a repeatable sequence for test > > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > > on every call? > > > Would it? > > I don't know, haven't tried it yet, Now I have and there is no problem. > merely extrapolating from how I _THINK_ it works. And my thinking was mistaken, the patch doesn't reset the seed, so nevermind. > I used to be a System Test Engineer > and had a gift for being able to walk up to hardware/software > and break it. Spooky? No, because I could extrapolate from > the design, I could often anticipate just where to nudge it to > cause it to crash. I wasn't very popular with the programmers. > > > > > It may just be that you are now itching to see a problem even where > > there isn't one. > > No, no, no. That would be an oh-what-a-giveaway, wouldn't it? > > > > > > > i.- Hide quoted text - > > - Show quoted text - From frikker at gmail.com Wed Mar 5 11:17:22 2008 From: frikker at gmail.com (blaine) Date: Wed, 5 Mar 2008 08:17:22 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> <13sr22ii98uipc4@corp.supernews.com> <13ssb8fjrdecbfe@corp.supernews.com> Message-ID: > Because it is NOT 0x10007... It is OCTAL 010007 -- which just > happens to map to hexadecimal 0x1007 > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ oh wow - that makes a lot more sense. haha. The processor we are going to use is ARM, yes, but our development at this point (to keep it simple) is just on a simple linux laptop pc. Thanks again for all the help :) From barnburnr at gmail.com Mon Mar 3 15:14:29 2008 From: barnburnr at gmail.com (barnburnr at gmail.com) Date: Mon, 3 Mar 2008 12:14:29 -0800 (PST) Subject: clocking subprocesses References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> <5af6d8ab-880a-4873-9352-cf1aaae236e0@e6g2000prf.googlegroups.com> Message-ID: On Mar 3, 12:41 pm, Preston Landers wrote: > > Run your command through the "time" program. You can parse the output > format of "time", or set a custom output format. This mostly applies > to Unix-like systems but there is probably an equivalent somewhere on > Windows. > > Preston Thanks for the quick answer. That seems to work, though, I'll write a timesubprocess() function which runs the program through time and spits the formatted out to a file, then parses that file, then returns the execution time. There doesn't appear to be a more elegant way to do this. Kevin From duncan.booth at invalid.invalid Fri Mar 7 03:46:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Mar 2008 08:46:43 GMT Subject: Looking for very light weight template library (not framework) References: Message-ID: "Malcolm Greene" wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. You could try using the Template class: >>> from string import Template >>> class EvalTemplate(Template): idpattern = '[^{}]+' >>> class EvalDict(dict): def __getitem__(self, name): if name in self: return dict.__getitem__(self, name) return eval(name, globals(), self) >>> class Invoice: def __init__(self, total): self.total = total >>> i = Invoice(42) >>> template = EvalTemplate("The total cost is ${invoice.total}") >>> template.substitute(EvalDict(invoice=i)) 'The total cost is 42' The usual caveats about using 'eval' apply (maybe it should be called EvilDict), and I'm sure you could override substitute/safe_substitute to construct the EvalDict transparently. From bryanjugglercryptographer at yahoo.com Thu Mar 13 14:50:47 2008 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Thu, 13 Mar 2008 11:50:47 -0700 (PDT) Subject: subprocess.Popen pipeline bug? References: Message-ID: <026208f0-cd70-4f6a-bfe5-9f8f09a5b0f6@n58g2000hsf.googlegroups.com> Marko Rauhamaa wrote: > This tiny program hangs: > > ======================================================================== > #!/usr/bin/env python > import subprocess > a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, > stdout = subprocess.PIPE) > b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) > a.stdin.close() > b.wait() # hangs > a.wait() # never reached > ======================================================================== To make it work, add close_fds=True in the Popen that creates b. > It shouldn't, should it? Not sure. I think what's happening is that the second cat subprocess never gets EOF on its stdin, because there are still processes with an open file descriptor for the other end of the pipe. The Python program closes a.stdin, and let's suppose that's file descriptor 4. That's not enough, because the subshell that ran cat and the cat process itself inherited the open file descriptor 4 when they forked off. It looks like Popen is smart enough to close the extraneous descriptors for pipes it created in the same Popen call, but that one was created in a previous call and passed in. -- --Bryan From danb_83 at yahoo.com Mon Mar 17 02:56:50 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 16 Mar 2008 23:56:50 -0700 (PDT) Subject: String To List References: Message-ID: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> On Mar 17, 1:15 am, Girish wrote: > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? > Thanks for the help... eval(a) will do the job, but you have to be very careful about using that function. An alternative is [s.strip('\'"') for s in a.strip('[]').split(', ')] From yhidalgo86 at gmail.com Sun Mar 16 23:39:28 2008 From: yhidalgo86 at gmail.com (Yusniel) Date: Sun, 16 Mar 2008 20:39:28 -0700 (PDT) Subject: File system in TreeWidget Message-ID: Hi friends. How can I do a Tree Widget with all directories and files given path parameter or a tree generated with the function os.walk(). Sorry for my bad english. From ncoghlan at gmail.com Tue Mar 11 05:43:29 2008 From: ncoghlan at gmail.com (NickC) Date: Tue, 11 Mar 2008 02:43:29 -0700 (PDT) Subject: for-else References: Message-ID: On Mar 4, 11:27 pm, bearophileH... at lycos.com wrote: > > The meaning is explicit. While "else" seems to mean little there. > So I may like something similar for Python 3.x (or the removal of the > "else"). Consider a loop with the following form: while 1: if : <0-to-many times code block> else: <0-to-1 times code block> break A break, return or exception in the 0-to-many times code block will obviously skip over the 'else' part of that if statement - it will only be executed if evaluates as a false value. The above code is actually equivalent to a normal Python while-loop: while : <0-to-many times code block> else: <0-to-1 times code block> For loops aren't quite so straightforward since the termination condition is tied up with the StopIteration exception, but the clause keeps the same name as the corresponding clause on the while loop. Thinking of it as break-else (as someone else posted) probably isn't a bad way to look at the situation. Cheers, Nick. From Lie.1296 at gmail.com Sat Mar 8 12:45:38 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 09:45:38 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> Message-ID: Personally I preferred a code that has chosen good names but have little or no comments compared to codes that makes bad names and have twenty pages of comments to read and understand what it's about. Personally, I think comments should be made as short and as concise as possible and codes should try to be self-understandable if the comments aren't accessible. From cwitts at gmail.com Tue Mar 18 06:18:20 2008 From: cwitts at gmail.com (Chris) Date: Tue, 18 Mar 2008 03:18:20 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: On Mar 18, 11:57?am, Simon Forman wrote: > Is there a more efficient way to do this? > > def f(L): > ? ? '''Return a set of the items that occur more than once in L.''' > ? ? L = list(L) > ? ? for item in set(L): > ? ? ? ? L.remove(item) > ? ? return set(L) > > |>> f([0, 0, 1, 1, 2, 2, 3]) > set([0, 1, 2]) def f(L): D = dict() for item in L: if item in D: D[item] += 1 else: D[item] = 1 return [i for i,j in D.items() if j > 1] That would be my way to do it, would need to test it via several thousand iterations to see which one is most efficient though. From gherron at islandtraining.com Mon Mar 31 15:06:30 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 31 Mar 2008 12:06:30 -0700 Subject: [OT] troll poll In-Reply-To: References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> Message-ID: <47F13636.4030401@islandtraining.com> Duncan Booth wrote: > Paul Rubin wrote: > > >> "Daniel Fetchinson" writes: >> >>> [ ] - Xah Lee >>> [ ] - castironpi >>> >> I've lost track but has it been established that they are not the same >> person? >> >> > Has it actually been established that castironpi is actually a person? I > thought it was probably a random sentence generator. > Ahhh... Perhaps someone is running a Turing test on us. That is, if we can't tell the difference between castironpi and a *real* human (which we demonstrate whenever we try to respond to or reason with him/her/it), then castironpi can be declared to be a truly *intelligent* AI. AFAICT, there appears no danger of that happening yet. Gary Herron :-) From adairicky at gmail.com Sat Mar 8 10:43:05 2008 From: adairicky at gmail.com (333) Date: Sat, 8 Mar 2008 07:43:05 -0800 (PST) Subject: wholesale and retail nike sports shoes,nike shox,air maxss,dunks Message-ID: <4f755f56-4b38-4225-b423-174b673fc7f9@s13g2000prd.googlegroups.com> our website: http://www.FASHION4BIZ.com our MSN:fashion4biz at msn.com our EMAIL:fashion4biz at gmail.com paypal accept,wholesale and retail accept,dropship accept sale new Nike Sneakers,Air Jordan Sneakers,AIR FORCE 1S,Nike Dunks SB, Bape Sta from nike outlets and factory stores, also Nike wholesale - Jordan Shoes we supply nike sneaker jordan sneaker air force 1s ... Featuring unique gift ideas for birthdays, weddings, anniversaries & holidays.Nike Air Max LTD-Nike Air Max Ltd Shoes, Nike Air Max Ltd Trainers. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Air Max - Nike Air Max TN Plus,TN BURBERRY,Gucci,TN L.V.. NIKE TN REQUINS CHAUSSURES, neuves hommes Nike TN basketball shoes requins Chaussures : Nike Air Max TN Plus men's ,Nike Shox - Mens, Womens Nike Shox basketball shoes wholesale from china Nike Shox TL NZ R4 R5 Turbo Monster Nike shoes wholesale,Puma - Puma Shoes. Nike shoes wholesale: Puma Shoes men's women's trainers .. Puma Shoes cheap discount shoes nike wholesale and sale to nike shop and nike We sell Nike Air Max shoes,nike air max trainers for running and training- Nike Air Max 360 95 97 2003 Tn Plus Nike shoes wholesale,air max2 cb 94,air max2 cb,air ...Nike Wholesale,Nike Sneaker, jordan Sneaker, Air Force one 1s, Dunk Dunks Jordan Jordans Air Max Shox Rift ... Timberland. Timberland boots,Timberland shoes, Prada wholesale, Prada sale, Prada shop, Prada store. we wholesale and sale cheap discount Timberland men's women's ,We Wholesale Cheap Jordan Shoes, Michael Jordan Shoes, Nike Jordan Basketball shoes, Nike Air Jordan ... Once again, thank you for www.fashion4biz.com Timberland - Timberland Boots. Nike shoes wholesale: Timberland Boots men's women's trainers sneakers basketball shoes running shoes. Timberland Boots cheap discount Nike Air Max 90-Nike Air Max 90 Shoes, Nike Air Max 90 trainers. ... nikeshoes Nike Air Max -> Nike Air Max 90 (Note Mens model size 41 42 43 44 45 46.Nike shoes buy, nike shoes wholesale, buy nike shoes from china nike shoes wholesale ... www.fashhion4biz.com ,Nike Running shoes,nike shox and nike air max Running shoes, nike shox tl nz r4 turbo monster running shoes,nike air max tn,Puma - Puma Speed Cat. Nike shoes wholesale: Puma Speed Cat men's women's trainers sneakers basketball shoes running shoes,Nike Air Max 2003-Nike Air Max 2003 Trainers,Nike Air Max 2003 Shoes. ... Nike Air Max 2003 cheap discount shoes nike wholesale and sale to nike shop and nike store.Nike Air Max - Nike Air Max 2004 trainers. Nike shoes wholesale: Nike Air Max ... Nike Air Max 2003 cheap discount shoes nike wholesale and sale to nike shop and nike factory.Nike Air Jordan 3,nike jordan 3 retro shoes,nike air jordan 3 retro sneakers, Nike air jordan 3 shoes wholesale: Nike Air Jordan 3 men's women's trainers sneakers ,Nike Shox - Nike Shox TL NZ R4 R5 Turbo Monster Nike shoes wholesale. We wholesale nike shoes: Nike Shox TL, Nike Shox NZ, Nike Shox R4, Nike Shox R5, Nike Shox Nike Air Dunk - Nike Air Dunk High. Nike shoes wholesale: Nike Air Dunk High men's women's trainers sneakers running shoes.Nike Air Max 97, Nike Womens Air Max 97 trainers, nike mens air max 97 trainers, nike air max 97 running shoes sell cheap with discount,Nike Air Force 1 - Nike ... Nike Air force 1 High cheap discount shoes nike wholesale and ... We also sale and wholesale nike shoes other styles:nike air we sell cheap Nike Air Max 95 shoes and trainers for womens, mens and for running, trainning, tennis with all black color, pink color,red, blue..with discount,Nike air jordan shoes for wholesale, We wholesale ans sale nike air jordan Basketball shoes, buy quality of nike air jordan running shoes trainers sneakers for our ...Nike cheap shoes, we sale nike shoes in cheap price, buy cheap nike shoes Adidas. Adidas shoes, Adidas wholesale, Adidas shop, Adidas store, Adidas goodyear, Adidas TMAC, Adidas Running shoes,we wholesale and sale cheap discount Adidas.Nike Dunk - Nike Air Dunk. Nike Dunk Air Dunk Low Mid High Nike shoes wholesale. We wholesale Nike Dunk Air Dunk Men's Women's shoes wholesale at cheap discount price,Nike Air Rift - Nike Rift Air Rift Nike shoes wholesale. We wholesale nike shoes; Nike Rift shoes, Nike Air Rift shoes.Puma - Puma Joggers. Nike shoes wholesale: Puma Joggers men's women's trainers ... Puma Joggers cheap discount shoes nike wholesale and sale to nike shop and nike Adidas - Adidas Shoes. Nike shoes wholesale: Adidas Shoes men's women's trainers ... Adidas Shoes cheap discount shoes nike wholesale and sale to nike shop and nike Shoes. Nike Air Max. Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike Air Max 95 ... Nike Air force 1 Low. Nike Air force 1 High. Nike Air Jordan Nike Air Max Nike Air Max 360 95 97 2003 Tn Plus ... Nike Air Max 360, Nike Air Max 95, Nike Air Max 97, Nike Air Max 2003, ... www.fashion4biz.com ,Nike Air Jordan 2, Nike Jordan 2 Retro Shoes Nike Air Jordan 2 shoes wholesale: Nike Air Jordan 2 men's women's trainers sneakers basketball shoes running shoes,Nike Air Max - Nike Air Max 2005, Nike Air Max 2005 Trainers. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ,Nike Air Jordan 11 Retro- Nike Air Jordan XI Retro. ... Nike Air Jordan 11 cheap discount shoes nike wholesale and sale to nike shop andJordan 5-Jordan V,Nike Air Jordan 5 V- Nike Air Jordan 5. Nike air jordan 5 shoes wholesale: Nike Air Jordan 5 men's women's trainers sneakers basketball shoes ,Nike Air Force 1 - Nike ... Nike Air force 1 Low cheap discount shoes nike wholesale and ... We also sale and wholesale nike shoes other styles:nike air max ...Nike Shox Turbo- Nike Shox Turbo Oh+. Nike Shox Trubo shoes . ... We also sale and wholesale Original,Retro,Retro + ,Re-Retro +,Re-Retro Laser,Nike Shox - Nike Shox R4. Nike shoes wholesale: Nike Shox R4 men's women's ... Nike Shox R4 cheap discount shoes nike wholesale and sale to nike shop and nike ,Nike Air Jordan 12- Nike Air Jordan Xii. Nike Air Jordan 12 Retro shoes wholesale: Nike Air Jordan 12 men's women's trainers sneakers basketball shoes running ...Nike Air Max - Nike Air Max TN Plus. Nike shoes wholesale: Nike Air Max TN Plus ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Shoes. Nike Air Max. Nike Air Max TN Plus. Nike Airwholesale: Nike Shox ... Nike Shox Turbo oh, iv,iii shoes here at cheap price from wwww.fashion4biz.com ...Nike Air Dunk - Nike Air Dunk Low. Nike shoes wholesale: Nike Air Dunk Low men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ,Jordan 4 - Jordan 4 retro, Jordan iv retro sneakers Max 90. Nike Air Max 91. Nike Air Max 95 ... Nike Air force 1 Low. Nike Air force 1 High. Nike Air Jordan Nike Air Max Vends Nike Air Max TN Requin Chaussures. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Air Max 360, Nike ... Nike Air Max 360 cheap discount shoes nike wholesale and sale ... We also sale and wholesale nike Air Max shoes other styles:Nike Nike shop wholesale nike shoes include: Nike air jordan, Nike air dunk, Nike shox tl nz r4 turbo monster, Nike air ... Nike Replica shoes wholesale, wholesale replica shoes nike timberland Nike Shox - Nike Shox TL. Nike shoes wholesale: Nike Shox TL ... Get your cheap Nike Shox tl shoes for mens and womens at www.fashion4biz.com Nike Air Jordan - Nike Air Jordan XXI 21. Nike Air Jordan 21 XXI 11 3 4 5 6 7 20 ... We wholesale nike air jordan 21 1 2 3 4 5 6 8 9 10 11 12 13 14 17 18 19 20 21 22 retro cards.Prada - Prada Americas Cup. Nike shoes wholesale: Prada Americas Cup men's women's trainers sneakers basketball shoes running shoes. Prada Americas Cup cheap Nike Shox - Nike Shox BMW. Nike shoes wholesale: Nike Shox BMW men's women's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Shox R5- Nike Shox R5 Shoes. Nike shoes wholesale: Nike Shox R5 men's ... Nike Shox R5 cheap discount shoes nike wholesale and sale to nike shop and nike ...BapeSta - BapeSta Shoes. Nike shoes wholesale: BapeSta Shoes men's women's trainers sneakers basketball shoes running shoes. BapeSta Shoes cheap discount shoes nike Nike Air Jordan Xvi- Nike Air Jordan 16. Nike Air Jordan 16 retro shoes wholesale: Nike Air Jordan 16 men's women's trainers sneakers basketball shoes running shoes,Nike Shox 3- Nike Shox TL III. Nike shoes wholesale: Nike ... Get your cheap Nike Shox TL 3 III with wholesale price at www.fashion4biz.com,Nike Shox Monster - Nike Shox Monster Shoes. Nike Shox Monster shoes wholesale: ... and Womens Nike Shox Monster shoes at www.fashion4biz.com Nike Air Jordan 6 shoes- Nike Air Jordan 6 retro sneakers. ... jordan 6 shoes and sneakers Nike Air Max - Nike Air Max 91. Nike shoes wholesale: Nike Air Max 91 men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max Nike Air Jordan Dub Zero for wholesale, Nike Air Jordan dub zero shoes, Nike Air ... Shoes ID: JDB-02. Air Jordan Dub- Zero. Nike Air Jordan 5- Nike Air Jordan 5 v retro shoes. ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ...BapeSta,A baping ape sta,Baping Sta,Bape sta,shoes,shop,store,sale,wholesale ... Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike Air Max 95. Nike Air ...Puma shoes, wholesale and sale Puma shoes from our puma shop puma store, wholesale and sale Puma shoes sizes include mens women's mens womens.Nike Air Jordan 8 sneakers-Nike Air Jordan VIII Shoes. ... Nike Air Jordan 8 cheap discount shoes nike wholesale and sale to nike shop and Nike Air Max - Nike Air Max LTD. Nike shoes wholesale: Nike Air Max LTD men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max ...Nike Shox - Nike Shox NZ. Nike Shox Nz shoes wholesale: Nike Shox NZ men's .. Nike Shox NZ cheap discount shoes nike wholesale and sale to nike shop and nike We Sell Air Jordan 1 Shoes, Nike Air Jordan 1 Retro shoes at cheap price for wholesale and ... Nike Air Jordan 1, Nike Air Jordan 1 Retro for Mens.Nike Air Max , Nike Air Max 95. Nike shoes wholesale: Nike Air Max 95 men's ... We also sale and wholesale nike shoes other styles:nike air max - nike air max.Nike Shox TL II 2, Nike Shox TL 2, Nike Shox TL II, Nike Shox TL 2 II running shoes, We wholesale Litmited nike shox TL 2 II mens' women's shoes.Nike Air Max 97, Nike Womens Air Max 97 trainers. ... Nike Air Max 97 cheap discount shoes nike wholesale and sale to nike shop and Nike Air Max 90, Nike Air Max 90 running, Nike Air Max 97 Women's Trainer, Nike Air Max 90 shoes. ... We can Produce shoes in all sizes : Kids shoes , Big size US 14 US15 Prada shoes, Prada shoes wholesale, Prada Americas Cup shoes wholesale. ... Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike Air Max 95. Nike Air Max 97 Nike Shox - Nike Shox Turbo. Nike shoes wholesale: Nike Shox Turbo men's women's ... Nike Shox Turbo cheap discount shoes nike wholesale and sale to nike shop and Nike Air Max 90, Nike Air Max 90 running Trainers, Nike Air Max 90 shoes. ... Nike Air Max 360, Nike Air Max 360 running, nike air max 360 Shoes, Nike air max 180.Nike Air Jordan - Nike Air Jordan 8 sneakers. Nike shoes wholesale: Nike Air Jordan 8 men's women's trainers sneakers basketball shoes running shoes. Nike Air,Nike air jordan shoes for wholesale, We wholesale ans sale nike air jordan Basketball shoes, buy quality of nike air jordan running shoes trainers sneakers for our.Prada shoes, Prada shoes wholesale and sale, buy replica prada shoes from our prada shop store. ... Nike Air Max TN Plus. Nike Air Max 90. Nike Air Max 91. Nike ,Evisu T- shirts,Gino Green Global t -shirts Lacoste polo china wholesale,Polo shirts t-shirts Edhardy chanel AF bape CD evisu shirt B.R.M t-shirts Dsquared,LRG tshirts,lacoste shirts t-shirts g-star and BBC,DG,burberry t-shirts,shirt china wholesale,china t-shirts at cheap price,factory wholesale price,nike,polo for child,Sean John,prada,GUINT,CROPPED HEADS armani,10 deep t-shirt,COOGI,juicy t- shirts desquared woman t-shirt,callaway-golf,baby woman t- shirts,artfull dodger,adidas,seven shirts t-shirts NBA jerseys NFL jersey,nba jersey china factory wholesale,discount nfl jersey china suppliers. lacoste t-shirts Made In China Products,lacoste t-shirts China Suppliers and China Manufacturers, lacoste t-shirts China wholesale. Red monkey jeans evisu edhardy Made In China edhadry jeans bape hoody bape bbc hoodies Products,evisu jeans China Suppliers and China Manufacturers,edhardy jeans China Salers,seven jeans China Buyers,evisu jeans manufacturer,evisu factory wholesale.cheap evisu jeans,discount diesel jeans.replica evisu jeans,china wholesale evisu boss jeans.cheap red monkey jeans,discount BBC jeans, wholesale ape jeans, ANTIK jeans,DG jeans,TAVERNITI SO JEANS china suppliers Levis jeans,take two jeans,bape Diesel jeans factory wholesale ,artful dodger green bbc global jeans,seven jeans,true religion jeans rock republic jeans evisu jeans manufacture edhardy jeans D&G woman Jeans rock republic woman jeans people for peace jeans,buy wholesale sale sell cheap jeans men's.Wholesale replica designer Handbags, replica knockoff designer handbag, gucci,handbag,coach handbag,chanel handbag. coach handbag,louis vuitton,handbag,Cheap gucci,handbag wholesale,discount handbag prada,fendi handbag china wholesaler,burberry handbag factory,wholesale designer handbag, OEM factory dooney and bourke handbag in china, chloe handbag cheap,handbag dior,handbag lv replica handbag,juicy couture handbag dooney and burke replica handbag replica knockoffs fake handbag marc jacobs replic,Cellular Phones, Cell Phones, Wireless Phones, Wholesale Cell Phones, Wholesale, Nokia N95, wholesale price, dropship, import and export deal, stock details ,Nokia N95 at Wholesale Price for exporters from outside of China.China Distributor/Wholesaler of Nokia N95, 8800, N93, N93i, N90, N77, N75, ... wholesale replica nokia sirocco motorola samsung,apple iphone vertu.Sell Mobile Phone N95, Mobile Phone, Nokia Phone, Cell Phone ... wholesale Mobile Phone supplier in China,wholesale :Mobile Phone,Nokia N95,Nokia ,Nokia N95, 8800, N93, N93i, N90, N77, N75, 5700xm, Samsung, Motorola, Dopod, Blackberry, GSM, Dual Sim Card Cell Phone. Get ... wholesale ... Mobile Phones ,Latest Mobile Phones. Nokia 5700. Nokia N95 ... on mobile phones | wholesale Nokia phone deals | wholesale Motorola phone deals From jeff at schwabcenter.com Thu Mar 13 15:37:09 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 13 Mar 2008 12:37:09 -0700 Subject: Is there Python equivalent to Perl BEGIN{} block? In-Reply-To: <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> References: <13tgrqb132if842@corp.supernews.com> <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> Message-ID: Paddy wrote: > On Mar 13, 7:03 pm, Jonathan Gardner > wrote: >> On Mar 12, 6:37 pm, Carl Banks wrote: > > <> >> And leave out the magical -p and -n. If you want to iterate through a >> file, "for line in sys.stdin:". > > Or better still: > > import fileinput > for line in fileinput.input(): > process(line) I write maybe a dozen one-liners a day. It's not practical to do this with Python, or at least it's not nearly as convenient as Perl. I'm fine with the magic. Abusing the magic is another story; Perl language features are meant to be used in particular contexts, and BEGIN blocks are rarely if ever necessary in Perl modules. From malkarouri at gmail.com Sat Mar 8 17:20:40 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 14:20:40 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <47D2C25C.9050400@v.loewis.de> Message-ID: <6fd3179f-1b32-4593-a552-43e73e091a17@34g2000hsz.googlegroups.com> On Mar 8, 4:44?pm, "Martin v. L?wis" wrote: ... > Notice that the language specification *deliberately* does not > distinguish between deletion of earlier and later items, but > makes modification of the sequence undefined behavior to allow > alternative implementations. E.g. an implementation that would > crash, erase your hard disk, or set your house in flames if you > confront it with your code still might be a conforming Python > implementation. Really appreciated, Martin. It was exactly the *deliberately* part I am interested in. Settles it for me. Thanks, Muhammad Alkarouri From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 04:16:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 08:16:31 -0000 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> <69175d52-a701-40f2-9803-0e422e8d4f8f@d62g2000hsf.googlegroups.com> Message-ID: <13umluvs1vdor02@corp.supernews.com> On Wed, 26 Mar 2008 00:55:22 -0700, Arnaud Delobelle wrote: [snip] > Except it only *appears* to work. What happens if were store the > instances in a list and then execute them all in one go? Ah yes, nicely spotted. Another solution would be to use a proper factory function: def factory(record): def f(n): return (record + " ")*n return f class MyClass(object): pass records = ["spam", "ham"] instances = [] for record in records: instance = MyClass() setattr(instance, 'execute', factory(record)) instances.append(instance) for instance in instances: instance.execute(5) -- Steven From jkugler at bigfoot.com Fri Mar 14 15:44:05 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 14 Mar 2008 11:44:05 -0800 Subject: How to import custom python file in python server page (psp) ? References: <60bb95410803140415x621b5b23w75b83013997c750b@mail.gmail.com> Message-ID: James Yu wrote: > Hi folks, > > I prepared a python script for dynamically get the absolute paths of the > files in certain folder. > Then I tried to invoke that function from my web server in a .psp file > like this: > > 1 > 2 > 3 asdfasdfasdfa > 4 > 5 <% > 6 import glob > 7 import os > 8 *import Helper > * 9 > 10 body = '' > 11 top = 'asdfasdfasdfa' > 12 links = {} > 13 *Helper.GetLinks(top=top) > * 14 *paths = Helper.GenLinkPath(links) > * 15 body = paths > 16 %> > 17 <%=body%> > 18 > 19 > > However, this is the error message I received when I open the page in a > browser: > >> Mod_python error: "PythonHandler mod_python.psp" >> >> Traceback (most recent call last): >> >> File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, >> in HandlerDispatch >> result = object(req) >> >> File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 302, in >> handler >> p.run() >> >> File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 213, in >> run >> exec code in global_scope >> >> File "/var/www/.cyu021/.pic/index.psp", line 8, in >> import Helper >> >> ImportError: No module named Helper > > > *PS. I put Helper.py and index.psp in the same dir > * > Thanks in advance, What is the import path? The current directory in PSP might not be the directory in which the .psp file resides. Print out sys.path before you import your helper module to see what paths you're dealing with. j From sjmachin at lexicon.net Fri Mar 21 18:47:43 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 15:47:43 -0700 (PDT) Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> Message-ID: <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: > [1] Just one example:http://docs.mootools.net/Class/Class.js Mootools being something a coworker might use? From schiz at lon.don Sun Mar 2 05:25:49 2008 From: schiz at lon.don (Schizoid Man) Date: Sun, 02 Mar 2008 10:25:49 +0000 Subject: Beginner's assignment question In-Reply-To: References: Message-ID: Lorenzo Gatti wrote: > On Mar 1, 3:39 pm, Schizoid Man wrote: >> As in variable assignment, not homework assignment! :) >> >> I understand the first line but not the second of the following code: >> >> a, b = 0, 1 >> a, b = b, a + b >> >> In the first line a is assigned 0 and b is assigned 1 simultaneously. >> >> However what is the sequence of operation in the second statement? I;m >> confused due to the inter-dependence of the variables. > > The expressions of the right of the assignment operator are evaluated > before assigning any new values, to the destinations on the left side > of the assignment operator. > So substitutig the old values of a and b the second assignment means > > a, b = 0, 0 + 1 > > Simplifying the Python Reference Manual ("6.3 Assignment Statements") > a little : > > assignment_stmt ::= target_list "="+ expression_list > > An assignment statement evaluates the expression list (remember that > this can be a single expression or a comma-separated list, the latter > yielding a tuple) and assigns the single resulting object to each of > the target lists, from left to right. > > [...] > > WARNING: Although the definition of assignment implies that overlaps > between the left-hand side and the right-hand side are `safe' (for > example "a, b = b, a" swaps two variables), overlaps within the > collection of assigned-to variables are not safe! For instance, the > following program prints "[0, 2]": > > x = [0, 1] > i = 0 > i, x[i] = 1, 2 > print x > > Lorenzo Gatti Thank you for the explanation. I guess my question can be simplified as: First step: a, b = 0, 1 No problem here as a and b are assigned values. Second step: a, b = b, a + b Now my question is does b become a + b after a becomes 1 or while a stays at 0? As the assignment occurs simultaneously I suppose the answer is while a stays at 0. Thank you. From grante at visi.com Sat Mar 22 11:44:31 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Mar 2008 15:44:31 -0000 Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> <5bd9b02a-958b-452d-9e20-c10e4c29f9e4@i29g2000prf.googlegroups.com> Message-ID: <13uaaavi55n7d9b@corp.supernews.com> On 2008-03-22, harrelson wrote: >>> proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) >>> stderr_value = proc.communicate()[0] >>> print stderr_value >> dialog displays the widget on stdout. You've connected stdout >> to a pipe, so you're not going to see anything displayed unless >> you read data from the stdout pipe and write it to the terminal. > > Reading this tutorial on subprocess: > > http://blog.doughellmann.com/2007/07/pymotw-subprocess.html > > led me to believe this was exactly what I was doing. Ah, my mistake. I believed you when you named the variable "stderr_value". ;) I've never used the communicate() method, but according to that tutorial: "The communicate() method reads all of the output and waits for child process to exit before returning. And the lib references says: communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). The key is that it doesn't return until after the subprocess has terminated. So, you're reading stdout and putting it in the variable you named stderr_value. After the dialog exits, you then print the stdout string (which contains the widget's "display" data). Since the widget has already exited, that string contains both the initial display _and_ the escape sequence that clears the screen and restores it. So, you just see a flash of blue. If you want to be able to see and interact with the widget, you need to leave stdout connected to the terminal while the widget is running. Try this: ------------------------------------------------------------ import subprocess command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" "4 this and that"' proc = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE) stdout,stderr = proc.communicate() print stderr ------------------------------------------------------------ NB: using shell=True introduces a number security holes and adds the overhead of starting a shell. It's good practice to avoid it if you don't actually need a shell (you don't). However, without it you need to split up the command line explicitly: ------------------------------------------------------------ import subprocess command = ('/usr/bin/dialog','--clear','--title','title', '--menu','text','20','50','5', 'a','this and that', 'c','3 this and that', 'b','2 this and that', 'd','4 this and that') proc = subprocess.Popen(command, stderr=subprocess.PIPE) stdout,stderr = proc.communicate() print stderr ------------------------------------------------------------ If you're generating the commands programatically, it's usually simpler to generate them as tuples as shown in the second example anyway. -- Grant Edwards grante Yow! I joined scientology at at a garage sale!! visi.com From stugots at qwest.net Sun Mar 2 13:01:45 2008 From: stugots at qwest.net (John DeRosa) Date: Sun, 02 Mar 2008 10:01:45 -0800 Subject: Beautiful Code in Python? References: Message-ID: On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: >Hi, > >Have you ever seen Beautiful Python code? >Zope? Django? Python standard lib? or else? > >Please tell me what code you think it's stunning. Just about any Python code I look at. From israelu at elbit.co.il Sun Mar 30 07:42:46 2008 From: israelu at elbit.co.il (iu2) Date: Sun, 30 Mar 2008 04:42:46 -0700 (PDT) Subject: License of Python Message-ID: Hi guys, I'd like to use Python in a commercial application. In fact I would like to write the application entirely in Python. But I think I wouldn't like telling what language the application is written in. The problem is that including Python's license in the binary, which as I understand is a must do, reveals that the appliation is based on Python. I'll appreciate your advices about this Thanks iu2 From noname9968 at gmail.com Wed Mar 19 13:37:11 2008 From: noname9968 at gmail.com (Alex9968) Date: Wed, 19 Mar 2008 20:37:11 +0300 Subject: Tkinter.Text widget - how to get text cursor position? Message-ID: <47E14F47.6000202@gmail.com> Is it possible to get position (in numbers) of the insertion cursor? As I understood, Text widget uses mark named INSERT to store it, which is available globally by just referencing INSERT, but how could I get actual coordinate numbers of the mark? I need this because I want not just to insert string at, but to examine text before and after the insertion cursor. I can probably use .get() to extract the halves of text before and after cursor, but it'd be better just to know the position. Thanks From asmodai at in-nomine.org Sat Mar 29 13:33:38 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sat, 29 Mar 2008 18:33:38 +0100 Subject: Why prefer != over <> for Python 3.0? In-Reply-To: <7x3aq9212z.fsf@ruckus.brouhaha.com> References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> <7x3aq9212z.fsf@ruckus.brouhaha.com> Message-ID: <20080329173338.GY80617@nexus.in-nomine.org> -On [20080329 13:01], Paul Rubin ("http://phr.cx"@NOSPAM.invalid) wrote: >Yes, what I mean is that some languages (e.g. Ada, Haskell) use /= for >nonequality. /= is understandable given how it looks like a digraph for ? (U+2260) and I am guessing that was the intent. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Cum angelis et pueris, fideles inveniamur. Quis est iste Rex gloriae..? From mr.names at gmail.com Fri Mar 14 07:53:06 2008 From: mr.names at gmail.com (mr.names@gmaIL.COM) Date: Fri, 14 Mar 2008 04:53:06 -0700 (PDT) Subject: The best computer solutions Message-ID: <2f53622c-9c7b-4328-adac-b7b2a5b1eb30@d45g2000hsc.googlegroups.com> http://r8p.org/upload/213.html From castironpi at gmail.com Wed Mar 12 02:17:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:17:45 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> <72f2856c-eeca-44f2-849d-912889d26a79@d21g2000prf.googlegroups.com> <13tescq3n0j6qda@corp.supernews.com> Message-ID: <43924119-4e4d-42f1-aaf1-90ae743d8cf9@u69g2000hse.googlegroups.com> > > Are there any that aren't persistent? > > ? ? ? ? SQLite -- when opening a "memory" database rather than giving it a > physical file. {I'm a tad too busy to look up the format of the memory > parameter, but it shouldn't be too difficult to find it} What? If I wanted to code string literals, I'd use exec. Where's the real one? From see.signature at no.spam Wed Mar 26 11:54:21 2008 From: see.signature at no.spam (Eric Brunel) Date: Wed, 26 Mar 2008 16:54:21 +0100 Subject: Tkinter menus from keyboard References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: On Wed, 26 Mar 2008 13:45:29 +0100, Guilherme Polo wrote: > 2008/3/26, MartinRinehart at gmail.com : >> Tkinter defaults to, for example, Alt+f = File (if File is your first >> menu name starting with "f"). >> >> I'd like to assign my own letters and have them underscored, per the >> universal standard. Can this be done? >> > > Set the underline option to the index of the desired letter BTW, this "standard" is not universal at all: e.g, there is no such convention on Macs. Not (only...) nitpicking: if your application has to run on a Mac, it may look weird if you use this option... But I never tested how it was handled on Macs. My $0.02... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From israelu at elbit.co.il Mon Mar 17 20:05:04 2008 From: israelu at elbit.co.il (iu2) Date: Mon, 17 Mar 2008 17:05:04 -0700 (PDT) Subject: Tkinter right-to-left windows Message-ID: Hi, I use tix NoteBook, and I need the tabs arranged right to left. Is it possible? Thanks From stefan_ml at behnel.de Tue Mar 11 12:01:52 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 Mar 2008 17:01:52 +0100 Subject: wxPython/wxWidgets ok for production use ? In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: <47D6ACF0.5060300@behnel.de> Sion Arrowsmith wrote: > And before you blame wx* for crashes: what platform was this on? > Because my experience was that wx on GTK was significantly more prone > to glitches than on Windows (through to wxglade being unusably crashy) > -- if the underlying toolkit has problems, that's going to be > reflected in wx. :) Interesting. This was actually on GTK. Although I would still blame at least the wxWidgets-GTK bindings here. I never had any problems with GTK in my life. Stefan From nagle at animats.com Sun Mar 23 02:15:00 2008 From: nagle at animats.com (John Nagle) Date: Sat, 22 Mar 2008 23:15:00 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <7xlk4anjcn.fsf@ruckus.brouhaha.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> Message-ID: <47e5f31f$0$36325$742ec2ed@news.sonic.net> Paul Rubin wrote: > Jeff Schwab writes: >> I've been learning a fair amount about functional programming >> recently, mostly because compile-time C++ turns out to be a pure >> functional programming language. Where should I go for a solid >> grounding in lambda-calculus? > > For PL theory in general, try this: > > http://www.cs.cmu.edu/~rwh/plbook/book.pdf What a mess. That's some professor inventing his very own variation on predicate calculus and writing a book using his own notation and terminology. There's no sign of footnotes or references to prior work. The notation doesn't seem to do anything not previously possible; it's just different. Back when I was doing program verification work, we used to refer to stuff like that as the "logic of the month club". John Nagle From http Tue Mar 18 07:00:19 2008 From: http (Paul Rubin) Date: 18 Mar 2008 04:00:19 -0700 Subject: finding items that occur more than once in a list References: Message-ID: <7xwso0z48s.fsf@ruckus.brouhaha.com> Simon Forman writes: > Is there a more efficient way to do this? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263 From andre.roberge at gmail.com Sat Mar 22 13:02:01 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 22 Mar 2008 10:02:01 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <9ca7e0a0-d686-4c69-bac0-5f4a1447aac3@c19g2000prf.googlegroups.com> On Mar 22, 1:40 pm, jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. Yes. You'll probably get 100 positive answers! Check out the edu-sig mailing list for discussions on the topic. And you may want to check out rur-ple.sourceforge.net, where "ple" stands for "Python Learning Environment". Andr? From rajb at rice.edu Mon Mar 31 16:57:05 2008 From: rajb at rice.edu (Raj Bandyopadhyay) Date: Mon, 31 Mar 2008 15:57:05 -0500 Subject: Question about overloading of binary operators In-Reply-To: References: Message-ID: <47F15021.6000603@rice.edu> Hi Here's a simple class example I've defined ############################# class myInt(int): def __add__(self,other): return 0 print 5 + myInt(4) #prints 9 print myInt(4) + 5 #prints 0 ############################# The Python binary operation function (binary_op1() in Objects/abstract.c) states the rules for binary operations as follows: v w Action ------------------------------------------------------------------- new new w.op(v,w)[*], v.op(v,w), w.op(v,w) new old v.op(v,w), coerce(v,w), v.op(v,w) old new w.op(v,w), coerce(v,w), v.op(v,w) old old coerce(v,w), v.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type It seems that my example should fall in case 1, and in both cases, the __add__ function of the subclass should be used, returning 0, regardless of operand order. However, in one case the subclass's function is used and not in the other case. What am I missing here? Thanks Raj From MadComputerGuy at gmail.com Mon Mar 10 19:32:26 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Mon, 10 Mar 2008 16:32:26 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> Message-ID: <87a50033-10ea-4016-af14-66b3bc62865f@e39g2000hsf.googlegroups.com> On Mar 10, 12:10 pm, Mensanator wrote: > On Mar 10, 12:48 am, Gabriel Genellina wrote: > > > On 10 mar, 02:08, Nathan Pinno wrote: > > > > How do I factor a number? > > If factoring is actually what you want, the sympy module can do it. > > >>> n = 85085**3 > >>> print n > 615969217989125 > >>> import sympy > >>> f = sympy.factorint(n) > >>> f > > [(5, 3), (7, 3), (11, 3), (13, 3), (17, 3)]>>> ff = [[i[0]]*i[1] for i in f] > >>> ff > > [[5, 5, 5], [7, 7, 7], [11, 11, 11], [13, 13, 13], [17, 17, 17]]>>> fff = sympy.flatten(ff) > >>> fff > > [5, 5, 5, 7, 7, 7, 11, 11, 11, 13, 13, 13, 17, 17, 17] > > Provided that your needs are modest. It claims to be > able to handle 10 digit factors, but it certainly can't > handle numbers of this magnitude: > > 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 > > As it takes a couple hours of run-time only to crash > with an out of memory error. > > If you need to handle something like that, you may want to > get factor.exe which is part of the MIRACL library. The library > is in C and doesn't have a Python interface, but you can run > the .exe from Python and capture the output. > > Keep in mind two things: factor.exe doesn't have consistent > output making it more difficult to interpret the captured > output. I re-compiled my copy of factor.exe to provide > consistent output. > > The other thing is that factor.exe sometimes gets confused > claiming a number is composite that factor.exe is fully > capable of factoring. Luckily this can be easily fixed in > the Python program that calls it. > > In the following example, if factor!.exe (my re-compiled > version) returns any composites, I simply feed them back > into the program until all are factored or determinened to > be truly intractable. > > Note the times. If you have serious factoring needs, the > MIRACL solution is better than sympy. > > ## ======================================== > ## Phase 1 > ## ['COMPOSITE_FACTOR', > '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] > ## > ## ['PRIME_FACTOR', '37'] > ## ['PRIME_FACTOR', '43'] > ## ['PRIME_FACTOR', '167'] > ## ['COMPOSITE_FACTOR', '507787751'] > ## ['PRIME_FACTOR', '69847'] > ## ['PRIME_FACTOR', '30697'] > ## ['PRIME_FACTOR', '89017'] > ## ['PRIME_FACTOR', '3478697'] > ## ['PRIME_FACTOR', '434593'] > ## ['PRIME_FACTOR', '49998841'] > ## ['PRIME_FACTOR', '161610704597143'] > ## ['PRIME_FACTOR', '14064370273'] > ## ['COMPOSITE_FACTOR', '963039394703598565337297'] > ## ['PRIME_FACTOR', '11927295803'] > ## > ## 0.860000133514 seconds > ## ======================================== > ## Phase 2 > ## ['COMPOSITE_FACTOR', '507787751'] > ## > ## ['PRIME_FACTOR', '29819'] > ## ['PRIME_FACTOR', '17029'] > ## > ## 0.0780000686646 seconds > ## ======================================== > ## Phase 3 > ## ['COMPOSITE_FACTOR', '963039394703598565337297'] > ## > ## ['PRIME_FACTOR', '518069464441'] > ## ['PRIME_FACTOR', '1858900129817'] > ## > ## 0.0469999313354 seconds > ## ======================================== > ## > ## Factoring complete > ## > ## PRIME_FACTOR 37 > ## PRIME_FACTOR 43 > ## PRIME_FACTOR 167 > ## PRIME_FACTOR 17029 > ## PRIME_FACTOR 29819 > ## PRIME_FACTOR 30697 > ## PRIME_FACTOR 69847 > ## PRIME_FACTOR 89017 > ## PRIME_FACTOR 434593 > ## PRIME_FACTOR 3478697 > ## PRIME_FACTOR 49998841 > ## PRIME_FACTOR 11927295803 > ## PRIME_FACTOR 14064370273 > ## PRIME_FACTOR 518069464441 > ## PRIME_FACTOR 1858900129817 > ## PRIME_FACTOR 161610704597143 > ## > ## ======================================== > > > I mean how do I translate x! into proper > > > Python code, so that it will always do the correct math? > > > Do you want to compute x! (factorial of x)? That is, you want a > > program that given a 4, returns 24? > > Think how would you compute it by hand and try to write the same thing > > using Python instructions. > > > If you come with a program and have a specific problem someone here > > will be able to help you, but don't expect your homework to be done > > for free... > > > -- > > Gabriel Genellina Thanks on the factoring bit, but I did mean factorial, not factoring. How do I code that correctly, so that I can figure the following equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax error and highlight the !. So it would be nice to find a way to solve such a problem. Thanks, Nathan P. From castironpi at gmail.com Sun Mar 9 19:51:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 16:51:40 -0700 (PDT) Subject: Returning values from function to Python shell/IPython References: Message-ID: <91fbb488-4ada-4fea-864b-c5c33c5b4386@e39g2000hsf.googlegroups.com> > > ?> well after all it's a function so the only ways you can get things out > > ?> of it are: > > ?> - return a dict with all the objects > > ?> - use global (very messy) > > ?> - use a decorator to do either of the above. > > > ?Messy, all of those... :(. > > > ?> on the other hand have you consider using a proper test package? > > ?> instead of inspecting the objects manually from the shell you could > > ?> make it all automatic. with assert statements. you could use the std. > > ?> python testing moduleshttp://docs.python.org/lib/development.htmlor > > ?> something less verbosed like nose > > > ?Usually, I'm using standard Python testing modules, but sometimes that is > > ?just an overkill. Sometimes I like to do 'exploratory programming', > > ?especially in the early phases of development - create a bunch of objects I > > ?want to play with and do that from IPython. Only way I found out to > > ?somewhat automate this procedure is to have a function that creates all of > > ?the test objects, and then raises an exception at the end. IPython starts > > ?ipdb, so I can work with the objects the function created (without copying > > ?them back to the shell). But this somehow looks too hack-ish for me, so I > > ?was wondering if there was an alternative... > > ohhh if that is the case then what you are doing seems to be the > optimal. Just have module lvl code ran the testing in fact I don't > even put those into the if __name__, the reason is that this is just > temp testing that will later become real unit testing, and will never > hit a production app. it gives you the most flexibility. While you're at it, can you call up prior source, and edit it? BASIC had line numbers: 10 def f( a ): 20 return a+ 1 >>> 15 print( a ) 10 def f( a ): 15 print( a ) 20 return a+ 1 >>> 15 print( a ) 10 def f( a ): 15 print( a ) 20 return a+ 1 '''Interactives could some day have this too:''' >>> edit f Object f opened in editor >>> close Object f written back. Elapsed time 5 minutes. >>> From steve at holdenweb.com Sun Mar 2 09:32:18 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 09:32:18 -0500 Subject: tcp In-Reply-To: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: 7stud wrote: > On Mar 2, 6:09 am, Gif wrote: >> i have this small script which after some router configurations works. >> >> ########################################################## >> >> #! /usr/bin/python >> import socket >> >> HOST = '' >> PORT = 1515 >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> s.bind((HOST, PORT)) >> s.listen(1) >> conn, addr = s.accept() >> conn.send('HTTP/1.1 200 OK\r\n') >> conn.send('Content-Type: text/html\r\n') >> conn.send('Server: test/1.0\r\n\r\n') >> conn.send('test') >> s.close() >> >> ########################################################## >> >> as you see it listens to 1515 until a connection is established and >> then it accepts it... >> the problem is that when it accepts the connection it sends those >> strings and exits, but then it exits the program. i want it to listen >> to 1515 then accept a connection, send.. and then listen to the port >> again and again until new connections are found. >> >> i've been struggling with try..except,while and all kinds of loops but >> always new erros pop up, or it overflows. > > while True: > conn, addr = s.accept() > ... And now you get to start asking all the interesting questions that come up, like "How do I get my server to respond to multiple requests in parallel?" It's a long road, but it's fun. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From zerty.david at gmail.com Thu Mar 27 18:19:49 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 27 Mar 2008 19:19:49 -0300 Subject: Problems wit List Object Message-ID: <5dc598e30803271519k39440eccj3b9db110f9097b98@mail.gmail.com> Hello all, I have a Class1 that there has a list, and a function that returns this list, In another class I got an instance of this first class, and when I make: obj1 = Class1() list = obj1.getList() I got this exception: traceback (most recent call last): File "xxx", line 184, in onAddErro list = self.errorMgr.getList() TypeError: 'list' object is not callable How can I solve it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu Mar 13 21:15:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 18:15:19 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: On Mar 13, 7:45?pm, castiro... at gmail.com wrote: > On Mar 13, 7:18?pm, Mel wrote: > > > > > > > Diez B. Roggisch wrote: > > >> My understanding is that foo.bar does *not* create a new object. > > > > Your understanding is not correct. > > > >> ?All it > > >> does is return the value of the bar attribute of object foo. ?What new > > >> object is being created? > > > > A bound method. This happens through the descriptor-protocol. Please see > > > this example: > > > > class Foo(object): > > > ? ? def bar(self): > > > ? ? ? ? pass > > > > f = Foo() > > > a = Foo.bar > > > b = f.bar > > > c = f.bar > > > > print a, b, c > > > print id(b), id(c) > > > (What Diez said.) ?From what I've seen, f.bar creates a bound method > > object by taking the unbound method Foo.bar and binding its first > > parameter with f. ?This is a run-time operation because it's easy to > > re-assign some other function to the name Foo.bar, and if you do, the > > behaviour of f.bar() will change accordingly. > > > You can get some very useful effects from these kinds of games. ?You > > can make f into a file-like object, for example, with > > > import sys > > f.write = sys.stdout.write > > > Here, f.write *is* a straight attribute of f, although it's a built-in > > method of the file class. ?It's still bound, in a way, to sys.stdout. > > ? I'm assuming that a different example could create an attribute of f > > that's a bound method of some other object entirely. ?I've verified > > that f.write('howdy') prints 'howdy' on standard output. > > Accordingly, > > f.write= types.MethodType( sys.stdout.__class__.write, sys.stdout ). > > It depends on what you want the implicit first (self) to be-- f or > sys.stdout. > > But how come this works? > > >>> import types > >>> import sys > > >>> class C: > > ... ? ? write= sys.stdout.write > ... ? ? def g( self ): > ... ? ? ? ? ? ? self.write( 'was in \'g\'\n' ) > ...>>> c= C() > >>> c.g() > > was in 'g' > > Shouldn't 'write' be getting extra parameters? ?Sounds fishy, not to > mix metaphors. Ah. Because this doesn't. >>> class C: ... write= sys.stdout.__class__.write #<-- ... def g( self ): ... self.write( 'was in \'g\'\n' ) ... >>> c= C() >>> c.g() Traceback (most recent call last): File "", line 1, in File "", line 4, in g File "c:\programs\python\lib\io.py", line 1236, in write if self.closed: AttributeError: 'C' object has no attribute 'closed' >>> That is, because sys.stdout.write is -not- a user-defined function. What it is, is a bound member function, and only the former is converted/wrapped/bound*, as it is in the subsequent example. */ whatever. From aahz at pythoncraft.com Sat Mar 29 21:47:58 2008 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2008 18:47:58 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: In article <5805ee5f-970f-4b16-a5c5-90ebe0748feb at y21g2000hsf.googlegroups.com>, wrote: > >I don't know if this is the right place to discuss the death of <> in >Python 3.0, or if there have been any meaningful discussions posted >before (hard to search google with '<>' keyword), but why would anyone >prefer the comparison operator != over <>??? Are you asking why Python 3.0 gets rid of one of them or are you asking why != was chosen over <>? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 07:05:11 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 12:05:11 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: References: <47EB6480.2080402@wtf.websiteburo.oops.com> Message-ID: <47eb7f60$0$5151$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > Bruno Desthuilliers wrote: >> Gabriel Rossetti a ?crit : (snip) >>> registerServiceAtomic = partial(__registerService, True) >>> registerServiceNonAtomic = partial(__registerService, False) >>> >>> I should pass self when applying partial, but then I can't do that >>> since self is not available there. Does anyone have any ideas? >> >> registerServiceAtomic = partial(__registerService, atomic=True) >> registerServiceNonAtomic = partial(__registerService, atomic=False) >> >> Caveat: you'll have to either invert the order of the atomic and >> service params, or call the partials with named arg for service. >> >> > Ok, thanks, I didn't know you could do that, I though partial was always > left to right It's left to right for positional arguments. Using named arguments, you can pass them in whatever order. > (I had read that about curry) Which 'curry' ?-) From rhh2109 at columbia.edu Sun Mar 2 22:29:07 2008 From: rhh2109 at columbia.edu (Roy H. Han) Date: Sun, 2 Mar 2008 22:29:07 -0500 Subject: Where's GUI for Python? In-Reply-To: <72616FCD61C649DF8E1B1BEAD493EC0F@Hippo> References: <62tvhmF256jk7U1@mid.individual.net> <47C9D33E.9040407@tim.thechases.com> <6a5569ec0803011429q4444ec25o7c235ae80590dff8@mail.gmail.com> <72616FCD61C649DF8E1B1BEAD493EC0F@Hippo> Message-ID: <6a5569ec0803021929u72b49d27v5d32e99f5c9f2857@mail.gmail.com> Hi Konrad, I remember taking a long time in deciding which GUI framework to use last year and I picked wxGlade/wxPython because it seemed mature, easy to use and easy to understand. In the beginning I wasted a lot of time coding the GUI manually but wxGlade lets me use the mouse to arrange the components so that I can focus on writing the event handling code. I mostly don't touch the code that wxGlade auto-generates and I work my code around it. http://wxglade.sourceforge.net/demo/ Sorry I responded to your personal email by mistake. I pressed Reply All in gmail. I don't know who wrote wxGlade or wxPython but both have been real timesavers to me. Roy On Sun, Mar 2, 2008 at 3:50 AM, Konrad Viltersten wrote: > > Konrad, I use wxPython with wxGlade. > > I love wxGlade! > > wxGlade http://wxglade.sourceforge.net/ > > You need to look at this documentation to > > code event handling. wxWidgets: > > http://www.wxwidgets.org/manuals/stable/wx_classesbycat.html > > > > You can also try coding the GUI manually, > > but it is much easier to use wxGlade. > > wxPython > > http://wiki.wxpython.org/AnotherTutorial > > May i ask what's the advantage in using > wxGlade instead of the buil-in Tkinter? > > Also - why did you replied to my private > email instead of to news? Is the choice of > GUI an infected matter among the Python > community, by any chance? > > -- > Regards > Konrad Viltersten > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Mar 10 12:36:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Mar 2008 16:36:53 -0000 Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <13taot5khcl933a@corp.supernews.com> On Mon, 10 Mar 2008 07:39:25 -0700, Gary Herron wrote: > If either is a surprise, then understand that the "is" operator should > probably *never* be used with immutable types. Carl Banks has already mentioned testing for None with "is". The standard idiom for using mutable default arguments goes something like this: def foo(arg=None): if arg is None: arg = [] do_something_with(arg) Another standard idiom that requires "is": sentinel = object() # a special value that isn't None ... if something is sentinel: blah blah blah Mutable or immutable, it makes no difference: "is" is for testing identity, == is for testing equality. If you need to test for identity, use "is". If you need to test for equality, use ==. -- Steven From python at rgbaz.eu Sun Mar 16 09:07:36 2008 From: python at rgbaz.eu (Python) Date: Sun, 16 Mar 2008 14:07:36 +0100 Subject: Python and 3D In-Reply-To: <00a99921-a931-49cf-9bd1-4978d805290f@8g2000hsu.googlegroups.com> References: <00a99921-a931-49cf-9bd1-4978d805290f@8g2000hsu.googlegroups.com> Message-ID: <27BD105D-E720-4F97-B210-E329D3FEED5A@rgbaz.eu> On 15 mrt 2008, at 23:06, Mike Driscoll wrote: > On Mar 15, 3:09 pm, Eric von Horst wrote: >> Hi, >> >> I am looking for Python modules that allow you to manipulate 3D >> objects, more specifically Alias Wavefront .OBJ objects. >> Also, a module that would allow you to vizualize these models and >> rotate them etc.. >> >> The goal is not to build a new renderer or something; just a small >> program that I need to do some manipulations in bulk on a set of OBJs >> >> Any help much appreciated >> >> Eric > > I'm not aware of anything. You might look at pyOpenGL or pyglet. They > should be good for 3D modeling at least. > > Mike ...or have a look at Blender's bpython module: http://www.blender.org/education-help/python/ Arno From michael.wieher at gmail.com Tue Mar 11 15:08:55 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Tue, 11 Mar 2008 14:08:55 -0500 Subject: Obtaining the PyObject * of a class In-Reply-To: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com> Message-ID: 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : > > On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > > > "Cooper, Andrew" wrote in message > > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca > ... > > > > | Are there any Python C API experts/SWIG experts out there that can > help > > | me with this issue please. > > > > | I',m currently using SWIG to generate a python interface to a C DLL. > > > > Some people have switched to using ctypes for this, and many other SWIG > > users have stopped reading clp. But I hope someone answers who can. > > > > > Using Pyrex or Cython is likely to be much easier than using SWIG for > this. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Mar 6 15:17:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Mar 2008 21:17:51 +0100 Subject: Ncurses not found - embedded linux In-Reply-To: References: Message-ID: <63b1rjF26p2fkU1@mid.uni-berlin.de> blaine schrieb: > Hello Everyone! > I am hoping that someone out there can help me out with this > problem. We are using a gumstix platform to develop an embedded > system. All that really matters is that it is an ARM processor > running an embedded linux, details to follow. Gumstix has its own > kernel tree that we cross compile for the system. We do have python, > and it has all of the modules that I need except for one. I need > ncurses (module curses). I can't seem to figure out how to get it to > work - and the only documentation I can find is for Windows (because > windows doesn't have ncurses). We have enabled ncurses support in the > kernel menu, and that has not helped. I can't seem to trace down > where we would 'enable' ncurses support? All other modules seem to > work that I've tried (termios, sys, os, etc.) > > Output from python: > [root at gumstix ~]# python > , Feb 20 2008, 11:07:36) > [GCC 4.1.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import curses > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/curses/__init__.py", line 15, in ? > from _curses import * > ImportError: No module named _curses > > [root at gumstix ~]# uname -a > Linux gumstix 2.6.21gum #1 Tue Mar 4 15:31:07 EST 2008 armv5tel > unknown > > [root at gumstix lib]# ls /usr/lib/*curses* > /usr/lib/libcurses.a@ /usr/lib/libncurses.a /usr/lib/ > libncurses.so@ > > [root at gumstix lib-dynload]# ls _* > _bisect.so* _codecs_tw.so* _random.so* > _codecs_cn.so* _csv.so* _socket.so* > _codecs_hk.so* _heapq.so* _testcapi.so* > _codecs_iso2022.so* _hotshot.so* _weakref.so* > _codecs_jp.so* _locale.so* > _codecs_kr.so* _multibytecodec.so* > > I hope this is trivial, and I apologize ahead of time if so. Would > this perhaps be a compilation issue? Something we have to turn on in > the python compile? Usually, you need not only the libraries but also the headers at compilation time. Most probably these were missing. Diez From timr at probo.com Mon Mar 3 01:31:33 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 03 Mar 2008 06:31:33 GMT Subject: SV: Where's GUI for Python? References: <62tvhmF256jk7U1@mid.individual.net> <63038fF23j6foU1@mid.individual.net> Message-ID: <4v5ns3907dqsqgovtuboc3q6qbk93gvf9g@4ax.com> "K Viltersten" wrote: > >As long as we're on the subject, i also wonder >if there's a general concensus on which >technology is recommended in the different >types of projects that are developed. (E.g. >"use A for small/fast fixes, use B for stuff >you'll need to maintain later on".) Are you talking specifically about GUI toolkits? I seriously doubt that anyone routinely uses more than one GUI with Python (although I'm sure there are exceptions). Each of them has a pretty big learning curve to climb, and once you have climbed it, all of the GUI kits will solve the same problems. (Caution: the following contains gross generalities.) If you have ever done GUI programming in Windows using the Win32 API, then wxPython will seem more natural than Tkinter or Qt (although I should point out that all of them work equally well on Windows and Linux). If you have ever done GUI programming in X, or if you have done script with with Tcl/Tk, then it is likely that Tkinter will seem more natural than wxPython. Perhaps the best option is to take a look at some samples, and see what looks more natural to you. wxPython, for instance, has a wonderful set of demos that demonstrate almost every feature of the toolkit. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From stargaming at gmail.com Mon Mar 17 12:42:20 2008 From: stargaming at gmail.com (Stargaming) Date: 17 Mar 2008 16:42:20 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> Message-ID: <47de9f6c$0$2657$9b622d9e@news.freenet.de> On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: > For the answer I actually want each asterisk substitutes for exactly one > character. Played around a bit and found that one: Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1 >>> b = 1//1 >>> if a is b: print('yes!') ... >>> b 1 >>> type(b) From dave_mikesell at fastmail.fm Thu Mar 20 21:23:51 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Thu, 20 Mar 2008 18:23:51 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: On Mar 20, 2:39 am, "Daniel Fetchinson" wrote: > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: I really like Python since I started using it a couple years ago, but this is a huge turnoff and the kind of thing that keeps me using C++. Stability is important. And I don't have any real code base. Can't imagine those that have made a big investment in Python being all too happy about the rug being pulled out from under them. From p at ulmcnett.com Fri Mar 14 13:42:17 2008 From: p at ulmcnett.com (=?UTF-8?B?UGF1bCBNwqJOZXR0?=) Date: Fri, 14 Mar 2008 10:42:17 -0700 Subject: Thousand Seperator In-Reply-To: References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <47DAB8F9.7020700@ulmcnett.com> Eddie Corns wrote: > ewanfisher at gmail.com writes: > >> I'm trying to find some code that will turn: > >> 100 -> 100 >> 1000 -> 1,000 >> 1000000 -> 1,000,000 >> -1000 -> -1,000 > >> I know that can be done using a regular expression. In Perl I would do >> something like: > >> sub thousand { >> $number = reverse $_[0]; >> $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; >> return scalar reverse $number; >> } > >> But I cannot find how to do this in Python. > > Look at the locale module. If you're producing the numbers yourself then they > get printed in that format otherwise you can convert them to numbers first. Specifically: import locale locale.setlocale(locale.LC_ALL, '') for trial in (100, 1000, 1000000, -1000): print trial, locale.format("%0f", trial, True) If that results in no comma separators, then you may need to set the locale specifically, such as: >>> locale.setlocale(locale.LC_ALL, 'en_us') 'en_us' >>> for trial in (100, 1000, 100000, -1000): ... print trial, locale.format("%.0f", trial, True) ... 100 100 1000 1,000 100000 100,000 -1000 -1,000 Paul From john.deas at gmail.com Sat Mar 8 07:11:36 2008 From: john.deas at gmail.com (John Deas) Date: Sat, 8 Mar 2008 04:11:36 -0800 (PST) Subject: parralel downloads Message-ID: Hi, I would like to write a python script that will download a list of files (mainly mp3s) from Internet. For this, I thought to use urllib, with urlopen("myUrl").read() and then writing the resulting string to a file my problem is that I would like to download several files at the time. As I have not much experience in programming, could you point me the easier ways to do this in python ? Thanks, JD From malaclypse2 at gmail.com Fri Mar 7 15:55:10 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 7 Mar 2008 15:55:10 -0500 Subject: I cannot evaluate this statement... In-Reply-To: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <16651e80803071255p67ad2101uc3ef93cf0e22c742@mail.gmail.com> On Fri, Mar 7, 2008 at 3:38 PM, waltbrad wrote: > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. > But, again, on linux pyfile evaluates to python.exe This seems to work as expected on my Ubuntu box. Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, sys >>> sys.platform 'linux2' >>> pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' >>> pyfile 'python' >>> What do you get for sys.platform when you run this code under linux? -- Jerry From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 19:32:28 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 31 Mar 2008 01:32:28 +0200 Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <65am8cF2fecpvU1@mid.individual.net> iu2 wrote: > Due to Competitors... I don't want to expost the language I use A serious competitor that wants to find out _will_ find out, no matter what you try. Regards, Bj?rn -- BOFH excuse #341: HTTPD Error 666 : BOFH was here From tdelaney at avaya.com Wed Mar 26 16:42:28 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 27 Mar 2008 04:42:28 +0800 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <13ubn5ue821ak7e@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > >> Yes. And because Python is a "scripting language" > > > Python is a programming language. It can be used for scripting, but > that's not all it can do. Describing it as a "scripting language" is > like describing a fully-equipped professional kitchen as "a left-over > warming room". I'm putting words in sturlamolden's mouth here, but I think he was implying that Python has all the advantages of a "scripting language", hence has a much gentler introduction than many fully-fledged programming languages (and indeed, many scripting languages). Cheers, Tim Delaney From kyosohma at gmail.com Thu Mar 6 16:51:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Mar 2008 13:51:59 -0800 (PST) Subject: Python on the renderfarm References: Message-ID: On Mar 6, 3:35 pm, "Terry Reedy" wrote: > It is fairly well know that cinematic digital effects are most often > rendered on *nix machines with efficient numeric code.http://www.linuxjournal.com/article/9951 > > But Python sometimes has a role too: from the middile of the above link > > ''' > Tippett Studio: Linux Python Pipeline > JET is a proprietary Python-based system comprising software tools and > scripts used to implement a visual effects and animation pipeline. "A > visual effects and animation pipeline is an assembly line of software used > to organize, automate and facilitate the creation of computer-generated > imagery", says Darling. "The JET tool is highly customizable, featuring > XML-based user-interface templates that can be modified to suit specific > types of artists or production needs. JET uses modular template chunks to > perform each of the tasks in the pipeline, such as rendering or > compositing. The templates are implemented as Python objects and are > centrally located. JET is not only implemented entirely in Python, but it's > also used to generate Python scripts automatically. These custom scripts > form unique pipelines for each computer graphics job to run on the > renderfarm." > > ''' That's neat. Phil Tippett has been one of my favorite Special Effects people and now he's using my favorite programming language too. Hopefully Python will make Tippett more productive than ILM! Mike From deets at nospam.web.de Fri Mar 28 13:16:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Mar 2008 18:16:38 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <87od8yolay.fsf@mulj.homelinux.net> References: <87od8yolay.fsf@mulj.homelinux.net> Message-ID: <654ng1F2cvh8aU1@mid.uni-berlin.de> > systems. (In theory, file input/output should also be available as > asynchronous code, but async IO is low-level and not available in > Python.) While threads shouldn't be considered a replacement for I suggest you tell that the twisted-guys. And the ones from the built-in asyncore-module. They will be surprised to hear that their years worth of working code will evaporate in a rosa cloud. Diez From stefan_ml at behnel.de Thu Mar 6 05:58:31 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 06 Mar 2008 11:58:31 +0100 Subject: generateDS problem: __init__ of base class is not called (processing linked xsd files) In-Reply-To: References: Message-ID: <47CFCE57.9000900@behnel.de> Vladimir Kropylev wrote: > Is it possible to have __init__ of superclass called when superclass > and subclass are defined in different XSD files? > There's no problem when super and subclass are defined within single XSD file. > > In another words, can generateDS correctly process schema, described > in a set of linked xsd files? The XML Schema support of generateDS is not complete. Last time I checked, there were quite a number of things that were not supported. Stefan From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:53:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:53:23 -0300 Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: En Thu, 27 Mar 2008 17:37:33 -0300, Aaron Watters escribi?: >> "this";"is";"a";"test" >> >> Resulting in an output of: >> >> ['this', 'is', 'a', 'test'] >> >> However, if I modify the csv to: >> >> "t"h"is";"is";"a";"test" >> >> The output changes to: >> >> ['th"is"', 'is', 'a', 'test'] > > I'd be tempted to say that this is a bug, > except that I think the definition of "csv" is > informal, so the "bug/feature" distinction > cannot be exactly defined, unless I'm mistaken. AFAIK, the csv module tries to mimic Excel behavior as close as possible. It has some test cases that look horrible, but that's what Excel does... I'd try actually using Excel to see what happens. Perhaps the behavior could be more configurable, like the codecs are. -- Gabriel Genellina From castironpi at gmail.com Sun Mar 9 17:44:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:44:50 -0700 (PDT) Subject: Logically/Selectively Sub Class? References: Message-ID: <14923672-e7c9-40b2-a266-fd6c0b36e392@2g2000hsn.googlegroups.com> On Mar 9, 4:28?pm, xkenneth wrote: > Might be a silly question, but is it possible to selectively subclass, > IE subclass is a supporting module is present and not otherwise. > > Regards, > Kenneth Miller if mod is present: class Waypoint( Mine, Yours ): pass else: class Waypoint( Mine ): pass class NewClass( Waypoint ). In 3.0, you can do if mod is present: bases= Mine, Yours else: bases= Mine, class NewClass( *bases ). From ccomb at free.fr Sun Mar 23 21:31:53 2008 From: ccomb at free.fr (Christophe Combelles) Date: Mon, 24 Mar 2008 02:31:53 +0100 Subject: PyCon FR - =?UTF-8?B?Sm91cm7DqWVzIFB5dGhvbg==?= Message-ID: <47e70487$0$15874$426a34cc@news.free.fr> PyCon FR will take place in Paris, France, 17-18 May 2008. The French Python Association (AFPY) is organizing this event called "Journ?es Python" for the second time. We expect most talks to be in french, but any proposal in english is also greatly welcome! You may submit your idea of talks and presentations now, either here if you speak french: http://fr.pycon.org/actualites/appel-a-propositions/ , or here if you don't : pycon -at- afpy.org Topics: We're expecting talks about anything related to the Python programming language, including: * the language and its libraries * the web technologies * Python in scientific computing * game programming * development environnement setup * agile programmnig and tests The expected audience will span on any level, from the beginner to the expert. Thus, your talk may fit even to beginners and will be welcome. Other formats: As well as regular talks, we will host tutorials about Python programming for beginners, and we may include 15-minutes lightning talks on any topic you want to talk about (e.g.: a project you're working on). You may submit debate topics for open discussions too. Important dates: * March, 7th : Call for papers * March, 30th : Paper submissions are closed * April 4th : Final schedule publication How to get involved? If you want to attend as a simple visitor, please register on this page to help us count the expected audience: * http://fr.pycon.org/inscription To submit a talk, tutorial, etc., please register with the link above, and fill the following form: * http://fr.pycon.org/contact/proposition-de-presentation For any information about the event, go to: * http://fr.pycon.org get in touch with the organization team via: pycon -at- afpy.org See you soon! --'AFPy Team. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 10 04:59:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 10 Mar 2008 09:59:37 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> Message-ID: <47d4f850$0$21765$426a74cc@news.free.fr> Guillermo a ?crit : > Mamma mia! My head just exploded. I've seen the light. > > So you only need to ?want? to have a protocol? That's amazing... Far > beyond the claim that Python is easy. You define protocols in writing > basically! Even my grandma could have her own Python protocol. > > Okay, so I think I know where's the catch now -- you must rely on the > fact that the protocol is implemented, Indeed. But even with static declarative typing ? la Java, you must rely on the fact that the protocol is *correctly* implemented (what about having file.close sending mails to all your contacts and then rebooting the computer ?-). IOW, at some point, you have to trust the coder anyway. > there's no way to enforce it if > you're expecting a parrot-like object. Yes there is: > You'd try to call the speak() > method That's it. > and deal with the error if there's no such method? Either catch the AttributeError and raise a TypeError or ValueError (or some more specific one) instead, or just let the AttributeError propagate - whichever makes more sens given the context. I'd say the default would be to catch the AttributeError and raise a TypeError instead (that's at least what len() does when passed an unsized object). From kkadrese at gmail.com Tue Mar 18 12:17:32 2008 From: kkadrese at gmail.com (kkadrese at gmail.com) Date: Tue, 18 Mar 2008 09:17:32 -0700 (PDT) Subject: lock access to serial port Message-ID: hello group, how to get ttyS0 serial port for exclusive access? I have a python script that uses this device with AT commands. I need that two instances can call simultaneosuly this python script but only one of them gets the device. I tried fcntl.flock, it was just ignored, put writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not know what are appropriate arguments), googled half a day for various phrases, error messages etc....without success. please help, Andra From bborcic at gmail.com Mon Mar 10 13:51:18 2008 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 10 Mar 2008 18:51:18 +0100 Subject: __iter__ yield In-Reply-To: <910581f3-6587-4f6a-91ba-0049d583c1d6@y77g2000hsy.googlegroups.com> References: <27d24b75-f1b5-4996-b54a-15ab2ba16593@59g2000hsb.googlegroups.com> <910581f3-6587-4f6a-91ba-0049d583c1d6@y77g2000hsy.googlegroups.com> Message-ID: Paul Hankin wrote: > On Mar 10, 3:12 am, George Sakkis wrote: >> On Mar 9, 7:37 pm, Paul Hankin wrote: >> >> >> >>> On Mar 9, 8:58 pm, duccio wrote: >>>> Someone knows if it's possible to make this __iter__ function with just >>>> one 'yield' intead of two? >>>> ... >>>> def __iter__(self): >>>> yield self #1 >>>> for n in self.childs: >>>> for nn in n.__iter__(): >>>> yield nn #2 >>> Only one yield and shorter (but not really any simpler): >>> from itertools import chain >>> class Node: >>> ... >>> def __iter__(self): >>> for x in chain([self], *self.childs): >>> yield x >> Actually this doesn't need a yield at all: >> >> class Node: >> ... >> def __iter__(self): >> return chain([self], *self.childs) > > The two have slightly different behaviours: without the yield, iter is > called immediately on every node in the tree as the iterators are > built. With yield, iterators are built lazily, giving better > behaviour. generator expressions allow to save on the 'yield' while keeping the lazy behavior, with either : def __iter__(self): return chain([self],(y for x in self.childs for y in x)) or def __iter__(self): return (y for x in chain([[self]],self.childs) for y in x) BB From Robert.Bossy at jouy.inra.fr Wed Mar 19 13:45:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 19 Mar 2008 18:45:57 +0100 Subject: xml sax In-Reply-To: References: Message-ID: <47E15155.4050008@jouy.inra.fr> Timothy Wu wrote: > Hi, > > I am using xml.sax.handler.ContentHandler to parse some simple xml. > > I want to detect be able to parse the content of this tag embedded in > the XML. > 174 > > > Is the proper way of doing so involving finding the "Id" tag > from startElement(), setting flag when seeing one, and in characters(), > when seeing that flag set, save the content? > > What if multiple tags of the same name are nested at different levels > > and I want to differentiate them? I would be setting a flag for each level. > I can imagine things get pretty messy when flags are all around. > Hi, You could have a list of all opened elements from the root to the innermost. To keep such a list, you append the name of the element to this stack at the end of startElement() and pop it off at the end of endElement(). In this way you have acces to the path of the current parser position. In order to differentiate between character data in Id and in Id/Id, you just have to iterate at the last elements of the list. Cheers, RB From http Sun Mar 23 13:45:38 2008 From: http (Paul Rubin) Date: 23 Mar 2008 10:45:38 -0700 Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <7xr6e11ghp.fsf@ruckus.brouhaha.com> John Nagle writes: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : I like to think len(dict) is constant time but I haven't checked the code. Same for bool(dict) (which is what you get when you run "if dict: ..."). From version5 at gmail.com Sun Mar 23 17:26:32 2008 From: version5 at gmail.com (nnp) Date: Sun, 23 Mar 2008 21:26:32 +0000 Subject: Issue with select.select() and missing data Message-ID: <28749c0e0803231426o7d9bec23j2b168e3c43c427be@mail.gmail.com> Hi guys, I have an issue when using select.select(). I have an application that creates sockets then sends data on them. These sockets are then passed off to a listener which uses select.select() to detect any responses. For some reason every socket can only receive one response before my computer begins to issue ICMP port unreachable messages for that port. The code doing the listening is below. No sockets are returned in the broken list. Can anyone spot anything stupid I'm doing in the following code or think of any reason for this issue? def __listen(self): while self.listening and len(self.notify_q_list) != 0: self.lock.acquire() r_read, r_write, broken = select(self.socket_list, [], [], .1) for sock in r_read: data, addr = sock.recvfrom(2**16) for function_tuple in self.notify_q_list: function_tuple[0].put((True, data, 1, addr, 5.0)) self.lock.release() time.sleep(.1) for sock in self.socket_list: sock.close() self.socket_list = [] Thanks, nnp -- http://www.smashthestack.org http://www.unprotectedhex.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From praveena_python at yahoo.com Thu Mar 27 19:28:27 2008 From: praveena_python at yahoo.com (Praveena B) Date: Thu, 27 Mar 2008 16:28:27 -0700 (PDT) Subject: how to capture screenshots of the active window in Python Message-ID: <142053.72537.qm@web44801.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu Mar 6 20:46:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 17:46:43 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: <4e8c4617-af5e-416b-aeba-f58023026340@8g2000hse.googlegroups.com> On Mar 6, 7:10?pm, "Gabriel Genellina" wrote: > En Thu, 06 Mar 2008 22:56:33 -0200, escribi?: > > > On Mar 6, 5:35?am, "Gabriel Genellina" wrote: > > >> p = P() > >> print p.bar.func_name # -> bar > >> p.bar.im_func.anotherattribute = 1 > >> print p.bar.anotherattribute # -> 1 > > >> (the attribute must be set on the *function* itself if you want it to ? > >> be ? > >> somewhat persistent; methods are usually volatile objects) > > > You read my mind. > > You could try to write in a way that reading your mind isn't necesary... > > > I was just getting: > > ? ?assert p.bar is p.bar > > and failing. > > > But if you set them on im_func, instances don't have their own. > > Instances don't have their own methods either. What do you actually want ? > to do? If you need a method with per-instance attributes, that looks like ? > another object to me. Hi, great thanks for giving me your ear this far. First of all, -I have it working-. But the design isn't encapsulated quite right. Here's what I have. 69 lines, so I'll ask to post it first. The gist is: class ISS( SS, metaclass= autonaming ): message= MessageDec() @message def user_act( msg, self, change ): print( 'user act self change', msg, self, change ) IncomingServer... but it originally came from 'clientsideserver.' iss= ISS() class OSS( SS, metaclass= autonaming ): message= MessageDec() user_act= message.out() oss= OSS() oss.message is a abstraction class that writes the method name into a string, then sends it to OSS... outgoingserver or serverside. Now that I'm writing it, and this is important, -to- the -newsgroup-, I realize you could do it with a simple wrapper... include the function name in parameters and call the pickler and send. OSS then looks like this: def something_happens( *ar ): self.user_act( something_about( *ar ) ) So the message.out() instance pickles ( 'user_act', ar ) and sends it. Then iss.incoming receives it, unpickles that string, gets 'user_act' from self, and invokes. The cool part is the declaration of user_act= message.out(), which uses a metaclass to assign its own name, and returns a function which includes the object in its signature. Cool. Yes it's working and a little slack. However-: this is the cool part. I'd like messages to know which instance they came from, and perform the sending & receiving encapsulated on their own--- not to subclass class SS( Sending ): with various behaviors: that is, to assign them as class attributes rather than superclasses. The dreaming comes in here--- I'd like the class to look just like this. Tell me it's possible. And I changed my mind on posting the code, here's the whole thing. Just get SS.send and SS.incoming into MessageDec. har har har har har. Change anything before class OSS:. How does a weak reference lookup in doublebound sound? from functools import wraps import pickle class doublebound: __slots__ = ( '_func', 'assname', '_orig' ) def __init__( self, func ): @wraps( func ) def f( *ar, **kws ): return func( self, *ar, **kws ) self.assname= None self._func, self._orig= f, func def __get__( self, instance, owner ): return self._func.__get__( instance, owner ) class autonaming( type ): def __init__( self, name, bases, namespace ): for k,v in namespace.items(): if isinstance( v, doublebound ): v.assname= k class Sending: def send( *ar, **kws ): raise NotImplemented class MessageDec: def __call__( self, fun ): return doublebound( fun ) def out( self ): return doublebound( self._send ) def _send( self, message, other, *ar, **kws ): return other.send( message.assname, *ar, **kws ) class SS( Sending ): def send( self, methn, *ar, **kws ): transpmessage= methn, ar, kws transpstr= pickle.dumps( transpmessage ) self.far.incoming( transpstr ) def incoming( self, transpstr ): transpmessage= pickle.loads( transpstr ) methn, ar, kws= transpmessage meth= getattr( self, methn ) meth( *ar, **kws ) class OSS( SS, metaclass= autonaming ): message= MessageDec() user_act= message.out() somethingelse= message.out() @message def amessage( msg, self, *change ): print( 'something else', change ) class ISS( SS, metaclass= autonaming ): message= MessageDec() @message def user_act( msg, self, change ): print( 'user act self change', msg, self, change ) @message def somethingelse( msg, self, change= 'and' ): print( 'something else', change ) amessage= message.out() oss= OSS() iss= ISS() oss.far= iss iss.far= oss oss.user_act(2) oss.somethingelse( 'butwhat?') iss.amessage( 2, 3, 4, 5 ) From mauriceling at acm.org Tue Mar 18 05:25:06 2008 From: mauriceling at acm.org (Maurice LING) Date: Tue, 18 Mar 2008 09:25:06 GMT Subject: Multiple Submits in HTML Forms - Cherrypy In-Reply-To: References: <47df6bd4$1@news.unimelb.edu.au> Message-ID: <47df8a6f@news.unimelb.edu.au> Carsten Haese wrote: > On Tue, 2008-03-18 at 07:14 +0000, Maurice LING wrote: >> Hi, >> >> Assuming that I have this code for Cherrypy 3 >> >> class Welcome: >> def index(self): >> return """ >>
>> >> >>
""" >> index.exposed = True >> >> How should I write "btn_handler" so that it will perform different >> actions when different button is pressed? > > Something like this would do it: > > def btn_handler(self, AddBtn=None, EditBtn=None): > if AddBtn: > return "You pressed Add!" > if EditBtn: > return "You pressed Edit!" > > Alternatively you could use a kwargs dictionary and test it for the > presence of the "AddBtn" or "EditBtn" keys. > Thank you Carsten maurice From kyosohma at gmail.com Sat Mar 15 18:06:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 15 Mar 2008 15:06:13 -0700 (PDT) Subject: Python and 3D References: Message-ID: <00a99921-a931-49cf-9bd1-4978d805290f@8g2000hsu.googlegroups.com> On Mar 15, 3:09 pm, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs > > Any help much appreciated > > Eric I'm not aware of anything. You might look at pyOpenGL or pyglet. They should be good for 3D modeling at least. Mike From peter.bulychev at gmail.com Sun Mar 16 05:00:46 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Sun, 16 Mar 2008 12:00:46 +0300 Subject: question about module compiler: line numbers and positions of substring, which are covered by AST nodes Message-ID: Hello. I use standard module Compiler to build ASTs of Python code. Given AST subtree I want to restore coordinates of substring in the input, which is covered by the subtree. Example: Suppose, the input is 'a+(b+c)'. It is parsed to the tree ADD(a, ADD(b,c)) by module Compiler. I want to have a function, which given ADD(b,c) will return the coordinates of the substring '(b+c)'. Module Compiler provides only line numbers for each node. But even this information is incorrect: only the first line of multi-lined statements is stored. What is the easiest way of doing what I want? As I understand, module Compiler is automatically generated by some parser generator. Maybe I can modify it? -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Fri Mar 7 14:55:25 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 7 Mar 2008 11:55:25 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> <51ca8638-65fa-490b-a04a-33ffbefd4aca@s19g2000prg.googlegroups.com> <5d4827e1-8b90-4feb-bfb0-6d956e138b5e@b64g2000hsa.googlegroups.com> Message-ID: <9e8bc711-bdd6-4be7-9e28-b3c72c674832@i7g2000prf.googlegroups.com> [castiro] > Slice literals are a logical next step, precedented by raw strings and > bytes. slice= islice is too, precedented by range= xrange. Looking closely at the [::] notation, I think it can easily be confused with an open box of fleas. IMO, the one unequivocal, explicit way of checking for lice is itertools.is_lice(). Raymond _ ~ @ @ \_/ From dstromberglists at gmail.com Thu Mar 20 14:58:11 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 20 Mar 2008 18:58:11 GMT Subject: forkpty not working? References: Message-ID: <7tyEj.20469$Ch6.19687@newssvr11.news.prodigy.net> If you google a bit, I believe you'll find one or more python modules for working with ssh. Also, if you want to roll your own, the easiest way to get around the password requirement is to use ssh passwordless authentication using DSA or RSA public/private keypairs: http://stromberg.dnsalias.org/~dstromberg/ssh-keys.html As far as why the code below doesn't open your "it_worked" file - exec replaces the current process with the specified process - so the current process effectively goes away on exec. On Thu, 20 Mar 2008 00:40:49 -0700, est wrote: > Hello everyone. I am trying to write a bash/ssh wrapper in python so > python scripts could interact with bash/ssh. > > Because when input passwords to ssh it requires a tty rather than stdin > pipe, so i have to use a pty module to do that. > > I copied this snippet from this thread > http://groups.google.com/group/comp.lang.python/browse_thread/ thread/6bbc3d36b4e6ff55/ > > def rcmd(user, rhost, pw, cmd): > #Fork a child process, using a new pseudo-terminal as the > child's controlling terminal. > pid, fd = os.forkpty() > # If Child; execute external process > if pid == 0: > os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + > cmd) > x=open("it_worked.txt", "w") #output a file for test > x.write("xxx") > x.close() > #if parent, read/write with child through file descriptor else: > pause() > #Get password prompt; ignore > os.read(fd, 1000) > pause() > #write password > os.write(fd, pw + "\n") > pause() > res = '' > #read response from child process > s = os.read(fd,1 ) > while s: > res += s > s = os.read(fd, 1) > return res > > As far as I can see the code is not working, when called the function > rcmd() there is no file it_worked.txt spawned in the directory. I am > n00b to POSIX, so anyone please give me some hint? what happened when > os.forkpty()? From lutz at rmi.net Tue Mar 18 17:00:58 2008 From: lutz at rmi.net (Mark Lutz) Date: Tue, 18 Mar 2008 14:00:58 -0700 (PDT) Subject: Colorado Python training in May Message-ID: Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on May 14-16, 2008. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. For more information on this session, please visit its web page: http://home.earthlink.net/~python-training/longmont-public-classes.htm For additional background on the class itself, see our home page: http://home.earthlink.net/~python-training Thanks for your interest. --Mark Lutz at Python Training Services From Jeff.Goldfinkle at gmail.com Wed Mar 5 15:25:35 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Wed, 5 Mar 2008 12:25:35 -0800 (PST) Subject: Bit twiddling floating point numbers Message-ID: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Hi All Is there a simple way to twiddle the bits of a float? In particular, I would like to round my float to the n most significant bits. For example - 0.123 in binary is 0.000111111 Rounding to 4 bits I get 0.0001. I can pack and unpack a float into a long e.g. struct.unpack('I',struct.pack('f',0.123))[0] but then I'm not sure how to work with the resulting long. Any suggestions? From ggpolo at gmail.com Thu Mar 27 11:21:28 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 12:21:28 -0300 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: 2008/3/27, Skip Montanaro : > > > >>> proc = subprocess.Popen ("ls /tmp") > > > > proc = subprocess.Popen ("ls /tmp", shell=True) > > > > or > > > > proc = subprocess.Popen (["ls", "/tmp"]) > > > > should work. > > > Why should I need to set shell=True? The default is shell=False, which means that Popen will use os.excevp to execute your command, (talking about UNIX here), which in turn expects a list as the "args" parameter, but you are passing a string. Setting shell=True makes Popen execute the string passed through the shell. > I'm not globbing anything. The > second case still fails: > > >>> proc = subprocess.Popen (["/usr/bin/ls" "/tmp"]) Notice how yours is lacking a comma separating the strings while mine does include it. > > Traceback (most recent call last): > > File "", line 1, in ? > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 542, in > __init__ > errread, errwrite) > File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 975, in > > _execute_child > raise child_exception > > OSError: [Errno 20] Not a directory > > Thx, > > > Skip > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From paul at boddie.org.uk Mon Mar 17 06:58:51 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 17 Mar 2008 03:58:51 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <1a560143-9a65-4c9f-bf5b-cb535d17cc13@z38g2000hsc.googlegroups.com> On 17 Mar, 02:39, "BJ?rn Lindqvist" wrote: > > I haven't been to EuroPython even when it has been fairly nearby > because the entrance fee was to high. But how do you help change > something like that? You could join in and make your case. There was a more protracted discussion than usual last year about fees because some people pointed out the discrepancy between salary and price levels in different parts of Europe and the need to make the conference more affordable: what may be relatively inexpensive for some might be relatively expensive for others, and the organisers felt that it would be foolish to exclude the latter group, particularly when they may be more likely to travel to the conference in its present location. It's hard to say whether the conference is reaching everyone it should, given the composition of attendees: http://www.europython.org/community/Planning/Projections But without anyone to pursue a particular cause, and with decisions needing to be made within certain timeframes (which is often a struggle, anyway), things often get preserved as they are rather than being improved. I live in a European country which is either number one or two on the price scale (depending on whether you include alcohol prices or not), and I can't say what the right fee level should be (other than "possibly lower than it is") - it's up to others to weigh in and give their opinion, I think. Paul From arnodel at googlemail.com Sat Mar 22 14:48:00 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 18:48:00 GMT Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: jmDesktop writes: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. I'm not from the US and I'm not sure what 9th/12th grade are, but if you want to use programming to explore maths, er I mean math, have a look at the sage project: http://www.sagemath.org/ -- Arnaud From admin.397 at gmail.com Wed Mar 26 02:35:23 2008 From: admin.397 at gmail.com (Admin.397) Date: Tue, 25 Mar 2008 23:35:23 -0700 (PDT) Subject: Decent 2D animation with Windows.Forms GUI Message-ID: <58745015-2b0e-49c2-936a-e92e8c14d692@d4g2000prg.googlegroups.com> Hi folks, I'm running a simple 2D game using Pygame but really would like a decent GUI and am currently testing out wxPython. As it turns out, I can't get Pygame working in a wxPython canvas and instead turned to openGL - which is painfully slow at reading through an array of points. Can anyone advise on a combination of a good GUI (wxPython really takes the cake here, plugging into the OSes GUI - does anything else do that?) and some form of 2D animation package that has a fair bit of horsepower behind it, that can fit into said GUI? Failing that, any advice on speeding up PyopenGL? I appreciate your assistance! From castironpi at gmail.com Fri Mar 21 02:47:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:47:50 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> <3797c5dd-8d10-4298-af05-fd06440119ce@c19g2000prf.googlegroups.com> Message-ID: On Mar 20, 2:07?am, John Machin wrote: > On Mar 20, 12:50?pm, "Gabriel Genellina" > wrote:> En Wed, 19 Mar 2008 20:16:36 -0300, John Machin ? > > escribi?: > > > > On Mar 20, 9:14 am, sturlamolden wrote: > > >> Is a Python set implemented using a hash table? > > > > What don't you understand about the comments in the first two > > > screenfuls of Objects/setobject.c? > > > That comment was unnecesarily harsh, don't you think? > > No, otherwise I wouldn't have made it. Screenfuls is an awful lot, the way you guys write. Besides, what's the answer? What don't you understand? From Dodin.Roman at gmail.com Wed Mar 26 05:45:17 2008 From: Dodin.Roman at gmail.com (hellt) Date: Wed, 26 Mar 2008 02:45:17 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> On 26 ???, 02:30, kellygreer1 wrote: > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > Is there a page on this in the Python in a Nutshell or the Python > Cookbook? > Did I miss something? > > Kelly Greer > kellygre... at nospam.com > change nospam to yahoo or just look this thread for a fastest solution http://groups.google.com/group/comp.lang.python/browse_frm/thread/7091898414444310/af8961f1ed91ccea?lnk=gst&q=duplicates#af8961f1ed91ccea From half.italian at gmail.com Sat Mar 1 02:17:11 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 29 Feb 2008 23:17:11 -0800 (PST) Subject: Run wxPython app remotely under XWindows References: <9c785431-dd6f-41cc-b185-1820e3827ef0@e10g2000prf.googlegroups.com> <62ovn3F23qsbuU1@mid.individual.net> <48d9279b-4030-4b25-b42f-422ae15c2804@e6g2000prf.googlegroups.com> <147642c3-d0db-4eeb-b1d3-b5919733c1f0@s19g2000prg.googlegroups.com> <3f18e823-727e-4790-82f4-77deee37c3d1@z17g2000hsg.googlegroups.com> Message-ID: <596a5f32-05c8-4aa9-9863-7e418458edf6@e23g2000prf.googlegroups.com> On Feb 29, 8:19?am, Mike Driscoll wrote: > On Feb 28, 7:49 pm, Sean DiZazzo wrote: > > > > > On Feb 28, 5:26 pm, Sean DiZazzo wrote: > > > > On Feb 28, 3:50 pm, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > > > Sean DiZazzo wrote: > > > > > Is there something special you have to do to get a wxPython app to > > > > > run remotely under xwindows? ?My Tkinter apps always automatically > > > > > work that way, so I was surprised to even be confronted with this > > > > > problem. > > > > > Could you please provide more detail? My wxPython apps run perfectly > > > > remotely in the X Window System like this: > > > > > $ ssh some-other-machine > > > > $ DISPLAY=:0 ./my_app.py > > > > Should wxPython apps work this way? ?Do you think it's something with > > > the server? > > > Just to close the loop I think think this is a problem with the ssh > > server. > > > ~Sean > > If it's not the server, then please post the issue to the wxPython > list. They can probably help: > > http://wxpython.org/maillist.php > > Mike To follow up with a solution. I learned that the default install of wxPython, and Tkinter for that matter is compiled to run under Aqua as opposed to X11. It won't run remotely, as I first posted, compiled this way. To get Tkinter to work under X11 you simply need to configure and install a version of python for the X11 environment. The default Mac install (Leopard) and the MacPython distro are configured to run under Aqua. Instead of compiling my own, I found that the default Fink install is configured to run under X11, so if you install it, and run that version of Python, you can run Tkinter apps remotely from a Mac box. wxPython is a bit more complicated. The idea is the same, but the process is much more complicated to get it working. You need to compile wxPython under GTK2, which I found is not well supported for Mac. I followed the instructions at this site: http://wiki.wxpython.org/wxGTK_on_Mac_OSX to get it working. Even with the instructions, I had to finagle a few things to get it to work properly. But it does work! My first successful install was on Tiger, but I'm trying an install on Leopard as we speak. Thanks to Cody Precord for the instructions. I would have never been able to do it without. Now my users will have a prettier GUI! ~Sean From steve at holdenweb.com Sat Mar 1 13:23:30 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 13:23:30 -0500 Subject: Import, how to change sys.path on Windows, and module naming? In-Reply-To: References: Message-ID: Jeremy Nicoll - news posts wrote: > If I understand correctly, when I import something under Windows, Python > searches the directory that the executing script was loaded from, then other > directories as specified in "sys.path". > Technically, I believe it just puts the script's directory at the start of sys.path, then uses sys.path as its module search path. > I assume there are standard locations inside my installed Python - in my > case inside: C:\Program Files\~P-folder\Python25 - where I could put my > modules and they'd automatically be found? But even if that's the norm, I > don't want to put my own modules in such directories, partly because a > uninstall or reinstall or upgrade of Python might lose my stuff, and partly > because I don't believe in mixing distributed code with home-grown code. > There's Lib/site-packages, which is where third-party code normally goes. > However I'm quite happy to have a line or three of code to alter sys.path > to suit my set-up, if that's a normal way to handle this problem. Where > does one do that? > Take a look at site.py, and see that it runs sitecustomize.py when present. > > Also, I presume that there's a risk that the module name that I give to any > of my utilities will clash with a present or future standard module's name. > Does that mean that I should give my own modules names like "JNfoo" rather > than "foo", etc? Or something like "JNutils.foo"? > You can always be sure your own modules will be loaded in preference to shadowing system modules if you put your directories on the path before the standard directories, but most people don't spend a lot of time worrying about this. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Robert.Bossy at jouy.inra.fr Tue Mar 25 11:20:00 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 16:20:00 +0100 Subject: dynamically created names / simple problem In-Reply-To: <47E91645.4000706@jouy.inra.fr> References: <000c01c88e88$96c29490$0600a8c0@laptop> <47E91645.4000706@jouy.inra.fr> Message-ID: <47E91820.7090009@jouy.inra.fr> Robert Bossy wrote: > Jules Stevenson wrote: > >> Hello all, >> >> I'm fairly green to python and programming, so please go gently. The >> following code >> >> for display in secondary: >> >> self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") >> >> Errors, because of the apparent nastyness at the beginning. What I?m >> trying to do is loop through a list and create uniquely named wx >> widgets based on the list values. Obviously the above doesn?t work, >> and is probably naughty ? what?s a good approach for achieving this? >> >> > Hi, > > What you're looking for is the builtin function setattr: > http://docs.python.org/lib/built-in-funcs.html#l2h-66 > > Your snippet would be written (not tested): > > for display in secondary: > > setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1, > "checkbox_2")) Damn! The indentation didn't came out right, it should be: for display in secondary: setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1,"checkbox_2")) RB From vampiro4l at gmail.com Mon Mar 17 17:37:01 2008 From: vampiro4l at gmail.com (Vamp4L) Date: Mon, 17 Mar 2008 14:37:01 -0700 (PDT) Subject: Convert binary file Message-ID: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> Hello, Specifically, I'm trying to convert the Internet Explorer history file (index.dat) into a readable format. Anyone done something similar or know of any functions that may help with such a task? I'm not sure exactly what kind of file the index.dat is, it is some kind of binary file. I have tried some of the binascii functions (http:// docs.python.org/lib/module-binascii.html) without any luck. Thanks From brnstrmrs at gmail.com Wed Mar 19 14:55:18 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Wed, 19 Mar 2008 11:55:18 -0700 (PDT) Subject: csv dictreader References: Message-ID: On Mar 19, 2:32 pm, Mike Driscoll wrote: > On Mar 19, 1:06 pm, brnstrmrs wrote: > > > > > I am trying to use the dictionary reader to import the data from a csv > > file and create a dictnary from it but just can't seem to figure it > > out. > > > Here is my code: > > > >>>import csv > > >>>reader = csv.DictReader(open('table.csv')) > > >>>for row in reader: > > >>>print row > > > my csv files looks like this: > > > Bytecode,Element > > \x00\x00,0000 > > \x01\x00,0001 > > .... > > \x09\x00,0009 > > > My output shows: > > {'Bytecode': '\\x00\\x00', 'Element': '0000'} > > {'Bytecode': '\\x01\\x00', 'Element': '0001'} > > ... > > {'Bytecode': '\\x09\\x00', 'Element': '0009'} > > > 1. how can I get access to this directory > > What do you mean? You can get each element in the dict by doing this: > > for row in reader: > print row['Bytecode'] > print row['Element'] > > > 2. why does the values come with two backslashs infront of the "x" > > The double back slash is for escaping purposes, I think. If you print > this: '\\x09\\x00' > you'll get this: \x09\x00 > > Mike Thanks. It works for the Bytecode but when I do print row['Element'] I get a error message print row['Element'] KeyError: 'Element' From fumanchu at aminus.org Sun Mar 16 12:05:10 2008 From: fumanchu at aminus.org (fumanchu) Date: Sun, 16 Mar 2008 09:05:10 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> On Mar 16, 7:18 am, a... at pythoncraft.com (Aahz) wrote: > Bruce Eckel wrote: > > If the following seems unnecessarily harsh, it was even more harsh for > > me to discover that the time and money I had spent to get to my > > favorite conference had been sold to vendors, presenting me as a > > captive audience they could pitch to. > > Ouch. I'm probably one of the few organizers currently paying much > attention to c.l.py -- because I'm also one of the few who's not at > PyCon. We debated this extensively before going ahead, and we decided > it was worth an experiment. If your feedback is at all representative, > this won't happen again, I assure you. Add me to the list, then, please. I heard from several people that the entire first day was a bit wasted, that even the non-vendor talks on Friday were rather dull and simple. This is my third PyCon, and I've found a reasonably-sized cadre of people who come for the hallway conversations plus a Bof or two, having given up on hearing anything new, useful, or inspiring in the talks. There are several people I know who would like to see a more advanced academic track. > What we were trying to do was to increase sponsorship to decrease > the cost to attendees -- we have NO interest in pushing the > commercialization of Python. Can't fault you for that. But perhaps we're seeing the limit of what that approach can provide. Robert Brewer fumanchu at aminus.org From castironpi at gmail.com Wed Mar 26 04:42:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 01:42:50 -0700 (PDT) Subject: Prototype OO References: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> <13ujk0f9inb73c2@corp.supernews.com> <13uk1e1m2vl0qf4@corp.supernews.com> Message-ID: On Mar 26, 3:14?am, Dennis Lee Bieber wrote: > On Wed, 26 Mar 2008 02:03:24 -0300, "Gabriel Genellina" > declaimed the following in comp.lang.python: > > > > > No:http://en.wikipedia.org/wiki/Saruman Ask him any time over. From iwanttobeabadger at googlemail.com Tue Mar 25 22:04:21 2008 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Wed, 26 Mar 2008 02:04:21 +0000 Subject: Calling a shared library using C types In-Reply-To: References: Message-ID: Hi, Just as a follow up to this...I ve discovered that its an issue with building shared libraries on mac os and it works fine on a Linux box :S. Thanks Nathan On 25/03/2008, Nathan Harmston wrote: > > > > On 25/03/2008, Gabriel Genellina wrote: > > > > En Mon, 24 Mar 2008 19:56:08 -0300, Nathan Harmston > > escribi?: > > > > > > > import ctypes > > > t = ctypes.CDLL('./Simulation.so') > > > this works fine, I have a simple function I ve put in for testing > > which > > > just > > > returns the integer 4. However when I try to access this function it > > > doesnt > > > work > > > t.test() > > > File "", line 1, in > > > File > > > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > > line 325, in __getattr__ > > > func = self.__getitem__(name) > > > File > > > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > > line 330, in __getitem__ > > > func = self._FuncPtr((name_or_ordinal, self)) > > > AttributeError: dlsym(0x81e6b0, test): symbol not found > > > > > > Looks like the symbol isn't public - probably if you try loading the > > library with a C program it won't find it either. How is the function > > declared in the source? > > Try listing all public symbols with: nm -D Simulation.so > > Thanks for the quick reply: > Running nm lists test as > 00001760 T _test > > in the source its declared as: > > int test(){ > return 4; > } > > Sorry, this is the first time I'm making my own shared library and using > ctypes, so being a little slow. > > Thanks again > > Nathan > > > > > > > Im hoping python-list is ok for questions regarding ctypes :S > > > > > > It's not off topic, although there is a specific list for ctypes-related > > questions. But hijacking a thread to post a completely different > > question > > is not good netiquette. > > > > -- > > Gabriel Genellina > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Sat Mar 15 14:05:28 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 18:05:28 +0000 Subject: Getting started with OS X Leopard Message-ID: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> One thing I really liked about Ubuntu was that Nautilus allowed you to add scripts to a directory which could be accessed via the RMB. It was a very simple thing to do. I've recently switched to Leopard, and I'm trying to do the same thing. I'm fairly experienced with Python, but new to OS X. I have installed FinderPop, which lets me add scripts and make them accessible via Contextual Menus, but it is not as easy as the Nautilus way. The sorts of things I want to do are: * copy the directory of Finder to the clipboard * add a new file to Finder's directory. * find out the size of a directory * open a file with Aquamacs, regardless of file type, My head's swimming, though. Anyone got any really good pointers and sample scripts that will help me work out how to achieve the sorts of things I'm trying to do? From gabriel.rossetti at mydeskfriend.com Tue Mar 11 04:49:25 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 11 Mar 2008 09:49:25 +0100 Subject: execute python script question In-Reply-To: References: <47D575E9.8040507@mydeskfriend.com> Message-ID: <47D64795.2090103@mydeskfriend.com> Michael Wieher wrote: > stupid question: you have myPackage somewhere on sys.path? > > I mean, module1.py only knows it lives in a directory, it doesn't know > anything about anything above it. > > > > 2008/3/10, Gabriel Rossetti >: > > Hello, > > I have been developping something in python that has the following > hierarchy : > > project/src/myPackage/ > project/src/myPackage/__init__.py > project/src/myPackage/module1.py > project/src/myPackage/module2.py > project/src/myPackage/test/ > project/src/myPackage/test/__init__.py > project/src/myPackage/test/test_module1.py > project/src/myPackage/test/test_module2.py > project/src/myPackage/mySubPackage/__init__.py > project/src/myPackage/mySubPackage/module1.py > project/src/myPackage/mySubPackage/test/ > project/src/myPackage/mySubPackage/test/__init__.py > project/src/myPackage/mySubPackage/test/module1.py > ... > > up until now, I had been executing my modules from inside > project/src/myPackage/ > but I realised that that is wrong (while implementing the test suite) > and that since all my modules had relative imports (if module2 needed > module1, it would just say : import module1) I changed them to > myPackage.module1 for example. Now my test suite is happy, I can say : > test.sh myPackage.test and it tests everything. The only problem > now is > that I can't execute the scripts from inside or outside the myPackage > dir, I get this : > > from outside : > > Traceback (most recent call last): > File "myPackage/module1.py", line 15, in > from myPackage import constants, utils > ImportError: No module named myPackage > > or if from inside it : > > Traceback (most recent call last): > File "module1.py", line 15, in > from myPackage import constants, utils > ImportError: No module named myPackage > > can anybody please help me? I don't think I understood the whole > package/module thing I think... I think some people do some sort of > importing in the __init__.py files but I'm not sure this helps in > this case. > > Thanks, > Gabriel > > Hello Michael, not a stupid question, I think that may be it. I tried setting PYTHONPATH like Sam suggested and it worked, but I was unable to do it programmically. I tried putting it in the __init__.py file like a web post suggested but it wasn't run until after I set PYTHONPATH, and once that was done there is no need (that I can see anyways) to set it in __init__.py. Thanks for your help, Gabriel From robert.rawlins at thinkbluemedia.co.uk Thu Mar 13 13:38:03 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 13 Mar 2008 17:38:03 -0000 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <47D951C7.3090900@jouy.inra.fr> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> <47D94D61.9010708@jouy.inra.fr> <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> <47D951C7.3090900@jouy.inra.fr> Message-ID: <011501c88530$ff6f7c80$fe4e7580$@rawlins@thinkbluemedia.co.uk> Haha, I could use a stiff whisky myself after the stress that caused me :-) Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Bossy Sent: 13 March 2008 16:10 To: python-list at python.org Subject: Re: "Attribute Doesnt Exist" ... but.... it does :-s Robert Rawlins wrote: > Hi Guys, > > Well thanks for the response, I followed your advice and chopped out all the > crap from my class, right down to the bare __init__ and the setter method, > however, the problem continued to persist. > > However, Robert mentioned something about unindented lines which got me > thinking so I deleted my tab indents on that method and replaces them with > standard space-bar indents and it appears to have cured the problem. > Aha! Killed the bug at the first guess! You owe me a beer, mate. RB -- http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Sun Mar 23 18:30:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 15:30:54 -0700 (PDT) Subject: pydoc References: Message-ID: On Mar 24, 3:31 am, "Gabriel Genellina" wrote: > En Sun, 23 Mar 2008 12:57:35 -0300, A Hutchison escribi?: > > > Any known reasons why pydoc no longer works? > > It gets confused by many timezone changes that occur this month around the > world; pydoc tries hard to please all kind of users and tracking those > locale changes isn't easy. > Wait until April and it will resume working fine, I presume. It's a combination of related factors ... equinox, Easter, full moon. Another seasonal phenomenon: some posters seem to be alpha-testing posts that they intend to make on the first day of the new month. From torriem at gmail.com Sat Mar 1 22:20:32 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Mar 2008 20:20:32 -0700 Subject: Question about lambda and variable bindings In-Reply-To: References: <47CA160C.3000305@gmail.com> Message-ID: <47CA1D00.6090107@gmail.com> poof65 wrote: > An idea, i don't know if it will work in your case. > > for x in xrange(10): > funcs.append(lambda p,z=x: testfunc(z+2,p)) Good idea. I will try it. I also figured out a way to architecture my program differently to avoid this problem. But this idiom might be handy in certain situations. Suppose you need to provide a callback function with a fixed signature to some library routine. But you want to add extra contextual data to your callback. This just might be the ticket. Michael From castironpi at gmail.com Sat Mar 15 18:28:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 15:28:59 -0700 (PDT) Subject: string literal or NoneType References: Message-ID: <5fe63b9c-178f-4333-87a6-7118e8ad7550@s50g2000hsb.googlegroups.com> On Mar 15, 10:27?am, menosa... at gmail.com wrote: > hi all > i want to check a condition and if true should return a filename > string ?from a list.if the condition is false i am returning a > "" ?(string literal).. > > retv="" > if ?somecondition: > ? ? retv=mylist[x] > ... > return retv > > The calling function will check the return value and print the > filename if it is not """. > in the calling function i can code > if returnval !="": > ? ? print "filename is:",returnval > else: > ? ? print "no filename found" > > what i want to know is ,should i rewrite the ?if returnval !="" ?as > > if returnval: > ? ?print "filename is:",returnval > else: > ? ? print "no filename found" > > or is the way i coded the right way ? i am little confused here > Someone suggested that i make a variable retv None and if the > condition true then set retv as filename , > > retv=None > if somecondition: > ? ? retv=mylist[x] > > ... > return retv > > which approach is correct..? can someone help please > vincent One possibility: def fun( ..., testpair, ... ): if somecondition: testpair[ True ]( mylist[x] ) else: testpair[ False ]() . However 'fun' knows "too much for its scope" by varying call signature. Call it by: fun( ..., { True: partial( print, 'filename is:' ), False: partial( print, 'no filename found' ) }, ... ) , which relies even MORE on the particulars of how 'fun' calls. Reversed: return somecondition, partial( mylist.__getitem__, x ) cond, dataf= fun( ... ) if cond: print( 'filename is ', dataf() ) else: print( 'no filename found' ) , which leave different amounts of genericity/genericness/generality to work in. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 12:55:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Mar 2008 16:55:24 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <13ud2rss7oigl94@corp.supernews.com> On Sun, 23 Mar 2008 09:24:35 -0700, Aahz wrote: > The problem with lambda is that too often it results in clutter (this is > a strictly made-up example off the top of my head for illustrative > purposes rather than any real code, but I've seen plenty of code similar > at various times): > > gui.create_window(origin=(123,456), background=gui.WHITE, > foreground=gui.BLACK, callback=lambda x: x*2) > > That means I need to pause reading the create_window() arguments while I > figure out what the lambda means -- and often the lambda is more > complicated than that. Moreover, because the lambda is unnamed, it's > missing a reading cue for its purpose. And of course this would be so much better: def double(x): return x*2 gui.create_window(origin=(123,456), background=gui.WHITE, foreground=gui.BLACK, callback=double) Not. The source of the "clutter" (having *less* code is clutter???) and confusion isn't the lambda, it's the callback. -- Steven From grante at visi.com Wed Mar 19 09:43:32 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 19 Mar 2008 13:43:32 -0000 Subject: lock access to serial port References: Message-ID: <13u2644hpullvd8@corp.supernews.com> On 2008-03-18, kkadrese at gmail.com wrote: > how to get ttyS0 serial port for exclusive access? I have a python > script that uses this device with AT commands. I need that two > instances can call simultaneosuly this python script but only one of > them gets the device. I tried fcntl.flock, it was just ignored, put > writtable file LCK..ttyS0 in /var/lock, Using a lock file is the traditional method of providing mutually exclusive access to a serial port. > tried ioctl (but I may not know what are appropriate > arguments), googled half a day for various phrases, error > messages etc....without success. It's unclear what "without success" means. Lockfiles have been used for decades, and they work fine as long as all of the applications follow the rules. -- Grant From gh at ghaering.de Mon Mar 31 08:39:55 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 31 Mar 2008 14:39:55 +0200 Subject: Problem with sqlite In-Reply-To: <91055e8b-ce64-49a3-b736-16afe8336c4b@e39g2000hsf.googlegroups.com> References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> <91055e8b-ce64-49a3-b736-16afe8336c4b@e39g2000hsf.googlegroups.com> Message-ID: <65c4csF2f0dq5U1@mid.uni-berlin.de> aiwarrior wrote: > [...] > What i'm going to study is whether it's possible to evaluate if a > table already exists, and if so act accordingly. [...] You can use a statement like "CREATE TABLE IF NOT EXISTS tbl(col1, col2);". If you just want to check, you can query SQLite's schema metadata with something like def table_exists(con, table_name): return con.execute("select count(*) from sqlite_master where type='table' and tbl_name=?", (table_name,)).fetchone()[0] -- Gerhard From gagsl-py2 at yahoo.com.ar Wed Mar 19 21:31:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 22:31:28 -0300 Subject: Inserting DTD statement to XML References: <80eadd7f-5a2b-4fa1-a561-23e542436232@8g2000hsu.googlegroups.com> Message-ID: En Wed, 19 Mar 2008 15:33:19 -0300, jakecjacobson at gmail.com escribi?: > I am new to Python and I am writing a script to build a XML document > and post it to a website. I have a working script but need to insert > a DTD statement in my XML document and can't find out how to do this. > I am using "from xml.dom.minidom import Document" > > Some code I am using is: > > doc = Document() > rootNode = doc.createElement("employees") > doc.appendChild(rootNode ) > > I get the following when I print it out > > > > ... > >What I would like is to have something like: > > > > > ... > > Try this: from xml.dom.minidom import getDOMImplementation impl = getDOMImplementation() dt = impl.createDocumentType("employees", "-//ICES//DTD ICES EMPLOYEES//EN", "") doc = impl.createDocument(None, "employees", dt) root = doc.documentElement node = doc.createElement("foo") node.setAttribute("some","attribute") node.setAttribute("attr","value") root.appendChild(node) print doc.toxml() But unless you *have* to use DOM for some reason, better switch to another, more "pythonic" library. Like ElementTree or lxml (both implement the same interface); the former comes with Python 2.5, the later you can get from http://codespeak.net/lxml import xml.etree.ElementTree as ET root = ET.Element("employees") ET.SubElement(root, "foo", some="attribute", attr="value") ET.dump(root) # # ElementTree cannot generate a doctype header, do it by hand f = open("test.xml", "w") f.write('\n') f.write('\n') f.write(ET.tostring(root)) f.close() (note: the lxml version may have doctype support) -- Gabriel Genellina From bj_666 at gmx.net Sat Mar 15 12:57:19 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 16:57:19 GMT Subject: Unicode/UTF-8 confusion References: Message-ID: <642dfeF27mbs3U1@mid.uni-berlin.de> On Sat, 15 Mar 2008 12:09:19 -0400, Tom Stambaugh wrote: > I'm still confused about this, even after days of hacking at it. It's time I > asked for help. I understand that each of you knows more about Python, > Javascript, unicode, and programming than me, and I understand that each of > you has a higher SAT score than me. So please try and be gentle with your > responses. > > I use simplejson to serialize html strings that the server is delivering to > a browser. Since the apostrophe is a string terminator in javascript, I need > to escape any apostrophe embedded in the html. > > Just to be clear, the specific unicode character I'm struggling with is > described in Python as: > u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for > example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of > 0x27. > > This can be expressed in several common ways: > hex: 0x27 > Python literal: u"\u0027" > > Suppose I start with some test string that contains an embedded > apostrophe -- for example: u" ' ". I believe that the appropriate json > serialization of this is (presented as a list to eliminate notation > ambiguities): > > ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] > > This is a 14-character utf-8 serialization of the above test string. > > I know I can brute-force this, using something like the following: > def encode(aRawString): > aReplacement = ''.join(['\\', '0', '0', '2', '7']) > aCookedString = aRawString.replace("'", aReplacement) > answer = simplejson.dumps(aCookedString) > return answer > > I can't even make mailers let me *TYPE* a string literal for the replacement > string without trying to turn it into an HTML link! > > Anyway, I know that my "encode" function works, but it pains me to add that > "replace" call before *EVERY* invocation of the simplejson.dumps() method. > The reason I upgraded to 1.7.4 was to get the c-level speedup routine now > offered by simplejson -- yet the need to do this apostrophe escaping seems > to negate this advantage! Is there perhaps some combination of dumps keyword > arguments, python encode()/str() magic, or something similar that > accomplishes this same result? > > What is the highest-performance way to get simplejson to emit the desired > serialization of the given test string? Somehow I don't get what you are after. The ' doesn't have to be escaped at all if " are used to delimit the string. If ' are used as delimiters then \' is a correct escaping. What is the problem with that!? Ciao, Marc 'BlackJack' Rintsch From robert.rawlins at thinkbluemedia.co.uk Mon Mar 10 06:49:37 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 10 Mar 2008 10:49:37 -0000 Subject: Logging Date/Time Format Message-ID: <00bd01c8829c$6fe77d10$4fb67730$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm using the python logging module, however I'm not happy with the current date/time format which is used to write the timestamp into the log file. I need the logger to write the stamp without the milliseconds appended too it. This is because I use a 3rd party application to parse the logs at a later date as a CSV and the comma separating the milliseconds throws things out. I've been looking through the API documentation but couldn't see any decent method for doing so. Any ideas? Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Sat Mar 1 12:13:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 1 Mar 2008 09:13:11 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> Message-ID: <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> On Mar 1, 11:23?pm, Marc 'BlackJack' Rintsch wrote: (snip) > But the type of `x` must be specialized somehow. ?`x` doesn't start as > `Int` or `Integer` but the very generic and AFAIK abstract type class `Num`. > > After seeing the second line the compiler finds an implementation for `+` > and the type class `Fractional` for both operands and now thinks `x` must > be a `Fractional`, a subclass of `Num`. > > Then comes the third line with `length` returning an `Int` and the > `Fractional` `x` but there is no implementation for a `+` function on > those types. I see, but the same arguments still holds true: the second line have an implicit side-effect of redefining x's type into Fractional type. If I were the designer of the language, I'd leave x's type as it is (as Num) and coerce x for current calculation only. From castironpi at gmail.com Sat Mar 8 13:04:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 10:04:04 -0800 (PST) Subject: multiplication of lists of strings References: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> <47ce56e9$0$10738$426a34cc@news.free.fr> Message-ID: <564294c7-cd78-483e-9393-aad0092809f7@59g2000hsb.googlegroups.com> On Mar 5, 2:16?am, Bruno Desthuilliers wrote: > castiro... at gmail.com a ?crit : > (snip) > > > That reminds me: ?Is there a generic 'relation' pattern/recipie, such > > as finding a computer that's "paired" with multiple users, each of who > > are "paired" with multiple computers, without maintaining dual- > > associativity? > > Yes : use a relational database. No performance hit. Can I write an ad hoc relational class structure? From mensanator at aol.com Tue Mar 4 14:32:59 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 11:32:59 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: <504cc6a7-985e-464e-b38c-c6d31c280e44@e10g2000prf.googlegroups.com> On Mar 4, 2:44?am, Erik Max Francis wrote: > Mensanator wrote: > > On Mar 3, 11:58 pm, Erik Max Francis wrote: > >> Mensanator wrote: > >>> I'm not hard to please at all. > >> No, of course not, since logically you must think all software is useless. > > > Somehow, I expected better logic from people who call themselves > > programmers. > > So you agree with me. ? Are you deliberately misconstruing what I write? > Lack of prefection = uselessness. ? _I_ never said that. What I said was a zero change in net functionality is "worthless". A negative change in net functionality is "less than worthless". Haven't negative numbers been well understood since the Middle Ages? Why is this concept so difficult to grasp? > Thanks for being honest, I wish I could say the same. > whether your realized you defeated your own disclaimer or not. Conclusion based on false premise. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > ? ?I wonder if heaven got a ghetto > ? ? -- Tupac Shakur From python at rcn.com Fri Mar 7 14:20:32 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 7 Mar 2008 11:20:32 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Message-ID: [Cruxic] > Is it possible to get an object out of a set() given another object > that has the same hash code and equality (__hash__() and __eq__() > return the same)? Yes, but it requires an indirect approach. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299 Raymond From aisaac at american.edu Mon Mar 3 09:06:24 2008 From: aisaac at american.edu (Alan Isaac) Date: Mon, 03 Mar 2008 14:06:24 GMT Subject: Is it possible to return a variable and use it...? In-Reply-To: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> References: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> Message-ID: Nathan Pinno wrote: > Is it possible to return a variable and then use it I think you are asking about the ``global`` statement. > like the following: Presumably not. ;-) Cheers, Alan Isaac From tjreedy at udel.edu Sat Mar 1 00:49:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Mar 2008 00:49:09 -0500 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com><13see4t3s23pn59@corp.supernews.com><9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> Message-ID: "Arnaud Delobelle" wrote in message news:ea3aecb0-c946-46be-bcd5-0c7584751e4b at b1g2000hsg.googlegroups.com... | Perhaps it'll be like when I quit smoking six years ago. I didn't | enjoy it although I knew it was good for me... And now I don't regret | it even though I still have the occasional craving. In following the development of Py3, there have been a few decisions that I wish had gone otherwise. But I agree with more than the majority and am not going to deprive myself of what I expect to be an improved experience without giving Py3 a fair trial. tjr From Jeff.Goldfinkle at gmail.com Thu Mar 6 16:01:24 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Thu, 6 Mar 2008 13:01:24 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> <%oOzj.61235$Pv2.29718@newssvr23.news.prodigy.net> Message-ID: <980961ef-43c8-4936-a536-8b5fbc04f0d0@2g2000hsn.googlegroups.com> On Mar 6, 11:00 am, Bryan Olson wrote: > Mark Dickinson wrote: > > Jeff Goldfin wrote: > >> I can pack and unpack a float into a long > >> e.g. > >> struct.unpack('I',struct.pack('f',0.123))[0] > >> but then I'm not sure how to work with the resulting long. > > >> Any suggestions? > > > One alternative to using struct is to use math.ldexp and math.frexp: > > >>>> m, e = frexp(pi) > >>>> m > > 0.78539816339744828 > >>>> e > > 2 > >>>> int(m*2**53) > > 7074237752028440L > > > Then you can do your bit twiddling on int(m*2**53), before using > > ldexp to 'repack' the float. > > Ah, those are handy. Jeff described his problem: "In particular, > I would like to round my float to the n most significant bits." > I think this works: > > from math import frexp, ldexp, floor > > def round_mantissa(x, nbits): > shifter = 1 << nbits > (m, e) = frexp(x) > m = floor(m * shifter + 0.5) / shifter > return ldexp(m, e) > > -- > --Bryan Thanks for the help - your function seems to fit the bill even better than gmpy since I don't need an external module. In my case I'll use m = floor(m * shifter) / shifter instead of m = floor(m * shifter + 0.5) / shifter Jeff From nagle at animats.com Wed Mar 26 11:51:42 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 08:51:42 -0700 Subject: Beta testers needed for a high performance Python application server In-Reply-To: <7xd4pi2bn4.fsf@ruckus.brouhaha.com> References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> <47e9f77b$0$36357$742ec2ed@news.sonic.net> <7xd4pi2bn4.fsf@ruckus.brouhaha.com> Message-ID: <47EA710E.9090909@animats.com> Paul Rubin wrote: > John Nagle writes: >> Fast cgi is a good technology, but it's not well documented or >> well supported. For some reason, the Apache people don't like it. >> It used to be part of the Apache distribution, but that ended years ago. > > It seems to be coming back into favor. See: > > http://cryp.to/publications/fastcgi/ That paper is from 2002. John Nagle From kyosohma at gmail.com Wed Mar 19 14:26:26 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 11:26:26 -0700 (PDT) Subject: modules devoted to manipulationg .reg files References: <12fdb0c5-f880-4264-86d1-be3ad2be8c51@c19g2000prf.googlegroups.com> Message-ID: <5e897a4c-fb4d-4184-8152-176ce3fdfe27@u10g2000prn.googlegroups.com> On Mar 19, 1:14 pm, black_13 wrote: > are there any python modules for manipulation of .reg files producted > by > the win32 prog "reg". > thanks. > black_13 The *.reg files are text files, so you can parse them like any text file. You can just edit the Windows Registry directly using the built- in module: _winreg. There's also a more abstract wrapper called YARW. Mike From sophacles at gmail.com Thu Mar 20 17:53:43 2008 From: sophacles at gmail.com (Erich) Date: Thu, 20 Mar 2008 14:53:43 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> Message-ID: <927f5a44-f8fa-4fe2-bdc2-12fac2d50e7a@s37g2000prg.googlegroups.com> On Mar 20, 12:39 pm, Ed Leafe wrote: > On Mar 20, 2008, at 11:54 AM, atom.ander... at gmail.com wrote: > > > Number Three: Too much code, not enough concept. > > > Presenters this one's for you. I can't count the number of > > presentations I attended where the presenter would click through three > > slides of pycode just to show us a two or three-line snippet that > > illustrated their point. Worse yet, it was often at the bottom of the > > screen so no one but the front row could see it. This goes for text > > two. I saw some great presentations as well, and they had limited > > text on each slide. The last thing your audience wants to see is a > > slide drenched in text of any kind. > > This is good advice: simple slides serve as organization cues, but > the content should come from the speaker. The worst case (only saw > this twice at this year's PyCon) is when there is a text-heavy slide > that the presenter simply reads. We can all read it ourselves! Your > job is to elaborate on the topic. > > I'd like to see two things regarding slides: first, if at all > possible, set a limit on the percentage of the talk that can consist > of slides. I would much rather see the presenter show actual > demonstrations of what they're talking about than simply talking about > it. If that's not possible, then in the session description, clearly > state the % of the talk that will be slides. Perhaps there are people > who like to sit in a room and watch long PowerPoint (-type) > presentations, but I'm not one of them. Let's see some code! Let's see > stuff working (and sometimes crashing!), and how changes affect the > results. When I've presented at PyCon and other conferences, that's > the part that I spend the most time on: preparing demonstrations. It's > not easy to do; certainly much more difficult than creating a slide > that sums up what the demo does. But it makes for a much more > interesting session! > > -- Ed Leafe I'd like to see code listings made available to download where appropriate. That way the slides dont have much hard to read content, and we can look at the bits of code we find tricky as we see fit. And if we get bored with bits, we can play with code! Erich. From sajmikins at gmail.com Tue Mar 18 05:57:06 2008 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Mar 2008 02:57:06 -0700 (PDT) Subject: finding items that occur more than once in a list Message-ID: Is there a more efficient way to do this? def f(L): '''Return a set of the items that occur more than once in L.''' L = list(L) for item in set(L): L.remove(item) return set(L) |>> f([0, 0, 1, 1, 2, 2, 3]) set([0, 1, 2]) From paul at boddie.org.uk Sun Mar 2 15:35:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 2 Mar 2008 12:35:19 -0800 (PST) Subject: tuples, index method, Python's design References: Message-ID: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> On 2 Mar, 19:06, Alan Isaac wrote: > On April 12th, 2007 at 10:05 PM Alan Isaac wrote: > > > The avoidance of tuples, so carefully defended in other > > terms, is often rooted (I claim) in habits formed from > > need for list methods like ``index`` and ``count``. > > Indeed, I predict that Python tuples will eventually have > > these methods and that these same people will then defend > > *that* status quo. You were more confident about this than I was. Still, nothing happens if no-one steps up to do something about it. > > > - Issue #2025 : Add tuple.count() and tuple.index() > > methods to comply with the collections.Sequence API. Here's the tracker item that may have made it happen: http://bugs.python.org/issue1696444 I think you need to thank Raymond Hettinger for championing the cause. ;-) Paul From Afro.Systems at gmail.com Sat Mar 29 16:40:16 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sat, 29 Mar 2008 13:40:16 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> Message-ID: <5ce5652e-4e75-49ca-acb8-30bc6efd350d@b1g2000hsg.googlegroups.com> after executing insert do conection.commit() From sturlamolden at yahoo.no Wed Mar 19 11:56:16 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 08:56:16 -0700 (PDT) Subject: is hash map data structure available in Python? References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Message-ID: <87a293ab-c4f1-4dfc-97b7-efb10bb42e6b@e6g2000prf.googlegroups.com> On 19 Mar, 09:40, grbgooglefan wrote: > How do I create hash map in Python? Python dictionaries are the fastest hash maps known to man. If you need persistent storage of your hash map, consider module bsddb or dbhash. From castironpi at gmail.com Sun Mar 2 11:09:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 08:09:24 -0800 (PST) Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> Message-ID: On Mar 2, 8:15?am, Giles Brown wrote: > On Mar 2, 2:08 pm, Preben Randhol > +valid_for_reply_from_n... at pvv.org> wrote: > > On Sun, 2 Mar 2008 15:06:17 +0100 > > > Preben Randhol wrote: > > > ? ?class dbase(list): > > > Sorry the definition of the class is: > > > ? ? ? ? class dbase(object): > > > it doesn't derive from the list class. > > > Preben > > http://docs.python.org/lib/typeiter.html Be careful on your descision to return an ordered iterator or not-- that is, whether it iterates over the dictionary or the list (if I understand you correctly). If the order's unimportant then please disregard. You can also use: >>> a= [2,3,4] >>> b= iter( a ) >>> next( b ) 2 >>> next( b ) 3 >>> next( b ) 4 From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 21:34:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 01:34:17 -0000 Subject: Big file References: Message-ID: <13th14pe0hhsie1@corp.supernews.com> On Wed, 12 Mar 2008 19:42:44 -0500, Andrew Rekdal wrote: > I am working in the class constructor defining elements of an > application. The problem is the file is getting unmanageble and I am > wanting to extend the contructor __init__ to another file. > > Is it possible to import directly into the contructor the contents of > another module file? > > If so how would this be done? Here's the way you do what you literally asked for: class MyClass(object): def __init__(self, *args): # Warning: completely untested execfile('myfile.py') # may need extra arguments? but you almost certainly don't want to do that. A better way is by importing modules, the same as you would for anything else: class MyClass(object): def __init__(self, *args): from AnotherModule import constructor constructor(self, *args) But frankly if you find yourself needing to do this because your file is "too big" and is unmanageable, I think you are in desperate need of refactoring your code to make if more manageable. Pushing vast amounts of random code out into other files just increases the complexity: not only do you have vast amounts of code, but you have large numbers of files to manage as well. -- Steven From johan.sanden at gmail.com Thu Mar 6 14:03:24 2008 From: johan.sanden at gmail.com (johan.sanden at gmail.com) Date: Thu, 6 Mar 2008 11:03:24 -0800 (PST) Subject: What is a class? References: Message-ID: On Mar 5, 7:50 pm, castiro... at gmail.com wrote: > What is a class that is not a module? A class is a bag of stuff and a namespace :) J. From cruxic at gmail.com Fri Mar 7 14:13:28 2008 From: cruxic at gmail.com (Cruxic) Date: Fri, 7 Mar 2008 11:13:28 -0800 (PST) Subject: Can't get items out of a set? Message-ID: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Hello, all. Is it possible to get an object out of a set() given another object that has the same hash code and equality (__hash__() and __eq__() return the same)? You can't do this with Java Sets either and I've needed it on multiple occasions. Doesn't it seem like it would be useful? Consider: class Person: def __init__(self, id, name): self.id = id self.name = name def __hash__(self): return self.id def __eq__(self, other): return self.id == other.id people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) ... p = people.get_equivalent(2) #method doesn't exist as far as I know print p.name #prints Sue I'm not sure if the above code compiles but I hope you get the idea. Is it possible? Much Thanks. - Cruxic From mensanator at aol.com Tue Mar 4 15:03:47 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Mar 2008 12:03:47 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: <7b1ddced-8138-4ddd-ba87-fb1d55e23197@d4g2000prg.googlegroups.com> On Mar 4, 10:50?am, Lie wrote: > On Mar 4, 1:12?pm, Mensanator wrote: > > > > > > > On Mar 3, 11:58?pm, Erik Max Francis wrote: > > > > Mensanator wrote: > > > > While we're on the subject of English, the word "worthless" > > > > means "has no value". So, a program that doesn't work would > > > > generally be "worthless". One that not only doesn't work but > > > > creates side effects that cause other programs to not work > > > > (which don't have bugs) would be "worse than worthless". > > > > All programs have bugs, which means that in some circumstances, they > > > won't work. ? > > > And in such circumstances, would be worthless. > > > > Therefore, by your reasoning, all programs are worse than > > > useless. > > > That doesn't follow from my reasoning. > > > Suppose you downloaded a new calculator program that > > couldn't add properly. That would be useless to you, right? > > > But suppose the program contained a virus that erased > > your hard drive. That would be "worse than useless", wouldn't it? > > > > > I'm not hard to please at all. > > > > No, of course not, since logically you must think all software is useless. > > > Somehow, I expected better logic from people who call themselves > > programmers. > > Mensanator, for alls sake, you've done right by pointing out the bug > instead of muttering silently in your room, I thought that was what's important. Who am I that anyone cares about my opinions? > but there is a thing > called tolerance that you really should learn, it's about tolerating > and understanding the possibility that other people are humans too and > humans create mistakes, lots of them in fact and that includes you (if > you're humans). Actually, I had resolved to do that and I thought my original post reflected that. Guess I still have to work at it. > Along with tolerance should come a better choice of > wordings, Apparently. > instead of saying "it sucks " I didn't say that. > "because it does something unexpected and unwanted" I didn't say that either. "Unexpected and unwanted" is not necessarily a problem, provided those symptoms are confined to the program. When they reach out and damage things outside the program, it's a lot more serious. > and telling everyone not to use it, It was intended as a warning not to use it. When I saw the random number generator wasn't working, guess what the last cause was that I considered? Do you realize how subtle that error is, how many times I had to stare at it before realizing the problem? You can't see it looking at the trees (factorint() reurns exactly the factors of the composite it was given). It isn't until you step back and look at the forest you suddenly realize that the sequence coming from the "randomly" selected factors is repeating. I was trying to prevent a lot of head scratching by other end users who may be playing with it. > you could > just say "it does something unexpected and unwanted" and say that you > wanted it fixed. I don't think that conveys the proper seriousness. > It's not that you've done anything wrong, but it's > about your attitude. As I said, I thought I had toned done the attitude. OTOH, I'm not sure certain others aren't deliberately misconstuing what I wrote. From troworld at gmail.com Sun Mar 2 15:50:09 2008 From: troworld at gmail.com (Tro) Date: Sun, 2 Mar 2008 15:50:09 -0500 Subject: Altering imported modules In-Reply-To: <200803011856.27611.troworld@gmail.com> References: <200803011856.27611.troworld@gmail.com> Message-ID: <200803021550.09713.troworld@gmail.com> On Saturday 01 March 2008, Tro wrote: > Hi, list. > > I've got a simple asyncore-based server. However, I've modified the > asyncore module to allow me to watch functions as well as sockets. The > modified asyncore module is in a specific location in my project and is > imported as usual from my classes. > > Now I'd like to use the tlslite library, which includes an asyncore mixin > class. However, tlslite imports "asyncore", which doesn't include my own > modifications. > > I'd like to know if it's possible to make tlslite load *my* asyncore module > without changing any of the tlslite code. I guess I could just copy over the relevant tlslite file that imports asyncore and change the import, but that seems clumsy. Is there no better way? Thanks, Tro From aboudouvas at panafonet.gr Thu Mar 27 08:48:12 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 05:48:12 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> Message-ID: On 27 ???, 14:35, Paul Rubin wrote: > king kikapu writes: > > it seems that Psyco's author will not port it for the upcoming Python > > 3000 release :( > > I think the idea is it will be part of PyPy and you should use that. I know that his efforts are on PyPy now but i do not know when PyPy is going to be stable and if i can use it with my current "development stack" (PyQt, Eric4 etc). I mean, i do not know if it will be possible to "abandon" CPYthon and use PyPy instead. From gagsl-py2 at yahoo.com.ar Thu Mar 6 06:35:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 09:35:07 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> Message-ID: En Wed, 05 Mar 2008 02:57:58 -0200, escribi?: >> > > >> >> Can you overload -type-'s decision of what to 'bind'?... >> whenever it >> > > >> >> is it makes it. >> >> > > >> Use delegation instead of inheritance. This class is almost ? >> > > >> indistinguishable from a true function (when used as a method): >> >> Notwithstanding. ?Now bar has a name. > Now func has it. > > from functools import wraps > class myfunction: > __slots__ = ('func','name') > # > def __init__(self, func): > @wraps( func ) > def f( *ar, **kws ): > return func( self, *ar, **kws ) > object.__setattr__(self, 'func', f) > object.__setattr__(self, 'name', None) > # > def __get__(self, instance, owner): > print( "__get__ called for",instance ) > return self.func.__get__(instance, owner) > # > def __getattr__(self, name): > return getattr(self.func, name) > # > def __setattr__(self, name, value): > object.__setattr__(self.func, name, value) > > class mymeta( type ): > def __init__( self, name, bases, namespace ): > for k,v in namespace.items(): > if isinstance( v, myfunction ): > v.name= k > > class P( metaclass= mymeta ): > def foo(self, x): print( 'foo',x ) > # > @myfunction > def bar( fob,self, x): print( 'bar',fob,x ) > > p= P() > p.foo( 0 ) > p.bar( 1 ) > print( p.bar ) > print( p.bar.name ) Mmm, looks too complicated and I don't see any advantage over the original code. Functions already know their (original) name: func_name. If `name` was just an example, note that functions already have writeable attributes too, and my code exposes them as well. This should work with that version (untested): p = P() print p.bar.func_name # -> bar p.bar.im_func.anotherattribute = 1 print p.bar.anotherattribute # -> 1 (the attribute must be set on the *function* itself if you want it to be somewhat persistent; methods are usually volatile objects) -- Gabriel Genellina From nick.fabry at coredump.us Fri Mar 21 22:37:31 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Fri, 21 Mar 2008 22:37:31 -0400 Subject: Improving datetime In-Reply-To: <47E3F234.9010607@cheimes.de> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <47E3C1A3.6050608@ncf.ca> <47E3F234.9010607@cheimes.de> Message-ID: On Mar 21, 2008, at 13:36, Christian Heimes wrote: > Colin J. Williams schrieb: >> You might consider adding the Julian date >> (http://en.wikipedia.org/wiki/Julian_date). >> >> I had a crack at this a while ago but didn't seem to get quire the >> right >> result, using the ACM algorithm. I seemed to be a day out at the >> BC/AD >> divide. > > Yes, the Julian date family is very useful when dealing with dates > before 1900. I'm +1 for adding JDT and MJD. > > TAI64 is another time format used for high precision and real time > measurement. http://cr.yp.to/libtai/tai64.html > This is that 'feature creep' thing I keep reading about on Dilbert, eh? ;-) Obviously, this would not be considered an 'easy bit' - however, the basic datetime.datetime class needs overhauling anyway when we get to the harder bits. So, it's worth determining whether we just want to have it run in the proleptic Gregorian calendar (ISO 8601), or figure out other calendars as well. I don't know anything about TAI64, but I'll read about it. The Julian I do know about (rioting after 'losing' 10 days? Sheesh!) - it was a pretty reasonable swag at hitting the solar year for its time.... Perhaps it might be wise to consider a 'calendar definition object' - I'll dub it a calinfo object for now - that allows third parties to develop a set of rules that define a) how to count in a calendar, and b) how to translate unambiguously from one calendar to another. This suggests that we need a 'standard' calendar, much like UTC is the default timezone for calculations; the proleptic Gregorian seems like the obvious choice for now. So, a new 'superaware' datetime object represents a moment in time and would have: a local datetime, representing what 'local' clocks and calendar indicate at that time a UTC datetime, representing what UTC clocks and calendar indicate at that time a tzinfo object, encapsulating the the rules for translating local times to/from UTC, and a calinfo object, encapsulating: the calculation rules for adding & subtracting timedeltas to datetimes the calculation rules for finding the timedelta between two datetimes the translation rules for converting a datetime with a calinfo object into a datetime with a 'standard' calinfo object With time zones, because their offsets regularly swing back and forth, we have issues with illegal and ambiguous local times. I don't know much about different calendars - I am somewhat sure for Gregorian <--> Julian there are no ambiguities or 'illegal' dates, but I don't know about other calendars. I haven't thought of this before. I need to mull over how to do this - if we are going to spend the time developing three different methods of calculations for three different calendars, and I know there are other calendar systems in the world, it strikes me that the forward thinking thing to do is figure out how to abstract the calendar rule concept, develop a few common examples, and leave it to others (initially) to develop other calendars, much as third parties implemented concrete tzinfo subclasses. In doing so, they revealed some of the present limitations with the current implementation of datetime, that we are now considering updating. We may not have enough experience here of other calendar systems to get this totally right on the first go round, but it sounds worth a try.... > Christian > P.S. By Stewart, I assume you mean the author of pytz? And I think I got the 'no novel' concept - write for people who understand the basic ideas already. Have a good weekend! Nick > -- > http://mail.python.org/mailman/listinfo/python-list From needin4mation at gmail.com Thu Mar 20 11:30:28 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 20 Mar 2008 08:30:28 -0700 (PDT) Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> Message-ID: On Mar 20, 11:21?am, Grant Edwards wrote: > On 2008-03-20, jmDesktop wrote: > > > Hi, I'm trying to learn Python. ?I using Aquamac an emac > > implementation with mac os x. ?I have a program. ?If I go to the > > command prompt and type pythong myprog.py, it works. ?Can the program > > be run from within the editor or is that not how development is done? > > I ask because I was using Visual Studio with C# and, if you're > > familiar, you just hit run and it works. ?On Python do I use the > > editor for editing only and then run the program from the command > > line? > > http://www.google.com/search?q=emacs+python > > -- > Grant Gee. Thanks. From mail at timgolden.me.uk Tue Mar 18 05:02:26 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 18 Mar 2008 09:02:26 +0000 Subject: Convert binary file In-Reply-To: <6487iaF2ar8k2U1@mid.uni-berlin.de> References: <6d7d92fb-640d-4da9-87e6-60a6f21f1604@e39g2000hsf.googlegroups.com> <6487iaF2ar8k2U1@mid.uni-berlin.de> Message-ID: <47DF8522.2010700@timgolden.me.uk> Diez B. Roggisch wrote: > Vamp4L schrieb: >> Hello, >> Specifically, I'm trying to convert the Internet Explorer history >> file (index.dat) into a readable format. Anyone done something >> similar or know of any functions that may help with such a task? I'm >> not sure exactly what kind of file the index.dat is, it is some kind >> of binary file. I have tried some of the binascii functions (http:// >> docs.python.org/lib/module-binascii.html) without any luck. >> Thanks > > You have to have a definition of the format or reverse engineer it. If > you have done that, you can use the module struct. > > But there is no generic way to infer how a binary format is built. Well, there is some info here: http://answers.google.com/answers/threadview?id=115849 on the subject. But, honestly, doing any kind of direct messing with opaque file formats (Microsoft's or anyone else's) is pretty much asking for trouble. Without my ever having tried this, it looks as though a combination of comtypes and IID_IUrlhistoryStg2 [2] might work. If I get the time later I'll try to knock sthg together. (Unless someone else pops in first!) TJG [1] http://pypi.python.org/pypi/comtypes [2] http://support.microsoft.com/kb/897169 From rschroev_nospam_ml at fastmail.fm Sat Mar 29 08:06:27 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 29 Mar 2008 13:06:27 +0100 Subject: finding euclidean distance,better code? In-Reply-To: <13us4sh6u8mfn96@corp.supernews.com> References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> Message-ID: <8hqHj.175213$8Z.117427@newsfet10.ams> Steven D'Aprano schreef: > On Sat, 29 Mar 2008 10:11:28 +0100, Roel Schroeven wrote: > >> Steven D'Aprano schreef: >>> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: >>> >>>> Gabriel Genellina wrote: >>>>> That's what I said in another paragraph. "sum of coordinates" is >>>>> using a different distance definition; it's the way you measure >>>>> distance in a city with square blocks. I don't know if the distance >>>>> itself has a name, but >>>> I think it is called Manhattan distance in reference of the walking >>>> distance from one point to another in this city. >>> You know, there are other cities than Manhattan. Some of them even have >>> streets and blocks. >> I'm not sure what your point is. The name > > "The" name? You go on to list four additional names, so why do you say > that "Manhattan distance" is THE name? When I studied this at university, > we called it the taxi metric. > > >> of the distance happens to be >> Manhattan distance (or taxicab distance, rectilinear distance, L1 >> distance, city block distance; see >> http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid >> point. > > Wikipedia doesn't believe that M-D is the primary or most common name, > and the link you give redirects to "Taxicab distance". Googlefight > agrees: "Taxicab distance" is more than twice as common, and "rectilinear > distance" more than five times as common. > > My point was to draw attention to Robert's unconscious assumptions which > are reflected in his choice of language. Rectilinear distance applies to > more than "distance from one point to another in THIS city" (emphasis > added). You can hardly blame that on Robert. It's true that Manhattan distance is not the only name and not even the most popular one, but it's also true that it's a valid name, and that Robert didn't invent it, he merely used an existing name. > It applies in parts of Rome, Sydney, London, Moscow and many other > places. It even applies to sleepy little country towns like Bendigo and > Mildura here in Australia. Manhattan is hardly the only place where > cities are carved up into rectangular or square city blocks, and I doubt > that it applies to the entirety of Manhattan. No, but it's actually very close. I just looked at the places you mention in Google Earth; while they do have sections with rectangular layouts, in none of them it is as prevalent and obvious as in Manhattan (Manhattan isn't a city of course like the other ones, it's only a part of New York). Now of course it's true that there are many other places with checker board layouts, but I still don't think that makes Manhattan distance a bad name. > The very name is New York-centric, just as much as if the English called > the science of acoustics "Big-Ben-onics" in reference to the peals of Big > Ben's clock. I had thought I had pointed that out with a little gentle > understatement. I'm absolutely not USA/America/New York centric myself, but Manhattan simply is a good and well-known example of a checker board layout. There are worse examples of bad names: 'French fries' for example is French-centric, but that's not the real problem. The real problem is that the name is simply wrong because fries are Belgian (which is disputed, but I believe it since I'm from Belgium ;) ). But I'm still not going the call them freedom fries or anything. In any case, I replied because your reaction didn't feel all that gentle to me; to be honest, it felt rather rude. I apologize for interpreting the tone incorrectly. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From steve at REMOVE-THIS-cybersource.com.au Tue Mar 18 09:10:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 18 Mar 2008 13:10:26 -0000 Subject: how to create instances of classes without calling the constructor? References: <47df0816$0$6635$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <13tvfq214jf8b79@corp.supernews.com> On Tue, 18 Mar 2008 01:08:45 +0100, Dominik Jain wrote: > Hi! > > Does anyone know how an instance of a (new-style) class can be created > without having to call the constructor (and providing the arguments it > requires)? With old-style classes, this was possible using new.instance. > Surely there must be a simple way to do this with new-style classes, too > -- or else how does pickle manage? I don't think you can create an instance without calling __new__. (At least not without all sorts of metaclass tricks.) Creating the instance is what __new__ does. But you can create a new instance without calling the initialiser __init__. Here's a variation on a recipe from Alex Martelli: class Spam(object): def __init__(self, *args): print "spam spam spam spam" self.args = args def empty_instance(cls): class Empty(cls): def __init__(self): pass x = Empty() x.__class__ = cls return x >>> # Create a Spam instance the regular way ... a = Spam("args") spam spam spam spam >>> # And a Spam instance the unusual way ... b = empty_instance(Spam) >>> a.args ('args',) >>> b.args Traceback (most recent call last): File "", line 1, in AttributeError: 'Spam' object has no attribute 'args' -- Steven From castironpi at gmail.com Sun Mar 30 15:43:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 12:43:31 -0700 (PDT) Subject: question Message-ID: <52bef071-e5a7-4712-bafc-cb155b9f46ef@e39g2000hsf.googlegroups.com> Say you have an auditory waveform. In dream hardware, positives would accumulate until something, which would trigger a small chain reaction. In software, with a function f of time t, f( t ), in constant space, what can you know at t? Presume. Silence first, then a broken triad vamps. How long til you recognize it? One sec., i'll attach a binary. From mail at timgolden.me.uk Mon Mar 17 07:34:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 17 Mar 2008 11:34:56 +0000 Subject: Spaces in path name In-Reply-To: References: <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> <9a5974c0-5ac2-4b6f-bdb5-39fd03e279aa@u72g2000hsf.googlegroups.com> <708a66a7-da8f-4d44-824d-8a25203030f7@n58g2000hsf.googlegroups.com> Message-ID: <47DE5760.5050203@timgolden.me.uk> Gertjan Klein wrote: > joep wrote: > >> * If shell=True is required, then the executable is a build-in shell >> command, which does not contain spaces, and, therefore, has no >> problems > > This is only true when you are referring to directly executable files. > However, Shell=True is also required when you want to "execute" a file > by it's association. For example, if you want to execute a ".pyw" file > directly (i.e., by using whichever python executable is associated with > that extension), you need Shell=True. Thanks for that clarification. I hadn't tried that path. TJG From godzillaismad at gmail.com Fri Mar 21 02:13:22 2008 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 20 Mar 2008 23:13:22 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: Just found out that win32api.GetTickCount() returns a tick count in milli-second since XP started. Not sure whether that is reliable. Anyone uses that for calculating elapsed time? From mensanator at aol.com Tue Mar 11 15:36:04 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 11 Mar 2008 12:36:04 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <2fec18c7-2ca7-4706-95b4-3244a01469b0@s19g2000prg.googlegroups.com> On Mar 11, 10:57?am, Mike Hansen wrote: > If one wants to do serious math using Python, the best bet is to use > Sage (http://www.sagemath.org). ?Here are some examples: > > sage: def f(x, bits=53): > ....: ? ? R = RealField(bits); z = R(x) > ....: ? ? return cos(R(pi) * factorial(z-1) / z) > sage: f(100.00,bits=1000) > 0.9999999999999999999999999999999999999999999999999999999999999999999999999?999999999999999999999999999999999999999999999999999999999999999999999999999?999999999999999999999999999999999999999999999999999999999999999999999999999?999999999999999999999999999999999999999999999999999999999999999999999999923?43 If one wants to do serious math using Python, it would be even better to understand the math before breaking out Sage. Didn't you realize that cos(pi*n) is a red herring? That you only need to know if the rational factorial(z-1)/z has a denominator >1 (although you have to make allowances when it's 2)? 2 Prime: True True Prime: True 1/2 3 Prime: True True Prime: True 2/3 4 Prime: False True Prime: False 3/2 5 Prime: True True Prime: True 24/5 6 Prime: False True Prime: False 20 7 Prime: True True Prime: True 720/7 8 Prime: False True Prime: False 630 9 Prime: False True Prime: False 4480 10 Prime: False True Prime: False 36288 11 Prime: True True Prime: True 3628800/11 12 Prime: False True Prime: False 3326400 13 Prime: True True Prime: True 479001600/13 14 Prime: False True Prime: False 444787200 15 Prime: False True Prime: False 5811886080 16 Prime: False True Prime: False 81729648000 17 Prime: True True Prime: True 20922789888000/17 18 Prime: False True Prime: False 19760412672000 19 Prime: True True Prime: True 6402373705728000/19 > > sage: a = > 508184298003433059930221143303110332712493139579190463526792062622045893426?23811236647989889145173098650749 > sage: time ecm.factor(a) > CPU times: user 0.00 s, sys: 0.06 s, total: 0.06 s > Wall time: 2.63 > > [3478697, > ?49998841, > ?11927295803, > ?518069464441, > ?1858900129817, > ?161610704597143, > ?157394131396743433859615518992811454816816449] > > sage: a = ZZ.random_element(10**100); a > 126608167051554688363992508839040790329461609432561783112868335758991396849?7538978358203322629420841 > sage: a.is_prime() > False > sage: b = a.next_prime(); b > 897566586864575221876983862371789080887133487597424495265748007237361461447?1639002293590745490978883 > sage: b.is_prime() > True > > --Mike From mail2spj at yahoo.com Tue Mar 25 11:28:06 2008 From: mail2spj at yahoo.com (SPJ) Date: Tue, 25 Mar 2008 08:28:06 -0700 (PDT) Subject: Reading new mail from outlook using Python In-Reply-To: <47E81CE4.10305@howaboutnow.net> Message-ID: <971720.4797.qm@web50104.mail.re2.yahoo.com> Thanks... I could access the folders in outlook express using the COM interface. Now I am stuck with how to read to a file only new mails. Anyone knows how to achieve this? Thanks SPJ --- On Tue, 3/25/08, Pete Stapley wrote: > From: Pete Stapley > Subject: Re: Reading new mail from outlook using Python > To: mail2spj at yahoo.com > Cc: python-list at python.org > Date: Tuesday, March 25, 2008, 2:58 AM > Well on a FreeBSD/Unix system you can use the .forward to > pipe the > incoming mail for a user to a program. Below is the > contents of my > .forward that invokes procmail. > > "|/usr/local/bin/procmail -m > /path/to/conf/.procmailrc" > > So I imagine you could do something like this in a > .forward. > > "|/path/myprogram.py" > > SPJ wrote: > > Hi, > > > > I am trying to create new tickets in the ticketing > system using > > python. When I receive new email from a particular > address, I have to > > trigger the python script and parse the mail in > required format. > > > > The main hurdle here is, how to invoke the script on > arrival of new > > mail? I checked the outlook settings and found that it > supports only > > microsoft VB script and Jscript. Is there any other > way? I mean, if I > > make a daemon, how will it be notified of new mail? Is > there any > > python module that does this? > > > > I am not sure if this is the right place to ask this, > since it is also > > a microsoft related question. But any help is > appreciated. > > > > Thanks, > > SPJ > > > > > > > ------------------------------------------------------------------------ > > Be a better friend, newshound, and know-it-all with > Yahoo! Mobile. Try > > it now. > > > ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 19:05:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 23:05:15 -0000 Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: <13u5rdb7vmqsma3@corp.supernews.com> On Thu, 20 Mar 2008 10:45:03 -0700, Sean DiZazzo wrote: > After trying again this morning, the file is opened for reading. I must > have had some wonky permissions on that file, so the error method won't > work. Then fix the permissions. -- Steven From paul at boddie.org.uk Sun Mar 30 15:32:21 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Mar 2008 12:32:21 -0700 (PDT) Subject: Vote for a New EuroPython Logo! Message-ID: Earlier this year, the organisers of EuroPython (the annual European Python community conference) decided it was time to update the conference logo: the current logo has been in use since EuroPython began back in 2002. We asked for and received many great submissions for a new logo, and we've made these available on the EuroPython Web site. Now we need your help in deciding which logo shall be part of the EuroPython conference's updated image. Visit the EuroPython Web site to browse the submissions and to cast your votes on the ones you like the most: http://www.europython.org/community/Planning/ProposedLogo We intend to announce the winning logo on Friday 4th April at the latest, so hurry on over to the EuroPython site and cast your votes now! (And stay tuned for more updates on EuroPython 2008!) From larry.cebuala at gmail.com Tue Mar 18 01:25:28 2008 From: larry.cebuala at gmail.com (Larry) Date: Mon, 17 Mar 2008 22:25:28 -0700 (PDT) Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> Message-ID: <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> Thanks to all those who responded to this query. It seems to me that Python always add intervening spaces between data elements when writing to a file. Even with tostring() of numpy, array elements get separated by space character. I like the output of sys.stdout.write(file) to be writen as is to a binary file, but how? I'll try your suggestions. Good luck, especially to me! :) From felciano at gmail.com Mon Mar 24 10:15:58 2008 From: felciano at gmail.com (felciano) Date: Mon, 24 Mar 2008 07:15:58 -0700 (PDT) Subject: Multiline CSV export to Excel produces unrecognized characters? References: <4f6f122f-45bb-4aa5-b9c9-5eb3e84a0964@i7g2000prf.googlegroups.com> <64p25uF2c2qidU2@mid.uni-berlin.de> Message-ID: > > Any chance you are doing this on Windows and Excel doesn't like the > return+linefeed line endings that Windows produces when writing files in > text mode? Try 'wb' as mode for the output file. > > Ciao, > Marc 'BlackJack' Rintsch > Fixed! Can't believe I missed that... Thank you for the quick reply! Ramon From craigm3604 at gmail.com Tue Mar 25 11:24:13 2008 From: craigm3604 at gmail.com (Craig) Date: Tue, 25 Mar 2008 08:24:13 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> <8fd0d8bd-c80a-4ec1-a70a-ea659a84413e@e6g2000prf.googlegroups.com> <13uh5bq2ri0280a@corp.supernews.com> Message-ID: On Mar 25, 2:02 am, Dennis Lee Bieber wrote: > On Mon, 24 Mar 2008 15:21:11 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > And this is what I got: > > VmxGet test - looking for valid record... > > Before - PriKey = 0x0044F56C, SecKey = 0x0044F534 > > ci_PriKey = 0x0044F56C, ci_SecKey = 0x0044F534 > > After - PriKey = 0x0044F56C, SecKey = 0x0044F534 > > ci_PriKey = 0x0043D49C, ci_SecKey = 0x0043D484 > > So VmxGet() DID allocate new BSTR structures. > > It might be interesting to extract the length data that is part of > the BSTR and compare. > > ctypes.string_at(PriKey - 4, 4) #if I recall the arguments > vs > ctypes.string_at(ci_PriKey - 4, 4) > > If the second (after conversion to integer) is larger than the > former, it could mean that the routine checks what is passed in to > ensure enough storage space, and if it won't fit, does the allocation. > > If it were always going to do an allocation, there would have been > no excuse for /reading/ the passed in structure length. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ I changed to the following to followup on the length data: printf ("Before - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(ci_SecKey), byref(ci_PriKey), TypeDef ) printf ("After - PriKey = 0x%8.8X, SecKey = 0x%8.8X\n", PriKey, SecKey) printf (" ci_PriKey = 0x%8.8X, ci_SecKey = 0x%8.8X\n", ci_PriKey.value, ci_SecKey.value) print ord(string_at(PriKey - 4, 1)), ord(string_at(PriKey - 3, 1)), ord(string_at(PriKey - 2, 1)), ord(string_at(PriKey - 1, 1)) print ord(string_at(ci_PriKey.value - 4, 1)), ord(string_at(ci_PriKey.value - 3, 1)), ord(string_at(ci_PriKey.value - 2, 1)), ord(string_at(ci_PriKey.value - 1, 1)) And, got: Before - PriKey = 0x0028B6FC, SecKey = 0x0028B6C4 ci_PriKey = 0x0028B6FC, ci_SecKey = 0x0028B6C4 After - PriKey = 0x0028B6FC, SecKey = 0x0028B6C4 ci_PriKey = 0x0027D284, ci_SecKey = 0x0027D26C 41 0 0 0 7 0 0 0 Which makes sense for two reasons: 1. It would only return the non-space-filled part of the returned key. 2. At least from VB6, the variable does not even have to be used before the call. I have gone on to design a function for printing the contents as fields in a Structure. def DCOD_Print(): temp = unpack(DecoderRecordFormat, TypeDef.raw) DCOD = DecoderRecord(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5]) print " DistID = \x22%s\x22" % DCOD.DistID print " YearCode = \x22%s\x22" % DCOD.YearCode print " AccountType = \x22%s\x22" % DCOD.AccountType print "AccountNumber = \x22%s\x22" % DCOD.AccountNumber print " Description = \x22%s\x22" % DCOD.Description print " Unused = \x22%s\x22" % DCOD.Unused return class DecoderRecord(Structure): _fields_ = [ ("DistID", c_char_p), ("YearCode", c_char_p), ("AccountType", c_char), ("AccountNumber", c_char_p), ("Description", c_char_p), ("Unused", c_char_p) ] DecoderRecordFormat = "3s4ss32s32s56s" Then, a simple: print DCOD_Print() parses the record into its fields, and displays those fields. In other files, some of those fields are VB6 currency types, which have been described as 8-byte integers with an implied 4 decimal places (which I guess would be __int64 or c_longlong and then divide by 10,000, or simply put a decimal point 4 away from the end). Any ideas on how best to process this type of data in Python? From mattheww at chiark.greenend.org.uk Wed Mar 5 18:27:21 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 05 Mar 2008 23:27:21 +0000 (GMT) Subject: Why """, not '''? References: <13su5tn6rpjb345@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >On Wed, 05 Mar 2008 19:19:08 +0000, Matthew Woodcraft wrote: >> One advantage is that a dumb syntax highlighter is more likely to cope >> well if the content includes an apostrophe. > But if the content contains double-quote marks, the "dumb syntax > highligher" is more likely to cope well if you use '''. That's right. But apostrophes are rather more common than quote marks in English text. > And, let's be realistic here, a "dumb syntax highlighter" is more > likely to not cope well with triple-quote strings *at all*. In practice they often do the right thing, what with three being an odd number. -M- From jaywgraves at gmail.com Tue Mar 11 09:34:03 2008 From: jaywgraves at gmail.com (jay graves) Date: Tue, 11 Mar 2008 06:34:03 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> Message-ID: On Mar 11, 12:21 am, royG wrote: > On Mar 10, 8:03 pm, Tim Chase wrote: > in the version using glob() > > >path = os.path.normpath(os.path.join(folder, '*.txt')) > >lst = glob.glob(path) > > is it possible to check for more than one file extension? here i will > have to create two path variables like > path1 = os.path.normpath(os.path.join(folder, '*.txt')) > path2 = os.path.normpath(os.path.join(folder, '*.doc')) > > and then use glob separately.. > or is there another way? use a loop. (untested) def parsefolder(folder): lst = [] for pattern in ('*.txt','*.doc'): path = os.path.normpath(os.path.join(folder, pattern)) lst.extend(glob.glob(path)) lst.sort() return lst From sjmachin at lexicon.net Sat Mar 15 22:37:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Mar 2008 19:37:56 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: <83232bff-e991-422d-835e-f321dafa1ede@i12g2000prf.googlegroups.com> On Mar 16, 12:12 pm, lampshade wrote: > Hello, > > I'm having some problems with os.path.isdir I think it is something > simple that I'm overlooking. > > #!/usr/bin/python > import os > > my_path = os.path.expanduser("~/pictures/") > print my_path > results = os.listdir(my_path) > for a_result in results: > if os.path.isdir(str(my_path) + str(a_result)): Not parts of the problem, but: (1) you don't need to use str() here. (2) use os.path.join instead of the + operator, if you are interested in portable code. > results.remove(a_result) > > for x in results: print x > > The problem is, that the directories are never removed. Can anyone > point out what I'm missing that is causing the bug? Is there a better > way of doing this? > > Thanks, You are removing directory *NAMES* from the container named "results". If you want to remove the directories from your filesystem, use os.rmdir. From kyosohma at gmail.com Sun Mar 16 08:47:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 16 Mar 2008 05:47:10 -0700 (PDT) Subject: Python for BlackBerry References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> Message-ID: <79aa668a-f1b6-4f59-9ff9-8dc9dfc177aa@a23g2000hsc.googlegroups.com> On Mar 15, 9:52 pm, "Sandipan Gangopadhyay" wrote: > Thanks, Mike. > This one seems to be for Nokia, particularly S60 and Symbian in general. > Does BlackBerry work on Symbian? Let me check. > Thanks. > Sandipan > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of Mike > Driscoll > Sent: Saturday, March 15, 2008 6:04 PM > To: python-l... at python.org > Subject: Re: Python for BlackBerry > > On Mar 15, 7:24 am, "Sandipan Gangopadhyay" > wrote: > > Is there a Python for BlackBerry? Thanks. > > > -----Original Message----- > > From: python-list-bounces+news=sandipan.... at python.org > > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of > E-Lo > > Sent: Saturday, March 15, 2008 6:03 AM > > To: python-l... at python.org > > Subject: Python for Palm OS > > > Is there any other edition of Python for Palm OS instead of Pippy? > > --http://mail.python.org/mailman/listinfo/python-list > > You might look at Mobile Python. I'm not sure if it works on > Blackberry though:http://www.mobilepythonbook.org/ > > Mike > --http://mail.python.org/mailman/listinfo/python-list I was afraid of that. I'm at PyCon and between their flakey wireless and my own laptop's flakey wireless card, it''s been a pain to do any research. Good luck. Mike From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 00:48:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 04:48:29 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: <13uecktbcbt9r1e@corp.supernews.com> On Sun, 23 Mar 2008 22:36:35 -0400, Roy Smith wrote: >> > I've also done two things. First, I've created a function object >> > (i.e. a lambda body), and I've also bound the name torture to that >> > function object, in much the same way I did with the list. But, it's >> > different. The function object KNOWS that it's name is torture. >> >> No it does not. Function objects don't know their name. All they know >> is that they have a label attached to them that is useful to use as a >> name in some contexts, e.g. when printing tracebacks. It's just a >> label, nothing more. > > I think we're arguing the same thing. When you write > > def foo(): > whatever > > you create an object which contains the string "foo", retrievable > through its __name__ attribute. That's what I meant by "it knows its > name" But that's not true. Firstly, you can't access the __name__ attribute unless you already have a reference to the object (not necessarily a name), so clearly the __name__ attribute isn't how you retrieve objects. Secondly, the __name__ attribute has no special purpose. It's not even used for tracebacks. >>> def foo(): ... return "result" ... >>> foo.__name__ = "something" >>> something() Traceback (most recent call last): File "", line 1, in NameError: name 'something' is not defined >>> >>> something = foo >>> something() 'result' >>> something(None) Traceback (most recent call last): File "", line 1, in TypeError: foo() takes no arguments (1 given) >>> something.__name__ 'something' -- Steven From pavloutefkros at gmail.com Mon Mar 31 12:11:49 2008 From: pavloutefkros at gmail.com (Gif) Date: Mon, 31 Mar 2008 09:11:49 -0700 (PDT) Subject: wxPython listctrl References: <4dc652a5-d6f9-4cb8-af30-ec1c9e4ea505@y21g2000hsf.googlegroups.com> <8fcac15f-ad92-47b2-84bb-1d8e474ea016@i7g2000prf.googlegroups.com> Message-ID: <37308f0e-8edd-410f-83d1-62012f08cdef@s8g2000prg.googlegroups.com> thanks Mike, i'll post there. From hniksic at xemacs.org Wed Mar 19 18:41:12 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 19 Mar 2008 23:41:12 +0100 Subject: removing all instances of a certain value from a list References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Message-ID: <87lk4e2v7b.fsf@mulj.homelinux.net> Lee Sander writes: > Hi, > I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are > many missing vlaues which are represented as None. I would like to > remove all such instances in one go. > There is a remove function but it removes only the first instance, is > there a delete/remove all function? No, but you can easily simulate it using, for example: lst[:] = (el for el in lst if el is not None) From pavlovevidence at gmail.com Thu Mar 6 09:30:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 06:30:41 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> On Mar 5, 8:44 pm, Steven D'Aprano wrote: > But what about classes? Are they singletons? Obviously classes aren't > Singleton classes, that is, given an arbitrary class C you can create > multiple instances of C. But what about class objects themselves? I've > found a few odd references to "classes are singletons", but nothing in > the language reference. Probably because "singleton" is the wrong word. A singleton means there is one instance of a type; classes are instances of "type" which can have many instances so classes are not singletons. Anyway, the answer to what you are probably asking is No. Try this: >>>import module >>>c1 = module.Someclass >>>reload(module) >>>c2 = module.Someclass >>>c1 is c2 For that matter, try this: >>>import module >>>c1 = module.Someclass >>>module.Someclass = some_other_class() >>>c2 = module.Someclass >>>c1 is c2 Carl Banks From tjreedy at udel.edu Fri Mar 21 02:29:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 Mar 2008 02:29:03 -0400 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0] References: Message-ID: "Simon Forman" wrote in message news:b39eb6cc-5c35-41d7-87be-6821f8f1ded3 at a1g2000hsb.googlegroups.com... | I've been thinking of volunteering to "port" Tkinter to Python 3.0, I | hadn't noticed that there was any discussion of removing it. It would | be a shame IMHO. Sure it has warts, but it /works/ and good for quick | and dirty GUIs as well as elaborate (even totally visually customized) | fancy applications. If you are serious, please communicate that willingness to the lib-sig. A lack of such a volunteer would be a factor in dropping it. The current developers are pretty well booked up with other stuff. From rridge at caffeine.csclub.uwaterloo.ca Mon Mar 10 14:52:00 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 10 Mar 2008 14:52:00 -0400 Subject: BitVector References: <508e7867-d6ed-439d-befc-a5c994475211@x41g2000hsb.googlegroups.com> Message-ID: DanielJohnson wrote: >I am trying to solve a genetic algorithm problem where I want to read >a bitvector of very large size (say 10000) and manipulate bits based >on certain algorithms. > >I am a newbie in Python. What data structure are good to read such >huge data set. Are there any built in classes for bit fiddling. A 10000 bit data set is by no means huge. Depending on exactly what operations you want to perform converting your "bitvector" to a byte array, one bit per byte may be fast way to go. This increases the size of data set by 8 times, but it's probably the fastest way in Python to test and set individual bits. Here's a couple of functions I wrote for very quickly converting a "bitvector" in the form of a string (eg. read from a file) in to a byte array: import string import array import binascii _tr_16 = string.maketrans("0123456789abcdef", "\x00\x01\x02\x03" "\x10\x11\x12\x13" "\x20\x21\x22\x23" "\x30\x31\x32\x33") _tr_4 = string.maketrans("0123", "\x00\x01" "\x10\x11") _tr_2 = string.maketrans("01", "\x00\x01") def string_to_bit_array(s): """Convert a string to an array containing a sequence of bits.""" s = binascii.hexlify(s).translate(_tr_16) s = binascii.hexlify(s).translate(_tr_4) s = binascii.hexlify(s).translate(_tr_2) a = array.array('B', s) return a _tr_rev_2 = string.maketrans("\x00\x01", "01") _tr_rev_4 = string.maketrans("\x00\x01" "\x10\x11", "0123") _tr_rev_16 = string.maketrans("\x00\x01\x02\x03" "\x10\x11\x12\x13" "\x20\x21\x22\x23" "\x30\x31\x32\x33", "0123456789abcdef") def bit_array_to_string(a): """Convert an array containing a sequence of bits to a string.""" remainder = len(a) % 8 if remainder != 0: a.fromlist([0] * (8 - remainder)) s = a.tostring() s = binascii.unhexlify(s.translate(_tr_rev_2)) s = binascii.unhexlify(s.translate(_tr_rev_4)) return binascii.unhexlify(s.translate(_tr_rev_16)) I've used these functions to implement a data compression algorithim in Python. The algorithm still runs very slow in Python, but it runs much faster than it would have if I had used Python's bitwise operators. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From gowricp at gmail.com Sun Mar 23 20:10:40 2008 From: gowricp at gmail.com (Gowri) Date: Sun, 23 Mar 2008 17:10:40 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> <29cd9085-b70f-4873-899e-3837d8e42d90@u69g2000hse.googlegroups.com> Message-ID: <89e74a42-09b5-4612-be54-6ece1d2de696@e39g2000hsf.googlegroups.com> Hi Tim, I'm able to get and print correctly some HTML content. I don't know how to fix this. Need all the help I can get with this :) Regards, Gowri From planders at gmail.com Thu Mar 20 16:55:33 2008 From: planders at gmail.com (Preston Landers) Date: Thu, 20 Mar 2008 13:55:33 -0700 (PDT) Subject: Strange behavior of the Eclipse embedded console References: <23ab07a7-0355-48a7-8bf2-266a56f4efb9@h11g2000prf.googlegroups.com> Message-ID: On Mar 20, 9:09?am, hellt wrote: > "The eclipse console is not an exact copy of a shell... one of the > changes is that when you press in a shell, it may give you a > \r, \n or \r\n as an end-line char, depending on your platform. Python > does not expect this -- from the docs it says that it will remove the > last \n (checked in version 2.4), but, in some platforms that will > leave a \r there. This means that the raw_input() should usually be > used as raw_input().replace('\r', ''), and input() should be changed > for: eval(raw_input().replace('\r', ''))." While I do love Eclipse as a Python code editor, interactive debugger, front-end to SVN / Trac, and for many other things... it is unfortunately terrible as an interactive console. But then again, despite being a long time Emacs user I never did anything complex inside Emacs' shell / terminal emulator, instead preferring a 'real' console using xterm or rxvt or konsole or what have you. By the way, so far the only text editing feature from Emacs I am missing in Eclipse is the ability to reformat line endings - i.e., M-x fill-paragraph-or-region regards Preston From goldspin at gmail.com Thu Mar 6 19:43:58 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 6 Mar 2008 16:43:58 -0800 Subject: How to Encode String of Raw UTF-8 into Unicode? Message-ID: Hi everyone, Suppose I start out with a raw string of utf-8 code points. raw_string = "68656E727963" I can coerce it into proper unicode format by slicing out two characters at a time. unicode_string = u"\x68\x65\x6E\x72\x79\x63" >>> print unicode_proper >>> henry My question: is there an existing function that can do this (without having to manually slicing the raw text string)? Thanks. From dickinsm at gmail.com Wed Mar 12 11:25:41 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 12 Mar 2008 08:25:41 -0700 (PDT) Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: On Mar 12, 10:18?am, Gerdus van Zyl wrote: > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: You could wait for Python 2.6, or download the current alpha: Python 2.6a1+ (trunk:61353M, Mar 12 2008, 11:21:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from itertools import product >>> for c in product(['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']): print c ... ('3', '9', '5', '4', '2') ('3', '9', '5', '4', '5') ('3', '9', '5', '4', '8') ('3', '1', '5', '4', '2') ('3', '1', '5', '4', '5') ('3', '1', '5', '4', '8') If you can't wait, look at http://docs.python.org/dev/library/itertools.html where equivalent code is given. Mark From michael.wieher at gmail.com Fri Mar 14 10:15:58 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 14 Mar 2008 09:15:58 -0500 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: 2008/3/14, Pradeep Rai : > > Dear All, > > I am working on the python tools that process a huge amount of GIS data. > These tools encountering the problem of memory leaks. > > Please suggest what are the different ways to detect the memory leaks in > python ? > > This is very critical problem for me. Help needed urgently. > > Thanks & Regards, > > Pradeep > Python doesn't have memory leaks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Sun Mar 2 15:32:57 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 12:32:57 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <7xskz9wpw6.fsf@ruckus.brouhaha.com> References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I can live with int/int=float but > find it sloppy and would be happier if int/int always threw an error > (convert explicitly if you want a particular type result). Better yet, how hard would it be to define an otherwise int-like type that did not define a non-flooring division operator? Are there any real use cases for such a type? Maybe a division operator could be defined to perform a run-time check that, for an operation n/d==q, n==q*d; else, throw an exception. Code written to support duck-typed integers should work with such a UDT "out of the box." From sjdevnull at yahoo.com Tue Mar 4 11:18:39 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Tue, 4 Mar 2008 08:18:39 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> <55f1c2b7-0f8f-4bcc-ac59-0b78a81cf81e@e31g2000hse.googlegroups.com> Message-ID: On Mar 4, 10:44 am, Ron DuPlain wrote: > On Mar 4, 10:13 am, Siddhant wrote: > > > Hi people. > > I was just wondering if a tab-completion feature in python command > > line interface would be helpful? > > If yes, then how can I implement it? > > Thanks, > > Siddhant > > ipython provides auto tab completion.http://ipython.scipy.org/ > > You can also get it by: > $ easy_install ipython > > Run it using the command: > $ ipython > > Is this what you want? ipython also makes stack traces nearly unreadable by default (setting "xmode Plain" in the ipythonrc fixed that) and tends to take up too much vertical screen space, wants to colorize a lot of stuff, and has a few other things that I was't fond of. There's some nice stuff in ipython (saving the return values of every line in the shell), but I found trying to configure off all of the "magically helpful" stuff that wound up being more annoying than useful was a fairly long job. I found it easier just to turn on completion in the regular python shell. From my .pythonrc: try: import readline except ImportError: print "Module readline not available." else: import rlcompleter readline.parse_and_bind("tab: complete") del readline, rlcompleter With that and persistent history I'm pretty happy: import readline histfile = os.path.join(os.environ["HOME"], ".pyhist") try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del os, histfile From castironpi at gmail.com Sun Mar 16 02:35:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 23:35:49 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: On Mar 15, 9:28?pm, Benjamin wrote: > On Mar 15, 7:29 pm, castiro... at gmail.com wrote:> 'join' in the wrong word for the method in class Thread. > > > The agent-patient semantics of calling functions can get ambiguous. > > It is not a problem of native Pythoners alone. ?Is it due to lazy > > programming, an inability of English (do you have it in other > > languages?), or not a problem at all? > > This is what Java uses, and Python's threading module tries to imitate > it. If everybody's using join, then everybody's using join. That by itself doesn't constitute a case that the practice, the trend, is either right or wrong. Which is why I bring it up! Upon some second thoughts, the OP (myself) could use a few more examples... maybe even some parameters. Maybe even a spell checker (subject line). > th1.join() -> 'be joined by th1' > file1.close()-> 'close file1' > lock1.wait()-> 'getinlinefor lock1' One approach is to take a 'declarative' perspective: make them statements instead of commands. th1.join() -> th1.joins() file1.close() -> file1.closes() lock1.wait() -> lock1.becomesfree() htmlparser.reset() -> htmlparser.resets() htmlparser.feed( data ) -> htmlparser.eats( data ) pickle.dump( obj ) -> pickle.dumps( obj ) pickle.dumps( obj ) -> pickle.sdumps( obj ) socket.accept() -> socket.accepts() I tried once but got frustrated because the libraries wouldn't fit in. lock1.becomesfree() is a fine example. It's saying what happens in that statement, which is a lot closer to what's actually going on-- because lock is doing exactly nothing until something else in some other story line. thread1.joins() similarly. I do contend that names are hard to pick-- "one-worders" take perspective and distance, which are pricey pricey-- and unfortunately deadlines press and the existing ones come already to be used. Of course, Python version graduation is a fine time to make the change, but I'm no good at asking politely-- the right people at the right times and in the right ways. A tool might be able to convert the obvious cases automatically, and prompt the operator about any residue. He wouldn't necessarily even have to change overridden methods by hand either! Multi-control systems may have cause the rift. Without them, 'do it' is the same as 'it does it'. With them, 'he does it' and 'you do it' are different. However the popularity of object-orientation may be the culprit: not all of our instruction names made the jump right. Maybe both. Aside: The docs are heavily (-heavily-) in the patient (passive) voice too: code.interact: "is passed", "is then run", "is discarded", as well as alternate between declaration and command. But -you- rewrite them, Mr. Backseat Driver! A lot of abbreviations 'recv', 'del', 'dir', and 'stat' can go. I digress. The language would be changing pretty deeply: returns, yields, passes, dels, raises, breaks, continues, imports. The 'returns' would even move over: retval returns; object() returns; match returns (return retval, return object(), return match). Maybe there's a language out there that understands! The inconsistency is in the address of threads and synchro. objects: The author changes audiences. In th1.join(), he is not commanding his audience to join th1. Biggest problem. It's like an implicit 'the self thread' shows up from dreamworld or something. th1.join( this_thread ) lock1.waitfor( a_goahead ) lock1.waitfor( someone_else_to_finish_up ) I'm not holding that the functions aren't defined. I'm saying the names are hastily chosen. The join documentation doesn't use the word 'join'. Event.wait doesn't use wait, but Condition, os, and subprocess do. "Event.wait( [timeout]) Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). " Aside: The rage-against-the-machine/paranoia/conspiracy-theory side of me tries to ascribe malice to the writers, saying "they" were "holding" "me" "down" (referring to my nose, of course). I know better, but college was rough and the girlfriend pulled, so I don't always catch it. Cough. My earlier use of 'lazy' may have been a bit pejorative. It insinuated the authors devoted time to Doritos over better names, rather than just other names or even bugs. I was in a different setting then -and- on autopilot. It proves my point, though. Time is scarce. Help me ask the right way! From iainking at gmail.com Mon Mar 17 07:16:46 2008 From: iainking at gmail.com (Iain King) Date: Mon, 17 Mar 2008 04:16:46 -0700 (PDT) Subject: String To List References: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> <42858a90-80eb-45ac-8f76-ad9d06ee4fbf@d21g2000prf.googlegroups.com> Message-ID: <4ea462e2-cecc-40fc-a62b-658c0fcc28a6@c19g2000prf.googlegroups.com> On Mar 17, 9:27 am, Iain King wrote: > On Mar 17, 6:56 am, Dan Bishop wrote: > > > On Mar 17, 1:15 am, Girish wrote: > > > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > > this?? > > > Thanks for the help... > > > eval(a) will do the job, but you have to be very careful about using > > that function. An alternative is > > > [s.strip('\'"') for s in a.strip('[]').split(', ')] > > This will fall over if xyz or abc include any of the characters your > stripping/splitting on (e.g if xyz is actually "To be or not to be, > that is the question"). Unless you can guarantee they won't, you'll > need to write (or rather use) a parser that understands the syntax. > > Iain Thinking about this some more; could the string module not use a simple tokenizer method? I know that relentlessly adding features to built-ins is a bad idea, so I'm not sure if this falls within batteries-included, or is actually just adding bulk. On the one hand, it's not difficult to write a simple state-based token parser yourself, but on the other it is also quite easy to include a pile of bugs when you do. By simple I mean something like: def tokenize(string, delim, closing_delim=None, escape_char=None) which would return a list (or a generator) of all the parts of the string enclosed by delim (or which begin with delim and end with closing_delim if closing_delim is set), ignoring any delimiters which have been escaped by escape_char. Throw an exception if the string is malformed? (odd number of delimiters, or opening/closing delims don't match) In the OP's case, he could get what he want's with a simple: l = a.tokenize("'") The point of this ramble not being that this is a how to solve the OP's question, but wondering if it would be a good inclusion to the language in general. Or there's actually a module which already does it that I couldn't find and I'm an idiot... Iain From http Sat Mar 29 10:38:34 2008 From: http (Paul Rubin) Date: 29 Mar 2008 07:38:34 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> <65701aF2erbbsU1@mid.uni-berlin.de> Message-ID: <7xr6dta93p.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > In which sense is that different? AFAIK select lets you avoid polling > and provides notifications (possibly with timeouts) for IO-events. So > where exactly is the difference? I read TFA, and it does mention that > select/poll have potential for optimization, but not something that > disqualified them (or rather select) as being not async. Select blocks until the data is ready, while with AIO the i/o happens completely in the background and your process gets an interrupt when the i/o completes. Also, with select based i/o, usually the kernel reads data from the external device into a system buffer, and then you do a read system call that copies the data from the system buffer to your buffer. AIO can be set up so the i/o happens directly into your buffer, avoiding the extra copying. You can also initiate a bunch of different i/o events with a single system call, avoiding some context switches. http://www.ibm.com/developerworks/linux/library/l-async/ describes select as "asynchronous, blocking" as opposed to AIO which is asynchronous and nonblocking. Other descriptions I've seen reserve "asynchronous i/o" for AIO-like schemes. It's just a terminological thing. The PDP-10 operating systems even let you define your own page fault handlers, so you could do i/o with something like mmap and not get delayed in the cases where the page you wanted wasn't in memory. I guess that's even more asynchronous than AIO. From Lie.1296 at gmail.com Sun Mar 16 05:12:39 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 02:12:39 -0700 (PDT) Subject: find string in file References: Message-ID: On Mar 14, 8:25?pm, fminerv... at gmail.com wrote: > Hi friends !! > > I'm neophite about python, my target is to create a programa that > find ?a specific string in text file. > How can do it? > > Thanks > fel I'd recommend regular expression (import re) if the string you're searching is in a complex format (like all strings that starts with a dollar sign followed by an arbitrary number of numbers which might or might not contain commas every three number). If what you're searching is just simple queries (like searching where "Hello" appeared in the text you'd better use the string modules. as they're simpler to use and faster. From http Fri Mar 14 13:18:32 2008 From: http (Paul Rubin) Date: 14 Mar 2008 10:18:32 -0700 Subject: Thousand Seperator References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <7xiqzpjkbb.fsf@ruckus.brouhaha.com> ewanfisher at gmail.com writes: > 100 -> 100 > 1000 -> 1,000 > 1000000 -> 1,000,000 > -1000 -> -1,000 def sep(n): if n<0: return '-' + sep(-n) if n<1000: return str(n) return '%s,%03d' % (sep(n//1000), n%1000) From saluk64007 at gmail.com Wed Mar 12 23:50:26 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Wed, 12 Mar 2008 20:50:26 -0700 Subject: a Roguelike in Python In-Reply-To: <776b49ce-852d-43da-ac56-6fc3cdcaca92@u72g2000hsf.googlegroups.com> References: <776b49ce-852d-43da-ac56-6fc3cdcaca92@u72g2000hsf.googlegroups.com> Message-ID: On Wed, Mar 12, 2008 at 9:23 AM, Carl Banks wrote: > Even though it's typically used for graphical games, PyGame would be a > good way to make a cross-platform "text-mode" game. It should be > pretty straightforward to simulate a text mode terminal using a grid > of sprites. (There might even be some third-party text terminals out > there.) This is a cool technique, and also gives the game designer a lot of freedom in their representation. It can continue to look old school while also letting you have icons where they may be appropriate, or add an eye on your gridbug 'x' just for fun :) This technique was used in phoenix from one of the pyweek competitions: http://www.pyweek.org/e/Cursed/ By the way, that game emulates curses as well. If you go with pygame display only, you are losing some compatibility as well, as it won't run on textmode only systems. No roguelikes over ssh :( From rolf.oltmans at gmail.com Wed Mar 12 12:17:45 2008 From: rolf.oltmans at gmail.com (Oltmans) Date: Wed, 12 Mar 2008 09:17:45 -0700 (PDT) Subject: Unable to handle File Open dialog (using Pamie) Message-ID: <54766eca-9f83-4a4a-962f-d78d88aec7fa@e6g2000prf.googlegroups.com> Hi all, I'm new to Python and am automating few tasks using Pamie. Everything worked well until I had to handle the File Open Dialog. I mean I'm trying to automate the file upload process using Pamie. Basically I just want to automate the process of file upload. I want to automatically hit the Browse button and then enter 'C:\image1.jpg' in the File Name text field and then hit the Open button (all using Pamie, winguiauto or whatever would give me the solution :-) Here is my html ( file is stored in my PC at C:\\Test\Test.html ) and here is my source ie.navigate("C:\Test\Test.html") ie.buttonClick('upload') handle = winGuiAuto.findTopWindow(wantedText="Choose file") print 'handle ='+ str(handle) p=handlePopup('ChooseFile','&Open') p.enterTextAndClickControl(handle,('C:\image1.jpg','&Open')) p.run() now when I run the above program the Browse button gets clicked and File Open dialog pops up but 'c:\image1.jpg' (without quotes) is not entered in the File Name field and neither the Open button gets clicked. Also I get this error in the console -- Traceback (most recent call last): File "firsttest.py", line 26, in p.enterTextAndClickControl(handle,('C:\image1.jpg','&Open')) File "C:\Python25\lib\site-packages\cModalPopUp.py", line 113, in enterTextAn ClickControl wantedClass="Edit") File "C:\Python25\lib\site-packages\winGuiAuto.py", line 167, in findControl selectionFunction=selectionFunction) File "C:\Python25\lib\site-packages\winGuiAuto.py", line 235, in findControls return searchChildWindows(topHwnd) File "C:\Python25\lib\site-packages\winGuiAuto.py", line 213, in searchChildW ndows childWindows) TypeError: an integer is required -- I've searched Internet, searched usenet, scratched my head but nothing worked. Also, I tried joining the Pamie User group but I couldn't. So I will really appreciate your help/insights/ideas/hints/anythiing that can help me fix the problem. Thanks, Rolf From tn.pablo at gmail.com Tue Mar 25 12:27:58 2008 From: tn.pablo at gmail.com (ptn) Date: Tue, 25 Mar 2008 09:27:58 -0700 (PDT) Subject: Files, directories and imports - relative to the current directory only Message-ID: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> Hello, group. I can only read files and import modules that are in the same directory as the one my script is. Here is a test script (path.py): import os import uno # some module I wrote print list(os.walk('~/hacking/python')) f = open('~/read/foo.txt') print f.read() And here is the output: Traceback (most recent call last): File "path.py", line 2, in import uno ImportError: No module named uno If I comment that import, the output becomes this: [] Traceback (most recent call last): File "path.py", line 4, in f = open('~/read/foo.txt') IOError: [Errno 2] No such file or directory: '~/read/foo.txt' (Notice the empty list at the beginning, that would be the output of os.walk().) I have added this line to my .bashrc: export PYTHONPATH=$PYTHONPATH:~/hacking/python I thought that by doing so all the scripts found in that directory and all it's children would be available for import, but that doesn't seem to be the case. As for the other problems, I have no idea. So, what's wrong here? Maybe there's something I haven't set up? From mail at microcorp.co.za Sat Mar 29 06:43:22 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Mar 2008 12:43:22 +0200 Subject: Re; finding euclidean distance,better code? Message-ID: <001c01c8918e$48556a40$03000080@hendrik> On Saturday 29 March 2008 03:09:46 Steven D'Aprano wrote: > On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > > Gabriel Genellina wrote: > >> That's what I said in another paragraph. "sum of coordinates" is using > >> a different distance definition; it's the way you measure distance in a > >> city with square blocks. I don't know if the distance itself has a > >> name, but > > > > I think it is called Manhattan distance in reference of the walking > > distance from one point to another in this city. > > You know, there are other cities than Manhattan. Some of them even have > streets and blocks. Sorry about having to dispel your illusions, but - In Printed Circuit Board Layout jargon, the 'manhattan distance' is the sum of the distances along the orthogonal axes between two points on the board that should be connected. The sum of all such distances is an idealised minimum for the total track length on a double sided board, given that it were possible to lay all tracks with segments connected by vias, making strictly increasing progress in the desired direction, by laying x direction tracks on the one, and y direction tracks on the other side of the board without having to "backtrack" - i.e. having to "dodge around" obstacles, thereby adding "overshooting" segments of track. (A via is a through plated hole that connects copper traces or tracks on opposite sides of the board) So I have met the beast, but I have no concept of its origin, other than the mind numbing regularity of the layout of the suburb of the city after which it seems to be named - For all I know 'manhatten' could be a native american word that means "net". Have you noticed that when people say "Sorry.....but...." they are not normally sorry at all? :-) - Hendrik From frikker at gmail.com Tue Mar 4 18:31:09 2008 From: frikker at gmail.com (blaine) Date: Tue, 4 Mar 2008 15:31:09 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> <13sr22ii98uipc4@corp.supernews.com> Message-ID: > It looks like the fastest speed supported by python termios on > Linux is B460800 (uses a constant of 0x1004). If you look in > /usr/include/..., baud rates do go up to 921600 (which uses a > constant of 0x1007). > > Try using the appropriate constant from /usr/include/... (for > the target platform, of course). > > -- > Grant Edwards grante Yow! Please come home with > at me ... I have Tylenol!! > visi.com I want to thank you SO MUCH for all your help. Here are my issues that I overcame (sanity check): 1. Why did we have to use 0x1007, instead of 0x10007 that our grep command returns? 2. PySerial works beautifully. Thank you for the suggestion. What I had to do was add this to the PySerial source root in serialpostix.py, after the import termios: termios.B921600 = 0x1007 because PySerial looks for the actual baud rate in termios (via getattr()) which does not exist. PySerial actually defines the following baud rates, but termios does not handle it: #default values, may be overriden in subclasses that do not support all values BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600, 19200,38400,57600,115200,230400,460800,500000,576000,921600, 1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000) ... so now I can pass 921600 as a parameter to PySerial! :) So my next question is - I would like to contribute to the python source tree by updating termios.h to handle the higher baud rates by default. Is this a good opportunity for me to submit a patch? I've never done this before but have always been interested in doing so. Thanks again! Blaine From paul at boddie.org.uk Mon Mar 31 11:14:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 31 Mar 2008 08:14:23 -0700 (PDT) Subject: Licensing References: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> Message-ID: On 31 Mar, 09:36, Duncan Booth wrote: > > I don't have a printed copy, but Google Books has it (not sure which > edition I found) and page xix says: > > Given the nature of the cookbook, we wanted the recipes to be usable under > any circumstances where Python could be used. In other words, we wanted to > ensure completely unfettered use, in the same spirit as the Python license. > Unfortunately, the Python license cannot really be used to refer to > anything other than Python itself. As a compromise, we chose to use the > modified Berkeley license, which is considered the most liberal of > licenses. ... and then the license follows ... > > So, if the recipe is in the printed cookbook the licensing is clear > (primarily you must retain the copyright notice). The best advice I've found so far is the following: http://www.softwarefreedom.org/resources/2007/gpl-non-gpl-collaboration.html It spells out exactly what you have to do to satisfy the original licence and to uphold your own licence choice. It's also written by well-regarded legal people. Paul P.S. An older and more ambiguous conclusion on the topic can be found here: http://groups.google.com/group/linux.kernel/msg/4c8b3114c35df368 From timr at probo.com Wed Mar 5 02:49:13 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 05 Mar 2008 07:49:13 GMT Subject: Delete hidden files on unix References: Message-ID: loial wrote: > >How can I delete hidden files on unix with python, i.e I want to do >equivalent of > >rm .lock* What did you try? I'm curious to know what you tried that didn't work, because I can't think of any obvious solution to this that would not just work. You did try to solve this yourself before sending a message around the world, didn't you? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Thu Mar 6 07:35:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 10:35:38 -0200 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 10:10:47 -0200, Guillermo escribi?: > This is my first post here. I'm getting my feet wet with Python and I > need to know how can I check whether a variable is of type dictionary. > > Something like this: > > if isdict(a) then print "a is a dictionary" if isinstance(a, dict): ... But note that it's more common in Python to try to use it in the intended way, and catch the possible errors. Look for "duck typing" in this group, and the difference between "easier to ask forgiveness than permission" and "look before you leap". -- Gabriel Genellina From hajducko at gmail.com Fri Mar 28 05:39:25 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Fri, 28 Mar 2008 02:39:25 -0700 (PDT) Subject: Plugins accessing parent state References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> <653q99F2e37q8U1@mid.uni-berlin.de> Message-ID: On Mar 28, 1:58?am, "Diez B. Roggisch" wrote: > hajdu... at gmail.com schrieb: > > > > > Does anyone have some design ideas ( or can point me at the right > > design pattern, because I can't find it. ) for having a plugin being > > able to access a parent's state? > > > For example, let's say I have a class that receives some commands. > > When it gets a command, it checks which of the registered plugins > > deals with that command and passes the details of the command off to > > that plugin. ?So I'd end up with something like.. > > > result = plugin.do(msg_details) > > > Now, I want to write a plugin called "help" that loops through all the > > registered plugins and prints out their doc strings. ?If all my plugin > > is getting is the msg details, how is it supposed to get the list of > > available plugins from the calling class? > > > Or, for instance, let's say my class loads a configuration file that > > lists a set of admins who can enter commands. ?I want the plugins, if > > they so choose, ?to be able to test if the msg came from an admin, but > > again, I'm not passing the admin list into every plugin, it's just in > > my calling class. ?I could make the plugin specify an attribute for > > itself, like "admin_only" and test for that before I pass the command > > but what if certain parts of the plugin are to be restricted and > > others aren't, based on the details of the command sent? > > > Is this as simple as just passing the instance of my class to each > > plugin? ?It doesn't seem like the proper thing to do, because now the > > plugin class has the capability of accessing the whole bot's > > interface. > > Yes, it is simple as that. Of course you can choose *what* you pass, if > you want to restrict that - nobody forces you to pass the whole > plugin-manager, if that would expose properties/methods you wouldn't > want ther. > > But to be honest: you are thinking much to far there - after all, it's > all *your* code, and inside one interpreter. A real isolation isn't > available anyway. > > So just do what fullfills the functional requirements. > > diez Since I want to have a uniform call to all plugins, would it make sense to split out the attributes that I do want to share to a separate class and then simply create a new instance of that class and store it in the main class? For instance ... self.utilities = Utilities(self) ... plugin.do(msg,self.utilities) From solisgb at gmail.com Sun Mar 9 11:37:07 2008 From: solisgb at gmail.com (luis) Date: Sun, 9 Mar 2008 08:37:07 -0700 (PDT) Subject: unable to install gdal Message-ID: <15838144-b7a0-4d1b-98b3-fdfcfdb9a916@n75g2000hsh.googlegroups.com> Hi On Windows xp sp2 and python 2.4 Yesterday I running old versions of gdal, and I try to upgrade I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 I follow install's instructions from http://trac.osgeo.org/gdal/wiki/GdalOgrInPython, all is ok, I set path and path_data variables with correct values, but whe I run a script, an error raises from osgeo import ogr File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? import _ogr ImportError: DLL load failed: process not found Also I try with instructions from http://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gdalinstall.html I move _gdal.pyd (and the others *.pyd) from my Python installation's (C:\Python24\Lib\site-packages\osgeo) into my Python installation's DLLs folder (C:\Python24\DLLs). When I run the script the error message persists. Some help is welcome. From stef.mientki at gmail.com Tue Mar 11 21:07:41 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 12 Mar 2008 02:07:41 +0100 Subject: how to pass the workspace ? Message-ID: <47D72CDD.9000706@gmail.com> hello, I've GUI tree with drag and drop nodes, where each nodes contains a code snippet. Now I want to run one or more branches in that tree, so I enumerate over the nodes and have to run something like this: execfile ( node1 ) execfile ( node2 ) etc.. Now how do I pass the workspace created in node1, to node 2, etc ? thanks, Stef Mientki From duncan.booth at invalid.invalid Wed Mar 19 10:10:12 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Mar 2008 14:10:12 GMT Subject: Speaking Text References: Message-ID: David C. Ullrich wrote: > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? > (If it's there in Linux presumably it only works if there > happens to be a speech engine available...) Perhaps http://www.mindtrove.info/articles/pytts.html ? Or if all else fails Python can drive Microsoft's MSAGENT for speaking animated figures. From pmc411-usenet at yahoo.com Thu Mar 20 11:51:45 2008 From: pmc411-usenet at yahoo.com (Paulo da Costa) Date: Thu, 20 Mar 2008 15:51:45 GMT Subject: Can I run a python program from within emacs? In-Reply-To: <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: Jeff Schwab wrote: > jmDesktop wrote: >> On Mar 20, 11:21 am, Grant Edwards wrote: >>> On 2008-03-20, jmDesktop wrote: >>> >>>> Hi, I'm trying to learn Python. I using Aquamac an emac >>>> implementation with mac os x. I have a program. If I go to the >>>> command prompt and type pythong myprog.py, it works. Can the program >>>> be run from within the editor or is that not how development is done? >>>> I ask because I was using Visual Studio with C# and, if you're >>>> familiar, you just hit run and it works. On Python do I use the >>>> editor for editing only and then run the program from the command >>>> line? > > Sort of. Modern editors generally have support for building and running > your program directly from a toolbar button or textual command. I > personally use Vim with the toolbar disabled, running in a Terminal, and > run the program by first putting Vim in the background (^z). Modern editors like GNU Emacs show you a Python tab when you're editing a Python file that allows you to do various things with the code, just like Visual Studio, I don't know about "Aquamacs". > I believe Grant was suggesting that Emacs often serves a similar purpose > on Unix to what Visual Studio does on Windows, which seemed to be what > you were asking. When asking about Mac OS X here, you are likely to get > a lot of generic Unix responses. (Would it have been clearer if he had > just said "emacs?") There are several flavors, it's best to specify which one you mean. People who say Emacs often mean GNU Emacs. Paulo From ntv1534 at gmail.com Mon Mar 3 12:37:21 2008 From: ntv1534 at gmail.com (MooMaster) Date: Mon, 3 Mar 2008 09:37:21 -0800 (PST) Subject: Inheritance issue... Message-ID: I'm trying to use inheritance to create a simple binary tree, but it's not going so well... here's what I pull from the documentation for super() "super( type[, object-or-type]) Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes. A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg) " So here's what I do: class Node: def __init__(self, val=0, prnt = None): self.value = val self.parent = prnt class Tree(Node): def __init__(self, val=0): self.root = super(Tree, self).__init__(val) self.leftChild = None self.rightChild = None def addChild(self, value): if self.root == None: self.__init__(value) else: n = self.root while(n is not None): if(n.leftChild == None and n.rightChild == None): n.leftChild = Node(value, n) elif(n.rightChild == None): n.rightChild = Node(value, n) else: if(n.leftChild.leftChild is not None and n.leftChild.rightChild is not None): n = n.rightChild else: n = n.leftChild def printTree(self): if self.root == None: print "None" else: n = self.root print n.value while(n is not None): if(n.leftChild is None): print str(n.value) + "'s left child is None" elif(n.rightChild is None): print str(n.value) + "'s right child is None" else: if(n.leftChild.leftChild is not None and n.leftChild.rightChild is not None): n = n.rightChild else: n = n.leftChild def main(): play = Tree(1) play.addChild(2) play.addChild(3) play.addChild(4) play.addChild(5) play.printTree() if __name__ == "__main__": main() ...and here's what I get: Traceback (most recent call last): File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 53, in main() File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 45, in main play = Tree(1) File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 8, in __init__ self.root = super(Tree, self).__init__(val) TypeError: super() argument 1 must be type, not classobj Looks to me like the super(Tree, self)__init__(val) follows the example in the documentation, but I may be a witch. Anyone know why this doesn't work? From zedshaw at zedshaw.com Mon Mar 31 04:37:48 2008 From: zedshaw at zedshaw.com (Zed A. Shaw) Date: Mon, 31 Mar 2008 04:37:48 -0400 Subject: [ANN] Vellum 0.4 (it builds things, mostly books) Message-ID: <20080331043748.291ffa58.zedshaw@zedshaw.com> Hi All, I'd like to just announce that I've cranked out a fun little Python project named Vellum. It is an attempt at a Python make alternative written in about 200 lines of Python: http://www.zedshaw.com/projects/vellum/ It currently actually works, and can take a YAML or Python file as the description of the build, including namespaces, recipes from other files, and two samples for running nose and distutiles (respectively). I'm using it to automate most of my Python project builds and my website right now and it's doing great. The defining difference between it and other make-alikes is that each target is just a multi-line string, with different 3-char prefixes to determine how that line should be run: - >>> means it's Python, so run the python with exec. - <-- means eval a test and stop processing that target if False. - <<< means output some text. - --> means jump to another target, with an optional {} has of different options. - Nothing means it's a shell command, run it with os.system(). As the target is processed, each line is passed in as a string % options so you can do replacement on settings you've made. So, you can do this: <<< My name is %(name)s And if options: name: "fred", then it says it's name is fred. I'm pretty sure it's turing complete. :-) All information about the project, getting at the bzr, several sample files, and even the whole source to the core of the project are on the above page. Since I'm a total Python newbie, I'd love any advice about my code I can get. Thanks much. -- Zed A. Shaw - Hate: http://savingtheinternetwithhate.com/ - Good: http://www.zedshaw.com/ - Evil: http://yearofevil.com/ From jeffober at gmail.com Tue Mar 25 07:54:48 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 25 Mar 2008 04:54:48 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> Rather than use Foo.bar(), use this syntax to call methods of the super class: super(ParentClass, self).method() From castironpi at gmail.com Wed Mar 26 21:06:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 18:06:04 -0700 (PDT) Subject: Why does python behave so? (removing list items) References: <2f626a4d-1db2-4b10-bf5c-e4197a3db811@z38g2000hsc.googlegroups.com> Message-ID: <1d2288e4-225b-4027-a3b8-e046828aff82@m36g2000hse.googlegroups.com> On Mar 26, 5:28?pm, bearophileH... at lycos.com wrote: > Micha? Bentkowski: > > > Why does python create a reference here, not just copy the variable? > > I think to increase performance, in memory used and running time (and > to have a very uniform way of managing objects). > > Bye, > bearophile A variable is a name-value pair. It's undefined outside of one-to- ones therein. You have two names. Do they refer to the same object. There is no such thing as the "primitive contents" of -any- standard object. From timr at probo.com Fri Mar 21 00:43:10 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 21 Mar 2008 04:43:10 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: Sean DiZazzo wrote: > >The overall idea is to be able to tell if a file has finished being >placed in a directory without any control over what is putting it >there. There is simply no way to do this on Windows that works in the general case. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jgardner at jonathangardner.net Fri Mar 14 12:17:51 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 14 Mar 2008 09:17:51 -0700 (PDT) Subject: %x unsigned? References: <87skytbbbc.fsf@mulj.homelinux.net> Message-ID: <9f2f667e-bc91-4826-81f6-32fd73d189d6@s19g2000prg.googlegroups.com> On Mar 14, 8:00?am, Hrvoje Niksic wrote: > The %x conversion specifier is documented inhttp://docs.python.org/lib/typesseq-strings.htmlas "Unsigned > hexadecimal (lowercase)." ?What does "unsigned" refer to? > > >>> '0x%x' % 10 > '0xa' Somewhat unrelated, but have you seen the # modifier? >>> '%#x' % 10 '0xa' From jjlofaro at yahoo.com.au Wed Mar 26 05:47:11 2008 From: jjlofaro at yahoo.com.au (Jeff Lofaro) Date: Wed, 26 Mar 2008 02:47:11 -0700 (PDT) Subject: Time module is not behaving. Message-ID: <604727.52623.qm@web52209.mail.re2.yahoo.com> Yep that does it. Thanks Gary. ----- Original Message ---- From: Gary Herron To: jjlofaro Cc: python-list at python.org Sent: Wednesday, 26 March, 2008 2:49:55 AM Subject: Re: Time module is not behaving. jjlofaro wrote: > Hi > > I'm just getting myself going again on Python and would appreciate any > help. > > My install of Python seems to have some difficulty loading and using > the time module in a script. Strange thing is that if I start another > instance of Python I can type in my program manually/interactively and > it works. > > The version of Python I am using is... > * > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2* > > Installed on a Ubuntu 7.10 workstation. > > Here's my little program.... > > *jeff at office:~/tmp$ more < time.py > > import time > * Right there is the problem. Your program, named time.py, is hiding the Python supplied module. So that import of time is finding and re-importing itself. Rename your script to something that won't shadow a Python library module. Gary Herron > *print time.time()* > > And this is what happens when I run it.... > > *jeff at office:~/tmp$ python time.py > > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > Error in sys.excepthook: > Traceback (most recent call last): > File "/var/lib/python-support/python2.5/apport_python_hook.py", line > 38, in apport_excepthook > from apport.fileutils import likely_packaged > File "/var/lib/python-support/python2.5/apport/__init__.py", line 1, > in > from apport.report import Report > File "/var/lib/python-support/python2.5/apport/report.py", line 14, > in > import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys > File "/usr/lib/python2.5/urllib.py", line 28, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > Original exception was: > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > jeff at office:~/tmp$ * > > Any hints or tips appreciated. > Jeff. Get the name you always wanted with the new y7mail email address. www.yahoo7.com.au/y7mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Mar 31 23:28:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 20:28:08 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> <80d1731d-a3c6-4fce-81fd-9c3f3537e59b@d21g2000prf.googlegroups.com> Message-ID: <5386cf08-c155-4fbb-8373-dbbb9829a9e7@m3g2000hsc.googlegroups.com> On Mar 31, 9:27?pm, George Sakkis wrote: > On Mar 31, 8:51 pm, castiro... at gmail.com wrote: > > On Mar 31, 7:14 pm, 7stud wrote: > > > > On Mar 31, 5:31 pm, castiro... at gmail.com wrote: > > > > > Can you have a Python object stored entirely on disk? > > > > import cPickle as cp > > > > class Dog(object): > > > ? ? def __init__(self, name): > > > ? ? ? ? self.name = name > > > > d = Dog("Spot") > > > > f = open("data.txt", "w") > > > cp.dump(d, f) > > > f.close() > > > > f = open("data.txt") > > > stored_obj = cp.load(f) > > > print stored_obj.name > > > > --output:-- > > > Spot > > >>> import pickle > > >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps > > ? ? Pickler(f, protocol).dump(obj) > > ? File "C:\Programs\Python\lib\pickle.py", line 221, in dump > > ? ? self.save(obj) > > ? File "C:\Programs\Python\lib\pickle.py", line 283, in save > > ? ? f(self, obj) # Call unbound method with explicit self > > ? File "C:\Programs\Python\lib\pickle.py", line 697, in save_global > > ? ? (obj, module, name)) > > pickle.PicklingError: Can't pickle : it's not > > found as __ > > main__.None > > http://docs.python.org/lib/node317.html- Hide quoted text - What's involved in Can you have a Python object stored entirely on disk? No process to access: changes to contents written back. From stefan_ml at behnel.de Mon Mar 24 11:36:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Mar 2008 16:36:39 +0100 Subject: Element Tree Help In-Reply-To: References: Message-ID: <47E7CA87.7090901@behnel.de> Robert Rawlins wrote: > Hello Guys,I have little to no experiance with element tree and I'm > struggling to find a way to parse the details from the XML document > (attached) into my application. Essentialy I'm looking to take the > following document and turn it into a dict of tuples, each dict element > defines a datasource with the key to the element being the 'name' which is > defined in the XML and then the value of the pair is a tuple which contains > the details of the datasource, like the host and port etc.I've attached a > copy of the example XML to this email.Can anyone offer some advice on how > to get started with this? I've spent a little time looking over the > documentation of element tree and have struggled to break the ice and parse > this document.Thanks guys,Robert Given this document: a name localhost 3306 database1 someusername somepassword another name localhost 3306 database2 itsusername andthepassword I would do something like this: d = {} for event, element in ET.iterparse("thefile.xml"): if element.tag == "datasource": d[element.find("name")] = tuple([ el.text for el in element ]) Stefan From tjreedy at udel.edu Wed Mar 19 00:47:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2008 00:47:39 -0400 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org><87r6e9zu4p.fsf@benfinney.id.au><646uapF2at163U1@mid.uni-berlin.de><13tst1388cp67d8@corp.supernews.com><47de9f6c$0$2657$9b622d9e@news.freenet.de> Message-ID: "Duncan Booth" wrote in message news:Xns9A65624FD1932duncanbooth at 127.0.0.1... | Stargaming wrote: | | > On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: | > | >> For the answer I actually want each asterisk substitutes for exactly one | >> character. | > | > Played around a bit and found that one: | > | > Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) | > [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 | > Type "help", "copyright", "credits" or "license" for more information. | >>>> a = 1 | >>>> b = 1//1 | >>>> if a is b: print('yes!') | > ... | >>>> b | > 1 | >>>> type(b) | > | | I've had a look to see why this happens: long division (and in Python 3 all | integers are longs) allocates a new long to hold the result of the division | so it will never use one of the preallocated 'small int' values. | | That makes sense so far as it goes, but I'm slightly suprised if it isn't | worth an extra check somewhere for numerator fitting in a machine int and | shortcutting the long division. I submitted the following to the issue tracker http://bugs.python.org/issue2417 Python 3.0a3 (r30a3:61161, Mar 1 2008, 22:51:17) [MSC v.1500 32 bit (Intel)] on win32 >>> a,b=1,1//1 >>> a is b False IDLE 3.0a3 >>> a,b=1,1//1 >>> a is b True ditto for 2.5.2 interpreter On c.l.p, Duncan Booth wrote I've had a look to see why this happens: long division (and in Python 3 all integers are longs) allocates a new long to hold the result of the division so it will never use one of the preallocated 'small int' values. That maybe explains the change from 2.5 but not the difference from IDLE. More important, the small int checks are present with the other operations: >>> 1*1 is 1 True >>> 1+1 is 2 True >>> 1-1 is 0 True >>> 1**1 is 1 True so the omission with // is plausibly a bug. Terry Jan Reedy From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 19:39:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 00:39:28 -0000 Subject: Nested phrases [was Re: Want - but cannot get - a nested class to inherit from outer class] References: <18b456bf-bc3d-45f6-af92-369e01e0f426@o77g2000hsf.googlegroups.com> Message-ID: <13t3o20lbtipica@corp.supernews.com> On Fri, 07 Mar 2008 14:26:25 -0800, castironpi wrote: > Humans have enormous "mental stacks"--- the stacks the contexts the > speakers speak in push things they're hearing on to. This is not true. Human beings have extremely shallow mental stacks, limited by short-term memory. Most people are capable of keeping seven, plus or minus two, items in short term memory at once. Any more than that and they are subject to fading away or being over-written. Grammatically, it doesn't take many levels to confuse most people, and even the best and brightest can't keep track of hundreds of levels, let alone "enormous" numbers. At least, not unless you consider five to be enormous. Steven Pinker's "The Language Instinct" has some excellent examples of such "top heavy" phases, such as: He gave the girl that he met in New York while visiting his parents for ten days around Christmas and New Year's the candy. She saw the matter that had caused her so much anxiety in former years when she was employed as an efficiency expert by the company through. Fortunately the English grammar, which is very strict about word order (Pinker describes it as "tyrannical") allows alternate forms that are easier for our shallow stacks to deal with: He gave the candy to the girl that he met in New York while visiting his parents for ten days around Christmas and New Year's. She saw the matter through that had caused her so much anxiety in former years when she was employed as an efficiency expert by the company through. Pinker also describes situations where the words can be grouped into phrases as you go, and so are easy to comprehend: Remarkable is the rapidity of the motion of the wing of the hummingbird. and a counter-example of a perfectly grammatical sentence, with only THREE levels, which is all but unintelligible: The rapidity that the motion that the wing that the hummingbird has has has is remarkable. These nested "onion sentences" are exceedingly difficult for the human brain to parse. In fact, I'm betting that at least 90% of people will, on first reading, will question whether it could possibly be grammatically correct. -- Steven From sjmachin at lexicon.net Wed Mar 19 07:09:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 04:09:27 -0700 (PDT) Subject: a beginner, beginners question References: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Message-ID: On Mar 19, 9:40 pm, klaus wrote: > Hello, > > I'm trying to learn python programming and so far so good. However when > trying to master the oop side I ran into a small problem. > > I think I've done everything ok as outlined below. But I just don't > understand why the `method' of `class' example isn't printing any of the > variables that I have set earlier on ? Could someone please explain to me > what it is I am doing wrong ? > > Thank you so much ! > > #!/usr/bin/env python > > class example: What book or online tutorial are using that doesn't lead you to express that as: class Example(object): ?? > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > def method(self): > print "method ... :" > print self.foo > print self.bar > > if __name__ == "__main__": > obj = example To see what is happening here, do: print repr(obj) You need to CALL the class: obj = example() > obj.foo = "var1" > obj.bar = "var2" > obj.method This expression produces the method itself, then throws it away. You need to CALL the method: obj.method() HTH, John From duncan.booth at invalid.invalid Thu Mar 13 05:50:07 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Mar 2008 09:50:07 GMT Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <7x3aqvf9o2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Terry Reedy" writes: >> | I don't see what's so inefficient about it necessarily. >> >> The key function is called once per list item, for n calls total. >> The comparision function is called once per comparision. There are >> at least n-1 such calls and typically something on the order of n * >> lg2(n) calls. > > Right. Depending on the application, calling the comparison function > lg(n) times may be faster than calling the key function once. > > Example: you want to sort a list of strings case-independently, each > string containing a few pages worth of text. There are 10000 strings, > each maybe 10000 chars long. Then (untested): > > x.sort(xs, key=lower) > > makes a copy of each of the 10000 strings, makes 10000 tuples, sorts, > then releases the temporary strings and tuples. At least 100 > megabytes of memory allocated and 100 million chars copied, even > though any give pair of strings will usually differ somewhere in the > first few characters and there's no need to look past those. Not tuples actually, there's a special sortwrapper type which is used. This is slightly better as it stops the comparison leaking through to the original values without having to store an index value. As Dan has pointed out, for those rare cases where it actually is better to use cmp than key you can easily create a wrapper. The only change is that you now have to work at using cmp instead of it being the first thing you think of. So here you could use his wrapper and your comparison function together: x.sort(key=cmp_key(xcmp)) I'd agree though that the comparison wrapper should be reasonably well publicised: I'd remembered that there was an easy way to implement cmp in terms of key but not what it was. From arnodel at googlemail.com Sat Mar 22 13:07:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 10:07:59 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> Message-ID: <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> On Mar 22, 4:38?pm, Zentrader wrote: > > if ('one', 'two') are in f: ... > > "are" gives me an error in Python 2.5 with a "from future import *" > statement included. ?What version and platform are you running. ?Also, > the docs don't mention it.http://docs.python.org/ref/keywords.html That's because you have to do: from bearophile import musings HTH -- Arnaud From brnstrmrs at gmail.com Mon Mar 17 16:00:50 2008 From: brnstrmrs at gmail.com (brnstrmrs) Date: Mon, 17 Mar 2008 13:00:50 -0700 (PDT) Subject: struct unpack Message-ID: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> If I run: testValue = '\x02\x00' junk = struct.unpack('h', testValue) Everything works but If I run testValue = raw_input("Enter Binary Code..:") inputting at the console '\x02\x00' junk = struct.unpack('h', testValue) It errors out with Traceback (most recent call last): File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in junk = struct.unpack('h', testValue) File "struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 2 any ideas? From sjmachin at lexicon.net Thu Mar 20 03:07:34 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Mar 2008 00:07:34 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: <3797c5dd-8d10-4298-af05-fd06440119ce@c19g2000prf.googlegroups.com> On Mar 20, 12:50?pm, "Gabriel Genellina" wrote: > En Wed, 19 Mar 2008 20:16:36 -0300, John Machin ? > escribi?: > > > On Mar 20, 9:14 am, sturlamolden wrote: > >> Is a Python set implemented using a hash table? > > > What don't you understand about the comments in the first two > > screenfuls of Objects/setobject.c? > > That comment was unnecesarily harsh, don't you think? > No, otherwise I wouldn't have made it. From gabriel.rossetti at mydeskfriend.com Wed Mar 26 04:35:07 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Wed, 26 Mar 2008 09:35:07 +0100 Subject: Strange loop behavior Message-ID: <47EA0ABB.3030804@mydeskfriend.com> Hello, I wrote a program that reads data from a file and puts it in a string, the problem is that it loops infinitely and that's not wanted, here is the code : d = repr(f.read(DEFAULT_BUFFER_SIZE)) while d != "": file_str.write(d) d = repr(f.read(DEFAULT_BUFFER_SIZE)) I also tried writing the while's condition like so : len(d) > 0, but that doesn't change anything. I tried step-by-step debugging using PyDev(eclipse plugin) and I noticed this, once the while was read once, it is never re-read, basically, the looping does happen, but just in between the two lines in the loop's body/block, it never goes on the while and thus never verifies the condition and thus loops forever. I had been using psyco (a sort of JIT for python) and so I uninstalled it and restarted eclipse and I still get the same thing. This looks like some bug, but I may be wrong, does anybody understand what's going on here? Thanks, Gabriel PS And yes I checked, the "d" variable is en empty string at some point, so the looping should stop. -- Arimaz SA Av. du 24 Janvier 11 Ateliers de la Ville de Renens, Atelier 5 1020 Renens, Switzerland www.mydeskfriend.com Mob: +41-(0)79-539-0069 From davids at evertech.com.au Thu Mar 13 00:25:12 2008 From: davids at evertech.com.au (David S) Date: Thu, 13 Mar 2008 04:25:12 GMT Subject: Handling global variables (Newbie) Message-ID: Hi, I have an error occurring at self.build_root = os.path.abspath(os.path.split(__file__)[0]) The error states 'NameError: global name '__file__' is not defined' In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get defined? Yours, David From castironpi at gmail.com Mon Mar 31 23:48:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 20:48:35 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> <80d1731d-a3c6-4fce-81fd-9c3f3537e59b@d21g2000prf.googlegroups.com> <5386cf08-c155-4fbb-8373-dbbb9829a9e7@m3g2000hsc.googlegroups.com> Message-ID: <3c27b270-e593-4f2a-b881-68126319760c@8g2000hsu.googlegroups.com> On Mar 31, 10:28?pm, castiro... at gmail.com wrote: > On Mar 31, 9:27?pm, George Sakkis wrote: > > > > > > > On Mar 31, 8:51 pm, castiro... at gmail.com wrote: > > > On Mar 31, 7:14 pm, 7stud wrote: > > > > > On Mar 31, 5:31 pm, castiro... at gmail.com wrote: > > > > > > Can you have a Python object stored entirely on disk? > > > > > import cPickle as cp > > > > > class Dog(object): > > > > ? ? def __init__(self, name): > > > > ? ? ? ? self.name = name > > > > > d = Dog("Spot") > > > > > f = open("data.txt", "w") > > > > cp.dump(d, f) > > > > f.close() > > > > > f = open("data.txt") > > > > stored_obj = cp.load(f) > > > > print stored_obj.name > > > > > --output:-- > > > > Spot > > > >>> import pickle > > > >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) > > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps > > > ? ? Pickler(f, protocol).dump(obj) > > > ? File "C:\Programs\Python\lib\pickle.py", line 221, in dump > > > ? ? self.save(obj) > > > ? File "C:\Programs\Python\lib\pickle.py", line 283, in save > > > ? ? f(self, obj) # Call unbound method with explicit self > > > ? File "C:\Programs\Python\lib\pickle.py", line 697, in save_global > > > ? ? (obj, module, name)) > > > pickle.PicklingError: Can't pickle : it's not > > > found as __ > > > main__.None > > >http://docs.python.org/lib/node317.html-Hide quoted text - > > What's involved in Can you have a Python object stored entirely on > disk? ?No process to access: changes to contents written back. We do have, but on Windows, file is not locked to multi-tasking, shelve. But why don't we have types in there, or non-string primitives in keys? >>> c= shelve.open( 'temp', 'c' ) >>> c['0']= 'a' >>> c.sync() >>> del c >>> c= shelve.open( 'temp', 'c' ) >>> c['0'] 'a' >>> c['0'].append( 0 ) >>> c['0'] [] And why don't primitive mutations modify contents of disk? A metaquestion. >>> c['0']= type('None',(),{}) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\shelve.py", line 114, in __setitem__ p.dump(value) File "C:\Programs\Python\lib\pickle.py", line 221, in dump self.save(obj) File "C:\Programs\Python\lib\pickle.py", line 283, in save f(self, obj) # Call unbound method with explicit self File "C:\Programs\Python\lib\pickle.py", line 697, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle : it's not found as __ main__.None From nospam at nospam.com Fri Mar 14 02:32:11 2008 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 14 Mar 2008 07:32:11 +0100 Subject: Monitoring SSHd and web servers? Message-ID: Hello I'd like to monitor connections to a remote SSH and web server. Does someone have some code handy that would try to connect every 5mn, and print an error if the script can't connect? Thank you. From castironpi at gmail.com Fri Mar 21 09:58:16 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 06:58:16 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> Message-ID: <555af81e-9d3e-4ab3-a6f3-43d02a8b4acd@m3g2000hsc.googlegroups.com> On Mar 21, 8:14?am, castiro... at gmail.com wrote: > On Mar 20, 9:28?am, "Jerry Hill" wrote: > > On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano > > wrote: > > > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > > > > ?> suppose > > > ?> origsz=(400,300) > > > ?> i want to divide the origsize by 2.5 so i can resize to (160,120) > > > > ?> scale=2.5 > > > ?> how can i get the newsz? > > > ?> obviously origsz/2.5 won't work ?.. > > > > ?newsz = (origsz[0]/scale, origsz[1]/scale) > > > That works fine for a 2-tuple, but might get unwieldy for larger > > tuples, or if you don't know the length until runtime. ?A more general > > solution might use a generator expression, like this: > > > newsz = tuple(x/scale for x in origsz) > > You want to perform a uniform call on the elements of a collection. > +1 compose. By the way. -And sorry for interrupting the OP's time- I feel that control flow objects could be a really powerful addition to a language. Compose a for-loop. From marko at pacujo.net Thu Mar 13 16:58:07 2008 From: marko at pacujo.net (Marko Rauhamaa) Date: 13 Mar 2008 22:58:07 +0200 Subject: subprocess.Popen pipeline bug? References: <026208f0-cd70-4f6a-bfe5-9f8f09a5b0f6@n58g2000hsf.googlegroups.com> Message-ID: bryanjugglercryptographer at yahoo.com: > Not sure. I think what's happening is that the second cat subprocess > never gets EOF on its stdin, because there are still processes with an > open file descriptor for the other end of the pipe. You are right. However, the close_fds technique seems a bit heavy-handed. Well, that's what you get when you try to combine fork and exec into a single call. Marko -- Marko Rauhamaa mailto:marko at pacujo.net http://pacujo.net/marko/ From ggpolo at gmail.com Wed Mar 26 06:05:16 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 26 Mar 2008 07:05:16 -0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: <47EA1604.4070905@gmail.com> References: <47EA1604.4070905@gmail.com> Message-ID: 2008/3/26, Alex9968 : > Hi all, > > I use Tkinter's Pack widget geometry manager (I really prefer it over > using visual GUI designers), so my question is which other GUI toolkits > have similar functionality. The geometry manager isn't related to using GUI designers tools at all. And each toolkit has it's own way to do the things, wxPython uses sizers, PyGtk uses containers. > > Secondly, I like the detailed widget borders configuration possible in > Tkinter, which can be used to tweak GUI look, and wonder if other > toolkits support it. With Tkinter's case, I like the resulting (tweaked) > look in Windows, but I'm afraid it can be quite different (and ugly) on > other platforms. You sure can, but differently. > > (The reason I ever consider moving from Tkinter is some inconveniences, > involving for example window scrolling, plus its smaller amount of > widgets compared to some other toolkits, plus its (rumored) ugly look on > certain environments. I will not necessary change the toolkit, but I > have to consider it) > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC. For now you could try using Tile extension, and update to Tk 8.5. If you don't want to use extensions, then you will have to wait or change the toolkit for now. > Could anyone with experience in different toolkits help, please > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bearophileHUGS at lycos.com Sun Mar 16 10:32:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Mar 2008 07:32:13 -0700 (PDT) Subject: Types, Cython, program readability Message-ID: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> It seems the development of Cython is going very well, quite differently from the dead-looking Pyrex. Hopefully Cython will become more user-friendly too (Pyrex is far from being user-friendly for Windows users, it doesn't even contain a compiler, I think. The ShedSkin Windows installer contains an old but working MinGW, and this is positive). It seems Cython is going to become an efficient and general purpose language after all, with optional static typing (its purpose: mostly for speed), and it may even gain some kind of macros soon. So it may even end replacing Python itself in some situations where running efficiency is important, and where Psyco can't be used or isn't enough. Apparently unrelated: few days ago I was translating a 200-lines long program from Python to D (D is mostly statically typed, like C++, Java) for personal use. That Python program was without unit tests, comments, docstrings, documentation, etc. So finding the types of all the variables required some time. So I have fed the whole program to ShedSkin, and in 20 seconds on my old PC it has produced a Python program with full type annotations (as comments on each line of code), that later I have translated quickly to D. In such "blind" situations (that are often enough in some scripts I find around) I think a statically typed program (without type inference) can be more readable than a Python program, because even if the programmer is super-lazy types must be present (otherwise the program doesn't compile), and with the variable names they give me some information that's absent (well, it's less easy to extract. ShedSkin is often able to extract it) from the Python code. The (little) point of this post: sometimes (when the programmer is quite lazy) statically typed code is more "readable" than Python code. Bye, bearophile From grante at visi.com Sat Mar 1 23:09:14 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 04:09:14 -0000 Subject: Telnet versus telnetlib References: <8acce230-4acf-43fe-9cb7-e4e50350381e@s13g2000prd.googlegroups.com> Message-ID: <13ska3aju6cse5b@corp.supernews.com> On 2008-03-01, Gabriel Genellina wrote: > En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis > escribi?: > >> When I do an analogous process using telnetlib, I get no debug output, >> and most importantly, when I send the XML file to the host, I get no >> printed page. Unfortunately, I do not have access to the host to do >> troubleshooting there, so I have to "feel" my way around. Any >> suggestions on what might be going wrong? >> >> In [12]: tn.write(""" >> ....: > \ is the quote character. You have to duplicate it "C:\\labels..." or use > a raw string r""" <64b3e29d-ce9d-42f9-a285-5001a31d9448@d62g2000hsf.googlegroups.com> Message-ID: Hi all, Thank you so much for all your help :) I really appreciate it. I discovered that my problem was because of my firewall and everything works now :) Regards, Gowri From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 07:23:41 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 11:23:41 -0000 Subject: MySQL DB-Api Message-ID: <008601c8836a$5c5fbf90$151f3eb0$@rawlins@thinkbluemedia.co.uk> Good morning list. I'm in the process of learning my way around the DB-API module for MySQL and wanted to come and get some advice on how you all manage your database connections and cursors. Within my applications I'll have many classes which access the database, I'm wondering to what level I should extract the database connection. Should I create a new database connection and close it for every method which calls the database? Should I create the connection/cursor to the DB when I construct the class and place the cursor in the self scope? Or should I create a application wide connection/cursor to the database and inject the cursor into all the classes which require it? All classes within the application access the same database so at the moment I'm leaning towards creating an application wide connection and cursor and then injecting it into classes which require database access, does that sound like a fair plan? I'm just interested to learn how you are managing this. Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From nejtak... Sun Mar 9 17:26:59 2008 From: nejtak... (Troels Thomsen) Date: Sun, 9 Mar 2008 22:26:59 +0100 Subject: 1.5.2 and functools or similar Message-ID: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Hello, I am writing a simple delayed-call mechanism , that is causing a bit of headache. Works like this: myPrint(s) print "..." + s myTimer.add(myPrint , "hello" , 15) This means that the myprint function is called in 15 seconds with the parameter "hello". The housekeeping of these timers is called by the main loop of the "os" This works well but i would like to be able to use it with any number of parameters Functools is not a part of the 1.5.2+ python that I am running on (embedded device), so i tried to pass the parameters as a tuple like this myTimer.add(myAdder , (3,6) , 15) and the housekeeping function would then call the function like this def updateTimers() for timerItm in timerTable: ... .... .... timerItm.func(*timerItm.parameters) Works well on python 2.5 but not on 1.5.2 (?) Current solution is to have default parameters None for the add function def add( func , timeout , param1 = None , param2 = None) And the update function then checks if parameters is specified def updateTimers() for timerItm in timerTable: ... .... .... # ugly part : if timerItm.param1 is not None and timerItm.param2 is not None: timerItm.func(timerItm.param1, timerItm.param2) # two parameters elif ...... timerItm.func(timerItm.param1) # one parameter else timerItm.func() # no parameters This has the implication that I can not call a function with the parameter None if I wanted to. (not a huge problem) Right now it works quite well with up to two parameters, it covers 99% of usage. If I need to call a function with more parameters, i can always write a wrapper function for it. Wondering if anyone had some sugestions ? By the way, is it bad style to check for object identity instead of value "None". What aboutt integers ? if value is 0: .. I guess it is implementation specific / could change in future versions ? Thx, Troels From steve at holdenweb.com Mon Mar 31 00:44:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 00:44:57 -0400 Subject: Odd behaviour with list comprehension In-Reply-To: References: <4fbfbb8f0802291901s5ed7e0b4ua3e77ad46aa53bb7@mail.gmail.com> <871w6vkq3z.fsf@micah.cowan.name> Message-ID: Terry Reedy wrote: > "Steve Holden" wrote in message [...] > | Well, the fact that the bound variable in the list comprehension does > | indeed remain outside the construct is simply the result of an > | over-zealous wish to emulate for loop semantics. The original reasoning, > | IIRC, as that since a for loop left its bound variable at the last used > | value, so should a list comprehension. > | > | This was quickly recognized as a mistake, but unfortunately not quickly > | enough. As it was felt that some people might already have relied on > | that behavior, it was retained in the interests of preserving backwards > | compatibility. > > But it will not be retained in 3.0, as I understand it. > So best to not exploit the deprecated behavior. > Correct. The compatibility break provided by 3.0 allows the developers to drop this historical grunge. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stugots at qwest.net Tue Mar 18 12:04:40 2008 From: stugots at qwest.net (John DeRosa) Date: Tue, 18 Mar 2008 09:04:40 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> Message-ID: <0rpvt3pls55b0uiaqfvnubarm2afjtpgh8@4ax.com> On Mon, 17 Mar 2008 14:36:29 -0500, "J. Clifford Dyer" wrote: >Note to speakers: do not say > > x, y = tee(foo) > >say > > from itertools import tee > x, y = tee(foo) > >or better (for pedagogical purposes) > > import itertools > x, y = itertools.tee(foo) > I was scratching my head over tee() also, in the session where I heard it. Were you in the "iterators II" session also? I've used itertools a bit, but never tee(), and so when I thumbed through my copy of PER I thought, ahh, I've skimmed over but never registered the importance of that little bugger before... That was one of the more interesting sessions to me. John From bharathv6.project at gmail.com Tue Mar 4 09:41:08 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Tue, 4 Mar 2008 20:11:08 +0530 Subject: http server performance Message-ID: <2613171a0803040641u1b48dfcai96c9172fd093c4d7@mail.gmail.com> hi, my project involves lot of I/O over the network.. one part of my project involves a server(http) which is listening on the port for many client . this sever fetches an image from the web and and send it to clients .... and many clients will request the server concurrently .. to implement concurrent serving to clients i used threaded http server like this class HTTPServer(SocketServer.ThreadingMixIn,BaseHTTPServer.HTTPServer): pass class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): print "received connection from: ",self.client_address image=image_retreive() #where image retreive is a function that retrieves image from the web and works fine self.send_response(200) self.send_header("Content-type",format) self.send_header("Content-Length",len(image_data)) self.end_headers() self.request.sendall(image_data) httpd = HTTPServer(('',port_number), RequestHandler) httpd.serve_forever() this code worked fine but this performance was very bad ... it workes fine if the clients requested for small n medium size images as the server sends the response immediately and also workes fine if one client is requesting a large image (obviously server takes time to send response as it takes time to fetch the image from the web ) and other clients concurrently request for small and medium images these clients will be served immediately even if the other client is waiting but problem crops up when 2 clients concurrently request for an large image .. while these two clients are waiting for the response fromthe server . The server doesn't accept any other client request ... i can see this as i am printing the address of the client that connects with server in the 1st line of get method of the request handler if two clients concurrently request for an large image and only two clients address gets printed that means only 2 clients receives connection to the server even if other clients are requesting the server at the same time and other servers are served only after the those 2 server releases the connection or get the response . that means server servers only 2 clients at a time .this is very undesirable as even if 3rd client is requesting for very small image and 2 clients are waiting for large image .. 3rd client won't receive the response until those 2 clients are served . to make thing worst my server should serve 10 to 15 clients concurrently to solve this i did some searching and found about cherrypy and twisted also implemented my server in cherrypy like this from cherrypy import wsgiserver def image_httpserver_app(environ, start_response): print >>sys.stdout,"received connection from: (%s : %s ) \nthe image url is: %s " % (environ["REMOTE_ADDR"],environ["REMOTE_PORT"],environ["QUERY_STRING"]) status = '200 OK' response_headers = [('Content-type',format)] image=image_retreive() response_headers = [("Content-Length",`len(image_data)`)] start_response(status, response_headers) return [image_data] mappings=[('/', image_httpserver_app)] wsgi_apps = mappings server = wsgiserver.CherryPyWSGIServer(('localhost', 8888), wsgi_apps, server_name='localhost',numthreads=20) if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop() this didn't solve the problem at all .. same thing is happening only 2 clients is served at a time ..even if no of threads is assigned to 20 .. i have did lot of searching and reading .. and hoping to find a solution ..can anyone make it easier for me i have heard of twisted deffered object .. will it solved the problem ? if not pls suggest me alternative.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 8 17:14:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 08 Mar 2008 20:14:18 -0200 Subject: SV: Quit-command not quiting References: <63d2efF271u6hU1@mid.individual.net> <63d5v1F23vm9fU1@mid.individual.net> Message-ID: En Fri, 07 Mar 2008 13:56:45 -0200, K Viltersten escribi?: >>> The window itself vanishes if i click the >>> cross in the upper-right corner but pressing >>> the quit-button only makes it "pressed". >>> Then, the program freezes. >> >> How did you run it? From inside IDLE? IDLE itself is written >> using Tk, and I think that your mainloop interferes with the >> one inside it. If you run your program from the command line >> it should work fine. > > I press F5 while in the editor window. Is there a way to run the > program without going to the console window? > Perhaps i'm just making things unneccesarily complicated > and Python IS supposed to be run from console window? No, use IDLE if you prefer, or any other editor/IDE. But in your case there is an unfortunate coupling between IDLE and your script. Fix: change the quit method as suggested in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/92bee52a3e2a325e/ def quit(self): self.master.destroy() This is OK if used on the top level widget on the application (your Demo class, for instance). A more general solution: def quit(self): parent = self while parent.winfo_class() != 'Tk': if parent.master is None: break; parent = parent.master else: parent.destroy() (from https://sourceforge.net/tracker/index.php?func=detail&aid=661324&group_id=9579&atid=109579 ) This appears to work fine. But the loop, as written, could exit without calling destroy() on anything; perhaps some other people knowing better how Tkinter and Tk work could improve it or confirm it's fine as it is. -- Gabriel Genellina From phd at phd.pp.ru Mon Mar 10 07:37:46 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 10 Mar 2008 14:37:46 +0300 Subject: SQLObject 0.9.5 Message-ID: <20080310113746.GB14369@phd.pp.ru> Hello! I'm pleased to announce the 0.9.5, a minor bug fix release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.5 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.4 ---------------- Bug Fixes ~~~~~~~~~ * Fixed a minor bug in SQLiteConnection.columnsFromSchema() - set dbName. * A bug in delColumn() that removes all properties is fixed by recreating properties. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From steve at REMOVE-THIS-cybersource.com.au Thu Mar 13 17:22:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 21:22:30 -0000 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <87skyvuhpo.fsf@rudin.co.uk> Message-ID: <13tj6omdip82f13@corp.supernews.com> On Thu, 13 Mar 2008 08:54:43 +0000, Paul Rudin wrote: >> Whatever python has for a calling convention, it is close enough that >> naming it "call by reference" gives people a reasonable idea of what is >> going on. > > Quite. The thing is not to get hung up with the label - but to > understand what actually happens. Agreed. And I think the best way to do that is to use the same terms that other languages use to get very different behaviour indeed. "Python is call by reference, but this doesn't work like call by reference in all the other languages I've used: def negate(n): n = -n x = 2 negate(x) assert x == -2 Is this a bug, or is Python actually call by value?" And now comes the explanations that Python is actually call by value, but the values being copied are *pointers* (ignoring Jython, IronPython and PyPy); or that Python is really call by reference, but different "things" (it's never quite clear what exactly) happen depending on whether the arguments are mutable or immutable; or that if you define reference broadly enough, everything is a reference; or that if you define value broadly enough, everything is a value; or if schools would just stop teaching kiddies C and start teaching them Lisp, call by reference semantics would be understood in a different way, or or or or... And thus, by insisting that there are two and only two calling conventions, no matter how many different kinds of calling behaviour actually exist, we ensure that we'll be having this same *&$%^*# argument when Python 4000 comes out. And for that we can all be grateful. -- Steven From carsten at uniqsys.com Sun Mar 23 21:18:31 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 02:18:31 +0100 Subject: Does python hate cathy? In-Reply-To: References: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> Message-ID: <1206321511.3365.28.camel@localhost.localdomain> On Sun, 2008-03-23 at 20:05 -0500, Michael Wieher wrote: > is that farnarkeling about in a __del__ method is *not* a good > idea. > > Ok that having been said, is accessing an unbound variable of a class > and using it to coordinate between instances of that class common > practice? I'm not sure what you mean by "accessing an unbound variable" means in the context of this thread, or any context for that matter. Nothing of the kind is happening in the OP's example. What's happening is that a class attribute is initialized, incremented, and decremented. Using class attributes is common practice. The problem, as I explained in my previous post, is that the class attribute is looked up via a global name of the class, and that name may or may not have disappeared in a puff of logic by the time the instance's __del__ method is run in the VM shutdown sequence. -- Carsten Haese http://informixdb.sourceforge.net From smartpawn at gmail.com Wed Mar 19 03:43:34 2008 From: smartpawn at gmail.com (Deepak Rokade) Date: Wed, 19 Mar 2008 13:13:34 +0530 Subject: Using threads in python is safe ? In-Reply-To: References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Message-ID: <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> Thanks all for removing confusion about GIL, one more question; If jobs to be processed by threds is I/O bound would multithreading help python to improve speed of application ? Since I read that " multithreading is not a good strategy to improve speed of python application." On Mon, Mar 17, 2008 at 7:00 AM, Benjamin wrote: > On Mar 16, 3:40 pm, "Gabriel Genellina" > wrote: > > En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade > > escribi?: > > > > > I want to use therads in my application. Going through the docs , I > read > > > about GIL. > > > Now I am confused whether using threads in python is safe or not. > > > > > One thing I know that if I am accessing global variables in two or > more > > > threads I need to synchronize them > > > using locking or such mechanism so that only one thread access them at > a > > > time. > > > > Yes, altough some operations are known to be atomic so you don't need a > > lock in that cases. I think there is a list in the wiki somewhere > http://wiki.python.org/moinor perhaps at the effbot's site > http://www.effbot.org > Even for atomic operations, you should lock, though. That is not > consistent over different Python implementations and is not always > going to be in same in CPython. > > > > > 1. In order to support multi-threaded Python programs, there's a > global > > > lock that must be held > > > by the current thread before it can safely access Python objects. > > > Does this lock need to be held by python application script > expliciltly > > > before accessing any python object or > > > interpreter takes acre of it ? > > > > No, the interpreter takes care of it. The GIL is a concern for those > > writing extensions using the Python API. > > > > > 2. Does multithreaded python script need to held lock before calling > any > > > blocking I/O call? > > > Or one should not worry about GIL while using python threads if job to > be > > > processed by thread does not call > > > any global variables and thread unsafe Python/C extension ? > > > > Python code should not worry about the GIL. The problem would be, a > > callback written in Python for a not-thread-aware extension that had > > released the GIL. > > > > -- > > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanx & Regards, Deepak Rokade Do what u Enjoy & Enjoy what u Do........... -------------- next part -------------- An HTML attachment was scrubbed... URL: From craigm3604 at gmail.com Sun Mar 23 17:24:52 2008 From: craigm3604 at gmail.com (Craig) Date: Sun, 23 Mar 2008 14:24:52 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> Message-ID: <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> On Mar 23, 4:48 pm, Dennis Lee Bieber wrote: > On Sat, 22 Mar 2008 19:05:31 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > I got back exactly what I expected for TypeDef, but SecKey and PriKey > > were what I initialized them to , not what should have been returned. > > > Do you mean that I should change any string that is expected to be > > changed by the dll to a create_string_buffer type (LPSTR) instead of a > > windll.oleaut32.SysAllocStringByteLen type (LPBSTR) and then simply > > list it in the call instead of byref, as I did with TypeDef? > > Based upon my interpretation of the C prototype and the ctypes > documentation (sample code), that IS what I expect... (I didn't expect > it to work with the TypeDef field though...) > > There are two ways in which a C language function call can handle > returning string data. (Let's see if I remember how to code C; been 6 > years) > > char pre_alloc_buffer[] = "This is a fixed nul-terminated buffer space"; > char *dynamic_buffer; /* this is an uninitialized pointer to char */ > char *dynamic_too; > > The function can either modify a buffer passed in: > > int func1(char *bfr); > > or it can allocate a buffer internally and return that either as a > function result, or via a reference to a pointer variable > > char *func2(char *bfr[]); /* ugh, my memory is fading */ > /* If I did this right, it is a pointer to array of character */ > > res = func1(pre_alloc_buffer); > or > res = func1(&pre_alloc_buffer[0]); /* long/explicit form */ > > The address of the start of the buffer space is passed, and func1 > performs its magic in the pre-allocated buffer. > > dynamic_too = func2(&dynamic_buffer); > > Here, we pass the address of just a pointer variable (which > currently points to garbage). func2 is expected to perform something > wherein IT allocates memory and that memory address is what is put into > the argument/return > > ... > *bfr = malloc(...); > return (bfr); > > Based on my interpretation of the prototypes, I'd have expected the > two BSTR to be the func1 style passing of a buffer, but the last > argument /might/ have been the second func2 style. > > I really can't be more definitive; I've not used ctypes -- only read > the documentation; the only DLLs I've had to use were covered by the > win32 extension library which comes as part of the ActiveState Python > installation. > > > > > Can it really be that simple? > > > As for the structure: > > class VSTATS(Structure): > > _fields_ = [ > > ("nrecords", c_long), > > ("gps_used", c_short), > > ("gps_unused", c_short), > > ("max_key_len", c_short), > > ("grp_size", c_long), > > ("init_alloc", c_short), > > ("cr_opts", c_short), > > ("free_prop_area", c_short), > > ("format", c_void_p), > > ("reserved", c_void_p) > > ] > > vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) > > can I just use a create_string_buffer (LPSTR) and parse things up via > > substrings after the call returns? > > It may be possible, though the library seems to have gone out of its > way to mask such efforts from the user. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ This dll was designed to be used from either C or Visual Basic 6. I have the declare statements for VB6, if that helps. Based on the results I have so far (and I have tried MANY permutations like trying to use the LPSTR for SecKey and PriKey which are returned as is TypeDef), it looks like SecKey and PriKey are being used as data instead of pointers. For this, I try: LPSTR = c_char_p VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = create_string_buffer(41) SecKey.raw = "1234567890123456789012345678901234567890" PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) and I get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 158, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) WindowsError: exception: access violation reading 0x3433322D I notice that SecKey.raw starts with "1234" and the exception address is 0x3433322D, which is "432-". And, changing to: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, LPSTR] PriKey = create_string_buffer(41) PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) I then get: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 159, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) WindowsError: exception: access violation reading 0x4443423D I notice that PriKey.raw starts with "ABCD" and the exception address is 0x4443423D, which is "DBC=". So, I can see that there is data where pointers are expected. I just don't see how to pass those pointers. When they were passed as LPBSTR (and oleaut32.SysAllocString), the calls "worked" in that they didn't get exceptions and they did return the correct record, but the SecKey and PriKey fields were not correct, and they were BSTR (pointers). I did get the VmxInfo to work by: VSTATS_fmt = "lhhhlhhhlll" VsamInfo = create_string_buffer(36) temp = unpack(VSTATS_fmt, VsamInfo.raw) vStats = VSTATS(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7]) Any idea on how to jump the last hurdle on VmxGet? This is the very last thing that is stopping my project. From john.deas at gmail.com Sun Mar 9 09:06:04 2008 From: john.deas at gmail.com (John Deas) Date: Sun, 9 Mar 2008 06:06:04 -0700 (PDT) Subject: parralel downloads References: Message-ID: <50047985-ed16-46cb-a933-8afddac6a056@y77g2000hsy.googlegroups.com> On Mar 9, 1:25 pm, John Deas wrote: > On Mar 8, 5:47 pm, Gary Herron wrote: > > > > > poof65 wrote: > > > For your problem you have to use threads. > > > Not at all true. Thread provide one way to solve this, but another is > > the select function. For this simple case, select() may (or may not) be > > easier to write. Pseudo-code would look something like this: > > > openSockets = list of sockets one per download file: > > while openSockets: > > readySockets = select(openSockets ...) # Identifies sockets with > > data to be read > > for each s in readSockets: > > read from s and do whatever with the data > > if s is at EOF: close and remove s from openSockets > > > That's it. Far easier than threads. > > > Gary Herron > > > > You can have more information here. > > >http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > > > >> Hi, > > > >> I would like to write a python script that will download a list of > > >> files (mainly mp3s) from Internet. For this, I thought to use urllib, > > >> with > > > >> urlopen("myUrl").read() and then writing the resulting string to a > > >> file > > > >> my problem is that I would like to download several files at the time. > > >> As I have not much experience in programming, could you point me the > > >> easier ways to do this in python ? > > > >> Thanks, > > > >> JD > > >> -- > > >> http://mail.python.org/mailman/listinfo/python-list > > Thank you both for your help. Threads are working for me. However, a > new problem for me is that the url I want to download are in an xml > file (I want to download podcasts), and is not the same as the file > downloaded: > > http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2... > > will be redirected to download: > > http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 > > is there a way, knowing the first url to get the second at runtime in > my script ? Found it: geturl() does the job From kaushikbarat at gmail.com Sat Mar 15 05:10:24 2008 From: kaushikbarat at gmail.com (kaush) Date: Sat, 15 Mar 2008 02:10:24 -0700 (PDT) Subject: ImportError while Embedding python in C Message-ID: <0e568278-c5b3-40d3-a172-7d1701510f50@s19g2000prg.googlegroups.com> Hi All, I have a simple python script saved to "test.py" as import os import base64 def Testfunction(): print "Hello World" return Testfunction() I am trying to invoke this from a C program as follows int main(int argc, char* argv[]) { Py_Initialize(); PyObject* main_module = PyImport_AddModule("__main__"); PyObject* main_dict = PyModule_GetDict(main_module); FILE* file_1 = fopen(TestFile, "r"); PyRun_AnyFile(file_1, TestFile); Py_Finalize(); return 0; } This fails with the error Traceback (most recent call last): File "/home/kaushik/shadowFs/test.py", line 4, in import base64 File "/usr/local/lib/python2.5/base64.py", line 9, in import struct File "/usr/local/lib/python2.5/struct.py", line 30, in from _struct import Struct, error ImportError: /usr/local/lib/python2.5/lib-dynload/_struct.so: undefined symbol: PyExc_TypeError I am able to run test.py successfully from the shell. What am i missing in importing the base64 library? Thanks, Kaushik From castironpi at gmail.com Sat Mar 29 10:11:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 07:11:19 -0700 (PDT) Subject: Help me on function definition References: Message-ID: <9d932e66-ac5f-43ad-a06c-cd3f5186b47e@e67g2000hsa.googlegroups.com> On Mar 29, 4:18?am, Roel Schroeven wrote: > aeneng schreef: > > > > > > > Hello everyone, > > > I am just starting to use python in numerical cacluation. > > I need you to help me to see what's wrong with the following piece of > > codes, which computes the cross product of two vectors and returns > > the result. u and v are two 3x1 matrix. > > > when I import the function, error message show like this > >>>> import cross > > Traceback (most recent call last): > > ? File "", line 1, in ? > > ? File "cross.py", line 8 > > ? ? ppp2=u[2]*v[0]-u[0]*v[2] > > ? ? ^ > > SyntaxError: invalid syntax > > > WHAT IS WRONG WITH MY CODE? > > > I appreciate your help. > > > ##here is the function definition. > > ##cross.py## > > def cross(u,v) > > ? ? """input two vectors u and v in 3-D space, ? ? > > ? ? ? ?output a cross product of vector w, in column or in row > > accordingly.""" > > ? ? ppp1,ppp2,ppp3=0.0,0.0,0.0 > > You forgot the : after def cross(u, v) No; directional is only signed and unsigned. There's a laptop on my computer. From http Thu Mar 13 01:57:33 2008 From: http (Paul Rubin) Date: 12 Mar 2008 22:57:33 -0700 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: <7x3aqvf9o2.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > | I don't see what's so inefficient about it necessarily. > > The key function is called once per list item, for n calls total. The > comparision function is called once per comparision. There are at least > n-1 such calls and typically something on the order of n * lg2(n) calls. Right. Depending on the application, calling the comparison function lg(n) times may be faster than calling the key function once. Example: you want to sort a list of strings case-independently, each string containing a few pages worth of text. There are 10000 strings, each maybe 10000 chars long. Then (untested): x.sort(xs, key=lower) makes a copy of each of the 10000 strings, makes 10000 tuples, sorts, then releases the temporary strings and tuples. At least 100 megabytes of memory allocated and 100 million chars copied, even though any give pair of strings will usually differ somewhere in the first few characters and there's no need to look past those. from string import lower from operator import eq from itertools import * def xcmp(a,b): for x,y in izip(a,b)): c = cmp(x.lower() y.lower()) if c: return c return 0 x.sort(xcmp) runs the comparison function about 14000 times, looking at only a few bytes on most of the calls, and using only a small constant amount of auxiliary storage, and is likely to be much faster than all that copying. Hmm, there is a slight problem with xcmp-- it will fail if a is a prefix of b. That's fixable but anyway it still makes its point as written. From castironpi at gmail.com Tue Mar 4 21:31:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 18:31:11 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: On Mar 4, 7:06?pm, Tommy Grav wrote: > On Mar 4, 2008, at 4:53 PM, Jeff Schwab wrote: > > > What does "SV" in the subject mean? > > SV = "Svar" is the Norwegian word for Reply. > > Cheers > ? ?Tommy It is also the name of my lockermate in grade school. "So, Svar, how 'bout them posters?" From http Sun Mar 9 19:35:07 2008 From: http (Paul Rubin) Date: 09 Mar 2008 16:35:07 -0700 Subject: 1.5.2 and functools or similar References: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Message-ID: <7xbq5nqxn8.fsf@ruckus.brouhaha.com> "Troels Thomsen" writes: > timerItm.func(*timerItm.parameters) > > Works well on python 2.5 but not on 1.5.2 (?) I think in 1.5.2 the *args notation wasn't present and you had to say: apply(timerItm.func, timerItm.parameters) From python at bdurham.com Mon Mar 10 11:27:06 2008 From: python at bdurham.com (Malcolm Greene) Date: Mon, 10 Mar 2008 11:27:06 -0400 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) In-Reply-To: <47D54F11.4020508@behnel.de> References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <1205162826.18146.1241560441@webmail.messagingengine.com> Stefan, > My personal experience with wxPython has its ups and downs. Specifically when it comes to crashes, I wouldn't bet my life on it. (but then, the OP I'm new to Python and getting ready to build a small client based application intended to run on Windows and Linux. I was planning on using wxPython until I saw your comment above. Any suggestions on an alternative Python client-side GUI library (pyQT ?) or tips on where I can find out more about wxPython/wxWidget problems? Thank you, Malcolm From zerty.david at gmail.com Sun Mar 30 16:07:46 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:07:46 -0300 Subject: Error Raised But dont know what it means In-Reply-To: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> References: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> Message-ID: <5dc598e30803301307g20d9494ekf140387361c31968@mail.gmail.com> Here is the code: This one raises the error: def criaLista(self): self.listbox.Clear() for dupla in self.duplas: self.listbox.Append(dupla.__str__()) This one works well but doesn't raises error dupla1 = Duplas("2422", "2455") dupla2 = Duplas("454", "15") list = [] list.append(dupla1) list.append(dupla2) erros = ErrorMgr() erros.geraErro("1", "erro idiota", 2.2) dic = {1:dupla1, 2:dupla2} a = Arquivos("batata.txt") a.saveFile(list, erros, dic) a.openFile() lista = a.getListaDuplas() e = a.getErrorsManager() d = a.getDicDuplas() for i in lista: print i print d[1] On Sun, Mar 30, 2008 at 5:03 PM, David Anderson wrote: > Well, I'm dealing with files in Pickle, I'm saving at the file a List of > Objects from the same Class, When I try to retrive this information and try > to iterate over them this error is raised: > TypeError: 'instancemethod' object is not iterable > > But if I just print the method I get the 'real thing' what's the problem? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Mar 28 12:17:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Mar 2008 17:17:44 +0100 Subject: threads and extension module initialization In-Reply-To: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: <654k1kF2e8bnuU1@mid.uni-berlin.de> pianomaestro at gmail.com schrieb: > I have an extension module that gets initialized multiple > times because I am using threads. > > How can this module access global state (not per-thread state) ? > It needs to create a singleton. The question is very unclear. If you are after *not* initializing your module concurrently, why don't you just do it *once* before the threads are started? alternatively, you need to govern the initialization-code with a mutex - or anything similar. Diez From stefan_ml at behnel.de Sun Mar 23 12:51:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Mar 2008 17:51:21 +0100 Subject: Issues with XMLTreeBuilder in cElementTree and ElementTree In-Reply-To: <5d820787-e27d-4ae2-8b2b-b82af8ce67cf@p25g2000hsf.googlegroups.com> References: <5d820787-e27d-4ae2-8b2b-b82af8ce67cf@p25g2000hsf.googlegroups.com> Message-ID: <47E68A89.3020900@behnel.de> Michael Becker wrote: > Secondly, I found a potential issue with the cElementTree module. My > understanding (which could be incorrect) of python C modules is that > they should work the same as the python versions but be more > efficient. The XMLTreeBuilder class in cElementTree doesn't seem to be > using the same parser as that in ElementTree. The following code > illustrates this issue: > >>>> import xml.etree.cElementTree >>>> t1=xml.etree.cElementTree.XMLTreeBuilder() >>>> t1._parser.ordered_attributes = 1 > Traceback (most recent call last): > File "", line 1, in > AttributeError: _parser >>>> import xml.etree.ElementTree >>>> t1=xml.etree.ElementTree.XMLTreeBuilder() >>>> t1._parser.ordered_attributes = 1 Mind the underscore. You are using a non-public interface here. Don't expect other implementations to support that. Stefan From mail at microcorp.co.za Sat Mar 29 07:14:46 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Mar 2008 13:14:46 +0200 Subject: Serial port error statistics - any comparable data? Message-ID: <001b01c8918e$323b74c0$03000080@hendrik> Hi, I have been doing some tests on a device that we are thinking of incorporating into a product, and I have seen that reception on a serial port at 115200 baud over about six metres of RS-232 cable makes mistakes, to the order of 125 lines with errors in them out of approximately 18.4 million lines of 65 or so chars - about one errored line in 147000, or one error character in 95 million. The PC that is making the errors is a 64 bit dual core AMD machine running at 2 Gig, and I am running stock standard Open Suse 10.3 with the supplied Python 2.5. What kind of bothers me is the nature of the errors - I seem to get only missing characters, as if an interrupt was missed. There are no munged characters as one would expect if the errors were bit related. Has anyone else seen anything like this, and am I worrying needlessly? I realise that my production protocols will easily handle this almost non existent level of error - but if this were in microcontroller code that I had written myself, I would suspect that I was spending too long in some critical section of code. - Hendrik From pradiprai at gmail.com Mon Mar 31 06:27:25 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 15:57:25 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Hi All, I have upgraded python v2.5.2 from python v2.4.3. The upgradation results into following error: "Python C API version mismatch for module dbi: This Python has API version 1013, module dbi has version 1012." Please suggest, how to resolve this error to proceed further. Regards, Pradeep Rai -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Fri Mar 14 08:20:45 2008 From: DustanGroups at gmail.com (Dustan) Date: Fri, 14 Mar 2008 05:20:45 -0700 (PDT) Subject: This actually works. References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> Message-ID: On Mar 13, 6:19 pm, "Dotan Cohen" wrote: > On 14/03/2008, Dustan wrote: > > > you.screw() > > Ah, you are pushing sex pills. > > > self.thank(God, encapsulation) > > And bibles? Interesting combination. > > > not self.want_to_know(you.screw.func_code) > > Unsubscribe? I know better... > > Dotan Cohen > > http://what-is-what.comhttp://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? SyntaxError: invalid syntax From misceverything at gmail.com Fri Mar 28 15:40:01 2008 From: misceverything at gmail.com (misceverything at gmail.com) Date: Fri, 28 Mar 2008 12:40:01 -0700 (PDT) Subject: Finding Full Path to Process EXE Message-ID: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Hello, I would like to write a script that would enumerate all running processes and return the full path to the EXE of each running process. However, I can't seem to find any good info on how to do this..any help is greatly appreciated. Thanks. T From siona at chiark.greenend.org.uk Wed Mar 5 07:23:24 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 Mar 2008 12:23:24 +0000 (GMT) Subject: popening a process in a specific working directory References: Message-ID: Michael Torrie wrote: >I'm currently using popen2.Popen4. Is there a way to properly specify a >particular working directory when launching a process in python? Switch to using subprocess.Popen and specify the cwd argument. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From neilcrighton at gmail.com Tue Mar 11 16:43:32 2008 From: neilcrighton at gmail.com (neilcrighton at gmail.com) Date: Tue, 11 Mar 2008 13:43:32 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: Sorry my initial post was muddled. Let me try again. I've got a zipped archive that I can extract files from with my standard archive unzipping program, 7-zip. I'd like to extract the files in python via the zipfile module. However, when I extract the file from the archive with ZipFile.read(), it isn't the same as the 7- zip-extracted file. For text files, the zipfile-extracted version has '\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't tried comparing binary files via the two extraction methods yet. Regarding the code I posted; I was writing it from memory, and made a mistake. I didn't use: z = zipfile.ZipFile(open('foo.zip', 'r')) I used this: z = zipfile.ZipFile('foo.zip') But Duncan's comment was useful, as I generally only ever work with text files, and I didn't realise you have to use 'rb' or 'wb' options when reading and writing binary files. To answer John's questions - I was calling '\r' a newline. I should have said carriage return. I'm not sure what operating system the original zip file was created on. I didn't fiddle with the extracted file contents, other than replacing '\r' with ''. I wrote out all the files with open('outputfile','w') - I seems that I should have been using 'wb' when writing out the binary files. Thanks for the quick responses - any ideas why the zipfile-extracted files and 7-zip-extracted files are different? On Mar 10, 9:37 pm, John Machin wrote: > On Mar 10, 11:14 pm, Duncan Booth > wrote: > > > > > "Neil Crighton" wrote: > > > I'm using the zipfile library to read a zip file in Windows, and it > > > seems to be adding too many newlines to extracted files. I've found > > > that for extracted text-encoded files, removing all instances of '\r' > > > in the extracted file seems to fix the problem, but I can't find an > > > easy solution for binary files. > > > > The code I'm using is something like: > > > > from zipfile import Zipfile > > > z = Zipfile(open('zippedfile.zip')) > > > extractedfile = z.read('filename_in_zippedfile') > > > > I'm using Python version 2.5. Has anyone else had this problem > > > before, or know how to fix it? > > > > Thanks, > > > Zip files aren't text. Try opening the zipfile file in binary mode: > > > open('zippedfile.zip', 'rb') > > Good pickup, but that indicates that the OP may have *TWO* problems, > the first of which is not posting the code that was actually executed. > > If the OP actually executed the code that he posted, it is highly > likely to have died in a hole long before it got to the z.read() > stage, e.g. > > >>> import zipfile > >>> z = zipfile.ZipFile(open('foo.zip')) > > Traceback (most recent call last): > File "", line 1, in > File "C:\python25\lib\zipfile.py", line 346, in __init__ > self._GetContents() > File "C:\python25\lib\zipfile.py", line 366, in _GetContents > self._RealGetContents() > File "C:\python25\lib\zipfile.py", line 404, in _RealGetContents > centdir = struct.unpack(structCentralDir, centdir) > File "C:\python25\lib\struct.py", line 87, in unpack > return o.unpack(s) > struct.error: unpack requires a string argument of length 46 > > >>> z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK > >>> z = zipfile.ZipFile('foo.zip', 'r') # OK > > If it somehow made it through the open stage, it surely would have > blown up at the read stage, when trying to decompress a contained > file. > > Cheers, > John From gagsl-py2 at yahoo.com.ar Mon Mar 17 13:51:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 14:51:27 -0300 Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> <9192affb-3a3f-4558-909b-d9734c1b1ad2@u10g2000prn.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 14:22:31 -0300, hellt escribi?: > On 17 ???, 15:48, "Gabriel Genellina" wrote: >> En Mon, 17 Mar 2008 08:56:26 -0200, hellt >> escribi?: >> >> > i have a problem with this modules py2exe + pywinauto + sendkeys used >> > together. >> > pywinauto uses sendkeys when performs TypeKeys function. > when i include sendkeys to my package's list i have an error posted > below: > > "No module named SendKeys" Does your script actually work *without* py2exe? SendKeys is a separate package that you have to download and install separately. -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 06:25:09 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 12:25:09 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <659845F2e56g7U2@mid.individual.net> Lie wrote: > Ah yes, that is also used (I completely forgot about that one, my > math's aren't that sharp anymore) and I think it's used more > frequently than ><. Where did you read that (I mean, which country)? I've never seen this sign in any german or english book on mathematics/physics/engineering I saw. > but my argument was that no math book use != or <> (except in math > for programmers). That's true. Personally, I don't ever use "a!=b" in favor of "not a==b". Regards, Bj?rn -- BOFH excuse #282: High altitude condensation from U.S.A.F prototype aircraft has contaminated the primary subnet mask. Turn off your computer for 9 days to avoid damaging it. From http Sat Mar 29 05:25:03 2008 From: http (Paul Rubin) Date: 29 Mar 2008 02:25:03 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> Message-ID: <7xzlshkhlc.fsf@ruckus.brouhaha.com> Hrvoje Niksic writes: > Note that I said "*file* input/output". Twisted and asyncore are > about asynchronous socket programming that polls over nonblocking file > descriptors such as found in socket programming, not about wrapping > aio(3) and the equivalent Windows APIs. aio is also used for sockets, while twisted and asyncore use select or something similar. That is asynchronous but in a different sense of the word. See also: http://www.kegel.com/c10k.html From tmp1 at viltersten.com Mon Mar 10 00:20:28 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Mon, 10 Mar 2008 05:20:28 +0100 Subject: SV: SV: Changing the size of a Button In-Reply-To: References: <63ifhtF277va7U1@mid.individual.net> <63iokhF284p4hU1@mid.individual.net> Message-ID: <63jq9qF26sreoU1@mid.individual.net> >> What i wish to do is to affect the size >> of the button but not due to change of >> text but due to resize of the frame it >> resides in. > > This is done by the layout manager, too: > > import Tkinter as tk > > root = tk.Tk() > button = tk.Button(root, text="42") > button.pack(fill=tk.BOTH, expand=True) > root.mainloop() > > Alternatively, with a grid layout: > > button.grid(row=0, column=0, sticky="nsew") > root.rowconfigure(0, weight=1) > root.columnconfigure(0, weight=1) Ah, great! I'll try that right away. After breakfast, of course! Thanks! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From aboudouvas at panafonet.gr Thu Mar 27 07:59:44 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 04:59:44 -0700 (PDT) Subject: Psyco alternative Message-ID: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> Hi, it seems that Psyco's author will not port it for the upcoming Python 3000 release :( So, for us who use it we will continue to use CPython 2.5.x version for some time to come. Is there an alternative to Psyco so i can have a look at ? Thanks in advance. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 07:41:20 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 13:41:20 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Message-ID: <47cfe65d$0$9590$426a74cc@news.free.fr> Sam a ?crit : > Hello > > if type(a) is dict: > print "a is a dictionnary!" class MyDict(dict): pass a = MyDict() type(a) is dict => False From grante at visi.com Wed Mar 5 15:38:21 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 20:38:21 -0000 Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: <13su15t266dimc2@corp.supernews.com> On 2008-03-05, Jeff.Goldfinkle at gmail.com wrote: > Is there a simple way to twiddle the bits of a float? In particular, I > would like to round my float to the n most significant bits. > > For example - 0.123 in binary is 0.000111111 > Rounding to 4 bits I get 0.0001. > > I can pack and unpack a float into a long > e.g. > struct.unpack('I',struct.pack('f',0.123))[0] > but then I'm not sure how to work with the resulting long. > > Any suggestions? Just use the bitwise and/or/not operators: & | ~ -- Grant Edwards grante Yow! Half a mind is a at terrible thing to waste! visi.com From bbxx789_05ss at yahoo.com Sun Mar 2 08:57:49 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 2 Mar 2008 05:57:49 -0800 (PST) Subject: tcp References: Message-ID: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> On Mar 2, 6:09?am, Gif wrote: > i have this small script which after some router configurations works. > > ########################################################## > > #! /usr/bin/python > import socket > > HOST = '' > PORT = 1515 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.bind((HOST, PORT)) > s.listen(1) > conn, addr = s.accept() > conn.send('HTTP/1.1 200 OK\r\n') > conn.send('Content-Type: text/html\r\n') > conn.send('Server: test/1.0\r\n\r\n') > conn.send('test') > s.close() > > ########################################################## > > as you see it listens to 1515 until a connection is established and > then it accepts it... > the problem is that when it accepts the connection it sends those > strings and exits, but then it exits the program. i want it to listen > to 1515 then accept a connection, send.. and then listen to the port > again and again until new connections are found. > > i've been struggling with try..except,while and all kinds of loops but > always new erros pop up, or it overflows. while True: conn, addr = s.accept() ... From modelnine at modelnine.org Wed Mar 26 13:31:42 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 26 Mar 2008 18:31:42 +0100 Subject: Some notes on a high-performance Python application. In-Reply-To: <47ea78a5$0$36353$742ec2ed@news.sonic.net> References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: <200803261831.43109.modelnine@modelnine.org> Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: > ... > > Using MySQL as a queueing engine across multiple servers is unusual, > but it works well. It has the nice feature that the queue ordering > can be anything you can write in a SELECT statement. So we put "fair > queueing" in the rating scheduler; multiple requests from the same IP > address compete with each other, not with those from other IP addresses. > So no one site can use up all the rating capacity. > > ... > > Does anyone else architect their systems like this? A Xen(tm) management system I've written at least shares this aspect in that the RPC subsystem for communication between the frontend and the backends is basically a (MySQL) database table which is regularily queried by all backends that work on VHosts to change the state (in the form of a command) according to what the user specifies in the (Web-)UI. FWIW, the system is based on SQLObject and CherryPy, doing most of the parallel tasks threaded from a main process (because the largest part of the backends is dealing with I/O from subprocesses [waiting for them to complete]), which is different from what you do. CherryPy is also deployed with the threading server. -- Heiko Wundram From riccardocirello at gmail.com Tue Mar 25 12:19:56 2008 From: riccardocirello at gmail.com (cuordileone) Date: Tue, 25 Mar 2008 09:19:56 -0700 (PDT) Subject: Outlook 2003 and Python References: <2pidnTOUdc03jHTanZ2dnUVZ_uqvnZ2d@comcast.com> Message-ID: On Mar 25, 3:52?pm, Larry Bates wrote: > cuordileone wrote: > > Good Day. > > > I woul like to ask you if it is possible to make a program in python > > that move the email messages that I had received in outlook 2003, to a > > specific folder, accoding to the sender's name: > > > Es: mar... at martin.com -->> folder Martin. > > > Thanks. > > > Riccardo. > > You could, but it is much easier to just use built in tools (from Outlook > help): > > Automatically move messages from a certain person > Select a message from the person whose messages you want to automatically move. > On the Tools menu, click Organize. > In the second bulleted item, click the options you want. To choose a folder, > click the arrow next to the Into list. > Click Create. > Note ?To create more complex rules for organizing items, you can also use the > Rules and Alerts dialog box on the Tools menu. > > -Larry Thanks a lot, Larry From gandalf at shopzeus.com Fri Mar 21 04:54:34 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 21 Mar 2008 09:54:34 +0100 Subject: eval and unicode In-Reply-To: <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E377CA.10301@shopzeus.com> Hi Jonathan, I think I made it too complicated and I did not concentrate on the question. I could write answers to your post, but I'm going to explain it formally: >>> s = '\xdb' # This is a byte, without encoding specified. >>> s.decode('latin1') u'\xdb' # The above byte decoded in latin1 encoding >>> s.decode('latin2') u'\u0170' # The same byte decoded in latin2 encoding >>> expr = 'u"' + s + '"' # Create an expression for eval >>> expr 'u"\xdb"' # expr is not a unicode string - it is a binary string and it has no encoding assigned. >>> print repr(eval(expr)) # Eval it u'\xdb' # What? Why it was decoded as 'latin1'? Why not 'latin2'? Why not 'ascii'? >>> eval( "# -*- coding: latin2 -*-\n" + expr) u'\u0170' # You can specify the encoding for eval, that is cool. I hope it is clear now. Inside eval, an unicode object was created from a binary string. I just discovered that PEP 0263 can be used to specify source encoding for eval. But still there is a problem: eval should not assume that the expression is in any particular encoding. When it sees something like '\xdb' then it should raise a SyntaxError - same error that you should get when running a .py file containing the same expression: >>> file('test.py','wb+').write(expr + "\n") >>> ^D gandalf at saturnus:~$ python test.py File "test.py", line 1 SyntaxError: Non-ASCII character '\xdb' in file test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Otherwise the interpretation of the expression will be ambiguous. If there is any good reason why eval assumed a particular encoding in the above example? Sorry for my misunderstanding - my English is not perfect. I hope it is clear now. My problem is solved anyway. Anytime I need to eval an expression, I'm going to specify the encoding manually with # -*- coding: XXX -*-. It is good to know that it works for eval and its counterparts. And it is unambiguous. :-) Best, Laszlo From torriem at gmail.com Wed Mar 5 00:01:57 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 04 Mar 2008 22:01:57 -0700 Subject: popening a process in a specific working directory Message-ID: <47CE2945.9070303@gmail.com> I have a small multi-threaded program that spawns a number of threads that each spawn a particular process in a particular temporary directory. My problem is that using os.chdir to change the working directory before popening the process doesn't always work because another thread might change the cwd as it starts, before the process in this thread can start up. I'm currently using popen2.Popen4. Is there a way to properly specify a particular working directory when launching a process in python? I've hacked around my problem by writing a bash wrapper script that accepts the working directory as a parameter, changes the directory, then spawns the original program with the arguments. This works, but I'd like a better way. Michael From mentaltruckdriver at gmail.com Sat Mar 1 20:45:55 2008 From: mentaltruckdriver at gmail.com (Ryan M.) Date: Sat, 1 Mar 2008 17:45:55 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 1, 7:56?pm, Ira Solomon wrote: > I am an experienced programmer (40 years). ?I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. ?I would appreciate recommendations on those as well. > > Thanks > > Ira I would recommend checking out the official Python tutorial - http://docs.python.org/tut/ - it has some valuable information, and is always kept up to date. I'm haven't looked at any Python books (yet), so I can't provide any recommendations there. HTH. From martin at v.loewis.de Sat Mar 1 17:51:36 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Mar 2008 23:51:36 +0100 Subject: [Python-Dev] [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: <79990c6b0803011439n583bc2b2w5c544b620a91fa61@mail.gmail.com> References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> <47C9D802.2090205@v.loewis.de> <79990c6b0803011439n583bc2b2w5c544b620a91fa61@mail.gmail.com> Message-ID: <47C9DDF8.30000@v.loewis.de> > The 2.6a1 x86 MSI is there, but the 3.0a3 x86 MSI is still giving a 404. Please try again - *those* files weren't actually there when I sent my last message; I just built them. Regards, Martin From gagsl-py2 at yahoo.com.ar Fri Mar 21 14:29:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 11:29:29 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> <128011dd-a1a8-43af-bdea-beba452aa596@f63g2000hsf.googlegroups.com> Message-ID: <17b331d5-445a-481b-a637-e5e428f58ca0@f63g2000hsf.googlegroups.com> On 21 mar, 15:11, MRAB wrote: > On Mar 21, 11:48 am, fkallgren wrote:> Hi. > > > I have a little problem. I have a script that is in the scheduler > > (win32). But every now and then I update this script and I dont want > > to go to every computer and update it. So now I want the program to 1) > > check for new version of the script, 2) if there is a new version, > > copy that verision from server to local drive, 3) shutdown the program > > and start it up again as the new version. > > > The problem is that I can't run this script directly from server so it > > have to run it locally. > > > Anyone having any bright ideas?? > > import os > import sys > import shutil > > # Is there a newer version? > my_path = sys.argv[0] > update_path = os.path.join(os.path.dirname(my_path), "new_script.py") > > if os.path.getmtime(my_path) < os.path.getmtime(update_path): > ? ? # Update the script. > ? ? shutil.copy2(update_path, my_path) > ? ? # Re-start the script. > ? ? os.startfile(my_path) > ? ? sys.exit() > > # The rest of the script... I do mostly the same, except that instead of os.startfile I use: args = [sys.executable] args.extend(sys.argv) os.spawnl(os.P_NOWAIT, sys.executable, *args) to re-start the current script with the same arguments it was invoked before. -- Gabriel Genellina From micah at cowan.name Fri Mar 7 17:39:11 2008 From: micah at cowan.name (Micah Cowan) Date: Fri, 07 Mar 2008 22:39:11 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: <87zlta9n1s.fsf@micah.cowan.name> "K Viltersten" writes: > 2. You should use two spaces after a sentence-ending period. > > For heavens sake, why? I've always been obstructed by the double > blanks but tolerated them. Now, that i read that > it actually is a recommendation, i need to ask about the purpose. AFAICT from modern publications (which nevertheless get many other things wrong, such as how f and i are handled when they appear in sequence), this practice has mostly been eschewed, thankfully. In "The Elements of Typographical Style", by Robert Bringhurst, has this to say (section 2.1.4 of version 3.0): In the nineteenth century, which was a dark and inflationary age in typography and type design, many compositors were encouraged to stuff extra space between sentences. Generations of twentieth-century typists were then taught to do the same, by hitting the spacebar twice after every period. Your typing as well as your typesetting will benefit from unlearning this quaint Victorian habit. As a general rule, no more than a single space is required after a period, colon or any other mark of punctuation. Larger spaces (e.g., en spaces) are _themselves_ punctuation. He goes on to note that this does not apply to setting languages such as classical Latin or Greek, or other circumstances in which sentences begin with lowercase letters, where the extra space is actually helpful. The Elements of Typographical Style (much like Strunk & White) is not gospel, but is written by a highly experienced typesetter, and is chock full of very sound advice. Personally, I find double-spacing to be an abomination. However, there are some practical issues to note. One is that some editors (notably vi) only recognize a period as ending a sentence if they are followed by two spaces. This may be the default for Emacs as well (I don't do much "moving by sentence" in Emacs). For this reason, the GNU Coding Guidelines recommend ensuring that all periods in comments and in plaintext documentation have periods. Knuth's typesetting program, ???, in its default "plain" format (and in the popular La??? format as well), will add extra space at the ends of sentences automatically (I always disable this functionality when I write for either of those; I believe the command is "\frenchspacing"). -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From Grimsqueaker13 at gmail.com Thu Mar 27 04:59:26 2008 From: Grimsqueaker13 at gmail.com (Grimsqueaker) Date: Thu, 27 Mar 2008 01:59:26 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> <13umnl0ou29kn63@corp.supernews.com> Message-ID: <8e4a12d4-f848-40d3-b21b-2d3e57416377@m36g2000hse.googlegroups.com> OK, got that. If I use: for x in string_cartesian_product('abc'): print x I get: a b c What am I not understanding? Thank you From marek.rocki at wp.pl Sat Mar 8 08:38:43 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 8 Mar 2008 05:38:43 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> <1ec4b03a-75cd-432e-9e5d-750132324d38@s8g2000prg.googlegroups.com> <4e27c893-d7c6-4ab4-abaa-187520dfc69b@d62g2000hsf.googlegroups.com> Message-ID: <2317bea5-4451-4c73-abfe-c1bb626d9837@f47g2000hsd.googlegroups.com> Everybody has already explained why this doesn't work and a possible "solution" using metaclasses was suggested. I tried to implement it, ended up with monkey-patching __bases__, which is certainly an abomination (will it be possible in python 3.0?) but seems to do the trick. class _InheritFromOuterClass(object): """ This class is used as a marker. """ pass class MetaFixInheritance(type): """ This metaclass, along with ordinary class creation, changes base of all the inner classes (marked as inheriting from _InheritFromOuterClass) to the class being created. """ def __new__(self, name, bases, members): result = type(name, bases, members) for member in members.itervalues(): if isinstance(member, type) and issubclass(member, _InheritFromOuterClass): member.__bases__ = result, return result class Outer(object): """ Test an inner class inheriting from the outer class. Inheritance is monkey-patched upon creation of the outer class. """ __metaclass__ = MetaFixInheritance class Inner(_InheritFromOuterClass): pass def foo(self): return 'Outer.foo()' inner = Outer.Inner() print 'Inner.foo() is in fact', inner.foo() From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 23:23:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 04:23:40 -0000 Subject: float / rounding question References: Message-ID: <13t456cmgfpdhbc@corp.supernews.com> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote: > Sorry to come in so late in this discussion. Although it is correct to > say that many real numbers that have an exact decimal representation > cannot be exactly represented in binary, that is no excuse to print 53.6 > as 53.600000000000001. This is just lousy printing and the fact that > this kind of question comes up every week shows that it is confusing to > many people. Good. That's a feature, not a bug. Floats *are* confusing and unintuitive. Anyone with pretensions to be a programmer should get over the illusion that floats are reals as soon as possible, before they learn bad habits that have to be unlearned. If that starts with them asking why they get 53.600000000000001 instead of 53.6, so be it. If they want to be insulated from the harsh reality, they can do this: >>> print 53.6 53.6 -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 20:34:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 08 Mar 2008 01:34:16 -0000 Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <7xmypa844v.fsf@ruckus.brouhaha.com> Message-ID: <13t3r8oeh4frj43@corp.supernews.com> On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote: > Pierre Quentel writes: >> I would like to know if there is a module that converts a string to a >> value of the "most probable type" > > Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > >>> import this > The Zen of Python, by Tim Peters > ... > In the face of ambiguity, refuse the temptation to guess. Good advice, but one which really only applies to libraries. At the application level, sometimes (but not always, or even most times!) guessing is the right thing to do. E.g. spreadsheet applications don't insist on different syntax for strings, dates and numbers. You can use syntax to force one or the other, but by default the application will auto-detect what you want according to relatively simple, predictable and intuitive rules: * if the string looks like a date, it's a date; * if it looks like a number, it's a number; * otherwise it's a string. Given the user-base of the application, the consequences of a wrong guess, and the ease of fixing it, guessing is the right thing to do. Auto-completion is another good example of guessing in the face of ambiguity. It's not guessing that is bad, but what you do with the guess. -- Steven From sturlamolden at yahoo.no Sat Mar 22 11:09:39 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 08:09:39 -0700 (PDT) Subject: wxFormBuilder References: <7152b94f-fc30-473f-bd94-5d43a9153f56@p73g2000hsd.googlegroups.com> Message-ID: On 22 Mar, 08:10, CM wrote: > Why can't you use Boa Constructor? I really enjoy using it. It feels awkward. I don't know why. From aahz at pythoncraft.com Sun Mar 16 21:26:23 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Mar 2008 18:26:23 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <87zlsyyxee.fsf@benfinney.id.au> Message-ID: In article <87zlsyyxee.fsf at benfinney.id.au>, Ben Finney wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> I would like to encourage anyone who was at PyCon but has not >> provided formal feedback to use the following URLs: > >For those who don't like to follow opaque munged URLs from services >that give no indication where you'll end up, here are the actual URLs >you'll arrive at: > >> For the conference: >> http://tinyurl.com/2ara8u > > PyCon 2008: Conference Feedback > > >> For the tutorials: >> http://tinyurl.com/2ew2pc > > PyCon 2008: Tutorial Evaluation > Sorry, I agree with you -- those URLs were not (and should have been) on pycon.org, and I just pasted what I got from someone else. Not enough spoons.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bockman at virgilio.it Wed Mar 5 07:39:48 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 5 Mar 2008 04:39:48 -0800 (PST) Subject: draining pipes simultaneously References: Message-ID: > > Inserting delay in the beginning of the loop causes feeling of command > taking long to start and delay at the end of the loop may cause of > data loss when both thread became inactive during delay. time.sleep() pauses ony the thread that executes it, not the others. And queue objects can hold large amount of data (if you have the RAM), so unless your subprocess is outputting data very fast, you should not have data loss. Anyway, if it works for you ... :-) Ciao ----- FB From kyosohma at gmail.com Mon Mar 31 10:41:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 07:41:45 -0700 (PDT) Subject: wxPython listctrl References: <4dc652a5-d6f9-4cb8-af30-ec1c9e4ea505@y21g2000hsf.googlegroups.com> Message-ID: <8fcac15f-ad92-47b2-84bb-1d8e474ea016@i7g2000prf.googlegroups.com> On Mar 29, 4:27 pm, Gif wrote: > I was wondering if there is a way to extract an icon from a file > (executable) and then add it in a listctrl. I also 'd like to know if > i can shorten the icon in order to fit in a listctrl item. > I've managed to get the icon from an icon file and add t as a listctrl > item but it remains 32x32. > > code: > images = ['LimeWire.ico'] > > self.il = wx.ImageList(18, 10) > self.il.Add(wx.Bitmap(images[0])) > > #This below raises an error saying that no handle was found for that > image > #self.ib = wx.IconBundle() > #self.ib.AddIconFromFile(r'LimeWire.exe', wx.BITMAP_TYPE_ANY) > > self.listView1.SetImageList(self.il, wx.IMAGE_LIST_SMALL) > self.listView1.SetItemImage(0, 0) Please re-post to the wxPython user's group: http://wxpython.org/maillist.php I'm pretty sure they know how to do this. Mike From martin.nordstrom87 at gmail.com Thu Mar 27 15:29:23 2008 From: martin.nordstrom87 at gmail.com (martin.nordstrom87 at gmail.com) Date: Thu, 27 Mar 2008 12:29:23 -0700 (PDT) Subject: Building a "safe" python? Message-ID: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> I'm making a game where you'll be able to make your own mods and I want to be able to write these mods in python. However, python has a lot of "dangerous" functions (like erase any file on the harddrive etc) so I want a "safe" python. I first found RExec but that is disabled in python 2.5 so I was thinking about building python from source with a few changes. The changes I was thinking about was to change the import function so that it should only be able to import the .pyd-files that I allow (and it should of course still be able to import any .py-file) and remove or change the builtin functions that are "dangerous". Is this enough to make a "safe" python that can't do anything "dangerous"? I'm going to embed this "safe" python into my game and I've discovered that when I embed the original python and the mod wants to import a .py-file that is not in the game directory it will search for the .py-file in the python directory that is installed on my computer. Can I somehow prevent the embedded python to look in the python directory? Thanks! Martin From grahn+nntp at snipabacken.se Mon Mar 31 18:47:26 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 31 Mar 2008 22:47:26 GMT Subject: standard input, for s in f, and buffering References: <65bg55F2esfc1U3@mid.uni-berlin.de> Message-ID: On 31 Mar 2008 06:54:29 GMT, Marc 'BlackJack' Rintsch wrote: > On Sun, 30 Mar 2008 21:02:44 +0000, Jorgen Grahn wrote: > >> I realize this has to do with the extra read-ahead buffering documented for >> file.next() and that I can work around it by using file.readline() >> instead. >> >> The problem is, "for s in f" is the elegant way of reading files line >> by line. With readline(), I need a much uglier loop. I cannot find a >> better one than this: >> >> while 1: >> s = sys.stdin.readline() >> if not s: break >> print '####', s , >> >> And also, "for s in f" works on any iterator f -- so I have to choose >> between two evils: an ugly, non-idiomatic and limiting loop, or one >> which works well until it is used interactively. >> >> Is there a way around this? Or are the savings in execution time or >> I/O so large that everyone is willing to tolerate this bug? > > You can use ``for line in lines:`` and pass ``iter(sys.stdin.readline,'')`` > as iterable for `lines`. Thanks. I wasn't aware that building an iterator was that easy. The tiny example program then becomes #!/usr/bin/env python import sys f = iter(sys.stdin.readline, '') for s in f: print '####', s , It is still not the elegant interface I'd prefer, though. Maybe I do prefer handling file-like objects to handling iterators, after all. By the way, I timed the three solutions given so far using 5 million lines of standard input. It went like this: for s in file : 1 iter(readline, ''): 1.30 (i.e. 30% worse than for s in file) while 1 : 1.45 (i.e. 45% worse than for s in file) Perl while(<>) : 0.65 I suspect most of the slowdown comes from the interpreter having to execute more user code, not from lack of extra heavy input buffering. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From anaryin at gmail.com Thu Mar 27 10:31:41 2008 From: anaryin at gmail.com (=?ISO-8859-1?Q?Jo=E3o_Rodrigues?=) Date: Thu, 27 Mar 2008 14:31:41 +0000 Subject: Checking processes running under Windows Message-ID: Hello all! I'm trying to write a script that needs to check which processes are running under Windows (XP Pro, Home, whatever). The method I'm using is: >>> process_list = os.popen('TASKLIST').read() However, XP Home doesn't have the tasklist.exe tool so, this is kind of useless in that OS. Do you have any other methods I can use for this? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Mar 19 11:28:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 16:28:37 +0100 Subject: cx_Oracle execute procedure References: Message-ID: <64cppeF2at1j9U2@mid.uni-berlin.de> Poppy wrote: > I've been working on the code below and and executes silently, no > complaints, however the end result should be a record in my table and it's > not added. The procedure works with the passed credentials using SQLPlus > or SQL Developer clients. However I'm not sure if I'm constructing my > python code correctly to interact with Oracle. > > I've been basing the code below on what I found in this thread > http://www.thescripts.com/forum/thread33728.html . > > Zach- > > import cx_Oracle > > connection = cx_Oracle.connect("user/pass at server") > > ## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum > varchar2, p_prefix number) > > cur = connection.cursor() > > repParams = {} > repParams['arg1'] = "5555555" > repParams['arg2'] = "2" > repParams['arg3'] = "999" > > sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3); > end;""" > > cur.execute(sqlStr, repParams) > > connection.commit > > cur.close > > connection.close You forgot to call the methods using the ()-operator. connection.commit() and so forth. Diez From castironpi at gmail.com Fri Mar 7 14:22:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:22:49 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> <51ca8638-65fa-490b-a04a-33ffbefd4aca@s19g2000prg.googlegroups.com> Message-ID: <5d4827e1-8b90-4feb-bfb0-6d956e138b5e@b64g2000hsa.googlegroups.com> > > I find itertools.islice() useful, so for Python 3.x I may like to see > general iterables. ?Third, the analogy breaks down quickly (i.e. > chain(it[:2], it[2:]) does not give the same result as iter(it) unless > >>> s = 'abcdefg' > >>> list(W(s)[2:]) Slice literals are a logical next step, precedented by raw strings and bytes. slice= islice is too, precedented by range= xrange. Does s[2:] evaluate to an infinity? What is the natural meaning of skipping finitely many terms at the head of an iterable? itertools can also grow 'skip(n=0)' and 'drop(step=3)' operations. From apatheticagnostic at gmail.com Mon Mar 3 17:59:16 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Mon, 3 Mar 2008 14:59:16 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> Message-ID: <2ecbb96f-c246-48c5-836f-bf934ac56ba6@e25g2000prg.googlegroups.com> I swear, this is one of the most polite-oriented groups I've ever seen. Not that that's a bad thing or anything, it's nice to be nice. (This has been Captain Universal Truth, over and out) From sturlamolden at yahoo.no Sun Mar 16 13:31:59 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:31:59 -0700 (PDT) Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> Message-ID: <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> On 16 Mar, 18:23, "Martin Blume" wrote: > This seems to imply that the Mac, although running now on Intel > processors, is still big-endian. Or maybe the struct module thinks big-endian is native to all Macs? It could be a bug. From castironpi at gmail.com Thu Mar 13 20:45:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 17:45:52 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: On Mar 13, 7:18?pm, Mel wrote: > Diez B. Roggisch wrote: > >> My understanding is that foo.bar does *not* create a new object. > > > Your understanding is not correct. > > >> ?All it > >> does is return the value of the bar attribute of object foo. ?What new > >> object is being created? > > > A bound method. This happens through the descriptor-protocol. Please see > > this example: > > > class Foo(object): > > ? ? def bar(self): > > ? ? ? ? pass > > > f = Foo() > > a = Foo.bar > > b = f.bar > > c = f.bar > > > print a, b, c > > print id(b), id(c) > > (What Diez said.) ?From what I've seen, f.bar creates a bound method > object by taking the unbound method Foo.bar and binding its first > parameter with f. ?This is a run-time operation because it's easy to > re-assign some other function to the name Foo.bar, and if you do, the > behaviour of f.bar() will change accordingly. > > You can get some very useful effects from these kinds of games. ?You > can make f into a file-like object, for example, with > > import sys > f.write = sys.stdout.write > > Here, f.write *is* a straight attribute of f, although it's a built-in > method of the file class. ?It's still bound, in a way, to sys.stdout. > ? I'm assuming that a different example could create an attribute of f > that's a bound method of some other object entirely. ?I've verified > that f.write('howdy') prints 'howdy' on standard output. Accordingly, f.write= types.MethodType( sys.stdout.__class__.write, sys.stdout ). It depends on what you want the implicit first (self) to be-- f or sys.stdout. But how come this works? >>> import types >>> import sys >>> >>> class C: ... write= sys.stdout.write ... def g( self ): ... self.write( 'was in \'g\'\n' ) ... >>> c= C() >>> c.g() was in 'g' Shouldn't 'write' be getting extra parameters? Sounds fishy, not to mix metaphors. From rbossy at jouy.inra.fr Sat Mar 8 09:49:46 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 08 Mar 2008 15:49:46 +0100 Subject: os.chdir In-Reply-To: <47D2A42A.9010902@v.loewis.de> References: <47D2A42A.9010902@v.loewis.de> Message-ID: <1204987786.47d2a78a33e29@www.jouy.inra.fr> Quoting "Martin v. L?wis" : > >> os.chdir("~/dir1") > > > > It is not mentioned in the documentation but I'm pretty sure os.dir() > doesn't do > > tilde expansion since this is usually performed by a shell. > > > > You should use instead: > > > > os.chdir(os.join(os.environ['HOME'], 'dir1')) > > Or > > os.chdir(os.path.expanduser("~/dir1")) Well... duh! Thanks for reminding me. Cheers, RB From jgardner at jonathangardner.net Thu Mar 20 10:46:25 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 20 Mar 2008 07:46:25 -0700 (PDT) Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: On Mar 20, 4:51?am, "Giampaolo Rodola'" wrote: > Hi all. > Is there any way to su or login as a different user within a python > script? I mainly need to temporarily impersonate another user to > execute a command and then come back to the original user. > I tried to google a little bit about it but I still didn't find a > solution. In the unix world, this is highly discouraged. You shouldn't have to change your user. The only user who can change roles---and who should change roles for security reasons---is root. The only reason sudo is around is for those people who really are root but who don't like logging in as root to do root work. With a very limited permission set for sudo, it is very, very easy to get full root access. $ sudo cp /bin/cp /bin/cp.old; sudo cp /bin/su /bin/cp; sudo cp - # If you want a different user to access files that another user created, that's what groups are for. You should create a common group and then share the files by assigning them to that group and setting the appropriate permissions. Yes, this is painful, and every once in a while you get files that don't have the right permissions or the group is set to the wrong group. But this is the cost of running on a system where multiple users can be doing things all at once, and the cost of trying to make sure that users can't hurt each other. Someone somewhere has to say, "You are allowed to do this much, but no more". If that's not what you need, then you need to run the process as root. It can change its user and even chroot to a jail if need be. This is how apache, for instance, works. It starts as root and spawns the server processes as the apache user. (Apache does have an interesting problem with home directories, and it has a very special solution that is very insecure. Even there, the better solution is to put all the user's files under a common group in a common folder outside of their home directories.) From darkxanthos at gmail.com Wed Mar 19 18:57:16 2008 From: darkxanthos at gmail.com (Justin Bozonier) Date: Wed, 19 Mar 2008 15:57:16 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> Message-ID: On Mar 19, 2:48 pm, John Machin wrote: > On Mar 19, 10:08 am, sturlamolden wrote: > > > > > On 18 Mar, 23:45, Arnaud Delobelle wrote: > > > > > def nonunique(lst): > > > > slst = sorted(lst) > > > > dups = [s[0] for s in > > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > > > return [dups[0]] + [s[1] for s in > > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > > Argh! What's wrong with something like: > > > > def duplicates(l): > > > i = j = object() > > > for k in sorted(l): > > > if i != j == k: yield k > > > i, j = j, k > > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) > > as opposed to ours which are O(N log N). > > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > and is IMHO more readable than Paul's. It's not as much O(N)... Paul Robin's uses a sort first which is definitely not O(N). Paul's could be prettied up a bit but the general principle is sound. From Robert.Bossy at jouy.inra.fr Fri Mar 14 06:26:08 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 14 Mar 2008 11:26:08 +0100 Subject: merging intervals repeatedly In-Reply-To: References: Message-ID: <47DA52C0.6040207@jouy.inra.fr> Magdoll wrote: >> One question you should ask yourself is: do you want all solutions? or >> just one? >> If you want just one, there's another question: which one? the one with >> the most intervals? any one? >> > > I actually don't know which solution I want, and that's why I keep > trying different solutions :P > You should think about what is your data and what is probably the "best" solution. >> If you want all of them, then I suggest using prolog rather than python >> (I hope I won't be flamed for advocating another language here). >> > > Will I be able to switch between using prolog & python back and forth > though? Cuz the bulk of my code will still be written in python and > this is just a very small part of it. > You'll have to popen a prolog interpreter and parse its output. Not very sexy. Moreover if you've never done prolog, well, you should be warned it's a "different" language (but still beautiful) with an important learning curve. Maybe not worth it for just one single problem. >> If you have a reasonable number of intervals, you're algorithm seems >> fine. But it is O(n**2), so in the case you read a lot of intervals and >> you observe unsatisfying performances, you will have to store the >> intervals in a cleverer data structure, see one of these:http://en.wikipedia.org/wiki/Interval_treehttp://en.wikipedia.org/wiki/Segment_tree >> > > Thanks! Both of these look interesting and potentially useful :) > Indeed. However these structures are clearly heavyweight if the number of intervals is moderate. I would consider them only if I expected more than several thousands of intervals. Cheers, RB From giles_brown at hotmail.com Sun Mar 2 09:15:54 2008 From: giles_brown at hotmail.com (Giles Brown) Date: Sun, 2 Mar 2008 06:15:54 -0800 (PST) Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> On Mar 2, 2:08 pm, Preben Randhol wrote: > On Sun, 2 Mar 2008 15:06:17 +0100 > > Preben Randhol wrote: > > class dbase(list): > > Sorry the definition of the class is: > > class dbase(object): > > it doesn't derive from the list class. > > Preben http://docs.python.org/lib/typeiter.html From castironpi at gmail.com Fri Mar 7 17:27:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 14:27:02 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> <13t3cfpo6d8d2ab@corp.supernews.com> Message-ID: <79c6eb9f-fc4a-4d48-9c34-8d6a4fb94a70@n77g2000hse.googlegroups.com> > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! A shapely CATHOLIC > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? SCHOOLGIRL is FIDGETING > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ?inside my costume.. ... Are you wearing it? *plonkblock* So, what gets you plonked around h... *plonk*? From natambu at gmail.com Mon Mar 10 01:21:59 2008 From: natambu at gmail.com (natambu at gmail.com) Date: Sun, 9 Mar 2008 22:21:59 -0700 (PDT) Subject: tcp client socket bind problem Message-ID: I have a linux box with multiple ip addresses. I want to make my python client connect from one of the ip addresses. Here is my code, no matter what valid information I put in the bind it always comes from the default ip address on the server. Am I doing something wrong? ------------- #!/usr/bin/python import socket host = "server" port = 1190 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("",0)) sock.connect((host, port)) ------------- From mensanator at aol.com Wed Mar 12 00:21:12 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 11 Mar 2008 21:21:12 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> <306997c4-36dc-4603-8100-f47e25e55bef@s19g2000prg.googlegroups.com> <792e7610-7807-4deb-b13e-213d162cd2c0@d62g2000hsf.googlegroups.com> Message-ID: <29e51d14-1848-4bcc-aad9-8a5cae686ee8@m36g2000hse.googlegroups.com> On Mar 11, 9:50?pm, Nathan Pinno wrote: > On Mar 11, 1:12 pm, Mensanator wrote: > > > > > > > On Mar 11, 3:36 am, Duncan Booth wrote: > > > > Mensanator wrote: > > > > On Mar 10, 10:44???pm, Nathan Pinno wrote: > > > >> Why does my compiler say invalid syntax and then highlight the > > > >> quotation marks in the following code: > > > > >> # This program is to find primes. > > > > > Needs work. > > > > Be fair. > > > Being helpful isn't fair? > > > > The OP hadn't managed to figure out why the program wasn't > > > running, so you can't expect him to have got all the bugs out of the code > > > yet. > > > The bug had already been answered. > > > If you fail to implement your premise correctly, you have a bug. > > > It doesn't matter if the code is bug-free if the premise is false. > > > In this case, the premise that he can determine primes this way > > is false. He will have to abandon the cos() thing, for although it > > works in theory, he'll never get it to work in practice. > > > Besides, the cos() is a red herring (hint: cos(pi*n)). The problem > > can be made to work EXACTLY (at least up to z=10000) by using > > rationals > > (which gmpy supports). > > > His problem is going to take much more than fixing a syntax error. > > > > And he only asked about the specific syntax error not the entire > > > solution to his homework. > > > If this is indeed homework, and he's supposed to come up with a > > factorial algorithm, I seriously doubt the teacher would accept > > gmpy.fac(z-1), so I assume it isn't. > > > > My advice to Nathan would be: > > > > 1. If you get a weird syntax error that you don't understand try cutting > > > the code down to just the bit which generates the error. > > > > 2. Play around in the interactive interpreter to see what works and what > > > doesn't. > > > > 3. If you don't understand why the code doesn't work then get a stuffed > > > toy, cardboard cutout of a person, or the least technical member of your > > > family and explain to them in great detail exactly why the code must > > > (despite error messages to the contrary) be correct. Usually you'll spot > > > the problem half way through the explanation. > > > > 4. If you post to this list then post the full error message and traceback. > > > That way we don't have to guess which quotation marks are the problem. > > Yep, got it fixed, and no, it is not a homework problem...just a > project for fun to keep up my Python coding in my memory intact > (apparently, it doesn't work as well when I've been up early 3 days in > a row... :P ). > > Now I just have to figure out why it isn't working the way it is > supposed to. Did you see my hints, or are you keen to work it out? My solution tested up to z=10000. Factorial starts getting sluggish there and is utterly intractable for really large numbers, such as RSA. > It was given to me by someone in the sci.math area as an > alternative to working with 1 < x < n.- Hide quoted text - > > - Show quoted text - From ajaksu at gmail.com Thu Mar 20 16:35:35 2008 From: ajaksu at gmail.com (ajaksu) Date: Thu, 20 Mar 2008 13:35:35 -0700 (PDT) Subject: A question about a metacharacter References: Message-ID: On Mar 20, 8:19?am, igbt wrote: > However, if you don't enter anything the > script works but if you enter a dot (.) the script does not work. Have you tried it with other non-metacharacter values? > sss = entryName.get_text() ? ? ?# The script gets the text > ? ? ? ? if sss == "" or sss == ".": > ? ? ? ? ? ? ? ? gtk.main_quit() ? ? ? ?#The script finishes > Try adding this: else: print sss, type(sss) Good luck! Daniel From sjdevnull at yahoo.com Mon Mar 10 12:30:24 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 10 Mar 2008 09:30:24 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> Message-ID: <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> On Mar 10, 11:30 am, rockingred wrote: > On Mar 10, 10:26 am, Roel Schroeven > wrote: > > > > > rockingred schreef: > > > > On Mar 8, 8:27 pm, Dan Bishop wrote: > > >> // Copyright (C) 2008 Foobar Computer Consulting > > >> // > > >> // VERSION PROJECT# DATE DESCRIPTION > > >> // ------- -------- -------- ------------------ > > >> // 1.00 123456 01/04/08 Original creation. > > >> // > > > >> Eleven lines, of which the only useful information to me was the > > >> project number, as knowing this let me look up who was behind these > > >> comments. > > > > Actually, "editorial" comments that tell you who last changed a > > > program, when and why can be useful. I worked in a company with a > > > number of programmers on staff. Having comments that told us Joe > > > worked on a program yesterday that isn't working today could often > > > solve half the battle. Especially if Joe also added a comment near > > > the lines he had changed. Likewise including the "Project#" would > > > help us track all the programs that had to be changed for a specific > > > project. This allowed us to move all related items into the Live > > > system once the testing phase had been completed (we just searched for > > > everything with the same Project# in it). Yes, on rare occasions we > > > would have an entire page of "Editorial" comments to ignore at the > > > beginning of our program listing, but it was easy enough to skip that > > > page. I will grant you that probably after 10 changes the first > > > change isn't as important anymore (unless you want to backtrack and > > > find out who started the Project in the first place and what it's > > > original purpose was). > > > That is certainly useful, but IMO that's what version control systems > > are for. > > > -- > > The saddest aspect of life right now is that science gathers knowledge > > faster than society gathers wisdom. > > -- Isaac Asimov > > > Roel Schroeven- Hide quoted text - > > > - Show quoted text - > > Unfortunatly, in many of the companies I worked for, version control > software was not implemented. In some cases, where it was, it > actually inserted the comments into the header of the program as > described. In others, the software was so limited as to make it > useless. Fix that. That's usually something that's fairly easy to get done as a programmer (I've had to do it at 2 of the last 4 places I worked). Just go explain all the problems that can happen by not having VC and all the benefits it brings to your managers, and that there's a good free VC system that will work for everyone, and it'll likely become a mandate pretty quickly. It's almost certainly worth fixing that problem rather than mucking around with half-solutions. From kwitters at telenet.be Sat Mar 29 06:55:00 2008 From: kwitters at telenet.be (kwitters at telenet.be) Date: Sat, 29 Mar 2008 03:55:00 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? Message-ID: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> I don't know if this is the right place to discuss the death of <> in Python 3.0, or if there have been any meaningful discussions posted before (hard to search google with '<>' keyword), but why would anyone prefer the comparison operator != over <>??? I've written an article about it to try and save this nice "is not equal" operator, located at http://dewitters.koonsolo.com/python_neq.html Please set it straight in 3.0, and if not, convince me with a good reason of doing so, so that I can live with it and don't have to spend the rest of my life in 2.x ;). From timr at probo.com Mon Mar 3 01:14:15 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 03 Mar 2008 06:14:15 GMT Subject: Import, how to change sys.path on Windows, and module naming? References: Message-ID: <0o5ns35pusse2tqk33igkk727oattohhip@4ax.com> Jeremy Nicoll - news posts wrote: > >Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip >in their sys.path? What's the point of having a zip in the path? Starting with Python 2.4, Python is able to import modules directly from a zip, as if it were a directory. It's a very handy feature for distributing premade packages. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gherron at islandtraining.com Wed Mar 5 13:52:44 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 05 Mar 2008 10:52:44 -0800 Subject: Short confusing example with unicode, print, and __str__ In-Reply-To: <47CEDF77.5050501@andrew.cmu.edu> References: <47CEDF77.5050501@andrew.cmu.edu> Message-ID: <47CEEBFC.9010001@islandtraining.com> Gerard Brunick wrote: > I really don't understand the following behavior: > > >>> class C(object): > ... def __init__(self, s): self.s = s > ... def __str__(self): return self.s > ... > >>> cafe = unicode("Caf\xe9", "Latin-1") > >>> c = C(cafe) > >>> print "Print using c.s:", c.s > Print using c.s: Caf? > >>> print "Print using just c:", c > Print using just c: Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > >>> str(c) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > > Why would "print c.s" work but the other two cases throw an exception? > Any help understanding this would be greatly appreciated. > > Thanks in advance, > Gerard > It's the difference between how __str__ and __repr__ act on strings. Here's s simpler example >>> d=unicode("Caf\xe9", "Latin-1") >>> repr(d) "u'Caf\\xe9'" >>> str(d) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Gary Herron From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 5 07:12:51 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Mar 2008 13:12:51 +0100 Subject: Using re module better In-Reply-To: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> Message-ID: <47ce8e37$0$22806$426a74cc@news.free.fr> Mike a ?crit : > I seem to fall into this trap (maybe my Perl background) where I want > to simultaneously test a regular expression and then extract its match > groups in the same action. > For instance: > > if (match = re.search('(\w+)\s*(\w+)', foo)): > field1 = match.group(1) > field2 = match.group(2) > ... > > (compare to Perl:) > > if($foo =~ /(\w+)\s*(\w+)/) { > $field1 = $1; > $field2 = $2; > ... > } > > Problem is, my python is invalid above. What's the pythonic way to do > this? In your above use case, the solution is obvious: match = re.search('(\w+)\s*(\w+)', foo) if match: field1 = match.group(1) field2 = match.group(2) wrt/ assignement as an expression, this has been discussed about 2 days ago - look for a thread (badly) named "Is it possible to return a variable and use it...?" HTH From arnodel at googlemail.com Tue Mar 18 19:38:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 16:38:45 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> Message-ID: <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> On Mar 18, 3:59?pm, Ninereeds wrote: > Hrvoje Niksic wrote: > > This doesn't apply to Python, which implements dict storage as an > > open-addressed table and automatically (and exponentially) grows the > > table when the number of entries approaches 2/3 of the table size. > > Assuming a good hash function, filling the dict should yield amortized > > constant time for individual additions. Isn't this average constant time rather than amortized? > OK. I obviously need to look up open-addressed tables. I thought this > was just, in effect, implicit linked listing - ie it still needs a > linear search to handle collisions, it just avoids the need for > explicitly stored link fields. Perhaps I'm mistaken. I don't think you are mistaken, but if I'm wrong I'd be grateful for a link to further details. Thanks -- Arnaud From software at ginstrom.com Thu Mar 13 19:21:41 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 14 Mar 2008 08:21:41 +0900 Subject: Dispatch("Excel.Application") failed In-Reply-To: <84040989-8de9-42fb-ba08-6f1ee10566e0@s19g2000prg.googlegroups.com> References: <84040989-8de9-42fb-ba08-6f1ee10566e0@s19g2000prg.googlegroups.com> Message-ID: <075401c88560$ffcc68c0$0203a8c0@MOUSE> > On Behalf Of John Machin > > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > > None, None) > > Googling for 2147221005 gives some clues. > > That string of hex stuff appears where an error message is > expected -- it's not utf8, and makes no sense when I attempt > to decode it with cp1250 to cp1258 inclusive. If you start > IDLE and type: The hex stuff is Chinese. It appears to be a standard Windows error message. ???????? (Which I believe meaans "invalid class string") I wrote in another post (that doesn't appear to have made it to the list) that the call to Dispatch on Excel will fail if the formula bar edit box is active. Just another idea. Regards, Ryan Ginstrom From jeff at jmcneil.net Thu Mar 20 23:30:45 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 20 Mar 2008 23:30:45 -0400 Subject: An Application Program to Play a CD In-Reply-To: References: Message-ID: <82d28c40803202030s68f48ad7t40dcc8e11e4c0173@mail.gmail.com> I don't know of any Python specific stuff to do this, but have you looked at Asterisk? I know it's quite configurable and allows you to setup dial plans and route extensions and whatnot. http://www.asterisk.org/ That's probably a better fit. On 3/20/08, W. Watson wrote: > How difficult would it be to write a Python program that would play a > specific track on a CD from say 8 am to 6 pm each weekday on a PC's speaker, > and switch tracks each day? That is, what library capabilities might be able > to do that. Are they already available. > > Extra points. Now imagine the same as above, but the program should answer a > phone and play the track for the day while someone is holding the call, or > would be given the option to connect to the operator, say, or listen to the > recording? > > To get a bit specific, our science museum would like to buy the monthly set > of StarDate programs. Each program is about 2 minutes long and there's one > for every day of the month. There seems to be no such commercial software to > automate this process. > -- > Wayne Watson (Nevada City, CA) > > Web Page: > > -- > http://mail.python.org/mailman/listinfo/python-list > From duncan.booth at invalid.invalid Mon Mar 10 15:03:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2008 19:03:18 GMT Subject: Quality assurance in Python projects containing C modules References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: Stefan Behnel wrote: > Duncan Booth wrote: >> I would start by ensuring that any DLLs you write are written using >> Pyrex or Cython: almost always problems with C libraries called from >> Python are due to faulty reference counting but if you keep all of >> your Python related code in Pyrex/Cython modules the reference >> counting problem should be taken care of for you. You can call any >> required C/C++ code from the Cython code. > > I think the OP meant to use wxPython as an external module, in which > case he has no way of influencing the language it is implemented in. The OP mentioned 'two or three C libraries', so I assume wxPython is only part of the story. From mblume at freesurf.ch Sun Mar 2 11:55:52 2008 From: mblume at freesurf.ch (Martin Blume) Date: Sun, 2 Mar 2008 17:55:52 +0100 Subject: Problem with the strip string method References: Message-ID: <47cadc19$0$9036$5402220f@news.sunrise.ch> "Colin J. Williams" schrieb > The Library Reference has > strip( [chars]) > > Return a copy of the string with the > leading and trailing characters removed. ^^^^^^^^^^^^^^^^^^^^ It's "leading and trailing", not "leading, trailing or embedded". >>> "xxxaaaxxx".strip("x") 'aaa' >>> "xxxaaaxxxaaaxxx".strip("x") 'aaaxxxaaa' >>> HTH Martin From gagsl-py2 at yahoo.com.ar Fri Mar 28 18:19:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 19:19:23 -0300 Subject: Question regd downloading multipart mail using POP3 References: <118409.12220.qm@web50111.mail.re2.yahoo.com> Message-ID: En Fri, 28 Mar 2008 16:47:51 -0300, SPJ escribi?: > I am facing a strange problem when I am trying to retrieve multipart > mail from POP server with attachments. > The task is to write a script which will retrieve mail with specific > 'from' field. Get the subject, body and attachments if any and reuse > this info to send mail with different format to ticketing system. > > The global variable values I am expecting is: > msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so > on > attachmentList=[['none'],['attachname.txt','filename.pl']] > where none is no attachments. > > But the result I am getting is: > msgList = [[msg1_subject,msg1_body,0],[msg2_subject,msg2_body,1]] and so > on > attachmentList=[[none],['none', 'attachname.txt', 'filename.pl']] > > An extra 'none' in the attachment list except for plain/text mails > without attachments. None is a special object in Python, 'none' is a string, and none is a name that may refer to anything. They're not the same thing. I would remove *all* Nones and nones and "none"s. An empty list is enough indication that there are no attachments, ok? > # regex for searching mails from example at example.com > soc = re.compile(".*example\@example.com.*") This regex may be too slow. Use soc = re.compile(r"example at example\.com") (note the r and the \. and lack of .* on both ends; also @ isn't a special character so it's not necesary to escape it) > if soc.match(check1): > subject = msg1.get('Subject') # Subject for only mails With the above reg.exp., use: if soc.search(check1): ... > if part.get_content_type() != ("text/html" or > "text/plain" or "multipart/alternative" or "multipart/mixed"): That's wrong. The () evaluate simply to "text/html". You surely want this: content_type = part.get_content_type() if content_type not in ["text/html", "text/plain", "multipart/alternative", "multipart/mixed"]: ... -- Gabriel Genellina From jaywgraves at gmail.com Mon Mar 10 10:53:05 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 10 Mar 2008 07:53:05 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <3df2b3f8-64ad-4102-8b60-95717e6748fe@o77g2000hsf.googlegroups.com> On Mar 10, 9:28 am, Robert Bossy wrote: > Personally, I'd use glob.glob: > > import os.path > import glob > > def parsefolder(folder): > path = os.path.normpath(os.path.join(folder, '*.py')) > lst = [ fn for fn in glob.glob(path) ] > lst.sort() > return lst > Why the 'no-op' list comprehension? Typo? ... Jay From john106henry at hotmail.com Mon Mar 31 14:32:35 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 11:32:35 -0700 (PDT) Subject: Of qooxdoo, qwt, and Python References: <28f7384f-b8d1-430d-9e0d-389ebae7eefd@e10g2000prf.googlegroups.com> <51c2f4c2-8752-49e3-81f8-77094c078015@k13g2000hse.googlegroups.com> Message-ID: <6087b21f-7f4b-4395-9502-3a39c991f925@d21g2000prf.googlegroups.com> olive wrote: > On 31 mar, 18:05, John Henry wrote: > > I was searching for a way to redevelop a desktop Pythoncard based > > program into a web-application. I understand what need to be done for > > all of the non-GUI code. For the GUI capabilities, I stumbled across > > a package call qooxdoo (http://qooxdoo.org/). It appears to provide > > the GUI capabilities I need. Then I saw that there is qwt - which > > allows you to write qooxdoo code in pure Java. Since I don't know > > Java (or don't want to know), is there a similar path I can take using > > Python? > > > > Regards, > > you could try this http://code.google.com/p/pyjamas/ > or http://doc.appcelerator.org/overview/what_is_appcelerator/index.html > or maybe jython with any java based toolkit (qwt, zk ...). > > Regards. Thanks for the reply. pyjamas looks promising because I believe seeing something from the qooxdoo site that there are similarities between qooxdoo and the google web development kit. Not sure about appcelerator. From tkpmep at gmail.com Sun Mar 30 16:54:50 2008 From: tkpmep at gmail.com (tkpmep at gmail.com) Date: Sun, 30 Mar 2008 13:54:50 -0700 (PDT) Subject: Dispatching functions from a dictionary Message-ID: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> To keep a simulation tidy, I created a dispatcher that generates random variables drawn from various distributions as follows: import random RVType = 1 #Type of random variable - pulled from RVDict RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), '3': random.gammavariate(1,1), '4': random.gauss(0,1), '5': random.lognormvariate(1,1), '6': random.paretovariate(1), '7': random.uniform( -1,1), '8': random.weibullvariate(1,2) } x = [] y=[] rv = RVDict[str(RVType)] for i in range(N): x.append(rv) y.append(rv) Oddly, x and y get filled with a single value repeated N times. I expected to get a different random number appear each time I called rv ,but this does not happen. Instead, my first call to rv generates a random number from the appropriate distribution, while subsequent calls simply repeat the random number generated in the first call. Where am I going wrong? Thanks in advance for your help. Sincerely Thomas Philips From Robert.Bossy at jouy.inra.fr Tue Mar 25 11:12:05 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 16:12:05 +0100 Subject: dynamically created names / simple problem In-Reply-To: <000c01c88e88$96c29490$0600a8c0@laptop> References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: <47E91645.4000706@jouy.inra.fr> Jules Stevenson wrote: > > Hello all, > > I'm fairly green to python and programming, so please go gently. The > following code > > for display in secondary: > > self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") > > Errors, because of the apparent nastyness at the beginning. What I?m > trying to do is loop through a list and create uniquely named wx > widgets based on the list values. Obviously the above doesn?t work, > and is probably naughty ? what?s a good approach for achieving this? > Hi, What you're looking for is the builtin function setattr: http://docs.python.org/lib/built-in-funcs.html#l2h-66 Your snippet would be written (not tested): for display in secondary: setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1, "checkbox_2")) RB From peter.bulychev at gmail.com Mon Mar 17 07:28:31 2008 From: peter.bulychev at gmail.com (Peter Bulychev) Date: Mon, 17 Mar 2008 14:28:31 +0300 Subject: question about module compiler: line numbers and positions of substring, which are covered by AST nodes In-Reply-To: References: Message-ID: I will answer my own question. Maybe it will be useful for someone else in future. Compiler module just transforms parse trees into the abstract syntax trees. Parse trees are built using Parser module. Parser module is not pure Python module, it is written in C language and Python loads it as .so (or .dll) library. There is a required field in C implementation of parse trees ( node.n_col_offset), but it is unaccessible from Python. Therefore to get the information about the position of some lexem in the AST built by module Compiler, you have to perform the following steps: *) Get the Python sources *) Modify the Parser module *) Build Python (or just parser.so) *) Drag the node.n_col_offset field to the Compiler module It should be noted that this solution will not be cross-platform. Good luck! 2008/3/16, Peter Bulychev : > > Hello. > > I use standard module Compiler to build ASTs of Python code. > > Given AST subtree I want to restore coordinates of substring in the input, > which is covered by the subtree. > > Example: > Suppose, the input is 'a+(b+c)'. It is parsed to the tree ADD(a, ADD(b,c)) > by module Compiler. > I want to have a function, which given ADD(b,c) will return the > coordinates of the substring '(b+c)'. > > Module Compiler provides only line numbers for each node. But even this > information is incorrect: only the first line of multi-lined statements is > stored. > > What is the easiest way of doing what I want? > As I understand, module Compiler is automatically generated by some parser > generator. Maybe I can modify it? > > -- > Best regards, > Peter Bulychev. -- Best regards, Peter Bulychev. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Mar 17 15:20:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Mar 2008 15:20:25 -0400 Subject: how long do the different python-vm bytecodes take? References: <0555ed9f-c5f1-4d0b-afbd-439c863e9439@s13g2000prd.googlegroups.com> Message-ID: "GHUM" wrote in message news:0555ed9f-c5f1-4d0b-afbd-439c863e9439 at s13g2000prd.googlegroups.com... |I looked at the virtual machine bytecode of python programs: | | def f(whatever): | text="Hallo"+whatever | return text | | import dis | dis.dis(f) | 2 0 LOAD_CONST 1 ('Hallo') | 3 LOAD_FAST 0 (whatever) | 6 BINARY_ADD | 7 STORE_FAST 1 (text) | | 3 10 LOAD_FAST 1 (text) | 13 RETURN_VALUE | | | and now I am curious: how long does one LOAD_FAST take? I am thinking | of something like back in the assembler-world, where there existed | tables like: | | LDA -> 2 cycles | BNE -> 2 cycles, 3 on branch | | of course, the "real time" is dependand on many factors, esp. the | speed of the processor. | But ... is there a relative scale somewhere? | | Somehting like | | LOAD_CONST 1 arbitraryUnit | LOAD_FAST 1.9 arbitraryUnits | RETURN_VALUE 8.0 arbitraryUnits | | ??? | | my Google queries did not reveal anything usefull so far. Any hints? There is no such table that I know of and there hardly could be, as the relative times will depend on hardware, OS, C compiler (including optimization settings), as well as the objects on the stack to be operated on. Consider BINARY_ADD. Pretty fast for 2 ints, arbitrarily slow for arbitrary user-class objects. There are a few things knowns, such as _FAST versions being faster that other versions, and that eliminating unneeded codes is faster than not. Developers usually test proposed 'speedup' changes on several platforms. tjr From misterwang at gmail.com Tue Mar 18 21:35:54 2008 From: misterwang at gmail.com (Peter Wang) Date: Tue, 18 Mar 2008 18:35:54 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> <8fc48d27-1496-4240-a26c-708b6e9aa440@s8g2000prg.googlegroups.com> Message-ID: On Mar 18, 6:51 pm, Ivan Illarionov wrote: > > That's another new step for me. Any ideas where to start? > > http://docs.python.org/ext/simpleExample.html > > And look into the source of existing extensions. PIL and PyCairo are > the best in your situation. You shouldn't be afraid of doing raster graphics in Python; you'll just need to be familiar with Numpy. You can easily compose layers, mask out operations to only happen on one channel, etc., and code it all up in Python while getting C-level speed. The gotcha, if you use PIL, is that you're going to have to use tostring() and fromstring() to get the array data back and forth between numpy and PIL. An alternative is to use openGL, as others have suggested, and blit into a texture. If you use pyglet, for instance, you can use Andrew Straw's pygarrayimage module to convert a numpy array directly into a texture. I wouldn't recommend Cairo for doing pixel-level ops, since it is a vector graphics library. -Peter From NO_Kroeger at gmx.de Mon Mar 3 11:04:50 2008 From: NO_Kroeger at gmx.de (=?ISO-8859-1?Q?Nils_Oliver_Kr=F6ger?=) Date: Mon, 03 Mar 2008 17:04:50 +0100 Subject: Exception or not In-Reply-To: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> References: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Message-ID: <47CC21A2.6070705@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I don't think it is a good pattern because you are kind of mixing exceptions with return codes which makes the code a lot less readable later on. I personally would strongly opt for return codes in this case as one would intuitively expect a function named validateThisAndThat to return the result of a validation. This might me a simple true/false, a numeric code with 0=OK, 1=password not correct, 2=user does not exist or a string, whatever you need. In my opinion, such a function should raise an exception if it is unable to fullfill its task. For example lost connection to user database or things like that. A function should never propagate an expected result as an exception. Greetings Nils Monica Leko schrieb: | Suppose you have some HTML forms which you would like to validate. | Every field can have different errors. For example, this are the | forms: | | username | password | etc | | And you want to validate them with some class. Is this good pattern: | | class Foo(object): | def validateUsername(username): | if username isn't correct: | raise ValidationError() | def validatePassword(password): | if password isn't correct: | raise ValidationError() | | code: | try: | usernameError = validateUsername() | except ValidationError: | usernameError = error from exception | try: | passwordError = validatePassword() | except ValidationError: | passwordError = error from exception | | So, if there wasn't any errors, usernameError and passwordError both | contains None, and there was error, both contains some string? Should | I use exception or just return None or some string without | exception? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFHzCGhzvGJy8WEGTcRAvbGAJoDjn39xCmiOLmkc//0RTfeVXJFTACePRIG uYoDiQBZwRsShUn60LN/9oQ= =zvAY -----END PGP SIGNATURE----- From bignose+hates-spam at benfinney.id.au Sun Mar 2 16:31:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 03 Mar 2008 08:31:28 +1100 Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: <87bq5wak3z.fsf@benfinney.id.au> Kay Schluehr writes: > On 2 Mrz., 06:53, Ben Finney > wrote: > > > One of the stated goals of the migration is that the '2to3' > > program will only migrate Python 2.6 code -> Python 3.0 code. > > Yes, I know. Why? > > "The master said so" isn't an entirely satisfying answer. The people putting in the work to write '2to3' said so. -- \ "Courteous and efficient self-service." ?Caf? sign, southern | `\ France | _o__) | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 5 07:31:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 05 Mar 2008 13:31:01 +0100 Subject: Altering imported modules In-Reply-To: References: Message-ID: <47ce9279$0$27486$426a34cc@news.free.fr> Tro a ?crit : > Hi, list. > > I've got a simple asyncore-based server. However, I've modified the asyncore > module to allow me to watch functions as well as sockets. The modified > asyncore module is in a specific location in my project and is imported as > usual from my classes. > > Now I'd like to use the tlslite library, which includes an asyncore mixin > class. However, tlslite imports "asyncore", which doesn't include my own > modifications. > > I'd like to know if it's possible to make tlslite load *my* asyncore module > without changing any of the tlslite code. Not sure this apply to your case (depends on how asyncore is implemented and the exact "modifications"), but monkeypatching is a possible solution. http://en.wikipedia.org/wiki/Monkey_patch http://wiki.zope.org/zope2/MonkeyPatch http://mail.python.org/pipermail/python-dev/2008-January/076194.html HTH From duncan.booth at invalid.invalid Thu Mar 20 09:42:22 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Mar 2008 13:42:22 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: >> By default Python on Windows allows you to open a file for reading >> unless you specify a sharing mode which prevents it: > > But the OP is talking about another process having opened the file for > WRITING, not reading. It's that other process that has exclusive access, > and the OP was trying to determine when it was safe to attempt opening > the file according to whether or not it was still growing. > No, unless the other process has specified that it wants exclusive access there is nothing stopping his process also opening the file. That's why he has to specify when he opens it that he wants exclusive access: then it doesn't matter what the other process does, he won't be able to open it until the other process has closed the file. This all of course assumes that the other process writes the file in one single atomic chunk. If it were to create it and then separately open and write to it then all bets are off. From nospam at nospam.com Mon Mar 31 09:33:10 2008 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 31 Mar 2008 15:33:10 +0200 Subject: wxPython; adding a grid to a panel References: Message-ID: On Mon, 31 Mar 2008 11:01:19 +0100, "Moynes James" wrote: >In the script below I have added two panels to a frame. I want to >display the grid in one panel (and later on add other widgets to the >other panel), but I cannot get the grid to display properly. I'm learning wxPython as well. Could it be that you're using wx.PySimpleApp instead of App? From davids at evertech.com.au Fri Mar 14 20:15:47 2008 From: davids at evertech.com.au (David S) Date: Sat, 15 Mar 2008 00:15:47 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: By mapping network drives in windows I can get past these issues with path names. Thanks, David "Tim Golden" wrote in message news:mailman.1949.1205496184.9267.python-list at python.org... > David S wrote: >> Gets me further but still seems to be issue with space after 'Program' as >> code tries to run 'C:\Program'. Don't understand what is going on here... > > Slight apologies as I haven't followed this thread closely, but using the > Acrobat Reader executable, which is, I think, good enough for the > purposes of illustration: > > > import os > import subprocess > > filename = r"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe" > doc = r"C:\Program Files\Adobe\Reader 8.0\Resource\ENUtxt.pdf" > > print os.path.isfile (filename) > > os.system (filename + " " + doc) > > os.system ('"%s" "%s"' % (filename, doc)) > > subprocess.call ([filename, doc]) > > > > os.path.isfile succeeds > os.system (filename) fails as your code does > os.system ('"%s"' ...) fails even though both strings are requoted > subprocess.call (filename) succeeds > > The latter, at least, is because the subprocess module > has some special-case handling for exactly this situation > on MS Windows, while os.system doesn't. > > Now, ultimately, I don't know if this really helps your > exact situation but it least it should be clear what will > and what won't work. Conclusion: use subprocess.call if > you can. > > TJG From zooko at zooko.com Tue Mar 25 22:41:10 2008 From: zooko at zooko.com (zooko) Date: Tue, 25 Mar 2008 19:41:10 -0700 Subject: announcing allmydata.org "Tahoe", the Least-Authority Filesystem, v1.0 Message-ID: <7FD79D75-5EFF-40AD-B958-95F1881B47EC@zooko.com> Folks: This open source project is written entirely in Python, except of course for the performance-intensive or system-integration parts that are written in C/C++ -- things like erasure coding and encryption. Python has served as well. It is elegant enough and simple enough, and the implementation is mature and efficient enough. And, there is a vast array of compatible, open-source tools and packages that work well with Python. The company that sponsors this open source project, http:// allmydata.com/ , opens its doors to new customers tomorrow, using Tahoe for its new storage grid. Regards, Zooko ANNOUNCING Allmydata.org "Tahoe", the Least-Authority Filesystem, v1.0 We are pleased to announce the release of version 1.0 of the "Tahoe" Least Authority Filesystem. The "Tahoe" Least Authority Filesystem is a secure, decentralized, fault-tolerant filesystem. All of the source code is available under a Free Software, Open Source licence (or two). This filesystem is encrypted and distributed over multiple peers in such a way it continues to function even when some of the peers are unavailable, malfunctioning, or malicious. A one-page explanation of the security and fault-tolerance properties that it offers is visible at: http://allmydata.org/source/tahoe/trunk/docs/about.html We believe that this version of Tahoe is stable enough to rely on as a permanent store of valuable data. The version 1 branch of Tahoe will be actively supported and maintained for the forseeable future, and future versions of Tahoe will retain the ability to read files and directories produced by Tahoe v1.0 for the forseeable future. This release of Tahoe will form the basis of the new consumer backup product from Allmydata, Inc. -- http://allmydata.com . This is the successor to Allmydata.org "Tahoe" Least Authority Filesystem v0.9, which was released March 13, 2008 [1]. Since v0.9 we've made the following changes: * Use an added secret for convergent encryption to better protect the confidentiality of immutable files, and remove the publically readable hash of the plaintext (ticket #365). * Add a "mkdir-p" feature to the WAPI (ticket #357). * Many updates to the Windows installer and Windows filesystem integration. Tahoe v1.0 produces files which can't be read by older versions of Tahoe, although files produced by Tahoe >= 0.8 can be read by Tahoe 1.0. The reason that older versions of Tahoe can't read files produced by Tahoe 1.0 is that those older versions require the file to come with a publically-readable hash of the plaintext, but exposing such a hash is a confidentiality leak, so Tahoe 1.0 does not do it. WHAT IS IT GOOD FOR? With Tahoe, you can distribute your filesystem across a set of computers, such that if some of the computers fail or turn out to be malicious, the filesystem continues to work from the remaining computers. You can also share your files with other users, using a strongly encrypted, capability-based access control scheme. Because this software is the product of less than a year and a half of active development, we do not categorically recommend it for the storage of data which is extremely confidential or precious. However, we believe that the combination of erasure coding, strong encryption, and careful engineering makes the use of this software a much safer alternative than common alternatives, such as RAID, or traditional backup onto a remote server, removable drive, or tape. This software comes with extensive unit tests [2], and there are no known security flaws which would compromise confidentiality or data integrity. (For all currently known security issues please see the Security web page: [3].) This release of Tahoe is suitable for the "friendnet" use case [4] -- it is easy to create a filesystem spread over the computers of you and your friends so that you can share files and disk space with one another. 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" 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.0. The Transitive Grace Period Public Licence says that you may distribute proprietary derived works of Tahoe without releasing the source code of that derived work for up to twelve months, after which time you are obligated to release the source code of the derived work under the Transitive Grace Period Public Licence. See the file "COPYING.TGPPL.html" for the terms of the Transitive Grace Period Public Licence, version 1.0. (You may choose to use this package under the terms of either licence, at your option.) INSTALLATION Tahoe works on Linux, Mac OS X, Windows, Cygwin, and Solaris. For installation instructions please see "docs/install.html" [5]. HACKING AND COMMUNITY Please join us on the mailing list [6] to discuss uses of Tahoe. Patches that extend and improve Tahoe are gratefully accepted -- the RoadMap page [7] shows the next improvements that we plan to make and CREDITS [8] lists the names of people who've contributed to the project. The wiki Dev page [9] contains resources for hackers. SPONSORSHIP Tahoe is sponsored by Allmydata, Inc. [10], a provider of consumer backup services. Allmydata, Inc. contributes hardware, software, ideas, bug reports, suggestions, demands, and money (employing several allmydata.org Tahoe hackers and instructing them to spend part of their work time on this free-software project). We are eternally grateful! Zooko O'Whielacronx on behalf of the allmydata.org team March 25, 2008 San Francisco, California, USA [1] http://allmydata.org/trac/tahoe/browser/relnotes.txt?rev=2315 [2] http://allmydata.org/trac/tahoe/wiki/Dev [3] http://allmydata.org/trac/tahoe/wiki/Security [4] http://allmydata.org/trac/tahoe/wiki/UseCases [5] http://allmydata.org/source/tahoe/trunk/docs/install.html [6] http://allmydata.org/cgi-bin/mailman/listinfo/tahoe-dev [7] http://allmydata.org/trac/tahoe/roadmap [8] http://allmydata.org/trac/tahoe/browser/CREDITS?rev=2345 [9] http://allmydata.org/trac/tahoe/wiki/Dev [10] http://allmydata.com From patricksamal at googlemail.com Thu Mar 20 07:55:35 2008 From: patricksamal at googlemail.com (patricksamal at googlemail.com) Date: Thu, 20 Mar 2008 04:55:35 -0700 (PDT) Subject: Games, Software, Disk Storege and other are totally Free , Free ...................... Message-ID: <3a15f41d-ff33-44b9-98d4-ce4917b5e6a7@i12g2000prf.googlegroups.com> In exchange for having their Internet browsing and purchasing activity observed, members have access to free software downloads and other benefits including: * Free online disk storage * Free software to password protect important documents and folders * Free software to help maintain online privacy * Over 450 free online games * Free screensavers * Free sweepstakes entries * Points redeemable for merchandise and gift cards Membership is free and members' personal information will remain confidential in accordance with our privacy policy. http://www.kqzyfj.com/click-1944618-10402121 http://www.kqzyfj.com/click-1944618-10462173 From castironpi at gmail.com Tue Mar 4 22:50:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 19:50:56 -0800 (PST) Subject: multiplication of lists of strings References: Message-ID: <61170ee9-b716-419f-860a-e08f125d6427@s8g2000prg.googlegroups.com> On Mar 4, 9:46?pm, Jason Galyon wrote: > Gabriel Genellina wrote: > > En Tue, 04 Mar 2008 23:50:49 -0200, Jason escribi?: > > >> How could I return a list or tuple of each unique combination of a given > >> set of lists (perhaps from a dict or a list). ?This means the number of > >> lists are not known nor is the length of each. > > > Use the Google interfase for this group: > >http://groups.google.com/group/comp.lang.python/ > > Type "unique combinations lists" in the text box; press "Search in this > > group". The very first result contains some answers to your question. > > found it, the referenced cookbook recipe is perfect. > > Thanks, Gabriel That reminds me: Is there a generic 'relation' pattern/recipie, such as finding a computer that's "paired" with multiple users, each of who are "paired" with multiple computers, without maintaining dual- associativity? Good: py> user.getcomputers() [ Compie1, Compie2 ] Bad: user._computers.add( compieN ) compieN._users.add( user ) ? From Glich.Glich at googlemail.com Mon Mar 24 12:37:04 2008 From: Glich.Glich at googlemail.com (Glich) Date: Mon, 24 Mar 2008 09:37:04 -0700 (PDT) Subject: python, dbus and pointers help. Message-ID: <16059cb8-a182-40ff-9617-a8b6708e1183@s19g2000prg.googlegroups.com> ''' hello, using pidgin instant messenger I can get the value of 'message' when one is being sent but, I dont know how to chage the value of message. from the documentation (http://developer.pidgin.im/doxygen/dev/html/ conversation-signals.html#sending-im-msg): _____________________________ sending-im-msg: Emitted before sending an IM to a user. message is a pointer to the message string, so the plugin can replace the message before being sent. _____________________________ I think python get's a copy of the message (this is just a guess). How can I change the message before it is sent? Thanks. The code is taken from http://developer.pidgin.im/wiki/DbusHowto#Furtherreading and changed only a small amount. ''' #!/usr/bin/env python def cb_func(account, rec, message): #change message here somehow? print message import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() bus.add_signal_receiver(cb_func, dbus_interface="im.pidgin.purple.PurpleInterface", signal_name="SendingImMsg") loop = gobject.MainLoop() loop.run() From r&d2 at dave-tech.it Sat Mar 22 09:48:22 2008 From: r&d2 at dave-tech.it (llandre) Date: Sat, 22 Mar 2008 14:48:22 +0100 Subject: [RFC] How to implement command line tool integrating parsing engine Message-ID: <47E50E26.8090704@dave-tech.it> Hi all, I'd like to have some advices about how to implement a program that has the following requirements: - it must run both on linux and windows PC - it must interact with an electronic device connected to the PC through serial cable by sending/receiving some command strings and taking different actions depending on device responses; these strings and actions must be described in a text file (a sort of script) editable by user with a simple text editor; the language used to described this algorithm should be as simple as possible - initially the program must be written in the form of simple command line tool that is invoked like this: program - in the future, it must be possible to develop a graphical frontend on top of it; the resulting look&feel should be similar on linux and windows. In this mailing list I was adviced to use python: http://thread.gmane.org/gmane.comp.boot-loaders.u-boot/37939 As I never used python, I ask you: 1) about the script file, which language - for which a parsing engine is already available in python - do you suggest? 2) about the graphical frontend, which graphical libraries do you recommend? Thanks a lot in advance, llandre DAVE Electronics System House - R&D Department web: http://www.dave.eu email: r&d2 at dave-tech.it From jeff at schwabcenter.com Wed Mar 19 00:03:16 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 21:03:16 -0700 Subject: ftp recursively In-Reply-To: References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: Gabriel Genellina wrote: > En Tue, 18 Mar 2008 18:25:28 -0300, Jeff Schwab > escribi?: > >> I need to move a directory tree (~9GB) from one machine to another on >> the same LAN. What's the best (briefest and most portable) way to do >> this in Python? > > See Tools/scripts/ftpmirror.py in your Python installation. Thank you, that's perfect. Thanks to Arnaud as well, for the pointer to ftplib, which might useful for other purposes as well. Per the earlier advice of other posters (including one whose message seems mysteriously to have disappeared from c.l.python), I just stuck with the Unix tools I already knew: I ended up tarring the whole 9GB, ftping it as a flat file, and untarring it on the other side. Of course, the motivation wasn't just to get the files from point A to point B using Unix (which I already know how to do), but to take advantage of an opportunity to learn some Python; next time, I'll try the ftpmirror.py script if it's generic enough, or ftplib if there are more specific requirements. From Jeff.Goldfinkle at gmail.com Thu Mar 6 02:21:07 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Wed, 5 Mar 2008 23:21:07 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: On Mar 5, 11:27 pm, Mensanator wrote: > On Mar 5, 2:25 pm, "Jeff.Goldfin... at gmail.com" > > wrote: > > Hi All > > > Is there a simple way to twiddle the bits of a float? In particular, I > > would like to round my float to the n most significant bits. > > > For example - 0.123 in binary is 0.000111111 > > Rounding to 4 bits I get 0.0001. > > > I can pack and unpack a float into a long > > e.g. > > struct.unpack('I',struct.pack('f',0.123))[0] > > but then I'm not sure how to work with the resulting long. > > > Any suggestions? > > Here's one. > > >>> import gmpy > > # create a base 10 float>>> f = gmpy.mpf('123.456') > >>> f > > mpf('1.23456e2') > > # format in base 2, fixed point>>> f2 = gmpy.fdigits(f,2,0,0,99) > >>> f2 > > '1111011.01110100101111000110101001111110111110011101101100100010111' > > # seperate the characteristic from the mantissa > > >>> fs = f2.split('.') > > # re-assemble with the mantissa truncated to desired # of bits>>> f3 = fs[0]+'.'+fs[1][:4] > >>> f3 > > '1111011.0111' > > # convert the string back to a base 10 float>>> f4 = gmpy.mpf(f3,0,2) > >>> print f4 > > 123.4375 > > # check: print as base 2 and see how many digits are past radix point>>> print gmpy.fdigits(f4,2,0,0,99) > > 1111011.0111 excellent - thanks that does exactly what I need. From aboudouvas at panafonet.gr Sat Mar 29 10:16:50 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 29 Mar 2008 07:16:50 -0700 (PDT) Subject: Psyco alternative References: <10d4e6b6-71f3-4c22-8b13-17dd32a4374f@c19g2000prf.googlegroups.com> Message-ID: On 29 ???, 16:03, Luis M. Gonz?lez wrote: > On 27 mar, 13:14, king kikapu wrote: > > > > One reason attention is going to PyPy instead of Psyco... > > > > Jean-Paul > > > I had a look at PyPy, it, indeed, have a very long way to go so we can > > consider it an alternative. > > To see how it?s going, you can check this out:http://morepypy.blogspot.com/ Thanks, that is my source already! From pavlovevidence at gmail.com Thu Mar 6 22:39:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 19:39:45 -0800 (PST) Subject: Looking for very light weight template library (not framework) References: Message-ID: On Mar 6, 8:56 pm, "Malcolm Greene" wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated. You could do something like this with a single function. For instance: import re def apply_template(text,env): def eval_in_env(m): return str(eval(m.group(1),env)) return re.sub(r"{{(.*?)}}",eval_in_env,text) Where env is a dict with the variables you want to evaluate (locals() could be a good choice for this). Standard warning about usage of eval: don't use this with untrusted input or Bad Things can happen. Carl Banks From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 13 04:31:09 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Mar 2008 09:31:09 +0100 Subject: Class Inheritance In-Reply-To: References: Message-ID: <47d8e611$0$14050$426a74cc@news.free.fr> Andrew Rekdal < a ?crit : > I am trying to bring functions to a class by inheritance... for instance in > layout_ext I have.. > > > --- layout_ext.py--------- > class Layout() > def...some function that rely on css in Layout.py It shouldn't, definitively. The Layout instance should have a reference on the CSS instance, ie: # layout_ext.py class LayoutExt(object): def __init__(self, css): self.css = css def some_function(self): do_something_with(self.css) # layout.py from layout_ext import LayoutExt from CSS import CSS class Layout(LayoutExt): def __init__(self, css): LayoutExt.__init__(self, css) # etc > def... > > ---EOF-- > > in the main application file I have... > ----Layout.py--- > from layout_ext import Layout > from CSS import CSS > css = CSS() > class Layout(Layout) You will have a problem here - this class statement will shadow the Layout class imported from layout_ext. Remember that in Python, def and class statements are executed at runtime and that they bind names in current namespace - here, the 'class Layout' statement rebinds the name 'Layout' in the Layout module's namespace. > def __init__ > more code..... > > ----EOF---- > > > Problem is layout_ext and Layout code is dependant on a Class instance > 'css'. Whenever the CSS instance it parses a file, this means that I would > have to parse the file twice?? Why is this? Can I do something like pass an > already created instance to the import? Wrong solution, obviously. cf above for the most probably correct one. HTH From steve at REMOVE-THIS-cybersource.com.au Sat Mar 22 19:48:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 22 Mar 2008 23:48:35 -0000 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <3ee39d9f-dde7-432b-bc3c-5b8dd935e3f4@a70g2000hsh.googlegroups.com> Message-ID: <13ub6mjkfu4dkf6@corp.supernews.com> On Sat, 22 Mar 2008 16:16:03 -0700, bearophileHUGS wrote: > bearophile: >> A more computer-friendly (and Pythonic) syntax may be ('are' is a >> keyword): > > Sorry for causing confusion, I was just thinking aloud. English isn't my > first language, and sometimes I slip a bit. There is nothing wrong with what you said originally. You said "syntax MAY be" -- that's obvious to those who know English that you are talking about a hypothetical keyword. Admittedly non-English speakers may not pick up on the nuances of English, but that's not your fault. Your English is very good, better than some native English speakers. What is your native language? -- Steven From fn681 at ncf.ca Thu Mar 6 18:06:40 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Thu, 06 Mar 2008 18:06:40 -0500 Subject: Internet Explorer 8 beta release In-Reply-To: References: Message-ID: shsha wrote: > Internet Explorer 8 beta release is for developers, and Microsoft's > Dean Hachamovitch promised at MIX08 that IE8 will make it easier to > build Web sites for multiple browsers and stop wasting developers' > time. Microsoft's IE8 features Activities for looking up information > and Webslices to watch portions of Web sites for updates. > > more about MS > > http://www.toptechnews.com/story.xhtml?story_id=0120013PBF8O > > _____________ > get wild ....all the action http://www.getaction4ever.com Isn't compliance with the W3C standard the best way of achieving multiple browser rendering? Colin W. From nospam at nospam.com Wed Mar 12 03:20:16 2008 From: nospam at nospam.com (Gilles Ganault) Date: Wed, 12 Mar 2008 08:20:16 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <99cd$47d66262$83aef404$29936@news1.tudelft.nl> Message-ID: <5u0ft3tqf835s4fcj9mmhp5jjn6mtvb1us@4ax.com> On Tue, 11 Mar 2008 11:43:45 +0100, Stef Mientki wrote: >Funny, compared to Delphi-7, >I found the grid in wxPython much richer ;-) You haven't tried the better alternatives I had in mind: http://www.x-files.pl http://www.bergsoft.net http://www.tmssoftware.com http://www.scalabium.com/smdbgrid.htm http://www.tkweb.eu/en/delphicomp/kgrid.html http://www.devexpress.com/Products/VCL/ExQuantumGrid/ From troworld at gmail.com Thu Mar 6 15:29:05 2008 From: troworld at gmail.com (Tro) Date: Thu, 6 Mar 2008 15:29:05 -0500 Subject: Altering imported modules In-Reply-To: <47ce9279$0$27486$426a34cc@news.free.fr> References: <47ce9279$0$27486$426a34cc@news.free.fr> Message-ID: <200803061529.05268.troworld@gmail.com> On Wednesday 05 March 2008, Bruno Desthuilliers wrote: > Tro a ?crit : > > Hi, list. > > > > I've got a simple asyncore-based server. However, I've modified the > > asyncore module to allow me to watch functions as well as sockets. The > > modified asyncore module is in a specific location in my project and is > > imported as usual from my classes. > > > > Now I'd like to use the tlslite library, which includes an asyncore mixin > > class. However, tlslite imports "asyncore", which doesn't include my own > > modifications. > > > > I'd like to know if it's possible to make tlslite load *my* asyncore > > module without changing any of the tlslite code. > > Not sure this apply to your case (depends on how asyncore is implemented > and the exact "modifications"), but monkeypatching is a possible solution. > > http://en.wikipedia.org/wiki/Monkey_patch > http://wiki.zope.org/zope2/MonkeyPatch > http://mail.python.org/pipermail/python-dev/2008-January/076194.html Ooh. I didn't know this technique had a name. But that's basically how I'm modifying the built-in asyncore in my own class. I override its poll() and poll2() methods to do something extra. However, the issue with tlslite is that it imports the regular asyncore instead of the one I wrote, which means that I'd have to somehow monkeypatch its "import" statement. I'm guessing that means simply monkeypatching both the original asyncore module AND the tlslite module's asyncore attribute with my own version. Thanks, Tro From matthias.goetz.23 at googlemail.com Sat Mar 22 17:37:45 2008 From: matthias.goetz.23 at googlemail.com (=?ISO-8859-1?Q?Matthias_G=F6tz?=) Date: Sat, 22 Mar 2008 22:37:45 +0100 Subject: Problem with complex numbers Message-ID: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> Hello python fans, I have a small problem using python and complex math. The pow(complex,complex) function in the windows python version doesn't have the same semantic as the source version. (I have downloaded : - Python 2.5.2 compressed source tarball(for Unix or OS X compile) - Python 2.5.2 Windows installer ) If found in Complex.py: def __pow__(self, n, z=None): if z is not None: raise TypeError, 'Complex does not support ternary pow()' if IsComplex(n): if n.im: if self.im: raise TypeError, 'Complex to the Complex power' else: return exp(math.log(self.re)*n) n = n.re r = pow(self.abs(), n) phi = n*self.angle() return Complex(math.cos(phi)*r, math.sin(phi)*r) which mean for example if i calculate z1 power z2 (z1,z2 are complex numbers), and z1 and z2 has imaginary parts not equals zero, i must get an TypeError. Is that right? But i tried that in the IDLE python shell by doing this >>> z1=complex(1,2) >>> z2=complex(2,3) >>> z1**z2 (-0.01513267242272265-0.1798674839133349j) >>> and this is everything unlike an TypeError. So if somebody can help me, it would be nice. Thanks. Matze (Sorry for bad english, I'am german) -------------- next part -------------- An HTML attachment was scrubbed... URL: From danb_83 at yahoo.com Tue Mar 25 22:30:05 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 25 Mar 2008 19:30:05 -0700 (PDT) Subject: python hash() function References: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Message-ID: <68f6845a-f499-4527-a744-cd7c447f7aab@e6g2000prf.googlegroups.com> On Mar 25, 9:22 pm, "Terry Reedy" wrote: > "Alvin Delagon" wrote in message > > news:7a01f6c00803251905j4b12633m65b2cde0f3037854 at mail.gmail.com... > | Hello, > | > | >>> hash("foobar") > | -1969371895 > | > | Anyone can explain to me how the hash() function in python does its work? > A > | link to its source could help me a lot also. I'm looking for a way to > | replicate this function in php. Thanks in advance. > > If not part of your installation, start with svn.python.org and click > browse. I would look for builtins.c or somesuch. It's in stringobject.c: static long string_hash(PyStringObject *a) { register Py_ssize_t len; register unsigned char *p; register long x; if (a->ob_shash != -1) return a->ob_shash; len = Py_Size(a); p = (unsigned char *) a->ob_sval; x = *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= Py_Size(a); if (x == -1) x = -2; a->ob_shash = x; return x; } From michael.wieher at gmail.com Fri Mar 7 09:23:28 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 7 Mar 2008 08:23:28 -0600 Subject: hidden built-in module In-Reply-To: <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> Message-ID: 2008/3/7, koara : > > On Mar 5, 1:39 pm, gigs wrote: > > koara wrote: > > > Hello, is there a way to access a module that is hidden because > > > another module (of the same name) is found first? > > > > > More specifically, i have my own logging.py module, and inside this > > > module, depending on how initialization goes, i may want to do 'from > > > logging import *' from the built-in logging. > > > > > I hope my description was clear, cheers. > > > > > I am using python2.4. > > > > you can add your own logging module in extra directory that have > __init__.py and > > import it like: from extradirectory.logging import * > > > > and builtin: from logging import * > > > Thank you for your reply gigs. However, the point of this namespace > harakiri is that existing code which uses 'import logging' ... > 'logging.info()'... etc. continues working without any change. > Renaming my logging.py file is not an option -- if it were, i wouldn't > bother naming my module same as a built-in :-) > > Cheers. > > -- > http://mail.python.org/mailman/listinfo/python-list > I've never had a problem like this, but I'd imagine that you could delve into the inner-workings of import itself and figure a way to make this happen. There's probably a logical-order search path it follows, and if you can find a way to insert your module before the other, in that path, or modify the path and point its first entry at say, a directory containing only your module, you'd be in business. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sat Mar 8 21:36:20 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 8 Mar 2008 18:36:20 -0800 Subject: Green's Function In-Reply-To: <501978.67770.qm@web53602.mail.re2.yahoo.com> References: <501978.67770.qm@web53602.mail.re2.yahoo.com> Message-ID: > I am new to Python and trying to solve the Hamiltonian of a linear chair > of atoms using green's function. > Does anyone know any pre-existing library functions and literature that > could be helpful? You might find this helpful: http://scipy.org/ HTH, Daniel From waltbrad at hotmail.com Mon Mar 17 13:52:52 2008 From: waltbrad at hotmail.com (waltbrad) Date: Mon, 17 Mar 2008 10:52:52 -0700 (PDT) Subject: questions about named pipe objects... References: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> Message-ID: On Mar 17, 1:50 pm, waltbrad wrote: > > I then wanted to start the child process first and see what happened > when I ran the parent. Well that works but the reads come out in > random order. Well, I take that back. I accidentally had two 'parent' processes open. So, the reads were sequential but split between two windows. From deets at nospam.web.de Thu Mar 27 05:34:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 10:34:59 +0100 Subject: subtract dates with time module References: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> Message-ID: <65182uF2e0id5U2@mid.uni-berlin.de> barronmo wrote: > I'm trying to get the difference in dates using the time module rather > than datetime because I need to use strptime() to convert a date and > then find out how many weeks and days until that date. I'm a beginner > so any help would be appreciated. Here is the code: Use strptime to create time-tuples, and use the fields in there to create datetime-objects. Then do the math with them. Diez From bbxx789_05ss at yahoo.com Fri Mar 21 00:17:36 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 20 Mar 2008 21:17:36 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr modulein Py3.0] References: <7xy78dg79e.fsf@ruckus.brouhaha.com> Message-ID: On Mar 20, 8:42?pm, "Terry Reedy" wrote: > "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message > > news:7xy78dg79e.fsf at ruckus.brouhaha.com... > | "Daniel Fetchinson" writes: > | > Is it just me or others also think that it would be a major loss to > | > remove tkinter from the python core? > | > | That would be terrible. ?Every time I've tried to use one of the other > | packages it has led to installation hell. ?Tkinter isn't great, but > | it's extremely useful to have a gui module that's present > | automatically in every compete Python installation and that is > | reasonably cross platform. ?I can write a Python/Tkinter app under > | Linux and send it to Windows users and they can run it after a single, > | very simple Python installation from the Windows .msi. ?I have no > | Windows development tools whatsoever and very limited access to > | Windows boxes, so any Python code I deploy on Windows can't rely on > | any non-Python code outside of the stdlib. > | > | Also, because of tkinter's inherent limitations, I have the impression > | that upgrading it to the latest and greatest tcl/tk release wouldn't > | improve it much over the useful but low-rent module that it already is. > | Therefore, that supposed "benefit" of splitting it out to an external > | package is not much of a benefit. > | > | One of Python's traditionally best attractions has been the depth of > | its standard libraries, and backing away from that would be plain > | self-destructive. ?Python needs more stuff in its stdlib, not less. > | If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard > | distro. ?If that happens (i.e. some new toolkit is brought in and > | declared to be the standard) then it might be ok to drop Tkinter but > | it certainly shouldn't be dropped without a replacement. > > I think this nicely summarizes the case against dropping tkinter (and > indeed, the case against shrinking the stdlib), like some devs (who mostly > une *nix) want to do. ?Perhaps someone can forward it to the lib-sig and/or > the Py3-devel lists. > > tjr I think one of the advantages that python has over ruby is that python comes with tkinter. For me, tkinter worked from the get go after I installed python. I don't know if that's because my os already had the necessary tcl/tk framework set up or not, but not having to go through installation hell to get it working was nice. On the other hand, Ruby doesn't come with a gui framework. And trying to get Ruby tk working is a nightmare that I suspect many new programmers will never accomplish, and therefore gui programming will largely be inaccessible to them. Since the adherents to the various languages like to list the reasons why their language is better, removing tkinter from python will only will make python's list shorter. From Lie.1296 at gmail.com Sun Mar 9 05:25:24 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 01:25:24 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> On Mar 9, 3:27?am, castiro... at gmail.com wrote: > To Lie: > > > Personally I preferred a code that has chosen good names but have > > little or no comments compared to codes that makes bad names and have > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > I won't like it, it's that I can't. ?You know, in linguistics, there's > what's called 'code switching', which is switching between two > languages you know midstream. ?People can understand 'hear' a language > but not speak it. ?If you speak it, . ?If comments aren't > the 'short version', then patience is the problem. ?There's not one > word for lots and lots of things. ?Examples on backorder. But I much prefer it that the code has good names AND concise comments, not too short and not too long that it becomes obscure. If the code is complex, that it's hard to explain in a few sentences, it might be a good idea to refactor it. If I have to choose between bad names + twenty pages of documentation and good names + a paragraph of short documentation, I chose the latter. From sam at mas.pl Mon Mar 10 10:47:26 2008 From: sam at mas.pl (sam) Date: Mon, 10 Mar 2008 15:47:26 +0100 Subject: parsing directory for certain filetypes In-Reply-To: References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: Robert Bossy napisa?(a): > I leave you the exercice to add .doc files. But I must say (whoever's > listening) that I was a bit disappointed that glob('*.{txt,doc}') didn't > work. "{" and "}" are bash invention and not POSIX standard unfortunately -- UFO Occupation www.totalizm.org From castironpi at gmail.com Thu Mar 27 17:45:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 14:45:10 -0700 (PDT) Subject: Determine size of string in bytes References: <083180d3-3e7c-4db5-926f-b7528201a3b8@a22g2000hsc.googlegroups.com> Message-ID: <1677c156-f439-4999-ad4a-0e53776fb21a@s37g2000prg.googlegroups.com> On Mar 27, 4:10?pm, John Machin wrote: > On Mar 28, 6:45 am, breal wrote: > > > Forgive me for this question which is most likely stupid... > > The contents of your question are not stupid. The subject however does > invite a stupid answer like: len(the_string). > > Disclaimer: I know nothing about SOAP except that it's usually > capitalised :-) Now read on: > > > How do I determine the number of bytes a string takes up? ?I have a > > soap server that is returning a serialized string. > > Serialised how? UTF-8? > > > ?It seems that when > > the string goes over 65978 characters it does not return to the soap > > client. > > Why does it seem so? How did you arrive at such a precise limit? > > > ?Instead I get an error: > > error: (35, 'Resource temporarily unavailable') > > Is this error from the client or the server? Any error or logfile > record from the other side? > > Is there anything in the documentation about maximum sizes? > > > > > This makes me think the problem exists on the soap client side with > > some sort of max return length. > > Think? Can't you verify this by inspecting the source? > > > If I knew how many bytes the 65978 > > character string was, then I could try to up this value. > > How do you know the string is 65978 characters? If you are debugging > the server, can't you do len(serialise(the_65978_char_string))? > > 65978? Are you sure? Looks suspiciously close to 65535 aka 0xFFFF aka > (2 ** 16 - 1 ) to me. > > If you have the server, you presumably have the source code for both > client and server. Some options for you: > > (1) Look at the traceback(s), look at the source code, nut it out for > yourself. If there is some kind of max other than an implicit 16-bit > limitation in the client code, it shouldn't be too hard to find. > > (2) Post the traceback(s) here, along with other details that might be > useful, like what SOAP server s/w you are using, what version of > Python, what platform. I'm dying to find out. From bignose+hates-spam at benfinney.id.au Fri Mar 21 17:22:10 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 22 Mar 2008 08:22:10 +1100 Subject: How can I make a function equal to 0? References: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Message-ID: <87eja3wz5p.fsf@benfinney.id.au> Martin Manns writes: > I do not want the function to return 0 but to equal 0. Then it seems you don't want a function, but something else. Functions are functions, not integers. What problem are you trying to solve, and why do you think this behaviour will help? -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but 'apply North Pole' to what?" -- _Pinky and The | _o__) Brain_ | Ben Finney From deets at nospam.web.de Mon Mar 17 06:09:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 11:09:27 +0100 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> Message-ID: <646uapF2at163U1@mid.uni-berlin.de> cokofreedom at gmail.com wrote: >> >>> a = 1 >> >>> b = 1 >> >>> a is b >> True >> >>> id(a) >> 10901000 >> >>> id(b) >> 10901000 > > Isn't this because integers up to a certain range are held in a single > memory location, thus why they are the same? As the OP said: Depending on implementation, for immutable types, operations that compute new values may or may not actually return a reference to any existing object with the same type and value, while for mutable objects this is (strictly)? not allowed. Which is exactly what happens - the actual implementation chose to cache some values based on heuristics or common sense - but no guarantees are made in either way. Diez From falk at green.rahul.net Tue Mar 25 01:09:58 2008 From: falk at green.rahul.net (Edward A. Falk) Date: Tue, 25 Mar 2008 05:09:58 +0000 (UTC) Subject: Does python hate cathy? References: Message-ID: Interestingly, if you change swaroop = Person('Swaroop', 'M') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam', 'M') kalam.sayHi() kalam.howMany() cathy = Person('Catherine', 'F') cathy.sayHi() cathy.howMany() swaroop.sayHi() swaroop.howMany() to def main(): swaroop = Person('Swaroop', 'M') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam', 'M') kalam.sayHi() kalam.howMany() cathy = Person('Catherine', 'F') cathy.sayHi() cathy.howMany() swaroop.sayHi() swaroop.howMany() return 0 if __name__ == "__main__": sys.exit(main()) The problem goes away. (This is a good coding practice in any event.) As others have pointed out, the order in which local variables are deleted is undefined. It looks to me as if the class Person got deleted before Catherine did. Adding del kalam del cathy del swaroop to the end of the program did fix the problem, presumably by forcing kalam, cathy, and swaroop from being deleted before Person. However, Adding self.myclass = Person to the __init__() method didn't stop the problem. I thought it might, because then each of the objects would have held a reference to Person. Actually, I would have thought they'd hold a reference by merely existing, so is this not a bug? -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From gagsl-py2 at yahoo.com.ar Wed Mar 26 19:16:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 20:16:10 -0300 Subject: How to convert latex-based docs written with Python 2.5 to 2.6 framework References: Message-ID: En Wed, 26 Mar 2008 16:37:21 -0300, Michael Str?der escribi?: > I had a look on how Doc/ is organized with Python 2.6. There are files > with > suffix .rst. Hmm... > > I'm maintaing existing docs for python-ldap which I might have to > convert to > the new concept in the long run. What's the recommended procedure for > doing > so? Any pointer? Ask in the doc-sig mailing list. I'm sure there are some tools to help converting latex->rst http://mail.python.org/mailman/listinfo/doc-sig -- Gabriel Genellina From mensanator at aol.com Sun Mar 2 16:19:12 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 2 Mar 2008 13:19:12 -0800 (PST) Subject: sympy: nifty, but... (was: How about adding rational fraction to Python?) References: <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> <62te8iF24nbb5U1@mid.uni-berlin.de> <0af18797-295b-49ba-9c90-39eff6850440@s12g2000prg.googlegroups.com> Message-ID: On Mar 1, 12:29?pm, "Anand Patil" wrote: > Not sure if this is common knowledge yet but Sympy,http://code.google.com/p/sympy, has a rational type. I hadn't heard of this before, thanks for the link. Very nifty, lots of goodies not found in gmpy (although it seems to lack a modular inverse function and the linear congruence solver that can be derived from it making it of no value to me). Alas, it's written in Python. Who writes a math library in Python? Nevertheless, I thought I would try out the Rational numbers. Once I figured out how to use them, I converted my Polynomial Finder by Newton's Forward Difference Method program to use sympy instead of gmpy. I have a test case where I create 1 66 degree polynomial where the coefficients are large rationals. The polynomial was calculated flawlessly ## sympy ## Term0: [66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, 0] ## ## Seq: [66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66] ## ## The Polynomial: ## ## ## 1 ## ------------------------------------------------------------------------------------------- * n**66 ## 8247650592082470666723170306785496252186258551345437492922123134388955774976000000000000000 ## ## ## -67 ## ------------------------------------------------------------------------------------------ * n**65 ## 249928805820680929294641524448045340975341168222589014937034034375422902272000000000000000 ## ## ## 67 ## --------------------------------------------------------------------------------------- * n**64 ## 230703513065243934733515253336657237823391847590082167634185262500390371328000000000000 But because they are calculated using Python, it took 175 seconds compared to 0.2 seconds for gmpy to do the same polynomial. So, I'll keep it around for it's neat features that gmpy doesn't have, but it won't replace gmpy for any serious work. > > In [2]: from sympy import * > > In [3]: Rational(21,4) > Out[3]: 21/4 > > In [4]: Rational(21,4)+Rational(3,4) > Out[4]: 6 From timr at probo.com Wed Mar 19 03:26:34 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Mar 2008 07:26:34 GMT Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: Gowri wrote: > >I have a service running somewhere which gives me JSON data. >... >This prints a whole bunch of nonsense as expected. It's not nonsense. It's JSON. >I use cjson and am >unable to figure out how to print this json response You are already printing the JSON response. That's what that script does. >and I guess if I >can do this, parsing should be straightforward? doing a >cjson.decode(str(repsonse)) does not work. If response.read() returns the JSON string, as you show above, one might expect cjson.decode(response.read()) to parse it. Have you read the cjson documentation? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From duvo at tiscali.it Sun Mar 9 16:58:28 2008 From: duvo at tiscali.it (duccio) Date: Sun, 09 Mar 2008 21:58:28 +0100 Subject: __iter__ yield Message-ID: Hello! Someone knows if it's possible to make this __iter__ function with just one 'yield' intead of two? Is there some simpler way to make this __iter__ iter through all nodes? Thanks! class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): return '<'+str(self.data)+'>' def __iter__(self): yield self #1 for n in self.childs: for nn in n.__iter__(): yield nn #2 n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) for node in n: print node From kyosohma at gmail.com Wed Mar 19 14:32:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 11:32:46 -0700 (PDT) Subject: csv dictreader References: Message-ID: On Mar 19, 1:06 pm, brnstrmrs wrote: > I am trying to use the dictionary reader to import the data from a csv > file and create a dictnary from it but just can't seem to figure it > out. > > Here is my code: > > >>>import csv > >>>reader = csv.DictReader(open('table.csv')) > >>>for row in reader: > >>>print row > > my csv files looks like this: > > Bytecode,Element > \x00\x00,0000 > \x01\x00,0001 > .... > \x09\x00,0009 > > My output shows: > {'Bytecode': '\\x00\\x00', 'Element': '0000'} > {'Bytecode': '\\x01\\x00', 'Element': '0001'} > ... > {'Bytecode': '\\x09\\x00', 'Element': '0009'} > > 1. how can I get access to this directory What do you mean? You can get each element in the dict by doing this: for row in reader: print row['Bytecode'] print row['Element'] > 2. why does the values come with two backslashs infront of the "x" The double back slash is for escaping purposes, I think. If you print this: '\\x09\\x00' you'll get this: \x09\x00 Mike From aahz at pythoncraft.com Fri Mar 21 12:47:24 2008 From: aahz at pythoncraft.com (Aahz) Date: 21 Mar 2008 09:47:24 -0700 Subject: Python 2.x future (was Re: Improving datetime) References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> Message-ID: In article , Tim Roberts wrote: > >I thought there wasn't going to be a 2.7... Whatever gave you that idea? There's no *guarantee* that 2.7 will exist, but certainly it's being planned. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From pavlovevidence at gmail.com Mon Mar 3 15:49:33 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 12:49:33 -0800 (PST) Subject: sympy: what's wrong with this picture? References: Message-ID: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> On Mar 3, 3:40 pm, Mensanator wrote: > Notice anything funny about the "random" choices? > > import sympy > import time > import random > > f = [i for i in sympy.primerange(1000,10000)] > > for i in xrange(10): > f1 = random.choice(f) > print f1, > f2 = random.choice(f) > print f2, > C = f1*f2 > ff = None > ff = sympy.factorint(C) > print ff > > ## 7307 7243 [(7243, 1), (7307, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > > As in, "they're NOT random". > > The random number generator is broken by the sympy.factorint() > function. > > Random.choice() works ok if the factorint() function commented out. > > ## 6089 1811 None > ## 6449 1759 None > ## 9923 4639 None > ## 4013 4889 None > ## 4349 2029 None > ## 6703 8677 None > ## 1879 1867 None > ## 5153 5279 None > ## 2011 4937 None > ## 7253 5507 None > > This makes sympy worse than worthless, as it f***s up other modules. Dude, relax. It's just a bug--probably sympy is messing with the internals of the random number generator. It would be a simple fix. Instead of b****ing about it, file a bug report. Or better yet, submit a patch. Carl Banks From cokofreedom at gmail.com Mon Mar 17 04:32:38 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Mon, 17 Mar 2008 01:32:38 -0700 (PDT) Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> Message-ID: > >>> a = 1 > >>> b = 1 > >>> a is b > True > >>> id(a) > 10901000 > >>> id(b) > 10901000 Isn't this because integers up to a certain range are held in a single memory location, thus why they are the same? From bill.scherer at verizonwireless.com Wed Mar 19 08:57:52 2008 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Wed, 19 Mar 2008 08:57:52 -0400 Subject: Speaking Text In-Reply-To: References: Message-ID: <47E10DD0.4050600@verizonwireless.com> David C. Ullrich wrote: > Mac OS X has text-to-speech built into the interface. > So there must be a way to access that from the command > line as well - in fact the first thing I tried worked: > > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? > (If it's there in Linux presumably it only works if there > happens to be a speech engine available...) > With a little effort, the same code can work on Linux with the Festival speech engine. See http://www.cstr.ed.ac.uk/projects/*festival*/ > > David C. Ullrich > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Mar 19 19:19:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 20:19:32 -0300 Subject: csv.Sniffer - delete in Python 3.0? References: <18401.13509.344107.988906@montanaro-dyndns-org.local> Message-ID: En Wed, 19 Mar 2008 12:44:05 -0300, escribi?: > The csv module contains a Sniffer class which is supposed to deduce the > delimiter and quote character as well as the presence or absence of a > header > in a sample taken from the start of a purported CSV file. I no longer > remember who wrote it, and I've never been a big fan of it. It > determines > the delimiter based almost solely on character frequencies. It doesn't > consider what the actual structure of a CSV file is or that delimiters > and > quote characters are almost always taken from the set of punctuation or > whitespace characters. Consequently, it can cause some occasional > head-scratching: > > >>> sample = """\ > ... abc8def > ... def8ghi > ... ghi8jkl > ... """ > >>> import csv > >>> d = csv.Sniffer().sniff(sample) > >>> d.delimiter > '8' > >>> sample = """\ > ... a8bcdef > ... ab8cdef > ... abc8def > ... abcd8ef > ... """ > >>> d = csv.Sniffer().sniff(sample) > >>> d.delimiter > 'f' > > It's not clear to me that people use letters or digits very often as > delimiters. Both samples above probably represent data from > single-column > files, not double-column files with '8' or 'f' as the delimiter. I've seen an 'X' used as field separator - but in that case all values were numbers only. > I would be happy to get rid of it in 3.0, but I'm also aware that some > people use it. I'd like feedback from the Python community about this. > If > I removed it is there someone out there who wants it badly enough to > maintain it in PyPI? The Sniffer class already has a "delimiters" parameter; passing string.punctuation seems reasonable in case one wants to restrict the possible delimiter set. I think Sniffer is an useful class - but can't do magic, perhaps a few lines in the docs stating its limitations would be fine. -- Gabriel Genellina From fakeaddress at nowhere.org Sat Mar 22 04:31:45 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 22 Mar 2008 08:31:45 GMT Subject: finding items that occur more than once in a list In-Reply-To: <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > John Machin wrote: >> On Mar 22, 1:11 am, castiro... at gmail.com wrote: >>> A collision sequence is not so rare. >>>>>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] >>> [1, 1, 1, 1, 1, 1, 1, 1] >> Bryan did qualify his remarks: "If we exclude the case where an >> adversary is choosing the keys, ..." > > Some adversary. What, you mean, my boss or my customers? We mean that the party supplying the keys deliberately chose them to make the hash table inefficient. In this thread the goal is efficiency; a party working toward an opposing goal is an adversary. If you find real-world data sets that tend to induce bad-case behavior in Python's hash, please do tell. It would be reason enough to adjust the hash function. The hashes in popular software such as Python are already quite well vetted. Even a hash function that behaves as a random oracle has worst-case quadratic-time in the algorithm here, but that's an issue in theory and not in serving customers. -- --Bryan From hniksic at xemacs.org Tue Mar 18 11:18:04 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 18 Mar 2008 16:18:04 +0100 Subject: finding items that occur more than once in a list References: Message-ID: <87k5k02h8z.fsf@mulj.homelinux.net> Ninereeds writes: > The dictionary version Chris suggests (and the essentially > equivalent set-based approach) is doing essentially the same thing > in a way, but using hashing rather than ordering to organise the > list and spot duplicates. This is *not* O(n) due to the rate of > collisions increasing as the hash table fills. If collisions are > handled by building a linked list for each hash table entry, the > performance overall is still O(n^2) This doesn't apply to Python, which implements dict storage as an open-addressed table and automatically (and exponentially) grows the table when the number of entries approaches 2/3 of the table size. Assuming a good hash function, filling the dict should yield amortized constant time for individual additions. > I suspect Python handles collisions using linked lists, Why suspect, it's trivial to check. dictobject.c says: The basic lookup function used by all operations. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. Open addressing is preferred over chaining since the link overhead for chaining would be substantial (100% with typical malloc overhead). From jerry.fleming at saybot.com Tue Mar 18 02:12:12 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Tue, 18 Mar 2008 14:12:12 +0800 Subject: ctypes in python failed to honor c_int In-Reply-To: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> References: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> Message-ID: Gabriel Genellina wrote: > On 17 mar, 23:57, Jerry Fleming wrote: > >> I have a binary file written with c structures. Each record contains a >> null-terminated string followed by two 4-bytes integers. I wrote a small >> segment of python code to parse this file in this way: >> [coe] >> #!/usr/bin/python >> >> from ctypes import * >> >> class Entry(Structure): >> _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) >> >> idx = open('x.idx', 'rb') >> str = idx.read(1000) >> obj = Entry(str) >> print obj.w >> print obj.s >> print obj.l >> [/code] >> where the field w is the string, and s and l are the integers. Problem >> is that, I can only get the strings, not the integers. Well, I did got >> integers, but they are all zeros. What should I do to get the real numbers? > > So the string has a variable length? For "Hello" you have > 'h','e','l','l','o', a zero byte, followed by the two integers? This > is somewhat unusual for a C struct (in fact you can't declare it in > C). Perhaps the string is actually a char[n] array with a declared > maximum size? Yes, it has a variable length. The C version of the structure is something like this: [code] struct entry { char *str, int start, int length } [/code] And adding repr() would print something like this: [code] '(as) mad as a hatter\x00\x00\x00\x00\x00\x00\x00\x00\x1f-ish\x00\x00\x00\x00\x1f\x00\x00\x00 at -ism\x00\x00\x00\x00_\x00\x00\x00B-ist\x00\x00\x00\x00\xa1\x00\x00\x00J.AU\x00\x00\x00\x00\xeb\x00\x00\x00P.EXE\x00\x00\x00\x01;\x00\x00\x00`.GIF\x00\x00\x00' (as) mad as a hatter 0 0 [/code] where the first line is the result of repr(). We can find that, after the null-terminated string '(as) mad as a hatter', there are two integers, 0 and 31 (0x1f). But python treat 31 as zero. > > Try printing repr(a_few_read_bytes) or a_few_read_bytes.encode("hex") > to see the actual file contents. > > -- > Gabriel Genellina From aahz at pythoncraft.com Sun Mar 16 20:09:02 2008 From: aahz at pythoncraft.com (Aahz) Date: 16 Mar 2008 17:09:02 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: [warning: rant ahead] [[ Before starting my rant, I would like to encourage anyone who was at PyCon but has not provided formal feedback to use the following URLs: For the conference: http://tinyurl.com/2ara8u For the tutorials: http://tinyurl.com/2ew2pc ]] In article <5776428b-82b3-4921-945a-69beab134edd at b64g2000hsa.googlegroups.com>, fumanchu wrote: > >This is my third PyCon, and I've found a reasonably-sized cadre of >people who come for the hallway conversations plus a Bof or two, >having given up on hearing anything new, useful, or inspiring in the >talks. There are several people I know who would like to see a more >advanced academic track. Let's leave aside the issue of how sponsor talks were handled: assuming that there's general agreement that this year was a failed experiment, fixing it is easy. What you're bringing up here is a much more difficult issue, and it is, in the end, not a solvable issue in the general case. For starters, speaking as someone who has been going to science fiction conventions for more than twenty years, there will inevitably be plenty of people like your cadre. I rarely go to organized programming anymore, but I still have a great time because I'm seeing all my friends. PyCon is a similar community-oriented event. Moreover, PyCon's success rests on many legs: tutorials, Open Space, Lightning Talks, formal presentations, keynotes, and sprinting. That's aside from the myriad opportunities to network with people. Finally, trying to satisfy a thousand people is impossible. People who want to emphasize specific topics (e.g. an academic track) will need to start organizing other kinds of Python conferences. Now the rant: If you did not like the programming this year (aside from the sponsor talks) and you did not participate in organizing PyCon or in delivering presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! PyCon is built on the backs of its volunteers. I personally spent more than twenty hours just doing Program Committee work. We rejected half the proposals that we received, simply due to lack of space. We had difficulty evaluating some proposals because nobody on the PC had subject matter expertise. None of the speakers received any kind of honorarium. Except for keynote speakers (e.g. Ivan Krstic), no speakers received free registration unless they requested financial aid. There are no requirements for volunteering other than a willingness to volunteer and a modicum of courtesy in working with people. PyCon is what YOU make of it. If you want to change PyCon, propose a presentation or join the conference committee (concom) -- the latter only requires signing up for the pycon-organizers mailing list. This doesn't mean that we are uninterested in feedback. We love feedback. But there are stark limits to what we can do unless people get involved and push their pet projects. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From bcl at brianlane.com Tue Mar 25 11:37:00 2008 From: bcl at brianlane.com (Brian Lane) Date: Tue, 25 Mar 2008 08:37:00 -0700 Subject: Inheritance question In-Reply-To: References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: <47E91C1C.8090705@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Gerard Flanagan wrote: > Use the child class when calling super: > > -------------------------------------- > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = super(FooSon, self).getid() > b = self.id > return '%d.%d' % (a,b) > > print FooSon().getid() > -------------------------------------- That still doesn't do what he's trying to do. The problem here is that you only have one instance. self refers to it, so when you set self.id in the super you have set the instance's id to 1. When you set it to 2 after calling the super's __init__ you are now setting the *same* variable to a 2. Basically, you can't do what you are trying to do without using a different variable, or keeping track of a separate instance for the super instead of sub-classing it. Brian - -- - ---[Office 71.7F]--[Outside 33.2F]--[Server 99.5F]--[Coaster 68.7F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH6RwcIftj/pcSws0RArdpAJ9pCMjrkpBarHyQsl6hXEifj52giwCfXfKa Ot/1a+NNOLN5LA4mxBtfpis= =Yacu -----END PGP SIGNATURE----- From sjmachin at lexicon.net Mon Mar 10 07:25:53 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 04:25:53 -0700 (PDT) Subject: Problem with zipfile and newlines References: Message-ID: On Mar 10, 8:31 pm, "Neil Crighton" wrote: > I'm using the zipfile library to read a zip file in Windows, and it > seems to be adding too many newlines to extracted files. I've found > that for extracted text-encoded files, removing all instances of '\r' > in the extracted file seems to fix the problem, but I can't find an > easy solution for binary files. > > The code I'm using is something like: > > from zipfile import Zipfile > z = Zipfile(open('zippedfile.zip')) > extractedfile = z.read('filename_in_zippedfile') > "Too many newlines" is fixed by removing all instances of '\r'. What are you calling a newline? '\r'?? How do you know there are too many thingies? What operating system were the original files created on? When you do: # using a more meaningful name :-) extractedfilecontents = z.read('filename_in_zippedfile') then: print repr(extractedfilecontents) what do you see at the end of what you regard as each line: (1) \n (2) \r\n (3) \r (4) something else ? Do you fiddle with extractedfilecontents (other than trying to fix it) before writing it to the file? When you write out a text file, do you do: open('foo.txt', 'w').write(extractedfilecontents) or open('foo.txt', 'wb').write(extractedfilecontents) ? When you write out a binary file, do you do: open('foo.txt', 'w').write(extractedfilecontents) or open('foo.txt', 'wb').write(extractedfilecontents) ? From michael.wieher at gmail.com Sun Mar 16 13:43:05 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 12:43:05 -0500 Subject: Strange problem with structs Linux vs. Mac In-Reply-To: <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> Message-ID: you can specifify which encoding when you unpack the struct, so just try them till it works, or read the specs on the mac.. i find it quicker to try, there's only 4-5 2008/3/16, sturlamolden : > > On 16 Mar, 18:23, "Martin Blume" wrote: > > > This seems to imply that the Mac, although running now on Intel > > processors, is still big-endian. > > Or maybe the struct module thinks big-endian is native to all Macs? It > could be a bug. > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From codedread at gmail.com Sun Mar 9 13:26:57 2008 From: codedread at gmail.com (Jeff Schiller) Date: Sun, 9 Mar 2008 12:26:57 -0500 Subject: Need Help Building PythonQt on Windows Message-ID: Hello, I'm creating an application using Qt (4.4 Beta atm). I have pretty close to zero experience with Python (consisting of installing the Python interpreter, downloading a python programming and executing it on the command-line). I would like to invoke a Python script from my C++ Qt program and capture its output as a C++ structure. It seems that PythonQt might be suitable for my needs. Being a Qt program, I want this thing to be cross-platform. I'm having trouble getting things set up in Windows. Has anyone had any experience with this? I've built Qt from source using the mingw32 compiler. I installed Python 2.5 binary. I am trying to build PythonQt from source. As per http://pythonqt.sourceforge.net/#Building it says I need a "developer installation" of Python containing the header files and the library files. When I look at my system after installing the Python 2.5 binary, I can see I have header files (C:\Python25\include), a 199k python25.lib (C:\Python25\libs) and a 2MB python25.dll (C:\Windows\System32\). Have I got what I need? I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts to build but then it fails: g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to `_imp__Py_NoSiteFlag' ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to `_imp__Py_NoSiteFlag' ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to `_imp___Py_NoneStruct' C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to `_imp___Py_NoneStruct' ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to `_imp___Py_NoneStruct' C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to `_imp___Py_NoneStruct' ./debug\PythonQt.o: In function `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to `_imp__PyClass_Type' C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to `_imp__PyClass_Type' C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to `_imp__PyCFunction_Type' ... Since I'm new to compiling Qt with mingw and completely new to python, I was hoping for tips on why I'm getting these errors. If anyone has a better suggestion for a forum/mailing list then please let me know. Thanks, Jeff From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:16:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:16:39 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Message-ID: <13t6i47r3uoo6b4@corp.supernews.com> On Sat, 08 Mar 2008 15:26:35 -0800, Paul Rubin wrote: > Alasdair writes: >> What is the best way of finding a ceiling of a quotient of arbitrary >> sized integers? > > ceiling(a/b) = (a+b-1)//b Unfortunately that doesn't work reliably. >>> a, b = 9007199254741000.0, -3.0 >>> a/b -3002399751580333.5 >>> (a+b-1)//b # should be -3002399751580333 -3002399751580332.0 I make no claim that this is the most efficient way to do it, but this should work: def splitfloat(f): """Return the integer and fraction part of a float.""" fp = abs(f) % 1.0 ip = abs(f) - fp if f < 0: ip, fp = -ip, -fp return (ip, fp) def ceil(f): ip, fp = splitfloat(f) if fp == 0: return ip elif f < 0: return ip else: return ip + 1 >>> a, b = 9007199254741000.0, -3.0 >>> ceil(a/b) -3002399751580333.0 >>> a, b = 9007199254741000.0, 3.0 >>> ceil(a/b) 3002399751580334.0 It even works for infinities, if supported by your platform: >>> ceil(1.0/inf) 0.0 (Disclaimer: if you consider that 1.0/inf is a tiny bit more than zero, and therefore you want ceil(1.0/inf) to give 1.0, then you will disagree with me.) -- Steven From jeff at schwabcenter.com Thu Mar 13 01:45:15 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 12 Mar 2008 22:45:15 -0700 Subject: How to port Python code into C++ code automatically? In-Reply-To: References: Message-ID: Bo wrote: > I want to port a Python project (about 10,000 line python code) to C+ > +. Is there any automatically tool to do this kind of things? e.g., That's not trivial. Python is very heavily oriented toward run-time processing, whereas C++ favors compile-time processing. > e.g., SWIG(http://www.swig.org/)? Swig isn't so much a translator as a way of linking C or C++ code to multiple different scripting languages, using shared configuration (.i) files. If you're only connecting two languages (Python and C++), Swig is probably not going to help you much unless you happen to already be a master of Swig-foo. If the Python code works, then it's probably best to keep it in Python. To access it from C++, try Boost.Python. If you really do need to translate the code from Python to C++, try to do it incrementally. If the Python code is so monolithic that you can't find individual pieces to move one-at-a-time, consider refactoring the code in Python so that you'll at least have some modularity to work with. (In the process of refactoring, you may also find that you don't have to move the code out of Python, after all, e.g. because the performance improves along with the design.) From adrianbn at gmail.com Tue Mar 18 13:40:29 2008 From: adrianbn at gmail.com (=?ISO-8859-1?Q?Adri=E1n_Bravo_Navarro?=) Date: Tue, 18 Mar 2008 18:40:29 +0100 Subject: Comunicate processes with python In-Reply-To: References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> Message-ID: <267c4040803181040q2a70b91w8f92ff59359843fb@mail.gmail.com> That was what we were thinking of, so if there is not some kind of easy python magic we will probably use some sockets. Thanks!! 2008/3/18, Joshua Kugler : > > Adri?n Bravo Navarro wrote: > >> Is there any simple way to achieve this goal? We've been thinking of > >> sockets but Im not conviced at all with that. > > > If you want to communicate between processes on the same host, yes, you > can > use DBus or a couple of the options here: > http://docs.python.org/lib/ipc.html > > If you want to communicate between hosts, then sockets is probably going > to > be your only options, although there are libraries that abstract some of > that for you to make it easier to manage. You might want to take a look > at > Pyro. http://pyro.sourceforge.net/ > > j > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waldemar.osuch at gmail.com Fri Mar 14 15:46:41 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Fri, 14 Mar 2008 12:46:41 -0700 (PDT) Subject: ZSI and attachments References: Message-ID: <9efbc308-bb4e-4833-832d-d7b095692354@e60g2000hsh.googlegroups.com> On Mar 11, 8:59 am, Laszlo Nagy wrote: > Hi All, > > I wonder if the newest ZSI has support for attachments? Last time I > checked (about a year ago) this feature was missing. I desperately need > it. Alternatively, is there any other SOAP lib for python that can > handle attachments? > Does this help? http://trac.optio.webfactional.com/browser/soaplib/trunk/examples/binary.py From deets at nospam.web.de Mon Mar 3 15:09:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Mar 2008 21:09:01 +0100 Subject: Polymorphism using constructors In-Reply-To: <6333v2F25lleoU1@mid.individual.net> References: <6333v2F25lleoU1@mid.individual.net> Message-ID: <63346uF25gigqU1@mid.uni-berlin.de> K Viltersten schrieb: > I'm writing a class for rational numbers > and besides the most obvious constructor > > def __init__ (self, nomin, denom): > > i also wish to have two supporting ones > > def __init__ (self, integ): > self.__init__ (integ, 1) > def __init__ (self): > self.__init__ (0, 1) > > but for some reason (not known to me at > this point) i get errors. My suspicion is that it's a syntax issue. > > Suggestions? "errors" is not much of an error-description. That's what stacktraces are for. Apart from that, you won't succeed with the above. Python has no signature-based polymorphism. Instead, you use default arguments, like this: def __init__(nomin=0, denom=1): ... That should suffice. Diez From steve at holdenweb.com Sun Mar 2 12:38:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 12:38:17 -0500 Subject: tcp In-Reply-To: <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: Gif wrote: > i would like to apologize once more. i understand that you are saying > "what a fool he is waiting for us to solve all his problems", cause > i've said that for other posts, when they seemed "immature". It's just > that i couldn't find a way out of 20 lines of code and this drove me > mad. > > i end this topic here. If you want to use the socket module, take a look at http://holdenweb.com/py/networking/ which contains links to some fairly explicit notes about how to write TCP and UDP servers in Python. Nobody thinks you are a fool for wanting help with your problems, it's simply that you have to provide enough information about what' wring for us to get a handle on the issues. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:06:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:06:53 -0300 Subject: distutils as an application installer? References: <8cfcad33-a6c2-4e30-b585-6ad57555b316@c19g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 08:32:15 -0300, PurpleServerMonkey escribi?: > Was hoping someone could take a quick look at my distutils problem and > give it a quick sanity check. > > Basically I have a server application (for Linux) that I want to > install to /usr/local/, this location would have > subdirectories for the daemon scripts, log files, plugins etc. > > After reading a bunch of distutils documentation it appears that the > only good way out of this is to have my packages install to the system > wide site-packages directory. Then using the data_files command in > setup.py have it copy across an initial skeleton copy of the server > directory and finally install the startup scripts. > > Does this sound correct, any other suggestions? I'd use instead a standard setup script, and install it with --prefix or --home. You may want to provide a setup.cfg file with some defaults. > The distutils documentation doesn't cover this scenario and I've spent > days searching for information so any assistance is greatly > appreciated. It is in the "Installing" part, not in "Distributing". After all, you (as the developer) should only provide "what" to install; but "where" those parts get actually installed is decided by soemone else when the app is installed ("someone else" might even be yourself) -- Gabriel Genellina From fakeaddress at nowhere.org Fri Mar 14 04:07:09 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 08:07:09 GMT Subject: Socket Performance In-Reply-To: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: sleddd at gmail.com wrote: > Well, lets say you have a situation where you're going to be > alternating between sending large and small chunks of data. Is the > solution to create a NetworkBuffer class and only call send when the > buffer is full, always recv(8192)? Buffering can often improve performance, but with the above we'd to too quick to prematurely jump to an as yet unwarranted conclusion. You measured the one-large and many-small cases, but not the case you actually have. You might be able to take various measurements and generally characterize speed as a function of the number of calls and the size of the send. I wouldn't be surprised if the result is well approximated by a time per call plus a time per byte. In optimization, guessing is bad. Where you cannot reason with mathematical rigor, measure. Where you can derive a purely analytic result, taking the occasional measurements still isn't a bad idea (but don't tell my algorithms students). -- --Bryan From gagsl-py2 at yahoo.com.ar Wed Mar 26 15:11:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 16:11:40 -0300 Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 15:38:16 -0300, Tzury Bar Yochay escribi?: >> ....and then when my application execute code how can I set path to >> d3dx module to "library.zip/d3dx.py". >> I'm not sure is this properly set question. > > use the module zipimport > http://docs.python.org/lib/module-zipimport.html You don't have to do anything special to "use" zipimport; from : "It is usually not needed to use the zipimport module explicitly; it is automatically used by the builtin import mechanism" -- Gabriel Genellina From tmp1 at viltersten.com Sat Mar 8 15:21:48 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 8 Mar 2008 21:21:48 +0100 Subject: SV: Regarding coding style In-Reply-To: <13t5qd3slgt9nc0@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <63g9s0F26pgoeU1@mid.individual.net> > What I really can't stand are the > pointy-haired comment blocks at the > beginnings of C/C++ functions that do > things like tell you the name and return > type of the function and list the names > and types of the parameters. Gee, thanks. > I never could have figured that out from > looking at the source code itself. Coming from C++/Java camp i can't help noticing that in most cases, when i'm using a class written by somebody else, i don't want to see his/her code. I only want to know WHAT the function does (is intended to be doing, at least). I don't want to look at the source code (in some cases i can't even see the code because it's compiled). I only care that when i execute SomeType obj = SomeType(); obj.aggregate(); the object gets aggregated. How it's done will be up to the author. I'm just a user of the product. Now, i'm getting the signal that it's done in a different way in Python. Please elaborate. I'm very new to snakeology. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From MadComputerGuy at gmail.com Mon Mar 10 23:44:52 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Mon, 10 Mar 2008 20:44:52 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? Message-ID: Why does my compiler say invalid syntax and then highlight the quotation marks in the following code: # This program is to find primes. primes = [] import math import gmpy while 1: run = int(raw_input("Do you want to calculate primes? 1 = yes and 2 = no. ")) if run == 1: y = int(raw_input("What number do you want to use as the final number to calculate with? ")) x = int(raw_input("What number do you want to start calculating primes from? ")) while x < 2: print "Number must be at least 2 for math reasons." else: while x < y: prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) if prime < 0: primes.append(x) else: print x " is not prime. " # highlights the final " here x = x + 1 print primes elif run == 2: break else: print "Sorry, not a choice. Please enter your choice again." print "Goodbye." How do I fix such an invalid syntax? TIA, Nathan Pinno From skunkwerk at gmail.com Tue Mar 25 23:39:05 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 25 Mar 2008 20:39:05 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> Message-ID: <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> also, i've tried the Shell=True parameter for Popen, but that didn't seem to make a difference On Mar 25, 8:31 pm, skunkwerk wrote: > Hi, > i'm trying to call subprocess.popen on the 'rename' function in > linux. When I run the command from the shell, like so: > > rename -vn 's/\.htm$/\.html/' *.htm > > it works fine... however when I try to do it in python like so: > p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > print p.communicate()[0] > > nothing gets printed out (even for p.communicate()[1]) > > I think the problem is the quoted string the rename command wants - > when I put it in triple quotes like """s/\.htm$/\.html/""" I get some > output, but not the correct output. I've also tried escaping the > single quotes with \' and putting it in regular double quotes but that > didn't work either. > > i'd appreciate any help From bob.martin at excite.com Tue Mar 11 04:03:26 2008 From: bob.martin at excite.com (Bob Martin) Date: Tue, 11 Mar 2008 08:03:26 GMT Subject: Distributed App - C++ with Python for Portability? References: Message-ID: in 337600 20080310 222850 dave_mikesell at fastmail.fm wrote: >On Mar 10, 2:21 pm, Bob Martin wrote: > >> >> Java is more portable than most other languages, especially if your app needs a gui. > >The promise of Java portability was one of the biggest scams ever >perpetrated on the software industry. There are issues going from OS >to OS, VM to VM, DB to DB, app server to app server, etc. Certainly >no easier than porting C++ and the appropriate libraries, IMHO. Quite untrue - I have a stack of large java apps which run without change on Linux, OS/2 and Windows. Not many, if any, other languages can match that, and definitely not C++. From gagsl-py2 at yahoo.com.ar Wed Mar 26 12:29:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 13:29:55 -0300 Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 11:17:15 -0300, Python Programming on Win32 escribi?: > The problem is running smtplib in a py2exe compiled exe file. When it > tries to establish a socket to the mail server it fails. > > Just wondering someone has encountered this before, and if someone > might be able to point me in the right direction. > > Unhandled exception in thread started by > Traceback (most recent call last): > File "AutomationThread.pyc", line 152, in Run > File "mail.pyc", line 11, in sendMail > File "smtplib.pyc", line 244, in __init__ > File "smtplib.pyc", line 296, in connect > socket.gaierror: (10093, 'getaddrinfo failed') The script can't resolve the server name. Try to do it by hand using nslookup or even ping (you may want to add a few print statements inside the script to see the exact host name it is trying to connect to, in case it isn't what you expect) If you can't resolve the host name using nslookup, there is a network problem, not in your script. If you can resolve it, try your script without py2exe if possible. -- Gabriel Genellina From http Sat Mar 29 08:01:57 2008 From: http (Paul Rubin) Date: 29 Mar 2008 05:01:57 -0700 Subject: deleting a line from a file References: <13usb5ngt26qv26@corp.supernews.com> Message-ID: <7xy781zqkq.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > The only safe way to delete a line from a file (at least under common > operating systems like Windows, Linux and Mac) is to copy the file > (without the line you wish to delete) to a temporary file, then replace > the original file with the new version. That's also how to do it for > files too big to read into memory. You could do it "in place" in all those systems afaik, either opening the file for both reading and writing, or using something like mmap. Basically you'd leave the file unchanged up to line N, then copy lines downward starting from line N+1. At the end you'd use ftrunc to shrink the file, getting rid of the duplicate last line. From dave.brk at gmail.com Thu Mar 27 16:08:20 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 27 Mar 2008 22:08:20 +0200 Subject: Regarding __slots__ and other stuff: A couple of questions In-Reply-To: References: Message-ID: sorry, forget all I wrote: I should have read this more thoroughly, it explained it all http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.htm Descriptors only works with type objects, not instance. and you can't write from an instance object to a class variable. You can only hide it. Also __slots__ works by creating descriptors in the class and preventing creation of any atrributes in the class instance, so everything is clear now Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Mar 12 21:18:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Mar 2008 21:18:55 -0400 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: | > Hmm, wasn't aware they were taking it that far. You should almost | > always avoid using the cmp parameter because it's very inefficient; | | I don't see what's so inefficient about it necessarily. The key function is called once per list item, for n calls total. The comparision function is called once per comparision. There are at least n-1 such calls and typically something on the order of n * lg2(n) calls. From castironpi at gmail.com Wed Mar 5 15:06:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 12:06:11 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> Message-ID: <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: > castiro... at gmail.com schrieb: > > > I want to hash values to keys. ?How do the alternatives compare? > > http://catb.org/~esr/faqs/smart-questions.html ... without extending the whole way to a full relational database? From ivlenin at gmail.com Sun Mar 9 14:37:45 2008 From: ivlenin at gmail.com (I V) Date: Sun, 09 Mar 2008 18:37:45 GMT Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> <63hq8rF27chv6U1@mid.uni-berlin.de> <96486094-0706-45f1-b5c1-4af6333e3955@s13g2000prd.googlegroups.com> Message-ID: On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote: > Well, that suits me. The most unnatural thing about Python was adapting > to the idea of just letting unreleased resources go jogging off > wherever. :) Yes, that's a bad habit that garbage collection can encourage. GC is good for managing memory, but not good for managing other resources, so if an object holds some other resource, it's important to make sure the resource is released in a timely fashion rather than relying on the finalizer (the __del__ function). CPython uses reference counting, so it usually destroys objects fairly soon after the stop being used. But JPython and IronPython don't do reference counting, so forgetting to clean up resources can be a significant problem. > "Where's the f.close?" > "You don't need it!" Although, you still don't need f.close, with the new with statement: with open('myfile') as f: string = f.readline() # f.close() gets called automatically here, without waiting for # garbage collection. If you want to use this in 2.5, you have to write: from __future__ import with_statement The big advantage here is that f.close will get called if the block exits normally, or if there is an exception. For more, see http://effbot.org/pyref/with.htm . From tamim.shahriar at gmail.com Sun Mar 2 00:38:24 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sat, 1 Mar 2008 21:38:24 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 2, 6:56 am, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira I have found that 'Dive into Python' is a good book for people who have experience with other languages. It's available free here: http://www.diveintopython.org/ regards, Subeen http://love-python.blogspot.com/ From john.deas at gmail.com Sun Mar 9 08:25:19 2008 From: john.deas at gmail.com (John Deas) Date: Sun, 9 Mar 2008 05:25:19 -0700 (PDT) Subject: parralel downloads References: Message-ID: On Mar 8, 5:47 pm, Gary Herron wrote: > poof65 wrote: > > For your problem you have to use threads. > > Not at all true. Thread provide one way to solve this, but another is > the select function. For this simple case, select() may (or may not) be > easier to write. Pseudo-code would look something like this: > > openSockets = list of sockets one per download file: > while openSockets: > readySockets = select(openSockets ...) # Identifies sockets with > data to be read > for each s in readSockets: > read from s and do whatever with the data > if s is at EOF: close and remove s from openSockets > > That's it. Far easier than threads. > > Gary Herron > > > You can have more information here. > >http://artfulcode.nfshost.com/files/multi-threading-in-python.html > > > On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > > >> Hi, > > >> I would like to write a python script that will download a list of > >> files (mainly mp3s) from Internet. For this, I thought to use urllib, > >> with > > >> urlopen("myUrl").read() and then writing the resulting string to a > >> file > > >> my problem is that I would like to download several files at the time. > >> As I have not much experience in programming, could you point me the > >> easier ways to do this in python ? > > >> Thanks, > > >> JD > >> -- > >> http://mail.python.org/mailman/listinfo/python-list Thank you both for your help. Threads are working for me. However, a new problem for me is that the url I want to download are in an xml file (I want to download podcasts), and is not the same as the file downloaded: http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2BBD61E9ECD2C&ref=p_rss will be redirected to download: http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 is there a way, knowing the first url to get the second at runtime in my script ? From tmp1 at viltersten.com Sat Mar 1 19:49:38 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 01:49:38 +0100 Subject: SV: Where's GUI for Python? In-Reply-To: <62uai0F24sc4aU1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> Message-ID: <62uauaF2400f1U1@mid.individual.net> >> When that fails, try without the stutter >> >> import tkinter > > I must be doing something wrong because > neither tkinter nor tkininter works. > I tried both with and without stuttering. > I even asked my wife to stutter some but, > sadly, to no avail. > > When Tim Chase mentioned "battery-installed", > i interpreted it as "all is there". It seems > that either > a) not all the batteries are installed in my > version (v2.5.2) > or > b) some setup/linkage needs to be performed > in order to get the GUI running. > > The error itself is: > ImportError: No module named tkinter > > Suggestions? Here's a suggestion. Python is case-sensitive, while the users trying to help you are not. When they say "tininkerbell", they may mean "Tinkerbell". Check with "help()", then "modules" and see if it's installed or not. Sincerely Yourself :) (Seriously speaking - i'm thankful.) From xu.mathena at gmail.com Sun Mar 23 19:01:31 2008 From: xu.mathena at gmail.com (NotGuru) Date: Sun, 23 Mar 2008 16:01:31 -0700 (PDT) Subject: PyTuple_Check and other type check functions didn't check the NULL pointer Message-ID: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> I was writing some C extensions for Python and use PyTupleType_Check extensively. I found that all the PySomeType_Check macros directly delegate the job to PyObject_TypeCheck(op, &PyType_Type). The PyObject_TypeCheck(op, &PyType_Type) is again a macro and defined as ((ob)->ob_type == (tp) || PyType_IsSubtype((ob)->ob_type, (tp))) in object.h. My questions is: is it necessary to check the null pointer in the macro or it's a job for the user? Semantically all the type check should report a false if a null pointer is encountered. I've already had the patch to this issue but I am not sure if I think this problem right. I don't know if there are some python core developers around but I would like to hear all opinions towards this. BTW, if the user didn't check null pointer before call the function, a segmentation fault might occur. From dstromberglists at gmail.com Wed Mar 12 19:51:24 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Wed, 12 Mar 2008 23:51:24 GMT Subject: tcp client socket bind problem References: Message-ID: <00_Bj.17371$Ch6.8114@newssvr11.news.prodigy.net> On Sun, 09 Mar 2008 22:21:59 -0700, natambu wrote: > I have a linux box with multiple ip addresses. I want to make my python > client connect from one of the ip addresses. Here is my code, no matter > what valid information I put in the bind it always comes from the > default ip address on the server. Am I doing something wrong? > > > ------------- > #!/usr/bin/python > > import socket > > host = "server" > port = 1190 > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.bind(("",0)) > sock.connect((host, port)) > ------------- I'd've expected that to work. What does your routing table look like? You can view it with "netstat - nr". I believe when a Linux network interface is ifconfig'd, the kernel will add a route for that interface based on the netmask in the ifconfig, but you could conceivably have another route that is broader overriding the specific route. From nagle at animats.com Fri Mar 14 01:53:49 2008 From: nagle at animats.com (John Nagle) Date: Thu, 13 Mar 2008 22:53:49 -0700 Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup In-Reply-To: <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> References: <47d97288$0$36363$742ec2ed@news.sonic.net> <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> Message-ID: <47da10c8$0$36374$742ec2ed@news.sonic.net> John Machin wrote: > On Mar 14, 5:38 am, John Nagle wrote: >> Just noticed, again, that getattr/setattr are ASCII-only, and don't support >> Unicode. >> >> SGMLlib blows up because of this when faced with a Unicode end tag: >> >> File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag >> method = getattr(self, 'end_' + tag) >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' >> in position 46: ordinal not in range(128) >> >> Should attributes be restricted to ASCII, or is this a bug? >> >> John Nagle > > Identifiers are restricted -- see section 2.3 (Identifiers and > keywords) of the Reference Manual. The restriction is in effect that > they match r'[A-Za-z_][A-Za-z0-9_]*\Z'. Hence if you can't use > obj.nonASCIIname in your code, it makes sense for the equivalent usage > in setattr and getattr not to be available. > > However other than forcing unicode to str, setattr and getattr seem > not to care what you use: OK. It's really a bug in SGMLlib, then. SGMLlib lets you provide a subclass with a function with a name such as "end_img", to be called at the end of an "img" tag. The mechanism which implements this blows up on any tag name that won't convert to "str", even when there are no "end_" functions that could be relevant. It's easy to fix in SGMLlib. It's just necessary to change except AttributeError: to except AttributeError, UnicodeEncodeError: in four places. I suppose I'll have to submit a patch. John Nagle SiteTruth From bockman at virgilio.it Mon Mar 24 11:45:42 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 15:45:42 GMT Subject: Disable resize button References: Message-ID: <47e7cca5$0$16036$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 04:38:50 -0700, myonov ha scritto: > Hi! > > I need to disable resize button in Tkinter. I inherit the Frame class. > Then in the constructor i make my buttons, labels, etc. Then I pack them > and when move borders of the frame everything changes it's location and > it looks really bad. How can I change that? > That's my code: > # -*- coding: cp1251 -*- > import Tkinter > > class App(Tkinter.Frame): > def click(self): > pass > > def click2(self): > pass > > def __init__(self, master=None): > Tkinter.Frame.__init__(self, master, width = 700, height = > 400,\ > bg = "#999999") > self.pack() > > # Buttons > > self.b1 = Tkinter.Button(self, text = u"?????? ?????",\ > command=self.click, font = "Courier", > \ > fg = "red") > self.b2 = Tkinter.Button(self, text = u"?????? ???????",\ > command=self.click2, font = "Courier", > \ > fg = "red") > self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = > 0.75, rely = 0.4) > > # Labels > > self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ > text = u"??????????", fg = "#ffffff",\ > bg = "#999999") > self.l1.place(x = 275, y = 10) > > # Text Control > # self.txt = Tkinter.Text(self, bg = "#124456", ) # > self.txt.pack() > > You could try including the frame in a toplevel window (e.g. passing Tkinter.Tk() as super) and then doing super.wm_resizable(None, None) A better idea would be using pack instead of place, leaving to the toolkit the job of rearranging the widgets when the window is enlarged or reduced. Ciao ----- FB From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 07:49:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 11:49:11 -0000 Subject: deleting a line from a file References: Message-ID: <13usb5ngt26qv26@corp.supernews.com> On Sat, 29 Mar 2008 04:13:10 -0700, eMko wrote: > Is there some easy way how to delete a line from a middle of a file in > Python? If the file is small enough to fit into memory (say, up to a few hundred megabytes on most modern PCs): lines = open('file', 'r').readlines() del line[100] open('file', 'w').writelines(lines) Quick and easy for the coder, but not the safest way to do it in serious production code because there's no error handling there. The only safe way to delete a line from a file (at least under common operating systems like Windows, Linux and Mac) is to copy the file (without the line you wish to delete) to a temporary file, then replace the original file with the new version. That's also how to do it for files too big to read into memory. -- Steven From lbonafide at yahoo.com Sun Mar 16 20:08:43 2008 From: lbonafide at yahoo.com (lbonafide at yahoo.com) Date: Sun, 16 Mar 2008 17:08:43 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> Message-ID: <11252b13-e3d0-4aa7-9cf5-ee9db7bfc250@u69g2000hse.googlegroups.com> On Mar 16, 2:43 pm, Robert Hicks wrote: > On Mar 16, 12:38 pm, lbonaf... at yahoo.com wrote: > > > On Mar 16, 6:10 am, Bruce Eckel wrote: > > > > I think a lot of people have been caught up in the idea that we need > > > to commercialize Python, and ride some kind of wave of publicity the > > > way that Java and C# and Rails seem to have done. > > > This coming from someone who caught the Java wave and rode it for a > > decade. > > Doesn't that make him better to see the problems with it? Sure, but he dumped C++ (a truly non-commercial language) like a bad habit for the latest silver bullet ten years ago. Complaints against Java's commercial nature now ring a bit hollow. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Mar 25 14:35:34 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 25 Mar 2008 19:35:34 +0100 Subject: Files, directories and imports - relative to the current directory only References: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> Message-ID: <64suvmF2d8hphU1@mid.individual.net> ptn wrote: > Traceback (most recent call last): > File "path.py", line 4, in > f = open('~/read/foo.txt') > IOError: [Errno 2] No such file or > directory: '~/read/foo.txt' > [...] > So, what's wrong here? Maybe there's something I haven't set up? Simple: the directory "~" doesn't exist. Since you're not using a shell (but direct file access) there is no tilde expansion, and "~" is treated as a regular file name. If you need to get the home directory refer to the environment variable HOME (os.environ["HOME"]). There even may be a shorter way, please refer to the os module docs. Regards, Bj?rn -- BOFH excuse #139: UBNC (user brain not connected) From malaclypse2 at gmail.com Thu Mar 27 11:05:19 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 27 Mar 2008 11:05:19 -0400 Subject: Is subprocess.Popen completely broken? In-Reply-To: References: Message-ID: <16651e80803270805q399b1c17mec7703c0017cbac0@mail.gmail.com> On Thu, Mar 27, 2008 at 10:53 AM, Skip Montanaro wrote: > I am trying to replace os.system calls with subprocess.Popen. This simple > example fails miserably: > > >>> proc = subprocess.Popen ("ls /tmp") > Traceback (most recent call last): > File "", line 1, in > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 594, in __init__ > errread, errwrite) > File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 1091, in > _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > I also tried explicitly referencing /usr/bin/ls. Same result. What gives? It's looking for an executable named "ls /tmp" Since it can't find one, it raises an exception. If you just want to replace an os.system call, you need to pass shell=True to Popen, like this: proc = subprocess.Popen("ls /tmp", shell=True) That will get the shell to split your string into the program to be called, and the argument(s) to the program. Alternatively, you can do it yourself by passing a sequence to Popen: proc = subprocess.Popen(["ls", "/tmp"]) Take a look at the documentation for Popen (http://docs.python.org/lib/node528.html) and the specific examples for replacing os.system (http://docs.python.org/lib/node536.html) -- Jerry From wolf_tracks at invalid.com Fri Mar 28 14:26:02 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 28 Mar 2008 18:26:02 GMT Subject: Astronomy Fits format and gif.save(path) Message-ID: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> In what library would I find gif.save(path), where path is the name and path of a file, and the method would produce a file in a gif format? Is there a fits.save(path) somewhere? fits is commonly used in astronomical work. -- Wayne Watson (Nevada City, CA) Web Page: From arnodel at googlemail.com Sat Mar 22 16:42:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 13:42:17 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 7:00?pm, Larry Bates wrote: > jmDesktop wrote: > > For students 9th - 12th grade, with at least Algebra I. ?Do you think > > Python is a good first programming language for someone with zero > > programming experience? ?Using Linux and Python for first exposure to > > programming languages and principles. > > > Thank you. > > ABSOLUTELY. ?Get them started with a REAL programming language that will > teach them proper fundamentals. ?I wish Python would have been around 25 > years ago when I taught incoming Freshmen at local University. ?To get > students to understand about variable references, etc. I always started > them with Assembler so they could understand what was actually going on. > I see so may on this forum that have the wrong ideas about variable names/ > storage. It's funny, 25 years ago - I was 10 then - I got my first computer from my cousin (a Sinclair ZX81, I think it had a different name in the US) as he was getting a brand new C64. In those days BASIC was very slow so if you wanted to do anything demanding with a computer you had to learn 'machine language' (I didn't have an assembler...). I wrote my little programs in a notebook, then POKEd them into memory! I learnt so much then. Years later, when I got my first C compiler, it was a liberation. My other 'coming of age' was when I took a lambda-calculus course at university. I felt like a man who's had a black and white TV set all his life and watches colour TV for the first time. What if computers had been designed as 'lambda-calculus machines' from the start rather than Turing machines? Anyway, here the conclusion that I draw: learn lambda-calculus and Turing machines. The rest is syntactic sugar. Not quite seriously but still'ly yours -- Arnaud From gagsl-py2 at yahoo.com.ar Thu Mar 27 02:31:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 03:31:31 -0300 Subject: Plugin framework - Overcomplicating things? References: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 01:50:56 -0300, hajducko at gmail.com escribi?: > All this comes to my question - am I overcomplicating this project? I > can understand the use of something like the trac component system if > I had multiple components and plugins that handled different areas of > my project and different points of interaction, but I don't. I've got > exactly one spot where I want to check all my plugins and hand off the > message to which ever ones are looking for that command. As you said, it looks like you're really overengineering your design then. > So really, > should I even bother with trying to setup some framework for this or > should I just be doing a simple loop over a directory, importing all > the plugins and storing them in a list and then looping over them in > the message handler to see which ones were looking for the command and > letting them do their thing? That may be an option. You may want to setup a simple registry mechanism, so the plugin modules look like: ### begin niceplugin.py ### class AVeryNicePlugin(object): # or perhaps using a suitable base class def handle_message(self, message): ... from plugin import PluginRegistry PluginRegistry.register(AVeryNicePlugin) ### end niceplugin.py ### Your application scans a known directory for files ending in "plugin.py" and imports them; the modules register themselves any class (or classes), and at appropiate times the application calls some method(s) of the registered plugins. > As an aside, if there is anyone who is an experience developer and > designer and is willing to take some private correspondence, please > let me know. I feel embarrassed for asking, but I've got a alot of > questions that I don't want to litter this list with and would rather > voice them in private. Why not? Get another free account, post using a pseudonym, and nobody will know that *YOU* were the guy that asked the most stupid question of the week :) -- Gabriel Genellina From steve at holdenweb.com Sat Mar 29 22:57:33 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 29 Mar 2008 22:57:33 -0400 Subject: What motivates all unpaid volunteers at Pycon? In-Reply-To: <47EEBEFC.6040600@tim.thechases.com> References: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> <47EEBEFC.6040600@tim.thechases.com> Message-ID: Tim Chase wrote: >> I was wondering what motivated so many people to give so much to the >> Python community. > > fear, surprise, ruthless efficiency, an almost fanatical devotion > to the BDFL, and nice red uniforms. > > Oh... > NOT THE COMFY CHAIR! (tm) -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Tue Mar 4 23:12:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:12:01 -0800 (PST) Subject: is there enough information? References: <13s9u7dg24es73a@corp.supernews.com> <13spkb990ha3v6c@corp.supernews.com> <392cadeb-e1f8-4cef-834c-a837ba7e02f5@59g2000hsb.googlegroups.com> Message-ID: <51edef68-e12a-454b-9fad-a0732fb72229@x30g2000hsd.googlegroups.com> > How does it work? ?From reading threading.py, _Condition.wait() > acquires self.lock() too many times-- that is, once to call wait > ("cannot wait on un-aquired lock"), and once after--- are "all > waiters" waiting back at self.acquire, just to make it to > self.notify... and only one at a time at that!? ?Don't waiters have to > release before another waiter can go? It's not like Condition().acquire() appends self._lock to self._waiters *before* delegationing! So... how? From Lie.1296 at gmail.com Sun Mar 30 13:57:28 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 10:57:28 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> <87od8w7aws.fsf@physik.rwth-aachen.de> <659ggqF2f84eoU3@mid.individual.net> Message-ID: <31684d32-6ff6-4cb1-bb95-9910e6cd7106@s19g2000prg.googlegroups.com> On Mar 30, 7:48 pm, Bjoern Schliessmann wrote: > Torsten Bronger wrote: > > Maybe he means "?". > > Haven't seen this either, nor do I think it's the same than "<>". > From afar, it looks more like "><". Actually I meant an X-like symbol that is made not by crossing but by ><. I retracted saying it is the standard, now that I think about it the last time I saw >< was in elementary school (although it stuck on my head better than a crossed =, which I first met in high school). > But this does more look like > South Park style shut eyes than an operator. :) lol, I agree, it looks too much like closed eye smiley. Forums might automatically convert them to graphic smileys so it is obviously a bad choice if it is to be used. From mail at timgolden.me.uk Fri Mar 28 17:53:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 28 Mar 2008 21:53:16 +0000 Subject: Finding Full Path to Process EXE In-Reply-To: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: <47ED68CC.7020404@timgolden.me.uk> misceverything at gmail.com wrote: > Hello, > > I would like to write a script that would enumerate all running > processes and return the full path to the EXE of each running > process. However, I can't seem to find any good info on how to do > this..any help is greatly appreciated. Thanks. I have this strange feeling of deja vu. Try this: http://timgolden.me.uk/python/wmi_cookbook.html#running_processes (You want the .ExecutablePath or .CommandLine attributes I imagine) TJG From aisaac at american.edu Sun Mar 2 16:05:11 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 02 Mar 2008 21:05:11 GMT Subject: tuples, index method, Python's design In-Reply-To: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> References: <6d369e71-feb5-477d-a162-f6b0c4eb27f3@k2g2000hse.googlegroups.com> Message-ID: Paul Boddie wrote: > Here's the tracker item that may have made it happen: > http://bugs.python.org/issue1696444 > I think you need to thank Raymond Hettinger for championing the > cause. ;-) Yes indeed! Alan Isaac From craigm3604 at gmail.com Sat Mar 22 22:05:31 2008 From: craigm3604 at gmail.com (Craig) Date: Sat, 22 Mar 2008 19:05:31 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> Message-ID: <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> On Mar 22, 9:40 pm, Dennis Lee Bieber wrote: > On Sat, 22 Mar 2008 15:12:47 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > > > > > Anyway, I have the following for "types": > > LPBSTR = POINTER(c_void_p) > > HANDLE = POINTER(POINTER(c_long)) > > LPHANDLE = POINTER(HANDLE) > > LPSHORT = POINTER(c_short) > > LPVSTATS = POINTER(c_void_p) > > c_string = c_char_p > > LPSTR = c_string > > > I guess passing a structure is out of the question. So, I tried a > > string (something - just to get the data back): > > #short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS > > lpvstats); > > VmxInfo = windll.vbis5032.VmxInfo > > VmxInfo.restype = c_short > > VmxInfo.argtypes = [LPHANDLE, LPSTR] > > VsamInfo = create_string_buffer("12345678901234567890123456789012") > > printf ("VsamInfo = \x22%s\x22\n", VsamInfo.raw) > > print "Ready to call (Library = " + find_library("vbis5032") + ") ..." > > res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) > > And I get: > > Ready to call (Library = C:\Windows\vbis5032.dll) ... > > Traceback (most recent call last): > > File "C:\temp\vbisam_test_2.py", line 101, in > > res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) > > ctypes.ArgumentError: argument 2: : wrong > > type > > Did you try just passing the buffer, rather than nesting a "byref" > > http://docs.python.org/lib/ctypes-passing-pointers.html > > Note how the string buffer parameter has NO odd games on it. This > especially applies to the other call below, for PriKey and the other > BSTR *... term > > As for passing a structure... Well, I'd suggest using struct.pack to > push arguments into such a structure (though it it is using pointers to > other items it may get tricky), using create_string_buffer to make the > Python string "structure" a C-memory block, passing that, and if needed, > struct.unpack the item after the call. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ Based on your input, I changed: LPSTR = c_char_p VmxGet = windll.vbis5032.VmxGet VmxGet.restype = c_short VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), TypeDef ) printf ("After - res = %#x (%d), SecIndex = %d, Option = %d, hwmcb = %d \n", res, res, SecIndex, Option, hwmcb) printf ("SrchKey = \x22%s\x22\nSeckey = \x22%s\x22\nPriKey = \x22%s \x22\nTypeDef = \x22%s\x22\n", SrchKey, SecKey, PriKey, TypeDef.raw) I got back exactly what I expected for TypeDef, but SecKey and PriKey were what I initialized them to , not what should have been returned. Do you mean that I should change any string that is expected to be changed by the dll to a create_string_buffer type (LPSTR) instead of a windll.oleaut32.SysAllocStringByteLen type (LPBSTR) and then simply list it in the call instead of byref, as I did with TypeDef? Can it really be that simple? As for the structure: class VSTATS(Structure): _fields_ = [ ("nrecords", c_long), ("gps_used", c_short), ("gps_unused", c_short), ("max_key_len", c_short), ("grp_size", c_long), ("init_alloc", c_short), ("cr_opts", c_short), ("free_prop_area", c_short), ("format", c_void_p), ("reserved", c_void_p) ] vStats = VSTATS(1, 2, 3, 4, 5, 6, 7, 8) can I just use a create_string_buffer (LPSTR) and parse things up via substrings after the call returns? From gagsl-py2 at yahoo.com.ar Mon Mar 24 23:29:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 00:29:44 -0300 Subject: Python 2.2.1 and select() References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> <20080325020356.GF26870@dragontoe.org> Message-ID: En Mon, 24 Mar 2008 23:03:56 -0300, Derek Martin escribi?: > On Mon, Mar 24, 2008 at 05:52:54PM -0700, Noah wrote: >> On Mar 24, 2:58 pm, Derek Martin wrote: >> > If and only if the total amount of output is greater than the >> > specified buffer size, then reading on this file hangs indefinitely. You may try using two worker threads to read both streams; this way you don't care about the blocking issues. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Mar 3 02:15:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 05:15:27 -0200 Subject: Run Python app at startup References: Message-ID: En Sun, 02 Mar 2008 19:37:35 -0200, SMALLp escribi?: > Hy. > I create simple application. Yust an windows and "compile" it with > py2exe. I add registry value > reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run > /v > MyApp /t REG_SZ /d C:\myapp.exe /f' > > And it wont start. When i use console instead od window in py2exe i get > console opend but it closes. I'd check in this order: python prog.py Then, use console=... in setup.py, generate prog.exe Open a cmd window and execute prog.exe (from the dist directory) Repeat using window=... in setup.py That whole sequence works fine using on my WinXP SP2 + Python 2.5.1 + wxPython 2.8.7.1 -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 08:43:23 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 14:43:23 +0200 Subject: python ODF library? References: Message-ID: <659g7bF2f84eoU1@mid.individual.net> Matias Surdi wrote: > Do yo know any good OpenDocumentFormat library for python? > > I'm starting a project on wich I'll have to programatically modify > ODF text documments, so, after reinventing the wheel, I'd like to > know if already something exists. Probably this will help: http://wiki.services.openoffice.org/wiki/PyUNO_bridge Regards, Bj?rn -- BOFH excuse #327: The POP server is out of Coke From gagsl-py2 at yahoo.com.ar Thu Mar 6 17:01:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 20:01:46 -0200 Subject: system32 directory References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: En Thu, 06 Mar 2008 19:15:17 -0200, Robert Dailey escribi?: > On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden wrote: >> >> >>> import win32api >> >>> win32api.GetSystemDirectory () >> 'C:\\WINDOWS\\system32' > > I was aiming to figure out if the standard modules shipped with Python > could > do this already before I started using 3rd party libraries. Thanks. Use ctypes then: py> from ctypes import * py> windll.kernel32.GetSystemDirectoryA <_FuncPtr object at 0x00A0F918> py> GetSystemDirectory = windll.kernel32.GetSystemDirectoryA py> buffer = create_string_buffer(260) py> GetSystemDirectory(buffer, sizeof(buffer)) 19 py> buffer.value 'C:\\WINDOWS\\system32' -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 13 12:09:50 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 13 Mar 2008 11:09:50 -0500 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <-6101886065348230738@unknownmsgid> References: <47D94D61.9010708@jouy.inra.fr> <-6101886065348230738@unknownmsgid> Message-ID: 2008/3/13, Robert Rawlins : > > Hi Guys, > > Well thanks for the response, I followed your advice and chopped out all > the > crap from my class, right down to the bare __init__ and the setter method, > however, the problem continued to persist. > > However, Robert mentioned something about unindented lines which got me > thinking so I deleted my tab indents on that method and replaces them with > standard space-bar indents and it appears to have cured the problem. > > Usually my Eclipse IDE throws up an error about this but for some reason > decided not too this time around, what a PITA. > > Thanks for the ideas guys, I appreciate it. > > Robert > > -----Original Message----- > From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org > [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org > ] > On Behalf Of Robert Bossy > Sent: 13 March 2008 15:51 > To: python-list at python.org > Subject: Re: "Attribute Doesnt Exist" ... but.... it does :-s > > Robert Rawlins wrote: > > > > Hello Guys, > > > > I've got an awfully aggravating problem which is causing some > > substantial hair loss this afternoon J I want to get your ideas on > > this. I am trying to invoke a particular method in one of my classes, > > and I'm getting a runtime error which is telling me the attribute does > > not exist. > > > > I'm calling the method from within __init__ yet it still seems to > > think it doesn't exist. > > > > Code: > > > > # Define the RemoteDevice class. > > > > class *remote_device*: > > > > # I'm the class constructor method. > > > > def *__init__*(/self/, message_list=/""/): > > > > /self/.set_pending_list(message_list) > > > > def *set_pending_list*(/self/, pending_list): > > > > # Set the message list property. > > > > /self/.pending_list = message_list > > > > And the error message which I receive during the instantiation of the > > class: > > > > File: "/path/to/my/files/remote_device.py", line 22, in __init__ > > > > self.set_pending_list(message_list) > > > > AttributeError: remote_device instance has no attribute > 'set_pending_list' > > > > Does anyone have the slightest idea why this might be happening? I can > > see that the code DOES have that method in it, I also know that I > > don't get any compile time errors so that should be fine. I know it > > mentions line 22 in the error, but I've chopped out a load of non > > relevant code for the sake of posting here. > > > Hi, > I don't get this error if I run your code. Maybe the irrelevant code > causes the error: my guess is that there's a parenthesis mismatch or an > undeindented line. > > Btw, calls to set_pending_list will fail since the name "message_list" > is not defined in its scope. Please follow Chris Mellon's advice. > > Cheers, > RB > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list All the more reason to use VIM and set it to auto-indent / remove 4 spaces with tab & backspace. =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Mar 6 09:24:29 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 06 Mar 2008 15:24:29 +0100 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <63ad4tF26o96fU1@mid.individual.net> Guillermo wrote: > I'm just designing the algorithm, but I think Python dictionaries > can hold any kind of sequence? (Watch out, dicts are no sequence types.) I recommend relying duck typing as long as it's feasible. I. e. if it can be subscripted like a dict, it is a dict. If this makes problems, use the type({}) approach. Regards, Bj?rn -- BOFH excuse #56: Electricians made popcorn in the power supply From solisgb at gmail.com Wed Mar 12 03:52:17 2008 From: solisgb at gmail.com (luis) Date: Wed, 12 Mar 2008 00:52:17 -0700 (PDT) Subject: unable to install gdal References: <15838144-b7a0-4d1b-98b3-fdfcfdb9a916@n75g2000hsh.googlegroups.com> <86d8bc35-24d5-4145-8421-94d71066209d@60g2000hsy.googlegroups.com> Message-ID: <42b6735f-476d-4da0-9465-3867d1f0d41c@v3g2000hsc.googlegroups.com> On 10 mar, 09:49, luis wrote: > On 9 mar, 16:37, luis wrote: > > > > > Hi > > > On Windows xp sp2 and python 2.4 > > > Yesterday I running old versions of gdal, and I try to upgrade > > > I download gdalwin32exe150.zip and gdal-python-13.win32-py2.4.exe > > I unzip gdalwin32exe150.zip in C:\gdalwin32-1.5 > > > I follow install's instructions fromhttp://trac.osgeo.org/gdal/wiki/GdalOgrInPython, > > all is ok, I set path and path_data variables with correct values, but > > whe I run a script, an error raises > > > from osgeo import ogr > > File "C:\Python24\Lib\site-packages\osgeo\ogr.py", line 7, in ? > > import _ogr > > ImportError: DLL load failed: process not found > > > Also I try with instructions fromhttp://www.urbansim.org/opus/stable-releases/opus-2006-11-21/docs/gda... > > I move _gdal.pyd (and the others *.pyd) from my Python installation's > > (C:\Python24\Lib\site-packages\osgeo) into my Python installation's > > DLLs folder (C:\Python24\DLLs). > > When I run the script the error message persists. > > > Some help is welcome. > > If I install on a XP without previous installation of gdal, the > installation works fine. > > Perhaps is a problem with XP's registry If I run the script in the dos line command (>> python script_name.py) a final windows error's message says curls_multi_cleanup pocedure don`t find entry point in libcurl.dll I have found 2 programs using other versions libcurl.dll In the PATH environment variable I insert C:\gdalwin32-1.5\bin before paths those programs, and the error has disappeared From HMartin1 at gmx.net Fri Mar 28 16:13:00 2008 From: HMartin1 at gmx.net (Hans Martin) Date: Fri, 28 Mar 2008 21:13:00 +0100 Subject: Problem with format string and unicode Message-ID: <20080328201300.118730@gmx.net> Hi, this is probably a trivial problem, but a google search for "python" and "unicode" and" format string" gives too many hits: If I specify e.g. "%20s" in a format string and the string value contains UTF-8 stuff (differing number of bytes per character), the length of the resulting string (in characters) varies. How can I fix this? Many thanks in advance! -- Psssst! Schon vom neuen GMX MultiMessenger geh?rt? Der kann`s mit allen: http://www.gmx.net/de/go/multimessenger From gagsl-py2 at yahoo.com.ar Fri Mar 28 18:25:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 19:25:50 -0300 Subject: Problem with format string and unicode References: <20080328201300.118730@gmx.net> Message-ID: En Fri, 28 Mar 2008 17:13:00 -0300, Hans Martin escribi?: > this is probably a trivial problem, but a google search for "python" > and "unicode" and" format string" gives too many hits: If I specify > e.g. "%20s" in a format string and the string value contains UTF-8 > stuff (differing number of bytes per character), the length of the > resulting string (in characters) varies. How can I fix this? py> x = u"?a?o ?nico!" py> len(x) 11 py> len(x.encode("utf-8")) 14 py> f = u"%20s" % x py> f u' \xa1a\xf1o \xfanico!' py> print f ?a?o ?nico! py> len(f) 20 py> len(f.encode("utf-8")) 23 -- Gabriel Genellina From mr.cerutti at gmail.com Thu Mar 6 10:25:07 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Thu, 6 Mar 2008 10:25:07 -0500 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <51302a8c0803060725v4baa4033jea2c033730a64742@mail.gmail.com> On Thu, Mar 6, 2008 at 8:06 AM, Guillermo wrote: > I want to iterate recursively a dictionary whose elements might be > strings or nested tuples or dictionaries and then convert values to a > tagged format according to some rules. > > d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y': > ('a','b','c')}} This could be solved with dynamic polymorphism instead of introspection, which might simplify things depending on how your dictionary is constructed. class Value(object): def to_tagged_format(self): raise NotImplementedError class StringValue(Value): def to_tagged_format(self): ... class Tuplevalue(Value): def to_tagged_format(self): ... class DictValue(Value): def to_tagged_format(self): ... for k, v in d.iteritems(): d[k] = v.to_tagged_format() You can also get the dynamic polymorphism without invoking inheritance by specifying a protocol that the values in your dict must implement, instead. Protocols are plentiful in Python, perhaps more popular than type hierarchies. -- Neil Cerutti From martin at v.loewis.de Sat Mar 1 17:26:10 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Mar 2008 23:26:10 +0100 Subject: [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> Message-ID: <47C9D802.2090205@v.loewis.de> > As of 4:50 PM EST, the links to Windows installers give 404 File Not > Found. > > I gather that they are still in process, > and notice that there is no public c.l.p. announcement. I just fixed that. The files were there; just the links were wrong. Regards, Martin From jorgen.maillist at gmail.com Mon Mar 17 08:21:50 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Mon, 17 Mar 2008 13:21:50 +0100 Subject: comtypes question In-Reply-To: References: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> Message-ID: <11e49df10803170521w7c041c71l7d8e26c259bd9b95@mail.gmail.com> Hi Thomas, Thank you a lot for going through great lenghts to help me. I am relatively new to COM and to python, so using those two together is sometimes watching water burn and be totally amazed by it ;-) It's greatly aprpeciated that you installed the app and even checked out the typelib to see what might go wrong. I will investigate furter and look at your working example to see what I was missing in my code. I will also subscribe to the comtypes-users mailinglist for future questions. ps. For background info about Bartender, it is a label application and it can be automated by COM. By sending an XML script to it, I can set the variables for that label and issue a print command. With kind regards, - Jorgen On Mon, Mar 17, 2008 at 12:58 PM, Thomas Heller wrote: > Jorgen Bodde schrieb: > > > > Hi All, > > > > I am trying to automate a 3rd party application, and all I have to > > work on is the type library and some documentation. I hope a Python / > > COM guru can answer this or put me on the right path because I don't > > know why it does not work. > > > > First I imported the typelib with comtypes like; > > > >>> from comtypes.client import GetModule > >>> GetModule("C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe") > > > > Which blurbs out a lot of text: > > > > # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1 > > # Generating comtypes.gen.BarTender > > > 'C:\Python24\lib\site-packages\comtypes\gen\_D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1.pyc'> > > > > Which seems to be ok. Now, I need to call a function on the > > Application object on which I need a "Messages" instance. The > > Application object gets created properly: > > > >>> import comtypes.gen.Bartender as bt > >>> app = comtypes.client.CreateObject(bt.Application) > > > > Which gives me the application (the bt.Application points to a wrapper > > class containing the CLSID of the COM class to be instantiated). > > > > Now I browse the typelibrary and I see there is a CoClass called > > Messages. I need one of those to pass as an argument, and since > > Messages is listed as a CoClass similar to Application, I assume it > > can also be instantiated. But when I try this I get an error: > > > >>>> msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}') > > [...] > > > > WindowsError: [Errno -2147221164] Class not registered > > > > Both Application and Messages are listed as CoClass inside the > > typelibrary. Does anybody know why it gives me this error and what I > > am doing wrong? > > Not all coclasses can be created from scratch with CreateObject. Sometimes > they are created by calls to methods on some other object. > I downloaded the bartender trial, and looking into the typelib it seems that, > for example, the 'XMLScript' method on the IBtApplication interface returns > Messages instances: > COMMETHOD([dispid(17), helpstring(u'Runs xml scripts')], HRESULT, 'XMLScript', > ( ['in'], BSTR, 'XMLScript' ), > ( ['in'], BtXMLSourceType, 'SourceType' ), > ( ['out'], POINTER(POINTER(Messages)), 'Messages' ), > ^^^^^^^^ > ( ['retval', 'out'], POINTER(BSTR), 'retval' )), > > Here is an interactive session: > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from comtypes.gen import BarTender > >>> from comtypes.client import CreateObject > >>> app = CreateObject(BarTender.Application) > >>> print app > > >>> app.XMLScript("foo", 0) > (, u'') > >>> msg, retval = app.XMLScript("foo", 0) > >>> print msg > > >>> msg[0] > > Traceback (most recent call last): > File "", line 1, in > File "comtypes\__init__.py", line 308, in __getitem__ > result = self.Item(index) > _ctypes.COMError: (-2147220992, None, (u'The item at position 0 was not found.', u'bartend', None, 0, None)) > >>> msg[1] > > >>> m = msg[1] > >>> print m > > >>> m.Number > 3908 > >>> m.Message > u"An error occurred during XML script processing:\r\n\r\nInvalid at the top level of the document.\r\nLine 1, Column 1: > 'foo'" > >>> ^Z > > Not that the above makes much sense, but I hope it will get you started. > > Thomas > > BTW: The 'official' comtypes mailing list is at > https://lists.sourceforge.net/lists/listinfo/comtypes-users. Requires that you subscribe before you can > post, but you could disable mail delivery and use via gmane: gmane.comp.python.comtypes.user > > -- > http://mail.python.org/mailman/listinfo/python-list > From cmpython at gmail.com Sat Mar 22 03:10:22 2008 From: cmpython at gmail.com (CM) Date: Sat, 22 Mar 2008 00:10:22 -0700 (PDT) Subject: wxFormBuilder References: Message-ID: <7152b94f-fc30-473f-bd94-5d43a9153f56@p73g2000hsd.googlegroups.com> On Mar 20, 9:41 am, sturlamolden wrote: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed,Boa > constructor), this is the first one I can actually use. Why can't you use Boa Constructor? I really enjoy using it. From castironpi at gmail.com Fri Mar 28 15:20:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 12:20:22 -0700 (PDT) Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <5f8f15f4-36b7-49ce-bce6-521e76603054@y21g2000hsf.googlegroups.com> On Mar 28, 10:15?am, harryos wrote: > > The code is pretty legible as it is now. Anyway, using min() and a > > generator: > > hi > is this calculated distance really Euclidean distance? When i checked > wikipediahttp://en.wikipedia.org/wiki/Euclidean_distance > it shows a calculation involving sum of squares of the differences of > elements.Here in this code ,the sum of coordinates are used? is that a > different measure? I want the angle into an array. > < sign bit on distance to [zero element/kernel]. Are you coming out in uni-pole and/or lensed/focused/ parabolaed? Is that a yes-or-no question? From fkallgren at gmail.com Fri Mar 21 07:48:33 2008 From: fkallgren at gmail.com (fkallgren) Date: Fri, 21 Mar 2008 04:48:33 -0700 (PDT) Subject: Is this doable Message-ID: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Hi. I have a little problem. I have a script that is in the scheduler (win32). But every now and then I update this script and I dont want to go to every computer and update it. So now I want the program to 1) check for new version of the script, 2) if there is a new version, copy that verision from server to local drive, 3) shutdown the program and start it up again as the new version. The problem is that I can't run this script directly from server so it have to run it locally. Anyone having any bright ideas?? /fkallgren From paul at boddie.org.uk Thu Mar 20 21:28:28 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 20 Mar 2008 18:28:28 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <75fcc319-1f4b-4d24-8de6-7b1c56929fb0@8g2000hsu.googlegroups.com> On 21 Mar, 01:43, Simon Forman wrote: > > I've been thinking of volunteering to "port" Tkinter to Python 3.0, I > hadn't noticed that there was any discussion of removing it. That's because the forum for discussing these things wasn't mentioned on comp.lang.python until two days ago. Perhaps we're also about to find out that the Vogons are showing up shortly. Paul From castironpi at gmail.com Tue Mar 4 23:09:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:09:38 -0800 (PST) Subject: is there enough information? References: <13s9u7dg24es73a@corp.supernews.com> <13spkb990ha3v6c@corp.supernews.com> Message-ID: <392cadeb-e1f8-4cef-834c-a837ba7e02f5@59g2000hsb.googlegroups.com> On Mar 4, 5:59?pm, David Bolen wrote: > Dennis Lee Bieber writes: > > > > > > > On Mon, 3 Mar 2008 08:11:43 -0500, Jean-Paul Calderone > > declaimed the following in comp.lang.python: > > >> I'm not sure, but you seem to be implying that the only way to use Windows' > >> asynchronous I/O APIs is with threads. ?Actually, it is possible (and Twisted > >> allows you) to use these as well without writing a threaded application. > > > ? ?I only pointed out that, on Windows, one can not use the common > > /select()/ function with files. And one rarely sees examples of coding a > > Twisted-style (emphasis on style) asynchronous callback system mixing > > files and network sockes using the Windows-specific API. > > > ? ?If using threads, the Windows asynchronous I/O isn't needed... let > > the thread block until the I/O completes, then transfer the data (or a > > message that the data is available) back to the main processing > > thread... > > You're probably right that it's rare, but when needed, using the > Windows asynchronous/overlapping API can provide a better solution > than blocking threads depending on the needs at hand, and without > involving any callbacks or Twisted-style programming. > > An example of mine is high performance serial port handling as part of > a custom FHSS wireless adapter with a serial port interface to the PC. > In this case, minimizing I/O latency was crucial since delays could > mean missing a broadcast timeslot (about 15ms) on the wireless > network. ?A serial port isn't a disk file, but certainly a "file" in > the context of Windows handles. > > Early implementations used independent threads for reading/writing to > the serial port and blocking during such operations, but that turned > out to have an undesirable amount of latency, and was also difficult > to interrupt when the threads were in a blocked condition. > > Instead I created a single thread that had a loop using overlapped I/O > simultaneously in each direction as well as native Windows event > objects for aborting or signaling that there was additional data to be > written (the pending read I/O handled the read case). ?The main loop > was just a WaitForMultipleObjects to handle any of the I/O completion > indications, requests for more I/O or aborts. ?It was very high > performing (low latency) with low CPU usage - measurably better than a > multi-threaded version. > > Communication with the rest of the application was through a > thread-safe bi-directional buffer object, also using native Win32 > event objects. ?It worked similar to a queue, but by using the native > event objects I didn't have the performance inefficiencies for reads > with timeouts of the Python objects. ?The underlying Python primitives > don't have the timeout capability built in, so reads with timeouts get > implemented through checks for data interspersed with increasing > sleeps, which adds unnecessary latency. > > Anyway, it worked extremely well, and was a much better fit for my > needs than a multi-threaded version with blocking I/O, without it > having to be Twisted-style. > > -- David- Hide quoted text - > > - Show quoted text - How does it work? From reading threading.py, _Condition.wait() acquires self.lock() too many times-- that is, once to call wait ("cannot wait on un-aquired lock"), and once after--- are "all waiters" waiting back at self.acquire, just to make it to self.notify... and only one at a time at that!? Don't waiters have to release before another waiter can go? From grante at visi.com Fri Mar 21 18:59:02 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 21 Mar 2008 22:59:02 -0000 Subject: Subprocess and /usr/bin/dialog References: Message-ID: <13u8fdmq9hnsh06@corp.supernews.com> On 2008-03-21, harrelson wrote: > I am trying to get the below code to work and can't quite make things > happen. This is with Python 2.5.1. Dialog is doing something odd... > I have tinkered with different combinations and I can't get the dialog > to show properly-- it does show properly directly in the shell. Any > hints? > > import subprocess > command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 > 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" > "4 this and that"' > proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, > stderr=subprocess.STDOUT) > #proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) > stderr_value = proc.communicate()[0] > print stderr_value [It would be helpful if you didn't wrap sample code when you post it.] dialog displays the widget on stdout. You've connected stdout to a pipe, so you're not going to see anything displayed unless you read data from the stdout pipe and write it to the terminal. -- Grant Edwards grante Yow! Boy, am I glad it's at only 1971... visi.com From steve at holdenweb.com Mon Mar 31 06:35:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 06:35:48 -0400 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: Pradeep Rai wrote: > Hi All, > > I have upgraded python v2.5.2 from python v2.4.3. The upgradation > results into following error: > "Python C API version mismatch for module dbi: This Python has API > version 1013, module dbi has version 1012." > > Please suggest, how to resolve this error to proceed further. > > Regards, > Pradeep Rai > > Don't try and drag 2.4 extension modules into the 2.5 environemnt. You will have to install a 2.5 version of dbi for it to work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fakeaddress at nowhere.org Sun Mar 23 22:45:54 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 23 Mar 2008 19:45:54 -0700 Subject: Testing for an empty dictionary in Python In-Reply-To: References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: D'Arcy J.M. Cain wrote: > John Nagle wrote: >> What's the cheapest way to test for an empty dictionary in Python? > Try this: > > if dict: D'Arcy is right; that's the way to go. I'll add that 'dict' is the name of the built-in class, so an instance is usually best named something else. -- --Bryan From castironpi at gmail.com Sun Mar 9 18:34:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 15:34:19 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6d3lppl8lv2a@corp.supernews.com> Message-ID: > > >> Good comments are better than bad names. Good names are better than bad > > >> comments. > > > > If you're taking the time to write good comments, why not just fix the > > > bad names? ?The compiler/interpreter can never, ever catch bad comments. > > > Yes, but the Python compiler can only catch bad names if you do this at > > the top of every module: > > > import semantic_analysis > > import magic.crystal_ball.read_programmers_mind > > dir( magic )! > dir( magic.crystal_ball )? Someone should try annotating code with a dictionary lookup on identifiers. Anyone bored on Fridays? No one should try printing out the definitions in real-time as the code is executing. From gnewsg at gmail.com Mon Mar 24 14:34:23 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Mon, 24 Mar 2008 11:34:23 -0700 (PDT) Subject: Impersonate another user (Guest) on Windows Message-ID: <14cfc3e7-f07b-465c-99f9-8c3082047a12@u10g2000prn.googlegroups.com> Hi, I'm trying to write a plug-in for a ftp server of mine to permit the integration with accounts defined on the Windows system. What I basically need is impersonating a user, execute e filesystem call (e.g. create a directory via os.mkdir()) and then switch back to the original user (Administrator). I wrote down this simple class which seems to fit pretty well for my purposes: class WinNTAuthorizer: def impersonate_user(self, username, password): self.impersonated_user_handler = win32security.LogonUser( username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(self.impersonated_user_handler) def terminate_impersonation(self): win32security.RevertToSelf() self.impersonated_user_handler.Close() What I need now is impersonating the Guest user to handle the anonymous logins (which it's exactly what IIS FTPd does) but I don't know how to do it. Does Guest account has a password or do I have to use something different than LogonUser to manage it? Could someone point me in the right direction? Thanks in advance. --- Giampaolo http://code.google.com/p/pyftpdlib From harrelson at gmail.com Sat Mar 22 11:41:40 2008 From: harrelson at gmail.com (harrelson) Date: Sat, 22 Mar 2008 08:41:40 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> Message-ID: <9d220cde-e456-47d6-a9ba-b835812c870a@s12g2000prg.googlegroups.com> > > [It would be helpful if you didn't wrap sample code when you > post it.] > > dialog displays the widget on stdout. You've connected stdout > to a pipe, so you're not going to see anything displayed unless > you read data from the stdout pipe and write it to the terminal. Also... if I put the dialog call in a one line shell script and execute it with: subprocess.call('dialog.sh') it works properly. From python.list at tim.thechases.com Tue Mar 11 09:45:26 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Mar 2008 08:45:26 -0500 Subject: parsing directory for certain filetypes In-Reply-To: <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> Message-ID: <47D68CF6.7020203@tim.thechases.com> royG wrote: > On Mar 10, 8:03 pm, Tim Chase wrote: > >> In Python2.5 (or 2.4 if you implement the any() function, ripped >> from the docs[1]), this could be rewritten to be a little more >> flexible...something like this (untested): >> > > that was quite a good lesson for a beginner like me.. > thanks guys > > in the version using glob() >> path = os.path.normpath(os.path.join(folder, '*.txt')) >> lst = glob.glob(path) > > is it possible to check for more than one file extension? here i will > have to create two path variables like > path1 = os.path.normpath(os.path.join(folder, '*.txt')) > path2 = os.path.normpath(os.path.join(folder, '*.doc')) > > and then use glob separately.. Though it doesn't use glob, the 2nd solution I gave (the one that uses the any() function you quoted) should be able to handle an arbitrary number of extensions... -tkc From hiteshthakkar.h at gmail.com Tue Mar 11 13:53:29 2008 From: hiteshthakkar.h at gmail.com (hitesh thakkar) Date: Tue, 11 Mar 2008 23:23:29 +0530 Subject: XML-SAX parser problem Message-ID: <5ae40d820803111053q6bcdde19s6ad34ecb9b8bbc25@mail.gmail.com> Hello, Can any one help for error in following code. actually i want to map parent element with child element, but i am unable to do so. here is the code which i am trying for please do reply if iam not on right track. import xml.sax.handler class BookHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inTitle1 = 0 self.inTitle2 = 0 self.mapping1 = {} self.mapping2 = {} def startElement(self, name, attributes="NULL"): #attributes="None" if name == "emph3": self.buffer1 = "" self.inTitle1 = 1 # self.id = attributes["None"] elif name == "year": self.buffer2 = "" self.inTitle2 = 1 def characters(self,data): if self.inTitle1 == 1: self.buffer1 += data elif self.inTitle2 == 1: self.buffer2 += data def endElement(self,name): if name == "year": self.inTitle2 = 0 self.mapping2[self.name] = self.buffer2 elif name =="emph3": self.inTitle1 =0 self.mapping1[self.name] = self.buffer1 # # # Jose Joaquin Avila # 1929 # # Yiye Avila # 1941 # # -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert_rawlins at hotmail.com Mon Mar 24 11:12:28 2008 From: robert_rawlins at hotmail.com (Robert Rawlins) Date: Mon, 24 Mar 2008 15:12:28 +0000 Subject: Element Tree Help Message-ID: Hello Guys,I have little to no experiance with element tree and I'm struggling to find a way to parse the details from the XML document (attached) into my application. Essentialy I'm looking to take the following document and turn it into a dict of tuples, each dict element defines a datasource with the key to the element being the 'name' which is defined in the XML and then the value of the pair is a tuple which contains the details of the datasource, like the host and port etc.I've attached a copy of the example XML to this email.Can anyone offer some advice on how to get started with this? I've spent a little time looking over the documentation of element tree and have struggled to break the ice and parse this document.Thanks guys,Robert _________________________________________________________________ The next generation of Windows Live is here http://www.windowslive.co.uk/get-live -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: datasources.txt URL: From python at bdurham.com Sat Mar 15 08:06:39 2008 From: python at bdurham.com (Malcolm Greene) Date: Sat, 15 Mar 2008 08:06:39 -0400 Subject: Python for Palm OS In-Reply-To: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Message-ID: <1205582799.12820.1242548149@webmail.messagingengine.com> E-Lo, PalmPython ???? http://c2.com/cgi/wiki?PalmPython I have no experience with Python for Palm OS's. This is just a reference from my personal notes. Malcolm From pradiprai at gmail.com Fri Mar 14 09:31:40 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Fri, 14 Mar 2008 19:01:40 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave_mikesell at fastmail.fm Mon Mar 3 07:17:37 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Mon, 3 Mar 2008 04:17:37 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: <6c90f26b-e7b7-4048-bf98-ef5ed5bba462@u72g2000hsf.googlegroups.com> On Mar 1, 10:53 pm, Kay Schluehr wrote: > On 1 Mrz., 19:51, Barry Warsaw wrote: > > > Python 2.6 is not only the next advancement in the Python 2 series, it > > is also a transitionary release, helping developers begin to prepare > > their code for Python 3.0. > > Isn't this a silly idea? People have to migrate from 2.5 or lower > releases to Python 2.6 first just to migrate to Python 3.0? What are > the inherent / technical reasons that prevent migration directly from > 2.5 to 3.0? Not only that, you have to wait for your library providers to migrate first (PyOpenGL, PyGame, PIL, etc for me). Hopefully this is the last quantum shift for a while. From shakefu at gmail.com Fri Mar 7 17:10:57 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:10:57 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <9a07507e-b8eb-440c-92af-62278cd36b5e@d62g2000hsf.googlegroups.com> On Mar 7, 4:08 pm, shak... at gmail.com wrote: > I'm new to python and I was wondering if there are any intelligent > date/time parsing modules out there. I've looked at strptime (or > whichever it is) and mxDateTime from the eGenix package. I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. > > So are there any modules that allow for that kind of parsing? I forgot to say, thanks ahead of time, and I'd appreciate any direction that you can give me! (How rude of me!) - Jacob Alheid From rakesh.usenet at gmail.com Sun Mar 2 14:56:32 2008 From: rakesh.usenet at gmail.com (Rakesh Kumar) Date: Sun, 2 Mar 2008 11:56:32 -0800 (PST) Subject: cx_Freeze : LookupError: unknown encoding: ascii References: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> <47c9e9bc$0$4562$9b622d9e@news.freenet.de> Message-ID: <5ecd5295-1570-45d2-9dcc-39425523fa2e@s19g2000prg.googlegroups.com> On Mar 1, 3:41?pm, "Martin v. L?wis" wrote: > > Can somebody point to some clues about options that need to be passed > > to FreezePython API to get the right executable. > > You need to tell it to include the encodings.ascii module. > > Regards, > Martin Thanks Martin. Adding something like ./freeze --include-modules=encodings.ascii,encodings.utf_8 fixed the issue. From lipun4u at gmail.com Tue Mar 11 15:17:14 2008 From: lipun4u at gmail.com (asit) Date: Tue, 11 Mar 2008 12:17:14 -0700 (PDT) Subject: mulithreaded server References: Message-ID: <0e845694-2788-43e2-b88b-86bbbbe3c7c0@e23g2000prf.googlegroups.com> On Mar 11, 9:10 pm, Jean-Paul Calderone wrote: > On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit wrote: > >import socket > >import sys > >import thread > > >p=1 > >PORT=11000 > >BUFSIZE=1024 > > >def getData(cSocket): > > global stdoutlock,cSocketlock > > while True: > > cSocketlock.acquire() > > data=cSocket.recv(BUFSIZE) > > if data=='q': > > data='client exited' > > cSocket.close() > > p=0 > > cSocketlock.release() > > stdoutlock.acquire() > > stdout.write(data) > > stdoutlock.release() > > >def sendData(cSocket): > > global stdoutlock,cSocketlock > > while True: > > stdoutlock.acquire() > > data=raw_input('>>') > > cSocketlock.acquire_lock() > > if data=='q': > > stdout.write('server exited') > > stdout.release() > > p=0 > > cSocket.close() > > sSocket.send(data) > > sSocketlock.release() > > Could it be because `sSocketlock? here > > > > >stdout=sys.stdout > >host='' > >sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > >sSocket.bind((host,PORT,)) > >sSocket.listen(1) > >#sSocketlock=thread.allocate_lock() > > is never bound since the line above here is commented out? > > >stdoutlock=thread.allocate_lock() > >print 'waiting for connection' > >cSocket,addr=sSocket.accept() > >print 'connection from',addr > >cSocketlock=thread.allocate_lock() > >thread.start_new_thread(sendData,(cSocket,)) > >thread.start_new_thread(getData,(cSocket,)) > >if p==0: > > sSocket.close() > > >In the above program, why there is an unhandeled exception ??? > > Just a guess. You should really include the traceback when you ask a > question like this. > > Jean-Paul It's not a traceback error. It's an unhandeled exception..please help From larry.bates at websafe.com` Tue Mar 25 10:57:20 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 25 Mar 2008 09:57:20 -0500 Subject: Reading new mail from outlook In-Reply-To: References: <315315.36624.qm@web50108.mail.re2.yahoo.com> Message-ID: Tim Golden wrote: > SPJ wrote: >> I am trying to create new tickets in the ticketing system using >> python. When I receive new email from a particular address, I have to >> trigger the python script and parse the mail in required format. >> >> The main hurdle here is, how to invoke the script on arrival of new >> mail? I checked the outlook settings and found that it supports only >> microsoft VB script and Jscript. Is there any other way? I mean, if I >> make a daemon, how will it be notified of new mail? Is there any >> python module that does this? >> >> I am not sure if this is the right place to ask this, since it is also >> a microsoft related question. But any help is appreciated. > > Outlook does have some events in its automation interface > (which you can handle from within Python by using > win32com.client.DispatchWithEvents) but if an immediate response > weren't critical it's probably slightly easier to schedule a job > to interrogate the mailbox every so often and harvest any new > emails. Depends on your particular need. > > TJG Best way I can think of is to get a copy of SpamBayes source code and see how it is done there. Much easier to look at something that already looks at new messages as they arrive in the Inbox than to try to figure it out. http://spambayes.sourceforge.net/windows.html -Larry From bbxx789_05ss at yahoo.com Tue Mar 18 23:58:06 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 18 Mar 2008 20:58:06 -0700 (PDT) Subject: Need Help Starting Out References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <9a2df924-99b0-4dd1-b5b7-5e0fca17dc04@e39g2000hsf.googlegroups.com> On Mar 18, 10:10?am, jmDesktop wrote: > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. ? I think you are getting ahead of yourself. Get the book Learning Python(3rd edition), which just came out, and start at the beginning. I think the proper order is to learn the basics first, then learn an application of the language that you are interested in, i.e. web programming. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 19:32:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 00:32:03 -0000 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> <13t2cget4hubma9@corp.supernews.com> Message-ID: <13t6c03hs3bg067@corp.supernews.com> On Sat, 08 Mar 2008 09:52:41 -0800, castironpi wrote: > On Mar 7, 6:16?am, Steven D'Aprano cybersource.com.au> wrote: >> On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote: >> > you >> > could say exec( open( 'modA.py' ).read() ) ==> import modA >> >> Yes, you could say that, but you'd be wrong. Please test your code >> before making such claims in the future. > > Aye aye. -1 response not phrased in the form of a question. All the words in that sentence are English, but as a whole it makes no sense. > Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA > import * create "effectively" same results, You're getting closer now. (By the way, exec is a statement, so you don't need brackets around its arguments.) exec open('modA.py').read() gives *almost* the same results as from modA import * The differences I can think of: (1) The exec version doesn't cache the results, so if you execute the line repeatedly you will execute the same code over and over again, possibly causing unexpected side-effects. import caches the results, and so will be faster. (2) The import version may read from modA.pyc, modA.pyo or modA.so even if there is a modA.py file. The exec version can't import from anything but modA.py. (3) The exec version as written always puts the results in the global scope, even if you execute it inside a function. (In the future, "from modA import *" will be forbidden inside functions, but at the moment it is still legal.) (4) The exec version doesn't search sys.path for modA; import does. (5) The exec version can't read modules inside a zip file; import can. There may be other differences I haven't thought of. > such as in the remaning > program not checking __module__ attributes? Again, I don't understand what you are saying. > Is there a slight modification of both sides that does cover a non- > trivial volume of programs, such as maybe, exec( open( 'modA.py' > ).read(), locals= dict( __module__= 'modA' ) ) - and- from modA import > *, or something? *Slight* modification, no. I'm sure that with sufficient effort, you could add caching, search sys.path, and look inside zip files. Those three things wouldn't be horribly difficult, but it wouldn't be a one-liner -- off the top of my head, I'd guess fifty to a hundred lines of code to re-invent those particular wheels correctly. However, recreating the rest of the import mechanism would be terribly complicated. I'm not really sure it could be done. For example, how would you deal with modules written in C from within Python? You'd need access to Python internals that, as far as I know, aren't available. -- Steven From goon12 at gmail.com Tue Mar 11 11:04:42 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 11 Mar 2008 11:04:42 -0400 Subject: difference b/t dictionary{} and anydbm - they seem the same In-Reply-To: <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> Message-ID: <6a2ccd190803110804u76cb06edkb54d6f951b045494@mail.gmail.com> On Tue, Mar 11, 2008 at 10:58 AM, davidj411 wrote: > Thanks, that makes sense. Are there any local relational databases > available to python that don't require a server backend? sqlite http://www.sqlite.org/ From grante at visi.com Thu Mar 20 17:25:26 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 21:25:26 -0000 Subject: Code folder with Emacs Message-ID: <13u5li6kspler51@corp.supernews.com> Has anybody figured out how to do code folding of Python source files in emacs? I tried "hide-show" minor mode, but it doesn't really work for Python code: the only think it knows how to hide/show are function bodies. It can't do normal things like hide/show a code block like it can for other languages. Google also found my "folding mode", but that's based on user-inserted tokens and isn't syntax aware. -- Grant From rodmena.com at gmail.com Wed Mar 12 12:35:07 2008 From: rodmena.com at gmail.com (Farsheed Ashouri) Date: Wed, 12 Mar 2008 09:35:07 -0700 (PDT) Subject: Py2exe and Multi Treading problem. References: Message-ID: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> NO it dont work. If I remove threading part, it works like a charm. Any Idea? From arnodel at googlemail.com Thu Mar 13 15:13:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 12:13:19 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> Message-ID: On Mar 13, 10:42?am, Paul Rubin wrote: [...] > By Python convention, methods that mutate the object return None, and > also stuff that returns None doesn't generate output at the > interactive prompt. A convention that does not always hold: >>> l = [1, 2, 3] >>> l.pop() 3 >>> l [1, 2] >>> There is also the .next() method: >>> i = iter([1, 2, 3]) >>> i.next() 1 >>> i.next() 2 >>> I can't think of others ATM in python 2.x but there might be some. Moreover PEP 3119 introduces .add(), .discard(), .toggle() for MutableSets which all mutate self and return a non None object. -- Arnaud From danb_83 at yahoo.com Sat Mar 8 20:27:32 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 8 Mar 2008 17:27:32 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 1:31 pm, Grant Edwards wrote: ... > > What I really can't stand are the pointy-haired comment blocks > at the beginnings of C/C++ functions that do things like tell > you the name and return type of the function and list the names > and types of the parameters. Gee, thanks. I never could have > figured that out from looking at the source code itself. IMO, > comments explaining what the parameters are used for usually > indicates that the parameter names were poorly chosen. You must work for the same company I do. I've seen a whole bunch of comments that look like: //--------------------------------------------------------------------------- // CXyzBase::LogMessage // // Write a message to the log. // // Args: // strMsg = the message to log // void CXyzBase::LogMessage(const CString& strMsg) { // } And even worse, at the top of that file: //--------------------------------------------------------------------------- // XyzBase.cpp // // This file contains the implementation of class CXyzBase. // // Copyright (C) 2008 Foobar Computer Consulting // // VERSION PROJECT# DATE DESCRIPTION // ------- -------- -------- ------------------ // 1.00 123456 01/04/08 Original creation. // Eleven lines, of which the only useful information to me was the project number, as knowing this let me look up who was behind these comments. From nkavitha551 at gmail.com Thu Mar 6 05:58:49 2008 From: nkavitha551 at gmail.com (nkavitha551 at gmail.com) Date: Thu, 6 Mar 2008 02:58:49 -0800 (PST) Subject: Your Fortune for the Day!!! Message-ID: <600833ea-38d6-43e0-9d7c-d867c37aa664@i29g2000prf.googlegroups.com> Hi, To know what it is? Visit the website below and be cool !!! ------------------------------------------------------------------------------ http://myprofilekavitha.blogspot.com/ ------------------------------------------------------------------------------- From bernard at blimyk.org Mon Mar 17 02:23:41 2008 From: bernard at blimyk.org (Bernard Lim) Date: Mon, 17 Mar 2008 06:23:41 +0000 (UTC) Subject: Immutable and Mutable Types Message-ID: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> Hi, I'm reading the Python Reference Manual in order to gain a better understanding of Python under the hood. On the last paragraph of 3.1, there is a statement on immutable and mutable types as such: Depending on implementation, for immutable types, operations that compute new values may or may not actually return a reference to any existing object with the same type and value, while for mutable objects this is (strictly)? not allowed. Using the example given in 3.1, how do I verify that this is true pertaining to immutable types? Below is my understanding on verifying the above statement: >>> a = 1 >>> b = 1 >>> a is b True >>> id(a) 10901000 >>> id(b) 10901000 Is this correct? Regards Bernard From bronger at physik.rwth-aachen.de Sun Mar 30 06:40:03 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 30 Mar 2008 12:40:03 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> Message-ID: <87od8w7aws.fsf@physik.rwth-aachen.de> Hall?chen! Bjoern Schliessmann writes: > Lie wrote: > >> Ah yes, that is also used (I completely forgot about that one, my >> math's aren't that sharp anymore) and I think it's used more >> frequently than ><. > > Where did you read that (I mean, which country)? I've never seen > this sign in any german or english book on > mathematics/physics/engineering I saw. Maybe he means "?". >> but my argument was that no math book use != or <> (except in >> math for programmers). > > That's true. Personally, I don't ever use "a!=b" in favor of "not > a==b". As a side note, I've always found == rather ugly. I'd prefer to have = for both purposes. The constructs that wouldn't work anymore are rare as far as I can see (and possibly there are even workarounds). Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From arnodel at googlemail.com Fri Mar 14 15:23:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 14 Mar 2008 12:23:20 -0700 (PDT) Subject: Custom Exception Value? References: <5fbe35d4-6590-41c2-824d-0b1656173829@x30g2000hsd.googlegroups.com> Message-ID: On Mar 14, 6:47?pm, erikcw wrote: > Hi, > > When I use sys.exc_info() on one of my custom exception classes, the > "message"/value isn't returned. ?But it is when I use a built in > exception. > > Example: > > In [32]: class Test(Exception): > ? ?....: ? ? def __init__(self, x): > ? ?....: ? ? ? ? self.value = x > ? ?....: ? ? def __str__(self): > ? ?....: ? ? ? ? return repr(self.value) > ? ?....: > ? ?....: > In [39]: try: > ? ?....: ? ? raise Test('mess') > ? ?....: except: > ? ?....: ? ? sys.exc_info() > ? ?....: > ? ?....: > Out[39]: (, Test(), 0xb7802e8c>) > > In [40]: try: > ? ?....: ? ? 1/0 > ? ?....: except: > ? ?....: ? ? sys.exc_info() > ? ?....: > ? ?....: > Out[40]: > (, > ?ZeroDivisionError('integer division or modulo by zero',), > ?) > > Wy does the output of ZeroDivisionError appear in sys.exc_info() but > for test it is just Test() (should be Test('mess') right??) Three ways to do it right: * Override __repr__() rather than __str__ or forget about __repr__() and instead: * call super(Test, self).__init__(x) from within Test.__init__() or even * self self.args = (x,) within Test.__init__() HTH -- Arnaud From gabriel.rossetti at mydeskfriend.com Thu Mar 27 06:15:17 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 11:15:17 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: <47EB6480.2080402@wtf.websiteburo.oops.com> References: <47EB6480.2080402@wtf.websiteburo.oops.com> Message-ID: <47EB73B5.8020804@mydeskfriend.com> Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : >> Hello, >> >> I am using Partial Function Application in a class and I've come up >> with a problem, when the method is called it tries to pass "self" to >> the curried/partial function, but this should be the first argument >> in reality, but since the function is curried, then the self gets >> passed as the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that >> since self is not available there. Does anyone have any ideas? > > registerServiceAtomic = partial(__registerService, atomic=True) > registerServiceNonAtomic = partial(__registerService, atomic=False) > > Caveat: you'll have to either invert the order of the atomic and > service params, or call the partials with named arg for service. > > HTH > Ok, thanks, I didn't know you could do that, I though partial was always left to right (I had read that about curry) Gabriel From http Thu Mar 27 17:24:42 2008 From: http (Paul Rubin) Date: 27 Mar 2008 14:24:42 -0700 Subject: Instrumented web proxy References: Message-ID: <7xod8zrhb9.fsf@ruckus.brouhaha.com> Andrew McLean writes: > I would like to write a web (http) proxy which I can instrument to > automatically extract information from certain web sites as I browse > them. Specifically, I would want to process URLs that match a > particular regexp. For those URLs I would have code that parsed the > content and logged some of it. > > Think of it as web scraping under manual control. I've used Proxy 3 for this, a very cool program with powerful capabilities for on the fly html rewriting. http://theory.stanford.edu/~amitp/proxy.html From guillermo.listas at googlemail.com Thu Mar 6 08:06:50 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Thu, 6 Mar 2008 05:06:50 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: Wow, I think I'm gonna like this forum. Thank you all for the prompt answers! >What makes you say you "need" to know this ? Except for a couple corner >cases, you usually don't need to care about this. If you told us more >about the actual problem (instead of asking about what you think is the >solution), we might be of more help... Good point. I want to iterate recursively a dictionary whose elements might be strings or nested tuples or dictionaries and then convert values to a tagged format according to some rules. d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y': ('a','b','c')}} I'm just designing the algorithm, but I think Python dictionaries can hold any kind of sequence? Regards, Guillermo From jason.scheirer at gmail.com Thu Mar 27 14:18:21 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 27 Mar 2008 11:18:21 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: On Mar 27, 8:40 am, mungkol wrote: > Dear all, > > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: > > running install > running build > running build_ext > building 'Stemmer' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- > prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 > -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- > i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o > In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > syslimits.h:7, > from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > limits.h:11, > from libstemmer_c/src_c/../runtime/header.h:2, > from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: > /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: > limits.h: No such file or directory > error: command 'gcc' failed with exit status 1 > > Did anyone experience this before? > > Any comment/suggestion is highly appreciated. > > Thank you. > > Best regards, > > Supheakmungkol This is a system configuration issue, not a Python issue: you seem to be missing a header file. First, make sure it exists ( /usr/lib/gcc/ i486-linux-gnu/4.1.3/include/limits.h ) and that you have permission to read it. If it's there, just sudo chmod a+r it and see if that helps. Also try installing Ubuntu's standard essential build tools ( sudo apt-get update && sudo apt-get install build-essential ) and see if that helps From cruxic at gmail.com Sat Mar 8 11:28:29 2008 From: cruxic at gmail.com (Cruxic) Date: Sat, 8 Mar 2008 08:28:29 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <6kyAj.284$Ls6.153@trnddc01> Message-ID: On Mar 8, 7:32 am, Alan Isaac wrote: > Cruxic wrote: > > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) > > ... > > p = people.get_equivalent(2) #method doesn't exist as far as I know > > print p.name #prints Sue > > def get_equivalent(test, container): > > for p in container: > > if p == test: > > return p > > hth, > > Alan Isaac > > #example (note change in __eq__ to match your case; fix if nec) > > class Person: > > def __init__(self, id, name): > > self.id = id > > self.name = name > > def __hash__(self): > > return self.id > > def __eq__(self, other): > > return self.id == other > > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) > > get_equivalent(2,people) That works fine for small data sets but my goal is to avoid a linear search, instead leveraging the O(1) lookup time for a hash based set. From http Fri Mar 28 20:19:04 2008 From: http (Paul Rubin) Date: 28 Mar 2008 17:19:04 -0700 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> <47ed882d$0$26468$afc38c87@news.optusnet.com.au> Message-ID: <7x63v6tm9z.fsf@ruckus.brouhaha.com> Richard Jones writes: > Check out tinypy: > http://www.philhassey.com/blog/category/tinypy/ I don't really understand the point of it. See also: http://hedgehog.oliotalo.fi/ From sturlamolden at yahoo.no Tue Mar 18 13:30:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 10:30:37 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: On 18 Mar, 17:48, Miki wrote: > Apart from PIL, some other options are: > 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object > you can draw on Yes, but at least on Windows you will get a GDI canvas. GDI is slow. > 2. A bit of an overkill, but you can use PyOpenGL OpenGL gives you a fast 'bitblit' for drawing bitmaps to the fram buffer (much faster than GDI). Here is some C code that does that (8- bit color depth). Translating to Python is trivial. I prefer not to use PyOpenGL as it has some unwanted overhead. It is better to use ctypes. void bitblt(void *frame, int w, int h) { glViewport(0,0,w,h); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRasterPos2i(0,0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glDrawPixels(w, h, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, (GLvoid *)frame); glFlush(); } From fetchinson at googlemail.com Thu Mar 6 01:17:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 5 Mar 2008 22:17:45 -0800 Subject: What is a class? In-Reply-To: References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> Message-ID: > > Where to begin? > > What does exec( open( 'modA.py' ).read() ) do? The most appropriate list to ask those questions is: http://mail.python.org/mailman/listinfo/tutor From josef.pktd at gmail.com Sat Mar 15 17:42:07 2008 From: josef.pktd at gmail.com (joep) Date: Sat, 15 Mar 2008 14:42:07 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> Message-ID: <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> > > http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... Note: this works for subprocess.call but for subprocess.Popen this does not work if there are two arguments in the command line with spaces. Especially, even after trying out many different versions, I never managed to get subprocess.Popen to work, when both the executable and one argument have spaces in the file path. subprocess.Popen requires the same extra double quoting at front or around the entire command as os.system. It took me many hours to find the versions of quoting that work. Explanation by Fredrik Lundh in thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/775ca566af9a70c2/65504296a27b43d5?lnk=gst&q=subprocess+windows+spaces#65504296a27b43d5 Here is a test file checking several cases: '''use winrar to get file information of a rar file testing double quotes for windows file paths with spaces using subprocess.Popen see: http://groups.google.com/group/comp.lang.python/browse_thread/thread/775ca566af9a70c2/65504296a27b43d5?lnk=gst&q=subprocess+windows+spaces#65504296a27b43d5 result: * most robust: use double quotes around entire command string * command as list argument never works when 2 file paths have spaces ''' import sys, os import subprocess def rargetinfo(filename,version=0): '''use winrar to get file information of a rar file ''' if version == 0: rarcmd = '"%s %s %s ' % (r'"C:\Program Files\WinRAR\Rar.exe"', "v", filename) elif version == 1: rarcmd = '"%s %s %s" ' % (r'"C:\Program Files\WinRAR \Rar.exe"', "v", filename) elif version == 2: rarcmd = '%s %s %s ' % (r'"C:\Program Files\WinRAR\Rar.exe"', "v", filename) elif version == 3: rarcmd = [r'"C:\Program Files\WinRAR\Rar.exe"', "v", filename] elif version == 4: executable_name = os.path.join(r'C:\Program Files\WinRAR', 'Rar.exe') rarcmd = [executable_name, "v", filename] p = subprocess.Popen(rarcmd, shell=True, stdout=subprocess.PIPE) rettext,reterror = p.communicate() retcode = p.wait() p.stdout.close() print rarcmd print 'this is rettext',rettext[:50] return rettext, rarcmd filenames = [r'"C:\temp\Copy of papers.rar"'] filenames.append(r'"C:\temp\papers.rar"') filenames.append(r'C:\temp\papers.rar') positives = {} negatives = {} for filename in filenames: for version in range(5): print '\n%s version: %d' % (filename,version) rettext, cmd = rargetinfo(filename,version) if rettext : print 'success' positives.setdefault(version,[]).append(cmd) else: print 'failure' negatives.setdefault(version,[]).append(cmd) from pprint import pprint print 'positives:' pprint(positives) print 'negatives:' pprint(negatives) From grante at visi.com Fri Mar 7 13:22:12 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 07 Mar 2008 18:22:12 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t2vvstgkne233@corp.supernews.com> <63ddtqF27a5u2U1@mid.individual.net> Message-ID: <13t31ukn750vr22@corp.supernews.com> On 2008-03-07, K Viltersten wrote: >>> Personally, I dislike double spaces after sentences, but it is >>> not wrong to put them there any more than it is wrong not to >>> put them there. >> >> You're lucky my high school typing teacher didn't hear you say >> that... > > I'm unclear if your teacher was a double or single spacer. Double. > It's only implied that he felt strongly one way. She, actually. Leaving out one of the two spaces after the end of a sentence was no less an error than leaving out the period or forgetting to capitalize the first word of the next sentence. AFAIK, that's the way pretty much everybody was taught to type back then (1977). If you're using a word-processor or typesetting system that's worth its weight in bits, it won't matter how many spaces you type -- the paragraph layout algorithm will handle it. -- Grant Edwards grante Yow! I'm having fun at HITCHHIKING to CINCINNATI visi.com or FAR ROCKAWAY!! From modelnine at modelnine.org Tue Mar 25 18:15:36 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Tue, 25 Mar 2008 23:15:36 +0100 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: <200803252315.36924.modelnine@modelnine.org> Am Dienstag, 25. M?rz 2008 23:02:00 schrieb Dark Wind: > In most of the languages ^ is used for 'to the power of'. In python we have > ** for that. But what does ^ do? ^ is the binary exclusive-or (xor) operator. Possibly it helps to see the following (numbers are in binary) to get the drift: 00 ^ 01 = 01 01 ^ 01 = 00 10 ^ 01 = 11 11 ^ 01 = 10 -- Heiko Wundram From gatti at dsdata.it Sat Mar 1 11:07:56 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Sat, 1 Mar 2008 08:07:56 -0800 (PST) Subject: Beginner's assignment question References: Message-ID: On Mar 1, 3:39 pm, Schizoid Man wrote: > As in variable assignment, not homework assignment! :) > > I understand the first line but not the second of the following code: > > a, b = 0, 1 > a, b = b, a + b > > In the first line a is assigned 0 and b is assigned 1 simultaneously. > > However what is the sequence of operation in the second statement? I;m > confused due to the inter-dependence of the variables. The expressions of the right of the assignment operator are evaluated before assigning any new values, to the destinations on the left side of the assignment operator. So substitutig the old values of a and b the second assignment means a, b = 0, 0 + 1 Simplifying the Python Reference Manual ("6.3 Assignment Statements") a little : assignment_stmt ::= target_list "="+ expression_list An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. [...] WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (for example "a, b = b, a" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "[0, 2]": x = [0, 1] i = 0 i, x[i] = 1, 2 print x Lorenzo Gatti From Lie.1296 at gmail.com Thu Mar 20 03:56:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 20 Mar 2008 00:56:13 -0700 (PDT) Subject: Is this valid ? References: Message-ID: On Mar 20, 4:18?am, Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > > thanks, > Stef Mientki a == b == 2 is equivalent to a == b and b == 2 except that b is only evaluated once for the whole comparison From dave_mikesell at fastmail.fm Fri Mar 7 23:57:32 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Fri, 7 Mar 2008 20:57:32 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> Message-ID: <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> On Mar 7, 10:38 pm, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 20:04:47 -0800, dave_mikesell wrote: > > On Mar 7, 10:31 am, "K Viltersten" wrote: > >> I've been recommended reading > >> of:http://www.python.org/dev/peps/pep-0008/and in there i saw two > >> things that i > >> need to get elaborated. > > >> 1. When writing English, Strunk and > >> White apply. > > > If your code needs so much descriptive prose that you have to consult > > Strunk and White, refactor it to be more clear. Excessive comments are > > the hobgoblin of overly complex and/or sloppy code. > > Nonsense. Poor English is poor English whether you're writing short one- > line comments or three hundred page manuals. > > store = make_store() > x = get_stuff(store) # Get the stuff what was brought at the store. Perfect example of an unnecessary comment. The variable and function names are commentary enough. From robert.kern at gmail.com Sat Mar 8 15:58:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 08 Mar 2008 14:58:02 -0600 Subject: distutils - Is is possible to install without the .py extensions In-Reply-To: References: Message-ID: Jari Aalto wrote: > * Fri 2008-03-07 Robert Kern gmane.comp.python.general > * Message-Id: fqt61a$sj5$1 at ger.gmane.org > >>>>> setup(name='program', >>> ... >>>>> scripts = ['program,py'], >>>>> ) >>>>> that the the result is: >>>>> >>>>> /usr/bin/program >>>>> >>>>> instead of: >>>>> >>>>> /usr/bin/program.py >>>> The easiest and best way is to just rename the file in your source tree to >>>> "program" and be done with it. >>> Is there any other way? This is the source package that I would like >>> to keep intact and just patch the setup.py >> Not really, no. Why is it so important to only patch the setup.py >> file and not any others? > > It has to do with generating a diff against the original package. If > the file is moved: > > mv file.py file > > prior setup.py run (which, according to answers, would have a change > to <>), the problem is the generated diff > against original sources: > > + would flag removal of 'file.py' > + inclusion of 'file' > > The ideal would be if setup.py could do all the destination install > "postwork". The generated patch would be clean and only contain > changes in setup.py. > > But I understand, if distutils does not support stripping the > extensions during install. It just cacuses exra work for utility > packagers. What build system are you using that doesn't let you execute cp file.py file before running the setup.py? -- 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 george.sakkis at gmail.com Wed Mar 12 15:58:33 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 12 Mar 2008 12:58:33 -0700 (PDT) Subject: Does __import__ require a module to have a .py suffix? References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: <05559d08-2479-4178-830c-adf65dfc733c@s37g2000prg.googlegroups.com> On Mar 12, 12:22 pm, mrstephengross wrote: > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? You can use execfile: foo = {} execfile('foo', foo) Apart from the different syntax in accessing the module globals (attributes with __import__ (foo.x) vs dict entries with execfile (foo['x'])), there are probably more subtle differences but I can't tell for sure. It would be nice if someone more knowledgeable can compare and contrast these two appraches. George From florian.harmuth at googlemail.com Mon Mar 17 08:12:22 2008 From: florian.harmuth at googlemail.com (mich1985) Date: Mon, 17 Mar 2008 05:12:22 -0700 (PDT) Subject: SAXReaderNotAvaiable after switching Python Message-ID: <0e990748-2e57-46ce-9a8e-2f0b89754d7c@z38g2000hsc.googlegroups.com> Hello all, after i have switched from python-2.4.2 to python-2.4.3 i get the following message if run my web configuration: parser = xml.sax.make_parser() ..... SAXReaderNotAvailable: No parsers found The files under /usr/lib/python2.4/xml/sax are the same as before. Any hints where i can start my search? (a ng search didn't solved my problem). Best Regards, flo From arnodel at googlemail.com Mon Mar 3 05:32:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 3 Mar 2008 02:32:49 -0800 (PST) Subject: First post from a Python newbiw References: Message-ID: <41cfe2c1-51d0-4b15-b9c8-ea3d4389b6cf@e6g2000prf.googlegroups.com> Steve Turner wrote: > I finally decided to have a go with Python and am working through the > tutorial. Great! > On my old BBC Computer [...] These were nice machines... > In Python I thought I could do this with: > > >>> a=[0,0,0] > >>> b=[a,a,a] > >>> b > [[0, 0, 0], [0, 0, 0], [0, 0, 0]] > >>> b[1][1]='foo' > >>> b > [[0, 'foo', 0], [0, 'foo', 0], [0, 'foo', 0]] > >>> > > I can understand why as b[1][1]='foo' is actually changing a[1] > > Apart from doing something like > a=[0,0,0] > b=[0,0,0] > c=[0,0,0] > d=[a,b,c] > > is there a better way of creating d?? It's a FAQ: http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list -- Arnaud From hniksic at xemacs.org Tue Mar 25 14:07:55 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Mar 2008 19:07:55 +0100 Subject: Does python hate cathy? References: <64spscF2derd7U3@mid.uni-berlin.de> Message-ID: <87hceuoex0.fsf@mulj.homelinux.net> Marc 'BlackJack' Rintsch writes: > On Tue, 25 Mar 2008 14:58:51 +0000, Edward A. Falk wrote: > >> In article , >> Patrick Mullen wrote: >> >>>Then again, I can count the number of times I have ever needed __del__ >>>with no fingers (never used it!). Still, quite interesting to >>>explore. >> >> I used it once, for an object that had a doubly-linked list. >> The __del__() method walked the list, setting all the elements' >> prev/next pointers to None to make sure the elements of the list would >> get garbage-collected. > > Without the `__del__()` the elements would get garbage collected just > fine. It gets even worse than that: the __del__ method actually *prevents* objects that participate in cycles from getting garbage-collected. Python's GC doesn't deallocate objects that define __del__. (The way to handle those is to grep for them in gc.garbage, break the cycles in a way that works for the application -- e.g. by removing the prev and next references -- and finally del gc.garbage[:].) From spradml at gmail.com Tue Mar 4 00:19:54 2008 From: spradml at gmail.com (Pradnyesh Sawant) Date: Tue, 4 Mar 2008 10:49:54 +0530 Subject: help needed with regex and unicode Message-ID: <20080304051954.GA3992@debian> Hi all, I have a file which contains chinese characters. I just want to find out all the places that these chinese characters occur. The following script doesn't seem to work :( ********************************************************************** class RemCh(object): def __init__(self, fName): self.pattern = re.compile(r'[\u2F00-\u2FDF]+') fp = open(fName, 'r') content = fp.read() s = re.search('[\u2F00-\u2fdf]', content, re.U) if s: print s.group(0) if __name__ == '__main__': rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php') ********************************************************************** the php file content is something like the following: ********************************************************************** // Check if the folder still has subscribed blogs $subCount = function1($param1, $param2); if ($subCount > 0) { $errors['summary'] = '?????????????????????????????????????????'; $errorMessage = '?????????????????????????????????????????'; } if (empty($errors)) { $ret = function2($blog_res, $yuid, $fid); if ($ret >= 0) { $saveFalg = TRUE; } else { error_log("ERROR:: ret: $ret, function1($param1, $param2)"); $errors['summary'] = "????????????????????????????? $errorMessage = "????????????????????????????? } } ********************************************************************** -- warm regards, Pradnyesh Sawant -- Luck is the residue of good design. --Anon -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From mail at timgolden.me.uk Tue Mar 18 09:51:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 18 Mar 2008 13:51:54 +0000 Subject: stdout custom In-Reply-To: <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: <47DFC8FA.1060700@timgolden.me.uk> castironpi at gmail.com wrote: >>> Can I allocate a second console window, so I can place certain output >>> to that directly, and leave the original streams alone? I've rather lost track of what you're trying to do, but I would second Gabriel's suggestion of the standard Windows method of debug output: using OutputDebugString. There's an example here: http://timgolden.me.uk/python/win32_how_do_i/capture-OutputDebugString.html and it shouldn't be too hard to wrap it in a file-like object for stderr-substitution use, say. Obviously there are 1,001 other ways of doing IPC but since this one's ready-made you might as well use it. You can distinguish between different processes' outputs by virtue of the PID which is the first item on the mmap. TJG From bogus@does.not.exist.com Sat Mar 1 17:42:14 2008 From: bogus@does.not.exist.com (From) Date: Sat, 01 Mar 2008 17:42:14 -0500 Subject: Surprised by the command "del" References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: On Sat, 1 Mar 2008 21:05:41 +0100, "K Viltersten" wrote: >I'm reading the docs and at 5.2 the del >statement is discussed. At first, i thought >i've found a typo but as i tried that >myself, it turns it actually does work so. > > a = ["alpha", "beta", "gamma"] > del a[2:2] > a > >Now, i expected the result to be that the >"beta" element has been removed. Obviously, >Python thinks otherwise. Why?! > >Elaboration: >I wonder why such an unintuitive effect has >been implemented. I'm sure it's for a very >good reason not clear to me due to my >ignorance. Alternatively - my expectations >are not so intuitive as i think. :) I think it should say del a[1:2] then it works From carsten at uniqsys.com Wed Mar 12 16:52:43 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 12 Mar 2008 16:52:43 -0400 Subject: string / split method on ASCII code? In-Reply-To: References: Message-ID: <1205355164.9891.39.camel@dot.uniqsys.com> On Wed, 2008-03-12 at 15:29 -0500, Michael Wieher wrote: > Hey all, > > I have these annoying textilfes that are delimited by the ASCII char > for << (only its a single character) and >> (again a single character) > > Their codes are 174 and 175, respectively. > > My datafiles are in the moronic form > > X<>Z Those are decidedly not ASCII codes, since ASCII only goes to 127. The easiest approach is probably to replace those markers with some other characters that occurs nowhere else, for example good old NUL, and then split on that: line = line.replace(chr(174), "\0") line = line.replace(chr(175), "\0") result = line.split("\0") HTH, -- Carsten Haese http://informixdb.sourceforge.net From MadComputerGuy at gmail.com Sun Mar 2 23:15:10 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Sun, 2 Mar 2008 20:15:10 -0800 (PST) Subject: Is it possible to return a variable and use it...? Message-ID: <729c4064-9231-42ee-812b-db987e2026b3@n75g2000hsh.googlegroups.com> Hello all, Is it possible to return a variable and then use it like the following: [code] dir exp_1: while hen != "*" sum = sum + hen return sum dir exp_2: if sum >= total_needed: print "Profit can be made." else: print "Expect a loss." total_needed = int(raw_input("What is the total eggs needed? ")) hen = int(raw_input("How many eggs did each hen lay? Enter them in 1 by 1 or enter * when done. ")) exp_1 exp_2 [/code] If not, then how do I do so? Thanks, Nathan P. From tjreedy at udel.edu Sun Mar 2 01:26:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 01:26:35 -0500 Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: "Kay Schluehr" wrote in message news:eba3804e-4585-4ec7-85d2-a17513719025 at c33g2000hsd.googlegroups.com... | On 1 Mrz., 19:51, Barry Warsaw wrote: | | > Python 2.6 is not only the next advancement in the Python 2 series, it | > is also a transitionary release, helping developers begin to prepare | > their code for Python 3.0. | | Isn't this a silly idea? People have to migrate from 2.5 or lower | releases to Python 2.6 first just to migrate to Python 3.0? You are quite free to update any code you want. Barry just said that 2.6 will help make the process easier. (At least it should for people who prefer incremental changes to doing it all at once.) In any case, 2.5 and earlier code that does not depend on bugs later fixed should usually run unchanged in 2.6 | What are | the inherent / technical reasons that prevent migration directly from | 2.5 to 3.0? None. tjr From steve at REMOVE-THIS-cybersource.com.au Fri Mar 14 07:13:37 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 14 Mar 2008 11:13:37 -0000 Subject: sorting question References: Message-ID: <13tknf14vncbu34@corp.supernews.com> On Thu, 13 Mar 2008 22:37:00 -0500, "Andrew Rekdal" wrote: > Seems 'KEYBOARDS' works nicely in reply to a post from "jcnbp8k" who wrote: > > That's easy solved, the word is keyboards. Hmmm... using my incredible powers of deduction, I predict that the word is "keyboards". -- Steven From michael.wieher at gmail.com Sun Mar 16 20:13:20 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 19:13:20 -0500 Subject: Pycon disappointment In-Reply-To: <11252b13-e3d0-4aa7-9cf5-ee9db7bfc250@u69g2000hse.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> <11252b13-e3d0-4aa7-9cf5-ee9db7bfc250@u69g2000hse.googlegroups.com> Message-ID: well, like, at least he left a free copy of his book on the web, that was kinda decent. 2008/3/16, lbonafide at yahoo.com : > > On Mar 16, 2:43 pm, Robert Hicks wrote: > > On Mar 16, 12:38 pm, lbonaf... at yahoo.com wrote: > > > > > On Mar 16, 6:10 am, Bruce Eckel wrote: > > > > > > I think a lot of people have been caught up in the idea that we need > > > > to commercialize Python, and ride some kind of wave of publicity the > > > > way that Java and C# and Rails seem to have done. > > > > > This coming from someone who caught the Java wave and rode it for a > > > decade. > > > > Doesn't that make him better to see the problems with it? > > Sure, but he dumped C++ (a truly non-commercial language) like a bad > habit for the latest silver bullet ten years ago. Complaints against > Java's commercial nature now ring a bit hollow. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Mar 7 10:46:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 13:46:06 -0200 Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: En Fri, 07 Mar 2008 13:12:13 -0200, nodrogbrown escribi?: > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? join is fine. "\\" is a single character. \ is used as the escape character, and has to be doubled when representing itself. Print an individual element to see the effect: print filenameslist[0] F:/brown/code/python/fgrp1\amber1.jpg (a list uses repr() on its elements instead of str()). > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', If the string is only used to open a file, and never shown to the user, what you prefer is irrelevant, isn't it? What is important here is what Windows prefers, and that's a backslash, although many times / is accepted too. You can convert the file names to their preferred spelling using os.path.normpath Back to your code, try this: from os.path import join, normpath folder = 'F:/brown/code/python/fgrp1' names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] filenameslist = [normpath(join(folder, name)) for name in names] -- Gabriel Genellina From kla at us.de Wed Mar 19 07:17:12 2008 From: kla at us.de (klaus) Date: 19 Mar 2008 11:17:12 GMT Subject: a beginner, beginners question References: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Message-ID: <47e0f638$0$307$e4fe514c@dreader24.news.xs4all.nl> On Wed, 19 Mar 2008 05:57:04 -0500, Tim Chase wrote: >> class example: >> def __init__(self, foo, bar): >> self.foo = foo >> self.bar = bar >> >> def method(self): >> print "method ... :" >> print self.foo >> print self.bar >> >> if __name__ == "__main__": >> obj = example > > This makes "obj" a synonym for "example". You want to instantiate your > "example" class with > > obj = example("Some foo", "Some Bar") > >> obj.foo = "var1" >> obj.bar = "var2" > > which then makes these two lines either unneeded or an overwriting of > the initialization > >> obj.method > > and this returns a function, not the results of the function. You need > to call it > > obj.method() > > -tkc Ok thank you for elaborating I think I've got it. Thnkx. ! From michael.wieher at gmail.com Fri Mar 28 22:03:51 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 28 Mar 2008 21:03:51 -0500 Subject: Help me on function definition In-Reply-To: References: Message-ID: No problem... your def needs a colon.. def function(params): yours lacks it =) thats all On Fri, Mar 28, 2008 at 8:47 PM, aeneng wrote: > Hello everyone, > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this > >>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 > ppp1=u[1]*v[2]-u[2]*v[1] > ppp2=u[2]*v[0]-u[0]*v[2] > ppp3=u[0]*v[1]-u[1]*v[0] > # store the result of the cross product in u > u[0]=ppp1 > u[1]=ppp2 > u[2]=ppp3 > return u #return the cross product of vector u x v. > if __name__=="__main__": > from cvxopt.base import matrix > u=matrix([1.0,0.0,0.0],(3,1)) > v=matrix([0.0,1.0,0.0],(3,1)) > print cross(u,v) > print "file name is %s" %__name__ > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Mar 24 11:37:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Mar 2008 16:37:50 +0100 Subject: Element Tree Help In-Reply-To: <47E7CA87.7090901@behnel.de> References: <47E7CA87.7090901@behnel.de> Message-ID: <47E7CACE.1020508@behnel.de> Stefan Behnel schrieb: > Robert Rawlins wrote: >> Hello Guys,I have little to no experiance with element tree and I'm >> struggling to find a way to parse the details from the XML document >> (attached) into my application. Essentialy I'm looking to take the >> following document and turn it into a dict of tuples, each dict element >> defines a datasource with the key to the element being the 'name' which is >> defined in the XML and then the value of the pair is a tuple which contains >> the details of the datasource, like the host and port etc.I've attached a >> copy of the example XML to this email.Can anyone offer some advice on how >> to get started with this? I've spent a little time looking over the >> documentation of element tree and have struggled to break the ice and parse >> this document.Thanks guys,Robert > > Given this document: > > > > > > a name > localhost > 3306 > database1 > someusername > somepassword > > > another name > localhost > 3306 > database2 > itsusername > andthepassword > > > > I would do something like this: > > d = {} > for event, element in ET.iterparse("thefile.xml"): > if element.tag == "datasource": > d[element.find("name")] = tuple([ el.text for el in element ]) Sorry, the last line should be d[element.findtext("name")] = tuple([ el.text for el in element ]) but you'll likely have to modify that line anyway. Stefan From tjreedy at udel.edu Wed Mar 5 21:05:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Mar 2008 21:05:31 -0500 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13suj3u2d17f205 at corp.supernews.com... |I recall that Python guarantees that module objects are singletons, and | that this must hold for any implementation, not just CPython: you can | only ever create one instance of a module via the import mechanism. But | my google-foo is obviously weak today, I cannot find where the Python | language reference guarantees that. Can somebody please point me at the | link making that guarantee? | | (Note: you can create multiple modules with the same name and state using | new.module. I don't think that counts, although it may be a good way to | win bar bets with your Python buddies.) | | | But what about classes? Are they singletons? Obviously classes aren't | Singleton classes, that is, given an arbitrary class C you can create | multiple instances of C. But what about class objects themselves? I've | found a few odd references to "classes are singletons", but nothing in | the language reference. | | I've done some experimentation, e.g.: | | >>> import module | >>> from module import Class | >>> module.Class is Class | True | | | but I'm not sure if that's (1) meaningful or (2) implementation-specific. If I understand your question, classes are not singletons: >>> ll=[] >>> for i in range(2): import string ll[i]=string >>> ll[0] is ll[1] True >>> for i in range(2): class C: pass ll[i] = C >>> ll[0] is ll[1] False tjr From mnordhoff at mattnordhoff.com Sun Mar 16 03:24:39 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sun, 16 Mar 2008 07:24:39 +0000 Subject: Python Generators In-Reply-To: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: <47DCCB37.2040004@mattnordhoff.com> mpc wrote: > def concatenate(sequences): > for seq in sequences: > for item in seq: > yield item You should check out itertools.chain(). It does this. You call it like "chain(seq1, seq2, ...)" instead of "chain(sequences)" though, which may be a problem for you. The rest of itertools might be interesting too: -- From partofthething at gmail.com Mon Mar 17 23:55:54 2008 From: partofthething at gmail.com (partofthething) Date: Mon, 17 Mar 2008 20:55:54 -0700 (PDT) Subject: Can't get bsddb working on Solaris 8 Message-ID: I've been struggling with this all day. I am trying to get Python 2.5 running with the BerkeleyDB bindings provided by bsddb. First, I downloaded the BerkeleyDB system (version 4.5) from http://www.oracle.com/technology/products/berkeley-db/index.html. Then, I downloaded bsddb from http://pybsddb.sourceforge.net/ and built it using my python 2.5 install with python2.5 setup.py build and python2.5 setup.py install. During the install, the scripts explain that they found the BerkeleyDB system version 4.5 right where I installed it to. I even tried rebuilding all of Python after my BerkeleyDB was set up. My error persists: File "/usr/local/lib/python2.5/bsddb/__init__.py", line 51, in import _bsddb ImportError: No module named _bsddb This is a Solaris 8 machine (SunOS 5.8). I've added the library path (/ usr/local/BerkeleyDB.4.5/lib) to LD_LIBRARY_PATH before building. I'm out of ideas. Any help? Thanks. From xiebopublic at gmail.com Wed Mar 12 23:15:32 2008 From: xiebopublic at gmail.com (Bo) Date: Wed, 12 Mar 2008 20:15:32 -0700 (PDT) Subject: How to port Python code into C++ code automatically? Message-ID: I want to port a Python project (about 10,000 line python code) to C+ +. Is there any automatically tool to do this kind of things? e.g., SWIG(http://www.swig.org/)? Any comment is welcome! Thanks! From mark.manning at gmail.com Mon Mar 10 18:58:03 2008 From: mark.manning at gmail.com (Mark M Manning) Date: Mon, 10 Mar 2008 15:58:03 -0700 (PDT) Subject: Python Sockets Help Message-ID: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> I need your expertise with a sockets question. Let me preface this by saying I don't have much experience with sockets in general so this question may be simple. I am playing with the mini dns server from a script I found online: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt All I want to do is edit this script so that it records the IP address. I've seen other examples use the accept() object which returns the data and the IP address it is receiving the data from. I can't use that in this case but I'm wondering if someone could show me how. Here is the socket part of the script: if __name__ == '__main__': ip='192.168.1.1' print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udps.bind(('',53)) try: while 1: data, addr = udps.recvfrom(1024) p=DNSQuery(data) udps.sendto(p.respuesta(ip), addr) print 'Respuesta: %s -> %s' % (p.dominio, ip) except KeyboardInterrupt: print 'Finalizando' udps.close() Thanks to everyone in advance! ~Mark From castironpi at gmail.com Tue Mar 11 17:56:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 14:56:26 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> Message-ID: <72f2856c-eeca-44f2-849d-912889d26a79@d21g2000prf.googlegroups.com> > > ?Thanks, that makes sense. Are there any local relational databases > > ?available to python that don't require a server backend? > > sqlite > http://www.sqlite.org/ Are there any that aren't persistent? From rmsa50 at yahoo.co.in Thu Mar 20 21:41:32 2008 From: rmsa50 at yahoo.co.in (Gokul) Date: Thu, 20 Mar 2008 18:41:32 -0700 (PDT) Subject: A-Z about Operating systems and other programming languages Message-ID: <2aa5e9bb-ac8a-42c5-ad5a-a6225a8f1f53@u10g2000prn.googlegroups.com> Hai friends. Welcome to Comp.lang.c group. Today I found a website where it gives the entire details about C++ and other IT related tools such as SQL server 2008 updates, IBM tools and techniques and a lot more in the field of Information Technology. http://www.sqlserversoftware.blogspot.com From george.sakkis at gmail.com Wed Mar 19 01:26:40 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 22:26:40 -0700 (PDT) Subject: Get actual call signature? References: <3ef0a8e9-6c86-46a5-be48-63f738f9ec88@s13g2000prd.googlegroups.com> Message-ID: <37b38eb8-624e-4a4b-b0d3-10bc29ba1b93@v3g2000hsc.googlegroups.com> On Mar 18, 4:24 pm, George Sakkis wrote: > On Mar 18, 6:40 am, Jarek Zgoda wrote: > > > > > Say, I have a function defined as: > > > def fun(arg_one, arg_two='x', arg_three=None): > > pass > > > Is there any way to get actual arguments that will be effectively used > > when I call this function in various ways, like: > > > fun(5) => [5, 'x', None] > > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > > fun(5, 'something') => [5, 'something', None] > > > (et caetera, using all possible mixes of positional, keyword and default > > arguments) > > > I'd like to wrap function definition with a decorator that intercepts > > not only passed arguments, but also defaults that will be actually used > > in execution. > > > If this sounds not feasible (or is simply impossible), I'll happily > > throw this idea and look for another one. ;) > > I also needed this for a typecheck module I had written some time ago. > It is feasible, but it's rather hairy. I can dig up the code, polish > it and post it as a recipe (or maybe as a patch to the inspect stdlib > module where it belongs). > > George Posted at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551779. For any correction or improvement, please leave a comment. George From gagsl-py2 at yahoo.com.ar Mon Mar 17 21:16:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 18:16:24 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> Message-ID: <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> On 17 mar, 19:43, castiro... at gmail.com wrote: > Can I allocate a second console window, so I can place certain output > to that directly, and leave the original streams alone? ?I tried some > things in subprocess (Py 3a3 /WinXP) but they failed. ?I don't know if > it's supposed to be possible though, so I didn't press very hard or > keep the code. ?If it is, I can go repro where it went south. ?Is it? Have you tried using the creationflags argument to subprocess.Popen? Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation for CreateProcess at http://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx (Note that a process can be attached at most to one console) If your goal is to output some debug information, try using OutputDebugString + the DebugView utility from www.sysinternals.com -- Gabriel Genellina From pydecker at gmail.com Wed Mar 19 13:10:17 2008 From: pydecker at gmail.com (Peter Decker) Date: Wed, 19 Mar 2008 12:10:17 -0500 Subject: Need Help Starting Out In-Reply-To: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop wrote: > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. > > I want to use it for web building with database access. What do I use > for that? Does it matter what I use on the client side (mootools, or > whatever)? If you are going to be developing web applications, there are many excellent frameworks available, all of which provide database support. If you are looking to develop desktop applications, you should check out Dabo (http://dabodev.com). They integrate data access and GUI controls, making it simple to create database apps. They use wxPython for the UI layer, but hide all of its ugliness, allowing you to program to a clean, consistent API for your GUI. -- # p.d. From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:40:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:40:49 -0300 Subject: Determine size of string in bytes References: Message-ID: En Thu, 27 Mar 2008 16:45:52 -0300, breal escribi?: > Forgive me for this question which is most likely stupid... > > How do I determine the number of bytes a string takes up? I have a > soap server that is returning a serialized string. It seems that when > the string goes over 65978 characters it does not return to the soap > client. Instead I get an error: > error: (35, 'Resource temporarily unavailable') len(x)? Or do you wan to know how many bytes will have an unicode object when encoded in a certain encoding? The only way is to actually encode it and take the length. -- Gabriel Genellina From sturlamolden at yahoo.no Fri Mar 28 13:24:51 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 28 Mar 2008 10:24:51 -0700 (PDT) Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: On 28 Mar, 15:52, s... at pobox.com wrote: > I'm having trouble explaining the benefits and tradeoffs of threads to my > coworkers and countering their misconceptions about Python's threading model > and facilities. ? Python's threading module is modelled on Java's thread model. There are some minor differences, though. Whereas Python has special lock objects, Java can lock (synchronize) on any object. > They all come from C++ and are used to thinking of > multithreading as a way to harness multiple CPU cores for compute-bound > processing. ?I also encountered, "Python doesn't really do threads" today. > *sigh* You can't use threads for that in CPython, due to the GIL (global interpreter lock). The GIL resembles the BKL in earlier versions of the Linux kernel. Due to the GIL, multiple threads cannot be simultaneously in the Python interpreter. This e.g. means that I cannot implement a parallel QuickSort in pure Python and get performance gain from multiple CPUs. Although common misbeliefs, this DOES NOT mean: * Python threads are not useful. * Python programs cannot utilize multiple CPUs or multi-core CPUs. Here is the explanations: The GIL can be released by extension modules, which are native libraries of compiled C, C++ or Fortran. This is the key to the usefulness of Python threads. For example: * Python file and socket objects are extension modules that release the GIL. The GIL is released when a thread is waiting for i/o to complete. This e.g. allows you to write multi-threaded server apps in Python. * NumPy is an extension library that releases the GIL before commencing on a time-consuming CPU-bound computations. If you have N CPUs, NumPy allows you to do N FFTs or SVDs in parallel. * ctypes is an extension module that allows Python code to call DLLs. ctypes releases the GIL before the foregin call on cdecl functions (but not stdcall functions!), allowing you to call many cdecl DLL functions in parallel. * Extension libraries that spawns multiple threads will utilize mutiple CPUs, even if the GIL are not released. There is also other reasons why threads are useful, that does not depend on extension modules releasing the GIL. One example: Multithreading is the key to responsive user interfaces, as only one thread should process events. An event-handler should spawn a thread before commencing on a time-consuming task. IronPython and Jython are implemented without a GIL. (They run on the .NET and Java VMs, respectively.) Finally, remeber that pure Python often runs 200 times slower than pure C on algoritmic code! If you need to do lengthy computational tasks, a pure Python may not be what you want. With two dual-core CPUs, nearly perfect load scheduling, a no-GIL implementation of Python, a pure Python would still be more than 50 times solwer than a single-threaded C solution. Hence, you would gain a lot more from profiling, identifying the worst bottlenecks, and translating those parts to C. From kkadrese at gmail.com Wed Mar 19 10:30:05 2008 From: kkadrese at gmail.com (Andra) Date: Wed, 19 Mar 2008 07:30:05 -0700 (PDT) Subject: lock access to serial port References: <13u2644hpullvd8@corp.supernews.com> Message-ID: I tried ready-made commands for file locking, and turned to that LCK file just in case some permissions are wrong and that's the reason the commands fail. On 19 Marts, 15:43, Grant Edwards wrote: > On 2008-03-18, kkadr... at gmail.com wrote: > > > how to get ttyS0 serial port for exclusive access? I have a python > > script that uses this device with AT commands. I need that two > > instances can call simultaneosuly this python script but only one of > > them gets the device. I tried fcntl.flock, it was just ignored, put > > writtable file LCK..ttyS0 in /var/lock, > > Using a lock file is the traditional method of providing > mutually exclusive access to a serial port. > > > tried ioctl (but I may not know what are appropriate > > arguments), googled half a day for various phrases, error > > messages etc....without success. > > It's unclear what "without success" means. ?Lockfiles have been > used for decades, and they work fine as long as all of the > applications follow the rules. > > -- > Grant From kyosohma at gmail.com Mon Mar 24 14:57:43 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 24 Mar 2008 11:57:43 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <65ebcba0-0283-4003-b667-ff145bc2cd54@u10g2000prn.googlegroups.com> On Mar 24, 1:53 pm, pythonnubie wrote: > Hi Everyone > > I am new to programming in general although I have read alot and > done alot of experimentation as well as researched afew languages > namely java python and visual basic . My conclusion is that python > is one of the best because it eliminates the need to learn about > access modifiers and form handlers so a user can concentrate > primarliy on the nuts and bolts of the language . > > i have come across my first exeption using randrange . The exeption > is " no such attribute " in module random > > platform is xp home and the python build is activestate 2.5 > > All help much appreciated ! Please post the code that throws this error along with the entire traceback. Thanks, Mike From jacob.kaplanmoss at gmail.com Mon Mar 17 19:22:50 2008 From: jacob.kaplanmoss at gmail.com (Jacob Kaplan-Moss) Date: Mon, 17 Mar 2008 16:22:50 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> <83b2ca86-32bb-4bf4-b119-f8d593d4c9eb@p25g2000hsf.googlegroups.com> Message-ID: On Mar 17, 2:52?pm, Dianne Marsh wrote: > I'm bummed about the lightning talks at PyCon from 2008, but I have a > lot of confidence based on what I have read here from Jacob and > others, that things will be different in 2009. They will! This year's lightning talks[*] were disappointing because nobody really thought through how having so many more sponsors changed the dynamic. Now we know, and we'll fix it. Jacob [*] Personally, I thought the Sunday talks -- which featured no sponsors -- were quite good. I think attendance was spotty because it was the last day, and because Saturday's talks were so painful. From KephnosAnagennao at gmail.com Sat Mar 22 16:27:49 2008 From: KephnosAnagennao at gmail.com (sgharvey) Date: Sat, 22 Mar 2008 13:27:49 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order Message-ID: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> ... and by works, I mean works like I expect it to. I'm writing my own cheesy config.ini parser because ConfigParser doesn't preserve case or order of sections, or order of options w/in sections. What's confusing me is this: If I try matching every line to one pattern at a time, all the patterns that are supposed to match, actually match. If I try to match every pattern to one line at a time, only one pattern will match. What am I not understanding about re.search? Doesn't match properly: # Iterate through each pattern for each line for line in lines: for pattern in patterns: # Match each pattern to the current line match = patterns[pattern].search(line) if match: "%s: %s" % (pattern, str(match.groups()) ) _Does_ match properly: # Let's iterate through all the lines for each pattern for pattern in pattern: for line in lines: # Match each pattern to the current line match = patterns[pattern].search(line) if match: "%s: %s" % (pattern, str(match.groups()) ) Related code: The whole src http://pastebin.com/f63298772 regexen and delimiters (imported into whole src) http://pastebin.com/f485ac180 From DustanGroups at gmail.com Sun Mar 23 09:19:22 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 23 Mar 2008 06:19:22 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <7x63vfn3ix.fsf@ruckus.brouhaha.com> Message-ID: <8e4e1ae0-9a34-41c2-b253-7ea8846f6de5@i7g2000prf.googlegroups.com> On Mar 21, 3:57 pm, Paul Rubin wrote: > From at home writes: > > if 'one' and 'two' in f: > > alist.append(f) > > Use: > if 'one' in f and 'two' in f: ... Personally, I would put parentheses around to be clearer: if ('one' in f) and ('two' in f): ... I'm not saying to put parentheses around everything, but in the more ambiguous cases, it certainly helps. From michael at stroeder.com Sat Mar 29 08:25:52 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 29 Mar 2008 13:25:52 +0100 Subject: ANN: python-ldap-2.3.4 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.4 2008-03-29 Changes since 2.3.3: Modules/ * Fixed seg fault when calling LDAPObject.get_option() (see SF#1926507, thanks to Matej) ---------------------------------------------------------------- Released 2.3.3 2008-03-26 Changes since 2.3.2: Fixed backward-compability when building with OpenLDAP 2.3.x libs. From enleverlesX.XmcX at XmclaveauX.com Fri Mar 7 02:40:20 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 7 Mar 2008 08:40:20 +0100 Subject: Internet Explorer 8 beta release In-Reply-To: References: Message-ID: <47d0f485$0$868$ba4acef3@news.orange.fr> Hi! > compliance with the W3C standard Ouarf! Ouarf! which navigator has been compatible with CSS-3, left for several years? And, it's only ONE point... @-salutations Michel Claveau From exxfile at hotmail.com Mon Mar 24 15:03:26 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 12:03:26 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> Message-ID: <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> On Mar 24, 11:57?am, Jeff wrote: > What does the code look like? # Random Access # Demonstrates string indexing # Michael Dawson - 1/27/03 import random word = "index" print "The word is: ", word, "\n" high = len(word) low = -len(word) for i in range(10): position = random.randrange(low, high) print "word[", position, "]\t", word[position] raw_input("\n\nPress the enter key to exit.") The code is an exerp from a chm file . I am petty sutre I am nmot getting a char map error from the copy/paste ! it looks simple enough ! From istvan.albert at gmail.com Thu Mar 27 11:54:58 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 27 Mar 2008 08:54:58 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: <148e049b-f165-4a92-962d-11bc325db5ca@2g2000hsn.googlegroups.com> On Mar 26, 5:28 pm, Sean Davis wrote: > I am working with genomic data. Basically, it consists of many tuples > of (start,end) on a line. I would like to convert these tuples of > (start,end) to a string of bits where a bit is 1 if it is covered by > any of the regions described by the (start,end) tuples and 0 if it is > not. I then want to do set operations on multiple bit strings (AND, > OR, NOT, etc.). Any suggestions on how to (1) set up the bit string > and (2) operate on 1 or more of them? Java has a BitSet class that > keeps this kind of thing pretty clean and high-level, but I haven't > seen anything like it for python. The solution depends on what size of genomes you want to work with. There is a bitvector class that probably could do what you want, there are some issues on scaling as it is pure python. http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html If you want high speed stuff (implemented in C and PyRex) that works for large scale genomic data analysis the bx-python package might do what you need (and even things that you don't yet know that you really want to do) http://bx-python.trac.bx.psu.edu/ but of course this one is a lot more complicated i. From fn681 at ncf.ca Sun Mar 2 11:37:15 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sun, 02 Mar 2008 11:37:15 -0500 Subject: Problem with the strip string method Message-ID: The Library Reference has strip( [chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip() 'spacious' >>> 'www.example.com'.strip('cmowz.') 'example' Only the last two examples below behave as expected. Is it intended that the full range of characters be handled? Colin W. [Dbg]>>> 'ab$%\n\rcd'.strip('%') 'ab$%\n\rcd' [Dbg]>>> 'ab$%cd'.strip('$') 'ab$%\n\rcd' [Dbg]>>> 'ab$%cd'.strip('$') 'ab$%cd' [Dbg]>>> ' ab$%cd '.strip('$') ' ab$%cd ' [Dbg]>>> ' ab$%cd '.strip('%') ' ab$%cd ' [Dbg]>>> ' spacious '.strip() 'spacious' [Dbg]>>> 'www.example.com'.strip('cmowz.') 'example' From pavlovevidence at gmail.com Sat Mar 29 15:49:05 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Mar 2008 12:49:05 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <3e6de9d7-4278-4b1e-9373-78c98fa11a3f@m34g2000hsc.googlegroups.com> On Mar 29, 6:55 am, kwitt... at telenet.be wrote: > why would anyone Questions that begin with the words "why would anyone" are almost always betray an arrogance about their own beliefs and an ignorance (or feigning ignorance) of human nature. Wiser folks know better than to phrase this question so judgmentally. > Please set it straight in 3.0, and if not, convince me with a good > reason of doing so, so that I can live with it and don't have to spend > the rest of my life in 2.x ;). 1. It's not going to change in Python 3.0. 2. It's a silly thing to care so much about that you will avoid using a langauge because of it. Carl Banks From george.sakkis at gmail.com Mon Mar 24 15:09:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Mar 2008 12:09:01 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> On Mar 24, 2:53 pm, pythonnubie wrote: > Hi Everyone > > I am new to programming in general although I have read alot and > done alot of experimentation as well as researched afew languages > namely java python and visual basic . My conclusion is that python > is one of the best because it eliminates the need to learn about > access modifiers and form handlers so a user can concentrate > primarliy on the nuts and bolts of the language . > > i have come across my first exeption using randrange . The exeption > is " no such attribute " in module random > > platform is xp home and the python build is activestate 2.5 Welcome aboard! There's definitely a randrange function in the random module, so something else must be wrong. To get the most out of this list and minimize wasted bandwidth, the most effective way usually consists of copying and pasting: 1. The offending code (or just the relevant part if it's too big). 2. The full traceback of the raised exception. Regards, George From gherron at islandtraining.com Sat Mar 29 15:11:05 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 29 Mar 2008 12:11:05 -0700 Subject: problem with logic in reading a binary file In-Reply-To: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Message-ID: <47EE9449.2080607@islandtraining.com> Bryan.Fodness at gmail.com wrote: > Hello, > > I am having trouble writing the code to read a binary string. I would > like to extract the values for use in a calculation. > > Any help would be great. > Without having looked at your code an any detail, may I humbly suggest that you throw it all out and use the struct module: http://docs.python.org/lib/module-struct.html It is meant to solve this kind of problem, and it is quite easy to use. Gary Herron > Here is my function that takes in a string. > > def parseSequence(data, start): > > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > pos = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > return element, start, value > > else: > return element, start, value > > else: > return element, pos, value > > And, here is a sample string (I have split up and indented for > readability). There is an identifier (\xfe\xff\x00\xe0) followed by > the length of the nested values. > > > '\xfe\xff\x00\xe0\x18\x02\x00\x00 -length=536 > \n0q\x00\x02\x00\x00\x001 > \n0x\x00\x02\x00\x00\x0010 > \n0\x80\x00\x02\x00\x00\x004 > \n0\xa0\x00\x02\x00\x00\x000 > \x0c0\x04\x00\xe8\x01\x00\x00 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 > \n0\x86\x00\x10\x00\x00\x00127.378510918301 > \x0c0\x06\x00\x02\x00\x00\x001 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x001.629998e-1 > \n0\x86\x00\x10\x00\x00\x0023.159729257873 > \x0c0\x06\x00\x02\x00\x00\x004 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.26285318894435 > \n0\x86\x00\x10\x00\x00\x00227.690980638769 > \x0c0\x06\x00\x02\x00\x00\x003 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.52797639111557 > \n0\x86\x00\x10\x00\x00\x00263.433384670643 > \x0c0\x06\x00\x02\x00\x00\x002 ') > > > From python.list at tim.thechases.com Sun Mar 23 21:05:58 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 23 Mar 2008 20:05:58 -0500 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: <47E6FE76.40508@tim.thechases.com> > When I run this script, I got the following exception: > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xb7d8ac6c>> ignored > > To to newcomer like me, this message doesn't make much sense. What > seems weird to me is that, if I change the variable cathy to something > else, like cath, or even cat, then the script will finish gracefully. > Why "cathy" is not liked?!! > > My python is of version 2.5.1, on Ubuntu. When I first read this, I thought you were crazy. I ran the code, and you're not. I tried under versions 2.3, 2.4, and 2.5 on my Debian box, and got the same results. Neither "cathy" nor "ca" works, but "c", "cat", "cath", "cath_y" and "cathy_" all work just fine. Even more infuriating is that if I try and use pdb to debug, Swaroop drops into pdb, but Abdul and Cathy both error out. That's just plain nuts. Something odd is happening with __del__ calls. -tkc From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 09:47:39 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 15:47:39 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <47d003f8$0$8335$426a74cc@news.free.fr> Guillermo a ?crit : > Wow, I think I'm gonna like this forum. Thank you all for the prompt > answers! Welcome onboard !-) >> What makes you say you "need" to know this ? Except for a couple corner >> cases, you usually don't need to care about this. If you told us more >> about the actual problem (instead of asking about what you think is the >> solution), we might be of more help... > > Good point. > > I want to iterate recursively a dictionary whose elements might be > strings or nested tuples or dictionaries and then convert values to a > tagged format according to some rules. If you're absolutely definitively 101% sure that you'll never have anything else in your dict - IOW : this dict is an internal part of your module, produced by the module and consumed by the module -, then it *might* be one of the corner cases where testing type (either directly or - preferably - via isinstance) is the right thing to do. > d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y': > ('a','b','c')}} > > I'm just designing the algorithm, but I think Python dictionaries can > hold any kind of sequence? Any Python object (which include classes, modules, functions etc) can be used as value. From __peter__ at web.de Mon Mar 24 15:15:16 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Mar 2008 20:15:16 +0100 Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> Message-ID: pythonnubie wrote: > On Mar 24, 11:57?am, Jeff wrote: >> What does the code look like? > > # Random Access > # Demonstrates string indexing > # Michael Dawson - 1/27/03 > > import random > > word = "index" > print "The word is: ", word, "\n" > > high = len(word) > low = -len(word) > for i in range(10): > position = random.randrange(low, high) > print "word[", position, "]\t", word[position] > > raw_input("\n\nPress the enter key to exit.") > > The code is an exerp from a chm file . I am petty sutre I am > nmot getting a char map error from the copy/paste ! it looks > simple enough ! You have probably called your script random.py, and now it imports itself instead of the random.py module in Python's standard library. Rename your script to myrandom.py, remove the compiled version random.pyc in the same folder, and you should be able to run it successfully. Peter From josef.pktd at gmail.com Sun Mar 16 09:23:21 2008 From: josef.pktd at gmail.com (joep) Date: Sun, 16 Mar 2008 06:23:21 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> Message-ID: <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> Tim Golden wrote: > subprocess.call ([ > > r"C:\Program Files\Adobe\Acrobat 5.0\Reader\acro reader.exe", > > r"C:\Program Files\Adobe\Acr > obat 5.0\Reader\plug_ins.donotuse\Annotations\Stamps\abc def.pdf" > > ]) > > Can you confirm that something equivalent *doesn't* work on your > setup? Or have I misunderstood your point earlier? I'd really > like to get to the point where we can definitively state: this > works (and possibly: that doesn't). > > Thanks > TJG This works without problems for me on Windows XP, Python 2.4.3 In the past, I didn't have problems with subprocess.call, and I never had to look closer to the different versions of quoting. I often had problems understanding subprocess.Popen and getting it to work. For example the equivalent case for popen, as your subprocess.call example, does not work, or I'm making a different mistake with subprocess.Popen: p = subprocess.Popen([ r"C:\Program Files\WinRAR\Rar.exe", r"C:\temp\Copy of papers.rar"], shell=True, stdout=subprocess.PIPE) rettext,reterror = p.communicate() retcode = p.wait() p.stdout.close() results in: 'C:\Program' is not recognized as an internal or external command, operable program or batch file. I assume that there is some difference how subprocess.call and subprocess.Popen handle and format the command. subprocess.Popen does the correct formatting when only one file path has spaces and requires double quoting, but not if there are two file paths with spaces in it. Josef From knut.urbye at gmail.com Thu Mar 27 11:12:55 2008 From: knut.urbye at gmail.com (Knut) Date: Thu, 27 Mar 2008 08:12:55 -0700 (PDT) Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: <6347ae92-a8c9-40db-a822-6a4bfcf3e8cb@i7g2000prf.googlegroups.com> This is frustrating. I was working on writing a sample for my problem. I start with dissecting my code which still gives the same error. Then I start thinking that it might be my setup file doing the damage. And i start it from scratch. Everything suddenly works. Fine! i think, i will have to start over with the setup file. Buy i give the old setup a last go, and guess what. It works. So I am honestly utterly frustrated.. I have no idea what what the reason for the problem, but apparently it is solved, for now. Thanks for all you comments and help. I really appreciate it! K From gagsl-py2 at yahoo.com.ar Sun Mar 2 03:48:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 06:48:11 -0200 Subject: Telnet versus telnetlib References: <8acce230-4acf-43fe-9cb7-e4e50350381e@s13g2000prd.googlegroups.com> <13ska3aju6cse5b@corp.supernews.com> Message-ID: En Sun, 02 Mar 2008 02:09:14 -0200, Grant Edwards escribi?: > On 2008-03-01, Gabriel Genellina wrote: >> En Fri, 29 Feb 2008 20:34:41 -0200, Sean Davis >> escribi?: >> >>> When I do an analogous process using telnetlib, I get no debug output, >>> and most importantly, when I send the XML file to the host, I get no >>> printed page. Unfortunately, I do not have access to the host to do >>> troubleshooting there, so I have to "feel" my way around. Any >>> suggestions on what might be going wrong? >>> >>> In [12]: tn.write(""" >>> ....: > >> \ is the quote character. You have to duplicate it "C:\\labels..." or >> use >> a raw string r""" > Or use a forward slash: > > "C:/labels/anzick_primary_sample.lbl" I didn't menction that alternative because it generates a different string; the resulting xml document may or may not be equivalent. -- Gabriel Genellina From deets at nospam.web.de Sun Mar 9 15:31:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 20:31:25 +0100 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: <63ilglF28106hU1@mid.uni-berlin.de> Message-ID: <63is8gF27pndgU1@mid.uni-berlin.de> Jeff Schiller schrieb: > I said "PythonQt" not PyQt. That's an important distinction, I think :) > > See http://pythonqt.sourceforge.net/ It sure is. Sorry, didn't realize the difference. Diez From castironpi at gmail.com Thu Mar 6 13:32:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 10:32:42 -0800 (PST) Subject: Identifying messages in a thread (was: Please keep the full address) References: <8763w094sy.fsf_-_@benfinney.id.au> <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> Message-ID: <5b712074-8cce-426f-a103-dab6a4b9a8ad@y77g2000hsy.googlegroups.com> On Mar 6, 10:47?am, "D'Arcy J.M. Cain" wrote: > On Thu, 6 Mar 2008 07:58:06 -0800 (PST) > > Carl Banks wrote: > > > I don't want to have to tag every thread. ?I just want to *plonk* > > > certain posters. > > > > Anyway, I'll live with Google's failings I guess. > > > Sounds like you need better filtering. > > > A decent news filter should be able not only kill a poster, but also > > all followups to that poster recursively. > > Actually, I am reading this as a mailing list and since I run Unix and > procmail I am sure that I could set something up if it really starts to > be annoying. ?So far the simple filters deal with all but a smattering > of problem postings so I don't need to expend the time. The Google Groups reader doesn't always let you see new replies to really old messages, something they should change (this means you). But there is an 'active old threads', but it doesn't catch every one. I want to read those plonk. From deets at nospam.web.de Fri Mar 7 09:50:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 07 Mar 2008 15:50:58 +0100 Subject: hidden built-in module In-Reply-To: <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> Message-ID: <63d32jF23f54eU1@mid.uni-berlin.de> koara schrieb: > On Mar 5, 1:39 pm, gigs wrote: >> koara wrote: >>> Hello, is there a way to access a module that is hidden because >>> another module (of the same name) is found first? >>> More specifically, i have my own logging.py module, and inside this >>> module, depending on how initialization goes, i may want to do 'from >>> logging import *' from the built-in logging. >>> I hope my description was clear, cheers. >>> I am using python2.4. >> you can add your own logging module in extra directory that have __init__.py and >> import it like: from extradirectory.logging import * >> >> and builtin: from logging import * > > > Thank you for your reply gigs. However, the point of this namespace > harakiri is that existing code which uses 'import logging' ... > 'logging.info()'... etc. continues working without any change. > Renaming my logging.py file is not an option -- if it were, i wouldn't > bother naming my module same as a built-in :-) You can only try and search the sys-path for the logging-module, using sys.prefix and then look for logging.py. Using __import__(path) you get a reference to that module. Diez From deets at nospam.web.de Tue Mar 25 12:08:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Mar 2008 17:08:08 +0100 Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <29bc6ff2-f172-4776-87b7-884585277570@d21g2000prf.googlegroups.com> <4b864142-5323-46f6-aac5-d39ea7ad64ec@s19g2000prg.googlegroups.com> Message-ID: <64smbvF2de27aU1@mid.uni-berlin.de> Anthony wrote: > On Mar 25, 2:31 pm, Tzury Bar Yochay wrote: >> I wish it was that simple but 'a = Foo().getid()' is actually creating >> a new instance of Foo whereas I want the data of the Foo instanced by >> __init__ of FooSon(). > > I don't think Foo.__init__(self) creates an instance of the Foo > class. If you want FooSon to create an instance of Foo, try: You wrote: a = Foo().getid() Which indeed creates a *new* Foo-instance. So it's of no use to the OP. Of course Foo.(self) calls that method without creating a new instance, which is the behavior one uses when invoking the constructor of Foo inside FooSon.__init__. But that doesn't make your example any better. Diez From grante at visi.com Sat Mar 1 23:12:19 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 04:12:19 -0000 Subject: invert or not ? References: Message-ID: <13ska93iif10eab@corp.supernews.com> On 2008-03-01, Stef Mientki wrote: > from the manual I read that a bitwise inversion should be done > by invert. But from some experiments I see that not works > equally well. What experiments are those? >>> print ~0xaa, not 0xaa -171 False >>> print ~0x55, not 0x55 -86 False >>> >>> print ~True, not True -2 False >>> > Is this coincidence ? Is what coincidence? > (The disadvantage of invert is that I've to import operators) No you don't. -- Grant Edwards grante Yow! If elected, Zippy at pledges to each and every visi.com American a 55-year-old houseboy... From aaron.watters at gmail.com Thu Mar 27 16:37:33 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Thu, 27 Mar 2008 13:37:33 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: > "this";"is";"a";"test" > > Resulting in an output of: > > ['this', 'is', 'a', 'test'] > > However, if I modify the csv to: > > "t"h"is";"is";"a";"test" > > The output changes to: > > ['th"is"', 'is', 'a', 'test'] I'd be tempted to say that this is a bug, except that I think the definition of "csv" is informal, so the "bug/feature" distinction cannot be exactly defined, unless I'm mistaken. What I would do is write roll my own parser using very simple python and check that it works for the examples of interest. If, for example, you can assume that the delimiter will never occur inside the payload and the payload contains no "quoted" characters you could do something like: ==== cut def trimQuotes(txt): txt = txt.strip() if txt: start = txt[0] end = txt[-1] if start==end and start in ('"', "'"): return txt[1:-1] return txt def simpleCsv(lines, delimiter): for line in lines: fields = line.split(delimiter) fields = map(trimQuotes, fields) yield fields def test(): lines = ['"t"h"is";"is";"a";"test"'] for fields in simpleCsv(lines, ';'): print fields if __name__=="__main__": test() === cut If you want fame and admiration you could fix the arguably bug in the csv module and send the patch to the python bugs mailing list. However, I just had a perusal of csv.py.... good luck :). -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=too+general From watine at cines.fr Fri Mar 14 07:37:50 2008 From: watine at cines.fr (Benjamin Watine) Date: Fri, 14 Mar 2008 12:37:50 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: <47DA638E.7030800@cines.fr> Bryan Olson a ?crit : > I wrote: >> [...] Pipe loops are tricky business. >> >> Popular solutions are to make either the input or output stream >> a disk file, or to create another thread (or process) to be an >> active reader or writer. > > Or asynchronous I/O. On Unix-like systems, you can select() on > the underlying file descriptors. (MS-Windows async mechanisms are > not as well exposed by the Python standard library.) > Hi Bryan Thank you so much for your advice. You're right, I just made a test with a 10 MB input stream, and it hangs exactly like you said (on cat.stdin.write(myStdin))... I don't want to use disk files. In reality, this script was previously done in bash using disk files, but I had problems with that solution (the files wasn't always cleared, and sometimes, I've found a part of previous input at the end of the next input.) That's why I want to use python, just to not use disk files. Could you give me more information / examples about the two solutions you've proposed (thread or asynchronous I/O) ? Thank you ! Ben From gandalf at shopzeus.com Fri Mar 21 07:38:49 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 21 Mar 2008 12:38:49 +0100 Subject: eval and unicode In-Reply-To: <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E39E49.6020107@shopzeus.com> > > Your problem is, I think, that you think the magic of decoding source > code from the byte sequence into unicode happens in exec or eval. It > doesn't. It happens in between reading the file and passing the > contents of the file to exec or eval. > I think you are wrong here. Decoding source happens inside eval. Here is the proof: s = 'u"' + '\xdb' + '"' print eval(s) == eval( "# -*- coding: iso8859-2\n" + s) # prints False, indicating that the decoding of the string expression happened inside eval! It can also be prooven that eval does not use 'ascii' codec for default decoding: '\xdb'.decode('ascii') # This will raise an UnicodeDecodeError eval() somehow decoded the passed expression. No question. It did not use 'ascii', nor 'latin2' but something else. Why is that? Why there is a particular encoding hard coded into eval? Which is that encoding? (I could not decide which one, since '\xdb' will be the same in latin1, latin3, latin4 and probably many others.) I suspected that eval is going to use the same encoding that the python source file/console had at the point of execution, but this is not true: the following program prints u'\xdb' instead of u'\u0170': # -*- coding iso8859-2 -*- s = '\xdb' expr = 'u"' + s +'"' print repr(eval(expr)) Regards, Laszlo From ptmcg at austin.rr.com Mon Mar 24 19:55:41 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 16:55:41 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: Message-ID: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> On Mar 24, 6:32?pm, Tess wrote: > Hello All, > > I have a Beautiful Soup question and I'd appreciate any guidance the > forum can provide. > I *know* you're using Beautiful Soup, and I *know* that BS is the de facto HTML parser/processor library. Buuuuuut, I just couldn't help myself in trying a pyparsing scanning approach to your problem. See the program below for a pyparsing treatment of your question. -- Paul """ My goal is to extract all elements where the following is true:

and

. """ from pyparsing import makeHTMLTags, withAttribute, keepOriginalText, SkipTo p,pEnd = makeHTMLTags("P") p.setParseAction( withAttribute(align="left") ) div,divEnd = makeHTMLTags("DIV") div.setParseAction( withAttribute(align="center") ) # basic scanner for matching either

or

with desired attrib value patt = ( p + SkipTo(pEnd) + pEnd ) | ( div + SkipTo(divEnd) + divEnd ) patt.setParseAction( keepOriginalText ) print "\nBasic scanning" for match in patt.searchString(html): print match[0] # simplified data access, by adding some results names patt = ( p + SkipTo(pEnd)("body") + pEnd )("P") | \ ( div + SkipTo(divEnd)("body") + divEnd )("DIV") patt.setParseAction( keepOriginalText ) print "\nSimplified field access using results names" for match in patt.searchString(html): if match.P: print "P -", match.body if match.DIV: print "DIV -", match.body Prints: Basic scanning

P1

div2a
div2b

P3

div3b

P4

div4b
Simplified field access using results names P - P1 DIV - div2a DIV - div2b P - P3 DIV - div3b P - P4 DIV - div4b From martin.laloux at gmail.com Fri Mar 14 05:29:56 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Fri, 14 Mar 2008 02:29:56 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> <13tk779m3nfs1bb@corp.supernews.com> Message-ID: <6be1cc04-6739-485a-808e-b2fb0faa0887@i7g2000prf.googlegroups.com> use the glob module import os, glob dor = the path you want for dir, subdir, files in os.walk(dor): for file in files: if glob.fnmatch.fnmatch(file,"*.txt"): do what you want From saeed008 at umn.edu Fri Mar 7 17:25:51 2008 From: saeed008 at umn.edu (Maryam Saeedi) Date: Fri, 7 Mar 2008 16:25:51 -0600 Subject: os.chdir Message-ID: I have a problem using os.chdir on linux. What should I do if I want to change to root directory? The below does not work: os.chdir("~/dir1") Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvschorre at sbcglobal.net Wed Mar 19 15:41:17 2008 From: dvschorre at sbcglobal.net (dvschorre at sbcglobal.net) Date: Wed, 19 Mar 2008 12:41:17 -0700 (PDT) Subject: Calling Mac programs from Python instead of from AppleScript Message-ID: When I'm running Script Editor, I can get Maya to draw a sphere by typing: tell application "Maya" execute "sphere" end tell When I try this using Python, I get this error message: IDLE 1.2.2 >>> app('Maya').execute('sphere') Traceback (most recent call last): File "", line 1, in app('Maya').execute('sphere') NameError: name 'app' is not defined >>> Maybe I need to load some libraries first. Please help me to get started. Thanks Dewey V. Schorre From tms at zeetix.com Sat Mar 15 13:53:52 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 13:53:52 -0400 Subject: No subject Message-ID: <003e01c886c5$8837b290$0200a8c0@TMSMAIN> > Somehow I don't get what you are after. The ' doesn't have to be escaped > at all if " are used to delimit the string. If ' are used as delimiters > then \' is a correct escaping. What is the problem with that!? If I delimit the string with double quote, then I have to escape every double quote in whatever I serialize. I'm moving strict html from the server to the browser, and therefore the value of every tag attribute is delimited by double quotes. That means that I'd have to escape every double quote, and there are MANY more of them. From fuzzyman at gmail.com Mon Mar 10 11:13:23 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Mon, 10 Mar 2008 08:13:23 -0700 (PDT) Subject: Python-URL! - weekly Python news and links (Feb 18) References: Message-ID: On Mar 10, 2:33 pm, Piet van Oostrum wrote: > >>>>> Peter Otten <__pete... at web.de> (PO) wrote: > >PO> Piet van Oostrum wrote: > >>>>>>>> "Gabriel Genellina" (GG) wrote: > > >GG> "Given this indispensable process and architecture issue, isn't it > >>>> obvious GG> that it's totally irrelevant to the system's overall safety > >>>> whether the GG> compiler has performed the further smattering of > >>>> semantically puny GG> 'verifications' allowed by mandatory-declaration, > >>>> stating-typing GG> languages?" - Alex Martelli > I've just been at a student conference in Krakow (SFI) where I heard a talk by Gilad Bracha on the problems with Java (and he is in a position to know!). I will write it up in a blog entry, but my two favourite quotes from his talk are: 1. The programs that can be written in languages with static type systems are a subset of all possible programs. For some people this is enough. 2. Mandatory static typing is an inherent security risk. He has a very interesting tale about Java to demonstrate the second point... Michael http://www.manning.com/foord > >>> I couldn't find the original of this. I would like to see it in its > >>> context. Googling didn't reveal anything but this Python-URL. > >PO> My google is better than yours then: > >PO>http://mail.python.org/pipermail/python-list/2003-March/193864.html > > Thanks. I probably have searched for "mandatory-declaration, static-typing > languages" instead of "mandatory-declaration, stating-typing languages" > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From carsten at uniqsys.com Sun Mar 23 20:05:36 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 01:05:36 +0100 Subject: always getting 'None' return value from PyObject_CallObject In-Reply-To: References: Message-ID: <1206317136.3365.6.camel@localhost.localdomain> On Sun, 2008-03-23 at 23:43 +0000, Gal Aviel wrote: > [...] > When calling a function defined in my module, the function executes Ok How do you know that? > - it sees > the correct arguments being passed from C How do you know that? > , and executes 100% How do you know that? > - only the return > value is always 'None' How are you reaching this conclusion? > (I tried returning a simple integer like '5' which > doesn't work). What does "doesn't work" mean? -- Carsten Haese http://informixdb.sourceforge.net From samuel.progin at gmail.com Mon Mar 10 17:29:36 2008 From: samuel.progin at gmail.com (Sam) Date: Mon, 10 Mar 2008 14:29:36 -0700 (PDT) Subject: execute python script question References: Message-ID: <9e299ffa-2fab-4dcc-907c-8aa667bde3d4@n58g2000hsf.googlegroups.com> Hello, I may misunderstand your problem, but it may be related to the execution environment, especially the PYTHONPATH variable. Have a look at the following log: samuel at Bioman2:/$ pwd / samuel at Bioman2:/$ cat -n /tmp/test_import.py 1 class A(object): 2 def __init__(self): 3 self.value = 1 4 def show(self): 5 print self.value samuel at Bioman2:/$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from test_import import A Traceback (most recent call last): File "", line 1, in ImportError: No module named test_import >>> exit() samuel at Bioman2:/$ export PYTHONPATH=/tmp samuel at Bioman2:/$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from test_import import A >>> a=A() >>> a.show() 1 >>> ++ Sam From castironpi at gmail.com Sun Mar 16 05:58:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 02:58:57 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: <87od9f3vrt.fsf@physik.rwth-aachen.de> Message-ID: <79e48717-37cb-4d60-a76b-4fafdb79153a@2g2000hsn.googlegroups.com> On Mar 16, 3:42?am, Torsten Bronger wrote: > Hall?chen! > > castiro... at gmail.com writes: > > [...] > > *** English is SVO, subject-verb-object. ?French is too, unless the > > object is direct: subject- direct-object -verb. > > Really? ?I thought this is only the case for pronouns. Yes, yes, I remembered that later on tonight. A complete misformulation... sigh. Subject objective-pronoun verb objective- noun(-phrase). What factors in to L'Academie Francaise's decisions? From greg at cosc.canterbury.ac.nz Fri Mar 28 19:59:22 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 29 Mar 2008 11:59:22 +1200 Subject: Can my own objects support tuple unpacking? In-Reply-To: <13um6p08v0ea9f3@corp.supernews.com> References: <13um6p08v0ea9f3@corp.supernews.com> Message-ID: <655fdfF2e9gooU1@mid.individual.net> Scott David Daniels wrote: > class Foo(object): # _Never_ use old-style without a reason > def __getitem__(self, index): > print index > if index < 3: > return index * 5 # just to see > raise IndexError('Zapped') # The secret -- run out. Another way is to make your object iterable -- read up about the "iterator protocol". -- Greg From here at softcom.net Wed Mar 26 17:42:31 2008 From: here at softcom.net (Sal) Date: Wed, 26 Mar 2008 14:42:31 -0700 (PDT) Subject: Newbie: unsigned shift right Message-ID: <276efacc-dad3-4844-a3b4-a6845c71473b@h11g2000prf.googlegroups.com> Is there any way to do an unsigned shift right in Python? When I enter (-1>>1) the answer is -1. What I'm looking for is the equivalent of an unsigned shift in C or the ">>>" operator in Java. From pavloutefkros at gmail.com Sun Mar 9 17:33:01 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 9 Mar 2008 14:33:01 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: ok i found a workaround. From mal at egenix.com Tue Mar 4 05:41:16 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 04 Mar 2008 11:41:16 +0100 Subject: tools to install not in python tree? In-Reply-To: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> References: <9de283d7-bd56-4951-82f0-43ddc7a5819b@34g2000hsz.googlegroups.com> Message-ID: <47CD274C.7080207@egenix.com> On 2008-03-04 02:55, commander_coder at hotmail.com wrote: > Hello, > > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ and some programs that I want in ~/public_html/ . I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). But as I understand it setup only targets > installing below sys.prefix; is that right? The distutils "install" command provides a lot of what you're looking for, in particular, it makes it easy to install the various parts of a package in different directories: $ python2.5 setup.py install --help Common commands: (see '--help-commands' for more) setup.py build will build the package underneath 'build/' setup.py install will install the package Global options: --verbose (-v) run verbosely (default) --quiet (-q) run quietly (turns verbosity off) --dry-run (-n) don't actually do anything --help (-h) show detailed help message --set-version override the package version number Options for 'mx_install' command: --prefix installation prefix --exec-prefix (Unix only) prefix for platform-specific files --home (Unix only) home directory to install under --install-base base installation directory (instead of --prefix or -- home) --install-platbase base installation directory for platform-specific files (instead of --exec-prefix or --home) --root install everything relative to this alternate root directory --install-purelib installation directory for pure Python module distributions --install-platlib installation directory for non-pure module distributions --install-lib installation directory for all module distributions (overrides --install-purelib and --install-platlib) --install-headers installation directory for C/C++ headers --install-scripts installation directory for Python scripts --install-data installation directory for data files --compile (-c) compile .py to .pyc [default] --no-compile don't compile .py files --optimize (-O) also compile with optimization: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0] --force (-f) force installation (overwrite any existing files) --skip-build skip rebuilding everything (for testing/debugging) --record filename in which to record list of installed files usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help > I can write routines for myself but other people must need to do these > things also and a tested solution is obviously better. Is there such > a tool? Things that the stock distutils cannot do out of the box can easily be added by subclassing commands or adding new ones in your setup.py. For some examples how this can be done, have a look at e.g. the mxSetup.py module we ship with the eGenix mx Base Distribution: http://www.egenix.com/products/python/mxBase/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 04 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From python at rcn.com Sat Mar 8 14:15:12 2008 From: python at rcn.com (Raymond Hettinger) Date: Sat, 8 Mar 2008 11:15:12 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> Message-ID: <54abf8a6-6156-4663-903c-eb761e6b5148@h11g2000prf.googlegroups.com> > > > Is it possible to get an object out of a set() given another object > > > that has the same hash code and equality (__hash__() and __eq__() > > > return the same)? > > > Yes, but it requires an indirect approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299 > > > Raymond > > That's a clever work around. ?Thanks, Raymond. ?Clearly you had a need > for this. ?Do you feel it's a common need that should be submitted as > a Python feature request? ?To me it seems like such a simple thing > that would increase the general utility of the set class. ?I suppose I > could start another thread like "feature request: New method for set - > get_equivalent". Glad you liked the recipe. :-) FWIW, it is not specific to sets. The recipe works with any container including dictionaries and lists. The approach is easily extended to any situation with equality testing. For example, it can be used with list.remove(x) to find the identity of the removed object. Long ago, I rejected adding get_equivalent() to the set API. The existing API has a near zero learning curve and it would be nice to keep it that way. For most use cases, the obvious, explicit approach is better. Just make a dictionary where the value is the canonical representative of the equivalence class: >>> d = {1:1, 2:2, 3:3} >>> d[2.0] 2 The intern() builtin uses this approach: interned = {} def intern(s): if s in interned: return interned[s] interned[s] = s return s Raymond From castironpi at gmail.com Thu Mar 6 00:57:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 21:57:37 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> <87hcfk30lo.fsf@micah.cowan.name> Message-ID: <4710658c-1d2f-44b2-a9ed-badd9f7391ae@m36g2000hse.googlegroups.com> > > *plonk* > > > key is an iterable, just like the constructors to > > other collection. > > Um... "*plonk*" is the (imaginary) sound made by dropping someone into > your plonkfile (killfile, scorefile, whatever): the action of setting > your newsreader to ignore someone you perceive to be a troll. > > I have extreme doubts that you have actually done this to _yourself_. Your doubts are extreme! From pavloutefkros at gmail.com Sun Mar 2 09:38:50 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 06:38:50 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: you could at least check before posting. as i said i've tried like 1000 ways of doing that, and im so desparate that i'm thinking of quiting python. This damn thing just doesnt work. when i do as you post the server never even replies, as it tends to accept connections all the time. anyone has a better idea? From bearophileHUGS at lycos.com Tue Mar 25 19:38:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 25 Mar 2008 16:38:39 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: <39f5237e-fed7-4f66-9291-08099e213f25@e6g2000prf.googlegroups.com> Kelly Greer: > What is the best way to filter a Python list to its unique members? If Python is "batteries included", then an industrial-strength unique() seems one of the most requested 'batteries' that's not included :-) I feel that it's coming in Python 2.6/3.x. In the meantime: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502263 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438599 Bye, bearophile From castironpi at gmail.com Tue Mar 4 13:26:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:26:33 -0800 (PST) Subject: is there enough information? References: <13spkb9eirsq26d@corp.supernews.com> Message-ID: <30b6d419-5965-46b5-bc3d-ea9ff6b35736@h11g2000prf.googlegroups.com> On Mar 3, 10:34?pm, Dennis Lee Bieber wrote: > On Mon, 3 Mar 2008 07:00:55 -0800 (PST), castiro... at gmail.com declaimed > the following in comp.lang.python: > > > What's the API call for it? > > ? ? ? ? I'd suspect one of the win32event.WaitFor..., when combined with > win32file.CreateFile(), win32file.ReadFile() with the Overlapped flag > set, win32file.WriteFile() with Overlapped flag set... > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ select maps to two different calls on Windows. From james.pye at gmail.com Tue Mar 4 10:18:32 2008 From: james.pye at gmail.com (james.pye at gmail.com) Date: Tue, 4 Mar 2008 07:18:32 -0800 (PST) Subject: tab completion? References: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> Message-ID: <909d5c24-ae7f-4abd-b671-ee4d384f70a0@s12g2000prg.googlegroups.com> On Mar 4, 8:13?am, Siddhant wrote: > Hi people. > I was just wondering if a tab-completion feature in python command > line interface would be helpful? > If yes, then how can I implement it? > Thanks, > Siddhant Is this what you are looking for? http://docs.python.org/lib/module-rlcompleter.html From darcy at druid.net Sun Mar 23 11:52:30 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 23 Mar 2008 11:52:30 -0400 Subject: Testing for an empty dictionary in Python In-Reply-To: <47e67a99$0$36364$742ec2ed@news.sonic.net> References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <20080323115230.0f45091b.darcy@druid.net> On Sun, 23 Mar 2008 08:53:02 -0700 John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). Try this: if dict: It should be faster as it only checks whether or not there are any members and does not run keys() or len() on the dictionary. Of course, you should test 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 andrei.avk at gmail.com Wed Mar 12 20:07:48 2008 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Wed, 12 Mar 2008 17:07:48 -0700 (PDT) Subject: Open a file with default handler app? References: <83bc9bf2-9b9c-4959-870f-f4b37281f6e0@m3g2000hsc.googlegroups.com> <79ae8d93-5845-466c-b7f8-e345c3d63c46@i7g2000prf.googlegroups.com> Message-ID: <231ef3b4-c595-4826-bb5f-affafdc561fd@u69g2000hse.googlegroups.com> On Mar 11, 11:50?pm, Wubbul... at gmail.com wrote: > > Hey there, > I've had to do the same things for a program that I'm writing. The > following command should do the trick: > > os.startfile("yourfilehere") > > from the os module. Hope this helps! That's perfect, thanks a ton++! From lunasf at gmail.com Thu Mar 20 08:29:02 2008 From: lunasf at gmail.com (igbt) Date: Thu, 20 Mar 2008 05:29:02 -0700 (PDT) Subject: A question about a metacharacter References: <09156537-3eb3-4cff-b1f6-3727ca660f6f@p73g2000hsd.googlegroups.com> Message-ID: <9f4e60ad-91f3-424d-afe5-067ee425695a@p73g2000hsd.googlegroups.com> On 20 mar, 12:38, Chris wrote: > On Mar 20, 1:19 pm, igbt wrote: > > > > > I am creating a simple script which is using gtk. In this script you > > must enter a text, if you do not enter anything or you enter a dot, > > the script will be finished. However, if you don't enter anything the > > script works but if you enter a dot (.) the script does not work. I > > was investigating about it and I think the problem is with the dot > > character sss == "." . I was trying the same line with other > > metacharacters like *, (, ) ... and I found the same problem. I was > > looking for an example where I could see the way I could do it without > > any error but I did not find it. Could somebody tell me how can I > > solve this error? > > > sss = entryName.get_text() # The script gets the text > > if sss == "" or sss == ".": > > gtk.main_quit() #The script finishes > > > Thanks ; -) > > try this. > > sss = entryName.get_text() > if not sss.strip() or sss.strip() == '.': > gtk.main_quit() > > I wouldn't be suprised if your input is being captured with End-Of- > Line characters which would cause the mis-match. It does not work. Thanks for your help From xelapond at gmail.com Mon Mar 31 21:40:14 2008 From: xelapond at gmail.com (Alex Teiche) Date: Mon, 31 Mar 2008 18:40:14 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> Message-ID: <1a8a5b03-0b9e-49de-bd87-43fa1aa99dc2@b5g2000pri.googlegroups.com> On Mar 31, 11:49 am, Alex Teiche wrote: > On Mar 30, 3:50 pm, Benjamin wrote: > > > > > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > implement the following thing into my python application: > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > it, but I could not get this specific thing to work. Can someone give > > > me some hints as to get it working in Python? > > > What problems are you having? > > > > Thanks a ton, > > > > Alex > > Thanks everyone for your help. I found the example to be particularly > helpful, and I have made a simplified version just to display an icon > with a quit button in its menu. Once I know how to do that I will > incorporate it into my larger program, with more options and the > ability show messages. The problem is, it doesn't work, and I can't > find out what's wrong. Can you give me some hints? > > Here is the code: > import sys > from PyQt4 import QtGui, QtCore > > class trayIcon(QtGui.QWidget): > def __init__(self, parent=None): > QtGui.QWidget.__init__(self, parent) > > #********Create Actions for the Tray Menu********# > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > QtCore.QObject.connect(self.quitAction, > QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) > > create_tray_icon() > > self.composeAction.setEnabled(visible) > QtGui.QWidget.setVisible(self, visible) > > self.trayIcon.show() > > def create_tray_icon(self): > self.trayIconMenu = QtGui.QMenu(self) > self.trayIconMenu.addAction(self.composeAction) > self.trayIcon = QtGui.QSystemTrayIcon(self) > self.trayIcon.setContextMenu(self.trayIconMenu) > self.trayIcon.setIcon(bad.svg) > > app = QtGui.QApplication(sys.argv) > sys.exit(app.exec_()) OK, I messed around with it some more, and it works. I just don't know how to set an icon, and the example doesn't help at all. Here is the code: import sys from PyQt4 import QtCore, QtGui class Systray(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.createActions() self.createTrayIcon() #QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL("messageClicked()"), self.messageClicked) #QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.iconActivated) self.trayIcon.show() def createActions(self): #self.minimizeAction = QtGui.QAction(self.tr("Mi&nimize"), self) #QtCore.QObject.connect(self.minimizeAction, # QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("hide()")) #self.maximizeAction = QtGui.QAction(self.tr("Ma&ximize"), self) #QtCore.QObject.connect(self.maximizeAction, # QtCore.SIGNAL("triggered()"), self, # QtCore.SLOT("showMaximized()")) #self.restoreAction = QtGui.QAction(self.tr("&Restore"), self) #QtCore.QObject.connect(self.restoreAction, # QtCore.SIGNAL("triggered()"), self, # QtCore.SLOT("showNormal()")) self.quitAction = QtGui.QAction(self.tr("&Quit"), self) QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) def createTrayIcon(self): self.trayIconMenu = QtGui.QMenu(self) #self.trayIconMenu.addAction(self.minimizeAction) #self.trayIconMenu.addAction(self.maximizeAction) #self.trayIconMenu.addAction(self.restoreAction) #self.trayIconMenu.addSeparator() self.trayIconMenu.addAction(self.quitAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) app = QtGui.QApplication(sys.argv) x = Systray() sys.exit(app.exec_()) How would I go about setting the icon? From george.sakkis at gmail.com Wed Mar 5 10:11:30 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 5 Mar 2008 07:11:30 -0800 (PST) Subject: Why """, not '''? References: Message-ID: <550ce289-9a5b-465f-9183-a7a2094f6e2d@d21g2000prf.googlegroups.com> On Mar 5, 9:56 am, MartinRineh... at gmail.com wrote: > Why is """ the preferred delimiter for multi-line strings? Is it ? FWIW, I use single quotes whenever I can and double whenever I have to (i.e. rarely). George From tjreedy at udel.edu Mon Mar 24 20:11:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Mar 2008 20:11:41 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> <13ufb02heg16d44@corp.supernews.com> <69ec26f2-59fc-46ac-95c2-dc7fef7e7723@e6g2000prf.googlegroups.com> <13ufd10ps50mm4a@corp.supernews.com> Message-ID: "Arnaud Delobelle" wrote in message news:ce8f8ec1-80a0-49ac-8762-a8c9d4cbdcc0 at c19g2000prf.googlegroups.com... >From what I remember when I looked at the source: stack frames execute code objects, not functions. They don't know what function has spawned them, only what code object they are executing. In fact when one thinks of it, it makes more sense for code objects to have a name (taken from the def statement) than for function objects, as there is exactly one code object for every def statement. This is what I tried to say before. Function objects have the attributes needed to call the code. Code objects have attributes needed to execute the code. Both have a name for str() and repr(). tjr From zerty.david at gmail.com Wed Mar 26 14:04:44 2008 From: zerty.david at gmail.com (David Anderson) Date: Wed, 26 Mar 2008 15:04:44 -0300 Subject: what does ^ do in python In-Reply-To: <47E97E8B.2010108@tim.thechases.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> Message-ID: <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> HOw can we use express pointers as in C or python? On Tue, Mar 25, 2008 at 7:36 PM, Tim Chase wrote: > > In most of the languages ^ is used for 'to the power of'. > > > > No, not in most languages. In most languages (C, C++, Java, C#, Python, > > Fortran, ...), ^ is the xor operator ;) > > ...and in Pascal it's the pointer-dereferencing operator... > > -tkc > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Mar 10 12:57:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 09:57:54 -0700 (PDT) Subject: tcp client socket bind problem References: Message-ID: <42925034-6cf7-40a7-b079-8f3bf978fea2@n36g2000hse.googlegroups.com> On Mar 10, 9:40?am, Marc Christiansen wrote: > nata... at gmail.com wrote: > > I have a linux box with multiple ip addresses. I want to make my > > python client connect from one of the ip addresses. Here is my code, > > no matter what valid information I put in the bind it always comes > > from the default ip address on the server. Am I doing something wrong? > > > ------------- > > #!/usr/bin/python > > > import socket > > > host = "server" > > port = 1190 > > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > sock.bind(("",0)) > > sock.connect((host, port)) > > ------------- > > Looks good to me. Just to verify it, I added 127.1.2.3 as an address to > lo (ip addr add 127.1.2.3/8 dev lo broadcast 127.255.255.255), and... > > ?>>> import socket > ?>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > ?>>> sock.bind(("127.1.2.3",0)) > ?>>> sock.connect(("127.0.0.1",80)) > > In another shell: > tolot:~> lsof -c python -a -i -nP > COMMAND ?PID ?USER ? FD ? TYPE ?DEVICE SIZE NODE NAME > [...] > python ?1287 tolot ? ?3u ?IPv4 3553610 ? ? ? TCP 127.1.2.3:38329->127.0.0.1:80 (ESTABLISHED) help string: Bind the socket to a local address. For IP sockets, the address is a pair (host, port); the host must refer to the local host. docs: Bind the socket to address. Wikipedia: Before a socket may accept incoming connections, it must be bound. PHP.net: Binds the name given in address to the socket described by socket . This has to be done before a connection is be established using socket_connect() or socket_listen(). This function must be used on the socket before socket_connect(). From python at rcn.com Fri Mar 7 14:14:38 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 7 Mar 2008 11:14:38 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> Message-ID: <51ca8638-65fa-490b-a04a-33ffbefd4aca@s19g2000prg.googlegroups.com> [bearophileH] > I find itertools.islice() useful, so for Python 3.x I may like to see > it removed from the itertools module, and the normal slicing syntax > [::] extended to work with generators/iterators too. This is a can of worms. First, remember iterations is a protocol, not a type. So, this would have to be added to every possible iterator class (dict.iteritems() and enumerate() for example). Second, he who wants slicing, at some time will want getitem, but Guido ruled this out long ago saying that it is a mistake to conflate sequences and general iterables. Third, the analogy breaks down quickly (i.e. chain(it[:2], it[2:]) does not give the same result as iter(it) unless working on a re-iterable sequence). Fourth, this suggests other related hyper-generalizations which also break down in practice (i.e. using the plus operator for chain() breaks down when you write it+it and find that the second one is fully consumed by the time chain() gets to it). Besides, if you know what you're doing it is simple to write a trivial wrapper class that temporarily supports the slicing notation: class W: def __init__(self, it): self.it = iter(it) def __getitem__(self, n): if isinstance(n, slice): return islice(self.it, n.start, n.stop, n.step) return islice(self.it, n, n+1) >>> s = 'abcdefg' >>> list(W(s)[2:]) ['c', 'd', 'e', 'f', 'g'] >>> list(W(s)[:2]) ['a', 'b'] >>> list(W(s)[::2]) ['a', 'c', 'e', 'g'] >>> list(W(s)[2]) ['c'] Raymond From me at privacy.net Sat Mar 15 16:06:26 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 20:06:26 +0000 Subject: Getting started with OS X Leopard In-Reply-To: <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> Message-ID: <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Arnaud Delobelle wrote: > Is there a particular reason you want python from MacPorts? OSX > Leopard comes with python 2.5, that's what I use on my mac. I heard from somewhere that Apple's version was a bit wonky, and that I would be better off with a "proper" build. From kpdere at derenet.us Sun Mar 2 10:27:18 2008 From: kpdere at derenet.us (Ken Dere) Date: Sun, 02 Mar 2008 10:27:18 -0500 Subject: Book Recomendations References: Message-ID: Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira I started off with Fortran 6X so I have been in the business about as long. Do just about everything now in Python. I liked Learning Python Ken D. From castironpi at gmail.com Sun Mar 30 01:34:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 22:34:27 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> <13utgh8j9ik8t7c@corp.supernews.com> Message-ID: On Mar 29, 5:33?pm, Scott David Daniels wrote: > Lie wrote: > > On Mar 30, 2:57 am, mac_the_sco... at hotmail.com wrote: > >> Hi there. > >> I ... started writing simple programs in the python gui... ?when I write > >> python code ...[and]... double click it all that happens is a black box > >> flashes up on the screen, but nothing else!? .... > > > open the program in IDLE (or any other Python IDEs). I'm guessing that > > your program is printing a traceback (error) when trying to get input > > that's why it immediately closes itself. > > Another possibility is to open a shell (or command window or "dos box"), > and in that window type in "python myfile.py" You'll see error messages > because the display window does not depend on the program staying alive. > > By the way, a better thing to have said when you asked this would > include your OS, the python version, and the GUI system you are using. > Those details matter. ?If you are doing wxPython programming, for > example, you cannot easily use IDLE for your program (GUI systems > fight for control of the display). The screen is real (r-e-a-l): all manners intended. Real. Just bid and auction. From PeterBraden1 at googlemail.com Sat Mar 8 20:37:25 2008 From: PeterBraden1 at googlemail.com (PB) Date: Sat, 8 Mar 2008 17:37:25 -0800 (PST) Subject: Image Libraries References: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> Message-ID: <8654ddf0-a3ab-4c2a-a730-95b152512fad@59g2000hsb.googlegroups.com> Maybe I am unaware of the right way to do it, but the only way I can think to draw several shapes of different transparencies is to create an image for each layer and then combine them which seems overly complex. It would be nice to simply be able to specify colors with an alpha value combined (ie RGBA) for image draw operations. Is there a way to do this? Cheers, Peter Ken wrote: > PB wrote: > > I have been using PIL for generating images, however it does not > > easily support operations with transparency etc. > > > > I tried to install aggdraw but it wouldn't compile. > > > > Ideally I'd like something open source so I can adapt it, hopefully > > mostly written in python rather than C. > > > > Is there any other decent image libraries for python? > > > > > I use PIL, and I haven't had any difficulty with alpha channel > transparency. But maybe I'm using it for different things than you > (blitting PGN(RGBA) antialiased images mostly). What problems are you > having specifically? > > Ken Seehart From bj_666 at gmx.net Tue Mar 4 01:51:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Mar 2008 06:51:35 GMT Subject: help needed with regex and unicode References: Message-ID: <6349rmF23qmbmU1@mid.uni-berlin.de> On Tue, 04 Mar 2008 10:49:54 +0530, Pradnyesh Sawant wrote: > I have a file which contains chinese characters. I just want to find out > all the places that these chinese characters occur. > > The following script doesn't seem to work :( > > ********************************************************************** > class RemCh(object): > def __init__(self, fName): > self.pattern = re.compile(r'[\u2F00-\u2FDF]+') > fp = open(fName, 'r') > content = fp.read() > s = re.search('[\u2F00-\u2fdf]', content, re.U) > if s: > print s.group(0) > if __name__ == '__main__': > rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php') > ********************************************************************** > > the php file content is something like the following: > > ********************************************************************** > // Check if the folder still has subscribed blogs > $subCount = function1($param1, $param2); > if ($subCount > 0) { > $errors['summary'] = '?????????????????????????????????????????'; > $errorMessage = '?????????????????????????????????????????'; > } Looks like an UTF-8 encoded file viewed as ISO-8859-1. Sou you should decode `content` to unicode before searching the chinese characters. Ciao, Marc 'BlackJack' Rintsch From roygeorget at gmail.com Tue Mar 11 06:54:23 2008 From: roygeorget at gmail.com (royG) Date: Tue, 11 Mar 2008 03:54:23 -0700 (PDT) Subject: rmdir problem References: Message-ID: <239ccb7e-9c11-4a59-9ec9-f2d3fa8e5efa@h11g2000prf.googlegroups.com> On Mar 11, 3:37 pm, Paul > Have a look at shutil.rmtree > thanks Paul RG From thudfoo at opensuse.us Thu Mar 6 13:19:24 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Thu, 6 Mar 2008 10:19:24 -0800 Subject: Better grammar.txt In-Reply-To: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> Message-ID: <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> On 3/5/08, MartinRinehart at gmail.com wrote: > MartinRineh... at gmail.com wrote: > > It includes three corrections to grammar.txt (imagnumber, xor_expr and > > and_expr) that I've reported. > > > Make that four corrections. Add augop. > > -- > http://mail.python.org/mailman/listinfo/python-list > An error occurred while loading http://www.martinrinehart.com/articles/python-grammar.html: Unknown host www.martinrinehart.com From chris at wonderstore.com Wed Mar 26 10:13:09 2008 From: chris at wonderstore.com (wrightee) Date: Wed, 26 Mar 2008 07:13:09 -0700 (PDT) Subject: PyQT / QDate / QTableWidget Message-ID: <4bba38af-afd9-4696-b71d-19a256fafcea@i7g2000prf.googlegroups.com> Hi, new at PyQT but not coding.. I'm stumbling with QDate and QTableWidget using PyQT and would appreciate some guidance: My server gives me a string y[0]: "20080327", which I convert to a QDateTime object using: x=QDateTime.fromString(y[0],"yyyymmdd") Printing x.toString("dd-mm-yyyy") gives me what I would expect - 27-03-2008 What I'm trying to do though is add this to a QTableWidget item to create a date sortable column; I'm using this: if type(y)==QDateTime: item=QTableWidgetItem() item.setData(Qt.DisplayRole,QVariant(y)) BUT.. I'm adding 90 dates going back from today and getting values that look like this: 27/01/2007 00:12 28/01/2007 00:12 29/01/2007 00:12 30/01/2007 00:12 31/01/2007 00:12 01/01/2008 00:01 01/01/2008 00:02 01/01/2008 00:03 etc I tried using QDate but couldn't seem to be able to get QDate.fromString to create an object at all. Could someone please advise where I'm going wrong, the end result should be a column in my QTableWidget formatted dd/mm/yyyy that can be sorted as dates, not strings, and originate from data formatted "YYYYMMDD" Thank you very much in advance! From paddy3118 at googlemail.com Sun Mar 23 14:02:40 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 23 Mar 2008 11:02:40 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <8e5cca0c-e9c8-4c5c-9a54-d8951289f92b@c19g2000prf.googlegroups.com> On Mar 23, 4:14 pm, Paddy wrote: > On Mar 23, 3:53 pm, John Nagle wrote: > > > What's the cheapest way to test for an empty dictionary in Python? > > > if len(dict.keys() > 0) : > > > is expensive for large dictionaries, and makes loops O(N^2). > > > John Nagle > > As others have stated, if : is false for built-in > container types such as dicts, lists, sets, tuples,... > Its nice to make any of your own container types follow the same > convention too. > > - Paddy. I missed out *empty* didn't I. Its false for empty container types. - Paddy. From aisaac at american.edu Wed Mar 12 16:51:30 2008 From: aisaac at american.edu (Alan Isaac) Date: Wed, 12 Mar 2008 20:51:30 GMT Subject: no more comparisons Message-ID: I was surprised to see that comparison is slated for death in Python 3000. For example: http://www.python.org/dev/peps/pep-3100/ list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done] But there is a rumor of a PEP to restore comparisons. http://mail.python.org/pipermail/python-3000/2008-January/011764.html Is that going anywhere? Also, what is the core motivation for removing this functionality? Alan Isaac From timr at probo.com Mon Mar 3 01:16:05 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 03 Mar 2008 06:16:05 GMT Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: Kay Schluehr wrote: > >On 2 Mrz., 06:53, Ben Finney >wrote: > >> One of the stated goals of the migration is that the '2to3' program >> will only migrate Python 2.6 code -> Python 3.0 code. > >Yes, I know. Why? > >"The master said so" isn't an entirely satisfying answer. Nevertheless, it IS the answer for many questions in the Python world. That's the advantage of being Benevolent Dictator For Life. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From willsteve2003 at yahoo.ca Fri Mar 7 12:19:18 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Fri, 7 Mar 2008 09:19:18 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: Dates can be a pain. I wrote my own date program, simply because there are so many different ways to write a date: Mar 8, 2008 March 8th, 08 03/08/08 03-08-2008 And so on and so forth. The tricky bit is how to tell the difference between Day, Month and Year. I wrote a program to check the format used for a date. I assumed that any 4 digits together in a single group were the year. Then I had a list of Months, with the first 3 characters of each and compared that to the field being checked, if found, then that was the month. Then I assumed any number greater than 12 was a day. If I couldn't match those criteria I assumed Month Day Year (the standard at the company I worked for). From lists at cheimes.de Sat Mar 22 18:29:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Mar 2008 23:29:10 +0100 Subject: Problem with complex numbers In-Reply-To: <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> References: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> Message-ID: <47E58836.70202@cheimes.de> Matthias G?tz schrieb: > So can you tell me what's the purpose of Complex.py, > > and where can i find the semantic i'am looking for. Well, the file is in the Demo folder. It's just a demo how to implement a naive complex type in Python. Why do you think the power of a complex to a complex is not defined? Raising a complex to a complex power is well defined, although the mathematical proof isn't trivial. You have to use the Euler form. Ask Google for some examples Christian From rockxuan at gmail.com Tue Mar 18 03:46:00 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:46:00 -0700 (PDT) Subject: www.51cntrade.com suipply you replicas watches & jewellery fashion Message-ID: <2ce5607d-1538-40a9-ad24-d364c534a342@d4g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From pavlovevidence at gmail.com Mon Mar 3 16:13:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 13:13:23 -0800 (PST) Subject: Inheritance issue... References: <632vhiF262j15U1@mid.uni-berlin.de> Message-ID: On Mar 3, 3:14 pm, MooMaster wrote: > On Mar 3, 11:49 am, "Diez B. Roggisch" wrote: > > > > > MooMaster schrieb: > > > > I'm trying to use inheritance to create a simple binary tree, but it's > > > not going so well... here's what I pull from the documentation for > > > super() > > > "super( type[, object-or-type]) > > > > Return the superclass of type. If the second argument is omitted the > > > super object returned is unbound. If the second argument is an object, > > > isinstance(obj, type) must be true. If the second argument is a type, > > > issubclass(type2, type) must be true. super() only works for new-style > > > classes. > > > The last sentence contains the important bit. You need to use > > new-style-classes, which means they have to have the ancestor "object" > > somewhere in their inheritance-graph. > > > Like this: > > > class Foo(object): pass > > > Certainly one of the somewhat uglier corners of Python... > > > Diez > > Thanks guys, I hadn't even heard of the distinction between "old" and > "new" style classes...is this in the tutorial somewhere? I didn't see > it in Classes... Here's some reading material (it can get deep): http://www.python.org/doc/newstyle/ http://www.python.org/download/releases/2.2.3/descrintro/ New style classes have been a part of Python since 2.2, but unfortunately many documents intended for newbies don't even mention them, which seems to cause more confusion than it prevents, such as when newbies go Googling for code examples and see incompatible usage of new-style classes. For simple uses, new-style and old-style classes behave similarly enough that it doesn't matter which you use, but new-style classes support lots of things that old-style classes don't, and usage of these features is getting more and more common. Newbies who aren't being alerted to this are getting a raw deal. Thankfully old-style classes are getting the axe in Python 3.0 and hopefully this confusion will go away. Until you switch to 3.0, inherit your base classes from object; it will ensure that more recent additions like properties and super() calls work. class Node(object): .... Carl Banks From ewanfisher at gmail.com Fri Mar 14 13:05:07 2008 From: ewanfisher at gmail.com (ewanfisher at gmail.com) Date: Fri, 14 Mar 2008 10:05:07 -0700 (PDT) Subject: Thousand Seperator Message-ID: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> I'm trying to find some code that will turn: 100 -> 100 1000 -> 1,000 1000000 -> 1,000,000 -1000 -> -1,000 I know that can be done using a regular expression. In Perl I would do something like: sub thousand { $number = reverse $_[0]; $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; return scalar reverse $number; } But I cannot find how to do this in Python. Thanks, Ewan From dmitrey.kroshko at scipy.org Wed Mar 26 08:50:15 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Wed, 26 Mar 2008 05:50:15 -0700 (PDT) Subject: memory allocation for Python list Message-ID: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> hi all, I have a python list of unknown length, that sequentially grows up via adding single elements. Each element has same size in memory (numpy.array of shape 1 x N, N is known from the very beginning). As I have mentioned, I don't know final length of the list, but usually I know a good approximation, for example 400. So, how can I optimize a code for the sake of calculations speedup? Currently I just use myList = [] for i in some_range: ... myList.append(element) ... Thank you in advance, Dmitrey From sam at mas.pl Mon Mar 10 10:21:00 2008 From: sam at mas.pl (sam) Date: Mon, 10 Mar 2008 15:21:00 +0100 Subject: parsing directory for certain filetypes In-Reply-To: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: royG napisa?(a): > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? > Probably this should be rewriten and should be very compact. Maybe you should grab string: find $dirname -type f -a \( -name '*.txt' -o -name '*.doc' \) and split by "\n"? -- UFO Occupation www.totalizm.org From arnodel at googlemail.com Sat Mar 15 05:56:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 15 Mar 2008 02:56:18 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: On Mar 15, 5:47?am, Tim Roberts wrote: > Jeff Schwab wrote: > >Roel Schroeven wrote: > >> castiro... at gmail.com schreef: > >>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: > >>>>> Subject: RIP: Joseph Weizenbaum > >>>>> Creator of Eliza: > >>>>>http://www-tech.mit.edu/V128/N12/weizenbaum.html > > >>>> How do you feel about creator of Eliza? > > >>> What is Eliza? > > >> Does that question interest you? > > >Well played, sir. > > >Earlier you said what is Eliza. ?Do you still feel that way? > > I am embarrassed to say that this vaguely disrespectful exchange made me > laugh out loud. Does it bother you that this vaguely disrespectful exchange made you laugh out loud? From 2huggie at gmail.com Wed Mar 19 07:43:17 2008 From: 2huggie at gmail.com (Timothy Wu) Date: Wed, 19 Mar 2008 19:43:17 +0800 Subject: xml sax Message-ID: Hi, I am using xml.sax.handler.ContentHandler to parse some simple xml. I want to detect be able to parse the content of this tag embedded in the XML. 174 Is the proper way of doing so involving finding the "Id" tag from startElement(), setting flag when seeing one, and in characters(), when seeing that flag set, save the content? What if multiple tags of the same name are nested at different levels and I want to differentiate them? I would be setting a flag for each level. I can imagine things get pretty messy when flags are all around. Timothy -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:08:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:08:01 -0200 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: En Sat, 01 Mar 2008 22:51:08 -0200, escribi?: > Hi everyone: > > I posted here a couple days ago looking for some help creating a > Telnet-based chat server. You guys pointed me to Twisted, which has > solved most of my issues. > > However, what I want to do is analyze strings received for keywords > such as 'listcmds' and have the server return something to the client. > I know how to do that part, at least. > > The issue is, when I use clients like PuTTY, it returns a lot of what > appears to be formatting (e.g. if I typed Hello, it would return "\xff > \xfb\x1f\xff\ > xfb \xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) They are part of the telnet protocol; 0xFF (IAC=Interpret as Command) starts a two or three byte command sequence. Weren't you using telnetlib? It's supposed to handle this transparently. > How would I go about filtering this stuff out of the strings? The > thing is too, if I use other Telnet programs like Microsoft Telnet, > they don't have this formatting, so I want to be able to recognize if > it does have this formatting and act based on if it does or if it > doesn't. Any client could send similar commands at the start of the session, or even later. > Any help is appreciated, I know I'm probably asking too many questions > already :) It isn't too hard to filter them out, if you want to do it by hand. See the source for telnetlib, and the original Telnet specificacion, RFC 854 http://www.rfc-archive.org/getrfc.php?rfc=854 and RFC 855. -- Gabriel Genellina From jr9445 at ATT.COM Mon Mar 24 12:20:09 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 24 Mar 2008 11:20:09 -0500 Subject: Element Tree Help In-Reply-To: References: Message-ID: Robert Rawlins wrote: > I have little to no experiance with element tree and I'm struggling to > find a way to parse the details from the XML document?(attached) into > my application. Essentialy I'm looking to take the following document > and turn it into a?dict of tuples, each?dict element defines a > datasource with the key to the element being the 'name' which is > defined in the XML?and then the value of the pair is a tuple which? > contains the details of the datasource, like the host and port etc. Here's another way to walk an ElementTree. This one creates a hash of hashes which are normally more useful than tuples for property lookups. import xml.etree.ElementTree as ET tree = ET.ElementTree(file = "foo.xml") d = {} for ds in tree.findall("datasource"): name = ds.find('name').text d[name] = {} print 'datasource =', name for i in ds.findall('*'): #for i in ds.getiterator(): # also works if i.tag in ('datasource', 'name'): continue print ' ',i.tag, "=", i.text d[name][i.tag] = i.text print print d ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From fhaxbox66 at googlemail.com Sun Mar 2 09:46:52 2008 From: fhaxbox66 at googlemail.com (Dr. leo) Date: Sun, 2 Mar 2008 15:46:52 +0100 Subject: Hyphenation: PyHyphen 0.4.1 and textwrap2-0.1.1 released Message-ID: <47cabc90$0$582$6e1ede2f@read.cnntp.org> This latest version of PyHyphen is only important for Python 2.4 addicts who encountered a missing type when compiling. Further, a few signed/unsigned mismatch warnings coming from MSVC should be fixed. As I have only Python 2.5, I'd be interested in any experiences when compiling it with Python 2.4. Visit http://cheeseshop.python.org/pypi/PyHyphen Further, as suggested here some days ago, I have integrated 'textwrap ' with PyHyphen. While I anticipated lots of work and hoped for volunteers, I have done it myself now. And it was a cake walk! Just had to insert roughly a handfull of lines... Pure Python is pure fun! Visit http://cheeseshop.python.org/pypi/textwrap2 Bests Stefan From joe.p.cool at googlemail.com Tue Mar 18 16:15:15 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Tue, 18 Mar 2008 13:15:15 -0700 (PDT) Subject: method to create class property Message-ID: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> Hi, I like C#'s style of defining a property in one place. Can the following way to create a property be considered reasonable Python style (without the print statements, of course)? class sample(object): def __init__(self): sample.y = self._property_y() def _property_y(self): def _get(self): print 'getting y.' return self._y def _set(self, value): print 'setting y.' self._y = value def _del(self): print 'bye, y!' del self._y return property(_get, _set, _del) From anthonysmith80 at gmail.com Tue Mar 25 11:31:49 2008 From: anthonysmith80 at gmail.com (Anthony) Date: Tue, 25 Mar 2008 08:31:49 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <29bc6ff2-f172-4776-87b7-884585277570@d21g2000prf.googlegroups.com> Message-ID: <4b864142-5323-46f6-aac5-d39ea7ad64ec@s19g2000prg.googlegroups.com> On Mar 25, 2:31 pm, Tzury Bar Yochay wrote: > I wish it was that simple but 'a = Foo().getid()' is actually creating > a new instance of Foo whereas I want the data of the Foo instanced by > __init__ of FooSon(). I don't think Foo.__init__(self) creates an instance of the Foo class. If you want FooSon to create an instance of Foo, try: class FooSon(Foo): def __init__(self): self.foo = Foo() self.id = 2 def getid(self): a = self.foo.getid() b = self.id return '%d.%d' % (a,b) >>> FooSon().getid() '1.2' Or change "self.id" in Foo to something else, e.g., "self.id_foo". Does that help? Anthony From xelapond at gmail.com Mon Mar 31 21:41:37 2008 From: xelapond at gmail.com (Alex Teiche) Date: Mon, 31 Mar 2008 18:41:37 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> <1a8a5b03-0b9e-49de-bd87-43fa1aa99dc2@b5g2000pri.googlegroups.com> Message-ID: <6b732135-a488-4175-889b-0cccf5f0c581@s8g2000prg.googlegroups.com> On Mar 31, 6:40 pm, Alex Teiche wrote: > On Mar 31, 11:49 am, Alex Teiche wrote: > > > > > On Mar 30, 3:50 pm, Benjamin wrote: > > > > On Mar 29, 11:02 pm, Alex Teiche wrote:> Hello, > > > > > I am pretty new to Python, and have never learned C++. I am trying to > > > > implement the following thing into my python application: > > > > >http://doc.trolltech.com/4.3/qsystemtrayicon.html > > > > > Through PyQt. I have been using PyQt for awhile and I know how do use > > > > it, but I could not get this specific thing to work. Can someone give > > > > me some hints as to get it working in Python? > > > > What problems are you having? > > > > > Thanks a ton, > > > > > Alex > > > Thanks everyone for your help. I found the example to be particularly > > helpful, and I have made a simplified version just to display an icon > > with a quit button in its menu. Once I know how to do that I will > > incorporate it into my larger program, with more options and the > > ability show messages. The problem is, it doesn't work, and I can't > > find out what's wrong. Can you give me some hints? > > > Here is the code: > > import sys > > from PyQt4 import QtGui, QtCore > > > class trayIcon(QtGui.QWidget): > > def __init__(self, parent=None): > > QtGui.QWidget.__init__(self, parent) > > > #********Create Actions for the Tray Menu********# > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > > QtCore.QObject.connect(self.quitAction, > > QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) > > > create_tray_icon() > > > self.composeAction.setEnabled(visible) > > QtGui.QWidget.setVisible(self, visible) > > > self.trayIcon.show() > > > def create_tray_icon(self): > > self.trayIconMenu = QtGui.QMenu(self) > > self.trayIconMenu.addAction(self.composeAction) > > self.trayIcon = QtGui.QSystemTrayIcon(self) > > self.trayIcon.setContextMenu(self.trayIconMenu) > > self.trayIcon.setIcon(bad.svg) > > > app = QtGui.QApplication(sys.argv) > > sys.exit(app.exec_()) > > OK, I messed around with it some more, and it works. I just don't > know how to set an icon, and the example doesn't help at all. > > Here is the code: > import sys > from PyQt4 import QtCore, QtGui > > class Systray(QtGui.QWidget): > def __init__(self): > QtGui.QWidget.__init__(self) > > self.createActions() > self.createTrayIcon() > > #QtCore.QObject.connect(self.trayIcon, > QtCore.SIGNAL("messageClicked()"), self.messageClicked) > #QtCore.QObject.connect(self.trayIcon, > QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), > self.iconActivated) > > self.trayIcon.show() > > def createActions(self): > #self.minimizeAction = QtGui.QAction(self.tr("Mi&nimize"), self) > #QtCore.QObject.connect(self.minimizeAction, > # QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("hide()")) > > #self.maximizeAction = QtGui.QAction(self.tr("Ma&ximize"), self) > #QtCore.QObject.connect(self.maximizeAction, > # QtCore.SIGNAL("triggered()"), self, > # QtCore.SLOT("showMaximized()")) > > #self.restoreAction = QtGui.QAction(self.tr("&Restore"), self) > #QtCore.QObject.connect(self.restoreAction, > # QtCore.SIGNAL("triggered()"), self, > # QtCore.SLOT("showNormal()")) > > self.quitAction = QtGui.QAction(self.tr("&Quit"), self) > QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), > QtGui.qApp, QtCore.SLOT("quit()")) > > def createTrayIcon(self): > self.trayIconMenu = QtGui.QMenu(self) > #self.trayIconMenu.addAction(self.minimizeAction) > #self.trayIconMenu.addAction(self.maximizeAction) > #self.trayIconMenu.addAction(self.restoreAction) > #self.trayIconMenu.addSeparator() > self.trayIconMenu.addAction(self.quitAction) > > self.trayIcon = QtGui.QSystemTrayIcon(self) > self.trayIcon.setContextMenu(self.trayIconMenu) > > app = QtGui.QApplication(sys.argv) > x = Systray() > sys.exit(app.exec_()) > > How would I go about setting the icon? Sorry, here is the code with commented out lines removed: import sys from PyQt4 import QtCore, QtGui class Systray(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.createActions() self.createTrayIcon() self.trayIcon.show() def createActions(self): self.quitAction = QtGui.QAction(self.tr("&Quit"), self) QtCore.QObject.connect(self.quitAction, QtCore.SIGNAL("triggered()"), QtGui.qApp, QtCore.SLOT("quit()")) def createTrayIcon(self): self.trayIconMenu = QtGui.QMenu(self) self.trayIconMenu.addAction(self.quitAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) app = QtGui.QApplication(sys.argv) x = Systray() sys.exit(app.exec_()) From simon at brunningonline.net Wed Mar 19 09:03:46 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 19 Mar 2008 13:03:46 +0000 Subject: Using threads in python is safe ? In-Reply-To: <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> <48224a820803190043n29974c25xf5a5e770080d89ae@mail.gmail.com> Message-ID: <8c7f10c60803190603u5c104908p37dd103035e90348@mail.gmail.com> On Wed, Mar 19, 2008 at 7:43 AM, Deepak Rokade wrote: > If jobs to be processed by threds is I/O bound would multithreading help > python to improve speed of application ? Probably, yes. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From frikker at gmail.com Mon Mar 3 10:39:41 2008 From: frikker at gmail.com (blaine) Date: Mon, 3 Mar 2008 07:39:41 -0800 (PST) Subject: Talking to a usb device (serial terminal) Message-ID: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Hey everyone, We have a usb spectrometer device that we have finally got working in linux (we were provided linux only drivers). The device has a Silicon Instruments cp2101 serial-to-usb chip onboard, and we loaded the kernel module cp2101.c after taking the device apart to see what was on the inside. Using minicom we are able to set a baud rate and open up a terminal when pointing to the device /dev/ttyusb0 (I think). Anyway, I want to be able to talk to our cool device using python. I haven't been able to find many resources specifically in this area, but there are a few package that are vaguely mentioned, including fcntl and termios. But the web doesn't seem to have a lot of documentation on fcntl, particularly information thats from the past 8 years. So my question is this - what is the easiest way to interface to this "serial" device? I don't imagine a straight read() and write() command to /dev/ttyusb0 is the most efficient (if it even works) especially since we would need to set a baud rate. My experience with terminal communication is pretty limited. Any advice that can be offered would be awesome. Thanks! PS: The device that we will be using python on will be an embedded ARM system. Currently we are testing using a linux laptop and cross compiling the kernel over to the embedded device. The device has Python 2.4, and does have both the termios and fcntl packages available. Python 2.4.2 (#1, Feb 20 2008, 11:07:36) [GCC 4.1.1] on linux2 uname -a: Linux gumstix 2.6.21gum #1 Wed Feb 20 02:53:01 EST 2008 armv5tel unknown Blaine Booher University of Cincinnati From nothanks at null.invalid Sat Mar 22 23:27:57 2008 From: nothanks at null.invalid (Bill) Date: Sat, 22 Mar 2008 23:27:57 -0400 Subject: wxFormBuilder In-Reply-To: References: Message-ID: <47E5CE3D.8010102@null.invalid> sturlamolden wrote, On 3/20/2008 9:41 AM: > I just discovered wxFormBuilder. After having tried several GUI > builders for wx (including DialogBlocks, wxGlade, XRCed, Boa > constructor), this is the first one I can actually use. > > To use it wxFormBuilder with wxPython, I generated an xrc resource and > loaded it with wxPython. All the tedious GUI coding is gone :-) > > http://wxformbuilder.org/ > http://wiki.wxpython.org/index.cgi/XRCTutorial > > What don't you like about wxGlade? It actually generates Python code. There has been a lot more development going on recently, too. Bill From castironpi at gmail.com Wed Mar 26 22:00:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 19:00:40 -0700 (PDT) Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Message-ID: <248e2789-822f-43cd-be3c-e2498d4c8ea7@d45g2000hsc.googlegroups.com> On Mar 26, 5:11?pm, Miki wrote: > Hello Tim, > > > > > > > I want to write a tiny interactive app for the following situation: > > I have books of many chapters that must be split into volumes before going > > to the printer. > > A volume can have up to 600 pages. We obviously break the book into volumes > > only at chapter breaks. Since some chapters make a natural grouping, we want > > some human interaction for where the volume breaks occur. > > > Not having experience with interactive apps, I'm asking for advice about how > > to go about it. The data I start with is just a dictionary with chapter name > > = ending page number. I figured I would first show where the volumes would > > break with no human interaction, with the begin and ending chapter > > names/pagenumbers for each volume. > > > From here I thought about having a slider for each volume, but the number of > > volumes could change during the session. > > Or maybe I should just ask 'enter the ending chapter for the first volume' > > and recalculate, etc until all volumes are defined. > > > Any ideas on a simple interface for this? > > How about something like: > > Chapter 1 (001-200 200) > Chapter 2 (200-300 100) > ------ 001-300 300 ---- > Chapter 3 (300-450 150) > Chapter 4 (450-500 50) > ------ 300-450 250 ---- > Chapter 5 (500-600 100) > ------ 500-600 100 ---- > > Where the user can move the divider up and down to create new volume, > they can also add and delete dividers. > > The program will not allow to drag the divider above the 600 page > limit. If you're a WISIWIG editor, you can select text by - typing STRNG - editor overlays IDs on every occurence - repeat or select number I'm looking at debugging, and you do get: >>> pdb.run( 'f()' ) > (1)()->None (Pdb) s --Call-- > (1)f() (Pdb) s > (5)f() (Pdb) s --Call-- > c:\programs\python\lib\io.py(1235)write() -> def write(self, s: str): (Pdb) l 1230 return self.buffer.fileno() 1231 1232 def isatty(self): 1233 return self.buffer.isatty() 1234 1235 -> def write(self, s: str): 1236 if self.closed: 1237 [snip] 1238 if not isinstance(s, str): 1239 [snip] 1240 [snip] allowing you to see what you want, adjust, and keep a mind's-eye representation of the program. Are you complaining that the mouse is too slow? That the GUI is too distant? Closest lexical: 'editor sucks' and 'console sucks'. I think a SmartConsole would take A.I. I want a multi-column console. I'm not sure how generally you can harness today's GI on a keyboard, but tomorrow's certainly can. (scrollbar2 up>up>up), and I think you'd get console gi primitives pretty quickly. (graphical/spatial interface.) You're thinking of mimetic/conceptual zoom. How does this look? >>> open Chapter 1 (001-200 200) Chapter 2 (200-300 100) ------ 001-300 300 ---- Chapter 3 (300-450 150) Chapter 4 (450-500 50) ------ 300-450 250 ---- Chapter 5 (500-600 100) ------ 500-600 100 ---- >>> move up Chapter 1 (001-200 200) ------ 001-200 200 ---- Chapter 2 (200-300 100) Chapter 3 (300-450 150) Chapter 4 (450-500 50) ------ 300-450 150 ---- Chapter 5 (500-600 100) ------ 500-600 100 ---- >>> move up Chapter 1 (001-200 200) ------ 001-200 200 ---- Chapter 2 (200-300 100) Chapter 3 (300-450 150) ------ 200-450 250 ---- Chapter 4 (450-500 50) Chapter 5 (500-600 100) ------ 450-600 150 ---- But us mortal humans, temporal beings, get confused quickly with what section is where, so we'll mis-specify eventually. ("No, the -other- up!") Did everyone know that the graphics blits in BASIC were 'get' and 'put'? You could probably pick a recommended contextmanager out of the box; it could learn what you wanted by when you said 'no'. You'll want a: >>> notify me when a volume's page length > 600 which isn't clear at all how to translate into CS in a rigorous way, and its varying meanings for different structures. >>> Upon( page length.volume > 600 for volume in book, print ) And each page length change notifies 'Upon', cf. Observer. I feel like the way from point A you mention and the actual implementation would be useful. Python shows promise for 'rollback' potential too. >>> UponAny( page length.volume > 600 for volume in book, raise ) >>> Upon( any( sum( volume ) > 600 for volume in book ), raise ) Somehow, your data are still around during console session-- exception doesn't kill a console. This one generates a console of a dictionary and lets you assign to it. --> a= 2 --> print( a ) 2 --> def con(): while 1: try: yield input( '--> ' ) except: print( 'exception.' ) glos, locs= {}, {} for inp in con(): exec( inp, glos, locs ) We might have to mark our objects live / "on the air", to notify generators of change in conditions, rerun at every step. I think you need live primitives. From willsteve2003 at yahoo.ca Thu Mar 6 15:29:38 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Thu, 6 Mar 2008 12:29:38 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <3ddf3ef3-529c-4a81-932a-d2dda4972704@e23g2000prf.googlegroups.com> Message-ID: On Mar 6, 3:20?pm, George Sakkis wrote: > On Mar 6, 9:27 am, Pierre Quentel wrote: > > > > > > > Hi, > > > I would like to know if there is a module that converts a string to a > > value of the "most probable type" ; for instance : > > - if the string is "abcd" the value is the same string "abcd" > > - string "123" : value = the integer 123 > > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > > = the float -1.23 > > - string "2008/03/06" (the format is also locale-dependant) : value = > > datetime.date(2008,03,06) > > > Like in spreadsheets, special prefixes could be used to force the > > type : for instance '123 would be converted to the *string* "123" > > instead of the *integer* 123 > > > I could code it myself, but this wheel is probably already invented > > Maybe, but that's a so domain-specific and easy to code wheel that > it's no big deal reinventing. > > George- Hide quoted text - > > - Show quoted text - Actually you could probably write your own code very easily, a couple of try/except clauses. I would recommend you try int() first, then try float(), then try date check and when all else fails leave it a string. However, it may be an interesting challenge for those who are willing to make the attempt. "Define Cell/Field contents". From tjreedy at udel.edu Tue Mar 11 00:04:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 00:04:44 -0400 Subject: image matching algorithms References: Message-ID: "Daniel Fetchinson" wrote in message news:fbe2e2100803092332u5b222ff8o2ffe84cbc0334f7 at mail.gmail.com... | The various free tools differ by their chosen optimization paths and | their degree of specialization. My preference would be, | | 1. Doesn't really matter how long it takes to compute the N numbers per image Your problem here is that there is really no such thing as 'general features' and correspondingly, no such thing as 'general similarity of features'. The features extracted have to have a specific definition. The features represent a severe lossy compression of the original. What to keep depends on the application. Example: classify each pixel as white, black, red, green, or blue. Will that match your intuitive idea of what matches? To be a bit more sophisticated, use more color bins and do the binning separately for multiple areas, such as top, left, center, right, and bottom (or center, upper right, upper left, lower right, and lower left). I suspect Google does something like this to match, for instance, pictures with skin tones in the center, or pictures with blue tops (sky?) and green bottoms (vegetation?). | 2. Lookups should be fast, consequently N should not be too large (I guess) | 3. It should be a generic algorithm working on generic images (everyday photos) Given feature vectors, there are various ways to calculate a distance or similarity coefficient. There have been great debates on what is 'best'. | 4. PIL should be enough for the implementation | | So if anyone knows of a good resource that is close to being pseudo | code I would be very grateful! If you do not have sufficient insight into your own idea of 'matches', try something on a test set of perhaps 20 photos, calculate a 'match matrix', and compare that you your intuition. Terry Jan Reedy From http Mon Mar 17 04:20:52 2008 From: http (Paul Rubin) Date: 17 Mar 2008 01:20:52 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <7x3aqpg3rv.fsf@ruckus.brouhaha.com> Stephan Deibel writes: > I have to admit, I'll keep coming to PyCon even if all the talks suck > abysmally as long as there's good hallway time, open space, BoFs, and > sprints. ;-) OK, so why not get rid of all the talks and other stuff, and just have a basically structureless conference, beyond scheduling some open meetings on various topics? That would be a lot less expensive and a lot more interesting. From saluk64007 at gmail.com Tue Mar 25 02:18:53 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Mon, 24 Mar 2008 23:18:53 -0700 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: It seems like this is mostly a non-issue. The original code actually works correctly (of course the updated versions that solve the exception problem are probably better). The only thing that is going haywire is the interpreter shutdown process. I think it is going a bit overboard to "consider __del__ harmful" because it might throw an exception as the program is quitting. It is important to not rely on __del__ too much but there can be some designs where you need to know when something is gone, and you don't know exactly where or when something is deleted. Then again, I can count the number of times I have ever needed __del__ with no fingers (never used it!). Still, quite interesting to explore. From aboudouvas at panafonet.gr Thu Mar 27 12:14:15 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 09:14:15 -0700 (PDT) Subject: Psyco alternative References: Message-ID: <10d4e6b6-71f3-4c22-8b13-17dd32a4374f@c19g2000prf.googlegroups.com> > One reason attention is going to PyPy instead of Psyco... > > Jean-Paul I had a look at PyPy, it, indeed, have a very long way to go so we can consider it an alternative. From tgrav at mac.com Tue Mar 4 20:06:38 2008 From: tgrav at mac.com (Tommy Grav) Date: Tue, 4 Mar 2008 20:06:38 -0500 Subject: SV: Polymorphism using constructors In-Reply-To: References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: On Mar 4, 2008, at 4:53 PM, Jeff Schwab wrote: > What does "SV" in the subject mean? SV = "Svar" is the Norwegian word for Reply. Cheers Tommy From __peter__ at web.de Thu Mar 13 05:20:15 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Mar 2008 10:20:15 +0100 Subject: List mutation method gotcha - How well known? References: Message-ID: Hendrik van Rooyen wrote: > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): I thought it were a FAQ, but found only http://effbot.org/pyfaq/why-doesn-t-list-sort-return-the-sorted-list.htm I'm sure you can draw the analogy. Peter From noZ.spamZ at ZZ.ZsvpZ.com Sat Mar 29 16:27:25 2008 From: noZ.spamZ at ZZ.ZsvpZ.com (Michel Claveau - NoSpam SVP ; merci) Date: Sat, 29 Mar 2008 21:27:25 +0100 Subject: Finding Full Path to Process EXE In-Reply-To: References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> Message-ID: <47eea713$0$27902$426a74cc@news.free.fr> Hi! Warning : WMI give the "command-line" of a process only for windows > 2000 @-salutations Michel Claveau From gagsl-py2 at yahoo.com.ar Mon Mar 17 21:33:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 18:33:53 -0700 (PDT) Subject: First Program Bug (Newbie) References: Message-ID: <7ee63034-f73e-43c8-8183-fdf824201d9f@c19g2000prf.googlegroups.com> On 17 mar, 21:03, Benjamin Serrato wrote: > I Found It!! The following was a post asking for help finding a bug. I > thought I needed help with my syntax, but just before sending I found > the bug on line 13. Line 13 should read: "base = 2". I would still > appreciate any comments on my program. Maybe there is a better way to do > it that I didn't think about. I know it's not that interesting but it's > my first one. You may look at the fact.py demo script (somewhere in your python installation) > I'm almost halfway through an online tutorial I found on the python.org > site and decided to stop and write a program for myself. I got it in my > head to write a program to print all the primes; the idea came from > another tutorial. The program prints some non-prime numbers. In a > comparison to lists of primes the program prints eight non-primes for > numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. > Here is the program. > > base = 2 > candidate = 3 > > while True: > ? ? ? ? while candidate % base != 0: > ? ? ? ? ? ? ? ? base = base + 1 > ? ? ? ? ? ? ? ? if base > (candidate / 2): > ? ? ? ? ? ? ? ? ? ? ? ? print candidate > ? ? ? ? ? ? ? ? ? ? ? ? candidate = candidate + 1 > ? ? ? ? ? ? ? ? ? ? ? ? base = 2 > ? ? ? ? else: > ? ? ? ? ? ? ? ? candidate = candidate + 1 > base = 2 # added Note that you can increment candidate by 2 (starting at 3, all primes are odd numbers). And after testing 2, you can increment base by 2 also. And you can exit somewhat earlier: if base*base>candidate there is no point in keep trying (now you`re exiting when base*2>candidate) > At first I tried to use 'return' on the 'else' block to cause the > program to loop, but I don't understand 'return' yet and that didn't > work. So, I put the rest into another while loop and was really happy to > find it worked but the program prints some non-prime numbers. return only makes sense inside a function. Wait until the next lesson... -- Gabriel Genellina From Grimsqueaker13 at gmail.com Thu Mar 27 02:15:41 2008 From: Grimsqueaker13 at gmail.com (Grimsqueaker) Date: Wed, 26 Mar 2008 23:15:41 -0700 (PDT) Subject: counting using variable length string as base Message-ID: Hi, I'm fairly new to Python and to this list. I have a problem that is driving me insane, sorry if it seems simple to everyone, I've been fighting with it for a while. :)) I want to take a variable length string and use it as a base for counting, eg. given the string 'abc' the sequence would be: a b c aa ba ca ab bb cb ... ccc Basically I want to find every possible order of every combination. Its easy if you know how many characters there will be in your string (use nested for loops), but I am stuck with the variable length string. I think I have to use a generator but I'm not sure exactly how. Can anyone give me a pointer in the right direction? Thanks Daniel Browne From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 13 06:46:34 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 13 Mar 2008 11:46:34 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: References: Message-ID: <47d905cd$0$16137$426a74cc@news.free.fr> Hendrik van Rooyen a ?crit : > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above answer 5 - list.append returns None, which when printed gives 'None'. You'll get the same thing with list.sort, list.extend, list.reverse etc... From znfmail-pythonlang at yahoo.com Wed Mar 19 11:35:14 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Wed, 19 Mar 2008 11:35:14 -0400 Subject: cx_Oracle execute procedure References: Message-ID: Thanks Jerry and Diez. The first two replies I found answered my noob question. "Jerry Hill" wrote in message news:mailman.2148.1205940209.9267.python-list at python.org... > On Wed, Mar 19, 2008 at 11:03 AM, Poppy > wrote: >> I've been working on the code below and and executes silently, no >> complaints, however the end result should be a record in my table and >> it's >> not added. The procedure works with the passed credentials using SQLPlus >> or >> SQL Developer clients. However I'm not sure if I'm constructing my >> python >> code correctly to interact with Oracle. > ... >> connection.commit >> cur.close >> connection.close > > You have to actually call these methods: > connection.commit() > cur.close() > connection.close() > > Without the parentheses, you're just getting a reference to the > methods and immediately discarding them. > > -- > Jerry From stephenhorne100 at aol.com Mon Mar 17 09:06:59 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 06:06:59 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: On Mar 17, 12:28 pm, castiro... at gmail.com wrote: > > Why is the immutable form the default? > > Using a house definition from some weeks ago, a tuple is a data > structure such which cannot contain a refrence to itself. Can a > single expression refer to itself ever? Can't imagine why that feature was highlighted in particular, but a list can reference itself even though an expression can't. The following example looks a bit self-referential, but isn't... a = 2 a = [1, a, 3] # result [1, 2, 3] The following additional line, however does create a self-referencing list... a [1] = a The result being [1, [...], 2] It's nice to see that Python can handle the output for this without going into an infinite recursion - which is exactly what it used to do in the distant past. A tuple cannot be made to reference itself because it cannot be modified after creation. The key point is that lists are mutable, whereas tuples are not. From castironpi at gmail.com Tue Mar 25 18:04:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 15:04:53 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: On Mar 23, 8:05?pm, Tim Chase wrote: > > When I run this script, I got the following exception: > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'population'" in > <__main__.Person instance at 0xb7d8ac6c>> ignored > > > To to newcomer like me, this message doesn't make much sense. What > > seems weird to me is that, if I change the variable cathy to something > > else, like cath, or even cat, then the script will finish gracefully. > > Why "cathy" is not liked?!! > > > My python is of version 2.5.1, on Ubuntu. > > When I first read this, I thought you were crazy. ?I ran the > code, and you're not. ?I tried under versions 2.3, 2.4, and 2.5 > on my Debian box, and got the same results. ?Neither "cathy" nor > "ca" works, ?but "c", "cat", "cath", "cath_y" and "cathy_" all > work just fine. > > Even more infuriating is that if I try and use pdb to debug, > Swaroop drops into pdb, but Abdul and Cathy both error out. > [snip] > Does Python hate Cathy? Does Pothon? From deets at nospam.web.de Sun Mar 30 08:23:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Mar 2008 14:23:39 +0200 Subject: problem with logic in reading a binary file In-Reply-To: <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> Message-ID: <659f2cF2dq5riU1@mid.uni-berlin.de> hdante schrieb: > On Mar 30, 4:31 am, John Machin wrote: >> On Mar 30, 3:58 pm, hdante wrote: >> >> >> >>> On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" >>> wrote: >>>> Hello, >>>> I am having trouble writing the code to read a binary string. I would >>>> like to extract the values for use in a calculation. >>>> Any help would be great. >>> I'm too lazy to debug your binary string, but I suggest that you >>> completely throw away the binary file and restart with a database or >>> structured text. See, for example: >>> http://pyyaml.org/wiki/PyYAML >>> If you have some legacy binary file that you need to process, try >>> creating a C program that freads the binary file and printfs a text >>> equivalent. >> ... and that couldn't be done faster and better in Python?? > > No. A C struct is done faster and better than python (thus, the > correctness check is faster in C). Also, chances are high that there's > already an include file with the binary structure. That is utter nonsense. There is no "correctness check" in C. and using printf & thus creating strings that you then need to parse in python just doubles the effort needlessly. The standard-lib module "struct" is exactly what you need, nothing else. it sure is faster than any parsing of preprocessed data, doesn't introduce a language-mixture and is prototyped/tested much faster because of it being python - and not C-compiler and C-debugger. Alternatively, *IF* there were C-structure-declarations available for the binary format, the usage of ctypes would allow for roughly the same, even reducing the effort to create the structure definition a great deal. Diez From ganeshborse at gmail.com Wed Mar 19 04:40:44 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Wed, 19 Mar 2008 01:40:44 -0700 (PDT) Subject: is hash map data structure available in Python? Message-ID: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Hi, I have a situation that I need to search a name in a big list of names in my Python embedded interpreter. I am planning to use hash map for quicker search. How do I create hash map in Python? Can you please guide me to some documentation or tutorial which provides information on creating, editing, searching through hash map in Python? Thanks. From jeffrey at fro.man Thu Mar 27 16:12:47 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 27 Mar 2008 13:12:47 -0700 Subject: Signal problem References: Message-ID: <13unvtvnmvsm609@corp.supernews.com> Fabio Durieux Lopes wrote: > def signalHandler(signum, frame): > terminate = True This creates a new variable named "terminate" inside the signalHandler function's local scope. To adjust the value of a module-level global from inside a function, use the "global" keyword: def signalHandler(signum, frame): global terminate terminate = True Jeffrey From w.a.h.d222 at gmail.com Fri Mar 21 00:57:11 2008 From: w.a.h.d222 at gmail.com (=?windows-1256?B?zebm5sjt?=) Date: Thu, 20 Mar 2008 21:57:11 -0700 (PDT) Subject: sex sex downlond Message-ID: <51a85330-1cfc-470b-9ece-bb115f93b0b7@u69g2000hse.googlegroups.com> sex sex downlond http://www.al-lail.com/vb/showthread.php?goto=newpost&t=4454 From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 20:48:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 01:48:21 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Message-ID: <13t6gf5on1qnhbe@corp.supernews.com> On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote: > On Mar 8, 6:26?pm, Paul Rubin wrote: >> Alasdair writes: >> > What is the best way of finding a ceiling of a quotient of arbitrary >> > sized integers? >> >> ceiling(a/b) = (a+b-1)//b > > I prefer: > > ceiling(a/b) = -(-a)//b > > which also works if a and b are something other than integers (e.g. > rational numbers). Unfortunately it doesn't give the right answer. >>> a, b = 101.0, 10.0 >>> -(-a)//b # should be 11.0 10.0 >>> a, b = -101.0, 10.0 >>> -(-a)//b # should be -10.0 -11.0 Looks like you've confused ceiling() and floor(). (And the ease that these mistakes can happen is why such fundamental functions should be in the standard library, no matter how easy they are to implement.) -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 16:58:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 21:58:29 -0000 Subject: What is a class? References: Message-ID: <13su5s530rnkgfe@corp.supernews.com> On Wed, 05 Mar 2008 10:50:12 -0800, castironpi wrote: > What is a class that is not a module? Er, all of them? I'm curious what classes you think are modules. -- Steven From castironpi at gmail.com Tue Mar 25 14:44:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 11:44:20 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: On Mar 25, 12:01?pm, Robert Bossy wrote: > Hi, > > I'm not sure what you're trying to actually achieve, but it seems that > you want an identificator for classes, not for instances. In this case, > setting the id should be kept out of __init__ since it is an instance > initializer: make id static and thus getid() a classmethod. > Furthermore, if you have several Foo subclasses and subsubclasses, etc. > and still want to use the same identificator scheme, the getid() method > would better be defined once for ever in Foo. I propose you the following: > > > class Foo(object): > ? ? id = 1 > > ? ? def getid(cls): > ? ? ? ? if cls == Foo: return str(cls.id) > ? ? ? ? return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the > parent id and append its own id > ? ? getid = classmethod(getid) > > class FooSon(Foo): > ? ? id = 2 > > class Bar(Foo): > ? ? id = 3 > > class Toto(Bar): > ? ? id = 1 > > # Show me that this works > for cls in [Foo, FooSon, Bar, Toto]: > ? ? inst = cls() > ? ? print '%s id: %s\n ? ?also can getid from an instance: %s\n' % > (cls.__name__, cls.getid(), inst.getid()) > > > One advantage of this approach is that you don't have to redefine the > getid() method for each Foo child and descendent. Unfortunately, the > "cls.__bases__[0]" part makes getid() to work if and only if the first > base class is Foo or a subclass of Foo. You're not using multiple > inheritance, are you? > > RB It is clear there are always two vectors is programmer thoughtspace: class and instance, and that they are orthogonal, and even orthonormal. Every (human-thought native) data structure can be expressed as a sum of two vectors, scalar * unit, scalar * unit in a particular order (cf. Gram-Schmidt), or a tuple. Writing code is simply the specification of scalar and scalar. Clearly the alphabet-space of programs ( symbol* ) contains (improper) the alphabet-space of Python programs, (which) contains (proper) the token-space of Python programs, (which) contains (proper) the grammar- space of Python programs, yet but here we lose thought; do you think in Python? Python ignores some subset of distinctions we make in thought, and we ignore some subset of distinctions Python require (w.c.)s. How do we effectively communicate with it? Order is a non-commutative relation. (a,b) did come from reality, but does not fulfill Rab; conclude (a,b) did not come from reality; and R is a truth relation. Conclude Rab is a scalar. Is a gram a pound? Is it two pounds? Newton's zero-find method finds b given a and Rab. (Expected time to zero pent). Do you think in Newton's method? Are functions scalars? '''In the mid-20th century, some mathematicians decided that writing "g o f" to mean "first apply f, then apply g" was too confusing and decided to change notations. They wrote "xf" for "f(x)" and "xfg" for "g(f(x))". This can be more natural and seem simpler than writing functions on the left in some areas.''' - wikipedia. Does anyone know category theory or pointless topology? My point in asking, is if we can explain in a really easy way using those establishments, to Python how we think, (several symbols, what when), we would like it, assuming it likes us. To effectively communicate with Python, what does the assumption that 'we want something', that 'there's a reward' exclude? Python wants to reward programmers often enough. (Python + Usenet does!) Do we like to be frustrated? What's good for us is good for Python. What frustrates you the most? From kyosohma at gmail.com Wed Mar 26 15:23:47 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 26 Mar 2008 12:23:47 -0700 (PDT) Subject: A question on decorators References: Message-ID: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> On Mar 26, 2:10 pm, Tim Henderson wrote: > Hello > > I am writing an application that has a mysql back end and I have this > idea to simplify my life when accessing the database. The idea is to > wrap the all the functions dealing with a particular row in a > particular in a particular table inside a class. So if you have a > table that looks like this: > > id str1 str2 pickled_data1 pickled_data2 > 0 woeif aposf (bin) (bin) > 1 ofime powe (bin) (bin) > ... > n oiew opiwe (bin) (bin) > > you can access this table like this > > t = Table(id) #to load a pre-entered row > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > when you change a an attribute of the class like this... > t.str1 = 'new value' > > it automatically updates the database backend. > > I have what I just described working. However I want an easier way to > deal with my pickled_data. Right now I am pickling dictionaries and > list types. Now there is one problem with this, let me demonstrate > > t.data.update({'new key':'new value'}) > print t.data > {... 'new key':'new value' ...} > > which makes it appear that the database has been updated as well, but > in fact it hasn't to update the database with this scheme you actually > have to do this. > > t.data.update({'new key':'new value'}) > t.data = t.data > > this is not ideal so I subclassed the built in dict type like this: > > class _my_dict(dict): > > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > self.update_db() > > def __delitem__(self, key): > if self.write_access: > dict.__delitem__(self, key) > self.update_db() > > def __setitem__(self, key, value): > if self.write_access: > dict.__setitem__(self, key, value) > self.update_db() > > def clear(self): > if self.write_access: > dict.clear(self) > self.update_db() > > ... > more methods which are simliar > ... > > def update_db(self): > if self.write_access: > con = get_dbConnection() > cur = con.cursor() > > table = self.experiment.TABLE > row_index_name = self.row_index_name > row_index = self.row_index > column_name = self.column_name > column_value = MySQLdb.escape_string(pickle.dumps(self)) > > q1 = '''UPDATE %(table)s > SET %(column_name)s = '%(column_value)s' > WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() > > cur.execute(q1) > con.close() > > Now while this works, it is a lot of work. What I want to be able to > do is something where I write one decorator function that > automatically updates the database for me. So let us pretend I have > this function. > > let: dec_update_db() be my decorator which updates the dictionary. > > to use this function it seems I would probably still have to subclass > dict like this: > > class _my_dict2(dict): > > @dec_update_db > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > @dec_update_db > def __delitem__(self, key): > dict.__delitem__(self, key) > > @dec_update_db > def __setitem__(self, key, value): > dict.__setitem__(self, key, value) > > @dec_update_db > def clear(self): > dict.clear(self) > > ... and so on ... > > this is also not ideal. because I still have to apply the decorator to > every function which changes the dictionary. > > What I really want is a way to have the decorator applied > automatically every time a method in dict or a sub class is called. I > feel like this must be possible. Has any one here done anything like > this before? > > Thank you for reading my long post, I hope you understand what I am > asking especially since the code in it is not very good. > > cheers > Tim Henderson Why aren't you using SQLAlchemy or SQLObject? I think they would work better than this and give you a lot more flexibility. Besides, you should use sqlite rather than pickle databases. It's especially easy since sqlite is included with Python 2.5. Mike From nkanthikiran at gmail.com Wed Mar 12 07:37:58 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Wed, 12 Mar 2008 04:37:58 -0700 (PDT) Subject: Creating a file with $SIZE References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: I think I am not clear with my question, I am sorry. Here goes the exact requirement. We use dd command in Linux to create a file with of required size. In similar way, on windows I would like to use python to take the size of the file( 50MB, 1GB ) as input from user and create a uncompressed file of the size given by the user. ex: If user input is 50M, script should create 50Mb of blank or empty file Thank you From arnodel at googlemail.com Wed Mar 12 18:55:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 12 Mar 2008 15:55:18 -0700 (PDT) Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> <47D7E9A1.7000403@ncee.net> Message-ID: <1225bf07-ad62-46d3-9e7a-3bf826aac67e@i12g2000prf.googlegroups.com> On Mar 12, 3:38?pm, "Reedick, Andrew" wrote: [...] > Start here > > http://www.mail-archive.com/python-l... at python.org/msg178356.html > and go through the thread. ?There are several ways to solve the problem > and we evaluated the performance and 'pythonicity' of each. ? I used a kind of extended cartesian product function a while ago while writing a parser. If I simplify it down to a simple product function it goes like this: def product(*sequences): i, n = 0, len(sequences) vals = [None]*n iters = map(iter, sequences) while i >= 0: if i == n: yield tuple(vals) i -= 1 else: for vals[i] in iters[i]: i += 1 break else: iters[i] = iter(sequences[i]) i -= 1 It's neither recursive nor a hack, I haven't tried to measure it against other approaches (obviously it wouldn't beat the eval(...) hack). I haven't optimised it for readability (by others) either :) -- Arnaud From blwatson at gmail.com Sun Mar 30 00:48:42 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Sat, 29 Mar 2008 21:48:42 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> <75c10b67-c971-4db4-be13-26cafd24e9d2@d4g2000prg.googlegroups.com> Message-ID: Rock and roll baby!!! Thanks so much. It took some doing, but many thanks!!!! From software at ginstrom.com Sun Mar 30 11:40:07 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 31 Mar 2008 00:40:07 +0900 Subject: Build complete, now I just need to "install" it... In-Reply-To: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: <084501c8927c$54cfbe80$0203a8c0@MOUSE> > On Behalf Of axl > Since I don't have access to MSVS 2003 I need to rebuild > Python using MSVS 2008 in order for the binaries to go along. Another option is to compile your extensions with gcc, and specify that it link to MSVCR71.dll as the C runtime. For MinGW, it's sufficient to edit the specs (e.g. in C:\MinGW\lib\gcc\mingw32\3.4.2) like so: *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 And tell distutils to use mingw, by putting this in lib/distutils/distutils.cfg: [build] compiler=mingw32 [build_ext] compiler=mingw32 Regards, Ryan Ginstrom From Dominique.Holzwarth at ch.delarue.com Thu Mar 27 08:28:25 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 27 Mar 2008 12:28:25 +0000 Subject: Pickle: several class instance objects in one file? Message-ID: <5213E58D85BC414998FA553C701E386C0EDD00F451@SGBD012511.dlrmail.ad.delarue.com> Hi everyone I've never used the module 'pickle' so far, thus I've got some questions about how to use it: Lets say I have instances of class A and class B: a = A() b = B() Is it possible to pickle both of these instances to the same pkl-file or will that have any bad impact for unpickle (i.e. the instance are 'mixed' or 'destroyed')? Or should I rather use a seperate file for every class instance I want to pickle? Another very basic question about pickling class instances: To store the value of attributes of an instance is it enough for the pickling-algorithm to use the __dict__ or do I have to implement the _setstate_ and _getstate_ function? I didn't really get the meaning of those while reading the python user manual... Thanks in advance Dominique From giles.thomas at resolversystems.com Tue Mar 4 13:28:42 2008 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Tue, 4 Mar 2008 10:28:42 -0800 (PST) Subject: ANN: Resolver One 1.0.1 Message-ID: <5be62ef4-eb68-4925-a08d-7ef151d7cb54@s12g2000prg.googlegroups.com> Hi! We're delighted to announce version 1.0.1 of Resolver One, a Windows spreadsheet/IDE mashup that can be programmed in IronPython. As you enter formulae on the grid, it writes the equivalent IronPython program for you. As you add your own code, the grid is updated. This allows you to build applications that are much more complex but better-structured than a traditional spreadsheet, much more quickly than you could if you were using a regular programming language. You can then export the code and re-use it elsewhere in your own programs. It's primarily targetted at heavy users of number-crunching software, such as financial firms and the biotech industry, but we use it internally for all kinds of tasks, so we think any Python developer will be able to do fun stuff with it :-) This is primarily a performance enhancement and bugfix release, but has a couple of features correcting the more egregious missing features in version 1.0. We've put up a full change list, but the highlights are: * Many memory usage and performance fixes, in particular while importing Excel-format spreadsheets. * Updated to IronPython 1.1.1 (fixes socket bugs) * Added UI to set the background color. * Fixed defect 367 - Looking up cells by header row/col is slow * Fixed defect 370 - Cut and Copy part of the text in a cell is not handled correctly If you want to download the non-commercial version of the software, or to buy the commercial version, you can download it from our website (free registration required): Regards, Giles Giles Thomas MD & CTO, Resolver Systems Ltd. giles.thomas at resolversystems.com +44 (0) 20 7253 6372 Try out Resolver One! (Free registration required) 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From gagsl-py2 at yahoo.com.ar Sun Mar 30 18:48:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 19:48:16 -0300 Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 16:46:00 -0300, escribi?: > using python and wpython. Soory, I don't know what wpython is > when using run module or python shell on the run menu in the GUI i get > "socket error, connection refused". > > it worked before, what si wrong now? Try to detect what changed on your system between "before" and "now". > and i cant find where to start the shell directly. think i had an exe > before but cant seem to find it now. python.exe? > c: > cd \ > dir /s python.exe -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Mar 7 04:14:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 07:14:35 -0200 Subject: help on file storage for split multi part download References: Message-ID: En Fri, 07 Mar 2008 04:16:42 -0200, escribi?: > On Mar 7, 1:38 am, "Gabriel Genellina" wrote: >> En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: >> >> > storage class which can write the file splits that are currently being >> > downloaded to the disk. this is exactly what other download >> > accelerators do, i guess. >> >> Uh, unless I misundersand you, a standard file object is enough. First >> create a file with the required size (open(...,'wb'), seek(n-1), >> write(chr(0))). For each downloaded chunk you have to know its position >> in >> the file; then just seek() and write() it. > > BUT the thing thats going in my mind is thread safety. i plan to start > each part of the file download in a different thread. and then when > each thread had downloaded more than 100kb (or eof or boundary > reached) write the buffer to the disk. can this be achieved using > mutex ? i have never shared objects between threads. Use a different (single) thread to write the file; the others put write requests on a Queue.queue object, and the writer just gets the requests and processes them. > is there a way to write this without using threads at all ??? Using asyncore, and perhaps the Twisted framework. -- Gabriel Genellina From michael.wieher at gmail.com Wed Mar 26 09:43:08 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 26 Mar 2008 08:43:08 -0500 Subject: memory allocation for Python list In-Reply-To: <96e81eb0-9d27-4cfd-82da-7fcc9b3dae25@m3g2000hsc.googlegroups.com> References: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> <96e81eb0-9d27-4cfd-82da-7fcc9b3dae25@m3g2000hsc.googlegroups.com> Message-ID: Just write it in C and compile it into a .so/pyd =) 2008/3/26, bearophileHUGS at lycos.com : > > dmitrey: > > > As I have mentioned, I don't know final length of the list, but > > usually I know a good approximation, for example 400. > > > There is no reserve()-like method, but this is a fast enough operation > you can do at the beginning: > > l = [None] * 400 > > It may speed up your code, but the final resizing may kill your > performance anyway. You can try it. Just using Psyco is probably > better. > > Bye, > bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From geert at nznl.com Tue Mar 18 13:56:10 2008 From: geert at nznl.com (geert) Date: Tue, 18 Mar 2008 10:56:10 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> Message-ID: <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> On Mar 14, 1:15?pm, martin.lal... at gmail.com wrote: > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html Just wanted to let you know that I've solved my problem. The solution is to compile mysql using MACOSX_DEPLOYMENT_TARGET=10.5 \ CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ ./configure --disable-dependency-tracking --enable-thread-safe-client --prefix=/usr/local/mysql You then go this way to get it running on your machine: http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ Then reinstall MySQLdb. Magic! Geert From gagsl-py2 at yahoo.com.ar Fri Mar 7 04:40:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 07:40:22 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> <5aee6834-e612-48d6-aea2-602df2777c82@n36g2000hse.googlegroups.com> <4e8c4617-af5e-416b-aeba-f58023026340@8g2000hse.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 23:46:43 -0200, escribi?: > oss.message is a abstraction class that writes the method name into a > string, then sends it to OSS... outgoingserver or serverside. > > Now that I'm writing it, and this is important, -to- the -newsgroup-, > I realize you could do it with a simple wrapper... include the > function name in parameters and call the pickler and send. > > OSS then looks like this: > > def something_happens( *ar ): > self.user_act( something_about( *ar ) ) > > So the message.out() instance pickles ( 'user_act', ar ) and sends > it. Then iss.incoming receives it, unpickles that string, gets > 'user_act' from self, and invokes. > > The cool part is the declaration of user_act= message.out(), which > uses a metaclass to assign its own name, and returns a function which > includes the object in its signature. Cool. > > Yes it's working and a little slack. However-: this is the cool > part. I'd like messages to know which instance they came from, and > perform the sending & receiving encapsulated on their own--- not to > subclass class SS( Sending ): with various behaviors: that is, to > assign them as class attributes rather than superclasses. You may look at the SimpleXMLRPCServer class and see how it implements introspection. It's rather easy (and doesn't require metaclasses nor decorators nor any other fancy stuff; I think it works the same since Python 2.1). Apparently you're doing a similar thing, but using pickles instead of xmlrpc. -- Gabriel Genellina From pofuk at email.t-com.hr Tue Mar 4 13:36:03 2008 From: pofuk at email.t-com.hr (SMALLp) Date: Tue, 04 Mar 2008 19:36:03 +0100 Subject: Run Python app at startup In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Sun, 02 Mar 2008 19:37:35 -0200, SMALLp escribi?: > >> Hy. >> I create simple application. Yust an windows and "compile" it with >> py2exe. I add registry value >> reg add >> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v >> MyApp /t REG_SZ /d C:\myapp.exe /f' >> >> And it wont start. When i use console instead od window in py2exe i get >> console opend but it closes. > > I'd check in this order: > > python prog.py > Then, use console=... in setup.py, generate prog.exe > Open a cmd window and execute prog.exe (from the dist directory) > Repeat using window=... in setup.py > > That whole sequence works fine using on my WinXP SP2 + Python 2.5.1 + > wxPython 2.8.7.1 > Program works fine. When i run it it works. Problem is how to make this aplication start at windows startup. It opens and it closes in my case. From pradiprai at gmail.com Fri Mar 14 09:30:35 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Fri, 14 Mar 2008 19:00:35 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From sigzero at gmail.com Sun Mar 16 15:43:14 2008 From: sigzero at gmail.com (Robert Hicks) Date: Sun, 16 Mar 2008 12:43:14 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> Message-ID: On Mar 16, 12:38?pm, lbonaf... at yahoo.com wrote: > On Mar 16, 6:10 am, Bruce Eckel wrote: > > > I think a lot of people have been caught up in the idea that we need > > to commercialize Python, and ride some kind of wave of publicity the > > way that Java and C# and Rails seem to have done. > > This coming from someone who caught the Java wave and rode it for a > decade. Doesn't that make him better to see the problems with it? Robert From gagsl-py2 at yahoo.com.ar Sun Mar 16 16:40:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 18:40:42 -0200 Subject: Using threads in python is safe ? References: <48224a820803150657i74c3a7bdj2e05b1d02ef60b87@mail.gmail.com> Message-ID: En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade escribi?: > I want to use therads in my application. Going through the docs , I read > about GIL. > Now I am confused whether using threads in python is safe or not. > > One thing I know that if I am accessing global variables in two or more > threads I need to synchronize them > using locking or such mechanism so that only one thread access them at a > time. Yes, altough some operations are known to be atomic so you don't need a lock in that cases. I think there is a list in the wiki somewhere http://wiki.python.org/moin or perhaps at the effbot's site http://www.effbot.org > 1. In order to support multi-threaded Python programs, there's a global > lock that must be held > by the current thread before it can safely access Python objects. > Does this lock need to be held by python application script expliciltly > before accessing any python object or > interpreter takes acre of it ? No, the interpreter takes care of it. The GIL is a concern for those writing extensions using the Python API. > 2. Does multithreaded python script need to held lock before calling any > blocking I/O call? > Or one should not worry about GIL while using python threads if job to be > processed by thread does not call > any global variables and thread unsafe Python/C extension ? Python code should not worry about the GIL. The problem would be, a callback written in Python for a not-thread-aware extension that had released the GIL. -- Gabriel Genellina From jr9445 at ATT.COM Thu Mar 20 16:23:06 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 20 Mar 2008 15:23:06 -0500 Subject: What Programming Languages Should You Learn Next? In-Reply-To: References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com><64bugqF2anottU1@mid.uni-berlin.de><7xve3j15ya.fsf@ruckus.brouhaha.com><87fxunumqx.fsf@physik.rwth-aachen.de><7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Donn Cave > Sent: Thursday, March 20, 2008 3:39 PM > To: python-list at python.org > Subject: Re: What Programming Languages Should You Learn Next? > > > Worth repeating. > > One of the perhaps surprising consequences, Haskell code can > be very easy to modify. I've been fooling around with computer > programs for a couple decades, and I'm just getting used to the > idea that I can casually rewrite Haskell code and get the compiler > to find what I missed. I have come to feel that the indiscipline > of dynamic typing in languages like Python leads to an intuitively > surprising rigidity. Ten years ago I would cheerfully accept this, > given the meager and clumsy support for static typing in languages > like C++, but today, it makes me appreciate Haskell's potential > for complex projects. > Haskell does look interesting (especially in light of that one summer job way back when doing a _lot_ of Lotus-123 spreadsheet programming.) There's a Haskell wiki: http://www.haskell.org/ Quicksort in Haskell versus C is amazing: http://www.haskell.org/haskellwiki/Introduction#What.27s_good_about_func tional_programming.3F Quicksort in Python inspired by Haskell's quicksort: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473 ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From fakeaddress at nowhere.org Fri Mar 14 07:17:50 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 04:17:50 -0700 Subject: escape string to store in a database? In-Reply-To: <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> <03408165-6c2d-4ba9-979e-872657f5bf68@n36g2000hse.googlegroups.com> Message-ID: andrei.avk at gmail.com wrote: > how would this work with UPDATE > command? I get this error: > > cmd = "UPDATE items SET content = ? WHERE id=%d" % id > > self.cursor.execute(cmd, content) > pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings > supplied. The c > rrent statement uses 1, and there are 0 supplied. The error message implies that 'content' is an empty sequence. Even when the SQL takes exactly one parameter, the second argument is a sequence containing the parameter. You can use a one-element list, written [someparam], or a one-tuple (someparam,). > Sqlite site doesn't give any details on using parameter bindings in > UPDATE command, I'm > going to look around some more.. To make effective use of Python's Sqlite3 module, I need three references: the Python DB API v2 spec, the Sqlite3 module's doc, and the Sqlite database doc. http://www.python.org/dev/peps/pep-0249/ http://docs.python.org/lib/module-sqlite3.html http://www.sqlite.org/docs.html With all three, parameter binding is still under-specified, but only a little. Those new to the relational model and to SQL will need sources on those as well. On the model, I think the foundational paper has held up well over the decades: Codd, E.F. "A Relational Model of Data for Large Shared Data Banks". /Communications of the ACM/ Volume 13 number 6, June 1970; pages 377?387. It is currently available on line at: http://www.seas.upenn.edu/~zives/03f/cis550/codd.pdf Anyone have a particularly good and easily accessible source to recommend on SQL? -- --Bryan From timr at probo.com Tue Mar 11 03:19:29 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 11 Mar 2008 07:19:29 GMT Subject: tcp client socket bind problem References: <42925034-6cf7-40a7-b079-8f3bf978fea2@n36g2000hse.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > >On Mar 10, 9:40?am, Marc Christiansen wrote: >> nata... at gmail.com wrote: >> > I have a linux box with multiple ip addresses. I want to make my >> > python client connect from one of the ip addresses. Here is my code, >> > no matter what valid information I put in the bind it always comes >> > from the default ip address on the server. Am I doing something wrong? >... > >help string: >Bind the socket to a local address. For IP sockets, the address is a >pair (host, port); the host must refer to the local host. > >docs: >Bind the socket to address. > >Wikipedia: >Before a socket may accept incoming connections, it must be bound. > >PHP.net: >Binds the name given in address to the socket described by socket . >This has to be done before a connection is be established using >socket_connect() or socket_listen(). >This function must be used on the socket before socket_connect(). That's all true. So what was your point? How does this help the original poster? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From __peter__ at web.de Sat Mar 8 13:36:48 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Mar 2008 19:36:48 +0100 Subject: del class with recursive list References: Message-ID: duccio wrote: > Will someone have time to tell me why this code don't work as I expect? > And what should I do to make the "del n" delete all the lower nodes? > Thanks! > > class Node: > def __init__(self): > self.childs=[] > def appendNode(self, n): > self.childs.append(n) > def __del__(self): > print 'del', id(self) > > n = Node() > for i in range(5): > n.appendNode(Node()) > for nodes in n.childs: > nodes.appendNode(Node()) # you forgot a reference to a child node and its child: del nodes > del n > > print '--------end--------' > > > gives this: > > > del 10965280 > del 10965440 > del 10965640 > del 10965400 > del 10965600 > del 10965360 > del 10965560 > del 10965320 > del 10965520 > --------end-------- > del 10965480 > del 10965680 Peter From mblume at freesurf.ch Sun Mar 16 13:45:19 2008 From: mblume at freesurf.ch (Martin Blume) Date: Sun, 16 Mar 2008 18:45:19 +0100 Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> Message-ID: <47dd5caf$0$9029$5402220f@news.sunrise.ch> "sturlamolden" schrieb > > > This seems to imply that the Mac, although running now > > on Intel processors, is still big-endian. > > Or maybe the struct module thinks big-endian is native > to all Macs? It could be a bug. > Dunno, I'm on thin ice here. Never used a Mac. Maybe the underlying C library thinks that all Macs are big-endian? I don't think this qualifies as a bug, but I am astonished that the struct module does not tell you whether you are big endian, you have to find out yourself with struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] Anyway, when handling binary data across machines, I think it is proper to explicitly specify the endian-ness and to do sanity-checking of the results. Regards Martin From S.Mientki-nospam at mailbox.kun.nl Tue Mar 11 06:43:45 2008 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 11 Mar 2008 11:43:45 +0100 Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) In-Reply-To: References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: <99cd$47d66262$83aef404$29936@news1.tudelft.nl> Gilles Ganault wrote: > On Mon, 10 Mar 2008 11:27:06 -0400, "Malcolm Greene" > wrote: >> Any suggestions on an alternative Python client-side GUI library (pyQT >> ?) or tips on where I can find out more about wxPython/wxWidget >> problems? > > One thing that bothers me is that it seems like there's no ecosystem > around it, so the only widgets available are those that come from > wxWidgets proper. > > For instance, I find the grid object a bit poor-featured compared to > what's available for VB6, .Net, or Delphi, but I didn't find > alternatives. Funny, compared to Delphi-7, I found the grid in wxPython much richer ;-) Very easy to add own in place editors, easy add checkboxes, colorpickers etc into the grid. cheers, Stef From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:07:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:07:42 -0700 (PDT) Subject: Returning values from function to Python shell/IPython References: <91fbb488-4ada-4fea-864b-c5c33c5b4386@e39g2000hsf.googlegroups.com> Message-ID: <95556936-ede6-46a7-999c-56111d6287dc@e60g2000hsh.googlegroups.com> On 9 mar, 20:51, castiro... at gmail.com wrote: > While you're at it, can you call up prior source, and edit it? ?BASIC > had line numbers: > > 10 def f( a ): > 20 ? return a+ 1 > > >>> 15 print( a ) Not so easy. The current CPython implementation assumes that once an object is allocated, it is never moved to another memory location. If doing that were allowed, all the object references had to be updated, or another level of indirection would be required, and neither alternative looks very promising. The reload function tries to reuse the module object itself, but its contents are destroyed and recreated. Maybe for some simple changes like the above the *same* function object could be re-utilized, but not in the general case. -- Gabriel Genellina From danb_83 at yahoo.com Thu Mar 13 21:32:47 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 13 Mar 2008 18:32:47 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: On Mar 13, 7:38 pm, Alan Isaac wrote: > Mark Dickinson wrote: > > Sorting tuples, where the second item in the tuple should > > have the opposite ordering to the first is going to be > > a bit of a pain. Or even worse, where the ordering of the > > second item depends on the value of the first item in the > > tuple. > > This is like some examples where I had used cmp, > > but if I understand correctly I think it is not a problem. > > > For example, suppose that (for whatever contrived reason) > > you're representing integers in (sign, magnitude) format > > by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for > > negative) and i is a string representing the absolute > > value of the integer. So > > Does this do it? :: > > key= lambda x: (-x[1],int(x2)) > > Here I am depending on the lexicographic sorting of tuples. > Without that there would be real trouble. Even assuming you meant (-x[0], int(x[1])), that sorts negative numbers in the wrong order. You want key = lambda x: (-1 if x[0] else 1) * int(x[1]) From castironpi at gmail.com Fri Mar 21 10:07:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 07:07:33 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> <63ns5vF1fcb15U1@mid.uni-berlin.de> <9a0f1e31-7e3a-47ad-a5cf-063829ac7f85@s37g2000prg.googlegroups.com> Message-ID: <2452a0fc-ce28-4f3f-9656-6cd9e6389048@o22g2000hsh.googlegroups.com> On Mar 11, 2:30?pm, Lie wrote: > On Mar 12, 12:00?am, "Diez B. Roggisch" wrote: > > > Actually, the latter is even less cluttered, misses a raise - if pure number > > of literals is your metric, that is. > > You don't just compare by the calling code, you've got to compare also > by the surrounding codes. The calling codes in SE might be a little > bit messy, but it worths by making the code surrounding it more clean > and structured. And anyway, if you used Context Object callback, they > will be as messy as each other. > > > You didn't understand my example. If there is a handler registered, it will > > be invoked. If not, nothing will be raised. The exact same amount of > > state-keeping and lookups needs to be done by the SE-implementation. > > I do understand your example. And even if I misunderstood you about > passing context object, the same problem still exists in context > object based solution, i.e. functions can't make the called function > break automatically, it must be 'break' manually or the program will > go astray (break ==> return, sorry I confused it with break for > loops). And if you used InterruptException to break, it doesn't play > well with multiple SoftExceptions. Are you interested in yielding an object? In situ, a routine has extra information it wants to return to the caller. Can you protocol a number of yields? Discard x for x in operation()[:3]; x= operation(). Or, x= operation()[3], and go back and look operation() [1], which is cached. From puneetbrar at gmail.com Mon Mar 24 05:48:50 2008 From: puneetbrar at gmail.com (puneetbrar) Date: Mon, 24 Mar 2008 09:48:50 -0000 Subject: problems with harvestman on ubuntu 7.10 gusty gibbon Message-ID: Hi there I just saw that program on the awards and wanted to use it as i installed it on ubuntu gusty gibbon it worked fine without errors and when i run it i get the following errors File "/usr/bin/harvestman", line 364, in spider.run_projects() File "/usr/bin/harvestman", line 283, in run_projects self.register_common_objects() File "/usr/bin/harvestman", line 135, in register_common_objects conn = connector.HarvestManNetworkConnector() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/connector.py", line 201, in _init_ self.__configure() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/connector.py", line 326, in __configure self.__configure_protocols() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/connector.py", line 449, in __configure_protocols cookiehandler) File "/usr/lib/python2.5/urllib2.py", line 467, in build_opener opener.add_handler(h) File "/usr/lib/python2.5/urllib2.py", line 303, in add_handler type(handler)) TypeError: expected BaseHandler instance, got regards puneet brar From kyosohma at gmail.com Wed Mar 19 10:57:34 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 19 Mar 2008 07:57:34 -0700 (PDT) Subject: Improving datetime References: Message-ID: On Mar 19, 9:12 am, "Nicholas F. Fabry" wrote: > This is a query for information as to how to proceed. I am not a > professional programmer, but I use Python a great deal to help me in > my main job, which involves designing schedules for a global airline. > As such, I use datetime (and dateutil) extensively, and after much > use, I have come to some conclusions about their utility, and how to > improve them. Some of these changes are quite minor and would result > in a large increase in utility (low hanging fruit), while some changes > are major, and would result in less obvious benefits - but these > changes would increase the 'Python Zen' of them. > > So - where should I propose these changes? Here? python-dev? Should > I write up a full PEP or should I just give a more informal outline > with code samples? I would volunteer to help maintain/improve > datetime, but I don't speak C at all, unfortunately, and datetime > appears to be in C. > > In addition, I have little contact with the Python community - I work > somewhat 'solo' when it comes to my programming projects. So, are > there other people out there who use datetime? Dateutil? What do you > find the deficits/benefits of these modules to be? > > Thank you for your thoughts.... > > Nick Fabry I think you need to do this sort of thing on python-dev. I'm not sure how the PEP process works though. If you give your thoughts in a PEP- like format, you'd probably be taken more seriously though. Mike From gbrunick at andrew.cmu.edu Wed Mar 5 12:59:19 2008 From: gbrunick at andrew.cmu.edu (Gerard Brunick) Date: Wed, 05 Mar 2008 12:59:19 -0500 Subject: Short confusing example with unicode, print, and __str__ Message-ID: <47CEDF77.5050501@andrew.cmu.edu> I really don't understand the following behavior: >>> class C(object): ... def __init__(self, s): self.s = s ... def __str__(self): return self.s ... >>> cafe = unicode("Caf\xe9", "Latin-1") >>> c = C(cafe) >>> print "Print using c.s:", c.s Print using c.s: Caf? >>> print "Print using just c:", c Print using just c: Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) >>> str(c) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Why would "print c.s" work but the other two cases throw an exception? Any help understanding this would be greatly appreciated. Thanks in advance, Gerard From mcepl at redhat.com Sun Mar 2 03:16:28 2008 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 02 Mar 2008 09:16:28 +0100 Subject: sqlite3 adaptors mystery References: Message-ID: On 2008-03-01, 23:41 GMT, Mel wrote: > There's nothing much wrong. cur.fetchall is returning a list > of all the selected rows, and each row is a tuple of fields. > Each tuple is being converted for display by repr, so the > strings are shown as unicode, which is what they are > internally. Change the print to > > for (field,) in cur.fetchall(): > print field > > and you'll see your plain-text strings. Thanks for your help, but plain-text strings is not what I wanted. The boolean variables was what I was after. See this modified version of the script: #!/usr/bin/python import sqlite3 def adapt_boolean(bol): if bol: return "True" else: return "False" def convert_boolean(bolStr): if str(bolStr) == "True": return bool(True) elif str(bolStr) == "False": return bool(False) else: raise ValueError, "Unknown value of bool attribute '%s'" % bolStr sqlite3.register_adapter(bool,adapt_boolean) sqlite3.register_converter("boolean",convert_boolean) db = sqlite3.connect(":memory:") cur=db.cursor() cur.execute("create table test(p boolean)") p=False cur.execute("insert into test(p) values (?)", (p,)) p=True cur.execute("insert into test(p) values (?)", (p,)) cur.execute("select p from test") for (field,) in cur.fetchall(): print field,type(field) The output here is: [matej at viklef dumpBugzilla]$ python testAdaptors.py False True [matej at viklef dumpBugzilla]$ I thought that converter is there for just exactly this -- that I would get back bool values not strings. Sorry for not being clear in the first run. Matej From sturlamolden at yahoo.no Sat Mar 15 17:26:05 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 14:26:05 -0700 (PDT) Subject: Python Generators References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: <87f4929c-4f4a-4522-a4ed-c40acfbfe69c@e25g2000prg.googlegroups.com> On 15 Mar, 21:35, mpc wrote: > generator embedded in the argument only once. Can anyone explain while > the generator will not re-initiate, and suggest a simple fix? I am not sure what you are trying to do, but it seems a bit confused. >>> def concat(seq): for s in seq: yield s >>> seq = xrange(3) >>> for n in xrange(5): h = concat(s for s in seq) for i in h: print i,n 0 0 1 0 2 0 0 1 1 1 2 1 0 2 1 2 2 2 0 3 1 3 2 3 0 4 1 4 2 4 Generators work they way they should. Even when one is used as argument for another. From kyosohma at gmail.com Mon Mar 31 16:52:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 13:52:08 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Message-ID: <41b598ef-c422-417f-9a77-b48eff8e6334@s37g2000prg.googlegroups.com> On Mar 31, 12:24 pm, Amit Gupta wrote: > Hi > > I am looking for a some tool that can convert python scripts to > executable on Linux. > > I found freeeze.py as the only option so far. Couple of queries on > freeze: > > 1. Have anyone used the freeze utility and any experiences to share > from that? > 2. Is there any enterprise-level exe-builder for python on linux > (ActiveState has nothing)? > > Any other related commets are also welcome. > > Thanks > Amit What about creating a setup.py and using the distutils command to build rpms or tarballs? http://docs.python.org/dist/built-dist.html Mike From mblume at freesurf.ch Sun Mar 16 13:23:41 2008 From: mblume at freesurf.ch (Martin Blume) Date: Sun, 16 Mar 2008 18:23:41 +0100 Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> Message-ID: <47dd579d$0$9035$5402220f@news.sunrise.ch> "jasonwiener" schrieb > > I am having a VERY odd problem with unpacking right now. > I'm reading data from a binary file and then using a very > simple struct.unpack to get a long. Works fine on my MacBook, > but when I push it to a Linux box,it acts differently and > ends up pewking. > [...] > > the data looks to be the same, but the unpacking seems to > treat it differently. > Probably little-endian vs. big-endian issue: >>> s '\x1e\xc6\xf3\xb4' >>> struct.unpack('>> struct.unpack('>I', s) (516354996L,) See help(struct) for further information. This seems to imply that the Mac, although running now on Intel processors, is still big-endian. HTH Martin From nanjundi at gmail.com Mon Mar 3 22:12:25 2008 From: nanjundi at gmail.com (Nanjundi) Date: Mon, 3 Mar 2008 19:12:25 -0800 (PST) Subject: _struct in Python 2.5.2 References: Message-ID: <07928222-0436-479f-a1ec-0741f3522500@m34g2000hsc.googlegroups.com> On Feb 24, 10:39 am, Olaf Schwarz wrote: > Hi, > > I am trying to run this applicationhttp://svn.navi.cx/misc/trunk/python/bemused/ > on uNSLUng Linux 6.10 using the optware python packages. > > As I obtained segmentation faults using Python 2.4, I have upgraded to > 2.5.2. Now the execution terminates a lot earlier with this error > message: > > File "/usr/local/bemused_mpd/bemused-mpd.py", line 33, in > import bemused > File "/usr/local/bemused_mpd/bemused.py", line 27, in > import bluetooth, syslog > File "/opt/lib/python2.5/site-packages/bluetooth.py", line 2, in > > import struct > File "/opt/lib/python2.5/struct.py", line 30, in > from _struct import Struct, error > ImportError: No module named _struct > > I found out that there has been a file named _struct.so in 2.5.1 but > it has disappeared in 2.5.2. With no package available for downgrading > to 2.5.1 and no idea how to resolve this I am stuck at this point. > > Any help appreciated. > > Thank you > Olaf Hi Olaf, If you are still stuck, run ./configure make make install if you skip the command make, then the required files (lib/python2.5/lib-dynload/_struct.so) doesn't get created. Get the latest 2.5.2 rpm from python.org, it works. Good luck. -N From castironpi at gmail.com Sun Mar 9 20:37:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 17:37:51 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> <63j4ebF25g6okU1@mid.uni-berlin.de> Message-ID: On Mar 9, 4:51?pm, "Diez B. Roggisch" wrote: > > Perhaps similar technique the compiler uses to determine whether a > > function is a normal function or a generator function? Positive > > forward lookup for any soft exceptions, which would then activate > > matching soft exceptions inside the code? > > What would work is most probably to register soft-exception-handlers > when encountering them at runtime, thus making raising-code aware of > them and execute it only if there are one (or several) present. > > [HO snip] Mr. Roggisch, I just said that. You can unplonk me now. From http Sat Mar 8 18:26:35 2008 From: http (Paul Rubin) Date: 08 Mar 2008 15:26:35 -0800 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: <7xhcfg94r8.fsf@ruckus.brouhaha.com> Alasdair writes: > What is the best way of finding a ceiling of a quotient of arbitrary sized > integers? ceiling(a/b) = (a+b-1)//b From roy at panix.com Sat Mar 1 09:29:01 2008 From: roy at panix.com (Roy Smith) Date: Sat, 01 Mar 2008 09:29:01 -0500 Subject: Problems building 2.5.1 on AIX Message-ID: I've got an AIX-5.2 box that I'm trying to build Python 2.5.1 on. Configure dies pretty much immediately: hasty:Python-2.5.1$ CC=/usr/vacpp/bin/cc_r ./configure --without-gcc checking MACHDEP... aix5 checking EXTRAPLATDIR... checking for --without-gcc... yes checking for gcc... cc checking for C compiler default output file name... configure: error: C compiler cannot create executables See `config.log' for more details. I get the same result with or without the --without-cgg. There's nothing obvious in config.log (not that I can ever make much sense out of the gibberish configure generates). Any ideas? From tmp1 at viltersten.com Fri Mar 7 10:56:45 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 16:56:45 +0100 Subject: SV: Quit-command not quiting In-Reply-To: References: <63d2efF271u6hU1@mid.individual.net> Message-ID: <63d5v1F23vm9fU1@mid.individual.net> >> The window itself vanishes if i click the >> cross in the upper-right corner but pressing >> the quit-button only makes it "pressed". >> Then, the program freezes. > > How did you run it? From inside IDLE? IDLE itself is written > using Tk, and I think that your mainloop interferes with the > one inside it. If you run your program from the command line > it should work fine. I press F5 while in the editor window. Is there a way to run the program without going to the console window? Perhaps i'm just making things unneccesarily complicated and Python IS supposed to be run from console window? >> from Tkinter import * >> class Demo (Frame): >> def __init__ (self, master = None): >> Frame.__init__ (self, master) >> self.grid () >> self.doLayout () >> def doLayout (self): >> self.quitButton = Button ( >> self, >> text = "Quit", >> command = self.quit) >> self.quitButton.grid () >> >> d = Demo () >> d.master.title ("the coolest demo ever") >> d.mainloop () > > There is only one thing I hate more than spaces after a > parens: spaces before it :) > Please read PEP8, about the suggested style for writting > Python code. http://www.python.org/dev/peps/pep-0008/ I've got no issues one way or the other. Most likely i'll forget from time to time but other than that, i'll try to keep it in mind. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:36:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:36:05 -0300 Subject: Is this a good time to start learning python? References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: En Mon, 31 Mar 2008 13:40:40 -0300, Rui Maciel escribi?: > Recently I woke up inclined to take up the task of learning another > programming language. I've already dipped my toes in Perl (I've read > online > tutorials and wrote a couple of irrelevant pet projects) but, as the > computers at my workplace only sport the python interpreter, it probably > means that learning python will end up serving me better, at least in the > short run. Plus, you know how Perl goes. >So far the decision seems to be a no brainer. Yet, Python 3000 will > arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put > it > in other words, I fear that I will be wasting my time. Don't be scared by the "backwards incompatible" tag - it's the way to get rid of nasty things that could not be dropped otherwise. The basics of Python will continue to be the same, it's not a new, different language; learning Python 2.X isn't a waste of time. Python 3 won't be in widespread use until some (long?) time, and some people won't ever consider it until Python 3.1 arrives; so Python 2.X will continue being used for a long time. -- Gabriel Genellina From pscott at uwc.ac.za Mon Mar 31 07:13:37 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Mon, 31 Mar 2008 13:13:37 +0200 Subject: Beginner advice In-Reply-To: <10dc13c3-df5a-42fc-bca5-318f890feb66@i29g2000prf.googlegroups.com> References: <65bfk7F2esfc1U1@mid.uni-berlin.de> <10dc13c3-df5a-42fc-bca5-318f890feb66@i29g2000prf.googlegroups.com> Message-ID: <1206962017.6828.55.camel@paul-laptop> On Mon, 2008-03-31 at 04:02 -0700, Graham Ashton wrote: > pyGTK is great. I used it quite heavily a year or so ago. GTK is a > nice tool kit from the user's perspective too; you can make some > rather attractive and usable applications with it, and the GUI builder > is a boon. Obviously it integrates slightly better into it's native > platform than it does Mac/Windows, but if you're targetting Ubuntu > users then it's a great choice. OK, this is almost exactly what I needed. All that I really want to know is can I do this in a really easy, comfortable tool like GTK and get away with it without someone 3 months down the line saying something like: "Dude, what were you *thinking* using deprecated stuff like that?" Sorry, but I had to ask, and I am sure that I will ask a lot more questions as things move along. I really appreciate all the feedback so far! It is often quite difficult sifting through all the years worth of blogs, docs and other resources when starting on something new like this, so bear with me, and I will try and make a more meaningful contribution back to Python as soon as I can! --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From castironpi at gmail.com Sun Mar 30 02:22:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 23:22:39 -0700 (PDT) Subject: Where can I find : References: <13uu56hn1vdqb9d@corp.supernews.com> Message-ID: <768026ee-b9f1-4445-bd02-088a2f725a9d@b64g2000hsa.googlegroups.com> On Mar 29, 11:19?pm, Dennis Lee Bieber wrote: > On Sat, 29 Mar 2008 20:15:59 -0700 (PDT), pythonnubie > declaimed the following in comp.lang.python: > > > Hi ?All : > > Does anyone know where I ?can find ?either a book or a website ?that > > explains ?beginning ?python ?by actually ?building a ?project ?line by > > line and explaining ?it indepth . I ?am primarily interested in > > understading ?flowcontrol as well ?as syntax . > > ? ? ? ? Flow control, if I'm not misinterpreting your usage, is something > that most common language books will not really cover -- that falls into > the realms of software engineering... Or, at the simplest, structured > design/programming (even if a language is OO, when one gets down to the > actual logic of methods, one is back into structured programming). > > ? ? ? ? Syntax is covered in the Python language reference manual, and > Python has a very simple vocabulary to learn. > > ? ? ? ? The two are disjoint concepts. Structured design applies to any > language, one just has to map the constructs of the language (and since > Python lacks a native GOTO, this becomes even simpler). That's weird. I feel like I could go on about an introductory program for days and days, la. I usually start (both times) with interpreted vs. compiled. It's a layer of abstraction. But it's very weird; the layers can't tell either of each other apart. I can hand you the machine instructions, the names of circuitry, that run Line 1 to Line 9 one time, but you can't tell the difference between the code and the data. Some of it lingers in post-perceptive operations: the memory system, for the record. Some lingers long times. So far it equates to different Pythons produce different Pythons, however, though, so I'll ask the spell checker. Python.get_back_in_skin(). Weird. I'm not sure if it makes any difference. The binary you run is Python.exe. It's already running, then you feed it a raw string, not on disk without loss of generality. The translation is a little hard to find too. Python :: mingw-c++ : Python.exe :: mingw-c++.exe : what? :: machine instructions.exe In Python there's a for-loop that's the exact same as one in machine instructions. 0101 b1= 1000 0110 if a < b0 goto b1 0111 b2= b2+ 1 accumulates a number in register b2. You probably want interface and graphics primitives. Sometimes I feel like "with a scroll bar" suffices to specify all the detail you need; there's too many options. (I can do this and this and ... scroll bar, please.) You know the episode of Star Trek NG where Barclay takes over the Enterprise. I'd also like to be able to write (write) a series of instructions and have it loop, and debug in vivo, as though a BASIC program were running and I could edit lines in its doing so, maybe time Windows Media visualization codecs in time. You could tell story lines and have it refine, post-inspiration. You might be surprised how much repetition in instructions Lines 1 through 9 (of -code-) share, in both sides of the analogy. Anyone work with a VAX? From ken at seehart.com Sat Mar 8 20:29:56 2008 From: ken at seehart.com (Ken) Date: Sat, 08 Mar 2008 17:29:56 -0800 Subject: Image Libraries In-Reply-To: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> References: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> Message-ID: <47D33D94.6000509@seehart.com> PB wrote: > I have been using PIL for generating images, however it does not > easily support operations with transparency etc. > > I tried to install aggdraw but it wouldn't compile. > > Ideally I'd like something open source so I can adapt it, hopefully > mostly written in python rather than C. > > Is there any other decent image libraries for python? > > I use PIL, and I haven't had any difficulty with alpha channel transparency. But maybe I'm using it for different things than you (blitting PGN(RGBA) antialiased images mostly). What problems are you having specifically? Ken Seehart From castironpi at gmail.com Fri Mar 28 16:59:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 13:59:51 -0700 (PDT) Subject: Tell ya' what: Message-ID: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> I want to regression a signal. It's NN, not necessarily, sine wave. What kind of numbers of harmonic simultaneous sounds are we looking at? How close to an A 440 can a human make? I want recognition to alert me. As a sine wave is coming in: >>> for t in [ ( 200* sin( x*2 ), 200* cos( x*2 ) ) for x in range( 10 ) ]: print( *t ) ... 0.0 200.0 181.859485365 -83.2293673094 -151.360499062 -130.728724173 -55.8830996398 192.03405733 197.871649325 -29.1000067617 -108.804222178 -167.814305815 -107.3145836 168.770791746 198.121471139 27.3474436416 -57.580663333 -191.531896065 -150.197449354 132.063341649 I want new feature characteristics to chain events. Circuits on -not- affected- external nodes can decouple clock tick. Realistically, the human brain uses a layer of several tens before anything is recognizable (sure, this photoreceptor says red all the time). Bring us the process of focus: Think mushroom clouds. Some of the smoke cycles back to redirection newcome particles, formed later in the blast. Program some of the ops. I feel like I'm asking if all the senses stream in paralell. Thing about rivers is, their current runs downstream: which does echo the process of muscle control: multiple brain pathways combine at confluences to generate a river: one muscle fiber microbundle (non contiguous, but that was later evolution). (Finely articulate ionic grades in three dimensions.) Input is other. It's still downstream for inputs, but the waves overlap at the 'deltas' with an chemoelectric interference pattern in either brain or spine, and have to agree on something (saw red, saw temperature, felt pressure). Those, by the way, are triggered by molecule discharge on the scale of 1,000s of atoms: C1814H2725N423O477S25. Recharge takes an electron. (Get one!) Humans: big brains. In brains we have a dynamic structure: you don't ever 'notice' things per se; they just reorganize brain (in particular trigger growth-- they decay themselves). Given intermodality (say, verbo-tactile?), varying circuit length (shortest and longest paths from a peripheral sensory cell to a motor cell (somewhen the name), cumulative depth (length) of iteration (generation) at which concepts form (Sartorius muscle direct stimulation), and correlate factor length of concept, children learn words based on exposure time (snooty kids know 'entrepreneur' (a between taker by the way, and 'revenue' come in again)) and varieties of thingsthatleduptoit: things that led up to it. The deeper concepts don't even motivate you to move, hardly even the tongue. You could do a lot of refining on your electric-medium perceptions: no boring stuff, no watered down, spam making, spam fighting, though with a few extra generations of hardware. Did everyone take the course on computer architecture? From http Sun Mar 2 17:35:33 2008 From: http (Paul Rubin) Date: 02 Mar 2008 14:35:33 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> Message-ID: <7xzltgrbyi.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > Better yet, how hard would it be to define an otherwise int-like type > that did not define a non-flooring division operator? Are there any > real use cases for such a type? User defined types in python are fairly heavyweight compared with the built-in types, and a type like that is just another thing for the user to have to remember. The C library has a bunch of different types like off_t (offset in a file) and size_t, so if you pass an off_t to a function that expects a size_t as that arg, the compiler notices the error. But they are really just integers and they compile with no runtime overhead. So, I think Python won't easily support lots of different types of integers, and we've got what we've got. There's an interesting talk linked from LTU about future languages: http://lambda-the-ultimate.org/node/1277 From castironpi at gmail.com Fri Mar 28 06:14:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:14:31 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> Message-ID: On Mar 28, 1:57?am, raj wrote: > To ankit: > > Well, sort() doesn't return the sorted list. It returns None. Why not > this straightforward way? > dvals = dict.values() > dvals.sort() > print dvals Why not sorted( dict.values() ). Can it return the right things from the right things in order from the givens? ( dvals , values, sort, print ).decode() From jzgoda at o2.usun.pl Mon Mar 17 07:49:57 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 17 Mar 2008 12:49:57 +0100 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: <1a560143-9a65-4c9f-bf5b-cb535d17cc13@z38g2000hsc.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <1a560143-9a65-4c9f-bf5b-cb535d17cc13@z38g2000hsc.googlegroups.com> Message-ID: Paul Boddie napisa?(a): >> I haven't been to EuroPython even when it has been fairly nearby >> because the entrance fee was to high. But how do you help change >> something like that? > > You could join in and make your case. There was a more protracted > discussion than usual last year about fees because some people pointed > out the discrepancy between salary and price levels in different parts > of Europe and the need to make the conference more affordable: what > may be relatively inexpensive for some might be relatively expensive > for others, and the organisers felt that it would be foolish to > exclude the latter group, particularly when they may be more likely to > travel to the conference in its present location. > > It's hard to say whether the conference is reaching everyone it > should, given the composition of attendees: > > http://www.europython.org/community/Planning/Projections I did not event think on attending EuroPython in Switzerland due to high cost of 3-day accomodation there (relatively to my wage these times). Lithuania seems to be not much more expensive than my home country, so I'll travel to Vilnius this year too. I thionk it was valid for others in Poland too, judging from the figures you mention. > But without anyone to pursue a particular cause, and with decisions > needing to be made within certain timeframes (which is often a > struggle, anyway), things often get preserved as they are rather than > being improved. I live in a European country which is either number > one or two on the price scale (depending on whether you include > alcohol prices or not), and I can't say what the right fee level > should be (other than "possibly lower than it is") - it's up to others > to weigh in and give their opinion, I think. EUR 100 does not seem too high as early bird registration fee, so the most intimidating costs (for me at least) is accomodation and travel. I mean, lowering the fee would be nice, but not essential to me. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From deets at nospam.web.de Thu Mar 27 04:27:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 09:27:44 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: References: Message-ID: <65144bF2dp2abU1@mid.uni-berlin.de> Gabriel Rossetti schrieb: > Hello, > > I am using Partial Function Application in a class and I've come up with > a problem, when the method is called it tries to pass "self" to the > curried/partial function, but this should be the first argument in > reality, but since the function is curried, then the self gets passed as > the second argument. Here is the code : > > def __registerService(self, atomic, service): > def reg(service): > # registers the service > ... > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > I should pass self when applying partial, but then I can't do that since > self is not available there. Does anyone have any ideas? Use a bound-method instead. That has the self already bound to it. Like this: class Foo: def m(self, arg): print arg f = Foo() partial(f.m, 10) Diez From pavlovevidence at gmail.com Wed Mar 12 17:42:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 14:42:39 -0700 (PDT) Subject: no more comparisons References: Message-ID: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> On Mar 12, 4:51 pm, Alan Isaac wrote: > I was surprised to see that > comparison is slated for death > in Python 3000. > > For example:http://www.python.org/dev/peps/pep-3100/ > list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done] Hmm, wasn't aware they were taking it that far. You should almost always avoid using the cmp parameter because it's very inefficient; instead, look at the key parameter which is a function that maps objects in a your sequence to a sort key and sorts on that. So instead of (for a simple example): s.sort(cmp=lambda a,b: cmp(a.get_id(),b.get_id())) You would use: s.sort(key=lambda a:a.get_id()) (However, there are rare cases where you can't easily map your items to a sortable builtin. I suppose in those cases you'll have to use a custom comparison proxy. But I digress.) > But there is a rumor of a PEP to restore comparisons.http://mail.python.org/pipermail/python-3000/2008-January/011764.html > > Is that going anywhere? No. > Also, what is the core motivation for removing this functionality? The basically replaced it with a better one. Instead of the cmp methods above, use the key method. Instead of __cmp__ method for overriding object operators, use the rich comparison methods: __lt__, __gt__, and so on. Python 2.x currently implements both cmp and rich comparisons at the same time, but that creates a lot of underlying complexity, so they got rid of it. Carl Banks From larry.bates at websafe.com Fri Mar 28 09:29:25 2008 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 28 Mar 2008 08:29:25 -0500 Subject: simple web-server In-Reply-To: References: Message-ID: <1206710965.11955.14.camel@fc8.home.com> On Fri, 2008-03-28 at 12:53 +0100, Pavol Murin wrote: > hello python users, > > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). > > Longer story: > > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed). > > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? > > thank you, muro Take a look at twisted web, it fits in between. -Larry From robert.kern at gmail.com Mon Mar 3 17:08:53 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Mar 2008 16:08:53 -0600 Subject: sympy: what's wrong with this picture? In-Reply-To: <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 2:49 pm, Carl Banks wrote: >> It's just a bug--probably sympy is messing with the internals of the >> random number generator. It would be a simple fix. Instead of >> b****ing about it, file a bug report. > > I did. > >> Or better yet, submit a patch. > > I would if I knew what the problem was. Did you even try to figure it out? It took me all of 5 minutes to find the mistake. > I posted it here because someone recommended it. > I'm simply un-recommending it. It was a mistake, an easily remedied mistake, not a big unchangeable design decision. If you want to recommend against sympy as a package, there is a larger burden of proof that you have yet to meet. -- 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 gagsl-py2 at yahoo.com.ar Sat Mar 22 20:03:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 22 Mar 2008 21:03:52 -0300 Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: En Sat, 22 Mar 2008 17:27:49 -0300, sgharvey escribi?: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. Take a look at ConfigObj http://pypi.python.org/pypi/ConfigObj/ Instead of: # Remove the '\n's from the end of each line lines = [line[0:line.__len__()-1] for line in lines] line.__len__() is a crazy (and ugly) way of spelling len(line). The comment is misleading; you say you remove '\n's but you don't actually check for them. The last line in the file might not have a trailing \n. See this: lines = [line.rstrip('\n') for line in lines] Usually trailing spaces are ignored too; so you end up writing: lines = [line.rstrip() for line in lines] In this case: # Compile the regexen patterns = {} for pattern in pattern_strings: patterns.update(pattern: re.compile(pattern_strings[pattern], re.VERBOSE)) That code does not even compile. I got lost with all those similar names; try to choose meaningful ones. What about this: patterns = {} for name,regexpr in pattern_strings.iteritems(): patterns[name] = re.compile(regexpr, re.VERBOSE)) or even: patterns = dict((name,re.compile(regexpr, re.VERBOSE)) for name,regexpr in pattern_strings.iteritems() or even compile them directly when you define them. I'm not sure you can process a config file in this unstructured way; looks a lot easier if you look for [sections] and process sequentially lines inside sections. if match: content.update({pattern: match.groups()}) I wonder where you got the idea of populating a dict that way. It's a basic operation: content[name] = value The regular expressions look strange too. A comment may be empty. A setting too. There may be spaces around the = sign. Don't try to catch all in one go. -- Gabriel Genellina From marco at sferacarta.com Wed Mar 12 12:44:32 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 12 Mar 2008 17:44:32 +0100 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> Message-ID: Robert Bossy wrote: > Indeed! Maybe the best choice for chunksize would be the file's buffer > size... I won't search the doc how to get the file's buffer size because > I'm too cool to use that function and prefer the seek() option since > it's lighning fast regardless the size of the file and it takes near to > zero memory. And makes a hole in the file, I suppose, hence the fragmentation. The OP explicitly asked for an uncompressed file. From tjreedy at udel.edu Sun Mar 30 22:43:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Mar 2008 22:43:58 -0400 Subject: Odd behaviour with list comprehension References: <4fbfbb8f0802291901s5ed7e0b4ua3e77ad46aa53bb7@mail.gmail.com> <871w6vkq3z.fsf@micah.cowan.name> Message-ID: "Steve Holden" wrote in message news:fspe8a$ptq$1 at ger.gmane.org... | Micah Cowan wrote: | > "Jerry Hill" writes: | > | >> On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu wrote: | >>> Is there a way for me keep the iterating variable in list | >>> comprehension local to the list comprehension? | >> Kind of. You can use a generator expression instead of a list | >> comprehension, and those don't leak their internal variables into the | >> enclosing scope: | > | > Whoa, that's cool. I didn't even think to try that, just assuming it | > would do the same. | > | > Though now that I think about it, I don't see how it possibly could, | > since it just evaluates to an object that you could pass around, and | > return, using it the same way elsewhere. | > | Well, the fact that the bound variable in the list comprehension does | indeed remain outside the construct is simply the result of an | over-zealous wish to emulate for loop semantics. The original reasoning, | IIRC, as that since a for loop left its bound variable at the last used | value, so should a list comprehension. | | This was quickly recognized as a mistake, but unfortunately not quickly | enough. As it was felt that some people might already have relied on | that behavior, it was retained in the interests of preserving backwards | compatibility. But it will not be retained in 3.0, as I understand it. So best to not exploit the deprecated behavior. tjr From tjreedy at udel.edu Mon Mar 24 04:33:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Mar 2008 04:33:53 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as afirst programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <13ue0gsj76m6070@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13ue0gsj76m6070 at corp.supernews.com... | Unfortunately there's nothing we can do to fix that error. Even though | the function object has an attribute "__name__" (also known as | "func_name") which is set to spam, it isn't used for tracebacks. Instead, | the label comes from a read-only attribute buried deep in the function | object: | | >>> tasty_stuff.func_code.co_name = 'yummy meat-like product in a can' | Traceback (most recent call last): | File "", line 1, in | TypeError: readonly attribute The fact that .func_name (which is writeable) is not used at first surprised me until I remembered that code objects can potentially be used by multiple function objects and hence are not connected to any one in particular. | This is a mistake, in my opinion. It's an arbitrary decision to make this | read-only (as far as I can tell), which goes against the grain of | Python's "we're all consenting adults here" philosophy. | | By the way, in case you're thinking that wanting to change the (so- | called) name of a function is a silly think to do, not at all. Consider | factory functions: | | def factory(how_much): | def f(n=1): | for i in range(n): | print "I love spam a %s" % how_much | return f | | Every function created by the factory has the same "name", no matter what | name you actually use to refer to it. factory('little') and | factory('lot') both uselessly identify themselves as "f" in tracebacks. workaround: >>> ftext = 'def %s(): pass' >>> exec ftext%'ftest' >>> ftest so: def factory(how_much): 'param how_much MUST be a legal name' exec '''def %(how_much)s(n=1): for i in range(n): print "I love spam a %(how_much)s"''' % {'how_much': how_much} return locals()[how_much] f2=factory('much') print f2.func_name prints 'much' But certainly setting .co_name directly would be easier Terry Jan Reedy From aahz at pythoncraft.com Mon Mar 17 09:21:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 Mar 2008 06:21:05 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> Message-ID: In article <7x3aqpg3rv.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >Stephan Deibel writes: >> >> I have to admit, I'll keep coming to PyCon even if all the talks suck >> abysmally as long as there's good hallway time, open space, BoFs, and >> sprints. ;-) > >OK, so why not get rid of all the talks and other stuff, and just have >a basically structureless conference, beyond scheduling some open >meetings on various topics? That would be a lot less expensive and a >lot more interesting. Don't think we haven't discussed this. The problem is that some kinds of talks demand a lot of preparation (and therefore need to be scheduled in advance), plus plenty of people like some structure. PyCon -- like most organized human endeavors -- is in many ways about the art of compromise, trying to figure out how to satisfy as many people as possible and disappointing as few as possible, keeping in mind that it is almost impossible to completely satisfy anyone and most people will have some disappointment (if only because two talks that are ABSOLUTELY CRITICAL to them are cross-scheduled). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From deets at nospam.web.de Tue Mar 18 16:59:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Mar 2008 21:59:58 +0100 Subject: method to create class property In-Reply-To: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> Message-ID: <64aoqjF29asbkU1@mid.uni-berlin.de> Joe P. Cool schrieb: > Hi, > > I like C#'s style of defining a property in one place. Can the > following way > to create a property be considered reasonable Python style (without > the > print statements, of course)? > > class sample(object): > def __init__(self): > sample.y = self._property_y() > > def _property_y(self): > def _get(self): > print 'getting y.' > return self._y > def _set(self, value): > print 'setting y.' > self._y = value > def _del(self): > print 'bye, y!' > del self._y > return property(_get, _set, _del) There are a few recipies, like this: class Foo(object): @apply def foo(): def fget(self): return self._foo def fset(self, value): self._foo = value return property(**locals()) Diez From grante at visi.com Mon Mar 24 18:11:40 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 24 Mar 2008 22:11:40 -0000 Subject: FW:Reading new mail from outlook express using Python References: Message-ID: <13ug9osrv1c6h2b@corp.supernews.com> On 2008-03-24, SPJ wrote: > I am trying to create new tickets in the ticketing system > using python. When I receive new email from a particular > address, I have to trigger the python script and parse the > mail in required format. > > The main hurdle here is, how to invoke the script on arrival > of new mail? I checked the outlook settings and found that it > supports only microsoft VB script and Jscript. Is there any > other way? I mean, if I make a daemon, how will it be notified > of new mail? Is there any python module that does this? > > I am not sure if this is the right place to ask this, since it > is also a microsoft related question. But any help is > appreciated. You can use Outlook's COM interface from Python. That allows you to read messages from a mailbox. I don't know of any way to get "notified", but you can use the COM interface to poll the mailbox(es) periodically. -- Grant From wolf_tracks at invalid.com Fri Mar 21 10:33:16 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 21 Mar 2008 07:33:16 -0700 Subject: An Application Program to Play a CD In-Reply-To: References: Message-ID: Thanks for the link. I briefly looked at it, and it sure would be hard to tell if it has application here. The material looks developer oriented. Your short descriptions gives more insight than their home page. They aren't exactly marketing driven; however, I'll give it a closer look. Maybe joining the forum will reveal more about it. Jeff McNeil wrote: > I don't know of any Python specific stuff to do this, but have you > looked at Asterisk? I know it's quite configurable and allows you to > setup dial plans and route extensions and whatnot. > > http://www.asterisk.org/ > > That's probably a better fit. > > On 3/20/08, W. Watson wrote: >> How difficult would it be to write a Python program that would play a >> specific track on a CD from say 8 am to 6 pm each weekday on a PC's speaker, >> and switch tracks each day? That is, what library capabilities might be able >> to do that. Are they already available. >> >> Extra points. Now imagine the same as above, but the program should answer a >> phone and play the track for the day while someone is holding the call, or >> would be given the option to connect to the operator, say, or listen to the >> recording? >> >> To get a bit specific, our science museum would like to buy the monthly set >> of StarDate programs. Each program is about 2 minutes long and there's one >> for every day of the month. There seems to be no such commercial software to >> automate this process. >> -- >> Wayne Watson (Nevada City, CA) >> >> Web Page: >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> -- Wayne Watson (Nevada City, CA) Web Page: From steve at REMOVE-THIS-cybersource.com.au Fri Mar 21 07:21:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 21 Mar 2008 11:21:12 -0000 Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> Message-ID: <13u76h8mifniibc@corp.supernews.com> On Fri, 21 Mar 2008 11:43:33 +0100, sam wrote: > I can see that Python and Javascript inheritance model is almost the > same. Both languages are dynamically typed. And it seems that using > "classes" in Python makes some things more complicated then it is > necessary (eg functions, methods and lambdas are differen beeing in > Python concept). Please explain why you think that functions are more complicated in Python because of the class model. -- Steven From sturlamolden at yahoo.no Wed Mar 19 18:14:25 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Mar 2008 15:14:25 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> Message-ID: <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> On 19 Mar, 22:48, John Machin wrote: > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > and is IMHO more readable than Paul's. Is a Python set implemented using a hash table? From stephenhorne100 at aol.com Mon Mar 17 08:56:24 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 05:56:24 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: <15905376-3ec6-4994-84e7-5744ef521778@z38g2000hsc.googlegroups.com> On Mar 17, 11:49 am, MartinRineh... at gmail.com wrote: > What are the considerations in choosing between: > > return [a, b, c] > > and > > return (a, b, c) # or return a, b, c > > Why is the immutable form the default? My understanding is that the immutable form is not the default - neither form is a default. The syntax for mutable lists requires square brackets. The syntax for immutable tuples only requires commas. However, commas are also used for other purposes. The parens for tuples are the same parens that might wrap any subexpression, in this case guarding against misinterpretation of commas. Since the parens are normally included for consistency as well as disambiguation, they end up being part of the tuple psychologically, but to Python itself they are separate. Personally, I'd make the parens compulsory so that mindsets and language specification are better aligned. If, that is, I was inventing a new language. But you can be sure that there's plenty of code out there that would break if a change like that was made now. As for choosing, if you never plan to modify the members of the sequence, a tuple expresses that intent and allows Python to enforce it. Some operations on tuples are probably also more efficient as a result. That said, 90%+ of the time I use a list either way. After all, as requirements change I might find I do need to modify after all. A change from tuple to list in any non-trivial case would require a thorough test suite to ensure that all cases are updated correctly (partly because Python is dynamically typed), and ashamed as I am to admit it, my test suites are rarely that thorough. Without that testing, there might be an obscure case where you still create a tuple, and that tuple gets passed to code that expects a list and tries to replace an element. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 08:45:22 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 14:45:22 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: <659gb2F2f84eoU2@mid.individual.net> hdante wrote: > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: Could you please list some that do, and are also convenient? Regards, Bj?rn -- BOFH excuse #288: Hard drive sleeping. Let it wake up on it's own... From jeff at schwabcenter.com Thu Mar 20 12:59:55 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 09:59:55 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: <13u52hqlbtdv1d1@corp.supernews.com> References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> <13u52hqlbtdv1d1@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-03-20, Jeff Schwab wrote: > >>>> http://www.google.com/search?q=emacs+python >>> Gee. Thanks. >> I believe Grant was suggesting that Emacs often serves a similar purpose >> on Unix to what Visual Studio does on Windows, which seemed to be what >> you were asking. When asking about Mac OS X here, you are likely to get >> a lot of generic Unix responses. (Would it have been clearer if he had >> just said "emacs?") > > Don't the normal "run/debug python from inside emacs" methods > work on OS-X? AFAIK, yes; I don't see why it wouldn't. I missed the word "emacs" in the subject header, and did not recognize "an emac" in the original post as meaning "emacs." From puneetbrar at gmail.com Mon Mar 24 05:47:17 2008 From: puneetbrar at gmail.com (gags) Date: Mon, 24 Mar 2008 02:47:17 -0700 (PDT) Subject: problem with harvestman on ubuntu7.10 gusty Message-ID: <3eacea57-5df9-4f0a-a6e1-548f835ec6ae@s13g2000prd.googlegroups.com> Hi there I just saw that program on the awards and wanted to use it as i installed it on ubuntu gusty gibbon it worked fine without errors and when i run it i get the following errors File "/usr/bin/harvestman", line 364, in spider.run_projects() File "/usr/bin/harvestman", line 283, in run_projects self.register_common_objects() File "/usr/bin/harvestman", line 135, in register_common_objects conn = connector.HarvestManNetworkConnector() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/ connector.py", line 201, in _init_ self.__configure() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/ connector.py", line 326, in __configure self.__configure_protocols() File "/usr/share/pycentral/harvestman/site-packages/HarvestMan/ connector.py", line 449, in __configure_protocols cookiehandler) File "/usr/lib/python2.5/urllib2.py", line 467, in build_opener opener.add_handler(h) File "/usr/lib/python2.5/urllib2.py", line 303, in add_handler type(handler)) TypeError: expected BaseHandler instance, got regards puneet brar 9815665000 From rasmussen.bryan at gmail.com Wed Mar 12 02:02:36 2008 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Wed, 12 Mar 2008 07:02:36 +0100 Subject: SOAP access to SharePoint In-Reply-To: <1205271534.4382.5.camel@localhost.localdomain> References: <1205271534.4382.5.camel@localhost.localdomain> Message-ID: <3bb44c6e0803112302m7eecb962jd4e1f05e46c553a5@mail.gmail.com> It's usually not a totally mind destroying process if you hand craft your SOAP messages going off of examples from the service (if you're lucky enough they have ones) and reading their XML Schemas/WSDLs to see what they actually expect. Since it's MS do tests on your hand rolled xml with Microsoft XML Schema validation, this may seem tedious but it is likely to be less tedious than relying on any APIs to agree in the wide wonderful world of Soap based WebServices. Cheers, Bryan Rasmussen On Tue, Mar 11, 2008 at 10:38 PM, Paul Watson wrote: > Has anyone successfully accessed a Microsoft SharePoint WSS using > Python? No, not IronPython. I need for this to be able to run on all > machines the customer might choose. > > Which libs are you using? ZSI, SOAPpy, soaplib, ??? > > http://wiki.python.org/moin/WebServices > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Mar 17 07:59:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 09:59:14 -0200 Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: En Mon, 17 Mar 2008 01:54:01 -0200, WaterWalk escribi?: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. See the wiki at http://wiki.python.org/moin/DevelopmentTools for more editors, debugging tools and IDEs. -- Gabriel Genellina From fn681 at ncf.ca Fri Mar 21 10:30:29 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:30:29 -0500 Subject: Is this valid ? In-Reply-To: References: Message-ID: Lie wrote: > On Mar 20, 4:18 am, Stef Mientki wrote: >> hello, >> >> by accident I typed a double value test, >> and to my surprise it seems to work. >> Is this valid ? >> >> a = 2 >> b = 2 >> >> a == b == 2 >> >> thanks, >> Stef Mientki > > a == b == 2 > is equivalent to > a == b and b == 2 > except that b is only evaluated once for the whole comparison Yes - there seems to be unanimity. Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). Formally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy are comparison operators, then a opa b opb c ...y opy z is equivalent to a opa b and b opb c and ... y opy z, except that each expression is evaluated at most once. Colin W. From yuxi at ece.gatech.edu Mon Mar 10 17:15:46 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 10 Mar 2008 17:15:46 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > There are a number of free tools for image matching but it's not very > easy to decipher the actual algorithm from the code that includes db > management, GUI, etc, etc. I have my own image database and GUI so all > I need is the actual algorithm preferably in pseudo code and not in > the form of a research paper (from which I also found a lot but since > I'm not that much interested in the actual science of image > recognition this seems like an over kill). I'd recommend SIFT. There's quite a bit of information on SIFT. In most cases, they don't cover the background science too much, but are still heavy on the math. Pseudo code is hard to come by since it will take many lines of pseudo code just to express one concise mathematical equation. There are however many links to implementations in various languages on the Wikipedia page. http://en.wikipedia.org/wiki/Scale-invariant_feature_transform I have had good experiences with SIFT for feature extraction from images (I have used it for panorama stitching and robot mapping). It's insensitive to scale and rotation. Note that it is a patented algorithm and this may (or may not) pose a problem for you. From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:25:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:25:48 -0000 Subject: I cannot evaluate this statement... References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <13t3cms4fn6318e@corp.supernews.com> On Fri, 07 Mar 2008 12:38:11 -0800, waltbrad wrote: > The script comes from Mark Lutz's Programming Python. It is the second > line of a script that will launch a python program on any platform. > > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe > > That makes sense. Because the first condition is true and 'python.exe' > is true. So the next comparison is 'python.exe' or 'python' Well, > python.exe is true. So that value is returned to pyfile. > > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. So, the next comparison should be 'False' or > 'python' -- This is because 'and' returns the first false value. But, > again, on linux pyfile evaluates to python.exe Not on my Linux box. >>> import os, sys >>> sys.platform 'linux2' >>> (sys.platform[:3] == 'win' and 'python.exe') or 'python' 'python' > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? When the first three letters of sys.platform aren't 'win'. -- Steven From castironpi at gmail.com Wed Mar 12 18:04:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 15:04:48 -0700 (PDT) Subject: string / split method on ASCII code? References: Message-ID: <7edad086-68cd-47e1-b984-2c45eb3ef730@n58g2000hsf.googlegroups.com> > ? ?import re > ? ?splitter_re = re.compile(chr(174) + '|' + chr(175)) > ? ?for line in file(FILENAME): > ? ? ?parts = splitter_re.split(line) > ? ? ?do_something(parts) > > and then go find a large blunt object with which to bludgeon the > creator of the file... :) p>> creator= CreatorOfTheFile() p>> creator.bludgeon > p>> From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 18:32:41 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 22:32:41 -0000 Subject: python program deleted References: Message-ID: <13uo84963p30926@corp.supernews.com> On Thu, 27 Mar 2008 18:08:05 -0400, jim-on-linux wrote: > py users, > > I developed a python program and used py2exe to create the exe. > > I zip the entire package and email it to my clients. > > Some clients get the zip file, unzip the package and everything works > fine. > > And some clients get my email with an icon attached which has the > correct filename but the size is 8k when it should be about 5 mb. That would be an email problem, not a Python problem. You need to: (1) Check that you actually are attaching the 5MB file to the email like you think you are. (2) Check that your mail client is sending the email with attachment. (3) Check that your mail server is accepting the email. (4) Check that your mail server is sending the email. (5) Check that the receiver's mail server is accepting the email. (6) Check that the receiver's mail server is delivering the 5MB email to the user's mailbox. (7) Check that the receiver's mail client is displaying the attachment. It's quite possible that the receiver's mail server is quarantining the attachment. 5MB is a lot for email -- many mail servers will reject emails larger than 10MB, although in my opinion setting the limit at 5MB is being overly strict. Once you've confirmed that the attachment left your mail server, you need to tell your clients to speak to their system administrator. -- Steven From half.italian at gmail.com Thu Mar 20 13:45:03 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 20 Mar 2008 10:45:03 -0700 (PDT) Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: On Mar 20, 6:42?am, Duncan Booth wrote: > Steven D'Aprano wrote: > > On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: > >> By default Python on Windows allows you to open a file for reading > >> unless you specify a sharing mode which prevents it: > > > But the OP is talking about another process having opened the file for > > WRITING, not reading. It's that other process that has exclusive access, > > and the OP was trying to determine when it was safe to attempt opening > > the file according to whether or not it was still growing. > > No, unless the other process has specified that it wants exclusive access > there is nothing stopping his process also opening the file. That's why he > has to specify when he opens it that he wants exclusive access: then it > doesn't matter what the other process does, he won't be able to open it > until the other process has closed the file. > > This all of course assumes that the other process writes the file in one > single atomic chunk. If it were to create it and then separately open and > write to it then all bets are off. Thanks for your input. After trying again this morning, the file is opened for reading. I must have had some wonky permissions on that file, so the error method won't work. Trying to use the md5 technique won't work here either. It takes quite awhile to run one md5, let alone two on a growing file. These files can be 20-50GB. The overall idea is to be able to tell if a file has finished being placed in a directory without any control over what is putting it there. If I'm in control of the process, I know I can put it in a temp area, etc. I use the method I mention in my original post regularly without knowing how the file gets there, and was surprised to see it didn't work on Windows. In this case, there will be so few people touching the system, that I think I can get away with having the copy be done from Unix, but it would be nice to have a general way of knowing this on Windows. ~Sean From grante at visi.com Sat Mar 1 23:14:44 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 04:14:44 -0000 Subject: SV: Where's GUI for Python? References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> Message-ID: <13skadks8k9bvf7@corp.supernews.com> On 2008-03-02, K Viltersten wrote: >>> import tkininter >>> >> When that fails, try without the stutter >> >> import tkinter > > > I must be doing something wrong because > neither tkinter nor tkininter works. You probably don't have tkinter installed. It's not installed by default on many systems. -- Grant Edwards grante Yow! Yow! I'm imagining at a surfer van filled with visi.com soy sauce! From castironpi at gmail.com Sun Mar 2 13:18:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 10:18:40 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> On Mar 2, 12:01?pm, John DeRosa wrote: > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > >Hi, > > >Have you ever seen Beautiful Python code? > >Zope? Django? Python standard lib? or else? > > >Please tell me what code you think it's stunning. > > Just about any Python code I look at. Decorators, with, and namedtuple. From jr9445 at ATT.COM Fri Mar 14 14:47:07 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 14 Mar 2008 13:47:07 -0500 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Aahz > Sent: Friday, March 14, 2008 2:05 PM > To: python-list at python.org > Subject: RIP: Joseph Weizenbaum > > Creator of Eliza: > > http://www-tech.mit.edu/V128/N12/weizenbaum.html > -- How do you feel about creator of Eliza? ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From castironpi at gmail.com Wed Mar 26 22:55:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 19:55:53 -0700 (PDT) Subject: genetic algors in practical application Message-ID: <2242528c-764f-4aa6-a605-f2d05b25484e@u69g2000hse.googlegroups.com> I want to go in to construction. However, 'I' means 'newsgroup' and 'want to go' means 'is'. If you had an army of two-micron spiders, could we build something? Use case is an American skyscraper. They have powerful tricks. Clearly they can withstand a force. These can withstand more combined, greater-than-minimum. What is their command set? Braid. Hoist. Vine power and waste. Charge, double-pump circuit. Round-trip a dollar. I said round. (What's the square trip.) You do know that the brain has seven trillion atoms, right? Mass of water. You know, combine 'muscle fiber' with 'inhibition, excitation' and 'motor neuron circuit', and you might be on to something, and you might be right. Here's free from Neuro. 'Each motor neuron synapses with multiple muscle fibers. .. Cross section through the muscle shows the distribution of muscle fibers (red dots) contacted by the motor neuron.' Power-- Tools. Note that 'synapse' verb. Written English folks. 'myelin debris' too. Is your concern the actual construction of the nanospiders (interesting side note), or programming it? Get a team of programmers too. Who asked for the 'Python d.j. console'? Did -uuu- put that on line. From kar1107 at gmail.com Tue Mar 4 02:09:35 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 3 Mar 2008 23:09:35 -0800 (PST) Subject: clocking subprocesses References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> Message-ID: On Mar 3, 9:57 am, barnbu... at gmail.com wrote: > Hi, > > I've seen several threads on this subject, but haven't (yet) run > across one that answers my specific questions. This should be really > easy for someone, so here goes: > > I'm running some numerical simulations under Ubuntu, and using Python > as my scripting language to automatically manage input and output. I > need to have a precise performance measurement (CPU time) of how long > it takes to run my simulations. > > Right now I have something like: > > stime = time.time() > subprocess.call(["./mysim","args"]) > ftime = time.time() > print ftime-stime > > However, time.time() only gives wall-clock time, so I'm also measuring > the time it takes to run other processes running at the same time. > What I'd rather have is: > > stime = time.clock() > subprocess.call(["./mysim","args"]) > ftime = time.clock() > print ftime-stime > > But this, of course, usually outputs 0, because time.clock() does not > count the CPU ticks of the subprocess. > > So, long story short, I need to get CPU time of something I call using > subprocess.call(). I don't want to have to profile my code, since it > will significantly reduce computation time. Use os.times(). It returns a 5-tuple and what you want is child cpu times. times(...) times() -> (utime, stime, cutime, cstime, elapsed_time) Return a tuple of floating point numbers indicating process times. cutime+cstime will give you the total CPU used by child (your simulation). Karthik > > Thanks for the advice. > > Kevin From mensanator at aol.com Tue Mar 11 01:40:52 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 10 Mar 2008 22:40:52 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <2f49410a-b7cd-451c-b958-589aef278218@x41g2000hsb.googlegroups.com> On Mar 10, 10:44?pm, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. Needs work. ## Do you want to calculate primes? 1 = yes and 2 = no. 1 ## What number do you want to use as the final number to calculate with? 66 ## What number do you want to start calculating primes from? 2 ## 2 is not prime. False ## 3 is prime. True ## 4 is prime. False ## 5 is prime. True ## 6 is not prime. True ## 7 is prime. True ## 8 is not prime. True ## 9 is not prime. True ## 10 is not prime. True ## 11 is prime. True ## 12 is not prime. True ## 13 is prime. True ## 14 is not prime. True ## 15 is not prime. True ## 16 is not prime. True ## 17 is prime. True ## 18 is not prime. True ## 19 is prime. True ## 20 is not prime. True ## 21 is prime. False ## 22 is not prime. True ## 23 is prime. True ## 24 is prime. False ## 25 is prime. False ## 26 is not prime. True ## 27 is not prime. True ## 28 is not prime. True ## 29 is prime. True ## 30 is not prime. True ## 31 is not prime. False ## 32 is prime. False ## 33 is prime. False ## 34 is not prime. True ## 35 is prime. False ## 36 is not prime. True ## 37 is not prime. False ## 38 is not prime. True ## 39 is prime. False ## 40 is prime. False ## 41 is prime. True ## 42 is not prime. True ## 43 is not prime. False ## 44 is not prime. True ## 45 is prime. False ## 46 is not prime. True ## 47 is prime. True ## 48 is not prime. True ## 49 is not prime. True ## 50 is prime. False ## 51 is not prime. True ## 52 is not prime. True ## 53 is not prime. False ## 54 is not prime. True ## 55 is prime. False ## 56 is prime. False ## 57 is not prime. True ## 58 is not prime. True ## 59 is not prime. False ## 60 is prime. False ## 61 is prime. True ## 62 is not prime. True ## 63 is prime. False ## 64 is not prime. True ## 65 is prime. False ## Do you want to calculate primes? 1 = yes and 2 = no. 2 ## Goodbye. From willsteve2003 at yahoo.ca Sat Mar 8 13:24:38 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Sat, 8 Mar 2008 10:24:38 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <7d442cdd-749e-4391-ba31-e9c86d090137@x41g2000hsb.googlegroups.com> On Mar 8, 9:43?am, malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > ? ? x = q.get() > ? ? #process x to get zero or more y's > ? ? #for each y: > ? ? q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > ? ? #process x to get zero or more y's > ? ? q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? > > Regards, > > Muhammad Alkarouri I think it's a bad practice to get into. Did you intend to do the "process" step again over the added variables? If not I would set a new variable, based on your awful naming convention, let's call it z. Then use z.append(y) within the for loop and after you are out of your for loop, q.append(z). From furkankuru at gmail.com Tue Mar 25 21:22:41 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 03:22:41 +0200 Subject: embedded python pythonpath In-Reply-To: References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> Message-ID: <3a4a8f930803251822h5d423198yc318ed270ad7d92a@mail.gmail.com> On 3/26/08, Gabriel Genellina wrote: > En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru > escribi?: > > > Actually, I do not want any .py or .pyc files around my executable. > > (including userdict, sys, site etc) > > I want to have just single zip file for all python files. > > Putting all of them into pythonNN.zip (NN depending on the Python version > in use) should be enough, but I've never tried it. I had already tried putting all of them into pythonNN.zip but I had to copy it to the place where sys.path points in my case it was windows\system32\python25.zip > I had a look at py2exe source codes but could not figure out how it just > > looks into a zip file. > > Standard Python already supports having zip files in sys.path (using the > builtin zipimport module), you don't have to do anything special to enable > that (apart from building with the required dependencies, like zlib, of > course) yes I know but I do not want "any" py or pyc file. I would still need dict.pyc, sys.pyc, site.pyc etc. files for py_initialize. > So maybe I have to compile the svn version of python. > > After renaming the directory where Python 2.5 were installed, my > test25.exe program (the one compiled using Python 2.5.1) worked fine. So > it looks like it is something with how the "python home" is searched. Ok then changing or deleting pythonhome environment variable may fix the problem? thanks, Anyway, as I said earlier, you don't have to play with PYTHONPATH; just > add any required directory to sys.path at runtime. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat Mar 1 13:01:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 10:01:49 -0800 (PST) Subject: SQLLITE References: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> <62tjigF24ui98U2@mid.uni-berlin.de> Message-ID: <74838b55-9b05-4f90-8a15-37bb50a775da@h11g2000prf.googlegroups.com> On Mar 1, 11:54?am, "Diez B. Roggisch" wrote: > nexes schrieb: > > > Hello All, > > ? ?I am having a minor problem when I try and do this: > > ? ? ? c.execute("insert into [tblTranscripts] (MovieID,Transcript) > > Values(" + movieID + ",'" + formatText + "');") ? (don't even bother > > commenting of the sql style I know its bad form but this is a simple > > script). Whenever I try and do the insert I get table not found, > > however when I perform the sql through sqlite's command line program > > (the sql is outputted via a print statement) it works fine. ?Any ideas? > > No, and without more context nobody will have. Does working with the > table with other statments work, how do you connect the DB, are you sure > you really use the same DB-file and so forth. > > Diez There's a number of things it could be-- narrow it down a little more (for the reader). Beginner stuff is usually forgetting 'use moviedata'. From gandalf at shopzeus.com Tue Mar 25 05:05:28 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Mar 2008 10:05:28 +0100 Subject: eval and unicode In-Reply-To: <47E42213.50208@v.loewis.de> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> <47E42213.50208@v.loewis.de> Message-ID: <47E8C058.8050702@shopzeus.com> Martin v. L?wis wrote: >> eval() somehow decoded the passed expression. No question. It did not >> use 'ascii', nor 'latin2' but something else. Why is that? Why there >> is a particular encoding hard coded into eval? Which is that >> encoding? (I could not decide which one, since '\xdb' will be the >> same in latin1, latin3, latin4 and probably many others.) > > I think in all your examples, you pass a Unicode string to eval, not > a byte string. In that case, it will encode the string as UTF-8, and > then parse the resulting byte string. You are definitely wrong: s = 'u"' + '\xdb' + '"' type(s) # eval(s) # u'\xdb' s2 = '# -*- coding: latin2 -*-\n' + s type(s2) # eval(s2) # u'\u0170' Would you please read the original messages before sending answers? :-D L From stefan_ml at behnel.de Thu Mar 27 13:23:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Mar 2008 18:23:25 +0100 Subject: "Soup Strainer" for ElementSoup? In-Reply-To: <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> <47e87a88$0$36376$742ec2ed@news.sonic.net> <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> Message-ID: <47EBD80D.3010902@behnel.de> erikcw wrote: > I'm parsing real-world HTML with BeautifulSoup and XML with > cElementTree. > > I'm guessing that the only benefit to using ElementSoup is that I'll > have one less API to keep track of, right? If your "real-world" HTML is still somewhat close to HTML, lxml.html might be an option. It combines the ElementTree API with a good close-to-HTML parser and some helpful HTML handling tools. http://codespeak.net/lxml http://codespeak.net/lxml/lxmlhtml.html You can also use it with the BeautifulSoup parser if you really need to. http://codespeak.net/lxml/elementsoup.html Stefan From davidbak at gmail.com Fri Mar 7 16:00:53 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 13:00:53 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class Message-ID: I want - but cannot get - a nested class to inherit from an outer class. (I searched the newsgroup and the web for this, couldn't find anything - if I missed an answer to this please let me know!) I would like to build a class for a data structure such that nodes of the data structure - of interest only to the data structure implementation itself and not to the consumer - are instances of one of two class types. I thought to encapsulate the nodes' classes like this: class Tree(object): ...class _MT(Tree): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node(Tree): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def merge(self, T): ......def __init__(): return _MT() ...... In other words, some methods would be implemented on instances' classes (like isEmpty and insert) and some on the outer class (like merge). Users of the data structure never need to know about the nodes, much less the nodes' classes, so I wanted to encapsulate them However I can't do this, because, of course, the name Tree isn't available at the time that the classes _MT and _Node are defined, so _MT and _Node can't inherit from Tree. What is the Pythonic thing I should be doing instead? (Easy answer: Put this code in a module, exposing only a factory function. I could do that, but wanted to know if I could encapsulate it as described so I could actually put several similar data structures into one module.) Thanks! -- David From deets at nospam.web.de Sat Mar 29 09:49:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 14:49:31 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> Message-ID: <656vnpF2ekcsrU1@mid.uni-berlin.de> > I appreciate the droll sense of humor, but do you mean to > assert that asyncore.py supports asynchronous disk file I/O? As I said in an answer to the OP, I somewhat glossed over the "file" and just read IO. And under Posix, python *does* support asynchronous IO using the select-module. If you can faciliate that using the asynchore module I can't say, but the question was if python as whole supported async IO out of the box - asyncore & twisted I mention as references of implementations using that. > What that means to me is, you queue a disk read, and there's > an event flag or something that you can wait for before you > come back to find the data in your buffer. (That's how I > remember it from the old days, when it mattered a little, > though not enough that I ever remember actually doing it, > and 20 years later I guess the incentive is even less.) Which is exactly what select allows you to do. You pass a set of file-descriptors and are notified if data arrives or has been successfully transmitted. Diez From mail2spj at yahoo.com Mon Mar 24 17:00:13 2008 From: mail2spj at yahoo.com (SPJ) Date: Mon, 24 Mar 2008 14:00:13 -0700 (PDT) Subject: Reading new mail from outlook using Python Message-ID: <924616.42495.qm@web50105.mail.re2.yahoo.com> An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Mon Mar 3 07:35:30 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Mon, 3 Mar 2008 12:35:30 -0000 Subject: Cant run application as ./myapp.py Message-ID: <00ec01c87d2b$11f4f0f0$35ded2d0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got an application here which for some reason won't start using the following syntax from the command line: Cd /mydirectory ./MyApplication.py I have to run this as a fully qualified python launch such as: Cd /mydirectory python MyApplication.py This is a little bit confusing to me as I have other applications which run just fine using the ./somthing.py syntax. Is there any reason why this doesn't work? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ebenze at hotmail.com Fri Mar 14 16:09:44 2008 From: ebenze at hotmail.com (Eric B.) Date: Fri, 14 Mar 2008 16:09:44 -0400 Subject: Installing Python2.4 on RHEL4? Message-ID: Hi, I appologize if this is slightly OT, but I am really struggling to figure out how to install Python2.4 on RHEL4. To make matters worse, the RHEL4 machine is a 64bit architecture. I search pyvault, but they only have for .i386. Does anyone know where / how I can find Python2.4 for RHEL4 x64? If there is a better place to be asking this question, please let me know, and I will redirect my queries elsewhere. Thanks so much. Eric From ankitks.mital at gmail.com Fri Mar 28 01:38:48 2008 From: ankitks.mital at gmail.com (ankitks.mital at gmail.com) Date: Thu, 27 Mar 2008 22:38:48 -0700 (PDT) Subject: problem with sorting Message-ID: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> >>> dict = {'M':3, 'R':0, 'S':2} >>> print dict {'S': 2, 'R': 0, 'M': 3} now if I wanted sorted values in list, i am not able to do this >>> print dict.values().sort() None it returns None instead of [0, 2, 3] From castironpi at gmail.com Fri Mar 7 15:25:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 12:25:22 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: On Mar 7, 10:12?am, alex.pedwyso... at gmail.com wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... > > I want to be able to detect if they fail with error, I want to be able > to time them, and I want to be able to stop them if they run too > long. ?I cannot add code to the eval'd strings that will help me > accomplish this. > > Is there a good way to do this? ?I have it figured out for perl but > I'd rather use python if possible. > > Thanks for any assistance. How does this sound? Write back if it's way far off from what you want. for line in break in put on line break push in interactive console extra linebreak at function ends return list of functions? ... and I'll stop before I actually write it. Bets off! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Mar 19 06:04:54 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 19 Mar 2008 11:04:54 +0100 Subject: Need Help Starting Out In-Reply-To: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <47e0e546$0$30851$426a74cc@news.free.fr> jmDesktop a ?crit : > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. > > I want to use it for web building with database access. What do I use > for that? Does it matter what I use on the client side (mootools, or > whatever)? Your best bets are probably Django, Pylons or web.py. But you should learn enough of the core language itself before jumping in web stuff IMHO. From deets at nospam.web.de Thu Mar 27 03:59:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 08:59:00 +0100 Subject: last mouse movment or keyboard hit In-Reply-To: References: Message-ID: <6512egF2dik46U1@mid.uni-berlin.de> Ron Eggler schrieb: > Hi, > > I would like to get the time of the most recent human activity like a cursor > movement or a key hit. > Does anyone know how I can get this back to start some action after there > has been no activity for X minutes/seconds? Try hooking yourself into the OS screen-saver-code. Diez From arnodel at googlemail.com Thu Mar 13 19:45:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 16:45:49 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: <5d974a2f-a810-4882-8254-513f7b000fbe@e23g2000prf.googlegroups.com> On Mar 13, 11:29?pm, Dave Kuhlman wrote: > Arnaud Delobelle wrote: > > > 4. ?Both points above follow from the fact that foo.bar is really a > > function call that returns a (potentially) new object: in fact what > > really happens is something like > > Arnaud and Imri, too - > > No. ?foo.bar is *not* really a function/method call. It is. The keyword here is 'descriptor'. Maybe reading this will help: http://users.rcn.com/python/download/Descriptor.htm > > > > ? ? Foo.__dict__['bar'].__get__(foo, Foo). > > > So every time foo.bar is executed an object is (or may be) created, > > with a new id. > > > HTH > > I appreciate the help, but ... > > Actually, it does not help, because ... > > My understanding is that foo.bar does *not* create a new object. ?All it > does is return the value of the bar attribute of object foo. ?What new > object is being created? A bound method. Compare the following: >>> foo.bar > >>> Foo.__dict__['bar'].__get__(foo, Foo) > >>> > If I have: > > ? ? class Foo(object): > ? ? ? ? def bar(self): pass > > And I do: > > ? ? foo = SomeClass() > > then: > > ? ? foo.bar > > should return the same (identical) object everytime, no? ?yes? No. This is what I explained in my original reply. > I'm still confused. That's because you need to adjust your understanding. -- Arnaud From theller at ctypes.org Sun Mar 16 07:01:42 2008 From: theller at ctypes.org (Thomas Heller) Date: Sun, 16 Mar 2008 12:01:42 +0100 Subject: app runs fine with interpreter, but not under py2exe In-Reply-To: References: Message-ID: Doug Morse schrieb: > Peter, > > Genius! You nailed it -- thanks! > > py2exe is apparently getting confused by the fact that packages "Numeric" and > "numpy" both have files multiarray.pyd and umath.pyd. It copies just one of > each -- from $PYTHONHOME/Lib/site-packages/numpy/core -- and puts both of them > into the top-level of the created "dist" directory. Also, there are no such > files as multiarray.pyc and umath.pyc in my python installation, but py2exe > seems to create these (in the dist and dist/numpy/core directories) -- they > are small (e.g., 526 bytes) and I'm guessing that they are stubs that simply > point python to the matching .pyd that py2exe relocated. [...] > > Just for completeness and perhaps a bit of additional clarity, here's a > limited directory listing of what the steps in the previous paragraph produce: > > morse> find dist | egrep "(multia|umath)" | xargs ls -l > -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd > -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/multiarray.pyd > -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/umath.pyd > -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd > [...] > Is this something I should pursue getting the py2exe folks to fix / work with > them on fixing? In investigating this issue, I noted that a lot of other > py2exe problems seem to revolve around confusions when duplicate files exist > in different modules. I wouldn't thinking that getting py2exe to pay better > attention to the containing modules when building it's dependency tree would > be that difficult (or is it)? I have the impression that this issue may already be fixed in py2exe CVS but noone bothered to do a release. Here is the corresponding changelog entry: * build_exe.py: Patch from Grant Edwards, slightly adjusted: py2exe now renames the pyd files that it copies into the dist directory so that they include the package name. This prevents name conflicts. I have created installers and uploaded them (for testing!) to the starship: http://starship.python.net/crew/theller/py2exe-0.6.7.win32-py2.3.exe http://starship.python.net/crew/theller/py2exe-0.6.7.win32-py2.4.exe http://starship.python.net/crew/theller/py2exe-0.6.7.win32-py2.5.exe Please try them out. Thanks, Thomas From castironpi at gmail.com Fri Mar 7 18:41:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 15:41:06 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> Message-ID: On Mar 7, 4:39?pm, DBak wrote: > On Mar 7, 1:19?pm, "Chris Mellon" wrote: > > > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > > ?However I can't do this, because, of course, the name Tree isn't > > > ?available at the time that the classes _MT and _Node are defined, so > > > ?_MT and _Node can't inherit from Tree. > > > Not only is the name not defined, the class doesn't even exist yet. > > Yes, but, well - it certainly isn't usable yet, but some object (that > will be the class when it is finished) is being built (its __dict__ is > being populated, etc.) - so there's an object pointer available inside > the interpreter that could be put somewhere. ?But this is pedantic - > you're right, the class really isn't available until after the class > statement. There is no obvious solution-- What do you mean? If there are any at all, there is significant competition without clear winners. dict dictA: membA= 0 membB= 0 dict dictB: membC= 0 But, if you try to nest them, do you want the rest of the 'dict' at its outer level evaluated (that's your 'here is the crux'), or only that point so far? dict dictO: membA= 0 dict membB: membC= 0 membD= membE membE= 0 So, you can't refer to it at all. Especially if membE is defined in outer scope. > class Tree(object): > ...class _MT(Tree): Can you use a metaclass--- postponedinstantiating (since a class is an instance of A PARTICULAR THING.) And one of us could even lobby the wigs to put a metaclass in the standard library. What's the first to go? . If you could have any one metaclass in it, what would it be? The additions with the biggest pull are the ones that can make money really easily for Python speakers. Yes, money. How long is the workaround? In this case, if you want _MT in Tree (or the analogous pair, without loss of generality), you can still get it done (you know where to find me), thanks to Python. You just sacrifice how closely the final product (code), resembles the concept. Yes, that idea would make class definitions more explanitorily powerful-- have more acute explanations. But you need to assign meaning to a syntax element, which is done over time. If Python is a hybrid between C and ML, what is the hybrid between Python and XML? From castironpi at gmail.com Thu Mar 6 14:37:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 11:37:50 -0800 (PST) Subject: What is a class? References: Message-ID: On Mar 6, 1:03?pm, "johan.san... at gmail.com" wrote: > On Mar 5, 7:50 pm, castiro... at gmail.com wrote: > > > What is a class that is not a module? > > A class is a bag of stuff and a namespace :) > > J. A module is a bag of stuff and a namespace. Different stuff. { '__module__', '__weakref__'} From cokofreedom at gmail.com Tue Mar 18 12:19:58 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 18 Mar 2008 09:19:58 -0700 (PDT) Subject: globals() using For Loop against Generator Message-ID: <599451f4-7687-4d02-b546-a7fbb0f33c8d@h11g2000prf.googlegroups.com> if __name__ == '__main__': print "Globals (For Loop):" try: for i in globals(): print "\t%s" % i except RuntimeError: print "Only some globals() printed\n" else: print "All globals() printed\n" print "Globals (Generator):" try: print "\n".join("\t%s" % i for i in globals()) except RuntimeError: print "Only some globals() printed\n" else: print "All globals() printed\n" >>> >>> Globals (For Loop): >>> __builtins__ >>> Only some globals() printed >>> >>> Globals (Generator): >>> __builtins__ >>> __name__ >>> __file__ >>> i >>> __doc__ >>> All globals() printed >>> Why is it with a generator I get everything out but with a for loop I don't? I know that globals is not read-only but I would of expected the same behaviour from both... Any thoughts? From bavanikumar22 at gmail.com Wed Mar 26 05:47:07 2008 From: bavanikumar22 at gmail.com (bee) Date: Wed, 26 Mar 2008 02:47:07 -0700 (PDT) Subject: Hi iam bavani Message-ID: <9f1a51e7-333c-4b69-99be-91fe20fe7e52@s8g2000prg.googlegroups.com> Hi iam bavani life is the first gift love is thesecond understanding is the third **************************************** htt:"my profile 22 blogs pot.com ********************************************** username:bavanikumar22 *********************************************** From __peter__ at web.de Sun Mar 9 15:04:24 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Mar 2008 20:04:24 +0100 Subject: SV: Changing the size of a Button References: <63ifhtF277va7U1@mid.individual.net> <63iokhF284p4hU1@mid.individual.net> Message-ID: K Viltersten wrote: > What i wish to do is to affect the size > of the button but not due to change of > text but due to resize of the frame it > resides in. This is done by the layout manager, too: import Tkinter as tk root = tk.Tk() button = tk.Button(root, text="42") button.pack(fill=tk.BOTH, expand=True) root.mainloop() Alternatively, with a grid layout: button.grid(row=0, column=0, sticky="nsew") root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) Peter From troworld at gmail.com Tue Mar 4 10:04:49 2008 From: troworld at gmail.com (Tro) Date: Tue, 4 Mar 2008 10:04:49 -0500 Subject: Altering imported modules In-Reply-To: <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> References: <200803011856.27611.troworld@gmail.com> <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> Message-ID: <200803041004.50553.troworld@gmail.com> On Monday 03 March 2008, castironpi at gmail.com wrote: > On Mar 3, 5:09?pm, Tro wrote: > > On Sunday 02 March 2008, Paul McGuire wrote: > > > On Mar 2, 3:48?pm, Tro wrote: > > > > On Sunday 02 March 2008, Terry Reedy wrote: > > > > > "Tro" wrote in message > > > > >news:200803011856.27611.troworld at gmail.com... > > > > > > > > > > | Hi, list. > > > > > | > > > > > | I've got a simple asyncore-based server. However, I've modified > > > > > | the > > > > > > > > > > asyncore > > > > > > > > > > | module to allow me to watch functions as well as sockets. The > > > > > | modified asyncore module is in a specific location in my project > > > > > | and is imported > > > > > > > > > > as > > > > > > > > > > | usual from my classes. > > > > > | > > > > > | Now I'd like to use the tlslite library, which includes an > > > > > | asyncore mixin class. However, tlslite imports "asyncore", which > > > > > | doesn't include my own modifications. > > > > > | > > > > > | I'd like to know if it's possible to make tlslite load *my* > > > > > | asyncore > > > > > > > > > > module > > > > > > > > > > | without changing any of the tlslite code. > > > > > > > > > > If your module is also 'asyncore' and comes earlier in the search > > > > > path, I would expect the import to get yours. > > > > > > > > It's not. It has a package prefix like my.package.asyncore. I think I > > > > can either move my version of asyncore up a couple of levels or add > > > > the my.package directory to sys.path. > > > > > > > > My version of asyncore imports several functions from the built-in > > > > asyncore. Now that my version of it is imported as asyncore, how > > > > would it import the built-in version from python2.5/site-packages? > > > > > > > > Thanks, > > > > Tro > > > > > > What happens if you do "import my.package.asyncore as asyncore"? > > > > > > If that doesn't work (trying the simplest hack first), I know that > > > there are various hooks in the import mechanism that should help. > > > > In the classes that use my version of asyncore currently, that is how I > > do it. I import my version as "import my.package.asyncore as asyncore". > > In my asyncore module I do "import asyncore", because I override a few > > functions from the asyncore module included with python. However, if I > > were to add "my.package" to sys.path, then I wouldn't be able to "import > > asyncore" from my own asyncore module. I'd have to do some trickery with > > sys.path to take the "my.package" component out, import standard > > asyncore, readd the "my.package" component, so that other modules can > > "import asyncore" and get my version. > > > > Is there a way to import the standard python asyncore module in this > > scenario? > > > > Thanks, > > Tro > > > > > > Are you trying to interfere with the default module on only your > machine? Just rename it. If something in the std. lib. imports > asyncore, they get yours too that way. No, I'd like it to be a generalized solution and only for this one project. I'm trying to get it to work on any recent python installation out of the box, so I can't rename built-in modules. What I'm trying to do is allow a 3rd party module (tlslite) to import *my* version of asyncore without me going into tlslite's code and changing its import statement explicitly, but only for the scope of this one project. Thanks, Tro From pianomaestro at gmail.com Thu Mar 27 17:35:48 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Thu, 27 Mar 2008 14:35:48 -0700 (PDT) Subject: extension module initialization called twice Message-ID: <9d8ea768-4c19-497b-a043-74fd42e5dc7d@s37g2000prg.googlegroups.com> I have a cython extension module "mux" where the initialization is being called more than once (the initmux c function). I am wondering if my use of multiple threads causes this. Can't multiple threads share the same python module ? The threads are being created from an external C library. I just call PyEval_InitThreads on startup, and then acquire the gil from the c callbacks. Here is my gdb session: (gdb) break initmux Breakpoint 1 (initmux) pending. (gdb) break PyEval_InitThreads Breakpoint 2 at 0x80c2906 (gdb) run prod-foo.py Starting program: /usr/bin/python prod-foo.py (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [Thread debugging using libthread_db enabled] [New Thread -1210001216 (LWP 11155)] (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [Switching to Thread -1210001216 (LWP 11155)] Breakpoint 2, 0x080c2906 in PyEval_InitThreads () (gdb) c Continuing. Breakpoint 3 at 0xb787c919: file mux.c, line 6829. Pending breakpoint "initmux" resolved Breakpoint 3, initmux () at mux.c:6829 6829 __pyx_m = Py_InitModule4("mux", __pyx_methods, 0, 0, PYTHON_API_VERSION); (gdb) c Continuing. [New Thread -1419904112 (LWP 11158)] [New Thread -1420432496 (LWP 11159)] [New Thread -1420960880 (LWP 11160)] [New Thread -1421489264 (LWP 11161)] [New Thread -1422017648 (LWP 11162)] [New Thread -1422546032 (LWP 11163)] [New Thread -1424647280 (LWP 11164)] Breakpoint 3, initmux () at mux.c:6829 6829 __pyx_m = Py_InitModule4("mux", __pyx_methods, 0, 0, PYTHON_API_VERSION); (gdb) Simon. From ptmcg at austin.rr.com Sun Mar 2 11:53:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 2 Mar 2008 08:53:47 -0800 (PST) Subject: Python-based regular expression parser that allows patterns to call functions? References: Message-ID: On Mar 2, 8:41?am, Andrew Warkentin wrote: > I am writing a filtering HTTP proxy (the site ishttp://xuproxy.sourceforge.net/). I want it to be compatible with > Proxomitron (http://proxomitron.info/) filters. I need a regular > expression parser that allows patterns to call functions (or more > likely, class methods), to implement "matching commands" (look at the > Proxmitron documentation to see what I mean). Does anyone know if such a > library exists for Python, or do I have to write my own parser? Andrew - Pyparsing allows you to define parse actions that get called when element within a grammar are matched. These actions can update external data structures, modify the matched text, or can be used to provide additional semantic validation. Here's an example: from pyparsing import * integer = Regex(r"\b\d+\b") # could also be written as #~ integer = WordStart() + Word(nums) + WordEnd() # convert matched text to actual integer def cvt_to_int (tokens): return int(tokens[0]) # only accept integers < 100 def must_be_less_than_100(tokens): if (tokens[0]) >= 100: raise ParseException("only integers < 100 are allowed") # add value to running tally of matches def increment_tally(tokens): global running_total running_total += tokens[0] integer.setParseAction( cvt_to_int) integer.addParseAction( must_be_less_than_100 ) integer.addParseAction( increment_tally ) # could also be written as #~ integer.setParseAction( cvt_to_int, #~ must_be_less_than_100, #~ increment_tally ) running_total = 0 print integer.searchString("absdlkj 1 5 12 121 78 22") print running_total Prints: [[1], [5], [12], [78], [22]] 118 More info about pyparsing at http://pyparsing.wikispaces.com, plus more examples, and links to other doc sources. -- Paul From bearophileHUGS at lycos.com Sun Mar 23 21:42:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 23 Mar 2008 18:42:48 -0700 (PDT) Subject: On copying arrays References: Message-ID: <970005df-41e6-4867-acc7-b0bda1da0db0@f63g2000hsf.googlegroups.com> ernesto: best = list(test) may be faster than: best = [x for x in test] Bye, bearophile From bayer.justin at googlemail.com Wed Mar 26 15:39:25 2008 From: bayer.justin at googlemail.com (Justin S Bayer) Date: Wed, 26 Mar 2008 12:39:25 -0700 (PDT) Subject: distutils crashing: $MACOSX_DEPLOYMENT_TARGET mismatch Message-ID: Hi group, When starting a distutils script (which I mostly consider as a black box) distutils crashes with the following traceback: Traceback (most recent call last): File "pyrexcompile.py", line 50, in cmdclass = {'build_ext': build_ext}) File "/sw/lib/python2.5/distutils/core.py", line 125, in setup dist.parse_config_files() File "/sw/lib/python2.5/distutils/dist.py", line 366, in parse_config_files filenames = self.find_config_files() File "/sw/lib/python2.5/distutils/dist.py", line 329, in find_config_files check_environ() File "/sw/lib/python2.5/distutils/util.py", line 208, in check_environ os.environ['PLAT'] = get_platform() File "/sw/lib/python2.5/distutils/util.py", line 78, in get_platform cfgvars = get_config_vars() File "/sw/lib/python2.5/distutils/sysconfig.py", line 493, in get_config_vars func() File "/sw/lib/python2.5/distutils/sysconfig.py", line 378, in _init_posix raise DistutilsPlatformError(my_msg) distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now "10.3" but "10.5" during configure The script is used to trigger pyrex compilation. I am using Pyrex 0.9.6.4. I set the environment variable to 10.5 manually from the bash. I also hacked the distutils script and manually set it in os.environ to 10.5. Googling for the error message did not help a lot, either. I am running Mac OS X 10.5 on an Intel processor. I have distutils verison 2.5.1 running on a Python 2.5.2 installed via fink. Any help would be greatly appreciated! Regards, -Justin From __peter__ at web.de Fri Mar 7 03:02:55 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Mar 2008 09:02:55 +0100 Subject: the problem of import module References: <8db5d6fa-f582-4311-817d-17da26846a57@d21g2000prf.googlegroups.com> Message-ID: fts2012 at gmail.com wrote: > follow the dive into python > ----------------------------------------------------------------- >>>> import sys >>>> sys.path >>>> sys.path.append('E \achieve\book\diveintopython-pdfzh-cn-5.4b\diveintopythonzh-cn-5.4b\py') > ----------------------------------------------------------------- > I append the filepath of <>'s examples into > sys.path,but > ----------------------------------------------------------------- >>>> sys.path > ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', > 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat- > win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\ > \site-packages', 'E:\x07chieve\x08ook\\diveintopython-pdfzh-cn-5.4b\ > \diveintopythonzh-cn-5.4b\\py'] >>>> import fileinfo#fileinfo is a module in the path > > Traceback (most recent call last): > File "", line 1, in > import fileinfo > ImportError: No module named fileinfo > > ----------------------------------------------------------------- > Can anyone tell me the reason of the above and how to add paths to > python path except adding them in the enviroment path. > Thanks. The path you append to sys.path is not properly escaped: >>> "E:\archive" 'E:\x07rchive' # \a has become the single character chr(7) Use double backslashes or raw strings instead: >>> "E:\\archive" 'E:\\archive' >>> r"E:\archive" 'E:\\archive' When you print it the extra backslash will be gone: >>> print "E:\\archive" # \\ is the escape sequence for the backslash E:\archive Peter From mh at pixar.com Wed Mar 12 00:52:57 2008 From: mh at pixar.com (mh at pixar.com) Date: Wed, 12 Mar 2008 04:52:57 GMT Subject: best way to have enum-like identifiers? Message-ID: I currently have a 2-dim hash, indexed by two strings: template['py']['funcpre'] template['py']['funcpost'] ... but I would prefer to have these indexed by constants of some kind, since this seems a bit more natural: template[py][funcpre] template[py][funcpost] ... Currently I'm just putting this at the top of the file: py=1 funcpre=2 funcpost=3 ... but I'm curious if there's a better way of doing this, some kind of enum-like thing or somesuch. Many TIA! Mark -- Mark Harrison Pixar Animation Studios From andre.roberge at gmail.com Sat Mar 22 15:04:08 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 22 Mar 2008 12:04:08 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: On Mar 22, 3:48 pm, Arnaud Delobelle wrote: > jmDesktop writes: > > For students 9th - 12th grade, with at least Algebra I. Do you think > > Python is a good first programming language for someone with zero > > programming experience? Using Linux and Python for first exposure to > > programming languages and principles. > > I'm not from the US and I'm not sure what 9th/12th grade are, but if > you want to use programming to explore maths, er I mean math, have a > look at the sage project: > 9th grade roughly corresponds to 3e coll?ge and 10th/12th grade roughly correspond to the first three years of "le lyc?e" - although from my past teaching experience (as a physicist) in French, I have concluded that mathematics is taught at a higher level in France than it is in North America - simply looking at the various books available on given topics. > http://www.sagemath.org/ Sage is great. However, I think it is much too advanced for 9th/12th grade. Furthermore, the OP was looking for suggestion teaching *programming*, not math. Andr? > > -- > Arnaud From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 13:18:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 18:18:37 +0100 Subject: singleton decorator In-Reply-To: <1983c7ec-a7da-4fae-97a9-4f22cc2ea4c7@d4g2000prg.googlegroups.com> References: <1983c7ec-a7da-4fae-97a9-4f22cc2ea4c7@d4g2000prg.googlegroups.com> Message-ID: <47ebd6e4$0$19836$426a74cc@news.free.fr> r.grimm at science-computing.de a ?crit : > Hallo, > playing with the decorators from PEP 318 I found the elegant singleton > decorator. > > def singleton(cls): > instances = {} > def getinstance(): > if cls not in instances: > instances[cls] = cls() > return instances[cls] > return getinstance > > @singleton > class A: pass > (snip) > But I always get a syntax error declaring class A as singleton. > >>>> reload ( decorator) > Traceback (most recent call last): > File "", line 1, in ? > File "decorator.py", line 27 > class A: pass > ^ > SyntaxError: invalid syntax > > What's the problem with this code because it's only copied for the PEP > 318? > It doesn't work with python 2.4 and python 2.5. A pep is a proposal, not a feature documentation. As written in pep318, class decorators have not been implemented so far. They'll be implemented in 2.6 (more exactly: they are implemented in 2.6, but 2.6 is still alpha so far). From hgk at ieee.org Wed Mar 19 09:52:07 2008 From: hgk at ieee.org (=?ISO-8859-1?Q?Hans_Georg_Krauth=E4user?=) Date: Wed, 19 Mar 2008 06:52:07 -0700 (PDT) Subject: Speaking Text References: Message-ID: <18b17c14-717d-4cc6-b4e3-40157c9a7c0b@m34g2000hsc.googlegroups.com> On 19 Mrz., 13:41, David C. Ullrich wrote: > Mac OS X has text-to-speech built into the interface. > So there must be a way to access that from the command > line as well - in fact the first thing I tried worked: > > os.system('say hello') > > says 'hello'. > > Is there something similar in Windows and/or Linux? > (If it's there in Linux presumably it only works if there > happens to be a speech engine available...) > > David C. Ullrich In Windows -> pyTTS http://www.mindtrove.info/articles/pytts.html Regards Hans Georg From musiccomposition at gmail.com Mon Mar 3 23:01:33 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 3 Mar 2008 20:01:33 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > What are metaclasses? Depends on whether you want to be confused or not. If you do, look at this old but still head bursting essay: http://www.python.org/doc/essays/metaclasses/. Basically, the metaclass of a (new-style) class is responsible for creating the class. This means when Python sees class Foo(object): __metaclass__ = FooMeta class FooMeta(type): def __new__(cls, name, bases, dct): #do something cool to the class pass It asks FooMeta to create the class Foo. Metaclasses always extend type because type is the default metaclass. From gagsl-py2 at yahoo.com.ar Mon Mar 3 19:14:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 22:14:33 -0200 Subject: Import, how to change sys.path on Windows, and module naming? References: <820d6ac9-041a-4d8a-a444-d2978ad41ba4@p25g2000hsf.googlegroups.com> <300f1fa1-2e64-41b1-b8f3-aad87b9e6785@n58g2000hsf.googlegroups.com> Message-ID: En Mon, 03 Mar 2008 14:39:20 -0200, escribi?: > On 3 Mar, 17:12, bock... at virgilio.it wrote: > > Oops... I tried removing python25.zip from sys.path, and I can still > import packages from zip files ... Yes, python25.zip is in sys.path by default, not to enable zipimport (which is enabled by default, if zlib is available), but to allow the entire Python library to be distributed in a .zip When Python starts, it imports site.py (and a *lot* of other modules, too much for my taste); that script is responsible of building sys.path, adding lib/site-packages and looking for .pth files and so. Before that, sys.path contains a minimal set of dirs. If there were no .zip already in sys.path, site.py (and all the modules it uses) should exist on an actual directory already present on sys.path in order to be imported - so the entire library could not reside on a zip file. Having python25.zip in sys.path by default (*before* processing site.py) allows to distribute the whole std library (and possibly other packages too) in a single zip file. -- Gabriel Genellina From Afro.Systems at gmail.com Mon Mar 24 14:22:43 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Mon, 24 Mar 2008 11:22:43 -0700 (PDT) Subject: behavior varied between empty string '' and empty list [] Message-ID: <1d822b31-fd7a-47f2-abee-45226c6b0c26@e6g2000prf.googlegroups.com> while I can invoke methods of empty string '' right in typing (''.join(), etc.) I can't do the same with empty list example: >>> a = [1,2,3] >>> b = [].extend(a) >>> b >>> b = [] >>> b.extend(a) >>> b [1,2,3] I would not use b = a since I don't want changes on 'b' to apply on 'a' do you think this should be available on lists to invoke method directly? From mwilson at the-wire.com Sun Mar 2 07:25:18 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 02 Mar 2008 07:25:18 -0500 Subject: sqlite3 adaptors mystery References: Message-ID: Matej Cepl wrote: > Thanks for your help, but plain-text strings is not what > I wanted. The boolean variables was what I was after. See this > modified version of the script: > > #!/usr/bin/python > import sqlite3 > def adapt_boolean(bol): > if bol: > return "True" > else: > return "False" > > def convert_boolean(bolStr): > if str(bolStr) == "True": > return bool(True) > elif str(bolStr) == "False": > return bool(False) > else: > raise ValueError, "Unknown value of bool attribute > '%s'" % bolStr > > sqlite3.register_adapter(bool,adapt_boolean) > sqlite3.register_converter("boolean",convert_boolean) > > db = sqlite3.connect(":memory:") > cur=db.cursor() > cur.execute("create table test(p boolean)") > p=False > cur.execute("insert into test(p) values (?)", (p,)) > p=True > cur.execute("insert into test(p) values (?)", (p,)) > cur.execute("select p from test") > for (field,) in cur.fetchall(): > print field,type(field) > > The output here is: > > [matej at viklef dumpBugzilla]$ python testAdaptors.py False 'unicode'> > True > [matej at viklef dumpBugzilla]$ > > I thought that converter is there for just exactly this -- that > I would get back bool values not strings. > > Sorry for not being clear in the first run. Sorry about the misunderstanding. It seems you want db = sqlite3.connect("test.db", detect_types=sqlite3.PARSE_DECLTYPES) After this, the print shows False True Mel. From michael at stroeder.com Wed Mar 26 13:54:29 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Mar 2008 18:54:29 +0100 Subject: Some notes on a high-performance Python application. In-Reply-To: References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: >> ... >> >> Using MySQL as a queueing engine across multiple servers is unusual, >> but it works well. It has the nice feature that the queue ordering >> can be anything you can write in a SELECT statement. So we put "fair >> queueing" in the rating scheduler; multiple requests from the same IP >> address compete with each other, not with those from other IP addresses. >> So no one site can use up all the rating capacity. >> ... >> Does anyone else architect their systems like this? > > A Xen(tm) management system I've written at least shares this aspect in that > the RPC subsystem for communication between the frontend and the backends is > basically a (MySQL) database table which is regularily queried by all > backends that work on VHosts to change the state (in the form of a command) > according to what the user specifies in the (Web-)UI. I see nothing unusual with this: I vaguely remember that this database approach was teached at my former university as a basic mechanism for distributed systems at least since 1992, but I'd guess much longer... And in one of my projects a RDBMS-based queue was used for a PKI registration server (e.g. for handling the outbound CMP queue). IIRC Microsoft's Biztalk Server also stores inbound and outbound queues in its internal MS-SQL database (which then can be the bottleneck). Ciao, Michael. From forwardshortleg at gmail.com Wed Mar 5 20:08:38 2008 From: forwardshortleg at gmail.com (forwardshortleg at gmail.com) Date: Wed, 5 Mar 2008 17:08:38 -0800 (PST) Subject: Returning a byte buffer from C extension References: Message-ID: <9f3e185c-1328-47f8-b363-7efd895ee629@60g2000hsy.googlegroups.com> I just realized that I could do this as follows: static PyObject* GetByteBuffer(PyObject* self, PyObject* args) { char byteBuffer[100]; // do something to fill byteBuffer with values. return Py_BuildValue("s#", byteBuffer, numberOfBytesToReturn); } Sorry for the unnecessary distraction. Eknath On Mar 5, 4:42 pm, forwardshort... at gmail.com wrote: > Hello, > > I am new to Python programming. So, kindly excuse me if I don't use > correct terminology here below. > > I am trying to write an extension function that returns an array of > bytes as shown in the example below: > > static PyObject* GetByteBuffer(PyObject* self, PyObject* args) > { > char byteBuffer[100]; > > // do something to fill byteBuffer with values. > > return Py_BuildValue("y", byteBuffer); > > } > > Is this valid? I get a run time error in Python 2.5 (actually 2.6) and > Python 3.0 returns null terminated byte string. > My byte buffer may contain one or more zeros and I want is the entire > buffer regardless of its contents. How do I do it? > > Thanks, > > Eknath > > P.S: I know that 2.6 & 3.0 are not meant for a newcomers like me. > Unfortunately 2.5.2 and older for windows are built using MSCVC 6.0 > and they pose problems building extensions. From peanut.sam at googlemail.com Thu Mar 6 03:58:15 2008 From: peanut.sam at googlemail.com (Sam Garson) Date: Thu, 6 Mar 2008 08:58:15 +0000 Subject: Why """, not '''? In-Reply-To: <880dece00803052311p181c753cx9ae8338e954f9290@mail.gmail.com> References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> <880dece00803052311p181c753cx9ae8338e954f9290@mail.gmail.com> Message-ID: <4e1ac4910803060058k7657b1b0q2e9214b3e68cab8f@mail.gmail.com> The """ is for the docstring - if you need the user to know what theyre doing with the program you can create documentation, and what you put in those quotes wwill come up in that (I think) On 3/6/08, Dotan Cohen wrote: > > On 06/03/2008, Dan Bishop wrote: > > On Mar 5, 7:24 pm, Matt Nordhoff wrote: > > > > > Steven D'Aprano wrote: > > > > Surely it would depend on the type of text: pick up any random > English > > > > novel containing dialogue, and you're likely to find a couple of > dozen > > > > pairs of quotation marks per page, against a few apostrophes. > > > > > > > > That's an idea... Write a novel in Python docstrings. > > > > > > Or better yet, write in Python syntax. > > > > > > assert len([man for man in now_alive() if > > man.remembers(datetime.date(1775, 4, 18))]) <= HARDLY > > > > lantern_count = {'land': 1, 'sea': 2}.get(british.location(), 0) > > n_ch_twr.hang(Lantern() for _ in xrange(lantern_count)) > > > > if lantern_count: > > for village in middlesex: > > ride_thru(village) > > spread_alarm(village) > > > > That looks ported from lolcode. > http://lolcode.com/ > > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > -- > http://mail.python.org/mailman/listinfo/python-list -- I like kids, but I don't think I could eat a whole one... -------------- next part -------------- An HTML attachment was scrubbed... URL: From xu.mathena at gmail.com Mon Mar 24 00:26:59 2008 From: xu.mathena at gmail.com (NotGuru) Date: Sun, 23 Mar 2008 21:26:59 -0700 (PDT) Subject: always getting 'None' return value from PyObject_CallObject References: Message-ID: On Mar 23, 6:43?pm, Gal Aviel wrote: > Hello all, > > Kinda desperate over here .. Any help would be greatly appreciated ! > > I'm trying to embed a Python interpreter inside a Verilog simulator as a > SystemVerilog DPI application. The python side implements a few SV exported > tasks. I've got a thin C shared library as the dpi app; all it does it get the > task arguments from the simulator and hand those to the Python side using the > Python C API. > > I followed '5.3 Pure Embedding' under Python 2.5 documentation very closely. > > When calling a function defined in my module, the function executes Ok - it sees > the correct arguments being passed from C, and executes 100% - only the return > value is always 'None' (I tried returning a simple integer like '5' which > doesn't work). > I met similar problems before and I guess you can try to start from a minimum version that f takes no arguments. If your can't pass the right argument to f, it will always return none without any prompt. From castironpi at gmail.com Fri Mar 21 02:18:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:18:34 -0700 (PDT) Subject: seek into file-like for ipc Message-ID: <85a349dd-226f-423a-ae6d-742e013b816a@n58g2000hsf.googlegroups.com> Hive: How about a shared-memory/file-map to a Python object? Seek and tell. Has its own GIL? Raises Exceptions? Standard C++ prohibits returning pointer-to-members. File runs in its own thread, can callback host and raise its own exceptions, iow file process. Think live persistence. Client side producer proxies / delegates to the object. Ready, Go! From ron at example.com Thu Mar 27 01:02:40 2008 From: ron at example.com (Ron Eggler) Date: Thu, 27 Mar 2008 05:02:40 GMT Subject: last mouse movment or keyboard hit References: Message-ID: azrael wrote: > You can use wxPython. Take a look on the DemoFiles that you can > download also from the site. I remember that there has been a demo of > capturing mouse coordinates and also one example about capturing Which > key has been pressed at which time. > Just start the time, count the interactions of key strokes and mouse > gestures. Apply some statistics and voila. there it is. But that wouldn't be system wide, would it? :o > On Mar 26, 3:28?pm, Ron Eggler wrote: >> Gabriel Genellina wrote: >> > En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler >> > escribi?: >> >> >> I would like to get the time of the most recent human activity like a >> >> cursor >> >> movement or a key hit. >> >> Does anyone know how I can get this back to start some action after >> >> there has been no activity for X minutes/seconds? >> >> > Which platform? On non-ancient Windows versions, you can periodically >> > check GetLastInputInfo >> >> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winu... >> >> No, it would be for Linux and preferrably it would work on MacOS & >> Windows as well....is there anything? >> Thanks! >> -- >> chEErs roN -- chEErs roN From dickinsm at gmail.com Sat Mar 8 11:34:27 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 08:34:27 -0800 (PST) Subject: float / rounding question References: <13t456cmgfpdhbc@corp.supernews.com> Message-ID: On Mar 7, 11:23?pm, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote: > > Sorry to come in so late in this discussion. Although it is correct to > > say that many real numbers that have an exact decimal representation > > cannot be exactly represented in binary, that is no excuse to print 53.6 > > as 53.600000000000001. This is just lousy printing and the fact that > > this kind of question comes up every week shows that it is confusing to > > many people. > > Good. That's a feature, not a bug. Even so, it's not clear that Python's current behaviour couldn't be improved. I have a mild dislike of the lack of consistency in the following, which arises from Python arbitrarily stripping trailing zeros from the result returned by the C library functions: >>> 10.1 10.1 >>> 10.2 10.199999999999999 >>> 10.3 10.300000000000001 >>> 10.4 10.4 Piet van Oostrum's suggestion gives one nice way of dealing with this inconsistency. Unfortunately it doesn't look easy to implement this in practice: the main difficulty seems to be that to ensure float(repr(x))==x round-tripping you'd need to write routines to take control of both str -> float and float -> str conversions, not forgetting that those routines have to be reasonably fast, and work correctly on various non IEEE 754 platforms as well as the usual ones. This means adding, maintaining and testing hundreds of lines of complicated code, where right now a few C library calls suffice. Mark From darcy at druid.net Wed Mar 5 20:07:33 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 20:07:33 -0500 Subject: Please keep the full address In-Reply-To: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: <20080305200733.ba43c354.darcy@druid.net> On Wed, 5 Mar 2008 14:00:17 -0800 (PST) Mike Driscoll wrote: > What are you talking about? I didn't change the address at all. I'm > not even sure what you mean. Are you talking about the post subject > line (which I have never touched in any post)? If you're talking about > the OP's email address, that's Google's fault for cropping them. I'm talking about castironpi. I find his posts a waste of my time so I have them filtered out along with a few others and I also filter out responses by searching for his address in the body so changing it defeats that. However, if it is something that you have no control over I apologize for the noise. -- 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 pharmapsychotic at gmail.com Tue Mar 25 16:22:55 2008 From: pharmapsychotic at gmail.com (blackpawn) Date: Tue, 25 Mar 2008 13:22:55 -0700 (PDT) Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: > Does the Noddy example use GC (Py_TPFLAGS_HAVE_GC)? Container objects > must use the cycle GC or circular referneces aren't broken. Have you > tried calling PyGC_Collect() multiple times? Yeah the Noddy example is from "2.1.3 Supporting cyclic garbage collection" part of the Python docs. They list sample C and Python code which I cut and pasted with no changes and on Py_Finalize and app shut down it leaks the object. I know the garbage collector is tracking the object because it properly calls the traverse function but for whatever reason it never calls the clear function. Does anyone have experience with circular references and had success with it or the example in the docs? From castironpi at gmail.com Sat Mar 15 10:57:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 07:57:51 -0700 (PDT) Subject: Joseph Weizenbaum References: Message-ID: <9dd9167c-6d7c-4b48-b371-2bc7a4bc3722@p25g2000hsf.googlegroups.com> On Mar 15, 4:56?am, Arnaud Delobelle wrote: > On Mar 15, 5:47?am, Tim Roberts wrote: > > > > > > > Jeff Schwab wrote: > > >Roel Schroeven wrote: > > >> castiro... at gmail.com schreef: > > >>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: > > >>>>> Subject: RIP: Joseph Weizenbaum > > >>>>> Creator of Eliza: > > >>>>>http://www-tech.mit.edu/V128/N12/weizenbaum.html > > > >>>> How do you feel about creator of Eliza? > > > >>> What is Eliza? > > > >> Does that question interest you? > > > >Well played, sir. > > > >Earlier you said what is Eliza. ?Do you still feel that way? > > > I am embarrassed to say that this vaguely disrespectful exchange made me > > laugh out loud. > > Does it bother you that this vaguely disrespectful exchange made you > laugh out loud? No more than funerals, really, and weddings and birthday parties are kind of suspect too; I'm torn. How do you feel about them? From rui.maciel at gmail.com Mon Mar 31 12:40:40 2008 From: rui.maciel at gmail.com (Rui Maciel) Date: Mon, 31 Mar 2008 17:40:40 +0100 Subject: Is this a good time to start learning python? Message-ID: <47f1140e$0$735$a729d347@news.telepac.pt> Recently I woke up inclined to take up the task of learning another programming language. I've already dipped my toes in Perl (I've read online tutorials and wrote a couple of irrelevant pet projects) but, as the computers at my workplace only sport the python interpreter, it probably means that learning python will end up serving me better, at least in the short run. Plus, you know how Perl goes. So far the decision seems to be a no brainer. Yet, Python 3000 will arrive in a few months. As it isn't backwards compatible with today's Python, there is the risk that no matter what I learn until then, I will end up having to re-learn at least a considerable part of the language. To put it in other words, I fear that I will be wasting my time. At least that is what a clueless newbie believes. As this group is frequented by people who have more insight into all things pythonesque, what are your thoughts on this? Thanks for the help Rui Maciel From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 08:54:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 12:54:05 -0000 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: <13t7nfdmdtuf7be@corp.supernews.com> On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote: > (3) Informing codes above it about what's currently happening inside, > the thing is just a mundane report that might be useful to codes above > > Which might be a useful place to use SoftExceptions Okay, now we're getting somewhere. So, I have a function foo() which raises a HardException on error, but it also raises a SoftException if it wants to notify me of something "mundane". def foo(sequence): if args == []: raise SoftException("empty list") return len(args) Now, how do I use that? try: x = foo(something) except TypeError: print "you should pass a sequence" sys.exit() # unrecoverable error except SoftException: print "you passed an empty list" print x Am I close? But there's a problem. Once the SoftException is caught, execution will continue from the line "print x" -- but the function foo() never got a chance to actually return a result! In order to make that work, you would need a significant change to Python's internals. I don't know how difficult that would be, but I'm guess that it would be a lot of work for not much benefit. But even if that happened, it would mean that the one mechanism has TWO different effects: try: x = foo(sequence) except SoftException: print x # this is okay, because foo() did return except TypeError: print x # this is NOT okay, because foo() never returned That is a recipe for confusion. [...] > No, you're misunderstanding the purpose of Soft Exception, it's not for > silencing errors and not so much for exceptional cases. It's for the > more mundane tasks such as: [...] > Perhaps relabeling it as Warning, and renaming raise SoftException as > give Warning might make it more acceptable? Do you realise that Python already has a warnings module? > And I agree that the > probability for misuse is quite high, but the benefits is also quite > high, it's just that you can't see it since you're not used to using > such exceptions. The benefit of SoftExceptions lies mostly on the > regular programmings tasks, not the exceptional programming tasks > > Practical Example: > This example takes _case ideas_ from this simple gravity simulator > http://www.pygame.org/project/617/ BUT _no line of code is taken from > it_. I only give this link so you can easily know what the case is about > without lengthy explanation. > > A particle machine. > The particle machine calculates gravity created by the particles in a > field. Additionaly, it clumps together two particles that happens to be > near enough (less than the sum of their radiuses). > > The force two particle is expressing to each other is calculated with: > def calculateforce(P1, P2): > return (P1.mass - P2.mass) / distance(P1, P2) > > and this is done to every particle in the field against the current > particle. > > And the distance is calculated by: > def distance(P1, P2) > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > The problem happens when the distance is small enough and we want to > clump them together. > > A possible solution to this problem might be to check whether distance > is less than P1.radius + P2.radius in the calculateforce. But, this > obfuscate the code since we have to separate distance calculation from > the main formula (see !s), I don't agree that this obfuscates the code. > and this also insist that clumping be done on > force calculation level (see @s), shortly this piece of code is plain > bad: > def distance(P1, P2): > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > def calculateforce(P1, P2): > ## Separating this dist calculation into its own line is > ## necessary if we want to check the value of dist > ## Personally I think that's a bit obfuscated. > ## Well known formulas should be kept to one line if possible > ! dist = distance(P1, P2) > > if dist <= P1.radius + P2.radius: > ## Calling clump() here is bad, because > ## there are occasions where we only want to > ## calculate force but doesn't want to > ## clump it > @ clump(P1, P2) > else: > ! return (P1.mass - P2.mass) / dist I agree that calling clump() there is bad. > ## Codes calling calculateforce() > # Note: this code is located inside a loop > > F = calculateforce(P1, P2) > # Do something else, acceleration calculation, movement > calculations, etc > > > A better refactoring would be like this, but this requires calculating > distance twice (see !s): That's not better. Don't do it. > def distance(P1, P2): > return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > > def calculateforce(P1, P2): > ## Here distance is calculated once > ! return (P1.mass - P2.mass) / distance(P1, P2) > > ## Codes calling calculateforce() > # Note: this code is located inside a loop > > ## Here distance is calculated again > ! if distance(P1, P2) <= P1.radius + P2.radius: > clump(P1, P2) > break > F = calculateforce(P1, P2) > # Do something else, acceleration calculation, movement > calculations, etc And here's a way to do it that doesn't calculate anything twice, and doesn't require any exceptions: def calculateforce(P1, P2, dist): return (P1.mass - P2.mass)/dist And then for all pairs of particles: dist = distance(P1, P2) if dist <= P1.radius + P2.radius: clump(P1, P2) break F = calculateforce(P1, P2, dist) > A much better solution would be to use SoftException > def distance(P1, P2): > D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 > if D <= P1.radius + P2.radius: > raise Collision > return D But look at that line, "raise Collision". You could replace that with a callback function, and have the same result: DO_NOTHING = lambda : None def distance(P1, P2, callback=DO_NOTHING): D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 if D <= P1.radius + P2.radius: callback() return D That gives you virtually everything you want. If you want to ignore the signal, you simply call distance(P1, P2). If you want to do something on the signal, you set the callback. But frankly, the function distance() is NOT the place for that. Why should the distance() function decide what's a special result and what isn't? With your plan, you end up with functions like this: def distance(P1, P2): D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 if D <= P1.radius + P2.radius: raise Collision elif D > 1000: raise FredsModuleEscape elif D <= 1: raise MagnetismModuleUnity elif D == 0: raise AnotherFunctionSingularity elif ... ... ... else: raise NothingSpecialHappened return D Every module and function that calls distance() will start demanding that it raises the SoftExceptions that *it* wants, and before you know it, your distance() function has a hundred SoftExceptions covering all sorts of things that most people don't care about. No. This is a terrible idea. If the caller wants to treat a particular result as special, the caller should be responsible for detecting that, not the callee. > This results in a cleaner code. I don't agree. > And it also allow _other part of codes_ > that uses calculate distance and force to easily ignore or handle the > Collision Exception. And demand their own SoftExceptions. Okay, now that I understand your intention better, I've gone from -1 to -2 on the idea. I no longer think it's a bad idea, I think it's a TERRIBLE idea. Just out of curiosity, are there any existing languages that do something like this, or did you invent it yourself? -- Steven From castironpi at gmail.com Sun Mar 30 05:56:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 30 Mar 2008 02:56:59 -0700 (PDT) Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> <23908024-8174-4c3d-9d0d-70765834a331@s37g2000prg.googlegroups.com> Message-ID: On Mar 27, 4:22?pm, Miki wrote: > Hello Tim, > > > that looks nice, simple, and intuitive. thanks for thinking about it. > > Thanks, glad I could help. > > > Now to dive into some gui coding! > > IMO you can pull it off as a web application and then you won't need > to worry about cross-platform, > upgrades and all that interesting stuff. > Chapter 1 (001-200 200) > Chapter 2 (200-300 100) > ------ 001-300 300 ---- Does anyone want to see it under a graphics layer? From deets at nospam.web.de Sun Mar 30 08:36:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Mar 2008 14:36:01 +0200 Subject: problem with logic in reading a binary file In-Reply-To: References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> <659f2cF2dq5riU1@mid.uni-berlin.de> Message-ID: <659fpiF2f1e1hU1@mid.uni-berlin.de> > > Whatever you say. Can't express what your approval means to me! Diez From aahz at pythoncraft.com Thu Mar 6 16:24:47 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Mar 2008 13:24:47 -0800 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: In article <13sulsu4nbr2199 at corp.supernews.com>, Steven D'Aprano wrote: > >I accept my question about classes being singletons is not well-formed, >not even in my own mind. I guess one way of asking is, for any two class >objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? Even that stricture fails under the presence of metaclasses. ;-) But answering your real question, I don't remember off-hand the required sequence, but it is possible to import a class two different ways such that the classes are not the object. This can cause problems with e.g. pickle. Within a single module, given a class defined only once within that module, the class will be a singleton. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From sean at ardishealth.com Mon Mar 17 09:46:13 2008 From: sean at ardishealth.com (Sean Allen) Date: Mon, 17 Mar 2008 09:46:13 -0400 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: <319A6E0F-3517-4BFB-82A3-4577882765FC@ardishealth.com> On Mar 17, 2008, at 3:21 AM, Pradeep Rai wrote: > Thanks for your inputs !!! > > I have installed python v 2.5 on my Linux machine and executing the > tool again. > > I would like to share the memory status( using free -m command ) > before and after the execution of the tool. > > BEFORE EXECUTION > ================ > > total used free shared > buffers cached > Mem: 1006 148 858 0 > 8 92 > -/+ buffers/cache: 46 960 > Swap: 2047 0 2047 > > > AFTER EXECUTION > =============== > total used free shared > buffers cached > Mem: 1006 940 66 0 > 49 846 > -/+ buffers/cache: 44 962 > Swap: 2047 0 2047 > > > I am unable to find out why 66 MB system memory is left after tool > execution ? If python does not have memory leaks then where this > memory is going ? > the free you are looking at is not a good indication of 'actual memory available' in linux. the number you are intersted is this one: > -/+ buffers/cache: 46 960 vs > -/+ buffers/cache: 44 962 before execution you had 960 available for use by applications after execution you had 962 available. here is one of many pages explaining memory under linux: http://gentoo-wiki.com/FAQ_Linux_Memory_Management -------------- next part -------------- An HTML attachment was scrubbed... URL: From pydecker at gmail.com Sun Mar 2 09:47:17 2008 From: pydecker at gmail.com (Peter Decker) Date: Sun, 2 Mar 2008 08:47:17 -0600 Subject: Where's GUI for Python? In-Reply-To: References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: On Sat, Mar 1, 2008 at 10:04 PM, Bill wrote: > You should also take a look at wxGlade: > > http://wxglade.sourceforge.net/ > > which sits on top of wxPython: > > http://wxpython.org/ > > which wraps wxWidgets: > > http://www.wxwindows.org/ I have used wxGlade, and while it worked well enough, it didn't seem to fit my brain. I always found myself "thinking backwards" in order to guess how the tool needed me to do things. > I've found that wxGlade is more usable, currently, than Dabo in it's > visual layout tools that help you create the GUI for your apps. I didn't like that wxGlade generated code. If I later edited the code, I could no longer use wxGlade to refine the design. I've been amazed that so many people actually *like* working with wxPython-style code. I always hated it, and even tried a few times to make my own wrapper to insulate me from it (it was never very good). When I found out about Dabo, I took to it instantly and got much more productive very quickly. I was certain that everyone else would respond the way that I did. Obviously that's not what happened. I think that one of the reasons is that I never coded in C++, so the ALL_CAPS_CONSTANTS style and the whole getter/setter mentality seemed foreign to me. I'm a Python programmer, and don't have to switch gears when writing UI code anymore. I think if you like the sort of code that you need to use wxPython directly, you're probably perfectly happy to code at that level. For me, though, everytime I see raw wxPython code these days I cringe, and am thankful that I don't have to deal with it anymore. -- # p.d. From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:19:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:19:34 -0300 Subject: Setting the value of one cell in QTableWidget fills everything. References: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 12:01:01 -0300, Constantly Distracted escribi?: > I've just started PyQt programming and I've run into this little > problem. When I set the text of one cell in my table, all the other > cells fill with that value. > def filltable(self): > items=QtGui.QTableWidgetItem() Here you create a *single* object named item [why not "item" instead?] > for column in range(self.mytable.columnCount()): > for row in range(self.mytable.rowCount()): > items.setText("row: " + str(row) + " column: " + > str(column)) > self.mytable.setItem(row,column,items) Here you set the *same* item all over the table. -- Gabriel Genellina From guillermo.listas at googlemail.com Sun Mar 9 09:58:15 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Sun, 9 Mar 2008 06:58:15 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> Message-ID: <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> Mamma mia! My head just exploded. I've seen the light. So you only need to ?want? to have a protocol? That's amazing... Far beyond the claim that Python is easy. You define protocols in writing basically! Even my grandma could have her own Python protocol. Okay, so I think I know where's the catch now -- you must rely on the fact that the protocol is implemented, there's no way to enforce it if you're expecting a parrot-like object. You'd try to call the speak() method and deal with the error if there's no such method? Thanks a lot! Guillermo From thehazard at gmail.com Fri Mar 7 02:22:56 2008 From: thehazard at gmail.com (Daniel Bonekeeper) Date: Fri, 7 Mar 2008 04:22:56 -0300 Subject: Python GDB Wrapper In-Reply-To: References: Message-ID: On Fri, Mar 7, 2008 at 4:01 AM, Raja wrote: > Hi, > I am trying to develop a a GDB wrapper script in python which is > able to extract a stack trace and all relevant data. > > Has anyone does this before ? Even some basic idea or code as to how > to proceed would be great. > > Thanks, > Raja. > -- > http://mail.python.org/mailman/listinfo/python-list > You mean extract the information from core dump files that gdb interprets ? Check out stuff like ELF, Dwarf 3 (http://dwarf.freestandards.org/) and gdb sources. -- What this world needs is a good five-dollar plasma weapon. From gregory.bronner at lehman.com Fri Mar 7 09:44:46 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 7 Mar 2008 09:44:46 -0500 Subject: Edit and continue for debugging? Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2973@nypcmg1exms318.leh.lbcorp.lehman.com> I haven't seen much on this for a few years: I'm working on a GUI application that has lots of callbacks. Testing it is very slow and quite boring, as every time I find an error, I have to exit it, restart it, and repeat the series of clicks. It would be really amazing if python supported a reasonable form of edit and continue. Is there any way to do this? I'd like to be able to change my code and have it apply to a running instance of a class. I wonder if it would be possible to do this by configuring the interpreter to parse classes and functions rather than whole modules, and to re-parse as necessary; also to have byte-compiled modules be singletons rather than be standard reference counted objects. Thanks Gregory R. Bronner (212) 526-0102 gregory.bronner at lehman.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From ark at acm.org Mon Mar 10 10:29:48 2008 From: ark at acm.org (Andrew Koenig) Date: Mon, 10 Mar 2008 14:29:48 GMT Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: >> if type(a) is dict: >> print "a is a dictionnary!" > class MyDict(dict): > pass > a = MyDict() > type(a) is dict > => False isinstance(a, dict) => True So the question you need to answer is whether you want to determine whether an object is exactly of type dict, or whether it you are willing to accept types derived from dict also. From Bryan.Fodness at gmail.com Sat Mar 29 14:44:55 2008 From: Bryan.Fodness at gmail.com (Bryan.Fodness at gmail.com) Date: Sat, 29 Mar 2008 11:44:55 -0700 (PDT) Subject: problem with logic in reading a binary file Message-ID: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Hello, I am having trouble writing the code to read a binary string. I would like to extract the values for use in a calculation. Any help would be great. Here is my function that takes in a string. def parseSequence(data, start): group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] pos = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': data = value while start < length: group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = (group_num+element_num) if element == '\xfe\xff\x00\xe0': data = value while start < length: group_num = data[start:start+2] element_num = data[start+2:start+4] vl_field = data[start+4:start+8] length = struct.unpack('hh', vl_field)[0] value = data[start+8:(start+8+length)] start = start+8+length element = (group_num+element_num) return element, start, value else: return element, start, value else: return element, pos, value And, here is a sample string (I have split up and indented for readability). There is an identifier (\xfe\xff\x00\xe0) followed by the length of the nested values. '\xfe\xff\x00\xe0\x18\x02\x00\x00 -length=536 \n0q\x00\x02\x00\x00\x001 \n0x\x00\x02\x00\x00\x0010 \n0\x80\x00\x02\x00\x00\x004 \n0\xa0\x00\x02\x00\x00\x000 \x0c0\x04\x00\xe8\x01\x00\x00 \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 \n0\x86\x00\x10\x00\x00\x00127.378510918301 \x0c0\x06\x00\x02\x00\x00\x001 \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x0c\x00\x00\x001.629998e-1 \n0\x86\x00\x10\x00\x00\x0023.159729257873 \x0c0\x06\x00\x02\x00\x00\x004 \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x10\x00\x00\x001.26285318894435 \n0\x86\x00\x10\x00\x00\x00227.690980638769 \x0c0\x06\x00\x02\x00\x00\x003 \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ \189.182112099444 \n0\x84\x00\x10\x00\x00\x001.52797639111557 \n0\x86\x00\x10\x00\x00\x00263.433384670643 \x0c0\x06\x00\x02\x00\x00\x002 ') From stephenhorne100 at aol.com Mon Mar 17 10:35:49 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Mon, 17 Mar 2008 07:35:49 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: On Mar 17, 1:31 pm, Duncan Booth wrote: > A common explanation for this is that lists are for homogenous > collections, tuples are for when you have heterogenous collections i.e. > related but different things. I interpret this as meaning that in a data table, I should have a list of records but each record should be a tuple of fields, since the fields for a table usually have different forms whereas the records usually all have the same record layout. Makes sense, but not exactly *because* of the homogenous/heterogenous thing but rather because a record is smaller than a table, and a records component fields are more closely bound together than the records in a table. In short, adding, removing and overwriting records are essential operations (though Haskell programmers might disagree). Any modifications to records themselves can practically be handled as replacing one complete tuple with another. As a final note, I tend to implement tables as either lists of dictionaries, or lists of class instances. That way my fields are named. Its better in maintenance terms if I need to add new fields to the tables later on. From dickinsm at gmail.com Thu Mar 13 17:10:42 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 13 Mar 2008 14:10:42 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: On Mar 13, 3:48?pm, Alan Isaac wrote: > So maybe this is not as bad as I feared. ?What are some use > > cases that will clearly be harder (i.e., at least require > > a slightly elaborate wrapper) after this change? Sorting tuples, where the second item in the tuple should have the opposite ordering to the first is going to be a bit of a pain. Or even worse, where the ordering of the second item depends on the value of the first item in the tuple. For example, suppose that (for whatever contrived reason) you're representing integers in (sign, magnitude) format by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for negative) and i is a string representing the absolute value of the integer. So (0, '3') represents 3 (1, '14') represents 14 and you want to sort according to numeric value. One can certainly come up with a key that works, but it's not quite as straightforward as writing a custom __cmp__. This isn't a totally contrived example: the internal Decimal format isn't so different from this. Mark From castironpi at gmail.com Wed Mar 5 14:09:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 11:09:28 -0800 (PST) Subject: Using re module better References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> Message-ID: <1f63d5df-70e8-4eb9-81f7-7f2abb6f98b1@u10g2000prn.googlegroups.com> On Mar 5, 6:12?am, Tim Chase wrote: > > if (match = re.search('(\w+)\s*(\w+)', foo)): > > Caveat #1: ?use a raw string here > Caveat #2: ?inline assignment is verboten > > ? ?match = re.search(r'(\w+)\s*(\w*+)', foo) > ? ?if match: > > > ? ? field1 = match.group(1) > > ? ? field2 = match.group(2) > > This should then work more or less. ?However, since you know > there are two matches, you can just use > > ? ?field1, field2 = match.groups() > > If the regexp is one you plan to reuse (or call in a loop), you > can pre-compile it: > > ? ?r = re.compile(r'(\w+)\s*(\w*+)') > ? ?for thing in bunch_of_things: > ? ? ?m = r.search(thing) > ? ? ?if m: > ? ? ? ?field1, field2 = m.groups() > ? ? ? ?do_something(field1, field2) > > HTH, > > -tkc Opposed is to mimic MatchGroup that doesn't do anything, and returns from a non-match call, field1, field2 = match.groups() or [ Dummy, Dummy ], and similarly ...= [ None, None ]. On another note, why do people X, Y, and Z, including me, all hate to write a= b(); if a: a.something()? From mrstevegross at gmail.com Wed Mar 12 12:22:46 2008 From: mrstevegross at gmail.com (mrstephengross) Date: Wed, 12 Mar 2008 09:22:46 -0700 (PDT) Subject: Does __import__ require a module to have a .py suffix? Message-ID: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Hi all. I've got a python file called 'foo' (no extension). I want to be able to load it as a module, like so: m = __import__('foo') However, the interpreter tells me "No module named foo". If I rename it foo.py, I can indeed import it. Is the extension required? Is there any way to override that requirement? Thanks, --Steve From grante at visi.com Sat Mar 8 16:44:01 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 08 Mar 2008 21:44:01 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> Message-ID: <13t6251ep5bou67@corp.supernews.com> On 2008-03-08, K Viltersten wrote: >> What I really can't stand are the pointy-haired comment blocks >> at the beginnings of C/C++ functions that do things like tell >> you the name and return type of the function and list the >> names and types of the parameters. Gee, thanks. I never could >> have figured that out from looking at the source code itself. > > Coming from C++/Java camp i can't help noticing that in most > cases, when i'm using a class written by somebody else, i > don't want to see his/her code. I only want to know WHAT the > function does (is intended to be doing, at least). If you can't/don't look at the source file, then comments aren't going to help (except in the case of something like docstrings in Python). > I don't want to look at the source code (in some cases i can't > even see the code because it's compiled). I only care that > when i execute > > SomeType obj = SomeType(); > obj.aggregate(); > > the object gets aggregated. How it's done will be up to the > author. I'm just a user of the product. If you don't look at the source file, then I guess the question of whether comments are good, bad, or indifferent is irrelevent to you. > Now, i'm getting the signal that it's done in a different way > in Python. I'm not sure how you concluded that from this thread. I very rarely look at the source files for the standard library. I usually just look at the library reference document. The only times I look at the source code are the rare occasion that the function doesn't seem to be working correctly or when I can't understand what the reference docs are saying. The cases where I suspect the former generally turn out to be the latter. Comments in source code are for people maintaining the code, not for people using a standard library API (again, except for docstrings). -- Grant Edwards grante Yow! YOU PICKED KARL at MALDEN'S NOSE!! visi.com From bj_666 at gmx.net Sat Mar 15 02:03:45 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 06:03:45 GMT Subject: Handling global variables (Newbie) References: <613c51a0-d928-46b1-a04f-d0bc9fdcf453@a70g2000hsh.googlegroups.com> Message-ID: <641760F29qj9jU2@mid.uni-berlin.de> On Fri, 14 Mar 2008 12:19:18 -0700, MRAB wrote: > On Mar 13, 4:25 am, "David S" wrote: >> Hi, >> >> I have an error occurring at >> self.build_root = os.path.abspath(os.path.split(__file__)[0]) >> >> The error states 'NameError: global name '__file__' is not defined' >> >> In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get >> defined? >> > Do you perhaps mean '__name__'? I guess not. It makes more sense to apply path functions to `__file__` than to `__name__`. Ciao, Marc 'BlackJack' Rintsch From mnordhoff at mattnordhoff.com Mon Mar 10 03:46:30 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 10 Mar 2008 07:46:30 +0000 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> Message-ID: <47D4E756.7010609@mattnordhoff.com> Paddy wrote: > After profiling their may be other ways to remove a bottleneck, such > as > using existing highly-optimised libraries such as Numpy; Psycho, an > optimising interpreter that can approach C type speeds for Python > code; > and you could create your own C++ based libraries. > > You might want to ask the Mercurial development team how they got > their > impressive speed and functionality out of using mainly Python with > critical regions in C. - Or watch this: > http://video.google.com/videoplay?docid=-7724296011317502612 For what you do decide to rewrite in C, you can also use a language like Cython [1] (which is a fork of Pyrex [2]). It looks mostly like Python, and is translated to C without you having to write all of the boilerplate Python C API stuff. Of course, not quite as efficient well-tuned raw C, but much more pleasant to write. (FWIW, Bazaar [3], another VCS written in Python similar to Mercurial, has rewritten parts of two modules in Pyrex. Another one is in raw C, because that's what was contributed.) [1] [2] [3] -- From gagsl-py2 at yahoo.com.ar Sun Mar 16 19:25:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 21:25:18 -0200 Subject: BitVector read-from-file Question References: Message-ID: En Mon, 10 Mar 2008 14:06:07 -0200, Michael Wieher escribi?: > I'm trying to read in data from large binary files using BitVector > (thanks > btw, for whoever mentioned it on the list, its nice) > > I'll be reading the data in as requested by the user, in (relatively) > small > chunks as needed. > > Problem is I can't read the whole file in at once (its ridiculously > large) > and the object created by BitVector(filename="path") doesn't include a > "seek" function (to reset the filepointer) > > Any suggestions on how to this without > closing/reopening/reading(offset)/read(data) ? (thats a lot of overhead) (I understand that you don't want to create a BitVector from the whole file, but from many segments) You could try to circumvent BitVector oddities reading the file yourself and creating BitVector objects from the parts you are interested in. -- Gabriel Genellina From rockxuan at gmail.com Tue Mar 18 03:41:24 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:41:24 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <27e5d0a8-5257-400c-9568-e140b44f32c9@s19g2000prg.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From castironpi at gmail.com Sat Mar 8 15:27:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:18 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> <54abf8a6-6156-4663-903c-eb761e6b5148@h11g2000prf.googlegroups.com> Message-ID: > something something equivalence class. > The intern() builtin uses this approach: > > ? ?interned = {} > ? ?def intern(s): > ? ? ? ? if s in interned: > ? ? ? ? ? ? return interned[s] > ? ? ? ? interned[s] = s > ? ? ? ? return s If you've seen it before, and have the old one, return the old one. Do I have this straight? From jeff at schwabcenter.com Sun Mar 2 16:27:20 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 13:27:20 -0800 Subject: Book Recomendations In-Reply-To: References: Message-ID: > Ira Solomon wrote: >> I am an experienced programmer (40 years) . . . >> I'm interested in learning Python > js wrote: >> I wonder why nobody mension Python Cookbook yet . . . >> and Python Standard Library Because cookbooks are not supposed to be language introductions. They are collections of non-obvious techniques, for use by people already familiar with a core language and its standard libraries. Python in particular offers a lot for traditional programmers to wrap their minds around before considering cookbooks; Programming Python, for example, purports to help programmers think Pythonically, and probably belongs chronologically between the introductory books and the cookbooks. Many programmers coming from different languages tend (at first) to write code that makes experienced Pythonistas cringe. Effective use of the language depends on an understanding of its extremely dynamic nature, which can be tough to grasp for those of us coming from compiled language backgrounds. It seems to me, based purely on discussions seen in comp.lang.python, that even folks coming from relatively dynamic languages like Lisp often underestimate the level of run-time indirection provided by Python. One of the neat things about the Nutshell book is that it shows how even the process of resolving object attributes is potentially complicated, and how the new 'type' metaclass helps to at least make the process more consistent than with old-style objects. Experienced programmers first have to learn that an expression like "a.x" means something very different in Python from what it means elsewhere; then, they can begin leveraging these language features to do the sorts of things illustrated in the cookbooks. From mankyd at gmail.com Tue Mar 18 19:33:37 2008 From: mankyd at gmail.com (dave) Date: Tue, 18 Mar 2008 16:33:37 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> First I want to say thank you all for your timely replies. This is all good food for thought. I've been programming more many years, but fast graphics rendering is new territory for me. I'm hoping to fine something like a buffer_blit, where I can set all the pixels to change using basic operators, blit them all at once to a pixel buffer, then swap the visible buffer. Ideally it will only change the region of the pixel buffer that needs changing. Because I want layers, I would like to take advantage wherever possible of the available hardware features. I.E. ideally I am hoping that the layers can be textures in memory that get composited in hardware onto the screen. Maybe this is wishful thinking though? I'm also thinking that maybe I can reduce the number of active layers from N down to 3 - the active layer, the layers below it, and the layers above it. Obviously only the active layer needs any sort of sprite-like animations and it on this layer than response time is most important. Having to layer the top layers ontop of it may also play a factor but, as I suggested, I can merge them all together in one time and then use the merged result to layer on top of the active layer. I'm a little nervous about going the C/C++ route. It's been a few years since I used them, I'm new to Python, and jumping into coding Python extensions with C/C++ is not particularly palatable (though I'll do it if I have to.) > Any GUI toolkit will work if you find the low-level access > to their image memory buffers. That's another new step for me. Any ideas where to start? Thanks! From neilcrighton at gmail.com Mon Mar 10 05:31:37 2008 From: neilcrighton at gmail.com (Neil Crighton) Date: Mon, 10 Mar 2008 10:31:37 +0100 Subject: Problem with zipfile and newlines Message-ID: <63751c30803100231u682fc67ex7d5364c5555a07df@mail.gmail.com> I'm using the zipfile library to read a zip file in Windows, and it seems to be adding too many newlines to extracted files. I've found that for extracted text-encoded files, removing all instances of '\r' in the extracted file seems to fix the problem, but I can't find an easy solution for binary files. The code I'm using is something like: from zipfile import Zipfile z = Zipfile(open('zippedfile.zip')) extractedfile = z.read('filename_in_zippedfile') I'm using Python version 2.5. Has anyone else had this problem before, or know how to fix it? Thanks, Neil From bruno.desthuilliers at gmail.com Fri Mar 7 05:23:55 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 7 Mar 2008 02:23:55 -0800 (PST) Subject: Altering imported modules References: <47ce9279$0$27486$426a34cc@news.free.fr> Message-ID: <26f69931-c508-4a1e-8382-32b5b57158b3@60g2000hsy.googlegroups.com> On 6 mar, 21:29, Tro wrote: > On Wednesday 05 March 2008, Bruno Desthuilliers wrote: > > > > > Tro a ?crit : (snip) > > > I'd like to know if it's possible to make tlslite load *my* asyncore > > > module without changing any of the tlslite code. > > > Not sure this apply to your case (depends on how asyncore is implemented > > and the exact "modifications"), but monkeypatching is a possible solution. > > >http://en.wikipedia.org/wiki/Monkey_patch > >http://wiki.zope.org/zope2/MonkeyPatch > >http://mail.python.org/pipermail/python-dev/2008-January/076194.html > > Ooh. I didn't know this technique had a name. But that's basically how I'm > modifying the built-in asyncore in my own class. I override its poll() and > poll2() methods to do something extra. > > However, the issue with tlslite is that it imports the regular asyncore > instead of the one I wrote, One of us must be missing something here. The monkeypatch way is: # -- mypatch.py -- import BaseModule # backup original if we want to call it _original_something = BaseModule.something def my_patched_something(args): my_code_here_doing_stuff # eventually _original_something(args) more_code_here BaseModule.something = my_patched_something # -- main.py -- import mypatch # From now on, any other module calling # BaseModule.something will call my_patched_something. import other_module_using_BaseModule app_code_here > which means that I'd have to somehow monkeypatch > its "import" statement. I'm guessing that means simply monkeypatching both > the original asyncore module AND the tlslite module's asyncore attribute with > my own version. Unless there are some really strange things happening in tlslite and asyncore, if you import your monkeypatch before importing tlslite, you shouldn't have to touch anything in tlslite. Which is the whole point of monkeypatching. From hdante at gmail.com Mon Mar 31 19:35:38 2008 From: hdante at gmail.com (hdante) Date: Mon, 31 Mar 2008 16:35:38 -0700 (PDT) Subject: PyQt - How to prevent a dialog being resized? References: Message-ID: On Mar 31, 7:12 pm, Kelie wrote: > Hello, > > My question is as subject. I tried something like this and it doesn't > work. > > def resizeEvent(self, event): > self.size = event.oldSize() > > Any hint? > > Thank you. You should preset size hints: http://doc.trolltech.com/4.2/qwidget.html#minimumSize-prop From software at ginstrom.com Tue Mar 25 17:41:03 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Wed, 26 Mar 2008 06:41:03 +0900 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <47e92b07$0$15563$426a34cc@news.free.fr> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com><4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> <47e92b07$0$15563$426a34cc@news.free.fr> Message-ID: <032201c88ec0$ed4e3610$0203a8c0@MOUSE> > On Behalf Of Bruno Desthuilliers > >> for line in open("/etc/passwd"): > > NB : this idiom relies on the VM automatically closing files, > which is not garanteed on each and every implementation > (IIRC, jython won't do it). This is ok for Q&D throwaway > scripts targeting CPython, but should not go into production code. You're right. For production, I'd probably do this. def create_user_dirs(lines): for line in lines: pass # process lines here with open("/etc/passwd") as fp: create_user_dirs(fp) This has the benefit of allowing me to test create_user_dirs without touching the file system (by passing in a list of lines). Regards, Ryan Ginstrom From gagsl-py2 at yahoo.com.ar Tue Mar 18 22:55:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 23:55:00 -0300 Subject: automatically doing some cleaning-up by the process when the systems shuts down References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> Message-ID: En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh escribi?: > my programs runs as daemon and it does some logging .. when system > shuts down .. which may be done manually . i want my process do some > cleaning up automatically such as writing in to the log file when the > process terminats before the system shuts down handling the SYSTERM signal? -- Gabriel Genellina From mail at timgolden.me.uk Sun Mar 16 14:42:41 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 18:42:41 +0000 Subject: When file-like objects aren't file-like enough for Windows In-Reply-To: References: Message-ID: <47DD6A21.20609@timgolden.me.uk> William McBrine wrote: > Now, I have a similar problem with subprocess.Popen... The code that > works in Linux looks like this: > > source = urllib.urlopen(url) > child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) > try: > shutil.copyfileobj(child.stdout, self.wfile) > except: > kill(child.pid) > > But wfile isn't the problem this time; instead, it's the source: > > ... > child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=source) > File "C:\Python25\lib\subprocess.py", line 586, in __init__ > errread, errwrite) = self._get_handles(stdin, stdout, stderr) > File "C:\Python25\lib\subprocess.py", line 698, in _get_handles > p2cread = msvcrt.get_osfhandle(stdin.fileno()) > IOError: [Errno 9] Bad file descriptor > > How can I get around this, short of resorting to copying all of the input > before passing it to the child? It looks like you're stuck, I'm afraid. Basically you're falling foul of a documented limitation of the underlying socket file-likeness whose fileno () under Windows "cannot be used where a file descriptor can be used (such as os.fdopen())" I doubt you have any choice but to channel your urlopen data through some real file so it can make the stdin of the external process. TJG From darcy at druid.net Wed Mar 5 20:11:20 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 20:11:20 -0500 Subject: Identifying messages in a thread (was: Please keep the full address) In-Reply-To: <8763w094sy.fsf_-_@benfinney.id.au> References: <8763w094sy.fsf_-_@benfinney.id.au> Message-ID: <20080305201120.830e1c48.darcy@druid.net> On Thu, 06 Mar 2008 09:36:29 +1100 Ben Finney wrote: > > Those of us who identify the time wasters would also like to drop > > the responses to their posts and changing the address makes this > > impossible. > > Not at all. AFAIK the messages from Google mail correctly include the > 'In-Reply-To' field or the 'References' field in the message header. > So, you can know by those fields whether a message is part of a thread > you've previously identified. I don't want to have to tag every thread. I just want to *plonk* certain posters. Anyway, I'll live with Google's failings I guess. -- 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 castironpi at gmail.com Wed Mar 5 22:38:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:38:52 -0800 (PST) Subject: access to base class __init__ References: Message-ID: <3b5a3545-b1bf-4673-8a11-96368b76a629@n58g2000hsf.googlegroups.com> On Mar 5, 6:09?pm, sambo q wrote: > I got myself in jam trying to be too fancy with ?threading.Thread > Docs say / remind to call the base __init__ > but I can't fighure out how. > > --------------------------- > def main() > ..... > ? ? ls.listen(5) > ? ? key = ' ' > # ? ?while key != EXITCHARCTER: > ? ? while stop_serving == False: > ? ? ? ? cs, raddr = ls.accept() > ? ? ? ? print "Main_Thread: ",cs, raddr > ? ? ? ? nt = client_socket_handler( cs, raddr ) > ? ? ? ? print threading.enumerate() > ? ? ? ? key = getkey() > > # ? ?ls.close() > ? ? time.sleep(4) > ? ? print "Server Exiting." > > class client_socket_handler(threading.Thread): > ? ? def __init__(self, cs, remote_address): > ??????????????????????? > ? ? ? ? self.threading.Thread.__init__(self,self.socket_handler,None,None) > ? ? ? ? self.socket = cs > ? ? ? ? self.rhost_addr = remote_address > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > # ? ? ? ?t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) > # ? ? ? ?t1.start() > ? ? ? ? self.start() > ? ? ? ? print "client_socket_handler.__init__(): ", self.socket, > self.rhost_addr > ? ? ? ? print "client_socket_handler.__init__(): enumerate()", > threading.enumerate() > > ? ? def socket_handler( self, invar, indict ): > ? ? ? ? threadname = self.getName() > ? ? ? ? print "\"%s started\"" % threadname > ? ? ? ? print "client_socket_handler.socket_handler() invar: ", invar > ? ? ? ? instr = self.socket.recv( 500 ) > # ? ? ? ?print instr > ? ? ? ? req_lines = string.split( instr, "\r" ) > ? ? ? ? for line in req_lines: > ? ? ? ? ? ? line.strip( "\n") > ? ? ? ? print req_lines > ? ? ? ? print len( instr ) > > ---------------------------------- > > self.threading.Thread.__init__() > self.Thread.__init__() > ?? recall a= A() --> a.b() --> A.b( a ). What is A? threading.Thread. In other words, threading.Thread.__init__( *stuff ). From MartinRinehart at gmail.com Thu Mar 27 10:54:48 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 07:54:48 -0700 (PDT) Subject: Tkinter menus made easy Message-ID: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Writing Tkinter menu code used to be rather tedious, uninspiring work. I figured that I could delegate the job to a program: http://www.martinrinehart.com/articles/menus.py Run it. Then look at the source (bottom of file). There's a bit more doc in the doc comment at the top. Peer review is most welcome. From gagsl-py2 at yahoo.com.ar Mon Mar 10 00:45:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 21:45:46 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> <13t7smt4rn8rn32@corp.supernews.com> Message-ID: On 9 mar, 11:23, Steven D'Aprano wrote: > On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > > Okay, so I think I know where's the catch now -- you must rely on the > > fact that the protocol is implemented, there's no way to enforce it if > > you're expecting a parrot-like object. You'd try to call the speak() > > method and deal with the error if there's no such method? > > That's right. That's called "duck typing" -- if all you want is something > that quacks like a duck, then it doesn't matter if it actually is a duck > or not. In addition to duck typing, in some cases an explicit declaration may be useful: "I implement the Parrot protocol". The zope.interface package does that: there is a way to define interfaces (a set of methods any implementation must provide), and classes can assert "I implement this interface", and one can determine whether a class implements or not certain interface. See http://pypi.python.org/pypi/zope.interface Abstract Base Classes (ABC, for Python 3.0) provide a similar concept (but they're not the same thing). See http://www.python.org/dev/peps/pep-3119/ Of course there is some overlapping between all of these techniques - one should choose the best method in each case. -- Gabriel Genellina From adelagon at gmail.com Tue Mar 25 23:11:23 2008 From: adelagon at gmail.com (Alvin Delagon) Date: Wed, 26 Mar 2008 11:11:23 +0800 Subject: python hash() function Message-ID: <7a01f6c00803252011k638b16f6p45764b4dcf2a323@mail.gmail.com> Thanks for the fast replies guys. Very much appreciated. :) --- Alvin -------------- next part -------------- An HTML attachment was scrubbed... URL: From jon+usenet at unequivocal.co.uk Fri Mar 7 12:40:08 2008 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 7 Mar 2008 17:40:08 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> Message-ID: On 2008-03-07, D'Arcy J.M. Cain wrote: >> 2. You should use two spaces after a sentence-ending period. >> >> For heavens sake, why? I've always been obstructed by the double >> blanks but tolerated them. Now, that i read that it actually is a >> recommendation, i need to ask about the purpose. > > Like many things of this nature, the purpose is to follow the rules of > correct English usage. Well, no, it's to follow a particular person's choice out of the many and various competing rules of "correct English usage". Personally, I dislike double spaces after sentences, but it is not wrong to put them there any more than it is wrong not to put them there. Consistency is far more important (hence the rule, I presume). From wbsoft at xs4all.nl Thu Mar 27 09:56:50 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Thu, 27 Mar 2008 14:56:50 +0100 Subject: And the reverse? Does os also import os.path? In-Reply-To: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> References: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> Message-ID: <200803271456.50894.wbsoft@xs4all.nl> If i do >>> import os >>> os.path.abspath("bla") '/home/wilbert/bla' >>> it seems that just import os also makes available al os.path functions. But is that always true? Thanks, Wilbert -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandhi From aaron.watters at gmail.com Tue Mar 4 12:04:11 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 4 Mar 2008 09:04:11 -0800 (PST) Subject: why not bisect options? References: Message-ID: On Feb 29, 9:31 am, Robert Bossy wrote: > Hi all, > > I thought it would be useful if insort and consorts* could accept the > same options than list.sort, especially key and cmp..... Wouldn't this make them slower and less space efficient? It would be fine to add something like this as an additional elaboration, but I want bisect to scream as fast as possible in the default streamlined usage. -- Aaron Watters === dueling bumper stickers: use java/get rich use perl/get laid -- both equally sensible http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=wince From mail at timgolden.me.uk Mon Mar 31 03:50:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 31 Mar 2008 08:50:34 +0100 Subject: Finding Full Path to Process EXE In-Reply-To: References: <599236b4-038e-4d26-b1e9-a0a82c6f331d@t54g2000hsg.googlegroups.com> <47eea713$0$27902$426a74cc@news.free.fr> Message-ID: <47F097CA.1080103@timgolden.me.uk> misceverything at gmail.com wrote: > That's not a problem - I'm only interested in Win2k+. Thanks for the > caveat. > > On a similar note, is there a way (preferably using WMI) to get the > full path to the executable that has a port open (the same thing that > fport does, just implemented in Python)? It looks as though it might be possible with the (not installed by default) SNMP WMI provider. Haven't tried it myself, but there's some info here: http://groups.google.com/group/microsoft.public.win32.programmer.wmi/msg/761b8497826e4aea and here: http://msdn2.microsoft.com/en-us/library/aa393621(VS.85).aspx Alternatively, look around for the GetExtendedTcpTable functionality and so on. Sorry, this isn't really my area -- all I've done here is to let my fingers do the walking. TJG From robin at reportlab.com Wed Mar 19 12:24:46 2008 From: robin at reportlab.com (Robin Becker) Date: Wed, 19 Mar 2008 16:24:46 +0000 Subject: csv.Sniffer - delete in Python 3.0? In-Reply-To: <18401.13509.344107.988906@montanaro-dyndns-org.local> References: <18401.13509.344107.988906@montanaro-dyndns-org.local> Message-ID: <47E13E4E.5030306@chamonix.reportlab.co.uk> skip at pobox.com wrote: ........ > > I would be happy to get rid of it in 3.0, but I'm also aware that some > people use it. I'd like feedback from the Python community about this. If > I removed it is there someone out there who wants it badly enough to > maintain it in PyPI? ...... sounds like we really need import ai info = ai.guess_what_this_is('crummy.csv') but I suspect that won't arrive before py5000 I use csv, but almost always with tab or comma separation and \r\n line terminators. -- Robin Becker From sturlamolden at yahoo.no Sat Mar 15 11:40:06 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 08:40:06 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: <5359a380-7c78-43f3-b18b-88ea50d98556@h11g2000prf.googlegroups.com> On 28 Feb, 02:24, Steven D'Aprano wrote: > Python doesn't do call by reference. Nor does it do call by value. Please > pay no attention to anyone who says it does. Exactly. Python pass variables the same way as Lisp, which is neither "call-by-value" (cf. C) nor "call-by-reference" (cf. Fortran). The Python equivalent of "pass by reference" is a function that returns its arguments to the caller: def foobar(arg1, arg2, arg3): # Mutate an object shared with the caller. # I.e. calling convention cannot be not "pass-by-value" arg1.whatever = 1 # Rebind variables in the local namespace. # I.e. calling convention cannot be "pass-by-reference" arg1, arg2, arg3 = 1, 2, 3 # Return rebound variables to achieve the effect of # "pass-by-reference": return (arg1, arg2, arg3) # Call the function foobar, and rebind its arguments to its # return values: arg1, arg2, arg3 = foobar(arg1, arg2, arg3) From driedel at printingforsystems.com Wed Mar 12 09:57:23 2008 From: driedel at printingforsystems.com (David P. Riedel) Date: Wed, 12 Mar 2008 09:57:23 -0400 Subject: problem with Python 2.5.2 and gcc 4.3 Message-ID: <7jRBj.20981$QC.15171@newsfe20.lga> Hi I tried building Python 2.5.2 using gcc 4.3.0. The build completes with no problems but when I run 'make test', I get a segfault part way through the test run. here is the last part of the output from make test test_softspace test_sort test_sqlite test_sqlite skipped -- no sqlite available test_startfile test_startfile skipped -- cannot import name startfile test_str make: *** [test] Segmentation fault Has anyone else seen this? Thanks Dave Riedel From castironpi at gmail.com Fri Mar 7 20:32:51 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 17:32:51 -0800 (PST) Subject: Nested phrases [was Re: Want - but cannot get - a nested class to inherit from outer class] References: <18b456bf-bc3d-45f6-af92-369e01e0f426@o77g2000hsf.googlegroups.com> <13t3o20lbtipica@corp.supernews.com> Message-ID: <0997e5bc-2328-4914-b3a4-d96ba90a07cf@m3g2000hsc.googlegroups.com> On Mar 7, 6:39?pm, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 14:26:25 -0800, castironpi wrote: > > Humans have enormous "mental stacks"--- the stacks the contexts the > > speakers speak in push things they're hearing on to. > > This is not true. Oh yeah. (See below.) > Human beings have extremely shallow mental stacks, limited by short-term > memory. Most people are capable of keeping seven, plus or minus two, > items in short term memory at once. Any more than that and they are > subject to fading away or being over-written. > ? ? efficiency expert by the company through. > ? ? Remarkable is the rapidity of the motion of the wing > ? ? of the hummingbird. Oh, you mean hummingbird wing motion rapidity remarkability! How - could- I! 'Stack' may have been the wrong word. I probably meant 'intermodal recognition': the "Ah yes, I know it" response. But whether that's related to our tool-bearer capacity, isn't something you can test all that easily. What animals encounter something they had a use for once, and forget what? The breadth of objects in, say, a leopard's representation table* (working term), doesn't include chisels and footballs. Nothing is its favorite football, and a football isn't its favorite anything. What are its favorites? * Proposition table is clearly wrong. But given the human ability to touch an object, then open eyes, and identify which it touched might suggest 'intermodal recognition table', 'resemblance table', or 'value table'. How about resemblance-value? It at least would explain our susceptibility and reaction to greedy traps and shock: it's a the shock and greedy trap susceptibility and reaction of ours explanation. That is, how close something you like is to something you like..... and how much you like it. How much you like and how close something is... . Monotonically decreasing bivariate, delta> 0 => value( object, prior value+ delta )< value( object, prior value ) & value( object+ delta, prior value )< value( object, prior value ). ... which, by the way, should answer Archimedes' riddle: can you step in the same river? By degree. You're downstream and know it. Nota bene, how fast we can recall a song we even haven't heard in years we hear a snippet of, and not even from the overture. Given a 'symbol' that comes over a channel, in baud, our hash function maps it to a value close to previous hashings of it--- we merely search nearby memories and it's recognized. Odd! From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 15:47:08 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 21:47:08 +0100 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: References: <47c93bb8$0$874$ba4acef3@news.orange.fr> <47c990b9$0$899$ba4acef3@news.orange.fr> Message-ID: <47c9c25a$0$907$ba4acef3@news.orange.fr> Hi! Thank you for return. I will uninstall+reinstall Pyscripter. @-salutations -- Michel Claveau From userprogoogle-139 at yahoo.co.uk Wed Mar 19 08:04:05 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Wed, 19 Mar 2008 05:04:05 -0700 (PDT) Subject: Need Help Starting Out References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> <47e0e546$0$30851$426a74cc@news.free.fr> Message-ID: <13a8683f-6675-444d-a483-ea439d9c48d2@u69g2000hse.googlegroups.com> > Your best bets are probably Django, Pylons or web.py. But you should > learn enough of the core language itself before jumping in web stuff IMHO. Yes, a good point. If you are looking for general info then then "Dive Into Python" (a link is on the Python website) is a good start for people who are familiar with other programming languages. Otherwise I also found "Python in a Nutshell" useful. rod From dieterv at optionexplicit.be Sun Mar 30 06:49:42 2008 From: dieterv at optionexplicit.be (Dieter Verfaillie) Date: Sun, 30 Mar 2008 12:49:42 +0200 Subject: PyGTK localisation on Win32 In-Reply-To: <9c795bfa-b2a1-4c72-bc69-0f5664c0d3e1@i12g2000prf.googlegroups.com> References: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> <9c795bfa-b2a1-4c72-bc69-0f5664c0d3e1@i12g2000prf.googlegroups.com> Message-ID: <1206874182.4245.8.camel@PO001> On Thu, 2008-03-27 at 05:21 -0700, Sukhov Dmitry wrote: > I have the same problem. I did all as you wrote. gettext translations > do work fine. But translations in glade does not work. > > The only way to turn it on is to set environment variable LANG > explicitly before program run: > set LANG=ru_RU > python test.py Yep, from python 2.4 on, os.environ changes only work within python and no longer apply to low level c stuff on win32. Luckily, it's still possible to force environment variables through the kernel32.SetEnvironmentVariableW and msvcrt._putenv functions. Put the attached locale module in a libi18n package and use like this: #!/usr/bin/env python from libi18n import locale locale.fix_locale() del locale hth, Dieter -------------- next part -------------- A non-text attachment was scrubbed... Name: locale.py Type: text/x-python Size: 13405 bytes Desc: not available URL: -------------- 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 stef.mientki at gmail.com Sat Mar 1 05:46:40 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 01 Mar 2008 11:46:40 +0100 Subject: invert or not ? Message-ID: <47C93410.9050005@gmail.com> hello, from the manual I read that a bitwise inversion should be done by invert. But from some experiments I see that not works equally well. Is this coincidence ? (The disadvantage of invert is that I've to import operators) thanks, Stef From aaron.murray at gmail.com Sun Mar 16 10:31:00 2008 From: aaron.murray at gmail.com (Aaron) Date: Sun, 16 Mar 2008 07:31:00 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <1327e484-be39-4b1e-af1c-a0cbbfb27441@d45g2000hsc.googlegroups.com> > In my opinion, open spaces should have had greater status and billing, > with eyes-forward talks and vendor sessions offered only as possible > alternatives. Especially, vendor sessions should not be presented as > "keynotes" during plenary sessions. I think it took a little while > for people to catch on to the idea that they could have control of > their own experience through the open spaces and that the main > offerings were not the only option. This is an excellent suggestion and observation. Sold sponsorships are fine as long as they are billed as such. Labels on the vendor speeches indicated they were sold as ad space would be great, as well as more strongly emphasizing the ad hoc discussion spaces. From mhwalker at shaw.ca Tue Mar 4 02:45:31 2008 From: mhwalker at shaw.ca (Mike Walker) Date: Tue, 04 Mar 2008 07:45:31 GMT Subject: Command line arguments in Windows In-Reply-To: References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: "Mark Tolonen" wrote in message news:of6dnVTvVvGtalHanZ2dnUVZ_uCdnZ2d at comcast.com... > > From the command line, the 'ftype' and 'assoc' commands can be used > view how an extension is handled: > > C:\>assoc .py > .py=Python.File > > C:\>ftype Python.File > Python.File="C:\Python25\python.exe" "%1" %* > > My guess is your command line looks something like this: > > Python.File="C:\Python25\python.exe" "%1" > > The script name is being passed, but not the rest of the arguments. > I vaguely remember seeing this on an older version one of ActiveState's > ActivePython installers. What version of Python are you running? > > --Mark > Here is the output from the commands you listed which looks right to me. C:\>assoc .py .py=Python.File C:\>ftype python.file python.file="C:\Python25\python.exe" "%1" %* I am using Python 2.5.2 from http://www.python.org/ running on Windows Vista. Would ActiveState's version be a better choice here? ~Mike From robert.kern at gmail.com Mon Mar 24 15:13:40 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Mar 2008 14:13:40 -0500 Subject: New to group In-Reply-To: <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> Message-ID: pythonnubie wrote: > On Mar 24, 11:57 am, Jeff wrote: >> What does the code look like? > > # Random Access > # Demonstrates string indexing > # Michael Dawson - 1/27/03 > > import random Make sure that you do not have a random.py module in the current directory. Python checks the current directory for modules before the standard directories. -- 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 castironpi at gmail.com Thu Mar 13 12:05:39 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 09:05:39 -0700 (PDT) Subject: What's Going On? References: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> <63sgh6F28j923U1@mid.uni-berlin.de> Message-ID: <45fe5ddf-e747-46b2-bae3-1dbb6d494b52@m3g2000hsc.googlegroups.com> On Mar 13, 6:12 am, "Diez B. Roggisch" wrote: > MartinRineh... at gmail.com wrote: > > (Accompanied by Marvin Gaye) > > >>>> def f(list=[0]): > > ... list[0]+=1 > > ... return list[0] > > ... > >>>> f() > > 1 > >>>> f() > > 2 > >>>> f() # 'list' is a name bound to a list (mutable) so this makes sense > > 3 > >>>> f([5]) > > 6 > >>>>f() # What's Going On? > > 4 > > That the same default argument is mutated? What did you expect, that it got > replaced by you passing another list? That would kind of defy the meaning > of default-arguments, replacing them whenever you call a function with > actual parameters. f( ite, itr= ite.__iter__ ). Case 1: 'ite' is bound in outer scope. Case 2: not. function(code, globals[, name[, argdefs[, closure]]]) The optional argdefs tuple specifies the default argument values. TypeError: __defaults__ must be set to a tuple object >>> import functools >>> def k(): ... print( 'k call' ) ... >>> class GT: ... def __init__( self, arg ): ... self._arg= arg ... >>> def latebound( fun ): ... @functools.wraps( fun ) ... def post( *ar ): ... lar= list( fun.__defaults__ ) ... for i, a in enumerate( lar ): ... if isinstance( lar[ i ], GT ): ... lar[ i ]= eval( a._arg) ... return fun( *( list( ar )+ lar ) ) ... return post ... >>> @latebound ... def f( ite, itr= GT('k()') ): ... return itr ... >>> f( 2 ) k call >>> f( 2 ) k call >>> f( 2 ) k call >>> Furthermore, ... >>> @latebound ... def f( ite, itr= GT('ar[0]+ 1') ): ... return itr ... >>> f( 2 ) 3 >>> f( 2 ) 3 >>> f( 2 ) 3 >>> Unfortunately, ... >>> @latebound ... def f( ite, itr= GT('ite+ 1') ): ... return itr ... >>> f( 2 ) Traceback (most recent call last): File "", line 1, in File "", line 7, in post File "", line 1, in NameError: name 'ite' is not defined >>> The moral of the story is, wouldn't it be nice if wrappers could access the post-invocation bindings of the wrappee's internal variables? Certainly the 'TypeError: __defaults__ must be set to a tuple object' is unnecessarily restrictive: let it be a mutable, or, if it's not a tuple, call it. Just add a __call__ method to that tuple that does nothing, if a type-test isn't faster-- perhaps even a null __call__ which does -actually- nothing. (Why is __defaults__ None when empty, not an empty tuple?) What are the use case proportions of function-static vs. call-time evaluation? Function-static is nice in that it keeps objects floating around with the function, both in information design, and in encapsulation. They both have easy workarounds: >>> import functools >>> def auto( fun ): ... @functools.wraps( fun ) ... def post( *ar ): ... return fun( post, *ar ) ... return post ... >>> @auto ... def f( self ): ... print( self.ite ) ... >>> f.ite= [] >>> >>> f() [] >>> f.ite.append( 2 ) >>> f() [2] @auto adds the binding function to its called parameter list, which is nice if the function will change names ever-- that is, become bound to other variables-- because its statics still stay with it, and because it's not a global either. >>> g= f >>> del f >>> g() Traceback (most recent call last): File "", line 1, in File "", line 4, in post File "", line 3, in f NameError: global name 'f' is not defined But on the other hand, if the Python community on the whole wants to keep the status quo, >>> def f( ite, itr= None ): ... if None is itr: ... itr= ite+ 1 ... return itr ... >>> f( 2 ) 3 >>> f( 2 ) 3 >>> f( 2 ) 3 isn't so bad. (If you think it is, lobby!) @latebound is a good compromise. It keeps the information in the right place, but takes a little redundancy if the evalled expression refers to another variable, and but costs the additional GT class, and adds an O( n ) argument-length boilerplate rearrangement. @auto frees us to allow a different behavior to default parameters while keeping both statics and call-times explicit, keeping the information in the right place, but it's a change in the language. Lastly, we have: >>> @late( itr= 'ite+ 1' ) ... def f( ite, itr= latearg, j= 0 ): ... return itr, j ... >>> print( f( 2 ) ) (3, 0) Proof of concept: import functools latearg= object() def late( **kw ): def pre( fun ): _defs= fun.__defaults__ if None is _defs: _defs= () _names= fun.__code__.co_varnames _deflen= len( _defs ) _namelen= fun.__code__.co_argcount for k in kw: if k not in _names: raise TypeError( 'Non-parameter' ' keyword \'%s\' in \'late\'' ' call.'% k ) print( _defs ) print( _names ) print( _deflen ) for a, b in zip( _names[ -_deflen: ], _defs ): if b is latearg and a not in kw: raise TypeError( 'Non-bound' ' latearg \'%s\' in \'late\'' ' call.'% k ) @functools.wraps( fun ) def post( *ar ): _arglen= len( ar ) _defleft= _namelen- _arglen _defused= () if _defleft: _defused= _defs[ -_defleft: ] _lar= list( ar+ _defused ) _funargs= {} for i, a in enumerate( ar ): _funargs[ _names[ i ] ]= a for k, v in kw.items(): if k not in _names: raise TypeError( 'Not all latearg' ' arguments bound in call' ' of \'%s\''% fun.__name__ ) _place= _names.index( k ) if _place>= _arglen: _lar[ _place ]= eval( v, globals(), _funargs ) if latearg in _lar: raise TypeError( 'Not all latearg' ' arguments bound in call' ' of \'%s\''% fun.__name__ ) return fun( *_lar ) return post return pre @late( itr= 'ite+ 1' ) def f( ite, itr= latearg, j= 0 ): return itr, j assert f( 2 )== ( 3, 0 ) assert f( 2, 0 )== ( 0, 0 ) assert f( 2, 0, 1 )== ( 0, 1 ) assert f( 2, 1 )== ( 1, 0 ) To complete 'post' (**kw not shown) is left as an exercise to the reader. From bj_666 at gmx.net Tue Mar 25 13:08:28 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Mar 2008 17:08:28 GMT Subject: Does python hate cathy? References: Message-ID: <64spscF2derd7U3@mid.uni-berlin.de> On Tue, 25 Mar 2008 14:58:51 +0000, Edward A. Falk wrote: > In article , > Patrick Mullen wrote: > >>Then again, I can count the number of times I have ever needed __del__ >>with no fingers (never used it!). Still, quite interesting to >>explore. > > I used it once, for an object that had a doubly-linked list. > The __del__() method walked the list, setting all the elements' > prev/next pointers to None to make sure the elements of the list would > get garbage-collected. Without the `__del__()` the elements would get garbage collected just fine. If you don't want to wait until the garbage collector in CPython detects the cycle, you can use `weakref`\s for one of the two "pointers" in each element. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Thu Mar 13 17:35:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Mar 2008 14:35:46 -0700 (PDT) Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup References: <47d97288$0$36363$742ec2ed@news.sonic.net> Message-ID: <8c3f8c61-6c22-4a4f-a396-ddcce337319b@h11g2000prf.googlegroups.com> On Mar 14, 5:38 am, John Nagle wrote: > Just noticed, again, that getattr/setattr are ASCII-only, and don't support > Unicode. > > SGMLlib blows up because of this when faced with a Unicode end tag: > > File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag > method = getattr(self, 'end_' + tag) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' > in position 46: ordinal not in range(128) > > Should attributes be restricted to ASCII, or is this a bug? > > John Nagle Identifiers are restricted -- see section 2.3 (Identifiers and keywords) of the Reference Manual. The restriction is in effect that they match r'[A-Za-z_][A-Za-z0-9_]*\Z'. Hence if you can't use obj.nonASCIIname in your code, it makes sense for the equivalent usage in setattr and getattr not to be available. However other than forcing unicode to str, setattr and getattr seem not to care what you use: >>> class O(object): ... pass ... >>> o = O() >>> setattr(o, '42', 'universe') >>> getattr(o, '42') 'universe' >>> # doesn't even need to be ASCII >>> setattr(o, '\xff', 'notA-Za-z etc') >>> getattr(o, '\xff') 'notA-Za-z etc' >>> Cheers, John From kyosohma at gmail.com Mon Mar 10 14:29:12 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 11:29:12 -0700 (PDT) Subject: lowercase u before string in "python for windows" References: <3ec088d3-b86d-49b2-a49d-5509c2faec41@m44g2000hsc.googlegroups.com> Message-ID: <21b38583-1623-4df5-a14d-d224c9128083@c33g2000hsd.googlegroups.com> > > > is there a newsgroup explicitly for python windows extensions? > > Not that I know of, other than what's described here: > > https://sourceforge.net/mail/?group_id=78018 > > -tkc There is a PyWin32 user's group: http://mail.python.org/mailman/listinfo/python-win32 The maintainer of the project is a regular contributor to the list as are a number of other very knowledgeable Windows guys. Mike From kla at us.de Fri Mar 21 11:19:05 2008 From: kla at us.de (klaus) Date: 21 Mar 2008 15:19:05 GMT Subject: beginners question about return value of re.split Message-ID: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Hello, I have a question regarding the return value of re.split() since I have been unable to find any answers in the regular sources of documentation. Please consider the following: #!/usr/bin/env python import re if __name__ == "__main__": datum = "2008-03-14" the_date = re.split('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', datum, 3) print the_date Now the result that is printed is: ['', '2008', '03', '14', ''] My question: what are the empty strings doing there in the beginning and in the end ? Is this due to a faulty regular expression ? Thank you ! KL. From sajmikins at gmail.com Thu Mar 20 20:43:59 2008 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Mar 2008 17:43:59 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: On Mar 19, 11:39 pm, "Daniel Fetchinson" wrote: > > Was looking at PEP 3108,http://www.python.org/dev/peps/pep-3108/, > > and saw that the repr module was slated for vaporization. I've only > > used the module a few times ever. I'm curious if the community wants > > it kept around or whether it is considered clutter. > > > The PEP is going to be finalized soon, so if you have issues with it, > > they should be sent to the PEP author or brought up on the list, > >http://mail.python.org/mailman/listinfo/stdlib-sig. > > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: > > Each module to be removed needs to have a justification as to why it > should no longer be distributed with Python. > > then goes on with, > > With so many other GUI options out there that are considered better > than Tkinter, it might be best to remove Tkinter from the stdlib and > make it an externally maintained package. > > I don't get it. There are many [insert your favorite software > component] options outside of the python core that are considered > better than the one coming with python, yet they don't get removed. > All network servers for example could be thrown out because twisted is > considered better. This just doesn't make sense to me. Tkinter is > great for its purpose, typical use cases are creating a simple GUI > composed of a couple of components only. You can nicely do this with > tkinter and the large user base shows that it's a real need real > people have. Sure, for fancy GUI stuff there are better options but > for quick and simple things tkinter is just great. And last time I > checked python comes with batteries included so why sould I need to > search and download a third party package for such a common use case? > > Thoughts anyone? > > Cheers, > Daniel I've been thinking of volunteering to "port" Tkinter to Python 3.0, I hadn't noticed that there was any discussion of removing it. It would be a shame IMHO. Sure it has warts, but it /works/ and good for quick and dirty GUIs as well as elaborate (even totally visually customized) fancy applications. ~Simon From malkarouri at gmail.com Sat Mar 8 17:37:11 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 14:37:11 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <7d442cdd-749e-4391-ba31-e9c86d090137@x41g2000hsb.googlegroups.com> Message-ID: <70f5b8e7-4e76-43f7-b390-c5dd994ff434@e31g2000hse.googlegroups.com> On Mar 8, 6:24?pm, rockingred wrote: > I think it's a bad practice to get into. ?Did you intend to do the > "process" step again over the added variables? ?If not I would set a > new variable, based on your awful naming convention, let's call it z. > Then use z.append(y) within the for loop and after you are out of your > for loop, q.append(z). Thanks, rockingred, for the advice. I hope that you didn't assume that I was a newbie, even if my question looks so. What I was trying to do is write some Python code which I need to optimize as much as possible. I am using Cython (Pyrex) and would probably end up rewriting my whole module in C at one point, but it is really hard to beat Python data structures at their home turf. So meanwhile, I am making use of dubious optimizations - on my own responsibility. There have been a lot of these along the years - like using variables leaking from list expressions (not anymore). Think of it as a goto. Yes, I intend to do the process step again over the added variables. The suggested deque is probably the best, though I need the speed here. What are the variable naming you would suggest, for a throwaway - probably anonymized for the same of publishing on the web - code? Cheers, Muhammad Alkarouri From aisaac at american.edu Thu Mar 13 20:38:40 2008 From: aisaac at american.edu (Alan Isaac) Date: Fri, 14 Mar 2008 00:38:40 GMT Subject: no more comparisons In-Reply-To: References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: Mark Dickinson wrote: > Sorting tuples, where the second item in the tuple should > have the opposite ordering to the first is going to be > a bit of a pain. Or even worse, where the ordering of the > second item depends on the value of the first item in the > tuple. This is like some examples where I had used cmp, but if I understand correctly I think it is not a problem. > For example, suppose that (for whatever contrived reason) > you're representing integers in (sign, magnitude) format > by tuples (s, i), where s = 0 or 1 (0 for positive, 1 for > negative) and i is a string representing the absolute > value of the integer. So Does this do it? :: key= lambda x: (-x[1],int(x2)) Here I am depending on the lexicographic sorting of tuples. Without that there would be real trouble. Cheers, Alan Isaac From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 10:00:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 14:00:09 -0000 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> <8hqHj.175213$8Z.117427@newsfet10.ams> Message-ID: <13usir93664fe2d@corp.supernews.com> On Sat, 29 Mar 2008 13:06:27 +0100, Roel Schroeven wrote: > In any case, I replied because your reaction didn't feel all that gentle > to me; to be honest, it felt rather rude. Are you new to Usenet? :-) No offense taken; I hope Robert didn't take offense either, but took the little dig in the spirit it was intended. -- Steven From hniksic at xemacs.org Sun Mar 30 16:11:43 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 30 Mar 2008 22:11:43 +0200 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <656vhnF2e9ao7U1@mid.uni-berlin.de> Message-ID: <8763v4otts.fsf@mulj.homelinux.net> "Diez B. Roggisch" writes: >> Note that I said "*file* input/output". Twisted and asyncore are >> about asynchronous socket programming that polls over nonblocking file >> descriptors such as found in socket programming, not about wrapping >> aio(3) and the equivalent Windows APIs. > > I admit glossing over the file-input - however this is available on > posix-systems using the select-module. I believe you stil misunderstand. The select module doesn't provide an inteface to aio(3). It provides an interface to select() and poll() system calls, which don't provide asynchronous access to regular files. > So if I were in nitpicking-mood, your assertion still would be false I invite constructive nitpicking, but you are completely missing the point. You are confusing aio(3) with select and poll. > I'm pretty sure though that tiwsted & asynchore don't poll, but > instead use the select-module. Which at least for unix (and AFAIK > for Windows as well) is asynchronous - you get notified if data > arrives or has been transmitted, and otherwise your process sleeps. Unfortunately, this is not the case for files at all, even on Unix. (On Windows, select doesn't work on files at all, it only accepts sockets.) From kyosohma at gmail.com Thu Mar 6 09:20:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Mar 2008 06:20:03 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: On Mar 5, 7:07 pm, "D'Arcy J.M. Cain" wrote: > On Wed, 5 Mar 2008 14:00:17 -0800 (PST) > > Mike Driscoll wrote: > > What are you talking about? I didn't change the address at all. I'm > > not even sure what you mean. Are you talking about the post subject > > line (which I have never touched in any post)? If you're talking about > > the OP's email address, that's Google's fault for cropping them. > > I'm talking about castironpi. I find his posts a waste of my time so I > have them filtered out along with a few others and I also filter out > responses by searching for his address in the body so changing it > defeats that. However, if it is something that you have no control over > I apologize for the noise. > > -- > D'Arcy J.M. Cain | Democracy is three wolveshttp://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. No problem. I wish I could use something other than Google Groups when I'm at work, but we currently have NNTP disabled...and I haven't found a good workaround yet. Mike From hdante at gmail.com Sun Mar 30 17:21:08 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 14:21:08 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <6deb5443-e87b-448e-a1a6-6a1886c9f12a@x41g2000hsb.googlegroups.com> <87od8vzzr4.fsf@physik.rwth-aachen.de> Message-ID: <2799dc1e-3652-420c-bfd0-f0a5f8adc07e@m3g2000hsc.googlegroups.com> On Mar 30, 6:08 pm, Torsten Bronger wrote: > Hall?chen! > > hdante writes: > > On Mar 30, 9:45 am, Bjoern Schliessmann > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > >> hdante wrote: > > >>> BTW, my opinion is that it's already time that programmer > >>> editors have input methods advanced enough for generating this: > > >> Could you please list some that do, and are also convenient? > > > AFAICT there's none. This should be easy to implement on emacs, > > It *is* implemented in Emacs. You can even choose from many input > methods, optimised for differend areas/languages. I mean creating an input method specific for programming languages, not using the TeX one. > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: bron... at jabber.org > (Seehttp://ime.webhop.orgfor further contact info.) From roman.dodin at softjoys.com Mon Mar 17 06:12:13 2008 From: roman.dodin at softjoys.com (Roman Dodin) Date: Mon, 17 Mar 2008 13:12:13 +0300 Subject: About reading Python code In-Reply-To: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <47DE43FD.5090308@softjoys.com> WaterWalk ?????: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. > > So I'm curious how to read code effectively. I agree that python code > is clear, but when it becomes long, reading it can still be a hard > work. > You also can use free IDE (for example Eclipse) and PyDev plugin, which includes comfortable Debugger From http Fri Mar 21 15:52:12 2008 From: http (Paul Rubin) Date: 21 Mar 2008 12:52:12 -0700 Subject: How can I make a function equal to 0? References: Message-ID: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Martin Manns writes: > Is there a way to create a function that is equal to 0? def f(): return 0 From jr9445 at ATT.COM Mon Mar 31 14:06:29 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 31 Mar 2008 13:06:29 -0500 Subject: Is this a good time to start learning python? In-Reply-To: <47f1140e$0$735$a729d347@news.telepac.pt> References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Rui Maciel > Sent: Monday, March 31, 2008 12:41 PM > To: python-list at python.org > Subject: Is this a good time to start learning python? > > Recently I woke up inclined to take up the task of learning another > programming language. I've already dipped my toes in Perl (I've read > online > tutorials and wrote a couple of irrelevant pet projects) but, as the > computers at my workplace only sport the python interpreter, it > probably > means that learning python will end up serving me better, at least in > the > short run. Plus, you know how Perl goes. > > So far the decision seems to be a no brainer. Yet, Python 3000 will > arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put > it > in other words, I fear that I will be wasting my time. > > At least that is what a clueless newbie believes. As this group is > frequented by people who have more insight into all things pythonesque, > what are your thoughts on this? > Meh. That's like asking if you should learn to use a fork or a spoon. If you're learning how to program, go with Python. (Learning as in algorithms and data structures.) If you need to use OO, go with Python. Perl's OO syntax is just horrific. If you're using a lot of regexes, need a bit of speed, or need something a bit more robust than dynamically typed objects randomly breaking your code, then go with Perl. ;-) Libraries can also affect your choice. (I had to switch to Perl when Python's win32com failed.) Perl's learning curve is "unreadable" syntax, whereas Python's curve requires knowing about side effects and dealing with strong, dynamic typing. Overall, Python is more high level and cleaner looking/readable. However, Python's dynamically typed objects require additional effort/expense to debug, and it's regex module is pretty quirky/painful to use. Perl has a very large library, is fast, is mostly statically compiled, and doesn't get in the way (automatic type conversions, several ways to do something, etc..) Python is probably faster to learn (clearer syntax and OO,) but slower to master (side effects, strongly but dynamically typed.) With Perl, once you get the core syntax down, you don't need to master Perl. Instead you just look up the module/feature you want to use and just use it. Finally, I find that Perl's documentation is much better than Python's. All IMO, IME. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From jason.scheirer at gmail.com Mon Mar 31 13:37:45 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 31 Mar 2008 10:37:45 -0700 (PDT) Subject: Automatically fill in forms on line References: <772b20d1-a845-480b-a583-cf8ba470ecae@q27g2000prf.googlegroups.com> Message-ID: <8e6c8058-c89f-402e-ab17-f310d7ffb8cd@e10g2000prf.googlegroups.com> On Mar 31, 10:35 am, Jason Scheirer wrote: > On Mar 31, 9:50 am, "Jackie Wang" wrote: > > > > > Dear all, > > > I want to automatically complete the following task: > > > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx; > > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > > Highway 102"; > > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > > 4. Click the bottom "search"; > > 5. In the opened page, extract and save the number after "Tract Code". > > In the example, it will be "9659". > > 6. Repeat Step 1 with a new address. > > > Can Python realize these steps? Can these steps be done witout > > openning and IE windows? Especially, I dont know how to write code for > > step 2, 4 and 5. > > > Thank you! > > You may also want to look at the Yahoo! maps API, which will also give > you geocoding with a much nicer interface: > > http://www.yahooapis.com/maps/rest/V1/geocode.html > > unless you specifically need to use the TeleAtlas data or the API > licensing is incompatible with the task at hand, I'd recommend using > that instead. And as a follow up, check out the Python Geocoding Toolbox: http://exogen.case.edu/projects/geopy/ It already has Yahoo! Geocoding API bindings, as well as Google Maps geocidng bindings in a nice Pythonic interface. From littlesweetmelon at gmail.com Tue Mar 4 03:22:16 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Tue, 4 Mar 2008 16:22:16 +0800 Subject: Difference between 'function' and 'method' Message-ID: Howdy everyone, This is a big problem puzzles me for a long time. The core question is: How to dynamically create methods on a class or an instance? Let me state it step by step. 1. def gunc(self): pass class A(object): def func(self): pass a = A() a.func # gives "bound method", type is "instancemethod" A.func # gives "unbound method", type is "instancemethod" gunc # gives "function", type if "function" # ?? Does this line attach a method to instance? ... I don't think so. a.gunc = gunc I found stardard library 'new' may help. Is that right? 2. a = A() # instance of old class A # Do attach a new method to class A... b = A() # instance of new class A Does "a" can get the new method automatically? Does new method have the *same* concept level with old methods? Especially, if there are classes inherit from class A, how does name resolution work on this case? 3. How do I write a decroator for a method? Eg: class A(object): @my_dec def func(self): pass Here, my_dec should return a method rathar than a function/lambda. Am I right? What does @property @staticmethod... really do? I cannot step-into them for source code. 4. If most of above questions can be solved, then it would be easy to implement the feature: "dynamic property attach". Eg: One class can read/store settings from/to some file based on the file content. # File: cfg.ini x = 1 y = python config = SettingClass('cfg.ini') # dynamically build up properties x and y. x = config.x # x will be set to 1 (str -> int convertion would be done by 'property x') y = config.y # y will be set to 'python' config.x = 9 # 'x = 9' is written to cfg.ini. How to implement ^_^ Maybe there are some library does the same thing. What is it? How to implement ? Thank you for your attention! --- ShenLei From Lie.1296 at gmail.com Mon Mar 3 16:11:07 2008 From: Lie.1296 at gmail.com (Lie) Date: Mon, 3 Mar 2008 13:11:07 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> Message-ID: On Mar 2, 11:36?pm, Paul Rubin wrote: > Lie writes: > > You hit the right note, but what I meant is the numeric type > > unification would make it _appear_ to consist of a single numeric type > > (yeah, I know it isn't actually, but what appears from outside isn't > > always what's inside). > > That is clearly not intended; floats and decimals and integers are > really different from each other and Python has to treat them distinctly. In certain operations it would, such as: a = Decimal('32.324') b = 90.3453 c = 43 d = a + b + c <<< this should work without manual type casting This behavior is what is intended in numeric type unification, floats and decimals and integers should work together flawlessly without the need for manual type casting. This gives the _impression_ of a single numeric type (although programmers should still be aware that the underlying type still exists). It's true Python have to treat them differently, but programmers would be able to treat them all the same (at least in most parts) > > > Try with a=7, b=25 > > > They should still compare true, but they don't. The reason why they > > don't is because of float's finite precision, which is not exactly > > what we're talking here since it doesn't change the fact that > > multiplication and division are inverse of each other. > > What? ?Obviously they are not exact inverses for floats, as that test > shows. ?They would be inverses for mathematical reals or rationals, > but Python does not have those. When I said multiplication and division are inverse, I was pointing out the fact that even though float's inexactness make them imperfect inverse, mult & div are still inverse of each other. In-practice, the inversing behavior is impossible unless we have a way to represent real number (which we don't), and the *workaround* to make them work is to do epsilon comparison. When I'm talking about things I usually talk in purely theoretical condition first and considers practical implementations that doesn't work that way as making up a workaround inside their limitations. In this case, the theoretical condition is that multiplication and division is inverse of each other. The practical consideration is float is inexact and reals is impossible, and thus epsilon comparison is necessary to walk around float's limitations so multiplication and division could still be inverses. Aside: Python would have rationals > > One way to handle this situation is to do an epsilon aware > > comparison (as should be done with any comparison involving floats), > > but I don't do it cause my intention is to clarify the real problem > > that multiplication is indeed inverse of division and I want to > > avoid obscuring that with the epsilon comparison. > > I think you are a bit confused. ?That epsilon aware comparison thing > acknowledges that floats only approximate the behavior of mathematical > reals. ? Yes, I realized that floats aren't the same as reals. > When we do float arithmetic, we accept that "equal" often > really only means "approximately equal". ?But when we do integer > arithmetic, we do not expect or accept equality as being approximate. > Integer equality means equal, not approximately equal. ?That is why > int and float arithmetic cannot work the same way. No, no, they don't work the same way, but they should appear to work the same way as reals in pure mathematics do. Again, I'm talking in theory first: ints and floats should work the same way, but since practical considerations make them impossible, then they should at least appear to work the same way (or they would have become completely different things, remember duck typing?). From jkugler at bigfoot.com Thu Mar 27 14:23:31 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Thu, 27 Mar 2008 10:23:31 -0800 Subject: SoC project: Python-Haskell bridge - request for feedback References: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Message-ID: Micha? Janeczek wrote: > Hi, > > I am a student interested in participating in this year's SoC. > At http://tsk.ch.uj.edu.pl/~janeczek/socapp.html (and also below > in this email) you can find a draft of my project proposal. > > I'd like to ask you to comment on it, especially the deliverables > part. Are you interested in such a project, and if yes, what features > would be most important to you? Is anything missing, or should > something get more priority or attention? You might want to take a look at this: http://www.artfulcode.net/articles/extending-python-almost-anything/ That might get you started at least on the calling Haskell part. j From MartinRinehart at gmail.com Thu Mar 13 06:53:13 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 13 Mar 2008 03:53:13 -0700 (PDT) Subject: What's Going On? Message-ID: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> (Accompanied by Marvin Gaye) >>> def f(list=[0]): ... list[0]+=1 ... return list[0] ... >>> f() 1 >>> f() 2 >>> f() # 'list' is a name bound to a list (mutable) so this makes sense 3 >>> f([5]) 6 >>>f() # What's Going On? 4 Off topic: Motown chief Berry Gordy tells Gaye he won't release the "uncommercial" song. Gaye tells Gordy he'll never have another Gaye song if he doesn't release it. Gordy backs down. 2.5 million singles plus title track for blockbuster album. From darcy at druid.net Fri Mar 14 11:32:28 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 14 Mar 2008 11:32:28 -0400 Subject: %x unsigned? In-Reply-To: <87skytbbbc.fsf@mulj.homelinux.net> References: <87skytbbbc.fsf@mulj.homelinux.net> Message-ID: <20080314113228.961193b0.darcy@druid.net> On Fri, 14 Mar 2008 16:00:07 +0100 Hrvoje Niksic wrote: > The %x conversion specifier is documented in > http://docs.python.org/lib/typesseq-strings.html as "Unsigned > hexadecimal (lowercase)." What does "unsigned" refer to? > > >>> '0x%x' % 10 > '0xa' > >>> '0x%x' % -10 > '0x-a' > > Is this a bug or is %x misdocumented? I think it is working exactly as documented. It says that it displays unsigned numbers. If you give it a negative number you get undefined behaviour. Are you saying that the docs could be a little clearer? -- 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 bogus@does.not.exist.com Thu Mar 13 16:03:56 2008 From: bogus@does.not.exist.com (Andrew Rekdal) Date: Thu, 13 Mar 2008 15:03:56 -0500 Subject: Python regex Message-ID: I hope posting is ok here for this question... I am attempting to extract the text from a CSS comment using 're' such as... string = "/* CSS comment /*" exp = "[^(/*)].*[^(*/)] " p = re.compile(exp) q = p.search(string) r = q.group() print r >>CSS comment although this works to a degree... I know the within the brackets everything is taken literally so the pattern I am to negating is "(/*)". ie. includes the parenthesis. So my question is... Is there a way to negate a pattern that is more than on character long? eg. where rather than saying if forward slash OR astrisk appear..negate. I would be saying if parenthesis AND asterisk appear in this order... negate -- Andrew From esj at harvee.org Sat Mar 1 00:43:03 2008 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 01 Mar 2008 00:43:03 -0500 Subject: Backup Script over ssh In-Reply-To: References: Message-ID: <47C8ECE7.4060309@harvee.org> Gabriel Genellina wrote: > En Wed, 27 Feb 2008 13:32:07 -0200, Christian Kortenhorst > escribi?: > >> But there is no rsync for windows without using cygwin > > That's no big deal; rsync doesn't require tons of libraries, just > cygpopt-0.dll and cygwin1.dll. See this page: > http://www.brentnorris.net/rsyncntdoc.html > If you prefer a nice GUI around it (mmm... not so nice actually :) ) > http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp > windows rsync sans gui http://www.itefix.no/phpws/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=6&MMN_position=23:23 or google cwrsync I use in conjunction with rsnapshot for backing up xp and vista machines --- eric -- Speech-recognition in use. It makes mistakes, I correct some. From exxfile at hotmail.com Mon Mar 24 20:35:28 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 17:35:28 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <67d6b43e-a11a-44c6-a9d8-90df545c9418@e23g2000prf.googlegroups.com> <7681802b-656b-42fa-9b11-83f3382a1b03@s37g2000prg.googlegroups.com> Message-ID: <28afd7e0-b64a-40cf-b584-b91393d326b4@e10g2000prf.googlegroups.com> On Mar 24, 12:18?pm, George Sakkis wrote: > On Mar 24, 3:13 pm, pythonnubie wrote: > > > > > > > > > i ?have ?come across my first exeption using randrange . The exeption > > > > is " no such ?attribute " in ?module random > > > > > platform ?is xp ?home ?and the python ?build is activestate 2.5 > > > > Welcome aboard! > > > > There's definitely a randrange function in the random module, so > > > something else must be wrong. To get the most out of this list and > > > minimize wasted bandwidth, the most effective way usually consists of > > > copying and pasting: > > > 1. The offending code (or just the relevant part if it's too big). > > > 2. The full traceback of the raised exception. > > > > Regards, > > > George > > > Hwere is the complete traceback ! >>> The word is: ?index > > > Traceback (most recent call last): > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 307, in RunScript > > ? ? debugger.run(codeObject, __main__.__dict__, start_stepping=0) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \__init__.py", line 60, in run > > ? ? _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > > ? File "F:\Python25\Lib\site-packages\pythonwin\pywin\debugger > > \debugger.py", line 631, in run > > ? ? exec cmd in globals, locals > > ? File "F:\Documents and Settings\Mark\My Documents\rand.py", line 5, > > in > > ? ? import random > > ? File "F:\Documents and Settings\Mark\My Documents\random.py", line > > 13, in > > ? ? distributions on the real line: > > AttributeError: 'module' object has no attribute 'randrange' > > > Why ?would it say ?it can't find the function ? > > Because you named your file 'random.py' and it shadows the standard > random module! Change the name to something else, say foo.py, and try > it again. > > George- Hide quoted text - > > - Show quoted text - Hi that was the problem I shoaswoed the random module . Thanks to everyone for their support ! Mark From george.sakkis at gmail.com Sun Mar 9 23:12:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 9 Mar 2008 20:12:58 -0700 (PDT) Subject: __iter__ yield References: Message-ID: <27d24b75-f1b5-4996-b54a-15ab2ba16593@59g2000hsb.googlegroups.com> On Mar 9, 7:37 pm, Paul Hankin wrote: > On Mar 9, 8:58 pm, duccio wrote: > > > Someone knows if it's possible to make this __iter__ function with just > > one 'yield' intead of two? > > ... > > def __iter__(self): > > yield self #1 > > for n in self.childs: > > for nn in n.__iter__(): > > yield nn #2 > > Only one yield and shorter (but not really any simpler): > > from itertools import chain > > class Node: > ... > def __iter__(self): > for x in chain([self], *self.childs): > yield x Actually this doesn't need a yield at all: class Node: ... def __iter__(self): return chain([self], *self.childs) George From nyamatongwe+thunder at gmail.com Mon Mar 17 20:16:22 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 18 Mar 2008 00:16:22 GMT Subject: Which way to access Scintilla In-Reply-To: References: Message-ID: Alex: > I also want to embed Scintilla in Tkinter-created window (create the > rest of the GUI in Tkinter), or rather, I want to know if that's > possible at all. Any suggestions are appreciated. While it may be possible with sufficient dedication, it is unlikely to be simple. If you really want to use Tkinter then you are probably better off using some existing code that uses its text widget from Python such as Idle. Neil From python at rolfvandekrol.nl Thu Mar 20 10:09:08 2008 From: python at rolfvandekrol.nl (Rolf van de Krol) Date: Thu, 20 Mar 2008 15:09:08 +0100 Subject: Is this valid ? In-Reply-To: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> Message-ID: <47E27004.8020805@rolfvandekrol.nl> John Machin wrote: > Of course. You can chain comparisons as much as you like and is > (semi-)sensible, e.g. > Hmm, 'of course' is not the correct word for it. Although the Stef Mientki would probably be able to find it in the documentation it is not as simple as you might think. Most languages interpret a == b == 2 as (a == b) == 2, or throw an error because this syntax is not valid. The fact that python understand the obvious meaning of this code, is quite unique to Python, as far as I know. From castironpi at gmail.com Sun Mar 2 11:01:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 08:01:03 -0800 (PST) Subject: Python-based regular expression parser that allows patterns to call functions? References: Message-ID: On Mar 2, 8:41?am, Andrew Warkentin wrote: > I am writing a filtering HTTP proxy (the site ishttp://xuproxy.sourceforge.net/). I want it to be compatible with > Proxomitron (http://proxomitron.info/) filters. I need a regular > expression parser that allows patterns to call functions (or more > likely, class methods), to implement "matching commands" (look at the > Proxmitron documentation to see what I mean). Does anyone know if such a > library exists for Python, or do I have to write my own parser? To make a list of commands available: class C: def behavior( self ): pass def behavior2( self ): pass cmds= [ behavior, behavior2 ] Then search C.cmds for a match to the regular expression. C.behavior.func_name contains the string 'behavior' for checking. You might need to "bind" the contents of C.cmds before you call them too. More info available, just ask. You can also do: class C: @string_callable def behavior( self ): pass @string_callable def behavior2( self ): pass and class C: def behavior( self ): pass def behavior2( self ): pass cmds= [ 'behavior', 'behavior2' ] (strings this time), and use getattr( C, 'behavior' ) or for c= C(), getattr( c, 'behavior' ). class C: def behavior( self ): pass def behavior2( self ): pass cmds= [ 'behavior', 'behavior2' ] C.cmds= commandmap( C, C.cmds ) can generate a dictionary of strings to methods. And there's always getattr( c, strA ), for your choice of strA, which throws an exception if strA is not an attribute (method or property) of c, and hasattr( c, strA ) can test if it is. You less often want to generate distinct functions based on parameters only, but you can. c= C() def behavior3( self ): pass c.behavior3= behavior3 so c.behavior3() is legal. Where does that get you? From needin4mation at gmail.com Thu Mar 20 11:09:40 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 20 Mar 2008 08:09:40 -0700 (PDT) Subject: Can I run a python program from within emacs? Message-ID: Hi, I'm trying to learn Python. I using Aquamac an emac implementation with mac os x. I have a program. If I go to the command prompt and type pythong myprog.py, it works. Can the program be run from within the editor or is that not how development is done? I ask because I was using Visual Studio with C# and, if you're familiar, you just hit run and it works. On Python do I use the editor for editing only and then run the program from the command line? Thank you. From andreas.axelsson at gmail.com Sun Mar 30 11:58:30 2008 From: andreas.axelsson at gmail.com (axl) Date: Sun, 30 Mar 2008 08:58:30 -0700 (PDT) Subject: Build complete, now I just need to "install" it... References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: On 30 Mar, 17:40, "Ryan Ginstrom" wrote: > Another option is to compile your extensions with gcc, and specify that it > link to MSVCR71.dll as the C runtime. > > For MinGW, it's sufficient to edit the specs (e.g. in > C:\MinGW\lib\gcc\mingw32\3.4.2) like so: > *libgcc: > %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 True, I was hoping to avoid MinGW, since I've been using MSVC for ages and I know it well. Yet another package on the disk, etc... But as this seems like the simplest solution for now I'll try that. Cheers! /axl From deets at nospam.web.de Thu Mar 27 09:56:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 14:56:02 +0100 Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> Message-ID: <651ncdF2cmik2U1@mid.uni-berlin.de> king kikapu wrote: > On 27 ???, 14:35, Paul Rubin wrote: >> king kikapu writes: >> > it seems that Psyco's author will not port it for the upcoming Python >> > 3000 release :( >> >> I think the idea is it will be part of PyPy and you should use that. > > I know that his efforts are on PyPy now but i do not know when PyPy is > going to be stable and if i can use it with my current "development > stack" (PyQt, Eric4 etc). I mean, i do not know if it will be possible > to "abandon" CPYthon and use PyPy instead. Currently? No way. It's *way* to slow. Diez From jzgoda at o2.usun.pl Fri Mar 14 05:57:41 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 14 Mar 2008 10:57:41 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: References: Message-ID: Lie napisa?(a): >> foo = [1,2,3,4] >> x = foo.append(5) >> print x >> >> What will be the output (choose one): >> >> 1) [1,2,3,4] >> 2) [1,2,3,4,5] >> 3) That famous picture of Albert Einstein sticking out his tongue >> 4) Nothing - no output >> 5) None of the above >> >> I undertake to summarise answers posted to complete this "survey". > > I think I'll choose 3. Well, no, I suppose the correct behavior > _should_ be undefined (i.e. what it returns is an implementation > details that should not be relied on). The fact that it returns None > is just a "coincidence" that happens to happen every time you tested > it (you can't prove by ignorance) I think in Python there's no notion of "void" return type. Deliberate choice to return None for functions that modify objects in place seems to be OK as long as it is used consistently and documented. Which is the case. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From ss.dtvcs at gmail.com Wed Mar 5 19:16:31 2008 From: ss.dtvcs at gmail.com (ss.dtvcs at gmail.com) Date: Wed, 5 Mar 2008 16:16:31 -0800 (PST) Subject: 2nd CFP: DATICS 2008 - Design, Analysis and Tools for Integrated Circuits and Systems Message-ID: Apologies for any multiple copies received. We would appreciate it if you could distribute the following call for papers to any relevant mailing lists you know of. 2nd CALL FOR PAPERS =============================================================================== Special session: Design, Analysis and Tools for Integrated Circuits and Systems DATICS 2008 July 22-24, 2008 (Crete Island, Greece) http://digilander.libero.it/systemcfl/datics =============================================================================== Aims and Scope -------------- The main target of the Special Session: DATICS 2008 of the WSEAS CSCC multi-conference (http://www.wseas.org/conferences/2008/greece/icc/) is to bring together software/hardware engineering researchers, computer scientists, practitioners and people from industry to exchange theories, ideas, techniques and experiences related to all areas of design, analysis and tools for integrated circuits (e.g. digital, analog and mixed-signal circuits) and systems (e.g. real-time, hybrid and embedded systems). The special session also focuses on the field of formal methods and low power design methodologies for integrated circuits. Topics ------ Topics of interest include, but are not limited to, the following: * digital, analog, mixed-signal designs and test * RF design and test * design-for-testability and built-in self test methodologies * reconfigurable system design * high-level synthesis * EDA tools for design, testing and verification * low power design methodologies * network and system on-a-chip * application-specific SoCs * specification languages: SystemC, SystemVerilog and UML * all areas of modelling, simulation and verification * formal methods and formalisms (e.g. process algebras, petri-nets, automaton theory and BDDs) * real-time, hybrid and embedded systems * software engineering (including real-time Java, real-time UML and performance metrics) Industrial Collaborators ------------------------ DATICS 2008 is partnered with: * CEOL: Centre for Efficiency-Oriented Languages "Towards improved software timing", University College Cork, Ireland ( http://www.ceol.ucc.ie) * International Software and Productivity Engineering Institute, USA (http://www.intspei.com ) * Intelligent Support Ltd., United Kingdom (http://www.isupport- ltd.co.uk) * Minteos, Italy (http://www.minteos.com) * M.O.S.T., Italy (http://www.most.it) * Electronic Center, Italy (http://www.el-center.com) DATICS 2008 is sponsored by: 1. LS Industrial Systems, South Korea (http://eng.lsis.biz) 2. Solari, Hong Kong (http://www.solari-hk.com) Technical Program Committee --------------------------- * Prof. Vladimir Hahanov, Kharkov National University of Radio Electronics, Ukraine * Prof. Paolo Prinetto, Politecnico di Torino, Italy * Prof. Alberto Macii, Politecnico di Torino, Italy * Prof. Joongho Choi, University of Seoul, South Korea * Prof. Wei Li, Fudan University, China * Prof. Michel Schellekens, University College Cork, Ireland * Prof. Franco Fummi, University of Verona, Italy * Prof. Jun-Dong Cho, Sung Kyun Kwan University, South Korea * Prof. AHM Zahirul Alam, International Islamic University Malaysia, Malaysia * Prof. Gregory Provan, University College Cork, Ireland * Dr. Emanuel Popovici, University College Cork, Ireland * Dr. Jong-Kug Seon, Telemetrics Lab., LG Industrial Systems Co. Ltd., South Korea * Dr. Umberto Rossi, STMicroelectronics, Italy * Dr. Graziano Pravadelli, University of Verona, Italy * Dr. Vladimir Pavlov, International Software and Productivity Engineering Institute, USA * Dr. Jinfeng Huang, Philips & LiteOn Digital Solutions Netherlands, Advanced Research Centre, The Netherlands * Dr. Thierry Vallee, Georgia Southern University, Statesboro, Georgia, USA * Dr. Menouer Boubekeur, University College Cork, Ireland * Dr. Ana Sokolova, University of Salzburg, Austria * Dr. Sergio Almerares, STMicroelectronics, Italy * Ajay Patel (Director), Intelligent Support Ltd, United Kingdom * Monica Donno (Director), Minteos, Italy * Alessandro Carlo (Manager), Research and Development Centre of FIAT, Italy * Yui Fai Lam (Manager), Microsystems Packaging Institute, Hong Kong University of Science and Technology, Hong Kong Important Dates --------------- March 31, 2008: Deadline for submission of completed papers May 1, 2008: Notification of acceptance/rejection to authors Please visit our web-site for further information on the hosting conference of DATICS, submission guidelines, proceedings and publications and international technical reviewers. Best regards, General Chair of DATICS: Dr. K.L. Man (University College Cork, Ireland) and Organising Committee Chair: Miss Maria O'Keeffe (University College Cork, Ireland) From amca01 at gmail.com Sun Mar 9 05:57:15 2008 From: amca01 at gmail.com (Alasdair) Date: Sun, 09 Mar 2008 20:57:15 +1100 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: Thanks, all - you've been most helpful. By the way, what does // do? I haven't yet run down its definition in the manual. -A. From jldunn2000 at googlemail.com Mon Mar 3 06:57:14 2008 From: jldunn2000 at googlemail.com (loial) Date: Mon, 3 Mar 2008 03:57:14 -0800 (PST) Subject: Delete hidden files on unix Message-ID: How can I delete hidden files on unix with python, i.e I want to do equivalent of rm .lock* From aboudouvas at panafonet.gr Fri Mar 28 05:40:35 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Fri, 28 Mar 2008 02:40:35 -0700 (PDT) Subject: Eclipse and PyDev Package explorer References: <1d4e6f2b-a058-413e-a566-674ccc733d6f@s19g2000prg.googlegroups.com> Message-ID: <9af850bd-01a3-4e6f-8cd9-d2883284db30@m44g2000hsc.googlegroups.com> A, and another one: If i set a custom builder for a pydev project, is there a way for this builder to automatically be "assigned" to every (pydev) project i will create from now on or i have to re-define it for every new one ? From stefan_ml at behnel.de Thu Mar 27 10:50:21 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Mar 2008 15:50:21 +0100 Subject: Psyco alternative In-Reply-To: References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: <47EBB42D.9090206@behnel.de> king kikapu wrote: >>> As for psyco, are there any alternatives to use now ? >> But ultimately, the author says that the approach is flawed, so at *some* >> point it will be discontinued. But that could be said about nearly >> everything, couldn't it? >> > It is a pity because this module *does* really solve some problems... If it's about "some problems", then maybe Cython is an alternative. http://cython.org Stefan From ken at seehart.com Sat Mar 8 01:58:23 2008 From: ken at seehart.com (Ken) Date: Fri, 07 Mar 2008 22:58:23 -0800 Subject: list of attributes Message-ID: <47D2390F.8010003@seehart.com> I have a class with a __getattr__ method that returns various methods. I also have the ability to determine the list of method names that are supported by my __getattr__ method (this list would be dynamically generated as it depends on the current state). What I would like to know is if there is a way overload the behavior of dir(instance) to include this dynamically generated list of method names. Ideally this would have the effect of making these methods visible to the autocomplete feature of debuggers in most modern IDEs. It looks like this would be __dir__ in 2.6, is that right? Ken From moonrie at gmail.com Wed Mar 12 23:19:53 2008 From: moonrie at gmail.com (moonrie) Date: Wed, 12 Mar 2008 20:19:53 -0700 (PDT) Subject: help please, splitter windows like in maya or 3ds max Message-ID: hi, everyone there, I am doing a 3D modeling project. I like to do it with Python( am a newbie), but have no idea with the wxSplitterWindow to create the 4-view windows( top, front, side, perspective), like the mfc CSplitterWnd guy), anyone can give me some help with wxPython? thanks in advance. - moonrie From dmitry.sukhov at gmail.com Thu Mar 27 08:21:08 2008 From: dmitry.sukhov at gmail.com (Sukhov Dmitry) Date: Thu, 27 Mar 2008 05:21:08 -0700 (PDT) Subject: PyGTK localisation on Win32 References: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> Message-ID: <9c795bfa-b2a1-4c72-bc69-0f5664c0d3e1@i12g2000prf.googlegroups.com> > > I had no problem with using standard gettext way of doing i18n on > Windows with PyGTK an Glade, apart some quirks with LANG environment > variable. Basically, the code that works looks like this: > > import gettext, locale > locale.setlocale(locale.LC_ALL, '') > if os.name == 'nt': > # windows hack for locale setting > lang = os.getenv('LANG') > if lang is None: > defaultLang, defaultEnc = locale.getdefaultlocale() > if defaultLang: > lang = defaultLang > if lang: > os.environ['LANG'] = lang > gtk.glade.bindtextdomain(appname, translation_dir) > gtk.glade.textdomain(appname) > gettext.install(appname, translation_dir, unicode=True) > > Be aware, that you can not change the locale setting from the command > line like you do on Linux. > I have the same problem. I did all as you wrote. gettext translations do work fine. But translations in glade does not work. The only way to turn it on is to set environment variable LANG explicitly before program run: set LANG=ru_RU python test.py From deets at nospam.web.de Tue Mar 11 03:50:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Mar 2008 08:50:37 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: <877541e6-1407-4c0d-9818-e500f38823d5@o77g2000hsf.googlegroups.com> References: <63i6j9F2793buU1@mid.uni-berlin.de> <63lqcuF27pbnbU1@mid.uni-berlin.de> <877541e6-1407-4c0d-9818-e500f38823d5@o77g2000hsf.googlegroups.com> Message-ID: <63mruiF26r9e6U1@mid.uni-berlin.de> Chris schrieb: > If all you wanted was some grouping of exceptions why not something > like... > > soft_exception_list = [IndexError, TypeError] > hard_exception_list = [ZeroDivision] > > try: > do_something() > except Exception, e: > if e.__class__ in soft_exception_list: > handle_soft_exception() > elif e.__class__ in hard_exception_list: > handle_hard_exception() > else: > raise NotImplementedError > > Granted you're most likely looking for something that does this > constantly on every line of code though... It's not about grouping, which would be done better with inheritance by the way. Its about not raising certain exceptions if there is no handler. Diez From cyu021 at gmail.com Fri Mar 14 07:15:28 2008 From: cyu021 at gmail.com (James Yu) Date: Fri, 14 Mar 2008 19:15:28 +0800 Subject: How to import custom python file in python server page (psp) ? Message-ID: <60bb95410803140415x621b5b23w75b83013997c750b@mail.gmail.com> Hi folks, I prepared a python script for dynamically get the absolute paths of the files in certain folder. Then I tried to invoke that function from my web server in a .psp file like this: 1 2 3 asdfasdfasdfa 4 5 <% 6 import glob 7 import os 8 *import Helper * 9 10 body = '' 11 top = 'asdfasdfasdfa' 12 links = {} 13 *Helper.GetLinks(top=top) * 14 *paths = Helper.GenLinkPath(links) * 15 body = paths 16 %> 17 <%=body%> 18 19 However, this is the error message I received when I open the page in a browser: > Mod_python error: "PythonHandler mod_python.psp" > > Traceback (most recent call last): > > File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, > in HandlerDispatch > result = object(req) > > File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 302, in > handler > p.run() > > File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 213, in > run > exec code in global_scope > > File "/var/www/.cyu021/.pic/index.psp", line 8, in > import Helper > > ImportError: No module named Helper *PS. I put Helper.py and index.psp in the same dir * Thanks in advance, -- This is a UTF-8 formatted mail ----------------------------------------------- James C.-C.Yu -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Mar 14 04:09:37 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Mar 2008 09:09:37 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: Dave Kuhlman wrote: > Arnaud Delobelle wrote: > >> >> 4. Both points above follow from the fact that foo.bar is really a >> function call that returns a (potentially) new object: in fact what >> really happens is something like > > Arnaud and Imri, too - > > No. foo.bar is *not* really a function/method call. > >> >> Foo.__dict__['bar'].__get__(foo, Foo). >> >> So every time foo.bar is executed an object is (or may be) created, >> with a new id. >> >> HTH > > I appreciate the help, but ... > > Actually, it does not help, because ... > > My understanding is that foo.bar does *not* create a new object. All it > does is return the value of the bar attribute of object foo. What new > object is being created? If the attribute has a __get__() method that's completely under the attribute's control: >>> class Bar(object): ... def __get__(self, *args): ... print "__get__%s" % (args,) ... return self.next() ... def next(self): ... self.count += 1 ... return self.count ... count = -1 ... >>> class Foo(object): ... bar = Bar() ... def __repr__(self): return "foo" ... >>> foo = Foo() >>> foo.bar __get__(foo, ) 0 >>> foo.bar __get__(foo, ) 1 >>> foo.bar __get__(foo, ) 2 >>> getattr(foo, "bar") __get__(foo, ) 3 Peter From frikker at gmail.com Mon Mar 3 16:43:17 2008 From: frikker at gmail.com (blaine) Date: Mon, 3 Mar 2008 13:43:17 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> Message-ID: <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> > pyserial is pure python, so I don't see how it's going to be > any more painful than something you write yourself. If you > want something that's more of a transparent object wrapper > aroudn the Posix serial interface, there's PosixSerial.py (upon > which pyserial's posix support is based): > > ftp://ftp.visi.com/users/grante/python/PosixSerial.py > > -- > Grant Edwards grante Yow! Everybody gets free > at BORSCHT! > visi.com Oh - good point. There wouldn't be any compilation issues with the C api. Nevermind! :) I do have a question though. In the termios module, I am attempting to set the baud rate to 921600, which is what we use with 'cutecom' (because minicom does not have this as an option) and is what the supplier recommends. When I try to set the rate using termios.tcsetattr(), I get an Argument Error. I do not get this when I use an existing baud rate, such as termios.B9600. Is there a way I can get around this? We would like to use it at full speed. Thank you, Blaine From __peter__ at web.de Wed Mar 19 05:50:52 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Mar 2008 10:50:52 +0100 Subject: Is there a way to get __thismodule__? References: Message-ID: benhoyt wrote: > Is there a way to get __thismodule__ in Python? That is, the current > module you're in. Or isn't that known until the end of the module? > > For instance, if I'm writing a module of message types/classes, like > so: > > class SetupMessage(Message): > number = 1 > > class ResetMessage(Message): > number = 2 > > class OtherMessage(Message): > number = 255 > > nmap = { # maps message numbers to message classes > 1: SetupMessage, > 2: ResetMessage, > 255: OtherMessage, > } > > Or something similar. But adding each message class manually to the > dict at the end feels like repeating myself, and is error-prone. It'd > be nice if I could just create the dict automatically, something like > so: > > nmap = {} > for name in dir(__thismodule__): > attr = getattr(__thismodule__, name) > if isinstance(attr, Message): > nmap[attr.number] = attr > > Or something similar. Any ideas? Use globals(): def is_true_subclass(a, b): try: return issubclass(a, b) and a is not b except TypeError: return False nmap = dict((m.number, m) for m in globals().itervalues() if is_true_subclass(m, Message)) print nmap You may also rely on duck-typing, assuming that everything that has a number attribute is a Message subclass: nmap = dict((m.number, m) for m in globals().itervalues() if hasattr(m, "number")) Peter From fakeaddress at nowhere.org Sat Mar 29 02:46:20 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 29 Mar 2008 06:46:20 GMT Subject: why does socket.makefile require non-blocking mode? In-Reply-To: References: Message-ID: <0BlHj.26232$Ch6.6951@newssvr11.news.prodigy.net> Forest wrote: > The socket.makefile() docs say, "the socket must be in blocking mode." I > don't see any explanation of why blocking mode is required, and I'm not sure > whether that means timeout mode is forbidden as well. Can someone clarify > this? Looking at the code for the existing _fileobject's read method, it will loose data it has already read if a socket.recv() call raises an exception. The function keeps buffers in a local variable that will be lost if an exception exits the scope. That much could be fixed with a try...finally. Other methods have similar problems. > I wanted to use file-like objects with socket timeouts, so I ended up writing > my own replacement for socket._fileobject. I'd appreciate it if someone could > either explain to my why my new class was unnecessary, or else encourage me to > contribute it as a patch to the socket module. Sure, fix it. A harder problem is that it doesn't play nice with select(). -- --Bryan From ttsiodras at gmail.com Fri Mar 28 09:29:21 2008 From: ttsiodras at gmail.com (ttsiodras at gmail.com) Date: Fri, 28 Mar 2008 06:29:21 -0700 (PDT) Subject: Global variables in modules... Message-ID: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> With a.py containing this: ========== a.py =========== #!/usr/bin/env python import b g = 0 def main(): global g g = 1 b.callb() if __name__ == "__main__": main() ========================== ...and b.py containing... ========= b.py ============= import a, sys def callb(): print a.g ========================== ...can someone explain why invoking a.py prints 0? I would have thought that the global variable 'g' of module 'a' would be set to 1... From pavlovevidence at gmail.com Tue Mar 4 10:17:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 4 Mar 2008 07:17:39 -0800 (PST) Subject: for-else References: Message-ID: On Mar 4, 8:27 am, bearophileH... at lycos.com wrote: > So far in Python I've almost hated the 'else' of the 'for' loops: > - I have problems to remember its meaning; > - It gives me little problems when I later want to translate Python > code to other languages (and you always have to translate long-lived > code). > - I have used it only once, so far. > > So so far I'd liked to see it removed from Python 3.0. > > But then this article:http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel... > has shown me that my problems with the 'else' of the 'for' mostly come > from just its bad naming. The converge language is yet another very > Python-like language, and it uses a better naming (the word > "exhausted" is long and has a complex spelling for non-English > speakers, so it's not perfect): > > for ...: > ... > exhausted: > ... > broken: > ... > > The meaning is explicit. While "else" seems to mean little there. > So I may like something similar for Python 3.x (or the removal of the > "else"). I would not be opposed to this on its own merits, but there is a rationale behind the name "else". If you consider a for loop to be a rolled-up if...elif...else statement (situations where this is reasonable tend to be the same ones were else would be useful), then the "else" clause would remain unchanged on the for loop. For instance, if you have a (trivial) if...elif...else like this: if a == 0: do_task_0() elif a == 1: do_task_1() elif a == 2: do_task_2() else: do_default_task() You could roll it up into a for...else statement like this: for i in range(3): if a == i: do_task[a]() else: do_default_task() (Please never mind the trivialness of this example; I know you can eliminate the for loop altogether; this is JUST an example.) I keep this analogy in mind when using for...else to keep the semantics straight. Carl Banks From duncan.booth at invalid.invalid Mon Mar 17 06:21:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 10:21:32 GMT Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <47DD33D7.2020300@timgolden.me.uk> Message-ID: "Tom Stambaugh" wrote: > For example, the new (!) simplejson (v1.7.4) doesn't compile correctly > (on my WinXP system, at least) with either any current MS or MinGW > compiler. Oh, I know I can make it work if I spend enough time on it > -- but the binary egg I eventually found seems to work just fine. I've also just spent a while getting simplejson 1.7.4 to install on a (non- windows) system without a C compiler. The trick is to unzip the tar file and then before you try to install it delete everything in simplejson.egg-info. Then 'setup.py install' will run to completion and while it warns about 'speedups are not enabled.' it doesn't take it as fatal error. Without this step it preserves the reference to native_libs.txt in SOURCES.txt even though the native_libs.txt file itself gets deleted. From Lie.1296 at gmail.com Sat Mar 29 15:18:27 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 29 Mar 2008 12:18:27 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: On Mar 30, 1:24 am, Duncan Booth wrote: > Lie wrote: > > You're forcing your argument too much, both != and <> are NOT standard > > mathematics operators -- the standard not-equal operator is >< -- and > > I can assure you that both != and <> won't be comprehensible to non- > > programmers. > > My maths may be a bit rusty, but I always thought that the standard not- > equal operator was like an = sign but with a diagonal slash through it as > displayed when you do: > > print u'\u2260' Ah yes, that is also used (I completely forgot about that one, my math's aren't that sharp anymore) and I think it's used more frequently than ><. Some books use >< while most use ?, but my argument was that no math book use != or <> (except in math for programmers). From janeczek at gmail.com Mon Mar 24 16:37:03 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Mon, 24 Mar 2008 21:37:03 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback Message-ID: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Hi, I am a student interested in participating in this year's SoC. At http://tsk.ch.uj.edu.pl/~janeczek/socapp.html (and also below in this email) you can find a draft of my project proposal. I'd like to ask you to comment on it, especially the deliverables part. Are you interested in such a project, and if yes, what features would be most important to you? Is anything missing, or should something get more priority or attention? Regards, Michal Python-Haskell bridge ===================== Description ----------- This project will seek to provide a comprehensive, high level (and thus easy to use) binding between Haskell and Python programming languages. This will allow using libraries of either side from each language. Benefits for Python ------------------- * Robust, high assurance components It might be beneficial to implement safety-critical components in a strongly, statically typed language, using Python to keep them together. Cryptography or authentication modules can be an example. * Performance improvements for speed-critical code Haskell compiled to native code is typically an order of magnitude faster than Python. Aside from that, advanced language features (such as multicore parallel runtime, very lightweight threads and software transactional memory) further serve in improving the performance. Haskell could become a safe, high level alternative to commonly used C extensions. * Access to sophisticated libraries While its set of libraries is not as comprehensive as that of Python, Haskell can still offer some well tested, efficient libraries. Examples might be rich parser combinator libraries (like Parsec) and persistent, functional data structures. QuickCheck testing library could also be used to drive analysis of Python code. Benefits for Haskell -------------------- The project would benefit Haskell by providing it with access to an impressive suite of libraries. It also has a potential to help Haskell adoption, by mitigating risk of using Haskell in a project. Deliverables ------------ * A low level library to access Python objects from Haskell * A set of low level functions to convert built-in data types between Haskell and Python (strings, numbers, lists, dictionaries, functions, generators etc.) * A higher level library allowing easy (transparent) access to Python functions from Haskell, and wrapping Haskell functions for Python to access * A way to easily derive conversion functions for user-defined data types/objects. Functions derived in such a way should work well with both low level and high level access libraries * Documentation and a set of examples for all of above Optional goals -------------- These are of lower priority, and might require a fair amount of work. I would like to implement most of them, if technically feasible. If they don't fit into Summer of Code timeframe, I am planning to finish afterwards. * A Python module for accessing functions from Haskell modules without manual wrapping (such wrapping should be already easy thanks to the high level library). It'd be accomplished through GHC api - if it allows it. The Haskell side of the high level library will already support such mode of operation * Extend and refactor the code, to make it support other similar dynamic languages. This is a lot of work, and definitely out of the scope of Summer of Code project, but some design decisions may be influenced by this. Related projects ---------------- They (and quite possibly some others) will be referenced for ideas. * MissingPy Provides a one way, low level binding to Python. Some of the code can be possibly reused, especially data conversion functions. It doesn't seem to export all features, in particular function callbacks are not supported * HaXR XML-RPC binding for Haskell. It could provide inspiration for reconciling Haskell and Python type systems, resulting in a friendly interface * rocaml A binding between Ruby and OCaml From fetchinson at googlemail.com Thu Mar 13 21:59:55 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 13 Mar 2008 18:59:55 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > Since you seem to know quite a bit about this topic, what is your > > opinion on the apparently 'generic' algorithm described here: > > http://grail.cs.washington.edu/projects/query/ ? > > So far it seems to me that it does what I'm asking for, it does even > > more because it can take a hand drawn sample image and query the > > database for similar photos. > > > > There is even a python implementation for it here: > > http://members.tripod.com/~edcjones/pycode.html > > > > On the histogram method I agree that it won't work partly because of > > what you say and partly because it is terribly slow since it's > > comparing every single pixel. > > I'm hardly the expert and can't answer authoritatively, but here's my 2c. > > I can't comment as to the actual accuracy of the algorithm, since it > will depend on your specific data set (set of photos). The algorithm is > sensitive to spatial and luminance information (because of the YIQ > colorspace), so there are simple ways in which it will fail. > > The histogram method uses only color, but has a lot of numbers to > compare. You may find the histogram method insensitive to spatial > relations (a landscape with the mountain on the left and one with the > mountain on the right) compared to the wavelet approach. > > This is a relatively old paper, and I've seen other more recent image > retrieval research using wavelets (some cases using only the > high-frequency wavelets for "texture" information instead of the > low-frequency ones used by this paper for "shape") and other information > retrieval-related research using lossy compressed data as the features. > If you have time, you may want to look at other research that cite this > particular paper. > > And just a thought: Instead of merely cutting off at m largest-wavelets, > why not apply a quantization matrix to all the values? I'm not at all an expert, just started to look into image matching, so I'm not quite sure what you mean. What's a quantization matrix in this context? From jura.grozni at gmail.com Thu Mar 13 14:26:01 2008 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Mar 2008 11:26:01 -0700 (PDT) Subject: wx and pil conversion References: <4a7969e2-b507-448d-bf63-a9c08986ac69@s12g2000prg.googlegroups.com> <63t1tnF29egotU1@mid.uni-berlin.de> <63t895F298us9U1@mid.uni-berlin.de> Message-ID: On Mar 13, 6:57?pm, "Diez B. Roggisch" wrote: > azrael wrote: > > I thought of using Temp files but I am afraid of the JPG destorsion > > while saving because of the compresion.I am looking for a way to > > directly transform it. > > Then don't use JPEG, use PNG. It's lossless. > > Diez thnx. i did't think about that. i totaly forgot png. From jstanforth at gmail.com Thu Mar 13 07:32:55 2008 From: jstanforth at gmail.com (John at Quintivity) Date: Thu, 13 Mar 2008 04:32:55 -0700 Subject: help please, splitter windows like in maya or 3ds max In-Reply-To: <1dab98f7-7a29-4afb-b9ef-9728d133697d@s13g2000prd.googlegroups.com> References: <1dab98f7-7a29-4afb-b9ef-9728d133697d@s13g2000prd.googlegroups.com> Message-ID: <813f79f60803130432g3404854ch27a52b571d5e011d@mail.gmail.com> Sounds like this might do exactly what you need... http://xoomer.alice.it/infinity77/main/FourWaySplitter.html Cheers, John On Thu, Mar 13, 2008 at 1:45 AM, moonrie wrote: > On Mar 13, 12:47 pm, "Andrew Rekdal" <@comcast.net> wrote: > > This seems to work... split then split each side. then tandem the size. > > > > import wx > > > > class Layout(wx.Frame): > > > > def __init__(self, parent, id, title): > > > > wx.Frame.__init__(self, parent, id, title) > > > > sizer = wx.BoxSizer(wx.HORIZONTAL) > > > > panel = wx.Panel(self,-1) > > > > splitter = wx.SplitterWindow(panel) > > > > sizer_left = wx.BoxSizer(wx.VERTICAL) > > > > panel_left = wx.Panel(splitter,-1) > > > > splitter_left = wx.SplitterWindow(panel_left) > > > > splitter_left.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.leftChange > ,id=splitter_left.GetId()) > > > > panel_left_upper = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > > > panel_left_upper.SetBackgroundColour("WHITE") > > > > panel_left_lower = wx.Panel(splitter_left,style= wx.BORDER_SUNKEN) > > > > splitter_left.SplitHorizontally(panel_left_upper,panel_left_lower) > > > > sizer_left.Add(splitter_left,1,wx.EXPAND) > > > > sizer_right = wx.BoxSizer(wx.VERTICAL) > > > > panel_right = wx.Panel(splitter,-1) > > > > splitter_right =wx.SplitterWindow(panel_right) > > > > splitter_right.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,self.rightChange > ,id=splitter_right.GetId()) > > > > panel_right_upper = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > > > panel_right_lower = wx.Panel(splitter_right,style= wx.BORDER_SUNKEN) > > > > panel_right_lower.SetBackgroundColour("WHITE") > > > > splitter_right.SplitHorizontally(panel_right_upper,panel_right_lower) > > > > sizer_right.Add(splitter_right,1,wx.EXPAND) > > > > splitter.SplitVertically(panel_left,panel_right) > > > > sizer.Add(splitter,1,wx.EXPAND) > > > > panel.SetSizer(sizer) > > > > panel_left.SetSizer(sizer_left) > > > > panel_right.SetSizer(sizer_right) > > > > self.splitter_left = splitter_left > > > > self.splitter_right = splitter_right > > > > def leftChange(self,event): > > > > pos = self.splitter_left.GetSashPosition() > > > > self.splitter_right.SetSashPosition(pos) > > > > event.Skip() > > > > def rightChange(self,event): > > > > pos = self.splitter_right.GetSashPosition() > > > > self.splitter_left.SetSashPosition(pos) > > > > event.Skip() > > > > app = wx.App(0) > > > > k = Layout(None, -1, 'layout.py') > > > > k.Show(True) > > > > app.MainLoop() > > > > -- Andrew > > > > ----- Original Message ----- > > From: "moonrie" > > > > Newsgroups: comp.lang.python > > Sent: Wednesday, March 12, 2008 10:19 PM > > Subject: help please, splitter windows like in maya or 3ds max > > > > > hi, everyone there, I am doing a 3D modeling project. I like to do it > > > with Python( am a newbie), but have no idea with the wxSplitterWindow > > > to create the 4-view windows( top, front, side, perspective), like the > > > mfc CSplitterWnd guy), > > > anyone can give me some help with wxPython? > > > > > thanks in advance. > > > > > - moonrie > > should be these ones, > > thanks, :P > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Thu Mar 6 11:03:42 2008 From: python at bdurham.com (Malcolm Greene) Date: Thu, 06 Mar 2008 11:03:42 -0500 Subject: Does python support working with password protected zip files? Message-ID: <1204819422.29123.1240935267@webmail.messagingengine.com> I'm new to Python and trying to figure out how to read and write to password protected zip files. I can work with plain zip files no problem. I've googled this topic and am coming up empty except for a post on Nabbler.com that seemed to imply that password protected zip files may(???) be supported in Python 2.6 and ads for a commercial Windows (only) zip component from chilkat.com. Any suggestions? Thank you, Malcolm From Robert.Bossy at jouy.inra.fr Tue Mar 25 13:01:08 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 25 Mar 2008 18:01:08 +0100 Subject: Inheritance question In-Reply-To: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <47E92FD4.2070204@jouy.inra.fr> Hi, I'm not sure what you're trying to actually achieve, but it seems that you want an identificator for classes, not for instances. In this case, setting the id should be kept out of __init__ since it is an instance initializer: make id static and thus getid() a classmethod. Furthermore, if you have several Foo subclasses and subsubclasses, etc. and still want to use the same identificator scheme, the getid() method would better be defined once for ever in Foo. I propose you the following: class Foo(object): id = 1 def getid(cls): if cls == Foo: return str(cls.id) return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the parent id and append its own id getid = classmethod(getid) class FooSon(Foo): id = 2 class Bar(Foo): id = 3 class Toto(Bar): id = 1 # Show me that this works for cls in [Foo, FooSon, Bar, Toto]: inst = cls() print '%s id: %s\n also can getid from an instance: %s\n' % (cls.__name__, cls.getid(), inst.getid()) One advantage of this approach is that you don't have to redefine the getid() method for each Foo child and descendent. Unfortunately, the "cls.__bases__[0]" part makes getid() to work if and only if the first base class is Foo or a subclass of Foo. You're not using multiple inheritance, are you? RB From jeff at schwabcenter.com Sun Mar 2 18:23:45 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 15:23:45 -0800 Subject: First post from a Python newbiw In-Reply-To: <5e3f7c46-802a-4305-984e-718ce2045f31@i29g2000prf.googlegroups.com> References: <62vrleF24ontgU2@mid.uni-berlin.de> <5e3f7c46-802a-4305-984e-718ce2045f31@i29g2000prf.googlegroups.com> Message-ID: <5MSdnavOndBMq1banZ2dnUVZ_oTinZ2d@comcast.com> castironpi at gmail.com wrote: >>>>> is there a better way of creating d?? >>>> a = [[0] * 3 for dummy in xrange(3)] >> Each element of a refers to a distinct array. >> >>> Why not simply [[0]*3]*3 ? >> All three elements of the result refer to the same array. > > ... whereas you reassign all three elements of [0]* 3. > >>>> ((0,)*3,)*3 > ((0, 0, 0), (0, 0, 0), (0, 0, 0)) > > You're safe in this one-- changing [0][0] won't change [1][0], 'cuz > you can't! A technically correct solution. :) From bearophileHUGS at lycos.com Sun Mar 30 07:27:49 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 30 Mar 2008 04:27:49 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <13uut2uabcbok38@corp.supernews.com> Message-ID: <5fcc899a-570e-4bc0-8091-1c966c1016c4@m73g2000hsh.googlegroups.com> hdante: > it's already time that programmer editors > have input methods advanced enough for generating this: > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) Take a look at Fortress language, by Sun. A free (slow) interpreter is already available. (Mathematica too allows you to write those symbols, but it costs a lot, and (despite tons of good things it has) as *programming language* it's awful, IHMO). Steven D'Aprano: > In Python we can write the above as: > if x != 0: > [f1(y) if y >= 0 else f2(y) for y in s] Your code builds an actual array (Python list) of results, while I think the original code just calls f1/f2. Bye, bearophile From mlists.sgv at gmail.com Wed Mar 19 03:24:41 2008 From: mlists.sgv at gmail.com (Sanjaya Vitharana) Date: Wed, 19 Mar 2008 12:54:41 +0530 Subject: Search the command history - Python Shell Message-ID: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> Hi All, Are there any simillar key combination in Python Shell like Linux Ctrl+R (reverse-i-search) to search the command history? Thanks. Sanjaya Vitharana -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Sun Mar 9 07:21:54 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 09 Mar 2008 07:21:54 -0400 Subject: What c.l.py's opinions about Soft Exception? References: Message-ID: Lie wrote: [ ... ] > Soft Exception > What is "Soft Exception"? > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. For example, if a variable turns into NoneType, > it'll raise Soft Exception that it have become NoneException, > programmers that wants to handle it can handle it with a try...except > block while programmers that doesn't care about it (or know it won't > be a problem to his code) can just leave the code as it is. > > Soft Exception differs from Hard Exceptions (the regular Exception) in > a way that Hard Exception must be handled at all cost or the program > will be terminated while Soft Exception allow programmers not to > handle it if they don't want to. [ ... ] > Ideology Base: > - EAAP: Easier to apologize than to ask permission. Sort of like a COME FROM statement. Drastic effects on program execution: a `raise SoftException` in the middle of a loop would break the loop if a catcher existed, or leave the loop running if not. It would really need the ability to resume after catching an exception. You can't really talk about 'apologize' around something that's so irreparable. I'd try for this effect by creating a class of objects with well-defined callbacks. Mel. From martin.laloux at gmail.com Sat Mar 15 16:42:49 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Sat, 15 Mar 2008 13:42:49 -0700 (PDT) Subject: Getting started with OS X Leopard References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Message-ID: if you are not satisfied with the native version, why not install the official version directly from python site http://www.python.org/download/ (macpython) instead of using that of macports. It moreover is provided with many utilities There is a macpython list that you can consult at http://www.nabble.com/Python---pythonmac-sig-f2970.html From craigm3604 at gmail.com Wed Mar 26 07:27:26 2008 From: craigm3604 at gmail.com (Craig) Date: Wed, 26 Mar 2008 04:27:26 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> <8fd0d8bd-c80a-4ec1-a70a-ea659a84413e@e6g2000prf.googlegroups.com> <13uh5bq2ri0280a@corp.supernews.com> <13ujk0ffekb3lc3@corp.supernews.com> Message-ID: On Mar 26, 12:24 am, Dennis Lee Bieber wrote: > On Tue, 25 Mar 2008 08:24:13 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > 41 0 0 0 > > 7 0 0 0 > > Which makes sense for two reasons: > > 1. It would only return the non-space-filled part of the returned key. > > 2. At least from VB6, the variable does not even have to be used > > before the call. > > Hmmm... I wonder what the library would have done if you just passed > a 0 to it... Rather than even doing that SysAlloc...() mess... > > PriKey = ctypes.int32(0) #or whatever the syntax was > > ... byref(PriKey) > > May with an effective null pointer the library would just allocate > directly rather than trying to determine the length field of the one > passed in. > > Something for the future, maybe... > > > print " DistID = \x22%s\x22" % DCOD.DistID > > You realize you can avoid those \x22 literals by changing the outer > quotes? > > print ' DistID = "%s" ' % .... > > or using triples > > print """ DistID = "%s" """ % ... > > > > > In other files, some of those fields are VB6 currency types, which > > have been described as 8-byte integers with an implied 4 decimal > > places (which I guess would be __int64 or c_longlong and then divide > > by 10,000, or simply put a decimal point 4 away from the end). > > Don't divide directly; you might lose significance as the result is > converted to double-precision float. > > You could possibly convert to string, splice in that . and then pass > the result to the Decimal module/type... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ I made these changes: # SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) SecKey = c_int32(0) ci_SecKey = c_int32(SecKey) # PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) PriKey = c_int32(0) ci_PriKey = c_int32(PriKey) And got: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 123, in ci_SecKey = c_int32(SecKey) TypeError: an integer is required Creating 2 "dummy" BSTR's isn't too bad of an option anyway. No, being somewhat new I didn't realize I could use (') in place if (") if I wanted to use a (") as a literal, but it seems to make a lot of sense now. I don't understand why I never tried it. As for the division vs. string manipulation, I agree - the string seems to be the simplest way to insure no loss of data. Thanks for all the input. From DustanGroups at gmail.com Thu Mar 13 08:42:05 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 13 Mar 2008 05:42:05 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> On Mar 13, 2:36 am, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above 5. From steve at REMOVE-THIS-cybersource.com.au Mon Mar 10 12:37:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Mar 2008 16:37:04 -0000 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <13taotgb321gn41@corp.supernews.com> On Mon, 10 Mar 2008 14:29:48 +0000, Andrew Koenig wrote: > So the question you need to answer is whether you want to determine > whether an object is exactly of type dict, or whether it you are willing > to accept types derived from dict also. Or other mappings that don't inherit from dict but behave just like dicts, such as UserDict. -- Steven From menosaint at gmail.com Fri Mar 14 01:44:54 2008 From: menosaint at gmail.com (menosaint at gmail.com) Date: Thu, 13 Mar 2008 22:44:54 -0700 (PDT) Subject: newbie question structure of function References: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> <37088f9c-e68e-483e-92a3-e730411a79bf@2g2000hsn.googlegroups.com> Message-ID: <5313a050-612f-47f9-ac3c-483888d10ece@i7g2000prf.googlegroups.com> Aaron thanx for the input > > resultname=""" > > That starts a string literal. i am not sure if this is the right way..i used it in case matchdistance < threshold return False.then the filename will not be taken from the filenameslist and so returns as an empty string. > > return (matchdistance,resultname) > > Parentheses optional there too. "return matchdistance," returns a > 'one-tuple'. but then the call matchvalue,matchfilename=findmatchingfile() will give ValueError trying to unpack from a one-tuple if anyone can suggest a more decent way of doing this pls do thanx vincent From castironpi at gmail.com Wed Mar 5 10:23:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 07:23:10 -0800 (PST) Subject: Protocol for thread communication References: Message-ID: On Mar 4, 11:12?pm, Michael Torrie wrote: > Does anyone have any recommended ideas/ways of implementing a proper > control and status protocol for communicating with threads? ?I have a > program that spawns a few worker threads, and I'd like a good, clean way > of communicating the status of these threads back to the main thread. > Each thread (wrapped in a very simple class) has only a few states, and > progress levels in those states. ?And sometimes they can error out, > although if the main thread knew about it, it could ask the thread to > retry (start over). ?How would any of you do this? ?A callback method > that the thread can call (synchronizing one-way variables isn't a > problem)? ?A queue? ?How would the main thread check these things? > Currently the main thread is polling some simple status variables. ?This > works, and polling will likely continue to be the simplest and easiest > way, but simple status variables are very limited. ?Are there any > pythonic patterns people have developed for this. > > thanks. > > Michael It depends on the messages. In the general form, 'do X', there are a lot of specifics relevant. - Do X at time T - for relative time T - for absolute time T - for conditional time T While the wording is vague, it illustrates a contrast. - Do X at time T - relative T -- T is a time offset into the future - absolute time T -- T is an absolute time, independent of the rest of the program - conditional time T -- under certain conditions, such as, right after X' finishes, right before X' starts, if Y happens during X In the big picture, the choice of X is irrelevant. However, in a particular PL, in a particular data, encapsulation, or abstraction model, some combinations of ( T, X ) may be impossible, or even long- winded, ugly, or wordy. For the idealists, an pure imperative model may fit best, so let X = 'set a bit', and conflict never arises. However such one restricts the universal turing machine-- can only write one value, which may or may not forbid solution of some problems. But without loss of generality, for X in { set B, reset B }, you have a conflict when for OPS= { (T1, X1), (T1, X2) }, X1= set B, and X2= reset B. Then there exists an ( X, T ) such that the semantics of the program are undefined. From fdrake at acm.org Sun Mar 2 21:22:27 2008 From: fdrake at acm.org (Fred Drake) Date: Sun, 2 Mar 2008 21:22:27 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: On Mar 2, 2008, at 8:35 PM, Kevin Teague wrote: > This issue was fixed for Python 2.5. As the issue notes, you can > work around it with: > > ./configure MACOSX_DEPLOYMENT_TARGET=10.5 Indeed, that works wonderfully for me for 2.4.5. > But it would be really nice if the configure fix for 2.5 was > backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped > system builds for 2.4 going direct from 2.3 -> 2.5. Yes, it would be very nice if this worked out of the box on Mac OS X 10.5.2. It's definitely a surprise for those of us who built our 2.4.4 on Mac OS X 10.4.x. -Fred -- Fred Drake From castironpi at gmail.com Sat Mar 29 05:08:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 02:08:20 -0700 (PDT) Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> Message-ID: <26eb664d-9bb4-4ef2-a839-994af666903a@d1g2000hsg.googlegroups.com> On Mar 28, 3:59?pm, castiro... at gmail.com wrote: > I want to regression a signal. ?It's NN, not necessarily, sine wave. > What kind of numbers of harmonic simultaneous sounds are we looking > at? ?How close to an A 440 can a human make? > > I want recognition to alert me. ?As a sine wave is coming in: > > >>> for t in [ ( 200* sin( x*2 ), 200* cos( x*2 ) ) for x in range( 10 ) ]: print( *t ) > > ... > 0.0 200.0 > 181.859485365 -83.2293673094 > -151.360499062 -130.728724173 > -55.8830996398 192.03405733 > 197.871649325 -29.1000067617 > -108.804222178 -167.814305815 > -107.3145836 168.770791746 > 198.121471139 27.3474436416 > -57.580663333 -191.531896065 > -150.197449354 132.063341649 > > Did everyone take the course on computer architecture? E.g. sum() is not an operation you do in world operations. (i question that 'walk' is.) you don't ( add ) drop to puddle, you move drop. we've all got graphics sub-primitives but no modelling ones. you don't want to decode sense cell inputs, do you? i'd say in complexity, one cell adds up to an entire input line-trail (wake). I would be proposing multiplexcating every CPU unit onto every input gate: off keystrokes and camera photovoltaics. (Light takes six - complexity- muscles, plus squinting, while not six calory-muscles.) So, taking outputs to be common combinations of inputs, unless you want symbological inputs to map to anything constructive. I think we design architecture utility-first. Ste p1. Big box? Would calculations include utility transponders (tabulation)? Time-scale is discretized. Can you be more productive continuously? Do you need to recognize users discretely, each an own interaction on file, due to discrete measures (discrete times)? It's more robotic than our interface with dogs. Does anyone have names for syllables? Superlatives are always theoretical. What can we learn from an executed time-space translation? Point is, sum() is not real, add is. I think event-driven stuff. It's non-destructive. Are there other tables after D.J.? He's predictable alright. Broadcast dropoff "sighted" (recognized). Is that bandwidth or baud? How quickly can you get total human decible out of a room? From grahn+nntp at snipabacken.se Sun Mar 30 17:50:25 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 21:50:25 GMT Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> <7x4paqy0sr.fsf@ruckus.brouhaha.com> <13uqqml7sk05ec8@corp.supernews.com> Message-ID: On Fri, 28 Mar 2008 22:01:57 -0000, Grant Edwards wrote: > On 2008-03-28, Paul Rubin wrote: >> castironpi at gmail.com writes: >>> Did everyone take the course on computer architecture? >> >> Yow! Does your SPEED QUEEN have CABLE? > > Ya know, I was thinking about trying to find an updated file of > Zippy quotes for use in my .sig, but I decided that having all > of the pop culture references be 30-years out of date was part > of the charm. "I hope the ''Eurythmics'' practice birth control ..." More like 20--25 years. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From Robert.Bossy at jouy.inra.fr Tue Mar 4 07:47:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 04 Mar 2008 13:47:57 +0100 Subject: Eurosymbol in xml document In-Reply-To: <634sleF25sd22U1@mid.uni-berlin.de> References: <634sleF25sd22U1@mid.uni-berlin.de> Message-ID: <47CD44FD.40206@jouy.inra.fr> Diez B. Roggisch wrote: > Hellmut Weber wrote: > > >> Hi, >> i'm new here in this list. >> >> i'm developing a little program using an xml document. So far it's easy >> going, but when parsing an xml document which contains the EURO symbol >> ('?') then I get an error: >> >> UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in >> position 11834: character maps to >> >> the relevant piece of code is: >> >> from xml.dom.minidom import Document, parse, parseString >> ... >> doc = parse(inFIleName) >> > > The contents of the file must be encoded with the proper encoding which is > given in the XML-header, or has to be utf-8 if no header is given. > > From the above I think you have a latin1-based document. Does the encoding > header match? If the file is declared as latin-1 and contains an euro symbol, then the file is actually invalid since euro is not defined of in iso-8859-1. If there is no encoding declaration, as Diez already said, the file should be encoded as utf-8. Try replacing or adding the encoding with latin-15 (or iso-8859-15) which is the same as latin-1 with a few changes, including the euro symbol: If your file has lot of strange diacritics, you might take a look on the little differences between latin-1 and latin-15 in order to make sure that your file won't be broken: http://en.wikipedia.org/wiki/ISO_8859-15 Cheers, RB From pavlovevidence at gmail.com Wed Mar 12 14:48:20 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Mar 2008 11:48:20 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: On Mar 12, 2:19 pm, Alex wrote: > Hi all, > > The subject says pretty much all, i would very appreciate an answer. I > tried to search the various forums and groups, but didn't find any > specific answer... Python technically has no equivalent: you can't run code at compile time. However, the BEGIN block in Perl seems to have been added to work around some of Perl's nonlinear order of execution. Normally in Python you don't need a BEGIN block: just put the code at the top of you script/module and it will exectute before anything else. Want to tell us what you need it for? Perhaps we can suggest a way of doing it that's appropriate in Python. Carl Banks From carsten at uniqsys.com Sun Mar 23 21:22:54 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 02:22:54 +0100 Subject: Does python hate cathy? In-Reply-To: <1206321511.3365.28.camel@localhost.localdomain> References: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> <1206321511.3365.28.camel@localhost.localdomain> Message-ID: <1206321774.3365.31.camel@localhost.localdomain> On Mon, 2008-03-24 at 02:18 +0100, I wrote the barely intelligible phrase: > I'm not sure what you mean by "accessing an unbound variable" means in > the context of this thread I'm starting to sound like castironpi. Time to go to sleep. -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Mon Mar 31 13:24:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 14:24:01 -0300 Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: En Mon, 31 Mar 2008 07:59:13 -0300, sam escribi?: > Steve Holden napisa?(a): > >>> 1. You have different syntax for named and unnamed (lambdas) >>> functions. Functions and methods are different things in Python even >>> if they have same syntax. But all these are still a pieces of code >>> that you use repeatedly to make some task. >>> >> A knife and scissors are both used to cut things, but that doesn't mean >> they are the same. > > Well -- sometimes you have to use many, many types of scissors. I don't get the point - weren't you criticizing Python for having many different kind of functions? >> The desire to provide information hiding is fundamentally against the >> Python philosophy, which basically says that attribute values are >> exposed for all to see. This avoids the nonsense of having to provide >> setter and getter methods which Java imposes on the programmer. > > This philosophy is great and makes Python such a good language. But you > can't go > beyond what programmers need. If you do so, then you will have to > implement > tricks as __id. The __id "trick" is not for hidding instance attributes, but to avoid name collisions. Unlike other languages, all instance attributes share a single namespace, you can't qualify a reference to say "the foo attribute from this base class, not this other foo": it is always "the foo attribute" no matter inside which class it was assigned. The __ prefix creates mangled names so __foo used inside a certain class is a different attribute name than __foo outside that class. It is not used to "hide" the attribute, the rules for the mangled name are very easy to emulate. What are those programmers needs? -- Gabriel Genellina From kay.schluehr at gmx.net Sun Mar 9 10:29:02 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 9 Mar 2008 07:29:02 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> Message-ID: <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> On 9 Mrz., 13:50, Lie wrote: > On Mar 9, 4:31 pm, Kay Schluehr wrote: > > > > > On 9 Mrz., 09:30, Lie wrote: > > > On Mar 9, 12:05 pm, Kay Schluehr wrote: > > > > > On 9 Mrz., 04:51, Lie wrote: > > > > > > A more through implementation would start from the raiser inspecting > > > > > the execution stack and finding whether there are any try block above > > > > > it, if no try block exist it pass silently and if one exist it will > > > > > check whether it have a matching except clause. This also circumvents > > > > > a problem that simple implementation have, as described below. > > > > > This will not be easy in particular in the presence of inheritance and > > > > dynamism. There is no way to statically decide whether an exception > > > > BException has the type AException and will be caught by the except > > > > clause in > > > > > try: > > > > BLOCK > > > > except AException, e: > > > > print "SoftException %s caught"%e > > > > A feasible solution was to invert the try...except statement and > > > > creating a continuation. > > > > > catch AException, a: > > > > print "SoftException A: %s"%a > > > > catch BException , b: > > > > print "SoftException B: %s"%b > > > > ... > > > > in: > > > > BLOCK > > > > > Here each SoftException is raised initially when a catch clause is > > > > entered and a continuation is created that returns to the catch block > > > > of the raised SoftException if required. When a SoftException is > > > > raised within BLOCK a lookup will be made and if a corresponding > > > > SoftException was found that was raised by a catch-clause the current > > > > control flow will be suspended and the continuation is called. > > > > I'd rather want to avoid any syntax changes, as I wished that Soft > > > Exception can be added to the language silently[1] so that new > > > programmers doesn't _need_ to know about it (although knowing it could > > > change the way they write codes to be more structured and simple). > > > I just tried to save your proposal from being unimplementable. Maybe > > you can comment on it? > > Perhaps I'm not the appropriate person to talk about whether unchanged > syntax is feasible for such implementation since I basically have no > idea about how Python's internals works. It's only that I think if > current syntax could be used, we could just use it (except if there is > a strong reason why it shouldn't be done). You are an appropriate person to consider the workflow in a dynamic language, no matter how the language is implemented internally. Just start with function calls maybe_raise(ZeroDivisionError) The only requirement is that maybe_raise has to know when it shall raise ZeroDivisionError. This depends on whether the exception is caught. How do the program knows this in advance? There are no static analysis techniques available. When maybe_raise is entered the system must know that the exception is handled in the future. You can't inspect the call stack for this purpose because the call stack represents past events and continuations ( and you can't rely on names ). So you need something like this do_softexception(ZeroDivisionError) try: TRY_BLOCK except ZeroDivisionError: EXCEPT_BLOCK But this looks odd and the solution isn't DRY. So better one macro- transforms a new statement into this form. From mwolffedu at gmail.com Sat Mar 15 22:33:55 2008 From: mwolffedu at gmail.com (lampshade) Date: Sat, 15 Mar 2008 19:33:55 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: On Mar 15, 9:27 pm, Benjamin wrote: > On Mar 15, 8:12 pm, lampshade wrote:> Hello, > > > I'm having some problems with os.path.isdir I think it is something > > simple that I'm overlooking. > > > #!/usr/bin/python > > import os > > > my_path = os.path.expanduser("~/pictures/") > > print my_path > > results = os.listdir(my_path) > > for a_result in results: > > if os.path.isdir(str(my_path) + str(a_result)): > > Try if os.path.isdir(os.path.join(my_path, a_result)):> results.remove(a_result) > > > for x in results: print x > > > The problem is, that the directories are never removed. Can anyone > > point out what I'm missing that is causing the bug? Is there a better > > way of doing this? > > You should always use os.path.join to join paths. You shouldn't add > them like normal strings. I suspect you're getting a combination which > doesn't exist, so it isn't a dir. :) > > > > > Thanks, Thanks, that nailed it perfectly! I'll remember the os.path.join from now on! From lists at cheimes.de Tue Mar 25 16:03:15 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 25 Mar 2008 21:03:15 +0100 Subject: Circular references not being cleaned up by Py_Finalize() In-Reply-To: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: blackpawn schrieb: > So what's the deal here? :) I want all objects to be freed when I > shut down and their destruction functions to be properly called. Is > there really no way to make this happen? Does the Noddy example use GC (Py_TPFLAGS_HAVE_GC)? Container objects must use the cycle GC or circular referneces aren't broken. Have you tried calling PyGC_Collect() multiple times? Christian From bruno.desthuilliers at gmail.com Mon Mar 31 15:30:38 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 31 Mar 2008 12:30:38 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: <7eb5d21a-c4de-4655-ab93-9221d996f424@i7g2000prf.googlegroups.com> On 31 mar, 20:09, Duncan Booth wrote: > xkenneth wrote: > > Now obviously, if I test an instance of either class equal to each > > other, an attribute error will be thrown, how do I handle this? I > > could rewrite every __eq__ function and catch attribute errors, but > > that's tedious, and seemingly unpythonic. Also, I don't want an > > attribute error thrown whenever two classes are compared that don't > > have the same attributes. > > > I have a sneaky feeling I'm doing something completely unpythonic > > here. > > Surely an A isn't equal to every other object which just happens to have > the same attributes 'a' and 'b'? And why not ?-) > I would have thoughts the tests want to be > something like: > > class A: > def __eq__(self,other): > return (isinstance(other, A) and > self.a == other.a and self.b == other.b) > > (and similar for B) with either an isinstance or exact match required for > the type. I don't think there's a clear rule here. Python is dynamically typed for good reasons, and MHO is that you should not fight against this unless you have equally good reasons to do so. From kperkins257 at gmail.com Mon Mar 10 20:29:29 2008 From: kperkins257 at gmail.com (kperkins257 at gmail.com) Date: Mon, 10 Mar 2008 17:29:29 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: On Mar 10, 3:33 pm, Mike Driscoll wrote: > On Mar 10, 2:11 pm, Stefan Behnel wrote: > > > > > Malcolm Greene wrote: > > >> My personal experience with wxPython has its ups and downs. Specifically > > >> when it comes to crashes, I wouldn't bet my life on it. > > > > I'm new to Python and getting ready to build a small client based > > > application intended to run on Windows and Linux. I was planning on using > > > wxPython until I saw your comment above. > > > Just to make this sound a bit less like FUD: my last experience with wxPython > > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > > in a project, which crashed a bit too often to do real work with it - and with > > crashing I mean crashing Python, not just showing us its blank traceback. So > > this was definitely a problem either in wxWindows or in wxPython. > > > I have no idea how well it works today, but this has definitely forged my > > opinion on wxPython. > > > > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > > > or tips on where I can find out more about wxPython/wxWidget problems? > > > The only other GUI library I used was PyQT3. To me, it has proven to be very > > stable, pretty easy to use and feature rich. And from what I read about it, > > PyQT4 is supposed to be another lot better and has removed the few API quirks > > I found at the time (AFAIR, it finally returns plain Python strings from the > > API, for example). > > > Stefan > > I agree with Stef. Boa is definitely goofy and while I know some > people swear by it, I see far too many people having issues. I go with > hand coding or XRC. Some also like SPE, but I haven't tried that to > know. > > Mike SPE is actually a very good editor--I'm using it for all my Python coding. It integrates well with wxglade, and wxpython, and is built on wxpython. I've used wxpython on a couple of little projects, and it works very well (on Linux, anyways). I'm starting a couple of bigger projects now, and am confident that it will scale up, seeing some of the projects that are using it. I've tried Boa a couple of times but, for me, the interface sucks, and is not very intuitive. From gandalf at shopzeus.com Tue Mar 25 05:26:04 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Mar 2008 10:26:04 +0100 Subject: StringIO + unicode Message-ID: <47E8C52C.9060501@shopzeus.com> Is there a standard "in-memory file" interface for reading/writting unicode stings? Something like StringIO. E.g. this would be possible: - create UnicodeStringIO - write unicode strings into it - wite data (binary) string of UnicodeStringIO into a file ('wb' mode) and then later: - read the same file with codecs.open(filename,"r",encoding="utf-8") Maybe there is no standard class for this and I have to implement it myself. (?) Thanks, Laszlo From cokofreedom at gmail.com Thu Mar 13 06:51:42 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 13 Mar 2008 03:51:42 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <7x1w6enbwi.fsf@ruckus.brouhaha.com> <7xtzjalx05.fsf@ruckus.brouhaha.com> Message-ID: <2c744609-19e5-4b3b-8cf8-607e1990fb13@n58g2000hsf.googlegroups.com> Still, I suppose this is a gotcha for a lot of people, just follow the good advice Paul said; "By Python convention, methods that mutate the object return None, and also stuff that returns None doesn't generate output at the interactive prompt." And you should survive most. From steve at REMOVE-THIS-cybersource.com.au Mon Mar 17 09:37:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 17 Mar 2008 13:37:39 -0000 Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> Message-ID: <13tst1388cp67d8@corp.supernews.com> On Mon, 17 Mar 2008 10:40:43 +0000, Duncan Booth wrote: > Here's a puzzle for those who think they know Python: > > Given that I masked out part of the input, which version(s) of Python > might give the following output, and what might I have replaced by > asterisks? There's too many variables -- at least five Python implementations that I know of (CPython, Jython, PyPy, IronPython, and the Lisp-based implementation that I can never remember the name of), and given that this is an implementation-dependent feature it could have changed at any time, in any version number (say, between minor releases). And there's literally an infinite number of ways to get b equal to an int with the value 1. So I think unless somebody happens to have stumbled across this behaviour, it's not predictable. But having said that, I'm going to take a stab in the dark: The line "b = ****" should be "b = int('1')" and the version is CPython 1.4. Am I close? -- Steven From rsarpi at gmail.com Thu Mar 6 19:46:08 2008 From: rsarpi at gmail.com (icarus) Date: Thu, 6 Mar 2008 16:46:08 -0800 (PST) Subject: Flash interface for a python program Message-ID: Is it possible to call an external python program, through a Flash interface? Meaning, I create a Flash window with a button. When I press that button, it automagically invokes the external python program. Is that possible? Any books/online tutorials you can recommend me? I guess I'm looking for alternatives in the area of GUI development. From jeffrey at fro.man Mon Mar 24 15:14:29 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 24 Mar 2008 12:14:29 -0700 Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <13ufvcl5lbda972@corp.supernews.com> pythonnubie wrote: > The exeption > is " no such ?attribute " in ?module random Is your own source file named "random.py" by chance? If so, rename it, and be sure to remove the leftover random.pyc file as well. Jeffrey From deets at nospam.web.de Tue Mar 4 08:32:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Mar 2008 14:32:21 +0100 Subject: Eurosymbol in xml document References: <634sleF25sd22U1@mid.uni-berlin.de> Message-ID: <6351b3F25irgtU1@mid.uni-berlin.de> > If the file is declared as latin-1 and contains an euro symbol, then the > file is actually invalid since euro is not defined of in iso-8859-1. If > there is no encoding declaration, as Diez already said, the file should > be encoded as utf-8. > You are right of course - latin1 doesn't contain the euro-symbol. ISO-8859-15 it is. Dumb me. Diez From cantabile.03 at wanadoo.fr Mon Mar 17 22:12:19 2008 From: cantabile.03 at wanadoo.fr (cantabile) Date: 18 Mar 2008 02:12:19 GMT Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <0369b78b-6681-4807-b944-fb371cdd1522@59g2000hsb.googlegroups.com> Message-ID: <47df2503$0$868$ba4acef3@news.orange.fr> Le Mon, 17 Mar 2008 09:03:07 -0700, joep a ?crit?: > An example: looks for all 'junk*.txt' files in current directory and > replaces in each line the string 'old' by the string 'new' > Josef Works like a charm. Many thanks for the example Josef :-) From bronger at physik.rwth-aachen.de Sun Mar 30 17:08:15 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 30 Mar 2008 23:08:15 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> <659gb2F2f84eoU2@mid.individual.net> <6deb5443-e87b-448e-a1a6-6a1886c9f12a@x41g2000hsb.googlegroups.com> Message-ID: <87od8vzzr4.fsf@physik.rwth-aachen.de> Hall?chen! hdante writes: > On Mar 30, 9:45 am, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: > >> hdante wrote: >> >>> BTW, my opinion is that it's already time that programmer >>> editors have input methods advanced enough for generating this: >> >> Could you please list some that do, and are also convenient? > > AFAICT there's none. This should be easy to implement on emacs, It *is* implemented in Emacs. You can even choose from many input methods, optimised for differend areas/languages. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From timr at probo.com Sat Mar 15 01:47:23 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Mar 2008 05:47:23 GMT Subject: Joseph Weizenbaum References: Message-ID: Jeff Schwab wrote: >Roel Schroeven wrote: >> castironpi at gmail.com schreef: >>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>>> Subject: RIP: Joseph Weizenbaum >>>>> Creator of Eliza: >>>>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>>>> >>>> How do you feel about creator of Eliza? >>> >>> What is Eliza? >> >> Does that question interest you? > >Well played, sir. > >Earlier you said what is Eliza. Do you still feel that way? I am embarrassed to say that this vaguely disrespectful exchange made me laugh out loud. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sun Mar 2 17:43:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 14:43:40 -0800 (PST) Subject: Function Overloading and Python References: Message-ID: On Feb 25, 11:04?am, castiro... at gmail.com wrote: > > B1.fun(A(x), A(y), A(z)) == B.fun(A(x), A(y), A(z)) > > but > > B1.fun(A1(x), A(y), A(z) != B.fun(A1(x), A(y), A(z)) > > > Is there a data-structure solution or third party module that would > > mimic this behavior? > > class B: > ? ?xfun= Overloaded() > ? ?def fun( self, *a ): > ? ? ? return self.xfun.dispatch( self, *a ) > ? ?@xfun.make( A, A, A ) > ? ?def q( self, x, y, z ): > ? ? ? return 'B AAA' > ? ?@xfun.make( A1, A, A ) > ? ?def q( self, x, y, z ): > ? ? ? return 'B A1AA' > B.xfun.push( B ) You could also call xfun.methods( self ) in B.__init__. Overloaded.methods binds the methods specified with xfun.make to the B instance. In this case, the effect is, self.fun= types.MethodType( self.__class__.[x?]fun, self ) -- I forget by now. But time is money, and money doesn't grow on trees-- so catch me later with your own. (A decorator could also do it too-- and just in the base class!) From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 06:01:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 10:01:53 -0000 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> Message-ID: <13us4sh6u8mfn96@corp.supernews.com> On Sat, 29 Mar 2008 10:11:28 +0100, Roel Schroeven wrote: > Steven D'Aprano schreef: >> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: >> >>> Gabriel Genellina wrote: >>>> That's what I said in another paragraph. "sum of coordinates" is >>>> using a different distance definition; it's the way you measure >>>> distance in a city with square blocks. I don't know if the distance >>>> itself has a name, but >>> I think it is called Manhattan distance in reference of the walking >>> distance from one point to another in this city. >> >> You know, there are other cities than Manhattan. Some of them even have >> streets and blocks. > > I'm not sure what your point is. The name "The" name? You go on to list four additional names, so why do you say that "Manhattan distance" is THE name? When I studied this at university, we called it the taxi metric. > of the distance happens to be > Manhattan distance (or taxicab distance, rectilinear distance, L1 > distance, city block distance; see > http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid > point. Wikipedia doesn't believe that M-D is the primary or most common name, and the link you give redirects to "Taxicab distance". Googlefight agrees: "Taxicab distance" is more than twice as common, and "rectilinear distance" more than five times as common. My point was to draw attention to Robert's unconscious assumptions which are reflected in his choice of language. Rectilinear distance applies to more than "distance from one point to another in THIS city" (emphasis added). It applies in parts of Rome, Sydney, London, Moscow and many other places. It even applies to sleepy little country towns like Bendigo and Mildura here in Australia. Manhattan is hardly the only place where cities are carved up into rectangular or square city blocks, and I doubt that it applies to the entirety of Manhattan. It also applies to supermarket isles, church pews, chess boards, pixels on a monitor and no doubt other places as well. The very name is New York-centric, just as much as if the English called the science of acoustics "Big-Ben-onics" in reference to the peals of Big Ben's clock. I had thought I had pointed that out with a little gentle understatement. -- Steven From mdw at distorted.org.uk Mon Mar 31 14:10:03 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Mon, 31 Mar 2008 18:10:03 +0000 (UTC) Subject: deleting a line from a file References: <13usb5ngt26qv26@corp.supernews.com> <7xy781zqkq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > You could do it "in place" in all those systems afaik, either opening > the file for both reading and writing, or using something like mmap. > Basically you'd leave the file unchanged up to line N, then copy lines > downward starting from line N+1. At the end you'd use ftrunc to > shrink the file, getting rid of the duplicate last line. Making a new copy and renaming it when you're finished is probably both easier (don't have to keep seeking about all the time) and more reliable (doesn't leave your file corrupted if you crash half-way through). Is there a standard wossname which does this? from __future__ import with_statement from contextlib import contextmanager import os, sys, errno def fresh_file(base, mode = 'w'): """ Return a file name and open file handle for a fresh file in the same directory as BASE. """ for seq in xrange(50): try: name = '%s.new.%d' % (base, seq) fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL) f = os.fdopen(fd, mode) return name, f except OSError, err: if err.errno == errno.EEXIST: pass else: raise raise IOError(errno.EEXIST, os.strerror(errno.EEXIST), base) @contextmanager def safely_writing(filename, mode = 'w'): """ Context manager for updating files safely. It produces a file object. If the controlled suite completes successfully, the file named by FILENAME is atomically replaced by the material written to the file object; otherwise the file is left alone. Safe in the presence of multiple simultaneous writers, in the sense that the resulting file is exactly the output of one of the writers (chosen nondeterministically). """ f = None newname = None try: newname, f = fresh_file(filename, mode) yield f f.close() f = None os.rename(newname, filename) finally: if f is not None: f.close() if newname is not None: try: os.unlink(newname) except: pass It seems like an obvious thing to want. (Extra messing about will be needed on Windows, which doesn't have proper atomic-rename semantics. Playing with the transactional filesystem stuff is left as an exercise to the interested student.) -- [mdw] From Frank.Aune at broadpark.no Mon Mar 3 06:41:26 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Mon, 3 Mar 2008 12:41:26 +0100 Subject: Python logging: Retrieving the last log record from a handler Message-ID: <200803031241.26857.Frank.Aune@broadpark.no> Hi, I'm using a log hierarchy in my application, and sometimes I find myself wanting to retrieve the latest log message written to the root logger. (Typical usage might be displaying the latest log message at all times in a GUI). The only way I've found how to solve this, is by adding a custom loghandler: --- class LastRecordHandler(logging.Handler): def __init__(self): logging.Handler.__init__(self) self.lastRecord = None def emit(self, record): self.lastRecord = record def getRecord(self): return self.lastRecord.getMessage() --- I will be fairly surprised if this functionality is not already built-in for the default logging handlers, but so far I've been unable to figure out how to pull it of without the custom loghandler above. The kind of functionality I'm looking for is something like: self.log = logging.getLogger('GUI') (...) lastRecord = self.log.getLastRecord() # Display lastRecord in GUI Is this possible in some way, or do I need to extend the default logging handlers in order to archieve this? Thanks, Frank From Lie.1296 at gmail.com Tue Mar 11 15:30:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 12:30:59 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> <63ns5vF1fcb15U1@mid.uni-berlin.de> Message-ID: <9a0f1e31-7e3a-47ad-a5cf-063829ac7f85@s37g2000prg.googlegroups.com> (If there is anything weird that I say, please ignore it since I'm writing this half-sleeping) On Mar 12, 12:00?am, "Diez B. Roggisch" wrote: (snip) > I totally fail to see where > > raise Equal(a, b) > > is less cluttered or not than > > callback(a, b) > > Actually, the latter is even less cluttered, misses a raise - if pure number > of literals is your metric, that is. You don't just compare by the calling code, you've got to compare also by the surrounding codes. The calling codes in SE might be a little bit messy, but it worths by making the code surrounding it more clean and structured. And anyway, if you used Context Object callback, they will be as messy as each other. > > If there is a syntax support, you could also make "resume" able to > > transfer values: > > > ? ? def somefunc(a, b): > > ? ? ? ? if a == b: a, b = raise Equal(a, b) > > > ? ? def toplevel(): > > ? ? ? ? try: > > ? ? ? ? ? ? somefunc(10, 20) > > ? ? ? ? except Equal, args: > > ? ? ? ? ? ? a, b = args[0], args[1] + 1 > > ? ? ? ? ? ? resume a, b > > Sure, you can make all kinds of things, but so far you didn't come up with a > comprehensive feature description that just _does_ specify what SEs are and > what not. - Exception that aren't handled when no handler exists for it. - It's not a way for notifying errors - It's a way to describe status changes to higher codes - Everything described in the first post > > Perhaps you meant: > > ? ? raise_soft(SoftException) > > > cause SoftException() may have side effects if called greedily > > Nope, I didn't, and it's beside the point. Then what happen when SoftException is called? And a side-effect occurs? > > That could be done, but when raise_soft() returns, it returns to the > > code that raises it so it must be 'break'en: > > > ? ? def caller(a, b): > > ? ? ? ? if a == b: > > ? ? ? ? ? ? raise_soft(SoftException) > > ? ? ? ? ? ? break > > > but this makes SoftException must break everytime, which make it lost > > its original purpose, so you have to add return code to raise_soft > > whether you want to break it or not: > > You didn't understand my example. If there is a handler registered, it will > be invoked. If not, nothing will be raised. The exact same amount of > state-keeping and lookups needs to be done by the SE-implementation. I do understand your example. And even if I misunderstood you about passing context object, the same problem still exists in context object based solution, i.e. functions can't make the called function break automatically, it must be 'break' manually or the program will go astray (break ==> return, sorry I confused it with break for loops). And if you used InterruptException to break, it doesn't play well with multiple SoftExceptions. The final, resulting code by function passing below is extremely messy, see if you can make it cleaner and with the same functionalities and all to the SE version. def called(a, b, cont_obj = Null_CO): if a == b: a, b = cont_obj.a_equal_b(a, b) cont_obj.addition(a, b) return a + b def caller(): class cont_obj(object): def a_equal_b(a, b): if a < 0 and b < 0: return a + 1, b # resume raise InterruptException(('a_e_b',)) # break def addition(a, b): if a > b: return raise InterruptException(('addit', (a, b))) # break try: called(10, 10, cont_obj) except InterruptException, args: # if breaken ret, arg = args if ret == 'a_e_b': return -1 a, b = arg if ret == 'addit': return a ** b # by adding try clauses, and you've really equalize the biggest overhead of SE. # And I don't think you could create a less messy InterruptException handler, # the other solution to it would be to create a handler for each unique returns # but that would make it exceed the second SE overhead, the Exception Declaration # In other words, the tricks that is used to emulate the SoftException would all # have higher code overhead compared to using the clean, structured SEs # * Overheads means garbage code that's important to make something work # The code is separated into three parts, "try except", and cont_obj, and called. Worse, the cont_obj can't determine what happen if they got unresumed errors, without using some tricky part. Compare that code above with: def called(a, b): if a == b: a, b = raise a_equal_b(a, b) raise addition(a, b) return a + b def caller(): class a_equal_b(Exception): pass class addition(Exception): pass try: ret = called(10, 10) except a_equal_b(a, b): if a < 0 and b < 0: resume a + 1, b return -1 except addition(a, b): if a > b: resume return a ** b # The code is separated into two parts, the "trys and excepts" and the called code. > > That could be done, but when raise_soft() returns, it returns to the > > code that raises it so it must be 'break'en: > > ? ? def caller(a, b): > > ? ? ? ? if a == b: > > ? ? ? ? ? ? if raise_soft(SoftException): > > ? ? ? ? ? ? ? ? break > > > Compare to: > > ? ? def caller(a, b): > > ? ? ? ? if a == b: > > ? ? ? ? ? ? raise SoftException > > > And this also makes it impossible to have state-changing behavior > > without some other weirder tricks > > That's not true. The > > with add_soft_handler(SoftException, handler): > > approach (I missed the handrel the first time, sorry) > can easily throw an exception to interrupt, like this: > > def handler(e): > ? ? if some_condition_on_e(e): > ? ? ? ?raise InterruptException() > > with add_soft_handler(SoftException, handler): > ? ? ?try: > ? ? ? ? ? work(...) > ? ? ?except InterruptException: > ? ? ? ? ? pass > > You could also introduce a function > > def interruptable(fun, *args, **kwargs): > ? ? try: > ? ? ? ?return fun(*args, **kwargs) > ? ? except InterruptException: > ? ? ? ?passthe > > to make the code look a bit cleaner - if it fits your usecase, that is of > course. The code doesn't work well with multiple excepts that have multiple fallbacks. > I don't say that SoftExceptions can't have semantics that go beyond this. I > just don't see a oh-so-compelling use-case that makes things so much better > than they are reachable now, without actually much programming. From zerty.david at gmail.com Mon Mar 31 16:56:48 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 31 Mar 2008 17:56:48 -0300 Subject: Python and Db In-Reply-To: <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> Message-ID: <5dc598e30803311356p6a5cf418oe9930a118d441e96@mail.gmail.com> It's DB = DataBase, I typed wrong on the text, but right at the subject =) On Mon, Mar 31, 2008 at 5:50 PM, David Anderson wrote: > I would like to use sqlite, But I also wanted a tutorial with the basis of > the sql and etc, I never dealed with dbs before > > > On Mon, Mar 31, 2008 at 3:42 PM, Gabriel Genellina > wrote: > > > En Mon, 31 Mar 2008 14:50:27 -0300, David Anderson < > > zerty.david at gmail.com> > > escribi?: > > > > > Hi! I'm don't know almost nothing about bds, Can You suggest me an > > Simple > > > but efficient Bd to work with python apps? Can You suggest me any > > > tutorials? > > > > See the Python wiki at: http://wiki.python.org/moin/DatabaseProgramming > > If you stick with DBAPI 2.0 you won't have much trouble writing for one > > database or another. sqlite is a good start and is included with Python > > 2.5 > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Tue Mar 4 13:07:31 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Tue, 04 Mar 2008 12:07:31 -0600 Subject: for-else In-Reply-To: References: Message-ID: <47CD8FE3.4070801@ncee.net> > if a == 0: > do_task_0() > elif a == 1: > do_task_1() > elif a == 2: > do_task_2() > else: > do_default_task() The if-elif-else structure that calls functions (like that above) can be avoided with the code below: def foo0(): print 'foo0' def bar0(): print 'bar0' def foo1(): print 'foo1' def bar1(): print 'bar1' def do_default_task(): print 'do_default_task' do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, } a = 1 # example of normal usage if a in do_task.keys(): do_task[a]() else: do_default_task() # example of testing all functions in the dict as well as the default function for a in do_task.keys() + [8]: # 8 is a non-existent key in the do_task dict print "a is ",a,"and it gives this output:", if a in do_task.keys(): do_task[a]() else: do_default_task() Carl Banks wrote: > On Mar 4, 10:55 am, "BJ?rn Lindqvist" wrote: > >> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks wrote: >> >>> > for ...: >>> > ... >>> > exhausted: >>> > ... >>> > broken: >>> > ... >>> >>> > The meaning is explicit. While "else" seems to mean little there. >>> > So I may like something similar for Python 3.x (or the removal of the >>> > "else"). >>> >>> I would not be opposed to this on its own merits, but there is a >>> rationale behind the name "else". If you consider a for loop to be a >>> rolled-up if...elif...else statement (situations where this is >>> reasonable tend to be the same ones were else would be useful), then >>> the "else" clause would remain unchanged on the for loop. >>> >>> For instance, if you have a (trivial) if...elif...else like this: >>> >>> if a == 0: >>> do_task_0() >>> elif a == 1: >>> do_task_1() >>> elif a == 2: >>> do_task_2() >>> else: >>> do_default_task() >>> >>> You could roll it up into a for...else statement like this: >>> >>> for i in range(3): >>> if a == i: >>> do_task[a]() >>> else: >>> do_default_task() >>> >> You forgot the break statement. The else suite will always be executed >> in this loop. Kind of proves bearophiles point, for-else is really >> tricky. >> > > Ah ha, but that would have been a mistake with or without the else > clause.... > > > Carl Banks > This approach works well for me: def foo0(): print 'foo0' def bar0(): print 'bar0' def foo1(): print 'foo1' def bar1(): print 'bar1' def do_default_task(): print 'do_default_task' do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, } a = 1 # example of normal usage if a in do_task.keys(): do_task[a]() else: do_default_task() # example of testing for i in range(len(do_task.keys)): if a in do_task.keys(): do_task[a]() else: do_default_task() -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From KephnosAnagennao at gmail.com Sun Mar 23 03:32:28 2008 From: KephnosAnagennao at gmail.com (sgharvey) Date: Sun, 23 Mar 2008 00:32:28 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> Message-ID: On Mar 22, 5:03 pm, "Gabriel Genellina" wrote: > En Sat, 22 Mar 2008 17:27:49 -0300, sgharvey > escribi?: > Take a look at ConfigObjhttp://pypi.python.org/pypi/ConfigObj/ Thanks for the pointer; I'll check it out. > I'm not sure you can process a config file in this unstructured way; looks > a lot easier if you look for [sections] and process sequentially lines > inside sections. It works though... now that I've fixed up all my ugly stuff, and a dumb logic error or two. > The regular expressions look strange too. A comment may be empty. A > setting too. There may be spaces around the = sign. Don't try to catch all > in one go. I didn't think about empty comments/settings... fixed now. It also seemed simpler to handle surrounding spaces after the match was found. New version of the problematic part: self.contents = [] content = {} # Get the content in each line for line in lines: for name in patterns: # Match each pattern to the current line match = patterns[name].search(line) if match: content[name] = match.group(0).strip() self.contents.append(content) content = {} new iniparsing.py http://pastebin.com/f445701d4 new ini_regexen_dicts.py http://pastebin.com/f1e41cd3d > -- > Gabriel Genellina Much thanks to all for the constructive criticism. Samuel Harvey From stefan_ml at behnel.de Sun Mar 16 10:57:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 16 Mar 2008 15:57:16 +0100 Subject: Types, Cython, program readability In-Reply-To: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <47DD354C.3020501@behnel.de> Hi, bearophileHUGS at lycos.com wrote: > It seems Cython is going to become an efficient and > general purpose language after all, with optional static typing (its > purpose: mostly for speed), and it may even gain some kind of macros > soon. So it may even end replacing Python itself in some situations > where running efficiency is important, and where Psyco can't be used > or isn't enough. Even without any static type annotations, Cython currently runs the supported portion of pybench some 30% faster than CPython 2.5.1, with for-loops and if-then-else being multiple times faster. Even on plain Python numbers, arithmetic gives you a factor of 2 in Cython. http://comments.gmane.org/gmane.comp.python.cython.devel/680?set_lines=100000 If you need more, C arithmetic and integer loops can easily be enabled with type annotations, and the Cython project is working on further optimisations for normal Python code. So if speed is important and the existing code is supported by Cython (or can be made working), compilation is definitely an option. Stefan From danb_83 at yahoo.com Mon Mar 17 02:51:14 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 16 Mar 2008 23:51:14 -0700 (PDT) Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> Message-ID: Bernard Lim wrote: > Hi, > > I'm reading the Python Reference Manual in order to gain a better understanding > of Python under the hood. > > On the last paragraph of 3.1, there is a statement on immutable and mutable > types as such: > > > Depending on implementation, for immutable types, operations that compute > new values may or may not actually return a reference to any existing object > with the same type and value, while for mutable objects this is (strictly)? > not allowed. > > > Using the example given in 3.1, how do I verify that this is true pertaining > to immutable types? Below is my understanding on verifying the above statement: > > >>> a = 1 > >>> b = 1 > >>> a is b > True > >>> id(a) > 10901000 > >>> id(b) > 10901000 > > Is this correct? Yes, that's correct. However, >>> a = 100 >>> b = 100 >>> a is b False >>> id(a) 135644988 >>> id(b) 135645000 From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 23:39:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 10 Mar 2008 03:39:22 -0000 Subject: any chance regular expressions are cached? References: Message-ID: <13t9bbap76cbdf3@corp.supernews.com> On Mon, 10 Mar 2008 00:42:47 +0000, mh wrote: > I've got a bit of code in a function like this: > > s=re.sub(r'\n','\n'+spaces,s) > s=re.sub(r'^',spaces,s) > s=re.sub(r' *\n','\n',s) > s=re.sub(r' *$','',s) > s=re.sub(r'\n*$','',s) > > Is there any chance that these will be cached somewhere, and save me the > trouble of having to declare some global re's if I don't want to have > them recompiled on each function invocation? At the interactive interpreter, type "help(re)" [enter]. A page or two down, you will see: purge() Clear the regular expression cache and looking at the source code I see many calls to _compile() which starts off with: def _compile(*key): # internal: compile pattern cachekey = (type(key[0]),) + key p = _cache.get(cachekey) if p is not None: return p So yes, the re module caches it's regular expressions. Having said that, at least four out of the five examples you give are good examples of when you SHOULDN'T use regexes. re.sub(r'\n','\n'+spaces,s) is better written as s.replace('\n', '\n'+spaces). Don't believe me? Check this out: >>> s = 'hello\nworld' >>> spaces = " " >>> from timeit import Timer >>> Timer("re.sub('\\n', '\\n'+spaces, s)", ... "import re;from __main__ import s, spaces").timeit() 7.4031901359558105 >>> Timer("s.replace('\\n', '\\n'+spaces)", ... "import re;from __main__ import s, spaces").timeit() 1.6208670139312744 The regex is nearly five times slower than the simple string replacement. Similarly: re.sub(r'^',spaces,s) is better written as spaces+s, which is nearly eleven times faster. Also: re.sub(r' *$','',s) re.sub(r'\n*$','',s) are just slow ways of writing s.rstrip(' ') and s.rstrip('\n'). -- Steven From ggpolo at gmail.com Sun Mar 23 09:29:37 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 23 Mar 2008 10:29:37 -0300 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] In-Reply-To: <47E4202C.5060400@v.loewis.de> References: <47E4202C.5060400@v.loewis.de> Message-ID: 2008/3/21, "Martin v. L?wis" : > > I've been thinking of volunteering to "port" Tkinter to Python 3.0, I > > hadn't noticed that there was any discussion of removing it. It would > > be a shame IMHO. > > > I don't think Tkinter will be removed. It works just fine in 3k. > > Of course, if you would port IDLE to Tk 8.5: that would be a useful > contribution. I'm interested in doing this, but are you aware of bugs yet ? I know just one that is specific to Tk 8.5, this one being the background color of the editor. > > Regards, > > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From toolmaster at 163.com Mon Mar 17 04:12:44 2008 From: toolmaster at 163.com (WaterWalk) Date: Mon, 17 Mar 2008 01:12:44 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <47de07a2$0$2699$9b622d9e@news.freenet.de> Message-ID: On Mar 17, 1:54 pm, Stargaming wrote: > On Sun, 16 Mar 2008 20:54:01 -0700, WaterWalk wrote: > > Hello. I wonder what's the effective way of figuring out how a piece of > > python code works. > > If your Python code is well-written, it should be easy figuring out what > it means by just reading it. For more complex programs, of course, this > method can fail. > > > With C I often find it very useful to be able to run > > the code in step mode and set breakpoints in a debugger so I can watch > > how the it executes, how the data change and how the code jumps from one > > function to another. But with Python, the debugger is a little > > primitive. The default IDLE doesn't even allow me to set a breakpoint. > > When the code is long, I am often lost in it. > > IDLE is just, well, a batteries-included editor. There are many people > (me included) who do *not* like it because it's so weak and doesn't have > any real uses cases if your programs get sufficiently complex (because > IDLE itself is sufficiently primitive). > > You might be interested in *real* debuggers, such as the Python Debugger > `PDB `_. If you don't find > its usage obvious, a quick google search just turned up a nice `tutorial > `_. > > You might find the `Python Profilers profile.html>`_ particularly interesting, `profile` for finding out which > function sucks up the most calls/time, `trace` for more sophisticated > stuff. > `pythontracer ` sounds like a > good combination of both. > > > So I'm curious how to read code effectively. I agree that python code is > > clear, but when it becomes long, reading it can still be a hard work. > > A common practice is just inserting `print` statements since it's so > easy. If you think your debugging isn't temporary but could be useful and > will be enabled every now and then, you could also use the `logging > module `_ with the > ``DEBUG`` level. > > There was a blog post recently about how to do this `generically for > functions `_. > > > BTW. I think this problem also exists in other script languages. > > FWIW, I think it's particularly easier in scripting languages to > implement all kinds of tracing (apart from debugging, which is rather > unpopular in Python) because you have one *extra* level (the interpreter) > between your machine and your code. > > HTH, > Stargaming Thanks for your informative reply. I'll try them. I think I need more practice to familiarize myself with those idioms of Python. From kay.schluehr at gmx.net Sun Mar 16 03:48:20 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 16 Mar 2008 00:48:20 -0700 (PDT) Subject: ANN: EasyExtend 3.0 - second beta Message-ID: The second beta of EasyExtend 3.0 has been released today. This release is mostly about bugfixes and the reintegration of the fun langlet Teuton and the code coverage langlet. The code coverage langlet has been enhanced s.t. it can detect uncovered branches in boolean operations now. ------------------------------------------------------------------------------------------------------------------------------------------------------------------ What has EE 3.0 to offer? * Trail - a new powerful parser generator. * User defined file suffixes are recognized by the import machinery * Framework extension that supports facilitation of writing user defined tokenizers * Simplification of access to tokenizer and parser from individual extension languages ( langlets ). * Improved stability of the CST transformation process and improved debugging facilities URLs: http://www.fiber-space.de/EasyExtend/doc/EE.html http://pypi.python.org/pypi/EasyExtend/3.0-beta2 From fakeaddress at nowhere.org Tue Mar 18 07:24:12 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 18 Mar 2008 04:24:12 -0700 Subject: finding items that occur more than once in a list In-Reply-To: References: Message-ID: Simon Forman wrote: > Is there a more efficient way to do this? > > def f(L): > '''Return a set of the items that occur more than once in L.''' > L = list(L) > for item in set(L): > L.remove(item) > return set(L) That's neat, but quadratic time because list.remove() requires a linear search. We can make an efficient variant by using remove on a set rather than a list: def multiples(lst): singles = set(lst) mults = set() for x in lst: if x in singles: singles.remove(x) else: mults.add(x) return mults Though probably better is: def multiples(lst): seen = set() mults = set() for x in lst: if x in seen: mults.add(x) else: seen.add(x) return mults I've typically used dicts for such things, as in: def multiples(lst): h = {} for x in lst: h[x] = h.get(x, 0) + 1 return set([x for x in h if h[x] > 1]) -- --Bryan From gagsl-py2 at yahoo.com.ar Sat Mar 15 05:14:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 07:14:05 -0200 Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Message-ID: En Fri, 14 Mar 2008 17:23:14 -0200, Amit Gupta escribi?: > So What do I do, if my testcase if failing because of an uncaught > exception and I want to run it in pdb. Oh, sorry, my last message doesn't apply because the unittest framework caughts the exception. Looks like you have to override TestResult.addError and call pdb.pm() there. -- Gabriel Genellina From deets at nospam.web.de Fri Mar 21 05:34:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Mar 2008 10:34:09 +0100 Subject: Code folder with Emacs In-Reply-To: <13u5li6kspler51@corp.supernews.com> References: <13u5li6kspler51@corp.supernews.com> Message-ID: <64hdonF2boovnU1@mid.uni-berlin.de> Grant Edwards schrieb: > Has anybody figured out how to do code folding of Python source > files in emacs? > > I tried "hide-show" minor mode, but it doesn't really work for > Python code: the only think it knows how to hide/show are > function bodies. It can't do normal things like hide/show a > code block like it can for other languages. > > Google also found my "folding mode", but that's based on > user-inserted tokens and isn't syntax aware. > I just recently started hacking in emacs, to enhance the python-mode and make pdb work with persisten breakpoints (by that I mean BPs that survive one debug-session). Code-folding isn't currently on my agenda, but an interesting idea. given that e.g. ecb already has structural analysis buffers, there are python-aware code parsers (cedet?) So it shouldn't be too hard. The only interesting/important thing would be to integrate it with ecb because I wouldn't want several parse-runs at once. BTW, I can highly recommend flymake for running pylint over the sources! That really helps me a lot these days! Diez From andis59 at gmail.com Fri Mar 7 07:02:33 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Fri, 7 Mar 2008 13:02:33 +0100 Subject: List all files using FTP References: <446cec86-760e-4280-9101-ff5a1470b1b5@e60g2000hsh.googlegroups.com> Message-ID: <195hfxxrjzc7u$.dlg@ostling.com> On Thu, 6 Mar 2008 20:07:46 +0000, Simon Brunning wrote: > This might be of use: > > Nice, Just what I needed! Thank you! // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:55:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:55:36 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6i47r3uoo6b4@corp.supernews.com> <7x3ar0wjhn.fsf@ruckus.brouhaha.com> Message-ID: <13t6uuoj1s56p52@corp.supernews.com> On Sat, 08 Mar 2008 21:32:04 -0800, Paul Rubin wrote: > I should have mentioned (a+b-1)//b expects a and b to be positive > integers. Oh, I don't think that would have made any difference. I think I'm seeing floats everywhere today, including coming out of the walls. -- Steven From robert.rawlins at thinkbluemedia.co.uk Wed Mar 12 11:10:42 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Wed, 12 Mar 2008 15:10:42 -0000 Subject: agg (effbot) In-Reply-To: <47D7F0DE.5000106@tim.thechases.com> References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> <63q90kF268j23U1@mid.uni-berlin.de> <47D7F0DE.5000106@tim.thechases.com> Message-ID: <007e01c88453$402c5ba0$c08512e0$@rawlins@thinkbluemedia.co.uk> Haha, Tim, that cracks me up! lol Bring forth the Holy Hand Grenade of Antioch Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Chase Sent: 12 March 2008 15:04 To: python-list at python.org Subject: Re: agg (effbot) Importance: Low Gerhard H?ring wrote: > fraleysinger at gmail.com wrote: >> aggdraw-1.2a3-20060212.tar.gz > > Try shegabittling the frotz first. If that doesn't help, please post the > output of the compile command that threw the error. Maynard: He who is valiant and pure of spirit may find the compiling instructions in the Drawing Program of Agg Arthur: what?! Maynard: the Drawing Program of Agg. Bedevere: What's that? Maynard: he must of died while typing it Launcelaot: Oh, come on! Maynard: well, that's what it's called Artuhur: Look, if he was dying, he wouldn't bother to name it "agg" Maynard: Well, that's what's written in the URL Galahad: Perhaps he was dictating... Arthur: Oh, shut up. ... -tkc -- http://mail.python.org/mailman/listinfo/python-list From fakeaddress at nowhere.org Sat Mar 15 09:18:01 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 15 Mar 2008 06:18:01 -0700 Subject: Socket Performance In-Reply-To: <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <817932e4-8c89-4f67-b020-f159fef04489@m3g2000hsc.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > Gabriel Genellina wrote: >> No need to reinvent the wheel. socket objects already have a makefile >> method returning a file-like object, which behaves like a buffered socket. That wheel is far from round, and needs some reinvention. Python's file-like objects do not play nice with lower level calls, which would be tolerable if they supported some well-defiend high-level asynchronous I/O, but they do not. > Newbie question: Can you write to the 'file-like object' a pickle, > and receive it intact-- as one string with nothing else? Yes, but there's a world of gotcha's. Sockets do not recognize record boundaries, and Python's 'pickle' has holes one's enemies could drive a truck through. Still, you can pickle, write, read, un-pickle, and get back your data intact. > I want to know because I want to send two pickles. "Two pickles" sounds like a tasty snack, but also suggests you may be playing hopscotch in a minefield. This is a helpful group. Give us more to go on, and you are likely to receive thousands of dollars worth of consulting for free. -- --Bryan From bill.mill at gmail.com Sun Mar 16 16:46:40 2008 From: bill.mill at gmail.com (Bill Mill) Date: Sun, 16 Mar 2008 13:46:40 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: Tom Moertel organized a Perl conference with an interesting sponsorship policy, that may be worth considering. He posted about it on the reddit thread about this clp thread: http://reddit.com/info/6c9l6/comments/c03gli2 . (Disclaimer: I have no idea if that would work for pycon at all or in part, I'm just posting it because I found it thought-provoking.) -Bill Mill http://billmill.org From gabriel.rossetti at mydeskfriend.com Thu Mar 27 04:30:17 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 09:30:17 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: <47EB58B5.1020801@mydeskfriend.com> References: <47EB58B5.1020801@mydeskfriend.com> Message-ID: <47EB5B19.9080906@mydeskfriend.com> Gabriel Rossetti wrote: > Hello, > > I am using Partial Function Application in a class and I've come up with > a problem, when the method is called it tries to pass "self" to the > curried/partial function, but this should be the first argument in > reality, but since the function is curried, then the self gets passed as > the second argument. Here is the code : > > def __registerService(self, atomic, service): > def reg(service): > # registers the service > ... > > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > I should pass self when applying partial, but then I can't do that since > self is not available there. Does anyone have any ideas? > > Thanks, > Gabriel > I also tried this : def __registerService(atomic, self, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) registerServiceAtomic = partial(__registerService, True) registerServiceNonAtomic = partial(__registerService, False) thinking that the self will be passed as the first argument of the registerService* calls and thus the second argument to the curried/partial method, but it doesn't work either, I get : Traceback (most recent call last): File "/home/xxx/Documents/Code/Python/test/test_serv.py", line 245, in test_registeration self.f.registerServiceAtomic(self.serv) exceptions.TypeError: __registerService() takes exactly 3 arguments (2 given) I don't get it... Gabriel From roygeorget at gmail.com Wed Mar 19 02:14:40 2008 From: roygeorget at gmail.com (royG) Date: Tue, 18 Mar 2008 23:14:40 -0700 (PDT) Subject: need a function to create eigenface image Message-ID: hi while trying to make an eigenface image from a numpy array of floats i tried this from numpy import array import Image imagesize=(200,200) def makeimage(inputarray,imagename): inputarray.shape=(-1,) newimg=Image.new('L', imagesize) newimg.putdata(inputarray) newimg.save(imagename) since i am using images of 200X200 size, i use an array with 40000 elements like [ -92.35294118 -81.88235294 -67.58823529 ..., -3.47058824 -13.23529412 -9.76470588] the problem is ,i get an image that is too dark.it looks like a face but is too dark that even different arrays will create images rhat all look alike!.. is there a way to 'tone it down' so that i can generate an eigenface that can be displayed better? thanks RG From duncan.booth at invalid.invalid Sat Mar 29 14:24:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 29 Mar 2008 18:24:19 GMT Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: Lie wrote: > You're forcing your argument too much, both != and <> are NOT standard > mathematics operators -- the standard not-equal operator is >< -- and > I can assure you that both != and <> won't be comprehensible to non- > programmers. My maths may be a bit rusty, but I always thought that the standard not- equal operator was like an = sign but with a diagonal slash through it as displayed when you do: print u'\u2260' From nagle at animats.com Thu Mar 13 14:38:37 2008 From: nagle at animats.com (John Nagle) Date: Thu, 13 Mar 2008 11:38:37 -0700 Subject: getattr/setattr still ASCII-only, not Unicode - blows up SGMLlib from BeautifulSoup Message-ID: <47d97288$0$36363$742ec2ed@news.sonic.net> Just noticed, again, that getattr/setattr are ASCII-only, and don't support Unicode. SGMLlib blows up because of this when faced with a Unicode end tag: File "/usr/local/lib/python2.5/sgmllib.py", line 353, in finish_endtag method = getattr(self, 'end_' + tag) UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 46: ordinal not in range(128) Should attributes be restricted to ASCII, or is this a bug? John Nagle From steve at holdenweb.com Mon Mar 31 06:18:35 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 06:18:35 -0400 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: sam wrote: > Steven D'Aprano napisa?(a): > >>> I can see that Python and Javascript inheritance model is almost the >>> same. Both languages are dynamically typed. And it seems that using >>> "classes" in Python makes some things more complicated then it is >>> necessary (eg functions, methods and lambdas are differen beeing in >>> Python concept). >> Please explain why you think that functions are more complicated in >> Python because of the class model. > > Sorry for a late reply (I was out of the office). > > > 1. You have different syntax for named and unnamed (lambdas) functions. > Functions and methods are different things in Python even if they have same > syntax. But all these are still a pieces of code that you use repeatedly to make > some task. > A knife and scissors are both used to cut things, but that doesn't mean they are the same. > 2. Static function doesn't need to reference "self", and Python forces > programmer to put "self" explicitly. Then you have to do some "tricks" on > function to become static. Python is said "nothing is really private", but > interpreter does some "tricks" to make __id hidden for a class. > Static functions don't even need to live in classes, and certainly don't need references to "self", which only makes sense in the context of acting on instances of classes. > > Some opinions: > > 1. In early days you could do OOP in C -- you just used additional parameter in > a function. Then C++ appeared to make life easier: "when you write > mystring.toupper(), then toupper function gets hidden argument called "this"". > Programs are written in a high level object oriented languages now. In these > languages you still use the same syntax mystring.toupper(), but now you don't > pass object to a function (as in C), but you act on that object. So in the body > of toupper() you can REFERENCE object "mystring". So why do I have to put that > "strange" argument "self"? > > This is not only my opinion > (http://apache.ece.arizona.edu/~edatools/Python/Prototypes.htm). Without "self" > you would use same syntax for ordinary functions, methods, and lambdas. > I think you are bundling quite different things together here. The difference in semantics between bound methods (where the instance reference is added as a first argument) and regular functions (where no additional argument is supplied) has nothing to do with the difference between function and lambda definition syntax. > > 2. Something is private because you can't reference that from outside the scope. > The wrong way is to make object properties private by declaring them private or > to do hidden actions (__id). For example all local variables in function are > private, because you can't access them from outside that function. Why desn't > this work for objects? > > Again this is not only my opinion -- > http://www.crockford.com/javascript/private.html. > The desire to provide information hiding is fundamentally against the Python philosophy, which basically says that attribute values are exposed for all to see. This avoids the nonsense of having to provide setter and getter methods which Java imposes on the programmer. You use the references you provide as a drunken man uses a lamp post - more for support than enlightenment. Python is not JavaScript, and never will be. JavaScript is a better language than it's often given credit for, but its object semantics are closer to Self than to Python. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Mon Mar 31 15:17:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Mar 2008 15:17:39 -0400 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com><8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com><659gb2F2f84eoU2@mid.individual.net><87hceo73ap.fsf@physik.rwth-aachen.de><65anbqF2fg18bU1@mid.individual.net><87r6drjss4.fsf@physik.rwth-aachen.de> <65c0bfF2ffipiU1@mid.individual.net> Message-ID: "Bjoern Schliessmann" wrote in message news:65c0bfF2ffipiU1 at mid.individual.net... | > However, I'm quite sure that when Unicode has arrived almost | > everywhere, some languages will start considering such characters | > in their core syntax. | | This should be the time when there are widespread quasi-standardised | input methods for those characters. C has triglyphs for keyboards missing some ASCII chars. != and <= could easily be treated as diglyphs for the corresponding chars. In a sense they are already, it is just that the real things are not allowed ;=). From xkenneth at gmail.com Wed Mar 12 12:29:11 2008 From: xkenneth at gmail.com (xkenneth) Date: Wed, 12 Mar 2008 09:29:11 -0700 (PDT) Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> Message-ID: On Mar 12, 6:32?am, "Diez B. Roggisch" wrote: > xkenneth wrote: > > Hi All, > > > ? ?Quick question. I've got an XML schema file (XSD) that I've > > written, that works fine when my data is present as an XML file. > > (Served out by apache2.) Now when I call python as a cgi script, and > > tell it print out all of the same XML, also served up by apache2, the > > XSD is not applied. Does this have to do with which content type i > > defined when printing the xml to stdout? > > Who's applying the stylesheet? The browser, some application like XmlSpy or > what? > > Diez The browser. Regards, Kenneth Miller From http Fri Mar 7 19:13:04 2008 From: http (Paul Rubin) Date: 07 Mar 2008 16:13:04 -0800 Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <7xmypa844v.fsf@ruckus.brouhaha.com> Pierre Quentel writes: > I would like to know if there is a module that converts a string to a > value of the "most probable type" Python 2.4.4 (#1, Oct 23 2006, 13:58:00) >>> import this The Zen of Python, by Tim Peters ... In the face of ambiguity, refuse the temptation to guess. From tjreedy at udel.edu Sat Mar 29 16:12:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2008 16:12:22 -0400 Subject: Help me on function definition References: Message-ID: "aeneng" wrote in message news:fsk739+ff60 at eGroups.com... | def cross(u,v) | """input two vectors u and v in 3-D space, | output a cross product of vector w, in column or in row | accordingly.""" | ppp1,ppp2,ppp3=0.0,0.0,0.0 To add to other comments, remove above which is complete waste. From mensanator at aol.com Tue Mar 4 01:00:42 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 22:00:42 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <2aceec91-618d-4e62-9958-e223505bc51f@13g2000hsb.googlegroups.com> Message-ID: <0809c202-4759-4fc1-9c36-e079c212ca0e@u69g2000hse.googlegroups.com> On Mar 3, 8:31?pm, castiro... at gmail.com wrote: > > All software has bugs. > > Good software has bugs. > > Therefore, good software is software. > > > This makes sympy worse than worthless, as it f***s up other modules. > > What is it still good for? Lots. The problem is when the total is less than the sum of the parts. From asmodai at in-nomine.org Mon Mar 31 07:17:52 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 31 Mar 2008 13:17:52 +0200 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <20080331111752.GH80617@nexus.in-nomine.org> -On [20080331 13:13], Pradeep Rai (pradiprai at gmail.com) wrote: >Yes, i have copied everything from site-packages of the old one to the new >one. Don't do that. :) site-packages is version dependent, you can get away with it with most Python-only modules, I guess, but with dbi you found out what can happen. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ The last word in a chronicle is never set down... From abelufsc at gmail.com Mon Mar 10 08:26:42 2008 From: abelufsc at gmail.com (Abel Ferreira) Date: Mon, 10 Mar 2008 09:26:42 -0300 Subject: logging problem Message-ID: <4871dbda0803100526h78aaff23v35bba82ddfaf2475@mail.gmail.com> Hi. I have a problem with python. I dont wanna bother you, but it's seem you had the same error. Did you get solve this problem? I know it's old, but if you remember, tell me. i'm using python's logging facilities in all of my application modules. > my logging.conf file is: > [loggers] > keys=root > [handlers] > keys=roth > [formatters] > keys=simpleFormatter > [logger_root] > level=DEBUG > handlers=roth > [handler_roth] > class=handlers.RotatingFileHandler > level=DEBUG > formatter=simpleFormatter > args=('adssim.log','w', 2000000, 4) > [formatter_simpleFormatter] > format=%(asctime)s - %(message)s > datefmt=%Y-%m-%d %H:%M:%S > > i'm "creating" a logger in my adslogging module in the following way: > import logging > import logging.config > > logging.config.fileConfig("logging.conf") > logger = logging.getLogger("root") > > all my app modules import the adslogging module, and refer to the logger > as adslogging.logger and perform stuff like adslogging.logger.debug(msg1) > or adslogging.logger.info(msgN) > > although i'm not explicitly closing the logfile and i don't think the logfile size has > maxed out (i see one logfile under my app directory with size 31K), i'm getting the following error messages in windows xp. what might i be doing wrong? > > > C:\adssim1>python adstest.py 19.52.160.171 139 W04 > > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > Traceback (most recent call last): > File "C:\Python24\lib\logging\handlers.py", line 71, in emit > if self.shouldRollover(record): > File "C:\Python24\lib\logging\handlers.py", line 143, in shouldRollover > self.stream.seek(0, 2) #due to non-posix-compliant Windows feature > ValueError: I/O operation on closed file > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Mar 6 05:30:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 10:30:09 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <13svhthrlvqoad2@corp.supernews.com> On Thu, 06 Mar 2008 08:37:07 +0000, Bryan Olson wrote: > Grant Edwards wrote: >> It may be obvious that he has a question. It's not the least bit >> obvious what that question is. > > How can we efficiently implement an abstract data type, call it > 'DoubleDict', where the state of a DoubleDict is a binary relation, that > is, a set of pairs (x, y); and the operations on a DoubleDict are those > on a Python set, plus: > > find_by_first(self, x): return [y where (x, y) in DoubleDict] > > find_by_second(self, y): return [x where (x, y) in DoubleDict] > > > Python can implement this ADT directly as specified, but the find_by_ > operations would run in time len(self). We want an implementation where > the find_by's run in O(1 + k) where k is the length of the returned > sequence. If I've understood you correctly, what you want is a reverse lookup dict. Here's a Quick & Dirty partial implementation to get you started. It's VERY simple-minded, and barely tested at all. But both lookup and reverse- lookup should be almost as efficient as Python dicts, and it only uses roughly twice as many pointers as a regular dict. class RLdict(object): def __init__(self, **items): self.D = {} self.R = {} for key, value in items.iteritems(): self[key] = value def __getitem__(self, key): return self.D[key] def getkey(self, value): return self.R[value] def __setitem__(self, key, value): self.D[key] = value self.R[value] = key def __repr__(self): return "RLdict(%s)" % self.D And in action: >>> d = RLdict(a=1, b=2, c=3, d=4) >>> d RLdict({'a': 1, 'c': 3, 'b': 2, 'd': 4}) >>> d['b'] 2 >>> d.getkey(2) 'b' Naturally both the keys and values must be hashable. The version above makes keys/values a one-to-one mapping; if you want many-to-many, you'll need something more clever. It's also possible that inheriting from dict instead of object would give you a whole lot of extra functionality for free, but I haven't explored that avenue. -- Steven From sturlamolden at yahoo.no Sat Mar 22 11:02:44 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 08:02:44 -0700 (PDT) Subject: How to implement command line tool integrating parsing engine References: Message-ID: On 22 Mar, 14:48, llandre wrote: > - it must run both on linux and windows PC > - it must interact with an electronic device connected to the PC through > serial cable Python should be fine. > - initially the program must be written in the form of simple command > line tool that is invoked like this: > program python script_file.py > - in the future, it must be possible to develop a graphical frontend on > top of it; the resulting look&feel should be similar on linux and windows. Python has numerous cross-platform GUI libraries. > As I never used python, I ask you: > 1) about the script file, which language - for which a parsing engine is > already available in python - do you suggest? I'd suggest Python... > 2) about the graphical frontend, which graphical libraries do you recommend? wxPython, PyGTK, tkinter, PyQt, or PyGame are some options. I have started to prefer wxPython together with wxFormBuilder for my graphical frontends. http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-with-wxpython.html From ACooper at cimtek.com Tue Mar 11 09:02:43 2008 From: ACooper at cimtek.com (Cooper, Andrew) Date: Tue, 11 Mar 2008 09:02:43 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: References: Message-ID: Are there any Python C API experts/SWIG experts out there that can help me with this issue please. Andy -----Original Message----- From: python-list-bounces+acooper=cimtek.com at python.org [mailto:python-list-bounces+acooper=cimtek.com at python.org] On Behalf Of Cooper, Andrew Sent: 10 March 2008 15:55 To: python-list at python.org Subject: Obtaining the PyObject * of a class I',m currently using SWIG to generate a python interface to a C DLL. I'm new to the Python C API and have a question that has been stumping me for the last week. As part of the wrapper process I want to hide some of the complexity with dealing with handles using a python class. But the problem I have is I don't know how to get the PyObject* that refers to the class Pin that I have defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list From sturlamolden at yahoo.no Thu Mar 20 13:53:25 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 10:53:25 -0700 (PDT) Subject: wxFormBuilder References: <9a27e$47e28f17$83aef404$28537@news1.tudelft.nl> Message-ID: <9eab5de1-5c0b-4c81-b83b-2bbcf117db73@c19g2000prf.googlegroups.com> On 20 Mar, 17:21, Stef Mientki wrote: > I've tried several of the above mentioned builders, > with the same result. > I've also looked at wxFormBuilder, > but I found it far too difficult and > fully unreadable (how can you create actions/bindings on components you don't see ?). > So I might be very very naive, > but why all so complex ?? It is not complex. I have posted a small 'Hello World!' howto on my blog. It shows you how to bind events: http://sturlamolden.blogspot.com/2008/03/howto-using-wxformbuilder-with-wxpython.html From kaushikbarat at gmail.com Sun Mar 2 03:24:28 2008 From: kaushikbarat at gmail.com (kaush) Date: Sun, 2 Mar 2008 00:24:28 -0800 (PST) Subject: mod_python Unable to create file References: <62v31gF24ontgU1@mid.uni-berlin.de> Message-ID: On Mar 1, 11:24?pm, Marc 'BlackJack' Rintsch wrote: > On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: > > I am using Apache and mod_python to service POST/GET requests on MAC > > OS. My script tries to create a file > > > file = open(file_path, 'w') > > > This fails with the following error > > > EACCES > > Permission denied > > > What is missing? > > To state the ovious: the rights to create a file at `file_path`. ?Remember > that web servers usually have their own "user". > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Thanks Marc. In Apache what are the ways/directives to set the rights to a folder? From kevin at bud.ca Sun Mar 2 20:35:21 2008 From: kevin at bud.ca (Kevin Teague) Date: Sun, 2 Mar 2008 17:35:21 -0800 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> Message-ID: "It has to do with the MACOSX_DEPLOYMENT_TARGET. If it's set to 10.4, the legacy version of setpgrp is used (with args), it it's 10.5, setpgrp expects no arguments. It seems configure won't detect the difference." http://bugs.python.org/issue1358 This issue was fixed for Python 2.5. As the issue notes, you can work around it with: ./configure MACOSX_DEPLOYMENT_TARGET=10.5 But it would be really nice if the configure fix for 2.5 was backported to 2.4.5 since Zope is still on 2.4 and Mac OS X skipped system builds for 2.4 going direct from 2.3 -> 2.5. From dave_mikesell at fastmail.fm Tue Mar 11 05:36:54 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Tue, 11 Mar 2008 02:36:54 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: Message-ID: <64980caf-7321-45da-8248-b16df7ff42fd@x41g2000hsb.googlegroups.com> On Mar 11, 3:03 am, Bob Martin wrote: > in 337600 20080310 222850 dave_mikes... at fastmail.fm wrote: > > >On Mar 10, 2:21 pm, Bob Martin wrote: > > >> Java is more portable than most other languages, especially if your app needs a gui. > > >The promise of Java portability was one of the biggest scams ever > >perpetrated on the software industry. There are issues going from OS > >to OS, VM to VM, DB to DB, app server to app server, etc. Certainly > >no easier than porting C++ and the appropriate libraries, IMHO. > > Quite untrue - I have a stack of large java apps which run without change on > Linux, OS/2 and Windows. Not many, if any, other languages can match that, > and definitely not C++. I'm happy that it's worked for you, but I haven't seen it in my experience. My current client has code that works in 1.4.0, but not higher versions of the JDK without code changes. And other that won't run in later versions of the app server (JBoss) than the one for which it was developed. And upgrading our SQL Server version required an upgrade of DB drivers. Another headache. They have their own JVM requirements as well, as do other packages and libraries. Getting them all to play together hasn't been seamless or easy by any stretch. From sjmachin at lexicon.net Mon Mar 24 18:43:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Mar 2008 15:43:13 -0700 (PDT) Subject: Paramiko bugs out on windows 2003 server References: Message-ID: <97203a80-32ae-4d3e-862a-9ff437d5fa2e@e23g2000prf.googlegroups.com> On Mar 25, 7:50 am, "Tarun Kapoor" wrote: > I am using the paramiko library to pull a data from a server using SFTP. > It works perfect on a windows xp machine but bugs out a windows 2003 > server. I get the following error: > Traceback (most recent call last): > File "S:\Temp\ftpBOA.py", line 5, in ? > import paramiko > File "C:\Python23\lib\paramiko\__init__.py", line 69, in ? > from transport import randpool, SecurityOptions, Transport > File "C:\Python23\lib\paramiko\transport.py", line 32, in ? > from paramiko import util > File "C:\Python23\lib\paramiko\util.py", line 31, in ? > from paramiko.common import * > File "C:\Python23\lib\paramiko\common.py", line 98, in ? > from osrandom import OSRandomPool > File "C:\Python23\lib\paramiko\osrandom.py", line 54, in ? > raise ImportError("Cannot find OS entropy source") > ImportError: Cannot find OS entropy source > > Anyone knows how to solve it ? Here's some meta-help: paramiko seems to be actively maintained and has a mailing list -- see http://www.lag.net/mailman/listinfo/paramiko -- consider asking on that list. Not only is paramiko open source but also you have the source code on your machine already -- consider looking at C:\Python23\lib\paramiko \osrandom.py and see if you can nut out what it is complaining about. Even if you can't, the experience may help you to better answer questions from the maintainer, who may well not have a Windows 2003 server box upon which to replicate the problem. From stefan_ml at behnel.de Tue Mar 4 13:37:55 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 04 Mar 2008 19:37:55 +0100 Subject: XML Schema validation in Python In-Reply-To: References: Message-ID: <47CD9703.9000808@behnel.de> Medhat.Gayed at gmail.com wrote: > I tested and tried a few XML validators but none of them is able to > successfully validate a string of xml (not a file just a string) to > programatically be able to validate messages of xml that flow in and > out of the different systems. http://codespeak.net/lxml/tutorial.html#parsing-from-strings-and-files http://codespeak.net/lxml/validation.html#validation-at-parse-time http://codespeak.net/lxml/validation.html#xmlschema Stefan From jjlofaro at yahoo.com.au Tue Mar 25 08:08:17 2008 From: jjlofaro at yahoo.com.au (jjlofaro) Date: Tue, 25 Mar 2008 12:08:17 -0000 Subject: Time module is not behaving. Message-ID: Hi I'm just getting myself going again on Python and would appreciate any help. My install of Python seems to have some difficulty loading and using the time module in a script. Strange thing is that if I start another instance of Python I can type in my program manually/interactively and it works. The version of Python I am using is... Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Installed on a Ubuntu 7.10 workstation. Here's my little program.... jeff at office:~/tmp$ more < time.py import time print time.time() And this is what happens when I run it.... jeff at office:~/tmp$ python time.py Traceback (most recent call last): File "time.py", line 1, in import time File "/home/jeff/tmp/time.py", line 2, in print time.time() TypeError: 'module' object is not callable Error in sys.excepthook: Traceback (most recent call last): File "/var/lib/python-support/python2.5/apport_python_hook.py", line 38, in apport_excepthook from apport.fileutils import likely_packaged File "/var/lib/python-support/python2.5/apport/__init__.py", line 1, in from apport.report import Report File "/var/lib/python-support/python2.5/apport/report.py", line 14, in import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys File "/usr/lib/python2.5/urllib.py", line 28, in import time File "/home/jeff/tmp/time.py", line 2, in print time.time() TypeError: 'module' object is not callable Original exception was: Traceback (most recent call last): File "time.py", line 1, in import time File "/home/jeff/tmp/time.py", line 2, in print time.time() TypeError: 'module' object is not callable jeff at office:~/tmp$ Any hints or tips appreciated. Jeff. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Mar 10 23:22:37 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Mar 2008 23:22:37 -0400 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> <7a6555fa-819a-41c0-befe-ee0123272b31@59g2000hsb.googlegroups.com> Message-ID: "rockingred" wrote in message news:7a6555fa-819a-41c0-befe-ee0123272b31 at 59g2000hsb.googlegroups.com... On Mar 8, 4:15 pm, "Terry Reedy" wrote: > If the sense of else were reversed, one would have to write the clumbsier > > complete = True # though false at this point > while loop_condition: > > if break_condition: > complete = False > break > > else: > > if complete: > > > Terry Jan Reedy Terry, instead of using "complete = True" and setting it to false on failure, why not set "loop_completed = False" and set it to True if the break condition is met? [OE not quoting properly] ===================== Because completion is False when broken? Actually, I am not sure what you mean without seeing the snippet rewritten. Certainly, one could set 'broken=False' at top (tho not true) and 'broken = True' before breaking and test for 'not broken' at end, but that is not an improvement. tjr From robert.kern at gmail.com Fri Mar 7 23:51:52 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 07 Mar 2008 22:51:52 -0600 Subject: distutils - Is is possible to install without the .py extensions In-Reply-To: References: Message-ID: Jari Aalto wrote: > * Fri 2008-03-07 Robert Kern gmane.comp.python.general > * Message-Id: fqsf3a$4lv$1 at ger.gmane.org >> Jari Aalto wrote: >>> #!/usr/bin/python >>> >>> from distutils.core import setup >>> import glob >>> >>> setup(name='program', > ... >>> scripts = ['program,py'], >>> ) >>> that the the result is: >>> >>> /usr/bin/program >>> >>> instead of: >>> >>> /usr/bin/program.py >> The easiest and best way is to just rename the file in your source tree to >> "program" and be done with it. > > Is there any other way? This is the source package that I would like > to keep intact and just patch the setup.py Not really, no. Why is it so important to only patch the setup.py file and not any others? -- 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 tjreedy at udel.edu Thu Mar 6 16:35:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Mar 2008 16:35:39 -0500 Subject: Python on the renderfarm Message-ID: It is fairly well know that cinematic digital effects are most often rendered on *nix machines with efficient numeric code. http://www.linuxjournal.com/article/9951 But Python sometimes has a role too: from the middile of the above link ''' Tippett Studio: Linux Python Pipeline JET is a proprietary Python-based system comprising software tools and scripts used to implement a visual effects and animation pipeline. ?A visual effects and animation pipeline is an assembly line of software used to organize, automate and facilitate the creation of computer-generated imagery?, says Darling. ?The JET tool is highly customizable, featuring XML-based user-interface templates that can be modified to suit specific types of artists or production needs. JET uses modular template chunks to perform each of the tasks in the pipeline, such as rendering or compositing. The templates are implemented as Python objects and are centrally located. JET is not only implemented entirely in Python, but it's also used to generate Python scripts automatically. These custom scripts form unique pipelines for each computer graphics job to run on the renderfarm.? ''' From MartinRinehart at gmail.com Mon Mar 17 07:49:07 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 17 Mar 2008 04:49:07 -0700 (PDT) Subject: lists v. tuples Message-ID: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> What are the considerations in choosing between: return [a, b, c] and return (a, b, c) # or return a, b, c Why is the immutable form the default? From __peter__ at web.de Fri Mar 21 16:04:28 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Mar 2008 21:04:28 +0100 Subject: How can I make a function equal to 0? References: Message-ID: Martin Manns wrote: > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > >>>> def f(): return "" > ... >>>> # Some magic >>>> f == 0 > True > > Thanks in advance > > Martin Use a callable object: >>> class F(object): ... def __cmp__(self, other): return cmp(other, 0) ... def __call__(self): return "" ... >>> f = F() >>> f() '' >>> f == 0 True Peter From castironpi at gmail.com Mon Mar 24 11:17:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 24 Mar 2008 08:17:46 -0700 (PDT) Subject: what are generators? Message-ID: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> I'm looking for a cool trick using generators. Know any exercises I can work? From bj_666 at gmx.net Sun Mar 2 09:24:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Mar 2008 14:24:46 GMT Subject: First post from a Python newbiw References: Message-ID: <62vrleF24ontgU2@mid.uni-berlin.de> On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: > Apart from doing something like > a=[0,0,0] > b=[0,0,0] > c=[0,0,0] > d=[a,b,c] > > is there a better way of creating d?? a = [[0] * 3 for dummy in xrange(3)] Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 11:18:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 15:18:53 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: <13uvbqt55k3or4f@corp.supernews.com> On Sun, 30 Mar 2008 15:03:21 +0200, Peter Otten wrote: > Maybe the following enhancement of timeit would be worthwhile? [snip] Passing a namespace argument would be excellent. > By the way, haven't we been there before, two years ago? > > http://mail.python.org/pipermail/python-list/2006-February/368341.html Two years huh? Gosh, how time flies. -- Steven From Robert.Bossy at jouy.inra.fr Mon Mar 10 11:04:26 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 10 Mar 2008 16:04:26 +0100 Subject: parsing directory for certain filetypes In-Reply-To: <3df2b3f8-64ad-4102-8b60-95717e6748fe@o77g2000hsf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> <3df2b3f8-64ad-4102-8b60-95717e6748fe@o77g2000hsf.googlegroups.com> Message-ID: <47D54DFA.4020602@jouy.inra.fr> jay graves wrote: > On Mar 10, 9:28 am, Robert Bossy wrote: > >> Personally, I'd use glob.glob: >> >> import os.path >> import glob >> >> def parsefolder(folder): >> path = os.path.normpath(os.path.join(folder, '*.py')) >> lst = [ fn for fn in glob.glob(path) ] >> lst.sort() >> return lst >> >> > > Why the 'no-op' list comprehension? Typo? > My mistake, it is: import os.path import glob def parsefolder(folder): path = os.path.normpath(os.path.join(folder, '*.py')) lst = glob.glob(path) lst.sort() return lst From hexusnexus at gmail.com Mon Mar 31 15:39:54 2008 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Mon, 31 Mar 2008 12:39:54 -0700 (PDT) Subject: Command line input Message-ID: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> How do I receive input from the command line in Python? From josef.pktd at gmail.com Fri Mar 14 21:05:31 2008 From: josef.pktd at gmail.com (joep) Date: Fri, 14 Mar 2008 18:05:31 -0700 (PDT) Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> On Mar 14, 8:15 pm, "David S" wrote: > By mapping network drives in windows I can get past these issues with path > names. > > Thanks, > David > > "Tim Golden" wrote in message > > news:mailman.1949.1205496184.9267.python-list at python.org... > > > David S wrote: > >> Gets me further but still seems to be issue with space after 'Program' as > >> code tries to run 'C:\Program'. Don't understand what is going on here... > > > Slight apologies as I haven't followed this thread closely, but using the > > Acrobat Reader executable, which is, I think, good enough for the > > purposes of illustration: > > > > > import os > > import subprocess > > > filename = r"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe" > > doc = r"C:\Program Files\Adobe\Reader 8.0\Resource\ENUtxt.pdf" > > > print os.path.isfile (filename) > > > os.system (filename + " " + doc) > > > os.system ('"%s" "%s"' % (filename, doc)) > > > subprocess.call ([filename, doc]) > > > > > > os.path.isfile succeeds > > os.system (filename) fails as your code does > > os.system ('"%s"' ...) fails even though both strings are requoted > > subprocess.call (filename) succeeds > > > The latter, at least, is because the subprocess module > > has some special-case handling for exactly this situation > > on MS Windows, while os.system doesn't. > > > Now, ultimately, I don't know if this really helps your > > exact situation but it least it should be clear what will > > and what won't work. Conclusion: use subprocess.call if > > you can. > > > TJG I had the same problem recently with subprocess.popen, when there is a space in the executable and a space in an additional argument as in the acrobat example. I finally found a past thread in this news group that explained that you have to use two (2) leading double quotes, and as on the command line all arguments with spaces have to be quoted. All three examples with acrobat work on my WindowsXP in this case (opens Acrobat three times, after closing previous): import os import subprocess filename = r"C:\Program Files\Adobe\Acrobat 7.0\Acrobat\Acrobat.exe" doc = r"C:\Program Files\Adobe\Acrobat 7.0\Help\ENU\Pdfmark.pdf" print os.path.isfile (filename) print 'case 1' os.system ('""' + filename + '" "' + doc + '"') # quotes split up for clarity: (' " " ' + filename + ' " " ' + doc + ' " ') print 'case 2' os.system ('""%s" "%s"' % (filename, doc)) print 'case 3' subprocess.call ([filename, doc]) Josef From sachincric08 at gmail.com Sun Mar 2 06:42:54 2008 From: sachincric08 at gmail.com (sachincric08 at gmail.com) Date: Sun, 2 Mar 2008 03:42:54 -0800 (PST) Subject: Work Part time or Full time from Home. No Age Bar. Basic Message-ID: Work Part time or Full time from Home. No Age Bar. Basic knowledge in Computers and Internet is enough. http://freeonlinejobs4u.googlepages.com From 42flicks at gmail.com Fri Mar 7 19:39:22 2008 From: 42flicks at gmail.com (Mike D) Date: Sat, 8 Mar 2008 13:39:22 +1300 Subject: DOM parsing not working! Message-ID: <2b54d4370803071639w30912a60i4bc93981533ecfbb@mail.gmail.com> Hello, I've spent the morning trying to parse a simple xml file and have the following: import sys from xml.dom import minidom doc=minidom.parse('topstories.xml') items = doc.getElementsByTagName("item") text='' for i in items: t = i.firstChild print t.nodeName if t.nodeType == t.TEXT_NODE: print "TEXT_NODE" print t.nodeValue text += t.data print text I can't figure out how to print the text value for a text node type. There must be something obvious I'm missing, any suggestions? Thanks. XML is as follows: Stuff.co.nz - Top Stories http://www.stuff.co.nz Top Stories from Stuff.co.nz. New Zealand, world, sport, business & entertainment news on Stuff.co.nz. en-nz Fairfax New Zealand Ltd. 30 /static/images/logo.gif Stuff News http://www.stuff.co.nz Prince Harry 'wants to live in Africa' http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303 For Prince Harry it must be the ultimate dark irony: to be in such a privileged position and have so much opportunity, and yet be unable to fulfil a dream of fighting for the motherland. EDMUND TADROS stuff.co.nz/4423924 Mon, 03 Mar 2008 00:44:00 GMT -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri Mar 28 12:47:55 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 16:47:55 -0000 Subject: How do I reconnect a disconnected socket? References: <13uq69e8us4oo74@corp.supernews.com> Message-ID: <13uq89rskf16u9a@corp.supernews.com> On 2008-03-28, Laszlo Nagy wrote: > >> Yes, that is exactly what it means. >> >> >From the recv() man page: >> >> RETURN VALUE >> These calls return the number of bytes received, or -1 if an error >> occurred. The return value will be 0 when the peer has performed an >> orderly shutdown. >> >> > Mea cupla. :-) > > What about non-blocking sockets? $ man recv ... If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is non-blocking (see fcntl(2)), in which case the value -1 is returned and the external variable errno set to EAGAIN. ... -- Grant From asim.ihsan at gmail.com Sat Mar 1 02:31:23 2008 From: asim.ihsan at gmail.com (Asim) Date: Fri, 29 Feb 2008 23:31:23 -0800 (PST) Subject: Pythons & Ladders References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> <93b6e5e7-be80-408a-8e15-4141b8682392@x41g2000hsb.googlegroups.com> Message-ID: On Feb 28, 9:10?pm, Jeff Schwab wrote: > Benoit wrote: > > Forgive my language concerning C++ as its turned the thread into > > something I did not intend. I merely wished to point out that Python > > was easier for me to learn than C++. ?To Schwab, its likely that Mark > > Lutz is simply a better instructor than my professor. > > Sorry for hijacking your thread! > > In addition to Python Challenge, check out Code Golf: > > ? ? ?http://codegolf.com/ > > It's eye-opening to see how concise the solutions can be. You should also give Project Euler a shot: http://projecteuler.net/index.php?section=problems Just keep in mind two points. One, your solutions should work with under one minute of execution time, even in Python. Secondly, the main benefit of the site is attempting some of the simpler problems and then diving head-first into the forums to see other peoples' solutions to the same problem. I guarantee you'll find some unique Python techniques from these forums that should open new avenues of learning wrt Python for you. Nothing enterprise level...but definitely interesting. Be warned that some of the harder problems require undergraduate-level math. From tms at zeetix.com Sat Mar 15 16:33:24 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 16:33:24 -0400 Subject: Unicode/UTF-8 confusion Message-ID: <007401c886db$d197b780$0200a8c0@TMSMAIN> I appreciate the answers the community has provided, I think I need to add some additional context. I use a trick to let me pass the information into my browser client application. The browser requests the server information from a form whose target is a hidden iframe. The string the server serializes is wrapped in html that embeds it in an onload handler like this: When this html finishes loading, its onload handler fires, it in turn fires the "loadObject" method of the _clientApplication that is waiting for the result, and the clientApplication then unpacks aSerializedObject into the browser. Once back in the browser, the loadObject method calls JSON.parse on aSerializedObject, the json string we're discussing. A serialized object typically contains many (at least tens, and sometimes several hundred) html fragments. It contains at most a handful of apostrophes. That means there are MANY more double quotes than apostrophes, if I delimit attributes with double quotes. In order to successfully pass the escapes to the server, I already have to double any each backslash. At the end of the day, it's easier -- and results in better performance -- to convert each apostrophe to its unicode equivalent, as I originally asked. I just want to know if there's a faster way to persuade simplejson to accomplish the feat. From Lie.1296 at gmail.com Sun Mar 16 04:53:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 01:53:40 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <409579d8-0120-42bd-96e4-fdebf0512fd1@d21g2000prf.googlegroups.com> On Mar 16, 4:43?am, Guido van Brakel wrote: > Hello > > I have this now: > > > def gem(a): > > ? ? g = sum(a) / len(a) > > ? ? return g > > > print gem([1,2,3,4]) > > print gem([1,10,100,1000]) > > print gem([1,-2,3,-4,5]) > > It now gives a int, but i would like to see floats. How can integrate > that into the function? > > Regards, > > -- > Guido van Brakel > Life is like a box of chocolates, you never know what you're gonna get > -- Python 2's division operator's default behavior is to do integer division whenever all of its operands are integers/long and do float division if any of them are float/decimal, in Python 3, this is going to be changed so that division would always be float division and while integer division would have its own operator "//". You can change the default behavior of Python 2 by importing division behavior from __future__ module (from __future__ import division), or you could convert one of the operands to float ("float(a) / b" or "a / float(b)"). From deets at nospam.web.de Sun Mar 2 10:56:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Mar 2008 16:56:26 +0100 Subject: tcp In-Reply-To: <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> Message-ID: <63011aF1bg56vU1@mid.uni-berlin.de> Gif schrieb: > sorry for acting like a fool but this is just to weirdly easy that i > can't get to work. i've written a small web server in another language > and this is more like copying code. > i already have everything figured out, except this one but noone seems > either willing or capable of helping me. > again sorry but i was in a very bad mood. Writing a webserver (you NEVER stated that that is your ultimate goal) is a two-liner in Python. See the module SimpleHTTPServer. Using the extremely lowlevel module socket is a totally different beast. It requires rather deep knowledge of unix sockets, and has a steep learning curve. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 22:19:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 02:19:09 -0000 Subject: Help me on function definition References: Message-ID: <13ur9ott52roc0c@corp.supernews.com> Oh, I forgot to mention... On Sat, 29 Mar 2008 01:47:21 +0000, aeneng wrote: > if __name__=="__main__": ... > print "file name is %s" %__name__ This doesn't do what you expect it to do. You've already established that __name__ is equal to "__main__", so you might as well change that line to: print "file name is not actually __main__" What you want is: print "file name is %s" % __file__ -- Steven From http Thu Mar 20 03:54:37 2008 From: http (Paul Rubin) Date: 20 Mar 2008 00:54:37 -0700 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <7xy78dg79e.fsf@ruckus.brouhaha.com> "Daniel Fetchinson" writes: > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? That would be terrible. Every time I've tried to use one of the other packages it has led to installation hell. Tkinter isn't great, but it's extremely useful to have a gui module that's present automatically in every compete Python installation and that is reasonably cross platform. I can write a Python/Tkinter app under Linux and send it to Windows users and they can run it after a single, very simple Python installation from the Windows .msi. I have no Windows development tools whatsoever and very limited access to Windows boxes, so any Python code I deploy on Windows can't rely on any non-Python code outside of the stdlib. Also, because of tkinter's inherent limitations, I have the impression that upgrading it to the latest and greatest tcl/tk release wouldn't improve it much over the useful but low-rent module that it already is. Therefore, that supposed "benefit" of splitting it out to an external package is not much of a benefit. One of Python's traditionally best attractions has been the depth of its standard libraries, and backing away from that would be plain self-destructive. Python needs more stuff in its stdlib, not less. If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard distro. If that happens (i.e. some new toolkit is brought in and declared to be the standard) then it might be ok to drop Tkinter but it certainly shouldn't be dropped without a replacement. From usenet at solar-empire.de Sat Mar 15 14:31:09 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Sat, 15 Mar 2008 19:31:09 +0100 Subject: Unicode/UTF-8 confusion References: Message-ID: Tom Stambaugh wrote: >> Somehow I don't get what you are after. The ' doesn't have to be escaped >> at all if " are used to delimit the string. If ' are used as delimiters >> then \' is a correct escaping. What is the problem with that!? > > If I delimit the string with double quote, then I have to escape every > double quote in whatever I serialize. I'm moving strict html from the server > to the browser, and therefore the value of every tag attribute is delimited > by double quotes. That means that I'd have to escape every double quote, and > there are MANY more of them. I haven't done much programming with Javascript/AJAX, so why is the following not sufficient? All the double quotes get escaped. >>> link = u"""Click here""" >>> simplejson.dumps(link) '"Click here<\\/a>"' >>> print simplejson.dumps(link) "Click here<\/a>" And ' is a valid delimiter for attributes, so you don't have to use double quotes for them. Marc From lizhongan at gmail.com Sun Mar 16 23:17:31 2008 From: lizhongan at gmail.com (zaley) Date: Sun, 16 Mar 2008 20:17:31 -0700 (PDT) Subject: pass float array(list) parameter to C Message-ID: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> In my program, python is communicated with C use ctypes . I can't find a better way to pass float array(list) parameter to C function. Can someone give me a help? From steve at holdenweb.com Wed Mar 19 06:27:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Mar 2008 06:27:57 -0400 Subject: PSF Community Awards Message-ID: <47E0EAAD.4070204@holdenweb.com> For those who weren't at PyCon, or who missed the announcement (which seems to include all of the recipients :-) I have just made a post in the PSF blog to publicize the first PSF Community Awards. See http://pyfound.blogspot.com/2008/03/psf-community-awards.html These awards are made to recognize those who perform work of benefit to the broader Python community. If you have benefited from the work the first award winners have done, please further acknowledge their valuable contributions by adding a short comment to the post. Steve Holden Chairman, Python Software Foundation From steve at holdenweb.com Tue Mar 4 11:06:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 11:06:29 -0500 Subject: Altering imported modules In-Reply-To: <200803041004.50553.troworld@gmail.com> References: <200803011856.27611.troworld@gmail.com> <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> <200803041004.50553.troworld@gmail.com> Message-ID: Tro wrote: > On Monday 03 March 2008, castironpi at gmail.com wrote: >> On Mar 3, 5:09 pm, Tro wrote: >>> On Sunday 02 March 2008, Paul McGuire wrote: >>>> On Mar 2, 3:48 pm, Tro wrote: >>>>> On Sunday 02 March 2008, Terry Reedy wrote: >>>>>> "Tro" wrote in message >>>>>> news:200803011856.27611.troworld at gmail.com... >>>>>> >>>>>> | Hi, list. >>>>>> | >>>>>> | I've got a simple asyncore-based server. However, I've modified >>>>>> | the >>>>>> >>>>>> asyncore >>>>>> >>>>>> | module to allow me to watch functions as well as sockets. The >>>>>> | modified asyncore module is in a specific location in my project >>>>>> | and is imported >>>>>> >>>>>> as >>>>>> >>>>>> | usual from my classes. >>>>>> | >>>>>> | Now I'd like to use the tlslite library, which includes an >>>>>> | asyncore mixin class. However, tlslite imports "asyncore", which >>>>>> | doesn't include my own modifications. >>>>>> | >>>>>> | I'd like to know if it's possible to make tlslite load *my* >>>>>> | asyncore >>>>>> >>>>>> module >>>>>> >>>>>> | without changing any of the tlslite code. >>>>>> >>>>>> If your module is also 'asyncore' and comes earlier in the search >>>>>> path, I would expect the import to get yours. >>>>> It's not. It has a package prefix like my.package.asyncore. I think I >>>>> can either move my version of asyncore up a couple of levels or add >>>>> the my.package directory to sys.path. >>>>> >>>>> My version of asyncore imports several functions from the built-in >>>>> asyncore. Now that my version of it is imported as asyncore, how >>>>> would it import the built-in version from python2.5/site-packages? >>>>> >>>>> Thanks, >>>>> Tro >>>> What happens if you do "import my.package.asyncore as asyncore"? >>>> >>>> If that doesn't work (trying the simplest hack first), I know that >>>> there are various hooks in the import mechanism that should help. >>> In the classes that use my version of asyncore currently, that is how I >>> do it. I import my version as "import my.package.asyncore as asyncore". >>> In my asyncore module I do "import asyncore", because I override a few >>> functions from the asyncore module included with python. However, if I >>> were to add "my.package" to sys.path, then I wouldn't be able to "import >>> asyncore" from my own asyncore module. I'd have to do some trickery with >>> sys.path to take the "my.package" component out, import standard >>> asyncore, readd the "my.package" component, so that other modules can >>> "import asyncore" and get my version. >>> >>> Is there a way to import the standard python asyncore module in this >>> scenario? >>> >>> Thanks, >>> Tro >>> >>> >> Are you trying to interfere with the default module on only your >> machine? Just rename it. If something in the std. lib. imports >> asyncore, they get yours too that way. > > No, I'd like it to be a generalized solution and only for this one project. > I'm trying to get it to work on any recent python installation out of the > box, so I can't rename built-in modules. What I'm trying to do is allow a 3rd > party module (tlslite) to import *my* version of asyncore without me going > into tlslite's code and changing its import statement explicitly, but only > for the scope of this one project. > In that case try something like import myasyncore as asnycore sys.modules['asyncore'] = asyncore import tlslite regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Mon Mar 31 22:39:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 23:39:36 -0300 Subject: Python and Db References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> Message-ID: En Mon, 31 Mar 2008 17:50:42 -0300, David Anderson escribi?: > I would like to use sqlite, But I also wanted a tutorial with the basis > of > the sql and etc, I never dealed with dbs before Then any database tutorial covering SQL will do. Of course there are differences between different DBMS, but the basics are the same. Once you know the SQL sentence you want to execute (e.g. "select name, salary from employee order by name") consult the Python docs to see how to actually write it: conn = sqlite3.connect('acme.db') cursor = conn.cursor() cursor.execute("select name, salary from employee order by name") for row in cursor: name, salary = row print "%20s %8.2f" % (name, salary) -- Gabriel Genellina From phishboh at gmail.com Mon Mar 17 05:08:30 2008 From: phishboh at gmail.com (phishboh at gmail.com) Date: Mon, 17 Mar 2008 02:08:30 -0700 (PDT) Subject: Image capture from Alacron FastFrame-CB Message-ID: Hi. I would like to perform some image processing using Python. Can someone please point me in the right direction on how to get images from the framegrabber (Alacron FastFrame-CB)? Is VideoCapture (http://videocapture.sourceforge.net/) the correct way to go? Thanks in advance. From castironpi at gmail.com Wed Mar 26 01:46:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 22:46:17 -0700 (PDT) Subject: My python interpreter became mad ! References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> Message-ID: <8f52bc76-e0e8-4bd9-93e2-0f37426869b6@k13g2000hse.googlegroups.com> On Mar 25, 7:45?pm, John Machin wrote: > Furkan Kuru incorrigibly top-posted: > > > Ok, you're right. > > > but I did not give it a chance "not trying python interpreter in another > > directory" > > I don't understand that sentence. > > > so if we assume the problem exists in every directory, it has something > > to do with ?pythonpath. > > Why would/should we assume that? Process of enumeration. > > you can try setting pythonpath to some directory and put a re.py there > > and try from any directory starting your interpreter and importing re. > > and achieve the same result: importing the bogus re. What's your point? I'm not so sure that dispute burdens of proof are resolved all that virtuously (life isn't fair; fair is good). What are newsgroups like in the monarchies? Ever feel you're typing on auto-pilot? It's not like you vote on me staying. However, the things I've said about myself aren't written intepretation-strict, thence there must be some distinction between interpretations, or between resident attitudes for me? Perhaps my fault for overinvesting hope in the newsgroups. You're not a best friend to me! . If you look like your pets, do we look like computers? Restrictions are different for justice: my only analytically (or never) outweighs my threshold. By the process of cognition, we ascribe malice (how probabilistically- malicious is it) to people (as danger to objects?), but the ideal realm (kingdom Logos), but revising estimates is expensive. Do visual mirrors make a round-trip error? Is there emotionally such thing as a computer? They are certainly deep, but perhaps only axiomatically; people aren't made of binary. How far to the nearest indefinite precision computer? Any pull around here? Someone have a thesis on wake-detection in a parallel system? Can we 'black-box' people? ("Are you a black box?") What kind of accuracy is there in uniform media? Can we 'black-box' groups? Wakes and patterned perturbations can be modeled in feature-sets, abitrary feature collisions not fully particle. I'd be more interested in a feature specialty that facilitates to transmit waves, and a sum-of-waveform native. Is there a recursive expression of the taylor expansion of e^x, by the way? Interface and deface. Honest and true? Can you just buffer? Beliefs might settle wrong, and it's hard to change them: huge machine, right nail. Can a spider swarm simulate a macro operation (building a building), either given a power source or carrying "lifeform batteries"? Operator would need interface: thought to operation: fast enough - idle loop cost: can't be governing every small bug (once again, features over particles), the machines would need overall/level/summary operations, read memories. But you can get a couple microvolts and a memory cell on a 2-micron spider, and a radio-static but sees a medium, speed-of-propogation, limitation. Just think outside the case. How organized is the newsgroup? Can I buy a long non-commutative associative (time order (resort)) record? It's not. (That's a tongue thing, right?) A place to come to: a place to sit at energy level. (New you vs. same me here too.) 2-D primitives suck on serial input. I'd almost rather decode a video of hands. Would a computer mind learning? You could by a perceptive-order code. What the world needs is a few good spacers. I have to think; leave silent, and return broadcasting. How's yours suck + what's the monkey on your back? Multi-type time people for sale, American dollar. Anyone up for a little register- base broadcasting? It's a broad. From aaron.watters at gmail.com Fri Mar 28 09:33:29 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 28 Mar 2008 06:33:29 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: On Mar 27, 6:00 pm, John Machin wrote: > ...The Python csv module emulates Excel in delivering garbage silently in > cases when the expected serialisation protocol has (detectably) not > been followed.... Fine, but I'd say the heuristic adopted produces bizarre and surprising results in the illustrated case. It's a matter of taste of course... -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=mondo+bizarre From hdante at gmail.com Sun Mar 30 08:41:28 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 05:41:28 -0700 (PDT) Subject: python ODF library? References: Message-ID: On Mar 30, 9:29 am, Matias Surdi wrote: > Do yo know any good OpenDocumentFormat library for python? > > I'm starting a project on wich I'll have to programatically modify ODF > text documments, so, after reinventing the wheel, I'd like to know if > already something exists. > > Thanks a lot. Excellent question. I've found this (have no idea if it works). http://appyframework.org/pod.html It's possible that you could implement what you want by hand. There's this book: http://books.evc-cit.info/odbook/book.html which has a lot of code snippets. On the other hand, it may be easier to pick and editor and go with its scripting lanugage. From tenax.raccoon at gmail.com Mon Mar 24 10:48:04 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 24 Mar 2008 07:48:04 -0700 (PDT) Subject: Shortcutting the function call stack References: Message-ID: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> On Mar 24, 5:21 am, Julien wrote: > Hello all, > > I would like to do something like: > > def called(arg) > if arg==True: > !!magic!!caller.return 1 > > def caller(arg) > called(arg) > return 2 > > Here, the fake !!!magic!!! represents a statement (which I ignore) > that would make the caller function return a value different from what > it'd return normally. > > For example, caller(True) would return 1, and caller(False) would > return 2. The reason I want that is because I don't want the caller > function to know what's going on in the called function, and be > shortcut if the called function think it's necessary. > > Would you know if that's possible, and if so, how? > > I've done a bit of research and I think I've found some good pointers, > in particular using the 'inspect' library: > > import inspect > > def called(arg) > if arg==True: > caller_frame = inspect.stack()[1] > ... > > Here 'caller_frame' contains the frame of the caller function. Now, > how can I make that frame return a particular value? > > By the way, I'm not really interested in 'called' throwing an > exception and 'caller' catching it. In fact, I want things to remain > completely transparent for 'caller'. > > Hope that was clear... :/ > > Thanks! > > Julien As Steven wrote, it's not very clear. If we knew the intent of this, we could perhaps point you to a more useful, maintainable technique. We don't know why you're trying to circumvent the programming language in this case. Any solution that works as you described will probably be unportable between the different Pythons (CPython, Jython, IronPython, etc). Please note that the following code should work, but I've only run it through the interpreter in my brain. My brain's interpreter is full of Heisenbugs, so you may need to adjust a few things. Here's my thoughts: Given: def First( arg ): Second( arg ) return 5 1) If you can modify both functions, change the first function to return a value in certain circumstances: def AltFirst( arg ): value = Second( arg ) if value is not None: return value return 5 2) Raise an exception in Second, and catch that exception above First: class SecondExcept(Exception): def __init__(self, value): Exception.__init__(self, 'Spam!') self.value = value def Second(arg): if arg == my_conditional_value: raise SecondExcept( 5 ) # The following could even be put in your own function, # or in a wrapper or decorator for the First function. try: myvalue = First( 'Vikings!' ) except SecondExcept, exc: myvalue = exc.value When you need to use an exceptional pathway, use an exception. They aren't just for reporting errors. Hope this helps. --Jason From usenet at solar-empire.de Mon Mar 10 10:40:10 2008 From: usenet at solar-empire.de (Marc Christiansen) Date: Mon, 10 Mar 2008 15:40:10 +0100 Subject: tcp client socket bind problem References: Message-ID: natambu at gmail.com wrote: > I have a linux box with multiple ip addresses. I want to make my > python client connect from one of the ip addresses. Here is my code, > no matter what valid information I put in the bind it always comes > from the default ip address on the server. Am I doing something wrong? > > ------------- > #!/usr/bin/python > > import socket > > host = "server" > port = 1190 > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > sock.bind(("",0)) > sock.connect((host, port)) > ------------- Looks good to me. Just to verify it, I added 127.1.2.3 as an address to lo (ip addr add 127.1.2.3/8 dev lo broadcast 127.255.255.255), and... >>> import socket >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> sock.bind(("127.1.2.3",0)) >>> sock.connect(("127.0.0.1",80)) In another shell: tolot:~> lsof -c python -a -i -nP COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME [...] python 1287 tolot 3u IPv4 3553610 TCP 127.1.2.3:38329->127.0.0.1:80 (ESTABLISHED) Looks correct. This is using Linux 2.6.23. So, if you're doing something wrong, it's nothing obvious to me. Marc From furkankuru at gmail.com Tue Mar 25 19:04:59 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 01:04:59 +0200 Subject: My python interpreter became mad ! In-Reply-To: <47E964CA.4070603@lexicon.net> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> Message-ID: <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> Ok, you're right. but I did not give it a chance "not trying python interpreter in another directory" so if we assume the problem exists in every directory, it has something to do with pythonpath. you can try setting pythonpath to some directory and put a re.py there and try from any directory starting your interpreter and importing re. On 3/25/08, John Machin wrote: > > Furkan Kuru top-posted: > > Most probably X-Spam added itself to your path. > > What is "X-Spam"? Added itself to Benjamin's path [not mine] in such a > fashion that it is invoked when one does "import re"? > > > you should look at your PATH and PYTHONPATH environment variables. > > Most *IM*probably. Read the traceback: > """ > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > """ > > This is a classic case of a script (which does not guard against side > effects (like spewing out gibberish) when imported instead of being > executed) being given the same name as a Python-included module and > being executed in the current directory and hence ends up importing > itself. > > > > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > > wrote: > > > > On Mar 25, 10:05 pm, Benjamin Watine > > wrote: > > > Yes, my python interpreter seems to became mad ; or may be it's > > me ! :) > > > > > > I'm trying to use re module to match text with regular > > expression. In a > > > first time, all works right. But since yesterday, I have a very > > strange > > > behaviour : > > > > > > $ python2.4 > > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > > > Type "help", "copyright", "credits" or "license" for more > > information. > > > >>> import re > > > X-Spam-Flag: YES > > [snip] > > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "/etc/postfix/re.py", line 19, in ? > > > m = re.match('(Spam)', mail) > > > AttributeError: 'module' object has no attribute 'match' > > > >>> > > > > > > What's the hell ?? I'm just importing the re module. > > > > No you're not importing *the* re module. You're importing *an* re > > module, the first one that is found. In this case: your own re.py. > > Rename it. > > > > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From noah at noah.org Thu Mar 13 21:34:49 2008 From: noah at noah.org (Noah) Date: Thu, 13 Mar 2008 18:34:49 -0700 (PDT) Subject: How do I iterate over items in a dict grouped by N number of elements? Message-ID: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> What is the fastest way to select N items at a time from a dictionary? I'm iterating over a dictionary of many thousands of items. I want to operate on only 100 items at a time. I want to avoid copying items using any sort of slicing. Does itertools copy items? This works, but is ugly: >>> from itertools import * >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} >>> N = 3 >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N): ... print G ... (('a', 1), ('c', 3), ('b', 2)) (('e', 5), ('d', 4), ('g', 7)) (('f', 6), ('i', 9), ('h', 8)) (('j', 10), None, None) I'd prefer the last sequence not return None elements and instead just return (('j',10)), but this isn't a huge deal. This works and is clear, but it makes copies of items: >>> ii = D.items() >>> for i in range (0, len(ii), N): ... print ii[i:i+N] ... [('a', 1), ('c', 3), ('b', 2)] [('e', 5), ('d', 4), ('g', 7)] [('f', 6), ('i', 9), ('h', 8)] [('j', 10)] -- Noah From iwanttobeabadger at googlemail.com Mon Mar 24 18:56:08 2008 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Mon, 24 Mar 2008 22:56:08 +0000 Subject: Calling a shared library using C types In-Reply-To: References: Message-ID: Hi, I know this is a pretty simple question but I've spent a while on this and can't see whats wrong. I'm trying to access a shared library which I've created called Simulation.so, its created as such (snip from makefile): all: simulation simulation: Simulation.so Simulation.so: Simulation.o Statistics.o gcc -shared Simulation.o Statistics.o -L/usr/local/lib -lsbml -lstdc++ -lm -o Simulation.so Statistics.o: Statistics.c Statistics.h gcc -fpic -g -O2 -I/usr/include -c Statistics.c Simulation.o: Simulation.c gcc -fpic -g -O2 -I/usr/include -c Simulation.c and I can load it properly in python import ctypes t = ctypes.CDLL('./Simulation.so') this works fine, I have a simple function I ve put in for testing which just returns the integer 4. However when I try to access this function it doesnt work t.test() File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 325, in __getattr__ func = self.__getitem__(name) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 330, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x81e6b0, test): symbol not found I've tried using t.__getattr__("test") but still have the same exception, I've tried loading the library with mode = RTLD_GLOBAL aswell and still have no luck. As far I as I can see this should work? But as I am just starting with ctypes I am sure I doing something sorry very stupid. Any pointers would be greatly appreciated, Many thanks in advance, Nathan Im hoping python-list is ok for questions regarding ctypes :S -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregory.bronner at lehman.com Fri Mar 7 09:13:57 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 7 Mar 2008 09:13:57 -0500 Subject: Edit and continue? Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2972@nypcmg1exms318.leh.lbcorp.lehman.com> I haven't seen much on this for a few years: I'm working on a GUI application that has lots of callbacks. Testing it is very slow and quite boring, as every time I find an error, I have to exit it, restart it, and repeat the series of clicks. It would be really amazing if python supported a reasonable form of edit and continue. Is there any way to do this? I'd like to be able to change my code and have it apply to a running instance of a class. Thanks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From castironpi at gmail.com Sun Mar 2 11:02:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 08:02:50 -0800 (PST) Subject: Keeping the console window References: <62vs0iF24tv6jU1@mid.individual.net> <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> Message-ID: On Mar 2, 9:55?am, Sam wrote: > You may use python in interactive mode: > > $ python -i yourScript.py > > Or use a blocking readline: > > $ cat yourScript.py > import sys > sys.stdin.readline() > > ++ > > Sam FWIW, for what it's worth, you can invoke the interpreter from a batch file/shell script too, and just use the native PAUSE instruction to prompt for 'any key to continue'. From miki.tebeka at gmail.com Wed Mar 12 18:34:48 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 12 Mar 2008 15:34:48 -0700 (PDT) Subject: How to make a Tkinter widget always visible? References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> <47D6C81A.1070301@codebykevin.com> <47D6D890.3060104@codebykevin.com> Message-ID: Hello Kevin, > Please post the code you're using--it will be easier to help if we can > see exactly what you are trying. In a nutshell: ------------------------------- import Tkinter as tk, tkFont from tkMessageBox import showinfo, showerror from os import popen def main(): root = tk.Tk() # Log window tk.Label(root, text="Log:", anchor=tk.W).pack(fill=tk.X) frame = tk.Frame(root) scrollbar = tk.Scrollbar(frame) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) log = tk.Text(frame, width=80) log.config(state=tk.DISABLED) log.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) scrollbar.config(command=log.yview) frame.pack(fill=tk.BOTH, expand=1) # Button frame frame = tk.Frame(root) update = tk.Button(frame, text="GO", command=lambda: showinfo("OUCH")) update.pack(side=tk.LEFT) tk.Button(frame, text="Quit", command=root.quit).pack(side=tk.LEFT) frame.pack(fill=tk.X) root.bind("", lambda e: root.quit()) update.focus() root.minsize(-1, 100) root.mainloop() if __name__ == "__main__": main() ------------------------------- When I pack the buttons frame first (using side=BOTTOM), it stays visible at all times. Thanks, -- Miki http://pythonwise.blogspot.com From musiccomposition at gmail.com Sat Mar 15 22:28:32 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 15 Mar 2008 19:28:32 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: On Mar 15, 7:29 pm, castiro... at gmail.com wrote: > 'join' in the wrong word for the method in class Thread. > > The agent-patient semantics of calling functions can get ambiguous. > It is not a problem of native Pythoners alone. Is it due to lazy > programming, an inability of English (do you have it in other > languages?), or not a problem at all? This is what Java uses, and Python's threading module tries to imitate it. > > th1.join() doesn't mean, 'do something to th1', or even, 'have th1 do > something to itself.' In fact, if anything is doing anything > differently, taking waiting to be doing something different, it's the > caller. > > Translating literally, > > th1.join() -> join me here, th1. > > And, > > file1.close() -> close yourself, file1. > > But not, > > th1.join() -/> join yourself, th1. > > Worse, > > lock1.wait() -/> wait, lock1. (For what?) > > Furthermore, in toolbars: > > File -> Open -/> file an open. > > and: > > File -> Load -/> load a file. (It means, load the computer.) > > In English, the placements of identifiers isn't consistent. IOW, > there isn't a syntactic mapping into natural language sentences. > (Though you can do it in Latin, German, Sanskrit, and Russian with > case markers*.) What are the true literals? What's doing what? > > th1.join() -> 'be joined by th1' > file1.close()-> 'close file1' > lock1.wait()-> 'getinlinefor lock1' > > And of course, 'open' isn't a method of File objects at all. The > closest is, 'be loaded by file1'. > > Assuming speakers** of classical computer languages use OVS order-- > object-verb-subject***, the most literal transformations are: > > th1.bejoinedby() > file1.close() > lock1.getinlinefor(). > > The mapping of identifiers to English isn't consistent. It takes some > knowledge to read them-- shuffle an English sentence and it changes > meaning. > > Functional languages are one long sentence: True.**** Declarative > ones tell a story. ('th1' joins him.) Imperatives command an > impartial audience. > > What do the docs say about it? > > ''' > Thread.join([timeout]) > Wait until the thread terminates. This blocks the calling thread until > the thread whose join() method is called terminates - either normally > or through an unhandled exception - or until the optional timeout > occurs. > > When the timeout argument is present and not None, it should be a > floating point number specifying a timeout for the operation in > seconds (or fractions thereof). As join() always returns None, you > must call isAlive() after join() to decide whether a timeout happened > - if the thread is still alive, the join() call timed out. > > When the timeout argument is not present or None, the operation will > block until the thread terminates. > > A thread can be join()ed many times. > > join() raises a RuntimeError if an attempt is made to join the current > thread as that would cause a deadlock. It is also an error to join() a > thread before it has been started and attempts to do so raises the > same exception. > ''' > > The natural language meaning of 'join' isn't used. Do benevolent > dictators do this? What do malevolent ones call themselves? > > *Latin, German, Sanskrit, and Russian can do it. Latin, German, > Sanskrit, and Russian -speakers- can do it. > **It would be interesting to try to learn a language without ever > speaking it. > *** English is SVO, subject-verb-object. French is too, unless the > object is direct: subject- direct-object -verb. > **** The sum of the first three integers in the last two files, sorted > alphabetically, in 'c:\programs'. From mahesh.prakriya at gmail.com Tue Mar 18 01:39:07 2008 From: mahesh.prakriya at gmail.com (mahesh.prakriya at gmail.com) Date: Mon, 17 Mar 2008 22:39:07 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 7:10?am, Bruce Eckel wrote: > If the following seems unnecessarily harsh, it was even more harsh for > me to discover that the time and money I had spent to get to my > favorite conference had been sold to vendors, presenting me as a > captive audience they could pitch to. > Yes, the keynotes were very boring compared to last year. If there's only one thing ot change, I think sponsorship shouldn't entitle one to a keynote. FWIW, tho we sponsored at a Platinum level from Microsoft this year but we declined to take up on any lightning talks, etc. To me, its worth sponsoring PyCon (just for Python) irrespective of what we get. From crackeur at comcast.net Tue Mar 4 19:54:16 2008 From: crackeur at comcast.net (jimmy Zhang) Date: Tue, 4 Mar 2008 16:54:16 -0800 Subject: Latest XML Parsing/Memory benchmark Message-ID: The latest benchmark results are now available using the latest Intel Core2 Duo processor. In summary, VTD-XML using JDK 1.6's server JVM achieved an astonishing 120MB/sec sustained throughput per core on a Core2 Duo 2.5 GHz processor. * Parsing Only: http://www.ximpleware.com/2.3/benchmark_2.3_parsing_only.html * XPath Only: http://www.ximpleware.com/2.3/benchmark_2.3_xpath.html * Parsing/XPath/Update: http://www.ximpleware.com/2.3/benchmark_2.3_update.html * Indexing/XPath/Update: http://www.ximpleware.com/2.3/benchmark_2.3_indexing.html From timr at probo.com Sat Mar 1 01:59:29 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 01 Mar 2008 06:59:29 GMT Subject: rstrip error python2.4.3 not in 2.5.1? References: <3bb061c2-4ec0-4ad0-add0-035264caa28b@s37g2000prg.googlegroups.com> <5114b18c-80ab-43b7-bedf-e8a553093be3@k2g2000hse.googlegroups.com> Message-ID: dirkheld wrote: >> >> What is the actual error message [SyntaxError, NameError? etc] that you >> clipped? > >Here it is : I tought that I didn't matter because the deliciousapi >worked fine on my mac. > >Traceback (most recent call last): > File "delgraph.py", line 62, in ? > url_metadata = d.get_url(site.rstrip()) > File "deliciousapi.py", line 269, in get_url > document.bookmarks = self._extract_bookmarks_from_url_history(data) > File "deliciousapi.py", line 297, in >_extract_bookmarks_from_url_history > timestamp = datetime.datetime.strptime(month_string, '%b ‘ >%y') >AttributeError: type object 'datetime.datetime' has no attribute >'strptime' I suppose it is cruel of me, but I find it hilarious that you looked at this traceback and came to the conclusion that the problem was in "rstrip". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mnordhoff at mattnordhoff.com Wed Mar 12 09:09:06 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 12 Mar 2008 13:09:06 +0000 Subject: Creating a file with $SIZE In-Reply-To: <47D7D1F3.5040706@jouy.inra.fr> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> Message-ID: <47D7D5F2.8050303@mattnordhoff.com> Robert Bossy wrote: > k.i.n.g. wrote: >> I think I am not clear with my question, I am sorry. Here goes the >> exact requirement. >> >> We use dd command in Linux to create a file with of required size. In >> similar way, on windows I would like to use python to take the size of >> the file( 50MB, 1GB ) as input from user and create a uncompressed >> file of the size given by the user. >> >> ex: If user input is 50M, script should create 50Mb of blank or empty >> file >> > def make_blank_file(path, size): > f = open(path, 'w') > f.seek(size - 1) > f.write('\0') > f.close() > > I'm not sure the f.seek() trick will work on all platforms, so you can: > > def make_blank_file(path, size): > f = open(path, 'w') > f.write('\0' * size) > f.close() I point out that a 1 GB string is probably not a good idea. def make_blank_file(path, size): chunksize = 10485760 # 10 MB chunk = '\0' * chunksize left = size fh = open(path, 'wb') while left > chunksize: fh.write(chunk) left -= chunksize if left > 0: fh.write('\0' * left) fh.close() > Cheers, > RB -- From davids at evertech.com.au Fri Mar 14 07:38:31 2008 From: davids at evertech.com.au (David S) Date: Fri, 14 Mar 2008 11:38:31 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: Hi, Gets me further but still seems to be issue with space after 'Program' as code tries to run 'C:\Program'. Don't understand what is going on here... using "java.exe" from "C:\Program Files\Java\jdk1.6.0_01" using "C:\Program Files\apache-ant-1.7.0\bin\ant.bat" for building Building from E:\Red5\red5_server\install\windows Cleaning old directories... Compiling Java 1.5 version... 'C:\Program' is not recognized as an internal or external command, operable program or batch file. Traceback (most recent call last): File "installer.py", line 132, in main() File "installer.py", line 128, in main builder.build() File "installer.py", line 70, in build self.compile(self.ant_cmd, os.path.join(red5_root, 'build.xml'), '1.5', 'cle an', 'installerdist') File "installer.py", line 26, in compile assert os.system('%s -quiet -Djava.target_version=%s -buildfile %s%s' % (ant , version, script, args)) == 0 AssertionError "Bryan Olson" wrote in message news:LxqCj.19741$Ch6.1841 at newssvr11.news.prodigy.net... > David S wrote: >> I get >> >> ERROR: ""C:\Program Files\apache-ant-1.7.0\bin\ant"" does not exist >> >> If I cut the path statement here and paste it next to a windows XP >> command prompt ant is invoked. >> >> The python code here is >> if not os.path.isfile(ANT_CMD): >> error('"%s" does not exist' % ANT_CMD) > > There you don't want the quotes within the string. On my MS-Win box: > > >>> import os > >>> os.path.isfile(r'C:\Program Files\Windows NT\dialer.exe') > True > >>> print os.path.isfile(r'"C:\Program Files\Windows NT\dialer.exe"') > False > > > -- > --Bryan From bearophileHUGS at lycos.com Wed Mar 5 19:40:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 5 Mar 2008 16:40:56 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> Message-ID: <83f40c69-a356-4af3-8fcf-aac4097dc480@n75g2000hsh.googlegroups.com> Troels Thomsen: > The discussion of words is silly. My surprise about "else following a for > loop.... what the heck ...." lasted excactly as long as it takes to read > this sentence. Maybe I don't follow what you are saying, but well chosen words are a very important part of a well designed API. If you take a look at the Python developers mailing list you may see that people discuss days, weeks to find the best naming for things. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 20:23:13 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 00:23:13 -0000 Subject: Access function name from within a function References: Message-ID: <13tgsvhe3too5d2@corp.supernews.com> On Thu, 13 Mar 2008 00:16:13 +0100, Hellmut Weber wrote: > Hi, > i would liek to define an error routine which print amongs other things > the name of the function from which it has been called. You mean like Python exceptions already do? >>> def broken(): ... x = 100 + 'foo' ... return x ... >>> broken() Traceback (most recent call last): File "", line 1, in File "", line 2, in broken TypeError: unsupported operand type(s) for +: 'int' and 'str' > IOW what I'm looking for is: > > def bar(): > name = some_function(some-parameter) > print name > > should print 'bar' I'm guessing that what you want to do is something like this: def bar(): do_calculation() if error: call_error_routine("something went wrong", magic_function()) where magic_function() knows the name of bar() is "bar". But you already know the name of the function when you write it, so why can't you do this? def bar(): do_calculation() if error: call_error_routine("something went wrong", "bar") Of course, this has the disadvantage that if you change the name of the function bar(), you have to manually change the argument to your error routine as well. Another approach is this: def bar(): import inspect return inspect.getframeinfo(inspect.currentframe())[2] but this should be considered the deepest Black Magic. I can make no promises that it will work the way you expect it to work in all circumstances. If you use this, you're elbow-deep in the Python internals. Frankly, I think your approach of having an "error routine" is probably the wrong approach, and you're better to use exceptions. But I could be wrong. -- Steven From castironpi at gmail.com Sun Mar 2 21:50:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 18:50:43 -0800 (PST) Subject: along the lines, hash and obj. id. References: <1460d022-a990-42d8-8117-4f28025d1027@b29g2000hsa.googlegroups.com> <13s78vvhjhl1df8@corp.supernews.com> <59e8ba74-0014-4366-a293-d15a0aabb23d@h25g2000hsf.googlegroups.com> Message-ID: <3f9f7fae-e0cd-46be-9128-298b6cdd4be4@s13g2000prd.googlegroups.com> On Feb 27, 5:38?pm, castiro... at gmail.com wrote: > On Feb 27, 4:16 pm, "Gabriel Genellina" > > For a), you use something like obj.a.somemethod(). "obj.a" still refers to > > the same object, even if it changed internally; if obj.a and foo.bar both > > were refering to the same object, they still do. [1] > > Or wrap the value into another shared object. > it can still set the element there: elem.val= 0, elem.val+= 1, &c., in Following obj.a.val is foo.bar.val and obj.a is foo.bar, you can also get away with a= A(); a.c.val= 2; assert A.c.val== 2. From fakeaddress at nowhere.org Fri Mar 21 05:17:10 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 21 Mar 2008 09:17:10 GMT Subject: finding items that occur more than once in a list In-Reply-To: References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > Bryan Olson wrote: [...] >> Arnaud Delobelle offered a good Wikipedia link, and for more background >> look up "amortized analysis. > > Hrvoje Niksic provided the link :). Oops, careless thread-following. Hrvoje Niksic it was. > I still think two unrelated > things are being compared in this thread when people say that method A > (using dictionaries / sets) is O(n) and method B (sorting the list) > O(nlogn). > > Isn't it the case that: > > | Worst case | Average case > ---------|------------|------------- > Method A | O(n^2) | O(n) > Method B | O(nlogn) | O(nlogn) > > Which method is the best would then be determined by the distribution > of the hash values of your data, and whether you want to have a > guarantee the method will have a less-than-quadratic behaviour. If we exclude the case where an adversary is choosing the keys, the chance of a seriously degenerate case in the hashing method is so remote that we do should not worry about it. Those who insist on ranking by worst-case behavior have probably abandoned Python long ago, as it uses those hashed 'dict' things everywhere. Of course they've also abandoned OS's with demand-paged virtual memory and such. -- --Bryan From keios.titan at gmail.com Thu Mar 6 14:14:54 2008 From: keios.titan at gmail.com (keios.titan at gmail.com) Date: Thu, 6 Mar 2008 11:14:54 -0800 (PST) Subject: Exploring Attributes and Methods Message-ID: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Hi, Is there a python command that allows me to extract the names (not values) of the attributes of a class. example Class Sample: fullname = 'Something' How can I know that this class has an attribute called 'fullname'? I hope my question is clear. Thanks From kf9150 at gmail.com Fri Mar 28 20:02:51 2008 From: kf9150 at gmail.com (Kelie) Date: Fri, 28 Mar 2008 17:02:51 -0700 (PDT) Subject: case insensitive lstrip function? References: <0eb666fe-8c3e-4a93-afbf-1953922c19bd@s13g2000prd.googlegroups.com> <655bbtF2e1u8fU2@mid.uni-berlin.de> Message-ID: <9b90c8d9-a53b-4a03-9a11-4af00e47bf2a@i29g2000prf.googlegroups.com> On Mar 28, 12:55 pm, Marc 'BlackJack' Rintsch wrote: > What about this: > > def lstrip2(string, chars, ignore_case=True): > if ignore_case: > chars = chars.lower() + chars.upper() > return string.lstrip(chars) > > Ciao, > Marc 'BlackJack' Rintsch Thanks Marc. I think yours looks much better. From castironpi at gmail.com Mon Mar 10 01:30:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 22:30:22 -0700 (PDT) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> <35ccf945-07ca-436f-a3a3-752fb0c1a7de@d62g2000hsf.googlegroups.com> Message-ID: <1af35fba-fdee-42b8-8196-568818c97860@d62g2000hsf.googlegroups.com> On Mar 8, 12:57?pm, Tim Chase wrote: > > I am a GNU newbie. ?(I know C &o.) ?Can you point me to a > > place to find the source for 'date'? > > It's part of the GNU Coreutils: > > http://ftp.gnu.org/gnu/coreutils/ > > Within the file, you're likely interested in lib/getdate.* > > It helps if you have a working knowledge of Yacc. > > -tkc Ah excellent. I am looking at the part with: static table const meridian_table[] = { { "AM", tMERIDIAN, MERam }, ... { "JANUARY", tMONTH, 1 }, { "FEBRUARY", tMONTH, 2 }, ... { "YEAR", tYEAR_UNIT, 1 }, { "MONTH", tMONTH_UNIT, 1 }, (where is 'lunar month'? ;) ) How do you like it? Certainly Python cleans it up by a multiple, but what about the rest? From aahz at pythoncraft.com Mon Mar 17 09:16:36 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 Mar 2008 06:16:36 -0700 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> Message-ID: In article <873aqp6bbq.fsf at physik.rwth-aachen.de>, Torsten Bronger wrote: >Carl Banks writes: >> On Mar 16, 10:49 pm, Brian Jones wrote: >>> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: >>>> >>>> If you did not like the programming this year (aside from the >>>> sponsor talks) and you did not participate in organizing PyCon >>>> or in delivering presentations, it is YOUR FAULT. PERIOD. >>>> EXCLAMATION POINT! >>> >>> I find this insulting, inexcusable, and utter nonsense. If >>> putting the blame for a failed experiment on the backs of the >>> good folks who paid good money for travel, lodging, and >>> registration is also an experiment, you can hereby consider it >>> also failed. >> >> He said "aside from the sponsor talks", chief. > >I see no reason why the "fault" for parts of the rest being >sub-optimal, too, must necessarily be on the attendee's side. (Just >hypothetically; I wasn't at PyCon.) Let's suppose you have a group of friends who collectively throw a party. They invite you to help out organizing it and putting it together, but you choose not to. If you don't have a good time at the party because it wasn't what you wanted, I think it's fair to say it was your fault. And I think exactly the same thing is true for PyCon, albeit on a much larger scale. It is absolutely critical to the long-term success of PyCon as a volunteer-run community conference that each attendee take responsibility for their experience. Science fiction fandom -- the part that holds volunteer-run events such as Worldcon -- has lots of experience with this model. It is one reason why such cons make a fuss about attendees being "members", compared to "purchasing a ticket" (which is what you do for a commercialized Star Trek con). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From 42flicks at gmail.com Mon Mar 3 03:59:07 2008 From: 42flicks at gmail.com (Mike D) Date: Mon, 3 Mar 2008 21:59:07 +1300 Subject: Trouble using XML Reader Message-ID: <2b54d4370803030059s722ed808j9ddd7512ed50eea4@mail.gmail.com> Hello, I'm using XML Reader (xml.sax.xmlreader.XMLReader) to create an rss reader. I can parse the file but am unsure how to extract the elements I require. For example: For each element I want the title and description. I have some stub code; I want to create a list of objects which include a title and description. I have the following code (a bit hacked up): import sys from xml.sax import make_parser from xml.sax import handler class rssObject(object): objectList=[] def addObject(self,object): rssObject.objectList.append(object) class rssObjectDetail(object): title = "" content = "" class SimpleHandler(handler.ContentHandler): def startElement(self,name,attrs): print name def endElement(self,name): print name def characters(self,data): print data class SimpleDTDHandler(handler.DTDHandler): def notationDecl(self,name,publicid,systemid): print "Notation: " , name, publicid, systemid def unparsedEntityDecl(self,name,publicid,systemid): print "UnparsedEntity: " , name, publicid, systemid, ndata p= make_parser() c = SimpleHandler() p.setContentHandler(c) p.setDTDHandler(SimpleDTDHandler()) p.parse('topstories.xml') And am using this xml file: Stuff.co.nz - Top Stories http://www.stuff.co.nz Top Stories from Stuff.co.nz. New Zealand, world, sport, business & entertainment news on Stuff.co.nz. en-nz Fairfax New Zealand Ltd. 30 /static/images/logo.gif Stuff News http://www.stuff.co.nz Prince Harry 'wants to live in Africa' http://www.stuff.co.nz/4423924a10.html?source=RSStopstories_20080303 For Prince Harry it must be the ultimate dark irony: to be in such a privileged position and have so much opportunity, and yet be unable to fulfil a dream of fighting for the motherland. EDMUND TADROS stuff.co.nz/4423924 Mon, 03 Mar 2008 00:44:00 GMT Is there something I'm missing? I can't figure out how to correctly interpret the document using the SAX parser. I'm sure I;'m missing something obvious :) Any tips or advice would be appreciated! Also advice on correctly implementing what I want to achieve would be appreciated as using objectList=[] in the ContentHandler seems like a hack. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From haraldarminmassa at gmail.com Wed Mar 12 06:14:06 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 12 Mar 2008 03:14:06 -0700 (PDT) Subject: Py2exe and Multi Treading problem. References: Message-ID: Farsheed Ashouri , > Here is my script > #********************************************************************** > #********************************************************************** > import threading > import socket > def openSocket(portNum): > mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) > mySocket.bind ( ( '', portNum ) ) > mySocket.listen ( 1 ) > channel, details = mySocket.accept() > msg = channel.recv(4096) > > class CmdPortThread( threading.Thread ): > def run( self ): > openSocket(6000) > > def fakeCommandPort(): > CmdPortThread().start() > fakeCommandPort() > If works perfect with python 2.5.2. Now I want to convert it to > standalone program. > but the .exe file fails to run without any error. are you sure that it fails to run? I expect it to run, and exit immediately after fakeCommandPort(). That is: there is nothing more to do in the main thread, so the application exits. To learn more, add prints and use the usual if __name__=='__main__' class CmdPortThread( threading.Thread ): def run( self ): print "Thread CmdPortThread running" openSocket(6000) if __name__=='__main__': print "Mese running" fakeCommandPort() print "Mese done starting Thread" Harald From kyosohma at gmail.com Sat Mar 15 18:08:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 15 Mar 2008 15:08:11 -0700 (PDT) Subject: Code to send RSS news by Sendmail References: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> Message-ID: <87941df1-a371-49ca-af6b-9016810035f2@u72g2000hsf.googlegroups.com> On Mar 15, 3:18 pm, Ulysse wrote: > Hello, > > I'm searching a code which allow you to parse each item in the RSS > feed, get the news page of each item, convert it to text and send it > by mail. > > Do you know if it exists ? > > Thanks Try using Google next time. In the meantime, here's the wiki on RSS: http://wiki.python.org/moin/RssLibraries As for emailing it, you should check out the email module: http://docs.python.org/lib/module-email.html Mike From pi.arctan at gmail.com Sat Mar 8 17:27:58 2008 From: pi.arctan at gmail.com (pi.arctan at gmail.com) Date: Sat, 8 Mar 2008 14:27:58 -0800 (PST) Subject: extract multiple ranges from a list References: Message-ID: On 8 Mar, 17:32, Peter Otten <__pete... at web.de> wrote: > pi.arc... at gmail.com wrote: > > One of my many project involves working with YUV-files, where I need > > to reduce > > the vertical resolution with a factor of two, i.e. remove every other > > scan line. > > Today I'm using two for-loops in the fashion shown below > > > y = [] > > for i in range(0, width*height, width*2): > > for j in range(0,width): > > y.append(Y[i+j]) > > > This approach doesn't feel very pythonic but I can't come up with a > > better idea to do it. > > I've tried list comprehension and map together with lambda but I can't > > get a flattened list > > of every other scan-line... > > > CIF = 352x288 items for luminance and the aim is to have the list > > below: > > y = [0:352 704:1056 ... ] > >>> width = 3; height = 5 > >>> Y = range(width*height) > >>> y = [] > >>> for i in range(0, width*height, 2*width): > > ... y.extend(Y[i:i+width]) > ...>>> y > > [0, 1, 2, 6, 7, 8, 12, 13, 14] > > Probably more efficient, but needs numpy: > > >>> import numpy > >>> width = 3 > >>> height = 5 > >>> Y = range(width*height) > >>> a = numpy.array(Y).reshape(height, width) > >>> a > > array([[ 0, 1, 2], > [ 3, 4, 5], > [ 6, 7, 8], > [ 9, 10, 11], > [12, 13, 14]])>>> b = a[::2] > >>> b > > array([[ 0, 1, 2], > [ 6, 7, 8], > [12, 13, 14]])>>> list(b.reshape(len(b)*width)) > > [0, 1, 2, 6, 7, 8, 12, 13, 14] > > Peter Thanx guys! From rokkamraja at gmail.com Fri Mar 7 02:01:10 2008 From: rokkamraja at gmail.com (Raja) Date: Thu, 6 Mar 2008 23:01:10 -0800 (PST) Subject: Python GDB Wrapper Message-ID: Hi, I am trying to develop a a GDB wrapper script in python which is able to extract a stack trace and all relevant data. Has anyone does this before ? Even some basic idea or code as to how to proceed would be great. Thanks, Raja. From deets at nospam.web.de Thu Mar 20 13:42:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 20 Mar 2008 18:42:15 +0100 Subject: zope and python 2.5.1 References: Message-ID: <64fm02F2ba5puU1@mid.uni-berlin.de> hberig wrote: > Hi, > I'm sorry if this is an off-topic message, but I didn't found other > group. > I've read some articles about Zope, and since I like very much python, > I would like to run a webserver application using Zope instead other > web application server. I've difficulties to install zope 3 and zope 2 > on linux 2.6.20 (ubuntu distribution), python 2.5.1. What happen?? Is > there a simple way to fix it? apt-get install python2.4 Diez From falk at green.rahul.net Tue Mar 4 02:06:45 2008 From: falk at green.rahul.net (Edward A. Falk) Date: Tue, 4 Mar 2008 07:06:45 +0000 (UTC) Subject: Answer: Is there a way to "link" a python program from several files? References: <0f3e4884-59f8-4db8-a2a3-6f6d4fc14275@u72g2000hsf.googlegroups.com> <92dc6954-6f9a-40b2-9cee-4bd46b9a2826@f47g2000hsd.googlegroups.com> Message-ID: In article <92dc6954-6f9a-40b2-9cee-4bd46b9a2826 at f47g2000hsd.googlegroups.com>, George Sakkis wrote: > >What's so complicated about "python setup.py install" ? Even that is >not strictly necessary for pure python packages; a user may just >unpack the archive, cd to the extracted directory and execute the >appropriate .py file(s). Aha. Completely forgot about setup.py. Unfortunately, under Linux, all it seems to do is build a tarball for me, which when unpacked produces several discrete .py files, leaving me back where I started. Anyway, I did what I should have done in the first place and trolled /usr/bin to see how other people had done it. It turns out there are a few answers: First, you can simply just produce the program as a single .py file (which is what I wound up doing). Second, you can put all the .py files other than the "main" one into /usr/share/ and then append that directory to your path before importing anything. Third, you can put all the .py files other than the "main" one into /usr/lib/python2.2/site-packages/ and then you don't have to modify your path. The second and third methods have the advantage that you can have .pyc files hanging around. Anyway, thanks for all your input. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From arnodel at googlemail.com Fri Mar 21 16:12:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 21 Mar 2008 13:12:56 -0700 (PDT) Subject: How can I make a function equal to 0? References: Message-ID: On Mar 21, 7:48?pm, Martin Manns wrote: > Hi, > > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > > >>> def f(): return "" > ... > >>> # Some magic > >>> f == 0 > > True Why do you want to do that? >>> class WhyOhWhy(object): ... def __init__(self, f): self.f = f ... def __call__(self, *args, **kwargs): return self.f(*args, **kwargs) ... def __eq__(self, other): return other == 0 ... >>> @WhyOhWhy ... def f(x): print "Why oh why,", x ... >>> f("do this?") Why oh why, do this? >>> f == 0 True >>> -- Arnaud From mail at timgolden.me.uk Sun Mar 16 10:51:03 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:51:03 +0000 Subject: Types, Cython, program readability In-Reply-To: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <47DD33D7.2020300@timgolden.me.uk> bearophileHUGS at lycos.com wrote: > It seems the development of Cython is going very well, quite > differently from the dead-looking Pyrex. I'll leave others to comment on how dead Pyrex is or isn't ... > Hopefully Cython will become > more user-friendly too (Pyrex is far from being user-friendly for > Windows users, it doesn't even contain a compiler, I think. The > ShedSkin Windows installer contains an old but working MinGW, and this > is positive). I'm not entirely sure why you think Pyrex should "contain a compiler". It certainly works well enough with the free [beer] MS VS 2008 Express and I'm fairly sure it's fine with MingW. Both of those are readily available and I don't imagine anyone who's going to use Pyrex / Cython / ShedSkin is going to baulk at downloading a compiler set :) TJG From aboudouvas at panafonet.gr Thu Mar 27 10:37:40 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 07:37:40 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: > > > As for psyco, are there any alternatives to use now ? > > Nope, but I heard through the grapevine that while it won't be supported for > all times to come, a new version is in the making. Aha!! It seems you have better "sources" than me! :) > But ultimately, the author says that the approach is flawed, so at *some* > point it will be discontinued. But that could be said about nearly > everything, couldn't it? > > Diez It is a pity because this module *does* really solve some problems... From craigm3604 at gmail.com Mon Mar 24 15:45:25 2008 From: craigm3604 at gmail.com (Craig) Date: Mon, 24 Mar 2008 12:45:25 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> <13ubd90kmbg7h57@corp.supernews.com> <8e6ae2a4-3df8-404b-8c69-9f0c301c96a9@u72g2000hsf.googlegroups.com> <13udggro39ase06@corp.supernews.com> <647d0f55-057d-4acc-b4b4-cc6d1346a91e@s37g2000prg.googlegroups.com> <13udrnd27fnjk1a@corp.supernews.com> <2c22cac9-7da6-4217-9f7e-dcce1794c230@s13g2000prd.googlegroups.com> Message-ID: On Mar 24, 12:27 pm, Craig wrote: > On Mar 23, 7:59 pm, Dennis Lee Bieber wrote: > > > > > On Sun, 23 Mar 2008 14:24:52 -0700 (PDT), Craig > > declaimed the following in comp.lang.python: > > > > This dll was designed to be used from either C or Visual Basic 6. > > > > I have the declare statements for VB6, if that helps. > > > Probably not that much -- I'd bet it's full of variant records > > > > Based on the results I have so far (and I have tried MANY permutations > > > like trying to use the LPSTR for SecKey and PriKey which are returned > > > as is TypeDef), it looks like SecKey and PriKey are being used as data > > > instead of pointers. > > > > For this, I try: > > > LPSTR = c_char_p > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPBSTR, > > > LPSTR] > > > SrchKey = > > > windll.oleaut32.SysAllocStringByteLen("MSD19DN > > > \x00", 41) > > > SecKey = create_string_buffer(41) > > > SecKey.raw = "1234567890123456789012345678901234567890" > > > PriKey = > > > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > > > 41) > > > TypeDef = create_string_buffer(128) > > > TypeDef.raw = "X".center(128, "X") > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(SrchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > and I get: > > > Traceback (most recent call last): > > > File "C:\temp\vbisam_test_2.py", line 158, in > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(S > > > rchKey)), SecKey, byref(c_void_p(PriKey)), TypeDef ) > > > WindowsError: exception: access violation reading 0x3433322D > > > > I notice that SecKey.raw starts with "1234" and the exception address > > > is 0x3433322D, which is "432-". > > > 0x2D is 4 less than the expected 0x31... > > > > And, changing to: > > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPSTR, > > > LPSTR] > > > PriKey = create_string_buffer(41) > > > PriKey.raw = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234" > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > I then get: > > > Traceback (most recent call last): > > > File "C:\temp\vbisam_test_2.py", line 159, in > > > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > > > byref(c_void_p(S > > > rchKey)), byref(c_void_p(SecKey)), PriKey, TypeDef ) > > > WindowsError: exception: access violation reading 0x4443423D > > > > I notice that PriKey.raw starts with "ABCD" and the exception address > > > is 0x4443423D, which is "DBC=". > > > ... and 0x3D is 4 less than the expected 0x41 > > > Which leads me to suspect that BSTR are a structure, not a plain > > string, in which the address given is supposed to be prefaced with a > > length value. IOWs, something like: > > > |----|--------------------------------------| > > ^ ^ C-string data > > | |Address to be passed > > |(address - 4) to get to a length count field > > > Confirmed:http://msdn2.microsoft.com/en-us/library/ms221069(VS.85).aspx > > > (the URL is from HTTP through to the end, including .aspx) > > > Creating such may not be difficult -- but passing it to the DLL > > could be. I don't know if ctypes allows pointer arithmetic. > > > ctypes OLESTR is a c_wchar_p, but that is still a c-style string with no > > length prefix. > > > The only mention of BSTR in the win32 extensions is in text that > > implies that the win32 extension library takes care of converting > > from/to BSTR and Python strings transparently -- but that won't work for > > your third-party library I suspect. > > > Might have to beg the author(s) of ctypes to add a BSTR type to the > > list of those supported... as I can find no means of tweaking the > > address computed by byref() to point somewhere into a structure rather > > than the beginning of the structure. > > > >>> pk = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 12) > > >>> pk > > 1373844 > > >>> id(pk) > > 18941724 > > >>> ctypes.string_at(pk) > > '1234567890' > > >>> ctypes.string_at(pk-4, 20) > > > '\x0c\x00\x00\x001234567890\x00\x01\x00\x00\x00\x00' > > > Okay, the return value from SysAlloc... IS the integer representing > > the address of a BSTR structure (IE, the address four bytes in from the > > real memory start)... Note how backing up 4 bytes reveals the BSTR > > length field > > > What happens if you just pass that item as-is, no byref(), no > > conversion to ctypes pointer types... > > > PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > SecKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > > res = VmxGet( byref(hwmcb), > > byref(SecIndex), > > byref(Option), > > byref(c_void_p(SrchKey)), > > SecKey, > > PriKey, > > TypeDef ) > > > >>> PriKey = ctypes.windll.oleaut32.SysAllocStringByteLen("1234567890", 41) > > >>> ctypes.string_at(PriKey, 41) > > > "1234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'">>> ctypes.string_at(PriKey-4, 41+4) > > > ")\x00\x00\x001234567890\x00\x01:\x00\x00\x00\xb6\x01\x00\x000\x99#\x01\xe0\x94\x1a\x1e\x0b\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00'" > > > >>> ord(")") > > 41 > > > You'll need to use the .string_at() or .wstring_at() functions to > > extract any data changed by the call. Should not be a Python > > immutability problem as all "you" allocated in Python is the integer > > holding the address. You may need to call a Sys... function to free the > > memory that had been allocated -- Python doesn't know about it. > > -- > > Wulfraed Dennis Lee Bieber KD6MOG > > wlfr... at ix.netcom.com wulfr... at bestiaria.com > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: web-a... at bestiaria.com) > > HTTP://www.bestiaria.com/ > > The VB6 Declare is: > Declare Function VmxGet Lib "vbis5032.DLL" (DatasetHandle&, > SecIndexField%, Options%, SelectorKey$, RSecondaryKey$, RPrimaryKey$, > RRecordVariable As Any) As Integer > > The only variant is the RRecordVariable, which is actually meant to be > a Type structure. > > Anyway, I thought maybe there was a clue in here that I am missing. > > Back to Python. I ran with the following: > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > LPSTR] > SrchKey = > windll.oleaut32.SysAllocStringByteLen("MSD19DN > \x00", 41) > SecKey = > windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", > 41) > PriKey = > windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", > 41) > TypeDef = create_string_buffer(128) > TypeDef.raw = "X".center(128, "X") > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) > And, now I get: > Traceback (most recent call last): > File "C:\temp\vbisam_test_2.py", line 156, in > res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), > byref(c_void_p(S > rchKey)), SecKey, PriKey, TypeDef ) > ctypes.ArgumentError: argument 5: : wrong > type > > So, now the problem is with: > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, > LPSTR] > I am not sure what to put for arguments 5 and 6 now. > > I realized the need to release the BSTRs myself, and already included: > windll.oleaut32.SysFreeString(SrchKey) > windll.oleaut32.SysFreeString(SecKey) > windll.oleaut32.SysFreeString(PriKey) > at the end of the program. > > I have no problem using .string_at() to extract the returned values - > once the .argtypes let the call execute. > > In case this helps, here is an excerpt from a C program that was > provided with the dll: > typedef struct tagMYREC > { > char name[51]; // 1 xref generated name key > > char lastname[31]; // 2 last name > char firstname[21]; // 3 first name > char address[41]; // 4 address > char city[31]; // 5 xref city key > char state[3]; // 6 xref state > char zip[11]; // 7 xref zip code > char phone[21]; // 8 xref phone number > BSTR notes; // 9 notes > > } MYREC; > typedef MYREC FAR * LPMYREC; > > short rc; // return code (from VB/ISAM function calls) > static HANDLE nDatasetNumber; > static short cur_index; > static short GetOpt; > static BSTR Dummy; > static BSTR Throwaway; > static BSTR PrimaryKey; > static MYREC myrec; > > rc = VmxGet(&nDatasetNumber, // int DatasetNumber // VIS_BUSY ? > &cur_index, // int SelectedIndex > &GetOpt, // int OptionParameter > &Dummy, // Don't need a Selector param with > these options > &Throwaway, // Don't need returned index entry in > this case > &PrimaryKey, // LPBSTR lpPriKey > (void *) &myrec); // LPVOID lpRecordStructure > > For someone who knows C and Python, this may provide a clue to the > BSTR passing/return problem. I received two emails from Dennis, included below (for completeness): ++++++++++++++++++++++++ Start of email #1 ++++++++++++++++++++++++ I'm back at work, hence the email. -=-=-=-=-=-=- So, now the problem is with: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPSTR, LPSTR, LPSTR] I am not sure what to put for arguments 5 and 6 now. I realized the need to release the BSTRs myself, and already included: windll.oleaut32.SysFreeString(SrchKey) windll.oleaut32.SysFreeString(SecKey) windll.oleaut32.SysFreeString(PriKey) at the end of the program. I have no problem using .string_at() to extract the returned values - once the .argtypes let the call execute. -=-=-=-=-=-=-=- Might I suggest plain old c_int (or c_int32) After all, you don't want a pointer /to/ the integer value that was returned by the SysAlloc...; the integer value itself /is/ the pointer (to the BSTR memory) that needs to be passed, as is, to the DLL function. c_int should do just that -- take the integer value "out" of the Python integer object, and put it on the stack for the DLL function. I must state that I'm surprised some parts of Windows is using a hybridized BCPL string. Last place I saw using those was on the Amiga -- in which, while the Exec, Intuition, Graphics, and other low- level libraries were in C, the command line user interface (utility commands, environment, etc.) were ported from Tripos -- and Tripos had been written in BCPL. The hybrid comment is that Windows is combining the BCPL length value with C null terminations, so the string can be used in both ways. +++++++++++++++++++++++++ End of email #1 +++++++++++++++++++++++++ ++++++++++++++++++++++++ Start of email #2 ++++++++++++++++++++++++ -=-=-=-=-=-=- TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") -=-=-=-=-=-=- typedef struct tagMYREC { char name[51]; // 1 xref generated name key char lastname[31]; // 2 last name char firstname[21]; // 3 first name char address[41]; // 4 address char city[31]; // 5 xref city key char state[3]; // 6 xref state char zip[11]; // 7 xref zip code char phone[21]; // 8 xref phone number BSTR notes; // 9 notes } MYREC; -=-=-=-=-=-=- Might I suggest increasing the length of your string buffer. Adding up the allocation in MYREC comes to: 179 bytes BEFORE including "notes" -- and as a BSTR declaration, notes is going to be a 4-byte length, 1 or 2 nulls (the spec for a unicode result implied a 2-byte null) PLUS whatever value length is itself. You may need to find out what the maximum length allowed for the notes field is in advance and add that to the buffer size. Pity its not a BSTR *notes -- that would imply memory allocated elsewhere and an address -- the .string_at() could use the pointer to retrieve the real notes. +++++++++++++++++++++++++ End of email #2 +++++++++++++++++++++++++ Sorry for the confusion on "MYREC" - this was just used in the sample C program provided with the dll. It is not applicable to the files I am using. For my file, the 128 is correct. I tried: VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, c_int32, c_int32, LPSTR] SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19DN \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234\x00", 41) TypeDef = create_string_buffer(128) TypeDef.raw = "X".center(128, "X") res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) And got: Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 156, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), SecKey, PriKey, TypeDef ) WindowsError: exception: access violation reading 0x3433322D That was what I was getting at earlier. We know that it is a c_int32 type, but the .argtypes is not doing something right (or I am not specifying it correctly). How do I correctly pass what needs to be passed? From gagsl-py2 at yahoo.com.ar Sun Mar 30 00:58:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 01:58:53 -0300 Subject: html DOM References: Message-ID: En Sun, 30 Mar 2008 00:19:08 -0300, Michael Wieher escribi?: > Was this not of any use? > > http://www.boddie.org.uk/python/HTML.html > > I think, since HTML is a sub-set of XML, any XML parser could be adapted > to > do this... That's not true. A perfectly valid HTML document might even not be well formed XML; some closing tags are not mandatory, attributes may not be quoted, tags may be written in uppercase, etc. Example: Invalid xml

a The above document validates with no errors on http://validator.w3.org If you are talking about XHTML documents, yes, they *should* be valid XML documents. > I doubt there's an HTML-specific version, but I would imagine you > could wrap any XML parser, or really, create your own that derives from > the > XML-parser-class... The problem is that many HTML and XHTML pages that you find on the web aren't valid, some are ridiculously invalid. Browsers have a "quirks" mode, and can imagine/guess more or less the writer's intent only because HTML tags have some meaning. A generic XML parser, on the other hand, usually just refuses to continue parsing an ill-formed document. You can't simply "adapt any XML parser to to that". BeautifulSoup, by example, does a very good job trying to interpret and extract some data from the "tag soup", and may be useful to the OP. http://www.crummy.com/software/BeautifulSoup/ -- Gabriel Genellina From edreamleo at charter.net Fri Mar 14 12:03:50 2008 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 14 Mar 2008 11:03:50 -0500 Subject: ANN: Leo 4.4.8 beta 2 released Message-ID: <5nxCj.8$ET1.2@newsfe06.lga> Leo 4.4.8 beta 2 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This version features a new ipython plugin that provides a two-way bridge between Leo and IPython. See http://webpages.charter.net/edreamleo/IPythonBridge.html Leo is a text editor, data organizer, project manager and more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.8: ---------------------------- - Leo's source code is now managed by bzr. See the Bzr link below. - Leo's discussion is now hosted by Google Groups: See the Forum link below. - The first, third, fifth etc. arguments to g.es and g.es_print can now be translated using Python's gettext.gettext function. - Completed ILeo: a bridge between IPython and Leo. See http://webpages.charter.net/edreamleo/IPythonBridge.html - Added support for arguments to minibuffer commands. - @menu trees can now refer to commands created by @command and @button nodes - Added support for common @commands nodes in settings files. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From nkanthikiran at gmail.com Wed Mar 12 06:32:22 2008 From: nkanthikiran at gmail.com (k.i.n.g.) Date: Wed, 12 Mar 2008 03:32:22 -0700 (PDT) Subject: Creating a file with $SIZE Message-ID: Hi All, I would like create files of different size, taking size as user input. I need to check the data transfer rates from one network to another . In order to do this I will have to create files of diff size and work out. I am new to Python Thanks in advance. KK From http Wed Mar 26 22:16:38 2008 From: http (Paul Rubin) Date: 26 Mar 2008 19:16:38 -0700 Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: <7xej9woqrd.fsf@ruckus.brouhaha.com> Sean Davis writes: > OR, NOT, etc.). Any suggestions on how to (1) set up the bit string > and (2) operate on 1 or more of them? Java has a BitSet class that > keeps this kind of thing pretty clean and high-level, but I haven't > seen anything like it for python. You could wrap something around the array module, or the bit vector objects from numarray, or use something like PyJudy (google for it). Or consider using something like a tree data structure that supports set operations, rather than a bitmap, if that's closer to what you're really trying to do. From Gerald.Klix at klix.ch Tue Mar 18 06:46:13 2008 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Tue, 18 Mar 2008 11:46:13 +0100 Subject: detect current timezone set by kde In-Reply-To: <20080318102726.GB3880@debian> References: <20080318102726.GB3880@debian> Message-ID: <47DF9D75.2050501@klix.ch> I suggest to change /etc/timezone by invoking sudo tzselect. HTH, Gerald Pradnyesh Sawant schrieb: > Hello, > can someone please tell me how can I programatically detect the timezone > information that has been set through kde? > > basically, I have a small pyqt4 app which shows the current time. however > it shows me my system time (dunno where that is stored; basically it shows > me time in IST). however, I'm right now in hk and would like the app to > show me time in my current timezone (hong kong). Any guidelines how may I > go about doing this? > > thanks a lot in advance :-) > From watine at cines.fr Tue Mar 25 09:50:51 2008 From: watine at cines.fr (Benjamin Watine) Date: Tue, 25 Mar 2008 14:50:51 +0100 Subject: My python interpreter became mad ! In-Reply-To: References: Message-ID: <47E9033B.3070108@cines.fr> John Machin a ?crit : > On Mar 25, 10:05 pm, Benjamin Watine wrote: >> Yes, my python interpreter seems to became mad ; or may be it's me ! :) >> >> I'm trying to use re module to match text with regular expression. In a >> first time, all works right. But since yesterday, I have a very strange >> behaviour : >> >> $ python2.4 >> Python 2.4.4 (#2, Apr 5 2007, 20:11:18) >> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import re >> X-Spam-Flag: YES >> X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org >> X-Spam-Level: ********************** >> X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, >> MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, >> >> RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, >> >> URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, >> URIBL_WS_SURBL autolearn=failed version=3.1.7-deb >> >> Traceback (most recent call last): >> File "", line 1, in ? >> File "/etc/postfix/re.py", line 19, in ? >> m = re.match('(Spam)', mail) >> AttributeError: 'module' object has no attribute 'match' >> >>> >> >> What's the hell ?? I'm just importing the re module. > > No you're not importing *the* re module. You're importing *an* re > module, the first one that is found. In this case: your own re.py. > Rename it. > Oh... yes, that's it ; I have a file named re.py ! Ouch, sorry for this stupid question, and thank you for this evident answer. I didn't knew that it was possible to import a module this way... Thank you for the fast answer ! Ben From nagle at animats.com Mon Mar 31 00:34:00 2008 From: nagle at animats.com (John Nagle) Date: Sun, 30 Mar 2008 21:34:00 -0700 Subject: Creating Class Objects in Loop In-Reply-To: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> References: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> Message-ID: <47f0673e$0$36321$742ec2ed@news.sonic.net> Fish wrote: > Hello Folks, > I am reading a CSV file and based on that I am creating TestCase(my > own defined class) objects in a for loop. The problem is each time I > create a new TestCase object in loop, previous objects data is already > copied in that object. What's actually happening to you is that you've run into one of the dumber features of Python - default values for parameters which are mutable, like lists, result in rather unexpected behavior. The problem is that def __init__(self, pcap = None, sids = []): creates the empty list "[]" once at startup, and that list is persistent across calls to __init__. Yes, that's wierd, but Python does that for historical reasons. Actually, you can write your main loop much more simply: def returnTcLst(path): fp = open(path) for line in fp: fields = line.split(",") # split into list at commas fields = map(lambda(s) : s.strip(), fields) # strip whitespace tcLst.append(TestCase(fields[0], fields[1:])) # pcap, then sids John Nagle From igorr at ifi.uio.no Tue Mar 11 20:05:06 2008 From: igorr at ifi.uio.no (Igor V. Rafienko) Date: 12 Mar 2008 01:05:06 +0100 Subject: catching object Message-ID: Hi, I was wondering if someone could help me explain this situation: h[1] >>> import inspect h[1] >>> inspect.getmro(ValueError) (, , , , ) h[2] >>> try: raise ValueError("argh") except object: print "why not?" Traceback (most recent call last): File "", line 2, in ValueError: argh The question is, why isn't ValueError caught? It *does* inherit from object (albeit indirectly), and my understanding of the wording of CPython docs is that this guarantees "compatibility" (between what is being raised and what is being caught). So, why doesn't object match ValueError (or any other exception for that matter). I am aware of "except:", but in my particular situation it is eh... unsuitable. Any hints/pointers are appreciated. ivr -- <+Kaptein-Dah> igorr: for f? parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent From martin at v.loewis.de Sat Mar 1 18:39:41 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Mar 2008 00:39:41 +0100 Subject: Problems building 2.5.1 on AIX In-Reply-To: References: Message-ID: <47C9E93D.3020208@v.loewis.de> > hasty:Python-2.5.1$ CC=/usr/vacpp/bin/cc_r ./configure --without-gcc > checking MACHDEP... aix5 > checking EXTRAPLATDIR... > checking for --without-gcc... yes > checking for gcc... cc > checking for C compiler default output file name... configure: error: C > compiler cannot create executables > See `config.log' for more details. > > I get the same result with or without the --without-cgg. There's nothing > obvious in config.log (not that I can ever make much sense out of the > gibberish configure generates). > > Any ideas? You really do have to check config.log. Check for any lines where it tries to invoke the compiler, and check whether it does so in the way you expect it to. From the output you provide, it seems to use "cc" as the compiler, not /usr/vacpp/bin/cc_r. Looking at the comfigure code, this is not surprising: --without-gcc resets CC to cc. Regards, Martin From deets at nospam.web.de Fri Mar 21 11:30:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Mar 2008 16:30:55 +0100 Subject: beginners question about return value of re.split In-Reply-To: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <64i2lmF2c6dvgU1@mid.uni-berlin.de> klaus schrieb: > Hello, > > I have a question regarding the return value of re.split() since I have > been unable to find any answers in the regular sources of documentation. > > Please consider the following: > > #!/usr/bin/env python > > import re > > if __name__ == "__main__": > datum = "2008-03-14" > the_date = re.split('^([0-9]{4})-([0-9]{2})-([0-9]{2})$', datum, 3) > print the_date > > Now the result that is printed is: > ['', '2008', '03', '14', ''] > > My question: what are the empty strings doing there in the beginning and > in the end ? Is this due to a faulty regular expression ? Read the manual: """ split( pattern, string[, maxsplit = 0]) Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.) """ The Key issue here being "If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list." Consider this: >>> re.compile("a").split("bab") ['b', 'b'] >>> re.compile("(a)").split("bab") ['b', 'a', 'b'] >>> Consider using match or search if split isn't what you actually want. Diez From Lie.1296 at gmail.com Thu Mar 13 14:46:16 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 13 Mar 2008 11:46:16 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: On Mar 13, 2:36?pm, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) ?[1,2,3,4] > 2) ?[1,2,3,4,5] > 3) ?That famous picture of Albert Einstein sticking out his tongue > 4) ?Nothing - no output > 5) ?None of the above > > I undertake to summarise answers posted to complete this "survey". > > - Hendrik I think I'll choose 3. Well, no, I suppose the correct behavior _should_ be undefined (i.e. what it returns is an implementation details that should not be relied on). The fact that it returns None is just a "coincidence" that happens to happen every time you tested it (you can't prove by ignorance) From istvan.albert at gmail.com Thu Mar 27 14:45:15 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 27 Mar 2008 11:45:15 -0700 (PDT) Subject: Is subprocess.Popen completely broken? References: Message-ID: <16300891-8fbf-489a-9011-e38180310618@s8g2000prg.googlegroups.com> On Mar 27, 10:53 am, Skip Montanaro wrote: > Is subprocess.Popen completely broken? Your lack of faith in Python is somewhat disturbing ... From jzgoda at o2.usun.pl Tue Mar 18 16:18:33 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 18 Mar 2008 21:18:33 +0100 Subject: Get actual call signature? In-Reply-To: References: Message-ID: castironpi at gmail.com pisze: > On Mar 18, 5:40 am, Jarek Zgoda wrote: >> Say, I have a function defined as: >> >> def fun(arg_one, arg_two='x', arg_three=None): >> pass >> >> Is there any way to get actual arguments that will be effectively used >> when I call this function in various ways, like: >> >> fun(5) => [5, 'x', None] >> fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] >> fun(5, 'something') => [5, 'something', None] >> >> (et caetera, using all possible mixes of positional, keyword and default >> arguments) >> >> I'd like to wrap function definition with a decorator that intercepts >> not only passed arguments, but also defaults that will be actually used >> in execution. >> >> If this sounds not feasible (or is simply impossible), I'll happily >> throw this idea and look for another one. ;) > > It evaluates to a substantial problem. The combinations include > things that Python disallows, such as double-spec. of keywords and > spec'n of keys w/out a dictionary arg; as well as double-spec'ing of > inspection. How do you want to access the parameters? What is the > least redundant way? P.S. Does there exist a possible authority who > doesn't want me to post this? Well, after some thinking and research I found this much more complicated than my first thoughts. However, I found that somebody already wrote some code to solve similar problem and even described what has to be done: http://wordaligned.org/articles/echo. Too bad for me, the most interesting part relies on features introduced with Python 2.5, while I am still on 2.4. Anyway, basics still works and fortunately I am in control in both function definitions and calls. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From kaushikbarat at gmail.com Sun Mar 2 01:47:02 2008 From: kaushikbarat at gmail.com (kaush) Date: Sat, 1 Mar 2008 22:47:02 -0800 (PST) Subject: mod_python Unable to create file Message-ID: Hi, I am using Apache and mod_python to service POST/GET requests on MAC OS. My script tries to create a file file = open(file_path, 'w') This fails with the following error EACCES Permission denied What is missing? Thanks, Kaushik From roman.dodin at softjoys.com Fri Mar 14 10:02:48 2008 From: roman.dodin at softjoys.com (Roman Dodin) Date: Fri, 14 Mar 2008 17:02:48 +0300 Subject: find string in file In-Reply-To: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> References: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> Message-ID: <47DA8588.6030800@softjoys.com> On 14 mar, 14:25, fminerv... at gmail.com wrote: >> Hi friends !! >> >> I'm neophite about python, my target is to create a programa that >> find a specific string in text file. >> How can do it? >> >> Thanks >> fel >> > > > One more way to do this f = codecs.open("log.txt", 'r', "utf_16_le") lines = f.readlines() for line in lines: if(line.find("my string to find")!=-1): print line From castironpi at gmail.com Sun Mar 9 17:40:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:40:28 -0700 (PDT) Subject: 1.5.2 and functools or similar References: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Message-ID: On Mar 9, 4:26?pm, "Troels Thomsen" wrote: > Hello, > > I am writing a simple delayed-call mechanism , that is causing a bit of > headache. Works like this: > > myPrint(s) > ? print "..." + s > > myTimer.add(myPrint , "hello" , 15) > > This means that the myprint function is called in 15 seconds with the > parameter "hello". > The housekeeping of these timers is called by the main loop of the "os" > > This works well but i would like to be able to use it with any number of > parameters > > Functools is not a part of the 1.5.2+ python that I am running on (embedded > device), > so i tried to pass the parameters as a tuple like this > > myTimer.add(myAdder , (3,6) , 15) > > and the housekeeping function would then call the function like this > > def updateTimers() > ? for timerItm in timerTable: > ? ... > ? ? .... > ? ? ? .... > ? ? ? ? timerItm.func(*timerItm.parameters) > > Works well on python 2.5 but not on 1.5.2 (?) > > Current solution is to have default parameters None for the add function > > def add( func , timeout , param1 = None , param2 = None) > > And the update function then checks if parameters is specified > > def updateTimers() > ? for timerItm in timerTable: > ? ... > ? ? .... > ? ? ? .... > ? ? ? # ugly part : > ? ? ? if timerItm.param1 is not None and timerItm.param2 is not None: > ? ? ? ? timerItm.func(timerItm.param1, timerItm.param2) # two parameters > ? ? ? elif ...... > ? ? ? ? timerItm.func(timerItm.param1) # one parameter > ? ? ? else > ? ? ? ? timerItm.func() # no parameters > > This has the implication that I can not call a function with the parameter > None if I wanted to. > (not a huge problem) > > Right now it works quite well with up to two parameters, it covers 99% of > usage. If I need to call a function with more parameters, i can always write > a wrapper function for it. Wondering if anyone had some sugestions ? > > By the way, is it bad style to check for object identity instead of value > "None". > What aboutt integers ? if value is 0: .. > I guess it is implementation specific / could change in future versions ? > > Thx, > Troels def g( arg1, arg2 ): print( arg1, arg2 ) return arg1 def h( arg1 ): print( arg1 ) return arg1 def caller( fun, *args, **kwargs ): return fun( *args, **kwargs ) print( caller( g, 'abc', 'def' ) ) print( caller( h, 'abc' ) ) ''' abc def abc abc abc ''' From musiccomposition at gmail.com Sun Mar 9 23:05:36 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 9 Mar 2008 20:05:36 -0700 (PDT) Subject: execute References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: <7ef97850-6244-43c4-9ff8-f0955c61c348@u69g2000hse.googlegroups.com> On Mar 9, 4:22 pm, Gif wrote: > i'm trying to execute a file without replacing the current process, > but after searching the help file, documentations and the web, i can't > a way of doing that. > > os.exec*() will close the current program. Have a look at the subprocess module. > > ps: by executing i mean like typing "mspaint" in run dialog.. it's not > a python file From deevine-removethis-spam at gmail.com Fri Mar 28 10:01:55 2008 From: deevine-removethis-spam at gmail.com (Jason Kristoff) Date: Fri, 28 Mar 2008 10:01:55 -0400 Subject: How do I reconnect a disconnected socket? Message-ID: I'm trying to make something that once it is disconnected will automatically try to reconnect. I'll add some more features in later so it doesn't hammer the server but right now I just want to keep it simple and get that part working. The problem is that when I use sock.close I get an error message of Bad File Descriptor and if I either use shutdown or just go straight to reconnecting I get: Transport endpoint is already connected This is what I've got right now: #! /usr/bin/env python import socket, string sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def doconn(): sock.connect(("localhost", 1234)) def dodiscon(): sock.close() doconn() doconn() while (1): buffer = sock.recv(1024) if not buffer: dodiscon() From mgedmin at gmail.com Tue Mar 18 14:05:29 2008 From: mgedmin at gmail.com (Marius Gedminas) Date: Tue, 18 Mar 2008 11:05:29 -0700 (PDT) Subject: Python Generators References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: <57b42684-2e4d-4e57-83f6-6d2ed011e485@i29g2000prf.googlegroups.com> On Mar 16, 9:24?am, Matt Nordhoff wrote: > mpc wrote: > > def concatenate(sequences): > > ? ? for seq in sequences: > > ? ? ? ? for item in seq: > > ? ? ? ? ? ? yield item > > You should check out itertools.chain(). It does this. You call it like > "chain(seq1, seq2, ...)" instead of "chain(sequences)" though, which may > be a problem for you. Solved rather easily by chain(*sequences): >>> from itertools import chain >>> def concat(sequences): ... return chain(*sequences) ... >>> concat([[1,2], [3, 4], [5], [6, 7, 8]]) >>> list(concat([[1,2], [3, 4], [5], [6, 7, 8]])) [1, 2, 3, 4, 5, 6, 7, 8] wondering if google groups will add a .sig or not-ly, Marius Gedminas From http Sun Mar 2 10:02:29 2008 From: http (Paul Rubin) Date: 02 Mar 2008 07:02:29 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> Message-ID: <7xprud88ze.fsf@ruckus.brouhaha.com> Lie writes: > That's quite complex and restrictive, but probably it's because my > mind is not tuned to Haskell yet. That aspect is pretty straightforward, other parts like only being able to do i/o in functions having a special type are much more confusing. > Anyway, I don't think Python should > work that way, because Python have a plan for numerical integration > which would unify all numerical types into an apparent single type, > which requires removal of operator's limitations. Well I think the idea is to have a hierarchy of nested numeric types, not a single type. > from __future import division > a = 10 > b = 5 > c = a / b > if c * b == a: print 'multiplication is inverse of division' Try with a=7, b=25 From ebgssth at gmail.com Mon Mar 10 19:31:07 2008 From: ebgssth at gmail.com (js) Date: Tue, 11 Mar 2008 08:31:07 +0900 Subject: TextWrapper keepking line breaks? Message-ID: Hi list, Can I make TextWrapper keep line breaks in the text? For example, >>> s = "spam\nham" >>> print wrap(s) spam ham As far as I can tell, there seems no way to do this, but before writing my own solution, I want to know whether the solution already exists or not. Thanks. From kay.schluehr at gmx.net Mon Mar 17 02:36:35 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 16 Mar 2008 23:36:35 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <3a2e4490-f4e9-4edf-ae35-0aa3c90103f7@i7g2000prf.googlegroups.com> Message-ID: On 16 Mrz., 21:52, Bruce Eckel wrote: > On Mar 16, 2:48 pm, Pete Forde wrote: > > > My friends and I decided to stage a grassroots Ruby conference this > > summer; it will have no paid sponsors for exactly this reason. We're > > trying to change up the typical format as well: it's a single-track > > event, no "keynotes", no schills for well-heeled interests. We're even > > organizing activities for significant others traveling with conference > > attendees so that everyone has a good time. > > > The response we've gotten to this approach has been curious; many > > people totally get why these things are important, and the speaker > > list reflects this. However, we've also had a lot of complaints that > > our event is too expensive. In fact, they say that it should be free, > > like a BarCamp. Just get a bunch of sponsors, and that will be the > > ticket. We say bollocks to that. > > >http://rubyfringe.com/ > > I've been running open spaces conferences for the past few years and I > would suggest you do that instead of an "eyes-forward" conference. > It's not only a lot easier, but it's also a lot more fun. For example, > last week we did the Java Posse Roundup, which is all open-spaces. Since the rubyfringe seems to make also a commitment against the Ruby mainstream I'm not sure how Open Spaces can help? Self organization is always an aid for those who are already strong, maintain popular projects ( Rails, Django... anyone? ) and keep lots of attention. I certainly wouldn't attend to an Open Space conference if I intended to make my development and findings public. From rune.strand at gmail.com Fri Mar 14 17:21:37 2008 From: rune.strand at gmail.com (Rune Strand) Date: Fri, 14 Mar 2008 14:21:37 -0700 (PDT) Subject: Ping and ARP on both Win and Linux in Python References: Message-ID: <70f1300f-cdd3-4c92-ad8d-ffdda7aaa139@e25g2000prg.googlegroups.com> On Mar 13, 9:14 pm, "Mauro \"Baba\" Mascia" wrote: > Hi, this is my question: > > I want to know if several switch (about 50) in a big lan are up and then > know their MAC addresses to do a list that contains host name, ip and mac. > I know only the range of their IP addresses (the host name it's simply > to know using socket.gethostn. > > The first idea it's to ping all ip, parse the response and then execute > the command "arp -a" and parse the response. > However this way depends on the operating system and the ping response > depends too from the language. > > Another way it's to open the main page of the switch and parse the HTML > code where i can find the MAC address. > However this way depends on the particular brand's switch. > > I know (or better i think) that there is a third way: make ping and arp > building the packets with socket and so on (but i dont have understand > in what way do this). > > Any suggestion? > > (i've already search in google, found many sources but a lot of them > don't works or don't do what im trying to do...) > > Regards, > Mauretto. There are several Ping /ICMP implentations in Python. I did something similar using a python ping module and parsing the arp cache. A different approach may be to use SNMP. I believe there are Python tools around. From arkanes at gmail.com Tue Mar 18 13:47:26 2008 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 18 Mar 2008 12:47:26 -0500 Subject: Fast 2D Raster Rendering with GUI In-Reply-To: References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Message-ID: <4866bea60803181047m7649d357nfaf91f5146bcbc52@mail.gmail.com> On Tue, Mar 18, 2008 at 12:30 PM, sturlamolden wrote: > On 18 Mar, 17:48, Miki wrote: > > > Apart from PIL, some other options are: > > 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object > > you can draw on > > Yes, but at least on Windows you will get a GDI canvas. GDI is slow. Of all the major platforms, GDI is probably the fastest for basic pixel-level interaction with the screen. I have no idea why you think it's slow. > > > > > 2. A bit of an overkill, but you can use PyOpenGL > > OpenGL gives you a fast 'bitblit' for drawing bitmaps to the fram > buffer (much faster than GDI). Here is some C code that does that (8- > bit color depth). Translating to Python is trivial. I prefer not to > use PyOpenGL as it has some unwanted overhead. It is better to use > ctypes. > > > void bitblt(void *frame, int w, int h) > { > glViewport(0,0,w,h); > glClearColor(0.0, 0.0, 0.0, 0.0); > glClear(GL_COLOR_BUFFER_BIT); > glMatrixMode(GL_PROJECTION); > glLoadIdentity(); > gluOrtho2D(0.0, (GLfloat)w, 0.0, (GLfloat)h); > glMatrixMode(GL_MODELVIEW); > glLoadIdentity(); > glRasterPos2i(0,0); > glPixelStorei(GL_UNPACK_ALIGNMENT, 1); > glDrawPixels(w, h, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, (GLvoid *)frame); > glFlush(); > > > } > OpenGL is totally unsuitable if the goal is to implement your own pixel-level raster drawing. From gagsl-py2 at yahoo.com.ar Wed Mar 26 19:07:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 20:07:33 -0300 Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> <47EA99EE.5030304@tim.thechases.com> <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> Message-ID: En Wed, 26 Mar 2008 16:14:07 -0300, David Anderson escribi?: > The right question was:HOw can we use/express pointers python as in C or > Pascal? I think you should read this article: http://effbot.org/zone/python-objects.htm and then: http://effbot.org/zone/call-by-object.htm -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Mar 26 09:32:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 26 Mar 2008 06:32:03 -0700 (PDT) Subject: memory allocation for Python list References: <83317728-733c-4b9b-a68c-24d2221a4c3e@i7g2000prf.googlegroups.com> Message-ID: <96e81eb0-9d27-4cfd-82da-7fcc9b3dae25@m3g2000hsc.googlegroups.com> dmitrey: > As I have mentioned, I don't know final length of the list, but > usually I know a good approximation, for example 400. There is no reserve()-like method, but this is a fast enough operation you can do at the beginning: l = [None] * 400 It may speed up your code, but the final resizing may kill your performance anyway. You can try it. Just using Psyco is probably better. Bye, bearophile From deets at nospam.web.de Mon Mar 17 11:23:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 17 Mar 2008 16:23:12 +0100 Subject: Missing PyObject definition References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: <647gn4F2aphcqU1@mid.uni-berlin.de> James Whetstone wrote: > I'm trying to access a PyObject directly from C++ for the purpose of > calling method on a Python object that is an intance of a derived C++ > class. My problem is that the compiler is complaining about not PyObject > not being > defined. Has anyone run into the problem? Where is PyObject defined? This is a problem-description pretty far on the vague side, so the answer can be as vague only: in Python.h, which should be part of your python-installation. Better answers can be provided when you give more information - platform, python-version, source-code, tracebacks... Diez From mnordhoff at mattnordhoff.com Thu Mar 20 17:09:09 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 20 Mar 2008 21:09:09 +0000 Subject: Problem with PARAGRAPH SEPARATOR In-Reply-To: <8D5970DD46B50A409A0E42BA407964FE0E6DF433@SGBD012007.dlrmail.ad.delarue.com> References: <8D5970DD46B50A409A0E42BA407964FE0E6DF433@SGBD012007.dlrmail.ad.delarue.com> Message-ID: <47E2D275.2020209@mattnordhoff.com> Dominique.Holzwarth at ch.delarue.com wrote: > Actually that's what I tried to do, for example: > outputString = myString.encode('iso-8859-1','ignore') > > However, I always get such messages (the character, that's causing problems varies, but its always higher than 127 ofc...) > > 'ascii' codec can't decode byte 0xc3 in position 51: ordinal not in range(128) > > It doesn't matter what encoding I use (tried 'utf-8' 'utf-16' 'latin_1' and the iso one). The debugger is showing all the special characters (from french and german language) so I'm wondering why there's still the message about the 'ascii' codec... > > Would that mean that the string "myString" is an ascii-string or what? That's a *decode* error. If myString is a str object, it has to be *decoded* before it can be *encoded* to ISO-8859-1 or whatever you want, and it's defaulting to ASCII. This page may help: -- From jameswhetstone at comcast.net Mon Mar 17 11:12:22 2008 From: jameswhetstone at comcast.net (James Whetstone) Date: Mon, 17 Mar 2008 08:12:22 -0700 Subject: Missing PyObject definition Message-ID: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> I'm trying to access a PyObject directly from C++ for the purpose of calling method on a Python object that is an intance of a derived C++ class. My problem is that the compiler is complaining about not PyObject not being defined. Has anyone run into the problem? Where is PyObject defined? Thanks! James From rranshous at gmail.com Thu Mar 13 16:39:41 2008 From: rranshous at gmail.com (_robby) Date: Thu, 13 Mar 2008 13:39:41 -0700 (PDT) Subject: Update pytz timezone definitions Message-ID: I am looking at using pytz in a scheduling application which will be used internationally. I would like to be able to update the definition files that pytz uses monthly or bi-monthly. As far as I can tell, pytz seems to be updated (fairly) regularly to the newest tzdata, but I don't want to have to update my pytz, just it's definitions. http://www.twinsun.com/tz/tz-link.htm says that pytz "compiles tz source into Python." Does this mean that there is already a method for updating the definitions? Any help would be greatly appreciated, even if it is to point out something obvious which I over looked. - Robby From roger.dahlstrom at gmail.com Mon Mar 31 14:13:48 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 31 Mar 2008 11:13:48 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: On Mar 31, 12:53 pm, "mimi.vx" wrote: > On Mar 31, 4:22 pm, rdahlstrom wrote: > > > > > So I have a 64 bit Windows 2003 system, running python 2.5.1.1. > > > I can import a Windows .dll (msvcrt or whatever) using ctypes, but > > when attempting to import another application-specific .dll (tibrv.dll > > if anyone is familiar with it), I receive the error WindowsError: > > [Error 193] %1 is not a valid Win32 application. > > > I know there's a Windows on Windows (wow) which allows 32 bit > > processes to run on 64 bit windows - is there a way to work this in > > somehow? Maybe I'm barking up the wrong tree? > > > Code is simple, and works on 32 bit systems no > > > from ctypes import * > > #this doesn't work > > tibrv = cdll.tibrv > > #this does work > > msvcrt = cdll.msvcrt > > all dlls and python must be 32bit or 64bit, no mixed ... Crap, no way to make a 32 bit load, even using the wowexec? From Lie.1296 at gmail.com Tue Mar 11 12:31:09 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 09:31:09 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> <2b098afa-2dcc-4bde-bdde-02eece46fd68@47g2000hsb.googlegroups.com> Message-ID: <817b79d0-d451-4696-ab73-1289a380136c@d4g2000prg.googlegroups.com> On Mar 10, 4:16?am, castiro... at gmail.com wrote: > On Mar 9, 4:25?am, Lie wrote: > > > On Mar 9, 3:27?am, castiro... at gmail.com wrote: > > > > To Lie: > > > > > Personally I preferred a code that has chosen good names but have > > > > little or no comments compared to codes that makes bad names and have > > > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > > > I won't like it, it's that I can't. ?You know, in linguistics, there's > > > But I much prefer it that the code has good names AND concise > > comments, not too short and not too long that it becomes obscure. > > What do you mean? ?If 'obscure' is the right word, then it's > subjective (from metrics import obscurity?), which means that 10% of > the people disagree with you, or 90% do. ?The end-all be-all, there is > no such thing. ?I don't think it's obscure; I do. ?Is it? No, there is a point where everyone would say obscure. Such as a simple two integer addition function that have thirty pages of documentation and that have names like: def dosomereallyfunkythings(argumentoneissomethingadded, argumentbisaddinga): """ blah blah blah blah ... 30 or so pages later... ... Ok, that is the end of it, it's a complex function actually """ return argumentoneissomethingadded + argumentbisaddinga (remember you don't have access to source code, so you have to decipher the documentation for what the function is about) I prefer to see something like this: def add(a, b): return a + b Even without documentation I'd know immediately what it does from the name (add) From noone at nowhere.com Fri Mar 7 00:12:30 2008 From: noone at nowhere.com (pythonNEWB) Date: Thu, 06 Mar 2008 23:12:30 -0600 Subject: jython jmx tutorials? Message-ID: I am looking to try to build a simple, generic tool for basic monitoring and gathering of config information from java app servers such as weblogic (I know WLST is there, but I want the exercise and for it to work with more than just weblogic), tomcat and jboss using jython and jmx. Can anyone recommend any docs or sites that might have any useful info on those topics that might help me get started? I have been using python for a year or two now, but my java skills are pretty beginner... TIA. From michael.wieher at gmail.com Mon Mar 17 17:14:54 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 16:14:54 -0500 Subject: Apache binary error? In-Reply-To: References: Message-ID: yes that was already there, but it kept giving me that every-other problem i know its the fact the web-browser wasn't passed the "content-type=..." on the alternate reloads but as to why im lost in the end i figure its best to just ignore this and move to the more beta-test dev stage which involves django, so hopefully that'll just erase this weird error and i know the script worked (ie: the content should be being piped to the page) because the 2nd refresh (or first, alternately) would provide me with the expected result (ie: a web page) thanks tho =) 2008/3/17, Graham Dumpleton : > > On Mar 18, 4:43 am, Sean Allen wrote: > > On Mar 17, 2008, at 10:55 AM, Michael Wieher wrote: > > > > > have simple webpage running > > > > > apache,mod_python > > > > > the error is binary.... > > > ...binary as in "every other" time I load the page, Firefox keeps > > > telling me I'm downloading a python script, and asks to open it in > > > WINE, which is really strange. > > > > > then, alternately, it loads the page just fine. any clues as to why > > > this is happening? > > > -- > > > > for anything like mod_perl,mod_pythonetc the first thing i do when i > > get really weird errors > > it move to having only one apache process for testing. > > > > might want to start there. > > In mod_python handler code: > > req.content_type = 'text/plain' > > or otherwise. > > If you don't indicate what the response content type is web browsers > will often try and work it out based on the extension in the URL. > > This is presuming you configured Apache correctly and your code is > actually being executed and you aren't just serving up your code > instead. > > Graham > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gigs at hi.t-com.hr Wed Mar 5 08:39:19 2008 From: gigs at hi.t-com.hr (gigs) Date: Wed, 05 Mar 2008 14:39:19 +0100 Subject: hidden built-in module In-Reply-To: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> Message-ID: koara wrote: > Hello, is there a way to access a module that is hidden because > another module (of the same name) is found first? > > More specifically, i have my own logging.py module, and inside this > module, depending on how initialization goes, i may want to do 'from > logging import *' from the built-in logging. > > I hope my description was clear, cheers. > > I am using python2.4. you can add your own logging module in extra directory that have __init__.py and import it like: from extradirectory.logging import * and builtin: from logging import * From fuzzyman at gmail.com Sun Mar 16 10:59:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 16 Mar 2008 07:59:38 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 11:10 am, Bruce Eckel wrote: [snip..] > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Vendors were guaranteed first pick on lightning talk slots, and > we in the audience, expectantly looking forward to interesting and > entertaining content, again started to feel like things were awfully > commercial. And what seemed like a good idea, moving lightning talks > into plenary sessions with no competition, began to look like another > way to deliver a captive audience to vendors. > coming. I have a conflict of interests - coming to PyCon from a sponsor company and having given a lightning talk. But I *kind* of agree with you. Most of the sponsor lightning talks were pretty dull. I *hope* mine was one of the exceptions. (Resolver One demo.) ;-) This isn't new though. Last year (my only other PyCon) all the sponsors gave lightning talks. The difference is that there were more sponsors this year I guess... Personally I think 'sponsor keynotes' was a mistake. Not a huge mistake, but nonetheless... Michael Foord Resolver Systems From http Tue Mar 18 01:32:20 2008 From: http (Paul Rubin) Date: 17 Mar 2008 22:32:20 -0700 Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> Message-ID: <7xod9cvbq3.fsf@ruckus.brouhaha.com> Larry writes: > It seems to me that Python always add intervening spaces between data > elements when writing to a file It's just the print statement that does that. From davids at evertech.com.au Fri Mar 14 00:37:12 2008 From: davids at evertech.com.au (David S) Date: Fri, 14 Mar 2008 04:37:12 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: Hi, I get ERROR: ""C:\Program Files\apache-ant-1.7.0\bin\ant"" does not exist If I cut the path statement here and paste it next to a windows XP command prompt ant is invoked. The python code here is if not os.path.isfile(ANT_CMD): error('"%s" does not exist' % ANT_CMD) David "Mensanator" wrote in message news:360a8612-f5a2-4f2f-bae2-c89ed35b7d1b at n77g2000hse.googlegroups.com... On Mar 13, 5:16 pm, "David S" wrote: > Hi, > > I have some code in which I have to change some path names to get it to > work. The original code seems to have assumed that path names would not > have > any embedded spaces. > > I am not sure how to write the following line so when used in my script > the > path will be found. > > ANT_CMD = r'C:\Program Files\apache-ant-1.7.0\bin\ant' Try ANT_CMD = r'"C:\Program Files\apache-ant-1.7.0\bin\ant"' > > Regards, > David From grante at visi.com Sun Mar 9 00:23:27 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:23:27 -0000 Subject: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> <63h1j2F27rdfoU1@mid.individual.net> Message-ID: <13t6t2feje9gvd2@corp.supernews.com> On 2008-03-09, K Viltersten wrote: >>> /** Projects an object from 3D to 2D using >>> the method of Alexander The Great. >>> \param 3D structure to be projected >>> \returns 2D projection >>> */ >>> public Proj2D get2Dfrom3D(Proj3D param); >>> >>> The above is, to me, very clear and >>> consistent. Not to mention, easily >>> handled with e.g. Doxygen to create a >>> readable documentation. >>> >>> I don't see how this is dislikeable. Please >>> explain. >> >> When get2Dfrom3D changes its signature but >> the comment is not changed. That's where I >> have a problem, and it's only a matter of >> time before it happens. > > I think we've arrived at the spot where i'll > claim that a _always_ update my comments, Perhaps you do. AFAICT, nobody else does. :) -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From stuff at greenery.me.uk Mon Mar 17 08:03:08 2008 From: stuff at greenery.me.uk (Thomas G) Date: Mon, 17 Mar 2008 12:03:08 GMT Subject: wxPython graphics query (newbie) Message-ID: I am exploring wxPython and would be grateful for some help. It is important to me to be able to slide words and shapes around by dragging them from place to place. I don't mean dragging them into a different window, which is what 'Drag and Drop' has come to mean, just moving them around within a canvas-like space. This is easy using Tkinter. Can anybody offer me a tiny, very simple example of how it would be done in wxPython, please? To make sure I convey what I'm looking for, here is what it looks like using Tkinter, written very simply. What I'm looking for is the same, quite simple functionality expressed in wxPython, again written very simply so that I can easily understand it. #!/usr/bin/python from Tkinter import * root = Tk() global canv def makeFrame(root): global canv canv = Canvas (root, height = 200, width = 350) canv.create_text(100, 100, text='drag me', tags=('movable')) canv.tag_bind('movable', '', slide) #B1-motion is a drag with left button down canv.pack() def slide (event): ''' triggered when something is dragged on the canvas - move thing under mouse ('current') to new position ''' newx = event.x newy = event.y canv.coords('current', newx, newy) makeFrame(root) root.mainloop() Many thanks in advance -- Thomas Green From gagsl-py2 at yahoo.com.ar Fri Mar 21 14:08:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 11:08:45 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> Message-ID: <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> On 21 mar, 10:14, castiro... at gmail.com wrote: > On Mar 20, 9:28?am, "Jerry Hill" wrote: > > A more general > > solution might use a generator expression, like this: > > newsz = tuple(x/scale for x in origsz) > > You want to perform a uniform call on the elements of a collection. > "Diagram A" appends 0 to every item of a list. > > >>> y= [ [] for k in range( 10 ) ] > >>> def x( fun, *ar, **kw ): > > ... ? ? def post( *xr, **xw ): > ... ? ? ? ? ? ? return fun( *(xr+ ar), **kw ) > ... ? ? return post > ...>>> x( list.append, 0 )( y[0] ) Sane programmers replace that crazyness with this code: for x in collection: x.append(0) > >>> y= ( 300, 400 ) > >>> tuple( map( x( int.__add__, 1, ), y ) ) > > (301, 401) Sane programmers replace that crazyness with this code: tuple(x+1 for x in y) > Floats get harder, since you're looking at composition. > > >>> tuple( map( compose( float, x( float.__mul__, 1/ 2.5 ) ), y ) ) > > (120.0, 160.0) # (160, 120) Sane programmers -like D'Aprano, Jerry Hill and me- replace that crazyness with this code: tuple(x/2.5 for x in y) > def compose( *f ): > ? ? def post( *ar, **kw ): > ? ? ? ? ? ? if len( f )> 1: > ? ? ? ? ? ? ? ? ? ? return f[0]( compose( *f[1:] )( *ar, **kw ) ) > ? ? ? ? ? ? return f[0]( *ar, **kw ) > ? ? return post Sane programmers don't write such semi-functional things (unless it helps expressing the problem in certain domains). I now think that deprecating map, lambda & Co. was a good thing after all. -- Gabriel Genellina From george.sakkis at gmail.com Sun Mar 30 10:23:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 30 Mar 2008 07:23:10 -0700 (PDT) Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote: > Steven D'Aprano wrote: > > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > > >> Second try: > > ... > >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with > >> each call. But it's the only way I could find, at least without changing > >> the code template used by timeit. > > > Eeek. Talk about namespace pollution. > > > Thanks for the effort, but if that's the only solution, I think the > > solution is worse than the problem! > > > Perhaps it's time for me to take a different approach. > > [snip] > > Maybe the following enhancement of timeit would be worthwhile? [snip] That would be great. I sometimes avoid timeit altogether because setting up the environment is so cumbersome. Can you post the patch to bugs.python.org so it doesn't get lost ? George From sadreti at gmail.com Sun Mar 9 08:03:12 2008 From: sadreti at gmail.com (sadreti at gmail.com) Date: Sun, 9 Mar 2008 05:03:12 -0700 (PDT) Subject: The intel processor reach the very high place... Message-ID: <19211ed6-26ff-436b-88da-e93128a4fe62@s19g2000prg.googlegroups.com> The intel processor reach the very high place... http://intelsprocessor.googlepages.com From gherron at islandtraining.com Mon Mar 10 10:39:25 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 10 Mar 2008 07:39:25 -0700 Subject: is operator In-Reply-To: <004801c881f2$a04081f0$0b020b0a@nb1011> References: <004801c881f2$a04081f0$0b020b0a@nb1011> Message-ID: <47D5481D.4000004@islandtraining.com> Metal Zong wrote: > > The operator is and is not test for object identity: x is y is true if > and only if x and y are the same objects. > > > > >>> x = 1 > > >>> y = 1 > > >>> x is y > > True > > > > Is this right? Why? Thanks. > > > Yes that is true, but it's an implementation defined optimization and could be applied to *any* immutable type. For larger ints, such a thing is not true. >>> x=1000 >>> y=1000 >>> x is y False If either is a surprise, then understand that the "is" operator should probably *never* be used with immutable types. Gary Herron From aahz at pythoncraft.com Fri Mar 7 16:31:14 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Mar 2008 13:31:14 -0800 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <13t3c5t4hau9075@corp.supernews.com> <13t3cfpo6d8d2ab@corp.supernews.com> Message-ID: In article <13t3cfpo6d8d2ab at corp.supernews.com>, Grant Edwards wrote: > >My thumb has been putting two spaces after a period for 30 >years, so the chances that it's going to change are rather >slim. :) +1 QOTW -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From duncan.booth at invalid.invalid Mon Mar 17 06:40:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 10:40:43 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > Which is exactly what happens - the actual implementation chose to cache > some values based on heuristics or common sense - but no guarantees are > made in either way. Here's a puzzle for those who think they know Python: Given that I masked out part of the input, which version(s) of Python might give the following output, and what might I have replaced by asterisks? >>> a = 1 >>> b = 5-4 >>> if a is b: print 'yes!' ... yes! >>> b = **** >>> if a is b: print 'yes!' ... >>> b 1 >>> type(b) From dkuhlman at rexx.com Thu Mar 13 19:29:11 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 13 Mar 2008 16:29:11 -0700 Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> Message-ID: <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Arnaud Delobelle wrote: > > 4. Both points above follow from the fact that foo.bar is really a > function call that returns a (potentially) new object: in fact what > really happens is something like Arnaud and Imri, too - No. foo.bar is *not* really a function/method call. > > Foo.__dict__['bar'].__get__(foo, Foo). > > So every time foo.bar is executed an object is (or may be) created, > with a new id. > > HTH I appreciate the help, but ... Actually, it does not help, because ... My understanding is that foo.bar does *not* create a new object. All it does is return the value of the bar attribute of object foo. What new object is being created? If I have: class Foo(object): def bar(self): pass And I do: foo = SomeClass() then: foo.bar should return the same (identical) object everytime, no? yes? I'm still confused. - Dave > > -- > Arnaud -- Dave Kuhlman http://www.rexx.com/~dkuhlman From PeterBraden1 at googlemail.com Sat Mar 8 14:29:11 2008 From: PeterBraden1 at googlemail.com (PB) Date: Sat, 8 Mar 2008 11:29:11 -0800 (PST) Subject: Image Libraries Message-ID: <457a205f-4c44-489a-9f71-253d76d31482@e31g2000hse.googlegroups.com> I have been using PIL for generating images, however it does not easily support operations with transparency etc. I tried to install aggdraw but it wouldn't compile. Ideally I'd like something open source so I can adapt it, hopefully mostly written in python rather than C. Is there any other decent image libraries for python? From http Thu Mar 13 22:02:24 2008 From: http (Paul Rubin) Date: 13 Mar 2008 19:02:24 -0700 Subject: How do I iterate over items in a dict grouped by N number of elements? References: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> Message-ID: <7xiqzq6p1r.fsf@ruckus.brouhaha.com> Noah writes: > What is the fastest way to select N items at a time from a dictionary? > I'm iterating over a dictionary of many thousands of items. > I want to operate on only 100 items at a time. > I want to avoid copying items using any sort of slicing. I'd do something like (untested): def groups(seq, n): while True: s = list(itertools.islice(seq, n)) if not s: return yield s items = d.iteritems() for g in groups(items, 100): operate_on (g) > Does itertools copy items? I don't understand this question. From paddy3118 at googlemail.com Mon Mar 10 01:59:45 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 9 Mar 2008 22:59:45 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: Message-ID: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> On Mar 9, 11:41 pm, Roopan wrote: > Hello! > > I am looking at developing an enterprise-grade distributed data > sharing application - key requirements are productivity and platform > portability. > > Will it be sensible to use C++ for performance-critical sections and > Python for all the glue logic. > > Pls comment from your *experiences* how Python scales to large > projects( > 200KLOC). > I assume the C++/Python binding is fairly painless. > > Regards > Elam. You might try prototyping as much as possible in Python as soon as possible. Then, and only after getting something that computes the right results, profile your prototype to see where the real bottlenecks are. Sometimes it it is not evident at the beginning where the bottlenecks in the prototype will be. If you write most of the prototype in Python then you will write less lines of code, in a shorter time and so should be more inclined to experiment with different algorithms, and do more testing. (Doctest can be great). After profiling their may be other ways to remove a bottleneck, such as using existing highly-optimised libraries such as Numpy; Psycho, an optimising interpreter that can approach C type speeds for Python code; and you could create your own C++ based libraries. You might want to ask the Mercurial development team how they got their impressive speed and functionality out of using mainly Python with critical regions in C. - Or watch this: http://video.google.com/videoplay?docid=-7724296011317502612 - Paddy. From gert.cuykens at gmail.com Wed Mar 5 19:47:37 2008 From: gert.cuykens at gmail.com (gert) Date: Wed, 5 Mar 2008 16:47:37 -0800 (PST) Subject: http://httpd.apache.org/docs/2.2/mod/mod_dbd.html Message-ID: Would anybody explain to me what needs to be done to have a DB-API 2.0 layer for this ? And how many lines of code we are talking ? http://httpd.apache.org/docs/2.2/mod/mod_dbd.html From vvangelovski at gmail.com Mon Mar 24 10:04:41 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Mon, 24 Mar 2008 07:04:41 -0700 (PDT) Subject: URL encoding Message-ID: <9693ffda-1454-4d56-acee-1e6fc4ebeccb@h11g2000prf.googlegroups.com> Is there any method in the standard modules that can perform proper url encoding according to RFC? From hajducko at gmail.com Thu Mar 27 00:50:56 2008 From: hajducko at gmail.com (hajducko at gmail.com) Date: Wed, 26 Mar 2008 21:50:56 -0700 (PDT) Subject: Plugin framework - Overcomplicating things? Message-ID: <12d7b774-7aa5-49b8-a43c-3bc6e29bac0d@d4g2000prg.googlegroups.com> As a side project and a learning experience and ultimately, a good tool for my department, I started developing a simple jabber bot for our work's conference server, with the intention of making it capable of running specific commands and utilities. I realize there are other bots out there, but I thought this would be a good first python project for me. Most of my current scripts/utilities are in perl or php, so the OO world is a little new. In any case, I wrote up a Bot class, got it to connect, join rooms, see chat, and the world rejoiced. Now, instead of writing a monolithic function for the message handler to deal with all the incoming text and all the possible cool things I could do with the bot like intranet lookups, dns checks, etc, I thought to myself: "self, wouldn't it be cool if you made a plugin framework that could read in a bunch of plugins and the bot could hand off the text to a plugin that was looking for that command and it could do the job". Then the smarter side of myself said "self, you have no frak'n idea how to do that". So I've been scouring this list for days, reading some of the past conversations. I investigated the trac component system, downloaded the source and tried my best to make heads ( or tails, take your pick ) of it. I looked at setuptools and eggs, I looked at Marty's simple framework at http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/ and I searched all over google for anything, even stuff that was non- python specific and just detailed plugin frameworks in theory ( I didn't find any good ones, so if you have some links, gimme. :) ) and I'm sorry say, but I still don't get it. While I understand half of it, I'm still not getting the point of using it for something like what I'm trying to accomplish. All this comes to my question - am I overcomplicating this project? I can understand the use of something like the trac component system if I had multiple components and plugins that handled different areas of my project and different points of interaction, but I don't. I've got exactly one spot where I want to check all my plugins and hand off the message to which ever ones are looking for that command. So really, should I even bother with trying to setup some framework for this or should I just be doing a simple loop over a directory, importing all the plugins and storing them in a list and then looping over them in the message handler to see which ones were looking for the command and letting them do their thing? I don't see the advantage I'd get from implementing something more complicated at this point. If you could show me the yellow brick road or offer any pointers, I'd appreciate it. I'm more than willing to go off reading more pages, but when the first 5 pages of a google search for 'plugin framework design' shows all purple, visited links and I'm still not getting it, I finally decided to turn here to the list and get some professional advice. As an aside, if there is anyone who is an experience developer and designer and is willing to take some private correspondence, please let me know. I feel embarrassed for asking, but I've got a alot of questions that I don't want to litter this list with and would rather voice them in private. Thanks, steve From grante at visi.com Tue Mar 4 15:46:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 04 Mar 2008 20:46:14 -0000 Subject: Python an Exchange Server References: Message-ID: <13srd8micnh7g35@corp.supernews.com> On 2008-03-04, Tim Chase wrote: > Exchange offers other proprietary functionality, exposed > through the MAPI. You might be able to use some of the Win32 > functionality in one of the add-on modules for talking with > COM objects. I spent a while looking into this a few years ago, and there was no way to use MAPI other than via the COM interface to Outlook. There are examples of using Outlook via its COM interface floating around somewhere. -- Grant Edwards grante Yow! Go on, EMOTE! at I was RAISED on thought visi.com balloons!! From mwilson at the-wire.com Thu Mar 13 20:18:31 2008 From: mwilson at the-wire.com (Mel) Date: Thu, 13 Mar 2008 20:18:31 -0400 Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> My understanding is that foo.bar does *not* create a new object. > > Your understanding is not correct. > >> All it >> does is return the value of the bar attribute of object foo. What new >> object is being created? > > A bound method. This happens through the descriptor-protocol. Please see > this example: > > > class Foo(object): > def bar(self): > pass > > > f = Foo() > a = Foo.bar > b = f.bar > c = f.bar > > print a, b, c > print id(b), id(c) (What Diez said.) From what I've seen, f.bar creates a bound method object by taking the unbound method Foo.bar and binding its first parameter with f. This is a run-time operation because it's easy to re-assign some other function to the name Foo.bar, and if you do, the behaviour of f.bar() will change accordingly. You can get some very useful effects from these kinds of games. You can make f into a file-like object, for example, with import sys f.write = sys.stdout.write Here, f.write *is* a straight attribute of f, although it's a built-in method of the file class. It's still bound, in a way, to sys.stdout. I'm assuming that a different example could create an attribute of f that's a bound method of some other object entirely. I've verified that f.write('howdy') prints 'howdy' on standard output. Mel. From miki.tebeka at gmail.com Tue Mar 25 20:36:03 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 25 Mar 2008 17:36:03 -0700 (PDT) Subject: what are generators? References: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> Message-ID: On Mar 24, 8:17?am, castiro... at gmail.com wrote: > I'm looking for a cool trick using generators. ?Know any exercises I > can work? Simple one the comes to mind is flattening a list: >>> list(flatten([1, [[2], 3], [[[4]]]])) [1, 2, 3, 4] >>> HTH, -- Miki http://pythonwise.blogspot.com From ursneed.urs at gmail.com Thu Mar 13 03:57:12 2008 From: ursneed.urs at gmail.com (ursneed) Date: Thu, 13 Mar 2008 00:57:12 -0700 (PDT) Subject: need in deed.....!!! Message-ID: hi.... here the links are goes here..... http://ursneed.googlepages.com/home http://ursneed.googlepages.com/coolneeds http://ursneed.googlepages.com/funnimes http://ursneed.googlepages.com/secrets http://ursneed.googlepages.com/flashgames please do me comments... or revert back ur responce (request).... i am here do it for YOU.... ursneed From gh at ghaering.de Sat Mar 29 14:46:19 2008 From: gh at ghaering.de (=?ISO-8859-15?Q?Gerhard_H=E4ring?=) Date: Sat, 29 Mar 2008 19:46:19 +0100 Subject: How to insert multiple rows in SQLite Dbase In-Reply-To: References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> Message-ID: <657h3nF2eehi8U1@mid.uni-berlin.de> Gabriel Genellina wrote: > [...] > and execute: > cur.executemany("insert into log (IP, EntryDate, Requestt, ErrorCode) > values (:ip, :date, :request, :errorcode)", values) It's probably worth mentioning that pysqlite's executemany() accepts anything iterable for its parameter. So you don't need to build a list beforehand to enjoy the performance boost of executemany(). The deluxe version with generators could look like this: def parse_logfile(): logf = open(...) for line in logf: if ...: row = (value1, value2, value3) yield row logf.close() ... cur.executemany("insert into ... values (c1, c2, c3)", parse_logfile()) -- Gerhard PS: pysqlite internally has a statement cache since verson 2.2, so multiple execute() calls are almost as fast as executemany(). From tralalal at joepie.nl Wed Mar 19 05:00:32 2008 From: tralalal at joepie.nl (taco) Date: Wed, 19 Mar 2008 10:00:32 +0100 Subject: lock access to serial port References: Message-ID: kkadrese at gmail.com wrote: > hello group, > > how to get ttyS0 serial port for exclusive access? I have a python > script that uses this device with AT commands. I need that two > instances can call simultaneosuly this python script but only one of > them gets the device. I tried fcntl.flock, it was just ignored, put > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not > know what are appropriate arguments), googled half a day for various > phrases, error messages etc....without success. > > please help, > > Andra not sure if I understand you well, but how about a server application which accepts 2 clients which can send messages which are output on the serial device? The serial device access protected with a mutex while receiving messages done in 2 threads or something. taco From fairwinds at eastlink.ca Fri Mar 28 16:50:49 2008 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 28 Mar 2008 17:50:49 -0300 Subject: cProfile for python 2.4 Message-ID: <47ED5A29.6070906@eastlink.ca> I'd like to compile cProfile for python 2.4. Where can I get it to do this? I realize it is part of python 2.5. Many thanks. From castironpi at gmail.com Wed Mar 5 17:51:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 14:51:04 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: On Mar 5, 4:00?pm, Grant Edwards wrote: > On 2008-03-05, castiro... at gmail.com wrote: > > >>>>> I want to hash values to keys. ?How do the alternatives compare? > > >>>>http://catb.org/~esr/faqs/smart-questions.html > > >>> ... without extending the whole way to a full relational database? > > >> You didn't bother following the link and reading the advice, did you? If > >> you did, you haven't done a good job of following that advice. > > > Well, obviously there's someone who's interested in computers and > > programming that has a question. > > It may be ?obvious that he has a question. ?It's not the least > bit obvious what that question is. > > > Communication is not his forte, but effort, willingness, > > devotion, and dedication are. ?What should he do, and what > > should the others, who are gifted speakers? > > He should spend less time trying to generate "gifted speach" > and more time learning how to ask an understandable, meaningful > question. ?The link which you ignored explains how to do that. > > In your original post, it's not very clear what you mean by > "hash values to keys" means nor what alternatives you're asking > about. If you're trying to learn about hashing algorithms, then > google "hashing algorithms" and read the first half-dozen hits. > > The first two are Wikipedia articles which are both quite good > and are almost certainly available in your native lanauge. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! But they went to MARS > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? around 1953!! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? Are you vegetarian? A little off topic. Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a) is also in it, and maps to the same object? From python.list at tim.thechases.com Wed Mar 12 11:03:58 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Mar 2008 10:03:58 -0500 Subject: agg (effbot) In-Reply-To: <63q90kF268j23U1@mid.uni-berlin.de> References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> <63q90kF268j23U1@mid.uni-berlin.de> Message-ID: <47D7F0DE.5000106@tim.thechases.com> Gerhard H?ring wrote: > fraleysinger at gmail.com wrote: >> aggdraw-1.2a3-20060212.tar.gz > > Try shegabittling the frotz first. If that doesn't help, please post the > output of the compile command that threw the error. Maynard: He who is valiant and pure of spirit may find the compiling instructions in the Drawing Program of Agg Arthur: what?! Maynard: the Drawing Program of Agg. Bedevere: What's that? Maynard: he must of died while typing it Launcelaot: Oh, come on! Maynard: well, that's what it's called Artuhur: Look, if he was dying, he wouldn't bother to name it "agg" Maynard: Well, that's what's written in the URL Galahad: Perhaps he was dictating... Arthur: Oh, shut up. ... -tkc From arnodel at googlemail.com Sat Mar 22 06:58:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 22 Mar 2008 03:58:15 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> Message-ID: <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> On Mar 22, 8:31?am, Bryan Olson wrote: > castiro... at gmail.com wrote: > > John Machin wrote: > >> On Mar 22, 1:11 am, castiro... at gmail.com wrote: > >>> A collision sequence is not so rare. > >>>>>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > >>> [1, 1, 1, 1, 1, 1, 1, 1] > >> Bryan did qualify his remarks: "If we exclude the case where an > >> adversary is choosing the keys, ..." > > > Some adversary. ?What, you mean, my boss or my customers? > > We mean that the party supplying the keys deliberately chose > them to make the hash table inefficient. In this thread the goal > is efficiency; a party working toward an opposing goal is an > adversary. There are situations where this can happen I guess > If you find real-world data sets that tend to induce bad-case > behavior in Python's hash, please do tell. It would be reason > enough to adjust the hash function. The hashes in popular > software such as Python are already quite well vetted. As Python allows you to make your own hash functions for your own classes, another danger is that you are dealing with objects with a bad hash function. I've actually tried it (as I am *not* a pro!) and FWIW here are the results. -------- badhash.py ---------- class BadHash(object): def __hash__(self): return 1 # that's a bad hash function! from time import time def test(n): t0 = time() # Create a hash table of size n s = set(BadHash() for x in xrange(n)) t1 = time() # Add an object to it obj = BadHash() s.add(obj) t2 = time() # Find that object obj in s t3 = time() print "%s\t%.3e\t%.3e\t%.3e" % (n, (t1-t0)/n**2, (t2-t1)/n, (t3- t2)/n) print "n\tcreate/n^2\tadd/n\t\tfind/n" for k in range(8, 17): # I'm hoping that adding an element to a dict of size (1 << k) + 1 # will not trigger a resize of the hasmap. test((1 << k) + 1) -------------------------------- marigold:junk arno$ python badhash.py n create/n^2 add/n find/n 257 3.917e-08 6.958e-08 7.051e-08 513 3.641e-08 8.598e-08 7.018e-08 1025 3.522e-08 7.118e-08 6.722e-08 2049 3.486e-08 6.935e-08 6.982e-08 4097 3.480e-08 7.053e-08 6.931e-08 8193 3.477e-08 6.897e-08 6.981e-08 16385 3.441e-08 6.963e-08 7.075e-08 32769 3.720e-08 7.672e-08 7.885e-08 65537 3.680e-08 7.159e-08 7.510e-08 So theory and practice agree! In this case The hash table behaves just like a linked list. Lastly, if one deals with a totally ordered set of object but they are not hashable (there isn't a good hash function), then Ninereeds' idea of sorting first is still useful. -- Arnaud From noname9968 at gmail.com Thu Mar 27 07:57:52 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 14:57:52 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> <47EB7F55.8090909@gmail.com> Message-ID: <47EB8BC0.1020604@gmail.com> Guilherme Polo wrote: > 2008/3/27, Alex9968 : > >> Guilherme Polo wrote: >> > 2008/3/27, Alex9968 : >> > >> >> Guilherme Polo wrote: >> >> > 2008/3/26, Alex9968 : >> >> > >> >> >> Hi all, >> >> >> >> >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> >> >> using visual GUI designers), so my question is which other GUI toolkits >> >> >> have similar functionality. >> >> >> >> >> > >> >> > The geometry manager isn't related to using GUI designers tools at >> >> > all. And each toolkit has it's own way to do the things, wxPython uses >> >> > sizers, PyGtk uses containers. >> >> > >> >> >> >> Well, the geometry manager isn't *directly* related to using GUI >> >> designers, but as Pack arranges widgets automatically, using GUI >> >> designers isn't required, while with geometry managers that don't, GUI >> >> designers are necessary (if you start placing widgets programmatically, >> >> you'll end up reinventing something like Tkinter's Pack or Grid geometry >> >> manager). I hope I can be understood clearly this time ;-) >> >> >> > >> > Not at all, can't understand your point yet. GUI designers aren't just >> > for placing widgets, they also will keep the interface design >> > separated from your code. >> > >> >> I do not want to separate interface from code and I do not experience >> the need to use GUI designers. >> >> > > It is your opinion, it seems I can't change it for now but I hope you > reconsider it for the future. > > >> Pack arranges widgets perfectly, and it's very complex to do the same >> without it, both in code and in GUI designer. >> > > For some level of "perfect", of course. > Also, I can't understand why you say it is hard to do such thing in a > gui designer tool, which tool have you tried ? Maybe you are not > familiar with them yet, and that could be the problem. > Can you explain why my opinion is to be reconsidered? In GUI designer it's easy to produce initial (still) layout, but what if it should be changed at runtime (for example, widgets added or removed), and still be ideally arranged? I know that widgets might have some parameters affecting for example how they move when their container is resized, and that might help when updating interface, but I think it's inconvenient that they're hidden inside their property sheets (and therefore invisible while designing). I should answer the question - I used Visual C# from Microsoft Visual Studio .NET 2003, and after moving to Python I did not use any GUI designer. From mwilson at the-wire.com Wed Mar 19 11:58:19 2008 From: mwilson at the-wire.com (Mel) Date: Wed, 19 Mar 2008 11:58:19 -0400 Subject: how to remove suffix from filename References: <70a97b17-77d0-467d-acb1-ced03aefe241@d21g2000prf.googlegroups.com> Message-ID: royG wrote: > when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/ > two.jpg'....] etc i want to extract the > basename without the suffix...ie i want to get 'one','two' etc and not > 'one.jpg' > > is there a function in python to do this or do i have tosplit it ..? > thanks os.path.splitext is the one, it think. From marko at pacujo.net Thu Mar 13 08:03:51 2008 From: marko at pacujo.net (Marko Rauhamaa) Date: 13 Mar 2008 14:03:51 +0200 Subject: How to send a var to stdin of an external software References: Message-ID: Benjamin Watine : > How can I do this ? I would like a function like that : > > theFunction ('cat -', stdin=myVar) > > Another related question : Is there's a limitation of var size ? I > would have var up to 10 MB. import subprocess myVar = '*' * 10000000 cat = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE) cat.stdin.write(myVar) cat.stdin.close() cat.wait() Marko -- Marko Rauhamaa mailto:marko at pacujo.net http://pacujo.net/marko/ From rpdooling at gmail.com Wed Mar 12 14:16:15 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Wed, 12 Mar 2008 11:16:15 -0700 (PDT) Subject: Does __import__ require a module to have a .py suffix? References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: <3d4247e6-1240-434e-adc6-090cd480a551@y77g2000hsy.googlegroups.com> On Mar 12, 11:22 am, mrstephengross wrote: > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? > I think you answered your own question, but if you want more info: >From the Python Tutorial: http://docs.python.org/tut/node8.html "A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended." RD > Thanks, > --Steve From asmodai at in-nomine.org Fri Mar 14 14:20:02 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 14 Mar 2008 19:20:02 +0100 Subject: Thousand Seperator In-Reply-To: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <20080314182002.GE60713@nexus.in-nomine.org> -On [20080314 18:11], ewanfisher at gmail.com (ewanfisher at gmail.com) wrote: >But I cannot find how to do this in Python. I am not sure of your goal, but if you need this for localization purposes, look at Babel (http://babel.edgewall.org/). In particular http://babel.edgewall.org/wiki/ApiDocs/babel.numbers We make use of the Unicode CLDR information to provide locale-specific formatting. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ When we have not what we like, we must like what we have... From castironpi at gmail.com Sat Mar 8 15:27:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:27:09 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 1:31?pm, Grant Edwards wrote: > On 2008-03-08, castiro... at gmail.com wrote: > > > Does one side of this hold that there are no -good- comments? > > I wouldn't say there are _no_ good comments, but I would say > that 90+% of the comments I've seen in my lifetime were bad. Limit your comments, in other words. LIM-IT. > comment explaining a particularly opaque algorithm can be > useful as well. But can't the name do that? > at the beginnings of C/C++ functions that do things like tell > you the name and return type of the function and list the names > and types of the parameters. Gee, thanks. ?I never could have > figured that out from looking at the source code itself. IMO, Sometimes void*s are guaranteed to be HTHREADs. > I'm also a bit baffled by people who put a comment at the top > of every file that tells you what the filename is. ?I sometimes > wonder how/where these files were created. All of the OSes I've > ever used had a feature called a "filesystem" which kept track > of info like the names of files. ?It must be a bitch-and-a-half > to work on an computer that doesn't keep track of filenames and > makes the user do it. > > When was the last time you thought to yourself: "Gee, I wonder > what's the the name of that file over there? I guess I'd better > open the file and look at the comment at the top to see what > the filename is? What file did you open? To Lie: > Personally I preferred a code that has chosen good names but have > little or no comments compared to codes that makes bad names and have Personally I don't. Show me a good one. Until you do, it's not that I won't like it, it's that I can't. You know, in linguistics, there's what's called 'code switching', which is switching between two languages you know midstream. People can understand 'hear' a language but not speak it. If you speak it, . If comments aren't the 'short version', then patience is the problem. There's not one word for lots and lots of things. Examples on backorder. Good comments are better than bad names. Good names are better than bad comments. And enter multi-word identifiers. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:54:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:54:18 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> <13t6s8pk90olef8@corp.supernews.com> <13t6te6p71r3u3e@corp.supernews.com> Message-ID: <13t6usamhmai128@corp.supernews.com> On Sun, 09 Mar 2008 05:29:42 +0000, Grant Edwards wrote: >> Sure, but really, adding ONE LINE to the start of a file is hardly >> "cluttering up" anything. Especially if it is in the doc string, like >> this: >> >> """widgets.py: create, manage and destroy widgets. >> >> blah blah blah blah...""" > > The bad part is that it's redundant information. That means that > eventually, it's going to be wrong. I withdraw my defense of including the file name. After looking at both the Python standard library and my own scripts/ modules, I can see that it is a lot rarer than I thought it was, and even when I do it, it is almost always in help strings for quick and dirty scripts. -- Steven From castironpi at gmail.com Thu Mar 6 14:06:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 11:06:50 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> Message-ID: On Mar 6, 8:30?am, Carl Banks wrote: > On Mar 5, 8:44 pm, Steven D'Aprano > cybersource.com.au> wrote: > > But what about classes? Are they singletons? Obviously classes aren't > > Singleton classes, that is, given an arbitrary class C you can create > > multiple instances of C. But what about class objects themselves? I've > > found a few odd references to "classes are singletons", but nothing in > > the language reference. > > Probably because "singleton" is the wrong word. ?A singleton means > there is one instance of a type; classes are instances of "type" which > can have many instances so classes are not singletons. > > Anyway, the answer to what you are probably asking is No. ?Try this: > > >>>import module > >>>c1 = module.Someclass > >>>reload(module) > >>>c2 = module.Someclass > >>>c1 is c2 What about >>> o= object() >>> b1= o.someattr >>> reload( o ) >>> b2= o.someattr >>> b1 is b2 ? From P.G.Aravindh at gmail.com Sun Mar 23 20:48:10 2008 From: P.G.Aravindh at gmail.com (Santhosh1992) Date: Sun, 23 Mar 2008 17:48:10 -0700 (PDT) Subject: TUTORIALS ON COMPUTER PROGRAMMING Message-ID: languages Have the complete details regarding programming languages. A-Z about programming languages like Java J2EE, C++, code implementation guides and more. http://operatingsys.blogspot.com/ From grante at visi.com Wed Mar 5 15:59:23 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 20:59:23 -0000 Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <13su15t266dimc2@corp.supernews.com> <13su1pl8tnq5o6a@corp.supernews.com> <6fa9d736-1769-4e79-a276-f071a83ebce9@e60g2000hsh.googlegroups.com> Message-ID: <13su2dbpqjoig2e@corp.supernews.com> On 2008-03-05, Jeff.Goldfinkle at gmail.com wrote: > thanks for the reply but I'm still unsure as to how to > continue. Using the bitwise operators will help me deal with > integers but I really want to work with floats. In your original post, you said that you've got the values as integers. > For instance - which bits do I twiddle to round my float to > the nearest number of bits? The format of a float (actually Python uses doubles) depends on your platform, but in all likelihood it's the IEEE-754 64-bit format. googling for "IEEE-754 format" finds some good references: http://en.wikipedia.org/wiki/IEEE_floating-point_standard http://steve.hollasch.net/cgindex/coding/ieeefloat.html http://www.psc.edu/general/software/packages/ieee/ieee.html -- Grant Edwards grante Yow! Well, I'm INVISIBLE at AGAIN ... I might as well visi.com pay a visit to the LADIES ROOM ... From pDOTpagel at helmholtz-muenchen.de Mon Mar 3 07:13:52 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Mon, 3 Mar 2008 12:13:52 +0000 (UTC) Subject: Delete hidden files on unix References: Message-ID: loial wrote: > How can I delete hidden files on unix with python, i.e I want to do > equivalent of > rm .lock* Here is one way to do it: import os, glob for filename in glob.glob('.lock*'): os.unlink(filename) Alternatively, you could also do this: import os os.system('rm .lock*') cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From deets at nospam.web.de Wed Mar 5 11:04:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Mar 2008 17:04:26 +0100 Subject: Unit testing Web applications References: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> Message-ID: <637uk7F257fv5U1@mid.uni-berlin.de> Monica Leko wrote: > Hi! > > Does Python has some testing frameworks for testing Web applications > (like Cactus and HttpUnit for Java), generating requests and checking > if the response is correct? mechanize and webunit come to my mind. Yet the most powerful will be selenium together with selenium-remote driven via python. Don't forget to check out the brilliant selenium IDE. Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 3 06:06:37 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Mar 2008 12:06:37 +0100 Subject: Beautiful Code in Python? In-Reply-To: References: Message-ID: <47cbdbbd$0$25962$426a34cc@news.free.fr> js a ?crit : > Hi, > > Have you ever seen Beautiful Python code? > Zope? Django? Python standard lib? or else? > > Please tell me what code you think it's stunning. FormEncode has some very interesting parts IMHO. From willkab6 at gmail.com Sat Mar 22 11:09:18 2008 From: willkab6 at gmail.com (willkab6 at gmail.com) Date: Sat, 22 Mar 2008 08:09:18 -0700 (PDT) Subject: NameError: name 'guess' is not defined Message-ID: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> I am very new to both programming and Pyhton and while trying to do some practice using A byte of python an Error pops up on the IDLE shell. I am using windows XP. PLease see below. while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that.' else: print 'No, it is a little lower than that.' else: print 'The while loop is over.' # Do anything else you want to do here print 'Done' After typing the above as the book says, I get the error NameError: name 'guess' is not defined What Am I doing wrong? From fakeaddress at nowhere.org Fri Mar 14 04:25:07 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 01:25:07 -0700 Subject: Spaces in path name In-Reply-To: <0RpCj.25549$421.10498@news-server.bigpond.net.au> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <13tk779i4r8j9ba@corp.supernews.com> <0RpCj.25549$421.10498@news-server.bigpond.net.au> Message-ID: David S wrote: > Using "C:\Program Files\apache-ant-1.7.0\bin\ant.bat" just gives me the same > result. Did you try the raw string, with the .bat extension? As in: r'C:\Program Files\apache-ant-1.7.0\bin\ant.bat' After Microsoft started allowing blanks in paths, it took them years to fix many common cases where their own software choked on the paths. I got into the habit of installing everything under c:\bin rather than C:\Program Files. I still do that just to avoid writing essays into my PATH variable. -- --Bryan From arkanes at gmail.com Thu Mar 20 16:55:09 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 20 Mar 2008 15:55:09 -0500 Subject: Need help calling a proprietary C DLL from Python In-Reply-To: <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> Message-ID: <4866bea60803201355r2acc8353qe133ae9d23415b0d@mail.gmail.com> On Thu, Mar 20, 2008 at 3:42 PM, Craig wrote: > > On Mar 20, 2:38 pm, Craig wrote: > > On Mar 20, 2:29 pm, sturlamolden wrote: > > > > > On 20 Mar, 19:09, Craig wrote: > > > > > The culprit i here: > > > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > > > This binds these names to Python ints, but byref expects C types. > > > > > Also observe that CacheSize and OpenMode should be c_short. > > > > I changed CacheSize and OpenMode to c_short, and commented out that > > line producing the "Before" message, and the output is the same. > > > > Further "tinkering" revealed that it is the byref on the fName and pw > > that are causing the error. > > > > The entire problem appears to be around the production of a BSTR and > > the passing of pointers (byref) to the BSTR. > > > Can anyone shed some light on how to work with BSTR's? Since you didn't tell ctypes about the function signature, it assumes it returns int and gives you a python int. Provide a function signature (c_void_p should work for BSTR) for both functions and you should have an easier time of it. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From planders at gmail.com Mon Mar 3 14:41:38 2008 From: planders at gmail.com (Preston Landers) Date: Mon, 3 Mar 2008 11:41:38 -0800 (PST) Subject: clocking subprocesses References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> Message-ID: <5af6d8ab-880a-4873-9352-cf1aaae236e0@e6g2000prf.googlegroups.com> On Mar 3, 11:57?am, barnbu... at gmail.com wrote: > So, long story short, I need to get CPU time of something I call using > subprocess.call(). ? Run your command through the "time" program. You can parse the output format of "time", or set a custom output format. This mostly applies to Unix-like systems but there is probably an equivalent somewhere on Windows. Preston From rokkamraja at gmail.com Fri Mar 7 03:41:57 2008 From: rokkamraja at gmail.com (Raja) Date: Fri, 7 Mar 2008 00:41:57 -0800 (PST) Subject: Python GDB Wrapper References: <47d0f228$0$17725$9b622d9e@news.freenet.de> Message-ID: On Mar 7, 1:21 pm, Raja wrote: > Hi All, > Thanks for replies. Daniel- I am looking at just a wrapper > around GDB. I dont want to emulate the functionalities of GDB but > instead use them in python scripting. > Martin - Misc/gdbinit looks promising. Thanks a lot. > > Thanks, > Raja. > > On Mar 7, 12:43 pm, "Martin v. L?wis" wrote: > > > > Has anyone does this before ? Even some basic idea or code as to how > > > to proceed would be great. > > > Have you seen Misc/gdbinit? > > > Regards, > > Martin Hi All, Marting- I looked at the Misc/gdbinit but what I want is a Python module which wraps around GDB and exposes its functionality, which has some methods in it like pystack to which if I give the arguments as program name and arguments displays the stack trace of that particular program . Thanks, Raja. From nir1408 at gmail.com Mon Mar 17 05:54:59 2008 From: nir1408 at gmail.com (Nir) Date: Mon, 17 Mar 2008 02:54:59 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: On Mar 17, 5:54 am, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece > ofpythoncode works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in adebuggerso I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But withPython, thedebuggeris a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. When the code is long, I am often lost in it. > > So I'm curious how to read code effectively. I agree thatpythoncode > is clear, but when it becomes long, reading it can still be a hard > work. Try Winpdb - www.winpdb.org (works on Linux as well). Don't forget to send feedback. From alex.pulver at gmail.com Sat Mar 15 06:31:46 2008 From: alex.pulver at gmail.com (Alex) Date: Sat, 15 Mar 2008 03:31:46 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> Message-ID: <92d6c804-4854-4d48-ae8c-588c6f9ab402@n75g2000hsh.googlegroups.com> On Mar 15, 5:42 am, Carl Banks wrote: > On Mar 14, 6:37 pm, Alex wrote: > > > > > On Mar 13, 6:21 pm, Carl Banks wrote: > > > > On Mar 13, 7:02 am, Bruno Desthuilliers > > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > > Alex a ?crit : > > > > (sni) > > > > > > First of all thanks all for answering! > > > > > > I have some environment check and setup in the beginning of the code. > > > > > I would like to move it to the end of the script. > > > > > Why ? (if I may ask...) > > > Sure, because of a readability (similar to function declarations in > > C). > > > > > > But I want it to > > > > > execute first, so the script will exit if the environment is not > > > > > configured properly. > > > > > If you want some code to execute first when the script/module is loaded, > > > > then keep this code where it belongs : at the beginning of the script. > > > > I concur with Bruno's recommendation: stuff you want to do first > > > should come first in the script. Things like BEGIN blocks hurt > > > readability because you can't identify where execution begins without > > > reading the whole file. > > > > Having said that, one thing that often happens in Python scripts is > > > that all the functions are defined first, then the script logic > > > follows. So you could put the meat of your script in a function, then > > > the "BEGIN" stuff after that functions: > > > > def run_script(): > > > # > > > # script contained in this long function > > > # > > > > # Then test preconditions here... > > > if os.environ["HELLO"] != "WORLD": > > > sys.exit(2) > > > > # Then call the run_script functions > > > run_script() > > > > But having said THAT, I don't recommend you do that with > > > preconditions. If the script has a quick early exit scenario, you > > > really ought to put that near the top, before the function > > > definitions, to clearly show to a human reader what is necessary to > > > run the script. > > > > Carl Banks > > > Hi, > > > Maybe i was a little bit unclear... I meant that i wanted to do > > something like this: > > > #!usr/bin/env python > > > check_env() > > > from subprocess import * > > > class MyClass: > > # Class definition > > > def check_env(): > > # Code > > > if __name__ == "__main__": > > # Script logic > > > The thing is, as i saw, that Python doesn't recognize the > > "check_env()" function before it reaches the "def" statement. > > You could rearrange it like this and it will work: > > #!usr/bin/env python > > def check_env(): > # Code > > check_env() > > from subprocess import * > > class MyClass: > # Class definition > > if __name__ == "__main__": > # Script logic > > Or, better yet, do what Arnaud Delobelle suggests. > > It's not a big deal to move imports down the page a bit, as long as > you throw in a few clear comments explaning what you're doing and why. > > You might also consider putting check_env() in a separate module. > > Carl Banks Hi guys, Thanks for help! :) From qingshan.chen at gmail.com Sun Mar 23 20:01:59 2008 From: qingshan.chen at gmail.com (QS) Date: Sun, 23 Mar 2008 17:01:59 -0700 (PDT) Subject: Does python hate cathy? Message-ID: Hi to all! I am new to python, and I encountered a weird problem. Here is my code ##########>8#################### #!/usr/bin/python # Filename: objvar.py class Person: '''Represents a person.''' population = 0 #sex = 'F' #age = 22 # It is vague here: is this variable going to be a class, or object, variable def __init__(self, name, sex): '''Initializes the person's data.''' self.name = name self.sex = sex print '(Initializing %s )' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' self.age = 25 print 'Hi, my name is %s, and I am %s, and I am age %d ' % (self.name, self.sex, self.age) def howMany(self): '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop', 'M') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam', 'M') kalam.sayHi() kalam.howMany() cathy = Person('Catherine', 'F') cathy.sayHi() cathy.howMany() swaroop.sayHi() swaroop.howMany() ############# 8< ######################### When I run this script, I got the following exception: Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored To to newcomer like me, this message doesn't make much sense. What seems weird to me is that, if I change the variable cathy to something else, like cath, or even cat, then the script will finish gracefully. Why "cathy" is not liked?!! Some of you may have recognized that the code is derived from a sample code in Swaroop's "A byte of python". My python is of version 2.5.1, on Ubuntu. From arkanes at gmail.com Thu Mar 13 11:47:18 2008 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 13 Mar 2008 10:47:18 -0500 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <-161202553970035867@unknownmsgid> References: <-161202553970035867@unknownmsgid> Message-ID: <4866bea60803130847u38d69060mf8a46d08e484d603@mail.gmail.com> On Thu, Mar 13, 2008 at 10:36 AM, Robert Rawlins wrote: > > > > > Hello Guys, > > > > I've got an awfully aggravating problem which is causing some substantial > hair loss this afternoon J I want to get your ideas on this. I am trying to > invoke a particular method in one of my classes, and I'm getting a runtime > error which is telling me the attribute does not exist. > > > > I'm calling the method from within __init__ yet it still seems to think it > doesn't exist. > > > > Code: > > > > # Define the RemoteDevice class. > > class remote_device: > > > > # I'm the class constructor method. > > def __init__(self, message_list=""): > > self.set_pending_list(message_list) > > > > def set_pending_list(self, pending_list): > > # Set the message list property. > > self.pending_list = message_list > > > > And the error message which I receive during the instantiation of the class: > > > > File: "/path/to/my/files/remote_device.py", line 22, in __init__ > > self.set_pending_list(message_list) > > AttributeError: remote_device instance has no attribute 'set_pending_list' > > > > Does anyone have the slightest idea why this might be happening? I can see > that the code DOES have that method in it, I also know that I don't get any > compile time errors so that should be fine. I know it mentions line 22 in > the error, but I've chopped out a load of non relevant code for the sake of > posting here. > > > > Perhaps I'm missing something really simple, but it's got my head spinning. > Create a copy of your source file, confirm that it shows the problem, and start chopping out lines until all that is left is what you pasted here. See if it still shows the problem. If it does, and if you haven't found the problem yet, post again, attaching (not pasting inline) your chopped down file. From ivan.illarionov at gmail.com Mon Mar 17 16:46:54 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 17 Mar 2008 13:46:54 -0700 (PDT) Subject: struct unpack References: <1878d2f6-8a87-4599-98bb-2d3d2bcbce7f@u72g2000hsf.googlegroups.com> Message-ID: <953cab77-f601-4e18-a177-b50f7f066efa@e6g2000prf.googlegroups.com> On Mar 17, 11:00 pm, brnstrmrs wrote: > If I run: > > testValue = '\x02\x00' > junk = struct.unpack('h', testValue) > > Everything works but If I run > > testValue = raw_input("Enter Binary Code..:") inputting at the > console '\x02\x00' > junk = struct.unpack('h', testValue) > > It errors out with > Traceback (most recent call last): > File "/home/nirmal/eDoseCheck/yennes1.py", line 9, in > junk = struct.unpack('h', testValue) > File "struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 2 > > any ideas? You may need to use eval, because raw_input() does not understand '\'- prefixed characters. >>> testValue = eval('"%s"' % raw_input("Enter Binary Code..: ")) Enter Binary Code..: \x02\x00 >>> junk, = struct.unpack('h', testValue) >>> print junk 2 From gagsl-py2 at yahoo.com.ar Wed Mar 26 19:02:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 20:02:57 -0300 Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 18:01:31 -0300, George Sakkis escribi?: > On Mar 26, 3:41 pm, Tim Henderson wrote: > >> I am using mysql, and sqlite is not appropriate for my situation since >> some of the databases and tables I access are being accessed by other >> applications which are already written and live. I am not using the >> SQLAlchemy or SQLObject, because I didn't want too (although in the >> future I may consider using them). > > I'd strongly second looking into SQLAlchemy; from what you wrote, I > suspect sooner or later you'll end up creating (to paraphrase > Greenspun) an ad hoc, informally-specified, bug-ridden, slow > implementation of half of SQLAlchemy. You beat me to say that, but using SQLObject instead. Moreover, the OP is looking for the PersistentDict and PersistentList classes that ZODB uses. I'm not sure that triggering a database write for each and every modified attribute is a good thing; I'd use a "dirty" flag instead (ZODB uses _p_changed) and write all modifications at the end. Since not all methods modify the object contents, using a metaclass to flag all of them isn't a good idea either. I'd use a decorator; after all, they're not so many methods; if you inherit from DictMixin you only have to write __getitem__, __setitem__, __delitem__ and keys(), and of those, only __setitem__ and __delitem__ modify the object. -- Gabriel Genellina From kla at us.de Mon Mar 24 16:11:45 2008 From: kla at us.de (klaus) Date: 24 Mar 2008 20:11:45 GMT Subject: beginners question about return value of re.split References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> <47e3d9ff$0$17341$e4fe514c@dreader19.news.xs4all.nl> <84dedb7d-d726-4acf-84fc-2a8f28277d0d@s12g2000prg.googlegroups.com> Message-ID: <47e80b01$0$22546$e4fe514c@dreader13.news.xs4all.nl> On Fri, 21 Mar 2008 13:34:27 -0700, John Machin wrote: > On Mar 22, 2:53 am, klaus wrote: >> On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote: >> >> <..........> >> >> Ok thank you ! >> >> I think I got a bit lost in all the possibilities python has to offer. > > IMHO you got more than a bit lost. You seem to have stumbled on a > possibly unintended side effect of re.split. > > What is your underlying goal? > > If you want merely to split on '-', use datum.split('-'). > > If you want to verify the split results as matching patterns (4 digits, > 2 digits, 2 digits), use something like this: > > | >>> import re > | >>> datum = '2008-03-14' > | >>> pattern = r'^(\d\d\d\d)-(\d\d)-(\d\d)\Z' You may notice two > differences between my pattern and yours ... > | >>> mobj = re.match(pattern, datum) | >>> mobj.groups() > | ('2008', '03', '14') > > But what are you going to do with the result? If the resemblance between > '2008-03-14' and a date is not accidental, you may wish to consider > going straight from a string to a datetime or date object, e.g. > > | >>> import datetime > | >>> dt = datetime.datetime.strptime(datum, '%Y-%m-%d') > | >>> dt > | datetime.datetime(2008, 3, 14, 0, 0) > | >>> d = > datetime.datetime.date(dt) > | >>> d > | datetime.date(2008, 3, 14) > > HTH, > John Ok, sorry for my late reply. I got caught up in a fight with easterbunnys over some extraordinary large, fruitty and fertile eggs. Some creatures take Easter just to serious and it is not even mating season ! Can you believe that ? :-) Anyway, the underlying goal was to verify user input and to split up the date so that I could easily convert it to another format. Among others, an url and for a database querry. And I have succeeded in that. Thank you again; for taking the time to explain - and to question. KL. From python.list at tim.thechases.com Tue Mar 4 11:00:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Mar 2008 10:00:06 -0600 Subject: for-else In-Reply-To: References: Message-ID: <47CD7206.2050203@tim.thechases.com> > For instance, if you have a (trivial) if...elif...else like this: > > if a == 0: > do_task_0() > elif a == 1: > do_task_1() > elif a == 2: > do_task_2() > else: > do_default_task() > > You could roll it up into a for...else statement like this: > > for i in range(3): > if a == i: > do_task[a]() important "break" missing here... > else: > do_default_task() or otherwise this code will do_task_i *and* do_default_task()... -tkc From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:49:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:49:41 -0200 Subject: Beginner's assignment question References: Message-ID: En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > Lorenzo Gatti wrote: >> On Mar 1, 3:39 pm, Schizoid Man wrote: >>> As in variable assignment, not homework assignment! :) >>> >>> I understand the first line but not the second of the following code: >>> >>> a, b = 0, 1 >>> a, b = b, a + b >>> >>> In the first line a is assigned 0 and b is assigned 1 simultaneously. >>> >>> However what is the sequence of operation in the second statement? I;m >>> confused due to the inter-dependence of the variables. >> >> The expressions of the right of the assignment operator are evaluated >> before assigning any new values, to the destinations on the left side >> of the assignment operator. >> So substitutig the old values of a and b the second assignment means >> >> a, b = 0, 0 + 1 >> >> Simplifying the Python Reference Manual ("6.3 Assignment Statements") >> a little : >> >> assignment_stmt ::= target_list "="+ expression_list >> >> An assignment statement evaluates the expression list (remember that >> this can be a single expression or a comma-separated list, the latter >> yielding a tuple) and assigns the single resulting object to each of >> the target lists, from left to right. >> >> [...] >> >> WARNING: Although the definition of assignment implies that overlaps >> between the left-hand side and the right-hand side are `safe' (for >> example "a, b = b, a" swaps two variables), overlaps within the >> collection of assigned-to variables are not safe! For instance, the >> following program prints "[0, 2]": >> >> x = [0, 1] >> i = 0 >> i, x[i] = 1, 2 >> print x >> >> Lorenzo Gatti > > Thank you for the explanation. I guess my question can be simplified as: > > First step: a, b = 0, 1 > No problem here as a and b are assigned values. > > Second step: a, b = b, a + b > > Now my question is does b become a + b after a becomes 1 or while a > stays at 0? > > As the assignment occurs simultaneously I suppose the answer is while a > stays at 0. Read the previous response carefully and you'll answer your question. The right hand side is EVALUATED in full before values are assignated to the left hand side. Evaluating b, a+b results in 1, 1. The, those values are assigned to a, b. -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 20 11:43:57 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 10:43:57 -0500 Subject: Can I run a python program from within emacs? In-Reply-To: References: Message-ID: Well, I suppose you could. But why bother with learing emacs when you'll have to switch to vim later anyway? 2008/3/20, jmDesktop : > > Hi, I'm trying to learn Python. I using Aquamac an emac > implementation with mac os x. I have a program. If I go to the > command prompt and type pythong myprog.py, it works. Can the program > be run from within the editor or is that not how development is done? > I ask because I was using Visual Studio with C# and, if you're > familiar, you just hit run and it works. On Python do I use the > editor for editing only and then run the program from the command > line? Thank you. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waltbrad at hotmail.com Mon Mar 17 13:50:01 2008 From: waltbrad at hotmail.com (waltbrad) Date: Mon, 17 Mar 2008 10:50:01 -0700 (PDT) Subject: questions about named pipe objects... Message-ID: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> I'm proceeding slowly though the Lutz book "Programming Python". I'm in the section on named pipes. The script he uses has two functions: one for the child the other for the parent. You start the parent then the child: python pipefifo.py #starts the parent file /tmp/pipefifo # shows that the file is a named pipe python pipefifo.py -child # starts a child process and writes to the pipe. This is done between two command windows - the first for the parent and the second for the child. Now, the child's write loop is infinite. So, I used Ctrl-C and stopped the process. But the parent's read loop is also infinite and without and exception, so it keeps reading from the pipe after the child is shutdown even though the lines are empty. So, I had to shut that down also. I then wanted to start the child process first and see what happened when I ran the parent. Well that works but the reads come out in random order. This got me wondering about the pipe file itself. So I tried to open it with leafpad and found that I couldn't. I guess these files can only be opened by processes? Okay. But exactly when does the system brand this file as a named pipe and how? From watine at cines.fr Mon Mar 17 09:19:10 2008 From: watine at cines.fr (Benjamin Watine) Date: Mon, 17 Mar 2008 14:19:10 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: <47DE6FCE.9010506@cines.fr> bryanjugglercryptographer at yahoo.com a ?crit : > I wrote: >> And here's a thread example, based on Benjamin's code: > [...] > > Doh! Race condition. Make that: > > import subprocess > import thread > import Queue > > def readtoq(pipe, q): > q.put(pipe.read()) > > cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, > stdout=subprocess.PIPE) > > myVar = str(range(1000000)) # arbitrary test data. > > q = Queue.Queue() > thread.start_new_thread(readtoq, (cat.stdout, q)) > cat.stdin.write(myVar) > cat.stdin.close() > cat.wait() > myNewVar = q.get() > > assert myNewVar == myVar > print len(myNewVar), "bytes piped around." > > > -- > --Bryan > Great, it works, thank you Bryan ! Could you explain me why you use a queue instead of a simple array for getting the piped var ? Regards, Ben From jorge.vargas at gmail.com Sun Mar 9 12:32:27 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sun, 9 Mar 2008 10:32:27 -0600 Subject: Returning values from function to Python shell/IPython In-Reply-To: References: Message-ID: <32822fe60803090932q33f88f27qddbc1d62d5f1a7ff@mail.gmail.com> On Sun, Mar 9, 2008 at 9:56 AM, Karlo Lozovina <_karlo_ at mosor.net> wrote: > Hi all! > > I have a runTest() function inside my module, which sets up and initializes > lots of objects and performs some basic tests on them. Usually (from > IPython) I just write `run my_module.py`, and then `runTest()`. But > sometimes I would like to manually twiddle with objects runTest creates. Is > there any way I can "return" all those objects local to runTest(), and have > them available in IPython (or ordinary Python shell)? well after all it's a function so the only ways you can get things out of it are: - return a dict with all the objects - use global (very messy) - use a decorator to do either of the above. on the other hand have you consider using a proper test package? instead of inspecting the objects manually from the shell you could make it all automatic. with assert statements. you could use the std. python testing modules http://docs.python.org/lib/development.html or something less verbosed like nose http://code.google.com/p/python-nose/ > > Thanks... > > > P.S. > I know I can do it from a: > > if __name__ == '__main__': > # lots of object initialization... > > and then have all those objects available in the interpreter. > > -- > Karlo Lozovina -- Mosor > -- > http://mail.python.org/mailman/listinfo/python-list > From don.raikes at oracle.com Sun Mar 9 20:41:31 2008 From: don.raikes at oracle.com (Donald Raikes) Date: Sun, 9 Mar 2008 17:41:31 -0700 Subject: python-2.5.2 src rpm Message-ID: <20080309174131250.00000001416@draikes-pc> Hello, I am trying to install python 2.5.2 onto enterprise linux, and would like to start with a source rpm package so that I can build the package locally and make sure I have all necessary dependencies. I have been unable to locate a source rpm package for python 2.5.2 or any version of 2.5 for that matter. Any pointers would be appreciated. Donald Raikes | Accessibility Specialist Phone: +1 602 824 6213 | Fax: +1 602 824 6213 | Mobile: +1 520 271 7608 Oracle JDeveloper QA "Please consider your environmental responsibility before printing this e-mail" From viji.jp1 at gmail.com Wed Mar 12 05:58:30 2008 From: viji.jp1 at gmail.com (viji.jp1 at gmail.com) Date: Wed, 12 Mar 2008 02:58:30 -0700 (PDT) Subject: YOU LIKE THIS Message-ID: <90de7976-e437-4c73-9e1d-d646a0bc6190@s13g2000prd.googlegroups.com> YOU LIKE THIS ***************************************** http://hollywood154.blogspot.com/ ***************************************** From http Sat Mar 22 15:22:42 2008 From: http (Paul Rubin) Date: 22 Mar 2008 12:22:42 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <7xmyoqlg1p.fsf@ruckus.brouhaha.com> jmDesktop writes: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? It's at least pretty good. It's not ideal, but nothing ever is. What I mean is: it's the best suggestion I can think of, but I can't say with confidence that there's nothing better out there. Alternatives would probably be more esoteric languages like Logo. Chris Okasaki (of functional data structures fame) has an interesting blog post about why indentation-based structuring is a big help for teaching: http://okasaki.blogspot.com/2008/02/in-praise-of-mandatory-indentation-for.html From python.list at tim.thechases.com Wed Mar 19 06:07:50 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 05:07:50 -0500 Subject: Search the command history - Python Shell In-Reply-To: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> References: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> Message-ID: <47E0E5F6.2010701@tim.thechases.com> > Are there any simillar key combination in Python Shell like Linux Ctrl+R > (reverse-i-search) to search the command history? It must depend on how your version of Python was built...mine here on my Linux box has exactly that functionality. I press ^R and start typing, and the line comes up from my typed history. bash$ python2.4 Python 2.4.4 (#2, Jan 3 2008, 13:36:28) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 42 (reverse-i-search)`a': a = 42 bash$ python2.5 Python 2.5.2a0 (r251:54863, Feb 10 2008, 01:31:28) [GCC 4.2.3 (Debian 4.2.3-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 42 (reverse-i-search)`a': a = 42 -tkc From clodoaldo.pinto at gmail.com Fri Mar 28 09:54:49 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Fri, 28 Mar 2008 06:54:49 -0700 (PDT) Subject: base64.urlsafe_b64encode and the equal character Message-ID: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> I'm using a md5 hash encoded with base64.urlsafe_b64encode as a parameter of a URL used to confirm a registration in a site. It has been working great. The url is like this: http://example.com/ce?i=878&h=kTfWSUaby5sBu9bIfoR87Q== Now i need to match that URL in a certain text and i realized that urlsafe_b64encode uses the "=" character so i can't just use \w{24} to match the parameter. What i need to know is where can an equal char appear in a urlsafe_b64encoded string?: a)only at end; b)both at the end and at the begginig; c)anywhere in the string; A sure answer will make my regexp safer. In another point, does the "=" char make it urlunsafe? I guess not because i believe it would only be unsafe if the equal appeared like in "&var=" and since there are no "&" in the string than there is no problem right? Or wrong? Regards, Clodoaldo Pinto Neto From ivan.illarionov at gmail.com Mon Mar 17 19:27:18 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 17 Mar 2008 16:27:18 -0700 (PDT) Subject: Interesting math problem References: Message-ID: On Mar 18, 1:24 am, "BJ?rn Lindqvist" wrote: > Here is an interesting math problem: > > You have a number X > 0 and another number Y > 0. The goal is to > divide X into a list with length Y. Each item in the list is an > integer. The sum of all integers is X. Each integer is either A or A + > 1, those should be "evenly distributed." > > Example: > > 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] > 16 // 4 = 4 gives the list [4, 4, 4, 4] > 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, > 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, > 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] > > This algorithm is used a lot in programming. For example, for > projecting a line on a pixel display. Your mission, should you choose > to accept it, is to improve the code given below which is my best > attempt and make it more succinct and easier to read. Preferably by > using list comprehensions, map or even reduce.... > > def make_slope(distance, parts): > step = distance / float(parts) > intstep = int(step) > floatstep = step - intstep > > steps = [] > acc = 0.0 > for i in range(parts): > acc += floatstep > step = intstep > if acc > 0.999: > step += 1 > acc -= 1.0 > steps.append(step) > return steps > > # Test code > distance = 130 > parts = 50 > L = make_slope(distance, parts) > assert(len(L) == parts) > assert(sum(L) == distance) > print L > > -- > mvh Bj?rn Integer-only version: def make_slope(distance, parts): intstep, err = divmod(distance, parts) steps = [] acc = 0 for i in range(parts): acc += err step = intstep if acc >= parts: step += 1 acc -= parts steps.append(step) return steps # Test code distance = 130 parts = 50 L = make_slope(distance, parts) assert(len(L) == parts) assert(sum(L) == distance) print L From castironpi at gmail.com Wed Mar 26 21:00:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 18:00:53 -0700 (PDT) Subject: A question on decorators References: <944662fa-6ca5-4331-985c-445fe74bbbe4@u10g2000prn.googlegroups.com> Message-ID: <2e61203f-da5e-4721-a029-554787d6694d@13g2000hsb.googlegroups.com> On Mar 26, 6:02?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 18:01:31 -0300, George Sakkis ? > escribi?: > > > On Mar 26, 3:41 pm, Tim Henderson wrote: > > >> I am using mysql, and sqlite is not appropriate for my situation since > >> some of the databases and tables I access are being accessed by other > >> applications which are already written and live. I am not using the > >> SQLAlchemy or SQLObject, because I didn't want too (although in the > >> future I may consider using them). > > > I'd strongly second looking into SQLAlchemy; from what you wrote, I > > suspect sooner or later you'll end up creating (to paraphrase > > Greenspun) an ad hoc, informally-specified, bug-ridden, slow > > implementation of half of SQLAlchemy. > > You beat me to say that, but using SQLObject instead. > Moreover, the OP is looking for the PersistentDict and PersistentList ? > classes that ZODB uses. > I'm not sure that triggering a database write for each and every modified ? > attribute is a good thing; I'd use a "dirty" flag instead (ZODB uses ? > _p_changed) and write all modifications at the end. > Since not all methods modify the object contents, using a metaclass to ? > flag all of them isn't a good idea either. I'd use a decorator; after all, ? > they're not so many methods; if you inherit from DictMixin you only have ? > to write __getitem__, __setitem__, __delitem__ and keys(), and of those, ? > only __setitem__ and __delitem__ modify the object. That depends on technology: in volatile memory, persistence is a long- term commitment. In static-state memory, it's a norm. Say you've got a flash drive on the bus, you could store the objects themselves: the Python module would have to allocate from the ROM, reobtain later. Don't store the interpreter on the ROM, and trade-off feature sets for expiration date. But standards expire? From graemeglass at gmail.com Mon Mar 31 08:30:00 2008 From: graemeglass at gmail.com (Graeme Glass) Date: Mon, 31 Mar 2008 05:30:00 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <4d1d7d83-8155-4c1a-a807-0b5c951e1192@d21g2000prf.googlegroups.com> On Mar 27, 11:01 am, Peter Otten <__pete... at web.de> wrote: > Grimsqueaker wrote: > > That seems to give me the items in the list back in an iterator. Am I > > using it incorrectly? > > With Dan's functions in cartesian.py you can do the following: > > >>> from cartesian import * > >>> def count(digits): > > ... args = [] > ... while 1: > ... args.append(digits) > ... for n in string_cartesian_product(*args): > ... yield n > ...>>> from itertools import islice > >>> print " ".join(islice(count("abc"), 30)) > > a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab > bac bba bbb bbc bca bcb bcc > > Peter Here is a cool solution we came up with during a little interactive session at our local meet up. (http://www.python.org.za/pugs/cape-town/cape-town) s = 'abcdef' ["".join([s[j] for j in range(len(s)) if x & (1 << j)]) for x in range(1,2**len(s)) ] http://groups.google.com/group/ctpug/browse_thread/thread/986aab83f9782f6c Regards, Graeme From ptmcg at austin.rr.com Tue Mar 25 11:27:12 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 Mar 2008 08:27:12 -0700 (PDT) Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> Message-ID: This code is SO *CUTE*! I wish there was a font with little hearts to dot the 'i's with, then it would be PERFECT! From sjmachin at lexicon.net Sun Mar 30 03:31:57 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Mar 2008 00:31:57 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> Message-ID: <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> On Mar 30, 3:58 pm, hdante wrote: > On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" > > wrote: > > Hello, > > > I am having trouble writing the code to read a binary string. I would > > like to extract the values for use in a calculation. > > > Any help would be great. > > I'm too lazy to debug your binary string, but I suggest that you > completely throw away the binary file and restart with a database or > structured text. See, for example: > > http://pyyaml.org/wiki/PyYAML > > If you have some legacy binary file that you need to process, try > creating a C program that freads the binary file and printfs a text > equivalent. > ... and that couldn't be done faster and better in Python?? From martin at marcher.name Thu Mar 6 09:26:27 2008 From: martin at marcher.name (Martin Marcher) Date: Thu, 6 Mar 2008 15:26:27 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <5fa6c12e0803060626l5624a4a7qd374d8e741eb900f@mail.gmail.com> On Thu, Mar 6, 2008 at 2:06 PM, Guillermo wrote: > >What makes you say you "need" to know this ? Except for a couple corner > >cases, you usually don't need to care about this. If you told us more > >about the actual problem (instead of asking about what you think is the > >solution), we might be of more help... > > I want to iterate recursively a dictionary whose elements might be > strings or nested tuples or dictionaries and then convert values to a > tagged format according to some rules. just do so, if it's not a dict you can always catch the exception, then handle tuples (or the exception), then strings which should work always (of course also error handling here according to your needs) > I'm just designing the algorithm, but I think Python dictionaries can > hold any kind of sequence? python dicts can hold any kind of object (as a value). What you can't do is have a list as the key, but that is easily circumvented by using a tuple (or any other immutable type). hth martin -- http://tumblr.marcher.name https://twitter.com/MartinMarcher http://www.xing.com/profile/Martin_Marcher http://www.linkedin.com/in/martinmarcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From castironpi at gmail.com Sat Mar 8 12:44:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 09:44:26 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> Message-ID: On Mar 8, 9:31?am, Grant Edwards wrote: > On 2008-03-08, dave_mikes... at fastmail.fm wrote: > > >> The function name also doesn't explain anything. How was the stuff got? > >> Was it paid for, or stolen, or picked up on consignment, or what? Compare > >> the above line with: > > >> x = get_stuff(store) ?# Steal stuff from the store. > > >> or > > >> x = get_stuff(store) ?# Pickup the stuff from the store for disposal. > >> # The amount paid by the store is stored in global variable "pay_received" > >> # and the name of the employee authorizing the pickup is stored in the > >> # global "authorized_by". > > > Shouldn't get_stuff's comment be with its definition? > > Probably, but better that comment shouldn't be anywhere. > > get_stuff() should be > > ?1) renamed, as you state below. > > ?2) written such that it's obvious from reading the source code > ? ? that the amount paid is stored in the global variable > ? ? pay_received and that the name of the employee authorizing > ? ? the pickup is stored in the global authorized by. > > But, it's not really fare picking on an example like that... > > > And just rename the function to something more meaningful, > > like purchase_goods(store), or whatever. > >> But even if you were right that the comment was unnecessary, > >> you have missed my point that even single sentences can be > >> grammatically bogus and the writer could learn a lot from > >> Strunk and White or equivalent. > > That's true. ?I don't know how many times I've seen a single > sentence comment that was just plain vague and ambiguous. And > most of the time they're just plain wrong as well because the > code had been changed but nobody changed the comment (possibly > because they couldn't understand what the comment was trying to > say). There are bad comments and bad variable names. fcrg= dothingthatgoesplace( qkjwvm ). # that thing I talked about # in last Tuesday's code for searching qkjwvm and returning its attribute. Does one side of this hold that there are no -good- comments? From asr-1 at comcast.net Wed Mar 12 21:50:57 2008 From: asr-1 at comcast.net (Andrew Rekdal) Date: Wed, 12 Mar 2008 20:50:57 -0500 Subject: Big file References: <13th14pe0hhsie1@corp.supernews.com> Message-ID: <9LKdnQpmfOvhFUXanZ2dnUVZ_gKdnZ2d@comcast.com> Well, I can see how this could get real messy but within defining a GUI there are many elements and so the block of elements such as a wx.notebook for instance I would hope I could place all the code for this in another file and somehow include it into place. This way I can work on layered panels and such in a fresh document rather than travesing through tons of widgets and sizers. Thanks for your replies -- -- Andrew "Steven D'Aprano" wrote in message news:13th14pe0hhsie1 at corp.supernews.com... > On Wed, 12 Mar 2008 19:42:44 -0500, Andrew Rekdal wrote: > >> I am working in the class constructor defining elements of an >> application. The problem is the file is getting unmanageble and I am >> wanting to extend the contructor __init__ to another file. >> >> Is it possible to import directly into the contructor the contents of >> another module file? >> >> If so how would this be done? > > > Here's the way you do what you literally asked for: > > class MyClass(object): > def __init__(self, *args): > # Warning: completely untested > execfile('myfile.py') # may need extra arguments? > > but you almost certainly don't want to do that. A better way is by > importing modules, the same as you would for anything else: > > class MyClass(object): > def __init__(self, *args): > from AnotherModule import constructor > constructor(self, *args) > > > But frankly if you find yourself needing to do this because your file is > "too big" and is unmanageable, I think you are in desperate need of > refactoring your code to make if more manageable. Pushing vast amounts of > random code out into other files just increases the complexity: not only > do you have vast amounts of code, but you have large numbers of files to > manage as well. > > > > > -- > Steven > > > From steve at holdenweb.com Mon Mar 3 23:16:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Mar 2008 23:16:12 -0500 Subject: pySQLite Insert speed In-Reply-To: <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> Message-ID: mmm wrote: >>> Hence (if I understand python convention), this can be >>> solved by adding >>> sqlx= copy.copy(sqlx) >>> before the looping. And in tests adding this step saved about 5-10% in >>> time. >> Now this I don;t really understand at all. What's the point of trying to >> replace sqlx with a copy of itself? Perhaps if you explained what you >> hope this will achieve I could comment more intelligently. >> > > I am/was attempting to convert > > sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) > > to code that did to need to be re-evaluated. i.e. to insert the > dtable and ph values as if they were hard coded. > > copy.copy --> A shallow copy constructs a new compound object and > then (to the extent possible) inserts references into it to the > objects found in the original. Unfortunately you weren't dealing with a compound object object here, so all you are doing is creating a copy of the string you've just created and replacing the original with it. Copy.copy() is meant for creating (say) lists, tuples and dicts where the elements are references to the same objects that the elements of the original structure referred to. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From danb_83 at yahoo.com Wed Mar 12 21:55:08 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 12 Mar 2008 18:55:08 -0700 (PDT) Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> Message-ID: <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> On Mar 12, 6:52 pm, Alan Isaac wrote: > Paul Rubin wrote: > > The cmp option should not be removed. However, requiring > > it to be specified as a keyword parameter instead of just > > passed as an unlabelled arg is fine. > > Sure; I would have no problem with that. > > But that is not what is happening. > > As for Carl's suggestion to use ``key``: > this is already possible when it is convenient, > but it is not always convenient. (Even aside > from memory considerations.) def cmp_key(cmp_fn): class CmpWrapper(object): def __init__(self, obj): self.obj = obj def __cmp__(self, other): return cmp_fn(self.obj, other.obj) return CmpWrapper From danb_83 at yahoo.com Thu Mar 27 02:29:29 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 26 Mar 2008 23:29:29 -0700 (PDT) Subject: counting using variable length string as base References: Message-ID: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> On Mar 27, 1:15 am, Grimsqueaker wrote: > Hi, I'm fairly new to Python and to this list. I have a problem that > is driving me insane, sorry if it seems simple to everyone, I've been > fighting with it for a while. :)) > > I want to take a variable length string and use it as a base for > counting, eg. given the string 'abc' the sequence would be: > > a > b > c > aa > ba > ca > ab > bb > cb > ... > ccc > > Basically I want to find every possible order of every combination. > Its easy if you know how many characters there will be in your string > (use nested for loops), but I am stuck with the variable length > string. I think I have to use a generator but I'm not sure exactly > how. > > Can anyone give me a pointer in the right direction? def cartesian_product(*args): """Iterates over the Cartesian product of args[0], args[1], ...""" if not args: return elif len(args) == 1: for item in args[0]: yield (item,) else: for item in args[0]: for item2 in cartesian_product(*args[1:]): yield (item,) + item2 def string_cartesian_product(*args): return (''.join(combo) for combo in cartesian_product(*args)) From bernard.chhun at gmail.com Thu Mar 13 14:46:46 2008 From: bernard.chhun at gmail.com (Bernard) Date: Thu, 13 Mar 2008 11:46:46 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array References: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> <1ce4546b-f206-4f02-91c3-67f3d5773d50@p25g2000hsf.googlegroups.com> Message-ID: <49c0e986-36af-4e5d-92b8-bcc7105c7ecf@h11g2000prf.googlegroups.com> d'oh! On 12 mar, 07:58, John Machin wrote: > On Mar 12, 10:29 pm, Bernard wrote: > > > > > Hey Larry, > > > that one is fairly easy: > > > >>> from array import array > > >>> array('i', [1, 2, 3, 4, 5, 1, 2]) > > >>> def count(x, arr): > > > ? ? ? ? cpt = 0 # declare a counter variable > > ? ? ? ? for el in arr: # for each element in the array > > ? ? ? ? ? ? ? ? if el == x: # when it is equal to the 'x' value > > ? ? ? ? ? ? ? ? ? ? ? ? cpt+=1 # increment the counter variable by one > > ? ? ? ? return cpt # return the counter after the loop>>> count(1,a) > > > 2 > > Hey Bernard, you have just laboriously reinvented the count method: > > > > >>> from array import array > >>> a = array('i', [1, 2, 3, 4, 5, 1, 2]) > >>> a.count(1) > 2 > > which Larry has already said doesn't do the job -- the job is to > create a histogram!! From mensanator at aol.com Wed Mar 5 15:34:28 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Mar 2008 12:34:28 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> <51f4bce3-8561-4149-9b3b-e436bbee8ee7@u69g2000hse.googlegroups.com> Message-ID: <1bcbee35-c5bf-4a6d-b68a-1eed87ffcf8d@p25g2000hsf.googlegroups.com> On Mar 5, 9:29?am, Nanjundi wrote: > On Mar 4, 3:13 pm, Mensanator wrote: > > > On Mar 4, 12:32 pm, Nanjundi wrote: > > > > Does seeding ( random.seed ) random with time fix this? It should. > > > I suppose that depends on how long it takes factorint() to > > process a number. If the seed is reset before the next clock > > tick, you will get the same random numbers as the previous > > iteration. > > Alright, then make it constant and don't worry about the clock tick. Reseeding with a constant always sets the sequence to the same starting point. >>> for i in xrange(10): > > ... ? f1 = random.choice(f) > ... ? print f1, > ... ? f2 = random.choice(f) > ... ? print f2, > ... ? C = f1*f2 > ... ? ff = None > ... ? ff = sympy.factorint(C) > ... ? print ff > ... ? random.seed(i) > ... > 5573 5171 [(5171, 1), (5573, 1)] > 8537 7673 [(7673, 1), (8537, 1)] > 2063 8573 [(2063, 1), (8573, 1)] > 9551 9473 [(9473, 1), (9551, 1)] > 2909 5659 [(2909, 1), (5659, 1)] > 2897 1789 [(1789, 1), (2897, 1)] > 6361 7541 [(6361, 1), (7541, 1)] > 8017 8293 [(8017, 1), (8293, 1)] > 3671 2207 [(2207, 1), (3671, 1)] > 2803 9629 [(2803, 1), (9629, 1)] > > > Frankly, I don't understand why factorint() reseeds at all. > > Read the doc: > * ? ?The rho algorithm is a Monte Carlo method whose outcome can be > affected by changing the random seed value. ?* But that doesn't give it the right to mess with the state of the random number generator _I'm_ using. Had I actually known what was happening, I could have saved the state of my random number generator s=random.getstate() and then restored it after calling factorint(), random.setstate(s). import sympy # with RK's patch removed import time import random f = [i for i in sympy.primerange(1000,10000)] for i in xrange(10): f1 = random.choice(f) print f1, f2 = random.choice(f) print f2, C = f1*f2 ff = None rs = random.getstate() ff = sympy.factorint(C) random.setstate(rs) print ff 5669 3863 [(3863, 1), (5669, 1)] 1973 5431 [(1973, 1), (5431, 1)] 7577 6089 [(6089, 1), (7577, 1)] 8761 4957 [(4957, 1), (8761, 1)] 4153 2719 [(2719, 1), (4153, 1)] 4999 5669 [(4999, 1), (5669, 1)] 8863 5417 [(5417, 1), (8863, 1)] 7151 7951 [(7151, 1), (7951, 1)] 7867 9887 [(7867, 1), (9887, 1)] 9283 5227 [(5227, 1), (9283, 1)] Of course, this is new as of Python 2.4, so if factorint() tried to save & restore state, sympy wouldn't work on Python 2.3 or earlier. If I'm reading RK's patch correctly, he doesn't reseed the random number generator, he creates a new random object that maintains it's own state that can be freely seeded to any value without disturbing the state of my random number generator. > > > Doesn't Random automatically initialize the seed? > > Doesn't constantly reseeding degrade the performance of the > > random number generator? With Robert Kern's patch, the reseeding > > is no longer a constant, fixing the immediate symptom. > > Does it matter? I was wrong. It is a constant, just not 1234. If that's what factorint() needs, fine. As long as it maintains a seperate state than the one I'm using. > The factorint reseeds using a constant seed (1234). Not now it doesn't: @@ -92,8 +92,8 @@ def pollard_pm1(n, B=10, seed=1234): """ from math import log - random.seed(seed + B) - a = random.randint(2, n-1) + prng = random.Random(seed + B) + a = prng.randint(2, n-1) for p in sieve.primerange(2, B): e = int(log(B, p)) a = pow(a, p**e, n) > > > But what if _I_ wanted to make a repeatable sequence for test > > purposes? Wouldn't factorint() destroy my attempt by reseeding > > on every call? > > Repeatable sequence? save it and reuse! As part of my resolution to tone down my attitude, I won't even reply to that. > Think about "What if"s doesn't get any work done. ? > > -N From iwanttobeabadger at googlemail.com Mon Mar 24 21:58:49 2008 From: iwanttobeabadger at googlemail.com (Nathan Harmston) Date: Tue, 25 Mar 2008 01:58:49 +0000 Subject: Calling a shared library using C types In-Reply-To: References: Message-ID: On 25/03/2008, Gabriel Genellina wrote: > > En Mon, 24 Mar 2008 19:56:08 -0300, Nathan Harmston > escribi?: > > > > import ctypes > > t = ctypes.CDLL('./Simulation.so') > > this works fine, I have a simple function I ve put in for testing which > > just > > returns the integer 4. However when I try to access this function it > > doesnt > > work > > t.test() > > File "", line 1, in > > File > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > line 325, in __getattr__ > > func = self.__getitem__(name) > > File > > > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > > line 330, in __getitem__ > > func = self._FuncPtr((name_or_ordinal, self)) > > AttributeError: dlsym(0x81e6b0, test): symbol not found > > > Looks like the symbol isn't public - probably if you try loading the > library with a C program it won't find it either. How is the function > declared in the source? > Try listing all public symbols with: nm -D Simulation.so Thanks for the quick reply: Running nm lists test as 00001760 T _test in the source its declared as: int test(){ return 4; } Sorry, this is the first time I'm making my own shared library and using ctypes, so being a little slow. Thanks again Nathan > Im hoping python-list is ok for questions regarding ctypes :S > > > It's not off topic, although there is a specific list for ctypes-related > questions. But hijacking a thread to post a completely different question > is not good netiquette. > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwolffedu at gmail.com Sat Mar 15 21:12:21 2008 From: mwolffedu at gmail.com (lampshade) Date: Sat, 15 Mar 2008 18:12:21 -0700 (PDT) Subject: os.path.isdir question Message-ID: Hello, I'm having some problems with os.path.isdir I think it is something simple that I'm overlooking. #!/usr/bin/python import os my_path = os.path.expanduser("~/pictures/") print my_path results = os.listdir(my_path) for a_result in results: if os.path.isdir(str(my_path) + str(a_result)): results.remove(a_result) for x in results: print x The problem is, that the directories are never removed. Can anyone point out what I'm missing that is causing the bug? Is there a better way of doing this? Thanks, From fakeaddress at nowhere.org Thu Mar 13 12:31:09 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 13 Mar 2008 16:31:09 GMT Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: Benjamin Watine wrote: > And if somebody need it : to get the stdout in a var (myNewVar), not in > the shell : > > cat = subprocess.Popen('cat', shell = True, stdin = subprocess.PIPE, > stdout=subprocess.PIPE) > cat.stdin.write(myVar) > cat.stdin.close() > cat.wait() > myNewVar = cat.stdout.read() > > Is it correct ? No, not really. It is prone to deadlock. The external program might work by iteratively reading a little input and writing a little output, as 'cat' almost surely does. If the size of myVar exceeds the buffer space in cat and the pipes, you get stuck. Your Python program can block at "cat.stdin.write(myVar)", waiting for cat to read from its input pipe, while cat blocks at a write to its output stream, waiting for you to start reading and freeing up buffer space. Pipe loops are tricky business. Popular solutions are to make either the input or output stream a disk file, or to create another thread (or process) to be an active reader or writer. -- --Bryan From grflanagan at gmail.com Tue Mar 25 11:24:19 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 25 Mar 2008 08:24:19 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: On Mar 25, 1:34 pm, Tzury Bar Yochay wrote: > > Rather than use Foo.bar(), use this syntax to call methods of the > > super class: > > > super(ParentClass, self).method() > > Hi Jeff, > here is the nw version which cause an error > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = super(Foo, self).getid() > b = self.id > return '%d.%d' % (a,b) > > FooSon().getid() > > Traceback (most recent call last): > File "a.py", line 19, in > FooSon().getid() > File "a.py", line 14, in getid > a = super(Foo, self).getid() > AttributeError: 'super' object has no attribute 'getid' Use the child class when calling super: -------------------------------------- class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = super(FooSon, self).getid() b = self.id return '%d.%d' % (a,b) print FooSon().getid() -------------------------------------- G. From jeff at schwabcenter.com Mon Mar 17 21:29:17 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 18:29:17 -0700 Subject: About reading Python code In-Reply-To: <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> Message-ID: sturlamolden wrote: > On 17 Mar, 04:54, WaterWalk wrote: > >> So I'm curious how to read code effectively. I agree that python code >> is clear, but when it becomes long, reading it can still be a hard >> work. > > First, I recommend that you write readable code! Don't use Python as > if you're entering the obfuscated C contest. Er, don't use anything other than C if you're entering an obfuscated C contest, or anything other Perl for an obfuscated Perl contest, etc. Do use Python if you're entering an obfuscated Python contest. Found online: [#[#[#[#[#[#[#[#[# By TaroOgawa #]#]#]#]#]#]#]#]#] globals() .update({ "______": lambda x: globals() .update(( dict([[x] *2])))}), ______((( "Just"))) ,______(( "another" )),______ ("Python" ),______( "Hacker") ];print ( " ".join( [(Just),( (another) ),(Python ),Hacker] ));______ > Two particularly important points: > > * If you find yourself thinking this module is too long, that's > probably what it is. Half a page of code per module is fine. Two pages > of code per module can be too much. > > * Comments are always helpful to the reader. If only 'twere so. *Good* comments are always helpful. Please do not comment every method with "this is a method" or the like. One of the things that often makes newb code stand out is that the programmer couldn't tell the things that needed to be commented from the places where comments just got in the way. > Second, I recommend getting a good IDE. E.g. pick one of: > > * Microsoft Visual Studio (commercial) > * Eclipse with PyDev and CDT (free) > * SPE (free) > * ActiveState Komodo IDE (commercial) * Vim on Linux. (No desire here to debate the meaning of IDE, but with Vim or Emacs on any Unix-like platform, the whole system effectively is the IDE.) From jeff_barish at earthlink.net Mon Mar 10 12:05:19 2008 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Mon, 10 Mar 2008 10:05:19 -0600 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: egbert wrote: > The idea of the if-else is: > . ?depending on some condition either do this or do something else, > . ?don't do them both. Indubitably, this statement is correct for other programming languages. I was initially surprised by loop-else when learning Python because I approached these constructs from the perspective of other programming languages I knew, as you are doing. Before rejecting the Python constructs, I asked myself whether the application of a different idea resulted in a consistent, sensible interpretation. The key is to ask not whether the Python constructs fit a particular idea of if-else and loop-else, but whether a reasonable idea exists within which the Python constructs make sense. For me and others in this thread, it does. Different keywords would, no doubt, result in constructs that fit other ideas better, but personally I am content with the current solution. -- Jeffrey Barish From robert.kern at gmail.com Tue Mar 18 18:16:30 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 Mar 2008 17:16:30 -0500 Subject: Any fancy grep utility replacements out there? In-Reply-To: References: Message-ID: samslists at gmail.com wrote: > So I need to recursively grep a bunch of gzipped files. This can't be > easily done with grep, rgrep or zgrep. (I'm sure given the right > pipeline including using the find command it could be done....but > seems like a hassle). > > So I figured I'd find a fancy next generation grep tool. Thirty > minutes of searching later I find a bunch in Perl, and even one in > Ruby. But I can't find anything that interesting or up to date for > Python. Does anyone know of something? I have a grep-like utility I call "grin". I wrote it mostly to recursively grep SVN source trees while ignoring the garbage under the .svn/ directories and more or less do exactly what I need most frequently without configuration. It could easily be extended to open gzip files with GzipFile. https://svn.enthought.com/svn/sandbox/grin/trunk/ Let me know if you have any requests. -- 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 tjreedy at udel.edu Sat Mar 8 20:46:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Mar 2008 20:46:29 -0500 Subject: Green's Function References: <501978.67770.qm@web53602.mail.re2.yahoo.com> Message-ID: "olusina eric" wrote in message news:501978.67770.qm at web53602.mail.re2.yahoo.com... | I am new to Python and trying to solve the Hamiltonian of a linear chair of atoms using green's function. | Does anyone know any pre-existing library functions and literature that could be helpful? Did you try searching for "Python Green's function"? From sturlamolden at yahoo.no Thu Mar 20 18:26:23 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 15:26:23 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> Message-ID: <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> On 20 Mar, 19:09, Craig wrote: > The following is the C++ prototype for one of the functions: > short FAR PASCAL VmxOpen(BSTR *Filespec, > LPSHORT lpLocatorSize, > LPSHORT lpOmode, > LPHANDLE lphwmcb, > BSTR *Password); import ctypes import comtypes LPBSTR = ctypes.POINTER(comtypes.BSTR) HANDLE = ctypes.POINTER(ctypes.POINTER(ctypes.c_long)) LPHANDLE = ctypes.POINTER(HANDLE) LPSHORT = ctypes.POINTER(ctypes.c_short) VmxOpen = ctypes.windll.vbis5032.VmxOpen VmxOpen.restype = c_short VmxOpen.argtypes = [LPBSTR, LPSHORT, LPSHORT, LPHANDLE, LPBSTR] Filespec = comtypes.BSTR('blahblahblah') LocatorSize = ctypes.c_short(256) Omode = ctypes.c_short(1) hwmcb = HANDLE() Password = comtypes.BSTR('blahblahblah') res = WmxOpen( byref(Filespec), byref(LocatorSize), byref(Omode), byref(hwmcb), byref(Password) ) or if that fails: pFilespec = ctypes.pointer(Filespec) pLocatorSize = ctypes.pointer(LocatorSize) pOmode = ctypes.pointer(Omode) phwmcb = ctypes.pointer(hwmcb) pPassword = ctypes.pointer(Password) res = WmxOpen( pFilespec, pLocatorSize, pOmode, phwmcb, pPassword ) From sajmikins at gmail.com Wed Mar 12 20:59:33 2008 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 12 Mar 2008 17:59:33 -0700 (PDT) Subject: Big file References: Message-ID: <0842cf80-eeaf-4bf1-85dc-c90e5ff27c43@i29g2000prf.googlegroups.com> On Mar 12, 5:42 pm, "Andrew Rekdal" wrote: > I am working in the class constructor defining elements of an application. The problem is the file is getting unmanageble and I am wanting to extend the contructor __init__ to another file. > > Is it possible to import directly into the contructor the contents of another module file? > > If so how would this be done? > > Thanks -- andrew First, you should consider breaking your __init__() method into smaller pieces (methods) and calling those from within __init__(). That said, you can add attributes to an instance by means of its __dict__ dict attribute: |>> class foo: |>> def __init__(self): |>> self.__dict__['hi'] = ['An object'] |>> print self.__dict__ |>> |>> f = foo() {'hi': ['An object']} |>> f.hi ['An object'] You might try: |>> exec 'from sys import *' in f.__dict__ Now everything in sys appears in f: |>> f.copyright 'Copyright (c) 2001-2006 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n \nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.' HTH, ~Simon From tim.tadh at gmail.com Wed Mar 26 15:10:29 2008 From: tim.tadh at gmail.com (Tim Henderson) Date: Wed, 26 Mar 2008 12:10:29 -0700 (PDT) Subject: A question on decorators Message-ID: Hello I am writing an application that has a mysql back end and I have this idea to simplify my life when accessing the database. The idea is to wrap the all the functions dealing with a particular row in a particular in a particular table inside a class. So if you have a table that looks like this: id str1 str2 pickled_data1 pickled_data2 0 woeif aposf (bin) (bin) 1 ofime powe (bin) (bin) ... n oiew opiwe (bin) (bin) you can access this table like this t = Table(id) #to load a pre-entered row t2 = Table(id, str1, str2, data1, data2) #to create a new row when you change a an attribute of the class like this... t.str1 = 'new value' it automatically updates the database backend. I have what I just described working. However I want an easier way to deal with my pickled_data. Right now I am pickling dictionaries and list types. Now there is one problem with this, let me demonstrate t.data.update({'new key':'new value'}) print t.data {... 'new key':'new value' ...} which makes it appear that the database has been updated as well, but in fact it hasn't to update the database with this scheme you actually have to do this. t.data.update({'new key':'new value'}) t.data = t.data this is not ideal so I subclassed the built in dict type like this: class _my_dict(dict): def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) self.update_db() def __delitem__(self, key): if self.write_access: dict.__delitem__(self, key) self.update_db() def __setitem__(self, key, value): if self.write_access: dict.__setitem__(self, key, value) self.update_db() def clear(self): if self.write_access: dict.clear(self) self.update_db() ... more methods which are simliar ... def update_db(self): if self.write_access: con = get_dbConnection() cur = con.cursor() table = self.experiment.TABLE row_index_name = self.row_index_name row_index = self.row_index column_name = self.column_name column_value = MySQLdb.escape_string(pickle.dumps(self)) q1 = '''UPDATE %(table)s SET %(column_name)s = '%(column_value)s' WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() cur.execute(q1) con.close() Now while this works, it is a lot of work. What I want to be able to do is something where I write one decorator function that automatically updates the database for me. So let us pretend I have this function. let: dec_update_db() be my decorator which updates the dictionary. to use this function it seems I would probably still have to subclass dict like this: class _my_dict2(dict): @dec_update_db def __init__(self, row_index_name, row_index, column_name, a=None, **kwargs): self.row_index_name = row_index_name self.row_index = row_index self.column_name = column_name self.write_access = True if (a == None): dict.__init__(self, kwargs) else: dict.__init__(self, a) @dec_update_db def __delitem__(self, key): dict.__delitem__(self, key) @dec_update_db def __setitem__(self, key, value): dict.__setitem__(self, key, value) @dec_update_db def clear(self): dict.clear(self) ... and so on ... this is also not ideal. because I still have to apply the decorator to every function which changes the dictionary. What I really want is a way to have the decorator applied automatically every time a method in dict or a sub class is called. I feel like this must be possible. Has any one here done anything like this before? Thank you for reading my long post, I hope you understand what I am asking especially since the code in it is not very good. cheers Tim Henderson From dave_mikesell at fastmail.fm Sat Mar 8 16:38:21 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 13:38:21 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: <7be573d9-d009-4ac9-8eb4-86c13d2d68c0@13g2000hsb.googlegroups.com> On Mar 8, 1:31 pm, Grant Edwards wrote: LOL. Thanks for the laughs. I share your frustration. From kkadrese at gmail.com Wed Mar 19 06:37:27 2008 From: kkadrese at gmail.com (kkadrese at gmail.com) Date: Wed, 19 Mar 2008 03:37:27 -0700 (PDT) Subject: lock access to serial port References: Message-ID: <78873650-1130-4be9-9ea7-3889036b2bbf@a23g2000hsc.googlegroups.com> not the goal setup but the way I tried it out - a webpage to send an sms to mobile phone. This is an php what calls a python script. A python script opens serial device, checks for gsm network, sends a message - on all the way I try to make sure that appropriate answers are received from the gsm device so that I know that all is going well (and if not - cancel it with error message). Testing it with sending an sms from two open webpages, I normally got that one message was sent and for the other I received "try once more, happened that and that". But I got also an inadmissible situation - the received sms contained also unwanted text. As far as I can realize how to deal with it is not allowing writing to the device for two processes simultaneously. Andra On 19 Marts, 11:00, taco wrote: > kkadr... at gmail.com wrote: > > hello group, > > > how to get ttyS0 serial port for exclusive access? I have a python > > script that uses this device with AT commands. I need that two > > instances can call simultaneosuly this python script but only one of > > them gets the device. I tried fcntl.flock, it was just ignored, put > > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not > > know what are appropriate arguments), googled half a day for various > > phrases, error messages etc....without success. > > > please help, > > > Andra > > not sure if I understand you well, but how about a server application which > accepts 2 clients which can send messages which are output on the serial > device? The serial device access protected with a mutex while receiving > messages done in 2 threads or something. > taco From paul at boddie.org.uk Thu Mar 13 20:34:23 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 13 Mar 2008 17:34:23 -0700 (PDT) Subject: EuroPython 2008: A Call for Theme and Talk Suggestions Message-ID: <57801aa4-ff53-41c3-9ffd-105d69304c70@s13g2000prd.googlegroups.com> This year, the EuroPython conference will take up residence for the second time in Vilnius, Lithuania with the main programme of talks and events taking place on Monday 7th, Tuesday 8th and Wednesday 9th July, and with sprints continuing after the main programme until and including Saturday 12th July. More information can be found on the updated EuroPython site, which can be found in the usual place: http://www.europython.org/ Last year, the conference focused on agile development, but also promoted many of the familiar categories: business, education, games, language and libraries, science, social skills and Web development. Of course, topics such as Web development remain as popular as ever, but we also saw strong contributions in other areas such as robotics and database systems. With this in mind, we would like to get feedback from anyone thinking of coming to EuroPython 2008 about the kind of topics they would like to see covered at the conference. Perhaps the arrival of Python 3.0 makes you wonder about how, when or even whether you might make the transition from Python 2.x or earlier to the new release series. Perhaps you want to know more about how Python is used in the "real world" and how others have deployed large systems written in Python. Or maybe you are fascinated with the potential for using Python on mobile devices. We welcome your thoughts and ideas, either on this list/group (just reply to this message!), on the EuroPython mailing list... http://mail.python.org/mailman/listinfo/europython ...or by becoming a contributor on the EuroPython Web site: http://www.europython.org/community/Participants Take a look at this page for some ideas that have already been proposed: http://www.europython.org/community/Talk_Suggestions And feel free to suggest specific talk ideas or even other kinds of activities which might enhance the conference experience, perhaps borrowed from conferences such as PyCon. Since EuroPython is a community conference, volunteers are welcome in many different areas: http://www.europython.org/community/Volunteers Why not step up and improve the EuroPython experience for yourself and for everyone else? Make EuroPython yours: get involved now! From jeff at schwabcenter.com Sat Mar 22 14:39:05 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 11:39:05 -0700 Subject: List question In-Reply-To: <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> Message-ID: Zentrader wrote: > On Mar 22, 10:07 am, Arnaud Delobelle wrote: >> On Mar 22, 4:38 pm, Zentrader wrote: >> >>>> if ('one', 'two') are in f: ... >>> "are" gives me an error in Python 2.5 with a "from future import *" >>> statement included. What version and platform are you running. Also, >>> the docs don't mention it.http://docs.python.org/ref/keywords.html >> That's because you have to do: >> >> from bearophile import musings >> >> HTH >> >> -- >> Arnaud > > Thanks. I am admittedly naive and don't have any type of guard up > when on this group for people who think that type of comment makes > them intelligent/funny. No one meant to laugh at you. Your naivete was not obvious. FWIW, a sense of humor is a valuable possession in most Python-related conversations. From castironpi at gmail.com Thu Mar 13 19:13:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 16:13:50 -0700 (PDT) Subject: newbie question structure of function References: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> Message-ID: <37088f9c-e68e-483e-92a3-e730411a79bf@2g2000hsn.googlegroups.com> Just some FYI options. > ? ? if not matchfilename: May return positive if you someday return an object that holds a 'not' value. > ? ? resultname=""" That starts a string literal. > if (matchdistance < threshold): Parentheses optional. > ? ? return (matchdistance,resultname) Parentheses optional there too. "return matchdistance," returns a 'one-tuple'. From gygulyas at gmail.com Wed Mar 19 22:04:27 2008 From: gygulyas at gmail.com (Gyula) Date: Wed, 19 Mar 2008 19:04:27 -0700 (PDT) Subject: ADO error - large data set References: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> <9qgEj.4646$6H.3740@newssvr22.news.prodigy.net> Message-ID: <7ce74b92-8018-46b7-a1ce-bde2cb1186b9@s19g2000prg.googlegroups.com> Ok. After several tries, I think I found out why it breaks and it has nothing to do with the number of records... Here is the code/ see notes below: ######################### code starts here # First import wincom32 client from win32com.client import * # Create the ADO Connection object via COM oConn = Dispatch(r'ADODB.Connection') # Now set the connection properties via the ConnectionString oConn.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" + \ "DATA SOURCE=C:/Documents and Settings/user/Desktop/PythonWS/data/ anydata.mdb;" # Now open the connection oConn.Open() # create a recordset rs = Dispatch(r'ADODB.Recordset') rs.Open('SELECT TOP 300 * FROM input;', oConn, constants.adOpenStatic, constants.adLockOptimistic) rs.MoveFirst() counter = 1 while not rs.EOF: print counter # do nothing, just cycle through counter += 1 rs.MoveNext() # cleanup rs.Close() rs = None oConn.Close() oConn = None print 'Done!' ##################### code ends here the line where it breaks: rs.Open('SELECT TOP 300 * FROM input;', oConn, constants.adOpenStatic, constants.adLockOptimistic) 'input' is supposed to be the table name, but it breaks in Python when you want to open the recordset. I need to use: rs.Open('SELECT TOP 300 * FROM [input];', oConn, constants.adOpenStatic, constants.adLockOptimistic) as input is an SQL keyword...arrrrrgh. Gyula On Mar 19, 5:17 pm, Gyula wrote: > Thanks! I will give it a try. It seems though that I get stuck on > rs.Open that makes no sense. I was wondering about pagesize or other > registry settings that might cause this? Will try to track down any > bad data first... > gg > > On Mar 19, 3:27 pm, "dsavitsk" wrote: > > > Is it possible there is some bad data in the larger db? This is asinine, but > > maybe write a small script that adds some data, then opens and closes the > > db, then repeats this. If this is a size issue, then you can at least narrow > > it down to where the size limit is? And, if it isn't you should be able to > > figure that out, too. Otherwise, play around with the locking and cursor > > options. > > > -d > > > "Gyula" wrote in message > > >news:475c155d-fe16-472f-a4f8-363f6db339eb at d21g2000prf.googlegroups.com... > > > > Hi there, > > > > I have been running Python to tap into an MS Access 2003 database > > > using ADO (PythonWin+COM). Everything works great creating recordsets > > > etc. when I open a table with a small number of records. However, when > > > I try to run the same Python code with a large table (>100,000) I get: > > > > Traceback (most recent call last): > > > File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework > > > \scriptutils.py", line 310, in RunScript > > > exec codeObject in __main__.__dict__ > > > File "C:\Documents and Settings\user\Desktop\PythonWS\scripts > > > \readmsaccess.py", line 43, in > > > rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) > > > File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- > > > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open > > > , ActiveConnection, CursorType, LockType, Options) > > > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > > > 5003251, -2147467259), None) > > > > The small and large table structures are identical, all I do is change > > > the tblname from input1000 (1000 records) to input (>100000 records). > > > I use optimistic locking and keyset cursor..nothing out of the > > > ordinary? > > > > Any ideas? ADO 2.8 is what I am using. > > > > Thanks a lot! > > > GG ' From tjreedy at udel.edu Sat Mar 22 21:13:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Mar 2008 21:13:40 -0400 Subject: Problem with complex numbers References: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> <47E58836.70202@cheimes.de> Message-ID: "Christian Heimes" wrote in message news:47E58836.70202 at cheimes.de... | Well, the file is in the Demo folder. It's just a demo how to implement a naive complex type in Python. | Why do you think the power of a complex to a complex is not defined? I suspect because the naive implementation raise TypeError for that case. From Sebastien.Boisgerault at gmail.com Mon Mar 3 13:40:54 2008 From: Sebastien.Boisgerault at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Boisg=E9rault?=) Date: Mon, 3 Mar 2008 10:40:54 -0800 (PST) Subject: News from Jython world Message-ID: Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a key Jython developer and is specifically hired to work full time on Jython, a version of the Python interpreter that runs on top of the JVM and provides full access to Java libraries. After a period where the development had slowed, Jython was recently getting seriously back on track. Now it's getting even better ! Don't wait too much ... Jython is very useful RIGHT NOW if you live in the Java Universe. More details at: - http://www.infoworld.com/article/08/03/03/hirings-python_1.html - http://fwierzbicki.blogspot.com/2008/02/jythons-future-looking-sunny.html Cheers, SB From hdante at gmail.com Wed Mar 12 21:37:39 2008 From: hdante at gmail.com (hdante) Date: Wed, 12 Mar 2008 18:37:39 -0700 (PDT) Subject: Big file References: Message-ID: On Mar 12, 9:42 pm, "Andrew Rekdal" wrote: > I am working in the class constructor defining elements of an application. The problem is the file is getting unmanageble and I am wanting to extend the contructor __init__ to another file. > > Is it possible to import directly into the contructor the contents of another module file? > > If so how would this be done? > > Thanks -- andrew class BigObject: import my_module def __init__(self): self.my_module.do_this() --------------------------------------- class BigObject(MyUtils): def __init__(self): self.things_from_utils() From shaq.koby at gmail.com Sat Mar 15 15:52:35 2008 From: shaq.koby at gmail.com (shaq.koby at gmail.com) Date: Sat, 15 Mar 2008 12:52:35 -0700 (PDT) Subject: Cannot install SOAPpy Message-ID: <1a00b6b8-fb18-4189-8572-946e22f1774c@e39g2000hsf.googlegroups.com> I installed SOAPpy on my server with Python 2.5. But now everytime I exit, I get the following error: Exception exceptions.AttributeError: '_shutdown' in ignored Here is the command line output: mhagen at sebastian:~$ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import SOAPpy >>> exit Use exit() or Ctrl-D (i.e. EOF) to exit >>> Exception exceptions.AttributeError: '_shutdown' in ignored From castironpi at gmail.com Fri Mar 21 09:14:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 06:14:42 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> Message-ID: <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> On Mar 20, 9:28?am, "Jerry Hill" wrote: > On Thu, Mar 20, 2008 at 3:42 AM, Steven D'Aprano > > wrote: > > On Wed, 19 Mar 2008 23:06:44 -0700, royG wrote: > > > ?> suppose > > ?> origsz=(400,300) > > ?> i want to divide the origsize by 2.5 so i can resize to (160,120) > > > ?> scale=2.5 > > ?> how can i get the newsz? > > ?> obviously origsz/2.5 won't work ?.. > > > ?newsz = (origsz[0]/scale, origsz[1]/scale) > > That works fine for a 2-tuple, but might get unwieldy for larger > tuples, or if you don't know the length until runtime. ?A more general > solution might use a generator expression, like this: > > newsz = tuple(x/scale for x in origsz) You want to perform a uniform call on the elements of a collection. "Diagram A" appends 0 to every item of a list. >>> y= [ [] for k in range( 10 ) ] >>> def x( fun, *ar, **kw ): ... def post( *xr, **xw ): ... return fun( *(xr+ ar), **kw ) ... return post ... >>> x( list.append, 0 )( y[0] ) >>> y [[0], [], [], [], [], [], [], [], [], []] >>> x( list.pop, 0 )( y[0] ) 0 >>> y [[], [], [], [], [], [], [], [], [], []] >>> list( map( x( list.append, 0 ), y ) ) [None, None, None, None, None, None, None, None, None, None] >>> y [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]] If the elements are immutable, >>> y= [ () for k in range( 10 ) ] >>> list( map( x( tuple.__add__, ( 0, ) ), y ) ) [(0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,), (0,)] you get your new list from map. Here it is with integer elements: >>> y= ( 300, 400 ) >>> tuple( map( x( int.__add__, 1, ), y ) ) (301, 401) --You could spell the call like this: latemap( y, int.__add__, 1 ) With mul: >>> tuple( map( x( int.__mul__, 2, ), y ) ) (600, 800) It's like partial, but the argument addition is commuted. The key is that 'y' is going in the first slot, as 'self'. It's not clear that argument addition commution applies (matches, is correct, generalizes with right meaning): you just want the first parameter to come from a separate call. Other uses cases of the generalizer might not align. + a fraction on 'x'. Floats get harder, since you're looking at composition. >>> tuple( map( compose( float, x( float.__mul__, 1/ 2.5 ) ), y ) ) (120.0, 160.0) # (160, 120) +1 compose. def compose( *f ): def post( *ar, **kw ): if len( f )> 1: return f[0]( compose( *f[1:] )( *ar, **kw ) ) return f[0]( *ar, **kw ) return post From dblubaugh at belcan.com Mon Mar 10 10:19:25 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 10 Mar 2008 10:19:25 -0400 Subject: Python To C Module Generator Stand-Alone Executable Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3802AF98F0@AWMAIL04.belcan.com> Does anybody know if the Python To C Module Generator is of any value? Has anyone found or developed a means to convert python source code into c source code, where an algorithm that has been developed in python, can now be converted to C in order to develop a stand alone application? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjourne at gmail.com Wed Mar 19 18:35:31 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 19 Mar 2008 22:35:31 +0000 Subject: removing all instances of a certain value from a list In-Reply-To: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Message-ID: <740c3aec0803191535t57690621rd377512db5d60a83@mail.gmail.com> On Wed, Mar 19, 2008 at 10:28 PM, Lee Sander wrote: > Hi, > I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are > many missing vlaues which are represented as None. I would like to > remove all such instances in one go. > There is a remove function but it removes only the first instance, is > there a delete/remove all function? > thanks If it is ok to copy the list instead of mutating it, use a list comprehension: >>> L = [-1.3, 1.22, 9.2, None, 2.3] >>> [x for x in L if x is not None] [-1.3, 1.22, 9.1999999999999993, 2.2999999999999998] -- mvh Bj?rn From nick at craig-wood.com Mon Mar 10 10:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 10 Mar 2008 09:30:03 -0500 Subject: Writing Memory to File References: Message-ID: Stefan Wagner wrote: > I'm trying to do some memory analyzing stuff, i wrote me a small .c so > far to dump the memory to a file for later analysis, > the analyzing part itself is python code. > I wonder if any of you has an idea how to dump the whole memory in > Linux/Windows from python ? > Using the .c for this somehow doesn't look right and comfy ;-) The whole memory of what? Under linux : If you want the whole physical memory of the system then you can dump /dev/mem You can dump the memory of an individual process using the ptrace interface. Both those things will require the relevant rights and neither is quite as easy as you might hope for! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From yoz at home.havin.us Thu Mar 13 14:56:27 2008 From: yoz at home.havin.us (yoz) Date: Thu, 13 Mar 2008 18:56:27 GMT Subject: List mutation method gotcha - How well known? In-Reply-To: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> References: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> Message-ID: Dustan wrote: > On Mar 13, 2:36 am, "Hendrik van Rooyen" wrote: >> Hi, >> >> I am surprised that it took me so long to bloody my nose on this one. >> >> It must be well known - and I would like to find out how well known. >> >> So here is a CLOSED BOOK multiple choice question - no RTFM, >> no playing at the interactive prompt: >> >> Given the following three lines of code at the interactive prompt: >> >> foo = [1,2,3,4] >> x = foo.append(5) >> print x >> >> What will be the output (choose one): >> >> 1) [1,2,3,4] >> 2) [1,2,3,4,5] >> 3) That famous picture of Albert Einstein sticking out his tongue >> 4) Nothing - no output >> 5) None of the above > > 5. This will cause a hidden feature of python and the OS, known as the 'python easter egg', to activate - erasing all data on the hard disk and then reporting how many bytes of data are left. Usually "None" ;-} - This really is a 'gotcha'.... (Aren't you sorry you cheated and typed this in !!) So the answer is 5 ? From dave_mikesell at fastmail.fm Sun Mar 2 19:23:10 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sun, 2 Mar 2008 16:23:10 -0800 (PST) Subject: Run Python app at startup References: Message-ID: On Mar 2, 3:37 pm, "SMALLp" wrote: > Hy. > I create simple application. Yust an windows and "compile" it with > py2exe. I add registry value > reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v > MyApp /t REG_SZ /d C:\myapp.exe /f' > > And it wont start. When i use console instead od window in py2exe i get > console opend but it closes. > > Program: > > import os > import wx > > app = wx.App() > frame = wx.Frame(None, -1, "MyFrame") > frame.Show() > > app.MainLoop() > > > Then in commang prompt: > > python.exe setup.py py2exe > > > from distutils.core import setup > import py2exe > > setup(console=['prog.py']) > Don't you have to include the wxPython code somehow, perhaps on the command line when building the exe? From castironpi at gmail.com Sun Mar 9 17:04:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:04:01 -0700 (PDT) Subject: parralel downloads References: <50047985-ed16-46cb-a933-8afddac6a056@y77g2000hsy.googlegroups.com> Message-ID: <8a2e744e-6ecf-4bb5-8abc-8e0627c81da4@13g2000hsb.googlegroups.com> > > > >> ?my problem is that I would like to download several files at the time. > > > >> ?As I have not much experience in programming, could you point me the > > > >> ?easier ways to do this in python ? > > > Thank you both for your help. Threads are working for me. However, a > > new problem for me is that the url I want to download are in an xml > > file (I want to download podcasts), and is not the same as the file > > downloaded: > > >http://www.sciam.com/podcast/podcast.mp3?e_id=86102326-0B1F-A3D4-74B2... > > > will be redirected to download: > > >http://podcast.sciam.com/daily/sa_d_podcast_080307.mp3 > > > is there a way, knowing the first url to get the second at runtime in > > my script ? > > Found it: geturl() does the job That's for normalizing schemes. I believe you subclass FancyURLopener and override the read method. From duncan.booth at invalid.invalid Tue Mar 18 05:47:56 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Mar 2008 09:47:56 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> <646uapF2at163U1@mid.uni-berlin.de> <13tst1388cp67d8@corp.supernews.com> <47de9f6c$0$2657$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > On Mon, 17 Mar 2008 16:03:19 +0000, Duncan Booth wrote: > >> For the answer I actually want each asterisk substitutes for exactly one >> character. > > Played around a bit and found that one: > > Python 3.0a3+ (py3k:61352, Mar 12 2008, 12:58:20) > [GCC 4.2.3 20080114 (prerelease) (Debian 4.2.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = 1 >>>> b = 1//1 >>>> if a is b: print('yes!') > ... >>>> b > 1 >>>> type(b) > I've had a look to see why this happens: long division (and in Python 3 all integers are longs) allocates a new long to hold the result of the division so it will never use one of the preallocated 'small int' values. That makes sense so far as it goes, but I'm slightly suprised if it isn't worth an extra check somewhere for numerator fitting in a machine int and shortcutting the long division. From tew24 at spam.ac.uk Thu Mar 6 06:33:55 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 06 Mar 2008 11:33:55 +0000 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: Tom Wright wrote: > If someone has worked their way through this maze before and has an > answer, I'd be keen to hear it. Hmm, an answer of sorts: Inkscape's Windows build comes with MSVCR70.dll and MSVCR71.dll (but not MSVCP71.dll). As it's a big and high-profile project distributed under GPL2, I think they must've done their homework. Let's hope I'm ok in slightly different circumstances: distributing MSVCP71.dll as well, and under GPL3. -- I'm at CAMbridge, not SPAMbridge From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 07:15:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 12:15:17 -0000 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> Message-ID: <13t2celd4h80i7f@corp.supernews.com> On Thu, 06 Mar 2008 06:30:41 -0800, Carl Banks wrote: > On Mar 5, 8:44 pm, Steven D'Aprano cybersource.com.au> wrote: >> But what about classes? Are they singletons? Obviously classes aren't >> Singleton classes, that is, given an arbitrary class C you can create >> multiple instances of C. But what about class objects themselves? I've >> found a few odd references to "classes are singletons", but nothing in >> the language reference. > > > Probably because "singleton" is the wrong word. A singleton means there > is one instance of a type; classes are instances of "type" which can > have many instances so classes are not singletons. Right. I knew there was something funny about using the term "singleton" to refer to classes, but I couldn't put my finger on it. [snip] > For that matter, try this: > >>>>import module >>>>c1 = module.Someclass >>>>module.Someclass = some_other_class() >>>>c2 = module.Someclass >>>>c1 is c2 That example is cheating because you rebind the *name* module.Someclass. Of course you get something different. But in any case, I'm satisfied now... the name singleton is inappropriate for modules and classes, although they are both singleton-like. I like Gabriel's term "named singleton" (from another thread). Thank you to everybody who answered. -- Steven From coolman.guron at gmail.com Sat Mar 8 05:27:12 2008 From: coolman.guron at gmail.com (coolman.guron at gmail.com) Date: Sat, 8 Mar 2008 02:27:12 -0800 (PST) Subject: help on file storage for split multi part download References: Message-ID: <0c422a07-3c07-499f-87da-f82a6a81ed52@s37g2000prg.googlegroups.com> On Mar 7, 2:14 pm, "Gabriel Genellina" wrote: > En Fri, 07 Mar 2008 04:16:42 -0200, escribi?: > > > > > On Mar 7, 1:38 am, "Gabriel Genellina" wrote: > >> En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: > > >> > storage class which can write the file splits that are currently being > >> > downloaded to the disk. this is exactly what otherdownload > >> > accelerators do, i guess. > > >> Uh, unless I misundersand you, a standard file object is enough. First > >> create a file with the required size (open(...,'wb'), seek(n-1), > >> write(chr(0))). For each downloaded chunk you have to know its position > >> in > >> the file; then just seek() and write() it. > > > BUT the thing thats going in my mind is thread safety. i plan to start > > each part of the filedownloadin a different thread. and then when > > each thread had downloaded more than 100kb (or eof or boundary > > reached) write the buffer to the disk. can this be achieved using > > mutex ? i have never shared objects between threads. > > Use a different (single) thread to write the file; the others put write > requests on a Queue.queue object, and the writer just gets the requests > and processes them. > > > is there a way to write this without using threads at all ??? > > Using asyncore, and perhaps the Twisted framework. > > -- > Gabriel Genellina asyncore is basically a server thing right? From iteration.nth at gmail.com Thu Mar 20 00:34:44 2008 From: iteration.nth at gmail.com (iteration.nth at gmail.com) Date: Wed, 19 Mar 2008 21:34:44 -0700 (PDT) Subject: keeping state in an iterator object by rebinding next() References: Message-ID: <691a1267-0407-43e4-96d3-d58467af8614@59g2000hsb.googlegroups.com> On Mar 19, 3:36 pm, Wilbert Berendsen wrote: > Hi, > > i am writing a simple parser, that generates tokens. The parser needs to > maintain some state, because some parts of the file consist of different > tokens. I thought the object could simply remember its state by assigning > it's next() method to the method that is currently parsing. When the state > changes, the called method rebinds next() and the next token will be returned > by that function. Here's an example, proving that this indeed works. > > >>> class A: > > ... def a(self): > ... self.next = self.b > ... return 1 > ... def b(self): > ... self.next = self.a > ... return 2 > ... def __iter__(self): > ... return self > ...>>> a=A() > >>> a.a() > 1 > >>> a.next() > 2 > >>> a.next() > 1 > >>> j=0 > >>> for i in a: > > ... j += 1 > ... if j > 10: break # prevent from running endlessly > ... print i > ... > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 > > > > my question is: is this legal Python? An iterator could save the next() method > object, and in that case it could stop working.... It works now, because > apparently the for- construct resolves 'next' each time for the object before > calling it. > > The other solution would be just jumping to the correct method from within the > next() method. But that gives an extra call... > > Met vriendelijke groet, > Wilbert Berendsen > > --http://www.wilbertberendsen.nl/ > "You must be the change you wish to see in the world." > -- Mahatma Gandi """" "You must be the change you wish to see in the world." -- Mahatma Gandi """" JFYI: Mahatma Gandhi (NOT Gandi). From castironpi at gmail.com Sat Mar 29 19:37:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 29 Mar 2008 16:37:05 -0700 (PDT) Subject: Can anyone help me? Message-ID: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> I have this. 'pycaster.py' works. 'spherecollide.py' doesn't. C:\Documents and Settings\usr\My Documents\inbin\SphereCollide> \programs\python2 5\python SphereCollide.py Traceback (most recent call last): File "SphereCollide.py", line 39, in dlWorld, dlSpheres, dlFakeshadow = Objects.main() File "C:\Documents and Settings\usr\My Documents\inbin\SphereCollide \Objects.p y", line 11, in main GL_RGBA, GL_UNSIGNED_BYTE, Data ) File "C:\programs\Python25\Lib\site-packages\OpenGL\wrapper.py", line 1624, in __call__ return self.finalise()( *args, **named ) File "C:\programs\Python25\Lib\site-packages\OpenGL\wrapper.py", line 924, in wrapperCall raise err OpenGL.error.GLError: GLError( err = 1281, description = 'invalid value', baseOperation = glTexImage2D, pyArgs = [ GL_TEXTURE_2D, 0, GL_RGBA, 200, 200, 0, GL_RGBA, GL_UNSIGNED_BYTE, '\x80\x80\x80\xff\x80\x80\x80\xff\x80... ], cArgs = [ GL_TEXTURE_2D, 0, GL_RGBA, 200, 200, 0, GL_RGBA, GL_UNSIGNED_BYTE, '\x80\x80\x80\xff\x80\x80\x80\xff\x80... ], cArguments = ( GL_TEXTURE_2D, 0, GL_RGBA, 200, 200, 0, GL_RGBA, GL_UNSIGNED_BYTE, c_void_p(189956812), ) ) C:\Documents and Settings\usr\My Documents\inbin\SphereCollide> From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 09:06:17 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 15:06:17 +0100 Subject: Can one get "for x in y" to work for non builtin classes? Message-ID: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Hi I'm making a kind of ordered dictionary class. It is not exactly a dictionary, but it uses a list and dictionary to store the data. Something like: class dbase(list): '''Database class keeping track of the order and data''' def __init__(self): self.__data = {} self.__order = [] self.__uniq_id = 0 I'm just wondering if it is possible to get my class to work so that if one do: d=dbase() d.append("Data") d.append([1,2]) one can do like this to iterate over the data. for x in d: ... I'm looking at the list class but I don't quite understand from pydoc which __ __ methods I have to implement to get the above to work. Thanks in advance Preben From gagsl-py2 at yahoo.com.ar Tue Mar 25 22:02:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 23:02:08 -0300 Subject: My python interpreter became mad ! References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> <47E99C99.2060401@lexicon.net> <3a4a8f930803251814t3043f724v913bcc9e7aa7bf6e@mail.gmail.com> Message-ID: En Tue, 25 Mar 2008 22:14:39 -0300, Furkan Kuru escribi?: > I did not think he/she/anyone would ask the question in the main thread > without trying the interpreter a few times starting it from different > directories. Perhaps *you* would do that, but that is far beyond a newbie would do. Most newbies are lost enough to not even be able to ask the question in the first place. If the book doesn't tell anything about the directory, why should the starting directory be relevant? Why should I care not to use a reserved name to save my script? Where is that list of reserved names? -- Gabriel Genellina From gygulyas at gmail.com Wed Mar 19 12:14:49 2008 From: gygulyas at gmail.com (Gyula) Date: Wed, 19 Mar 2008 09:14:49 -0700 (PDT) Subject: ADO error - large data set Message-ID: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> Hi there, I have been running Python to tap into an MS Access 2003 database using ADO (PythonWin+COM). Everything works great creating recordsets etc. when I open a table with a small number of records. However, when I try to run the same Python code with a large table (>100,000) I get: Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\user\Desktop\PythonWS\scripts \readmsaccess.py", line 43, in rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open , ActiveConnection, CursorType, LockType, Options) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 5003251, -2147467259), None) The small and large table structures are identical, all I do is change the tblname from input1000 (1000 records) to input (>100000 records). I use optimistic locking and keyset cursor..nothing out of the ordinary? Any ideas? ADO 2.8 is what I am using. Thanks a lot! GG From ccomb at free.fr Sun Mar 23 21:40:16 2008 From: ccomb at free.fr (Christophe Combelles) Date: Mon, 24 Mar 2008 02:40:16 +0100 Subject: PyCon FR - =?UTF-8?B?Sm91cm7DqWVzIFB5dGhvbg==?= Message-ID: <47E70680.8000709@free.fr> PyCon FR will take place in Paris, France, 17-18 May 2008. The French Python Association (AFPY) is organizing this event called "Journ?es Python" for the second time. We expect most talks to be in french, but any proposal in english is also greatly welcome! You may submit your idea of talks and presentations now, either here if you speak french: http://fr.pycon.org/actualites/appel-a-propositions/ , or here if you don't : pycon -at- afpy.org Topics: We're expecting talks about anything related to the Python programming language, including: * the language and its libraries * the web technologies * Python in scientific computing * game programming * development environnement setup * agile programmnig and tests The expected audience will span on any level, from the beginner to the expert. Thus, your talk may fit even to beginners and will be welcome. Other formats: As well as regular talks, we will host tutorials about Python programming for beginners, and we may include 15-minutes lightning talks on any topic you want to talk about (e.g.: a project you're working on). You may submit debate topics for open discussions too. Important dates: * March, 7th : Call for papers * March, 30th : Paper submissions are closed * April 4th : Final schedule publication How to get involved? If you want to attend as a simple visitor, please register on this page to help us count the expected audience: * http://fr.pycon.org/inscription To submit a talk, tutorial, etc., please register with the link above, and fill the following form: * http://fr.pycon.org/contact/proposition-de-presentation For any information about the event, go to: * http://fr.pycon.org get in touch with the organization team via: pycon -at- afpy.org See you soon! --'AFPy Team. From gagsl-py2 at yahoo.com.ar Sun Mar 16 17:03:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 19:03:46 -0200 Subject: Weight Problem References: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> Message-ID: En Sat, 15 Mar 2008 18:57:36 -0200, Ravi Kumar escribi?: > An Interesting problem, > """ > A man has only 4 bricks of different weights, lies between 1-40KG, > Also, the total weights of Brick A, B, C, D (ie A+B+C+D) is 40KG. > The man uses that brick to calculate every possible weight > from 1 KG to 40 KG in his shop. (only whole numbers 1KG, 2KG etc, not > like > 2.3KG) > """ > > I thought it would really be good to solve it by python, and right now on > the mid-way solving using very dirty approach. > But I feel, using SETs with python in such would solve it better. > Can anyone come with good solution, and maybe solution showing usage of > Sets. This isn't specifically Python problem; some hints anyway: a) Any integer can be written as a base-3 number (anyone knows base-10 numbers, and you know base-2/binary numbers, I presume). x = a[n]*3**n + a[n-1]*3**(n-1) + ... + a[1]*3 + a[0] where all a[i] are either 0, 1 or 2 b) 2*3**n = (3-1)*3**n = 3**(n+1) - 3**n So you can replace every a[i]==2 in the a) expression with (-1), adding +1 to the coefficient to the left (why?). You end up with an expression involving only +1 and -1 coefficients (why?) c) You can compare, add and substract weights using an old two-plate balance. -- Gabriel Genellina From darcy at druid.net Tue Mar 25 10:21:13 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 25 Mar 2008 10:21:13 -0400 Subject: sendmail should throw an exception but does not In-Reply-To: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> References: <7071df9d-906c-40a9-9cb7-47b87d7dccd4@p25g2000hsf.googlegroups.com> Message-ID: <20080325102113.d8688b7f.darcy@druid.net> On Tue, 25 Mar 2008 06:39:57 -0700 (PDT) Clodoaldo wrote: > I need to know if an email was refused for whatever reason, it makes > no difference. > > The email is sent to an email address that does not exist in a foreign > domain. I can see in the postfix log that the email was sent and > bounced with the error code 550. That's the sendmail daemon, not your program. > The problem is that sendmail should throw an exception but it does > not. And the returned dictionary is empty as if the email was > accepted. > > d = smtpserver.sendmail(sender, recipient, m.as_string()) What this does is connect to your sendmail server and submit the email for sending. The server accepts the email and queues it up as asked. No error here. > I guess that the error code returned by the destination mail server is > not is not forwarded to the client by my mail server. It can't. By the time it finds out that there is a problem you have already closed the connection to the sendmail server. To do what you want you have to connect to the remote server yourself. This is a more complicated operation and there are still problems. First of all, your ISP may not allow you to connect to remote mail servers. Second, some [broken] mail servers will accept your email and only check and bounce after you have disconnected. I'm not sure what you are trying to do but you may want to consider using an Error-to: header that points to an email robot and manage bounces asynchronously. -- 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 hyena at gmail.com Sat Mar 15 20:14:19 2008 From: hyena at gmail.com (sun) Date: Sun, 16 Mar 2008 01:14:19 +0100 Subject: how can pulldom save to xml file? Message-ID: <9c6ce$47dc665c$5039443c$23160@news1.tudelft.nl> I have a large xml file parsed by pulldom. I did some editing on some node,change attributes and remove some child node, how do I save it back to this xml file or write a new xml file? The save method in minidom does not work for pulldom. Thanks From gagsl-py2 at yahoo.com.ar Thu Mar 27 15:55:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 16:55:09 -0300 Subject: How to take snap shot of the of project screen in Python References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 15:24:05 -0300, Praveena Boppudi (c) escribi?: > Can anyone help me out? What is "the project screen"? Do you want your development session using any IDE? Your running program? What platform? OS? Console or graphical application? Why using Python? -- Gabriel Genellina From grflanagan at gmail.com Thu Mar 20 07:09:51 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Thu, 20 Mar 2008 04:09:51 -0700 (PDT) Subject: Script Request... References: <64ccfbF2bbfckU1@mid.uni-berlin.de> Message-ID: <147cf9cb-f5c6-44fc-99cf-d846d04068ca@h11g2000prf.googlegroups.com> On Mar 19, 10:29 pm, some one wrote: > Thanks Diez, I found some docs and examples on urllib2. Now how do i > search the string I get from urllib2, lets say I put it in "myURL", How > do I search for only Numbers and ".'s" in the "#.#.#.#" pattern. That > is all I am interested in with all the data retrieved. Just the IP > Address from amongst a bunch of data that I have no use of currently. > > I would I write a pattern matching function to extract only the IP > address from "myURL"? > See the subsection titled 'Matching An IP Address', here: http://www.oreilly.com/catalog/regex/chapter/ch04.html Gerard > > > Show us your concrete efforts, and we will suggest improvements. > > > Diez From mcphail_colin at hotmail.com Wed Mar 12 14:43:32 2008 From: mcphail_colin at hotmail.com (CMcP) Date: 12 Mar 2008 18:43:32 GMT Subject: [pysqlite] [ANN] pysqlite and APSW projects moved References: <47D42EED.8070107@ghaering.de> Message-ID: In article Gerhard H?ring wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > Gerhard H?ring wrote: >> [...] APSW >> ==== >> >> web: http://oss.itsystementwicklung.de/trac/apsw/ >> scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ > That should have been > http://oss.itsystementwicklung.de/svn/apsw/apsw/ > - -- Gerhard > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX > V7sH3uAskDDNBuxYG34vExI= > =IXOx > -----END PGP SIGNATURE----- Hi, I'm getting a 404 Not Found trying to get to the APSW web page: Not Found The requested URL /svn/apsw/apsw/ was not found on this server. Apache/2.2.4 (Ubuntu) DAV/2 PHP/5.2.3-1ubuntu6.3 mod_ssl/2.2.4 OpenSSL/0.9.8e mod_wsgi/1.3 Python/2.5.1 Server at oss.itsystementwicklung.de Port 80 Regards, --CMcP -- I'm trying a new usenet client for Mac, Nemo OS X. You can download it at http://www.malcom-mac.com/nemo -- Posted via a free Usenet account from http://www.teranews.com From godzillaismad at gmail.com Tue Mar 18 06:43:29 2008 From: godzillaismad at gmail.com (Godzilla) Date: Tue, 18 Mar 2008 03:43:29 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> Message-ID: <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> Thanks Roel. If there is a way to pass in the PRESERVE_PRECISION constant in the python time.clock library, that would be great. But I'm afraid it's not possible. I think I will change away from using time.clock() from now on... seems too edgy to me. Thank you for sharing your experience with me nonetheless. Cheers mate. From julius.welby at gmail.com Fri Mar 28 02:44:31 2008 From: julius.welby at gmail.com (jwelby) Date: Thu, 27 Mar 2008 23:44:31 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> Message-ID: On Mar 28, 5:38 am, ankitks.mi... at gmail.com wrote: > >>> dict = {'M':3, 'R':0, 'S':2} > >>> print dict > > {'S': 2, 'R': 0, 'M': 3} > > now if I wanted sorted values in list, i am not able to do this>>> print dict.values().sort() > > None > > it returns None instead of [0, 2, 3] The sort method works by sorting 'in place'. That means it doesn't return the sorted value, but just sorts the sequence. >>> t = {'M':3, 'R':0, 'S':2} >>> x = t.values() >>> x.sort() >>> x [0, 2, 3] or you can use sorted(), which does return the sorted sequence: >>> sorted(t.values()) [0, 2, 3] From waltbrad at hotmail.com Fri Mar 7 15:38:11 2008 From: waltbrad at hotmail.com (waltbrad) Date: Fri, 7 Mar 2008 12:38:11 -0800 (PST) Subject: I cannot evaluate this statement... Message-ID: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> The script comes from Mark Lutz's Programming Python. It is the second line of a script that will launch a python program on any platform. import os, sys pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' Okay, run on a win32 machine, pyfile evaluates to python.exe That makes sense. Because the first condition is true and 'python.exe' is true. So the next comparison is 'python.exe' or 'python' Well, python.exe is true. So that value is returned to pyfile. Now. Run this on linux. The first condition evaluates sys.platform[:3] == 'win' as false. So, the next comparison should be 'False' or 'python' -- This is because 'and' returns the first false value. But, again, on linux pyfile evaluates to python.exe Where am I going wrong. And when will this statment make pyfile evaluate to 'python' ? From sjmachin at lexicon.net Fri Mar 7 17:12:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 14:12:13 -0800 (PST) Subject: How to clear a list (3 ways). References: Message-ID: <8c4fb388-7788-4ed9-ae4d-33f16b92d920@u10g2000prn.googlegroups.com> On Mar 8, 1:49 am, "Gabriel Genellina" wrote: > En Fri, 07 Mar 2008 09:39:05 -0200, > escribi?: > > > Executive summary : What idiom do you use for resetting a list ? > > lst = |] # (1) > > lst[:] = [] # (2) > > del lst[:] # (3) > > (3) if I want to keep the same list else (1) "resetting a list" is vague and dubious terminology. (1) abandons a reference to some object (which MAY be a list) and binds the name "lst" to a new empty list. (3) providing that the referred-to object is of a type that supports assigning to slices, removes the contents. (2) effects the same as (3) -- it's just slower to type, compile and execute. I would rewrite the advice to the OP as: Use (3) if and only if you have a justifiable need (not "want") to keep the same list. Cheers, John From gowricp at gmail.com Wed Mar 19 02:01:46 2008 From: gowricp at gmail.com (Gowri) Date: Tue, 18 Mar 2008 23:01:46 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <4fd038fb-399a-40f8-a12b-6c6539574b58@n75g2000hsh.googlegroups.com> I actually have a weirder problem. The code I posted earlier prints garbage on Windows and python 2.5 and the perfect json data on RHEL python 2.3.4. I'm so confused and helpless. json.py doesn't seem to help either. It says raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all() Somebody please help! From blwatson at gmail.com Sat Mar 29 23:39:58 2008 From: blwatson at gmail.com (blwatson at gmail.com) Date: Sat, 29 Mar 2008 20:39:58 -0700 (PDT) Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> Message-ID: <75c10b67-c971-4db4-be13-26cafd24e9d2@d4g2000prg.googlegroups.com> On Mar 29, 6:42?pm, "Gabriel Genellina" wrote: > En Sat, 29 Mar 2008 20:54:36 -0300, escribi?: > > > I tried to add the directory "//simplejson" to my sys.path > > in the interpreter, hoping that the call to import simplejson would > > work if the dir was there, even though simplejson.py did not exist is > > that dir, but the encoder, decoder, jsonfilter and scanner .py files > > were all there. > > > My problem is that the call "import simplejson" fails. ?How can I make > > that call work? > > simplejson is a package (a directory with an __init__.py), not a module; ? > don't look for simplejson.py > Its *parent* directory must be in sys.path for Python to find it. Try ? > copying the simplejson directory below site-packages (which should be ? > already in sys.path) > > -- > Gabriel Genellina Gabriel - First, thanks for the help. You have solved one problem but created a new one. Isn't that always how it works? So I copied over the dir, and now I get this error when trying to import simplejson: The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/Users/bwatson/.python-eggs/ simplejson-1.8.1-py2.5-macosx-10.3-fat.egg-tmp/simplejson/tmpJVSqa_. $extract' The Python egg cache directory is currently set to: /Users/bwatson/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. So I went looking for that egg...the following exists in my frameworks dir: simplejson-1.8.1-py2.5-macosx-10.3-fat.egg I hate eggs...I am stuck again. Any ideas? From msc at es.aau.dk Tue Mar 25 06:14:54 2008 From: msc at es.aau.dk (Martin Sand Christensen) Date: Tue, 25 Mar 2008 11:14:54 +0100 Subject: Code folder with Emacs References: <13u5li6kspler51@corp.supernews.com> Message-ID: >>>>> "Grant" == Grant Edwards writes: Grant> Has anybody figured out how to do code folding of Python source Grant> files in emacs? I use outline-minor-mode with the following home baked configuration: ;; Python stuff for outline mode. (defvar py-outline-regexp "^\\([ \t]*\\)\\(def\\|class\\|if\\|elif\\|else\\|while\\|for\\|try\\|except\\|with\\)" "This variable defines what constitutes a 'headline' to outline mode.") (defun py-outline-level () "Report outline level for Python outlining." (save-excursion (end-of-line) (let ((indentation (progn (re-search-backward py-outline-regexp) (match-string-no-properties 1)))) (if (and (> (length indentation) 0) (string= "\t" (substring indentation 0 1))) (length indentation) (/ (length indentation) py-indent-offset))))) (add-hook 'python-mode-hook '(lambda () (outline-minor-mode 1) (setq outline-regexp py-outline-regexp outline-level 'py-outline-level))) Martin From castironpi at gmail.com Wed Mar 5 16:52:38 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 13:52:38 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> Message-ID: <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> On Mar 5, 3:38?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: > > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: > >> castiro... at gmail.com schrieb: > > >> > I want to hash values to keys. ?How do the alternatives compare? > > >>http://catb.org/~esr/faqs/smart-questions.html > > > ... without extending the whole way to a full relational database? > > You didn't bother following the link and reading the advice, did you? If > you did, you haven't done a good job of following that advice. Well, obviously there's someone who's interested in computers and programming that has a question. Communication is not his forte, but effort, willingness, devotion, and dedication are. What should he do, and what should the others, who are gifted speakers? From steve at REMOVE-THIS-cybersource.com.au Tue Mar 25 18:55:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 25 Mar 2008 22:55:00 -0000 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> Message-ID: <13uj0m4qd1dit79@corp.supernews.com> On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: > As per your suggestion, I tried looking at include/code.h and > include/funcobject.h (my MS Windows distribution does not appear to > contain .c files). However, since I'm not a C programmer, I did not > find the .h files all that helpful. I'm hardly surprised. The naivety of those who insist that the "best way to understand how new.function and new.code work" is to look at the C source code for object is amusing. Not everybody reads C. This is a Python group, and surely the best way would be to see some good examples using *Python*. > What I failed to make clear in my original posting is that the > functions must be created dynamically using information in a *record* > as the code iterates over all *records*. So, I can not pre-define the > functions and then simply select the desired one at run-time. Here's an example that might help. class MyClass(object): pass records = ["spam", "ham"] for record in records: # define a new function def f(n): return (record + " ")*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instance.execute(5) -- Steven From steve at holdenweb.com Mon Mar 17 04:59:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Mar 2008 04:59:44 -0400 Subject: [PyCON-Organizers] FWD: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: <20080317001209.GA16907@panix.com> References: <20080317001209.GA16907@panix.com> Message-ID: <47DE3300.4060108@holdenweb.com> Aahz wrote: > FYI > > ----- Forwarded message from Aahz ----- > > From: Aahz > Newsgroups: comp.lang.python > Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) > Date: 16 Mar 2008 17:09:02 -0700 > Organization: The Cat & Dragon > > [warning: rant ahead] > > [[ > Before starting my rant, I would like to encourage anyone who was at > PyCon but has not provided formal feedback to use the following URLs: > > For the conference: > http://tinyurl.com/2ara8u > > For the tutorials: > http://tinyurl.com/2ew2pc > ]] > > In article <5776428b-82b3-4921-945a-69beab134edd at b64g2000hsa.googlegroups.com>, > fumanchu wrote: >> This is my third PyCon, and I've found a reasonably-sized cadre of >> people who come for the hallway conversations plus a Bof or two, >> having given up on hearing anything new, useful, or inspiring in the >> talks. There are several people I know who would like to see a more >> advanced academic track. > > Let's leave aside the issue of how sponsor talks were handled: assuming > that there's general agreement that this year was a failed experiment, > fixing it is easy. > > What you're bringing up here is a much more difficult issue, and it is, > in the end, not a solvable issue in the general case. For starters, > speaking as someone who has been going to science fiction conventions > for more than twenty years, there will inevitably be plenty of people > like your cadre. I rarely go to organized programming anymore, but I > still have a great time because I'm seeing all my friends. PyCon is a > similar community-oriented event. > > Moreover, PyCon's success rests on many legs: tutorials, Open Space, > Lightning Talks, formal presentations, keynotes, and sprinting. That's > aside from the myriad opportunities to network with people. > > Finally, trying to satisfy a thousand people is impossible. People who > want to emphasize specific topics (e.g. an academic track) will need to > start organizing other kinds of Python conferences. > > > Now the rant: > > If you did not like the programming this year (aside from the sponsor > talks) and you did not participate in organizing PyCon or in delivering > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! > > PyCon is built on the backs of its volunteers. I personally spent more > than twenty hours just doing Program Committee work. We rejected half > the proposals that we received, simply due to lack of space. We had > difficulty evaluating some proposals because nobody on the PC had subject > matter expertise. > > None of the speakers received any kind of honorarium. Except for keynote > speakers (e.g. Ivan Krstic), no speakers received free registration > unless they requested financial aid. > > There are no requirements for volunteering other than a willingness to > volunteer and a modicum of courtesy in working with people. > > PyCon is what YOU make of it. If you want to change PyCon, propose a > presentation or join the conference committee (concom) -- the latter only > requires signing up for the pycon-organizers mailing list. > > This doesn't mean that we are uninterested in feedback. We love > feedback. But there are stark limits to what we can do unless people get > involved and push their pet projects. I am copying this reply to comp.lang.python just so that the people who were *not* involved in the organization of the conference will know two things: first, that the negative feedback the organizers have received is regarded as valuable, helpful, and (to some extent) justified; secondly, so that everyone who receives this message knows that they are welcome to participate in improving PyCon (which, as Aahz has indicated, really means that the broader the range of expertise on the program committee the more the selected talks can reflect the true needs of the audience - but don't imagine that participation is limited to the Program Committee). Also, please be aware this is only one message on a *very* long thread in the pycon-organizers list. Before I say anything else, I want to (again) publicly thank David Goodger and his team, and the ChiPy team led by Chris McAvoy, for the long hours and hard work they put in to what I personally (as the founder of PyCon) regard as the best PyCon ever. You will perhaps get some idea of the explosive growth in demand they have managed to satisfy by pointing out that this year there were more people attending paid tutorials, and there are more people staying after the conference to sprint (thereby improving Python and its applications), and more people attending their *first* PyCon this year, than attended the first PyCon that I organized five years ago in DC. If you have not been privy to the planning process, let me assure you that you have *no* idea how hard people have worked to try to ensure that *everyone* who came to PyCon this year had a positive experience. I can say this without fear of being thought to defend my own position, since I have (for the first time ever, yay!) played absolutely no formal role in the organization of PyCon. I can also say with every confidence that if you would like to volunteer to make the next PyCon (again in Chicago in 2009) better then you are unlikely to be turned away. The conference is growing so fast we have to run to keep up, everyone is learning as we go along. Ken Whitesell has written (after admitting that his original assessment might have been hasty) """By rough count, I attended 22 separate talks, including the tutorials and plenary sessions. Of that, there were 4 (not 5 that I wrote below) that I would consider below par.""" If the Program Committee have managed to provide a program where 75% of the talks were at or above average then they have worked a statistical miracle, though personally I have always felt that the general quality of PyCon talks has been way above that provided by the average "pay to play" technical conference. This does bring up another useful issue, which is that the overall delegate satisfaction is always going to be a bell-shaped curve. As the total number of delegates continues to rise the tails of that curve broaden, and it is more likely that a few delegates will be unhappy with the majority of the scheduled talks that they attend. It's unfortunate, but all the organizers can do is keep the focus on quality and continue to encourage broad participation. It is likely that almost everyone who reads this message has a legitimate right to consider themselves a part of the Python community. To address the specific issue of sponsor presentations, I believe that the Diamond Sponsor Keynotes given by both White Oak Technologies and Google were entirely within the spirit of PyCon, and appropriate to the audience even though not highly technical. As far as the sponsor lightning talks go, all involved admit that mistakes were made. The specific issue that had the largest negative impact was the bunching of the talks at the beginning of the session on Friday and (particularly) on Saturday. This was effectively an attempt to repeat the successful 2007 formula without acknowledging the effects of the (huge!) increase in sponsorship this year. While there are steps that could be taken to remedy this issue, I believe (though David Goodger can choose to contradict me, since he is the authority and I have not yet discussed this with him) that the success of the exhibition hall this year means that the sponsors are unlikely to need a specific channel in the conference program to present their commercial message. If they have a technical talk they feel would interest the delegates then they can use the same sign-up sheet that everyone else does, and be subject to the same rules as everyone else. To put the sponsorship in complete perspective, subtracting the catering costs of (I think) $182 a delegate paying $200 (the hobbyist early-bird registration fee) for a place at PyCon 2008 was contributing $18 to the remaining costs, which were not insignificant. A number of delegates with whom I have discussed this issue have agreed with me that for that kind of subsidy it isn't unreasonable to expect us to "rent our eyeballs" for a brief period, though next year I am sure the organizers will be sure to brief all sponsor keynote speakers carefully about acceptable topics. In summary, when things are growing as fact as PyCon is a few mis-steps are inevitable, as we are traversing foreign territory and learning as we go. While it's upsetting to know that some individual delegates were less than happy with their conference experience I believe the feedback will tell a different overall story when it has been analyzed. The organizers continue to be open to offers of assistance, and feedback from any participant. That is the spirit of PyCon, and I'd like to thank Bruce Eckel for saying what was on his mind. As a provider of commercial training I am uncomfortably aware that one normally hears from one customer out of each seven who are dissatisfied. If the other six will contact me personally I will do what I can to remedy the situation :-) Again, the URLs for delegates to provide feedback about their experiences are > For the conference: > http://tinyurl.com/2ara8u > > For the tutorials: > http://tinyurl.com/2ew2pc I hope to see you all at PyCon next year. Way to go, Chicago!! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From yao1337 at gmail.com Wed Mar 19 03:05:50 2008 From: yao1337 at gmail.com (purple) Date: Wed, 19 Mar 2008 00:05:50 -0700 (PDT) Subject: How to solve a three-element equation set? Message-ID: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> Could you guys do me a favor for solving a equation set? Z=d/4*(1-SIN(X)/X) X=8q/(D^2*Y)+SIN(X) Y=1/n*Z^(2/3)*i^(1/2) In this equation set, X,Y&Z are the unkown parameters, the others say, d, q, n&i are known. SO in python, how to program it to represent X, Y and Z in the form of d, q, n and i? Thanks very much. From kyosohma at gmail.com Mon Mar 10 11:36:22 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 10 Mar 2008 08:36:22 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: On Mar 10, 10:27 am, "Malcolm Greene" wrote: > Stefan, > > > My personal experience with wxPython has its ups and downs. Specifically when it comes to crashes, I wouldn't bet my life on it. (but then, the OP > > I'm new to Python and getting ready to build a small client based > application intended to run on Windows and Linux. I was planning on > using wxPython until I saw your comment above. > > Any suggestions on an alternative Python client-side GUI library (pyQT > ?) or tips on where I can find out more about wxPython/wxWidget > problems? > > Thank you, > Malcolm We use wxPython here at work for new application development and have had no major problems with it once we knew what dlls to include. In my experience, I've needed gdiplus.dll, msvcp71.dll and MSVCR71.dll from time to time. Mike From steve at holdenweb.com Sun Mar 30 15:35:34 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Mar 2008 15:35:34 -0400 Subject: License of Python In-Reply-To: References: Message-ID: iu2 wrote: > Hi guys, > > I'd like to use Python in a commercial application. In fact I would > like to write the application entirely in Python. > But I think I wouldn't like telling what language the application is > written in. > The problem is that including Python's license in the binary, which as > I understand is a must do, reveals that the appliation is based on > Python. > > I'll appreciate your advices about this > Thanks > iu2 My advice would be to create something of real value before you worry about issues like this. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From zubeido at yahoo.com.br Sat Mar 8 11:57:34 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 8 Mar 2008 08:57:34 -0800 (PST) Subject: SQL problem in python Message-ID: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> class db: def __init__(self): #constructor conn = sqlite3.connect(":memory:") conn.isolation_level = None self.cursor = conn.cursor() self.cursor.execute("CREATE TABLE database (album,filepath)") def add_entry(self, eone , etwo): #Add entry to database self.cursor.execute("INSERT INTO database (album,filepath) VALUES (?,?)", ( eone , etwo ) ) return 1 #TODO: exception handler def get_mediadb(self, print_db = False): self.cursor.execute('SELECT * FROM database') if (print_db == True): print self.cursor.fetchall() def get_value( self, column ): self.cursor.execute( "SELECT (?) FROM database", column ) for n in self.cursor: print n def destructor(self): self.cursor.close() if __name__ == "__main__": f = db() f.add_entry( "Pinkk Floyd", "fdgf" ) f.add_entry( "Pink", "fdgf" ) # f.get_mediadb(print_db=True) f.get_value(('filepath',)) f.destructor() When i run it the get_value() returns 'filepath' instead of the columns. But if i dont use any variable and make the expression static all goes on as its supposed to. What am i doing wrong? PS: Dont mind the bad code From deets at nospam.web.de Thu Mar 13 19:44:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Mar 2008 00:44:28 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> Message-ID: <63tsj3F27o6o5U1@mid.uni-berlin.de> > My understanding is that foo.bar does *not* create a new object. Your understanding is not correct. > All it > does is return the value of the bar attribute of object foo. What new > object is being created? A bound method. This happens through the descriptor-protocol. Please see this example: class Foo(object): def bar(self): pass f = Foo() a = Foo.bar b = f.bar c = f.bar print a, b, c print id(b), id(c) The result is this: > > 315560 788960 So b and c really are different objects - "a is not b == True" Diez From wingi at gmx.com Wed Mar 12 05:10:46 2008 From: wingi at gmx.com (wingi at gmx.com) Date: Wed, 12 Mar 2008 02:10:46 -0700 (PDT) Subject: Exctract GIF comment from image References: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Message-ID: <8f93339a-c78e-4580-903c-eeff991b9892@q78g2000hsh.googlegroups.com> On 11 Mrz., 18:39, "Guilherme Polo" wrote: > 2008/3/11, wi... at gmx.com : > > > Hi, > > > simple question: ThePILdoes not support reading the optional > > description in GIF Images. > > > I did a quick thing here, try it and check if it solves the problem for you: > Wow - thanx for the fast answer! Yes it works and can use it ;-) *smile* From paddy3118 at googlemail.com Thu Mar 13 01:09:48 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 12 Mar 2008 22:09:48 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> Message-ID: On Mar 13, 1:37 am, Carl Banks wrote: > On Mar 12, 8:11 pm, Justus Schwabedal > wrote: > > > What do you need it for anyway? I just read about it and I think it's > > useless > > in python. > > Perl, like Python, has a separate compilation and run times. One day, > someone who was trying to use Perl for something asked, "You know, > wouldn't it be neat-o if you could execute some Perl code *before* you > compiled the script?" And so (since that's usually enough reason to > add something to Perl) was borne the BEGIN block. > > I believe the official rationale was that they wanted to add some > magic variables that affected Perl's compilation and couldn't do it > without a magic block that executed at compile time. > > Python solved a similar problem by introducing __future__ imports. > > Carl Banks And theres me thinking it was part of Perls AWK compatibility code. - Paddy. From p.f.moore at gmail.com Sat Mar 1 17:39:41 2008 From: p.f.moore at gmail.com (Paul Moore) Date: Sat, 1 Mar 2008 22:39:41 +0000 Subject: [Python-Dev] [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: <47C9D802.2090205@v.loewis.de> References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> <47C9D802.2090205@v.loewis.de> Message-ID: <79990c6b0803011439n583bc2b2w5c544b620a91fa61@mail.gmail.com> On 01/03/2008, "Martin v. L?wis" wrote: > > As of 4:50 PM EST, the links to Windows installers give 404 File Not > > Found. > > > > I gather that they are still in process, > > and notice that there is no public c.l.p. announcement. > > > I just fixed that. The files were there; just the links were wrong. The 2.6a1 x86 MSI is there, but the 3.0a3 x86 MSI is still giving a 404. Paul. From bharathv6.project at gmail.com Tue Mar 18 08:51:03 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Tue, 18 Mar 2008 18:21:03 +0530 Subject: automatically doing some cleaning-up by the process when the systems shuts down Message-ID: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> hi .. my programs runs as daemon and it does some logging .. when system shuts down .. which may be done manually . i want my process do some cleaning up automatically such as writing in to the log file when the process terminats before the system shuts down thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkapoor at wscm.net Mon Mar 24 16:50:19 2008 From: tkapoor at wscm.net (Tarun Kapoor) Date: Mon, 24 Mar 2008 15:50:19 -0500 Subject: Paramiko bugs out on windows 2003 server Message-ID: I am using the paramiko library to pull a data from a server using SFTP. It works perfect on a windows xp machine but bugs out a windows 2003 server. I get the following error: Traceback (most recent call last): File "S:\Temp\ftpBOA.py", line 5, in ? import paramiko File "C:\Python23\lib\paramiko\__init__.py", line 69, in ? from transport import randpool, SecurityOptions, Transport File "C:\Python23\lib\paramiko\transport.py", line 32, in ? from paramiko import util File "C:\Python23\lib\paramiko\util.py", line 31, in ? from paramiko.common import * File "C:\Python23\lib\paramiko\common.py", line 98, in ? from osrandom import OSRandomPool File "C:\Python23\lib\paramiko\osrandom.py", line 54, in ? raise ImportError("Cannot find OS entropy source") ImportError: Cannot find OS entropy source Anyone knows how to solve it ? Tarun Kapoor Disclaimer This e-mail and any attachments is confidential and intended solely for the use of the individual(s) to whom it is addressed. Any views or opinions presented are solely those of the author and do not necessarily represent those of Waterstone Capital Management, L.P and affiliates. If you are not the intended recipient, be advised that you have received this e-mail in error and that any use, dissemination, printing, forwarding or copying of this email is strictly prohibited. Please contact the sender if you have received this e-mail in error. You should also be aware that e-mails are susceptible to interference and you should not assume that the contents of this e-mail originated from the sender above or that they have been accurately reproduced in their original form. Waterstone Capital Management, L.P. and affiliates accepts no responsibility for information, or errors or omissions in this e-mail or use or misuse thereof. If in doubt, please verify the authenticity with the sender. From durieux_br at yahoo.com.br Thu Mar 27 15:27:16 2008 From: durieux_br at yahoo.com.br (Fabio Durieux Lopes) Date: Thu, 27 Mar 2008 19:27:16 -0000 Subject: Signal problem Message-ID: Hello again! Full of problems today! This one is about signal treatment. I made a daemon and set it to treat 2 signals: SIGALRM and SIGTERM. It goes like this: signal.signal(signal.SIGTERM, daemon.signalHandler) signal.signal(signal.SIGALRM, aFilter.alarmHandler) On daemon.py I have: " ... terminate = False def signalHandler(signum, frame): terminate = True ... " And my main loop goes like this: 'while(not daemon.terminate):' When the signal treatment was in the same file as my loop it worked just fine, and since I've separated it in another file it stopped working. The SIGALRM treatment, which remains in the same file, is still working. Any reason why it doesn't treat SIGTERM anymore? Does it have anything to do with the fact that 'terminate' is not a class variable? Any ideas? Thanks in advance! From jeff at schwabcenter.com Mon Mar 17 13:59:52 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 10:59:52 -0700 Subject: questions about named pipe objects... In-Reply-To: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> References: <2c2eb43b-b7b1-420f-85bd-ce839e44caf2@a1g2000hsb.googlegroups.com> Message-ID: waltbrad wrote: > I'm proceeding slowly though the Lutz book "Programming Python". I'm > in the section on named pipes. The script he uses has two functions: > one for the child the other for the parent. You start the parent then > the child: > > python pipefifo.py #starts the parent > > file /tmp/pipefifo # shows that the file is a named pipe You appear to be using something Unix-like. > python pipefifo.py -child # starts a child process and writes to the > pipe. > > This is done between two command windows - the first for the parent > and the second for the child. > > Now, the child's write loop is infinite. So, I used Ctrl-C and stopped > the process. But the parent's read loop is also infinite and without > and exception, so it keeps reading from the pipe after the child is > shutdown even though the lines are empty. So, I had to shut that down > also. > > I then wanted to start the child process first and see what happened > when I ran the parent. Well that works but the reads come out in > random order. This got me wondering about the pipe file itself. So I > tried to open it with leafpad and found that I couldn't. I guess > these files can only be opened by processes? > > Okay. But exactly when does the system brand this file as a named pipe > and how? A Unix fifo is only nominally a file. It's really just a convenient way of referring to an in-memory object. mkfifo f some_prog > f & cat f Is semantically equivalent to: some_prog | cat If you want to peruse the data in your editor, use a regular file, not a fifo. Have the writer (producer, "child" in your example) open it in append mode. From Robert.Bossy at jouy.inra.fr Fri Mar 21 04:01:10 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 21 Mar 2008 09:01:10 +0100 Subject: script won't run using cron.d or crontab In-Reply-To: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> References: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> Message-ID: <47E36B46.4050002@jouy.inra.fr> Bjorn Meyer wrote: > I appologize if this been discussed previously. If so, just point me > to that information. > > I have done a fair bit of digging, but I haven't found a description > of what to actually do. > > I have a fairly lengthy script that I am able to run without any > problems from a shell. My problem is, now I am wanting to get it > running using crontab or cron.d. It seems that running it this way > there is a problem with some of the commands that I am using. For > instance "commands.getoutput" or "os.access". I am assuming that there > is something missing within the environment that cron runs that fails > to allow these commands to run. > If anyone has any information that would help, it would be greatly > appreciated. Hi, From a shell, type: man 5 crontab and read carefully. You'll realize that a croned script does not inherit from the user shell's environment. Cheers, RB From gagsl-py2 at yahoo.com.ar Mon Mar 31 13:35:26 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 14:35:26 -0300 Subject: How to insert multiple rows in SQLite Dbase References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> <657h3nF2eehi8U1@mid.uni-berlin.de> Message-ID: En Mon, 31 Mar 2008 11:22:40 -0300, afandi escribi?: > On Mar 30, 4:46 am, Gerhard H?ring wrote: >> >> The deluxe version with generators could look like this: >> >> def parse_logfile(): >> logf = open(...) >> for line in logf: >> if ...: >> row = (value1, value2, value3) >> yield row >> logf.close() >> >> ... >> >> cur.executemany("insert into ... values (c1, c2, c3)", parse_logfile()) > > Thanks regards to your suggestion, but I don't understand why we have > to put the IF statement? Which if statement? The if inside parse_logfile quoted above is just an example, it's not essential. -- Gabriel Genellina From furkankuru at gmail.com Tue Mar 25 21:14:39 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 03:14:39 +0200 Subject: My python interpreter became mad ! In-Reply-To: <47E99C99.2060401@lexicon.net> References: <3a4a8f930803250555u2ec592cfjf2be878811890f47@mail.gmail.com> <47E964CA.4070603@lexicon.net> <3a4a8f930803251604r33562ec8wb8dcaa665288f184@mail.gmail.com> <47E99C99.2060401@lexicon.net> Message-ID: <3a4a8f930803251814t3043f724v913bcc9e7aa7bf6e@mail.gmail.com> On 3/26/08, John Machin wrote: > > > > but I did not give it a chance "not trying python interpreter in another > > directory" > > I don't understand that sentence. ok let me explain: I did not think he/she/anyone would ask the question in the main thread without trying the interpreter a few times starting it from different directories. > so if we assume the problem exists in every directory, it has something > > to do with pythonpath. > > Why would/should we assume that? Because I, as an individual, would not ask this question without running interpreter from different directories. and I would look whether I created a py file with the exact same name of a core module. And this "simple" mistake had been pointed out by other guys. The only other reason that came to my mind was this pythonpath. ( and I was dealing with it recently: you may have take a look at the thread titled 'embedded pyton pythonpath' any answer is appreciated :p ) > > you can try setting pythonpath to some directory and put a re.py there > > and try from any directory starting your interpreter and importing re. > > and achieve the same result: importing the bogus re. What's your point? yeah same result: bogus re. but from a different way: not user's re but created by someone else in another directory. > > > > > > > On 3/25/08, *John Machin* > > wrote: > > > > Furkan Kuru top-posted: > > > Most probably X-Spam added itself to your path. > > > > What is "X-Spam"? Added itself to Benjamin's path [not mine] in such > a > > fashion that it is invoked when one does "import re"? > > > > > you should look at your PATH and PYTHONPATH environment > variables. > > > > Most *IM*probably. Read the traceback: > > """ > > > > File "/etc/postfix/re.py", line 19, in ? > > > > m = re.match('(Spam)', mail) > > > > AttributeError: 'module' object has no attribute 'match' > > """ > > > > This is a classic case of a script (which does not guard against > side > > effects (like spewing out gibberish) when imported instead of being > > executed) being given the same name as a Python-included module and > > being executed in the current directory and hence ends up importing > > itself. > > > > > > > > On Tue, Mar 25, 2008 at 1:40 PM, John Machin > > > > > >> > wrote: > > > > > > On Mar 25, 10:05 pm, Benjamin Watine > > > > >> wrote: > > > > Yes, my python interpreter seems to became mad ; or may be > > it's > > > me ! :) > > > > > > > > I'm trying to use re module to match text with regular > > > expression. In a > > > > first time, all works right. But since yesterday, I have a > > very > > > strange > > > > behaviour : > > > > > > > > $ python2.4 > > > > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > > > > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on > linux2 > > > > Type "help", "copyright", "credits" or "license" for more > > > information. > > > > >>> import re > > > > X-Spam-Flag: YES > > > > [snip] > > > > > > Traceback (most recent call last): > > > > File "", line 1, in ? > > > > File "/etc/postfix/re.py", line 19, in ? > > > > m = re.match('(Spam)', mail) > > > > AttributeError: 'module' object has no attribute 'match' > > > > >>> > > > > > > > > What's the hell ?? I'm just importing the re module. > > > > > > No you're not importing *the* re module. You're importing > *an* re > > > module, the first one that is found. In this case: your own > > re.py. > > > Rename it. > > > > > > > > > > > > > -- > > Furkan Kuru > > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From zutesmog at gmail.com Wed Mar 12 03:17:48 2008 From: zutesmog at gmail.com (zutesmog at gmail.com) Date: Wed, 12 Mar 2008 00:17:48 -0700 (PDT) Subject: Problems installing Python Imaging Library References: <76000a76-0c8f-4b79-95c8-9d0f4aae0972@n58g2000hsf.googlegroups.com> Message-ID: On Mar 10, 3:06 am, Nick Day wrote: > Hi, > > I'm trying to install PIL from source on my CentOS 4.5 server. The > build summary reports that I have everything installed... > > -------------------------------------------------------------------- > PIL 1.1.6 BUILD SUMMARY > -------------------------------------------------------------------- > version 1.1.6 > platform linux2 2.3.4 (#1, Dec 11 2007, 05:28:55) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] > -------------------------------------------------------------------- > --- TKINTER support ok > --- JPEG support ok > --- ZLIB (PNG/ZIP) support ok > --- FREETYPE2 support ok > > ... but if I try and build it I receive the following error: > > /usr/bin/ld: /usr/local/lib/libjpeg.a(jcparam.o): relocation > R_X86_64_32 against `a local symbol' can not be used when making a > shared object; recompile with -fPIC > > How do I fix this? I am currently running "python setup.py build" and > don't understand how I would change the compiling options to add the "- > fPIC" flag. I'm quite a newbie when it comes to Linux/Python so any > help you could give me would be great. > > Thanks, > Nick You should be linking against a dynamic version of libjpeg rather than the static version. ie libjpeg.so Looks like you have locally installed libjpeg but only built a static version. Rgds Tim From torriem at gmail.com Wed Mar 5 00:12:00 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 04 Mar 2008 22:12:00 -0700 Subject: Protocol for thread communication Message-ID: <47CE2BA0.2060001@gmail.com> Does anyone have any recommended ideas/ways of implementing a proper control and status protocol for communicating with threads? I have a program that spawns a few worker threads, and I'd like a good, clean way of communicating the status of these threads back to the main thread. Each thread (wrapped in a very simple class) has only a few states, and progress levels in those states. And sometimes they can error out, although if the main thread knew about it, it could ask the thread to retry (start over). How would any of you do this? A callback method that the thread can call (synchronizing one-way variables isn't a problem)? A queue? How would the main thread check these things? Currently the main thread is polling some simple status variables. This works, and polling will likely continue to be the simplest and easiest way, but simple status variables are very limited. Are there any pythonic patterns people have developed for this. thanks. Michael From wescpy at gmail.com Wed Mar 19 00:26:02 2008 From: wescpy at gmail.com (wesley chun) Date: Tue, 18 Mar 2008 21:26:02 -0700 (PDT) Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <6653ea0b-5d8b-4017-b0bd-8948ea0bf7a1@e23g2000prf.googlegroups.com> > > You're mixing two completely different approaches of building a > > property. If that code is actually in the book like that, that's a typo > > that you should mention to the author. > > : > > The recipe you're referring to uses a magical function that returns a > > dictionary of getter function, setter function, deleter function, and > > docstring, with suitable key names so that the dictionary can be passed > > as a keyword argument dictionary into the property() constructor. > > However, that requires the magical foo=property(**foo()) invocation, not > > the regular decorator invocation foo=property(foo). > > Ah, ok, I'll send him an email then, thanks for the explanation! this well-known error was discovered pretty early... apologies to all readers. please checkout the Errata at the book's website -- http://corepython.com -- and keep it as a companion in case you find anything else like this. i appreciate all constructive feedback... don't trust everything you read! send any other corrections to me at corepython at yahoo... including suggestions for future editions, ideas for exercises, new material that you think should be covered, etc. best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From knut.urbye at gmail.com Thu Mar 27 04:50:13 2008 From: knut.urbye at gmail.com (Knut) Date: Thu, 27 Mar 2008 01:50:13 -0700 (PDT) Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> Message-ID: <3e6246de-5af2-4296-bea5-76bfa26adf12@u10g2000prn.googlegroups.com> On 26 Mar, 23:08, Thomas Heller wrote: > Knut schrieb: > > > > >> The script can't resolve the server name. Try to do it by hand using > >> nslookup or even ping (you may want to add a few print statements inside > >> the script to see the exact host name it is trying to connect to, in case > >> it isn't what you expect) > >> If you can't resolve the host name using nslookup, there is a network > >> problem, not in your script. If you can resolve it, try your script > >> without py2exe if possible. > > >> -- > >> Gabriel Genellina > > > Thank you for the quick reply Gabriel. > > > I have made sure the script works fine before I exe it. > > It is when I compile the program I get this error. > > > I don't get how the compile changes server availability. > > Could it be a firewall issue? > > Thomas Hi Thomas, Thanks for the tip! Disabled the firewall to check if this could be the problem, but no help there either.. The mail server is on the local network, but I have also tried connecting to internal sockets to another program I have which sniffs a port. This works fine, until I run it as an exe.. My quest continues.. From fhaxbox66 at googlemail.com Fri Mar 7 09:37:21 2008 From: fhaxbox66 at googlemail.com (fhaxbox66 at googlemail.com) Date: Fri, 7 Mar 2008 06:37:21 -0800 (PST) Subject: Hyphenation: PyHyphen project now hosted on GoogleCode Message-ID: <38ab7938-9baf-4c41-ac7c-cad345cb830a@x30g2000hsd.googlegroups.com> This is to inform you that development of PyHyphen and issue tracking takes now place at http://pyhyphen.googlecode.com. All interested parties are encouraged to submit comments, suggestions and bug reports. Snapshots of the source tree can be obtained using subversion. At this stage, the sources contain a number of minor improvements over version 0.4.1 which is still available on the pypi. Windows installers are though still lacking. Regards Leo From george.sakkis at gmail.com Wed Mar 26 17:25:31 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 14:25:31 -0700 (PDT) Subject: Not understanding lamdas and scoping References: Message-ID: On Mar 26, 5:02 pm, Joshua Kugler wrote: > I am trying to use lamdba to generate some functions, and it is not working > the way I'd expect. The code is below, followed by the results I'm > getting. More comments below that. > > (...) > > So, is there some scoping issue with lambda > that I'm not seeing? Yes; it's not related to lambda though but to closures (whether defined as lambdas or regular functions). See for example http://groups.google.com/group/comp.lang.python/browse_frm/thread/94d1bba8ad56baf4 There should be an entry for this at http://www.python.org/doc/faq/programming/, that's really an FAQ. George From deets at nospam.web.de Thu Mar 13 07:12:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 12:12:37 +0100 Subject: What's Going On? References: <57c19083-8450-4484-a4e0-30a20ff1ee85@u10g2000prn.googlegroups.com> Message-ID: <63sgh6F28j923U1@mid.uni-berlin.de> MartinRinehart at gmail.com wrote: > (Accompanied by Marvin Gaye) > >>>> def f(list=[0]): > ... list[0]+=1 > ... return list[0] > ... >>>> f() > 1 >>>> f() > 2 >>>> f() # 'list' is a name bound to a list (mutable) so this makes sense > 3 >>>> f([5]) > 6 >>>>f() # What's Going On? > 4 That the same default argument is mutated? What did you expect, that it got replaced by you passing another list? That would kind of defy the meaning of default-arguments, replacing them whenever you call a function with actual parameters. Diez From castironpi at gmail.com Mon Mar 31 19:23:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 16:23:04 -0700 (PDT) Subject: class super method References: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> Message-ID: <252dbf5b-6bad-4957-b56f-5bb36f66d80e@n58g2000hsf.googlegroups.com> On Mar 31, 5:58?pm, George Sakkis wrote: > On Mar 31, 6:25 pm, gigs wrote: > > > is there any tutorial for super method (when/how to use it)? > > > or maybe someone could explain me how it works? > > > thx > > Super is one of the dark corners of the language [1,2]... a good rule > of thumb is to stay away from it, or at least stick to its basic > usage. > > George > > [1]http://www.phyast.pitt.edu/~micheles/python/super.html > [2]http://fuhm.net/super-harmful/ Is ancestry mutable? From sturlamolden at yahoo.no Sun Mar 16 11:01:07 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 08:01:07 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <199cfa42-ca1a-4db6-bf4d-a0a811daa791@s12g2000prg.googlegroups.com> On 16 Mar, 15:32, bearophileH... at lycos.com wrote: > It seems the development of Cython is going very well, quite > differently from the dead-looking Pyrex. Hopefully Cython will become > more user-friendly too (Pyrex is far from being user-friendly for > Windows users, it doesn't even contain a compiler, I think. The Pyrex is not dead. And although it may come as a surprise to you, Pyrex IS a compiler. Pyrex does not contain a C compiler. But why should it? There are Microsoft Visual C++, MinGW, Cygwin, lcc, Borland C++, Intel C++ compiler, OpenWatcom, among others. Get your favourite. Being written in pure Python, Pyrex is equally easy to use on Windows and Linux. You have to use the command prompt or disttools on either platform. > The (little) point of this post: sometimes (when the programmer is > quite lazy) statically typed code is more "readable" than Python code. If your task is to translate a Python program into a statically typed language, type annotations can be helpful. But you don't need types to read a/b as 'a divided by b'. From gagsl-py2 at yahoo.com.ar Tue Mar 25 19:21:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 23:21:15 +0000 (UTC) Subject: embedded python pythonpath References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> Message-ID: Furkan Kuru gmail.com> writes: > I've tried below code (Setting pythonpath environment variable) > and then initialize python interpreter but the embedded python interpreter did not get the newly assigned PYTHONPATH. > I ve looked at the sys.path in python code (that is run by the embedded interpreter) and it behaved according to older pythonpath. Note that you don't HAVE to set the environment variable PYTHONPATH, there are other ways to get directories listed in sys.path - and that is what really counts. The simplest way is to just write code to insert the desired directories in front of sys.path, after the call to Py_Initialize. The only problem is that some modules (like site and sitecustomize) are searched and executed before your code has a chance to modify sys.path - I hope it's not a problem for you. > Setting environment variable seemed to be correct. > Does py_initialize run in another thread so it starts before setting the environment var? I could reproduce the problem with a smaller code (using C, not C++). Testing with Python 2.5.1 doesn't work (that means, it ignores the new setting for PYTHONPATH). Testing with current Python trunk (from svn) *does* work. I don't know if this is a bug that has been fixed, or it works that way because the svn version is not the default installation and then searches for things in a different way. #include int main(int argc, char *argv[]) { putenv("PYTHONPATH=C:\\TEMP\\MF"); system("set PYTHONPATH"); printf("Py_GETENV(PYTHONPATH)=%s\n", Py_GETENV("PYTHONPATH")); Py_Initialize(); PyRun_SimpleString("import sys\nprint sys.path"); Py_Finalize(); return 0; } I compiled twice with these commands: cl -MD -Ic:\apps\python25\include test.c c:\apps\python25 \Libs\Python25.lib /Fetest25.exe cl -MD -Ic:\apps\python\trunk\PC -Ic:\apps\python\trunk\include test.c c:\apps\python\trunk\PCbuild\Python26.lib /Fetest26.exe Python25.dll and Python26.dll both were copied into the current directory. test25.exe: PYTHONPATH=C:\TEMP\MF Py_GETENV(PYTHONPATH)=C:\TEMP\MF ['C:\\Apps\\Python25\\lib\\site-packages\\setuptools-0.6c5- py2.5.egg', 'C:\\Apps\\Python25\\lib\\site-packages\\ simplejson-1.7.1-py2.5-win32.egg', ... many directories, not including C:\TEMP\MF ... ] test26.exe: PYTHONPATH=C:\TEMP\MF Py_GETENV(PYTHONPATH)=C:\TEMP\MF 'import site' failed; use -v for traceback ['C:\\TEMP\\MF', 'C:\\TEMP\\python26.zip', '', 'C:\\TEMP'] I don't understand how the test program, compiled for 2.5.1, could actually locate the Python directory. (It's not in my PATH, it's not the default install directory, and I deleted the HKLM\Software\Python\PythonCore\2.5 registry key). -- Gabriel Genellina From nothanks at null.invalid Sat Mar 1 23:04:06 2008 From: nothanks at null.invalid (Bill) Date: Sat, 01 Mar 2008 23:04:06 -0500 Subject: Where's GUI for Python? In-Reply-To: References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: Peter Decker wrote, On 3/1/2008 9:58 PM: > On Sat, Mar 1, 2008 at 3:35 PM, K Viltersten wrote: >> I'm certain there is an API for creating >> GUI's but as far i can find it in the >> http://docs.python.org/tut/tut.html >> the only "gui" is in "Guido". > > Check out Dabo: http://dabodev.com > > It uses the wxPython UI toolkit, but wraps it in a much more Pythonic API. > > I've been using Dabo for over a year, and it rocks!! > Hi Peter, You should also take a look at wxGlade: http://wxglade.sourceforge.net/ which sits on top of wxPython: http://wxpython.org/ which wraps wxWidgets: http://www.wxwindows.org/ I've found that wxGlade is more usable, currently, than Dabo in it's visual layout tools that help you create the GUI for your apps. If you want a more "Pythonic" API (more than wxPython/wxWidgets) and want to write your GUI using mainly code instead of a visual layout tool, then Dabo is probably the way to go. If you want an interactive application that lets you visually create Frame or Dialog based applications, full of "widgets", then wxGlade is pretty good these days. Dabo, last time I looked, didn't yet have a usable visual menu creation capability in it's toolset, and this is a major reason, for me, that I currently have gravitated back to wxGlade. Also, although Dabo has a "Class Designer" that can design the GUI visually, and is in some ways more advanced than wxGlade, it seems in other ways to be more limiting. Neither one, unfortunately, is very well documented, but wxGlade is fairly obvious, and directly generates wxPython code (not a "higher level" API as is done in Dabo), which lets you use the wxGlade and wxWidgets documentation to figure things out. Also, BTW, I think the statement on the wxGlade site about "the generated code does nothing apart from displaying the created widgets", is not really true, and should be re-worded. Current versions of wxGlade include the capability to automatically create simple event-handler functions, and automatically generates the code to connect the events generated by the GUI widgets to the event handlers. In my opinion, this is much more than doing "nothing apart from displaying the created widgets". It helps make it real easy to call your handler functions, and I don't really want it doing much more than that anyway. In either case, when you write your own code, it is probably best to learn how to have the tool generate the code containing the classes that form the GUI interface, but, use derived classes (subclasses) in your own separate file(s) to form your application's interface to the GUI. That way, you can let wxGlade (or Dabo) always generate (and overwrite) its own code that remains entirely separate from your own code. Bill From fn681 at ncf.ca Fri Mar 28 16:22:37 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 28 Mar 2008 16:22:37 -0400 Subject: how to capture screenshots of the active window in Python In-Reply-To: References: <142053.72537.qm@web44801.mail.sp1.yahoo.com> Message-ID: <47ED538D.2020607@ncf.ca> Gabriel Genellina wrote: > En Thu, 27 Mar 2008 20:28:27 -0300, Praveena B > escribi?: > >> Can anyone help me out?? > > Still lacking details... PIL has a ImageGrab module, Windows only. > For Windows, Alt Prtscn usually copies the image to a clipboard. Colin W. From _karlo_ at mosor.net Sun Mar 9 11:56:14 2008 From: _karlo_ at mosor.net (Karlo Lozovina) Date: Sun, 09 Mar 2008 16:56:14 +0100 Subject: Returning values from function to Python shell/IPython Message-ID: Hi all! I have a runTest() function inside my module, which sets up and initializes lots of objects and performs some basic tests on them. Usually (from IPython) I just write `run my_module.py`, and then `runTest()`. But sometimes I would like to manually twiddle with objects runTest creates. Is there any way I can "return" all those objects local to runTest(), and have them available in IPython (or ordinary Python shell)? Thanks... P.S. I know I can do it from a: if __name__ == '__main__': # lots of object initialization... and then have all those objects available in the interpreter. -- Karlo Lozovina -- Mosor From castironpi at gmail.com Mon Mar 10 05:46:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 02:46:17 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> <47D4F207.6050606@behnel.de> Message-ID: > >> And if you really need the efficiency of "well-tuned raw C", it's one function > >> call away in your Cython code. > > > What do you mean by that? > > > I know nothing about how Cython compares to C in performance, so I said > > "well-tuned" because it must be possible to write C that is faster than > > Cython, though it may take some effort. > > So, you write the hand-optimised function in plain C, declare it in Cython and > call it. That's what I meant. Since Cython compiles to C code, linking against > a C module is straight forward. And this still keeps you from having to write > all the Python API glue code in plain C. Python was originally intended to just link C modules, right? (ITTRW if that's the right word?) What are Python's roots? What are its principles? What are its fundamentals? (And what does Python 8! look like!?) We can even get multi-threading running outside of the Global Interpreter Lock, if the thread only acquires it to access shared object code... make that mananged objects. One big decision is if you have a separate Python interpreter running on every remote location, versus say as just a relay mechanism. C on the rest. CMIIW, correct me if I'm wrong, but the productivity bottlenecks vs. performance bottlenecks make a trade-off. For my part, sometimes I get __getattr__ bottlenecks, and other times object instantiation bottlenecks. There was an iterator one in there too. But no I didn't have competing C code to test to compare. If I understand OP correctly, C libraries will be running at all locations, which means they'll need separate compilations. In fact, come to think of it, I'm having trouble with the concept of cross-platform distributed. Do OP mean that lots of programmers are sharing data? Will all the platforms be performing all of the tasks? Or do they specialize? (Not necessarily / no / yes ok.) Lastly, if you can get a boost by buying more servers, then there's a resource bottleneck breakpoint to consider too. From NeilFang2008 at gmail.com Sat Mar 1 21:55:23 2008 From: NeilFang2008 at gmail.com (Neil.Fang.CN) Date: Sat, 1 Mar 2008 18:55:23 -0800 (PST) Subject: class object interface document Message-ID: Hello Where can I find the Python class object interface document, such as struct PyClassObject, PyClass_New()? Thanks! -- Neil From wolf_tracks at invalid.com Mon Mar 31 06:58:20 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 31 Mar 2008 10:58:20 GMT Subject: Class Image.Image? Message-ID: I put a print statement in some Python code to determine the class (__class__) of a variable and the result was Image.Image. Why not just Image; otherwise, what's it telling me? -- Wayne Watson (Nevada City, CA) Web Page: From kyosohma at gmail.com Wed Mar 5 16:38:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 5 Mar 2008 13:38:59 -0800 (PST) Subject: What is a class? References: Message-ID: On Mar 5, 12:50 pm, castiro... at gmail.com wrote: > What is a class that is not a module? Why is a raven like a writing desk? As for Python class information, I would recommend reading the following sites: http://docs.python.org/tut/node11.html http://www.diveintopython.org/object_oriented_framework/defining_classes.html And for modules, check these out: http://docs.python.org/tut/node8.html http://www.penzilla.net/tutorials/python/modules/ Mike From fakeaddress at nowhere.org Tue Mar 25 22:49:04 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Wed, 26 Mar 2008 02:49:04 GMT Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: Benjamin Watine wrote: > OK, so if I understand well what you said, using queue allow to be sure > that the data is passed in totality before coninuing with next > instruction. That make sense. Right. > Using thread and queue seems to be very more slow than using files > redirection with bash. I'll see if it make a great load average and/or > I/O time. Hmmm... you might try increasing the buffer size. -- --Bryan From musiccomposition at gmail.com Sat Mar 15 22:27:07 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 15 Mar 2008 19:27:07 -0700 (PDT) Subject: os.path.isdir question References: Message-ID: On Mar 15, 8:12 pm, lampshade wrote: > Hello, > > I'm having some problems with os.path.isdir I think it is something > simple that I'm overlooking. > > #!/usr/bin/python > import os > > my_path = os.path.expanduser("~/pictures/") > print my_path > results = os.listdir(my_path) > for a_result in results: > if os.path.isdir(str(my_path) + str(a_result)): Try if os.path.isdir(os.path.join(my_path, a_result)): > results.remove(a_result) > > for x in results: print x > > The problem is, that the directories are never removed. Can anyone > point out what I'm missing that is causing the bug? Is there a better > way of doing this? You should always use os.path.join to join paths. You shouldn't add them like normal strings. I suspect you're getting a combination which doesn't exist, so it isn't a dir. :) > > Thanks, From castironpi at gmail.com Sat Mar 1 14:59:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 11:59:43 -0800 (PST) Subject: Surprised by the command "del" References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: On Mar 1, 2:05?pm, "K Viltersten" wrote: > I'm reading the docs and at 5.2 the del > statement is discussed. At first, i thought > i've found a typo but as i tried that > myself, it turns it actually does work so. > > ? a = ["alpha", "beta", "gamma"] > ? del a[2:2] > ? a > > Now, i expected the result to be that the > "beta" element has been removed. Obviously, > Python thinks otherwise. Why?! > > Elaboration: > I wonder why such an unintuitive effect has > been implemented. I'm sure it's for a very > good reason not clear to me due to my > ignorance. Alternatively - my expectations > are not so intuitive as i think. ? :) It's the Phillips vs. the flathead. Is b in x[a:b:c] an endpoint or a distance? This is Python too; you're welcome to implement: - b means length - one-based indices - inclusive - b out of bounds exceptions A slice object (a,b,c) is passed to whatevercollection.__getitem__, .__setitem__, or .__delitem__. From pavlovevidence at gmail.com Mon Mar 3 19:40:22 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 16:40:22 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: <1154e7d6-11e9-40ff-8565-029d2f002e2e@e23g2000prf.googlegroups.com> On Mar 3, 7:24 pm, Mensanator wrote: > On Mar 3, 4:53 pm, Carl Banks wrote: > > > > > On Mar 3, 4:47 pm, Mensanator wrote: > > > > On Mar 3, 2:49 pm, Carl Banks wrote: > > > > > On Mar 3, 3:40 pm, Mensanator wrote: > > > > > > Notice anything funny about the "random" choices? > > > > > > import sympy > > > > > import time > > > > > import random > > > > > > f = [i for i in sympy.primerange(1000,10000)] > > > > > > for i in xrange(10): > > > > > f1 = random.choice(f) > > > > > print f1, > > > > > f2 = random.choice(f) > > > > > print f2, > > > > > C = f1*f2 > > > > > ff = None > > > > > ff = sympy.factorint(C) > > > > > print ff > > > > > > ## 7307 7243 [(7243, 1), (7307, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > > > As in, "they're NOT random". > > > > > > The random number generator is broken by the sympy.factorint() > > > > > function. > > > > > > Random.choice() works ok if the factorint() function commented out. > > > > > > ## 6089 1811 None > > > > > ## 6449 1759 None > > > > > ## 9923 4639 None > > > > > ## 4013 4889 None > > > > > ## 4349 2029 None > > > > > ## 6703 8677 None > > > > > ## 1879 1867 None > > > > > ## 5153 5279 None > > > > > ## 2011 4937 None > > > > > ## 7253 5507 None > > > > > > This makes sympy worse than worthless, as it f***s up other modules. > > > > > Dude, relax. > > > > > It's just a bug--probably sympy is messing with the internals of the > > > > random number generator. It would be a simple fix. Instead of > > > > b****ing about it, file a bug report. > > > > I did. > > > > > Or better yet, submit a patch. > > > > I would if I knew what the problem was. > > > > I posted it here because someone recommended it. > > > I'm simply un-recommending it. Those who don't care > > > needn't pay any attention. Those who do should be > > > glad that faults are pointed out when found. > > > 1. You can point out the faults of a program without insults and > > vulgarity > > Did I insult someone? Yes, the intelligence of most people here, if you think anyone's going to buy your rationalization of your spiteful behavior. Four posts is more than enough of you. *PLONK* Carl Banks From tjreedy at udel.edu Sun Mar 2 17:02:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 17:02:25 -0500 Subject: First post from a Python newbiw References: <62vrleF24ontgU2@mid.uni-berlin.de> Message-ID: "Christoph Zwerschke" wrote in message news:fqf4do$gq7$1 at online.de... | Marc 'BlackJack' Rintsch schrieb: | > On Sun, 02 Mar 2008 14:15:09 +0000, Steve Turner wrote: | > | >> Apart from doing something like | >> a=[0,0,0] | >> b=[0,0,0] | >> c=[0,0,0] | >> d=[a,b,c] | >> | >> is there a better way of creating d?? | > | > a = [[0] * 3 for dummy in xrange(3)] | | Why not simply [[0]*3]*3 ? Because that is essentially the same as what the OP originally did, which does not work as he wanted. From castironpi at gmail.com Fri Mar 7 14:36:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 11:36:52 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <218ee049-13a6-4e97-82b7-5087e635efb7@z17g2000hsg.googlegroups.com> > And so on and so forth. ?The tricky bit is how to tell the difference > between Day, Month and Year. There isn't one. From python at rcn.com Wed Mar 26 04:00:30 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 26 Mar 2008 01:00:30 -0700 (PDT) Subject: Filtering a Python list to uniques References: Message-ID: On Mar 25, 4:30?pm, kellygreer1 wrote: > What is the best way to filter a Python list to its unique members? > I tried some method using Set but got some "unhashable" error. > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > # how do i reduce this to > lsttwo = [ 1, 2, 3, 4, 5, 6 ] If the elements are hashable, try this: lsttwo = sorted(set(lstone)) If not hashable, try: lsttwo = [k for k,v in itertools.groupby(sorted(lstone))] Raymond From mr.ecik at gmail.com Wed Mar 26 18:04:07 2008 From: mr.ecik at gmail.com (=?ISO-8859-2?Q?Micha=B3_Bentkowski?=) Date: Wed, 26 Mar 2008 23:04:07 +0100 Subject: Why does python behave so? (removing list items) Message-ID: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Why does python create a reference here, not just copy the variable? >>> j=range(0,6) >>> k=j >>> del j[0] >>> j [1, 2, 3, 4, 5] >>> k [1, 2, 3, 4, 5] Shouldn't k remain the same? -- Micha? Bentkowski mr.ecik at gmail.com From apatheticagnostic at gmail.com Mon Mar 3 10:43:32 2008 From: apatheticagnostic at gmail.com (apatheticagnostic) Date: Mon, 3 Mar 2008 07:43:32 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 2, 6:16 am, David Cook wrote: > On 2008-03-02, Jeff Schwab wrote: > > > Python In A Nutshell: > >http://www.oreilly.com/catalog/pythonian2/ > > Another vote for the Nutshell book, which I find a very useful and practical > book. > > I never found the "Dive in" book useful. > > Dave Cook Here's another vote for Python in a Nutshell. If you have a lot of experience with other languages, it should be all you need to get up to speed with python quickly. From jerry.fleming at saybot.com Mon Mar 17 21:57:25 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Tue, 18 Mar 2008 09:57:25 +0800 Subject: ctypes in python failed to honor c_int Message-ID: Hi, I have a binary file written with c structures. Each record contains a null-terminated string followed by two 4-bytes integers. I wrote a small segment of python code to parse this file in this way: [coe] #!/usr/bin/python from ctypes import * class Entry(Structure): _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) idx = open('x.idx', 'rb') str = idx.read(1000) obj = Entry(str) print obj.w print obj.s print obj.l [/code] where the field w is the string, and s and l are the integers. Problem is that, I can only get the strings, not the integers. Well, I did got integers, but they are all zeros. What should I do to get the real numbers? Thanks for help. - Jerry From bob.martin at excite.com Mon Mar 10 15:21:14 2008 From: bob.martin at excite.com (Bob Martin) Date: Mon, 10 Mar 2008 19:21:14 GMT Subject: Distributed App - C++ with Python for Portability? References: <63km1jF27n1hpU1@mid.uni-berlin.de> Message-ID: in 337513 20080310 115744 "Diez B. Roggisch" wrote: >Roopan wrote: > >> Hello! >> >> I am looking at developing an enterprise-grade distributed data >> sharing application - key requirements are productivity and platform >> portability. >> >> Will it be sensible to use C++ for performance-critical sections and >> Python for all the glue logic. >> >> Pls comment from your *experiences* how Python scales to large >> projects( > 200KLOC). >> I assume the C++/Python binding is fairly painless. > >It depends. There are good wrappers out there, I personally prefer SIP. >However, a mixed language environment is always a PITA, especially for >distribution. > >If you can, write everything in python. Identify bottlenecks, and if you >must, I suggest using C + ctypes for performance-critical code. > >Obviously it's a matter of taste, but C++ is a beast, and getting it to work >seamless under varying compilers and OSes could be avoided using plain C. > >Diez Java is more portable than most other languages, especially if your app needs a gui. From larry.cebuala at gmail.com Tue Mar 18 02:00:26 2008 From: larry.cebuala at gmail.com (Larry) Date: Mon, 17 Mar 2008 23:00:26 -0700 (PDT) Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> <13400cb5-ca78-4022-9875-4286b29e6d93@i29g2000prf.googlegroups.com> <7xod9cvbq3.fsf@ruckus.brouhaha.com> Message-ID: On Mar 18, 1:32?pm, Paul Rubin wrote: > Larry writes: > > It seems to me that Python always add intervening spaces between data > > elements when writing to a file > > It's just the print statement that does that. I doubt that. I tried one small file, I opened it using the application I mentioned, the display said like data, NaN, data, NaN... I even went further to opening the file using notepad, and did a search-and-replace for space characters. The result was what I desired: data,data,data... From tms at zeetix.com Mon Mar 17 08:17:23 2008 From: tms at zeetix.com (Tom Stambaugh) Date: Mon, 17 Mar 2008 08:17:23 -0400 Subject: No subject Message-ID: <009a01c88828$db718b20$0200a8c0@TMSMAIN> "Duncan Booth" wrote in message news:Xns9A64693269C16duncanbooth at 127.0.0.1... > I've also just spent a while getting simplejson 1.7.4 to install on a > (non- > windows) system without a C compiler. > > The trick is to unzip the tar file and then before you try to install it > delete everything in simplejson.egg-info. Then 'setup.py install' will run > to completion and while it warns about 'speedups are not enabled.' it > doesn't take it as fatal error. > > Without this step it preserves the reference to native_libs.txt in > SOURCES.txt even though the native_libs.txt file itself gets deleted. I had no trouble getting it to install without the speedups -- but the primary reason I upgraded was to take advantage of the speedups! From arnodel at googlemail.com Sun Mar 23 03:56:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Mar 2008 00:56:54 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Message-ID: On Mar 22, 9:11?pm, rh0dium wrote: > Hi all, Hi, > I am struggling with parsing the following data: > > test1 = """ > Technology ? ? ?{ > ? ? ? ? ? ? ? ? name ? ? ? ? ? ? ? ? ? ? ? ? ? ?= "gtc" > ? ? ? ? ? ? ? ? dielectric ? ? ? ? ? ? ? ? ? ? ?= 2.75e-05 [...] I know it's cheating, but the grammar of your example is actually quite simple and the values are valid python expressions, so here is a solution without pyparsing (or regexps, for that matter). *WARNING* it uses the exec statement. from textwrap import dedent def parse(txt): globs, parsed = {}, {} units = txt.strip().split('}')[:-1] for unit in units: label, params = unit.split('{') paramdict = {} exec dedent(params) in globs, paramdict try: label, key = label.split() parsed.setdefault(label, {})[eval(key)] = paramdict except ValueError: parsed[label.strip()] = paramdict return parsed >>> p = parse(test1) >>> p['Layer']['PRBOUNDARY'] {'maskName': '', 'defaultWidth': 0, 'color': 'cyan', 'pattern': 'blank', 'layerNumber': 0, 'minSpacing': 0, 'blink': 0, 'minWidth': 0, 'visible': 1, 'pitch': 0, 'selectable': 1, 'lineStyle': 'solid'} >>> p['Layer']['METAL2']['maskName'] 'metal2' >>> p['Technology']['gridResolution'] 5 >>> HTH -- Arnaud From sjmachin at lexicon.net Mon Mar 10 06:58:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 03:58:23 -0700 (PDT) Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> <48822113-5d03-4937-afb7-d3adb10ed476@x30g2000hsd.googlegroups.com> Message-ID: <79ba8d61-6411-4a5f-862d-43806fb8ed75@d21g2000prf.googlegroups.com> On Mar 10, 9:11 pm, Matt Nordhoff wrote: > castiro... at gmail.com wrote: > >> I believe Python automatically creates and caches int objects for 0-256, > >> so whenever you use them, they refer to the same exact objects. Since > >> ints are immutable, it doesn't matter. > > > One of the biggest hits on start-up time, by the way. ;) > > Well, the developers clearly decided it was worth it at the time. Who > knows, perhaps that's changed since then. > -- Matt, PDFTT. Cheers, John From Afro.Systems at gmail.com Mon Mar 24 01:33:58 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sun, 23 Mar 2008 22:33:58 -0700 (PDT) Subject: encoding/decoding issue with python2.5 and pymssql Message-ID: <3a6c32fe-e7c1-4230-882d-efb3415196c1@b1g2000hsg.googlegroups.com> hi, in my table the field row_id is type of uniqueidentifier. when try to fetch the data, pymssql somehow, encodes the values in a way which yields odd results. for example: the value 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7' is represent as '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7' the only way I manged to pass this is by converting the value into varchar at the server side. I would like to solve this at the python side and not in the database for several obvious reasons see example: >>> conn = mymssql.connect(**connection_details) >>> cur = conn.cursor() >>> sql = "select row_id, cast(row_id as varchar(36)) from table_a" >>> cur.execute(sql) >>> rows = cur.fetchall() >>> rows[0] ('\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7', 'EE604EE3-4AB0-4EE7- AF4D-018124393CD7') >>> >>> From duncan.booth at invalid.invalid Mon Mar 31 14:09:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 18:09:42 GMT Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: xkenneth wrote: > Now obviously, if I test an instance of either class equal to each > other, an attribute error will be thrown, how do I handle this? I > could rewrite every __eq__ function and catch attribute errors, but > that's tedious, and seemingly unpythonic. Also, I don't want an > attribute error thrown whenever two classes are compared that don't > have the same attributes. > > I have a sneaky feeling I'm doing something completely unpythonic > here. > Surely an A isn't equal to every other object which just happens to have the same attributes 'a' and 'b'? I would have thoughts the tests want to be something like: class A: def __eq__(self,other): return (isinstance(other, A) and self.a == other.a and self.b == other.b) (and similar for B) with either an isinstance or exact match required for the type. From deets at nospam.web.de Sat Mar 22 11:44:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 22 Mar 2008 16:44:23 +0100 Subject: NameError: name 'guess' is not defined In-Reply-To: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> References: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> Message-ID: <64knqtF2cdrc4U1@mid.uni-berlin.de> willkab6 at gmail.com schrieb: > I am very new to both programming and Pyhton and while trying to do > some practice using A byte of python an Error pops up on the IDLE > shell. I am using windows XP. PLease see below. > while running: > guess = int(raw_input('Enter an integer : ')) > > if guess == number: > print 'Congratulations, you guessed it.' > running = False # this causes the while loop to stop > elif guess < number: > print 'No, it is a little higher than that.' > else: > print 'No, it is a little lower than that.' > else: > print 'The while loop is over.' > # Do anything else you want to do here > > print 'Done' > > After typing the above as the book says, I get the error NameError: > name 'guess' is not defined > What Am I doing wrong? You most certainly did NOT write the above - because in Python whitespace is significant, and thus the above would result in a syntax-error because you need to have things like if condition: something() and not if condition: something() So unless you post what you *really* entered (and make sure your NG-client/mailclient doesn't eat leading whitespace), nobody will be able to help you. Diez From seberino at spawar.navy.mil Sat Mar 29 16:49:46 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Sat, 29 Mar 2008 13:49:46 -0700 (PDT) Subject: What motivates all unpaid volunteers at Pycon? Message-ID: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> I was impressed and humbled by all the unpaid volunteers at Pycon. I was wondering what motivated so many people to give so much to the Python community. (I have my guesses but I'd rather listen than assume I know.) Any ideas? Chris From castironpi at gmail.com Wed Mar 5 22:43:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 19:43:52 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: <7a8a2706-10d0-4f50-b5ad-8b490e57edd5@y77g2000hsy.googlegroups.com> On Mar 5, 8:31?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 21:05:31 -0500, Terry Reedy wrote: > > If I understand your question, classes are not singletons: > >>>> ll=[] > >>>> for i in range(2): > > ?import string > > ?ll[i]=string > > Where's the IndexError? :-) > > >>>> ll[0] is ll[1] > > True > > But yes, modules are singletons in that way, at least if you go through > the import mechanism. > > >>>> for i in range(2): > > ?class C: pass > > ?ll[i] = C > > >>>> ll[0] is ll[1] > > False > > Ah, but each time around the loop you create a *new class* that just > happens to be called C. An alternative way to see similar behaviour is: > > def foo(x=None): > ? ? class C(object): > ? ? ? ? X = x > ? ? return C > > Naturally foo() is foo() gives False -- although both classes are called > C, they are different classes that just happen to have the same state. > > I accept my question about classes being singletons is not well-formed, > not even in my own mind. I guess one way of asking is, for any two class > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? >>> class metaC( type ): ... def __eq__( self, other ): ... return random.choice([ True, False ]) ... >>> class C( metaclass= metaC ): ... pass ... >>> import random >>> C==C True >>> C==C False >>> C==C False >>> C==C True >>> C==C False >>> You made me think of this. What relevance it has is open to debate. ...In a separate thread. http://en.wikipedia.org/wiki/Relevance It's my Signal-channel signal signal. From aiya.vinay at gmail.com Tue Mar 11 14:07:27 2008 From: aiya.vinay at gmail.com (Vinay Aiya) Date: Tue, 11 Mar 2008 23:37:27 +0530 Subject: help regarding xml parser modules Message-ID: Hello, Can any one help for error in following code. actually i want to map the element name with its data between start and end tag , but i am unable to do so. here is the code which i am trying for please do reply if i am not on right track. import xml.sax.handler class BookHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inTitle1 = 0 self.inTitle2 = 0 self.mapping1 = {} self.mapping2 = {} def startElement(self, name, attributes="NULL"): #attributes="None" if name == "emph3": self.buffer1 = "" self.inTitle1 = 1 # self.id = attributes["None"] elif name == "year": self.buffer2 = "" self.inTitle2 = 1 def characters(self,data): if self.inTitle1 == 1: self.buffer1 += data elif self.inTitle2 == 1: self.buffer2 += data def endElement(self,name): if name == "year": self.inTitle2 = 0 self.mapping2[self.name] = self.buffer2 elif name =="emph3": self.inTitle1 =0 self.mapping1[self.name] = self.buffer1 this is an xml file an example # # # Jose Joaquin Avila # 1929 # # Yiye Avila # 1941 # # This is main file import xml.sax import try1 import pprint parser = xml.sax.make_parser() handler = try1.BookHandler() parser.setContentHandler(handler) parser.parse("tp.xml") pprint.pprint(handler.mapping1) pprint.pprint(handler.mapping2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From userprogoogle-139 at yahoo.co.uk Tue Mar 18 12:27:46 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Tue, 18 Mar 2008 09:27:46 -0700 (PDT) Subject: Need Help Starting Out References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <4aa24daf-4f7b-405e-83c2-d1face854ed1@s37g2000prg.googlegroups.com> > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. Hi, For database stuff you can plug directly into either MySQL or SQLite. For MySQL you need to install a third party library which you can get from: http://sourceforge.net/projects/mysql-python I think SQLite support is now included in Python 2.5, all you need to do is type "import sqlite3", and away it goes. You will of course need to install SQLite, just search for it online. I found SQlite more than sufficient for any single user non-web based apps. On the client side you can use these library and if you like build a free standing app to run everything. For GUI toolkits you can do worse than download and install wxPython, which again is free (www.wxpython.org). If you want to dabble in games programming there is also PyGame. If you want to build free standing applications you can use Py2Exe (Windows) and Py2App (Mac), just Google them and they will appear. You may at times find Python a little slow, and you can even get round that problem in Windows and Intel based Macs by using Psyco (again just Google). It can speed up your code by quite a large margin. Hope these help you get started... Rod From gagsl-py2 at yahoo.com.ar Fri Mar 7 09:49:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 12:49:39 -0200 Subject: How to clear a list (3 ways). References: Message-ID: En Fri, 07 Mar 2008 09:39:05 -0200, escribi?: > Executive summary : What idiom do you use for resetting a list ? > lst = |] # (1) > lst[:] = [] # (2) > del lst[:] # (3) (3) if I want to keep the same list else (1) An example when (1) is desirable: # generate lines of text not exceeding 40 chars # yields a list of words forming a line def gen_lines(words): line = [] width = 0 for word in words: if width + len(word) + 1 > 40: yield line # <<< del line[:] # <<< width = 0 line.append(word) width += len(word) + 1 yield line import string words = string.__doc__.split() # some text lines = list(gen_lines(words)) print lines [['considered', 'printable'], ['considered', 'printable'], ['considered', 'print able'], ['considered', 'printable'], ['considered', 'printable'], ... In this case, yielding always the same object isn't a good idea if the consumer doesn't process it immediately. Changing the generator function to use the method (1) gives the expected result (or, one could say, lessens the coupling between the generator and its consumer). -- Gabriel Genellina From frank at chagford.com Tue Mar 11 01:17:16 2008 From: frank at chagford.com (Frank Millman) Date: Mon, 10 Mar 2008 22:17:16 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules) References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> Message-ID: Gilles Ganault wrote: > On Mon, 10 Mar 2008 11:27:06 -0400, "Malcolm Greene" > wrote: > >Any suggestions on an alternative Python client-side GUI library (pyQT > >?) or tips on where I can find out more about wxPython/wxWidget > >problems? > > One thing that bothers me is that it seems like there's no ecosystem > around it, so the only widgets available are those that come from > wxWidgets proper. > > For instance, I find the grid object a bit poor-featured compared to > what's available for VB6, .Net, or Delphi, but I didn't find > alternatives. I do not know if this helps, but here is an extract from a recent post to the wxPython mailing list from Robin Dunn, the main developer of wxPython - "The new wxDataViewCtrl coming in 2.9 might make this unnecessary. Think of it as a wxListCtrl that is always in virtual mode with a plug- in data model, can optionally have hierarchical data (like wxTreeCtrl) in one of the columns, and where every column can have a custom renderer/editor for the cells like wxGrid. And it uses the native controls on Mac and GTK. I've been working on the wrappers for it off and on over the past few weeks and while it is a complex beast, it will probably be easier to use than wxGrid in most cases and easier than wxListCtrl in some cases too." I also strongly recommend using the mailing list for any questions, problems, or feature requests. Robin is a very active contributor to the list, and frequently provides very insightful answers. Also there are a number of other active contributors, some of whom have designed their own composite widgets using the underlying components of the toolkit, and are happy to share them. Frank Millman From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 17:25:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 22:25:53 -0000 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> Message-ID: <13su7fhdj3rdk70@corp.supernews.com> On Wed, 05 Mar 2008 13:49:20 -0800, castironpi wrote: > Classes and modules are really similar. In Python they're really > *really* similar. Yes they are. Both are namespaces. The very last line of the Zen of Python says: >>> import this ... Namespaces are one honking great idea -- let's do more of those! http://en.wikipedia.org/wiki/Namespace -- Steven From mdboldin at gmail.com Sat Mar 1 10:00:17 2008 From: mdboldin at gmail.com (mdboldin at gmail.com) Date: Sat, 1 Mar 2008 07:00:17 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> Message-ID: <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> Steve, I want to make sure I understand. My test code is below, where ph serves as a placeholder. I am preparing for a case where the number of ? will be driven by the length of the insert record (dx) dtable= 'DTABLE3' print 'Insert data into table %s, version #3' % dtable ph= '?, ?, ?, ?' sqlx= 'INSERT INTO %s VALUES ( %s ) ' % (dtable,ph) t0a=time.time() for dx in d1: curs1.execute(sqlx,dx) print (time.time()-t0a) print curs1.lastrowid conn1.commit() I think you are saying that sqlx is re-evaluated in each loop, i.e. not the same as pure hard coding of sqlx= 'INSERT INTO DTABLE3 VALUES ( ?, ?, ?, ? ) ' Is that right? Hence (if I understand python convention), this can be solved by adding sqlx= copy.copy(sqlx) before the looping. And in tests adding this step saved about 5-10% in time. And yes, I can see why (B) is always better from a security standpoint. The python solutions for problems such as there are a great help for people like me, in the sense that the most secure way does not have a speed penalty (and in this case is 3-4x faster). From gagsl-py2 at yahoo.com.ar Sun Mar 30 19:36:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 20:36:53 -0300 Subject: Creating Class Objects in Loop References: <4dbe90f1-b70a-4e7c-b400-0e5cb4ce3b68@s13g2000prd.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 19:59:14 -0300, Fish escribi?: > Hello Folks, > I am reading a CSV file and based on that I am creating TestCase(my > own defined class) objects in a for loop. The problem is each time I > create a new TestCase object in loop, previous objects data is already > copied in that object. See this FAQ entry: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects > ======= Problem Code > > The function snippet reading CSV and creating TestCase objects is > [code] > tcLst = [] > # CSV file is read in variable 'lines' Try to use the standard csv module instead; it's fairly easy. > def returnTcLst(path): > fp = open(path) > lines = fp.readlines() > for line in lines: Instead of those two lines, you could use: for line in fp: (readlines() has to read the whole file into memory; files are their own line iterators) > tc.setPcap(line[:i].strip()) getters/setters are not usually used in Python because they offer no advantage over directly using an attribute: tc.pcap = line[:i].strip() > tcLst.append(tc) > del tc Why "del tc"? That doesn't invoke the destructor, just removes the name "tc" from the local namespace. (The object tc refers to isn't destroyed yet because it has at least one reference: it's contained in the tcLst list) > class TestCase(object): > def __init__(self, pcap = None, sids = []): > self.__Pcap = pcap > self.__lstSid = sids As you can see in the FAQ entry, the common idiom is to write: def __init__(self, pcap = None, sids = None): if sids is None: sids = [] self.Pcap = pcap self._lstSid = sids Note that I've changed the __names; use __ when you expect a name collision with a subclass. For "implementation only" attributes, use a single underscore; based on your appendSid method, lstSid looks like it's used in this way. > def setPcap(self, path): > self.__Pcap = path This method isn't necesary anymore. > def appendSid(self, sid): > def __str__(self): Should be changed accordingly. -- Gabriel Genellina From rschroev_nospam_ml at fastmail.fm Fri Mar 14 18:16:43 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Mar 2008 23:16:43 +0100 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: castironpi at gmail.com schreef: > On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>> Subject: RIP: Joseph Weizenbaum >>> Creator of Eliza: >>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>> -- >> How do you feel about creator of Eliza? > > What is Eliza? Does that question interest you? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ron.longo at cox.net Thu Mar 20 16:15:47 2008 From: ron.longo at cox.net (Ron Provost) Date: Thu, 20 Mar 2008 16:15:47 -0400 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module inPy3.0] References: Message-ID: <00b801c88ac7$2f643340$6501a8c0@aristotle> I would really hate to see Tkinter removed from 3.0. Because it's part of the distribution and extremely easy to create simple GUIs I use it all the time. Isn't Python supposed to be a "Batteries Included" language? Can that be said anymore without a GUI library? And do we want to drop Tkinter only now, when tk seems to finally be getting renewed attention after years of neglect? ----- Original Message ----- From: "Daniel Fetchinson" To: Sent: Thursday, March 20, 2008 3:39 AM Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module inPy3.0] >> Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , >> and saw that the repr module was slated for vaporization. I've only >> used the module a few times ever. I'm curious if the community wants >> it kept around or whether it is considered clutter. >> >> The PEP is going to be finalized soon, so if you have issues with it, >> they should be sent to the PEP author or brought up on the list, >> http://mail.python.org/mailman/listinfo/stdlib-sig . > > Is it just me or others also think that it would be a major loss to > remove tkinter from the python core? PEP 3108 starts off with: > > Each module to be removed needs to have a justification as to why it > should no longer be distributed with Python. > > then goes on with, > > With so many other GUI options out there that are considered better > than Tkinter, it might be best to remove Tkinter from the stdlib and > make it an externally maintained package. > > I don't get it. There are many [insert your favorite software > component] options outside of the python core that are considered > better than the one coming with python, yet they don't get removed. > All network servers for example could be thrown out because twisted is > considered better. This just doesn't make sense to me. Tkinter is > great for its purpose, typical use cases are creating a simple GUI > composed of a couple of components only. You can nicely do this with > tkinter and the large user base shows that it's a real need real > people have. Sure, for fancy GUI stuff there are better options but > for quick and simple things tkinter is just great. And last time I > checked python comes with batteries included so why sould I need to > search and download a third party package for such a common use case? > > Thoughts anyone? > > Cheers, > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list From grahn+nntp at snipabacken.se Mon Mar 31 06:30:54 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 31 Mar 2008 10:30:54 GMT Subject: Where can I find : References: <13uu56hn1vdqb9d@corp.supernews.com> <13v0997i28t8i90@corp.supernews.com> Message-ID: On Sun, 30 Mar 2008 16:41:31 -0700, Dennis Lee Bieber wrote: > On 30 Mar 2008 23:07:02 GMT, Jorgen Grahn > declaimed the following in comp.lang.python: > >> >> He *might* simply be talking about if, for, while, break and so on -- >> things which control program flow. >> > Which /is/ what I was referring to... with regards to structuring > the usage of said in a safe&sane manner Oh, sorry. I see that now. I was thinking of flow control as in communication protocols, preventing a fast sender from flooding a receiver and so on. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From micah at hollister.bcsweb.com Wed Mar 5 22:38:50 2008 From: micah at hollister.bcsweb.com (Micah Cowan) Date: Thu, 06 Mar 2008 03:38:50 GMT Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: Steven D'Aprano writes: > I recall that Python guarantees that module objects are singletons, and > that this must hold for any implementation, not just CPython: you can > only ever create one instance of a module via the import mechanism. But > my google-foo is obviously weak today, I cannot find where the Python > language reference guarantees that. Can somebody please point me at the > link making that guarantee? It's not an absolute strict guarantee; it's just implied by the fact that "import" uses any appropriate objects already found in sys.modules. >>> import sys >>> ll = [] >>> for i in range(2): ... import string ... ll.append(string) ... del sys.modules['string'] ... >>> ll[0] is ll[1] False (I'm sure there are very good reasons never to do what I just did there.) -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From castironpi at gmail.com Sat Mar 1 20:58:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 17:58:05 -0800 (PST) Subject: Where's GUI for Python? References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> <62uauaF2400f1U1@mid.individual.net> Message-ID: On Mar 1, 6:49?pm, "K Viltersten" wrote: > >> When that fails, try without the stutter > > >> import tkinter > > > I must be doing something wrong because > > neither tkinter nor tkininter works. > > I tried both with and without stuttering. > > I even asked my wife to stutter some but, > > sadly, to no avail. > > > When Tim Chase mentioned "battery-installed", > > i interpreted it as "all is there". It seems > > that either > > a) not all the batteries are installed in my > > version (v2.5.2) > > or > > b) some setup/linkage needs to be performed > > in order to get the GUI running. > > > The error itself is: > > ImportError: No module named tkinter > > > Suggestions? > > Here's a suggestion. Python is case-sensitive, > while the users trying to help you are not. > When they say "tininkerbell", they may mean > "Tinkerbell". Check with "help()", then > "modules" and see if it's installed or not. > > Sincerely > Yourself > > :) > > (Seriously speaking - i'm thankful.)- Hide quoted text - > > - Show quoted text - AmbiguityWarning: Variables 'tklst' and 'tklist' resemble 'tkst'. Automatic snap-to-slot has been disabled. From strombrg at gmail.com Sat Mar 8 12:39:17 2008 From: strombrg at gmail.com (Dan Stromberg) Date: Sat, 08 Mar 2008 17:39:17 GMT Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: <9bAAj.15017$0o7.13276@newssvr13.news.prodigy.net> On Sun, 02 Mar 2008 23:05:27 -0500, Roy Smith wrote: > In article > , > Gabriel Genellina wrote: > >> On 2 mar, 17:21, castiro... at gmail.com wrote: >> >> > This worked: >> > >> > import socket >> > from time import time >> > >> > for i in range( 20 ): >> > ? ? HOST = '' >> > ? ? PORT = 80 #<---- >> > ? ? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> > ? ? s.bind((HOST, PORT)) >> > ? ? print( 'listen' ) >> > ? ? s.listen(1) >> > ? ? conn, addr = s.accept() >> > ? ? print( 'connected', addr ) >> > ? ? print( conn.recv( 4096 ) ) #<---- >> > ? ? conn.send( bytes('test %f> > html>'%time(),'ascii') ) >> > ? ? conn.close() #<---- >> > ? ? s.close() >> > >> > ... and connect with a browser: ?http://localhost/if it's internet >> > exploder. >> >> Note that there is no need (nor is desirable) to close and rebind the >> listening socket for each connection. > > I'd say, "nor is desirable", is an understatement. On most systems, an > attempt to re-bind to a given port number soon after it was unbound will > fail (unless you utter magic ioctl incantations). This will manifest > itself in the s.bind() call raising an exception on the *second* pass > through the loop. I believe the incantation may be setsockopt(), not ioctl(), but if there's an ioctl() way of doing it, i'd be interested in seeing it. From sjmachin at lexicon.net Thu Mar 27 04:00:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 01:00:01 -0700 (PDT) Subject: do 'os.path' include 'os' for us? References: Message-ID: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> On Mar 27, 6:41?pm, Jerry Fleming wrote: > Hi, > > I wrote a python script to list files in a directory but somehow did it > wrongly by importing os.path instead of os. To my astonishment, it works > just as charm: > #!/usr/bin/python > import os.path > for file in os.listdir('/root/'): > ? ? ? ? print file > > I was wondering why? os.path doesn't contain listdir, why there is no > complaint like 'os: unknown name'? Does this mean, instead of importing > os, we can import os.path? > import os.path in effect imports os, and then os.path, and injects the latter into the former as an attribute. If it didn't, then when you tried to use (say) os.path.join, it would raise an exception. Why don't you do some experimentation at the interactive prompt e.g. import os.path type(os) dir(os) a = os a.path a = nonesuch # The above will show you what the actual meesage is instead of complaint like 'os: unknown name' :-) HTH, John From furkankuru at gmail.com Tue Mar 25 08:48:03 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:48:03 +0200 Subject: Inheritance question In-Reply-To: <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: <3a4a8f930803250548m28f74b7cye1f3bc2de06c74a@mail.gmail.com> a = super(Foo, self).getid() should be a = super(FooSon, self).getid() On Tue, Mar 25, 2008 at 2:34 PM, Tzury Bar Yochay wrote: > > Rather than use Foo.bar(), use this syntax to call methods of the > > super class: > > > > super(ParentClass, self).method() > > Hi Jeff, > here is the nw version which cause an error > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = super(Foo, self).getid() > b = self.id > return '%d.%d' % (a,b) > > > FooSon().getid() > > > Traceback (most recent call last): > File "a.py", line 19, in > FooSon().getid() > File "a.py", line 14, in getid > a = super(Foo, self).getid() > AttributeError: 'super' object has no attribute 'getid' > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From spe.stani.be at gmail.com Sat Mar 1 17:03:47 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 1 Mar 2008 14:03:47 -0800 (PST) Subject: Please test Phatch on Windows (was Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL) References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: I have been working the last couple of days purely on bug fixing and to port the code of Phatch fully to Windows as there were many issues. This has improved: - Phatch can now create droplets on Windows (win32 extensions required) - Installed fonts are retrieved from the Windows registry - Image file dialogs are now working correctly - Missing icons are added (including a phatch.ico) and are now displayed in the windows titlebars - Image Inspector was missing a panel - Preview in Image Inspector now displays correctly - (...) Besides that Phatch now features for all platforms: - fonts can be defined with a nice dropdown autocomplete list - drop down lists with convenient values in all actions - the action masks now ships with some predefined masks (such as torn edges) - right click in the actions dialog box to see the source of an action - View>Droplet nows shows the name of the action box rendered in the logo - Dutch translation is 100% complete As such no new features have been added, but the user experience feels much more polished now. Please read *carefully* the installation instructions first: http://photobatch.wikidot.com/install#toc6 People who have been using Phatch before should clear their font cache (if it exists). Simply delete the file: C:\Documents and Settings\Username\.phatch\fonts I did the Phatch port on a Windows 2000 machine, so I am curious to hear how Phatch works on Windows XP and Vista. I will fix any bug (as far as possible) which is reported quickly in the next couple of days. You can help translating Phatch here: https://translations.launchpad.net/phatch/trunk/+pots/phatch Thanks in advance, Stani On 18 feb, 15:58, "SPE - Stani's Python Editor" wrote: > I'm pleased to announce the release ofPhatchwhich is a > powerful batch processor and renamer.Phatchexposes a big part of the > Python Imaging Library through an user friendly GUI. (It is using > python-pyexiv2 to offer more extensive EXIF and IPTC support.)Phatch > is not targeted at manipulating individual pictures (such as with > Gimp), but repeating the same actions on hundreds or thousands of > images. > > If you know PIL and have some nice recipes laying around, it is very > easy to write plugins asPhatchgenerates the corresponding GUI > automagically just like in Django. Any existings PIL scripts can be > added very easily. Let me know if you want to contribute or have any > questions. > > Homepage:http://photobatch.stani.be(free download link below) > Tutorials:http://photobatch.wikidot.com/tutorials > Translations:https://translations.launchpad.net/phatch/trunk/+pots/phatch > License: GPLv3 > Screenshot:http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg > (the perspective and reflection is produced byPhatchitself) > > Phatchhas many features, like: > - EXIF information inspector with thumbnail > - limit jpeg file size when saving > - tons of actions organized by tags (including perspective, round > corners, shadow, reflection, ...) > - console version (Phatchcan now run without a gui on servers) > - batch rename and copy files based on exif metadata > - data stamping (http://photobatch.wikidot.com) > - online documentation wiki (http://photobatch.wikidot.com) > > Linux only features: > - desktop or panel droplets on which images or folders can be dropped > (will be ported to Windows & Mac) > - Nautilus and desktop integration (with its own mime type and > nautilus extension) > - manpage with examples > > With python-pyexiv2 the following featues are added: > - embedding the original EXIF and IPTC tags in the image > > All actions mostly have a separate pil function in their source code, > so they could be read as a recipe book for PIL: > * Auto Contrast - Maximize image contrast > * Background - Put colour under transparent image > * Border - Crop or add border to all sides > * Brightness - Adjust brightness from black to white > * Canvas - Crop the image or enlarge canvas without resizing the image > * Colorize - Colorize grayscale image > * Common - Copies the most common pixel value > * Contrast - Adjust from grey to black & white > * Convert Mode - Convert the color mode of an image (grayscale, RGB, > RGBA or CMYK) > * Copy - Copy image file > * Effect - Blur, Sharpen, Emboss, Smooth, ... > * Equalize - Equalize the image histogram > * Fit - Downsize and crop image with fixed ratio > * Grayscale - Fade all colours to gray > * Invert - Invert the colors of the image (negative) > * Maximum - Copies the maximum pixel value > * Mask - Apply a transparency mask > * Median - Copies the median pixel value > * Minimum - Copies the minimum pixel value > * Offset - Offset by distance and wrap around > * Posterize - Reduce the number of bits of colour channel > * Perspective - Shear 2d or 3d > * Rank - Copies the rank'th pixel value > * Reflect - Drops a reflection > * Rename - Rename image file > * Rotate - Rotate with random angle > * Round - Round or crossed corners with variable radius and corners > * Saturation - Adjust saturation from grayscale to high > * Save - Save an image with variable compression in different types > * Scale - Scale an image with different resample filters. > * Shadow - Drop a blurred shadow under a photo with variable position, > blur and color > * Solarize - Invert all pixel values above threshold > * Text - Write text at a given position > * Transpose - Flip or rotate an image by 90 degrees > * Watermark - Apply a watermark image with variable placement (offset, > scaling, tiling) and opacity > > I developPhatchon Ubuntu/Linux, but I have tested and polished it > regularly on Windows and Mac Os X. (Only the droplet functionality > needs to be ported.)Phatchis submitted to Debian unstable and > Ubuntu Hardy. Packagers for other platforms are welcome. > > Requirements: > - PIL 1.1.5 or higher > - wxPython 2.6 or higher > - pyexiv2 (optional) > - python nautilus bindings (optional) > > Best regards, > Stani > --http://pythonide.stani.be From dblubaugh at belcan.com Wed Mar 19 12:17:01 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Wed, 19 Mar 2008 12:17:01 -0400 Subject: Python to C/C++ Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> To All, Has anyone worked with a translator that will translate python to c/c++ source code? I know that there is already one translator of this nature (shedskin compiler) out there. However, it is still in the beta stage of development. Does anyone know of a more developed version of a translator of this nature? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 23:20:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 03:20:34 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> Message-ID: <13uu1o25912ulb0@corp.supernews.com> On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote: > Or maybe: > > def main(): > global func > func = factory() > return timeit.Timer('func()', 'from __main__ import func').timeit() Alas, this does not work, because all the Timer instances share the same state. import timeit, time def test_timer(func1, func2): global gFUNC gFUNC = func1 T1 = timeit.Timer('gFUNC()', 'from __main__ import gFUNC') gFUNC = func2 T2 = timeit.Timer('gFUNC()', 'from __main__ import gFUNC') print "Calling %s" % func1.__name__ T1.repeat(3, 1) print "Calling %s" % func2.__name__ T2.repeat(3, 1) def functionA(): print "Function A" def functionB(): print "Function B" And here's the results: >>> test_timer(functionA, functionB) Calling functionA Function B Function B Function B Calling functionB Function B Function B Function B -- Steven From davidj411 at gmail.com Tue Mar 11 09:49:49 2008 From: davidj411 at gmail.com (davidj411) Date: Tue, 11 Mar 2008 06:49:49 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same Message-ID: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> anydbm and dictionary{} seem like they both have a single key and key value. Can't you put more information into a DBM file or link tables? I just don't see the benefit except for the persistent storage. d= dbm.open('c:\\temp\\mydb.dat','n') It has the following interface (key and data are strings): d[key] = data # store data at key (may override data at # existing key) data = d[key] # retrieve data at key (raise KeyError if no # such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = key in d # true if the key exists list = d.keys() # return a list of all existing keys (slow!) From istvan.albert at gmail.com Tue Mar 4 16:00:34 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Tue, 4 Mar 2008 13:00:34 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <5dbcfc89-4ee3-4c3a-b724-92954e8882b5@s12g2000prg.googlegroups.com> Message-ID: <042d507d-f53d-4219-be6e-d6b7a1f1d6c4@s8g2000prg.googlegroups.com> On Mar 4, 3:13 pm, Mensanator wrote: > But what if _I_ wanted to make a repeatable sequence for test > purposes? Wouldn't factorint() destroy my attempt by reseeding > on every call? Would it? It may just be that you are now itching to see a problem even where there isn't one. i. From watine at cines.fr Thu Mar 13 07:13:54 2008 From: watine at cines.fr (Benjamin Watine) Date: Thu, 13 Mar 2008 12:13:54 +0100 Subject: How to send a var to stdin of an external software Message-ID: <47D90C72.2020401@cines.fr> Hi the list, I need to send a var to stdin of an external soft ("cat" command for example). How can I do this ? I would like a function like that : theFunction ('cat -', stdin=myVar) I don't need to get any return value. Another related question : Is there's a limitation of var size ? I would have var up to 10 MB. Thanks ! Ben From robert.rawlins at thinkbluemedia.co.uk Thu Mar 13 12:03:35 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 13 Mar 2008 16:03:35 -0000 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <47D94D61.9010708@jouy.inra.fr> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> <47D94D61.9010708@jouy.inra.fr> Message-ID: <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> Hi Guys, Well thanks for the response, I followed your advice and chopped out all the crap from my class, right down to the bare __init__ and the setter method, however, the problem continued to persist. However, Robert mentioned something about unindented lines which got me thinking so I deleted my tab indents on that method and replaces them with standard space-bar indents and it appears to have cured the problem. Usually my Eclipse IDE throws up an error about this but for some reason decided not too this time around, what a PITA. Thanks for the ideas guys, I appreciate it. Robert -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Bossy Sent: 13 March 2008 15:51 To: python-list at python.org Subject: Re: "Attribute Doesnt Exist" ... but.... it does :-s Robert Rawlins wrote: > > Hello Guys, > > I've got an awfully aggravating problem which is causing some > substantial hair loss this afternoon J I want to get your ideas on > this. I am trying to invoke a particular method in one of my classes, > and I'm getting a runtime error which is telling me the attribute does > not exist. > > I'm calling the method from within __init__ yet it still seems to > think it doesn't exist. > > Code: > > # Define the RemoteDevice class. > > class *remote_device*: > > # I'm the class constructor method. > > def *__init__*(/self/, message_list=/""/): > > /self/.set_pending_list(message_list) > > def *set_pending_list*(/self/, pending_list): > > # Set the message list property. > > /self/.pending_list = message_list > > And the error message which I receive during the instantiation of the > class: > > File: "/path/to/my/files/remote_device.py", line 22, in __init__ > > self.set_pending_list(message_list) > > AttributeError: remote_device instance has no attribute 'set_pending_list' > > Does anyone have the slightest idea why this might be happening? I can > see that the code DOES have that method in it, I also know that I > don't get any compile time errors so that should be fine. I know it > mentions line 22 in the error, but I've chopped out a load of non > relevant code for the sake of posting here. > Hi, I don't get this error if I run your code. Maybe the irrelevant code causes the error: my guess is that there's a parenthesis mismatch or an undeindented line. Btw, calls to set_pending_list will fail since the name "message_list" is not defined in its scope. Please follow Chris Mellon's advice. Cheers, RB -- http://mail.python.org/mailman/listinfo/python-list From fakeaddress at nowhere.org Thu Mar 6 04:00:39 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 06 Mar 2008 01:00:39 -0800 Subject: Bit twiddling floating point numbers In-Reply-To: <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> Message-ID: <%oOzj.61235$Pv2.29718@newssvr23.news.prodigy.net> Mark Dickinson wrote: > Jeff Goldfin wrote: >> I can pack and unpack a float into a long >> e.g. >> struct.unpack('I',struct.pack('f',0.123))[0] >> but then I'm not sure how to work with the resulting long. >> >> Any suggestions? > > One alternative to using struct is to use math.ldexp and math.frexp: > >>>> m, e = frexp(pi) >>>> m > 0.78539816339744828 >>>> e > 2 >>>> int(m*2**53) > 7074237752028440L > > Then you can do your bit twiddling on int(m*2**53), before using > ldexp to 'repack' the float. Ah, those are handy. Jeff described his problem: "In particular, I would like to round my float to the n most significant bits." I think this works: from math import frexp, ldexp, floor def round_mantissa(x, nbits): shifter = 1 << nbits (m, e) = frexp(x) m = floor(m * shifter + 0.5) / shifter return ldexp(m, e) -- --Bryan From nagle at animats.com Thu Mar 6 13:44:31 2008 From: nagle at animats.com (John Nagle) Date: Thu, 06 Mar 2008 10:44:31 -0800 Subject: Data aggregation In-Reply-To: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> References: <4b10564a-e747-4e43-b2f9-0c1f9ba31b7c@p73g2000hsd.googlegroups.com> Message-ID: <47d039a6$0$36391$742ec2ed@news.sonic.net> vedranp wrote: > I would like to avoid the step of taking data out from database in > order to process it. You can probably do this entirely within SQL. Most SQL databases, including MySQL, will let you put the result of a SELECT into a new table. John Nagle From mensanator at aol.com Sun Mar 16 12:36:03 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 16 Mar 2008 09:36:03 -0700 (PDT) Subject: Basics of Python,learning References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <73557ae7-85de-4aa2-bfc6-b02cef67d430@m34g2000hsc.googlegroups.com> On Mar 16, 11:25?am, Guido van Brakel wrote: > Hello > > Why is this not working, Why is _what_ not working? > and how can I correct it? Start over. > > > > > > > #!/usr/bin/env python > > #coding=utf-8 > > > z = raw_input ('Give numbers') > > y = z.split() > > b=[] > > > for i in y: > > ? ? ?b.append(float(i)) > > > def b(min,max,gem) > > ? ? x=min(a) > > ? ? x=gem(a) > > ? ? x=max(a) > > ? ? return a > > > print min(a) > > print max(a) > > print gem(a) > > Regards, > > -- > Guido van Brakel > Life is like a box of chocolates, you never know what you're gonna get > --- Hide quoted text - > > - Show quoted text - From siti.nurhaliza5 at gmail.com Wed Mar 26 03:15:49 2008 From: siti.nurhaliza5 at gmail.com (siti) Date: Wed, 26 Mar 2008 00:15:49 -0700 (PDT) Subject: Computer Shop center Message-ID: <27749a9c-e9ec-46bc-b242-e9deacff6d2d@s12g2000prg.googlegroups.com> Hi friends. if you wanna looking the latest original software..mobile phone...laptop..pc.. accessories... you can search at here..it will give the best price for you. Amazon has teamed up with Allianz Insurance plc who can offer you insurance on this product, covering accidental damage and breakdown.Amazon Services Europe SARL is an introducer appointed representative of Allianz Insurance plc which is authorised and regulated by the Financial Services Authority. AmazonServices Europe SARL, 5 Rue de Plaetis, L-2338, Luxembourg, is not part of the Allianz (UK) Group. The insurance is arranged, sold and administered by Allianz. By purchasing this insurance you confirm that you have read and understood the Technical details, product description and Keyfacts document provided by Allianz. This your URL http://astore.amazon.co.uk/happyfamily-21 From sam at mas.pl Thu Mar 20 11:44:43 2008 From: sam at mas.pl (sam) Date: Thu, 20 Mar 2008 16:44:43 +0100 Subject: Prototype OO In-Reply-To: <47e24b99$0$24941$426a74cc@news.free.fr> References: <47e24b99$0$24941$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers napisa?(a): > Most of the arguments in favor of prototypes seems to come to, mainly: > 1/ it lets you customize behaviour on a per-object base > 2/ it removes the mental overhead of inheritance, classes etc > > Point 1. is a non-problem in Python, since you can already add/replace > methods on a per-objec basis (ok, with a couple restrictions wrt/ > __magic__ methods and such). > > Point 2. is not (IMHO) such a problem in Python, where inheritance is > mainly an implementation detail (it's not needed for polymorphic > dispatch to work) and class hierarchy tend to be very flat, when they > even exist. > > Mainly, Python's object system is actually quite close to javascript > here. That is, you get more or less the same flexibility. And a couple > of powerful features you don't have with javascript (like hooks in the > attribute lookup mechanism), too. Thanks for precise opinion and spending your time. I think that when you use statically typed language, than you have to define classes, because compiler has to know what is allowed to do with instances of that class. But when you use dynamically typed language, then classes are redundant, because object is looked at when it is referenced. Dynamically typed language needs only objects hierarchy and you can add properties (methods, values) to that object during program execution. In dynamically typed language when you create object A that is inherited from another object B, than object A knows that B is his predecessor. So when you reference A.prop, then prop is looked in A first, then in B, then in predecessors of B, and so on. Having object A you can access its predecessor B. When you have access to object B, then you can add properties to it and these properties could be accessed by all other objects inherited from B. You can do all these things in Python. But why it uses classes? So you can say: "CLASS BASED PROGRAMMING" == "STATICALY TYPED LANGUAGE" From mensanator at aol.com Tue Mar 18 20:39:15 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Mar 2008 17:39:15 -0700 (PDT) Subject: First Program Bug (Newbie) References: Message-ID: <518f4420-19e1-4708-8b65-e44ca23da586@t54g2000hsg.googlegroups.com> On Mar 18, 6:39?pm, oog1e <""benjamin.serrato\"@G(oog1e)MAIL.com"> wrote: > Hey, big thanks to you and Gabriel for replying. I couldn't quite follow > what you did yet. What is this 'gimpy' thing gmpy. It's the GMP (Gnu Multi-Precision) C-library in a Python wrapper. It supports arbitrary precision integers, floats and rationals. Although Python has built in Big Integers, the gmpy versions can sometimes run rings around Python's. Also, lots of functions unavailable elswhere. > and where can I read about it? http://code.google.com/p/gmpy > In response: > > First: Heh, I'm a little embarrassed I didn't notice this. I thought 'I > only need to check up to half' but it didn't occur that base**2 was more > than 1/2 candidate. > > Second: I don't quite follow this. Actually, I'm not following it anymore either. For a while my test program was claiming 27 was prime. All these false primes had 0 as the remainder of candidate/2. I put this in to reject them, but I don't see the problem anymore. > > Third: Yeah, I found that bug just before, and because of, posting. > > Fourth: I used the incrementing command and incremented candidates by > two to check only odds and now the program is a lot faster. > > Thanks a lot for yall's replies. Three more things before I go. What is > the square root function in python? There's one in the math module. Use the one in gmpy if you have it. > I couldn't find the fact.py demo > script. I didn't mean return I meant 'continue'. > > > > Mensanator wrote: > > On Mar 17, 7:03 pm, Benjamin Serrato > > wrote: > >> I Found It!! The following was a post asking for help finding a bug. I > >> thought I needed help with my syntax, but just before sending I found > >> the bug on line 13. Line 13 should read: "base = 2". I would still > >> appreciate any comments on my program. Maybe there is a better way to do > >> it that I didn't think about. I know it's not that interesting but it's > >> my first one. > > >> [post] > >> I'm almost halfway through an online tutorial I found on the python.org > >> site and decided to stop and write a program for myself. I got it in my > >> head to write a program to print all the primes; the idea came from > >> another tutorial. The program prints some non-prime numbers. In a > >> comparison to lists of primes the program prints eight non-primes for > >> numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. > >> Here is the program. > > >> base = 2 > >> candidate = 3 > > >> while True: > >> ? ? ? ? while candidate % base != 0: > >> ? ? ? ? ? ? ? ? base = base + 1 > >> ? ? ? ? ? ? ? ? if base > (candidate / 2): > >> ? ? ? ? ? ? ? ? ? ? ? ? print candidate > >> ? ? ? ? ? ? ? ? ? ? ? ? candidate = candidate + 1 > >> ? ? ? ? ? ? ? ? ? ? ? ? base = 2 > >> ? ? ? ? else: > >> ? ? ? ? ? ? ? ? candidate = candidate + 1 > > >> The following is a rundown of the program. > > >> candidate: A possible prime number. > >> base: Start point for divisibility testing. > >> outer while loop: Causes the program to loop. > >> inner while loop: Obviously, checks if 'candidate' mod 'base' equals > >> zero. If not base is incremented by one then 'if loop'. > >> if loop: After base has been incremented this checks whether all the > >> possible divisors have been used up. If they have then 'candidate' must > >> be prime. So, candidate is printed, a new candidate is chosen and the > >> base is reset. > >> else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is > >> not prime and a new candidate is chosen. > > >> I realize yall probably didn't need all that. > > >> At first I tried to use 'return' on the 'else' block to cause the > >> program to loop, but I don't understand 'return' yet and that didn't > >> work. So, I put the rest into another while loop and was really happy to > >> find it worked but the program prints some non-prime numbers. > > >> Thanks, Benjamin Serrato > > >> P.S. What is the chance I'll get spam for using my real email address? I > >> currently don't get any so... > >> [/post] > > > Several items. > > > First, you don't need to check base larger than sqrt(candidate). > > > Second, see comments following dc. > > > Third, you need to add base = 2 to end of program, otherwise next > > candidate starts base where previous candidate left off. > > > Fourth, use +=1 to increment. > > > Finally, throw this away and use gmpy. :-) > > > import gmpy ?# for Quality Assurance > > base = 2 > > candidate = 3 > > p = 0 ? ? ? ? ? ? ? ? ? ? ? ? ? ?# prime count > > while p<100: ? ? ? ? ? ? ? ? ? ? # limit the loop to 100 primes > > ? while candidate % base != 0: > > ? ? base += 1 > > ? ? #if base > (candidate / 2): > > ? ? if base > (gmpy.sqrt(candidate)): ?# only need to test to > > sqrt(candidate) > > ? ? ? dc = divmod(candidate,2) ? ? ? ? # remainder==0 gives false > > primes > > ? ? ? if dc[1]==1: > > ? ? ? ? # > > ? ? ? ? # the gmpy functions are for QA, verifies that what you call a > > prime > > ? ? ? ? # really is one and the next_prime makes sure you don't skip > > any > > ? ? ? ? # these can be removed once working > > ? ? ? ? # > > ? ? ? ? print > > candidate,gmpy.is_prime(candidate)>0,gmpy.next_prime(candidate) > > ? ? ? ? p += 1 > > ? ? ? ? candidate += 1 > > ? ? ? ? base = 2 > > ? ? ? else: > > ? ? ? ? candidate += 1 ? ? ? ? ? ? ? ? # false prime, reset > > ? ? ? ? base = 2 > > ? else: > > ? ? candidate += 1 > > ? ? base = 2 ? ? ? ? ? ? ? ? ? ? ? ? ? # failure to reset causes false > > primes > > > ## ?3 True 5 > > ## ?5 True 7 > > ## ?7 True 11 > > ## ?11 True 13 > > ## ?13 True 17 > > ## ?17 True 19 > > ## ?19 True 23 > > ## ?23 True 29 > > ## ?29 True 31 > > ## ?31 True 37 > > ## ?37 True 41 > > ## ?41 True 43 > > ## ?43 True 47 > > ## ?47 True 53 > > ## ?53 True 59 > > ## ?59 True 61 > > ## ?61 True 67 > > ## ?67 True 71 > > ## ?71 True 73 > > ## ?73 True 79 > > ## ?79 True 83 > > ## ?83 True 89 > > ## ?89 True 97 > > ## ?97 True 101 > > ## ?101 True 103 > > ## ?103 True 107 > > ## ?107 True 109 > > ## ?109 True 113 > > ## ?113 True 127 > > ## ?127 True 131 > > ## ?131 True 137 > > ## ?137 True 139 > > ## ?139 True 149 > > ## ?149 True 151 > > ## ?151 True 157 > > ## ?157 True 163 > > ## ?163 True 167 > > ## ?167 True 173 > > ## ?173 True 179 > > ## ?179 True 181 > > ## ?181 True 191 > > ## ?191 True 193 > > ## ?193 True 197 > > ## ?197 True 199 > > ## ?199 True 211 > > ## ?211 True 223 > > ## ?223 True 227 > > ## ?227 True 229 > > ## ?229 True 233 > > ## ?233 True 239 > > ## ?239 True 241 > > ## ?241 True 251 > > ## ?251 True 257 > > ## ?257 True 263 > > ## ?263 True 269 > > ## ?269 True 271 > > ## ?271 True 277 > > ## ?277 True 281 > > ## ?281 True 283 > > ## ?283 True 293 > > ## ?293 True 307 > > ## ?307 True 311 > > ## ?311 True 313 > > ## ?313 True 317 > > ## ?317 True 331 > > ## ?331 True 337 > > ## ?337 True 347 > > ## ?347 True 349 > > ## ?349 True 353 > > ## ?353 True 359 > > ## ?359 True 367 > > ## ?367 True 373 > > ## ?373 True 379 > > ## ?379 True 383 > > ## ?383 True 389 > > ## ?389 True 397 > > ## ?397 True 401 > > ## ?401 True 409 > > ## ?409 True 419 > > ## ?419 True 421 > > ## ?421 True 431 > > ## ?431 True 433 > > ## ?433 True 439 > > ## ?439 True 443 > > ## ?443 True 449 > > ## ?449 True 457 > > ## ?457 True 461 > > ## ?461 True 463 > > ## ?463 True 467 > > ## ?467 True 479 > > ## ?479 True 487 > > ## ?487 True 491 > > ## ?491 True 499 > > ## ?499 True 503 > > ## ?503 True 509 > > ## ?509 True 521 > > ## ?521 True 523 > > ## ?523 True 541 > > ## ?541 True 547 > > ## ?547 True 557 From sturlamolden at yahoo.no Sun Mar 16 13:10:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:10:58 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> Message-ID: <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> On 16 Mar, 16:58, bearophileH... at lycos.com wrote: > I think lot of Win users (computational biologists?), even people that > know how to write good Python code, don't even know how to install a C > compiler. If you don't know how to install a C compiler like Microsoft Visual Studio, you should not be programming computers anyway. > I meant a compiler that spits out the final executable a person can > click on. You don't click on compiled Python C extensions. You call it from your Python code. > >Being written in pure Python, Pyrex is equally easy to use on Windows and Linux.< > > Or maybe equally difficult :-) The computational biology students I > was with think PythonWin is "easy" enough (or take a look at the > "Processing" Java-like language user interface). Lowering entry > difficulties is positive. Can things be made simpler for newbies? Being a computational biologist myself (PhD), I do not agree. Any student smart enough to program Python can learn to use disttools or even a command prompt (whether it's bash or DOS does not matter). There is no way of avoiding the keyboard when your are programming computers, except for some strange drag-and-drop languages like LabView. The way I see it, using a C compiler should be a part of the general education for any student in computational sciences. Java is not less complicated. It requires compilation step as well (javac and possibly gnumake). Students are either forced to learn an IDE (Eclispe og NetBeans), or deal with the command prompt. From hgk at ieee.org Wed Mar 19 04:26:32 2008 From: hgk at ieee.org (=?ISO-8859-1?Q?Hans_Georg_Krauth=E4user?=) Date: Wed, 19 Mar 2008 01:26:32 -0700 (PDT) Subject: Get actual call signature? References: Message-ID: <39c5b285-6334-4944-8506-63f315cf4fe5@q78g2000hsh.googlegroups.com> On 18 Mrz., 11:40, Jarek Zgoda wrote: > Say, I have a function defined as: > > def fun(arg_one, arg_two='x', arg_three=None): > pass > > Is there any way to get actual arguments that will be effectively used > when I call this function in various ways, like: > > fun(5) => [5, 'x', None] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > fun(5, 'something') => [5, 'something', None] > > (et caetera, using all possible mixes of positional, keyword and default > arguments) > > I'd like to wrap function definition with a decorator that intercepts > not only passed arguments, but also defaults that will be actually used > in execution. > > If this sounds not feasible (or is simply impossible), I'll happily > throw this idea and look for another one. ;) > > -- > Jarek Zgoda > Skype: jzgoda | GTalk: zg... at jabber.aster.pl | voice: +48228430101 > > "We read Knuth so you don't have to." (Tim Peters) Perhaps like so: import inspect class CLS(object): def fun(self, arg_one, arg_two='x', arg_three=None): print get_signature(self) def get_signature(obj): frame = inspect.currentframe() outerframes = inspect.getouterframes(frame) caller = outerframes[1][0] try: args, varargs, varkw, loc = inspect.getargvalues(caller) allargs = args allargs.pop(0) # self if not varargs is None: allargs += varargs if not varkw is None: allargs += varkw sdict={} for arg in allargs: sdict[arg]=caller.f_locals[arg] ccframe = outerframes[2][0] ccmodule = inspect.getmodule(ccframe) try: slines, start = inspect.getsourcelines(ccmodule) except: clen = 100 else: clen = len(slines) finfo = inspect.getframeinfo(ccframe, clen) theindex = finfo[4] lines = finfo[3] theline = lines[theindex] cmd = theline for i in range(theindex-1, 0, -1): line = lines[i] try: compile (cmd.lstrip(), '', 'exec') except SyntaxError: cmd = line + cmd else: break finally: del frame del outerframes del caller del ccframe return cmd, sdict if __name__ == '__main__': c=CLS() c.fun(5) c.fun(5, arg_three=['a', 'b']) c.fun(5, 'something') c.fun(5, 'something') a=c.fun a(4) Best Regards Hans Georg From girish.cfc at gmail.com Mon Mar 17 02:15:46 2008 From: girish.cfc at gmail.com (Girish) Date: Sun, 16 Mar 2008 23:15:46 -0700 (PDT) Subject: String To List Message-ID: I have a string a = "['xyz', 'abc']".. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... From emailamit at gmail.com Mon Mar 31 16:42:36 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 13:42:36 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> <304acc0a-3944-44a4-8626-30c2ab9da506@z38g2000hsc.googlegroups.com> Message-ID: <08805546-531f-4b5e-83fc-8b30b0e45db6@s37g2000prg.googlegroups.com> On Mar 31, 11:00 am, xkenneth wrote: > Yeah, this is what I'm talking about: > > > def __eq__(self, other) : > > try : > > return <> > > except AttributeError: > > return False > > That seems a bit nasty to me. One thing about python (IMO); you can't just say this doesn't look good. You need to say: why do you think this is not good. To me, it appears a concise and local solution to your problem. From attn.steven.kuo at gmail.com Thu Mar 13 22:22:12 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 13 Mar 2008 19:22:12 -0700 (PDT) Subject: How do I iterate over items in a dict grouped by N number of elements? References: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> Message-ID: <55183d53-e100-4803-8df8-93cb4c06a7f8@s8g2000prg.googlegroups.com> On Mar 13, 6:34 pm, Noah wrote: > What is the fastest way to select N items at a time from a dictionary? > I'm iterating over a dictionary of many thousands of items. > I want to operate on only 100 items at a time. > I want to avoid copying items using any sort of slicing. > Does itertools copy items? > > This works, but is ugly: > > >>> from itertools import * > >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} > >>> N = 3 > >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N): > > ... print G > ... > (('a', 1), ('c', 3), ('b', 2)) > (('e', 5), ('d', 4), ('g', 7)) > (('f', 6), ('i', 9), ('h', 8)) > (('j', 10), None, None) > > I'd prefer the last sequence not return None > elements and instead just return (('j',10)), but this isn't a huge > deal. > > This works and is clear, but it makes copies of items: > > >>> ii = D.items() > >>> for i in range (0, len(ii), N): > > ... print ii[i:i+N] > ... > [('a', 1), ('c', 3), ('b', 2)] > [('e', 5), ('d', 4), ('g', 7)] > [('f', 6), ('i', 9), ('h', 8)] > [('j', 10)] > groupby? import itertools D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} N = 3 it = itertools.groupby(enumerate(D.items()), lambda t: int(t[0]/N)) for each in it: print tuple(t[1] for t in each[1]) -- Hope this helps, Steven From arnodel at googlemail.com Fri Mar 14 19:24:34 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 14 Mar 2008 16:24:34 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> Message-ID: On Mar 14, 10:37?pm, Alex wrote: > On Mar 13, 6:21 pm, Carl Banks wrote: > > > On Mar 13, 7:02 am, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > Alex a ?crit : > > > (sni) > > > > > First of all thanks all for answering! > > > > > I have some environment check and setup in the beginning of the code. > > > > I would like to move it to the end of the script. > > > > Why ? (if I may ask...) > > Sure, because of a readability (similar to function declarations in > C). > > > > > > > But I want it to > > > > execute first, so the script will exit if the environment is not > > > > configured properly. > > > > If you want some code to execute first when the script/module is loaded, > > > then keep this code where it belongs : at the beginning of the script. > > > I concur with Bruno's recommendation: stuff you want to do first > > should come first in the script. ?Things like BEGIN blocks hurt > > readability because you can't identify where execution begins without > > reading the whole file. > > > Having said that, one thing that often happens in Python scripts is > > that all the functions are defined first, then the script logic > > follows. ?So you could put the meat of your script in a function, then > > the "BEGIN" stuff after that functions: > > > def run_script(): > > ? ? # > > ? ? # script contained in this long function > > ? ? # > > > # Then test preconditions here... > > if os.environ["HELLO"] != "WORLD": > > ? ? sys.exit(2) > > > # Then call the run_script functions > > run_script() > > > But having said THAT, I don't recommend you do that with > > preconditions. ?If the script has a quick early exit scenario, you > > really ought to put that near the top, before the function > > definitions, to clearly show to a human reader what is necessary to > > run the script. > > > Carl Banks > > Hi, > > Maybe i was a little bit unclear... I meant that i wanted to do > something like this: > > #!usr/bin/env python > > check_env() > > from subprocess import * > > class MyClass: > ? ?# Class definition > > def check_env(): > ? ?# Code > > if __name__ == "__main__": > ? ?# Script logic > > The thing is, as i saw, that Python doesn't recognize the > "check_env()" function before it reaches the "def" statement. > > I need the check to be done before the subprocess import, because our > customers use different Python versions, some of them do not have > subprocess module. So i want to exit if i see that Python version > being used doesn't have that module. > > The solution to that problem with what you suggested could be wrapping > the subprocess import with function, am i correct? why not: try: from subprocess import * except ImportError: sys.exit('No subprocess module :(') # Rest of module -- Arnaud From jackie.python at gmail.com Mon Mar 31 12:50:29 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Mon, 31 Mar 2008 12:50:29 -0400 Subject: Automatically fill in forms on line Message-ID: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> Dear all, I want to automatically complete the following task: 1. Go to http://www.ffiec.gov/Geocode/default.aspx; 2. Fill in an address in the form "Street Address:" . e.g. "1316 State Highway 102"; 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; 4. Click the bottom "search"; 5. In the opened page, extract and save the number after "Tract Code". In the example, it will be "9659". 6. Repeat Step 1 with a new address. Can Python realize these steps? Can these steps be done witout openning and IE windows? Especially, I dont know how to write code for step 2, 4 and 5. Thank you! From http Fri Mar 21 17:57:58 2008 From: http (Paul Rubin) Date: 21 Mar 2008 14:57:58 -0700 Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Message-ID: <7x63vfn3ix.fsf@ruckus.brouhaha.com> From at home writes: > if 'one' and 'two' in f: > alist.append(f) Use: if 'one' in f and 'two' in f: ... From yhidalgo86 at gmail.com Tue Mar 4 14:20:14 2008 From: yhidalgo86 at gmail.com (Yusniel) Date: Tue, 4 Mar 2008 11:20:14 -0800 (PST) Subject: Python an Exchange Server Message-ID: Hi friends. Someone know how to work with python and exchange server?. From michael.wieher at gmail.com Thu Mar 6 10:54:44 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 6 Mar 2008 09:54:44 -0600 Subject: Py-Extension Irregularity Message-ID: Observe. Python Code Snippet: ==================== ... 66 while i < (self.nPCodes): 67 # print "%s:%s" % (self.nPCodes,i) 68 (c,l,sn,f,fn,sz) = tabmodule.getQuestion(i,self.mx3Path) 69 if _debug and sz>0: 70 _newPtrLoc = tabmodule.getMx3Ptr() 71 _diff = _newPtrLoc-_oldPtrLoc 72 _oldPtrLoc = _newPtrLoc 73 if _diff>16: 74 print _diff .... C++ Code Snippet: --------------------------- 189 static PyObject* 190 tabmodule_getMx3Ptr(PyObject * self, PyObject * args) { 191 int a; 192 a=mx3File.tellg(); 193 return Py_BuildValue("i",a); 194 } ... 189 PyObject * 190 tabmodule_getQuestion(PyObject * self, PyObject * args) { .... 208 mx3File.read((char*)&m_mdx,16); .... 237 //if(m_mdx.size==0) 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); 239 //return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); } Output== michael at majw-m65:~/MRI/tabModule$ ./tabModule.py michael at majw-m65:~/MRI/tabModule$ None. (ie: the _diff is always 16 or less, which is what is SHOULD be, in fact, it is always 16.) Observe!!!! 237 if(m_mdx.size==0) 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); 239 return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); By uncommenting line 237 and 239, we see: ... 64 80 32 32 32 48 128 160 32 32 64 .... Most of the numbers are still 16, but _diff is often larger than 16, by some multiple. How in Buddah's name is returning a Py_BuildValue() affecting a file pointer that isn't being used at all in the function???? -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Wed Mar 5 18:31:45 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 23:31:45 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <13subb12stga62c@corp.supernews.com> On 2008-03-05, castironpi at gmail.com wrote: > Are you vegetarian? Some days. > A little off topic. Ya think? > Anyway, if (a,b) is a key in dictionary d, can it guarantee > that (b,a) is also in it, and maps to the same object? Do you not know how to run the Python interpreter? >>> d = {(1,2): "onetwo"} >>> (1,2) in d True >>> (2,1) in d False Tuples are ordered, so why would you expect that the tuple (a,b) be considered equal to the tuple (b,a)? There is, of course, the degenerate case where a and b are the same so that the tuple (a,b) does equal (b,a): >>> t = (1,2,3) >>> a = t >>> b = t >>> d = {(a,b): "hi there"} >>> (b,a) in d True An unoderded collection of objects in Python is called a set, but sets are mutable so they're not hashable: >>> s1 = set((1,2)) >>> s2 = set((2,1)) >>> s1 == s2 True >>> d = {s1: "hi there"} Traceback (most recent call last): File "", line 1, in ? TypeError: set objects are unhashable To solve that problem, Python provides the immutable "frozenset" type: >>> s1 = frozenset((1,2)) >>> s2 = frozenset((2,1)) >>> s1 == s2 True >>> d = {s1: "hi there"} >>> s1 in d True >>> s2 in d True See how much better a result you get when you ask an understandble, specific, concrete question? -- Grant Edwards grante Yow! Do I hear th' at SPINNING of various visi.com WHIRRING, ROUND, and WARM WHIRLOMATICS?! From hdante at gmail.com Sat Mar 15 19:48:52 2008 From: hdante at gmail.com (hdante) Date: Sat, 15 Mar 2008 16:48:52 -0700 (PDT) Subject: Big file References: <13th14pe0hhsie1@corp.supernews.com> <9LKdnQpmfOvhFUXanZ2dnUVZ_gKdnZ2d@comcast.com> Message-ID: <8ac593da-0051-410e-8784-d97e2da37200@d45g2000hsc.googlegroups.com> On Mar 12, 10:50 pm, "Andrew Rekdal" wrote: > Well, I can see how this could get real messy but within defining a GUI > there are many elements and so the block of elements such as a wx.notebook > for instance I would hope I could place all the code for this in another > file and somehow include it into place. This way I can work on layered > panels and such in a fresh document rather than travesing through tons of > widgets and sizers. > > Thanks for your replies > > -- > -- Andrew > > "Steven D'Aprano" wrote in message > > news:13th14pe0hhsie1 at corp.supernews.com... > > > On Wed, 12 Mar 2008 19:42:44 -0500, Andrew Rekdal wrote: > > >> I am working in the class constructor defining elements of an > >> application. The problem is the file is getting unmanageble and I am > >> wanting to extend the contructor __init__ to another file. > > >> Is it possible to import directly into the contructor the contents of > >> another module file? > > >> If so how would this be done? > > > Here's the way you do what you literally asked for: > > > class MyClass(object): > > def __init__(self, *args): > > # Warning: completely untested > > execfile('myfile.py') # may need extra arguments? > > > but you almost certainly don't want to do that. A better way is by > > importing modules, the same as you would for anything else: > > > class MyClass(object): > > def __init__(self, *args): > > from AnotherModule import constructor > > constructor(self, *args) > > > But frankly if you find yourself needing to do this because your file is > > "too big" and is unmanageable, I think you are in desperate need of > > refactoring your code to make if more manageable. Pushing vast amounts of > > random code out into other files just increases the complexity: not only > > do you have vast amounts of code, but you have large numbers of files to > > manage as well. > > > -- > > Steven You should define your objects in a recursive way. The main window object only deals with their immediate children. Each childen should have a class that deals with their immediate children. This way, each constructor should have a dozen or so children and each of them should easily fit in a single file. Or you should be using a GUI editor. From bearophileHUGS at lycos.com Sat Mar 8 06:59:47 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 8 Mar 2008 03:59:47 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> <8357c29f-8a28-40d7-8ac7-f8c6737ce202@o77g2000hsf.googlegroups.com> Message-ID: <829107aa-a8fe-4f05-b02a-4360d4042a0e@34g2000hsz.googlegroups.com> George Sakkis: > I had posted some time ago an OO wrapper of itertools; slice notation > for islice was one motivation:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272 I think I did see that, but later I forgot of it. It looks nice. Thank you, bearophile From michael.wieher at gmail.com Sun Mar 23 21:05:12 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 23 Mar 2008 20:05:12 -0500 Subject: Does python hate cathy? In-Reply-To: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> References: <20bafe1a-83c0-4bfd-9fec-0fe712b1d66a@u10g2000prn.googlegroups.com> Message-ID: > > > is that farnarkeling about in a __del__ method is *not* a good idea. Ok that having been said, is accessing an unbound variable of a class and using it to coordinate between instances of that class common practice? -------------- next part -------------- An HTML attachment was scrubbed... URL: From frederic.degraeve at gmail.com Wed Mar 26 06:55:15 2008 From: frederic.degraeve at gmail.com (=?ISO-8859-1?Q?Fr=E9d=E9ric_Degraeve?=) Date: Wed, 26 Mar 2008 03:55:15 -0700 (PDT) Subject: matplotlib / legend of x-axis Message-ID: <780b94a4-94c0-4f7c-aa32-7cde8b5d50f7@i12g2000prf.googlegroups.com> Hi everybody, I've got a problem concerning matplotlib/pylab. I use it to represent curves. I will use these pictures in a report. However, it writes me a string 'date' on the bottom of my x-axis. I use this to produce my date axis (x-axis): mondays = WeekdayLocator(MONDAY) # every monday months = MonthLocator(range(1,13), bymonthday=1) # every month monthsFmt = DateFormatter("%b %d '%y") years = YearLocator() # every month yearsFmt = DateFormatter("%y") # subplot.xaxis.set_major_locator(months) # subplot.xaxis.set_major_formatter(monthsFmt) # subplot.xaxis.set_minor_locator(mondays) subplot.xaxis.set_major_locator(years) subplot.xaxis.set_major_formatter(yearsFmt) #subplot.autoscale_view() setp(subplot.get_xticklabels(), 'rotation', 45, fontsize=10) Can you help me to remove this 'date'? thank you! Fr?d?ric From jzgoda at o2.usun.pl Tue Mar 25 16:11:05 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 25 Mar 2008 21:11:05 +0100 Subject: PyGTK localisation on Win32 In-Reply-To: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> References: <8f44765f-f995-4875-b01e-1974fab6f936@d4g2000prg.googlegroups.com> Message-ID: jwesonga pisze: > I've built an app on linux which we have managed to localise into at > least three languages, the app runs well using this command LANG=fr_FR > python app.py which would translate the app into french. We've tried > the replicate the same principle on windows but so far nothing works, > the app will need to be translated into other languages that have no > locale, in windows is there a way to have Glade load values from a > textfile instead of trying to use the .mo files? I had no problem with using standard gettext way of doing i18n on Windows with PyGTK an Glade, apart some quirks with LANG environment variable. Basically, the code that works looks like this: import gettext, locale locale.setlocale(locale.LC_ALL, '') if os.name == 'nt': # windows hack for locale setting lang = os.getenv('LANG') if lang is None: defaultLang, defaultEnc = locale.getdefaultlocale() if defaultLang: lang = defaultLang if lang: os.environ['LANG'] = lang gtk.glade.bindtextdomain(appname, translation_dir) gtk.glade.textdomain(appname) gettext.install(appname, translation_dir, unicode=True) Be aware, that you can not change the locale setting from the command line like you do on Linux. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From mail2spj at yahoo.com Mon Mar 24 17:00:04 2008 From: mail2spj at yahoo.com (SPJ) Date: Mon, 24 Mar 2008 14:00:04 -0700 (PDT) Subject: Reading new mail from outlook Message-ID: <315315.36624.qm@web50108.mail.re2.yahoo.com> An HTML attachment was scrubbed... URL: From sla1nte2001 at yahoo.com Sun Mar 9 22:59:37 2008 From: sla1nte2001 at yahoo.com (John Boy) Date: Sun, 9 Mar 2008 19:59:37 -0700 (PDT) Subject: Import - interpreter works but .py import does not Message-ID: <055c615e-3beb-4037-ab1e-02afeb38da40@e6g2000prf.googlegroups.com> First post and very much a newbie to Python. Have 2.5 on Linux (GG). I think I have set up PYTHONPATH correctly in that I can import a module apply_bp and it complains about line 20 in apply_bp which is: import sys, aipy, numpy, os At the interpreter prompt, however, I can import sys, numpy etc. and can do dir() and see the entry points so I think my overall installation is OK. Why does line not work ? Also I would have thought that when I pre- imported sys et al that they would be in the symbol table so that the import line would be a noop. Thanks, Slainte, John From castironpi at gmail.com Fri Mar 28 06:00:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:00:15 -0700 (PDT) Subject: any good g.a.'s? References: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Message-ID: <5bd6f2f8-2321-4201-a979-666d1d014d29@s8g2000prg.googlegroups.com> On Mar 25, 11:03?am, Tim Chase wrote: > > Any good genetic algorithms involving you-split, i-pick? > > I've always heard it as "you divide, I decide"... > > That said, I'm not sure how that applies in a GA world. ?It's > been a while since I've done any coding with GAs, but I don't > recall any facets related to the You Divide, I Decide problem. > It sounds like a simple optimization of "equality", which would > be a normal use of a GA. ?This would apply for both the division > and the decision, depending on which side the GA is (the "you" or > the "I") or two diff. GAs can be on either side of the process. > > -tkc Tim, if you have any interest in the stuff: You Divide I Decide YDID only works where resources are highly divisible: Except if, do livelock or deadlock occur in real time? If I get in line for going to bars, I enter a decreased-expressivity (- outlet) state, open up, close, and come sit down. Now, what do I generally yield? A life's story. I think I 'send' a request for details in the form of a repetition, except it takes into account a lot of computation, spef. my understading. I also think I look for a 'random' generator to call 'send' on, but that could just be prioritized by strength of pole, but here's the important part, -at- - the- -time-. Taking priority graph/queue to be a function of the past, you can classify into spatial pole and cumulative pole; just the sense mechanata 'say where': 'we favor X' progressively over time. Back at the fork in the road, I was favoring a turn, not a path. I can make a dual, and for the sake of discussion, entertain I do. Are you a musician? Is Heaven a noninterest market? Electricity is a uniform current, highly potent (can sterilize+neutralize), highly uniform (verb regulize). I don't like "discovering poles" "once on the road (just to where)"; I think they're a net quality of life decrease; I don't like poles; they make one answer, heavy questions. Computers at least, can't come and answer; hypothetically, analytically, their pulls can't either. (Computers and their pulls, doh.) However, if I create pole by my actions, they're only part to blame (yes, instead of entirely either or not). Except but, how do I get home? I don't get random homes, it's the same one. Neither does my home pull random people (is it a pole to). It's weird: you can bury latent poles, though clearly time isn't the fuse-length. Contingently exclusive (upon?). There's a layer of discouragement for everything and around everyone else's; surprising me at home is repulsive, lightly. Eating is attractive, more and less over time, sometimes crucial (oddly enough); it creates a junction by outweighing discouragement. (My kitchen is extremely unattractive but not repulsive at all, any farther than the newcome stir, which will come with me after that, though the process of dissipation is a little mysterious-- LaPlace?) There's no good framework for composing (draw analogy to, analogee) the process of emancipation (w.c.) and dissipation, so I lean to church, even though it's chalk-full of non- mathematical (non-vicarous) remarks: "We come, and the vicar leaves. He's just of no interest." Interest might be mutual too, but only in magnitude. I don't like attraction wars. Can I get a tongue regressed (cf. kitchen sink regression)? Are we in Economics? There's money in it. I have to go speak French. Je dois aller. http://www.westga.edu/~jhasbun/osp/Fourier.htm If you receive a sign, do you just design it? What if you have a more clever way to spell a word, qua composite sign? What if you spell it the old way? Consign, design, ensign, and resign. The English tongue is really 'pulling forward' quite fast. Time is generational in facet. (Is a phoneme a particle? Phones are not.) I think time means 'generation', which you can do across space. Ears receive 1-D parametric impressions, Eyes receive 2-D. I don't know of much work in deparametrization, but method iteration ( f_i= f( f_(i-1) ) ), representing space as time, creates generations of something. Problem is, iterations are chosen by somebody, what function to call next in time, so there is a lot of money in choosing functions to call in order, es. if it's refining parameters to other functions. Feedback on computers is lightning-fast, bringing billion- baud guess-and-checking to hands. If you were a tuple, what tuple would you be? Encode, hash, and echo? Do you GOTO home or GOSUB home? What if you limited call stack depth to like five? From gagsl-py2 at yahoo.com.ar Sat Mar 22 15:51:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 22 Mar 2008 16:51:05 -0300 Subject: function-class frustration References: <740f8b7f-7d1a-4f98-96c9-71e58e6a8519@u10g2000prn.googlegroups.com> Message-ID: En Sat, 22 Mar 2008 07:07:18 -0300, John Machin escribi?: > On Mar 22, 7:19 pm, castiro... at gmail.com wrote: > >> On the other hand, are you willing to make changes to the console? >> How big and what? I was thinking of __ to keep the second-to-last >> most recent command. > > Access to and editing of previous input lines is already provided by > the cooked mode of the console (e.g. on Windows, lean on the up-arrow > key) or can be obtained by installing the readline package. Perhaps by > analogy with _, you mean the *result* of the penultimate *expression*. > This functionality would be provided by the Python interactive > interpreter but it's not ... do have a look at IPython (http:// There is no need to change the interpreter, one can use sys.displayhook to achieve that. Create or add the following to your sitecustomize.py module: # sitecustomize.py import sys import __builtin__ as builtin def displayhook(value): if value is not None: sys.stdout.write('%s\n' % value) builtin._ = value if not hasattr(builtin, '__'): __ = builtin.__ = displaylist() else: __ = builtin.__ __.append(value) sys.displayhook = displayhook class displaylist(list): """List of expressions kept by displayhook. It has a maximum size and a custom display, enumerating lines. Lines are trimmed at the middle to fit the maximum width""" maxlen = 20 maxwidth = 80-1-4 def __str__(self): def genlines(self): for i, value in enumerate(self): s = str(value) if len(s) > self.maxwidth: p = (self.maxwidth - 3) // 2 s = s[:p] + '...' + s[-(self.maxwidth - p - 3):] yield '%2d: %s' % (i, s) return '\n'.join(genlines(self)) def append(self, value): # don't keep duplicates # obey the maximum size if value is self: return if value in self: self.remove(value) if len(self) > self.maxlen - 1: del self[:-self.maxlen - 1] list.append(self, value) py> 24*60*60*365 31536000 py> "hello world".split() ['hello', 'world'] py> help Type help() for interactive help, or help(object) for help about object. py> quit Use quit() or Ctrl-Z plus Return to exit py> __ 0: 31536000 1: ['hello', 'world'] 2: Type help() for interactiv...ct) for help about object. 3: Use quit() or Ctrl-Z plus Return to exit py> __[1] ['hello', 'world'] py> __[0] // 3 10512000 py> __ 0: 31536000 1: Type help() for interactiv...ct) for help about object. 2: Use quit() or Ctrl-Z plus Return to exit 3: ['hello', 'world'] 4: 10512000 py> -- Gabriel Genellina From tamim.shahriar at gmail.com Wed Mar 26 13:48:35 2008 From: tamim.shahriar at gmail.com (subeen) Date: Wed, 26 Mar 2008 10:48:35 -0700 (PDT) Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: <16b6150a-d16a-485f-b41c-54a1c18f8e8d@d21g2000prf.googlegroups.com> On Mar 26, 8:12 pm, waltbrad wrote: > Stumbling through Mark Lutz's "Programming Python 3rd", he gives an > example of a program that will automatically configure environment > settings and launch other programs. Then he gives an example of > running this program. On his command line he types: > > C:\...\PP3E>Launcher.py > > and this begins the program. Doesn't work for me. I have to type: > > C:\...\PP3E>python Launcher.py > > Is this a typo on his part or has he configured his settings in such a > way that the command line will automatically associate the extension > with the program? (If so, he didn't mention this in his book). You have to set the path in your run time environment. regards, Subeen. http://love-python.blogspot.com/ From ttsiodras at gmail.com Fri Mar 28 10:50:51 2008 From: ttsiodras at gmail.com (ttsiodras at gmail.com) Date: Fri, 28 Mar 2008 07:50:51 -0700 (PDT) Subject: Global variables in modules... References: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> Message-ID: <6842b4de-f241-425a-aeec-29ba2077ec65@e10g2000prf.googlegroups.com> That clears it up. Thanks. From pavloutefkros at gmail.com Sun Mar 2 09:54:34 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 06:54:34 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> sorry for acting like a fool but this is just to weirdly easy that i can't get to work. i've written a small web server in another language and this is more like copying code. i already have everything figured out, except this one but noone seems either willing or capable of helping me. again sorry but i was in a very bad mood. From tew24 at spam.ac.uk Fri Mar 7 06:27:21 2008 From: tew24 at spam.ac.uk (Tom Wright) Date: Fri, 07 Mar 2008 11:27:21 +0000 Subject: Licence confusion: distributing MSVC?71.DLL References: Message-ID: jim-on-linux wrote: > This is what someone wrote on 1-21-2007 > to this help site about this pain in the a... > MSVCR71 stuff. > > " I believe this problem doesn't exist. > (snip useful bit of EULA and explanation) Thanks for that - just what I didn't manage to turn up with Google. I'll go ahead and publish then :-) -- I'm at CAMbridge, not SPAMbridge From lialie at gmail.com Thu Mar 13 22:02:50 2008 From: lialie at gmail.com (lialie) Date: Fri, 14 Mar 2008 10:02:50 +0800 Subject: Dispatch("Excel.Application") failed Message-ID: <47D9DCCA.3060401@gmail.com> On Behalf Of John Machin > > > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > > > None, None) > > > Googling for 2147221005 gives some clues. > > That string of hex stuff appears where an error message is > expected -- it's not utf8, and makes no sense when I attempt > to decode it with cp1250 to cp1258 inclusive. If you start > IDLE and type: >>The hex stuff is Chinese. It appears to be a standard Windows error message. >>???????? (Which I believe meaans "invalid class string") >>I wrote in another post (that doesn't appear to have made it to the list) >>that the call to Dispatch on Excel will fail if the formula bar edit box is >>active. Just another idea. >>Regards, >>Ryan Ginstrom Thanks. I did try to google the question, but the answer wasn't properly. I am using Windows XP sp2 which language is Chinese simp. At first, I thought the hex string was coding in cp936 or utf8, then failed. second, try to run my script on the other computer, and it run well without any error! At last, I give up.After Windows Excel reinstalled, it work, but still confused.:( The net speed is horribly slow when connect to Pywin32 project at SF. Regards, Lialie From castironpi at gmail.com Tue Mar 18 21:27:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 18:27:02 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> Message-ID: <4e740d0f-9b1d-4b1d-9f6b-8bd56ea11a65@z38g2000hsc.googlegroups.com> > >> >>> b in b > >> False > > > That's actually interesting. > > Just for the avoidance of doubt, I didn't write the 'b in b' line: > castironpi is replying to himself without attribution. > > P.S. I still don't see the relevance of any of castironpi's followup to my > post, but since none it made any sense to me I guess it doesn't matter. Well, it does show thought and it's an interesting anomaly. It's related to the OP too (no less so than the one before it than any other to the one before it): 'Why?' is pretty open-ended. D'Aprano pointed out an ambiguity in the 'in' operator, which sparked an idea that contributes to some other threads. I thought Booth and Bossy, "homogeneous ... add+remove" pretty well summed it up. That's my mistake for showing excitement to one thread that was actually mostly prepared by another. I'm in A.I. if that helps any. I am puzzled by the failure on 'a in a' for a=[a]. >>> a== [a] also fails. Can we assume/surmise/deduce/infer it's intentional? From nodrogbrown at gmail.com Fri Mar 7 10:12:13 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 7 Mar 2008 07:12:13 -0800 (PST) Subject: problem with join Message-ID: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> hi i am using python on WinXP..i have a string 'folder ' that i want to join to a set of imagefile names to create complete qualified names so that i can create objects out of them folder='F:/brown/code/python/fgrp1' filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] filenameslist=[] for x in filenms: myfile=join(folder,x) filenameslist.append(myfile) now when i print the filenameslist i find that it looks like ['F:/brown/code/python/fgrp1\\amber1.jpg', 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] is there some problem with the way i use join? why do i get \\ infront of the basename? i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', can anyone pls help gordon From castironpi at gmail.com Tue Mar 11 17:53:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 14:53:47 -0700 (PDT) Subject: python interactive - threaded console (run -i) References: <56661ddb-f06b-4229-8011-7996cd023600@m34g2000hsc.googlegroups.com> Message-ID: <4eb586c0-ce9a-4d54-a43c-a38d18df041d@s13g2000prd.googlegroups.com> > ? ? ? ? self._doneevents= {} is extraneous. > id, fun, ar, kw= self.get() done, fun, ar, kw= self.get() suffices. > def _draintilclose( conn, understandfun= None ): > ? ? ? ? if None is not understandfun: > ? ? ? ? ? ? understandfun( _curmsg ) yield _curmsg is an interesting synonym: the static interface. Compare signatures: def _draingen( conn ): ... yield _curmsg def _draintilclose( sck, th ): for x in _draingen( sck ): th._print( x ) or in place of th._print, whatever function you passed to understandfun. The general case, pseudocode, consumer: def _draintilclose( conn, visitee ): for x in _draingen( conn ): x.visit( visitee ) class Tool1Visitee: def typeA( self, arg ): tool1.listbox.add( arg ) def typeB( self, arg ): tool1.combobox.add( arg ) class Tool2Visitee: def typeA( self, arg ): tool2.icons.add( arg ) def typeB( self, arg ): tool2.listbox.add( arg ) and: class VisitorX: def visit( self, v ): v.typeA( self._attr ): class VisitorY: def visit( self, v ): v.typeB( self._attr ): Producer: def _draingen( conn ): ... if: _curvisitee= VisitorX( _curmsg ) else: _curvisitee= VisitorY( _curmsg ) yield _curvisitee and: th1Visitee= Tool1Visitee() new_thread( _draintilclose, conn1, th1Visitee ) th2Visitee= Tool2Visitee() new_thread( _draintilclose, conn2, th2Visitee ) Tool1Visitor.typeA still just receives a byte array, but type information comes with. By that point, the 'message knows' that it's in a Tool1Visitor, and that it's a typeA message, and so adds it to tool1.listbox. That puts just the right information in just the right place... if it's the right time. Or pass the visitee directly to _draingen as fit, without the visitor or yields, as a callback collection. def _draingen( conn, visitee ): ... if: visitee.typeA( _curmsg ) else: visitee.typeB( _curmsg ) As a callback collection: tool1_ft= dict( typeA= tool1.listbox.add, typeB= tool1.combobox.add ) tool2_ft= dict( typeA= tool2.icons.add, typeB= too2.listbox.add ) @new_threads( conn1, tool1_ft ) @new_threads( conn2, tool2_ft ) def _( conn, tool_ft ): for tp, msg in _draingen( conn, tool_ft ): tool_ft[ tp ]( msg ) using a generator, or directly without: tool1_ft= dict( typeA= tool1.listbox.add, typeB= tool1.combobox.add ) new_thread( _draintilclose, conn1, tool1_ft ) tool2_ft= dict( typeA= tool2.icons.add, typeB= too2.listbox.add ) new_thread( _draintilclose, conn2, tool2_ft ) From jaywgraves at gmail.com Mon Mar 10 10:24:50 2008 From: jaywgraves at gmail.com (jay graves) Date: Mon, 10 Mar 2008 07:24:50 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <094a9916-66ac-42f6-9146-a16872c7f78d@m36g2000hse.googlegroups.com> On Mar 10, 8:57 am, royG wrote: > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? Try the 'glob' module. ... Jay From gagsl-py2 at yahoo.com.ar Fri Mar 7 09:57:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Mar 2008 12:57:03 -0200 Subject: hidden built-in module References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> Message-ID: En Fri, 07 Mar 2008 12:15:04 -0200, koara escribi?: > On Mar 5, 1:39 pm, gigs wrote: >> koara wrote: >> > Hello, is there a way to access a module that is hidden because >> > another module (of the same name) is found first? >> >> > More specifically, i have my own logging.py module, and inside this >> > module, depending on how initialization goes, i may want to do 'from >> > logging import *' from the built-in logging. >> >> you can add your own logging module in extra directory that have >> __init__.py and >> import it like: from extradirectory.logging import * >> and builtin: from logging import * > > Thank you for your reply gigs. However, the point of this namespace > harakiri is that existing code which uses 'import logging' ... > 'logging.info()'... etc. continues working without any change. > Renaming my logging.py file is not an option -- if it were, i wouldn't > bother naming my module same as a built-in :-) Read a very recent post from Bruno Desthuilliers with subject "Altering imported modules" -- Gabriel Genellina From tmp1 at viltersten.com Sun Mar 2 12:02:08 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 18:02:08 +0100 Subject: SV: Keeping the console window In-Reply-To: <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> References: <62vs0iF24tv6jU1@mid.individual.net> <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> Message-ID: <6303tdF24pjjtU1@mid.individual.net> > You may use python in interactive mode: > > $ python -i yourScript.py > > Or use a blocking readline: > > $ cat yourScript.py > import sys > sys.stdin.readline() Thanks guys! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From jeff at schwabcenter.com Tue Mar 18 16:07:40 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 13:07:40 -0700 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> <8ede2d83-a9f8-4d31-903c-b53271831722@z38g2000hsc.googlegroups.com> <0cb67cb0-0e0f-4969-8faa-46a87981c13c@b64g2000hsa.googlegroups.com> <3552d429-e008-4671-a2b1-0fc05134cd44@s19g2000prg.googlegroups.com> <710989d4-cb2a-47f1-8a76-1f0db1815fa1@c19g2000prf.googlegroups.com> Message-ID: Mike Driscoll wrote: > On Mar 18, 1:41 pm, fumanchu wrote: >> On Mar 17, 6:25 pm, dundeemt wrote: >> >>> I agree - the balance wasn't as good. We can all agree that HowTos >>> and Intros are a necessary part of the conference talks track, but as >>> Robert pointed out some talks should be of a more advanced nature. I >>> enjoy those that stretch my brain. Alex M, Pyke and NetworkIO and >>> Mark Hammond's keynote were among my favorite talks. >> Raymond Hettinger's talk on collections was not only one of my >> favorites, it was apparently lots of other people's too--the room was >> PACKED. I can't recall seeing any other talk that was even close to >> seating capacity. >> >> Robert Brewer >> fuman... at aminus.org > > The "Using PyGame and PySight to Create an Interactive Halloween > Activity (#9)" session with Mr. John Harrison was also quite full as > was the one for Pyglet. I think the nose presentation had people > sitting on the floor. > > Geeks like games! I know I do! Me too. As I have never attended PyCon, the amount of entertainment already gleaned from this thread has wildly exceeded my expectations. :) Are slides or notes from any of the presentations available online? What was the topic of the well-received presentation from Google? From steve at REMOVE-THIS-cybersource.com.au Sun Mar 30 06:35:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 10:35:30 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <0964631d-67e4-4c7f-968e-5bf42c0787c2@d45g2000hsc.googlegroups.com> Message-ID: <13uur7ishec9795@corp.supernews.com> On Sun, 30 Mar 2008 01:13:04 -0700, dewitters wrote: > On Mar 29, 6:34 pm, Lie wrote: >> You're forcing your argument too much, both != and <> are NOT standard >> mathematics operators -- the standard not-equal operator is >< -- and I >> can assure you that both != and <> won't be comprehensible to non- >> programmers. > > What I meant was that both < and > are standard mathematics operators, > and that by that knowledge one could deduce what <> means. But you would be wrong, because "less than or greater than" is not the same as "not equal to". >>> 3+2j != 2-3j True >>> (3+2j < 2-3j) or (3+2j > 2-3j) Traceback (most recent call last): File "", line 1, in TypeError: no ordering relation is defined for complex numbers -- Steven From craigm3604 at gmail.com Thu Mar 20 17:25:43 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 14:25:43 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> Message-ID: <8a84e37c-4f03-41ab-becc-7632b84b0389@s12g2000prg.googlegroups.com> On Mar 20, 4:55 pm, "Chris Mellon" wrote: > On Thu, Mar 20, 2008 at 3:42 PM, Craig wrote: > > > On Mar 20, 2:38 pm, Craig wrote: > > > On Mar 20, 2:29 pm, sturlamolden wrote: > > > > > On 20 Mar, 19:09, Craig wrote: > > > > > The culprit i here: > > > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > > > This binds these names to Python ints, but byref expects C types. > > > > > Also observe that CacheSize and OpenMode should be c_short. > > > > I changed CacheSize and OpenMode to c_short, and commented out that > > > line producing the "Before" message, and the output is the same. > > > > Further "tinkering" revealed that it is the byref on the fName and pw > > > that are causing the error. > > > > The entire problem appears to be around the production of a BSTR and > > > the passing of pointers (byref) to the BSTR. > > > Can anyone shed some light on how to work with BSTR's? > > Since you didn't tell ctypes about the function signature, it assumes > it returns int and gives you a python int. Provide a function > signature (c_void_p should work for BSTR) for both functions and you > should have an easier time of it. > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list Thanks Chris. I changed X to a c_short also, and modified the example as suggested: X = c_short(0) X = windll.vbis5032.VmxOpen(byref(c_void_p(fName)), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(c_void_p(pw))) printf ("After - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) And, this is what printed: After - X = 4325376, CacheSize = 0, OpenMode = 3, vHandle = 17586736 The printf shows that the values of X and vHandle have changed, but I am not sure it is working properly as X should be a MUCH smaller number (< 256). I would have expected a 0 (VIS_OK), 13 (VIS_DOS_ERROR) or 14(VIS_DISK_ERROR) if it had worked. Next, I changed: fName = windll.oleaut32.SysAllocStringByteLen("u:\\msdb\\dcod\x00", 13) so that I knew it would not find the file, and got: After - X = 2555917, CacheSize = 0, OpenMode = 3, vHandle = 0 The vHandle staying 0 tells me that it did not find the file, but the value of X seems random. Based on the original C prototype, what am I doing wrong so that the return from the call to vbis5032 is not "usable"? From deets at nospam.web.de Thu Mar 6 15:19:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 06 Mar 2008 21:19:54 +0100 Subject: Exploring Attributes and Methods In-Reply-To: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: <63b1veF26p2fkU2@mid.uni-berlin.de> keios.titan at gmail.com schrieb: > Hi, > Is there a python command that allows me to extract the names (not > values) of the attributes of a class. > > example > > Class Sample: > fullname = 'Something' > > How can I know that this class has an attribute called 'fullname'? > > I hope my question is clear. The question others have answered already. But I have one for you: you are aware that these kind of variables are *class variables*, NOT *instance variables*, as they are created like this: class Foo(object): def __init__(self): self.fullname = "something" Diez From gherron at islandtraining.com Sun Mar 2 11:37:11 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 02 Mar 2008 08:37:11 -0800 Subject: Question on importing and function defs In-Reply-To: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> Message-ID: <47CAD7B7.8040006@islandtraining.com> TC wrote: > I have a problem. Here's a simplified version of what I'm doing: > > I have functions a() and b() in a module called 'mod'. b() calls a(). > > So now, I have this program: > > from mod import * > > def a(): > blahblah > > b() > > > The problem being, b() is calling the a() that's in mod, not the new > a() that I want to replace it. (Both a()'s have identical function > headers, in case that matters.) How can I fix this? > > Thanks for any help. > Since b calls mod.a, you could replace mod.a with your new a. Like this: (Warning, this could be considered bad style because it will confuse anyone who examines the mod module in an attempt to understand you code.) import mod def replacement_a(): ... mod.a = replacement_a ... Or another option. Define b to take, as a parameter, the "a" function to call. In mod: def a(): ... def b(fn=a): # to set the default a to call ... And you main program: from mod import * def my_a(): ... b(my_a) Hope that helps Gary Herron From castironpi at gmail.com Thu Mar 6 05:29:55 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 02:29:55 -0800 (PST) Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: On Mar 6, 2:37?am, Bryan Olson wrote: > Grant Edwards wrote: > > It may be ?obvious that he has a question. ?It's not the least > > bit obvious what that question is. > > How can we efficiently implement an abstract data type, call it > 'DoubleDict', where the state of a DoubleDict is a binary > relation, that is, a set of pairs (x, y); and the operations on > a DoubleDict are those on a Python set, plus: > > ? ? ?find_by_first(self, x): ?return [y where (x, y) in DoubleDict] > > ? ? ?find_by_second(self, y): ?return [x where (x, y) in DoubleDict] > > Python can implement this ADT directly as specified, but the > find_by_ operations would run in time len(self). ?We want an > implementation where the find_by's run in O(1 + k) where k is > the length of the returned sequence. > > -- > --Bryan It gets hairier if you have an element that isn't a first or second necessarily. find_by_other(self, x): return [y where (x, y) in DoubleDict or (y, x) in DoubleDict] From sjmachin at lexicon.net Tue Mar 25 07:40:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Mar 2008 04:40:18 -0700 (PDT) Subject: My python interpreter became mad ! References: Message-ID: On Mar 25, 10:05 pm, Benjamin Watine wrote: > Yes, my python interpreter seems to became mad ; or may be it's me ! :) > > I'm trying to use re module to match text with regular expression. In a > first time, all works right. But since yesterday, I have a very strange > behaviour : > > $ python2.4 > Python 2.4.4 (#2, Apr 5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > X-Spam-Flag: YES > X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org > X-Spam-Level: ********************** > X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, > MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, > > RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, > > URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, > URIBL_WS_SURBL autolearn=failed version=3.1.7-deb > > Traceback (most recent call last): > File "", line 1, in ? > File "/etc/postfix/re.py", line 19, in ? > m = re.match('(Spam)', mail) > AttributeError: 'module' object has no attribute 'match' > >>> > > What's the hell ?? I'm just importing the re module. No you're not importing *the* re module. You're importing *an* re module, the first one that is found. In this case: your own re.py. Rename it. From grante at visi.com Thu Mar 20 12:00:58 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 16:00:58 -0000 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: <13u52hqlbtdv1d1@corp.supernews.com> On 2008-03-20, Jeff Schwab wrote: >>> http://www.google.com/search?q=emacs+python > >> Gee. Thanks. > > I believe Grant was suggesting that Emacs often serves a similar purpose > on Unix to what Visual Studio does on Windows, which seemed to be what > you were asking. When asking about Mac OS X here, you are likely to get > a lot of generic Unix responses. (Would it have been clearer if he had > just said "emacs?") Don't the normal "run/debug python from inside emacs" methods work on OS-X? -- Grant From nkavitha551 at gmail.com Sat Mar 1 05:33:06 2008 From: nkavitha551 at gmail.com (nkavitha551 at gmail.com) Date: Sat, 1 Mar 2008 02:33:06 -0800 (PST) Subject: Wanna be a pride owner? Message-ID: <9c27ba17-1a54-4cc2-a3ca-16ac4c995253@e10g2000prf.googlegroups.com> Hi, Wanna be a pride owner? Visit the website below and make others look at you with envy!!! ------------------------------------------------------------------------------ http://kavitha551.blogspot.com/ ------------------------------------------------------------------------------- From george.sakkis at gmail.com Fri Mar 7 21:55:29 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 7 Mar 2008 18:55:29 -0800 (PST) Subject: islice ==> [::] References: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> Message-ID: <8357c29f-8a28-40d7-8ac7-f8c6737ce202@o77g2000hsf.googlegroups.com> On Mar 7, 7:49 am, bearophileH... at lycos.com wrote: > I find itertools.islice() useful, so for Python 3.x I may like to see > it removed from the itertools module, and the normal slicing syntax > [::] extended to work with generators/iterators too. > > from itertools import islice > primes = (x for x in xrange(1,999) if all(x % y for y in xrange(2, > x))) > print list(islice(primes, 0, 20)) > ==> > print list(primes[:20]) > > Bye, > bearophile I had posted some time ago an OO wrapper of itertools; slice notation for islice was one motivation: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272 George From sjmachin at lexicon.net Sat Mar 22 19:17:06 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 16:17:06 -0700 (PDT) Subject: Prototype OO References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <64hp4bF2bhmtuU1@mid.uni-berlin.de> <6920f5aa-dd70-4e3e-9dc0-ab9d53a2cab2@d21g2000prf.googlegroups.com> <64kg3pF2avnseU1@mid.uni-berlin.de> Message-ID: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> On Mar 23, 12:32 am, "Diez B. Roggisch" wrote: > John Machin schrieb: > > > On Mar 21, 11:48 pm, "Diez B. Roggisch" wrote: > > >> [1] Just one example:http://docs.mootools.net/Class/Class.js > > > Mootools being something a coworker might use? > > I don't understand the question. > > Diez It presupposes that the reader on first seeing "coworker" has mentally decomposed it as "cow-ork-er". From gabriel.rossetti at mydeskfriend.com Wed Mar 26 05:07:28 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Wed, 26 Mar 2008 10:07:28 +0100 Subject: Strange loop behavior In-Reply-To: References: Message-ID: <47EA1250.9010305@mydeskfriend.com> Arnaud Delobelle wrote: > On Mar 26, 8:35 am, Gabriel Rossetti > wrote: > >> Hello, >> >> I wrote a program that reads data from a file and puts it in a string, >> the problem is that it loops infinitely and that's not wanted, here is >> the code : >> >> d = repr(f.read(DEFAULT_BUFFER_SIZE)) >> while d != "": >> file_str.write(d) >> d = repr(f.read(DEFAULT_BUFFER_SIZE)) >> >> I also tried writing the while's condition like so : len(d) > 0, but >> that doesn't change anything. I tried step-by-step debugging using >> PyDev(eclipse plugin) and I noticed this, once the while was read once, >> it is never re-read, basically, the looping does happen, but just in >> between the two lines in the loop's body/block, it never goes on the >> while and thus never verifies the condition and thus loops forever. I >> had been using psyco (a sort of JIT for python) and so I uninstalled it >> and restarted eclipse and I still get the same thing. This looks like >> some bug, but I may be wrong, does anybody understand what's going on here? >> >> Thanks, >> Gabriel >> >> PS >> And yes I checked, the "d" variable is en empty string at some point, so >> the looping should stop. >> > > No, it isn't the empty string, it is the printable representation of > the empty string (because you wrap your f.read() calls in repr()), > which is the string "''": > > >>> print "''" > '' > > Why do you wrap f.read(...) in the repr() function? If you remove the > two repr() I suspect your code will work. > > OTOH do you know that the read() method of file objects does what you > want? You could simply write: > > file_str = f.read() > > Or are there some other factors that prevent you from doing this? > > -- > Arnaud > > Ok, like I mentioned in my second msg, I had put repr() there because I was getting errors because the ascii range (128) was exceeded, I tried cheating and telling it it was unicode but that didn't work, so I tried repr() and it gave me a string rep. of my data, that was ok. After that I tried using StringIO instead of what I had before, a list of strings that I later joined with an empty string. I just re-tried removing the repr() and it works with the StringIO version. Thanks for all your answers, Gabriel From jasynwiener at gmail.com Sun Mar 16 14:22:54 2008 From: jasynwiener at gmail.com (jasonwiener) Date: Sun, 16 Mar 2008 11:22:54 -0700 (PDT) Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> Message-ID: <8e570583-1a62-49d3-8d00-8bdce8f05df0@s13g2000prd.googlegroups.com> Completely helped! Working as expected now. Thanks. You really got me out of a bind! J. On Mar 16, 10:23 am, "Martin Blume" wrote: > "jasonwiener" schrieb > > > I am having a VERY odd problem with unpacking right now. > > I'm reading data from a binary file and then using a very > > simple struct.unpack to get a long. Works fine on my MacBook, > > but when I push it to a Linux box,it acts differently and > > ends up pewking. > > [...] > > > the data looks to be the same, but the unpacking seems to > > treat it differently. > > Probably little-endian vs. big-endian issue: > > >>> s > '\x1e\xc6\xf3\xb4' > >>> struct.unpack(' (3035874846L,) > >>> struct.unpack('>I', s) > > (516354996L,) > > See help(struct) for further information. > > This seems to imply that the Mac, although running now on Intel > processors, is still big-endian. > > HTH > Martin From iainking at gmail.com Mon Mar 17 05:27:31 2008 From: iainking at gmail.com (Iain King) Date: Mon, 17 Mar 2008 02:27:31 -0700 (PDT) Subject: String To List References: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> Message-ID: <42858a90-80eb-45ac-8f76-ad9d06ee4fbf@d21g2000prf.googlegroups.com> On Mar 17, 6:56 am, Dan Bishop wrote: > On Mar 17, 1:15 am, Girish wrote: > > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > this?? > > Thanks for the help... > > eval(a) will do the job, but you have to be very careful about using > that function. An alternative is > > [s.strip('\'"') for s in a.strip('[]').split(', ')] This will fall over if xyz or abc include any of the characters your stripping/splitting on (e.g if xyz is actually "To be or not to be, that is the question"). Unless you can guarantee they won't, you'll need to write (or rather use) a parser that understands the syntax. Iain From rschroev_nospam_ml at fastmail.fm Mon Mar 10 11:26:32 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 10 Mar 2008 16:26:32 +0100 Subject: Regarding coding style In-Reply-To: <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> Message-ID: rockingred schreef: > On Mar 8, 8:27 pm, Dan Bishop wrote: >> // Copyright (C) 2008 Foobar Computer Consulting >> // >> // VERSION PROJECT# DATE DESCRIPTION >> // ------- -------- -------- ------------------ >> // 1.00 123456 01/04/08 Original creation. >> // >> >> Eleven lines, of which the only useful information to me was the >> project number, as knowing this let me look up who was behind these >> comments. > > Actually, "editorial" comments that tell you who last changed a > program, when and why can be useful. I worked in a company with a > number of programmers on staff. Having comments that told us Joe > worked on a program yesterday that isn't working today could often > solve half the battle. Especially if Joe also added a comment near > the lines he had changed. Likewise including the "Project#" would > help us track all the programs that had to be changed for a specific > project. This allowed us to move all related items into the Live > system once the testing phase had been completed (we just searched for > everything with the same Project# in it). Yes, on rare occasions we > would have an entire page of "Editorial" comments to ignore at the > beginning of our program listing, but it was easy enough to skip that > page. I will grant you that probably after 10 changes the first > change isn't as important anymore (unless you want to backtrack and > find out who started the Project in the first place and what it's > original purpose was). That is certainly useful, but IMO that's what version control systems are for. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From gherron at islandtraining.com Wed Mar 19 17:30:11 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 Mar 2008 14:30:11 -0700 Subject: Is this valid ? In-Reply-To: <47E18332.9030202@gmail.com> References: <47E18332.9030202@gmail.com> Message-ID: <47E185E3.3080902@islandtraining.com> Stef Mientki wrote: > hello, > > by accident I typed a double value test, > and to my surprise it seems to work. > Is this valid ? > > a = 2 > b = 2 > > a == b == 2 > > thanks, > Stef Mientki > > Yes. It's been in Python since the earliest days. You usually see it in test like this: if a < b < c: but any comparison operators work. The meaning is the same as the AND of each individual test. Gary Herron From dieter at handshake.de Fri Mar 14 15:23:23 2008 From: dieter at handshake.de (Dieter Maurer) Date: 14 Mar 2008 20:23:23 +0100 Subject: ZSI and attachments In-Reply-To: References: Message-ID: Laszlo Nagy writes on Tue, 11 Mar 2008 15:59:36 +0100: > I wonder if the newest ZSI has support for attachments? Last time I > checked (about a year ago) this feature was missing. I desperately > need it. Alternatively, is there any other SOAP lib for python that > can handle attachments? The ZSI 2.0 documentation says: "...It can also be used to build applications using SOAP Messages with Attachments...." I never did it and do not know how ZSI supports this. You probably will get a more informed answer on mailto:pywebsvcs-talk at lists.sourceforge.net, the ZSI mailing list. Dieter From castironpi at gmail.com Sat Mar 22 06:50:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 03:50:09 -0700 (PDT) Subject: Can I run a python program from within emacs? References: <3413d022-b9c6-4503-8d5a-d01ffead3c99@m36g2000hse.googlegroups.com> Message-ID: <106813ce-4ae7-4b3e-8a73-a78967e59844@e60g2000hsh.googlegroups.com> On Mar 22, 3:47?am, David Reitter wrote: > On Mar 20, 3:09 pm, jmDesktop wrote: > > > Hi, I'm trying to learn Python. ?I using Aquamac an emac > > implementation with mac os x. ?I have a program. ?If I go to the > > command prompt and type pythong myprog.py, it works. ?Can the program > > be run from within the editor or is that not how development is done? > > I ask because I was using Visual Studio with C# and, if you're > > familiar, you just hit run and it works. ?On Python do I use the > > editor for editing only and then run the program from the command > > line? ?Thank you. > > Aquamacs, just like any variant of GNU Emacs, will show a Python > menu. ?There's a "Start Interpreter" function, and one to evaluate the > buffer (C-c C-c). ?It's pretty straightforward (a euphemism for > obvious). Aside: Straightforward may not be completely objective, i.e. have a metric/ unique metric. If perception & cognition are points on and paths through a multi-dimensional space (densities in which limited by sense mechanism), straightforward under its most literal interpretation, means, 'in a straight line in the direction you're facing'. Straight could mean an elementary, transcendantal, or composite function (say, a sum of three sine waves). But forward leaves less to imagine. If two ships cross, and one captain says, 'Bermuda? Sure. It's straight forward,' to the other, he travels for a day and doesn't get there, and he's angry, does he feel and/or believe that the first captain provoked him, did he, and does he know it. Straightforward doesn't necessarily evaluate to a concrete move sequence in chess ('The pin is straightforward'); forward is ambiguous (my forward, your forward, the formal forward), and straight is too. In a depth-first search (unspecified), straight means move the same piece repeatedly. In breadth-first, straight means you know exactly my node weights. Forward means I know which direction you're facing, or I'm following you. Both are resent-worthy assumptions: If you lose me or I lose you, it's still your fault. I take that back: either party can slack on following protocol; both are following one. There's a ball, who dropped it (and who's on it!). "Obvious", come to think of it, is pretty subjective too. The objects and their respective distances away in one's perceptive(/cognitive) environment vary from person to person, time to time ("by person by time"). If you're telling me something is obvious, one of us made an out-of-band inference. I'm not sure what to think of the prevalence of human miscommunications. Upon discovering one, either cut and go, or go back for it; it's a sunken cost. (Is it a, 'I forgot to bring something' on an embarked voyage (road trip), in the metaphor of ship travel?) Do those both generate fights? There's social profit in commerce-- but people are making some damn foolish partnerships. (Even exclusivity can be profitable, but for some reason, 'exclusivity agreement' isn't in Wikipedia, under exclusivity, marketing, marketing strategy, or consumer engagement. 'Product bundling' is a good place to start though-- lower marginal cost -and- higher marginal utility. ('Bundling' is also a social practice in the Netherlands!) Also see law of excluded middle.) Back to the exam: If A knows B's 'straight' and 'forward', maybe it can be helpful, merely advising, 'don't take any turns and you won't miss it (undershoot or overshoot)', which does take knowledge of steering, just not of the terrain. It's just that if I don't know how to stay on course, (not to turn), I'll still resent you. Not to mention, a 'great circle straight' isn't the same as a Euclidian one. It's possible, though, in the economy of social transaction, that "I" don't "have time" to "take you there", all of those being defined earlier: one of the parties can't afford to board, possibly return, tow, or tie you, or it isn't profitable. It's possible your ship can't take the tow too. Notwithstanding, in the domain of collective social entities (many- small/organisms), other senses of channel symbols / band symbols can arise. "That doesn't mean the same thing back home / back in the channel." I don't like learning the hard way-- by definition. But the solution to the 'rich bully dilemma' is pretty much boycott-- cf. Nash and optimal equilibrium. (That's optimal, not optical.) In light of some certain "mental health" observations too, if boycotts fail, protest is plan B. Mere incompetence on either part is pretty easy to fix. It's the 'incompetent rich bully' who interferes with everybody else. Nothing personal to the poster-- he covered his socal bases-- just being thorough. Last thing-- does "maintain forever" mean deal with us? Hush. A pretty small group could build/anchor an outland base and maintain people there forever, just with ferry trips back in. Past a certain radius too (from hubs), bases become polynomially sparser-- just move in with the monkey on your back, and we'll all get orbits around the sun. From gagsl-py2 at yahoo.com.ar Thu Mar 6 20:04:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 23:04:14 -0200 Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: En Thu, 06 Mar 2008 22:48:42 -0200, Krishna escribi?: >>>> class Test(object): > ... def __init__(self): > ... self.a= 2 > ... def func(self, k = self.a): > ... print k > ... > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in Test > NameError: name 'self' is not defined >>>> > > In the 'definition of the class', what would the first argument 'self' > in the methods evaluate to; when we have an object defined, it is > bound to the object reference, but what happens while the class > definition is executed, which I believe happens when the module > containing the class definition is imported Function default arguments are evaluated when the function is defined (when the class is defined, in this case) so "self" itself has not a value. Try this instead: def func(self, k=None): if k is None: k = self.a print k If None is an allowed argument, use a special marker instead: _marker=object() ... def func(self, k=_marker): if k is _marker: k = self.a ... -- Gabriel Genellina From asmodai at in-nomine.org Mon Mar 31 07:57:25 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 31 Mar 2008 13:57:25 +0200 Subject: ERROR: Python C API version mismatch for module dbi In-Reply-To: References: Message-ID: <20080331115725.GI80617@nexus.in-nomine.org> -On [20080331 12:56], Pradeep Rai (pradiprai at gmail.com) wrote: >Can you guide me how to install a 2.5 version of dbi for it to work ? Same way you installed dbi for 2.4 just make sure the called python executable is the 2.5 one. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ Sometimes things stare us in the face and we are too blind to see... From sturlamolden at yahoo.no Thu Mar 20 09:41:17 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 06:41:17 -0700 (PDT) Subject: wxFormBuilder Message-ID: I just discovered wxFormBuilder. After having tried several GUI builders for wx (including DialogBlocks, wxGlade, XRCed, Boa constructor), this is the first one I can actually use. To use it wxFormBuilder with wxPython, I generated an xrc resource and loaded it with wxPython. All the tedious GUI coding is gone :-) http://wxformbuilder.org/ http://wiki.wxpython.org/index.cgi/XRCTutorial From larry.bates at websafe.com Thu Mar 27 13:34:02 2008 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 27 Mar 2008 12:34:02 -0500 Subject: Py2exe embed my modules to libary.zip In-Reply-To: <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> Message-ID: <1206639241.3132.0.camel@fc8.home.com> Create your py2exe distribution without a zipfile and all the modules will just be put into the installation directory. Use Inno Setup to make a proper installer for your application. -Larry On Thu, 2008-03-27 at 06:44 -0700, vedrandekovic at yahoo.com wrote: > On 27 o?u, 10:44, "Gabriel Genellina" wrote: > > En Thu, 27 Mar 2008 06:00:26 -0300, escribi?: > > > > > > > > > I was add this into my application code: > > > > > import sys > > > import os > > > my_dir=os.getcwd() > > > sys.path.append(my_dir) > > > sys.path.append(my_dir+"\\libary.zip") > > > sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder > > > f=open("path.txt","w") > > > f.write(str(sys.path)) > > > f.close() > > > > > an the output in path.txt is : > > > > > ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users > > > \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ > > > \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ > > > \libary.zip\\py2exe'] > > > > > But it still can't find module py2exe.What should I do now? Any > > > examples? > > > > I assume you're talking about the py2exe package available from www.py2exe.org- so it's not a module, it's a package. > > py2exe usually is only relevant on your *development* machine, so why do > > you want to put it inside a .zip? What do you want to do? > > > > Anyway, I tried the following and could import py2exe successully (but I > > don't know if it actually works as a distutils extension...) > > > > - compressed the py2exe folder into py2exe.zip > > - deleted the original py2exe folder > > - moved py2exe.zip onto some temporary directory > > - tried to import py2exe, failed as expected > > - added py2exe.zip to sys.path > > - tried to import py2exe, this time OK > > > > py> import py2exe > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module named py2exe > > py> import sys > > py> sys.path.append(r"C:\TEMP\pna\py2exe.zip") > > py> import py2exe > > py> py2exe.__path__ > > ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] > > > > -- > > Gabriel Genellina > > Hello again, > > Thanks for previous post, it was useful! > > So now I know what is a problem, but I don't know how to solve > it.Under my application user can convert his python code to > executable, > I was created this with subprocess: > > retcode =subprocess.Popen(["ython","setup.py","py2exe","-d","exe"], > shell=True, stdout=subprocess.PIPE,creationflags = > win32process.CREATE_NO_WINDOW) > stdout_value = retcode.communicate()[0] > > ...Py2exe exit from process here: > > running py2exe > creating C:\Users\veki\Desktop\python\PGS\dist\build > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32 > creating C:\Users\veki\Desktop\python\PGS\dist\build > \bdist.win32\winexe > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe > \collect-2.5 > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe > \bundle-2.5 > creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe > \temp > creating C:\Users\veki\Desktop\python\PGS\dist\exe > *** searching for required modules *** > > ...it's trying to find d3d,d3dx,d3dc,d3dgui... modules but it can't > cause these modules are in library.zip.How can I set target for > finding path to library.zip , I'm running these py2exe compile process > from my main excutable? > > Regards, > Vedran From kwmsmith at gmail.com Wed Mar 26 01:53:29 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Wed, 26 Mar 2008 00:53:29 -0500 Subject: subprocess.popen function with quotes In-Reply-To: References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: On Wed, Mar 26, 2008 at 12:15 AM, skunkwerk wrote: > On Mar 25, 9:25 pm, "Gabriel Genellina" > wrote: > > En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk > > escribi?: > > > > > >> i'm trying to call subprocess.popen on the 'rename' function in > > >> linux. When I run the command from the shell, like so: > > > > >> rename -vn 's/\.htm$/\.html/' *.htm > > > > >> it works fine... however when I try to do it in python like so: > > >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > > >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > > > >> print p.communicate()[0] > > > > >> nothing gets printed out (even for p.communicate()[1]) > > > > > I'd try with: > > > > p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > > stdout=subprocess.PIPE, stderr=subprocess.PIPE, > > shell=True) > > > > (note that I added shell=True and I'm using a raw string to specify the > > reg.expr.) > > > > -- > > Gabriel Genellina > > Thanks Gabriel, > I tried the new command and one with the raw string and single > quotes, but it is still giving me the same results (no output). any > other suggestions? I had similar problems passing quoted arguments to grep -- I don't have rename on my system so I can't do an exact translation. First version, passing argument to grep that would normally have to be quoted if typed in shell: In [1]: from subprocess import * In [2]: p1 = Popen(['ls'], stdout=PIPE) In [3]: p2 = Popen(['grep', '[0-9]\{7\}'], stdin=p1.stdout, stdout=PIPE) # note that the grep regex isn't double quoted... In [4]: output = p2.communicate()[0] In [5]: print output cur0046700.png cur0046700_1.png cur0046750.png dendat0046700.png dendat0046700_1.png dendat0046750.png And we see that everything is hunky dory. Now, trying to pass grep a quoted argument: In [10]: p1 = Popen(['ls'], stdout=PIPE) In [11]: p2 = Popen(['grep', '"[0-9]\{7\}"'], stdin=p1.stdout, stdout=PIPE) In [12]: output = p2.communicate()[0] In [13]: print output In [14]: And we get nothing. N.B. that's a single-quote double-quote string argument to grep in the second example, not a triple single quote. Incidentally, a triple quoted string will work as well. Moral from this example: when passing arguments that would normally be quoted to be safe from the shell's expansion, etc, don't. Just pass it using Popen(['cmd', 'arg-that-would-normally-be-quoted']) and it will be passed directly to the function without the shell's intervention. Since the argument is passed directly to the command (rename in your case, grep in this one) quoting to preserve special characters isn't needed, and the quotes will be passed as part of the argument, giving the null results you got above. Kurt From phd at phd.pp.ru Mon Mar 3 11:48:33 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 3 Mar 2008 19:48:33 +0300 Subject: SQLObject 0.9.4 Message-ID: <20080303164833.GC5252@phd.pp.ru> Hello! I'm pleased to announce the 0.9.4 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.4 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.3 ---------------- Bug Fixes ~~~~~~~~~ * Use list.reverse() in manager/command.py for Python 2.2 compatibility. * Prevent MultipleJoin from removing the intermediate table if it was not created by the Join. * Fixed a bug with no default when defaultSQL is defined for the column. * Recognize POINT data type as string in PostgresConnection.columnsFromSchema(). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From durieux_br at yahoo.com.br Wed Mar 26 20:53:54 2008 From: durieux_br at yahoo.com.br (Salsa) Date: Wed, 26 Mar 2008 17:53:54 -0700 (PDT) Subject: Daylight savings time problem In-Reply-To: <20080326171009.8a6766bf.darcy@druid.net> Message-ID: <36633.21298.qm@web90607.mail.mud.yahoo.com> Yeah, I guess it would, but it doesn't feel like the "right" way to do it. Isn't there a way I can set tm_isdst to "-1"? Or at least slice the time_struct and then add another element to its end when passing it to mktime? Thanks for all your help! --- "D'Arcy J.M. Cain" wrote: > On Wed, 26 Mar 2008 13:23:23 -0700 (PDT) > Salsa wrote: > > I'm sorry, but could you be more specific? How > exactly should I use UTC? > > Pardon me. I misread. I thought that you were > creating the files. I > see that you are reading files created by someone > else. > > Still, would "os.environ['TZ'] = 'UTC'" fix the > issue? > > -- > 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. > -- Fabio Durieux Lopes - Salsa ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From ggpolo at gmail.com Thu Mar 27 11:04:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 12:04:06 -0300 Subject: Tkinter menus made easy In-Reply-To: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: 2008/3/27, MartinRinehart at gmail.com : > Writing Tkinter menu code used to be rather tedious, uninspiring work. > I figured that I could delegate the job to a program: > I didn't look at it yet, but just in case you weren't aware there is a gui designer tool for tkinter called GUI Designer (what a bad name), which used to be called SpecTcl, where you can design the menus and it then converts to python code. > http://www.martinrinehart.com/articles/menus.py > > Run it. Then look at the source (bottom of file). There's a bit more > doc in the doc comment at the top. > > Peer review is most welcome. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From furkankuru at gmail.com Thu Mar 27 17:37:49 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Thu, 27 Mar 2008 23:37:49 +0200 Subject: Filtering a Python list to uniques In-Reply-To: <438077.65068.qm@web50303.mail.re2.yahoo.com> References: <3a4a8f930803251645g1aed792bv5f0bceaaf2bc650e@mail.gmail.com> <438077.65068.qm@web50303.mail.re2.yahoo.com> Message-ID: <3a4a8f930803271437u9208b1aoc8a545d252e12177@mail.gmail.com> lstOne = [ 'A', 'B', 'C', 'C' ] dct = {} for item in lstOne: if dct.has_key(item): dct[item] += 1 else: dct[item] = 1 On Thu, Mar 27, 2008 at 10:51 PM, Kelly Greer wrote: > I'm in Python 2.4.4 > > And it works for me in the Python Shell like you just > did. Let me try another thing or two. I can't > reproduce the unhashable error now. :( > > Can you help me with one more thing? > If I have > lstOne = [ 'A', 'B', 'C', 'C' ] > > # what is the easiest way to get > # back a dictionary like this: > dct = { 'A': 1, 'B': 1, 'C': 2 } > # in other words counting the times a letter appears > in the list. > > Thanks, > Kelly > > > --- Furkan Kuru wrote: > > > set(lstone) > > works fine in python 2.5.1 > > > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) > > [MSC v.1310 32 bit (Intel)] > > on > > win32 > > Type "help", "copyright", "credits" or "license" for > > more information. > > >>> lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > > >>> set(lstone) > > set([1, 2, 3, 4, 5, 6]) > > > > > > > > On 3/26/08, kellygreer1 > > wrote: > > > > > > What is the best way to filter a Python list to > > its unique members? > > > I tried some method using Set but got some > > "unhashable" error. > > > > > > lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] > > > # how do i reduce this to > > > lsttwo = [ 1, 2, 3, 4, 5, 6 ] > > > > > > Is there a page on this in the Python in a > > Nutshell or the Python > > > Cookbook? > > > Did I miss something? > > > > > > Kelly Greer > > > kellygreer1 at nospam.com > > > change nospam to yahoo > > > -- > > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > -- > > Furkan Kuru > > > > > > > ____________________________________________________________________________________ > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. > http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From craigm3604 at gmail.com Thu Mar 20 14:09:29 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 11:09:29 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python Message-ID: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> I use a proprietary dll from Software Source (vbis5032.dll). I have successfully used it from Visual Basic 6, Fujitsu Cobol and from Perl. I would now like to use it from Python. The following is the C++ prototype for one of the functions: short FAR PASCAL VmxOpen(BSTR *Filespec, LPSHORT lpLocatorSize, LPSHORT lpOmode, LPHANDLE lphwmcb, BSTR *Password); The following is some Python code I put together: from ctypes import * from ctypes.util import * libc = cdll.msvcrt printf = libc.printf sprintf = libc.sprintf print "\nVB/ISAM testing:" fName = windll.oleaut32.SysAllocStringByteLen("s:\\msdb\\dcod\x00", 13) printf ("fName = \x22%slx22\n", fName) pw = windll.oleaut32.SysAllocStringByteLen("XYZ\x00", 4) printf ("pw = \x22%slx22\n", pw) CacheSize = c_long(0) OpenMode = c_long(3) vHandle = c_long(0) p_vHandle = pointer(vHandle) X = c_long(0) printf ("Before - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." X = windll.vbis5032.VmxOpen(byref(fName), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(pw)) printf ("After - X = %d, CacheSize = %d, OpenMode = %d, vHandle = %d \n", X, CacheSize, OpenMode, vHandle) exit(0) The following is the output from the Python code: VB/ISAM testing: fName = "s:\msdb\dcodlx22 pw = "XYZlx22 Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\test3.py", line 19, in X = windll.vbis5032.VmxOpen(byref(fName), byref(CacheSize), byref(OpenMode), byref(vHandle), byref(pw)) TypeError: byref() argument must be a ctypes instance, not 'int' I am neither a C++ nor a Python expert, but having already used this dll from other languages, I know this should be possible. I am sure it is just my lack of knowledge of Python. Can anyone assist with this? From deets at nospam.web.de Tue Mar 25 05:56:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Mar 2008 10:56:43 +0100 Subject: StringIO + unicode References: Message-ID: <64s0jhF2ctp4eU1@mid.uni-berlin.de> Laszlo Nagy wrote: > Is there a standard "in-memory file" interface for reading/writting > unicode stings? Something like StringIO. > > E.g. this would be possible: > > - create UnicodeStringIO > - write unicode strings into it > - wite data (binary) string of UnicodeStringIO into a file ('wb' mode) > > and then later: > > - read the same file with codecs.open(filename,"r",encoding="utf-8") > > Maybe there is no standard class for this and I have to implement it > myself. (?) Never tried it, but can't you just combine StringIO + codecs-module, the latter offers a wrapping-service for streams. Diez From bearophileHUGS at lycos.com Thu Mar 27 11:55:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 27 Mar 2008 08:55:13 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: On Mar 27, 3:54 pm, MartinRineh... at gmail.com wrote: > Writing Tkinter menu code used to be rather tedious, uninspiring work. > I figured that I could delegate the job to a program: I did develop a proggy that takes the following as input, it's part of my "agui" project, you can use it as an idea to improve your code: menudef = """ File New, callNew, Ctrl-N New Window, callNewWindow, Ctrl-Shift-N __ Open, lambda e=0:para(1), Ctrl-O __ Save, lambda e=0:para(2), Ctrl-S Save As, CallSaveAs, F12 __ Minimize, called, Ctrl-M Magic, called, Alt-X Edit Cut, called, Ctrl-X Copy, called, Ctrl-C Paste, called, Ctrl-V __ Align Left, Right, ___ """ m = Menu(root, globals(), menudef) Callee: def __init__(self, root, globalVars, menuDef, font=None, fieldSep=",", itemSep="_"): ... Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:06:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:06:22 -0300 Subject: StringIO + unicode References: <47E8C52C.9060501@shopzeus.com> Message-ID: En Tue, 25 Mar 2008 06:26:04 -0300, Laszlo Nagy escribi?: > Is there a standard "in-memory file" interface for reading/writting > unicode stings? Something like StringIO. > > E.g. this would be possible: > > - create UnicodeStringIO > - write unicode strings into it > - wite data (binary) string of UnicodeStringIO into a file ('wb' mode) No. Files contain bytes, not characters; you have to encode the Unicode object when writing to a file (or StringIO object). As Diez suggested, use the codecs classes: py> import codecs py> from StringIO import StringIO py> orig_file = StringIO() py> wrapped_file = codecs.getwriter('hex')(orig_file) py> wrapped_file.write("Hello world!") py> wrapped_file.getvalue() 48656c6c6f20776f726c6421 See http://docs.python.org/lib/stream-writer-objects.html -- Gabriel Genellina From Scott.Daniels at Acm.Org Sat Mar 29 18:25:47 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 29 Mar 2008 15:25:47 -0700 Subject: Licensing In-Reply-To: References: Message-ID: <13utg1v4rs9c2d1@corp.supernews.com> DS wrote: > I'm getting ready to publish a first open-source project written in > python. I am planning to use GPL as the license. However, in my code, > there is a function that I like from Python Cookbook.... > So, my options appear to be: > 1. Don't use it. > 2. Use it with no comment -- that doesn't seem right. > 3. Use it with remarks in the code that acknowledge the source. I vote for this. If you got it of the web site, include a url. If you went for the book, I'd prefer crediting both, but at least give enough so the interested reader can get back to some version of "the original." > 4. Provide a separate licensing page for that function > along with the GPL for my code. > What is the appropriate course of action here? I'm thinking #3 is > probably ok. How do others deal with this in an honorable way? As the author of several of those recipes, I definitely expect others to use them. I'd hate to slow them up by requiring them to ask permission, but would appreciate an acknowledgment. -Scott David Daniels Scott.Daniels at Acm.Org From michael.wieher at gmail.com Sun Mar 9 13:47:55 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 9 Mar 2008 12:47:55 -0500 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: Message-ID: 2008/3/9, Jeff Schiller : > > Hello, I'm creating an application using Qt (4.4 Beta atm). I have pretty > close to zero experience with Python (consisting of installing the > Python interpreter, downloading a python programming and executing it > on the command-line). > > I would like to invoke a Python script from my C++ Qt program and > capture its output as a C++ structure. It seems that PythonQt might > be suitable for my needs. > > Being a Qt program, I want this thing to be cross-platform. I'm > having trouble getting things set up in Windows. Has anyone had any > experience with this? > > I've built Qt from source using the mingw32 compiler. I installed > Python 2.5 binary. I am trying to build PythonQt from source. As per > http://pythonqt.sourceforge.net/#Building it says I need a "developer > installation" of Python containing the header files and the library > files. When I look at my system after installing the Python 2.5 > binary, I can see I have header files (C:\Python25\include), a 199k > python25.lib (C:\Python25\libs) and a 2MB python25.dll > (C:\Windows\System32\). Have I got what I need? > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > to build but then it fails: > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyCFunction_Type' > ... > > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. > > Thanks, > Jeff > > -- > http://mail.python.org/mailman/listinfo/python-list Another thing to be aware of, although this might not be something you need to worry about, is that there are debug-versions of the python libraries that are not installed by the MSI installer on windows. Sadly, the only way to get these libraries is to compile Python from source on your Windows machine, being sure to also create the debug libraries at this time. I don't know if you need them or not, because the error message you got was not entirely descriptive. ~mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.wieher at gmail.com Fri Mar 21 15:57:13 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Fri, 21 Mar 2008 14:57:13 -0500 Subject: How can I make a function equal to 0? In-Reply-To: References: Message-ID: Well, you could have a variable f that points at a memory address, such that >>> def x(): ... return ... >>> x >>> x=0 >>> x 0 >>> but I don't really understand why/what you're trying to do 2008/3/21, Martin Manns : > > Hi, > > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > > >>> def f(): return "" > ... > >>> # Some magic > >>> f == 0 > True > > Thanks in advance > > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:27:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:27:45 -0300 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13utucbj9mkrpd4@corp.supernews.com> Message-ID: En Sat, 29 Mar 2008 23:23:07 -0300, Steven D'Aprano escribi?: > The general problem is that I wish to time an arbitrary function with > arbitrary arguments. The function and arguments are provided to me as > Python objects, but timeit requires strings. Converting the objects to > strings is not practical, and the objects might not exist in the __main__ > module. Ah, ok, I understand now. I think this is more-or-less what you want: py> def test1(s): ... return len(s) ... py> def test2(s): ... return s.__len__() ... py> from timeanyfunc import timeanyfunc py> timeanyfunc(test1, [1,2,3]) [1.3858088108963571, 1.3810702198184406, 1.3818543976957964] py> timeanyfunc(test2, [1,2,3]) [1.6241321173501095, 1.6240804348038651, 1.6195021993018663] # timeanyfunc.py from timeit import Timer def timeanyfunc(fn, *args, **kw): global wrapped_fn def wrapped_fn(): return fn(*args, **kw) return Timer("wrapped_fn()", "from %s import wrapped_fn" % __name__ ).repeat() -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Mar 28 16:57:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 17:57:32 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 16:14:07 -0300, escribi?: > I am trying to install the twitter python wrapper...I got that > installed just fine, but am having serious troubles getting the > simplejson package to install. I need help diagnosing where this is > failing. I am trying to use: > > http://pypi.python.org/pypi/simplejson > > and I run "python setup.py build" and then "python setup.py install", > which both seem to work just fine. I don't understand - if it worked fine, what's the problem? > I tried running with easy_install, but that too is not working. I end > up with: > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > in my: > > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- > packages/ > > I am on Mac OS X 10.5. Any help would be greatly appreciated. And then you import simplejson and it fails? Or what? -- Gabriel Genellina From tmp1 at viltersten.com Fri Mar 7 13:04:35 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 19:04:35 +0100 Subject: SV: Regarding coding style In-Reply-To: References: <63d80bF273nraU1@mid.individual.net> Message-ID: <63ddenF2684mpU1@mid.individual.net> >> 2. You should use two spaces after a >> sentence-ending period. >> >> For heavens sake, why? I've always been >> obstructed by the double blanks but >> tolerated them. Now, that i read that >> it actually is a recommendation, i need >> to ask about the purpose. > > (a) It makes the ends of sentences more visually obvious. > (b) It makes text easier to parse reliably from scripts. > (c) Some text-editors can navigate such sentences out of > the box, whereas others cannot. Got it. Thanks. :) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From bj_666 at gmx.net Thu Mar 20 10:24:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Mar 2008 14:24:16 GMT Subject: Problem with PARAGRAPH SEPARATOR References: Message-ID: <64facgF29ep7qU1@mid.uni-berlin.de> On Thu, 20 Mar 2008 13:03:17 +0000, Dominique.Holzwarth wrote: > The output of the transformation (a big string containg the whole file) > contains a so called 'paragraph separator' (unicode: 2029). If I want to > pring that string (file) to the std out or a file object then I get a > "UnicodeError" saying that the unicode 2029 can't be encoded... > > Can anyone please tell me how I should handle that paragraph seperator? You have to encode the unicode object in an encoding that know this character. UTF-8 might be a candidate encoding for this. Ciao, Marc 'BlackJack' Rintsch From darcy at druid.net Wed Mar 5 10:13:59 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 5 Mar 2008 10:13:59 -0500 Subject: Why """, not '''? In-Reply-To: References: Message-ID: <20080305101359.20a8234d.darcy@druid.net> On Wed, 5 Mar 2008 06:56:24 -0800 (PST) MartinRinehart at gmail.com wrote: > Why is """ the preferred delimiter for multi-line strings? Where did you see that? The only place I saw it was the style guide and it was only talking about docstrings. Even there they used """ as an example but the text talked about using triple quotes as opposed to single quotes even when it is a single line docstring. I don't think that there is any preference for """ over ''' in general. Pick one for consistiency. Note however that """ can't be confused with " followed by ' as in "'A' is the first letter of the alphabet." -- 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 rschroev_nospam_ml at fastmail.fm Sat Mar 8 10:20:44 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 08 Mar 2008 16:20:44 +0100 Subject: List as FIFO in for loop In-Reply-To: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: malkarouri schreef: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > x = q.get() > #process x to get zero or more y's > #for each y: > q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > #process x to get zero or more y's > q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? Changing a loop while iterating over it is to be avoided, if possible. In any case, a deque is more efficient for this kind of use. I'd use it like this: from collections import deque q = deque([a, b, c]) while q: x = q.popleft() # ... q.append(y) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From hasnihon.support at gmail.com Mon Mar 24 19:51:00 2008 From: hasnihon.support at gmail.com (hasnihon.support at gmail.com) Date: Mon, 24 Mar 2008 16:51:00 -0700 (PDT) Subject: Serving another web site which requires authentication References: Message-ID: Hi binaryj, Yeah I feel lucky, thanks... Well, actually, I want my users to be able to see the auction information about some vehicles. It's a Japanese site (https://www.iauc.co.jp/) I've no experience about the proxy staff, but when I googled I found; - Twisted - pyCurl but, I don't know how to all the proxy thing... especially, serving the password protected area of the site.. hoping to feel lucky again :) On 24 Mart, 23:01, binaryj wrote: > ur in luck i am an expert at this! > tell me the details , site name etc > > you would have to proxy everything, basically the urls in the copied > page have to be changed to point to ur site. > > its highly possible. a minor adjustment to ur urlconf and it will work. From justin.mailinglists at gmail.com Tue Mar 18 23:08:11 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 18 Mar 2008 20:08:11 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: FWIW, using json.py I got from somewhere forgotten, >>> import json >>> url = 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails' >>> params = {'format':'json'} >>> import urllib >>> eparams = urllib.urlencode(params) >>> import urllib2 >>> request = urllib2.Request(url,eparams) >>> response = urllib2.urlopen(request) >>> s = response.read() >>> len(s) 115337 >>> s[:200] '{"phedex":{"request": [{"last_update":"1188037561","numofapproved":"1","id":"7425"}, {"last_update":"1188751826","numofapproved":"1","id":"8041"}, {"last_update":"1190116795","numofapproved":"1","id":"92' >>> x = json.read(s) >>> type(x) >>> x.keys() ['phedex'] >>> type(x['phedex']) >>> x['phedex'].keys() ['request_date', 'request_timestamp', 'request', 'call_time', 'instance', 'request_call', 'request_url'] ## json.py implements a JSON (http://json.org) reader and writer. ## Copyright (C) 2005 Patrick D. Logan ## Contact mailto:patrickdlogan at stardecisions.com ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA From castironpi at gmail.com Thu Mar 6 17:30:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 14:30:14 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <1c04696f-591e-4b3d-bdf4-8fdc4927f617@m34g2000hsc.googlegroups.com> <63b46aF26qudpU1@mid.uni-berlin.de> Message-ID: <9a5a78e4-79b2-4001-a8dc-5af816185b0c@f47g2000hsd.googlegroups.com> On Mar 6, 2:57?pm, Marc 'BlackJack' Rintsch wrote: > On Thu, 06 Mar 2008 11:06:50 -0800, castironpi wrote: > > On Mar 6, 8:30?am, Carl Banks wrote: > >> Anyway, the answer to what you are probably asking is No. ?Try this: > > >> >>>import module > >> >>>c1 = module.Someclass > >> >>>reload(module) > >> >>>c2 = module.Someclass > >> >>>c1 is c2 > > > What about > > >>>> o= object() > >>>> b1= o.someattr > >>>> reload( o ) > >>>> b2= o.someattr > >>>> b1 is b2 > > > ? > > You are really a bit thick, a troll, or a bot. The point was, that's one difference between classes and modules: you can't reload classes plonk. From sajmikins at gmail.com Tue Mar 18 18:42:22 2008 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Mar 2008 15:42:22 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> Message-ID: <35a65348-dfa4-4aae-a734-a14c120754a9@s19g2000prg.googlegroups.com> I love you guys, thanks! ;-) ~Simon From Lie.1296 at gmail.com Tue Mar 4 11:50:54 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 4 Mar 2008 08:50:54 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: On Mar 4, 1:12?pm, Mensanator wrote: > On Mar 3, 11:58?pm, Erik Max Francis wrote: > > > Mensanator wrote: > > > While we're on the subject of English, the word "worthless" > > > means "has no value". So, a program that doesn't work would > > > generally be "worthless". One that not only doesn't work but > > > creates side effects that cause other programs to not work > > > (which don't have bugs) would be "worse than worthless". > > > All programs have bugs, which means that in some circumstances, they > > won't work. ? > > And in such circumstances, would be worthless. > > > Therefore, by your reasoning, all programs are worse than > > useless. > > That doesn't follow from my reasoning. > > Suppose you downloaded a new calculator program that > couldn't add properly. That would be useless to you, right? > > But suppose the program contained a virus that erased > your hard drive. That would be "worse than useless", wouldn't it? > > > > > > I'm not hard to please at all. > > > No, of course not, since logically you must think all software is useless. > > Somehow, I expected better logic from people who call themselves > programmers. Mensanator, for alls sake, you've done right by pointing out the bug instead of muttering silently in your room, but there is a thing called tolerance that you really should learn, it's about tolerating and understanding the possibility that other people are humans too and humans create mistakes, lots of them in fact and that includes you (if you're humans). Along with tolerance should come a better choice of wordings, instead of saying "it sucks because it does something unexpected and unwanted" and telling everyone not to use it, you could just say "it does something unexpected and unwanted" and say that you wanted it fixed. It's not that you've done anything wrong, but it's about your attitude. From Dominique.Holzwarth at ch.delarue.com Thu Mar 20 11:39:50 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 20 Mar 2008 15:39:50 +0000 Subject: Problem with PARAGRAPH SEPARATOR In-Reply-To: <64facgF29ep7qU1@mid.uni-berlin.de> Message-ID: <8D5970DD46B50A409A0E42BA407964FE0E6DF433@SGBD012007.dlrmail.ad.delarue.com> Actually that's what I tried to do, for example: outputString = myString.encode('iso-8859-1','ignore') However, I always get such messages (the character, that's causing problems varies, but its always higher than 127 ofc...) 'ascii' codec can't decode byte 0xc3 in position 51: ordinal not in range(128) It doesn't matter what encoding I use (tried 'utf-8' 'utf-16' 'latin_1' and the iso one). The debugger is showing all the special characters (from french and german language) so I'm wondering why there's still the message about the 'ascii' codec... Would that mean that the string "myString" is an ascii-string or what? -----Original Message----- From: Marc 'BlackJack' Rintsch [mailto:bj_666 at gmx.net] Sent: Donnerstag, 20. M?rz 2008 15:24 To: python-list at python.org Subject: Re: Problem with PARAGRAPH SEPARATOR On Thu, 20 Mar 2008 13:03:17 +0000, Dominique.Holzwarth wrote: > The output of the transformation (a big string containg the whole > file) contains a so called 'paragraph separator' (unicode: 2029). If I > want to pring that string (file) to the std out or a file object then > I get a "UnicodeError" saying that the unicode 2029 can't be encoded... > > Can anyone please tell me how I should handle that paragraph seperator? You have to encode the unicode object in an encoding that know this character. UTF-8 might be a candidate encoding for this. Ciao, Marc 'BlackJack' Rintsch ********************************* This e-mail and any files attached are strictly confidential, may be legally privileged and are intended solely for the addressee. If you are not the intended recipient please notify the sender immediately by return email and then delete the e-mail and any attachments immediately. The views and or opinions expressed in this e-mail are not necessarily the views of De La Rue plc or any of its subsidiaries and the De La Rue Group of companies, their directors, officers and employees make no representation about and accept no liability for its accuracy or completeness. You should ensure that you have adequate virus protection as the De La Rue Group of companies do not accept liability for any viruses De La Rue plc Registered No.3834125, De La Rue Holdings plc Registered No 58025 and De La Rue International Limited Registered No 720284 are all registered in England with their registered office at: De La Rue House, Jays Close, Viables, Hampshire RG22 4BS From ptrk.mcm at gmail.com Tue Mar 25 23:37:07 2008 From: ptrk.mcm at gmail.com (ptrk.mcm at gmail.com) Date: Tue, 25 Mar 2008 20:37:07 -0700 (PDT) Subject: Files, directories and imports - relative to the current directory only References: <7e3185b0-a755-4b16-95ba-af8568c2a4b7@q78g2000hsh.googlegroups.com> Message-ID: <5608b49d-5537-4f35-85c3-6fd346ffd4fb@t54g2000hsg.googlegroups.com> On Mar 25, 11:27 am, ptn wrote: > Hello, group. > > I can only read files and import modules that are in the same > directory > as the one my script is. Here is a test script (path.py): > > import os > import uno # some module I wrote > > print list(os.walk('~/hacking/python')) > f = open('~/read/foo.txt') > print f.read() > > And here is the output: > > Traceback (most recent call last): > File "path.py", line 2, in > import uno > ImportError: No module named uno > > If I comment that import, the output becomes this: > > [] > Traceback (most recent call last): > File "path.py", line 4, in > f = open('~/read/foo.txt') > IOError: [Errno 2] No such file or directory: '~/read/foo.txt' > > (Notice the empty list at the beginning, that would be the output of > os.walk().) > > I have added this line to my .bashrc: > export PYTHONPATH=$PYTHONPATH:~/hacking/python > I thought that by doing so all the scripts found in that directory and > all it's children would be available for import, but that doesn't seem > to be the case. i'm not sure why you are unable to import uno (assuming uno is at ~/ hacking/python/uno.py) after exporting the PYTHONPATH variable. an alternative way to incorporate uno is to change sys.path, the list of search paths import sys sys.path.append(os.path.expanduser('~/hacking/python')) import uno From yuxi at ece.gatech.edu Wed Mar 12 20:44:50 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Wed, 12 Mar 2008 20:44:50 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > The photos are just coming straight from my digital camera. Same > format (JPEG), varying size (6-10 megapixel) and I would like to be > able to pick one and then query the database for similar ones. For > example: I pick a photo which is more or less a portrait of someone, > the query should return other photos with more or less portraits. If I > pick a landscape with lot of green and a mountain the query should > result in other nature (mostly green) photos. Something along these > lines, of course the matches won't be perfect because I'm looking for > a simple algorithm, but something along these lines. > Ah. In that case, SIFT isn't for you. SIFT would work well if you have multiple photos of the same object. Say, a building from different angles, or the a vase against different backdrops. If I'm understanding your correctly, what you're attempting here is very general and well into the highly experimental. I've been wishing for such a feature to appear in something like Google Image Search (pick/submit a photo and return similar images found on the web). I'm sure if there's even a practical solution, Google (or MS) would be on it already. The problem is that there isn't really one. Despite what you may see claimed in university press releases and research papers, the current crop of algorithms don't work very well, at least according to my understanding and discussion with researchers in this field. The glowing results tend to be from tests done under ideal conditions and there's no real practical and commercial solution. If you restrict the domain somewhat, there are some solutions, but none trivial. You are probably aware of the face searches available on Google and Live. The histogram approach suggested by Shane Geiger may work for some cases and in fact would work very well for identical resized images. I doubt it will work for the general case. A mountain with a grassy plain at noon has quite a different histogram from one at sunset, and yet both have related content. Manual tagging of the images, a la Flickr, would probably be your best bet. Good luck. From grante at visi.com Thu Mar 6 09:13:28 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 06 Mar 2008 14:13:28 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> <13subb12stga62c@corp.supernews.com> <87hcfk30lo.fsf@micah.cowan.name> Message-ID: <13svv088r9eu256@corp.supernews.com> On 2008-03-06, Micah Cowan wrote: > castironpi at gmail.com writes: >> On Mar 5, 8:03?pm, castiro... at gmail.com wrote: >>> assert b not in d >>> #there's the hangup >> >> *plonk* >> >> key is an iterable, just like the constructors to >> other collection. > > Um... "*plonk*" is the (imaginary) sound made by dropping someone into > your plonkfile (killfile, scorefile, whatever): the action of setting > your newsreader to ignore someone you perceive to be a troll. > > I have extreme doubts that you have actually done this to _yourself_. Oh, I don't know. I wouldn't be a bit surprised if he never reads anything that he's writes. ;) -- Grant Edwards grante Yow! I have many CHARTS at and DIAGRAMS.. visi.com From tmp1 at viltersten.com Sun Mar 2 11:50:58 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 17:50:58 +0100 Subject: SV: Where's GUI for Python? In-Reply-To: References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: <63038fF23j6foU1@mid.individual.net> >> You should also take a look at wxGlade: >> >> http://wxglade.sourceforge.net/ >> >> which sits on top of wxPython: >> >> http://wxpython.org/ >> >> which wraps wxWidgets: >> >> http://www.wxwindows.org/ > > I have used wxGlade, and while it worked well > enough, it didn't seem to fit my brain. I > always found myself "thinking backwards" in order > to guess how the tool needed me to do things. > For me, though, everytime I see raw wxPython code > these days I cringe, and am thankful that I don't > have to deal with it anymore. May i see a short sample of the two different ways of coding, please? I'm very curious how they differ (and of course, decide what's the most pleasurable way for me). As long as we're on the subject, i also wonder if there's a general concensus on which technology is recommended in the different types of projects that are developed. (E.g. "use A for small/fast fixes, use B for stuff you'll need to maintain later on".) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From wbsoft at xs4all.nl Thu Mar 20 09:45:02 2008 From: wbsoft at xs4all.nl (Wilbert Berendsen) Date: Thu, 20 Mar 2008 14:45:02 +0100 Subject: Thanks. (Re: keeping state in an iterator object by rebinding next()) In-Reply-To: <691a1267-0407-43e4-96d3-d58467af8614@59g2000hsb.googlegroups.com> References: <691a1267-0407-43e4-96d3-d58467af8614@59g2000hsb.googlegroups.com> Message-ID: <200803201445.02913.wbsoft@xs4all.nl> Thanks for all the elaborate answers and help! It helped me deepening my understanding of Python. Sincere, Wilbert Berendsen -- http://www.wilbertberendsen.nl/ "You must be the change you wish to see in the world." -- Mahatma Gandhi From sjmachin at lexicon.net Mon Mar 24 19:24:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Mar 2008 16:24:27 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: On Mar 25, 9:05 am, Julien wrote: > Hi all, and thanks a lot for your answers! > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making > up the term) a function: > > def hijacker(arg): > if I_feel_its_necessary: > hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > hijacker(something) > ... # Continue as normal > return 2 > Your end goal (avoiding duplicate code) is laudable. However most folk manage to do this without needing to invent arcane control structures like the COME FROM and the COBOL ALTER verb. def common_code(arg): if necessary(arg): return 1 # assuming None is not a valid return from myfunc1 etc return None def myfunc1(arg): return_value = common_code(something) if return_value is not None: return return_value # continue # Look, Ma! No decorators! Those functions could be methods of classes, but IMHO you don't need anything fancier than that. You mentioned maintainability. To borrow someone else's advice: Consider that the next person to maintain your code may know where you live and may possess a chain-saw. HTH, John From deets at nospam.web.de Mon Mar 10 11:58:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 16:58:33 +0100 Subject: defining a method that could be used as instance or static method References: Message-ID: <63l454F275mskU1@mid.uni-berlin.de> Sam wrote: > Hello > > I would like to implement some kind of comparator, that could be > called as instance method, or static method. Here is a trivial pseudo > code of what I would like to execute > >>> class MyClass: > ... def __init__(self, value): > ... self.value = value > ... def comp(self, compValue): > ... return self.value == compValue.value >>> a = MyClass(3) >>> b = MyClass(4) >>> c = MyClass(3) >>> a.comp(b) > False >>> a.comp(c) > True > > This is actually achieved by MyClass, how could implement it in order > to accept: > >>> MyClass.comp(a, b) > False > > I would really appreciate a pointer or a way to complete MyClass in > order to fulfill my requirements. Thank you for your attention. Did you try that it doesn't work? because it should. Whenever you do instance.method(arg, ..) you can as well do Class.method(instance, arg, ...) so your requirement should be met by comp already. Diez From qggjonny at msn.com Mon Mar 31 13:43:15 2008 From: qggjonny at msn.com (qgg) Date: Mon, 31 Mar 2008 10:43:15 -0700 (PDT) Subject: How to build a body like this use SOAPPy? Message-ID: <0b531c8c-9f33-48f5-9446-09a1cb2db313@e6g2000prf.googlegroups.com> repeat arrWords aa 11 bb 22 99 I try like this,but fail: WordsRequest(arrWords=[{'Name:u'aa','Num':u'11'}, {'Name:u'bb','Num':u'22'}],intActionId=99) WordsRequest(arrWords={'Name:u'aa','Num':u'11'},arrWords={'Name:u'bb','Num'?:u'22'},intActionId=99) From deets at nospam.web.de Thu Mar 13 06:21:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 11:21:52 +0100 Subject: List mutation method gotcha - How well known? References: Message-ID: <63sdi1F28jh62U1@mid.uni-berlin.de> Hendrik van Rooyen wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above > > I undertake to summarise answers posted to complete this "survey". None, as python chose deliberately to return None on mutating functions like append, sort and reverse. Diez From nishanthy012 at gmail.com Mon Mar 31 07:13:03 2008 From: nishanthy012 at gmail.com (nishanthy012 at gmail.com) Date: Mon, 31 Mar 2008 04:13:03 -0700 (PDT) Subject: DOYOULIKECOMPUTER Message-ID: <23dd1bcd-5157-4194-b18f-03655b19009a@b5g2000pri.googlegroups.com> http://myprofile0116.blogspot.com From ssharkey at linuxunlimited.com Wed Mar 26 12:33:31 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Wed, 26 Mar 2008 12:33:31 -0400 Subject: naive packaging question Message-ID: <47EA7ADB.3030400@linuxunlimited.com> Hello all, I've read a number of the python books, and several online tutorials about modules and packaging, but not one addresses this issue, so I thought I'd ask here... I am building a library for use in an internal project. This library is the client side interface to a REST-ful service that provides access to parts of our accounting database. BUT, we are pretty sure that the accounting database and hence the service implementation will change in the future. So, I want to design a generic (abstract) api for fetching various info from the accounting db, but I want to isolate the specific details into a module/package that can be changed in future (and co-exist with the old one). I've designed a generic api class, with functions to fetch the various info into python data structures (mostly lists of dictionaries, some just single values). And I've got an interface-specific version that follows that same api, and which is derived from the generic api. I'm a bit unclear on the best way to implement the module and package. Here's the directory structure that I've got so far: project

top level directory setup.py company eventually, we'll have other modules __init__.py error.py some classes that will be used in all log.py modules acctdb the acct db interface directory __init__.py api.py the abstract class def (derived from object) specific.py the specific implementation, derived from the api base class For arguments sake, let's call the base class (defined in api.py) 'BaseClass', and the specific implementation 'SpecificClass(BaseClass)' So, in the acctdb/__init__.py, do I do something like this: if SPECIFIC_CLASS: from company.acctdb.specific import SpecificClass as BaseClass with the idea that at some point in the future I'd designate a different class in some other way? Hopefully this is enough info for you to see what I'm trying to accomplish. It's a bit like the DB interfaces, where there is a generic DB API, and then the different drivers to implement that API (MySQL, etc). Thanks for any suggestions! -scott From gagsl-py2 at yahoo.com.ar Tue Mar 18 23:05:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 00:05:08 -0300 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: En Tue, 18 Mar 2008 18:25:28 -0300, Jeff Schwab escribi?: > I need to move a directory tree (~9GB) from one machine to another on > the same LAN. What's the best (briefest and most portable) way to do > this in Python? See Tools/scripts/ftpmirror.py in your Python installation. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Mar 26 00:14:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 01:14:23 -0300 Subject: last mouse movment or keyboard hit References: Message-ID: En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler escribi?: > I would like to get the time of the most recent human activity like a > cursor > movement or a key hit. > Does anyone know how I can get this back to start some action after there > has been no activity for X minutes/seconds? Which platform? On non-ancient Windows versions, you can periodically check GetLastInputInfo http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp -- Gabriel Genellina From martin at v.loewis.de Sat Mar 1 18:41:48 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 02 Mar 2008 00:41:48 +0100 Subject: cx_Freeze : LookupError: unknown encoding: ascii In-Reply-To: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> References: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> Message-ID: <47c9e9bc$0$4562$9b622d9e@news.freenet.de> > Can somebody point to some clues about options that need to be passed > to FreezePython API to get the right executable. You need to tell it to include the encodings.ascii module. Regards, Martin From jkugler at bigfoot.com Tue Mar 18 13:13:58 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Tue, 18 Mar 2008 09:13:58 -0800 Subject: Comunicate processes with python References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> Message-ID: Adri?n Bravo Navarro wrote: >> Is there any simple way to achieve this goal? We've been thinking of >> sockets but Im not conviced at all with that. If you want to communicate between processes on the same host, yes, you can use DBus or a couple of the options here: http://docs.python.org/lib/ipc.html If you want to communicate between hosts, then sockets is probably going to be your only options, although there are libraries that abstract some of that for you to make it easier to manage. You might want to take a look at Pyro. http://pyro.sourceforge.net/ j From micah at micah.cowan.name Sat Mar 1 21:31:35 2008 From: micah at micah.cowan.name (Micah Cowan) Date: Sun, 02 Mar 2008 02:31:35 GMT Subject: Book Recomendations References: Message-ID: <87ablhkga7.fsf@micah.cowan.name> Ira Solomon writes: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. I have found the official documentation available at python.org (including both the tutorial and references) to be very high-quality. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From nodrogbrown at gmail.com Fri Mar 7 11:30:18 2008 From: nodrogbrown at gmail.com (nodrogbrown) Date: Fri, 7 Mar 2008 08:30:18 -0800 (PST) Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: <507cc368-cfd4-4030-a4da-3a56c602c5f4@e60g2000hsh.googlegroups.com> > If the string is only used to open a file, and never shown to the user, > what you prefer is irrelevant, isn't it? guess thats right.. > Back to your code, try this: > > from os.path import join, normpath > folder = 'F:/brown/code/python/fgrp1' > names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist = [normpath(join(folder, name)) for name in names] thanks Gabriel.. gordon From josef.pktd at gmail.com Mon Mar 17 12:03:07 2008 From: josef.pktd at gmail.com (joep) Date: Mon, 17 Mar 2008 09:03:07 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> <0369b78b-6681-4807-b944-fb371cdd1522@59g2000hsb.googlegroups.com> Message-ID: On Mar 16, 10:35 pm, sturlamolden wrote: > On 15 Mar, 21:54, Unknown wrote: > > > I was expecting to replace the old value (serial) with the new one > > (todayVal). Instead, this code *adds* another line below the one found... > > > How can I just replace it? > > A file is a stream of bytes, not a list of lines. You can't just > replace a line with another, unless they have the exact same length. > You must rewrite the whole file to get it right. An example: looks for all 'junk*.txt' files in current directory and replaces in each line the string 'old' by the string 'new' import os, glob, fileinput allfiles = glob.glob(os.getcwd() + '\\junk*.txt') # makes absolute paths findstr = 'old' replstr = 'new' countlinesfound = 0 for line in fileinput.input(allfiles,inplace=1): if line.find(findstr) != -1: line = line.replace(findstr,replstr) # old string , new string countlinesfound += 1 print line, # this writes line back to the file print countlinesfound I found something similar in a tutorial when I started to learn Python, but I don't remember which one. Josef From darcy at druid.net Wed Mar 26 17:10:09 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 Mar 2008 17:10:09 -0400 Subject: Daylight savings time problem In-Reply-To: <585793.80038.qm@web90609.mail.mud.yahoo.com> References: <585793.80038.qm@web90609.mail.mud.yahoo.com> Message-ID: <20080326171009.8a6766bf.darcy@druid.net> On Wed, 26 Mar 2008 13:23:23 -0700 (PDT) Salsa wrote: > I'm sorry, but could you be more specific? How exactly should I use UTC? Pardon me. I misread. I thought that you were creating the files. I see that you are reading files created by someone else. Still, would "os.environ['TZ'] = 'UTC'" fix the issue? -- 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 roygeorget at gmail.com Tue Mar 11 06:35:46 2008 From: roygeorget at gmail.com (royG) Date: Tue, 11 Mar 2008 03:35:46 -0700 (PDT) Subject: rmdir problem Message-ID: hi i am checking if a directory exists and if it does i want to delete it and its contents.then i want to create the directory before creating files in it. def myfolderops(): testdir='..\mytestdir' #if dir exist remove it if isdir(testdir): rmdir(testdir) #again create directory mkdir(testdir) I am working on WinXP and logged in as admin in WinXP. when there is no dir called '..\mytestdir' or an empty dir this code works removing and creating the directory.but if the directory exists with contents already then it causes an error 145 when rmdir is executed.the message says 'directory is not empty' what should i do to correct this? (i need to remove the dir with its contents because each time i will be putting diff files into it and donot want them to be mixed with old files) thanks RG From jphalip at gmail.com Mon Mar 24 18:05:38 2008 From: jphalip at gmail.com (Julien) Date: Mon, 24 Mar 2008 15:05:38 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: Hi all, and thanks a lot for your answers! I'll try to explain a bit more what I'm after, and hopefully that will be clearer. In fact, what I'm trying to do is to "hijack" (I'm making up the term) a function: def hijacker(arg): if I_feel_its_necessary: hijack_caller_function_and_make_it_return(1) def my_function1(arg): hijacker(something) ... # Continue as normal return 2 def my_function2(arg): ... # Maybe do some processing here hijacker(whatever) ... # Continue as normal return 3 I have some long functions like my_function1 and my_function2 which I'd like to alter, but I want to keep the alterations as little as as possible. I'd like the extra behaviour to be handled by 'hijacker' and let it decide what the caller function should return. Just adding a call to 'hijacker' in all of these functions would be ideal for me because that would be quick to modify them and also easier to maintain, I believe. If 'hijacker' thinks it's necessary, it would force the caller function to return a certain value, otherwise it would let the caller function do its normal business. For while I thought I'd make hijacker a decorator: @hijacker def my_function(request): .... But that wouldn't work, since some functions need to do some processing before calling the hijacker. Yet, I think a decorator is systematically called before the function itself so no prior processing can be done by the function... Any idea on how to do that, if that's even possible? Thanks! Julien On Mar 25, 2:06 am, castiro... at gmail.com wrote: > On Mar 24, 9:48 am, Jason wrote: > > > > > On Mar 24, 5:21 am, Julien wrote: > > > > Hello all, > > > > I would like to do something like: > > > > def called(arg) > > > if arg==True: > > > !!magic!!caller.return 1 > > > > def caller(arg) > > > called(arg) > > > return 2 > > > > Here, the fake !!!magic!!! represents a statement (which I ignore) > > > that would make the caller function return a value different from what > > > it'd return normally. > > > > For example, caller(True) would return 1, and caller(False) would > > > return 2. The reason I want that is because I don't want the caller > > > function to know what's going on in the called function, and be > > > shortcut if the called function think it's necessary. > > > > Would you know if that's possible, and if so, how? > > > > I've done a bit of research and I think I've found some good pointers, > > > in particular using the 'inspect' library: > > > > import inspect > > > > def called(arg) > > > if arg==True: > > > caller_frame = inspect.stack()[1] > > > ... > > > > Here 'caller_frame' contains the frame of the caller function. Now, > > > how can I make that frame return a particular value? > > > > By the way, I'm not really interested in 'called' throwing an > > > exception and 'caller' catching it. In fact, I want things to remain > > > completely transparent for 'caller'. > > > > Hope that was clear... :/ > > > > Thanks! > > > > Julien > > > As Steven wrote, it's not very clear. If we knew the intent of this, > > we could perhaps point you to a more useful, maintainable technique. > > We don't know why you're trying to circumvent the programming language > > in this case. Any solution that works as you described will probably > > be unportable between the different Pythons (CPython, Jython, > > IronPython, etc). > > > Please note that the following code should work, but I've only run it > > through the interpreter in my brain. My brain's interpreter is full > > of Heisenbugs, so you may need to adjust a few things. Here's my > > thoughts: > > > Given: > > def First( arg ): > > Second( arg ) > > return 5 > > > 1) If you can modify both functions, change the first function to > > return a value in certain circumstances: > > def AltFirst( arg ): > > value = Second( arg ) > > if value is not None: return value > > return 5 > > > 2) Raise an exception in Second, and catch that exception above > > First: > > > class SecondExcept(Exception): > > def __init__(self, value): > > Exception.__init__(self, 'Spam!') > > self.value = value > > > def Second(arg): > > if arg == my_conditional_value: > > raise SecondExcept( 5 ) > > > # The following could even be put in your own function, > > # or in a wrapper or decorator for the First function. > > try: > > myvalue = First( 'Vikings!' ) > > except SecondExcept, exc: > > myvalue = exc.value > > > When you need to use an exceptional pathway, use an exception. They > > aren't just for reporting errors. > > Exceptions are a control tool. There was a 'goto using Exceptions' > once in the manuals. I don't see a problem with a local control-flow > object. It would appease a number of requests I've read. > > for x: > for y: > control.break( 2 ) > > if a: > if b: > control.fail( 2 ) > > so no need to reduplicate: > > else: > thing() > else: > thing() > > if a: > if b: > control.mostrecenttest( 0 ) > > def f(): > def g(): > control.return( 2 )( "early" ) > > Something tells me generators could solve the problem, but I may be > enamored, so it's a separate post. From arnodel at googlemail.com Wed Mar 26 03:27:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 00:27:17 -0700 (PDT) Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: On Mar 25, 10:55?pm, Steven D'Aprano wrote: > On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote: > > As per your suggestion, I tried looking at include/code.h and > > include/funcobject.h (my MS Windows distribution does not appear to > > contain .c files). ?However, since I'm not a C programmer, I did not > > find the .h files all that helpful. > > I'm hardly surprised. The naivety of those who insist that the "best way > to understand how new.function and new.code work" is to look at the C > source code for object is amusing. Since 'those who insist...' are just one person, me, you might as well name them. Firstly I didn't 'insist', I stated it once. Secondly I'm glad that I provided you with a few chuckles, but to proclaim that one is 'amused by the naivety of others' doesn't make one automatically right. Do you know how these functions behave? Have you looked at their documentation? new.function and new.code (implemented as Objects/ funcobject.c:func_new and Objects/codeobject.c:new_code) are not really documented (new.code.__doc__ is 'Create a code object. Not for the faint of heart.'). If you can't read the source then I don't think you should use the functions. > Not everybody reads C. This is a > Python group, and surely the best way would be to see some good examples > using *Python*. And this is what I did in the second part of my post. I gave an example which was in essence trying to illustrate the same aspect of Python as your example, quoted below (namely that you can use 'def' to create functions on the fly). > Here's an example that might help. > > class MyClass(object): > ? ? pass > > records = ["spam", "ham"] > for record in records: > ? ? # define a new function > ? ? def f(n): > ? ? ? ? return (record + " ")*n > ? ? # create a new instance > ? ? instance = MyClass() > ? ? # and dynamically add a method to it > ? ? setattr(instance, 'execute', f) > ? ? instance.execute(5) Amusingly naive'ly yours -- Arnaud From castironpi at gmail.com Mon Mar 24 11:26:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 24 Mar 2008 08:26:08 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> <210f1e24-649a-43c0-b975-8209211d56de@a70g2000hsh.googlegroups.com> <6900b188-8d08-4a9b-976f-719ba176fb97@e23g2000prf.googlegroups.com> Message-ID: <74f53b2d-5dae-4d9c-8ca7-f5bedc2f43f8@f63g2000hsf.googlegroups.com> On Mar 23, 12:22?pm, Lie wrote: > On Mar 22, 2:23?pm, castiro... at gmail.com wrote: > > > > Sane programmers don't write such semi-functional things (unless it > > > helps expressing the problem in certain domains). > > > I now think that deprecating map, lambda & Co. was a good thing after > > > all. > > > If you write it that way the first time, you need therapy. ?Actually, > > at this point, I (for one, personally) want to investigate 'certain > > domains'. ?Tell me it's really bad at everything or what it's good > > at. ?What can I respect about it? > > If you (castiro..) write it your way, you'll surely win the Obfuscated > Python Code Contest. Sometimes you're on a roll and you don't want to back up a step. What are good "on a roll" habits? (Or, what roll?) From python.list at tim.thechases.com Sat Mar 1 17:09:45 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 Mar 2008 16:09:45 -0600 Subject: A python STUN client is ready on Google Code. In-Reply-To: References: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> <8ce119530803010101w320b8d30md5112aebab6f7551@mail.gmail.com> Message-ID: <47C9D429.5050706@tim.thechases.com> > |I upload a new version. Add more print log into my code to help people > | understand my program > > Announcements should include a short paragraph explaining what the > announcement is about for those of us not in the know. IE, what is > STUN? -- and therefore, what is a STUN client? I believe this STUN client refers to http://en.wikipedia.org/wiki/Simple_traversal_of_UDP_over_NATs which is used if both user A and user B are behind a NAT'ing (Network Address Translating) firewall, and need to talk directly with each other. -tkc From castironpi at gmail.com Sat Mar 1 09:17:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 06:17:59 -0800 (PST) Subject: UponAcquiring synchro. class Message-ID: <82d1a986-fc02-495b-bace-298bc88440e8@s8g2000prg.googlegroups.com> from __future__ import with_statement ''' 3) upon_acquiring( lockA, lockB )( function, *ar, **kwar ) upon_acquiring spawns new thread upon acquiring locks A and B. Locks may be specified in any order, as none is acquired until all are free. The options to spawn a new thread upon call, lock, and not release until "it's its turn"; just block until then; and vary honoring order are open. 6) @with_self Prepends the function object to itself to the parameter list ''' ''' a lockA lockB b lockA lockB c lockA lockB d lockA lockC e lockB lockD f lockE lockF assert a< b assert b< c assert c< d assert c< e assert f in. ''' ''' A (A,B)1 (A,C)2 (A,B)3 B (A,B)1 (A,B)3 C (A,C)2 (C,D,E)4 D (C,D,E)4 E (C,D,E)4 a.lock: A, a.state: Free, a.waiters: [ X1(a,b), X2(a,c), X3(a,b) ] b.lock: B, b.state: Free, b.waiters: [ X1(a,b), X3(a,b) ] c.lock: C, c.state: Free, X3.waiters: [ X2(a,c), X4(c,d,e) ] d.lock: D, d.state: Free, X3.waiters: [ X4(c,d,e) ] e.lock: E, e.state: Free, X3.waiters: [ X4(c,d,e) ] acq a,b x1= a,b a.waiters+= x1 b.waiters+= x1 #same as if a.state is free and b.state is free: a.state= taken b.state= taken a.waiters-= x1 b.waiters-= x1 a.lock.release() #acq? b.lock.release() #acq? x1.lock.release() acq a,c x2= a,c a.waiters+= x2 c.waiters+= x2 if a.state is free and c.state is free: a.state= taken c.state= taken a.waiters-= x2 c.waiters-= x2 a.lock.release() #acq? c.lock.release() #acq? x2.lock.release() acq a,b x3= a,b a.waiters+= x3 b.waiters+= x3 acq c,d,e x4= c,d,e c.waiters+= x4 d.waiters+= x4 e.waiters+= x4 ''' from thread import start_new_thread from threading import Lock, Thread, Event import time from functools import partial class LockDeps: def __init__( self, lock, state, waiters ): self.lock, self.state, self.waiters= \ lock, state, waiters class LockSet: #ok to use them elsewhere, just gets in line. def __init__( self, *locks ): self._locks= locks self._lock= Lock() self._lock.acquire() self._remains= set( locks ) self._doneevt= Event() self.th= None self.retval= None def release( self, *locks ): for lock in locks: lock.release() self._remains.remove( lock ) def releaseall( self ): for lock in self._remains: lock.release() self._remains.clear() class UponAcquiring: def __init__( self ): self._deps= {} self._oplock= Lock() def acq( self, *locks ): lckset= LockSet( *locks ) return partial( self._enqueue, lckset ) def _enqueue( self, lckset, fun, *ar, **kwar ): with self._oplock: for lock in lckset._locks: dep= self._deps.get( lock ) if None is dep: dep= LockDeps( lock, False, [] ) self._deps[ lock ]= dep dep.waiters.append( lckset ) th= Thread( target= self._functhd, args= ( lckset, fun )+ ar, kwargs= kwar ) lckset.th= th th.start() self._analyze( lckset ) return lckset def _functhd( self, lckset, fun, *ar, **kwar ): try: with lckset._lock: lckset.retval=\ fun( lckset, *ar, **kwar ) lckset._doneevt.set() finally: with self._oplock: lckset.releaseall() for lock in lckset._locks: self._deps[ lock ].state= False self._analyze( lckset ) def _analyze( self, lckset ): with self._oplock: for lock in lckset._locks: dep= self._deps[ lock ] if dep.state: continue for lckset in dep.waiters: assert lock in lckset._locks for lock2 in lckset._locks: if self._deps[ lock2 ].state: break else: for lock2 in lckset._locks: dep2= self._deps[ lock2 ] dep2.state= True assert dep2.waiters.count( lckset )== 1 dep2.waiters.remove( lckset ) lock2.acquire() lckset._lock.release() break results= [] ver= results.index lcksets= set() import random from sys import stdout def callback( locks, i ): stdout.write( 'cb%i '% i ) time.sleep( random.uniform( 0, .01 ) ) results.append( i ) if random.choice( [ False, True ] ): locks.releaseall() #if random.random()< 0.1: # raise Exception() while 1: class Case1: lockA, lockB, lockC= Lock(), Lock(), Lock() lockD, lockE, lockF= Lock(), Lock(), Lock() a= ( lockA, lockB ) b= ( lockA, lockB ) c= ( lockA, lockB ) d= ( lockA, lockC ) e= ( lockB, lockD ) f= ( lockE, lockF ) ua= UponAcquiring() for i, x in enumerate( [ a, b, c, d, e, f ] ): lcksets.add( ua.acq( *x )( callback, i ) ) for lckset in lcksets: lckset.th.join() stdout.write( repr( results ) ) stdout.write( '\n' ) stdout.flush() assert ver( 0 )< ver( 1 ) assert ver( 1 )< ver( 2 ) assert ver( 2 )< ver( 3 ) assert ver( 2 )< ver( 4 ) assert len( set( results ) )== len( results ) '''permissible orders e.g.: [0, 5, 1, 2, 3, 4] [5, 0, 1, 2, 3, 4] [0, 5, 1, 2, 4, 3] [5, 0, 1, 2, 4, 3] ''' del results[:] lcksets.clear() From Graham.Dumpleton at gmail.com Sat Mar 15 02:03:17 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 14 Mar 2008 23:03:17 -0700 (PDT) Subject: How to import custom python file in python server page (psp) ? References: <60bb95410803140415x621b5b23w75b83013997c750b@mail.gmail.com> Message-ID: <3d073ffc-865e-4401-ac92-b22994d2b447@h11g2000prf.googlegroups.com> On Mar 15, 6:44?am, Joshua Kugler wrote: > James Yu wrote: > > Hi folks, > > > I prepared a python script for dynamically get the absolute paths of the > > files in certain folder. > > Then I tried to invoke that function from my web server in a .psp file > > like this: > > > ? ? ? 1 > > ? ? ? 2 > > ? ? ? 3 asdfasdfasdfa > > ? ? ? 4 > > ? ? ? 5 <% > > ? ? ? 6 import glob > > ? ? ? 7 import os > > ? ? ? 8 *import Helper > > * ? ? ?9 > > ? ? ?10 body = '' > > ? ? ?11 top = 'asdfasdfasdfa' > > ? ? ?12 links = {} > > ? ? ?13 *Helper.GetLinks(top=top) > > * ? ? 14 *paths = Helper.GenLinkPath(links) > > * ? ? 15 body = paths > > ? ? ?16 %> > > ? ? ?17 ? ? <%=body%> > > ? ? ?18 > > ? ? ?19 > > > However, this is the error message I received when I open the page in a > > browser: > > >>Mod_pythonerror: "PythonHandlermod_python.psp" > > >> Traceback (most recent call last): > > >> ? File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, > >> in HandlerDispatch > >> ? ? result = object(req) > > >> ? File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 302, in > >> handler > >> ? ? p.run() > > >> ? File "/usr/lib/python2.5/site-packages/mod_python/psp.py", line 213, in > >> run > >> ? ? exec code in global_scope > > >> ? File "/var/www/.cyu021/.pic/index.psp", line 8, in > >> ? ? import Helper > > >> ImportError: No module named Helper > > > *PS. I put Helper.py and index.psp in the same dir > > * > > Thanks in advance, > > What is the import path? ?The current directory in PSP might not be the > directory in which the .psp file resides. ?Print out sys.path before you > import your helper module to see what paths you're dealing with. If using mod_python 3.3.1, see: http://issues.apache.org/jira/browse/MODPYTHON-220 Graham From castironpi at gmail.com Tue Mar 18 14:20:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 11:20:50 -0700 (PDT) Subject: Get actual call signature? References: Message-ID: On Mar 18, 5:40?am, Jarek Zgoda wrote: > Say, I have a function defined as: > > def fun(arg_one, arg_two='x', arg_three=None): > ? ? pass > > Is there any way to get actual arguments that will be effectively used > when I call this function in various ways, like: > > fun(5) => [5, 'x', None] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] > fun(5, 'something') => [5, 'something', None] > > (et caetera, using all possible mixes of positional, keyword and default > arguments) > > I'd like to wrap function definition with a decorator that intercepts > not only passed arguments, but also defaults that will be actually used > in execution. > > If this sounds not feasible (or is simply impossible), I'll happily > throw this idea and look for another one. ;) It evaluates to a substantial problem. The combinations include things that Python disallows, such as double-spec. of keywords and spec'n of keys w/out a dictionary arg; as well as double-spec'ing of inspection. How do you want to access the parameters? What is the least redundant way? P.S. Does there exist a possible authority who doesn't want me to post this? How about an index of value and list/tuple of name? > def fun(arg_one, arg_two='x', arg_three=None): > fun(5) => [5, 'x', None] get_args( fun, 5 )-> names= [ 'arg_one', 'arg_two', 'arg_three' ] vals= [ 5, 'x', None ] > fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']] get_args( fun, 5, arg_three=['a', 'b'] ) names= [ 'arg_one', 'arg_two', 'arg_three' ] vals= [ 5, 'x', ['a', 'b'] ] > fun(5, 'something') => [5, 'something', None] get_args( fun, 5, 'something' )-> names= [ 'arg_one', 'arg_two', 'arg_three' ] vals= [ 5, 'something', None ] From toby at tobiah.org Mon Mar 24 16:28:41 2008 From: toby at tobiah.org (Tobiah) Date: Mon, 24 Mar 2008 13:28:41 -0700 Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. Can't you just put the script on a network share? Tobiah -- Posted via a free Usenet account from http://www.teranews.com From goon12 at gmail.com Mon Mar 10 19:12:37 2008 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 10 Mar 2008 19:12:37 -0400 Subject: Python Sockets Help In-Reply-To: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> References: <97c94446-f685-492a-9314-7f98dedaa9f0@m3g2000hsc.googlegroups.com> Message-ID: <6a2ccd190803101612l1a59ba27q83b88add32f28066@mail.gmail.com> On Mon, Mar 10, 2008 at 6:58 PM, Mark M Manning wrote: > I need your expertise with a sockets question. > > Let me preface this by saying I don't have much experience with > sockets in general so this question may be simple. I would suggest taking a quick look at this tutorial. http://ilab.cs.byu.edu/python/ Especially this: http://ilab.cs.byu.edu/python/socket/echoserver.html From darkwind.87 at gmail.com Wed Mar 26 09:22:21 2008 From: darkwind.87 at gmail.com (Dark Wind) Date: Wed, 26 Mar 2008 06:22:21 -0700 Subject: Dimensions of Arrays, Matrices Message-ID: <8a6035a00803260622v686441ddy1d3dd942b2377e21@mail.gmail.com> Hi, Suppose we have a 3X3 matrix in Mathematica. We can get its dimensions by: Dimensions[A] = {3,3} TensorRank[A] = 2 Are there exact functions for these two in Python? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From tlesher at gmail.com Tue Mar 18 14:01:14 2008 From: tlesher at gmail.com (Tim Lesher) Date: Tue, 18 Mar 2008 11:01:14 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net><9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com><13t462h7vgqo081@corp.supernews.com><7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com><13t4k50d7pg0d63@corp.supernews.com><1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com><13t5cbcrhtfsrd2@corp.supernews.com><13t5qd3slgt9nc0@corp.supernews.com><63g9s0F26pgoeU1@mid.individual.net><13t6c8kdis2gbb5@corp.supernews.com> <13t6tha12dcdh5a@corp.supernews.com> Message-ID: On Mar 9, 2:04 am, "Ryan Ginstrom" wrote: > > On Behalf Of Grant Edwards > > I think docstrings are a great idea. What's needed is a way > > to document the signature that can't get out-of-sync with > > what the fucntion really expects. > > Like doctests? (I know, smart-ass response) > > Regards, > Ryan Ginstrom Not a smart-ass response at all--a _smart_ response. Doctests are one of the few mechanisms I've ever seen that even attempt to make this happen. -- Tim Lesher tlesher at gmail.com From poof65 at gmail.com Sat Mar 1 22:11:24 2008 From: poof65 at gmail.com (poof65) Date: Sun, 2 Mar 2008 04:11:24 +0100 Subject: Question about lambda and variable bindings In-Reply-To: <47CA160C.3000305@gmail.com> References: <47CA160C.3000305@gmail.com> Message-ID: An idea, i don't know if it will work in your case. for x in xrange(10): funcs.append(lambda p,z=x: testfunc(z+2,p)) On Sun, Mar 2, 2008 at 3:50 AM, Michael Torrie wrote: > I need to use a lambda expression to bind some extra contextual data > (should be constant after it's computed) to a call to a function. I had > originally thought I could use something like this demo (but useless) code: > > funcs=[] > > def testfunc(a,b): > print "%d, %d" % (a,b) > > for x in xrange(10): > funcs.append(lambda p: testfunc(x+2,p)) > > > Now what I'd like is to call, for example, funcs[0](4) and it should > print out "2,4". In other words I'd like the value of x+2 be encoded > into the lambda somehow, for funcs[x]. However the disassembly shows > this, which is reasonable, but not what I need: > > >>> dis.dis(funcs[0]) > 2 0 LOAD_GLOBAL 0 (testfunc) > 3 LOAD_GLOBAL 1 (x) > 6 LOAD_CONST 0 (2) > 9 BINARY_ADD > 10 LOAD_FAST 0 (p) > 13 CALL_FUNCTION 2 > 16 RETURN_VALUE > > The LOAD_GLOBAL 1 (x) line is definitely a problem. For one it refers > to a variable that won't be in scope, should this lambda be called from > some stack frame not descended from the one where I defined it. > > So how can I create a lambda expression that calculates a constant based > on an expression, rather than referring to the object itself? Can it be > done? > > Michael > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Thu Mar 13 09:09:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Mar 2008 14:09:13 +0100 Subject: Python - CGI - XML - XSD References: <4dbfb5dc-2e02-4a23-8ad1-ddb32a7469f5@e25g2000prg.googlegroups.com> <63ptavF28u3flU2@mid.uni-berlin.de> <47D80BC4.2010307@behnel.de> Message-ID: <63snbqF26qphaU1@mid.uni-berlin.de> > Sorry, it was really late when i wrote this post. The file is an XSL > file. It defines HTML depending on what appears in the XML document. Then the content-type might be the culprit, yes. But testing so would have been faster than waiting for answers here... Diez From deets at nospam.web.de Wed Mar 19 11:27:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 16:27:50 +0100 Subject: How to get an XML DOM while offline? References: Message-ID: <64cpnvF2at1j9U1@mid.uni-berlin.de> william tanksley wrote: > I want to parse my iTunes Library xml. All was well, until I unplugged > and left for the train (where I get most of my personal projects > done). All of a sudden, I discovered that apparently the presence of a > DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing > the Internet... So suddenly I was unable to do any work. > > I don't want to modify the iTunes XML; iTunes rewrites it too often. > How can I prevent xml.dom.minidom from dying when it can't access the > Internet? > > Is there a simpler way to read the iTunes XML? (It's merely a plist, > so the format is much simpler than general XML.) Normally, this should be solved using an entity-handler that prevents the remote fetching. I presume the underlying implementation of a SAX-parser does use one, but you can't override that (at least I didn't find anything in the docs) The most pragmatic solution would be to rip the doctype out using simple string methods and/or regexes. Diez From furkankuru at gmail.com Tue Mar 25 08:34:58 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Tue, 25 Mar 2008 14:34:58 +0200 Subject: embedded python in c++ packaging In-Reply-To: <21CFA1FC32D3214EBFA2F449FF211E310EAD2878@nypcmg1exms318.leh.lbcorp.lehman.com> References: <3a4a8f930802070839n31ac4d88t96d64a4138d23ff4@mail.gmail.com> <3a4a8f930802071505x70946723wabe84ad9ea4ae465@mail.gmail.com> <21CFA1FC32D3214EBFA2F449FF211E310EAD2878@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <3a4a8f930803250534h4c9073ej750291b6373b43c5@mail.gmail.com> Sorry for long delay, I've tried below code (Setting pythonpath environment variable) and then initialize python interpreter but the embedded python interpreter did not get the newly assigned PYTHONPATH. I ve looked at the sys.path in python code (that is run by the embedded interpreter) and it behaved according to older pythonpath. Setting environment variable seemed to be correct. Does py_initialize run in another thread so it starts before setting the environment var? // add custom plib.zip archive to pythonpath if(!::getenv("PYTHONPATH")) { ::putenv("PYTHONPATH=.;.\\plib.zip"); } else ::putenv("PYTHONPATH=%PYTHONPATH%;.\\plib.zip"); std::cout << "PYTHONPath Set to: " << ::getenv("PYTHONPATH") << std::endl << "And Again: "; system("echo %PYTHONPATH%"); Py_Initialize(); Regards, On Fri, Feb 8, 2008 at 2:08 AM, Bronner, Gregory wrote: > I've done this the rather old-fashioned way. > > Basically, what I do is: > > Step 1: > > Embed Python: > if(!::getenv("PYTHONHOME")) > { > ::putenv("PYTHONHOME="); > } > if(!::getenv("PYTHONPATH")) > { > ::putenv("PYTHONPATH=."); > } > > Py_SetProgramName("leaktester"); > Py_InitializeEx(0); > init_memoryhoginterface(); // This initializes your SWIG module > PyRun_SimpleString("print 'HELLO FROM PYTHON'"); //<--- OR you can do > something else here like run a file > > > Step 2: > Extend python to talk back to your C++ code. > I use one giant SWIG module (see init function above) > > SWIG allows you to finely control what you expose to python, so you don't > wind up exposing the whole C++ API. > > > > > > > > > > ------------------------------ > *From:* Furkan Kuru [mailto:furkankuru at gmail.com] > *Sent:* Thursday, February 07, 2008 6:06 PM > *To:* python-list at python.org > *Subject:* Re: embedded python in c++ packaging > > I do not have access to my development machine right now. > but is it enough adding just a simple line at the top of my main python > file 'sys.path.append("modules.zip")' before importing any other modules? > > On 2/7/08, Gabriel Genellina wrote: > > > > En Thu, 07 Feb 2008 16:18:57 -0200, Joshua Kugler > > escribi?: > > > Furkan Kuru wrote: > > >> > > >> I have been developing an application in C++ that embeds Python > > >> interpreter. It takes advantage of too many modules from Python. > > >> When I want to package this application, I need to add too many files > > >> (.pyc) from Python/lib folder together with Python25.dll. > > >> Is there a way to pack these .pyc files to a zip file and redirect > > >> Python25.dll to that zip file? > > > > > > That is effectively what py2exe does with the modules required by the > > > main > > > application. It takes all the required modules and puts them in a > > > library.zip file. You might take a look at how it does it. > > > > Using py2exe has an additional advantage, it recursively scans all > > modules > > looking for dependencies. > > Once you know the required set of modules, you can bundle them in a .zip > > file and add its full path into sys.path (the absolute path including > > filename and .zip extension). Python does look into the .zip searching > > for > > modules. > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Furkan Kuru > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - This message is intended only for the personal and > confidential use of the designated recipient(s) named above. If you are not > the intended recipient of this message you are hereby notified that any > review, dissemination, distribution or copying of this message is strictly > prohibited. This communication is for information purposes only and should > not be regarded as an offer to sell or as a solicitation of an offer to buy > any financial product, an official confirmation of any transaction, or as an > official statement of Lehman Brothers. Email transmission cannot be > guaranteed to be secure or error-free. Therefore, we do not represent that > this information is complete or accurate and it should not be relied upon as > such. All information is subject to change without notice. -------- IRS > Circular 230 Disclosure: Please be advised that any discussion of U.S. tax > matters contained within this communication (including any attachments) is > not intended or written to be used and cannot be used for the purpose of (i) > avoiding U.S. tax related penalties or (ii) promoting, marketing or > recommending to another party any transaction or matter addressed herein. -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From willsteve2003 at yahoo.ca Mon Mar 10 11:30:00 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Mon, 10 Mar 2008 08:30:00 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> Message-ID: <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> On Mar 10, 10:26?am, Roel Schroeven wrote: > rockingred schreef: > > > > > > > On Mar 8, 8:27 pm, Dan Bishop wrote: > >> // ? ?Copyright (C) 2008 Foobar Computer Consulting > >> // > >> // ? ?VERSION ? PROJECT# ? ? DATE ? ? DESCRIPTION > >> // ? ?------- ? -------- ? -------- ? ------------------ > >> // ? ? ?1.00 ? ? 123456 ? ?01/04/08 ? Original creation. > >> // > > >> Eleven lines, of which the only useful information to me was the > >> project number, as knowing this let me look up who was behind these > >> comments. > > > Actually, "editorial" comments that tell you who last changed a > > program, when and why can be useful. ?I worked in a company with a > > number of programmers on staff. ?Having comments that told us Joe > > worked on a program yesterday that isn't working today could often > > solve half the battle. ?Especially if Joe also added a comment near > > the lines he had changed. ?Likewise including the "Project#" would > > help us track all the programs that had to be changed for a specific > > project. ?This allowed us to move all related items into the Live > > system once the testing phase had been completed (we just searched for > > everything with the same Project# in it). ?Yes, on rare occasions we > > would have an entire page of "Editorial" comments to ignore at the > > beginning of our program listing, but it was easy enough to skip that > > page. ?I will grant you that probably after 10 changes the first > > change isn't as important anymore (unless you want to backtrack and > > find out who started the Project in the first place and what it's > > original purpose was). > > That is certainly useful, but IMO that's what version control systems > are for. > > -- > The saddest aspect of life right now is that science gathers knowledge > faster than society gathers wisdom. > ? ?-- Isaac Asimov > > Roel Schroeven- Hide quoted text - > > - Show quoted text - Unfortunatly, in many of the companies I worked for, version control software was not implemented. In some cases, where it was, it actually inserted the comments into the header of the program as described. In others, the software was so limited as to make it useless. From bignose+hates-spam at benfinney.id.au Sun Mar 16 21:03:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Mar 2008 12:03:37 +1100 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <87zlsyyxee.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > I would like to encourage anyone who was at PyCon but has not > provided formal feedback to use the following URLs: For those who don't like to follow opaque munged URLs from services that give no indication where you'll end up, here are the actual URLs you'll arrive at: > For the conference: > http://tinyurl.com/2ara8u PyCon 2008: Conference Feedback > For the tutorials: > http://tinyurl.com/2ew2pc PyCon 2008: Tutorial Evaluation Thanks for posting these links, Aahz. -- \ "Imagine a world without hypothetical situations." ?anonymous | `\ | _o__) | Ben Finney From steve at holdenweb.com Sun Mar 2 12:45:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Mar 2008 12:45:50 -0500 Subject: Problem with the strip string method In-Reply-To: References: Message-ID: Colin J. Williams wrote: > The Library Reference has > strip( [chars]) > > Return a copy of the string with the > leading and trailing characters removed. > The chars argument is a string > specifying the set of characters to be > removed. If omitted or None, the chars > argument defaults to removing > whitespace. The chars argument is not a > prefix or suffix; rather, all > combinations of its values are stripped: > >>> ' spacious '.strip() > 'spacious' > >>> 'www.example.com'.strip('cmowz.') > 'example' > > Only the last two examples below behave > as expected. > Adjust your expectations. The software is correct. > Is it intended that the full range of > characters be handled? > > Colin W. > > [Dbg]>>> 'ab$%\n\rcd'.strip('%') > 'ab$%\n\rcd' > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%\n\rcd' > [Dbg]>>> 'ab$%cd'.strip('$') > 'ab$%cd' > [Dbg]>>> ' ab$%cd '.strip('$') > ' ab$%cd ' > [Dbg]>>> ' ab$%cd '.strip('%') > ' ab$%cd ' > [Dbg]>>> ' spacious '.strip() > 'spacious' > [Dbg]>>> 'www.example.com'.strip('cmowz.') > 'example' I suspect what you need is the .replace() method. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jeff at schwabcenter.com Mon Mar 17 11:45:16 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 08:45:16 -0700 Subject: Missing PyObject definition In-Reply-To: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> Message-ID: James Whetstone wrote: > I'm trying to access a PyObject directly from C++ for the purpose of calling > method on a Python object that is an intance of a derived C++ class. My > problem is that the compiler is complaining about not PyObject not being > defined. Has anyone run into the problem? Where is PyObject defined? Are you using Python's C API? Did you #include "Python.h" before using PyObject? PyObject is a C-style struct defined in object.h, which is in turn included by Python.h. Does your compiler know where to look for those headers? If you are getting messages of the form "error: cannot find Python.h," then add -Iyour_python_root/include/python2.5 (or whatever version) to the CXXFLAGS variable in your makefile, or to your compiler's command line. From Lie.1296 at gmail.com Sun Mar 16 14:04:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 11:04:59 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> <1befdccf-2efc-4640-bcf8-b4a792d8e646@i29g2000prf.googlegroups.com> Message-ID: <5782d52d-0f8c-42b8-9ccc-7445616e5717@u10g2000prn.googlegroups.com> On Mar 11, 4:15?am, John Machin wrote: > On Mar 11, 3:19 am, cokofree... at gmail.com wrote: > > > The trick in the case of when you do not want to guess, or the choices > > grow too much, is to ask the user to tell you in what format they want > > it and format according to their wishes. > > > Neatly avoids too much guessing and isn't much extra to add. > > The plot is about understanding input, not formatting output. And what he meant is simply to make an agreement with the user on how he/she would format his/her input and to disallow input from formats that haven't been agreed to avoid guessing. That is the cleanest and most polite solution, although I'd suspect it would be considered less user friendly by regular user although power user would be most happy with that. From mensanator at aol.com Wed Mar 5 16:27:36 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Mar 2008 13:27:36 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: On Mar 5, 2:25?pm, "Jeff.Goldfin... at gmail.com" wrote: > Hi All > > Is there a simple way to twiddle the bits of a float? In particular, I > would like to round my float to the n most significant bits. > > For example - 0.123 in binary is 0.000111111 > Rounding to 4 bits I get 0.0001. > > I can pack and unpack a float into a long > e.g. > struct.unpack('I',struct.pack('f',0.123))[0] > but then I'm not sure how to work with the resulting long. > > Any suggestions? Here's one. >>> import gmpy # create a base 10 float >>> f = gmpy.mpf('123.456') >>> f mpf('1.23456e2') # format in base 2, fixed point >>> f2 = gmpy.fdigits(f,2,0,0,99) >>> f2 '1111011.01110100101111000110101001111110111110011101101100100010111' # seperate the characteristic from the mantissa >>> fs = f2.split('.') # re-assemble with the mantissa truncated to desired # of bits >>> f3 = fs[0]+'.'+fs[1][:4] >>> f3 '1111011.0111' # convert the string back to a base 10 float >>> f4 = gmpy.mpf(f3,0,2) >>> print f4 123.4375 # check: print as base 2 and see how many digits are past radix point >>> print gmpy.fdigits(f4,2,0,0,99) 1111011.0111 From bj_666 at gmx.net Sat Mar 15 02:01:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 15 Mar 2008 06:01:52 GMT Subject: List mutation method gotcha - How well known? References: <210b2a22-a8e3-414e-9018-15f7d74c9f83@d4g2000prg.googlegroups.com> Message-ID: <64172eF29qj9jU1@mid.uni-berlin.de> On Fri, 14 Mar 2008 11:32:41 -0700, Lie wrote: > No, there is no need for "void" return type, what I meant is that > everything that's not said in the documentation should be assumed to > be an implementation detail, a method or a function that doesn't say > anything about its return type should be assumed to return an > implementation detail (which basically means: Don't rely on this). The > fact that list.append returns none is just a coincidence, you might > encounter another list.append that returns different thing some time > in the future, or the far future, or perhaps at the end of the > galaxy's life. I expect functions with no documentation of what they return to return `None`. Assuming they are documented at all, of course. :-) It's like not writing a ``return`` statement in the code: there's always an implicit ``return None`` at the end of every function. Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Sun Mar 9 17:12:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:12:28 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6d3lppl8lv2a@corp.supernews.com> Message-ID: On Mar 8, 7:51?pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 13:40:56 -0800, dave_mikesell wrote: > > On Mar 8, 2:27 pm, castiro... at gmail.com wrote: > > >> Good comments are better than bad names. Good names are better than bad > >> comments. > > > If you're taking the time to write good comments, why not just fix the > > bad names? ?The compiler/interpreter can never, ever catch bad comments. > > Yes, but the Python compiler can only catch bad names if you do this at > the top of every module: > > import semantic_analysis > import magic.crystal_ball.read_programmers_mind dir( magic )! dir( magic.crystal_ball )? From michael.wieher at gmail.com Wed Mar 5 11:11:44 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 5 Mar 2008 10:11:44 -0600 Subject: ActiveX in Webpage? Message-ID: Hello, I'm trying to design a python-based web-app from scratch, based on a standalone MFC application. Obviously I'll be wrapping a lot of C++ functionality in custom extensions, but is anyone aware of any documentation/techniques that could help me "drop" an ActiveX control into a webpage, and just use it? That, or, of course, a solid bit of writing detailing the idiosyncrasies of MFC-wrapped Py-Extensions would be useful as well. -Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffrey at fro.man Wed Mar 26 11:05:31 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 26 Mar 2008 08:05:31 -0700 Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> Message-ID: <13ukphrj8hng018@corp.supernews.com> skunkwerk wrote: > p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ > model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > print p.communicate()[0] > > i change to print p.communicate()[1] in case the output is blank the > first time > > this is the output: > *.htm renamed as model.html Without shell=True, your glob characters will not be expanded. Hence, the command looks for a file actually named "*.htm" > when I add shell=True to the subprocess command, I get the following > output: > Usage: rename [-v] [-n] [-f] perlexpr [filenames] Here the use of the shell may be confounding the arguments passed. Your command will probably work better if you avoid using shell=True. However, you will need to perform your own globbing: # Untested (no perl-rename here): command = ['rename','-vn', 's/(.*)\.htm$/model.html/'] files = glob.glob('*.htm') command.extend(files) p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) Jeffrey From aisaac at american.edu Sun Mar 2 13:06:32 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 02 Mar 2008 18:06:32 GMT Subject: tuples, index method, Python's design Message-ID: On April 12th, 2007 at 10:05 PM Alan Isaac wrote: > The avoidance of tuples, so carefully defended in other > terms, is often rooted (I claim) in habits formed from > need for list methods like ``index`` and ``count``. > Indeed, I predict that Python tuples will eventually have > these methods and that these same people will then defend > *that* status quo. - Issue #2025 : Add tuple.count() and tuple.index() methods to comply with the collections.Sequence API. Cheers, Alan Isaac From paul.hankin at gmail.com Sat Mar 8 18:55:29 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 8 Mar 2008 15:55:29 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> <876ecbb3-5bfe-40bd-a1ff-102af8d19fbc@n77g2000hse.googlegroups.com> Message-ID: On Mar 8, 10:42?pm, Carl Banks wrote: > On Mar 8, 9:43 am, malkarouri wrote: > > > Hi everyone, > > > I have an algorithm in which I need to use a loop over a queue on > > which I push values within the loop, sort of: > > > while not(q.empty()): > > ? ? x = q.get() > > ? ? #process x to get zero or more y's > > ? ? #for each y: > > ? ? q.put(y) > > Why not just do it like that? ?With a few changes it'll work fine: > > while q: > ? ? x = q.pop(0) > ? ? for y in process(x): > ? ? ? ? q.append(y) Or (almost) equivalently... while q: x = q.pop(0) q.extend(process(x)) -- Paul Hankin From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 03:35:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 07:35:58 -0000 Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <13umjiu5aa8585d@corp.supernews.com> On Wed, 26 Mar 2008 19:45:34 +0100, Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 19:04:44 schrieb David Anderson: >> HOw can we use express pointers as in C or python? > > There's no such thing as a pointer in Python, so you can't "express" > them either. Was this what you were trying to ask? But if you really need then, you can fake them: memory = [None]*10 # get a "pointer" to a memory location ptr = 5 # and assign a function there memory[ptr] = lambda s: '$' + s + '$' assert memory[ptr]('hello') == '$hello$' # store a pointer to a pointer memory[3] = ptr assert memory[memory[3]]('bye') == '$bye$' In Python this is a silly trick, not worth doing because there are better ways to solve problems that other languages use pointers for. But in older languages like Fortran, before they gained pointers, this was a standard method for getting pointers into a language without pointers. Thank goodness those days are long-gone! -- Steven From gigs at hi.t-com.hr Mon Mar 31 18:03:54 2008 From: gigs at hi.t-com.hr (gigs) Date: Tue, 01 Apr 2008 00:03:54 +0200 Subject: Question about overloading of binary operators In-Reply-To: References: Message-ID: Raj Bandyopadhyay wrote: > Hi > > Here's a simple class example I've defined > > ############################# > class myInt(int): > def __add__(self,other): > return 0 > > print 5 + myInt(4) #prints 9 > print myInt(4) + 5 #prints 0 > ############################# > > The Python binary operation function (binary_op1() in > Objects/abstract.c) states > the rules for binary operations as follows: > > v w Action > ------------------------------------------------------------------- > new new w.op(v,w)[*], v.op(v,w), w.op(v,w) > new old v.op(v,w), coerce(v,w), v.op(v,w) > old new w.op(v,w), coerce(v,w), v.op(v,w) > old old coerce(v,w), v.op(v,w) > > [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of > v->ob_type > > > It seems that my example should fall in case 1, and in both cases, the > __add__ function of the subclass should be used, returning 0, regardless > of operand order. However, in one case the subclass's function is used > and not in the other case. What am I missing here? > > Thanks > Raj > i think that you need to use __radd__ for addition with custom object on right From mensanator at aol.com Mon Mar 10 14:10:48 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 10 Mar 2008 11:10:48 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <2659c411-bc3a-4d4c-a2ce-4aafd680546b@e60g2000hsh.googlegroups.com> On Mar 10, 12:48?am, Gabriel Genellina wrote: > On 10 mar, 02:08, Nathan Pinno wrote: > > > How do I factor a number? If factoring is actually what you want, the sympy module can do it. >>> n = 85085**3 >>> print n 615969217989125 >>> import sympy >>> f = sympy.factorint(n) >>> f [(5, 3), (7, 3), (11, 3), (13, 3), (17, 3)] >>> ff = [[i[0]]*i[1] for i in f] >>> ff [[5, 5, 5], [7, 7, 7], [11, 11, 11], [13, 13, 13], [17, 17, 17]] >>> fff = sympy.flatten(ff) >>> fff [5, 5, 5, 7, 7, 7, 11, 11, 11, 13, 13, 13, 17, 17, 17] Provided that your needs are modest. It claims to be able to handle 10 digit factors, but it certainly can't handle numbers of this magnitude: 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 As it takes a couple hours of run-time only to crash with an out of memory error. If you need to handle something like that, you may want to get factor.exe which is part of the MIRACL library. The library is in C and doesn't have a Python interface, but you can run the .exe from Python and capture the output. Keep in mind two things: factor.exe doesn't have consistent output making it more difficult to interpret the captured output. I re-compiled my copy of factor.exe to provide consistent output. The other thing is that factor.exe sometimes gets confused claiming a number is composite that factor.exe is fully capable of factoring. Luckily this can be easily fixed in the Python program that calls it. In the following example, if factor!.exe (my re-compiled version) returns any composites, I simply feed them back into the program until all are factored or determinened to be truly intractable. Note the times. If you have serious factoring needs, the MIRACL solution is better than sympy. ## ======================================== ## Phase 1 ## ['COMPOSITE_FACTOR', '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749'] ## ## ['PRIME_FACTOR', '37'] ## ['PRIME_FACTOR', '43'] ## ['PRIME_FACTOR', '167'] ## ['COMPOSITE_FACTOR', '507787751'] ## ['PRIME_FACTOR', '69847'] ## ['PRIME_FACTOR', '30697'] ## ['PRIME_FACTOR', '89017'] ## ['PRIME_FACTOR', '3478697'] ## ['PRIME_FACTOR', '434593'] ## ['PRIME_FACTOR', '49998841'] ## ['PRIME_FACTOR', '161610704597143'] ## ['PRIME_FACTOR', '14064370273'] ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ['PRIME_FACTOR', '11927295803'] ## ## 0.860000133514 seconds ## ======================================== ## Phase 2 ## ['COMPOSITE_FACTOR', '507787751'] ## ## ['PRIME_FACTOR', '29819'] ## ['PRIME_FACTOR', '17029'] ## ## 0.0780000686646 seconds ## ======================================== ## Phase 3 ## ['COMPOSITE_FACTOR', '963039394703598565337297'] ## ## ['PRIME_FACTOR', '518069464441'] ## ['PRIME_FACTOR', '1858900129817'] ## ## 0.0469999313354 seconds ## ======================================== ## ## Factoring complete ## ## PRIME_FACTOR 37 ## PRIME_FACTOR 43 ## PRIME_FACTOR 167 ## PRIME_FACTOR 17029 ## PRIME_FACTOR 29819 ## PRIME_FACTOR 30697 ## PRIME_FACTOR 69847 ## PRIME_FACTOR 89017 ## PRIME_FACTOR 434593 ## PRIME_FACTOR 3478697 ## PRIME_FACTOR 49998841 ## PRIME_FACTOR 11927295803 ## PRIME_FACTOR 14064370273 ## PRIME_FACTOR 518069464441 ## PRIME_FACTOR 1858900129817 ## PRIME_FACTOR 161610704597143 ## ## ======================================== > I mean how do I translate x! into proper > > Python code, so that it will always do the correct math? > > Do you want to compute x! (factorial of x)? That is, you want a > program that given a 4, returns 24? > Think how would you compute it by hand and try to write the same thing > using Python instructions. > > If you come with a program and have a specific problem someone here > will be able to help you, but don't expect your homework to be done > for free... > > -- > Gabriel Genellina From randhol+valid_for_reply_from_news at pvv.org Sun Mar 2 11:19:07 2008 From: randhol+valid_for_reply_from_news at pvv.org (Preben Randhol) Date: Sun, 2 Mar 2008 17:19:07 +0100 Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> <20080302150856.e2b720e9.randhol+valid_for_reply_from_news@pvv.org> <22b51bec-8dae-4efb-8b91-b386a0e5d9f2@v3g2000hsc.googlegroups.com> Message-ID: <20080302171907.ffa19838.randhol+valid_for_reply_from_news@pvv.org> On Sun, 2 Mar 2008 08:09:24 -0800 (PST) castironpi at gmail.com wrote: > On Mar 2, 8:15?am, Giles Brown wrote: > > http://docs.python.org/lib/typeiter.html > > Be careful on your descision to return an ordered iterator or not-- > that is, whether it iterates over the dictionary or the list (if I > understand you correctly). If the order's unimportant then please > disregard. I was thinking to iterate over the list which contains the uniq_ids as order is important :-) Thanks! Preben From ptmcg at austin.rr.com Wed Mar 5 16:12:43 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 5 Mar 2008 13:12:43 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> Message-ID: <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> On Mar 5, 2:04?pm, castiro... at gmail.com wrote: > On Mar 5, 1:29?pm, Paul McGuire wrote: > > > On Mar 5, 12:50?pm, castiro... at gmail.com wrote: > > > > What is a class that is not a module? > > > Please stop posting these one-liner beginner questions. ?If you can > > type it in one line, you can enter it on the Google.com or Ask.com > > query page and get a wealth of *existing* information, from tutorials, > > documentation, online presentations. ?If you are able to phrase such a > > question, you are capable of doing a little research and > > experimentation on your own. > > > These posts translate to "I'm too lazy to use Google, or too cheap to > > buy a Python book, or too lazy to read it, or too impatient to do my > > own experimenting - much better to just post on c.l.py and have the > > answer spoon-fed to me!" > > > I refuse to spoon feed you the answer to this question when plenty of > > supporting material is already available. > > In the future, shall I assume that other readers here have no ideas > (on this, read *ever*), that haven't already been published? ?'Cause I > have. > > For instance, in this example, I've tried a few approaches that didn't > turn out well. > Fair game. Capture one of these classes (or better, distill it down to a *small* example demonstrating the problem), tell us what you are trying to achieve, post it, AND tell us what is "not turning out well." (Your previous posts have done a poor job in providing one or more of these elements.) > Do you want a comparison of existing solutions? ?Do you have a proof > that they exhaust the solution space? > *I* don't want *any* such thing, especially on the topics of "what is a class?" and "how is a class different from a module?", nor do I need proof that the basic background info on this topic covers the mainstream applications of classes and modules. These are basic OO concepts in Python. Try googling "python object-oriented". And if there were some esoteric aspect of "what is a class?" that you want to pursue that might not be covered in the available material, I would expect one to include that in the original post. > I'm willing to address convention, in serial or parallel--- (change > subject to 'what goes on newsgroups'?), but it's not clear from fact > what assumption who has made. > Since you did not elaborate on what your efforts were and the extent they were undesirable (certainly useful info from someone honestly interested in a helpful answer), I assumed you had made none. > Next time, why don't you say, "How much experience do you have?", or > "What level should I gear my answer toward?" > I put the onus on the poster to realize that the question they are asking is in fact a basic concept, *especially* when the subject of the question is captured in a built-in method, type, class, or keyword. Surely you are aware that Python has been around for a number of years, and that in all that time, it is entirely likely that the topic of "what is a class?" has been covered, in any number of the tutorials and docs so charitably written by many of the contributors in this newsgroup. Please stop asking those people to further expend their time repeating this work just for your benefit. It is like arriving late to a meeting, and asking everyone to stop and bring you up to speed on what you missed, in effect saying, "My time is more valuable than yours, I can't be bothered to arrive on time, or do even the simplest research for myself." -- Paul From pedro.santa at gmail.com Thu Mar 20 13:47:56 2008 From: pedro.santa at gmail.com (Pedro Machado Santa) Date: Thu, 20 Mar 2008 10:47:56 -0700 (PDT) Subject: Import a file to namespace References: <0cdb3c90-e961-4982-9996-de3ac02706bc@13g2000hsb.googlegroups.com> <13u57f51c3ee82e@corp.supernews.com> Message-ID: <45b0b2fc-daa8-49b9-8f80-4eac40f6c35f@q78g2000hsh.googlegroups.com> On Mar 20, 5:24 pm, Jeffrey Froman wrote: > This method should work fine. Modules are effectively singletons, so running > this code one time anywhere in your application will cause the changes to > appear in all references to the original module. Yhea. I got it now. :) It already works. I wasn't putting the module on my working dir. (I created the module testpackageaddon.py and I did the "override" on it, then imported it after the import testpackage on my working script.) Thanks. Pedro Machado Santa From fetchinson at googlemail.com Mon Mar 10 21:06:14 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 18:06:14 -0700 Subject: image matching algorithms In-Reply-To: <47D5D64A.8030300@ncee.net> References: <47D5D64A.8030300@ncee.net> Message-ID: > >>> There are a number of free tools for image matching but it's not very > >>> easy to decipher the actual algorithm from the code that includes db > >>> management, GUI, etc, etc. I have my own image database and GUI so all > >>> I need is the actual algorithm preferably in pseudo code and not in > >>> the form of a research paper (from which I also found a lot but since > >>> I'm not that much interested in the actual science of image > >>> recognition this seems like an over kill). > >>> > >> I'd recommend SIFT. There's quite a bit of information on SIFT. In most > >> cases, they don't cover the background science too much, but are still > >> heavy on the math. Pseudo code is hard to come by since it will take > >> many lines of pseudo code just to express one concise mathematical > >> equation. There are however many links to implementations in various > >> languages on the Wikipedia page. > >> > >> http://en.wikipedia.org/wiki/Scale-invariant_feature_transform > >> > >> I have had good experiences with SIFT for feature extraction from images > >> (I have used it for panorama stitching and robot mapping). It's > >> insensitive to scale and rotation. Note that it is a patented algorithm > >> and this may (or may not) pose a problem for you. > >> > > > > Thanks for the info! SIFT really looks like a heavy weight solution, > > but do you think the whole concept can be simplified if all I needed > > was: given a photo, find similar ones? I mean SIFT first detects > > objects on the image and find similarities, but I don't need the > > detection part at all, all I care about is similarity for the whole > > photo. I surely don't understand the big picture fully but just have > > the general feeling that SIFT and other expert tools are an overkill > > for me and a simplified version would be just as good with a much more > > easily comprehensible core algorithm. > > > > Or am I being too optimistic and there is no way out of going into the > details? > > > > > Using the histogram of the picture may be good enough for your > application. Here's something I put together for comparing images (for > purposes of detecting motion) taken by the built-in web cam in my > Macbook Pro. This might be good enough if you play with the threshold. > > > """ > I'm writing a simple little app for doing motion detection with data > output from wacaw, a package for MacOSX. You could easily modify this > script to get data output from some other source. Thanks Shane, this is simple enough indeed, which is great. I'll give this a try and maybe it'll be good enough for me. From grante at visi.com Wed Mar 5 15:48:53 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 05 Mar 2008 20:48:53 -0000 Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <13su15t266dimc2@corp.supernews.com> Message-ID: <13su1pl8tnq5o6a@corp.supernews.com> On 2008-03-05, Grant Edwards wrote: > On 2008-03-05, Jeff.Goldfinkle at gmail.com wrote: >> Any suggestions? > > Just use the bitwise and/or/not operators: & | ~ Oh, I forgot to mention the shift operators << and >> -- Grant Edwards grante Yow! All of life is a blur at of Republicans and meat! visi.com From gherron at islandtraining.com Thu Mar 27 18:27:57 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Mar 2008 15:27:57 -0700 Subject: Problems wit List Object In-Reply-To: <5dc598e30803271519k39440eccj3b9db110f9097b98@mail.gmail.com> References: <5dc598e30803271519k39440eccj3b9db110f9097b98@mail.gmail.com> Message-ID: <47EC1F6D.7090908@islandtraining.com> David Anderson wrote: > Hello all, I have a Class1 that there has a list, and a function that > returns this list, In another class I got an instance of this first > class, and when I make: > > obj1 = Class1() > list = obj1.getList() > > I got this exception: > > traceback (most recent call last): > File "xxx", line 184, in onAddErro > list = self.errorMgr.getList() > TypeError: 'list' object is not callable > > How can I solve it? This error implies that getList is a list, *not* a function which returns a list. If that's not enough explanation for you, you'll have to provide some code for us to look at. Gary Herron From skip at pobox.com Thu Mar 27 11:10:17 2008 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Mar 2008 15:10:17 +0000 (UTC) Subject: Is subprocess.Popen completely broken? References: Message-ID: > > >>> proc = subprocess.Popen ("ls /tmp") > > proc = subprocess.Popen ("ls /tmp", shell=True) > > or > > proc = subprocess.Popen (["ls", "/tmp"]) > > should work. Why should I need to set shell=True? I'm not globbing anything. The second case still fails: >>> proc = subprocess.Popen (["/usr/bin/ls" "/tmp"]) Traceback (most recent call last): File "", line 1, in ? File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 542, in __init__ errread, errwrite) File "/opt/app/g++lib6/python-2.4/lib/python2.4/subprocess.py", line 975, in _execute_child raise child_exception OSError: [Errno 20] Not a directory Thx, Skip From web1986 at gmail.com Sat Mar 15 16:25:28 2008 From: web1986 at gmail.com (4ever) Date: Sat, 15 Mar 2008 13:25:28 -0700 (PDT) Subject: .:Www.4Down.Info:. for all your needs Message-ID: .:Www.4Down.Info:. for all your needs http://4down.info/ Free CMS,Templates,Movies,Scripts,SEo tools,Adsense Tools,Applications,MP3..and much more http://4down.info/ Free cPanel Web Hosting with PHP5/Mysql - no advertising! http://4down.info/news/1207-free-cpanel-web-hosting-with-php5mysql.html Hidden Expedition: Everest http://4down.info/games/1270-hidden-expedition-everest.html Eminem - TBA (2008) http://4down.info/music/1269-eminem-tba-2008.html Eminem- Psycho Killer DVD (2008) http://4down.info/music/1267-eminem-psycho-killer-dvd-2008.html Stargate - The Art Of The Truth (2008) http://4down.info/movies/1261-stargate-the-art-of-the-truth-2008.html Adobe Photoshop CS4 http://4down.info/applications/1258-adobe-photoshop-cs4.html Robin Hood: The Legend of Sherwood (ISO) http://4down.info/games/1253-robin-hood-the-legend-of-sherwood-iso.html Jumper (2008) http://4down.info/movies/1252-jumper-2008.html From terry at jon.es Fri Mar 28 10:54:36 2008 From: terry at jon.es (Terry Jones) Date: Fri, 28 Mar 2008 15:54:36 +0100 Subject: Global variables in modules... In-Reply-To: Your message at 15:13:15 on Friday, 28 March 2008 References: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> Message-ID: <18413.1708.63299.691860@jon.es> >>>>> "Peter" == Peter Otten <__peter__ at web.de> writes: Peter> ttsiodras at gmail.com wrote: [snip] >> ...can someone explain why invoking a.py prints 0? >> I would have thought that the global variable 'g' of module 'a' would >> be set to 1... Peter> When you run a.py as a script it is put into the sys.modules module Peter> cache under the key "__main__" instead of "a". Thus, when you import Peter> a the cache lookup fails and a.py is executed again. You end up with Peter> two distinct copies of the script and its globals [snip] Suggesting the following horribleness in a.py g = 0 def main(): global g import b g = 1 b.callb() if __name__ == "__main__": import sys, __main__ sys.modules['a'] = __main__ main() Terry From bruno.desthuilliers at gmail.com Mon Mar 31 15:36:13 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 31 Mar 2008 12:36:13 -0700 (PDT) Subject: Looking for indent advice howto in emacs python-mode References: Message-ID: <440c7af6-deaf-4180-afa8-91d9a3f359f3@e10g2000prf.googlegroups.com> On 31 mar, 18:32, "Steven W. Orr" wrote: > Here's what I want to do: > > if ( ( v == 1 ) > or ( v == 2 ) > or ( v == 3 ) ): > pass Why the parens ? if a == 1 \ or b == 2 \ or c == 3: pass From Robert.Bossy at jouy.inra.fr Tue Mar 4 12:36:02 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Tue, 04 Mar 2008 18:36:02 +0100 Subject: why not bisect options? In-Reply-To: References: Message-ID: <47CD8882.3020009@jouy.inra.fr> Aaron Watters wrote: > On Feb 29, 9:31 am, Robert Bossy wrote: > >> Hi all, >> >> I thought it would be useful if insort and consorts* could accept the >> same options than list.sort, especially key and cmp..... >> > > Wouldn't this make them slower and less space efficient? It would > be fine to add something like this as an additional elaboration, but > I want bisect to scream as fast as possible in the default streamlined > usage. Yes it is slower and bigger, so I agree that the canonical implementation for default values should be kept. Also because the original bisect functions are actually written in C, the speed difference is even more noticeable. Though, I needed custom ordering bisects since I was implementing interval trees (storing intervals by startpoint/endpoint). Cheers, RB From micah at cowan.name Sat Mar 8 20:27:16 2008 From: micah at cowan.name (Micah Cowan) Date: Sun, 09 Mar 2008 01:27:16 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> Message-ID: <87zlt8d6vj.fsf@micah.cowan.name> dave_mikesell at fastmail.fm writes: > On Mar 8, 2:38 am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote: >> >> x = get_stuff(store) # Get the stuff what was brought at the store. >> >> > Perfect example of an unnecessary comment. The variable and function >> > names are commentary enough. >> >> "x" is a terrible name. What does it mean? Nothing. > > Right, that's a problem with the code. A comment only masks the bad > smell. 'x' should be renamed to something meaningful, obviating the > need for comments to follow it around. > >> There's only three places x is an appropriate name: > >> (1) A meta-syntactic variable like foo, bar, spam, ham, parrot. >> >> (2) Library functions, where x stands for a generic argument, usually a >> number, e.g. def sin(x). >> >> (3) Throw-away code you don't need to maintain. > > I use single letter variables where their scope is very small. e.g., > tight loops, small functions, etc. I even use them as class members > where they make sense in the domain. x, y, z for 3d vectors, r, g, b, > a for colors, etc. This was a two-line code sample. Since you've indicated you use such names where their scope is small, it's rather hard to say, without more information, whether using "x" for this code generats a "smell" or not. For that small amount of code, I'd say it doesn't. I find that long names in short code segments actually detract from readability. In the very first section of their book "The Practice of Programming", Kernighan and Pike recommend using "descriptive names for globals, short names for locals," saying "within a function, may be sufficient, is fine, and is overkill." As you point out, even for non-super-small scopes, such as class members, it can make more sense to use single-letter names; I'd consider red, green, blue and alpha to be unnecessary names, and it's hard to improve on the x, y and z you gave as an example. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From catelkak at gmail.com Tue Mar 11 06:55:00 2008 From: catelkak at gmail.com (online money) Date: Tue, 11 Mar 2008 03:55:00 -0700 (PDT) Subject: how to increase the system speed....to improve the proceesssor speed..... Message-ID: <7fbbdbf9-b0e5-4507-9d43-b4f4fd43f7e0@s13g2000prd.googlegroups.com> how to increase the system speed....to improve the proceesssor speed..... http://intelspentium.googlepages.com From python.list at tim.thechases.com Fri Mar 7 16:04:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Mar 2008 15:04:51 -0600 Subject: I cannot evaluate this statement... In-Reply-To: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> References: <753de997-76c5-4540-96ef-99e209ff111a@e25g2000prg.googlegroups.com> Message-ID: <47D1ADF3.6080607@tim.thechases.com> > import os, sys > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python' > > Okay, run on a win32 machine, pyfile evaluates to python.exe [snip] > Now. Run this on linux. The first condition evaluates sys.platform[:3] > == 'win' as false. [snip] > Where am I going wrong. And when will this statment make pyfile > evaluate to 'python' ? Your reasoning is correct. I'm guessing you're typing something wrong? Or typing the right thing in the wrong window (so that the command is run on a Windows box)? Or perhaps you're running on some weird build of Python? It does indeed work on my Debian box: tim at rubbish:~$ uname -a Linux rubbish 2.6.22-2-686 #1 SMP Fri Aug 31 00:24:01 UTC 2007 i686 GNU/Linux tim at rubbish:~$ python Python 2.4.4 (#2, Jan 3 2008, 13:36:28) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.platform 'linux2' >>> sys.platform[:3]=="win" and "python.exe" or "python" 'python' >>> (sys.platform[:3]=="win" and "python.exe") or "python" 'python' Whereas on my Windows machine: c:\> python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.platform 'win32' >>> sys.platform[:3] == "win" and "python.exe" or "python" 'python.exe' That's both with and without the parens. Same happens in assignments. -tkc From menosaint at gmail.com Thu Mar 13 18:33:04 2008 From: menosaint at gmail.com (menosaint at gmail.com) Date: Thu, 13 Mar 2008 15:33:04 -0700 (PDT) Subject: newbie question structure of function Message-ID: <57bc78cd-2744-465a-aa32-7143343e3b84@i12g2000prf.googlegroups.com> hi I am new to python programming..I would like to call a function that returns an integer value and a filename string as a tuple.I coded it like this below...I want to know if this can be coded more compactly and efficiently..(i am from java background and thus code often becomes bulky ..) def mycallerfunction(): matchvalue,matchfilename=findmatchingfile() if not matchfilename: print "no match found" dosomething() else: print "match found:",matchfilename,"with matching distance:",matchvalue dosomethingelse() def findmatchingfile(): # calculate matchdistance and matchfilename and return as tuple # if matchdistance found is not within a threshold then filename # may be "" (an empty string) ... ... resultname=""" matchdistance,index=dosomecalculations() if (matchdistance < threshold): resultname=filenameslist[index] return (matchdistance,resultname) if you can give some advice/suggestions it wd be great thankx -vincent From castironpi at gmail.com Fri Mar 28 14:49:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 11:49:59 -0700 (PDT) Subject: Dynamic code problem References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> <8c7f10c60803280314q320884e8k9993592d688fec83@mail.gmail.com> Message-ID: On Mar 28, 8:41?am, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 07:14:17 -0300, Simon Brunning ? > escribi?: > > > On Thu, Mar 27, 2008 at 4:13 PM, ? wrote: > >> My dynamic code failed at this site http://****/, need > >> ?some help thank you. > > > > > I assumed it was just spam, not a question. To be or not to be, not a question? From kaantuna at gmail.com Mon Mar 17 09:30:11 2008 From: kaantuna at gmail.com (Kaan Tuna) Date: Mon, 17 Mar 2008 15:30:11 +0200 Subject: Entry point not found error Message-ID: <9a7827a80803170630g492ff102m162f362bf81a538c@mail.gmail.com> Hi, I am using cygwin on a Windows Xp machine. I used to have python2.3 working without problems, but when i install v2.5.1 via cygwin setup, python.exe and python2.5.exe are giving "Entry point not found - Exception processing message - Parameters 18ef...." error box, while python2.3.exe still runs normally. My librairies are in cygwin/lib folder. Do you have any idea to solve this problem? Thanks in advance. Kaan -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Thu Mar 6 21:25:15 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 6 Mar 2008 18:25:15 -0800 (PST) Subject: Flash interface for a python program References: Message-ID: On 7 Mrz., 01:46, icarus wrote: > Is it possible to call an external python program, through a Flash > interface? > > Meaning, I create a Flash window with a button. When I press that > button, it automagically invokes the external python program. Is that > possible? Any books/online tutorials you can recommend > me? > > I guess I'm looking for alternatives in the area of GUI development. You might look at PyAMF for data-bindings. http://pyamf.org/ An alternative is mentioned in the Flex/Python articles by Bruce Eckel. http://www.artima.com/weblogs/viewpost.jsp?thread=208528 From dickinsm at gmail.com Fri Mar 14 12:08:36 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 14 Mar 2008 09:08:36 -0700 (PDT) Subject: urllib proxy support confusion References: <13td9mobtoadgc2@corp.supernews.com> Message-ID: <12cbbfc3-bd19-4895-b47a-2432ddc9a803@c33g2000hsd.googlegroups.com> On Mar 11, 11:35?am, Grant Edwards wrote: > Reading through the doc athttp://docs.python.org/lib/module-urllib.html, > there are several paragraphs (including code examples) showing > how you specify what proxies to use when calling urlopen(): See http://bugs.python.org/issue2288 From jeff at schwabcenter.com Sun Mar 2 18:21:31 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 02 Mar 2008 15:21:31 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <7xzltgrbyi.fsf@ruckus.brouhaha.com> References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <7xzltgrbyi.fsf@ruckus.brouhaha.com> Message-ID: <5MSdnajOndDRq1banZ2dnUVZ_oSunZ2d@comcast.com> Paul Rubin wrote: > Jeff Schwab writes: >> Better yet, how hard would it be to define an otherwise int-like type >> that did not define a non-flooring division operator? Are there any >> real use cases for such a type? > > User defined types in python are fairly heavyweight compared with the > built-in types, Yet they continue to form the basis of almost all non-trivial Python programs. Anyway, it's a bit soon to be optimizing. :) > and a type like that is just another thing for the > user to have to remember. How so? A well-written function generally shouldn't depending on the exact types of its arguments, anyway. If someone has written a function to find (e.g.) the median of a collection of numbers, their code should already be prepared to accept values of user-defined numeric types. If I want to call such a function with my hand-rolled DivisionSafeInteger type, it should just work, unless specifically documented to work only with a particular subset of Python data types. > The C library has a bunch of different types like off_t (offset in a off_t is vendor-specific extension, not part of the standard C library. In gcc, it's a typedef for __off_t, which is a macro for _G_off_t, which is in turn a macro for a compiler-specific type called _IO_off_t. Elsewhere, it may just be a typedef of long int. > file) and size_t, so if you pass an off_t to a function that expects a > size_t as that arg, the compiler notices the error. On what compiler? I've never seen a C compiler that would mind any kind of calculation involving two native, unsigned types. $ cat main.c #include int main() { off_t ot = 0; long li = 3L; ot = li; } $ make cc -ansi -pedantic -Wall -std=c99 main.c -o main $ > But they are > really just integers and they compile with no runtime overhead. They do indeed have run-time overhead, as opposed to (e.g.) meta-types whose operations are performed at compile-time. If you mean they have less overhead than types whose operations perform run-time checks, then yes, of course that's true. You specifically stated (then snipped) that you "would be happier if int/int always threw an error." The beauty of a language with such extensive support for user-defined types that can be used like built-in type is that you are free to define types that meet your needs. The weight of such hand-rolled solutions may lead to performance problems at first, but C-linkable extensions go a long way to help; hence numpy et al. > So, I think Python won't easily support lots of different types of > integers, and we've got what we've got. My understanding is that Python will easily support lots of different types of just about anything. That's the point. In theory at least, it supports programming in a way that lets the translator (compiler + interpreter) keep track of the exact types being used, so that the programmer doesn't have to. The fact that the tracking is done dynamically, rather than statically, is a fundamental design decision that was made early in the language's development. > There's an interesting talk linked from LTU about future languages: > > http://lambda-the-ultimate.org/node/1277 Thanks, but that just seems to have links to the slides. Is there a written article, or a video of Mr. Sweeney's talk? From gagsl-py2 at yahoo.com.ar Tue Mar 25 20:33:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 21:33:52 -0300 Subject: embedded python pythonpath References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> Message-ID: En Tue, 25 Mar 2008 20:38:39 -0300, Furkan Kuru escribi?: > Actually, I do not want any .py or .pyc files around my executable. > (including userdict, sys, site etc) > I want to have just single zip file for all python files. Putting all of them into pythonNN.zip (NN depending on the Python version in use) should be enough, but I've never tried it. > I had a look at py2exe source codes but could not figure out how it just > looks into a zip file. Standard Python already supports having zip files in sys.path (using the builtin zipimport module), you don't have to do anything special to enable that (apart from building with the required dependencies, like zlib, of course) > So maybe I have to compile the svn version of python. After renaming the directory where Python 2.5 were installed, my test25.exe program (the one compiled using Python 2.5.1) worked fine. So it looks like it is something with how the "python home" is searched. Anyway, as I said earlier, you don't have to play with PYTHONPATH; just add any required directory to sys.path at runtime. -- Gabriel Genellina From afandimscit at gmail.com Fri Mar 28 17:05:29 2008 From: afandimscit at gmail.com (afandi) Date: Fri, 28 Mar 2008 14:05:29 -0700 (PDT) Subject: How to insert multiple rows in SQLite Dbase Message-ID: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> Hi, Generally, it involves SQL statement such as follow INSERT INTO (field1,field2,.......fieldn) VALUES ('abc','def'...........) If I have data taken from Apache Server Log,let say 100 lines which is printed output of 8 fields such as: data 1 IP: 61.5.65.101 Date: 26/Sep/2007 Time: 20:43:25 GMT: +0900 Requestt: GET /index.php?option=com_content&task=view&id=55&Itemid=19 HTTP/1.1 ErrorCode: 200 Bytes: 6458 Referel:http://www.joomla.org/index.php? option=com_content&task=view&id=35&Itemid=19 Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 data 2 IP: 21.5.65.101 Date: 26/Sep/2007 Time: 20:43:25 GMT: +0900 Requestt: GET /index.php?option=com_content&task=view&id=55&Itemid=19 HTTP/1.1 ErrorCode: 200 Bytes: 6458 Referel:http://www.joomla.org/index.php? option=com_content&task=view&id=35&Itemid=19 Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4 . . . . until the 100 data How toI insert into SQLite database? by using SQL statement.TQ From piet at cs.uu.nl Tue Mar 11 06:31:27 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 11 Mar 2008 11:31:27 +0100 Subject: execute python script question References: <47D575E9.8040507@mydeskfriend.com> Message-ID: >>>>> Gabriel Rossetti (GR) wrote: >GR> not a stupid question, I think that may be it. I tried setting PYTHONPATH >GR> like Sam suggested and it worked, but I was unable to do it programmically. >GR> I tried putting it in the __init__.py file like a web post suggested but it >GR> wasn't run until after I set PYTHONPATH, and once that was done there is no >GR> need (that I can see anyways) to set it in __init__.py. The __init__.py is executed during your import statement, thus it is too late to find MyPackage. You will have to change the sys.path before the import, e.g. in your main program. Or do what is usually done: put MyPackage in the site-packages directory. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From stef.mientki at gmail.com Fri Mar 28 17:48:05 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 22:48:05 +0100 Subject: Class or dictionary ? (was: class or inherited list ?) In-Reply-To: <47ED0BA1.9020103@gmail.com> References: <47ED0BA1.9020103@gmail.com> Message-ID: <47ED6795.9090308@gmail.com> Sorry, although the code example was correct, the question was wrong. Stef Mientki Stef Mientki wrote: > hello, > > Passing all kinds of data between objects, > I'm looking for an elegant (and simple) way to pack the data. > Now it looks to me that both the class and the inherited list, > performs equally well. > Till now, the most elegant way (in my view) is the list inheritance, > mainly because you don't need brackets and no quotes. > What are others opinion about this ? > > thanks, > Stef Mientki > > class super_list(list): > pass > > def kwadraat ( value ) : > return value * value > > x={} > x['frequency']=33 > x['functie']=kwadraat > print x['functie'](2) > > y = super_list() > y.frequency = 33 > y.functie = kwadraat > print y.functie(3) > > > From jgardner at jonathangardner.net Fri Mar 7 19:31:08 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 7 Mar 2008 16:31:08 -0800 (PST) Subject: Edit and continue for debugging? References: Message-ID: <4efecf9f-6947-440c-bf9c-c9d2ac44ff21@s8g2000prg.googlegroups.com> This is an interesting issue because we who write web applications face the same problem. Except in the web world, the application state is stored in the browser so we don't have to work our way back to where we were. We just keep our url, cookies, and request parameters handy. Before I go on, I would suggest one thing: unit tests. If you have a hard time writing unit tests, then you need to rethink your code so that you can write unit tests. Having unit tests, running them, and debugging them is a far easier way to catch bugs and prevent them from coming back. If you don't know what a "regression test" is, you should look into the field of software testing. You'll thank yourself for it. I'm no lisp programmer, but my understanding of how lisp and lisp-like programs do this is that they replace the function with the new version. What this does to threads that are already running the function, I guess they just finish and continue on. What about closures? Well, you're out of luck there. I guess lisp programmers don't use closures in that way too often. I guess you could do the same in your debug session, although it would be hacky and difficult at best. You're out of luck if there's more than a handful of things referring to the object. A better solution would probably be to fix the offending line in the offending file and somehow magically reload that file. Well, you still have the same problem. See, a lot of your program depends on the functions and classes and objects already in that file. Those dependencies don't get magically fixed to point to the new objects just loaded. You'll have to go throughout the entire universe of variables and make them point to the new stuff. This is not an easy feat to do. In the end, you're going to realize that unless you design the system to allow you to "reload" files, whatever that means (and you'll have to define that as well), you aren't going to be able to do that. There just isn't a straightforwad, one-size-fits-all solution to this problem, except for stopping the process altogether and restarting from scratch. On Mar 7, 6:44 am, "Bronner, Gregory" wrote: > I haven't seen much on this for a few years: > > I'm working on a GUI application that has lots of callbacks. Testing it > is very slow and quite boring, as every time I find an error, I have to > exit it, restart it, and repeat the series of clicks. It would be really > amazing if python supported a reasonable form of edit and continue. > > Is there any way to do this? I'd like to be able to change my code and > have it apply to a running instance of a class. I wonder if it would be > possible to do this by configuring the interpreter to parse classes and > functions rather than whole modules, and to re-parse as necessary; also > to have byte-compiled modules be singletons rather than be standard > reference counted objects. From tmp1 at viltersten.com Mon Mar 10 15:12:25 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Mon, 10 Mar 2008 20:12:25 +0100 Subject: SV: Adjust a canvas as the window is resized In-Reply-To: References: <63ga4fF27edonU1@mid.individual.net> Message-ID: <63leibF26ab65U1@mid.individual.net> >> Do i need to set a callback to a canvas >> in order to "listen" to the root window >> being resized in order to make it adjust >> its contents? >> >> If so, how? If not, how do i make the >> canvas draw a line from one corner to >> an other? > > import Tkinter as tk > > root = tk.Tk() > canvas = tk.Canvas(root) > canvas.pack(expand=True, fill=tk.BOTH) > line = canvas.create_line(0, 0, 0, 0) > > def resize(event): > canvas.coords(line, 0, 0, event.width, event.height) > canvas.bind("", resize) > > root.mainloop() Super nice! Thanks a million! -- -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From zzvladimir at gmail.com Thu Mar 6 04:36:58 2008 From: zzvladimir at gmail.com (Vladimir Kropylev) Date: Thu, 6 Mar 2008 12:36:58 +0300 Subject: generateDS problem: __init__ of base class is not called (processing linked xsd files) Message-ID: Hi, Is it possible to have __init__ of superclass called when superclass and subclass are defined in different XSD files? There's no problem when super and subclass are defined within single XSD file. In another words, can generateDS correctly process schema, described in a set of linked xsd files? Thanks. From sweet.trixie4u at gmail.com Thu Mar 6 14:39:35 2008 From: sweet.trixie4u at gmail.com (sweet.trixie4u at gmail.com) Date: Thu, 6 Mar 2008 11:39:35 -0800 (PST) Subject: RENT ADULT DVDs by MAIL - JUST LIKE NETFLIX: GET 15 DAYS FOR FREE...TRY IT NOW! Message-ID: Try It Now For FREE! http://in.urentdvds.com/c/dvdIn.cgi/3/1280876/G Choose your Porn online and it's delivered quickly and discreetly by Mail. Keep it as long as you want, then send it back when you're done. Free shipping both ways. http://in.urentdvds.com/c/dvdIn.cgi/3/1280876/G TRY IT FREE! Choose your favorite type of movies: Hardcore Action Movies http://in.urentdvds.com/c/dvdIn.cgi/32/1280876/G Movies Starring Chicks with Big Boobs http://in.urentdvds.com/c/dvdIn.cgi/31/1280876/G Porn Stars http://in.urentdvds.com/c/dvdIn.cgi/26/1280876/G Anal Movies http://in.urentdvds.com/c/dvdIn.cgi/27/1280876/G Girl on Girl Action Movies http://in.urentdvds.com/c/dvdIn.cgi/37/1280876/G Butt Shots http://in.urentdvds.com/c/dvdIn.cgi/32/1280876/G Beautiful Black Women http://in.urentdvds.com/c/dvdIn.cgi/30/1280876/G Hot Latina Women http://in.urentdvds.com/c/dvdIn.cgi/36/1280876/G Interracial Couples http://in.urentdvds.com/c/dvdIn.cgi/14/1280876/G Blow Jobs http://in.urentdvds.com/c/dvdIn.cgi/13/1280876/G Double Penetration http://in.urentdvds.com/c/dvdIn.cgi/33/1280876/G Teens http://in.urentdvds.com/c/dvdIn.cgi/41/1280876/G Three Ways http://in.urentdvds.com/c/dvdIn.cgi/42/1280876/G Tranny Movies/Chicks with Dicks http://in.urentdvds.com/c/dvdIn.cgi/25/1280876/T Gay Movies http://in.urentdvds.com/c/dvdIn.cgi/35/1280876/H From roygeorget at gmail.com Tue Mar 11 01:21:48 2008 From: roygeorget at gmail.com (royG) Date: Mon, 10 Mar 2008 22:21:48 -0700 (PDT) Subject: parsing directory for certain filetypes References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <0baa2e91-3894-49cd-94ba-0d3dc1b86f03@h11g2000prf.googlegroups.com> On Mar 10, 8:03 pm, Tim Chase wrote: > In Python2.5 (or 2.4 if you implement the any() function, ripped > from the docs[1]), this could be rewritten to be a little more > flexible...something like this (untested): > that was quite a good lesson for a beginner like me.. thanks guys in the version using glob() >path = os.path.normpath(os.path.join(folder, '*.txt')) >lst = glob.glob(path) is it possible to check for more than one file extension? here i will have to create two path variables like path1 = os.path.normpath(os.path.join(folder, '*.txt')) path2 = os.path.normpath(os.path.join(folder, '*.doc')) and then use glob separately.. or is there another way? RG From jimtruck at gmail.com Wed Mar 26 00:30:43 2008 From: jimtruck at gmail.com (jimtruck at gmail.com) Date: Tue, 25 Mar 2008 21:30:43 -0700 (PDT) Subject: 4GB USB flash drives for only $14.49 Message-ID: <3b3fb5d0-ee10-436a-9844-b3895fa0d9b9@59g2000hsb.googlegroups.com> Hi guys, www.dealsusb.com has 4GB USB flash drives for only $14.49 Free Shipping with warranty Jimmy From mail at timgolden.me.uk Thu Mar 27 11:21:47 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Mar 2008 15:21:47 +0000 Subject: Checking processes running under Windows In-Reply-To: References: Message-ID: <47EBBB8B.3060509@timgolden.me.uk> Jo?o Rodrigues wrote: > Hello all! I'm trying to write a script that needs to check which processes > are running under Windows (XP Pro, Home, whatever). The method I'm using is: > >>>> process_list = os.popen('TASKLIST').read() > > However, XP Home doesn't have the tasklist.exe tool so, this is kind of > useless in that OS. Do you have any other methods I can use for this? You can do this with WMI: http://timgolden.me.uk/python/wmi_cookbook.html#running_processes TJG From mail2spj at yahoo.com Mon Mar 24 17:13:54 2008 From: mail2spj at yahoo.com (SPJ) Date: Mon, 24 Mar 2008 14:13:54 -0700 (PDT) Subject: FW:Reading new mail from outlook express using Python Message-ID: <835075.68341.qm@web50102.mail.re2.yahoo.com> My previous post was not clear, hence resending this. ------------------------- Hi, I am trying to create new tickets in the ticketing system using python. When I receive new email from a particular address, I have to trigger the python script and parse the mail in required format. The main hurdle here is, how to invoke the script on arrival of new mail? I checked the outlook settings and found that it supports only microsoft VB script and Jscript. Is there any other way? I mean, if I make a daemon, how will it be notified of new mail? Is there any python module that does this? I am not sure if this is the right place to ask this, since it is also a microsoft related question. But any help is appreciated. Thanks, SPJ ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From castironpi at gmail.com Thu Mar 13 03:10:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 00:10:06 -0700 (PDT) Subject: sys.stdout assign to- bug References: <39b263ea-e6f0-41f0-b1e8-edcbea851275@13g2000hsb.googlegroups.com> Message-ID: <6992ac74-85fa-4e98-bd8d-308517cdc07a@8g2000hse.googlegroups.com> > import sys > class ThreadedOut: > ? ? ? ? def __init__( self, old ): > ? ? ? ? ? ? ? ? self._old= old > ? ? ? ? def write( self, s ): > ? ? ? ? ? ? ? ? self._old.write( s ) > sys.stdout= ThreadedOut( sys.stdout ) > > Python 3.0a2 WinXP, on the console. ?'a' is undeclared but error > message isn't thrown. ?With 'sys.stdout= Thr...' commented: > stdout and stderr needn't be built-in file objects: any object is > acceptable as long as it has a write() method that takes a string > argument. Adding def flush( self ): self._old.flush() fixed it. Can we get that in the docs? From sturlamolden at yahoo.no Mon Mar 31 15:39:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 31 Mar 2008 12:39:43 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig References: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> <09a0fafc-5658-470a-87a4-8b906caab5ed@e6g2000prf.googlegroups.com> Message-ID: On 31 Mar, 20:52, kim wrote: > array_pointer_t = ndpointer(dtype=c_double) This one is wrong. The dtype should be the datatype kept in the array, which is 'float' (Python doubles) or 'numpy.float64'. array_pointer_t = ndpointer(dtype=numpy.float64) I'd take a good look at that C code. For example, this is not valid C: double timewarp(double x[], int lenx, double y[], int leny) { double prev; double recx[lenx+1]; double recy[leny+1]; double warp[lenx+2][leny+2]; int i,j; I would be valid C99, but you are not compiling it as C99 (gcc does not implement automatic arrays correctly in C99 anyway). If Fortran is what you want, get gfortran or Intel Fortran. To make this valid C, you will need to malloc these buffers, and free them when you are done. Another option is to give them a fixed maximum size: #define MAXLEN 1024 double recx[MAXLEN + 1]; double recy[MAXLEN + 1]; double warp[MAXLEN +2][MAXLEN +2]; There may be other errors as well, I did not look at it carefully. From jkrukoff at ltgc.com Wed Mar 12 15:17:33 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 12 Mar 2008 13:17:33 -0600 Subject: Does __import__ require a module to have a .py suffix? In-Reply-To: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> References: <8d4e0e56-f033-44ac-b27c-df66e18e17f6@u72g2000hsf.googlegroups.com> Message-ID: <1205349453.9664.33.camel@localhost.localdomain> On Wed, 2008-03-12 at 09:22 -0700, mrstephengross wrote: > Hi all. I've got a python file called 'foo' (no extension). I want to > be able to load it as a module, like so: > > m = __import__('foo') > > However, the interpreter tells me "No module named foo". If I rename > it foo.py, I can indeed import it. Is the extension required? Is there > any way to override that requirement? > > Thanks, > --Steve I recently solved a similar issue, importing from a string, with this code: >>> service = imp.new_module( 'ServiceModule' ) >>> compiled = compile( '''...some code here...''', '', 'exec', 0, 1 ) >>> exec compiled in service.__dict__ You could probably shorten it for your needs by using execfile instead. If it's not in the current directory, you'll probably run into some issues with further imports not working as expected unless you set the names/paths right. -- John Krukoff Land Title Guarantee Company From lists at cheimes.de Wed Mar 19 18:10:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 19 Mar 2008 23:10:38 +0100 Subject: Improving datetime In-Reply-To: References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <47E18F5E.8030608@cheimes.de> Nicholas F. Fabry schrieb: > Thank you for the prompt response and suggestion! I am writing up a > proposal presently. There are, however, two broad category of changes > - the 'easy' changes, which could be accomplished with little > additional effort, and the 'hard' changes, which would require > significant reworking of the datetime class (or a wrapper around it). > I was going to break my proposal up into two parts, the easy part and > the hard part. Does that sound like a good idea? Or should I unify > the two? The prime purpose of all the changes, easy and hard, is to > make timezone handling accurate and clear, reduce and make clearer the > (application programmer) code required to use them, and give more > informaton to the programmer about errors, not silently assume > something and pass them. Yes, it sounds like a good idea. The low hanging fruits (aka easy tasks) could be implemented for 2.6 and 3.0. The more complex tasks may have to wait for 2.7 and 3.1 Apropos time zones. A while ago I proposed the inclusion of pytz. But Stuart argued that the tz database may change monthly so I retracted my proposal. But Stuart has proposed some improvements for datetime's tz class. I suggest you contact him. > Please clarify how long a novel is? The problem with the modules are > not bugs, they are problems with real world use scenarios that result > in inescabably ugly code without improvements to the module - so the > explanations involve code samples and use cases... so they may be > 'long'. Could you suggest a maximum number of (70 char) lines, or an > example of an overly long proposal? Some people tend to start their postings like: In the year 2008 after the birth of Christ I, the son of Jone, son of James ... Do you get my point? :] I suggest you start with a short introduction of yourself and your proposal. Short paragraphs and short sentences are easier to read than long. You'll do fine ;) Christian From castironpi at gmail.com Sat Mar 1 15:09:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 12:09:30 -0800 (PST) Subject: rpc shortcut Message-ID: RPC might be -really- easy. Mixin class: getattribute returns a remoting callable if ('name') is callable, or in a special list. On call, pack the parameters, execute locally, and broadcast. You'd need two mixins, BroadcasterMixin and ReceiverMixin, but the same code can still run-- how can behavior depend on whether a given class is listening or "talking" in a given instance? Also, customize mixins: BcastMixin, RceiveMixin with ServerSideMixin, ClientSideMixin, or BothSidesMixin, the first two executing state change in one place, and informing of the new state, or independently, opt'ly with some verification in worries of non-determinism. Or, perhaps, @ServerSide and @ClientSide decorations. It sucks when bandwidth cost might depend on certain parameters-- big state changes vs. big processing time vs. big parameter lists comparatively, esp'ly when they aren't right as separate functions... though do cf. multimethods for param. value checking on this: @servside @params( 'i', lambda i: i> 100 ) def func( i ) / @cliside @params( default ) def func( i ). From brooklineTom at gmail_spam_blocking_suffix.com Mon Mar 31 09:57:44 2008 From: brooklineTom at gmail_spam_blocking_suffix.com (brooklineTom at gmail_spam_blocking_suffix.com) Date: Mon, 31 Mar 2008 09:57:44 -0400 Subject: Smalltalk-style "senders" and "implementors" Message-ID: I'm wondering if anyone has coded up a way to do Smalltalk-style runtime "senders" and "implementors" for python methods. For senders, I think the idea is to traverse the module space and collect, for each method, the names of any methods or functions it calls. In Smalltalk, the workhorse is "CompiledMethod>>sendsSelector". The Smalltalk heuristic is to collect a method name, then traverse all the classes, and within each class traverse all the CompiledMethod instances, invoking the above and collecting the results. I'm wondering if an equivalent exists for Python. For implementors, the idea is to traverse the module space looking for classes that define some supplied method name. I'm looking for a way to do this, at run-time, based on the modules that are actually loaded (rather than a full-text traversal of all the files). The purpose is so that I have a way to make refactoring easier. For example, when I need to change a method name, I want an easy way to find all the methods that invoke it. Full-text lexical search works, but answers lots of false hits, for example from packages where unused files are still hanging around. Thx, Tom From dickinsm at gmail.com Sat Mar 8 21:27:27 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 18:27:27 -0800 (PST) Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: <756ec84d-643a-4bc5-a58f-25c72bd979b1@8g2000hse.googlegroups.com> On Mar 8, 9:19?pm, "Terry Reedy" wrote: > Obvious typo: -(-a)//b == a//b > > This should be -(-a//b) == -((-a)//b) Yes: thanks for the correction! A lesson to me to include parentheses even when redundant... This reminds me of the following parenthesization gem (see next to last line): def isqrt(n): """Find the closest integer to sqrt(n), for n a positive integer.""" a, b = n, 1 while a != b: a, b = a -- n // a >> 1, a return a Mark From zerty.david at gmail.com Wed Mar 26 15:14:07 2008 From: zerty.david at gmail.com (David Anderson) Date: Wed, 26 Mar 2008 16:14:07 -0300 Subject: what does ^ do in python In-Reply-To: <47EA99EE.5030304@tim.thechases.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> <47EA99EE.5030304@tim.thechases.com> Message-ID: <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> Err even I cant understand what I wrote... The right question was:HOw can we use/express pointers python as in C or Pascal? But thx to Heiko, He got what I mean =) On Wed, Mar 26, 2008 at 3:46 PM, Tim Chase wrote: > >> HOw can we use express pointers as in C or python? > > > > Traceback (most recent call last): > > File "", line 1, in > > File "parser.py", line 123, in parse_text > > tree = language.parse_text(text) > > File "english.py", line 456, in parse_text > > tree = self.parse_sentence(sentence) > > File "english.py", line 345, in parse_sentence > > raise ParserError, "can't parse %r" % sentence > > ParserError: can't parse 'HOw can we use express pointers as in C or > > python?' > > Possible "express pointers": > > http://www.geocities.com/derwin_b/sr91sign.jpg > > http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg > > http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg > > If those meet the OP's need, I recommend urllib2 and PIL. > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 16:59:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 21:59:19 -0000 Subject: Why """, not '''? References: Message-ID: <13su5tn6rpjb345@corp.supernews.com> On Wed, 05 Mar 2008 19:19:08 +0000, Matthew Woodcraft wrote: > wrote: >> Why is """ the preferred delimiter for multi-line strings? > > One advantage is that a dumb syntax highlighter is more likely to cope > well if the content includes an apostrophe. But if the content contains double-quote marks, the "dumb syntax highligher" is more likely to cope well if you use '''. And, let's be realistic here, a "dumb syntax highlighter" is more likely to not cope well with triple-quote strings *at all*. Python treats ' and " symmetrically. There is no difference between them, except that: (1) to type " requires using the shift-key, typing ' does not (on English QWERTY keyboards at least); (2) in some typefaces " (double-quote) may be confused with '' (two single-quotes); and (3) they look different. Pretty basic stuff really. -- Steven From deets at nospam.web.de Tue Mar 25 17:52:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Mar 2008 22:52:52 +0100 Subject: _tkinter fails when installing Python 2.4.4 In-Reply-To: References: Message-ID: <64tahuF2absebU1@mid.uni-berlin.de> jgelfand schrieb: > I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat > Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ > usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but > I get the following error message when I run "make": > > building '_tkinter' extension > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ > usr/local/yosi/Python-2.5.2/Modules/_tkinter.o > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ > yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ > usr/local/yosi/Python-2.5.2/Modules/tkappinit.o > gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ > Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ > yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ > lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - > ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so > *** WARNING: renaming "_tkinter" since importing it failed: build/ > lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents > > Any suggestions / ideas as to what is going wrong? I don't get any > other warnings or errors on the other modules. Thanks -- Yosi You are aware that the above shows python 2.5 as the version that is being used for compilation? Diez From harrelson at gmail.com Sat Mar 22 18:51:00 2008 From: harrelson at gmail.com (harrelson) Date: Sat, 22 Mar 2008 15:51:00 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> <5bd9b02a-958b-452d-9e20-c10e4c29f9e4@i29g2000prf.googlegroups.com> <13uaaavi55n7d9b@corp.supernews.com> Message-ID: <0920ddb2-1b36-481b-933f-5a15c3c4dd3d@i12g2000prf.googlegroups.com> Thanks Grant, that does it! I knew it had to be something simple like that and it was frustrating not to be able to find it. I do prefer the tuple. Thanks again. culley From geert at nznl.com Wed Mar 19 06:30:33 2008 From: geert at nznl.com (geert) Date: Wed, 19 Mar 2008 03:30:33 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> <3fd38818-10a8-4815-9359-b1eaf270ee9c@i29g2000prf.googlegroups.com> <7900f1db-16a5-45d1-ada3-962ac0e712b8@e6g2000prf.googlegroups.com> Message-ID: <046c9579-9ff3-44ad-86b7-0c64c8a606ed@8g2000hsu.googlegroups.com> On Mar 19, 2:26?am, Graham Dumpleton wrote: > On Mar 19, 9:47 am, geert wrote: > > > > > On Mar 18, 6:56 pm, geert wrote: > > > > On Mar 14, 1:15 pm, martin.lal... at gmail.com wrote: > > > > > look athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d... > > > > > There is a macpython list that you can consult athttp://www.nabble.com/Python---pythonmac-sig-f2970.html > > > > Just wanted to let you know that I've solved my problem. The solution > > > is to compile mysql using > > > > MACOSX_DEPLOYMENT_TARGET=10.5 \ > > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ > > > ./configure --disable-dependency-tracking ?--enable-thread-safe-client > > > --prefix=/usr/local/mysql > > > > You then go this way to get it running on your machine: > > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/ > > > > Then reinstall MySQLdb. Magic! > > > > Geert > > > Seems that I've yelled success to quickly. Everything's ok as long as > > I just run the django dev server, but moving to apache throughmod_wsgibrings a well-known but less than comforting complaint: > > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352): > > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/ > > LN/LNApache.wsgi'., referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent > > call last):, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in > > __call__, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? response = > > self.get_response(request), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in > > get_response, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? response = > > middleware_method(request), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line > > 13, in process_request, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? engine = > > __import__(settings.SESSION_ENGINE, {}, {}, ['']), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line > > 2, in , referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? from > > django.contrib.sessions.models import Session, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5, > > in , referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? from django.db > > import models, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/db/__init__.py", line 17, in , > > referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? backend = > > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, > > {}, ['']), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? File "/Library/ > > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12, > > in , referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ? ? raise > > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured: > > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/ > > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no > > suitable image found. ?Did find:, referer:http://localhost/images/ > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/ > > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg- > > tmp/_mysql.so: no matching architecture in universal wrapper, referer:http://localhost/images/ > > Did you again confirm that running: > > ? file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5- > macosx-10.5-i386.egg-tmp/_mysql.so > > shows the .so having the required architectures, specifically what > Apache runs as (eg. x86_64)? > > Do the gcc compiler flags when building and linking the .so file show > all the architecture flags? > > Have you empty the Python egg cache to make sure it isn't an older > compiled version? > > Graham Hi all, GOT IT! I have every running now. So, to sum it all up: I'm on a new intel mac with a 64-bit capable processor running macosx 10.5.2. I have httpd (apache2) running as a 64 bit app, which it would of course on a 64-bit machine. Activity monitor confirms this. I compiled mysql from source, configured as stated below: MACOSX_DEPLOYMENT_TARGET=10.5 \ CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \ ./configure --disable-dependency-tracking --enable-thread-safe- client --prefix=/usr/local/mysql Then came mod_wsgi, just out of the box. Then came MySQLdb. Extracted the tar, then edited _mysql.c. Commented lines 37 - 39: //#ifndef uint //#define uint unsigned int //#endif and changed this: uint port = MYSQL_PORT; uint client_flag = 0; to this: unsigned int port = MYSQL_PORT; unsigned int client_flag = 0; on lines 484 and 485 Then - but I don't know if this is really (always) necessary, in site.cfg I changed Threadsafe = True to False. I set the ARCHFLAGS, but I don't think this helped one inch. ARCHFLAGS='-arch ppc -arch ppc64 -arch i386 -arch x86_64' OK. So then I went sudo python setup.py build. (I realise that the sudo isn't required just to do a build) There, I noticed this: creating build/temp.macosx-10.5-i386-2.5 gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes - DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -pipe - Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/ include/mysql -I/System/Library/Frameworks/Python.framework/Versions/ 2.5/include/python2.5 -c _mysql.c -o build/temp.macosx-10.5-i386-2.5/ _mysql.o -arch i386 -arch x86_64 -arch ppc7400 -arch ppc64 You see, here _mysql.o is being created. If you do file _mysql.o, you get: /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o: Mach-O universal binary with 4 architectures /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture i386): Mach-O object i386 /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture x86_64): Mach-O 64-bit object x86_64 /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture ppc7400): Mach-O object ppc /Users/geert/Desktop/MySQL-python-1.2.2/build/temp.macosx-10.5- i386-2.5/_mysql.o (for architecture ppc64): Mach-O 64-bit object ppc64 which is ok. But, strangely, when _mysql.so is created in the next step, gcc doesn't add all the arch flags: gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch i386 -arch ppc build/temp.macosx-10.5-i386-2.5/_mysql.o -L/usr/local/mysql/lib/mysql - lmysqlclient -lz -lm -o build/lib.macosx-10.5-i386-2.5/_mysql.so and you end up with this: geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/geert/ Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/_mysql.so /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ _mysql.so: Mach-O universal binary with 2 architectures /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ _mysql.so (for architecture i386): Mach-O bundle i386 /Users/geert/Desktop/MySQL-python-1.2.2/build/lib.macosx-10.5-i386-2.5/ _mysql.so (for architecture ppc7400): Mach-O bundle ppc which is most definitely NOT ok. So I did this: sudo gcc -Wl,-F. -bundle -undefined dynamic_lookup -arch ppc -arch ppc64 -arch i386 -arch x86_64 build/temp.macosx-10.5-i386-2.5/_mysql.o -L/usr/local/mysql/lib/mysql -lmysqlclient -lz -lm -o build/ lib.macosx-10.5-i386-2.5/_mysql.so adding the arch flags myself, and running gcc again, under sudo. and lo and behold.... geert-dekkerss-imac:MySQL-python-1.2.2 geert$ file /Users/ geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/ _mysql.so /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so: Mach-O universal binary with 4 architectures /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture ppc7400): Mach-O bundle ppc /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture ppc64): Mach-O 64-bit bundle ppc64 /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture i386): Mach-O bundle i386 /Users/geert/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5- i386.egg-tmp/_mysql.so (for architecture x86_64): Mach-O 64-bit bundle x86_64 Well, it only took 20 years off my life span and all the hairs on my head :) Geert From bj_666 at gmx.net Tue Mar 18 05:44:33 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Mar 2008 09:44:33 GMT Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> <8ca43caa-5a2c-4b7b-b168-aad4cfb0581a@a23g2000hsc.googlegroups.com> Message-ID: <649h81F2974cmU1@mid.uni-berlin.de> On Mon, 17 Mar 2008 12:51:14 -0700, sjdevnull at yahoo.com wrote: > On Mar 17, 12:15 pm, rockingred wrote: >> On Mar 10, 11:30 am, "sjdevn... at yahoo.com" >> >> Unfortunately, no free VC system existed for the language in which I >> was programming > > Explain? VC isn't language-specific. It is. It depends usually on the fact that there are individual files. Preferably text files if you want automagic merging of different changes. Now think of languages that are tightly coupled with their IDE storing only binary "tokenized" files instead of plain text or even one big binary file that contains all sources and resources of the project. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:09:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:09:36 -0700 (PDT) Subject: del class with recursive list References: Message-ID: <252fefaa-0695-4f00-9bdc-bebd5bc509b8@n77g2000hse.googlegroups.com> On 9 mar, 17:20, d... at tiscali.it wrote: > Thanks! I just need to remember to del the variables after "for in". And when working on the interactive interpreter, it's easy to forget the _ variable too (that holds the last printed expression) -- Gabriel Genellina From codedread at gmail.com Sun Mar 9 13:43:57 2008 From: codedread at gmail.com (Jeff Schiller) Date: Sun, 9 Mar 2008 12:43:57 -0500 Subject: Need Help Building PythonQt on Windows In-Reply-To: <63ilglF28106hU1@mid.uni-berlin.de> References: <63ilglF28106hU1@mid.uni-berlin.de> Message-ID: I said "PythonQt" not PyQt. That's an important distinction, I think :) See http://pythonqt.sourceforge.net/ Regards, Jeff On 3/9/08, Diez B. Roggisch wrote: > Jeff Schiller schrieb: > > > Hello, > > > > I'm creating an application using Qt (4.4 Beta atm). I have pretty > > close to zero experience with Python (consisting of installing the > > Python interpreter, downloading a python programming and executing it > > on the command-line). > > > > I would like to invoke a Python script from my C++ Qt program and > > capture its output as a C++ structure. It seems that PythonQt might > > be suitable for my needs. > > > > Being a Qt program, I want this thing to be cross-platform. I'm > > having trouble getting things set up in Windows. Has anyone had any > > experience with this? > > > > I've built Qt from source using the mingw32 compiler. I installed > > Python 2.5 binary. I am trying to build PythonQt from source. As per > > http://pythonqt.sourceforge.net/#Building it says I need a "developer > > installation" of Python containing the header files and the library > > files. When I look at my system after installing the Python 2.5 > > binary, I can see I have header files (C:\Python25\include), a 199k > > python25.lib (C:\Python25\libs) and a 2MB python25.dll > > (C:\Windows\System32\). Have I got what I need? > > > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > > to build but then it fails: > > > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > > `_imp__Py_NoSiteFlag' > > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > > `_imp__Py_NoSiteFlag' > > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > > `_imp___Py_NoneStruct' > > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > > `_imp___Py_NoneStruct' > > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > > `_imp___Py_NoneStruct' > > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > > `_imp___Py_NoneStruct' > > ./debug\PythonQt.o: In function > > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > > `_imp__PyClass_Type' > > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > > `_imp__PyClass_Type' > > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > > `_imp__PyCFunction_Type' > > ... > > > > Since I'm new to compiling Qt with mingw and completely new to python, > > I was hoping for tips on why I'm getting these errors. If anyone has > > a better suggestion for a forum/mailing list then please let me know. > > > > A few of suggestions: > > - take this to the PyQt mailing list > (http://www.riverbankcomputing.com/mailman/listinfo/pyqt) > > - you only *need* pyqt if what you want to do in python has really to > deal with Qt-objects - maybe "simple" embedding is enough for your needs > > - I don't see why you need to compile PyQt yourself at all - are you > sure you can't use the stock PyQt for windows? What makes you believe > you really need this to be self-compiled? > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > From spammb at gmail.com Thu Mar 20 15:10:17 2008 From: spammb at gmail.com (Michael Becker) Date: Thu, 20 Mar 2008 12:10:17 -0700 (PDT) Subject: Issues with XMLTreeBuilder in cElementTree and ElementTree Message-ID: <5d820787-e27d-4ae2-8b2b-b82af8ce67cf@p25g2000hsf.googlegroups.com> I had some xmls being output by an application whose formating did not allow for easy editing by humans so I was trying to write a short python app to pretty print xml files. Most of the data in these xml files is in the attributes so I wanted each attribute on its own line. I wrote a short app using xml.etree.ElementTree.XMLTreeBuilder(). To my dismay the attributes were getting reordered. I found that the implementation of XMLTreeBuilder did not make proper use of the ordered_attributes attribute of the expat parser (which it defaults to). The constructor sets ordered_attributes = 1 but then the _start_list method iterates through the ordered list of attributes and stores them in a dictionary! This is incredibly unintuitive and seems to me to be a bug. I would recommend the following changes to ElementTree.py: class XMLTreeBuilder: ... def _start_list(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = [] if attrib_in: for i in range(0, len(attrib_in), 2): attrib.append((fixname(attrib_in[i]), self._fixtext(attrib_in[i+1]))) return self._target.start(tag, attrib) class _ElementInterface: ... def items(self): try: return self.attrib.items() except AttributeError: return self.attrib These changes would allow the user to take advantage of the ordered_attributes attribute in the expat parser to use either ordered or unorder attributes as desired. For backwards compatibility it might be desirable to change XMLTreeBuilder to default to ordered_attributes = 0. I've never submitted a bug fix to a python library so if this seems like a real bug please let me know how to proceed. Secondly, I found a potential issue with the cElementTree module. My understanding (which could be incorrect) of python C modules is that they should work the same as the python versions but be more efficient. The XMLTreeBuilder class in cElementTree doesn't seem to be using the same parser as that in ElementTree. The following code illustrates this issue: >>> import xml.etree.cElementTree >>> t1=xml.etree.cElementTree.XMLTreeBuilder() >>> t1._parser.ordered_attributes = 1 Traceback (most recent call last): File "", line 1, in AttributeError: _parser >>> import xml.etree.ElementTree >>> t1=xml.etree.ElementTree.XMLTreeBuilder() >>> t1._parser.ordered_attributes = 1 In case it is relevant, here is the version and environment information: tpadmin at osswlg1{/tpdata/ossgw/config} $ python -V Python 2.5.1 tpadmin at osswlg1{/tpdata/ossgw/config} $ uname -a SunOS localhost 5.10 Generic_118833-33 sun4u sparc SUNW,Netra-240 From arnodel at googlemail.com Fri Mar 14 08:17:23 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 14 Mar 2008 05:17:23 -0700 (PDT) Subject: How do I iterate over items in a dict grouped by N number of elements? References: <9e7a1cd7-aade-48a9-b935-96ebce07a03d@h11g2000prf.googlegroups.com> Message-ID: <95231b52-4f6b-4e56-a316-68a04d243214@u10g2000prn.googlegroups.com> On Mar 14, 1:34?am, Noah wrote: > What is the fastest way to select N items at a time from a dictionary? > I'm iterating over a dictionary of many thousands of items. > I want to operate on only 100 items at a time. > I want to avoid copying items using any sort of slicing. > Does itertools copy items? > > This works, but is ugly: > > >>> from itertools import * > >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10} > >>> N = 3 > >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N): This solution matches exactly the one proposed in itertools. The following is an extract from http://docs.python.org/lib/itertools-functions.html. Note, the left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using "izip(*[iter(s)]*n)". For data that doesn't fit n-length groups exactly, the last tuple can be pre-padded with fill values using "izip(*[chain(s, [None]*(n-1))]*n)". -- Arnaud From dstromberglists at gmail.com Sun Mar 30 21:03:26 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 31 Mar 2008 01:03:26 +0000 (UTC) Subject: Serial port error statistics - any comparable data? References: <001b01c8918e$323b74c0$03000080@hendrik> Message-ID: On Sat, 29 Mar 2008 13:14:46 +0200, Hendrik van Rooyen wrote: > Hi, > > I have been doing some tests on a device that we are thinking of > incorporating into a product, and I have seen that reception on a serial > port at 115200 baud over about six metres of RS-232 cable makes > mistakes, to the order of 125 lines with errors in them out of > approximately 18.4 million lines of 65 or so chars - about one errored > line in 147000, or one error character in 95 million. > > The PC that is making the errors is a 64 bit dual core AMD machine > running at 2 Gig, and I am running stock standard Open Suse 10.3 with > the supplied Python 2.5. > > What kind of bothers me is the nature of the errors - I seem to get only > missing characters, as if an interrupt was missed. There are no munged > characters as one would expect if the errors were bit related. > > Has anyone else seen anything like this, and am I worrying needlessly? > > I realise that my production protocols will easily handle this almost > non existent level of error - but if this were in microcontroller code > that I had written myself, I would suspect that I was spending too long > in some critical section of code. > > - Hendrik Have you verified that you have flow control enabled? ISTR hearing there is one kind of software flow control and two kinds of hardware flow control. I'm not serial expert, but ISTR that if your cable supports it, you should use RTS/CTS hardware flow control, and if it doesn't, use software flow control. From malaclypse2 at gmail.com Wed Mar 19 11:23:18 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 19 Mar 2008 11:23:18 -0400 Subject: cx_Oracle execute procedure In-Reply-To: References: Message-ID: <16651e80803190823g4536d422o548732d539a05eda@mail.gmail.com> On Wed, Mar 19, 2008 at 11:03 AM, Poppy wrote: > I've been working on the code below and and executes silently, no > complaints, however the end result should be a record in my table and it's > not added. The procedure works with the passed credentials using SQLPlus or > SQL Developer clients. However I'm not sure if I'm constructing my python > code correctly to interact with Oracle. ... > connection.commit > cur.close > connection.close You have to actually call these methods: connection.commit() cur.close() connection.close() Without the parentheses, you're just getting a reference to the methods and immediately discarding them. -- Jerry From gagsl-py2 at yahoo.com.ar Sun Mar 16 19:44:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 16 Mar 2008 21:44:17 -0200 Subject: Basics of Python,learning References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: En Sun, 16 Mar 2008 14:25:26 -0200, Guido van Brakel escribi?: > Why is this not working,and how can I correct it? I guess you want to: a) read a single line containing many numbers separated by white space b) convert them to a list of floating point numbers c) print their minimum and maximum value a) Already done >> z = raw_input ('Give numbers') b) Already done >> y = z.split() >> b=[] >> for i in y: >> b.append(float(i)) The list of numbers is called "b". Don't define a function with the same name, you'll lose the original list attached to the name "b". c) Almost done; remember that your list of numbers is called "b" not "a": >> print min(b) >> print max(b) d) We (Python and me) have no idea what "gem" is: >> print gem(b) -- Gabriel Genellina From dripton at ripton.net Thu Mar 13 09:57:08 2008 From: dripton at ripton.net (dripton) Date: Thu, 13 Mar 2008 06:57:08 -0700 (PDT) Subject: Problem with subprocess in threaded enviroment References: <5972c513-c86c-42bf-bcc8-632dd0f0e8f0@i7g2000prf.googlegroups.com> Message-ID: <0c3c6eac-1773-4386-b34a-c8736b03c583@q78g2000hsh.googlegroups.com> On Mar 12, 12:58 pm, Ningyu Shi wrote: > I'm trying to write a multi-task downloader to download files from a > website using multi-threading. I have one thread to analyze the > webpage, get the addresses of the files to be downloaded and put these > in a Queue. Then the main thread will start some threads to get the > address from the queue and download it. To keep the maximum files > downloaded concurrently, I use a semaphore to control this, like at > most 5 downloads at same time. You don't need a semaphore for that. Semaphores are low-level and very hard to get right. (Read http://www.greenteapress.com/semaphores/ if you don't believe me.) You don't need any other type of explicit lock either. Just use Queues. Queues are much easier. Make simple threads, each of which typically reads from one queue and writes to one queue. If you want N-way concurrency at one stage, start N instances of that thread. If you need to guarantee non-concurrency at some stage, make that thread a singleton. Avoid sharing mutable data across threads except through Queues. > I tried to use urllib.urlretreive in the download() thread, but from > time to time, it seems that one download thread may freeze the whole > program. Then I gave up and use subprocess to call wget to do the job. > My download thread is like this: > > def download( url ): > subprocess.call(["wget", "-q", url]) > with print_lock: > print url, 'finished.' > semaphore.realease() If the prints are just for debugging, print_lock is overkill. And in practice that print statement is probably atomic in CPython because of the GIL. But let's assume that it really is critical not to mix the output streams, and that the print isn't necessarily atomic. So instead of the lock, use a print_queue and a single PrintThread that just pulls strings off the queue and prints them. > But later I found that after the specific wget job finished > downloading, that download() thread never reach the print url > statement. So I end up with files been downloaded, but the download() > thread never ends and don't realease the semaphore then block the > whole program. My guess is that at the time wget process ends, that > specific download thread is not active and missed the return of the > call. The fact that changing libraries didn't fix your problem is a strong indicator that it's your code, not the libraries. You're probably introducing deadlocks with your semaphores. Too much locking is as bad as too little. Here's the skeleton of how I'd write this program: main thread: create queues, create and start other threads, find URLs, put URLs on input_queue class DownloadThread(threading.Thread): def run(self): while True: url = input_queue.get() urllib.urlretrieve(url) print_queue.put("done with %s" % url) class PrintThread(threading.Thread): def run(self): while True: st = print_queue.get() print st Then you just have to worry about clean shutdown. A simple way to handle this to initialize a counter to the number of URLs in main, and decrement it in PrintThread. Then have main busy-wait (with a sleep to avoid consuming too much CPU) for it to hit zero, then join all the other threads and exit. (This seems to violate the no-shared-mutable- data rule, but only one thread at a time can mutate it, so it's safe.) Once you've done this manually, consider using the TaskQueue recipe on the Python Cookbook site, to simplify it a bit. From fn681 at ncf.ca Sat Mar 1 10:40:58 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Sat, 01 Mar 2008 10:40:58 -0500 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c93bb8$0$874$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI (MVP) wrote: > Hi, all! > > Since the install of Python 2.5.2, Pyscripter (1.9.9.1) close for each > error. > Is it only me? Or another guys have the same thing? > > @-salutations > > Michel Claveau > > > > Could you be more explicit please? I use PyScripter and do not have this problem. Colin W. From adonis_vargas at -Remove-This-bellsouth.net Thu Mar 13 19:46:04 2008 From: adonis_vargas at -Remove-This-bellsouth.net (Adonis Vargas) Date: Thu, 13 Mar 2008 19:46:04 -0400 Subject: Python regex In-Reply-To: References: Message-ID: Andrew Rekdal < wrote: > I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > >>> CSS comment > > although this works to a degree... I know the within the brackets everything > is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? eg. > where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... negate > > > -- Andrew > > Have you looked into this library: http://cthedot.de/cssutils/ May help you, if you are trying to achieve something. If your doing it as an exercise then I can not help you, I avoid regex like the plague (but thats just me). Hope this helps. Adonis Vargas From lac at openend.se Mon Mar 17 03:47:01 2008 From: lac at openend.se (Laura Creighton) Date: Mon, 17 Mar 2008 08:47:01 +0100 Subject: Europython fees (was PyCon Disappointment) Message-ID: <200803170747.m2H7l1qg031084@theraft.openend.se> Bj?rn wrote: >I haven't been to EuroPython even when it has been fairly nearby >because the entrance fee was to high. But how do you help change >something like that? Last year rates were: 100 Euros for early bird, 160 Euros for later registration, 65 Euros for early students and 85 Euros for later registration. Thus for most people transportation costs and hotel costs work out to more than Europython costs. There is also a program of financial aide for people who cannot afford the costs, approval on a per-case basis. Are you sure you aren't confusing us with OSCON? Can we discuss this on europython-improve at python.org ? Laura Creighton From sturlamolden at yahoo.no Tue Mar 18 10:10:20 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 07:10:20 -0700 (PDT) Subject: Interesting math problem References: Message-ID: On 18 Mar, 00:58, Jeff Schwab wrote: > def make_slope(distance, parts): > if parts == 0: > return [] > > q, r = divmod(distance, parts) > > if r and parts % r: > q += 1 > > return [q] + make_slope(distance - q, parts - 1) Beautiful. If Python could optimize tail recursion, it would even run fast. From bj_666 at gmx.net Tue Mar 18 08:26:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Mar 2008 12:26:15 GMT Subject: Python 3 and PEP238 division References: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> Message-ID: <649qn7F2974cmU3@mid.uni-berlin.de> On Tue, 18 Mar 2008 04:47:49 -0700, Ninereeds wrote: > On Mar 17, 7:26 pm, "Terry Reedy" wrote: >> 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion >> program > > The tools can work out the *intent* of any particular division > operator? Can work out whether the result should be integer or float, > independent of any particular set of arguments? Seems unlikely. The interpreter can at least print out warnings when a "normal" division operator is called with two `int`\s at runtime. Ciao, Marc 'BlackJack' Rintsch From bearophileHUGS at lycos.com Thu Mar 27 11:59:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 27 Mar 2008 08:59:33 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch: > the author says that the approach is flawed, so at *some* > point it will be discontinued. Can't Psyco be improved, so it can compile things like: nums = (i for i in xrange(200000) if i % 2) print sum(nums) I think the current Psyco runs slower than Python with generators/ iterators. To speed up that code with Psyco you have to write this: nums = [i for i in xrange(200000) if i % 2] print sum(nums) Bye, bearophile From jared.grubb at gmail.com Thu Mar 6 02:47:31 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Wed, 5 Mar 2008 23:47:31 -0800 Subject: for-else Message-ID: <925822270803052347r6239f268pef9b7e8e5ff9b28f@mail.gmail.com> I think bearophile makes an excellent point. I also have a hard time remembering what else does. I have always pictured that the "normal" behavior of a for loop is to get through all the items. In special circumstances, it is necessary to break out early. Therefore, it FEELS like the else loop should excute in the "unexpected" or abnormal case (break), whereas the else actually gets executed only when the entire loop DOES complete. Ben Finney's idea of using an except clause after the for loop is an excellent idea, as it makes it VERY clear when the case gets executed. (I would disagree with his suggestion to use "else" in the break case, however, because that would confuse the previous meaning.) However, you could then make "break" equivalent to "raise BreakException", and provide the following: for foo in bar_sequence: # normal iteration spam(foo) if funky(foo): break except StopIteration, exc: # the iterator stopped normally eggs(exc) except BreakException, exc: # the iterator exited abnormally, i.e. 'break' sausage() Giving a loop a "try"-like behavior could open up the ability to jump out of multiple levels of loops: while 1: while 1: break except BreakException: break # or re-raise? Or maybe you can do "raise BreakException(2)" without any except clauses at all? Just my $0.02. Jared On 4 Mar 2008, at 12:27, bearophileHUGS at lycos.com wrote: Raymond HettInger: FWIW, I'm very happy with for-else. Most of the time, you don't need it, but when you do, it beats the heck out of doing silly tricks with flags. I'd like it to be renamed to something more natural :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Sun Mar 2 04:02:31 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 2 Mar 2008 01:02:31 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> Message-ID: <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> On 2 Mrz., 06:53, Ben Finney wrote: > One of the stated goals of the migration is that the '2to3' program > will only migrate Python 2.6 code -> Python 3.0 code. Yes, I know. Why? "The master said so" isn't an entirely satisfying answer. What are the *technical reasons* that make it hard to apply '2to3' directly on Python 2.4 or Python 2.5? From sjdevnull at yahoo.com Sun Mar 9 01:25:07 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sat, 8 Mar 2008 22:25:07 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> <13t6s8pk90olef8@corp.supernews.com> Message-ID: <626b9dfc-2f4a-47d8-b461-adb3ca813ea0@2g2000hsn.googlegroups.com> On Mar 9, 12:09 am, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 20:45:25 -0800, sjdevn... at yahoo.com wrote: > > On Mar 8, 7:34 pm, Steven D'Aprano > cybersource.com.au> wrote: > >> On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > >> > I'm also a bit baffled by people who put a comment at the top of > >> > every file that tells you what the filename is. > > >> [snip rant] > > >> You've never printed out a source file on pieces of dead tree to read > >> on the train on the way home, or in bed or the bath? > > >> Yes, some editors will print a header or footer showing the file name, > >> but not all will, or are configured to do so. > > > The only times I can recall printing source were in college classes > > where I was required to hand in a hardcopy with the assignment and code > > samples for job interviews. In the real world the code base tends to be > > too huge to contemplate printing... > > You've never (say) printed out the source code to one of the modules in > the Python standard library to read and study? Nope. It's a lot easier to read on the computer, with searching, proper syntax highlighting, tags, etc and access to all the other information I might want while reading the code, and the ability to drift to other modules that might be imported/mentioned, find examples using them, etc. > If your code base is so huge that you can't print out any meaningful > piece, then you desperately need more encapsulation. Yeah, most of the code is encapsulated into smaller parts. The problem is figuring out what meaningful piece(s) I might want. How often do you really find yourself knowing ahead of time exactly what you want to read? Even in code reviews it's common to look at other files in the system, version control history, the issue/spec tracker, or even wander off into Python documentation, algorithm papers, or whatever. It just doesn't seem worth playing a guessing game about exactly what code/versioning/docs/etc I might want to have on hand when the net result even if I guess right will be a worse reading experience without searching, tags, bookmarks, etc. > > Even in the early 1990s the moral equivalent of enscript (I think it was > > a2ps) worked just fine for printing with filenames, line/page numbers, > > and other niceties no matter what editor you used. It seems more > > reasonable to mandate using a sane print tool for the odd case where > > someone wants to print things out than to mandate cluttering up every > > file with the filename in a comment. > > Sure, but really, adding ONE LINE to the start of a file is hardly > "cluttering up" anything. It's not terrible, no, just vaguely pointless and a bit fragile in the face of change. From patrick.waldo at gmail.com Sat Mar 1 09:14:30 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Sat, 1 Mar 2008 06:14:30 -0800 (PST) Subject: joining strings question References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> Message-ID: <616e9a4f-a474-486d-a574-cd799fa4c717@i12g2000prf.googlegroups.com> > def category_iterator(source): > source = iter(source) > try: > while True: > item = source.next() This gave me a lot of inspiration. After a couple of days of banging my head against the wall, I finally figured out a code that could attach headers, titles, numbers, and categories in their appropriate combinations--basically one BIG logic puzzle. It's not the prettiest thing in the world, but it works. If anyone has a better way to do it, then I'll be all ears. Anyways, thank you all for your input, it helped me think outside the box. import re data = ['RULES', 'Approval and Promulgation of Air Quality Implementation Plans:', 'Illinois; Revisions to Emission Reduction Market System, ', '11042 [E8-3800]', 'E8-3800.pdf', 'Ohio; Oxides of Nitrogen Budget Trading Program; Correction, ', '11192 [Z8-2506]', 'Z8-2506.pdf', 'NOTICES', 'Agency Information Collection Activities; Proposals, Submissions, and Approvals, ', '11108-11110 [E8-3934]', 'E8-3934.pdf', 'Data Availability for Lead National Ambient Air Quality Standard Review, ', '11110-11111 [E8-3935]', 'E8-3935.pdf', 'Environmental Impacts Statements; Notice of Availability, ', '11112 [E8-3917]', 'E8-3917.pdf'] NOTICES = re.compile(r'NOTICES') RULES = re.compile(r'RULES') TITLE = re.compile(r'[A-Z][a-z].*') NUM = re.compile(r'\d.*') PDF = re.compile(r'.*\.pdf') counted = [] sorted = [] title = [] tot = len(data) x=0 while x < tot: try: item = data[x] title = [] if NOTICES.match(item) or RULES.match(item): module = item header = '' if TITLE.match(data[x+1]) and TITLE.match(data[x+2]) and NUM.match(data[x+3]): #Header header = data[x+1] counted.append(data[x+1]) sorted.append(data[x+1]) #Title counted.append(data[x+2]) sorted.append(data[x+2]) #Number counted.append(data[x+3]) sorted.append(data[x+3]) title.append(''.join(sorted)) print title, module print sorted = [] x+=1 elif TITLE.match(data[x+1]) and NUM.match(data[x+2]): #Title counted.append(data[x+1]) sorted.append(data[x+1]) #Number counted.append(data[x+2]) sorted.append(data[x+2]) title.append(''.join(sorted)) print title, module print sorted = [] x+=1 else: print item, "strange1" break x+=1 else: if item in counted: x+=1 elif PDF.match(item): x+=1 elif TITLE.match(data[x]) and TITLE.match(data[x+1]) and NUM.match(data[x+2]): #Header header = data[x] counted.append(data[x]) sorted.append(data[x]) #Title counted.append(data[x+1]) sorted.append(data[x+1]) #Number counted.append(data[x+2]) sorted.append(data[x+2]) title.append(''.join(sorted)) sorted = [] print title, module print x+=1 elif TITLE.match(data[x]) and NUM.match(data[x+1]): #Title sorted.append(header) counted.append(data[x]) sorted.append(data[x]) #Number counted.append(data[x+1]) sorted.append(data[x+1]) title.append(''.join(sorted)) sorted = [] print title, module print x+=1 else: print item, "strange2" x+=1 break except IndexError: break From jgardner at jonathangardner.net Mon Mar 3 14:56:41 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 3 Mar 2008 11:56:41 -0800 (PST) Subject: Beautiful Code in Python? References: Message-ID: <772d72a0-e641-4d4c-9ff0-77cffe831ae0@h11g2000prf.googlegroups.com> On Mar 2, 8:35?am, Michele Simionato wrote: > On Mar 2, 5:23 pm, js wrote: > > > Hi, > > > Have you ever seen Beautiful Python code? > > Zope? Django? Python standard lib? or else? > > > Please tell me what code you think it's stunning. > > The doctest module in the standard library. > > ?M.S. The first thing of beauty I found in Python (coming from C, C++, and perl) was the way Python handled variables, or as someone recently described them, names. Python's "for" statement is always beautiful to look at. Especially when someone uses the else clause rather than trying to detect if the list was exhausted. I sometimes avoid using the comprehensions just to get an excuse to write another for loop in Python. There can never be enough for loops written in Python! Also, Python's iterator interface is by far the most beautiful thing I have ever seen in the world of programming. Of course, the reason why the for loop is so beautiful is because iterators are so beautiful. From bjourne at gmail.com Tue Mar 4 10:55:27 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 4 Mar 2008 16:55:27 +0100 Subject: for-else In-Reply-To: References: Message-ID: <740c3aec0803040755o76f7096aud261b89043b26bcd@mail.gmail.com> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks wrote: > > for ...: > > ... > > exhausted: > > ... > > broken: > > ... > > > > The meaning is explicit. While "else" seems to mean little there. > > So I may like something similar for Python 3.x (or the removal of the > > "else"). > > > I would not be opposed to this on its own merits, but there is a > rationale behind the name "else". If you consider a for loop to be a > rolled-up if...elif...else statement (situations where this is > reasonable tend to be the same ones were else would be useful), then > the "else" clause would remain unchanged on the for loop. > > For instance, if you have a (trivial) if...elif...else like this: > > if a == 0: > do_task_0() > elif a == 1: > do_task_1() > elif a == 2: > do_task_2() > else: > do_default_task() > > You could roll it up into a for...else statement like this: > > for i in range(3): > if a == i: > do_task[a]() > else: > do_default_task() You forgot the break statement. The else suite will always be executed in this loop. Kind of proves bearophiles point, for-else is really tricky. -- mvh Bj?rn From frikker at gmail.com Thu Mar 6 14:47:46 2008 From: frikker at gmail.com (blaine) Date: Thu, 6 Mar 2008 11:47:46 -0800 (PST) Subject: Ncurses not found - embedded linux Message-ID: Hello Everyone! I am hoping that someone out there can help me out with this problem. We are using a gumstix platform to develop an embedded system. All that really matters is that it is an ARM processor running an embedded linux, details to follow. Gumstix has its own kernel tree that we cross compile for the system. We do have python, and it has all of the modules that I need except for one. I need ncurses (module curses). I can't seem to figure out how to get it to work - and the only documentation I can find is for Windows (because windows doesn't have ncurses). We have enabled ncurses support in the kernel menu, and that has not helped. I can't seem to trace down where we would 'enable' ncurses support? All other modules seem to work that I've tried (termios, sys, os, etc.) Output from python: [root at gumstix ~]# python , Feb 20 2008, 11:07:36) [GCC 4.1.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import curses Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/curses/__init__.py", line 15, in ? from _curses import * ImportError: No module named _curses [root at gumstix ~]# uname -a Linux gumstix 2.6.21gum #1 Tue Mar 4 15:31:07 EST 2008 armv5tel unknown [root at gumstix lib]# ls /usr/lib/*curses* /usr/lib/libcurses.a@ /usr/lib/libncurses.a /usr/lib/ libncurses.so@ [root at gumstix lib-dynload]# ls _* _bisect.so* _codecs_tw.so* _random.so* _codecs_cn.so* _csv.so* _socket.so* _codecs_hk.so* _heapq.so* _testcapi.so* _codecs_iso2022.so* _hotshot.so* _weakref.so* _codecs_jp.so* _locale.so* _codecs_kr.so* _multibytecodec.so* I hope this is trivial, and I apologize ahead of time if so. Would this perhaps be a compilation issue? Something we have to turn on in the python compile? Thank you, Blaine Booher University of Cincinnati From coolman.guron at gmail.com Mon Mar 24 10:01:42 2008 From: coolman.guron at gmail.com (binaryj) Date: Mon, 24 Mar 2008 07:01:42 -0700 (PDT) Subject: Serving another web site which requires authentication References: Message-ID: ur in luck i am an expert at this! tell me the details , site name etc you would have to proxy everything, basically the urls in the copied page have to be changed to point to ur site. its highly possible. a minor adjustment to ur urlconf and it will work. From pavlovevidence at gmail.com Thu Mar 6 11:00:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 08:00:58 -0800 (PST) Subject: Please keep the full address References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: On Mar 5, 8:07 pm, "D'Arcy J.M. Cain" wrote: > On Wed, 5 Mar 2008 14:00:17 -0800 (PST) > > Mike Driscoll wrote: > > What are you talking about? I didn't change the address at all. I'm > > not even sure what you mean. Are you talking about the post subject > > line (which I have never touched in any post)? If you're talking about > > the OP's email address, that's Google's fault for cropping them. > > I'm talking about castironpi. I find his posts a waste of my time "His" posts? Carl Banks From bcl at brianlane.com Sun Mar 23 11:53:35 2008 From: bcl at brianlane.com (Brian Lane) Date: Sun, 23 Mar 2008 08:53:35 -0700 Subject: Testing for an empty dictionary in Python In-Reply-To: <47e67a99$0$36364$742ec2ed@news.sonic.net> References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <47E67CFF.90507@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). > > John Nagle if dict: ... :) - -- - ---[Office 68.7F]--[Outside 42.9F]--[Server 100.4F]--[Coaster 68.0F]--- - ---[ KLAHOWYA WSF (366773110) @ 47 31.2076 -122 27.2249 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com Movie Landmarks Search Engine http://www.movielandmarks.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFH5nz/Iftj/pcSws0RAnnMAJoDX9P0cK+RshuvuRRfkyJ4CPwqxACeMWkF pq7AKr/qzVWyVat0QiTtUfo= =bpei -----END PGP SIGNATURE----- From ricaraoz at gmail.com Sat Mar 1 21:17:45 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Mar 2008 23:17:45 -0300 Subject: SV: Where's GUI for Python? In-Reply-To: <62uai0F24sc4aU1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> <13sjn6gn3houdaa@corp.supernews.com> <62uai0F24sc4aU1@mid.individual.net> Message-ID: <47CA0E49.2060502@bigfoot.com> K Viltersten wrote: >>> import tkininter >>> >> When that fails, try without the stutter >> >> import tkinter > > > I must be doing something wrong because > neither tkinter nor tkininter works. > I tried both with and without stuttering. > I even asked my wife to stutter some but, > sadly, to no avail. > > When Tim Chase mentioned "battery-installed", > i interpreted it as "all is there". It seems > that either > a) not all the batteries are installed in my > version (v2.5.2) > or > b) some setup/linkage needs to be performed > in order to get the GUI running. > > The error itself is: > ImportError: No module named tkinter > > Suggestions? > import Tkinter (first letter is uppercase) From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 04:45:20 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 08:45:20 -0000 Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <13umnl0ou29kn63@corp.supernews.com> On Thu, 27 Mar 2008 00:33:21 -0700, Grimsqueaker wrote: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? Given an iterator, you use it like this: for item in iterator: print item # or do something else If you're sure that the iterator is relatively small, you can do this: give_me_everything_at_once = list(iterator) but don't try that with this one: def ones(): # never-ending series of ones while True: yield 1 iterator = ones() -- Steven From gagsl-py2 at yahoo.com.ar Fri Mar 21 05:34:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Mar 2008 02:34:17 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> <17b0622a-7c99-430e-9172-ed4e5a55ae7e@s12g2000prg.googlegroups.com> <1147e52b-fe97-4dbf-b512-a8ddeaffdaad@i12g2000prf.googlegroups.com> Message-ID: On 21 mar, 03:13, Godzilla wrote: > Just found out that win32api.GetTickCount() returns a tick count in > milli-second since XP started. Not sure whether that is reliable. > Anyone uses that for calculating elapsed time? I use GetTickCount on other languages because it's easy to call. Note that it returns a value in ms but the *precision* may be not so high. Anyway I think your problem is in the code, not on time.clock() -- Gabriel Genellina From Dodin.Roman at gmail.com Mon Mar 17 13:48:06 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 10:48:06 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> <9192affb-3a3f-4558-909b-d9734c1b1ad2@u10g2000prn.googlegroups.com> Message-ID: On 17 ???, 20:22, hellt wrote: > On 17 ???, 15:48, "Gabriel Genellina" wrote: > > > > > En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > > > > i have a problem with this modules py2exe + pywinauto + sendkeys used > > > together. > > > > In my script i'm using this expression > > > app.window_(title="SJphone").Edit.TypeKeys("Test is > > > running",with_spaces=True) > > > > TypeKeys is using SendKeys module i suppose. > > > Does it work as a normal script, without using py2exe? > > > > my setup.py looks like that: > > > > from distutils.core import setup > > > import py2exe > > > > setup( > > > options = {"py2exe": {"compressed": 1, > > > "optimize": 0, > > > "bundle_files": 1, > > > "packages": ["encodings", "pywinauto", > > > "pywinauto.controls", "pywinauto.tests"] } }, > > > zipfile = None, > > > console=["hosts.py"] > > > ) > > > Perhaps you have to include SendKeys explicitely. I think pywinauto > > doesn't require SendKeys, but uses it if already installed. > > > -- > > Gabriel Genellina > > pywinauto uses sendkeys when performs TypeKeys function. > when i include sendkeys to my package's list i have an error posted > below: > > "No module named SendKeys" ok.. all is ok. i have just reinstall sendkeys. From kyosohma at gmail.com Mon Mar 17 10:31:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 17 Mar 2008 07:31:03 -0700 (PDT) Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> Message-ID: <32bbf0e5-22ca-4b27-810d-919c4978c0f7@d4g2000prg.googlegroups.com> On Mar 17, 8:16 am, a... at pythoncraft.com (Aahz) wrote: > In article <873aqp6bbq.... at physik.rwth-aachen.de>, > Torsten Bronger wrote: > > > > >Carl Banks writes: > >> On Mar 16, 10:49 pm, Brian Jones wrote: > >>> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: > > >>>> If you did not like the programming this year (aside from the > >>>> sponsor talks) and you did not participate in organizing PyCon > >>>> or in delivering presentations, it is YOUR FAULT. PERIOD. > >>>> EXCLAMATION POINT! > > >>> I find this insulting, inexcusable, and utter nonsense. If > >>> putting the blame for a failed experiment on the backs of the > >>> good folks who paid good money for travel, lodging, and > >>> registration is also an experiment, you can hereby consider it > >>> also failed. > > >> He said "aside from the sponsor talks", chief. > > >I see no reason why the "fault" for parts of the rest being > >sub-optimal, too, must necessarily be on the attendee's side. (Just > >hypothetically; I wasn't at PyCon.) > > Let's suppose you have a group of friends who collectively throw a party. > They invite you to help out organizing it and putting it together, but > you choose not to. If you don't have a good time at the party because it > wasn't what you wanted, I think it's fair to say it was your fault. And > I think exactly the same thing is true for PyCon, albeit on a much larger > scale. > > It is absolutely critical to the long-term success of PyCon as a > volunteer-run community conference that each attendee take responsibility > for their experience. Science fiction fandom -- the part that holds > volunteer-run events such as Worldcon -- has lots of experience with this > model. It is one reason why such cons make a fuss about attendees being > "members", compared to "purchasing a ticket" (which is what you do for a > commercialized Star Trek con). > -- > Aahz (a... at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan You have a lot of good points, Aahz. I was thinking of the talks and such as a kind of seminar learning event, not a participatory community event. I went for two reasons: 1) To learn more Plone / Zope 2) To hang out with Python geeks The first one I didn't really get anywhere with, but I got lots of time with PyCon attendees, which was cool. I hope I can go next year, make new friends and maybe present some of my own stuff. Mike From stefan_ml at behnel.de Mon Mar 10 05:47:00 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 10:47:00 +0100 Subject: How to create Python object in C/C++ extension by class name? In-Reply-To: References: Message-ID: <47D50394.3060006@behnel.de> Neil.Fang.CN wrote: > I'm trying to write a C++ extension like this: > > //----------------------------------------------------------------------- > // C++ code > class ActorBase > {...}; > > // export ActorBase to Python as a new type > > class ActorManager > { > void addNewActor(const char* actorClassName) > { > ????? > } > } > > // export ActorManagerto Python as a new type > //----------------------------------------------------------------------- > > The question is how to implement ActorManger::addNewActor(), I want > the class name can be a Python class which inherits the C++ class > ActorBase? Have you considered writing your extension in Cython? http://cython.org/ It would allow you to use Python idioms for what you want to achieve. Stefan From mrmakent at cox.net Mon Mar 3 10:48:01 2008 From: mrmakent at cox.net (Mike Kent) Date: Mon, 3 Mar 2008 07:48:01 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Message-ID: > So my question is this - what is the easiest way to interface to this > "serial" device? > http://pyserial.sourceforge.net/ or perhaps http://pyusb.berlios.de/ From nico-NoSp at m-teknico.net.invalid Thu Mar 27 17:55:51 2008 From: nico-NoSp at m-teknico.net.invalid (Nicola Larosa) Date: Thu, 27 Mar 2008 22:55:51 +0100 Subject: Last Call for Papers for PyCon Italia Due Message-ID: <47ec17ea@extreme.x-privat.org> Only five days left to propose a paper to PyCon Italia Due , the second Italian Python conference. Also, booking is now open. Here are the next deadlines: Start of Early booking: March 25 End of Call for papers: April 1 Start of Late booking: April 23 End of booking: May 3 For a short while we are still accepting papers for PyCon Italia Due, the second edition of the Italian Python conference. This year the conference will be held from May 9th to 11th in Florence, Italy. The first day of the conference (9th May) will start at Palazzo Vecchio in the afternoon with an opening keynote by Richard Stallman. The next days the conference will instead be at the Viva Hotel Laurus near the Duomo. Call for papers =================================================== Papers ~~~~~~ The conference is structured on three parallel tracks: Discovering Python, Spreading Python and Learning Python. * Discovering Python will primarily focus on introductory topics about Python libraries, framework and technologies; * Spreading Python will focus both on advanced technical topics and parallel arguments like development methodologies, real-world use cases and management techniques; * Learning Python will feature a continuous interaction between the speaker and the audience: the speaker will propose a topic and introduce a possible solution, then the talk will dynamically evolve, naturally following questions and notes from the audience. Talks could focus on the following topics (the list is neither exclusive nor exaustive): * large and/or distributed applications written in Python; * scientific and computationally intensive applications; * interaction with other languages/environments, RPC, services; * web programming and frameworks; * desktop programming and GUI toolkits; * Python as "scripting" language (system housekeeping, COM, etc...); * Python and databases; * Python as an educational language. Talks will be screened on contents, relevance for Python community and overall quality. Each talk will have one of the following duration: 30', 60' or 90'. Please specify which length best fits your contents. This timeframe also includes question time, and enough leeway for the audience to enter and leave the room. The talk must be given in either English or Italian language. For native English speaker, please consider that you will probably need to speak a little slower than usual, for better comprehension by the audience, so the talk may come out longer than you expect. See also the note at the end of this paper. How to submit a paper ~~~~~~~~~~~~~~~~~~~~~ Your talk proposal must be submitted online through Assopy[1]. You will need to enter some biographic notes about the speaker, and an abstract of the talk (a couple of paragraphs). If your talk is accepted ~~~~~~~~~~~~~~~~~~~~~~~~ Once your talk proposal is approved, you have to submit your paper before the conference opening day. Each paper must be original work. We cannot accept papers containing material copyrighted by others. Papers should be in plain text, HTML (single page please), PostScript or PDF. Please use a standard format, viewable and printable on all major systems. The files must be submitted within Assopy[1]. A note for non-Italian speakers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We warmly welcome and encourage the presence of non-Italian speakers at PyCon Italia. However, most talks will be in Italian language. We will probably provide Italian-to-English realtime translation for our guests, and also English-to-Italian realtime translation for that part of the audience which is not much familiar with English. [1]: -- Nicola Larosa - http://www.tekNico.net/ From patty206 at charter.net Thu Mar 13 19:21:58 2008 From: patty206 at charter.net (Patty Sutcliffe) Date: Thu, 13 Mar 2008 18:21:58 -0500 Subject: sorting question Message-ID: The website you list regarding 9-letter scrambled words doesn't exist any longer. Is there another way that I can access it to see your program you designed? I have a nine letter work I need to unscramble. I will send it just in case you can figure it out for me and let me know. KAEOSYBRD I'm not very good at that sort of thing, but would love to know the answer to this one. Thank you, Patty patty206 at charter.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Mon Mar 17 10:44:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 Mar 2008 07:44:05 -0700 Subject: PyCon Feedback and Volunteers ( Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <873aqp6bbq.fsf@physik.rwth-aachen.de> <87fxup4goi.fsf@physik.rwth-aachen.de> Message-ID: In article <87fxup4goi.fsf at physik.rwth-aachen.de>, Torsten Bronger wrote: >Aahz writes: >> In article <873aqp6bbq.fsf at physik.rwth-aachen.de>, >> Torsten Bronger wrote: >>> >>> I see no reason why the "fault" for parts of the rest being >>> sub-optimal, too, must necessarily be on the attendee's side. (Just >>> hypothetically; I wasn't at PyCon.) >> >> Let's suppose you have a group of friends who collectively throw a >> party. They invite you to help out organizing it and putting it >> together, but you choose not to. If you don't have a good time at >> the party because it wasn't what you wanted, I think it's fair to say >> it was your fault. And I think exactly the same thing is true for >> PyCon, albeit on a much larger scale. > >Fair enough. But then I question the sensibility in saying "it is XY's >fault" at all. > >Somebody not involved in organising was not happy with the Con. You >may take the criticism or leave it. The criticism may be justified or >not. But saying that it is "his fault" is useless in my opinion, it >even discourages feedback. It think it's okay to evaluate something >that you didn't help coming into existence. A good point is a good >point no matter who makes it. Two things: * There's a reason why I labelled it a "rant" ;-) * You may be misunderstanding the distinction between "fault" and "blame". When there is fault, it is a person's responsibility to correct it. Blame, OTOH, is about responsibility that *should* have been taken. We're not telling people that they should volunteer to run PyCon (although the vast majority of people who help run events like this end up enjoying them more than people who just show up). But anyone who complains and doesn't volunteer is at fault -- the only recourse likely to produce results is to change their volunteer status. As I said, feedback is welcome. Those of us who volunteer do so because we care about the Python community and want to put on a successful event for everyone. But we can rarely make commitments to change anything unless people step up to fix them. It's really no different from the people who show up here on c.l.py to complain about Python: the answer inevitably boils down to "write a patch!" -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From ericofam at yahoo.com Sat Mar 8 22:19:20 2008 From: ericofam at yahoo.com (olusina eric) Date: Sat, 8 Mar 2008 19:19:20 -0800 (PST) Subject: Green's Function Message-ID: <991274.80799.qm@web53607.mail.re2.yahoo.com> I did search for "Python Green's function" and no reasonable hit. I also searched on scipy with no result. Thanks EOF olusina eric wrote: Hi All, I am new to Python and trying to solve the Hamiltonian of a linear chain of atoms using green?s function. Does anyone know any pre-existing library functions and literature that could be helpful? Thanks EOF --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. --------------------------------- Never miss a thing. Make Yahoo your homepage. -------------- next part -------------- An HTML attachment was scrubbed... URL: From morse at edoug.org Tue Mar 11 23:05:07 2008 From: morse at edoug.org (Doug Morse) Date: Wed, 12 Mar 2008 03:05:07 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe Message-ID: Hi, I have an application that runs just fine using the standard Python distro interpreter (v2.5.1 on WinXP) but throws the following exception when run as an executable built with py2exe. My questions are: (a) does anyone have any thoughts on why this exception is occurring and what to do about it, and (b) more generally, why would a problem like this occur under py2exe but not with the standard distro? Thanks in adavance for any and all help. Cheers, Doug Traceback (most recent call last): File "VisionTrainer.py", line 49, in File "SessionController.pyc", line 53, in File "VisionEgg\__init__.pyc", line 42, in File "VisionEgg\ParameterTypes.pyc", line 28, in File "Numeric.pyc", line 93, in File "Precision.pyc", line 26, in File "Precision.pyc", line 23, in _fill_table File "Precision.pyc", line 18, in _get_precisions TypeError: data type not understood From deets at nospam.web.de Wed Mar 19 04:52:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 09:52:45 +0100 Subject: is hash map data structure available in Python? In-Reply-To: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> References: <1e9b3812-97ba-4e21-b258-8a3faf03026d@a70g2000hsh.googlegroups.com> Message-ID: <64c2j2F2b3qg7U1@mid.uni-berlin.de> grbgooglefan schrieb: > Hi, > I have a situation that I need to search a name in a big list of names > in my Python embedded interpreter. I am planning to use hash map for > quicker search. > How do I create hash map in Python? > Can you please guide me to some documentation or tutorial which > provides information on creating, editing, searching through hash map > in Python? http://docs.python.org/tut/node7.html#SECTION007500000000000000000 Diez From stargaming at gmail.com Mon Mar 17 01:54:42 2008 From: stargaming at gmail.com (Stargaming) Date: 17 Mar 2008 05:54:42 GMT Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: <47de07a2$0$2699$9b622d9e@news.freenet.de> On Sun, 16 Mar 2008 20:54:01 -0700, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece of > python code works. If your Python code is well-written, it should be easy figuring out what it means by just reading it. For more complex programs, of course, this method can fail. > With C I often find it very useful to be able to run > the code in step mode and set breakpoints in a debugger so I can watch > how the it executes, how the data change and how the code jumps from one > function to another. But with Python, the debugger is a little > primitive. The default IDLE doesn't even allow me to set a breakpoint. > When the code is long, I am often lost in it. IDLE is just, well, a batteries-included editor. There are many people (me included) who do *not* like it because it's so weak and doesn't have any real uses cases if your programs get sufficiently complex (because IDLE itself is sufficiently primitive). You might be interested in *real* debuggers, such as the Python Debugger `PDB `_. If you don't find its usage obvious, a quick google search just turned up a nice `tutorial `_. You might find the `Python Profilers `_ particularly interesting, `profile` for finding out which function sucks up the most calls/time, `trace` for more sophisticated stuff. `pythontracer ` sounds like a good combination of both. > So I'm curious how to read code effectively. I agree that python code is > clear, but when it becomes long, reading it can still be a hard work. A common practice is just inserting `print` statements since it's so easy. If you think your debugging isn't temporary but could be useful and will be enabled every now and then, you could also use the `logging module `_ with the ``DEBUG`` level. There was a blog post recently about how to do this `generically for functions `_. > BTW. I think this problem also exists in other script languages. FWIW, I think it's particularly easier in scripting languages to implement all kinds of tracing (apart from debugging, which is rather unpopular in Python) because you have one *extra* level (the interpreter) between your machine and your code. HTH, Stargaming From enleverlesX.XmcX at XmclaveauX.com Sat Mar 1 17:04:36 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 1 Mar 2008 23:04:36 +0100 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c93bb8$0$874$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> Message-ID: <47c9d79e$0$859$ba4acef3@news.orange.fr> Hi! Problem solved, after reset layouts. Thanks, all! Michel Claveau From xu.mathena at gmail.com Mon Mar 24 00:24:03 2008 From: xu.mathena at gmail.com (NotGuru) Date: Sun, 23 Mar 2008 21:24:03 -0700 (PDT) Subject: PyTuple_Check and other type check functions didn't check the NULL pointer References: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> Message-ID: <69a00306-8dd3-4918-85cb-60157130d0da@c65g2000hsa.googlegroups.com> On Mar 23, 8:24?pm, Christian Heimes wrote: > NotGuru schrieb: > > > My questions is: is it necessary to check the null pointer in the > > macro or it's a job for the user? Semantically all the type check > > should report a false if a null pointer is encountered. I've already > > had the patch to this issue but I am not sure if I think this problem > > right. ?I don't know if there are some python core developers around > > but I would like to hear all opinions towards this. > > Unless stated otherwise no Py* or PY* function is NULL safe. You have to > check for NULL unless the docs *explicitly* say it's safe to call it > with a NULL argument. > > Christian Thank you Christian and John, I skipped Section 1.3 of that document, so shameful. ;) From george.sakkis at gmail.com Fri Mar 7 22:43:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 7 Mar 2008 19:43:48 -0800 (PST) Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: On Mar 7, 11:12 am, alex.pedwyso... at gmail.com wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... > > I want to be able to detect if they fail with error, I want to be able > to time them, and I want to be able to stop them if they run too > long. I cannot add code to the eval'd strings that will help me > accomplish this. > > Is there a good way to do this? I have it figured out for perl > but I'd rather use python if possible. > > Thanks for any assistance. Check out these two recipes: - Using signals: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 - Using threads: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752 Note that neither is perfect; the first breaks if the timed code overrides the alarm signal, while the second can't interrupt code that doesn't release the GIL and doesn't actually kill the function after the timeout. I'd be rather surprised if the perl solution you figured out doesn't have any issues. George From jeff at schwabcenter.com Sun Mar 16 17:48:44 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sun, 16 Mar 2008 14:48:44 -0700 Subject: Types, Cython, program readability In-Reply-To: <87abky1i6i.fsf@benfinney.id.au> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> <87abky1i6i.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > sturlamolden writes: > >> If you don't know how to install a C compiler like Microsoft Visual >> Studio, you should not be programming computers anyway. > > Utter elitist nonsense. > > Programming should be made easier, and I see Python as a very good > language for making programming easier. Lowering the barrier for > prospective hackers to get into programming is a good thing. The > installation of a C compiler is incidental to that, and has no > necessary connection with programming. > > Placing meaningless roadblocks, as you suggest should be done, is > anathema to education. Hear, hear! I continue to be shocked when an OS doesn't come with a compiler for the language in which the OS is written. It seems like one of the most basic things that should just be there, along with some kind of command shell (be it CLI or graphical), and ideally a well-defined scripting interface that is easily extensible from the "core" language. Nowadays, scripts are often intended to work on multiple different platforms; various scripting languages therefore list portability among their most valuable features. One issue from which most of them suffer is that they really are not suitable for systems programming. As scripts evolve into applications, native-language compilers end up being necessary, after all, such that portability of non-trivial programs is severely limited. (It's not really the languages' fault. After all, they were only really meant to enable portable scripting.) Python, I think, helps improve the situation with specific support for applications programming. Unlike Perl or Tcl, Python is not just a scripting language with a set of ad-hoc extensions. There are still issues, and Python probably will never be a general-purpose replacement for system-native language compilers, but it does enable a smooth ramp from "just a user," through "a user who does some scripting," to "application developer." I am of the opinion that the more regular users write and share code, the faster we will see improvement in overall software quality, and the more pleasant the world will be for all of us to live in. See also: http://cm.bell-labs.com/cm/cs/upe/ http://www.linfo.org/unix_philosophy.html From zerty.david at gmail.com Sun Mar 30 16:03:52 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 30 Mar 2008 17:03:52 -0300 Subject: Error Raised But dont know what it means Message-ID: <5dc598e30803301303t13fd8d57q7551d66e95cc7143@mail.gmail.com> Well, I'm dealing with files in Pickle, I'm saving at the file a List of Objects from the same Class, When I try to retrive this information and try to iterate over them this error is raised: TypeError: 'instancemethod' object is not iterable But if I just print the method I get the 'real thing' what's the problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fred.sells at adventistcare.org Tue Mar 25 23:19:06 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 25 Mar 2008 23:19:06 -0400 Subject: Can I run a python program from within emacs? In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B0895@acesxch01.ADVENTISTCORP.NET> I use a .emacs file (attached) that some associates gave me nearly 20 years ago. Some of it is OBE now, but it still works for me on both windows and Linux. With this file I can cntrl-c cntrl-c (i.e. ^c twice to run the current buffer). Don't ask me to explain it, it just works. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Jeff Schwab > Sent: Thursday, March 20, 2008 11:29 AM > To: python-list at python.org > Subject: Re: Can I run a python program from within emacs? > > > Grant Edwards wrote: > > On 2008-03-20, jmDesktop wrote: > > > >> Hi, I'm trying to learn Python. I using Aquamac an emac > >> implementation with mac os x. I have a program. If I go to the > >> command prompt and type pythong myprog.py, it works. Can > the program > >> be run from within the editor or is that not how > development is done? > >> I ask because I was using Visual Studio with C# and, if you're > >> familiar, you just hit run and it works. On Python do I use the > >> editor for editing only and then run the program from the command > >> line? > > > > http://www.google.com/search?q=emacs+python > > Or achieve a similar (more flexible (IMO), but less smoothly > integrated) > effect with Vim and GNU Screen. Until recently, you had to > patch Screen > if you wanted vertical splits, but now it's in the main line. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: .emacs Type: application/octet-stream Size: 3635 bytes Desc: .emacs URL: From sgeiger at ncee.net Fri Mar 14 12:46:17 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 14 Mar 2008 11:46:17 -0500 Subject: Monitoring SSHd and web servers? In-Reply-To: <36a2338f-60fd-456d-a906-716bb52e8122@s8g2000prg.googlegroups.com> References: <36a2338f-60fd-456d-a906-716bb52e8122@s8g2000prg.googlegroups.com> Message-ID: <47DAABD9.7010300@ncee.net> I would recommend using a tried-and-true solution for making sure your uptime of various services is maximized (if that's what your goal is). Running a local "daemon-monitoring daemon" is one option--monit does a good job. Checking services over the network, as nagios does well, is another solution. Jonathan Gardner wrote: > On Mar 13, 11:32 pm, Gilles Ganault wrote: > >> I'd like to monitor connections to a remote SSH and web server. Does >> someone have some code handy that would try to connect every 5mn, and >> print an error if the script can't connect? >> > > from time import sleep > while True: > # Try to connect. May want to spawn a subprocess running a simple > shell script > # Handle success / failure appropriately > sleep 5*60 # Sleep for 5 minutes > > What you monitor is up to you. At a basic level, you can see if the > server is accepting connections. At a higher level, see if you can get > a page or see if you can login as a specific person. At a higher > level, you may want to check what is on the page or what happens when > you log in. It's all up to you. > > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From gagsl-py2 at yahoo.com.ar Tue Mar 4 21:39:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 00:39:03 -0200 Subject: multiplication of lists of strings References: Message-ID: En Tue, 04 Mar 2008 23:50:49 -0200, Jason escribi?: > How could I return a list or tuple of each unique combination of a given > set of lists (perhaps from a dict or a list). This means the number of > lists are not known nor is the length of each. Use the Google interfase for this group: http://groups.google.com/group/comp.lang.python/ Type "unique combinations lists" in the text box; press "Search in this group". The very first result contains some answers to your question. -- Gabriel Genellina From rhh2109 at columbia.edu Sat Mar 1 17:29:13 2008 From: rhh2109 at columbia.edu (Roy H. Han) Date: Sat, 1 Mar 2008 17:29:13 -0500 Subject: Where's GUI for Python? In-Reply-To: <47C9D33E.9040407@tim.thechases.com> References: <62tvhmF256jk7U1@mid.individual.net> <47C9D33E.9040407@tim.thechases.com> Message-ID: <6a5569ec0803011429q4444ec25o7c235ae80590dff8@mail.gmail.com> Konrad, I use wxPython with wxGlade. I love wxGlade! wxGlade http://wxglade.sourceforge.net/ You need to look at this documentation to code event handling. wxWidgets http://www.wxwidgets.org/manuals/stable/wx_classesbycat.html You can also try coding the GUI manually, but it is much easier to use wxGlade. wxPython http://wiki.wxpython.org/AnotherTutorial Roy On Sat, Mar 1, 2008 at 5:05 PM, Tim Chase wrote: > > I'm certain there is an API for creating > > GUI's but as far i can find it in the > > http://docs.python.org/tut/tut.html > > the only "gui" is in "Guido". > > > > What do i miss? > > > The batteries-included GUI: > > import tkininter > > Add-on solutions include wxPython, PythonCard and many others. GIYF: > > http://google.com/search?q=python+gui > > -tkc > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mdonle at gmail.com Wed Mar 12 09:25:05 2008 From: Mdonle at gmail.com (Mdonle at gmail.com) Date: Wed, 12 Mar 2008 06:25:05 -0700 (PDT) Subject: a Roguelike in Python Message-ID: Seeing the 7DRL start up recently, i wanted to see what one was made of. Python is the language i'm most familiar with so i searched for some code to look at, but i couldn't find any. Can anyone direct me to the right place? I did some searching on what it would take to write a roguelike in python and it looked like the curses module would work perfectly, but it looks to me like it doesn't work in windows? I tried to import it and it says 'No Module named _curses' Sorry if all this sounds a bit noobish, it's only cause i am. From castironpi at gmail.com Mon Mar 24 11:06:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 24 Mar 2008 08:06:01 -0700 (PDT) Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> Message-ID: <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> On Mar 24, 9:48?am, Jason wrote: > On Mar 24, 5:21 am, Julien wrote: > > > > > > > Hello all, > > > I would like to do something like: > > > def called(arg) > > ? ? if arg==True: > > ? ? ? ? !!magic!!caller.return 1 > > > def caller(arg) > > ? ? called(arg) > > ? ? return 2 > > > Here, the fake !!!magic!!! represents a statement (which I ignore) > > that would make the caller function return a value different from what > > it'd return normally. > > > For example, caller(True) would return 1, and caller(False) would > > return 2. The reason I want that is because I don't want the caller > > function to know what's going on in the called function, and be > > shortcut if the called function think it's necessary. > > > Would you know if that's possible, and if so, how? > > > I've done a bit of research and I think I've found some good pointers, > > in particular using the 'inspect' library: > > > import inspect > > > def called(arg) > > ? ? if arg==True: > > ? ? ? ? caller_frame = inspect.stack()[1] > > ? ? ? ? ... > > > Here 'caller_frame' contains the frame of the caller function. Now, > > how can I make that frame return a particular value? > > > By the way, I'm not really interested in 'called' throwing an > > exception and 'caller' catching it. In fact, I want things to remain > > completely transparent for 'caller'. > > > Hope that was clear... :/ > > > Thanks! > > > Julien > > As Steven wrote, it's not very clear. ?If we knew the intent of this, > we could perhaps point you to a more useful, maintainable technique. > We don't know why you're trying to circumvent the programming language > in this case. ?Any solution that works as you described will probably > be unportable between the different Pythons (CPython, Jython, > IronPython, etc). > > Please note that the following code should work, but I've only run it > through the interpreter in my brain. ?My brain's interpreter is full > of Heisenbugs, so you may need to adjust a few things. ?Here's my > thoughts: > > Given: > ? ? def First( arg ): > ? ? ? ? Second( arg ) > ? ? ? ? return 5 > > 1) ?If you can modify both functions, change the first function to > return a value in certain circumstances: > ? ? def AltFirst( arg ): > ? ? ? ? value = Second( arg ) > ? ? ? ? if value is not None: ?return value > ? ? ? ? return 5 > > 2) ?Raise an exception in Second, and catch that exception above > First: > > class SecondExcept(Exception): > ? ? def __init__(self, value): > ? ? ? ? Exception.__init__(self, 'Spam!') > ? ? ? ? self.value = value > > def Second(arg): > ? ? if arg == my_conditional_value: > ? ? ? ? raise SecondExcept( 5 ) > > # The following could even be put in your own function, > # or in a wrapper or decorator for the First function. > try: > ? ? myvalue = First( 'Vikings!' ) > except SecondExcept, exc: > ? ? myvalue = exc.value > > When you need to use an exceptional pathway, use an exception. ?They > aren't just for reporting errors. Exceptions are a control tool. There was a 'goto using Exceptions' once in the manuals. I don't see a problem with a local control-flow object. It would appease a number of requests I've read. for x: for y: control.break( 2 ) if a: if b: control.fail( 2 ) so no need to reduplicate: else: thing() else: thing() if a: if b: control.mostrecenttest( 0 ) def f(): def g(): control.return( 2 )( "early" ) Something tells me generators could solve the problem, but I may be enamored, so it's a separate post. From gagsl-py2 at yahoo.com.ar Sun Mar 30 14:59:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 15:59:27 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 11:10:20 -0300, MRAB escribi?: > On Mar 30, 6:35 am, "Gabriel Genellina" > wrote: >> En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: >> >> > BTW, my opinion is that it's already time that programmer editors >> > have input methods advanced enough for generating this: >> >> > if x ? 0: >> > ?y ? s: >> > if y ? 0: f1(y) >> > else: f2(y) >> >> Fine if you have the right keyboard... Try to write APL with a standard >> keyboard :) >> > There was a version of APL for the Sinclair QL which replaced the > standard APL symbols with keywords. Wow, APL on 8 bits? Now there is (or perhaps there was) J, a reincarnation of APL by Iverson himself that uses ASCII characters only. -- Gabriel Genellina From tim.arnold at sas.com Thu Mar 27 12:39:15 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 27 Mar 2008 12:39:15 -0400 Subject: first interactive app References: <34ba46bf-8389-43e1-9c04-92732203a1ce@h11g2000prf.googlegroups.com> Message-ID: "Miki" wrote in message news:34ba46bf-8389-43e1-9c04-92732203a1ce at h11g2000prf.googlegroups.com... > Hello Tim, >> >> Any ideas on a simple interface for this? >> > How about something like: > > Chapter 1 (001-200 200) > Chapter 2 (200-300 100) > ------ 001-300 300 ---- > Chapter 3 (300-450 150) > Chapter 4 (450-500 50) > ------ 300-450 250 ---- > Chapter 5 (500-600 100) > ------ 500-600 100 ---- > > Where the user can move the divider up and down to create new volume, > they can also add and delete dividers. > > The program will not allow to drag the divider above the 600 page > limit. > > HTH, > -- > Miki > http://pythonwise.blogspot.com Hi Miki, that looks nice, simple, and intuitive. thanks for thinking about it. Now to dive into some gui coding! thanks, --Tim From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 09:52:41 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 15:52:41 +0100 Subject: Checking if a variable is a dictionary In-Reply-To: <5c0bab72-8dd2-4be9-a832-168a32d99585@8g2000hse.googlegroups.com> References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <5c0bab72-8dd2-4be9-a832-168a32d99585@8g2000hse.googlegroups.com> Message-ID: <47d00526$0$301$426a74cc@news.free.fr> Jeffrey Seifried a ?crit : (snip) > if type(a)==type({}): > print 'a is a dictionary' This instanciates a dict, call type() on it, and discard the dict - which is useless since the dict type is a builtin. Also, when you want to test identity, use an identity test. if type(a) is dict: print "blah blah blah" From paul at boddie.org.uk Mon Mar 3 05:52:44 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 3 Mar 2008 02:52:44 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au> <996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: <524be122-1eee-40fd-a521-8d02de5e86b2@m34g2000hsc.googlegroups.com> On 2 Mar, 10:02, Kay Schluehr wrote: > On 2 Mrz., 06:53, Ben Finney > wrote: > > > One of the stated goals of the migration is that the '2to3' program > > will only migrate Python 2.6 code -> Python 3.0 code. > > Yes, I know. Why? > > "The master said so" isn't an entirely satisfying answer. What are the > *technical reasons* that make it hard to apply '2to3' directly on > Python 2.4 or Python 2.5? I imagine that in Python 2.6 there are some semantic changes (conveniences, really), plus some expansion of the language syntax to overlap with Python 3, both of which let the 2to3 tool work as intended. Obviously 2to3 doesn't do too much complicated stuff, and I imagine (or have deduced from what I've heard) that you have to write code that is "obvious" to the tool so that it can translate it correctly. Perhaps 2.5 and earlier don't permit such obvious code to be written. Paul From mail at timgolden.me.uk Mon Mar 17 05:14:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 17 Mar 2008 09:14:30 +0000 Subject: Types, Cython, program readability In-Reply-To: <00be01c88779$0a40ca70$0200a8c0@TMSMAIN> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <47DD33D7.2020300@timgolden.me.uk> <00be01c88779$0a40ca70$0200a8c0@TMSMAIN> Message-ID: <47DE3676.1010201@timgolden.me.uk> Tom Stambaugh wrote: >> I'm not entirely sure why you think Pyrex should "contain a compiler". >> It certainly works well enough with the free [beer] MS VS 2008 Express >> and I'm fairly sure it's fine with MingW. Both of those are readily >> available and I don't imagine anyone who's going to use Pyrex / Cython / >> ShedSkin is going to baulk at downloading a compiler set :) > > Anything like this is a lot more attractive to me if I can download and > install a binary without *needing* a compiler. Most of the time, I just want > something to run -- I don't want to risk diving in compiler-hell if I can > avoid it. It isn't downloading the compiler set that worries me, it's that I > almost never even want to think about it. I certainly sympathise with the compiler-hell syndrome here: the subject of compiling Python itself and its extensions under Windows has long been a source of questions and qualified answers on the Python lists. This cuts both ways: Python itself is effectively only buildable with the MS tools [1] (notwithstanding some valiant efforts to provide patchsets so that it builds under MingW [2]). On the other hand, some useful libraries, say ffmpeg, only *won't* build with the MS tools[3]. Both sides of that debate have a valid position, but it doesn't ultimately help the developers. Which is probably why avbin/pyglet[4] took the decoupled route and used ctypes to join the two together! In the case of a general extension (like simpleJSON or PIL etc.) I'm usually just after a binary. In the case of Pyrex, though, the Pyrex code *itself* is pure Python; it's the code it generates which is C -- one step further away. Granted, it might be possible to produce some sort of bundle which shipped a MingW-based extension along with the Pyrex release bundle, but my own philosophy is that, if you've got to the point of using Pyrex then downloading a compiler isn't going to be too much work. It's clear, though, from the posts in this thread, that other people don't necessarily agree. Admittedly I have the advantage of being a professional programmer who is therefore bound to know what a compiler *is*! TJG [1] http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-04/msg03627.html [2] http://jove.prohosting.com/iwave/ipython/pyMinGW.html [3] http://ffmpeg.mplayerhq.hu/faq.html#SEC36 [4] http://code.google.com/p/avbin/ From emailamit at gmail.com Mon Mar 31 13:26:51 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 10:26:51 -0700 (PDT) Subject: Newbie Question - Overloading == References: <85edb5fb-eae8-4e8f-8f77-0ee4668063cd@u69g2000hse.googlegroups.com> Message-ID: <4bee3421-305c-440f-9c6d-fd2c72542971@i12g2000prf.googlegroups.com> On Mar 31, 10:23 am, xkenneth wrote: > > class A: > def __eq__(self,other): > return self.a == other.a and self.b == other.b > > class B: > def __eq__(self,other): > return self.a == other.a and self.c == other.c > > Thanks! > > Regards, > Kenneth Miller Can't say aboyt unpythonic: I am no expert at that: but to avoid catching Attribute-Error everywhere, you can redefine __eq__ as def __eq__(self, other) : try : return <> except AttributeError: return False From gagsl-py2 at yahoo.com.ar Mon Mar 24 14:56:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 15:56:24 -0300 Subject: behavior varied between empty string '' and empty list [] References: <1d822b31-fd7a-47f2-abee-45226c6b0c26@e6g2000prf.googlegroups.com> Message-ID: En Mon, 24 Mar 2008 15:22:43 -0300, Tzury Bar Yochay escribi?: > while I can invoke methods of empty string '' right in typing > (''.join(), etc.) I can't do the same with empty list > > example: > >>>> a = [1,2,3] >>>> b = [].extend(a) >>>> b >>>> b = [] >>>> b.extend(a) >>>> b > [1,2,3] extend() -like most mutating methods- does not return the list, it returns None. Your empty list grow the 3 additional items, but since there were no additional references to it, got destroyed. > I would not use b = a since I don't want changes on 'b' to apply on > 'a' Try with b = list(a) > do you think this should be available on lists to invoke method > directly? You already can. Your example is misleading because you used b with two meanings. (Compare the *usage* of each variable/value, not their names). This is equivalent to the second part of your example: py> a = [1,2,3] py> b = [] py> b.extend(a) py> b [1, 2, 3] and this is the first part: py> a = [1,2,3] py> b = [] py> c = b.extend(a) py> c py> b [1, 2, 3] except that in your original example, the empty list had no name so you cannot see how it changed. -- Gabriel Genellina From chris at wonderstore.com Mon Mar 31 18:02:32 2008 From: chris at wonderstore.com (wrightee) Date: Mon, 31 Mar 2008 15:02:32 -0700 (PDT) Subject: PyQT / QDate / QTableWidget References: Message-ID: <216d8145-4ce2-47ee-9dfd-a789d77ec2a2@e6g2000prf.googlegroups.com> That worked! Thank you; I had given up on QDate but changing the format worked perfectly. From castironpi at gmail.com Mon Mar 17 08:15:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 05:15:28 -0700 (PDT) Subject: writing to a binary file without intervening spaces References: <7xtzj5eou0.fsf@ruckus.brouhaha.com> Message-ID: <501a0165-4396-467c-a68f-209b764283bb@m3g2000hsc.googlegroups.com> On Mar 17, 3:28?am, Paul Rubin wrote: > Larry writes: > > My data is a = [23, 45, 56, 255]. > > My desire output is: 234556255, of course in binary file > > representation already. > > > I tried to make one using write after pack method of struct module, > > but because of spaces I got incorrect results. > > struct.pack works for me: > > ? ? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > ? ? >>> import struct, os > ? ? >>> x = struct.pack('BBBB', 23, 45, 56, 255) > ? ? >>> len(x) > ? ? 4 > ? ? >>> f = open('/tmp/foo','w'); f.write(x); f.close() > ? ? >>> os.system("ls -l /tmp/foo") > ? ? -rw------- 1 phr phr 4 Mar 17 01:27 /tmp/foo > ? ? >>> > > You could also do the list-string conversion with the array module. Python 3.0a2 (r30a2:59405M, Dec 7 2007, 15:23:28) [MSC v.1500 32 bit (Intel)] o n win32 Type "help", "copyright", "credits" or "license" for more information. >>> bytes( [ 23, 45, 56, 255 ] ) b'\x17-8\xff' >>> a= _ >>> f= open('temp.x','wb') >>> f.write( a ) 4 >>> f= open('temp.x','rb') >>> f.read() b'\x17-8\xff' From jeff at schwabcenter.com Mon Mar 17 11:26:38 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 08:26:38 -0700 Subject: String To List In-Reply-To: References: Message-ID: Girish wrote: > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? Do you want: (1) Specifically to vivify lists formatted as in your example? If so, why? (2) To save and restore arbitrary python objects? (3) To define some kind of configuration file format that you can read from Python? From Lie.1296 at gmail.com Sun Mar 23 13:43:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 23 Mar 2008 10:43:59 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> <128011dd-a1a8-43af-bdea-beba452aa596@f63g2000hsf.googlegroups.com> Message-ID: <4db3e139-3da4-4d77-a4d7-b5304cc9a28b@s12g2000prg.googlegroups.com> On Mar 22, 1:11?am, MRAB wrote: > On Mar 21, 11:48 am, fkallgren wrote:> Hi. > > > I have a little problem. I have a script that is in the scheduler > > (win32). But every now and then I update this script and I dont want > > to go to every computer and update it. So now I want the program to 1) > > check for new version of the script, 2) if there is a new version, > > copy that verision from server to local drive, 3) shutdown the program > > and start it up again as the new version. > > > The problem is that I can't run this script directly from server so it > > have to run it locally. > > > Anyone having any bright ideas?? > > The script could just check to see if the version on the server is > more recent and if it is then copy it over the local one, start the > local one, and then quit. > > Python compiles the script to bytecode and then interprets the > bytecode, so when the script is being run the .py or .pyw source > itself isn't being used and can be overwritten. I've tried the > following on Windows XP and it works: > > (snip) Even if the .py and .pyw is being locked, you could always use a helper script that calls the main program if there is no update. This way, the main program is never called directly, only by the updater script. Such implementation is trivial. # updater script # when you're running your program, you # call this script instead of the real # main program if needupdate(): update() else: callmainprogram() # main program # this script should never be called # directly, only by the updater program # (well, except perhaps on development stage) def checkupdate(): if needupate(): callupdatescript() terminateself() # possibly saving state, etc From steven.p.clark at gmail.com Mon Mar 17 23:57:14 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Mon, 17 Mar 2008 23:57:14 -0400 Subject: ord function problem from newbie In-Reply-To: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> References: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> Message-ID: <663744510803172057x78d07300u955e3c71ed9e416b@mail.gmail.com> print sum([ord(ch)-96 for ch in small]) On Mon, Mar 17, 2008 at 11:28 PM, wrote: > I'm trying to convert a name into a numerical value that is not > consistent with ANSCII values. In my case, I convert all to lowercase, > then try to sum the value of the letters entered by the user, can't > get it to add them. Here is what I have. By the way, the values I need > to use is: a=1, b=2, c=3, etc... I'm trying to subtract 96 from the > ANSCII value, then total. > > import string > def main(): > print "This program calculates the numeric value of a name with > which" > print "you could look up online as to what that value represents." > print > # Get name to calculate > name = raw_input("Please type a name: ") > small = string.lower(name) > print "Here is the calculated value:" > > print small > for ch in small: > v = ord(ch)-96 > print v > > > main() > > Looks like this: > This program calculates the numeric value of a name with which > you could look up online as to what that value represents. > > Please type a name: David > Here is the calculated value: > david > 4 > 1 > 22 > 9 > 4 > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sat Mar 29 07:08:16 2008 From: http (Paul Rubin) Date: 29 Mar 2008 04:08:16 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: <7xhcepeqjj.fsf@ruckus.brouhaha.com> kwitters at telenet.be writes: > I don't know if this is the right place to discuss the death of <> in > Python 3.0, or if there have been any meaningful discussions posted > before (hard to search google with '<>' keyword), but why would anyone > prefer the comparison operator != over <>??? I doubt anyone cares. Python probably chose != because it's what C uses. The scary choice is /= which can be interpreted as an assignment. Python lacks assignment expressions partly because of a meme that using = instead of == by accident is a common C bug. I'm sure it happens but at least in my own experience (from having written plenty of buggy C code over the years) it's not that frequent. Using /= instead of != seems more likely, for programmers who switch between C and languages that use /= for nonequality. From castironpi at gmail.com Sun Mar 16 04:28:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 01:28:02 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. References: Message-ID: On Mar 16, 1:43?am, Erik Max Francis wrote: > castiro... at gmail.com wrote: > > 'join' in the wrong word for the method in class Thread. > > That's the standard term in threading. ?If it's not familiar to you, > well, bummer, but there's not much more that can be done about that than > for you to read the literature. Do you agree that it's inconsistent? From poof65 at gmail.com Sat Mar 8 11:32:47 2008 From: poof65 at gmail.com (poof65) Date: Sat, 8 Mar 2008 17:32:47 +0100 Subject: parralel downloads In-Reply-To: References: Message-ID: For your problem you have to use threads. You can have more information here. http://artfulcode.nfshost.com/files/multi-threading-in-python.html On Sat, Mar 8, 2008 at 1:11 PM, John Deas wrote: > Hi, > > I would like to write a python script that will download a list of > files (mainly mp3s) from Internet. For this, I thought to use urllib, > with > > urlopen("myUrl").read() and then writing the resulting string to a > file > > my problem is that I would like to download several files at the time. > As I have not much experience in programming, could you point me the > easier ways to do this in python ? > > Thanks, > > JD > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sun Mar 30 17:06:18 2008 From: http (Paul Rubin) Date: 30 Mar 2008 14:06:18 -0700 Subject: Dispatching functions from a dictionary References: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> Message-ID: <7xd4pbexbp.fsf@ruckus.brouhaha.com> tkpmep at gmail.com writes: > RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), ...} This actually calls the functions random.betavariate, etc. when initializing RVDict. If you print out the contents of RVDict you'll see that each value in it is just a floating point number, not a callable. You want something like: RVDict = {'1': lambda: random.betavariate(1,1), '2': lambda: random.expovariate(1), etc. The "lambda" keyword creates a function that when called evaluates the expression that you gave it. For example, lambda x: x*x is a function that squares its argument, so saying y = (lambda x: x*x) (3) is similar to saying: def square(x): return x*x y = square(3) Both of them set y to 9. In the case of lambda: random.expovariate(1) you have made a function with no args, so you'd call it like this: > rvfunc = RVDict[str(RVType)] > for i in range(N): > x.append(rvfunc()) > y.append(rvfunc()) rvfunc (the retrieved dictionary item) is now a callable function instead of just a number. It takes no args, so you call it by saying rvfunc(). From castironpi at gmail.com Thu Mar 6 17:31:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 14:31:47 -0800 (PST) Subject: Protocol for thread communication References: Message-ID: <703eb1ca-3d22-4347-9a3c-c647e0038700@f47g2000hsd.googlegroups.com> > > Does anyone have any recommended ideas/ways of implementing a proper > > control and status protocol for communicating with threads? ?I have a > > program that spawns a few worker threads, and I'd like a good, clean way > > of communicating the status of these threads back to the main thread. > > Each thread (wrapped in a very simple class) has only a few states, and > > progress levels in those states. ?And sometimes they can error out, > > although if the main thread knew about it, it could ask the thread to > > retry (start over). ?How would any of you do this? ?A callback method > > that the thread can call (synchronizing one-way variables isn't a > > problem)? ?A queue? ?How would the main thread check these things? > > Currently the main thread is polling some simple status variables. ?This > > works, and polling will likely continue to be the simplest and easiest > > way, but simple status variables are very limited. ?Are there any > > pythonic patterns people have developed for this. There is the PyThreadState_SetAsyncExc API. "To prevent naive misuse, you must write your own C extension to call this." From allardwarrink at gmail.com Sat Mar 1 18:17:46 2008 From: allardwarrink at gmail.com (Allard Warrink) Date: Sat, 1 Mar 2008 15:17:46 -0800 (PST) Subject: PIL transparency gradient References: <6e44e95a-2cb0-4026-ad98-f6516e934e27@s37g2000prg.googlegroups.com> <4293dfd7-52aa-463e-b36c-c254a56616c4@s19g2000prg.googlegroups.com> Message-ID: Thanks for the inspiration! This what I did (Using your Python Editor (SPE), I really like to work with SPE, keep up the good work!!): ############################################# import Image, os p = # path to image file im = Image.open(p) # check if im has Alpha band... if im.mode != 'RGBA': im = im.convert('RGBA') # create a vertical gradient... gradient = Image.new('L', (1,255)) for y in range(255): gradient.putpixel((0,254-y),y) # resize the gradient to the size of im... alpha = gradient.resize(im.size) # put alpha in the alpha band of im... im.putalpha(alpha) # Save as png... im.save(os.path.splitext(p)[0] + '.png', 'PNG ############################################# From http Mon Mar 17 04:22:03 2008 From: http (Paul Rubin) Date: 17 Mar 2008 01:22:03 -0700 Subject: String To List References: Message-ID: <7xy78hep5g.fsf@ruckus.brouhaha.com> Girish writes: > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > list with elements 'xyz' and 'abc'. Is there any simple solution for > this?? > Thanks for the help... Be careful about using eval, if the string came from a potentially hostile source. Maybe what you really want is JSON, which has python-like syntax but a bunch of safe parsers. From castironpi at gmail.com Wed Mar 26 21:13:29 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 18:13:29 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> Message-ID: <9d2bcdeb-9076-45a2-bfd1-62a5d0be1ba1@x41g2000hsb.googlegroups.com> On Mar 26, 5:10?pm, bearophileH... at lycos.com wrote: > Sean Davis>Java has a BitSet class that keeps this kind of thing > pretty clean and high-level, but I haven't seen anything like it for > python.< > > If you look around you can usually find Python code able to do most of > the things you want, like (you can modify this code to add the boolean > operations):http://svn.zope.org/*checkout*/Zope3/trunk/src/zope/textindex/ricecod... > (Later I have improved that code for personal use). > > But operations on such bit arrays are very common, and you may need > them to be very fast, so you may use Cython (Pyrex) to write a small > class able to do those things in a much faster way. > Or you can also use Pyd plus an easy 30-lines long D program to write > a class that does those operations very quickly ?(using a dynamic > array of uint, with the help ofwww.digitalmars.com/d/1.0/phobos/std_intrinsic.html > ). > Maybe you can use GMPY numbers as bit arrays too. (I don't know if you > can use NumPy for this using a compact representation of the bits). I believe you're talking about collision detection, and my bartender is entertaining a proof that serial memory can't do it in time. So far the idea I see here is primitive memory couplings that change value based on primitive conditions of other memory. Peripherals including a chipset might show promise, esp. a flash chip, s.l. 'autopersistent' memory. Even if you still poll results, it's still a factor off O( n ). From stephenhorne100 at aol.com Tue Mar 18 11:59:04 2008 From: stephenhorne100 at aol.com (Ninereeds) Date: Tue, 18 Mar 2008 08:59:04 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> Message-ID: <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> Hrvoje Niksic wrote: > This doesn't apply to Python, which implements dict storage as an > open-addressed table and automatically (and exponentially) grows the > table when the number of entries approaches 2/3 of the table size. > Assuming a good hash function, filling the dict should yield amortized > constant time for individual additions. OK. I obviously need to look up open-addressed tables. I thought this was just, in effect, implicit linked listing - ie it still needs a linear search to handle collisions, it just avoids the need for explicitly stored link fields. Perhaps I'm mistaken. As for the growth pattern, each time you grow the table you have to redistribute all the items previously inserted to new locations. Resizes would get rarer as more items are added due to the exponential growth, but every table resize would take longer too since there are more items to move. Inserting n items still intuitively looks like O(n^2) to me. That said, it does remind me of that old exponential realloc trick for array resizing. Same thing, I suppose, since a hash table is basically an array. Maybe my math "intuition" is just wrong. From cmpython at gmail.com Sat Mar 22 03:21:30 2008 From: cmpython at gmail.com (CM) Date: Sat, 22 Mar 2008 00:21:30 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: On Mar 10, 3:27 pm, Stef Mientki wrote: > Stefan Behnel wrote: > > Malcolm Greene wrote: > > >>> My personal experience with wxPython has its ups and downs. Specifically > >>> when it comes to crashes, I wouldn't bet my life on it. > > >> I'm new to Python and getting ready to build a small client based > >> application intended to run on Windows and Linux. I was planning on using > >> wxPython until I saw your comment above. > > > Just to make this sound a bit less like FUD: my last experience with wxPython > > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > > in a project, which crashed a bit too often to do real work with it - and with > > crashing I mean crashing Python, not just showing us its blank traceback. So > > this was definitely a problem either in wxWindows or in wxPython. > > > I have no idea how well it works today, but this has definitely forged my > > opinion on wxPython. > > I'm using wxPython for half a year now, and building quit a large / > heavy GUI with it. > And although it's not so easy as Delphi, it's certainly just as stable > as Delphi. > > If you're talking aboutBoa, that's a completely different story, > I tried it on 3 different machines, and couldn't get it working on any > of them. I thinkBoa/ Dabo / .. are basically good ideas to make programming > wxPython more easy, and probably a lot of people invested a lot of their free time in the > product with the best intentions, but unfortunately these programs are not ready for use by > others (specially not for windows users). Although Boa Constructor is not yet "perfect", I am using it all the time with, in my (very limited) opinion, very good results. One thing is that the download site is not updated frequently, even if SVN is, so you must get it from SVN to get the recent version. Once I got the swing of doing things the Boa-istic way, I can set up pages, with sizers, and with many (but not all) of the currently available wxPython widgets, really quickly. Taking the tutorial, though tedious of course, pays off later. Although there are always more improvements it could have, what is there I find extremely impressive. It can draw bitmaps, allow for notes, shows sizers graphically, allows for timers and other utilities, works with Zope (though I haven't done that), and tons of stuff I'm not even aware of yet. One key is to create any changes to your app by hand but NOT in the sections which indicate that they are Boa-generated and not to be edited (the Designer takes "jurisdiction" over them). Early on I was frustrated by commenting things out in those sections and then having Boa "constrict" and swallow them whole--gone code! But now I just do things in my own def statements, and there are no problems with that. I understand if it is not for everyone, though; these things are a matter of taste to some degree it would seem. But I just figured I'd get a testimonial out there. From bruno.desthuilliers at gmail.com Mon Mar 31 16:37:33 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 31 Mar 2008 13:37:33 -0700 (PDT) Subject: Problem with method overriding from base class References: Message-ID: On 31 mar, 11:05, wrote: > Hello everyone > > I have defined some sort of 'interface class' and a factory function that creates instance objects of specific classes, which implement that interface: > > Interface definition: > *************************************************************************************** > import GUI.webGUI as webGUI > > class EditInterface(webGUI.WebGUI): > def addEntry(self, *p): > raise 'EditInterface.addEntry(): Interface must not be called directly' You want: raise NotImplementedError('EditInterface.addEntry(): Interface must not be called directly') And unless you have some pretty good reason to do so (ie: template methods in EditInterface depending on these methods), you don't even want to bother with all this - just document which methods must be implemented, and let Python raise an AttributeError if they are not. (snip) > Factory: > *************************************************************************************** > def factory(type, *p): > if type == common.databaseEntryTypes[0]: > return module1.Class1(*p); > elif type == common.databaseEntryTypes[1]: > return module2.Class2(*p); > elif type == common.databaseEntryTypes[2]: > return module3.Class3(*p); > elif type == common.databaseEntryTypes[3]: > return module4.Class4(*p); The whole point of polymorphic dispatch in OO is to avoid this kind of mess. What's wrong with instanciating classes directly ? NB : in Python, classes are objects too, so you can pass them around as needed. Also, instanciation is done thu a call to the class object - which makes it just the same as a function call. IOW, you just don't need a clumsy dedicated factory function just to make sure the client code is not too tightly coupled to the exact implementation. > > Implementing Class1: > *************************************************************************************** > import editInterface > > class Class1(editInterface.EditInterface): > > def __init__(self, product, database): > # do something here ... > > def showEntry(self, entry, statustext): > # do something here as well, return some string... > *************************************************************************************** > > Now, when I want to create an Instance of Class1 I do: > > myClass1Instance = factory.factory(common.databaseEntryTypes[1], 'Name', databaseObj ) > Which seems to work fine according to the debugger. But when I do next: > > msg = myClass1Instance.show(firstEntry, '') > > Then the show() method of the class 'EditInterface' is called instead of the show() method of the class 'Class1' !! Reread your code : class Class1 have no 'show' method !-) From gandalf at shopzeus.com Thu Mar 27 12:48:25 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 27 Mar 2008 17:48:25 +0100 Subject: dynimac code with lambda function creation In-Reply-To: <47EBAD07.9010603@gmail.com> References: <47EBAD07.9010603@gmail.com> Message-ID: <47EBCFD9.7050007@shopzeus.com> Justin Delegard wrote: > So I am trying to pass an object's method call to a function that > requires a function pointer. I figured an easy way to do it would be to > create a lambda function that calls the correct method, but this is > proving more difficult than I imagined. > > Here is the function I'm using: > > def objectMethodCallerFunctionCreator(testerObj, method): > exec("y=lambda x: testerObj."+method+"(x)") > return y > You are making it too difficult. What about this: def objectMethodCallerFunctionCreator(testerObj, method): return getattr(testerObj,method) BTW, when you need to return a value (instead of simple code execution) you should use eval() instead of exec(). > Where testerObj is an instance of an object, and method is a string > representing the method to call. The problem is, when I actually run > the function created (y in this case), it tells me it can't find the > symbol testerObj in the global scope. That is true. The 'testerObj' parameter is assigned to the local namespace. The local namespace is created when the function is called. When you call exec, it creates a new namespace. Thus, testerObj is not available inside exec(). But please see above - you do not need exec for this. It is unsafe, slow and really not necessary. > I am assuming this is happening because of the exec() call, but I don't > see another way of calling a variable method on an object. Generally, you should not use exec, eval and their counterparts to access certain attributes of different objects. Same for defining functions, classes, create instances etc. If you still feel that you need to use eval or exec for some reason, drop me an email and hopefully I can help avoiding it. :-) Best, Laszlo From hniksic at xemacs.org Fri Mar 28 12:39:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Mar 2008 17:39:01 +0100 Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: <87od8yolay.fsf@mulj.homelinux.net> skip at pobox.com writes: > I'm having trouble explaining the benefits and tradeoffs of threads > to my coworkers and countering their misconceptions about Python's > threading model and facilities. They all come from C++ and are used > to thinking of multithreading as a way to harness multiple CPU cores > for compute-bound processing. I also encountered, "Python doesn't > really do threads" today. *sigh* Compute-bound processing pretty much excludes a Python-only solution, so any performance considerations should take into account C extensions. Extensions are free to allow other threads to run during CPU-extensive portions of their work, and many of them in fact do so. As long as the extensions are correctly written, you can write your "glue code" in Python and harness the multiple cores using threads, exactly as expected by a C++ programmer. The other use for threads is the case when dealing with blocking APIs that don't support polling. These typically include database APIs and some network APIs (such as the portable host name lookup), but also basic file input/output, if you take into account network file systems. (In theory, file input/output should also be available as asynchronous code, but async IO is low-level and not available in Python.) While threads shouldn't be considered a replacement for event-driven programming, they are certainly useful in such situations. From ericgorr at gmail.com Wed Mar 19 11:32:26 2008 From: ericgorr at gmail.com (Eric) Date: Wed, 19 Mar 2008 08:32:26 -0700 (PDT) Subject: SOAP Server in Python References: <50ccc1be-87ac-4847-b21d-7dfd46379ea4@z38g2000hsc.googlegroups.com> Message-ID: On Mar 19, 10:59 am, dave_mikes... at fastmail.fm wrote: > On Mar 19, 9:19 am, Eric wrote: > > > I am basically looking to do the same thing in Python as easily. > > > Any help or pointers would be appreciated. > > Googling for "python soap" turned up a few hits that may help you. Yes, but I don't have the knowledge to accurately or effectively evaluate the information. I was hoping someone here had some experience writing a SOAP Server using Python and would be willing to share what they know. From arnodel at googlemail.com Sun Mar 23 16:08:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Mar 2008 13:08:41 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> Message-ID: On Mar 23, 5:45?pm, Paul Rubin wrote: > John Nagle writes: > > ? ?What's the cheapest way to test for an empty dictionary in Python? > > > ? ?if len(dict.keys() > 0) : > > I like to think len(dict) is constant time but I haven't checked the code. > Same for bool(dict) (which is what you get when you run "if dict: ..."). It has to be constant time as it is a lower bound for inserts (which average to constant time). -- Arnaud From pavloutefkros at gmail.com Sun Mar 2 16:22:55 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 13:22:55 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: thanks everybody, i've got this to work. i'm not trying to write an actual web server, i'm just using it for some procedures like URL rewriting. From bbxx789_05ss at yahoo.com Mon Mar 31 20:14:51 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 31 Mar 2008 17:14:51 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> Message-ID: <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> On Mar 31, 5:31?pm, castiro... at gmail.com wrote: > Can you have a Python object stored entirely on disk? import cPickle as cp class Dog(object): def __init__(self, name): self.name = name d = Dog("Spot") f = open("data.txt", "w") cp.dump(d, f) f.close() f = open("data.txt") stored_obj = cp.load(f) print stored_obj.name --output:-- Spot From me at privacy.net Sat Mar 15 15:31:03 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 19:31:03 +0000 Subject: Getting started with OS X Leopard In-Reply-To: References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> Message-ID: <47dc23f7$0$32053$da0feed9@news.zen.co.uk> has wrote: > On 15 Mar, 18:05, Mark Carter wrote: >> The sorts of things I want to do are: >> * copy the directory of Finder to the clipboard >> * add a new file to Finder's directory. >> * find out the size of a directory >> * open a file with Aquamacs, regardless of file type, > > If you want to control desktop applications directly, that generally > means using Apple event IPC. The most popular language for application > scripting is traditionally AppleScript, but Apple event bridges exist > for other languages as well. The best of these is appscript; see my > sig for links. Some Finder scripting examples: > > > #!/usr/bin/python > ... > Control AppleScriptable applications from Python, Ruby and ObjC: > http://appscript.sourceforge.net Aah! Many thanks. I see that I had to do easy_install appscript and ensure I use /usr/bin/python I'm off to play with it now. Exciting stuff. I installed the Python from MacPorts. That's not quite what I wanted, because they only have a version for Python 2.4. *Sigh*. MacPorts seems to be getting new ports all the time. The problem is, there also seems to be an aweful lot of ports gathering bitrot. Am I the only one to form the opinion that OS X can sometimes appear to be a bit of a mish-mash? I tried XCode the other day. Seemed a bit complicated, if you ask me. I've tried to like Lisp, too. In the end, Python just rocks. I started out with Glade a short while ago, and I'm impressed how relatively easy it is to create GUIs and add handlers in Python. From castironpi at gmail.com Thu Mar 27 01:13:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 22:13:28 -0700 (PDT) Subject: A question on decorators References: <64vpmnF2dvlccU1@mid.uni-berlin.de> <818b5a6c-636d-4a6e-8fb3-b44e32925ca0@e10g2000prf.googlegroups.com> Message-ID: On Mar 26, 10:02?pm, alex23 wrote: > On Mar 27, 8:30 am, castiro... at gmail.com wrote: > > > I want the * to precede the dot too. ?Let's yack. ?I want to compile > > Python. ?Did you see my new post? ?I like it. ?Do you have any time > > you don't want? ?Time sale. ?Diez is still mad at me. ?I want > > primitives to structure themselves so I can pick up a pen. ?I am > > volunteer primitive structuring. ?Your structure sucks. ?assert > > atmostphere has drags. > > Could you possibly once, just once, put down the Robert Anton Wilson & > the meth pipe before you post? Loud and clear. Copy back to you. From george.sakkis at gmail.com Tue Mar 18 14:47:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 11:47:35 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <29b0d6d3-93e9-4c85-b7e9-6e30f4eb0e2f@x41g2000hsb.googlegroups.com> Message-ID: <4339fff0-3c11-4151-9ea9-a85228648b77@d21g2000prf.googlegroups.com> On Mar 18, 1:49 pm, Mike Orr wrote: > On Mar 16, 6:10 am, Bruce Eckel wrote: > vendors: > > On top of that, the quality of the presentations was unusually low. > > I did feel that. An advanced track would be a good idea. Because > you do need to repeat stuff for the newbies. At least 30% of the > attendees were at PyCon for the first time. Not all first-comers are newbies; I attended for the first time too but I've been using Python for the last four years or so. My overall (totally unscientific) impression was that most attendants had at least a decent grasp of the language. George From castironpi at gmail.com Thu Mar 27 07:45:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:45:40 -0700 (PDT) Subject: what are generators? References: <0410de06-5b4b-4df1-877c-4155042fae82@m44g2000hsc.googlegroups.com> <5875e7c0-6051-4e27-b019-5bae126d457e@p25g2000hsf.googlegroups.com> Message-ID: <955c278f-6555-48fa-a33c-6573d0a1e49e@a1g2000hsb.googlegroups.com> On Mar 27, 6:19?am, castiro... at gmail.com wrote: > On Mar 25, 7:36?pm, Miki wrote: > > > On Mar 24, 8:17?am, castiro... at gmail.com wrote: > > > > I'm looking for a cool trick using generators. ?Know any exercises I > > > can work? > > > Simple one the comes to mind is flattening a list: > > > >>> list(flatten([1, [[2], 3], [[[4]]]])) > > [1, 2, 3, 4] > > I don't think it's well-defined. ?(But this is impossible and useless > calling.) ?CMIIW? > > This is generic: Revise: >>> def f(): ... __gen= None ... def set( gen ): ... nonlocal __gen ... __gen= gen ... yield set ... i= 0 ... while 1: ... i+= 1 ... yield __gen( i ) ... >>> a= f() >>> set= next( a ) >>> set( lambda x: print( x ) ) >>> next( a ) 1 >>> next( a ) 2 >>> next( a ) 3 >>> From python.list at tim.thechases.com Wed Mar 19 12:21:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 11:21:19 -0500 Subject: url validator in python In-Reply-To: <7a27c19d-2e0e-4242-9054-9455f825df8f@i7g2000prf.googlegroups.com> References: <7a27c19d-2e0e-4242-9054-9455f825df8f@i7g2000prf.googlegroups.com> Message-ID: <47E13D7F.8050009@tim.thechases.com> > How can I check the validity of absolute urls with http scheme? > example: > "http://www.example.com/something.html" -> valid > "http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid You could try something like import urllib tests = ( ("http://www.google.com/ + Brite_AB_Iframe_URL + ", False), ("http://www.example.com/something.html", True), ("https://www.google.com/ + Brite_AB_Iframe_URL + ", False), ("https://www.example.com/something.html", True), ) def no_method(url): if ':' in url[:7]: # strip off the leading http: return url.split(':', 1)[1] return url def is_valid_url(url): url = no_method(url) return url == urllib.quote(url) for test_url, expected_result in tests: print "Testing %s\nagainst %s" % ( no_method(test_url), urllib.quote(no_method(test_url)) ) actual_result = is_valid_url(test_url) print 'Pass: %s' % (actual_result == expected_result) print '='*70 The reason for the no_method() is that otherwise it gets normalized to "http%3A//..." so you have to strip off that bit before comparing. -tkc From castironpi at gmail.com Sun Mar 2 10:47:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 07:47:56 -0800 (PST) Subject: Network server- / client-side messaging Message-ID: ''' a website wants to show you different arrangements of framed pictures on a wall. you can click, drag, scale, and rotate pictures in place. you can also drag new pictures in to it. spacing is uniform and settable-- if you rotate one, the readout of the total square area changes along with the new value. you can also select themes from the host that determine formulae for spacing, based on established aesthetics constraints. user clicks a picture and clicks rotate. clientside doesn't want to transmit the whole array back to the server for calculation, but calculation takes a long time, due to the complexity of the spacing formulae. therefore, maintain paralell data on both sides: client for displaying and interfacing, so as not to inform the server of every mouse click, and server side to decrease transmission redundancy and size. do not broadcast every click, but do not broadcast entire interface state. constraint-based best-fit labor distribution is between. changes are sent to the server in the form of the change parameters (perhaps a change object), the layout is updated roughly (still by server-side procedures), and then precisely (along with the sq. ft. readout) when the calculation completes. the interface remains continuously active. Partial cast: ''' class PictureClientSide: def __init__( self, image ): self._image= image def on_scale( self, *params ): change= self.whatchange( scale, *params ) self.tell_the_server( change ) def on_rotate( self, *params ): change= self.whatchange( rotate, *params ) self.tell_the_server( change ) def server_says( self, layoutchange ): renderchange( layoutchange ) class PictureServerSide: def __init__( self, image ): self._image= image def client_says( self, change ): preliminary= self.calculation() preliminary_change= whatchange( preliminary ) tell_the_client( preliminary_change ) completed= self.other_calculation() completed_change= whatchange( completed ) tell_the_client( completed_change ) ''' It's too tangled to proceed. What if a second client 'change' and the first server 'completed' cross paths? Will you cancel the first change explicitly or just drop it? Are you shooting for five-nines quality, or one? What about signal loss and reordering? Will you retransmit an entire message upon suspected loss, or intervalled AYT messages (are you there)? What about an immediate time estimate? How general can the underlying framework be? The rest is a brainstorm. Please critique. ''' class PictureClientSide( ClientSide ): settings= Setting1(), Setting2() @incremental def server_says( self, layoutchange ): renderchange( layoutchange ) class PictureServerSide( ServerSide ): settings= Setting3(), Setting4() ''' We may want to distinguish requests in both directions. Depending on which side takes care of the rotation, server_says may divide based on increment. ''' class PictureClientSide( ClientSide ): @incremental( 1 ) def server_says( self, layoutchange ): renderchange( layoutchange ) @incremental( 2 ) def server_says( self, layoutchange ): renderchange( layoutchange ) ''' Furthermore, you may want the time estimate in its own method. ''' class PictureClientSide( ClientSide ): @incremental( layoutchange, 1 ) def server_says( self, layoutchange ): renderchange( layoutchange ) @incremental( layoutchange, 2 ) def server_says( self, layoutchange ): renderchange( layoutchange ) @message( timeout_message ) def timeout_message( self, etc ): report( etc ) From MartinRinehart at gmail.com Wed Mar 26 14:00:11 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 26 Mar 2008 11:00:11 -0700 (PDT) Subject: Tkinter menus from keyboard References: <462eae55-e4bc-4e8d-aca5-90ca6d873bb6@s19g2000prg.googlegroups.com> Message-ID: Eric Brunel wrote: > BTW, this "standard" is not universal at all: e.g, there is no such > convention on Macs. Thanks for the info. It's standard on Windows and Linux/KDE. GNOME, anyone? From planders at gmail.com Wed Mar 19 11:26:59 2008 From: planders at gmail.com (Preston Landers) Date: Wed, 19 Mar 2008 08:26:59 -0700 (PDT) Subject: Improving datetime References: Message-ID: <60ef7aa5-a387-4129-9c77-6ca91bafc152@f63g2000hsf.googlegroups.com> On Mar 19, 9:12?am, "Nicholas F. Fabry" wrote: > So - where should I propose these changes? ?Here? ?python-dev? ?Should ? > I write up a full PEP or should I just give a more informal outline ? > with code samples? ? My guess is that the python-dev folks would send you here or to the python-ideas mailing list. My suggestion is to give a more informal outline with code samples either here or in python-ideas before proceeding any further. Preston From grante at visi.com Fri Mar 28 12:13:34 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 16:13:34 -0000 Subject: How do I reconnect a disconnected socket? References: Message-ID: <13uq69e8us4oo74@corp.supernews.com> On 2008-03-28, Laszlo Nagy wrote: >> while (1): >> buffer = sock.recv(1024) >> if not buffer: >> dodiscon() >> > > sock.recv(1024) can return zero bytes of data indicating that no data > arrived yet. No, it can't. > It does not mean that you have been disconnected. Yes, that is exactly what it means. >From the recv() man page: RETURN VALUE These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown. -- Grant From mail at timgolden.me.uk Sun Mar 16 03:42:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 07:42:31 +0000 Subject: Spaces in path name In-Reply-To: <47DCC1C4.2010806@timgolden.me.uk> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> Message-ID: <47DCCF67.7050503@timgolden.me.uk> Tim Golden wrote: > joep wrote: >> On Mar 15, 5:42 pm, joep wrote: >>>> http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-spa... >>> Note: this works for subprocess.call but for subprocess.Popen this >>> does not work if there are two arguments in the command line with >>> spaces. Especially, even after trying out many different versions, I >>> never managed to get subprocess.Popen to work, when both the >>> executable and one argument have spaces in the file path. >>> >> Sorry, incomplete sentence >> >> Especially, even after trying out many different versions, I never >> managed to get subprocess.Popen to work '''when command line is given >> as a *list* argument to subprocess.Popen''' >> in the case when both the executable and one argument have spaces in >> the file path. Following up, I'm a little bemused. Below is a command which works on a Win2K Python 2.4 installation (and on WinXP with Python 2.5). I've deliberately chosen something in Program Files and I've copied both the executable and the document so that even the base filenames have embedded spaces, as well as the directory path to get there. (The lines are quite long: you'll probably have to piece them together a bit; that's why I've put an extra line space between each.) subprocess.call ([ r"C:\Program Files\Adobe\Acrobat 5.0\Reader\acro reader.exe", r"C:\Program Files\Adobe\Acr obat 5.0\Reader\plug_ins.donotuse\Annotations\Stamps\abc def.pdf" ]) Can you confirm that something equivalent *doesn't* work on your setup? Or have I misunderstood your point earlier? I'd really like to get to the point where we can definitively state: this works (and possibly: that doesn't). Thanks TJG From godzillaismad at gmail.com Wed Mar 19 08:17:25 2008 From: godzillaismad at gmail.com (Godzilla) Date: Wed, 19 Mar 2008 05:17:25 -0700 (PDT) Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> Message-ID: <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> Hi John, I am using time.clock to calculate the elapsed time. Below is an example of what I was trying to do: import time import thread class elapseTime: def __init__(self, name=''): self.name = name self.timeStamp = None self.checkTimeFlag = False thread.start_new_thread(self.elapsedTime, ()) def setTime(self, state): if state == 1: self.checkTimeFlag = True self.timeStamp = time.clock() else: self.checkTimeFlag = False def elapsedTime(self): while True: curTime = time.clock() if self.checkTimeFlag: if (curTime - self.timeStamp) > 1.0: print "Elapsed time greater than 1 second. Actual Elapsed Time", round(curTime-self.timeStamp, 3) self.checkTimeFlag = False prevTime = curTime time.sleep(0.05) obj = elapseTime() while True: obj.setTime(1) time.sleep(10) But the time.clock() sometimes return a value of between -3.5 to -4.5 seconds backward. Note that not all computers are behaving the same. I have not experience the same problem with the computer at home. From martin.laloux at gmail.com Wed Mar 5 07:40:13 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Wed, 5 Mar 2008 04:40:13 -0800 (PST) Subject: Leopard and MySQL References: Message-ID: <929700bd-89e6-4fb9-ac02-558841cb939e@i12g2000prf.googlegroups.com> There is a macpython list that you can consult at http://www.nabble.com/Python---pythonmac-sig-f2970.html. When you search for your problem http://www.nabble.com/forum/Search.jtp?forum=2970&local=y&query=mysqldb you have the solution http://www.nickshanny.com/2007/10/os-x-105-python-and-mysqldb.html From grante at visi.com Sun Mar 9 00:20:53 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 09 Mar 2008 05:20:53 -0000 Subject: SV: SV: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: <13t6stlnvt6foa9@corp.supernews.com> On 2008-03-08, K Viltersten wrote: >> If you can't/don't look at the source file, >> then comments aren't going to help (except >> in the case of something like docstrings in >> Python). > > I strongly disagree. Now, perhaps we're > talking about different things, here? > Usually, in the header file (C++), Header files are source code. > there won't be any source code, except for method > declarations. Declarations are source code. > A common example: > > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); That's source code. > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. I've no problem with that. > I don't see how this is dislikeable. Please > explain. Perhaps the above IS what you > ment by "docstrings"? http://en.wikipedia.org/wiki/Docstring http://epydoc.sourceforge.net/docstrings.html > For Java, one has the JavaDocs, a great tool, provided one > will comment each method and variable used. > >>> Now, i'm getting the signal that it's done >> in a different way in Python. >> >> I'm not sure how you concluded that from this thread. > > The below, more or less. :) > >> "What I really can't stand are the >> pointy-haired comment blocks at the >> beginnings of C/C++ functions that do >> things like tell you the name and return >> type of the function and list the names >> and types of the parameters." > > Please note that i DO NOT argue against one > way or another. I simply expressed surprise > since i've been tought otherwise earlier > and, maybe, there's a larger picture than > what i've seen this far. As stated before, > snakeology is a very new area to me. Yet. ;) Duplicating information in a comment that is plainly obvious 5 lines below it in the actual source code is a waste of time when the code is written. A week later, the comment will be out of sync with the code and anybody paying attention to the comment will be mislead. I exaggerate (slightly), but in my experience anytime information is duplicated in multiple places it doesn't take very long at all before it's out-of-sync and incorrect in all places except one. -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.com glimpse of the INNER WORKINGS of this POTATO!! From mail at microcorp.co.za Sun Mar 30 09:49:16 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Mar 2008 15:49:16 +0200 Subject: Serial port error statistics - any comparable data? Message-ID: <001d01c8926c$f8ffdc20$03000080@hendrik> "Diez B. Roggisch" wrote: >RS232 is unfortunately as bad as a "protocol" as it can get. I've used >it for communication with a microcontroller for just a few bytes every >second. And it failed miserably, so I needed to implement a protocol on >top of it. We normally do this anyway, except for stuff like menus that are intended for interactive use as setup - doing without on machine to machine comms feels a bit too cowboy... > >The machine spec is totally irrelevant - what is interesting is the >serial hardware you use. Are you by any chance using a >serial2usb-converter? I had nothing but troubles with these. > I have also heard rumours about this, and you have just hardened my admittedly irrational attitude towards them. I have never used one in anger. >if you have the chance, try & attach a machine with legacy rs232 port, >and see if the errors still remain. > >Diez Alas - the port in question is the native legacy motherboard port. If it were windows, it would be COM1... I had hoped that somebody would have done some similar work, so that we could compare notes on the error frequency. It does not seem likely though - If I was not testing the performance of the Lantronix xport device, I would not have kept stats either - it is kind of tedious to sit and watch the fox scroll up the screen for days on end.. It just surprised me to find that the errors were made in the PC's receive. I proved this by short circuiting the xport's receive and transmit at the RS-232 level and gave up after some ten million error free lines. (Most of an afternoon, overnight, and most of the next morning ;-( ) thanks Diez. Then Castironpi wrote: >Transmit observed minus expected to cluster. The "cluster" in all the cases observed is the loss of exactly one character, somewhere from around more or less the middle of the string: "The quick brown fox jumps over the lazy dog 0123456789" Why do you make the assertion that the errors would cluster? >What kind of tables does the input device build? Whatever the kernel and the cpython implementation does to receive the string from a port unblocked with fcntl - and the throw away python script that does the echoing builds the string up with a read(1). And before I get flamed for wasting resources - The read(1) is necessary to be able to run a protocol, later. - Hendrik From fkallgren at gmail.com Sat Mar 22 04:09:07 2008 From: fkallgren at gmail.com (fkallgren) Date: Sat, 22 Mar 2008 01:09:07 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <8c942685-576f-4afb-844a-b825fcc7205c@8g2000hsu.googlegroups.com> On Mar 21, 12:48 pm, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > > /fkallgren Thanks everyone. I now have several attack angles to solve this problem. /fkallgren From grflanagan at gmail.com Mon Mar 10 12:07:19 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Mon, 10 Mar 2008 09:07:19 -0700 (PDT) Subject: defining a method that could be used as instance or static method References: Message-ID: <5d11ea42-3d84-459f-9500-83b4bc0df827@x30g2000hsd.googlegroups.com> On Mar 10, 4:39 pm, Sam wrote: > Hello > > I would like to implement some kind of comparator, that could be > called as instance method, or static method. Here is a trivial pseudo > code of what I would like to execute > > >> class MyClass: > > ... def __init__(self, value): > ... self.value = value > ... def comp(self, compValue): > ... return self.value == compValue.value>> a = MyClass(3) > >> b = MyClass(4) > >> c = MyClass(3) > >> a.comp(b) > False > >> a.comp(c) > > True > > This is actually achieved by MyClass, how could implement it in order > to accept: > > >> MyClass.comp(a, b) > > False > > I would really appreciate a pointer or a way to complete MyClass in > order to fulfill my requirements. Thank you for your attention. > > Sam ------------------------------------------------------ class MyClass(object): ''' >>> a = MyClass(3) >>> b = MyClass(4) >>> c = MyClass(3) >>> a.isequal(b) False >>> a.isequal(c) True >>> MyClass.comp(a, b) False >>> MyClass.comp(a, c) True ''' def __init__(self, val): self.value = val @staticmethod def comp(a, b): return a.value == b.value def isequal(self, b): return self.comp(self, b) if __name__ == '__main__': import doctest options = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE doctest.testmod(optionflags=options) ------------------------------------------------------ From danb_83 at yahoo.com Sat Mar 15 18:48:58 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 15 Mar 2008 15:48:58 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <112a4e45-e413-4fd3-9ecb-94e0b77e8fd1@s12g2000prg.googlegroups.com> On Mar 15, 4:43 pm, Guido van Brakel wrote: > Hello > > I have this now: > > > def gem(a): > > g = sum(a) / len(a) > > return g > > > print gem([1,2,3,4]) > > print gem([1,10,100,1000]) > > print gem([1,-2,3,-4,5]) > > It now gives a int, but i would like to see floats. How can integrate > that into the function? If you add "from __future__ import division" at the top of the file, division will work properly. From lists at cheimes.de Sat Mar 22 09:18:56 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Mar 2008 14:18:56 +0100 Subject: implementing tab completion using python In-Reply-To: <5f733b8e-b869-4f2b-930c-42a044935ad4@u10g2000prn.googlegroups.com> References: <5f733b8e-b869-4f2b-930c-42a044935ad4@u10g2000prn.googlegroups.com> Message-ID: Siddhant schrieb: > Hi. > How can I implement a tab-completing code using Python? > Like for example, I want to design a simple shell (using Python, of > course), which could support tab completion as well. How do I go about > it? http://docs.python.org/lib/module-rlcompleter.html Christian From gagsl-py2 at yahoo.com.ar Mon Mar 24 14:41:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 15:41:51 -0300 Subject: importing package contents from multiple places in PYTHONPATH References: <6c6765d4-e1d7-4ca8-af96-e3c038fc5f3e@i7g2000prf.googlegroups.com> Message-ID: En Mon, 24 Mar 2008 15:06:51 -0300, escribi?: > Hi all, > > I'm new to python, and am trying to determine if it's possible to do > the following... > > I have a directory structure like this, with both 'dir1' and 'dir2' in > my PYTHONPATH > > dir1/ > foo/ > __init__.py > a.py > b.py > > dir2/ > foo/ > __init__.py > a.py > c.py > > I'd like to be able to: > > python> import foo.a, foo.b, foo.c > > I'd hope for package 'foo.a' to come from dir1 since it was first on > the path, with 'foo.b' and 'foo.c' coming form dir1 and dir2 > respectively. Yes. Note that dir2/foo/__init__.py is not used at all and it's just confusing. And a.py (in dir2) won't be found inside the package but any "import a" from c.py will import that one instead of the one at dir1. dir2/foo is just a "bag", not a "package" :) > I understand that python stops once it encounters the first 'foo' > package in PYTHONPATH, but I was wondering if there was a way around > this. I've had some success modifying __path__ in the foo/__init__.py > files, but am unsure if this is the best approach. I think it is the simplest approach, if not the only one... > Perhaps there's a > way to do this with import hooks? Perhaps... But appending a single item to __path__ is simple enough to stop further thinking from my side :) Anyway, why do you want to do that? Can't use a different name for dir2/foo, and perhaps import its modules from inside dir1/foo/__init__.py? -- Gabriel Genellina From mensanator at aol.com Mon Mar 3 20:44:13 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 17:44:13 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: <2aceec91-618d-4e62-9958-e223505bc51f@13g2000hsb.googlegroups.com> On Mar 3, 6:49?pm, Robert Kern wrote: > Mensanator wrote: > > On Mar 3, 4:53 pm, Carl Banks wrote: > >> 3. You must be terribly naive if you expect a freeware program with a > >> version number of 0.5.12 not to have bugs > > > No, but I guess I'm naive thinking that when someone posts a link to > > such a program that he's recommending going and trying it out. That > > is why they're making it available, isn't it? For people to try out > > so they can get free testing? Aren't I doing my part? Should I just > > uninstall it and forget it? > > Finding the issue and reporting it to the sympy bug tracker is commendable. > > Coming here and "un-recommending" sympy before the issue was resolved is not. Bad choice of words I guess. I'll try to keep that in mind. > > -- > 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 gagsl-py2 at yahoo.com.ar Thu Mar 6 15:38:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 18:38:33 -0200 Subject: help on file storage for split multi part download References: Message-ID: En Thu, 06 Mar 2008 14:34:27 -0200, escribi?: > storage class which can write the file splits that are currently being > downloaded to the disk. this is exactly what other download > accelerators do, i guess. > > can this be done using the python file class?? i am pretty good at > handling file uploads (at server end) this is the first time i have to > think the other way round. Uh, unless I misundersand you, a standard file object is enough. First create a file with the required size (open(...,'wb'), seek(n-1), write(chr(0))). For each downloaded chunk you have to know its position in the file; then just seek() and write() it. -- Gabriel Genellina From skip at pobox.com Thu Mar 27 11:49:43 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 27 Mar 2008 10:49:43 -0500 Subject: Is subprocess.Popen completely broken? In-Reply-To: <16651e80803270819t131e01adle1a5b9ed8b8fb976@mail.gmail.com> References: <16651e80803270819t131e01adle1a5b9ed8b8fb976@mail.gmail.com> Message-ID: <18411.49687.719497.174832@montanaro-dyndns-org.local> >> Why should I need to set shell=True? I'm not globbing anything. The >> second case still fails: Jerry> RTFM Thank you. I had. The bits about the type of the args parameter don't mention the shell parameter or that there was any difference between using strings or lists. I missed the reasoning in the discussion on the shell parameter. I think the subprocess module docs probably need some rework. In general, I understand that having a bunch of different ways to execute subprocesses can be confusing. The swiss army knife approach used in the subprocess module is also problematic. Skip From simon at brunningonline.net Fri Mar 28 06:14:17 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 28 Mar 2008 10:14:17 +0000 Subject: Dynamic code problem In-Reply-To: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> Message-ID: <8c7f10c60803280314q320884e8k9993592d688fec83@mail.gmail.com> On Thu, Mar 27, 2008 at 4:13 PM, wrote: > My dynamic code failed at this site http://playwide1.extra.hu/, need > some help thank you. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From me at privacy.net Sat Mar 15 17:35:26 2008 From: me at privacy.net (Mark Carter) Date: Sat, 15 Mar 2008 21:35:26 +0000 Subject: Getting started with OS X Leopard In-Reply-To: References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Message-ID: <47dc411e$0$32041$da0feed9@news.zen.co.uk> martin.laloux at gmail.com wrote: > if you are not satisfied with the native version, why not install the > official version directly from python site > http://www.python.org/download/ (macpython) instead of using that of > macports. It moreover is provided with many utilities > > There is a macpython list that you can consult at > http://www.nabble.com/Python---pythonmac-sig-f2970.html Thanks. Actually, I created my first python appscript (well, "stole" it from a previous poster is more like it) - and it's pretty cool when I combine it with FinderPop. From exxfile at hotmail.com Sat Mar 29 23:15:59 2008 From: exxfile at hotmail.com (pythonnubie) Date: Sat, 29 Mar 2008 20:15:59 -0700 (PDT) Subject: Where can I find : Message-ID: Hi All : Does anyone know where I can find either a book or a website that explains beginning python by actually building a project line by line and explaining it indepth . I am primarily interested in understading flowcontrol as well as syntax . If it was related to netwoprking then that would be a great addition although not required because that is my primary field of interest . All help greatly appreciated ! Mark From cito at online.de Mon Mar 3 17:33:37 2008 From: cito at online.de (Christoph Zwerschke) Date: Mon, 03 Mar 2008 23:33:37 +0100 Subject: First post from a Python newbiw In-Reply-To: <41cfe2c1-51d0-4b15-b9c8-ea3d4389b6cf@e6g2000prf.googlegroups.com> References: <41cfe2c1-51d0-4b15-b9c8-ea3d4389b6cf@e6g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle schrieb: > It's a FAQ: > http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list Somewhere on my todo list I have "read through the whole Python FAQ", but so far never got round doing it. Should probably set it to prio A. -- Christoph From sdeibel at gmail.com Mon Mar 17 01:42:28 2008 From: sdeibel at gmail.com (Stephan Deibel) Date: Sun, 16 Mar 2008 22:42:28 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: On Mar 16, 6:10 am, Bruce Eckel wrote: > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Vendors were guaranteed first pick on lightning talk slots, and > we in the audience, expectantly looking forward to interesting and > entertaining content, again started to feel like things were awfully > commercial. And what seemed like a good idea, moving lightning talks > into plenary sessions with no competition, began to look like another > way to deliver a captive audience to vendors. Yes, this sucked, and I say that as one of the guys that gave a boring vendor lightning talk. I felt obligated to take the slot but probably shouldn't have, or should have talked about something else. The problem was definition of the sponsorships without carefully limiting the benefits that would get out of hand when 3X as many sponsorships were sold as expected (which is what happened). To be fair, I'm not sure I would have foreseen this either. > I know what the argument for the results of Pycon 2008 will be: we > needed the money. My answer: it's not worth it. If this is what you > have to do to grow the conference, then don't. If the choice is > between selling my experience to vendors and reducing the size of the > conference, then cut the size of the conference. Keep the quality of > my experience as the primary decision criteria, or I'll stop coming. I have to admit, I'll keep coming to PyCon even if all the talks suck abysmally as long as there's good hallway time, open space, BoFs, and sprints. ;-) But, yes, lightning talks are also a critical part of the conf, and would be a terrible loss. - Stephan From ebgssth at gmail.com Sun Mar 2 11:23:32 2008 From: ebgssth at gmail.com (js) Date: Mon, 3 Mar 2008 01:23:32 +0900 Subject: Beautiful Code in Python? Message-ID: Hi, Have you ever seen Beautiful Python code? Zope? Django? Python standard lib? or else? Please tell me what code you think it's stunning. From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 20:44:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 01:44:30 -0000 Subject: Classes and modules are singletons? Message-ID: <13suj3u2d17f205@corp.supernews.com> I recall that Python guarantees that module objects are singletons, and that this must hold for any implementation, not just CPython: you can only ever create one instance of a module via the import mechanism. But my google-foo is obviously weak today, I cannot find where the Python language reference guarantees that. Can somebody please point me at the link making that guarantee? (Note: you can create multiple modules with the same name and state using new.module. I don't think that counts, although it may be a good way to win bar bets with your Python buddies.) But what about classes? Are they singletons? Obviously classes aren't Singleton classes, that is, given an arbitrary class C you can create multiple instances of C. But what about class objects themselves? I've found a few odd references to "classes are singletons", but nothing in the language reference. I've done some experimentation, e.g.: >>> import module >>> from module import Class >>> module.Class is Class True but I'm not sure if that's (1) meaningful or (2) implementation-specific. -- Steven From max at alcyone.com Thu Mar 6 21:43:53 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 06 Mar 2008 18:43:53 -0800 Subject: Looking for very light weight template library (not framework) In-Reply-To: References: Message-ID: <2bKdncqgYK93Nk3anZ2dnUVZ_rCtnZ2d@speakeasy.net> Malcolm Greene wrote: > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. ... > Any suggestions appreciated. EmPy may work: http://www.alcyone.com/software/empy/ Your template would look something like: myOutput = """\ The total cost is @invoice.total. This order will be shipped to @invoice.contact at the following address: @invoice.address This order was generated at @time.ctime() """ This could be instrumented with something as simple as: >>> import em, time >>> myOutput = """\ ... ... The total cost is @invoice.total. ... ... This order will be shipped to @invoice.contact at the following ... address: ... ... @invoice.address ... ... This order was generated at @time.ctime() ... """ >>> >>> class Invoice: pass ... >>> invoice = Invoice() >>> invoice.total = "$123.45" >>> invoice.contact = "Jack McCoy" >>> invoice.address = "1 Police Plaza\nNew York City, NY" >>> print em.expand(myOutput, globals()) The total cost is $123.45. This order will be shipped to Jack McCoy at the following address: 1 Police Plaza New York City, NY This order was generated at Thu Mar 6 18:41:58 2008 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There's a reason why we / Keep chasing morning -- Sandra St. Victor From samuel.progin at gmail.com Sun Mar 2 10:55:23 2008 From: samuel.progin at gmail.com (Sam) Date: Sun, 2 Mar 2008 07:55:23 -0800 (PST) Subject: Keeping the console window References: <62vs0iF24tv6jU1@mid.individual.net> Message-ID: <35865c8c-34a0-4a5f-9340-a45bf4dd4a63@d4g2000prg.googlegroups.com> You may use python in interactive mode: $ python -i yourScript.py Or use a blocking readline: $ cat yourScript.py import sys sys.stdin.readline() ++ Sam From castironpi at gmail.com Mon Mar 3 22:14:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 19:14:12 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: <51a14a19-a116-44b7-b94b-c3a0ef6dba54@i29g2000prf.googlegroups.com> On Mar 3, 8:22?pm, "Daniel Fetchinson" wrote: > > What are metaclasses? > > http://www.google.com/search?q=python+metaclass > > HTH, > Daniel Not satisfied. http://en.wikipedia.org/wiki/Metaclass#Python_example That's a limitation. The constructor can omit the superclass call, but it can't have keyword arguments, and can't use AttributeInitType.__call__ with positionals. Subclass AttributeInition, decorate __init__, or decorate class. From gagsl-py2 at yahoo.com.ar Tue Mar 4 22:01:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Mar 2008 01:01:32 -0200 Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: En Wed, 05 Mar 2008 00:30:26 -0200, escribi?: > On Mar 4, 8:11?pm, "Gabriel Genellina" wrote: >> En Tue, 04 Mar 2008 16:45:40 -0200, escribi?: >> >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it >> >> is it makes it. >> >> >>>> from types import FunctionType, MethodType >> >>>> class A( FunctionType ): pass >> > ... >> > Traceback (most recent call last): >> > ? File "", line 1, in >> > TypeError: type 'function' is not an acceptable base type >> >> Use delegation instead of inheritance. This class is almost ? >> indistinguishable from a true function (when used as a method): [... long interactive example ...] > I actually don't believe you-- bar is not bound to an instance when P > is initialized... er, instantiated. However, the evidence indicates > my belief mechanism is faulty... and rather conclusively at that. > If P calls __get__( you ), is p a > gotcha? I didn't cheat, that was an actual Python interactive session. So you'll have to formulate a new theory taking into account the new facts... or read how the descriptor protocol works http://www.python.org/doc/newstyle/ I don't understand your last sentence. -- Gabriel Genellina From castironpi at gmail.com Tue Mar 11 15:49:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 12:49:04 -0700 (PDT) Subject: mulithreaded server References: <0e845694-2788-43e2-b88b-86bbbbe3c7c0@e23g2000prf.googlegroups.com> Message-ID: <0da45d77-65c8-4de2-8b70-dd22a7a6998b@e10g2000prf.googlegroups.com> > > >In the above program, why there is an unhandeled exception ??? > > > Just a guess. You should really include the traceback when you ask a > > question like this. > > It's not a traceback error. It's an unhandeled exception. Have a look at this: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5cbf90133a6ffaca/ It gives you a console with several threads running that you send functions to call to. Then it connects to a socket on one of them, serving on the other. From guillermo.listas at googlemail.com Sun Mar 9 08:20:41 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Sun, 9 Mar 2008 05:20:41 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> >A protocol is just an interface that an object agrees to implement. In >your case, you would state that every object stored in your special >dict must implement the to_tagged_value method with certain agreeable >semantics. Hm... I've searched about the implementation of protocols and now (I believe) I know how to implement the iterable protocol, for instance, but have no clue about how to define my own... I'm surely not thinking the right way, but I don't seem to be able to wrap my head around the implementation details of "custom" protocols... Is it just a matter of extending the different object classes (dict, list, tuple...)? Where do you put the interface/protocol code? :-? Regards, Guillermo From castironpi at gmail.com Mon Mar 17 18:43:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 15:43:15 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> Message-ID: <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> On Mar 17, 8:16?am, "Gabriel Genellina" wrote: > En Sun, 16 Mar 2008 22:27:28 -0200, escribi?: > > > Specifically, before the prompts. ?Where does the prompt write come > > from; why doesn't it honor my settings of sys.stdout and sys.stderr? > > The interactive interpreter uses directly the C predefined streams stdout ? > and stderr. Can I allocate a second console window, so I can place certain output to that directly, and leave the original streams alone? I tried some things in subprocess (Py 3a3 /WinXP) but they failed. I don't know if it's supposed to be possible though, so I didn't press very hard or keep the code. If it is, I can go repro where it went south. Is it? From francois.petitjean at bureauveritas.com Thu Mar 6 12:28:17 2008 From: francois.petitjean at bureauveritas.com (francois.petitjean at bureauveritas.com) Date: Thu, 6 Mar 2008 18:28:17 +0100 Subject: How to clear a list (3 ways). Message-ID: Consider the following code : #!/usr/bin/env python # -*- coding: latin_1 -*- """ container.py how to clear a container """ class Container(object): def __init__(self): self.elts = {} self.parts = [] def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts = [] # (1) # self.parts[:] = [] # (2) # del self.parts[:] # (3) def __len__(self): return len(self.parts) def add_predicate(self, part): """return True if part should be added (to override)""" return True def add(self, part): """return True if part is added""" res = self.add_predicate(part) if res: self.parts.append(part) self.elts[str(part)] = part # or wahtever return res def replace_parts(self, values): """return True if all values are added/replaced""" acceptable = all(map(self.add_predicate, values)) # FIXME itertools.imap ? if not acceptable: return acceptable self.parts[:] = values # TODO elts return acceptable Container1 = Container class Container2(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts[:] = [] # (2) class Container3(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) del self.parts[:] # (3) Solution (1) is somewhat broken (see the test_container.rst hereafter) but often used. For instance in configobj we have def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] self.comments = {} self.inline_comments = {} self.configspec = {} What idiom do you use (and prefer) ? test_container.rst can be used like this : >>> import doctest >>> doctest.testfile('test_container.rst', encoding='latin_1') (nfails, ntests) is printed. =================== test_container.rst =================== >>> from container import Container1, Container2, Container3 >>> cont1 = Container1() >>> cont1.add(1) True >>> cont1.add(2) True >>> cont1.add(3) True >>> parts = cont1.parts >>> parts [1, 2, 3] The client has cached the parts attribute. Solution (1) is not robust, is the parts attribute in the public API ? >>> cont1.clear() >>> parts [1, 2, 3] >>> cont1.parts, parts ([], [1, 2, 3]) We now have two different objects. >>> cont2 = Container2() >>> cont2.add(21) True >>> cont2.add(22) True >>> cont2.add(23) True >>> parts2 = cont2.parts >>> parts2 [21, 22, 23] >>> cont2.clear() >>> parts2 [] >>> cont1.parts, parts ([], [1, 2, 3]) >>> cont3 = Container3() >>> cont3.add(31) True >>> cont3.add(32) True >>> parts3 = cont3.parts >>> cont3.add(33) True >>> parts3 [31, 32, 33] >>> cont3.clear() >>> parts3 [] Test de replace_parts >>> cont3 = Container3() >>> len(cont3) 0 >>> parts3 = cont3.parts >>> cont3.add(30) True >>> parts3 [30] >>> cont3.replace_parts( (31, 32, 33) ) True >>> parts3 [31, 32, 33] >>> Regards. NOTICE: This message contains information which is confidential and the copyright of our company or a third party. If you are not the intended recipient of this message please delete it and destroy all copies. If you are the intended recipient of this message you should not disclose or distribute this message to third parties without the consent of our company. Our company does not represent, warrant and/or guarantee that the integrity of this message has been maintained nor that the communication is free of virus, interception or interference. The liability of our company is limited by our General Conditions of Services. Nota : Ce message contient des informations confidentielles propri?t? de notre soci?t? et/ou d'un tiers. Si vous n??tes pas parmi les destinataires d?sign?s de ce message, merci de l'effacer ainsi que toutes ses copies. Si vous ?tes parmi les destinataires d?sign?s de ce message, pri?re de ne pas le divulguer ni de le transmettre ? des tiers sans l?accord de notre soci?t?. Notre soci?t? ne peut garantir que l?int?grit? de ce message a ?t? pr?serv?e ni que la pr?sente communication est sans virus, interception ou interf?rence. La responsabilit? de notre soci?t? est limit?e par nos Conditions G?n?rales de Services. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Thu Mar 13 11:55:21 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 13 Mar 2008 08:55:21 -0700 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> Message-ID: k.i.n.g. wrote: > I think I am not clear with my question, I am sorry. Here goes the > exact requirement. > > We use dd command in Linux to create a file with of required size. In > similar way, on windows I would like to use python to take the size of > the file( 50MB, 1GB ) as input from user and create a uncompressed > file of the size given by the user. > > ex: If user input is 50M, script should create 50Mb of blank or empty > file You mean all zero bytes? Python cannot guarantee that the system will not compress such a file. For testing data transfer rates, random data is a usually a better choice. -- --Bryan From n.s.buttar at gmail.com Fri Mar 7 04:08:14 2008 From: n.s.buttar at gmail.com (Navtej Singh) Date: Fri, 7 Mar 2008 14:38:14 +0530 Subject: Python GDB Wrapper In-Reply-To: References: <47d0f228$0$17725$9b622d9e@news.freenet.de> Message-ID: <1090e4100803070108j7599f90ch26affb6c1d481d20@mail.gmail.com> Raja, Check this http://fusil.hachoir.org/trac/wiki/Ptrace [gdb.py] On Fri, Mar 7, 2008 at 2:11 PM, Raja wrote: > On Mar 7, 1:21 pm, Raja wrote: > > Hi All, > > Thanks for replies. Daniel- I am looking at just a wrapper > > around GDB. I dont want to emulate the functionalities of GDB but > > instead use them in python scripting. > > Martin - Misc/gdbinit looks promising. Thanks a lot. > > > > Thanks, > > Raja. > > > > On Mar 7, 12:43 pm, "Martin v. L?wis" wrote: > > > > > > Has anyone does this before ? Even some basic idea or code as to how > > > > to proceed would be great. > > > > > Have you seen Misc/gdbinit? > > > > > Regards, > > > Martin > > Hi All, > Marting- I looked at the Misc/gdbinit but what I want is a Python > module which wraps around GDB and exposes its functionality, which has > some methods in it like pystack to which if I give the arguments as > program name and arguments displays the stack trace of that particular > program . > > Thanks, > Raja. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Wed Mar 12 10:52:03 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 12 Mar 2008 15:52:03 +0100 Subject: agg (effbot) In-Reply-To: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> References: <0ffd79b8-dfea-4890-be23-99dd02de5291@m36g2000hse.googlegroups.com> Message-ID: <63q90kF268j23U1@mid.uni-berlin.de> fraleysinger at gmail.com wrote: > Downloaded to Knoppix 5.1: > : > aggdraw-1.2a3-20060212.tar.gz > > Followed README. Wouldn't compile. [...] Try shegabittling the frotz first. If that doesn't help, please post the output of the compile command that threw the error. -- Gerhard From Robert.Bossy at jouy.inra.fr Fri Mar 7 10:39:21 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 07 Mar 2008 16:39:21 +0100 Subject: problem with join In-Reply-To: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: <47D161A9.7090004@jouy.inra.fr> nodrogbrown wrote: > hi > i am using python on WinXP..i have a string 'folder ' that i want to > join to a set of imagefile names to create complete qualified names so > that i can create objects out of them > > folder='F:/brown/code/python/fgrp1' > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > filenameslist=[] > for x in filenms: > myfile=join(folder,x) > filenameslist.append(myfile) > > now when i print the filenameslist i find that it looks like > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > is there some problem with the way i use join? why do i get \\ infront > of the basename? > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', > os.path.join() http://docs.python.org/lib/module-os.path.html#l2h-2185 vs. string.join() http://docs.python.org/lib/node42.html#l2h-379 RB From miki.tebeka at gmail.com Wed Mar 12 18:30:48 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 12 Mar 2008 15:30:48 -0700 (PDT) Subject: How to parse this timestamp? References: Message-ID: <06baa795-ad19-4c80-ad86-889f9a0701f8@s37g2000prg.googlegroups.com> Hello, > [19-Aug-2007 07:38:43+216ms NZST] > > How can I parse them? ?I don't see any way to build a strftime() > format string that can handle the +216ms part. The best I can see is > tearing it all apart with a regex, but I'm trying to avoid that pain > if I can. > > (PS: I have no clue why google groups thinks it should put > "gnu.gcc.help" on the from line) Just zap the end and use time.strptime: >>> s = '19-Aug-2007 07:38:43+216ms NZST' >>> strptime(re.sub("\+\d{3}ms [A-Z]{4}", "", s), "%d-%b-%Y %H:%M:%S") (2007, 8, 19, 7, 38, 43, 6, 231, -1) >>> HTH, -- Miki http://pythonwise.blogspot.com From sjmachin at lexicon.net Tue Mar 25 08:00:08 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 25 Mar 2008 05:00:08 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: <534cd01c-3d49-4dd8-ba04-71551cdd46d3@d21g2000prf.googlegroups.com> On Mar 25, 10:44 pm, Tzury Bar Yochay wrote: > given two classes: > > class Foo(object): > def __init__(self): > self.id = 1 > > def getid(self): > return self.id > > class FooSon(Foo): > def __init__(self): > Foo.__init__(self) > self.id = 2 > > def getid(self): > a = Foo.getid() > b = self.id > return '%d.%d' % (a,b) > > While my intention is to get 1.2 I get 2.2 > I would like to know what would be the right way to yield the expected > results Post the code that you actually executed. What you have shown lacks the code to execute it ... but the execution will fail anyway: a = Foo.getid() TypeError: unbound method getid() must be called with Foo instance as first argument (got nothing instead) From fredrik at pythonware.com Sun Mar 30 12:45:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Mar 2008 18:45:51 +0200 Subject: "Soup Strainer" for ElementSoup? In-Reply-To: <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> <47e87a88$0$36376$742ec2ed@news.sonic.net> <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> Message-ID: erikcw wrote: > I'm parsing real-world HTML with BeautifulSoup and XML with > cElementTree. > > I'm guessing that the only benefit to using ElementSoup is that I'll > have one less API to keep track of, right? Or are there memory > benefits in converting the Soup object to an ElementTree? It's purely an API thing: ElementSoup loads the entire HTML file with BeautifulSoup, and then uses the resulting BS data structure to build an ET tree. The ET tree doesn't contain cycles, though, so you can safely pull out the strings you need from ET and throw away the rest of the tree. > Any idea about using a Soup Strainer with ElementSoup? The strainer is used when parsing the file, to control what goes into the BS tree; to add straining support to ES, you could e.g. add a parseOnlyThese option that's passed through to BS. From __peter__ at web.de Mon Mar 31 06:15:21 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Mar 2008 12:15:21 +0200 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: George Sakkis wrote: > On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote: >> Steven D'Aprano wrote: >> > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: >> >> >> Second try: >> > ... >> >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing >> >> with each call. But it's the only way I could find, at least without >> >> changing the code template used by timeit. >> >> > Eeek. Talk about namespace pollution. >> >> > Thanks for the effort, but if that's the only solution, I think the >> > solution is worse than the problem! >> >> > Perhaps it's time for me to take a different approach. >> >> [snip] >> >> Maybe the following enhancement of timeit would be worthwhile? > > [snip] > > > That would be great. I sometimes avoid timeit altogether because > setting up the environment is so cumbersome. Can you post the patch to > bugs.python.org so it doesn't get lost ? Looking into http://svn.python.org/view/python/trunk/Lib/timeit.py?rev=54953&view=markup I discovered that the Python developers took a different approach and timeit now allows callables for setup and statement: >>> def f(): print 42 ... >>> timeit.Timer(f).repeat(1, 1) 42 [3.3855438232421875e-05] So my patch is probably a case of instant obsolescence... Peter From justjpm at aol.com Sat Mar 22 09:38:41 2008 From: justjpm at aol.com (Jim) Date: Sat, 22 Mar 2008 06:38:41 -0700 (PDT) Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> <13u3660kfnhq412@corp.supernews.com> <74cdd195-2bfa-4548-a16e-bf14c6b07b50@p73g2000hsd.googlegroups.com> <13u5ra4fdbp7235@corp.supernews.com> Message-ID: On Mar 20, 7:03 pm, Steven D'Aprano wrote: > On Thu, 20 Mar 2008 10:26:14 -0700, Jim wrote: > > The program is my first and I'm not a programmer so it will take me some > > time to get your recommendation to work. So far the program runs after I > > added code based on your example but the program still aborts and none > > of the code ("Temporary failure, Skip/Halt/try Again?" or "Unknown > > response, boo hiss to you!") in your example is displayed. > > Try replacing the line: > > exceptURLError, e: > > with: > > except urllib2.URLError, e: > > and see if that helps. > > -- > Steven Steven, Got it to work with your example see code below. The process continued bypassing the records when exceptions occurred. My process displayed 'print here 1' then 'print here 4' and continued process with next record without aborting. What should be displayed, if anything, with the line "response = raw_input("Temporary failure, Skip/Halt/try Again?")" as I didn't see anything? Thanks for your help Jim Code: except urllib2.URLError, e: print "here 1" if e.errno == 10053: response = raw_input("Temporary failure, Skip/Halt/try Again?") response = response.lower().strip() if response in ('h', 'halt'): print "here 2" break elif response in ('a', 'again', 't', 'try', 'try again'): print "here 3" continue elif response in ('', 's', 'skip'): print "here 4" lines -= 1 continue else: print "Unknown response, boo hiss to you!" raise From francois.petitjean at bureauveritas.com Fri Mar 7 06:39:05 2008 From: francois.petitjean at bureauveritas.com (francois.petitjean at bureauveritas.com) Date: Fri, 7 Mar 2008 12:39:05 +0100 Subject: How to clear a list (3 ways). Message-ID: (second try with an enhanced version) Executive summary : What idiom do you use for resetting a list ? lst = |] # (1) lst[:] = [] # (2) del lst[:] # (3) Consider the following code : #!/usr/bin/env python # -*- coding: latin_1 -*- """ container.py how to clear a container """ class Container(object): def __init__(self): self.elts = {} self.parts = [] def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts = [] # (1) # self.parts[:] = [] # (2) # del self.parts[:] # (3) def __len__(self): return len(self.parts) def add_predicate(self, part): """return True if part should be added (to override)""" return True def add(self, part): """return True if part is added""" res = self.add_predicate(part) if res: self.parts.append(part) self.elts[str(part)] = part # or wahtever return res def replace_parts(self, values): """return True if all values are added/replaced""" acceptable = all(map(self.add_predicate, values)) # FIXME itertools.imap ? if not acceptable: return acceptable self.parts[:] = values # TODO elts return acceptable Container1 = Container class Container2(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) self.parts[:] = [] # (2) class Container3(Container): def clear(self): self.elts.clear() # for a dictionary it's clear :-) del self.parts[:] # (3) Solution (1) is somewhat broken (see the test_container.rst hereafter) but often used. For instance in configobj we have def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] self.comments = {} self.inline_comments = {} self.configspec = {} Solution (2) does not suffer the same problem, and (3) has the advantage of not building an empty list. What idiom do you use (and prefer) ? test_container.rst can be used like this : >>> import doctest >>> doctest.testfile('test_container.rst', encoding='latin_1') (nfails, ntests) is printed. =================== test_container.rst =================== >>> from container import Container1, Container2, Container3 >>> cont1 = Container1() >>> cont1.add(1) True >>> cont1.add(2) True >>> cont1.add(3) True >>> parts = cont1.parts >>> parts [1, 2, 3] The client has cached the parts attribute. Solution (1) is not robust, is the parts attribute in the public API ? >>> cont1.clear() >>> parts [1, 2, 3] >>> cont1.parts, parts ([], [1, 2, 3]) We now have two different objects. >>> cont2 = Container2() >>> cont2.add(21) True >>> cont2.add(22) True >>> cont2.add(23) True >>> parts2 = cont2.parts >>> parts2 [21, 22, 23] >>> cont2.clear() >>> parts2 [] >>> cont1.parts, parts ([], [1, 2, 3]) >>> cont3 = Container3() >>> cont3.add(31) True >>> cont3.add(32) True >>> parts3 = cont3.parts >>> cont3.add(33) True >>> parts3 [31, 32, 33] >>> cont3.clear() >>> parts3 [] Test de replace_parts >>> cont3 = Container3() >>> len(cont3) 0 >>> parts3 = cont3.parts >>> cont3.add(30) True >>> parts3 [30] >>> cont3.replace_parts( (31, 32, 33) ) True >>> parts3 [31, 32, 33] >>> Regards. NOTICE: This message contains information which is confidential and the copyright of our company or a third party. If you are not the intended recipient of this message please delete it and destroy all copies. If you are the intended recipient of this message you should not disclose or distribute this message to third parties without the consent of our company. Our company does not represent, warrant and/or guarantee that the integrity of this message has been maintained nor that the communication is free of virus, interception or interference. The liability of our company is limited by our General Conditions of Services. Nota : Ce message contient des informations confidentielles propri?t? de notre soci?t? et/ou d'un tiers. Si vous n??tes pas parmi les destinataires d?sign?s de ce message, merci de l'effacer ainsi que toutes ses copies. Si vous ?tes parmi les destinataires d?sign?s de ce message, pri?re de ne pas le divulguer ni de le transmettre ? des tiers sans l?accord de notre soci?t?. Notre soci?t? ne peut garantir que l?int?grit? de ce message a ?t? pr?serv?e ni que la pr?sente communication est sans virus, interception ou interf?rence. La responsabilit? de notre soci?t? est limit?e par nos Conditions G?n?rales de Services. -------------- next part -------------- An HTML attachment was scrubbed... URL: From musiccomposition at gmail.com Mon Mar 10 22:47:59 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 10 Mar 2008 19:47:59 -0700 (PDT) Subject: wxPython/wxWidgets ok for production use ? References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> <47D54F11.4020508@behnel.de> <47D587F9.3050703@behnel.de> Message-ID: <250c1e21-7a49-4a94-8752-e1c69067d614@n36g2000hse.googlegroups.com> On Mar 10, 2:11 pm, Stefan Behnel wrote: > Malcolm Greene wrote: > >> My personal experience with wxPython has its ups and downs. Specifically > >> when it comes to crashes, I wouldn't bet my life on it. > > > I'm new to Python and getting ready to build a small client based > > application intended to run on Windows and Linux. I was planning on using > > wxPython until I saw your comment above. > > Just to make this sound a bit less like FUD: my last experience with wxPython > dates back a couple of years (2004/5?), but back then, we used BoaConstructor > in a project, which crashed a bit too often to do real work with it - and with > crashing I mean crashing Python, not just showing us its blank traceback. So > this was definitely a problem either in wxWindows or in wxPython. > > I have no idea how well it works today, but this has definitely forged my > opinion on wxPython. > > > Any suggestions on an alternative Python client-side GUI library (pyQT ?) > > or tips on where I can find out more about wxPython/wxWidget problems? > > The only other GUI library I used was PyQT3. To me, it has proven to be very > stable, pretty easy to use and feature rich. And from what I read about it, > PyQT4 is supposed to be another lot better and has removed the few API quirks > I found at the time (AFAIR, it finally returns plain Python strings from the > API, for example). No, it still returns QStrings, so it doesn't break tons of code. I just always convert it to unicode if I'm going to keep the string around. > > Stefan From jeffrey at fro.man Thu Mar 27 11:04:43 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 27 Mar 2008 08:04:43 -0700 Subject: Is subprocess.Popen completely broken? References: Message-ID: <13undsbqop54h4b@corp.supernews.com> Skip Montanaro wrote: > I am trying to replace os.system calls with subprocess.Popen. ?This simple > example fails miserably: > >>>> proc = subprocess.Popen ("ls /tmp") Popen expects a list of program arguments. When passed a single string instead of a list, as in your example, it assumes that the string is the command, and looks for an executable named "ls /tmp", which of course does not exist. Split your command into a list of separate parameters, with the executable as the first parameter, and it will work: >>> subprocess.Popen(['ls', '/tmp']) >>> (ls output here) Jeffrey From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:53:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:53:57 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> <75c10b67-c971-4db4-be13-26cafd24e9d2@d4g2000prg.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 00:39:58 -0300, escribi?: > First, thanks for the help. You have solved one problem but created a > new one. Isn't that always how it works? Ouch - yes, sometimes :( > So I copied over the dir, and now I get this error when trying to > import simplejson: > > > The following error occurred while trying to extract file(s) to the > Python egg > cache:[error messages snipped] > So I went looking for that egg...the following exists in my frameworks > dir: > > simplejson-1.8.1-py2.5-macosx-10.3-fat.egg > > I hate eggs...I am stuck again. Any ideas? I'd remove the egg and all references to it from easy_install.pth, and use the simplejson directory from the source distribution (.tar.gz), as I suggested on a previous message. -- Gabriel Genellina From ptmcg at austin.rr.com Mon Mar 24 23:22:35 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 20:22:35 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> <34b46ea7-7c87-4742-9d67-0a39e5daf983@e23g2000prf.googlegroups.com> Message-ID: <4e3f9a3d-bf3f-479e-a00d-37a00f95133e@m44g2000hsc.googlegroups.com> On Mar 24, 7:56?pm, Tess wrote: > > Anyhow, a simple regex took care of the issue in BS: > > for i in soup.findAll(re.compile('^p|^div'),align=re.compile('^center| > ^left')): > ? ? print i > But I thought you only wanted certain combinations: "My goal is to extract all elements where the following is true:

and

." Wont this solution give you false hits, such as

and

? -- Paul From gagsl-py2 at yahoo.com.ar Sat Mar 15 05:11:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 07:11:20 -0200 Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Message-ID: En Fri, 14 Mar 2008 17:23:14 -0200, Amit Gupta escribi?: > On Feb 20, 8:51 pm, Miki wrote: >> Hello Amit, >> >> > python testname.py : the unitests runs as usual and I get the >> > following results: >> > ---------------------------------------------------------------------- >> > Ran 2 tests in 0.024s >> >> > OK >> > -------------------------------------------------------------------- >> >> > However, if I do "python -mpdbtestnames.py": I get >> > ython -mpdbtestnames.py> /s/nd6/amit/pyiglu/testnames.py(1)() >> >> > -> importunittest >> > (Pdb) c >> >> > ---------------------------------------------------------------------- >> > Ran 0 tests in 0.000s >> > > So What do I do, if my testcase if failing because of an uncaught > exception and I want to run it in pdb. Run your script with python -i testname.py If an exception occur, you'll get the Python prompt. Execute: py> import pdb py> pdb.pm() to enter pdb "post-mortem". -- Gabriel Genellina From waldemar.osuch at gmail.com Thu Mar 27 03:18:55 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Thu, 27 Mar 2008 00:18:55 -0700 (PDT) Subject: How to convert latex-based docs written with Python 2.5 to 2.6 framework References: Message-ID: On Mar 26, 1:37 pm, Michael Str?der wrote: > HI! > > I had a look on how Doc/ is organized with Python 2.6. There are files with > suffix .rst. Hmm... > > I'm maintaing existing docs for python-ldap which I might have to convert to > the new concept in the long run. What's the recommended procedure for doing > so? Any pointer? > > Ciao, Michael. I found the original python docs converter here: http://svn.python.org/projects/doctools/converter/ Unfortunately it is very specific to the Python docs :) I did try to run it on python-ldap .tex files and I was partially successful. It has produced a skeleton of the docs in the new format. After couple of hours of manual conversion I got far enough to actually see some results. Whatever I did is definitely not in finished state but it could be a start. Send me an off-line email if you are interested in what I have got so far. Waldemar From gagsl-py2 at yahoo.com.ar Sun Mar 2 23:09:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 02:09:13 -0200 Subject: How to subclass a built-in int type and prevent comparisons References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: En Fri, 29 Feb 2008 19:00:06 -0200, Bronner, Gregory escribi?: > I'm trying to create a type-safe subclass of int (SpecialInt) such that > instances of the class can only be compared with ints, longs, and other > subclasses of SpecialInt -- I do not want them to be compared with > floats, bools, or strings, which the native int implementation supports. > > Obviously, I could overload __lt_, __eq__, __le__, etc, and write a > bunch of boilerplate code. > > Should this code throw an exception if the types are not comparable? > What would I lose by doing that? > > def __gt__(self, other): > if(other is self): > return False > if(self.__isComparable(other)): > return int(self)>int(other) > else: > raise ValueError(str(self) +" and "+ str(other) > +" are not comparable") I think that the easiest way is to write __cmp__ similar to your code above, and then redefine __gt__, __ge__ etc based on that. __gt__ = lambda self, other: self.__cmp__(other)>0 Note that you have to override a lot of methods too; if x is a SpecialInt instance, abs(x) or x+1 will return a plain integer instead. > Is this code likely to be efficient? Unless you implement the above in a C extension, certainly it will run much slower than the original int implementation. But measure how much this is going to affect you. -- Gabriel Genellina From paul at boddie.org.uk Sun Mar 30 14:32:05 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Mar 2008 11:32:05 -0700 (PDT) Subject: Licensing References: Message-ID: <418402d4-3ff8-4693-ae01-578f0d6d0160@e23g2000prf.googlegroups.com> On 29 Mar, 20:24, DS wrote: > I'm pretty sure this is the wrong place to ask, but I'm hoping someone > will point me in the right direction. > > I'm getting ready to publish a first open-source project written in > python. I am planning to use GPLas the license. However, in my code, > there is a function that I like from Python Cookbook. I would like to > use it, although I could certainly write a less elegant version that > would do the same thing. Note that the Python Cookbook says this about licensing: "Except where otherwise noted, recipes in the Python Cookbook are published under the Python license." The link is incorrect, but I presume they mean this licence: http://www.python.org/psf/license/ It's generally not recommended to use this licence for anything other than Python because it mentions the need to reproduce the Python copyright statement in derived works, which would be nonsense for anything which isn't the Python distribution. However, one can infer that the copyright notice specific to the software concerned should be reproduced, and this is what the original CWI licence says. Of course, if a different licence is mentioned on the specific recipe you're using, you have to observe the terms mentioned in that licence instead. > So, my options appear to be: > 1. Don't use it. > 2. Use it with no comment -- that doesn't seem right. > 3. Use it with remarks in the code that acknowledge the source. > 4. Provide a separate licensing page for that function > along with the GPL for my code. > > What is the appropriate course of action here? I'm thinking #3 is > probably ok. How do others deal with this in an honorable way? In the > book, it appears that they are saying they don't really care unless > there is some massive use. You just need to do what's necessary to satisfy the licence applied to the code you're using. If that's the Python licence, I would imagine that reproducing the copyright statement and licence details would be sufficient, even if your own work is GPL-licensed. What I've done when I've released work which incorporates other work (itself available under a permissive licence) is to include the copyright statements and the licence text for that other work, but I've made it clear in the licensing information that the derived work (my code incorporating the other code) is available under the specific licence I've chosen, noting that the other work was made available under a different licence. So I suppose that #4 is the closest, but you should be able to assert that the entire work is GPL-licensed unless the recipe isn't licensed in a GPL-compatible way, which would open up a range of other issues that you hopefully won't have to deal with. ;-) Paul P.S. This isn't anything close to legal advice, so please take other opinions into account. ;-) From jeff at schwabcenter.com Fri Mar 7 12:11:57 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 07 Mar 2008 09:11:57 -0800 Subject: Regarding coding style In-Reply-To: <63d80bF273nraU1@mid.individual.net> References: <63d80bF273nraU1@mid.individual.net> Message-ID: K Viltersten wrote: > I've been recommended reading of: > http://www.python.org/dev/peps/pep-0008/ > and in there i saw two things that i need to get elaborated. > > > 1. When writing English, Strunk and White apply. > > Where can i download it? Am i actually > expected to read the whole book? It's a short book, and worth your time. Searching does turn up free downloads, but I recommend the illustrated version (of which I own a copy). http://www.libraryshop.org/elofstilbywi.html > How many people actually do aply it? The problem is how many people don't. > 2. You should use two spaces after a sentence-ending period. > > For heavens sake, why? I've always been obstructed by the double blanks > but tolerated them. Now, that i read that > it actually is a recommendation, i need to ask about the purpose. (a) It makes the ends of sentences more visually obvious. (b) It makes text easier to parse reliably from scripts. (c) Some text-editors can navigate such sentences out of the box, whereas others cannot. (I recall this limitation with Emacs' text-editing major mode, though it may have been fixed since then; I switched to Vim about five years ago.) From keios.titan at gmail.com Thu Mar 6 14:41:57 2008 From: keios.titan at gmail.com (keios.titan at gmail.com) Date: Thu, 6 Mar 2008 11:41:57 -0800 (PST) Subject: Exploring Attributes and Methods References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: <67ad6ef7-5cbd-48d4-89cb-580e865c73f3@e10g2000prf.googlegroups.com> On Mar 7, 12:30 am, "Terry Reedy" wrote: > wrote in message > > news:6018ff8f-3372-42c2-9a2e-5ca996744d5b at e6g2000prf.googlegroups.com... > | Hi, > | Is there a python command that allows me to extract the names (not > | values) of the attributes of a class. > | > | example > | > | Class Sample: > | fullname = 'Something' > | > | How can I know that this class has an attribute called 'fullname'? > > >>> class C: a = 1 > >>> dir(C) > > ['__doc__', '__module__', 'a'] Thank You From DustanGroups at gmail.com Thu Mar 13 18:39:51 2008 From: DustanGroups at gmail.com (Dustan) Date: Thu, 13 Mar 2008 15:39:51 -0700 (PDT) Subject: This actually works. References: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> Message-ID: <8d64b77b-b466-4b5f-98c7-6921a4fa1372@p25g2000hsf.googlegroups.com> On Mar 13, 3:16 pm, troyj1... at gmail.com wrote: > not self.believe > programming.screw() > > self.serious; this.works > > make_money(EASY) > anyone.can_do(this) you.screw() self.thank(God, encapsulation) not self.want_to_know(you.screw.func_code) programming.is_good From rridge at caffeine.csclub.uwaterloo.ca Wed Mar 19 13:15:08 2008 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 19 Mar 2008 13:15:08 -0400 Subject: Anomaly in time.clock() References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> <2fe4283a-3714-4fda-bc79-18087bd51fa0@h11g2000prf.googlegroups.com> <306f60ee-31b4-49f6-a41e-3efe6a3a7165@s13g2000prd.googlegroups.com> <62b77ed7-ef2a-4ada-b5da-f316821ddbe8@s8g2000prg.googlegroups.com> Message-ID: Godzilla wrote: >But the time.clock() sometimes return a value of between -3.5 to -4.5 >seconds backward. There are race conditions in your code. In between the time you execute "curTime = time.clock()" and calculate "curTime - self.timeStamp" in one thread, the other thread can execute "self.timeStamp = time.clock()". It's the only way your example program can print a negative "Actual Elapsed Time" value. The race condition seems unlikely, and it's hard to explain how this could result in it printing a value in the range of -3.5 to -4.5. However, a race condition occuring between the two evaluations of "curTime - self.timeStamp" is the only way your example program could print a negative value. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From morse at edoug.org Fri Mar 14 11:03:35 2008 From: morse at edoug.org (Doug Morse) Date: Fri, 14 Mar 2008 15:03:35 +0000 (UTC) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Hi, Well, my attempt to not use the --skip-archive option didn't get very far, as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. I'm guessing that they can't be in library.zip for a reason (i.e., they are DLL files, essentially, and thus must be readily available to be loaded into memory). Is there a work-around for this, then? That is, is there a way to either (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and umath.pyd files or (b) perhaps rename one set of the .pyd files -- say the numpy/core versions -- to say multiarray2.pyd and umath2.pyd, and then manual create the "stub"-like .pyc files that py2exe creates to point to these alternate .pyd files and then place these stubs in library.zip/numpy/core? Or am I just hoping for too much here and am going to be stuck with using the --skip-archive option? Thanks, Doug On Fri, 14 Mar 2008 14:37:32 +0000 (UTC), Doug Morse wrote: > Peter, > > Genius! You nailed it -- thanks! > > py2exe is apparently getting confused by the fact that packages "Numeric" > ... > > > So, my next step will be to try to not use the --skip-archive option and > then make these same modifications regarding multiarray.pyd and umath.pyd > to the py2exe-generated library.zip file and see if I can get things > running that way as well (and in so doing reduce my "dist" directory by > about 10mg). I may also try creating a dist/Numeric subdirectory and > moving dist/multiarray.pyd and dist/umath.pyd to this dist/Numeric > subdirectory -- for the goal of more accurately mirroring the actual > file/directory structure found in $PYTHONHOME/Lib/site-packages. > > From mail at hellmutweber.de Wed Mar 12 19:16:13 2008 From: mail at hellmutweber.de (Hellmut Weber) Date: Thu, 13 Mar 2008 00:16:13 +0100 Subject: Access function name from within a function Message-ID: <47D8643D.1090000@hellmutweber.de> Hi, i would liek to define an error routine which print amongs other things the name of the function from which it has been called. Having tried def foo(): print dir() and all other ideas which came to my (rather python newbie) mind. Googling too did not show me a possibility. IOW what I'm looking for is: def bar(): name = some_function(some-parameter) print name should print 'bar' Any ideas appreciated Hellmut -- Dr. Hellmut Weber mail at hellmutweber.de Degenfeldstra?e 2 tel +49-89-3081172 D-80803 M?nchen-Schwabing mobil +49-172-8450321 please: No DOCs, no PPTs. why: tinyurl.com/cbgq From hdante at gmail.com Sun Mar 30 00:58:29 2008 From: hdante at gmail.com (hdante) Date: Sat, 29 Mar 2008 21:58:29 -0700 (PDT) Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> Message-ID: <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> On Mar 29, 3:44 pm, "Bryan.Fodn... at gmail.com" wrote: > Hello, > > I am having trouble writing the code to read a binary string. I would > like to extract the values for use in a calculation. > > Any help would be great. I'm too lazy to debug your binary string, but I suggest that you completely throw away the binary file and restart with a database or structured text. See, for example: http://pyyaml.org/wiki/PyYAML If you have some legacy binary file that you need to process, try creating a C program that freads the binary file and printfs a text equivalent. If the decision of using binary files is not yours, then > > Here is my function that takes in a string. > > def parseSequence(data, start): > > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > pos = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > > if element == '\xfe\xff\x00\xe0': > data = value > > while start < length: > group_num = data[start:start+2] > element_num = data[start+2:start+4] > vl_field = data[start+4:start+8] > length = struct.unpack('hh', vl_field)[0] > value = data[start+8:(start+8+length)] > start = start+8+length > element = (group_num+element_num) > return element, start, value > > else: > return element, start, value > > else: > return element, pos, value > > And, here is a sample string (I have split up and indented for > readability). There is an identifier (\xfe\xff\x00\xe0) followed by > the length of the nested values. > > '\xfe\xff\x00\xe0\x18\x02\x00\x00 -length=536 > \n0q\x00\x02\x00\x00\x001 > \n0x\x00\x02\x00\x00\x0010 > \n0\x80\x00\x02\x00\x00\x004 > \n0\xa0\x00\x02\x00\x00\x000 > \x0c0\x04\x00\xe8\x01\x00\x00 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x008.9617062e-1 > \n0\x86\x00\x10\x00\x00\x00127.378510918301 > \x0c0\x06\x00\x02\x00\x00\x001 > \xfe\xff\x00\xe0p\x00\x00\x00 -length=112 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x0c\x00\x00\x001.629998e-1 > \n0\x86\x00\x10\x00\x00\x0023.159729257873 > \x0c0\x06\x00\x02\x00\x00\x004 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.26285318894435 > \n0\x86\x00\x10\x00\x00\x00227.690980638769 > \x0c0\x06\x00\x02\x00\x00\x003 > \xfe\xff\x00\xe0t\x00\x00\x00 -length=116 > \n0\x82\x002\x00\x00\x0042.9068704277562\\-392.3545926477\ > \189.182112099444 > \n0\x84\x00\x10\x00\x00\x001.52797639111557 > \n0\x86\x00\x10\x00\x00\x00263.433384670643 > \x0c0\x06\x00\x02\x00\x00\x002 ') From darcy at druid.net Wed Mar 26 15:49:57 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 26 Mar 2008 15:49:57 -0400 Subject: Daylight savings time problem In-Reply-To: References: Message-ID: <20080326154957.2482469c.darcy@druid.net> On Wed, 26 Mar 2008 19:37:16 -0000 "Fabio Durieux Lopes" wrote: > I'm trying to execute some operations based on a file's time. The > file's time is actually the file's name (e.g. FILE1_20080326170558). > So I do this: > fileTimeInSecs = time.mktime(time.strptime(timeString, > "%Y%m%d%H%M")) > > timeString contains the date part of the file's name. Function > strptime returns a time_struct, but my problem is that tm_isdst is > set to 0, and when we enter daylight savings time the file's time is > off by 1 hour. This time_struct is also read only so I can't change > tm_isdst to -1. > > Anyone knows how to fix it? Use UTC. -- 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 mail at timgolden.me.uk Thu Mar 6 03:42:38 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Mar 2008 08:42:38 +0000 Subject: system32 directory In-Reply-To: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> Message-ID: <47CFAE7E.6030501@timgolden.me.uk> Robert Dailey wrote: > Hi, > > Is there a way to get the System32 directory from windows through python? > For example, in C++ you do this by calling GetSystemDirectory(). Is there an > equivalent Python function for obtaining windows installation dependent > paths? First thing to do when asking "How do I do X in Python under Windows?" is to stick -- python X -- into Google and you get, eg: http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html which suggests that the win32api module from the pywin32 modules has the function you need. And sure enough... Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32api >>> win32api.GetSystemDirectory () 'C:\\WINDOWS\\system32' >>> TJG From sturlamolden at yahoo.no Thu Mar 20 09:13:09 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 06:13:09 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: Message-ID: <07618a7c-2cfc-4fc0-9ae1-067c24ef86bb@s12g2000prg.googlegroups.com> On 20 Mar, 08:39, "Daniel Fetchinson" wrote: > Thoughts anyone? I don't use tk myself, but scheduling tkinter for vaporization would be a bad idea. A lot of programs depend on it, and it doesn't look ugly anymore (the one that ship with Python still does). Would inclusion of wxPython and PyGTK in the standard library be an option? Or does LGPL prevent it? From gabriel.rossetti at mydeskfriend.com Tue Mar 18 05:55:03 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 18 Mar 2008 10:55:03 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom In-Reply-To: <1205831099.3212.18.camel@localhost.localdomain> References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <47DF9177.4050906@mydeskfriend.com> Carsten Haese wrote: > On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > >> Hello, >> >> I am reading core python python programming and it talks about using the >> idiom >> described on >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . >> >> I'm using python 2.5.1 and if I try : >> >> class MyClass(object): >> def __init__(self): >> self._foo = "foo" >> self._bar = "bar" >> >> @property >> def foo(): >> doc = "property foo's doc string" >> def fget(self): >> return self._foo >> def fset(self, value): >> self._foo = value >> def fdel(self): >> del self._foo >> return locals() # credit: David Niergarth >> >> @property >> def bar(): >> doc = "bar is readonly" >> def fget(self): >> return self._bar >> return locals() >> >> like suggested in the book (the decorator usage) I get this : >> >> >>> a=MyClass() >> >>> a.foo >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: foo() takes no arguments (1 given) >> >> but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : >> >> >>> a = MyClass() >> >>> a.foo >> 'foo' >> >> does anyone have an idea as of why this is happening? >> > > You're mixing two completely different approaches of building a > property. If that code is actually in the book like that, that's a typo > that you should mention to the author. > > The @property decorator can only be used to turn a single getter > function into a read-only attribute, because this: > > @property > def foo(...): > ... > > is the same as this: > > def foo(...): > ... > foo = property(foo) > > and calling property() with one argument builds a property that has just > a getter function that is the single argument you're giving it. > > The recipe you're referring to uses a magical function that returns a > dictionary of getter function, setter function, deleter function, and > docstring, with suitable key names so that the dictionary can be passed > as a keyword argument dictionary into the property() constructor. > However, that requires the magical foo=property(**foo()) invocation, not > the regular decorator invocation foo=property(foo). > > HTH, > > Ah, ok, I'll send him an email then, thanks for the explanation! Gabriel From graham.ashton at gmail.com Mon Mar 31 07:02:30 2008 From: graham.ashton at gmail.com (Graham Ashton) Date: Mon, 31 Mar 2008 04:02:30 -0700 (PDT) Subject: Beginner advice References: <65bfk7F2esfc1U1@mid.uni-berlin.de> Message-ID: <10dc13c3-df5a-42fc-bca5-318f890feb66@i29g2000prf.googlegroups.com> On Mar 31, 8:15?am, Paul Scott wrote: > Thanks for the feedback, now I just need some justification on the > GTK/GUI stuff - wxWidgets, GTK+ Glade or other? pyGTK is great. I used it quite heavily a year or so ago. GTK is a nice tool kit from the user's perspective too; you can make some rather attractive and usable applications with it, and the GUI builder is a boon. Obviously it integrates slightly better into it's native platform than it does Mac/Windows, but if you're targetting Ubuntu users then it's a great choice. I've never used wxWidgets in anger but I didn't take to it having used pyGTK quite extensively. I guess it just wasn't for me. Back then (things may have changed) it didn't (visually) integrate quite so well into a modern GNOME desktop either, even though it was using GTK to draw the widgets. I'd re-evaluate it if I really wanted to build a cross platform app though. From arnodel at googlemail.com Wed Mar 26 03:55:22 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 00:55:22 -0700 (PDT) Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: <69175d52-a701-40f2-9803-0e422e8d4f8f@d62g2000hsf.googlegroups.com> On Mar 25, 10:55?pm, Steven D'Aprano wrote: [...] In my haste I forgot to finish my post: > Here's an example that might help. > > class MyClass(object): > ? ? pass > > records = ["spam", "ham"] > for record in records: > ? ? # define a new function > ? ? def f(n): > ? ? ? ? return (record + " ")*n > ? ? # create a new instance > ? ? instance = MyClass() > ? ? # and dynamically add a method to it > ? ? setattr(instance, 'execute', f) > ? ? instance.execute(5) Except it only *appears* to work. What happens if were store the instances in a list and then execute them all in one go? class MyClass(object): pass records = ["spam", "ham"] instances = [] for record in records: # define a new function def f(n): return (record + " ")*n # create a new instance instance = MyClass() # and dynamically add a method to it setattr(instance, 'execute', f) instances.append(instance) # ONLY THIS LINE CHANGED for instance in instances: instance.execute(5) Outputs: 'ham ham ham ham ham ' 'ham ham ham ham ham ' Because the name 'record' in f is bound to 'ham' after the loop. To fix this, you can for example change def f(n): ... to def f(n, record=record): ... This way, 'record' is local to f and won't change at the next iteration of the loop. -- Arnaud From exxfile at hotmail.com Mon Mar 24 14:53:24 2008 From: exxfile at hotmail.com (pythonnubie) Date: Mon, 24 Mar 2008 11:53:24 -0700 (PDT) Subject: New to group Message-ID: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Hi Everyone I am new to programming in general although I have read alot and done alot of experimentation as well as researched afew languages namely java python and visual basic . My conclusion is that python is one of the best because it eliminates the need to learn about access modifiers and form handlers so a user can concentrate primarliy on the nuts and bolts of the language . i have come across my first exeption using randrange . The exeption is " no such attribute " in module random platform is xp home and the python build is activestate 2.5 All help much appreciated ! From spamhater at spamhaters Wed Mar 12 15:35:24 2008 From: spamhater at spamhaters (Thin Myrna) Date: Wed, 12 Mar 2008 20:35:24 +0100 Subject: Py2exe and Multi Treading problem. In-Reply-To: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> References: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> Message-ID: <47d8307c$0$12126$3b214f66@aconews.univie.ac.at> Farsheed Ashouri wrote: > NO it dont work. If I remove threading part, it works like a charm. > Any Idea? Of course it does then. Try to join the thread or do something else to prevent the non-threading part to exit prematurely. HTH Thin From andre.roberge at gmail.com Fri Mar 28 05:58:11 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Fri, 28 Mar 2008 02:58:11 -0700 (PDT) Subject: Plugins accessing parent state References: <883081df-9880-4cc4-a6cf-ccc84a97a4bc@b1g2000hsg.googlegroups.com> <653q99F2e37q8U1@mid.uni-berlin.de> Message-ID: On Mar 28, 6:39 am, "hajdu... at gmail.com" wrote: > On Mar 28, 1:58 am, "Diez B. Roggisch" wrote: > > > > > hajdu... at gmail.com schrieb: > > > > Does anyone have some design ideas ( or can point me at the right > > > design pattern, because I can't find it. ) for having a plugin being > > > able to access a parent's state? > > > > For example, let's say I have a class that receives some commands. > > > When it gets a command, it checks which of the registered plugins > > > deals with that command and passes the details of the command off to > > > that plugin. So I'd end up with something like.. > > > > result = plugin.do(msg_details) > > > > Now, I want to write a plugin called "help" that loops through all the > > > registered plugins and prints out their doc strings. If all my plugin > > > is getting is the msg details, how is it supposed to get the list of > > > available plugins from the calling class? > > > > Or, for instance, let's say my class loads a configuration file that > > > lists a set of admins who can enter commands. I want the plugins, if > > > they so choose, to be able to test if the msg came from an admin, but > > > again, I'm not passing the admin list into every plugin, it's just in > > > my calling class. I could make the plugin specify an attribute for > > > itself, like "admin_only" and test for that before I pass the command > > > but what if certain parts of the plugin are to be restricted and > > > others aren't, based on the details of the command sent? > > > > Is this as simple as just passing the instance of my class to each > > > plugin? It doesn't seem like the proper thing to do, because now the > > > plugin class has the capability of accessing the whole bot's > > > interface. > > > Yes, it is simple as that. Of course you can choose *what* you pass, if > > you want to restrict that - nobody forces you to pass the whole > > plugin-manager, if that would expose properties/methods you wouldn't > > want ther. > > > But to be honest: you are thinking much to far there - after all, it's > > all *your* code, and inside one interpreter. A real isolation isn't > > available anyway. > > > So just do what fullfills the functional requirements. > > > diez > > Since I want to have a uniform call to all plugins, would it make > sense to split out the attributes that I do want to share to a > separate class and then simply create a new instance of that class and > store it in the main class? > > For instance > > ... > self.utilities = Utilities(self) > ... > plugin.do(msg,self.utilities) I would bypass the step of creating a new instance and write instead plugin.do(msg, self) thus having access to all properties/methods of the calling object. Why restrict it?... Andr? From pmc411-usenet at yahoo.com Thu Mar 20 14:07:39 2008 From: pmc411-usenet at yahoo.com (Paulo da Costa) Date: Thu, 20 Mar 2008 18:07:39 GMT Subject: Can I run a python program from within emacs? In-Reply-To: References: <13u50796m76e9c7@corp.supernews.com> <9MednU_zmpEFG3_anZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: Jeff Schwab wrote: > Paulo da Costa wrote: > >> People who say Emacs often mean GNU Emacs. > > That's funny; to me, Emacs usually means XEmacs. :) Which is often a cause of confusion. Paulo From chris.stromberger at gmail.com Tue Mar 4 16:10:32 2008 From: chris.stromberger at gmail.com (chris) Date: Tue, 4 Mar 2008 13:10:32 -0800 (PST) Subject: sqlite3 permission issue Message-ID: I am trying to execute an update to a sqlite3 db via a python cgi script. I can execute a select via a cgi script, but when I attempt an update, I get an "unable to open database file" error. But the error comes on the update statement, not on the connect. So the script has: conn = sqlite3.connect('db') c = conn.cursor() --we get here ok-- c.execute("insert into contact ...") <-- this statement produces the error I can run the exact same python code from the command line and it works, so it has something to do with the user that runs the cgi (apache I assume). I chmodded the db file to 666, but it did not help. Any ideas? Thanks, Chris From castironpi at gmail.com Wed Mar 26 00:27:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 25 Mar 2008 21:27:15 -0700 (PDT) Subject: Prototype OO References: <8ff3b2ba-39e4-4d08-9913-10ec922419ef@i29g2000prf.googlegroups.com> <13ujk0f9inb73c2@corp.supernews.com> Message-ID: On Mar 25, 11:24?pm, Dennis Lee Bieber wrote: > On Wed, 26 Mar 2008 06:49:57 +0800, "Delaney, Timothy (Tim)" > declaimed the following in comp.lang.python: > > > > > As an aside, having lived much of my early life on a hobby farm, I've > > often wondered to myself just what cow-orking involves ... ;) > > ? ? ? ? Probably millennia too late to ask Saruman... Solomon? From harrelson at gmail.com Fri Mar 21 18:15:16 2008 From: harrelson at gmail.com (harrelson) Date: Fri, 21 Mar 2008 15:15:16 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog Message-ID: I am trying to get the below code to work and can't quite make things happen. This is with Python 2.5.1. Dialog is doing something odd... I have tinkered with different combinations and I can't get the dialog to show properly-- it does show properly directly in the shell. Any hints? import subprocess command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" "4 this and that"' proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) stderr_value = proc.communicate()[0] print stderr_value From dickinsm at gmail.com Tue Mar 4 14:04:23 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Mar 2008 11:04:23 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: <763ea020-731a-4ca0-8be7-55430676f1b7@i7g2000prf.googlegroups.com> On Mar 4, 9:39?am, Mark Dickinson wrote: > On Mar 4, 8:46?am, NickC wrote: > > > The increased number of inaccurate answers with Decimal (31% vs 10%) > > is probably due to the fact that it is actually more precise than > > float > > I suspect it has more to do with the fact that 10 is bigger than 2, > though I'm not sure I could precisely articulate the reasons why > this matters. Indeed, a quick lunchtime back-of-the-envelope calculation suggests that precision is largely irrelevant: it's the base that matters. For randomly chosen(*) base B floats x and y, the probability that (x/y)*y == x is approximately given by 1/2 + 1/log(B) - 1/log(B)**2 + 1/B/log(B)**2 For Decimal, this gives a probability of: >>> 0.5 + 1/log(10) - 1/log(10)**2 + 1/10/log(10)**2 0.76454395459279922 while for randomly chosen floats it's the same thing with all 10s replaced by 2s: >>> 0.5 + 1/log(2) - 1/log(2)**2 + 1/2/log(2)**2 0.90201055038615952 (*) Here, randomly chosen means I'm assuming that log(x) and log(y) are independent and uniformly distributed over some largish interval. Maybe not the most obvious definition of random, but not unreasonable. (And it makes the analysis easier!) A quick check, for floats: ##### from __future__ import division from random import random from math import exp def random_float(): return exp(random()*400.-200.) def test(): x = random_float() y = random_float() return (x/y)*y == x print sum(test() for i in xrange(10**8))/10**8 ##### produces (eventually): 0.90199129 Mark From stargaming at gmail.com Wed Mar 26 13:05:48 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 26 Mar 2008 17:05:48 GMT Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: <47ea826c$0$10148$9b622d9e@news.freenet.de> On Wed, 26 Mar 2008 13:05:55 -0300, Gabriel Genellina wrote: > En Wed, 26 Mar 2008 11:12:21 -0300, waltbrad > escribi?: > >> Stumbling through Mark Lutz's "Programming Python 3rd", he gives an >> example of a program that will automatically configure environment >> settings and launch other programs. Then he gives an example of >> running this program. On his command line he types: >> >> C:\...\PP3E>Launcher.py >> >> and this begins the program. Doesn't work for me. I have to type: >> >> C:\...\PP3E>python Launcher.py >> >> Is this a typo on his part or has he configured his settings in such a >> way that the command line will automatically associate the extension >> with the program? (If so, he didn't mention this in his book). > > I think it is an option in the installer, to associate or not Python to > the .py extension. > You could reinstall Python paying attention to the options, or repair > the association as described in this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ b1d0fd05b3615057/ See also the official (development version of the) documentation with the new section "Using Python". "Using Python on Windows" covers exactly this topic: http://docs.python.org/dev/using/windows.html#executing-scripts HTH, -- Robert "Stargaming" Lehmann From sgeiger at ncee.net Fri Mar 14 13:50:40 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Fri, 14 Mar 2008 12:50:40 -0500 Subject: Thousand Seperator In-Reply-To: References: <9ed95d4c-39ab-49bb-8814-b77bf18e9e72@h11g2000prf.googlegroups.com> Message-ID: <47DABAF0.20207@ncee.net> http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/python/lib/decimal-recipes.html Eddie Corns wrote: > ewanfisher at gmail.com writes: > > >> I'm trying to find some code that will turn: >> > > >> 100 -> 100 >> 1000 -> 1,000 >> 1000000 -> 1,000,000 >> -1000 -> -1,000 >> > > >> I know that can be done using a regular expression. In Perl I would do >> something like: >> > > >> sub thousand { >> $number = reverse $_[0]; >> $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g; >> return scalar reverse $number; >> } >> > > >> But I cannot find how to do this in Python. >> > > Look at the locale module. If you're producing the numbers yourself then they > get printed in that format otherwise you can convert them to numbers first. > > Eddie > > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From Robert.Bossy at jouy.inra.fr Fri Mar 14 06:18:48 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 14 Mar 2008 11:18:48 +0100 Subject: Creating a file with $SIZE In-Reply-To: <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Message-ID: <47DA5108.3040902@jouy.inra.fr> Bryan Olson wrote: > Robert Bossy wrote: > >> cokofreedom at gmail.com wrote: >> >>> Robert Bossy wrote: >>> >>>> Indeed! Maybe the best choice for chunksize would be the file's buffer >>>> size... >>>> > > That bit strikes me as silly. > The size of the chunk must be as little as possible in order to minimize memory consumption. However below the buffer-size, you'll end up filling the buffer anyway before actually writing on disk. >> Though, as Marco Mariani mentioned, this may create a fragmented file. >> It may or may not be an hindrance depending on what you want to do with >> it, but the circumstances in which this is a problem are quite rare. >> > > Writing zeros might also create a fragmented and/or compressed file. > Using random data, which is contrary to the stated requirement but > usually better for stated application, will prevent compression but > not prevent fragmentation. > > I'm not entirely clear on what the OP is doing. If he's testing > network throughput just by creating this file on a remote server, > the seek-way-past-end-then-write trick won't serve his purpose. > Even if the filesystem has to write all the zeros, the protocols > don't actually send those zeros. Amen. Cheers, RB From zentraders at gmail.com Sat Mar 22 14:33:06 2008 From: zentraders at gmail.com (Zentrader) Date: Sat, 22 Mar 2008 11:33:06 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> Message-ID: <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> On Mar 22, 10:07 am, Arnaud Delobelle wrote: > On Mar 22, 4:38 pm, Zentrader wrote: > > > > if ('one', 'two') are in f: ... > > > "are" gives me an error in Python 2.5 with a "from future import *" > > statement included. What version and platform are you running. Also, > > the docs don't mention it.http://docs.python.org/ref/keywords.html > > That's because you have to do: > > from bearophile import musings > > HTH > > -- > Arnaud Thanks. I am admittedly naive and don't have any type of guard up when on this group for people who think that type of comment makes them intelligent/funny. From george.sakkis at gmail.com Sun Mar 30 18:20:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 30 Mar 2008 15:20:54 -0700 (PDT) Subject: Dispatching functions from a dictionary References: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> <7xd4pbexbp.fsf@ruckus.brouhaha.com> Message-ID: <1ec62988-4def-4fd9-85e6-0e97e26e17e0@c26g2000prf.googlegroups.com> On Mar 30, 5:06 pm, Paul Rubin wrote: > tkp... at gmail.com writes: > > RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), ...} > > This actually calls the functions random.betavariate, etc. when > initializing RVDict. If you print out the contents of RVDict you'll see > that each value in it is just a floating point number, not a callable. > > You want something like: > > RVDict = {'1': lambda: random.betavariate(1,1), > '2': lambda: random.expovariate(1), etc. In Python 2.5, you can also write this as: from functools import partial RVDict = {'1': partial(random.betavariate,1,1), '2': partial(random.expovariate,1), etc. George From miki.tebeka at gmail.com Sun Mar 9 14:26:25 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 9 Mar 2008 11:26:25 -0700 (PDT) Subject: Parse specific text in email body to CSV file References: Message-ID: <87ad5667-326b-4de2-8d8f-5f470da7353b@e25g2000prg.googlegroups.com> Hello, > I have been searching all over for a solution to this. I am new to > Python, so I'm a little lost. Any pointers would be a great help. I > have a couple hundred emails that contain data I would like to > incorporate into a database or CSV file. I want to search the email > for specific text. > > The emails basically look like this: > > random text _important text:_15648 random text random text random text > random text > random text random text random text _important text:_15493 random text > random text > random text random text _important text:_11674 random text random text > random text > ===============Date: Wednesday March 5, 2008================ > name1: 15 ? ? ? ? ? ? ? ?name5: 14 > > name2: 18 ? ? ? ? ? ? ? ?name6: 105 > > name3: 64 ? ? ? ? ? ? ? ?name7: 2 > > name4: 24 ? ? ? ? ? ? ? ?name8: 13 > > I want information like "name1: 15" to be placed into the CSV with the > name "name1" and the value "15". The same goes for the date and > "_important text:_15493". > > I would like to use this CSV or database to plot a graph with the > data. import re for match in re.finditer("_([\w ]+):_(\d+)", text): print match.groups()[0], match.groups()[1] for match in re.finditer("Date: ([^=]+)=", text): print match.groups()[0] for match in re.finditer("(\w+): (\d+)", text): print match.groups()[0], match.groups()[1] Now you have two problems :) HTH, -- Miki http://pythonwise.blogspot.com From bjourne at gmail.com Sun Mar 16 21:39:29 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 17 Mar 2008 01:39:29 +0000 Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) In-Reply-To: References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <740c3aec0803161839l3c63ebcaw17b6e12f58422e70@mail.gmail.com> On Mon, Mar 17, 2008 at 12:32 AM, Paul Boddie wrote: > On 17 Mar, 01:09, a... at pythoncraft.com (Aahz) wrote: > > > > PyCon is what YOU make of it. If you want to change PyCon, propose a > > presentation or join the conference committee (concom) -- the latter only > > requires signing up for the pycon-organizers mailing list. > > > > This doesn't mean that we are uninterested in feedback. We love > > feedback. But there are stark limits to what we can do unless people get > > involved and push their pet projects. > > The same rules apply for most of the other Python conferences, too. > Apologies to Aahz for hijacking his rant, but for anyone interested in > enhancing the EuroPython 2008 experience, the advice is fairly > similar: join the volunteers organising the conference and make what > you want to see actually happen. For EuroPython, start here: > > http://www.europython.org/community/Volunteers I haven't been to EuroPython even when it has been fairly nearby because the entrance fee was to high. But how do you help change something like that? -- mvh Bj?rn From george.sakkis at gmail.com Thu Mar 6 15:20:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 6 Mar 2008 12:20:54 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> Message-ID: <3ddf3ef3-529c-4a81-932a-d2dda4972704@e23g2000prf.googlegroups.com> On Mar 6, 9:27 am, Pierre Quentel wrote: > Hi, > > I would like to know if there is a module that converts a string to a > value of the "most probable type" ; for instance : > - if the string is "abcd" the value is the same string "abcd" > - string "123" : value = the integer 123 > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value > = the float -1.23 > - string "2008/03/06" (the format is also locale-dependant) : value = > datetime.date(2008,03,06) > > Like in spreadsheets, special prefixes could be used to force the > type : for instance '123 would be converted to the *string* "123" > instead of the *integer* 123 > > I could code it myself, but this wheel is probably already invented Maybe, but that's a so domain-specific and easy to code wheel that it's no big deal reinventing. George From aboudouvas at panafonet.gr Thu Mar 27 11:01:12 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 08:01:12 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> <47EBB42D.9090206@behnel.de> Message-ID: <25b14b32-8fce-4e79-b236-c64fa96744e8@e23g2000prf.googlegroups.com> > If it's about "some problems", then maybe Cython is an alternative. > > http://cython.org > > Stefan Hmmm...thanks but i think Pyrex-like solution is not the ideal one. Coming from C# and having 8 years of expertise on it, i have gain a very positive thinking about jit compilers and i think that psyco (ok, a just-in-time specializer) is a more easy (and more correct) way to go that mixing 2 languages. From __peter__ at web.de Fri Mar 28 10:13:15 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Mar 2008 15:13:15 +0100 Subject: Global variables in modules... References: <8e3b97c4-a926-4e14-b325-9a737094636b@x41g2000hsb.googlegroups.com> Message-ID: ttsiodras at gmail.com wrote: > With a.py containing this: > > ========== a.py =========== > #!/usr/bin/env python > import b > > g = 0 > > def main(): > global g > g = 1 > b.callb() > > if __name__ == "__main__": > main() > ========================== > > ...and b.py containing... > > ========= b.py ============= > import a, sys > > def callb(): > print a.g > ========================== > > ...can someone explain why invoking a.py prints 0? > I would have thought that the global variable 'g' of module 'a' would > be set to 1... When you run a.py as a script it is put into the sys.modules module cache under the key "__main__" instead of "a". Thus, when you import a the cache lookup fails and a.py is executed again. You end up with two distinct copies of the script and its globals: $ python -i a.py 0 >>> import __main__, a >>> a.g 0 >>> __main__.g 1 Peter From castironpi at gmail.com Sun Mar 9 22:11:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 19:11:37 -0700 (PDT) Subject: Solve a Debate References: <82ol85-0o5.ln1@darkstargames.dnsalias.net> Message-ID: > days_in_month 12: > 31 > 30 > 28 > 31 > ... > 30 > 31 > assign $days days_in_month[$month] > > This program consists of 2 operations (table jump and assignment) > and 12 values. This makes a memory consumption of 12+2 = 14 Along the same lines, you could populate the table somewhat sparsely, and goto a modulo key. You could even put functions in it: setreturn $endoftable hash month goto -0 -1 -2 jan.-> 3: setvjmp janfun -4 -5 apr.-> 6: setvjmp aprfun $endoftable Sweet! Are you stack-ops? From sjmachin at lexicon.net Thu Mar 27 18:00:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 15:00:01 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: On Mar 28, 7:37 am, Aaron Watters wrote: > > If you want fame and admiration you could fix > the arguably bug in the csv module and send > the patch to the python bugs mailing list. > However, I just had a perusal of csv.py.... > good luck :). It is *NOT* a bug in the Python CSV module. The data is the problem. The admittedly arcane way that the admittedly informal CSV writing protocol works for each field is (simplified by ignoring \n and other quotables): QUOTE = '"' DELIM = ',' if QUOTE in field: emit(QUOTE + field.replace(QUOTE, QUOTE+QUOTE) + QUOTE) elif DELIM in field: emit(QUOTE + field + QUOTE) else: emit(field) Example: database query, customer's surname recorded as O"Brien This should be written as ...,"O""Brien",... and read back as ['...', 'O"Brien', '...'] Aside: this quote-doubling caper is not restricted to CSV and not exactly an uncommon occurrence: SELECT * FROM cust WHERE surname = 'O''Brien'; A common mistake in CSV writing is to omit the quote-doubling step above. If that is done, it is impossible to recover the original contents unambiguously in all cases without further knowledge, assumptions, heuristics, or look-ahead e.g. (1) the original field had an even number of quotes or (2) the intended number of fields is known or (3) there is only one quote in the line and there are no embedded newlines ... The Python csv module emulates Excel in delivering garbage silently in cases when the expected serialisation protocol has (detectably) not been followed. Proffering fame and admiration might be better directed towards introducing a "strict" option than patching a non-existing bug (which would introduce new ones). Cheers, John From theller at ctypes.org Wed Mar 26 18:08:50 2008 From: theller at ctypes.org (Thomas Heller) Date: Wed, 26 Mar 2008 23:08:50 +0100 Subject: py2exe socket.gaierror (10093) In-Reply-To: <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> Message-ID: Knut schrieb: >> The script can't resolve the server name. Try to do it by hand using >> nslookup or even ping (you may want to add a few print statements inside >> the script to see the exact host name it is trying to connect to, in case >> it isn't what you expect) >> If you can't resolve the host name using nslookup, there is a network >> problem, not in your script. If you can resolve it, try your script >> without py2exe if possible. >> >> -- >> Gabriel Genellina > > Thank you for the quick reply Gabriel. > > I have made sure the script works fine before I exe it. > It is when I compile the program I get this error. > > I don't get how the compile changes server availability. > Could it be a firewall issue? Thomas From David.J.Anderson66 at gmail.com Mon Mar 17 23:28:35 2008 From: David.J.Anderson66 at gmail.com (David.J.Anderson66 at gmail.com) Date: Mon, 17 Mar 2008 20:28:35 -0700 (PDT) Subject: ord function problem from newbie Message-ID: <990b4d55-09e0-4b35-8119-e48ee38acc98@p25g2000hsf.googlegroups.com> I'm trying to convert a name into a numerical value that is not consistent with ANSCII values. In my case, I convert all to lowercase, then try to sum the value of the letters entered by the user, can't get it to add them. Here is what I have. By the way, the values I need to use is: a=1, b=2, c=3, etc... I'm trying to subtract 96 from the ANSCII value, then total. import string def main(): print "This program calculates the numeric value of a name with which" print "you could look up online as to what that value represents." print # Get name to calculate name = raw_input("Please type a name: ") small = string.lower(name) print "Here is the calculated value:" print small for ch in small: v = ord(ch)-96 print v main() Looks like this: This program calculates the numeric value of a name with which you could look up online as to what that value represents. Please type a name: David Here is the calculated value: david 4 1 22 9 4 From vvangelovski at gmail.com Wed Mar 19 11:51:38 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Wed, 19 Mar 2008 08:51:38 -0700 (PDT) Subject: url validator in python Message-ID: <7a27c19d-2e0e-4242-9054-9455f825df8f@i7g2000prf.googlegroups.com> How can I check the validity of absolute urls with http scheme? example: "http://www.example.com/something.html" -> valid "http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid From malaclypse2 at gmail.com Wed Mar 26 15:43:18 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 26 Mar 2008 15:43:18 -0400 Subject: Filtering a Python list to uniques In-Reply-To: References: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> Message-ID: <16651e80803261243i3d8b7ecam3624398db1c86dbe@mail.gmail.com> On Wed, Mar 26, 2008 at 2:50 PM, kellygreer1 wrote: > How come the Set() thing seems to work for some people and I get the > 'unhashable' error? > > How do you test for 'membership' on a dictionary? > > # where tmp is the non-unique list > # dct is a dictionary where each unique key will be tied to a count > (the value) > # for testing I was setting the count to 0 > for v in tmp: > if not v in dct: dct[v] = 0 > > # I get unhashable error here. > # Even if I write it. > > for v in tmp: > if not v in dct.keys(): dct[v] = 0 > > What am I missing? Some of the elements of tmp are unhashable. Unhashable items can't be the keys of a dictionary or members of a set. I don't think you've said anywhere in the thread what these items are, you just started out with an example of a list of integers. Do you believe the elements in tmp are integers? If so, try the following - for v in tmp: print type(v), repr(v), hash(v) and let us know what it spits out. -- Jerry From cpthomas at gmail.com Wed Mar 12 14:10:06 2008 From: cpthomas at gmail.com (Casey T) Date: Wed, 12 Mar 2008 11:10:06 -0700 (PDT) Subject: Different results when running script from IDLE versus Command Line Message-ID: <895b88e4-694d-4fee-a633-08aa8a407999@p73g2000hsd.googlegroups.com> Hi, I'm new to Python and I'm having some problems with getting different results from my script when I run it from IDLE versus just double- clicking the .py file and having it run through the command line. Basically, my script reads some CSV files, assembles a text files, then uploads that test file to an ftp site. When I run the script from IDLE, everything works fine. But when it runs from the command line, the file that gets uploaded is empty. It seems that it is creating a new file to upload, rather than using the existing file (or at least that's what I think is going on.) Below is my script. I apologize for any ugly code. Thanks for your help. import sys,os,linecache,csv,ftplib,time starttime = time.time() #******* #Summary file assembling #******* currentdir = "//folder/" reg_sum = open('reg_sum.txt','w') reg_sum.close for files in os.listdir(currentdir): reg_file = csv.reader(open(currentdir + files)) for row in reg_file: reg_sum = open('reg_sum.txt','a') reg_sum.write(",".join(row) + ',\n') reg_sum.close #******* #Summary file processing #******* coordList = [ ["F10",40.0053,-75.0927], ["T10",40.0272,-75.1123], ["D22",39.9811,-75.0998], ["P02",40.0437,-75.0217], ["D68",39.9203,-75.1388], ["D51",39.9534,-75.1405], ["S43",39.9217,-75.2275], ["S33",39.9360,-75.2077], ["S42A",39.9215,-75.1937], ["S05",39.9617,-75.1782], ["T14",40.0165,-75.1077]] coordList_index = ["F10","T10","D22","P02","D68","D51","S43","S33","S42A","S05","T14"] #coordList_index is a list containing in_text = open('reg_sum.txt','r') out_text = open('reg_out.txt','w') out_text.close out_text = open('reg_out.txt','a') for line in in_text: split_line = line.split(',') if (split_line[0]) in coordList_index: i = coordList_index.index(split_line[0]) coords = str(coordList[i][1]) + "," + str(coordList[i][2]) last_update = str(split_line[2]) print str(split_line[0]) if split_line[1] == "1": out_text.write(split_line[0] + "
,Test1: " + last_update + "," + coords + ",1" + "\n") elif split_line[1] == "0": out_text.write(split_line[0] + "
,Test2.
Last updated: " + last_update + "," + coords + ",0" + "\n") else: out_text.write(split_line[0] + "
,No data.," + coords + "\n") in_text.close ###******* ###Uploads file via FTP ###******* s = ftplib.FTP('ftp.blah123.org,'user','pass') f.open('reg_out.txt','r') s.storlines('STOR reg_out.txt', f) f.close() s.quit() print "Processed in " + str(((time.time() - starttime) / 60) *60) + " seconds!" #prints elapsed time From castironpi at gmail.com Mon Mar 3 20:11:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 17:11:43 -0800 (PST) Subject: Beautiful Code in Python? References: <1c6d273b-e4aa-4e66-b57e-acc3e932b38c@h11g2000prf.googlegroups.com> Message-ID: On Mar 3, 4:30?pm, "sjdevn... at yahoo.com" wrote: > On Mar 2, 1:18 pm, castiro... at gmail.com wrote: > > > On Mar 2, 12:01 pm, John DeRosa wrote: > > > > On Mon, 3 Mar 2008 01:23:32 +0900, js wrote: > > > >Hi, > > > > >Have you ever seen Beautiful Python code? > > > >Zope? Django? Python standard lib? or else? > > > > >Please tell me what code you think it's stunning. > > > > Just about any Python code I look at. > > > Decorators, with, and namedtuple. > > IMO, decorators are functional but far from beautiful. ?They're a > special, somewhat ugly syntax for something that was already handled > by normal constructs ("foo=classmethod(foo)") that you didn't need > extra knowledge to understand. > > On balance I think it's worth it in order to get those "declarations" > up by the function defs, but it's sort of a tradeoff of magical non- > explicitness for pragmatism over purity. ?A worthwile tradeoff, but > not what I'd ever call beautiful. Someone study architecture. What are the Palmer House, the Rookery, and the Lyric Opera? From sturlamolden at yahoo.no Sun Mar 23 00:11:51 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 22 Mar 2008 21:11:51 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> Message-ID: On 22 Mar, 23:42, 7stud wrote: > Beginning programmers in grades 9-12 are not going to understand > issues like that, and it would be a mistake to try and introduce > them. Beginning programmers should be concentrating their efforts on > learning the syntax of a language and basic constructs like for-loops > and if statements. Yes. And because Python is a "scripting language" one does not even have to introduce functions to demonstrate this. Students can play with loops, datatypes, operators, assignments, and conditionals, without being confused by higher level constructs like functions and classes. Python is one of very few languages that allow that. If you e.g. start to teach programming with with Java, students are from the start faced with confusing constructs like classes and public static methods if they are to try out anything on their own. With Python, higher level constructs can be gradually introduced. That has a tremendous pedagogical value. From ntv1534 at gmail.com Mon Mar 3 15:14:11 2008 From: ntv1534 at gmail.com (MooMaster) Date: Mon, 3 Mar 2008 12:14:11 -0800 (PST) Subject: Inheritance issue... References: <632vhiF262j15U1@mid.uni-berlin.de> Message-ID: On Mar 3, 11:49 am, "Diez B. Roggisch" wrote: > MooMaster schrieb: > > > I'm trying to use inheritance to create a simple binary tree, but it's > > not going so well... here's what I pull from the documentation for > > super() > > "super( type[, object-or-type]) > > > Return the superclass of type. If the second argument is omitted the > > super object returned is unbound. If the second argument is an object, > > isinstance(obj, type) must be true. If the second argument is a type, > > issubclass(type2, type) must be true. super() only works for new-style > > classes. > > The last sentence contains the important bit. You need to use > new-style-classes, which means they have to have the ancestor "object" > somewhere in their inheritance-graph. > > Like this: > > class Foo(object): pass > > Certainly one of the somewhat uglier corners of Python... > > Diez Thanks guys, I hadn't even heard of the distinction between "old" and "new" style classes...is this in the tutorial somewhere? I didn't see it in Classes... From gh at ghaering.de Wed Mar 19 03:49:36 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 19 Mar 2008 08:49:36 +0100 Subject: How to solve a three-element equation set? In-Reply-To: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> References: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> Message-ID: <64busgF2anottU2@mid.uni-berlin.de> purple wrote: > Could you guys do me a favor for solving a equation set? > > Z=d/4*(1-SIN(X)/X) > X=8q/(D^2*Y)+SIN(X) > Y=1/n*Z^(2/3)*i^(1/2) > > In this equation set, X,Y&Z are the unkown parameters, the others say, > d, q, n&i are known. SO in python, how to program it to represent X, Y > and Z in the form of d, q, n and i? Will you do your homework yourself, please? Hint: make X, Y and Z Python functions. -- Gerhard From sarc26 at gmail.com Fri Mar 14 07:07:09 2008 From: sarc26 at gmail.com (Saideep A V S) Date: Fri, 14 Mar 2008 16:37:09 +0530 Subject: request for Details about Dictionaries in Python Message-ID: Hello Sir, I am a beginner level programmer in Python. I am in search of a function for 'On-Disk' Dictionaries which is similar to On-Disk Hash tables in Perl (i.e., tie function in Perl). Could anyone help me with the concept. I have also searched the net, but was not successful in finding any related. Awaiting your Solutions. Thanks in Advance. Saideep -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Fri Mar 14 02:24:55 2008 From: cwitts at gmail.com (Chris) Date: Thu, 13 Mar 2008 23:24:55 -0700 (PDT) Subject: Need Script For read multiple files(.txt) from a folder References: <861f689b-78a7-42ba-bcb6-67f7ff67e1fc@s13g2000prd.googlegroups.com> Message-ID: <6a4e7475-d291-4572-b114-6835cc9061bc@n75g2000hsh.googlegroups.com> On Mar 14, 6:28?am, jai_python wrote: > hi frenz I ?Need a Python Script For read multiple files(.txt) from a > folder and write it in a single text file.... > > Thanks Take a look at the OS Module for the listdir funtion, you can use it to build a list of all files in the given folder. Iterate through the list checking to see if the file is of the correct type and if it is then append/write it to your single file. Don't forget to flush() your output otherwise you can easily run into memory issues. From software at ginstrom.com Sun Mar 9 21:11:39 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 10 Mar 2008 10:11:39 +0900 Subject: any chance regular expressions are cached? In-Reply-To: <47D48662.4090002@tim.thechases.com> References: <47D48662.4090002@tim.thechases.com> Message-ID: <054301c8824b$b202dfb0$0203a8c0@MOUSE> > On Behalf Of Tim Chase > Sounds like what you want is to use the compile() call to > compile once, and then use the resulting objects: > > re1 = re.compile(r'\n') > re2 = re.compile(r'^') > ... > s = re1.sub('\n' + spaces, s) > s = re2.sub(spaces, s) Yes. And I would go a step further and suggest that regular expressions are best avoided in favor of simpler things when possible. That will make the code easier to debug, and probably faster. A couple of examples: >>> text = """spam spam spam spam spam spam spam""" >>> # normalize newlines >>> print "\n".join([line for line in text.splitlines() if line]) spam spam spam spam spam spam spam >>> # normalize whitespace >>> print " ".join(text.split()) spam spam spam spam spam spam spam >>> # strip leading/trailing space >>> text = " spam " >>> print text.lstrip() spam >>> print text.rstrip() spam >>> print text.strip() spam Regards, Ryan Ginstrom From craigm3604 at gmail.com Sat Mar 22 18:12:47 2008 From: craigm3604 at gmail.com (Craig) Date: Sat, 22 Mar 2008 15:12:47 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <83fa8bde-d993-4b54-ac1a-89771ce99871@e23g2000prf.googlegroups.com> <13u6qvp8b6qhaa4@corp.supernews.com> <4f08914b-3087-4924-afbb-b0124759c99b@59g2000hsb.googlegroups.com> <13uamij1rprdk5f@corp.supernews.com> Message-ID: On Mar 22, 3:13 pm, Dennis Lee Bieber wrote: > On Fri, 21 Mar 2008 23:21:48 -0700 (PDT), Craig > declaimed the following in comp.lang.python: > > > Sorry, I wasn't trying to exclude any credit from Dennis, I just > > wasn't sure if he wanted to be listed. > > As responded to elsewhere -- it was more a case of minimizing the > "non-work" traffic on my work email address... > > > > > This is what I have tried: > > > > > LPBSTR = POINTER(c_void_p) > > > > > And, on the last variation of this, this function needs to receive > > BSTR values passed back from the dll: > > short FAR PASCAL VmxGet(LPHANDLE lpDatasetNumber, LPSHORT lpSecIndex, > > LPSHORT lpOption, BSTR *SrchKey, > > BSTR *SecKey, BSTR *PriKey, LPSTR > > lpTypeDef); > > SrchKey is provided by me, SecKey and PriKey are returned by the dll, > > and TypeDef is defined by me and filled by the dll. > > > For this, I have added: > > VmxGet = windll.vbis5032.VmxGet > > VmxGet.restype = c_short > > VmxGet.argtypes = [LPHANDLE, LPSHORT, LPSHORT, LPBSTR, LPBSTR, LPBSTR, > > LPBSTR] > > Remember that Python strings are immutable... Also note that the > signature you give above seems to differentiate between passing a > pointer variable LPSTR (ie; lpTypeDef is just 4-bytes which will/should > contain the address pointing to the real string) and passing the address > of the first byte of a string buffer BSTR (*PriKey is the same as > &PriKey[0] -- but PriKey itself has to be a sequence of characters or an > empty buffer allocated to hold them). > > From the ctypes documentation: > http://docs.python.org/lib/node453.html > > """ > Assigning a new value to instances of the pointer types c_char_p, > c_wchar_p, and c_void_p changes the memory location they point to, not > the contents of the memory block (of course not, because Python strings > are immutable): > > >>> s = "Hello, World" > >>> c_s = c_char_p(s) > >>> print c_s > > c_char_p('Hello, World')>>> c_s.value = "Hi, there" > >>> print c_s > > c_char_p('Hi, there') > > >>> print s # first string is unchanged > Hello, World > > You should be careful, however, not to pass them to functions expecting > pointers to mutable memory. If you need mutable memory blocks, ctypes > has a create_string_buffer function which creates these in various ways. > The current memory block contents can be accessed (or changed) with the > raw property; if you want to access it as NUL terminated string, use the > value property: > > >>> from ctypes import * > >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes > >>> print sizeof(p), repr(p.raw) > 3 '\x00\x00\x00' > >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string > >>> print sizeof(p), repr(p.raw) > 6 'Hello\x00' > >>> print repr(p.value) > 'Hello' > >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer > >>> print sizeof(p), repr(p.raw) > > 10 'Hello\x00\x00\x00\x00\x00'>>> p.value = "Hi" > >>> print sizeof(p), repr(p.raw) > > 10 'Hi\x00lo\x00\x00\x00\x00\x00' > > """ > > Drawback -- it looks like you may have to preset the size of the > buffer... > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ That is not really a drawback. Pretty much everything is fixed-length anyway. I guess I am having trouble with the whole immutable thing. And, the pointers too. Anyway, I have the following for "types": LPBSTR = POINTER(c_void_p) HANDLE = POINTER(POINTER(c_long)) LPHANDLE = POINTER(HANDLE) LPSHORT = POINTER(c_short) LPVSTATS = POINTER(c_void_p) c_string = c_char_p LPSTR = c_string I guess passing a structure is out of the question. So, I tried a string (something - just to get the data back): #short FAR PASCAL VmxInfo(LPHANDLE lpDatasetNumber, LPVSTATS lpvstats); VmxInfo = windll.vbis5032.VmxInfo VmxInfo.restype = c_short VmxInfo.argtypes = [LPHANDLE, LPSTR] VsamInfo = create_string_buffer("12345678901234567890123456789012") printf ("VsamInfo = \x22%s\x22\n", VsamInfo.raw) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) And I get: Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 101, in res = VmxInfo( byref(hwmcb), byref(VsamInfo) ) ctypes.ArgumentError: argument 2: : wrong type So, to get to the VmxGet, I comment out the VmxInfo call, and proceed to: SrchKey = windll.oleaut32.SysAllocStringByteLen("MSD19PH \x00", 41) SecKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) PriKey = windll.oleaut32.SysAllocStringByteLen("1234567890123456789012345678901234567890\x00", 41) TypeDef = create_string_buffer("X".center(129, "X")) print "Ready to call (Library = " + find_library("vbis5032") + ") ..." res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(SrchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), byref(c_void_p(TypeDef)) ) And for this, I get: Ready to call (Library = C:\Windows\vbis5032.dll) ... Traceback (most recent call last): File "C:\temp\vbisam_test_2.py", line 114, in res = VmxGet( byref(hwmcb), byref(SecIndex), byref(Option), byref(c_void_p(S rchKey)), byref(c_void_p(SecKey)), byref(c_void_p(PriKey)), byref(TypeDef) ) ctypes.ArgumentError: argument 7: : wrong type I know I am missing something, probably very basic (pardon the pun) to Python. From wolf_tracks at invalid.com Fri Mar 28 20:38:08 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 29 Mar 2008 00:38:08 GMT Subject: Astronomy Fits format and gif.save(path) In-Reply-To: References: <_KaHj.26177$Ch6.11894@newssvr11.news.prodigy.net> Message-ID: I'm pretty new to Python and libraries. I'm actually trying to modify some code someone else wrote. There are two ways images are saved. One is for the user to select a "Save as GIF" menu item, or save as tiff, or others. The other way is that the user wants a collected image from a camera saved every, say, 10 minutes. The "save" process is different for some reason. Here are the two code segments involved: A. Save every 10 minutes t = time.localtime(now_time) s = "a%4d%02d%02d_%02d%02d%02d.tif" % ( NOTE my comments below B. t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec ) s = os.path.join("Exposures",s) <========== auto-exposures if not os.path.exists("Exposures"): os.mkdir("Exposures") self.current_image.save(s) <============ save image if self.trigger_mode: self.Trigger() self.CheckEvent() contrast this with where the user specifically wants the image he sees saved as a gif: B. From menu option def SaveGIF(self): if self.current_path: default_path = splitext(basename(self.current_path))[0] + ".gif" path = asksaveasfilename(defaultextension=".gif", title="Save as GIF", initialfile=default_path, filetypes=GIF_FILE_TYPES) else: path = asksaveasfilename(defaultextension=".gif", title="Save as GIF", filetypes=GIF_FILE_TYPES) if not path: return gif = self.current_image.convert("RGB") gif.save(path) <===========Save as gif. The programmer told me if I change the tif in A. to gif, jpg or whatever, it would work. Instead I get a file the of zero length when I use jpg. Can anyone explain why this wouldn't work? I see that current_image.convert is involved in one place and current_image.save in the first. {I erroneously thought gif.save was some PIL method.) Hmmm, maybe I needed to use jpeg? As for fits formats, I see PIL shows FITS for identify only. Not sure what that means. Read but not write? Gary Herron wrote: > W. Watson wrote: >> In what library would I find gif.save(path), where path is the name >> and path of a file, and the method would produce a file in a gif >> format? >> >> Is there a fits.save(path) somewhere? fits is commonly used in >> astronomical work. >> > You may want to install PIL (the Python Image Library) for this: > > http://www.pythonware.com/products/pil/ -- Wayne Watson (Nevada City, CA) Web Page: From __peter__ at web.de Wed Mar 12 04:52:40 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Mar 2008 09:52:40 +0100 Subject: best way to have enum-like identifiers? References: Message-ID: mh at pixar.com wrote: > I currently have a 2-dim hash, indexed by two strings: > > template['py']['funcpre'] > template['py']['funcpost'] > ... > > but I would prefer to have these indexed by constants of > some kind, since this seems a bit more natural: > > template[py][funcpre] > template[py][funcpost] > ... > > Currently I'm just putting this at the top of the file: > > py=1 > funcpre=2 > funcpost=3 > ... > but I'm curious if there's a better way of doing this, > some kind of enum-like thing or somesuch. A dictionary with a fixed set of keys is better spelt as a class, e. g. instead of the inner dictionary you can use something like class Hooks(object): def __init__(self, pre=None, post=None): self.pre = pre self.post = post ... def before(): print "before" def after(): print "after" template["py"] = Hooks(before, after) Peter From koara at atlas.cz Fri Mar 7 09:15:04 2008 From: koara at atlas.cz (koara) Date: Fri, 7 Mar 2008 06:15:04 -0800 (PST) Subject: hidden built-in module References: <56e25b80-04c3-4cfa-9089-9ad1d2d23f5a@p73g2000hsd.googlegroups.com> Message-ID: <1e794f53-bf66-4e00-856f-b3c78823a6bd@47g2000hsb.googlegroups.com> On Mar 5, 1:39 pm, gigs wrote: > koara wrote: > > Hello, is there a way to access a module that is hidden because > > another module (of the same name) is found first? > > > More specifically, i have my own logging.py module, and inside this > > module, depending on how initialization goes, i may want to do 'from > > logging import *' from the built-in logging. > > > I hope my description was clear, cheers. > > > I am using python2.4. > > you can add your own logging module in extra directory that have __init__.py and > import it like: from extradirectory.logging import * > > and builtin: from logging import * Thank you for your reply gigs. However, the point of this namespace harakiri is that existing code which uses 'import logging' ... 'logging.info()'... etc. continues working without any change. Renaming my logging.py file is not an option -- if it were, i wouldn't bother naming my module same as a built-in :-) Cheers. From sjmachin at lexicon.net Thu Mar 27 18:07:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 15:07:21 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: <18171c4d-70a7-4e57-8fbd-6c9122d25903@c19g2000prf.googlegroups.com> On Mar 28, 8:40 am, jwbrow... at gmail.com wrote: > On Mar 27, 1:53 pm, "Gabriel Genellina" > wrote: > > > > > En Thu, 27 Mar 2008 17:37:33 -0300, Aaron Watters > > escribi?: > > > >> "this";"is";"a";"test" > > > >> Resulting in an output of: > > > >> ['this', 'is', 'a', 'test'] > > > >> However, if I modify the csv to: > > > >> "t"h"is";"is";"a";"test" > > > >> The output changes to: > > > >> ['th"is"', 'is', 'a', 'test'] > > > > I'd be tempted to say that this is a bug, > > > except that I think the definition of "csv" is > > > informal, so the "bug/feature" distinction > > > cannot be exactly defined, unless I'm mistaken. > > > AFAIK, the csv module tries to mimic Excel behavior as close as possible. > > It has some test cases that look horrible, but that's what Excel does... > > I'd try actually using Excel to see what happens. > > Perhaps the behavior could be more configurable, like the codecs are. > > > -- > > Gabriel Genellina > > Thank you Aaron and Gabriel. I was also hesitant to use the term > "bug" since as you said CSV isn't a standard. Yet in the same right I > couldn't readily think of an instance where the quote should be > removed if it's not sitting right next to the delimiter (or at the > very beginning/end of the line). > > I'm not even sure if it should be patched since there could be cases > where this is how people want it to behave and I wouldn't want their > code to break. > > I think rolling out a custom class seems like the only solution but if > anyone else has any other advice I'd like to hear it. > I have code in awk, C, and Python for reading bad-CSV data under the assumptions (1) no embedded newlines (2) embedded quotes are not doubled as they should be (3) there is an even number of quotes in each original field (4) the caller prefers an exception or error return when there is anomalous data. From justdelegard at gmail.com Thu Mar 27 17:13:15 2008 From: justdelegard at gmail.com (Justin Delegard) Date: Thu, 27 Mar 2008 17:13:15 -0400 Subject: dynimac code with lambda function creation In-Reply-To: <47ebd337$0$13089$426a74cc@news.free.fr> References: <47ebd337$0$13089$426a74cc@news.free.fr> Message-ID: <47EC0DEB.8040908@gmail.com> An HTML attachment was scrubbed... URL: From joe at neosource.com.au Thu Mar 13 22:24:01 2008 From: joe at neosource.com.au (jcnbp8k) Date: Thu, 13 Mar 2008 19:24:01 -0700 (PDT) Subject: sorting question In-Reply-To: References: Message-ID: <16043041.post@talk.nabble.com> Hi Patty, That's easy solved, the word is keyboards. I just did a google search for 'anagram solver' and got lucky with Andy's free online anagram solver at http://www.ssynth.co.uk/~gay/anagram.html :) I know it's not a python script, though are you actually working on a python program to de-scramble words yourself or did you just want the answer? Hope that helps. Cheers, Joe http://www.neosource.com.au www.neosource.com.au - Practical Software Solutions Patty Sutcliffe wrote: > > The website you list regarding 9-letter scrambled words doesn't exist any > longer. Is there another way that I can access it to see your program you > designed? I have a nine letter work I need to unscramble. I will send it > just in case you can figure it out for me and let me know. > > KAEOSYBRD > > I'm not very good at that sort of thing, but would love to know the answer > to this one. > > Thank you, > Patty > patty206 at charter.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- View this message in context: http://www.nabble.com/sorting-question-tp16041301p16043041.html Sent from the Python - python-list mailing list archive at Nabble.com. From pscott at uwc.ac.za Mon Mar 31 01:23:00 2008 From: pscott at uwc.ac.za (Paul Scott) Date: Mon, 31 Mar 2008 07:23:00 +0200 Subject: Beginner advice Message-ID: <1206940981.6828.13.camel@paul-laptop> I have been tasked to come up with an audio recorder desktop (cross platform if possible - but linux only is OK) that: 1. records a lecture as an MP3 file (pymedia?) 2. Provides a login form for server credentials 3. Uploads via XMLRPC (pyxmlrpclib) to the server as a podcast I have been working on this (having never really worked with Python before) for the past 24 hours or so, and would just like to get some feedback on the direction that I am taking if possible. 1. Is pymedia an active project? Should I use something else? 2. GUI design - I am using glade designer and pyGTK. Good choice? 3. pyXMLRPClib - active? Something better? 4. I see that there are literally thousands of somewhat external looking libraries for python, I presume that there is some way of bundling all the deps into a single source and then compiling? or otherwise packaging them all (this software will be for academia, so difficult installs are out!) 5. Editor - I am using Eric (which I quite like), any advice on IDE's? Any help would be massively appreciated! Python looks like a *really* easy and powerful language (hey, I managed to do a desktop application in a few hours and I am a botanist!) and I would like to do a lot more with it. I have a PHP background (taught myself that also) so C syntax is almost like my native tongue :) but Python syntax seems just as easy, if not easier! I am still going through Mark Pilgrims' tutorials (dive into ones) and am slowly getting the hang of things, so if these questions seem inane, please do excuse me and feel free to tell me to RTFM! Thanks --Paul -------------- next part -------------- All Email originating from UWC is covered by disclaimer http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm From furkankuru at gmail.com Tue Mar 25 19:38:39 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 01:38:39 +0200 Subject: embedded python pythonpath In-Reply-To: References: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> Message-ID: <3a4a8f930803251638p47f8b39y4cd6780d528843b1@mail.gmail.com> Actually, I do not want any .py or .pyc files around my executable. (including userdict, sys, site etc) I want to have just single zip file for all python files. I had a look at py2exe source codes but could not figure out how it just looks into a zip file. So maybe I have to compile the svn version of python. On 3/26/08, Gabriel Genellina wrote: > > Furkan Kuru gmail.com> writes: > > > I've tried below code (Setting pythonpath environment variable) > > and then initialize python interpreter but the embedded python > interpreter > did not get the newly assigned PYTHONPATH. > > I ve looked at the sys.path in python code (that is run by the embedded > interpreter) and it behaved according to older pythonpath. > > Note that you don't HAVE to set the environment variable PYTHONPATH, there > are > other ways to get directories listed in sys.path - and that is what really > counts. > The simplest way is to just write code to insert the desired directories > in > front of sys.path, after the call to Py_Initialize. The only problem is > that > some modules (like site and sitecustomize) are searched and executed > before > your code has a chance to modify sys.path - I hope it's not a problem for > you. > > > Setting environment variable seemed to be correct. > > Does py_initialize run in another thread so it starts before setting the > environment var? > > I could reproduce the problem with a smaller code (using C, not C++). > Testing > with Python 2.5.1 doesn't work (that means, it ignores the new setting for > PYTHONPATH). Testing with current Python trunk (from svn) *does* work. I > don't > know if this is a bug that has been fixed, or it works that way because > the > svn version is not the default installation and then searches for things > in a > different way. > > #include > > int main(int argc, char *argv[]) > { > putenv("PYTHONPATH=C:\\TEMP\\MF"); > system("set PYTHONPATH"); > printf("Py_GETENV(PYTHONPATH)=%s\n", Py_GETENV("PYTHONPATH")); > > Py_Initialize(); > PyRun_SimpleString("import sys\nprint sys.path"); > Py_Finalize(); > return 0; > } > > I compiled twice with these commands: > cl -MD -Ic:\apps\python25\include test.c c:\apps\python25 > \Libs\Python25.lib /Fetest25.exe > cl -MD -Ic:\apps\python\trunk\PC -Ic:\apps\python\trunk\include test.c > c:\apps\python\trunk\PCbuild\Python26.lib /Fetest26.exe > > Python25.dll and Python26.dll both were copied into the current directory. > > test25.exe: > PYTHONPATH=C:\TEMP\MF > Py_GETENV(PYTHONPATH)=C:\TEMP\MF > ['C:\\Apps\\Python25\\lib\\site-packages\\setuptools-0.6c5- > py2.5.egg', 'C:\\Apps\\Python25\\lib\\site-packages\\ > simplejson-1.7.1-py2.5-win32.egg', > ... many directories, not including C:\TEMP\MF ... ] > > test26.exe: > PYTHONPATH=C:\TEMP\MF > Py_GETENV(PYTHONPATH)=C:\TEMP\MF > 'import site' failed; use -v for traceback > ['C:\\TEMP\\MF', 'C:\\TEMP\\python26.zip', '', 'C:\\TEMP'] > > I don't understand how the test program, compiled for 2.5.1, could > actually > locate the Python directory. (It's not in my PATH, it's not the default > install directory, and I deleted the HKLM\Software\Python\PythonCore\2.5 > registry key). > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkpmep at gmail.com Sun Mar 30 21:17:05 2008 From: tkpmep at gmail.com (tkpmep at gmail.com) Date: Sun, 30 Mar 2008 18:17:05 -0700 (PDT) Subject: Dispatching functions from a dictionary References: <9016d50f-c4e5-478d-87a8-e3d77ffc2b09@d21g2000prf.googlegroups.com> <7xd4pbexbp.fsf@ruckus.brouhaha.com> <1ec62988-4def-4fd9-85e6-0e97e26e17e0@c26g2000prf.googlegroups.com> Message-ID: <55eaa328-11b7-416d-b093-5ad8275e8a84@s8g2000prg.googlegroups.com> Paul, George, Thanks a mill - the help is greatly appreciated. Thomas Philips From troworld at gmail.com Sat Mar 1 20:47:54 2008 From: troworld at gmail.com (Tro) Date: Sat, 1 Mar 2008 20:47:54 -0500 Subject: Book Recomendations In-Reply-To: References: Message-ID: <200803012047.54656.troworld@gmail.com> On Saturday 01 March 2008, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. The official tutorial is required reading. After that, Dive Into Python (http://diveintopython.org/). Cheers, Tro From bearophileHUGS at lycos.com Mon Mar 17 22:28:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 17 Mar 2008 19:28:13 -0700 (PDT) Subject: Py in Counter Strike Message-ID: <859db668-8ff1-47ee-8691-d27e3ade6800@x41g2000hsb.googlegroups.com> A PDF file, Embedding_Python_into_Counter-Strike: http://us.pycon.org/common/2008/talkdata/PyCon2008/020/Case_Study_-_Embedding_Python_into_Counter-Strike_Source.pdf It talks about some problems too. Bye, bearophile From harunbaykal at gmail.com Sun Mar 2 21:27:52 2008 From: harunbaykal at gmail.com (Harun BAYKAL) Date: Mon, 3 Mar 2008 04:27:52 +0200 Subject: Character Problem Message-ID: <4493315f0803021827j775b693ndaaa80bb0d2c8841@mail.gmail.com> Hi, I am studying on an addon developed for QGIS, a GIS software. But I have a problem. The extension has been developed with QT and Python. Actually Python is used for the interface design. For the user interface Python reads some values from some database files. I am not experienced Python user and the first developer of the addon had written the python codes for his database. And his database doesn't include any characters than the usual characaters. But my database file contains many characters which are not used in English. So I can not compile the extension because Python can not read the database files. So how can I change the python files for making it to read the databases without modifying the database. Otherwise I had to clear all the non usual characters from the database file which means most of the names and strings will be wrong. So somehow I had to make the python files to read the other unicode and non english characters? Anybody have any idea about how I can I fix such a problem. Thanks Harun From interracial2suckers at gmail.com Mon Mar 24 10:44:21 2008 From: interracial2suckers at gmail.com (interracial2suckers at gmail.com) Date: Mon, 24 Mar 2008 07:44:21 -0700 (PDT) Subject: girl nipples tortured girl singapore tammy sikh girl in action Message-ID: <9edc8586-a506-4bb9-9c74-4d111ffd322c@c19g2000prf.googlegroups.com> http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new http://totalvideos.isgreat.org/video/new geocities girl mn sweet, gallery geocities girl oregon photo, geocities japanese bra girl photos, black domain face geocities girl japanese, bored geocities girl name sarah, bored geocities girl lonely, 2006 7 geocities girl mn, geocities girl medical australia, geocities black hairy girl, 2006 8 geocities girl mn, bored geocities girl named sarah, girl indian maal, van morrison brown eyed girl tab, story of a girl guitar ninedays, purdy girl greenwich village, marti gras girl, girl on potty chair, growth chart percentile girl, pig boar sex girl, imgboard board3 little girl, bike daytona girl, stencils of geisha girl, fangs vampire girl, the girl from dundee high, dilivery girl, whirly girl the movie, girl snowsuit size 7, girl scout brownie try it, aslyn lyrics be the girl, girl does stripshow for boyfriend, gurrlie girl, austin obrien my girl 2, gang bang girl sasha grey, what company makes girl scout cookies, bike bikini dirt girl, drunk girl freind, girl puncher, adventure girl lava sharkboy, mutya buena reall girl, girl socks stink, pirelli calendar girl, 1900 gibson girl, girl spreader bar, barbi girl spanish, ugly girl lyrics mermade melidy, sexy burmese girl dancing ago, kiss because i ma girl mv, girl shagging horse, dark magician girl ecchi, beach bikini candid girl picture, before girl her post puke she, morning girl summary michael dorris, preemie girl clothes, cover girl mineral cosmetics, girl sportbike riders, hey girl-pretty ricky, twin girl crochet bonnets, abbotsford single girl online, sienna miller nude video factory girl, pony girl tack, rush limbaughs girl friend, supertramp girl friend, sexy girl webcams for mac dashboard, 1940 pin up girl pictures, country girl tits arse, breezewood call girl, nanyang girl, free cheatah girl invitations, anthropomorphic dog girl, spider-girl volume 1 legacy summary, jojo not that kinda girl video, rich girl by hall oates, girl i little love oingo song, all-girl orgy, gfx girl, puro rancho girl, lutheran girl jokes, girl southington, the bohemian girl opera, reliant k girl friend, butterfly girl clipart, wowowee girl, 7 girl phatty, octa girl, girl lifegaurd, beach drunky girl in, chinees girl feet, young dro my girl, vivid girl janine biography, jim sanders girl scouts, sugar plum girl dress, cruel girl jeans web site, girl fucked by a dof, splitz enz message to my girl, feedee girl, wf girl wrestelers, ugly girl lyrics by weird al, banquet cheering girl, poopy girl, glock girl pictures, caryl top girl, barloe girl she, t-girl dallas personal ads, baby by girl innervoices lyric, by girl lyric talk tlc, young girl puss, everythng girl, wisconsin girl scout camps, galaxy girl sim date, elf girl sim date cheat, foglio girl genius, girl scouts kennebec council, teen girl funstuff, girl getting banged bt horse, girl scout awards for cadetts, young girl swimmer sheila, historical dress american girl doll, girl school bomb extrem pakistan, palm glade girl scouts, horse-girl sex, cookie delivery girl scout, laker girl audition, bad girl black buddafly, pinup girl with bow and arrow, nicaragua nude girl photos, bear fucks girl, spandex girl lycra woman, hypnotized girl clip, teen girl glases, being dragon girl sacrificed, girl scouts silver sage council, bam margera girl women clothes, ceremony flag girl scout, lil girl gone devin the dude, elle girl magzine, aloud girl hot long summer video, sweat young girl nude, girl want suckdick, download barlow girl, girl relay runners, brownie uniform for american girl doll, kazakh girl, daddy punishes girl, girl scouts great trail council, girl missinf in portugal luxe resort, harry potter girl scout camp, thc girl, teenage girl beating caught on tape, skinnie girl, girl maria moore xl, a girl s world online clubhouse, geisha girl halloween, ebony t-girl, japen girl sex, chat ethiopian girl, girl scout tours of savannah georgia, every girl millimeter sell, treat gloom cookie girl pretty, eamon girl version, picasso girl before the mirror, anka gilmore girl paul, leo blais oh girl, homly girl, whirly girl puke scene, japanese geisha girl tattoo, kenworth trucking mud flap girl, boy and girl club la habra, roller blade girl boogie nights, girl in pic poop toilet, bad man nah dress like girl, sagattarius man and a gemini girl, pacific peaks girl scout council, types of girl scout cookies 2005, girl scout puzzlers badge, cosmo girl magazine website, wb show gilmore girl, girl scouts camp seniors detroit michigan, ssx tricky girl, ash girl from mars mp3, jersey shore girl dottie, lyrics for nasty girl by chingy, rachel weissman girl's hair accessories, confirmation e-card special girl, anime blog girl high joshikousei, barbie german girl rammstein, disney disney girl nightgown princess, fingerbang a girl, award ceremony girl scout, girl from ipanema song lyric, the fattest girl with boobs, factory girl sienna sex scenes, zales commercial girl song, fruits basket akito girl, charles dana gibson girl, arta girl, last girl standing rapidshare, daddys little girl by al martino, young girl mentral education, butthole girl pix, girl taking huge poo, reclining girl by francois boucher, jamaica girl scouts, 6yo girl, how to impress a teenage girl, girl koi no victory, aqua ugly girl lyrics, mud flap girl pin, san francisco girl band cockpit, magical girl pretty sammy, rostov on don girl, japanese kogal school girl, candi girl wild, girl scout coloring pages, american girl doll outlet store, girl nipples tortured, council girl hills rolling scout, girl scouts of dupage county il, litles girl, girl bust inflation, x-girl, girl take it easy lyrics pietasters, animated lust little girl squirrel, girl gymnastics merrill samantha, little girl with dorky glasses, bobble head girl version lyrics, arabic blue clip girl tooth, girl gwen hollaback lyric song stefani, girl interrupted quizzes, goodbye girl squeeze, baby ebay girl oarb reborn, peach girl change of heart spoilers, brownie girl idea scout, molestation girl symptoms signs, white girl feat young jeezy, derby girl roller texas, girl scout camporee meals, girl interrupted suicide song, nasty girl lyrics by inaya day, sweet japanese girl cleanser reviews, voodoo girl tim burton, super girl by krystal harris, eureka springs girl's getaway, father flanagans boy and girl town, cam girl masturbates, girl's buzzcut, shonen knife i'm a super girl, cinammon girl tab, citrus council girl scouts, mckay pasadena girl, lucy dress pattern girl, ballow girl, assparade rebecca assparade porn girl rebecaa, girl abducted in tyler texas, naked college hooter girl, costume dance georgie girl, beautiful decent girl russian, girl in greenwood gifted, girl in lovefreekz video, dw girly girl, girl gone wild dorm room, missing girl devin arizona, college girl gyno, tw3 girl, girl groaning audio, doa girl wallpaper, derry community girl scouts, freak a leak girl, ganguro girl v 1.5 cheats, sour girl stone temple, miracle lyrics boy meets girl, terri clark dirty girl guitar tabs, al martino daddys little girl lyrics, 20th century american girl doll, bird girl seussical, johanna grace flower girl dress, girl jewish personals single, nobody's girl bratz rock angelz, girl sleeve tattoo, yong girl upskirt, toasty girl, girl scouts cookie boxes, gourmet-girl, mae girl orgasm, girl huntin girls, ebony girl wanks white guy, billy gilman shes my girl, biki teen girl, girl s titi, rottweiler on girl, girl listen tonite, geocities free sex cam, girl scout candy mould, buff girl myspace layout, living dead girl rob zombie lyrics, country girl cleaning service nashville tn, nina sky move your body girl, blog archive podcast expo soccer girl, foxey golden girl, audio girl promiscuous, girl scout lone star council, girl rad nude, lip piercing girl hiding, girl crush lip potion, adult girl scout costume, lynching murder girl, rina av girl, the shins girl inform me, stupid girl named chelsie, girl jumping rope gold necklace, keep yuor hands off my girl, girl pooping in jeans, paula abdul as a young girl, escort girl versailles, girl viginas boobs, revolutionary girl utena amvs, poor little rich girl edie warhol, killers video mr brightside girl, girl's basketball camps in doylestown pa, the girl most likely rebecca sparrow, nude girl tweens, black gi raping french girl, samoan girl names, thai names-girl, girl mcdaniel mel plastic, nude dark magician girl, china girl iggy pop, girl scouts of america jackson michigan, girl hip hugger jeans, booty butt community girl type, girl fucks landlord, whacked out sports girl, girl scout pen pals, big shoeless girl, david bowie china girl moviefone, girl in the pentacle, girl in pantys and bra, never alone by barlow girl lyrics, aloud girl oops, dp girl nastiest, assie girl, girl surrender ultimate video wrestling, champagne girls flower girl dresses, pink leatherman girl tools, pony girl fetish wear, lyrics for material girl madonna, neil simon the goodbye girl, champagne bottle in a girl ass, natural hairy girl leslie, little girl are heavenly treasure, prepuberty girl, kabuki girl, the other boleyn girl phillipa gregory, girl rihanna selfish, land rover and girl pics, eazy e college girl are easy, busty pinup girl, slutty catholic school girl pics, ordinary girl clueless, vivid girl get doggy, arb girl, impressionists girl looking at her hands, rockabilly girl hair style, north face metropolis girl, flapper girl dress, kochi girl, gunslinger girl wallpapers, directions for masterbating a girl, barbie girl-chinese, umpire girl, girl scout cookie brand, icy blu girl, bikini candid girl model underwear, barlow girl music group, baby girl briggs washington state, girl scout of the permian basin, girl picture skinhead, baby girl nursery decorating ideas, the bottlerockets gas girl, missing girl found hartsford staircase, freaky ghost girl in hallway picture, excort girl, venom spider-girl, lyrics nasty girl christina, one girl to love bobby valentino, saturn girl hentai, a girl from yamhill cover, judo girl comic, sikh girl in action, jet boy jet girl chron gen, cover girl mascaras, anime girl turning into a shemale, girl singapore tammy, girl scout cookie trivia, guitar chords stupid girl, bike girl super umbrella, daisy girl scouts bridging, tuskegee girl, girl masterbating loudly, whiskey girl guitar chords, teen girl slumber parties supplies, birmingham girl scouts, perfect physique girl, 138 girl punk hair styles 199, doctor rose jack girl torchwood, jesse mccartney daddys little girl lyrics, girl peeing in the potty, girl model laika, commercial fahrenheit girl, coastal carolina girl scout, girl gonna jet tab, about a girl chords nirvana, charleston south carolina girl scouts, girl gone summer wiled, school girl plaid skirt, the history of girl scout swaps, girl scouts of adirondack, girl scout of san fernando valley, pisces animated girl pictures, girl scouts brownie vest, cover girl eye shadow discontinued colors, junior girl scout handbook pages, girl little strange strangler, chinese baby girl adoption us citizen, girl in appron, i want a girl barbershop, bop girl goes calypso, kathy van zeeland and undercover girl, melina pizza girl, wheelchair lakers girl tina walker, fattass girl, goth girl freeones hardcore, girl membership pin scout, 50s girl pin up, aud bikini contest girl round, girl of fear factor playboy pic, girl wearing diapers and rubber panties, psycho girl matt download, graduation party invitations girl pink, yellowstone girl scouts, stacy keibler nitro girl, ficking girl mom, cotton toddler girl pajamas, 1.5 cheat ganguro girl, girl gumshoe, southern girl incubus, girl indian saree, irainian girl, unconscious girl fetish webcam, teen girl biceps, girl scout daisy petals, nn cute girl, audio girl sammie should, flower girl purse ivory, jessie's girl chords, coppertone cute dog girl remember, chaos girl az goth skinny, girl scout brownie tryits, etnies skate shoes for girl, girl trench coats, girl deepthroats horse, slavic girl, teenage girl wall stencils, sim girl 2.3 cheat, the slave girl by buchi emecheta, southern storm girl's basketball ky, frank zappa fine girl lyrics, cover girl outlast lipstick, girl scout thinking day quiz, marrekesh and single girl, number girl sappukei, chord lyric to brown eyed girl, av girl idol japanese school, girl interrupted cast and crew, wun laos girl, bitch cigar gal girl lady woman, that girl by marques houston lyrics, girl whirring, mardi gras girl pics, daddys girl scrapbooking, girl snapping turtles, t-girl links, daddies little girl pirn, muscle-girl pornstar, girl scout of milwaukee area, the temptations my girl chords, myspace graphics congratulations baby girl, kai winding hit girl, frisco tx girl scout cookies, austrailian nude girl, the girl who killed the python, japenese dark magician girl, girl scout of america daisy, girl avril lavine, naked everquest girl, girl in skimpy skirt teenage, girl scouts of america iowa jobs, girl lfo lyric tv, never alone barlow girl tab, hula girl doll, free xxxwomen xxx, From pete at unspace.ca Sun Mar 16 15:48:22 2008 From: pete at unspace.ca (Pete Forde) Date: Sun, 16 Mar 2008 12:48:22 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <3a2e4490-f4e9-4edf-ae35-0aa3c90103f7@i7g2000prf.googlegroups.com> > I know what the argument for the results of Pycon 2008 will be: we > needed the money. My answer: it's not worth it. If this is what you > have to do to grow the conference, then don't. If the choice is > between selling my experience to vendors and reducing the size of the > conference, then cut the size of the conference. Keep the quality of > my experience as the primary decision criteria, or I'll stop coming. This commodification of "eyeballs" is happening in the Ruby community, as well. 2008 seems to be the year of Ruby conferences, and both organizers and attendees have been entirely complicit in the gradual dilution of interesting, un-biased presentations. As a result, many of the most innovative members in our community no longer show up. This is a real shame. My friends and I decided to stage a grassroots Ruby conference this summer; it will have no paid sponsors for exactly this reason. We're trying to change up the typical format as well: it's a single-track event, no "keynotes", no schills for well-heeled interests. We're even organizing activities for significant others traveling with conference attendees so that everyone has a good time. The response we've gotten to this approach has been curious; many people totally get why these things are important, and the speaker list reflects this. However, we've also had a lot of complaints that our event is too expensive. In fact, they say that it should be free, like a BarCamp. Just get a bunch of sponsors, and that will be the ticket. We say bollocks to that. http://rubyfringe.com/ I'm posting here because even though the Python and Ruby communities are seen as being in some sort of competition, I personally believe that we have more in common (and lots to learn from each other) than we are credited for. For example, the popular Haml template engine is white-space sensitive, and that's a direct nod towards Python syntax. Thanks for your post, Bruce. You've given us a huge boost that we're doing something right, here. From sigzero at gmail.com Fri Mar 28 22:31:05 2008 From: sigzero at gmail.com (Robert Hicks) Date: Fri, 28 Mar 2008 19:31:05 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> <87abky1i6i.fsf@benfinney.id.au> Message-ID: <71f1daa6-9f48-440b-8f47-07f081891bb2@z38g2000hsc.googlegroups.com> On Mar 16, 5:48?pm, Jeff Schwab wrote: >?Unlike Perl or Tcl, Python is not just a > scripting language with a set of ad-hoc extensions. ?There are still > issues, and Python probably will never be a general-purpose replacement > for system-native language compilers, but it does enable a smooth ramp > from "just a user," through "a user who does some scripting," to > "application developer." Danger! My crap-o-meter went to 100%! You really need to explain what you mean better here. What enables Python to give you a "smooth ramp"? Inquiring minds want to know.I am sure there are a whole lotta programmers in the Perl and Tcl camps that would like to know what you mean as well. I await your enlightenment. Robert From castironpi at gmail.com Sat Mar 8 03:44:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 00:44:34 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> <1ec4b03a-75cd-432e-9e5d-750132324d38@s8g2000prg.googlegroups.com> Message-ID: <4e27c893-d7c6-4ab4-abaa-187520dfc69b@d62g2000hsf.googlegroups.com> On Mar 7, 7:46?pm, DBak wrote: > > > > > ?However I can't do this, because, of course, the name Tree isn't > > > > > ?available at the time that the classes _MT and _Node are defined, so > > > > > ?_MT and _Node can't inherit from Tree. > > > > > Not only is the name not defined, the class doesn't even exist yet. > > > > Yes, but, well - it certainly isn't usable yet, but some object (that > > > will be the class when it is finished) is being built (its __dict__ is > > > being populated, etc.) - so there's an object pointer available inside > > > the interpreter that could be put somewhere. ?But this is pedantic - > > > you're right, the class really isn't available until after the class > > > statement. > > > There is no obvious solution-- What do you mean? ?If there are any at > > all, there is significant competition without clear winners. > > > dict dictA: > > ? ?membA= 0 > > ? ?membB= 0 > > > dict dictB: > > ? ?membC= 0 > > Thanks for your answer. ?To the extent I understand it: ?There is a > difference between the class statements I was trying to nest, with the > inner inheriting from the outer, and your dict example. ?The main > thing is that in the class example - when the inner class is being > built (i.e., inside its class statement's block) there is no need (as > I understand it) for the parent class to be functional at all WHILE I > AM DEFINING METHODS on the inner class. ?Sure, if the inner class had An interesting observation. > But in the case I'm talking about I just want to define methods on the > inner class, using names such that when the method is eventually > called on an instance of the inner class the attribute lookup will > proceed with the outer class being the inner class' parent. ?Creating There are two possibilities I'm thinking of. In both, cases you go back after Tree is finished executing, and inform _Node and _MT of their parentage. I haven't tested either. The first is, define a metaclass that allows __mro__ (method resolution order) to be written to. But does the look-up get performed on the one you define? The second is, cache _Node and _MT during creation, and go back and reinstantiate them. class Tree(object): ...class _MT( metaclass= placeholder ): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node( metaclass= placeholder ): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... Tree._MT.complete( Tree ) Tree._Node.complete( Tree ) And similarly, class Tree(object): @placeholder ...class _MT(): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) @placeholder ...class _Node( metaclass= placeholder( Tree ) ): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... Tree._MT.complete( Tree ) Tree._Node.complete( Tree ) Here the last lines might read: Tree._MT= Tree._MT.complete( Tree ) Tree._Node= Tree._Node.complete( Tree ) But maybe not. Here's a third, actually: class Tree( placeholder ): pass class Tree(object, metaclass= placeholderreplace( Tree ) ): ...class _MT(Tree): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node(Tree): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... If you're using Python -3.0, you might even be able to get away without metaclasses on the first one, or decorators on the second one: class Tree(object): ...class _MT(): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) _MT= placeholder( _MT ) ...class _Node( metaclass= placeholder( Tree ) ): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) _Node= placeholder( _Node ) ...def __init__(): return _MT() ...def merge(self, T): ...... Tree._MT.complete( Tree ) Tree._Node.complete( Tree ) And once again I'm still not sure. From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:12:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:12:55 -0300 Subject: problem with CGIHTTPServer References: Message-ID: En Fri, 28 Mar 2008 12:38:45 -0300, 7stud escribi?: > After I start the server script, load the html page in my browser, and > click on the link, I get the desired output in my browser, but the > server script outputs the following in my terminal: > > localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/ > 1.1" 200 - > localhost - - [28/Mar/2008 08:51:22] code 404, message File not found > localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 - > > > What are the error messages on lines two and three? Line 3 is your browser (IE, I presume?) asking for an icon for the site. See http://en.wikipedia.org/wiki/Favicon I don't know about line 2, maybe it's just a diagnostic message related to line 3. Try refreshing the page, or using an inexistent url to see if it still appears. Or put any icon as /favicon.ico to make your browser happy. -- Gabriel Genellina From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 07:00:59 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 11:00:59 -0000 Subject: Check For SELF Variable Existance Message-ID: <007501c88367$308371d0$918a5570$@rawlins@thinkbluemedia.co.uk> Hello Guys, I want to be able to check if a class has a certain property in its 'self' scope, what's the best way to do this? I've seen a few examples of people using a try: block to test if the variable exists but to be honest, this seems a little bit verbose, do we not have a better method of checking for its existence? Cheers, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Tue Mar 4 01:01:31 2008 From: cwitts at gmail.com (Chris) Date: Mon, 3 Mar 2008 22:01:31 -0800 (PST) Subject: Command line arguments in Windows References: Message-ID: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> On Mar 4, 7:12 am, "Mike Walker" wrote: > I am having some problems with command line arguments in Windows. The same > code under Linux works fine. > > In Windows I only get one argument no matter how many arguments are passed > on the command line. I think there is some problem with the way the .py > files are associated causing this. I'm just not sure how to go about fixing > it. > > If I call the python script using the command "python argtest.py arg1 arg2 > etc..." this also works fine. Its only when run the program using the name > only that the problem occurs. > > Does anyone have any ideas what the problem is here and hopefully how to go > about fixing it? > > import sys > > if __name__ == "__main__": > for arg in sys.argv: > print arg If you run a python file, ie. just double clicking it the only argument you will have will be the filename of the script. If you create a shortcut to the script and in the target box add your arguments (if you have quotation marks place them after not inside) you will see your arguments. fwiw you answered yourself in the third paragraph. From chris.stromberger at gmail.com Tue Mar 4 16:46:16 2008 From: chris.stromberger at gmail.com (chris) Date: Tue, 4 Mar 2008 13:46:16 -0800 (PST) Subject: sqlite3 permission issue References: Message-ID: On Mar 4, 3:10 pm, chris wrote: > I am trying to execute an update to a sqlite3 db via a python cgi > script. I can execute a select via a cgi script, but when I attempt > an update, I get an "unable to open database file" error. But the > error comes on the update statement, not on the connect. > > So the script has: > > conn = sqlite3.connect('db') > c = conn.cursor() > --we get here ok-- > c.execute("insert into contact ...") <-- this statement produces the > error > > I can run the exact same python code from the command line and it > works, so it has something to do with the user that runs the cgi > (apache I assume). I chmodded the db file to 666, but it did not > help. > > Any ideas? > > Thanks, > Chris Nevermind, it was the directory permissions causing the issue. Works now. From sturlamolden at yahoo.no Sat Mar 15 12:02:04 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 09:02:04 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: <19562869-a412-401c-b169-3bcbf6be747f@i12g2000prf.googlegroups.com> On 13 Mar, 09:22, Antoon Pardon wrote: > Whatever python has for a calling convention, it is close enough that > naming it "call by reference" gives people a reasonable idea of what > is going on. Only to the extent that many mistake passing Java or C# reference types for "call-by-reference". "Call by reference" is the calling convention used by Fortran, Pascal and Visual Basic 6. If you don't know any of these languages, chances are you don't understand what "call by reference" really means. From grante at visi.com Fri Mar 28 17:43:52 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 28 Mar 2008 21:43:52 -0000 Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> Message-ID: <13uqpko97kt1h65@corp.supernews.com> On 2008-03-28, castironpi at gmail.com wrote: > Did everyone take the course on computer architecture? No. I personally know dozens of people who didn't. And I know others who took a course on computer architecture but not the course on computer architecture. -- Grant Edwards grante Yow! PEGGY FLEMMING is at stealing BASKET BALLS to visi.com feed the babies in VERMONT. From gagsl-py2 at yahoo.com.ar Thu Mar 27 02:00:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 03:00:11 -0300 Subject: copy file over LAN References: <47EB15BC.3060505@al.com.au> Message-ID: En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee escribi?: > I have a file on another machine on the local network (my machine and > local machines are on windows) and I want to copy it locally. Now the > machine requires authentication and when I try to do a > import shutil > shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') > and it gives me a IOError: [Errno 13] Permission denied: error, which I > expect. How do I provide authentication to copy this file? Probably there are other ways, but the "net use" command looks easy enough. Execute "net help use | more" in a console to see the right syntax. Use the subprocess module to run the command from inside Python. -- Gabriel Genellina From ilochab at yahoo.it Tue Mar 11 17:59:18 2008 From: ilochab at yahoo.it (ilochab) Date: Tue, 11 Mar 2008 21:59:18 GMT Subject: How to import a module that must override a standard one Message-ID: I'm writing a python package that will contain a logging service for twisted in python style. I'm using some modules I downloaded from a twisted trunk, that are not released with twisted but have the same names. One of them is log.py that is usually imported from twisted modules like: from twisted.python import log But I need to import __my__ log, and I need that all the other modules that will use my package would import __my__ log module too. So I see 2 options to do so, but neither of them satisfies me: 1) I put __my__ log in my package tree and I import it from there, but in this way any other module must do the same (and this is bad for previous twisted application that want to use my package) 2) I oblige any potential user to patch the standard twisted installation with my modules, but this is even worse. I'm quite sure there is some pythonic way to override the original twisted's log module after its first import with my one: I just don't know how to do it. So I'll patiently wait for an answer from this group. Ciao! Licia From tjreedy at udel.edu Tue Mar 11 00:20:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 00:20:44 -0400 Subject: is operator References: <004801c881f2$a04081f0$0b020b0a@nb1011> <13taot5khcl933a@corp.supernews.com> Message-ID: wrote in message news:b61e001a-3a41-4a35-ab3a-546e453d8d69 at b64g2000hsa.googlegroups.com... | What is the notion of equal defined for functions? Isness. The developers did not see sufficient reason to refine it further by comparing all the attributes, including the code object. But there has just been a discussion on pydev about the notion of equality for bound methods. Isness is also the default notion of equality for user-class instances, but in this latter case, an explicit and different __eq__ method can be given. tjr From sjmachin at lexicon.net Thu Mar 27 17:10:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 14:10:03 -0700 (PDT) Subject: Determine size of string in bytes References: Message-ID: <083180d3-3e7c-4db5-926f-b7528201a3b8@a22g2000hsc.googlegroups.com> On Mar 28, 6:45 am, breal wrote: > Forgive me for this question which is most likely stupid... The contents of your question are not stupid. The subject however does invite a stupid answer like: len(the_string). Disclaimer: I know nothing about SOAP except that it's usually capitalised :-) Now read on: > How do I determine the number of bytes a string takes up? I have a > soap server that is returning a serialized string. Serialised how? UTF-8? > It seems that when > the string goes over 65978 characters it does not return to the soap > client. Why does it seem so? How did you arrive at such a precise limit? > Instead I get an error: > error: (35, 'Resource temporarily unavailable') Is this error from the client or the server? Any error or logfile record from the other side? Is there anything in the documentation about maximum sizes? > > This makes me think the problem exists on the soap client side with > some sort of max return length. Think? Can't you verify this by inspecting the source? > If I knew how many bytes the 65978 > character string was, then I could try to up this value. How do you know the string is 65978 characters? If you are debugging the server, can't you do len(serialise(the_65978_char_string))? 65978? Are you sure? Looks suspiciously close to 65535 aka 0xFFFF aka (2 ** 16 - 1 ) to me. If you have the server, you presumably have the source code for both client and server. Some options for you: (1) Look at the traceback(s), look at the source code, nut it out for yourself. If there is some kind of max other than an implicit 16-bit limitation in the client code, it shouldn't be too hard to find. (2) Post the traceback(s) here, along with other details that might be useful, like what SOAP server s/w you are using, what version of Python, what platform. HTH, John From ggpolo at gmail.com Thu Mar 27 06:37:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 27 Mar 2008 07:37:06 -0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: <47EB35FF.4020407@gmail.com> References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> Message-ID: 2008/3/27, Alex9968 : > Guilherme Polo wrote: > > 2008/3/26, Alex9968 : > > > >> Hi all, > >> > >> I use Tkinter's Pack widget geometry manager (I really prefer it over > >> using visual GUI designers), so my question is which other GUI toolkits > >> have similar functionality. > >> > > > > The geometry manager isn't related to using GUI designers tools at > > all. And each toolkit has it's own way to do the things, wxPython uses > > sizers, PyGtk uses containers. > > > > Well, the geometry manager isn't *directly* related to using GUI > designers, but as Pack arranges widgets automatically, using GUI > designers isn't required, while with geometry managers that don't, GUI > designers are necessary (if you start placing widgets programmatically, > you'll end up reinventing something like Tkinter's Pack or Grid geometry > manager). I hope I can be understood clearly this time ;-) Not at all, can't understand your point yet. GUI designers aren't just for placing widgets, they also will keep the interface design separated from your code. > > >> Secondly, I like the detailed widget borders configuration possible in > >> Tkinter, which can be used to tweak GUI look, and wonder if other > >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) > >> look in Windows, but I'm afraid it can be quite different (and ugly) on > >> other platforms. > >> > > > > You sure can, but differently. > > > > I suppose any toolkit allows setting parameters like "no border", "flat > border" and "3d border", but which ones can set ANY type of border to > ANY widget like Tkinter does? For example set GROOVE border to buttons > and text widgets (instead of traditional wide raised/lowered borders), > which is cool (in my opinion). > The widgets subclass some base class, which contains some common methods which could be the border and relief for example. In the case of PyGtk, border width is controlled at Container, so most widgets will have this feature, but the relief style of the widget is not common to all widgets so you will need to check this one (Button has it). In wxPython, widgets will subclass Window, which has all you want and more. But PyQt doesn't seem to care much about this, you can change the widget to flat (if it makes sense to that widget have setFlat method) but not much related to the borders. You could recheck your use-cases and see if they are acceptable. > > > >> (The reason I ever consider moving from Tkinter is some inconveniences, > >> involving for example window scrolling, plus its smaller amount of > >> widgets compared to some other toolkits, plus its (rumored) ugly look on > >> certain environments. I will not necessary change the toolkit, but I > >> have to consider it) > >> > >> > > > > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > > Tkinter for upcoming GSoC. For now you could try using Tile extension, > > and update to Tk 8.5. If you don't want to use extensions, then you > > will have to wait or change the toolkit for now. > > > > Thanks. I haven't heard of Tile before, now I will keep this in mind. > You forgot to mention WHAT you're planning to solve ;-) , so I have to > add that Tile is modernization of Tk widgets (so it fixes ugly look). > WHAT I'm planning to solve, quote from my own paragraph: "I'm planning to "solve" this, I'm suggesting inclusion of Ttk into Tkinter for upcoming GSoC." I would like to add the possibility to use Ttk widgets into tkinter, providing you have Tk 8.5. It would solve the problem of "not enough widgets" and the other one of "being ugly" mainly. Tk 8.5 also auto-fixes some other problems, it provides smooth-scrolling for the text widget, for example. But keep in mind that using Tk 8.5 in Python is not yet supported (but possible). > > > >> Could anyone with experience in different toolkits help, please > >> > >> Thanks > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > > > > > > > > -- -- Guilherme H. Polo Goncalves From george.sakkis at gmail.com Mon Mar 31 09:29:27 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 06:29:27 -0700 (PDT) Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> <13uusct7elou5e3@corp.supernews.com> Message-ID: On Mar 31, 6:15 am, Peter Otten <__pete... at web.de> wrote: > George Sakkis wrote: > > On Mar 30, 9:03 am, Peter Otten <__pete... at web.de> wrote: > >> Steven D'Aprano wrote: > >> > On Sun, 30 Mar 2008 01:27:18 -0300, Gabriel Genellina wrote: > > >> >> Second try: > >> > ... > >> >> Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing > >> >> with each call. But it's the only way I could find, at least without > >> >> changing the code template used by timeit. > > >> > Eeek. Talk about namespace pollution. > > >> > Thanks for the effort, but if that's the only solution, I think the > >> > solution is worse than the problem! > > >> > Perhaps it's time for me to take a different approach. > > >> [snip] > > >> Maybe the following enhancement of timeit would be worthwhile? > > > [snip] > > > That would be great. I sometimes avoid timeit altogether because > > setting up the environment is so cumbersome. Can you post the patch to > > bugs.python.org so it doesn't get lost ? > > Looking into > > http://svn.python.org/view/python/trunk/Lib/timeit.py?rev=54953&view=... > > I discovered that the Python developers took a different approach and timeit > now allows callables for setup and statement: > > >>> def f(): print 42 > ... > >>> timeit.Timer(f).repeat(1, 1) > > 42 > [3.3855438232421875e-05] > > So my patch is probably a case of instant obsolescence... > > Peter I'm afraid that the taken approach is worse than your patch. For one thing, it allows only zero-arg functions. Of course one can work around it by passing "lambda: f(...)" but that's adding extra overhead which can be measurable for small fast functions. Even if passing *args and **kwds to a Timer is allowed, that's still going to be slower (because of tuple unpacking and whatnot) as Steven's attempt above showed. I think it's at least worth bringing this to the attention of the developers. George From gagsl-py2 at yahoo.com.ar Wed Mar 19 21:50:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 22:50:20 -0300 Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> <0742e0b8-d917-4f2f-bbf2-34e1c3d6ce9c@s13g2000prd.googlegroups.com> Message-ID: En Wed, 19 Mar 2008 20:16:36 -0300, John Machin escribi?: > On Mar 20, 9:14 am, sturlamolden wrote: >> Is a Python set implemented using a hash table? > > What don't you understand about the comments in the first two > screenfuls of Objects/setobject.c? That comment was unnecesarily harsh, don't you think? -- Gabriel Genellina From fakeaddress at nowhere.org Tue Mar 18 06:53:28 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 18 Mar 2008 03:53:28 -0700 Subject: win32: emulating select() on pipes In-Reply-To: References: Message-ID: gangesmaster wrote: > i'm trying to figure out if a pipe on win32 has data for me to read. [...] > does anyone know of a better way to tell if data is available on a > pipe? > something that blocks until data is available or the timeout is > elapsed, In Win32 WaitForMultipleObjects and WaitForMultipleObjectsEx do that, for up to 64 objects. In the Hammond Win32 extension package, they're exported by win32event. If 64 pipes in one call isn't enough, there are completion ports. CreateIoCompletionPort is in win32file. A third way in Win32 is WriteFileEx and a completion routine, but it looks like the extension module doesn't support it. I have not used the functions from the Hammond package, and I notice the doc strings are None. You can probably figure the wrappers out by reading the Microsoft documentation and trying stuff. And of then there's the source. If you put together a simple working example, I hope you'll post it. -- --Bryan From mail at timgolden.me.uk Sun Mar 16 10:30:11 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:30:11 +0000 Subject: Spaces in path name In-Reply-To: <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> Message-ID: <47DD2EF3.1080900@timgolden.me.uk> joep wrote: > I assume that there is some difference how subprocess.call and > subprocess.Popen handle and format the command. subprocess.Popen does > the correct formatting when only one file path has spaces and requires > double quoting, but not if there are two file paths with spaces in it. The briefest of code explorations shows that subprocess.call simply hands straight off to Popen, passing args & kwargs along verbatim, and then calls .wait on the result. ie, this: subprocess.call (['a.exe', 'b.doc']) simply becomes: subprocess.Popen (['a.exe', 'b.doc']).wait () What I haven't investigated yet is whether the additional flags your example is passing (shell=True etc.) cause the main Popen mechanism to take a different path. I'll spend some time on that this pm, unless someone gets in first with more of a clue than I currently have. TJG From cwitts at gmail.com Tue Mar 11 03:01:47 2008 From: cwitts at gmail.com (Chris) Date: Tue, 11 Mar 2008 00:01:47 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <0d6402a4-62ee-4a5a-b26b-07a4f37cdc97@d62g2000hsf.googlegroups.com> On Mar 11, 5:44?am, Nathan Pinno wrote: > Why does my compiler say invalid syntax and then highlight the > quotation marks in the following code: > > # This program is to find primes. > primes = [] > import math > import gmpy > while 1: > ? ? run = int(raw_input("Do you want to calculate primes? 1 = yes and > 2 = no. ")) > ? ? if run == 1: > ? ? ? ? y = int(raw_input("What number do you want to use as the final > number to calculate with? ")) > ? ? ? ? x = int(raw_input("What number do you want to start > calculating primes from? ")) > ? ? ? ? while x < 2: > ? ? ? ? ? ? print "Number must be at least 2 for math reasons." > ? ? ? ? else: > ? ? ? ? ? ? while x < y: > ? ? ? ? ? ? ? ? prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) > ? ? ? ? ? ? ? ? if prime < 0: > ? ? ? ? ? ? ? ? ? ? primes.append(x) > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print x " is not prime. " # highlights the final " > here > ? ? ? ? ? ? ? ? x = x + 1 > ? ? ? ? ? ? print primes > ? ? elif run == 2: > ? ? ? ? break > ? ? else: > ? ? ? ? print "Sorry, not a choice. Please enter your choice again." > print "Goodbye." > > How do I fix such an invalid syntax? > > TIA, > Nathan Pinno The reason that line is giving you a syntax error is because you have no comma between your variable and the string. Same reason you can do something like 'print a b c' but instead have to use 'print a, b, c' From baba_mmx at yahoo.it Thu Mar 13 16:14:52 2008 From: baba_mmx at yahoo.it (Mauro "Baba" Mascia) Date: Thu, 13 Mar 2008 21:14:52 +0100 Subject: Ping and ARP on both Win and Linux in Python Message-ID: <47D98B3C.7070307@yahoo.it> Hi, this is my question: I want to know if several switch (about 50) in a big lan are up and then know their MAC addresses to do a list that contains host name, ip and mac. I know only the range of their IP addresses (the host name it's simply to know using socket.gethostn. The first idea it's to ping all ip, parse the response and then execute the command "arp -a" and parse the response. However this way depends on the operating system and the ping response depends too from the language. Another way it's to open the main page of the switch and parse the HTML code where i can find the MAC address. However this way depends on the particular brand's switch. I know (or better i think) that there is a third way: make ping and arp building the packets with socket and so on (but i dont have understand in what way do this). Any suggestion? (i've already search in google, found many sources but a lot of them don't works or don't do what im trying to do...) Regards, Mauretto. From castironpi at gmail.com Wed Mar 12 15:15:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 12:15:09 -0700 (PDT) Subject: for-else References: Message-ID: On Mar 11, 4:43?am, NickC wrote: > On Mar 4, 11:27 pm, bearophileH... at lycos.com wrote: > > > > > The meaning is explicit. While "else" seems to mean little there. > > So I may like something similar for Python 3.x (or the removal of the > > "else"). > > Consider a loop with the following form: > > while 1: > ? if : > ? ? <0-to-many times code block> > ? else: > ? ? <0-to-1 times code block> > ? ? break > > A break, return or exception in the 0-to-many times code block will > obviously skip over the 'else' part of that if statement - it will > only be executed if evaluates as a false value. The above > code is actually equivalent to a normal Python while-loop: > > while : > ? <0-to-many times code block> > else: > ? <0-to-1 times code block> > > For loops aren't quite so straightforward since the termination > condition is tied up with the StopIteration exception, but the clause > keeps the same name as the corresponding clause on the while loop. > Thinking of it as break-else (as someone else posted) probably isn't a > bad way to look at the situation. > > Cheers, > Nick. Here's what try: else: says. "when control flows off the end of the try clause." So at least their usage is consistent, even if pessimistic. They might be using, "2. in addition to the persons or things mentioned or implied: Who else was there?" - dictionary.com. But conflate with 'if-else', the if and else are mutually exclusive. Maybe the if-else should be if-orelse. One's a misnomer. From tjreedy at udel.edu Tue Mar 11 13:19:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 13:19:12 -0400 Subject: Check For SELF Variable Existance References: <-8215347293566648508@unknownmsgid><8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> <40727.816677145$1205243089@news.gmane.org> Message-ID: "Robert Rawlins" wrote in message news:40727.816677145$1205243089 at news.gmane.org... | Thank you Simon, | | I was hoping there would be something as simple as that :-) | >>> class Spam(object): | ... def egg(self): | ... if hasattr(self, 'chips'): print 'got chips!' I strongly suggest that you read Library Reference Ch.2 on builtin functions and types. From gagsl-py2 at yahoo.com.ar Thu Mar 6 16:32:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 19:32:35 -0200 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 14:40:47 -0200, escribi?: > On Mar 6, 12:17?am, "Daniel Fetchinson" > wrote: >> >> > What does exec( open( 'modA.py' ).read() ) do? >> > > A more appropriate formulation of the 'question behind the words' > would have been, 'are there any weird corner cases in which it doesn't > import modA? I recognize it doesn't on .pyc and .pyd files, but you > could say exec( open( 'modA.py' ).read() ) ==> import modA, even if > import modA =!=> exec( open( 'modA.py' ).read() ) all the time. Then write the question that way. Working crystall balls are hard to find nowadays... They're different; no module object is created by the exec statement. When the import machinery determines that certain module isn't already loaded, and that the .py version has to be used, it does something like this: newmodule = sys.modules[modulename] = ModuleType(modulename) # constructor sets __name__ and a null __doc__ newmodule.__builtins__ = current builtins newmodule.__file__ = filename code = read from filename and compile it exec code in newmodule.__dict__ > However, a way of asking that's more direct would have been, "Wait... > can't you create multiple module instances like that?", but since > we've already seen successful loadings of at least the builtins, > that's been treated. There are ways to create many instances of the same module, but not using a plain import statement, or using the API in the intended way. > Maybe you even hear the right thing if I say, > "Does exec( open( 'modA.py' ).read() ) do the things of import modA?" Only in part, as you can see above. > Yes, I can read the docs, but no, I can't check every possible > combination of modules. > The idea behind a singleton is to ensure something. You want non- > primary instances impossible to create. However, if (wording got > tangled here) for singleton A, if class B does the same thing, just > has different allocations-- it's own-- then A is still a singleton. > The writer of B hasn't defeated or contradicted the letter or spirit > of A. > > OP's question might have come from a variety of perspectives. In some > ways yes, in others no. That is, if you try to reinstantiate modA, > you get the same instance. But if you try really hard, you get a new > one. Are you looking for an extension to import modA that won't > return an instance that is old? > > So far, I know this: modules and classes are both namespaces. Are > those singletons? Strictly speaking, neither classes nor modules are singletons; classes are instances of type, and modules are instances of their type, and there are many instances of each. We can consider "qualified singletons", where we want to have a single instance of a class given certain attributes. In that sense, modules are "named" singletons; Python tries to ensure that, given a module name, the module object returned is always the same one - even if you spell the name in different ways. The import statement, the __import__ builtin, the imp module, the PyImport_AddModule C function, all of them try to ensure that. Of course there are ways to shoot yourself in the foot -by example, creating a new module "in the fly" with PyModule_New- On the contrary, classes have no such restrictions. Of course, for classes defined at the global level in a module, you can't have two of them with the same name, but that's just because the module namespace can't hold two values for a single name. But you can create classes dinamically, or define them inside a function, or... lots of ways of creating many instances of the "same" class, and Python won't enforce them to be always the same object. So, I'd say that modules are named singletons, and classes aren't singletons at all. -- Gabriel Genellina From kellygreer1 at yahoo.com Tue Mar 25 19:30:20 2008 From: kellygreer1 at yahoo.com (kellygreer1) Date: Tue, 25 Mar 2008 16:30:20 -0700 (PDT) Subject: Filtering a Python list to uniques Message-ID: What is the best way to filter a Python list to its unique members? I tried some method using Set but got some "unhashable" error. lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ] # how do i reduce this to lsttwo = [ 1, 2, 3, 4, 5, 6 ] Is there a page on this in the Python in a Nutshell or the Python Cookbook? Did I miss something? Kelly Greer kellygreer1 at nospam.com change nospam to yahoo From python at rcn.com Tue Mar 18 13:17:19 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 18 Mar 2008 10:17:19 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: <0c6e45f4-c995-476f-bb65-a7da4d98ee30@s19g2000prg.googlegroups.com> On Mar 18, 2:57 am, Simon Forman wrote: > Is there a more efficient way to do this? > > def f(L): > '''Return a set of the items that occur more than once in L.''' > L = list(L) > for item in set(L): > L.remove(item) > return set(L) > > |>> f([0, 0, 1, 1, 2, 2, 3]) > set([0, 1, 2]) def f(L): seen = set() dups = set() for e in L: if e in seen: dups.add(e) else: seen.add(e) return dups Raymond From pradiprai at gmail.com Mon Mar 31 06:53:37 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 31 Mar 2008 16:23:37 +0530 Subject: ERROR: Python C API version mismatch for module dbi Message-ID: Hi Steve, Can you guide me how to install a 2.5 version of dbi for it to work ? Thanks !! Pradeep Pradeep Rai wrote: > Hi All, > > I have upgraded python v2.5.2 from python v2.4.3. The upgradation > results into following error: > "Python C API version mismatch for module dbi: This Python has API > version 1013, module dbi has version 1012." > > Please suggest, how to resolve this error to proceed further. > > Regards, > Pradeep Rai > > Don't try and drag 2.4 extension modules into the 2.5 environemnt. You will have to install a 2.5 version of dbi for it to work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC *http://www.holdenweb.com/* -- *http://mail.python.org/mailman/listinfo/python-list* -------------- next part -------------- An HTML attachment was scrubbed... URL: From DustanGroups at gmail.com Fri Mar 14 08:23:42 2008 From: DustanGroups at gmail.com (Dustan) Date: Fri, 14 Mar 2008 05:23:42 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <39edb37d-ee5a-4b18-aeb0-9f53af74fd7e@13g2000hsb.googlegroups.com> Message-ID: <86a6d375-0397-4cb1-aca2-552196350894@v3g2000hsc.googlegroups.com> On Mar 13, 1:56 pm, yoz wrote: > This will cause a hidden feature of python and the OS, known as the > 'python easter egg', to activate - erasing all data on the hard disk and > then reporting how many bytes of data are left. > > Usually "None" ;-} - This really is a 'gotcha'.... (Aren't you sorry you > cheated and typed this in !!) > > So the answer is 5 ? Good one. You got a smile out of me. From grante at visi.com Thu Mar 20 11:59:47 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 20 Mar 2008 15:59:47 -0000 Subject: Can I run a python program from within emacs? References: <13u50796m76e9c7@corp.supernews.com> Message-ID: <13u52fj5btjug80@corp.supernews.com> On 2008-03-20, jmDesktop wrote: > On Mar 20, 11:21?am, Grant Edwards wrote: >> On 2008-03-20, jmDesktop wrote: >> >> > Hi, I'm trying to learn Python. ?I using Aquamac an emac >> > implementation with mac os x. ?I have a program. ?If I go to the >> > command prompt and type pythong myprog.py, it works. ?Can the program >> > be run from within the editor or is that not how development is done? >> > I ask because I was using Visual Studio with C# and, if you're >> > familiar, you just hit run and it works. ?On Python do I use the >> > editor for editing only and then run the program from the command >> > line? >> >> http://www.google.com/search?q=emacs+python > > Gee. Thanks. Golly. You're welcome. Don't the hits on the first page answer your question? They explain how to do things like run python programs from within emacs (including how to do source-level debugging). This is probably one of the better pages that the google search above found: http://wiki.python.org/moin/EmacsEditor -- Grant From sturlamolden at yahoo.no Sun Mar 16 13:25:29 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 10:25:29 -0700 (PDT) Subject: Basics of Python,learning References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <8d7e8d6b-3ddd-491b-811f-99986eb29158@h11g2000prf.googlegroups.com> On 16 Mar, 17:25, Guido van Brakel wrote: > Why is this not working,and how can I correct it? [code skipped] There is no way of correcting that. Delete it and start over. From kyosohma at gmail.com Sun Mar 16 09:42:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 16 Mar 2008 06:42:16 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <754ec817-1039-44d2-9c8e-1fe28f688747@n58g2000hsf.googlegroups.com> > But it gets worse. The lightning talks, traditionally the best, newest > and edgiest part of the conference, were also sold like commercial air > time. Vendors were guaranteed first pick on lightning talk slots, and > we in the audience, expectantly looking forward to interesting and > entertaining content, again started to feel like things were awfully > commercial. And what seemed like a good idea, moving lightning talks > into plenary sessions with no competition, began to look like another > way to deliver a captive audience to vendors. > This was my first time at PyCon and when I went to the Lightning Talks yesterday, I was also under the impression that they were for attendees. About half of the ones I saw were commercials. It was weird and made me wonder if they were always like that. > On top of that, the quality of the presentations was unusually low. > I'd say that 80% were not worth going to -- there were definitely some > good ones, but it was a lot of pain to discover them. > Do you mean the "official" presentations or the lightning talks? I thought both were kind of bad. Jeff Rush was great in both of the sessions I saw and the gaming presenters were also good. But I saw a lot of people who had never presented and were unprepared. In fact, one didn't have any code whatsoever to share and the other one only started showing some code during the last 10 minutes of his time. The sponsor keynotes weren't all bad. I thought the White Oaks guy was quite sincere and it was cool to hear about Python from the business side. And the Google rep probably had the slickest presentation I've ever seen. In retrospect, I'm not sure what it had to do with Python though. Mike From max at alcyone.com Tue Mar 4 03:44:04 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 04 Mar 2008 00:44:04 -0800 Subject: sympy: what's wrong with this picture? In-Reply-To: <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> Message-ID: Mensanator wrote: > On Mar 3, 11:58 pm, Erik Max Francis wrote: >> Mensanator wrote: >>> I'm not hard to please at all. >> No, of course not, since logically you must think all software is useless. > > Somehow, I expected better logic from people who call themselves > programmers. So you agree with me. Lack of prefection = uselessness. Thanks for being honest, whether your realized you defeated your own disclaimer or not. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis I wonder if heaven got a ghetto -- Tupac Shakur From castironpi at gmail.com Wed Mar 12 02:16:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 11 Mar 2008 23:16:36 -0700 (PDT) Subject: merging intervals repeatedly References: <20b3dfb8-c5b7-4fd0-97a1-93f590f54595@u10g2000prn.googlegroups.com> <13tescq9e809idb@corp.supernews.com> Message-ID: <3602eec7-5ffc-4241-b495-dd4ca21fc213@e39g2000hsf.googlegroups.com> > > Correct. I meant the final should be > > (1,30), (29,40), (50,100) > > ? ? ? ? Actually, even that is incorrect -- note that ,30 overlaps 29, Actually, given the specification, (overlaps > N count), (1,15), (20, 30), (29, 40), (50, 66), (62,100) is right, since 66-62= 4<= 5. [1] > ? ? ? ? Since this feels like a homework assignment, I won't be posting my > code... What are the pros and cons, Mr. Bieber? Is cl.py a nanny or a resource? If someone asks for help, there's probably a reason, and if they cheat, then they don't learn Python. Besides, two or three in a row and that's justified. Besides, business programmers get plenty of answers here-- that's cheating too. Besides, just 'cause you help somebody else, doesn't mean everyone will. Besides, your solution doesn't work for floats. [1] > My ultimate goal is to produce a final set of intervals such that not > two intervals overlap by more than N, where N is a predetermined > length. From jules at js3d.co.uk Sun Mar 2 05:33:51 2008 From: jules at js3d.co.uk (Jules Stevenson) Date: Sun, 2 Mar 2008 10:33:51 -0000 Subject: Escaping a triple quoted string' newbie question In-Reply-To: <004401c87c4f$e27b6f60$0301a8c0@laptop> References: <002801c87c3b$d6cd42b0$0301a8c0@laptop> <004401c87c4f$e27b6f60$0301a8c0@laptop> Message-ID: <004801c87c50$e83fc3a0$0301a8c0@laptop> Sorry, original post got a bit mangled, which didn't help the explanation at all, reposted stuff: Apologies if the terminology in this email is a little incorrect, I'm still finding my feet. I'm using python to generate some script for another language (MEL, in maya, specifically expressions). Maya runs python too, but unfortunately its expression language still has to use the maya syntax. If I pass the expression this code (excuse the double spacing, email seems to e ignoring my line breaks): #runtime code [mel] expRuntime=""" float $pos[]=particleShape1.worldPosition; setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; """ dynExpression (p, s=expRuntime, rad=1) #generate the expression Then maya errors out, however if I pass maya an 'escaped' version: expRuntime=""" float $pos[]=particleShape1.worldPosition;\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """ Then all is well. My question is, is there any way to convert the first variable example to the second? It's a lot easier to type and on the eye. From python.list at tim.thechases.com Sat Mar 1 17:05:50 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 01 Mar 2008 16:05:50 -0600 Subject: Where's GUI for Python? In-Reply-To: <62tvhmF256jk7U1@mid.individual.net> References: <62tvhmF256jk7U1@mid.individual.net> Message-ID: <47C9D33E.9040407@tim.thechases.com> > I'm certain there is an API for creating > GUI's but as far i can find it in the > http://docs.python.org/tut/tut.html > the only "gui" is in "Guido". > > What do i miss? The batteries-included GUI: import tkininter Add-on solutions include wxPython, PythonCard and many others. GIYF: http://google.com/search?q=python+gui -tkc From pharmapsychotic at gmail.com Tue Mar 25 15:32:17 2008 From: pharmapsychotic at gmail.com (blackpawn) Date: Tue, 25 Mar 2008 12:32:17 -0700 (PDT) Subject: Circular references not being cleaned up by Py_Finalize() Message-ID: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> I've been trying to get garbage collection of circular references to work properly with no success then I noticed the documentation stating that it just doesn't: >From documentation on Py_Finalize() -> "Memory tied up in circular references between objects is not freed. " I copy pasted the Noddy example for circular reference breaking from the documentation and set a break point in its Noddy_dealloc function and sure enough even that simple example doesn't work properly. So what's the deal here? :) I want all objects to be freed when I shut down and their destruction functions to be properly called. Is there really no way to make this happen? Many thanks for any insights, Jim From ernesto.adorio at gmail.com Sun Mar 23 17:26:33 2008 From: ernesto.adorio at gmail.com (ernesto.adorio at gmail.com) Date: Sun, 23 Mar 2008 14:26:33 -0700 (PDT) Subject: On copying arrays Message-ID: Is there a conceptual difference between best =test[:] and best = [x for x in test] ? test is a list of real numbers. Had to use the second form to avoid a nasty bug in a program I am writing. I have to add too that I was using psyco in Python 2.5.1. Regards, Ernie. From dickinsm at gmail.com Wed Mar 26 18:02:46 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 26 Mar 2008 15:02:46 -0700 (PDT) Subject: Newbie: unsigned shift right References: <276efacc-dad3-4844-a3b4-a6845c71473b@h11g2000prf.googlegroups.com> Message-ID: On Mar 26, 5:42?pm, Sal wrote: > Is there any way to do an unsigned shift right in Python? When I enter > (-1>>1) the answer is -1. What I'm looking for is the equivalent of an > unsigned shift in C or the ">>>" operator in Java. What answer were you hoping for, and why? 2**31-1? 2**63-1? If you're thinking of the -1 as representing a particular fixed-width bit pattern, try doing a bitwise 'and' operation with a suitable mask first. For example, if you're thinking of -1 as a 32-bit quantity, then (-1 & (2**32-1)) >> 1 might produce what you want. Mark From michael.wieher at gmail.com Thu Mar 20 16:35:48 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 15:35:48 -0500 Subject: Haskell vs ?? Message-ID: Just to help clear up my own understanding of this discussion, this is basically a language that obfuscates details and makes low-level decisions in a "average-best" way, and thus allows for lazy people to write kind of decent code quickly? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Mar 23 17:31:04 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 14:31:04 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: On Mar 24, 2:53 am, John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : TypeError: object of type 'bool' has no len() I presume you meant if len(dict.keys()) > 0: > > is expensive for large dictionaries, and makes loops O(N^2). I don't understand "makes loops O(N^2)" ... what I see in the dict_keys function in Objects/dictobject.c is that it makes one linear pass through its table, ignoring unused and formerly-used slots; seems like O(N) where N is the size of the table. Where did you get O(N^2) from? From arnodel at googlemail.com Thu Mar 13 16:31:00 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 13:31:00 -0700 (PDT) Subject: Python regex References: <9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c@i29g2000prf.googlegroups.com> Message-ID: On Mar 13, 8:22?pm, "Andrew Rekdal" <@comcast.net> wrote: [...] > in your expression above.. > > >>> r = re.compile(r'/\*(.*?)\*/') > > what does the 'r' do? It means the literal is a 'raw string' : >>> print 'Hi\nthere!' Hi there! >>> print r'Hi\nthere!' Hi\nthere! >>> If you haven't done so already, I suggest reading the tutorial. Here is a link to the relevant section on strings: http://docs.python.org/tut/node5.html#SECTION005120000000000000000 -- Arnaud From castironpi at gmail.com Sun Mar 16 02:44:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 23:44:01 -0700 (PDT) Subject: string literal or NoneType References: <97eb79e8-e79d-4bd8-af6d-108579e7d54c@59g2000hsb.googlegroups.com> Message-ID: <5f8034ef-2886-4ed5-9820-07d7788039d8@t54g2000hsg.googlegroups.com> > > | hi all > > | i want to check a condition and if true should return a filename > > | string ?from a list.if the condition is false i am returning a > > | "" ?(string literal).. Identity is the strictest test, and you can't define your own. Lots of things can evaluate to True. Only None is None. Does that help? From mal at egenix.com Mon Mar 3 06:17:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 03 Mar 2008 12:17:39 +0100 Subject: Can one get "for x in y" to work for non builtin classes? In-Reply-To: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <47CBDE53.9030805@egenix.com> On 2008-03-02 15:06, Preben Randhol wrote: > Hi > > I'm making a kind of ordered dictionary class. It is not exactly a > dictionary, but it uses a list and dictionary to store the data. > > Something like: > > class dbase(list): > '''Database class keeping track of the order and data''' > > def __init__(self): > self.__data = {} > self.__order = [] > self.__uniq_id = 0 > > I'm just wondering if it is possible to get my class to work so that if > one do: > > > d=dbase() > d.append("Data") > d.append([1,2]) > > one can do like this to iterate over the data. > > for x in d: > ... > > I'm looking at the list class but I don't quite understand from pydoc > which __ __ methods I have to implement to get the above to work. The easiest is to implement an iterator which then get's returned by the .__iter__() method. http://www.python.org/doc/lib/typeiter.html It's also possible to implement .__getitem__() and .__len__() methods and have Python create an iterator on-the-fly. That's how Python used to work before iterators were added to the language. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 03 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From bjorn.m.meyer at gmail.com Thu Mar 20 22:09:33 2008 From: bjorn.m.meyer at gmail.com (Bjorn Meyer) Date: Thu, 20 Mar 2008 20:09:33 -0600 Subject: script won't run using cron.d or crontab Message-ID: <73b543b30803201909g57b559fck5b9d150abfa89468@mail.gmail.com> I appologize if this been discussed previously. If so, just point me to that information. I have done a fair bit of digging, but I haven't found a description of what to actually do. I have a fairly lengthy script that I am able to run without any problems from a shell. My problem is, now I am wanting to get it running using crontab or cron.d. It seems that running it this way there is a problem with some of the commands that I am using. For instance "commands.getoutput" or " os.access". I am assuming that there is something missing within the environment that cron runs that fails to allow these commands to run. If anyone has any information that would help, it would be greatly appreciated. -- Have a GREAT day!!! Bjorn -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 11 07:32:16 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 11 Mar 2008 12:32:16 +0100 Subject: Python PDF + Pictures In-Reply-To: References: Message-ID: <47d66d8f$0$14029$426a74cc@news.free.fr> durumdara at gmail.com a ?crit : > Hi, dear Python Masters! > > I wanna ask about the Python and PDF creating. > > I have many photos, and I wanna make some "presentation" from these > photos, a "thumbnail" like document with one image per one page. > > If I wanna make one document now I do this: > I execute a python script that create a html site with resized pictures, > and split this html site to 50 images per one html file. > Next I open these files in OpenOffice Writer by hand, and save them as > PDF document with poor quality (image compression 95%, image DPI 75). > This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that > can opened everywhere (because of PDF format). > > But I wanna automatize this process with python. > The technic that I will use is this: > 1.) Collect the files in dirs. > 2.) I process one dir in one time. > 3.) I get the files. > 4.) I resize them to max. 1024/768. > 5.) I put the actual image file to the PDF document. > 6.) After each 50. file I open new numbered PDF. > 7.) Every picture placed in one page, and every page orientation set up > as the picture orientation (Portrait or Landscape). > > The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. > > Do you knows about a PDF maker library with I can make this thing? > > Or other technic to simplify the making? Dont know if this will match your needs, but you may want to have a look at pisa: http://www.htmltopdf.org/ From larry.bates at websafe.com` Sat Mar 22 15:00:26 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Sat, 22 Mar 2008 14:00:26 -0500 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. > > Thank you. ABSOLUTELY. Get them started with a REAL programming language that will teach them proper fundamentals. I wish Python would have been around 25 years ago when I taught incoming Freshmen at local University. To get students to understand about variable references, etc. I always started them with Assembler so they could understand what was actually going on. I see so may on this forum that have the wrong ideas about variable names/ storage. Good Luck, Larry Bates From bj_666 at gmx.net Mon Mar 31 16:13:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 20:13:05 GMT Subject: Command line input References: <00c99698-e5cb-49dd-88fd-8130623a4e45@e6g2000prf.googlegroups.com> Message-ID: <65cuuhF2fhuoaU4@mid.uni-berlin.de> On Mon, 31 Mar 2008 12:39:54 -0700, hexusnexus wrote: > How do I receive input from the command line in Python? Direct way `sys.argv`, comfortable way `optparse`. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Mon Mar 10 17:15:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 14:15:09 -0700 (PDT) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <43df18b2-6dcc-4d58-9d25-7637b419ec5f@h11g2000prf.googlegroups.com> <2fb584c3-9add-43d4-9421-d397c7517d82@13g2000hsb.googlegroups.com> <73ff3479-56b5-48ec-948e-b0a4c797adb2@b1g2000hsg.googlegroups.com> Message-ID: <1befdccf-2efc-4640-bcf8-b4a792d8e646@i29g2000prf.googlegroups.com> On Mar 11, 3:19 am, cokofree... at gmail.com wrote: > The trick in the case of when you do not want to guess, or the choices > grow too much, is to ask the user to tell you in what format they want > it and format according to their wishes. > > Neatly avoids too much guessing and isn't much extra to add. The plot is about understanding input, not formatting output. From steve at holdenweb.com Tue Mar 4 06:51:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 06:51:25 -0500 Subject: Command line arguments in Windows In-Reply-To: References: <6f04af5d-32c4-42e2-b08b-77531547439d@47g2000hsb.googlegroups.com> Message-ID: Chris wrote: > On Mar 4, 8:38 am, "Mike Walker" wrote: >>> If you run a python file, ie. just double clicking it the only >>> argument you will have will be the filename of the script. If you >>> create a shortcut to the script and in the target box add your >>> arguments (if you have quotation marks place them after not inside) >>> you will see your arguments. fwiw you answered yourself in the third >>> paragraph. >> As I mentioned I am working from the command line, not clicking on the icon. >> The only difference between it working and not is the python prefix, which >> is why I was thinking this is some sort of file association problem. >> >> I probably wasn't as clear as I could have been in the third paragraph. >> >> argtest.py arg1 arg2 arg3 - Does not work only get sys.argv[0] >> python argtest.py arg1 arg2 arg3 - Works > > That seems rather wierd, just running argtest.py arg1 arg2 arg3 I get > the correct output, Python 2.5.1 from python.org but running on XP > though. Potentially an issue with Vista... ? Strange as it may seem, there have been issues with other Windows command processors, and one in particular (I can never remember which one) messes up IO redirection when the pathext mechanism is used to select the executable that processes the Python file. So I would tend to suspect yet another variation on this familiar theme given your testing results. But I don't intend to tangle with Vaster any sooner than I must. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From siddhantgoel at gmail.com Tue Mar 4 10:13:02 2008 From: siddhantgoel at gmail.com (Siddhant) Date: Tue, 4 Mar 2008 07:13:02 -0800 (PST) Subject: tab completion? Message-ID: <6aa4a77e-822b-4efa-a3c6-b8f79ecaeb57@e10g2000prf.googlegroups.com> Hi people. I was just wondering if a tab-completion feature in python command line interface would be helpful? If yes, then how can I implement it? Thanks, Siddhant From gagsl-py2 at yahoo.com.ar Sun Mar 2 05:55:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 02 Mar 2008 08:55:51 -0200 Subject: Escaping a triple quoted string' newbie question References: <002801c87c3b$d6cd42b0$0301a8c0@laptop> <004401c87c4f$e27b6f60$0301a8c0@laptop> <004801c87c50$e83fc3a0$0301a8c0@laptop> Message-ID: En Sun, 02 Mar 2008 08:33:51 -0200, Jules Stevenson escribi?: > Sorry, original post got a bit mangled, which didn't help the > explanation at > all, reposted stuff: > > Apologies if the terminology in this email is a little incorrect, I'm > still > finding my feet. > > I'm using python to generate some script for another language (MEL, in > maya, > specifically expressions). Maya runs python too, but unfortunately its > expression language still has to use the maya syntax. > > If I pass the expression this code (excuse the double spacing, email > seems > to e ignoring my line breaks): > > #runtime code [mel] > expRuntime=""" > float $pos[]=particleShape1.worldPosition; > > setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; > > setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; > > setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; > """ > dynExpression (p, s=expRuntime, rad=1) #generate the expression > > Then maya errors out, however if I pass maya an 'escaped' version: > > expRuntime=""" > float $pos[]=particleShape1.worldPosition;\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\nsetAttr > (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2]; """ > > Then all is well. My question is, is there any way to convert the first > variable example to the second? It's a lot easier to type and on the eye. Except for the doble-space on the first version, \n is the line separator on both, so I'll ignore them. """one two""" is the same thing as "one\ntwo" (even on Windows). The only remaining difference that I see is " -> \" def mayaquote(text): return text.replace('"', '\\"') -- Gabriel Genellina From bbxx789_05ss at yahoo.com Fri Mar 28 21:40:45 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Mar 2008 18:40:45 -0700 (PDT) Subject: problem with CGIHTTPServer References: Message-ID: On Mar 28, 10:12?am, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 12:38:45 -0300, 7stud ? > escribi?: > > > After I start the server script, load the html page in my browser, and > > click on the link, I get the desired output in my browser, but the > > server script outputs the following in my terminal: > > > localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/ > > 1.1" 200 - > > localhost - - [28/Mar/2008 08:51:22] code 404, message File not found > > localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 - > > > What are the error messages on lines two and three? > > Line 3 is your browser (IE, I presume?) asking for an icon for the site. > Seehttp://en.wikipedia.org/wiki/Favicon > Safari. > I don't know about line 2, maybe it's just a diagnostic message related to ? > line 3. Try refreshing the page, or using an inexistent url to see if it ? > still appears. Or put any icon as /favicon.ico to make your browser happy. > I searched for a .ico file on my computer, then copied it into the same directory as the server program, and renamed the .ico file: favcion.ico Then I loaded my html file in Safari and clicked on the link, and this was the output: localhost - - [28/Mar/2008 19:30:31] "GET /my_cgi_scripts/test.py HTTP/ 1.1" 200 - localhost - - [28/Mar/2008 19:30:31] "GET /favicon.ico HTTP/1.1" 200 - So, it looks like Safari automatically requests a .ico file from a server. Thanks. From grahn+nntp at snipabacken.se Sun Mar 30 17:02:44 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 21:02:44 GMT Subject: standard input, for s in f, and buffering Message-ID: One thing that has annoyed me for quite some time. I apologize if it has been discussed recently. If I run this program on Unix (Python 2.4.4, on Debian Linux) import sys for s in sys.stdin: print '####', s , and type the input on the keyboard rather than piping a file into it, two annoying things happen: - I don't see any output until I have entered a lot of input (approximately 8k). I expect pure Unix filters like this to process a line immediately -- that is what cat, grep and other utilities do, and also what Perl's while(<>) { ... } construct does. - I have to type the EOF character *twice* to stop the program. This is also highly unusual. If I saw this behavior in a program, as a long-time Unix user, I'd call it a bug. I realize this has to do with the extra read-ahead buffering documented for file.next() and that I can work around it by using file.readline() instead. The problem is, "for s in f" is the elegant way of reading files line by line. With readline(), I need a much uglier loop. I cannot find a better one than this: while 1: s = sys.stdin.readline() if not s: break print '####', s , And also, "for s in f" works on any iterator f -- so I have to choose between two evils: an ugly, non-idiomatic and limiting loop, or one which works well until it is used interactively. Is there a way around this? Or are the savings in execution time or I/O so large that everyone is willing to tolerate this bug? BR, /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From george.sakkis at gmail.com Tue Mar 18 14:20:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 11:20:58 -0700 (PDT) Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <782b7e65-646b-48d8-8a2b-b595424c9783@e6g2000prf.googlegroups.com> On Mar 18, 6:03 am, Gabriel Rossetti wrote: > Carsten Haese wrote: > > On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > > >> Hello, > > >> I am reading core python python programming and it talks about using the > >> idiom > >> described on > >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183. > > >> I'm using python 2.5.1 and if I try : > > >> class MyClass(object): > >> def __init__(self): > >> self._foo = "foo" > >> self._bar = "bar" > > >> @property > >> def foo(): > >> doc = "property foo's doc string" > >> def fget(self): > >> return self._foo > >> def fset(self, value): > >> self._foo = value > >> def fdel(self): > >> del self._foo > >> return locals() # credit: David Niergarth > > >> @property > >> def bar(): > >> doc = "bar is readonly" > >> def fget(self): > >> return self._bar > >> return locals() > > >> like suggested in the book (the decorator usage) I get this : > > >> >>> a=MyClass() > >> >>> a.foo > >> Traceback (most recent call last): > >> File "", line 1, in > >> TypeError: foo() takes no arguments (1 given) > > >> but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : > > >> >>> a = MyClass() > >> >>> a.foo > >> 'foo' > > >> does anyone have an idea as of why this is happening? > > > You're mixing two completely different approaches of building a > > property. If that code is actually in the book like that, that's a typo > > that you should mention to the author. > > > The @property decorator can only be used to turn a single getter > > function into a read-only attribute, because this: > > > @property > > def foo(...): > > ... > > > is the same as this: > > > def foo(...): > > ... > > foo = property(foo) > > > and calling property() with one argument builds a property that has just > > a getter function that is the single argument you're giving it. > > > The recipe you're referring to uses a magical function that returns a > > dictionary of getter function, setter function, deleter function, and > > docstring, with suitable key names so that the dictionary can be passed > > as a keyword argument dictionary into the property() constructor. > > However, that requires the magical foo=property(**foo()) invocation, not > > the regular decorator invocation foo=property(foo). > > > HTH, > > I was able to get it t work with the decorator by doing this : > > def MyProperty(fcn): > return property(**fcn()) > > and using it like this : > > class MyClass(object): > def __init__(self): > self._foo = "foo" > self._bar = "bar" > > @MyProperty > def foo(): > doc = "property foo's doc string" > def fget(self): > return self._foo > def fset(self, value): > self._foo = value > def fdel(self): > del self._foo > return locals() # credit: David Niergarth > > @MyProperty > def bar(): > doc = "bar is readonly" > def fget(self): > return self._bar > return locals() > > Cheers, > Gabriel Also check out a related recipe that doesn't require returning locals() explicitly: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698 George From dteslenko at gmail.com Wed Mar 5 07:03:32 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 5 Mar 2008 15:03:32 +0300 Subject: draining pipes simultaneously In-Reply-To: References: Message-ID: <91325fec0803050403k14e87c2j44a79601a8fa9348@mail.gmail.com> On Wed, Mar 5, 2008 at 1:34 PM, wrote: > The Queue.get method by default is blocking. The documentation is not > 100% clear about that (maybe it should report > the full python definition of the function parameters, which makes > self-evident the default value) but if you do > help(Queue.Queue) in a python shell you will see it. > Hence, try using a timeout or a non-blocking get (but in case of a non > blocking get you should add a delay in the > loop, or you will poll the queues at naximum speed and maybe prevent > the other threads from accessing them). Thanks for advice! Finally I came up to following loop: while to.isAlive() or te.isAlive(): try: while True: line = qo.get(False) if out_filter: out_filter(line) except Queue.Empty: pass try: while True: line = qe.get(False) if err_filter: err_filter(line) except Queue.Empty: pass Inserting delay in the beginning of the loop causes feeling of command taking long to start and delay at the end of the loop may cause of data loss when both thread became inactive during delay. From lists at cheimes.de Sun Mar 23 21:24:25 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 24 Mar 2008 02:24:25 +0100 Subject: PyTuple_Check and other type check functions didn't check the NULL pointer In-Reply-To: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> References: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> Message-ID: NotGuru schrieb: > My questions is: is it necessary to check the null pointer in the > macro or it's a job for the user? Semantically all the type check > should report a false if a null pointer is encountered. I've already > had the patch to this issue but I am not sure if I think this problem > right. I don't know if there are some python core developers around > but I would like to hear all opinions towards this. Unless stated otherwise no Py* or PY* function is NULL safe. You have to check for NULL unless the docs *explicitly* say it's safe to call it with a NULL argument. Christian From metawilm at gmail.com Mon Mar 10 15:14:40 2008 From: metawilm at gmail.com (metawilm at gmail.com) Date: Mon, 10 Mar 2008 12:14:40 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <63i6j9F2793buU1@mid.uni-berlin.de> Message-ID: On Mar 9, 2:21 pm, "Diez B. Roggisch" wrote: > Is this soft-exception implemented anywhere, so that one can see what > experiences and best practices have evolved around using it? Lie's idea is to separate exceptions in two groups, those that must be handled and those that don't. A better way is to have two different ways to raise exceptions: one exceptional situation can be "Hard" in some situations and "Soft" in others, and it is up to the way of raising to make the choice, while the exception stays the same. Common Lisp has two ways of raising: functions "error" and "signal". Python's "raise" is like CL's "error": you end up in the debugger if the exception is not handled. Exceptions that are raised by CL's "signal" don't have to be caught: if there is no matching "except" clause the raise statement becomes a "pass". Or as Wikipedia states nicely: "Conditions are a generalization of exceptions. When a condition arises, an appropriate condition handler is searched for and selected, in stack order, to handle the condition. Conditions which do not represent errors may safely go unhandled entirely; their only purpose may be to propagate hints or warnings toward the user." http://en.wikipedia.org/wiki/Exception_handling#Condition_systems - Willem From castironpi at gmail.com Thu Mar 6 01:25:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 22:25:27 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: <0806e3fe-7f69-4c3e-871c-9ac1a2289e94@d62g2000hsf.googlegroups.com> > I accept my question about classes being singletons is not well-formed, > not even in my own mind. I guess one way of asking is, for any two class > objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? C and D are instances of metaC in that. class metaC( type ): def what( self ): return self class C( metaclass= metaC ): pass class D( metaclass= metaC ): pass assert C is C.what() and D is D.what() #print( C.what(), D.what() ) C= metaC('C',(),{}) D= metaC('D',(),{}) assert C is C.what() and D is D.what() #print( C.what(), D.what() ) furthermore. From michael.wieher at gmail.com Mon Mar 17 16:18:33 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 15:18:33 -0500 Subject: placing a Python com object into Excel In-Reply-To: References: Message-ID: 2008/3/17, Mathew : > > Hi > I have seen examples from Mark Hammonds book where a Python COM object > is accessed from Excel with a VBA script. But, what if I want to Insert > a Python COM into the Sheet itself? > > When I try this, a list of available objects appear. But my object isn't > on the list. > > Anybody have any ideas? Well, how are you inserting it? My experience with MS-Visual Studio is that you first have to register the COM/ActiveX component with the system in some way (ie: so that Visual Studio knows it exists) and from there, you drop it into your application using the GUI. If Visual Studio hasn't been told the COM object exists, it won't be able to incorporate it. Here's a link describing how to insert a COM object in Visual Studio .NET. http://support.microsoft.com/kb/307367 If that doesn't help, look for something similar, not sure which version of VS you're running. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave_mikesell at fastmail.fm Sat Mar 8 21:11:12 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 18:11:12 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> On Mar 8, 5:14 pm, "K Viltersten" wrote: > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); > > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. > > I don't see how this is dislikeable. Please > explain. When get2Dfrom3D changes its signature but the comment is not changed. That's where I have a problem, and it's only a matter of time before it happens. From castironpi at gmail.com Sun Mar 9 16:48:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 13:48:07 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> Message-ID: D'Aprano suggested callbacks. How does this work for you? class SomeNumeric(object): def __div__(a, b): if b == 0: raise ZeroDivisionError ## Hard Exception... if a == 0: msgboard- ZeroNumerator() f = a / b i = a // b if f == float(i): msgboard- IntegerDivision() return a // b #? return i? else: msgboard- FloatDivision() return a / b #? return f? If it works, I can write some implementations of msgboard and discuss its scope. It sounded at one point like you were augmenting control flow, but you cleared that up by saying, raise SoftException is not a true raise. Correct? There is a limit to how many behaviors you can fit in a single statement in any language. What behaviors is determined by other choices in the language design. Those choices have many consequences, some linguistic, some social, and some personal. If a dictator always makes impersonal decisions, which linguistic + social ones should he make? If the answer is, "No, we will not strike note J and K because we elected to strike notes L and M instead", then it's disappointing, but it might ease that to know what L and M are. Lastly, that notation I wrote was kind of sly. I might favor msgboard( ZeroNumerator() ) or even msgboard.add( ZeroNumerator() ). How far are you willing to come from the OP's proposal to get it to work? If they add something half-way there, but you don't get exactly what you want, is that fair? From john106henry at hotmail.com Mon Mar 31 14:45:33 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 11:45:33 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <89d34053-4b16-49df-9153-eb3625249ad4@u10g2000prn.googlegroups.com> Message-ID: <7cee8a91-ebcc-43d0-8a84-63eca2409dc7@s19g2000prg.googlegroups.com> On Mar 31, 10:38 am, Amit Gupta wrote: > On Mar 31, 10:37 am, John Henry wrote: > > > > > On Mar 31, 10:24 am, Amit Gupta wrote: > > > > Hi > > > > I am looking for a some tool that can convert python scripts to > > > executable on Linux. > > > > I found freeeze.py as the only option so far. Couple of queries on > > > freeze: > > > > 1. Have anyone used the freeze utility and any experiences to share > > > from that? > > > 2. Is there any enterprise-level exe-builder for python on linux > > > (ActiveState has nothing)? > > > > Any other related commets are also welcome. > > > > Thanks > > > Amit > > > I don't know about freeeze.py but for me, I've been using py2exe, and > > also pyinstall quite often and they both work for me. > > Isnt py2exe for windows only? Not sure. I use it on windows. > I haven't looked at pyinstall.. Is it for linux? It appears so - according to http://www.pyinstaller.org/ From bj_666 at gmx.net Thu Mar 27 09:41:47 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Mar 2008 13:41:47 GMT Subject: Pickle: several class instance objects in one file? References: Message-ID: <651mgqF2dfhueU4@mid.uni-berlin.de> On Thu, 27 Mar 2008 12:28:25 +0000, Dominique.Holzwarth wrote: > Lets say I have instances of class A and class B: > > a = A() > b = B() > > Is it possible to pickle both of these instances to the same pkl-file or > will that have any bad impact for unpickle (i.e. the instance are > 'mixed' or 'destroyed')? Or should I rather use a seperate file for > every class instance I want to pickle? You can pickle a data structure, for example a tuple, that contains both instances. Or you can write one after the other into the pickle file. Then you'll have to retrieve them in two steps too. > Another very basic question about pickling class instances: > > To store the value of attributes of an instance is it enough for the > pickling-algorithm to use the __dict__ or do I have to implement the > _setstate_ and _getstate_ function? I didn't really get the meaning of > those while reading the python user manual... Usually `pickle` just works. Those methods can be used if you want to customize the process, for example if you don't want to pickle the entire object but just parts of it. Ciao, Marc 'BlackJack' Rintsch From needin4mation at gmail.com Mon Mar 24 13:00:45 2008 From: needin4mation at gmail.com (jmDesktop) Date: Mon, 24 Mar 2008 10:00:45 -0700 (PDT) Subject: Is IronPython real Python? Message-ID: I know that IronPython and CPython are different in that one does not use the .net framework, but are they both really the same Python language. From my basic understanding, it will depend on what the programmer's goal is as to which of the two would be used, but I didn't know if they were really the same language. From janeczek at gmail.com Thu Mar 27 14:36:34 2008 From: janeczek at gmail.com (=?UTF-8?Q?Micha=C5=82_Janeczek?=) Date: Thu, 27 Mar 2008 19:36:34 +0100 Subject: SoC project: Python-Haskell bridge - request for feedback In-Reply-To: References: <561cb5bc0803241337i1ebac4bbse5fdc5e6be1985a0@mail.gmail.com> Message-ID: <561cb5bc0803271136x35cf72f2ga2a5119c4379f9c5@mail.gmail.com> On Thu, Mar 27, 2008 at 7:23 PM, Joshua Kugler wrote: > You might want to take a look at this: > > http://www.artfulcode.net/articles/extending-python-almost-anything/ > > That might get you started at least on the calling Haskell part. Yes, ctypes is on my related works/projects to study list. I am trying to keep this public draft low on technical details, and focus on the idea/deliverables part. I am hoping that a casual python list subscriber is more likely to read/comment on a shorter document :) Thanks for your feedback! -- Regards, Michal From NeilFang2008 at gmail.com Mon Mar 10 05:25:04 2008 From: NeilFang2008 at gmail.com (Neil.Fang.CN) Date: Mon, 10 Mar 2008 02:25:04 -0700 (PDT) Subject: How to create Python object in C/C++ extension by class name? Message-ID: Hello I'm trying to write a C++ extension like this: //----------------------------------------------------------------------- // C++ code class ActorBase {...}; // export ActorBase to Python as a new type class ActorManager { void addNewActor(const char* actorClassName) { ????? } } // export ActorManagerto Python as a new type //----------------------------------------------------------------------- The question is how to implement ActorManger::addNewActor(), I want the class name can be a Python class which inherits the C++ class ActorBase? Thanks -- Neil From tjreedy at udel.edu Wed Mar 19 18:56:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Mar 2008 18:56:46 -0400 Subject: keeping state in an iterator object by rebinding next() References: <200803192036.22626.wbsoft@xs4all.nl> Message-ID: "Wilbert Berendsen" wrote in message news:200803192036.22626.wbsoft at xs4all.nl... | Hi, | | i am writing a simple parser, that generates tokens. The parser needs to | maintain some state, because some parts of the file consist of different | tokens. I thought the object could simply remember its state by assigning | it's next() method to the method that is currently parsing. When the state | changes, the called method rebinds next() and the next token will be returned | by that function. Here's an example, proving that this indeed works. For some undisclosed version. | >>> class A: I stronly suspect that if you make this a new-style class by adding '(object)', this will not work. See below. | ... def a(self): | ... self.next = self.b This attaches the class attribute (method) b to the instance | ... return 1 | ... def b(self): | ... self.next = self.a | ... return 2 | ... def __iter__(self): | ... return self Since A does not have a 'next' (or __next__, in 3.0), instances of A are not really iterators, under the new iterator protocol, and hence __iter__ above is not valid. See below. | ... | >>> a=A() | >>> a.a() | 1 | >>> a.next() | 2 | >>> a.next() | 1 | >>> j=0 | >>> for i in a: In 3.0a3, which uses new-style classes and iterator protocol, this croaks with TypeError: iter() returned non-iterator of type 'A' | ... j += 1 | ... if j > 10: break # prevent from running endlessly | ... print i I suspect that this only works because the for-loop, not finding A.next, used the old iterate-by-index protocol and calls a.next with 0, 1, 2, .... To find out, put 'print self' inside methods a and b. ... | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | >>> | | my question is: is this legal Python? In whatever version you used, it seems to be, but not in the future. | An iterator could save the next() method object, You mean, the iterator user. | and in that case it could stop working.... It works now, because | apparently the for- construct resolves 'next' each time for the object before | calling it. A standard idiom for explicit iteration with a new style iterator and 'while' would do just what you suggest. itnext = iter(a).next try: while True print itnext() except StopIteration: pass | The other solution would be just jumping to the correct method from within the | next() method. But that gives an extra call... Or, make a and b staticmethods, remove the self param, and make __iter__ a generator def __iter__(self): while True: yield self.next() The speed penalty of the indirection thru the generator is minimal. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Sun Mar 16 17:18:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 17 Mar 2008 08:18:45 +1100 Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> <867f5e04-13cd-4d7f-9458-66ec20449780@s19g2000prg.googlegroups.com> Message-ID: <87abky1i6i.fsf@benfinney.id.au> sturlamolden writes: > If you don't know how to install a C compiler like Microsoft Visual > Studio, you should not be programming computers anyway. Utter elitist nonsense. Programming should be made easier, and I see Python as a very good language for making programming easier. Lowering the barrier for prospective hackers to get into programming is a good thing. The installation of a C compiler is incidental to that, and has no necessary connection with programming. Placing meaningless roadblocks, as you suggest should be done, is anathema to education. -- \ "The best mind-altering drug is truth." -- Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney From godzillaismad at gmail.com Mon Mar 17 07:26:56 2008 From: godzillaismad at gmail.com (Godzilla) Date: Mon, 17 Mar 2008 04:26:56 -0700 (PDT) Subject: Anomaly in time.clock() Message-ID: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> Hello, I have been reading a thread about time.clock() going backward, which is exactly what I am seeing... the thread generally leaning toward the problem is caused by multi-processor machines. But I am seeing it at a single CPU computer, and running XP. The error I am seeing between two very close invokation of time.clock() is always around 3.5 seconds! This is enough to throw a lot of the timing requirement in the software out of the window... this is a fairly serious problem. A quick fix will be to capture the time.clock() going backward 3.5 seconds, and then adjust rest of the system accordingly. But I don't feel like this is a good way around this problem. I was using time.time() before switching to time.clock(). The reason I changed is because I need a way to calculate elapsed time independent of system time. Should I just stick with time.time() instead? Or is there another way to calculate elapsed time accurately, independent of system time being changed? From max at alcyone.com Sun Mar 16 02:43:40 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 Mar 2008 23:43:40 -0700 Subject: 'join' in the wrong word for the method in class Thread. In-Reply-To: References: Message-ID: castironpi at gmail.com wrote: > 'join' in the wrong word for the method in class Thread. That's the standard term in threading. If it's not familiar to you, well, bummer, but there's not much more that can be done about that than for you to read the literature. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Take the slow train / To my destination -- Sandra St. Victor From lists at cheimes.de Tue Mar 25 22:33:43 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 26 Mar 2008 03:33:43 +0100 Subject: python hash() function In-Reply-To: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> References: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Message-ID: <47E9B607.4080204@cheimes.de> Alvin Delagon schrieb: > Hello, > >>>> hash("foobar") > -1969371895 > > Anyone can explain to me how the hash() function in python does its work? A > link to its source could help me a lot also. I'm looking for a way to > replicate this function in php. Thanks in advance. The code is in Objects/stringobject.c:string_hash() Christian From vokinloksar at yahoo.se Mon Mar 31 22:28:13 2008 From: vokinloksar at yahoo.se (vokinloksar at yahoo.se) Date: Mon, 31 Mar 2008 19:28:13 -0700 (PDT) Subject: socket error when loading the shell? References: <24bce233-dfac-4dca-8abb-280ba16826e5@c19g2000prf.googlegroups.com> Message-ID: i mean vpython(www.vpython.org). tried wi5th the normal IDLE too and it worked later after i posted this but now it doesnt work again. and i havent chnaged my firewall in between. python.exe works but i want the idle not the dos-interpreter. From carlwenrich at gmail.com Fri Mar 21 11:15:55 2008 From: carlwenrich at gmail.com (Carl) Date: Fri, 21 Mar 2008 08:15:55 -0700 (PDT) Subject: How do I change the font size for the default coordinates in matplotlib? References: Message-ID: <40494a77-db0a-46a9-8b62-94e3f8ed5884@i7g2000prf.googlegroups.com> On Mar 20, 10:12 pm, "attn.steven.... at gmail.com" wrote: > On Mar 20, 8:20 pm, Carl wrote: > > > I've searched the user manual (and this forum) but I don't see > > anything that helps. > > Did you mean the font size for the ticks or for > the labels? Here's an example: > > from pylab import * > > x = arange(0, 2*pi, 0.01) > y = sin(2*pi*x) > > rcParams.update({'xtick.labelsize': 5, 'ytick.labelsize': 10}) > > subplot(111) > plot(x,y) > ylabel("Vert", fontsize=15) > xlabel("Horiz", fontsize=20) > show() > > -- > Hope this helps, > Steven It was the: rcParams.update({'xtick.labelsize': 5, 'ytick.labelsize': 10}) that fixed it. Thanks. From galaviel at yahoo.com Mon Mar 24 06:24:43 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Mon, 24 Mar 2008 10:24:43 +0000 (UTC) Subject: always getting 'None' return value from =?utf-8?b?UHlPYmplY3RfQ2FsbE9iamVjdA==?= References: <1206317136.3365.6.camel@localhost.localdomain> Message-ID: problem fixed ... my bad. I was using a dispatch mechanism where the C code always called the same python dispatch function, with the actual function name to invoke as arguments. Anyway, I forgot the 'return' statement. The code is below. Many thanks and apologies for the help provided :) def dispatch(*args): #print "Dispatch: args are " #print args[1:] global_dict = globals() return global_dict[args[0]](args[1:]) From jgelfand01 at gmail.com Wed Mar 26 11:21:39 2008 From: jgelfand01 at gmail.com (jgelfand) Date: Wed, 26 Mar 2008 08:21:39 -0700 (PDT) Subject: _tkinter fails when installing Python 2.4.4 References: <64tahuF2absebU1@mid.uni-berlin.de> <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> <64uoqiF2dcihhU1@mid.uni-berlin.de> Message-ID: <19b9409f-f4c3-4254-b445-980462f11bf1@13g2000hsb.googlegroups.com> On Mar 26, 7:02 am, "Diez B. Roggisch" wrote: > > I think the actual problem is that the linking doesn't find the > XftGlyphExtends. I can only guess, but it might be related to > 64-bit-problems. Make sure you have the library that contains the > XftGlyphExtends is available in the lib64 dirs and so forth. I tried running configure with --x-include="/usr/X11R6/include" --x- libraries="/usr/X11R6/lib" (in addition to the flags above) and got the same error. I believe XftGlyphExtends is defined in "Xft.h" which is located in the directory "/usr/X11R6/include/X11/Xft". Based on the output below, python looks in "/usr/X11R6/include" but not in this directory: building '_tkinter' extension gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/_tkinter.c - o build/temp.linux-x86_64-2.4/_tkinter.o gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno- strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/local/ yosi/Python-2.4.4/./Include -I/usr/local/yosi/ciao-4.0/ots/include -I/ usr/local/include -I/usr/local/yosi/Python-2.4.4/Include -I/usr/local/ yosi/Python-2.4.4 -c /usr/local/yosi/Python-2.4.4/Modules/tkappinit.c - o build/temp.linux-x86_64-2.4/tkappinit.o gcc -pthread -shared build/temp.linux-x86_64-2.4/_tkinter.o build/ temp.linux-x86_64-2.4/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib - L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -ltk8.5 -ltcl8.5 - lX11 -o build/lib.linux-x86_64-2.4/_tkinter.so When I try setting CFLAGS="-I/usr/X11R6/include/X11/Xft" and re- running configure, I get the same error message regardless if I tell python to it to use the 32 bit of 64 bit X-Windows libraries. How should I force python to look in this directory? Thanks a lot -- Yosi From bj_666 at gmx.net Mon Mar 17 03:12:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Mar 2008 07:12:13 GMT Subject: Strange problem with structs Linux vs. Mac References: <03006f0e-6ac4-41ef-9e55-715c976fe82f@c19g2000prf.googlegroups.com> <47dd579d$0$9035$5402220f@news.sunrise.ch> <3f28438a-7264-4086-9bb4-9c6551d1fb26@d21g2000prf.googlegroups.com> <47dd5caf$0$9029$5402220f@news.sunrise.ch> Message-ID: <646judF2ao2tkU1@mid.uni-berlin.de> On Sun, 16 Mar 2008 18:45:19 +0100, Martin Blume wrote: > I don't think this qualifies as a bug, but I am astonished > that the struct module does not tell you whether you are > big endian, you have to find out yourself with > struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] Maybe a little more compact and readable: In [92]: sys.byteorder Out[92]: 'little' Ciao, Marc 'BlackJack' Rintsch From coolman.guron at gmail.com Mon Mar 24 10:07:16 2008 From: coolman.guron at gmail.com (binaryj) Date: Mon, 24 Mar 2008 07:07:16 -0700 (PDT) Subject: URL encoding References: <9693ffda-1454-4d56-acee-1e6fc4ebeccb@h11g2000prf.googlegroups.com> Message-ID: On Mar 24, 7:04 pm, vvangelov... at gmail.com wrote: > Is there any method in the standard modules that can perform proper > url encoding according to RFC? whats wrong with the current encoding ??? it just works fine!!! or is it that u dont know about urllib.urlencode() ?? From Lie.1296 at gmail.com Sat Mar 29 16:06:13 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 29 Mar 2008 13:06:13 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Message-ID: On Mar 30, 2:57?am, mac_the_sco... at hotmail.com wrote: > Hi there. > I downloaded python a couple of days ago from the official site and > have started writing simple programs in the python gui (this being my > first attempt at programming ever). The only thing is when I write > python code in a text editor and save it as a .py file, when I double > click it all that happens is a black box flashes up on the screen, but > nothing else!? > > At first I thought this was because I had only written a hello world > program, and that the box had displayed "hello world" and then closed. > But then I wrote a program requiring user input and the same thing > happened... Am I doing something wrong? > > Thanks in advance for any help! > > //mac open the program in IDLE (or any other Python IDEs). I'm guessing that your program is printing a traceback (error) when trying to get input that's why it immediately closes itself. From tgl at sss.pgh.pa.us Mon Mar 3 11:12:28 2008 From: tgl at sss.pgh.pa.us (Tom Lane) Date: Mon, 03 Mar 2008 11:12:28 -0500 Subject: [SQL] compiling plpython compilation error In-Reply-To: <47CBFA04.30300@fmed.uba.ar> References: <47CBFA04.30300@fmed.uba.ar> Message-ID: <24554.1204560748@sss.pgh.pa.us> Gerardo Herzig writes: > Hi all. Im having a hard time trying to compile the plpython package. > This is the error make gives me: > /usr/lib/python2.5/config/libpython2.5.a(abstract.o): relocation > R_X86_64_32 against `a local symbol' can not be used when making a > shared object; recompile with -fPIC Well, I'd try following the error message's advice: use -fPIC not -fpic. Note that it's not real clear whether this needs to be done for plpython, or libpython, or perhaps both; so you might well be in for making a custom libpython installation. regards, tom lane From castironpi at gmail.com Tue Mar 18 06:09:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 18 Mar 2008 03:09:08 -0700 (PDT) Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> Message-ID: <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> On Mar 17, 8:16?pm, Gabriel Genellina wrote: > On 17 mar, 19:43, castiro... at gmail.com wrote: > > > Can I allocate a second console window, so I can place certain output > > to that directly, and leave the original streams alone? ?I tried some > > things in subprocess (Py 3a3 /WinXP) but they failed. ?I don't know if > > it's supposed to be possible though, so I didn't press very hard or > > keep the code. ?If it is, I can go repro where it went south. ?Is it? > > Have you tried using the creationflags argument to subprocess.Popen? > Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation > for CreateProcess athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx > (Note that a process can be attached at most to one console) > > If your goal is to output some debug information, try using > OutputDebugString + the DebugView utility fromwww.sysinternals.com One console per process is fine, but I tried using 'cmd.exe', 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32) as separate processes. The sign is the console window splashes up and vanishes right away. >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdout= subprocess.P IPE, creationflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 >>> p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe', stdout= subprocess.PI PE, creationflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 >>> p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe /K', stdout= subprocess .PIPE, creationflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 >>> f= open( 'temp.txt', 'a' ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\cmd.exe /K', stdout= f, creatio nflags= subprocess.CREATE_NEW_CONSOLE ) >>> p.poll() 0 ------------------------Couple other symptoms. >>> f.write( b'abc' ) 'f.write' is not recognized as an internal or external command, operable program or batch file. >>> f.write( b'abc' ) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\io.py", line 1240, in write s.__class__.__name__) TypeError: can't write bytes to text stream >>> f.write( 'abc' ) 3 >>> >>> ^Z >>> >>> ^Z ^Z 5000 09871234 ------------------------ >>> f.write('2'*2000) 2000 >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> f= os.fdopen( q[0], 'a' ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> f.read() Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\io.py", line 1378, in read res += decoder.decode(self.buffer.read(), True) File "C:\Programs\Python\lib\io.py", line 564, in read self._unsupported("read") File "C:\Programs\Python\lib\io.py", line 240, in _unsupported (self.__class__.__name__, name)) io.UnsupportedOperation: BufferedWriter.read() not supported >>> f.read(1) Traceback (most recent call last): File "", line 1, in File "C:\Programs\Python\lib\io.py", line 1384, in read readahead, pending = self._read_chunk() File "C:\Programs\Python\lib\io.py", line 1277, in _read_chunk readahead = self.buffer.read1(self._CHUNK_SIZE) AttributeError: 'BufferedWriter' object has no attribute 'read1' >>> f.write() Traceback (most recent call last): File "", line 1, in TypeError: write() takes exactly 2 positional arguments (1 given) >>> f.write('2') 1 >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags= 16 ) >>> p= subprocess.Popen( 'c:\\windows\\system32\\more.com', stdin= f, creationfl ags=0 ) 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 22222222222222222222222222222222222222222222222222222222222222222222222222222222 ------------------------- Writing my own process is an option. I did not try sysinternals yet. From shakefu at gmail.com Fri Mar 7 17:41:22 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:41:22 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <16db6135-a8eb-432f-9b50-91efe65e2b3b@13g2000hsb.googlegroups.com> Message-ID: On Mar 7, 4:33 pm, Carl Banks wrote: > On Mar 7, 5:08 pm, shak... at gmail.com wrote: > > > I'm new to python and I was wondering if there are any intelligent > > date/time parsing modules out there. I've looked at strptime (or > > whichever it is) and mxDateTime from the eGenix package. I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > > So are there any modules that allow for that kind of parsing? > > GNU date can do a lot of these things--if your Django server is > running Linux it probably has GNU date installed. (Might not be > practical to start a new process in the middle of a query, especially > a lot of them.) > > From a shell command line, get the current time (in seconds since > epoch, which you can pass to Python time functions) this way: > > date +"%s.%N" > > And you can enter all sort of relative and absolute date strings: > > date +"%s.%N" --date='last monday' > date +"%s.%N" --date='a year ago' > date +"%s.%N" --date='10pm tuesday' > > These all apparently work. Now all you have to do is call it from > Python using subprocess module and you're set. (DO NOT use os.system > for this since it starts a shell process, which is unnecessarily slow, > and dangerous when passed user input.) > > Carl Banks Super sweet! I didn't even know you could do craziness like that in python. Thanks for the advice! From rbossy at jouy.inra.fr Sat Mar 8 09:18:26 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 08 Mar 2008 15:18:26 +0100 Subject: os.chdir In-Reply-To: References: Message-ID: <1204985906.47d2a03248681@www.jouy.inra.fr> Quoting Maryam Saeedi : > I have a problem using os.chdir on linux. What should I do if I want to > change to root directory? The below does not work: > > os.chdir("~/dir1") It is not mentioned in the documentation but I'm pretty sure os.dir() doesn't do tilde expansion since this is usually performed by a shell. You should use instead: os.chdir(os.join(os.environ['HOME'], 'dir1')) Cheers, RB From roman at smoerz.org Fri Mar 7 05:04:52 2008 From: roman at smoerz.org (Roman Bertle) Date: 07 Mar 2008 10:04:52 GMT Subject: Looking for very light weight template library (not framework) References: Message-ID: * Malcolm Greene : > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. [...] > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. [...] You might look at YAPTU http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305A or YAPTOO http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465508, very small but powerful templating engines. I use YAPTU myself for invoice templating. Regards, Roman From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 21:09:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 01:09:46 -0000 Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <13ur5mq7fugqgc1@corp.supernews.com> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > Gabriel Genellina wrote: >> That's what I said in another paragraph. "sum of coordinates" is using >> a different distance definition; it's the way you measure distance in a >> city with square blocks. I don't know if the distance itself has a >> name, but > I think it is called Manhattan distance in reference of the walking > distance from one point to another in this city. You know, there are other cities than Manhattan. Some of them even have streets and blocks. -- Steven From tjreedy at udel.edu Sat Mar 22 17:42:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Mar 2008 17:42:31 -0400 Subject: Django gets Wired Message-ID: from Wired magazine, April 2008 (arrived today), p.44: Expired: ASP.NET; Tired: PHP; Wired: Django Congrats to the Django crew. http://www.djangoproject.com/ From nick.fabry at coredump.us Wed Mar 19 17:40:39 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Wed, 19 Mar 2008 17:40:39 -0400 Subject: Improving datetime In-Reply-To: <47E17801.606@cheimes.de> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: On Mar 19, 2008, at 16:30, Christian Heimes wrote: > Nicholas F. Fabry schrieb: >> This is a query for information as to how to proceed. I am not a >> professional programmer, but I use Python a great deal to help me >> in my main job, which involves designing schedules for a global >> airline. As such, I use datetime (and dateutil) extensively, and >> after much use, I have come to some conclusions about their >> utility, and how to improve them. Some of these changes are quite >> minor and would result in a large increase in utility (low hanging >> fruit), while some changes are major, and would result in less >> obvious benefits - but these changes would increase the 'Python >> Zen' of them. >> So - where should I propose these changes? Here? python-dev? >> Should I write up a full PEP or should I just give a more informal >> outline with code samples? I would volunteer to help maintain/ >> improve datetime, but I don't speak C at all, unfortunately, and >> datetime appears to be in C. > > Please write a detailed but not too long proposal to the Python > ideas mailing list. The proposal should explain how you like to > improve the datetime module. But *please* don't write a novel. > You'll get more attention when the signal to noise ratio is high. A > bullet list of features is easier to read than a long text block. > Thank you for the prompt response and suggestion! I am writing up a proposal presently. There are, however, two broad category of changes - the 'easy' changes, which could be accomplished with little additional effort, and the 'hard' changes, which would require significant reworking of the datetime class (or a wrapper around it). I was going to break my proposal up into two parts, the easy part and the hard part. Does that sound like a good idea? Or should I unify the two? The prime purpose of all the changes, easy and hard, is to make timezone handling accurate and clear, reduce and make clearer the (application programmer) code required to use them, and give more informaton to the programmer about errors, not silently assume something and pass them. I have to sign up for that mailing list - I will do so, and submit my ideas there. Please clarify how long a novel is? The problem with the modules are not bugs, they are problems with real world use scenarios that result in inescabably ugly code without improvements to the module - so the explanations involve code samples and use cases... so they may be 'long'. Could you suggest a maximum number of (70 char) lines, or an example of an overly long proposal? > I'm a core developer and I may be interested in mentoring your > proposal. I can guide you through the process, review code and > commit it. > Thank you very much for the offer - I greatly appreciate it. I must admit, my motivation is because Python made programming so much fun for me again (my first machine was a Sinclair ZX80, long, long ago), and I want to improve this part of the language so datetime calculations are clean and neat (like the rest of Python) and don't force programmers to manually go through what the library should do for them. > Yes, the datetime module is written in C. But we may move the C code > to _datetime and create a facade module in Python. > That would be excellent for me, because the underlying datetime routines work correctly and quickly; it's the 'topmost' layer that needs to be improved to do the right thing. And, I could then actually write/maintain the Python code in the facade module, rather than request someone else 'do it for me' in C. To summarize my proposal VERY briefly: - Make aware datetime objects display in local time, but calculate/ compare in UTC. - Raise exceptions when an illegal or ambiguous datetime is instantated. Thank you again, Nick > Christian From skip at pobox.com Thu Mar 27 10:53:43 2008 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Mar 2008 14:53:43 +0000 (UTC) Subject: Is subprocess.Popen completely broken? Message-ID: I am trying to replace os.system calls with subprocess.Popen. This simple example fails miserably: >>> proc = subprocess.Popen ("ls /tmp") Traceback (most recent call last): File "", line 1, in File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 594, in __init__ errread, errwrite) File "/home/titan/skipm/local/lib/python2.5/subprocess.py", line 1091, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I also tried explicitly referencing /usr/bin/ls. Same result. What gives? I see this behavior in both Python 2.4 and 2.5 on Solaris 10 and with 2.6alpha on Mac OS X. Frustrated in Chicago... Skip From carsten at uniqsys.com Tue Mar 18 03:30:58 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 18 Mar 2008 08:30:58 +0100 Subject: Multiple Submits in HTML Forms - Cherrypy In-Reply-To: <47df6bd4$1@news.unimelb.edu.au> References: <47df6bd4$1@news.unimelb.edu.au> Message-ID: <1205825458.3212.2.camel@localhost.localdomain> On Tue, 2008-03-18 at 07:14 +0000, Maurice LING wrote: > Hi, > > Assuming that I have this code for Cherrypy 3 > > class Welcome: > def index(self): > return """ >
> > >
""" > index.exposed = True > > How should I write "btn_handler" so that it will perform different > actions when different button is pressed? Something like this would do it: def btn_handler(self, AddBtn=None, EditBtn=None): if AddBtn: return "You pressed Add!" if EditBtn: return "You pressed Edit!" Alternatively you could use a kwargs dictionary and test it for the presence of the "AddBtn" or "EditBtn" keys. HTH, -- Carsten Haese http://informixdb.sourceforge.net From praveena_python at yahoo.com Thu Mar 27 14:29:36 2008 From: praveena_python at yahoo.com (Praveena B) Date: Thu, 27 Mar 2008 11:29:36 -0700 (PDT) Subject: How to take snap shot of the of project screen in Python Message-ID: <286574.25471.qm@web44807.mail.sp1.yahoo.com> An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Wed Mar 12 10:45:29 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 12 Mar 2008 07:45:29 -0700 (PDT) Subject: List Combinations References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: <20b5dc87-166c-4d57-9df6-3ae3bfd83cc1@u10g2000prn.googlegroups.com> On Mar 12, 10:18 am, Gerdus van Zyl wrote: > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus Search for "cartesian product" recipes. George From patrick.waldo at gmail.com Mon Mar 31 14:52:18 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Mon, 31 Mar 2008 11:52:18 -0700 (PDT) Subject: xlrd and cPickle.dump/rows to list Message-ID: <5dd95747-81af-4019-9995-944421ebdfc2@m71g2000hse.googlegroups.com> Hi all, I have to work with a very large excel file and I have two questions. First, the documentation says that cPickle.dump would be the best way to work with it. However, I keep getting: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\python_files\pickle_test.py", line 12, in ? cPickle.dump(book,wb.save(pickle_path)) File "C:\Python24\lib\copy_reg.py", line 69, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle file objects I tried to use open(filename, 'w') as well as pyExcelerator (wb.save(pickle_path)) to create the pickle file, but neither worked. Any ideas would be much appreciated. Patrick From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 20:32:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 00:32:05 -0000 Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> <7xr6e11ghp.fsf@ruckus.brouhaha.com> Message-ID: <13udtk586ijktec@corp.supernews.com> On Sun, 23 Mar 2008 10:45:38 -0700, Paul Rubin wrote: > John Nagle writes: >> What's the cheapest way to test for an empty dictionary in Python? >> >> if len(dict.keys() > 0) : > > I like to think len(dict) is constant time but I haven't checked the > code. Same for bool(dict) (which is what you get when you run "if dict: > ..."). Except that "if dict" doesn't needlessly and wastefully create a bool. >>> from timeit import Timer >>> Timer("if {1:2}: pass").timeit() 1.1590199184417725 >>> Timer("if bool({1:2}): pass").timeit() 1.8825540542602539 Python knows the truth value of built-in types like dicts without actually converting them to bools, or for that matter calling __len__ or __nonzero__ on them. -- Steven From grflanagan at gmail.com Sat Mar 29 08:45:55 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Sat, 29 Mar 2008 05:45:55 -0700 (PDT) Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> <4JnHj.3124$e%6.335@newsfet15.ams> <13us4sh6u8mfn96@corp.supernews.com> Message-ID: <61b59d4e-b7c1-42d8-a132-4b36d63eeb26@m71g2000hse.googlegroups.com> On Mar 29, 11:01 am, Steven D'Aprano wrote: > On Sat, 29 Mar 2008 10:11:28 +0100, Roel Schroeven wrote: > > Steven D'Aprano schreef: > >> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > > >>> Gabriel Genellina wrote: > >>>> That's what I said in another paragraph. "sum of coordinates" is > >>>> using a different distance definition; it's the way you measure > >>>> distance in a city with square blocks. I don't know if the distance > >>>> itself has a name, but > >>> I think it is called Manhattan distance in reference of the walking > >>> distance from one point to another in this city. > > >> You know, there are other cities than Manhattan. Some of them even have > >> streets and blocks. > > > I'm not sure what your point is. The name > > "The" name? You go on to list four additional names, so why do you say > that "Manhattan distance" is THE name? When I studied this at university, > we called it the taxi metric. > > > of the distance happens to be > > Manhattan distance (or taxicab distance, rectilinear distance, L1 > > distance, city block distance; see > >http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid > > point. > > Wikipedia doesn't believe that M-D is the primary or most common name, > and the link you give redirects to "Taxicab distance". Googlefight > agrees: "Taxicab distance" is more than twice as common, and "rectilinear > distance" more than five times as common. > > My point was to draw attention to Robert's unconscious assumptions which > are reflected in his choice of language. Rectilinear distance applies to > more than "distance from one point to another in THIS city" (emphasis > added). > > It applies in parts of Rome, Sydney, London, Moscow and many other > places. It even applies to sleepy little country towns like Bendigo and > Mildura here in Australia. Manhattan is hardly the only place where > cities are carved up into rectangular or square city blocks, and I doubt [...] a metric by any other name... http://news.bbc.co.uk/2/hi/uk_news/northern_ireland/2595215.stm From gagsl-py2 at yahoo.com.ar Mon Mar 31 14:18:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Mar 2008 15:18:50 -0300 Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> <4d1d7d83-8155-4c1a-a807-0b5c951e1192@d21g2000prf.googlegroups.com> Message-ID: En Mon, 31 Mar 2008 09:30:00 -0300, Graeme Glass escribi?: > On Mar 27, 11:01 am, Peter Otten <__pete... at web.de> wrote: >> a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc >> baa bab >> bac bba bbb bbc bca bcb bcc > > Here is a cool solution we came up with during a little interactive > session at our local meet up. > (http://www.python.org.za/pugs/cape-town/cape-town) > > s = 'abcdef' > ["".join([s[j] for j in range(len(s)) if x & (1 << j)]) for x in > range(1,2**len(s)) ] But it's doesn't generate the right sequence, and a lot of elements are missing. For 'abc': ['a', 'b', 'ab', 'c', 'ac', 'bc', 'abc'] It lacks ba, bb, ca, cb, cc, all b??, all c?? - see the sequence quoted above. -- Gabriel Genellina From pavlovevidence at gmail.com Wed Mar 26 14:04:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Mar 2008 11:04:14 -0700 (PDT) Subject: naive packaging question References: Message-ID: <006bd428-beca-4420-b54b-aed805ff1e73@m36g2000hse.googlegroups.com> On Mar 26, 12:33 pm, Scott Sharkey wrote: > Here's the directory structure that I've got so far: > > project
top level directory > setup.py > company eventually, we'll have other modules > __init__.py > error.py some classes that will be used in all > log.py modules > acctdb the acct db interface directory > __init__.py > api.py the abstract class def (derived from object) > specific.py the specific implementation, derived > from the api base class > > For arguments sake, let's call the base class (defined in api.py) > 'BaseClass', and the specific implementation 'SpecificClass(BaseClass)' > > So, in the acctdb/__init__.py, do I do something like this: > > if SPECIFIC_CLASS: > from company.acctdb.specific import SpecificClass as BaseClass Seems pretty reasonable to me. Do you have any specific reasons for being concerned about this organization? (My only minor suggestion would be not to import the SpecificClass as BaseClass, but instead with a name that's different from both, for example, PublicClass. All that does is to avoid a tiny bit of potential confusion down the road.) Carl Banks From castironpi at gmail.com Sat Mar 22 03:23:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 00:23:32 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> <13u45bam9k12n71@corp.supernews.com> <97b69085-f6e9-4a56-be03-a7e19a2e0d4e@u69g2000hse.googlegroups.com> <4a7f2ffa-3ae4-4510-b5e7-3cfced233191@2g2000hsn.googlegroups.com> Message-ID: <210f1e24-649a-43c0-b975-8209211d56de@a70g2000hsh.googlegroups.com> On Mar 21, 1:08?pm, Gabriel Genellina wrote: > Sane programmers replace that crazyness with this code: > > tuple(x+1 for x in y) > > Sane programmers -like D'Aprano, Jerry Hill and me- replace that > crazyness with this code: > > tuple(x/2.5 for x in y) > > Sane programmers don't write such semi-functional things (unless it > helps expressing the problem in certain domains). > I now think that deprecating map, lambda & Co. was a good thing after > all. If you write it that way the first time, you need therapy. Actually, at this point, I (for one, personally) want to investigate 'certain domains'. Tell me it's really bad at everything or what it's good at. What can I respect about it? From code at pizzashack.org Wed Mar 26 19:59:46 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 26 Mar 2008 19:59:46 -0400 Subject: Python 2.2.1 and select() In-Reply-To: <20080326164951.GA6349@noah.org> References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> <20080325020356.GF26870@dragontoe.org> <20080326164951.GA6349@noah.org> Message-ID: <20080326235946.GL26870@dragontoe.org> On Wed, Mar 26, 2008 at 09:49:51AM -0700, Noah Spurrier wrote: > On 2008-03-24 22:03-0400, Derek Martin wrote: > >That's an interesting thought, but I guess I'd need you to elaborate > >on how the buffering mode would affect the operation of select(). I > >really don't see how your explanation can cover this, given the > >following: > > I might be completely off the mark here. I have not tested your code or even > closely examined it. I don't mean to waste your time. I'm only giving a > reflex response because your problem seems to exactly match a very common > situation where someone tries to use select with a pipe to a subprocess > created with popen and that subprocess uses C stdio. Yeah, you're right, more or less. I talked to someone much smarter than I here in the office, who pointed out that the behavior of Python's read() without a specified size is to attempt to read until EOF. This will definitely cause the read to block (if there's I/O waiting from STDERR), if you're allowing I/O to block... :( The solution is easy though... def set_nonblock(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) Then in the function, after calling popen: set_nonblock(io.fromchild.fileno()) set_nonblock(io.childerr.fileno()) Yay for smart people. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From hniksic at xemacs.org Fri Mar 14 11:00:07 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 14 Mar 2008 16:00:07 +0100 Subject: %x unsigned? Message-ID: <87skytbbbc.fsf@mulj.homelinux.net> The %x conversion specifier is documented in http://docs.python.org/lib/typesseq-strings.html as "Unsigned hexadecimal (lowercase)." What does "unsigned" refer to? >>> '0x%x' % 10 '0xa' >>> '0x%x' % -10 '0x-a' Is this a bug or is %x misdocumented? From mmanns at gmx.net Fri Mar 21 15:48:09 2008 From: mmanns at gmx.net (Martin Manns) Date: Fri, 21 Mar 2008 20:48:09 +0100 Subject: How can I make a function equal to 0? Message-ID: Hi, Is there a way to create a function that is equal to 0? I try to redefine __cmp__ but I am pretty stuck. Something like: >>> def f(): return "" ... >>> # Some magic >>> f == 0 True Thanks in advance Martin From arnodel at googlemail.com Tue Mar 25 15:44:33 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 25 Mar 2008 12:44:33 -0700 (PDT) Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> On Mar 25, 6:13?pm, j vickroy wrote: > Hello, > > Here is some pseudo-code that hopefully illustrates what I want to do: > > records = list(...) > for record in records: > ? ? new_fcn = define_a function_for(record) > ? ? instance = my_new_class_instance() > ? ? setattr(instance, 'myfcn', new_fcn) > ? ? instance.execute() # instance.execute() calls instance.myfcn(*args) > > I have looked at some of the functions in the *new* module and > new.code(...), new.function(...), and new.instancemethod(...) appear to > do what I want, but I do not know how to use new.code() and > new.function() -- specifically what its *global* parameter should be. The best way to understand how new.function and new.code work is to look at the Python source. (Objects/funcobject.c and Objects/ codeobject.c, actual objects are defined in and Include/funcobject.h Include/code.h). However, to create a function dynamically in Python it is often no more trouble than a def statement: Funnily enough I can't think of a nice example ATM so here is a bad one: say you want to create a function that checks the spelling of a word, regardless of case. You could a function that returns on-the- fly created functions that check the spelling of a word like this: def get_spellchecker(word): word = word.upper() def check_spelling(candidate): return candidate.upper() == word return scheck_spelling Then >>> check_hypo = get_spellchecker('hypopothamus') >>> check_hypo('Hypopothamus') True >>> check_hypo('Big scary mammal') False (Warning: this is all untested). HTH -- Arnaud From tamim.shahriar at gmail.com Mon Mar 3 09:38:06 2008 From: tamim.shahriar at gmail.com (subeen) Date: Mon, 3 Mar 2008 06:38:06 -0800 (PST) Subject: Delete hidden files on unix References: Message-ID: On Mar 3, 6:13 pm, Philipp Pagel wrote: > loial wrote: > > How can I delete hidden files on unix with python, i.e I want to do > > equivalent of > > rm .lock* > > Here is one way to do it: > > import os, glob > for filename in glob.glob('.lock*'): > os.unlink(filename) > > Alternatively, you could also do this: > > import os > os.system('rm .lock*') > > cu > Philipp > > -- > Dr. Philipp Pagel > Lehrstuhl f. Genomorientierte Bioinformatik > Technische Universit?t M?nchenhttp://mips.gsf.de/staff/pagel Another way is to execute the linux command directly :) Check here: http://love-python.blogspot.com/2008/02/execute-linux-commands-in-python.html regards, subeen. http://love-python.blogspot.com From tenax.raccoon at gmail.com Mon Mar 10 19:10:50 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 10 Mar 2008 16:10:50 -0700 (PDT) Subject: wxPython: some help with Drag&Drop References: Message-ID: <53d59d18-5774-4cef-b34c-f9646888a3c4@d21g2000prf.googlegroups.com> Eric von Horst wrote: > Hi, > > I need some advice on Drag&Drop. > > What I want to achieve is the following: > - I have a window that is divided in two : on the left hand I > have a wx.TreeCtlr and on the other hand a wx.StaticBitmap > > I want to be able to drag an item from the tree onto the static > bitmap. > > I know how to do drag&drop in a treeCtrl but is there a way that I can > make the bitmap detect that something has been dropped on it? > > I would only need to know the name of the tree obj that was dropped on > the bitmap (and the location) > > Any help much appreciated > > > > Erik Take a look at the wxPython demo [1]. In the "Clipboard and DnD" section, there's the "CustomDragAndDrop" demo. It sounds like that's exactly what you want. (It uses the wx.PyDropTarget class to accomplish this, BTW.) [1] The demo package for your platform can be found at "http:// www.wxpython.org/download.php#binaries" --Jason From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:02:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:02:31 -0300 Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: En Sat, 29 Mar 2008 21:48:21 -0300, Paul McGuire escribi?: > What is the collision of spheres? Is it the melding of a sphere of > influence and cosmic sphere? What does it mean to say that such a > collision "doesn't work"? The sphere is the optimal solid for storing > the maximum volume in the minimum area. A sphere can retain the Too much logical cohesion, even if you didn't want it... I'm sorry but you still can't emulate Aaron's jumping thoughts - maybe if you try harder next time... -- Gabriel Genellina From jorge.vargas at gmail.com Sun Mar 9 13:36:44 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sun, 9 Mar 2008 11:36:44 -0600 Subject: Returning values from function to Python shell/IPython In-Reply-To: References: Message-ID: <32822fe60803091036l3380f48aia49348a46c93c0d@mail.gmail.com> On Sun, Mar 9, 2008 at 11:07 AM, Karlo Lozovina <_karlo_ at mosor.net> wrote: > Jorge Vargas wrote: > > > well after all it's a function so the only ways you can get things out > > of it are: > > - return a dict with all the objects > > - use global (very messy) > > - use a decorator to do either of the above. > > Messy, all of those... :(. > > > > on the other hand have you consider using a proper test package? > > instead of inspecting the objects manually from the shell you could > > make it all automatic. with assert statements. you could use the std. > > python testing modules http://docs.python.org/lib/development.html or > > something less verbosed like nose > > Usually, I'm using standard Python testing modules, but sometimes that is > just an overkill. Sometimes I like to do 'exploratory programming', > especially in the early phases of development - create a bunch of objects I > want to play with and do that from IPython. Only way I found out to > somewhat automate this procedure is to have a function that creates all of > the test objects, and then raises an exception at the end. IPython starts > ipdb, so I can work with the objects the function created (without copying > them back to the shell). But this somehow looks too hack-ish for me, so I > was wondering if there was an alternative... > ohhh if that is the case then what you are doing seems to be the optimal. Just have module lvl code ran the testing in fact I don't even put those into the if __name__, the reason is that this is just temp testing that will later become real unit testing, and will never hit a production app. it gives you the most flexibility. > Anyway, thanks for your answer ;). > welcome > > > -- > Karlo Lozovina -- Mosor > -- > http://mail.python.org/mailman/listinfo/python-list > From Lie.1296 at gmail.com Tue Mar 11 12:47:26 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 09:47:26 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> On Mar 10, 12:08?pm, Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? > > Thanks in advance, > Nathan P. Factorial algorithm is a very simple and common algorithm, and it's one of the most basic of all recursive algorithm def fact(x): return x * fact(x - 1) That recursive function is very close to the basic definition of factorials, that is x! = x * (x - 1)! If however, you expected x to be a real (float) value, you'd better consider the gamma function as Mark Dickinson pointed out. Wikipedia is a good start to create your gamma function: http://en.wikipedia.org/wiki/Factorial http://en.wikipedia.org/wiki/Gamma_function From castironpi at gmail.com Sun Mar 2 13:16:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 10:16:46 -0800 (PST) Subject: Problem with the strip string method References: Message-ID: On Mar 2, 11:45?am, Steve Holden wrote: > I suspect what you need is the .replace() method. The information's there-- the word 'contiguous' might clear it up a bit. > > Return a copy of the string with the > > leading and trailing characters removed. > > The chars argument is a string > > specifying the set of characters to be > > removed. If omitted or None, the chars > > argument defaults to removing > > whitespace. The chars argument is not a > > prefix or suffix; rather, all > > combinations of its values are stripped: Return the string's substring from the first character not a member of 'chars' to the last such. Remove contiguous leading and trailing members of 'chars'. If omitted or None, 'chars' defaults over to the set of whitespace set( "\n\r\t " ). (XXX TODO: ask Steve Reg Ex Guru this). From http Sun Mar 2 02:23:21 2008 From: http (Paul Rubin) Date: 01 Mar 2008 23:23:21 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> Message-ID: <7xskz9wpw6.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > def mean(data): return sum(data)/len(data) > > That does the right thing for data, no matter of what it consists of: > floats, ints, Decimals, rationals, complex numbers, or a mix of all of > the above. One of those types is not like the others: for all of them except int, the quotient operation actually is the inverse of multiplication. So I'm unpersuaded that the "mean" operation above does the "right thing" for ints. If the integers being averaged were prices in dollars, maybe the result type should even be decimal. For this reason I think // is a good thing and I've gotten accustomed to using it for integer division. I can live with int/int=float but find it sloppy and would be happier if int/int always threw an error (convert explicitly if you want a particular type result). From cabalamat at googlemail.com Tue Mar 25 10:23:57 2008 From: cabalamat at googlemail.com (Phil) Date: Tue, 25 Mar 2008 14:23:57 +0000 (UTC) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> Message-ID: On 2008-03-18, sturlamolden wrote: > First, I recommend that you write readable code! Don't use Python as > if you're entering the obfuscated C contest. > > Two particularly important points: > > * Comments are always helpful to the reader. It would be nice if this was the case! I once saw a preogram where a line of code like this: foo++; Would be annotated with a comment like this: /****************************************************/ /* */ /* Increment foo */ /* */ /****************************************************/ This comment was worse than useless, because it (and others like it) took up space that distracted from the information-containing parts of the code. From ckimyt at gmail.com Wed Mar 5 06:32:55 2008 From: ckimyt at gmail.com (Mike) Date: Wed, 5 Mar 2008 03:32:55 -0800 (PST) Subject: Using re module better Message-ID: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> I seem to fall into this trap (maybe my Perl background) where I want to simultaneously test a regular expression and then extract its match groups in the same action. For instance: if (match = re.search('(\w+)\s*(\w+)', foo)): field1 = match.group(1) field2 = match.group(2) ... (compare to Perl:) if($foo =~ /(\w+)\s*(\w+)/) { $field1 = $1; $field2 = $2; ... } Problem is, my python is invalid above. What's the pythonic way to do this? Thanks in advance O Python Charmers Mike From Afro.Systems at gmail.com Tue Mar 25 08:34:17 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 05:34:17 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> Message-ID: <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> > Rather than use Foo.bar(), use this syntax to call methods of the > super class: > > super(ParentClass, self).method() Hi Jeff, here is the nw version which cause an error class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = super(Foo, self).getid() b = self.id return '%d.%d' % (a,b) FooSon().getid() Traceback (most recent call last): File "a.py", line 19, in FooSon().getid() File "a.py", line 14, in getid a = super(Foo, self).getid() AttributeError: 'super' object has no attribute 'getid' From spamspam at spam.eggs Mon Mar 17 04:48:33 2008 From: spamspam at spam.eggs (Ben C) Date: Mon, 17 Mar 2008 03:48:33 -0500 Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> Message-ID: On 2008-03-17, WaterWalk wrote: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. It does, you just right-click and go "set breakpoint". But yes IDLE is a bit basic. From george.sakkis at gmail.com Tue Mar 18 21:19:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 18 Mar 2008 18:19:16 -0700 (PDT) Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> <5b4e2347-9c02-46bc-a1b7-bd0c9b25a0f8@b1g2000hsg.googlegroups.com> <81a0e2d1-21c5-4591-8744-5b90041480b4@13g2000hsb.googlegroups.com> Message-ID: <1c9f7516-bb8d-4023-8653-6b1831a36769@e6g2000prf.googlegroups.com> On Mar 18, 5:34 pm, Duncan Booth wrote: > castiro... at gmail.com wrote: > >> > > On Mar 17, 1:31 pm, Duncan Booth > >> > > wrote: > > >> > >> A common explanation for this is that lists are for homogenous > >> > >> collections, tuples are for when you have heterogenous > >> > >> collections i.e. related but different things. > > >> > > I interpret this as meaning that in a data table, I should have a > >> > > list of records but each record should be a tuple of fields, > >> > > since the fields for a table usually have different forms whereas > >> > > the records usually all have the same record layout. > > >> >>> b in b > >> False > > > That's actually interesting. > > Just for the avoidance of doubt, I didn't write the 'b in b' line: > castironpi is replying to himself without attribution. > > P.S. I still don't see the relevance of any of castironpi's followup to my > post, but since none it made any sense to me I guess it doesn't matter. Plus, it does work fine over here: Python 2.5.1 (r251:54863, May 8 2007, 14:46:30) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = [] >>> a.append(a) >>> a [[...]] >>> a in a True George From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 21:31:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 02:31:58 -0000 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> Message-ID: <13sulsu4nbr2199@corp.supernews.com> On Wed, 05 Mar 2008 21:05:31 -0500, Terry Reedy wrote: > If I understand your question, classes are not singletons: >>>> ll=[] >>>> for i in range(2): > import string > ll[i]=string Where's the IndexError? :-) >>>> ll[0] is ll[1] > True But yes, modules are singletons in that way, at least if you go through the import mechanism. >>>> for i in range(2): > class C: pass > ll[i] = C > > >>>> ll[0] is ll[1] > False Ah, but each time around the loop you create a *new class* that just happens to be called C. An alternative way to see similar behaviour is: def foo(x=None): class C(object): X = x return C Naturally foo() is foo() gives False -- although both classes are called C, they are different classes that just happen to have the same state. I accept my question about classes being singletons is not well-formed, not even in my own mind. I guess one way of asking is, for any two class objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? -- Steven From ptmcg at austin.rr.com Mon Mar 24 08:50:12 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 05:50:12 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> <731a7080-f7a5-4d7a-823a-f366550160da@d45g2000hsc.googlegroups.com> <17e6ca72-0b61-45a4-9604-dda4029ba5eb@e23g2000prf.googlegroups.com> Message-ID: On Mar 23, 4:04?pm, rh0dium wrote: > > I needed to tweak it a bit to ignore the comments.. ?Namely this fixed > it up.. > > ? ? mainDict = dictOf( > ? ? ? ? ? ? Group(Word(alphas)+Optional(quotedString)), > ? ? ? ? ? ? Suppress("{") + attrDict + Suppress("}") > ? ? ? ? ? ? ) | cStyleComment.suppress() > > Thanks again. ?Now I just need to figure out how to use your dicts to > do some work..- Hide quoted text - > > - Show quoted text - I'm glad this is coming around to some reasonable degree of completion for you. One last thought - your handling of comments is a bit crude, and will not handle comments that crop up in the middle of dict entries, as in: color = /* using non-standard color during testing */ "plum" The more comprehensive way to handle comments is to call ignore. Using ignore will propagate the comment handling to all embedded expressions, so you only need to call ignore once on the top-most pyparsing expression, as in: mainDict.ignore(cStyleComment) Also, ignore does token suppression automatically. -- Paul From dstromberglists at gmail.com Wed Mar 26 15:52:42 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Wed, 26 Mar 2008 19:52:42 GMT Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: On Wed, 26 Mar 2008 19:45:34 +0100, Heiko Wundram wrote: > Am Mittwoch, 26. M?rz 2008 19:04:44 schrieb David Anderson: >> HOw can we use express pointers as in C or python? > > There's no such thing as a pointer in Python, so you can't "express" > them either. Was this what you were trying to ask? Strictly speaking, many objects are passed by reference, which is kind of pointer-like, even though it doesn't expose the true messiness of a true pointer. Also strictly speaking, if you use SWIG, it can wrap up pointers from other languages as a python object to be passed around within a python program. From jeff at schwabcenter.com Fri Mar 14 19:33:36 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 14 Mar 2008 16:33:36 -0700 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: Roel Schroeven wrote: > castironpi at gmail.com schreef: >> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>> Subject: RIP: Joseph Weizenbaum >>>> Creator of Eliza: >>>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>>> -- >>> How do you feel about creator of Eliza? >> >> What is Eliza? > > Does that question interest you? Well played, sir. -- Earlier you said what is Eliza. Do you still feel that way? From lists at cheimes.de Tue Mar 25 18:19:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 25 Mar 2008 23:19:09 +0100 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: Dark Wind schrieb: > Hi, > > In most of the languages ^ is used for 'to the power of'. In python we have > ** for that. But what does ^ do? > I could not get it just by using it ... some examples are: > 1^1 returns 0 > 2^2 returns 0 > 1^4 returns 5 > 4^1 returns 5 > 3^5 returns 6 > 5^3 returns 6 ...... ^ is exclusive or (xor) # 1 ^ 1 = 0 >>> 1 ^ 1 0 # 01 ^ 10 = 11 >>> 1 ^ 2 3 # 01 ^ 11 = 10 >>> 1 ^ 3 2 # 001 ^ 100 = 101 >>> 1 ^ 4 5 Christian From dundeemt at gmail.com Mon Mar 17 22:00:49 2008 From: dundeemt at gmail.com (dundeemt) Date: Mon, 17 Mar 2008 19:00:49 -0700 (PDT) Subject: PyCon video editing Message-ID: Anyone know who is in charge of this? I'd like to help out if I could. -jeff hinrichs From 2huggie at gmail.com Thu Mar 20 01:38:37 2008 From: 2huggie at gmail.com (Timothy Wu) Date: Thu, 20 Mar 2008 13:38:37 +0800 Subject: xml sax In-Reply-To: <47E15155.4050008@jouy.inra.fr> References: <47E15155.4050008@jouy.inra.fr> Message-ID: Oh right, why didn't I think of that. =) Many thanks. Timothy On Thu, Mar 20, 2008 at 1:45 AM, Robert Bossy wrote: > Timothy Wu wrote: > > Hi, > > > > I am using xml.sax.handler.ContentHandler to parse some simple xml. > > > > I want to detect be able to parse the content of this tag embedded in > > the XML. > > 174 > > > > > > Is the proper way of doing so involving finding the "Id" tag > > from startElement(), setting flag when seeing one, and in characters(), > > when seeing that flag set, save the content? > > > > What if multiple tags of the same name are nested at different levels > > > > and I want to differentiate them? I would be setting a flag for each > level. > > I can imagine things get pretty messy when flags are all around. > > > Hi, > > You could have a list of all opened elements from the root to the > innermost. To keep such a list, you append the name of the element to > this stack at the end of startElement() and pop it off at the end of > endElement(). > > In this way you have acces to the path of the current parser position. > In order to differentiate between character data in Id and in Id/Id, you > just have to iterate at the last elements of the list. > > Cheers, > RB > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Wed Mar 19 17:16:43 2008 From: python at rcn.com (Raymond Hettinger) Date: Wed, 19 Mar 2008 14:16:43 -0700 (PDT) Subject: Fate of the repr module in Py3.0 Message-ID: Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , and saw that the repr module was slated for vaporization. I've only used the module a few times ever. I'm curious if the community wants it kept around or whether it is considered clutter. The PEP is going to be finalized soon, so if you have issues with it, they should be sent to the PEP author or brought up on the list, http://mail.python.org/mailman/listinfo/stdlib-sig . Raymond From fetchinson at googlemail.com Tue Mar 11 03:05:17 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 11 Mar 2008 00:05:17 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > The second thing I'll try (after trying > your suggestion) is based on this paper which I found in the meantime: > http://salesin.cs.washington.edu/abstracts.html#MultiresQuery > In case anyone is interested, it describes a multiresolution querying > algorithm and best of all, it has pseudo code for the various steps. I > don't know yet how difficult the implementation will be but so far > this looks the most promising. Actually, the exact same algorithm has already been implemented in ....... drum roll ............ python! http://members.tripod.com/~edcjones/pycode.html From http Sat Mar 29 05:39:11 2008 From: http (Paul Rubin) Date: 29 Mar 2008 02:39:11 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> Message-ID: <7xve35kgxs.fsf@ruckus.brouhaha.com> Paul Rubin writes: > aio is also used for sockets, while twisted and asyncore use select or > something similar. That is asynchronous but in a different sense of > the word. See also: http://www.kegel.com/c10k.html Hmm that actually says that in Linux 2.6.0#-test2 sockets weren't supported. I can't tell the situation from the man page on the system I'm using right now. I may have misremembered but I thought I talked with someone a while back who was using aio in a high concurrency VOIP system and that it was beating other approaches. I don't know what kernels were involved etc. Anyway using this stuff in Python would be overkill. From Robert.Bossy at jouy.inra.fr Thu Mar 13 12:09:43 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 13 Mar 2008 17:09:43 +0100 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> <47D94D61.9010708@jouy.inra.fr> <00fd01c88523$cbe262e0$63a728a0$@rawlins@thinkbluemedia.co.uk> Message-ID: <47D951C7.3090900@jouy.inra.fr> Robert Rawlins wrote: > Hi Guys, > > Well thanks for the response, I followed your advice and chopped out all the > crap from my class, right down to the bare __init__ and the setter method, > however, the problem continued to persist. > > However, Robert mentioned something about unindented lines which got me > thinking so I deleted my tab indents on that method and replaces them with > standard space-bar indents and it appears to have cured the problem. > Aha! Killed the bug at the first guess! You owe me a beer, mate. RB From duncan.booth at invalid.invalid Mon Mar 17 12:03:18 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 16:03:18 GMT Subject: lists v. tuples References: <0090b8fb-b101-444f-a47b-4e381089635c@h11g2000prf.googlegroups.com> Message-ID: Ninereeds wrote: > On Mar 17, 1:31 pm, Duncan Booth wrote: > >> A common explanation for this is that lists are for homogenous >> collections, tuples are for when you have heterogenous collections i.e. >> related but different things. > > I interpret this as meaning that in a data table, I should have a list > of records but each record should be a tuple of fields, since the > fields for a table usually have different forms whereas the records > usually all have the same record layout. That is indeed what Python's Database API usually does (although it doesn't mandate it): .fetchmany([size=cursor.arraysize]) Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. From duncan.booth at invalid.invalid Sun Mar 2 06:10:16 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Mar 2008 11:10:16 GMT Subject: Question about lambda and variable bindings References: <47CA160C.3000305@gmail.com> Message-ID: Michael Torrie wrote: > poof65 wrote: >> An idea, i don't know if it will work in your case. >> >> for x in xrange(10): >> funcs.append(lambda p,z=x: testfunc(z+2,p)) > > Good idea. I will try it. I also figured out a way to architecture my > program differently to avoid this problem. But this idiom might be > handy in certain situations. Suppose you need to provide a callback > function with a fixed signature to some library routine. But you want > to add extra contextual data to your callback. This just might be the > ticket. There are three obvious ways to solve your problem: 1) Using a default argument as above is the original and used to be the only way to do it. 2) Using a factory function to generate the function: def gencaller(fn, x): def caller(p): return fn(x+2, p) return caller for x in xrange(10): funcs.append(gencaller(testfunc, x)) 3) Using functools.partial: from functools import partial for x in xrange(10): funcs.append(partial(testfunc, x+2)) or even: funcs = [partial(testfunc, x+2) for x in range(10)] A lot depends on what your real code actually wants to pass as the parameters. If they are some complicated expression you cannot evaluate until it is called then use a factory function, if it is something simple as in your example then partial is easily the cleanest. From castironpi at gmail.com Thu Mar 13 19:45:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 13 Mar 2008 16:45:31 -0700 (PDT) Subject: getattr(foo, 'foobar') not the same as foo.foobar? References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> Message-ID: > > Basically, the above code is saying that foo.foobar is not the same as > > getattr(foo, 'foobar'). > > > What gives? ?This breaks my understanding of id(), the is operator, and > > getattr(). > > 4. ?Both points above follow from the fact that foo.bar is really a > function call that returns a (potentially) new object: in fact what > really happens is something like > > ? ? Foo.__dict__['bar'].__get__(foo, Foo). > > So every time foo.bar is executed an object is (or may be) created, > with a new id. When is it? Why is the 'owner' argument there? Do you ever use '__set__'? From lists at cheimes.de Sat Mar 22 17:48:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Mar 2008 22:48:31 +0100 Subject: Problem with complex numbers In-Reply-To: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> References: <5330bd900803221437k6262ad3kd0e655ffc6305b7b@mail.gmail.com> Message-ID: Matthias G?tz schrieb: > So if somebody can help me, it would be nice. Thanks. The complex type is implemented in C. It's totally unrelated to Complex.py. Christian From mensanator at aol.com Tue Mar 4 01:12:45 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 22:12:45 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: <01a8abbc-42c5-478d-a282-b3d511ab2620@q78g2000hsh.googlegroups.com> On Mar 3, 11:58?pm, Erik Max Francis wrote: > Mensanator wrote: > > While we're on the subject of English, the word "worthless" > > means "has no value". So, a program that doesn't work would > > generally be "worthless". One that not only doesn't work but > > creates side effects that cause other programs to not work > > (which don't have bugs) would be "worse than worthless". > > All programs have bugs, which means that in some circumstances, they > won't work. ? And in such circumstances, would be worthless. > Therefore, by your reasoning, all programs are worse than > useless. That doesn't follow from my reasoning. Suppose you downloaded a new calculator program that couldn't add properly. That would be useless to you, right? But suppose the program contained a virus that erased your hard drive. That would be "worse than useless", wouldn't it? > > > I'm not hard to please at all. > > No, of course not, since logically you must think all software is useless. Somehow, I expected better logic from people who call themselves programmers. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > ? ?Life is a zoo in a jungle. > ? ? -- Peter de Vries From troworld at gmail.com Mon Mar 3 18:09:31 2008 From: troworld at gmail.com (Tro) Date: Mon, 3 Mar 2008 18:09:31 -0500 Subject: Altering imported modules In-Reply-To: <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> References: <200803011856.27611.troworld@gmail.com> <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> Message-ID: <200803031809.32005.troworld@gmail.com> On Sunday 02 March 2008, Paul McGuire wrote: > On Mar 2, 3:48?pm, Tro wrote: > > On Sunday 02 March 2008, Terry Reedy wrote: > > > "Tro" wrote in message > > >news:200803011856.27611.troworld at gmail.com... > > > > > > | Hi, list. > > > | > > > | I've got a simple asyncore-based server. However, I've modified the > > > > > > asyncore > > > > > > | module to allow me to watch functions as well as sockets. The > > > | modified asyncore module is in a specific location in my project and > > > | is imported > > > > > > as > > > > > > | usual from my classes. > > > | > > > | Now I'd like to use the tlslite library, which includes an asyncore > > > | mixin class. However, tlslite imports "asyncore", which doesn't > > > | include my own modifications. > > > | > > > | I'd like to know if it's possible to make tlslite load *my* asyncore > > > > > > module > > > > > > | without changing any of the tlslite code. > > > > > > If your module is also 'asyncore' and comes earlier in the search path, > > > I would expect the import to get yours. > > > > It's not. It has a package prefix like my.package.asyncore. I think I can > > either move my version of asyncore up a couple of levels or add the > > my.package directory to sys.path. > > > > My version of asyncore imports several functions from the built-in > > asyncore. Now that my version of it is imported as asyncore, how would it > > import the built-in version from python2.5/site-packages? > > > > Thanks, > > Tro > > > > > > What happens if you do "import my.package.asyncore as asyncore"? > > If that doesn't work (trying the simplest hack first), I know that > there are various hooks in the import mechanism that should help. In the classes that use my version of asyncore currently, that is how I do it. I import my version as "import my.package.asyncore as asyncore". In my asyncore module I do "import asyncore", because I override a few functions from the asyncore module included with python. However, if I were to add "my.package" to sys.path, then I wouldn't be able to "import asyncore" from my own asyncore module. I'd have to do some trickery with sys.path to take the "my.package" component out, import standard asyncore, readd the "my.package" component, so that other modules can "import asyncore" and get my version. Is there a way to import the standard python asyncore module in this scenario? Thanks, Tro From kevinpruiz at gmail.com Mon Mar 17 17:14:27 2008 From: kevinpruiz at gmail.com (browntown) Date: Mon, 17 Mar 2008 14:14:27 -0700 (PDT) Subject: php/python webkit2png issue Message-ID: <606d2db4-4f0b-4309-8ca0-7d5678830a04@e39g2000hsf.googlegroups.com> Hi...i'm relatively new to python...i'm trying to use webkit2png to take some screenshots. Everything works fine when I run the script from the command line...things do not work when i try to execute them from php using exec. My php code looks something like: exec("python /usr/local/bin/webkit2png2.py -m http://www.google.com -D ~/Desktop/snap"); which produces the following output: "Cannot find pyobjc library files. Are you sure it is installed?" That output is generated from the webkit2png script after it fails to import foundation, webkit, appkit and pyobjc. How can I enable the python script to find the necessary files/ libraries when being executed from php? I'm using paul hammond's webkit2png on OS X, running apache 1.3 with php 4.47 and python 2.5.2. Thanks. From deets at nospam.web.de Sat Mar 29 09:54:36 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Mar 2008 14:54:36 +0100 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <7xzlshkhlc.fsf@ruckus.brouhaha.com> References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <7xzlshkhlc.fsf@ruckus.brouhaha.com> Message-ID: <65701aF2erbbsU1@mid.uni-berlin.de> Paul Rubin schrieb: > Hrvoje Niksic writes: >> Note that I said "*file* input/output". Twisted and asyncore are >> about asynchronous socket programming that polls over nonblocking file >> descriptors such as found in socket programming, not about wrapping >> aio(3) and the equivalent Windows APIs. > > aio is also used for sockets, while twisted and asyncore use select or > something similar. That is asynchronous but in a different sense of > the word. See also: http://www.kegel.com/c10k.html In which sense is that different? AFAIK select lets you avoid polling and provides notifications (possibly with timeouts) for IO-events. So where exactly is the difference? I read TFA, and it does mention that select/poll have potential for optimization, but not something that disqualified them (or rather select) as being not async. Diez From Graham.Dumpleton at gmail.com Tue Mar 25 19:30:17 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Mar 2008 16:30:17 -0700 (PDT) Subject: Beta testers needed for a high performance Python application server References: Message-ID: On Mar 26, 7:31 am, Minor Gordon wrote: > Hello all, > > I'm looking for beta testers for a high performance, event-driven Python > application server I've developed. > > About the server: the front end and other speed-critical parts of the > server are written in portable, multithreaded C++. The back end is an > embedded CPython interpreter. The server is much faster than anything in > pure Python, and it can compete with C servers (including e.g. lighttpd > for file workloads) or outdo them (e.g. anything behind Apache) until > CPython consumes a single processor. On the Python side it supports WSGI > (the server can handle the static and dynamic requests of MoinMoin with > a handful of lines), the DB API with blocking calls offloaded to a > connection in a separate thread (MySQL, SQLite supported), Google's > ctemplate, gzipping responses, file caching, reading and writing to URIs > as a client, AJAX integration, debugging as a Python extension, and a > lot of other features. The core Python API is event-driven, using > continuations like Twisted but much cleaner (continuations are any > callables, there are no special objects anywhere). The Python back end > also supports Stackless Python so all of the continuation machinery can > be hidden behind tasklet switching. > > Background: I'm in this to help write a "story" for Python and web > applications. Everyone likes to go on about Ruby on Rails, and as far as > I can tell there's nothing that approaches Rails in Python. I want to > code quickly in Python like I can with Rails, but without sacrificing > single node performance on many cores. > > Beta testers: should be intermediate to advanced Python programmers with > demanding applications, particularly web applications with databases and > AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory > libraries beyond python-dev. > > Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. Why not just put it on the net somewhere and tell us where it is? People aren't generally going to want to help or even look at it if you treat it like a proprietary application. So, put the documentation and code up somewhere for all to see. BTW, multiprocess web servers such as Apache can quite happily make use of multiple cores. Even within a single Apache multithread process it can still use multiple cores quite happily because all the underlying network code and static file handling code is in C and not subject to the GIL. So, as much as people like to bash up on the GIL, within Apache it is not necessarily as big a deal as people make out. Also, an event driven model, or even a large dependence on multithreading, can actually be worse for Python web applications where using it means one can handle a much larger number of concurrent requests. This is because you greatly increase the risk of code having large requirements for transient memory being hit at the same time. The result can be large unpredictable blowouts in memory requirements for the process, with that memory then being held by the process and not necessarily able to be released back to operating system. Thus, for large Python web applications, use of a multiprocess web server, where each worker process is single threaded, is in various way still best as it provides the most predictable memory profile. Finally, the speed of the underlying web server (except for CGI) generally has minimal bearing on the performance of a large Python web application. This is because that isn't where the bottlenecks are. The real bottlenecks are generally in the application code itself and in any access to a back end database. Thus, pursuing absolute speed is a bit of a fools errand when you consider that any performance gain you may have over a competing solution may only end up resulting in somewhat less than 1% difference when one looks at overall request time. Graham From george.sakkis at gmail.com Mon Mar 3 18:29:18 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 3 Mar 2008 15:29:18 -0800 (PST) Subject: News from Jython world References: Message-ID: <0a9bfffc-7f13-4174-8972-27143f8b5c66@h11g2000prf.googlegroups.com> On Mar 3, 1:40 pm, S?bastien Boisg?rault wrote: > Frank Wierzbicki and Ted Leung have been hired by Sun. Frank is a > key Jython developer and is specifically hired to work full time on > Jython, a version of the Python interpreter that runs on top of the > JVM and provides full access to Java libraries. After a period where > the development had slowed, Jython was recently getting seriously > back on track. Now it's getting even better ! > > Don't wait too much ... Jython is very useful RIGHT NOW if you live > in the Java Universe. > > More details at: > -http://www.infoworld.com/article/08/03/03/hirings-python_1.html > -http://fwierzbicki.blogspot.com/2008/02/jythons-future-looking-sunny.... > > Cheers, > > SB Great news! Having to go back to the Java world might not be such a turn-off in the near future ;-) George From nanjundi at gmail.com Tue Mar 4 13:41:53 2008 From: nanjundi at gmail.com (Nanjundi) Date: Tue, 4 Mar 2008 10:41:53 -0800 (PST) Subject: unicode box drawing References: <6a2fcafe-18c0-48b3-bb9c-4ab545732cfb@s13g2000prd.googlegroups.com> Message-ID: <3319005c-98b9-44a0-96dc-72db45f2ae27@z17g2000hsg.googlegroups.com> On Mar 4, 12:51 pm, jefm wrote: > How can I print the unicode box drawing characters in python: > > print u'\u2500' > print u'\u2501' > print u'\u2502' > print u'\u2503' > print u'\u2504' > > Traceback (most recent call last): > File "\test.py", line 3, in ? > print u'\u2500' > File "C:\Python24\lib\encodings\cp1252.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u2500' > in position 0: character maps to Just FYI, not an answer. It works like a charm on linux (ubuntu, fc3, python 2.4.1 & 2.5.2) Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print u'\u2500' ? >>> print u'\u2501' ? >>> print u'\u2502' ? >>> print u'\u2503' ? >>> >>> print u'\u2504' ? on windows using python 2.4. ??? -N From zubeido at yahoo.com.br Sat Mar 29 13:33:41 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sat, 29 Mar 2008 10:33:41 -0700 (PDT) Subject: Problem with sqlite Message-ID: class db: def __init__(self): #constructor conn = sqlite3.connect('./db.db') conn.isolation_level = None self.cursor = conn.cursor() try: self.cursor.execute("CREATE TABLE database (album,filepath)" ) except: pass def add_entry( self, eone , etwo ): #Add entry to database self.cursor.execute( "INSERT INTO database (album,filepath) VALUES (?,?)", ( eone , etwo ) ) return 1 #TODO: exception handler def get_mediadb( self, print_db = False ): self.cursor.execute( 'SELECT * FROM database' ) if (print_db == True): print self.cursor.fetchall() def get_value( self, column ): self.cursor.execute( "SELECT %s FROM database" % column ) for n in self.cursor: print n def destructor(self): self.cursor.close() def walking_and_filling(db): pass if __name__ == "__main__": db = db() #walking_and_filling( db ) for root, dirs, files in os.walk( '''foo_path/''', topdown=False ): for name in files: joined = os.path.join(root, name) if (name[-3:] == 'mp3' and os.path.isfile( joined ) ): try: audio = MP3 (joined, ID3=EasyID3 ) print (audio['album']) db.add_entry( joined, audio['album'] ) except: pass db.get_mediadb( print_db=True ) When i execute this the database doesn't get filled with anything and the program stays running in memory for ever. The print statement is just a Unicode string that would get to the database if i stated it in the add_entry function as a constant string. It's a really weird problem that i dont seem to understand why it's working out this way. Thanks in advance From david at boddie.org.uk Mon Mar 17 20:49:23 2008 From: david at boddie.org.uk (David Boddie) Date: Tue, 18 Mar 2008 01:49:23 +0100 Subject: EuroPython 2008 - Any interest in tutorials? Message-ID: <200803180149.24055.david@boddie.org.uk> As many of you may be aware, preparations for EuroPython 2008 - the European Python community conference - are under way. For the second year running, the event will be held in Vilnius, Lithuania, with the main programme taking place on Monday 7th, Tuesday 8th and Wednesday 9th July. Those of us involved with the conference are looking for ways in which we can make the event more interesting for beginners and experts alike. One way in which we could do this, particularly for people who are learning Python, is to allocate time for tutorials. This approach appears to be popular at conferences like PyCon and PyCon UK, but isn't something we normally do at EuroPython, though there are often talks are aimed at beginners in the schedule. What we'd like to know is: * Is this something that you would like to see? * Would you be interested in giving a tutorial? * Which subject would you be interested in hearing/talking about? If you answered "yes" to either of the first two questions, please feel free to add suggestions for tutorials, either as a participant or as a speaker, to this page on the EuroPython Wiki: http://www.europython.org/community/Talk_Suggestions If you're interested in participating in EuroPython this year in any way, please come and join us on the europython mailing list http://mail.python.org/mailman/listinfo/europython or visit this page on the EuroPython Web site: http://www.europython.org/community/Participants Hope to see some of you there! David Boddie - EuroPython 2008 participant :-) From arkanes at gmail.com Fri Mar 7 16:19:55 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 7 Mar 2008 15:19:55 -0600 Subject: Want - but cannot get - a nested class to inherit from outer class In-Reply-To: References: Message-ID: <4866bea60803071319o38686ec7te0d5adf5f4cd6ee7@mail.gmail.com> On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > I want - but cannot get - a nested class to inherit from an outer > class. (I searched the newsgroup and the web for this, couldn't find > anything - if I missed an answer to this please let me know!) > > I would like to build a class for a data structure such that nodes of > the data structure - of interest only to the data structure > implementation itself and not to the consumer - are instances of one > of two class types. I thought to encapsulate the nodes' classes like > this: > > class Tree(object): > ...class _MT(Tree): > ......def isEmpty(self): return True > ......def insert(self, X): return Tree._Node(X) > ...class _Node(Tree): > ......def isEmpty(self): return False > ......def insert(self, X): return _Node(X, self, Tree._MT()) > ...def merge(self, T): > ......def __init__(): return _MT() > ...... > > In other words, some methods would be implemented on instances' > classes (like isEmpty and insert) and some on the outer class (like > merge). Users of the data structure never need to know about the > nodes, much less the nodes' classes, so I wanted to encapsulate them > > However I can't do this, because, of course, the name Tree isn't > available at the time that the classes _MT and _Node are defined, so > _MT and _Node can't inherit from Tree. > Not only is the name not defined, the class doesn't even exist yet. > What is the Pythonic thing I should be doing instead? > Don't nest them. The single underscore is all you need to keep any from using them (don't forget that even if your method worked, they'd be perfectly visible as attributes of the Tree class, or as the types of returned values). Worrying too much about visibility is a waste of time in Python. > (Easy answer: Put this code in a module, exposing only a factory > function. I could do that, but wanted to know if I could encapsulate > it as described so I could actually put several similar data > structures into one module.) > There's no reason to use a factory function. If you do put them in a module, you can use __all__ to document your exports. As with all visibility issues in Python, this is advisory only - the only code it affects is the symbols that are exported by "from module import *". From steve at holdenweb.com Tue Mar 4 09:50:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 09:50:16 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD61A8.4000104@holdenweb.com> Peter Otten wrote: > Steve Holden wrote: > >> What I will repeat, however, is that while there is a *slight* >> difference is semantics between >> >> s = "some string" >> s1 = s >> >> and >> >> s = "some string" >> s1 = copy.copy(s) >> >> that difference is only to ensure that s and s1 point to different >> copies of the same string in the latter case, whereas in the former case >> s and s1 point to the same string. > > No, both "point" to the same string: > >>>> import copy >>>> s = "some string" >>>> s1 = s >>>> s1 is s > True >>>> s2 = copy.copy(s) >>>> s2 is s > True > > copy.copy() is just an expensive no-op here. > I suppose wiht strings being immutable there is no need for copy.copy() to actually return anything other than its argument for a string. Thanks for pointing that out. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From noname9968 at gmail.com Thu Mar 27 01:51:59 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 08:51:59 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> Message-ID: <47EB35FF.4020407@gmail.com> Guilherme Polo wrote: > 2008/3/26, Alex9968 : > >> Hi all, >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> using visual GUI designers), so my question is which other GUI toolkits >> have similar functionality. >> > > The geometry manager isn't related to using GUI designers tools at > all. And each toolkit has it's own way to do the things, wxPython uses > sizers, PyGtk uses containers. > Well, the geometry manager isn't *directly* related to using GUI designers, but as Pack arranges widgets automatically, using GUI designers isn't required, while with geometry managers that don't, GUI designers are necessary (if you start placing widgets programmatically, you'll end up reinventing something like Tkinter's Pack or Grid geometry manager). I hope I can be understood clearly this time ;-) >> Secondly, I like the detailed widget borders configuration possible in >> Tkinter, which can be used to tweak GUI look, and wonder if other >> toolkits support it. With Tkinter's case, I like the resulting (tweaked) >> look in Windows, but I'm afraid it can be quite different (and ugly) on >> other platforms. >> > > You sure can, but differently. > I suppose any toolkit allows setting parameters like "no border", "flat border" and "3d border", but which ones can set ANY type of border to ANY widget like Tkinter does? For example set GROOVE border to buttons and text widgets (instead of traditional wide raised/lowered borders), which is cool (in my opinion). > >> (The reason I ever consider moving from Tkinter is some inconveniences, >> involving for example window scrolling, plus its smaller amount of >> widgets compared to some other toolkits, plus its (rumored) ugly look on >> certain environments. I will not necessary change the toolkit, but I >> have to consider it) >> >> > > I'm planning to "solve" this, I'm suggesting inclusion of Ttk into > Tkinter for upcoming GSoC. For now you could try using Tile extension, > and update to Tk 8.5. If you don't want to use extensions, then you > will have to wait or change the toolkit for now. > Thanks. I haven't heard of Tile before, now I will keep this in mind. You forgot to mention WHAT you're planning to solve ;-) , so I have to add that Tile is modernization of Tk widgets (so it fixes ugly look). > >> Could anyone with experience in different toolkits help, please >> >> Thanks >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > From dundeemt at gmail.com Mon Mar 17 20:55:28 2008 From: dundeemt at gmail.com (dundeemt) Date: Mon, 17 Mar 2008 17:55:28 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <6715d78c-17df-4dfa-8181-d3606a8508c5@m44g2000hsc.googlegroups.com> > This is my third PyCon, and I've found a reasonably-sized cadre of > people who come for the hallway conversations plus a Bof or two, > having given up on hearing anything new, useful, or inspiring in the > talks. There are several people I know who would like to see a more > advanced academic track. Yes, Yes. This was my third pycon and before, I had always left feeling as though my brain had been stretched. (A good thing) This years balance of talks and my choices didn't leave me with the same feeling. I would have like to seen slightly longer talks, especially the ones I liked ;) -Jeff Hinrichs From aahz at pythoncraft.com Thu Mar 6 16:25:44 2008 From: aahz at pythoncraft.com (Aahz) Date: 6 Mar 2008 13:25:44 -0800 Subject: OT: Failed saving throw References: <13suutrmlm5208a@corp.supernews.com> Message-ID: In article <13suutrmlm5208a at corp.supernews.com>, Dennis Lee Bieber wrote: >On 5 Mar 2008 07:36:37 -0800, aahz at pythoncraft.com (Aahz) declaimed the >following in comp.lang.python: >> >> For anyone who hasn't heard, E. Gary Gygax died yesterday. Some people >> think we should build a tomb in his honor. ;-) > > Just a tomb? Commission Disney to build a whole dungeon with the >tomb somewhere inside... Of course, they'd want to charge admission You're apparently missing the reference to Tomb of Horrors. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From george.sakkis at gmail.com Mon Mar 17 05:58:59 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 17 Mar 2008 02:58:59 -0700 (PDT) Subject: String To List References: <7xy78hep5g.fsf@ruckus.brouhaha.com> Message-ID: On Mar 17, 3:22 am, Paul Rubin wrote: > Girish writes: > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > this?? > > Thanks for the help... > > Be careful about using eval, if the string came from a potentially > hostile source. Maybe what you really want is JSON, which has > python-like syntax but a bunch of safe parsers. Or take a look at a restricted safe eval variant (e.g. http://groups.google.com/group/comp.lang.python/browse_frm/thread/262d479569b1712e) George From floris.bruynooghe at gmail.com Tue Mar 4 11:10:45 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Tue, 4 Mar 2008 08:10:45 -0800 (PST) Subject: Altering imported modules References: Message-ID: On Mar 1, 11:56 pm, Tro wrote: > I'd like to know if it's possible to make tlslite load *my* asyncore module > without changing any of the tlslite code. the pkgutil module might be helpful, not sure though as I've never used it myself. http://blog.doughellmann.com/2008/02/pymotw-pkgutil.html is a fairly detailed look at what pkgutil can do. Regards Floris From tjreedy at udel.edu Tue Mar 11 19:34:01 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Mar 2008 19:34:01 -0400 Subject: min/max: "stable" invariant? References: Message-ID: "Giovanni Bajo" wrote in message news:jiEBj.16245$q53.9583 at tornado.fastwebnet.it... | Hello, | | assuming that a sequence contains multiple elements with minimum/maximum | value, do min/max guarantee to return the *first* element in the sequence | among those? | | Example: | | >>> class A: | ... def __init__(self, x): self.x = x | ... | >>> L = [A(0), A(1), A(2), A(0)] | >>> min(L, key=lambda a:a.x) is L[0] | True | >>> min(L, key=lambda a:a.x) is L[3] | False | | Is this guaranteed by the Python language formal specification? | Is this guaranteed to always by true in CPython? (I guess so) | | I can't find any mention in the documentation. If there is no mention in the documentation (Lib Ref, Ch2 builtin functions), then there is no guarantee. From modelnine at modelnine.org Wed Mar 26 14:15:32 2008 From: modelnine at modelnine.org (Heiko Wundram) Date: Wed, 26 Mar 2008 19:15:32 +0100 Subject: Some notes on a high-performance Python application. In-Reply-To: References: <47ea78a5$0$36353$742ec2ed@news.sonic.net> Message-ID: <200803261915.32923.modelnine@modelnine.org> Am Mittwoch, 26. M?rz 2008 18:54:29 schrieb Michael Str?der: > Heiko Wundram wrote: > > Am Mittwoch, 26. M?rz 2008 17:33:43 schrieb John Nagle: > >> ... > >> > >> Using MySQL as a queueing engine across multiple servers is unusual, > >> but it works well. It has the nice feature that the queue ordering > >> can be anything you can write in a SELECT statement. So we put "fair > >> queueing" in the rating scheduler; multiple requests from the same IP > >> address compete with each other, not with those from other IP addresses. > >> So no one site can use up all the rating capacity. > >> ... > >> Does anyone else architect their systems like this? > > > > A Xen(tm) management system I've written at least shares this aspect in > > that the RPC subsystem for communication between the frontend and the > > backends is basically a (MySQL) database table which is regularily > > queried by all backends that work on VHosts to change the state (in the > > form of a command) according to what the user specifies in the (Web-)UI. > > I vaguely remember that this database approach was teached at my former > university as a basic mechanism for distributed systems at least since > 1992, but I'd guess much longer... I didn't say it was unusual or frowned upon (and I was also taught this at uni IIRC as a means to "easily" distribute systems which don't have specific requirements for response time to RPC requests), but anyway, as you noted for Biztalk, it's much easier to hit bottlenecks with a polling-style RPC than with a "true" RPC system, as I've come to experience when the number of nodes (i.e., backends) grew over the last year and a half. That's what's basically causing a re-consideration to move from DB-style RPC to socket-based RPC, which is going to happen at some point in time for the system noted above (but I've sinced changed jobs and am now only a consulting developer for that anyway, so it won't be my job to do the dirty migration and the redesign ;-)). -- Heiko Wundram From Afro.Systems at gmail.com Wed Mar 26 14:38:16 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 26 Mar 2008 11:38:16 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip References: Message-ID: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> > ....and then when my application execute code how can I set path to > d3dx module to "library.zip/d3dx.py". > I'm not sure is this properly set question. use the module zipimport http://docs.python.org/lib/module-zipimport.html From fdrake at acm.org Sun Mar 2 19:52:50 2008 From: fdrake at acm.org (Fred Drake) Date: Sun, 2 Mar 2008 19:52:50 -0500 Subject: [Python-Dev] [ANN] Python 2.3.7 and 2.4.5, release candidate 1 In-Reply-To: <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> References: <47CB168A.103@v.loewis.de> <88D43806-B25D-4538-8F7D-D17EB979C40E@acm.org> Message-ID: <592F38CC-7EFD-4ABA-BC93-CE8BB50C9CB4@acm.org> On Mar 2, 2008, at 7:43 PM, Fred Drake wrote: > 2.4.5 won't build for me from the svn checkout on Mac OS X 10.5.2: Neither does 2.3.7 now that I've tried that: gcc -u __dummy -u _PyMac_Error -framework System -framework CoreServices -framework Foundation -o python.exe \ Modules/python.o \ libpython2.3.a -ldl Undefined symbols: "__dummy", referenced from: ld: symbol(s) not found collect2: ld returned 1 exit status make: *** [python.exe] Error 1 Of course, I wasn't using an earlier 2.3.x version on this box. I would really like to be able to use 2.4.5, since I've been using 2.4.4 for work for a while now. -Fred -- Fred Drake From gagsl-py2 at yahoo.com.ar Sun Mar 30 01:35:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 02:35:55 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: > > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) Fine if you have the right keyboard... Try to write APL with a standard keyboard :) -- Gabriel Genellina From frikker at gmail.com Tue Mar 4 09:40:18 2008 From: frikker at gmail.com (blaine) Date: Tue, 4 Mar 2008 06:40:18 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> <13sotqbl5kqrsa9@corp.supernews.com> Message-ID: > > It looks like the fastest speed supported by python termios on > Linux is B460800 (uses a constant of 0x1004). If you look in > /usr/include/..., baud rates do go up to 921600 (which uses a > constant of 0x1007). > > Try using the appropriate constant from /usr/include/... (for > the target platform, of course). > > -- > Grant Edwards grante Yow! Please come home with > at me ... I have Tylenol!! > visi.com Thank you for your response. I can't seem to find what you're referencing in /usr/include. I found termios.h - but it does not define any constants (I can include it if you wish). I did find termios.c in the Python module file, which only defines constants up to : [...] {"B2400", B2400}, {"B4800", B4800}, {"B9600", B9600}, {"B19200", B19200}, {"B38400", B38400}, #ifdef B57600 {"B57600", B57600}, #endif #ifdef B115200 {"B115200", B115200}, #endif #ifdef B230400 {"B230400", B230400}, I could recompile python, I imagine, with additional constants but this wouldn't be ideal - although it is a possible solution. the only reference to a baud rate in termios.h is here: /* Return the output baud rate stored in *TERMIOS_P. */ extern speed_t cfgetospeed (__const struct termios *__termios_p) __THROW; /* Return the input baud rate stored in *TERMIOS_P. */ extern speed_t cfgetispeed (__const struct termios *__termios_p) __THROW; /* Set the output baud rate stored in *TERMIOS_P to SPEED. */ extern int cfsetospeed (struct termios *__termios_p, speed_t __speed) __THROW; /* Set the input baud rate stored in *TERMIOS_P to SPEED. */ extern int cfsetispeed (struct termios *__termios_p, speed_t __speed) __THROW; the termios.h and const.h in the linux/ folder aren't much help. I'm sure I'm just looking at the wrong file. Thank you again for all your help! Blaine From tmp1 at viltersten.com Sat Mar 1 19:32:06 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 2 Mar 2008 01:32:06 +0100 Subject: SV: Surprised by the command "del" In-Reply-To: References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: <62u9tdF25hghiU1@mid.individual.net> >>I'm reading the docs and at 5.2 the del >>statement is discussed. At first, i thought >>i've found a typo but as i tried that >>myself, it turns it actually does work so. >> >> a = ["alpha", "beta", "gamma"] >> del a[2:2] >> a >> >>Now, i expected the result to be that the >>"beta" element has been removed. Obviously, >>Python thinks otherwise. Why?! >> >>Elaboration: >>I wonder why such an unintuitive effect has >>been implemented. I'm sure it's for a very >>good reason not clear to me due to my >>ignorance. Alternatively - my expectations >>are not so intuitive as i think. :) > > I think it should say > del a[1:2] > then it works While i'm thankful for the advice, i need to point out that the question wasn't "how to" but "why". Anyhow, it's been explained as a matter of definition of a "slice". -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From Lie.1296 at gmail.com Sun Mar 23 13:17:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 23 Mar 2008 10:17:56 -0700 (PDT) Subject: dividing tuple elements with an int or float References: <9823fb53-b7bd-4f1f-832f-928051972e4f@e6g2000prf.googlegroups.com> Message-ID: <2da398c2-7976-42d9-bb77-3c1c476452e6@i7g2000prf.googlegroups.com> On Mar 20, 1:06?pm, royG wrote: > hi > i am trying to resize some images.First i'd read the size as a 2 > tuple ?and then i want to divide it by 2 or 4 or 2.5 etc.. > > suppose > origsz=(400,300) > i want to divide the origsize by 2.5 so i can resize to (160,120) There are several ways to do what you wanted: ------------- width = origsz[0] * scale height = origsz[1] * scale return width, height ------------- width, height = origsz return width * scale, height * scale ------------- return origsz[0] * scale, origsz[1] * scale ------------- # and an overly complex way of doing this return tuple(x * scale for x in origsz) ------------- > scale=2.5 > how can i get the newsz? > obviously origsz/2.5 won't work ?.. > thanks > RG Aside: I think you're a bit confused about the semantic of scaling in image resizing, when you want to halve the image size (e.g. 100x100 -> 50x50) you scale it by 0.5, and when you want to double the image size (e.g. 100x100 -> 200x200) you scale it by 2. This operation is done by multiplication, not division. (i.e. scaling a 400x300 images by 2.5 means upsizing the image into 1000x750) On Mar 20, 9:28 pm, "Jerry Hill" wrote: (snip) > That works fine for a 2-tuple, but might get unwieldy for larger > tuples, or if you don't know the length until runtime. A more general > solution might use a generator expression, like this: (snip) I think since the semantic of origsz is well defined (width-height pair of an image) it will always be a 2-tuple, anything other than 2- tuple should either be discarded or raise an error (depending on design choice). P.S.: If you're sure that you want to use division, make sure to "from __future__ import division" or convert the scaling factor into floats or you'll most likely get the wrong result as Python defaults to integer division (due to be changed in Python 3). And you should remember that the resulting image size should also be (integer, integer) since you can't have an image that's 100.2432x392.9875 From castironpi at gmail.com Tue Mar 4 23:02:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 20:02:46 -0800 (PST) Subject: Difference between 'function' and 'method' References: <47cd3238$0$17697$426a74cc@news.free.fr> <1a6a401b-e67a-416d-a058-bda62bbe7c22@d21g2000prf.googlegroups.com> <3bf1963f-45f8-4eda-a2ac-0d857af23105@s19g2000prg.googlegroups.com> Message-ID: On Mar 4, 9:53?pm, castiro... at gmail.com wrote: > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it > > >> >> is it makes it. > > > >> >>>> from types import FunctionType, MethodType > > >> >>>> class A( FunctionType ): pass > > >> > ... > > >> > Traceback (most recent call last): > > >> > ? File "", line 1, in > > >> > TypeError: type 'function' is not an acceptable base type > > > >> Use delegation instead of inheritance. This class is almost ? > > >> indistinguishable from a true function (when used as a method): > If P gets, p gotcha. > > > gotcha= partial( get, you ). ?bor hor hor. ?Yes... Notwithstanding. Now bar has a name. class myfunction: __slots__ = ('func','name') # def __init__(self, func): object.__setattr__(self, 'func', func) object.__setattr__(self, 'name', None) # def __get__(self, instance, owner): print( "__get__ called for",instance ) return self.func.__get__(instance, owner) # def __getattr__(self, name): return getattr(self.func, name) # def __setattr__(self, name, value): object.__setattr__(self.func, name, value) class mymeta( type ): def __init__( self, name, bases, namespace ): for k,v in namespace.items(): if isinstance( v, myfunction ): v.name= k class P( metaclass= mymeta ): def foo(self, x): print( 'foo',x ) # @myfunction def bar(self, x): print( 'bar',x ) p= P() p.foo( 0 ) p.bar( 1 ) print( p.bar ) print( p.bar.name ) ''' output: ''' foo 0 __get__ called for <__main__.P object at 0x00B481F0> bar 1 __get__ called for <__main__.P object at 0x00B481F0> > __get__ called for <__main__.P object at 0x00B481F0> bar From ncoghlan at gmail.com Tue Mar 4 08:46:48 2008 From: ncoghlan at gmail.com (NickC) Date: Tue, 4 Mar 2008 05:46:48 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> Message-ID: <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> On Mar 4, 7:11 am, Lie wrote: > On Mar 2, 11:36 pm, Paul Rubin wrote: > > > > Try with a=7, b=25 > > > > They should still compare true, but they don't. The reason why they > > > don't is because of float's finite precision, which is not exactly > > > what we're talking here since it doesn't change the fact that > > > multiplication and division are inverse of each other. > > > What? Obviously they are not exact inverses for floats, as that test > > shows. They would be inverses for mathematical reals or rationals, > > but Python does not have those. > > When I said multiplication and division are inverse, I was pointing > out the fact that even though float's inexactness make them imperfect > inverse, mult & div are still inverse of each other. In-practice, the > inversing behavior is impossible unless we have a way to represent > real number (which we don't), and the *workaround* to make them work > is to do epsilon comparison. A mildly interesting Py3k experiment: Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from fractions import Fraction >>> from decimal import Decimal >>> def check_accuracy(num_type, max_val=1000): ... wrong = 0 ... for x in range(1, max_val): ... for y in range(1, max_val): ... wrong += (x / num_type(y)) * y != x ... return wrong ... >>> check_accuracy(float) 101502 >>> check_accuracy(Decimal) 310013 >>> check_accuracy(Fraction) 0 The conclusions I came to based on running that experiment are: - Decimal actually appears to suffer more rounding problems than float for rational arithmetic - Decimal appears to be significantly slower than Fraction for small denominator rational arithmetic - both Decimal and Fraction are significantly slower than builtin floats The increased number of inaccurate answers with Decimal (31% vs 10%) is probably due to the fact that it is actually more precise than float - for the builtin floats, the rounding error in the division step may be cancelled out by a further rounding error in the multiplication step (this can be seen happening in the case of ((1 / 3.0) * 3) == 1.0, where the result of the multiplication ends up being 1.0 despite the rounding error on division, due to the next smallest floating value being 0.99999999999999989). The speed difference between Decimal and Fraction is likely due to the fact that Fraction can avoid actually doing any division most of the time - it does addition and multiplication instead. The main reason behind the overall speed advantage of builtin floats should hopefully be obvious ;) Regardless, the result of integer division is going to be a binary floating point value in Py3k. For cases where that isn't adequate or acceptable, the application should really be tightly controlling its numeric types anyway and probably using a high performance math library like numpy or gmpy instead of the standard numeric types (as others have already noted in this thread). From castironpi at gmail.com Thu Mar 27 01:55:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 22:55:19 -0700 (PDT) Subject: Line segments, overlap, and bits References: <8524740b-ddba-4a77-8f21-ffdd9849adb0@u69g2000hse.googlegroups.com> <7xej9woqrd.fsf@ruckus.brouhaha.com> Message-ID: <028353bb-26a0-46d1-b450-8396a4d419bb@p25g2000hsf.googlegroups.com> On Mar 26, 9:16?pm, Paul Rubin wrote: > Sean Davis writes: > > OR, NOT, etc.). ?Any suggestions on how to (1) set up the bit string > > and (2) operate on 1 or more of them? ?Java has a BitSet class that > > keeps this kind of thing pretty clean and high-level, but I haven't > > seen anything like it for python. > > You could wrap something around the array module, or the bit vector > objects from numarray, or use something like PyJudy (google for it). > Or consider using something like a tree data structure that supports > set operations, rather than a bitmap, if that's closer to what you're > really trying to do. Keep it continuous. You're looking at holographic or specific on tree leaves. I can store a GPS a -lot- easier than words. Force impact from a direction? (Strong A, two Bs.) Record wind. Repose. On idle, broadcast at unique intervals, wait for something to do. (developmental reposition) I suppose you want perception in the medium, but I think a special mechanism is always more efficient. Can you have minispiders hand off instructions by rapid tactile contact? Dock incl. clock sync, dual transmit, undock, work. Sounds like modem (modulator/demodulator) and ATM. The DNA of an organism doesn't change over time, but it manages to perform multi-cellular operations. Each cell has its very own copy, read-only, of the whole's DNA. Can lightning bugs turn on and off instruction sets (exec, donotexec)? Mem. block: 0000 Yes 0 1 add 0001 Yes 0 2 add 0010 No 0 3 add 0011 Yes 0 4 add runs: ( add 1, add 2, add 4 ). Local can transmit modifications to neighbor sames. Local gradient is stronger, which takes us to chemical. There is no living model for bees that sync post-mortem live -- they get orders for the next day "at dance". By the way, Queen bees, Workers and Drones have a developmental period of 16, 21, 24 days respectively. Conclude Workers are the special. Thing is, two adjacent cells in the animal body can vary pretty widely in trait. Stem cells can "differentiate into a diverse range of specialized cell types". Is time a factor in response to mechanistic signal propogation. Make a uniform response to every signal, and you're a functional programmer. input f o output. From castironpi at gmail.com Wed Mar 5 21:08:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 18:08:08 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> <83f40c69-a356-4af3-8fcf-aac4097dc480@n75g2000hsh.googlegroups.com> Message-ID: <52ad243f-4f72-4dcf-8c51-2f2d8c1da687@o77g2000hsf.googlegroups.com> On Mar 5, 6:40?pm, bearophileH... at lycos.com wrote: > Troels Thomsen: > > > The discussion of words is silly. My surprise about "else following a for > > loop.... what the heck ...." lasted excactly as long as it takes to read > > this sentence. > > Maybe I don't follow what you are saying, but well chosen words are a > very important part of a well designed API. If you take a look at the > Python developers mailing list you may see that people discuss days, > weeks to find the best naming for things. They should've called it "or-else". Bor hor hor. ...The keyword, I mean. From gagsl-py2 at yahoo.com.ar Sat Mar 1 01:35:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Mar 2008 04:35:07 -0200 Subject: at-exit-thread References: <62r68tF220j59U1@mid.uni-berlin.de> <6b3e762b-f053-451a-845e-5a08bdb13b9d@s8g2000prg.googlegroups.com> Message-ID: En Fri, 29 Feb 2008 18:12:13 -0200, escribi?: > On Feb 29, 1:55?pm, "Diez B. Roggisch" wrote: >> castiro... at gmail.com schrieb: >> >> > The Python main interpreter has an at-exit list of callables, which >> > are called when the interpreter exits. ?Can threads have one? ?What's >> > involved, or is the best way merely to subclass Thread? >> >> Is that some sort of trick-question? >> >> class MyThread(Thread): >> >> ? ? def run(self): >> ? ? ? ? while some_condition: >> ? ? ? ? ? ? ?do_something() >> ? ? ? ? do_something_after_the_thread_ends() >> >> The atexit stuff is for process-termination which is/may be induced by >> external signals - which is the reason why these callbacks extist. >> Threads don't have that, thus no need. > > That depends. If a thread adds an object it creates to a nonlocal > collection, such as a class-static set, does it have to maintain a > list of all such objects, just to get the right ones destroyed on > completion? Yes, like any other objects. All threads in a process share the same memory space; any thread can "see" any other created object, and the general rules on reference counting apply: an object is destroyed when it is no more referenced. There are threading.local objects, which are specially designed to provide per-thread storage; they are not shared among threads. (BTW, you should use a threading.local instance instead of indexing by get_ident()) > Processes destroy their garbage hassle-free; how can > threads? And don't forget Thread.run( self ) in the example, if > anyone ever wants to make use of the 'target' keyword. Any object created inside a thread will be destroyed when the last reference to it is removed, as any other object. Threads are not special in this regard. -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Tue Mar 18 05:59:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 18 Mar 2008 20:59:55 +1100 Subject: Program source implemented in non-text storage (was: Regarding coding style) References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <082e467c-0565-4dda-ae47-daada3022443@u69g2000hse.googlegroups.com> <04eecb57-e7c7-4022-b16d-8b904694d298@m36g2000hse.googlegroups.com> <1309d923-16cc-45c8-9172-4a8362eccd26@o77g2000hsf.googlegroups.com> <8ca43caa-5a2c-4b7b-b168-aad4cfb0581a@a23g2000hsc.googlegroups.com> <649h81F2974cmU1@mid.uni-berlin.de> Message-ID: <871w68z71g.fsf_-_@benfinney.id.au> Marc 'BlackJack' Rintsch writes: > [A general VCS] depends usually on the fact that there are > individual files. Preferably text files if you want automagic > merging of different changes. Yes. > Now think of languages that are tightly coupled with their IDE > storing only binary "tokenized" files instead of plain text or even > one big binary file that contains all sources and resources of the > project. Those issues have nothing to do with the language, and everything to do with the language implementation. Moreover, a brain-dead monstrosity as you describe would result in far greater problems than merely the lack of decent version control support. I think it's safe to leave such implementations to rot, rather than stretching tools to acommodate them. -- \ ?That's all very good in practice, but how does it work in | `\ *theory*?? ?anonymous | _o__) | Ben Finney From kw at codebykevin.com Sat Mar 15 16:33:36 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 15 Mar 2008 16:33:36 -0400 Subject: Getting started with OS X Leopard In-Reply-To: <47dc2c42$0$32056$da0feed9@news.zen.co.uk> References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> <47dc23f7$0$32053$da0feed9@news.zen.co.uk> <904b78ef-d3b4-468b-a0e1-69569137107b@e6g2000prf.googlegroups.com> <47dc2c42$0$32056$da0feed9@news.zen.co.uk> Message-ID: <47DC32A0.4000707@codebykevin.com> Mark Carter wrote: > Arnaud Delobelle wrote: > >> Is there a particular reason you want python from MacPorts? OSX >> Leopard comes with python 2.5, that's what I use on my mac. > > I heard from somewhere that Apple's version was a bit wonky, and that I > would be better off with a "proper" build. Not sure where you heard that. Apple's Python is built according to Mac guidelines (as a "framework"), but it works the same as on other platforms. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mikey at swampgas.com Wed Mar 26 15:38:55 2008 From: mikey at swampgas.com (Michael Owings) Date: Wed, 26 Mar 2008 14:38:55 -0500 Subject: PyODBC Stored proc calling Message-ID: <47EAA64F.30908@swampgas.com> This is probably pretty late to be replying but I had the same problem. As it turns out, you just need to be sure you use the correct syntax to call the sproc: db_cur.execute( "{call test_bed(?)}", ('test data string') ) -- Teleoperate a roving mobile robot from the web: http://www.swampgas.com/robotics/rover.html From gagsl-py2 at yahoo.com.ar Mon Mar 24 21:26:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Mar 2008 22:26:32 -0300 Subject: Calling a shared library using C types References: Message-ID: En Mon, 24 Mar 2008 19:56:08 -0300, Nathan Harmston escribi?: > import ctypes > t = ctypes.CDLL('./Simulation.so') > this works fine, I have a simple function I ve put in for testing which > just > returns the integer 4. However when I try to access this function it > doesnt > work > t.test() > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > line 325, in __getattr__ > func = self.__getitem__(name) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", > line 330, in __getitem__ > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: dlsym(0x81e6b0, test): symbol not found Looks like the symbol isn't public - probably if you try loading the library with a C program it won't find it either. How is the function declared in the source? Try listing all public symbols with: nm -D Simulation.so > Im hoping python-list is ok for questions regarding ctypes :S It's not off topic, although there is a specific list for ctypes-related questions. But hijacking a thread to post a completely different question is not good netiquette. -- Gabriel Genellina From stefan_ml at behnel.de Mon Mar 10 04:32:07 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Mar 2008 09:32:07 +0100 Subject: Distributed App - C++ with Python for Portability? In-Reply-To: References: <01e8acf9-9628-484d-910a-3a791517b22a@k13g2000hse.googlegroups.com> <47d4e9aa$0$25511$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <47D4F207.6050606@behnel.de> Matt Nordhoff wrote: > Stefan Behnel wrote: >> And if you really need the efficiency of "well-tuned raw C", it's one function >> call away in your Cython code. > > What do you mean by that? > > I know nothing about how Cython compares to C in performance, so I said > "well-tuned" because it must be possible to write C that is faster than > Cython, though it may take some effort. So, you write the hand-optimised function in plain C, declare it in Cython and call it. That's what I meant. Since Cython compiles to C code, linking against a C module is straight forward. And this still keeps you from having to write all the Python API glue code in plain C. Stefan From rschroev_nospam_ml at fastmail.fm Mon Mar 17 14:18:19 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 17 Mar 2008 19:18:19 +0100 Subject: Anomaly in time.clock() In-Reply-To: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> References: <95e3ec24-2fd0-4bf1-9412-ccb03604aab3@d4g2000prg.googlegroups.com> Message-ID: Godzilla schreef: > Hello, > > I have been reading a thread about time.clock() going backward, which > is exactly what I am seeing... the thread generally leaning toward the > problem is caused by multi-processor machines. But I am seeing it at a > single CPU computer, and running XP. > > The error I am seeing between two very close invokation of > time.clock() is always around 3.5 seconds! This is enough to throw a > lot of the timing requirement in the software out of the window... > this is a fairly serious problem. I don't know if it's the same problem, but I've seen something similar to this. Are you by any chance using DirectX? When you create a DirectX device, DirectX by default resets the precision of the CPU to 20 bits or so. I had that problem in a project at work, with similar results (and other strange calculation errors). The solution was to use a flag (PRESERVE_PRECISION or something like that) in the CreateDevice() call (it was a C++ project). If it's something else, I'm afraid I can't help. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From MartinRinehart at gmail.com Thu Mar 27 11:03:39 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 08:03:39 -0700 (PDT) Subject: Tkinter Text widget Message-ID: <5c2ef3b6-00cb-497e-845e-7683ac22310e@s13g2000prd.googlegroups.com> Is there a way of translating from the Text widget's width/height (in characters) to pixels so you can open an appropriately sized window? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 05:22:13 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 10:22:13 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: References: <47EB58B5.1020801@mydeskfriend.com> Message-ID: <47eb673e$0$26637$426a74cc@news.free.fr> Gabriel Rossetti a ?crit : > > Gabriel Rossetti wrote: >> Hello, >> >> I am using Partial Function Application in a class and I've come up >> with a problem, when the method is called it tries to pass "self" to >> the curried/partial function, but this should be the first argument in >> reality, but since the function is curried, then the self gets passed >> as the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that >> since self is not available there. Does anyone have any ideas? >> >> Thanks, >> Gabriel >> > I also tried this : > > def __registerService(atomic, self, service): > def reg(service): > # registers the service > ... > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > thinking that the self will be passed as the first argument of the > registerService* calls and thus the second argument to the > curried/partial method, but it doesn't work either, I get : > > Traceback (most recent call last): > File "/home/xxx/Documents/Code/Python/test/test_serv.py", line 245, in > test_registeration > self.f.registerServiceAtomic(self.serv) > exceptions.TypeError: __registerService() takes exactly 3 arguments (2 > given) > > I don't get it... Looks like functools.partial doesn't implement the protocol descriptor to behave like an ordinary function. I suppose there's some good reason for this, but anyway you'll have to either extend partial to add the appropriate descriptor support, or provide self by yourself (like Diez suggested). From hdante at gmail.com Sun Mar 30 18:22:42 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 15:22:42 -0700 (PDT) Subject: Summary of threading for experienced non-Python programmers? References: Message-ID: On Mar 28, 11:52 am, s... at pobox.com wrote: > I'm having trouble explaining the benefits and tradeoffs of threads to my > coworkers and countering their misconceptions about Python's threading model > and facilities. They all come from C++ and are used to thinking of > multithreading as a way to harness multiple CPU cores for compute-bound > processing. I also encountered, "Python doesn't really do threads" today. > *sigh* > > I don't need pointers to the relevant documentation sections. A bit of > googling didn't turn up much about threading beyond tutorial introductions. > I'm looking for something which will explain the rationale for using threads > in Python to someone who is experienced with multithreading in other > languages (like C/C++). Maybe a compare-and-contrast sort of document? > > Thanks, > > Skip I think you are having trouble because threads suck. They are the worst way of dealing with concurrency that exists (unfortunately they are the fastest also) :-). Threads are bad because, by construction, code may be subject to non- trivial hazards. There are other ways of dealing with concurrency that doesn't have this problem, like event-driven programming. I think threads are so bad, that when I left my job at a company that developed for PDAs, I told my team: "whenever you have an argument about how to make multitasking, you may count my vote against using threads". If you really need to use threads, then use design patterns that make threads behave like message passing systems (I believe there were the "monitor model" or the "actor model" or something). If you need threads because you need speed, then use a recent JIT- compiled language, like Java or C#. In general, you may use C or C++ also, but there are a few obscure problems with them because they weren't defined with threads in mind. If you just would like to use "multitasking" as a programming paradigm, try Twisted, or switch to stackless python (then write an blog about your findings). :-) From sjmachin at lexicon.net Sat Mar 22 07:48:17 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 04:48:17 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> <51bc52ea-74dc-441a-9be4-989e10044be6@m3g2000hsc.googlegroups.com> Message-ID: On Mar 22, 9:58 pm, Arnaud Delobelle wrote: > > Lastly, if one deals with a totally ordered set of object but they are > not hashable (there isn't a good hash function), then Ninereeds' idea > of sorting first is still useful. ... and if not totally ordered, then ... I'll just stand aside and cue the timbot :-) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 From zerty.david at gmail.com Wed Mar 26 15:18:20 2008 From: zerty.david at gmail.com (David Anderson) Date: Wed, 26 Mar 2008 16:18:20 -0300 Subject: what does ^ do in python In-Reply-To: <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> <47EA99EE.5030304@tim.thechases.com> <5dc598e30803261214p363ac76cqc1c044d4bd2e678a@mail.gmail.com> Message-ID: <5dc598e30803261218m6e7d2790xac49eacf030bc0d@mail.gmail.com> ANd... By express I mean... Dereferencing... Habits from my native language where the verb express also means this On Wed, Mar 26, 2008 at 4:14 PM, David Anderson wrote: > Err even I cant understand what I wrote... > The right question was:HOw can we use/express pointers python as in C or > Pascal? > But thx to Heiko, He got what I mean =) > > > On Wed, Mar 26, 2008 at 3:46 PM, Tim Chase > wrote: > > > >> HOw can we use express pointers as in C or python? > > > > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "parser.py", line 123, in parse_text > > > tree = language.parse_text(text) > > > File "english.py", line 456, in parse_text > > > tree = self.parse_sentence(sentence) > > > File "english.py", line 345, in parse_sentence > > > raise ParserError, "can't parse %r" % sentence > > > ParserError: can't parse 'HOw can we use express pointers as in C or > > > python?' > > > > Possible "express pointers": > > > > http://www.geocities.com/derwin_b/sr91sign.jpg > > > > http://www.gribblenation.net/njpics/drive/78/exp78on78w.jpg > > > > > > http://adcentered.typepad.com/photos/uncategorized/2007/03/31/subway2.jpg > > > > If those meet the OP's need, I recommend urllib2 and PIL. > > > > -tkc > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Mar 21 16:39:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 21 Mar 2008 13:39:09 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> Message-ID: <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> On Mar 22, 1:11 am, castiro... at gmail.com wrote: > On Mar 21, 4:17 am, Bryan Olson wrote: > > > > > Arnaud Delobelle wrote: > > > Bryan Olson wrote: > > [...] > > >> Arnaud Delobelle offered a good Wikipedia link, and for more background > > >> look up "amortized analysis. > > > > Hrvoje Niksic provided the link :). > > > Oops, careless thread-following. Hrvoje Niksic it was. > > > > I still think two unrelated > > > things are being compared in this thread when people say that method A > > > (using dictionaries / sets) is O(n) and method B (sorting the list) > > > O(nlogn). > > > > Isn't it the case that: > > > > | Worst case | Average case > > > ---------|------------|------------- > > > Method A | O(n^2) | O(n) > > > Method B | O(nlogn) | O(nlogn) > > > > Which method is the best would then be determined by the distribution > > > of the hash values of your data, and whether you want to have a > > > guarantee the method will have a less-than-quadratic behaviour. > > > If we exclude the case where an adversary is choosing the keys, the > > chance of a seriously degenerate case in the hashing method is so > > remote that we do should not worry about it. Those who insist on > > ranking by worst-case behavior have probably abandoned Python long > > ago, as it uses those hashed 'dict' things everywhere. Of course > > they've also abandoned OS's with demand-paged virtual memory and > > such. > > > -- > > --Bryan > > A collision sequence is not so rare. > > >>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > > [1, 1, 1, 1, 1, 1, 1, 1] Bryan did qualify his remarks: "If we exclude the case where an adversary is choosing the keys, ..." From dave.brk at gmail.com Wed Mar 19 19:53:49 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 20 Mar 2008 01:53:49 +0200 Subject: [newbie] using ElementTree, how to add doctype and xml pi Message-ID: Hi all I have an svg file i'm creating on the fly. How do I add the doctype and xml pi? They're not an element per se, and there is no function to add them. Am I suppose to add them as elements after all? I have something like this: self.svgRoot = ET.Element("svg", xmlns=r'http://www.w3.org/2000/svg') ET.SubElement(self.svgRoot, "g", transform="scale(1,-1)") .... .... .... self.tree = ET.ElementTree(self.svgRoot) ... thanks dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat Mar 1 02:03:01 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 01 Mar 2008 07:03:01 GMT Subject: pySQLite Insert speed References: Message-ID: mdboldin at gmail.com wrote: > >I hav read on this forum that SQL coding (A) below is preferred over >(B), but I find (B) is much faster (20-40% faster) > >(A) > > sqla= 'INSERT INTO DTABLE1 VALUES (%d, %d, %d, %f)' % values > curs.execute(sqla) > >(B) > pf= '?, ?, ?, ?' > sqlxb= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > curs.execute( sqlxb, values ) > >Any intution on why (A) is slower? I think you misunderstood. (B) is *ALWAYS* the proper way of doing parameterized SQL queries. Unconditionally. The (A) style is way too vulnerable to SQL injection attacks. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From myeates at jpl.nasa.gov Mon Mar 17 15:34:29 2008 From: myeates at jpl.nasa.gov (Mathew) Date: Mon, 17 Mar 2008 12:34:29 -0700 Subject: placing a Python com object into Excel Message-ID: Hi I have seen examples from Mark Hammonds book where a Python COM object is accessed from Excel with a VBA script. But, what if I want to Insert a Python COM into the Sheet itself? When I try this, a list of available objects appear. But my object isn't on the list. Anybody have any ideas? Mathew From martin at v.loewis.de Sun Mar 9 18:35:18 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 09 Mar 2008 23:35:18 +0100 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: Message-ID: <47D46626.6090203@v.loewis.de> > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. These symbols are all from pythonxy.dll. You need to add the corresponding import library (libpythonxy.a/pythonxy.lib) into the linker line, using a -l option. Regards, Martin From pavlovevidence at gmail.com Mon Mar 3 17:53:21 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Mar 2008 14:53:21 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> Message-ID: <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> On Mar 3, 4:47 pm, Mensanator wrote: > On Mar 3, 2:49 pm, Carl Banks wrote: > > > > > On Mar 3, 3:40 pm, Mensanator wrote: > > > > Notice anything funny about the "random" choices? > > > > import sympy > > > import time > > > import random > > > > f = [i for i in sympy.primerange(1000,10000)] > > > > for i in xrange(10): > > > f1 = random.choice(f) > > > print f1, > > > f2 = random.choice(f) > > > print f2, > > > C = f1*f2 > > > ff = None > > > ff = sympy.factorint(C) > > > print ff > > > > ## 7307 7243 [(7243, 1), (7307, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > ## 8563 2677 [(2677, 1), (8563, 1)] > > > ## 4091 6829 [(4091, 1), (6829, 1)] > > > > As in, "they're NOT random". > > > > The random number generator is broken by the sympy.factorint() > > > function. > > > > Random.choice() works ok if the factorint() function commented out. > > > > ## 6089 1811 None > > > ## 6449 1759 None > > > ## 9923 4639 None > > > ## 4013 4889 None > > > ## 4349 2029 None > > > ## 6703 8677 None > > > ## 1879 1867 None > > > ## 5153 5279 None > > > ## 2011 4937 None > > > ## 7253 5507 None > > > > This makes sympy worse than worthless, as it f***s up other modules. > > > Dude, relax. > > > It's just a bug--probably sympy is messing with the internals of the > > random number generator. It would be a simple fix. Instead of > > b****ing about it, file a bug report. > > I did. > > > Or better yet, submit a patch. > > I would if I knew what the problem was. > > I posted it here because someone recommended it. > I'm simply un-recommending it. Those who don't care > needn't pay any attention. Those who do should be > glad that faults are pointed out when found. 1. You can point out the faults of a program without insults and vulgarity 2. You must be terribly difficult to please if one bug is enough to recommend against a program as "worse than worthless" 3. You must be terribly naive if you expect a freeware program with a version number of 0.5.12 not to have bugs Carl Banks From mmanns at gmx.net Fri Mar 21 19:06:41 2008 From: mmanns at gmx.net (Martin Manns) Date: Sat, 22 Mar 2008 00:06:41 +0100 Subject: How can I make a function equal to 0? References: <8b27bb50-5dd6-4ea2-afa0-f0e7832a7f04@59g2000hsb.googlegroups.com> Message-ID: On Fri, 21 Mar 2008 14:51:49 -0700 (PDT) Gabriel Genellina wrote: > > If I fill the array with 0 instead of the functions that > > return "" this works really fast. > > > > However, I would like to be able call the content of each > > cell in the array as a function. > > If you drop this condition then you could fill the array with zeroes > as before, replace only the interesting ones with actual functions, > and write: > > for item in myarray[nonzero(myarray)]: > print item() if callable(item) else item Works for me. Thank you Martin From gabriel.rossetti at mydeskfriend.com Tue Mar 18 06:03:15 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 18 Mar 2008 11:03:15 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom In-Reply-To: <1205831099.3212.18.camel@localhost.localdomain> References: <47DF7803.1070902@mydeskfriend.com> <1205831099.3212.18.camel@localhost.localdomain> Message-ID: <47DF9363.3050807@mydeskfriend.com> Carsten Haese wrote: > On Tue, 2008-03-18 at 09:06 +0100, Gabriel Rossetti wrote: > >> Hello, >> >> I am reading core python python programming and it talks about using the >> idiom >> described on >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . >> >> I'm using python 2.5.1 and if I try : >> >> class MyClass(object): >> def __init__(self): >> self._foo = "foo" >> self._bar = "bar" >> >> @property >> def foo(): >> doc = "property foo's doc string" >> def fget(self): >> return self._foo >> def fset(self, value): >> self._foo = value >> def fdel(self): >> del self._foo >> return locals() # credit: David Niergarth >> >> @property >> def bar(): >> doc = "bar is readonly" >> def fget(self): >> return self._bar >> return locals() >> >> like suggested in the book (the decorator usage) I get this : >> >> >>> a=MyClass() >> >>> a.foo >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: foo() takes no arguments (1 given) >> >> but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : >> >> >>> a = MyClass() >> >>> a.foo >> 'foo' >> >> does anyone have an idea as of why this is happening? >> > > You're mixing two completely different approaches of building a > property. If that code is actually in the book like that, that's a typo > that you should mention to the author. > > The @property decorator can only be used to turn a single getter > function into a read-only attribute, because this: > > @property > def foo(...): > ... > > is the same as this: > > def foo(...): > ... > foo = property(foo) > > and calling property() with one argument builds a property that has just > a getter function that is the single argument you're giving it. > > The recipe you're referring to uses a magical function that returns a > dictionary of getter function, setter function, deleter function, and > docstring, with suitable key names so that the dictionary can be passed > as a keyword argument dictionary into the property() constructor. > However, that requires the magical foo=property(**foo()) invocation, not > the regular decorator invocation foo=property(foo). > > HTH, > > I was able to get it t work with the decorator by doing this : def MyProperty(fcn): return property(**fcn()) and using it like this : class MyClass(object): def __init__(self): self._foo = "foo" self._bar = "bar" @MyProperty def foo(): doc = "property foo's doc string" def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() # credit: David Niergarth @MyProperty def bar(): doc = "bar is readonly" def fget(self): return self._bar return locals() Cheers, Gabriel From jeff at schwabcenter.com Tue Mar 18 00:28:31 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 17 Mar 2008 21:28:31 -0700 Subject: Interesting math problem In-Reply-To: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> References: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > On Mar 17, 10:24 pm, "BJ?rn Lindqvist" wrote: >> Here is an interesting math problem: >> >> You have a number X > 0 and another number Y > 0. The goal is to >> divide X into a list with length Y. Each item in the list is an >> integer. The sum of all integers is X. Each integer is either A or A + >> 1, those should be "evenly distributed." >> >> Example: >> >> 17 // 5 = 3 gives the list [3, 3, 4, 3, 4] >> 16 // 4 = 4 gives the list [4, 4, 4, 4] >> 113 // 50 = 2 gives the list [2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, >> 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, >> 3, 2, 3, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3, 3] >> >> This algorithm is used a lot in programming. For example, for >> projecting a line on a pixel display. Your mission, should you choose >> to accept it, is to improve the code given below which is my best >> attempt and make it more succinct and easier to read. Preferably by >> using list comprehensions, map or even reduce.... >> >> def make_slope(distance, parts): >> step = distance / float(parts) >> intstep = int(step) >> floatstep = step - intstep >> >> steps = [] >> acc = 0.0 >> for i in range(parts): >> acc += floatstep >> step = intstep >> if acc > 0.999: >> step += 1 >> acc -= 1.0 >> steps.append(step) >> return steps >> >> # Test code >> distance = 130 >> parts = 50 >> L = make_slope(distance, parts) >> assert(len(L) == parts) >> assert(sum(L) == distance) >> print L >> >> -- >> mvh Bj?rn > > OK then, using list comprehensions. It is more succint, is it easier > to read? > > def slope(dist, parts): > return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)] That's awesome, but I sure hope you'd mix in a comment in real code. ;) From vedrandekovic at yahoo.com Thu Mar 27 09:44:07 2008 From: vedrandekovic at yahoo.com (vedrandekovic at yahoo.com) Date: Thu, 27 Mar 2008 06:44:07 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip References: <94178aef-40dc-400f-a1f5-70cd794acb2a@i12g2000prf.googlegroups.com> Message-ID: <984aa470-107b-4047-be36-90405c27da39@s19g2000prg.googlegroups.com> On 27 o?u, 10:44, "Gabriel Genellina" wrote: > En Thu, 27 Mar 2008 06:00:26 -0300, escribi?: > > > > > I was add this into my application code: > > > import sys > > import os > > my_dir=os.getcwd() > > sys.path.append(my_dir) > > sys.path.append(my_dir+"\\libary.zip") > > sys.path.append(my_dir+"\\libary.zip\\py2exe") # PY2EXE is folder > > f=open("path.txt","w") > > f.write(str(sys.path)) > > f.close() > > > an the output in path.txt is : > > > ['C:\\Users\\veki\\Desktop\\python\\PGS\\dist\\library.zip', 'C:\\Users > > \\veki\\Desktop\\python\\PGS\\dist', 'C:\\Users\\veki\\Desktop\\python\ > > \PGS\\dist\\libary.zip', 'C:\\Users\\veki\\Desktop\\python\\PGS\\dist\ > > \libary.zip\\py2exe'] > > > But it still can't find module py2exe.What should I do now? Any > > examples? > > I assume you're talking about the py2exe package available from www.py2exe.org- so it's not a module, it's a package. > py2exe usually is only relevant on your *development* machine, so why do > you want to put it inside a .zip? What do you want to do? > > Anyway, I tried the following and could import py2exe successully (but I > don't know if it actually works as a distutils extension...) > > - compressed the py2exe folder into py2exe.zip > - deleted the original py2exe folder > - moved py2exe.zip onto some temporary directory > - tried to import py2exe, failed as expected > - added py2exe.zip to sys.path > - tried to import py2exe, this time OK > > py> import py2exe > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named py2exe > py> import sys > py> sys.path.append(r"C:\TEMP\pna\py2exe.zip") > py> import py2exe > py> py2exe.__path__ > ['C:\\TEMP\\pna\\py2exe.zip\\py2exe'] > > -- > Gabriel Genellina Hello again, Thanks for previous post, it was useful! So now I know what is a problem, but I don't know how to solve it.Under my application user can convert his python code to executable, I was created this with subprocess: retcode =subprocess.Popen(["ython","setup.py","py2exe","-d","exe"], shell=True, stdout=subprocess.PIPE,creationflags = win32process.CREATE_NO_WINDOW) stdout_value = retcode.communicate()[0] ...Py2exe exit from process here: running py2exe creating C:\Users\veki\Desktop\python\PGS\dist\build creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32 creating C:\Users\veki\Desktop\python\PGS\dist\build \bdist.win32\winexe creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \collect-2.5 creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \bundle-2.5 creating C:\Users\veki\Desktop\python\PGS\dist\build\bdist.win32\winexe \temp creating C:\Users\veki\Desktop\python\PGS\dist\exe *** searching for required modules *** ...it's trying to find d3d,d3dx,d3dc,d3dgui... modules but it can't cause these modules are in library.zip.How can I set target for finding path to library.zip , I'm running these py2exe compile process from my main excutable? Regards, Vedran From bharathv6.project at gmail.com Wed Mar 19 03:06:52 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Wed, 19 Mar 2008 12:36:52 +0530 Subject: automatically doing some cleaning-up by the process when the systems shuts down In-Reply-To: References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> Message-ID: <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> hi , thanks Gabriel ... but r u sure if it is SYSTERM ?or is it SIGTERM ? I am not aware of any SYSTERM signal .. if it is SYSTERM please tell me more about it .. as google search is not helping .. and also is there some way for my process which is running as a daemon to know that system was not shut down properly previously ....eg a power failure .. so that my program can do necessary steps if cleaning up is not done during its last termination On Wed, Mar 19, 2008 at 8:25 AM, Gabriel Genellina wrote: > En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh > escribi?: > > > my programs runs as daemon and it does some logging .. when system > > shuts down .. which may be done manually . i want my process do some > > cleaning up automatically such as writing in to the log file when the > > process terminats before the system shuts down > > handling the SYSTERM signal? > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sun Mar 2 06:15:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 03:15:02 -0800 (PST) Subject: Beginner's assignment question References: Message-ID: <360f7e15-0d24-4c30-8513-1ae683a69b33@q33g2000hsh.googlegroups.com> On Mar 2, 4:49?am, "Gabriel Genellina" wrote: > En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > > > > > > > Lorenzo Gatti wrote: > >> On Mar 1, 3:39 pm, Schizoid Man wrote: > >>> As in variable assignment, not homework assignment! :) > > >>> I understand the first line but not the second of the following code: > > >>> a, b = 0, 1 > >>> a, b = b, a + b > > >>> In the first line a is assigned 0 and b is assigned 1 simultaneously. > > >>> However what is the sequence of operation in the second statement? I;m > >>> confused due to the inter-dependence of the variables. > > >> The expressions of the right of the assignment operator are evaluated > >> before assigning any new values, to the destinations on the left side > >> of the assignment operator. > >> So substitutig the old values of a and b the second assignment means > > >> a, b = 0, 0 + 1 > > >> Simplifying the Python Reference Manual ("6.3 Assignment Statements") > >> a little : > > >> assignment_stmt ::= target_list "="+ expression_list > > >> An assignment statement evaluates the expression list (remember that > >> this can be a single expression or a comma-separated list, the latter > >> yielding a tuple) and assigns the single resulting object to each of > >> the target lists, from left to right. > > >> [...] > > >> WARNING: Although the definition of assignment implies that overlaps > >> between the left-hand side and the right-hand side are `safe' (for > >> example "a, b = b, a" swaps two variables), overlaps within the > >> collection of assigned-to variables are not safe! For instance, the > >> following program prints "[0, 2]": > > >> x = [0, 1] > >> i = 0 > >> i, x[i] = 1, 2 > >> print x > > >> Lorenzo Gatti > > > Thank you for the explanation. I guess my question can be simplified as: > > > First step: a, b = 0, 1 > > No problem here as a and b are assigned values. > > > Second step: a, b = b, a + b > > > Now my question is does b become a + b after a becomes 1 or while a > > stays at 0? > > > As the assignment occurs simultaneously I suppose the answer is while a > > stays at 0. > > Read the previous response carefully and you'll answer your question. The ? > right hand side is EVALUATED in full before values are assignated to the ? > left hand side. Evaluating b, a+b results in 1, 1. The, those values are ? > assigned to a, b. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - Another way to think of it is: a, b= b, a+b ---> X= b, a+b a, b= X where X is a pair (2-tuple, two-element tuple, ordered pair, &c.) From gabriel.rossetti at mydeskfriend.com Thu Mar 27 04:40:30 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Thu, 27 Mar 2008 09:40:30 +0100 Subject: Partial Function Application and implicit self problem In-Reply-To: <65144bF2dp2abU1@mid.uni-berlin.de> References: <65144bF2dp2abU1@mid.uni-berlin.de> Message-ID: <47EB5D7E.7080109@mydeskfriend.com> Diez B. Roggisch wrote: > Gabriel Rossetti schrieb: > >> Hello, >> >> I am using Partial Function Application in a class and I've come up with >> a problem, when the method is called it tries to pass "self" to the >> curried/partial function, but this should be the first argument in >> reality, but since the function is curried, then the self gets passed as >> the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that since >> self is not available there. Does anyone have any ideas? >> > > Use a bound-method instead. That has the self already bound to it. Like > this: > > > class Foo: > def m(self, arg): > print arg > > f = Foo() > partial(f.m, 10) > > > Diez > Ok, thanks, I moved the partial defs to __init__() and now it seams to work (I still have a but elsewhere, but this part no longer gives an error : def __init__(): self.registerServiceAtomic = partial(self.__registerService, True) self.registerServiceNonAtomic = partial(self.__registerService, False) def __registerService(self, atomic, service): def reg(service): # registers the service ... if(atomic): # Lock the service dict and register the service, then unlock it self.__mutex.lock(reg, service) self.__mutex.unlock() else: reg(service) Thanks, Gabriel From hniksic at xemacs.org Sun Mar 30 17:24:56 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 30 Mar 2008 23:24:56 +0200 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <656vhnF2e9ao7U1@mid.uni-berlin.de> <8763v4otts.fsf@mulj.homelinux.net> Message-ID: <87ve33oqfr.fsf@mulj.homelinux.net> Hrvoje Niksic writes: > I believe you stil misunderstand. The select module doesn't provide > an inteface to aio(3). It provides an interface to select() and > poll() system calls, which don't provide asynchronous access to > regular files. It occurred to me that I didn't provide an example of what I mean by select not providing asynchronous access to regular files. Using this code: >>> import os, select >>> fd = os.open('/mnt/custom/x.jpg', os.O_RDONLY) >>> fd 3 # /mnt/custom is an SMB or NFS mount. At this point, kill -STOP the # SMB server. >>> select.select([fd], [], [], 10) # test whether fd is readable ([3], [], []) # exits immediately, assume >>> os.read(3, 1024) ... hangs until smb server continues ... The thing is, select() *always* returns immediately on regular files, even if they are in fact not readable or writable. In this case, select() claimed the file descriptor to be readable when in fact it wasn't. The same is the case with poll, but not with aio. In most cases this isn't a problem, but it does mean that an application that reads from a network-share-located file in a select/poll-driven event loop will stall until the file server responds. Threads, on the other hand, don't have this problem. A program that reads the file in a separate thread will not block even if the file is on a temporarily non-responding NFS server. From gagsl-py2 at yahoo.com.ar Fri Mar 28 11:14:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 12:14:30 -0300 Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 11:51:10 -0300, escribi?: > I have an extension module that gets initialized multiple > times because I am using threads. And do you want thread local variables? > How can this module access global state (not per-thread state) ? > It needs to create a singleton. C global variables are global, not per-thread. -- Gabriel Genellina From thudfoo at opensuse.us Sun Mar 16 23:37:45 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Sun, 16 Mar 2008 19:37:45 -0800 Subject: Code to send RSS news by Sendmail In-Reply-To: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> References: <966fc6e8-4880-4755-bb59-c061925dafaa@e23g2000prf.googlegroups.com> Message-ID: <3d881a310803162037i14913a78p2bb5b971034211a6@mail.gmail.com> On 3/15/08, Ulysse wrote: > Hello, > > I'm searching a code which allow you to parse each item in the RSS > feed, get the news page of each item, convert it to text and send it > by mail. > > Do you know if it exists ? > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > Feed parser: http://feedparser.org/ From gandalf at shopzeus.com Thu Mar 20 17:20:46 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 20 Mar 2008 22:20:46 +0100 Subject: eval and unicode In-Reply-To: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <47E2D52E.6080007@shopzeus.com> >> I tried to use eval with/without unicode strings and it worked. Example: >> >> >>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? >> ?????? ????????? ???????"' ) >> True >> > When you feed your unicode data into eval(), it doesn't have any > encoding or decoding work to do. > Yes, but what about eval( 'u' + '"????????? ????????? ???????"' ) The passed expression is not unicode. It is a "normal" string. A sequence of bytes. It will be evaluated by eval, and eval should know how to decode the byte sequence. Same way as the interpreter need to know the encoding of the file when it sees the u"????????? ????????? ???????" byte sequence in a python source file - before creating the unicode instance, it needs to be decoded (or not, depending on the encoding of the source). String passed to eval IS python source, and it SHOULD have an encoding specified (well, unless it is already a unicode string, in that case this magic is not needed). Consider this: exec(""" import codecs s = u'?' codecs.open("test.txt","w+",encoding="UTF8").write(s) """) Facts: - source passed to exec is a normal string, not unicode - the variable "s", created inside the exec() call will be a unicode string. However, it may be Û or something else, depending on the source encoding. E.g. ASCII encoding it is invalid and exec() should raise a SyntaxError like: SyntaxError: Non-ASCII character '\xc5' in file c:\temp\aaa\test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details Well at least this is what I think. If I'm not right then please explain why. Thanks Laszlo From gagsl-py2 at yahoo.com.ar Thu Mar 6 16:32:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 19:32:35 -0200 Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> <13su7fhdj3rdk70@corp.supernews.com> <1da96373-d64a-40c0-a840-f1d9df3e9106@p73g2000hsd.googlegroups.com> <976c9ca2-3241-4197-813a-6d2a82ddc8b6@z17g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 14:40:47 -0200, escribi?: > On Mar 6, 12:17?am, "Daniel Fetchinson" > wrote: >> >> > What does exec( open( 'modA.py' ).read() ) do? >> > > A more appropriate formulation of the 'question behind the words' > would have been, 'are there any weird corner cases in which it doesn't > import modA? I recognize it doesn't on .pyc and .pyd files, but you > could say exec( open( 'modA.py' ).read() ) ==> import modA, even if > import modA =!=> exec( open( 'modA.py' ).read() ) all the time. Then write the question that way. Working crystall balls are hard to find nowadays... They're different; no module object is created by the exec statement. When the import machinery determines that certain module isn't already loaded, and that the .py version has to be used, it does something like this: newmodule = sys.modules[modulename] = ModuleType(modulename) # constructor sets __name__ and a null __doc__ newmodule.__builtins__ = current builtins newmodule.__file__ = filename code = read from filename and compile it exec code in newmodule.__dict__ > However, a way of asking that's more direct would have been, "Wait... > can't you create multiple module instances like that?", but since > we've already seen successful loadings of at least the builtins, > that's been treated. There are ways to create many instances of the same module, but not using a plain import statement, or using the API in the intended way. > Maybe you even hear the right thing if I say, > "Does exec( open( 'modA.py' ).read() ) do the things of import modA?" Only in part, as you can see above. > Yes, I can read the docs, but no, I can't check every possible > combination of modules. > The idea behind a singleton is to ensure something. You want non- > primary instances impossible to create. However, if (wording got > tangled here) for singleton A, if class B does the same thing, just > has different allocations-- it's own-- then A is still a singleton. > The writer of B hasn't defeated or contradicted the letter or spirit > of A. > > OP's question might have come from a variety of perspectives. In some > ways yes, in others no. That is, if you try to reinstantiate modA, > you get the same instance. But if you try really hard, you get a new > one. Are you looking for an extension to import modA that won't > return an instance that is old? > > So far, I know this: modules and classes are both namespaces. Are > those singletons? Strictly speaking, neither classes nor modules are singletons; classes are instances of type, and modules are instances of their type, and there are many instances of each. We can consider "qualified singletons", where we want to have a single instance of a class given certain attributes. In that sense, modules are "named" singletons; Python tries to ensure that, given a module name, the module object returned is always the same one - even if you spell the name in different ways. The import statement, the __import__ builtin, the imp module, the PyImport_AddModule C function, all of them try to ensure that. Of course there are ways to shoot yourself in the foot -by example, creating a new module "in the fly" with PyModule_New- On the contrary, classes have no such restrictions. Of course, for classes defined at the global level in a module, you can't have two of them with the same name, but that's just because the module namespace can't hold two values for a single name. But you can create classes dinamically, or define them inside a function, or... lots of ways of creating many instances of the "same" class, and Python won't enforce them to be always the same object. So, I'd say that modules are named singletons, and classes aren't singletons at all. -- Gabriel Genellina From shakefu at gmail.com Fri Mar 7 22:23:46 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 19:23:46 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <8250e2ce-769f-4dc9-8245-112c01f1fc97@p73g2000hsd.googlegroups.com> I figured I might as well share the code I ended up using, in case anyone else wants an easy way to get strings to, for instance, SQL- storable datetimes. jake at house:~$ cat test.py #!/usr/bin/python from datetime import datetime import subprocess def parsedate( date ): p = subprocess.Popen(['date','+%s.%N',"--date=%s" % date],stdout=subprocess.PIPE) out = float(p.stdout.read()) return "%s" % datetime.fromtimestamp(out) jake at house:~$ python -i test.py >>> parsedate("today") '2008-03-07 21:20:31.870489' >>> parsedate("tomorrow") '2008-03-08 21:20:40.516243' >>> parsedate("next monday") '2008-03-10 00:00:00' >>> parsedate("10pm last week") '2008-02-29 22:00:00' >>> parsedate("last tuesday") '2008-03-04 00:00:00' Thanks to everyone who helped! Jacob From tjreedy at udel.edu Tue Mar 18 22:06:27 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:06:27 -0400 Subject: Get actual call signature? References: Message-ID: "Jarek Zgoda" wrote in message news:fro6j9$i44$1 at nemesis.news.neostrada.pl... | Say, I have a function defined as: | | def fun(arg_one, arg_two='x', arg_three=None): | pass | | Is there any way to get actual arguments that will be effectively used | when I call this function in various ways, like: ... | I'd like to wrap function definition with a decorator that intercepts | not only passed arguments, but also defaults that will be actually used | in execution. You essentially have to do the same thing the interpreter does to call a function, which, as has been noted, is pretty hairy. You just want to print the args instead of executing the code. From castironpi at gmail.com Wed Mar 26 18:30:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 26 Mar 2008 15:30:09 -0700 (PDT) Subject: A question on decorators References: <64vpmnF2dvlccU1@mid.uni-berlin.de> Message-ID: On Mar 26, 3:23?pm, "Diez B. Roggisch" wrote: > Tim Henderson schrieb: > > > > > > > Hello > > > I am writing an application that has a mysql back end and I have this > > idea to simplify my life when accessing the database. The idea is to > > wrap the all the functions dealing with a particular row in a > > particular in a particular table inside a class. So if you have a > > table that looks like this: > > > id ? str1 ? ? ? str2 ? ? ? ?pickled_data1 ? pickled_data2 > > 0 ? ?woeif ? ? ?aposf ? ? ? (bin) ? ? ? ? ? ? ? ? ?(bin) > > 1 ? ?ofime ? ? ?powe ? ? ? ?(bin) ? ? ? ? ? ? ? ? ?(bin) > > ... > > n ? ?oiew ? ? ? opiwe ? ? ? (bin) ? ? ? ? ? ? ? ? ?(bin) > > > you can access this table like this > > > t = Table(id) #to load a pre-entered row > > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > > when you change a an attribute of the class like this... > > t.str1 = 'new value' > > > it automatically updates the database backend. > > > I have what I just described working. However I want an easier way to > > deal with my pickled_data. Right now I am pickling dictionaries and > > list types. Now there is one problem with this, let me demonstrate > > > t.data.update({'new key':'new value'}) > > print t.data > > {... 'new key':'new value' ...} > > > which makes it appear that the database has been updated as well, but > > in fact it hasn't to update the database with this scheme you actually > > have to do this. > > > t.data.update({'new key':'new value'}) > > t.data = t.data > > > this is not ideal so I subclassed the built in dict type like this: > > > class _my_dict(dict): > > > ? ? def __init__(self, row_index_name, row_index, column_name, a=None, > > **kwargs): > > ? ? ? ? self.row_index_name = row_index_name > > ? ? ? ? self.row_index = row_index > > ? ? ? ? self.column_name = column_name > > ? ? ? ? self.write_access = True > > ? ? ? ? if (a == None): dict.__init__(self, kwargs) > > ? ? ? ? else: dict.__init__(self, a) > > > ? ? ? ? self.update_db() > > > ? ? def __delitem__(self, key): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? dict.__delitem__(self, key) > > ? ? ? ? ? ? self.update_db() > > > ? ? def __setitem__(self, key, value): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? dict.__setitem__(self, key, value) > > ? ? ? ? ? ? self.update_db() > > > ? ? def clear(self): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? dict.clear(self) > > ? ? ? ? ? ? self.update_db() > > > ? ? ... > > ? ? more methods which are simliar > > ? ? ... > > > ? ? def update_db(self): > > ? ? ? ? if self.write_access: > > ? ? ? ? ? ? con = get_dbConnection() > > ? ? ? ? ? ? cur = con.cursor() > > > ? ? ? ? ? ? table = self.experiment.TABLE > > ? ? ? ? ? ? row_index_name = self.row_index_name > > ? ? ? ? ? ? row_index = self.row_index > > ? ? ? ? ? ? column_name = self.column_name > > ? ? ? ? ? ? column_value = MySQLdb.escape_string(pickle.dumps(self)) > > > ? ? ? ? ? ? q1 = '''UPDATE %(table)s > > ? ? ? ? ? ? SET %(column_name)s = '%(column_value)s' > > ? ? ? ? ? ? WHERE %(row_index_name)s = '%(row_index)s' ?''' % locals() > > > ? ? ? ? ? ? cur.execute(q1) > > ? ? ? ? ? ? con.close() > > > Now while this works, it is a lot of work. What I want to be able to > > do is something where I write one decorator function that > > automatically updates the database for me. So let us pretend I have > > this function. > > > let: dec_update_db() be my decorator which updates the dictionary. > > > to use this function it seems I would probably still have to subclass > > dict like this: > > > class _my_dict2(dict): > > > ? ? @dec_update_db > > ? ? def __init__(self, row_index_name, row_index, column_name, a=None, > > **kwargs): > > ? ? ? ? self.row_index_name = row_index_name > > ? ? ? ? self.row_index = row_index > > ? ? ? ? self.column_name = column_name > > ? ? ? ? self.write_access = True > > ? ? ? ? if (a == None): dict.__init__(self, kwargs) > > ? ? ? ? else: dict.__init__(self, a) > > > ? ? @dec_update_db > > ? ? def __delitem__(self, key): > > ? ? ? ? dict.__delitem__(self, key) > > > ? ? @dec_update_db > > ? ? def __setitem__(self, key, value): > > ? ? ? ? dict.__setitem__(self, key, value) > > > ? ? @dec_update_db > > ? ? def clear(self): > > ? ? ? ? dict.clear(self) > > > ? ? ... and so on ... > > > this is also not ideal. because I still have to apply the decorator to > > every function which changes the dictionary. > > > What I really want is a way to have the decorator applied > > automatically every time a method in dict or a sub class is called. I > > feel like this must be possible. Has any one here done anything like > > this before? > > There are a few possibilities - one of them is using a metaclass to > apply the decorator to alle methods. > > Diez- Hide quoted text - > > - Show quoted text - I like his post. I thought that structures can be counter-primitive. I don't know why lambda doesn't work. Where's the guy that thinks everything in lambdas. I think that f*2=partial( partial( f ) ). It's not: no 'of'. I want to say that's on the internet. May I define multiplication of operators? That's just order. Pick one. Do you play Civilization? I am newsgroup.confuse over and out. Divide * conquer = cut * run.decode(). I want the * to precede the dot too. Let's yack. I want to compile Python. Did you see my new post? I like it. Do you have any time you don't want? Time sale. Diez is still mad at me. I want primitives to structure themselves so I can pick up a pen. I am volunteer primitive structuring. Your structure sucks. assert atmostphere has drags. i don't think 'and' means the right thing. 'and' is composure. So the above should be 'divide and conquer, normalize in the neighborhood of, cut and run'. I want to run laps. Are generators good for it? Can we punctuate differently Python? Try to explain to a 'stream' of particles particle what it's doing. I'm particle, who's wave. From http Tue Mar 18 17:52:25 2008 From: http (Paul Rubin) Date: 18 Mar 2008 14:52:25 -0700 Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> Message-ID: <7xfxunr97q.fsf@ruckus.brouhaha.com> sturlamolden writes: > def nonunique(lst): > slst = sorted(lst) > return list(set([s[0] for s in > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) The items are all comparable and you're willing to take them out of order? from collections import defaultdict def nonunique(lst): d = defaultdict(int) for x in lst: d[x] += 1 return [x for x,n in d.iterkeys() if n > 1] From miki.tebeka at gmail.com Thu Mar 27 14:07:41 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 11:07:41 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: <04b1789a-664f-413d-8550-84bf8aa0edeb@59g2000hsb.googlegroups.com> Hello Supheakmungkol, > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: > > running install > running build > running build_ext > building 'Stemmer' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- > prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 > -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- > i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o > In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > syslimits.h:7, > ? ? ? ? ? ? ? ? ?from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > limits.h:11, > ? ? ? ? ? ? ? ? ?from libstemmer_c/src_c/../runtime/header.h:2, > ? ? ? ? ? ? ? ? ?from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: > /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: > limits.h: No such file or directory > error: command 'gcc' failed with exit status 1 > > Did anyone experience this before? Nope, compiles out of the box for me on 7.1 (IIRC easy_install worked for it as well). > Any comment/suggestion is highly appreciated. Do you have limits.h on your system? Did you install the python2.5-dev package? HTH, -- Miki http://pythonwise.blogspot.com From paddy3118 at googlemail.com Sun Mar 2 02:09:34 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 1 Mar 2008 23:09:34 -0800 (PST) Subject: Book Recomendations References: Message-ID: On Mar 2, 12:56 am, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira Hi Ira, Get Python installed on your machine - I would suggest the latest 2.5 release then either start up idle (or pythonwin if you have that on windows), or just type python at a command line prompt to get you to pythons shell. The Python shell together with the official tutorial is a great way to learn Python. If you start to flag, then their are a few videos of pre-teen kids learning Python here: http://showmedo.com/videos/python?topic=beginner_programming If they can learn it .... ;-) Welcome to Python, have fun! - Paddy. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 05:37:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 10:37:01 +0100 Subject: A question on decorators In-Reply-To: References: Message-ID: <47eb6ab6$0$16903$426a74cc@news.free.fr> Tim Henderson a ?crit : > Hello > > I am writing an application that has a mysql back end and I have this > idea to simplify my life when accessing the database. The idea is to > wrap the all the functions dealing with a particular row in a > particular in a particular table inside a class. So if you have a > table that looks like this: > > id str1 str2 pickled_data1 pickled_data2 > 0 woeif aposf (bin) (bin) > 1 ofime powe (bin) (bin) > ... > n oiew opiwe (bin) (bin) > > you can access this table like this > > t = Table(id) #to load a pre-entered row > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > when you change a an attribute of the class like this... > t.str1 = 'new value' > > it automatically updates the database backend. Congratulation, you just reinvented ORM. Good news is that there are already quite a few such packages in Python. May I recommand SQLAlchemy ?-) > I have what I just described working. However I want an easier way to > deal with my pickled_data. Right now I am pickling dictionaries and > list types. Now there is one problem with this, Indeed, but not the one you mention. The problem is that storing serialized dicts / lists / any other non atomic data in a blob is, well, not exactly the best possible use of a *relational* database. Do yourself a favour: learn what 'relational' means, and replace your blobs with the appropriate tables in the database. (snip code) > > Now while this works, it is a lot of work. This is why it's better to use an existing package whenever possible. SQLAlchemy is here: http://www.sqlalchemy.org/ (snip mode code) From steve at holdenweb.com Mon Mar 31 13:17:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Mar 2008 13:17:42 -0400 Subject: Automatically fill in forms on line In-Reply-To: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> References: <37b964200803310950v74e36d62keb4fe67498ccba72@mail.gmail.com> Message-ID: Jackie Wang wrote: > Dear all, > > I want to automatically complete the following task: > > 1. Go to http://www.ffiec.gov/Geocode/default.aspx; > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > Highway 102"; > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > 4. Click the bottom "search"; > 5. In the opened page, extract and save the number after "Tract Code". > In the example, it will be "9659". > 6. Repeat Step 1 with a new address. > > Can Python realize these steps? Can these steps be done witout > openning and IE windows? Especially, I dont know how to write code for > step 2, 4 and 5. > Look at the mechanize library at http://wwwsearch.sourceforge.net/mechanize/ > Thank you! A pleasure. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jgardner at jonathangardner.net Thu Mar 20 18:39:20 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 20 Mar 2008 15:39:20 -0700 (PDT) Subject: eval and unicode References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> On Mar 20, 2:20?pm, Laszlo Nagy wrote: > > >> ?>>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? > >> ?????? ????????? ???????"' ) > >> True > > > When you feed your unicode data into eval(), it doesn't have any > > encoding or decoding work to do. > > Yes, but what about > > eval( 'u' + '"????????? ????????? ???????"' ) > Let's take it apart, bit by bit: 'u' - A byte string with one byte, which is 117 '"????????? ????????? ???????"' - A byte string starting with " (34), but then continuing in an unspecified byte sequence. I don't know what encoding your terminal/file/whatnot is written in. Assuming it is in UTF-8 and not UTF-16, then it would be the UTF-8 representation of the unicode code points that follow. Before you are passing it to eval, you are concatenating them. So now you have a byte string that starts with u, then ", then something beyond 128. Now, when you are calling eval, you are passing in that byte string. This byte string, it is important to emphasize, is not text. It is text encoded in some format. Here is what my interpreter does (in a UTF-8 console): >>> u"????????? ????????? ???????" u'\u5fb9\u5e95\u3057\u305f\u30b3\u30b9\u30c8\u524a\u6e1b \xc1\xcd \u0170\u0150\xdc\xd6\xda\xd3\xc9 \u0442\u0440\u0438\u0440\u043e \u0432\u0430' The first item in the sequence is \u5fb9 -- a unicode code point. It is NOT a byte. >>> eval( '"????????? ????????? ???????"' ) '\xe5\xbe\xb9\xe5\xba\x95\xe3\x81\x97\xe3\x81\x9f \xe3\x82\xb3\xe3\x82\xb9\xe3\x83\x88\xe5\x89\x8a\xe6\xb8\x9b \xc3\x81\xc3\x8d\xc5\xb0\xc5\x90\xc3\x9c\xc3\x96\xc3\x9a \xc3\x93\xc3\x89 \xd1\x82\xd1\x80\xd0\xb8\xd1\x80\xd0\xbe \xd0\xb2\xd0\xb0' The first item in the sequence is \xe5. This IS a byte. This is NOT a unicode point. It doesn't represent anything except what you want it to represent. >>> eval( 'u"????????? ????????? ???????"' ) u'\xe5\xbe\xb9\xe5\xba\x95\xe3\x81\x97\xe3\x81\x9f \xe3\x82\xb3\xe3\x82\xb9\xe3\x83\x88\xe5\x89\x8a\xe6\xb8\x9b \xc3\x81\xc3\x8d\xc5\xb0\xc5\x90\xc3\x9c\xc3\x96\xc3\x9a \xc3\x93\xc3\x89 \xd1\x82\xd1\x80\xd0\xb8\xd1\x80\xd0\xbe \xd0\xb2\xd0\xb0' The first item in the sequence is \xe5. This is NOT a byte. This is a unicode point-- LATIN SMALL LETTER A WITH RING ABOVE. >>> eval( u'u"????????? ????????? ???????"' ) u'\u5fb9\u5e95\u3057\u305f\u30b3\u30b9\u30c8\u524a\u6e1b \xc1\xcd \u0170\u0150\xdc\xd6\xda\xd3\xc9 \u0442\u0440\u0438\u0440\u043e \u0432\u0430' The first item in the sequence is \u5fb9, which is a unicode point. In the Python program file proper, if you have your encoding setup properly, the expression u"????????? ????????? ???????" is a perfectly valid expression. What happens is the Python interpreter reads in that string of bytes between the quotes, interprets them to unicode based on the encoding you already specified, and creates a unicode object to represent that. eval doesn't muck with encodings. I'll try to address your points below in the context of what I just wrote. > The passed expression is not unicode. It is a "normal" string. A > sequence of bytes. Yes. > It will be evaluated by eval, and eval should know > how to decode the byte sequence. You think eval is smarter than it is. > Same way as the interpreter need to > know the encoding of the file when it sees the u"????????? > ????????? ???????" byte sequence in a python source file - before > creating the unicode instance, it needs to be decoded (or not, depending > on the encoding of the source). > Precisely. And it is. Before it is passed to eval/exec/whatever. > String passed to eval IS python source, and it SHOULD have an encoding > specified (well, unless it is already a unicode string, in that case > this magic is not needed). > If it had an encoding specified, YOU should have decoded it and passed in the unicode string. > Consider this: > > exec(""" > import codecs > s = u'?' > codecs.open("test.txt","w+",encoding="UTF8").write(s) > """) > > Facts: > > - source passed to exec is a normal string, not unicode > - the variable "s", created inside the exec() call will be a unicode > string. However, it may be Û or something else, depending on the > source encoding. E.g. ASCII encoding it is invalid and exec() should > raise a SyntaxError like: > > SyntaxError: Non-ASCII character '\xc5' in file c:\temp\aaa\test.py on > line 1, but no encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor details > > Well at least this is what I think. If I'm not right then please explain > why. > If you want to know what happens, you have to try it. Here's what happens (again, in my UTF-8 terminal): >>> exec(""" ... import codecs ... s = u'?' ... codecs.open("test.txt","w+",encoding="UTF8").write(s) ... """) >>> s u'\xc5\xb0' >>> print s ?? >>> file('test.txt').read() '\xc3\x85\xc2\xb0' >>> print file('test.txt').read() ?? Note that s is a unicode string with 2 unicode code points. Note that the file has 4 bytes--since it is that 2-code sequence encoded in UTF-8, and both codes are not ASCII. Your problem is, I think, that you think the magic of decoding source code from the byte sequence into unicode happens in exec or eval. It doesn't. It happens in between reading the file and passing the contents of the file to exec or eval. From fakeaddress at nowhere.org Fri Mar 14 03:42:05 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 07:42:05 GMT Subject: Socket Performance In-Reply-To: <3c1f0d7b-4f1d-4ec6-ba6f-ba4fa2833647@b1g2000hsg.googlegroups.com> References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> <13tk779gboqcgb9@corp.supernews.com> <3c1f0d7b-4f1d-4ec6-ba6f-ba4fa2833647@b1g2000hsg.googlegroups.com> Message-ID: castironpi at gmail.com wrote: [Dennis Lee Bieber had written:] >> Or create a protocol where the first 16 bits (in network byte order) >> contain a length value for the subsequent data, and use a receive >> process that consists of: >> >> leng = ntoh(socket.recv(2)) >> data = socket.receive(leng) >> >> (the send can combine the length with the data into a single packet) > > Are two 'sends' guaranteed to arrive as at least two 'receives'? No. Nor are they guaranteed to arrive as at least most two. > Send-3: xxx > Send-3: yyy > Receive-6: xxxyyy Can happen, though I think the problem with Dennis's code is the other way. The recv in leng = ntoh(socket.recv(2)) might return one byte of data, not two. The latter recv is similar. -- --Bryan From castironpi at gmail.com Sat Mar 22 03:25:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 22 Mar 2008 00:25:57 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> <5b074f3a-a9d6-453d-8457-618d31f896c4@m44g2000hsc.googlegroups.com> <8746e9bf-ce87-4eef-862d-4dd568131ddd@c19g2000prf.googlegroups.com> Message-ID: <8d28ca49-482f-4480-a683-0ba7e463ae44@n77g2000hse.googlegroups.com> On Mar 21, 3:39?pm, John Machin wrote: > On Mar 22, 1:11 am, castiro... at gmail.com wrote: > > A collision sequence is not so rare. > > > >>> [ hash( 2**i ) for i in range( 0, 256, 32 ) ] > > > [1, 1, 1, 1, 1, 1, 1, 1] > > Bryan did qualify his remarks: "If we exclude the case where an > adversary is choosing the keys, ..." Some adversary. What, you mean, my boss or my customers? From gagsl-py2 at yahoo.com.ar Sun Mar 30 00:27:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 01:27:18 -0300 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> <13uu1o25912ulb0@corp.supernews.com> Message-ID: En Sun, 30 Mar 2008 00:20:34 -0300, Steven D'Aprano escribi?: > On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote: > >> def main(): >> global func >> func = factory() >> return timeit.Timer('func()', 'from __main__ import func').timeit() > > Alas, this does not work, because all the Timer instances share the same > state. Second try: # timeanyfunc.py from timeit import Timer from itertools import count _counter = count() def timeanyfunc(fn, *args, **kw): def wrapper(fn=fn, args=args, kw=kw): return fn(*args, **kw) wrappername = 'wrapper%d' % _counter.next() globals()[wrappername] = wrapper return Timer("%s()" % wrappername, "from %s import %s" % (__name__, wrappername)) Horrible, I know. Those wrapper1,wrapper2,wrapper3... keep growing with each call. But it's the only way I could find, at least without changing the code template used by timeit. py> from timeanyfunc import timeanyfunc py> py> def functionA(arg): ... print "Function A",arg ... py> def functionB(arg): ... print "Function B",arg ... py> def test_timer(func1, func2): ... T1 = timeanyfunc(func1, "arg1") ... T2 = timeanyfunc(func2, "arg2") ... print "Calling %s" % func1.__name__ ... T1.repeat(3, 1) ... print "Calling %s" % func2.__name__ ... T2.repeat(3, 1) ... py> test_timer(functionA, functionB) Calling functionA Function A arg1 Function A arg1 Function A arg1 Calling functionB Function B arg2 Function B arg2 Function B arg2 -- Gabriel Genellina From tjreedy at udel.edu Sun Mar 9 19:23:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Mar 2008 19:23:25 -0400 Subject: 1.5.2 and functools or similar References: <47d45625$0$15876$edfadb0f@dtext01.news.tele.dk> Message-ID: "Troels Thomsen" <"nej tak..."@bag.python.org> wrote in message news:47d45625$0$15876$edfadb0f at dtext01.news.tele.dk... | def updateTimers() | for timerItm in timerTable: | ... | .... | .... | timerItm.func(*timerItm.parameters) | | Works well on python 2.5 but not on 1.5.2 (?) apply(timerItm.func, timerItm.parameters) # see http://docs.python.org/lib/non-essential-built-in-funcs.html apply disappears in 3.0 tjr From kla at us.de Fri Mar 21 11:53:35 2008 From: kla at us.de (klaus) Date: 21 Mar 2008 15:53:35 GMT Subject: beginners question about return value of re.split References: <47e3d1e9$0$17341$e4fe514c@dreader19.news.xs4all.nl> Message-ID: <47e3d9ff$0$17341$e4fe514c@dreader19.news.xs4all.nl> On Fri, 21 Mar 2008 10:31:20 -0500, Tim Chase wrote: <..........> Ok thank you ! I think I got a bit lost in all the possibilities python has to offer. But your answers did the trick. Thank you all again for responding and elaborating. Cheers, KL. From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 09:13:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 13:13:48 -0000 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> Message-ID: <13t7okcjo91gaa2@corp.supernews.com> On Sun, 09 Mar 2008 05:20:41 -0700, Guillermo wrote: >>A protocol is just an interface that an object agrees to implement. In >>your case, you would state that every object stored in your special dict >>must implement the to_tagged_value method with certain agreeable >>semantics. > > Hm... I've searched about the implementation of protocols and now (I > believe) I know how to implement the iterable protocol, for instance, > but have no clue about how to define my own... I'm surely not thinking > the right way, but I don't seem to be able to wrap my head around the > implementation details of "custom" protocols... Is it just a matter of > extending the different object classes (dict, list, tuple...)? Where do > you put the interface/protocol code? :-? A protocol is a convention that you insist other objects must follow, not code. To implement that convention, naturally you need to write code, but the convention makes the protocol, not the code. Some examples: To be considered a writable file, your object must include a write() method and a close() method. It doesn't matter what those methods do exactly, so long as they behave reasonably. For instance, the close() method might do nothing, and the write() method might send an SMS. To be a random-access writable file, it must also include a seek() method. To be a sequence, your object must obey the sequence protocol, which says it has a __getitem__ method which takes integer arguments starting at 0 and increasing, until it raises IndexError. You don't have to write any code to create a protocol, you just have to tell people what it is. Here's my parrot protocol: To be a parrot, your object must have a method speak() which takes an integer argument and returns the case-insensitive string "spam" repeated that many times. I'm done. I have a protocol. But if I want to actually use it, then I need an object that obeys it, and if I can't wait for somebody else to write it, I need to write one myself. So here it is: class Viking(object): def __init__(self, case='upper'): if case == 'upper': self.case = str.upper else: self.case = str.lower def speak(self, n): return self.case("spam"*n) And now Viking instances are also parrots, or rather, they obey the parrot protocol: >>> v = Viking() >>> v.speak(3) 'SPAMSPAMSPAM' I hope this helps. -- Steven From michael.wieher at gmail.com Thu Mar 20 12:34:54 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 20 Mar 2008 11:34:54 -0500 Subject: if __name__ == '__main__': In-Reply-To: <8c7f10c60803200921p3c4a989ajf7797688072468e@mail.gmail.com> References: <8c7f10c60803200921p3c4a989ajf7797688072468e@mail.gmail.com> Message-ID: Well, consider this: you have a file named .py, built like this: ~~~~~~~~~~~~~~~~~~~~~ #!/usr/bin/python def : .... return if __name__=="__main__": print "Unit test" else: pass #module imported by another module/script ~~~~~~~~~~~~~~~~~~~~~~ If you type, on command line, >python ./.py you will see "Unit test" printed to the screen. if, however you are in another python file and type "import " the code will, instead, "pass" and nothing will occur. I hope this helps =) 2008/3/20, Simon Brunning : > > On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde wrote: > > Hi, > > I am new to the python and not getting meaning of following line, > > > > if __name__ == '__main__': > > main() > > < > http://www.python.org/doc/faq/programming/#how-do-i-find-the-current-module-name > > > > -- > Cheers, > Simon B. > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ > GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Mar 10 04:43:33 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Mar 2008 09:43:33 +0100 Subject: Adjust a canvas as the window is resized References: <63ga4fF27edonU1@mid.individual.net> Message-ID: K Viltersten wrote: > Do i need to set a callback to a canvas > in order to "listen" to the root window > being resized in order to make it adjust > its contents? > > If so, how? If not, how do i make the > canvas draw a line from one corner to > an other? import Tkinter as tk root = tk.Tk() canvas = tk.Canvas(root) canvas.pack(expand=True, fill=tk.BOTH) line = canvas.create_line(0, 0, 0, 0) def resize(event): canvas.coords(line, 0, 0, event.width, event.height) canvas.bind("", resize) root.mainloop() Peter From stef.mientki at gmail.com Fri Mar 28 14:02:27 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 19:02:27 +0100 Subject: class or inherited list ? In-Reply-To: <47ED195B.4070902@gmail.com> References: <47ED0BA1.9020103@gmail.com> <47ED195B.4070902@gmail.com> Message-ID: <47ED32B3.8060604@gmail.com> >>> >>> class super_list(list): >>> pass >>> >>> def kwadraat ( value ) : >>> return value * value >>> >>> x={} >>> x['frequency']=33 >>> x['functie']=kwadraat >>> print x['functie'](2) >>> >>> y = super_list() >>> y.frequency = 33 >>> y.functie = kwadraat >>> print y.functie(3) >>> >> >> You don't use y as a list at all - you might as well inherit from >> object. > Good point, didn't notice that. Sorry, not a good point, by deriving from a list, I get all the list methods for nothing. cheers, Stef Mientki From MartinRinehart at gmail.com Wed Mar 5 11:40:15 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 08:40:15 -0800 (PST) Subject: Why """, not '''? References: Message-ID: <23757d81-402e-4a99-b927-379f3e953b4c@i7g2000prf.googlegroups.com> D'Arcy J.M. Cain wrote: > Where did you see that? The only place I saw it was the style guide > and it was only talking about docstrings. PEP 8 and 257, and you're right, they are both about docstrings. Also, I'd never seen an example of the triple apostrophe form until I dove into the formal syntax specification. From donn at u.washington.edu Fri Mar 28 14:30:05 2008 From: donn at u.washington.edu (Donn Cave) Date: Fri, 28 Mar 2008 11:30:05 -0700 Subject: Summary of threading for experienced non-Python programmers? References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> Message-ID: In article <654ng1F2cvh8aU1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > > systems. (In theory, file input/output should also be available as > > asynchronous code, but async IO is low-level and not available in > > Python.) While threads shouldn't be considered a replacement for > > I suggest you tell that the twisted-guys. And the ones from the built-in > asyncore-module. > > They will be surprised to hear that their years worth of working code > will evaporate in a rosa cloud. > > Diez I appreciate the droll sense of humor, but do you mean to assert that asyncore.py supports asynchronous disk file I/O? What that means to me is, you queue a disk read, and there's an event flag or something that you can wait for before you come back to find the data in your buffer. (That's how I remember it from the old days, when it mattered a little, though not enough that I ever remember actually doing it, and 20 years later I guess the incentive is even less.) I see MacOS supports an F_RDADVISE that might give you a head start on reading into the system buffer, but that's 3rd rate asynchrony because there's no way to know when the data is ready, and 3rd rate I/O because afterwards you still have the copying to do. I don't see even this much in asyncore.py, but I just gave it a glance. thanks, Donn Cave, donn at u.washington.edu From PurpleServerMonkey at gmail.com Thu Mar 20 21:30:18 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Thu, 20 Mar 2008 18:30:18 -0700 (PDT) Subject: Distributing Python Apps on Linux\BSD Message-ID: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> Working on a rather large open source python application that I want to release for Linux and BSD and was wondering what methods others are using to distribute large and complex applications. Setuptools and friends seem to be focused on distributing modules, I'm at the other end of the scale where I want to distribute an entire application so that an Administrator can run a single install and have a fully operational product. A key requirement is that I want the application to fit in with what and admin would expect an application to look like at the system level i.e site-packages like structures aren't suitable. So far I've thought of using a configure script and make which would call some custom python installer script to do the actual install. It fits in nicely with what I want to achieve but are there any better options out there, how are others doing the same thing? From roygeorget at gmail.com Mon Mar 10 00:36:34 2008 From: roygeorget at gmail.com (royG) Date: Sun, 9 Mar 2008 21:36:34 -0700 (PDT) Subject: dot() and tensordot() Message-ID: hi can numpy.dot() be used instead of tensordot()? is there any performance difference? I am talking about operation btw numpy arrays of dimensions 50 X 20,000 where elements are of float type. i tried posting in numpy group where i had gotten membership..but when i post a msg it says posting by non member and so doesn't show up :-( royG From clodoaldo.pinto at gmail.com Fri Mar 28 13:03:03 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Fri, 28 Mar 2008 10:03:03 -0700 (PDT) Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> <37d6b141-5ba0-4178-b45a-512e59433803@s12g2000prg.googlegroups.com> Message-ID: On Mar 28, 1:56 pm, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 13:22:06 -0300, Clodoaldo > escribi?: > > > > > On Mar 28, 12:09 pm, "Gabriel Genellina" wrote: > >> En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo > >> escribi?: > > >> > What i need to know is where can an equal char appear in a > >> > urlsafe_b64encoded string?: > > >> > a)only at end; > >> > b)both at the end and at the begginig; > >> > c)anywhere in the string; > > >> > A sure answer will make my regexp safer. > > >> Only at the end. The encoded string has 4*n chars when the input string > >> has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has > >> 4*(n+1) chars right padded with 2 or 1 "=" chars. > >> If your input has 3n chars, the output won't have any "=" > > > Thanks. But I'm not sure i get it. What is n? > > (Any nonnegative integer...) > I mean: For base64 encoding, the length of the output depends solely of > the length of the input. If the input string length is a multiple of 3, > the output length is a multiple of 4, with no "=". If the input length is > one more than a multiple of 3, the output has two "==" at the end. If the > input length is two more than a multiple of 3, the output has only one "=" > at the end. In all cases, the output length is a multiple of 4. > > [base64 uses 64=2**6 characters so it encodes 6 bits per character; to > encode 3 bytes=3*8=24 bits one requires 24/6=4 characters] > > > A md5 digest will always be 16 bytes length. So if i understand it > > correctly (not sure) the output will always be 22 chars plus two > > trailing equal chars. Right? > > Exactly. Thank you. That was great support! From michael.wieher at gmail.com Sun Mar 23 21:03:32 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 23 Mar 2008 20:03:32 -0500 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: I changed the last few lines to read: 37 kalam.howMany() 38 c = Person('Catherine', 'F') 39 #cathy.sayHi() 40 #cathy.howMany() 41 #swaroop.sayHi() 42 #swaroop.howMany() 43 And I don't get the error. However if I change line 38 to read ca = Person('Catherine','F') It again initializes and then the error occurs. It isn't random, I can run the code 10, 20 times with variable name 'c' and no error, and then again with variable name 'ca' or 'cathy' and the error does occur. I haven't much experience with __del__() functions but you're right -- this is strange as all hell. And I can't even imagine why it would happen at all. Obviously it is attempting to access the Person.population() variable. Which is a logic error, (I think) since well, we have 3 instances of the class being created and then the unbound variable (ie: a variable not associated with any instantiation of the class) being incremented and decremented. Logically, I think it shouldn't work at all, but somehow this unbound variable is working but in a very buggy way. Or am I wrong? Are unbound class-variables supposed to be used to coordinate between multiple instantiations of that class? 2008/3/23, George Sakkis : > > On Mar 23, 8:01 pm, QS wrote: > > Hi to all! > > I am new to python, and I encountered a weird problem. > > > > Here is my code > > > > ##########>8#################### > > #!/usr/bin/python > > # Filename: objvar.py > > class Person: > > '''Represents a person.''' > > > > population = 0 > > #sex = 'F' > > #age = 22 > > # It is vague here: is this variable going to be a class, or > > object, variable > > > > def __init__(self, name, sex): > > '''Initializes the person's data.''' > > self.name = name > > self.sex = sex > > print '(Initializing %s )' % self.name > > # When this person is created, he/she > > # adds to the population > > Person.population += 1 > > > > def __del__(self): > > '''I am dying.''' > > > > print '%s says bye.' % self.name > > Person.population -= 1 > > if Person.population == 0: > > print 'I am the last one.' > > else: > > print 'There are still %d people left.' % > > Person.population > > > > def sayHi(self): > > '''Greeting by the person. > > > > Really, that's all it does.''' > > > > self.age = 25 > > print 'Hi, my name is %s, and I am %s, and I am age %d ' % > > (self.name, self.sex, self.age) > > > > def howMany(self): > > '''Prints the current population.''' > > if Person.population == 1: > > print 'I am the only person here.' > > else: > > print 'We have %d persons here.' % Person.population > > > > swaroop = Person('Swaroop', 'M') > > swaroop.sayHi() > > swaroop.howMany() > > kalam = Person('Abdul Kalam', 'M') > > kalam.sayHi() > > kalam.howMany() > > cathy = Person('Catherine', 'F') > > cathy.sayHi() > > cathy.howMany() > > swaroop.sayHi() > > swaroop.howMany() > > > > ############# 8< ######################### > > > > When I run this script, I got the following exception: > > Exception exceptions.AttributeError: "'NoneType' object has no > > attribute 'population'" in > <__main__.Person instance at 0xb7d8ac6c>> ignored > > > > To to newcomer like me, this message doesn't make much sense. What > > seems weird to me is that, if I change the variable cathy to something > > else, like cath, or even cat, then the script will finish gracefully. > > Why "cathy" is not liked?!! > > > > Some of you may have recognized that the code is derived from a sample > > code in Swaroop's "A byte of python". > > > > My python is of version 2.5.1, on Ubuntu. > > > That's really weird... it's reproducible on Windows too. It doesn't > make any sense why the name of the variable would make a difference. > My guess is you hit some kind of obscure bug. > > > George > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed Mar 26 12:33:43 2008 From: nagle at animats.com (John Nagle) Date: Wed, 26 Mar 2008 09:33:43 -0700 Subject: Some notes on a high-performance Python application. Message-ID: <47ea78a5$0$36353$742ec2ed@news.sonic.net> I run SiteTruth (sitetruth.com), which rates web sites for legitimacy, based on what information it can find out about the business behind the web site. I'm going to describe here how the machinery behind this is organized, because I had to solve some problems in Python that I haven't seen solved before. The site is intended mainly to support AJAX applications which query the site for every ad they see. You can download the AdRater client ("http://www.sitetruth.com/downloads/adrater.html") and use the site, if you like. It's an extension for Firefox, written in Javascript. For every web page you visit, it looks for URLs that link to ad sites, and queries the server for a rating, then puts up icons on top of each ad indicating the rating of the advertiser. The client makes the query by sending a URL to an .fcgi program in Python, and gets XML back. So that's the interface. At the server end, there's an Linux/Apache/mod_fcgi/Python server. Requests come in via FCGI, and are assigned to an FCGI server process by Apache. The initial processing is straightforward; there's a MySQL database and a table of domains and ratings. If the site is known, a rating is returned immediately. This is all standard FCGI. If the domain hasn't been rated yet, things get interesting. The server returns an XML reply with a status code that tells the client to display a "busy" icon and retry in five seconds. Then the process of rating a site has to be started. This takes more resources and needs from 15 seconds to a minute, as pages from the site are read and processed. So we don't want to do rating inside the FCGI processes. We want FCGI processing to remain fast even during periods of heavy rating load. And we may need to spread the processing over multiple computers. So the FCGI program puts a rating request into the database, in a MySQL table of type ENGINE=MEMORY. This is just an in-memory table, something that MySQL supports but isn't used much. Each rating server has a "rating scheduler" process, which repeatedly reads from that table, looking for work to do. When it finds work, it marks the task as "in process". The rating scheduler launches multiple subprocesses to do ratings, all of which run at a lower priority than the rest of the system. The rating scheduler communicates with its subprocesses via pipes and Pickle. Launching a new subprocess for each rating is too slow; it adds several seconds as CPython loads code and starts up. So the subprocesses are reusable, like FCGI tasks. Every 100 uses or so, we terminate each subprocess and start another one, in case of memory leaks. (There seems to be a leak we can't find in M2Crypto. Guido couldn't find it either when he used M2Crypto, as he wrote in his blog.) Each rating process only rates one site at a time, but is multithreaded so it can read multiple pages from the site, and other remote data sources like BBBonline, at one time. This allows us to get a rating within 15 seconds or so. When the site is rated, the database is updated, and the next request back at the FCGI program level will return the rating. We won't have to look at that domain for another month. The system components can run on multiple machines. One can add rating capacity by adding another rating server and pointing it at the same database. FCGI capacity can be added by adding more FCGI servers and a load balancer. Adding database capacity is harder, because that means going to MySQL replication, which creates coordination problems we haven't dealt with yet. Also, since multiple processes are running on each CPU, multicore CPUs help. Using MySQL as a queueing engine across multiple servers is unusual, but it works well. It has the nice feature that the queue ordering can be anything you can write in a SELECT statement. So we put "fair queueing" in the rating scheduler; multiple requests from the same IP address compete with each other, not with those from other IP addresses. So no one site can use up all the rating capacity. Another useful property of using MySQL for coordination is that we can have internal web pages that make queries and display the system and queue status. This is easy to do from the outside when the queues are in MySQL. It's tough to do that when they're inside some process. We log errors in a database table, not text files, for the same reason. In addition to specific problem logging, all programs have a final try block around the whole program that does a stack backtrace and puts that in a log entry in MySQL. All servers log to the same database. Looking at this architecture, it was put together from off the shelf parts, but not the parts that have big fan bases. FCGI isn't used much. The MySQL memory engine isn't used much. MySQL advisory locking (SELECT GET LOCK("lockname",timeout)) isn't used much. Pickle isn't used much over pipes. M2Crypto isn't used much. We've spent much time finding and dealing with problems in the components. Yet all this works quite well. Does anyone else architect their systems like this? John Nagle From rschroev_nospam_ml at fastmail.fm Thu Mar 13 06:46:57 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 13 Mar 2008 11:46:57 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: References: Message-ID: Hendrik van Rooyen schreef: > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above Answer 5: the output will be 'None': append() doesn't return the list, it returns None. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From watine at cines.fr Tue Mar 25 07:05:57 2008 From: watine at cines.fr (Benjamin Watine) Date: Tue, 25 Mar 2008 12:05:57 +0100 Subject: My python interpreter became mad ! Message-ID: <47E8DC95.4010009@cines.fr> Yes, my python interpreter seems to became mad ; or may be it's me ! :) I'm trying to use re module to match text with regular expression. In a first time, all works right. But since yesterday, I have a very strange behaviour : $ python2.4 Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re X-Spam-Flag: YES X-Spam-Checker-Version: SpamAssassin 3.1.7-deb (2006-10-05) on w3hosting.org X-Spam-Level: ********************** X-Spam-Status: Yes, score=22.2 required=5.0 tests=MISSING_HB_SEP, MISSING_HEADERS,MISSING_SUBJECT,RAZOR2_CF_RANGE_51_100, RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,TO_CC_NONE,UNPARSEABLE_RELAY, URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SBL,URIBL_SC_SURBL, URIBL_WS_SURBL autolearn=failed version=3.1.7-deb Traceback (most recent call last): File "", line 1, in ? File "/etc/postfix/re.py", line 19, in ? m = re.match('(Spam)', mail) AttributeError: 'module' object has no attribute 'match' >>> What's the hell ?? I'm just importing the re module. The code showed, is a previous test code, that seems to be buffered and that make an error. Each call to re module generate that error. How can I workaround ? Is there is a way to flush or restart python interpreter. Is it a bug in python ?? Thanks ! Ben From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 10:07:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 14:07:16 -0000 Subject: [OT] Modesty and apologies [Re: Re; finding euclidean distance,better code?] References: Message-ID: <13usj8k2ciks907@corp.supernews.com> On Sat, 29 Mar 2008 12:43:22 +0200, Hendrik van Rooyen wrote: > Sorry about having to dispel your illusions, but - [...] > Have you noticed that when people say "Sorry.....but...." they are not > normally sorry at all? Heh heh heh. Reminds me of a quote from the character Spike of "Buffy the Vampire Slayer": [quote] Yeah, I did a couple Slayers in my time. I don't like to brag. Who am I kidding? I love to brag! There was this one Slayer during the Boxer Rebellion, and... [end quote] -- Steven From mwilson at the-wire.com Sat Mar 1 18:41:42 2008 From: mwilson at the-wire.com (Mel) Date: Sat, 01 Mar 2008 18:41:42 -0500 Subject: sqlite3 adaptors mystery References: Message-ID: Matej Cepl wrote: [ ... ] > However, when running this program it seems converter doesn?t seem to work, > because I get: > > [matej at viklef dumpBugzilla]$ rm test.db ; python testAdaptors.py > [(u'False',), (u'True',)] > [matej at viklef dumpBugzilla]$ > > There is probably something quite obvious what I do incorrectly, but I just > don't see it. Could somebody kick me in the right direction, please? There's nothing much wrong. cur.fetchall is returning a list of all the selected rows, and each row is a tuple of fields. Each tuple is being converted for display by repr, so the strings are shown as unicode, which is what they are internally. Change the print to for (field,) in cur.fetchall(): print field and you'll see your plain-text strings. Mel. From http Sun Mar 2 12:02:38 2008 From: http (Paul Rubin) Date: 02 Mar 2008 09:02:38 -0800 Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <7483730d-4de4-4883-8021-2d607f691595@28g2000hsw.googlegroups.com> <7xk5kska5h.fsf@ruckus.brouhaha.com> Message-ID: <7xk5klnjo1.fsf@ruckus.brouhaha.com> Robert Brown writes: > Unfortunately, performance often comes at the cost of safety and > correctness. Optimized C programs can crash when pointers walk off the > end of arrays or they can yield incorrect results when integers overflow > the limits of the hardware. Yes, even unoptimized C programs can do that. C is just plain dangerous. > [SBCL Common Lisp] > Very rarely, say inside a loop, I temporarily change my default compiler > settings. Inside the lexical scope of these declarations, the compiled > code does no run-time type checking and trusts me. Here, broken Lisp > code can crash the system (just as broken C code can), but the compiled > code runs very fast. > > I trade off safety for speed, but only where necessary. It seems to me that this trade-off results from a problem with the language's expressivity. If you have a sound argument that the subscripts in your loop are actually safe, you ought to be able to express that argument to the compiler for static checking. That should result in safe code with no runtime checks needed. That said, trying to provide that level of expressivity is at the cutting edge of programming language research, and in real-world languages, for now, we have to live with some runtime checks. But in an example like (pseudocode): for i in 1..100: hack(x[i]) it should be enough to check outside the loop in constant time that 1..100 are valid subscripts for x, then generate the loop code with no check on each separate access. That is maybe not possible in C because i might be aliased to something, but in a sane language it should be possible. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Mar 30 08:48:26 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 30 Mar 2008 14:48:26 +0200 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> <87od8w7aws.fsf@physik.rwth-aachen.de> Message-ID: <659ggqF2f84eoU3@mid.individual.net> Torsten Bronger wrote: > Maybe he means "?". Haven't seen this either, nor do I think it's the same than "<>". >From afar, it looks more like "><". But this does more look like South Park style shut eyes than an operator. :) Regards, Bj?rn -- BOFH excuse #407: Route flapping at the NAP. From arnodel at googlemail.com Thu Mar 20 05:43:26 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 20 Mar 2008 02:43:26 -0700 (PDT) Subject: finding items that occur more than once in a list References: <87k5k02h8z.fsf@mulj.homelinux.net> <6ff9448b-c052-4752-bd89-b0cc55da57a6@h11g2000prf.googlegroups.com> <554ae666-99ef-440f-9579-8935cc323ae8@e23g2000prf.googlegroups.com> Message-ID: On Mar 19, 3:08?am, Bryan Olson wrote: > Arnaud Delobelle wrote: > > Ninereeds wrote: > >> Hrvoje Niksic wrote: > >>> This doesn't apply to Python, which implements dict storage as an > >>> open-addressed table and automatically (and exponentially) grows the > >>> table when the number of entries approaches 2/3 of the table size. > >>> Assuming a good hash function, filling the dict should yield amortized > >>> constant time for individual additions. > > > Isn't this average constant time rather than amortized? > > This is expected amortized constant time. Is that really the same > thing as average constant time? Hmmm... that's subtle. I am not sure what the difference between expected amortized time complexity and average time complexity is (I know that they are defined as different notions but I don't know whether they reduce to the same thing or not). Anyway both are average case complexities and AFAIK worst case time complexity of insertion / lookup in a hashtable is still O(n). > >> OK. I obviously need to look up open-addressed tables. I thought this > >> was just, in effect, implicit linked listing - ie it still needs a > >> linear search to handle collisions, it just avoids the need for > >> explicitly stored link fields. Perhaps I'm mistaken. > > The amortized doubling breaks that. > > > I don't think you are mistaken, but if I'm wrong I'd be grateful for a > > link to further details. > > Arnaud Delobelle offered a good Wikipedia link, and for more background > look up "amortized analysis. Hrvoje Niksic provided the link :). I still think two unrelated things are being compared in this thread when people say that method A (using dictionaries / sets) is O(n) and method B (sorting the list) O(nlogn). Isn't it the case that: | Worst case | Average case ---------|------------|------------- Method A | O(n^2) | O(n) Method B | O(nlogn) | O(nlogn) Which method is the best would then be determined by the distribution of the hash values of your data, and whether you want to have a guarantee the method will have a less-than-quadratic behaviour. -- Arnaud From gagsl-py2 at yahoo.com.ar Sun Mar 2 22:56:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 2 Mar 2008 19:56:55 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: On 2 mar, 17:21, castiro... at gmail.com wrote: > This worked: > > import socket > from time import time > > for i in range( 20 ): > ? ? HOST = '' > ? ? PORT = 80 #<---- > ? ? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > ? ? s.bind((HOST, PORT)) > ? ? print( 'listen' ) > ? ? s.listen(1) > ? ? conn, addr = s.accept() > ? ? print( 'connected', addr ) > ? ? print( conn.recv( 4096 ) ) #<---- > ? ? conn.send( bytes('test %f html>'%time(),'ascii') ) > ? ? conn.close() #<---- > ? ? s.close() > > ... and connect with a browser: ?http://localhost/if it's internet > exploder. Note that there is no need (nor is desirable) to close and rebind the listening socket for each connection. The loop should start with the accept call, and end at the conn.close() call (s.close() is left out of the loop). And then you get a pretty standard server that handles one connection at a time. -- Gabriel Genellina From zerty.david at gmail.com Mon Mar 31 16:50:42 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 31 Mar 2008 17:50:42 -0300 Subject: Python and Db In-Reply-To: References: <5dc598e30803311050k5e8352e4g85380fb67cce5ac2@mail.gmail.com> Message-ID: <5dc598e30803311350o79b691bfn27330a9595bbfe53@mail.gmail.com> I would like to use sqlite, But I also wanted a tutorial with the basis of the sql and etc, I never dealed with dbs before On Mon, Mar 31, 2008 at 3:42 PM, Gabriel Genellina wrote: > En Mon, 31 Mar 2008 14:50:27 -0300, David Anderson > escribi?: > > > Hi! I'm don't know almost nothing about bds, Can You suggest me an > Simple > > but efficient Bd to work with python apps? Can You suggest me any > > tutorials? > > See the Python wiki at: http://wiki.python.org/moin/DatabaseProgramming > If you stick with DBAPI 2.0 you won't have much trouble writing for one > database or another. sqlite is a good start and is included with Python > 2.5 > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From priya4u001 at gmail.com Mon Mar 3 23:26:09 2008 From: priya4u001 at gmail.com (priya4u) Date: Mon, 3 Mar 2008 20:26:09 -0800 (PST) Subject: download students tutorials,ebooks,softwares here for Free!!!! Message-ID: <5a3f53dd-59d4-48fa-a8dc-33b3e583a428@s12g2000prg.googlegroups.com> download students tutorials,ebooks,softwares here for Free!!!! Download Softwares Ebooks Students tutorials Games Ring tones Wallpapers and Lots of fun everything for FREE only at www.studentshangout.com From monica.leko at gmail.com Wed Mar 5 10:36:46 2008 From: monica.leko at gmail.com (Monica Leko) Date: Wed, 5 Mar 2008 07:36:46 -0800 (PST) Subject: Unit testing Web applications Message-ID: <558c3b4d-5b30-4394-a221-72ad8d2499e4@i12g2000prf.googlegroups.com> Hi! Does Python has some testing frameworks for testing Web applications (like Cactus and HttpUnit for Java), generating requests and checking if the response is correct? From castironpi at gmail.com Tue Mar 4 21:47:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 18:47:17 -0800 (PST) Subject: for-else References: <87r6eq82ch.fsf@benfinney.id.au> Message-ID: <6479eee7-839c-4250-ab9c-2784c890d9bc@e6g2000prf.googlegroups.com> That you could do yourself, CMIIW correct me if I'm wrong. try: ? ? for foo in iterex( bar_sequence ): > ? ? ? ? # normal iteration > ? ? ? ? spam(foo) > ? ? ? ? if funky(foo): > ? ? ? ? ? ? break ? ? except StopIterationEx, exc: > ? ? ? ? # the iterator stopped normally > ? ? ? ? eggs(exc) > ? ? else: > ? ? ? ? # the iterator exited abnormally, i.e. 'break' > ? ? ? ? sausage() > ? ? finally: > ? ? ? ? # always executed, even on 'break' > ? ? ? ? beans() Qualm, except would be needed in every for-, and in one sense doesn't obey the semantics of exceptions. The end of a finite list is not an exceptional element-- it's not one. However generator semantics don't yield finite sequences-- and finity is an exception, but for-loops don't use infinite ones. Makes it sound (*subj've) like I'm hacking by using for-loops..... or, like sequencetype.__iter__ is malformed. From http Wed Mar 26 03:21:51 2008 From: http (Paul Rubin) Date: 26 Mar 2008 00:21:51 -0700 Subject: Beta testers needed for a high performance Python application server References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> <47e9f77b$0$36357$742ec2ed@news.sonic.net> Message-ID: <7xd4pi2bn4.fsf@ruckus.brouhaha.com> John Nagle writes: > Fast cgi is a good technology, but it's not well documented or > well supported. For some reason, the Apache people don't like it. > It used to be part of the Apache distribution, but that ended years ago. It seems to be coming back into favor. See: http://cryp.to/publications/fastcgi/ I've thought for a long time that the right way to do it is with the SCM_RIGHTS ancillary message on unix domain sockets, that lets you pass file descriptors around between processes. One of these days... From knut.urbye at gmail.com Wed Mar 26 17:55:45 2008 From: knut.urbye at gmail.com (Knut) Date: Wed, 26 Mar 2008 14:55:45 -0700 (PDT) Subject: py2exe socket.gaierror (10093) References: <105384dd-c178-45e8-a66d-d09dc13bd135@s19g2000prg.googlegroups.com> Message-ID: <44590b6d-b44f-47e3-a3d2-ff84370b9ee6@i7g2000prf.googlegroups.com> > The script can't resolve the server name. Try to do it by hand using > nslookup or even ping (you may want to add a few print statements inside > the script to see the exact host name it is trying to connect to, in case > it isn't what you expect) > If you can't resolve the host name using nslookup, there is a network > problem, not in your script. If you can resolve it, try your script > without py2exe if possible. > > -- > Gabriel Genellina Thank you for the quick reply Gabriel. I have made sure the script works fine before I exe it. It is when I compile the program I get this error. I don't get how the compile changes server availability. Thanks again, Knut From martin at v.loewis.de Fri Mar 21 17:17:00 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 21 Mar 2008 22:17:00 +0100 Subject: os.path.getsize() on Windows In-Reply-To: <47E42413.8020503@ulmcnett.com> References: <47E41F3C.6040109@v.loewis.de> <47E42413.8020503@ulmcnett.com> Message-ID: <47E425CC.3070408@v.loewis.de> >> Why do you say that? It most definitely returns what the size currently >> is, not what it will be in the future (how could it know, anyway). > > I've seen this before, when copying a file in Windows. Windows reports > the size the file will be after the copy is complete (it knows, after > all, the size of the source file). I always thought this meant that > Windows is just much smarter than me, so I ignored it. No, I really think the target file has its size right from the beginning. Regards, Martin From siti.nurhaliza5 at gmail.com Wed Mar 26 03:16:02 2008 From: siti.nurhaliza5 at gmail.com (siti) Date: Wed, 26 Mar 2008 00:16:02 -0700 (PDT) Subject: Computer Shop center Message-ID: <205a2198-dceb-4079-a43e-00303800a528@d4g2000prg.googlegroups.com> Hi friends. if you wanna looking the latest original software..mobile phone...laptop..pc.. accessories... you can search at here..it will give the best price for you. Amazon has teamed up with Allianz Insurance plc who can offer you insurance on this product, covering accidental damage and breakdown.Amazon Services Europe SARL is an introducer appointed representative of Allianz Insurance plc which is authorised and regulated by the Financial Services Authority. AmazonServices Europe SARL, 5 Rue de Plaetis, L-2338, Luxembourg, is not part of the Allianz (UK) Group. The insurance is arranged, sold and administered by Allianz. By purchasing this insurance you confirm that you have read and understood the Technical details, product description and Keyfacts document provided by Allianz. This your URL http://astore.amazon.co.uk/happyfamily-21 From stefan_ml at behnel.de Sun Mar 16 11:49:15 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 16 Mar 2008 16:49:15 +0100 Subject: Types, Cython, program readability In-Reply-To: <199cfa42-ca1a-4db6-bf4d-a0a811daa791@s12g2000prg.googlegroups.com> References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> <199cfa42-ca1a-4db6-bf4d-a0a811daa791@s12g2000prg.googlegroups.com> Message-ID: <47DD417B.9070907@behnel.de> sturlamolden wrote: > On 16 Mar, 15:32, bearophileH... at lycos.com wrote: >> It seems the development of Cython is going very well, quite >> differently from the dead-looking Pyrex. Hopefully Cython will become >> more user-friendly too (Pyrex is far from being user-friendly for >> Windows users, it doesn't even contain a compiler, I think. The > > Pyrex is not dead. Technically, that's true. There has been a release not so long ago, although after a rather lengthy idle period. However, the current development cycle of Cython is so fast that Pyrex will have a hard time catching up. So there isn't much of a reason why you should prefer Pyrex over Cython. Stefan From http Wed Mar 12 18:38:32 2008 From: http (Paul Rubin) Date: 12 Mar 2008 15:38:32 -0700 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> Message-ID: <7xy78neffb.fsf@ruckus.brouhaha.com> Carl Banks writes: > > For example:http://www.python.org/dev/peps/pep-3100/ > > list.sort() and builtin.sorted() methods: eliminate cmp parameter [27] [done] > > Hmm, wasn't aware they were taking it that far. You should almost > always avoid using the cmp parameter because it's very inefficient; I don't see what's so inefficient about it necessarily. The key argument invokes a DSU scheme that allocates and releases potentially a lot of memory, which both uses time and increases the program's memory region. The cmp option should not be removed. However, requiring it to be specified as a keyword parameter instead of just passed as an unlabelled arg is fine. From manicos010 at gmail.com Sat Mar 15 07:20:29 2008 From: manicos010 at gmail.com (manicos010 at gmail.com) Date: Sat, 15 Mar 2008 04:20:29 -0700 (PDT) Subject: ************GET FREE SOFTWARES HERE************** Message-ID: <37412733-4bb9-4cb8-9c86-4413c2e0337e@e10g2000prf.googlegroups.com> ************GET FREE SOFTWARES HERE************** GET SOME USEFUL SOFTWARE FOR FREE. THIS IS REALLY HERE IS THE LINK TO DOWNLOAD.JUST CLICK THE LINK BELOW THEN DOWNLOAD THE SOFTWARE YOU WANT. http://freeproductsforyou.googlepages.com From Lie.1296 at gmail.com Sat Mar 8 12:27:34 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 8 Mar 2008 09:27:34 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <7xmypa844v.fsf@ruckus.brouhaha.com> <13t3r8oeh4frj43@corp.supernews.com> Message-ID: On Mar 8, 8:34?am, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote: > > Pierre Quentel writes: > >> I would like to know if there is a module that converts a string to a > >> value of the "most probable type" > > > ? ? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > > ? ? >>> import this > > ? ? The Zen of Python, by Tim Peters > > ? ? ... > > ? ? In the face of ambiguity, refuse the temptation to guess. > > Good advice, but one which really only applies to libraries. At the > application level, sometimes (but not always, or even most times!) > guessing is the right thing to do. Guessing should only be done when it have to be done. Users should input data in an unambiguous way (such as using 4 digit years and textual month name, this is the most preferred solution, as flexibility is retained but ambiguity is ruled out) or be forced to use a certain convention or be aware of how to properly input the date. Guessing should be done at the minimum. Personally, when I'm working with spreadsheet applications (in MS Office or OpenOffice) I always input dates in an unambiguous way using 4-digit year and textual month name (usually the 3-letter abbrevs for quicker inputting), then I can confidently rely the spreadsheet to convert it to its internal format correctly. The general parsers like the OP wanted are easy to create if dates aren't involved. > E.g. spreadsheet applications don't insist on different syntax for > strings, dates and numbers. You can use syntax to force one or the other, > but by default the application will auto-detect what you want according > to relatively simple, predictable and intuitive rules: > > * if the string looks like a date, it's a date; > * if it looks like a number, it's a number; > * otherwise it's a string. The worse thing that can happen is when we input a date in a format we know but the application can't parse and it consider it as a string instead. This kind of thing can sometimes easily pass our nose. I remembered I once formatted a column in Excel to write date with certain style, but when I tried to input the date with the same style, Excel can't recognize it, making the whole column rendered as useless string and requiring me to reinput the dates again. > Given the user-base of the application, the consequences of a wrong > guess, and the ease of fixing it, guessing is the right thing to do. > > Auto-completion is another good example of guessing in the face of > ambiguity. It's not guessing that is bad, but what you do with the guess. > > -- > Steven From grflanagan at gmail.com Tue Mar 25 12:36:49 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 25 Mar 2008 09:36:49 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <0e15a0da-835a-42de-b2fc-e6fe72bb203e@t54g2000hsg.googlegroups.com> <74971084-b01c-4bd1-be6b-dbe8faa89023@c19g2000prf.googlegroups.com> Message-ID: On Mar 25, 4:37 pm, Brian Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > > Gerard Flanagan wrote: > > Use the child class when calling super: > > > -------------------------------------- > > class Foo(object): > > def __init__(self): > > self.id = 1 > > > def getid(self): > > return self.id > > > class FooSon(Foo): > > def __init__(self): > > Foo.__init__(self) > > self.id = 2 > > > def getid(self): > > a = super(FooSon, self).getid() > > b = self.id > > return '%d.%d' % (a,b) > > > print FooSon().getid() > > -------------------------------------- > > That still doesn't do what he's trying to do. > Ah, I see. Maybe something like the following then? -------------------------------------- class Foo(object): def __init__(self): self._id = [1] def getid(self): return '.'.join(str(i) for i in self._id) class FooSon(Foo): def __init__(self): Foo.__init__(self) self._id.append(2) print FooSon().getid() -------------------------------------- G. From michael.wieher at gmail.com Thu Mar 6 15:34:45 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 6 Mar 2008 14:34:45 -0600 Subject: Py-Extension Irregularity In-Reply-To: References: Message-ID: Ah. Well, that is true =) Still, the fact of the file-pointer shifting more than 16-increments to the right is insane. Its a simple read(&struct,16) command. but you're right, the problem might lie elsewhere. I forgot that using 0 for a sentinel value in two places can confuse a complier (let alone me.) I ended up fixing it by resetting the file-pointer to zero on re-entry, and then manually fseeking() to the correct location each time. Its one extra command per iteration, but not a huge speed issue. I feel bad using a global file object, but its that or I open/close it every time I call the funct. Thanks for pointing out that bit of confusion =) 2008/3/6, Gabriel Genellina : > > En Thu, 06 Mar 2008 13:54:44 -0200, Michael Wieher > escribi?: > > > > Observe. > > > > Python Code Snippet: > > ==================== > > ... > > 66 while i < (self.nPCodes): > > 67 # print "%s:%s" % (self.nPCodes,i) > > 68 (c,l,sn,f,fn,sz) = tabmodule.getQuestion(i,self.mx3Path) > > 69 if _debug and sz>0: > > 70 _newPtrLoc = tabmodule.getMx3Ptr() > > 71 _diff = _newPtrLoc-_oldPtrLoc > > 72 _oldPtrLoc = _newPtrLoc > > 73 if _diff>16: > > 74 print _diff > > .... > > > > C++ Code Snippet: > > --------------------------- > > 189 static PyObject* > > 190 tabmodule_getMx3Ptr(PyObject * self, PyObject * args) { > > 191 int a; > > 192 a=mx3File.tellg(); > > 193 return Py_BuildValue("i",a); > > 194 } > > ... > > > > 189 PyObject * > > 190 tabmodule_getQuestion(PyObject * self, PyObject * args) { > > .... > > 208 mx3File.read((char*)&m_mdx,16); > > .... > > 237 //if(m_mdx.size==0) > > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > > 239 //return Py_BuildValue("iiiiii",m_mdx.compression, > > m_mdx.location, > > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > > } > > > > Output== > > michael at majw-m65:~/MRI/tabModule$ ./tabModule.py > > michael at majw-m65:~/MRI/tabModule$ > > > > None. (ie: the _diff is always 16 or less, which is what is SHOULD be, > > in > > fact, it is always 16.) > > > Why do you assert that? With those commented out lines, the last item > returned by getQuestion (sz) is always 0; nothing is printed because sz==0 > and the python code never enters the outer if. From that evidence I can't > say anything about _diff. > > > > Observe!!!! > > > > 237 if(m_mdx.size==0) > > 238 return Py_BuildValue("iiiiii",0,0,0,0,0,0); > > 239 return Py_BuildValue("iiiiii",m_mdx.compression, m_mdx.location, > > m_mdx.stacknotes, m_mdx.file, m_mdx.footnote, m_mdx.size); > > > > By uncommenting line 237 and 239, we see: > > ... > > 64 > > 80 > > 32 > > 32 > > 32 > > 48 > > 128 > > 160 > > 32 > > 32 > > 64 > > .... > > > > Most of the numbers are still 16, but _diff is often larger than 16, by > > some > > multiple. > > > I'd print m_mdx values in the C++ source. > > > > How in Buddah's name is returning a Py_BuildValue() affecting a file > > pointer > > that isn't being used at all in the function???? > > > I don't think this is the cause... > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Sat Mar 1 23:53:04 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 1 Mar 2008 20:53:04 -0800 (PST) Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: On 1 Mrz., 19:51, Barry Warsaw wrote: > Python 2.6 is not only the next advancement in the Python 2 series, it > is also a transitionary release, helping developers begin to prepare > their code for Python 3.0. Isn't this a silly idea? People have to migrate from 2.5 or lower releases to Python 2.6 first just to migrate to Python 3.0? What are the inherent / technical reasons that prevent migration directly from 2.5 to 3.0? From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 21:21:32 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 01:21:32 -0000 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <13ue0gsj76m6070@corp.supernews.com> On Sun, 23 Mar 2008 13:51:34 -0400, Roy Smith wrote: > On the other hand, when I do: > > def torture(): > woman.putInChair() > cushion.poke() > rack.turn() > > I've also done two things. First, I've created a function object (i.e. > a lambda body), and I've also bound the name torture to that function > object, in much the same way I did with the list. But, it's different. > The function object KNOWS that it's name is torture. No it does not. Function objects don't know their name. All they know is that they have a label attached to them that is useful to use as a name in some contexts, e.g. when printing tracebacks. It's just a label, nothing more. You can prove that for yourself with a few simple tests. Firstly, we can prove that functions don't know what they are called by writing a recursive function: def spam(n): if n <= 1: return "Spam" return "Spam " + spam(n-1) If spam() knows what it is called, then you should be able to rename the function and the recursive call will continue to work. But in fact, that's not what happens: >>> spam(3) # check that it works 'Spam Spam Spam' >>> tasty_stuff = spam # make an alias >>> tasty_stuff(3) 'Spam Spam Spam' But now watch what happens when we create a new function with the name spam. It hijacks the recursive call: >>> def spam(n): ... return "ham-like meat product" ... >>> tasty_stuff(3) 'Spam ham-like meat product' The function formerly known as "spam" isn't calling itself, it is merely calling a function by name "spam". But we can see that the function tasty_stuff() is still using the old "spam" label for itself: >>> tasty_stuff('foo') Traceback (most recent call last): File "", line 1, in File "", line 3, in spam TypeError: unsupported operand type(s) for -: 'str' and 'int' Unfortunately there's nothing we can do to fix that error. Even though the function object has an attribute "__name__" (also known as "func_name") which is set to spam, it isn't used for tracebacks. Instead, the label comes from a read-only attribute buried deep in the function object: >>> tasty_stuff.func_code.co_name = 'yummy meat-like product in a can' Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute This is a mistake, in my opinion. It's an arbitrary decision to make this read-only (as far as I can tell), which goes against the grain of Python's "we're all consenting adults here" philosophy. By the way, in case you're thinking that wanting to change the (so- called) name of a function is a silly think to do, not at all. Consider factory functions: def factory(how_much): def f(n=1): for i in range(n): print "I love spam a %s" % how_much return f Every function created by the factory has the same "name", no matter what name you actually use to refer to it. factory('little') and factory('lot') both uselessly identify themselves as "f" in tracebacks. The truth is that objects don't know what name they have, because objects don't have names. The relationship is the other way around: names have objects, not vice versa. Some objects (functions, classes, anything else?) usefully need a label so that they can refer to themselves in tracebacks and similar, and we call that label "the name", but it's just a label. It doesn't mean anything. [snip] > What Python give us with lambdas is some half-way thing. It's not a > full function, so it's something that people use rarely, Which people? > which means most people (like me) can't remember the exact syntax. Speak for yourself, not for "most people". > Even when I know > it's the right thing to be using in a situation, I tend not to use it > simply because the path of least resistance is to write a one-off > function vs. looking up the exact syntax for a lambda in the manual. lambda arguments : expression Why is that harder to remember than this? def name ( arguments ) : block And don't forget to include a return statement, or you'll be surprised by the result of the function. -- Steven From bkjones at gmail.com Sun Mar 16 22:49:51 2008 From: bkjones at gmail.com (Brian Jones) Date: Sun, 16 Mar 2008 19:49:51 -0700 (PDT) Subject: PyCon Feedback and Volunteers (Re: Pycon disappointment) References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <5776428b-82b3-4921-945a-69beab134edd@b64g2000hsa.googlegroups.com> Message-ID: <4a04063e-0abe-4e97-a639-94bb691f9bf7@n58g2000hsf.googlegroups.com> On Mar 16, 8:09 pm, a... at pythoncraft.com (Aahz) wrote: > If you did not like the programming this year (aside from the sponsor > talks) and you did not participate in organizing PyCon or in delivering > presentations, it is YOUR FAULT. PERIOD. EXCLAMATION POINT! I find this insulting, inexcusable, and utter nonsense. If putting the blame for a failed experiment on the backs of the good folks who paid good money for travel, lodging, and registration is also an experiment, you can hereby consider it also failed. The bottom line is that the people who are providing feedback in this forum are doing so *voluntarily*, and for the good of future PyCon events. They were sold a bill of goods, it was ill-comunicated, and they have taken their time to express that this is not a good idea moving forward. If it weren't for these people giving feedback, you would not have a complete experiment, because you would never have been able to prove or disprove your hypothesis. In fact, the people in this forum are just as important to the process as those who devised the experiment. As an experiment, it would seem that having an event organizer, who is presumably interested in the future success of the event, talking down to the people who would also like to see a better event in the future (and think they can make that happen - otherwise why bother giving feedback?), is doomed to failure. Of course, I'm only looking at how the experiment is being carried out. I claim ignorance as to the hypothesis. The rest of the points in your rant are all pretty commonly known by now, to most. At the end of the day, the buck has to stop somewhere, and that somewhere has to be with the organization that were charged with motivating a volunteer force, and the organization who set the expectations of the attendees. If you think that PyCon would've been better had there been more volunteers, then you should feed that back to the folks in charge of attracting and motivating said force. If you think it was simply a mis-labeling of the different classes of talks, feed that back to the folks who are in charge of such things. The point is that there are endless things that can be done which are more useful and productive than pointing fingers back at the people who support the conference by being attendees. They help build the conference too. A conference answers to its attendees, and that should be an expectation of anyone concerned with conference organization. Period. Exclamation point. Brian K. Jones Editor in Chief Python Magazine From carsten at uniqsys.com Wed Mar 12 21:32:24 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 12 Mar 2008 21:32:24 -0400 Subject: escape string to store in a database? In-Reply-To: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> References: <2de6a097-1178-493b-b4e5-bc93dc87848c@m44g2000hsc.googlegroups.com> Message-ID: <1205371944.3313.16.camel@localhost.localdomain> On Wed, 2008-03-12 at 18:18 -0700, andrei.avk at gmail.com wrote: > These pieces of text may have single and double quotes in > them, I tried escaping them using re module and string module and > either I did something wrong, or they escape either single quotes or > double quotes, not both of these. So that when I insert that text into > a db record, this causes an error from the database. What's the > accepted way of dealing with this? The accepted way of dealing with this is to use parameter binding: conn = somedbmodule.connect(...) cur = conn.cursor() cur.execute("insert into sometable(textcolumn) values (?)", (stringvar,) ) (Note that the question mark may have to be replaced with %s depending on which database module you're using.) For background information on parameter binding see, for example, http://informixdb.blogspot.com/2007/07/filling-in-blanks.html . HTH, -- Carsten Haese http://informixdb.sourceforge.net From python at rcn.com Mon Mar 3 16:17:08 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Mar 2008 13:17:08 -0800 (PST) Subject: Polymorphism using constructors References: <6333v2F25lleoU1@mid.individual.net> Message-ID: <8ebd32bf-41b3-4602-8ad3-9becab699d26@h11g2000prf.googlegroups.com> On Mar 3, 12:21 pm, "K Viltersten" wrote: > I'm writing a class for rational numbers > and besides the most obvious constructor > > def __init__ (self, nomin, denom): > > i also wish to have two supporting ones > > def __init__ (self, integ): > self.__init__ (integ, 1) > def __init__ (self): > self.__init__ (0, 1) For this particular use case, providing default arguments will suffice: class Fraction: def __init__(self, numerator=0, denomiator=1): ... Since Python doesn't support having two methods with the same name, the usual solution is to provide alternative constructors using classmethod(): @classmethod def from_decimal(cls, d) sign, digits, exp = d.as_tuple() digits = int(''.join(map(str, digits))) if sign: digits = -digits if exp >= 0: return cls(digits * 10 ** exp) return cls(digits, 10 ** -exp) Raymond From pete.forman at westerngeco.com Wed Mar 12 13:35:13 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 12 Mar 2008 17:35:13 +0000 Subject: best way to have enum-like identifiers? References: Message-ID: mh at pixar.com writes: > Currently I'm just putting this at the top of the file: > > py=1 > funcpre=2 > funcpost=3 > ... That can be done more compactly with py, funcpre, funcpost = range(3) give or take 1. > but I'm curious if there's a better way of doing this, > some kind of enum-like thing or somesuch. https://launchpad.net/munepy describes itself as yet another Python enum implementation. Its author is Barry Warsaw. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From davidbak at gmail.com Fri Mar 7 20:46:54 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 17:46:54 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: <964fb7a8-3375-49a4-820a-d6b5d87c7ba0@e10g2000prf.googlegroups.com> Message-ID: <1ec4b03a-75cd-432e-9e5d-750132324d38@s8g2000prg.googlegroups.com> On Mar 7, 3:41?pm, castiro... at gmail.com wrote: > On Mar 7, 4:39?pm, DBak wrote: > > > On Mar 7, 1:19?pm, "Chris Mellon" wrote: > > > > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > > > ?However I can't do this, because, of course, the name Tree isn't > > > > ?available at the time that the classes _MT and _Node are defined, so > > > > ?_MT and _Node can't inherit from Tree. > > > > Not only is the name not defined, the class doesn't even exist yet. > > > Yes, but, well - it certainly isn't usable yet, but some object (that > > will be the class when it is finished) is being built (its __dict__ is > > being populated, etc.) - so there's an object pointer available inside > > the interpreter that could be put somewhere. ?But this is pedantic - > > you're right, the class really isn't available until after the class > > statement. > > There is no obvious solution-- What do you mean? ?If there are any at > all, there is significant competition without clear winners. > > dict dictA: > ? ?membA= 0 > ? ?membB= 0 > > dict dictB: > ? ?membC= 0 > > But, if you try to nest them, do you want the rest of the 'dict' at > its outer level evaluated (that's your 'here is the crux'), or only > that point so far? > > dict dictO: > ? membA= 0 > ? dict membB: > ? ? membC= 0 > ? ? membD= membE > ? membE= 0 > > So, you can't refer to it at all. ?Especially if membE is defined in > outer scope. Thanks for your answer. To the extent I understand it: There is a difference between the class statements I was trying to nest, with the inner inheriting from the outer, and your dict example. The main thing is that in the class example - when the inner class is being built (i.e., inside its class statement's block) there is no need (as I understand it) for the parent class to be functional at all WHILE I AM DEFINING METHODS on the inner class. Sure, if the inner class had code to be executed immediately, such as statements setting class attributes on the inner class, and that code used names such that attribute lookup needed to be done, then that might or might not work - it would depend on where the names were defined in the outer class relative to the placement of the inner class statement - exactly like the fact that the order of definition matters when executing code when defining a module: functions defined in a module can, in their body, name functions not yet defined, but assignment statements to module attributes cannot (they get a run time error). But in the case I'm talking about I just want to define methods on the inner class, using names such that when the method is eventually called on an instance of the inner class the attribute lookup will proceed with the outer class being the inner class' parent. Creating instances of the inner class won't happen until after the inner class and the outer class are both fully created (and assigned to their names) so any name lookup using inheritance won't happen until both class objects are fully created, so ... if you could do it ... it would work fine. Anyway, I know it can't be done the way I wanted it - the attribute with the outer class' name hasn't been assigned yet when I need to reference it in the inner class' class statement - so I was just looking to see what the preferred alternative was. Based on the discussion so far it seems I should just forget about using nested classes and flatten everything to the module level, using the __all__ attribute to make it clear to the user of the data structure what pieces of the module he should actually be using. -- David From dave.brk at gmail.com Thu Mar 27 10:27:42 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 27 Mar 2008 16:27:42 +0200 Subject: Regarding __slots__ and other stuff: A couple of questions Message-ID: I'm new to Python. I'm trying to understand the type/class/object(instance) model. I have read here: http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html and here: http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html as well as here: http://users.rcn.com/python/download/Descriptor.htm There are still a couple of issues I'm unclear about. I'll be very happy if one of you could help me. *first:* Why doesn't this works? >>> class C(object): ... __slots__ = ['foo', 'bar'] ... class_attr = 'class attribute' ... >>> c = C() >>> c.foo = 'foo' >>> c.bar = 'bar' >>> c.bar, c.foo ('bar', 'foo') >>> c.__slots__ ['foo', 'bar'] >>> c.__slots__.append('eggs') >>> c.__slots__ ['foo', 'bar', 'eggs'] >>> c.eggs = 'eggs' Traceback (innermost last): File "", line 1, in AttributeError: 'C' object has no attribute 'eggs' *second:* what happens here? Why can I write to spam using the class object but not the using the instance? >>> class C(object): ... __slots__ = ['foo', 'bar'] ... class_attr = 'class attribute' ... >>> C.spam = 50 >>> C.spam 50 >>> C.spam = 56 >>> c = C() >>> c.spam = 55 Traceback (innermost last): File "", line 1, in AttributeError: 'C' object attribute 'spam' is read-only >>> C.spam = 55 >>> C.spam 55 *Third:* class RevealAccess(object): """A data descriptor that sets and returns values normally and prints a message logging their access. """ def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print 'Retrieving', self.name return self.val def __set__(self, obj, val): print 'Updating' , self.name self.val = val class A(object): def __init__(self): self.x = RevealAccess(10, 'var "x"') self.y = 5 class B(object): x = RevealAccess(10, 'var "x"') y = 5 >>> a = A() >>> b = B() >>> a.x <__main__.RevealAccess object at 0x00BAC730> >>> a.x = 55 >>> b.x Retrieving var "x" 10 >>> b.x = 55 Updating var "x" >>> Why the descriptor works only when created as a static variable and not as an instance variable? I'm sure all this questions stem from my lack of understanding python object model. But, please, what am I missing? Thanks Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Tue Mar 11 06:14:54 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 03:14:54 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> Message-ID: On Mar 11, 2:18?am, "Diez B. Roggisch" wrote: > > The problem with callbacks is that it works only for a small amount of > > callbacks, it'd be too messy to have twenty different callbacks. > > And the ultimate problem with callbacks is that we can't determine > > from the outside whether the operation should continue or breaks at > > the point of the callback without some messy trick. > > > We can't always determine whether we want to do this: > > def somefunc(argA, argB, callback = DO_NOTHING): > > ? ? if argA == argB: > > ? ? ? ? callback() > > > or this: > > def somefunc(argA, argB, callback = DO_NOTHING): > > ? ? if argA == argB: > > ? ? ? ? callback() > > ? ? ? ? return > > > perhaps we could do this: > > ? ? if argA == argB: > > ? ? ? ? if callback() == True: return > > > but that's so much extra codes written and would've been too messy to > > write. > > > And actually this isn't a rare cases, and in fact is very common. It's > > just that most cases that can be more cleanly written in > > SoftException, can usually be handled in different ways, using tricks > > that range from subtle to messy (like callbacks). > > I fail to see how your arguments follow. > > Regarding the number of callbacks: you can as well pass an object that > has several methods to call. If you passed an object that has several methods to call (using tuple or list) and you want to handle several softexceptions and ignore some others, you must still pass an empty methods to the one you want to ignore, cluttering the caller's code by significant degree: def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, DO_NOTHING)): if a == 0: raise callback(0) try: a += b except ZeroDivisionError: raise callback(1) if a <= 0: raise callback(2) raise callback(3) return a somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, DO_NOTHING)) if instead we use dict, well, we know how convenient dict's syntax is for a lot of manual data entry. ## imagine if we want to handle five or more callbacks somefunc(a, b, {callbackzero:handlerzero, callbacktwo:handlertwo}) > And the above example can easily be accomplished with "normal" > exceptions, like this: > > def toplelevel(): > ? ? ?def callback(a, b): > ? ? ? ? ?if a == b: > ? ? ? ? ? ? raise InterruptException() > ? ? ?try: > ? ? ? ? ? work(callback) > ? ? ?except InterruptException: > ? ? ? ? ? pass > > def work(callback=callback): > ? ? ?a = 10 > ? ? ?b = 20 > ? ? ?callback(a, b) That's why I said most things that can be more cleanly handled by SoftException can usually be handled in other forms, although in a more cluttered way. That could be more cleanly written in SoftException as: def work(): a = 10 b = 20 raise Equal(a, b) def toplevel(): try: work() except Equal, args: a, b = args if a == b: raise InterruptException OR ALTERNATIVELY (Which one's better depends on the purpose, generally the one below is better, but the one in the above is more flexible, yet a bit less convenient to use) def work(): a = 10 b = 20 if a == b: raise Equal def toplevel(): try: work() except Equal: raise InterruptException The reason why SoftException is useful is similar to the reason why for-loop and while is useful. AFAIK, all looping cases can be handled only by a blind loopers (a.k.a. while True:) and break, but a blind loopers is very inconvenient to use, and for-loop and while simplifies a lot of codes a lot. Exactly the same reason why SoftException is useful. > And even more: the callback-approach can do things like this: > > a, b = callback(a,b) > > to change values, which makes it superior to SoftExceptions - unless I > missed it's ability to capture context. If there is a syntax support, you could also make "resume" able to transfer values: def somefunc(a, b): if a == b: a, b = raise Equal(a, b) def toplevel(): try: somefunc(10, 20) except Equal, args: a, b = args[0], args[1] + 1 resume a, b On Mar 11, 5:18 am, "Diez B. Roggisch" wrote: > How would that differ from something like this: > > with add_soft_handler(SoftException): > invoke_something() > > ... # deep down in code > > raise_soft(SoftException()) > > The implementation of add_soft_handler and raise_soft is trivial - a bit > of thread-local storage and a stack. Perhaps you meant: raise_soft(SoftException) cause SoftException() may have side effects if called greedily That could be done, but when raise_soft() returns, it returns to the code that raises it so it must be 'break'en: def caller(a, b): if a == b: raise_soft(SoftException) break but this makes SoftException must break everytime, which make it lost its original purpose, so you have to add return code to raise_soft whether you want to break it or not: def caller(a, b): if a == b: if raise_soft(SoftException): break Compare to: def caller(a, b): if a == b: raise SoftException And this also makes it impossible to have state-changing behavior without some other weirder tricks From usenet at ionline.dk Thu Mar 27 06:27:26 2008 From: usenet at ionline.dk (ndlarsen) Date: Thu, 27 Mar 2008 11:27:26 +0100 Subject: Print to end of line in a terminal In-Reply-To: <47c5afe4$0$90273$14726298@news.sunsite.dk> References: <47c5afe4$0$90273$14726298@news.sunsite.dk> Message-ID: <47eb7692$0$90262$14726298@news.sunsite.dk> Hello again. I apologize for not replying earlier but I have been swamped in work lately. I appreciate your replies. Eventually I chose using curses for "right-hand edge of the window" as it seemed to be the most suitable solution. Thank you. ndlarsen From tommy.nordgren at comhem.se Sun Mar 2 09:12:43 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Sun, 2 Mar 2008 15:12:43 +0100 Subject: Book Recomendations In-Reply-To: References: Message-ID: <82E6B4FF-4D10-4632-9255-3B4B00AA2296@comhem.se> On 2 mar 2008, at 01.56, Ira Solomon wrote: > I am an experienced programmer (40 years). I've done Algol (if you've > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > few other odd languages (e.g. Taskmate). > I'm interested in learning Python and have downloaded a slew of books. > Too many. > I'd like a recommendation as to which books are considered to be the > cream of the crop. > I know there are tutorials on the web, but, again, I don't know the > quality. I would appreciate recommendations on those as well. > > Thanks > > Ira > -- > http://mail.python.org/mailman/listinfo/python-list I would recommend "Programming Python", by Mark Lutz, from O'Reillys ------------------------------------------------------ "Home is not where you are born, but where your heart finds peace" - Tommy Nordgren, "The dying old crone" tommy.nordgren at comhem.se From mal at egenix.com Wed Mar 12 15:51:09 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 12 Mar 2008 20:51:09 +0100 Subject: Time Zone application after strptime? In-Reply-To: References: <47D1B703.6040200@egenix.com> Message-ID: <47D8342D.7030205@egenix.com> Jim Carroll wrote: > M.-A. Lemburg egenix.com> writes: > >> On 2008-03-07 22:24, Jim Carroll wrote: >>> It's taken me a couple of hours to give up on strptime >>> with %Z for recognizing >>> time zones... but that still leaves me in the wrong zone: >>> >>> How can I use the "PST" (or any other time zone name) >>> to adjust dt by the >>> correct number of hours to get it into UTC before storing in MySQL? >> You could try mxDateTime's parser. It will convert most timezones >> into UTC for you: >> >> >>> from mx.DateTime import * >> >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008') >> > 00' at 2afdc7078f50> >> > > Unfortunately, mx.DateTime also ignores the time zone. If > I parse the PST time, and ask for the result's time zone it > gives me my local time zone. The result of the mxDateTime parser will always be UTC, if you provide a time zone. You can then convert this value to any other timezone you choose. The reason for this is simple: UTC is the only stable timezone you can use if you want to store date/time value in e.g. a database or file. -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Aug 10 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ From pavloutefkros at gmail.com Sat Mar 29 17:27:16 2008 From: pavloutefkros at gmail.com (Gif) Date: Sat, 29 Mar 2008 14:27:16 -0700 (PDT) Subject: wxPython listctrl Message-ID: <4dc652a5-d6f9-4cb8-af30-ec1c9e4ea505@y21g2000hsf.googlegroups.com> I was wondering if there is a way to extract an icon from a file (executable) and then add it in a listctrl. I also 'd like to know if i can shorten the icon in order to fit in a listctrl item. I've managed to get the icon from an icon file and add t as a listctrl item but it remains 32x32. code: images = ['LimeWire.ico'] self.il = wx.ImageList(18, 10) self.il.Add(wx.Bitmap(images[0])) #This below raises an error saying that no handle was found for that image #self.ib = wx.IconBundle() #self.ib.AddIconFromFile(r'LimeWire.exe', wx.BITMAP_TYPE_ANY) self.listView1.SetImageList(self.il, wx.IMAGE_LIST_SMALL) self.listView1.SetItemImage(0, 0) From fetchinson at googlemail.com Thu Mar 20 03:39:48 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 20 Mar 2008 00:39:48 -0700 Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] Message-ID: > Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ , > and saw that the repr module was slated for vaporization. I've only > used the module a few times ever. I'm curious if the community wants > it kept around or whether it is considered clutter. > > The PEP is going to be finalized soon, so if you have issues with it, > they should be sent to the PEP author or brought up on the list, > http://mail.python.org/mailman/listinfo/stdlib-sig . Is it just me or others also think that it would be a major loss to remove tkinter from the python core? PEP 3108 starts off with: Each module to be removed needs to have a justification as to why it should no longer be distributed with Python. then goes on with, With so many other GUI options out there that are considered better than Tkinter, it might be best to remove Tkinter from the stdlib and make it an externally maintained package. I don't get it. There are many [insert your favorite software component] options outside of the python core that are considered better than the one coming with python, yet they don't get removed. All network servers for example could be thrown out because twisted is considered better. This just doesn't make sense to me. Tkinter is great for its purpose, typical use cases are creating a simple GUI composed of a couple of components only. You can nicely do this with tkinter and the large user base shows that it's a real need real people have. Sure, for fancy GUI stuff there are better options but for quick and simple things tkinter is just great. And last time I checked python comes with batteries included so why sould I need to search and download a third party package for such a common use case? Thoughts anyone? Cheers, Daniel From schiz at lon.don Sun Mar 2 14:13:42 2008 From: schiz at lon.don (Schizoid Man) Date: Sun, 02 Mar 2008 19:13:42 +0000 Subject: Beginner's assignment question In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Sun, 02 Mar 2008 08:25:49 -0200, Schizoid Man escribi?: > >> Lorenzo Gatti wrote: >>> On Mar 1, 3:39 pm, Schizoid Man wrote: >>>> As in variable assignment, not homework assignment! :) >>>> >>>> I understand the first line but not the second of the following code: >>>> >>>> a, b = 0, 1 >>>> a, b = b, a + b >>>> >>>> In the first line a is assigned 0 and b is assigned 1 simultaneously. >>>> >>>> However what is the sequence of operation in the second statement? I;m >>>> confused due to the inter-dependence of the variables. >>> >>> The expressions of the right of the assignment operator are evaluated >>> before assigning any new values, to the destinations on the left side >>> of the assignment operator. >>> So substitutig the old values of a and b the second assignment means >>> >>> a, b = 0, 0 + 1 >>> >>> Simplifying the Python Reference Manual ("6.3 Assignment Statements") >>> a little : >>> >>> assignment_stmt ::= target_list "="+ expression_list >>> >>> An assignment statement evaluates the expression list (remember that >>> this can be a single expression or a comma-separated list, the latter >>> yielding a tuple) and assigns the single resulting object to each of >>> the target lists, from left to right. >>> >>> [...] >>> >>> WARNING: Although the definition of assignment implies that overlaps >>> between the left-hand side and the right-hand side are `safe' (for >>> example "a, b = b, a" swaps two variables), overlaps within the >>> collection of assigned-to variables are not safe! For instance, the >>> following program prints "[0, 2]": >>> >>> x = [0, 1] >>> i = 0 >>> i, x[i] = 1, 2 >>> print x >>> >>> Lorenzo Gatti >> >> Thank you for the explanation. I guess my question can be simplified as: >> >> First step: a, b = 0, 1 >> No problem here as a and b are assigned values. >> >> Second step: a, b = b, a + b >> >> Now my question is does b become a + b after a becomes 1 or while a >> stays at 0? >> >> As the assignment occurs simultaneously I suppose the answer is while a >> stays at 0. > > Read the previous response carefully and you'll answer your question. > The right hand side is EVALUATED in full before values are assignated to > the left hand side. Evaluating b, a+b results in 1, 1. The, those values > are assigned to a, b. Thank you very much. It's clear now. From brooklinetom at gmail.com Sat Mar 15 11:38:34 2008 From: brooklinetom at gmail.com (Tom Stambaugh) Date: Sat, 15 Mar 2008 11:38:34 -0400 Subject: Unicode/UTF-8 confusion Message-ID: I'm still confused about this, even after days of hacking at it. It's time I asked for help. I understand that each of you knows more about Python, Javascript, unicode, and programming than me, and I understand that each of you has a higher SAT score than me. So please try and be gentle with your responses. I use simplejson to serialize html strings that the server is delivering to a browser. Since the apostrophe is a string terminator in javascript, I need to escape any apostrophe embedded in the html. Just to be clear, the specific unicode character I'm struggling with is described in Python as: u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of 0x27. This can be expressed in several common ways: hex: 0x27 Python literal: u"\u0027" Suppose I start with some test string that contains an embedded apostrophe -- for example: u" ' ". I believe that the appropriate json serialization of this is (presented as a list to eliminate notation ambiguities): ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] This is a 14-character utf-8 serialization of the above test string. I know I can brute-force this, using something like the following: def encode(aRawString): aReplacement = ''.join(['\\', '0', '0', '2', '7']) aCookedString = aRawString.replace("'", aReplacement) answer = simplejson.dumps(aCookedString) return answer I can't even make mailers let me *TYPE* a string literal for the replacement string without trying to turn it into an HTML link! Anyway, I know that my "encode" function works, but it pains me to add that "replace" call before *EVERY* invocation of the simplejson.dumps() method. The reason I upgraded to 1.7.4 was to get the c-level speedup routine now offered by simplejson -- yet the need to do this apostrophe escaping seems to negate this advantage! Is there perhaps some combination of dumps keyword arguments, python encode()/str() magic, or something similar that accomplishes this same result? What is the highest-performance way to get simplejson to emit the desired serialization of the given test string? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Thu Mar 27 11:23:47 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 27 Mar 2008 10:23:47 -0500 Subject: Checking processes running under Windows In-Reply-To: References: Message-ID: <47EBBC03.5020608@ncee.net> One way: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339 Another way: wmi # List all running processes # http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.ProcessId, process.Name # List all running notepad processes import wmi c = wmi.WMI () for process in c.Win32_Process (name="notepad.exe"): print process.ProcessId, process.Name # Create and then destroy a new notepad process import wmi c = wmi.WMI () process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe") for process in c.Win32_Process (ProcessId=process_id): print process.ProcessId, process.Name result = process.Terminate () Jo?o Rodrigues wrote: > Hello all! I'm trying to write a script that needs to check which > processes are running under Windows (XP Pro, Home, whatever). The > method I'm using is: > > >>> process_list = os.popen('TASKLIST').read() > > However, XP Home doesn't have the tasklist.exe tool so, this is kind > of useless in that OS. Do you have any other methods I can use for this? > > Thanks! -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From toby at tobiah.org Thu Mar 13 15:40:40 2008 From: toby at tobiah.org (Tobiah) Date: Thu, 13 Mar 2008 12:40:40 -0700 Subject: Advantage of the array module over lists? Message-ID: I checked out the array module today. It claims that arrays are 'efficient'. I figured that this must mean that they are faster than lists, but this doesn't seem to be the case: ################ one.py ############## import array a = array.array('i') for x in xrange(10000000): a.append(x) for x in a: a[x] += 1 ################ two.py ############## a = [] for x in xrange(10000000): a.append(x) for x in a: a[x] += 1 ###################################### ktops:toby:pytest> time python one.py; time python two.py real 0m28.116s user 0m17.504s sys 0m10.435s real 0m23.026s user 0m13.027s sys 0m9.777s Perhaps the only advantage is that they take less memory to store a large number of items? It would seem then, that 'economical' might have been a better choice of word than 'efficient'. Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From bj_666 at gmx.net Tue Mar 25 15:49:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Mar 2008 19:49:34 GMT Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: <64t3aeF2derd7U4@mid.uni-berlin.de> On Tue, 25 Mar 2008 12:32:17 -0700, blackpawn wrote: > So what's the deal here? :) I want all objects to be freed when I > shut down and their destruction functions to be properly called. Then you want something that's not guaranteed by the language. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Sun Mar 23 20:29:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 17:29:13 -0700 (PDT) Subject: always getting 'None' return value from PyObject_CallObject References: Message-ID: <335691c7-79f0-4c7e-b19f-e9b94306d7f6@s12g2000prg.googlegroups.com> On Mar 24, 10:43 am, Gal Aviel wrote: > Hello all, > > Kinda desperate over here .. Any help would be greatly appreciated ! > > I'm trying to embed a Python interpreter inside a Verilog simulator as a > SystemVerilog DPI application. The python side implements a few SV exported > tasks. I've got a thin C shared library as the dpi app; all it does it get the > task arguments from the simulator and hand those to the Python side using the > Python C API. > > I followed '5.3 Pure Embedding' under Python 2.5 documentation very closely. > > When calling a function defined in my module, the function executes Ok - it sees > the correct arguments being passed from C, and executes 100% - only the return > value is always 'None' (I tried returning a simple integer like '5' which > doesn't work). > > Any ideas? > So you are saying that your Python functions does: return 5 [are you sure it's not falling off the end and thus implicitly returning None?] but PyObject_CallObject transmogrifies that into the Python object None -- or do you mean a C NULL pointer? It might be a good idea if you showed us the exact C code that you are using instead of this snippet from the manual: pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } including the part where you demonstrate that the returned pointer points to the None object. It might be a good idea if you showed us the minimal Python function that exhibits this behaviour with your C code ... does it happen with: def myfunc(): return 5 ? And what version of Python on what platform? From kla at us.de Wed Mar 19 06:40:10 2008 From: kla at us.de (klaus) Date: 19 Mar 2008 10:40:10 GMT Subject: a beginner, beginners question Message-ID: <47e0ed8a$0$307$e4fe514c@dreader24.news.xs4all.nl> Hello, I'm trying to learn python programming and so far so good. However when trying to master the oop side I ran into a small problem. I think I've done everything ok as outlined below. But I just don't understand why the `method' of `class' example isn't printing any of the variables that I have set earlier on ? Could someone please explain to me what it is I am doing wrong ? Thank you so much ! #!/usr/bin/env python class example: def __init__(self, foo, bar): self.foo = foo self.bar = bar def method(self): print "method ... :" print self.foo print self.bar if __name__ == "__main__": obj = example obj.foo = "var1" obj.bar = "var2" obj.method From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 6 06:09:59 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 06 Mar 2008 12:09:59 +0100 Subject: Hi In-Reply-To: References: Message-ID: <47cfd0f5$0$6540$426a74cc@news.free.fr> hellogaurang at gmail.com a ?crit : > Hello > > can u plz tell how to send and read msg from device(telit-863-GPS) and > the coding is in python. > > if this can happen then plz send the source code to my mail account You'll find relevant code and examples here: http://catb.org/~esr/faqs/smart-questions.html#intro HTH From Grimsqueaker13 at gmail.com Thu Mar 27 03:33:21 2008 From: Grimsqueaker13 at gmail.com (Grimsqueaker) Date: Thu, 27 Mar 2008 00:33:21 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: That seems to give me the items in the list back in an iterator. Am I using it incorrectly? From castironpi at gmail.com Mon Mar 3 20:10:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 3 Mar 2008 17:10:24 -0800 (PST) Subject: Altering imported modules References: <200803011856.27611.troworld@gmail.com> <683411d9-3ddf-454a-97e7-a34b351f5d1d@e31g2000hse.googlegroups.com> Message-ID: <78560896-f539-4f0a-8a5b-0e5fa26fa00f@u10g2000prn.googlegroups.com> On Mar 3, 5:09?pm, Tro wrote: > On Sunday 02 March 2008, Paul McGuire wrote: > > > > > > > On Mar 2, 3:48?pm, Tro wrote: > > > On Sunday 02 March 2008, Terry Reedy wrote: > > > > "Tro" wrote in message > > > >news:200803011856.27611.troworld at gmail.com... > > > > > | Hi, list. > > > > | > > > > | I've got a simple asyncore-based server. However, I've modified the > > > > > asyncore > > > > > | module to allow me to watch functions as well as sockets. The > > > > | modified asyncore module is in a specific location in my project and > > > > | is imported > > > > > as > > > > > | usual from my classes. > > > > | > > > > | Now I'd like to use the tlslite library, which includes an asyncore > > > > | mixin class. However, tlslite imports "asyncore", which doesn't > > > > | include my own modifications. > > > > | > > > > | I'd like to know if it's possible to make tlslite load *my* asyncore > > > > > module > > > > > | without changing any of the tlslite code. > > > > > If your module is also 'asyncore' and comes earlier in the search path, > > > > I would expect the import to get yours. > > > > It's not. It has a package prefix like my.package.asyncore. I think I can > > > either move my version of asyncore up a couple of levels or add the > > > my.package directory to sys.path. > > > > My version of asyncore imports several functions from the built-in > > > asyncore. Now that my version of it is imported as asyncore, how would it > > > import the built-in version from python2.5/site-packages? > > > > Thanks, > > > Tro > > > What happens if you do "import my.package.asyncore as asyncore"? > > > If that doesn't work (trying the simplest hack first), I know that > > there are various hooks in the import mechanism that should help. > > In the classes that use my version of asyncore currently, that is how I do it. > I import my version as "import my.package.asyncore as asyncore". In my > asyncore module I do "import asyncore", because I override a few functions > from the asyncore module included with python. However, if I were to > add "my.package" to sys.path, then I wouldn't be able to "import asyncore" > from my own asyncore module. I'd have to do some trickery with sys.path to > take the "my.package" component out, import standard asyncore, readd > the "my.package" component, so that other modules can "import asyncore" and > get my version. > > Is there a way to import the standard python asyncore module in this scenario? > > Thanks, > Tro- Hide quoted text - > > - Show quoted text - Are you trying to interfere with the default module on only your machine? Just rename it. If something in the std. lib. imports asyncore, they get yours too that way. From ed at leafe.com Thu Mar 20 13:39:15 2008 From: ed at leafe.com (Ed Leafe) Date: Thu, 20 Mar 2008 12:39:15 -0500 Subject: Pycon disappointment In-Reply-To: References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> <7x3aqpg3rv.fsf@ruckus.brouhaha.com> <303498db-a398-4f42-a1e2-1192b5527c7f@s8g2000prg.googlegroups.com> Message-ID: <68CC88AA-DE38-490D-953B-5AD7AB8493CC@leafe.com> On Mar 20, 2008, at 11:54 AM, atom.anderson at gmail.com wrote: > Number Three: Too much code, not enough concept. > > Presenters this one's for you. I can't count the number of > presentations I attended where the presenter would click through three > slides of pycode just to show us a two or three-line snippet that > illustrated their point. Worse yet, it was often at the bottom of the > screen so no one but the front row could see it. This goes for text > two. I saw some great presentations as well, and they had limited > text on each slide. The last thing your audience wants to see is a > slide drenched in text of any kind. This is good advice: simple slides serve as organization cues, but the content should come from the speaker. The worst case (only saw this twice at this year's PyCon) is when there is a text-heavy slide that the presenter simply reads. We can all read it ourselves! Your job is to elaborate on the topic. I'd like to see two things regarding slides: first, if at all possible, set a limit on the percentage of the talk that can consist of slides. I would much rather see the presenter show actual demonstrations of what they're talking about than simply talking about it. If that's not possible, then in the session description, clearly state the % of the talk that will be slides. Perhaps there are people who like to sit in a room and watch long PowerPoint (-type) presentations, but I'm not one of them. Let's see some code! Let's see stuff working (and sometimes crashing!), and how changes affect the results. When I've presented at PyCon and other conferences, that's the part that I spend the most time on: preparing demonstrations. It's not easy to do; certainly much more difficult than creating a slide that sums up what the demo does. But it makes for a much more interesting session! -- Ed Leafe From castironpi at gmail.com Thu Mar 27 06:59:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 03:59:44 -0700 (PDT) Subject: what does ^ do in python References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> <47E97E8B.2010108@tim.thechases.com> <5dc598e30803261104w33cfcb40h74ed158e144bd5a1@mail.gmail.com> Message-ID: <69875928-eab0-46fb-bcd0-88ac515f270e@t54g2000hsg.googlegroups.com> On Mar 26, 1:36?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 15:04:44 -0300, David Anderson ? > escribi?: > > > HOw can we use express pointers as in C or python? > > Traceback (most recent call last): > ? ?File "", line 1, in > ? ?File "parser.py", line 123, in parse_text > ? ? ?tree = language.parse_text(text) > ? ?File "english.py", line 456, in parse_text > ? ? ?tree = self.parse_sentence(sentence) > ? ?File "english.py", line 345, in parse_sentence > ? ? ?raise ParserError, "can't parse %r" % sentence > ParserError: can't parse 'HOw can we use express pointers as in C or ? > python?' Try to coil it up. It would explain part-of-speech errors (we make all the time over here). Coil goes so bad on blip-screen. We don't think in English. Hold. I meant, decoil it. Parts near each other on inferior rings of a circle: radius broadcasts in x**-2 (a.k.a. x/2 in logs) from a pole/ attractor, for redundancy-- distance along a harmonic around the attractor. It proposes path. Digital charter. Current sea. What's square curvature? Number's a square thought. Space and time are interchangable to verbal representations. (Space is money: see? And space doesn't grow on trees. So, what do you want for walls (same destination, new tack.-- high-dimension paths? I don't get what I (I) feel is mine-- you have to stay where you think you are. Spike the drink? What do you spike it with, nominal existence? What do -we- need and get at church, life and freedom?)? Microcircuitry and microplumbing in walls and microrecycling and microtransit could save a lot of energy and be safer and cheaper. The circles here suck. Graph vertices square and accept successfully. What is the identity relation in cause? Do you just like to build and eat coils? I'd like to (affirm/bolt) a structure that gets better at it. I deceive all the senses. My spelling is awe-ful. Am I trying to do the impossible? I like to regulate everything. What should I do? What is the good life? Give it some recoil and it works for me. Raise Locked coil. Sixth- grade English-native speakers don't discern (when prompted) commutations of 'is': 'a is c', 'b is c', therefore 'a is b'. ('Is' is causally intransitive to them.) Formal logic is pretty refined, or they're distracted. Do you? From steve at REMOVE-THIS-cybersource.com.au Wed Mar 19 18:50:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 19 Mar 2008 22:50:40 -0000 Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> Message-ID: <13u3660kfnhq412@corp.supernews.com> On Wed, 19 Mar 2008 14:45:39 -0700, Jim wrote: > Program randomly aborts when looking up url. The program loop thru > 4000+ records looking > up ID via internet and returns html code which is used in subsequent > processing. The code > for looking-up record is below followed by abort details. Can anyone > help with catching the > abort before program aborts or provide code to automatically start > program? Yes. Wrap the offending code with a try...except loop, something similar to this. try: contents = urllib2.urlopen(url).read() except URLError, e: if e.errno == 10053: # "Software caused connection abort" response = raw_input( "Temporary failure, Skip/Halt/try Again?") response = response.lower().strip() if response in ('h', 'halt'): break elif response in ('a', 'again', 't', 'try', 'try again'): continue elif response in ('', 's', 'skip'): lines -= 1 continue else: print "Unknown response, boo hiss to you!" raise -- Steven From stefan_ml at behnel.de Tue Mar 25 14:50:12 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Mar 2008 19:50:12 +0100 Subject: Beautiful Soup Looping Extraction Question In-Reply-To: References: Message-ID: <47E94964.30201@behnel.de> Hi, again, not BS related, but still a solution. Tess wrote: > Let's say I have a file that looks at file.html pasted below. > > My goal is to extract all elements where the following is true:

align="left"> and

. Using lxml: from lxml import html tree = html.parse("file.html") for el in tree.iter(): if el.tag == 'p' and el.get('align') == 'left': print el.tag elif el.tag == 'div' and el.get('align') == 'center': print el.tag I assume that BS can do something similar, though. Stefan From matthieu.brucher at gmail.com Tue Mar 25 18:25:59 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 25 Mar 2008 23:25:59 +0100 Subject: what does ^ do in python In-Reply-To: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> References: <8a6035a00803251502v5fa992d7j1af36fab4d485d83@mail.gmail.com> Message-ID: Hi, In most of the languages ^ is used for 'to the power of'. > No, not in most languages. In most languages (C, C++, Java, C#, Python, Fortran, ...), ^ is the xor operator ;) Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From supheakmungkol.sarin at gmail.com Thu Mar 27 23:07:35 2008 From: supheakmungkol.sarin at gmail.com (mungkol) Date: Thu, 27 Mar 2008 20:07:35 -0700 (PDT) Subject: Pystemmer 1.0.1 installation problem in Linux References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> <47ec0cd0$0$90262$14726298@news.sunsite.dk> Message-ID: On Mar 28, 6:06 am, Damjan wrote: > mungkol wrote: > > Dear all, > > > I am a newbie to Python community. For my project, I tried to install > > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > > unsuccessful. It produced the following error: > > you need to install the "build-essential" pacakge group on Ubuntu so that > you can compile programs. > > apt-get install build-essential > > > limits.h: No such file or directory > > This is probably /usr/include/linux/limits.h part of the kernel headers. > > -- > damjan Dear all, Thank you so much. It works out when I install the "build-essential" package as suggested. I appreciate your help very much. Regards, Supheakmungkol From fakeaddress at nowhere.org Sun Mar 9 07:57:08 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 09 Mar 2008 04:57:08 -0700 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: Message-ID: Lie wrote: [...] > Soft Exception is an exception that if is unhandled, pass silently as > if nothing happened. [...] > Implementation: > Simple implementation might be done by catching all exceptions at the > highest level, then filtering which exceptions would be stopped (Soft > Exception) and which exceptions will be reraised and terminate the > program (Hard Exception). This is simple and can be easily implemented > but is inefficient as that means all soft exceptions must bubble > through its way to the top to find out if it is Soft or Hard. If I'm following what you want, that "simple implementation" does not work. If a function, possibly deep in a call stack, raises a soft exception that no caller above catches, what executes next? Correct me if I'm misunderstanding your idea: You want raising an un-caught soft exception to be equivalent to a 'pass'; execution continues as if the 'raise' never happened. Catching everything at a high level does nothing like that. The exception causes execution to leave the function invoking the raise statement, and abolishes the stack state from the point of the raise to the point of the catch. As Python exceptions currently work, "catching all exceptions at the highest level" is either what Python already does, or ill-defined nonsense. When an exception is uncaught, there is no useful "highest level", other than the level at which the program simply fails. Python *must* terminate execution upon an unhanded exception, because the program defined no state from which executions could correctly continue. > A more through implementation would start from the raiser inspecting > the execution stack and finding whether there are any try block above > it, if no try block exist it pass silently and if one exist it will > check whether it have a matching except clause. This also circumvents > a problem that simple implementation have, as described below. The described problems do not include the "where should execution resume" problem, which I think is central to the issue. Correct me if I've misunderstood: A "soft" exception is one that gets raised only if some calling frame has arranged to catch it. The if-exception-would-be-unhanded-then-pass logic strikes me as interesting. It would be a huge change to Python, so I doubt it will get traction here. Still, I'd say it's worth more consideration and discussion. -- --Bryan From dickinsm at gmail.com Wed Mar 5 16:06:37 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 5 Mar 2008 13:06:37 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> Message-ID: <1bb82da0-6640-4183-b257-cfa2bad25575@m36g2000hse.googlegroups.com> On Mar 5, 3:25?pm, "Jeff.Goldfin... at gmail.com" wrote: > I can pack and unpack a float into a long > e.g. > struct.unpack('I',struct.pack('f',0.123))[0] > but then I'm not sure how to work with the resulting long. > > Any suggestions? One alternative to using struct is to use math.ldexp and math.frexp: >>> m, e = frexp(pi) >>> m 0.78539816339744828 >>> e 2 >>> int(m*2**53) 7074237752028440L Then you can do your bit twiddling on int(m*2**53), before using ldexp to 'repack' the float. Mark From fred.sells at adventistcare.org Tue Mar 11 23:29:43 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 11 Mar 2008 23:29:43 -0400 Subject: Looking for very light weight template library (not framework) In-Reply-To: <1204854964.1470.1241033951@webmail.messagingengine.com> Message-ID: <0A53725C4A497848A7B3A0874B259831011B087C@acesxch01.ADVENTISTCORP.NET> As I recall Quixote allowed you to embed html in python. was actually pretty cool. Havenot tried it in a long time. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Malcolm Greene > Sent: Thursday, March 06, 2008 8:56 PM > To: python-list at python.org > Subject: Looking for very light weight template library (not > framework) > > > New to Python and looking for a template library that allows Python > expressions embedded in strings to be evaluated in place. In > other words > something more powerful than the basic "%(variable)s" or "$variable" > (Template) capabilities. > > I know that some of the web frameworks support this type of template > capability but I don't need a web framework, just a library that > supports embedded expression evaluation. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated. > > Malcolm > -- > http://mail.python.org/mailman/listinfo/python-list > From aahz at pythoncraft.com Sun Mar 23 12:24:35 2008 From: aahz at pythoncraft.com (Aahz) Date: 23 Mar 2008 09:24:35 -0700 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: In article , Jeff Schwab wrote: > >Also, despite reassurances to the contrary, I still get the impression >that there is a strong anti-lambda sentiment among the Python "in" >crowd. Is it just a question of the word "lambda," as opposed to >perceived cleaner syntax? The problem with lambda is that too often it results in clutter (this is a strictly made-up example off the top of my head for illustrative purposes rather than any real code, but I've seen plenty of code similar at various times): gui.create_window(origin=(123,456), background=gui.WHITE, foreground=gui.BLACK, callback=lambda x: x*2) That means I need to pause reading the create_window() arguments while I figure out what the lambda means -- and often the lambda is more complicated than that. Moreover, because the lambda is unnamed, it's missing a reading cue for its purpose. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From nytrokiss at gmail.com Sun Mar 2 11:06:30 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 2 Mar 2008 17:06:30 +0100 Subject: Book Recomendations In-Reply-To: References: Message-ID: <8a6b8e350803020806g2f6d44evdbd23917a743b1eb@mail.gmail.com> I liked Core Python Programming 2nd edition! On Sun, Mar 2, 2008 at 4:27 PM, Ken Dere wrote: > Ira Solomon wrote: > > > I am an experienced programmer (40 years). I've done Algol (if you've > > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > > few other odd languages (e.g. Taskmate). > > I'm interested in learning Python and have downloaded a slew of books. > > Too many. > > I'd like a recommendation as to which books are considered to be the > > cream of the crop. > > I know there are tutorials on the web, but, again, I don't know the > > quality. I would appreciate recommendations on those as well. > > > > Thanks > > > > Ira > > I started off with Fortran 6X so I have been in the business about as > long. > Do just about everything now in Python. > > I liked Learning Python > > > Ken D. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Mar 18 18:09:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Mar 2008 23:09:57 +0100 Subject: method to create class property In-Reply-To: <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> References: <17bd4d78-2c06-43ff-a629-50dd05916bb8@k13g2000hse.googlegroups.com> <64aoqjF29asbkU1@mid.uni-berlin.de> <82797a3d-080e-4826-b322-8a3882eb4e6b@a23g2000hsc.googlegroups.com> Message-ID: <64astpF29u3k1U1@mid.uni-berlin.de> Joe P. Cool schrieb: > On 18 Mrz., 21:59, "Diez B. Roggisch" wrote: >> Joe P. Cool schrieb: >>> def _property_y(self): >>> def _get(self): >>> [...] >> There are a few recipies, like this: >> >> class Foo(object): >> >> @apply >> def foo(): >> def fget(self): >> return self._foo >> def fset(self, value): >> self._foo = value >> return property(**locals()) > > This is really cool! Thanks, Diez! I should definitely > learn to handle decorators :) But isnt't apply bound to > be dropped in Python 3.0? In python 3.0, there will be an even nicer way - propset: @property def foo(self): return self._foo @propset def foo(self, value): self._value = value Diez From roger.dahlstrom at gmail.com Mon Mar 31 10:22:04 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 31 Mar 2008 07:22:04 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll Message-ID: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> So I have a 64 bit Windows 2003 system, running python 2.5.1.1. I can import a Windows .dll (msvcrt or whatever) using ctypes, but when attempting to import another application-specific .dll (tibrv.dll if anyone is familiar with it), I receive the error WindowsError: [Error 193] %1 is not a valid Win32 application. I know there's a Windows on Windows (wow) which allows 32 bit processes to run on 64 bit windows - is there a way to work this in somehow? Maybe I'm barking up the wrong tree? Code is simple, and works on 32 bit systems no from ctypes import * #this doesn't work tibrv = cdll.tibrv #this does work msvcrt = cdll.msvcrt From gagsl-py2 at yahoo.com.ar Thu Mar 27 16:35:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 17:35:16 -0300 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> Message-ID: En Thu, 27 Mar 2008 16:29:23 -0300, escribi?: > I'm making a game where you'll be able to make your own mods and I > want to be able to write these mods in python. However, python has a > lot of "dangerous" functions (like erase any file on the harddrive > etc) so I want a "safe" python. I first found RExec but that is > disabled in python 2.5 so I was thinking about building python from > source with a few changes. > The changes I was thinking about was to change the import function so > that it should only be able to import the .pyd-files that I allow (and > it should of course still be able to import any .py-file) and remove > or change the builtin functions that are "dangerous". > Is this enough to make a "safe" python that can't do anything > "dangerous"? No, and that's the reason for rexec/bastion removal. There are several ways to circumvent it. By example, if the user can get access to a file object, he can open any other file using type(f)("anyotherfile"). If he can get an object defined in your code: py> type(x).some_method.func_globals['__builtins__'].__import__ and then import anything. I think that a highly reputed Python developer made some time ago a really safe version and nobody could spot any holes, but I can't find the reference. > I'm going to embed this "safe" python into my game and I've discovered > that when I embed the original python and the mod wants to import > a .py-file that is not in the game directory it will search for > the .py-file in the python directory that is installed on my computer. > Can I somehow prevent the embedded python to look in the python > directory? Python looks along sys.path for importing things. Sorry but if you don't know that you shouldn't try to build a safe Python version on your own - at least you should have a lot of doubts that it is actually safe. -- Gabriel Genellina From noreply at noreply.org Wed Mar 19 06:50:17 2008 From: noreply at noreply.org (some one) Date: Wed, 19 Mar 2008 04:50:17 -0600 Subject: Script Request... Message-ID: Hi all, I am not to familiar with python yet and I am wondering if someone can write a script that will monitor my DSL modems IP address and notify when it changes, its a 2Wire Advanced DSL Modem. I need to know when it changes because I am trying to run my own inhouse server and have to update my domain records through verio.com. The script would need to read the text of a web page( on my modem the address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and search for a string containing the IP address. Can anyone help? thanks, I'll keep monitoring this thread. From ivan.illarionov at gmail.com Mon Mar 17 21:53:11 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 17 Mar 2008 18:53:11 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: Message-ID: On Mar 18, 4:36 am, dave wrote: > Hi All. I've been formulating in my head a simple image editor. I > actually started prototyping is some time ago in Java, but am liking > Python more and more. My editor will be nowhere near the level of Gimp/ > Photoshop, but I do need fast pixel level control and display. For > instance, that means no automatic anti-aliasing and that I will be > implementing my own line drawing algorithms. > > I've got the high level architectual aspects of my program down, but > am stuck on what graphics API to use. I want a canvas area of > adjustable size which users can draw on with as little lag as > possible. The canvas area will be composed of layers (i.e. I require > an alpha channel) and I need to be able to zoom in and out of it (zoom > levels will be at fixed intervals, so this can be simulated if need > be.) > > I started looking at PyGame but realize that I need to integrate a GUI > into the whole thing (or integrate the image into the GUI rather) and > I didn't see a straightforward way to do that. Of course, I don't even > know if PyGame is the right API for the job anyways :P > > Any thoughts or ideas that could help me get started? Thanks! Look at the PIL source code for reference and implement your own C extensions for drawing and image manipulation. Or write your app on top of PIL. Any GUI toolkit will work if you find the low-level access to their image memory buffers. PyGame is for multimedia applications, you probably need Tkinter, Qt, wx or GTK. And as long as you need such low-level things as custom drawing and anti-aliasing your API is plain old C malloc's, free's and raw memory addresses. -- Ivan From noname9968 at gmail.com Thu Mar 27 08:11:49 2008 From: noname9968 at gmail.com (Alex9968) Date: Thu, 27 Mar 2008 15:11:49 +0300 Subject: GUI toolkits with Tkinter's .pack() alternative In-Reply-To: References: <47EA1604.4070905@gmail.com> <47EB35FF.4020407@gmail.com> <47EB7F55.8090909@gmail.com> Message-ID: <47EB8F05.8090505@gmail.com> Guilherme Polo wrote: > 2008/3/27, Alex9968 : > >> Guilherme Polo wrote: >> > 2008/3/27, Alex9968 : >> > >> >> Guilherme Polo wrote: >> >> > 2008/3/26, Alex9968 : >> >> > >> >> >> Hi all, >> >> >> >> >> >> I use Tkinter's Pack widget geometry manager (I really prefer it over >> >> >> using visual GUI designers), so my question is which other GUI toolkits >> >> >> have similar functionality. >> >> >> >> >> > >> >> > The geometry manager isn't related to using GUI designers tools at >> >> > all. And each toolkit has it's own way to do the things, wxPython uses >> >> > sizers, PyGtk uses containers. >> >> > >> >> >> >> Well, the geometry manager isn't *directly* related to using GUI >> >> designers, but as Pack arranges widgets automatically, using GUI >> >> designers isn't required, while with geometry managers that don't, GUI >> >> designers are necessary (if you start placing widgets programmatically, >> >> you'll end up reinventing something like Tkinter's Pack or Grid geometry >> >> manager). I hope I can be understood clearly this time ;-) >> >> >> > >> > Not at all, can't understand your point yet. GUI designers aren't just >> > for placing widgets, they also will keep the interface design >> > separated from your code. >> > >> >> I do not want to separate interface from code and I do not experience >> the need to use GUI designers. >> >> > > It is your opinion, it seems I can't change it for now but I hope you > reconsider it for the future. > > >> Pack arranges widgets perfectly, and it's very complex to do the same >> without it, both in code and in GUI designer. >> > > For some level of "perfect", of course. > Also, I can't understand why you say it is hard to do such thing in a > gui designer tool, which tool have you tried ? Maybe you are not > familiar with them yet, and that could be the problem. > Can you explain why my opinion is to be reconsidered? In GUI designer it's easy to produce initial (still) layout, but what if it should be changed at runtime (for example, widgets added or removed), and still be ideally arranged? I know that widgets might have some parameters affecting for example how they move when their container is resized, and that might help when updating interface, but I think it's inconvenient that they're hidden inside their property sheets (and therefore invisible while designing). I should answer the question - I used Visual C# from Microsoft Visual Studio .NET 2003, and after moving to Python I did not use any GUI designer. From carsten at uniqsys.com Sat Mar 15 15:12:05 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 15 Mar 2008 20:12:05 +0100 Subject: Unicode/UTF-8 confusion In-Reply-To: <1205607791.3224.4.camel@localhost.localdomain> References: <000b01c886b6$ecf506b0$0200a8c0@TMSMAIN> <1205607791.3224.4.camel@localhost.localdomain> Message-ID: <1205608325.3224.9.camel@localhost.localdomain> On Sat, 2008-03-15 at 20:03 +0100, Carsten Haese wrote: > On Sat, 2008-03-15 at 12:09 -0400, Tom Stambaugh wrote: > > [...] > > I use simplejson to serialize html strings that the server is delivering to > > a browser. Since the apostrophe is a string terminator in javascript, I need > > to escape any apostrophe embedded in the html. > > [...] > > simplejson escapes them for you: > > >>> import simplejson > >>> s = " ' " > >>> simplejson.dumps(s) > '" \' "' > > Why is this not good enough for your needs? And before somebody else corrects my use of the word "escaping", simplejson doesn't actually escape the apostrophe. The backslash is, of course, python's repr() escaping the apostrophe. simplejson simply handles the apostrophe by enclosing it in quotation marks. The result should still be good enough, though. -- Carsten Haese http://informixdb.sourceforge.net From aaron.watters at gmail.com Wed Mar 19 09:38:19 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 19 Mar 2008 06:38:19 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <8ee4ae2d-10af-41cd-a405-0fbdf73ce9d9@a70g2000hsh.googlegroups.com> On Mar 18, 12:55 pm, perrygreenfi... at gmail.com wrote: > Amen on the diamond keynotes and lightning talks. The lightning talks > were a great disappointment. Sponsor talks (or any such talks pitched > at selling or recruiting) should go in their own, clearly labeled > group so those of us who don't care about them can avoid them... Seconded. I haven't been at a Python Conf for a long time but as a former attendee and (not very good) organizer I have a couple suggestions based on my past experience and mistakes: - The conference is too long and it shouldn't be on the weekend. - Almost all talks should be 10 minutes at most with prepared slides and extended abstract with references. - With much shorter talks you should be able to accept just about any properly prepared talk (with abstract and slides) and this should reduce the politics and increase the attendance (with speakers and some colleagues and maybe broader interest). I don't know about this conference, but in past conferences I've been frustrated by people who give out a train of conscience meander including popping in and out of various console prompts, editors, web pages, guis... without conveying any useful information (to me) in 30 minutes. If you tell them they have 10 minutes and make them get organized in advanced they are much more likely to get to the point and everyone can see something else before they run out of attention span. -- Aaron Watters === bye bye petroleum! good riddance. http://biofuels.usu.edu/htm/initiative http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=pretty+boring From gggg.iiiii at gmail.com Mon Mar 3 18:56:22 2008 From: gggg.iiiii at gmail.com (G) Date: Mon, 3 Mar 2008 18:56:22 -0500 Subject: os.system with cgi Message-ID: <4a7f84ac0803031556p721d9a74h2cd7051bf6bc5b7e@mail.gmail.com> Hi, I have the following peace of code def getBook(textid, path): url = geturl(textid) if os.path.isfile(path + textid): f = open(path + textid) else: os.system('wget -c ' + url + ' -O ' path + textid) f = open(path + textid) return f The reason I am not using urllib is that I want to have random access within the downloaded file. When i execute the file from a regular python script I get the file downloaded and a handle for the file returned. When I execute the file from a python cgi script i get an error saying that the file doesn't exist. In other words the call to os.system is not running. Could someone please point out what the problem with that peace of code running as a cgi script. Best. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfbolz at gmx.de Sun Mar 30 14:47:52 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 30 Mar 2008 20:47:52 +0200 Subject: ANN: Py-Lib 0.9.1 released Message-ID: py lib 0.9.1: bugfix release ============================= The py lib team has just released version 0.9.1 of the py lib - a library aiming to support agile and test-driven python development on various levels. This is mostly a bugfix release, with a couple of new features sneaked in. Most important changes: * reduced the number of threads used in py.execnet * some new functionality (authentication, export, locking) in py.path's Subversion APIs * stability and segfault fixes in execnet * numerous small fixes in py.test's rsession (experimental pluggable session) and generative test features * some fixes in the py.test core * added py.misc.killproc, which allows killing processes on (some flavours of) Windows and UNIX For a complete list of changes, see doc/changes-0.9.1.txt in the source package. Download/Install: http://codespeak.net/py/0.9.1/download.html Documentation/API: http://codespeak.net/py/0.9.1/index.html Work on the py lib has been partially funded by the European Union IST programme and by http://merlinux.de within the PyPy project. best, have fun and let us know what you think! holger krekel, Maciej Fijalkowski, Carl Friedrich Bolz, Guido Wesdorp From simon at brunningonline.net Tue Mar 11 09:21:23 2008 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 11 Mar 2008 13:21:23 +0000 Subject: Check For SELF Variable Existance In-Reply-To: <-8215347293566648508@unknownmsgid> References: <-8215347293566648508@unknownmsgid> Message-ID: <8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> On Tue, Mar 11, 2008 at 11:00 AM, Robert Rawlins wrote: > I want to be able to check if a class has a certain property in its 'self' > scope, what's the best way to do this? >>> class Spam(object): ... def egg(self): ... if hasattr(self, 'chips'): print 'got chips!' ... >>> spam = Spam() >>> spam.egg() >>> spam.chips = 'beans' >>> spam.egg() got chips! -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 19:07:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 06 Mar 2008 00:07:00 -0000 Subject: Why """, not '''? References: <13su5tn6rpjb345@corp.supernews.com> Message-ID: <13sudd49au3e1c1@corp.supernews.com> On Wed, 05 Mar 2008 23:27:21 +0000, Matthew Woodcraft wrote: > Steven D'Aprano wrote: >>On Wed, 05 Mar 2008 19:19:08 +0000, Matthew Woodcraft wrote: >>> One advantage is that a dumb syntax highlighter is more likely to cope >>> well if the content includes an apostrophe. > >> But if the content contains double-quote marks, the "dumb syntax >> highligher" is more likely to cope well if you use '''. > > That's right. But apostrophes are rather more common than quote marks in > English text. Surely it would depend on the type of text: pick up any random English novel containing dialogue, and you're likely to find a couple of dozen pairs of quotation marks per page, against a few apostrophes. -- Steven From mauriceling at acm.org Sat Mar 29 08:11:48 2008 From: mauriceling at acm.org (Maurice LING) Date: Sat, 29 Mar 2008 12:11:48 GMT Subject: Re; finding euclidean distance,better code? In-Reply-To: References: Message-ID: <47ee31f7$1@news.unimelb.edu.au> Hendrik van Rooyen wrote: > On Saturday 29 March 2008 03:09:46 Steven D'Aprano wrote: >> On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: >>> Gabriel Genellina wrote: >>>> That's what I said in another paragraph. "sum of coordinates" is using >>>> a different distance definition; it's the way you measure distance in a >>>> city with square blocks. I don't know if the distance itself has a >>>> name, but >>> I think it is called Manhattan distance in reference of the walking >>> distance from one point to another in this city. >> You know, there are other cities than Manhattan. Some of them even have >> streets and blocks. > > Sorry about having to dispel your illusions, but - > > In Printed Circuit Board Layout jargon, the 'manhattan distance' is > the sum of the distances along the orthogonal axes between > two points on the board that should be connected. > > The sum of all such distances is an idealised minimum for the > total track length on a double sided board, given that it were > possible to lay all tracks with segments connected by vias, > making strictly increasing progress in the desired direction, > by laying x direction tracks on the one, and y direction tracks > on the other side of the board without having to "backtrack" > - i.e. having to "dodge around" obstacles, thereby adding > "overshooting" segments of track. > > (A via is a through plated hole that connects copper traces or > tracks on opposite sides of the board) > > So I have met the beast, but I have no concept of its origin, > other than the mind numbing regularity of the layout of the > suburb of the city after which it seems to be named - > For all I know 'manhatten' could be a native american word that > means "net". > > Have you noticed that when people say "Sorry.....but...." they are > not normally sorry at all? > > :-) > > - Hendrik > Manhatten distance is also known as "taxicab distance" or "city block distance" - the average distance of getting from point A to point B in a city with roads laid out as grids. maurice From half.italian at gmail.com Tue Mar 18 18:27:27 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 18 Mar 2008 15:27:27 -0700 (PDT) Subject: os.path.getsize() on Windows References: Message-ID: <6abeaadf-0055-4216-9aed-ad87bc006038@h11g2000prf.googlegroups.com> On Mar 18, 2:27?pm, Duncan Booth wrote: > Sean DiZazzo wrote: > > On windows, this returns the size of the file as it _will be_, not the > > size that it currently is. ?Is this a feature? ?What is the proper way > > to get the current size of the file? ?I noticed > > win32File.GetFileSize() ?Does that behave the way I expect? > > > PS. ?I also tried os.stat()[6] > > I think all of those will return the current size of the file, but that may > be the same as the final size: just because the data hasn't been copied > doesn't mean the file space hasn't been allocated. You don't say how you > are copying the file, but I seem to remember that Windows copy command pre- > allocates the file at its final size (so as to reduce fragmentation) and > then just copies the data after that. > > If you need to make sure you don't access a file until the copy has > finished then get hwatever is doing the copy to copy it to a temporary > filename in the same folder and rename it when complete. Then you just have > to check for existence of the target file. Hmmm... The file could be copied in by several different sources of which I have no control. I can't use your technique in my situation. I also tried getting md5 hashes with some time in between on advice, but the file is not opened for reading until the copy completes so I can't get the hashes. Any other ideas? From cappallo at gmail.com Sun Mar 2 11:52:27 2008 From: cappallo at gmail.com (TC) Date: Sun, 2 Mar 2008 08:52:27 -0800 (PST) Subject: Question on importing and function defs References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> Message-ID: <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> On Mar 2, 11:37 am, Gary Herron wrote: > TC wrote: > > I have a problem. Here's a simplified version of what I'm doing: > > > I have functions a() and b() in a module called 'mod'. b() calls a(). > > > So now, I have this program: > > > from mod import * > > > def a(): > > blahblah > > > b() > > > The problem being, b() is calling the a() that's in mod, not the new > > a() that I want to replace it. (Both a()'s have identical function > > headers, in case that matters.) How can I fix this? > > > Thanks for any help. > > Since b calls mod.a, you could replace mod.a with your new a. Like > this: (Warning, this could be considered bad style because it will > confuse anyone who examines the mod module in an attempt to understand > you code.) > > import mod > > def replacement_a(): > ... > > mod.a = replacement_a > > ... > > Or another option. Define b to take, as a parameter, the "a" function > to call. > > In mod: > > def a(): > ... > > def b(fn=a): # to set the default a to call > ... > > And you main program: > > from mod import * > > def my_a(): > ... > > b(my_a) > > Hope that helps > > Gary Herron Thanks for the tips, but no luck. This is for a homework assignment, so there are a couple of requirements, namely that I can't touch 'mod', and I have to do 'from mod import *' as opposed to 'import mod'. So the first method you suggested won't work as written, since the mod namespace doesn't exist. I tried a = replacement_a, but b() is still calling mod's version of a() for some reason. And because I can't touch mod, I can't use your second suggestion. In case I somehow oversimplified, here's the actual relevant code, in 'mod' (actually called 'search'). The first fn is what I've been calling a(), the second is b(). (lots of stuff...) def compare_searchers(problems, header, searchers=[breadth_first_tree_search, breadth_first_graph_search, depth_first_graph_search, iterative_deepening_search, depth_limited_search, astar_search]): def do(searcher, problem): p = InstrumentedProblem(problem) searcher(p) return p table = [[name(s)] + [do(s, p) for p in problems] for s in searchers] print_table(table, header) def compare_graph_searchers(): compare_searchers(problems=[GraphProblem('A', 'B', romania), GraphProblem('O', 'N', romania), GraphProblem('Q', 'WA', australia)], header=['Searcher', 'Romania(A,B)', 'Romania(O, N)', 'Australia']) That's the end of the 'search' file. And here's my program, which defines an identical compare_searchers() with an added print statement. That statement isn't showing up. from search import * def compare_searchers(problems, header, searchers=[breadth_first_tree_search, breadth_first_graph_search, depth_first_graph_search, iterative_deepening_search, depth_limited_search, astar_search, best_first_graph_search]): def do(searcher, problem): p = InstrumentedProblem(problem) searcher(p) return p table = [[name(s)] + [do(s, p) for p in problems] for s in searchers] print 'test' print_table(table, header) compare_graph_searchers() From duncan.booth at invalid.invalid Mon Mar 31 05:32:37 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Mar 2008 09:32:37 GMT Subject: Problem with method overriding from base class References: Message-ID: wrote: > Factory: > ********************************************************************** * > **************** def factory(type, *p): > if type == common.databaseEntryTypes[0]: > return module1.Class1(*p); > elif type == common.databaseEntryTypes[1]: > return module2.Class2(*p); > elif type == common.databaseEntryTypes[2]: > return module3.Class3(*p); > elif type == common.databaseEntryTypes[3]: > return module4.Class4(*p); > ********************************************************************** * Have you considered using a dictionary mapping name to class, or even just storing the classes directly in common.databaseEntryTypes. That way your code would get a lot smaller and less messy: e.g. in common.py: databaseEntryTypes = [ module1.Class1, module2.Class2, module3.Class3, module4.Class4 ] and then factory becomes: def factory(type, *p): return type(*p) after which you can remove factory altogether. Or if you keep the name -> type mapping then at least factory becomes maintainable. > > Implementing Class1: > ********************************************************************** * > **************** import editInterface > > class Class1(editInterface.EditInterface): > > def __init__(self, product, database): > # do something here ... > > def showEntry(self, entry, statustext): > # do something here as well, return some string... > ********************************************************************** * > **************** > > Now, when I want to create an Instance of Class1 I do: > > myClass1Instance = factory.factory(common.databaseEntryTypes[1], > 'Name', databaseObj ) > > Which seems to work fine according to the debugger. But when I do > next: > > msg = myClass1Instance.show(firstEntry, '') > > Then the show() method of the class 'EditInterface' is called instead > of the show() method of the class 'Class1' !! Does anyone have an idea > why the method of the base class is called instead of the method of > the derived class and how can I do it, so that the show() of Class1 is > called instead? In the code you posted Class1 doesn't have a show() method, it has a showEntry() method so calling show() will call the base class as the only implementation it has. From george.sakkis at gmail.com Mon Mar 24 15:13:59 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 24 Mar 2008 12:13:59 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> <6448a26f-cf49-42cf-89b1-e5ba9cd0be9c@e6g2000prf.googlegroups.com> Message-ID: On Mar 24, 3:03 pm, pythonnubie wrote: > On Mar 24, 11:57 am, Jeff wrote: > > > What does the code look like? > > # Random Access > # Demonstrates string indexing > # Michael Dawson - 1/27/03 > > import random > > word = "index" > print "The word is: ", word, "\n" > > high = len(word) > low = -len(word) > for i in range(10): > position = random.randrange(low, high) > print "word[", position, "]\t", word[position] > > raw_input("\n\nPress the enter key to exit.") > > The code is an exerp from a chm file . I am petty sutre I am > nmot getting a char map error from the copy/paste ! it looks > simple enough ! It works fine on on Windows with standard Python 2.5. Something is probably wrong with your ActiveState installation. George From samuel.progin at gmail.com Mon Mar 10 12:06:53 2008 From: samuel.progin at gmail.com (Sam) Date: Mon, 10 Mar 2008 09:06:53 -0700 (PDT) Subject: defining a method that could be used as instance or static method References: <63l454F275mskU1@mid.uni-berlin.de> Message-ID: <328a8554-42eb-4f59-9e4a-c573353ae495@2g2000hsn.googlegroups.com> > Did you try that it doesn't work? because it should. Whenever you do > No... -_- I kept on trying things @staticmethod. Thanks for your hint, it works fine! Sam From lists at cheimes.de Fri Mar 21 13:36:52 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 21 Mar 2008 18:36:52 +0100 Subject: Improving datetime In-Reply-To: <47E3C1A3.6050608@ncf.ca> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <47E3C1A3.6050608@ncf.ca> Message-ID: <47E3F234.9010607@cheimes.de> Colin J. Williams schrieb: > You might consider adding the Julian date > (http://en.wikipedia.org/wiki/Julian_date). > > I had a crack at this a while ago but didn't seem to get quire the right > result, using the ACM algorithm. I seemed to be a day out at the BC/AD > divide. Yes, the Julian date family is very useful when dealing with dates before 1900. I'm +1 for adding JDT and MJD. TAI64 is another time format used for high precision and real time measurement. http://cr.yp.to/libtai/tai64.html Christian From gagsl-py2 at yahoo.com.ar Wed Mar 19 18:32:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 19:32:13 -0300 Subject: printing dictionary and tuple References: Message-ID: En Wed, 19 Mar 2008 08:16:52 -0300, Beema shafreen escribi?: > i am trying to print the dictionary values and tuple in a same line as > below > > print "\t".join(dict[a].values())+'\t'+"\t".join(b) > > Error I get is the TypeError, > since i have misisng values in the dictionary. if i use exception i > will > miss those > how should i print the data without missing the lines excluding the error > separated by tab. What is a? What is b? Their contents? I *guess* this is what you want: a = {'some': 'values', 3.14: 'in a', 1234: 'dictionary'} b = ('99', 'bottles', 'of', 'beer') print '\t'.join(a.values()) + '\t' + '\t'.join(b) The code above only works if all values are strings - else you could get a TypeError. In that case, convert all items to string before joining: a = {'some': 'values', 'in a': 3.14, 'dictionary': 1234} b = (99, 'bottles', 'of', 'beer') print ('\t'.join([str(value) for value in a.values()]) + '\t' + '\t'.join([str(item) for item in b])) If this is not your problem, please provide a complete example next time, and the full exception traceback is very important too. -- Gabriel Genellina From Jeff.Goldfinkle at gmail.com Wed Mar 5 15:51:11 2008 From: Jeff.Goldfinkle at gmail.com (Jeff.Goldfinkle at gmail.com) Date: Wed, 5 Mar 2008 12:51:11 -0800 (PST) Subject: Bit twiddling floating point numbers References: <35f3b367-44cd-4595-b920-49a22162711b@c33g2000hsd.googlegroups.com> <13su15t266dimc2@corp.supernews.com> <13su1pl8tnq5o6a@corp.supernews.com> Message-ID: <6fa9d736-1769-4e79-a276-f071a83ebce9@e60g2000hsh.googlegroups.com> On Mar 5, 10:48 pm, Grant Edwards wrote: > On 2008-03-05, Grant Edwards wrote: > > > On 2008-03-05, Jeff.Goldfin... at gmail.com wrote: > >> Any suggestions? > > > Just use the bitwise and/or/not operators: & | ~ > > Oh, I forgot to mention the shift operators << and >> > > -- > Grant Edwards grante Yow! All of life is a blur > at of Republicans and meat! > visi.com thanks for the reply but I'm still unsure as to how to continue. Using the bitwise operators will help me deal with integers but I really want to work with floats. For instance - which bits do I twiddle to round my float to the nearest number of bits? Jeff From miki.tebeka at gmail.com Thu Mar 27 17:13:16 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 27 Mar 2008 14:13:16 -0700 (PDT) Subject: Tips Re Pattern Matching / REGEX References: <7ebb329d-12e0-42d8-a543-15521d1ecc46@u10g2000prn.googlegroups.com> Message-ID: Hello, > I have a large text file (1GB or so) with structure similar to the > html example below. > > I have to extract content (text between div and tr tags) from this > file and put it into a spreadsheet or a database - given my limited > python knowledge I was going to try to do this with regex pattern > matching. > > Would someone be able to provide pointers regarding how do I approach > this? Any code samples would be greatly appreciated. The ultimate tool for handling HTML is http://www.crummy.com/software/BeautifulSoup/ where you can do stuff like: soup = BeautifulSoup(html) for div in soup("div", {"class" : "special"}): ... Not sure how fast it is though. There is also the htmllib module that comes with python, it might do the work as well and maybe a bit faster. If the file is valid HTML and you need some speed, have a look at xml.sax. HTH, -- Miki http://pythonwise.blogspot.com From nagle at animats.com Tue Mar 25 20:54:54 2008 From: nagle at animats.com (John Nagle) Date: Tue, 25 Mar 2008 17:54:54 -0700 Subject: dynamically created names / simple problem In-Reply-To: References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: <47e99c9b$0$36374$742ec2ed@news.sonic.net> Robert Bossy wrote: > Jules Stevenson wrote: >> >> Hello all, >> >> I'm fairly green to python and programming, so please go gently. The >> following code >> >> for display in secondary: >> >> self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, >> "checkbox_2") >> >> Errors, because of the apparent nastyness at the beginning. What I?m >> trying to do is loop through a list and create uniquely named wx >> widgets based on the list values. Obviously the above doesn?t work, >> and is probably naughty ? what?s a good approach for achieving this? >> > Hi, > > What you're looking for is the builtin function setattr: > http://docs.python.org/lib/built-in-funcs.html#l2h-66 Actually, you don't need to use attributes for this at all. You're better off with an ordinary dictionary. Something like this: class someclass(object) : def __init__(self) : self.widgets = {} # empty dictionary def addwidget(self, widgetname, widgetfn) self.widgets[widgetname] = widgetfn def callwidgetbyname(self, widgetname, args) self.widgets[widgetname](*args) The only reason to use attributes is when you want to allow the use of the notation objectinstance.attributename If you're only going to get the attributes with getattr, they don't need to be attributes. John Nagle From arnodel at googlemail.com Tue Mar 18 18:12:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 15:12:16 -0700 (PDT) Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: <9bdc6a9e-08de-459b-ab10-74823f4dda51@s19g2000prg.googlegroups.com> Jeff Schwab wrote: > I need to move a directory tree (~9GB) from one machine to another on > the same LAN. What's the best (briefest and most portable) way to do > this in Python? > > I see that urllib has some support for getting files by FTP, but that it > has some trouble distinguishing files from directories. > > http://docs.python.org/lib/module-urllib.html > > "The code handling the FTP protocol cannot differentiate > between a file and a directory." > > I tried it anyway, but got an authentication problem. I don't see a > "how to log into the FTP server" section on docs.python.org. Is there a > tutorial I should read? > > I am particularly looking for a quick, "good enough" solution that I can > use this afternoon. Thanks in advance to any kind-hearted soul who > chooses to help me out. Have you tried ftplib? (http://docs.python.org/lib/module-ftplib.html) Here is an example of how to use it to differentiate between files and directories (untested). conn = ftplib.FTP('host', 'user', 'password') def callback(line): name = line.rpartition(' ')[-1] # assumes no whitespace in filenames if line[0] == 'd': #filename is a directory print 'directory', name else: print 'file', name #This will print all files in cwd prefixed by 'directory' or 'file' #You can change callback to retrieve files and explore #directories recursively conn.dir(callback) HTH -- Arnaud From gagsl-py2 at yahoo.com.ar Wed Mar 19 15:43:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 16:43:05 -0300 Subject: How to solve a three-element equation set? References: <2a274618-a368-4f20-96d2-3ed9b270768c@k13g2000hse.googlegroups.com> Message-ID: En Wed, 19 Mar 2008 04:05:50 -0300, purple escribi?: > Could you guys do me a favor for solving a equation set? > > Z=d/4*(1-SIN(X)/X) > X=8q/(D^2*Y)+SIN(X) > Y=1/n*Z^(2/3)*i^(1/2) > > In this equation set, X,Y&Z are the unkown parameters, the others say, > d, q, n&i are known. SO in python, how to program it to represent X, Y > and Z in the form of d, q, n and i? You want a numeric result, I presume. SciPy www.scipy.org has several minimization functions. -- Gabriel Genellina From michael.wieher at gmail.com Thu Mar 6 12:47:11 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Thu, 6 Mar 2008 11:47:11 -0600 Subject: Please keep the full address In-Reply-To: <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> <0c01deb0-b539-49f7-8a87-dfa65226f2ad@d62g2000hsf.googlegroups.com> Message-ID: I normally find this kind of back & forth useless and annoying spam but the irony is too much to avoid commenting. (read the following, then ...) > > > > "His" posts? > > > > Whatever. I'm too old to worry about searching for politically correct, > > gender neutral pronouns. > > > I'm pretty sure even the most PC people wouldn't suggest using a > masculine pronoun for an inanimate objects. > > > (Ok, some probably would.) > > Carl Banks Mr Banks. Technically, the sentence should be "...pronoun for inanimate objects" .. OR "...pronoun for an inanimate object." If you're going to nitpick, then at least do it right. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff.fw at gmail.com Mon Mar 17 16:39:10 2008 From: jeff.fw at gmail.com (Jeff) Date: Mon, 17 Mar 2008 13:39:10 -0700 (PDT) Subject: Sharing code between server, client, and web Message-ID: Hello everyone. This is a basic question of structure--something that it's rather difficult to search for. So, here's what there will be once this project is finished: 1) A server using Twisted and SQLAlchemy 2) A desktop client connecting to that server (with Twisted), using wxPython 3) A web interface using Pylons and SQLAlchemy The web interface and desktop app will be accessing the same data, but with different privileges and features. Twisted will be used to shuttle objects back and forth (using Perspective Broker). So, what I would really like to do is this: 1) Define the SQLAlchemy tables and models only once, and share that between the server and Pylons 2) Define methods on the models that can be used from the web interface and desktop app--meaning the models need to be shared (to some extent) with the client. Nothing is written yet, but I already have code from a current project to make SQLAlchemy and Twisted's Perspective Broker play nicely together (that was an interesting exercise). What I'm not sure about, though, is the best way to share some of the code all around. I've thought of two possible ways, but I don't particularly like either: 1) Make the entire directory structure a package, so I can use relative imports. This has the drawback that I'd need to package most or all of the server code in with the client, which I really don't want to do. 2) Have a separate lib directory that's symlinked into each place that it's needed. Does anyone see any major drawbacks to this one? It just rubs me the wrong way... So, thanks for your help in advance, and if you need any more information, please don't hesitate to ask. Thanks, Jeff From python.list at tim.thechases.com Tue Mar 25 12:03:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Mar 2008 11:03:56 -0500 Subject: any good g.a.'s? In-Reply-To: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> References: <8c2be8b0-5ae3-4a3e-9f01-bae649c82c41@e67g2000hsa.googlegroups.com> Message-ID: <47E9226C.7040309@tim.thechases.com> > Any good genetic algorithms involving you-split, i-pick? I've always heard it as "you divide, I decide"... That said, I'm not sure how that applies in a GA world. It's been a while since I've done any coding with GAs, but I don't recall any facets related to the You Divide, I Decide problem. It sounds like a simple optimization of "equality", which would be a normal use of a GA. This would apply for both the division and the decision, depending on which side the GA is (the "you" or the "I") or two diff. GAs can be on either side of the process. -tkc From steve at REMOVE-THIS-cybersource.com.au Sun Mar 23 00:29:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 23 Mar 2008 04:29:50 -0000 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> Message-ID: <13ubn5ue821ak7e@corp.supernews.com> On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > On 22 Mar, 23:42, 7stud wrote: > >> Beginning programmers in grades 9-12 are not going to understand issues >> like that, and it would be a mistake to try and introduce them. >> Beginning programmers should be concentrating their efforts on learning >> the syntax of a language and basic constructs like for-loops and if >> statements. > > Yes. And because Python is a "scripting language" Python is a programming language. It can be used for scripting, but that's not all it can do. Describing it as a "scripting language" is like describing a fully-equipped professional kitchen as "a left-over warming room". -- Steven From marko at pacujo.net Thu Mar 13 07:45:33 2008 From: marko at pacujo.net (Marko Rauhamaa) Date: 13 Mar 2008 13:45:33 +0200 Subject: subprocess.Popen pipeline bug? Message-ID: This tiny program hangs: ======================================================================== #!/usr/bin/env python import subprocess a = subprocess.Popen('cat',shell = True,stdin = subprocess.PIPE, stdout = subprocess.PIPE) b = subprocess.Popen('cat >/dev/null',shell = True,stdin = a.stdout) a.stdin.close() b.wait() # hangs a.wait() # never reached ======================================================================== It shouldn't, should it? Environment: ======================================================================== Python 2.5.1 (r251:54863, Jun 20 2007, 12:14:09) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 ======================================================================== Marko -- Marko Rauhamaa mailto:marko at pacujo.net http://pacujo.net/marko/ From steve at REMOVE-THIS-cybersource.com.au Wed Mar 12 20:03:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 13 Mar 2008 00:03:23 -0000 Subject: Is there Python equivalent to Perl BEGIN{} block? References: Message-ID: <13tgrqb132if842@corp.supernews.com> On Wed, 12 Mar 2008 11:19:05 -0700, Alex wrote: > Hi all, > > The subject says pretty much all Only to people who know what the Perl BEGIN{} block means. -- Steven From 018worker at gmail.com Thu Mar 6 05:23:43 2008 From: 018worker at gmail.com (018worker at gmail.com) Date: Thu, 6 Mar 2008 02:23:43 -0800 (PST) Subject: Worldwide computer based Home Workers Needed. Message-ID: <26c58520-d5fd-401f-88cb-9e46c37eaf46@q78g2000hsh.googlegroups.com> Worldwide computer based Home Workers Needed. Earn by doing simple Computer Jobs. No Selling Required. No Going out of Home. No Office. No Boss Not a 9 to 5 job. No experience required. Simple Jobs. Basic knowledge of Computers and Internet is enough. Suitable for housewives, students, workers, retired persons and youths. For further details please visit: http://onlinejob7.googlepages.com From kyosohma at gmail.com Fri Mar 7 11:33:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 7 Mar 2008 08:33:59 -0800 (PST) Subject: Keep a python script running after browser window closed References: Message-ID: On Mar 7, 10:28 am, sophie_newbie wrote: > Hi, > > I have a cgi script that performs a very long computation that can > take several hours to complete. Is there any smart way that I can keep > this script running until it is finished (after the user has closed > the browser) and email them with the results. The email bit isn't the > problem, I just don't know how to keep the code running in the > background. I'm sure there is a smart way to do this... > > Thanks! You might have your cgi script use the subprocess module to open a second script that does the long-running process. Mike From jgardner at jonathangardner.net Fri Mar 21 10:16:14 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Mar 2008 07:16:14 -0700 (PDT) Subject: eval and unicode References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: On Mar 21, 1:54?am, Laszlo Nagy wrote: > ?>>> eval( "# -*- coding: latin2 -*-\n" + expr) > u'\u0170' # You can specify the encoding for eval, that is cool. > I didn't think of that. That's pretty cool. > I hope it is clear now. ?Inside eval, an unicode object was created from > a binary string. I just discovered that PEP 0263 can be used to specify > source encoding for eval. But still there is a problem: eval should not > assume that the expression is in any particular encoding. When it sees > something like '\xdb' then it should raise a SyntaxError - same error > that you should get when running a .py file containing the same expression: > > ?>>> file('test.py','wb+').write(expr + "\n") > ?>>> ^D > gandalf at saturnus:~$ python test.py > ? File "test.py", line 1 > SyntaxError: Non-ASCII character '\xdb' in file test.py on line 1, but > no encoding declared; seehttp://www.python.org/peps/pep-0263.htmlfor > details > > Otherwise the interpretation of the expression will be ambiguous. If > there is any good reason why eval assumed a particular encoding in the > above example? > I'm not sure, but being in a terminal session means a lot can be inferred about what encoding a stream of bytes is in. I don't know off the top of my head where this would be stored or how Python tries to figure it out. > > My problem is solved anyway. Anytime I need to eval an expression, I'm > going to specify the encoding manually with # -*- coding: XXX -*-. It is > good to know that it works for eval and its counterparts. And it is > unambiguous. ?:-) > I would personally adopt the Py3k convention and work with text as unicode and bytes as byte strings. That is, you should pass in a unicode string every time to eval, and never a byte string. From aeneng at gmail.com Fri Mar 28 22:10:10 2008 From: aeneng at gmail.com (aeneng pan) Date: Fri, 28 Mar 2008 22:10:10 -0400 Subject: Error message from function definition Message-ID: <263d8c50803281910x32e5375h37fd8bfe10f9f36c@mail.gmail.com> Dear community members, I just start to use python in numerical calculation. and I encountered some difficulties when I define my own function. Here is a piece of codes to compute the cross product of two 3x1 vector. can any one help me to find what is wrong with it? please see the codes below. when I import this function, it is not correct. here is the message I got. >>> import cross Traceback (most recent call last): File "", line 1, in ? File "cross.py", line 8 ppp2=u[2]*v[0]-u[0]*v[2] ^ SyntaxError: invalid syntax Thank you very much. Neng ##cross.py## def cross(u,v): """input two vectors u and v in 3-D space, both are in column or are in row. output a cross product of vector w, in column or in row accordingly. w=u x v. The type of u, v, w are matrix type from optcvx.base.matrix.""" ppp1,ppp2,ppp3=0.0,0.0,0.0 ppp1=u[1]*v[2]-u[2]*v[1] ppp2=u[2]*v[0]-u[0]*v[2] ppp3=u[0]*v[1]-u[1]*v[0] # store the result of the cross product in u u[0]=ppp1 u[1]=ppp2 u[2]=ppp3 return u #return the cross product of vector u x v. if __name__=="__main__": from cvxopt.base import matrix u=matrix([1.0,0.0,0.0],(3,1)) v=matrix([0.0,1.0,0.0],(3,1)) print "the cross product, uxv, is w= %6.3f" % cross(u,v) -------------- next part -------------- An HTML attachment was scrubbed... URL: From shakefu at gmail.com Fri Mar 7 17:12:07 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:12:07 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <3df1411d-836f-4214-9115-b508247649e3@p73g2000hsd.googlegroups.com> On Mar 7, 4:10 pm, Mike Driscoll wrote: > On Mar 7, 4:08 pm, shak... at gmail.com wrote: > > > I'm new to python and I was wondering if there are any intelligent > > date/time parsing modules out there. I've looked at strptime (or > > whichever it is) and mxDateTime from the eGenix package. I need > > something to parse user input for a django app, and it's awesome to be > > able to write "last monday", "a year ago", or "10pm tuesday" like > > PHP's strtotime. > > > So are there any modules that allow for that kind of parsing? > > There's the dateutil module that's a fancy wrapper for the datetime > module. The author's site has lots of examples as well as the source: > > http://labix.org/python-dateutil > > I use it quite a bit. > > HTH > > Mike Holy Crap that was fast. I'll check it out - thanks for the help! Jacob From ocollioud at gmail.com Fri Mar 28 06:47:56 2008 From: ocollioud at gmail.com (olive) Date: Fri, 28 Mar 2008 03:47:56 -0700 (PDT) Subject: Eclipse and PyDev Package explorer References: <1d4e6f2b-a058-413e-a566-674ccc733d6f@s19g2000prg.googlegroups.com> Message-ID: <02a2d458-ba16-4a48-9cda-1d65f7b858bb@f63g2000hsf.googlegroups.com> Hi, normally you just have to select your top level project folder in the Package Explorer and then from the menu bar choose Project -> Close Project (also accessible by the popup menu assigned to the right button of your mouse). HTH, Olivier. From tjreedy at udel.edu Thu Mar 6 14:30:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Mar 2008 14:30:09 -0500 Subject: Exploring Attributes and Methods References: <6018ff8f-3372-42c2-9a2e-5ca996744d5b@e6g2000prf.googlegroups.com> Message-ID: wrote in message news:6018ff8f-3372-42c2-9a2e-5ca996744d5b at e6g2000prf.googlegroups.com... | Hi, | Is there a python command that allows me to extract the names (not | values) of the attributes of a class. | | example | | Class Sample: | fullname = 'Something' | | How can I know that this class has an attribute called 'fullname'? >>> class C: a = 1 >>> dir(C) ['__doc__', '__module__', 'a'] From deets at nospam.web.de Sun Mar 9 13:36:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 18:36:18 +0100 Subject: Need Help Building PythonQt on Windows In-Reply-To: References: Message-ID: <63ilglF28106hU1@mid.uni-berlin.de> Jeff Schiller schrieb: > Hello, > > I'm creating an application using Qt (4.4 Beta atm). I have pretty > close to zero experience with Python (consisting of installing the > Python interpreter, downloading a python programming and executing it > on the command-line). > > I would like to invoke a Python script from my C++ Qt program and > capture its output as a C++ structure. It seems that PythonQt might > be suitable for my needs. > > Being a Qt program, I want this thing to be cross-platform. I'm > having trouble getting things set up in Windows. Has anyone had any > experience with this? > > I've built Qt from source using the mingw32 compiler. I installed > Python 2.5 binary. I am trying to build PythonQt from source. As per > http://pythonqt.sourceforge.net/#Building it says I need a "developer > installation" of Python containing the header files and the library > files. When I look at my system after installing the Python 2.5 > binary, I can see I have header files (C:\Python25\include), a 199k > python25.lib (C:\Python25\libs) and a 2MB python25.dll > (C:\Windows\System32\). Have I got what I need? > > I have tried to set up my symbols (PYTHON_PATH, PYTHON_LIB, > PYTHONQT_ROOT). I generate the Makefile (using qmake) and it starts > to build but then it fails: > > g++ -enable-stdcall-fixup -Wl,-enable-auto-import > -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -shared > -Wl,--out-implib,lib\libPythonQt.a -o lib\PythonQt.dll > object_script.PythonQt.Debug -L"c:\Qt\4.4.0-beta1\lib" > "c:\Python25\libs"/python25.lib -lQtGuid4 -lQtCored4 > ./debug\PythonQt.o: In function `ZN8PythonQtC2Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN8PythonQtC1Ei': > C:/PythonQt-1.0/src/PythonQt.cpp:118: undefined reference to > `_imp__Py_NoSiteFlag' > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate11wrapQObjectEP7QObject': > C:/PythonQt-1.0/src/PythonQt.cpp:256: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:257: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function `ZN15PythonQtPrivate7wrapPtrEPvRK10QByteArray': > C:/PythonQt-1.0/src/PythonQt.cpp:281: undefined reference to > `_imp___Py_NoneStruct' > C:/PythonQt-1.0/src/PythonQt.cpp:282: undefined reference to > `_imp___Py_NoneStruct' > ./debug\PythonQt.o: In function > `ZN8PythonQt13introspectionEP7_objectRK7QStringNS_10ObjectTypeE': > C:/PythonQt-1.0/src/PythonQt.cpp:620: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyClass_Type' > C:/PythonQt-1.0/src/PythonQt.cpp:625: undefined reference to > `_imp__PyCFunction_Type' > ... > > Since I'm new to compiling Qt with mingw and completely new to python, > I was hoping for tips on why I'm getting these errors. If anyone has > a better suggestion for a forum/mailing list then please let me know. A few of suggestions: - take this to the PyQt mailing list (http://www.riverbankcomputing.com/mailman/listinfo/pyqt) - you only *need* pyqt if what you want to do in python has really to deal with Qt-objects - maybe "simple" embedding is enough for your needs - I don't see why you need to compile PyQt yourself at all - are you sure you can't use the stock PyQt for windows? What makes you believe you really need this to be self-compiled? Diez From piet at cs.uu.nl Mon Mar 10 11:24:56 2008 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 10 Mar 2008 16:24:56 +0100 Subject: float / rounding question References: <13t48m9l27s2q78@corp.supernews.com> Message-ID: >>>>> Dennis Lee Bieber (DLB) wrote: >DLB> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum >DLB> declaimed the following in comp.lang.python: >>> Sorry to come in so late in this discussion. Although it is correct to say >>> that many real numbers that have an exact decimal representation cannot be >>> exactly represented in binary, that is no excuse to print 53.6 as >>> 53.600000000000001. This is just lousy printing and the fact that this kind >>> of question comes up every week shows that it is confusing to many people. >>> >>>>> 53.6 >DLB> 53.600000000000001 >>>>> print 53.6 >DLB> 53.6 >>>>> print str(53.6) >DLB> 53.6 >>>>> print repr(53.6) >DLB> 53.600000000000001 >>>>> >DLB> Looks like "print" already does what you expect. No, what you see is not the behaviour of `print' but of `str'. `print' uses `str' to do the formatting instead of `repr' whereas the interactive prompt uses `str'. `str' is meant to please the human reader, and `repr' is supposed to give you something that you can use as input and get exactly the same value. But `str' does it by just giving you less accuracy, thus sweeping the problem under the carpet: >>> str(53.59999999999) 53.6 >>> 53.59999999999==53.6 False >>> repr(53.59999999999) '53.599999999989997' >>> 53.599999999989997==53.59999999999 True >>> repr(53.6) '53.600000000000001' >>> 53.600000000000001==53.6 True -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From max at alcyone.com Thu Mar 13 19:22:51 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Mar 2008 16:22:51 -0700 Subject: List mutation method gotcha - How well known? In-Reply-To: <9a1d9da3-42a7-4138-b53b-9ee690b77b7e@p73g2000hsd.googlegroups.com> References: <9a1d9da3-42a7-4138-b53b-9ee690b77b7e@p73g2000hsd.googlegroups.com> Message-ID: Chris wrote: > No output because x is a NoneType... That's behavior of the interactive interpreter when printing results of expressions, not of print. It will print None. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There is no present or future; only the past, happening over and over again, now. -- Eugene O'Neill From nick.fabry at coredump.us Wed Mar 19 21:11:14 2008 From: nick.fabry at coredump.us (Nicholas F. Fabry) Date: Wed, 19 Mar 2008 21:11:14 -0400 Subject: Improving datetime In-Reply-To: <13u353a51v9kp36@corp.supernews.com> References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> <13u353a51v9kp36@corp.supernews.com> Message-ID: <5062F606-8D43-4393-B7B9-E06E38C00C96@coredump.us> On Mar 19, 2008, at 18:32, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote: > >> To summarize my proposal VERY briefly: >> >> >> - Make aware datetime objects display in local time, but calculate/ >> compare in UTC. > > Your proposal is ambiguous. What does that mean? Can you give an > example? > > That's why I said it was the VERY brief version - here is a longer version. I would like a datetime to display local times, since if I create it with a specific tzinfo timezone, that implies I'm interested in what clocks in that time zone say. For example: >>> from datetime import datetime >>> from dateutil.tz import gettz >>> NYC = gettz('America/New_York') >>> UTC = gettz('UTC') >>> wake_up_time = datetime(2008,3,8,15,30,0,tzinfo=NYC) >>> print wake_up_time 2008-03-08 15:30:00-05:00 >>> print wake_up_time.hour 15 This is the behavior I want - if I create a datetime in a specific timezone, I wish to know the member information (date, hour, second, etc.) in that timezone. However, when I calculate with it, I can get wrong answers. >>> a_later_time = datetime(2008,3,9,15,30,0,tzinfo=NYC) >>> print a_later_time - wake_up_time 1 day, 0:00:00 This is incorrect, because a_later_time is in daylight saving time, but the eariler time is in standard time - the gap is actually 23:00 hours. >>> print a_later_time.astimezone(UTC) - wake_up_time.astimezone(UTC) 23:00 The reason datetime performs this calculation incorrectly is documented - if the tzinfo members are the same object, it ignores them and makes the calculation as though the two datetimes were naive. If the tzinfo objects are different, even if they correspond to the exact same ruleset, then datetime does the job correctly. >>> import copy >>> ALT_NYC = copy.deepcopy(NYC) >>> the_same_later_time = datetime(2008,3,9,15,30,0,tzinfo=ALT_NYC) >>> print the_same_later_time - wake_up_time 23:00 The results of the calculation should not be dependent on whether the tzinfo object is the same or not, but what it's .utcoffset() method returns. Or, to summarize, ALL calculations with aware datetime objects should first change the datetime objects to UTC so the calculations are done correctly. Changing all times to UTC creation, aside from making ugly code, now forces a conversion back to local time, with more code, any time you want to display date and time information in the local time zone. This is not a good, pythonic solution. > > >> - Raise exceptions when an illegal or ambiguous datetime is >> instantated. > > You mean like they already do? > >>>> datetime.datetime(2008, 03, 35) # 35th of March > Traceback (most recent call last): > File "", line 1, in > ValueError: day is out of range for month > > However, the following does NOT raise an exception, and it should. >>> a_time = datetime(2008, 3, 9, 1, 30, 0, tzinfo=NYC) >>> print a_time 2008-03-09 01:30:00-05:00 The problem is that there IS no local wallclock time of 0130 on March 9, 2008 in New York. At 0100, local clocks jump to 0200 and proceed from there. A local wallclock time of 0130 on March 9, 2008 in New York is meaningless - it should not occur. Therefore, if a programmer is (for example) parsing local times (say, out of a schedule book), and an illegal time like this appears, instead of an exception immediately being raised to alert him/her of the faulty source data, the program *assumes* the illegal local time was 'meant' to be in standard time, and sends it merrily on its way... making it much harder when errors crop up later to figure out their source. > > > As for ambiguous, how can datetime arguments be ambiguous? > > Help on class datetime in module datetime: > > class datetime(date) > | datetime(year, month, day[, hour[, minute[, second[, > microsecond[,tzinfo]]]]]) > > > What possible ambiguity is there? > Continuing on from before: >>> b_time = datetime(2008, 11, 2, 1, 30, 0, tzinfo=NYC) >>> print b_time 2008-11-02 01:30:00-05:00 There is a little problem with this, though. At 2008 Nov 2 at 0200 Eastern Daylight Time, the clocks swing back one hour, to 0100, and essentially repeat the hour between 0100 and 0200 again. So - is b_time 0130 Eastern STANDARD Time, or is it 0130 Eastern DAYLIGHT Time? Simply providing a tzinfo class does not resolve this ambiguity, so it is again *assumed* that you 'meant' standard time. That may or may not be true, depending on the source data and other external factors. A good datetime library (or tzinfo library) should alert you to this fact. Isn't Explict better than Implicit? A further problem is that it is now impossible to specify using tzinfo = NYC, a time corresponding to 2008 Nov 2, 0530 UTC, or in other words, 2008 Nov 2 0130 EDT. If you try it directly, as above, you get 2008 Nov 2 0130 EST, which is 0630 UTC. If you create the time 2008 Nov 2 0530 UTC, and then use .astimezone(NYC), you will get the same result.... 2008 Nov 2 0130 EST, which is not the EDT time we wanted, nor is it equal to 0530 UTC. >>> c_time = datetime(2008,11,2,5,30,0,tzinfo=UTC) >>> print c_time.astimezone(NYC) 2008-11-02 01:30:00-05:00 >>> print c_time.astimezone(NYC).astimezone(UTC) == c_time False These problems all stem from the fact that local times are used for internal storage, when in certain circumstances they do not uniquely specify a real time. This could be fixed by making each datetime object really have TWO datetime objects within it - one that corresponds to UTC (so it is unambigious what real time it refers to, and so calculations can speedily access UTC time), and one that corresponds to local wallclock time (so it is known what the local wallclocks are displaying, and allowing efficient member extraction and not breaking existing code). This is the moderately short and casual version of it. Nick P.S. The code in full form, to follow along better: from datetime import datetime from dateutil.tz import gettz NYC = gettz('America/New_York') UTC = gettz('UTC') wake_up_time = datetime(2008,3,8,15,30,0,tzinfo=NYC) print wake_up_time #2008-03-08 15:30:00-05:00 print wake_up_time.hour #15 a_later_time = datetime(2008,3,9,15,30,0,tzinfo=NYC) print a_later_time - wake_up_time #1 day, 0:00:00 print a_later_time.astimezone(UTC) - wake_up_time.astimezone(UTC) #23:00 import copy ALT_NYC = copy.deepcopy(NYC) the_same_later_time = datetime(2008,3,9,15,30,0,tzinfo=ALT_NYC) print the_same_later_time - wake_up_time #23:00 a_time = datetime(2008, 3, 9, 1, 30, 0, tzinfo=NYC) print a_time #2008-03-09 01:30:00-05:00 b_time = datetime(2008, 11, 2, 1, 30, 0, tzinfo=NYC) print b_time #2008-11-02 01:30:00-05:00 c_time = datetime(2008,11,2,5,30,0,tzinfo=UTC) print c_time.astimezone(NYC) #2008-11-02 01:30:00-05:00 print c_time.astimezone(NYC).astimezone(UTC) == c_time #False > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Mar 19 19:06:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Mar 2008 16:06:46 -0700 (PDT) Subject: finding items that occur more than once in a list References: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> <5cf59226-98b6-4ad8-9fbc-ac63d7b7579b@s37g2000prg.googlegroups.com> <38b99788-7fbe-4afa-b429-878c4bc55142@e23g2000prf.googlegroups.com> <36b3e11b-1c55-4238-a06d-2f2158e7ad86@i12g2000prf.googlegroups.com> Message-ID: On Mar 20, 9:57 am, Justin Bozonier wrote: > On Mar 19, 2:48 pm, John Machin wrote: > > > > > On Mar 19, 10:08 am, sturlamolden wrote: > > > > On 18 Mar, 23:45, Arnaud Delobelle wrote: > > > > > > def nonunique(lst): > > > > > slst = sorted(lst) > > > > > dups = [s[0] for s in > > > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))] > > > > > return [dups[0]] + [s[1] for s in > > > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))] > > > > > Argh! What's wrong with something like: > > > > > def duplicates(l): > > > > i = j = object() > > > > for k in sorted(l): > > > > if i != j == k: yield k > > > > i, j = j, k > > > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N) > > > as opposed to ours which are O(N log N). > > > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's, > > and is IMHO more readable than Paul's. > > It's not as much O(N)... Paul Robin's uses a sort first which is > definitely not O(N). Paul's could be prettied up a bit but the general > principle is sound. """ from collections import defaultdict def nonunique(lst): d = defaultdict(int) for x in lst: d[x] += 1 return [x for x,n in d.iterkeys() if n > 1] """ I see no sort here. From ocollioud at gmail.com Mon Mar 31 13:56:52 2008 From: ocollioud at gmail.com (olive) Date: Mon, 31 Mar 2008 10:56:52 -0700 (PDT) Subject: Of qooxdoo, qwt, and Python References: <28f7384f-b8d1-430d-9e0d-389ebae7eefd@e10g2000prf.googlegroups.com> Message-ID: <51c2f4c2-8752-49e3-81f8-77094c078015@k13g2000hse.googlegroups.com> On 31 mar, 18:05, John Henry wrote: > I was searching for a way to redevelop a desktop Pythoncard based > program into a web-application. I understand what need to be done for > all of the non-GUI code. For the GUI capabilities, I stumbled across > a package call qooxdoo (http://qooxdoo.org/). It appears to provide > the GUI capabilities I need. Then I saw that there is qwt - which > allows you to write qooxdoo code in pure Java. Since I don't know > Java (or don't want to know), is there a similar path I can take using > Python? > > Regards, you could try this http://code.google.com/p/pyjamas/ or http://doc.appcelerator.org/overview/what_is_appcelerator/index.html or maybe jython with any java based toolkit (qwt, zk ...). Regards. From d3vvnull at gmail.com Tue Mar 18 12:53:43 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 18 Mar 2008 11:53:43 -0500 Subject: Need Help Starting Out In-Reply-To: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> Message-ID: <170543c70803180953u56137ed6g15e45a4e6c2fc013@mail.gmail.com> Pylons is a Ruby on Rails-like web framework that allows you build dynamic web applications with a database backend. Here is a link to the Pylons web site: http://pylonshq.com/ On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop wrote: > Hi, I would like to start using Python, but am unsure where to begin. > I know how to look up a tutorial and learn the language, but not what > all technologies to use. I saw references to plain Python, Django, > and other things. > > I want to use it for web building with database access. What do I use > for that? Does it matter what I use on the client side (mootools, or > whatever)? > > My rational for using Python is because I am hoping it will allow me > to better understand other python programs in other areas, not just > web. I have used other languages for web apps for several years. > Truth is that I always wanted to learn Python and have heard it was a > good thing to know. > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Fri Mar 14 06:33:39 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Mar 2008 10:33:39 GMT Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> <87skyvuhpo.fsf@rudin.co.uk> <13tj6omdip82f13@corp.supernews.com> Message-ID: On 2008-03-13, Steven D'Aprano wrote: > On Thu, 13 Mar 2008 08:54:43 +0000, Paul Rudin wrote: > >>> Whatever python has for a calling convention, it is close enough that >>> naming it "call by reference" gives people a reasonable idea of what is >>> going on. >> >> Quite. The thing is not to get hung up with the label - but to >> understand what actually happens. > > Agreed. And I think the best way to do that is to use the same terms that > other languages use to get very different behaviour indeed. > > "Python is call by reference, but this doesn't work like call by > reference in all the other languages I've used: > > def negate(n): > n = -n > > x = 2 > negate(x) > assert x == -2 > > Is this a bug, or is Python actually call by value?" > And now comes the explanations that Python is actually call by value, but > the values being copied are *pointers* (ignoring Jython, IronPython and > PyPy); or that Python is really call by reference, but different > "things" (it's never quite clear what exactly) happen depending on > whether the arguments are mutable or immutable; Which is wrong. The same thing happens with mutable and immutable objects. What one needs to understand is: Right after the call, x and n are the same object. After the assigment x and n no longer are the same object. The assignment doesn't negate the original object. It creates a new object with the negative value of the original while the latter remains bound to x. As long as the person who has trouble with this behaviour doesn't understand that the assignment is not a mutating operator. Your explanation will get you nowhere. The trouble is mosly caused because people see a line like n = -n and interpret this more or less as the object bound to n has the negated value after the assignment. That is why they think x should be -2 in your example. > or that if you define > reference broadly enough, everything is a reference; or that if you > define value broadly enough, everything is a value; or if schools would > just stop teaching kiddies C and start teaching them Lisp, call by > reference semantics would be understood in a different way, or or or or... > And thus, by insisting that there are two and only two calling > conventions, no matter how many different kinds of calling behaviour > actually exist, we ensure that we'll be having this same *&$%^*# argument > when Python 4000 comes out. But you seem to make the same kind of mistake, but with regard to assignments. You seem to implicitly assume there is only one kind of assignment and by trying to start from there and trying to explain what goes on in terms of different calling conventions you will ensure the same argument just as well. -- Antoon Pardon From george.sakkis at gmail.com Wed Mar 26 21:02:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 26 Mar 2008 18:02:35 -0700 (PDT) Subject: Not understanding lamdas and scoping References: Message-ID: On Mar 26, 6:03 pm, Joshua Kugler wrote: > George Sakkis wrote: > > On Mar 26, 5:02 pm, Joshua Kugler wrote: > > >> I am trying to use lamdba to generate some functions, and it is not > >> working > >> the way I'd expect. The code is below, followed by the results I'm > >> getting. More comments below that. > > >> (...) > > >> So, is there some scoping issue with lambda > >> that I'm not seeing? > > > Yes; it's not related to lambda though but to closures (whether > > defined as lambdas or regular functions). See for example > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/94d... > > > > > There should be an entry for this at > >http://www.python.org/doc/faq/programming/, that's really an FAQ. > > George - > > Thanks for the quick and clear answer...that makes perfect sense. To > bad...I'd like to just use a list comprehension. :) Did you actually read the replies on that thread ? You _can_ use a list comprehension or a loop, all you have to do is bind the passed values as default parameters: rules = [make_pattern(pattern=p, search=s, replace=r) for (p,s,r) in patterns] George From sjdevnull at yahoo.com Sat Mar 8 23:45:25 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sat, 8 Mar 2008 20:45:25 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: On Mar 8, 7:34 pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: > > I'm also a bit baffled by people who put a comment at the top of every > > file that tells you what the filename is. > > [snip rant] > > You've never printed out a source file on pieces of dead tree to read on > the train on the way home, or in bed or the bath? > > Yes, some editors will print a header or footer showing the file name, > but not all will, or are configured to do so. The only times I can recall printing source were in college classes where I was required to hand in a hardcopy with the assignment and code samples for job interviews. In the real world the code base tends to be too huge to contemplate printing, especially when I'd then be stuck without sane ways to navigate around (tags, search, oobr, etc). For instance, our project right now is around 350,000 lines of python and about 300,000 of DTML/mako templates. I expect the availability of laptops since I really started working as a programmer in the mid-1990s biases me a bit compared to earlier times. Even in the early 1990s the moral equivalent of enscript (I think it was a2ps) worked just fine for printing with filenames, line/page numbers, and other niceties no matter what editor you used. It seems more reasonable to mandate using a sane print tool for the odd case where someone wants to print things out than to mandate cluttering up every file with the filename in a comment. From madduck at madduck.net Mon Mar 17 12:41:23 2008 From: madduck at madduck.net (martin f krafft) Date: Mon, 17 Mar 2008 17:41:23 +0100 Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? In-Reply-To: <20080316132140.GA24529@piper.oerlikon.madduck.net> References: <20080316132140.GA24529@piper.oerlikon.madduck.net> Message-ID: <20080317164123.GA1988@piper.oerlikon.madduck.net> also sprach martin f krafft [2008.03.16.1421 +0100]: > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' There's a difference between those two. The first one has an empty string value ('') while the second one pretty clearly says that there is a parameter but has no value. Why ? -- martin | http://madduck.net/ | http://two.sentenc.es/ all software projects are done by iterative prototyping. some companies call their prototypes "releases", that's all. spamtraps: madduck.bogus at madduck.net -------------- next part -------------- A non-text attachment was scrubbed... Name: digital_signature_gpg.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature (see http://martin-krafft.net/gpg/) URL: From fuzzyman at gmail.com Sun Mar 16 11:00:48 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 16 Mar 2008 08:00:48 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <7e9cad5e-265d-4285-a26b-df9489937972@e39g2000hsf.googlegroups.com> > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan That's a great quote that I had not heard before. :-) Michael Foord http://www.manning.com/foord From darcy at druid.net Sun Mar 16 12:47:28 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 16 Mar 2008 12:47:28 -0400 Subject: Basics of Python,learning In-Reply-To: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> References: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <20080316124728.007c164c.darcy@druid.net> On Sun, 16 Mar 2008 17:25:26 +0100 Guido van Brakel wrote: > Hello > > Why is this not working,and how can I correct it? What are you expecting it to do? For one thing, you are acting on a variable 'a' but it is never defined. The only objects that you have is z, y, b and then b is redefined as a method which creates a variable 'x', overwrites it twice and then discards it. Doesn't matter since you never call the method anyway. Back to the textbook I think. -- 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 jasong at gmail.com Tue Mar 4 22:46:45 2008 From: jasong at gmail.com (Jason Galyon) Date: Tue, 04 Mar 2008 21:46:45 -0600 Subject: multiplication of lists of strings In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Tue, 04 Mar 2008 23:50:49 -0200, Jason escribi?: > >> How could I return a list or tuple of each unique combination of a given >> set of lists (perhaps from a dict or a list). This means the number of >> lists are not known nor is the length of each. > > Use the Google interfase for this group: > http://groups.google.com/group/comp.lang.python/ > Type "unique combinations lists" in the text box; press "Search in this > group". The very first result contains some answers to your question. > found it, the referenced cookbook recipe is perfect. Thanks, Gabriel From tibit at sonic.net Mon Mar 31 13:15:56 2008 From: tibit at sonic.net (Forest) Date: Mon, 31 Mar 2008 10:15:56 -0700 (PDT) Subject: why does socket.makefile require non-blocking mode? Message-ID: <18907.75.55.199.5.1206983756.squirrel@webmail.sonic.net> On Sat, 29 Mar 2008 08:18:23 -0300, Guilherme Polo wrote: >I don't know why you think timeout is forbidden too, it is not. I can't tell for sure whether it is or isn't, because of this language in the socket module docs: "s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1)." >>I wanted to use file-like objects with socket timeouts, so I ended up >>writing my own replacement for socket._fileobject. I'd appreciate it >>if someone could either explain to me why my new class was unnecessary, >>or else encourage me to contribute it as a patch to the socket module. > >It looks like to be unnecessary. I'm hoping for a more definitive answer than "looks like", but thank you just the same. My main concern is this: A brief look at the existing socket._fileobject shows that its read() method calls recv() in a loop, appending to a temporary buffer on each pass, and finally returning the buffer when recv() gets no more data. It looks to me like a socket timeout exception would cause that loop to exit without saving the data collected in earlier passes. In other words, data loss on recv() timeout. If someone more familiar with socket._fileobject can point out a reason this cannot happen (perhaps I've missed something) I'll be satisfied. Otherwise, I think my rewritten class has value. From steveo at syslang.net Mon Mar 31 12:32:38 2008 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 31 Mar 2008 12:32:38 -0400 (EDT) Subject: Looking for indent advice howto in emacs python-mode Message-ID: Here's what I want to do: if ( ( v == 1 ) or ( v == 2 ) or ( v == 3 ) ): pass but emacs (left to its own devices, does this. if ( ( v == 1 ) or ( v == 2 ) or ( v == 3 ) ): pass It works great for me in C-mode. Does anyone know how to jimmie up python-mode so it would know how to do this? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From sjmachin at lexicon.net Mon Mar 10 16:57:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 10 Mar 2008 13:57:19 -0700 (PDT) Subject: any chance regular expressions are cached? References: <51172306-ff2d-48e8-81cf-93be03f8a08f@s37g2000prg.googlegroups.com> Message-ID: On Mar 10, 3:42 pm, John Machin wrote rather baroquely: > ...>>> def myfunc(s, spaces): > > ... return '\n'.join(spaces + x.rstrip() if x.rstrip() else '' for > x in s.splitlines()) Better: ... return '\n'.join((spaces + x).rstrip() for x in s.splitlines()) From nexes128 at gmail.com Sat Mar 1 11:58:32 2008 From: nexes128 at gmail.com (nexes) Date: Sat, 1 Mar 2008 08:58:32 -0800 (PST) Subject: SQLLITE Message-ID: <1c40a09c-80bd-4d4f-a82c-535afe8cc6da@e23g2000prf.googlegroups.com> Hello All, I am having a minor problem when I try and do this: c.execute("insert into [tblTranscripts] (MovieID,Transcript) Values(" + movieID + ",'" + formatText + "');") (don't even bother commenting of the sql style I know its bad form but this is a simple script). Whenever I try and do the insert I get table not found, however when I perform the sql through sqlite's command line program (the sql is outputted via a print statement) it works fine. Any ideas? From castironpi at gmail.com Fri Mar 7 20:04:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 17:04:54 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> <13t3gq9qo0po5ce@corp.supernews.com> <81d37ead-edd9-4666-8adb-5b5da45c6321@k2g2000hse.googlegroups.com> Message-ID: On Mar 7, 5:00?pm, shak... at gmail.com wrote: > On Mar 7, 4:35 pm, Jeffrey Froman wrote: > > > shak... at gmail.com wrote: > > > I need > > > something to parse user input for a django app, and it's awesome to be > > > able to write "last monday", "a year ago", or "10pm tuesday" like > > > PHP's strtotime. > > > Django comes with some pretty handy filters for doing this sort of > > formatting. Check out the "date", "now", "timesince" and "timeuntil" > > filters here: > > >http://www.djangoproject.com/documentation/templates/#built-in-filter... > > > Jeffrey > > Very cool - that's definitely handy to know for the output side of > things. I was mostly interested in writing a custom widget for > handling datetime input, 'cause I can't imagine anyone being studious > enough to use the 2008-03-07 12:00:00 format all the time... besides, > it's hard to type! I'd much rather allow for users to just be able to > type "12pm today". > > So much to learn, so little time! > > Jacob With some acquaintence with the user, a program can even honor, "remind me 'later' to...". Will you assign meanings to weird ambiguities like, 'last February' (No, I mean laaaaaaast February.) if it's April and "tomorrow" if it's 4 a.m.? Just raise an exception: TimeOfDayException: "Yes, but it's 4 a.m." (or, Those probabilities are close.) The vocabulary for referring to time isn't that large. What did I miss? Yesterday, today, tomorrow, ago, from now, later, after, before, [units], [absolutes], wikipedia. But what's the elegant way to structure the expression? From steve at holdenweb.com Sat Mar 1 00:39:56 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 00:39:56 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <3f7980f4-9b07-46dc-a3d9-b333d0a29646@s12g2000prg.googlegroups.com> References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> <13sd3rnokh1975d@corp.supernews.com> <13sfb24231sjbb5@corp.supernews.com> <3f7980f4-9b07-46dc-a3d9-b333d0a29646@s12g2000prg.googlegroups.com> Message-ID: Dan Bishop wrote: > On Feb 29, 12:55 am, Dennis Lee Bieber wrote: >> On Thu, 28 Feb 2008 10:39:51 -0000, Steven D'Aprano >> declaimed the following in >> comp.lang.python: >> >>> By that logic, we should see this: >>>>>> len("a string") >>> '8' >> Why? len() is a function that /counts/ the elements of the argument >> -- said count remains in integral value (I presume we don't have a 1.5 >> character long string) > > The relevant point is that len() is a function that returns a > DIFFERENT type than its argument, and nobody ever complains about is. > A language that restricted its functions to returning the same types as its arguments wouldn't be very much use, would it? And what about functions that have multiple arguments of different types? >>> And rightly rejected by many other programming languages, including >>> modern Python, not to mention calculators, real mathematics and common >>> sense. >> I know of no calculator that has "integers" for normal math -- and >> the HP50 even emphasizes this by putting a decimal point into "integer" >> quantities. Heck -- most calculators work in BCD floats. Most merely >> suppress the decimal point if the trailing digits are all 0s > > My TI-89 treats them differently: 1.0/2.0 is 0.5, while 1/2 is the > symbolic expression 1/2. Any you don't even have to import anything from __future__! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at holdenweb.com Tue Mar 4 08:05:57 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 08:05:57 -0500 Subject: pySQLite Insert speed In-Reply-To: <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: mmm wrote: > Steve, I think you were right the first time is saying > >> it should really be this: >> sqlxb= 'INSERT INTO DTABLE2 VALUES (?, ?, ?, ?)' > > my copy.copy() has the equivalent effect. > > Running this test code produces the output below > > import copy > > print 'Test 1' > pf= '?,?,?,?' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print sqlx1 > > print > print 'Test 2' > sqlx2= copy.copy(sqlx1) > sqlx3= sqlx1 > pf= '?,?,?, ****' > sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf > print 'sqlx1= ', sqlx1 > print 'sqlx2= ', sqlx2 > print 'sqlx3= ', sqlx2 > > == output > Test group 1 > INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > Test group 2 > sqlx1= INSERT INTO DTABLE2 VALUES ( ?,?,?, **** ) > sqlx2= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > sqlx3= INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) > > I interpret this to mean that sqlx1 is not a simple string Sorry, since you didn't copy and paste the actual code you ran I don't regard those results as reliable. What I will repeat, however, is that while there is a *slight* difference is semantics between s = "some string" s1 = s and s = "some string" s1 = copy.copy(s) that difference is only to ensure that s and s1 point to different copies of the same string in the latter case, whereas in the former case s and s1 point to the same string. Since strings are immutable in Python this really doesn't make any difference. In either case changing the value of s will leave the value of s1 unchanged, since it will still point to the string it was originally bound to and s will point to some other string. I suspect some superstition is at play here, or possibly you are cargo cult programming :) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Wed Mar 19 21:56:17 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 22:56:17 -0300 Subject: [newbie] using ElementTree, how to add doctype and xml pi References: Message-ID: En Wed, 19 Mar 2008 20:53:49 -0300, dave berk escribi?: > I have an svg file i'm creating on the fly. How do I add the doctype and > xml > pi? They're not an element per se, and there is no function to add them. The easiest way (but perhaps not-so-pure) is to just write those lines by hand before the document itself; see a recent post about "Inserting DTD statement to XML" -- Gabriel Genellina From software at ginstrom.com Sun Mar 23 11:46:17 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Mon, 24 Mar 2008 00:46:17 +0900 Subject: Duplicating list of lists [newbie] In-Reply-To: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> References: <70ba063a-bf2b-4965-ae06-022b3c881b60@s19g2000prg.googlegroups.com> Message-ID: <078f01c88cfd$088b98c0$0203a8c0@MOUSE> > On Behalf Of yatsek at gmail.com > So - it looks that in list "b" there copy of all objects from list "a" > including not copy of list [5,6,7] but reference to it. > > Is there simple way to copy a into b (like a[:]) with all > copies of all objects going as deep as possible? Or it can be > done only manually? I'd suggest checking out copy.deepcopy. >>> a = [1, [1, 2, 3], 2] >>> b = a[:] >>> a[1][2] = 'spam' >>> b [1, [1, 2, 'spam'], 2] >>> from copy import deepcopy >>> b = deepcopy(a) >>> a[1][2] = 'deepcopy is your friend' >>> b [1, [1, 2, 'spam'], 2] Regards, Ryan Ginstrom From arnodel at googlemail.com Sun Mar 23 04:31:51 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 23 Mar 2008 01:31:51 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> <13uc4bpb0b564af@corp.supernews.com> Message-ID: <7a4c084f-ecb7-4ed4-8f3f-af29d811d44a@b64g2000hsa.googlegroups.com> On Mar 23, 8:14?am, Steven D'Aprano wrote: > On Sat, 22 Mar 2008 23:15:00 -0700, John Nagle wrote: > > That's some professor inventing his very own variation on predicate > > calculus and writing a book using his own notation and terminology. > > There's no sign of footnotes or references to prior work. ?The notation > > doesn't seem to do anything not previously possible; it's just > > different. > > You say that as if it were unusual in maths circles :) > Haha. As opposed to programmers who have all agreed to use the same language. Anyway, I have browsed the book and agree with Paul Rubin that there doesn't seem to be any unusual notation in it, although there are a numbers of topics that I am not really familiar with. -- Arnaud From tavares at fe.up.pt Thu Mar 6 09:15:33 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 6 Mar 2008 06:15:33 -0800 (PST) Subject: Int. J. of Tomography & Statistics, Special Issue on Image Processing - Call for papers Message-ID: (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) ****************************************************************************************************** Special issue on Image Processing Gest Editors: Jo?o Manuel R. S. Tavares & Renato M. Natal Jorge - UP - Portugal International Journal of Tomography & Statistics ISSN 0973-7294 (Online) - 0972-9976 (Print) http://www.isder.ceser.res.in/ijts.html ****************************************************************************************************** Dear Colleague, This special issue of the International Journal of Tomography & Statistics (IJT&S) is devoted to promote a broad exchange of information on technologies, applications, operations and quality assurance in the areas of Computed Tomography, Statistics as well as of Image Processing. This special issue on Image Processing is an opportunity for users, scientists, image equipment suppliers and all who are interested to present their works on image detectors and acquisition systems, signal processing, image processing and analysis, medical imaging, pattern analysis and recognition, volume scanning and reconstruction, features extraction and classification, telemedicine, virtual and augmented reality, enhanced computation and software applications of image processing. Thus, if you are working on the related areas of the special issue "Image Processing", It is an honour to invite you to submit your work to be published in the IJT&S. Important Dates and Instructions: Deadline for papers submission: 30/06/2008; Authors notification: 15/09/2008; Final version of accepted papers: 1/11/2008; If you intend to submit your work please notify as soon as possible the guest editors of your intention (tavares at fe.up.pt, rnatal at fe.up.pt); Papers for the special issue should be sent to the guest editors (tavares at fe.up.pt, rnatal at fe.up.pt); Instructions for authors are available at: http://www.isder.ceser.res.in/ijts/instr4a.html. With kind regards, Yours sincerely The Guest Editors Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) Renato M. Natal Jorge (rnatal at fe.up.pt) University of Porto, Portugal From tjreedy at udel.edu Sat Mar 1 16:32:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Mar 2008 16:32:11 -0500 Subject: A python STUN client is ready on Google Code. References: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> <8ce119530803010101w320b8d30md5112aebab6f7551@mail.gmail.com> Message-ID: "hawk gao" wrote in message news:8ce119530803010101w320b8d30md5112aebab6f7551 at mail.gmail.com... |I upload a new version. Add more print log into my code to help people | understand my program Announcements should include a short paragraph explaining what the announcement is about for those of us not in the know. IE, what is STUN? -- and therefore, what is a STUN client? From magdoll at gmail.com Tue Mar 11 18:43:40 2008 From: magdoll at gmail.com (Magdoll) Date: Tue, 11 Mar 2008 15:43:40 -0700 (PDT) Subject: merging intervals repeatedly References: Message-ID: <20b3dfb8-c5b7-4fd0-97a1-93f590f54595@u10g2000prn.googlegroups.com> Correct. I meant the final should be (1,30), (29,40), (50,100) On Mar 11, 3:41 pm, Magdoll wrote: > Hi, > > I have to read through a file that will give me a bunch of intervals. > My ultimate goal is to produce a final set of intervals such that not > two intervals overlap by more than N, where N is a predetermined > length. > > For example, I could read through this input: > (1,10), (3,15), (20,30),(29,40),(51,65),(62,100),(50,66) > > btw, the input is not guaranteed to be in any sorted order. > > say N = 5, so the final set should be > (1,15), (20, 30), (29, 40), (50, 100) > > Is there already some existing code in Python that I can easily take > advantage of to produce this? Right now I've written my own simple > solution, which is just to maintain a list of the intervals. I can use > the Interval module, but it doesn't really affect much. I read one > interval from the input file at a time, and use bisect to insert it in > order. The problem comes with merging, which sometimes can be > cascading. > > ex: > read (51,65) ==> put (51,65) in list > read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) > read (50,66) ==> merge with (51,65) to become (50,66) ==> now can > merge with (62,100) > > Of course I can check for cascading merges by pivoting around the > position where the insertion would've taken place...but just > wondering, is there some other nice way to do this? I also intuitively > don't sense a need for using trees, unless someone's already written > it, the interface is easy to use, and it won't result in more insert/ > delete/structure changes that nullifies its beauty...(also I'm not > using the output list for searching) > > Thanks in advance. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Mar 3 11:16:49 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 03 Mar 2008 17:16:49 +0100 Subject: Exception or not In-Reply-To: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> References: <17677b9e-1a53-4859-b931-ee2f158e7558@c33g2000hsd.googlegroups.com> Message-ID: <47cc2470$0$1688$426a74cc@news.free.fr> Monica Leko a ?crit : > Suppose you have some HTML forms which you would like to validate. > Every field can have different errors. For example, this are the > forms: > > username > password > etc > > And you want to validate them with some class. This is what the FormEncode package is for. From cwitts at gmail.com Tue Mar 11 02:52:50 2008 From: cwitts at gmail.com (Chris) Date: Mon, 10 Mar 2008 23:52:50 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <63i6j9F2793buU1@mid.uni-berlin.de> <63lqcuF27pbnbU1@mid.uni-berlin.de> Message-ID: <877541e6-1407-4c0d-9818-e500f38823d5@o77g2000hsf.googlegroups.com> If all you wanted was some grouping of exceptions why not something like... soft_exception_list = [IndexError, TypeError] hard_exception_list = [ZeroDivision] try: do_something() except Exception, e: if e.__class__ in soft_exception_list: handle_soft_exception() elif e.__class__ in hard_exception_list: handle_hard_exception() else: raise NotImplementedError Granted you're most likely looking for something that does this constantly on every line of code though... From tmp1 at viltersten.com Sat Mar 1 16:35:11 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 22:35:11 +0100 Subject: Where's GUI for Python? Message-ID: <62tvhmF256jk7U1@mid.individual.net> I'm certain there is an API for creating GUI's but as far i can find it in the http://docs.python.org/tut/tut.html the only "gui" is in "Guido". What do i miss? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From jeff.self at gmail.com Tue Mar 11 11:44:34 2008 From: jeff.self at gmail.com (jeffself) Date: Tue, 11 Mar 2008 08:44:34 -0700 (PDT) Subject: Python PDF + Pictures References: Message-ID: <6a34e7f9-96c4-4434-a7df-e7e83eabc58b@o77g2000hsf.googlegroups.com> On Mar 11, 5:00 am, "durumd... at gmail.com" wrote: > Hi, dear Python Masters! > > I wanna ask about the Python and PDF creating. > > I have many photos, and I wanna make some "presentation" from these > photos, a "thumbnail" like document with one image per one page. > > If I wanna make one document now I do this: > I execute a python script that create a html site with resized pictures, > and split this html site to 50 images per one html file. > Next I open these files in OpenOffice Writer by hand, and save them as > PDF document with poor quality (image compression 95%, image DPI 75). > This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that > can opened everywhere (because of PDF format). > > But I wanna automatize this process with python. > The technic that I will use is this: > 1.) Collect the files in dirs. > 2.) I process one dir in one time. > 3.) I get the files. > 4.) I resize them to max. 1024/768. > 5.) I put the actual image file to the PDF document. > 6.) After each 50. file I open new numbered PDF. > 7.) Every picture placed in one page, and every page orientation set up > as the picture orientation (Portrait or Landscape). > > The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. > > Do you knows about a PDF maker library with I can make this thing? > > Or other technic to simplify the making? > > Thanks for your help! > dd You might also want to take a look at ReportLab. Its a PDF library for Python. You can find it at http://www.reportlab.org/ From pstapley at howaboutnow.net Mon Mar 24 17:28:04 2008 From: pstapley at howaboutnow.net (Pete Stapley) Date: Mon, 24 Mar 2008 15:28:04 -0600 Subject: Reading new mail from outlook using Python In-Reply-To: <924616.42495.qm@web50105.mail.re2.yahoo.com> References: <924616.42495.qm@web50105.mail.re2.yahoo.com> Message-ID: <47E81CE4.10305@howaboutnow.net> Well on a FreeBSD/Unix system you can use the .forward to pipe the incoming mail for a user to a program. Below is the contents of my .forward that invokes procmail. "|/usr/local/bin/procmail -m /path/to/conf/.procmailrc" So I imagine you could do something like this in a .forward. "|/path/myprogram.py" SPJ wrote: > Hi, > > I am trying to create new tickets in the ticketing system using > python. When I receive new email from a particular address, I have to > trigger the python script and parse the mail in required format. > > The main hurdle here is, how to invoke the script on arrival of new > mail? I checked the outlook settings and found that it supports only > microsoft VB script and Jscript. Is there any other way? I mean, if I > make a daemon, how will it be notified of new mail? Is there any > python module that does this? > > I am not sure if this is the right place to ask this, since it is also > a microsoft related question. But any help is appreciated. > > Thanks, > SPJ > > > ------------------------------------------------------------------------ > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try > it now. > From zentraders at gmail.com Sat Mar 22 17:55:39 2008 From: zentraders at gmail.com (Zentrader) Date: Sat, 22 Mar 2008 14:55:39 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> <490c7712-c92e-47be-9264-b2867a402643@c19g2000prf.googlegroups.com> <4ac46cf9-6b49-41bb-aec2-7d0823c5a4b3@h11g2000prf.googlegroups.com> Message-ID: <0bfb2812-9041-4394-ae34-f6a15b9de6a0@e23g2000prf.googlegroups.com> > No one meant to laugh at you. Your naivete was not obvious. FWIW, a > sense of humor is a valuable possession in most Python-related > conversations. Perhaps someone can explain how telling something like this to the OP, who thinks this statement will work if 'one' and 'two' in f: is funny and not mean. In the words of whoever it was in "Gone With The Wind", frankly I don't give a damn (except to not mislead relative newbies). But this has wasted enough of everyone's time. From george.sakkis at gmail.com Tue Mar 18 00:31:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 17 Mar 2008 21:31:42 -0700 (PDT) Subject: Any fancy grep utility replacements out there? References: Message-ID: On Mar 17, 10:20 pm, "samsli... at gmail.com" wrote: > So I need to recursively grep a bunch of gzipped files. This can't be > easily done with grep, rgrep or zgrep. (I'm sure given the right > pipeline including using the find command it could be done....but > seems like a hassle). If it's for something quick & dirty, you can't beat the pipeline, e.g. something like: find some_dir -name "*gz" | xargs -i sh -c "echo '== {} =='; zcat {} | grep some_pattern" George From bearophileHUGS at lycos.com Tue Mar 4 08:27:56 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 4 Mar 2008 05:27:56 -0800 (PST) Subject: for-else Message-ID: So far in Python I've almost hated the 'else' of the 'for' loops: - I have problems to remember its meaning; - It gives me little problems when I later want to translate Python code to other languages (and you always have to translate long-lived code). - I have used it only once, so far. So so far I'd liked to see it removed from Python 3.0. But then this article: http://tratt.net/laurie/tech_articles/articles/the_high_risk_of_novel_language_features has shown me that my problems with the 'else' of the 'for' mostly come from just its bad naming. The converge language is yet another very Python-like language, and it uses a better naming (the word "exhausted" is long and has a complex spelling for non-English speakers, so it's not perfect): for ...: ... exhausted: ... broken: ... The meaning is explicit. While "else" seems to mean little there. So I may like something similar for Python 3.x (or the removal of the "else"). Bye, bearophile From colin.mcphail at mac.com Thu Mar 13 06:31:41 2008 From: colin.mcphail at mac.com (Colin Mcphail) Date: Thu, 13 Mar 2008 10:31:41 +0000 Subject: [pysqlite] [ANN] pysqlite and APSW projects moved References: Message-ID: <47d8f707$0$26041$88260bb3@free.teranews.com> On 2008-03-09 18:57:00 +0000, Gerhard H?ring said: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Gerhard H?ring wrote: >> [...] APSW >> ==== >> >> web: http://oss.itsystementwicklung.de/trac/apsw/ >> scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ > > That should have been http://oss.itsystementwicklung.de/svn/apsw/apsw/ > > - -- Gerhard > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFH1DL7dIO4ozGCH14RAq4gAJ9tZuB9qcPERBkGzKEVBEx8nybfXgCeK8cX > V7sH3uAskDDNBuxYG34vExI= > =IXOx > -----END PGP SIGNATURE----- I'm getting 404 Not Found for the 'corrected' apsw web page URL. Also, the subversion URL doesn't seem right either: $ svn co http://initd.org/svn/pysqlite/apsw/trunk/ apsw svn: PROPFIND request failed on '/svn/pysqlite/apsw/trunk' svn: PROPFIND of '/svn/pysqlite/apsw/trunk': 403 Forbidden (http://initd.org) Regards, -- CMcP -- Posted via a free Usenet account from http://www.teranews.com From gherzig at fmed.uba.ar Mon Mar 3 08:15:48 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Mon, 03 Mar 2008 10:15:48 -0300 Subject: compiling plpython compilation error Message-ID: <47CBFA04.30300@fmed.uba.ar> Hi all. Im having a hard time trying to compile the plpython package. This is the error make gives me: gherzig at vdb:/usr/local/src/postgresql-8.2.5/src/pl/plpython> make gcc -O2 -Wall -Wmissing-prototypes -Wpointer-arith -Winline -Wdeclaration-after-statement -Wendif-labels -fno-strict-aliasing -fpic -shared -Wl,-soname,libplpython.so.0 plpython.o -L/usr/lib/python2.5/config -L../../../src/port -lpython2.5 -lpthread -ldl -lutil -lm -Wl,-rpath,'/usr/lib/python2.5/config' -o libplpython.so.0.0 /usr/lib64/gcc/x86_64-suse-linux/4.2.1/../../../../x86_64-suse-linux/bin/ld: /usr/lib/python2.5/config/libpython2.5.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/lib/python2.5/config/libpython2.5.a: could not read symbols: Bad value collect2: ld returned 1 exit status make: *** [libplpython.so.0.0] Error 1 This runs on OpenSuse 10.3. python 2.5 postgres 8.2.5 ( and 8.3.0) Any clues? Thanks! Gerardo From vogelel at stinternet.net Sat Mar 29 17:33:12 2008 From: vogelel at stinternet.net (linda vogele) Date: Sat, 29 Mar 2008 15:33:12 -0600 Subject: Python vs. Perl, which is better to learn? Message-ID: <000701c891e4$7e03d310$0201a8c0@Linda> 4332951 -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Sun Mar 23 20:42:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 17:42:21 -0700 (PDT) Subject: Does python hate cathy? References: Message-ID: On Mar 23, 8:01 pm, QS wrote: > Hi to all! > I am new to python, and I encountered a weird problem. > > Here is my code > > ##########>8#################### > #!/usr/bin/python > # Filename: objvar.py > class Person: > '''Represents a person.''' > > population = 0 > #sex = 'F' > #age = 22 > # It is vague here: is this variable going to be a class, or > object, variable > > def __init__(self, name, sex): > '''Initializes the person's data.''' > self.name = name > self.sex = sex > print '(Initializing %s )' % self.name > # When this person is created, he/she > # adds to the population > Person.population += 1 > > def __del__(self): > '''I am dying.''' > > print '%s says bye.' % self.name > Person.population -= 1 > if Person.population == 0: > print 'I am the last one.' > else: > print 'There are still %d people left.' % > Person.population > > def sayHi(self): > '''Greeting by the person. > > Really, that's all it does.''' > > self.age = 25 > print 'Hi, my name is %s, and I am %s, and I am age %d ' % > (self.name, self.sex, self.age) > > def howMany(self): > '''Prints the current population.''' > if Person.population == 1: > print 'I am the only person here.' > else: > print 'We have %d persons here.' % Person.population > > swaroop = Person('Swaroop', 'M') > swaroop.sayHi() > swaroop.howMany() > kalam = Person('Abdul Kalam', 'M') > kalam.sayHi() > kalam.howMany() > cathy = Person('Catherine', 'F') > cathy.sayHi() > cathy.howMany() > swaroop.sayHi() > swaroop.howMany() > > ############# 8< ######################### > > When I run this script, I got the following exception: > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xb7d8ac6c>> ignored > > To to newcomer like me, this message doesn't make much sense. What > seems weird to me is that, if I change the variable cathy to something > else, like cath, or even cat, then the script will finish gracefully. > Why "cathy" is not liked?!! > > Some of you may have recognized that the code is derived from a sample > code in Swaroop's "A byte of python". > > My python is of version 2.5.1, on Ubuntu. That's really weird... it's reproducible on Windows too. It doesn't make any sense why the name of the variable would make a difference. My guess is you hit some kind of obscure bug. George From guillermo.listas at googlemail.com Thu Mar 6 07:10:47 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Thu, 6 Mar 2008 04:10:47 -0800 (PST) Subject: Checking if a variable is a dictionary Message-ID: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> Hello, This is my first post here. I'm getting my feet wet with Python and I need to know how can I check whether a variable is of type dictionary. Something like this: if isdict(a) then print "a is a dictionary" Regards, Guillermo From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 18:18:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 23:18:50 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> <13su4mr48on6p7f@corp.supernews.com> <8548d7ab-6b9f-4941-915c-a660d80e90e8@e25g2000prg.googlegroups.com> <13su60prq21ccd2@corp.supernews.com> Message-ID: <13suaiq5n02g015@corp.supernews.com> On Wed, 05 Mar 2008 14:51:04 -0800, castironpi wrote: > Anyway, if (a,b) is a key in dictionary d, can it guarantee that (b,a) > is also in it, and maps to the same object? It would take you approximately five seconds to answer that question for yourself. >>> D = {(1,2): "x"} >>> D[(2,1)] Traceback (most recent call last): File "", line 1, in KeyError: (2, 1) You've already been plonked by one long-time regular today. Are you aiming to get plonked by *everybody*? http://en.wikipedia.org/wiki/Plonk -- Steven From jeffrey at fro.man Thu Mar 20 11:12:51 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 20 Mar 2008 08:12:51 -0700 Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: <13u4vnjbgphfr61@corp.supernews.com> Giampaolo Rodola' wrote: > I mainly need to temporarily impersonate another user to > execute a command and then come back to the original user. If the script is run as root, you can freely impersonate other users with the os.seteuid() and os.setegid() methods. If the script is not run as root (either directly or through sudo, as suggested by other posters), then perhaps it should be. Jeffrey From danb_83 at yahoo.com Sun Mar 30 13:38:01 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 30 Mar 2008 10:38:01 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <659845F2e56g7U2@mid.individual.net> <87od8w7aws.fsf@physik.rwth-aachen.de> Message-ID: On Mar 30, 5:40 am, Torsten Bronger wrote: > Hall?chen! > > Bjoern Schliessmann writes: > > Lie wrote: > > >> Ah yes, that is also used (I completely forgot about that one, my > >> math's aren't that sharp anymore) and I think it's used more > >> frequently than ><. > > > Where did you read that (I mean, which country)? I've never seen > > this sign in any german or english book on > > mathematics/physics/engineering I saw. > > Maybe he means "?". > > >> but my argument was that no math book use != or <> (except in > >> math for programmers). > > > That's true. Personally, I don't ever use "a!=b" in favor of "not > > a==b". > > As a side note, I've always found == rather ugly. I'd prefer to > have = for both purposes. The earliest versions of Python *did* use = for both purposes. > The constructs that wouldn't work anymore > are rare as far as I can see (and possibly there are even > workarounds). The construct a = b == c could be rewritten as a = (b = c). From bearophileHUGS at lycos.com Thu Mar 20 09:11:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 20 Mar 2008 06:11:41 -0700 (PDT) Subject: Removal of tkinter from python 3.0? [was: Fate of the repr module in Py3.0] References: <7xy78dg79e.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > Python needs more stuff in its stdlib, not less. > If Tkinter doesn't satisfy, then add Gtk (or whatever) to the standard > distro. If that happens (i.e. some new toolkit is brought in and > declared to be the standard) then it might be ok to drop Tkinter but > it certainly shouldn't be dropped without a replacement. If Tkinter is removed from the std lib, then I think another simple GUI toolkit has to be added to replace it. I have appreciated Wax in the past, it works with Wx and is rather easy. It's a dead software now, but it can be improved. It can be almost as easy as Tk, and it shows that Wx can be used with a much better API. Something like gazpacho (http://gazpacho.sicem.biz/ ) can be created for Wax too, and it can be added to the std lib. Bye, bearophile From mensanator at aol.com Sun Mar 23 00:42:44 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 22 Mar 2008 21:42:44 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> <13ubn5ue821ak7e@corp.supernews.com> Message-ID: <65b2d722-9e4c-4dc8-948a-3197deeeb5b6@e67g2000hsa.googlegroups.com> On Mar 22, 11:29?pm, Steven D'Aprano wrote: > On Sat, 22 Mar 2008 21:11:51 -0700, sturlamolden wrote: > > On 22 Mar, 23:42, 7stud wrote: > > >> Beginning programmers in grades 9-12 are not going to understand issues > >> like that, and it would be a mistake to try and introduce them. > >> Beginning programmers should be concentrating their efforts on learning > >> the syntax of a language and basic constructs like for-loops and if > >> statements. > > > Yes. And because Python is a "scripting language" > > Python is a programming language. It can be used for scripting, but > that's not all it can do. Describing it as a "scripting language" is like > describing a fully-equipped professional kitchen as "a left-over warming > room". Sure, but then again, some are chefs, others merely cooks and yet others just warm leftovers. > > -- > Steven From python.list at tim.thechases.com Wed Mar 19 06:12:30 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 19 Mar 2008 05:12:30 -0500 Subject: PODCasts In-Reply-To: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> References: <2b54d4370803190206p1e10bad9pf50e623e29761ee8@mail.gmail.com> Message-ID: <47E0E70E.4080807@tim.thechases.com> > I really should say net cast as I think it's a better term ;) > > Does anyone have any recommended net casts on Python, or programming in > general? Well, though it's been a while since I last noticed a new release (last one dated Dec '07), the archives of "Python 411" should all be online: http://www.awaretek.com/python/ -tkc From python at rcn.com Tue Mar 4 15:09:45 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 Mar 2008 12:09:45 -0800 (PST) Subject: for-else References: Message-ID: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> [BearOphile] > So far in Python I've almost hated the 'else' of the 'for' loops FWIW, I'm very happy with for-else. Most of the time, you don't need it, but when you do, it beats the heck out of doing silly tricks with flags. The primary use case is searching a container: prep_tasks() for item in container: if predicate(item): found_tasks() break else: not_found_tasks() follow_up_tasks Raymond From paddy3118 at googlemail.com Sat Mar 29 14:01:40 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 29 Mar 2008 11:01:40 -0700 (PDT) Subject: deleting a line from a file References: Message-ID: On Mar 29, 11:13 am, eMko wrote: > Hello, > > In Perl, using a Tie::File module I can easily and comfortably delete > a line from the middle of a text file: > > my @file; > open(DATA, "+<:encoding(utf8):raw" , "file.txt") or return 0; > tie @file, 'Tie::File', \*DATA or return 0; > splice(@file, $_[0], 1); > untie @file; > close DATA; > > (when the first argument of the function ($_[0]) is a number of the > line which should be deleted) > > Is there some easy way how to delete a line from a middle of a file in > Python? > > Thanks a lot > eMko Module fileinput has\; Optional in-place filtering: if the keyword argument inplace=1 is passed to input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the keyword argument backup='.' is also given, it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. - Paddy. From tjreedy at udel.edu Thu Mar 13 17:20:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Mar 2008 17:20:14 -0400 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net><13sc3b0g7gud892@corp.supernews.com> Message-ID: "Antoon Pardon" wrote in message news:slrnfthp1s.61k.apardon at rcpc42.vub.ac.be... | On 2008-02-28, Steven D'Aprano wrote: | > On Thu, 28 Feb 2008 02:02:19 +0200, Tamer Higazi wrote: | > | >> Hi! | >> Can somebody of you make me a sample how to define a function based on | >> "call by reference" ??? | > | > Python doesn't do call by reference. Nor does it do call by value. Please | > pay no attention to anyone who says it does. | | Whatever python has for a calling convention, it is close enough that | naming it "call by reference" gives people a reasonable idea of what | is going on. But it is also different enough to mislead people. | AFAICS people don't have a problem with understanding the calling | convention of python. They have a problem understanding the | assignment semantics. The calling convention is cross-namespace assignment. So one cannot understand calls without understanding assignment. tjr From gh at ghaering.de Sun Mar 9 14:39:41 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 09 Mar 2008 19:39:41 +0100 Subject: [ANN] pysqlite and APSW projects moved Message-ID: <47D42EED.8070107@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dear pysqlite users! I've moved both the pysqlite and APSW project to new homes. pysqlite ======== web: http://oss.itsystementwicklung.de/trac/pysqlite aka http://pysqlite.org/ scm: pysqlite now uses a Mercurial repository http://oss.itsystementwicklung.de/hg/pysqlite/ APSW ==== web: http://oss.itsystementwicklung.de/trac/apsw/ scm: Subversion: http://initd.org/svn/pysqlite/apsw/trunk/ Both pysqlite and APSW have a common mailing list at http://itsystementwicklung.de/cgi-bin/mailman/listinfo/list-pysqlite Existing subscribers that have not set the "nomail" flag have been moved to the new list already. - -- Gerhard PS: Because of spam problems on the old Trac, I've patched AccountManager so that you will now have to verify your human-ness with a captcha when you register an account. The old Trac accounts were not moved on purpose to avoid spam. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFH1C7tdIO4ozGCH14RAjAhAKCmxm+rKkjxMalCkH2Wjs88raxuCACgiV4B XJq+YweOK0Zh1IWHLkrl3LI= =b6zE -----END PGP SIGNATURE----- From ptmcg at austin.rr.com Wed Mar 5 17:14:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 5 Mar 2008 14:14:23 -0800 (PST) Subject: What is a class? References: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> <83c80fce-b13c-4109-848d-a0aa0441ba40@e31g2000hse.googlegroups.com> Message-ID: <750087f0-2af9-4323-b6e1-e22c7b702fc3@8g2000hse.googlegroups.com> On Mar 5, 3:49?pm, castiro... at gmail.com wrote: > > Classes and modules are really similar. ?In Python they're really > *really* similar. > > Actually, at this point, that observation may have more of a > subjective component than I'm used to asserting. ?I pause here for > corroboration and others' perspectives. ?Aren't they? If all you use classes for is for the purpose of a namespace, and all of the methods in the class are just staticmethods, then you have used a class to replicate a module, and they aren't just really, *really* similar, they are the pretty much the same (at least BEHAVIORALLY speaking). But you can't do this: import Zmodule zobject = Zmodule() If you are really using the OO model, and creating instances of classes, then you *have* to use a class, a module wont cut it. I'd say, the less you use a class as an instance factory, the more similar that class is to a module. And you can't do this: class Zclass: import Zclass If Zclass is not defined in your local script, you *have* to know what module it is in, as in: from zpackage.zmodule import Zclass I have seen modules compared to classes that implement a Singleton pattern. In this case, a class is being used in an intentionally degenerate way, such that it creates only one instance. When doing this in Python, one has the choice of replicating the standard pattern with a class, or more simply, just using a module. (Python's language/ object model also permits another option, usually referred to as the Borg implementation, in which many Python names bind to many Python instances, but all share the same underlying object state. But this is tangential to your question.) In general I would say the similarity is a behavioral one, an artifact of the language implementation. Modules are for code packaging and namespace definition, classes are for type definition and object modeling. For more discussions about how similar classes are to modules, you might google for "Python singleton". -- Paul From zugnush at gmail.com Thu Mar 27 17:58:19 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Thu, 27 Mar 2008 14:58:19 -0700 (PDT) Subject: copy file over LAN References: Message-ID: <1d8447b4-26a1-40ae-b11c-20d5a6a40e3f@m34g2000hsc.googlegroups.com> On Mar 27, 6:48 pm, Teja wrote: > On Mar 27, 8:34 am, Astan Chee wrote: > > > > > Hi, > > I have afileon another machine on the localnetwork(my machine and > > local machines are on windows) and I want tocopyit locally. Now the > > machine requires authentication and when I try to do a > > import shutil > > shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt') > > and it gives me a IOError: [Errno 13] Permission denied: error, which I > > expect. How do I provide authentication tocopythisfile? > > Thanks for the help. > > Cheers > > Astan > > > -- > > "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." > > > Animal Logichttp://www.animallogic.com > > > Please think of the environment before printing this email. > > > This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. > > Hi, > > Is the folder where the file is present i.e. "temp" in your case, > shared???? > Can you share it and try it?? > > I tried this way and it worked! > > import shutil > > shutil.copyfile(r'\\129.124.66.112\Samplesharedfolder\samplefile.txt', > r'C:\\Test\\temppp.txt') > > Try this way and let me know I just discovered that this works for python upload into sharepoint too :-) From brian at briansmith.org Thu Mar 13 09:33:47 2008 From: brian at briansmith.org (Brian Smith) Date: Thu, 13 Mar 2008 06:33:47 -0700 Subject: Socket Performance In-Reply-To: References: Message-ID: <004b01c8850e$de8084a0$4001a8c0@T60> sleddd at gmail.com wrote: > Sent: Wednesday, March 12, 2008 9:47 PM > To: python-list at python.org > Subject: Socket Performance > > Can anyone explain why socket performance (throughput) varies > depending on the amount of data send and recv are called with? > > For example: try creating a local client/server (running on the same > computer) where the server sends the client a fixed amount of data. > Using method A, recv(8192) and sendall( ) with 8192 bytes > worth of data. Do this 100 times. Using method B, recv(1) and > sendall( ) with 1 byte worth of data. Do this 819200 times. > > If you time both methods, method A has much greater > throughput than method B. Why is it faster to drink a liter of water a cupful at a time than to drink it out of an eyedropper? - Brian From mnordhoff at mattnordhoff.com Wed Mar 26 05:00:40 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 26 Mar 2008 09:00:40 +0000 Subject: Strange loop behavior In-Reply-To: <47EA0ABB.3030804@mydeskfriend.com> References: <47EA0ABB.3030804@mydeskfriend.com> Message-ID: <47EA10B8.8080100@mattnordhoff.com> Gabriel Rossetti wrote: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) FWIW, you could do it like this to avoid duplicating that line of code: while True: d = f.read(DEFAULT_BUFFER_SIZE) if not d: break file_str.write(d) Some people would also compress the whitespace a bit: while True: d = f.read(DEFAULT_BUFFER_SIZE) if not d: break file_str.write(d) (I'll comment on your Unicode issues in a minute.) -- From http Fri Mar 21 00:19:05 2008 From: http (Paul Rubin) Date: 20 Mar 2008 21:19:05 -0700 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> <64bugqF2anottU1@mid.uni-berlin.de> <7xve3j15ya.fsf@ruckus.brouhaha.com> <87fxunumqx.fsf@physik.rwth-aachen.de> <7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: <7x63vgd806.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > What would be amazing would be a algorithm that could rewrite the > external-arrays Haskell/Python code to the equivalent of the in-place C > code. I don't think JHC (a fancy optimizing Haskell compiler) goes quite that far, but it compiles Haskell to C code that looks pretty much the same as imperative code that a careful programmer would write. > Can one even write such an equivalent in Haskell? (If it is purely > functional, then no, though one obviously can in Python.) Yes, you can write in an imperative styld while staying purely functional. The trick is to notice that b = f(a) c = g(b) d = h(c) ... requires evaluating f,g,h in exactly that order. So you can write sequential code as a bunch of nested function calls that the compiler optimizes away. Haskell has syntactic support for this, so the code you'd write looks somewhat C-like: do { b <- f a; c <- g b; d <- h c } but it is actually even cooler than that (complicated to explain so I won't try here). The result is that you really insist, you can code an imperative quicksort that looks about the same as the C one and compiles to about the same machine code, but is fully typesafe and polymorphic. From gagsl-py2 at yahoo.com.ar Mon Mar 3 01:55:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Mar 2008 04:55:09 -0200 Subject: class object interface document References: Message-ID: En Mon, 03 Mar 2008 04:37:38 -0200, Neil.Fang.CN escribi?: > On Mar 2, 6:26?pm, "Gabriel Genellina" wrote: >> En Sun, 02 Mar 2008 00:55:23 -0200, Neil.Fang.CN >> ? >> escribi?: >> >> > Where can I find the Python class object interface document, such as >> > struct PyClassObject, PyClass_New()? Thanks! >> >> PyClass_* and PyInstance_* are for old-style classes and instances ? >> respectively, and will disappear in v3.0. >> PyInstance is in the section 7.5.2 in the Python/C API Reference >> Manual; I?don't find any documentation on PyClass itself. > Thanks for your reply. > What is the counterpart in v3.0? New style classes, that exist since v2.2 http://www.python.org/doc/newstyle/ -- Gabriel Genellina From castironpi at gmail.com Sat Mar 1 22:12:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 1 Mar 2008 19:12:01 -0800 (PST) Subject: How to subclass a built-in int type and prevent comparisons References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> Message-ID: On Mar 1, 2:58 pm, Michael Torrie wrote: > castiro... at gmail.com wrote: > > Tell Wall. But why not [ 2, 3 ]>= 2? Back to your question, another > > option is to not subclass. > > Umm, no. You need to actually read the posts before you respond to > them. His question was whether or not to throw an exception in this > case. He's *already* subclassed the type. > > The first question was, should he throw an exception. And given that > Python 3.0 will throw exceptions, he is justified in throwing exceptions > as well. I have no idea what he would lose by throwing an exception. I > have no idea how else he would do this. > > His second question was, would his code for implementing __gt__ (and > throwing exceptions) be likely efficient. That I cannot say. Point taken. The is-a vs. has-a distinction was what I was looking at. Is it more work to the OP to disable the things in Int he doesn't want, or to enable those he does? On a tangent (you were alerted): A horse with three legs is a horse. A square with three sides is a square. A cup of coffee with no bottom is not a cup. If he doesn't throw an exception, he can compare to an arbitrary point, class-static, etc., post a message to a queue awaiting further instructions and block to its return, fire a synchronous callback, pause for user input, remove a certain element and set an op-abort flag, return a special value ( NoCompare= object() ), NaN, INF, &c., upgrade one or both operands, vary the behavior with class or instance, callback a coroutine omitting the point and assessing later, add it to a list of problem data to be treated by a superior, or take a special lunch break, after which the right-hand value is guaranteed to conform. You can try casting the RHV right-hand value to the required type too. Originally, exceptions came about as ways to respond to requests of a class hierarchy that fail to evaluate for the derived type, such as Ostrich().fly(), but expanded to include logic flow: do this this and this, except when file doesn't close correctly. In Python 1.0, a lot of classes set methods upon construction: init: self.data= data; self.__gt__= self.data.__gt__, and perhaps subclass that. Or move to C. In the trade, customers don't care what code made the program they bought. The company doesn't care what code made the program. Reinventing the wheel is cheap for certain wheels. Hallway full of doors; close some to get the product out sooner. What might we want down the road? What's down the road? Who is? In the hobbies, you can see an elaborate mixin to simplify work later, just for practice, or for the Zen-and-the art, like doing puzzles. class SpecialInt( Selective, int ): meths= Selective.numerics( int ) onlyif= [ partial( is_, int ), or_, partial( is_, SpecialInt ) ] It just costs performance-- product performance, even if not production team performance. from functools import partial from operator import is_, is_not assert partial( is_, int )( type( 2 ) ) assert partial( is_not, int )( type( 2.5 ) ) But: >>> class C: C ... Traceback (most recent call last): File "", line 1, in File "", line 1, in C NameError: name 'C' is not defined Can we have access to classes in their definitions? class C: delayed( 'C' ) works fine. If we don't want to permit calling a function on a half- executed class, then postcreator(or something) would have to be syntax. Class decorators can do it: * current= Current() @current.delay class SpecialInt: onlyif= [ partial( is_, int ), or_, partial( is_, current ) ] Similarly: * current= Current() class SpecialInt: onlyif= [ partial( is_, int ), or_, partial( is_, current ) ] current.delayedeval( SpecialInt ) But it starts to get really tangled: current= Current() @current.delay class SpecialInt: onlyif= [ partial( is_, int ), or_, current.partial( partial, is_, current ) ] where current.partial returns a delegation object that replaces current with the class current.delay wraps. If you don't want current to delegate too, then: current= Current() @current.delay class SpecialInt: onlyif= [ partial( is_, int ), or_, current.partial( partial, is_, current.ref ) ] may be next best. But all this is just to save two lines somewhere where you're allowed to use a custom wrap-in class, since Current is borderline library, and don't even mention 'standard'. However if it saves ten seconds in a coding competition, or captures the flash of an idea you get at 2 a.m. (make that 4 for the kids), then it's worth keeping around. import obscure. And class SpecialInt: onlyif= [ partial( is_, int ) ] SpecialInt.onlyif.extend( [ or_, partial( is_, SpecialInt ) ] ) sure is practical. From castironpi at gmail.com Mon Mar 31 19:31:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 31 Mar 2008 16:31:25 -0700 (PDT) Subject: python persistence Message-ID: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> Can you have a Python object stored entirely on disk? From deets at nospam.web.de Thu Mar 27 10:19:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 15:19:11 +0100 Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> Message-ID: <651onqF2dripdU1@mid.uni-berlin.de> > Ok, i know this. The one that i do not know, is if, let'say, in 2 > years it will be ready for seriously development, PyPy will aim to > "replace" CPython entirely ?? We are talking about an whole new > distribution ? Most certainly not. It's the goal of each language to finally become self-hosted, and I hope we see that for python. But that's nothing that will happen anytime soon (soon being at least half a decade), and most probably not for the 2.x-versions. > As for psyco, are there any alternatives to use now ? Nope, but I heard through the grapevine that while it won't be supported for all times to come, a new version is in the making. But ultimately, the author says that the approach is flawed, so at *some* point it will be discontinued. But that could be said about nearly everything, couldn't it? Diez From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:00:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:00:18 -0300 Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> <17e0f94a-555c-40c7-8dd6-90c6d9c0b633@a23g2000hsc.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 12:25:55 -0300, escribi?: > On Mar 28, 11:14 am, "Gabriel Genellina" > wrote: >> En Fri, 28 Mar 2008 11:51:10 -0300, escribi?: >> >> > How can this module access global state (not per-thread state) ? >> > It needs to create a singleton. >> >> C global variables are global, not per-thread. > > Yes, but they get initialized once per-thread, therefore my singleton > gets > created multiple times. Either don't call the initialization from every thread, or guard it with something like: a_big_object my_object = NULL; ... if (my_object!=NULL) { ...initialize object... my_object = ...; } That's a pretty standard idiom I think. -- Gabriel Genellina From craigtrucko at gmail.com Tue Mar 25 22:00:41 2008 From: craigtrucko at gmail.com (craigtrucko) Date: Tue, 25 Mar 2008 19:00:41 -0700 (PDT) Subject: 4gb USB Flash drive for $14.49 Message-ID: <1b8ba3b8-f71b-464f-9bec-33c6fc7a2e09@p73g2000hsd.googlegroups.com> Hey Guys, dealsusb.com has a 4gb USB Flash drive for $14.49 Free Shipping and no rebates. Now we can backup our smaller Databases onto a USB really cheap. craig From mail at timgolden.me.uk Sun Mar 16 10:54:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 16 Mar 2008 14:54:16 +0000 Subject: Spaces in path name In-Reply-To: <47DD2EF3.1080900@timgolden.me.uk> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> <4aad360c-a85a-4af5-b1b9-dd371cd2b73f@m3g2000hsc.googlegroups.com> <47DCC1C4.2010806@timgolden.me.uk> <59e73ea4-6c4f-4071-a34b-65a78cf19c1c@8g2000hse.googlegroups.com> <47DD2EF3.1080900@timgolden.me.uk> Message-ID: <47DD3498.9000901@timgolden.me.uk> Tim Golden wrote: > What I haven't investigated yet is whether the additional flags > your example is passing (shell=True etc.) cause the main Popen > mechanism to take a different path. Sure enough, passing shell=True -- which is probably quite a rare requirement -- causes the code to change the call from "a.exe b.doc" to '%COMSPEC% /c "a.exe" "b.doc"'. The quoting rules (from cmd /?) are slightly involved but I can't see at first why this shouldn't work. However it clearly doesn't so I'll try to put together either a patch to the subprocess code or to the docs warning of the behaviour. I think that, in general, you need to pass shell=True far less often that you might imagine. (Possibly only for internal commands like dir, copy etc.). TJG From gagsl-py2 at yahoo.com.ar Fri Mar 28 10:30:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 11:30:20 -0300 Subject: simple web-server References: Message-ID: En Fri, 28 Mar 2008 08:53:15 -0300, Pavol Murin escribi?: > could you point me to a very simple (single file is best) web-server? > I want to serve a few web-forms and run some shell scripts when the > forms are submitted. I might add Ajax later (this is not a > requirement, if it only supports forms it's OK). Ajax is mostly a client thing, any server would work. > I would like to provide a web-page for customization of an > application - it should run some shell commands as the user clicks > around in the page and at the end write a configuration file. I had a > look at the python wiki (http://wiki.python.org/moin/WebProgramming), > where various web servers and frameworks are listed. The frameworks > seem to heavy for such a simple task and BaseHTTPServer just seems to > be too light. How many requests/minute you expect to handle? From your description, not many, I think. So even CGI would be OK, and I'd choose the easiest server to configure and setup. TinyWeb www.ritlabs.com is the smallest web server I know of (Windows only, unfortunately), and almost setup-free. Ensure that .py scripts are executable, place them in a cgi-bin subdirectory, start tiny.exe and you're done. > So I took a look at the web-servers listed: > httpy had the last release 1,5 years ago, Medusa more than 5 years, > Twisted seems to be able to do a lot, so probably not the simple thing > I'm looking for. CherryPy looks promising, however it is still 89 > files (including some that can be removed) Don't make the release dates fool you. The HTTP specs haven't changed in years, once you have a functional server, there is no need to keep changing it. > If CGIHTTPServer is a good answer, could you point me to a good > (nontrivial) example? Running CGIHTTPServer takes 3 or 5 lines of code, and that's all to it. You don't have to touch the server itself. You write cgi scripts and put them somewhere so the server can find and execute them when requested; that's all. So you have to look for CGI examples, not server examples :) -- Gabriel Genellina From dotancohen at gmail.com Thu Mar 6 02:11:47 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 6 Mar 2008 09:11:47 +0200 Subject: Why """, not '''? In-Reply-To: <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> References: <13su5tn6rpjb345@corp.supernews.com> <13sudd49au3e1c1@corp.supernews.com> <6490c865-2336-41a1-bc13-4ad730697a6b@p73g2000hsd.googlegroups.com> Message-ID: <880dece00803052311p181c753cx9ae8338e954f9290@mail.gmail.com> On 06/03/2008, Dan Bishop wrote: > On Mar 5, 7:24 pm, Matt Nordhoff wrote: > > > Steven D'Aprano wrote: > > > Surely it would depend on the type of text: pick up any random English > > > novel containing dialogue, and you're likely to find a couple of dozen > > > pairs of quotation marks per page, against a few apostrophes. > > > > > That's an idea... Write a novel in Python docstrings. > > > Or better yet, write in Python syntax. > > > assert len([man for man in now_alive() if > man.remembers(datetime.date(1775, 4, 18))]) <= HARDLY > > lantern_count = {'land': 1, 'sea': 2}.get(british.location(), 0) > n_ch_twr.hang(Lantern() for _ in xrange(lantern_count)) > > if lantern_count: > for village in middlesex: > ride_thru(village) > spread_alarm(village) > That looks ported from lolcode. http://lolcode.com/ Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From gagsl-py2 at yahoo.com.ar Sat Mar 29 21:42:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 22:42:30 -0300 Subject: Installing simplejson issues References: <707e37d4-21bc-4669-8f6a-71bc25486d35@e6g2000prf.googlegroups.com> <657v9rF2eatagU1@mid.uni-berlin.de> <1f4f021a-770f-4282-9cd4-5dcc153524ed@c19g2000prf.googlegroups.com> Message-ID: En Sat, 29 Mar 2008 20:54:36 -0300, escribi?: > I tried to add the directory "//simplejson" to my sys.path > in the interpreter, hoping that the call to import simplejson would > work if the dir was there, even though simplejson.py did not exist is > that dir, but the encoder, decoder, jsonfilter and scanner .py files > were all there. > > My problem is that the call "import simplejson" fails. How can I make > that call work? simplejson is a package (a directory with an __init__.py), not a module; don't look for simplejson.py Its *parent* directory must be in sys.path for Python to find it. Try copying the simplejson directory below site-packages (which should be already in sys.path) -- Gabriel Genellina From jwbrown77 at gmail.com Thu Mar 27 17:40:58 2008 From: jwbrown77 at gmail.com (jwbrown77 at gmail.com) Date: Thu, 27 Mar 2008 14:40:58 -0700 (PDT) Subject: csv Parser Question - Handling of Double Quotes References: Message-ID: On Mar 27, 1:53?pm, "Gabriel Genellina" wrote: > En Thu, 27 Mar 2008 17:37:33 -0300, Aaron Watters ? > escribi?: > > > > >> "this";"is";"a";"test" > > >> Resulting in an output of: > > >> ['this', 'is', 'a', 'test'] > > >> However, if I modify the csv to: > > >> "t"h"is";"is";"a";"test" > > >> The output changes to: > > >> ['th"is"', 'is', 'a', 'test'] > > > I'd be tempted to say that this is a bug, > > except that I think the definition of "csv" is > > informal, so the "bug/feature" distinction > > cannot be exactly defined, unless I'm mistaken. > > AFAIK, the csv module tries to mimic Excel behavior as close as possible. ? > It has some test cases that look horrible, but that's what Excel does... ? > I'd try actually using Excel to see what happens. > Perhaps the behavior could be more configurable, like the codecs are. > > -- > Gabriel Genellina Thank you Aaron and Gabriel. I was also hesitant to use the term "bug" since as you said CSV isn't a standard. Yet in the same right I couldn't readily think of an instance where the quote should be removed if it's not sitting right next to the delimiter (or at the very beginning/end of the line). I'm not even sure if it should be patched since there could be cases where this is how people want it to behave and I wouldn't want their code to break. I think rolling out a custom class seems like the only solution but if anyone else has any other advice I'd like to hear it. Thanks again for the help. From yennes at gmail.com Thu Mar 20 06:24:49 2008 From: yennes at gmail.com (Dravidan) Date: Thu, 20 Mar 2008 03:24:49 -0700 (PDT) Subject: backslash in reading bytes Message-ID: <560a5033-576f-4876-91cf-08276985b308@s50g2000hsb.googlegroups.com> I am trying to read some byte data as a string then using a library to convert them a code: >>>reader = csv.DictReader(open('table.txt')) >>>def eleFind(value): >>> for row in reader: >>> if row['byteCode'] == value: >>> print row['Element'] >>> return >>> else: >>> print "No Match Found:" >>>eleFind('\x00\x00') My table contains: \x00\x00,0000 \x01\x00,0000 ...... The program errors out. How can I fix/overide this backslash issue. From jeff at schwabcenter.com Sat Mar 22 14:40:43 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 22 Mar 2008 11:40:43 -0700 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: jmDesktop wrote: > For students 9th - 12th grade, with at least Algebra I. Do you think > Python is a good first programming language for someone with zero > programming experience? Using Linux and Python for first exposure to > programming languages and principles. Linux and Python are a nearly ideal combination for this. Be aware that at some point, you will likely have to dig into C, the primary language used to implement both Linux and Python. From tmp1 at viltersten.com Tue Mar 4 15:05:27 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Tue, 4 Mar 2008 21:05:27 +0100 Subject: SV: Polymorphism using constructors In-Reply-To: <63346uF25gigqU1@mid.uni-berlin.de> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> Message-ID: <635ndjF2551ajU1@mid.individual.net> "Diez B. Roggisch" skrev i meddelandet news:63346uF25gigqU1 at mid.uni-berlin.de... >K Viltersten schrieb: >> I'm writing a class for rational numbers >> and besides the most obvious constructor >> >> def __init__ (self, nomin, denom): >> >> i also wish to have two supporting ones >> >> def __init__ (self, integ): >> self.__init__ (integ, 1) >> def __init__ (self): >> self.__init__ (0, 1) >> >> but for some reason (not known to me at >> this point) i get errors. My suspicion is that it's a syntax issue. > > "errors" is not much of an error-description. That's what stacktraces are > for. I assumed that the error was so obvious to a seasoned Pytonist (Pythoner?) that a trace didn't matter. Your help below proves it. :) Nevertheless, i'll be careful in the future and make sure to post the traces too. Sorry. > Apart from that, you won't succeed with the above. Python has no > signature-based polymorphism. Instead, you use default arguments, like > this: > > def __init__(nomin=0, denom=1): > ... Thank you. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From fn681 at ncf.ca Fri Mar 21 10:09:39 2008 From: fn681 at ncf.ca (Colin J. Williams) Date: Fri, 21 Mar 2008 09:09:39 -0500 Subject: Improving datetime In-Reply-To: References: <69CB88B8-0A3F-4CF2-A4BC-14D9C15CCD5E@coredump.us> <47E17801.606@cheimes.de> Message-ID: <47E3C1A3.6050608@ncf.ca> Nicholas F. Fabry wrote: > On Mar 19, 2008, at 16:30, Christian Heimes wrote: > >> Nicholas F. Fabry schrieb: >>> This is a query for information as to how to proceed. I am not a >>> professional programmer, but I use Python a great deal to help me in >>> my main job, which involves designing schedules for a global >>> airline. As such, I use datetime (and dateutil) extensively, and >>> after much use, I have come to some conclusions about their utility, >>> and how to improve them. Some of these changes are quite minor and >>> would result in a large increase in utility (low hanging fruit), >>> while some changes are major, and would result in less obvious >>> benefits - but these changes would increase the 'Python Zen' of them. >>> So - where should I propose these changes? Here? python-dev? >>> Should I write up a full PEP or should I just give a more informal >>> outline with code samples? I would volunteer to help >>> maintain/improve datetime, but I don't speak C at all, >>> unfortunately, and datetime appears to be in C. >> >> Please write a detailed but not too long proposal to the Python ideas >> mailing list. The proposal should explain how you like to improve the >> datetime module. But *please* don't write a novel. You'll get more >> attention when the signal to noise ratio is high. A bullet list of >> features is easier to read than a long text block. >> > > Thank you for the prompt response and suggestion! I am writing up a > proposal presently. There are, however, two broad category of changes - > the 'easy' changes, which could be accomplished with little additional > effort, and the 'hard' changes, which would require significant > reworking of the datetime class (or a wrapper around it). I was going > to break my proposal up into two parts, the easy part and the hard > part. Does that sound like a good idea? Or should I unify the two? > The prime purpose of all the changes, easy and hard, is to make timezone > handling accurate and clear, reduce and make clearer the (application > programmer) code required to use them, and give more informaton to the > programmer about errors, not silently assume something and pass them. > > I have to sign up for that mailing list - I will do so, and submit my > ideas there. > > Please clarify how long a novel is? The problem with the modules are > not bugs, they are problems with real world use scenarios that result in > inescabably ugly code without improvements to the module - so the > explanations involve code samples and use cases... so they may be > 'long'. Could you suggest a maximum number of (70 char) lines, or an > example of an overly long proposal? > > >> I'm a core developer and I may be interested in mentoring your >> proposal. I can guide you through the process, review code and commit it. >> > > Thank you very much for the offer - I greatly appreciate it. I must > admit, my motivation is because Python made programming so much fun for > me again (my first machine was a Sinclair ZX80, long, long ago), and I > want to improve this part of the language so datetime calculations are > clean and neat (like the rest of Python) and don't force programmers to > manually go through what the library should do for them. > > >> Yes, the datetime module is written in C. But we may move the C code >> to _datetime and create a facade module in Python. >> > > That would be excellent for me, because the underlying datetime routines > work correctly and quickly; it's the 'topmost' layer that needs to be > improved to do the right thing. And, I could then actually > write/maintain the Python code in the facade module, rather than request > someone else 'do it for me' in C. > > To summarize my proposal VERY briefly: > > > - Make aware datetime objects display in local time, but > calculate/compare in UTC. > > - Raise exceptions when an illegal or ambiguous datetime is instantated. > > > Thank you again, > > Nick > > > > > > >> Christian Nick, You might consider adding the Julian date (http://en.wikipedia.org/wiki/Julian_date). I had a crack at this a while ago but didn't seem to get quire the right result, using the ACM algorithm. I seemed to be a day out at the BC/AD divide. Colin W. > From mccredie at gmail.com Mon Mar 3 13:47:09 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 3 Mar 2008 10:47:09 -0800 (PST) Subject: Inheritance issue... References: Message-ID: <914ade29-c8b1-4632-bd73-be60f3e2b349@s12g2000prg.googlegroups.com> On Mar 3, 9:37 am, MooMaster wrote: > I'm trying to use inheritance to create a simple binary tree, but it's > not going so well... here's what I pull from the documentation for > super() > "super( type[, object-or-type]) > > Return the superclass of type. If the second argument is omitted the > super object returned is unbound. If the second argument is an object, > isinstance(obj, type) must be true. If the second argument is a type, > issubclass(type2, type) must be true. super() only works for new-style > classes. > A typical use for calling a cooperative superclass method is: > > class C(B): > def meth(self, arg): > super(C, self).meth(arg) > " > > So here's what I do: > > class Node: > def __init__(self, val=0, prnt = None): > self.value = val > self.parent = prnt > > class Tree(Node): > def __init__(self, val=0): > self.root = super(Tree, self).__init__(val) > self.leftChild = None > self.rightChild = None > > def addChild(self, value): > if self.root == None: > self.__init__(value) > else: > n = self.root > while(n is not None): > if(n.leftChild == None and n.rightChild == None): > n.leftChild = Node(value, n) > elif(n.rightChild == None): > n.rightChild = Node(value, n) > else: > if(n.leftChild.leftChild is not None and > n.leftChild.rightChild is not None): > n = n.rightChild > else: > n = n.leftChild > > def printTree(self): > if self.root == None: > print "None" > else: > n = self.root > print n.value > while(n is not None): > if(n.leftChild is None): > print str(n.value) + "'s left child is None" > elif(n.rightChild is None): > print str(n.value) + "'s right child is None" > else: > if(n.leftChild.leftChild is not None and > n.leftChild.rightChild is not None): > n = n.rightChild > else: > n = n.leftChild > def main(): > play = Tree(1) > play.addChild(2) > play.addChild(3) > play.addChild(4) > play.addChild(5) > play.printTree() > > if __name__ == "__main__": > main() > > ...and here's what I get: > > Traceback (most recent call last): > File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 53, in > > main() > File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 45, in > main > play = Tree(1) > File "C:/Users/The_N_Channel/Desktop/funWithTrees.py", line 8, in > __init__ > self.root = super(Tree, self).__init__(val) > TypeError: super() argument 1 must be type, not classobj > > Looks to me like the super(Tree, self)__init__(val) follows the > example in the documentation, but I may be a witch. Anyone know why > this doesn't work? Node should inherit from `object'. Unless you inherit from object you are using old-style classes, which do not derive from type and cannot use the super method. Example: class Node(object): Also, __init__ does not return anything, ever. This doesn't make sense: > self.root = super(Tree, self).__init__(val) When you call the __init__ method of a base class, it will operate on self. Example: >>> class CBase(object): ... def __init__(self, a): ... self.a = a ... >>> class C(CBase): ... def __init__(self, a, b): ... super(C, self).__init__(a) ... self.b = b ... >>> c = C(1,2) >>> c.a 1 >>> c.b 2 Doing things like self.__init__(val) doesn't make sense. Matt From cpgray at library.uwaterloo.ca Fri Mar 28 11:27:59 2008 From: cpgray at library.uwaterloo.ca (Chris Gray) Date: Fri, 28 Mar 2008 11:27:59 -0400 Subject: web application-level caching Message-ID: Is there a Python module comparable in functionality to the PEAR Cache_Lite package for PHP? I've been doing some Googling to little avail. I'm experimenting with Python CGI to learn various techniques at a low level and I'm adapting a model that uses PHP. Any info about application-level caching (or pointers to where to find such info) would be highly appreciated. Thanks, Chris From bockman at virgilio.it Mon Mar 3 11:12:20 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 3 Mar 2008 08:12:20 -0800 (PST) Subject: Import, how to change sys.path on Windows, and module naming? References: Message-ID: <820d6ac9-041a-4d8a-a444-d2978ad41ba4@p25g2000hsf.googlegroups.com> On 1 Mar, 20:17, Steve Holden wrote: > Jeremy Nicoll - news posts wrote: > > > > > Jeremy Nicoll - news posts wrote: > > >> If I understand correctly, when I import something under Windows, Python > >> searches the directory that the executing script was loaded from, then > >> other directories as specified in "sys.path". > > > Sorry to followup my own question, but I ran > > > ?for p,q in enumerate(sys.path): print p, q > > > and got: > > > 0 C:\Documents and Settings\Laptop\My Documents\JN_PythonPgms > > 1 C:\Program Files\~P-folder\Python25\Lib\idlelib > > 2 C:\WINDOWS\system32\python25.zip > > 3 C:\Program Files\~P-folder\Python25\DLLs > > 4 C:\Program Files\~P-folder\Python25\lib > > 5 C:\Program Files\~P-folder\Python25\lib\plat-win > > 6 C:\Program Files\~P-folder\Python25\lib\lib-tk > > 7 C:\Program Files\~P-folder\Python25 > > 8 C:\Program Files\~P-folder\Python25\lib\site-packages > > 9 C:\Program Files\~P-folder\Python25\lib\site-packages\win32 > > 10 C:\Program Files\~P-folder\Python25\lib\site-packages\win32\lib > > 11 C:\Program Files\~P-folder\Python25\lib\site-packages\Pythonwin > > > Does every Windows user have: 2 C:\WINDOWS\system32\python25.zip > > in their sys.path? ?What's the point of having a zip in the path? > > So that the files inside the zip can be imported as modules and > packsges, of course. > > > Also, looking in ?C:\WINDOWS\system32\ ? I don't actually have a file called > > python25.zip, but I do have one called ?python25.dll - so has something gone > > wrong in creation of sys.path? > > No. I'm not sure why the zip file is on there by default. > > regards > ? Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - I believe the answer is in how the new import protocol (PEP 302) works: when you install a new path handler in sys.import_hooks, this is called for each element of sys.path; the path handler has two options: either to raise ImportError, which means that cannot handle the specific path, or to return an object with the methods defined in the PEP, which means that the returned object - and only that one - will be used to import modules in the specific path. This means that only one path handler can be used for each element of sys.path. Therefore, if you want to add a path handler that does not interfere with the other ones, one way to do it is to add something in sys.path that is rejected by all path handlers except yours. I believe that python25.zip is that 'something' that is used by the zipimporter path handler, which allows to import directly from zip files. I did something similar in my toy experiment with the import hooks, half-believing that there was something I missed. Nice to see that the 'big guys' did the same trick :-) (unless of course I _did_ miss something and my guess is completely wrong; I should have done some experiment before posting, but I'm too lazy for that). Ciao ------- FB From wolf_tracks at invalid.com Sun Mar 2 21:57:40 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 03 Mar 2008 02:57:40 GMT Subject: Organizing Books in My Amazon Cart Message-ID: Anyone know of a way of listing all the books in my Amazon Shopping Cart--To Buy Latter? I have a considerable number, and working my way through the list is time consuming. Possibly someone has written a program to do it (Python, Perl, ...)? I have no idea if that's even possible. I figure this is one the largest NGs in my inventory, so maybe someone has thought about it, or can direct me to a more likely NG for the question. -- Wayne Watson (Nevada City, CA) Web Page: From http Tue Mar 18 17:52:59 2008 From: http (Paul Rubin) Date: 18 Mar 2008 14:52:59 -0700 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: <7xbq5br96s.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > I need to move a directory tree (~9GB) from one machine to another on > the same LAN. What's the best (briefest and most portable) way to do > this in Python? os.popen("rsync ...") From python.list at tim.thechases.com Sat Mar 29 18:13:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Mar 2008 17:13:16 -0500 Subject: What motivates all unpaid volunteers at Pycon? In-Reply-To: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> References: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> Message-ID: <47EEBEFC.6040600@tim.thechases.com> > I was wondering what motivated so many people to give so much to the > Python community. fear, surprise, ruthless efficiency, an almost fanatical devotion to the BDFL, and nice red uniforms. Oh... -tkc From newsgroup898sfie at 8439.e4ward.com Thu Mar 20 18:31:02 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Thu, 20 Mar 2008 18:31:02 -0400 Subject: putting text through pager In-Reply-To: <9suab5-jvs.ln1@ID-262785.user.uni-berlin.de> References: <9suab5-jvs.ln1@ID-262785.user.uni-berlin.de> Message-ID: <665bb5-cg2.ln1@ID-262785.user.uni-berlin.de> Michael Goerz wrote, on 03/20/2008 04:43 PM: > Hi, > > I'm trying to print some variable through a pager (i.e. 'less') on a > linux system. My attempt was this: > > > ====== snip here ====== > import subprocess > > def put_through_pager(displaystring): > less_pipe = subprocess.Popen(\ > 'less', shell=True, \ > stdin=subprocess.PIPE).stdin > less_pipe.write(displaystring) > less_pipe.close() > > def main(): > put_through_pager(longstring) > > > longstring = """ > Lorem ipsum dolor sit amet,... > http://www.lipsum.com/ > """ > > main() > > ====== snip here ====== > > That doesn't work however: first of all, it only flashes the text for a > fraction of a second, and secondly, after I run the program my terminal > is broken, not echoing whatever I type back to me. > > Any suggestions for putting text through a pager from Python? This is > strictly on a linux system, of course. > > Thanks, > Michael Using a tempfile seems to be a good solution: def put_through_pager(displaystring): (temp_fd, tempname) = tempfile.mkstemp(".mail") temp_fh = os.fdopen(temp_fd, "w") temp_fh.write(displaystring) temp_fh.close() os.system("less %s" % tempname) os.unlink(tempname) From testone at gmail.com Mon Mar 24 20:56:06 2008 From: testone at gmail.com (Tess) Date: Mon, 24 Mar 2008 17:56:06 -0700 (PDT) Subject: Beautiful Soup Looping Extraction Question References: <301d00da-d0c7-47c1-9efd-894adf19cfc5@e60g2000hsh.googlegroups.com> Message-ID: <34b46ea7-7c87-4742-9d67-0a39e5daf983@e23g2000prf.googlegroups.com> Paul - thanks for the input, it's interesting to see how pyparser handles it. Anyhow, a simple regex took care of the issue in BS: for i in soup.findAll(re.compile('^p|^div'),align=re.compile('^center| ^left')): print i Thanks again! T From tjreedy at udel.edu Sat Mar 29 16:15:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Mar 2008 16:15:08 -0400 Subject: Error message from function definition References: <263d8c50803281910x32e5375h37fd8bfe10f9f36c@mail.gmail.com> Message-ID: Please do not post same question twice. From maxime.p at gmail.com Sun Mar 23 16:58:22 2008 From: maxime.p at gmail.com (Ulysse) Date: Sun, 23 Mar 2008 13:58:22 -0700 (PDT) Subject: Problems with joining Unicode strings Message-ID: <5b623e11-054d-44b7-bc65-d75922728dce@b1g2000hsg.googlegroups.com> Hello, I have problems with joining strings. My program get web page fragments, then joins them into one single web page. I have error when I try to join these fregments : "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 208: ordinal not in range(128)" Here is my code : # Parcours des RSS f = open('soupresult.html', 'w') d = feedparser.parse(rss_url) separator = '
' data = '' refresh_time = 2*60*60 #Secondes resume_news = [] # Parcours des RSS if len(d['items']) > 0: now = datetime.datetime.now() for item in d['items']: item_date = item.date_parsed print item_date item_date2 = datetime.datetime(item_date[0], item_date[1], item_date[2], item_date[3], item_date[4], item_date[5]) age_item = now - item_date2 age_item = age_item.days*24*3600 + age_item.seconds if age_item < refresh_time: url = item['link'] print item.title try: req = urllib2.Request(url) browser = urllib2.urlopen(req) data = browser.read() clean_item = data resume_news.append(item.title) resume_news.append(clean_item) except urllib2.URLError, e: print e.code f.write(u''.join(resume_news)) From castironpi at gmail.com Sun Mar 9 16:58:15 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 13:58:15 -0700 (PDT) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> <13t7smt4rn8rn32@corp.supernews.com> Message-ID: On Mar 9, 9:23?am, Steven D'Aprano wrote: > On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > > Okay, so I think I know where's the catch now -- you must rely on the > > fact that the protocol is implemented, there's no way to enforce it if > > you're expecting a parrot-like object. You'd try to call the speak() > > method and deal with the error if there's no such method? > > That's right. That's called "duck typing" -- if all you want is something > that quacks like a duck, then it doesn't matter if it actually is a duck > or not. > > Or if you prefer: if it quacks like a duck and swims like a duck, then > it's close enough to a duck as to make no difference. The syntax checker over here raised a warning on this one. "So close to a duck as." (I'm using the so...as construct in my Propositional Calculus program.) > try: > ? ? something.speak > except AttributeError: > ? ? # No speak() method, so it can't be a parrot. > ? ? do_something_else() It might be a dead parrot. HAR! > else: > ? ? # It seems to follow the parrot protocol. > ? ? yummy_goodness = something.speak(5) > ? ? assert "spam" in yummy_goodness.lower() P.S. Is 'resemblant' a word? So resemblant of a duck as. From rbossy at jouy.inra.fr Sat Mar 15 14:39:37 2008 From: rbossy at jouy.inra.fr (rbossy at jouy.inra.fr) Date: Sat, 15 Mar 2008 19:39:37 +0100 Subject: Creating a file with $SIZE In-Reply-To: References: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> <47D7D1F3.5040706@jouy.inra.fr> <47D7D5F2.8050303@mattnordhoff.com> <5a7a55c6-9a85-430d-955e-e22414085d31@e23g2000prf.googlegroups.com> <1krCj.19742$Ch6.3782@newssvr11.news.prodigy.net> Message-ID: <1205606377.47dc17e94926f@www.jouy.inra.fr> Quoting Bryan Olson : > Robert Bossy wrote: > > Bryan Olson wrote: > >> Robert Bossy wrote: > >>>> Robert Bossy wrote: > >>>>> Indeed! Maybe the best choice for chunksize would be the file's buffer > >>>>> size... > >> > >> That bit strikes me as silly. > >> > > The size of the chunk must be as little as possible in order to minimize > > memory consumption. However below the buffer-size, you'll end up filling > > the buffer anyway before actually writing on disk. > > First, which buffer? The file library's buffer is of trivial size, > a few KB, and if we wanted to save even that we'd use os.open and > have no such buffer at all. The OS may set up a file-specific > buffer, but again those are small, and we could fill our file much > faster with larger writes. > > Kernel buffers/pages are dynamically assigned on modern operating > systems. There is no particular buffer size for the file if you mean > the amount of kernel memory holding the written data. Some OS's > do not buffer writes to disk files; the write doesn't return until > the data goes to disk (though they may cache it for future reads). > > To fill the file fast, there's a large range of reasonable sizes > for writing, but user-space buffer size - typically around 4K - is > too small. 1 GB is often disastrously large, forcing paging to and > from disk to access the memory. In this thread, Matt Nordhoff used > 10MB; fine size today, and probably for several years to come. > > If the OP is writing to a remote disk file to test network > throughput, there's another size limit to consider. Network file- > system protocols do not steam very large writes; the client has to > break a large write into several smaller writes. NFS version 2 had > a limit of 8 KB; version 3 removed the limit by allowing the server > to tell the client the largest size it supports. (Version 4 is now > out, in hundreds of pages of RFC that I hope to avoid reading.) Wow. That's a lot knowledge in a single post. Thanks for the information, Bryan. Cheers, RB From ragu.n4 at gmail.com Mon Mar 3 23:33:20 2008 From: ragu.n4 at gmail.com (ragu) Date: Mon, 3 Mar 2008 20:33:20 -0800 (PST) Subject: Earn from home Message-ID: <1db8dd72-6f03-4a67-a40c-3cac9a8ccfed@i12g2000prf.googlegroups.com> Today, We are earning upto Rs.20,000 every month from internet without working hard and spending only 30 min daily in the internet. This Income is keep on increasingday by day.We are not joking. We are not making any false statement. It's 100% true ! http://eanrfromyourhome.blogspot.com From gregory.bronner at lehman.com Wed Mar 12 11:04:48 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Wed, 12 Mar 2008 11:04:48 -0400 Subject: Obtaining the PyObject * of a class In-Reply-To: References: <4866bea60803111203yedab3a2p20610854999002f4@mail.gmail.com><21CFA1FC32D3214EBFA2F449FF211E310EAD2996@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2998@nypcmg1exms318.leh.lbcorp.lehman.com> The short answer is that you don't need to: Anything that has a 'handle' attribute that is an int should be fine to pass into the function, and your typemap will be fine (with some additional checking) If you really insist on absolute type safety, however, you'll need an instance of the Pin class to compare to. Actually, all you need is an instance of the Pin Type -- you can use PyObject_TypeCheck (if I recall). Chances are, the name 'Pin' is already in your locals or globals, so you find the object, grab its type, and then check the type. Personally, I wouldn't bother. ________________________________ From: Cooper, Andrew [mailto:ACooper at cimtek.com] Sent: Tuesday, March 11, 2008 7:34 PM To: python-list at python.org Subject: RE: Obtaining the PyObject * of a class The part I'm having problem with is as follows: I want to replace the 'strcmp' below with a call to PyObject_IsInstance(o, pinClassPyObject) But I don't know how to get the PyObject* for the Pin class that is defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input->ob_type->tp_name,"Pin") == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle")); } else { PyErr_SetString(PyExc_TypeError,"arg must be type Pin"); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i < $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o->ob_type->tp_name, "Pin") == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle")); } else { PyErr_SetString(PyExc_TypeError,"list must contain Pins"); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,"not a list"); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list From: python-list-bounces+acooper=cimtek.com at python.org [mailto:python-list-bounces+acooper=cimtek.com at python.org] On Behalf Of Bronner, Gregory Sent: 11 March 2008 20:52 To: Michael Wieher; python-list at python.org; accooper at cimtek.com Subject: RE: Obtaining the PyObject * of a class I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. ________________________________ From: Michael Wieher [mailto:michael.wieher at gmail.com] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list at python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the "boilerplate" code, but honestly, copy & paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon : On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy wrote: > > "Cooper, Andrew" wrote in message > news:C03234BF0E2A8C419C4C307D0914EB730251D3A9 at MAILSERVER.cimtek.on.ca... > > | Are there any Python C API experts/SWIG experts out there that can help > | me with this issue please. > > | I',m currently using SWIG to generate a python interface to a C DLL. > > Some people have switched to using ctypes for this, and many other SWIG > users have stopped reading clp. But I hope someone answers who can. > Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Mar 19 16:06:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 17:06:38 -0300 Subject: Search the command history - Python Shell References: <16803ed0803190024u31b893d4gbc0433784c428f82@mail.gmail.com> <47E0E5F6.2010701@tim.thechases.com> Message-ID: En Wed, 19 Mar 2008 07:07:50 -0300, Tim Chase escribi?: >> Are there any simillar key combination in Python Shell like Linux Ctrl+R >> (reverse-i-search) to search the command history? > > It must depend on how your version of Python was built...mine > here on my Linux box has exactly that functionality. I press ^R > and start typing, and the line comes up from my typed history. On Windows you would type a few characters and use F8 and Shift-F8, or F7 to choose from a pop-up list. -- Gabriel Genellina From bearophileHUGS at lycos.com Sun Mar 16 11:58:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 16 Mar 2008 08:58:58 -0700 (PDT) Subject: Types, Cython, program readability References: <47b48a4b-7d28-49b8-9188-b63ed5ff4142@t54g2000hsg.googlegroups.com> Message-ID: <65f89bc3-0140-4378-b107-222654049e71@c19g2000prf.googlegroups.com> Tim Golden: > I'm not entirely sure why you think Pyrex should "contain a compiler". I think lot of Win users (computational biologists?), even people that know how to write good Python code, don't even know how to install a C compiler. >I'm fairly sure it's fine with MingW< (In the past?) I think you have to tweak it a bit. --------------- sturlamolden: >And although it may come as a surprise to you, Pyrex IS a compiler.< I meant a compiler that spits out the final executable a person can click on. >Being written in pure Python, Pyrex is equally easy to use on Windows and Linux.< Or maybe equally difficult :-) The computational biology students I was with think PythonWin is "easy" enough (or take a look at the "Processing" Java-like language user interface). Lowering entry difficulties is positive. Can things be made simpler for newbies? Bye, bearophile From mm007.emko at gmail.com Fri Mar 14 12:36:36 2008 From: mm007.emko at gmail.com (eMko) Date: Fri, 14 Mar 2008 09:36:36 -0700 (PDT) Subject: find string in file References: <72c6a9d6-0ca5-4338-9442-ce99343cd9e3@e25g2000prg.googlegroups.com> Message-ID: <93e7f081-0217-4119-a91e-eb54b70a4a48@s13g2000prd.googlegroups.com> An of course, you can use a regular expression. (Module "re"). From gowricp at gmail.com Thu Mar 20 03:51:43 2008 From: gowricp at gmail.com (Gowri) Date: Thu, 20 Mar 2008 00:51:43 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <29cd9085-b70f-4873-899e-3837d8e42d90@u69g2000hse.googlegroups.com> Hi Tim, I understand it's JSON. My problem is that it just prints crazy characters instead of the JSON data. Like I mentioned, this happens on my windows machine which has python 2.5. On the other hand, the same code worked perfectly great on my linux machine with python 2.3.4. What could the problem be? Regards, Gowri From musiccomposition at gmail.com Sun Mar 30 18:50:17 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 30 Mar 2008 15:50:17 -0700 (PDT) Subject: Using QSystemTrayIcon with PyQt References: <76680315-cadd-42ad-942c-3e89536819df@i12g2000prf.googlegroups.com> Message-ID: <6d0b8776-bb64-4a58-8ccb-46efa35d75a2@s50g2000hsb.googlegroups.com> On Mar 29, 11:02 pm, Alex Teiche wrote: > Hello, > > I am pretty new to Python, and have never learned C++. I am trying to > implement the following thing into my python application: > > http://doc.trolltech.com/4.3/qsystemtrayicon.html > > Through PyQt. I have been using PyQt for awhile and I know how do use > it, but I could not get this specific thing to work. Can someone give > me some hints as to get it working in Python? What problems are you having? > > Thanks a ton, > > Alex From oswald.harry at gmail.com Fri Mar 28 17:15:04 2008 From: oswald.harry at gmail.com (harryos) Date: Fri, 28 Mar 2008 14:15:04 -0700 (PDT) Subject: finding euclidean distance,better code? References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <3b584949-73a2-4c2b-aa28-8d1f6622cd8c@u10g2000prn.googlegroups.com> > the norm from which it is derived is called norm-1, or L1; the usual > euclidean distance is derived from norm-2. > If you only want to see if two things are "close enough", this provides a faster measure than the euclidean distance. thanks Gabriel for the detailed explanation.. if i were to calculate the euclidean distance in the above example how should i go about it..? should i replace distance = abs(input_wk - weights[image, :]) with something else? thanks again oharry From danb_83 at yahoo.com Mon Mar 31 21:52:18 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 31 Mar 2008 18:52:18 -0700 (PDT) Subject: Stuck in a loop References: Message-ID: <23ab0de7-c262-4624-898b-00b95f3a6561@b5g2000pri.googlegroups.com> On Mar 31, 8:22 pm, hexusne... at gmail.com wrote: > I wrote a simple algorithm and it keeps getting stuck in a loop. I > guess I'm just to tired to figure it out: > > compcount=[5,4,2,2] > suitrank=[0,0,0,0] > > trump=2 > l,lt=0,0 > while l<4: > while lt<4: > if l==trump: > l+=1 > if l>3: > break > if lt==trump: > lt+=1 > if compcount[l] suitrank[l]+=1 > lt+=1 > l+=1 > > In case you're wondering, the point is to rank suits from highest to > lowest based on how few cards each suit has. I hope that's enough > information. Inside the inner loop, lt never changes if lt != trump, so you get an infinite loop the first time when lt == 0. I think you may have misindented the last two lines. From abarun22 at gmail.com Fri Mar 7 10:44:19 2008 From: abarun22 at gmail.com (abarun22 at gmail.com) Date: Fri, 7 Mar 2008 07:44:19 -0800 (PST) Subject: swig-python import error Message-ID: <0e5e98df-f0f0-4607-82a8-044530b383f5@c33g2000hsd.googlegroups.com> Hi I am facing a problem while loading a SWIG generated shared module from python. The development is under HP-UX 32b platform. I use gcc version 4.0.2 to build the shared module. This is how i try to build the module. # Compilation GCC="$GCC -march=1.1" $GCC -v -c -fpic ${ETUDE}.c ${ETUDE}_wrap.c -DDOUBLE_PRECISION - DDON_DOUBLE_PRECISION ${PYTHON_INCLUDE_PATH} ${CHAINE_INCLUDE_PATH} # linking ld -b binary -g -shared ${ETUDE}.o ${ETUDE}_wrap.o -o _${ETUDE}.so \ -a archive ${LIBS_CHAINE_PATH} -lfichiers_r8 -lmem -lutilitaires - lsysteme -lcalcul -lmsgml -lcaractere \ -rpath -L/michprojects/ef/deli/Working/Source/deli9-PYAPI/Sandbox/libs/ chaine/PYAPI/don -L/michprojects/ef/deli/Working/Source/deli9-PYAPI/ Sandbox/libs/chaine/hppa_portable-hp-hpux11.11/Debug The module generated is called _don.so. In addition to that i set the module path in LD_LIBRARY_PATH environment variable. Th error looks like as follows. Import error: module cannot be loaded. But i am wondering how i am getting import error although every thing looks OK. Any ideas are most welcome and thanks in advance. Regards, Arun From pavloutefkros at gmail.com Sun Mar 2 08:09:10 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 05:09:10 -0800 (PST) Subject: tcp Message-ID: i have this small script which after some router configurations works. ########################################################## #! /usr/bin/python import socket HOST = '' PORT = 1515 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() conn.send('HTTP/1.1 200 OK\r\n') conn.send('Content-Type: text/html\r\n') conn.send('Server: test/1.0\r\n\r\n') conn.send('test') s.close() ########################################################## as you see it listens to 1515 until a connection is established and then it accepts it... the problem is that when it accepts the connection it sends those strings and exits, but then it exits the program. i want it to listen to 1515 then accept a connection, send.. and then listen to the port again and again until new connections are found. i've been struggling with try..except,while and all kinds of loops but always new erros pop up, or it overflows. From erikwickstrom at gmail.com Sun Mar 23 11:48:44 2008 From: erikwickstrom at gmail.com (erikcw) Date: Sun, 23 Mar 2008 08:48:44 -0700 (PDT) Subject: "Soup Strainer" for ElementSoup? Message-ID: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> Hi all, I was reading in the Beautiful Soup documentation that you should use a "Soup Strainer" object to keep memory usage down. Since I'm already using Element Tree elsewhere in the project, I figured it would make sense to use ElementSoup to keep the api consistent. (and cElementTree should be faster right??). I can't seem to figure out how to pass ElementSoup a "soup strainer" though. Any ideas? Also - do I need to use the extract() method with ElementSoup like I do with Beautiful Soup to keep garbage collection working? Thanks! Erik From R.Brodie at rl.ac.uk Tue Mar 4 08:58:36 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 4 Mar 2008 13:58:36 -0000 Subject: Eurosymbol in xml document References: <634sleF25sd22U1@mid.uni-berlin.de> Message-ID: "Robert Bossy" wrote in message news:mailman.1583.1204634888.9267.python-list at python.org... > If the file is declared as latin-1 and contains an euro symbol, then the file is > actually invalid since euro is not defined of in iso-8859-1. Paradoxical would be a better description than invalid, if it contains things that it can't contain. If you decoded iso-8859-15 as if it were iso-8859-1, you would get u'\xa4' (Currency Sign) instead of the Euro. From the original error: "UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in position 11834: character maps to " that seems to be what happened, as you said. From MartinRinehart at gmail.com Wed Mar 5 09:56:24 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 06:56:24 -0800 (PST) Subject: Why """, not '''? Message-ID: Why is """ the preferred delimiter for multi-line strings? From 2huggie at gmail.com Mon Mar 24 01:33:22 2008 From: 2huggie at gmail.com (Timothy Wu) Date: Mon, 24 Mar 2008 13:33:22 +0800 Subject: xml.sax problem Message-ID: Hi, I have created a very, very simple parser for an XML. class FindGoXML2(ContentHandler): def characters(self, content): print content I have made it simple because I want to debug. This prints out any content enclosed by tags (right?). The XML is publicly available here: http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&id=9622&retmode=xml I show a few line embedded in this XML: GO 3824 catalytic activity evidence: IEA Notice the third line before the last. I expect my content printout to print out "evidence:IEA". However this is what I get. ------------------------- catalytic activity ==> this is the print out the line before e vidence: IEA ------------------------- I don't understand why a few blank lines were printed after "catalytic activity". But that doesn't matter. What matters is where the string "evidence: IEA" is split into two printouts. First it prints only "e", then "vidence: IEA". I parsed 825 such XMLs without a problem, this occurs on my 826th XML. Any explanations?? Timothy -------------- next part -------------- An HTML attachment was scrubbed... URL: From ebgssth at gmail.com Tue Mar 11 08:48:59 2008 From: ebgssth at gmail.com (js) Date: Tue, 11 Mar 2008 21:48:59 +0900 Subject: TextWrapper keepking line breaks? In-Reply-To: References: Message-ID: Hi Arnaud, Great. Thanks for your help! On Tue, Mar 11, 2008 at 10:27 AM, Arnaud Delobelle wrote: > > On Mar 10, 11:31 pm, js wrote: > > Hi list, > > > > Can I make TextWrapper keep line breaks in the text? > > > > For example, > > > > >>> s = "spam\nham" > > >>> print wrap(s) > > > > spam > > ham > > > > As far as I can tell, there seems no way to do this, > > but before writing my own solution, I want to know whether > > the solution already exists or not. > > > > Thanks. > > Don't know but you could write: > > >>> import textwrap > >>> def wraplines(text): > ... return '\n'.join(textwrap.fill(line) for line in > text.split('\n')) > ... > >>> s = "spam\nham" > >>> print wraplines(s) > spam > ham > >>> > > HTH > > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > From Graham.Dumpleton at gmail.com Mon Mar 17 16:58:14 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 17 Mar 2008 13:58:14 -0700 (PDT) Subject: Apache binary error? References: Message-ID: On Mar 18, 4:43?am, Sean Allen wrote: > On Mar 17, 2008, at 10:55 AM, Michael Wieher wrote: > > > have simple webpage running > > > apache,mod_python > > > the error is binary.... > > ...binary as in "every other" time I load the page, Firefox keeps ? > > telling me I'm downloading a python script, and asks to open it in ? > > WINE, which is really strange. > > > then, alternately, it loads the page just fine. ?any clues as to why ? > > this is happening? > > -- > > for anything like mod_perl,mod_pythonetc the first thing i do when i ? > get really weird errors > it move to having only one apache process for testing. > > might want to start there. In mod_python handler code: req.content_type = 'text/plain' or otherwise. If you don't indicate what the response content type is web browsers will often try and work it out based on the extension in the URL. This is presuming you configured Apache correctly and your code is actually being executed and you aren't just serving up your code instead. Graham From Wubbulous at gmail.com Tue Mar 11 00:57:35 2008 From: Wubbulous at gmail.com (Wubbulous at gmail.com) Date: Mon, 10 Mar 2008 21:57:35 -0700 (PDT) Subject: Why does my compiler say invalid syntax then highlight...? References: Message-ID: <4612d533-6f73-4abb-9f56-69caf29fdbdc@s8g2000prg.googlegroups.com> I may have your problem: if prime < 0: primes.append(x) else: print x, "is not prime. " # highlights the final " you have to separate each output with a comma, so try adding one after x. From david.reitter at gmail.com Sat Mar 22 04:47:47 2008 From: david.reitter at gmail.com (David Reitter) Date: Sat, 22 Mar 2008 01:47:47 -0700 (PDT) Subject: Can I run a python program from within emacs? References: Message-ID: <3413d022-b9c6-4503-8d5a-d01ffead3c99@m36g2000hse.googlegroups.com> On Mar 20, 3:09 pm, jmDesktop wrote: > Hi, I'm trying to learn Python. I using Aquamac an emac > implementation with mac os x. I have a program. If I go to the > command prompt and type pythong myprog.py, it works. Can the program > be run from within the editor or is that not how development is done? > I ask because I was using Visual Studio with C# and, if you're > familiar, you just hit run and it works. On Python do I use the > editor for editing only and then run the program from the command > line? Thank you. Aquamacs, just like any variant of GNU Emacs, will show a Python menu. There's a "Start Interpreter" function, and one to evaluate the buffer (C-c C-c). It's pretty straightforward (a euphemism for obvious). If the Python menu doesn't show, then something is going wrong. M-x python-mode RET would switch it on. -- http://aquamacs.org -- Aquamacs: Emacs on Mac OS X http://aquamacs.org/donate -- Could we help you? Return the favor and support the Aquamacs Project! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 13:02:57 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 18:02:57 +0100 Subject: dynimac code with lambda function creation In-Reply-To: References: Message-ID: <47ebd337$0$13089$426a74cc@news.free.fr> Justin Delegard a ?crit : > So I am trying to pass an object's method call I assume you mean "to pass an object's method", since I don't get what passing "an object's method call" could mean. > to a function that > requires a function pointer. s/pointer/object/ There's nothing like a pointer in Python, and Python's functions are plain objects (instances of class 'function'). FWIW and WWAI, Python's methods are thin callable wrappers around the function, the class and (for bound methods) the instance. > I figured an easy way to do it would be to > create a lambda function that calls the correct method, but this is > proving more difficult than I imagined. "easy" ??? Here's the easy way to pass a method to a function: def func(method): return method(42) class MyClass(object): def __init__(self, name): self.name = name def foo(self, whatever): return "I'm %s and whatever is %s" % (self.name, str(whatever)) obj = MyClass('boo') print func(obj.foo) > Here is the function I'm using: > > def objectMethodCallerFunctionCreator(testerObj, method): > exec("y=lambda x: testerObj."+method+"(x)") > return y My my my... Looks like you're in for the Rube Goldberg Award !-) Whenever you think exec (or eval FWIW) is the solution, odds are there's a way better solution. If what you want is to retrieve a reference to an attribute you only know by it's name, getattr() is your friend. And in Python, methods are attributes. def objectMethodCallerFunctionCreator(testerObj, method): y = lambda x: getattr(testerObj, method)(x) return y But as we've seen above, all this is useless overcomplexification. Just pass the method like it was any other attribute, and you're done. > > Where testerObj is an instance of an object, and method is a string > representing the method to call. The problem is, when I actually run > the function created (y in this case), it tells me it can't find the > symbol testerObj in the global scope. This is related to exec as far as I can tell. > I have successfully created > similar functions, except without using the exec() call. e.g. > > def functionCreator(a, b, c): > return lambda d: myFunc(a, b, c, d) > > and it doesn't complain about the variables a, b, or c when being run. > I am assuming this is happening because of the exec() call, but I don't > see another way of calling a variable method on an object. Is there > some other way to do this that I'm missing? print func(getattr(obj, 'foo')) > I tried passing in 'method' > as a function pointer (to the method of the object), but that didn't > work either. What did you try, and what result did you get ? 'does not work' is (almost) the most useless description of a problem. From gnewsg at gmail.com Thu Mar 27 22:28:45 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 27 Mar 2008 19:28:45 -0700 (PDT) Subject: Change user on UNIX References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: <86b83385-697d-40d6-8bbb-dfeeba372040@d21g2000prf.googlegroups.com> Sorry for replying so late. I'll try to describe what I'm actually trying to implement so that maybe it can help you understand a little better. The application is an asynchronous FTP server implementation. I decided that it would be desirable to change the current implementation so that every time a filesystem operation is going to be made I temporarily change the current process ID to reflect the current logged-in user, execute the filesystem call and then switch back to the original process ID. Pseudo code: def STOR(filename): authorizer = UnixAuthorizer() authorizer.impersonate_user(current_logged_in_user) try: f = open(filename, 'w') finally: authorizer.terminate_impersonation() ... The UnixAuthorizer class is expected to provide the mechanism to change the current user (presumably via os.setegid()/os.seteuid()) and then switch back to the original one. Since we're talking about an asynchronous environment I tought that temporarily changing the process ID was the only way to do this. I'm sincerely not skilled enough about the UNIX world to know which are the security implications behind such an approach. Do you think it is reasonable? --- Giampaolo http://code.google.com/p/pyftpdlib/ From spe.stani.be at gmail.com Sat Mar 1 16:37:32 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 1 Mar 2008 13:37:32 -0800 (PST) Subject: PIL transparency gradient References: <6e44e95a-2cb0-4026-ad98-f6516e934e27@s37g2000prg.googlegroups.com> Message-ID: <4293dfd7-52aa-463e-b36c-c254a56616c4@s19g2000prg.googlegroups.com> On 1 mrt, 22:04, Allard Warrink wrote: > I would like to create a transparency gradient over an image using > PIL. But I don't have a clue how to do this... > Is there anyone out here who could give me some advise? Phatch (PHoto & bATCH) is an application based on PIL. Its actions contain many useful PIL recipes, such as applying a transparency gradient to an image. You basically need to create an 1pxx256px grayscale image which goes from 0 to 255. After that you can stretch it to the image size and add it as an alpha channel. You'll find the source code for this in the phatch/actions/mask.py Every action contains a 'raw' PIL function that can work independently outside the context of Phatch. This is by design, inspired by the MVC model in which you could see PIL as the model and Phatch as the View. You can get Phatch at: http://photobatch.stani.be Read first *carefully* the installation instructions for your platform: http://photobatch.wikidot.com/install Stani From mail at timgolden.me.uk Tue Mar 11 06:43:27 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Mar 2008 10:43:27 +0000 Subject: rmdir problem In-Reply-To: References: Message-ID: <47D6624F.8060203@timgolden.me.uk> royG wrote: > hi > i am checking if a directory exists and if it does i want to delete it > and its contents.then i want to create the directory before creating > files in it. > > def myfolderops(): > testdir='..\mytestdir' > #if dir exist remove it > if isdir(testdir): > rmdir(testdir) > #again create directory > mkdir(testdir) > > I am working on WinXP and logged in as admin in WinXP. when there is > no dir called '..\mytestdir' or an empty dir this code works removing > and creating the directory.but if the directory exists with contents > already then it causes an error 145 when rmdir is executed.the message > says 'directory is not empty' > what should i do to correct this? > (i need to remove the dir with its contents because each time i will > be putting diff files into it and donot want them to be mixed with old > files) Two things: 1) Use raw strings (r"..\blah") or forward slashes ("../blah") when messing with path names under windows. 2) Check out the shutils module: http://docs.python.org/lib/module-shutil.html TJG From lizhongan at gmail.com Mon Mar 17 20:26:57 2008 From: lizhongan at gmail.com (zaley) Date: Mon, 17 Mar 2008 17:26:57 -0700 (PDT) Subject: pass float array(list) parameter to C References: <6cf9ef62-4111-4c98-9b45-ba36fe538e97@s19g2000prg.googlegroups.com> <013c161a-931c-4576-935d-4341911a299f@s37g2000prg.googlegroups.com> Message-ID: <2bdcc2d7-4033-4973-b57a-b09a9043ac3f@s8g2000prg.googlegroups.com> On Mar 17, 10:59 pm, marek.ro... at wp.pl wrote: > You can also do it with ctypes only; too bad it's not really well > documented. c_float is a type of a floating point number and it has * > operator defined, so that c_float*4 is a type of a 4-element array of > those numbers. So if you want to construct an array of floats from a > list of floats, you can do it like this: > > from ctypes import c_float > > x = [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9] > float_array_type = c_float*len(x) > float_array = float_array_type(*x) > print float_array Is there has any difference between the following arrays ? Buf0=(c_float* 9)(57,57,57,57,57,5,5,5,5) Buf0=array('f', [57,57,57,57,57,5,5,5,5]) function called like this in python: ret= SetAnalog(9,Buf0) function prototype in C like this int SetAnalog(UINT uChannel,float* pBuf) { ....... } From mobiledreamers at gmail.com Tue Mar 25 23:02:21 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 25 Mar 2008 20:02:21 -0700 Subject: Socialsoft Startup Jobs Message-ID: http://www.thesocialsoft.com/jobs.html We - Build stuff that people love and use everyday - have a healthy disregard for the impossible - are not a conventional company and do not intend to be one - Think big, think fast and think ahead - set our goals high and work to exceed them, then we set our sights even higher - love our users more than anything else - launch early launch often - work on Web scale projects - believe that velocity matters - Care about interaction and user interface - grow by systematically removing bottlenecks - easy to know when something is a win - are experts in building scalable high performance clusters - scale horizontally - are scientific - collect data and understand it - start with "good enough" and iterate rapidly to reach perfection and critical mass - truly love the internet - see the elegance in simplicity - know what the user wants but listen to feedback - love to experiment with new fun viral ideas - are a really high energy team, it is not surprising for traffic to double overnight - aim to be better than the best - believe that we can change the world - This is a great company and we are moving quickly to make it even better - love fresh home made frozen yogurt across the street Cutting edge Tools We use - we love love Python - cheetah - memcached - postgresql - berkeley db - starling - jquery - subversion - git - nginx - haproxy - php We are the Most fun team in Silicon valley - beanbag plushies - Be in the driving seat of your project - Herman miller chairs - believe in developer productivity and happiness - live in downtown Palo Alto You (exceptional) - are a brilliant web software hacker who can design, build, and ship interesting web products - are among the best at what you do and routinely solve hard technical problems - have an understanding of successful web properties - have some insight into what makes them resonate with users - want to reach millions if not billions of people through your code - Are pragmatic and flexible - Care deeply about users and the user experience - should be available to work full-time or more Start your incredibly fun journey with the Socialsoft Team! - Join the Socialsoft dream, email jobs at thesocialsoft.com now -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Tue Mar 11 09:41:09 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Tue, 11 Mar 2008 13:41:09 -0000 Subject: Check For SELF Variable Existance In-Reply-To: <8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> References: <-8215347293566648508@unknownmsgid> <8c7f10c60803110621u5112697eme90e78cdae2c2920@mail.gmail.com> Message-ID: <00be01c8837d$9311ff40$b935fdc0$@rawlins@thinkbluemedia.co.uk> Thank you Simon, I was hoping there would be something as simple as that :-) Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Simon Brunning Sent: 11 March 2008 13:21 To: python-list at python.org Subject: Re: Check For SELF Variable Existance On Tue, Mar 11, 2008 at 11:00 AM, Robert Rawlins wrote: > I want to be able to check if a class has a certain property in its 'self' > scope, what's the best way to do this? >>> class Spam(object): ... def egg(self): ... if hasattr(self, 'chips'): print 'got chips!' ... >>> spam = Spam() >>> spam.egg() >>> spam.chips = 'beans' >>> spam.egg() got chips! -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list From durieux_br at yahoo.com.br Wed Mar 26 15:37:16 2008 From: durieux_br at yahoo.com.br (Fabio Durieux Lopes) Date: Wed, 26 Mar 2008 19:37:16 -0000 Subject: Daylight savings time problem Message-ID: Hi, I'm trying to execute some operations based on a file's time. The file's time is actually the file's name (e.g. FILE1_20080326170558). So I do this: fileTimeInSecs = time.mktime(time.strptime(timeString, "%Y%m%d%H%M")) timeString contains the date part of the file's name. Function strptime returns a time_struct, but my problem is that tm_isdst is set to 0, and when we enter daylight savings time the file's time is off by 1 hour. This time_struct is also read only so I can't change tm_isdst to -1. Anyone knows how to fix it? From lunasf at gmail.com Thu Mar 20 07:19:49 2008 From: lunasf at gmail.com (igbt) Date: Thu, 20 Mar 2008 04:19:49 -0700 (PDT) Subject: A question about a metacharacter Message-ID: I am creating a simple script which is using gtk. In this script you must enter a text, if you do not enter anything or you enter a dot, the script will be finished. However, if you don't enter anything the script works but if you enter a dot (.) the script does not work. I was investigating about it and I think the problem is with the dot character sss == "." . I was trying the same line with other metacharacters like *, (, ) ... and I found the same problem. I was looking for an example where I could see the way I could do it without any error but I did not find it. Could somebody tell me how can I solve this error? sss = entryName.get_text() # The script gets the text if sss == "" or sss == ".": gtk.main_quit() #The script finishes Thanks ; -) From arnodel at googlemail.com Wed Mar 26 04:47:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 26 Mar 2008 01:47:17 -0700 (PDT) Subject: Strange loop behavior References: Message-ID: On Mar 26, 8:35?am, Gabriel Rossetti wrote: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > ? ? while d != "": > ? ? ? ? file_str.write(d) > ? ? ? ? d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > I also tried writing the while's condition like so : len(d) > 0, but > that doesn't change anything. I tried step-by-step debugging using > PyDev(eclipse plugin) and I noticed this, once the while was read once, > it is never re-read, basically, the looping does happen, but just in > between the two lines in the loop's body/block, it never goes on the > while and thus never verifies the condition and thus loops forever. I > had been using psyco (a sort of JIT for python) and so I uninstalled it > and restarted eclipse and I still get the same thing. This looks like > some bug, but I may be wrong, does anybody understand what's going on here? > > Thanks, > Gabriel > > PS > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. No, it isn't the empty string, it is the printable representation of the empty string (because you wrap your f.read() calls in repr()), which is the string "''": >>> print "''" '' Why do you wrap f.read(...) in the repr() function? If you remove the two repr() I suspect your code will work. OTOH do you know that the read() method of file objects does what you want? You could simply write: file_str = f.read() Or are there some other factors that prevent you from doing this? -- Arnaud From kyosohma at gmail.com Mon Mar 31 09:44:48 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Mar 2008 06:44:48 -0700 (PDT) Subject: wxPython; adding a grid to a panel References: Message-ID: <2c49ad39-a388-40a6-bb2d-8e89b18b58ff@s37g2000prg.googlegroups.com> Moynes, On Mar 31, 5:01 am, "Moynes James" wrote: > I am a Python newbie hoping for some help with wxPython. > > I am trying to build a frame which will display a wx.grid and a number > of other widgets (text controls, static text and buttons). In all the > example scripts I have seen, a gird is added directly to a frame; is it > possible to place a grid in a box sizer or on a wx.Panel so that it can > be arranged with other widgets in the same frame? > > In the script below I have added two panels to a frame. I want to > display the grid in one panel (and later on add other widgets to the > other panel), but I cannot get the grid to display properly. > > What am I doing wrong? > > Thanks in advance for your help, > > James > > ################################################# > import wx > import wx.grid > > class TestTable(wx.grid.PyGridTableBase): > def __init__(self): > wx.grid.PyGridTableBase.__init__(self) > self.rowLabels = ["uno", "dos", "tres", "quatro", "cinco"] > self.colLabels = ["homer", "marge", "bart", "lisa", "maggie"] > > def GetNumberRows(self): > return 5 > > def GetNumberCols(self): > return 5 > > def IsEmptyCell(self, row, col): > return False > > def GetValue(self, row, col): > return "(%s,%s)" % (self.rowLabels[row], self.colLabels[col]) > > def SetValue(self, row, col, value): > pass > > def GetColLabelValue(self, col): > return self.colLabels[col] > > def GetRowLabelValue(self, row): > return self.rowLabels[row] > > class TestFrame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, title="Grid Table", > size=(500,200)) > panel1 = wx.Panel(self, -1) > panel2 = wx.Panel(self, -1) > hbox1 = wx.BoxSizer(wx.HORIZONTAL) > > hbox1.Add(panel1, 1, wx.EXPAND | wx.ALL, 3) > hbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 3) > > grid = wx.grid.Grid(panel2, wx.EXPAND) > table = TestTable() > grid.SetTable(table, True) > self.SetSizer(hbox1) > > app = wx.PySimpleApp() > frame = TestFrame() > frame.Show() > app.MainLoop() > > ################################################## I'd never used the PyGridTableBase to do this before, so I used the wxPython demo to figure it out. If you check out the GridCustomTable demo code, you'd probably have gotten it as well. Basically, you needed to add another class that inherited from wx.grid.Grid that would use the base you created. Here's the modified code: import wx import wx.grid as gridlib class TestTable(wx.grid.PyGridTableBase): def __init__(self): gridlib.PyGridTableBase.__init__(self) self.rowLabels = ["uno", "dos", "tres", "quatro", "cinco"] self.colLabels = ["homer", "marge", "bart", "lisa", "maggie"] def GetNumberRows(self): return 5 def GetNumberCols(self): return 5 def IsEmptyCell(self, row, col): return False def GetValue(self, row, col): return "(%s,%s)" % (self.rowLabels[row], self.colLabels[col]) def SetValue(self, row, col, value): pass def GetColLabelValue(self, col): return self.colLabels[col] def GetRowLabelValue(self, row): return self.rowLabels[row] class CustTableGrid(gridlib.Grid): def __init__(self, parent): gridlib.Grid.__init__(self, parent, -1) table = TestTable() # The second parameter means that the grid is to take ownership of the # table and will destroy it when done. Otherwise you would need to keep # a reference to it and call it's Destroy method later. self.SetTable(table, True) self.SetRowLabelSize(0) self.SetMargins(0,0) self.AutoSizeColumns(False) class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Grid Table", size=(500,200)) panel1 = wx.Panel(self, -1) panel2 = wx.Panel(self, -1) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(panel1, 1, wx.EXPAND | wx.ALL, 3) hbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 3) table = CustTableGrid(panel2) tblSizer = wx.BoxSizer(wx.VERTICAL) tblSizer.Add(table, 1, wx.ALL|wx.EXPAND, 5) panel2.SetSizer(tblSizer) self.SetSizer(hbox1) app = wx.PySimpleApp() frame = TestFrame() frame.Show() app.MainLoop() FYI: There's an excellent wxPython mailing list - http://wxpython.org/maillist.php Mike From mark.e.tolonen at mailinator.com Tue Mar 4 02:43:32 2008 From: mark.e.tolonen at mailinator.com (Mark Tolonen) Date: Mon, 3 Mar 2008 23:43:32 -0800 Subject: help needed with regex and unicode References: <6349rmF23qmbmU1@mid.uni-berlin.de> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:6349rmF23qmbmU1 at mid.uni-berlin.de... > On Tue, 04 Mar 2008 10:49:54 +0530, Pradnyesh Sawant wrote: > >> I have a file which contains chinese characters. I just want to find out >> all the places that these chinese characters occur. >> >> The following script doesn't seem to work :( >> >> ********************************************************************** >> class RemCh(object): >> def __init__(self, fName): >> self.pattern = re.compile(r'[\u2F00-\u2FDF]+') >> fp = open(fName, 'r') >> content = fp.read() >> s = re.search('[\u2F00-\u2fdf]', content, re.U) >> if s: >> print s.group(0) >> if __name__ == '__main__': >> rc = RemCh('/home/pradnyesh/removeChinese/delFolder.php') >> ********************************************************************** >> >> the php file content is something like the following: >> >> ********************************************************************** >> // Check if the folder still has subscribed blogs >> $subCount = function1($param1, $param2); >> if ($subCount > 0) { >> $errors['summary'] = '????????? ???????????????????????????????'; >> $errorMessage = '????????? ???????????????????????????????'; >> } > > Looks like an UTF-8 encoded file viewed as ISO-8859-1. Sou you should > decode `content` to unicode before searching the chinese characters. > I couldn't get your data to decode into anything resembling Chinese, so I created my own file as an example. If reading an encoded text file, it comes in as just a bunch of bytes: >>> print open('chinese.txt','r').read() ????????????????????? W?? sh?? M??igu??r??n. I am an American. Garbage, because the encoding isn't known. Provide the correct encoding and decode it to Unicode: >>> print open('chinese.txt','r').read().decode('utf8') ??????? W? sh? M?igu?r?n. I am an American. Here's the Unicode string. Note the 'u' before the quotes to indicate Unicode. >>> s=open('chinese.txt','r').read().decode('utf8') >>> s u'\ufeff\u6211\u662f\u7f8e\u56fd\u4eba\u3002 W\u01d2 sh\xec M\u011bigu\xf3r\xe9n. I am an American.' If working with Unicode strings, the re module should be provided Unicode strings also: >>> print re.search(ur'[\u4E00-\u9FA5]',s).group(0) ? >>> print re.findall(ur'[\u4E00-\u9FA5]',s) [u'\u6211', u'\u662f', u'\u7f8e', u'\u56fd', u'\u4eba'] Hope that helps you. --Mark From kay.schluehr at gmx.net Sun Mar 9 01:24:36 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 8 Mar 2008 22:24:36 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> On 9 Mrz., 06:30, Steven D'Aprano wrote: > Hard Exceptions: terminate the program unless explicitly silenced > Soft Exceptions: pass silently unless explicitly caught > > In this case, I agree with the Zen of Python ("import this"): > > Errors should never pass silently. > Unless explicitly silenced. Exceptions in Python don't necessarily signal errors. Just think about StopIteration. Note also that the common practice of letting *possible* errors passed silently is to return None instead of raising an exception. Moreove people create boilerplate like this try: k = lst.index(elem) ... except IndexError: pass instead of with lst.index(elem) as k: ... It would be interesting to think about SoftException semantics for such clauses: lst.index would neither raises a HardException nor does it return None but leads to skipping the with-block. Is it really so exotic that it requires the demand for more use cases? From gagsl-py2 at yahoo.com.ar Wed Mar 26 18:29:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 19:29:19 -0300 Subject: Filtering a Python list to uniques References: <202c9e84-2e8e-482c-a780-6c4ee5507b42@s8g2000prg.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 15:50:30 -0300, kellygreer1 escribi?: > On Mar 26, 5:45 am, hellt wrote: >> On 26 ???, 02:30,kellygreer1 wrote: >> >> > What is the best way to filter a Python list to its unique members? > How come the Set() thing seems to work for some people and I get the > 'unhashable' error? > > How do you test for 'membership' on a dictionary? > > # where tmp is the non-unique list > # dct is a dictionary where each unique key will be tied to a count > (the value) > # for testing I was setting the count to 0 > for v in tmp: > if not v in dct: dct[v] = 0 > > # I get unhashable error here. > # Even if I write it. > > for v in tmp: > if not v in dct.keys(): dct[v] = 0 > > What am I missing? Mutable objects can't be used as keys in a dict nor be members of a set (at least if the mutable part is used to implement the == comparison). Technically, they should not implement __hash__ so hash(x) fails on them - they are "unhashable". Objects that can be used as keys in a dictionary or be members of a set include: instances of all numeric types, strings, tuples, frozensets; all of them are immutable and hashable. Instances of user-defined classes that don't implement __eq__ nor __cmp__ nor __hash__ are hashable and can be used too. Classes that implement such special methods must ensure that (x==y) => (hash(x)==hash(y)) and in that case can be used too; else, they should not implement __hash__ at all. On the other hand, mutable containers can't be keys in a dict, nor be members of a set; including instances of lists, sets, dicts, all of them are mutable and unhashable objects. Read the Cookbook recipes that someone posted before; one of them is generic enough to handle all cases, trying the fastest approaches first. If you think that all your objects should be hashable, try to find which one isn't. -- Gabriel Genellina From sam at mas.pl Mon Mar 31 06:59:13 2008 From: sam at mas.pl (sam) Date: Mon, 31 Mar 2008 12:59:13 +0200 Subject: Prototype OO In-Reply-To: References: <47e24b99$0$24941$426a74cc@news.free.fr> <47e384cb$0$567$426a74cc@news.free.fr> <13u76h8mifniibc@corp.supernews.com> Message-ID: Steve Holden napisa?(a): >> 1. You have different syntax for named and unnamed (lambdas) >> functions. Functions and methods are different things in Python even >> if they have same syntax. But all these are still a pieces of code >> that you use repeatedly to make some task. >> > A knife and scissors are both used to cut things, but that doesn't mean > they are the same. Well -- sometimes you have to use many, many types of scissors. > I think you are bundling quite different things together here. The > difference in semantics between bound methods (where the instance > reference is added as a first argument) and regular functions (where no > additional argument is supplied) has nothing to do with the difference > between function and lambda definition syntax. You are right. One is syntax issue, and the second is language implementation issue. It would be better to have one unified syntax and one unified implementation. > The desire to provide information hiding is fundamentally against the > Python philosophy, which basically says that attribute values are > exposed for all to see. This avoids the nonsense of having to provide > setter and getter methods which Java imposes on the programmer. This philosophy is great and makes Python such a good language. But you can't go beyond what programmers need. If you do so, then you will have to implement tricks as __id. From frikker at gmail.com Thu Mar 6 19:08:27 2008 From: frikker at gmail.com (blaine) Date: Thu, 6 Mar 2008 16:08:27 -0800 (PST) Subject: Ncurses not found - embedded linux References: <63b1rjF26p2fkU1@mid.uni-berlin.de> Message-ID: <754dad0b-9d3e-4ca7-a5fc-38519312947f@q78g2000hsh.googlegroups.com> > > I hope this is trivial, and I apologize ahead of time if so. Would > > this perhaps be a compilation issue? Something we have to turn on in > > the python compile? > > Usually, you need not only the libraries but also the headers at > compilation time. Most probably these were missing. > > Diez Thank you for our response. Do you mean that the ncurses header should be in /usr/include upon compilation of python? Will python automatically pick up on these headers, or would I need to change compilation options? Thanks! -Blaine From __peter__ at web.de Sat Mar 15 18:09:57 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Mar 2008 23:09:57 +0100 Subject: Python Generators References: <44565433-3adf-45d9-84ee-78686d5b3495@f63g2000hsf.googlegroups.com> Message-ID: mpc wrote: > I am trying to write a while loop that will iterate over generators to > capture all the headers of FFCache directories. However, the > generators embedded within the argument of another generator do not > seem to re-initiate. the example below loops through and initiates the > generator embedded in the argument only once. Can anyone explain while > the generator will not re-initiate, and suggest a simple fix? A generator or generator expression does indeed only run once. >>> gen = (i for i in range(5) if i%2) >>> for i in range(3): ... print "---", i, "---" ... for k in gen: print k, ... print ... --- 0 --- 1 3 --- 1 --- --- 2 --- The fix is to use a list or list comprehension, or make a new generator every time you need one: >>> for i in range(3): ... print "---", i, "---" ... gen = (i for i in range(5) if i%2) ... for k in gen: print k, ... print ... --- 0 --- 1 3 --- 1 --- 1 3 --- 2 --- 1 3 At first glance I would guess that in your case all_caches is the culprit that has to be moved into the 'while True: ...' loop. > while True: > n += 1 > time.sleep(0.5) all_caches = (path for path,dirlist,filelist in os.walk("/Users/") if '_CACHE_MAP_' in filelist) > for path in all_caches: > headers = generate_headers(path) > for h in headers: > print h,n (Untested, because you didn't bother to provide a self-contained example) Peter From haraldarminmassa at gmail.com Wed Mar 12 06:09:59 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Wed, 12 Mar 2008 03:09:59 -0700 (PDT) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Doug, > File "VisionTrainer.py", line 49, in > File "SessionController.pyc", line 53, in > File "VisionEgg\__init__.pyc", line 42, in > File "VisionEgg\ParameterTypes.pyc", line 28, in > File "Numeric.pyc", line 93, in > File "Precision.pyc", line 26, in > File "Precision.pyc", line 23, in _fill_table > File "Precision.pyc", line 18, in _get_precisions > TypeError: data type not understood to my knowledge, "data type not understood" is a message not from core Python, but rather thrown from "your" code. What is happening around Precision.py, line 18? What does trigger that exception? My guess is, you are dealing with some custom imported modules which define "data type"s. (PIL does something similiar for supported images)... that is, some module is trying to import all definitions from a specific directory. That "dynamic importing" fails within py2exe --- all the importing has to be definit at py2exing-time. Please ready http://www.py2exe.org/index.cgi/PIL_and_py2exe and the other receipe on py2exe.org and try to adapt that knowledge to your application. Harald Harald From zubeido at yahoo.com.br Sun Mar 30 10:44:42 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sun, 30 Mar 2008 07:44:42 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> Message-ID: <1d297e7f-df0b-4b4a-8639-a4ca3505b3ca@59g2000hsb.googlegroups.com> Ok regarding Gerhard's comment of the try, except, pass, i came to understand that it's really bad code. And i should have referred that i put that there be cause i was getting: Traceback (most recent call last): File "C:\Python25\Projects\cp.py", line 48, in db = db() File "C:\Python25\Projects\cp.py", line 19, in __init__ self.cursor.execute( "CREATE TABLE database (album,filepath)" ) OperationalError: table database already exists But when i tried to handle the Operational error with : try: self.cursor.execute( "CREATE TABLE database (album,filepath)" ) except OperationalError: pass I would got: NameError: global name 'OperationalError' is not defined I searched the Internet and found that sqlite3.OperationalError was missing. Dumb me. Now even though i've been reading a bit about exceptions in python tutorial i've come to realize that my approach won't give me the results i want. To my understanding the try statement will still execute the statement within it until it produces the error. So even if i caught this OperationalError i wouldn't know what to do with it. What i'm going to study is whether it's possible to evaluate if a table already exists, and if so act accordingly. Duncan Booth wrote: >Are you absolutely certain of that? If you use print to try to debug the >value of an object you should usually use repr > print repr(audio['album']) As Gerhard correctly guessed i'm a newbie and didn't know of the existence repr. I've been reading about it in python documentation but have yet to analyze it more carefully. I guess the parentheses are just some form of maniac stupidity. Will try to be more clean about them. Thanks for all the patience and hope i've been more forthcoming in this post. From castironpi at gmail.com Thu Mar 27 07:38:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 04:38:24 -0700 (PDT) Subject: Partial Function Application and implicit self problem References: <47EB6480.2080402@wtf.websiteburo.oops.com> <47eb7f60$0$5151$426a74cc@news.free.fr> Message-ID: <40e8142f-ac8e-45ca-b7e6-ea8454b88021@m3g2000hsc.googlegroups.com> On Mar 27, 6:05?am, Bruno Desthuilliers wrote: > Gabriel Rossetti a ?crit : > > > > > > > Bruno Desthuilliers wrote: > >> Gabriel Rossetti a ?crit : > (snip) > >>> ? registerServiceAtomic = partial(__registerService, True) > >>> registerServiceNonAtomic = partial(__registerService, False) > > >>> I should pass self when applying partial, but then I can't do that > >>> since self is not available there. Does anyone have any ideas? > > >> registerServiceAtomic = partial(__registerService, atomic=True) > >> registerServiceNonAtomic = partial(__registerService, atomic=False) > > >> Caveat: you'll have to either invert the order of the atomic and > >> service params, or call the partials with named arg for service. > > > Ok, thanks, I didn't know you could do that, I though partial was always > > left to right > > It's left to right for positional arguments. Using named arguments, you > can pass them in whatever order. > > > (I had read that about curry) > > Which 'curry' ?-) I think 'prefix' should go in there. Can you try: partial( G.f, a, b ) ( self= obj )? (If that's too brief let me know.) From kyosohma at gmail.com Mon Mar 24 13:44:53 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 24 Mar 2008 10:44:53 -0700 (PDT) Subject: Is IronPython real Python? References: Message-ID: <2f252763-0fa8-4053-8cd7-c8b3395d3788@u10g2000prn.googlegroups.com> On Mar 24, 12:00 pm, jmDesktop wrote: > I know that IronPython and CPython are different in that one does not > use the .net framework, but are they both really the same Python > language. From my basic understanding, it will depend on what the > programmer's goal is as to which of the two would be used, but I > didn't know if they were really the same language. I would say that they're mostly the same. IronPython allows the developer to use any of the .NET libraries within their Python program, much like Jython allows Python to import Java libraries. The main IronPython website has a wiki that outlines the differences: http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Differences&referringTitle=Home Mike From jeff at schwabcenter.com Tue Mar 4 16:53:19 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 04 Mar 2008 13:53:19 -0800 Subject: SV: Polymorphism using constructors In-Reply-To: <635ndjF2551ajU1@mid.individual.net> References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: What does "SV" in the subject mean? From miki.tebeka at gmail.com Tue Mar 18 12:48:58 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 18 Mar 2008 09:48:58 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: Message-ID: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> Hello Dave, > Hi All. I've been formulating in my head a simple image editor. I > actually started prototyping is some time ago in Java, but am liking > Python more and more. My editor will be nowhere near the level of Gimp/ > Photoshop, but I do need fast pixel level control and display. For > instance, that means no automatic anti-aliasing and that I will be > implementing my own line drawing algorithms. > > I've got the high level architectual aspects of my program down, but > am stuck on what graphics API to use. I want a canvas area of > adjustable size which users can draw on with as little lag as > possible. The canvas area will be composed of layers (i.e. I require > an alpha channel) and I need to be able to zoom in and out of it (zoom > levels will be at fixed intervals, so this can be simulated if need > be.) > > I started looking at PyGame but realize that I need to integrate a GUI > into the whole thing (or integrate the image ?into the GUI rather) and > I didn't see a straightforward way to do that. Of course, I don't even > know if PyGame is the right API for the job anyways :P > > Any thoughts or ideas that could help me get started? Thanks! Apart from PIL, some other options are: 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object you can draw on 2. A bit of an overkill, but you can use PyOpenGL 3. ImageMagick bindings? (http://www.imagemagick.org/script/api.php) HTH, -- Miki http://pythonwise.blogspot.com From kyosohma at gmail.com Sat Mar 15 18:04:02 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 15 Mar 2008 15:04:02 -0700 (PDT) Subject: Python for BlackBerry References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Message-ID: <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> On Mar 15, 7:24 am, "Sandipan Gangopadhyay" wrote: > Is there a Python for BlackBerry? Thanks. > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of E-Lo > Sent: Saturday, March 15, 2008 6:03 AM > To: python-l... at python.org > Subject: Python for Palm OS > > Is there any other edition of Python for Palm OS instead of Pippy? > --http://mail.python.org/mailman/listinfo/python-list You might look at Mobile Python. I'm not sure if it works on Blackberry though: http://www.mobilepythonbook.org/ Mike From ttkk1024 at gmail.com Fri Mar 7 21:30:13 2008 From: ttkk1024 at gmail.com (smalltalk) Date: Fri, 7 Mar 2008 18:30:13 -0800 (PST) Subject: the way of "import" Message-ID: <5baa5fc3-264d-4f9d-8c58-07b31f68fc2d@u10g2000prn.googlegroups.com> I have three files names t1.py,t2.py,t3.py in e:\test\dir1,of course dir2 is exsit the content of t1.py as follow: t1.py import os print 'this is t1.py' os.chdir('..\\dir2') the content of t2.py as follow: print "this is t2.py" the content of t3.py as follow: import t1 import t2 if i run t3.py in cmd of windows as follow: python t3.py no errors show if i run t3.py in idle: >>> import t3 this is t1.py Traceback (most recent call las File "", line 1, in File "t3.py", line 2, in ImportError: No module named t2 can you give me a help? From grahn+nntp at snipabacken.se Sun Mar 30 19:15:39 2008 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 30 Mar 2008 23:15:39 GMT Subject: problem with logic in reading a binary file References: <63ab8669-15fc-433f-8203-2b8d5a419907@e67g2000hsa.googlegroups.com> <66141ee6-f6c4-44fd-8798-6c7ab0cb17d9@f63g2000hsf.googlegroups.com> <064a499e-c0f9-4c50-9a5a-b3f0f9df8842@b5g2000pri.googlegroups.com> <57d648ff-7c82-4c3e-b37f-12e082a71088@m73g2000hsh.googlegroups.com> Message-ID: On Sun, 30 Mar 2008 04:48:59 -0700 (PDT), hdante wrote: > On Mar 30, 4:31 am, John Machin wrote: >> On Mar 30, 3:58 pm, hdante wrote: >> > If you have some legacy binary file that you need to process, try >> > creating a C program that freads the binary file and printfs a text >> > equivalent. >> >> ... and that couldn't be done faster and better in Python?? > > No. A C struct is done faster and better than python (thus, the > correctness check is faster in C). Also, chances are high that there's > already an include file with the binary structure. If a C struct defines the file format, he is probably screwed already. There are no guarantees that even different compilers on the same machine have the same struct layout. I have never seen this done by a serious program. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fireball74 at NOSPAM.gmail.NOSPAM.com Fri Mar 14 14:05:00 2008 From: fireball74 at NOSPAM.gmail.NOSPAM.com (fireball) Date: Fri, 14 Mar 2008 13:05:00 -0500 Subject: "Open with IDLE" Missing Message-ID: <47dabe43$0$6483$4c368faf@roadrunner.com> I installed Parallels Desktop and Win XP Pro on my iMac for testing purposes. I installed Python 2.5.2, wxPython, and PythonCard. I cannot get the "Open with IDLE" in an Explorer window to work. All the registry entries are there too. Any ideas? Thanks! Jay From steve at REMOVE-THIS-cybersource.com.au Mon Mar 24 09:54:08 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 24 Mar 2008 13:54:08 -0000 Subject: Shortcutting the function call stack References: Message-ID: <13ufck0ccif5c1f@corp.supernews.com> On Mon, 24 Mar 2008 04:21:29 -0700, Julien wrote: > Hello all, > > I would like to do something like: > > def called(arg) > if arg==True: > !!magic!!caller.return 1 Instead of writing "if arg==True", or "if (arg==True)==True", or even "if ((arg==True)==True)==True", you should just write: "if arg:" That's probably all you need. > > def caller(arg) > called(arg) > return 2 def called(arg): return 1 def caller(arg): if arg: return called(arg) return 2 And if you wish to change the place where the decision is made: def called(arg): if arg: return 1 else: return 2 def caller(arg): return called(arg) > Here, the fake !!!magic!!! represents a statement (which I ignore) that > would make the caller function return a value different from what it'd > return normally. The statement you use to return a value different from what you would normally return is the "return" statement. You need to call that statement from the function doing the returning, not from another function. > The reason I want that is because I don't want the caller function to > know what's going on in the called function, and be shortcut if the > called function think it's necessary. Not knowing what's going on in called functions is why functions were invented in the first place. That's what they do. What shortcut do you think you might want to take? There are probably better solutions than playing around with the internals of the interpreter. I have a feeling you are trying to implement some sort of function cache, maybe... def check_in_cache(arg): # fake cache code if arg: !!magic!!caller.return 1 # not real Python def function(arg): check_in_cache(arg) # magic happens here # but if it doesn't, we do lots of calculations here return 2 # and finally return Is that the sort of thing you're trying for? If so, that's not the way to go about it. -- Steven From fetchinson at googlemail.com Wed Mar 12 21:05:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 12 Mar 2008 18:05:45 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > The photos are just coming straight from my digital camera. Same > > format (JPEG), varying size (6-10 megapixel) and I would like to be > > able to pick one and then query the database for similar ones. For > > example: I pick a photo which is more or less a portrait of someone, > > the query should return other photos with more or less portraits. If I > > pick a landscape with lot of green and a mountain the query should > > result in other nature (mostly green) photos. Something along these > > lines, of course the matches won't be perfect because I'm looking for > > a simple algorithm, but something along these lines. > > > > Ah. In that case, SIFT isn't for you. SIFT would work well if you have > multiple photos of the same object. Say, a building from different > angles, or the a vase against different backdrops. > > If I'm understanding your correctly, what you're attempting here is very > general and well into the highly experimental. I've been wishing for > such a feature to appear in something like Google Image Search > (pick/submit a photo and return similar images found on the web). I'm > sure if there's even a practical solution, Google (or MS) would be on it > already. > > The problem is that there isn't really one. Despite what you may see > claimed in university press releases and research papers, the current > crop of algorithms don't work very well, at least according to my > understanding and discussion with researchers in this field. The glowing > results tend to be from tests done under ideal conditions and there's no > real practical and commercial solution. > > If you restrict the domain somewhat, there are some solutions, but none > trivial. You are probably aware of the face searches available on Google > and Live. > > The histogram approach suggested by Shane Geiger may work for some cases > and in fact would work very well for identical resized images. I doubt > it will work for the general case. A mountain with a grassy plain at > noon has quite a different histogram from one at sunset, and yet both > have related content. Manual tagging of the images, a la Flickr, would > probably be your best bet. Since you seem to know quite a bit about this topic, what is your opinion on the apparently 'generic' algorithm described here: http://grail.cs.washington.edu/projects/query/ ? So far it seems to me that it does what I'm asking for, it does even more because it can take a hand drawn sample image and query the database for similar photos. There is even a python implementation for it here: http://members.tripod.com/~edcjones/pycode.html On the histogram method I agree that it won't work partly because of what you say and partly because it is terribly slow since it's comparing every single pixel. Thanks, Daniel From pavlovevidence at gmail.com Fri Mar 14 23:42:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 14 Mar 2008 20:42:56 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <39d64506-17f6-4c74-ba26-52289b38e7da@m3g2000hsc.googlegroups.com> <47d90982$0$22008$426a74cc@news.free.fr> <8b40978a-4a8d-4fa2-ba8e-09d8402a854a@i12g2000prf.googlegroups.com> Message-ID: On Mar 14, 6:37 pm, Alex wrote: > On Mar 13, 6:21 pm, Carl Banks wrote: > > > On Mar 13, 7:02 am, Bruno Desthuilliers > > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > > > Alex a ?crit : > > > (sni) > > > > > First of all thanks all for answering! > > > > > I have some environment check and setup in the beginning of the code. > > > > I would like to move it to the end of the script. > > > > Why ? (if I may ask...) > > Sure, because of a readability (similar to function declarations in > C). > > > > > > > But I want it to > > > > execute first, so the script will exit if the environment is not > > > > configured properly. > > > > If you want some code to execute first when the script/module is loaded, > > > then keep this code where it belongs : at the beginning of the script. > > > I concur with Bruno's recommendation: stuff you want to do first > > should come first in the script. Things like BEGIN blocks hurt > > readability because you can't identify where execution begins without > > reading the whole file. > > > Having said that, one thing that often happens in Python scripts is > > that all the functions are defined first, then the script logic > > follows. So you could put the meat of your script in a function, then > > the "BEGIN" stuff after that functions: > > > def run_script(): > > # > > # script contained in this long function > > # > > > # Then test preconditions here... > > if os.environ["HELLO"] != "WORLD": > > sys.exit(2) > > > # Then call the run_script functions > > run_script() > > > But having said THAT, I don't recommend you do that with > > preconditions. If the script has a quick early exit scenario, you > > really ought to put that near the top, before the function > > definitions, to clearly show to a human reader what is necessary to > > run the script. > > > Carl Banks > > Hi, > > Maybe i was a little bit unclear... I meant that i wanted to do > something like this: > > #!usr/bin/env python > > check_env() > > from subprocess import * > > class MyClass: > # Class definition > > def check_env(): > # Code > > if __name__ == "__main__": > # Script logic > > The thing is, as i saw, that Python doesn't recognize the > "check_env()" function before it reaches the "def" statement. You could rearrange it like this and it will work: #!usr/bin/env python def check_env(): # Code check_env() from subprocess import * class MyClass: # Class definition if __name__ == "__main__": # Script logic Or, better yet, do what Arnaud Delobelle suggests. It's not a big deal to move imports down the page a bit, as long as you throw in a few clear comments explaning what you're doing and why. You might also consider putting check_env() in a separate module. Carl Banks From Lie.1296 at gmail.com Tue Mar 11 11:58:37 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 08:58:37 -0700 (PDT) Subject: __iter__ yield References: Message-ID: On Mar 10, 3:58 am, duccio wrote: > Hello! > Someone knows if it's possible to make this __iter__ function with just > one 'yield' intead of two? > Is there some simpler way to make this __iter__ iter through all nodes? > Thanks! > > class Node: > def __init__(self, data=None): > self.childs=[] > self.data=data > def appendNode(self, n): > node=Node(n) > self.childs.append(node) > return node > def __str__(self): > return '<'+str(self.data)+'>' > def __iter__(self): > yield self #1 > for n in self.childs: > for nn in n.__iter__(): > yield nn #2 > > n=Node() > n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) > n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) > for node in n: > print node Technically, the root node isn't a child node, and thus it shouldn't show up in the iteration. I think a more semantically correct way for this is to have the __str__() returns the current Node + All Descendants Nodes (like the one you wanted for __iter__) and while __iter__ only yields the child nodes (used by the __str__ to iterate through itself), like this: class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): ## Returns root node + all descendants return '<%s>\n' % self.data + ''.join(str(child) for child in self) def __iter__(self): ## yields childrens only for n in self.childs: yield n n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) ## Note I added the line below for testing branches in ## lower nodes n.childs[0].appendNode(222) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) print n The missing functionality of returning current Node's name can be easily solved by adding it in another function. The main problem with __iter__ behavior you originally wanted is that it doesn't reflect the nesting behavior of the Node class and you could've been equally well served by using flat data structure if you do that. I smell a bad data structure design here, you'd better revise your design. To reflect the nesting, you could do it like this: class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): ## This reflects nesting behavior better return '\n<%s>' % (str(self.data) + ''.join(str(child) for child in self)) ## Uncomment this and Comment the statement above ## for an alternate data structure you might be ## interested in, the format below resembles HTML ## curNode = str(self.data) ## return '\n<%s>%s\n' % ( ## curNode, ## ''.join(str(child) for child in self), ## curNode) def __iter__(self): for n in self.childs: yield n n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.childs[0].appendNode(222) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) print n This changes the data structure quite a lot though, but the data structure is bad from the start. From andrei.avk at gmail.com Mon Mar 24 15:21:04 2008 From: andrei.avk at gmail.com (AK) Date: Mon, 24 Mar 2008 14:21:04 -0500 Subject: ANN: Tobu 0.4j Message-ID: <47e7f111$0$16691$4c368faf@roadrunner.com> This is an initial announcement. Tobu is a freeform database / tagger / PIM and more. It works in both Linux and Windows and uses wxPython framework and pysqlite. Comments, suggestions, feature requests and critique are gladly appreciated. Tutorial with links to download page and to graphical overview page is located at the following link. It's best to start with graphical overview page that shows screenshots of main window and menus with thorough explanations of functionality of most items. http://www.lightbird.net/tobu/ From aisaac at american.edu Thu Mar 13 15:48:28 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 13 Mar 2008 19:48:28 GMT Subject: no more comparisons In-Reply-To: References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: >> Dan Bishop wrote: >>> def cmp_key(cmp_fn): >>> class CmpWrapper(object): >>> def __init__(self, obj): >>> self.obj = obj >>> def __cmp__(self, other): >>> return cmp_fn(self.obj, other.obj) >>> return CmpWrapper > On Mar 13, 12:38 pm, Alan Isaac wrote: >> how is this supposed to work if __cmp__ is no longer >> being called? (Which was my understanding.) Carl Banks wrote: > It won't. In Python 3.0 you'd have to write this class in terms of > rich comparisons (__lt__, __gt__, etc.). Exactly. So something simple (define an anonymous function) has become a bit of a pain. On the other hand, I've looked through my extant code and have not found a use of ``cmp`` that I cannot work around. So maybe this is not as bad as I feared. What are some use cases that will clearly be harder (i.e., at least require a slightly elaborate wrapper) after this change? Cheers, Alan Isaac From roy at panix.com Wed Mar 12 18:15:54 2008 From: roy at panix.com (gnu.gcc.help) Date: Wed, 12 Mar 2008 15:15:54 -0700 (PDT) Subject: How to parse this timestamp? Message-ID: I've got timestamps in a file that look like: [19-Aug-2007 07:38:43+216ms NZST] How can I parse them? I don't see any way to build a strftime() format string that can handle the +216ms part. The best I can see is tearing it all apart with a regex, but I'm trying to avoid that pain if I can. (PS: I have no clue why google groups thinks it should put "gnu.gcc.help" on the from line) From erikwickstrom at gmail.com Fri Mar 14 14:47:05 2008 From: erikwickstrom at gmail.com (erikcw) Date: Fri, 14 Mar 2008 11:47:05 -0700 (PDT) Subject: Custom Exception Value? Message-ID: <5fbe35d4-6590-41c2-824d-0b1656173829@x30g2000hsd.googlegroups.com> Hi, When I use sys.exc_info() on one of my custom exception classes, the "message"/value isn't returned. But it is when I use a built in exception. Example: In [32]: class Test(Exception): ....: def __init__(self, x): ....: self.value = x ....: def __str__(self): ....: return repr(self.value) ....: ....: In [39]: try: ....: raise Test('mess') ....: except: ....: sys.exc_info() ....: ....: Out[39]: (, Test(), ) In [40]: try: ....: 1/0 ....: except: ....: sys.exc_info() ....: ....: Out[40]: (, ZeroDivisionError('integer division or modulo by zero',), ) Wy does the output of ZeroDivisionError appear in sys.exc_info() but for test it is just Test() (should be Test('mess') right??) Thanks! From wingi at gmx.com Tue Mar 11 12:52:43 2008 From: wingi at gmx.com (wingi at gmx.com) Date: Tue, 11 Mar 2008 09:52:43 -0700 (PDT) Subject: Exctract GIF comment from image Message-ID: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Hi, simple question: The PIL does not support reading the optional description in GIF Images. http://www.pythonware.com/library/pil/handbook/format-gif.htm After some reasearch I could not find a python solution for this, any suggestions? Thanx, Wingi. From zentraders at gmail.com Sat Mar 22 12:38:24 2008 From: zentraders at gmail.com (Zentrader) Date: Sat, 22 Mar 2008 09:38:24 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> Message-ID: <25c85c01-4978-448b-b4f5-0ef3a52ea5d1@e10g2000prf.googlegroups.com> > if ('one', 'two') are in f: ... "are" gives me an error in Python 2.5 with a "from future import *" statement included. What version and platform are you running. Also, the docs don't mention it. http://docs.python.org/ref/keywords.html From ptmcg at austin.rr.com Wed Mar 5 14:29:30 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 5 Mar 2008 11:29:30 -0800 (PST) Subject: What is a class? References: Message-ID: <3f8799fa-9ba0-406e-b140-df07d5aa6ca0@e25g2000prg.googlegroups.com> On Mar 5, 12:50?pm, castiro... at gmail.com wrote: > What is a class that is not a module? Please stop posting these one-liner beginner questions. If you can type it in one line, you can enter it on the Google.com or Ask.com query page and get a wealth of *existing* information, from tutorials, documentation, online presentations. If you are able to phrase such a question, you are capable of doing a little research and experimentation on your own. These posts translate to "I'm too lazy to use Google, or too cheap to buy a Python book, or too lazy to read it, or too impatient to do my own experimenting - much better to just post on c.l.py and have the answer spoon-fed to me!" I refuse to spoon feed you the answer to this question when plenty of supporting material is already available. -- Paul From bearophileHUGS at lycos.com Mon Mar 24 11:52:59 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 24 Mar 2008 08:52:59 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as a firstprogramming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <5d973779-507c-4248-a218-61fa1c870003@m44g2000hsc.googlegroups.com> Paul Rubin>It's at least pretty good. It's not ideal, but nothing ever is.< I agree. At the moment Python is among the best languages for that, but it's not perfect for that purpose. I think newbies may need a bit more structured language, where you have to put things in a certain order to have a working program. I think this may teach them some good programming habits. Pascal is a bit too much old today, but it helps learn how to program in a tidy way. I am not sure about this, I'd like to have more data to be able to sort out this freedom/structure alternative regarding teaching languages. Another possible downside of Python is that it doesn't allow you to know very well what's under the language, so you can't use pointers and memory very well, so you can't learn those things very well. You need a different language for that, like C (or Pascal) or assembly, but such languages are useful later, and less as very first languages, especially for very young people. Paul Rubin>Chris Okasaki (of functional data structures fame) has an interesting blog post about why indentation-based structuring is a big help for teaching:< I have quite appreciated that article, and other people are doing similar things for C and C++ (I'd like to do something similar for D): http://blog.micropledge.com/2007/09/nobraces/ And OCaml: http://people.csail.mit.edu/mikelin/ocaml+twt/ Arnaud Delobelle>My other 'coming of age' was when I took a lambda- calculus course at university. I felt like a man who's had a black and white TV set all his life and watches colour TV for the first time.< Scheme-like languages are surely interesting, and eventually a programmer can learn one of them, but I think as a very first language Python is fitter, because its syntax is more compatible with a normal little trained human mind. 7stud>Beginning programmers in grades 9-12 are not going to understand issues like that, and it would be a mistake to try and introduce them. Beginning programmers should be concentrating their efforts on learning the syntax of a language and basic constructs like for-loops and if statements.< This is wrong. Some languages like Scheme are quite fit for young people, and they don't even need a for loop. A 7-9 years old person is able to understand quite a lot, and computer science and programming aren't based on syntax. They are more based on the fun of problem solving, and similar things. Syntax is important because it's the tool that allows you to tell the computer how to compute the results of the problems you have (usually) already solved, but it can't be the purpose, even in a first course of programming. When you want to teach painting to a 6 year old child your purpose isn't teaching her/him all about the structure of the canvas and brushes and the chemistry of the pigments, but how to have fun putting all the colors on the canvas/ paper, trying to create some image, for fun. (On the other hand you can teach to love chemistry to a 6-8 year old person, showing how much it can be fun, if you start talking about the chemistry behind the colors of fireworks, but that's not panting anymore). Ben C>Why does Python not have a switch or until statement?< Maybe because it thinks syntax minimalism is a virtue, or maybe because they aren't easy to add (try to design a do-while using Python- like syntax). Ben C>Why are very common objects (stack, queue, linked list) not builtin? etc.< Because it was a small language, used for scripting purposes, I think. You need those data structures if you want higher performance (in speed and/or memory used) but performance was not one of the main purposes of Python. Another purpose for those data structures is to teach them, but a good teaching language is probably one that allows you to write your own versions of them. Today the collections module and other built-in modules gives you some of those data structures, you just need to import them, so using them isn't much a hassle, even if they aren't built in. Aahz>The problem with lambda is that too often it results in clutter< Probably I am missing your point, but I'd like to remind people the syntax for lambdas in the last C# versions: x, y => x * 2 + y Instead of the Python syntax: lambda x, y: x * 2 + y I think that C# syntax is nice and readable enough. Terry Reedy>[lot of things] Yes, fundamentally different categories of types are (sensibly) treated differently with repect to definition and namespace names, but calling that 'disharmony' depends on the listener.< Thank you for your interesting explanation. Bye, bearophile From lbonafide at yahoo.com Sun Mar 16 12:38:06 2008 From: lbonafide at yahoo.com (lbonafide at yahoo.com) Date: Sun, 16 Mar 2008 09:38:06 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <6c54548d-de3e-4c79-b3c7-c14a87407c6e@p25g2000hsf.googlegroups.com> On Mar 16, 6:10 am, Bruce Eckel wrote: > I think a lot of people have been caught up in the idea that we need > to commercialize Python, and ride some kind of wave of publicity the > way that Java and C# and Rails seem to have done. This coming from someone who caught the Java wave and rode it for a decade. From magdoll at gmail.com Tue Mar 11 18:41:24 2008 From: magdoll at gmail.com (Magdoll) Date: Tue, 11 Mar 2008 15:41:24 -0700 (PDT) Subject: merging intervals repeatedly Message-ID: Hi, I have to read through a file that will give me a bunch of intervals. My ultimate goal is to produce a final set of intervals such that not two intervals overlap by more than N, where N is a predetermined length. For example, I could read through this input: (1,10), (3,15), (20,30),(29,40),(51,65),(62,100),(50,66) btw, the input is not guaranteed to be in any sorted order. say N = 5, so the final set should be (1,15), (20, 30), (29, 40), (50, 100) Is there already some existing code in Python that I can easily take advantage of to produce this? Right now I've written my own simple solution, which is just to maintain a list of the intervals. I can use the Interval module, but it doesn't really affect much. I read one interval from the input file at a time, and use bisect to insert it in order. The problem comes with merging, which sometimes can be cascading. ex: read (51,65) ==> put (51,65) in list read (62,100) ==> put (62,100) in list (overlap only be 4 <= N) read (50,66) ==> merge with (51,65) to become (50,66) ==> now can merge with (62,100) Of course I can check for cascading merges by pivoting around the position where the insertion would've taken place...but just wondering, is there some other nice way to do this? I also intuitively don't sense a need for using trees, unless someone's already written it, the interface is easy to use, and it won't result in more insert/ delete/structure changes that nullifies its beauty...(also I'm not using the output list for searching) Thanks in advance. From python.list at tim.thechases.com Mon Mar 10 11:03:59 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Mar 2008 10:03:59 -0500 Subject: parsing directory for certain filetypes In-Reply-To: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> References: <90b5f10c-f974-4f2a-b210-37610e54bdc2@i12g2000prf.googlegroups.com> Message-ID: <47D54DDF.7000801@tim.thechases.com> > i wrote a function to parse a given directory and make a sorted list > of files with .txt,.doc extensions .it works,but i want to know if it > is too bloated..can this be rewritten in more efficient manner? > > here it is... > > from string import split > from os.path import isdir,join,normpath > from os import listdir > > def parsefolder(dirname): > filenms=[] > folder=dirname > isadr=isdir(folder) > if (isadr): > dirlist=listdir(folder) > filenm="" > for x in dirlist: > filenm=x > if(filenm.endswith(("txt","doc"))): > nmparts=[] > nmparts=split(filenm,'.' ) > if((nmparts[1]=='txt') or (nmparts[1]=='doc')): > filenms.append(filenm) > filenms.sort() > filenameslist=[] > filenameslist=[normpath(join(folder,y)) for y in filenms] > numifiles=len(filenameslist) > print filenameslist > return filenameslist > > > folder='F:/mysys/code/tstfolder' > parsefolder(folder) It seems to me that this is awfully baroque with many unneeded superfluous variables. Is this not the same functionality (minus prints, unused result-counting, NOPs, and belt-and-suspenders extension-checking) as def parsefolder(dirname): if not isdir(dirname): return return sorted([ normpath(join(dirname, fname)) for fname in listdir(dirname) if fname.lower().endswith('.txt') or fname.lower().endswith('.doc') ]) In Python2.5 (or 2.4 if you implement the any() function, ripped from the docs[1]), this could be rewritten to be a little more flexible...something like this (untested): def parsefolder(dirname, types=['.doc', '.txt']): if not isdir(dirname): return return sorted([ normpath(join(dirname, fname)) for fname in listdir(dirname) if any( fname.lower().endswith(s) for s in types) ]) which would allow you to do both parsefolder('/path/to/wherever/') and parsefolder('/path/to/wherever/', ['.xls', '.ppt', '.htm']) In both cases, you don't define the case where isdir(dirname) fails. Caveat Implementor. -tkc [1] http://docs.python.org/lib/built-in-funcs.html From bearophileHUGS at lycos.com Fri Mar 28 08:24:41 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 28 Mar 2008 05:24:41 -0700 (PDT) Subject: problem with sorting References: <7053398c-5ecc-45ee-a8c7-7813392a77f8@d1g2000hsg.googlegroups.com> <126695f1-3978-482d-8995-946bbbc97085@2g2000hsn.googlegroups.com> Message-ID: <1b5564b6-8e40-43e1-90bd-cea0dd3a8edf@l42g2000hsc.googlegroups.com> Duncan Booth: > Both this and raj's suggestion create a single sorted list. Your suggestion > creates two lists: the unsorted one and a separate sorted one. In most > cases the difference is probably insignificant, but if you have a *lot* of > values it might make a difference. The good thing of Python 3.0 is that it forces you to do the right thing here :-) Bye, bearophile From gagsl-py2 at yahoo.com.ar Sun Mar 9 16:19:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 18:19:05 -0200 Subject: the way of "import" References: <5baa5fc3-264d-4f9d-8c58-07b31f68fc2d@u10g2000prn.googlegroups.com> Message-ID: En Sat, 08 Mar 2008 00:30:13 -0200, smalltalk escribi?: > I have three files names t1.py,t2.py,t3.py in e:\test\dir1,of course > dir2 is exsit > the content of t1.py as follow: > t1.py > import os > print 'this is t1.py' > os.chdir('..\\dir2') > the content of t2.py as follow: > print "this is t2.py" > the content of t3.py as follow: > import t1 > import t2 > > > if i run t3.py in cmd of windows as follow: > python t3.py > > no errors show > > if i run t3.py in idle: >>>> import t3 > this is t1.py > Traceback (most recent call las > File "", line 1, in > File "t3.py", line 2, in > ImportError: No module named t2 > > can you give me a help? Which Python version? Which Windows version? With IDLE from Python 2.5.1 on XP I don't get the error (and that's the right thing) -- Gabriel Genellina From code at pizzashack.org Mon Mar 24 22:03:56 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Mar 2008 22:03:56 -0400 Subject: Python 2.2.1 and select() In-Reply-To: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> Message-ID: <20080325020356.GF26870@dragontoe.org> On Mon, Mar 24, 2008 at 05:52:54PM -0700, Noah wrote: > On Mar 24, 2:58 pm, Derek Martin wrote: > > If and only if the total amount of output is greater than the > > specified buffer size, then reading on this file hangs indefinitely. > I think this is more of a limitation with the underlying clib. > Subprocess buffering defaults to block buffering instead of > line buffering. That's an interesting thought, but I guess I'd need you to elaborate on how the buffering mode would affect the operation of select(). I really don't see how your explanation can cover this, given the following: 1. The subprocess used to test, in both the case where it worked, and the case where it did not, was the very same shell script -- not a compiled program (well, bash technically). As far as I'm aware, there haven't been any significant changes to the buffering mode defaults in glibc... But I could easily be mistaken. 2. By default, STDERR is always unbuffered, whether or not STDOUT is a terminal device or not. 3. The actual subproc I care about is a perl script. 4. Most importantly, the whole point of using select() is that it should only return a list of file objects which are ready for reading or writing. In this case, in both the working case (Python 2.4+ on Red Hat) and the non-working case (Python 2.2.1 on Debian 3.1), select() returns the file object corresponding to the subprocess's STDOUT, which *should* mean that there is data ready to be read on that file descriptor. However, the actual read blocks, and both the parent and the child go to sleep. This should be impossible. That is the very problem select() is designed to solve... Moreover, we've set the buffer size to 8k. If your scenario were correct, then at the very least, as soon as the process wrote 8k to STDOUT, there should be data ready to read. Assuming full buffering is enabled for the pipe that connects STDOUT of the subprocess to the parent, the call to select() should block until one of the following conditions occur: - 8k of data is written by the child into the pipe - any amount of data is written to STDERR - the child process terminates The last point is important; if the child process only has 4k of data to write to STDOUT, and never writes anything to STDERR, then the buffer will never fill. However, the program will terminate, at which point (assuming there was no explicit call to close() previously) the operating system will close all open file descriptors, and flush all of the child's I/O buffers. At that point, the parent process, which would be sleeping in select(), will wake up, read the 4k of data, and (eventually) close its end of the pipe (an additional iteration through the select() loop will be required, I believe). Should the program write output to STDERR before the 8k STDOUT buffer is full, then again, the parent, sleeping in select(), will awaken, and select will return the file object corresponding to the parent's end of the pipe connecting to the child's STDERR. Again, all of this is the essence of what select() does. It is supposed to guarantee that any file descriptors (or objects) it returns are in fact ready for data to be read or written. So, unless I'm missing something, I'm pretty certain that buffering mode has nothing to do with what's going on here. I think there are only a few possibilities: 1. My implementation of the select() loop is subtlely broken. This seems like the most likely case to me; however I've been over it a bunch of times, and I can't find anything wrong with it. It's undenyable that select is returning a file object, and that reads on that file object immediately after the call to select block. I can't see how this could be possible, barring a bug somewhere else. 2. select.select() is broken in the version of Python I'm using. 3. The select() system call is somehow broken in the Linux kernel I'm using. I tend to rule this out, because I'm reasonably certain someone would have noticed this before I did. The kernel in question is being used on thousands of machines (I'm not exaggerating) which run a variety of network-oriented programs. I can't imagine that none of them uses select() (though perhaps its possible that none use it in quite the manner I'm using it here). But it may be worth looking at... I could write an implementation of a select() loop in C and see how that works. If you can see any flaw in my analysis, by all means point it out! Thanks for your response. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From castironpi at gmail.com Sun Mar 16 20:27:28 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 16 Mar 2008 17:27:28 -0700 (PDT) Subject: stdout custom Message-ID: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> The code should have extra colons. >>> class ThreadedOut: ... def __init__( self, old ): ... self._old= old ... def write( self, s ): ... self._old.write( ':' ) ... return self._old.write( s ) ... def flush( self ): ... self._old.flush() ... >>> import sys >>> thout= ThreadedOut( sys.stdout ) >>> olds= sys.stdout, sys.stderr, sys.__stderr__, sys.__stdout__ >>> sys.stdout= sys.stderr= sys.__stderr__= sys.__stdout__= thout >>> 0 :0: >>> >>> 123 :123: >>> >>> Specifically, before the prompts. Where does the prompt write come from; why doesn't it honor my settings of sys.stdout and sys.stderr? From mnordhoff at mattnordhoff.com Mon Mar 3 18:02:50 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 03 Mar 2008 23:02:50 +0000 Subject: clocking subprocesses In-Reply-To: References: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> <5af6d8ab-880a-4873-9352-cf1aaae236e0@e6g2000prf.googlegroups.com> Message-ID: <47CC839A.6040509@mattnordhoff.com> barnburnr at gmail.com wrote: > On Mar 3, 12:41 pm, Preston Landers wrote: >> Run your command through the "time" program. You can parse the output >> format of "time", or set a custom output format. This mostly applies >> to Unix-like systems but there is probably an equivalent somewhere on >> Windows. >> >> Preston > > Thanks for the quick answer. That seems to work, though, I'll write a > timesubprocess() function which runs the program through time and > spits the formatted out to a file, then parses that file, then returns > the execution time. There doesn't appear to be a more elegant way to > do this. > > Kevin subprocess can do that easily. What about something like this? def timecall(args): p = subprocess.Popen(['time', '--format', '%e %U %S'] + args, stderr=subprocess.PIPE) p.wait() timings = p.stderr.readline().split() assert len(timings) == 3 timings = tuple(float(t) for t in timings) return timings It returns (real, user, sys), in seconds. The program's stdout goes to sys.stdout, I don't know where the program's stderr goes, and it really doesn't handle errors, but it's got the basic idea. -- From arnodel at googlemail.com Mon Mar 3 15:05:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 3 Mar 2008 12:05:47 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <7xzltgrbyi.fsf@ruckus.brouhaha.com> <5MSdnajOndDRq1banZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoj92xz.fsf@ruckus.brouhaha.com> Message-ID: <66231763-40ca-4686-a602-8b02ab956cc3@e60g2000hsh.googlegroups.com> On Mar 3, 4:39?pm, Paul Rubin wrote: [...] > You are right, C is even worse than I remembered. It's good enough to be the language used for the reference implementation of python :-) [...] -- Arnaud From sturlamolden at yahoo.no Thu Mar 20 14:29:19 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 11:29:19 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> Message-ID: <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> On 20 Mar, 19:09, Craig wrote: The culprit i here: > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 This binds these names to Python ints, but byref expects C types. Also observe that CacheSize and OpenMode should be c_short. From aboudouvas at panafonet.gr Sat Mar 29 08:32:11 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Sat, 29 Mar 2008 05:32:11 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> <651onqF2dripdU1@mid.uni-berlin.de> <2f3a59c2-ef31-426a-be34-bdb187ea3b22@c19g2000prf.googlegroups.com> Message-ID: On 28 ???, 20:06, Paul Boddie wrote: > On 27 Mar, 15:19, "Diez B. Roggisch" wrote: > > > > [Psyco maintenance and further development] > > > Nope, but I heard through the grapevine that while it won't be supported for > > all times to come, a new version is in the making. > > > But ultimately, the author says that the approach is flawed, so at *some* > > point it will be discontinued. But that could be said about nearly > > everything, couldn't it? > > From what I've seen from browsing publicly accessible materials, > there's a certain commercial interest in seeing Psyco updated > somewhat. So, whether it gets discontinued depends on the usual > factors of satisfying a need and there being qualified and motivated > people to work on it. > > Paul Let's hope that this isn't going to happen (psyco dicontinued). But i do not have positive thinking after an email i got for the author last week. Unless something has changed... From kyosohma at gmail.com Tue Mar 4 15:59:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 4 Mar 2008 12:59:41 -0800 (PST) Subject: Python an Exchange Server References: Message-ID: <326f9dbe-86b4-4f51-a450-ecdcb5a64ed4@i7g2000prf.googlegroups.com> On Mar 4, 1:20 pm, Yusniel wrote: > Hi friends. Someone know how to work with python and exchange > server?. If you do go the COM route, you'll probably want to ask questions of the PyWin32 user's group, which can be found here: http://mail.python.org/mailman/listinfo/python-win32 They talk about this sort of thing quite a bit. Mike From ericgorr at gmail.com Wed Mar 19 10:19:32 2008 From: ericgorr at gmail.com (Eric) Date: Wed, 19 Mar 2008 07:19:32 -0700 (PDT) Subject: [Q] SOAP Server in Python Message-ID: What is the best, well supported, way to write a SOAP Server in Python? Where can a good example be found? I do have a WSDL file. In PHP5, it is rather trivial to write a SOAP server once one has a WSDL file. For example, a simple SOAP Server written using PHP5 might look like: setClass( "MySoapServer" ); $server->handle(); ?> I am basically looking to do the same thing in Python as easily. Any help or pointers would be appreciated. thank you. From jeff at schwabcenter.com Sat Mar 15 13:54:33 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 15 Mar 2008 10:54:33 -0700 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Tim Roberts wrote: >> Jeff Schwab wrote: >>> Roel Schroeven wrote: >>>> castironpi at gmail.com schreef: >>>>> On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>>>>> How do you feel about creator of Eliza? >>>>> What is Eliza? >>>> Does that question interest you? >>> Well played, sir. >>> >>> Earlier you said what is Eliza. Do you still feel that way? >> I am embarrassed to say that this vaguely disrespectful exchange made me >> laugh out loud. > > Serious: why do you think this is disrespectful? Not to speak for Tim, but I imagine it could be perceived as disrespectful because Prof. Weizenbaum has only recently passed away. In fact, I think the Prof would be very happy to see people having some fun at the expense of AI, which he saw as a real threat to human freedom. http://www-tech.mit.edu/V128/N12/weizenbaum.html "Named for the heroine of My Fair Lady, ELIZA was perhaps the first instance of what today is known as a chatterbot program. Specifically, the ELIZA program simulated a conversation between a patient and a psychotherapist by using a person?s responses to shape the computer?s replies. Weizenbaum was shocked to discover that many users were taking his program seriously and were opening their hearts to it. The experience prompted him to think philosophically about the implications of artificial intelligence, and, later, to become a critic of it. "In 1976, he authored Computer Power and Human Reason: From Judgment to Calculation, in which he displayed ambivalence toward computer technology and warned against giving machines the responsibility for making genuinely human choices. Specifically, Weizenbaum argued that it was not just wrong but dangerous and, in some cases, immoral to assume that computers would be able to do anything given enough processing power and clever programming." See also: http://www-ai.ijs.si/eliza-cgi-bin/eliza_script You: What is Eliza? Eliza: Does that question interest you? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 27 05:40:13 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 27 Mar 2008 10:40:13 +0100 Subject: Why does python behave so? (removing list items) In-Reply-To: References: <668bb39a0803261504j6dc1b9fdh2d6f7638164aa39e@mail.gmail.com> Message-ID: <47eb6b70$0$16903$426a74cc@news.free.fr> Thomas Dybdahl Ahle a ?crit : > On Wed, 2008-03-26 at 23:04 +0100, Micha? Bentkowski wrote: >> Why does python create a reference here, not just copy the variable? > > Python, like most other oo languages, will always make references for =, > unless you work on native types (numbers and strings). > There's nothing like a "native type" in Python, and numbers and strings are ordinary objects. Python will always use references, period. From johnmfisher at comcast.net Tue Mar 18 17:18:05 2008 From: johnmfisher at comcast.net (John Fisher) Date: Tue, 18 Mar 2008 14:18:05 -0700 Subject: keyboard "interrupt" Message-ID: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Hi Group, I have been absent a while, mainly because I have been getting better at figuring out my own Python problems. But not this one... I have a timed loop performing certain tasks until a total period of time has elapsed. I would like to be able to interrupt the loop or set various flags during execution via keyboard input. raw_input seems to just stop everything cold. I want the ability to just sacn the keyboard buffer and see if something is there, then proceed normally in the loop if there is no input in the buffer. Make sense? Totally easy? Let me know... wave_man From cwitts at gmail.com Wed Mar 12 06:52:53 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 03:52:53 -0700 (PDT) Subject: Creating a file with $SIZE References: Message-ID: On Mar 12, 12:32?pm, "k.i.n.g." wrote: > Hi All, > > I would like create files of different size, taking size as user > input. I need to check the data transfer rates from one network to > another . In order to do this I will have to create files of diff size > and work out. I am new to Python > > Thanks in advance. > > KK Welcome to Python. If you just want to create files with random junk from the user input then maybe something along these lines would help: import sys, random def random_junk(number_of_characters): tmp = [] while number_of_characters: tmp.append(random.randint(0, 127)) number_of_characters -= 1 return ''.join(map(str,tmp)) if len(sys.argv) < 2: sys.exit('Usage:python %s '%sys.argv[0]) for each_argv in sys.argv[1:]: output_file = open(each_argv,'wb').write(random_junk(each_argv)) From deets at nospam.web.de Tue Mar 11 13:00:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 11 Mar 2008 18:00:50 +0100 Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> <63lfsoF27od4kU1@mid.uni-berlin.de> Message-ID: <63ns5vF1fcb15U1@mid.uni-berlin.de> > If you passed an object that has several methods to call (using tuple > or list) and you want to handle several softexceptions and ignore some > others, you must still pass an empty methods to the one you want to > ignore, cluttering the caller's code by significant degree: > > def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, > DO_NOTHING)): > if a == 0: raise callback(0) > try: > a += b > except ZeroDivisionError: > raise callback(1) > if a <= 0: raise callback(2) > raise callback(3) > return a > > somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, > DO_NOTHING)) You misunderstood. I'd pass something like a context-object, which wold look like this: def somefunc(a, b, context=NullContext()): if a == b: context.a_equals_b() .... Not more clutter than with only one callback. And the NullContext-object would actually serve as documentation on what events the code produces. >> def toplelevel(): >> def callback(a, b): >> if a == b: >> raise InterruptException() >> try: >> work(callback) >> except InterruptException: >> pass >> >> def work(callback=callback): >> a = 10 >> b = 20 >> callback(a, b) > > That's why I said most things that can be more cleanly handled by > SoftException can usually be handled in other forms, although in a > more cluttered way. > > That could be more cleanly written in SoftException as: > def work(): > a = 10 > b = 20 > raise Equal(a, b) > > def toplevel(): > try: > work() > except Equal, args: > a, b = args > if a == b: > raise InterruptException I totally fail to see where raise Equal(a, b) is less cluttered or not than callback(a, b) Actually, the latter is even less cluttered, misses a raise - if pure number of literals is your metric, that is. > If there is a syntax support, you could also make "resume" able to > transfer values: > > def somefunc(a, b): > if a == b: a, b = raise Equal(a, b) > > def toplevel(): > try: > somefunc(10, 20) > except Equal, args: > a, b = args[0], args[1] + 1 > resume a, b Sure, you can make all kinds of things, but so far you didn't come up with a comprehensive feature description that just _does_ specify what SEs are and what not. > Perhaps you meant: > raise_soft(SoftException) > > cause SoftException() may have side effects if called greedily Nope, I didn't, and it's beside the point. > That could be done, but when raise_soft() returns, it returns to the > code that raises it so it must be 'break'en: > > def caller(a, b): > if a == b: > raise_soft(SoftException) > break > > but this makes SoftException must break everytime, which make it lost > its original purpose, so you have to add return code to raise_soft > whether you want to break it or not: You didn't understand my example. If there is a handler registered, it will be invoked. If not, nothing will be raised. The exact same amount of state-keeping and lookups needs to be done by the SE-implementation. > That could be done, but when raise_soft() returns, it returns to the > code that raises it so it must be 'break'en: > def caller(a, b): > if a == b: > if raise_soft(SoftException): > break > > Compare to: > def caller(a, b): > if a == b: > raise SoftException > > And this also makes it impossible to have state-changing behavior > without some other weirder tricks That's not true. The with add_soft_handler(SoftException, handler): approach (I missed the handrel the first time, sorry) can easily throw an exception to interrupt, like this: def handler(e): if some_condition_on_e(e): raise InterruptException() with add_soft_handler(SoftException, handler): try: work(...) except InterruptException: pass You could also introduce a function def interruptable(fun, *args, **kwargs): try: return fun(*args, **kwargs) except InterruptException: pass to make the code look a bit cleaner - if it fits your usecase, that is of course. I don't say that SoftExceptions can't have semantics that go beyond this. I just don't see a oh-so-compelling use-case that makes things so much better than they are reachable now, without actually much programming. Diez From roy at panix.com Sun Mar 2 23:05:27 2008 From: roy at panix.com (Roy Smith) Date: Sun, 02 Mar 2008 23:05:27 -0500 Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> Message-ID: In article , Gabriel Genellina wrote: > On 2 mar, 17:21, castiro... at gmail.com wrote: > > > This worked: > > > > import socket > > from time import time > > > > for i in range( 20 ): > > ? ? HOST = '' > > ? ? PORT = 80 #<---- > > ? ? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > ? ? s.bind((HOST, PORT)) > > ? ? print( 'listen' ) > > ? ? s.listen(1) > > ? ? conn, addr = s.accept() > > ? ? print( 'connected', addr ) > > ? ? print( conn.recv( 4096 ) ) #<---- > > ? ? conn.send( bytes('test %f > html>'%time(),'ascii') ) > > ? ? conn.close() #<---- > > ? ? s.close() > > > > ... and connect with a browser: ?http://localhost/if it's internet > > exploder. > > Note that there is no need (nor is desirable) to close and rebind the > listening socket for each connection. I'd say, "nor is desirable", is an understatement. On most systems, an attempt to re-bind to a given port number soon after it was unbound will fail (unless you utter magic ioctl incantations). This will manifest itself in the s.bind() call raising an exception on the *second* pass through the loop. From attn.steven.kuo at gmail.com Fri Mar 21 16:10:03 2008 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Fri, 21 Mar 2008 13:10:03 -0700 (PDT) Subject: How can I make a function equal to 0? References: Message-ID: <49ed8746-35f5-4493-89a5-56f0f4ed004b@s12g2000prg.googlegroups.com> On Mar 21, 12:48 pm, Martin Manns wrote: > Hi, > > Is there a way to create a function that is equal to 0? > I try to redefine __cmp__ but I am pretty stuck. > > Something like: > > >>> def f(): return "" > ... > >>> # Some magic > >>> f == 0 > > True > You would have to bind f (the name) to 0 (or False). You can "cheat" and use a decorator: >>> def makezero(f): return 0 >>> @makezero ... def f(): return 1 >>> f == 0 True -- Hope this helps, Steven From castironpi at gmail.com Fri Mar 28 06:18:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:18:45 -0700 (PDT) Subject: Dynamic code problem References: <3af8ca05-b595-4c6f-9c7b-ee13e5eb6584@n58g2000hsf.googlegroups.com> Message-ID: <70746ecb-05e8-4263-8acc-8bca5bbd3be0@e23g2000prf.googlegroups.com> On Mar 28, 5:14?am, "Simon Brunning" wrote: > On Thu, Mar 27, 2008 at 4:13 PM, ? wrote: > > My dynamic code failed at this sitehttp://playwide1.extra.hu/, need > > ?some help thank you. > > I almost clicked on that *plonk*. Plonk? Plonk who? Knock, knock. Please don't pet the snake. From half.italian at gmail.com Tue Mar 18 16:58:33 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 18 Mar 2008 13:58:33 -0700 (PDT) Subject: os.path.getsize() on Windows Message-ID: Hi all, I'm seeing some behavior that is confusing me. I often use a simple function to tell if a file is growing...ie being copied into a certain location. (Can't process it until it's complete) My function is not working on windows, and I'm wondering if I am missing something simple, or if I have just never tried this before. Here's what I'm trying to do: def isGrowing(f, timeout): ssize = os.path.getsize(f) time.sleep(timeout) esize =os.path.getsize(f) return esize != ssize On windows, this returns the size of the file as it _will be_, not the size that it currently is. Is this a feature? What is the proper way to get the current size of the file? I noticed win32File.GetFileSize() Does that behave the way I expect? PS. I also tried os.stat()[6] ~Sean From bignose+hates-spam at benfinney.id.au Sun Mar 2 00:53:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 02 Mar 2008 16:53:03 +1100 Subject: RELEASED Python 2.6a1 and 3.0a3 References: Message-ID: <87hcfpaczk.fsf@benfinney.id.au> Kay Schluehr writes: > On 1 Mrz., 19:51, Barry Warsaw wrote: > > > Python 2.6 is not only the next advancement in the Python 2 series, it > > is also a transitionary release, helping developers begin to prepare > > their code for Python 3.0. > > Isn't this a silly idea? People have to migrate from 2.5 or lower > releases to Python 2.6 first just to migrate to Python 3.0? What are > the inherent / technical reasons that prevent migration directly from > 2.5 to 3.0? One of the stated goals of the migration is that the '2to3' program will only migrate Python 2.6 code -> Python 3.0 code. So, the smoothest migration path will be: * get your program working with Python 2.6; then * use '2to3' to automatically translate that program to work with Python 3.0; then * stop using Python 2.x for that program, only use Python 3.x. Another reason is that good features from Python 3.0 will likely be backported (if possible) to Python 2.6.x, but not to any earlier version. -- \ "Dad always thought laughter was the best medicine, which I | `\ guess is why several of us died of tuberculosis." -- Jack | _o__) Handey | Ben Finney From cwitts at gmail.com Thu Mar 13 02:43:50 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 23:43:50 -0700 (PDT) Subject: copying all data(tags and values) after a particular XML tag References: <9c8740c5-7dfa-4007-a530-c28d4b31a20d@u10g2000prn.googlegroups.com> Message-ID: <33494a78-a49e-4502-8a86-33b980131b8f@a1g2000hsb.googlegroups.com> On Mar 13, 8:21?am, bije... at gmail.com wrote: > i've an XML file with the following structure.... > >
> > > . > . > . > . > . > > > > what i want to do is copy all data(tags and all) between N and N+k > appearances of . I am a python newbie. How do I do it? > > Thanks. You can take a look at the docs for Beautiful Soup, they might help you. If it's just as simple as you're describing and you could always do something like... test = """ 1 2 """ test = test.replace('','|||').replace('','|||') [i for (j,i) in enumerate(tmp2.split('|')) if j%2] which would yield ['\n 1\n ', '\n 2\n '] which you could then parse as required. From jari.aalto at cante.net Fri Mar 7 16:46:39 2008 From: jari.aalto at cante.net (Jari Aalto) Date: Fri, 07 Mar 2008 23:46:39 +0200 Subject: distutils - Is is possible to install without the .py extensions Message-ID: Given following setup.py stanza: #!/usr/bin/python from distutils.core import setup import glob setup(name='program', description='', keywords='', version='', url='', download_url='', license='', author='', author_email='', long_description=""" """, scripts = ['program,py'], packages = ['''], ) Is there any way to fix the installation (postinstall or something), so that the the result is: /usr/bin/program instead of: /usr/bin/program.py Jari -- Welcome to FOSS revolution: we fix and modify until it shines From deets at nospam.web.de Wed Mar 19 10:42:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Mar 2008 15:42:33 +0100 Subject: changing names of items in a list References: Message-ID: <64cn31F2b3pkfU1@mid.uni-berlin.de> royG wrote: > hi > i am trying to rename extension of files in a directory..as an initial > step i made a method in > > class ConvertFiles: > def __init__(self,infldr,outfldr): > self.infldr=infldr > self.outfldr=outfldr > self.origlist=os.listdir(infldr) > .... > def renamefiles(self,extn): > for x in self.origlist: > x=x+"."+extn > > ... > > later when i print self.origlist i find that the elements of list are > unchanged..even tho a print x inside the renamefiles() shows that > extn is appended to x .. > why does this happen? Because a piece of code like this x = some_list[index] x = something_else() doesn't change the object itself, just rebinds x to a new object. That the old object stored in x happened to be referenced in a list as well - who cares? So either your members of origlist become mutables - then you have to alter them, and then they will be reachable from the list. Like this: class Foo(object): def __init__(self): pass l = [Foo() for _ in xrang(10)] f = l[0] f.bar = "baz" print l[0].bar Or you rebind the list itself, or it's index under work - like this: for i, item in enumerate(l): l[i] = do_something_with_item(item) or new_l = [] for item in l: new_l.append(do_something(item)) l = new_l There are innumerable variations of this scheme. Diez From gandalf at shopzeus.com Thu Mar 20 08:20:11 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 20 Mar 2008 13:20:11 +0100 Subject: eval and unicode Message-ID: <47E2567B.6040308@shopzeus.com> How can I specify encoding for the built-in eval function? Here is the documentation: http://docs.python.org/lib/built-in-funcs.html It tells that the "expression" parameter is a string. But tells nothing about the encoding. Same is true for: execfile, eval and compile. The basic problem: - expressions need to be evaluated by a program - expressions are managed through a web based interface. The browser supports UTF-8, the database also supports UTF-8. The user needs to be able to enter string expressions in different languages, and store them in the database - expressions are for filtering emails, and the emails can contain any character in any encoding I tried to use eval with/without unicode strings and it worked. Example: >>> eval( u'"????????? ????????? ???????"' ) == eval( '"??? ?????? ????????? ???????"' ) True The above test was made on Unbuntu Linux and gnome-terminal. gnome-terminal does support unicode. What would happen under Windows? I'm also confused how it is related to PEP 0263. I always get a warning when I try to enter '"????????? ????????? ???????"' in a source file without "# -*- coding: " specified. Why is it not the same for eval? Why it is not raising an exception (or why the encoding does not need to be specified?) Thanks, Laszlo From mhansen at gmail.com Tue Mar 11 11:57:29 2008 From: mhansen at gmail.com (Mike Hansen) Date: Tue, 11 Mar 2008 08:57:29 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: If one wants to do serious math using Python, the best bet is to use Sage ( http://www.sagemath.org ). Here are some examples: sage: def f(x, bits=53): ....: R = RealField(bits); z = R(x) ....: return cos(R(pi) * factorial(z-1) / z) sage: f(100.00,bits=1000) 0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999992343 sage: a = 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 sage: time ecm.factor(a) CPU times: user 0.00 s, sys: 0.06 s, total: 0.06 s Wall time: 2.63 [3478697, 49998841, 11927295803, 518069464441, 1858900129817, 161610704597143, 157394131396743433859615518992811454816816449] sage: a = ZZ.random_element(10**100); a 1266081670515546883639925088390407903294616094325617831128683357589913968497538978358203322629420841 sage: a.is_prime() False sage: b = a.next_prime(); b 8975665868645752218769838623717890808871334875974244952657480072373614614471639002293590745490978883 sage: b.is_prime() True --Mike From ABH at MCHSI.COM Sun Mar 23 11:57:35 2008 From: ABH at MCHSI.COM (A Hutchison) Date: Sun, 23 Mar 2008 15:57:35 GMT Subject: pydoc Message-ID: Any known reasons why pydoc no longer works? AB From deets at nospam.web.de Wed Mar 26 04:42:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 09:42:06 +0100 Subject: Strange loop behavior In-Reply-To: References: Message-ID: <64ugj9F2ce388U1@mid.uni-berlin.de> Gabriel Rossetti schrieb: > Hello, > > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > > I also tried writing the while's condition like so : len(d) > 0, but > that doesn't change anything. I tried step-by-step debugging using > PyDev(eclipse plugin) and I noticed this, once the while was read once, > it is never re-read, basically, the looping does happen, but just in > between the two lines in the loop's body/block, it never goes on the > while and thus never verifies the condition and thus loops forever. I > had been using psyco (a sort of JIT for python) and so I uninstalled it > and restarted eclipse and I still get the same thing. This looks like > some bug, but I may be wrong, does anybody understand what's going on here? > > Thanks, > Gabriel > > PS > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. But you used a superfluous repr. Look at this: >>> repr("") "''" >>> repr("") == "" False >>> So - get rid of the useless repr, then things should work. Regarding the behavior in the debugger: that's an artifact of the debugger that it doesn't step into that line, it doesn't change the way the code works. Diez From marek.rocki at wp.pl Sat Mar 29 20:59:50 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sat, 29 Mar 2008 17:59:50 -0700 (PDT) Subject: Can anyone help me? References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: <3ba288b6-3b34-4362-a9c3-5c6bd489a80c@a1g2000hsb.googlegroups.com> I love Paul's response. castiro... at gmail.com napisa?(a): > My crystal ball broke a few days ago due to overuse, but I recall that OpenGL likes to have power-of-two texture sizes. If that doesn't work, please trim down your code as far as possible (so that it still displays the error) and post it. From furkankuru at gmail.com Tue Mar 25 18:01:09 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Wed, 26 Mar 2008 00:01:09 +0200 Subject: embedded python pythonpath Message-ID: <3a4a8f930803251501y6d42bd96jc9f131320fcb683e@mail.gmail.com> Hello, It is somehow related with c++ and python. I've tried below code (Setting pythonpath environment variable) and then initialize python interpreter but the embedded python interpreter did not get the newly assigned PYTHONPATH. I ve looked at the sys.path in python code (that is run by the embedded interpreter) and it behaved according to older pythonpath. Setting environment variable seemed to be correct. Does py_initialize run in another thread so it starts before setting the environment var? // add custom plib.zip archive to pythonpath if(!::getenv("PYTHONPATH")) { ::putenv( "PYTHONPATH=.;.\\plib.zip"); } else ::putenv("PYTHONPATH=%PYTHONPATH%;.\\plib.zip"); std::cout << "PYTHONPath Set to: " << ::getenv("PYTHONPATH") << std::endl << "And Again: "; system("echo %PYTHONPATH%"); Py_Initialize(); Sorry for asking it twice. Regards, -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sat Mar 8 21:11:24 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 18:11:24 -0800 (PST) Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: <74884d64-9cb6-4924-8183-c82f405a43aa@60g2000hsy.googlegroups.com> On Mar 8, 8:48?pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote: > > I prefer: > > > ceiling(a/b) = -(-a)//b > > Unfortunately it doesn't give the right answer. > > >>> a, b = 101.0, 10.0 > >>> -(-a)//b ?# should be 11.0 > 10.0 > >>> a, b = -101.0, 10.0 > >>> -(-a)//b ?# should be -10.0 > > -11.0 > > Looks like you've confused ceiling() and floor(). Whoops, you're right. No, I didn't confuse ceiling and floor; I misplaced the parentheses. I meant to type: ceiling(a/b) = -(-a//b) Mark From Krishna.00.K at gmail.com Fri Mar 7 12:49:58 2008 From: Krishna.00.K at gmail.com (Krishna) Date: Fri, 7 Mar 2008 09:49:58 -0800 (PST) Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments References: Message-ID: On Mar 6, 5:04 pm, "Gabriel Genellina" wrote: > En Thu, 06 Mar 2008 22:48:42 -0200, Krishna > escribi?: > > > > >>>> class Test(object): > > ... def __init__(self): > > ... self.a= 2 > > ... def func(self, k = self.a): > > ... print k > > ... > > Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 4, in Test > > NameError: name 'self' is not defined > > > In the 'definition of the class', what would the first argument 'self' > > in the methods evaluate to; when we have an object defined, it is > > bound to the object reference, but what happens while the class > > definition is executed, which I believe happens when the module > > containing the class definition is imported > > Function default arguments are evaluated when the function is defined > (when the class is defined, in this case) so "self" itself has not a > value. Try this instead: > > def func(self, k=None): > if k is None: > k = self.a > print k > > If None is an allowed argument, use a special marker instead: > > _marker=object() > ... > > def func(self, k=_marker): > if k is _marker: > k = self.a > ... > > -- > Gabriel Genellina Thanks for the reply. I am currently using the approach suggested by you. But, I am more interested in knowing about the first argument ('self'), what does it hold to allow the evaluation of the method, take the example you gave, 'self.a' as Rvalue inside the method, how and why is this allowed, when the same 'self.a' is not allowed as the default argument, considering the fact that I have already specified 'self' as first argument, only after whose evaluation, I believe would the next statement (k = self.a, in def func(self, k = self.a) ) gets evaluated Thanks, Krishna From harrelson at gmail.com Sat Mar 22 10:31:33 2008 From: harrelson at gmail.com (harrelson) Date: Sat, 22 Mar 2008 07:31:33 -0700 (PDT) Subject: Subprocess and /usr/bin/dialog References: <13u8fdmq9hnsh06@corp.supernews.com> Message-ID: <5bd9b02a-958b-452d-9e20-c10e4c29f9e4@i29g2000prf.googlegroups.com> On Mar 21, 3:59 pm, Grant Edwards wrote: > On 2008-03-21, harrelson wrote: > > > I am trying to get the below code to work and can't quite make things > > happen. This is with Python 2.5.1. Dialog is doing something odd... > > I have tinkered with different combinations and I can't get the dialog > > to show properly-- it does show properly directly in the shell. Any > > hints? > > > import subprocess > > command = '/usr/bin/dialog --clear --title "title" --menu "text" 20 50 > > 5 "a" "this and that" "c" "3 this and that" "b" "2 this and that" "d" > > "4 this and that"' > > proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, > > stderr=subprocess.STDOUT) > > #proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) > > stderr_value = proc.communicate()[0] > > print stderr_value > > [It would be helpful if you didn't wrap sample code when you > post it.] Sorry I posted through google groups and it wrapped it for me... > dialog displays the widget on stdout. You've connected stdout > to a pipe, so you're not going to see anything displayed unless > you read data from the stdout pipe and write it to the terminal. Reading this tutorial on subprocess: http://blog.doughellmann.com/2007/07/pymotw-subprocess.html led me to believe this was exactly what I was doing. The screen does actually turn blue for a second but it is as if I only get one keystroke and python is back in control... From aiya.vinay at gmail.com Fri Mar 14 10:53:04 2008 From: aiya.vinay at gmail.com (Vinay Aiya) Date: Fri, 14 Mar 2008 20:23:04 +0530 Subject: how to parse a wiki markup file Message-ID: hello, Anyone can help me how to extract the data from wiki file using python i.e is there any WIKIPARSER package and documentation to from parsing on wiki file . -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 16:38:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 21:38:35 -0000 Subject: Dual look-up on keys? References: <6715bea5-5926-414e-b81c-25d5eb12511e@e23g2000prf.googlegroups.com> <6389mcF25af40U1@mid.uni-berlin.de> <3d5380c9-f8ad-4771-87b3-789e76d7a231@i7g2000prf.googlegroups.com> Message-ID: <13su4mr48on6p7f@corp.supernews.com> On Wed, 05 Mar 2008 12:06:11 -0800, castironpi wrote: > On Mar 5, 1:13?pm, "Diez B. Roggisch" wrote: >> castiro... at gmail.com schrieb: >> >> > I want to hash values to keys. ?How do the alternatives compare? >> >> http://catb.org/~esr/faqs/smart-questions.html > > ... without extending the whole way to a full relational database? You didn't bother following the link and reading the advice, did you? If you did, you haven't done a good job of following that advice. -- Steven From rodmena.com at gmail.com Tue Mar 11 21:55:32 2008 From: rodmena.com at gmail.com (Farsheed Ashouri) Date: Tue, 11 Mar 2008 18:55:32 -0700 (PDT) Subject: Py2exe and Multi Treading problem. Message-ID: Here is my script #********************************************************************** #********************************************************************** import threading import socket def openSocket(portNum): mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', portNum ) ) mySocket.listen ( 1 ) channel, details = mySocket.accept() msg = channel.recv(4096) class CmdPortThread( threading.Thread ): def run( self ): openSocket(6000) def fakeCommandPort(): CmdPortThread().start() fakeCommandPort() #********************************************************************** #********************************************************************** If works perfect with python 2.5.2. Now I want to convert it to standalone program. but the .exe file fails to run without any error. If I cal CmdPortThread without Trading, It works perfect. What did I miss here? My setup.py is standard without any include or excludes. Should I include something in setup.py? I am not a py2exe newbie but I'll appreciate detailed descriptions. From Lie.1296 at gmail.com Sun Mar 30 08:45:25 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 05:45:25 -0700 (PDT) Subject: Problem with python References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Message-ID: <568e3a17-a7a2-4b0a-baab-80b2409adcc8@s37g2000prg.googlegroups.com> mac_the_sco... at hotmail.com wrote to me: (snip) > OK thanks mate you're the man :) > One more question though :P > If I write a python script in a text editor (I use Programmers > Notepad), how do I write indentations properly? e.g.: > --------------------------------------------------- > temperature = input("How hot is the spam? ") > while temperature < hot_enough: > print "Not hot enough... Cook it a bit more..." > sleep(30) > temperature = input("OK. How hot is it now? ") > print "It's hot enough - You're done!" > > (taken from hetland.org) > --------------------------------------------------- > Is it simply a case of hitting the spacebar until it looks right? Yep, it's just a matter of hitting spacebar until it looks right, but you should also be aware that the Python Interpreter doesn't like it if you mix tabs and spaces, so make sure you only use either one of them. As an additional note, Python's style guideline says you should use 4 spaces (additionally, most Python IDEs automatically convert tabs into 4 spaces for convenience and to avoid mixing tabs and cases). PS: I'll mirror this to comp.lang.python From wizzardx at gmail.com Sun Mar 30 01:24:15 2008 From: wizzardx at gmail.com (David) Date: Sun, 30 Mar 2008 07:24:15 +0200 Subject: Can anyone help me? In-Reply-To: References: <938fcca4-b88b-4157-aef6-dbb38ac99b1c@b64g2000hsa.googlegroups.com> Message-ID: <18c1e6480803292224r6cebeearc35af0892193b3e8@mail.gmail.com> > > What is the collision of spheres? Is it the melding of a sphere of > influence and cosmic sphere? What does it mean to say that such a > collision "doesn't work"? The sphere is the optimal solid for storing > the maximum volume in the minimum area. A sphere can retain the most > heat, with minimum surface area for radiation or conduction, > convection of course being dependent not only on surface area but also > ambient flow of surrounding conducting fluid if such flow is laminar > with respect to Reynold's magic number not to be confused with the > numbers of a magic square, which is a two-dimensional shape is there a > determination of the collision of a sphere's projection onto a plane > with a square on that same plane. I've had it with these MF'in > squares on this MF'in plane! When did the Time Cube guy join this list? From deets at nospam.web.de Mon Mar 10 15:18:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 10 Mar 2008 20:18:43 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> <47d4c107$0$36349$742ec2ed@news.sonic.net> Message-ID: <63lfsoF27od4kU1@mid.uni-berlin.de> > The problem with callbacks is that it works only for a small amount of > callbacks, it'd be too messy to have twenty different callbacks. > And the ultimate problem with callbacks is that we can't determine > from the outside whether the operation should continue or breaks at > the point of the callback without some messy trick. > > We can't always determine whether we want to do this: > def somefunc(argA, argB, callback = DO_NOTHING): > if argA == argB: > callback() > > or this: > def somefunc(argA, argB, callback = DO_NOTHING): > if argA == argB: > callback() > return > > perhaps we could do this: > if argA == argB: > if callback() == True: return > > but that's so much extra codes written and would've been too messy to > write. > > And actually this isn't a rare cases, and in fact is very common. It's > just that most cases that can be more cleanly written in > SoftException, can usually be handled in different ways, using tricks > that range from subtle to messy (like callbacks). I fail to see how your arguments follow. Regarding the number of callbacks: you can as well pass an object that has several methods to call. And the above example can easily be accomplished with "normal" exceptions, like this: def toplelevel(): def callback(a, b): if a == b: raise InterruptException() try: work(callback) except InterruptException: pass def work(callback=callback): a = 10 b = 20 callback(a, b) And even more: the callback-approach can do things like this: a, b = callback(a,b) to change values, which makes it superior to SoftExceptions - unless I missed it's ability to capture context. So far, you haven't shown a very convincing example of what SoftException are and how they can be useful. Diez From lialie at gmail.com Thu Mar 13 02:02:56 2008 From: lialie at gmail.com (lialie) Date: Thu, 13 Mar 2008 14:02:56 +0800 Subject: Dispatch("Excel.Application") failed Message-ID: <47D8C390.8090309@gmail.com> Hi, Maybe it 's quite simple, but I can't fix it. Do I make some mistakes in my env setting? My excel version is 2003. any suggestion? Thanks. Traceback (most recent call last): File "testexcel.py", line 3, in ? excel = Dispatch("Excel.Application") File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c lsctx) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 98, in _ GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 78, in _ GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II D_IDispatch) pywintypes.com_error: (-2147221005, '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', None, None) From http Sat Mar 1 14:36:05 2008 From: http (Paul Rubin) Date: 01 Mar 2008 11:36:05 -0800 Subject: why not bisect options? References: Message-ID: <7xy7928cey.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > The sort() function guarantees that it calls the key function exactly > once for each member of the list. That is a time-space tradeoff though, and it presupposes that it's possible to write a key function. Depending on the objects involved, it could be that it's easier to write a comparison function than a key function. From gslindstrom at gmail.com Thu Mar 20 16:07:09 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 20 Mar 2008 15:07:09 -0500 Subject: Pycon disappointment Message-ID: ,,,... Let's see some code! Let's see > stuff working (and sometimes crashing!), and how changes affect the > results. When I've presented at PyCon and other conferences, that's > the part that I spend the most time on: preparing demonstrations. It's > not easy to do; certainly much more difficult than creating a slide > that sums up what the demo does. But it makes for a much more > interesting session! > > -- Ed Leafe Here, here!! (or is it hear, hear??). I remember Ed's talk on Dabo a couple of years ago (or was it last year?) because he was writing code while up in front of the room. "Here's how to do this" and then he would tweak various aspects and show the results. I can appreciate the need for slides, but I also like seeing "code in action". --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Sun Mar 16 07:28:30 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 16 Mar 2008 04:28:30 -0700 (PDT) Subject: ANN: OpenOpt 0.17 (free numerical optimization framework) Message-ID: <8b788e55-bca0-4a4d-8274-91aef09f4c0f@s8g2000prg.googlegroups.com> Greetings, We're pleased to announce: OpenOpt 0.17 (release), free (license: BSD) optimization framework for Python language programmers, is available for download. Brief introduction to numerical optimization problems and related software: http://scipy.org/scipy/scikits/wiki/OOIntroduction Changes since previous release (December 15): * new classes: GLP (global problem), MMP (mini-max problem) * several new solvers written: goldenSection, nsmm * some more solvers connected: scipy_slsqp, bvls, galileo * possibility to change default solver parameters * user-defined callback functions * changes in auto derivatives check * "noise" parameter for noisy functions * some changes to NLP/NSP solver ralg * some changes in graphical output: initial estimations xlim, ylim * scaling * some bugfixes Newsline: http://openopt.blogspot.com/ Homepage: http://scipy.org/scipy/scikits/wiki/OpenOpt From gagsl-py2 at yahoo.com.ar Tue Mar 18 19:37:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 20:37:19 -0300 Subject: stdout custom References: <261a6d33-7295-4ead-a45b-6dd04d545648@13g2000hsb.googlegroups.com> <4005e915-f579-4ee3-a06f-85874893d3e2@p25g2000hsf.googlegroups.com> <3a56120c-381f-4641-a5c3-633fd9771b05@u10g2000prn.googlegroups.com> <9f4c1180-9004-4f08-ab63-b0a0bd8849e7@m36g2000hse.googlegroups.com> Message-ID: En Tue, 18 Mar 2008 07:09:08 -0300, escribi?: > On Mar 17, 8:16?pm, Gabriel Genellina wrote: >> On 17 mar, 19:43, castiro... at gmail.com wrote: >> >> > Can I allocate a second console window, so I can place certain output >> > to that directly, and leave the original streams alone? ?I tried >> Have you tried using the creationflags argument to subprocess.Popen? >> Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation >> for CreateProcess >> athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx >> (Note that a process can be attached at most to one console) >> > One console per process is fine, but I tried using 'cmd.exe', > 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32) > as separate processes. The sign is the console window splashes up and > vanishes right away. Apparently you have to either redirect stdout AND stdin, or none of them. This worked for me: p = subprocess.Popen('c:\\windows\\system32\\cmd.exe', stdout=subprocess.PIPE, stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE) p.communicate("dir\n") -- Gabriel Genellina From paul.hankin at gmail.com Mon Mar 10 04:32:43 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 10 Mar 2008 01:32:43 -0700 (PDT) Subject: __iter__ yield References: <27d24b75-f1b5-4996-b54a-15ab2ba16593@59g2000hsb.googlegroups.com> Message-ID: <910581f3-6587-4f6a-91ba-0049d583c1d6@y77g2000hsy.googlegroups.com> On Mar 10, 3:12?am, George Sakkis wrote: > On Mar 9, 7:37 pm, Paul Hankin wrote: > > > > > On Mar 9, 8:58 pm, duccio wrote: > > > > Someone knows if it's possible to make this __iter__ function with just > > > one 'yield' intead of two? > > > ... > > > ? ? ?def __iter__(self): > > > ? ? ? ? ?yield self #1 > > > ? ? ? ? ?for n in self.childs: > > > ? ? ? ? ? ? ?for nn in n.__iter__(): > > > ? ? ? ? ? ? ? ? ?yield nn #2 > > > Only one yield and shorter (but not really any simpler): > > > from itertools import chain > > > class Node: > > ? ? ... > > ? ? def __iter__(self): > > ? ? ? ? for x in chain([self], *self.childs): > > ? ? ? ? ? ? yield x > > Actually this doesn't need a yield at all: > > class Node: > ? ? ... > ? ? def __iter__(self): > ? ? ? ? return chain([self], *self.childs) The two have slightly different behaviours: without the yield, iter is called immediately on every node in the tree as the iterators are built. With yield, iterators are built lazily, giving better behaviour. But perhaps it's a defect of chain that it calls iter on all of its arguments straight away -- would it be better if it only built the iterators when they're needed? -- Paul Hankin From http Fri Mar 28 17:51:48 2008 From: http (Paul Rubin) Date: 28 Mar 2008 14:51:48 -0700 Subject: Tell ya' what: References: <5dd6fc74-6ab6-46ae-84bc-70886272faad@d45g2000hsc.googlegroups.com> Message-ID: <7x4paqy0sr.fsf@ruckus.brouhaha.com> castironpi at gmail.com writes: > Did everyone take the course on computer architecture? Yow! Does your SPEED QUEEN have CABLE? From sturlamolden at yahoo.no Tue Mar 18 17:22:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 14:22:53 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: On 18 Mar, 10:57, Simon Forman wrote: > def f(L): > '''Return a set of the items that occur more than once in L.''' > L = list(L) > for item in set(L): > L.remove(item) > return set(L) def nonunique(lst): slst = sorted(lst) return list(set([s[0] for s in filter(lambda t : not(t[0]-t[1]), zip(slst[:-1],slst[1:]))])) From timr at probo.com Wed Mar 5 02:51:09 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 05 Mar 2008 07:51:09 GMT Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> Message-ID: blaine wrote: > >...I haven't been able to find many resources specifically in >this area, but there are a few package that are vaguely mentioned, >including fcntl and termios. But the web doesn't seem to have a lot >of documentation on fcntl, particularly information thats from the >past 8 years. That's because serial ports, and the means of accessing them, haven't changed significantly in the last 8 years. Or the last 38 years, for that matter. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Mon Mar 10 12:39:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 09:39:59 -0700 (PDT) Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: <942cf9d5-3d26-41d9-ba8a-3e39dc1595c1@d62g2000hsf.googlegroups.com> > > The idea of the if-else is: > > . depending on some condition either do this or do something else, > > . don't do them both. > > constructs, I asked myself whether the application of a different idea > resulted in a consistent, sensible interpretation. They could just as easily have defined the else of a 'for' to mean 'if the loop only completed not an even number of times', giving these different outputs: for a in [1,2,3,4,5]: if a> 3: break else: print( 'bogus' ) for b in [1,2,3,4,5]: if b> 4: break else: print( 'foo' ) Just as easily, yes. Just as well? Just as meaningfully? Just as consistently, usefully, and sensibly? Possibly. The meaning of 'if a loop' could be construed to mean a parity test or a binary test (if it didn't even complete once, i.p. if the sequence was empty). If I tell you to do a loop, and then asked if you did it, what factors in to your answer? The docs say, 'A break statement executed in the first suite terminates the loop without executing the else clause's suite', for both for- and while-. Does for-and and while-and or for-ifso and while-ifso sound more to your liking? From forwardshortleg at gmail.com Wed Mar 5 19:42:10 2008 From: forwardshortleg at gmail.com (forwardshortleg at gmail.com) Date: Wed, 5 Mar 2008 16:42:10 -0800 (PST) Subject: Returning a byte buffer from C extension Message-ID: Hello, I am new to Python programming. So, kindly excuse me if I don't use correct terminology here below. I am trying to write an extension function that returns an array of bytes as shown in the example below: static PyObject* GetByteBuffer(PyObject* self, PyObject* args) { char byteBuffer[100]; // do something to fill byteBuffer with values. return Py_BuildValue("y", byteBuffer); } Is this valid? I get a run time error in Python 2.5 (actually 2.6) and Python 3.0 returns null terminated byte string. My byte buffer may contain one or more zeros and I want is the entire buffer regardless of its contents. How do I do it? Thanks, Eknath P.S: I know that 2.6 & 3.0 are not meant for a newcomers like me. Unfortunately 2.5.2 and older for windows are built using MSCVC 6.0 and they pose problems building extensions. From stef.mientki at gmail.com Fri Mar 28 12:14:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 28 Mar 2008 17:14:19 +0100 Subject: class or inherited list ? In-Reply-To: References: <47ED0BA1.9020103@gmail.com> Message-ID: <47ED195B.4070902@gmail.com> thanks Gabriel, Gabriel Genellina wrote: > En Fri, 28 Mar 2008 12:15:45 -0300, Stef Mientki > escribi?: > > >> Passing all kinds of data between objects, >> I'm looking for an elegant (and simple) way to pack the data. >> Now it looks to me that both the class and the inherited list, >> performs equally well. >> Till now, the most elegant way (in my view) is the list inheritance, >> mainly because you don't need brackets and no quotes. >> What are others opinion about this ? >> >> class super_list(list): >> pass >> >> def kwadraat ( value ) : >> return value * value >> >> x={} >> x['frequency']=33 >> x['functie']=kwadraat >> print x['functie'](2) >> >> y = super_list() >> y.frequency = 33 >> y.functie = kwadraat >> print y.functie(3) >> > > You don't use y as a list at all - you might as well inherit from object. Good point, didn't notice that. > > And in that case you get a generic attribute container - as you said, like > a dict but using attribute syntax (drawback: only valid names can be used > as keys) > Perfect, I don't need invalid names. > But I don't understand the "functie" usage - what's for? Perhaps if it > used y.frequency - in that case a proper method would be better. > In my case the sender of the data determines the function ("functie" is the Dutch word for "function"), assume this concept: Sender: - generates a huge array of data Receiver: - is a plot utility with interactive user interface - the user can select a part of the huge dataset and wants to see the result of "function" on the selected part of the huge dataset So by passing the function-name(s), I prevent that the functions(s) should be performed on all the data. while they will never be used. cheers, Stef Mientki From jeffober at gmail.com Mon Mar 24 14:57:13 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 24 Mar 2008 11:57:13 -0700 (PDT) Subject: New to group References: <14bc156b-bfb6-47d1-bef4-ff05d0c8ff2a@c19g2000prf.googlegroups.com> Message-ID: <657f1c33-cc7c-4c2a-aae4-a457a8eb1214@x41g2000hsb.googlegroups.com> What does the code look like? From duncan.booth at invalid.invalid Mon Mar 17 06:02:23 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 10:02:23 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <87r6e9zu4p.fsf@benfinney.id.au> Message-ID: cokofreedom at gmail.com wrote: >> >>> a = 1 >> >>> b = 1 >> >>> a is b >> True >> >>> id(a) >> 10901000 >> >>> id(b) >> 10901000 > > Isn't this because integers up to a certain range are held in a single > memory location, thus why they are the same? > Yes, in *some* implementations of Python this is exactly what happens. The exact range, or indeed whether it happens at all, and (if it does happen) whether the range depends on the phase of the moon are all undefined. This, for example, is what I just got for a similar sequence: >>> a = 1 >>> b = 5-4 >>> a is b False >>> id(a) 43L >>> id(b) 44L >>> From antroy at gmail.com Mon Mar 31 17:57:36 2008 From: antroy at gmail.com (Ant) Date: Mon, 31 Mar 2008 14:57:36 -0700 (PDT) Subject: Is this a good time to start learning python? References: <47f1140e$0$735$a729d347@news.telepac.pt> Message-ID: On Mar 31, 5:40 pm, Rui Maciel wrote: ... > So far the decision seems to be a no brainer. Yet, Python 3000 will arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put it > in other words, I fear that I will be wasting my time. Not at all. The lead developers have a plan for migrating older scripts to 3000 automatically (or at least semi-automatically). This can be done because the core syntax and builtin's are remaining largely the same. The sort of thing that is changing in a way that breaks backward compatibility are things such as removing the print statement (e.g. >>> print "Hello world") with a print function (e.g. print("Hello world")) and rearranging the standard library. As Terry said, the major changes are additions and deletions - to expand on this, the deletions are generally likely to be modules that are rarely used or are unmaintained. In any case, the python developers have a very good policy of making the upgrade path to new versions of Python smooth. Generally new features are released into the __future__ module in a release ready for inclusion in the next release. This allows time to play with new features before the "official" release of the feature comes out. Module deletions usually hang around for a few releases as "deprecated" before being permanently removed - again giving time to catch up. I believe that the deprecation speed may come rather abruptly with 3000, however the 2.6 release will contain a PyLint program for identifying changes that will need to be made before migrating to 3k. In addition, the 2.x branch is AFAIK going to be maintained up to (but no further than) a 2.9 release. So there will be plenty of time to adjust! In short, any time invested in learning Python at this stage (except perhaps old-style classes as pointed out above) will be time well spent, as learning Python 3000 will be minor tweaks to what you'll already know. And for what it's worth, I've programmed in Haskell, C, Java (Java's my profession), Javascript and Perl, and dabbled with Ruby, Lisp, Groovy (and probably others), and Python is by far my favorite language, not just for the clean syntax, rapid development, readability 5 years down the line etc, but also for the community, which is very helpful and knowledgeable. BTW. I have to disagree with Andrew's comment: "With Perl, once you get the core syntax down, you don't need to master Perl. Instead you just look up the module/feature you want to use and just use it.". This may be true for knocking up Perl scripts, but for reading *other peoples* code in any language you need to have a good mastery of the core language. In Perl this is a quagmire of strange syntax, special cases, multiple ways to do the same thing and esoterica/magic, whereas Python's design to make whitespace significant and its "One (obvious) way to do things" philosophy makes reading other peoples code much easier. (Of course other peoples code always sucks, but hey ;-) From aboudouvas at panafonet.gr Thu Mar 27 10:02:17 2008 From: aboudouvas at panafonet.gr (king kikapu) Date: Thu, 27 Mar 2008 07:02:17 -0700 (PDT) Subject: Psyco alternative References: <1369b321-f55b-432b-b2f9-6144787509d8@h11g2000prf.googlegroups.com> <7xlk4473ai.fsf@ruckus.brouhaha.com> <651ncdF2cmik2U1@mid.uni-berlin.de> Message-ID: On 27 ???, 15:56, "Diez B. Roggisch" wrote: > king kikapu wrote: > > On 27 ???, 14:35, Paul Rubin wrote: > >> king kikapu writes: > >> > it seems that Psyco's author will not port it for the upcoming Python > >> > 3000 release :( > > >> I think the idea is it will be part of PyPy and you should use that. > > > I know that his efforts are on PyPy now but i do not know when PyPy is > > going to be stable and if i can use it with my current "development > > stack" (PyQt, Eric4 etc). I mean, i do not know if it will be possible > > to "abandon" CPYthon and use PyPy instead. > > Currently? No way. It's *way* to slow. > > Diez Ok, i know this. The one that i do not know, is if, let'say, in 2 years it will be ready for seriously development, PyPy will aim to "replace" CPython entirely ?? We are talking about an whole new distribution ? As for psyco, are there any alternatives to use now ? From pradiprai at gmail.com Fri Mar 14 09:29:19 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Fri, 14 Mar 2008 18:59:19 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Dear All, I am working on the python tools that process a huge amount of GIS data. These tools encountering the problem of memory leaks. Please suggest what are the different ways to detect the memory leaks in python ? This is very critical problem for me. Help needed urgently. Thanks & Regards, Pradeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Tue Mar 25 11:49:55 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 25 Mar 2008 08:49:55 -0700 Subject: Time module is not behaving. In-Reply-To: References: Message-ID: <47E91F23.3050100@islandtraining.com> jjlofaro wrote: > Hi > > I'm just getting myself going again on Python and would appreciate any > help. > > My install of Python seems to have some difficulty loading and using > the time module in a script. Strange thing is that if I start another > instance of Python I can type in my program manually/interactively and > it works. > > The version of Python I am using is... > * > Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2* > > Installed on a Ubuntu 7.10 workstation. > > Here's my little program.... > > *jeff at office:~/tmp$ more < time.py > > import time > * Right there is the problem. Your program, named time.py, is hiding the Python supplied module. So that import of time is finding and re-importing itself. Rename your script to something that won't shadow a Python library module. Gary Herron > *print time.time()* > > And this is what happens when I run it.... > > *jeff at office:~/tmp$ python time.py > > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > Error in sys.excepthook: > Traceback (most recent call last): > File "/var/lib/python-support/python2.5/apport_python_hook.py", line > 38, in apport_excepthook > from apport.fileutils import likely_packaged > File "/var/lib/python-support/python2.5/apport/__init__.py", line 1, > in > from apport.report import Report > File "/var/lib/python-support/python2.5/apport/report.py", line 14, > in > import subprocess, tempfile, os.path, urllib, re, pwd, grp, os, sys > File "/usr/lib/python2.5/urllib.py", line 28, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > Original exception was: > Traceback (most recent call last): > File "time.py", line 1, in > import time > File "/home/jeff/tmp/time.py", line 2, in > print time.time() > TypeError: 'module' object is not callable > > jeff at office:~/tmp$ * > > Any hints or tips appreciated. > Jeff. From deets at nospam.web.de Sun Mar 9 17:51:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 09 Mar 2008 22:51:04 +0100 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> <286a5bc0-6935-4237-a88c-178977f0c3bb@e60g2000hsh.googlegroups.com> Message-ID: <63j4ebF25g6okU1@mid.uni-berlin.de> > Perhaps similar technique the compiler uses to determine whether a > function is a normal function or a generator function? Positive > forward lookup for any soft exceptions, which would then activate > matching soft exceptions inside the code? The difference between generators and functions is made on the yield-keyword. However, the exception-mechanism isn't governed by the compiler, but at runtime. You can do things like this: eclass = HardException if full_moon() else: SoftException raise eclass() Which means that you don't stand a chance determining soft-exception-usage at compiletime. What would work is most probably to register soft-exception-handlers when encountering them at runtime, thus making raising-code aware of them and execute it only if there are one (or several) present. However, IMHO it's not a worthy extension to the language - for the same reasons Steven gave. It seems only useful for tightly coupled code, not as a general mechanism. And callbacks or maybe even thread-local state are sufficient to deal with that I'd say. Diez From gagsl-py2 at yahoo.com.ar Tue Mar 25 16:54:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 17:54:08 -0300 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> Message-ID: En Tue, 25 Mar 2008 17:17:16 -0300, j vickroy escribi?: > Arnaud Delobelle wrote: >> On Mar 25, 6:13 pm, j vickroy wrote: >>> Hello, >>> >>> Here is some pseudo-code that hopefully illustrates what I want to do: >>> >>> records = list(...) >>> for record in records: >>> new_fcn = define_a function_for(record) >>> instance = my_new_class_instance() >>> setattr(instance, 'myfcn', new_fcn) >>> instance.execute() # instance.execute() calls instance.myfcn(*args) >>> >>> I have looked at some of the functions in the *new* module and >>> new.code(...), new.function(...), and new.instancemethod(...) appear to >>> do what I want, but I do not know how to use new.code() and >>> new.function() -- specifically what its *global* parameter should be. >> >> The best way to understand how new.function and new.code work is to >> look at the Python source. (Objects/funcobject.c and Objects/ >> codeobject.c, actual objects are defined in and Include/funcobject.h >> Include/code.h). >> >> However, to create a function dynamically in Python it is often no >> more trouble than a def statement: > > As per your suggestion, I tried looking at include/code.h and > include/funcobject.h (my MS Windows distribution does not appear to > contain .c files). However, since I'm not a C programmer, I did not > find the .h files all that helpful. It's not really necesary to look at the source - just define the desired function in Python. > What I failed to make clear in my original posting is that the functions > must be created dynamically using information in a *record* as the code > iterates over all *records*. So, I can not pre-define the functions and > then simply select the desired one at run-time. It doesn't matter *how* you define the function. It may use the record argument too. See this silly and contrived example: def define_a function_for(record): if hasattr(record, 'foo'): def function_float(self, arg1, arg2): return arg1*float(record.foo) + arg2 def function_str(self, arg1, arg2): return arg1+arg2+len(record.foo) if isinstance(record.foo, str): return function_str else: return function_float elif hasattr(record, 'bar') and isinstance(record.bar,basestring): def function(self, arg1, arg2): return self.other(record.bar.index(arg1)) - record.bar.index(arg2) return function else: def function(self, *args): return 0 return function Plug this into your "framework" above and it should work. You don't have to use new.* -- Gabriel Genellina From code at pizzashack.org Thu Mar 27 02:21:59 2008 From: code at pizzashack.org (Derek Martin) Date: Thu, 27 Mar 2008 02:21:59 -0400 Subject: Python 2.2.1 and select() In-Reply-To: <20080327021115.GA24827@noah.org> References: <3b87e805-788b-4ce1-bd5b-154fe19bc00f@d21g2000prf.googlegroups.com> <20080325020356.GF26870@dragontoe.org> <20080326164951.GA6349@noah.org> <20080326235946.GL26870@dragontoe.org> <20080327021115.GA24827@noah.org> Message-ID: <20080327062159.GM26870@dragontoe.org> On Wed, Mar 26, 2008 at 07:11:15PM -0700, Noah Spurrier wrote: > >def set_nonblock(fd): > > flags = fcntl.fcntl(fd, fcntl.F_GETFL) > > fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) > > > >Then in the function, after calling popen: > > set_nonblock(io.fromchild.fileno()) > > set_nonblock(io.childerr.fileno()) > > > >Yay for smart people. > > You should still try Pexpect :-) As I recall there are also gotchas > on the non-blocking trick. Well, you need to remember to read ALL the file descriptors (objects) that select() returns, and if you don't, your program will hang and spin... It might also be the case that if the child is using stdio functions for output, you'll need to set the buffering mode explicitly (which you can theoretically do, see below). Aside from that, there are none, and actually the problem with my program had nothing to do with stdio buffering modes. > Pexpect is 100% pure Python. No extra libs to install. I looked at it, and (what I believe is) the very reason it manages to solve this particular problem is also the reason it won't work for me: it combines STDOUT and STDERR to one I/O stream. The reason I'm bothering with all this is because I need to keep them separate. Interestingly, were it not for that fact, I'm not sure that pexpect wouldn't still suffer from the same problem that plagued my original implementation. I had to drag out W. R. Stevens to remind myself of a few things before I continued with this discussion... Even though it forces the program to use line buffering, read() would still try to read until EOF, and if STDOUT and STDERR were separate files, it seems likely that it would eventually block reading from one file when the child program was sending its output to the other. The only way to prevent that problem, aside from non-blocking I/O, is to do a read(1) (i.e. read one character at a time), which will use silly amounts of CPU time. But mixing stdio and non-stdio functions is kind of funky, and I'm not completely sure what the behavior would be in that case, and couldn't quickly ind anything in Stevens to suggest one way or the other. Also, you could combine the streams yourself without using pexpect by having your subproc use the shell to redirect STDERR to STDOUT, or (if Python has it) using the dup() family of system calls to combine the two in Python [i.e. dup2(1,2)]. As far as I can tell, the whole pseudo terminal thing (though it definitely does have its uses) is a red herring for this particular problem... I also read (some of) the pexpect FAQ, and there are a number of incorrect statements in it, particularly in the section 'Why not just use a pipe (popen())?" - a pipe, if programmed correctly, is perfectly fine for controlling interactive programs, most of the time. You will almost certainly need to use non-blocking I/O, unless your communicating programs are perfectly synchronized, or else you'll have I/O deadlocks. The only time a pipe isn't OK is where the program tries to use terminal services (e.g. writing to /dev/tty), in which case you will need a pseudo-terminal device (as the FAQ correctly points out with regard to entering passwords in SSH). - Any application which contains "#include " does not necessarily make use of the stdio library (which isn't really a separate library at all, it's part of the standard C library). The file stdio.h is just a C header file which contains declarations of the prototypes for stdio-related functions, and various constants. It's often included in source files simply because it's so common to need it, or to make use of some constants defined there. You're only actually using stdio if you use stdio functions in your program, which are: printf, fopen, getc, getchar, putc, scanf, gets, puts, etc. In particular, open(), read() and write() are *not* stdio functions, and do *not* buffer I/O. They're Unix system calls, and the C functions by the same name are simply interfaces to those system calls. There is a kernel I/O buffer associated with all of the streams you will use them on, but this is not a stdio buffer. I have not checked Python's code, but based on its behavior, I assume that its read() function is a wrapper around the Unix read() system call, and as such it is not using stdio at all, and thus the stdio buffers are not relevant (though if the child is using stdio functions, that could be an issue). - The FAQ states: "The STDIO lib will use block buffering when talking to a block file descriptor such as a pipe." This is only true *by default* and indeed you can change the buffering mode of any stdio stream using the setbuf() and setvbuf() stdio functions (though I don't know if Python provides a way to do this, but I assume it does). Since the python program is the one opening the pipe, it controls the buffering mode, and you have only to change it in your program, and the child will honor that. The way it works is because popen() opens the pipe, and then forks a child process, which inherits all of the parent's open files. Changing the properties on the files can be done in the parent, and will be honored in the child, because *it's the same file*. :) - It states: "[when writing to a pipe] In this mode the currently buffered data is flushed when the buffer is full. This causes most interactive programs to deadlock." That's misleading/false. Deadlocks can easily occur in this case, but it's definitely avoidable, and it's not *necessarily* because of buffering, per se. It's because you're trying to read or write to a file descriptor which is not ready to be read from or written to, which can be caused by a few things. STDIO buffers could be the cause, or it could simply be that the parent is reading from one file descriptor, but the child is writing to a different one. Or (perhaps even more likely) it is trying to read from the parent, so both are reading and no one is writing. Non-blocking I/O allows you to recover from all such I/O synchronization problems, though you'll still need (your program) to figure out where you should be reading and/or writing in order to avoid an infinite loop. But non-blocking I/O may not help with interactive programs that make use of the stdio library, unless you also explicitly set the buffering mode. All of the above are explained in much more detail in W. Richard Stevens' "Advanced Programming in the Unix Environment" than I can possibly go into here. See chapter 3 for the stdio stuff, chapter 12 for non-blocking I/O, and chapter 14 for discussions about pipes, popen(), and how buffering modes can be controlled by your program and how that affects the child. Don't get me wrong... pexpect is useful. But some of the problems you're trying to solve with it have other solutions, which in some cases might be more efficiently done in those other ways. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From python-url at phaseit.net Tue Mar 18 13:12:16 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 18 Mar 2008 17:12:16 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Mar 18) Message-ID: QOTW: "Most people don't use Python by accident, and most people don't continue to use Python by accident" - Chris Hagner, during the talk "Why Python Sucks (But Works Great For Us)" at PyCon 2008 "I don't want a macro facility in the language _because_ it would be so cool." - Laura Creighton Comments about PyCon 2008: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2b6cb0e7245347be/ http://opag.ca/pipermail/opag/2008-March/002704.html Immutable types and identity: http://groups.google.com/group/comp.lang.python/browse_thread/thread/194ce303c02fd9e3/ Avoiding a possible deadlock with subprocess when redirecting input and output: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c197df353787c044/ Guido on Py3000: http://www.artima.com/weblogs/viewpost.jsp?thread=227041 "arrays are more efficient than lists" - what does that actually mean? http://groups.google.com/group/comp.lang.python/browse_thread/thread/60b15d2438e9c827/ Iterating over generators may not be obvious: http://groups.google.com/group/comp.lang.python/browse_thread/thread/169bc46505b472fb/ Why isn't a method identical to itself? http://groups.google.com/group/comp.lang.python/browse_thread/thread/e48b60fdf00054ed People worried about sort() dropping its cmp argument: http://groups.google.com/group/comp.lang.python/browse_thread/thread/458d97c522e0723a/ enum-like identifiers: http://groups.google.com/group/comp.lang.python/browse_frm/thread/7012fd617feecd7e/ Experiences with Python and C++ / Java (portability, performance): http://groups.google.com/group/comp.lang.python/browse_frm/thread/bcc6361e7c4f646a/ Cython, Pyrex, ShedSkin, type annotation (and even compiler availability issues!): http://groups.google.com/group/comp.lang.python/browse_thread/thread/58a353757b79a973/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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 enthusiats": 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/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch 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://aspn.activestate.com/ASPN/Cookbook/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 are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python 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 roee88 at gmail.com Mon Mar 31 16:56:31 2008 From: roee88 at gmail.com (roee shlomo) Date: Mon, 31 Mar 2008 23:56:31 +0300 Subject: License of Python In-Reply-To: <9963f10e0803311350v1348e3cbg79e63461d28e6c8d@mail.gmail.com> References: <9963f10e0803311350v1348e3cbg79e63461d28e6c8d@mail.gmail.com> Message-ID: <9963f10e0803311356n3beb9d47h478f3811ffdf0d42@mail.gmail.com> On 30/03/2008, iu2 wrote: > > The problem is that including Python's license in the binary, which as > I understand is a must do I think you only need to include the PSF license if you modify python itself. from http://www.python.org/psf/license/: > There is no GPL-like "copyleft" restriction. Distributing binary-only > versions of Python, modified or not, is allowed. There is no requirement to > release any of your source code. You can also write extension modules for > Python and provide them only in binary form. > You cannot remove the PSF's copyright notice from either the source code > or the resulting binary. > It sounds like you cannot *remove* the copyright notice from files that already include it (like the Python source code and binaries. Not applications written in Python). >From the license itself: > 2. Subject to the terms and conditions of this License Agreement, PSF > hereby grants Licensee a nonexclusive, royalty-free, world-wide > license to reproduce, analyze, test, perform and/or display publicly, > prepare derivative works, distribute, and otherwise use Python 2.4 > alone or in any derivative version, provided, however, that PSF's > License Agreement and PSF's notice of copyright, i.e., "Copyright (c) > 2001, 2002, 2003, 2004 Python Software Foundation; All Rights Reserved" > are retained in Python 2.4 alone or in any derivative version prepared > by Licensee. > Correct me if I'm wrong. Thanks, Roee. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Tue Mar 4 05:38:26 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 4 Mar 2008 02:38:26 -0800 (PST) Subject: Difference between 'function' and 'method' References: Message-ID: On 4 Mar, 09:22, "??" wrote: > > This is a big problem puzzles me for a long time. The core question is: > How to dynamically create methods on a class or an instance? > > Let me state it step by step. > 1. > def gunc(self): > pass > class A(object): > def func(self): > pass > a = A() > a.func # gives "bound method", type is "instancemethod" > A.func # gives "unbound method", type is "instancemethod" > gunc # gives "function", type if "function" > > # ?? Does this line attach a method to instance? ... I don't think so. > a.gunc = gunc No, unfortunately not. You might get the detailed explanation from someone else, but generally, you have to assign functions to classes; these are then exposed as methods via instances of such classes. A.gunc = gunc > I found stardard library 'new' may help. Is that right? Yes, it can help: import new a.gunc = new.instancemethod(gunc, a, A) > 2. > a = A() # instance of old class A > # Do attach a new method to class A... > b = A() # instance of new class A > Does "a" can get the new method automatically? Can "a" get the new method automatically? Apparently, yes: class A: pass a = A() def f(self, x): print x A.f = f a.f(123) # works, printing 123 > Does new method have the *same* concept level with old methods? > Especially, if there > are classes inherit from class A, how does name resolution work on this case? As far as I'm aware, after you've added a method to a class, instances will regard the method like all the previously existing methods, since method lookup is a dynamic operation. I'll not address your other questions in this message since I'm not a heavy user of decorators and don't want to provide a quick answer without fully testing it first. However, it is important to remember that the "magic" occurs for class attributes, not instance attributes. So, for example, it's quite possible that you'd want to assign a function to an instance attribute, but you wouldn't want the instance to suddenly "own" that function... def somefunc(x, y): # Do something with x and y... return x + y a = A() a.somefunc = somefunc # store the function somewhere # Later... adder = a.somefunc # Later still... result = adder(p, q) # wouldn't work if somefunc became a method Python seems to do the most intuitive thing, I think, but it's quite tricky to contemplate all the implications. Paul P.S. I can never really remember all the different situations and outcomes with method assignment, but then it's something I hardly ever do. I'd be interested to know whether my situation is unusual, however. From tmp1 at viltersten.com Sat Mar 8 18:14:03 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 00:14:03 +0100 Subject: SV: SV: Regarding coding style In-Reply-To: <13t6251ep5bou67@corp.supernews.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> Message-ID: <63gjv0F270p58U1@mid.individual.net> > If you can't/don't look at the source file, > then comments aren't going to help (except > in the case of something like docstrings in > Python). I strongly disagree. Now, perhaps we're talking about different things, here? Usually, in the header file (C++), there won't be any source code, except for method declarations. A common example: /** Projects an object from 3D to 2D using the method of Alexander The Great. \param 3D structure to be projected \returns 2D projection */ public Proj2D get2Dfrom3D(Proj3D param); The above is, to me, very clear and consistent. Not to mention, easily handled with e.g. Doxygen to create a readable documentation. I don't see how this is dislikeable. Please explain. Perhaps the above IS what you ment by "docstrings"? For Java, one has the JavaDocs, a great tool, provided one will comment each method and variable used. >> Now, i'm getting the signal that it's done > in a different way in Python. > > I'm not sure how you concluded that from this thread. The below, more or less. :) "What I really can't stand are the pointy-haired comment blocks at the beginnings of C/C++ functions that do things like tell you the name and return type of the function and list the names and types of the parameters." Please note that i DO NOT argue against one way or another. I simply expressed surprise since i've been tought otherwise earlier and, maybe, there's a larger picture than what i've seen this far. As stated before, snakeology is a very new area to me. Yet. ;) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From martin at v.loewis.de Fri Mar 21 16:56:43 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 21 Mar 2008 21:56:43 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> Message-ID: <47E4210B.1080505@v.loewis.de> > Well at least this is what I think. If I'm not right then please explain > why. I think your confusion comes from the use of the interactive mode. PEP 263 doesn't really apply to the interactive mode, hence the behavior in interactive mode is undefined, and may and will change across Python versions. Ideally, interactive mode should assume the terminal's encoding for source code, but that has not been implemented. Regards, Martin From castironpi at gmail.com Thu Mar 6 17:45:09 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 6 Mar 2008 14:45:09 -0800 (PST) Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> Message-ID: <7817aa43-0f4d-4ace-9279-8e1fbdf2640d@b1g2000hsg.googlegroups.com> On Mar 6, 3:24?pm, a... at pythoncraft.com (Aahz) wrote: > In article <13sulsu4nbr2... at corp.supernews.com>, > Steven D'Aprano ? wrote: > > > > >I accept my question about classes being singletons is not well-formed, > >not even in my own mind. I guess one way of asking is, for any two class > >objects (not instances) C1 and C2, does "C1 == C2" imply "C1 is C2"? > > Even that stricture fails under the presence of metaclasses. ?;-) ?But > answering your real question, I don't remember off-hand the required > sequence, but it is possible to import a class two different ways such > that the classes are not the object. ?This can cause problems with e.g. > pickle. ?Within a single module, given a class defined only once within > that module, the class will be a singleton. > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "All problems in computer science can be solved by another level of ? ? > indirection." ?--Butler Lampson I'd like to question the source of the definition of C.__eq__. Observation: >>> class C: pass ... >>> class D: pass ... >>> C== D False What is different about them? I've created two empty classes, nothing more. From barry at python.org Sat Mar 1 17:29:39 2008 From: barry at python.org (Barry Warsaw) Date: Sat, 1 Mar 2008 17:29:39 -0500 Subject: [Python-3000] RELEASED Python 2.6a1 and 3.0a3 In-Reply-To: <47C9D802.2090205@v.loewis.de> References: <6E72CEB8-D3BF-4440-A1EA-1A3D545CC8DB@python.org> <47C9D802.2090205@v.loewis.de> Message-ID: <05D00F06-8B87-4B94-8878-42E1F3F50F90@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mar 1, 2008, at 5:26 PM, Martin v. L?wis wrote: >> As of 4:50 PM EST, the links to Windows installers give 404 File Not >> Found. >> >> I gather that they are still in process, >> and notice that there is no public c.l.p. announcement. > > I just fixed that. The files were there; just the links were wrong. Thanks for fixing these Martin! - -Barry -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) iQCVAwUBR8nY1HEjvBPtnXfVAQJ3YgP/TYr0X5vRqvVDEMgsHxHuiSuYZCIr8y36 ibAh3RAGeLLK7C7NiOyAfxkesf91HCbL1in0TcnD06QZy52O8elBa927JOomP3mc Y6K4Y49JhxonBrmGcmasnc9PFjbhXtGdWLREinuzpB5itLpRv+SevMhxP27Fp8qr df173TV4hpk= =nf32 -----END PGP SIGNATURE----- From nemesis at nowhere.invalid Sat Mar 8 15:02:35 2008 From: nemesis at nowhere.invalid (Nemesis) Date: 08 Mar 2008 20:02:35 GMT Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> Message-ID: <47d2f0da$0$4794$4fafbaef@reader4.news.tin.it> Bryan.Fodness at gmail.com wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). > > I would like to create a file that would have the structure, > > DoseReferenceStructureType = Site > ... > ... You should try with Regular Expressions or if it is something like xml there is for sure a library you can you to parse it ... anyway you can try something simpler like this: elem_dic=dict() for line in open(str(sys.argv[1])): line_splitted=line.split() for item in line_splitted: item_splitted=item.split("=") if len(item_splitted)>1: elem_dic[item_splitted[0]]=item_splitted[1] ... then you have to retrieve from the dict the items you need, for example, with the line you posted you obtain these items splitted: ['SITE'] and elem_dic will contain the last five, with the keys 'tag','vr','vm','len','name' and teh values 300a,0014 etc etc i.e. this: {'vr': '"CS"', 'tag': '"300a,0014"', 'vm': '"1"', 'len': '"4"', 'name': '"DoseReferenceStructureType">SITE'} -- Age is not a particularly interesting subject. Anyone can get old. All you have to do is live long enough. From arnodel at googlemail.com Sat Mar 1 03:07:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 1 Mar 2008 00:07:59 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com><13see4t3s23pn59@corp.supernews.com><9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> Message-ID: <10e9004f-4bba-42e0-9d17-786104019289@h25g2000hsf.googlegroups.com> On Mar 1, 5:49?am, "Terry Reedy" wrote: > "Arnaud Delobelle" wrote in message > > news:ea3aecb0-c946-46be-bcd5-0c7584751e4b at b1g2000hsg.googlegroups.com... > | Perhaps it'll be like when I quit smoking six years ago. ?I didn't > | enjoy it although I knew it was good for me... And now I don't regret > | it even though I still have the occasional craving. > > In following the development of Py3, there have been a few decisions that I > wish had gone otherwise. ?But I agree with more than the majority and am > not going to deprive myself of what I expect to be an improved experience > without giving Py3 a fair trial. I realise that my comment can be easily misunderstood! I wasn't implying that I would be quitting python, rather that I would have to adjust (with some discomfort) to a new division paradigm. I know from experience that I end up as a staunch defender of most of the design decisions in Python, particularly those that I disagreed with at the start! -- Arnaud From bj_666 at gmx.net Thu Mar 20 10:33:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Mar 2008 14:33:26 GMT Subject: backslash in reading bytes References: <560a5033-576f-4876-91cf-08276985b308@s50g2000hsb.googlegroups.com> Message-ID: <64fatmF29ep7qU2@mid.uni-berlin.de> On Thu, 20 Mar 2008 03:24:49 -0700, Dravidan wrote: > I am trying to read some byte data as a string then using a library to > convert them a code: > >>>>reader = csv.DictReader(open('table.txt')) >>>>def eleFind(value): >>>> for row in reader: >>>> if row['byteCode'] == value: >>>> print row['Element'] >>>> return >>>> else: >>>> print "No Match Found:" >>>>eleFind('\x00\x00') > > My table contains: > > \x00\x00,0000 > \x01\x00,0000 > ...... > > The program errors out. How can I fix/overide this backslash issue. What does `errors out` mean? It won't find two zero bytes. What you give at the `eleFind()` call are just *two* characters with a byte value of zero: In [116]: len('\x00\x00') Out[116]: 2 In [117]: print '\x00\x00' In [118]: len('\\x00\\x00') Out[118]: 8 In [119]: print '\\x00\\x00' \x00\x00 The backslash has a special meaning in string literals. If you don't want this meaning, you have to escape it with another backslash. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Mon Mar 10 23:34:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Mar 2008 23:34:56 -0400 Subject: for-else References: <20080308152034.GA12009@hccnet.nl> Message-ID: "Carl Banks" wrote in message news:dfcf19e3-a216-461d-998e-30fbe139a722 at n75g2000hsh.googlegroups.com... | Just to play Devil's advocate, there is one draw drawback to "such | elegance": when there are multiple break statements. Which means | you'd have to duplicate the break-only condition, or refactor somehow | (which may or may not be suitable). Yes, I knowingly glided over the possibility of multiple break statements with common break-only code and no completion-only code (other than artifactual flag setting as in your code below ;-). I presume that that triple condition is even rarer than simpler situations where one of those conditions is false. | There have been a couple occasions where I felt the best solution was | to a temporary varible like so: But I will accept your testimony that the set of such use cases is not empty. | completed = False | while loop_condition: | | if break_condition: | break | | if some_other_break_condition: | break | | else: | completed = False I presume you meant True | if not completed: | | | It felt icky but we're all still here so it couldn't have been that | bad. tjr From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 07:41:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 11:41:17 -0000 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> Message-ID: <13usamtfql9a87c@corp.supernews.com> On Sat, 29 Mar 2008 04:08:16 -0700, Paul Rubin wrote: > kwitters at telenet.be writes: >> I don't know if this is the right place to discuss the death of <> in >> Python 3.0, or if there have been any meaningful discussions posted >> before (hard to search google with '<>' keyword), but why would anyone >> prefer the comparison operator != over <>??? > > I doubt anyone cares. [channeling Luke Skywalker sotto voice] I care. > Python probably chose != because it's what C uses. Coming from a background in Pascal, I originally hated the look of != and preferred <> but I've now got used to the look of it. When I design my own language (ha!), I'll use != for "not equal to" and reserve <> for "greater than or less than but not equal to" which is subtly different. (Think about unordered values, where x != y does not imply that x < y or x > y, e.g. IEEE NaNs.) > The scary choice is /= which can be interpreted as an assignment. "Can be"? >>> x = 5.0 >>> x /= 2 >>> x 2.5 Koen, I've read your blog and I'm afraid that your reasoning is specious. You say: [quote] For comparison (not assignment!), they use operators like <, >, <= (smaller or equals), >= (larger or equals), == (double '=' so there is no confusion with assignment). All pretty clear hey? But now comes the catch, there exists an operator !=... but what does it mean? Well, that one is pretty easy, of course ! must be an operator of its own (in non-python languages meaning 'not'), and it resembles the fancy assignment statement, so a != b must mean "assign the value 'not b' to 'a'... right?... Wrong! Somehow this is a comparison operator meaning "not equals"... what??? Yes, that's right, but hey, you learn to live with it eventually. [end quote] Given that <= is a comparison operator, not an assignment, why do you jump to the conclusion that != is an assignment? Why don't you argue that "x <= y" means "assign the value of x Message-ID: On Mar 16, 2:27 pm, MRAB wrote: > On Mar 16, 2:27 am, Benjamin wrote: > > > On Mar 15, 8:12 pm, lampshade wrote:> Hello, > > > > I'm having some problems with os.path.isdir I think it is something > > > simple that I'm overlooking. > > > > #!/usr/bin/python > > > import os > > > > my_path = os.path.expanduser("~/pictures/") > > > print my_path > > > results = os.listdir(my_path) > > > for a_result in results: > > > if os.path.isdir(str(my_path) + str(a_result)): > > > Try if os.path.isdir(os.path.join(my_path, a_result)):> results.remove(a_result) > > > > for x in results: print x > > > > The problem is, that the directories are never removed. Can anyone > > > point out what I'm missing that is causing the bug? Is there a better > > > way of doing this? > > > You should always use os.path.join to join paths. You shouldn't add > > them like normal strings. I suspect you're getting a combination which > > doesn't exist, so it isn't a dir. :) > > You are also removing items from 'results' while iterating over it, > which has an undefined behaviour. It would be better to build a new > list of those that aren't directories. This list comprehension should do the trick pythonically: final_results = [a_result for a_result in results if os.path.isdir(os.path.join(my_path, a_result))] From jvines at arl.army.mil Mon Mar 10 10:42:05 2008 From: jvines at arl.army.mil (John Vines (CISD/HPCD)) Date: Mon, 10 Mar 2008 10:42:05 -0400 Subject: adding Tcl support to an existing install of Python Message-ID: <47D548BD.1070207@arl.army.mil> All, I need to add Tkinter support, build Tcl/Tk, to an existing RHEL5 python 2.5.1 installation. I know this can be done but I can't remember how :) Can someone lend some help in this area? Thanks in advance, John From http Sun Mar 23 00:40:40 2008 From: http (Paul Rubin) Date: 22 Mar 2008 21:40:40 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <7xlk4anjcn.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > I've been learning a fair amount about functional programming > recently, mostly because compile-time C++ turns out to be a pure > functional programming language. Where should I go for a solid > grounding in lambda-calculus? For PL theory in general, try this: http://www.cs.cmu.edu/~rwh/plbook/book.pdf From zubeido at yahoo.com.br Sun Mar 30 10:44:31 2008 From: zubeido at yahoo.com.br (aiwarrior) Date: Sun, 30 Mar 2008 07:44:31 -0700 (PDT) Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> Message-ID: <91055e8b-ce64-49a3-b736-16afe8336c4b@e39g2000hsf.googlegroups.com> Ok regarding Gerhard's comment of the try, except, pass, i came to understand that it's really bad code. And i should have referred that i put that there be cause i was getting: Traceback (most recent call last): File "C:\Python25\Projects\cp.py", line 48, in db = db() File "C:\Python25\Projects\cp.py", line 19, in __init__ self.cursor.execute( "CREATE TABLE database (album,filepath)" ) OperationalError: table database already exists But when i tried to handle the Operational error with : try: self.cursor.execute( "CREATE TABLE database (album,filepath)" ) except OperationalError: pass I would got: NameError: global name 'OperationalError' is not defined I searched the Internet and found that sqlite3.OperationalError was missing. Dumb me. Now even though i've been reading a bit about exceptions in python tutorial i've come to realize that my approach won't give me the results i want. To my understanding the try statement will still execute the statement within it until it produces the error. So even if i caught this OperationalError i wouldn't know what to do with it. What i'm going to study is whether it's possible to evaluate if a table already exists, and if so act accordingly. Duncan Booth wrote: >Are you absolutely certain of that? If you use print to try to debug the >value of an object you should usually use repr > print repr(audio['album']) As Gerhard correctly guessed i'm a newbie and didn't know of the existence repr. I've been reading about it in python documentation but have yet to analyze it more carefully. I guess the parentheses are just some form of maniac stupidity. Will try to be more clean about them. Thanks for all the patience and hope i've been more forthcoming in this post. From castironpi at gmail.com Fri Mar 14 17:52:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 14 Mar 2008 14:52:54 -0700 (PDT) Subject: Network server- / client-side messaging References: Message-ID: On Mar 2, 3:43?pm, castiro... at gmail.com wrote: > ''' > Last time, we left off at: > ''' > > class InterfaceClientSide( ClientSide ): > ? ? ? ? message= MessageDec() > ? ? ? ? incremental= message.incremental() > ? ? ? ? settings= AYT( .5, 3 ) > ? ? ? ? user_act= message.out() > ? ? ? ? def __init__( self, image ): > ? ? ? ? ? ? ? ? self._image= image > ? ? ? ? ? ? ? ? ClientSide.__init__( self ) > ? ? ? ? def on_scale( self, *args ): > ? ? ? ? ? ? ? ? change= self._whatchange( > ? ? ? ? ? ? ? ? ? ? ? ? self.on_scale, *args ) > ? ? ? ? ? ? ? ? self.user_act( change ) > ? ? ? ? def on_rotate( self, *args ): > ? ? ? ? ? ? ? ? change= self._whatchange( > ? ? ? ? ? ? ? ? ? ? ? ? self.on_rotate, *args ) > ? ? ? ? ? ? ? ? self.user_act( change ) > ? ? ? ? @incremental( 1 ) > ? ? ? ? def layout_return( self, layoutchange ): > ? ? ? ? ? ? ? ? renderchange( layoutchange ) > ? ? ? ? @incremental( 2 ) > ? ? ? ? def layout_return( self, layoutchange ): > ? ? ? ? ? ? ? ? renderchange( layoutchange ) > ? ? ? ? @message > ? ? ? ? def time_estimate( self, etc ): > ? ? ? ? ? ? ? ? report( etc ) > > class InterfaceServerSide( ServerSide ): > ? ? ? ? message= MessageDec() > ? ? ? ? incremental= message.incremental() > ? ? ? ? settings= AYT( .5, 3 ) > ? ? ? ? time_estimate= message.out() > ? ? ? ? layout_return= incremental() > ? ? ? ? def __init__( self, image ): > ? ? ? ? ? ? ? ? self._image= image > ? ? ? ? ? ? ? ? ServerSide.__init__( self ) > ? ? ? ? @message.intervene() > ? ? ? ? def user_act( self, change ): > ? ? ? ? ? ? ? ? etc= self.calculateeta( change ) > ? ? ? ? ? ? ? ? self.time_estimate( etc ) > ? ? ? ? ? ? ? ? preliminary= self.calculation() > ? ? ? ? ? ? ? ? preliminary_change= whatchange( preliminary ) > ? ? ? ? ? ? ? ? self.layout_return( preliminary_change ) > ? ? ? ? ? ? ? ? completed= self.other_calculation() > ? ? ? ? ? ? ? ? completed_change= whatchange( completed ) > ? ? ? ? ? ? ? ? self.layout_return( completed_change ) > ? ? ? ? ? ? ? ? self.layout_return.finish() > > ''' > Another use ClientSide and ServerSide should support is a peer-to-peer > chat-and-game server. ?And that said, it's not clear that there's any > distinction between ServerSide and ClientSide anyway, depending on > exactly how the listen and connect methods abstract. ?How much of the > implementation do they share? ?Most. > > You could mark 'time_estimate' as incremental( 3 ); they're separated > for illustration purposes. > > One remaining question is how to intervene in user_act, if a second > change arrives before the previous complete. ?You could combine the > earlier change parameter in the new call and throw an exception in the > thread handling the earlier one at its first loss of control--- and > maybe even at once with settrace! ?That tends to be costly. ?Not to > mention, change has already entered derived-class space. ?ServerSide > should make sure it's easy enough to address the issue on one's own, > and @message.nonintervene() is available too. > ''' The issues over here this week were delta vs. state-- if there is a unifiable way to specify constraints on which is cheaper given what, and transmit it, -- and, partial inheritance of not just methods, data: overriding 'message' and wanting -its- derivatives-- user_act, time_estimate-- to know it, without redefining. Obvious solutions can be redundant. self.message.layout_return is; get 'layout_return' into the class definition. It's immediately easy to receive the 'ServerSide' instance as a parameter-- less so to get both it and the 'message' instance. If we can, MessageDec can include data, but is still constrained by overriding 'message'. Conclusion? Might as well include some data in MessageDec. How well does message= MessageDec( ServerSide.send ) settle? From steve at REMOVE-THIS-cybersource.com.au Wed Mar 5 17:07:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Mar 2008 22:07:21 -0000 Subject: Using re module better References: <95fdfa3f-c4e2-45f7-9cc9-d85417ba0877@u69g2000hse.googlegroups.com> <1f63d5df-70e8-4eb9-81f7-7f2abb6f98b1@u10g2000prn.googlegroups.com> Message-ID: <13su6cpjl61mee7@corp.supernews.com> On Wed, 05 Mar 2008 11:09:28 -0800, castironpi wrote: > On another note, why do people X, Y, and Z, including me, all hate to > write a= b(); if a: a.something()? Is this a guessing game? You want us to guess why YOU hate to do something? Okay, I'm game for guessing games... You were traumatized as a child by a newline byte, and now you try to write everything possible as a one-liner. Am I close? Speaking for myself, I *prefer* to separate the assignment from the comparison. I dislike greatly the syntax "if (a=b()): a.something()". -- Steven From sturlamolden at yahoo.no Sat Mar 15 17:45:43 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 14:45:43 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: On 15 Mar, 22:43, Guido van Brakel wrote: > > def gem(a): > > g = sum(a) / len(a) > > return g > It now gives a int, but i would like to see floats. How can integrate > that into the function? You get an int because you are doing integer division. Cast one int to float. def gem(a): g = sum(a) / float(len(a)) return g From gandalf at shopzeus.com Wed Mar 19 06:24:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 19 Mar 2008 11:24:45 +0100 Subject: Decode email subjects into unicode In-Reply-To: <6gl1u3d3vei5tff9t6ivuhl7gf2qfg6p0k@4ax.com> References: <47DF8EED.1010501@shopzeus.com> <6gl1u3d3vei5tff9t6ivuhl7gf2qfg6p0k@4ax.com> Message-ID: <47E0E9ED.7050902@shopzeus.com> Gertjan Klein wrote: > Laszlo Nagy wrote: > > >> However, there are malformed emails and I have to put them into the >> database. What should I do with this: >> > [...] > >> There is no encoding given in the subject but it contains 0x92. When I >> try to insert this into the database, I get: >> > > This is indeed malformed email. The content type in the header specifies > iso-8859-1, but this looks like Windows code page 1252, where character > \x92 is a single right quote character (unicode \x2019). > > As the majority of the mail clients out there are Windows-based, and as > far as I can tell many of them get the encoding wrong, I'd simply try to > decode as CP1252 on error, especially if the content-type claims > iso-8859-1. Many Windows mail clients consider iso-8859-1 equivalent to > 1252 (it's not; the former doesn't use code points in the range \x8n and > \x9n, the latter does.) > > Thank you very much! From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 10:23:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 14:23:25 -0000 Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> <286ec45d-1240-4794-9230-dc4f5fe5839e@q78g2000hsh.googlegroups.com> <13t7okcjo91gaa2@corp.supernews.com> <62278c08-9eb1-4db1-9e73-75e6f5707563@n36g2000hse.googlegroups.com> Message-ID: <13t7smt4rn8rn32@corp.supernews.com> On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote: > Okay, so I think I know where's the catch now -- you must rely on the > fact that the protocol is implemented, there's no way to enforce it if > you're expecting a parrot-like object. You'd try to call the speak() > method and deal with the error if there's no such method? That's right. That's called "duck typing" -- if all you want is something that quacks like a duck, then it doesn't matter if it actually is a duck or not. Or if you prefer: if it quacks like a duck and swims like a duck, then it's close enough to a duck as to make no difference. Sometimes though, you need to check for a parrot up front. So I'd so this: try: something.speak except AttributeError: # No speak() method, so it can't be a parrot. do_something_else() else: # It seems to follow the parrot protocol. yummy_goodness = something.speak(5) assert "spam" in yummy_goodness.lower() -- Steven From jeff at schwabcenter.com Tue Mar 4 23:04:36 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 04 Mar 2008 20:04:36 -0800 Subject: SV: Polymorphism using constructors In-Reply-To: References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: Tommy Grav wrote: > > On Mar 4, 2008, at 4:53 PM, Jeff Schwab wrote: > >> What does "SV" in the subject mean? > > SV = "Svar" is the Norwegian word for Reply. Thanks. Serves me right for not speaking Norwegian. From crashbangboom at gmail.com Sat Mar 8 12:48:22 2008 From: crashbangboom at gmail.com (crashbangboom at gmail.com) Date: Sat, 8 Mar 2008 09:48:22 -0800 (PST) Subject: Help xxx.py Program Recognition problem Message-ID: <224ea046-65c4-40b5-8bd5-ede1c87c801e@e6g2000prf.googlegroups.com> Hi... I was using Python 2.4 and installed 2.5...I copied all my .py files from the Python24\ root directory to the Python25\ root directory...when I try to run them by double clicking I get: "XXXXX.py is not a valid Win32 application"... Also, the files do not appear to be associated with python...? I can run them from IDLE...but that is it... How do I fix this...? Thanks.. Dave From yuxi at ece.gatech.edu Thu Mar 13 18:00:08 2008 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Thu, 13 Mar 2008 18:00:08 -0400 Subject: image matching algorithms In-Reply-To: References: Message-ID: Daniel Fetchinson wrote: > Since you seem to know quite a bit about this topic, what is your > opinion on the apparently 'generic' algorithm described here: > http://grail.cs.washington.edu/projects/query/ ? > So far it seems to me that it does what I'm asking for, it does even > more because it can take a hand drawn sample image and query the > database for similar photos. > > There is even a python implementation for it here: > http://members.tripod.com/~edcjones/pycode.html > > On the histogram method I agree that it won't work partly because of > what you say and partly because it is terribly slow since it's > comparing every single pixel. I'm hardly the expert and can't answer authoritatively, but here's my 2c. I can't comment as to the actual accuracy of the algorithm, since it will depend on your specific data set (set of photos). The algorithm is sensitive to spatial and luminance information (because of the YIQ colorspace), so there are simple ways in which it will fail. The histogram method uses only color, but has a lot of numbers to compare. You may find the histogram method insensitive to spatial relations (a landscape with the mountain on the left and one with the mountain on the right) compared to the wavelet approach. This is a relatively old paper, and I've seen other more recent image retrieval research using wavelets (some cases using only the high-frequency wavelets for "texture" information instead of the low-frequency ones used by this paper for "shape") and other information retrieval-related research using lossy compressed data as the features. If you have time, you may want to look at other research that cite this particular paper. And just a thought: Instead of merely cutting off at m largest-wavelets, why not apply a quantization matrix to all the values? Let me know how it works out. From gandalf at shopzeus.com Fri Mar 28 12:28:02 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 28 Mar 2008 17:28:02 +0100 Subject: How do I reconnect a disconnected socket? In-Reply-To: <13uq69e8us4oo74@corp.supernews.com> References: <13uq69e8us4oo74@corp.supernews.com> Message-ID: <47ED1C92.10508@shopzeus.com> > Yes, that is exactly what it means. > > >From the recv() man page: > > RETURN VALUE > These calls return the number of bytes received, or -1 if an error > occurred. The return value will be 0 when the peer has performed an > orderly shutdown. > > Mea cupla. :-) What about non-blocking sockets? From nagle at animats.com Mon Mar 31 12:27:22 2008 From: nagle at animats.com (John Nagle) Date: Mon, 31 Mar 2008 09:27:22 -0700 Subject: Summary of threading for experienced non-Python programmers? In-Reply-To: <8763v4otts.fsf@mulj.homelinux.net> References: <87od8yolay.fsf@mulj.homelinux.net> <654ng1F2cvh8aU1@mid.uni-berlin.de> <87d4pe9caz.fsf@mulj.homelinux.net> <656vhnF2e9ao7U1@mid.uni-berlin.de> <8763v4otts.fsf@mulj.homelinux.net> Message-ID: <47f10e70$0$36392$742ec2ed@news.sonic.net> Hrvoje Niksic wrote: > Unfortunately, this is not the case for files at all, even on Unix. > (On Windows, select doesn't work on files at all, it only accepts > sockets.) "select" doesn't work on Windows pipes, either. I had to go to a multithreaded program to work around that. John Nagle From sales057 at aaa-replica-watch.com Mon Mar 17 23:59:53 2008 From: sales057 at aaa-replica-watch.com (sales057 at aaa-replica-watch.com) Date: Mon, 17 Mar 2008 20:59:53 -0700 (PDT) Subject: Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Replica Message-ID: <5cefbe3e-165a-44a2-8f5a-8a818f9ea287@s37g2000prg.googlegroups.com> Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Replica, Fake, Cheap, AAA Replica watch Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Link : http://www.aaa-replica-watch.com/Ebel_1215525.html Buy the cheapest Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 in toppest Replica . www.aaa-replica-watch.com helps you to save money! Ebel-1215525 , Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 , Replia , Cheap , Fake , imitation , Ebel Watches Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Information : Brand : Ebel Watches (http://www.aaa-replica-watch.com/ Replica_Ebel.html ) Gender : Ladies Model : Ebel-1215525 Case Material : 18kt Yellow Gold And Stainless Steel Case Diameter : 1215525, Ebel-1215525, 1200L21-6360, 1200L21/6360, 1200L21.6360, 1200L216360 Dial Color : Silver Guilloche Bezel : 18kt Yellow Gold Movement : Automatic Clasp : 18kt Yellow Gold And Stainless Steel Water Resistant : 100m/330ft Crystal : Scratch Resistant Sapphire Our Price : $ 220.00 18kt yellow gold and stainless steel case and bracelet. Silver sunburst guilloche dial. Date displays at 3 o'clock position. Hidden folding clasp. Anti-reflective scratch resistant sapphire crystal. Case diameter 27mm. Automatic movement. Water resistant at 100 meters (330 feet). Alternate model number 1200L21/6360. Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 Replica, With the mix of finest craftsmanship and contemporary styling, not only does it reflect the time but also care you put into looking good. choose one to promote your quality and make yourself impressive among people Thank you for choosing www.aaa-replica-watch.com as your reliable dealer of quality waches including Ebel 1911 Lady 18kt Yellow Gold and Steel Ladies Watch 1215525 . we guarantee every watch you receive will be exact watch you ordered. Each watch sold enjoy one year Warranty for free repair. Every order from aaa-replica-watches is shipped via EMS, the customer is responsible for the shipping fee on the first order, but since the second watch you buy from our site, the shipping cost is free. Please note that If the total amount of payment is over $600(USD), the customer is required to contact our customer service before sending the money in case failed payment. If you have any other questions please check our other pages or feel free to email us by service at aaa-replica-watch.com. The Same Ebel Watches Series : Ebel 1911 Mens Watch 91331240/14665P : http://www.aaa-replica.com/Ebel_91331240_14665P.html Ebel 1911 Womens Watch 1090211-19865P : http://www.aaa-replica.com/Ebel_1090211_19865P.html Ebel 1911 Mens Watch 1080241-13665P : http://www.aaa-replica.com/Ebel_1080241_13665P.html Ebel 1911 Womens Watch 9090214-19865P : http://www.aaa-replica.com/Ebel_9090214_19865P.html Ebel 1911 Womens Watch 1087221-15865P : http://www.aaa-replica.com/Ebel_1087221_15865P.html Ebel 1911 Womens Watch 1087221-19865P : http://www.aaa-replica.com/Ebel_1087221_19865P.html Ebel 1911 Mens Watch 9331240-13665P : http://www.aaa-replica.com/Ebel_9331240_13665P.html Ebel 1911 Mens Watch 9125241-10665P : http://www.aaa-replica.com/Ebel_9125241_10665P.html Ebel 1911 Mens Watch 9330240-15665P : http://www.aaa-replica.com/Ebel_9330240_15665P.html Ebel Classic Mini Stainless Steel Ladies Watch 9003F11.9925 : http://www.aaa-replica.com/ebel_classic_mini_watch_9003F11_9925.html Ebel Classic Stainless Steel Mens Watch 9120F51.6235134 : http://www.aaa-replica.com/ebel_classic_stainless_9120F516235134.html Ebel Classic Stainless Steel Mens Watch 9120F51/5235136 : http://www.aaa-replica.com/ebel_classic_stainless_9120F515235136.html From kaushikbarat at gmail.com Sun Mar 2 17:24:11 2008 From: kaushikbarat at gmail.com (Kaushik Barat) Date: Sun, 2 Mar 2008 14:24:11 -0800 Subject: mod_python Unable to create file In-Reply-To: <85F61543-7ACD-4D9A-97A2-DB65D3B70B27@ardishealth.com> References: <62v31gF24ontgU1@mid.uni-berlin.de> <85F61543-7ACD-4D9A-97A2-DB65D3B70B27@ardishealth.com> Message-ID: Hey thanks a lot Sean.Setting the permissions on the directory path solved the problem. On Sun, Mar 2, 2008 at 11:09 AM, Sean Allen wrote: > > On Mar 2, 2008, at 3:24 AM, kaush wrote: > > > On Mar 1, 11:24 pm, Marc 'BlackJack' Rintsch wrote: > >> On Sat, 01 Mar 2008 22:47:02 -0800, kaush wrote: > >>> I am using Apache and mod_python to service POST/GET requests on MAC > >>> OS. My script tries to create a file > >> > >>> file = open(file_path, 'w') > >> > >>> This fails with the following error > >> > >>> EACCES > >>> Permission denied > >> > >>> What is missing? > >> > >> To state the ovious: the rights to create a file at `file_path`. > >> Remember > >> that web servers usually have their own "user". > >> > >> Ciao, > >> Marc 'BlackJack' Rintsch > > > > Thanks Marc. > > In Apache what are the ways/directives to set the rights to a folder? > > none. you set permissions via the operating system. > > chmod would be the command from terminal you are looking for. > > or you can do get info on the folder in question via the finder and > set perms there. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 28 05:00:54 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 28 Mar 2008 10:00:54 +0100 Subject: Getting back an Object In-Reply-To: References: <5dc598e30803271840y4aeeb524w99d7f0550260fa8d@mail.gmail.com> Message-ID: <47ecb3b3$0$10375$426a74cc@news.free.fr> Gary Herron a ?crit : (snip) > One other word of warning. It is best to not use a variable named > "string" as Python has a builtin type of that name which would become > inaccessible if you redefine. Good advice, except that the builtin string type is actually named 'str', not 'string' !-) From z80vsvic20 at hotmail.com Sat Mar 15 16:09:18 2008 From: z80vsvic20 at hotmail.com (Eric von Horst) Date: Sat, 15 Mar 2008 13:09:18 -0700 (PDT) Subject: Python and 3D Message-ID: Hi, I am looking for Python modules that allow you to manipulate 3D objects, more specifically Alias Wavefront .OBJ objects. Also, a module that would allow you to vizualize these models and rotate them etc.. The goal is not to build a new renderer or something; just a small program that I need to do some manipulations in bulk on a set of OBJs Any help much appreciated Eric From grante at visi.com Mon Mar 3 17:10:19 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Mar 2008 22:10:19 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> <13sor5vjk06i71a@corp.supernews.com> <04ce92a8-9c24-4c38-bff1-304af21c86a1@d21g2000prf.googlegroups.com> Message-ID: <13sotqbl5kqrsa9@corp.supernews.com> On 2008-03-03, blaine wrote: > I do have a question though. In the termios module, I am attempting > to set the baud rate to 921600, which is what we use with > 'cutecom' (because minicom does not have this as an option) and is > what the supplier recommends. When I try to set the rate using > termios.tcsetattr(), I get an Argument Error. What values are you using for ispeed and ospeed? Those values are special (and rather arbitrary) constant bit-patterns and not simply integers like 9600 or 115200. > I do not get this when I use an existing baud rate, such as > termios.B9600. Is there a way I can get around this? We would > like to use it at full speed. It looks like the fastest speed supported by python termios on Linux is B460800 (uses a constant of 0x1004). If you look in /usr/include/..., baud rates do go up to 921600 (which uses a constant of 0x1007). Try using the appropriate constant from /usr/include/... (for the target platform, of course). -- Grant Edwards grante Yow! Please come home with at me ... I have Tylenol!! visi.com From pboppudi at vmware.com Thu Mar 27 14:24:05 2008 From: pboppudi at vmware.com (Praveena Boppudi (c)) Date: Thu, 27 Mar 2008 11:24:05 -0700 Subject: How to take snap shot of the of project screen in Python In-Reply-To: References: <7e67ff3d-4c0e-4e21-98f2-faace68e230f@s12g2000prg.googlegroups.com> Message-ID: Hi, Can anyone help me out? Thanks, Praveena. From Robert.Bossy at jouy.inra.fr Thu Mar 13 11:50:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Thu, 13 Mar 2008 16:50:57 +0100 Subject: "Attribute Doesnt Exist" ... but.... it does :-s In-Reply-To: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> References: <00ef01c88520$0db87820$29296860$@rawlins@thinkbluemedia.co.uk> Message-ID: <47D94D61.9010708@jouy.inra.fr> Robert Rawlins wrote: > > Hello Guys, > > I?ve got an awfully aggravating problem which is causing some > substantial hair loss this afternoon J I want to get your ideas on > this. I am trying to invoke a particular method in one of my classes, > and I?m getting a runtime error which is telling me the attribute does > not exist. > > I?m calling the method from within __init__ yet it still seems to > think it doesn?t exist. > > Code: > > # Define the RemoteDevice class. > > class *remote_device*: > > # I'm the class constructor method. > > def *__init__*(/self/, message_list=/""/): > > /self/.set_pending_list(message_list) > > def *set_pending_list*(/self/, pending_list): > > # Set the message list property. > > /self/.pending_list = message_list > > And the error message which I receive during the instantiation of the > class: > > File: ?/path/to/my/files/remote_device.py", line 22, in __init__ > > self.set_pending_list(message_list) > > AttributeError: remote_device instance has no attribute 'set_pending_list' > > Does anyone have the slightest idea why this might be happening? I can > see that the code DOES have that method in it, I also know that I > don?t get any compile time errors so that should be fine. I know it > mentions line 22 in the error, but I?ve chopped out a load of non > relevant code for the sake of posting here. > Hi, I don't get this error if I run your code. Maybe the irrelevant code causes the error: my guess is that there's a parenthesis mismatch or an undeindented line. Btw, calls to set_pending_list will fail since the name "message_list" is not defined in its scope. Please follow Chris Mellon's advice. Cheers, RB From sjmachin at lexicon.net Sun Mar 23 17:56:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 14:56:37 -0700 (PDT) Subject: Problems with joining Unicode strings References: <5b623e11-054d-44b7-bc65-d75922728dce@b1g2000hsg.googlegroups.com> Message-ID: <0f1d12c2-ac36-4b0e-9eed-6d59028710eb@d4g2000prg.googlegroups.com> On Mar 24, 7:58 am, Ulysse wrote: > Hello, > > I have problems with joining strings. > > My program get web page fragments, then joins them into one single web > page. I have error when I try to join these fregments : > "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position > 208: ordinal not in range(128)" > > Here is my code : [snip] Contrary to your message subject, you are *not* joining "Unicode strings". Your resume_news contains at least one str (8-bit string) objects [probably all of them are str!]. You need to decode each str object into a unicode object, using whatever encoding is appropriate to that str object. When you do u''.join(sequence_including_str_objects), Python attempts to decode each str object using the default 'ascii' encoding ... this of course fails if there is a non-ASCII character in the str object. This may help: www.amk.ca/python/howto/unicode Cheers, John From From at home Fri Mar 21 18:16:41 2008 From: From at home (From at home) Date: Fri, 21 Mar 2008 17:16:41 -0500 Subject: List question Message-ID: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> Hello, I am learning python and dont quuite understand why is this happening could someone explain? alist = [] blist = [ 'one','two','one and two','one and four','five','one two'] for f in blist: if 'one' and 'two' in f: alist.append(f) for i in alist: print i two one and two one two why is it printing the first "two"? tia From mnordhoff at mattnordhoff.com Mon Mar 3 19:14:22 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 04 Mar 2008 00:14:22 +0000 Subject: os.system with cgi In-Reply-To: <4a7f84ac0803031556p721d9a74h2cd7051bf6bc5b7e@mail.gmail.com> References: <4a7f84ac0803031556p721d9a74h2cd7051bf6bc5b7e@mail.gmail.com> Message-ID: <47CC945E.10303@mattnordhoff.com> G wrote: > Hi, > > I have the following peace of code > > def getBook(textid, path): > url = geturl(textid) > if os.path.isfile(path + textid): > f = open(path + textid) > else: > os.system('wget -c ' + url + ' -O ' path + textid) > f = open(path + textid) > return f > > The reason I am not using urllib is that I want to have random access > within the downloaded file. > > When i execute the file from a regular python script I get the file > downloaded and a handle for the file returned. > When I execute the file from a python cgi script i get an error saying > that the file doesn't exist. In other words the call to os.system is not > running. > Could someone please point out what the problem with that peace of code > running as a cgi script. > > Best. Ew. You could at least use subprocess and not be vulnerable to someone passing "; rm -rf ~; echo" or something as the path. If you need random access like that, and urllib2 can't do it, you could use urllib2 and a StringIO or temporary file or something. Using wget makes it much harder to handle errors. Heck, you could just read the file into a string and use slicing, if it's not too large... -- From simon at brunningonline.net Wed Mar 26 09:45:33 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Mar 2008 13:45:33 +0000 Subject: Do any of you recommend Python as a first programming language? In-Reply-To: <13ubn5ue821ak7e@corp.supernews.com> References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <1ad61c95-de3e-45ce-8f63-f8e78c5db486@n58g2000hsf.googlegroups.com> <63ba1212-cb8f-48bb-9c54-4640dd486bb2@h11g2000prf.googlegroups.com> <13ubn5ue821ak7e@corp.supernews.com> Message-ID: <8c7f10c60803260645n309badfcg164308999b5bda9d@mail.gmail.com> On Sun, Mar 23, 2008 at 4:29 AM, Steven D'Aprano wrote: > Python is a programming language. It can be used for scripting, but > that's not all it can do. Describing it as a "scripting language" is like > describing a fully-equipped professional kitchen as "a left-over warming > room". +1 QOTW. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From arnodel at googlemail.com Tue Mar 18 17:43:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 18 Mar 2008 14:43:01 -0700 (PDT) Subject: keyboard "interrupt" References: <1ie04t3.omt2i1167vfmiN%johnmfisher@comcast.net> Message-ID: John Fisher wrote: > Hi Group, Hi John > I have been absent a while, mainly because I have been getting better at > figuring out my own Python problems. But not this one... > > I have a timed loop performing certain tasks until a total period of > time has elapsed. I would like to be able to interrupt the loop or set > various flags during execution via keyboard input. raw_input seems to > just stop everything cold. I want the ability to just sacn the keyboard > buffer and see if something is there, then proceed normally in the loop > if there is no input in the buffer. Make sense? Totally easy? Let me > know... If you are on a UNIX platform, you can use the curses module. http://docs.python.org/lib/module-curses.html There is a link there to a tutorial, but it seems to be broken. A quick search finds it there: http://www.amk.ca/python/howto/curses/ HTH -- Arnaud From pianomaestro at gmail.com Fri Mar 28 11:25:55 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 08:25:55 -0700 (PDT) Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: <17e0f94a-555c-40c7-8dd6-90c6d9c0b633@a23g2000hsc.googlegroups.com> On Mar 28, 11:14 am, "Gabriel Genellina" wrote: > En Fri, 28 Mar 2008 11:51:10 -0300, escribi?: > > > I have an extension module that gets initialized multiple > > times because I am using threads. > > And do you want thread local variables? no > > > How can this module access global state (not per-thread state) ? > > It needs to create a singleton. > > C global variables are global, not per-thread. Yes, but they get initialized once per-thread, therefore my singleton gets created multiple times. Simon. > > -- > Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Mar 17 09:17:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 11:17:46 -0200 Subject: finding euclidean distance,better code? References: Message-ID: En Mon, 17 Mar 2008 03:04:16 -0200, devnew at gmail.com escribi?: > while trying to write a function that processes some numpy arrays and > calculate euclidean distance ,i ended up with this code > (though i used numpy ,i believe my problem has more to do with python > coding style..so am posting it here) > > for image in range(numimgs): > distance = abs(input_wk - weights[image, :]) > if image==0: > #copy from distance to mindistance > mindistance=distance.copy() > if sum(mindistance) > sum(distance): > imgindex=image > mindistance=distance.copy() > if max(mindistance) > 0.0: > #normalise mindistance > mindistance=mindistance/(max(mindistance)+1) > dist=sum(mindistance) > > this gets me the euclidean distance value. It looks like you're rather computing a distance derived from the 1-norm (sum of coordinates; like in a city with square blocks). I'd save the sum(mindistance) value to avoid recomputing it in every iteration. > I want to know if the way i > coded it can be improved,made more compact....if someone can give > suggestions it will be a great help . The code is pretty legible as it is now. Anyway, using min() and a generator: _, imgindex = min((sum(abs(input_wk - weights[image, :])),image) for image in xrange(numimgs)) mindistance = abs(input_wk - weights[imgindex, :]) # normalize and sum again -- Gabriel Genellina From andreas.axelsson at gmail.com Mon Mar 31 11:15:10 2008 From: andreas.axelsson at gmail.com (axl) Date: Mon, 31 Mar 2008 08:15:10 -0700 (PDT) Subject: Build complete, now I just need to "install" it... References: <1adb8ead-1eb1-4f4e-a3ed-c637051f591c@b5g2000pri.googlegroups.com> Message-ID: <145effd2-c733-4f78-b79f-c0feaf660e27@s13g2000prd.googlegroups.com> On 31 Mar, 00:32, "Gabriel Genellina" wrote: > En Sun, 30 Mar 2008 12:04:10 -0300, axl ? > escribi?: > > Which changes are those? I can build Python straight from the svn sources. I upgraded the project files to VS2008 format, changed some obsolete settings, hacked distutils so it wouldn't barf on the Windows SDK 6.1 and added include paths to tcltk to the python.vsprops. I did similar changes to all the external modules, tcl, tk, bzip2, etc. This was on the 2.5.2 tarball b.t.w. I suppose I could grab the svn tip, if things have changed there, but I thought I'd start at an official "release" point. > The MSI package generation is at Tools\msi in the source tree. > There are a few preliminary steps that must be done (only once) before ? > successfully building the installer, you'll notice as you go (the script ? > will tell you what's missing; a .rc file has to be compiled, as far as I ? > remember). Would be nice if you take note of them so one can write down ? > the proper build sequence. Thanks Gabriel, for some reason I just assumed everything PC related was in the PC* folders and the docs I found don't mention the msi folder. I'll have a look there. Cheers, /axl From castironpi at gmail.com Wed Mar 5 17:16:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 5 Mar 2008 14:16:36 -0800 (PST) Subject: What is a class? References: <13su5s530rnkgfe@corp.supernews.com> Message-ID: <774470ba-dc8a-4aea-94fc-3bcf1382d57f@i29g2000prf.googlegroups.com> On Mar 5, 3:58?pm, Steven D'Aprano wrote: > On Wed, 05 Mar 2008 10:50:12 -0800, castironpi wrote: > > What is a class that is not a module? > > Er, all of them? > > I'm curious what classes you think are modules. > > -- > Steven Thank you for your time in entertaining my questions so far. Functions are first-class objects. Modules are first-class objects. Classes are first-class objects. There's even a ModuleType in 'types'. >>> set( dir(type('None',(),{})) )- set( dir( ModuleType ) ) {'__module__', '__weakref__'} How superficial are the differences? From aahz at pythoncraft.com Mon Mar 31 22:35:01 2008 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2008 19:35:01 -0700 Subject: What motivates all unpaid volunteers at Pycon? References: <7b539c8e-af4c-4409-81bc-d94e687eea59@i7g2000prf.googlegroups.com> Message-ID: In article <7b539c8e-af4c-4409-81bc-d94e687eea59 at i7g2000prf.googlegroups.com>, seberino at spawar.navy.mil wrote: > >I was impressed and humbled by all the unpaid volunteers at Pycon. What about the unpaid volunteers who weren't at PyCon? ;-) >I was wondering what motivated so many people to give so much to the >Python community. There really isn't any simple answer. Most people seem to be motivated to help out their communities, and Python certainly has a substantial community associated with it. However, that motivation plays out in different ways for each person; some people create patches for Python and others volunteer for PyCon. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From dave.brk at gmail.com Thu Mar 27 16:09:45 2008 From: dave.brk at gmail.com (dave berk) Date: Thu, 27 Mar 2008 22:09:45 +0200 Subject: Regarding __slots__ and other stuff: A couple of questions In-Reply-To: References: Message-ID: Didn't see your answer, Gabriel. Thanks, now I understand it even better. On 3/27/08, dave berk wrote: > > sorry, forget all I wrote: I should have read this more thoroughly, it > explained it all > > http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.htm > > > Descriptors > only works with type objects, not instance. and you can't write from an > instance object to a > class variable. You can only hide it. Also __slots__ works by creating descriptors in the class and preventing creation of any atrributes in the class instance, so everything is clear now > > Dave > -------------- next part -------------- An HTML attachment was scrubbed... URL: From troworld at gmail.com Wed Mar 5 01:15:29 2008 From: troworld at gmail.com (Tro) Date: Wed, 5 Mar 2008 01:15:29 -0500 Subject: Altering imported modules In-Reply-To: References: Message-ID: <200803050115.30314.troworld@gmail.com> On Tuesday 04 March 2008, Floris Bruynooghe wrote: > On Mar 1, 11:56 pm, Tro wrote: > > I'd like to know if it's possible to make tlslite load *my* asyncore > > module without changing any of the tlslite code. > > the pkgutil module might be helpful, not sure though as I've never > used it myself. > > http://blog.doughellmann.com/2008/02/pymotw-pkgutil.html is a fairly > detailed look at what pkgutil can do. Thanks, that's neat. Tro From bignose+hates-spam at benfinney.id.au Wed Mar 12 02:00:34 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 12 Mar 2008 17:00:34 +1100 Subject: best way to have enum-like identifiers? References: Message-ID: <87k5k84h31.fsf@benfinney.id.au> mh at pixar.com writes: > Currently I'm just putting this at the top of the file: > > py=1 > funcpre=2 > funcpost=3 > ... Slightly better is: py = object() funcpre = object() funcpost = object() Thus, those names are all bound to unique objects, that won't be unexpectedly duplicated by some other value. > but I'm curious if there's a better way of doing this, some kind of > enum-like thing or somesuch. Please try the 'enum' package in the Cheeseshop: -- \ ?When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic.? ?Dresden James | Ben Finney From tmp1 at viltersten.com Sat Mar 1 08:35:38 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sat, 1 Mar 2008 14:35:38 +0100 Subject: SV: SV: Running test01.py under Windows (basic level) In-Reply-To: References: <62os33F2352veU1@mid.individual.net><62pf4dF24hb4hU1@mid.individual.net> Message-ID: <62t3efF24bb0gU1@mid.individual.net> >> There will be poking around with %PATH%, i can >> tell. Never liked to do that under Windows. > > No need to do that... Create an "alias.txt" file containing: > python=c:\path\to\your\python.exe $* > Execute (once, logged as administrator): > reg add "HKLM\SOFTWARE\Microsoft\Command Processor" > /v AutoRun /t REG_SZ /d > "doskey /macrofile=path\to\your\alias.txt" > Open a new cmd console. Typing python is enough to invoke the interpreter. > Documentation for the DOSKEY command: > http://technet2.microsoft.com/WindowsServer/en/library/f7f45601-5178-48c6-9219-51bd6f7abd3f1033.mspx > > If you don't like the above recipe, create a "python.cmd" file containing: > @c:\path\to\your\python.exe %* > and save it somewhere in your PATH. It worked. Thanks! >>> have you worked out the Tutorial? >> >> Not yet. I started off using some small things. >> I tend to learn by doing. Or rather making. A >> lot of errors, that is. :) > > At least overview it. Python syntax is very clear and legible, so probably > you can figure yourself a lot of things, but there are some important > topics that you have to know and are explained in the Tutorial. It isn't > very long. Naa, reading tutorials is for idiots... You can answer my questions instead. It's not like you've got anything better to do. I bet you've read the tutorial, haven't you? (a period of awkward silence...) (a short while of WTF?!) Oh, ah! This guy was joking. Pfew... Yes, i was definitely joking here. :) I do intend to go through the tutorial and i do deeply appreciate all the help i've received/ i'll receive. If all goes the way i hope, i'll be at a new project soon and it's written in Python. Great opportunity to learn it, right? By the way - thanks! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From malkarouri at gmail.com Thu Mar 27 17:38:51 2008 From: malkarouri at gmail.com (malkarouri) Date: Thu, 27 Mar 2008 14:38:51 -0700 (PDT) Subject: SoC project: Python-Haskell bridge - request for feedback References: <7xzlslvpn5.fsf@ruckus.brouhaha.com> Message-ID: On 26 Mar, 08:46, Paul Rubin wrote: > A few thoughts. The envisioned Python-Haskell bridge would have two > directions: 1) calling Haskell code from Python; 2) calling Python > code from Haskell. The proposal spends more space on #1 but I think > #1 is both more difficult and less interesting. FWIW, I find #1 more interesting for me personally. As a monad-challenged person, I find it much easier to develop components using pure functional programming in a language like Haskell and do all my I/O in Python than having it the other way round. Of course, if it is more difficult then I wouldn't expect it from a SoC project, but that's that. Muhammad Alkarouri From tjreedy at udel.edu Thu Mar 20 22:29:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Mar 2008 22:29:05 -0400 Subject: What Programming Languages Should You Learn Next? References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com><64bugqF2anottU1@mid.uni-berlin.de><7xve3j15ya.fsf@ruckus.brouhaha.com><87fxunumqx.fsf@physik.rwth-aachen.de><7xskynm4m8.fsf@ruckus.brouhaha.com> Message-ID: "Reedick, Andrew" wrote in message news:A20311AF91C11640ACBB721DC2558B4907D2F5A7 at brexc51p... | Quicksort in Haskell versus C is amazing: | http://www.haskell.org/haskellwiki/Introduction#What.27s_good_about_functional_programming.3F Sorry, bogus comparison, and not so amazing. 1.The short doubly recursive definition of qsort has nothing to do with Haskell. 2. The Haskell code refers to an external function 'filter'. The C code inlines the filter code. If that is shoved to an external function, we get this 'amazing' (but untested ;-) C code: void qsort(int a[], int lo, int hi) { int l; if (lo < hi) { ll = partition(a, lo, hi); qsort( a, lo, ll-1 ); qsort( a, ll+1, hi ); } } The is a fair comparision, and it looks nearly as good as the Haskell code. This can also be written as a one-liner if one finds such to be more 'amazing'. The C code does not even need code for the base case. Amazing! 3. The Haskell code makes two scans of the array (one for each filter) instead of just one and makes a copy of the array (minus the pivot) in two pieces. instead of none Whether the 'slice' 'xs' makes a copy or is just a view I don't know. Then it does more allocations and copies to put the separated pieces back together. The C code does the filtering in place. Hence no need to concatenate the sorted pieces. Of course that looks more complex -- because it is -- unless hidden away in the double-filter-in-place partition function. So Haskell trades textual terseness for computation space and, probably, time. Python makes the same trade-off, and I like it and use it for that reason. One can certainly like Haskell for that reason too, but it is a trade-off. What would be amazing would be a algorithm that could rewrite the external-arrays Haskell/Python code to the equivalent of the in-place C code. Can one even write such an equivalent in Haskell? (If it is purely functional, then no, though one obviously can in Python.) For efficiency, standard C qsort code turns the second (tail) recursive call into a loop. A Python version of the same could easily eliminate the first recursive call with an explicit stack. Again, less elegant code for more speed. | Quicksort in Python inspired by Haskell's quicksort: | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473 The list slicing could be done once instead of twice. Terry Jan Reedy From jeff at schwabcenter.com Tue Mar 18 17:25:28 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 18 Mar 2008 14:25:28 -0700 Subject: ftp recursively Message-ID: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> I need to move a directory tree (~9GB) from one machine to another on the same LAN. What's the best (briefest and most portable) way to do this in Python? I see that urllib has some support for getting files by FTP, but that it has some trouble distinguishing files from directories. http://docs.python.org/lib/module-urllib.html "The code handling the FTP protocol cannot differentiate between a file and a directory." I tried it anyway, but got an authentication problem. I don't see a "how to log into the FTP server" section on docs.python.org. Is there a tutorial I should read? I am particularly looking for a quick, "good enough" solution that I can use this afternoon. Thanks in advance to any kind-hearted soul who chooses to help me out. From bj_666 at gmx.net Mon Mar 31 13:46:02 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Mar 2008 17:46:02 GMT Subject: [OT] troll poll References: Message-ID: <65cmaqF2fhuoaU1@mid.uni-berlin.de> On Mon, 31 Mar 2008 10:04:31 -0700, Daniel Fetchinson wrote: > [Heavily off-topic fun stuff] > > This is a quick poll to have scientific data on our beloved troll community: > > Whose trolling behaviour is more professional? (check one) > > [X] - Xah Lee > [ ] - castironpi He dedicates some time to write up at least comprehensible postings that make *some* sense. > More specifically, who can create a bigger mess on c.l.py? (check one) > > [ ] - Xah Lee > [X] - castironpi Xah Lee's postings might be trolls but sometimes they spark some really interesting and serious subthreads, while the nonsense of castironpi is just irritating noise. > More specifically, who is more entertaining? (check one or none) > > [X] - Xah Lee > [ ] - castironpi Castironpibot becomes boring very quickly. Especially when it starts to answer its own posts. Ciao, Marc 'BlackJack' Rintsch From arnodel at googlemail.com Thu Mar 13 16:14:04 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 13 Mar 2008 13:14:04 -0700 (PDT) Subject: Python regex References: Message-ID: <9e9cfd5e-72e6-4033-bc9f-b089ec8fd95c@i29g2000prf.googlegroups.com> On Mar 13, 8:03?pm, "Andrew Rekdal" <@comcast.net> wrote: > I hope posting is ok here for this question... > > I am attempting to extract the text from a CSS comment using 're' such as... > > string = "/* CSS comment /*" > exp = "[^(/*)].*[^(*/)] " > > p = re.compile(exp) > q = p.search(string) > r = q.group() > > print r > > >>CSS comment > > although this works to a degree... I know the within the brackets everything > is taken literally so the pattern > I am to negating is "(/*)". ie. includes the parenthesis. > > So my question is... > > Is there a way to negate a pattern that is more than on character long? eg. > where rather than saying if forward slash OR astrisk appear..negate. > > I would be saying if parenthesis AND asterisk appear in this order... negate > > -- Andrew There would be many ways to do this. One: >>> import re >>> r = re.compile(r'/\*(.*?)\*/') >>> tst = '.a { color: 0xAACC66; /* Fav color */ }' >>> m = r.search(tst) >>> m.group(1) ' Fav color ' >>> HTH -- Arnaud From hberig at gmail.com Sun Mar 23 21:33:25 2008 From: hberig at gmail.com (hberig) Date: Sun, 23 Mar 2008 18:33:25 -0700 (PDT) Subject: python + olap Message-ID: Hi, I'm looking for python olap applications or frameworks, integrable to a web server application (like turbo gears or other) or some gui (like qt, wxwidgets or other). Any suggestion?? Thanks in advance!! From hexusnexus at gmail.com Mon Mar 31 21:22:49 2008 From: hexusnexus at gmail.com (hexusnexus at gmail.com) Date: Mon, 31 Mar 2008 18:22:49 -0700 (PDT) Subject: Stuck in a loop Message-ID: I wrote a simple algorithm and it keeps getting stuck in a loop. I guess I'm just to tired to figure it out: compcount=[5,4,2,2] suitrank=[0,0,0,0] trump=2 l,lt=0,0 while l<4: while lt<4: if l==trump: l+=1 if l>3: break if lt==trump: lt+=1 if compcount[l] <5330bd900803221452u567f4a40pe3dcc5bd24e00327@mail.gmail.com> Message-ID: <1npcu3p9hig3gm94mskfoksk9p43p8h2jm@4ax.com> On Sat, 22 Mar 2008 23:29:10 +0100, Christian Heimes wrote: >Matthias G?tz schrieb: >> So can you tell me what's the purpose of Complex.py, >> >> and where can i find the semantic i'am looking for. > >Well, the file is in the Demo folder. It's just a demo how to implement >a naive complex type in Python. > >Why do you think the power of a complex to a complex is not defined? >Raising a complex to a complex power is well defined, Really? One of the problems that used to show up on the master's exams aroung here was to find all the possible values of i**i. >although the >mathematical proof isn't trivial. You have to use the Euler form. Erm, the problem is that the Euler form of a complex number is not well-defined (_unless_ you specify that the argument is between -pi and pi). For example, i = exp(i pi/2) and also i = exp(i 5*pi/2); those two "forms" give different values for i**i. You might say that a complex power of an Euler form for a complex number is well-defined. If you do specify that -pi < argument <= pi, ie you consider the principal-value logarithm, then you get exactly one z**w. But that's not always the z**w that you need for your problem... >Ask >Google for some examples Thanks. >Christian David C. Ullrich From fetchinson at googlemail.com Mon Mar 10 21:05:12 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 18:05:12 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > Thanks for the info! SIFT really looks like a heavy weight solution, > > but do you think the whole concept can be simplified if all I needed > > was: given a photo, find similar ones? I mean SIFT first detects > > objects on the image and find similarities, but I don't need the > > detection part at all, all I care about is similarity for the whole > > photo. I surely don't understand the big picture fully but just have > > the general feeling that SIFT and other expert tools are an overkill > > for me and a simplified version would be just as good with a much more > > easily comprehensible core algorithm. > > Please describe the kind of photos you are dealing with. Are they > identical photos, in say different formats or with different metadata? > Or are they rescaled images? Or maybe they are the same photo cropped > differently? The photos are just coming straight from my digital camera. Same format (JPEG), varying size (6-10 megapixel) and I would like to be able to pick one and then query the database for similar ones. For example: I pick a photo which is more or less a portrait of someone, the query should return other photos with more or less portraits. If I pick a landscape with lot of green and a mountain the query should result in other nature (mostly green) photos. Something along these lines, of course the matches won't be perfect because I'm looking for a simple algorithm, but something along these lines. > SIFT will work in more or less the process you described in your first > post. It basically calculates the N sets of numbers for each image, > representing the unique features of that image and their relative > positions. The rest of the process if up to you. You have to compare the > different sets of numbers to find the image with the minimal difference, > as opposed to comparing the whole image. Great, this sounds very good, I'll give SIFT a try (at least trying to understand the basic concepts) although at the moment it looks a bit scary :) From alex.borgert at gmail.com Mon Mar 31 04:37:37 2008 From: alex.borgert at gmail.com (Artmi) Date: Mon, 31 Mar 2008 01:37:37 -0700 (PDT) Subject: Beginner advice References: <65bfk7F2esfc1U1@mid.uni-berlin.de> Message-ID: <2ba28546-92cd-4cfe-be5e-15a5a5f01f3a@c19g2000prf.googlegroups.com> On Mar 31, 9:15 am, Paul Scott wrote: > On Mon, 2008-03-31 at 06:45 +0000, Marc 'BlackJack' Rintsch wrote: > > There is an `xmlrpclib` in the standard library, so there is no need for > > an external package here. I even think that pyXMLRPClib is the one that's > > integrated in the standard library, so the external one might be "dead". > > Ah, yes it is indeed. Thanks. > > > For Windows there are tools to bundle your source and all dependencies and > > even the interpreter itself. `py2exe` is such a tool. With InnoSetup or > > NSIS or similar programs you can then make a `setup.exe` for that spoiled > > Windows brats. :-) > > > Under Linux many packages are available as distribution specific packages > > on most distributions. So for Linux you may get away with a README > > stating the dependencies of your program and a `setup.py` for installing > > your project. Look for `distutils` in the Python documentation for > > further information about `setup.py`\s. > > setup.py sounds like the best way to go. Most of the classrooms and > lecture halls run on Ubuntu machines, and as I said, I don't really care > much for the Windows brats anyway. 'doze installers etc would be a nice > to have, but not needed right now. > > > > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? > > > Use the one you like best. ;-) > > Thought as much. I do 90% of my coding in vi anyways, but am still > getting a couple of nutty errors from Python simply because I have not > yet gotten the hang of significant whitespace :) Darn that PHP! > > Thanks for the feedback, now I just need some justification on the > GTK/GUI stuff - wxWidgets, GTK+ Glade or other? > > --Paul > > All Email originating from UWC is covered by disclaimerhttp://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm I myself prefer wxPython(wxWidgets wrapper for python), it's more "Object Oriented" then, say GTK. But really, just check out their homepages to see features they include, and go by that instead. From deets at nospam.web.de Thu Mar 27 05:32:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Mar 2008 10:32:07 +0100 Subject: Partial Function Application and implicit self problem References: <47EB58B5.1020801@mydeskfriend.com> Message-ID: <6517tiF2e0id5U1@mid.uni-berlin.de> Gabriel Rossetti wrote: > > Gabriel Rossetti wrote: >> Hello, >> >> I am using Partial Function Application in a class and I've come up with >> a problem, when the method is called it tries to pass "self" to the >> curried/partial function, but this should be the first argument in >> reality, but since the function is curried, then the self gets passed as >> the second argument. Here is the code : >> >> def __registerService(self, atomic, service): >> def reg(service): >> # registers the service >> ... >> >> if(atomic): >> # Lock the service dict and register the service, then unlock it >> self.__mutex.lock(reg, service) >> self.__mutex.unlock() >> else: >> reg(service) >> >> registerServiceAtomic = partial(__registerService, True) >> registerServiceNonAtomic = partial(__registerService, False) >> >> I should pass self when applying partial, but then I can't do that since >> self is not available there. Does anyone have any ideas? >> >> Thanks, >> Gabriel >> > I also tried this : > > def __registerService(atomic, self, service): > def reg(service): > # registers the service > ... > > if(atomic): > # Lock the service dict and register the service, then unlock it > self.__mutex.lock(reg, service) > self.__mutex.unlock() > else: > reg(service) > > registerServiceAtomic = partial(__registerService, True) > registerServiceNonAtomic = partial(__registerService, False) > > thinking that the self will be passed as the first argument of the > registerService* calls and thus the second argument to the > curried/partial method, but it doesn't work either, I get : > > Traceback (most recent call last): > File "/home/xxx/Documents/Code/Python/test/test_serv.py", line 245, in > test_registeration > self.f.registerServiceAtomic(self.serv) > exceptions.TypeError: __registerService() takes exactly 3 arguments (2 > given) First, passing self not as first argument is not going to work, and a HUGE design flaw anyway: even IF it would work, it would mean that you *must* use partial to bind default-arguments before invoking a method. And it goes to much against the design of python. Apart from that, please post self-contained examples that produce the error. the above code is hard to grasp because it's unclear which is called from where with what. Diez From malkarouri at gmail.com Sat Mar 8 11:20:24 2008 From: malkarouri at gmail.com (malkarouri) Date: Sat, 8 Mar 2008 08:20:24 -0800 (PST) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <4298be09-e8b7-4d67-a0f4-59a2b34bfd49@f47g2000hsd.googlegroups.com> On Mar 8, 3:52?pm, duncan smith wrote: > malkarouri wrote: > > Hi everyone, > > > I have an algorithm in which I need to use a loop over a queue on > > which I push values within the loop, sort of: > > > while not(q.empty()): > > ? ? x = q.get() > > ? ? #process x to get zero or more y's > > ? ? #for each y: > > ? ? q.put(y) > > > The easiest thing I can do is use a list as a queue and a normal for > > loop: > > > q = [a, b, c] > > > for x in q: > > ? ? #process x to get zero or more y's > > ? ? q.append(y) > > > It makes me feel kind of uncomfortable, though it seems to work. The > > question is: is it guaranteed to work, or does Python expect that you > > wouldn't change the list in the loop? > > I have used exactly the same approach. ?I think it's a clean (even > elegant) solution. ?I'd be surprised if it ceased to work in some future > implementation of Python, but I don't know if that's absolutely guaranteed. > > Duncan Thanks Duncan, I think I will go ahead and use it. Though the Python tutorial says otherwise in section 4.2: "It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.". More explicitly, in 7.3 of the Python Reference Manual: "Warning: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop." This can be interpreted as don't play with the past. However, the part "When this counter has reached the length of the sequence the loop terminates." is interpretable as either the starting sequence length or the running sequence length. Testing: In [89]: x=range(4) In [90]: for i in x: ....: print i ....: x.append(i+4) ....: if i>=8:break ....: ....: 0 1 2 3 4 5 6 7 8 So it is the running sequence length. But I am still not sure if that is guaranteed. Regards, Muhammad Alkarouri From spam at ecp.cc Wed Mar 19 18:27:24 2008 From: spam at ecp.cc (dsavitsk) Date: Wed, 19 Mar 2008 17:27:24 -0500 Subject: ADO error - large data set References: <475c155d-fe16-472f-a4f8-363f6db339eb@d21g2000prf.googlegroups.com> Message-ID: <9qgEj.4646$6H.3740@newssvr22.news.prodigy.net> Is it possible there is some bad data in the larger db? This is asinine, but maybe write a small script that adds some data, then opens and closes the db, then repeats this. If this is a size issue, then you can at least narrow it down to where the size limit is? And, if it isn't you should be able to figure that out, too. Otherwise, play around with the locking and cursor options. -d "Gyula" wrote in message news:475c155d-fe16-472f-a4f8-363f6db339eb at d21g2000prf.googlegroups.com... > Hi there, > > I have been running Python to tap into an MS Access 2003 database > using ADO (PythonWin+COM). Everything works great creating recordsets > etc. when I open a table with a small number of records. However, when > I try to run the same Python code with a large table (>100,000) I get: > > Traceback (most recent call last): > File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework > \scriptutils.py", line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Documents and Settings\user\Desktop\PythonWS\scripts > \readmsaccess.py", line 43, in > rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3) > File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C- > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open > , ActiveConnection, CursorType, LockType, Options) > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, > 5003251, -2147467259), None) > > The small and large table structures are identical, all I do is change > the tblname from input1000 (1000 records) to input (>100000 records). > I use optimistic locking and keyset cursor..nothing out of the > ordinary? > > Any ideas? ADO 2.8 is what I am using. > > Thanks a lot! > GG From justjpm at aol.com Thu Mar 20 13:26:14 2008 From: justjpm at aol.com (Jim) Date: Thu, 20 Mar 2008 10:26:14 -0700 (PDT) Subject: URLError References: <61fd31d2-259c-4a2e-80ab-1c181f9a8f78@k13g2000hse.googlegroups.com> <13u3660kfnhq412@corp.supernews.com> Message-ID: <74cdd195-2bfa-4548-a16e-bf14c6b07b50@p73g2000hsd.googlegroups.com> On Mar 19, 6:50 pm, Steven D'Aprano wrote: > On Wed, 19 Mar 2008 14:45:39 -0700, Jim wrote: > > Program randomly aborts when looking up url. The program loop thru > > 4000+ records looking > > up ID via internet and returnshtmlcode which is used in subsequent > > processing. The code > > for looking-up record is below followed by abort details. Can anyone > > help with catching the > > abort before program aborts or provide code to automatically start > > program? > > Yes. Wrap the offending code with a try...except loop, something similar > to this. > > try: > contents = urllib2.urlopen(url).read() > except URLError, e: > if e.errno == 10053: > # "Software caused connection abort" > response = raw_input( > "Temporary failure, Skip/Halt/try Again?") > response = response.lower().strip() > if response in ('h', 'halt'): > break > elif response in ('a', 'again', 't', 'try', 'try again'): > continue > elif response in ('', 's', 'skip'): > lines -= 1 > continue > else: > print "Unknown response, boo hiss to you!" > raise > > -- > Steven Thanks Steven for recommendation. The program is my first and I'm not a programmer so it will take me some time to get your recommendation to work. So far the program runs after I added code based on your example but the program still aborts and none of the code ("Temporary failure, Skip/Halt/try Again?" or "Unknown response, boo hiss to you!") in your example is displayed. It appears to abort in the imported module "urllib2" which is open source. The code in urllib2 is way over my skill level. Jim From code at pizzashack.org Mon Mar 24 17:58:42 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Mar 2008 17:58:42 -0400 Subject: Python 2.2.1 and select() Message-ID: <20080324215842.GE26870@dragontoe.org> Hi kids! I've got some code that uses select.select() to capture all the output of a subprocess (both stdout and stderr, see below). This code works as expected on a variety of Fedora systems running Python > 2.4.0, but on a Debian Sarge system running Python 2.2.1 it's a no-go. I'm thinking this is a bug in that particular version of Python, but I'd like to have confirmation if anyone can provide it. The behavior I see is this: the call to select() returns: [] [] [] If and only if the total amount of output is greater than the specified buffer size, then reading on this file hangs indefinitely. For what it's worth, the program whose output I need to capture with this generates about 17k of output to STDERR, and about 1k of output to STDOUT, at essentially random intervals. But I also ran it with a test shell script that generates roughly the same amount of output to each file object, alternating between STDOUT and STDERR, with the same results. Yes, I'm aware that this version of Python is quite old, but I don't have a great deal of control over that (though if this is indeed a python bug, as opposed to a problem with my implementation, it might provide some leverage to get it upgraded)... Thanks in advance for any help you can provide. The code in question (quite short) follows: def capture(cmd): buffsize = 8192 inlist = [] inbuf = "" errbuf = "" io = popen2.Popen3(cmd, True, buffsize) inlist.append(io.fromchild) inlist.append(io.childerr) while True: ins, outs, excepts = select.select(inlist, [], []) for i in ins: x = i.read() if not x: inlist.remove(i) else: if i == io.fromchild: inbuf += x if i == io.childerr: errbuf += x if not inlist: break if io.wait(): raise FailedExitStatus, errbuf return (inbuf, errbuf) If anyone would like, I could also provide a shell script and a main program one could use to test this function... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From aisaac at american.edu Thu Mar 13 12:38:33 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 13 Mar 2008 16:38:33 GMT Subject: no more comparisons In-Reply-To: <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com> <7xy78neffb.fsf@ruckus.brouhaha.com> <88d79a8d-2484-45a7-8d95-556629bc2774@s37g2000prg.googlegroups.com> Message-ID: Dan Bishop wrote: > def cmp_key(cmp_fn): > class CmpWrapper(object): > def __init__(self, obj): > self.obj = obj > def __cmp__(self, other): > return cmp_fn(self.obj, other.obj) > return CmpWrapper Apparently I'm overlooking something obvious ... how is this supposed to work if __cmp__ is no longer being called? (Which was my understanding.) Thank you, Alan Isaac From emailamit at gmail.com Mon Mar 31 17:53:17 2008 From: emailamit at gmail.com (Amit Gupta) Date: Mon, 31 Mar 2008 14:53:17 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> <41b598ef-c422-417f-9a77-b48eff8e6334@s37g2000prg.googlegroups.com> Message-ID: On Mar 31, 1:52 pm, Mike Driscoll wrote: > > What about creating a setup.py and using the distutils command to > build rpms or tarballs? > > http://docs.python.org/dist/built-dist.html > > Mike My quick look: The link you sent is under the header "Distributing Python Modules". In my case, I have set of python-files that altogether is part of one product-functionality. I would like to package it and have it run standalone, even if the user does not have python installed. Ok, I guess build-dist can possibly achieve the same purpose (without reading through the link you sent). So my question would be: why is there pyinstaller, if this does the job. Is build-dist more low-level and thus is over-kill for the kind of application I am looking for?: Thanks From pianomaestro at gmail.com Fri Mar 28 11:41:16 2008 From: pianomaestro at gmail.com (pianomaestro at gmail.com) Date: Fri, 28 Mar 2008 08:41:16 -0700 (PDT) Subject: threads and extension module initialization References: <8595543a-cf01-4a16-ad5d-d709001974a4@8g2000hsu.googlegroups.com> Message-ID: <29a52f2a-c344-4405-be0c-b0a18503c1ee@59g2000hsb.googlegroups.com> On Mar 28, 11:14 am, "Gabriel Genellina" wrote: > C global variables are global, not per-thread. aha, a static pointer gets initialized to NULL, so I can check if it's not NULL in the module initializer. Thanks for jogging my brain, Simon. > > -- > Gabriel Genellina From mail at timgolden.me.uk Tue Mar 25 12:09:17 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Mar 2008 16:09:17 +0000 Subject: Reading new mail from outlook using Python In-Reply-To: <971720.4797.qm@web50104.mail.re2.yahoo.com> References: <971720.4797.qm@web50104.mail.re2.yahoo.com> Message-ID: <47E923AD.80803@timgolden.me.uk> SPJ wrote: > Thanks... > > I could access the folders in outlook express using the COM interface. > Now I am stuck with how to read to a file only new mails. Well, this Google query: http://www.google.co.uk/search?hl=en&q=OUTLOOK.application+unread+messages seems to indicate some useful hits. (But perhaps you knew that?) TJG From tmp1 at viltersten.com Fri Mar 7 09:56:44 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 7 Mar 2008 15:56:44 +0100 Subject: Quit-command not quiting Message-ID: <63d2efF271u6hU1@mid.individual.net> I entered the code from tkinter.pdf, section 2 but for reason, the application doesn't close as i press the quit-button. The wondow itself vanishes if i click the cross in the upper-right corner but pressing the quit-button only makes it "pressed". Then, the program freezes. This is the code. from Tkinter import * class Demo (Frame): def __init__ (self, master = None): Frame.__init__ (self, master) self.grid () self.doLayout () def doLayout (self): self.quitButton = Button ( self, text = "Quit", command = self.quit) self.quitButton.grid () d = Demo () d.master.title ("the coolest demo ever") d.mainloop () -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From arbo.newmedia at gmail.com Wed Mar 5 05:45:36 2008 From: arbo.newmedia at gmail.com (arbo.newmedia at gmail.com) Date: Wed, 5 Mar 2008 02:45:36 -0800 (PST) Subject: Leopard and MySQL Message-ID: Hi, can anyone help me with MySQL. I've got Mac OSX Leopard and I'm trying to install MySQLdb for Python. I'm running build and it goes withous any errors and install. But when I'm typing : import MySQLdb in IDLE I've got this: Traceback (most recent call last): File "", line 1, in import MySQLdb File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line 19, in File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/lisek/.python-eggs/MySQL_python-1.2.2-py2.5- macosx-10.3-fat.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/lisek/.python-eggs/MySQL_python-1.2.2-py2.5- macosx-10.3-fat.egg-tmp/_mysql.so Expected in: dynamic lookup And I don't know what is wrong... ;/ From diljeet_kr at yahoo.com Mon Mar 10 00:02:34 2008 From: diljeet_kr at yahoo.com (diljeet kaur) Date: Sun, 9 Mar 2008 21:02:34 -0700 (PDT) Subject: removing escape character Message-ID: <448738.13250.qm@web52806.mail.re2.yahoo.com> hi i am working on pyqt environment when i write to file, i get some unwanted characters like "ESC" in file how to get rid of these characters? --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From edreamleo at charter.net Fri Mar 28 11:04:55 2008 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 28 Mar 2008 10:04:55 -0500 Subject: ANN: Leo 4.4.8 b3 released Message-ID: Leo 4.4.8 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This version features a new ipython plugin that provides a two-way bridge between Leo and IPython. See http://webpages.charter.net/edreamleo/IPythonBridge.html Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.8: ---------------------------- - Leo's source code is now managed by bzr: see link below. - Leo's discussion is now hosted by Google Groups: see link below. - Arguments to g.es and g.es_print can be translated using gettext. - Completed ILeo: a bridge between IPython and Leo. See http://webpages.charter.net/edreamleo/IPythonBridge.html - Minibuffer commands may have arguments. - @menu trees can now refer to commands created by @command and @button nodes. - Added support for common @commands nodes in settings files. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jim.vickroy at noaa.gov Tue Mar 25 14:13:47 2008 From: jim.vickroy at noaa.gov (j vickroy) Date: Tue, 25 Mar 2008 12:13:47 -0600 Subject: how to dynamically create class methods ? In-Reply-To: References: <000c01c88e88$96c29490$0600a8c0@laptop> Message-ID: Hello, Here is some pseudo-code that hopefully illustrates what I want to do: records = list(...) for record in records: new_fcn = define_a function_for(record) instance = my_new_class_instance() setattr(instance, 'myfcn', new_fcn) instance.execute() # instance.execute() calls instance.myfcn(*args) I have looked at some of the functions in the *new* module and new.code(...), new.function(...), and new.instancemethod(...) appear to do what I want, but I do not know how to use new.code() and new.function() -- specifically what its *global* parameter should be. I was not able to find helpful information using Google. Thanks for any suggestions on how to approach this. -- jv From tmp1 at viltersten.com Sun Mar 9 12:10:56 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 17:10:56 +0100 Subject: Changing the size of a Button Message-ID: <63ifhtF277va7U1@mid.individual.net> How do i change the size of a Button (using Tkinter), other than to set it during construction? I've found methods for getting the size but not applying them. I've been laborating with .setvar(*) but i've been unsuccessful. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From mcepl at redhat.com Tue Mar 4 17:18:10 2008 From: mcepl at redhat.com (Matej Cepl) Date: Tue, 04 Mar 2008 23:18:10 +0100 Subject: Edit MP4 and/or WMV file metadata? Message-ID: <2eu0a5xpji.ln2@ppp1053.in.ipex.cz> On 2008-03-04, 18:53 GMT, allen.fowler wrote: > 1) Is there a python module I can use to edit the metadata in > MP4 > files? I am not sure whether taglib supports MP4, but take a look at http://developer.kde.org/~wheeler/taglib.html and http://developer.berlios.de/project/showfiles.php?group_id=2066 or http://news.tiker.net/software/tagpy > 2) Failing that, is there a python module I can use to edit the > metadata in the WMV files, and hope the data makes it through the > conversion? You may also be able to do something with gst-launch (on Linux). Mat?j From google at mrabarnett.plus.com Fri Mar 21 14:11:07 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 21 Mar 2008 11:11:07 -0700 (PDT) Subject: Is this doable References: <6fd94bf6-8b89-40f2-a43e-7f8cb56d86e2@s50g2000hsb.googlegroups.com> Message-ID: <128011dd-a1a8-43af-bdea-beba452aa596@f63g2000hsf.googlegroups.com> On Mar 21, 11:48 am, fkallgren wrote: > Hi. > > I have a little problem. I have a script that is in the scheduler > (win32). But every now and then I update this script and I dont want > to go to every computer and update it. So now I want the program to 1) > check for new version of the script, 2) if there is a new version, > copy that verision from server to local drive, 3) shutdown the program > and start it up again as the new version. > > The problem is that I can't run this script directly from server so it > have to run it locally. > > Anyone having any bright ideas?? > The script could just check to see if the version on the server is more recent and if it is then copy it over the local one, start the local one, and then quit. Python compiles the script to bytecode and then interprets the bytecode, so when the script is being run the .py or .pyw source itself isn't being used and can be overwritten. I've tried the following on Windows XP and it works: import os import sys import shutil # Is there a newer version? my_path = sys.argv[0] update_path = os.path.join(os.path.dirname(my_path), "new_script.py") if os.path.getmtime(my_path) < os.path.getmtime(update_path): # Update the script. shutil.copy2(update_path, my_path) # Re-start the script. os.startfile(my_path) sys.exit() # The rest of the script... From duncan.booth at invalid.invalid Mon Mar 17 16:31:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Mar 2008 20:31:45 GMT Subject: Immutable and Mutable Types References: <654fc15f5eb98ca5651a2450cf0@news.aioe.org> <13tst1388cp67d8@corp.supernews.com> Message-ID: Matthew Woodcraft wrote: > In article , > Duncan Booth wrote: >> I don't have a copy of 1.4 to check so I'll believe you, but you can >> certainly get the output I asked for with much more recent versions. > >> For the answer I actually want each asterisk substitutes for exactly >> one character. > > Then I'll guess you're looking for something like '0==0', with Python > 2.2 or so (so that you'd get the PyTrue object). > Yes, that was the answer I was looking for: CPython 1.5.x (or maybe earlier?) to 2.2.x without a bool type but separate values for true and false (as used by PyWin). Also it seems that Jython 2.2.1 (and probably other versions) behaves the same way. I'm intrigued though by Stargaming's answer with 1//1, I must look into that one. From erikwickstrom at gmail.com Tue Mar 25 16:13:13 2008 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 25 Mar 2008 13:13:13 -0700 (PDT) Subject: "Soup Strainer" for ElementSoup? References: <0cfba6cf-57ff-449f-9c68-704f5325893e@m36g2000hse.googlegroups.com> <47e87a88$0$36376$742ec2ed@news.sonic.net> Message-ID: <36dd9bf7-c038-4105-bb6a-de2f339a457a@m3g2000hsc.googlegroups.com> On Mar 25, 12:17 am, John Nagle wrote: > erikcwwrote: > > Hi all, > > > I was reading in the Beautiful Soup documentation that you should use > > a "Soup Strainer" object to keep memory usage down. > > > Since I'm already using Element Tree elsewhere in the project, I > > figured it would make sense to use ElementSoup to keep the api > > consistent. (and cElementTree should be faster right??). > > > I can't seem to figure out how to pass ElementSoup a "soup strainer" > > though. > > > Any ideas? > > > Also - do I need to use the extract() method with ElementSoup like I > > do with Beautiful Soup to keep garbage collection working? > > > Thanks! > > Erik > > I really should get my version of BeautifulSoup merged back into > the mainstream. I have one that's been modified to use weak pointers > for all "up" and "left" links, which makes the graph cycle free. So > the memory is recovered by reference count update as soon as you > let go of the head of the tree. That helps with the garbage problem. > > What are you parsing? If you're parsing well-formed XML, > BeautifulSoup is overkill. If you're parsing real-world HTML, > ElementTree is too brittle. > > John Nagle I'm parsing real-world HTML with BeautifulSoup and XML with cElementTree. I'm guessing that the only benefit to using ElementSoup is that I'll have one less API to keep track of, right? Or are there memory benefits in converting the Soup object to an ElementTree? Any idea about using a Soup Strainer with ElementSoup? Thanks! From sturlamolden at yahoo.no Tue Mar 18 17:25:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 14:25:12 -0700 (PDT) Subject: finding items that occur more than once in a list References: Message-ID: <1b1fe71d-4e8e-4b37-a6fc-471f0a5c6564@h11g2000prf.googlegroups.com> On 18 Mar, 22:22, sturlamolden wrote: > def nonunique(lst): > slst = sorted(lst) > return list(set([s[0] for s in > filter(lambda t : not(t[0]-t[1]), zip(slst[:-1],slst[1:]))])) Or perhaps better: def nonunique(lst): slst = sorted(lst) return list(set([s[0] for s in filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))])) From xkenneth at gmail.com Sun Mar 9 17:28:13 2008 From: xkenneth at gmail.com (xkenneth) Date: Sun, 9 Mar 2008 14:28:13 -0700 (PDT) Subject: Logically/Selectively Sub Class? Message-ID: Might be a silly question, but is it possible to selectively subclass, IE subclass is a supporting module is present and not otherwise. Regards, Kenneth Miller From Wayne.Oosthuizen at gmail.com Sat Mar 29 04:46:33 2008 From: Wayne.Oosthuizen at gmail.com (Constantly Distracted) Date: Sat, 29 Mar 2008 01:46:33 -0700 (PDT) Subject: Setting the value of one cell in QTableWidget fills everything. References: <6cf08ae2-28f2-44a0-96a7-69aaa56c9672@e10g2000prf.googlegroups.com> Message-ID: <851bdc24-6308-47ca-9d8d-cb31db41ce02@x41g2000hsb.googlegroups.com> > Move the creation of the QTableWidgetItem() to the inner loop (and call > it "item" rather than "items"). > > Phil Thanks, that works perfectly. From amca01 at gmail.com Sat Mar 8 18:11:53 2008 From: amca01 at gmail.com (Alasdair) Date: Sun, 09 Mar 2008 10:11:53 +1100 Subject: Arbitrary precision integer arithmetic: ceiling? Message-ID: I need to apply the ceiling function to arbitrary sized (long) integers. However, division automatically returns the type of its operands, so that, for example: math.ceil(7/4) returns 1. I can use float, as in: math.ceil(7/float(4)), except that for very large integers float causes an unacceptable loss of precision. What is the best way of finding a ceiling of a quotient of arbitrary sized integers? Thanks, Alasdair From gh at ghaering.de Wed Mar 19 03:43:23 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 19 Mar 2008 08:43:23 +0100 Subject: What Programming Languages Should You Learn Next? In-Reply-To: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> Message-ID: <64bugqF2anottU1@mid.uni-berlin.de> wesley chun wrote: > http://it.slashdot.org/it/08/03/18/1633229.shtml > > it was surprising and disappointing that Python was not mentioned > *anywhere* in that article [...] Probably because Ruby is all hot and sexy nowadays ;-) Though it's remarkably close to Python, apparently. So close that I couldn't be bothered to learn it. In fact, for me personally, Python was about the last programming language I learnt out of intrinsic motivation. I tried to take a look at functional langugages like Haskell and Erlang, but I tend to quickly get bored of toy examples and can learn best if I can apply a new language to a real problem that it can solve better than the other languages I know. Haven't found that killer problem so far ... -- Gerhard From pradiprai at gmail.com Mon Mar 17 03:21:01 2008 From: pradiprai at gmail.com (Pradeep Rai) Date: Mon, 17 Mar 2008 12:51:01 +0530 Subject: Urgent : How to do memory leaks detection in python ? Message-ID: Thanks for your inputs !!! I have installed python v 2.5 on my Linux machine and executing the tool again. I would like to share the memory status( using free -m command ) before and after the execution of the tool. BEFORE EXECUTION ================ total used free shared buffers cached Mem: 1006 148 *858* 0 8 92 -/+ buffers/cache: 46 960 Swap: 2047 0 2047 AFTER EXECUTION =============== total used free shared buffers cached Mem: 1006 940 *66* 0 49 846 -/+ buffers/cache: 44 962 Swap: 2047 0 2047 I am unable to find out why *66 MB* system memory is left after tool execution ? If python does not have memory leaks then where this memory is going ? I have explored few urls (as given below) related to memory leak in python : http://www.nightmare.com/medusa/memory-leaks.html http://mail.python.org/pipermail/tutor/1999-April/000162.html Please comment !!! -----Original Message----- *From:* python-list-bounces+pradiprai=gmail.com at python.org [mailto: python-list-bounces+pradiprai=gmail.com at python.org] *On Behalf Of *tsuraan *Sent:* 16 March 2008 8:27 AM *To:* python-list at python.org *Subject:* Re: Urgent : How to do memory leaks detection in python ? > Python doesn't have memory leaks. Yeah, interesting bit of trivia: python is the world's only non-trivial program that's totally free of bugs. Pretty exciting! But seriously, python 2.4, at least, does have some pretty trivially exposed memory leaks when working with strings. A simple example is this: >>> letters = [chr(c) for c in range(ord('a'), ord('z'))+range(ord('A'), ord('Z'))] >>> ary = [] >>> for a in letters: ... for b in letters: ... for c in letters: ... for d in letters: ... ary.append(a+b+c+d) ... >>> del(ary) >>> import gc >>> gc.collect() 0 The VM's memory usage will never drop from its high point of (on my computer) ~200MB. Since you're using GIS data, this could be what you're running into. I haven't been able to upgrade my systems to python 2.5, but from my tests, that version did not have that memory leak. Nobody seems interesting in backporting fixes from 2.5 to 2.4, so you're probably on your own in that case as well, if upgrading to python 2.5 isn't an option or isn't applicable to your situation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Afro.Systems at gmail.com Tue Mar 25 08:30:59 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Tue, 25 Mar 2008 05:30:59 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> <534cd01c-3d49-4dd8-ba04-71551cdd46d3@d21g2000prf.googlegroups.com> Message-ID: <1396c034-3f07-4991-96a8-09b44e1929cd@e23g2000prf.googlegroups.com> On Mar 25, 2:00?pm, John Machin wrote: > On Mar 25, 10:44 pm, Tzury Bar Yochay wrote: > > > > > given two classes: > > > class Foo(object): > > ? ? def __init__(self): > > ? ? ? ? self.id = 1 > > > ? ? def getid(self): > > ? ? ? ? return self.id > > > class FooSon(Foo): > > ? ? def __init__(self): > > ? ? ? ? Foo.__init__(self) > > ? ? ? ? self.id = 2 > > > ? ? def getid(self): > > ? ? ? ? a = Foo.getid() > > ? ? ? ? b = self.id > > ? ? ? ? return '%d.%d' % (a,b) > > > While my intention is to get 1.2 I get 2.2 > > I would like to know what would be the right way to yield the expected > > results > > Post the code that you actually executed. What you have shown lacks > the code to execute it ... but the execution will fail anyway: > > ? ? a = Foo.getid() > TypeError: unbound method getid() must be called with Foo instance as > first argument (got nothing instead) sorry, it should have been: a = Foo.getid(self) instead of a = Foo.getid() From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 16:52:36 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 21:52:36 -0000 Subject: Better grammar.txt References: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> <3d881a310803061019r6ef2c3c8tcd868da3671afe73@mail.gmail.com> Message-ID: <13t3e944k9p7tf0@corp.supernews.com> On Fri, 07 Mar 2008 13:42:56 -0800, MartinRinehart wrote: > Jeroen Ruigrok van der Werven wrote: >> >http://www.martinrinehart.com/articles/python-grammar.html: Unknown >> >host www.martinrinehart.com >> >> Works for me. > > Very interesting. The link I posted works for me, while the links quoted > are 404 errors, though they look identical. This really is a superior > version of the EBNF, so I wish it would work for everyone. Any ideas? I get 404. Perhaps you need to move this discussion to a mailing list for web admins, rather than Python developers? What I know about hosting a web site I could engrave on a poppy seed. In letters ten feet high. Doesn't mean I won't express an opinion though :) Perhaps it works for you because you are inside your firewall, rather than outside it? Also, I would be concerned that some people (one person?) is reporting an Unknown Host error. Who is your domain registrar? -- Steven From gagsl-py2 at yahoo.com.ar Sun Mar 30 05:10:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 06:10:12 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> <5f067c48-e6d4-405b-a064-70b26f8b0343@m71g2000hse.googlegroups.com> Message-ID: En Sun, 30 Mar 2008 05:08:34 -0300, escribi?: > On Mar 29, 12:41 pm, Steven D'Aprano cybersource.com.au> wrote: >> Since you jump to an invalid conclusion about !=, the rest of your >> argument fails. > > No, you said <= could be confusing, but we're talking about <> here, > and there is no confusion about that :). Yes, there is: <> looks like "less or greater", and being equal or not is a different thing that being less or greater. Trichotomy law holds for real numbers (although some people don't even accept that) but not for floating point (NANs); and Python isn't about numbers only. For a lot of objects it makes sense to compare them for equality or not, but you can't say which one is greater than the other (the weather forecast, books in a bookstore) -- Gabriel Genellina From __peter__ at web.de Wed Mar 19 17:11:26 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Mar 2008 22:11:26 +0100 Subject: keeping state in an iterator object by rebinding next() References: Message-ID: Wilbert Berendsen wrote: > Hi, > > i am writing a simple parser, that generates tokens. The parser needs to > maintain some state, because some parts of the file consist of different > tokens. I thought the object could simply remember its state by assigning > it's next() method to the method that is currently parsing. When the state > changes, the called method rebinds next() and the next token will be > returned by that function. Here's an example, proving that this indeed > works. > >>>> class A: > ... def a(self): > ... self.next = self.b > ... return 1 > ... def b(self): > ... self.next = self.a > ... return 2 > ... def __iter__(self): > ... return self > ... >>>> a=A() >>>> a.a() > 1 >>>> a.next() > 2 >>>> a.next() > 1 >>>> j=0 >>>> for i in a: > ... j += 1 > ... if j > 10: break # prevent from running endlessly > ... print i > ... > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 > 2 > 1 >>>> > > my question is: is this legal Python? An iterator could save the next() > method object, and in that case it could stop working.... It works now, > because apparently the for- construct resolves 'next' each time for the > object before calling it. > > The other solution would be just jumping to the correct method from within > the next() method. But that gives an extra call... It doesn't work with newstyle classes though as next() is looked up in the class rather than the instance, just like the __xxx__() methods: >>> class A(object): ... def __iter__(self): return self ... def next(self): return "class-next()" ... >>> a = A() >>> a.next = lambda: "instance-next()" >>> a.next() 'instance-next()' >>> from itertools import islice >>> for item in islice(a, 3): print item ... class-next() class-next() class-next() Without the class-next() it isn't even recognized as an iterator >>> del A.next >>> for item in a: pass ... Traceback (most recent call last): File "", line 1, in TypeError: iter() returned non-iterator of type 'A' even though the instance-next() is still there: >>> a.next() 'instance-next()' So I recommend that you avoid that can of worms and go with the extra indirection. Peter From gherron at islandtraining.com Sun Mar 16 11:32:47 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 16 Mar 2008 08:32:47 -0700 Subject: Weight Problem In-Reply-To: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> References: <9a63e8920803151357g483e9f32hd87960e34756973e@mail.gmail.com> Message-ID: <47DD3D9F.70102@islandtraining.com> Ravi Kumar wrote: > An Interesting problem, > """ > A man has only 4 bricks of different weights, lies between 1-40KG, > Also, the total weights of Brick A, B, C, D (ie A+B+C+D) is 40KG. > The man uses that brick to calculate every possible weight > from 1 KG to 40 KG in his shop. (only whole numbers 1KG, 2KG etc, not > like 2.3KG) > """ > > I thought it would really be good to solve it by python, and right now > on the mid-way solving using very dirty approach. > But I feel, using SETs with python in such would solve it better. > Can anyone come with good solution, and maybe solution showing usage > of Sets. > -- > -=Ravi=- This sounds like a homework problem, something you should be solving yourself. If, however, you have any Python questions, then please ask. We'll be glad to answer them. -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From lorgandon at gmail.com Thu Mar 13 18:31:19 2008 From: lorgandon at gmail.com (Imri Goldberg) Date: Fri, 14 Mar 2008 00:31:19 +0200 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: References: Message-ID: <47D9AB37.2020608@gmail.com> Dave Kuhlman wrote: > The following code has me mystified: > > In [4]: class A(object): > ...: def show(self): > ...: print 'hello' > ...: > ...: > In [5]: a = A() > In [6]: > In [7]: x = a.show > In [8]: y = getattr(a, 'show') > In [9]: x > Out[9]: > > In [10]: y > Out[10]: > > In [11]: > In [12]: id(x) > Out[12]: 12419552 > In [13]: id(y) > Out[13]: 12419872 > In [14]: > In [15]: x is y > Out[15]: False > In [16]: > In [17]: x() > hello > In [18]: y() > hello > > Basically, the above code is saying that foo.foobar is not the same as > getattr(foo, 'foobar'). > > But the documentation at > http://docs.python.org/lib/built-in-funcs.html#l2h-33 > says that they are equivalent. > > And, the following seems even worse: > > >>> id(getattr(a, 'show')) == id(a.show) > True > >>> getattr(a, 'show') is a.show > False > > Actually, while I don't know about the basic problem, this doesn't mean id() is broken. In the comparison, an object is created, then id() is computed, and the object is garbage collected. The same happens to the second object. Since by the time it is created the first object was garbage collected, it can have the same id(). As you have already shown in your previous example, when the first object is not discarded, the id() is different. Here's some code to illustrate this: In [17]: bla = [a.foo for x in range(5)] In [18]: bar = [id(z) for z in bla] In [19]: bar Out[19]: [138262924, 137884252, 137884212, 137884452, 137884572] (This result is equivalent for getattr(a,'foo').) > What gives? This breaks my understanding of id(), the is operator, and > getattr(). > > Can someone help me make sense of this? > > I'm using Python 2.5.2. > > - Dave > > Cheers, Imri ------------------------- Imri Goldberg www.algorithm.co.il/blogs www.imri.co.il ------------------------- Insert Signature Here ------------------------- From castironpi at gmail.com Tue Mar 11 00:19:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 10 Mar 2008 21:19:12 -0700 (PDT) Subject: python interactive - threaded console (run -i) Message-ID: <56661ddb-f06b-4229-8011-7996cd023600@m34g2000hsc.googlegroups.com> #interactive run -i import threading import Queue import functools class GenThread( threading.Thread, Queue.Queue ): _taskid= 0 def __init__( self, *ar, **kw ): threading.Thread.__init__( self, *ar, **kw ) Queue.Queue.__init__( self ) self.setDaemon( True ) self.start() self._doneevents= {} def run( self ): while 1: id, fun, ar, kw= self.get() self._= fun( *ar, **kw ) self._doneevents[id].set() if self._: self._print( self._ ) def me( self, fun, *ar, **kw ): id= GenThread._taskid GenThread._taskid+= 1 self.put( ( id, fun, ar, kw ) ) self._doneevents[ id ]= e= threading.Event() return e def _print( self, *ar, **kw ): print( self.getName(), *ar, **kw ) for i in range( 10 ): exec( 'th%i= GenThread()'% i ) import socket host= socket.socket( socket.AF_INET, socket.SOCK_STREAM ) host.bind( ( '', 8000 ) ) th1.me( host.listen, 1 ) _acc= th1.me( host.accept ) cli= socket.socket( socket.AF_INET, socket.SOCK_STREAM ) th2.me( cli.connect, ( 'localhost', 8000 ) ) _acc.wait() conn= th1._[0] ConnClose= object() class IncompleteTransmission( Exception ): pass def _draintilclose( conn, understandfun= None ): while 1: _preamb= '' while 1: _data= conn.recv( 1 ) if not _data: conn.close() return ConnClose if _data== b'\x00': break _preamb+= _data.decode() _len= int( _preamb, 16 ) _lenleft= _len _curmsg= bytearray() while _lenleft: _data= conn.recv( min( 4096, _lenleft ) ) if not _data: raise IncompleteTransmission _curmsg.extend( _data ) _lenleft-= len( _data ) assert len( _curmsg )== _len if None is not understandfun: understandfun( _curmsg ) def _dressandsend( sck, msg ): _preamble= hex( len( msg ) )[2:]+ '\x00' _dressed= bytes( _preamble, 'ascii' )+ msg _lenleft= len( _dressed ) while _lenleft: _sent= sck.send( _dressed[-_lenleft:] ) _lenleft-= _sent th1.me( _draintilclose, conn, th1._print ) th2.me( _draintilclose, cli, th2._print ) This is cool! Set up a socket and listen 'til close on one thread, print output by default as complete messages are received. Listen 'til close, same, on another, th1, th2 respectively. Roughly off the console: >>> _dressandsend( conn, b'abc' ) Thread-2 bytearray(b'abc') >>> _dressandsend( cli, b'def' ) Thread-1 bytearray(b'def') Rearranged the '>>>'. It's damn annoying. Probably a specialized stdout to detect when in a prompt and add extra newline, maybe modified GenThread._print. Someone go replace hex with base255 and conn.recv( 1 ) with conn.recv( 2 ). Should take any length-- base256 over hex is just a factor of 2, and still O( log( message length ) ). >>> dir() ['ConnClose', 'GenThread', 'IncompleteTransmission', 'Queue', '__builtins__', '__doc__', '__name__', '__package__', '_acc', '_draintilclose', '_dressandsend', 'cli', 'conn', 'functools', 'host', 'i', 'socket', 'th1', 'th2', 'th3', 'th4', 'th5', 'th6', 'th7', 'th8', 'th9', 'threading'] From Lie.1296 at gmail.com Sun Mar 9 08:50:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 05:50:29 -0700 (PDT) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> <979d9b68-2734-4201-a1b4-7b59ca4aceb5@2g2000hsn.googlegroups.com> Message-ID: On Mar 9, 4:31?pm, Kay Schluehr wrote: > On 9 Mrz., 09:30, Lie wrote: > > On Mar 9, 12:05 pm, Kay Schluehr wrote: > > > > On 9 Mrz., 04:51, Lie wrote: > > > > > A more through implementation would start from the raiser inspecting > > > > the execution stack and finding whether there are any try block above > > > > it, if no try block exist it pass silently and if one exist it will > > > > check whether it have a matching except clause. This also circumvents > > > > a problem that simple implementation have, as described below. > > > > This will not be easy in particular in the presence of inheritance and > > > dynamism. There is no way to statically decide whether an exception > > > BException has the type AException and will be caught by the except > > > clause in > > > > try: > > > ? ? BLOCK > > > except AException, e: > > > ? ? print "SoftException %s caught"%e > > > A feasible solution was to invert the try...except statement and > > > creating a continuation. > > > > catch AException, a: > > > ? ?print "SoftException A: %s"%a > > > catch BException , b: > > > ? ?print "SoftException B: %s"%b > > > ... > > > in: > > > ? ?BLOCK > > > > Here each SoftException is raised initially when a catch clause is > > > entered and a continuation is created that returns to the catch block > > > of the raised SoftException if required. When a SoftException is > > > raised within BLOCK a lookup will be made and if a corresponding > > > SoftException was found that was raised by a catch-clause the current > > > control flow will be suspended and the continuation is called. > > > I'd rather want to avoid any syntax changes, as I wished that Soft > > Exception can be added to the language silently[1] so that new > > programmers doesn't _need_ to know about it (although knowing it could > > change the way they write codes to be more structured and simple). > > I just tried to save your proposal from being unimplementable. Maybe > you can comment on it? Perhaps I'm not the appropriate person to talk about whether unchanged syntax is feasible for such implementation since I basically have no idea about how Python's internals works. It's only that I think if current syntax could be used, we could just use it (except if there is a strong reason why it shouldn't be done). > I know of course that syntax is Pythons holy cow but I'm not Guidos > mouthpiece and have a different perspective on some aspects of the > system for obvious reasons [1]. I agree, everybody have different perspective. But that differences is what makes languages evolves as it'd be continuously searching for the most optimal perspective. From bblais at bryant.edu Fri Mar 14 18:10:57 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 14 Mar 2008 18:10:57 -0400 Subject: Joseph Weizenbaum In-Reply-To: References: Message-ID: <902DE75B-EE78-44D6-AD13-4AFAE47D14F5@bryant.edu> On Mar 14, 2008, at Mar 14:5:59 PM, castironpi at gmail.com wrote: > On Mar 14, 1:47 pm, "Reedick, Andrew" wrote: >>> Subject: RIP: Joseph Weizenbaum >> >>> Creator of Eliza: >> >>> http://www-tech.mit.edu/V128/N12/weizenbaum.html >>> -- >> >> How do you feel about creator of Eliza? > > What is Eliza? You: What is Eliza? Eliza: Does that question interest you? (http://www-ai.ijs.si/eliza/eliza.html) bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From haraldarminmassa at gmail.com Thu Mar 13 14:46:41 2008 From: haraldarminmassa at gmail.com (GHUM) Date: Thu, 13 Mar 2008 11:46:41 -0700 (PDT) Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Doug, > Precision.py is part of the Numeric package. AFAIKT, the problem is during > the module initialization. The first lines of Precision.py are: > > from multiarray import zeros > import string > [.....] and your program is crashing on the lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 line... Please, try the following: import multiarray from multiarray import zeros import string (adding the line "import multiarray" before zeros are imported from it) I used this workaround with various packages I py2exed - maybe it also works for you? please keep us updated, Harald From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Mar 14 09:19:27 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 14 Mar 2008 14:19:27 +0100 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: References: <5648a6b8-74a6-4532-a24d-8eff71b94fa4@d21g2000prf.googlegroups.com> <9NiCj.64574$Pv2.50533@newssvr23.news.prodigy.net> <63tsj3F27o6o5U1@mid.uni-berlin.de> Message-ID: <47da7b1b$0$21083$426a74cc@news.free.fr> Mel a ?crit : (snip) > (What Diez said.) From what I've seen, f.bar creates a bound method > object by taking the unbound method Foo.bar and binding its first > parameter with f. Nope. it's Foo.__dict__['bar'] (that is, the function bar defined in the namespace of class Foo) that creates a bound instancemethod object when looked up on a Foo instance - or an unbound instancemethod object when looked up on Foo. FWIW, types.UnboundMethodType and types.MethodType are both aliases to instancemethod type. From fuzzyman at gmail.com Sun Mar 23 15:22:44 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 23 Mar 2008 12:22:44 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <5626884d-5ddb-4875-b938-cfdcd389af8e@s19g2000prg.googlegroups.com> On Mar 23, 4:24 pm, a... at pythoncraft.com (Aahz) wrote: > In article , > Jeff Schwab wrote: > > > > >Also, despite reassurances to the contrary, I still get the impression > >that there is a strong anti-lambda sentiment among the Python "in" > >crowd. Is it just a question of the word "lambda," as opposed to > >perceived cleaner syntax? > > The problem with lambda is that too often it results in clutter (this is > a strictly made-up example off the top of my head for illustrative > purposes rather than any real code, but I've seen plenty of code similar > at various times): > > gui.create_window(origin=(123,456), background=gui.WHITE, > foreground=gui.BLACK, callback=lambda x: x*2) > > That means I need to pause reading the create_window() arguments while I > figure out what the lambda means -- and often the lambda is more > complicated than that. Moreover, because the lambda is unnamed, it's > missing a reading cue for its purpose. I find lambdas invaluable very frequently - often to avoid the reading clutter. * Transforming function calls something.Event += lambda sender, event: real_handler() * Properties name = property(lambda self: self.__name, __set_name) * Very short functions where extra lines reduce readability if direction == 'left': transform = lambda x, y: -x else: transform = lambda x, y: x * Functions that take functions as arguments old_list = [(3,1), (2, 2), (1, 3)] new_list = sorted(old_list, key=lambda x: x[1]) new_data = process(data_Set, lambda x: x+1) new_data2 = process(data_Set, lambda x: x-1) I don't think any of these are unreadable or improved by defining a 'real' function. Michael http://www.ironpythoninaction.com > -- > Aahz (a... at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "It is easier to optimize correct code than to correct optimized code." > --Bill Harlan From aahz at pythoncraft.com Thu Mar 13 16:20:25 2008 From: aahz at pythoncraft.com (Aahz) Date: 13 Mar 2008 13:20:25 -0700 Subject: Is there Python equivalent to Perl BEGIN{} block? References: <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> Message-ID: In article , Jeff Schwab wrote: > >I write maybe a dozen one-liners a day. It's not practical to do this >with Python, or at least it's not nearly as convenient as Perl. That is a defensible position, but my take is that writing the one-liners in Python is more convenient than remembering enough Perl to make writing one-liners useful. Especially when the one-liners often start expanding. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From paul.hankin at gmail.com Sun Mar 9 19:37:29 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sun, 9 Mar 2008 16:37:29 -0700 (PDT) Subject: __iter__ yield References: Message-ID: On Mar 9, 8:58?pm, duccio wrote: > Someone knows if it's possible to make this __iter__ function with just ? > one 'yield' intead of two? > ... > ? ? ?def __iter__(self): > ? ? ? ? ?yield self #1 > ? ? ? ? ?for n in self.childs: > ? ? ? ? ? ? ?for nn in n.__iter__(): > ? ? ? ? ? ? ? ? ?yield nn #2 Only one yield and shorter (but not really any simpler): from itertools import chain class Node: ... def __iter__(self): for x in chain([self], *self.childs): yield x -- Paul Hankin From fetchinson at googlemail.com Mon Mar 3 21:22:24 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 3 Mar 2008 18:22:24 -0800 Subject: metaclasses In-Reply-To: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> Message-ID: > What are metaclasses? http://www.google.com/search?q=python+metaclass HTH, Daniel From castironpi at gmail.com Wed Mar 12 15:06:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 12 Mar 2008 12:06:52 -0700 (PDT) Subject: tcp client socket bind problem References: <42925034-6cf7-40a7-b079-8f3bf978fea2@n36g2000hse.googlegroups.com> Message-ID: <701ef870-e305-49a4-8565-45e4ebdde244@e60g2000hsh.googlegroups.com> On Mar 11, 2:19?am, Tim Roberts wrote: > castiro... at gmail.com wrote: > > >On Mar 10, 9:40?am, Marc Christiansen wrote: > >> nata... at gmail.com wrote: > >> > I have a linux box with multiple ip addresses. I want to make my > >> > python client connect from one of the ip addresses. Here is my code, > >> > no matter what valid information I put in the bind it always comes > >> > from the default ip address on the server. Am I doing something wrong? > >... > > >help string: > >Bind the socket to a local address. ?For IP sockets, the address is a > >pair (host, port); the host must refer to the local host. > > >docs: > >Bind the socket to address. > > >Wikipedia: > >Before a socket may accept incoming connections, it must be bound. > > >PHP.net: > >Binds the name given in address to the socket described by socket . > >This has to be done before a connection is be established using > >socket_connect() or socket_listen(). > >This function must be used on the socket before socket_connect(). > > That's all true. ?So what was your point? ?How does this help the original > poster? Confidence-- a second opinion of what the docs say. Then, something of a criticism of the docs. From florian.harmuth at googlemail.com Mon Mar 17 14:11:53 2008 From: florian.harmuth at googlemail.com (mich1985) Date: Mon, 17 Mar 2008 11:11:53 -0700 (PDT) Subject: SAXReaderNotAvaiable after switching Python References: <0e990748-2e57-46ce-9a8e-2f0b89754d7c@z38g2000hsc.googlegroups.com> Message-ID: Hello all, i think that my problem is solved now. I haven't seen that the old package was recompiled from another guy. Best regards, flo On 17 Mrz., 13:12, mich1985 wrote: > Hello all, > after i have switched from python-2.4.2 to python-2.4.3 i get the > following message if run my web configuration: > > parser = xml.sax.make_parser() > ..... > SAXReaderNotAvailable: No parsers found > > The files under /usr/lib/python2.4/xml/sax are the same as before. Any > hints where i can start my search? (a ng search didn't solved my > problem). > > Best Regards, > flo From castironpi at gmail.com Fri Mar 21 02:48:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 20 Mar 2008 23:48:07 -0700 (PDT) Subject: Is this valid ? References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> <13u5rgegehc8u04@corp.supernews.com> Message-ID: <33cabf0b-3dbb-4b30-aec0-317fce3ac16e@e60g2000hsh.googlegroups.com> On Mar 20, 6:06?pm, Steven D'Aprano wrote: > On Thu, 20 Mar 2008 15:09:08 +0100, Rolf van de Krol wrote: > > > John Machin wrote: > >> Of course. You can chain comparisons as much as you like and is > >> (semi-)sensible, e.g. > > > Hmm, 'of course' is not the correct word for it. > > Not at all. The Original Poster tried something, and it worked. There > were two alternatives: > > (1) Writing a == b == 2 is valid. > > (2) In the sixteen years that Python has been publicly available, with > tens of thousands or more developers using it, nobody had noticed that > Python had a bug in the compiler which incorrectly allowed a == b == 2 > until Stef Mientki came along and discovered it. > > Given those two alternatives, (2) would be very surprising indeed, and so > I think "of course" is well justified. > > That Python allows chaining comparisons this way isn't really surprising. > That's a very natural thing to do. What's surprising is that other > languages *don't* allow chaining comparisons, but force you to write the > inefficient and (sometimes) confusing "(a == 2) and (b == 2)" instead. You see a couple of occurrences in natural language-- I'm wondering where the majority of NL settles. >>> a is a is a True Do we do math on booleans on some level or in some contexts? Maybe a "with syntaxchangeA:" is in the future. From steve at REMOVE-THIS-cybersource.com.au Thu Mar 27 04:12:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 27 Mar 2008 08:12:03 -0000 Subject: how to dynamically create class methods ? References: <000c01c88e88$96c29490$0600a8c0@laptop> <247cc598-e444-40f1-ab77-8640a034c1d9@e23g2000prf.googlegroups.com> <47E95DCC.7050507@noaa.gov> <13uj0m4qd1dit79@corp.supernews.com> Message-ID: <13umlmj757pu172@corp.supernews.com> On Wed, 26 Mar 2008 00:27:17 -0700, Arnaud Delobelle wrote: >> I'm hardly surprised. The naivety of those who insist that the "best >> way to understand how new.function and new.code work" is to look at the >> C source code for object is amusing. > > Since 'those who insist...' are just one person, me, you might as well > name them. Firstly I didn't 'insist', I stated it once. Secondly I'm > glad that I provided you with a few chuckles, but to proclaim that one > is 'amused by the naivety of others' doesn't make one automatically > right. Your criticism is accepted. You're not the only person who says "Read the C source", so I wasn't pointing the finger at just you. > Do you know how these functions behave? Have you looked at their > documentation? new.function and new.code (implemented as Objects/ > funcobject.c:func_new and Objects/codeobject.c:new_code) are not really > documented (new.code.__doc__ is 'Create a code object. Not for the > faint of heart.'). If you can't read the source then I don't think you > should use the functions. *shrug* I don't know about that. People reverse-engineer programs without access to the source code all the time. Reading the source code may (but not always) make understanding the functions easier, but it's not compulsory. If I cared enough, the way I'd go about reverse-engineering the functions would be to start by pulling apart a Python function into a code object, then pulling apart the code object into its components, making small modifications to the components, then reversing the process (using new.code() and new.function()) to build up a function object I could call. Or I'd ask somebody who already knew how they worked to give an example or two of Python code that called new.code() and new.function(). It's not ideal, of course, in a perfect world whoever wrote new.code() would have written some better documentation, but it will do for non- production code. For production code that I relied on, I'd hire a C programmer to read the source and document it for me. *wink* -- Steven From http Thu Mar 13 06:42:05 2008 From: http (Paul Rubin) Date: 13 Mar 2008 03:42:05 -0700 Subject: List mutation method gotcha - How well known? References: Message-ID: <7x1w6enbwi.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > 4) Nothing - no output By Python convention, methods that mutate the object return None, and also stuff that returns None doesn't generate output at the interactive prompt. There is a similar situation with list.sort() which led to the introduction of the sorted() builtin. Lately I try to avoid mutation, e.g. by using a generator or listcomp instead of building up a list with .append() From sjmachin at lexicon.net Tue Mar 18 14:57:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Mar 2008 11:57:40 -0700 (PDT) Subject: Decode email subjects into unicode References: <47DF8EED.1010501@shopzeus.com> Message-ID: <594fef10-a8e3-4b48-b636-ba06fb8a317a@e23g2000prf.googlegroups.com> On Mar 18, 9:09 pm, Laszlo Nagy wrote: > Sorry, meanwhile i found that "email.Headers.decode_header" can be used > to convert the subject into unicode: > > > def decode_header(self,headervalue): > > val,encoding = decode_header(headervalue)[0] > > if encoding: > > return val.decode(encoding) > > else: > > return val > > However, there are malformed emails and I have to put them into the > database. What should I do with this: > > Return-Path: > X-Original-To: i... at designasign.biz > Delivered-To: dapi... at localhost.com > Received: from 195.228.74.135 (unknown [122.46.173.89]) > by shopzeus.com (Postfix) with SMTP id F1C071DD438; > Tue, 18 Mar 2008 05:43:27 -0400 (EDT) > Date: Tue, 18 Mar 2008 12:43:45 +0200 > Message-ID: <60285728.00719565 at optometrist.com> > From: "Euro Dice Casino" > To: tho... at designasign.biz > Subject: With 2'500 Euro of Welcome Bonus you can't miss the chance! > MIME-Version: 1.0 > Content-Type: text/html; charset=iso-8859-1 > Content-Transfer-Encoding: 7bit > > There is no encoding given in the subject but it contains 0x92. When I > try to insert this into the database, I get: > > ProgrammingError: invalid byte sequence for encoding "UTF8": 0x92 > > All right, this probably was a spam email and I should simply discard > it. Probably the spammer used this special character in order to prevent > mail filters detecting "can't" and "2500". But I guess there will be > other important (ham) emails with bad encodings. How should I handle this? Maybe with some heuristics about the types of mistakes made by do-it- yourself e-mail header constructors. For example, 'iso-8859-1' often should be construed as 'cp1252': >>> import unicodedata as ucd >>> ucd.name('\x92'.decode('iso-8859-1')) Traceback (most recent call last): File "", line 1, in ValueError: no such name >>> ucd.name('\x92'.decode('cp1252')) 'RIGHT SINGLE QUOTATION MARK' >>> From sleddd at gmail.com Thu Mar 13 13:18:44 2008 From: sleddd at gmail.com (sleddd at gmail.com) Date: Thu, 13 Mar 2008 10:18:44 -0700 (PDT) Subject: Socket Performance References: Message-ID: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> On Mar 13, 9:33 am, "Brian Smith" wrote: > sle... at gmail.com wrote: > > Sent: Wednesday, March 12, 2008 9:47 PM > > To: python-l... at python.org > > Subject: Socket Performance > > > Can anyone explain why socket performance (throughput) varies > > depending on the amount of data send and recv are called with? > > > For example: try creating a local client/server (running on the same > > computer) where the server sends the client a fixed amount of data. > > Using method A, recv(8192) and sendall( ) with 8192 bytes > > worth of data. Do this 100 times. Using method B, recv(1) and > > sendall( ) with 1 byte worth of data. Do this 819200 times. > > > If you time both methods, method A has much greater > > throughput than method B. > > Why is it faster to drink a liter of water a cupful at a time than to > drink it out of an eyedropper? > > - Brian Well, lets say you have a situation where you're going to be alternating between sending large and small chunks of data. Is the solution to create a NetworkBuffer class and only call send when the buffer is full, always recv(8192)? From saluk64007 at gmail.com Fri Mar 28 01:16:24 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Thu, 27 Mar 2008 22:16:24 -0700 Subject: [Twisted-web] [ANN] Twisted 8.0 In-Reply-To: <20080328031502.GA22852@mithrandi.net> References: <60ed19d40803261826v88d20e2s8c13a0e75ef194ec@mail.gmail.com> <20080328031502.GA22852@mithrandi.net> Message-ID: It's dangerously close to april fools for this kind of posting! Congrats on the release, it looks mighty impressive. From adonis_vargas at -Remove-This-bellsouth.net Wed Mar 12 00:45:32 2008 From: adonis_vargas at -Remove-This-bellsouth.net (Adonis Vargas) Date: Wed, 12 Mar 2008 00:45:32 -0400 Subject: Why no string return? In-Reply-To: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> References: <563f4a41-1bd9-4eba-b474-be921410a6a9@s37g2000prg.googlegroups.com> Message-ID: gargonx wrote: > Say i have the two methods: > > def ReturnMethod(request, x): > if request is True: > return x > else: print "No String for you...False!" > > def SendMethod(request): > xstring = "Some text" > ReturnMethod(request, xstring) > > SendMethod(True) > > Why does ReturnMethod not return the string x? I do believe it is > returning with a NoneType. > Any help would be greatly obliged > > Thanks, Josh That is because request is bound a string (str) object. You are probably testing for null so it should look like: if request: return x else: print "No String for you...False!" Hope this helps. Adonis From tjreedy at udel.edu Mon Mar 17 15:26:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Mar 2008 15:26:24 -0400 Subject: Python 3 and PEP238 division References: Message-ID: "Ninereeds" wrote in message news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... | Is the PEP238 change to division going into Python 3 as planned? IDLE 3.0a3 >>> 1/2 0.5 | I realise that the new integer division semantics have been available | in "from __future__" for quite a few years now, but a warning might be | appropriate now that Python 3 is in alpha. 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion program From tmp1 at viltersten.com Tue Mar 4 23:26:02 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Wed, 5 Mar 2008 05:26:02 +0100 Subject: SV: SV: Polymorphism using constructors In-Reply-To: References: <6333v2F25lleoU1@mid.individual.net> <63346uF25gigqU1@mid.uni-berlin.de> <635ndjF2551ajU1@mid.individual.net> Message-ID: <636ko9F24kphrU1@mid.individual.net> > What does "SV" in the subject mean? Probably, it's an abbreviation of "svar", which means "reply". -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From frank at niessink.com Mon Mar 24 13:00:40 2008 From: frank at niessink.com (Frank Niessink) Date: Mon, 24 Mar 2008 18:00:40 +0100 Subject: Problems with wxPython In-Reply-To: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> References: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> Message-ID: <67dd1f930803241000tbce352fp93bf2df6e1d082b1@mail.gmail.com> Hi David, 2008/3/24, David Anderson : > Hi, If ther's anyone who knows pretty much about wxPython can e-mail me? I'm > having some trouble in dealing with some guis here, I would thank u very > much if you could help me You should subscribe to the wxPython users mailinglist and ask there. It's a very helpful mailinglist. Robin Dunn (wxPython author) is very active in answering questions from wxPython users. See http://www.wxpython.org/maillist.php Cheers, Frank From sjmachin at lexicon.net Fri Mar 7 20:09:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 7 Mar 2008 17:09:37 -0800 (PST) Subject: Converting a string to the most probable type References: <222eb078-9ad1-421b-93e2-173d708fe451@8g2000hse.googlegroups.com> <7xmypa844v.fsf@ruckus.brouhaha.com> Message-ID: On Mar 8, 11:13 am, Paul Rubin wrote: > Pierre Quentel writes: > > I would like to know if there is a module that converts a string to a > > value of the "most probable type" > > Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > >>> import this > The Zen of Python, by Tim Peters > ... > In the face of ambiguity, refuse the temptation to guess. Reminds me of the story about the avionics software for a fighter plane which when faced with the situation of being exactly upside-down refused to guess whether it should initiate a left roll or a right roll :-) From ericgorr at gmail.com Wed Mar 19 11:32:36 2008 From: ericgorr at gmail.com (Eric) Date: Wed, 19 Mar 2008 08:32:36 -0700 (PDT) Subject: SOAP Server in Python References: <50ccc1be-87ac-4847-b21d-7dfd46379ea4@z38g2000hsc.googlegroups.com> Message-ID: <2914eaa7-ee98-4c50-98ae-00fe647fb990@8g2000hsu.googlegroups.com> On Mar 19, 10:59 am, dave_mikes... at fastmail.fm wrote: > On Mar 19, 9:19 am, Eric wrote: > > > I am basically looking to do the same thing in Python as easily. > > > Any help or pointers would be appreciated. > > Googling for "python soap" turned up a few hits that may help you. Yes, but I don't have the knowledge to accurately or effectively evaluate the information. I was hoping someone here had some experience writing a SOAP Server using Python and would be willing to share what they know. From fakeaddress at nowhere.org Fri Mar 21 04:55:19 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 21 Mar 2008 01:55:19 -0700 Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: Benjamin Watine wrote: > bryanjugglercryptographer at yahoo.com a ?crit : >> I wrote: >>> And here's a thread example, based on Benjamin's code: >> [...] >> >> Doh! Race condition. Make that: >> >> import subprocess >> import thread >> import Queue >> >> def readtoq(pipe, q): >> q.put(pipe.read()) >> >> cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, >> stdout=subprocess.PIPE) >> >> myVar = str(range(1000000)) # arbitrary test data. >> >> q = Queue.Queue() >> thread.start_new_thread(readtoq, (cat.stdout, q)) >> cat.stdin.write(myVar) >> cat.stdin.close() >> cat.wait() >> myNewVar = q.get() >> >> assert myNewVar == myVar >> print len(myNewVar), "bytes piped around." > > Great, it works, thank you Bryan ! > > Could you explain me why you use a queue instead of a simple array for > getting the piped var ? The call to q.get() will block until an item is in the queue. At that point in the program, we had already waited for cat to terminate: cat.wait() myNewVar = q.get() But passing cat.wait() does not imply that our own thread has already read all of cat's output and put it in some destination object. Data could still be in transit. My first version, subsequently titled, "Doh! Race condition," worked in all of several runs of its built-in test. Doesn't make it right. -- --Bryan From castironpi at gmail.com Sun Mar 9 17:16:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 9 Mar 2008 14:16:58 -0700 (PDT) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <5cec96ed-fdab-48f3-8a41-d77c6d855c0f@s12g2000prg.googlegroups.com> Message-ID: <2b098afa-2dcc-4bde-bdde-02eece46fd68@47g2000hsb.googlegroups.com> On Mar 9, 4:25?am, Lie wrote: > On Mar 9, 3:27?am, castiro... at gmail.com wrote: > > > To Lie: > > > > Personally I preferred a code that has chosen good names but have > > > little or no comments compared to codes that makes bad names and have > > > Personally I don't. ?Show me a good one. ?Until you do, it's not that > > I won't like it, it's that I can't. ?You know, in linguistics, there's > > But I much prefer it that the code has good names AND concise > comments, not too short and not too long that it becomes obscure. What do you mean? If 'obscure' is the right word, then it's subjective (from metrics import obscurity?), which means that 10% of the people disagree with you, or 90% do. The end-all be-all, there is no such thing. I don't think it's obscure; I do. Is it? From jeffrey at fro.man Thu Mar 20 13:24:52 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 20 Mar 2008 10:24:52 -0700 Subject: Import a file to namespace References: <0cdb3c90-e961-4982-9996-de3ac02706bc@13g2000hsb.googlegroups.com> Message-ID: <13u57f51c3ee82e@corp.supernews.com> Pedro Machado Santa wrote: > import testpackage > > class testClass(): > #... > > testpackage.testClass = ?testClass This method should work fine. Modules are effectively singletons, so running this code one time anywhere in your application will cause the changes to appear in all references to the original module. Jeffrey From fakeaddress at nowhere.org Sun Mar 16 21:29:30 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 16 Mar 2008 18:29:30 -0700 Subject: Convert int to float In-Reply-To: References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <1QjDj.4087$qS5.2590@nlpi069.nbdc.sbc.com> sturlamolden wrote: > Guido van Brakel wrote: > >>> def gem(a): >>> g = sum(a) / len(a) >>> return g > >> It now gives a int, but i would like to see floats. How can integrate >> that into the function? > > You get an int because you are doing integer division. Cast one int to > float. > > def gem(a): > g = sum(a) / float(len(a)) > return g An alternative is to multiply by 1.0. def gem(a): g = 1.0 * sum(a) / len(a) return g The gem function is well-defined on sequences of complex numbers, in which case the float() method will raise a TypeError, while the 1.0* method will return the complex result. It may not be what van Brakel wants here, but it's an alternative to keep in mind. And I find it easier to type. -- --Bryan From danb_83 at yahoo.com Mon Mar 31 21:56:07 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 31 Mar 2008 18:56:07 -0700 (PDT) Subject: Question about overloading of binary operators References: Message-ID: <6274a417-2e26-493e-b083-07ea9903bcdb@b5g2000pri.googlegroups.com> On Mar 31, 5:03 pm, gigs wrote: > Raj Bandyopadhyay wrote: > > Hi > > > Here's a simple class example I've defined > > > ############################# > > class myInt(int): > > def __add__(self,other): > > return 0 > > > print 5 + myInt(4) #prints 9 > > print myInt(4) + 5 #prints 0 > > ############################# > > > The Python binary operation function (binary_op1() in > > Objects/abstract.c) states > > the rules for binary operations as follows: > > > v w Action > > ------------------------------------------------------------------- > > new new w.op(v,w)[*], v.op(v,w), w.op(v,w) > > new old v.op(v,w), coerce(v,w), v.op(v,w) > > old new w.op(v,w), coerce(v,w), v.op(v,w) > > old old coerce(v,w), v.op(v,w) > > > [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of > > v->ob_type > > > It seems that my example should fall in case 1, and in both cases, the > > __add__ function of the subclass should be used, returning 0, regardless > > of operand order. However, in one case the subclass's function is used > > and not in the other case. What am I missing here? > > > Thanks > > Raj > > i think that you need to use __radd__ for addition with custom object on right Right. Python doesn't make any assumptions that addition is commutative. But if it is for your class, you can just write __radd__ = __add__ From has.temp3 at virgin.net Sat Mar 15 14:48:17 2008 From: has.temp3 at virgin.net (has) Date: Sat, 15 Mar 2008 11:48:17 -0700 (PDT) Subject: Getting started with OS X Leopard References: <47dc0fe9$0$10634$fa0fcedb@news.zen.co.uk> Message-ID: On 15 Mar, 18:05, Mark Carter wrote: > The sorts of things I want to do are: > * copy the directory of Finder to the clipboard > * add a new file to Finder's directory. > * find out the size of a directory > * open a file with Aquamacs, regardless of file type, If you want to control desktop applications directly, that generally means using Apple event IPC. The most popular language for application scripting is traditionally AppleScript, but Apple event bridges exist for other languages as well. The best of these is appscript; see my sig for links. Some Finder scripting examples: #!/usr/bin/python from appscript import * from osax import * finder = app('Finder') standardadditions = ScriptingAddition() folderref = finder.Finder_windows[1].target # set clipboard to path to front window's folder path = folderref.get(resulttype=k.alias).path standardadditions.set_the_clipboard_to(path) # make new empty file in front window's folder finder.make(new=k.file, at=folderref.get()) # get size of front window's folder # (note: this may return k.missing_value when first run # as Finder is sluggish at calculating folder sizes) print folderref.size.get() # open selected items in TextEdit selecteditems = finder.selection.get() finder.open(selecteditems, using=app.application_files.ID('com.apple.textedit')) HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From sivakumar433 at gmail.com Fri Mar 28 05:44:13 2008 From: sivakumar433 at gmail.com (sivakumar433 at gmail.com) Date: Fri, 28 Mar 2008 02:44:13 -0700 (PDT) Subject: ************************************************************** Message-ID: <151380e3-5e2c-4bd0-bca0-bcbb555cffac@d4g2000prg.googlegroups.com> ************************************************************** When you make a Web page available offline, you can read its content when your computer is not connected to the Internet. For example, you can view Web pages on your laptop computer when you don't have a network or Internet connection. Or you can read Web pages at home without tying up a phone line. You can specify how much content you want available, such as just a page, or a page and all its links, and choose how you want to update that content on your computer. If you just want to view a Web page offline, and you don't need to update the content, you can save the page on your computer. There are several ways you can save the Web page, from just saving the text to saving all of the images and text needed to display that page as it appears on the Web. *************************************************************** http:\\my profile6529.blogspot.com From termim at gmail.com Fri Mar 28 13:01:25 2008 From: termim at gmail.com (Mike) Date: Fri, 28 Mar 2008 10:01:25 -0700 (PDT) Subject: How do I reconnect a disconnected socket? References: Message-ID: <5caf589a-95ca-4ba0-9e74-7dfd11ab1ebc@e67g2000hsa.googlegroups.com> On Mar 28, 10:01 am, Jason Kristoff wrote: > I'm trying to make something that once it is disconnected will > automatically try to reconnect. I'll add some more features in later so > it doesn't hammer the server but right now I just want to keep it simple > and get that part working. The problem is that when I use sock.close I > get an error message of > Bad File Descriptor > and if I either use shutdown or just go straight to reconnecting I get: > Transport endpoint is already connected > > This is what I've got right now: > > #! /usr/bin/env python > import socket, string > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > def doconn(): > sock.connect(("localhost", 1234)) > def dodiscon(): > sock.close() > doconn() > > doconn() > > while (1): > buffer = sock.recv(1024) > if not buffer: > dodiscon() I'd recommend to look at Twisted ReconnectingClientFactory - http://twistedmatrix.com/trac/browser/trunk/twisted/internet/protocol.py#L198 From pjdelport at gmail.com Fri Mar 28 15:14:37 2008 From: pjdelport at gmail.com (Piet Delport) Date: Fri, 28 Mar 2008 12:14:37 -0700 (PDT) Subject: Advantage of the array module over lists? References: <8bcc2fa5-8c95-498e-ba8d-26396ddcfc8f@d4g2000prg.googlegroups.com> <645q0hF28fnk3U1@mid.uni-berlin.de> Message-ID: <014ff679-c16e-4d13-b980-fa1816bd584d@h11g2000prf.googlegroups.com> On Mar 17, 1:49 am, "Diez B. Roggisch" wrote: > > I doubt that. AFAIK both arrays and lists are continuous memory-areas, > that double (at least to a certain threshold or so) when reaching the > capacity limit. For what it's worth, lists over-allocate by ~1/8, and arrays by ~1/16. (Details in listobject.c:list_resize and arraymodule.c:array_resize.) From elampooranan at gmail.com Sun Mar 9 19:41:59 2008 From: elampooranan at gmail.com (Roopan) Date: Sun, 9 Mar 2008 16:41:59 -0700 (PDT) Subject: Distributed App - C++ with Python for Portability? Message-ID: Hello! I am looking at developing an enterprise-grade distributed data sharing application - key requirements are productivity and platform portability. Will it be sensible to use C++ for performance-critical sections and Python for all the glue logic. Pls comment from your *experiences* how Python scales to large projects( > 200KLOC). I assume the C++/Python binding is fairly painless. Regards Elam. From tjreedy at udel.edu Mon Mar 3 23:24:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 3 Mar 2008 23:24:30 -0500 Subject: RELEASED Python 2.6a1 and 3.0a3 References: <87hcfpaczk.fsf@benfinney.id.au><996e7afc-ea50-4a2c-8edc-de58ff9c52e4@d62g2000hsf.googlegroups.com> Message-ID: "Tim Roberts" wrote in message news:ir5ns3purngj4kt4ndpptqnqm5pj628qbj at 4ax.com... | Kay Schluehr wrote: | >"The master said so" isn't an entirely satisfying answer. | | Nevertheless, it IS the answer for many questions in the Python world. But not for the questions about 2to3 Current 2to3 is written in Py2.5 and will require the 2.5 interpreter until 2.6 is sufficiently stable to run it. Whether it will later use 2.6 features or not I do not know. I believe that pre-2.6 code will be directly upgradable if A. it does not depend on bugs that are fixed by 2.6, so that it is also 2.6 code; B. one is willing to do the upgrade more or less 'all at once', (while the code is frozen); C. one is willing to do *one* of the following: C1. keep the 2.x code frozen, or C2. redo the upgrade more or less 'from scratch' after base code edits, or C3. maintain the 2.x code and 3.0 code in parallel These are facts of programming life, not BDFL edicts. But many will prefer an incremental approach. Py 2.6 will ease this by 1) optionally issuing upgrade warnings, and 2) incorporating many new 3.0 features that do not conflict with 2.x features. tjr From george.sakkis at gmail.com Mon Mar 31 22:27:56 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 19:27:56 -0700 (PDT) Subject: python persistence References: <8b1723d9-67c8-4fe5-b07b-22b0b9311519@8g2000hsu.googlegroups.com> <7f58b5f4-3195-472c-b307-dec71b12aaa8@y21g2000hsf.googlegroups.com> <44f04bf3-4edc-4cb4-9e54-fe51b5e591bc@e39g2000hsf.googlegroups.com> Message-ID: <80d1731d-a3c6-4fce-81fd-9c3f3537e59b@d21g2000prf.googlegroups.com> On Mar 31, 8:51 pm, castiro... at gmail.com wrote: > On Mar 31, 7:14 pm, 7stud wrote: > > > > > On Mar 31, 5:31 pm, castiro... at gmail.com wrote: > > > > Can you have a Python object stored entirely on disk? > > > import cPickle as cp > > > class Dog(object): > > def __init__(self, name): > > self.name = name > > > d = Dog("Spot") > > > f = open("data.txt", "w") > > cp.dump(d, f) > > f.close() > > > f = open("data.txt") > > stored_obj = cp.load(f) > > print stored_obj.name > > > --output:-- > > Spot > >>> import pickle > >>> pickle.loads( pickle.dumps( type('None',(),{}) ) ) > > Traceback (most recent call last): > File "", line 1, in > File "C:\Programs\Python\lib\pickle.py", line 1303, in dumps > Pickler(f, protocol).dump(obj) > File "C:\Programs\Python\lib\pickle.py", line 221, in dump > self.save(obj) > File "C:\Programs\Python\lib\pickle.py", line 283, in save > f(self, obj) # Call unbound method with explicit self > File "C:\Programs\Python\lib\pickle.py", line 697, in save_global > (obj, module, name)) > pickle.PicklingError: Can't pickle : it's not > found as __ > main__.None > > http://docs.python.org/lib/node317.html From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:34:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:34:48 -0300 Subject: Breaking the barrier of a broken paradigm... part 1 References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> Message-ID: En Tue, 25 Mar 2008 07:44:59 -0300, john s. escribi?: >> for line in open("/etc/passwd"): >> user, _pwd = line.split(":") > ^----- Ok this one here we are taking a string spliting it > into to variables... > user gets one (the first) and _pwd gets to hold the > "leftovers"? No; if the line contains more than a single : that code will fail. user, remainder = line.split(":", 1) With Python 3.0 you could write: user, _pwd, *other = line.split(":") but limiting the number of splits is more efficient if you are not interested in the remaining list. A more interesting case is: a, b, *other, c = line.split(":") to obtain the first, second and last items. -- Gabriel Genellina From lipun4u at gmail.com Tue Mar 11 11:24:54 2008 From: lipun4u at gmail.com (asit) Date: Tue, 11 Mar 2008 08:24:54 -0700 (PDT) Subject: mulithreaded server Message-ID: <7c555afb-2df0-43f2-aa16-d1e48da1510a@e23g2000prf.googlegroups.com> import socket import sys import thread p=1 PORT=11000 BUFSIZE=1024 def getData(cSocket): global stdoutlock,cSocketlock while True: cSocketlock.acquire() data=cSocket.recv(BUFSIZE) if data=='q': data='client exited' cSocket.close() p=0 cSocketlock.release() stdoutlock.acquire() stdout.write(data) stdoutlock.release() def sendData(cSocket): global stdoutlock,cSocketlock while True: stdoutlock.acquire() data=raw_input('>>') cSocketlock.acquire_lock() if data=='q': stdout.write('server exited') stdout.release() p=0 cSocket.close() sSocket.send(data) sSocketlock.release() stdout=sys.stdout host='' sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sSocket.bind((host,PORT,)) sSocket.listen(1) #sSocketlock=thread.allocate_lock() stdoutlock=thread.allocate_lock() print 'waiting for connection' cSocket,addr=sSocket.accept() print 'connection from',addr cSocketlock=thread.allocate_lock() thread.start_new_thread(sendData,(cSocket,)) thread.start_new_thread(getData,(cSocket,)) if p==0: sSocket.close() In the above program, why there is an unhandeled exception ??? From paul.hankin at gmail.com Tue Mar 11 06:37:53 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 11 Mar 2008 03:37:53 -0700 (PDT) Subject: rmdir problem References: Message-ID: On Mar 11, 10:35 am, royG wrote: > i am checking if a directory exists and if it does i want to delete it > and its contents.then i want to create the directory before creating > files in it. Have a look at shutil.rmtree -- Paul Hankin From rakesh.usenet at gmail.com Sat Mar 1 17:40:18 2008 From: rakesh.usenet at gmail.com (Rakesh Kumar) Date: Sat, 1 Mar 2008 14:40:18 -0800 (PST) Subject: cx_Freeze : LookupError: unknown encoding: ascii Message-ID: <55b6d54d-a267-49d3-bc4f-31bd5794c545@d4g2000prg.googlegroups.com> Hi - I created a binary using the cx_Freeze utility on Linux (wxWidgets 2.8 / Python 2.5/ Mandriva 2008 ). When I tried to run the binary - this is the error that I got on the console. File "gdataapi.py", line 44, in __init__ self.service.ProgrammaticLogin() File "/opt/software/gdata-py/src/gdata/service.py", line 284, in ProgrammaticLogin auth_connection.putrequest('POST', '/accounts/ClientLogin') File "/usr/lib/python2.5/httplib.py", line 806, in putrequest host_enc = self.host.encode("ascii") LookupError: unknown encoding: ascii Can somebody point to some clues about options that need to be passed to FreezePython API to get the right executable. Thanks for the help. From bharathv6.project at gmail.com Sun Mar 23 16:23:33 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Mon, 24 Mar 2008 01:53:33 +0530 Subject: writing a message to the terminal in a daemon process Message-ID: <2613171a0803231323y501c76fbxf72aa7a86fe99446@mail.gmail.com> hi, i created a daemon process using the following code import os import sys # Default daemon parameters. # File mode creation mask of the daemon. UMASK = 0 # Default working directory for the daemon. WORKDIR = "/" # Default maximum for the number of available file descriptors. MAXFD = 1024 # The standard I/O file descriptors are redirected to /dev/null by default. if (hasattr(os, "devnull")): REDIRECT_TO = os.devnull else: REDIRECT_TO = "/dev/null" def goDaemon(): try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The first child. os.setsid() try: pid = os.fork() # Fork a second child. except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The second child. #os.chdir(WORKDIR) os.umask(UMASK) else: os._exit(0) else: os._exit(0) # Exit parent of the first child. import resource maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if (maxfd == resource.RLIM_INFINITY): maxfd = MAXFD for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass os.open(REDIRECT_TO, os.O_RDWR) # standard input (0) os.dup2(0, 1) # standard output (1) os.dup2(0, 2) # standard error (2) return(0) it can be seen that the standard output and standard error are redirected to null terminal now after the process is made daemon i.e after closing all the resources and redirecting the standard output and standard error to null terminal now I want to print some initial msg on the console(terminal) in which the program was started . *NOTE*:I realize that initial msg can be printed before closing all the resources and redirecting the standard output and standard error to null terminal but it necessary to print the msg after the process is made daemon i.e when the process actually starts doing some processing. I tried with following code: fd=os.open("/dev/tty",os.O_WRONLY) os.write(fd,msg) os.close(fd) but this worked fine before closing all the resources and redirecting the standard output and standard error to null terminal and after doing all these even it didn't help it didn't print any thing on the terminal pls can anyone how this can be done -------------- next part -------------- An HTML attachment was scrubbed... URL: From bijeshn at gmail.com Thu Mar 13 02:21:19 2008 From: bijeshn at gmail.com (bijeshn at gmail.com) Date: Wed, 12 Mar 2008 23:21:19 -0700 (PDT) Subject: copying all data(tags and values) after a particular XML tag Message-ID: <9c8740c5-7dfa-4007-a530-c28d4b31a20d@u10g2000prn.googlegroups.com> i've an XML file with the following structure.... . . . . . what i want to do is copy all data(tags and all) between N and N+k appearances of . I am a python newbie. How do I do it? Thanks. From bockman at virgilio.it Tue Mar 25 03:49:31 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 25 Mar 2008 07:49:31 GMT Subject: Shortcutting the function call stack References: <903d7b90-686c-44aa-8776-a2e728b7b837@x41g2000hsb.googlegroups.com> <634cb9f8-0bfc-489e-8232-9184ca227861@u69g2000hse.googlegroups.com> Message-ID: <47e8ae8a$0$21201$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 15:05:38 -0700, Julien ha scritto: ... > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making up > the term) a function: > > def hijacker(arg): > if I_feel_its_necessary: > hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > hijacker(something) > ... # Continue as normal > return 2 > > def my_function2(arg): > ... # Maybe do some processing here > hijacker(whatever) > ... # Continue as normal > return 3 > > > You could simply do something like: def hijacker(arg): if I_feel_its_necessary: return True, 1 else: return False, 0 def my_function1(arg): abort, code = hijiacker(something); if abort: return code ... # Continue as normal return 2 def my_function2(arg): ... # Maybe do some processing here abort, code = hijiacker(whatever); if abort: return code ... # Continue as normal return 3 Although purists may frown upon the double return statement, it is still a much cleaner code than using some magic to abort the caller function. And tou have only to add two lines - always the same - at each function. Ciao ----- FB From tjreedy at udel.edu Tue Mar 18 22:16:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Mar 2008 22:16:56 -0400 Subject: Python 3 and PEP238 division References: <3b9c9176-101f-4c72-8a56-82d16aea48d5@k13g2000hse.googlegroups.com> Message-ID: "Ninereeds" wrote in message news:3b9c9176-101f-4c72-8a56-82d16aea48d5 at k13g2000hse.googlegroups.com... | On Mar 17, 7:26 pm, "Terry Reedy" wrote: | > "Ninereeds" wrote in message | > | > news:ddaa40d0-3d75-44b7-98ad-7dfaa3b3e6de at m44g2000hsc.googlegroups.com... | > | Is the PEP238 change to division going into Python 3 as planned? | > | > IDLE 3.0a3>>> 1/2 | > | > 0.5 | > | > | I realise that the new integer division semantics have been available | > | in "from __future__" for quite a few years now, but a warning might be | > | appropriate now that Python 3 is in alpha. | > | > 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion | > program | | The tools can work out the *intent* of any particular division | operator? Can work out whether the result should be integer or float, | independent of any particular set of arguments? Seems unlikely. For the case of int division, one should have started using 1//2 already for floor division. Before running 2to3, a program should pass all tests with 'from __future__ import division', so that a/b definitely means fractions division even for int/int. Then the only thing 2to3 has to do in this regard is delete the future import. From grante at visi.com Mon Mar 31 14:56:27 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 31 Mar 2008 13:56:27 -0500 Subject: troll poll References: <7xr6dq3i54.fsf@ruckus.brouhaha.com> <199c5242-f561-4c51-a96b-428abe6f9d80@f63g2000hsf.googlegroups.com> Message-ID: On 2008-03-31, Carl Banks wrote: > On Mar 31, 1:41 pm, Paul Rubin wrote: >> "Daniel Fetchinson" writes: >> > [ ] - Xah Lee >> > [ ] - castironpi >> >> I've lost track but has it been established that they are not the same >> person? > > Has it been established that castironpi is a person at all? I think he is at least some of the time. Some of his posts look like they're generated by an undergrad AI class project, but there are also posts that seems to be written by a real person who's overly fond of metaphors. -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.com ATLANTA, Georgia!! From guillermo.listas at googlemail.com Thu Mar 6 12:17:31 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Thu, 6 Mar 2008 09:17:31 -0800 (PST) Subject: Checking if a variable is a dictionary References: <34810189-19ef-4ba7-8581-603b8b3c9391@y77g2000hsy.googlegroups.com> <47cfe65d$0$9590$426a74cc@news.free.fr> Message-ID: > You can also get the dynamic polymorphism without invoking inheritance > by specifying a protocol that the values in your dict must implement, > instead. Protocols are plentiful in Python, perhaps more popular than > type hierarchies. I'm used to languages with stricter rules than Python. I've read a bit about Python protocols, but where could I get some more info on implementation details? Sounds very interesting. Regards, Guillermo From bj_666 at gmx.net Mon Mar 3 06:41:32 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Mar 2008 11:41:32 GMT Subject: Can one get "for x in y" to work for non builtin classes? References: <20080302150617.bc9dcb20.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <6326fcF25g4d2U4@mid.uni-berlin.de> On Mon, 03 Mar 2008 12:17:39 +0100, M.-A. Lemburg wrote: > It's also possible to implement .__getitem__() and .__len__() > methods and have Python create an iterator on-the-fly. That's > how Python used to work before iterators were added to the > language. A suitable `__getitem__()` is enough. The end will be signaled by an `IndexError`. Ciao, Marc 'BlackJack' Rintsch From bjourne at gmail.com Wed Mar 19 06:17:18 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 19 Mar 2008 11:17:18 +0100 Subject: Interesting math problem In-Reply-To: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> References: <3a34caaf-a279-4e86-837d-42efa4d80129@d4g2000prg.googlegroups.com> Message-ID: <740c3aec0803190317u76d4233y1524906aab1e36da@mail.gmail.com> On Mon, Mar 17, 2008 at 11:57 PM, Arnaud Delobelle wrote: > > def make_slope(distance, parts): > > step = distance / float(parts) > > intstep = int(step) > > floatstep = step - intstep > > > > steps = [] > > acc = 0.0 > > for i in range(parts): > > acc += floatstep > > step = intstep > > if acc > 0.999: > > step += 1 > > acc -= 1.0 > > steps.append(step) > > return steps > > OK then, using list comprehensions. It is more succint, is it easier > to read? > > def slope(dist, parts): > return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)] Congratulations! You Won! Jeff Schwab's recursive approach is also cool but this is the most interesting abuse of integer division I have seen. I don't think any of the variants are readable at a first glance, but with a comment it should be ok. -- mvh Bj?rn From kmacphail at gmail.com Mon Mar 17 01:24:53 2008 From: kmacphail at gmail.com (Kevin MacPhail) Date: Sun, 16 Mar 2008 23:24:53 -0600 Subject: Python and 3D In-Reply-To: References: Message-ID: <9766d5b90803162224n7c613268k601a25bd7a7af6dc@mail.gmail.com> On Sat, Mar 15, 2008 at 2:09 PM, Eric von Horst wrote: > Hi, > > I am looking for Python modules that allow you to manipulate 3D > objects, more specifically Alias Wavefront .OBJ objects. > Also, a module that would allow you to vizualize these models and > rotate them etc.. > > The goal is not to build a new renderer or something; just a small > program that I need to do some manipulations in bulk on a set of OBJs > > Any help much appreciated > > Eric > -- > http://mail.python.org/mailman/listinfo/python-list > Cgkit might be what you're looking for: http://cgkit.sourceforge.net/ -Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Wed Mar 12 10:33:05 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 12 Mar 2008 09:33:05 -0500 Subject: List Combinations In-Reply-To: References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: <47D7E9A1.7000403@ncee.net> Michael Wieher wrote: > > > 2008/3/12, Gerdus van Zyl >: > > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus > > -- > > > list = [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > newList = [] > for l in list: > newList.extend(l) > > #newList = [3,9,1,5,4,2,5,8] > list=[] > for l in newList: > if l not in list: > list.append(l) > > #now list is [3,9,1,5,4,2,8] > > list.sort() > > #now your list is in sorted order > > Then, you can just write a series of for loops to spin off your data > however you like. > > def gen(lists): out = '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']' comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in range(len(lists))]) return eval('[ ' + out + comp + ' ]') a,b,c = [1,2,3],[4,5,6],[7,8,9] print gen([a, b, c]) -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From MartinRinehart at gmail.com Thu Mar 27 14:29:01 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 27 Mar 2008 11:29:01 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: bearophileH... at lycos.com wrote: > menudef = """ > File > New, callNew, Ctrl-N > New Window, callNewWindow, Ctrl-Shift-N > __ > Open, lambda e=0:para(1), Ctrl-O Nice design. I looked at it for a few seconds and didn't even think about pressing F1. Mine does less. But you tell it less to do it. Is there no way to get underscore/ keyboard access for the main menu items? From theller at ctypes.org Mon Mar 17 07:58:18 2008 From: theller at ctypes.org (Thomas Heller) Date: Mon, 17 Mar 2008 12:58:18 +0100 Subject: comtypes question In-Reply-To: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> References: <11e49df10803170406q6bd77f4cwbcec5bf9448292ae@mail.gmail.com> Message-ID: Jorgen Bodde schrieb: > Hi All, > > I am trying to automate a 3rd party application, and all I have to > work on is the type library and some documentation. I hope a Python / > COM guru can answer this or put me on the right path because I don't > know why it does not work. > > First I imported the typelib with comtypes like; > >>> from comtypes.client import GetModule >>> GetModule("C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe") > > Which blurbs out a lot of text: > > # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1 > # Generating comtypes.gen.BarTender > 'C:\Python24\lib\site-packages\comtypes\gen\_D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1.pyc'> > > Which seems to be ok. Now, I need to call a function on the > Application object on which I need a "Messages" instance. The > Application object gets created properly: > >>> import comtypes.gen.Bartender as bt >>> app = comtypes.client.CreateObject(bt.Application) > > Which gives me the application (the bt.Application points to a wrapper > class containing the CLSID of the COM class to be instantiated). > > Now I browse the typelibrary and I see there is a CoClass called > Messages. I need one of those to pass as an argument, and since > Messages is listed as a CoClass similar to Application, I assume it > can also be instantiated. But when I try this I get an error: > >>>> msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}') [...] > WindowsError: [Errno -2147221164] Class not registered > > Both Application and Messages are listed as CoClass inside the > typelibrary. Does anybody know why it gives me this error and what I > am doing wrong? Not all coclasses can be created from scratch with CreateObject. Sometimes they are created by calls to methods on some other object. I downloaded the bartender trial, and looking into the typelib it seems that, for example, the 'XMLScript' method on the IBtApplication interface returns Messages instances: COMMETHOD([dispid(17), helpstring(u'Runs xml scripts')], HRESULT, 'XMLScript', ( ['in'], BSTR, 'XMLScript' ), ( ['in'], BtXMLSourceType, 'SourceType' ), ( ['out'], POINTER(POINTER(Messages)), 'Messages' ), ^^^^^^^^ ( ['retval', 'out'], POINTER(BSTR), 'retval' )), Here is an interactive session: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from comtypes.gen import BarTender >>> from comtypes.client import CreateObject >>> app = CreateObject(BarTender.Application) >>> print app >>> app.XMLScript("foo", 0) (, u'') >>> msg, retval = app.XMLScript("foo", 0) >>> print msg >>> msg[0] Traceback (most recent call last): File "", line 1, in File "comtypes\__init__.py", line 308, in __getitem__ result = self.Item(index) _ctypes.COMError: (-2147220992, None, (u'The item at position 0 was not found.', u'bartend', None, 0, None)) >>> msg[1] >>> m = msg[1] >>> print m >>> m.Number 3908 >>> m.Message u"An error occurred during XML script processing:\r\n\r\nInvalid at the top level of the document.\r\nLine 1, Column 1: 'foo'" >>> ^Z Not that the above makes much sense, but I hope it will get you started. Thomas BTW: The 'official' comtypes mailing list is at https://lists.sourceforge.net/lists/listinfo/comtypes-users. Requires that you subscribe before you can post, but you could disable mail delivery and use via gmane: gmane.comp.python.comtypes.user From __peter__ at web.de Thu Mar 6 03:13:52 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Mar 2008 09:13:52 +0100 Subject: Short confusing example with unicode, print, and __str__ References: <47CEDF77.5050501@andrew.cmu.edu> <47CEEBFC.9010001@islandtraining.com> Message-ID: Gerard Brunick wrote: > It seems the question is more about what does print do. ?Lets extend > your example: > > >>> d=unicode("Caf\xe9", "Latin-1") > >>> repr(d) > "u'Caf\\xe9'" > >>> print d > Caf? > >>> str(d) > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 3: ordinal not in range(128) > > Why doesn't the print statement that a UnicodeEncodeError? ?I assumed > that print calls str and then prints > the result, but this doesn't seem to be the case. ?What the heck does > print do? Something like d = ... if type(d) is unicode: sys.stdout.write(d.encode(sys.stdout.encoding)) else: sys.stdout.write(str(d)) Unfortunately you can't make that work smoothly with arbitrary objects as you have to throw in an explicit conversion to unicode: >>> class C(object): ... def __unicode__(self): return u"Caf\xe9" ... >>> print C() <__main__.C object at 0x2b1da33e0bd0> >>> print unicode(C()) Caf? Or, even less intuitive: >>> class D(object): ... def __str__(self): return u"Caf\xe9" ... >>> print unicode(D()) Caf? >>> print D() Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) Peter From yennes at gmail.com Thu Mar 20 06:27:50 2008 From: yennes at gmail.com (Dravidan) Date: Thu, 20 Mar 2008 03:27:50 -0700 (PDT) Subject: csv dictreader References: <13u3vq77us4ku3c@corp.supernews.com> Message-ID: <60a85025-4103-494d-b31c-70e66cf9d58b@x30g2000hsd.googlegroups.com> It looks like the backslash is messing the whole thing up so I reposted to try to find out how to get over the backslash hump. On Mar 20, 2:08 am, Dennis Lee Bieber wrote: > On Wed, 19 Mar 2008 11:06:40 -0700 (PDT), brnstrmrs > declaimed the following in comp.lang.python: > > > my csv files looks like this: > > > Bytecode,Element > > \x00\x00,0000 > > \x01\x00,0001 > > .... > > \x09\x00,0009 > > I sure hope your data is more complex than that... otherwise it's a > waste of space... > > >>> for i in range(10): > ... print i, repr(struct.pack("h", i)) > ... > 0 '\x00\x00' > 1 '\x01\x00' > 2 '\x02\x00' > 3 '\x03\x00' > 4 '\x04\x00' > 5 '\x05\x00' > 6 '\x06\x00' > 7 '\x07\x00' > 8 '\x08\x00' > 9 '\t\x00' > > And, \t is the same value \x09 (a tab character) > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From bearophileHUGS at lycos.com Sat Mar 22 19:16:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 22 Mar 2008 16:16:03 -0700 (PDT) Subject: List question References: <8uc8u3p6v679uqo6s0fcagaa59huv6qpci@4ax.com> <1404603a-520a-4f15-92ba-4caad37f0874@b64g2000hsa.googlegroups.com> Message-ID: <3ee39d9f-dde7-432b-bc3c-5b8dd935e3f4@a70g2000hsh.googlegroups.com> bearophile: > A more computer-friendly (and Pythonic) syntax may be ('are' is a keyword): Sorry for causing confusion, I was just thinking aloud. English isn't my first language, and sometimes I slip a bit. Replace that with: > A more computer-friendly (and Pythonic) syntax may be ('are' is meant to be a keyword in such hypothetical situation): Bye, bearophile From mensanator at aol.com Mon Mar 3 20:39:31 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Mar 2008 17:39:31 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <120641da-f3fe-45c6-a3d0-2e17c31f10d8@e25g2000prg.googlegroups.com> Message-ID: On Mar 3, 6:21?pm, Robert Kern wrote: > Mensanator wrote: > > On Mar 3, 4:08 pm, Robert Kern wrote: > >> Mensanator wrote: > >>> On Mar 3, 2:49 pm, Carl Banks wrote: > >>>> It's just a bug--probably sympy is messing with the internals of the > >>>> random number generator. ?It would be a simple fix. ?Instead of > >>>> b****ing about it, file a bug report. ? > >>> I did. > >>>> Or better yet, submit a patch. > >>> I would if I knew what the problem was. > >> Did you even try to figure it out? It took me all of 5 minutes to find the mistake. > > > Could I trouble you to share? Then I could continue my testing. > > I posted the patch on the bug tracker: > > ? ?http://code.google.com/p/sympy/issues/detail?id=729 Thanks, I think I actually figured out how to use it. > > >>> I posted it here because someone recommended it. > >>> I'm simply un-recommending it. > >> It was a mistake, an easily remedied mistake, > > > But I didn't know that (and still don't). > > >> not a big unchangeable design decision. > > > I didn't know that either. For all I know, I might have to > > wait for the next version, and who knows when that will be? > > The point is that you didn't try to figure it out. Give me a break, I'm not a developer, just an end user. > And you assumed the worst Wasn't my assumption correct? That it really was messing outside it's domain? > rather than giving anyone the benefit of the doubt. As in "maybe it only fails for me"? Was I crying that the sky was falling? > You didn't even wait to get a response from the package > maintainer I have no experience with those web sites. I think this is the first time I was able to successfully report a bug and have no clue what the turnaround time is. > about how serious the issue was The symptom was serious although the fix was simple. > before you came here to un-recommend it. As an end user, I get most of my information here. Since I saw the link to sympy here on this newsgroup, I thought it would be irresponsible to file a bug report without simultaneously mentioning it here. > > All software has bugs. > > Good software has bugs. Are bugs off-topic here? > > Finding a single bug in a package is not sufficient cause to warn people away as > if it had the plague. It DID have the plague. It affected anything else that tried to use random numbers. > > >> If you want to recommend against sympy as a package, there is a larger > >> burden of proof that you have yet to meet. > > > What kind of burden of proof must one have to recommend it in the > > first place? > > Significantly less. "It was useful to me," is sufficient. Really? That's sufficient? Ok, but how is my pointing out a verifyable problem that affects the entire system not a sufficient burden of proof against recommending the package? Or should I just have worded it differently? Aren't I at least going to get credit for having found it? > > -- > 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 ericofam at yahoo.com Sun Mar 9 07:36:55 2008 From: ericofam at yahoo.com (ericofam at yahoo.com) Date: Sun, 9 Mar 2008 04:36:55 -0700 (PDT) Subject: Green's Function References: <501978.67770.qm@web53602.mail.re2.yahoo.com> Message-ID: On Mar 8, 9:46?pm, "Terry Reedy" wrote: > "olusina eric" wrote in message > > news:501978.67770.qm at web53602.mail.re2.yahoo.com... > | ?I am new to Python and trying to solve the Hamiltonian of a linear chair > of atoms using green's function. > | ?Does anyone know any pre-existing library functions and literature that > could be helpful? > > Did you try searching for "Python Green's function"? I did try serching for Python "Green's function" and useful hit. Also searched on scipy with no reasonable result too. EOF From ron.longo at cox.net Mon Mar 24 21:52:49 2008 From: ron.longo at cox.net (Ron Provost) Date: Mon, 24 Mar 2008 21:52:49 -0400 Subject: New Full Tkinter document editor widget -- suggestions, comments, etc. Message-ID: <003301c88e1a$eea60250$6501a8c0@aristotle> I've posted a demo (http://tkinter.unpy.net/wiki/StyledEditor). This demo creates a widget with full "styled editing" capabilities; sort of a mini-word processor. It runs "as is" on my WinXP machine with Python 2.5. The demo allows styling of any selected text via toolbars; just select the text, then select the styling. Also included are buttons to save and retrieve all content and styling information (works for the small tests I've tried myself, not guaranteed bug-free). The actual widget wraps the Text widget to give greater freedom in the assignment of any single styling attribute to any region. This differs from the Text widget itself in that the Text widget does not allow you to individually assign a family, size, weight or slant with tag_config(). That is, for example, you can't simply apply 'bold' to some region of text. This demo was written quite quickly (I pounded it out over the weekend) so I'm sure it's full of bugs. Also in my desire to get something working quickly its API doesn't really work like a normal widget, so I guess this serves as more of a proof of concept than full-blown widget but the basic functionality is there. I'm presenting it here because I thought maybe others might have thoughts on how to improve it. API Notes: applyStyleAttribute( index1, index2, attributeName, attributeValue ) This method is is frontend to the business. attributeName and attributeValue may be any option accpeted by tag_config() of the Text widget along with appropriate value. There are also some ''new'' options: - 'family', attributeValue is a font family name - 'size', attributeValue is a font point size - 'weight', attributeValue is one of: 'normal', 'bold' - 'bold', attributeValue is a boolean (alternative to using 'weight') - 'slant', attributeValue is one of: 'roman', 'italic' - 'italic', attributeValue is boolean (alternative to using 'slant') Several previously existing options have some new values: 'spacing1', 'spacing2' and 'spacing3' may take 'None', 'Half Line', 'One Line' or 'Two Lines' in addition to any of the values acceptable by tag_config(). 'offset' may take 'normal', 'superscript' or 'subscript' in addition to any value acceptable by tag_config. Please download and try-out my demo (http://tkinter.unpy.net/wiki/StyledEditor). I'm anxious for suggestions and comments. Ron Longo From mal at egenix.com Fri Mar 7 16:43:31 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 07 Mar 2008 22:43:31 +0100 Subject: Time Zone application after strptime? In-Reply-To: References: Message-ID: <47D1B703.6040200@egenix.com> On 2008-03-07 22:24, Jim Carroll wrote: > It's taken me a couple of hours to give up on strptime with %Z for recognizing > time zones... but that still leaves me in the wrong zone: > > def paypal_to_mysql_date(ppDate): > # a typical paypal date is 10:29:52 Feb 29, 2008 PST > date_parts = ppDate.split() > withouttz = " ".join(date_parts[:-1]) > > # eventually we need to apply the timezone > timezone = date_parts[-1] > > dt = datetime.strptime(withouttz, "%H:%M:%S %b %d, %Y") > return dt.strftime("%Y-%m-%d %H:%M") > > > How can I use the "PST" (or any other time zone name) to adjust dt by the > correct number of hours to get it into UTC before storing in MySQL? You could try mxDateTime's parser. It will convert most timezones into UTC for you: >>> from mx.DateTime import * >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008') However, note that I changed the position of the timezone in your example. Having the timezone at the end of the string and after the date is a rather unusual format and not supported out-of-the-box by mxDateTime (even though it does support a very wide range of formats). http://www.egenix.com/products/python/mxBase/mxDateTime/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Mar 07 2008) >>> 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 mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX 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 From lists at js3d.co.uk Tue Mar 25 11:31:11 2008 From: lists at js3d.co.uk (Jules Stevenson) Date: Tue, 25 Mar 2008 15:31:11 -0000 Subject: dynamically created names / simple problem In-Reply-To: <47E91820.7090009@jouy.inra.fr> References: <000c01c88e88$96c29490$0600a8c0@laptop><47E91645.4000706@jouy.inra.fr> <47E91820.7090009@jouy.inra.fr> Message-ID: <001d01c88e8d$41489d70$0600a8c0@laptop> Brilliant. Thanks From davidbak at gmail.com Fri Mar 7 16:07:21 2008 From: davidbak at gmail.com (DBak) Date: Fri, 7 Mar 2008 13:07:21 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: <83a114c1-e675-445f-909d-68c2407bc276@u10g2000prn.googlegroups.com> Sorry - code for the class should read: class Tree(object): ...class _MT(Tree): ......def isEmpty(self): return True ......def insert(self, X): return Tree._Node(X) ...class _Node(Tree): ......def isEmpty(self): return False ......def insert(self, X): return _Node(X, self, Tree._MT()) ...def __init__(): return _MT() ...def merge(self, T): ...... From bearophileHUGS at lycos.com Wed Mar 5 19:39:08 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 5 Mar 2008 16:39:08 -0800 (PST) Subject: for-else References: <7266c16c-c5b4-43b4-9a5b-ef8fb22d9b98@s12g2000prg.googlegroups.com> <47cf1426$0$15875$edfadb0f@dtext01.news.tele.dk> Message-ID: <2401e847-09da-4ec3-be89-29c382a82b04@60g2000hsy.googlegroups.com> On Mar 5, 10:44 pm, "Troels Thomsen" wrote: > > The primary use case is searching a container: > > > prep_tasks() > > for item in container: > > if predicate(item): > > found_tasks() > > break > > else: > > not_found_tasks() > > follow_up_tasks > > I've found myself mimicing this again and again in c, and was pleased to > find it in python and use it regularely. > int i > for (i = 0 ; i < 10 ; ++i) > blah > if i == 10 > not_found_tasks() > > The discussion of words is silly. My surprise about "else following a for > loop.... what the heck ...." lasted excactly as long as it takes to read > this sentence. > > tpt From duncan.booth at invalid.invalid Mon Mar 10 10:18:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2008 14:18:48 GMT Subject: Quality assurance in Python projects containing C modules References: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> Message-ID: NoelByron at gmx.net wrote: > Hello! > > We are thinking about writing a project for several customers in > Python. This project would include (among others) wxPython, a C/C++ > module. But what happens if this application generates a segmentation > fault on a customers PC. What changes do we have to trace back the > source of the error? Imagine you use two or three C libraries in a > Python project and you experience random crashes in 'Python.exe'. What > would you do? > I would start by ensuring that any DLLs you write are written using Pyrex or Cython: almost always problems with C libraries called from Python are due to faulty reference counting but if you keep all of your Python related code in Pyrex/Cython modules the reference counting problem should be taken care of for you. You can call any required C/C++ code from the Cython code. From roy at panix.com Sun Mar 23 13:51:34 2008 From: roy at panix.com (Roy Smith) Date: Sun, 23 Mar 2008 13:51:34 -0400 Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: > Also, despite reassurances to the contrary, I still get the impression > that there is a strong anti-lambda sentiment among the Python "in" > crowd. Is it just a question of the word "lambda," as opposed to > perceived cleaner syntax? There is a fundamental disharmony in how functions and other objects are treated in Python. If I say: x = ['surprise', 'fear', 'ruthless efficiency'] I've done two things. First, I've created a list, then I've bound the name x to that list (maybe "bound" is not exactly the right terminology). Until the assignment happend, the list had no name. In fact, it still has no name; there's just a reference to it stored in a variable whose name is x. If I were to then do y = x now y and x have equal relationships to the original list. The list's name is no more x than it is y, since the whole concept of "the name of the list" doesn't have any meaning in Python. On the other hand, when I do: def torture(): woman.putInChair() cushion.poke() rack.turn() I've also done two things. First, I've created a function object (i.e. a lambda body), and I've also bound the name torture to that function object, in much the same way I did with the list. But, it's different. The function object KNOWS that it's name is torture. When I later reassign it to another name and run it: weapon = torture weapon() This is what I get: Traceback (most recent call last): File "", line 1, in File "", line 2, in torture NameError: global name 'woman' is not defined Notice, the second line in the stack trace identified the function's name as "torture", not "weapon". Because that IS the function's name. Lists are anonymous. Functions have names (as do a few other things like classes and modules). If I ask a list what its name is, I get: AttributeError: 'list' object has no attribute '__name__' but, if I ask a function what it's name is (regardless of what name I've bound it to), I get the right answer: >>> torture.__name__ 'torture' >>> weapon.__name__ 'torture' >>> If we created lisp-like lambdas and bound them to names like we did with other types of objects, we wouldn't have that. What Python give us with lambdas is some half-way thing. It's not a full function, so it's something that people use rarely, which means most people (like me) can't remember the exact syntax. Even when I know it's the right thing to be using in a situation, I tend not to use it simply because the path of least resistance is to write a one-off function vs. looking up the exact syntax for a lambda in the manual. From tameranboobs at gmail.com Thu Mar 27 09:13:16 2008 From: tameranboobs at gmail.com (tameranboobs at gmail.com) Date: Thu, 27 Mar 2008 06:13:16 -0700 (PDT) Subject: genuine phentermine overnight delivery american express overnight pay phentermine phentermine without perscriptions Message-ID: http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ http://www.discountmed.biz/ order phentermine with saturday overnight delivery, phentermine order no scripts overnight delivery, phentermine fast overnight delivery guaranteed, delivery overnight guaranteed phentermine stock, order phentermine online saturday delivery, order phentermine with saturday delivery, overnight delivery phentermine 375 mg, phentermine overnight delivery text javascript, phentermine overnight ups delivery, phentermine overnight delivery to florida, phentermine sameday overnight saturday delivery, overnight phentermine with saturday delivery, buy phentermine overnight saturday delivery, phentermine cod overnight delivery no rx, order zithromax overnight delivery, order phentermine saturday delivery, delivery guaranteed in overnight phentermine stock, phentermine overnight saturday delivery, 30mg phentermine overnight delivery, phentermine overnight delivery us licensed pharmacies, phentermine guaranteed overnight delivery usa only, overnight delivery phentermine 37.5, phentermine fed ex overnight delivery, order phentermine by for saturday delivery, genuine phentermine overnight delivery, order phentermine by phone online consultation, order telephone viagra overnight delivery, purchase phentermine cheap overnight delivery guarantee, real phentermine overnight delivery no script, phentermine and 375 online overnight delivery, phentermine banners overnight delivery, phentermine overnight delivery available, phentermine 37.5 no prescription overnight delivery, immediate phentermine overnight delivery, delivery overnight in guaranteed phentermine stock, phentermine in stock overnight delivery, phentermine no prescription fedex overnight delivery, cod delivery overnight phentermine ups, 30mg blue phentermine overnight delivery, order by 2pm get phentermine overnight, phentermine online fed ex overnight delivery, phentermine for overnight and saturday delivery, phentermine overnight delivery saturday, overnight phentermine saturday delivery, delivery overnight phentermine us licensed pharmacies, phentermine and overnight delivery and saturday, phentermine 375 online overnight delivery, phentermine cod guaranteed overnight delivery, phentermine 37.5 overnight delivery, ups overnight delivery phentermine us only, e-check order phentermine fast delivery, no prescription 37.5 phentermine overnight delivery, phentermine online gt overnight delivery levitra, overnight saturday delivery for phentermine, order phentermine without prescription ship overnight, order phentermine by phone no script, phentermine order express shipping, order phentermine no primary care physician, order watson soma with saturday delivery, phentermine with cod delivery charge, no prescription premarin free overnight delivery, imitrex overnight delivery, allegra buy valium overnight delivery possible, fed ex overnight delivery cialis, phentermine usa pharmacy ativan guaranteed overnight, guaranteed overnight phentermine without rx, order phentermine oval a 159, angel book guest order phentermine site, order phentermine without calling my doctor, buy phentermine online same day delivery, buy phentermine by phone no script, phentermine on line with saturday delivery, fenphen file link order phentermine, places to order phentermine, cash delivery link medrx phentermine, guaranteed overnight phentermine without prescription, order phentermine wbr, phentermine overnight phentramine, phentermine no rx overnight, phentermine overnight paid by mastercard, order phentermine with online diagnosis, phentermine 37.5 tablets next day delivery, phentermine 15mg overnight shipping, phentermine overnight fedex no prescription 37.5, sumycin overnight delivery, prescription cipro overnight delivery, arthritis load cell order phentermine, order real phentermine without script, addiction adipexdrug online order phentermine, cash day delivery guaranteed next phentermine, phentermine 37.5 next day delivery, places to order ligit phentermine, phentermine overnight legal no prescription, phentermine blue white capsules order online, order phentermine without a doctor approval, phentermine overnight federal express, buy ritalin online phentermine order, real phentermine without prescription overnight ship, phentermine no script fedex overnight, viagra overnight delivery weekends, buy eon labs phentermine overnight, phentermine overnight no prescription legal legal, order cheap phentermine online overnite, buy no prescription next-day delivery phentermine, opensolaris forums buy phentermine online order, diovan online order fast delivery, order phentermine phentermineonline s xanga site, order phentermine and ship to arkansas, buy phentermine 37.5 tennessee overnight ship, phentermine order by 3pm, phentermine huge discounts fast delivery, dir link order phentermine, zithromax overnight delivery, phentermine via money order, phentermine no rx overnight fedex cod, zanaflex overnight delivery, phentermine overnight cod accepted, overnight phentermine adipex cod excepted, order phentermine online us licensed pharmacies, 90 count phentermine overnight shipping, bbs followup message order phentermine post, buy cheap phentermine moreover order viagra, cod delivery phentermine saturday, cheap phentermine offer cash on delivery, phentermine with satruday delivery, phentermine 37.5mg prescription overnight, phentermine cod overnight eft, prednisone order online overnight, phentermine no rx nextday delivery, order phentermine without drs rx, phentermine overnight shipping fed ex, phentermine pharmacy ships cod overnight, online pharmacy phentermine saturday delivery, phentermine 24 hour delivery, phentermine overnight no prior prescription, purchase tylenol 3 with overnight delivery, phentermine back-order, delivery flower buy phentermine, frontier pharmacies order phentermine eon labs, order phentermine 375 mg, phentermine 37.5 order no denials, phentermine saturday delivery cash on delivery, compare overnight phentermine prices united states, buspar fast overnight delivery usa only, delivery guaranteed overnight soma, cheap online order overnite phentermine, find phentermine overnight cod 100 count, phentermine fedex overnight shipping, kinds of phentermine doctors order, order phentermine 375 cod, order phentermine in usa without script, generic diflucan no prescription overnight delivery, inexpensive phentermine overnight, phentermine guaranteed overnight shipping, codeine tylenol 4 overnight delivery, buy lamictal with overnight delivery, extra cheap phentermine fed ex delivery, most reliable site to order phentermine, no prescription next-day delivery phentermine, fastest phentermine delivery no prescription, leo phentermine order online, phentermine 37.5 overnight shipping, diflucan phone order, phentermine online purchase saturday delivery, discrete overnight phentermine, phentermine cod next day delivery, phentermine cod saturday delivery, order phentermine without physicians approval, order phentermine or duramine online, buy phentermine sat delivery cod, florida in overnight phentermine shipped, order phentermine pay with mastercard, acomplia overnight delivery, order phentermine referrers total, ups delivery phentermine, order phentermine online use mastercard, guaranteed overnight phentermine, phentermine no prescription ship overnight, cheap morning after pill overnight delivery, order phentermine oval, money order phentermine umaxppc, phentermine free overnight shipping 89, order prednisone no prescription overnight fedex, phentermine no prescription saturday delivery, order phentermine priority mail, phentermine saturday delivery available, order cheap phentermine no prescript tin, acomplia guaranteed overnight delivery, adipexdrug addiction order phentermine online, echeck phentermine overnight, diflucan overnight delivery, overnight saturday phentermine before 4pm, phentermine phentramine online prescription order, phentermine delivered overnight, addiction adipexdrug order phentermine, presc s xanga site order phentermine, buy cheap phentermine shipped overnight, phentermine overnight discover credit card, phentermine with saturday delivery, nevada based phentermine overnight, ship overnight phentermine 37.5, phentermine 15mg overnight, accepted cod order phentermine s, internet order phentermine 37.5mg 90 tablets, no doctor contact to order phentermine, guaranteed delivery phentermine 37.5 no prescription, lasix without prescription overnight delivery, zovirax overnight delivery, buy phentermine online ritalin order, order phentermine no script united states, overnight prednisone delivery, receive phentermine saturday delivery, phentermine saturday delivery, phentermine shipped cash on delivery, blogs on where to order phentermine, phentermine saturday delivery best online pharmacy, order phentermine hcl overnite cod, cheap delivery online phentermine saturday, phentermine no prescriptions sat delivery, overnight phentermine brand no script, levitra fast overnight delivery usa only, delivery phentermine saturday, overnight phentermine with drs consult, phentermine 15mg fed ex overnight, phentermine 30 overnight fedex cod, order phentermine 37.5 180, same day delivery on phentermine, viagra by overnight delivery, customhrt phentermine order, famvir overnight delivery, phentermine overnight no script, phentermine overnight discover card, overnight delivery topamax, phentermine overnight $90, order phentermine overseas, phentermine no script overnight, order phentermine by 6pm, 4.22 order phentermine, buy phentermine without script fast delivery, phentermine no prescripition overnight ship, customs seized phentermine order, phentermine 37.5 cash on delivery, purchase phentermine overnight with paypal, can't order phentermine anymore, phentermine in stock overnight, phentermine shipped overnight, phentermine 37.5 fed ex overnight, didrex phentermine no rx overnight shipping, viagra overnight delivery on weekends, adipexdrug addiction order phentermine, cheap phentermine worldwide delivery, order phentermine 37.5 2 day ship, phentermine no prescription saturday delivery mastercard, buy cod delivery phentermine sat, cod money order accepted for phentermine, phentermine in stock california overnight, delivery phentermine united parcel, phentermine shipped cod overnight, phentermine cod overnight 100 ct, pravachol overnight delivery, fedex overnight delivery codeine ultram tramadol, generic cialis overnight delivery express delivery, order phentermine cod view more info, phentermine 37.5mg overnight shipping, miami distributer phentermine order online, cheap phentermine saturday delivery ups chep, overnite delivery of prescription phentermine, phentermine generic overnight 90 days, order phentermine online phentermine phentermine saturday, order phentermine without calling doctor, phentermine phentramine overnight yellow, phentermine 37.5 no prescription overnight shipping, prilosec stock overnight delivery, ultram overnight delivery same day, phentermine buy on line overnight, fedex overnight delivery ultram tramadol codeine, buy eon phentermine overnight, phentermine order without primary care physician, american express overnight pay phentermine, motrin overnight delivery, phentermine overnight ship, order phentermine safely without prescription, buy phentermine saturday delivery ohio, best order phentermine place umaxppc, order phentermine with no prior prescription, order topamax overnight, order phentermine phenterm ine online, phentermine and no prior and overnight, bulk order of phentermine, order phentermine online al bawaba blogs, phentermine 37.5 fed-x delivery, cash delivery hydrochloride phentermine, viagra overnight delivery 1 800, cialis and diazepam overnight delivery possible, order phentermine descriptive phentermine guidelines, phentermine and facts not to order, canada phentermine phentermine order mastercard, prednisone overnight delivery, order phentermine with no physcian approval, overnight phentermine licensed pharmacies online, phentermine secure online order, fed x delivery for phentermine, delivery overnight in guaranteed acomplia stock, cash on delivery shipping of phentermine, keyword phentermine online order shop baikalguide, c d o overnight phentermine, 180 37.5 order phentermine pill, order phentermine from middle east pharmacy, cheap phentermine nextday delivery, tennessee phentermine 37.5 overnight ship, phentermine 37.5 order medication, book guest link order phentermine, phentermine arkansas overnight, overnight express delivery generic cialis, order phentermine high quality pharmacy index, buy phentermine with saturday delivery, soma online overnight delivery to florida, phentermine 37.5 overnight phentramine hoodia, order phentermine no rx mastercard, overnight rocaltrol delivery, flomax overnight delivery, phentermine without a prescription saturday delivery, dc community forums phentermine cod delivery, cash delivery ordering phentermine phentermine dosing, phentermine by phone no script, phentermine smallest prices worldwide delivery, phentermine with cod and saturday delivery, 4.25 n online order phentermine, order phentermine online pharmacy catalog online, cytotec order overnight, order phentermine receive sameday, nexium overnight delivery, prilosec in stock overnight delivery, buy order phentermine hcl without prescription, desyrel order overnight, 4.25 online order phentermine, codeine ultram tramadol overnight delivery, ultram 059 order phentermine, phentermine overnight no subscription, cod delivery phentermine ups, phentermine phentramine overnight, collect on delivery phentermine, overnight phentermine 37 5mg, 375 cod order phentermine, guaranteed overnight phentermine us licensed pharmacies, cheapest phentermine fed x overnight, order phentermine without physicians prescription, order phentermine by cashier check, phentermine cash on delivery accepted, phentermine overnight to california, overnight phentermine no rx, lasix overnight delivery, phentermine guaranteed overnight, phentermine 37.5 pay by money order, order phentermine pay with echeck, blog cheap home link phentermine, best phentermine no perscription 30mg, phentermine banner, phentermine 37.5 free doctor, weight loss journal diet phentermine pill, phentermine hydrochloride iv tablets usp, does phentermine cause depression, phentermine 30mg blue clear caps discreet, 4.01 buy cheap phentermine, no rx phentermine 30mg, order herbal ecstasy, reliable sites for phentermine, b 12 phentermine raleigh, phentermine erection help, carisoprodol phentermine yellow, phentermine nrop cod, ativan link online phentermine phentermine9, phentermine topamax, phentermine plus wellbutrin fill prescriptions online, buy phentermine form eurpoe, phentermine hydro, cheap phentermine 30 mgs caps, phentermine vs dhea, order pal pay zocor, phentermine induced psychosis, doctors that perscribe phentermine, cure depression diet phentermine pill, phentermine 37.5 90 pills, phentermine 30mg without perscription, buy phentermine w out a prescription, phendimetrazine interactions with phentermine, dir florida link phentermine purchase ship, discount online phentermine without script, phentermine doctor st louis, phentermine side effects dangers, phentermine that uses paypal, dr in bakersfield phentermine, cheap prozac overnight, different shapes of phentermine tablets, ultram saturday delivery, phentermine no presciption, phentermine shipped to la, phentermine before surgery, phentermine 37 5mg shipped to kentucky, phentermine wikipedia the, lung problems from phentermine, phentermine eon labs buy online, phentermine licensed physician, phentermine on line official store, diflucan day delivery, re prozac and phentermine anyone, phentermine 37.5 no doctor consult, fastin online description chemistry ingredients phentermine, order the abortion pill, phentermine and sibutramine, pravachol phentermine pharmacy los angeles, phentermine sales for ky, phentermine capsules 37.5mg without prescription, seap debt counseling phentermine now, phentermine menstrual cycle, phentermine constipation, whats is phentermine, actos canada online pharmacy phentermine plavix, confidential online phentermine, 37.5 159 a phentermine, harmful effects of phentermine for adipex, phentermine w o rx, want phentermine shipped 48hours, generic viagra sent overnight, 37.5 mg phentermine with no rx, compare ionamin phentermine, phentermine dextroamphetamine amphetamine, phentermine query, phentermine blue white 30mg side effects, phentermine in hair follicle drug test, phentermine and mouth numbness, phentermine 90 count, book com guest myron phentermine site, phentermine 37.5 capsules, negative phentermine stories, having trouble finding phentermine information, museum phentermine site, phentermine delivered c o d, addiction adipexdrug online phentermine, phentermine tolerance, generic phentermine rss feed, phentermine testimony, didrex link online phentermine phentermine9, phentermine 37.5mg consultation, saff 0 q buy phentermine, phentermine and methamphetamine, order discount pravachol free shipping, order viagra international ships, real people opinions of phentermine, prednisone order doctor on staff, difference between meridia and phentermine, phentermine no perscription, phentermine yellow capsules, phentermine without dr script, phentermine prescription amount, phentermine through body building, cheap phentermine yellow free shipping, 365 generic medication phentermine, taking phentermine with paxilcr, phentermine sore throat, phentermine safety and does it work, phentermine have withdrawal symptoms, miami online phentermine, phentermine with online prescription, pm cheap phentermine us licensed pharmacies, phentermine without a perscription, overnight levaquin without prescription, 5htp phentermine, phentermine erection depression, phentermine and sibutramine be combined, sellers of phentermine 30 mg civ, difference between phentermine and phentermine, actos phentermine norvasc, diet pal pay phentermine pill, brand name phentermine 37.5 next day, phentermine without perscription shipped to ky, oder phentermine by cod, phentermine phoenix arizona, phentermine non perscription, phentermine incrediants, lotensin aciphex phentermine pharmacy chicago, phentermine no precription, 92 accepted cod phentermine, phentermine 37.5 90 ct no prescription, phentermine and zoloft us approved pharmacies, file link online phentermine phentermine side, baikalguide diet keyword phentermine pill shop, extended release phentermine, cardinal health diet phentermine pill, phentermine chemical enhancement, cheap levitra link phentermine phentermine9, phentermine creates erection, phentermine suspended, budget rx phentermine, phentermine without perscriptions, phentermine and customhrt, phentermine overview, need real phentermine without rx, diet pills phentermine us licensed pharmacies, prevacid prescription assistance, From gherzig at fmed.uba.ar Fri Mar 14 10:14:11 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 14 Mar 2008 11:14:11 -0300 Subject: request for Details about Dictionaries in Python In-Reply-To: References: <47DA6FF6.5000505@fmed.uba.ar> Message-ID: <47DA8833.9020205@fmed.uba.ar> Saideep A V S wrote: >Hello Sir, > > Thank You a ton. I was looking for this function. As far what I've >understood from the "Shelve" module is that, there would be no memory >wastage and the whole transactions would be done from and to the file we >specify. Am I right?. > > My actual task is to build a basic dictionary for two languages and store >word and its meaning in another language in a file and must be able to >access it through on-disk Hash tables. as these would be saving memory space >for a huge data. > >so, I hope shelve is the right one, I am searching for., I shall try out >with the function. > > >Thank You once again. > >Cheers, >Saideep > > > Plz remember allways reply to the python group also. They are many many many ones to know more than i do! Well, i dont quite think that it would be "no memory wastage", since when you read/write from disk, there is memory involved in the process. I *really* believe that, when data goes huge, a *real* database (like postgres, and others) has to come and play the game. Hope that helps Gerardo From danb_83 at yahoo.com Sat Mar 29 16:48:48 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 29 Mar 2008 13:48:48 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> Message-ID: <02864e42-d2d7-4eeb-ba13-6aa7ddbdf7aa@i29g2000prf.googlegroups.com> On Mar 29, 6:08 am, Paul Rubin wrote: > kwitt... at telenet.be writes: > > I don't know if this is the right place to discuss the death of <> in > > Python 3.0, or if there have been any meaningful discussions posted > > before (hard to search google with '<>' keyword), but why would anyone > > prefer the comparison operator != over <>??? > > I doubt anyone cares. Python probably chose != because it's what C uses. MOST of Python's operators are based on C's. Consider, for example, the bitwise operators | ^ & << >> ~ and the compound assignment operators += -= etc. The exceptions are ** (from Fortran), //, and the logical operators. From dullrich at sprynet.com Thu Mar 20 07:18:34 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 20 Mar 2008 06:18:34 -0500 Subject: Speaking Text References: Message-ID: On Wed, 19 Mar 2008 07:41:29 -0500, David C. Ullrich wrote: >Mac OS X has text-to-speech built into the interface. >So there must be a way to access that from the command >line as well - in fact the first thing I tried worked: > >os.system('say hello') > >says 'hello'. > >Is there something similar in Windows and/or Linux? >(If it's there in Linux presumably it only works if there >happens to be a speech engine available...) Thanks for the replies. >David C. Ullrich David C. Ullrich From tmp1 at viltersten.com Sat Mar 8 19:55:50 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 01:55:50 +0100 Subject: SV: SV: Quit-command not quiting In-Reply-To: References: <63d2efF271u6hU1@mid.individual.net><63d5v1F23vm9fU1@mid.individual.net> Message-ID: <63gptsF266bejU1@mid.individual.net> "Gabriel Genellina" skrev i meddelandet news:mailman.1750.1205017517.9267.python-list at python.org... > En Fri, 07 Mar 2008 13:56:45 -0200, K Viltersten > escribi?: > >>>> The window itself vanishes if i click the >>>> cross in the upper-right corner but pressing >>>> the quit-button only makes it "pressed". >>>> Then, the program freezes. >>> >>> How did you run it? From inside IDLE? IDLE itself is written >>> using Tk, and I think that your mainloop interferes with the >>> one inside it. If you run your program from the command line >>> it should work fine. >> >> I press F5 while in the editor window. Is there a way to run the >> program without going to the console window? >> Perhaps i'm just making things unneccesarily complicated >> and Python IS supposed to be run from console window? > > No, use IDLE if you prefer, or any other editor/IDE. But in your case > there is an unfortunate coupling between IDLE and your script. Fix: change > the quit method as suggested in this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/92bee52a3e2a325e/ > > def quit(self): > self.master.destroy() > > This is OK if used on the top level widget on the application (your Demo > class, for instance). A more general solution: > > def quit(self): > parent = self > while parent.winfo_class() != 'Tk': > if parent.master is None: > break; > parent = parent.master > else: > parent.destroy() > > (from > https://sourceforge.net/tracker/index.php?func=detail&aid=661324&group_id=9579&atid=109579 > ) > > This appears to work fine. But the loop, as written, could exit without > calling destroy() on anything; perhaps some other people knowing better > how Tkinter and Tk work could improve it or confirm it's fine as it is. Thank you. I'll try that tomorrow. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From jgardner at jonathangardner.net Thu Mar 13 15:03:25 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 13 Mar 2008 12:03:25 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> Message-ID: <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> On Mar 12, 6:37?pm, Carl Banks wrote: > On Mar 12, 8:11 pm, Justus Schwabedal > wrote: > > > What do you need it for anyway? I just read about it and I think it's > > useless > > in python. > > Perl, like Python, has a separate compilation and run times. ?One day, > someone who was trying to use Perl for something asked, "You know, > wouldn't it be neat-o if you could execute some Perl code *before* you > compiled the script?" ?And so (since that's usually enough reason to > add something to Perl) was borne the BEGIN block. > > I believe the official rationale was that they wanted to add some > magic variables that affected Perl's compilation and couldn't do it > without a magic block that executed at compile time. > It's a bit different. Python's "import" and perl's "use" statements aren't very similar at all. See, perl looks for any "use" statements and runs those first. That's not the way for Python at all. It's ok to import a module right before you need it in a function. If you never call the function, you'll never import the module. What if you want to reprogram the search path before you use a module? Well, in Python, you just work on sys.path before the import statement. But in perl, if you put a statement that mucks with the perl path, then it will be ignored until it is too late. So you have to throw it into the BEGIN block to have it do anything at all. What was an obvious task in Python that uses only constructs and concepts you already know about, requires a new concept and syntax that wasn't needed before in perl. Also, Jeff has it right. Those who don't get it should look closely at the '-p' option passed to perl. (It has a cousin '-n' that is also just as useful.) Here, he wants to initialize some code before the loop starts, but he can't specify that initializing code outside of the loop without a BEGIN block. BEGIN is a dirty, ugly, stupid bandage to an underlying weakness in perl. That is, there is magic that needs more magic to override it. (And then you'll need magic to override the overriding magic, ad infinitum.) Rather than adding more magic, what you really need to do is get rid of magic that gets in people's way, or change the magic so it is actually useful for everyone. Python has it right. Tokenize, parse, (skip compile-link-import magic), and run. And leave out the magical -p and -n. If you want to iterate through a file, "for line in sys.stdin:". From dave_mikesell at fastmail.fm Sat Mar 8 16:40:56 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 13:40:56 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 2:27 pm, castiro... at gmail.com wrote: > Good comments are better than bad names. > Good names are better than bad comments. If you're taking the time to write good comments, why not just fix the bad names? The compiler/interpreter can never, ever catch bad comments. From NoelByron at gmx.net Mon Mar 10 09:08:32 2008 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: Mon, 10 Mar 2008 06:08:32 -0700 (PDT) Subject: Quality assurance in Python projects containing C modules Message-ID: <51c292fc-8f38-4853-9fdb-d3b8c7802a93@2g2000hsn.googlegroups.com> Hello! We are thinking about writing a project for several customers in Python. This project would include (among others) wxPython, a C/C++ module. But what happens if this application generates a segmentation fault on a customers PC. What changes do we have to trace back the source of the error? Imagine you use two or three C libraries in a Python project and you experience random crashes in 'Python.exe'. What would you do? We intent to target mainly the Windows platform. Is there for example a way to use 'dbghelp.dll'? Best regards and thank you! Noel From vedrandekovic at gmail.com Wed Mar 26 13:55:43 2008 From: vedrandekovic at gmail.com (vedrandekovic at gmail.com) Date: Wed, 26 Mar 2008 10:55:43 -0700 (PDT) Subject: Py2exe embed my modules to libary.zip Message-ID: Hello, Does anybody have any idea how can I embed my modules to libary.zip and use it from my application.For example if user write this code in my TextEntry ( or something like that, textentry is created with wxpython ) : import d3dx # directpython module frame=d3dx.Frame(u"My frame") # create frame frame.Mainloop() # run it ....and then when my application execute code how can I set path to d3dx module to "library.zip/d3dx.py". I'm not sure is this properly set question. Regards, Vedran From jacob.kaplanmoss at gmail.com Sun Mar 16 11:51:33 2008 From: jacob.kaplanmoss at gmail.com (Jacob Kaplan-Moss) Date: Sun, 16 Mar 2008 08:51:33 -0700 (PDT) Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: <40b73be4-3744-4e29-8524-503d559445df@b64g2000hsa.googlegroups.com> On Mar 16, 9:59?am, Fuzzyman wrote: > This isn't new though. Last year (my only other PyCon) all the > sponsors gave lightning talks. The difference is that there were more > sponsors this year I guess... The difference (from my POV as the guy who helped plan and run the lightning talks this year and last) was that last year the sponsor talks were at a separate time, and clearly labeled as "Sponsor Lightning Talks". A *lot* of folks still showed up, and they didn't feel lied-to when they got product or company pitches. Jacob From jackdied at jackdied.com Sun Mar 23 01:26:28 2008 From: jackdied at jackdied.com (Jack Diederich) Date: Sun, 23 Mar 2008 01:26:28 -0400 Subject: Know Your Python-Devs! Message-ID: <20080323052627.GA6351@performancedrivers.com> At the PyCon core python sprint I suggested this game and it got some laughs. So I put together a webpage for the game of: German, American, or Other? There is a list of about 30 core devs' last names. Highlight the white text on white background for the [mostly correct] answers. http://jackdied.blogspot.com/2008/03/misc-from-pycon-ii.html Enjoy, -Jack From r.grimm at science-computing.de Fri Mar 21 04:53:23 2008 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Fri, 21 Mar 2008 01:53:23 -0700 (PDT) Subject: removing all instances of a certain value from a list References: <67c4ee28-79d5-4c58-8ee0-7cc2fc105af7@m36g2000hse.googlegroups.com> Message-ID: <93e8ab20-8dd5-47d3-b977-822329889b52@a70g2000hsh.googlegroups.com> On Mar 19, 11:28 pm, Lee Sander wrote: > Hi, > I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are > many missing vlaues which are represented as None. I would like to > remove all such instances in one go. > There is a remove function but it removes only the first instance, is > there a delete/remove all function? > thanks You can also do it with the filter function. >>> a= [-1.3, 1.22, 9.2, None, 2.3] >>> a=filter ( lambda b: b != None, a) >>> print a [-1.3, 1.22, 9.1999999999999993, 2.2999999999999998] Greetings Rainer From fakeaddress at nowhere.org Fri Mar 14 04:18:51 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 14 Mar 2008 08:18:51 GMT Subject: Spaces in path name In-Reply-To: References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> Message-ID: David S wrote: > I get > > ERROR: ""C:\Program Files\apache-ant-1.7.0\bin\ant"" does not exist > > If I cut the path statement here and paste it next to a windows XP command > prompt ant is invoked. > > The python code here is > if not os.path.isfile(ANT_CMD): > error('"%s" does not exist' % ANT_CMD) There you don't want the quotes within the string. On my MS-Win box: >>> import os >>> os.path.isfile(r'C:\Program Files\Windows NT\dialer.exe') True >>> print os.path.isfile(r'"C:\Program Files\Windows NT\dialer.exe"') False -- --Bryan From kyosohma at gmail.com Mon Mar 24 16:11:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 24 Mar 2008 13:11:52 -0700 (PDT) Subject: PyCon video editing References: <0ed1ce28-b517-4c17-b12e-7d6554f5274a@x41g2000hsb.googlegroups.com> Message-ID: <2694d982-a5d1-426d-81dc-eb16b27ddccc@i12g2000prf.googlegroups.com> On Mar 18, 10:09 am, amk wrote: > On Mar 17, 10:00 pm, dundeemt wrote: > > > Anyone know who is in charge of this? I'd like to help out if I > > could. > > I am, but haven't set anything up yet, such as a mailing list or a > host for the video. > I'll update the wiki pagehttp://wiki.python.org/moin/PyConRecordingBof > with news/further developments (you can create a wiki account and > follow the envelope icon at the upper right > to be notified of changes via e-mail). > > --amk Somebody has stuck a few videos on Youtube already: http://www.youtube.com/user/pycon08 Mike From fuzzyman at gmail.com Sat Mar 1 17:59:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 1 Mar 2008 14:59:38 -0800 (PST) Subject: Python COM automation - Controlling Microsoft Agent References: <0a998c60-fc33-4424-b5c7-65f4a2846e4d@i12g2000prf.googlegroups.com> Message-ID: <82b25446-78fb-4e02-b454-9f03b63c1e9f@e23g2000prf.googlegroups.com> On Mar 1, 12:47 am, Kamilche wrote: > Here's a snippet of code for pythoners to enjoy. > Make the Microsoft genie speak text and dance about! Code (with pretty pictures!) to do similar things from IronPython: http://www.ironpython.info/index.php/AgentServerObjects Michael Foord http://www.manning.com/foord From steven.klass at gmail.com Sun Mar 23 00:51:07 2008 From: steven.klass at gmail.com (rh0dium) Date: Sat, 22 Mar 2008 21:51:07 -0700 (PDT) Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> <2db2d0c7-ed89-4e36-aaca-d68aa30faac6@8g2000hse.googlegroups.com> <5c27f3df-d798-45f6-b5df-eed3b3345a15@p25g2000hsf.googlegroups.com> Message-ID: <3320cf26-4999-4cf8-8393-1859fb272852@s37g2000prg.googlegroups.com> On Mar 22, 6:30?pm, Paul McGuire wrote: > Oof, I see that you have multiple "Layer" entries, with different > qualifying labels. ?Since the dicts use "Layer" as the key, you only > get the last "Layer" value, with qualifier "PRBOUNDARY", and lose the > "Layer" for "METAL2". ?To fix this, you'll have to move the optional > alias term to the key, and merge "Layer" and "PRBOUNDARY" into a > single key, perhaps "Layer/PRBOUNDARY" or "Layer(PRBOUNDARY)" - a > parse action should take care of this for you. ?Unfortnately, these > forms will not allow you to use object attribute form > (md.Layer.lineStyle), you will have to use dict access form > (md["Layer(PRBOUNDARY)"].lineStyle), since these keys have characters > that are not valid attribute name characters. > > Or you could add one more level of Dict nesting to your grammar, to > permit access like "md.Layer.PRBOUNDARY.lineStyle". > > -- Paul OK - We'll I got as far as you did but I did it a bit differently.. Then I merged some of your data with my data. But Now I am at the point of adding another level of the dict and am struggling.. Here is what I have.. # parse actions LPAR = Literal("(") RPAR = Literal(")") LBRACE = Literal("{") RBRACE = Literal("}") EQUAL = Literal("=") # This will get the values all figured out.. # "metal2" 1 6.05E-05 30 cvtInt = lambda toks: int(toks[0]) cvtReal = lambda toks: float(toks[0]) integer = Combine(Optional(oneOf("+ -")) + Word(nums))\ .setParseAction( cvtInt ) real = Combine(Optional(oneOf("+ -")) + Word(nums) + "." + Optional(Word(nums)) + Optional(oneOf("e E")+Optional(oneOf("+ -")) +Word(nums)))\ .setParseAction( cvtReal ) atfstr = quotedString.setParseAction(removeQuotes) atflist = Group( LPAR.suppress() + delimitedList(real, ",") + RPAR.suppress() ) atfvalues = ( real | integer | atfstr | atflist ) # Now this should work out a single line inside a section # maskName = "metal2" # isDefaultLayer = 1 # visible = 1 # fatTblSpacing = (0.21,0.24,0.6, # 0.6,0.6,0.6) # minArea = 0.144 atfkeys = Word(alphanums) attrDict = dictOf( atfkeys , EQUAL.suppress() + atfvalues) # Now we need to take care of the "Metal2" { one or more attrDict } # "METAL2" { # layerNumber = 36 # maskName = "metal2" # isDefaultLayer = 1 # visible = 1 # fatTblSpacing = (0.21,0.24,0.6, # 0.24,0.24,0.6, # 0.6,0.6,0.6) # minArea = 0.144 # } attrType = dictOf(atfstr, LBRACE.suppress() + attrDict + RBRACE.suppress()) # Lastly we need to get the ones without attributes (Technology) attrType2 = LBRACE.suppress() + attrDict + RBRACE.suppress() mainDict = dictOf(atfkeys, attrType2 | attrType ) md = mainDict.parseString(test1) But I too am only getting the last layer. I thought if broke out the "alias" area and then built on that I'd be set but I did something wrong. From BeshrKayali at gmail.com Sat Mar 15 06:03:21 2008 From: BeshrKayali at gmail.com (E-Lo) Date: Sat, 15 Mar 2008 03:03:21 -0700 (PDT) Subject: Python for Palm OS Message-ID: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Is there any other edition of Python for Palm OS instead of Pippy? From Lie.1296 at gmail.com Sun Mar 16 05:55:51 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 16 Mar 2008 02:55:51 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: <210b2a22-a8e3-414e-9018-15f7d74c9f83@d4g2000prg.googlegroups.com> <64172eF29qj9jU1@mid.uni-berlin.de> Message-ID: <02533def-ccd8-483d-b041-30ec26cfa4e5@s8g2000prg.googlegroups.com> On Mar 15, 1:01?pm, Marc 'BlackJack' Rintsch wrote: > On Fri, 14 Mar 2008 11:32:41 -0700, Lie wrote: > > No, there is no need for "void" return type, what I meant is that > > everything that's not said in the documentation should be assumed to > > be an implementation detail, a method or a function that doesn't say > > anything about its return type should be assumed to return an > > implementation detail (which basically means: Don't rely on this). The > > fact that list.append returns none is just a coincidence, you might > > encounter another list.append that returns different thing some time > > in the future, or the far future, or perhaps at the end of the > > galaxy's life. > > I expect functions with no documentation of what they return to return > `None`. ?Assuming they are documented at all, of course. ?:-) > > It's like not writing a ``return`` statement in the code: there's always an > implicit ``return None`` at the end of every function. I personally won't to rely on it. Sometimes a return statement might be documented, but not complete enough, like this: def genericadd(a, b): """ Adds two number, returns the same as longadd if either operands are long type and returns the same as intadd if all operands are int type. """ if isinstance(a, long) or isinstance(b, long): return longadd(a, b) if isinstance(a, int) and isinstance(b, int): return intadd(a, b) return "Error" This function is written badly on purpose to simulate what a less-than- intelligent programmer might write, which is in no control of ours as a class user. From larry.cebuala at gmail.com Wed Mar 12 06:26:58 2008 From: larry.cebuala at gmail.com (Larry) Date: Wed, 12 Mar 2008 03:26:58 -0700 (PDT) Subject: frequency count or number of occurences of a number in an array Message-ID: <1525f954-8060-42ae-8b77-d887a84c27da@e25g2000prg.googlegroups.com> Dear all, I'm new to Python. I have a file (an image file actually) that I need to read pixel by pixel. It's an 8-bit integer type. I need to get the statistics like mean, standard deviation, etc., which I know a little bit already from reading numpy module. What I want to know is how to get the number of occurences of numeric element in an array. Say, b = array(([2, 2, 3, 4, 5, 5]) b.count(2) certainly does not work. Is there any more efficient way other than converting this as string characters? My data will produce a fairly large array like 400x400 = 160000 values. Hoping you guys can help me. Larry From castironpi at gmail.com Sun Mar 2 13:33:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 2 Mar 2008 10:33:07 -0800 (PST) Subject: Question on importing and function defs References: <30e4a789-1ed6-4034-9416-63edb50a354e@m34g2000hsc.googlegroups.com> <5afb0546-c22d-45b3-8a80-2e36c394b1c7@h11g2000prf.googlegroups.com> Message-ID: <04a7dfa1-a28b-4b52-aa3d-24b57bdbba3e@i29g2000prf.googlegroups.com> On Mar 2, 11:44?am, Steve Holden wrote: > TC wrote: > > On Mar 2, 11:37 am, Gary Herron wrote: > >> TC wrote: > >>> I have a problem. ?Here's a simplified version of what I'm doing: > >>> I have functions a() and b() in a module called 'mod'. ?b() calls a(). > >>> So now, I have this program: > >>> from mod import * > >>> def a(): > >>> ? ? blahblah > >>> b() > >>> The problem being, b() is calling the a() that's in mod, not the new > >>> a() that I want to replace it. ?(Both a()'s have identical function > >>> headers, in case that matters.) ?How can I fix this? > >>> Thanks for any help. > >> Since b calls mod.a, you could replace mod.a with your new a. ?Like > >> this: ?(Warning, this could be considered bad style because it will > >> confuse anyone who examines the mod module in an attempt to understand > >> you code.) > > >> ? import mod > > >> ? def replacement_a(): > >> ? ? ... > > >> ? mod.a = replacement_a > > >> ? ... > > >> Or another option. ?Define b to take, as a parameter, the "a" function > >> to call. > > >> In mod: > > >> ? def a(): > >> ? ?... > > >> ? def b(fn=a): ?# to set the default a to call > >> ? ? ... > > >> And you main program: > > >> ? from mod import * > > >> ? def my_a(): > >> ? ? ... > > >> ? b(my_a) > > >> Hope that helps > > >> Gary Herron > > > Thanks for the tips, but no luck. ?This is for a homework assignment, > > so there are a couple of requirements, namely that I can't touch > > 'mod', and I have to do 'from mod import *' as opposed to 'import > > mod'. > > > So the first method you suggested won't work as written, since the mod > > namespace doesn't exist. ?I tried a = replacement_a, but b() is still > > calling mod's version of a() for some reason. ?And because I can't > > touch mod, I can't use your second suggestion. > > > In case I somehow oversimplified, here's the actual relevant code, in > > 'mod' (actually called 'search'). ?The first fn is what I've been > > calling a(), the second is b(). > > > (lots of stuff...) > > > def compare_searchers(problems, header, > > searchers=[breadth_first_tree_search, > > ? ? ? ? ? ? ? ? ? ? ? breadth_first_graph_search, > > depth_first_graph_search, > > ? ? ? ? ? ? ? ? ? ? ? iterative_deepening_search, > > depth_limited_search, > > ? ? ? ? ? ? ? ? ? ? ? astar_search]): > > ? ? def do(searcher, problem): > > ? ? ? ? p = InstrumentedProblem(problem) > > ? ? ? ? searcher(p) > > ? ? ? ? return p > > ? ? table = [[name(s)] + [do(s, p) for p in problems] for s in > > searchers] > > ? ? print_table(table, header) > > > def compare_graph_searchers(): > > ? ? compare_searchers(problems=[GraphProblem('A', 'B', romania), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? GraphProblem('O', 'N', romania), > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? GraphProblem('Q', 'WA', australia)], > > ? ? ? ? ? ? header=['Searcher', 'Romania(A,B)', 'Romania(O, N)', > > 'Australia']) > > > That's the end of the 'search' file. ?And here's my program, which > > defines an identical compare_searchers() with an added print > > statement. ?That statement isn't showing up. > > > from search import * > > > def compare_searchers(problems, header, > > searchers=[breadth_first_tree_search, > > ? ? ? ? ? ? ? ? ? ? ? breadth_first_graph_search, > > depth_first_graph_search, > > ? ? ? ? ? ? ? ? ? ? ? iterative_deepening_search, > > depth_limited_search, > > ? ? ? ? ? ? ? ? ? ? ? astar_search, best_first_graph_search]): > > ? ? def do(searcher, problem): > > ? ? ? ? p = InstrumentedProblem(problem) > > ? ? ? ? searcher(p) > > ? ? ? ? return p > > ? ? table = [[name(s)] + [do(s, p) for p in problems] for s in > > searchers] > > ? ? print 'test' > > ? ? print_table(table, header) > > > compare_graph_searchers() > > Since you've admitted it's for homework, here are a couple of hints. > > 1. The b() function is *always* going to try and resolve its references > in the namespace it was defined in; > > 2. The technique you need is most likely known as "monkey patching". > When you say "I can't touch mod", that may mean "the source of mod must > remain unchanged", which is subtly different. Google is your friend ... > > Good luck with your assignment. > > regards > ? Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/- Hide quoted text - > > - Show quoted text - You can use 'settrace' to intervene. You might be able to delete the 'a'. From paddy3118 at googlemail.com Sun Mar 23 12:14:47 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 23 Mar 2008 09:14:47 -0700 (PDT) Subject: Testing for an empty dictionary in Python References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: On Mar 23, 3:53 pm, John Nagle wrote: > What's the cheapest way to test for an empty dictionary in Python? > > if len(dict.keys() > 0) : > > is expensive for large dictionaries, and makes loops O(N^2). > > John Nagle As others have stated, if : is false for built-in container types such as dicts, lists, sets, tuples,... Its nice to make any of your owh container types follow the same convention too. - Paddy. From kmgrds at gmail.com Sun Mar 30 16:21:26 2008 From: kmgrds at gmail.com (kmgrds at gmail.com) Date: Sun, 30 Mar 2008 13:21:26 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig Message-ID: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> Hello everybody, I'm building a python module to do some heavy computation in C (for dynamic time warp distance computation). The module is working perfectly most of the time, which makes it so difficult to track down the error. and I finally figured out that the strange segmentation faults I get from time to time have something to do with the length of the vectors I'm looking at. (So in this minimal example I'm doing completely useless distance measures on vectors with the same entry in all dimensions, but the errors seem to have nothing to with the actual values in the vectors, only with the lengths.) But somehow I haven't quite gotten the essential ideas of what one has to do to debug this module and I hope someone can give me some advice. The main problem is probably somewhere around passing the double vectors to the c module or reserving and freeing memory. so, for example list1,list2 = [0.1 for i in range(555)],[0.2 for i in range(1874)] ctimewarp(list1,list2) # see python file below works perfectly fine and if the vector has one more element list1,list2 = [0.1 for i in range(555)],[0.2 for i in range(1875)] ctimewarp(list1,list2) it dies with a simple Segmentation fault nothing more said :-S For very small lists again, no problem: list1,list2 = [0.1 for i in range(3)],[0.2 for i in range(4)] ctimewarp(list1,list2) for intermediate size I get an error and more information: list1,list2 = [0.1 for i in range(22)],[0.2 for i in range(99)] ctimewarp(list1,list2) give: *** glibc detected *** python: free(): invalid next size (fast): 0x0804d090 *** ======= Backtrace: ========= /lib/i686/libc.so.6[0xb7bed4e6] /lib/i686/libc.so.6(cfree+0x90)[0xb7bf1010] /home/kim/Documents/pythonprojects/alignator/ _timewarpsimple.so[0xb7aadc0c] /home/kim/Documents/pythonprojects/alignator/ _timewarpsimple.so[0xb7aae0db] /usr/lib/libpython2.5.so.1.0(PyCFunction_Call+0x107)[0xb7d5d8e7] ======= Memory map: ======== 08048000-08049000 r-xp 00000000 03:05 2344438 /usr/bin/python 08049000-0804a000 rwxp 00000000 03:05 2344438 /usr/bin/python 0804a000-080f3000 rwxp 0804a000 00:00 0 [heap] ....(truncated) When looping over these lengths of vectors, e.g. as I did in the python file below, it runs smooth for thousands of times before dying at 938 for the first list length and 1110 for the second. i noticed that the sum of the list lengths is 2048=2^11 and it often seems to die around that but that's just a guess... If anyone has a little advice or a code snippet on how to pass float lists to modules or anything of that kind, i would appreciate it very much! thanks a lot in advance cheers kim __________________________________ Below you can see the c file, the .i file for swig, and a little python script producing the errors: _______________ .c file: /* File : timewarpsimple.c */ #include #include #include double timewarp(double x[], int lenx, double y[], int leny) { // printf ("%d *******************************\n", lenx); // printf ("%d *******************************\n", leny); double prev; double recx[lenx+1]; double recy[leny+1]; double warp[lenx+2][leny+2]; int i,j; prev = 0.0; for (i = 0; i < lenx; i++) { recx[i]=x[i]-prev; prev = x[i]; } recx[lenx]=1.0-prev; prev = 0.0; for (i = 0; i < leny; i++) { recy[i]=y[i]-prev; prev = y[i]; } recy[leny]=1.0-prev; // recency vectors are done // let's warp warp[0][0]=0.0; for (i = 1; i < lenx+2; i++) { warp[i][0]=1.0; } for (j = 1; j < leny+2; j++) { warp[0][j]=1.0; } for (i = 1; i < lenx+2; i++) { for (j = 1; j < leny+2; j++) { warp[i][j]=fabs(recx[i-1]-recy[j-1]) + MIN(MIN(warp[i-1][j],warp[i] [j-1]),warp[i-1][j-1]); } } return warp[lenx+1][leny+1]; } ________________ .i file: %module timewarpsimple %include "carrays.i" %array_functions(double, doubleArray); %{ double timewarp(double x[], int lenx, double y[], int leny); %} double timewarp(double x[], int lenx, double y[], int leny); ________________ here's what I'm doing to compile: swig -python timewarpsimple.i gcc -c timewarpsimple.c timewarpsimple_wrap.c -I/usr/include/ python2.5/ ld -shared timewarpsimple.o timewarpsimple_wrap.o -o _timewarpsimple.so which goes thru without any problem. ________________ .py file: #!/usr/bin/python # -*- coding: UTF-8 -*- import timewarpsimple def ctimewarp(list1,list2): """ takes two lists of numbers between 0 and 1 and computes a timewarp distance """ print "timewarping" alen = len(list1) blen = len(list2) a = timewarpsimple.new_doubleArray(alen*4) # Create the first array # Why I have to reserve 4 times more space I don't know, but it's the only way to make it work... b = timewarpsimple.new_doubleArray(alen*4) # Create the second array for i,p in enumerate(list1): timewarpsimple.doubleArray_setitem(a,i,p) # Set a value. (a,i,0) gives identical errors for i,p in enumerate(list2): timewarpsimple.doubleArray_setitem(b,i,p) # Set a value warp = timewarpsimple.timewarp(a,alen,b,blen) print "result",warp timewarpsimple.delete_doubleArray(a) timewarpsimple.delete_doubleArray(b) #a,b = None,None return warp ########## the tests: #list1,list2 = [0.1 for i in range(22)],[0.2 for i in range(99)] #ctimewarp(list1,list2) for x in range(888,1111): for y in range(888,1111): list1,list2 = [0.1 for i in range(x)], [0.2 for i in range(y)] print len(list1),len(list2),len(list1)+len(list2) ctimewarp(list1,list2) From stef.mientki at gmail.com Fri Mar 14 05:32:11 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 14 Mar 2008 10:32:11 +0100 Subject: how to pass the workspace ? In-Reply-To: <13tk7796gt4u3b7@corp.supernews.com> References: <47D72CDD.9000706@gmail.com> <47D733A7.2070808@islandtraining.com> <13tk7796gt4u3b7@corp.supernews.com> Message-ID: <47DA461B.1010703@gmail.com> Thanks, Gary and Dennis, Dennis Lee Bieber wrote: > On Thu, 13 Mar 2008 21:35:42 +0100, Stef Mientki > declaimed the following in comp.lang.python: > > > >> The result of globals and locals in the file is eaxctly the same and >> none of them mentions 'NewVar' and 'beer' >> The result of tree_globs and tree_locals is exactly the same and both >> doesn't contain 'NewVar' and 'beer' >> Maybe it's very simple after reading the manual, >> but apperently I'm missing the essential clue. >> What am I missing ? >> >> > Use of globals() and locals() vs globals and locals? > Well I get an error with that. But you both give me some ideas, and it's working now: - I don't need the locals - from the file where the execute is launched, you must use the normal dictionary call tree_globs = {} tree_globs [ 'NewVar' ] = 24 filename = self.Get_Editor_Filename (nodename) execfile ( filename, tree_globs ) print self.tree_globs['NewVar'] print self.tree_globs['beer'] where the code in the executed file is: beer = 'testje' the output I get is: 24 testje and the "self.tree_globs" travels perfectly though all the files executed. cheers, Stef From SubjectEgo at gmail.com Thu Mar 20 23:05:29 2008 From: SubjectEgo at gmail.com (Jeremy N) Date: Thu, 20 Mar 2008 20:05:29 -0700 (PDT) Subject: Trouble with variable "leakage"? Message-ID: I am working with Python in Maya, and have run into a problem with a variable changing its contents without being scripted to do so. The various print() statements below were from my efforts to track down where it was occurring. I left them in so that anyone running this will more easily see what's happening. On the line that reads 'dx = d1 / dx ; print("dx = %f" % dx)' there is something happening to the variable that is being printed repeatedly between the lines. The print statements prior to this particular line print '...xlist[0][1] = 0.5' . However, on this line, that variable is being updated to reflect a new value, when no assignment to that variable has been made at that time. This leads me to believe that the variables 'dx' and 'xlist[0][1]' are inexplicably linked. I have no idea why. Please help me. a=[5,0,3,4] b=[8,3,0,10] c=[2,4,10,0] nlist = [a,b,c] xlist = [[],[],[]] for i in range(len(nlist)) : relist = list(nlist) relist.pop(i) dlist = list(nlist[i]) dlist.pop(0) ; dlist.pop(i) for j in range(len(relist)) : d1 = float(nlist[i][0]) d2 = float(relist[j][0]) dx = float(dlist[j]) r1 = 1 - ( abs(d1-dx) / float(d2) ) if r1 == 0.0 : r1 += (d1 < d2) xlist[i].append(float(r1)) del d1, d2, dx, relist, dlist ylist = list(xlist) print(xlist) print(ylist) for i in range(len(xlist)) : relist = list(xlist) relist.pop(i) for j in range(len(relist)) : print( "!!!!!!!!!!!!!!! NEW LOOP AT ( %d:%d ) !!!!!!!!!!!!!!!" % ( i, j ) ) print("%s / (%s + %s)" % ( str(xlist[i][j]), str(xlist[i][j]), str(relist[j][( (i!=0) * ((j>=i)+(i-1)) )]) ) ) d1 = float(xlist[i][j]) ; print("d1 = %f" % d1) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) d2 = relist[j][( (i!=0) * ((j>=i)+(i-1)) )] ; print("d2 = %f" % d2) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) dx = d1 + d2 ; print("dx = %f" % dx) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) dx = d1 / dx ; print("dx = %f" % dx) ylist[i][j] = float(dx) ; #print(ylist[i][j]) print( "...xlist[0][1] = %s" % str(xlist[0][1]) ) print( "||| xlist[2][0] = %s" % str(xlist[2][0]) ) print( "...\nxlist = %s\n..." % str(xlist) ) print(xlist) print(ylist) From michael.wieher at gmail.com Sun Mar 16 10:05:19 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Sun, 16 Mar 2008 09:05:19 -0500 Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? In-Reply-To: <20080316132140.GA24529@piper.oerlikon.madduck.net> References: <20080316132140.GA24529@piper.oerlikon.madduck.net> Message-ID: 2008/3/16, martin f krafft : > > Hi, > > xmlrpclib.dumps((None,), allow_none=True) yields > > '\n\n\n\n' > > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' > > Those are valid XML and valid XML-RPC, but isn't. > > Thanks for any thoughts... > > > -- > martin | http://madduck.net/ | http://two.sentenc.es/ > > a farmer is a man outstanding in his field. > > spamtraps: madduck.bogus at madduck.net No real idea, but to me it seems like a decent way to be double-sure that you actually got the complete and correct dump-file... otherwise, you might be just missing part of it... maybe there's a real reason though? -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.wieher at gmail.com Mon Mar 17 14:36:22 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 13:36:22 -0500 Subject: Missing PyObject definition In-Reply-To: <-eidnZbyjq-bAkPanZ2dnUVZ_rOqnZ2d@comcast.com> References: <34mdnca0RdXKF0PanZ2dnUVZ_oWdnZ2d@comcast.com> <-eidnZbyjq-bAkPanZ2dnUVZ_rOqnZ2d@comcast.com> Message-ID: 2008/3/17, James Whetstone : > > Hi, > > Yeah, I've included python.h and object.h but the compiler still complain > about not finding PyObject. It's weird. So I'm developing and App on > windows using VS 8.0. I've intalled Python 2.5 and have added the include > directory to my project's configuration. I'm also using boost.python in > another application to wrap my C++ classes. > > Here's the C++ class I'm wrapping: > > class widget > { > > public: > > widget(const string &name, unsigned int myint) : > { > > } > > static unsigned int __stdcall Callback(void * voidPtr); > void startMessageHandler(); > void stopMessageHandler(); > virtual void handleMessage(void *message)=0; > > }; > > So the idea here is that the Python user will derive from widget and > override the virtual method "handleMessage". A thread is spawned by > "startMessageHandler()" that does some work and periodically calls > "handleMessage" passing it a chunk of memory. This memory is intended to > be > zero-copy. Okay, so I've implemeted this class to set up the class for > Python: > > class py_widget : public widget > { > public: > py_widget(PyObject *p, const string &name, unsigned int myint) : > self(p), > py_widget(name, myint) > { > } > > void handleMessage(void *message); > > PyObject *self; > > }; > > where handleMessage has the following implementation: > > void PyAsyncQueue::handleMessage(void *message) > { > //get the memory block size with a method not shown here > int size = getSize(message); > > //create a buffer object so the Python users can access memory block > directly. > > PyObject *obj = PyBuffer_FromReadWriteMemory( message, size ) ; > > //now what ???? > > //I've tried calling the method directly based on some info I found > some documentation, but this doesn't > //compile because the compile can't find PyObject. Also, I really > know > what it looks like anyways. > //self->attr("handleMessage")(obj); > > //This boost.python call doesn't work either. > //call_method(self, "handleMessage", obj); > } > > > Thanks for your suggestions on this, > James > > > > "Jeff Schwab" wrote in message > news:mvadnfg_hOdmDEPanZ2dnUVZ_u2mnZ2d at comcast.com... > > James Whetstone wrote: > >> I'm trying to access a PyObject directly from C++ for the purpose of > >> calling method on a Python object that is an intance of a derived C++ > >> class. My problem is that the compiler is complaining about not > PyObject > >> not being defined. Has anyone run into the problem? Where is PyObject > >> defined? > > > > Are you using Python's C API? > > > > Did you #include "Python.h" before using PyObject? > > > > PyObject is a C-style struct defined in object.h, which is in turn > > included by Python.h. Does your compiler know where to look for those > > headers? If you are getting messages of the form "error: cannot find > > Python.h," then add -Iyour_python_root/include/python2.5 (or whatever > > version) to the CXXFLAGS variable in your makefile, or to your > compiler's > > command line. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > If you're using MS-Visual Studio, be sure you really included the file where you think you did... I ran into some stupidity of my own, trying to put include files in the "library" path and vice versa. If you have "Python.h" included properly, you should be able to compile some small test-code using PyObject. If you can't, you haven't got it included correctly. That's where I'd start. If there's other bugs in your code, thats a different issue, but if the compiler can't find class-X defined in file-Y, then you need to double-check your include, include-path, and so on and so forth. Also, don't forget that just because the include directory is on your project's path, that the actual file itself needs to be included. When running in VS 6.0 I had to place my includes in some awfully strange places. Redundant includes don't hurt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Mar 21 03:32:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 21 Mar 2008 00:32:40 -0700 (PDT) Subject: decoupling a certain method Message-ID: <04f0a593-c47d-4c50-ad8e-d81d0cfa40a7@m44g2000hsc.googlegroups.com> class Proxy: def __init__( self, proxer ): object.__setattr__( self, '_proxer', proxer ) ComplexObject= object viewA= type( 'ComplexView', ( Proxy, ComplexObject ), { '__eq__': lambda self, other: abs( self._proxer- other )<= 1 } ) j= range( 10 ) g= 5 for a in j: p= viewA( a ) print( p.__class__.__name__, p._proxer, p== g ) Subclassing provides an alternative to delegation and proxying. I got this far, but I'm lost: How do I allow g= proxy( 5 ) in line 11? Do I need to? If I do it, I get: TypeError line 7: unsupported operand type(s) for -: 'int' and 'ComplexView' From troyj1978 at gmail.com Thu Mar 13 16:16:05 2008 From: troyj1978 at gmail.com (troyj1978 at gmail.com) Date: Thu, 13 Mar 2008 13:16:05 -0700 (PDT) Subject: This actually works. Message-ID: <8d63a318-0954-44e8-83de-061f802745d2@s13g2000prd.googlegroups.com> I couldn't believe it. Screw programming Python anymore! I'm totally serious. This actually works! It is SO EASY to make money this way. Anyone, and I mean ANYONE can do it. You should start seeing returns within a day or two. Do yourself a favour and at least check it out: http://agentb.affstocks.hop.clickbank.net/ Troy From shakefu at gmail.com Fri Mar 7 17:08:18 2008 From: shakefu at gmail.com (shakefu at gmail.com) Date: Fri, 7 Mar 2008 14:08:18 -0800 (PST) Subject: Intelligent Date & Time parsing Message-ID: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> I'm new to python and I was wondering if there are any intelligent date/time parsing modules out there. I've looked at strptime (or whichever it is) and mxDateTime from the eGenix package. I need something to parse user input for a django app, and it's awesome to be able to write "last monday", "a year ago", or "10pm tuesday" like PHP's strtotime. So are there any modules that allow for that kind of parsing? From sambo at voidstar.com Thu Mar 6 22:35:18 2008 From: sambo at voidstar.com (Sam) Date: Thu, 06 Mar 2008 22:35:18 -0500 Subject: access to base class __init__ References: <13suutrsb4bab8b@corp.supernews.com> Message-ID: Dennis Lee Bieber wrote: > > I'm not sure why you need to subclass from threading.Thread if all > the thread control is being done internal to this class. Subclassing > means being able to do things like: > Well it was the first thing that occured to me how to have private data for each thread ( IP, PORT , CURDIR if I decide to serve files. ) although I did come across some private_data CLASS in the docs. > mySH = client_socket_handler(some, args) > ... > mySh.start() hope I can call self.start() from __init__() or self.socket_handler() > > ... ie; instances of your class behave just like an extended instance of > the Thread class; but the user of this class never sees that it IS a > thread. I believe the other facet is that when subclassing from Thread, > one overloads the run() method AS the target instead of passing some > other function as a target argument and letting the parent run() method > call it. > > > So why not just make the thread an attribute of the class instead. > > Maybe that would be clearer. Starting to wonder if I could return thread name this way, then again, I think part reason for this aproach was the fact that once started it could finish/crash all on it's lonesome and it's instance could wait for garbage collection. >> self.socket = cs >> self.rhost_addr = remote_address >> print "client_socket_handler.__init__(): ", self.socket, >> self.rhost_addr >> # t1 = threading.Thread( None,self.socket_handler, None, (5,78) ) >> # t1.start() > > Which is about what you were doing here, but should have used > self.t1 =... > self.t1.start() > Well this shouldn't realy be here just stuff I pasted over. Which brings me to a question how to start my thread internaly. Once I managed to call __init__() I should be able to call self.start() nicht var? or is it vahr? >> self.start() >> print "client_socket_handler.__init__(): ", self.socket, >> self.rhost_addr >> print "client_socket_handler.__init__(): enumerate()", >> threading.enumerate() >> >> def socket_handler( self, invar, indict ): > > You aren't passing any arguments to this method. > >> threadname = self.getName() >> print "\"%s started\"" % threadname >> print "client_socket_handler.socket_handler() invar: ", invar >> instr = self.socket.recv( 500 ) >> # print instr >> req_lines = string.split( instr, "\r" ) >> for line in req_lines: >> line.strip( "\n") > > What do you expect the behavior to be if a new-line is embedded and > not adjacent to a carriage return? > oops: #handle macs self.socket.send( "500 Inferior systems not permited.\r\n" ) self.socket.close() Heh. Besides I don't think NL is permisible as line separator. the command is at the beginnign and I don't expect to support any multitude of tags. From tejovathi.p at gmail.com Thu Mar 20 06:40:54 2008 From: tejovathi.p at gmail.com (Teja) Date: Thu, 20 Mar 2008 03:40:54 -0700 (PDT) Subject: Regarding Threads and locals() Message-ID: <8171f7f2-1bd6-4518-b678-c6267870b05b@h11g2000prf.googlegroups.com> Hi all, I have a GUI applicaion(along with threads). When the run button is pressed in the GUI a separate thread starts( Thread is created using beginthreadex) and does the required activity. Now, while the thread is being executed, i want the locals() present inside the thread's run function to be avaialbe in the GUI class from where the thread class is being created EG: ---------------------- main.py -------------------------- class WorkerThread(threading.Thread): def __init__(self, ): threading.Thread.__init__(self) # Start the thread and invoke the run method self.start() def run(self): # Start the thread. It executed self.func() as a separate thread self.workerThread, tid = win32process.beginthreadex(None, 0 , self.func ,(), 1) ....... def func(self): execfile(temp.py) class GUI(wxFrame): def __init__(self): ..... ..... def CreateThread(self): self.workerThread = WorkerThread() if name == _main_: ..... . .... . ..... --------------------- temp.py ------------------ i = 1 j = 2 k = 4 while(10000): print i print j print k i = 1+1 j = j+2 k = k + 3 Now, while the thread is executin func and printing i, j, k , In the main GUI thread how do i get the values of i, j ,k I tried with sys.modules, sys._current_frames, vars(). But nothing worked out. Ideally the locals() of func() should be passed to the GUI thread, how? From R.Brodie at rl.ac.uk Fri Mar 14 11:58:58 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 14 Mar 2008 15:58:58 -0000 Subject: %x unsigned? References: <87skytbbbc.fsf@mulj.homelinux.net> Message-ID: "Hrvoje Niksic" wrote in message news:87skytbbbc.fsf at mulj.homelinux.net... > The %x conversion specifier is documented in > http://docs.python.org/lib/typesseq-strings.html as "Unsigned > hexadecimal (lowercase)." What does "unsigned" refer to? It's obsolete, a fallout of int/long int unification. See http://www.python.org/dev/peps/pep-0237/ From michael.wieher at gmail.com Wed Mar 19 12:24:44 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 19 Mar 2008 11:24:44 -0500 Subject: Python to C/C++ In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: I think py2exe does this, but it might be a bit bloated 2008/3/19, Blubaugh, David A. : > > To All, > > Has anyone worked with a translator that will translate python to c/c++ > source code? I know that there is already one translator of this nature (shedskin > compiler) out there. However, it is still in the beta stage of > development. Does anyone know of a more developed version of a translator > of this nature? > > Thanks, > > David Blubaugh > > This e-mail transmission contains information that is confidential and may > be privileged. It is intended only for the addressee(s) named above. If > you receive this e-mail in error, please do not read, copy or disseminate it > in any manner. If you are not the intended recipient, any disclosure, > copying, distribution or use of the contents of this information is > prohibited. Please reply to the message immediately by informing the sender > that the message was misdirected. After replying, please erase it from your > computer system. Your assistance in correcting this error is appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun Mar 9 12:55:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 09 Mar 2008 14:55:15 -0200 Subject: help on file storage for split multi part download References: <0c422a07-3c07-499f-87da-f82a6a81ed52@s37g2000prg.googlegroups.com> Message-ID: En Sat, 08 Mar 2008 08:27:12 -0200, escribi?: > On Mar 7, 2:14 pm, "Gabriel Genellina" wrote: >> En Fri, 07 Mar 2008 04:16:42 -0200, escribi?: >> >> > BUT the thing thats going in my mind is thread safety. i plan to start >> > each part of the filedownloadin a different thread. and then when >> > each thread had downloaded more than 100kb (or eof or boundary >> > reached) write the buffer to the disk. can this be achieved using >> > mutex ? i have never shared objects between threads. >> >> Use a different (single) thread to write the file; the others put write >> requests on a Queue.queue object, and the writer just gets the requests >> and processes them. >> >> > is there a way to write this without using threads at all ??? >> >> Using asyncore, and perhaps the Twisted framework. > > asyncore is basically a server thing right? asyncore is usually used to build servers, because in a server you want to handle many requests with few resources, but you can use it to write a client too. Here is an example: http://effbot.org/zone/asyncore-ftp-client.htm How many files and how many simultaneous connections do you plan to handle? Using multiple threads to download and a single thread to write, connected thru a queue, looks like the "simplest thing that probably works" to me unless you have other constraints. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Mar 18 22:58:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 23:58:15 -0300 Subject: Comunicate processes with python References: <267c4040803171416y370a9ee1w993ca0f935cb367d@mail.gmail.com> <267c4040803180216q20f66e30mb1c59928b22c66b0@mail.gmail.com> <267c4040803181040q2a70b91w8f92ff59359843fb@mail.gmail.com> Message-ID: En Tue, 18 Mar 2008 14:40:29 -0300, Adri?n Bravo Navarro escribi?: > That was what we were thinking of, so if there is not some kind of easy > python magic we will probably use some sockets. You have pipes too, and a memory mapped file guarded by a semaphore. -- Gabriel Genellina From Dodin.Roman at gmail.com Mon Mar 17 13:22:31 2008 From: Dodin.Roman at gmail.com (hellt) Date: Mon, 17 Mar 2008 10:22:31 -0700 (PDT) Subject: py2exe + pywinauto + sendkeys issue References: <30f32324-711e-499c-9f2b-c7014f120fe4@s50g2000hsb.googlegroups.com> Message-ID: <9192affb-3a3f-4558-909b-d9734c1b1ad2@u10g2000prn.googlegroups.com> On 17 ???, 15:48, "Gabriel Genellina" wrote: > En Mon, 17 Mar 2008 08:56:26 -0200, hellt escribi?: > > > i have a problem with this modules py2exe + pywinauto + sendkeys used > > together. > > > In my script i'm using this expression > > app.window_(title="SJphone").Edit.TypeKeys("Test is > > running",with_spaces=True) > > > TypeKeys is using SendKeys module i suppose. > > Does it work as a normal script, without using py2exe? > > > my setup.py looks like that: > > > from distutils.core import setup > > import py2exe > > > setup( > > options = {"py2exe": {"compressed": 1, > > "optimize": 0, > > "bundle_files": 1, > > "packages": ["encodings", "pywinauto", > > "pywinauto.controls", "pywinauto.tests"] } }, > > zipfile = None, > > console=["hosts.py"] > > ) > > Perhaps you have to include SendKeys explicitely. I think pywinauto > doesn't require SendKeys, but uses it if already installed. > > -- > Gabriel Genellina pywinauto uses sendkeys when performs TypeKeys function. when i include sendkeys to my package's list i have an error posted below: "No module named SendKeys" From deets at nospam.web.de Wed Mar 26 07:02:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 12:02:18 +0100 Subject: _tkinter fails when installing Python 2.4.4 References: <64tahuF2absebU1@mid.uni-berlin.de> <4a13f8fc-f6da-4677-8af4-70f0ebe482d1@a1g2000hsb.googlegroups.com> Message-ID: <64uoqiF2dcihhU1@mid.uni-berlin.de> jgelfand wrote: > On Mar 25, 5:52 pm, "Diez B. Roggisch" wrote: >> jgelfand schrieb: >> >> >> >> > I'm installing Python 2.4.4 on a CentOS release 4.6 (Final) [RedHat >> > Enterprise Linux 4.6] 64-bit machine. Running "./configure --prefix="/ >> > usr/local/yosi/ciao-4.0/ots" --enable-shared" appears to be fine, but >> > I get the following error message when I run "make": >> >> > building '_tkinter' extension >> > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - >> > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ >> > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ >> > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ >> > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ >> > yosi/Python-2.5.2/Modules/_tkinter.c -o build/temp.linux-x86_64-2.5/ >> > usr/local/yosi/Python-2.5.2/Modules/_tkinter.o >> > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - >> > Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/ >> > local/yosi/Python-2.5.2/./Include -I/usr/local/yosi/ciao-4.0/ots/ >> > include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/ >> > yosi/Python-2.5.2/Include -I/usr/local/yosi/Python-2.5.2 -c /usr/local/ >> > yosi/Python-2.5.2/Modules/tkappinit.c -o build/temp.linux-x86_64-2.5/ >> > usr/local/yosi/Python-2.5.2/Modules/tkappinit.o >> > gcc -pthread -shared build/temp.linux-x86_64-2.5/usr/local/yosi/ >> > Python-2.5.2/Modules/_tkinter.o build/temp.linux-x86_64-2.5/usr/local/ >> > yosi/Python-2.5.2/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/ >> > lib -L/usr/local/yosi/ciao-4.0/ots/lib -L/usr/local/lib -L. -ltk8.5 - >> > ltcl8.5 -lX11 -lpython2.5 -o build/lib.linux-x86_64-2.5/_tkinter.so >> > *** WARNING: renaming "_tkinter" since importing it failed: build/ >> > lib.linux-x86_64-2.5/_tkinter.so: undefined symbol: XftGlyphExtents >> >> > Any suggestions / ideas as to what is going wrong? I don't get any >> > other warnings or errors on the other modules. Thanks -- Yosi >> >> You are aware that the above shows python 2.5 as the version that is >> being used for compilation? >> >> Diez > > Sorry. I get the same error messages for Python 2.4.4, Python 2.4.5, > and Python 2.5. The software package I'm trying to build from source > requests that I install Python 2.4.4, so I'm interesting in solutions > for that particular distribution. I think the actual problem is that the linking doesn't find the XftGlyphExtends. I can only guess, but it might be related to 64-bit-problems. Make sure you have the library that contains the XftGlyphExtends is available in the lib64 dirs and so forth. Diez From torriem at gmail.com Sat Mar 1 21:50:52 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Mar 2008 19:50:52 -0700 Subject: Question about lambda and variable bindings Message-ID: <47CA160C.3000305@gmail.com> I need to use a lambda expression to bind some extra contextual data (should be constant after it's computed) to a call to a function. I had originally thought I could use something like this demo (but useless) code: funcs=[] def testfunc(a,b): print "%d, %d" % (a,b) for x in xrange(10): funcs.append(lambda p: testfunc(x+2,p)) Now what I'd like is to call, for example, funcs[0](4) and it should print out "2,4". In other words I'd like the value of x+2 be encoded into the lambda somehow, for funcs[x]. However the disassembly shows this, which is reasonable, but not what I need: >>> dis.dis(funcs[0]) 2 0 LOAD_GLOBAL 0 (testfunc) 3 LOAD_GLOBAL 1 (x) 6 LOAD_CONST 0 (2) 9 BINARY_ADD 10 LOAD_FAST 0 (p) 13 CALL_FUNCTION 2 16 RETURN_VALUE The LOAD_GLOBAL 1 (x) line is definitely a problem. For one it refers to a variable that won't be in scope, should this lambda be called from some stack frame not descended from the one where I defined it. So how can I create a lambda expression that calculates a constant based on an expression, rather than referring to the object itself? Can it be done? Michael From max at alcyone.com Thu Mar 13 19:30:49 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 13 Mar 2008 16:30:49 -0700 Subject: getattr(foo, 'foobar') not the same as foo.foobar? In-Reply-To: References: Message-ID: <-cudnSGj6P-2JETanZ2dnUVZ_vShnZ2d@speakeasy.net> Dave Kuhlman wrote: > Basically, the above code is saying that foo.foobar is not the same as > getattr(foo, 'foobar'). Python promises that the behavior is the same. It does not promise that the _objects_ will be the same, which is what `is` determines. That is, you're not doing a useful test here. In Python, bound methods are dynamically generated. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There is no present or future; only the past, happening over and over again, now. -- Eugene O'Neill From tmp1 at viltersten.com Mon Mar 3 15:21:17 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Mon, 3 Mar 2008 21:21:17 +0100 Subject: Polymorphism using constructors Message-ID: <6333v2F25lleoU1@mid.individual.net> I'm writing a class for rational numbers and besides the most obvious constructor def __init__ (self, nomin, denom): i also wish to have two supporting ones def __init__ (self, integ): self.__init__ (integ, 1) def __init__ (self): self.__init__ (0, 1) but for some reason (not known to me at this point) i get errors. My suspicion is that it's a syntax issue. Suggestions? -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From darcy at druid.net Sun Mar 30 11:28:27 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 30 Mar 2008 11:28:27 -0400 Subject: License of Python In-Reply-To: <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> Message-ID: <20080330112827.0c5dc431.darcy@druid.net> On Sun, 30 Mar 2008 08:16:39 -0700 (PDT) iu2 wrote: > > > I'd like to use Python in a commercial application. In fact I would > > > like to write the application entirely in Python. > > > But I think I wouldn't like telling what language the application is > > > written in. > > > > Why is the reason for that? > > Due to Competitors... I don't want to expost the language I use You might hide it from many of your customers but don't count on hiding it from your competitors. Chances are, if they don't know it because they just don't care. -- 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 nagle at animats.com Mon Mar 10 01:12:16 2008 From: nagle at animats.com (John Nagle) Date: Sun, 09 Mar 2008 22:12:16 -0700 Subject: What c.l.py's opinions about Soft Exception? In-Reply-To: <13t76hsmp060e55@corp.supernews.com> References: <13t6tf3b5tpcv48@corp.supernews.com> <198efda1-c282-4f90-9195-042cc3a5a7fc@u72g2000hsf.googlegroups.com> <13t76hsmp060e55@corp.supernews.com> Message-ID: <47d4c107$0$36349$742ec2ed@news.sonic.net> Steven D'Aprano wrote: > On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote: > >> On 9 Mrz., 06:30, Steven D'Aprano > cybersource.com.au> wrote: >> Is it really so exotic that it requires the demand for more use cases? > > > Are the existing solutions really so incomplete that we need yet another > solution? > > What problem are you trying to solve with SoftExceptions? I actually implemented something like "soft exceptions" in a LISP program long ago. I called them "gripes". They were a way that a function could complain about something it wanted the caller to fix. The caller could either fix it or decline to do so. This was for a robotic planning application, where one module had detected that some precondition that it needed wasn't satisfied. This was usually something like some physical object being in the wrong place for a later operation, and a previously planned move needed to be modified. Passing the problem back to the caller sometimes allowed an easy fix, rather than aborting the whole plan and building a new one. This isn't a common problem. In the rare cases that it is needed, it can be implemented with callbacks. It doesn't require a language extension. John Nagle From gagsl-py2 at yahoo.com.ar Wed Mar 26 02:04:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 03:04:49 -0300 Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk escribi?: > On Mar 25, 9:25?pm, "Gabriel Genellina" > wrote: >> En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? >> escribi?: >> >> >> ? ?i'm trying to call subprocess.popen on the 'rename' function in >> >> linux. ?When I run the command from the shell, like so: >> >> >> rename -vn 's/\.htm$/\.html/' *.htm >> >> >> it works fine... however when I try to do it in python like so: >> >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ >> >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) >> >> >> print p.communicate()[0] >> >> >> nothing gets printed out (even for p.communicate()[1]) >> >> I'd try with: >> >> p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], >> ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, >> ? ? ? ?shell=True) >> >> (note that I added shell=True and I'm using a raw string to specify the >> reg.expr.) > > Thanks Gabriel, > I tried the new command and one with the raw string and single > quotes, but it is still giving me the same results (no output). any > other suggestions? My next try would be without the single quotes... -- Gabriel Genellina From timr at probo.com Sat Mar 29 21:10:11 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 30 Mar 2008 01:10:11 GMT Subject: Problem with sqlite References: <657gq6F2dh3fdU1@mid.uni-berlin.de> Message-ID: <7sptu318ea04m0u6vffsm3g6nj94390hf5@4ax.com> aiwarrior wrote: > >I'm sorry about not saying showing the libraries. It was not on >purpose. You didn't make any comment on the rest of Gerhard's suggestion, nor does it appear that you took any action to correct them. You should get out of the habit of using extra parentheses in "if" and "print" statements. They are not needed in Python, and they make the code more difficult to read. > self.cursor.execute( "CREATE TABLE database >(album,filepath)" ) Note the order of the fields: album, then path. > def add_entry( self, eone , etwo ): #Add entry to database > self.cursor.execute( "INSERT INTO database (album,filepath) >VALUES (?,?)", ( eone , etwo ) ) > return 1 #TODO: exception handler Again note the order of the fields here: album, then path. > def get_value( self, column ): > self.cursor.execute( "SELECT %s FROM database" % column ) > for n in self.cursor: > print n I suspect you wanted "self.cursor.fetchall()" there, but since you don't call it, it doesn't matter yet. > db.add_entry( joined, audio['album'] ) Now note the order that you supply the fields: path first, album second. You are inserting the fields in the wrong order here. >This is all the code. Some of that try pass code is just something i >glued to create a clean slate database file And such gluing is a very bad idea, because it is apparently hiding the real cause of your problems. Get rid of the try/except/pass sequences until you understand what is failing. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 06:33:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 10:33:40 -0000 Subject: Passing function objects to timeit Message-ID: <13us6o4og79iid0@corp.supernews.com> The timeit.Timer class times "code snippets" -- you pass it strings rather than function objects. That's good for what it's worth, but sometimes the code you want to time is too big to easily pass as a string, or maybe you only have access to a function object without the source, or for whatever reason it's not very convenient. In this case, a good trick is to import the function by name: timeit.Timer('spam()', 'from __main__ import spam') But now I find myself wanting to time a function that's not defined in __main__. Here's a illustrative example: def factory(): def f(): return "spam" return f def main(): func = factory() return timeit.Timer('func()', 'from __main__ import func').timeit() But it doesn't work: >>> main() Traceback (most recent call last): File "", line 1, in File "", line 3, in main File "/usr/lib/python2.5/timeit.py", line 161, in timeit timing = self.inner(it, self.timer) File "", line 3, in inner ImportError: cannot import name func Moving the definition of func into __main__ is not an option. What do I do? Am I reduced to re-writing the timeit module to take functions instead of strings? (Maybe I should do that anyway.) Or is there a way to inject the function object into the namespace used by timeit? -- Steven From James.Moynes at rte.ie Mon Mar 31 06:01:19 2008 From: James.Moynes at rte.ie (Moynes James) Date: Mon, 31 Mar 2008 11:01:19 +0100 Subject: wxPython; adding a grid to a panel References: Message-ID: I am a Python newbie hoping for some help with wxPython. I am trying to build a frame which will display a wx.grid and a number of other widgets (text controls, static text and buttons). In all the example scripts I have seen, a gird is added directly to a frame; is it possible to place a grid in a box sizer or on a wx.Panel so that it can be arranged with other widgets in the same frame? In the script below I have added two panels to a frame. I want to display the grid in one panel (and later on add other widgets to the other panel), but I cannot get the grid to display properly. What am I doing wrong? Thanks in advance for your help, James ################################################# import wx import wx.grid class TestTable(wx.grid.PyGridTableBase): def __init__(self): wx.grid.PyGridTableBase.__init__(self) self.rowLabels = ["uno", "dos", "tres", "quatro", "cinco"] self.colLabels = ["homer", "marge", "bart", "lisa", "maggie"] def GetNumberRows(self): return 5 def GetNumberCols(self): return 5 def IsEmptyCell(self, row, col): return False def GetValue(self, row, col): return "(%s,%s)" % (self.rowLabels[row], self.colLabels[col]) def SetValue(self, row, col, value): pass def GetColLabelValue(self, col): return self.colLabels[col] def GetRowLabelValue(self, row): return self.rowLabels[row] class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Grid Table", size=(500,200)) panel1 = wx.Panel(self, -1) panel2 = wx.Panel(self, -1) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(panel1, 1, wx.EXPAND | wx.ALL, 3) hbox1.Add(panel2, 1, wx.EXPAND | wx.ALL, 3) grid = wx.grid.Grid(panel2, wx.EXPAND) table = TestTable() grid.SetTable(table, True) self.SetSizer(hbox1) app = wx.PySimpleApp() frame = TestFrame() frame.Show() app.MainLoop() ################################################## -------------- next part -------------- *********************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RT? may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ************************************************************ From mmeazy at gmail.com Wed Mar 19 09:41:03 2008 From: mmeazy at gmail.com (Ramya) Date: Wed, 19 Mar 2008 06:41:03 -0700 (PDT) Subject: Make Money Online with Home Business Opportunities. Message-ID: <8c8f35fd-56f4-4ea1-8739-8a6837ba6eeb@i7g2000prf.googlegroups.com> Make Money Online with Home Business Opportunities. Make Money at Home on your Computer. No investment needed. http://mmeazy.blogspot.com/ . From paul at boddie.org.uk Wed Mar 19 13:19:22 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 19 Mar 2008 10:19:22 -0700 (PDT) Subject: How to get an XML DOM while offline? References: <64cpnvF2at1j9U1@mid.uni-berlin.de> Message-ID: <69ad9586-7a82-47a5-8bbb-c92ecdb08aa4@e6g2000prf.googlegroups.com> On 19 Mar, 16:27, "Diez B. Roggisch" wrote: > william tanksley wrote: > > I want to parse my iTunes Library xml. All was well, until I unplugged > > and left for the train (where I get most of my personal projects > > done). All of a sudden, I discovered that apparently the presence of a > > DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing > > the Internet... So suddenly I was unable to do any work. The desire to connect to the Internet for DTDs is documented in the following bug: http://bugs.python.org/issue2124 However, I can't reproduce the problem using xml.dom.minidom.parse/ parseString and plain XHTML, although I may be missing something which activates the retrieval of the DTD. > > I don't want to modify the iTunes XML; iTunes rewrites it too often. > > How can I prevent xml.dom.minidom from dying when it can't access the > > Internet? > > > Is there a simpler way to read the iTunes XML? (It's merely a plist, > > so the format is much simpler than general XML.) > > Normally, this should be solved using an entity-handler that prevents the > remote fetching. I presume the underlying implementation of a SAX-parser > does use one, but you can't override that (at least I didn't find anything > in the docs) There's a lot of complicated stuff in the xml.dom package, but I found that the DOMBuilder class (in xml.dom.xmlbuilder) probably contains the things which switch such behaviour on or off. That said, I've hardly ever used the most formal DOM classes to parse XML in Python (where you get the DOM implementation and then create other factory classes - it's all very "Java" in nature), so the precise incantation is unknown/forgotten to me. > The most pragmatic solution would be to rip the doctype out using simple > string methods and/or regexes. Maybe, but an example fragment of the XML might help us diagnose the problem, ideally with some commentary from the people who wrote the xml.dom software in the first place. Paul From danb_83 at yahoo.com Sat Mar 22 12:10:04 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 22 Mar 2008 09:10:04 -0700 (PDT) Subject: NameError: name 'guess' is not defined References: <8188b37a-8c5c-4de8-bd9a-28bc1edbea4d@13g2000hsb.googlegroups.com> <64knqtF2cdrc4U1@mid.uni-berlin.de> Message-ID: On Mar 22, 10:44 am, "Diez B. Roggisch" wrote: > willk... at gmail.com schrieb: > > > > > I am very new to both programming and Pyhton and while trying to do > > some practice using A byte of python an Error pops up on the IDLE > > shell. I am using windows XP. PLease see below. > > while running: > > guess = int(raw_input('Enter an integer : ')) > > > if guess == number: > > print 'Congratulations, you guessed it.' > > running = False # this causes the while loop to stop > > elif guess < number: > > print 'No, it is a little higher than that.' > > else: > > print 'No, it is a little lower than that.' > > else: > > print 'The while loop is over.' > > # Do anything else you want to do here > > > print 'Done' > > > After typing the above as the book says, I get the error NameError: > > name 'guess' is not defined > > What Am I doing wrong? > > You most certainly did NOT write the above - because in Python > whitespace is significant, and thus the above would result in a > syntax-error because you need to have things like > > if condition: > something() > > and not > > if condition: > something() > > So unless you post what you *really* entered (and make sure your > NG-client/mailclient doesn't eat leading whitespace), nobody will be > able to help you. If your newsclient *does* mangle whitespace, you can post your code like: exec """ number = 12345 # Defines the number variable before using while True: $guess = int(raw_input('Enter an integer : ')) $if guess == number: $$print 'Congratulations, you guessed it.' $$break # this causes the while loop to stop $elif guess < number: $$print 'No, it is a little higher than that.' $else: $$print 'No, it is a little lower than that.' print 'The while loop is over.' print 'Done' """.replace("$", "\t") From bearophileHUGS at lycos.com Thu Mar 27 21:33:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 27 Mar 2008 18:33:15 -0700 (PDT) Subject: Tkinter menus made easy References: <0f42dcf0-a00e-47de-a8f1-cc902860f4e8@e23g2000prf.googlegroups.com> Message-ID: <7b6fad3f-60ed-49f9-b685-9fc1ddd3e2dd@s19g2000prg.googlegroups.com> MartinRineh... at gmail.com: > Mine does less. But you tell it less to do it. Some of those fields are optional :-) Bye, bearophile From ricaraoz at gmail.com Sat Mar 1 14:19:09 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Mar 2008 16:19:09 -0300 Subject: Pb with 2.5.2 & PyScripter In-Reply-To: <47c990b9$0$899$ba4acef3@news.orange.fr> References: <47c93bb8$0$874$ba4acef3@news.orange.fr> <47c990b9$0$899$ba4acef3@news.orange.fr> Message-ID: <47C9AC2D.8090404@bigfoot.com> M?ta-MCI (MVP) wrote: > Re! > > An exemple. With this script: > a=123 > b=456 > d=a+b+c > (note than 'c' is not defined). > > When I run, inside Pyscripter, the error-dialog is showed, and, one > second after, PyScripter is closed. > This problem is present since Python 2.5.2. > > I search, for know if it's a problem only on my computer, or a more > general problem. > > Thanks by advance for your(s) answer(s). > > @-salutations Just tried it with PyScripter v 1.9.5.0 and Python 2.5.2. Error dialog showed but PyScripter did not close. From borasavas at gmail.com Mon Mar 24 13:54:01 2008 From: borasavas at gmail.com (Kaze) Date: Mon, 24 Mar 2008 10:54:01 -0700 (PDT) Subject: Serving an external web site which requires authentication Message-ID: Hi, I need your suggestions about the topic. Actually, I'm not sure where to start but basically, I want to make something like; (I have an account on a site which requires log-in) - I'll be logged-in to that site with my account in my server. - And when a user connects to my site, I'll forward him/her to that site, using my account even if he/she doesn't have an account on that site... probably, I need to develop a proxy to do this, but I'm not sure... (I'm developing a django site) I really appreciate your ideas. From jeff at schwabcenter.com Thu Mar 20 11:16:05 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 08:16:05 -0700 Subject: Change user on UNIX In-Reply-To: References: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Message-ID: Jonathan Gardner wrote: > On Mar 20, 4:51 am, "Giampaolo Rodola'" wrote: >> Is there any way to su or login as a different user within a python >> script? I mainly need to temporarily impersonate another user to >> execute a command and then come back to the original user. > In the unix world, this is highly discouraged. You shouldn't have to > change your user. > If you want a different user to access files that another user > created, that's what groups are for. What's your take on setuid scripts (Python or otherwise)? I more or less agree with your assessment of su, so I would be interested in your opinion of chmod ug+s some_custom_script. From steve at REMOVE-THIS-cybersource.com.au Sat Mar 29 22:23:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 30 Mar 2008 02:23:07 -0000 Subject: Passing function objects to timeit References: <13us6o4og79iid0@corp.supernews.com> Message-ID: <13utucbj9mkrpd4@corp.supernews.com> On Sat, 29 Mar 2008 21:12:33 -0300, Gabriel Genellina wrote: > En Sat, 29 Mar 2008 07:33:40 -0300, Steven D'Aprano > escribi?: > >> The timeit.Timer class times "code snippets" -- you pass it strings >> rather than function objects. That's good for what it's worth, but >> sometimes the code you want to time is too big to easily pass as a >> string, or maybe you only have access to a function object without the >> source, or for whatever reason it's not very convenient. >> >> In this case, a good trick is to import the function by name: >> >> timeit.Timer('spam()', 'from __main__ import spam') >> >> >> But now I find myself wanting to time a function that's not defined in >> __main__. Here's a illustrative example: >> >> >> def factory(): >> def f(): >> return "spam" >> return f >> >> def main(): >> func = factory() >> return timeit.Timer('func()', 'from __main__ import func').timeit() > > Would this help (untested)? > > def main(): > return timeit.Timer('func()', 'from __main__ import factory; func = > factory()').timeit() Unfortunately no. The above was just a simple illustration. Perhaps I misled you by showing where func() came from, but what I intended to illustrate was that func() could come from *anywhere*. I might not know where it came from: all I have is a function object. In fact, my question is actually more general than that, because my example was a little unrealistic in that the function took no arguments. I have to deal with the function arguments as well. The general problem is that I wish to time an arbitrary function with arbitrary arguments. The function and arguments are provided to me as Python objects, but timeit requires strings. Converting the objects to strings is not practical, and the objects might not exist in the __main__ module. The problem is that timeit creates its own namespace to execute the code in (which is a good thing!). Is there a way to insert arbitrary objects into that namespace? > Or maybe: > > def main(): > global func > func = factory() > return timeit.Timer('func()', 'from __main__ import func').timeit() I'll try playing around with that and see. -- Steven From gh at ghaering.de Fri Mar 28 17:24:26 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 28 Mar 2008 22:24:26 +0100 Subject: Python 2.5 - Build Error on Windows because of SQLite3 In-Reply-To: References: Message-ID: <655609F2e5310U1@mid.uni-berlin.de> llothar wrote: > Why does Python2.5 do not include the amalgamation source code of > sqlite3? [...] First, at the time Python grew the sqlite3 module, there was no amalgamation yet. My reasoning: So that Python doesn't need to release a security release, should a security bug in SQLite be found. Users can then download the new DLL from the SQLite homepage and place it into their Python's DLL folder. Ok, in reality that's probably only true for x86 Windows, not IA64 and/or AMD64 ;-) OTOH it would save me and the Python team some effort if we bundled a specific SQLite amalgamation with Python. Bug reports about bit-rotten SQLite 3.x versions would then not appear :-P Nowadays we support SQLite 3.0.8 through the very latest one. That means quite a few #ifdefs and friends in the C source code and also in the unit tests. -- Gerhard From bbxx789_05ss at yahoo.com Thu Mar 20 13:32:06 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 20 Mar 2008 10:32:06 -0700 (PDT) Subject: if __name__ == '__main__': References: Message-ID: On Mar 20, 10:21?am, "Simon Brunning" wrote: > On Thu, Mar 20, 2008 at 4:12 PM, Bhagwat Kolde wrote: > > Hi, > > I am new to the python and not getting meaning of following line, > > > if __name__ == '__main__': > > ? ? ? main() > The if statement is used to skip the code after the if statement in certain situations. If that if statement is in a file named test1.py, and you issue this command: $ python test1.py then the code after the if statement will execute. That's because python assigns the string '__main__' to the variable __name__ when the program starts However, if you do this: ------- #test1.py def my_func(num): print num * 2 if __name__ == "__main__": print "Testing my func:", my_func(10) -------- #test2.py import test1 test1.my_func(5) ------- ...and you issue the command: $python test2.py Then the code after the if statement in test1.py will not execute. From jules at js3d.co.uk Sun Mar 2 03:03:02 2008 From: jules at js3d.co.uk (Jules Stevenson) Date: Sun, 2 Mar 2008 08:03:02 -0000 Subject: FW: Escaping a triple quoted string' newbie question Message-ID: <002801c87c3b$d6cd42b0$0301a8c0@laptop> Hello, Apologies if the terminology in this email is a little incorrect, I'm still finding my feet. I'm using python to generate some script for another language (MEL, in maya, specifically expressions). Maya runs python too, but unfortunately its expression language still has to use the maya syntax. If I pass the expression this code: #runtime code [mel] expRuntime="""float $pos[]=particleShape1.worldPosition; setAttr ("heartPP_1_"+particleShape1.particleId+".tx") $pos[0]; setAttr ("heartPP_1_"+particleShape1.particleId+".ty") $pos[1]; setAttr ("heartPP_1_"+particleShape1.particleId+".tz") $pos[2]; """ dynExpression (p, s=expRuntime, rad=1) #generate the expression Then maya errors out, however if I pass maya an 'escaped' version: expRuntime="""float $pos[]=particleShape1.worldPosition;\r\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tx\") $pos[0];\r\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".ty\") $pos[1];\r\nsetAttr (\"heartPP_1_\"+particleShape1.particleId+\".tz\") $pos[2];" -rad particleShape1;""" Then all is well. My question is, is there any way to convert the first variable example to the second? It's a lot easier to type and on the eye. Tia, Jules From pavloutefkros at gmail.com Sun Mar 2 10:15:39 2008 From: pavloutefkros at gmail.com (Gif) Date: Sun, 2 Mar 2008 07:15:39 -0800 (PST) Subject: tcp References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> <7ef4128b-4b56-4ed3-8a31-6ed1c1b962b0@m36g2000hse.googlegroups.com> Message-ID: <670b9b5b-82e0-418c-8ed4-94eabe8bf3c9@h25g2000hsf.googlegroups.com> i would like to apologize once more. i understand that you are saying "what a fool he is waiting for us to solve all his problems", cause i've said that for other posts, when they seemed "immature". It's just that i couldn't find a way out of 20 lines of code and this drove me mad. i end this topic here. From fetchinson at googlemail.com Mon Mar 10 19:05:47 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 16:05:47 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > > There are a number of free tools for image matching but it's not very > > easy to decipher the actual algorithm from the code that includes db > > management, GUI, etc, etc. I have my own image database and GUI so all > > I need is the actual algorithm preferably in pseudo code and not in > > the form of a research paper (from which I also found a lot but since > > I'm not that much interested in the actual science of image > > recognition this seems like an over kill). > > I'd recommend SIFT. There's quite a bit of information on SIFT. In most > cases, they don't cover the background science too much, but are still > heavy on the math. Pseudo code is hard to come by since it will take > many lines of pseudo code just to express one concise mathematical > equation. There are however many links to implementations in various > languages on the Wikipedia page. > > http://en.wikipedia.org/wiki/Scale-invariant_feature_transform > > I have had good experiences with SIFT for feature extraction from images > (I have used it for panorama stitching and robot mapping). It's > insensitive to scale and rotation. Note that it is a patented algorithm > and this may (or may not) pose a problem for you. Thanks for the info! SIFT really looks like a heavy weight solution, but do you think the whole concept can be simplified if all I needed was: given a photo, find similar ones? I mean SIFT first detects objects on the image and find similarities, but I don't need the detection part at all, all I care about is similarity for the whole photo. I surely don't understand the big picture fully but just have the general feeling that SIFT and other expert tools are an overkill for me and a simplified version would be just as good with a much more easily comprehensible core algorithm. Or am I being too optimistic and there is no way out of going into the details? From darcy at druid.net Thu Mar 6 11:41:58 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 6 Mar 2008 11:41:58 -0500 Subject: Please keep the full address In-Reply-To: References: <9f8adebf-ea31-45cf-9408-aa6cfc19d9d7@m3g2000hsc.googlegroups.com> Message-ID: <20080306114158.a1133a3f.darcy@druid.net> On Thu, 6 Mar 2008 08:00:58 -0800 (PST) Carl Banks wrote: > > I'm talking about castironpi. I find his posts a waste of my time > > "His" posts? Whatever. I'm too old to worry about searching for politically correct, gender neutral pronouns. -- 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 kyosohma at gmail.com Thu Mar 13 09:03:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 13 Mar 2008 06:03:49 -0700 (PDT) Subject: Dispatch("Excel.Application") failed References: Message-ID: <07e73002-5b12-41c2-9194-5fc753dc6726@n36g2000hse.googlegroups.com> On Mar 13, 1:02 am, lialie wrote: > Hi, > Maybe it 's quite simple, but I can't fix it. Do I make some mistakes in > my env setting? My excel version is 2003. > any suggestion? Thanks. > > Traceback (most recent call last): > File "testexcel.py", line 3, in ? > excel = Dispatch("Excel.Application") > File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line > 95, in > Dispatch > dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c > lsctx) > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 98, in _ > GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 78, in _ > GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II > D_IDispatch) > pywintypes.com_error: (-2147221005, > '\xce\xde\xd0\xa7\xb5\xc4\xc0\xe0\xb1\xf0\xd7\xd6\xb7\xfb\xb4\xae', > None, None) I'm not seeing anything obviously wrong. What version of Windows are you using? Are you logged in as an admin? You also might try the PyWin32 user's mailing list: http://mail.python.org/mailman/listinfo/python-win32 Mike From mhwalker at shaw.ca Tue Mar 4 00:12:39 2008 From: mhwalker at shaw.ca (Mike Walker) Date: Tue, 04 Mar 2008 05:12:39 GMT Subject: Command line arguments in Windows Message-ID: I am having some problems with command line arguments in Windows. The same code under Linux works fine. In Windows I only get one argument no matter how many arguments are passed on the command line. I think there is some problem with the way the .py files are associated causing this. I'm just not sure how to go about fixing it. If I call the python script using the command "python argtest.py arg1 arg2 etc..." this also works fine. Its only when run the program using the name only that the problem occurs. Does anyone have any ideas what the problem is here and hopefully how to go about fixing it? import sys if __name__ == "__main__": for arg in sys.argv: print arg From phd at phd.pp.ru Tue Mar 11 09:40:03 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 11 Mar 2008 16:40:03 +0300 Subject: SQLObject 0.10.0 Message-ID: <20080311134003.GB14147@phd.pp.ru> Hello! I'm pleased to announce version 0.10.0, the first stable release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9 -------------- Features & Interface ~~~~~~~~~~~~~~~~~~~~ * Dropped support for Python 2.2. The minimal version of Python for SQLObject is 2.3 now. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.10. * SQLBuilder Select supports the rest of SelectResults options (reversed, distinct, joins, etc.) * SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect() use SQLBuilder Select queries; this make all SELECTs implemented internally via a single mechanism. * SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias) and properly sqlrepr. * Added SQLBuilder ImportProxy. It allows one to ignore the circular import issues with referring to SQLObject classes in other files - it uses the classregistry as the string class names for FK/Joins do, but specifically intended for SQLBuilder expressions. See tests/test_sqlbuilder_importproxy.py. * Added SelectResults.throughTo. It allows one to traverse relationships (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's a simple mechanism for pre-caching/eager-loading of later FK relationships (i.e., going to loop over a select of somePeople and ask for aPerson.group, first call list(somePeople.throughTo.group) to preload those related groups and use 2 db queries instead of N+1). See tests/test_select_through.py. * Added ViewSQLObject. * Added sqlmeta.getColumns() to get all the columns for a class (including parent classes), excluding the column 'childName' and including the column 'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to override it in the inheritable sqlmeta class; this makes asDict() to work properly on inheritable sqlobjects. * Allow MyTable.select(MyTable.q.foreignKey == object) where object is an instance of SQLObject. * Added rich comparison methods; SQLObjects of the same class are considered equal is they have the same id; other methods return NotImplemented. * RowDestroySignal is sent on destroying an SQLObject instance; postfunctions are run after the row has been destroyed. * Changed the implementation type in BoolCol under SQLite from TINYINT to BOOLEAN and made fromDatabase machinery to recognize it. * MySQLConnection (and DB URI) accept a number of SSL-related parameters: ssl_key, ssl_cert, ssl_ca, ssl_capath. * Use sets instead of dicts in tablesUsed. Dropped tablesUsedDict function; instead there is tablesUsedSet that returns a set of strings. * SQLBuilder tablesUsedSet handles sqlrepr'able objects. * Under MySQL, PickleCol no longer uses TEXT column types; the smallest column is now BLOB - it is not possible to create TINYBLOB column. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From lesande at gmail.com Wed Mar 19 19:37:24 2008 From: lesande at gmail.com (Lee Sander) Date: Wed, 19 Mar 2008 16:37:24 -0700 (PDT) Subject: slicing a list but in downward fashion Message-ID: hi, i have a list and i can get elements form it via slicing L[start:stop] but sometimes the start is > stop i.e. I want to go in the opposite direction,eg L[10:2], mattab lets you do L(10:-1:2) to achive this, is there a way to do this in python? thanks L From tjreedy at udel.edu Thu Mar 27 16:43:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Mar 2008 16:43:44 -0400 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> Message-ID: wrote in message news:4a2ade35-9624-4e26-ba47-984c72ea4f6a at y21g2000hsf.googlegroups.com... | I'm making a game where you'll be able to make your own mods and I | want to be able to write these mods in python. However, python has a | lot of "dangerous" functions (like erase any file on the harddrive | etc) so I want a "safe" python. I first found RExec but that is | disabled in python 2.5 so I was thinking about building python from | source with a few changes. There are modable commercial games, such as CIV4 I believe, that use Python as the scripting language for both the authors and modders. I presume they use customized interpreters, without the open and file builtins and process, socket, etc modules, and probably a customized import. But I have never seen an article or report on exactly what changes there are. There is also the question of what to about 'hang up' code like 'while True: pass', but that is less a concern for a game run on home machines than a web server. Anyone doing that could be blackballed from the mod distribution site without having trashed anyone's system. tjr From gowricp at gmail.com Tue Mar 18 23:48:37 2008 From: gowricp at gmail.com (Gowri) Date: Tue, 18 Mar 2008 20:48:37 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <505bf4e4-f99c-4b1c-9ad6-ba26846645bc@n77g2000hse.googlegroups.com> Thanks for your reply Justin. But how do I do it with cjson? From lists.eckel at gmail.com Sun Mar 16 07:10:58 2008 From: lists.eckel at gmail.com (Bruce Eckel) Date: Sun, 16 Mar 2008 04:10:58 -0700 (PDT) Subject: Pycon disappointment Message-ID: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> If the following seems unnecessarily harsh, it was even more harsh for me to discover that the time and money I had spent to get to my favorite conference had been sold to vendors, presenting me as a captive audience they could pitch to. I believe that this year's Pycon organizers suffered from inexperience and naivete, because they didn't know that some vendors will ask for anything just to see how far they can push it. And that it's a negotiation, that you must push back rather than give in just because the conference might get some money for it. More importantly, that the imperative to grow Pycon does not mean "at all costs." I've already spoken to more than one vendor who was dismayed by the state of things, so we are not talking about all vendors here by any means. At first the morning plenary sessions -- where the entire conference audience was in a single room -- just seemed a bit commercial. But then I slowly figured out that the so-called "diamond keynotes" were actually sold to vendors. It must have sounded great to some vendors: you get to pitch to everyone and nothing else is going on so the audience is trapped. But it gets worse. The lightning talks, traditionally the best, newest and edgiest part of the conference, were also sold like commercial air time. Vendors were guaranteed first pick on lightning talk slots, and we in the audience, expectantly looking forward to interesting and entertaining content, again started to feel like things were awfully commercial. And what seemed like a good idea, moving lightning talks into plenary sessions with no competition, began to look like another way to deliver a captive audience to vendors. What was supremely frustrating was discovering that the people wanting to give REAL lightning talks had been pushed off the end of the list by this guarantee to vendors. We didn't get to see the good stuff, the real stuff, because that time had been sold. On top of that, the quality of the presentations was unusually low. I'd say that 80% were not worth going to -- there were definitely some good ones, but it was a lot of pain to discover them. In my opinion, open spaces should have had greater status and billing, with eyes-forward talks and vendor sessions offered only as possible alternatives. Especially, vendor sessions should not be presented as "keynotes" during plenary sessions. I think it took a little while for people to catch on to the idea that they could have control of their own experience through the open spaces and that the main offerings were not the only option. The worst thing about the whole experience was the feeling that someone was trying to trick me and control me into watching these things, presenting them under the guise of real keynotes and real lightning talks. My trust has been violated. I paid a lot, in both money and time, to be at this conference just to be herded into a room and have my eyeballs sold to the highest bidder. And it's going to bug me, especially when I think about coming back next year. I'm going to need a lot of reassurance that this isn't going to happen again. I think a lot of people have been caught up in the idea that we need to commercialize Python, and ride some kind of wave of publicity the way that Java and C# and Rails seem to have done. This kind of thinking leads to bad, impulsive decisions that can have long-lasting or even permanent negative impacts on the community. Maybe things don't seem to be happening fast enough in comparison with those commercial endeavors, but this is a grass-roots movement. It's never been about moving as fast as you can. It's always been about vision, not tactics. For many, it's fun and exciting and really important to "catch the wave," but the wave passes and then you've just exhausted yourself chasing a brief bump in the water. Python may not have caught any particular wave, but it's always grown, steadily. I know what the argument for the results of Pycon 2008 will be: we needed the money. My answer: it's not worth it. If this is what you have to do to grow the conference, then don't. If the choice is between selling my experience to vendors and reducing the size of the conference, then cut the size of the conference. Keep the quality of my experience as the primary decision criteria, or I'll stop coming. From bbkolde at gmail.com Thu Mar 20 12:12:44 2008 From: bbkolde at gmail.com (Bhagwat Kolde) Date: Thu, 20 Mar 2008 21:42:44 +0530 Subject: if __name__ == '__main__': Message-ID: Hi, I am new to the python and not getting meaning of following line, if __name__ == '__main__': main() Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skunkwerk at gmail.com Wed Mar 26 09:44:21 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Wed, 26 Mar 2008 06:44:21 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> Message-ID: <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> On Mar 25, 11:04?pm, "Gabriel Genellina" wrote: > En Wed, 26 Mar 2008 02:15:28 -0300, skunkwerk ? > escribi?: > > > > > On Mar 25, 9:25?pm, "Gabriel Genellina" > > wrote: > >> En Wed, 26 Mar 2008 00:39:05 -0300, skunkwerk ? > >> escribi?: > > >> >> ? ?i'm trying to call subprocess.popen on the 'rename' function in > >> >> linux. ?When I run the command from the shell, like so: > > >> >> rename -vn 's/\.htm$/\.html/' *.htm > > >> >> it works fine... however when I try to do it in python like so: > >> >> p = subprocess.Popen(["rename","-vn","'s/\.htm$/ > >> >> \.html/'","*.htm"],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > >> >> print p.communicate()[0] > > >> >> nothing gets printed out (even for p.communicate()[1]) > > >> I'd try with: > > >> p = subprocess.Popen(["rename", "-vn", r"'s/\.htm$/\.html/'", "*.htm"], > >> ? ? ? ?stdout=subprocess.PIPE, stderr=subprocess.PIPE, > >> ? ? ? ?shell=True) > > >> (note that I added shell=True and I'm using a raw string to specify the ? > >> reg.expr.) > > > Thanks Gabriel, > > ? ?I tried the new command and one with the raw string and single > > quotes, but it is still giving me the same results (no output). ?any > > other suggestions? > > My next try would be without the single quotes... > > -- > Gabriel Genellina thanks for the input guys, I've tried the suggestions but can't get it to work. I have a file named test.htm in my directory, and when I run the following command: rename -vn 's/(.*)\.htm$/model.html/' *.htm from the shell in that directory I get the following output: test.htm renamed as model.html now my python script is called test.py, is located in the same directory, and is called from the shell with 'python test.py' the contents of test.py: import subprocess p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) print p.communicate()[0] i change to print p.communicate()[1] in case the output is blank the first time this is the output: *.htm renamed as model.html when I add shell=True to the subprocess command, I get the following output: Usage: rename [-v] [-n] [-f] perlexpr [filenames] am i doing something wrong? From tmp1 at viltersten.com Sat Mar 8 22:06:36 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 04:06:36 +0100 Subject: SV: Regarding coding style In-Reply-To: <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> <50bf3e02-65e1-4c77-8b18-ebec0f594c7b@m44g2000hsc.googlegroups.com> Message-ID: <63h1j2F27rdfoU1@mid.individual.net> >> /** Projects an object from 3D to 2D using >> the method of Alexander The Great. >> \param 3D structure to be projected >> \returns 2D projection >> */ >> public Proj2D get2Dfrom3D(Proj3D param); >> >> The above is, to me, very clear and >> consistent. Not to mention, easily >> handled with e.g. Doxygen to create a >> readable documentation. >> >> I don't see how this is dislikeable. Please >> explain. > > When get2Dfrom3D changes its signature but > the comment is not changed. That's where I > have a problem, and it's only a matter of > time before it happens. I think we've arrived at the spot where i'll claim that a _always_ update my comments, and you'll question that i can (in the long run). Let's agree on that! :) -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From samritmanmar at gmail.com Thu Mar 6 04:26:05 2008 From: samritmanmar at gmail.com (sexyman) Date: Thu, 6 Mar 2008 01:26:05 -0800 (PST) Subject: FREE DOWNLOAD game mario. Message-ID: <6375831c-35bb-4119-9626-a9c102619410@b1g2000hsg.googlegroups.com> mario http://www.ziddu.com/download.php?uid=Z7CdnZqoabCcluKnYqqhkZSoX6qfnZqu2 joy .......play game From hvendelbo.dev at googlemail.com Wed Mar 5 14:46:21 2008 From: hvendelbo.dev at googlemail.com (hvendelbo.dev at googlemail.com) Date: Wed, 5 Mar 2008 11:46:21 -0800 (PST) Subject: Embedding vs Configuring Python build Message-ID: I am using Python in an application that cannot depend on an existing Python installation or require Python to be installed. The application itself should not have an install procedure, but rather should be runnable from any location in the file system. Ideally I would prefer not to embed at all, but would rather prefer to configure. I found a couple of discussions on the default sys.path in the archive and am currently reading through the Py_GetPath. The path logic seems pretty specific to the platform, whereas I would want it to be relative regardless of platform. I figure that if I can just get to my own site.py/sitecustomize.py then I'm in business. This is what I wan't to achieve: * The python executable location should be used to determine dynamic libraries * The python exe location should be used to determine standard library scripts * site.py should be executed rather than the shell if no parameters are specified Is it possible to change the build configuration of Python to support this. From michael.wieher at gmail.com Wed Mar 26 09:32:28 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 26 Mar 2008 08:32:28 -0500 Subject: Dimensions of Arrays, Matrices In-Reply-To: <8a6035a00803260622v686441ddy1d3dd942b2377e21@mail.gmail.com> References: <8a6035a00803260622v686441ddy1d3dd942b2377e21@mail.gmail.com> Message-ID: Google -> "matrix python" 1st response: http://www.python.org/community/sigs/retired/matrix-sig/ "The purpose of this SIG was to continue development of a Python matrix type. This effort succeeded and resulted in Numerical Python, a high-speed array language for Python" by following the magic hyperlink I arrive at http://scipy.org/ which might be too embellished, so I then returned to the retired-sig and found http://sourceforge.net/projects/numpy I'm sure if you dig around in either of those places you'll find more than you are looking for =) 2008/3/26, Dark Wind : > > Hi, > > Suppose we have a 3X3 matrix in Mathematica. We can get its dimensions by: > Dimensions[A] = {3,3} > TensorRank[A] = 2 > > Are there exact functions for these two in Python? > > Thank you > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Sat Mar 29 04:40:21 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sat, 29 Mar 2008 08:40:21 GMT Subject: How do I reconnect a disconnected socket? In-Reply-To: <13uq89rskf16u9a@corp.supernews.com> References: <13uq69e8us4oo74@corp.supernews.com> <13uq89rskf16u9a@corp.supernews.com> Message-ID: Grant Edwards wrote: > Laszlo Nagy wrote: >> What about non-blocking sockets? > > $ man recv > ... > If no messages are available at the socket, the receive > calls wait for a message to arrive, unless the socket is > non-blocking (see fcntl(2)), in which case the value -1 > is returned and the external variable errno set to > EAGAIN. As Grant showed, a successful recv() returning zero bytes indicates the end of the data stream from the remote peer. Other cases block or raise errors. A few more notes: When a socket will return zero bytes to indicate the end of the data stream, it will select() as readable. In the case Laszlo asked about here -- a non-blocking socket is not shutdown but no data is immediately readable -- on some systems, the error is EWOULDBLOCK, which may be, but is not generally, the same code as EAGAIN. (There may be yet other systems that have different error conventions; I don't know.) The Python library's 'errno' module exports the error names with their associated numeric values. Python's socket module does not 'return' these error codes; it raises exceptions. A non-blocking socket, or equivalently a socket with a timeout of zero, will raise socket.error. The errno in the exception's (errno, string) value should be EAGAIN or EWOULDBLOCK. If a socket has a non-zero timeout, and that timeout expires, the operation raises socket.timeout. -- --Bryan From davids at evertech.com.au Fri Mar 14 03:31:08 2008 From: davids at evertech.com.au (David S) Date: Fri, 14 Mar 2008 07:31:08 GMT Subject: Spaces in path name References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <13tk779i4r8j9ba@corp.supernews.com> Message-ID: <0RpCj.25549$421.10498@news-server.bigpond.net.au> Hi, Using "C:\Program Files\apache-ant-1.7.0\bin\ant.bat" just gives me the same result. David "Dennis Lee Bieber" wrote in message news:13tk779i4r8j9ba at corp.supernews.com... > On Fri, 14 Mar 2008 04:37:12 GMT, "David S" > declaimed the following in comp.lang.python: > > >> If I cut the path statement here and paste it next to a windows XP >> command >> prompt ant is invoked. >> >> The python code here is >> if not os.path.isfile(ANT_CMD): >> error('"%s" does not exist' % ANT_CMD) >> > Any chance the /filename/ is something like "ant.exe" > >>>> pyt = "e:/python24/python" >>>> if not os.path.isfile(pyt): > ... print "%s does not exist" % pyt > ... > e:/python24/python does not exist >>>> pyt = "e:/python24/python.exe" >>>> if not os.path.isfile(pyt): > ... print "%s does not exist" % pyt > ... >>>> > > Remember, under Windows, files with certain extensions are > executable /without/ needing the extension on the command line -- unlike > Linux... > > My eclipse install has: ant.bat, ant.cmd, and ant.jar files, and > which (if they are in the same directory) gets picked when the extension > is not specified is beyond my current knowledge -- might depend on the > order of the extensions specified in the > > C:\Documents and Settings\Dennis Lee Bieber>echo %pathext% > .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.pyw;.py;.pyo;.pyc;.tcl > > (okay, the ant.jar won't be picked ) > > -- > 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/ From stefan_ml at behnel.de Mon Mar 24 11:42:52 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Mar 2008 16:42:52 +0100 Subject: URL encoding In-Reply-To: References: <9693ffda-1454-4d56-acee-1e6fc4ebeccb@h11g2000prf.googlegroups.com> Message-ID: <47E7CBFC.8090205@behnel.de> binaryj wrote: > On Mar 24, 7:04 pm, vvangelov... at gmail.com wrote: >> Is there any method in the standard modules that can perform proper >> url encoding according to RFC? > > whats wrong with the current encoding ??? it just works fine!!! > > or is it that u dont know about urllib.urlencode() ?? I think that was obvious from the question, no need to spill punctuation marks all over the place. Stefan From __peter__ at web.de Wed Mar 12 14:16:59 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Mar 2008 19:16:59 +0100 Subject: ValueError in pickle module during unpickling a infinite float (python 2.5.2) References: <4b9d0896-df9c-47b6-98b6-16f825d67975@i7g2000prf.googlegroups.com> Message-ID: rehn at iwm.mw.tu-dresden.de wrote: > Unpickling an infinite float caused a ValueError in the pickle module. > I need to pickle and load infinite floats in my project. Do you have > any suggestions how to solve the issue? You could try another protocol. Does >>> inf = 1e1000 >>> pickle.loads(pickle.dumps(inf, pickle.HIGHEST_PROTOCOL)) inf work? Peter From frikker at gmail.com Mon Mar 3 16:01:48 2008 From: frikker at gmail.com (blaine) Date: Mon, 3 Mar 2008 13:01:48 -0800 (PST) Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> Message-ID: <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> On Mar 3, 12:31 pm, Bjoern Schliessmann wrote: > It doesn't only work, it's the preferred way (if you don't use > advanced wrappers like pyserial). For the basics see > > http://www.easysw.com/~mike/serial/serial.html [...] > What is the relationship between read/write, the baud rate, and > efficiency? The serial port is configured using POSIX terminal > interface (termios). Thank you so much for that reference link, it was very helpful. I now understand the difference in the modules - termios and fctnl. As far as PySerial goes - were trying to stick to built-in modules since cross compiling to an arm processor is being a little bit of a pain for us. Thank you for the suggestion though! Thanks! Blaine From mdboldin at gmail.com Tue Mar 4 10:05:11 2008 From: mdboldin at gmail.com (mmm) Date: Tue, 4 Mar 2008 07:05:11 -0800 (PST) Subject: pySQLite Insert speed References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: Oops I did make a mistake. The code I wanted to test should have been import copy print 'Test 1' pf= '?,?,?,?' sqlx1= 'INSERT INTO DTABLE2 VALUES ( %s ) ' % pf print sqlx1 print print 'Test 2' sqlx2= copy.copy(sqlx1) sqlx3= sqlx1 pf= '?,?,?, ****' print 'sqlx1= ', sqlx1 print 'sqlx2= ', sqlx2 print 'sqlx3= ', sqlx2 and the results would == output Test group 1 INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) Test group 2 sqlx1= ?INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) sqlx2= ?INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) sqlx3= ?INSERT INTO DTABLE2 VALUES ( ?,?,?,? ) Such that sqlx1 does to change with the re-assignment of 'pf' And of course immutables such as strings are immutable. Got it now. From bockman at virgilio.it Mon Mar 24 11:48:38 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 15:48:38 GMT Subject: python library to manipulate PALM documents ? References: <47e7ae4d$0$18153$5fc30a8@news.tiscali.it> Message-ID: <47e7cd56$0$16036$5fc30a8@news.tiscali.it> Il Mon, 24 Mar 2008 12:08:59 -0300, Guilherme Polo ha scritto: > 24 Mar 2008 13:36:13 GMT, Francesco Bochicchio : >> Hi all, >> >> anybody knows a python equivalent of the perl PALM::Doc module (and >> eventually other PALM::). >> >> I have a e-book device wich reads mobi-pocket format (among others). I >> have downloaded from a forum a set of perl scripts to convert HTML to >> unencripted mobipocket format and vice-versa. It uses the PALM:: >> package. I would attempt (for my convenience and for the fun of it) to >> make a python equivalent of that. Hence my quest for a Palm::Doc >> equivalent. >> >> > I'm not sure if it is what you are after, but it seems to be, check > this: http://pypi.python.org/pypi/PalmDB/1.8.1 > It could be. I read that mobipocket files may have extension .prc. Ciao ---- FB From aisaac at american.edu Sat Mar 8 10:32:18 2008 From: aisaac at american.edu (Alan Isaac) Date: Sat, 08 Mar 2008 15:32:18 GMT Subject: Can't get items out of a set? In-Reply-To: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Message-ID: <6kyAj.284$Ls6.153@trnddc01> Cruxic wrote: > people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) > ... > p = people.get_equivalent(2) #method doesn't exist as far as I know > print p.name #prints Sue def get_equivalent(test, container): for p in container: if p == test: return p hth, Alan Isaac #example (note change in __eq__ to match your case; fix if nec) class Person: def __init__(self, id, name): self.id = id self.name = name def __hash__(self): return self.id def __eq__(self, other): return self.id == other people = set( [Person(1, 'Joe'), Person(2, 'Sue')] ) get_equivalent(2,people) From rasky at develer.com Tue Mar 11 19:09:03 2008 From: rasky at develer.com (Giovanni Bajo) Date: Tue, 11 Mar 2008 23:09:03 GMT Subject: min/max: "stable" invariant? Message-ID: Hello, assuming that a sequence contains multiple elements with minimum/maximum value, do min/max guarantee to return the *first* element in the sequence among those? Example: >>> class A: ... def __init__(self, x): self.x = x ... >>> L = [A(0), A(1), A(2), A(0)] >>> min(L, key=lambda a:a.x) is L[0] True >>> min(L, key=lambda a:a.x) is L[3] False Is this guaranteed by the Python language formal specification? Is this guaranteed to always by true in CPython? (I guess so) I can't find any mention in the documentation. -- Giovanni Bajo From sreya9636 at gmail.com Sat Mar 15 11:30:16 2008 From: sreya9636 at gmail.com (sreya9636) Date: Sat, 15 Mar 2008 08:30:16 -0700 (PDT) Subject: Exciting FREE Details Message-ID: <67c2c51d-b8a2-458a-8e99-d7ebd1474811@s8g2000prg.googlegroups.com> Tips On Buying A Desktop Computer While the case may not be important to some computer users it is a consideration to be thought about before purchasing a desktop computer. ... Log on : http://www.computer-solution.page.tl From Lie.1296 at gmail.com Sun Mar 2 07:53:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 2 Mar 2008 04:53:56 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> Message-ID: <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> On Mar 2, 2:02 pm, Paul Rubin wrote: > Lie writes: > > So basically they refused to satisfy everything that is still possible > > individually but would conflict if done together. > > I can't understand that. > > > x = 1 > > a = x + 1 << decides it's an int > > No, so far a and x are both Num (indeterminate) > > > b = x + 1.0 << error? or redefine to be float? > > This determines that a, b, and x are all floats. It's not "redefined" > since the types were unknown prior to this. > > Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional" > which is a narrower class than Num but it could still be Float, Double, > or Rational. Nums support addition, subtraction, multiplication, but > not necessarily division. So int/int is an error. Fractionals support > division. > > > c = x + 1 << would this cause error while it worked in line 2? > > No, c is also a float (actually Fractional) > > > A slightly obfuscated example: > > l = [1, 1.0, 1] > > This is the same as l = [1.0, 1.0, 1.0]. In Haskell, all elements > of a list must have the same type, so the 1.0 determines that l is > a list of fractionals. > > > x = 1 > > for n in l: > > c = x + n > > Haskell does not have loops, but if it did, all these values would be > fractionals. That's quite complex and restrictive, but probably it's because my mind is not tuned to Haskell yet. Anyway, I don't think Python should work that way, because Python have a plan for numerical integration which would unify all numerical types into an apparent single type, which requires removal of operator's limitations. On Mar 2, 2:23 pm, Paul Rubin wrote: > Steven D'Aprano writes: > > def mean(data): return sum(data)/len(data) > > > That does the right thing for data, no matter of what it consists of: > > floats, ints, Decimals, rationals, complex numbers, or a mix of all of > > the above. > > One of those types is not like the others: for all of them except int, > the quotient operation actually is the inverse of multiplication. > So I'm unpersuaded that the "mean" operation above does the "right > thing" for ints. If the integers being averaged were prices > in dollars, maybe the result type should even be decimal. In __future__ Python or Python 3.0, that mean function would work for all types. And divisions on int is also inverse of multiplications, just like subtraction is the inverse of addition: from __future import division a = 10 b = 5 c = a / b if c * b == a: print 'multiplication is inverse of division' From pavloutefkros at gmail.com Sat Mar 1 12:40:12 2008 From: pavloutefkros at gmail.com (Gif) Date: Sat, 1 Mar 2008 09:40:12 -0800 (PST) Subject: tcp functions Message-ID: is there a module for tcp functions or any other quick way to connect, listen, send and recieve from tcp? thanks in advance From MadComputerGuy at gmail.com Mon Mar 10 01:08:29 2008 From: MadComputerGuy at gmail.com (Nathan Pinno) Date: Sun, 9 Mar 2008 22:08:29 -0700 (PDT) Subject: How to factor using Python? Message-ID: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? Thanks in advance, Nathan P. From Scott.Daniels at Acm.Org Sat Mar 29 18:33:56 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 29 Mar 2008 15:33:56 -0700 Subject: Problem with python In-Reply-To: References: <1f4b1bf9-acb7-490e-8bc9-6e81540a7198@s37g2000prg.googlegroups.com> Message-ID: <13utgh8j9ik8t7c@corp.supernews.com> Lie wrote: > On Mar 30, 2:57 am, mac_the_sco... at hotmail.com wrote: >> Hi there. >> I ... started writing simple programs in the python gui... when I write >> python code ...[and]... double click it all that happens is a black box >> flashes up on the screen, but nothing else!? .... > > open the program in IDLE (or any other Python IDEs). I'm guessing that > your program is printing a traceback (error) when trying to get input > that's why it immediately closes itself. Another possibility is to open a shell (or command window or "dos box"), and in that window type in "python myfile.py" You'll see error messages because the display window does not depend on the program staying alive. By the way, a better thing to have said when you asked this would include your OS, the python version, and the GUI system you are using. Those details matter. If you are doing wxPython programming, for example, you cannot easily use IDLE for your program (GUI systems fight for control of the display). -Scott David Daniels Scott.Daniels at Acm.Org From ivan.illarionov at gmail.com Tue Mar 18 19:51:56 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 18 Mar 2008 16:51:56 -0700 (PDT) Subject: Fast 2D Raster Rendering with GUI References: <0508a057-bf9c-4240-88c0-327a7d2964ef@h11g2000prf.googlegroups.com> <714b31c8-e4e2-4034-8183-206c2259f030@z38g2000hsc.googlegroups.com> Message-ID: <8fc48d27-1496-4240-a26c-708b6e9aa440@s8g2000prg.googlegroups.com> > That's another new step for me. Any ideas where to start? http://docs.python.org/ext/simpleExample.html And look into the source of existing extensions. PIL and PyCairo are the best in your situation. From Lie.1296 at gmail.com Sun Mar 30 14:14:42 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 11:14:42 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: On Mar 30, 12:11 pm, hdante wrote: (snip) > BTW, my opinion is that it's already time that programmer editors > have input methods advanced enough for generating this: > > if x ? 0: > ?y ? s: > if y ? 0: f1(y) > else: f2(y) That would be a nightmare. Programming language (or most computer-based texts) should only use basic ASCII characters, except if it can't be helped since typing non- ASCII characters is still unreliable. It'd also be a headache to memorize what keyboard combinations to use to type a character. Not to mention how much more complex would the keyboard design be. Also not mentioning how much more complex the language design would be to handle all those non-ASCII characters. From bj_666 at gmx.net Sun Mar 9 14:59:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Mar 2008 18:59:10 GMT Subject: SV: Changing the size of a Button References: <63ifhtF277va7U1@mid.individual.net> <63iokhF284p4hU1@mid.individual.net> Message-ID: <63iqbuF27chv6U2@mid.uni-berlin.de> On Sun, 09 Mar 2008 19:45:58 +0100, K Viltersten wrote: > What i wish to do is to affect the size > of the button but not due to change of > text but due to resize of the frame it > resides in. > > This far i've managed to get a callback > to a function as the resize occurs and to > print the sizes. However, i'd like to > assign these values to the button so it > always stays the same width as the frame. Don't do it yourself, pack with the `fill` argument set to `Tkinter.X`. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Mon Mar 24 04:03:55 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Mar 2008 04:03:55 -0400 Subject: Does python hate cathy? References: Message-ID: "QS" wrote in message news:a5e95efc-f8cd-4595-bbbd-f5f59c45ea89 at u72g2000hsf.googlegroups.com... >From the title, I assumed this was spam like others with similar titles -- and that the perl newsgroup, for instance, would have 'Does perl hate cathy? | I am new to python, and I encountered a weird problem. Observation: as you will learn, the form of the error message was different from the standard tracebacks one gets during program execution. This was a clue that it was a cleanup message and actually did make sense. Summary lessons. 1. What a Python interpreter does after it executes the last statement is undefined by the language spec. It could do absolutely nothing (and I wish some programs that wastefully spend minutes 'cleaning up' did just that!). CPython tries to do some cleanup when requested but the results are sometimes seemingly arbitrary. 2. If you use __del__, do so for a reason (and keeping a population count is one, though rare*), and explicitly delete the objects for which you want dependable behavior. *A population count is a good example of a class attribute. But it seems to be rare in practice because if one wants that, it seems that a population collection (with a len() method) is usually also wanted -- perhaps so one can iterate thru the population. 3. Experimenting with Python is a good way to learn. Keep it up! tjr From kw at codebykevin.com Tue Mar 11 13:57:46 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 11 Mar 2008 13:57:46 -0400 Subject: How to make a Tkinter widget always visible? In-Reply-To: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> Message-ID: <47D6C81A.1070301@codebykevin.com> Miki wrote: > Hello, > > I have a simple Tkinter window with [GO] and [Quit] buttons at the > bottom. > > When I resize the window to be shorter, the first thing to disappear > are the buttons, however I want these button to be visible at all > times. > > Is there a way to make sure that these buttons are always visible? > There are various ways to do this: you can set the window to be non-resizable, or set a minimum size to it, so that it can't be resized below that level. However, if you allow arbitrary resizing of the window, there's no real way to guarantee that the widgets will be visible at all times. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From dave_mikesell at fastmail.fm Sat Mar 8 09:59:42 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Sat, 8 Mar 2008 06:59:42 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> Message-ID: <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> On Mar 8, 2:38 am, Steven D'Aprano wrote: > On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote: > >> x = get_stuff(store) # Get the stuff what was brought at the store. > > > Perfect example of an unnecessary comment. The variable and function > > names are commentary enough. > > "x" is a terrible name. What does it mean? Nothing. Right, that's a problem with the code. A comment only masks the bad smell. 'x' should be renamed to something meaningful, obviating the need for comments to follow it around. > There's only three places x is an appropriate name: > (1) A meta-syntactic variable like foo, bar, spam, ham, parrot. > > (2) Library functions, where x stands for a generic argument, usually a > number, e.g. def sin(x). > > (3) Throw-away code you don't need to maintain. I use single letter variables where their scope is very small. e.g., tight loops, small functions, etc. I even use them as class members where they make sense in the domain. x, y, z for 3d vectors, r, g, b, a for colors, etc. > The function name also doesn't explain anything. How was the stuff got? > Was it paid for, or stolen, or picked up on consignment, or what? Compare > the above line with: > > x = get_stuff(store) # Steal stuff from the store. > > or > > x = get_stuff(store) # Pickup the stuff from the store for disposal. > # The amount paid by the store is stored in global variable "pay_received" > # and the name of the employee authorizing the pickup is stored in the > # global "authorized_by". Shouldn't get_stuff's comment be with its definition? And just rename the function to something more meaningful, like purchase_goods(store), or whatever. > > But even if you were right that the comment was unnecessary, you have > missed my point that even single sentences can be grammatically bogus and > the writer could learn a lot from Strunk and White or equivalent. I do agree with that 100%. It's a chore reading design and requirements docs where I work. My problem is with excessive comments. Comments are pathological liars. They almost invariably fall out of date with the code. From ed at leafe.com Mon Mar 31 22:41:37 2008 From: ed at leafe.com (Ed Leafe) Date: Mon, 31 Mar 2008 21:41:37 -0500 Subject: class super method In-Reply-To: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> References: <1c9f126b-63f6-402b-803d-39ce1df4c380@i12g2000prf.googlegroups.com> Message-ID: <09819F33-4661-480D-94FC-1BDB3118890A@leafe.com> On Mar 31, 2008, at 5:58 PM, George Sakkis wrote: >> is there any tutorial for super method (when/how to use it)? >> >> or maybe someone could explain me how it works? >> >> thx > > Super is one of the dark corners of the language [1,2]... a good rule > of thumb is to stay away from it, or at least stick to its basic > usage. I disagree - super is quite elegant and dependable. Because Python support multiple inheritance, it is difficult to manually ensure that when augmenting a method that the correct superclass calls are made. super() handles that without having to guess as to what the correct inheritance hierarchy is. In my own project (Dabo), we use mixin classes liberally to provide consistent behavior across our UI classes. The use of super makes customizing __init__() behavior, for example, quite straightforward. The general form looks like: class DaboUIClass(dabo.ui.dControlMixin, someWxPythonClass): def __init__(self, *args, **kwargs): doOurCustomStuffBeforeTheSuperCall() super(DaboUIClass, self).__init__(*args, **kwargs) doOurCustomStuffAfterTheSuperCall() This has worked reliably for us in every place where we have used it. There's nothing dark and mysterious about it at all. -- Ed Leafe From sturlamolden at yahoo.no Tue Mar 18 10:07:39 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Mar 2008 07:07:39 -0700 (PDT) Subject: About reading Python code References: <12dc8d66-5773-4e82-bcc6-3a8ca35945e0@i29g2000prf.googlegroups.com> <908d9fd5-b7fc-4c4b-af2f-2434a327ea6f@i29g2000prf.googlegroups.com> <61a3fe08-268e-464e-9ce5-cc00d7a2e3e2@f63g2000hsf.googlegroups.com> Message-ID: On 18 Mar, 08:00, hellt wrote: > under Microsoft Visual Studio do you mean IronPython instance? AFAIK, with the latest VS 2008 you can develop for CPython and IronPython. http://blogs.msdn.com/haibo_luo/archive/2007/10/16/5482940.aspx From sivashankari127 at gmail.com Thu Mar 6 03:01:46 2008 From: sivashankari127 at gmail.com (sivashankari127 at gmail.com) Date: Thu, 6 Mar 2008 00:01:46 -0800 (PST) Subject: The Fortunate Way!!! Message-ID: <211e06e3-a9e2-4b12-ad53-ae0a1016d121@u72g2000hsf.googlegroups.com> Hi, To know what it is? Click the website below - ---------------------------------------------------------------- http://myprofile127.blogspot.com ----------------------------------------------------------------- From ShiNingyu at gmail.com Wed Mar 12 12:58:30 2008 From: ShiNingyu at gmail.com (Ningyu Shi) Date: Wed, 12 Mar 2008 09:58:30 -0700 (PDT) Subject: Problem with subprocess in threaded enviroment Message-ID: <5972c513-c86c-42bf-bcc8-632dd0f0e8f0@i7g2000prf.googlegroups.com> I'm trying to write a multi-task downloader to download files from a website using multi-threading. I have one thread to analyze the webpage, get the addresses of the files to be downloaded and put these in a Queue. Then the main thread will start some threads to get the address from the queue and download it. To keep the maximum files downloaded concurrently, I use a semaphore to control this, like at most 5 downloads at same time. I tried to use urllib.urlretreive in the download() thread, but from time to time, it seems that one download thread may freeze the whole program. Then I gave up and use subprocess to call wget to do the job. My download thread is like this: def download( url ): subprocess.call(["wget", "-q", url]) with print_lock: print url, 'finished.' semaphore.realease() But later I found that after the specific wget job finished downloading, that download() thread never reach the print url statement. So I end up with files been downloaded, but the download() thread never ends and don't realease the semaphore then block the whole program. My guess is that at the time wget process ends, that specific download thread is not active and missed the return of the call. Any comment and suggestion about this problem? Thanks From hdante at gmail.com Sun Mar 30 00:45:11 2008 From: hdante at gmail.com (hdante) Date: Sat, 29 Mar 2008 21:45:11 -0700 (PDT) Subject: Help me on function definition References: Message-ID: <4c1c2834-2ecb-46b6-a4ee-eb29d23cbf1a@a1g2000hsb.googlegroups.com> On Mar 28, 10:47 pm, "aeneng" wrote: > Hello everyone, Hi, Always avoid reinventing the wheel: from Numeric import array, cross_product a = array([1, 2, 3]) b = array([4, 5, 6]) print cross_product(a, b) See: http://numpy.scipy.org/ http://www.scipy.org/ (hint: consider that many people want to multiply matrices) :-) > > I am just starting to use python in numerical cacluation. > I need you to help me to see what's wrong with the following piece of > codes, which computes the cross product of two vectors and returns > the result. u and v are two 3x1 matrix. > > when I import the function, error message show like this>>> import cross > > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? > > I appreciate your help. > > ##here is the function definition. > ##cross.py## > def cross(u,v) > """input two vectors u and v in 3-D space, > output a cross product of vector w, in column or in row > accordingly.""" > ppp1,ppp2,ppp3=0.0,0.0,0.0 > ppp1=u[1]*v[2]-u[2]*v[1] > ppp2=u[2]*v[0]-u[0]*v[2] > ppp3=u[0]*v[1]-u[1]*v[0] > # store the result of the cross product in u > u[0]=ppp1 > u[1]=ppp2 > u[2]=ppp3 > return u #return the cross product of vector u x v. > if __name__=="__main__": > from cvxopt.base import matrix > u=matrix([1.0,0.0,0.0],(3,1)) > v=matrix([0.0,1.0,0.0],(3,1)) > print cross(u,v) > print "file name is %s" %__name__ From sturlamolden at yahoo.no Sun Mar 30 16:56:53 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 30 Mar 2008 13:56:53 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig References: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> Message-ID: On 30 Mar, 22:21, kmg... at gmail.com wrote: > Hello everybody, > > I'm building a python module to do some heavy computation in C (for > dynamic time warp distance computation). Why don't you just ctypes and NumPy arrays instead? # double timewarp(double x[], int lenx, double y[], int leny); import numpy import ctypes from numpy.ctypeslib import ndpointer from ctypes import c_int _timewarp = ctypes.cdll.timewarp.timewarp # timewarp.dll array_pointer_t = ndpointer(dtype=double) _timewarp.argtypes = [array_pointer_t, c_int, array_pointer_t, c_int] def timewarp(x, y): lenx, leny = x.shape[0], y.shape[0] return _timewarp(x, lenx, y, leny) From george.sakkis at gmail.com Sun Mar 23 12:46:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 23 Mar 2008 09:46:57 -0700 (PDT) Subject: Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?) References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <64091803-4e72-4216-a0a2-879f096cddfb@e6g2000prf.googlegroups.com> On Mar 23, 12:24 pm, a... at pythoncraft.com (Aahz) wrote: > The problem with lambda is that too often it results in clutter (this is > a strictly made-up example off the top of my head for illustrative > purposes rather than any real code, but I've seen plenty of code similar > at various times): > > gui.create_window(origin=(123,456), background=gui.WHITE, > foreground=gui.BLACK, callback=lambda x: x*2) > > That means I need to pause reading the create_window() arguments while I > figure out what the lambda means -- and often the lambda is more > complicated than that. Moreover, because the lambda is unnamed, it's > missing a reading cue for its purpose. In a sense the lambda here is not unnamed; it's name is the name of the keyword argument, 'callback', which is indeed a poor name at in terms of self-documentation. I don't see how replacing the lambda with a (better) named function would be any better than using the same name as a keyword parameter. George From bernard.chhun at gmail.com Sat Mar 8 15:01:37 2008 From: bernard.chhun at gmail.com (Bernard) Date: Sat, 8 Mar 2008 12:01:37 -0800 (PST) Subject: identifying and parsing string in text file References: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> Message-ID: Hey Brian, It seems the text you are trying to parse is similar to XML/HTML. So I'd use BeautifulSoup[1] if I were you :) here's a sample code for your scraping case: from BeautifulSoup import BeautifulSoup # assume the s variable has your text s = "whatever xml or html here" # turn it into a tasty & parsable soup :) soup = BeautifulSoup(s) # for every element tag in the soup for el in soup.findAll("element"): # print out its tag & name attribute plus its inner value! print el["tag"], el["name"], el.string that's it! [1] http://www.crummy.com/software/BeautifulSoup/ On 8 mar, 14:49, "Bryan.Fodn... at gmail.com" wrote: > I have a large file that has many lines like this, > > name="DoseReferenceStructureType">SITE > > I would like to identify the line by the tag (300a,0014) and then grab > the name (DoseReferenceStructureType) and value (SITE). > > I would like to create a file that would have the structure, > > DoseReferenceStructureType = Site > ... > ... > > Also, there is a possibility that there are multiple lines with the > same tag, but different values. These all need to be recorded. > > So far, I have a little bit of code to look at everything that is > available, > > for line in open(str(sys.argv[1])): > i_line = line.split() > if i_line: > if i_line[0] == " a = i_line[1] > b = i_line[5] > print "%s | %s" %(a, b) > > but do not see a clever way of doing what I would like. > > Any help or guidance would be appreciated. > > Bryan From zerty.david at gmail.com Mon Mar 24 14:38:38 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 24 Mar 2008 15:38:38 -0300 Subject: Problems with wxPython In-Reply-To: <67dd1f930803241000tbce352fp93bf2df6e1d082b1@mail.gmail.com> References: <5dc598e30803240929w6ec8bf68ma9fdeaacaa25bfff@mail.gmail.com> <67dd1f930803241000tbce352fp93bf2df6e1d082b1@mail.gmail.com> Message-ID: <5dc598e30803241138q2aae53pb2c452946993ba1a@mail.gmail.com> Thanx On Mon, Mar 24, 2008 at 2:00 PM, Frank Niessink wrote: > Hi David, > > 2008/3/24, David Anderson : > > Hi, If ther's anyone who knows pretty much about wxPython can e-mail me? > I'm > > having some trouble in dealing with some guis here, I would thank u very > > much if you could help me > > You should subscribe to the wxPython users mailinglist and ask there. > It's a very helpful mailinglist. Robin Dunn (wxPython author) is very > active in answering questions from wxPython users. > > See http://www.wxpython.org/maillist.php > > Cheers, Frank > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From MartinRinehart at gmail.com Wed Mar 5 09:49:27 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 06:49:27 -0800 (PST) Subject: Better grammar.txt Message-ID: I previously posted a link to an improved, HTML-based, hyperlinked grammar.txt. Discard that one. This one is much better. http://www.martinrinehart.com/articles/python-grammar.html If you find it useful, thank Gabriel Genellina for encouraging me to get it really right. It includes three corrections to grammar.txt (imagnumber, xor_expr and and_expr) that I've reported. From rockxuan at gmail.com Tue Mar 18 03:44:29 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:44:29 -0700 (PDT) Subject: Swiss watch in www.51cntrade.com Message-ID: <69d413f0-8e96-40b6-a7af-f860957bf044@h11g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From micah at micah.cowan.name Sun Mar 2 16:59:13 2008 From: micah at micah.cowan.name (Micah Cowan) Date: Sun, 02 Mar 2008 21:59:13 GMT Subject: Book Recomendations References: Message-ID: <87bq5w7poh.fsf@micah.cowan.name> Tommy Nordgren writes: > On 2 mar 2008, at 01.56, Ira Solomon wrote: > >> I am an experienced programmer (40 years). I've done Algol (if you've >> heard of that you must be old too), PL/1, VB,VBA, a little C, and a >> few other odd languages (e.g. Taskmate). >> I'm interested in learning Python and have downloaded a slew of books. >> Too many. >> I'd like a recommendation as to which books are considered to be the >> cream of the crop. >> I know there are tutorials on the web, but, again, I don't know the >> quality. I would appreciate recommendations on those as well. >> >> Thanks >> >> Ira >> -- >> http://mail.python.org/mailman/listinfo/python-list > I would recommend "Programming Python", by Mark Lutz, from O'Reillys Programming Python assumes you already have a working knowledge of basic Python programming (that is, it assumes you've read Learning Python). -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From ptmcg at austin.rr.com Tue Mar 25 16:22:06 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 25 Mar 2008 13:22:06 -0700 (PDT) Subject: Circular references not being cleaned up by Py_Finalize() References: <763da51b-6fa2-435d-89f4-71b7fedc65bb@e6g2000prf.googlegroups.com> Message-ID: <9f735816-98a6-4d52-bafc-843c96296c1b@d62g2000hsf.googlegroups.com> On Mar 25, 2:32?pm, blackpawn wrote: > I've been trying to get garbage collection of circular references to > work properly with no success then I noticed the documentation stating > that it just doesn't: > > From documentation on Py_Finalize() -> "Memory tied up in circular > references between objects is not freed. " > > I copy pasted the Noddy example for circular reference breaking from > the documentation and set a break point in its Noddy_dealloc function > and sure enough even that simple example doesn't work properly. > > So what's the deal here? ?:) ?I want all objects to be freed when I > shut down and their destruction functions to be properly called. ?Is > there really no way to make this happen? > > Many thanks for any insights, > Jim It sounds like you are using finalizers like destructors in C++. Don't do this. Garbage collection is not deterministic, and is not supposed to be. Instead, use language features that do similar scope-driven code execution: - try/except/finally - with Put your cleanup code in the finally block, or in the context managers __exit__ method. These will run when the program exits the given scope, without having to play GC shenanigans. -- Paul From ebgssth at gmail.com Sun Mar 2 02:16:42 2008 From: ebgssth at gmail.com (js) Date: Sun, 2 Mar 2008 16:16:42 +0900 Subject: Book Recomendations In-Reply-To: References: Message-ID: I wonder why nobody mension Python Cookbook yet. http://www.oreilly.com/catalog/pythoncook2/ Web version: http://aspn.activestate.com/ASPN/Cookbook/Python/ and Python Standard Library http://www.oreilly.com/catalog/pythonsl/ http://effbot.org/zone/librarybook-index.htm On Sun, Mar 2, 2008 at 4:09 PM, Paddy wrote: > On Mar 2, 12:56 am, Ira Solomon wrote: > > I am an experienced programmer (40 years). I've done Algol (if you've > > heard of that you must be old too), PL/1, VB,VBA, a little C, and a > > few other odd languages (e.g. Taskmate). > > I'm interested in learning Python and have downloaded a slew of books. > > Too many. > > I'd like a recommendation as to which books are considered to be the > > cream of the crop. > > I know there are tutorials on the web, but, again, I don't know the > > quality. I would appreciate recommendations on those as well. > > > > Thanks > > > > Ira > > Hi Ira, > Get Python installed on your machine - I would suggest the latest 2.5 > release then either start up idle (or pythonwin if you have that on > windows), or just type python at a command line prompt to get you to > pythons shell. > > The Python shell together with the official tutorial is a great way to > learn Python. > > If you start to flag, then their are a few videos of pre-teen kids > learning Python here: > http://showmedo.com/videos/python?topic=beginner_programming > If they can learn it .... ;-) > > Welcome to Python, have fun! > > - Paddy. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From benhoyt at gmail.com Wed Mar 19 04:15:45 2008 From: benhoyt at gmail.com (Ben Hoyt) Date: Wed, 19 Mar 2008 21:15:45 +1300 Subject: Is there a way to get __thismodule__? In-Reply-To: <82d28c40803182131j7b887a34j77c2a36586628193@mail.gmail.com> References: <2697e303-a472-4bf9-bc20-00863fdcee39@i29g2000prf.googlegroups.com> <82d28c40803182131j7b887a34j77c2a36586628193@mail.gmail.com> Message-ID: <7c93bf1e0803190115nde6f155y44065f00ab8efe88@mail.gmail.com> Aha! Thanks, Jeff. I'd heard about metaclasses, but never really seen them used. Your example was very helpful. This is somewhere that I would personally use a metaclass. That way, > if you define more subclasses of Message, you're not limited to doing > so in that single module. > Cheers, Ben. -- Ben Hoyt, http://benhoyt.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Mar 14 07:39:23 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Mar 2008 12:39:23 +0100 Subject: app runs fine with interpreter, but not under py2exe References: Message-ID: Doug Morse wrote: > from multiarray import zeros > import string > > typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', > 'Float':'fd', 'Complex':'FD'} > > def _get_precisions(typecodes): > ? ? lst = [] > ? ? for t in typecodes: > ? ? ? ? lst.append( (zeros( (1,), t ).itemsize()*8, t) ) ? <-- Line 18 > ? ? return lst > > def _fill_table(typecodes, table={}): > ? ? for key, value in typecodes.items(): > ? ? ? ? table[key] = _get_precisions(value) > ? ? return table > > _code_table = _fill_table(typecodes) > > I can't find any reason why line 18 is throwing a "data type not > understood" error. ?It doesn't seem to have anything to do with dynamic > importing, but I can't be sure. ?I would note that "zeros" is a built-in > function found in the "python dll" multiarray.pyd (in the Numeric module > directory). I don't know why, but your module seems to use numpy's multiarray instead of Numeric's: >>> from multiarray import zeros >>> zeros((1,), "1") array([0], '1') >>> from numpy.core.multiarray import zeros >>> zeros((1,), "1") Traceback (most recent call last): File "", line 1, in TypeError: data type not understood Peter From rurpy at yahoo.com Mon Mar 17 16:48:49 2008 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 17 Mar 2008 13:48:49 -0700 (PDT) Subject: elementtree and entities Message-ID: I need to parse little snipits of xml that come from a file that has a large DTD that defines hundreds or entities. But when these snipits are parsed (with elementtree.XML()) without the DTD, the entities are undefined and cause a parse failure. Is there any way to tell elementtree to not fail on undefined entities but just return the entity as text? (Or is this something I have to get the underlying parser to do? How?) Alternatively, can I supply my own entity mapping to elementtree? Prepending the large DTD to each little snippit before parsing seems awfully inefficient. From duncan.booth at invalid.invalid Mon Mar 24 05:52:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Mar 2008 09:52:21 GMT Subject: On copying arrays References: Message-ID: ernesto.adorio at gmail.com wrote: > Is there a conceptual difference between > best =test[:] > and > best = [x for x in test] ? > test is a list of real numbers. Had to use the second form to avoid a > nasty bug > in a program I am writing. I have to add too that I was using psyco > in Python 2.5.1. > The first one will only copy sliceable sequences and will give you a result of the same type as test (e.g. if test is a tuple so is best). The second one will copy any sequence, always results in a list and as a side effect assigns a value to 'x'. The method usually recommended is: best = list(test) as it has no side effects, copies any sequence and may be faster than the list comprehension. As with the second of your examples it always gives you a list. From noreply at noreply.org Wed Mar 19 17:29:33 2008 From: noreply at noreply.org (some one) Date: Wed, 19 Mar 2008 15:29:33 -0600 Subject: Script Request... References: <64ccfbF2bbfckU1@mid.uni-berlin.de> Message-ID: Thanks Diez, I found some docs and examples on urllib2. Now how do i search the string I get from urllib2, lets say I put it in "myURL", How do I search for only Numbers and ".'s" in the "#.#.#.#" pattern. That is all I am interested in with all the data retrieved. Just the IP Address from amongst a bunch of data that I have no use of currently. I would I write a pattern matching function to extract only the IP address from "myURL"? In article <64ccfbF2bbfckU1 at mid.uni-berlin.de>, deets at nospam.web.de says... > some one wrote: > > > Hi all, I am not to familiar with python yet and I am wondering if > > someone can write a script that will monitor my DSL modems IP address > > and notify when it changes, its a 2Wire Advanced DSL Modem. I need to > > know when it changes because I am trying to run my own inhouse server > > and have to update my domain records through verio.com. > > > > The script would need to read the text of a web page( on my modem the > > address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and > > search for a string containing the IP address. > > > > Can anyone help? > > thanks, I'll keep monitoring this thread. > > Try urllib2 to fetch the data, use either string-search, regular expressions > or even BeautifulSoup to extract the data. Use a cron-job to do that on a > regular base or use module time.sleep() together with an endless loop to > monitor that location periodically. > > Show us your concrete efforts, and we will suggest improvements. > > Diez > From Lie.1296 at gmail.com Tue Mar 11 13:06:17 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 11 Mar 2008 10:06:17 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> <9ac08385-c11e-422a-acd3-e61e284077da@u10g2000prn.googlegroups.com> Message-ID: <152176bd-1249-4c14-9ce8-7334aa52ad9d@d21g2000prf.googlegroups.com> On Mar 11, 11:47?pm, Lie wrote: > On Mar 10, 12:08?pm, Nathan Pinno wrote: > > > How do I factor a number? I mean how do I translate x! into proper > > Python code, so that it will always do the correct math? > > > Thanks in advance, > > Nathan P. > > Factorial algorithm is a very simple and common algorithm, and it's > one of the most basic of all recursive algorithm > def fact(x): > ? ? return x * fact(x - 1) As an exercise (actually I forget), I'll let you figure out yourself why the above function doesn't work. There is only one simple line to be added and all's done. Hint: There are two important elements in all recursive algorithm, the catch-all return statement (which I've given you) and the conditioned return statement (which you've got to figure out yourself) From sjmachin at lexicon.net Sun Mar 23 19:31:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Mar 2008 16:31:29 -0700 (PDT) Subject: PyTuple_Check and other type check functions didn't check the NULL pointer References: <7c8b81aa-9cda-4bb5-926e-ec04042140a1@n58g2000hsf.googlegroups.com> Message-ID: <95174442-c7c0-452b-b2e8-e321d25832d2@c19g2000prf.googlegroups.com> On Mar 24, 10:01 am, NotGuru wrote: > I was writing some C extensions for Python and use PyTupleType_Check > extensively. I found that all the PySomeType_Check macros directly > delegate the job to PyObject_TypeCheck(op, &PyType_Type). The > PyObject_TypeCheck(op, &PyType_Type) is again a macro and defined as > ((ob)->ob_type == (tp) || PyType_IsSubtype((ob)->ob_type, (tp))) > > in object.h. > > My questions is: is it necessary to check the null pointer in the > macro or it's a job for the user? Semantically all the type check > should report a false if a null pointer is encountered. I've already > had the patch to this issue but I am not sure if I think this problem > right. I don't know if there are some python core developers around > but I would like to hear all opinions towards this. > > BTW, if the user didn't check null pointer before call the function, a > segmentation fault might occur. You should check for null pointer returned by any C-API function that is meant to return an object pointer; this indicates that an exception has happened; your code should clean up and exit. See section 1.3 of the Python/C API Reference Manual. From fuzzyman at gmail.com Sun Mar 30 13:29:22 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 30 Mar 2008 10:29:22 -0700 (PDT) Subject: Buffer Overflow with Python 2.5 on Vista in import site References: Message-ID: On Mar 30, 3:53 am, "Gabriel Genellina" wrote: > En Sat, 29 Mar 2008 17:34:27 -0300, Fuzzyman escribi?: > > > A very odd error with Python 2.5 (both 2.5.1 and 2.5.2 from the > > official msi installers and running on Vista under Parallels on the > > Mac). > > It may be actually a Parallels issue - I've installed 2.5.1 on Vista (just > once, on a real PC) and it worked fine. Anyway a better place for bug > reports is bugs.python.org > > Mmm, maybe you should check all your .pth files - looks like this strange > path comes from one of them. I think it comes from the '._something.pth' that Textmate created as a temporary file when I edited a 'pth' file. The 'macromates' text in their is from textmate. I'm not sure if it is Mac specific or Texmate specific, but those temp files are really annoying. Thanks. Michael http://www.ironpythoninaction.com/ > > -- > Gabriel Genellina From rpdooling at gmail.com Wed Mar 26 15:50:51 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Wed, 26 Mar 2008 12:50:51 -0700 (PDT) Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: On Mar 26, 9:12 am, waltbrad wrote: > On his command line he types: > > C:\...\PP3E>Launcher.py > > and this begins the program. Doesn't work for me. I have to type: > > C:\...\PP3E>python Launcher.py > > Is this a typo on his part or has he configured his settings in such a > way that the command line will automatically associate the extension > with the program? (If so, he didn't mention this in his book). Browse this thread on clp: http://tinyurl.com/2wbnde RD From timr at probo.com Wed Mar 19 03:18:10 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 19 Mar 2008 07:18:10 GMT Subject: placing a Python com object into Excel References: <47deefc5$0$906$ba4acef3@news.orange.fr> Message-ID: Mathew wrote: >Thanks for the tip. But, instead of an AddIn, what if I want to be able >to insert an object? I see that the demo adds items to the windows >registry under \Excel\AddIns. Is there a similar location for the >"Insert Object" command? What you see there is the list of registered ActiveX controls. You need to implement a few additional interfaces. I believe IOleInPlaceObject is required to satisfy Excel. http://msdn2.microsoft.com/en-us/library/aa751972.aspx -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Tue Mar 4 16:40:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 4 Mar 2008 16:40:53 -0500 Subject: for-else References: Message-ID: wrote in message news:c4921e6c-119f-4306-8e89-c436c3cb6f6d at u69g2000hse.googlegroups.com... | So far in Python I've almost hated the 'else' of the 'for' loops: | - I have problems to remember its meaning; Consider the following pseudoPython which you should understand: label: loop if cond: do_something() goto loop else: do_else() We actually write the above as while cond: do_something() else: do_else() Same meaning; do_else is executed when condition is false. A for-loop is equivalent to a while loop with the condition 'iterator is not exhausted'. So do_else when that condition is false -- the iterator is exhausted. Terry Jan Reedy From davidj411 at gmail.com Tue Mar 11 10:58:28 2008 From: davidj411 at gmail.com (davidj411) Date: Tue, 11 Mar 2008 07:58:28 -0700 (PDT) Subject: difference b/t dictionary{} and anydbm - they seem the same References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> Message-ID: <7d041a6a-2a74-401e-ab5d-97d5af3a6196@e60g2000hsh.googlegroups.com> > Persistent storage /is/ the benefit. If you want to store relational > data, you should use a relational database. Thanks, that makes sense. Are there any local relational databases available to python that don't require a server backend? From noreply at noreply.org Thu Mar 20 06:45:15 2008 From: noreply at noreply.org (some one) Date: Thu, 20 Mar 2008 04:45:15 -0600 Subject: What is The Eric4 IDE??? Message-ID: I wanted to ask some opinions on the Eric4 Python IDE, It was the second result from google using the search term "Python IDE" (Quotes Included in the search), the first being http://wiki.python.org/moin/IntegratedDevelopmentEnvironments ! I haven't downloaded or installed it yet, since it has the prerequisites of: 1) Python 2.4.0 or better http://www.python.org/download/ 2) Qt 4.2.0 or better (from Trolltech) http://trolltech.com/solutions/solutions-opensource 3) PyQt 4.1.0 or better (from Riverbank) http://www.riverbankcomputing.co.uk/pyqt/index.php 4) QScintilla 2.1 or better (from Riverbank) http://www.riverbankcomputing.co.uk/qscintilla/index.php I see on the Eric4 website ( http://www.die-offenbachs.de/eric/eric4- download.html ) that it is also a commercial product for those not working with OpenSource, so I hope it's safe to assume that it's a good product to use for working with Python. I'd like some other opinions about it before I download and install all the prerequisites. They probably require their own specific configurations. Is there an OpenSource bundle with all the prerequisites for a smoother install? Is there a specific order to install the prerequisites? Thanks in advance for your replies. From gagsl-py2 at yahoo.com.ar Thu Mar 27 18:36:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 19:36:02 -0300 Subject: python program deleted References: <200803271808.06157.inq1ltd@inqvista.com> Message-ID: En Thu, 27 Mar 2008 19:08:05 -0300, jim-on-linux escribi?: > I developed a python program and used py2exe > to create the exe. > > I zip the entire package and email it to my > clients. > > Some clients get the zip file, unzip the > package and everything works fine. > > And some clients get my email with an icon > attached which has the correct filename but > the size is 8k when it should be about 5 mb. > > I've renamed the file without the zip ext. > and tried other renaming schemes without > success. > > Has anyone had this experience? Any ideas on > how to solve this problem. Yes: don't send the program by email :) Put it somewhere for your customers to download. Use some authorization scheme (user/password) if needed. -- Gabriel Genellina From steve at holdenweb.com Sat Mar 1 15:01:51 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Mar 2008 15:01:51 -0500 Subject: Surprised by the command "del" In-Reply-To: <62tq9sF24juhrU1@mid.individual.net> References: <62tq9sF24juhrU1@mid.individual.net> Message-ID: K Viltersten wrote: > I'm reading the docs and at 5.2 the del > statement is discussed. At first, i thought > i've found a typo but as i tried that > myself, it turns it actually does work so. > > a = ["alpha", "beta", "gamma"] > del a[2:2] > a > > Now, i expected the result to be that the > "beta" element has been removed. Obviously, > Python thinks otherwise. Why?! > > Elaboration: > I wonder why such an unintuitive effect has > been implemented. I'm sure it's for a very > good reason not clear to me due to my > ignorance. Alternatively - my expectations > are not so intuitive as i think. :) > It deletes all the elements referred to by the slice. But since 2-2==0, there are zero elements in the slice, and the list is unchanged when all zero of them have been deleted: >>> a = ["alpha", "beta", "gamma"] >>> a[2:2] [] >>> You would have got the result you expected with del a[2] or del a[2:3] or del a[-1] or ... Remember that slices are specified as half-open intervals. So a[m:n] includes m-n elements, those indexed from m to n-1. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fetchinson at googlemail.com Tue Mar 11 02:20:53 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 10 Mar 2008 23:20:53 -0700 Subject: image matching algorithms In-Reply-To: References: Message-ID: > | The various free tools differ by their chosen optimization paths and > | their degree of specialization. My preference would be, > | > | 1. Doesn't really matter how long it takes to compute the N numbers per > image > > Your problem here is that there is really no such thing as 'general > features' and correspondingly, no such thing as 'general similarity of > features'. Yes there are! :) Image manipulation experts defined dozens of ways of characterizing what 'similarity' means for images and all I was asking is whether anyone here knew of a simple one. > The features extracted have to have a specific definition. The > features represent a severe lossy compression of the original. What to > keep depends on the application. Yes, and if you know *any* simple but useful (yes, useful, in *any* sense) definition, I'd be happy to hear it. > Example: classify each pixel as white, black, red, green, or blue. Will > that match your intuitive idea of what matches? Probably not, but thanks for the idea. > To be a bit more sophisticated, use more color bins and do the binning > separately for multiple areas, such as top, left, center, right, and bottom > (or center, upper right, upper left, lower right, and lower left). I > suspect Google does something like this to match, for instance, pictures > with skin tones in the center, or pictures with blue tops (sky?) and green > bottoms (vegetation?). Now this sounds like a simple and good idea. I'll try this and see how far I get. > | 2. Lookups should be fast, consequently N should not be too large (I > guess) > | 3. It should be a generic algorithm working on generic images (everyday > photos) > > Given feature vectors, there are various ways to calculate a distance or > similarity coefficient. There have been great debates on what is 'best'. True. As I've said, *any* but concrete and useful example would make me happy. > | 4. PIL should be enough for the implementation > | > | So if anyone knows of a good resource that is close to being pseudo > | code I would be very grateful! > > If you do not have sufficient insight into your own idea of 'matches', try > something on a test set of perhaps 20 photos, calculate a 'match matrix', > and compare that you your intuition. Yes, this is what I'll do. The second thing I'll try (after trying your suggestion) is based on this paper which I found in the meantime: http://salesin.cs.washington.edu/abstracts.html#MultiresQuery In case anyone is interested, it describes a multiresolution querying algorithm and best of all, it has pseudo code for the various steps. I don't know yet how difficult the implementation will be but so far this looks the most promising. Cheers, Daniel From siona at chiark.greenend.org.uk Fri Mar 7 07:44:14 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 07 Mar 2008 12:44:14 +0000 (GMT) Subject: Difference between 'function' and 'method' References: Message-ID: Gabriel Genellina wrote: >En Thu, 06 Mar 2008 23:46:43 -0200, escribi???: >> [ ... ] >You may look at the SimpleXMLRPCServer class and see how it implements >introspection. It's rather easy (and doesn't require metaclasses nor >decorators nor any other fancy stuff; I think it works the same since >Python 2.1). Apparently you're doing a similar thing, but using pickles >instead of xmlrpc. It's not that difficult to graft pickles into SimpleXMLRPCServer -- I've done it, and if you're trying to sling large data structures over the connection it's a massive performance win (even with sgmlop in place to speed up XML parsing). -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From ilkeston at ntlworld.com Sun Mar 2 09:15:09 2008 From: ilkeston at ntlworld.com (Steve Turner) Date: Sun, 2 Mar 2008 14:15:09 -0000 Subject: First post from a Python newbiw Message-ID: I finally decided to have a go with Python and am working through the tutorial. On my old BBC Computer I could do something like this: DIM A(2,2) to create a 3 by 3 array of data. Then I could set any point: A(0,0) = foo A(0,1) = bar etc. In Python I thought I could do this with: >>> a=[0,0,0] >>> b=[a,a,a] >>> b [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> b[1][1]='foo' >>> b [[0, 'foo', 0], [0, 'foo', 0], [0, 'foo', 0]] >>> I can understand why as b[1][1]='foo' is actually changing a[1] Apart from doing something like a=[0,0,0] b=[0,0,0] c=[0,0,0] d=[a,b,c] is there a better way of creating d?? -- Steve From miki.tebeka at gmail.com Sun Mar 9 14:11:12 2008 From: miki.tebeka at gmail.com (Miki) Date: Sun, 9 Mar 2008 11:11:12 -0700 (PDT) Subject: Changing the size of a Button References: <63ifhtF277va7U1@mid.individual.net> Message-ID: Hello Konrad, > How do i change the size of a Button > (using Tkinter), other than to set it > during construction? In Tkinter, usually the geometry managers (such as pack) are the ones who size the widgets. If you run something like: import Tkinter as tk root = tk.Tk() def change_size(): b["text"] = "More text" b = tk.Button(root, text="Text", command=change_size) b.pack() root.mainloop() You'll see that the button changes size to accommodate the new text. HTH, -- Miki http://pythonwise.blogspot.com From fakeaddress at nowhere.org Fri Mar 21 08:31:08 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 21 Mar 2008 05:31:08 -0700 Subject: What Programming Languages Should You Learn Next? In-Reply-To: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> References: <998418a1-0b08-4c81-8c21-02f33738d66f@e10g2000prf.googlegroups.com> Message-ID: wesley chun wrote: > http://it.slashdot.org/it/08/03/18/1633229.shtml > > it was surprising and disappointing that Python was not mentioned > *anywhere* in that article but when someone replied, it sparked a long > thread of post-discussion. What I found disappointing was how many people thought they should be answering the question rather than asking it. I'm good with a number of popular languages, and I can talk knowledgeably and BS-free about many more. In grad school, I had an instructor who is a real programming language expert. Listening to his lectures was sometimes a bit like watching ESPN show the world championship of a game at which I usually beat my friends. There are levels beyond levels beyond my level. And I'm a pro. It is to the shame of my alma mater that they denied tenure to Dr. Sasaki. -- --Bryan From http Sat Mar 29 07:59:00 2008 From: http (Paul Rubin) Date: 29 Mar 2008 04:59:00 -0700 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> Message-ID: <7x3aq9212z.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > reserve <> for "greater than or less than but not equal to" which is > subtly different. (Think about unordered values, where x != y does not > imply that x < y or x > y, e.g. IEEE NaNs.) Heh, good point. > > The scary choice is /= which can be interpreted as an assignment. > "Can be"? Yes, what I mean is that some languages (e.g. Ada, Haskell) use /= for nonequality. So if you switch between Haskell and C, you could find yourself typing /= when you mean != and the compiler won't flag it. From aahz at pythoncraft.com Tue Mar 11 15:37:59 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Mar 2008 12:37:59 -0700 Subject: mulithreaded server References: <0e845694-2788-43e2-b88b-86bbbbe3c7c0@e23g2000prf.googlegroups.com> Message-ID: In article <0e845694-2788-43e2-b88b-86bbbbe3c7c0 at e23g2000prf.googlegroups.com>, asit wrote: >On Mar 11, 9:10 pm, Jean-Paul Calderone wrote: >> On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit wrote: >>> >>>In the above program, why there is an unhandeled exception ??? >> >> Just a guess. You should really include the traceback when you ask a >> question like this. > >It's not a traceback error. It's an unhandeled exception..please help http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From bearophileHUGS at lycos.com Fri Mar 7 07:49:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 7 Mar 2008 04:49:19 -0800 (PST) Subject: islice ==> [::] Message-ID: <141e8067-14e2-4670-8a4b-e98cdba1558c@x30g2000hsd.googlegroups.com> I find itertools.islice() useful, so for Python 3.x I may like to see it removed from the itertools module, and the normal slicing syntax [::] extended to work with generators/iterators too. from itertools import islice primes = (x for x in xrange(1,999) if all(x % y for y in xrange(2, x))) print list(islice(primes, 0, 20)) ==> print list(primes[:20]) Bye, bearophile From castironpi at gmail.com Fri Mar 7 17:26:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 7 Mar 2008 14:26:25 -0800 (PST) Subject: Want - but cannot get - a nested class to inherit from outer class References: Message-ID: <18b456bf-bc3d-45f6-af92-369e01e0f426@o77g2000hsf.googlegroups.com> On Mar 7, 3:19?pm, "Chris Mellon" wrote: > On Fri, Mar 7, 2008 at 3:00 PM, DBak wrote: > > > ?I would like to build a class for a data structure such that nodes of > > ?the data structure - of interest only to the data structure > > ?implementation itself and not to the consumer - are instances of one > > ?of two class types. ?I thought to encapsulate the nodes' classes [a certain way] > Not only is the name not defined, the class doesn't even exist yet. > > > ?What is the Pythonic thing I should be doing instead? > > Don't nest them. [ Too much anything is waste.] You expose a problem with the way I and some others write code. Humans have enormous "mental stacks"--- the stacks the contexts the speakers speak in push things they're hearing on to. When writing for computers, even those that speak Python, you have to say one thing at a time, and let it get its mind around it. They're not that deep, they're just at a deep depth. (The depth the ocean the submarine's in has, not the depth the submarine's -at-.) Marvelous memories, though. Your robotic snake can also do symbolic calculus, radio to clusters, and generate arbitrary auditory waveforms. But in a snake, the snake functions are primary. What's a multiplexer? From reginaa11111 at gmail.com Mon Mar 17 06:50:03 2008 From: reginaa11111 at gmail.com (reginee) Date: Mon, 17 Mar 2008 03:50:03 -0700 (PDT) Subject: THE AMAZING GOOGLE NETWORK INVITES YOU TO MAKE MILLIONS OF DOLLARS BY DOING A SIMPLE ONLINE WORK.THE LINK IS BELOW Message-ID: <62538771-9cc4-45ec-9638-a35b7aca4935@e6g2000prf.googlegroups.com> THE AMAZING GOOGLE NETWORK INVITES YOU TO MAKE MILLIONS OF DOLLARS BY DOING A SIMPLE ONLINE WORK.THE LINK IS BELOW www.jeeva235.blogspot.com IF YOU WORK LITTLE HARD YOU MAY EARN $3,00,000 IN A SINGLE PROJECT From dstromberglists at gmail.com Thu Mar 20 14:45:55 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 20 Mar 2008 18:45:55 GMT Subject: Python to C/C++ References: <27CC3060AF71DA40A5DC85F7D5B70F3802D197B7@AWMAIL04.belcan.com> Message-ID: On Wed, 19 Mar 2008 10:24:16 -0700, Patrick Mullen wrote: > (sorry michael, didn't mean to personal post > > On Wed, Mar 19, 2008 at 9:24 AM, Michael Wieher wrote: > > I think py2exe does this, but it might be a bit bloated > > No, py2exe basically bundles the main script and the interpreter > together so it's easy to run and requires no python installation. > > Look into pyrex and pypy. A mature translator doesn't exist. Also > there is ctypes which goes in reverse letting you use more c from > python easily. I believe pyrex allows you to write very python-like code but build a binary extension module from it that runs at nearly C speed. ISTR it does generate .c files. There's also shedskin, which I believe is a static python -> C++ translator that was written as part of google's summer of code. From jphalip at gmail.com Mon Mar 24 07:21:29 2008 From: jphalip at gmail.com (Julien) Date: Mon, 24 Mar 2008 04:21:29 -0700 (PDT) Subject: Shortcutting the function call stack Message-ID: Hello all, I would like to do something like: def called(arg) if arg==True: !!magic!!caller.return 1 def caller(arg) called(arg) return 2 Here, the fake !!!magic!!! represents a statement (which I ignore) that would make the caller function return a value different from what it'd return normally. For example, caller(True) would return 1, and caller(False) would return 2. The reason I want that is because I don't want the caller function to know what's going on in the called function, and be shortcut if the called function think it's necessary. Would you know if that's possible, and if so, how? I've done a bit of research and I think I've found some good pointers, in particular using the 'inspect' library: import inspect def called(arg) if arg==True: caller_frame = inspect.stack()[1] ... Here 'caller_frame' contains the frame of the caller function. Now, how can I make that frame return a particular value? By the way, I'm not really interested in 'called' throwing an exception and 'caller' catching it. In fact, I want things to remain completely transparent for 'caller'. Hope that was clear... :/ Thanks! Julien From floris.bruynooghe at gmail.com Fri Mar 14 10:47:15 2008 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Fri, 14 Mar 2008 07:47:15 -0700 (PDT) Subject: How to send a var to stdin of an external software References: Message-ID: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> On Mar 14, 11:37 am, Benjamin Watine wrote: > Bryan Olson a ?crit : > > > I wrote: > >> [...] Pipe loops are tricky business. > > >> Popular solutions are to make either the input or output stream > >> a disk file, or to create another thread (or process) to be an > >> active reader or writer. > > > Or asynchronous I/O. On Unix-like systems, you can select() on > > the underlying file descriptors. (MS-Windows async mechanisms are > > not as well exposed by the Python standard library.) > > Hi Bryan > > Thank you so much for your advice. You're right, I just made a test with > a 10 MB input stream, and it hangs exactly like you said (on > cat.stdin.write(myStdin))... > > I don't want to use disk files. In reality, this script was previously > done in bash using disk files, but I had problems with that solution > (the files wasn't always cleared, and sometimes, I've found a part of > previous input at the end of the next input.) > > That's why I want to use python, just to not use disk files. > > Could you give me more information / examples about the two solutions > you've proposed (thread or asynchronous I/O) ? The source code of the subprocess module shows how to do it with select IIRC. Look at the implementation of the communicate() method. Regards Floris From dickinsm at gmail.com Sat Mar 8 12:03:09 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 8 Mar 2008 09:03:09 -0800 (PST) Subject: float / rounding question References: <13t456cmgfpdhbc@corp.supernews.com> Message-ID: <29d0e1f9-3554-4f92-8a01-9519fb9d30d1@60g2000hsy.googlegroups.com> On Mar 8, 11:34?am, Mark Dickinson wrote: > following, which arises from Python arbitrarily stripping trailing > zeros from the result returned by the C library functions: Correction: on closer examination it's not Python doing the stripping of trailing zeros; it's the C library. Mark From manlio_perilloNO at SPAMlibero.it Wed Mar 26 15:08:48 2008 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Wed, 26 Mar 2008 19:08:48 GMT Subject: Beta testers needed for a high performance Python application server References: <47e99237$0$90273$14726298@news.sunsite.dk> <680787f0-0a1e-4087-b765-5fc0ae2eba56@s12g2000prg.googlegroups.com> <47e9f77b$0$36357$742ec2ed@news.sonic.net> Message-ID: <4bxGj.275580$%k.395923@twister2.libero.it> Il Wed, 26 Mar 2008 00:22:38 -0700, John Nagle ha scritto: > Graham Dumpleton wrote: >> Yes that is a viable option, as still are existing fastcgi solutions >> for Apache, lighttpd and nginx. > > Fast cgi is a good technology, Well, not really so good: http://twistedmatrix.com/pipermail/twisted-web/2006-April/002598.html > but it's not well documented or > well supported. For some reason, the Apache people don't like it. It > used to be part of the Apache distribution, but that ended years ago. > > It's more reliable than using things like mod_python, where you have > application code running in the web server's address space. That > creates both security problems and robustness problems. If an fcgi > process crashes, it is automatically replaced by a fresh copy of the > program at the next request. Other activity in progress is not > affected. Also, fcgi processes are reloaded after some number of > requests, so minor memory leaks won't choke the system over time. > The problem is simple: why put an extra server layer between an HTTP client and an HTTP server? Moreover, you should not use mod_python as an example. The WSGI module for Apache has a lot of feature for reducing these problems; and as an alternative you can use the WSGI implementation for Nginx. > [...] Manlio Perillo From P.G.Aravindh at gmail.com Mon Mar 10 10:21:45 2008 From: P.G.Aravindh at gmail.com (Santhosh) Date: Mon, 10 Mar 2008 07:21:45 -0700 (PDT) Subject: Recipies of South INDIA Message-ID: If you want to know how to make delicious South Indian foods please visit http://recipesoftamilnadu.blogspot.com/ From tsuraan at gmail.com Sat Mar 15 22:56:35 2008 From: tsuraan at gmail.com (tsuraan) Date: Sat, 15 Mar 2008 21:56:35 -0500 Subject: Urgent : How to do memory leaks detection in python ? In-Reply-To: References: Message-ID: <84fb38e30803151956w3af4db24pca2740c79760981e@mail.gmail.com> > Python doesn't have memory leaks. Yeah, interesting bit of trivia: python is the world's only non-trivial program that's totally free of bugs. Pretty exciting! But seriously, python 2.4, at least, does have some pretty trivially exposed memory leaks when working with strings. A simple example is this: >>> letters = [chr(c) for c in range(ord('a'), ord('z'))+range(ord('A'), ord('Z'))] >>> ary = [] >>> for a in letters: ... for b in letters: ... for c in letters: ... for d in letters: ... ary.append(a+b+c+d) ... >>> del(ary) >>> import gc >>> gc.collect() 0 The VM's memory usage will never drop from its high point of (on my computer) ~200MB. Since you're using GIS data, this could be what you're running into. I haven't been able to upgrade my systems to python 2.5, but from my tests, that version did not have that memory leak. Nobody seems interesting in backporting fixes from 2.5 to 2.4, so you're probably on your own in that case as well, if upgrading to python 2.5 isn't an option or isn't applicable to your situation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Mar 15 04:33:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Mar 2008 06:33:30 -0200 Subject: Socket Performance References: <601ecc66-66a2-44ff-98ca-a5f62b1a5f98@d62g2000hsf.googlegroups.com> Message-ID: En Thu, 13 Mar 2008 15:18:44 -0200, escribi?: > Well, lets say you have a situation where you're going to be > alternating between sending large and small chunks of data. Is the > solution to create a NetworkBuffer class and only call send when the > buffer is full, always recv(8192)? No need to reinvent the wheel. socket objects already have a makefile method returning a file-like object, which behaves like a buffered socket. -- Gabriel Genellina From MartinRinehart at gmail.com Wed Mar 5 12:34:46 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 5 Mar 2008 09:34:46 -0800 (PST) Subject: Better grammar.txt References: Message-ID: <819394f3-ac01-4606-b77b-99609d3b35af@s8g2000prg.googlegroups.com> MartinRineh... at gmail.com wrote: > It includes three corrections to grammar.txt (imagnumber, xor_expr and > and_expr) that I've reported. Make that four corrections. Add augop. From jeff at schwabcenter.com Thu Mar 20 11:28:39 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 20 Mar 2008 08:28:39 -0700 Subject: Can I run a python program from within emacs? In-Reply-To: <13u50796m76e9c7@corp.supernews.com> References: <13u50796m76e9c7@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-03-20, jmDesktop wrote: > >> Hi, I'm trying to learn Python. I using Aquamac an emac >> implementation with mac os x. I have a program. If I go to the >> command prompt and type pythong myprog.py, it works. Can the program >> be run from within the editor or is that not how development is done? >> I ask because I was using Visual Studio with C# and, if you're >> familiar, you just hit run and it works. On Python do I use the >> editor for editing only and then run the program from the command >> line? > > http://www.google.com/search?q=emacs+python Or achieve a similar (more flexible (IMO), but less smoothly integrated) effect with Vim and GNU Screen. Until recently, you had to patch Screen if you wanted vertical splits, but now it's in the main line. From guidovb1 at invalid Sun Mar 16 12:25:26 2008 From: guidovb1 at invalid (Guido van Brakel) Date: Sun, 16 Mar 2008 17:25:26 +0100 Subject: Basics of Python,learning Message-ID: <47dd48ca$0$14361$e4fe514c@news.xs4all.nl> Hello Why is this not working,and how can I correct it? > #!/usr/bin/env python > #coding=utf-8 > > z = raw_input ('Give numbers') > y = z.split() > b=[] > > for i in y: > b.append(float(i)) > > def b(min,max,gem) > x=min(a) > x=gem(a) > x=max(a) > return a > > print min(a) > print max(a) > print gem(a) Regards, -- Guido van Brakel Life is like a box of chocolates, you never know what you're gonna get -- From Minor.Gordon at cl.cam.ac.uk Tue Mar 25 16:31:39 2008 From: Minor.Gordon at cl.cam.ac.uk (Minor Gordon) Date: Tue, 25 Mar 2008 20:31:39 +0000 Subject: Beta testers needed for a high performance Python application server Message-ID: <47E9612B.5010401@cl.cam.ac.uk> Hello all, I'm looking for beta testers for a high performance, event-driven Python application server I've developed. About the server: the front end and other speed-critical parts of the server are written in portable, multithreaded C++. The back end is an embedded CPython interpreter. The server is much faster than anything in pure Python, and it can compete with C servers (including e.g. lighttpd for file workloads) or outdo them (e.g. anything behind Apache) until CPython consumes a single processor. On the Python side it supports WSGI (the server can handle the static and dynamic requests of MoinMoin with a handful of lines), the DB API with blocking calls offloaded to a connection in a separate thread (MySQL, SQLite supported), Google's ctemplate, gzipping responses, file caching, reading and writing to URIs as a client, AJAX integration, debugging as a Python extension, and a lot of other features. The core Python API is event-driven, using continuations like Twisted but much cleaner (continuations are any callables, there are no special objects anywhere). The Python back end also supports Stackless Python so all of the continuation machinery can be hidden behind tasklet switching. Background: I'm in this to help write a "story" for Python and web applications. Everyone likes to go on about Ruby on Rails, and as far as I can tell there's nothing that approaches Rails in Python. I want to code quickly in Python like I can with Rails, but without sacrificing single node performance on many cores. Beta testers: should be intermediate to advanced Python programmers with demanding applications, particularly web applications with databases and AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory libraries beyond python-dev. Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. Minor From sjmachin at lexicon.net Sat Mar 22 17:47:46 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Mar 2008 14:47:46 -0700 (PDT) Subject: re.search (works)|(doesn't work) depending on for loop order References: <5a540d97-77aa-4cfc-83b5-caa048f49e1e@s8g2000prg.googlegroups.com> <64lbj3F2an71mU3@mid.uni-berlin.de> Message-ID: <7982df0e-4c03-40d8-8e89-4fa6c7b01d4b@s37g2000prg.googlegroups.com> On Mar 23, 8:21 am, Marc 'BlackJack' Rintsch wrote: > On Sat, 22 Mar 2008 13:27:49 -0700, sgharvey wrote: > > ... and by works, I mean works like I expect it to. > > > I'm writing my own cheesy config.ini parser because ConfigParser > > doesn't preserve case or order of sections, or order of options w/in > > sections. > > > What's confusing me is this: > > If I try matching every line to one pattern at a time, all the > > patterns that are supposed to match, actually match. > > If I try to match every pattern to one line at a time, only one > > pattern will match. > > > What am I not understanding about re.search? > > That has nothing to do with `re.search` but how files work. A file has a > "current position marker" that is advanced at each iteration to the next > line in the file. When it is at the end, it stays there, so you can just > iterate *once* over an open file unless you rewind it with the `seek()` > method. > > That only works on "seekable" files and it's not a good idea anyway > because usually the files and the overhead of reading is greater than the > time to iterate over in memory data like the patterns. > Unless the OP has changed the pastebin code since you read it, that's absolutely nothing to do with his problem -- his pastebin code slurps in the whole .ini file using file.readlines; it is not iterating over an open file. From xkenneth at gmail.com Sun Mar 9 17:44:24 2008 From: xkenneth at gmail.com (xkenneth) Date: Sun, 9 Mar 2008 14:44:24 -0700 (PDT) Subject: Logically/Selectively Sub Class? References: <63j3ltF282fssU1@mid.uni-berlin.de> Message-ID: On Mar 9, 4:38?pm, "Diez B. Roggisch" wrote: > xkenneth schrieb: > > > Might be a silly question, but is it possible to selectively subclass, > > IE subclass is a supporting module is present and not otherwise. > > Yes, something like this should work > > class Foo(some, base, classes) > ? ? pass > > if condition: > ? ? Temp = Foo > ? ? class Foo(Temp, otherclass): pass > > Alternatively, you can use the type-function to create classes explicit > with a list of base-classes. > > However it smells after bad design... what's your actual usecase? > > Diez Yeah, it's really a non-issue, just more a curiosity. I'm using ZODB for a lot of my stuff now, and I need my objects to be persistent, however there might be a case where my classes could be used in a non- persistent manner. I'll just have ZODB as a requirement for my package. Regards, Kenneth Miller From afandimscit at gmail.com Mon Mar 31 10:22:40 2008 From: afandimscit at gmail.com (afandi) Date: Mon, 31 Mar 2008 07:22:40 -0700 (PDT) Subject: How to insert multiple rows in SQLite Dbase References: <50faeed7-775f-4e12-8131-21a95b5f91a8@e6g2000prf.googlegroups.com> <657h3nF2eehi8U1@mid.uni-berlin.de> Message-ID: On Mar 30, 4:46 am, Gerhard H?ring wrote: > Gabriel Genellina wrote: > > [...] > > and execute: > > cur.executemany("insert into log (IP, EntryDate, Requestt, ErrorCode) > > values (:ip, :date, :request, :errorcode)", values) > > It's probably worth mentioning that pysqlite's executemany() accepts > anything iterable for its parameter. So you don't need to build a list > beforehand to enjoy the performance boost of executemany(). > > The deluxe version with generators could look like this: > > def parse_logfile(): > logf = open(...) > for line in logf: > if ...: > row = (value1, value2, value3) > yield row > logf.close() > > ... > > cur.executemany("insert into ... values (c1, c2, c3)", parse_logfile()) > > -- Gerhard > > PS: pysqlite internally has a statement cache since verson 2.2, so > multiple execute() calls are almost as fast as executemany(). Thanks regards to your suggestion, but I don't understand why we have to put the IF statement? From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:14:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:14:00 -0700 (PDT) Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> <63hq8rF27chv6U1@mid.uni-berlin.de> <96486094-0706-45f1-b5c1-4af6333e3955@s13g2000prd.googlegroups.com> Message-ID: <25c0b8eb-683a-4703-ba76-906dbb762570@8g2000hse.googlegroups.com> On 9 mar, 15:37, I V wrote: > On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote: > > Well, that suits me. The most unnatural thing about Python was adapting > > to the idea of just letting unreleased resources go jogging off > > wherever. :) > > Yes, that's a bad habit that garbage collection can encourage. GC is good > for managing memory, but not good for managing other resources, so if an > object holds some other resource, it's important to make sure the > resource is released in a timely fashion rather than relying on the > finalizer (the __del__ function). > > Although, you still don't need f.close, with the new with statement: > > with open('myfile') as f: > ? ? ? ? string = f.readline() > # f.close() gets called automatically here, without waiting for ? ? ? ? > # garbage collection. Just for completeness, on earlier Python versions, the way to ensure that resources are always released is using try/finally: f = open(...) try: ...work with file... finally: f.close() -- Gabriel Genellina From deets at nospam.web.de Wed Mar 26 16:23:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Mar 2008 21:23:40 +0100 Subject: A question on decorators In-Reply-To: References: Message-ID: <64vpmnF2dvlccU1@mid.uni-berlin.de> Tim Henderson schrieb: > Hello > > I am writing an application that has a mysql back end and I have this > idea to simplify my life when accessing the database. The idea is to > wrap the all the functions dealing with a particular row in a > particular in a particular table inside a class. So if you have a > table that looks like this: > > id str1 str2 pickled_data1 pickled_data2 > 0 woeif aposf (bin) (bin) > 1 ofime powe (bin) (bin) > ... > n oiew opiwe (bin) (bin) > > you can access this table like this > > t = Table(id) #to load a pre-entered row > t2 = Table(id, str1, str2, data1, data2) #to create a new row > > when you change a an attribute of the class like this... > t.str1 = 'new value' > > it automatically updates the database backend. > > I have what I just described working. However I want an easier way to > deal with my pickled_data. Right now I am pickling dictionaries and > list types. Now there is one problem with this, let me demonstrate > > t.data.update({'new key':'new value'}) > print t.data > {... 'new key':'new value' ...} > > which makes it appear that the database has been updated as well, but > in fact it hasn't to update the database with this scheme you actually > have to do this. > > t.data.update({'new key':'new value'}) > t.data = t.data > > this is not ideal so I subclassed the built in dict type like this: > > class _my_dict(dict): > > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > self.update_db() > > def __delitem__(self, key): > if self.write_access: > dict.__delitem__(self, key) > self.update_db() > > def __setitem__(self, key, value): > if self.write_access: > dict.__setitem__(self, key, value) > self.update_db() > > > def clear(self): > if self.write_access: > dict.clear(self) > self.update_db() > > ... > more methods which are simliar > ... > > def update_db(self): > if self.write_access: > con = get_dbConnection() > cur = con.cursor() > > table = self.experiment.TABLE > row_index_name = self.row_index_name > row_index = self.row_index > column_name = self.column_name > column_value = MySQLdb.escape_string(pickle.dumps(self)) > > q1 = '''UPDATE %(table)s > SET %(column_name)s = '%(column_value)s' > WHERE %(row_index_name)s = '%(row_index)s' ''' % locals() > > cur.execute(q1) > con.close() > > > Now while this works, it is a lot of work. What I want to be able to > do is something where I write one decorator function that > automatically updates the database for me. So let us pretend I have > this function. > > let: dec_update_db() be my decorator which updates the dictionary. > > to use this function it seems I would probably still have to subclass > dict like this: > > class _my_dict2(dict): > > @dec_update_db > def __init__(self, row_index_name, row_index, column_name, a=None, > **kwargs): > self.row_index_name = row_index_name > self.row_index = row_index > self.column_name = column_name > self.write_access = True > if (a == None): dict.__init__(self, kwargs) > else: dict.__init__(self, a) > > @dec_update_db > def __delitem__(self, key): > dict.__delitem__(self, key) > > @dec_update_db > def __setitem__(self, key, value): > dict.__setitem__(self, key, value) > > @dec_update_db > def clear(self): > dict.clear(self) > > ... and so on ... > > this is also not ideal. because I still have to apply the decorator to > every function which changes the dictionary. > > What I really want is a way to have the decorator applied > automatically every time a method in dict or a sub class is called. I > feel like this must be possible. Has any one here done anything like > this before? There are a few possibilities - one of them is using a metaclass to apply the decorator to alle methods. Diez From castironpi at gmail.com Mon Mar 17 08:21:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 17 Mar 2008 05:21:54 -0700 (PDT) Subject: String To List References: <3dc3f6a7-f5f8-4f0a-9c29-a3790e5a1550@e10g2000prf.googlegroups.com> <42858a90-80eb-45ac-8f76-ad9d06ee4fbf@d21g2000prf.googlegroups.com> <4ea462e2-cecc-40fc-a62b-658c0fcc28a6@c19g2000prf.googlegroups.com> Message-ID: <22707a9a-0918-4750-8197-e445f1be75d3@u72g2000hsf.googlegroups.com> > > > > I have a string a = "['xyz', 'abc']".. I would like to convert it to a > > > > list with elements 'xyz' and 'abc'. Is there any simple solution for > > > > this?? > > > > Thanks for the help... > > > > eval(a) will do the job, but you have to be very careful about using > > > that function. ?An alternative is > > > > [s.strip('\'"') for s in a.strip('[]').split(', ')] > > > This will fall over if xyz or abc include any of the characters your > > stripping/splitting on (e.g if xyz is actually "To be or not to be, > > that is the question"). ?Unless you can guarantee they won't, you'll > > need to write (or rather use) a parser that understands the syntax. > > > Iain > > Thinking about this some more; could the string module not use a > simple tokenizer method? ?I know that relentlessly adding features to > built-ins is a bad idea, so I'm not sure if this falls within > batteries-included, or is actually just adding bulk. ?On the one hand, > it's not difficult to write a simple state-based token parser > yourself, but on the other it is also quite easy to include a pile of > bugs when you do. ?By simple I mean something like: > > def tokenize(string, delim, closing_delim=None, escape_char=None) > > which would return a list (or a generator) of all the parts of the > string enclosed by delim (or which begin with delim and end with > closing_delim if closing_delim is set), ignoring any delimiters which > have been escaped by escape_char. ? Throw an exception if the string > is malformed? (odd number of delimiters, or opening/closing delims > don't match) > > In the OP's case, he could get what he want's with a simple: ? l = > a.tokenize("'") Slippery slope, though, to nested delimiters, and XML after that. Where does shlex get us? Do we want to parse "['xyz', 'abc', ['def','ghi']]" any special way? Are there security concerns past a really low complexity level, such as recursion overflows? From Plemelle at comcast.net Sat Mar 29 18:54:32 2008 From: Plemelle at comcast.net (Paul Lemelle) Date: Sat, 29 Mar 2008 16:54:32 -0600 Subject: pexpect Message-ID: I am trying separate a script that users pexpect into various functions within the same expect session. The problem is that the function does not return control back Main. Any insight into this issue would be greatly appreciated. Below is sample code of the problem. Thanks, Paul ____ import pexpect def sshcon(user, password): go = pexpect.spawn ('/usr/bin/ssh -l root %s '% (user)) go.expect ('Password: ') go.sendline (password) go.interact() #get node info for both clusters. C1_node = raw_input("Enter the ip address for node on cluster 1: ") C1_pass = raw_input("Enter the password for the node on cluster 1: ") sshcon(C1_node, C1_pass) #The function will not run anything pass this point. If I place the #below code into the above funciton than everything works fine. chk = pexpect.spawn('ls') # veriy that you are connected #go to the path chk.expect('# ') chk.sendline('ls') chk.interact( #END From israelu at elbit.co.il Sun Mar 30 11:16:39 2008 From: israelu at elbit.co.il (iu2) Date: Sun, 30 Mar 2008 08:16:39 -0700 (PDT) Subject: License of Python References: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> Message-ID: <5feb7205-e852-401c-aac2-61ff3d1601ca@i12g2000prf.googlegroups.com> On 30 ???, 15:55, Lie wrote: > On Mar 30, 6:42 pm, iu2 wrote: > > > Hi guys, > > > I'd like to use Python in a commercial application. In fact I would > > like to write the application entirely in Python. > > But I think I wouldn't like telling what language the application is > > written in. > > Why is the reason for that? > Due to Competitors... I don't want to expost the language I use > You can just include it since most users never mess through their > program files and most users doesn't even know what Python is, while > advanced users could guess that you use Python by seeing the file > extension being used (py, pyc, pyo). I intend to use pyinstaller, so there is no .pyc at all. The main problem is when I use small programs (as single EXE) sent to someone as a means of maintenance or debugging. Sending Python's license file together with one EXE seems to me too obvious Another thing, what should the Python's license file be called? From tjreedy at udel.edu Thu Mar 13 02:55:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Mar 2008 02:55:59 -0400 Subject: no more comparisons References: <92ae17f4-a08a-48a0-931f-6c618a91651d@59g2000hsb.googlegroups.com><7xy78neffb.fsf@ruckus.brouhaha.com> <7x3aqvf9o2.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7x3aqvf9o2.fsf at ruckus.brouhaha.com... | "Terry Reedy" writes: | > | I don't see what's so inefficient about it necessarily. | > | > The key function is called once per list item, for n calls total. The | > comparision function is called once per comparision. There are at least | > n-1 such calls and typically something on the order of n * lg2(n) calls. | | Right. Depending on the application, calling the comparison function | lg(n) times may be faster than calling the key function once. | | Example: you want to sort a list of strings case-independently, each | string containing a few pages worth of text. There are 10000 strings, | each maybe 10000 chars long. If the strings are pulled in from a file, or stored off to a file, as I would expect in and real app of this sort, the in-memory data to be sorted could/should be tuples of the lowercased strings and files positions. Then no key param is needed. | Then (untested): | | x.sort(xs, key=lower) | | makes a copy of each of the 10000 strings, makes 10000 tuples, sorts, | then releases the temporary strings and tuples. At least 100 | megabytes of memory allocated and 100 million chars copied, even | though any give pair of strings will usually differ somewhere in the | first few characters and there's no need to look past those. | | from string import lower | from operator import eq | from itertools import * | | def xcmp(a,b): | for x,y in izip(a,b)): | c = cmp(x.lower() y.lower()) | if c: return c | return 0 | | x.sort(xcmp) | | runs the comparison function about 14000 times, 14 * 10000 = 140000, not 14000. For each of these, you have a call to izip and multiple calls to .next, cmp, and .lower. That said, this use case of where the potentially needed key is long whereas the actually needed key is much shorter is a better use case than anything I have seen so far. Still, as I figure it, the initial part of each text is lowercased around 28 times, on average. So there can only be a speed saving if the text is more than 28 times the effective actual key. To actually do such a thing, at least more than once, I would be tempted to have the key function take just the first k chars, for k perhaps 50. If the texts average, say, 1500 chars, then the key array would be 1/30 * perhaps 2 (for object overhead) = 1/15 of the original array space. Then run over the 'sorted' array to see if there are any cases where the first 50 chars match and if so, check more to see if a swap needs to be made. Easiest would be to do a simple bubble or insert sort with the full compare. tjr From ptmcg at austin.rr.com Mon Mar 24 09:33:11 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 24 Mar 2008 06:33:11 -0700 (PDT) Subject: parsing json output References: <81dad963-86cf-45f5-beda-00a0abdad16e@b64g2000hsa.googlegroups.com> Message-ID: <64b3e29d-ce9d-42f9-a285-5001a31d9448@d62g2000hsf.googlegroups.com> On Mar 18, 9:10?pm, Gowri wrote: > Hi, > > I have a service running somewhere which gives me JSON data. What I do > is this: > > import urllib,urllib2 > import cjson > > url = 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/ > tbedi/requestDetails' > params = {'format':'json'} > eparams = urllib.urlencode(params) > request = urllib2.Request(url,eparams) > response = urllib2.urlopen(request) ? ?# This request is sent in HTTP > POST > print response.read() > > This prints a whole bunch of nonsense as expected. I use cjson and am > unable to figure out how to print this json response and I guess if I > can do this, parsing should be straightforward? Gowri - On a lark, I tried using the JSON parser that ships with the examples in pyparsing (also available online at http://pyparsing.wikispaces.com/space/showimage/jsonParser.py). The parsed data returned by pyparsing gives you a results object that supports an attribute-style access to the individual fields of the JSON object. (Note: this parser only reads, it does not write out JSON.) Here is the code to use the pyparsing JSON parser (after downloading pyparsing and the jsonParser.py example), tacked on to your previously- posted code to retrieve the JSON data in variable 's': from jsonParser import jsonObject data = jsonObject.parseString(s) # dump out listing of object and attributes print data.dump() print # printe out specific attributes print data.phedex.call_time print data.phedex.instance print data.phedex.request_call # access an array of request objects print len(data.phedex.request) for req in data.phedex.request: #~ print req.dump() print "-", req.id, req.last_update This prints out (long lines clipped with '...'): [['phedex', [['request', [[['last_update', '1188037561'], ... - phedex: [['request', [[['last_update', '1188037561'], ['numofapproved', '1'],... - call_time: 0.10059 - instance: tbedi - request: [[['last_update', '1188037561'], ['numofapproved', '1'], ... - request_call: requestDetails - request_date: 2008-03-24 12:56:32 UTC - request_timestamp: 1206363392.09 - request_url: http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails?format=json 0.10059 tbedi requestDetails 1884 - 7425 1188037561 - 8041 1188751826 - 9281 1190116795 - 9521 1190248781 - 12821 1192615612 - 13121 1192729887 ... The dump() method is a quick way to see what keys are defined in the output object, and from the code you can see how to nest the attributes following the nesting in the dump() output. Pyparsing is pure Python, so it is quite portable, and works with Python 2.3.1 and up (I ran this example with 2.5.1). You can find out more at http://pyparsing.wikispaces.com. -- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Mar 20 07:33:45 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 20 Mar 2008 12:33:45 +0100 Subject: Prototype OO In-Reply-To: References: Message-ID: <47e24b99$0$24941$426a74cc@news.free.fr> sam a ?crit : > > Some time ago (2004) there were talks about prototype-based languages > and Prothon emerged. > > Can someone tell me why class-based OO is better that Prototype based, For which definition of "better" ?-) > especially in scripting langage with dynamic types as Python is? > > > Here are some links: > > http://c2.com/cgi/wiki?PrototypeBasedProgramming Most of the arguments in favor of prototypes seems to come to, mainly: 1/ it lets you customize behaviour on a per-object base 2/ it removes the mental overhead of inheritance, classes etc Point 1. is a non-problem in Python, since you can already add/replace methods on a per-objec basis (ok, with a couple restrictions wrt/ __magic__ methods and such). Point 2. is not (IMHO) such a problem in Python, where inheritance is mainly an implementation detail (it's not needed for polymorphic dispatch to work) and class hierarchy tend to be very flat, when they even exist. Mainly, Python's object system is actually quite close to javascript here. That is, you get more or less the same flexibility. And a couple of powerful features you don't have with javascript (like hooks in the attribute lookup mechanism), too. From kw at codebykevin.com Tue Mar 11 15:08:00 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 11 Mar 2008 15:08:00 -0400 Subject: How to make a Tkinter widget always visible? In-Reply-To: References: <3a30d192-812e-42a4-8a03-f3941b6fa78c@s12g2000prg.googlegroups.com> <47D6C81A.1070301@codebykevin.com> Message-ID: <47D6D890.3060104@codebykevin.com> Miki wrote: > Hello Kevin, > >>> Is there a way to make sure that these buttons are always visible? >> There are various ways to do this: you can set the window to be >> non-resizable, or set a minimum size to it, so that it can't be resized >> below that level. However, if you allow arbitrary resizing of the >> window, there's no real way to guarantee that the widgets will be >> visible at all times. > Thanks. > > I've set a minimal size to the window. However when I resize it to be > shorter, the buttons are hidden while the top frame stays visible. > Please post the code you're using--it will be easier to help if we can see exactly what you are trying. --K -- Kevin Walzer Code by Kevin http://www.codebykevin.com From Bryan.Fodness at gmail.com Sat Mar 8 14:49:31 2008 From: Bryan.Fodness at gmail.com (Bryan.Fodness at gmail.com) Date: Sat, 8 Mar 2008 11:49:31 -0800 (PST) Subject: identifying and parsing string in text file Message-ID: <15a6a72b-37bd-4cd6-8f11-4d3520b224e7@b64g2000hsa.googlegroups.com> I have a large file that has many lines like this, SITE I would like to identify the line by the tag (300a,0014) and then grab the name (DoseReferenceStructureType) and value (SITE). I would like to create a file that would have the structure, DoseReferenceStructureType = Site ... ... Also, there is a possibility that there are multiple lines with the same tag, but different values. These all need to be recorded. So far, I have a little bit of code to look at everything that is available, for line in open(str(sys.argv[1])): i_line = line.split() if i_line: if i_line[0] == " <5edbb232-4553-4d0a-9985-ef534504d214@b1g2000hsg.googlegroups.com> Message-ID: <47dc43e0$0$849$ba4acef3@news.orange.fr> Thanks, andrei. I'll try that. Le Sat, 15 Mar 2008 14:25:21 -0700, andrei.avk a ?crit?: > What you want to do is either 1. load everything up into a string, > replace > text, close file, reopen it with 'w' flag, write string to it. OR if > file is too big, you can read each line, replace, write to a temp file, > then when done move the file over the old one. From deets at nospam.web.de Tue Mar 4 07:12:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Mar 2008 13:12:31 +0100 Subject: Eurosymbol in xml document References: Message-ID: <634sleF25sd22U1@mid.uni-berlin.de> Hellmut Weber wrote: > Hi, > i'm new here in this list. > > i'm developing a little program using an xml document. So far it's easy > going, but when parsing an xml document which contains the EURO symbol > ('?') then I get an error: > > UnicodeEncodeError: 'charmap' codec can't encode character u'\xa4' in > position 11834: character maps to > > the relevant piece of code is: > > from xml.dom.minidom import Document, parse, parseString > ... > doc = parse(inFIleName) The contents of the file must be encoded with the proper encoding which is given in the XML-header, or has to be utf-8 if no header is given. >From the above I think you have a latin1-based document. Does the encoding header match? > > leo at brunello usexml $ locale > LANG=de_DE at euro > LC_CTYPE="de_DE at euro" > LC_NUMERIC="de_DE at euro" > LC_TIME="de_DE at euro" > LC_COLLATE="de_DE at euro" > LC_MONETARY="de_DE at euro" > LC_MESSAGES="de_DE at euro" > LC_PAPER="de_DE at euro" > LC_NAME="de_DE at euro" > LC_ADDRESS="de_DE at euro" > LC_TELEPHONE="de_DE at euro" > LC_MEASUREMENT="de_DE at euro" > LC_IDENTIFICATION="de_DE at euro" > LC_ALL=de_DE at euro This is irrelevant. Diez From bbxx789_05ss at yahoo.com Fri Mar 28 11:38:45 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Mar 2008 08:38:45 -0700 (PDT) Subject: problem with CGIHTTPServer Message-ID: 1) I have this simple cgi server: import CGIHTTPServer import BaseHTTPServer class MyRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = ['/my_cgi_scripts'] server = BaseHTTPServer.HTTPServer( ('', 8111), MyRequestHandler ) server.serve_forever() 2) I have this simple python script: test.py -------- #!/usr/bin/env python import cgitb; cgitb.enable() import cgi print "Content-type: text/html" print print "hello" 3) I have this simple html page with a link that calls test.py: My directory structure looks like this: ../dir1 -------myserver.py -------/my_cgi_scripts ----------------test.py After I start the server script, load the html page in my browser, and click on the link, I get the desired output in my browser, but the server script outputs the following in my terminal: localhost - - [28/Mar/2008 08:51:22] "GET /my_cgi_scripts/test.py HTTP/ 1.1" 200 - localhost - - [28/Mar/2008 08:51:22] code 404, message File not found localhost - - [28/Mar/2008 08:51:22] "GET /favicon.ico HTTP/1.1" 404 - What are the error messages on lines two and three? From "benjamin.serrato\" at G(oog1e)MAIL.com Tue Mar 18 19:39:16 2008 From: "benjamin.serrato\" at G(oog1e)MAIL.com (oog1e) Date: Tue, 18 Mar 2008 23:39:16 GMT Subject: First Program Bug (Newbie) In-Reply-To: References: Message-ID: Hey, big thanks to you and Gabriel for replying. I couldn't quite follow what you did yet. What is this 'gimpy' thing and where can I read about it? In response: First: Heh, I'm a little embarrassed I didn't notice this. I thought 'I only need to check up to half' but it didn't occur that base**2 was more than 1/2 candidate. Second: I don't quite follow this. Third: Yeah, I found that bug just before, and because of, posting. Fourth: I used the incrementing command and incremented candidates by two to check only odds and now the program is a lot faster. Thanks a lot for yall's replies. Three more things before I go. What is the square root function in python? I couldn't find the fact.py demo script. I didn't mean return I meant 'continue'. Mensanator wrote: > On Mar 17, 7:03 pm, Benjamin Serrato > wrote: >> I Found It!! The following was a post asking for help finding a bug. I >> thought I needed help with my syntax, but just before sending I found >> the bug on line 13. Line 13 should read: "base = 2". I would still >> appreciate any comments on my program. Maybe there is a better way to do >> it that I didn't think about. I know it's not that interesting but it's >> my first one. >> >> [post] >> I'm almost halfway through an online tutorial I found on the python.org >> site and decided to stop and write a program for myself. I got it in my >> head to write a program to print all the primes; the idea came from >> another tutorial. The program prints some non-prime numbers. In a >> comparison to lists of primes the program prints eight non-primes for >> numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147]. >> Here is the program. >> >> base = 2 >> candidate = 3 >> >> while True: >> while candidate % base != 0: >> base = base + 1 >> if base > (candidate / 2): >> print candidate >> candidate = candidate + 1 >> base = 2 >> else: >> candidate = candidate + 1 >> >> The following is a rundown of the program. >> >> candidate: A possible prime number. >> base: Start point for divisibility testing. >> outer while loop: Causes the program to loop. >> inner while loop: Obviously, checks if 'candidate' mod 'base' equals >> zero. If not base is incremented by one then 'if loop'. >> if loop: After base has been incremented this checks whether all the >> possible divisors have been used up. If they have then 'candidate' must >> be prime. So, candidate is printed, a new candidate is chosen and the >> base is reset. >> else loop: If 'candidate' mod 'base' equals zero, then 'candidate' is >> not prime and a new candidate is chosen. >> >> I realize yall probably didn't need all that. >> >> At first I tried to use 'return' on the 'else' block to cause the >> program to loop, but I don't understand 'return' yet and that didn't >> work. So, I put the rest into another while loop and was really happy to >> find it worked but the program prints some non-prime numbers. >> >> Thanks, Benjamin Serrato >> >> P.S. What is the chance I'll get spam for using my real email address? I >> currently don't get any so... >> [/post] > > Several items. > > First, you don't need to check base larger than sqrt(candidate). > > Second, see comments following dc. > > Third, you need to add base = 2 to end of program, otherwise next > candidate starts base where previous candidate left off. > > Fourth, use +=1 to increment. > > Finally, throw this away and use gmpy. :-) > > > import gmpy # for Quality Assurance > base = 2 > candidate = 3 > p = 0 # prime count > while p<100: # limit the loop to 100 primes > while candidate % base != 0: > base += 1 > #if base > (candidate / 2): > if base > (gmpy.sqrt(candidate)): # only need to test to > sqrt(candidate) > dc = divmod(candidate,2) # remainder==0 gives false > primes > if dc[1]==1: > # > # the gmpy functions are for QA, verifies that what you call a > prime > # really is one and the next_prime makes sure you don't skip > any > # these can be removed once working > # > print > candidate,gmpy.is_prime(candidate)>0,gmpy.next_prime(candidate) > p += 1 > candidate += 1 > base = 2 > else: > candidate += 1 # false prime, reset > base = 2 > else: > candidate += 1 > base = 2 # failure to reset causes false > primes > > ## 3 True 5 > ## 5 True 7 > ## 7 True 11 > ## 11 True 13 > ## 13 True 17 > ## 17 True 19 > ## 19 True 23 > ## 23 True 29 > ## 29 True 31 > ## 31 True 37 > ## 37 True 41 > ## 41 True 43 > ## 43 True 47 > ## 47 True 53 > ## 53 True 59 > ## 59 True 61 > ## 61 True 67 > ## 67 True 71 > ## 71 True 73 > ## 73 True 79 > ## 79 True 83 > ## 83 True 89 > ## 89 True 97 > ## 97 True 101 > ## 101 True 103 > ## 103 True 107 > ## 107 True 109 > ## 109 True 113 > ## 113 True 127 > ## 127 True 131 > ## 131 True 137 > ## 137 True 139 > ## 139 True 149 > ## 149 True 151 > ## 151 True 157 > ## 157 True 163 > ## 163 True 167 > ## 167 True 173 > ## 173 True 179 > ## 179 True 181 > ## 181 True 191 > ## 191 True 193 > ## 193 True 197 > ## 197 True 199 > ## 199 True 211 > ## 211 True 223 > ## 223 True 227 > ## 227 True 229 > ## 229 True 233 > ## 233 True 239 > ## 239 True 241 > ## 241 True 251 > ## 251 True 257 > ## 257 True 263 > ## 263 True 269 > ## 269 True 271 > ## 271 True 277 > ## 277 True 281 > ## 281 True 283 > ## 283 True 293 > ## 293 True 307 > ## 307 True 311 > ## 311 True 313 > ## 313 True 317 > ## 317 True 331 > ## 331 True 337 > ## 337 True 347 > ## 347 True 349 > ## 349 True 353 > ## 353 True 359 > ## 359 True 367 > ## 367 True 373 > ## 373 True 379 > ## 379 True 383 > ## 383 True 389 > ## 389 True 397 > ## 397 True 401 > ## 401 True 409 > ## 409 True 419 > ## 419 True 421 > ## 421 True 431 > ## 431 True 433 > ## 433 True 439 > ## 439 True 443 > ## 443 True 449 > ## 449 True 457 > ## 457 True 461 > ## 461 True 463 > ## 463 True 467 > ## 467 True 479 > ## 479 True 487 > ## 487 True 491 > ## 491 True 499 > ## 499 True 503 > ## 503 True 509 > ## 509 True 521 > ## 521 True 523 > ## 523 True 541 > ## 541 True 547 > ## 547 True 557 From gagsl-py2 at yahoo.com.ar Thu Mar 27 15:05:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 27 Mar 2008 16:05:47 -0300 Subject: And the reverse? Does os also import os.path? References: <7a1e0e8d-31bb-477e-9761-9c8a2839ad96@e23g2000prf.googlegroups.com> <47ebd7b4$0$19836$426a74cc@news.free.fr> Message-ID: En Thu, 27 Mar 2008 14:22:11 -0300, Bruno Desthuilliers escribi?: > Wilbert Berendsen a ?crit : >> If i do >> >>>>> import os >>>>> os.path.abspath("bla") >> '/home/wilbert/bla' >> >> it seems that just import os also makes available al os.path functions. >> >> But is that always true? > > Nope. Not all packages expose their sub-packages. In this case, the idea is to provide an OS-dependent module with a generic name. The os module imports one of several modules (ntpath, posixpath, etc.) depending on the current platform, and makes it available under the generic "path" name so users don't have to worry about that. (Note that os is a module, not a package; os.path is accessing the "path" attribute of the os module, not the path module in the os package) -- Gabriel Genellina From grante at visi.com Sun Mar 2 10:25:49 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 02 Mar 2008 15:25:49 -0000 Subject: Python Telnet formatting? References: <85c3410d-aff0-4e13-90b0-68ddb96a3985@u72g2000hsf.googlegroups.com> Message-ID: <13slhntr9qdr62f@corp.supernews.com> On 2008-03-02, mentaltruckdriver at gmail.com wrote: > I posted here a couple days ago looking for some help creating > a Telnet-based chat server. You guys pointed me to Twisted, > which has solved most of my issues. And we told you that you needed to implement the telnet protocol. > The issue is, when I use clients like PuTTY, it returns a lot > of what appears to be formatting (e.g. if I typed Hello, it > would return "\xff \xfb\x1f\xff\ > xfb\xff\xfb\x18\xff\xfb'\xff\xfd\x01\xff\xfb\x03\xff\xfd\x03Hello".) That "stuff" that you call "formatting" are commands for the telnet protocol. Apparently you've ignored what I told you about implementing the telnet protocol (or using something that does). > How would I go about filtering this stuff out of the strings? Once again: If you're trying to write a telnet server, you need to implement the telnet protocol. > The thing is too, if I use other Telnet programs like > Microsoft Telnet, they don't have this formatting, Different telnet clients act a little differently. Some won't try to negotiate with the tenlet server until the server starts the negotiation. > so I want to be able to recognize if it does have this > formatting and act based on if it does or if it doesn't. You have to handle the telnet protocol if you want to talk to telnet clients. -- Grant Edwards grante Yow! Yow! Those people at look exactly like Donnie visi.com and Marie Osmond!! From __peter__ at web.de Wed Mar 26 04:41:24 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Mar 2008 09:41:24 +0100 Subject: Strange loop behavior References: Message-ID: Gabriel Rossetti wrote: > I wrote a program that reads data from a file and puts it in a string, > the problem is that it loops infinitely and that's not wanted, here is > the code : > > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > while d != "": > file_str.write(d) > d = repr(f.read(DEFAULT_BUFFER_SIZE)) > And yes I checked, the "d" variable is en empty string at some point, so > the looping should stop. d may be an empty string, but repr(d) isn't: >>> d = "" >>> print repr(d) '' >>> print d Remove the two repr() calls and you should be OK. Peter From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:31:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:31:15 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: Message-ID: <13t6ivj3ctet0ac@corp.supernews.com> On Sun, 09 Mar 2008 10:11:53 +1100, Alasdair wrote: > I need to apply the ceiling function to arbitrary sized (long) integers. > However, division automatically returns the type of its operands, so > that, for example: math.ceil(7/4) returns 1. I can use float, as in: > math.ceil(7/float(4)), except that for very large integers float causes > an unacceptable loss of precision. > > What is the best way of finding a ceiling of a quotient of arbitrary > sized integers? def quot_ceil(a, b): """Returns the integer ceiling of the quotient of longints.""" q, r = divmod(a, b) if r: return q+1 else: return q -- Steven From ds-python-list at sidorof.com Sat Mar 29 14:24:34 2008 From: ds-python-list at sidorof.com (DS) Date: Sat, 29 Mar 2008 11:24:34 -0700 Subject: Licensing Message-ID: <47EE8962.8070708@sidorof.com> I'm pretty sure this is the wrong place to ask, but I'm hoping someone will point me in the right direction. I'm getting ready to publish a first open-source project written in python. I am planning to use GPLas the license. However, in my code, there is a function that I like from Python Cookbook. I would like to use it, although I could certainly write a less elegant version that would do the same thing. So, my options appear to be: 1. Don't use it. 2. Use it with no comment -- that doesn't seem right. 3. Use it with remarks in the code that acknowledge the source. 4. Provide a separate licensing page for that function along with the GPL for my code. What is the appropriate course of action here? I'm thinking #3 is probably ok. How do others deal with this in an honorable way? In the book, it appears that they are saying they don't really care unless there is some massive use. Thanks From shrek3333 at wp.pl Fri Mar 21 09:32:18 2008 From: shrek3333 at wp.pl (shrek33333) Date: Fri, 21 Mar 2008 06:32:18 -0700 (PDT) Subject: Funny video :) Message-ID: <96de7676-1baa-43f2-bf07-560a88c61fe8@s13g2000prd.googlegroups.com> http://rozrywka.yeba.pl/show.php?id=1029 :) Funny Sports Bloopers :) From andrew.kuchling at gmail.com Tue Mar 18 11:09:22 2008 From: andrew.kuchling at gmail.com (amk) Date: Tue, 18 Mar 2008 08:09:22 -0700 (PDT) Subject: PyCon video editing References: Message-ID: <0ed1ce28-b517-4c17-b12e-7d6554f5274a@x41g2000hsb.googlegroups.com> On Mar 17, 10:00 pm, dundeemt wrote: > Anyone know who is in charge of this? I'd like to help out if I > could. I am, but haven't set anything up yet, such as a mailing list or a host for the video. I'll update the wiki page http://wiki.python.org/moin/PyConRecordingBof with news/further developments (you can create a wiki account and follow the envelope icon at the upper right to be notified of changes via e-mail). --amk From petr.jakes.tpc at gmail.com Fri Mar 7 16:05:41 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Fri, 7 Mar 2008 13:05:41 -0800 (PST) Subject: looking for a light weighted library/tool to write simple GUI above the text based application References: <4085dba8-44eb-4779-81f1-ae3b4a4c4620@u10g2000prn.googlegroups.com> Message-ID: Finaly, after few experiments, I am using pygame. It comunicates directly with the framebuffer and the performance is excellent. Thanks for your help. Petr Jakes From nanjundi at gmail.com Tue Mar 4 13:32:43 2008 From: nanjundi at gmail.com (Nanjundi) Date: Tue, 4 Mar 2008 10:32:43 -0800 (PST) Subject: sympy: what's wrong with this picture? References: Message-ID: On Mar 3, 3:40 pm, Mensanator wrote: > Notice anything funny about the "random" choices? > > import sympy > import time > import random > > f = [i for i in sympy.primerange(1000,10000)] > > for i in xrange(10): > f1 = random.choice(f) > print f1, > f2 = random.choice(f) > print f2, > C = f1*f2 > ff = None > ff = sympy.factorint(C) > print ff > > ## 7307 7243 [(7243, 1), (7307, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > ## 8563 2677 [(2677, 1), (8563, 1)] > ## 4091 6829 [(4091, 1), (6829, 1)] > > As in, "they're NOT random". > > The random number generator is broken by the sympy.factorint() > function. > > Random.choice() works ok if the factorint() function commented out. > > ## 6089 1811 None > ## 6449 1759 None > ## 9923 4639 None > ## 4013 4889 None > ## 4349 2029 None > ## 6703 8677 None > ## 1879 1867 None > ## 5153 5279 None > ## 2011 4937 None > ## 7253 5507 None > > This makes sympy worse than worthless, as it fucks up other modules. Does seeding ( random.seed ) random with time fix this? It should. -N From martin at v.loewis.de Mon Mar 10 02:57:20 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 10 Mar 2008 07:57:20 +0100 Subject: python-2.5.2 src rpm In-Reply-To: References: Message-ID: <47d4dbd0$0$12151$9b622d9e@news.freenet.de> > I am trying to install python 2.5.2 onto enterprise linux, and would > like to start with a source rpm package so that I can build the > package locally and make sure I have all necessary dependencies. > > I have been unable to locate a source rpm package for python 2.5.2 or > any version of 2.5 for that matter. > > Any pointers would be appreciated. I have not released any source RPM for Python 2.5.2. You can build your own, from Misc/RPM. Regards, Martin From michael.wieher at gmail.com Wed Mar 12 10:24:11 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Wed, 12 Mar 2008 09:24:11 -0500 Subject: List Combinations In-Reply-To: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> References: <7432112c-5195-4312-9a90-7c2c852db4cb@s12g2000prg.googlegroups.com> Message-ID: 2008/3/12, Gerdus van Zyl : > > I have a list that looks like this: > [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] > > how can I get all the combinations thereof that looks like as follows: > 3,9,5,4,2 > 3,1,5,4,2 > 3,9,5,4,5 > 3,1,5,4,5 > etc. > > Thank You, > Gerdus > > -- list = [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']] newList = [] for l in list: newList.extend(l) #newList = [3,9,1,5,4,2,5,8] list=[] for l in newList: if l not in list: list.append(l) #now list is [3,9,1,5,4,2,8] list.sort() #now your list is in sorted order Then, you can just write a series of for loops to spin off your data however you like. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 18:47:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 22:47:15 -0000 Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: <13u5qbjq707as9e@corp.supernews.com> On Thu, 20 Mar 2008 13:42:22 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> On Wed, 19 Mar 2008 12:34:34 +0000, Duncan Booth wrote: >>> By default Python on Windows allows you to open a file for reading >>> unless you specify a sharing mode which prevents it: >> >> But the OP is talking about another process having opened the file for >> WRITING, not reading. It's that other process that has exclusive >> access, and the OP was trying to determine when it was safe to attempt >> opening the file according to whether or not it was still growing. >> > No, unless the other process has specified that it wants exclusive > access there is nothing stopping his process also opening the file. > That's why he has to specify when he opens it that he wants exclusive > access: then it doesn't matter what the other process does, he won't be > able to open it until the other process has closed the file. I think you're confused. Or possibly I'm confused. Or both. It seems to me that you're assuming that the OP has opened the file for reading first, and *then* another process comes along and wants to open it for writing. That's not how I read his post: he's trying to open a file for reading while it is already being written to by another process. Asking for exclusive access when reading isn't going to make any difference, because the other process has already opened the file for writing. I suppose it is conceivable that the other process might have opened the file for non-exclusive writing, assuming that such a thing is even possible, but how likely is that? > This all of course assumes that the other process writes the file in one > single atomic chunk. If it were to create it and then separately open > and write to it then all bets are off. The OP is repeatedly polling the file to see when the size stops increasing. Obviously a single atomic write is *not* taking place. -- Steven From paddy3118 at googlemail.com Thu Mar 13 15:25:26 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 13 Mar 2008 12:25:26 -0700 (PDT) Subject: Is there Python equivalent to Perl BEGIN{} block? References: <13tgrqb132if842@corp.supernews.com> <82768f95-3ed4-4064-852a-adf003a3f704@s8g2000prg.googlegroups.com> Message-ID: <2b1c4584-cac8-4582-bbdd-1bad3e02aa51@e6g2000prf.googlegroups.com> On Mar 13, 7:03 pm, Jonathan Gardner wrote: > On Mar 12, 6:37 pm, Carl Banks wrote: <> > > And leave out the magical -p and -n. If you want to iterate through a > file, "for line in sys.stdin:". Or better still: import fileinput for line in fileinput.input(): process(line) - Paddy. From Afro.Systems at gmail.com Fri Mar 28 05:05:49 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Fri, 28 Mar 2008 02:05:49 -0700 (PDT) Subject: chronic error with python on mac os/x 10.5 Message-ID: Although I am experiencing this problem using a specific domain library (pjsip). Googling this issue show that it is happening to many libraries in python on mac. I was wondering whether anyone solved this or alike in the past and might share what steps were taken. Note: this python lib works fine on other platforms (posix, win, and earlier versions of mac os x) >>> import py_pjsua Traceback (most recent call last): File "", line 1, in ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/site-packages/py_pjsua.so, 2): Symbol not found: ___CFConstantStringClassReference Referenced from: /Library/Frameworks/Python.framework/Versions/2.5/ lib/python2.5/site-packages/py_pjsua.so Expected in: dynamic lookup From bjourne at gmail.com Thu Mar 13 11:06:48 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 13 Mar 2008 16:06:48 +0100 Subject: List mutation method gotcha - How well known? In-Reply-To: <000901c884dd$057d5d80$03000080@hendrik> References: <000901c884dd$057d5d80$03000080@hendrik> Message-ID: <740c3aec0803130806w2eed0c5eq2c0f0096557fce8@mail.gmail.com> On Thu, Mar 13, 2008 at 8:36 AM, Hendrik van Rooyen wrote: > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above 5 -- mvh Bj?rn From nkavitha551 at gmail.com Fri Mar 7 06:19:17 2008 From: nkavitha551 at gmail.com (nkavitha551 at gmail.com) Date: Fri, 7 Mar 2008 03:19:17 -0800 (PST) Subject: Your Fortune for the Day!!! Message-ID: <0bf81834-f0ed-4377-a3ea-d741778e8fb2@u10g2000prn.googlegroups.com> Your Fortune for the Day!!! Hi, To know what it is? Visit the website below and be cool !!! ------------------------------------------------------------------------------ http://myprofilekavitha.blogspot.com/ From skunkwerk at gmail.com Thu Mar 27 01:33:50 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Wed, 26 Mar 2008 22:33:50 -0700 (PDT) Subject: subprocess.popen function with quotes References: <7f550baf-0622-42a1-bc01-157cf955bca3@i12g2000prf.googlegroups.com> <00e26c78-0d4d-47c2-bf60-601d690b5be3@e23g2000prf.googlegroups.com> <73b93526-fc81-4df7-824f-2e30b3a25456@h11g2000prf.googlegroups.com> <13ukphrj8hng018@corp.supernews.com> Message-ID: On Mar 26, 8:05?am, Jeffrey Froman wrote: > skunkwerk wrote: > > p = subprocess.Popen(['rename','-vn','s/(.*)\.htm$/ > > model.html/','*.htm'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > print p.communicate()[0] > > > i change to print p.communicate()[1] in case the output is blank the > > first time > > > this is the output: > > *.htm renamed as model.html > > Without shell=True, your glob characters will not be expanded. Hence, the > command looks for a file actually named "*.htm" > > > when I add shell=True to the subprocess command, I get the following > > output: > > Usage: rename [-v] [-n] [-f] perlexpr [filenames] > > Here the use of the shell may be confounding the arguments passed. Your > command will probably work better if you avoid using shell=True. However, > you will need to perform your own globbing: > > # Untested (no perl-rename here): > > command = ['rename','-vn', 's/(.*)\.htm$/model.html/'] > files = glob.glob('*.htm') > command.extend(files) > p = subprocess.Popen( > ? ? command, > ? ? stdout=subprocess.PIPE, > ? ? stderr=subprocess.PIPE, > ? ? ) > > Jeffrey thanks Jeffrey, that worked like a charm! From mm007.emko at gmail.com Sat Mar 29 07:13:10 2008 From: mm007.emko at gmail.com (eMko) Date: Sat, 29 Mar 2008 04:13:10 -0700 (PDT) Subject: deleting a line from a file Message-ID: Hello, In Perl, using a Tie::File module I can easily and comfortably delete a line from the middle of a text file: my @file; open(DATA, "+<:encoding(utf8):raw" , "file.txt") or return 0; tie @file, 'Tie::File', \*DATA or return 0; splice(@file, $_[0], 1); untie @file; close DATA; (when the first argument of the function ($_[0]) is a number of the line which should be deleted) Is there some easy way how to delete a line from a middle of a file in Python? Thanks a lot eMko From steve at REMOVE-THIS-cybersource.com.au Fri Mar 7 17:07:26 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 07 Mar 2008 22:07:26 -0000 Subject: Timed execution in eval References: <7daafdf3-f861-40d5-8bdd-712deba7d9d7@b1g2000hsg.googlegroups.com> Message-ID: <13t3f4u6vb77qf3@corp.supernews.com> On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote: > I have various bits of code I want to interpret and run at runtime in > eval ... I hope that code doesn't contain any data coming from an untrusted user. > I want to be able to detect if they fail with error, That's what try...except blocks are for. try: x = eval('1 + 1 = 2') except SyntaxError: x = 3 > I want to be able to time them, That's what the timeit module is for. If you do time them, you will find that eval(expr) is MUCH MUCH slower than just executing expr as normal. >>> from timeit import Timer >>> Timer('1+1').timeit() 0.25557518005371094 >>> Timer('eval("1+1")').timeit() 21.816912174224854 If you use eval() a lot, you will have a SLOW program. > and I want to be able to stop them if they run too long. That's tricky. As far as I know, the only way for a Python program to stop an arbitrary calculation after a certain period of time it to run it in a thread. You then monitor the elapsed time, and when the timer expires, ask the thread to die. And hope it listens. > I cannot add code to the eval'd strings that will help me accomplish > this. You can't? Why ever not? Note: that's almost certainly the wrong way to solve your problem, but I'm curious as to why you can't. -- Steven From castironpi at gmail.com Sat Mar 15 20:29:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 15 Mar 2008 17:29:10 -0700 (PDT) Subject: 'join' in the wrong word for the method in class Thread. Message-ID: 'join' in the wrong word for the method in class Thread. The agent-patient semantics of calling functions can get ambiguous. It is not a problem of native Pythoners alone. Is it due to lazy programming, an inability of English (do you have it in other languages?), or not a problem at all? th1.join() doesn't mean, 'do something to th1', or even, 'have th1 do something to itself.' In fact, if anything is doing anything differently, taking waiting to be doing something different, it's the caller. Translating literally, th1.join() -> join me here, th1. And, file1.close() -> close yourself, file1. But not, th1.join() -/> join yourself, th1. Worse, lock1.wait() -/> wait, lock1. (For what?) Furthermore, in toolbars: File -> Open -/> file an open. and: File -> Load -/> load a file. (It means, load the computer.) In English, the placements of identifiers isn't consistent. IOW, there isn't a syntactic mapping into natural language sentences. (Though you can do it in Latin, German, Sanskrit, and Russian with case markers*.) What are the true literals? What's doing what? th1.join() -> 'be joined by th1' file1.close()-> 'close file1' lock1.wait()-> 'getinlinefor lock1' And of course, 'open' isn't a method of File objects at all. The closest is, 'be loaded by file1'. Assuming speakers** of classical computer languages use OVS order-- object-verb-subject***, the most literal transformations are: th1.bejoinedby() file1.close() lock1.getinlinefor(). The mapping of identifiers to English isn't consistent. It takes some knowledge to read them-- shuffle an English sentence and it changes meaning. Functional languages are one long sentence: True.**** Declarative ones tell a story. ('th1' joins him.) Imperatives command an impartial audience. What do the docs say about it? ''' Thread.join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates - either normally or through an unhandled exception - or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened - if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception. ''' The natural language meaning of 'join' isn't used. Do benevolent dictators do this? What do malevolent ones call themselves? *Latin, German, Sanskrit, and Russian can do it. Latin, German, Sanskrit, and Russian -speakers- can do it. **It would be interesting to try to learn a language without ever speaking it. *** English is SVO, subject-verb-object. French is too, unless the object is direct: subject- direct-object -verb. **** The sum of the first three integers in the last two files, sorted alphabetically, in 'c:\programs'. From mmanns at gmx.net Fri Mar 21 16:02:01 2008 From: mmanns at gmx.net (Martin Manns) Date: Fri, 21 Mar 2008 21:02:01 +0100 Subject: How can I make a function equal to 0? References: <7xwsnvetxv.fsf@ruckus.brouhaha.com> Message-ID: On 21 Mar 2008 12:52:12 -0700 Paul Rubin wrote: > def f(): return 0 Let us try it: Python 2.5.1 (r251:54863, Jan 26 2008, 01:34:00) [GCC 4.1.2 (Gentoo 4.1.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def f(): return 0 ... >>> f==0 False >>> f()==0 True >>> I do not want the function to return 0 but to equal 0. Martin From craigm3604 at gmail.com Thu Mar 20 16:42:07 2008 From: craigm3604 at gmail.com (Craig) Date: Thu, 20 Mar 2008 13:42:07 -0700 (PDT) Subject: Need help calling a proprietary C DLL from Python References: <5cbe372d-56b3-447f-99ec-87d4638fa485@i12g2000prf.googlegroups.com> <1a36fca8-3442-4a83-942d-50b227e39e34@i12g2000prf.googlegroups.com> Message-ID: <2603d621-a966-46ab-b268-fc713cfad255@u10g2000prn.googlegroups.com> On Mar 20, 2:38 pm, Craig wrote: > On Mar 20, 2:29 pm, sturlamolden wrote: > > > On 20 Mar, 19:09, Craig wrote: > > > The culprit i here: > > > > Before - X = 0, CacheSize = 0, OpenMode = 3, vHandle = 0 > > > This binds these names to Python ints, but byref expects C types. > > > Also observe that CacheSize and OpenMode should be c_short. > > I changed CacheSize and OpenMode to c_short, and commented out that > line producing the "Before" message, and the output is the same. > > Further "tinkering" revealed that it is the byref on the fName and pw > that are causing the error. > > The entire problem appears to be around the production of a BSTR and > the passing of pointers (byref) to the BSTR. Can anyone shed some light on how to work with BSTR's? From sturlamolden at yahoo.no Sat Mar 15 11:34:46 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 08:34:46 -0700 (PDT) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <13sc3b0g7gud892@corp.supernews.com> Message-ID: On 28 Feb, 02:24, Steven D'Aprano wrote: > Python doesn't do call by reference. Nor does it do call by value. Please > pay no attention to anyone who says it does. Exactly. Python pass variables the same way as Lisp, which is neither "call-by-value" (cf. C) nor "call-by-reference" (cf. Fortran). The Python equivalent of "pass by reference" is a function that returns its arguments to the caller: def foobar(arg1, arg2, arg3): # Mutate a shared object. # I.e. calling convention cannot be not "pass-by-value" arg1.whatever = 1 # Rebind in the local namespace. # I.e. calling convention cannot be "pass-by-value" arg1, arg2, arg3 = 1, 2, 3 # Return rebound variables to achieve the effect of # "pass-by-reference": return (arg1, arg2, arg3) # Call the function foobar, and rebind its arguments to its # return values: arg1, arg2, arg3 = foobar(arg1, arg2, arg3) From duncan.booth at invalid.invalid Sun Mar 16 08:51:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Mar 2008 12:51:41 GMT Subject: Regular Expression Help References: Message-ID: "santhosh kumar" wrote: > I have text like , > STRINGTABLE > BEGIN > ID_NEXT_PANE "Cambiar a la siguiente secci??n de laventana > \nSiguiente secci??n" > ID_PREV_PANE "Regresar a la secci??n anterior de > laventana\nSecci??n anterior" > END > STRINGTABLE > BEGIN > ID_VIEW_TOOLBAR "Mostrar u ocultar la barra de > herramientas\nMostrar/Ocultar la barra de herramientas" > ID_VIEW_STATUS_BAR "Mostrar u ocultar la barra de > estado\nMostrar/Ocultar la barra de estado" > END > ................................ > .................................... > .......................................... > and i need to parse from STRINGTABLE to END as a list object. whatkind of > regular expression should i write. > I doubt very much whether you want any regular expressions at all. I'd do something alone these lines: find a line=="STRINGTABLE" assert the next line=="BEGIN" then until we find a line=="END": idvalue = line.strip().split(None,1) assert len(idvalue)==2 result.append(idvalue) From duncan.booth at invalid.invalid Thu Mar 20 17:14:56 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Mar 2008 21:14:56 GMT Subject: os.path.getsize() on Windows References: <13u2080sffjnnba@corp.supernews.com> <13u3ghthlh25sc0@corp.supernews.com> Message-ID: Sean DiZazzo wrote: > In this case, there will be so few people touching the system, that I > think I can get away with having the copy be done from Unix, but it > would be nice to have a general way of knowing this on Windows. > Doesn't the CreateFile call I posted earlier do what you want? From Lie.1296 at gmail.com Sun Mar 9 04:30:51 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 9 Mar 2008 00:30:51 -0800 (PST) Subject: What c.l.py's opinions about Soft Exception? References: <13t6tf3b5tpcv48@corp.supernews.com> Message-ID: On Mar 9, 12:05 pm, Kay Schluehr wrote: > On 9 Mrz., 04:51, Lie wrote: > > > A more through implementation would start from the raiser inspecting > > the execution stack and finding whether there are any try block above > > it, if no try block exist it pass silently and if one exist it will > > check whether it have a matching except clause. This also circumvents > > a problem that simple implementation have, as described below. > > This will not be easy in particular in the presence of inheritance and > dynamism. There is no way to statically decide whether an exception > BException has the type AException and will be caught by the except > clause in > > try: > BLOCK > except AException, e: > print "SoftException %s caught"%e > A feasible solution was to invert the try...except statement and > creating a continuation. > > catch AException, a: > print "SoftException A: %s"%a > catch BException , b: > print "SoftException B: %s"%b > ... > in: > BLOCK > > Here each SoftException is raised initially when a catch clause is > entered and a continuation is created that returns to the catch block > of the raised SoftException if required. When a SoftException is > raised within BLOCK a lookup will be made and if a corresponding > SoftException was found that was raised by a catch-clause the current > control flow will be suspended and the continuation is called. I'd rather want to avoid any syntax changes, as I wished that Soft Exception can be added to the language silently[1] so that new programmers doesn't _need_ to know about it (although knowing it could change the way they write codes to be more structured and simple). [1] Definition of silently: Codes that aren't aware of this functionality shouldn't break. Adding new syntax usually means adding keywords, making possible break in current program. On Mar 9, 12:30?pm, Steven D'Aprano wrote: > On Sat, 08 Mar 2008 19:51:24 -0800, Lie wrote: > > Soft Exception > > What is "Soft Exception"? > > Soft Exception is an exception that if is unhandled, pass silently as if > > nothing happened. For example, if a variable turns into NoneType, it'll > > raise Soft Exception that it have become NoneException, programmers that > > wants to handle it can handle it with a try...except block while > > programmers that doesn't care about it (or know it won't be a problem to > > his code) can just leave the code as it is. > > > Soft Exception differs from Hard Exceptions (the regular Exception) in a > > way that Hard Exception must be handled at all cost or the program will > > be terminated while Soft Exception allow programmers not to handle it if > > they don't want to. > > I don't think that there are very many cases where exceptions can be > ignored safely. There are two main reasons for using exceptions: > > (1) Signaling an exceptional event. In that case, programmers might decide whether to raise Soft or Hard Exception. Hard Exception is much preferred. > (2) An error occurred. Which must always be handled with Hard Exception. Adding another thing (3) Informing codes above it about what's currently happening inside, the thing is just a mundane report that might be useful to codes above Which might be a useful place to use SoftExceptions > I can't think of many cases where you would wish to ignore either, and > just continue processing. The only examples I can think of are in loops, > where you are doing the same thing over and over again with just a little > change, and you wish to skip any problematic data, e.g.: > > def plot_graph(func, domain): > ? ? for x in domain: > ? ? ? ? plot(x, func(x)) > > If an error occurs in plot() for one particular x value, you would want > to ignore it and go on to the next point. But that's easy enough to do > with a regular try...except block. No, you're misunderstanding the purpose of Soft Exception, it's not for silencing errors and not so much for exceptional cases. It's for the more mundane tasks such as: from __future__ import division class SomeNumeric(object): def __div__(a, b): if b == 0: raise ZeroDivisionError ## Hard Exception, don't ignore me! if a == 0: raise ZeroNumerator ## Soft Exception f = a / b i = a // b if f == float(i): raise IntegerDivision ## Soft Exception return a // b else: raise FloatDivision ## Soft Exception return a / b Most people can ignore the ZeroNumerator, IntegerDivision, and FloatDivision exceptions (warnings) because they're excessive and unnecessary, but some people might want to catch them and do something else (especially ZeroNumerator). Practicle example, far below. The example is actually quite bad at demonstrating the purpose of Soft Exception as it is very simple while Soft Exception is generally more useful in complex operations. But I want to avoid giving complex examples since it'll be more difficult to explain the complex examples instead of the simple examples. > Simply put, you're suggesting the following two alternatives: > > Hard Exceptions: terminate the program unless explicitly silenced > Soft Exceptions: pass silently unless explicitly caught > > In this case, I agree with the Zen of Python ("import this"): > > Errors should never pass silently. > Unless explicitly silenced. That's what sloppy programmers do, silently pass errors. OTOH, Soft exceptions are not used for errors (perhaps the wording can be better phrased: must not be used for errors), they're used for events that some might have interest in, but some would consider it as normal. That's why I mentioned to think of it as a Warning. Operations that raise Soft Exceptions should be able to run normally even when the exception isn't handled (although it might generate garbage out that can be handled at later time). > The cost of explicitly silencing exceptions is tiny, the risk of misuse > of Soft Exceptions is very high, and the benefit of them is negligible. Perhaps relabeling it as Warning, and renaming raise SoftException as give Warning might make it more acceptable? And I agree that the probability for misuse is quite high, but the benefits is also quite high, it's just that you can't see it since you're not used to using such exceptions. The benefit of SoftExceptions lies mostly on the regular programmings tasks, not the exceptional programming tasks Practical Example: This example takes _case ideas_ from this simple gravity simulator http://www.pygame.org/project/617/ BUT _no line of code is taken from it_. I only give this link so you can easily know what the case is about without lengthy explanation. A particle machine. The particle machine calculates gravity created by the particles in a field. Additionaly, it clumps together two particles that happens to be near enough (less than the sum of their radiuses). The force two particle is expressing to each other is calculated with: def calculateforce(P1, P2): return (P1.mass - P2.mass) / distance(P1, P2) and this is done to every particle in the field against the current particle. And the distance is calculated by: def distance(P1, P2) return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 The problem happens when the distance is small enough and we want to clump them together. A possible solution to this problem might be to check whether distance is less than P1.radius + P2.radius in the calculateforce. But, this obfuscate the code since we have to separate distance calculation from the main formula (see !s), and this also insist that clumping be done on force calculation level (see @s), shortly this piece of code is plain bad: def distance(P1, P2): return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 def calculateforce(P1, P2): ## Separating this dist calculation into its own line is ## necessary if we want to check the value of dist ## Personally I think that's a bit obfuscated. ## Well known formulas should be kept to one line if possible ! dist = distance(P1, P2) if dist <= P1.radius + P2.radius: ## Calling clump() here is bad, because ## there are occasions where we only want to ## calculate force but doesn't want to ## clump it @ clump(P1, P2) else: ! return (P1.mass - P2.mass) / dist ## Codes calling calculateforce() # Note: this code is located inside a loop F = calculateforce(P1, P2) # Do something else, acceleration calculation, movement calculations, etc A better refactoring would be like this, but this requires calculating distance twice (see !s): def distance(P1, P2): return (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 def calculateforce(P1, P2): ## Here distance is calculated once ! return (P1.mass - P2.mass) / distance(P1, P2) ## Codes calling calculateforce() # Note: this code is located inside a loop ## Here distance is calculated again ! if distance(P1, P2) <= P1.radius + P2.radius: clump(P1, P2) break F = calculateforce(P1, P2) # Do something else, acceleration calculation, movement calculations, etc A much better solution would be to use SoftException def distance(P1, P2): D = (P1.X - P2.X) ** 2 - (P1.Y - P2.Y) ** 2 if D <= P1.radius + P2.radius: raise Collision return D def calculateforce(P1, P2): try: F = (P1.mass - P2.mass) / distance(P1, P2) except Collision: raise ## Codes calling calculateforce() # Note: this code is located inside a loop try: F = calculateforce(P1, P2) except Collision: clump(P1, P2) break # Calculate the next particle pair else: # Do something else, acceleration calculation, # speed calculation, movement calculations, etc This results in a cleaner code. And it also allow _other part of codes_ that uses calculate distance and force to easily ignore or handle the Collision Exception. If this code had used Hard Exception, other codes would have to explicitly silence the exception or the program terminates. That would be too much since Collision is technically not an Error, but just a normal events that you might be interested to know. Soft Exception allows events of interest to be noticed or be ignored depending on the requirement. It's like a notice board: In the notice board, there are notices about the Maths Test next week, which you must not ignore (Hard Exception), but there are also notices about Part-time Job Advertisement, if you're interested about it you can look at it further, else you could just ignore it and do nothing (Soft Exception) From carsten at uniqsys.com Sun Mar 23 21:02:31 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 24 Mar 2008 02:02:31 +0100 Subject: Does python hate cathy? In-Reply-To: References: Message-ID: <1206320551.3365.20.camel@localhost.localdomain> On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote: > That's really weird... it's reproducible on Windows too. It doesn't > make any sense why the name of the variable would make a difference. > My guess is you hit some kind of obscure bug. This is not a bug, just an unexpected feature: http://mail.python.org/pipermail/python-list/2005-January/304873.html What's happening is that at the end of the script, all objects in the global namespace are set to None (in order to decrease their reference count and trigger garbage collection). This happens in the order in which the names appear as keys in the globals dictionary. It randomly happens that "swaroop", "kalam", and "cath" all are hashed in front of "Person", but "cathy" is hashed after "Person". Hence, if Catherine is named cath, Python "None's" all the instances first and then the type last, and all is well. However, if Catherine is called cathy, Person is set to None before cathy. Then, in the lookup of the global name "Person" during cathy.__del__, Person is None, which doesn't have a "population" attribute, causing the AttributeError. Possible workarounds are: 1) Explicitly delete the global names for the instances before the script runs out. 2) Don't refer to the "Person" type by its global name in __del__, but indirectly as type(self). (This requires Person to be a new-style class, though.) -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Sat Mar 29 20:00:43 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Mar 2008 21:00:43 -0300 Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> Message-ID: En Sat, 29 Mar 2008 16:24:01 -0300, Michael Wieher escribi?: > to me it seems simple. > > C uses != > > why does C use != .... because its kind of hard to type the "equal with a > slash" In C, ! by itself is the logical "not", so !(a==b) is the same as (a!=b) and that's rather consistent. Python doesn't use ! for anything else; != is rather arbitrary but certainly much better than <> (for many objects < and > are meaningless; being equal or not equal has nothing to do with being less or greater) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Mar 25 12:47:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 25 Mar 2008 13:47:34 -0300 Subject: Issues with Python + Batch File References: Message-ID: En Tue, 25 Mar 2008 08:55:12 -0300, tarun escribi?: > I've a batch file which invoks a python file. The python code in the file > brings up a GUI. The GUI is of a test tool which can execute scripts. > > I tried using the following 2 sample of code for my batch file: > > * (1) (2)* > D:\opengui.py D:\opengui.py > goto:end goto:end > :end :end > EXIT TASKKILL /IM C:\WINDOWS\system32\cmd.exe > > Double clicking on the batch file brings up a DOS BOX which opens up the > GUI. On Closing the GUI, the DOS BOX both get closed. But if I close the > GUI > when a test is under execution, the GUI gets closed but the DOS BOX still > remains open. > > I want to some how close the DOS BOX when the GUI is closed. Either rename the script "opengui.pyw" or start it explicitely using: pythonw d:\opengui.py pythonw.exe doesn't create a console (what you call a "DOS BOX"). -- Gabriel Genellina From duncan.booth at invalid.invalid Mon Mar 10 08:14:47 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Mar 2008 12:14:47 GMT Subject: Problem with zipfile and newlines References: Message-ID: "Neil Crighton" wrote: > I'm using the zipfile library to read a zip file in Windows, and it > seems to be adding too many newlines to extracted files. I've found > that for extracted text-encoded files, removing all instances of '\r' > in the extracted file seems to fix the problem, but I can't find an > easy solution for binary files. > > The code I'm using is something like: > > from zipfile import Zipfile > z = Zipfile(open('zippedfile.zip')) > extractedfile = z.read('filename_in_zippedfile') > > I'm using Python version 2.5. Has anyone else had this problem > before, or know how to fix it? > > Thanks, > Zip files aren't text. Try opening the zipfile file in binary mode: open('zippedfile.zip', 'rb') From steve at REMOVE-THIS-cybersource.com.au Fri Mar 28 22:14:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 29 Mar 2008 02:14:43 -0000 Subject: Help me on function definition References: Message-ID: <13ur9gjqggrf528@corp.supernews.com> On Sat, 29 Mar 2008 01:47:21 +0000, aeneng wrote: > Hello everyone, > > I am just starting to use python in numerical cacluation. I need you to > help me to see what's wrong with the following piece of codes, which > computes the cross product of two vectors and returns the result. u and > v are two 3x1 matrix. > > when I import the function, error message show like this >>>> import cross > Traceback (most recent call last): > File "", line 1, in ? > File "cross.py", line 8 > ppp2=u[2]*v[0]-u[0]*v[2] > ^ > SyntaxError: invalid syntax > > WHAT IS WRONG WITH MY CODE? You don't win any points by writing the most unreadable code can you. A little bit of white space makes the code so much easier to read: ppp2 = u[2]*v[0] - u[0]*v[2] But that's not the problem. Your code mixes spaces and tabs for indentation. Spaces are good; tabs are good; both together will eventually lead to disaster. But that's not your problem either. Your REAL problem is that the error you are reporting is NOT the error your code gives. Hint: if your code raises an error, you must copy the code that actually raises an error, not different code with different errors. The code you post reports this error: >>> import cross Traceback (most recent call last): File "", line 1, in File "cross.py", line 1 def cross(u,v) ^ SyntaxError: invalid syntax After fixing that fault (put a colon after the function definition), your code imports correctly. My *guess* is that in your actual code that fails, you have forgotten to close a bracket or brace in line 7 (not 8). -- Steven From rcdailey at gmail.com Wed Mar 5 18:01:19 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Wed, 5 Mar 2008 17:01:19 -0600 Subject: system32 directory Message-ID: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> Hi, Is there a way to get the System32 directory from windows through python? For example, in C++ you do this by calling GetSystemDirectory(). Is there an equivalent Python function for obtaining windows installation dependent paths? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Mon Mar 10 20:46:02 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 10 Mar 2008 19:46:02 -0500 Subject: image matching algorithms In-Reply-To: References: Message-ID: <47D5D64A.8030300@ncee.net> Daniel Fetchinson wrote: >>> There are a number of free tools for image matching but it's not very >>> easy to decipher the actual algorithm from the code that includes db >>> management, GUI, etc, etc. I have my own image database and GUI so all >>> I need is the actual algorithm preferably in pseudo code and not in >>> the form of a research paper (from which I also found a lot but since >>> I'm not that much interested in the actual science of image >>> recognition this seems like an over kill). >>> >> I'd recommend SIFT. There's quite a bit of information on SIFT. In most >> cases, they don't cover the background science too much, but are still >> heavy on the math. Pseudo code is hard to come by since it will take >> many lines of pseudo code just to express one concise mathematical >> equation. There are however many links to implementations in various >> languages on the Wikipedia page. >> >> http://en.wikipedia.org/wiki/Scale-invariant_feature_transform >> >> I have had good experiences with SIFT for feature extraction from images >> (I have used it for panorama stitching and robot mapping). It's >> insensitive to scale and rotation. Note that it is a patented algorithm >> and this may (or may not) pose a problem for you. >> > > Thanks for the info! SIFT really looks like a heavy weight solution, > but do you think the whole concept can be simplified if all I needed > was: given a photo, find similar ones? I mean SIFT first detects > objects on the image and find similarities, but I don't need the > detection part at all, all I care about is similarity for the whole > photo. I surely don't understand the big picture fully but just have > the general feeling that SIFT and other expert tools are an overkill > for me and a simplified version would be just as good with a much more > easily comprehensible core algorithm. > > Or am I being too optimistic and there is no way out of going into the details? > Using the histogram of the picture may be good enough for your application. Here's something I put together for comparing images (for purposes of detecting motion) taken by the built-in web cam in my Macbook Pro. This might be good enough if you play with the threshold. """ I'm writing a simple little app for doing motion detection with data output from wacaw, a package for MacOSX. You could easily modify this script to get data output from some other source. cd /Applications ; for i in `jot 1024`; do /Applications/wacaw --png picture-${i} && sleep 3 ; done; open *.png cd /Applications; open picture-* """ # cd /Applications ; for i in `jot 1024`; do /Applications/wacaw --png picture-${i} && sleep 3 ; done; open *.png # SOURCE: http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/ import os from time import sleep import tempfile import Image # Sun Mar 18 16:40:51 CDT 2007 def diff_image(img1, img2, pix_threshold=50, img_threshold=4): """Compare 2 images to detect possible motion You might want to choose the img_threshold amount based on the conditions. """ img1 = Image.open(img1) img2 = Image.open(img2) if not img1 or not img2: return False img1 = img1.getdata() img2 = img2.getdata() pixel_count = len(img1) pixdiff = 0 for i in range(pixel_count): #if abs(sum(img1[i]) - sum(img2[i])) > pix_threshold: diffval = abs(sum(img1[i]) - sum(img2[i])) #print "Pixel diffval:",diffval if diffval > pix_threshold: pixdiff += 1 diffperc = pixdiff / (pixel_count/100.0) print "Photo diff percentage:",diffperc if diffperc > img_threshold: # motion detected return True else: return False photos = [] # consider automatically serializing this data import commands """ def analyze_thresholds(list_of_photos): last = list_of_photos[0] for photo in list_of_photos[1:]: diff_image(last, photo) last = photo """ def detect(): number = 0 while True: number += 1 sleep(3) current = 'photo-'+str(number) #tmp = tempfile.mktemp() print commands.getoutput('/Applications/wacaw --png ' + current ) # ' + tmp +'.png') # Here's the actual name of the file wacaw created: current = '/Applications/'+current+'.png' photos.append( current ) if len(photos) < 2: # pad the list for the first time photos.append( current ) if diff_image(photos[-1],photos[-2], pix_threshold=50, img_threshold=5): print "motion detected" else: print "motion NOT detected" detect() #import glob #analyze_thresholds(glob.glob('/Applications/photo-*') -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From watine at cines.fr Tue Mar 25 07:00:20 2008 From: watine at cines.fr (Benjamin Watine) Date: Tue, 25 Mar 2008 12:00:20 +0100 Subject: How to send a var to stdin of an external software In-Reply-To: References: <77d0b060-22db-4a77-a057-a3a35eb91fc8@x30g2000hsd.googlegroups.com> Message-ID: <47E8DB44.6040508@cines.fr> Bryan Olson a ?crit : > Benjamin Watine wrote: >> bryanjugglercryptographer at yahoo.com a ?crit : >>> I wrote: >>>> And here's a thread example, based on Benjamin's code: >>> [...] >>> >>> Doh! Race condition. Make that: >>> >>> import subprocess >>> import thread >>> import Queue >>> >>> def readtoq(pipe, q): >>> q.put(pipe.read()) >>> >>> cat = subprocess.Popen('cat', shell=True, stdin=subprocess.PIPE, >>> stdout=subprocess.PIPE) >>> >>> myVar = str(range(1000000)) # arbitrary test data. >>> >>> q = Queue.Queue() >>> thread.start_new_thread(readtoq, (cat.stdout, q)) >>> cat.stdin.write(myVar) >>> cat.stdin.close() >>> cat.wait() >>> myNewVar = q.get() >>> >>> assert myNewVar == myVar >>> print len(myNewVar), "bytes piped around." > >> Great, it works, thank you Bryan ! >> >> Could you explain me why you use a queue instead of a simple array for >> getting the piped var ? > > The call to q.get() will block until an item is in the queue. > At that point in the program, we had already waited for cat to > terminate: > > cat.wait() > myNewVar = q.get() > > But passing cat.wait() does not imply that our own thread has > already read all of cat's output and put it in some destination > object. Data could still be in transit. > > My first version, subsequently titled, "Doh! Race condition," > worked in all of several runs of its built-in test. Doesn't > make it right. > OK, so if I understand well what you said, using queue allow to be sure that the data is passed in totality before coninuing with next instruction. That make sense. Using thread and queue seems to be very more slow than using files redirection with bash. I'll see if it make a great load average and/or I/O time. Thanks again for your help Bryan. Ben From castironpi at gmail.com Tue Mar 4 13:16:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 4 Mar 2008 10:16:32 -0800 (PST) Subject: metaclasses References: <7714baef-fee0-4c66-aa64-e04ef72e6eff@s8g2000prg.googlegroups.com> <75d14972-4dba-4311-9c06-63b3a2859f96@n75g2000hsh.googlegroups.com> Message-ID: On Mar 4, 12:51?am, Gerard Flanagan wrote: > On Mar 4, 6:31 am, castiro... at gmail.com wrote: > > > > > > > On Mar 3, 10:01 pm, Benjamin wrote: > > > > On Mar 3, 7:12 pm, castiro... at gmail.com wrote: > > > > > What are metaclasses? > > > > Depends on whether you want to be confused or not. If you do, look at > > > this old but still head bursting essay:http://www.python.org/doc/essays/metaclasses/. > > > > Basically, the metaclass of a (new-style) class is responsible for > > > creating the class. This means when Python sees > > > class Foo(object): > > > ? ? __metaclass__ = FooMeta > > > class FooMeta(type): > > > ? ? def __new__(cls, name, bases, dct): > > > ? ? ? ?#do something cool to the class > > > ? ? ? ?pass > > > It asks FooMeta to create the class Foo. Metaclasses always extend > > > type because type is the default metaclass. > > > But you can stack class decorations, but not class metas. > > > @somethingcool1 > > @somethingcool2 > > class Foo: > > ? ?pass > > > * class Foo: > > ? ?__metaclass__= MetaCool1, MetaCool > > > * denotes malformed > > ----------------------- > class Meta1(type): > > ? ? def foo1(cls): > ? ? ? ? print 'hello' > > class Meta2(type): > > ? ? def foo2(cls): > ? ? ? ? print 'castiron' > > class Meta(Meta1, Meta2): > ? ? pass > > class Base(object): > ? ? __metaclass__ = Meta > > Base.foo1() > Base.foo2() class Base(object): __metaclass__= type( 'Meta', ( Meta1, Meta2 ), {} ) From grante at visi.com Mon Mar 3 16:25:19 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 03 Mar 2008 21:25:19 -0000 Subject: Talking to a usb device (serial terminal) References: <2bb37982-6826-43a3-85b5-f22516d4a55a@s19g2000prg.googlegroups.com> <632r0bF25q334U1@mid.individual.net> <6de6c1b0-1319-4b78-93a4-5ef0a2b47f82@e6g2000prf.googlegroups.com> Message-ID: <13sor5vjk06i71a@corp.supernews.com> On 2008-03-03, blaine wrote: > As far as PySerial goes - were trying to stick to built-in > modules since cross compiling to an arm processor is being a > little bit of a pain for us. pyserial is pure python, so I don't see how it's going to be any more painful than something you write yourself. If you want something that's more of a transparent object wrapper aroudn the Posix serial interface, there's PosixSerial.py (upon which pyserial's posix support is based): ftp://ftp.visi.com/users/grante/python/PosixSerial.py -- Grant Edwards grante Yow! Everybody gets free at BORSCHT! visi.com From michael.wieher at gmail.com Mon Mar 17 10:55:41 2008 From: michael.wieher at gmail.com (Michael Wieher) Date: Mon, 17 Mar 2008 09:55:41 -0500 Subject: Apache binary error? Message-ID: have simple webpage running apache, mod_python the error is binary.... ...binary as in "every other" time I load the page, Firefox keeps telling me I'm downloading a python script, and asks to open it in WINE, which is really strange. then, alternately, it loads the page just fine. any clues as to why this is happening? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Mar 11 07:44:45 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 11 Mar 2008 12:44:45 +0100 Subject: Python PDF + Pictures In-Reply-To: References: Message-ID: <47D670AD.6050302@behnel.de> durumdara at gmail.com wrote: > I have many photos, and I wanna make some "presentation" from these > photos, a "thumbnail" like document with one image per one page. > > If I wanna make one document now I do this: > I execute a python script that create a html site with resized pictures, > and split this html site to 50 images per one html file. > Next I open these files in OpenOffice Writer by hand, and save them as > PDF document with poor quality (image compression 95%, image DPI 75). > This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that > can opened everywhere (because of PDF format). > > But I wanna automatize this process with python. > The technic that I will use is this: > 1.) Collect the files in dirs. > 2.) I process one dir in one time. > 3.) I get the files. > 4.) I resize them to max. 1024/768. > 5.) I put the actual image file to the PDF document. > 6.) After each 50. file I open new numbered PDF. > 7.) Every picture placed in one page, and every page orientation set up > as the picture orientation (Portrait or Landscape). > > The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. PIL can write PDFs, and it's clearly a good choice for image processing. http://www.pythonware.com/products/pil/ Stefan From castironpi at gmail.com Fri Mar 28 06:09:02 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 28 Mar 2008 03:09:02 -0700 (PDT) Subject: pygame handoff Message-ID: Can anyone do a simple pygame render of a rollercoaster in first- person? I'll do the generator. Just for fun for free. (Ha see pythaaaaaagh. He bothered to carve it. Have a nice day.) From tjreedy at udel.edu Sun Mar 2 16:21:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Mar 2008 16:21:06 -0500 Subject: Altering imported modules References: <200803011856.27611.troworld@gmail.com> Message-ID: "Tro" wrote in message news:200803011856.27611.troworld at gmail.com... | Hi, list. | | I've got a simple asyncore-based server. However, I've modified the asyncore | module to allow me to watch functions as well as sockets. The modified | asyncore module is in a specific location in my project and is imported as | usual from my classes. | | Now I'd like to use the tlslite library, which includes an asyncore mixin | class. However, tlslite imports "asyncore", which doesn't include my own | modifications. | | I'd like to know if it's possible to make tlslite load *my* asyncore module | without changing any of the tlslite code. If your module is also 'asyncore' and comes earlier in the search path, I would expect the import to get yours. From gnewsg at gmail.com Thu Mar 20 07:51:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 20 Mar 2008 04:51:28 -0700 (PDT) Subject: Change user on UNIX Message-ID: <9abaef04-071e-4651-8db9-4c6576cf2583@p73g2000hsd.googlegroups.com> Hi all. Is there any way to su or login as a different user within a python script? I mainly need to temporarily impersonate another user to execute a command and then come back to the original user. I tried to google a little bit about it but I still didn't find a solution. Thanks in advance. --- Giampaolo http://code.google.com/p/pyftpdlib From z80vsvic20 at hotmail.com Mon Mar 10 17:04:09 2008 From: z80vsvic20 at hotmail.com (Eric von Horst) Date: Mon, 10 Mar 2008 14:04:09 -0700 (PDT) Subject: wxPython: some help with Drag&Drop Message-ID: Hi, I need some advice on Drag&Drop. What I want to achieve is the following: - I have a window that is divided in two : on the left hand I have a wx.TreeCtlr and on the other hand a wx.StaticBitmap I want to be able to drag an item from the tree onto the static bitmap. I know how to do drag&drop in a treeCtrl but is there a way that I can make the bitmap detect that something has been dropped on it? I would only need to know the name of the tree obj that was dropped on the bitmap (and the location) Any help much appreciated Erik From gabriel.rossetti at mydeskfriend.com Tue Mar 18 04:06:27 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 18 Mar 2008 09:06:27 +0100 Subject: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 idiom Message-ID: <47DF7803.1070902@mydeskfriend.com> Hello, I am reading core python python programming and it talks about using the idiom described on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 . I'm using python 2.5.1 and if I try : class MyClass(object): def __init__(self): self._foo = "foo" self._bar = "bar" @property def foo(): doc = "property foo's doc string" def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() # credit: David Niergarth @property def bar(): doc = "bar is readonly" def fget(self): return self._bar return locals() like suggested in the book (the decorator usage) I get this : >>> a=MyClass() >>> a.foo Traceback (most recent call last): File "", line 1, in TypeError: foo() takes no arguments (1 given) but if I write it just like on the web page (without the decorator, using "x = property(**x())" instead) it works : >>> a = MyClass() >>> a.foo 'foo' does anyone have an idea as of why this is happening? Thanks, Gabriel From gagsl-py2 at yahoo.com.ar Fri Mar 28 12:56:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Mar 2008 13:56:34 -0300 Subject: base64.urlsafe_b64encode and the equal character References: <816488e4-5471-4c5e-aeb8-5c2821beaec4@m36g2000hse.googlegroups.com> <37d6b141-5ba0-4178-b45a-512e59433803@s12g2000prg.googlegroups.com> Message-ID: En Fri, 28 Mar 2008 13:22:06 -0300, Clodoaldo escribi?: > On Mar 28, 12:09 pm, "Gabriel Genellina" wrote: >> En Fri, 28 Mar 2008 10:54:49 -0300, Clodoaldo >> escribi?: >> >> > What i need to know is where can an equal char appear in a >> > urlsafe_b64encoded string?: >> >> > a)only at end; >> > b)both at the end and at the begginig; >> > c)anywhere in the string; >> >> > A sure answer will make my regexp safer. >> >> Only at the end. The encoded string has 4*n chars when the input string >> has 3*n chars; when the input length is 3*n+1 or 3*n+2, the output has >> 4*(n+1) chars right padded with 2 or 1 "=" chars. >> If your input has 3n chars, the output won't have any "=" > > Thanks. But I'm not sure i get it. What is n? (Any nonnegative integer...) I mean: For base64 encoding, the length of the output depends solely of the length of the input. If the input string length is a multiple of 3, the output length is a multiple of 4, with no "=". If the input length is one more than a multiple of 3, the output has two "==" at the end. If the input length is two more than a multiple of 3, the output has only one "=" at the end. In all cases, the output length is a multiple of 4. [base64 uses 64=2**6 characters so it encodes 6 bits per character; to encode 3 bytes=3*8=24 bits one requires 24/6=4 characters] > A md5 digest will always be 16 bytes length. So if i understand it > correctly (not sure) the output will always be 22 chars plus two > trailing equal chars. Right? Exactly. -- Gabriel Genellina From driedel at printingforsystems.com Thu Mar 13 08:53:05 2008 From: driedel at printingforsystems.com (David P. Riedel) Date: Thu, 13 Mar 2008 08:53:05 -0400 Subject: problem with Python 2.5.2 and gcc 4.3 In-Reply-To: References: <7jRBj.20981$QC.15171@newsfe20.lga> Message-ID: Andrew MacIntyre wrote: > David P. Riedel wrote: > >> I tried building Python 2.5.2 using gcc 4.3.0. The build completes >> with no problems but when I run 'make test', I get a segfault part >> way through the test run. >> >> here is the last part of the output from make test >> >> test_softspace >> test_sort >> test_sqlite >> test_sqlite skipped -- no sqlite available >> test_startfile >> test_startfile skipped -- cannot import name startfile >> test_str >> make: *** [test] Segmentation fault > > You don't identify the platform or O/S, though I'd guess some Linux > distro on i386 or x86-64... > > If you have gdb available, a backtrace might give a clue. > > However, as this is a new major release of gcc I'm automatically going to > assume an optimisation issue. To test this I'd suggest doctoring the > makefile generated by configure to reduce the optimisation level - I'd > suggest trying -O instead of -O3. If that works, try -O2 or -Os. > > If -O2 or -Os works, I'd be taking the matter up with the gcc team. > You are correct -- Mandriva Linux 2007. I will try varying the optimization level and see what happens. Thanks From upton at virginia.edu Sun Mar 9 17:41:17 2008 From: upton at virginia.edu (Dan Upton) Date: Sun, 9 Mar 2008 17:41:17 -0400 Subject: execute In-Reply-To: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> References: <423a01fd-9a0c-4f2c-9c82-49398d2c3e04@v3g2000hsc.googlegroups.com> Message-ID: <5504f9ac0803091441s31f8587ekbc3088e53fbb819e@mail.gmail.com> On Sun, Mar 9, 2008 at 5:22 PM, Gif wrote: > i'm trying to execute a file without replacing the current process, > but after searching the help file, documentations and the web, i can't > a way of doing that. > > os.exec*() will close the current program. > > ps: by executing i mean like typing "mspaint" in run dialog.. it's not > a python file On *nix, you can use os.fork(). According to http://effbot.org/librarybook/os.htm , you can use os.spawn to accomplish a similar effect on Windows, although I haven't used it. Also, you might check the subprocess module -- http://docs.python.org/lib/module-subprocess.html . -dan From cokofreedom at gmail.com Thu Mar 13 05:14:53 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 13 Mar 2008 02:14:53 -0700 (PDT) Subject: List mutation method gotcha - How well known? References: Message-ID: <42fb57ae-f3b8-44bd-b9b3-6df34e443125@n36g2000hse.googlegroups.com> On Mar 13, 8:36 am, "Hendrik van Rooyen" wrote: > Hi, > > I am surprised that it took me so long to bloody my nose on this one. > > It must be well known - and I would like to find out how well known. > > So here is a CLOSED BOOK multiple choice question - no RTFM, > no playing at the interactive prompt: > > Given the following three lines of code at the interactive prompt: > > foo = [1,2,3,4] > x = foo.append(5) > print x > > What will be the output (choose one): > > 1) [1,2,3,4] > 2) [1,2,3,4,5] > 3) That famous picture of Albert Einstein sticking out his tongue > 4) Nothing - no output > 5) None of the above > > I undertake to summarise answers posted to complete this "survey". > > - Hendrik None is the likely answer as .append is an inplace change and will return None... From dewitters at gmail.com Sun Mar 30 04:08:34 2008 From: dewitters at gmail.com (dewitters at gmail.com) Date: Sun, 30 Mar 2008 01:08:34 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <7xhcepeqjj.fsf@ruckus.brouhaha.com> <13usamtfql9a87c@corp.supernews.com> Message-ID: <5f067c48-e6d4-405b-a064-70b26f8b0343@m71g2000hse.googlegroups.com> On Mar 29, 12:41 pm, Steven D'Aprano wrote: > Given that <= is a comparison operator, not an assignment, why do you > jump to the conclusion that != is an assignment? Why don't you argue that > "x <= y" means "assign the value of x Since you jump to an invalid conclusion about !=, the rest of your > argument fails. No, you said <= could be confusing, but we're talking about <> here, and there is no confusion about that :). From sturlamolden at yahoo.no Sun Mar 16 22:35:22 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Mar 2008 19:35:22 -0700 (PDT) Subject: replace string in a file References: <47dc3781$0$869$ba4acef3@news.orange.fr> Message-ID: <0369b78b-6681-4807-b944-fb371cdd1522@59g2000hsb.googlegroups.com> On 15 Mar, 21:54, Unknown wrote: > I was expecting to replace the old value (serial) with the new one > (todayVal). Instead, this code *adds* another line below the one found... > > How can I just replace it? A file is a stream of bytes, not a list of lines. You can't just replace a line with another, unless they have the exact same length. You must rewrite the whole file to get it right. From fminervino at gmail.com Fri Mar 14 09:25:28 2008 From: fminervino at gmail.com (fminervino at gmail.com) Date: Fri, 14 Mar 2008 06:25:28 -0700 (PDT) Subject: find string in file Message-ID: Hi friends !! I'm neophite about python, my target is to create a programa that find a specific string in text file. How can do it? Thanks fel From rokkamraja at gmail.com Fri Mar 7 03:21:36 2008 From: rokkamraja at gmail.com (Raja) Date: Fri, 7 Mar 2008 00:21:36 -0800 (PST) Subject: Python GDB Wrapper References: <47d0f228$0$17725$9b622d9e@news.freenet.de> Message-ID: Hi All, Thanks for replies. Daniel- I am looking at just a wrapper around GDB. I dont want to emulate the functionalities of GDB but instead use them in python scripting. Martin - Misc/gdbinit looks promising. Thanks a lot. Thanks, Raja. On Mar 7, 12:43 pm, "Martin v. L?wis" wrote: > > Has anyone does this before ? Even some basic idea or code as to how > > to proceed would be great. > > Have you seen Misc/gdbinit? > > Regards, > Martin From http Wed Mar 19 02:47:27 2008 From: http (Paul Rubin) Date: 18 Mar 2008 23:47:27 -0700 Subject: ftp recursively References: <382dnfe5EIWqrn3anZ2dnUVZ_jGdnZ2d@comcast.com> Message-ID: <7xk5jz1a80.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > ftping it as a flat file, and untarring it on the other side. Of > course, the motivation wasn't just to get the files from point A to > point B using Unix (which I already know how to do), but to take > advantage of an opportunity to learn some Python; next time, I'll try > the ftpmirror.py script if it's generic enough, or ftplib if there are > more specific requirements. I see, that wasn't clear in your original post. You should look at the os.walk function if you want to know how to traverse a directory tree (maybe you are already doing this). Also, for security reasons, it's getting somewhat uncommon, and is generally not a good idea to run an ftpd these days, even on a LAN. It's more usual these days to transfer all files by rcp or rsync tunnelled through ssh. From steven.klass at gmail.com Sat Mar 22 17:11:16 2008 From: steven.klass at gmail.com (rh0dium) Date: Sat, 22 Mar 2008 14:11:16 -0700 (PDT) Subject: Pyparsing help Message-ID: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Hi all, I am struggling with parsing the following data: test1 = """ Technology { name = "gtc" dielectric = 2.75e-05 unitTimeName = "ns" timePrecision = 1000 unitLengthName = "micron" lengthPrecision = 1000 gridResolution = 5 unitVoltageName = "v" voltagePrecision = 1000000 unitCurrentName = "ma" currentPrecision = 1000 unitPowerName = "pw" powerPrecision = 1000 unitResistanceName = "kohm" resistancePrecision = 10000000 unitCapacitanceName = "pf" capacitancePrecision = 10000000 unitInductanceName = "nh" inductancePrecision = 100 } Tile "unit" { width = 0.22 height = 1.69 } Layer "PRBOUNDARY" { layerNumber = 0 maskName = "" visible = 1 selectable = 1 blink = 0 color = "cyan" lineStyle = "solid" pattern = "blank" pitch = 0 defaultWidth = 0 minWidth = 0 minSpacing = 0 } Layer "METAL2" { layerNumber = 36 maskName = "metal2" isDefaultLayer = 1 visible = 1 selectable = 1 blink = 0 color = "yellow" lineStyle = "solid" pattern = "blank" pitch = 0.46 defaultWidth = 0.2 minWidth = 0.2 minSpacing = 0.21 fatContactThreshold = 1.4 maxSegLenForRC = 2000 unitMinResistance = 6.1e-05 unitNomResistance = 6.3e-05 unitMaxResistance = 6.9e-05 unitMinHeightFromSub = 1.21 unitNomHeightFromSub = 1.237 unitMaxHeightFromSub = 1.267 unitMinThickness = 0.25 unitNomThickness = 0.475 unitMaxThickness = 0.75 fatTblDimension = 3 fatTblThreshold = (0,0.39,10.005) fatTblParallelLength = (0,1,0) fatTblSpacing = (0.21,0.24,0.6, 0.24,0.24,0.6, 0.6,0.6,0.6) minArea = 0.144 } """ So it looks like starting from the inside out I have an key and a value where the value can be a QuotedString, Word(num), or a list of nums So my code to catch this looks like this.. atflist = Suppress("(") + commaSeparatedList + Suppress(")") atfstr = quotedString.setParseAction(removeQuotes) atfvalues = ( Word(nums) | atfstr | atflist ) l = ("36", '"metal2"', '(0.21,0.24,0.6,0.24,0.24,0.6)') for x in l: print atfvalues.parseString(x) But this isn't passing the list commaSeparatedList. Can someone point out my errors? As a side note: Is this the right approach to using pyparsing. Do we start from the inside and work our way out or should I have started with looking at the bigger picture ( keyword + "{" + OneOrMore key / vals + "}" + ) I started there but could figure out how to look multiline - I'm assuming I'd just join them all up? Thanks From jerry.fleming at saybot.com Tue Mar 18 21:00:20 2008 From: jerry.fleming at saybot.com (Jerry Fleming) Date: Wed, 19 Mar 2008 09:00:20 +0800 Subject: ctypes in python failed to honor c_int In-Reply-To: <49a1aad5-9020-4e6c-9389-502504a55ae4@u69g2000hse.googlegroups.com> References: <010e2111-6c8b-4e7b-a52d-0c5c6ddfd148@v3g2000hsc.googlegroups.com> <49a1aad5-9020-4e6c-9389-502504a55ae4@u69g2000hse.googlegroups.com> Message-ID: Gabriel Genellina wrote: > On 18 mar, 04:12, Jerry Fleming wrote: >> Gabriel Genellina wrote: >>> On 17 mar, 23:57, Jerry Fleming wrote: >>>> I have a binary file written with c structures. Each record contains a >>>> null-terminated string followed by two 4-bytes integers. I wrote a small >>>> segment of python code to parse this file in this way: >>>> [coe] >>>> #!/usr/bin/python >>>> from ctypes import * >>>> class Entry(Structure): >>>> _fields_ = ('w', c_char_p), ('s', c_uint, 32), ('l', c_uint, 32) >>>> idx = open('x.idx', 'rb') >>>> str = idx.read(1000) >>>> obj = Entry(str) >>>> print obj.w >>>> print obj.s >>>> print obj.l >>>> [/code] >>>> where the field w is the string, and s and l are the integers. Problem >>>> is that, I can only get the strings, not the integers. Well, I did got >>>> integers, but they are all zeros. What should I do to get the real numbers? >>> So the string has a variable length? For "Hello" you have >>> 'h','e','l','l','o', a zero byte, followed by the two integers? This >>> is somewhat unusual for a C struct (in fact you can't declare it in >>> C). Perhaps the string is actually a char[n] array with a declared >>> maximum size? >> Yes, it has a variable length. The C version of the structure is >> something like this: >> [code] >> struct entry { >> char *str, >> int start, >> int length} >> >> [/code] > > But this doesn't match the file contents. There are no pointers in the > file. > >> And adding repr() would print something like this: >> [code] >> '(as) mad as a >> hatter\x00\x00\x00\x00\x00\x00\x00\x00\x1f-ish\x00\x00\x00\x00\x1f\x00\x00\?x00 at -ism\x00\x00\x00\x00_\x00\x00\x00B-ist\x00\x00\x00\x00\xa1\x00\x00\x00J?.AU\x00\x00\x00\x00\xeb\x00\x00\x00P.EXE\x00\x00\x00\x01;\x00\x00\x00`.GIF\?x00\x00\x00' >> (as) mad as a hatter >> 0 >> 0 >> [/code] >> where the first line is the result of repr(). We can find that, after >> the null-terminated string '(as) mad as a hatter', there are two >> integers, 0 and 31 (0x1f). But python treat 31 as zero. > > Ah, but it doesn't "treat 31 as zero". Entry(str) is the same as > Entry(w=str), that is, you are initializing the w attribute alone, > leaving the other two integers as 0. > I don't know how to use ctypes to read the structure (nor if it is > possible at all), I would read it normally with Python code and build > the struct afterwards (in case it is used to call any C code). > > w, data = data.split('\x00', 1) > s, l = struct.unpack("ll", data[:8]) > data= data[8:] > > -- > Gabriel Genellina Oh yes. What an idiot I am. Thanks Gabriel very much. From ncoghlan at gmail.com Tue Mar 4 07:00:17 2008 From: ncoghlan at gmail.com (NickC) Date: Tue, 4 Mar 2008 04:00:17 -0800 (PST) Subject: Embedding a literal "\u" in a unicode raw string. References: <47C340D4.6020803@v.loewis.de> Message-ID: <891938ee-ad81-43de-9985-73cd26e4268d@s12g2000prg.googlegroups.com> On Feb 26, 8:45 am, rmano wrote: > BTW, 2to3.py should warn when a raw string (not unicode) with \u in > it, I think. > I tried it and it seems to ignore the problem... Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> r"\u" '\\u' >>> r"\uparrow" '\\uparrow' >>> r"\u005c" '\\u005c' >>> r"\N{REVERSE SOLIDUS}" '\\N{REVERSE SOLIDUS}' >>> "\u005c" '\\' >>> "\N{REVERSE SOLIDUS}" '\\' 2to3.py may be ignoring a problem, but existing raw 8-bit string literals containing a '\u' aren't going to be it. If anything is going to have a problem with conversion to Py3k at this point, it is raw Unicode literals that contain a Unicode escape. From fakeaddress at nowhere.org Thu Mar 13 12:50:16 2008 From: fakeaddress at nowhere.org (Bryan Olson) Date: Thu, 13 Mar 2008 09:50:16 -0700 Subject: How to send a var to stdin of an external software In-Reply-To: References: Message-ID: I wrote: > [...] Pipe loops are tricky business. > > Popular solutions are to make either the input or output stream > a disk file, or to create another thread (or process) to be an > active reader or writer. Or asynchronous I/O. On Unix-like systems, you can select() on the underlying file descriptors. (MS-Windows async mechanisms are not as well exposed by the Python standard library.) -- --Bryan From andoni.oconchubhair at fmr.com Tue Mar 18 11:34:32 2008 From: andoni.oconchubhair at fmr.com (Andoni) Date: Tue, 18 Mar 2008 08:34:32 -0700 (PDT) Subject: Need to force SpamBayes to run. Message-ID: Hi all, I realise this is not the SpamBayes list but you could grow old waiting for that so trying here. We are using SpamBayes to filter messages coming in to a mailbox. It misses some messages with errors like what's below. When this happens we can go in and click "Filter Messages" and it runs no problem. What I would like to be able to do is to have an hourly batch-job that runs that same process for me. I don't see anything in the file system that would allow me to run a command-line call that executes "Filter Messages". Can anybody help? Thanks in advance, Andoni OConchubhair. pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "win32com\server\policy.pyc", line 283, in _Invoke_ File "win32com\server\policy.pyc", line 288, in _invoke_ File "win32com\server\policy.pyc", line 647, in _invokeex_ File "win32com\server\policy.pyc", line 581, in _invokeex_ File "addin.pyc", line 390, in OnItemAdd File "msgstore.pyc", line 365, in GetMessage msgstore.NotFoundException: NotFoundException: Exception 0x8004010f (MAPI_E_NOT_FOUND): OLE error 0x8004010f From steve at REMOVE-THIS-cybersource.com.au Sun Mar 9 00:09:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 05:09:45 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <13t6c58lu2iog2a@corp.supernews.com> Message-ID: <13t6s8pk90olef8@corp.supernews.com> On Sat, 08 Mar 2008 20:45:25 -0800, sjdevnull at yahoo.com wrote: > On Mar 8, 7:34 pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 08 Mar 2008 19:31:47 +0000, Grant Edwards wrote: >> > I'm also a bit baffled by people who put a comment at the top of >> > every file that tells you what the filename is. >> >> [snip rant] >> >> You've never printed out a source file on pieces of dead tree to read >> on the train on the way home, or in bed or the bath? >> >> Yes, some editors will print a header or footer showing the file name, >> but not all will, or are configured to do so. > > The only times I can recall printing source were in college classes > where I was required to hand in a hardcopy with the assignment and code > samples for job interviews. In the real world the code base tends to be > too huge to contemplate printing... You've never (say) printed out the source code to one of the modules in the Python standard library to read and study? If your code base is so huge that you can't print out any meaningful piece, then you desperately need more encapsulation. > Even in the early 1990s the moral equivalent of enscript (I think it was > a2ps) worked just fine for printing with filenames, line/page numbers, > and other niceties no matter what editor you used. It seems more > reasonable to mandate using a sane print tool for the odd case where > someone wants to print things out than to mandate cluttering up every > file with the filename in a comment. Sure, but really, adding ONE LINE to the start of a file is hardly "cluttering up" anything. Especially if it is in the doc string, like this: """widgets.py: create, manage and destroy widgets. blah blah blah blah...""" -- Steven From gabriel.rossetti at mydeskfriend.com Tue Mar 11 04:49:18 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Tue, 11 Mar 2008 09:49:18 +0100 Subject: execute python script question In-Reply-To: <9e299ffa-2fab-4dcc-907c-8aa667bde3d4@n58g2000hsf.googlegroups.com> References: <9e299ffa-2fab-4dcc-907c-8aa667bde3d4@n58g2000hsf.googlegroups.com> Message-ID: <47D6478E.1050403@mydeskfriend.com> Sam wrote: > Hello, > > I may misunderstand your problem, but it may be related to the > execution environment, especially the PYTHONPATH variable. Have a look > at the following log: > > samuel at Bioman2:/$ pwd > / > samuel at Bioman2:/$ cat -n /tmp/test_import.py > 1 class A(object): > 2 def __init__(self): > 3 self.value = 1 > 4 def show(self): > 5 print self.value > samuel at Bioman2:/$ python > Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> from test_import import A >>>> > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named test_import > >>>> exit() >>>> > samuel at Bioman2:/$ export PYTHONPATH=/tmp > samuel at Bioman2:/$ python > Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) > [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> from test_import import A >>>> a=A() >>>> a.show() >>>> > 1 > > > ++ > > Sam > Hello Sam, Thank you for your reply. I tried that and it works, thanks. I was trying to modify the sys.path in __init__.py and it wasn't working. Gabriel From newsgroups at debain.org Wed Mar 5 02:15:07 2008 From: newsgroups at debain.org (Samuel) Date: Wed, 5 Mar 2008 07:15:07 +0000 (UTC) Subject: Protocol for thread communication References: Message-ID: On Tue, 04 Mar 2008 22:12:00 -0700, Michael Torrie wrote: > Does anyone have any recommended ideas/ways of implementing a proper > control and status protocol for communicating with threads? I have a > program that spawns a few worker threads, and I'd like a good, clean way > of communicating the status of these threads back to the main thread. > Each thread (wrapped in a very simple class) has only a few states, and > progress levels in those states. And sometimes they can error out, > although if the main thread knew about it, it could ask the thread to > retry (start over). How would any of you do this? A callback method > that the thread can call (synchronizing one-way variables isn't a > problem)? A queue? How would the main thread check these things? I implemented a generic library that could easily support these things: http://code.google.com/p/exscript/source/browse/trunk/lib/WorkQueue/ Basically, it's an asynchronous queue into which the jobs are added. The "MainLoop" class manages jobs (like, making sure that n jobs are running at the same time, and providing signals when jobs are done). One way to add a status to each job is by adding a status attribute to the Job class, in addition, a Job may emit a signal (using a simple signal/event mechanism such as this one: http://code.google.com/p/exscript/source/browse/trunk/lib/Exscript/ Trackable.py ) whenever a status changes, and have the MainLoop class fetch that. -Samuel From richardjones at optushome.com.au Fri Mar 28 20:07:09 2008 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 29 Mar 2008 11:07:09 +1100 Subject: Building a "safe" python? References: <4a2ade35-9624-4e26-ba47-984c72ea4f6a@y21g2000hsf.googlegroups.com> Message-ID: <47ed882d$0$26468$afc38c87@news.optusnet.com.au> martin.nordstrom87 at gmail.com wrote: > I'm making a game where you'll be able to make your own mods and I > want to be able to write these mods in python. Check out tinypy: http://www.philhassey.com/blog/category/tinypy/ Richard From sjmachin at lexicon.net Thu Mar 27 06:56:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Mar 2008 10:56:29 GMT Subject: subtract dates with time module In-Reply-To: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> References: <16b10790-a57f-4e7e-bbb5-32e71b321771@u69g2000hse.googlegroups.com> Message-ID: <47eb7d5b$1@news.mel.dft.com.au> barronmo wrote: > I'm trying to get the difference in dates using the time module rather > than datetime because I need to use strptime() to convert a date and > then find out how many weeks and days until that date. datetime.datetime.strptime was introduced in Python 2.5; what version are you using? If you really want to get to datetime, here's a quick bridge: >>> import time, datetime >>> def mystrptime(astr, format): ... return datetime.datetime(*time.strptime(astr, format)[:6]) ... >>> mystrptime('2008-03-31', '%Y-%m-%d') datetime.datetime(2008, 3, 31, 0, 0) > I'm a beginner > so any help would be appreciated. Here is the code: > > def OBweeks(ptID): > qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' % > (ptID) > results = EMR_utilities.getAllData(qry) > for items in results: > r = re.search('\d\d\d\d-\d\d-\d\d', items) > if r: > d = time.strptime(r.group(), "%Y-%m-%d') - You have " at the start and ' at the end of what's supposed to be a string constant. That's a syntax error; it won't run. Please don't serve up what you thought you might have run -- use copy/paste. In this particular case, you can just use time.mktime to convert a time tuple into days since the epoch. # untested days = time.mktime(time.strptime(r.group(), "%Y-%m-%d")) - int(time.mktime(time.localtime())) weeks, days = divmod(days, 7) > time.localtime() > weeks, days = divmod(d.days, 7) > return '%s %s/7 weeks' % (weeks, days) > > This isn't working. I'm getting "unsupported operand type for -: > 'time.struct_time' and 'time.struct_time" error. It *is* working. That is the correct result of the code that you executed. There is is nothing in the time docs to suggest that attempting to subtract time tuples produces anything useful. HTH, John From bj_666 at gmx.net Tue Mar 18 03:41:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Mar 2008 07:41:52 GMT Subject: Why doesn't xmlrpclib.dumps just dump an empty value instead of ? References: <20080316132140.GA24529@piper.oerlikon.madduck.net> Message-ID: <649a20F24ufa8U1@mid.uni-berlin.de> On Mon, 17 Mar 2008 17:41:23 +0100, martin f krafft wrote: > also sprach martin f krafft [2008.03.16.1421 +0100]: >> Why doesn't it just yield >> >> '\n\n\n\n' >> >> Or even just >> >> '\n\n\n' > > There's a difference between those two. The first one has an empty > string value ('') while the second one pretty clearly says that > there is a parameter but has no value. > > Why ? Because there is a difference between no value and the NULL value!? Ciao, Marc 'BlackJack' Rintsch From aahz at pythoncraft.com Thu Mar 27 15:54:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2008 12:54:37 -0700 Subject: Pycon disappointment References: <5bd37c10-af5d-4254-8799-49c762673a3e@n58g2000hsf.googlegroups.com> Message-ID: In article , Barry Hawkins wrote: > >I'll step out and say that some of the non-vendor talks were quite >weak. The most severe was a talk on Stackless where the original >speaker was unable to be here and someone got up and clicked through >the slide deck at a very fast pace. I thought the person had stepped >in at the last minute, but later learned that he had volunteered with >a couple of weeks' notice. Additionally, the original speaker had >Andrew Dalke's *exact* slide deck from his Stackless talk last year. >One first-time attendee told me over lunch that he was going to >recommend to his employer that they not pay to send their programmers >to PyCon next year based on what he had seen in this year's talks. I >know that's an unpleasant message, but in the interest of preserving >PyCon's quality, I'm willing to be the jerk of a messenger. The plural of anecdote is not data. I sympathize with what you're saying to some extent, but any gathering of a thousand people will certainly garner comments like this. Moreover, there will be some talks that screw up because of short notice changes (and believe me, two weeks is short notice). Feedback is for the most part only interesting in the aggregate. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From google at mrabarnett.plus.com Sun Mar 30 10:10:20 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 30 Mar 2008 07:10:20 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: On Mar 30, 6:35 am, "Gabriel Genellina" wrote: > En Sun, 30 Mar 2008 02:11:33 -0300, hdante escribi?: > > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > > if x ? 0: > > ?y ? s: > > if y ? 0: f1(y) > > else: f2(y) > > Fine if you have the right keyboard... Try to write APL with a standard > keyboard :) > There was a version of APL for the Sinclair QL which replaced the standard APL symbols with keywords. From agostino.russo at gmail.com Wed Mar 19 10:38:18 2008 From: agostino.russo at gmail.com (ago) Date: Wed, 19 Mar 2008 07:38:18 -0700 (PDT) Subject: Generalizing PEP 370 (per user site-packages directory) via .pth files Message-ID: <03cb8d9c-71b5-460c-8fb1-44d4e60c40d0@s13g2000prd.googlegroups.com> Dear all, I was reading pep 370, "Per user site-packages directory" http://www.python.org/dev/peps/pep-0370/, and was wondering if the concept couldn't be generalized by having ways to pass a .pth file as commandline argument and/or via an environment variable (PYTHONPATH could also be used to feed .pth files) and/or via special named files such as ~/.python2.6-user.pth or ./python2.6-local.pth, or possibly even reusing the paths in the distutils configuration files (under [install]). Any path in the above files would be added to sys.path and scanned recursively for other pth files. The system would also load default.pth from a pre-defined location (e.g. /etc/python2.6/ default.pth), which would point to the default site-packages directory. There should also be a mechanism to disable/override default.pth for situations where a clean environment is desired. This would make it easier to setup special testing environments, perform local installations, and allow for file-based deployments (in simple scenarios), without resorting to special tools such as virtual- python, editing site.py and/or requiring sysadmin intervention. It would be particularly useful in environments where there is a clear separation between IT and developer roles. I just started giving some thoughts to the concept and I am not fully aware of the implications and requirements of the proposal, but even if the above turns out to be impractical, I hope that a debate on the topic will be beneficial. Ago From martin.laloux at gmail.com Fri Mar 14 08:15:55 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Fri, 14 Mar 2008 05:15:55 -0700 (PDT) Subject: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard References: <129a23b3-ed90-43cb-bdc9-8913c05bcc09@f63g2000hsf.googlegroups.com> Message-ID: <85a6cd50-9c03-45c6-832c-45a152eb2561@e6g2000prf.googlegroups.com> look at http://groups.google.be/group/comp.lang.python/browse_thread/thread/d75a491b8dbc3880/0ca1fb7f7deca194?hl=fr&lnk=gst&q=laloux#0ca1fb7f7deca194 There is a macpython list that you can consult at http://www.nabble.com/Python---pythonmac-sig-f2970.html From john106henry at hotmail.com Mon Mar 31 13:37:42 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 31 Mar 2008 10:37:42 -0700 (PDT) Subject: python scripts to standalone executable References: <34dce829-9eca-4e13-a9c5-eeb9f6b913be@e6g2000prf.googlegroups.com> Message-ID: On Mar 31, 10:24 am, Amit Gupta wrote: > Hi > > I am looking for a some tool that can convert python scripts to > executable on Linux. > > I found freeeze.py as the only option so far. Couple of queries on > freeze: > > 1. Have anyone used the freeze utility and any experiences to share > from that? > 2. Is there any enterprise-level exe-builder for python on linux > (ActiveState has nothing)? > > Any other related commets are also welcome. > > Thanks > Amit I don't know about freeeze.py but for me, I've been using py2exe, and also pyinstall quite often and they both work for me. From grante at visi.com Tue Mar 11 11:35:52 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 11 Mar 2008 15:35:52 -0000 Subject: urllib proxy support confusion Message-ID: <13td9mobtoadgc2@corp.supernews.com> Reading through the doc at http://docs.python.org/lib/module-urllib.html, there are several paragraphs (including code examples) showing how you specify what proxies to use when calling urlopen(): Alternatively, the optional proxies argument may be used to explicitly specify proxies. [...] The explanation of how to specify proxies is followed by this paragraph denying that the ability to do so exists: The urlopen() function does not support explicit proxy specification. If you need to override environmental proxy settings, use URLopener, or a subclass such as FancyURLopener. That seems a bit baffling. If it urlopen doesn't support specifying proxies, why are there examples showing how to do it? If it does support specifying proxies, what is the pragraph quoted above supposed to mean? -- Grant Edwards grante Yow! Am I accompanied by a at PARENT or GUARDIAN? visi.com From sturlamolden at yahoo.no Thu Mar 20 13:03:40 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Mar 2008 10:03:40 -0700 (PDT) Subject: wxFormBuilder References: <9a27e$47e28f17$83aef404$28537@news1.tudelft.nl> Message-ID: <4bfece6c-19ad-41bf-846a-7139034dc737@s8g2000prg.googlegroups.com> On 20 Mar, 17:21, Stef Mientki wrote: > I've tried several of the above mentioned builders, > with the same result. > I've also looked at wxFormBuilder, > but I found it far too difficult and > fully unreadable (how can you create actions/bindings on components you don't see ?). > So I might be very very naive, > but why all so complex ?? Complex? Not at all! Let me show you an 'hello world!' example. Below is the content of two files: HelloWorld.py hand-written be me, and HelloWorld.xrc emitted by wxFormBuilder. I gave each control a care about a name in wxFormBuilder, and use that to e.g. bind events and load resources. HelloWorld.py: import wx from wx import xrc import sys class MainFrame(object): def __init__(self, xml): self.xml = xml self.frame = xml.LoadFrame(None,'MainFrame') self.frame.Bind(wx.EVT_MENU, self.on_menu_exit, id=xrc.XRCID('menuExit')) self.frame.Bind(wx.EVT_BUTTON, self.on_say_hello, id=xrc.XRCID('btnSayHello')) self.frame.Show() def on_say_hello(self, evt): dlg = self.xml.LoadDialog(self.frame, 'HelloDialog') dlg.ShowModal() dlg.Destroy() def on_menu_exit(self, evt): self.frame.Destroy() sys.exit(0) class HelloWordApp(wx.App): def OnInit(self): xml = xrc.XmlResource('HelloWorld.xrc') self.MainFrame = MainFrame(xml) return True if __name__ == '__main__': app = HelloWordApp(0) app.MainLoop() HelloWorld.xrc: 289,171 wxVERTICAL wxEXPAND 5 0,0 wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL 5 0 wxEXPAND 5 0,0 190,144 wxVERTICAL wxEXPAND 5 wxVERTICAL wxEXPAND 5 0,0 wxALIGN_CENTER|wxALL 5 14 swiss normal 0 Times New Roman wxEXPAND 5 0,0 wxEXPAND | wxALL 5 wxEXPAND 5 wxALIGN_CENTER_HORIZONTAL|wxALL 5 From sjdevnull at yahoo.com Mon Mar 10 16:44:04 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 10 Mar 2008 13:44:04 -0700 (PDT) Subject: Keep a python script running after browser window closed References: Message-ID: <077706bf-7190-44bc-9407-7d16b205d886@p73g2000hsd.googlegroups.com> On Mar 10, 1:42 pm, sophie_newbie wrote: > On Mar 7, 4:33 pm, Mike Driscoll wrote: > > > > > On Mar 7, 10:28 am, sophie_newbie wrote: > > > > Hi, > > > > I have a cgi script that performs a very long computation that can > > > take several hours to complete. Is there any smart way that I can keep > > > this script running until it is finished (after the user has closed > > > the browser) and email them with the results. The email bit isn't the > > > problem, I just don't know how to keep the code running in the > > > background. I'm sure there is a smart way to do this... > > > > Thanks! > > > You might have your cgi script use the subprocess module to open a > > second script that does the long-running process. > > > Mike > > Ya it looks like: > > import subprocess > > # spawn subprocess > subprocess.Popen(["python", "spawn.py"]) > > Should do this job, where spawn.py is the script to do the job. > Thanks. In real life, you probably want spawn.py to do a full daemonize. That means fork/setsid/fork/chdir appropriately/deal with stdin/stdout/ umask, or however you set up a service on Windows. From max at alcyone.com Tue Mar 4 00:58:55 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 03 Mar 2008 21:58:55 -0800 Subject: sympy: what's wrong with this picture? In-Reply-To: <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <46ae5277-f79c-4939-b5a9-fb252d037d1c@s13g2000prd.googlegroups.com> Message-ID: Mensanator wrote: > While we're on the subject of English, the word "worthless" > means "has no value". So, a program that doesn't work would > generally be "worthless". One that not only doesn't work but > creates side effects that cause other programs to not work > (which don't have bugs) would be "worse than worthless". All programs have bugs, which means that in some circumstances, they won't work. Therefore, by your reasoning, all programs are worse than useless. > I'm not hard to please at all. No, of course not, since logically you must think all software is useless. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Life is a zoo in a jungle. -- Peter de Vries From barnburnr at gmail.com Mon Mar 3 12:57:35 2008 From: barnburnr at gmail.com (barnburnr at gmail.com) Date: Mon, 3 Mar 2008 09:57:35 -0800 (PST) Subject: clocking subprocesses Message-ID: <75656440-fc52-46f8-9974-599b4bbc86d1@h11g2000prf.googlegroups.com> Hi, I've seen several threads on this subject, but haven't (yet) run across one that answers my specific questions. This should be really easy for someone, so here goes: I'm running some numerical simulations under Ubuntu, and using Python as my scripting language to automatically manage input and output. I need to have a precise performance measurement (CPU time) of how long it takes to run my simulations. Right now I have something like: stime = time.time() subprocess.call(["./mysim","args"]) ftime = time.time() print ftime-stime However, time.time() only gives wall-clock time, so I'm also measuring the time it takes to run other processes running at the same time. What I'd rather have is: stime = time.clock() subprocess.call(["./mysim","args"]) ftime = time.clock() print ftime-stime But this, of course, usually outputs 0, because time.clock() does not count the CPU ticks of the subprocess. So, long story short, I need to get CPU time of something I call using subprocess.call(). I don't want to have to profile my code, since it will significantly reduce computation time. Thanks for the advice. Kevin From timothy.brian14 at gmail.com Wed Mar 26 11:31:39 2008 From: timothy.brian14 at gmail.com (Timothy B) Date: Wed, 26 Mar 2008 08:31:39 -0700 (PDT) Subject: Sr. Architect - NYC - Opportunity Message-ID: <601e5c47-519e-42e8-b4f8-0eeb0496f28e@a70g2000hsh.googlegroups.com> Senior Developer Must be proficient in Python, expert preferred Must have one large scale public web project in their portfolio, preferably startup experience Must be able to develop with certain architectural considerations in mind at all times, such as: multilingual text, runtime efficiency in a very high load environment, file mgmt in a clustered environment, etc Must be self-motivated and eager to utilize the existing team's business knowledge to advance their own knowledge. We don't want anyone who wants to squirrel themselves away and read code alone all day. We need to be as efficient as possible in knowledge sharing in order to keep the code generation rate high. Must be able to manage time efficiently among multiple projects. These tech requirements should be implicit in the criteria above, but nonetheless are imperative: OO design SQL including indexing and query tuning AJAX, including APIs like Google Maps RSS and XML feeds in general. We deal with a lot of third party feeds that love to use XML. DHTML with CSS and Javascript Working knowledge of subversion, including branching and merging Must be able to configure a LAMP development environment (If you can do one, you can do them all. In our case "LAMP" means FreeBSD, Apache, MySQL, Webware for Python) Please contact: timothy.brian14 at gmail.com From carsten at uniqsys.com Tue Mar 11 10:01:34 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 11 Mar 2008 10:01:34 -0400 Subject: difference b/t dictionary{} and anydbm - they seem the same In-Reply-To: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> References: <45e2e8b7-868e-4013-ac98-017c5e698d6a@q78g2000hsh.googlegroups.com> Message-ID: <1205244094.3430.20.camel@dot.uniqsys.com> On Tue, 2008-03-11 at 06:49 -0700, davidj411 wrote: > anydbm and dictionary{} seem like they both have a single key and key > value. > Can't you put more information into a DBM file or link tables? I just > don't see the benefit except for the persistent storage. Persistent storage /is/ the benefit. If you want to store relational data, you should use a relational database. -- Carsten Haese http://informixdb.sourceforge.net From rtw at freenet.co.uk Mon Mar 24 16:37:18 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 24 Mar 2008 15:37:18 -0500 Subject: encoding/decoding issue with python2.5 and pymssql References: <3a6c32fe-e7c1-4230-882d-efb3415196c1@b1g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote in news:3a6c32fe-e7c1-4230-882d-efb3415196c1 @b1g2000hsg.googlegroups.com in comp.lang.python: > for example: > the value > 'EE604EE3-4AB0-4EE7-AF4D-018124393CD7' > is represent as > '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7' > from uuid import * u = UUID( bytes = '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7') print u u = UUID( bytes_le = '\xe3N`\xee\xb0J\xe7N\xafM\x01\x81$9<\xd7') print u The "bytes_le" version prints: ee604ee3-4ab0-4ee7-af4d-018124393cd7 so I guess, this is what mysql is returning. http://docs.python.org/lib/module-uuid.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From george.sakkis at gmail.com Mon Mar 31 15:05:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 31 Mar 2008 12:05:42 -0700 (PDT) Subject: troll poll References: <65cmaqF2fhuoaU1@mid.uni-berlin.de> Message-ID: On Mar 31, 1:46 pm, Marc 'BlackJack' Rintsch wrote: > > More specifically, who can create a bigger mess on c.l.py? (check one) > > > [ ] - Xah Lee > > [X] - castironpi > > Xah Lee's postings might be trolls but sometimes they spark some really > interesting and serious subthreads, while the nonsense of castironpi is > just irritating noise. Which is exactly why there are rarely any replies to his random gibberish, so I would say that he/she/it has almost no effect on c.l.py. Yet I wish plonking was possible through Google groups. George From jason.scheirer at gmail.com Mon Mar 31 13:35:10 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 31 Mar 2008 10:35:10 -0700 (PDT) Subject: Automatically fill in forms on line References: Message-ID: <772b20d1-a845-480b-a583-cf8ba470ecae@q27g2000prf.googlegroups.com> On Mar 31, 9:50 am, "Jackie Wang" wrote: > Dear all, > > I want to automatically complete the following task: > > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx; > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State > Highway 102"; > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609"; > 4. Click the bottom "search"; > 5. In the opened page, extract and save the number after "Tract Code". > In the example, it will be "9659". > 6. Repeat Step 1 with a new address. > > Can Python realize these steps? Can these steps be done witout > openning and IE windows? Especially, I dont know how to write code for > step 2, 4 and 5. > > Thank you! You may also want to look at the Yahoo! maps API, which will also give you geocoding with a much nicer interface: http://www.yahooapis.com/maps/rest/V1/geocode.html unless you specifically need to use the TeleAtlas data or the API licensing is incompatible with the task at hand, I'd recommend using that instead. From gagsl-py2 at yahoo.com.ar Tue Mar 18 02:00:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 17 Mar 2008 23:00:42 -0700 (PDT) Subject: Cost of Queue.put References: <7d3e817b-6931-4fc5-921c-b2cf2b2400fa@i7g2000prf.googlegroups.com> Message-ID: On 18 mar, 01:13, James wrote: > Basically, what I need is a multi-process safe persistent quick queue. > The arrangement I had was a simple XML-RPC service running on the web > server which the various web server threads POST the relevant search > engine updates to. These updates were added to a persistent queue > built on top of Queue.Queue and cPickle, and there was a separate > thread in the XML-RPC server actually adding the updates to the search > engine. > > However, the CPU consumption of the XML-RPC server seems to grow > pretty much linearly with the length of the persistent queue. Isn't > Queue.put O(1)? Maybe, but pickle.dumps is very likely O(n) and dominates. Why don't you use a database? Just insert and delete records with each get and put. -- Gabriel Genellina From mlists.sgv at gmail.com Thu Mar 6 03:10:22 2008 From: mlists.sgv at gmail.com (Sanjaya Vitharana) Date: Thu, 6 Mar 2008 13:40:22 +0530 Subject: Display all variable/function bindings in Python Shell Message-ID: <16803ed0803060010l64444a76o281411d323284b36@mail.gmail.com> Hi All, New to Python. Have some simple questions as a beginner. 1.) Are there any way to display all variable/function bindings in Python Shell ? 2.) Are the any way to Search "Python-list Archives" before sending simple question to the list ? Regards, Sanjaya Vitharana -------------- next part -------------- An HTML attachment was scrubbed... URL: From corynissen at gmail.com Fri Mar 7 10:45:08 2008 From: corynissen at gmail.com (corynissen at gmail.com) Date: Fri, 7 Mar 2008 07:45:08 -0800 (PST) Subject: problem with join References: <249b0cfb-705d-454c-bf64-5e8663406dea@b64g2000hsa.googlegroups.com> Message-ID: On Mar 7, 9:33 am, corynis... at gmail.com wrote: > On Mar 7, 9:12 am, nodrogbrown wrote: > > > > > hi > > i am using python on WinXP..i have a string 'folder ' that i want to > > join to a set of imagefile names to create complete qualified names so > > that i can create objects out of them > > > folder='F:/brown/code/python/fgrp1' > > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg'] > > filenameslist=[] > > for x in filenms: > > myfile=join(folder,x) > > filenameslist.append(myfile) > > > now when i print the filenameslist i find that it looks like > > > ['F:/brown/code/python/fgrp1\\amber1.jpg', > > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\ > > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg'] > > > is there some problem with the way i use join? why do i get \\ infront > > of the basename? > > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg', > > > can anyone pls help > > gordon > > see path.join in the os library. Upon further examination... it looks like you are using windows and os.path.join. The separator for windows is a '\'. In python, you have to escape that character with another '\'. That's why you see '\\'. That being said, I think what you have will still work to access a file. Windows is usually smart enough to deal with a front slash here and there. From castironpi at gmail.com Sat Mar 8 15:00:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 8 Mar 2008 12:00:30 -0800 (PST) Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> Message-ID: On Mar 8, 1:31?pm, Grant Edwards wrote: > On 2008-03-08, castiro... at gmail.com wrote: > > > Does one side of this hold that there are no -good- comments? > > I wouldn't say there are _no_ good comments, but I would say > that 90+% of the comments I've seen in my lifetime were bad. Limit your comments, in other words. LIM-IT. > comment explaining a particularly opaque algorithm can be > useful as well. But can't the name do that? > at the beginnings of C/C++ functions that do things like tell > you the name and return type of the function and list the names > and types of the parameters. Gee, thanks. ?I never could have > figured that out from looking at the source code itself. IMO, Sometimes void*s are guaranteed to be HTHREADs. > I'm also a bit baffled by people who put a comment at the top > of every file that tells you what the filename is. ?I sometimes > wonder how/where these files were created. All of the OSes I've > ever used had a feature called a "filesystem" which kept track > of info like the names of files. ?It must be a bitch-and-a-half > to work on an computer that doesn't keep track of filenames and > makes the user do it. > > When was the last time you thought to yourself: "Gee, I wonder > what's the the name of that file over there? I guess I'd better > open the file and look at the comment at the top to see what > the filename is? What file did you open? To Lie: > Personally I preferred a code that has chosen good names but have > little or no comments compared to codes that makes bad names and have Personally I don't. Show me a good one. Until you do, it's not that I won't like it, it's that I can't. You know, in linguistics, there's what's called 'code switching', which is switching between two languages you know midstream. People can understand 'hear' a language but not speak it. If you speak it, . If comments aren't the 'short version', then patience is the problem. There's not one word for lots and lots of things. Examples on backorder. Good comments are better than bad names. Good names are better than bad comments. And enter multi-word identifiers. From petr.jakes.tpc at gmail.com Sat Mar 8 14:39:34 2008 From: petr.jakes.tpc at gmail.com (petr.jakes.tpc at gmail.com) Date: Sat, 8 Mar 2008 11:39:34 -0800 (PST) Subject: SQL problem in python References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> Message-ID: Maybe you should try SQLObject :-) from sqlobject import * from sqlobject.sqlbuilder import Select #from sqlobject.sqlbuilder import * from datetime import datetime # =========== sqlite ============================== #connection = connectionForURI('sqlite:///dev/shm/ourdata.db') connection = connectionForURI('sqlite:/:memory:') sqlhub.processConnection = connection class MyTable(SQLObject): album = StringCol(length=20, default=None) filepath = StringCol(length=50, default=None) #MyTable.dropTable(ifExists=True) #MyTable._connection.debug = True # you can switch debuging ON, so you can see SQL commands generated by SQLObject MyTable.createTable(ifNotExists=True) MyTable(album ="Pinkk Floyd", filepath= "qwst" ) MyTable(album ="Pinkk", filepath= "gbfbd" ) MyTable(album ="Floyd", filepath= "fdgf" ) q = MyTable.select() for row in q: print row.album, row.filepath for row in MyTable.select(MyTable.q.album == "Pinkk Floyd"): print row.album, row.filepath HTH Petr Jakes From gherron at islandtraining.com Mon Mar 31 17:14:04 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 31 Mar 2008 14:14:04 -0700 Subject: import multiple modules with same name In-Reply-To: References: Message-ID: <47F1541C.4080602@islandtraining.com> Christian Bird wrote: > Is it possible to import multiple modules with the same name from > different locations? I'm using two different pieces of software, both > of which have a module named util.py. I know that I can modify > sys.path to fix which util gets imported when I do: > > import util > > I'd like to be able to do something like: > > import sys > sys.path.append("/somedir1/") > import util as util1 > sys.path.insert(0, "/somedir2/") > import util as util2 > > But it appears that once python imports a module, it will never look > for a module with the same name again. Is there any way to get around > this? I'd rather not rename either of the util modules as other > pieces of software use them (but the others never use both of them of > course) and I don't want to break them or have multiple copies of the > code in different named files. I'm appreciative of anyone's ideas. > > -- Chris > > If your two "pieces of software" are in fact Python packages (i.e., the directories have files named __init__.py), then you can import each this way: from package1 import util as util1 from package2 import util as util2 If they are not packages, then they should be, and you can make them so by creating empty files named __init__.py in each directory. From tjreedy at udel.edu Tue Mar 25 22:22:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Mar 2008 22:22:34 -0400 Subject: python hash() function References: <7a01f6c00803251905j4b12633m65b2cde0f3037854@mail.gmail.com> Message-ID: "Alvin Delagon" wrote in message news:7a01f6c00803251905j4b12633m65b2cde0f3037854 at mail.gmail.com... | Hello, | | >>> hash("foobar") | -1969371895 | | Anyone can explain to me how the hash() function in python does its work? A | link to its source could help me a lot also. I'm looking for a way to | replicate this function in php. Thanks in advance. If not part of your installation, start with svn.python.org and click browse. I would look for builtins.c or somesuch. From ron at example.com Wed Mar 26 10:28:26 2008 From: ron at example.com (Ron Eggler) Date: Wed, 26 Mar 2008 14:28:26 GMT Subject: last mouse movment or keyboard hit References: Message-ID: Gabriel Genellina wrote: > En Wed, 26 Mar 2008 00:38:08 -0300, Ron Eggler escribi?: > >> I would like to get the time of the most recent human activity like a >> cursor >> movement or a key hit. >> Does anyone know how I can get this back to start some action after there >> has been no activity for X minutes/seconds? > > Which platform? On non-ancient Windows versions, you can periodically > check GetLastInputInfo > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp > > No, it would be for Linux and preferrably it would work on MacOS & Windows as well....is there anything? Thanks! -- chEErs roN From fuzzyman at gmail.com Sun Mar 23 15:25:09 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 23 Mar 2008 12:25:09 -0700 (PDT) Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> Message-ID: <5be24bac-f82a-415e-8ff1-176b87ec06d2@d4g2000prg.googlegroups.com> On Mar 22, 6:40 pm, Jeff Schwab wrote: > jmDesktop wrote: > > For students 9th - 12th grade, with at least Algebra I. Do you think > > Python is a good first programming language for someone with zero > > programming experience? Using Linux and Python for first exposure to > > programming languages and principles. > > Linux and Python are a nearly ideal combination for this. Be aware that > at some point, you will likely have to dig into C, the primary language > used to implement both Linux and Python. I've been using Python for five years and now work full-time as a Python programmer. I've not had to hit C. :-) Michael Foord http://www.ironpythoninaction.com From wolf_tracks at invalid.com Thu Mar 20 23:21:22 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Thu, 20 Mar 2008 20:21:22 -0700 Subject: An Application Program to Play a CD Message-ID: How difficult would it be to write a Python program that would play a specific track on a CD from say 8 am to 6 pm each weekday on a PC's speaker, and switch tracks each day? That is, what library capabilities might be able to do that. Are they already available. Extra points. Now imagine the same as above, but the program should answer a phone and play the track for the day while someone is holding the call, or would be given the option to connect to the operator, say, or listen to the recording? To get a bit specific, our science museum would like to buy the monthly set of StarDate programs. Each program is about 2 minutes long and there's one for every day of the month. There seems to be no such commercial software to automate this process. -- Wayne Watson (Nevada City, CA) Web Page: From castironpi at gmail.com Thu Mar 27 03:35:33 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 27 Mar 2008 00:35:33 -0700 (PDT) Subject: counting using variable length string as base References: <0d2b84b7-efd0-4e53-98da-01ff1d3c6b9e@s8g2000prg.googlegroups.com> Message-ID: <8edb9b4d-a775-4ccb-893d-9b8321e19be1@e39g2000hsf.googlegroups.com> On Mar 27, 2:33?am, Grimsqueaker wrote: > That seems to give me the items in the list back in an iterator. Am I > using it incorrectly? Use list( it ). From inq1ltd at inqvista.com Fri Mar 28 19:43:00 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 28 Mar 2008 19:43:00 -0400 Subject: python program deleted In-Reply-To: References: <200803271808.06157.inq1ltd@inqvista.com> Message-ID: <200803281943.01098.inq1ltd@inqvista.com> thanks for the responses. I put the files in an ftp site and all is well. jim-on-linux From bockman at virgilio.it Mon Mar 24 07:49:19 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 24 Mar 2008 11:49:19 GMT Subject: Pyparsing help References: <97c8a3c9-b544-48f2-968f-310679fb267b@i12g2000prf.googlegroups.com> Message-ID: <47e7953f$0$18153$5fc30a8@news.tiscali.it> Il Sat, 22 Mar 2008 14:11:16 -0700, rh0dium ha scritto: > Hi all, > > I am struggling with parsing the following data: > > test1 = """ > Technology { > name = "gtc" dielectric > = 2.75e-05 unitTimeName > = "ns" timePrecision = 1000 > unitLengthName = "micron" > lengthPrecision = 1000 gridResolution > = 5 > unitVoltageName = "v" voltagePrecision > = 1000000 unitCurrentName = > "ma" currentPrecision = 1000 > unitPowerName = "pw" powerPrecision > = 1000 unitResistanceName = > "kohm" resistancePrecision = 10000000 > unitCapacitanceName = "pf" > capacitancePrecision = 10000000 > unitInductanceName = "nh" > inductancePrecision = 100 > } > > Tile "unit" { > width = 0.22 height > = 1.69 > } > > Did you think of using something a bit more sofisticated than pyparsing? I have had a good experience to using ply, a pure-python implementation of yacc/lex tools, which I used to extract significant data from C programs to automatize documentation. I never used before yacc or similar tools, but having a bit of experience with BNF notation, I found ply easy enough. In my case, the major problem was to cope with yacc limitation in describing C syntax (which I solved by "oelaxing" the rules a bit, since I was going to process only already- compiled C code). In your much simpler case, I'd say that a few production rules should be enough. P.S : there are others, faster and maybe more complete python parser, but as I said ply is pure python: no external libraries and runs everywhere. Ciao ------- FB From ggpolo at gmail.com Sat Mar 29 07:18:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 29 Mar 2008 08:18:23 -0300 Subject: why does socket.makefile require non-blocking mode? In-Reply-To: <21989.75.55.199.5.1206748234.squirrel@webmail.sonic.net> References: <21989.75.55.199.5.1206748234.squirrel@webmail.sonic.net> Message-ID: 2008/3/28, Forest : > The socket.makefile() docs say, "the socket must be in blocking mode." I > don't see any explanation of why blocking mode is required, and I'm not sure > whether that means timeout mode is forbidden as well. Can someone clarify > this? > Have you set your socket to be nonblocking ? Otherwise it is blocking, it is the "normal" one. I don't know why you think timeout is forbidden too, it is not. > I wanted to use file-like objects with socket timeouts, so I ended up writing > my own replacement for socket._fileobject. I'd appreciate it if someone could > either explain to my why my new class was unnecessary, or else encourage me to > contribute it as a patch to the socket module. > It looks like to be unnecessary. > Cheers, > > Forest > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From vpalexander at gmail.com Sun Mar 9 05:57:38 2008 From: vpalexander at gmail.com (Vince) Date: Sun, 9 Mar 2008 01:57:38 -0800 (PST) Subject: gc question References: <95256b22-b404-4f6b-8992-a21edab38476@u10g2000prn.googlegroups.com> <63hq8rF27chv6U1@mid.uni-berlin.de> Message-ID: <96486094-0706-45f1-b5c1-4af6333e3955@s13g2000prd.googlegroups.com> On Mar 9, 1:51 am, Marc 'BlackJack' Rintsch wrote: > On Sun, 09 Mar 2008 01:42:01 -0800, vpalexander wrote: > > I keep seeing destructor calls in wx for ad hoc dialogs and wonder if > > this is required, and if so, why would normal gc flow not be good? > > Because there is no guarantee when `__del__()` is called or if it is > called *at all*. > > Ciao, > Marc 'BlackJack' Rintsch Well, that suits me. The most unnatural thing about Python was adapting to the idea of just letting unreleased resources go jogging off wherever. :) "Where's the f.close?" "You don't need it!" Hmmm! From fetchinson at googlemail.com Thu Mar 20 12:06:58 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 20 Mar 2008 09:06:58 -0700 Subject: pep 3108 Message-ID: Hi Brett, I've just looked through pep 3108 and since Raymond Hettinger suggested contacting you if we "have issues with it", here it goes: I don't think it would be a great idea to move tkinter from the core to a third party library because once that happens we can no longer assume that any GUI library is present on a box with python installed. Of course it's not a big deal to install an extra package but when it comes to distribution customers/friends/family/etc are forced to install the third party package too and that is beyond the control of the developer (are they willing to do it? are they able to do it? do they think it's a hassle?). I've brought up the issue on c.l.p and people seem to agree, please see the thread for additional detail: http://tinyurl.com/2v4mh3 Cheers, Daniel From darcy at druid.net Tue Mar 18 12:41:35 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 18 Mar 2008 12:41:35 -0400 Subject: Need Help Starting Out In-Reply-To: <4aa24daf-4f7b-405e-83c2-d1face854ed1@s37g2000prg.googlegroups.com> References: <125ee5fb-9a1d-4cd1-a45f-132bf3c806ea@x41g2000hsb.googlegroups.com> <4aa24daf-4f7b-405e-83c2-d1face854ed1@s37g2000prg.googlegroups.com> Message-ID: <20080318124135.7d170210.darcy@druid.net> On Tue, 18 Mar 2008 09:27:46 -0700 (PDT) rodmc wrote: > > > Hi, I would like to start using Python, but am unsure where to begin. > > I know how to look up a tutorial and learn the language, but not what > > all technologies to use. I saw references to plain Python, Django, > > and other things. > > Hi, > > For database stuff you can plug directly into either MySQL or SQLite. Or PostgreSQL. > For MySQL you need to install a third party library which you can get > from: > > http://sourceforge.net/projects/mysql-python And there are many interfaces for PostgreSQL including PyGreSQL which I maintain at http://PyGreSQL.org/ > Hope these help you get started... And don't forget the tutorial on the Python web site. -- 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 bearophileHUGS at lycos.com Tue Mar 4 16:08:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 4 Mar 2008 13:08:13 -0800 (PST) Subject: sympy: what's wrong with this picture? References: <6bbf46ef-5635-4e74-bdea-38567d4662a9@s12g2000prg.googlegroups.com> <99c941a8-b206-45ec-b13e-0e5ad1c6bc43@i12g2000prf.googlegroups.com> <71c1b33c-5fbd-499c-b3a2-034ffb99a831@e25g2000prg.googlegroups.com> <2ecbb96f-c246-48c5-836f-bf934ac56ba6@e25g2000prg.googlegroups.com> Message-ID: <7379aaf9-53b7-4258-b54d-b9753a007144@n36g2000hse.googlegroups.com> apatheticagnostic: > I swear, this is one of the most polite-oriented groups I've ever > seen. > Not that that's a bad thing or anything, it's nice to be nice. Yep, and with lot more work it may even become a bit fit for women/ females too. Bye, bearophile From maciej.blizinski at gmail.com Tue Mar 18 00:20:01 2008 From: maciej.blizinski at gmail.com (=?ISO-8859-2?Q?Maciej_Blizi=F1ski?=) Date: Mon, 17 Mar 2008 21:20:01 -0700 (PDT) Subject: urllib2.unquote() vs unicode Message-ID: <9b79a441-aa7a-4e4c-8ec6-337893c330ba@n77g2000hse.googlegroups.com> I've been hit by a urllib2.unquote() issue. Consider the following unit test: import unittest import urllib2 class UnquoteUnitTest(unittest.TestCase): def setUp(self): self.utxt = u'%C4%99' self.stxt = '%C4%99' def testEq(self): self.assertEqual( self.utxt, self.stxt) def testStrEq(self): self.assertEqual( str(self.utxt), str(self.stxt)) def testUnicodeEq(self): self.assertEqual( unicode(self.utxt), unicode(self.stxt)) def testUnquote(self): self.assertEqual( urllib2.unquote(self.utxt), urllib2.unquote(self.stxt)) def testUnquoteStr(self): self.assertEqual( urllib2.unquote(str(self.utxt)), urllib2.unquote(str(self.stxt))) def testUnquoteUnicode(self): self.assertEqual( urllib2.unquote(unicode(self.utxt)), urllib2.unquote(unicode(self.stxt))) if __name__ == '__main__': unittest.main() The three testEq*() tests positively confirm that the two are equal, they are the same, they are also the same if cast both to str or unicode. Tests with unquote() called with utxt and stxt cast into str or unicode are also successful. However... ...E.. ====================================================================== ERROR: testUnquote (__main__.UnquoteUnitTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "unquote.py", line 28, in testUnquote urllib2.unquote(self.stxt)) File "/usr/lib/python2.4/unittest.py", line 332, in failUnlessEqual if not first == second: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) ---------------------------------------------------------------------- Ran 6 tests in 0.001s FAILED (errors=1) Why does this test fail while others are successful? Any ideas? Regards, Maciej From gagsl-py2 at yahoo.com.ar Thu Mar 6 18:17:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 06 Mar 2008 21:17:49 -0200 Subject: Classes and modules are singletons? References: <13suj3u2d17f205@corp.supernews.com> <13sulsu4nbr2199@corp.supernews.com> <7817aa43-0f4d-4ace-9279-8e1fbdf2640d@b1g2000hsg.googlegroups.com> Message-ID: En Thu, 06 Mar 2008 20:45:09 -0200, escribi?: > I'd like to question the source of the definition of C.__eq__. > > Observation: > >>>> class C: pass > ... >>>> class D: pass > ... >>>> C== D > False > > What is different about them? I've created two empty classes, nothing > more. Their __name__ attribute? Types are compared by their memory addresses, not by contents, and that's enough and efficient for most people. If you require something different, use a metaclass. -- Gabriel Genellina From carsten at uniqsys.com Sat Mar 8 13:38:08 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 08 Mar 2008 13:38:08 -0500 Subject: SQL problem in python In-Reply-To: <13t5lm9lva8ji7a@corp.supernews.com> References: <333a1560-3137-4e75-a192-efb22ac84efb@59g2000hsb.googlegroups.com> <15f2175c-9d48-47c9-8499-889923004aee@x30g2000hsd.googlegroups.com> <13t5lm9lva8ji7a@corp.supernews.com> Message-ID: <1205001488.3161.24.camel@localhost.localdomain> On Sat, 2008-03-08 at 10:11 -0800, Dennis Lee Bieber wrote: > On Sat, 8 Mar 2008 09:28:23 -0800 (PST), aiwarrior > declaimed the following in comp.lang.python: > > > Thanks a lot. > > In the Python documentation, the sqlite module documentation doesn't > > mention that special rule. I really thought that every variable to be > > included in a query had to use that special method. > > > It's not sqlite specific -- it is common to all of the db-api > compatible adapters. > > The explanation for why you were getting 'filename' (or whatever the > field was is: parameter substitution ensures that the parameter value is > properly quoted and escaped to be safe for use as a value. It's called "parameter binding", not "parameter substitution". Parameter binding ensures that the value is passed to the database safely. That need not necessarily be a quoting-and-escaping exercise. Depending on the API module, it may use a mechanism that transmits the query string and the parameters to the database engine separately. Also note that SQL standard doesn't even allow parameters in the projection clause of a select statement. SQLite is just more relaxed about the standard than for example Informix: >>> import informixdb >>> conn = informixdb.connect("stores_demo") >>> cur = conn.cursor() >>> cur.execute("select ? from customer", ("customer_num",) ) Traceback (most recent call last): File "", line 1, in _informixdb.ProgrammingError: SQLCODE -201 in PREPARE: 42000: Syntax error or access violation -- Carsten Haese http://informixdb.sourceforge.net From pavlovevidence at gmail.com Thu Mar 6 10:58:06 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 6 Mar 2008 07:58:06 -0800 (PST) Subject: Identifying messages in a thread (was: Please keep the full address) References: <8763w094sy.fsf_-_@benfinney.id.au> Message-ID: <0999d4fd-ccbe-47a3-95cd-9cab8b1a1f11@d62g2000hsf.googlegroups.com> On Mar 5, 8:11 pm, "D'Arcy J.M. Cain" wrote: > On Thu, 06 Mar 2008 09:36:29 +1100 > > Ben Finney wrote: > > > Those of us who identify the time wasters would also like to drop > > > the responses to their posts and changing the address makes this > > > impossible. > > > Not at all. AFAIK the messages from Google mail correctly include the > > 'In-Reply-To' field or the 'References' field in the message header. > > So, you can know by those fields whether a message is part of a thread > > you've previously identified. > > I don't want to have to tag every thread. I just want to *plonk* > certain posters. > > Anyway, I'll live with Google's failings I guess. Sounds like you need better filtering. A decent news filter should be able not only kill a poster, but also all followups to that poster recursively. (No, I don't know of any that do that either.) Carl Banks From Krishna.00.K at gmail.com Thu Mar 6 19:48:42 2008 From: Krishna.00.K at gmail.com (Krishna) Date: Thu, 6 Mar 2008 16:48:42 -0800 (PST) Subject: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments Message-ID: >>> class Test(object): ... def __init__(self): ... self.a= 2 ... def func(self, k = self.a): ... print k ... Traceback (most recent call last): File "", line 1, in ? File "", line 4, in Test NameError: name 'self' is not defined >>> In the 'definition of the class', what would the first argument 'self' in the methods evaluate to; when we have an object defined, it is bound to the object reference, but what happens while the class definition is executed, which I believe happens when the module containing the class definition is imported Thanks, Kr From Minor.Gordon at cl.cam.ac.uk Tue Mar 25 16:37:21 2008 From: Minor.Gordon at cl.cam.ac.uk (Minor Gordon) Date: Tue, 25 Mar 2008 20:37:21 +0000 Subject: [Fwd: Beta testers needed for a high performance Python application server] Message-ID: <47E96281.5000304@cl.cam.ac.uk> One thing I forgot to add: the code is GPLv2, though I'll consider alternative licenses for specific users. -------- Original Message -------- Subject: Beta testers needed for a high performance Python application server Date: Tue, 25 Mar 2008 20:31:39 +0000 From: Minor Gordon To: python-list at python.org Hello all, I'm looking for beta testers for a high performance, event-driven Python application server I've developed. About the server: the front end and other speed-critical parts of the server are written in portable, multithreaded C++. The back end is an embedded CPython interpreter. The server is much faster than anything in pure Python, and it can compete with C servers (including e.g. lighttpd for file workloads) or outdo them (e.g. anything behind Apache) until CPython consumes a single processor. On the Python side it supports WSGI (the server can handle the static and dynamic requests of MoinMoin with a handful of lines), the DB API with blocking calls offloaded to a connection in a separate thread (MySQL, SQLite supported), Google's ctemplate, gzipping responses, file caching, reading and writing to URIs as a client, AJAX integration, debugging as a Python extension, and a lot of other features. The core Python API is event-driven, using continuations like Twisted but much cleaner (continuations are any callables, there are no special objects anywhere). The Python back end also supports Stackless Python so all of the continuation machinery can be hidden behind tasklet switching. Background: I'm in this to help write a "story" for Python and web applications. Everyone likes to go on about Ruby on Rails, and as far as I can tell there's nothing that approaches Rails in Python. I want to code quickly in Python like I can with Rails, but without sacrificing single node performance on many cores. Beta testers: should be intermediate to advanced Python programmers with demanding applications, particularly web applications with databases and AJAX. The C++ is portable to Win32, Linux, and OS X, with no mandatory libraries beyond python-dev. Please contact me if you're interested: firstname.lastname at cl.cam.ac.uk. Minor From __peter__ at web.de Fri Mar 7 02:35:39 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Mar 2008 08:35:39 +0100 Subject: Ncurses not found - embedded linux References: <63b1rjF26p2fkU1@mid.uni-berlin.de> <754dad0b-9d3e-4ca7-a5fc-38519312947f@q78g2000hsh.googlegroups.com> Message-ID: blaine wrote: >> > I hope this is trivial, and I apologize ahead of time if so. Would >> > this perhaps be a compilation issue? Something we have to turn on in >> > the python compile? >> >> Usually, you need not only the libraries but also the headers at >> compilation time. Most probably these were missing. >> >> Diez > > Thank you for our response. Do you mean that the ncurses header > should be in /usr/include upon compilation of python? Will python > automatically pick up on these headers, or would I need to change > compilation options? Thanks! -Blaine Just rerun the ./configure script -- it should detect the presence of the required header file automatically. If all went well you'll see "yes" three times: $ sudo aptitude install ncurses-dev [...] $ ./configure > tmp.txt [...] $ grep ncurses tmp.txt checking ncurses.h usability... yes checking ncurses.h presence... yes checking for ncurses.h... yes Peter From miki.tebeka at gmail.com Tue Mar 11 13:18:04 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 11 Mar 2008 10:18:04 -0700 (PDT) Subject: Exctract GIF comment from image References: <1f45e323-6654-4640-85ac-87eac9d9da08@8g2000hse.googlegroups.com> Message-ID: Hello Wingi, > simple question: The PIL does not support reading the optional > description in GIF Images. > > http://www.pythonware.com/library/pil/handbook/format-gif.htm > > After some reasearch I could not find a python solution for this, any > suggestions? Use ImageMagick (www.imagemagick.org), "identify -verbose " should have the comments somewhere in the output. There also a python binding to ImageMagick but I have no experience with it. HTH, -- Miki http://pythonwise.blogspot.com From kmgrds at gmail.com Mon Mar 31 14:52:11 2008 From: kmgrds at gmail.com (kim) Date: Mon, 31 Mar 2008 11:52:11 -0700 (PDT) Subject: Creating a python c-module: passing double arrays to c functions. segmentation fault. swig References: <8cfe6116-2e79-4940-b2cf-fba5cfe5df7d@b5g2000pri.googlegroups.com> Message-ID: <09a0fafc-5658-470a-87a4-8b906caab5ed@e6g2000prf.googlegroups.com> thanks a lot, sturlamolden, for the quick reply! so i tried to use numpy and ctypes as you advised and i got it working: with some little changes for my linux machine - i hope they aren't the cause of the results: to load it, i only got it going with LoadLibrary: lib = numpy.ctypeslib.load_library("_timewarpsimple.so",".") _timewarp = lib.timewarp i replaced double by c_double: array_pointer_t = ndpointer(dtype=c_double) and i needed to define a restype, too: _timewarp.restype = c_double so, the strange errors with lots of stack traces are gone, but for large lists i got the same problem: Segmentation fault. for example for the following two lines: list1,list2 = numpy.array([0.1 for i in range(999)]), numpy.array([0.7 for i in range(1041)]) print timewarp(list1,list2) So it is maybe more of a c problem, but still, if i copy the big arrays into my c code, everything works out just fine (x[]={0.1,0.1,... }...) so it may still have something to do with the python-c interface and memory allocation or something like that. below i put my new shorter python script, the c and the rest hasn't changed. what can i try now? thanks again kim import numpy import ctypes from numpy.ctypeslib import ndpointer from ctypes import c_int,c_double lib = numpy.ctypeslib.load_library("_timewarpsimple.so",".") _timewarp = lib.timewarp #_timewarp = ctypes.cdll.timewarp.timewarp # timewarp.dll array_pointer_t = ndpointer(dtype=c_double) _timewarp.argtypes = [array_pointer_t, c_int, array_pointer_t, c_int] _timewarp.restype = c_double def timewarp(x, y): lenx, leny = x.shape[0], y.shape[0] print lenx,leny return _timewarp(x, lenx, y, leny) # testing: list1,list2 = numpy.array([0.1 for i in range(999)]), numpy.array([0.7 for i in range(1041)]) print timewarp(list1,list2) for x in range(999,1111): for y in range(999,1111): list1,list2 = [0.1 for i in range(x)], [0.9 for i in range(y)] print len(list1),len(list2),len(list1)+len(list2) list1,list2 = numpy.array(list1), numpy.array(list2) print timewarp(list1,list2) On Mar 30, 10:56 pm, sturlamolden wrote: > On 30 Mar, 22:21, kmg... at gmail.com wrote: > > > Hello everybody, > > > I'm building a python module to do some heavy computation in C (for > > dynamic time warp distance computation). > > Why don't you just ctypes and NumPy arrays instead? > > # double timewarp(double x[], int lenx, double y[], int leny); > > import numpy > import ctypes > from numpy.ctypeslib import ndpointer > from ctypes import c_int > > _timewarp = ctypes.cdll.timewarp.timewarp # timewarp.dll > array_pointer_t = ndpointer(dtype=double) > _timewarp.argtypes = [array_pointer_t, c_int, array_pointer_t, c_int] > > def timewarp(x, y): > lenx, leny = x.shape[0], y.shape[0] > return _timewarp(x, lenx, y, leny) From anthonysmith80 at gmail.com Tue Mar 25 10:03:35 2008 From: anthonysmith80 at gmail.com (Anthony) Date: Tue, 25 Mar 2008 07:03:35 -0700 (PDT) Subject: Inheritance question References: <03b9eb90-2822-47ce-b755-61f15da3bdf3@s12g2000prg.googlegroups.com> Message-ID: On Mar 25, 11:44 am, Tzury Bar Yochay wrote: > While my intention is to get 1.2 I get 2.2 > I would like to know what would be the right way to yield the expected > results Is this what you want? class Foo(object): def __init__(self): self.id = 1 def getid(self): return self.id class FooSon(Foo): def __init__(self): Foo.__init__(self) self.id = 2 def getid(self): a = Foo().getid() b = self.id return '%d.%d' % (a,b) >>> FooSon().getid() '1.2' Best wishes, Anthony From pavlovevidence at gmail.com Fri Mar 7 17:33:20 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 7 Mar 2008 14:33:20 -0800 (PST) Subject: Intelligent Date & Time parsing References: <0f6d883d-9047-447e-9251-dd0e03060f22@m36g2000hse.googlegroups.com> Message-ID: <16db6135-a8eb-432f-9b50-91efe65e2b3b@13g2000hsb.googlegroups.com> On Mar 7, 5:08 pm, shak... at gmail.com wrote: > I'm new to python and I was wondering if there are any intelligent > date/time parsing modules out there. I've looked at strptime (or > whichever it is) and mxDateTime from the eGenix package. I need > something to parse user input for a django app, and it's awesome to be > able to write "last monday", "a year ago", or "10pm tuesday" like > PHP's strtotime. > > So are there any modules that allow for that kind of parsing? GNU date can do a lot of these things--if your Django server is running Linux it probably has GNU date installed. (Might not be practical to start a new process in the middle of a query, especially a lot of them.) >From a shell command line, get the current time (in seconds since epoch, which you can pass to Python time functions) this way: date +"%s.%N" And you can enter all sort of relative and absolute date strings: date +"%s.%N" --date='last monday' date +"%s.%N" --date='a year ago' date +"%s.%N" --date='10pm tuesday' These all apparently work. Now all you have to do is call it from Python using subprocess module and you're set. (DO NOT use os.system for this since it starts a shell process, which is unnecessarily slow, and dangerous when passed user input.) Carl Banks From rockxuan at gmail.com Tue Mar 18 03:41:15 2008 From: rockxuan at gmail.com (rockxuan at gmail.com) Date: Tue, 18 Mar 2008 00:41:15 -0700 (PDT) Subject: Movado Valeto Watches Replica - Movado Watches Cheap References: Message-ID: <8ec1f9b0-e740-475c-9d1a-61e8c2c27fd6@i12g2000prf.googlegroups.com> Our company www.51cntrade.com is one professional manufacturer specialized in wrist watches. We supply many kinds of watches such as Rolex, Omega, Breitling, Panerai, Cartier, TAG Heuer and more than 22 brands.And for fashion jewelry,we can supply Tiffany & co, Gucci and Dior etc,all of them are made of 100% 925 sterling sliver. We have the professional makers and strict checking process, in order to ensure the products are in the high quality. We provide the high-grade products and service but the prices are the most competitive. We have below advantages: 1. Replicas have 99% similar to the genuine one, Manufactory Price & Top quality, 2. Packing with same name box for watches. 3. Warranted for 1 year. Resend for free if broken!!! 4. Consignment by air, UPS / TNT / EMS / DHL. Safe and Efficiency!!!! 5. Dropshipoing is available, 6. Favorable wholesale policy, 7. Account to Minimum order, Shipping Free!!! 8. Volume goods on hand. Send out at anytime. If you have anything interest, please do not hesitate to contact me, Please let us know if we may be of further assistance, and we are looking forward to your specific enquiry. Replica watches, fake watches,replica rolex Imitation watches , clone watches,designer watches Tiffany & co , replica tiffany, tiffany replicas, fake tiffany Tiffany wholesale, tiffany replicas wholesale ,fake tiffany wholesale http://www.51cntrade.com/ http://www.51cntrade.com/productshopxp.asp?id=582 http://www.51cntrade.com/productshopxp.asp?id=724 http://www.51cntrade.com/productshopxp.asp?id=1070 http://www.51cntrade.com/productshopxp.asp?id=1107 http://www.51cntrade.com/productshopxp.asp?id=1114http://www.51cntrade.com/xpCatalog_xpsmall_Desc.asp?action_key_order=small&shopxpbe_id=102&shopxpse_id=691 http://www.51cntrade.com/xpCatalog_xpDesc.asp?action_key_order=big&shopxpbe_id=105 If you are interested in any of our products,just contact us freely : Website: www.51cntrade.com MSN: Rock at 51cntrade.com Email: Rock at 51cntrade.com From deets at nospam.web.de Sun Mar 2 09:54:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Mar 2008 15:54:01 +0100 Subject: tcp In-Reply-To: References: <284702f7-bcab-47e8-914f-d71ac6467d26@n58g2000hsf.googlegroups.com> Message-ID: <62vtc9F1q1kebU1@mid.uni-berlin.de> Gif schrieb: > you could at least check before posting. as i said i've tried like > 1000 ways of doing that, and im so desparate that i'm thinking of > quiting python. This damn thing just doesnt work. when i do as you > post the server never even replies, as it tends to accept connections > all the time. > > anyone has a better idea? http://www.catb.org/~esr/faqs/smart-questions.html Nobody here knows what you did - post code & stacktraces of at least one of your "1000 ways". Or quit python and try a language that is more friendly to reading your mind instead requiring you to spell out things in a computer readable way. You might need to hibernate a couple of centuries though until it's sufficient to open notepad and write "I'm a ubercool programmer, do make me the application of my dreams". DIEZ From steve at REMOVE-THIS-cybersource.com.au Sat Mar 8 21:30:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 09 Mar 2008 02:30:58 -0000 Subject: Arbitrary precision integer arithmetic: ceiling? References: <7xhcfg94r8.fsf@ruckus.brouhaha.com> <13t6gf5on1qnhbe@corp.supernews.com> Message-ID: <13t6iv2b9oeq6a6@corp.supernews.com> On Sun, 09 Mar 2008 01:48:21 +0000, Steven D'Aprano wrote: > (And the ease that these mistakes can happen is why such fundamental > functions should be in the standard library, no matter how easy they are > to implement.) Which, of course, they are. math.ceil() and math.floor() I knew that. *cough* -- Steven From Sandipan at gangopadhyay.com Sat Mar 15 08:24:55 2008 From: Sandipan at gangopadhyay.com (Sandipan Gangopadhyay) Date: Sat, 15 Mar 2008 08:24:55 -0400 Subject: Python for BlackBerry In-Reply-To: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> Message-ID: <0e8501c88697$9499a4e0$bdcceea0$@com> Is there a Python for BlackBerry? Thanks. -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of E-Lo Sent: Saturday, March 15, 2008 6:03 AM To: python-list at python.org Subject: Python for Palm OS Is there any other edition of Python for Palm OS instead of Pippy? -- http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Mon Mar 10 01:48:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 9 Mar 2008 22:48:07 -0700 (PDT) Subject: How to factor using Python? References: <92d43859-0fde-4150-b341-6f855c6b8553@13g2000hsb.googlegroups.com> Message-ID: On 10 mar, 02:08, Nathan Pinno wrote: > How do I factor a number? I mean how do I translate x! into proper > Python code, so that it will always do the correct math? Do you want to compute x! (factorial of x)? That is, you want a program that given a 4, returns 24? Think how would you compute it by hand and try to write the same thing using Python instructions. If you come with a program and have a specific problem someone here will be able to help you, but don't expect your homework to be done for free... -- Gabriel Genellina From NO_Kroeger at gmx.de Mon Mar 3 08:53:06 2008 From: NO_Kroeger at gmx.de (=?UTF-8?B?TmlscyBPbGl2ZXIgS3LDtmdlcg==?=) Date: Mon, 03 Mar 2008 14:53:06 +0100 Subject: Cant run application as ./myapp.py In-Reply-To: <00ec01c87d2b$11f4f0f0$35ded2d0$@rawlins@thinkbluemedia.co.uk> References: <00ec01c87d2b$11f4f0f0$35ded2d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <47CC02C2.8040901@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Robert, I have to guesses: a) The user as which you are trying to run the script is missing the execute right -> fix by chmod u+x MyApplication.px b) You did not specify the interpreter -> the first line of your script should look something like #!/usr/bin/python If none of this is the problem please post the error message you (hopefully) get. hth Nils Robert Rawlins schrieb: > Hello Guys, > > > > I?ve got an application here which for some reason won?t start using the > following syntax from the command line: > > > > Cd /mydirectory > > ./MyApplication.py > > > > I have to run this as a fully qualified python launch such as: > > > > Cd /mydirectory > > python MyApplication.py > > > > This is a little bit confusing to me as I have other applications which > run just fine using the ./somthing.py syntax. Is there any reason why > this doesn?t work? > > > > Cheers, > > > > Robert > -----BEGIN PGP SIGNATURE----- iD8DBQFHzALBzvGJy8WEGTcRAtE8AJ4jGFTjZ8G8ayZM2AUcLcArnF5d1QCdH0gj kCdp0414HwPaIMIDv/SSTZA= =tF3K -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: NO_Kroeger.vcf Type: text/x-vcard Size: 162 bytes Desc: not available URL: From grante at visi.com Sat Mar 8 10:31:56 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 08 Mar 2008 15:31:56 -0000 Subject: Regarding coding style References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> Message-ID: <13t5cbcrhtfsrd2@corp.supernews.com> On 2008-03-08, dave_mikesell at fastmail.fm wrote: >> The function name also doesn't explain anything. How was the stuff got? >> Was it paid for, or stolen, or picked up on consignment, or what? Compare >> the above line with: >> >> x = get_stuff(store) # Steal stuff from the store. >> >> or >> >> x = get_stuff(store) # Pickup the stuff from the store for disposal. >> # The amount paid by the store is stored in global variable "pay_received" >> # and the name of the employee authorizing the pickup is stored in the >> # global "authorized_by". > > Shouldn't get_stuff's comment be with its definition? Probably, but better that comment shouldn't be anywhere. get_stuff() should be 1) renamed, as you state below. 2) written such that it's obvious from reading the source code that the amount paid is stored in the global variable pay_received and that the name of the employee authorizing the pickup is stored in the global authorized by. But, it's not really fare picking on an example like that... > And just rename the function to something more meaningful, > like purchase_goods(store), or whatever. >> But even if you were right that the comment was unnecessary, >> you have missed my point that even single sentences can be >> grammatically bogus and the writer could learn a lot from >> Strunk and White or equivalent. That's true. I don't know how many times I've seen a single sentence comment that was just plain vague and ambiguous. And most of the time they're just plain wrong as well because the code had been changed but nobody changed the comment (possibly because they couldn't understand what the comment was trying to say). -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From schiz at lon.don Sat Mar 1 09:39:48 2008 From: schiz at lon.don (Schizoid Man) Date: Sat, 01 Mar 2008 14:39:48 +0000 Subject: Beginner's assignment question Message-ID: As in variable assignment, not homework assignment! :) I understand the first line but not the second of the following code: a, b = 0, 1 a, b = b, a + b In the first line a is assigned 0 and b is assigned 1 simultaneously. However what is the sequence of operation in the second statement? I;m confused due to the inter-dependence of the variables. From hdante at gmail.com Sun Mar 30 17:18:44 2008 From: hdante at gmail.com (hdante) Date: Sun, 30 Mar 2008 14:18:44 -0700 (PDT) Subject: Why prefer != over <> for Python 3.0? References: <5805ee5f-970f-4b16-a5c5-90ebe0748feb@y21g2000hsf.googlegroups.com> <8b05b5f4-b228-4782-97b0-ea0903ce8095@l42g2000hsc.googlegroups.com> Message-ID: <2f475146-3489-49b6-9ba9-3d27d297f095@d62g2000hsf.googlegroups.com> On Mar 30, 3:14 pm, Lie wrote: > On Mar 30, 12:11 pm, hdante wrote: > (snip) > > > BTW, my opinion is that it's already time that programmer editors > > have input methods advanced enough for generating this: > > > if x ? 0: > > ?y ? s: > > if y ? 0: f1(y) > > else: f2(y) > > That would be a nightmare. > > Programming language (or most computer-based texts) should only use > basic ASCII characters, except if it can't be helped since typing non- I completely disagree. Unicode should be used whenever the architecture doesn't have memory restrictions. For general (plain-)text there's no sense in talking about ASCII. The only language that "fits" in it that I can remember is Latin. > ASCII characters is still unreliable. It'd also be a headache to > memorize what keyboard combinations to use to type a character. Not to You'd have to memorize, for example "!=" and ">=". > mention how much more complex would the keyboard design be. Also not The keyboard would be the same. > mentioning how much more complex the language design would be to > handle all those non-ASCII characters. Wrong. From arnodel at googlemail.com Mon Mar 10 18:10:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 10 Mar 2008 15:10:03 -0700 (PDT) Subject: List as FIFO in for loop References: <285e1cec-ecc9-4a43-8a73-6af440d1a5fc@34g2000hsz.googlegroups.com> Message-ID: <8c4045ba-19eb-46ba-87bc-32d0d623f27d@x41g2000hsb.googlegroups.com> On Mar 8, 2:43?pm, malkarouri wrote: > Hi everyone, > > I have an algorithm in which I need to use a loop over a queue on > which I push values within the loop, sort of: > > while not(q.empty()): > ? ? x = q.get() > ? ? #process x to get zero or more y's > ? ? #for each y: > ? ? q.put(y) > > The easiest thing I can do is use a list as a queue and a normal for > loop: > > q = [a, b, c] > > for x in q: > ? ? #process x to get zero or more y's > ? ? q.append(y) > > It makes me feel kind of uncomfortable, though it seems to work. The > question is: is it guaranteed to work, or does Python expect that you > wouldn't change the list in the loop? > > Regards, > > Muhammad Alkarouri You could make it safe this way ('emulating' what a listiterator object does in CPython): >>> from itertools import count >>> def index_iter(l): ... try: ... for i in count(): yield l[i] ... except IndexError: ... return ... >>> l = list('SPAM') >>> for c in index_iter(l): ... if c == 'A': l += list(' EGGS') ... if c == 'S': l += list(' NI') ... >>> ''.join(l) 'SPAM NI EGGS NI' >>> Of course in practice this is no different from doing 'for c in l:...' but it is safe against implementation changes. -- Arnaud From rehn at iwm.mw.tu-dresden.de Wed Mar 12 11:22:19 2008 From: rehn at iwm.mw.tu-dresden.de (rehn at iwm.mw.tu-dresden.de) Date: Wed, 12 Mar 2008 08:22:19 -0700 (PDT) Subject: ValueError in pickle module during unpickling a infinite float (python 2.5.2) Message-ID: <4b9d0896-df9c-47b6-98b6-16f825d67975@i7g2000prf.googlegroups.com> Unpickling an infinite float caused a ValueError in the pickle module. I need to pickle and load infinite floats in my project. Do you have any suggestions how to solve the issue? # code describing the issue: # define float constants with double-precision: # copied from fpconst module: http://www.analytics.washington.edu/statcomp/projects/rzope/fpconst/ import struct _big_endian = struct.pack('i',1)[0] != '\x01' # check endianess if(_big_endian): # and define appropriate constants NaN = struct.unpack('d', '\x7F\xF8\x00\x00\x00\x00\x00\x00')[0] PosInf = struct.unpack('d', '\x7F\xF0\x00\x00\x00\x00\x00\x00')[0] NegInf = -PosInf else: NaN = struct.unpack('d', '\x00\x00\x00\x00\x00\x00\xf8\xff')[0] PosInf = struct.unpack('d', '\x00\x00\x00\x00\x00\x00\xf0\x7f')[0] NegInf = -PosInf # pickling and unpickling a infinite float: f = PosInf p = pickle.dumps(f) rf = pickle.loads(p) print f print rf # ValueError in python 2.5.2: Traceback (most recent call last): File "....py", line 89, in rf = pickle.loads(p) File "...\pickle.py", line 1374, in loads return Unpickler(file).load() File "...\pickle.py", line 858, in load dispatch[key](self) File "...\pickle.py", line 954, in load_float self.append(float(self.readline()[:-1])) ValueError: invalid literal for float(): 1.#INF From cwitts at gmail.com Wed Mar 12 07:17:49 2008 From: cwitts at gmail.com (Chris) Date: Wed, 12 Mar 2008 04:17:49 -0700 (PDT) Subject: Creating a file with $SIZE References: Message-ID: <8ab93287-ac21-4b90-8010-cd88967e0743@p25g2000hsf.googlegroups.com> On Mar 12, 12:52?pm, Chris wrote: > On Mar 12, 12:32?pm, "k.i.n.g." wrote: > > > Hi All, > > > I would like create files of different size, taking size as user > > input. I need to check the data transfer rates from one network to > > another . In order to do this I will have to create files of diff size > > and work out. I am new to Python > > > Thanks in advance. > > > KK > > Welcome to Python. > > If you just want to create files with random junk from the user input > then maybe something along these lines would help: > > import sys, random > > def random_junk(number_of_characters): > ? ? tmp = [] > ? ? while number_of_characters: > ? ? ? ? tmp.append(random.randint(0, 127)) > ? ? ? ? number_of_characters -= 1 > ? ? return ''.join(map(str,tmp)) > > if len(sys.argv) < 2: > ? ? sys.exit('Usage:python %s filesizes>'%sys.argv[0]) > > for each_argv in sys.argv[1:]: > ? ? output_file = open(each_argv,'wb').write(random_junk(each_argv)) Sorry, meant def random_junk(number_of_characters): tmp = [] while number_of_characters: tmp.append(chr(random.randint(0, 127))) number_of_characters -= 1 return ''.join(tmp) From newsgroup898sfie at 8439.e4ward.com Tue Mar 4 00:34:53 2008 From: newsgroup898sfie at 8439.e4ward.com (Michael Goerz) Date: Tue, 04 Mar 2008 00:34:53 -0500 Subject: 'normal' shell with curses In-Reply-To: <61c6832e-6897-476c-bcfc-448b7c4387df@d21g2000prf.googlegroups.com> References: <633s5lF24prinU1@mid.uni-berlin.de> <61c6832e-6897-476c-bcfc-448b7c4387df@d21g2000prf.googlegroups.com> Message-ID: <6345brF26560uU1@mid.uni-berlin.de> Miki wrote, on 03/03/2008 11:14 PM: > Hello Michael, > >> I'm trying to print out text in color. As far as I know, curses is the >> only way to do that (or not?). > On unix, every XTerm compatible terminal will be able to display color > using escape sequence. > (Like the one you see in the output of 'grep --color') > > See the shameless plug in http://pythonwise.blogspot.com/2008/03/ansiprint.html > The escape sequence approach is definitely interesting and I'd prefer it to curses if I can make it work. However, I ultimately would like to support other terminals than xterm (especially Windows), that I assume have different ANSI codes. So, two questions: What are the most common terminals that differ in the ANSI codes they use, and how can I detect which of those terminals the program is running on? Where can I find out what codes those terminals use for color? Michael. From mmetz at astro.uni-bonn.de Tue Mar 4 10:10:25 2008 From: mmetz at astro.uni-bonn.de (Manuel Metz) Date: Tue, 04 Mar 2008 16:10:25 +0100 Subject: HTTP keep-alive performance Message-ID: <47CD6661.60705@astro.uni-bonn.de> Hi all, I tried to use the HTTP keep-alive (HTTP/1.1) mechanism for an xmlrpc server/client session. This worked fine, after I found out how to fix the client, see: http://mail.python.org/pipermail/python-list/2004-April/256360.html and also http://mail.python.org/pipermail/python-list/2007-May/442541.html Now, as I said, everything seems to work fine -- except: performance got very bad :-( So, I captured the TCP traffic with wireshark (both, server and client are running on the same machine, 'http://localhost', so its not the network). What I found out is the following: The first remote-call is executed very fast. Then the connection is kept open (I verified that it is closed for HTTP/1.0). But when it comes to the second call, the performance gets bad. The TCP ACK package is sent after ~40ms only, which took ~ < 1ms before for the first call, even for HTTP/1.1. Why is that? So this is a sketch of what's going on: client server ---------- ---------- HEADER --> <-- ACK ~1ms CONTENT --> <-- ACK ~1ms <-- HEADER ACK --> ~1ms [...] response is submitted; connection is NOT closed [...] HEADER --> <-- ACK ~40ms CONTENT --> <-- ACK ~1ms <-- HEADER ACK --> ~40ms [...] response data is submitted It's just a rought timeline to show where the bottleneck is. Has anyone any idea why the acknowledgement messages take sooooo long to be sent??? Manuel From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Mar 25 12:40:40 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 25 Mar 2008 17:40:40 +0100 Subject: Breaking the barrier of a broken paradigm... part 1 In-Reply-To: <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> References: <2e8f0164-a31e-4faf-a2ca-eb799b4efdc3@a70g2000hsh.googlegroups.com> <4eea4191-73cc-454f-88c1-96da305563fc@n77g2000hse.googlegroups.com> Message-ID: <47e92b07$0$15563$426a34cc@news.free.fr> john s. a ?crit : > On Mar 24, 9:39 pm, "Ryan Ginstrom" wrote: >>> On Behalf Of john s. >>> import os, sys, string, copy, getopt, linecache >>> from traceback import format_exception >>> #The file we read in... >>> fileHandle = "/etc/passwd" >>> srcFile = open(fileHandle,'r') >>> srcList = srcFile.readlines() >>> #yah, a for loop that "iterates" through the file of "lines" >>> for i in srcList: >>> strUsr = string.split(i,":") Erroneous hungarian notation is Bad(tm). And FWIW, the convention is to use all_lower for variable names. (snip consideration about using str.methods instead of string functions etc...) >> How about for starters: >> >> import os >> >> for line in open("/etc/passwd"): NB : this idiom relies on the VM automatically closing files, which is not garanteed on each and every implementation (IIRC, jython won't do it). This is ok for Q&D throwaway scripts targeting CPython, but should not go into production code. >> user, _pwd = line.split(":") > ^----- Ok this one here we are taking a string spliting it > into to variables... > user gets one (the first) and _pwd gets to hold the > "leftovers"? Quite. user gets the first, _pwd gets the second. If you have more than 2 fields (IOW : more than one ':') in the line, it will raise. If you want to make sure this will still work with more than 2 fields, you can use the optional max_split arg: user, rest = line.split(':', 1) >> user_home = os.path.join("/expirt/home", user) >> >>> try: >>> os.makedirs('usrHome' ) >>> except Exception, e: Better to be as specific as possible wrt/ exceptions you want to handle. Remember that some exceptions are better left alone (hint: sys.exit works by raising an exception...) >>> print e >> if os.path.exists(user_home): > ^----- are(n't) exists and os.path.isadir > interchangable? They're not. If you want to be bulletproof, you'll have to use os.path.isdir *and* handle the case where user_home exists and is not a directory. HTH From gagsl-py2 at yahoo.com.ar Wed Mar 19 19:52:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 19 Mar 2008 20:52:14 -0300 Subject: add new csv line References: Message-ID: En Wed, 19 Mar 2008 13:01:08 -0300, Alexandru Dumitrescu escribi?: > Is there a way to add a new line at the beginning of a *.csv file, > line which contain the name of the columns? Once the file was written? You have to create another file, write the headings, and copy the data from the first one. If you are asking how to do that with a csv.Writer object, just call writerow(list_of_column_names) before writing the data itself. -- Gabriel Genellina From tmp1 at viltersten.com Sat Mar 8 20:04:54 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Sun, 9 Mar 2008 02:04:54 +0100 Subject: SV: SV: SV: Regarding coding style In-Reply-To: References: <63d80bF273nraU1@mid.individual.net> <9206a189-6fe7-4e83-bcd7-7f9f9a557f3c@47g2000hsb.googlegroups.com> <13t462h7vgqo081@corp.supernews.com> <7dc4b9f0-3967-4493-945f-b95ec506769f@m34g2000hsc.googlegroups.com> <13t4k50d7pg0d63@corp.supernews.com> <1841d445-d0c2-4818-aa74-0a38cd3fefa1@u72g2000hsf.googlegroups.com> <13t5cbcrhtfsrd2@corp.supernews.com> <13t5qd3slgt9nc0@corp.supernews.com> <63g9s0F26pgoeU1@mid.individual.net> <13t6251ep5bou67@corp.supernews.com> <63gjv0F270p58U1@mid.individual.net> Message-ID: <63guadF27gdujU1@mid.individual.net> >>> If you can't/don't look at the source file, >>> then comments aren't going to help (except >>> in the case of something like docstrings in >>> Python). >> >> I strongly disagree. Now, perhaps we're >> talking about different things, here? >> Usually, in the header file (C++), there >> won't be any source code, except for >> method declarations. A common example: >> >> /** Projects an object from 3D to 2D using >> the method of Alexander The Great. >> \param 3D structure to be projected >> \returns 2D projection >> */ >> public Proj2D get2Dfrom3D(Proj3D param); >> >> The above is, to me, very clear and >> consistent. Not to mention, easily >> handled with e.g. Doxygen to create a >> readable documentation. >> >> I don't see how this is dislikeable. Please >> explain. Perhaps the above IS what you >> ment by "docstrings"? For Java, one has the >> JavaDocs, a great tool, provided one will >> comment each method and variable used. > > The problem is that tools like Doxygen and > JavaDocs generate warnings and errors and > things if everything isn't documented > "completely". So you end up with a lot of > silly boilerplate. > /** > * Get the width of a box > * > * @param box the box > * @returns its width > */ > extern int box_get_width(box box); Oh, yes. This is stupid. I agree with you. If one's supposed to comment, let him comment RIGHT. Otherwise, let it be. Usually, when i comment my code, it's a blessing. If not, i don't comment at all. > You are right that is it often useful to > document what to pass to a method and > what to expect back and that if this is > done well in many cases it isn't > necessary to see the implementation. > But in many other cases it's obvious, and > in other cases it's obvious if you just > look at the source which you've got. I agree. Sometimes, there's a demand from the customer to comment all methods. Then, and then only, i'll go commenting all. But i believe strongly that we think alike on this one. When it's suitable, it should be there. Otherwise - why bother. Right? > The lack of fascism is the big innovation. > It sounds simple but it makes a huge > difference: it's much easier to find (and > keep up to date) the real documentation if > it's not hidden in a forest of bogus > documentation. I couldn't agree with you more on this one! Thank you for an interesting discussion. -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From mimi.vx at gmail.com Mon Mar 31 12:53:59 2008 From: mimi.vx at gmail.com (mimi.vx) Date: Mon, 31 Mar 2008 09:53:59 -0700 (PDT) Subject: CTypes, 64 bit windows, 32 bit dll References: <5a0d8c47-f1b7-4eae-9911-b312a1166757@d1g2000hsg.googlegroups.com> Message-ID: On Mar 31, 4:22 pm, rdahlstrom wrote: > So I have a 64 bit Windows 2003 system, running python 2.5.1.1. > > I can import a Windows .dll (msvcrt or whatever) using ctypes, but > when attempting to import another application-specific .dll (tibrv.dll > if anyone is familiar with it), I receive the error WindowsError: > [Error 193] %1 is not a valid Win32 application. > > I know there's a Windows on Windows (wow) which allows 32 bit > processes to run on 64 bit windows - is there a way to work this in > somehow? Maybe I'm barking up the wrong tree? > > Code is simple, and works on 32 bit systems no > > from ctypes import * > #this doesn't work > tibrv = cdll.tibrv > #this does work > msvcrt = cdll.msvcrt all dlls and python must be 32bit or 64bit, no mixed ... From Sandipan at gangopadhyay.com Sat Mar 15 22:52:46 2008 From: Sandipan at gangopadhyay.com (Sandipan Gangopadhyay) Date: Sat, 15 Mar 2008 22:52:46 -0400 Subject: Python for BlackBerry In-Reply-To: <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> References: <694616a7-2502-4c9a-9aad-cc6dfaef26b6@m34g2000hsc.googlegroups.com> <9a28c8e7-e556-4d30-9675-6b86c7cd3e0a@m34g2000hsc.googlegroups.com> Message-ID: <111301c88710$d105bda0$731138e0$@com> Thanks, Mike. This one seems to be for Nokia, particularly S60 and Symbian in general. Does BlackBerry work on Symbian? Let me check. Thanks. Sandipan -----Original Message----- From: python-list-bounces+news=sandipan.com at python.org [mailto:python-list-bounces+news=sandipan.com at python.org] On Behalf Of Mike Driscoll Sent: Saturday, March 15, 2008 6:04 PM To: python-list at python.org Subject: Re: Python for BlackBerry On Mar 15, 7:24 am, "Sandipan Gangopadhyay" wrote: > Is there a Python for BlackBerry? Thanks. > > -----Original Message----- > From: python-list-bounces+news=sandipan.... at python.org > > [mailto:python-list-bounces+news=sandipan.... at python.org] On Behalf Of E-Lo > Sent: Saturday, March 15, 2008 6:03 AM > To: python-l... at python.org > Subject: Python for Palm OS > > Is there any other edition of Python for Palm OS instead of Pippy? > --http://mail.python.org/mailman/listinfo/python-list You might look at Mobile Python. I'm not sure if it works on Blackberry though: http://www.mobilepythonbook.org/ Mike -- http://mail.python.org/mailman/listinfo/python-list From Lie.1296 at gmail.com Sun Mar 30 08:55:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 30 Mar 2008 05:55:10 -0700 (PDT) Subject: License of Python References: Message-ID: <683e7a60-1967-4c95-b66f-e80a5f4f0116@e6g2000prf.googlegroups.com> On Mar 30, 6:42 pm, iu2 wrote: > Hi guys, > > I'd like to use Python in a commercial application. In fact I would > like to write the application entirely in Python. > But I think I wouldn't like telling what language the application is > written in. Why is the reason for that? > The problem is that including Python's license in the binary, which as > I understand is a must do, reveals that the appliation is based on > Python. > > I'll appreciate your advices about this > Thanks > iu2 You can just include it since most users never mess through their program files and most users doesn't even know what Python is, while advanced users could guess that you use Python by seeing the file extension being used (py, pyc, pyo). From steve at REMOVE-THIS-cybersource.com.au Thu Mar 20 19:06:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 20 Mar 2008 23:06:54 -0000 Subject: Is this valid ? References: <7b74b9ec-94d6-4997-8569-36de104217c2@u10g2000prn.googlegroups.com> Message-ID: <13u5rgegehc8u04@corp.supernews.com> On Thu, 20 Mar 2008 15:09:08 +0100, Rolf van de Krol wrote: > John Machin wrote: >> Of course. You can chain comparisons as much as you like and is >> (semi-)sensible, e.g. >> > Hmm, 'of course' is not the correct word for it. Not at all. The Original Poster tried something, and it worked. There were two alternatives: (1) Writing a == b == 2 is valid. (2) In the sixteen years that Python has been publicly available, with tens of thousands or more developers using it, nobody had noticed that Python had a bug in the compiler which incorrectly allowed a == b == 2 until Stef Mientki came along and discovered it. Given those two alternatives, (2) would be very surprising indeed, and so I think "of course" is well justified. That Python allows chaining comparisons this way isn't really surprising. That's a very natural thing to do. What's surprising is that other languages *don't* allow chaining comparisons, but force you to write the inefficient and (sometimes) confusing "(a == 2) and (b == 2)" instead. -- Steven From gagsl-py2 at yahoo.com.ar Tue Mar 18 22:37:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 18 Mar 2008 23:37:15 -0300 Subject: Does __import__ require a module to have a .py suffix? References: <05559d08-2479-4178-830c-adf65dfc733c@s37g2000prg.googlegroups.com> <20080312200254.6859.696992993.divmod.quotient.18440@ohm> Message-ID: En Wed, 12 Mar 2008 18:02:54 -0200, Jean-Paul Calderone escribi?: > On Wed, 12 Mar 2008 12:58:33 -0700 (PDT), George Sakkis > wrote: >> On Mar 12, 12:22 pm, mrstephengross wrote: >> >>> Hi all. I've got a python file called 'foo' (no extension). I want to >>> be able to load it as a module, like so: >>> >>> m = __import__('foo') >>> >> You can use execfile: >> >> foo = {} >> execfile('foo', foo) >> >> Apart from the different syntax in accessing the module globals >> (attributes with __import__ (foo.x) vs dict entries with execfile >> (foo['x'])), there are probably more subtle differences but I can't >> tell for sure. It would be nice if someone more knowledgeable can >> compare and contrast these two appraches. > > Another difference is that when you import a module, its code is > (usually) > only executed once. Each import after the first just returns a reference > to the already-created module object. When you use execfile, the code is > re-evaluated each time. The steps done by import are outlined in this message http://groups.google.com/group/comp.lang.python/browse_thread/thread/7d0ef70c1adc39ac/3882ce35f13ff971#msg_96a590bca5f2be8c The relevant part (citing myself): newmodule = sys.modules[modulename] = ModuleType(modulename) # constructor sets __name__ and a null __doc__ newmodule.__builtins__ = current builtins newmodule.__file__ = filename code = read from filename and compile it exec code in newmodule.__dict__ Apart from sys.modules and __file__, there is another difference, the __builtins__ attribute. It is important: if not present, Python executes the code in "safe mode" where certain operations are disabled (and there is a big performance penalty). -- Gabriel Genellina From dickinsm at gmail.com Wed Mar 12 11:47:41 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 12 Mar 2008 08:47:41 -0700 (PDT) Subject: How about adding rational fraction to Python? References: <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> <13scn9ncl7lds14@corp.supernews.com> <7xskz9wpw6.fsf@ruckus.brouhaha.com> <62e074bc-b408-4eb6-a3d1-4d4370344aa7@d4g2000prg.googlegroups.com> <7xprud88ze.fsf@ruckus.brouhaha.com> <60418acf-2d66-4428-a359-d85e88e61b4f@i12g2000prf.googlegroups.com> <7xr6etgk1f.fsf@ruckus.brouhaha.com> <4d619317-9bcb-4969-b97b-9f36dbef81c9@e25g2000prg.googlegroups.com> Message-ID: On Mar 12, 7:20?am, Piet van Oostrum wrote: > But if the answer is incorrect (in the float calculation) the error is > limited. IEEE 754 prescribes that the error should be at most 1 LSB, IIRC. > And then the number of errors is the proper measure. There are two operations here, both of which can introduce error of up to 0.5 ulp (ulp = unit in the last place). Moreover, the second operation (the multiplication) can magnify the error introduced by the first (the division). You're correct that for IEEE 754 binary floating-point arithmetic, (x/y)*y and x will either be equal or differ by exactly 1ulp (except perhaps in rarely-occurring corner cases). But for decimal numbers, (x/y)*y and x could be as much as 5 ulps apart. Mark > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From gagsl-py2 at yahoo.com.ar Wed Mar 26 12:05:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 26 Mar 2008 13:05:55 -0300 Subject: Running a python program as main... References: <65f15ad8-31b0-477f-8227-415d94a84a9e@e39g2000hsf.googlegroups.com> Message-ID: En Wed, 26 Mar 2008 11:12:21 -0300, waltbrad escribi?: > Stumbling through Mark Lutz's "Programming Python 3rd", he gives an > example of a program that will automatically configure environment > settings and launch other programs. Then he gives an example of > running this program. On his command line he types: > > C:\...\PP3E>Launcher.py > > and this begins the program. Doesn't work for me. I have to type: > > C:\...\PP3E>python Launcher.py > > Is this a typo on his part or has he configured his settings in such a > way that the command line will automatically associate the extension > with the program? (If so, he didn't mention this in his book). I think it is an option in the installer, to associate or not Python to the .py extension. You could reinstall Python paying attention to the options, or repair the association as described in this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1d0fd05b3615057/ -- Gabriel Genellina From terry6394 at gmail.com Sat Mar 1 01:59:56 2008 From: terry6394 at gmail.com (Cyril.Liu) Date: Sat, 1 Mar 2008 14:59:56 +0800 Subject: write float to Excel with pyExcelerator write In-Reply-To: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> References: <6d2d06b10802290753q22d12a3g342504ac3ac0d48a@mail.gmail.com> Message-ID: <6d2d06b10802292259o77f84011y88965534cd18999f@mail.gmail.com> I use pyExcelerator to generat Excel files in my project. it works good before I found this bug: run this code: from pyExcelerator import * wb = Workbook() ws = wb.add_sheet("sheet") for i in xrange(1): ws.write(i,0, 10474224.6) wb.save(r'd:\error_float.xls') open d:\error_float.xls with M$ Excle you'll find the number in the cell is -263193.64 not 10474224.6 why? some body help me please. PS: I'm not good at English, I hope you can understand what i said. :) Thx -- About Cyril.Liu ----------------------------------- Cyril ????????????, ??????????????, ??????????????:"????????????????????????" -------------- next part -------------- An HTML attachment was scrubbed... URL: From Robert.Bossy at jouy.inra.fr Fri Mar 28 11:59:59 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 28 Mar 2008 16:59:59 +0100 Subject: finding euclidean distance,better code? In-Reply-To: References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> Message-ID: <47ED15FF.5010209@jouy.inra.fr> Gabriel Genellina wrote: > That's what I said in another paragraph. "sum of coordinates" is using a > different distance definition; it's the way you measure distance in a city > with square blocks. I don't know if the distance itself has a name, but I think it is called Manhattan distance in reference of the walking distance from one point to another in this city. RB From sturlamolden at yahoo.no Sat Mar 15 18:11:44 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 15 Mar 2008 15:11:44 -0700 (PDT) Subject: Convert int to float References: <47dc41d7$0$14347$e4fe514c@news.xs4all.nl> Message-ID: <0a5994c8-1d0f-4b4b-a40c-788af85749b1@i12g2000prf.googlegroups.com> On 15 Mar, 22:43, Guido van Brakel wrote: > > def gem(a): > > g = sum(a) / len(a) > > return g > > > print gem([1,2,3,4]) > > print gem([1,10,100,1000]) > > print gem([1,-2,3,-4,5]) gem( map(float,[1,2,3,4]) ) gem( float(i) for i in [1,2,3,4] ) From bharathv6.project at gmail.com Wed Mar 19 03:28:19 2008 From: bharathv6.project at gmail.com (bharath venkatesh) Date: Wed, 19 Mar 2008 12:58:19 +0530 Subject: automatically doing some cleaning-up by the process when the systems shuts down In-Reply-To: <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> References: <2613171a0803180551h1cc3be16h7389ab54096f96cb@mail.gmail.com> <2613171a0803190006y32857a82p26e06489919c0bb5@mail.gmail.com> Message-ID: <2613171a0803190028s4cc626apd2cd675a18e25799@mail.gmail.com> handling SIGTERM allowed me to do cleaning up while the system shuts down but as i mentioned previously how can my process know if the system was not shut down properly previously On Wed, Mar 19, 2008 at 12:36 PM, bharath venkatesh < bharathv6.project at gmail.com> wrote: > hi , > thanks Gabriel ... but r u sure if it is SYSTERM ?or is it SIGTERM ? > I am not aware of any SYSTERM signal > .. if it is SYSTERM please tell me more about it .. as google search is > not helping .. > > and also is there some way for my process which is running as a daemon to > know that system was not shut down properly previously ....eg a power > failure .. so that my program can do necessary steps if cleaning up is not > done during its last termination > > On Wed, Mar 19, 2008 at 8:25 AM, Gabriel Genellina > wrote: > > > En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh > > escribi?: > > > > > my programs runs as daemon and it does some logging .. when > > system > > > shuts down .. which may be done manually . i want my process do some > > > cleaning up automatically such as writing in to the log file when the > > > process terminats before the system shuts down > > > > handling the SYSTERM signal? > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Tue Mar 4 09:50:16 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Mar 2008 09:50:16 -0500 Subject: pySQLite Insert speed In-Reply-To: References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> <79674afd-04f2-41a8-98d6-4785b324efff@p25g2000hsf.googlegroups.com> <8d4d357f-95a4-4c1c-9dbd-73ab6b1fc447@13g2000hsb.googlegroups.com> <8e466d0a-9f95-4314-98e0-507228ea48d1@c33g2000hsd.googlegroups.com> Message-ID: <47CD61A8.4000104@holdenweb.com> Peter Otten wrote: > Steve Holden wrote: > >> What I will repeat, however, is that while there is a *slight* >> difference is semantics between >> >> s = "some string" >> s1 = s >> >> and >> >> s = "some string" >> s1 = copy.copy(s) >> >> that difference is only to ensure that s and s1 point to different >> copies of the same string in the latter case, whereas in the former case >> s and s1 point to the same string. > > No, both "point" to the same string: > >>>> import copy >>>> s = "some string" >>>> s1 = s >>>> s1 is s > True >>>> s2 = copy.copy(s) >>>> s2 is s > True > > copy.copy() is just an expensive no-op here. > I suppose wiht strings being immutable there is no need for copy.copy() to actually return anything other than its argument for a string. Thanks for pointing that out. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gagsl-py2 at yahoo.com.ar Sat Mar 29 23:36:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Mar 2008 00:36:49 -0300 Subject: Where can I find : References: Message-ID: En Sun, 30 Mar 2008 00:15:59 -0300, pythonnubie escribi?: > Does anyone know where I can find either a book or a website that > explains beginning python by actually building a project line by > line and explaining it indepth . I am primarily interested in > understading flowcontrol as well as syntax . See the section about Learing Python in the wiki: http://wiki.python.org/moin/BeginnersGuide > If it was related to netwoprking then that would be a great > addition although not required because that is my primary field of > interest . Many books on Python have some chapters on networking, and there are even whole books like Python Web Programming by Steve Holden. -- Gabriel Genellina From larry.cebuala at gmail.com Mon Mar 17 02:37:04 2008 From: larry.cebuala at gmail.com (Larry) Date: Sun, 16 Mar 2008 23:37:04 -0700 (PDT) Subject: writing to a binary file without intervening spaces Message-ID: Dear all, I need to write integer values to a binary file that will be read by another application, specifically ENVI. I want to write these values without intervening spaces between values. For example: My data is a = [23, 45, 56, 255]. My desire output is: 234556255, of course in binary file representation already. I tried to make one using write after pack method of struct module, but because of spaces I got incorrect results. ENVI asks what data type I have and from that gets a sequence of bytes to "form" the data. With spaces, I think this gave me the problem. Thanks. From me at metsger.com Mon Mar 3 12:06:28 2008 From: me at metsger.com (Ethan Metsger) Date: Mon, 03 Mar 2008 12:06:28 -0500 Subject: Decorators and buffer flushing References: <535e65ee-dcae-4767-a74b-8ed17ee834c0@o10g2000hsf.googlegroups.com> Message-ID: Hi, Gabriel. I missed this message initially; I apologize for not responding sooner. On Thu, 28 Feb 2008 18:53:28 -0500, Gabriel Genellina wrote: >> I can reproduce the issue in the console. I'm not convinced it's >> actually >> a bug, unless for some reason the interpreter is preventing a buffer >> flush. > > Try starting the interpreter with python -u xxx.py (-u = unbuffered) but > I don't really think this might be the cause. Are you sure the code > actually says sys.stdout.flush() and not sys.stdout.flush? As I mentioned in another message, I haven't had any luck with adding '-u' to the invocation of the interpreter. I am sure I'm not looking at the callable object rather than calling flush(). >> sys.stdout.write ("%s" % (self.name.ljust(30),)) > > Usually written as: > sys.stdout.write("%-30s" % self.name) Thanks for the tips! [...] >> Is it possible that flushing is prohibited until __exit__ is called? > > I don't think so... What's your platform/OS? I'm running Ubuntu Feisty with Python 2.5.1: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Try to post a minimal example showing the problem - copy & paste it, > don't retype. Maybe in the process of reducing your code to find the > minimal example, you find the problem yourself. The minimal example is a little long, but I think in the end I figured out what was happening. The initial build step took the longest amount of time to complete, but the other steps were nearly instantaneous. So the post-build '.' would appear, and the very fast run of the other steps made it appear as though everything was being buffered when it wasn't. Adding in a short delay (time.sleep(0.05) seemed to work) helped demonstrate that the data actually were unbuffered. > Are you aware of the existing framework for unit tests? the unittest > module? Yes. I haven't investigated its uses in this context due to the constraints of the legacy system and general inertia. I'm trying to duplicate functionality while addressing certain annoyances with the previous system. Thanks again for your help! Best, Ethan -- Ethan Metsger http://uppertank.net/ethanm/ From cruxic at gmail.com Sat Mar 8 11:25:06 2008 From: cruxic at gmail.com (Cruxic) Date: Sat, 8 Mar 2008 08:25:06 -0800 (PST) Subject: Can't get items out of a set? References: <9384661a-97f2-45a8-858e-be633144f610@b1g2000hsg.googlegroups.com> Message-ID: <99cdb92b-eaca-45e4-9d3f-916bbe0f24d7@e10g2000prf.googlegroups.com> On Mar 7, 11:20 am, Raymond Hettinger wrote: > [Cruxic] > > > Is it possible to get an object out of a set() given another object > > that has the same hash code and equality (__hash__() and __eq__() > > return the same)? > > Yes, but it requires an indirect approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299 > > Raymond That's a clever work around. Thanks, Raymond. Clearly you had a need for this. Do you feel it's a common need that should be submitted as a Python feature request? To me it seems like such a simple thing that would increase the general utility of the set class. I suppose I could start another thread like "feature request: New method for set - get_equivalent". From kyosohma at gmail.com Thu Mar 6 16:58:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 6 Mar 2008 13:58:16 -0800 (PST) Subject: system32 directory References: <496954360803051501q4c3dd21qeadd10254bc54ca7@mail.gmail.com> <47CFAE7E.6030501@timgolden.me.uk> <496954360803061315g5253e42fof38566f0041e325@mail.gmail.com> Message-ID: <85b740fb-3231-494f-bdb4-bd23f9e46de5@8g2000hse.googlegroups.com> On Mar 6, 3:49 pm, Trent Mick wrote: > > I was aiming to figure out if the standard modules shipped with Python > > could do this already before I started using 3rd party libraries. Thanks. > > You could also manage it with the ctypes module, if you consider that > standard: it is in the python.org and ActivePython distros as of Python 2.5. > > Cheers, > Trent > > -- > Trent Mick > trentm at activestate.com As I understand it, ActivePython includes PyWin32 by default, unlike the "Official" Python distro. Mike From renesd at gmail.com Sun Mar 30 06:44:18 2008 From: renesd at gmail.com (=?ISO-8859-1?Q?Ren=E9_Dudfield?=) Date: Sun, 30 Mar 2008 21:44:18 +1100 Subject: ANN: pygame 1.8 released Message-ID: <64ddb72c0803300344q5ee42d81xdb4a7695adef759b@mail.gmail.com> Hello, a new version of pygame is out. http://www.pygame.org/ Pygame is a set of Python modules designed for writing games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Pygame is highly portable and runs on nearly every platform and operating system. http://www.pygame.org/wiki/about Silliness built in. Does not require OpenGL. Multi core CPUs can be used easily. Uses optimized C, and Assembly code for core functions. Comes with many Operating systems. Truly portable. It's Simple, and easy to use. Many games have been published. You control your main loop. Does not require a GUI to use all functions. Fast response to reported bugs. Small amount of code. Modular. http://pygame.org/whatsnew.shtml Some of the changes... * pygame.mask for pixel perfect collision detection * pygame.scrap for clipboard support * new and improved sprite groups, including layers, automatically selecting fastest update mode(full screen or dirty rect updates), and blend modes... * blending support for filling and blitting surfaces. ADD, SUB, MULT, DIV etc. * saving surfaces as jpeg and png * buffer access for Surface and Sound objects * numpy, and numeric support for pygame.surfarray and pygame.pixelarray * PixelArray, which can be used instead of numpy - without the dependency. * smooth scale function written in mmx assembly with C fallback. * More functions release the GIL for multithreaded use. * lots of speed ups to many functions via better python wrapping. * color thresholding, bounding box finding for images, and surface averaging. * massive documentation updates (which have been available on the website for a while already). * pygame.time.Clock.tick() is more cpu friendly. * updates to example programs. * new windows, and mac installers. * hardware acceleration updates for overlays and opengl. * porting work to different platforms. * heaps of bug fixes including SRCALPHA blitting fixes, 64bit fixes, sound system fixes. Plus there have been lots of changes to SDL itself since the last pygame release. http://www.libsdl.org/release/changes-1.2.html. * lots of stuff really... but those are some of the nice things. Read the what's new page for full details http://pygame.org/whatsnew.shtml cheers, From martin at v.loewis.de Fri Mar 21 17:01:07 2008 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Mar 2008 22:01:07 +0100 Subject: eval and unicode In-Reply-To: References: <9e5e0240-fff9-4602-b84b-58bae37b5de1@s12g2000prg.googlegroups.com> <27cd6a2f-0848-4d6e-9a80-6bdc4ad7f973@d21g2000prf.googlegroups.com> Message-ID: <47E42213.50208@v.loewis.de> > eval() somehow decoded the passed expression. No question. It did not > use 'ascii', nor 'latin2' but something else. Why is that? Why there is > a particular encoding hard coded into eval? Which is that encoding? (I > could not decide which one, since '\xdb' will be the same in latin1, > latin3, latin4 and probably many others.) I think in all your examples, you pass a Unicode string to eval, not a byte string. In that case, it will encode the string as UTF-8, and then parse the resulting byte string. Regards, Martin From mail at timgolden.me.uk Sat Mar 15 08:08:21 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 15 Mar 2008 12:08:21 +0000 Subject: Spaces in path name In-Reply-To: <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> References: <360a8612-f5a2-4f2f-bae2-c89ed35b7d1b@n77g2000hse.googlegroups.com> <3acdef8d-baba-4505-b41c-7201e2635eac@u69g2000hse.googlegroups.com> Message-ID: <47DBBC35.8060902@timgolden.me.uk> joep wrote: > I had the same problem recently with subprocess.popen, when there is a > space in the executable and a space in an additional argument as in > the acrobat example. I finally found a past thread in this news group > that explained that you have to use two (2) leading double quotes, and > as on the command line all arguments with spaces have to be quoted. Thanks for this, joep. I've added a how-do-i to my website covering the different cases, I hope. This comes up often enough that maybe next time we can just point someone there first time! TJG http://timgolden.me.uk/python/win32_how_do_i/run-a-command-with-a-space-in-it.html From rschroev_nospam_ml at fastmail.fm Sat Mar 29 05:11:28 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 29 Mar 2008 10:11:28 +0100 Subject: finding euclidean distance,better code? In-Reply-To: <13ur5mq7fugqgc1@corp.supernews.com> References: <1c0b1ed4-27d9-4810-b7b1-1dde78a7fe8d@h11g2000prf.googlegroups.com> <13ur5mq7fugqgc1@corp.supernews.com> Message-ID: <4JnHj.3124$e%6.335@newsfet15.ams> Steven D'Aprano schreef: > On Fri, 28 Mar 2008 16:59:59 +0100, Robert Bossy wrote: > >> Gabriel Genellina wrote: >>> That's what I said in another paragraph. "sum of coordinates" is using >>> a different distance definition; it's the way you measure distance in a >>> city with square blocks. I don't know if the distance itself has a >>> name, but >> I think it is called Manhattan distance in reference of the walking >> distance from one point to another in this city. > > You know, there are other cities than Manhattan. Some of them even have > streets and blocks. I'm not sure what your point is. The name of the distance happens to be Manhattan distance (or taxicab distance, rectilinear distance, L1 distance, city block distance; see http://en.wikipedia.org/wiki/Manhattan_distance) so Robert has a valid point. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From rodmena.com at gmail.com Mon Mar 17 01:27:24 2008 From: rodmena.com at gmail.com (Farsheed Ashouri) Date: Sun, 16 Mar 2008 22:27:24 -0700 (PDT) Subject: Py2exe and Multi Treading problem. References: <53b170ca-a7b7-4b50-bb50-4689cff27d2d@e23g2000prf.googlegroups.com> <47d8307c$0$12126$3b214f66@aconews.univie.ac.at> Message-ID: <1eaf7012-7c2c-4377-8f16-c2d33115a172@d62g2000hsf.googlegroups.com> On Mar 12, 10:35 pm, Thin Myrna wrote: > Farsheed Ashouri wrote: > > NO it dont work. If I remove threading part, it works like a charm. > > Any Idea? > > Of course it does then. Try to join the thread or do something else to > prevent the non-threading part to exit prematurely. > > HTH > Thin Thanks, I got it. Very useful for me. Cheers. From tim.arnold at sas.com Wed Mar 26 15:52:42 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 26 Mar 2008 15:52:42 -0400 Subject: first interactive app Message-ID: hi, I want to write a tiny interactive app for the following situation: I have books of many chapters that must be split into volumes before going to the printer. A volume can have up to 600 pages. We obviously break the book into volumes only at chapter breaks. Since some chapters make a natural grouping, we want some human interaction for where the volume breaks occur. Not having experience with interactive apps, I'm asking for advice about how to go about it. The data I start with is just a dictionary with chapter name = ending page number. I figured I would first show where the volumes would break with no human interaction, with the begin and ending chapter names/pagenumbers for each volume. >From here I thought about having a slider for each volume, but the number of volumes could change during the session. Or maybe I should just ask 'enter the ending chapter for the first volume' and recalculate, etc until all volumes are defined. Any ideas on a simple interface for this? thanks, --Tim From lialie at gmail.com Wed Mar 26 12:21:15 2008 From: lialie at gmail.com (lialie) Date: Thu, 27 Mar 2008 00:21:15 +0800 Subject: Problem with write binary data to OLE field in Access Message-ID: <47EA77FB.3080706@gmail.com> Hi~ I would like to save images in OLE field in Microsoft Access. It writes the binary data which read from an JPEG/BMP file. But seems I meet an encoding problem. The following code demos that. Any sugguestion? --------------------------------------------------------------------------- import win32com.client as wc conn = wc.Dispatch(r'ADODB.Connection') recordset = wc.Dispatch(r'ADODB.RecordSet') dsn = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source="test.mdb";' conn.Open(dsn) print conn k = recordset.Open('[tblImageDataTypes]', conn, 1, 3) #recordset.AddNew() #recordset.Fields('Field3_GENERAL').AppendChunk(open('tt.jpg', 'rb').read()) #recordset.Update() #print ">>> Actual Size: ", recordset.Fields('Field3_GENERAL').ActualSize recordset.MoveFirst() kk = recordset.Fields('Field3_GENERAL').GetChunk( recordset.Fields('Field3_GENERAL').ActualSize) print len(str(kk).decode('utf-16')) print len(open('tt.jpg', 'rb').read()) recordset.Close conn.Close() ############################### One of the results: the length of original file is : 2598 the actual size of the field is: 3658 the length decode from the chunk is: 1829 I try to write some text files into the filed and read it out, it is OK. Windows XP sp2; Python 2.4.4; Pywin32 210; Microsoft Access 2002 --------------------------------------------------------------------------------------- Regards, lialie From http Sun Mar 23 02:09:07 2008 From: http (Paul Rubin) Date: 22 Mar 2008 23:09:07 -0700 Subject: Do any of you recommend Python as a first programming language? References: <56edc64f-5a4c-4ce1-a27d-d41e7b8463dc@a23g2000hsc.googlegroups.com> <7xlk4anjcn.fsf@ruckus.brouhaha.com> <47e5f31f$0$36325$742ec2ed@news.sonic.net> Message-ID: <7x4payug3g.fsf@ruckus.brouhaha.com> John Nagle writes: > What a mess. That's some professor inventing his very own variation on > predicate calculus and writing a book using his own notation and terminology. I thought it was all pretty standard. It's the same notation I see in other PL stuff. > There's no sign of footnotes or references to prior work. Maybe he'll add that. It's a work in progress. > Back when I was doing program verification work, we used to refer to > stuff like that as the "logic of the month club". I thought the book was pretty good and I've learned quite a bit from the parts I've read. Also, the author is one of the big cheeses in the SML world, if that matters. From noname9968 at gmail.com Sun Mar 16 15:46:01 2008 From: noname9968 at gmail.com (Alex) Date: Sun, 16 Mar 2008 22:46:01 +0300 Subject: Which way to access Scintilla Message-ID: <47DD78F9.8090306@gmail.com> There are several ways to use Scintilla in Python, the ones described at http://scintilla.sourceforge.net/ScintillaRelated.html are: -through wxPython -pyscintilla is the original Python binding for Scintilla's default GTK 1.x class. Includes some additional support, such as native printing on Windows. The binding is hand-written rather than auto-generated from the Scintilla.iface file. -pygtkscintilla is a Python binding for gtk1.x scintilla that uses gtkscintilla instead of the default GTK class. -pyscintilla2 is a Python binding for GTK 2.x scintilla that uses gtkscintilla2. I'm not using any of the libraries GTK 1.x, GTK 2.x or WxPython for GUI (always used Tkinter), but I want to use Scintilla so I wonder which way would have less overhead. First, loading of an additional library would (I think) slow down startup and operating time of program, plus there can be additional complexity of use. I also want to embed Scintilla in Tkinter-created window (create the rest of the GUI in Tkinter), or rather, I want to know if that's possible at all. Any suggestions are appreciated. Thanks From nagle at animats.com Sun Mar 23 16:00:09 2008 From: nagle at animats.com (John Nagle) Date: Sun, 23 Mar 2008 13:00:09 -0700 Subject: Testing for an empty dictionary in Python In-Reply-To: References: <47e67a99$0$36364$742ec2ed@news.sonic.net> Message-ID: <47e6b485$0$36325$742ec2ed@news.sonic.net> Brian Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > John Nagle wrote: >> What's the cheapest way to test for an empty dictionary in Python? >> >> if len(dict.keys()) : >> >> is expensive for large dictionaries, and makes loops O(N^2). >> >> John Nagle > > if dict: Cute. I'd already figured out that len(dict) works, which is probably better than len(dict.keys() > 0 which requires creating a list. John Nagle From miki.tebeka at gmail.com Fri Mar 21 11:26:26 2008 From: miki.tebeka at gmail.com (Miki) Date: Fri, 21 Mar 2008 08:26:26 -0700 (PDT) Subject: Distributing Python Apps on Linux\BSD References: <4d15a463-69db-4efb-a0bd-0c0088707493@u10g2000prn.googlegroups.com> Message-ID: <9290c7b1-3e51-46fe-96e7-6c2ebf4f5b77@u10g2000prn.googlegroups.com> Hello, Disclaimer: I'm not an expert on the subject. > Setuptools and friends seem to be focused on distributing modules, I'm > at the other end of the scale where I want to distribute an entire > application so that an Administrator can run a single install and have > a fully operational product. A key requirement is that I want the > application to fit in with what and admin would expect an application > to look like at the system level i.e site-packages like structures > aren't suitable. You do that with distutils as well. > So far I've thought of using a configure script and make which would > call some custom python installer script to do the actual install. It > fits in nicely with what I want to achieve but are there any better > options out there, how are others doing the same thing? Every distro flavor has it's own installer: apt/deb, rpm, port, ... On Windows you can use one of the free installer (InnoSetup and friends). HTH, -- Miki http://pythonwise.blogspot.com